blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
7dbc382e3397d9acc1d61605b9216b62ba7e67a4
ab80d88b354db83585acc72e36fe9f3f4a1c7e54
/support/inc/MonteCarloPredictor.h
9ca2e767e7d0491eb865bf785fa127d0a2204df3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
zhengbenchang/GSAP
a1ecedaf502e184827148cee4bd27b44315c6a2f
68a33f4df375d8144ffe10f6c90ad2d57204a6c9
refs/heads/master
2020-04-13T08:35:24.905767
2018-11-30T22:21:20
2018-12-04T22:37:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,814
h
/** MonteCarloPredictor - Header * @file MonteCarloPredictor Class * @ingroup GPIC++ * @ingroup Predictors * * @brief MonteCarloPredictor Class - Class defining the MonteCarloPredictor * * @author Matthew Daigle * @version 1.1.0 * * @pre N/A * * Contact: Matthew Daigle (matthew.j.daigle@nasa.gov) * Created: March 22, 2016 * * @copyright Copyright (c) 2018 United States Government as represented by * the Administrator of the National Aeronautics and Space Administration. * All Rights Reserved. */ #ifndef PCOE_MONTECARLOPREDICTOR_H #define PCOE_MONTECARLOPREDICTOR_H #include <vector> #include <string> #include "Model.h" #include "Predictor.h" #include "GSAPConfigMap.h" namespace PCOE { class MonteCarloPredictor final : public Predictor { private: unsigned int numSamples; // number of samples used in prediction std::vector<double> processNoise; // variance vector (zero-mean assumed) public: /** @brief Constructor for a MonteCarloPredictor based on a configMap * @param configMap Configuration map specifying predictor parameters **/ explicit MonteCarloPredictor(GSAPConfigMap & configMap); /** @brief Set model pointer * @param model given model pointer **/ void setModel(PrognosticsModel * model); /** @brief Predict function for a Predictor * @param tP Time of prediction * @param state state of system at time of prediction * @param data ProgData object, in which prediction results \re stored **/ void predict(const double tP, const std::vector<UData> & state, ProgData & data); }; } #endif // PCOE_MONTECARLOPREDICTOR_H
[ "christopher.a.teubert@nasa.gov" ]
christopher.a.teubert@nasa.gov
c339d25e92e864d43b4814779274c34f50c3c2e6
cd8abfb87e558f05b13fce74dbc27ea6375e45af
/fboss/agent/platforms/common/sandia/SandiaPlatformMapping.h
507d5460a9aa9e30beca2a44034258d52f5e69a3
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
nanWave/fboss
4e355915e6ae80452c579104b534397812e1b42b
b920e54c6919800f915222b6ba7a63757ecdc8bf
refs/heads/master
2022-08-13T22:44:10.869514
2022-07-25T05:30:57
2022-07-25T05:30:57
105,797,491
0
0
null
2017-10-04T17:31:02
2017-10-04T17:31:02
null
UTF-8
C++
false
false
774
h
/* * Copyright (c) 2004-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #pragma once #include "fboss/agent/platforms/common/PlatformMapping.h" namespace facebook { namespace fboss { class SandiaPlatformMapping : public PlatformMapping { public: SandiaPlatformMapping(); private: // Forbidden copy constructor and assignment operator SandiaPlatformMapping(SandiaPlatformMapping const&) = delete; SandiaPlatformMapping& operator=(SandiaPlatformMapping const&) = delete; }; } // namespace fboss } // namespace facebook
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
d5c7b89cd0d11741b1f5e2fed4913f6936266536
0458840fe3ad2b17e461e21444a2fdec5ef62172
/cocosjs/frameworks/runtime-src/Classes/GameCore/CResourcesManager.cpp
5ba1f324a5b5a2402ccbba7054024fc5bb29702c
[]
no_license
linyouhappy/kongkongxiyou
b204949b607def0b8918f69b7a5f5c3335b5a6c5
01d6f10105d74d3ed679e8eb40910d84419570d7
refs/heads/master
2023-04-27T18:31:40.933570
2023-04-26T00:36:28
2023-04-26T00:36:28
63,694,726
318
245
null
null
null
null
UTF-8
C++
false
false
34,044
cpp
#include "CResourcesManager.h" #include "CResourcesHelper.h" #include "CUpdateManager.h" #include "tinyxml2/tinyxml2.h" #include "unzip/unzip.h" #include "MyMD5.h" using namespace tinyxml2; #if(CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC) #include "curl/include/ios/curl/curl.h" #include <unistd.h> #elif(CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) #include "curl/include/android/curl/curl.h" #include <unistd.h> #elif(CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) #include "curl/include/win32/curl/curl.h" #endif static unzFile g_pScriptFile = NULL; static std::string myWord=""; char badWord[32]={0}; void initJSBZip() { badWord[7]='a'; if (!!g_pScriptFile) { unzClose(g_pScriptFile); g_pScriptFile=NULL; } badWord[0]='@'; badWord[3]='o'; badWord[6]='m'; badWord[2]='a'; badWord[9]='0'; badWord[10]='1'; badWord[1]='c'; badWord[11]='6'; std::string scriptFullPath=FileUtils::getInstance()->fullPathForFilename("data.js"); CCLOG("initJSBZip open file:%s",scriptFullPath.c_str()); badWord[4]='n'; badWord[5]='i'; badWord[8]='2'; g_pScriptFile = unzOpen(scriptFullPath.c_str()); if (!g_pScriptFile) { CCLOG("can't open file sciptFullPath=%s",scriptFullPath.c_str()); char msg[256]={0}; sprintf(msg, "致命性错误!执行文件打不开"); MessageBox(msg, "温馨提示"); CCAssert(0, "ERROR,can't open file"); } myWord=myMD5(badWord); CCLOG("congratulation,load jsb res success!"); CCLOG("jsb path:%s",scriptFullPath.c_str()); #if(CC_TARGET_PLATFORM == CC_PLATFORM_MAC) CCLOG("myWord=%s",myWord.c_str()); #endif badWord[0]='@'; } cocos2d::Data* getFileDataFromScriptZip(const char* pszFileName) { CCLOG("js file:%s",pszFileName); if (!g_pScriptFile) { return nullptr; } if (!pszFileName || strlen(pszFileName) == 0) { CCLOG("ScriptZip file is NULL"); return nullptr; } cocos2d::Data* data; unsigned char * pBuffer = NULL; ssize_t pSize=0; do { int nRet = unzLocateFile(g_pScriptFile, pszFileName, 1); if(UNZ_OK != nRet) { CCLOG("unzLocateFile failed:%s",pszFileName); break; } char szFilePathA[260]; unz_file_info FileInfo; nRet = unzGetCurrentFileInfo(g_pScriptFile, &FileInfo, szFilePathA, sizeof(szFilePathA), NULL, 0, NULL, 0); // CC_BREAK_IF(UNZ_OK != nRet); if(UNZ_OK != nRet) { CCLOG("unzGetCurrentFileInfo failed:%s",pszFileName); break; } // nRet=unzOpenCurrentFile(g_pScriptFile); nRet=unzOpenCurrentFilePassword(g_pScriptFile,myWord.c_str()); // nRet=unzOpenCurrentFilePassword(g_pScriptFile,"dea25b0af6cc5ea9da4961dbc5ffeb97"); if(UNZ_OK != nRet) { CCLOG("unzOpenCurrentFilePassword failed:%s",pszFileName); exit(0); break; } CCLOG("zip jsb:%s",pszFileName); pBuffer = new unsigned char[FileInfo.uncompressed_size]; int CC_UNUSED nSize = unzReadCurrentFile(g_pScriptFile, pBuffer, FileInfo.uncompressed_size); CCAssert(nSize == 0 || nSize == (int)FileInfo.uncompressed_size, "the file size is wrong"); pSize = FileInfo.uncompressed_size; unzCloseCurrentFile(g_pScriptFile); data=new Data; data->fastSet(pBuffer, pSize); return data; } while (0); return nullptr; } static const char* kLocalUpdateVersionFile = "update.xml"; static const char* kRemoteUpdateVersionFile="remoteupdate.xml"; static const char* kDownloadFolder="download/"; #define BUFFER_SIZE 8192 #define MAX_FILENAME 512 CFileDownloader::CFileDownloader() { requestFailedTimes=0; isFinish=false; } CFileDownloader::~CFileDownloader() { } CFileDownloader *CFileDownloader::create() { CFileDownloader *pRet = new CFileDownloader; if( pRet != NULL && pRet->init()) { pRet->autorelease(); return pRet; } else { CC_SAFE_DELETE(pRet); return NULL; } } bool CFileDownloader::init() { return true; } CResourcesManager::CResourcesManager() :m_pThread(NULL) ,m_pDelegate(NULL) ,m_pHelper(NULL) ,m_pCurrentFileDownloader(NULL) ,m_bIsHasRunDownload(false) ,m_sdk_url("") { m_pResourcesHelper=CResourcesHelper::getInstance(); m_strDownloadFolder=m_pResourcesHelper->getDownloadFolder(); m_strAppResourcesFolder=m_pResourcesHelper->getAppResourcesFolder(); m_strDownloadCacheFolder=*m_strDownloadFolder+kDownloadFolder; m_pResourcesHelper->createDirectory(m_strDownloadCacheFolder.c_str()); m_pFileDownloadersArray=__Array::create(); CC_SAFE_RETAIN(m_pFileDownloadersArray); m_pHelper = new CHelper(); } CResourcesManager::~CResourcesManager() { this->stopUpdate(); CC_SAFE_RELEASE_NULL(m_pHelper); CC_SAFE_RELEASE_NULL(m_pFileDownloadersArray); CResourcesHelper::deleteInstance(); } CResourcesManager* CResourcesManager::create(void) { CResourcesManager * pRet = new CResourcesManager(); if (pRet && pRet->init()) { pRet->autorelease(); } else { CC_SAFE_DELETE(pRet); } return pRet; } bool CResourcesManager::init() { m_oCurrentUpdateVersionData.res=0; m_oCurrentUpdateVersionData.ver=0; string downloadUpdateVersionPath=*m_strDownloadFolder+kLocalUpdateVersionFile; if(!FileUtils::getInstance()->isFileExist(downloadUpdateVersionPath.c_str())) { string appUpdateVersionPath=*m_strAppResourcesFolder+kLocalUpdateVersionFile; if(FileUtils::getInstance()->isFileExist(appUpdateVersionPath.c_str())) { m_pResourcesHelper->copyAppResToDownloadFile(kLocalUpdateVersionFile); } } this->loadUpdateVersionFile(downloadUpdateVersionPath.c_str(), &m_oCurrentUpdateVersionData); return true; } int CResourcesManager::getCurrentResourceVersion() { return m_oCurrentUpdateVersionData.res; } int CResourcesManager::getCurrentAppVersion() { return m_oCurrentUpdateVersionData.ver; } kUpdateFileStatus CResourcesManager::chechUpdate() { this->loadRemoteUpdateFile(); // if (m_oRemoteUpdateVersionData.res==-1) // { // CCLOG("程序版本号太低,请下载最新的程序包!"); // return kUpdateNeedApp; // } // if (m_oRemoteUpdateVersionData.res==0) { // CCLOG("版本文件读取失败,请重新启动程序!"); // return kUpdateVesionFileError; // } if (m_oRemoteUpdateVersionData.res<=0 || m_pFileDownloadersArray->count()==0) return kUpdateNone; return kUpdateNormal; } void CResourcesManager::startUpdate() { if (m_oRemoteUpdateVersionData.res==-1) { if (m_pDelegate) { m_pDelegate->onUpdateFailed("程序版本号太低,请下载最新的程序包!"); } return; } if (!m_bIsHasRunDownload) { m_bIsHasRunDownload=true; Director::getInstance()->getScheduler()->schedule(schedule_selector(CResourcesManager::mainThreadProcess), this, 0.0f, false); } } void CResourcesManager::stopUpdate() { if (m_bIsHasRunDownload) { Director::getInstance()->getScheduler()->unschedule(schedule_selector(CResourcesManager::mainThreadProcess), this); m_bIsHasRunDownload=false; m_pFileDownloadersArray->removeAllObjects(); CC_SAFE_RELEASE_NULL(m_pCurrentFileDownloader); } } void CResourcesManager::loadRemoteUpdateXML(const string* remoteUpdateXML) { if (remoteUpdateXML==NULL || remoteUpdateXML->length()==0) return; m_pResourcesHelper->saveDownloadFile(kRemoteUpdateVersionFile,remoteUpdateXML->c_str(), remoteUpdateXML->length()); m_oRemoteUpdateVersionData.res=0; m_oRemoteUpdateVersionData.ver=0; string remoteUpdateVersionPath=*m_strDownloadFolder+kRemoteUpdateVersionFile; bool res=this->loadUpdateVersionFile(remoteUpdateVersionPath.c_str(), &m_oRemoteUpdateVersionData); if (!res) { m_oRemoteUpdateVersionData.res=0; CCLOG("loadRemoteUpdateXML failed"); } else { m_pDownloadUrl=m_oRemoteUpdateVersionData.url; CCLOG("loadRemoteUpdateXML m_pDownloadUrl=%s",m_pDownloadUrl.c_str()); } } void CResourcesManager::loadRemoteUpdateFile() { m_pFileDownloadersArray->removeAllObjects(); if(m_oRemoteUpdateVersionData.res<=0) return; CUpdateVersionFileMap* updateVersionFileMap=&(m_oRemoteUpdateVersionData.updateVersionFileMap); CUpdateVersionFileMap::const_iterator iter=updateVersionFileMap->begin(); while (iter!=updateVersionFileMap->end()) { const char* name=iter->second.t.c_str(); if (name!=NULL && strlen(name)>0) { CUpdateVersionFileMap::const_iterator subIter=m_oCurrentUpdateVersionData.updateVersionFileMap.find(name); bool isShouldDownload=true; if (subIter!=m_oCurrentUpdateVersionData.updateVersionFileMap.end()) { if (iter->second.m==subIter->second.m) isShouldDownload=false; } if (isShouldDownload) { CFileDownloader* fileDownloader=CFileDownloader::create(); fileDownloader->t=iter->second.t; fileDownloader->s=iter->second.s; fileDownloader->f=iter->second.f; fileDownloader->m=iter->second.m; m_pFileDownloadersArray->addObject(fileDownloader); } } iter++; } if (m_pFileDownloadersArray->count()==0) { if(m_oRemoteUpdateVersionData.res==m_oCurrentUpdateVersionData.res) return; m_oCurrentUpdateVersionData.res=m_oRemoteUpdateVersionData.res; m_oCurrentUpdateVersionData.ver=m_oRemoteUpdateVersionData.ver; saveCurrentUpdateVersionFile(); } } void CResourcesManager::saveCurrentUpdateVersionFile() { tinyxml2::XMLDocument xmlDoc; XMLDeclaration * decl = xmlDoc.NewDeclaration(NULL);// new XMLDeclaration( "1.0", "utf-8", "" ); xmlDoc.LinkEndChild(decl); XMLElement* pRootElement=xmlDoc.NewElement("root"); xmlDoc.LinkEndChild(pRootElement); pRootElement->SetAttribute("res", m_oCurrentUpdateVersionData.res); pRootElement->SetAttribute("ver", m_oCurrentUpdateVersionData.ver); CUpdateVersionFileMap* updateVersionFileMap=&(m_oCurrentUpdateVersionData.updateVersionFileMap); CUpdateVersionFileMap::const_iterator iter=updateVersionFileMap->begin(); while (iter!=updateVersionFileMap->end()) { XMLElement* pChildElement=xmlDoc.NewElement("f"); pRootElement->LinkEndChild(pChildElement); pChildElement->SetAttribute("t", iter->second.t.c_str()); pChildElement->SetAttribute("s", iter->second.s); pChildElement->SetAttribute("f", iter->second.f.c_str()); pChildElement->SetAttribute("m", iter->second.m.c_str()); iter++; } string updateFullFilePath=*m_strDownloadFolder+kLocalUpdateVersionFile; xmlDoc.SaveFile(updateFullFilePath.c_str()); } void CResourcesManager::saveFileDownloader() { CFileDownloader* fileDownloader=m_pCurrentFileDownloader; if(fileDownloader==NULL) { return; } const char* name=fileDownloader->t.c_str(); if (name!=NULL && strlen(name)>0) { CUpdateVersionFileMap* updateVersionFileMap=&m_oCurrentUpdateVersionData.updateVersionFileMap; CUpdateVersionFileMap::const_iterator iter=updateVersionFileMap->find(name); if (iter!=updateVersionFileMap->end()) { updateVersionFileMap->erase(name); } CUpdateFileData updateFileData; updateFileData.t=fileDownloader->t; updateFileData.s=fileDownloader->s; updateFileData.f=fileDownloader->f; updateFileData.m=fileDownloader->m; updateVersionFileMap->insert(std::make_pair(name,updateFileData)); } this->saveCurrentUpdateVersionFile(); } bool CResourcesManager::loadUpdateVersionFile(const char *lpcszFilePath,CUpdateVersionData* updateVersionData) { bool isExists = FileUtils::getInstance()->isFileExist(lpcszFilePath); if (!isExists) { CCLOG("CResourcesManager::loadUpdateVersionFile XML file is not exist = %s", lpcszFilePath); MessageBox("更新版本文件不存在,请重新程序", "错误提示"); return false; } tinyxml2::XMLDocument xmlDoc; if(xmlDoc.LoadFile(lpcszFilePath)!=0) { if (remove(lpcszFilePath) != 0) CCLOG("can not remove loadUpdateVersionFile:%s", lpcszFilePath); CCLOG("loadUpdateVersionFile Not Found! %s",lpcszFilePath); MessageBox("更新版本文件读取错误,请重新程序", "错误提示"); return false; } XMLElement *pRootObject = xmlDoc.RootElement(); if(pRootObject == NULL ) { return false; } if (pRootObject->Attribute("res")) { updateVersionData->res=atoi(pRootObject->Attribute("res")); } if (pRootObject->Attribute("ver")) { updateVersionData->ver=atoi(pRootObject->Attribute("ver")); } if (pRootObject->Attribute("force")) { updateVersionData->force=atoi(pRootObject->Attribute("force")); } if (pRootObject->Attribute("url")) { updateVersionData->url=pRootObject->Attribute("url"); } // if (pRootObject->Attribute("sdk_open")) // { // m_bIsSdkOpen= atoi(pRootObject->Attribute("sdk_open"))==1?true:false; // CCLOG("sdk_open=%s",pRootObject->Attribute("sdk_open")); // } // if (pRootObject->Attribute("sdk_msg")) // { // m_strSdkMsg=pRootObject->Attribute("sdk_msg"); // } // if (pRootObject->Attribute("sdk_url")) // { // m_sdk_url=pRootObject->Attribute("sdk_url"); // } CUpdateVersionFileMap* updateVersionFileMap=&(updateVersionData->updateVersionFileMap); if(!pRootObject->NoChildren() ) { for(XMLElement *pChildElement = pRootObject->FirstChildElement() ; pChildElement != NULL ; pChildElement = pChildElement->NextSiblingElement()) { CUpdateFileData updateFileData; const char* type=pChildElement->Attribute("t"); if (type) { updateFileData.t=type; const char* size=pChildElement->Attribute("s"); if (size) { updateFileData.s=atoi(size); } const char* fileName=pChildElement->Attribute("f"); if (fileName) { updateFileData.f=fileName; } const char* md5=pChildElement->Attribute("m"); if (md5) { updateFileData.m=md5; } updateVersionFileMap->insert(std::make_pair(type,updateFileData)); } } } return true; } static size_t downLoadPackage(void *ptr, size_t size, size_t nmemb, void *userdata) { FILE *fp = (FILE*)userdata; size_t written = fwrite(ptr, size, nmemb, fp); return written; } int myAssetsManagerProgressFunc(void *ptr, double totalToDownload, double nowDownloaded, double totalToUpLoad, double nowUpLoaded) { CResourcesManager* manager = (CResourcesManager*)ptr; int currentPercent=(nowDownloaded+manager->m_lLocalFileLenth)*100/(totalToDownload+manager->m_lLocalFileLenth); if (currentPercent==manager->m_iCurrentPercent) { return 0; } manager->m_iCurrentPercent=currentPercent; CResourcesManager::CMessage *msg = new CResourcesManager::CMessage(); msg->what = kMessageUpdateProgress; msg->manager=manager; msg->nowDownloaded=nowDownloaded+manager->m_lLocalFileLenth; msg->totalToDownload=totalToDownload+manager->m_lLocalFileLenth; manager->m_pHelper->sendMessage(msg); return 0; } bool CResourcesManager::downLoad() { ////////////////////////////////////////// CResourcesManager::CMessage *msg = new CResourcesManager::CMessage(); msg->what = kMessageUpdateProgress; msg->manager=this; msg->nowDownloaded=0; msg->totalToDownload=0; this->m_pHelper->sendMessage(msg); ////////////////////////////////////////// CFileDownloader *fileDownloader=m_pCurrentFileDownloader; char szUrl[1024] = {0}; // sprintf(szUrl, "%s%s_%d_%d/%s",m_pDownloadUrl.c_str(), m_fAppVersion.c_str(),m_iResourceVersion,fileDownloader->t,fileDownloader->f.c_str()); sprintf(szUrl, "%s/%s",m_pDownloadUrl.c_str(),fileDownloader->f.c_str()); CCLOG("szUrl=%s",szUrl); long fileLenth=this->getDownloadFileLenth(szUrl); if (fileLenth <= 0) { sendErrorMessage(kNetwork); CCLOG("error when get package size"); return false; } string outFileName = m_strDownloadCacheFolder + fileDownloader->f; long localFileLenth = getLocalFileLength(outFileName.c_str()); m_lLocalFileLenth=localFileLenth; CCLOG("file=%s fileLenth=%ld,localFileLenth=%ld",fileDownloader->t.c_str(),fileLenth,localFileLenth); ////////////////////////////////////////// msg = new CResourcesManager::CMessage(); msg->what = kMessageUpdateProgress; msg->manager=this; msg->nowDownloaded=localFileLenth; msg->totalToDownload=localFileLenth+fileLenth; this->m_pHelper->sendMessage(msg); ////////////////////////////////////////// if (localFileLenth >0 && fileLenth==localFileLenth) { string filePath=kDownloadFolder+fileDownloader->f; bool isTrue =true;// CCCrypto::MD5WithFileCompare(filePath.c_str(),fileDownloader->m.c_str()); if (isTrue) { CCLOG("had succeed downloading package"); return true; } else { remove(outFileName.c_str()); } } else { remove(outFileName.c_str()); } FILE *fp = NULL; if(FileUtils::getInstance()->isFileExist(outFileName)) { fp = fopen(outFileName.c_str(), "ab+"); } else { fp = fopen(outFileName.c_str(), "wb"); } if (fp == NULL) { sendErrorMessage(kCreateFile); CCLOG("can not create file %s", outFileName.c_str()); return false; } CURLcode res; CURL *curl = curl_easy_init(); curl_easy_setopt(curl, CURLOPT_URL,szUrl); // curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, downLoadPackage); curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); curl_easy_setopt(curl, CURLOPT_RESUME_FROM, localFileLenth); // curl_easy_setopt(handle, CURLOPT_RESUME_FROM_LARGE, localFileLenth); curl_easy_setopt(curl, CURLOPT_NOPROGRESS, false); curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, myAssetsManagerProgressFunc); curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, this); res = curl_easy_perform(curl); curl_easy_cleanup(curl); if (res != 0) { sendErrorMessage(kNetwork); CCLOG("error when download package"); fclose(fp); return false; } fclose(fp); #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) Sleep(1); #else sleep(1); #endif // string filePath=kDownloadFolder+fileDownloader->f; // bool isTrue = CCCrypto::MD5WithFileCompare(filePath.c_str(),fileDownloader->m.c_str()); // if (!isTrue) // { // remove(outFileName.c_str()); // sendErrorMessage(kNetwork); // CCLOG("error when check md5"); // return false; // } return true; } long CResourcesManager::getLocalFileLength(const char* filePath) { long length =0; FILE *fp = fopen(filePath, "r"); if (fp) { fseek(fp, 0, SEEK_END); length = ftell(fp); fclose(fp); } return length; } long CResourcesManager::getDownloadFileLenth(const char* downloadUrl) { double fileLenth=0; CURL *handle = curl_easy_init(); curl_easy_setopt(handle, CURLOPT_URL, downloadUrl); curl_easy_setopt(handle, CURLOPT_NOBODY, 1L); curl_easy_setopt(handle, CURLOPT_HEADER, 0L); if (curl_easy_perform(handle) == CURLE_OK) { curl_easy_getinfo(handle, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &fileLenth); } else { fileLenth = -1; } return fileLenth; } void CResourcesManager::sendErrorMessage(CResourcesManager::ErrorCode code) { CMessage *msg = new CMessage(); msg->what = kMessageUpdateError; msg->code = code; msg->manager = this; m_pHelper->sendMessage(msg); } void resDownloadAndUncompress(void *data) { CResourcesManager* self =dynamic_cast<CResourcesManager*>((CResourcesManager*)data); bool isHappenError=false; while (self!=NULL && self->m_pCurrentFileDownloader!=NULL) { try { if (!self->downLoad()) { self->sendErrorMessage(CResourcesManager::kNetwork); isHappenError=true; break; } } catch(exception &e) { CCLOG("exception downLoad:%s",self->m_pCurrentFileDownloader->f.c_str()); char str[128]={0}; sprintf(str, "ERROR exception downLoad file:%s",self->m_pCurrentFileDownloader->f.c_str()); MessageBox(str, "ERROR TIPS"); } CResourcesManager::CMessage *msg1 = new CResourcesManager::CMessage(); msg1->what = kMessageUpdateDownload; msg1->manager = self; self->m_pHelper->sendMessage(msg1); try { if (!self->uncompress()) { self->sendErrorMessage(CResourcesManager::kUncompress); isHappenError=true; break; } } catch(exception &e) { CCLOG("exception uncompress:%s",self->m_pCurrentFileDownloader->f.c_str()); char str[128]={0}; sprintf(str, "ERROR exception uncompress file:%s",self->m_pCurrentFileDownloader->f.c_str()); MessageBox(str, "ERROR TIPS"); } CResourcesManager::CMessage *msg2 = new CResourcesManager::CMessage(); msg2->what = kMessageUpdateSucceed; msg2->manager = self; self->m_pHelper->sendMessage(msg2); self->maskCurrentFileDownloaderFinish(true); break; } if (isHappenError && self!=NULL && self->m_pCurrentFileDownloader!=NULL) { self->m_pCurrentFileDownloader->requestFailedTimes++; if (self->m_pCurrentFileDownloader->requestFailedTimes>4) { self->sendErrorMessage(CResourcesManager::kUpdateFailed); } } if (self!=NULL && self->m_pThread) { delete (self->m_pThread); self->m_pThread = NULL; } // return NULL; } void CResourcesManager::maskCurrentFileDownloaderFinish(bool isFinish) { m_pCurrentFileDownloader->isFinish=isFinish; } void CResourcesManager::resetCurrentFileDownloader() { CC_SAFE_RELEASE_NULL(m_pCurrentFileDownloader); } bool CResourcesManager::nextFileDownloader() { if (m_pFileDownloadersArray->count()==0) { if (m_pCurrentFileDownloader) { return true; } return false; } Ref* fileDownloader=m_pFileDownloadersArray->getLastObject(); if (fileDownloader!=NULL) { CC_SAFE_RELEASE_NULL(m_pCurrentFileDownloader); m_pCurrentFileDownloader=dynamic_cast<CFileDownloader*>(fileDownloader); if (!m_pCurrentFileDownloader) { return false; } CC_SAFE_RETAIN(m_pCurrentFileDownloader); m_pFileDownloadersArray->removeObject(fileDownloader); } return true; } void CResourcesManager::removeOldFile() { std::string removeFile="removeFiles.json"; std::string fullPath=FileUtils::getInstance()->fullPathForFilename(removeFile); if(FileUtils::getInstance()->isFileExist(fullPath)) { std::string contentStr=FileUtils::getInstance()->getStringFromFile(removeFile); if(contentStr.length()>3) { rapidjson::Document jsonDict; jsonDict.Parse<0>(contentStr.c_str()); if (jsonDict.HasParseError()) { CCLOG("removeOldFile GetParseError %d\n",jsonDict.GetParseError()); return; } if (jsonDict.IsArray()) { for (rapidjson::SizeType i=0; i<jsonDict.Size(); i++) { string outFileName = *m_strDownloadFolder +jsonDict[i].GetString(); if(FileUtils::getInstance()->isFileExist(outFileName)) { if (remove(outFileName.c_str()) != 0) CCLOG("can not remove removeOldFile %s", outFileName.c_str()); } } } } if (remove(fullPath.c_str()) != 0) CCLOG("can not remove removeOldFile %s", fullPath.c_str()); } } void CResourcesManager::mainThreadProcess(float dt) { if (m_pCurrentFileDownloader==NULL && !this->nextFileDownloader()) { m_pHelper->update(dt); this->stopUpdate(); if (m_pDelegate) { this->removeOldFile(); m_pDelegate->onUpdateFinish(); } return; } m_pHelper->update(dt); if (m_pCurrentFileDownloader==NULL) { return; } if (m_pThread!=NULL || m_pCurrentFileDownloader->isFinish) { return; } m_iCurrentPercent=0; m_pThread=new std::thread(resDownloadAndUncompress, this); m_pThread->detach(); } bool CResourcesManager::uncompress() { CFileDownloader *fileDownloader=m_pCurrentFileDownloader; if (fileDownloader==NULL) { return false; } string outFileName = m_strDownloadCacheFolder + fileDownloader->f; if (fileDownloader->f=="data.ios") { string inFileName = *m_strDownloadFolder + fileDownloader->f; FILE* srcFile = fopen(outFileName.c_str(),"r"); if (!srcFile) { CCLOG("can not open file %s", outFileName.c_str()); return false; } FILE* dstFile = fopen(inFileName.c_str(),"w+"); if (!dstFile) { CCLOG("can not open file %s", inFileName.c_str()); return false; } char readBuffer[BUFFER_SIZE]; size_t nread = 0; while ((nread=fread(readBuffer,sizeof(char),BUFFER_SIZE,srcFile))>0) { fwrite(readBuffer,sizeof(char),nread,dstFile); } fclose(srcFile); fclose(dstFile); return true; } unzFile zipfile = unzOpen(outFileName.c_str()); if (! zipfile) { CCLOG("can not open downloaded zip file %s", outFileName.c_str()); return false; } unz_global_info global_info; if (unzGetGlobalInfo(zipfile, &global_info) != UNZ_OK) { CCLOG("can not read file global info of %s", outFileName.c_str()); unzClose(zipfile); return false; } char readBuffer[BUFFER_SIZE]; uLong i; for (i = 0; i < global_info.number_entry; ++i) { CResourcesManager::CMessage *msg = new CResourcesManager::CMessage(); msg->what = kMessageUncompress; msg->manager=this; msg->nowDownloaded=i; msg->totalToDownload=global_info.number_entry; this->m_pHelper->sendMessage(msg); // Get info about current file. unz_file_info fileInfo; char fileName[MAX_FILENAME]; if (unzGetCurrentFileInfo(zipfile, &fileInfo, fileName, MAX_FILENAME, NULL, 0, NULL, 0) != UNZ_OK) { CCLOG("can not read file info"); unzClose(zipfile); return false; } string fullPath = *m_strDownloadFolder + fileName; const size_t filenameLength = strlen(fileName); if (fileName[filenameLength-1] == '/') { if (!m_pResourcesHelper->createDirectory(fullPath.c_str())) { CCLOG("can not create directory %s", fullPath.c_str()); unzClose(zipfile); return false; } } else { if (unzOpenCurrentFile(zipfile) != UNZ_OK) { CCLOG("can not open file %s", fileName); unzClose(zipfile); return false; } FILE *out = fopen(fullPath.c_str(), "wb"); if (!out) { CCLOG("can not open destination file %s", fullPath.c_str()); unzCloseCurrentFile(zipfile); unzClose(zipfile); return false; } int error = UNZ_OK; do { error = unzReadCurrentFile(zipfile, readBuffer, BUFFER_SIZE); if (error < 0) { CCLOG("can not read zip file %s, error code is %d", fileName, error); unzCloseCurrentFile(zipfile); unzClose(zipfile); return false; } if (error > 0) { fwrite(readBuffer, error, 1, out); } } while(error > 0); fclose(out); } unzCloseCurrentFile(zipfile); if ((i+1) < global_info.number_entry) { if (unzGoToNextFile(zipfile) != UNZ_OK) { CCLOG("can not read next file"); unzClose(zipfile); return false; } } } return true; } //////////////////////////////////////////////////////////////////////////////////////// CResourcesManager::CHelper::CHelper() { _messageQueue = new list<CMessage*>(); } CResourcesManager::CHelper::~CHelper() { delete _messageQueue; } void CResourcesManager::CHelper::sendMessage(CMessage *msg) { _messageQueueMutex.lock(); _messageQueue->push_back(msg); _messageQueueMutex.unlock(); } void CResourcesManager::CHelper::update(float dt) { _messageQueueMutex.lock(); if (0 == _messageQueue->size()) { _messageQueueMutex.unlock(); return; } CMessage *msg = *(_messageQueue->begin()); _messageQueue->pop_front(); _messageQueueMutex.unlock(); CResourcesManager* manager = (CResourcesManager*)msg->manager; switch (msg->what) { case kMessageUpdateSucceed: handleUpdateSucceed(msg); break; case kMessageUpdateProgress: if (manager->m_pDelegate) { CFileDownloader *fileDownloader=manager->m_pCurrentFileDownloader; if (fileDownloader) { manager->m_pDelegate->onProgress(fileDownloader->t.c_str(), msg->nowDownloaded,msg->totalToDownload); } } break; case kMessageUncompress: if (manager->m_pDelegate) { CFileDownloader *fileDownloader=manager->m_pCurrentFileDownloader; if (fileDownloader) { manager->m_pDelegate->onUncompressProgress(fileDownloader->t.c_str(), msg->nowDownloaded,msg->totalToDownload); } } break; case kMessageUpdateDownload: break; case kMessageUpdateError: if (manager->m_pDelegate) { manager->m_pDelegate->onError(msg->code); } switch (msg->code) { case kUpdateFailed: { if (manager->m_pDelegate) { CFileDownloader *fileDownloader=manager->m_pCurrentFileDownloader; string fileName=""; if (fileDownloader) { fileName=fileDownloader->t; } manager->m_pDelegate->onUpdateFailed(fileName.c_str()); fileName = manager->m_strDownloadCacheFolder + fileDownloader->f; if (remove(fileName.c_str()) != 0) { CCLOG("can not remove downloaded zip file %s", fileName.c_str()); } } manager->stopUpdate(); } break; default: break; } break; default: break; } delete msg; } void CResourcesManager::CHelper::handleUpdateSucceed(CMessage *msg) { CResourcesManager* manager = (CResourcesManager*)msg->manager; CFileDownloader *fileDownloader=manager->m_pCurrentFileDownloader; { string outFileName = manager->m_strDownloadCacheFolder + fileDownloader->f; if (remove(outFileName.c_str()) != 0) { CCLOG("can not remove downloaded zip file %s", outFileName.c_str()); } } manager->saveFileDownloader(); manager->resetCurrentFileDownloader(); if (manager->m_pDelegate) manager->m_pDelegate->onSuccess(); }
[ "linyouhappy@foxmail.com" ]
linyouhappy@foxmail.com
ce9247f84c01b5c024a5ec2b48785fa4d82acfa5
35217b604e87f78a09954236bf74c37ae01bdce1
/src/NN/pca.hpp
302664ed1f135f0ec762d903ac7b333d89604c19
[]
no_license
fengbingchun/NN_Test
f3e771a70a72414823854fd8717024da82054f2e
dcb1b600eb1c6637d41a9ef5bfe68b9cd81d95dd
refs/heads/master
2023-05-27T22:59:04.502548
2023-05-21T04:36:54
2023-05-21T04:36:54
53,240,908
358
302
null
null
null
null
UTF-8
C++
false
false
2,464
hpp
#ifndef FBC_NN_PCA_HPP_ #define FBC_NN_PCA_HPP_ // Blog: http://blog.csdn.net/fengbingchun/article/details/79235028 #include <vector> #include <string> namespace ANN { template<typename T = float> class PCA { public: PCA() = default; int load_data(const std::vector<std::vector<T>>& data, const std::vector<T>& labels); int set_max_components(int max_components); int set_retained_variance(double retained_variance); int load_model(const std::string& model); int train(const std::string& model); // project into the eigenspace, thus the image becomes a "point" int project(const std::vector<T>& vec, std::vector<T>& result) const; // re-create the image from the "point" int back_project(const std::vector<T>& vec, std::vector<T>& result) const; private: // width,height,eigen_vectors;width,height,eigen_values;width,height,means int save_model(const std::string& model) const; void calculate_covariance_matrix(std::vector<std::vector<T>>& covar, bool scale = false); // calculate covariance matrix int eigen(const std::vector<std::vector<T>>& mat, bool sort_ = true); // calculate eigen vectors and eigen values // generalized matrix multiplication: dst = alpha*src1.t()*src2 + beta*src3.t() int gemm(const std::vector<std::vector<T>>& src1, const std::vector<std::vector<T>>& src2, double alpha, const std::vector<std::vector<T>>& src3, double beta, std::vector<std::vector<T>>& dst, int flags = 0) const; int gemm(const std::vector<T>& src1, const std::vector<std::vector<T>>& src2, double alpha, const std::vector<T>& src3, double beta, std::vector<T>& dst, int flags = 0) const; // GEMM_2_T: flags = 1 int normalize(T* dst, int length); int computeCumulativeEnergy() const; int subtract(const std::vector<T>& vec1, const std::vector<T>& vec2, std::vector<T>& result) const; typedef struct Size_ { int width; int height; } Size_; std::vector<std::vector<T>> data; std::vector<T> labels; int samples_num = 0; int features_length = 0; double retained_variance = -1.; // percentage of variance that PCA should retain int max_components = -1; // maximum number of components that PCA should retain std::vector<std::vector<T>> eigen_vectors; // eigenvectors of the covariation matrix std::vector<T> eigen_values; // eigenvalues of the covariation matrix std::vector<T> mean; int covar_flags = 0; // when features_length > samples_num, covar_flags is 0, otherwise is 1 }; } // namespace ANN #endif // FBC_NN_PCA_HPP_
[ "fengbingchun@163.com" ]
fengbingchun@163.com
bb1031b15c60091398dbd843f409320445ff3a10
e221df659c887604b9afe99fe2a17aa015364edb
/labs/lab9v2/lab.cpp
c1e1ce257501bbd24407ad835885b0b05eaa52c0
[]
no_license
pvonleh/Programming-Languages
057cc98c7673940e50a74a4ff37ed0701589e3ce
77c46e2cdc514f81162d2243544cffe6b4c93303
refs/heads/master
2020-03-10T03:46:36.386581
2018-04-12T01:26:40
2018-04-12T01:26:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,581
cpp
#include <iostream> #include <sstream> #include <stdlib.h> using namespace std; int main() { int *Iarr = (int*)malloc(100*sizeof(int)); double *Darr = (double*)malloc(100*sizeof(double)); char *Carr = (char*)malloc(100*sizeof(char)); string Sarr[100]; string aString; int Icount = 0, Dcount = 0, Ccount = 0,Scount = 0; //int Dcount = 0; //int Ccount = 0; //int Scount = 0; // ch = Carr[1][0] while(true) { cout<<"\nEnter your input: "; cin >> aString; std::stringstream ss; ss << aString; int n; double d; char c; char *ep = NULL; const char *cstr = aString.c_str(); d = strtod (cstr, &ep); if (!ep || *ep || aString.find('.') == std::string::npos) { // cout<<"If"<<endl; ss>>n; //cout << n << "\nINTEGER\n"; if(ss.fail()) { // cout<<"Df"<<endl; ss>>c; //cout << c << "\nCHARACTER\n"; //Carr[Ccount++] = c; if(ss.fail()) { //cout<<"Cf"<<endl; Sarr[Scount++] = aString; cout << aString << "\nSTRING\n"; } else { cout << "doesn't hit else"; Carr[Ccount++] = c; cout << c << "\nCHARACTER\n"; } } else { //prints integer Iarr[Icount++] = n; } } else { Darr[Dcount++] = d; } cout<<"\nString List: "; for(int i=0;i<Scount;i++) cout<<Sarr[i]<<" "; cout<<"\nInteger List : "; for(int i=0;i<Icount;i++) cout<<Iarr[i]<<" "; cout<<"\nDouble List: "; for(int i=0;i<Dcount;i++) cout<<Darr[i]<<" "; cout<<"\nCharacter List: "; for(int i=0;i<Ccount;i++) cout<<Carr[i]<<" "; } }
[ "pvonleh@gmail.com" ]
pvonleh@gmail.com
9757efad4b5cdcd28ec789d242ef037e5526f0d9
0b0d4fb48fcc60d574e9b0ab599f0826a6cee25e
/src/kaguya/material/PatinaMaterial.cpp
6a003d638443e185f9db7c37a9b283869a11c1f1
[]
no_license
StormPhoenix/kaguya
fa8337cf5648a211a867d22aaad0d8385bed0386
bab3d634a24527524c87722e2e41885c52d091d4
refs/heads/master
2023-05-03T07:10:29.852816
2021-05-19T07:04:23
2021-05-19T07:04:23
302,261,135
11
0
null
null
null
null
UTF-8
C++
false
false
1,661
cpp
// // Created by Storm Phoenix on 2021/5/10. // #include <kaguya/material/PatinaMaterial.h> #include <kaguya/core/bsdf/microfacet/BeckmannDistribution.h> #include <kaguya/core/bsdf/microfacet/GGXDistribution.h> #include <kaguya/core/bsdf/BXDFGlossyDiffuseReflection.h> namespace kaguya { namespace material { using core::bsdf::BXDFGlossyDiffuseReflection; using core::bsdf::microfacet::GGXDistribution; using core::bsdf::microfacet::BeckmannDistribution; using core::bsdf::microfacet::MicrofacetDistribution; PatinaMaterial::PatinaMaterial(const Texture<Spectrum>::Ptr Kd, const Texture<Spectrum>::Ptr Ks, const Texture<Float>::Ptr alpha) : _Kd(Kd), _Ks(Ks), _alpha(alpha) { ASSERT(_alpha != nullptr, "CoatingMaterial parameter Alpha is nullptr. "); ASSERT(_Kd != nullptr, "CoatingMaterial parameter Kd is nullptr. "); ASSERT(_Ks != nullptr, "CoatingMaterial parameter Ks is nullptr. "); } void PatinaMaterial::computeScatteringFunctions(SurfaceInteraction &insect, MemoryArena &memoryArena, TransportMode mode) { Float alpha = _alpha->evaluate(insect); Spectrum Rd = _Kd->evaluate(insect); Spectrum Rs = _Ks->evaluate(insect); insect.bsdf = ALLOC(memoryArena, BSDF)(insect); const MicrofacetDistribution *distribution = ALLOC(memoryArena, GGXDistribution)(alpha); insect.bsdf->addBXDF(ALLOC(memoryArena, BXDFGlossyDiffuseReflection)(Rd, Rs, distribution)); } } }
[ "stormphoenix.hzau@hotmail.com" ]
stormphoenix.hzau@hotmail.com
d168abc2f83135c91375d0351b6eab5039f006d7
bb7645bab64acc5bc93429a6cdf43e1638237980
/Official Windows Platform Sample/Windows 8 app samples/[C++]-Windows 8 app samples/C++/Windows 8 app samples/ControlChannelTrigger StreamWebSocket sample (Windows 8)/C++/StreamWebSocketTransportHelper/CommModule.cpp
1121cda7736ab1383c6b067f8b8eba3fce6f1131
[ "MIT" ]
permissive
Violet26/msdn-code-gallery-microsoft
3b1d9cfb494dc06b0bd3d509b6b4762eae2e2312
df0f5129fa839a6de8f0f7f7397a8b290c60ffbb
refs/heads/master
2020-12-02T02:00:48.716941
2020-01-05T22:39:02
2020-01-05T22:39:02
230,851,047
1
0
MIT
2019-12-30T05:06:00
2019-12-30T05:05:59
null
UTF-8
C++
false
false
14,682
cpp
// WinCCTomponent.cpp #include "pch.h" #include "CommModule.h" #include <ppltasks.h> #include "DiagnosticsHelper.h" using namespace concurrency; using namespace Platform; using namespace Platform::Collections::Details::WFC; using namespace StreamWebSocketTransportHelper; using namespace StreamWebSocketTransportHelper::DiagnosticsHelper; using namespace Windows::ApplicationModel::Core; using namespace Windows::ApplicationModel::Background; using namespace Windows::Foundation; using namespace Windows::Networking; CoreDispatcher^ Diag::coreDispatcher=nullptr; TextBlock^ Diag::debugOutputTextBlock=nullptr; TSQueue^ AppContext::messageQueue_=nullptr; CommModule::CommModule(AppRole appRole) : TIMEOUT(30000),MAX_BUFFER_LENGTH(100) { } AppContext::AppContext(CommModule^ commInstance, StreamWebSocket^ socket, ControlChannelTrigger^ channel, String^ id) { SocketHandle = socket; Channel = channel; ChannelId = id; CommInstance = commInstance; messageQueue = ref new TSQueue(); } void CommModule::Reset() { concurrency::critical_section::scoped_lock slock(lock); readPacket = nullptr; writePacket = nullptr; socket = nullptr; if (channel != nullptr) { if (CoreApplication::Properties->HasKey(channel->ControlChannelTriggerId)) { CoreApplication::Properties->Remove(channel->ControlChannelTriggerId); } // Call the Dispose() method on the controlchanneltrigger object to release any // OS maintained resources for this channel object. delete channel_; channel_ = nullptr; } Diag::DebugPrint("CommModule has been reset."); } bool CommModule::RegisterWithCCT(String^ serverUri) { // To simplify consistency issues for the commModule instance, // demonstrate the core registration path to use async tasks // but wait for the entire operation to complete before returning from this method. // The transport setup routine can be triggered by user control, by network state change // or by keepalive task and a typical app must be resilient against all of this. bool result = false; socket = ref new StreamWebSocket(); // Specify the keepalive interval expected by the server for this app // in order of minutes. const int serverKeepAliveInterval = 30; // Specify the channelId string to differentiate this // channel instance from any other channel instance. // When background task fires, the channel object is provided // as context and the channel id can be used to adapt the behavior // of the app as required. String^ channelId = "channelOne"; // Try creating the controlchanneltrigger if this has not been already created and stored // in the property bag. Diag::DebugPrint("RegisterCCT Starting..."); ControlChannelTriggerStatus status; Diag::DebugPrint("Create ControlChannelTrigger ..."); // Create the controlchanneltrigger object and request a hardware slot for this app. // If the app is not on LockScreen, then the ControlChannelTrigger constructor will // fail right away. try { channel = ref new ControlChannelTrigger(channelId, serverKeepAliveInterval, ControlChannelTriggerResourceType::RequestHardwareSlot); } catch (AccessDeniedException^ e) { Diag::DebugPrint("Error: " + e->Message + " Please add the app on lockscreen."); return result; } // Register the apps background task with the trigger for keepalive. // // IMPORTANT: Note that this is a websocket sample, therefore the // keepalive task class is provided by Windows for websockets. // For websockets, the system does the keepalive on behalf of the // app but the app still needs to specify this well known keepalive task. // This should be done here in the background registration as well // as in the package manifest. auto keepAliveBuilder = ref new BackgroundTaskBuilder(); keepAliveBuilder->Name = "KeepaliveTaskForChannelOne"; keepAliveBuilder->TaskEntryPoint = "Windows.Networking.Sockets.WebSocketKeepAlive"; keepAliveBuilder->SetTrigger(channel->KeepAliveTrigger); keepAliveBuilder->Register(); // Register the apps background task with the trigger for push notification task. auto pushNotifyBuilder = ref new BackgroundTaskBuilder(); pushNotifyBuilder->Name = "PushNotificationTaskForChannelOne"; pushNotifyBuilder->TaskEntryPoint = "Background.PushNotifyTask"; pushNotifyBuilder->SetTrigger(channel->PushNotificationTrigger); pushNotifyBuilder->Register(); // Tie the transport method to the controlchanneltrigger object to push enable it. // Note that if the transport's TCP connection is broken at a later point of time, // the controlchanneltrigger object can be reused to plugin a new transport by // calling UsingTransport API again. try { Diag::DebugPrint("Calling UsingTransport() ..."); channel->UsingTransport(socket); } catch (Exception^ e) { Diag::DebugPrint("Error: " + e->Message); return result; } // Connect the socket // // If connect fails or times out it will throw exception. create_task(socket->ConnectAsync(ref new Uri(serverUri))).then([this, &status, &result](task<void> connectTask) { try { // Try getting any connect exception. connectTask.get(); Diag::DebugPrint("Connected"); // Call WaitForPushEnabled API to make sure the TCP connection has // been established, which will mean that the OS will have allocated // any hardware slot for this TCP connection. // // In this sample, the ControlChannelTrigger object was created by // explicitly requesting a hardware slot. // // On Non-AOAC systems, if app requests hardware slot as above, // the system will fallback to a software slot automatically. // // On AOAC systems, if no hardware slot is available, then app // can request a software slot [by re-creating the ControlChannelTrigger object]. status = channel->WaitForPushEnabled(); Diag::DebugPrint("WaitForPushEnabled() completed with status: " + status.ToString()); if (status != ControlChannelTriggerStatus::HardwareSlotAllocated && status != ControlChannelTriggerStatus::SoftwareSlotAllocated) { result = false; throw ref new Exception(E_FAIL, "Neither hardware nor software slot could be allocated."); } // Store the objects created in the property bag for later use. // NOTE: make sure these objects are free threaded. STA/Both objects can // cause deadlocks when foreground threads are suspended. if (CoreApplication::Properties->HasKey(channel->ControlChannelTriggerId)) { CoreApplication::Properties->Remove(channel->ControlChannelTriggerId); } auto appContext = ref new AppContext(this, socket, channel, channel->ControlChannelTriggerId); CoreApplication::Properties->Insert(channel->ControlChannelTriggerId, appContext); result = true; Diag::DebugPrint("RegisterCCT Completed."); // Almost done. Post a read since we are using stream web socket // to allow push notifications to be received. PostSocketRead(MAX_BUFFER_LENGTH); } catch (Exception^ exp) { Diag::DebugPrint("RegisterCCT Task failed with: " + exp->Message); // Exceptions may be thrown for example if the application has not // registered the background task class id for using ControlChannelTrigger // in the package appx manifest or if the application was not on lockscreen // or if the connect failed or the app tried a loopback connect. } }).wait(); return result; } bool CommModule::SetupTransport(String^ serverUri) { concurrency::critical_section::scoped_lock slock(lock); bool result = false; // Save these to help reconnect later. ServerUri = serverUri; // Set up the CCT channel with the stream socket. result = RegisterWithCCT(serverUri); if (result == false) { Diag::DebugPrint("Failed to sign on and connect"); socket = nullptr; readPacket = nullptr; if (channel != nullptr) { // Explicitly dispose any slot/resources that were allocated. delete channel; channel = nullptr; } } return result; } void CommModule::PostSocketRead(int length) { Diag::DebugPrint("Entering PostSocketRead"); // IMPORTANT: When using winRT based transports such as StreamWebSocket with the ControlChannelTrigger, // we have to use the raw async pattern for handling reads instead of the ppl tasks model. // Using the raw async pattern allows Windows to synchronize the PushNotification task's // IBackgroundTask::Run method with the return of the receive completion callback. // The Run method is invoked after the completion callback returns. This ensures that the app has // received the data/errors before the Run method is invoked. // It is important to note that the app has to post another read before it returns control from the completion callback. // It is also important to note that the DataReader is not directly used with the // StreamWebSocket transport since that breaks the synchronization described above. // It is not supported to use DataReader's LoadAsync method directly on top of the transport. Instead, // the IBuffer returned by the transport's ReadAsync method can be later passed to DataReader::FromBuffer() // for further processing. auto readBuf = ref new Buffer(static_cast<unsigned int>(length)); auto readOp = socket->InputStream->ReadAsync(readBuf, length, InputStreamOptions::Partial); readOp->Completed = ref new AsyncOperationWithProgressCompletedHandler<IBuffer^, unsigned int>([this](IAsyncOperationWithProgress<IBuffer^, unsigned int>^ asyncOp, AsyncStatus asyncStatus) { switch (asyncStatus) { case AsyncStatus::Completed: case AsyncStatus::Error: try { // GetResults in AsyncStatus::Error is called as it throws a user friendly error string. auto localReadBuf = asyncOp->GetResults(); unsigned int bytesRead = localReadBuf->Length; readPacket = DataReader::FromBuffer(localReadBuf); OnDataReadCompletion(bytesRead, readPacket); } catch(Exception^ e) { Diag::DebugPrint("Read completion failed: " + e->Message); } break; case AsyncStatus::Canceled: // Read is not cancelled in this sample. break; } }); Diag::DebugPrint("Leaving PostSocketRead"); } void CommModule::OnDataReadCompletion(unsigned int bytesRead, DataReader^ readPacket) { Diag::DebugPrint("OnDataReadCompletion Entry"); if (readPacket == nullptr) { Diag::DebugPrint("DataReader is null"); // Ideally when read completion returns error, // apps should be resilient and try to // recover if there is an error by posting another recv // after creating a new transport, if required. return; } unsigned int buffLen = readPacket->UnconsumedBufferLength; Diag::DebugPrint("bytesRead: " + bytesRead + ", unconsumedbufflength: " + buffLen); // Check if buffLen is 0 and treat that as fatal error. if (buffLen == 0) { Diag::DebugPrint("Received zero bytes from the socket. Server must have closed the connection."); Diag::DebugPrint("Try disconnecting and reconnecting to the server"); return; } // Perform minimal processing in the completion. String^ message = readPacket->ReadString(buffLen); Diag::DebugPrint("Received Buffer : " + message); // Enqueue the message received to a queue that the push notify task will pick up. auto appContext = dynamic_cast<AppContext^>(CoreApplication::Properties->Lookup("channelOne")); appContext->messageQueue->Enqueue(message); // Post another receive to ensure future push notifications. PostSocketRead(MAX_BUFFER_LENGTH); Diag::DebugPrint("OnDataReadCompletion Exit"); } void CommModule::SendMessage(String^ message) { concurrency::critical_section::scoped_lock slock(lock); if (socket == nullptr) { Diag::DebugPrint("Please setup connection with the server first."); } else { if (writePacket == nullptr) { try { writePacket = ref new DataWriter(socket->OutputStream); } catch (Exception^ e) { Diag::DebugPrint("Could not attach data writer to the socket"); return; }; } Diag::DebugPrint("Sending message to server: " + message); // Buffer any data we want to send. writePacket->UnicodeEncoding = Windows::Storage::Streams::UnicodeEncoding::Utf8; writePacket->WriteString(message); // Send the data as one complete message. create_task(writePacket->StoreAsync()).then([this](task<unsigned int> previousTask) { try { previousTask.get(); } catch (Exception^ exception) { Diag::DebugPrint("Write task failed with error: " + exception->Message); } }); } } TSQueue::TSQueue() { queue = new std::queue<String^,std::deque<String^,std::allocator<String^>>>(); } void TSQueue::Enqueue(String^ data) { concurrency::critical_section::scoped_lock slock(lock); queue->push(data); } String^ TSQueue::Dequeue() { String^ outdata; concurrency::critical_section::scoped_lock slock(lock); { if(queue->empty()) { outdata = nullptr; } else { outdata = queue->front(); queue->pop(); } } return outdata; }
[ "v-tiafe@microsoft.com" ]
v-tiafe@microsoft.com
a04e8e13b0e2cad316c9a5f63987f491f6225e73
6cbdcfcab39c0ab38f462a45331c4dd600d3c031
/tile/codegen/emitc.cc
0c3ccd2aa4c09b6c98a6ec87991ae2060e8a01f6
[ "Apache-2.0" ]
permissive
donaldlee2010/plaidml
01ae79cc6f91d682efd1562eae660fa5e4eb88f0
ec748d1cb488e5863b8134ec843cf85442df644d
refs/heads/master
2020-04-28T08:04:14.935971
2019-02-05T01:11:16
2019-02-05T01:11:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,305
cc
// Copyright 2018, Intel Corporation #include "tile/codegen/emitc.h" namespace vertexai { namespace tile { namespace codegen { using boost::format; using namespace std::placeholders; // NOLINT using namespace stripe; // NOLINT namespace { class CodeGenerator { public: CodeGenerator() {} std::string EmitProgram(const Block& program) { EmitLine("#include <stdint.h>"); EmitLine("#include <stdlib.h>"); EmitLine(R"( int min(int x, int y) { return (x < y) ? x : y; } int max(int x, int y) { return (x < y) ? y : x; } float softmax(float x) { return x; } )"); EmitLine("int main(int argc, char** argv) {"); PushTab(); EmitBlock(program); EmitLine("return 0;"); PopTab(); EmitLine("}"); return oss_.str(); } private: void EmitLoad(const Block& block, const Load& load) { auto ref = block.ref_by_into(load.from); EmitLine(format("%1% %2% = %3%[%4%];") // % IntoC(ref->interior_shape.type) // % ScalarName(load.into) // % UniqueName(load.from) // % UniqueResolve(ref->FlatAccess())); } void EmitStore(const Block& block, const Store& store) { auto ref = block.ref_by_into(store.into); auto into = UniqueName(ref->into); auto access = UniqueResolve(ref->FlatAccess()); if (ref->agg_op == Intrinsic::SUM) { EmitLine(format("%1%[%2%] += %3%;") % into % access % ScalarName(store.from)); } else if (ref->agg_op == Intrinsic::PROD) { EmitLine(format("%1%[%2%] *= %3%;") % into % access % ScalarName(store.from)); } else if (ref->agg_op == Intrinsic::MIN) { EmitLine(format("%1%[%2%] = min(%1%[%2%], %3%);") % into % access % ScalarName(store.from)); } else if (ref->agg_op == Intrinsic::MAX) { EmitLine(format("%1%[%2%] = max(%1%[%2%], %3%);") % into % access % ScalarName(store.from)); } else { EmitLine(format("%1%[%2%] = %3%;") % into % access % ScalarName(store.from)); } } void EmitIntrinsic(const Block& block, const Intrinsic& intrinsic) { if (intrinsic.outputs.size() > 1) { throw std::runtime_error("Only a single output is supported for intrinsics"); } auto output = ScalarName(intrinsic.outputs[0]); if (intrinsic.name == Intrinsic::MUL) { EmitLine(format("%1% %2% = %3% * %4%;") // % IntoC(intrinsic.type) // % output // % ScalarName(intrinsic.inputs[0]) // % ScalarName(intrinsic.inputs[1])); } else if (intrinsic.name == Intrinsic::ADD) { EmitLine(format("%1% %2% = %3% + %4%;") // % IntoC(intrinsic.type) // % output // % ScalarName(intrinsic.inputs[0]) // % ScalarName(intrinsic.inputs[1])); } else if (intrinsic.name == "bit_right") { EmitLine(format("%1% %2% = %3% >> %4%;") // % IntoC(intrinsic.type) // % output // % ScalarName(intrinsic.inputs[0]) // % ScalarName(intrinsic.inputs[1])); } else if (intrinsic.name == Intrinsic::ASSIGN) { EmitLine(format("%1% %2% = %3%;") // % IntoC(intrinsic.type) // % output // % ScalarName(intrinsic.inputs[0])); } else if (intrinsic.name == "zelu") { EmitLine(format("%1% %2% = %3% < 0 ? 0 : %3%;") // % IntoC(intrinsic.type) // % output // % ScalarName(intrinsic.inputs[0])); } else { std::stringstream inputs; for (size_t i = 0; i < intrinsic.inputs.size(); i++) { if (i) { inputs << ", "; } inputs << ScalarName(intrinsic.inputs[i]); } EmitLine(format("%1% %2% = %3%(%4%);") // % IntoC(intrinsic.type) // % output // % intrinsic.name // % inputs.str()); } } void EmitConstant(const Constant& constant) { switch (constant.type) { case ConstType::Integer: EmitLine(format("int %1% = %2%;") % ScalarName(constant.name) % constant.iconst); break; case ConstType::Float: EmitLine(format("double %1% = %2%;") % ScalarName(constant.name) % constant.fconst); break; } } void EmitSpecial(const Special& special) { // EmitLine(format("// TODO: %1%") % special); } void EmitBlock(const Block& block) { Push(); EmitLine(format("{ // block: %1%") % block.name); std::stringstream ss(block.comments); std::string line; for (std::string line; std::getline(ss, line, '\n');) { EmitLine(format("// %1%") % line); } PushTab(); for (const auto& idx : block.idxs) { auto idx_name = UniqueName(idx.name); if (idx.range == 1) { EmitLine(format("int %1% = %2%;") % idx_name % ParentResolve(idx.affine)); } else { EmitLine(format("for (int %1% = 0; %1% < %2%; %1%++) {") % idx_name % idx.range); PushTab(); } } for (const auto& constraint : block.constraints) { EmitLine(format("if ((%1%) < 0) {") % UniqueResolve(constraint)); PushTab(); EmitLine("continue;"); PopTab(); EmitLine("}"); } for (const auto& ref : block.refs) { auto type = IntoC(ref.interior_shape.type); auto into = UniqueName(ref.into); if (ref.from.empty()) { EmitLine(format("%1%* %2% = malloc(%3% * sizeof(%1%));") % type % into % ref.interior_shape.elem_size()); } else { EmitLine(format("%1%* %2% = %3% + %4%;") % type % into % ParentName(ref.from) % UniqueResolve(ref.FlatAccess())); } } for (const auto& stmt : block.stmts) { switch (stmt->kind()) { case StmtKind::Load: EmitLoad(block, *Load::Downcast(stmt)); break; case StmtKind::Store: EmitStore(block, *Store::Downcast(stmt)); break; case StmtKind::Intrinsic: EmitIntrinsic(block, *Intrinsic::Downcast(stmt)); break; case StmtKind::Constant: EmitConstant(*Constant::Downcast(stmt)); break; case StmtKind::Special: EmitSpecial(*Special::Downcast(stmt)); break; case StmtKind::Block: EmitBlock(*Block::Downcast(stmt)); break; } } for (const auto& ref : block.refs) { if (ref.from.empty()) { EmitLine(format("free(%1%);") % UniqueName(ref.into)); } } for (const auto& idx : block.idxs) { if (idx.range != 1) { PopTab(); EmitLine("}"); } } PopTab(); EmitLine("}"); Pop(); } std::string IntoC(const DataType& type) { switch (type) { case DataType::BOOLEAN: return "bool"; case DataType::INT8: return "int8_t"; case DataType::INT16: return "int16_t"; case DataType::INT32: return "int32_t"; case DataType::INT64: return "int64_t"; case DataType::UINT8: return "uint8_t"; case DataType::UINT16: return "uint16_t"; case DataType::UINT32: return "uint32_t"; case DataType::UINT64: return "uint64_t"; case DataType::FLOAT16: return "half"; case DataType::FLOAT32: return "float"; case DataType::FLOAT64: return "double"; default: throw std::runtime_error("Invalid tile type"); } } void EmitTab() { oss_ << std::string(indent_ << 1, ' '); } void EmitLine(const std::string& str) { EmitTab(); oss_ << str << '\n'; } void EmitLine(const format& fmt) { EmitTab(); oss_ << fmt << '\n'; } void Push() { depth_++; } void Pop() { depth_--; } void PushTab() { indent_++; } void PopTab() { indent_--; } std::string ScalarName(std::string str) { std::replace(str.begin(), str.end(), '$', '_'); return UniqueName(str); } Affine Resolve(Affine affine, const std::function<std::string(const std::string&)>& resolver) { std::vector<std::string> names; for (const auto& kvp : affine.getMap()) { if (!kvp.first.empty()) { names.push_back(kvp.first); } } for (const auto& name : names) { affine.substitute(name, Affine{resolver(name)}); } return affine; } std::string ParentName(const std::string& name) { return str(format("d%1%_%2%") % (depth_ - 1) % name); } std::string UniqueName(const std::string& name) { return str(format("d%1%_%2%") % depth_ % name); } Affine ParentResolve(const Affine& affine) { return Resolve(affine, std::bind(&CodeGenerator::ParentName, this, _1)); } Affine UniqueResolve(const Affine& affine) { return Resolve(affine, std::bind(&CodeGenerator::UniqueName, this, _1)); } std::ostringstream oss_; size_t indent_ = 0; size_t depth_ = 0; }; } // namespace std::string EmitC(const Block& program) { CodeGenerator gen; return gen.EmitProgram(program); } } // namespace codegen } // namespace tile } // namespace vertexai
[ "frank.laub@intel.com" ]
frank.laub@intel.com
8743fbef39bd207a2d606719082cf145e5cbe6f5
59215e2eb694b0a0ce629a2fe19cc7af84047b47
/WebSocketCPP_Beast/common/ssl_stream.hpp
ffbe495ce9e5f605dcdbdf1c79dd15955729dfe1
[ "MIT" ]
permissive
EdFuentetaja/WebSockets
3d83d06722c2dafcd11e83fcbab1c1c7fd0ae12d
c6241a291b74754356560e1ccad3a536980e0847
refs/heads/master
2021-01-24T02:17:24.395701
2018-07-21T08:08:28
2018-07-21T08:08:28
122,841,865
1
0
null
null
null
null
UTF-8
C++
false
false
8,947
hpp
// // Copyright (c) 2016-2017 Vinnie Falco (vinnie dot falco at gmail dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Official repository: https://github.com/boostorg/beast // #ifndef BOOST_BEAST_EXAMPLE_COMMON_SSL_STREAM_HPP #define BOOST_BEAST_EXAMPLE_COMMON_SSL_STREAM_HPP // This include is necessary to work with `ssl::stream` and `boost::beast::websocket::stream` #include <boost/beast/websocket/ssl.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/ssl/stream.hpp> #include <cstddef> #include <memory> #include <type_traits> #include <utility> /** C++11 enabled SSL socket wrapper This wrapper provides an interface identical to `boost::asio::ssl::stream`, with the following additional properties: @li Satisfies @b MoveConstructible @li Satisfies @b MoveAssignable @li Constructible from a moved socket. */ template<class NextLayer> class ssl_stream : public boost::asio::ssl::stream_base { // only works for boost::asio::ip::tcp::socket // for now because of the move limitations static_assert(std::is_same<NextLayer, boost::asio::ip::tcp::socket>::value, "NextLayer requirements not met"); using stream_type = boost::asio::ssl::stream<NextLayer>; std::unique_ptr<stream_type> p_; boost::asio::ssl::context* ctx_; public: /// The native handle type of the SSL stream. using native_handle_type = typename stream_type::native_handle_type; /// Structure for use with deprecated impl_type. using impl_struct = typename stream_type::impl_struct; /// The type of the next layer. using next_layer_type = typename stream_type::next_layer_type; /// The type of the lowest layer. using lowest_layer_type = typename stream_type::lowest_layer_type; /// The type of the executor associated with the object. using executor_type = typename stream_type::executor_type; ssl_stream( boost::asio::ip::tcp::socket socket, boost::asio::ssl::context& ctx) : p_(new stream_type{ socket.get_executor().context(), ctx}) , ctx_(&ctx) { p_->next_layer() = std::move(socket); } ssl_stream(ssl_stream&& other) : p_(new stream_type( other.get_executor().context(), *other.ctx_)) , ctx_(other.ctx_) { using std::swap; swap(p_, other.p_); } ssl_stream& operator=(ssl_stream&& other) { std::unique_ptr<stream_type> p(new stream_type{ other.get_executor().context(), other.ctx_}); using std::swap; swap(p_, p); swap(p_, other.p_); ctx_ = other.ctx_; return *this; } executor_type get_executor() noexcept { return p_->get_executor(); } native_handle_type native_handle() { return p_->native_handle(); } next_layer_type const& next_layer() const { return p_->next_layer(); } next_layer_type& next_layer() { return p_->next_layer(); } lowest_layer_type& lowest_layer() { return p_->lowest_layer(); } lowest_layer_type const& lowest_layer() const { return p_->lowest_layer(); } void set_verify_mode(boost::asio::ssl::verify_mode v) { p_->set_verify_mode(v); } boost::system::error_code set_verify_mode(boost::asio::ssl::verify_mode v, boost::system::error_code& ec) { return p_->set_verify_mode(v, ec); } void set_verify_depth(int depth) { p_->set_verify_depth(depth); } boost::system::error_code set_verify_depth( int depth, boost::system::error_code& ec) { return p_->set_verify_depth(depth, ec); } template<class VerifyCallback> void set_verify_callback(VerifyCallback callback) { p_->set_verify_callback(callback); } template<class VerifyCallback> boost::system::error_code set_verify_callback(VerifyCallback callback, boost::system::error_code& ec) { return p_->set_verify_callback(callback, ec); } void handshake(handshake_type type) { p_->handshake(type); } boost::system::error_code handshake(handshake_type type, boost::system::error_code& ec) { return p_->handshake(type, ec); } template<class ConstBufferSequence> void handshake( handshake_type type, ConstBufferSequence const& buffers) { p_->handshake(type, buffers); } template<class ConstBufferSequence> boost::system::error_code handshake(handshake_type type, ConstBufferSequence const& buffers, boost::system::error_code& ec) { return p_->handshake(type, buffers, ec); } template<class HandshakeHandler> BOOST_ASIO_INITFN_RESULT_TYPE(HandshakeHandler, void(boost::system::error_code)) async_handshake(handshake_type type, BOOST_ASIO_MOVE_ARG(HandshakeHandler) handler) { return p_->async_handshake(type, BOOST_ASIO_MOVE_CAST(HandshakeHandler)(handler)); } template<class ConstBufferSequence, class BufferedHandshakeHandler> BOOST_ASIO_INITFN_RESULT_TYPE(BufferedHandshakeHandler, void (boost::system::error_code, std::size_t)) async_handshake(handshake_type type, ConstBufferSequence const& buffers, BOOST_ASIO_MOVE_ARG(BufferedHandshakeHandler) handler) { return p_->async_handshake(type, buffers, BOOST_ASIO_MOVE_CAST(BufferedHandshakeHandler)(handler)); } void shutdown() { p_->shutdown(); } boost::system::error_code shutdown(boost::system::error_code& ec) { return p_->shutdown(ec); } template<class ShutdownHandler> BOOST_ASIO_INITFN_RESULT_TYPE(ShutdownHandler, void (boost::system::error_code)) async_shutdown(BOOST_ASIO_MOVE_ARG(ShutdownHandler) handler) { return p_->async_shutdown( BOOST_ASIO_MOVE_CAST(ShutdownHandler)(handler)); } template<class ConstBufferSequence> std::size_t write_some(ConstBufferSequence const& buffers) { return p_->write_some(buffers); } template<class ConstBufferSequence> std::size_t write_some(ConstBufferSequence const& buffers, boost::system::error_code& ec) { return p_->write_some(buffers, ec); } template<class ConstBufferSequence, class WriteHandler> BOOST_ASIO_INITFN_RESULT_TYPE(WriteHandler, void (boost::system::error_code, std::size_t)) async_write_some(ConstBufferSequence const& buffers, BOOST_ASIO_MOVE_ARG(WriteHandler) handler) { return p_->async_write_some(buffers, BOOST_ASIO_MOVE_CAST(WriteHandler)(handler)); } template<class MutableBufferSequence> std::size_t read_some(MutableBufferSequence const& buffers) { return p_->read_some(buffers); } template<class MutableBufferSequence> std::size_t read_some(MutableBufferSequence const& buffers, boost::system::error_code& ec) { return p_->read_some(buffers, ec); } template<class MutableBufferSequence, class ReadHandler> BOOST_ASIO_INITFN_RESULT_TYPE(ReadHandler, void(boost::system::error_code, std::size_t)) async_read_some(MutableBufferSequence const& buffers, BOOST_ASIO_MOVE_ARG(ReadHandler) handler) { return p_->async_read_some(buffers, BOOST_ASIO_MOVE_CAST(ReadHandler)(handler)); } template<class SyncStream> friend void teardown(boost::beast::websocket::role_type, ssl_stream<SyncStream>& stream, boost::system::error_code& ec); template<class AsyncStream, class TeardownHandler> friend void async_teardown(boost::beast::websocket::role_type, ssl_stream<AsyncStream>& stream, TeardownHandler&& handler); }; // These hooks are used to inform boost::beast::websocket::stream on // how to tear down the connection as part of the WebSocket // protocol specifications template<class SyncStream> inline void teardown( boost::beast::websocket::role_type role, ssl_stream<SyncStream>& stream, boost::system::error_code& ec) { // Just forward it to the wrapped ssl::stream using boost::beast::websocket::teardown; teardown(role, *stream.p_, ec); } template<class AsyncStream, class TeardownHandler> inline void async_teardown( boost::beast::websocket::role_type role, ssl_stream<AsyncStream>& stream, TeardownHandler&& handler) { // Just forward it to the wrapped ssl::stream using boost::beast::websocket::async_teardown; async_teardown(role, *stream.p_, std::forward<TeardownHandler>(handler)); } #endif
[ "ed.fuentetaja@gmail.com" ]
ed.fuentetaja@gmail.com
87ecd5a1ad8fab4db28bbd82821be6d03f98c13a
c845f1321793846ad460e9c26891f67624e715b4
/GLCD.h
c01cc9485d09051a6e85651b3f597d598039ba8f
[]
no_license
longshowadenshi/GLCD_SG12864
7b32ebb565023207b46b4ee9219633a55a47d6fc
74b99ab1e3e470c427a5c34b25bea113bcb1f761
refs/heads/main
2023-06-06T01:11:34.115482
2021-06-24T00:42:13
2021-06-24T00:42:13
379,761,167
0
0
null
null
null
null
UTF-8
C++
false
false
4,753
h
#ifndef GLCD_H #define GLCD_H #include <Arduino.h> #define GLCD_displayON 0x3e #define GLCD_Xaddress 0xb8 #define GLCD_Yaddress 0x40 #define GLCD_starline 0xc0 class GLCD { public: GLCD(int bl,int di, int rw, int e, int res, int cs1, int cs2, int db0, int db1, int db2, int db3, int db4, int db5, int db6, int db7); void enable(); void setside(int side); void setDisplay(uint8_t on); void setY(uint8_t col); void setX(uint8_t line); void writeData(uint8_t data); void init(); void gotoXY(uint8_t line,uint8_t col); void clr(); void printbmp(uint8_t *data); void setData(); void putChar(uint8_t line, uint8_t col, uint16_t chr); void printChar(uint8_t line, uint8_t col, char* str); void backLight( bool onOff ) { digitalWrite(bl_pin,onOff?HIGH:LOW); } char font7x8[679]={ 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 95, 0, 0, 0, 0, 7, 7, 0, 7, 7, 0, 20, 127, 127, 20, 127, 127, 20, 36, 46, 107, 107, 58, 18, 0, 70, 102, 48, 24, 12, 102, 98, 48, 122, 79, 93, 55, 122, 72, 4, 7, 3, 0, 0, 0, 0, 0, 28, 62, 99, 65, 0, 0, 0, 65, 99, 62, 28, 0, 0, 8, 42, 62, 28, 28, 62, 42, 8, 8, 62, 62, 8, 8, 0, 0, 128, 224, 96, 0, 0, 0, 8, 8, 8, 8, 8, 8, 0, 0, 0, 96, 96, 0, 0, 0, 96, 48, 24, 12, 6, 3, 1, 62, 127, 113, 89, 77, 127, 62, 64, 66, 127, 127, 64, 64, 0, 98, 115, 89, 73, 111, 102, 0, 34, 99, 73, 73, 127, 54, 0, 24, 28, 22, 83, 127, 127, 80, 39, 103, 69, 69, 125, 57, 0, 60, 126, 75, 73, 121, 48, 0, 3, 3, 113, 121, 15, 7, 0, 54, 127, 73, 73, 127, 54, 0, 6, 79, 73, 105, 63, 30, 0, 0, 0, 102, 102, 0, 0, 0, 0, 128, 230, 102, 0, 0, 0, 8, 28, 54, 99, 65, 0, 0, 36, 36, 36, 36, 36, 36, 0, 0, 65, 99, 54, 28, 8, 0, 2, 3, 81, 89, 15, 6, 0, 62, 127, 65, 93, 93, 31, 30, 124, 126, 19, 19, 126, 124, 0, 65, 127, 127, 73, 73, 127, 54, 28, 62, 99, 65, 65, 99, 34, 65, 127, 127, 65, 99, 62, 28, 65, 127, 127, 73, 93, 65, 99, 65, 127, 127, 73, 29, 1, 3, 28, 62, 99, 65, 81, 115, 114, 127, 127, 8, 8, 127, 127, 0, 0, 65, 127, 127, 65, 0, 0, 48, 112, 64, 65, 127, 63, 1, 65, 127, 127, 8, 28, 119, 99, 65, 127, 127, 65, 64, 96, 112, 127, 127, 14, 28, 14, 127, 127, 127, 127, 6, 12, 24, 127, 127, 28, 62, 99, 65, 99, 62, 28, 65, 127, 127, 73, 9, 15, 6, 30, 63, 33, 113, 127, 94, 0, 65, 127, 127, 9, 25, 127, 102, 38, 111, 77, 89, 115, 50, 0, 3, 65, 127, 127, 65, 3, 0, 127, 127, 64, 64, 127, 127, 0, 31, 63, 96, 96, 63, 31, 0, 127, 127, 48, 24, 48, 127, 127, 67, 103, 60, 24, 60, 103, 67, 7, 79, 120, 120, 79, 7, 0, 71, 99, 113, 89, 77, 103, 115, 0, 127, 127, 65, 65, 0, 0, 1, 3, 6, 12, 24, 48, 96, 0, 65, 65, 127, 127, 0, 0, 8, 12, 6, 3, 6, 12, 8, 128, 128, 128, 128, 128, 128, 128, 0, 0, 3, 7, 4, 0, 0, 32, 116, 84, 84, 60, 120, 64, 65, 127, 63, 72, 72, 120, 48, 56, 124, 68, 68, 108, 40, 0, 48, 120, 72, 73, 63, 127, 64, 56, 124, 84, 84, 92, 24, 0, 72, 126, 127, 73, 3, 2, 0, 56, 188, 164, 164, 252, 120, 0, 65, 127, 127, 8, 4, 124, 120, 0, 68, 125, 125, 64, 0, 0, 96, 224, 128, 128, 253, 125, 0, 65, 127, 127, 16, 56, 108, 68, 0, 65, 127, 127, 64, 0, 0, 120, 124, 28, 56, 28, 124, 120, 124, 124, 4, 4, 124, 120, 0, 56, 124, 68, 68, 124, 56, 0, 0, 252, 252, 164, 36, 60, 24, 24, 60, 36, 164, 248, 252, 132, 68, 124, 120, 76, 4, 28, 24, 72, 92, 84, 84, 116, 36, 0, 0, 4, 62, 127, 68, 36, 0, 60, 124, 64, 64, 60, 124, 64, 28, 60, 96, 96, 60, 28, 0, 60, 124, 112, 56, 112, 124, 60, 68, 108, 56, 16, 56, 108, 68, 60, 188, 160, 160, 252, 124, 0, 76, 100, 116, 92, 76, 100, 0, 8, 8, 62, 119, 65, 65, 0, 0, 0, 0, 127, 127, 0, 0, 65, 65, 119, 62, 8, 8, 0, 2, 3, 1, 3, 2, 3, 1, 255, 129, 129, 129, 129, 129, 255, 14, 159, 145, 177, 251, 74, 0}; private: int bl_pin; int di_pin; int rw_pin; int e_pin; int res_pin; int cs1_pin; int cs2_pin; uint8_t _data_pins[8]; uint8_t _data; int di; int rw; int side; }; #endif
[ "noreply@github.com" ]
longshowadenshi.noreply@github.com
1cb67701654204375fa55e8cec3ace72c00b7b2d
ebb1e564c8a11e5af453f3749dcba1b66e2f3931
/torch/csrc/jit/codegen/cuda/python_frontend/python_bindings.cpp
fe24497276490b5929fe7ea91781e256c8b508d6
[ "BSD-2-Clause", "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "BSL-1.0", "Apache-2.0" ]
permissive
jjsjann123/pytorch
06c3aee8dd3565664ac2e2fda0306432cf62dd7c
de9b3fb3e5eb54660190cbd20b6592fc5cbda547
refs/heads/master
2023-08-25T00:22:02.568347
2022-07-27T18:50:20
2022-07-27T22:38:28
152,169,545
0
1
NOASSERTION
2022-08-11T07:55:44
2018-10-09T01:33:17
C++
UTF-8
C++
false
false
64,774
cpp
#include <torch/csrc/jit/codegen/cuda/python_frontend/python_bindings.h> #ifdef USE_CUDA #include <c10/util/ArrayRef.h> #include <c10/util/irange.h> #include <torch/csrc/jit/codegen/cuda/arith.h> #include <torch/csrc/jit/codegen/cuda/ir_all_nodes.h> #include <torch/csrc/jit/codegen/cuda/ir_builder.h> #include <torch/csrc/jit/codegen/cuda/python_frontend/fusion_definition.h> #include <torch/csrc/jit/codegen/cuda/python_frontend/fusion_record.h> #include <torch/csrc/jit/codegen/cuda/python_frontend/python_bindings.h> #include <torch/csrc/jit/python/pybind_utils.h> #include <iostream> namespace torch { namespace jit { void initNvFuserPythonBindings(PyObject* module) { auto m = py::handle(module).cast<py::module>(); //! Top Level nvFuser Python submodule auto nvfuser = m.def_submodule("_nvfuser"); //! DataTypes supported by nvFuser in the FusionDefinition py::enum_<NvfDataType>(nvfuser, "DataType") .value("Double", NvfDataType::Double) .value("Float", NvfDataType::Float) .value("Half", NvfDataType::Half) .value("Int", NvfDataType::Int) .value("Int32", NvfDataType::Int32) .value("Bool", NvfDataType::Bool) .value("BFloat16", NvfDataType::BFloat16) .value("ComplexFloat", NvfDataType::ComplexFloat) .value("ComplexDouble", NvfDataType::ComplexDouble) .value("Null", NvfDataType::Null); //! Binding an object that owns a FusionExecutorCache instance and provides //! an interface //! \todo This object will be removed when a FusionManager is added //! containing a cache. py::class_<nvfuser::FusionOwner> fusion(nvfuser, "Fusion"); fusion.def(py::init<>()) .def( "execute", [](nvfuser::FusionOwner& self, const py::iterable& iter) { std::vector<IValue> inputs; for (py::handle obj : iter) { inputs.push_back(toIValue(obj, c10::AnyType::get())); } return self.execute(inputs); }, py::return_value_policy::reference) .def("print_ir", [](nvfuser::FusionOwner& self) { self.printIr(); }) .def("print_kernel", [](nvfuser::FusionOwner& self) { self.printKernel(); }); //! These are the FusionDefinition supported object types that are either //! defined as inputs or the output of an operation. py::class_<nvfuser::Tensor>(nvfuser, "Tensor"); py::class_<nvfuser::Scalar>(nvfuser, "Scalar"); //! The FusionDefinition is a context manager in Python where the user will //! define the set the operations and connections between operations for //! nvFuser to create. py::class_<nvfuser::FusionDefinition> fusion_def(nvfuser, "FusionDefinition"); fusion_def.def(py::init<nvfuser::FusionOwner*>()) .def_readwrite("ops", &nvfuser::FusionDefinition::ops) .def( "__enter__", [](nvfuser::FusionDefinition& self) -> nvfuser::FusionDefinition* { return self.enter(); }) .def( "__exit__", [](nvfuser::FusionDefinition& self, void* exc_type, void* exc_value, void* traceback) { self.exit(); }) .def( "add_output", [](nvfuser::FusionDefinition& self, nvfuser::Scalar* output) { self.defineRecord( new nvfuser::OutputRecord<NvfVal>({output->index})); }) .def( "add_output", [](nvfuser::FusionDefinition& self, nvfuser::Tensor* output) { self.defineRecord( new nvfuser::OutputRecord<NvfTensorView>({output->index})); }) .def( "define_tensor", [](nvfuser::FusionDefinition& self, size_t ndims, NvfDataType dtype = NvfDataType::Float) -> nvfuser::Tensor* { std::vector<int64_t> maybe_symbolic_sizes(ndims, -1); ; std::vector<bool> contig_info(ndims, false); nvfuser::Tensor* out = self.defineTensor(); self.defineRecord(new nvfuser::InputTensorRecord( {out->index}, std::move(maybe_symbolic_sizes), std::move(contig_info), dtype)); return out; }, py::arg("ndims"), py::arg("dtype") = torch::jit::fuser::cuda::DataType::Float, py::return_value_policy::reference) .def( "define_tensor", [](nvfuser::FusionDefinition& self, std::vector<int64_t> sizes, std::vector<int64_t> strides, NvfDataType dtype = NvfDataType::Float) -> nvfuser::Tensor* { TORCH_CHECK( sizes.size() == strides.size(), "The number of sizes does not match the number of strides.", sizes.size(), strides.size()); // TensorViewBuilder assumes any dim with a compile time constant // size == 1 is a "maybe broadcast" axis, symbolic sizes are // identified by -1, and size == 0 is not supported. // Translate to TensorViewBuilder's view of the world. std::vector<int64_t> maybe_symbolic_sizes; maybe_symbolic_sizes.reserve(sizes.size()); for (const auto i : c10::irange(sizes.size())) { TORCH_INTERNAL_ASSERT( sizes[i] > 0, "Size of ", sizes[i], " is not supported in nvFuser. Expected size > 0."); if (sizes[i] == 1) { maybe_symbolic_sizes.push_back(1); } else { maybe_symbolic_sizes.push_back(-1); } } std::vector<bool> contig_info(strides.size(), false); for (int i = contig_info.size() - 1; i >= 0; --i) { if (i == static_cast<int>(contig_info.size() - 1)) { contig_info[i] = (strides[i] == 1); } else { contig_info[i] = (strides[i] == (strides[i + 1] * sizes[i + 1])); } } nvfuser::Tensor* out = self.defineTensor(); self.defineRecord(new nvfuser::InputTensorRecord( {out->index}, std::move(maybe_symbolic_sizes), std::move(contig_info), dtype)); return out; }, py::arg("sizes"), py::arg("strides"), py::arg("dtype") = NvfDataType::Float, py::return_value_policy::reference) .def( "define_constant", [](nvfuser::FusionDefinition& self, double val) -> nvfuser::Scalar* { nvfuser::Scalar* out = self.defineScalar(); self.defineRecord( new nvfuser:: ConstantRecord<torch::jit::fuser::cuda::Double, double>( {out->index}, val)); return out; }, py::return_value_policy::reference) .def( "define_constant", [](nvfuser::FusionDefinition& self, c10::complex<double> val) -> nvfuser::Scalar* { nvfuser::Scalar* out = self.defineScalar(); self.defineRecord(new nvfuser::ConstantRecord< torch::jit::fuser::cuda::ComplexDouble, c10::complex<double>>({out->index}, val)); return out; }, py::return_value_policy::reference) .def( "define_constant", [](nvfuser::FusionDefinition& self, bool val) -> nvfuser::Scalar* { nvfuser::Scalar* out = self.defineScalar(); self.defineRecord( new nvfuser:: ConstantRecord<torch::jit::fuser::cuda::Bool, bool>( {out->index}, val)); return out; }, py::return_value_policy::reference) .def( "define_constant", [](nvfuser::FusionDefinition& self, int64_t val) -> nvfuser::Scalar* { nvfuser::Scalar* out = self.defineScalar(); self.defineRecord( new nvfuser:: ConstantRecord<torch::jit::fuser::cuda::Int, int64_t>( {out->index}, val)); return out; }, py::return_value_policy::reference) .def( "define_scalar", [](nvfuser::FusionDefinition& self, NvfDataType dtype = torch::jit::fuser::cuda::DataType::Double) -> nvfuser::Scalar* { nvfuser::Scalar* out = self.defineScalar(); self.defineRecord(new nvfuser::ScalarRecord({out->index}, dtype)); return out; }, py::arg("dtype") = torch::jit::fuser::cuda::DataType::Double, py::return_value_policy::reference); //! The Operators class is a nested class of FusionDefinition to allow the //! user to query the class for the list of operators. //! //! Example: //! help(FusionDefinition.Operators) //! //! Additional operators are expected to be defined below as needed. They //! may require defining a new RecordFunctor child class if they are unique. py::class_<nvfuser::FusionDefinition::Operators> nvf_ops( fusion_def, "Operators"); nvf_ops.def(py::init<nvfuser::FusionDefinition*>()); // ******************** INSERT OP BINDINGS BELOW HERE ******************** #define NVFUSER_PYTHON_BINDING_UNARY_OP(op_str, op_name) \ nvf_ops.def( \ op_str, \ [](nvfuser::FusionDefinition::Operators& self, \ nvfuser::Tensor* input) -> nvfuser::Tensor* { \ nvfuser::Tensor* output = self.fusion_definition->defineTensor(); \ self.fusion_definition->defineRecord( \ new nvfuser::OpRecord<NvfTensorView*, NvfTensorView*>( \ {input->index}, \ {output->index}, \ static_cast<NvfTensorView* (*)(NvfTensorView*)>( \ torch::jit::fuser::cuda::op_name))); \ return output; \ }, \ py::return_value_policy::reference); \ nvf_ops.def( \ op_str, \ [](nvfuser::FusionDefinition::Operators& self, \ nvfuser::Scalar* input) -> nvfuser::Scalar* { \ nvfuser::Scalar* output = self.fusion_definition->defineScalar(); \ self.fusion_definition->defineRecord( \ new nvfuser::OpRecord<NvfVal*, NvfVal*>( \ {input->index}, \ {output->index}, \ static_cast<NvfVal* (*)(NvfVal*)>( \ torch::jit::fuser::cuda::op_name))); \ return output; \ }, \ py::return_value_policy::reference); NVFUSER_PYTHON_BINDING_UNARY_OP("abs", abs) NVFUSER_PYTHON_BINDING_UNARY_OP("acos", acos) NVFUSER_PYTHON_BINDING_UNARY_OP("asin", asin) NVFUSER_PYTHON_BINDING_UNARY_OP("atan", atan) NVFUSER_PYTHON_BINDING_UNARY_OP("atanh", atanh) NVFUSER_PYTHON_BINDING_UNARY_OP("ceil", ceil) NVFUSER_PYTHON_BINDING_UNARY_OP("cos", cos) NVFUSER_PYTHON_BINDING_UNARY_OP("cosh", cosh) NVFUSER_PYTHON_BINDING_UNARY_OP("exp", exp) NVFUSER_PYTHON_BINDING_UNARY_OP("expm1", expm1) NVFUSER_PYTHON_BINDING_UNARY_OP("erf", erf) NVFUSER_PYTHON_BINDING_UNARY_OP("erfc", erfc) NVFUSER_PYTHON_BINDING_UNARY_OP("floor", floor) NVFUSER_PYTHON_BINDING_UNARY_OP("frac", frac) NVFUSER_PYTHON_BINDING_UNARY_OP("lgamma", lgamma) NVFUSER_PYTHON_BINDING_UNARY_OP("log", log) NVFUSER_PYTHON_BINDING_UNARY_OP("log10", log10) NVFUSER_PYTHON_BINDING_UNARY_OP("log1p", log1p) NVFUSER_PYTHON_BINDING_UNARY_OP("log2", log2) NVFUSER_PYTHON_BINDING_UNARY_OP("neg", neg) NVFUSER_PYTHON_BINDING_UNARY_OP("bitwise_not", bitwise_not) NVFUSER_PYTHON_BINDING_UNARY_OP("relu", relu) NVFUSER_PYTHON_BINDING_UNARY_OP("rand_like", randlike) NVFUSER_PYTHON_BINDING_UNARY_OP("reciprocal", reciprocal) NVFUSER_PYTHON_BINDING_UNARY_OP("round", round) NVFUSER_PYTHON_BINDING_UNARY_OP("rsqrt", rsqrt) NVFUSER_PYTHON_BINDING_UNARY_OP("set", set) NVFUSER_PYTHON_BINDING_UNARY_OP("sigmoid", sigmoid) NVFUSER_PYTHON_BINDING_UNARY_OP("silu", silu) NVFUSER_PYTHON_BINDING_UNARY_OP("sin", sin) NVFUSER_PYTHON_BINDING_UNARY_OP("sinh", sinh) NVFUSER_PYTHON_BINDING_UNARY_OP("sqrt", sqrt) NVFUSER_PYTHON_BINDING_UNARY_OP("tan", tan) NVFUSER_PYTHON_BINDING_UNARY_OP("tanh", tanh) NVFUSER_PYTHON_BINDING_UNARY_OP("trunc", trunc) NVFUSER_PYTHON_BINDING_UNARY_OP("isfinite", isfinite) NVFUSER_PYTHON_BINDING_UNARY_OP("isinf", isinf) NVFUSER_PYTHON_BINDING_UNARY_OP("isnan", isnan) NVFUSER_PYTHON_BINDING_UNARY_OP("isneginf", isneginf) NVFUSER_PYTHON_BINDING_UNARY_OP("isposinf", isposinf) NVFUSER_PYTHON_BINDING_UNARY_OP("isreal", isreal) NVFUSER_PYTHON_BINDING_UNARY_OP("real", real) NVFUSER_PYTHON_BINDING_UNARY_OP("imag", imag) #undef NVFUSER_PYTHON_BINDING_UNARY_OP #define NVFUSER_PYTHON_BINDING_BINARY_OP(op_str, op_name) \ nvf_ops.def( \ op_str, \ [](nvfuser::FusionDefinition::Operators& self, \ nvfuser::Tensor* arg1, \ nvfuser::Tensor* arg2) -> nvfuser::Tensor* { \ nvfuser::Tensor* output = self.fusion_definition->defineTensor(); \ self.fusion_definition->defineRecord(new nvfuser::OpRecord< \ NvfTensorView*, \ NvfTensorView*, \ NvfTensorView*>( \ {arg1->index, arg2->index}, \ {output->index}, \ static_cast<NvfTensorView* (*)(NvfTensorView*, NvfTensorView*)>( \ torch::jit::fuser::cuda::op_name))); \ return output; \ }, \ py::return_value_policy::reference); \ nvf_ops.def( \ op_str, \ [](nvfuser::FusionDefinition::Operators& self, \ nvfuser::Tensor* arg1, \ nvfuser::Scalar* arg2) -> nvfuser::Tensor* { \ nvfuser::Tensor* output = self.fusion_definition->defineTensor(); \ self.fusion_definition->defineRecord( \ new nvfuser::OpRecord<NvfTensorView*, NvfTensorView*, NvfVal*>( \ {arg1->index, arg2->index}, \ {output->index}, \ static_cast<NvfTensorView* (*)(NvfTensorView*, NvfVal*)>( \ torch::jit::fuser::cuda::op_name))); \ return output; \ }, \ py::return_value_policy::reference); \ nvf_ops.def( \ op_str, \ [](nvfuser::FusionDefinition::Operators& self, \ nvfuser::Scalar* arg1, \ nvfuser::Tensor* arg2) -> nvfuser::Tensor* { \ nvfuser::Tensor* output = self.fusion_definition->defineTensor(); \ self.fusion_definition->defineRecord( \ new nvfuser::OpRecord<NvfTensorView*, NvfVal*, NvfTensorView*>( \ {arg1->index, arg2->index}, \ {output->index}, \ static_cast<NvfTensorView* (*)(NvfVal*, NvfTensorView*)>( \ torch::jit::fuser::cuda::op_name))); \ return output; \ }, \ py::return_value_policy::reference); \ nvf_ops.def( \ op_str, \ [](nvfuser::FusionDefinition::Operators& self, \ nvfuser::Scalar* arg1, \ nvfuser::Scalar* arg2) -> nvfuser::Scalar* { \ nvfuser::Scalar* output = self.fusion_definition->defineScalar(); \ self.fusion_definition->defineRecord( \ new nvfuser::OpRecord<NvfVal*, NvfVal*, NvfVal*>( \ {arg1->index, arg2->index}, \ {output->index}, \ static_cast<NvfVal* (*)(NvfVal*, NvfVal*)>( \ torch::jit::fuser::cuda::op_name))); \ return output; \ }, \ py::return_value_policy::reference); NVFUSER_PYTHON_BINDING_BINARY_OP("add", add) NVFUSER_PYTHON_BINDING_BINARY_OP("atan2", atan2) NVFUSER_PYTHON_BINDING_BINARY_OP("div", div) NVFUSER_PYTHON_BINDING_BINARY_OP("fmod", fmod) NVFUSER_PYTHON_BINDING_BINARY_OP("mul", mul) NVFUSER_PYTHON_BINDING_BINARY_OP("pow", pow) NVFUSER_PYTHON_BINDING_BINARY_OP("remainder", remainder) NVFUSER_PYTHON_BINDING_BINARY_OP("sub", sub) NVFUSER_PYTHON_BINDING_BINARY_OP("mod", mod) NVFUSER_PYTHON_BINDING_BINARY_OP("eq", eq) NVFUSER_PYTHON_BINDING_BINARY_OP("ge", ge) NVFUSER_PYTHON_BINDING_BINARY_OP("gt", gt) NVFUSER_PYTHON_BINDING_BINARY_OP("le", le) NVFUSER_PYTHON_BINDING_BINARY_OP("lt", lt) NVFUSER_PYTHON_BINDING_BINARY_OP("ne", ne) NVFUSER_PYTHON_BINDING_BINARY_OP("bitwise_and", bitwise_and) NVFUSER_PYTHON_BINDING_BINARY_OP("bitwise_or", bitwise_or) NVFUSER_PYTHON_BINDING_BINARY_OP("bitwise_xor", bitwise_xor) NVFUSER_PYTHON_BINDING_BINARY_OP("bitwise_left_shift", bitwise_left_shift) NVFUSER_PYTHON_BINDING_BINARY_OP("bitwise_right_shift", bitwise_left_shift) #undef NVFUSER_PYTHON_BINDING_BINARY_OP #define NVFUSER_PYTHON_BINDING_BINARY_WITH_ALPHA_OP(op_str, op_name) \ nvf_ops.def( \ op_str, \ [](nvfuser::FusionDefinition::Operators& self, \ nvfuser::Tensor* arg1, \ nvfuser::Tensor* arg2, \ nvfuser::Scalar* arg3) -> nvfuser::Tensor* { \ nvfuser::Tensor* output = self.fusion_definition->defineTensor(); \ self.fusion_definition->defineRecord(new nvfuser::OpRecord< \ NvfTensorView*, \ NvfTensorView*, \ NvfTensorView*, \ NvfVal*>( \ {arg1->index, arg2->index, arg3->index}, \ {output->index}, \ static_cast< \ NvfTensorView* (*)(NvfTensorView*, NvfTensorView*, NvfVal*)>( \ torch::jit::fuser::cuda::op_name))); \ return output; \ }, \ py::return_value_policy::reference); \ nvf_ops.def( \ op_str, \ [](nvfuser::FusionDefinition::Operators& self, \ nvfuser::Tensor* arg1, \ nvfuser::Scalar* arg2, \ nvfuser::Scalar* arg3) -> nvfuser::Tensor* { \ nvfuser::Tensor* output = self.fusion_definition->defineTensor(); \ self.fusion_definition->defineRecord( \ new nvfuser:: \ OpRecord<NvfTensorView*, NvfTensorView*, NvfVal*, NvfVal*>( \ {arg1->index, arg2->index, arg3->index}, \ {output->index}, \ static_cast< \ NvfTensorView* (*)(NvfTensorView*, NvfVal*, NvfVal*)>( \ torch::jit::fuser::cuda::op_name))); \ return output; \ }, \ py::return_value_policy::reference); \ nvf_ops.def( \ op_str, \ [](nvfuser::FusionDefinition::Operators& self, \ nvfuser::Scalar* arg1, \ nvfuser::Tensor* arg2, \ nvfuser::Scalar* arg3) -> nvfuser::Tensor* { \ nvfuser::Tensor* output = self.fusion_definition->defineTensor(); \ self.fusion_definition->defineRecord( \ new nvfuser:: \ OpRecord<NvfTensorView*, NvfVal*, NvfTensorView*, NvfVal*>( \ {arg1->index, arg2->index, arg3->index}, \ {output->index}, \ static_cast< \ NvfTensorView* (*)(NvfVal*, NvfTensorView*, NvfVal*)>( \ torch::jit::fuser::cuda::op_name))); \ return output; \ }, \ py::return_value_policy::reference); \ nvf_ops.def( \ op_str, \ [](nvfuser::FusionDefinition::Operators& self, \ nvfuser::Scalar* arg1, \ nvfuser::Scalar* arg2, \ nvfuser::Scalar* arg3) -> nvfuser::Scalar* { \ nvfuser::Scalar* output = self.fusion_definition->defineScalar(); \ self.fusion_definition->defineRecord( \ new nvfuser::OpRecord<NvfVal*, NvfVal*, NvfVal*, NvfVal*>( \ {arg1->index, arg2->index, arg3->index}, \ {output->index}, \ static_cast<NvfVal* (*)(NvfVal*, NvfVal*, NvfVal*)>( \ torch::jit::fuser::cuda::op_name))); \ return output; \ }, \ py::return_value_policy::reference); NVFUSER_PYTHON_BINDING_BINARY_WITH_ALPHA_OP("add_alpha", add_alpha) NVFUSER_PYTHON_BINDING_BINARY_WITH_ALPHA_OP("sub_alpha", sub_alpha) #undef NVFUSER_PYTHON_BINDING_BINARY_WITH_ALPHA_OP #define NVFUSER_PYTHON_BINDING_TERNARY_OP(op_str, op_name) \ nvf_ops.def( \ op_str, \ [](nvfuser::FusionDefinition::Operators& self, \ nvfuser::Scalar* arg1, \ nvfuser::Scalar* arg2, \ nvfuser::Scalar* arg3) -> nvfuser::Scalar* { \ nvfuser::Scalar* output = self.fusion_definition->defineScalar(); \ self.fusion_definition->defineRecord( \ new nvfuser::OpRecord<NvfVal*, NvfVal*, NvfVal*, NvfVal*>( \ {arg1->index, arg2->index, arg3->index}, \ {output->index}, \ static_cast<NvfVal* (*)(NvfVal*, NvfVal*, NvfVal*)>( \ torch::jit::fuser::cuda::op_name))); \ return output; \ }, \ py::return_value_policy::reference); \ nvf_ops.def( \ op_str, \ [](nvfuser::FusionDefinition::Operators& self, \ nvfuser::Tensor* arg1, \ nvfuser::Tensor* arg2, \ nvfuser::Tensor* arg3) -> nvfuser::Tensor* { \ nvfuser::Tensor* output = self.fusion_definition->defineTensor(); \ self.fusion_definition->defineRecord(new nvfuser::OpRecord< \ NvfTensorView*, \ NvfTensorView*, \ NvfTensorView*, \ NvfTensorView*>( \ {arg1->index, arg2->index, arg3->index}, \ {output->index}, \ static_cast< \ NvfTensorView* (*)(NvfTensorView*, NvfTensorView*, NvfTensorView*)>( \ torch::jit::fuser::cuda::op_name))); \ return output; \ }, \ py::return_value_policy::reference); \ nvf_ops.def( \ op_str, \ [](nvfuser::FusionDefinition::Operators& self, \ nvfuser::Tensor* arg1, \ nvfuser::Tensor* arg2, \ nvfuser::Scalar* arg3) -> nvfuser::Tensor* { \ nvfuser::Tensor* output = self.fusion_definition->defineTensor(); \ self.fusion_definition->defineRecord(new nvfuser::OpRecord< \ NvfTensorView*, \ NvfTensorView*, \ NvfTensorView*, \ NvfVal*>( \ {arg1->index, arg2->index, arg3->index}, \ {output->index}, \ static_cast< \ NvfTensorView* (*)(NvfTensorView*, NvfTensorView*, NvfVal*)>( \ torch::jit::fuser::cuda::op_name))); \ return output; \ }, \ py::return_value_policy::reference); \ nvf_ops.def( \ op_str, \ [](nvfuser::FusionDefinition::Operators& self, \ nvfuser::Tensor* arg1, \ nvfuser::Scalar* arg2, \ nvfuser::Tensor* arg3) -> nvfuser::Tensor* { \ nvfuser::Tensor* output = self.fusion_definition->defineTensor(); \ self.fusion_definition->defineRecord(new nvfuser::OpRecord< \ NvfTensorView*, \ NvfTensorView*, \ NvfVal*, \ NvfTensorView*>( \ {arg1->index, arg2->index, arg3->index}, \ {output->index}, \ static_cast< \ NvfTensorView* (*)(NvfTensorView*, NvfVal*, NvfTensorView*)>( \ torch::jit::fuser::cuda::op_name))); \ return output; \ }, \ py::return_value_policy::reference); \ nvf_ops.def( \ op_str, \ [](nvfuser::FusionDefinition::Operators& self, \ nvfuser::Scalar* arg1, \ nvfuser::Tensor* arg2, \ nvfuser::Tensor* arg3) -> nvfuser::Tensor* { \ nvfuser::Tensor* output = self.fusion_definition->defineTensor(); \ self.fusion_definition->defineRecord(new nvfuser::OpRecord< \ NvfTensorView*, \ NvfVal*, \ NvfTensorView*, \ NvfTensorView*>( \ {arg1->index, arg2->index, arg3->index}, \ {output->index}, \ static_cast< \ NvfTensorView* (*)(NvfVal*, NvfTensorView*, NvfTensorView*)>( \ torch::jit::fuser::cuda::op_name))); \ return output; \ }, \ py::return_value_policy::reference); \ nvf_ops.def( \ op_str, \ [](nvfuser::FusionDefinition::Operators& self, \ nvfuser::Scalar* arg1, \ nvfuser::Scalar* arg2, \ nvfuser::Tensor* arg3) -> nvfuser::Tensor* { \ nvfuser::Tensor* output = self.fusion_definition->defineTensor(); \ self.fusion_definition->defineRecord( \ new nvfuser:: \ OpRecord<NvfTensorView*, NvfVal*, NvfVal*, NvfTensorView*>( \ {arg1->index, arg2->index, arg3->index}, \ {output->index}, \ static_cast< \ NvfTensorView* (*)(NvfVal*, NvfVal*, NvfTensorView*)>( \ torch::jit::fuser::cuda::op_name))); \ return output; \ }, \ py::return_value_policy::reference); \ nvf_ops.def( \ op_str, \ [](nvfuser::FusionDefinition::Operators& self, \ nvfuser::Tensor* arg1, \ nvfuser::Scalar* arg2, \ nvfuser::Scalar* arg3) -> nvfuser::Tensor* { \ nvfuser::Tensor* output = self.fusion_definition->defineTensor(); \ self.fusion_definition->defineRecord( \ new nvfuser:: \ OpRecord<NvfTensorView*, NvfTensorView*, NvfVal*, NvfVal*>( \ {arg1->index, arg2->index, arg3->index}, \ {output->index}, \ static_cast< \ NvfTensorView* (*)(NvfTensorView*, NvfVal*, NvfVal*)>( \ torch::jit::fuser::cuda::op_name))); \ return output; \ }, \ py::return_value_policy::reference); \ nvf_ops.def( \ op_str, \ [](nvfuser::FusionDefinition::Operators& self, \ nvfuser::Scalar* arg1, \ nvfuser::Tensor* arg2, \ nvfuser::Scalar* arg3) -> nvfuser::Tensor* { \ nvfuser::Tensor* output = self.fusion_definition->defineTensor(); \ self.fusion_definition->defineRecord( \ new nvfuser:: \ OpRecord<NvfTensorView*, NvfVal*, NvfTensorView*, NvfVal*>( \ {arg1->index, arg2->index, arg3->index}, \ {output->index}, \ static_cast< \ NvfTensorView* (*)(NvfVal*, NvfTensorView*, NvfVal*)>( \ torch::jit::fuser::cuda::op_name))); \ return output; \ }, \ py::return_value_policy::reference); NVFUSER_PYTHON_BINDING_TERNARY_OP("lerp", lerp) NVFUSER_PYTHON_BINDING_TERNARY_OP("where", where) #undef NVFUSER_PYTHON_BINDING_TERNARY_OP #define NVFUSER_PYTHON_BINDING_THRESHOLD_LIKE_OP(op_str, op_name) \ nvf_ops.def( \ op_str, \ [](nvfuser::FusionDefinition::Operators& self, \ nvfuser::Scalar* arg1, \ nvfuser::Scalar* arg2, \ nvfuser::Scalar* arg3) -> nvfuser::Scalar* { \ nvfuser::Scalar* output = self.fusion_definition->defineScalar(); \ self.fusion_definition->defineRecord( \ new nvfuser::OpRecord<NvfVal*, NvfVal*, NvfVal*, NvfVal*>( \ {arg1->index, arg2->index, arg3->index}, \ {output->index}, \ static_cast<NvfVal* (*)(NvfVal*, NvfVal*, NvfVal*)>( \ torch::jit::fuser::cuda::op_name))); \ return output; \ }, \ py::return_value_policy::reference); \ nvf_ops.def( \ op_str, \ [](nvfuser::FusionDefinition::Operators& self, \ nvfuser::Tensor* arg1, \ nvfuser::Scalar* arg2, \ nvfuser::Scalar* arg3) -> nvfuser::Tensor* { \ nvfuser::Tensor* output = self.fusion_definition->defineTensor(); \ self.fusion_definition->defineRecord( \ new nvfuser:: \ OpRecord<NvfTensorView*, NvfTensorView*, NvfVal*, NvfVal*>( \ {arg1->index, arg2->index, arg3->index}, \ {output->index}, \ static_cast< \ NvfTensorView* (*)(NvfTensorView*, NvfVal*, NvfVal*)>( \ torch::jit::fuser::cuda::op_name))); \ return output; \ }, \ py::return_value_policy::reference); NVFUSER_PYTHON_BINDING_THRESHOLD_LIKE_OP("clamp", clamp) NVFUSER_PYTHON_BINDING_THRESHOLD_LIKE_OP("threshold", threshold) #undef NVFUSER_PYTHON_BINDING_THRESHOLD_LIKE_OP #define NVFUSER_PYTHON_BINDING_TERNARY_WITH_ALPHA_OP(op_str, op_name) \ nvf_ops.def( \ op_str, \ [](nvfuser::FusionDefinition::Operators& self, \ nvfuser::Scalar* arg1, \ nvfuser::Scalar* arg2, \ nvfuser::Scalar* arg3, \ nvfuser::Scalar* arg4) -> nvfuser::Scalar* { \ nvfuser::Scalar* output = self.fusion_definition->defineScalar(); \ self.fusion_definition->defineRecord( \ new nvfuser:: \ OpRecord<NvfVal*, NvfVal*, NvfVal*, NvfVal*, NvfVal*>( \ {arg1->index, arg2->index, arg3->index, arg4->index}, \ {output->index}, \ static_cast< \ NvfVal* (*)(NvfVal*, NvfVal*, NvfVal*, NvfVal*)>( \ torch::jit::fuser::cuda::op_name))); \ return output; \ }, \ py::return_value_policy::reference); \ nvf_ops.def( \ op_str, \ [](nvfuser::FusionDefinition::Operators& self, \ nvfuser::Tensor* arg1, \ nvfuser::Tensor* arg2, \ nvfuser::Tensor* arg3, \ nvfuser::Scalar* arg4) -> nvfuser::Tensor* { \ nvfuser::Tensor* output = self.fusion_definition->defineTensor(); \ self.fusion_definition->defineRecord(new nvfuser::OpRecord< \ NvfTensorView*, \ NvfTensorView*, \ NvfTensorView*, \ NvfTensorView*, \ NvfTensorView*>( \ {arg1->index, arg2->index, arg3->index, arg4->index}, \ {output->index}, \ static_cast< \ NvfTensorView* (*)(NvfTensorView*, NvfTensorView*, NvfTensorView*, NvfVal*)>( \ torch::jit::fuser::cuda::op_name))); \ return output; \ }, \ py::return_value_policy::reference); \ nvf_ops.def( \ op_str, \ [](nvfuser::FusionDefinition::Operators& self, \ nvfuser::Tensor* arg1, \ nvfuser::Tensor* arg2, \ nvfuser::Scalar* arg3, \ nvfuser::Scalar* arg4) -> nvfuser::Tensor* { \ nvfuser::Tensor* output = self.fusion_definition->defineTensor(); \ self.fusion_definition->defineRecord(new nvfuser::OpRecord< \ NvfTensorView*, \ NvfTensorView*, \ NvfTensorView*, \ NvfVal*, \ NvfVal*>( \ {arg1->index, arg2->index, arg3->index, arg4->index}, \ {output->index}, \ static_cast< \ NvfTensorView* (*)(NvfTensorView*, NvfTensorView*, NvfVal*, NvfVal*)>( \ torch::jit::fuser::cuda::op_name))); \ return output; \ }, \ py::return_value_policy::reference); \ nvf_ops.def( \ op_str, \ [](nvfuser::FusionDefinition::Operators& self, \ nvfuser::Tensor* arg1, \ nvfuser::Scalar* arg2, \ nvfuser::Tensor* arg3, \ nvfuser::Scalar* arg4) -> nvfuser::Tensor* { \ nvfuser::Tensor* output = self.fusion_definition->defineTensor(); \ self.fusion_definition->defineRecord(new nvfuser::OpRecord< \ NvfTensorView*, \ NvfTensorView*, \ NvfVal*, \ NvfTensorView*, \ NvfVal*>( \ {arg1->index, arg2->index, arg3->index, arg4->index}, \ {output->index}, \ static_cast< \ NvfTensorView* (*)(NvfTensorView*, NvfVal*, NvfTensorView*, NvfVal*)>( \ torch::jit::fuser::cuda::op_name))); \ return output; \ }, \ py::return_value_policy::reference); \ nvf_ops.def( \ op_str, \ [](nvfuser::FusionDefinition::Operators& self, \ nvfuser::Scalar* arg1, \ nvfuser::Tensor* arg2, \ nvfuser::Tensor* arg3, \ nvfuser::Scalar* arg4) -> nvfuser::Tensor* { \ nvfuser::Tensor* output = self.fusion_definition->defineTensor(); \ self.fusion_definition->defineRecord(new nvfuser::OpRecord< \ NvfTensorView*, \ NvfVal*, \ NvfTensorView*, \ NvfTensorView*, \ NvfVal*>( \ {arg1->index, arg2->index, arg3->index, arg4->index}, \ {output->index}, \ static_cast< \ NvfTensorView* (*)(NvfVal*, NvfTensorView*, NvfTensorView*, NvfVal*)>( \ torch::jit::fuser::cuda::op_name))); \ return output; \ }, \ py::return_value_policy::reference); \ nvf_ops.def( \ op_str, \ [](nvfuser::FusionDefinition::Operators& self, \ nvfuser::Scalar* arg1, \ nvfuser::Scalar* arg2, \ nvfuser::Tensor* arg3, \ nvfuser::Scalar* arg4) -> nvfuser::Tensor* { \ nvfuser::Tensor* output = self.fusion_definition->defineTensor(); \ self.fusion_definition->defineRecord(new nvfuser::OpRecord< \ NvfTensorView*, \ NvfVal*, \ NvfVal*, \ NvfTensorView*, \ NvfVal*>( \ {arg1->index, arg2->index, arg3->index, arg4->index}, \ {output->index}, \ static_cast< \ NvfTensorView* (*)(NvfVal*, NvfVal*, NvfTensorView*, NvfVal*)>( \ torch::jit::fuser::cuda::op_name))); \ return output; \ }, \ py::return_value_policy::reference); \ nvf_ops.def( \ op_str, \ [](nvfuser::FusionDefinition::Operators& self, \ nvfuser::Tensor* arg1, \ nvfuser::Scalar* arg2, \ nvfuser::Scalar* arg3, \ nvfuser::Scalar* arg4) -> nvfuser::Tensor* { \ nvfuser::Tensor* output = self.fusion_definition->defineTensor(); \ self.fusion_definition->defineRecord(new nvfuser::OpRecord< \ NvfTensorView*, \ NvfTensorView*, \ NvfVal*, \ NvfVal*, \ NvfVal*>( \ {arg1->index, arg2->index, arg3->index, arg4->index}, \ {output->index}, \ static_cast< \ NvfTensorView* (*)(NvfTensorView*, NvfVal*, NvfVal*, NvfVal*)>( \ torch::jit::fuser::cuda::op_name))); \ return output; \ }, \ py::return_value_policy::reference); \ nvf_ops.def( \ op_str, \ [](nvfuser::FusionDefinition::Operators& self, \ nvfuser::Scalar* arg1, \ nvfuser::Tensor* arg2, \ nvfuser::Scalar* arg3, \ nvfuser::Scalar* arg4) -> nvfuser::Tensor* { \ nvfuser::Tensor* output = self.fusion_definition->defineTensor(); \ self.fusion_definition->defineRecord(new nvfuser::OpRecord< \ NvfTensorView*, \ NvfVal*, \ NvfTensorView*, \ NvfVal*, \ NvfVal*>( \ {arg1->index, arg2->index, arg3->index, arg4->index}, \ {output->index}, \ static_cast< \ NvfTensorView* (*)(NvfVal*, NvfTensorView*, NvfVal*, NvfVal*)>( \ torch::jit::fuser::cuda::op_name))); \ return output; \ }, \ py::return_value_policy::reference); NVFUSER_PYTHON_BINDING_TERNARY_WITH_ALPHA_OP("addcmul", addcmul) #undef NVFUSER_PYTHON_BINDING_TERNARY_WITH_ALPHA_OP #define NVFUSER_PYTHON_BINDING_REDUCTION_OP(op_str, op_name) \ nvf_ops.def( \ op_str, \ [](nvfuser::FusionDefinition::Operators& self, \ nvfuser::Tensor* arg, \ const std::vector<int>& axes, \ bool keep_dim, \ NvfDataType dtype) -> nvfuser::Tensor* { \ nvfuser::Tensor* output = self.fusion_definition->defineTensor(); \ self.fusion_definition->defineRecord(new nvfuser::ReductionOpRecord( \ {arg->index}, \ {output->index}, \ torch::jit::fuser::cuda::op_name, \ axes, \ keep_dim, \ dtype)); \ return output; \ }, \ py::arg("arg"), \ py::arg("axes"), \ py::arg("keep_dim"), \ py::arg("dtype") = torch::jit::fuser::cuda::DataType::Null, \ py::return_value_policy::reference); NVFUSER_PYTHON_BINDING_REDUCTION_OP("sum", sum) NVFUSER_PYTHON_BINDING_REDUCTION_OP("max", max) NVFUSER_PYTHON_BINDING_REDUCTION_OP("min", min) #undef NVFUSER_PYTHON_BINDING_REDUCTION_OP #define NVFUSER_PYTHON_BINDING_CAST_OP(op_str, op_name) \ nvf_ops.def( \ op_str, \ [](nvfuser::FusionDefinition::Operators& self, \ nvfuser::Tensor* arg, \ NvfDataType dtype) -> nvfuser::Tensor* { \ nvfuser::Tensor* output = self.fusion_definition->defineTensor(); \ self.fusion_definition->defineRecord( \ new nvfuser::CastOpRecord<NvfTensorView*, NvfTensorView*>( \ {arg->index}, \ {output->index}, \ static_cast<NvfTensorView* (*)(NvfDataType, NvfTensorView*)>( \ torch::jit::fuser::cuda::op_name), \ dtype)); \ return output; \ }, \ py::return_value_policy::reference); \ nvf_ops.def( \ op_str, \ [](nvfuser::FusionDefinition::Operators& self, \ nvfuser::Scalar* arg, \ NvfDataType dtype) -> nvfuser::Scalar* { \ nvfuser::Scalar* output = self.fusion_definition->defineScalar(); \ self.fusion_definition->defineRecord( \ new nvfuser::CastOpRecord<NvfVal*, NvfVal*>( \ {arg->index}, \ {output->index}, \ static_cast<NvfVal* (*)(NvfDataType, NvfVal*)>( \ torch::jit::fuser::cuda::op_name), \ dtype)); \ return output; \ }, \ py::return_value_policy::reference); NVFUSER_PYTHON_BINDING_CAST_OP("cast", castOp) #undef NVFUSER_PYTHON_BINDING_CAST_OP nvf_ops.def( "var", [](nvfuser::FusionDefinition::Operators& self, nvfuser::Tensor* arg, std::vector<int>& axes, int64_t correction, bool keepdim) -> nvfuser::Tensor* { nvfuser::Tensor* output = self.fusion_definition->defineTensor(); self.fusion_definition->defineRecord(new nvfuser::VarianceOpRecord( {arg->index}, {output->index}, axes, correction, keepdim)); return output; }, py::return_value_policy::reference); nvf_ops.def( "broadcast_in_dim", [](nvfuser::FusionDefinition::Operators& self, nvfuser::Tensor* arg, std::vector<int64_t>& output_shape, std::vector<int64_t>& broadcast_dims) -> nvfuser::Tensor* { nvfuser::Tensor* output = self.fusion_definition->defineTensor(); self.fusion_definition->defineRecord(new nvfuser::BroadcastOpRecord( {arg->index}, {output->index}, output_shape, broadcast_dims)); return output; }, py::return_value_policy::reference); } } // namespace jit } // namespace torch #else namespace torch { namespace jit { void initNvFuserPythonBindings(PyObject* module) {} } // namespace jit } // namespace torch #endif // USE_CUDA
[ "pytorchmergebot@users.noreply.github.com" ]
pytorchmergebot@users.noreply.github.com
28bd771699a1f14fc127e0cb5984f14e278b2e39
aee5753c5e49eb6e6778a539ddea204515fc3828
/main.cpp
2f4f5c6da3d5ae238f0e01c2fd561f90ad2f2483
[]
no_license
Andrey8/GeometryBuilder
21d85eb3353be92055c7183b79be350ec5dfd118
611d38fa31d57ededa49bb2a9aa5771acf8e1c16
refs/heads/master
2022-11-09T05:13:22.231901
2020-06-12T10:23:03
2020-06-12T10:23:03
268,571,203
0
0
null
null
null
null
UTF-8
C++
false
false
332
cpp
#include "Widgets/mainwindow.h" #include "polygonalgorithms.h" #include <QApplication> //#include <QDesktopWidget> //#include <QRect> #include <QDebug> int main( int argc, char * argv[] ) { //PolygonAlgorithms::Tests(); //Math::Tests(); QApplication app( argc, argv ); MainWindow mw; mw.show(); return app.exec(); }
[ "andrey.drobah.and@mail.ru" ]
andrey.drobah.and@mail.ru
a5db59e1790ed665d940eb4c09938ab5d4fe3f9c
1866d4046ced94b01e953bea65b1c361557fc9ea
/zkj_stl_alloc.h
58ebbd3f3c4da5f369cb8480891b7d1311490448
[]
no_license
zhuokaijia/zkj_stl
0693d1df8773ba58de2a4aba646820acc44bfafe
c6eb4116db07b216c0198c7591b1c9c04882b309
refs/heads/master
2021-01-17T13:01:02.367095
2016-06-14T16:19:33
2016-06-14T16:19:33
57,869,957
1
0
null
null
null
null
UTF-8
C++
false
false
2,715
h
/* NOTE:This is an internal header file,included by other header file. * you should not attempt to use it directly */ #ifndef _ZKJ_STL_ALLOC_H_ #define _ZKJ_STL_ALLOC_H_ #include <cassert> #include <cstdlib> #include <cstdio> #include <cstring> //for memcpy namespace zkj_stl{ template<class T,class Alloc=fl_malloc> class simple_alloc{ static T* allocate(size_t _n){ return (0 == _n) ? 0 : static_cast<T*>(Alloc::allocate(n*sizeof(T)); } static T* allocate(){ return (0 == _n) ? 0 : static_cast<T*>(Alloc::allocate(sizeof(T)); } static void deallocate(T* _p, size_t _n){ if (0 != _n){ Alloc::deallocate(_p, _n*sizeof(T)); } } static void deallocate(T*_p){ Alloc::deallocate(_p, sizeof(T)); } }; const int ALIGN = 8; const int MAX_BYTES = 128; const int NFLISTS = MAX_BYTES / ALIGN; // if the client request an object of size > MAX_BYTES // the object will be obtained directly by malloc class general_alloc{ public: static void* allocate(size_t _n){ void* res = malloc(_n); assert(res != nullptr); return res; } static void* deallocate(void* _p, size_t){ free(_p); _p = nullptr; } static void* reallocate(void* _p, size_t,size_t _n){ void* res = realloc(_p, _n); assert(res != nullptr); return res; } }; // if the client request an object of size <= MAX_BYTES // the object will be obtained by fl_malloc class fl_malloc{ //free-list-malloc private: static inline size_t round_up(size_t _n){ return (_n + ALIGN - 1)& (~(ALIGN - 1)); } union obj{ union obj* fl_link; char data[1]; }; // free-lists static obj* free_list[NFLISTS]; // from 0 to NFLISTS - 1 static size_t fl_index(size_t _n){ return (_n + ALIGN - 1) / ALIGN - 1; } static void* refill(size_t _n); // _nobjs pass by reference static char* chunk_alloc(size_t _n, size_t& _nobjs); //change in chunk_alloc function static char* head_free; static char* end_free; public: static void* allocate(size_t _n); static void deallocate(void* _p, size_t _n); static void* reallocate(void* _P, size_t _o,size_t _n); }; }//namespace zkj_stl //mode:c++ #endif
[ "946114150@qq.com" ]
946114150@qq.com
54ccbfc2d94718b6861a40f7bf64507e1bebfc1b
d472b26153e913bcf74e5a7582bb14c66c9f9299
/src/server.cpp
9fe21f414a13e6a9b988580dc76e63dd209fd27b
[]
no_license
mrnsapple/Zia
73c7b4bffc28157fa6424f02945f279de8312e0b
d08c35e7853bfdd75aeab5c2148d37df2912e5bb
refs/heads/master
2022-12-16T04:16:14.522200
2020-09-21T17:19:42
2020-09-21T17:19:42
297,409,775
0
0
null
null
null
null
UTF-8
C++
false
false
419
cpp
/* ** EPITECH PROJECT, 2020 ** CPP_zia_2019 ** File description: ** server */ #include "../include/server.hpp" void create_session(t_socket client, int server_port) { session s(client, server_port); s.do_read(); } void server::continous_listen() { t_socket client; while (1) { client = socket_.do_accept(); std::thread(&create_session, client, socket_.local_port()).detach(); } }
[ "oriol.manzano@epitech.eu" ]
oriol.manzano@epitech.eu
795643d29c3ac4ed7b5f19e353ed6ab8cd9c986c
443de09f7b9722041baea0822b1c29b182d052c9
/analyzers/ZeeTiming.h
7599a528cc079b4586fdbcd691d4b816bddba685
[]
no_license
dgawerc/RazorAnalyzer
3fdff4b0c46f2a1660c2440af72e9022b56048e5
80d58f00371286defbf0ef28d760d62cb45df5d3
refs/heads/master
2021-06-30T06:45:56.434771
2017-09-11T15:45:22
2017-09-11T15:45:22
103,127,832
0
0
null
2017-09-11T12:44:32
2017-09-11T11:31:34
C++
UTF-8
C++
false
false
914
h
#ifndef DEF_ZeeTiming #define DEF_ZeeTiming #include "RazorAnalyzer.h" class ZeeTiming: public RazorAnalyzer { public: uint start_run_tmp; uint end_run_tmp; uint start_time_tmp; uint end_time_tmp; vector <float> *IC_time_all; vector <float> *rms_G12_all; vector <float> *rms_G1_all; vector <float> *rms_G6_all; vector <int> *detID_all; const double N_EB = 38.1; //ns const double C_EB = 0.2439; //ns ZeeTiming(TTree *tree=0): RazorAnalyzer(tree) { } void Analyze(bool isData, int option, string outputFileName, string label); float getTimeCalibConstant(TTree *tree, vector <uint> & start_run, vector <uint> & end_run, uint run, uint detID); float getPedestalNoise(TTree *tree, vector <uint> & start_run, vector <uint> & end_run, uint run, uint detID); float getADCToGeV( uint run, int isEBOrEE); }; #endif
[ "Si.Xie@cern.ch" ]
Si.Xie@cern.ch
0f68d9ac99d01c47e3ecd5aae0f135b59d465c12
8c72abc8fba1aceb32264315e86718cb347e52b2
/Sortera/Sortera/IStack.h
ac40f733ece8288d94b32943f5a1152231d2ad6b
[]
no_license
AweZen/Skola
d6616a5963e7b2f8e69ab9686227e0490f8b8516
694f829d6b2119dd58e9f6fbdc8cbd3871c64f30
refs/heads/master
2021-04-27T09:34:29.274726
2018-03-02T07:22:24
2018-03-02T07:22:24
122,517,786
0
0
null
null
null
null
UTF-8
C++
false
false
238
h
#pragma once template<typename T> class IStack { public: virtual ~IStack() = 0 {}; virtual void push(const T& element) = 0; virtual T pop() noexcept(false) = 0; virtual T peek()const throw(...)= 0; virtual bool isEmpty()const = 0; };
[ "erik.eli@live.se" ]
erik.eli@live.se
5376509824aaa4401cb3ea808327685bfc308762
4a78fa24d1f5416f0a3b41556b3a11bd372b15d1
/utility/style.cpp
8b9f3f01861b786eef5a5c32d18b9e6c8ff4dca3
[]
no_license
ToniPlays/VideoEditor
95778f964ef3572f53ec5fcde3b7983c0c41e402
a9adc01f9580af70d38a4c6461a8031eb998acad
refs/heads/master
2021-01-14T18:36:09.707863
2020-03-01T11:53:21
2020-03-01T11:53:21
242,714,535
0
0
null
null
null
null
UTF-8
C++
false
false
300
cpp
#include "style.h" QString Style::Text() { return QString::fromUtf8("color: #B9B9B9"); } QString Style::Panel() { return QString::fromUtf8("background-color: rgb(35, 35, 35);"); } QString Style::Background() { return QString::fromUtf8("background-color: rgb(22, 22, 22);"); }
[ "noreply@github.com" ]
ToniPlays.noreply@github.com
684c2f159b5de11c4f22f88cf97ad7c2b2ba1449
e23cf10c9dee3c854c58e06dae5d9d024aff6ac5
/2019/s2/oop/workshop-12/hunter.cpp
bc162af9d341042a19c3df37b66f0361f302fa95
[]
no_license
bkoh1782291/bkoh1782291
fbdb2ac23eb30359e1cd29bd7b8582766ce3b079
ae328c1270c88f4adf5b0cc9ac1a9bcefc4cb783
refs/heads/main
2023-06-23T09:43:22.109038
2023-06-09T13:43:19
2023-06-09T13:43:19
350,210,138
0
0
null
null
null
null
UTF-8
C++
false
false
355
cpp
#include <iostream> #include <string> #include "hunter.h" using namespace std; int hunter::nextID = 1000; hunter::hunter(string n, int v) : animal(n, v){ name = n; volume = v; id = nextID++; } string hunter::get_name(){ return "Hunter: " + name; } int hunter::get_kills(){ return kills; } void hunter::set_kills(int hKills){ kills = hKills; }
[ "kohbrian88@gmail.com" ]
kohbrian88@gmail.com
f81495b093c57736c3ddd4c61328e1f7cc719014
ebc00ddf4c8c5f5076471e8b8d56c2b634c51230
/src/hash.h
7fce72ed7b01ff458a9d98e09e95327113a045f8
[ "MIT" ]
permissive
BlockMechanic/rain
584a9e245cfb7ab5fb1add97b699b86833bfbc5b
e8818b75240ff9277b0d14d38769378f05d0b525
refs/heads/master
2021-07-03T03:48:53.977665
2021-03-04T01:28:20
2021-03-04T01:28:20
228,412,343
0
0
MIT
2019-12-16T15:03:28
2019-12-16T15:03:27
null
UTF-8
C++
false
false
10,074
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2020 The Rain Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef RAIN_HASH_H #define RAIN_HASH_H #include <crypto/common.h> #include <crypto/ripemd160.h> #include <crypto/sha256.h> #include <prevector.h> #include <serialize.h> #include <uint256.h> #include <version.h> #include <vector> typedef uint256 ChainCode; /** A hasher class for Rain's 256-bit hash (double SHA-256). */ class CHash256 { private: CSHA256 sha; public: static const size_t OUTPUT_SIZE = CSHA256::OUTPUT_SIZE; void Finalize(unsigned char hash[OUTPUT_SIZE]) { unsigned char buf[CSHA256::OUTPUT_SIZE]; sha.Finalize(buf); sha.Reset().Write(buf, CSHA256::OUTPUT_SIZE).Finalize(hash); } CHash256& Write(const unsigned char *data, size_t len) { sha.Write(data, len); return *this; } CHash256& Reset() { sha.Reset(); return *this; } }; /** A hasher class for Rain's 160-bit hash (SHA-256 + RIPEMD-160). */ class CHash160 { private: CSHA256 sha; public: static const size_t OUTPUT_SIZE = CRIPEMD160::OUTPUT_SIZE; void Finalize(unsigned char hash[OUTPUT_SIZE]) { unsigned char buf[CSHA256::OUTPUT_SIZE]; sha.Finalize(buf); CRIPEMD160().Write(buf, CSHA256::OUTPUT_SIZE).Finalize(hash); } CHash160& Write(const unsigned char *data, size_t len) { sha.Write(data, len); return *this; } CHash160& Reset() { sha.Reset(); return *this; } }; /** Compute the 256-bit hash of an object. */ template<typename T1> inline uint256 Hash(const T1 pbegin, const T1 pend) { static const unsigned char pblank[1] = {}; uint256 result; CHash256().Write(pbegin == pend ? pblank : (const unsigned char*)&pbegin[0], (pend - pbegin) * sizeof(pbegin[0])) .Finalize((unsigned char*)&result); return result; } /** Compute the 256-bit hash of the concatenation of two objects. */ template<typename T1, typename T2> inline uint256 Hash(const T1 p1begin, const T1 p1end, const T2 p2begin, const T2 p2end) { static const unsigned char pblank[1] = {}; uint256 result; CHash256().Write(p1begin == p1end ? pblank : (const unsigned char*)&p1begin[0], (p1end - p1begin) * sizeof(p1begin[0])) .Write(p2begin == p2end ? pblank : (const unsigned char*)&p2begin[0], (p2end - p2begin) * sizeof(p2begin[0])) .Finalize((unsigned char*)&result); return result; } /** Compute the 256-bit hash of the concatenation of three objects. */ template<typename T1, typename T2, typename T3> inline uint256 Hash(const T1 p1begin, const T1 p1end, const T2 p2begin, const T2 p2end, const T3 p3begin, const T3 p3end) { static const unsigned char pblank[1] = {}; uint256 result; CHash256().Write(p1begin == p1end ? pblank : (const unsigned char*)&p1begin[0], (p1end - p1begin) * sizeof(p1begin[0])) .Write(p2begin == p2end ? pblank : (const unsigned char*)&p2begin[0], (p2end - p2begin) * sizeof(p2begin[0])) .Write(p3begin == p3end ? pblank : (const unsigned char*)&p3begin[0], (p3end - p3begin) * sizeof(p3begin[0])) .Finalize((unsigned char*)&result); return result; } /** Compute the 256-bit hash of the concatenation of three objects. */ template<typename T1, typename T2, typename T3, typename T4> inline uint256 Hash(const T1 p1begin, const T1 p1end, const T2 p2begin, const T2 p2end, const T3 p3begin, const T3 p3end, const T4 p4begin, const T4 p4end) { static const unsigned char pblank[1] = {}; uint256 result; CHash256().Write(p1begin == p1end ? pblank : (const unsigned char*)&p1begin[0], (p1end - p1begin) * sizeof(p1begin[0])) .Write(p2begin == p2end ? pblank : (const unsigned char*)&p2begin[0], (p2end - p2begin) * sizeof(p2begin[0])) .Write(p3begin == p3end ? pblank : (const unsigned char*)&p3begin[0], (p3end - p3begin) * sizeof(p3begin[0])) .Write(p4begin == p4end ? pblank : (const unsigned char*)&p4begin[0], (p4end - p4begin) * sizeof(p4begin[0])) .Finalize((unsigned char*)&result); return result; } /** Compute the 256-bit hash of the concatenation of three objects. */ template<typename T1, typename T2, typename T3, typename T4, typename T5> inline uint256 Hash(const T1 p1begin, const T1 p1end, const T2 p2begin, const T2 p2end, const T3 p3begin, const T3 p3end, const T4 p4begin, const T4 p4end, const T5 p5begin, const T5 p5end) { static const unsigned char pblank[1] = {}; uint256 result; CHash256().Write(p1begin == p1end ? pblank : (const unsigned char*)&p1begin[0], (p1end - p1begin) * sizeof(p1begin[0])) .Write(p2begin == p2end ? pblank : (const unsigned char*)&p2begin[0], (p2end - p2begin) * sizeof(p2begin[0])) .Write(p3begin == p3end ? pblank : (const unsigned char*)&p3begin[0], (p3end - p3begin) * sizeof(p3begin[0])) .Write(p4begin == p4end ? pblank : (const unsigned char*)&p4begin[0], (p4end - p4begin) * sizeof(p4begin[0])) .Write(p5begin == p5end ? pblank : (const unsigned char*)&p5begin[0], (p5end - p5begin) * sizeof(p5begin[0])) .Finalize((unsigned char*)&result); return result; } /** Compute the 256-bit hash of the concatenation of three objects. */ template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6> inline uint256 Hash(const T1 p1begin, const T1 p1end, const T2 p2begin, const T2 p2end, const T3 p3begin, const T3 p3end, const T4 p4begin, const T4 p4end, const T5 p5begin, const T5 p5end, const T6 p6begin, const T6 p6end) { static const unsigned char pblank[1] = {}; uint256 result; CHash256().Write(p1begin == p1end ? pblank : (const unsigned char*)&p1begin[0], (p1end - p1begin) * sizeof(p1begin[0])) .Write(p2begin == p2end ? pblank : (const unsigned char*)&p2begin[0], (p2end - p2begin) * sizeof(p2begin[0])) .Write(p3begin == p3end ? pblank : (const unsigned char*)&p3begin[0], (p3end - p3begin) * sizeof(p3begin[0])) .Write(p4begin == p4end ? pblank : (const unsigned char*)&p4begin[0], (p4end - p4begin) * sizeof(p4begin[0])) .Write(p5begin == p5end ? pblank : (const unsigned char*)&p5begin[0], (p5end - p5begin) * sizeof(p5begin[0])) .Write(p6begin == p6end ? pblank : (const unsigned char*)&p6begin[0], (p6end - p6begin) * sizeof(p6begin[0])) .Finalize((unsigned char*)&result); return result; } /** Compute the 160-bit hash an object. */ template<typename T1> inline uint160 Hash160(const T1 pbegin, const T1 pend) { static unsigned char pblank[1] = {}; uint160 result; CHash160().Write(pbegin == pend ? pblank : (const unsigned char*)&pbegin[0], (pend - pbegin) * sizeof(pbegin[0])) .Finalize((unsigned char*)&result); return result; } /** Compute the 160-bit hash of a vector. */ inline uint160 Hash160(const std::vector<unsigned char>& vch) { return Hash160(vch.begin(), vch.end()); } /** Compute the 160-bit hash of a vector. */ template<unsigned int N> inline uint160 Hash160(const prevector<N, unsigned char>& vch) { return Hash160(vch.begin(), vch.end()); } /** A writer stream (for serialization) that computes a 256-bit hash. */ class CHashWriter { private: CHash256 ctx; const int nType; const int nVersion; public: CHashWriter(int nTypeIn, int nVersionIn) : nType(nTypeIn), nVersion(nVersionIn) {} int GetType() const { return nType; } int GetVersion() const { return nVersion; } void write(const char *pch, size_t size) { ctx.Write((const unsigned char*)pch, size); } // invalidates the object uint256 GetHash() { uint256 result; ctx.Finalize((unsigned char*)&result); return result; } /** * Returns the first 64 bits from the resulting hash. */ inline uint64_t GetCheapHash() { unsigned char result[CHash256::OUTPUT_SIZE]; ctx.Finalize(result); return ReadLE64(result); } template<typename T> CHashWriter& operator<<(const T& obj) { // Serialize to this stream ::Serialize(*this, obj); return (*this); } }; /** Reads data from an underlying stream, while hashing the read data. */ template<typename Source> class CHashVerifier : public CHashWriter { private: Source* source; public: explicit CHashVerifier(Source* source_) : CHashWriter(source_->GetType(), source_->GetVersion()), source(source_) {} void read(char* pch, size_t nSize) { source->read(pch, nSize); this->write(pch, nSize); } void ignore(size_t nSize) { char data[1024]; while (nSize > 0) { size_t now = std::min<size_t>(nSize, 1024); read(data, now); nSize -= now; } } template<typename T> CHashVerifier<Source>& operator>>(T&& obj) { // Unserialize from this stream ::Unserialize(*this, obj); return (*this); } }; /** Compute the 256-bit hash of an object's serialization. */ template<typename T> uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=PROTOCOL_VERSION) { CHashWriter ss(nType, nVersion); ss << obj; return ss.GetHash(); } unsigned int MurmurHash3(unsigned int nHashSeed, const std::vector<unsigned char>& vDataToHash); void BIP32Hash(const ChainCode &chainCode, unsigned int nChild, unsigned char header, const unsigned char data[32], unsigned char output[64]); int univHash(const uint256 &x); #endif // RAIN_HASH_H
[ "blockmecha@gmail.com" ]
blockmecha@gmail.com
c176e44338ccfe04c4a31c89e8d5196a09fd7370
f83ef53177180ebfeb5a3e230aa29794f52ce1fc
/ACE/ACE_wrappers/TAO/orbsvcs/orbsvcs/SSLIOP/SSLIOP_Endpoint.inl
05f856207cb8e2cc5e63a338291567402374789c
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-sun-iiop" ]
permissive
msrLi/portingSources
fe7528b3fd08eed4a1b41383c88ee5c09c2294ef
57d561730ab27804a3172b33807f2bffbc9e52ae
refs/heads/master
2021-07-08T01:22:29.604203
2019-07-10T13:07:06
2019-07-10T13:07:06
196,183,165
2
1
Apache-2.0
2020-10-13T14:30:53
2019-07-10T10:16:46
null
UTF-8
C++
false
false
1,362
inl
// -*- C++ -*- TAO_BEGIN_VERSIONED_NAMESPACE_DECL ACE_INLINE TAO_IIOP_Endpoint * TAO_SSLIOP_Endpoint::iiop_endpoint (void) const { return this->iiop_endpoint_; } ACE_INLINE void TAO_SSLIOP_Endpoint::iiop_endpoint (TAO_IIOP_Endpoint *iiop_endpoint, bool destroy) { if (iiop_endpoint != 0) { TAO_IIOP_Endpoint *new_endpoint = 0; if (destroy) { TAO_Endpoint *endpoint = iiop_endpoint->duplicate (); new_endpoint = dynamic_cast<TAO_IIOP_Endpoint *> (endpoint); } else new_endpoint = iiop_endpoint; if (this->destroy_iiop_endpoint_) delete this->iiop_endpoint_; this->iiop_endpoint_ = new_endpoint; this->destroy_iiop_endpoint_ = destroy; } } ACE_INLINE const ::SSLIOP::SSL & TAO_SSLIOP_Endpoint::ssl_component (void) const { return this->ssl_component_; } ACE_INLINE ::Security::QOP TAO_SSLIOP_Endpoint::qop (void) const { return this->qop_; } ACE_INLINE ::Security::EstablishTrust TAO_SSLIOP_Endpoint::trust (void) const { return this->trust_; } ACE_INLINE TAO::SSLIOP::OwnCredentials * TAO_SSLIOP_Endpoint::credentials (void) const { return this->credentials_.in (); } ACE_INLINE int TAO_SSLIOP_Endpoint::credentials_set (void) const { return this->credentials_set_; } TAO_END_VERSIONED_NAMESPACE_DECL
[ "lihuibin705@163.com" ]
lihuibin705@163.com
212886a605f0e72bdfc309caf259fc658cfac109
679b6414bc832e81edb7ebf16bb0d7b779c40005
/test.cpp
b7a77a077c0d4711306bef971f10900946096ed2
[]
no_license
tfiedor/memory-repo
fd368281e7de3d34115f1bdbfefc0e52d2e812fd
74288675e4074f1ad5bbb0d3b3253911ab42267a
refs/heads/master
2021-01-22T23:48:33.453444
2017-03-24T07:13:36
2017-03-24T07:13:36
85,670,389
0
0
null
null
null
null
UTF-8
C++
false
false
770
cpp
/* * File: test.cpp * Project: Library for Profiling and Visualization of Memory Consumption * of C/C++ Programs, Bachelor's thesis * Date: 29.2.2017 * Author: Podola Radim, xpodol06@stud.fit.vutbr.cz * Description: Testing file for injected malloc.so library. TODO: Test for all allocation functions, use assert? */ #include <iostream> // std::cout #include <new> // ::operator new struct MyClass { int data[100]; MyClass(){(int*)calloc(1, sizeof(int)); } }; int main () { MyClass* p1 = new MyClass(); // allocates memory by calling: operator new (sizeof(MyClass)) // and then constructs an object at the newly allocated space int *i = new int; delete(i); delete(p1); return 0; }
[ "ifiedortom@fit.vutbr.cz" ]
ifiedortom@fit.vutbr.cz
bb5ae7afdc4e5da4d6282ecbfd647bf7b5d72454
7395e68094700c42c942f978e1d9152054cfd345
/REEEEEE/main.cpp
31fed0a2b1305d402607016ab183d7e35d28d1bb
[]
no_license
Cenaaa/CPSC462-Hotel-Project-
86ddcac2b8d690988b9772988edbcaabc44dfc2f
a66fae636a654b300a005aab86cef58758b360e4
refs/heads/master
2020-04-24T13:14:19.180582
2019-05-10T02:49:28
2019-05-10T02:49:28
171,980,549
0
0
null
2019-05-06T00:38:59
2019-02-22T02:29:55
HTML
UTF-8
C++
false
false
4,302
cpp
// // main.cpp // 462_Hotel // // Created by Alex Liao on 2019/4/28. // Copyright © 2019年 Alex Liao. All rights reserved. #include <string> #include <fstream> #include <iostream> #include "User.h" #include "Profile.h" #include "payment_info.h" #include "DatabaseTree.h" #include "GuestAccount.h" #include "StayingGuest.h" #include "Registration.h" #include "Authentication.h" #include "room.h" #include "payment.h" #include "payment_info.h" #include "make_reservation.h" #include "check_reservation.h" #include "services.h" #include "housekeeping.h" //#include "Services.h" //#include "Cleaners.h" //#include "HouseKeeping.h" #include "KitchenController.h" using std::string; using std::cout; using std::cin; string site_features[] {"Quit", "Register", "Login", "Reservation", "Housekeeping", "Food Order", "Logout"}; void home_Menu(); /* CSUF 657-278-2011 800 N. State College Blvd. Fullerton, CA 92831 CSUF@csu.fullerton.edu 8 1234 */ int main(int argc, const char * argv[]) { int choice, usrID_Ref; Authentication auth; Registration acct_Register; GuestAccount registered; DatabaseTree<GuestAccount> account_DB; make_reservation mr; KitchenController kc; Services myService; HouseKeeping houseKeeping; staff staff1("john", " jojo"); staff staff2("rob", " ali"); do { GuestAccount new_acct; home_Menu(); cin >> choice; cin.ignore(); switch (choice) { case 1: // Create guest account if (auth.get_Status()) { cout << "You're logged-in. Please log-out to continue!\n\n"; auth.logout(); registered = NULL; } else { cout << "New Account Registration!\n"; acct_Register.registering(new_acct); if (-2 != new_acct.get_ID()) { if (acct_Register.update(account_DB, new_acct)) { if (-1 != (usrID_Ref = auth.registrationAutoLogin(new_acct, account_DB))) { registered = new_acct; /**/ new_acct = NULL; cout << "Registered & Logged-in\n\n"; } else { cout << "Registration failed!\n\n"; } } } } break; case 2: // TO log-in if (auth.get_Status()) { cout << "Already logged-in!\n\n"; } else { usrID_Ref = auth.login(account_DB, registered); if (-1 == usrID_Ref) { cout << "Login failed!\n\n"; } else { cout << "You're logged-in!\n\n"; } } break; case 3: if (auth.get_Status()) { // Reservation payment_info new_payment_info = mr.make_res(); registered.set_Payment_Info(new_payment_info); } else { cout << "Please login first!\n\n"; } break; case 4: if (auth.get_Status()) { vector<room> allRooms; check_reservation myreserv(1, 1, 1); allRooms = myreserv.send_roomlist(); staff staff1("john", " jojo"); staff staff2("rob", " ali"); staff myCleaner("", ""); HouseKeeping myService; Services obj; payment_info new_payment_info = registered.get_Payment_Info(); int rm = new_payment_info.get_room(); myService.request_To_Be_Cleaned(allRooms[rm - 1]); vector<room> notCleaned = myService.retNeedToBeCleanedVector(); obj.addCleaner(staff1); obj.addCleaner(staff2); myCleaner = obj.getCleaner(); obj.addCleaner(myCleaner); obj.sendCleaner(staff2); //obj.removeCleaner(staff2); } // Housekeeping else { cout << "Please login first!\n\n"; } break; case 5: if (auth.get_Status()) { payment_info new_payment_info = registered.get_Payment_Info(); int rm = new_payment_info.get_room(); kc.kitchenStuff(rm - 1); } // Food Order else { cout << "Please login first!\n\n"; } break; case 6: auth.logout(); break; case 0: auth.logout(); break; } } while (0 != choice); return 0; } void home_Menu() { cout << "Select one of the following features\n"; for (int ix = 0; ix < 7; ++ix) { cout << ix << ": " << site_features[ix] << endl; } cout << "Enter choice: "; }
[ "noreply@github.com" ]
Cenaaa.noreply@github.com
30a0a66d7d9be820994fd3edf989e0cca28856d8
58ef72f1d3bd0ce696506e49e620fd554e0faf63
/libzxplayer/src/main/cpp/common/WlQueue.h
507f04aae76fc71a80a0fd5e7b5c21dd727959e6
[]
no_license
KimHyoungChul/ffmpeg_Player_new
bcf6e8e61bd03183c0bea32cf920a22b26e91a26
0cb343d6d1fb5ec9a273902111054e0adec5c34b
refs/heads/master
2020-06-12T07:47:53.975997
2018-08-16T02:08:05
2018-08-16T02:08:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
902
h
// // Created by ywl on 2017-12-3. // #ifndef WLPLAYER_QUEUE_H #define WLPLAYER_QUEUE_H #include "queue" #include "../WlPlayStatus.h" extern "C" { #include <libavcodec/avcodec.h> #include "pthread.h" }; class WlQueue { public: std::queue<AVPacket*> queuePacket; std::queue<AVFrame*> queueFrame; pthread_mutex_t mutexFrame; pthread_cond_t condFrame; pthread_mutex_t mutexPacket; pthread_cond_t condPacket; WlPlayStatus *wlPlayStatus = NULL; public: WlQueue(WlPlayStatus *playStatus); ~WlQueue(); int putAvpacket(AVPacket *avPacket); int getAvpacket(AVPacket *avPacket); int clearAvpacket(); int clearToKeyFrame(); int putAvframe(AVFrame *avFrame); int getAvframe(AVFrame *avFrame); int clearAvFrame(); void release(); int getAvPacketSize(); int getAvFrameSize(); int noticeThread(); }; #endif //WLPLAYER_QUEUE_H
[ "xiao244164200@qq.com" ]
xiao244164200@qq.com
c572bb6bb1d79b109d3733c37d351434adf7d1d9
090da3fcbcabed6db8b639ba860d6bc4f2c3e34f
/tests/windows/runner/utils.cpp
7e940c4f2f46d26c102b5cba11e04501c560c322
[ "BSD-3-Clause" ]
permissive
LucazzP/flutterfire
3abd50a5d64dc120af70555c5216f28fe594d165
6f4d3525e8521b8eea009707db50e6812c33db3a
refs/heads/master
2023-07-23T19:24:19.965142
2023-07-03T12:37:50
2023-07-03T12:37:50
240,923,696
0
0
BSD-3-Clause
2020-02-16T16:22:27
2020-02-16T16:22:27
null
UTF-8
C++
false
false
1,908
cpp
// Copyright 2023, the Chromium project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "utils.h" #include <flutter_windows.h> #include <io.h> #include <stdio.h> #include <windows.h> #include <iostream> void CreateAndAttachConsole() { if (::AllocConsole()) { FILE *unused; if (freopen_s(&unused, "CONOUT$", "w", stdout)) { _dup2(_fileno(stdout), 1); } if (freopen_s(&unused, "CONOUT$", "w", stderr)) { _dup2(_fileno(stdout), 2); } std::ios::sync_with_stdio(); FlutterDesktopResyncOutputStreams(); } } std::vector<std::string> GetCommandLineArguments() { // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. int argc; wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); if (argv == nullptr) { return std::vector<std::string>(); } std::vector<std::string> command_line_arguments; // Skip the first argument as it's the binary name. for (int i = 1; i < argc; i++) { command_line_arguments.push_back(Utf8FromUtf16(argv[i])); } ::LocalFree(argv); return command_line_arguments; } std::string Utf8FromUtf16(const wchar_t* utf16_string) { if (utf16_string == nullptr) { return std::string(); } int target_length = ::WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, -1, nullptr, 0, nullptr, nullptr); std::string utf8_string; if (target_length == 0 || target_length > utf8_string.max_size()) { return utf8_string; } utf8_string.resize(target_length); int converted_length = ::WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, -1, utf8_string.data(), target_length, nullptr, nullptr); if (converted_length == 0) { return std::string(); } return utf8_string; }
[ "noreply@github.com" ]
LucazzP.noreply@github.com
32ef379068837799fd30896cbe336ff782ca9834
ddf9fe457bc20001b562de86b94ab373826e7649
/Programming Assignment 6 by Joseph Cunningham/Joseph Cunningham-03-24-2017-00-53-44/122 PA 6/BSTNode.cpp
0fe7f06dbf81b1a96bef0ad021fe757233dc8a57
[]
no_license
Jham109/CS-122
02547985b6789c86af26e48691f790568d7a11c8
0a86ef92767976bd22c3d0167feb384f7948f112
refs/heads/master
2021-01-16T14:14:18.863392
2020-02-26T02:30:59
2020-02-26T02:30:59
243,149,812
0
0
null
null
null
null
UTF-8
C++
false
false
624
cpp
#include "BSTNode.h" Node::Node(string newCode, char newChar) { mCode = newCode; mChar = newChar; mLeft = nullptr; mRight = nullptr; } Node::~Node() { //the destructor of Node } string Node::getCode() const { return mCode; } char Node::getChar() const { return mChar; } Node *& Node::getLeft() { return mLeft; } Node *& Node::getRight() { return mRight; } void Node::setChar(const char newChar) { mChar = newChar; } void Node::setCode(const string newData) { mCode = newData; } void Node::setLeft(Node * const newLeft) { mLeft = newLeft; } void Node::setRight(Node * const newRight) { mRight = newRight; }
[ "joseph.cunningham@wsu.edu" ]
joseph.cunningham@wsu.edu
69c8342a4be7d723d78a89c40ddba4ba7bbeffc2
0c4bd1b977cc714a8a6b2839f51c4247ecfd32b1
/C++/lbann/src/layers/regularizers/batch_normalization.cpp
c93130f8442f9cfde708413758b9a8f01253c30e
[ "Apache-2.0" ]
permissive
ishine/neuralLOGIC
281d498b40159308815cee6327e6cf79c9426b16
3eb3b9980e7f7a7d87a77ef40b1794fb5137c459
refs/heads/master
2020-08-14T14:11:54.487922
2019-10-14T05:32:53
2019-10-14T05:32:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,016
cpp
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2014-2019, Lawrence Livermore National Security, LLC. // Produced at the Lawrence Livermore National Laboratory. // Written by the LBANN Research Team (B. Van Essen, et al.) listed in // the CONTRIBUTORS file. <lbann-dev@llnl.gov> // // LLNL-CODE-697807. // All rights reserved. // // This file is part of LBANN: Livermore Big Artificial Neural Network // Toolkit. For details, see http://software.llnl.gov/LBANN or // https://github.com/LLNL/LBANN. // // Licensed under the Apache License, Version 2.0 (the "Licensee"); you // may not use this file except in compliance with the License. You may // obtain a copy of the License at: // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the license. //////////////////////////////////////////////////////////////////////////////// #include "lbann/layers/regularizers/batch_normalization.hpp" #include "lbann/execution_contexts/sgd_execution_context.hpp" namespace lbann { template <> void batch_normalization_layer<data_layout::DATA_PARALLEL, El::Device::CPU>::fp_compute() { constexpr DataType zero = 0; constexpr DataType one = 1; const bool is_training = this->m_model->get_execution_context().get_execution_mode() == execution_mode::training; // Matrices const auto& input = get_prev_activations(); const auto& local_input = input.LockedMatrix(); auto& local_output = get_local_activations(); // Matrix parameters const auto& width = input.Width(); const auto& local_width = local_input.Width(); const auto& output_dims = get_output_dims(); const auto& num_channels = output_dims[0]; const auto& channel_size = get_output_size() / num_channels; // Compute statistics if (is_training) { // Local matrices auto& local_mean = m_mean_v->Matrix(); auto& local_var = m_var_v->Matrix(); auto& local_running_mean = this->m_weights[2]->get_values().Matrix(); auto& local_running_var = this->m_weights[3]->get_values().Matrix(); // Compute sums and sums of squares LBANN_OMP_PARALLEL_FOR for (El::Int channel = 0; channel < num_channels; ++channel) { DataType sum = zero; DataType sqsum = zero; const auto& row_start = channel * channel_size; const auto& row_end = (channel+1) * channel_size; for (El::Int col = 0; col < local_width; ++col) { for (El::Int row = row_start; row < row_end; ++row) { const auto& x = local_input(row, col); sum += x; sqsum += x * x; } } local_mean(channel, 0) = sum; local_var(channel, 0) = sqsum; } El::Int num_per_sum; if (m_statistics_group_size == 0) { // Global statistics aggregation; allreduce on fused buffer. m_comm->allreduce(*m_mean_and_var, m_mean_and_var->RedundantComm(), El::mpi::SUM); num_per_sum = channel_size * width; } else if (m_statistics_group_size == 1) { // Local aggregation, no allreduce needed. num_per_sum = channel_size * local_width; } else { // Grouped batchnorm. Allreduce on fused buffer. m_comm->allreduce(*m_mean_and_var, m_comm->get_packed_group_comm(m_statistics_group_size), El::mpi::SUM); if (m_num_per_sum_cache.count(width) == 0) { num_per_sum = channel_size * local_width; num_per_sum = m_comm->allreduce( num_per_sum, m_comm->get_packed_group_comm(m_statistics_group_size)); m_num_per_sum_cache[width] = num_per_sum; } else { num_per_sum = m_num_per_sum_cache[width]; } } // Compute minibatch statistics if (num_per_sum <= 1) { El::Fill(local_var, one); } else { LBANN_OMP_PARALLEL_FOR for (El::Int channel = 0; channel < num_channels; ++channel) { const auto& mean = local_mean(channel, 0) / num_per_sum; const auto& sqmean = local_var(channel, 0) / num_per_sum; auto var = num_per_sum * (sqmean - mean * mean) / (num_per_sum - 1); var = std::max(var, m_epsilon); local_mean(channel, 0) = mean; local_var(channel, 0) = var; auto& running_mean = local_running_mean(channel, 0); auto& running_var = local_running_var(channel, 0); running_mean = m_decay * running_mean + (one - m_decay) * mean; running_var = m_decay * running_var + (one - m_decay) * var; } } } // Get matrices const auto& local_scale = this->m_weights[0]->get_values().LockedMatrix(); const auto& local_bias = this->m_weights[1]->get_values().LockedMatrix(); const auto& local_mean = (is_training ? m_mean_v->LockedMatrix() : this->m_weights[2]->get_values().LockedMatrix()); const auto& local_var = (is_training ? m_var_v->LockedMatrix() : this->m_weights[3]->get_values().LockedMatrix()); // Iterate through channels LBANN_OMP_PARALLEL_FOR for (El::Int channel = 0; channel < num_channels; ++channel) { // Get channel parameters const auto& mean = local_mean(channel, 0); const auto& var = local_var(channel, 0); const DataType inv_stdev = 1 / std::sqrt(var + m_epsilon); const auto& scale = local_scale(channel, 0); const auto& bias = local_bias(channel, 0); // Apply batch normalization to inputs in channel const auto& row_start = channel * channel_size; const auto& row_end = (channel+1) * channel_size; for (El::Int col = 0; col < local_width; ++col) { for (El::Int row = row_start; row < row_end; ++row) { const auto& x = local_input(row, col); const auto& xhat = (x - mean) * inv_stdev; auto& y = local_output(row, col); y = scale * xhat + bias; } } } } template <> void batch_normalization_layer<data_layout::DATA_PARALLEL, El::Device::CPU>::bp_compute() { constexpr DataType one = 1; const bool is_training = this->m_model->get_execution_context().get_execution_mode() == execution_mode::training; // Matrices const auto& local_scale = this->m_weights[0]->get_values().LockedMatrix(); const auto& local_mean = (is_training ? m_mean_v->LockedMatrix() : this->m_weights[2]->get_values().LockedMatrix()); const auto& local_var = (is_training ? m_var_v->LockedMatrix() : this->m_weights[3]->get_values().LockedMatrix()); const auto& input = get_prev_activations(); const auto& local_input = input.LockedMatrix(); const auto& local_gradient_wrt_output = get_local_prev_error_signals(); auto& local_gradient_wrt_input = get_local_error_signals(); auto& local_mean_gradient = m_mean_gradient_v->Matrix(); auto& local_var_gradient = m_var_gradient_v->Matrix(); auto& local_scale_gradient = m_scale_gradient->Matrix(); auto& local_bias_gradient = m_bias_gradient->Matrix(); // Matrix parameters const auto& c = static_cast<sgd_execution_context&>(this->m_model->get_execution_context()); const auto effective_mini_batch_size = c.get_effective_mini_batch_size(); const auto& width = input.Width(); const auto& local_width = local_input.Width(); const auto& output_dims = get_output_dims(); const auto& num_channels = output_dims[0]; const auto& channel_size = get_output_size() / num_channels; // Compute local gradients LBANN_OMP_PARALLEL_FOR for (El::Int channel = 0; channel < num_channels; ++channel) { // Initialize channel parameters and gradients const auto& mean = local_mean(channel, 0); const auto& var = local_var(channel, 0); const auto& scale = local_scale(channel, 0); const DataType inv_stdev = 1 / std::sqrt(var + m_epsilon); const auto& dvar_factor = inv_stdev * inv_stdev * inv_stdev / 2; DataType dmean = 0; DataType dvar = 0; DataType dscale = 0; DataType dbias = 0; // Compute gradient contributions from local entries const auto& row_start = channel * channel_size; const auto& row_end = (channel+1) * channel_size; for (El::Int col = 0; col < local_width; ++col) { for (El::Int row = row_start; row < row_end; ++row) { const auto& x = local_input(row, col); const auto& xhat = (x - mean) * inv_stdev; const auto& dy = local_gradient_wrt_output(row, col); dscale += dy * xhat; dbias += dy; const auto& dxhat = dy * scale; dmean += - dxhat * inv_stdev; dvar += - dxhat * (x - mean) * dvar_factor; } } local_mean_gradient(channel, 0) = dmean; local_var_gradient(channel, 0) = dvar; local_scale_gradient(channel, 0) = dscale; local_bias_gradient(channel, 0) = dbias; } // Accumulate gradients if (is_training) { if (m_statistics_group_size == 0) { // Global aggregation; allreduce on fused buffer. m_comm->allreduce(*m_mean_and_var_gradient, m_mean_and_var_gradient->RedundantComm(), El::mpi::SUM); } else if (m_statistics_group_size > 1) { // Grouped batchnorm; allreduce on fused buffer. m_comm->allreduce(*m_mean_and_var_gradient, m_comm->get_packed_group_comm(m_statistics_group_size), El::mpi::SUM); } } else { // Zero fused buffer. El::Zero(*m_mean_and_var_gradient); } optimizer* scale_optimizer = m_weights[0]->get_optimizer(); if (scale_optimizer != nullptr) { scale_optimizer->add_to_gradient(*m_scale_gradient, one / effective_mini_batch_size, true); } optimizer* bias_optimizer = m_weights[1]->get_optimizer(); if (bias_optimizer != nullptr) { bias_optimizer->add_to_gradient(*m_bias_gradient, one / effective_mini_batch_size, true); } // Compute error signal El::Int num_per_sum; if (m_statistics_group_size == 0) { // Global statistics aggregation. num_per_sum = channel_size * width; } else if (m_statistics_group_size == 1) { // Local aggregation. num_per_sum = channel_size * local_width; } else { // Grouped batchnorm. num_per_sum = m_num_per_sum_cache[width]; // This was computed in FP. } if (num_per_sum <= 1) { El::Zero(local_gradient_wrt_input); } else { LBANN_OMP_PARALLEL_FOR for (El::Int channel = 0; channel < num_channels; ++channel) { // Initialize channel parameters and gradients const auto& mean = local_mean(channel, 0); const auto& var = local_var(channel, 0); const auto& scale = local_scale(channel, 0); const auto& dmean = local_mean_gradient(channel, 0); const auto& dvar = local_var_gradient(channel, 0); // Compute useful constants const DataType inv_stdev = 1 / std::sqrt(var + m_epsilon); const auto& dmean_term = dmean / num_per_sum; const auto& dvar_term = dvar * 2 / (num_per_sum - 1); // Compute error signal for current channel const auto& row_start = channel * channel_size; const auto& row_end = (channel+1) * channel_size; for (El::Int col = 0; col < local_width; ++col) { for (El::Int row = row_start; row < row_end; ++row) { const auto& x = local_input(row, col); const auto& dy = local_gradient_wrt_output(row, col); const auto& dxhat = dy * scale; auto& dx = local_gradient_wrt_input(row, col); dx = dxhat * inv_stdev + dmean_term + dvar_term * (x - mean); } } } } } } // namespace lbann
[ "the.new.horizon@outlook.com" ]
the.new.horizon@outlook.com
808abb58068a806a711dd57f02ade77b104d9b62
8df64af68085e3bd3eeb99ab6679eb074e80842b
/opensimAD-install/sdk/include/OpenSim/Common/Object.h
712724f3d7ae8011267cdd50043b6b541bc17d18
[ "Apache-2.0" ]
permissive
VDB-Bram/opensimAD
ace0a9db6a844ffde7f03f18f9c0a31d3b39bf40
7afad33dc669f3540fdffb54e8e93374dceb3624
refs/heads/main
2023-08-13T09:10:35.158779
2021-10-02T01:59:30
2021-10-02T01:59:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
68,566
h
#ifndef OPENSIM_OBJECT_H_ #define OPENSIM_OBJECT_H_ /* -------------------------------------------------------------------------- * * OpenSim: Object.h * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2017 Stanford University and the Authors * * Author(s): Frank C. Anderson, Ayman Habib, Ajay Seth, Michael A. Sherman * * * * Licensed under the Apache License, Version 2.0 (the "License"); you may * * not use this file except in compliance with the License. You may obtain a * * copy of the License at http://www.apache.org/licenses/LICENSE-2.0. * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * -------------------------------------------------------------------------- */ /* Note: This code was originally developed by Realistic Dynamics Inc. * Author: Frank C. Anderson */ #ifdef _WIN32 #pragma warning( disable : 4251 ) #pragma warning( disable : 4786 ) #pragma warning( disable : 4660 ) #endif // INCLUDES #include "osimCommonDLL.h" #include "PropertySet.h" #include "PropertyTable.h" #include "Property.h" #include <cstring> #include <cassert> #include "osim_adouble.h" // DISABLES MULTIPLE INSTANTIATION WARNINGS // EXPORT LINE FOR MICROSOFT VISUAL C++ #ifdef _WIN32 #ifndef SWIG template class OSIMCOMMON_API OpenSim::ArrayPtrs<OpenSim::Object>; #endif #endif #ifdef SWIG #ifdef OSIMCOMMON_API #undef OSIMCOMMON_API #endif #define OSIMCOMMON_API #ifdef SWIGJAVA #define SWIG_DECLARE_EXCEPTION throw(OpenSim::Exception) #else #define SWIG_DECLARE_EXCEPTION #endif #else #define SWIG_DECLARE_EXCEPTION #endif // Forward-declare SimTK types. namespace SimTK { // Needed for Object_GetClassName<SimTK::SpatialVec>, defined in this file. typedef Vec<2, Vec3> SpatialVec; } namespace OpenSim { // CONSTANTS const char ObjectDEFAULT_NAME[] = "default"; class XMLDocument; //============================================================================== // OBJECT //============================================================================== /** This is the base class for all %OpenSim objects that are serializable (meaning they can be written to and read back from files). In particular, all ModelComponent objects derive from %Object. It provides a common base class from which to derive serializable objects and also some basic functionality, such as writing to files in XML format, managing properties, and the equality, less than, and output operators. An %Object maintains a table of "properties" that know how to read themselves from XML and write themselves to XML. The available Property types are -# Primitive data types (int, bool, double, std::string, ...) -# Properties that contain other Objects, -# Properties containing lists of either of the previous 2 categories It is important to note that Objects and Properties together form a recursive tree structure that is the representation of an %OpenSim Model. See the documentation for the OpenSim::Property class for more information. <h3>%Object declaration</h3> The declaration of every class derived from %Object \e must have its first line (that is, immediately after the "{" in the class declaration) one of four standard "boilerplate" macros: @code OpenSim_DECLARE_CONCRETE_OBJECT (ClassName, SuperclassName); OpenSim_DECLARE_CONCRETE_OBJECT_T(ClassName, T, SuperclassName); OpenSim_DECLARE_ABSTRACT_OBJECT (ClassName, SuperclassName); OpenSim_DECLARE_ABSTRACT_OBJECT_T(ClassName, T, SuperclassName); @endcode ("Superclass" means the immediate class from which the class derives; that terminology is borrowed from Java. It is often called the "Parent" class but we'll use "Super" which is more precise.) The "_T" variants of the above macros are used for objects that are templatized, like Set\<T>. These macros provide a standardized set of declarations for every object, including @code typedef ClassName Self; // for all classes typedef SuperclassName Super; // for all classes static const std::string& getClassName(); // for all classes const std::string& getConcreteClassName(); // for concrete classes only ClassName* clone() const; // see below @endcode getClassName() is a static method that returns the name of the %Object-derived class for which it is invoked. For example, ModelComponent::getClassName() returns "ModelComponent". In contrast, getConcreteClassName() is a pure virtual method of %Object that returns the class name of the actual concrete object being referenced through the abstract base class. This method is implemented only in concrete classes. Note that getClassName() and getConcreteClassName() will return the same string only if the referenced class is concrete. For example, @code Function* funcp = new LinearFunction(...); std::cout << funcp->getClassName(); // output: "Function" std::cout << funcp->getConcreteClassName(); // output: "LinearFunction" @endcode For concrete objects, the class name is used as the "object type tag", the tag string that will appear in XML files. Also, when a Property\<T> has no name (allowed for properties that contain just a single object) the object class name T (which may be abstract like Function or ModelComponent) is used to select the property. See OpenSim::Property for more information. The standard clone() method produces a duplicate of a concrete object and thus is implemented only for concrete classes. However, the return type must always match the type of the invoking object (this is called a "covariant type" and does not change the method's identity). It is therefore redeclared even in abstract classes, but remains pure virtual in those cases. That means if you invoke Function::clone() you'll get back a Function* rather than an Object*; this avoids many unnecessary invocations of the awkward and expensive dynamic_cast operator. <h3>%Object registration and renaming</h3> An %Object type needs to be "registered" by calling Object::registerType() with an instance of a concrete object so that the serialization infrastructure knows what kind of %Object to create when it encounters a specific XML tag. This associates the concrete object's class name (object type tag) with a default instance of that object. The registration process is normally done during dynamic library (DLL) loading, that is, as part of the static initializer execution that occurs before program execution. For backwards compatibility, we support a renaming mechanism in which now-deprecated class names can be mapped to their current equivalents. This is done via a string-to-string table mapping the old names to the new ones; only the current names appear in the registered objects table. Specification of these aliases is done immediately after registration in the DLL static initializer. <h3>Defaults mechanism</h3> When an %Object is registered (either programmatically, or overridden in the defaults section of a document), a copy of it is maintained in a dictionary as a "default" object of its class. When new instances of this class are requested, the contents of the default object are used to populate the new instance before deserialization. This allows for specifying default values that will be commonly used in one place in the XML file rather than with each object which leads to smaller files that are easier to read. Property values that obtain their values from the defaults and are not subsequently overridden are marked as being default values, allowing us to avoid writing them back out when serializing. @author Frank C. Anderson, Ayman Habib, Ajay Seth, Michael Sherman @see OpenSim::Property **/ class OSIMCOMMON_API Object { //------------------------------------------------------------------------------ // PUBLIC METHODS //------------------------------------------------------------------------------ public: // Constructors are protected. /** * Virtual destructor for cleanup */ virtual ~Object(); /** Create a new heap-allocated copy of the concrete object to which this %Object refers. It is up to the caller to delete the returned object when no longer needed. Every concrete object deriving from %Object implements this pure virtual method automatically, via the declaration macro it invokes (e.g., OpenSim_DECLARE_CONCRETE_OBJECT()). Note that the concrete class overrides modify the return type to be a pointer to the \e concrete object; that still overrides the base class method because the return type is covariant with (that is, derives from) %Object. **/ virtual Object* clone() const = 0; /** Returns the class name of the concrete %Object-derived class of the actual object referenced by this %Object, as a string. This is the string that is used as the tag for this concrete object in an XML file. Every concrete class derived from %Object automatically overrides this method via the declaration macro it uses. See getClassName() to get the class name of the referencing (possibly abstract) class rather than the concrete object. @see getClassName() **/ virtual const std::string& getConcreteClassName() const = 0; /// @cond // This is an assignment operator for use in Java. virtual void assign(Object &aObject) = 0; /// @endcond //-------------------------------------------------------------------------- // OPERATORS //-------------------------------------------------------------------------- /** * Equality operator wrapper for use from languages not supporting operator * overloading. */ bool isEqualTo(const Object &aObject) const { return ((*this)==aObject); } #ifndef SWIG /** Copy assignment copies he base class fields, including the properties. **/ Object& operator=(const Object &aObject); /** Determine if two objects are equal. They are equal if all the simple base class members are equal, both objects have the same number of properties and corresponding properties are equal, and if the objects are the same concrete type and the concrete class says they are equal. Concrete object classes must override this if they have any fields to compare, but be sure to invoke the base class operator too. **/ virtual bool operator==(const Object &aObject) const; /** Provide an ordering for objects so they can be put in sorted containers. **/ virtual bool operator<(const Object &aObject) const; /** Write the type and name of this object into the given output stream. **/ friend std::ostream& operator<<(std::ostream &aOut, const Object &aObject) { aOut << aObject.getConcreteClassName() << " " << aObject.getName(); return(aOut); }; #endif //-------------------------------------------------------------------------- // GET AND SET //-------------------------------------------------------------------------- /** %Set the name of the Object. */ void setName(const std::string& name); /** Get the name of this Object. */ const std::string& getName() const; /** %Set description, a one-liner summary. */ void setDescription(const std::string& description); /** Get description, a one-liner summary. */ const std::string& getDescription() const; /** Get Authors of this Object */ const std::string& getAuthors() const { return _authors; }; /** %Set Authors of this object. Call this method in your constructor if needed. */ void setAuthors(const std::string& authors) { _authors=authors; }; /** Get references or publications to cite if using this object. */ const std::string& getReferences() const { return _references; }; /** %Set references or publications to cite if using this object. */ void setReferences(const std::string& references) { _references=references; }; //-------------------------------------------------------------------------- // PUBLIC ACCESS TO PROPERTIES //-------------------------------------------------------------------------- /** @name Public access to properties Methods in this section are for public access to the properties maintained by this OpenSim %Object. Properties are normally accessed through methods of the concrete %Object-derived classes that are generated by the Property declaration macros; see OpenSim::Property for information. However, when dealing with Objects from "the outside", as is done in the GUI, these methods allow access to properties via the property base class AbstractProperty to support various type-independent property services. That is particularly useful for %Object-containing properties since the objects can be obtained without knowing their concrete types. For simple types (e.g. int, std::string) you can only obtain the values if you know the expected type. For those types, or when you know the expected %Object type, you can use the templatized methods to deal with the concrete values. **/ /**@{**/ /** Determine how many properties are stored with this %Object. These are numbered 0..n-1 in the order they were created. **/ // Note: new properties come first, deprecated ones afterwards. int getNumProperties() const; /** Get a const reference to a property by its index number, returned as an AbstractProperty. **/ const AbstractProperty& getPropertyByIndex(int propertyIndex) const; /** Get a writable reference to a property by its index number, returned as an AbstractProperty. **/ AbstractProperty& updPropertyByIndex(int propertyIndex); /** Return true if this %Object has a property of any type with the given \a name, which must not be empty. **/ bool hasProperty(const std::string& name) const; /** Get a const reference to a property by its name, returned as an AbstractProperty. An exception is thrown if no property by this name is present in this %Object. **/ const AbstractProperty& getPropertyByName(const std::string& name) const; /** Get a writable reference to a property by its name, returned as an AbstractProperty. An exception is thrown if no property by this name is present in this %Object. **/ AbstractProperty& updPropertyByName(const std::string& name); /** Return true if this %Object contains an unnamed, one-object property that contains objects of the given template type T. The type must match exactly the type used when this property was created with addProperty<T>(). **/ template <class T> bool hasProperty() const; /** Get property of known type Property\<T> as a const reference; the property must be present and have the right type. This is primarily used by the Property declaration macros for fast access to properties. **/ template <class T> const Property<T>& getProperty(const PropertyIndex& index) const; /** Get property of known type Property\<T> as a writable reference; the property must be present and have the right type. This is primarily used by the Property declaration macros for fast access to properties. **/ template <class T> Property<T>& updProperty(const PropertyIndex& index); /** Returns \c true if no property's value has changed since the last time setObjectIsUpToDateWithProperties() was called. **/ bool isObjectUpToDateWithProperties() const {return _objectIsUpToDate;} /** Dump formatted property information to a given output stream, useful for creating a "help" facility for registered objects. Object name, property name, and property comment are output. Input is a class name and property name. If the property name is the empty string or just "*", then information for all properties in the class is printed. If the class name is empty, information in all properties of all registered classes is printed. @param os Output stream to which info is printed. @param classNameDotPropertyName A string combining the class name and property name. The two names should be separated by a period (ClassName.PropertyName). If PropertyName is empty or "*", the information for all properties in the class is printed. If ClassName is empty, the information for the properties of all registered classes is printed. @param printFlagInfo Print to the ostream some instructions for using the -PropertyInfo command line flag. Returns false if the provided names do not match known classes or properties; otherwise, returns true. **/ static bool PrintPropertyInfo(std::ostream& os, const std::string& classNameDotPropertyName, bool printFlagInfo = true); /** Same as the other signature but the class name and property name are provided as two separate strings. Returns false if the provided names do not match known classes or properties; otherwise, returns true. **/ static bool PrintPropertyInfo(std::ostream& os, const std::string& className, const std::string& propertyName, bool printFlagInfo = true); /**@}**/ //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // REGISTRATION OF TYPES AND DEFAULT OBJECTS //-------------------------------------------------------------------------- /** @name Registration of types and default objects Methods in this section deal with the requirement that all %OpenSim types derived from %Object must be registered and a default instance provided. This enables reading these objects from XML files. You can also recognize now-obsolete names for objects and have them quietly mapped to their modern names using the renameType() method. Rename can also be used programmatically to replace one registered type with another, because renaming occurs prior to object lookup. **/ /**@{**/ /** Register an instance of a class; if the class is already registered it will be replaced. This is normally called as part of the static initialization of a dynamic library (DLL). The supplied object's concrete class name will be used as a key, and a \e copy (via clone()) of the supplied %Object is used as the default value for objects of this type when created (typically during the deserialization process when reading an XML file). **/ static void registerType(const Object& defaultObject); /** Support versioning by associating the current %Object type with an old name. This is only allowed if \a newTypeName has already been registered with registerType(). Renaming is applied first prior to lookup so can be used both for translating now-obsolete names to their new names and for overriding one registered type with another. **/ static void renameType(const std::string& oldTypeName, const std::string& newTypeName); /** Return a pointer to the default instance of the registered (concrete) %Object whose class name is given, or NULL if the type is not registered. Note that this refers to the default %Object instance that is stored with the %Object class; do not delete it! If you want a copy of this object instead, use newInstanceOfType(). The given \a concreteClassName will be mapped through the renamed type table if necessary but the returned object will always have the new type name, which may differ from the supplied one. Note that renaming is applied first, prior to looking up the name in the registered objects table. @see registerType(), renameType() **/ static const Object* getDefaultInstanceOfType(const std::string& concreteClassName); /** Return true if the given concrete object type represents a subclass of the template object type T, and thus could be referenced with a T*. The object type to be tested is given by its class name as a string. For this to work the name must represent an already-registered object type. If necessary \a concreteClassName will be mapped through the renamed type table, so we'll return true if the class it maps to satisfies the condition. Note that renaming is applied first, prior to looking up the name in the registered objects table. @see registerType(), renameType() **/ template <class T> static bool isObjectTypeDerivedFrom(const std::string& concreteClassName) { const Object* defObj = getDefaultInstanceOfType(concreteClassName); if (defObj == NULL) return false; return dynamic_cast<const T*>(defObj) != NULL; } /** Create a new instance of the concrete %Object type whose class name is given as \a concreteClassName. The instance is initialized to the default object of corresponding type, possibly after renaming to the current class name. Writes a message to stderr and returns null if the tag isn't registered. **/ static Object* newInstanceOfType(const std::string& concreteClassName); /** Retrieve all the typenames registered so far. This is done by traversing the registered objects map, so only concrete classes that have registered instances are returned; renamed types will not appear unless they were separately registered. (Note that even if one registered type has been renamed to another, both will appear in the returned list.) The result returned in \a typeNames should not be cached while more shared libraries or plugins are loaded, because more types may be registered as a result. Instead the list should be reconstructed whenever in doubt. **/ static void getRegisteredTypenames(Array<std::string>& typeNames); /** Return an array of pointers to the default instances of all registered (concrete) %Object types that derive from a given %Object-derived type that does not have to be concrete. This is useful, for example, to find all Joints, Constraints, ModelComponents, Analyses, etc. **/ template<class T> static void getRegisteredObjectsOfGivenType(ArrayPtrs<T>& rArray) { rArray.setSize(0); rArray.setMemoryOwner(false); for(int i=0; i<_registeredTypes.getSize(); i++) { T* obj = dynamic_cast<T*>(_registeredTypes[i]); if (obj) rArray.append(obj); } } /**@}**/ //-------------------------------------------------------------------------- // XML //-------------------------------------------------------------------------- /** @name XML reading and writing These methods deal with writing out in-memory objects to XML files (serializing) and reading XML files to reconstruct in-memory objects (deserializing). **/ /**@{**/ /** Create an %OpenSim object whose type is based on the tag at the root node of the XML file passed in. This is useful since the constructor of %Object doesn't have the proper type info. This works by using the defaults table so that %Object does not need to know about its derived classes. It uses the defaults table to get an instance. **/ //static Object* makeObjectFromFile(const std::string& fileName); /** We're given an XML element from which we are to populate this %Object. If the element has a \c file attribute, we'll instead read the %Object from that file. Otherwise we'll invoke updateFromXMLNode() to read the %Object directly from the supplied element. Note that a relative file name will be interpreted relative to the current working directory, but that will normally have been set earlier to the directory containing the top-level (root) %Object, such as the Model file. **/ //void readObjectFromXMLNodeOrFile // (SimTK::Xml::Element& objectElement, // int versionNumber); /** Use this method to deserialize an object from a SimTK::Xml::Element. The element is assumed to be in the format consistent with the passed-in \a versionNumber. If there is a file attribute in \a objectElement it will be ignored; if you want it processed you should call readObjectFromXMLNodeOrFile() instead. **/ //virtual void updateFromXMLNode(SimTK::Xml::Element& objectElement, // int versionNumber); /** Serialize this object into the XML node that represents it. @param parent Parent XML node of this object. Sending in a parent node allows an XML node to be generated for this object if it doesn't already have one. If no parent node is supplied and this object doesn't already have an XML node, this object will become the root node for a new XML document. If this object already has an XML node associated with it, no new nodes are ever generated and the parent node is not used. **/ //virtual void updateXMLNode(SimTK::Xml::Element& parent) const; /** Inlined means an in-memory Object that is not associated with an XMLDocument. **/ //bool getInlined() const; /** Mark this as inlined or not and optionally provide a file name to associate with the new XMLDocument for the non-inline case. If there was already a document associated with this object it is deleted. **/ //void setInlined(bool aInlined, const std::string &aFileName=""); protected: /** When an object is initialized using the current values of its properties, it can set a flag indicating that it is up to date. This flag is automatically cleared when any property is modified. This allows objects to avoid expensive reinitialization if it is unnecessary (that is, whenever this %Object hands out writable access to a property). Note that use of this flag is entirely optional; most %Object classes don't have any expensive initialization to worry about. This flag is cleared automatically but if you want to clear it manually for testing or debugging, see clearObjectIsUpToDateWithProperties(). **/ void setObjectIsUpToDateWithProperties() { _objectIsUpToDate = true; } /** For testing or debugging purposes, manually clear the "object is up to date with respect to properties" flag. This is normally done automatically when a property is modified. Setting the flag is always done manually, however, see setObjectIsUpToDateWithProperties(). **/ void clearObjectIsUpToDateWithProperties() { _objectIsUpToDate = false; } /** Use this method only if you're deserializing from a file and the object is at the top level; that is, primarily in constructors that take a file name as input. **/ //void updateFromXMLDocument(); /** Unconditionally set the XMLDocument associated with this object. Use carefully -- if there was already a document its heap space is lost here. **/ //void setDocument(XMLDocument* doc) {_document=doc;} /** Get a const pointer to the document (if any) associated with this object. **/ //const XMLDocument* getDocument() const {return _document;} /** Get a writable pointer to the document (if any) associated with this object. **/ //XMLDocument* updDocument() {return _document;} public: /** If there is a document associated with this object then return the file name maintained by the document. Otherwise return an empty string. **/ //std::string getDocumentFileName() const; void setAllPropertiesUseDefault(bool aUseDefault); /** Write this %Object into an XML file of the given name; conventionally the suffix to use is ".osim". This is useful for writing out a Model that has been created programmatically, and also very useful for testing and debugging. **/ //bool print(const std::string& fileName) const; /** dump the XML representation of this %Object into an std::string and return it. Mainly intended for debugging and for use by the XML browser in the GUI. **/ //std::string dump(bool dumpName=false); /**@}**/ //-------------------------------------------------------------------------- // ADVANCED/OBSCURE/QUESTIONABLE/BUGGY //-------------------------------------------------------------------------- /** @name Advanced/Obscure Methods in this section are for specialized purposes not of interest to most OpenSim API users. For example, some of these are services needed by the OpenSim GUI which is written in Java. **/ /**@{**/ /** Return the name of this class as a string; i.e., "Object". See getConcreteClassName() if you want the class name of the underlying concrete object instead. Note that this method is automatically supplied for every class declaration that derives from Object via the standard macro provided for that purpose. See introductory text for this Object class for more information. **/ static const std::string& getClassName() { static std::string name ("Object"); return name; } /** Static function to control whether all registered objects and their properties are written to the defaults section of output files rather than only those values for which the default was explicitly overwritten when read in from an input file or set programmatically. **/ static void setSerializeAllDefaults(bool shouldSerializeDefaults) { _serializeAllDefaults = shouldSerializeDefaults; } /** Report the value of the "serialize all defaults" flag. **/ static bool getSerializeAllDefaults() { return _serializeAllDefaults; } /** Returns true if the passed-in string is "Object"; each %Object-derived class defines a method of this name for its own class name. **/ static bool isKindOf(const char *type) { return (strcmp("Object",type)==0); } /** The default implementation returns true only if the supplied string is "Object"; each %Object-derived class overrides this to match its own class name. **/ virtual bool isA(const char *type) const { return this->isKindOf(type); } /** %Set the debug level to get verbose output. Zero means no debugging. **/ static void setDebugLevel(int newLevel) { _debugLevel=newLevel; }; /** Get current setting of debug level. **/ static int getDebugLevel() { return _debugLevel; }; /** Wrapper to be used on Java side to display objects in tree; this returns just the object's name. **/ const std::string& toString() const; #ifndef SWIG /** OBSOLETE: Get a reference to the PropertySet maintained by the Object. **/ PropertySet& getPropertySet() { return _propertySet; } const PropertySet& getPropertySet() const { return _propertySet; } #endif /** Use the clone() method to duplicate the given object unless the pointer is null in which case null is returned. **/ static Object* SafeCopy(const Object *aObject) { return aObject ? aObject->clone() : 0; } /** OBSOLETE alternate name for registerType(). **/ static void RegisterType(const Object& defaultObject) { registerType(defaultObject); } /** OBSOLETE alternate name for renameType(). **/ static void RenameType(const std::string& oldName, const std::string& newName) { renameType(oldName, newName); } /**@}**/ //-------------------------------------------------------------------------- //------------------------------------------------------------------------------ // PROTECTED METHODS //------------------------------------------------------------------------------ protected: /** The default constructor is only for use by constructors of derived types. Initializes all base class data members to innocuous values. **/ Object(); /** Constructor from a file, to be called from other constructors that take a file as input. **/ explicit Object(const std::string& fileName, bool aUpdateFromXMLNode = true) SWIG_DECLARE_EXCEPTION; /** Copy constructor is invoked automatically by derived classes with default copy constructors; otherwise it must be invoked explicitly. **/ Object(const Object& source); /** Construct the base class portion of an %Object from a given Xml element that describes this Object. Assumes latest XML file format; there is no provision for version numbering. **/ //explicit Object(SimTK::Xml::Element& aElement); /** Define a new single-value property of known type T, with the given \a name, associated \a comment, and initial \a value. The name must be unique within this %Object's property table. If T is an object type (i.e., derived from %Object), it is permissible for the property to be unnamed; pass an empty string for \a name. You will then be able to select the property using the object class name (that is, T::getClassName()) as though it were the property's name. An %Object can thus only have one unnamed property of any particular object type. @returns Reference to the new Property object stored in this object's property table. @see addOptionalProperty(), addListProperty() **/ template <class T> PropertyIndex addProperty(const std::string& name, const std::string& comment, const T& value); /** Add an optional property, meaning it can contain either no value or a single value. Here no initial value is provided. The property must have a name (the empty string is not acceptable), and that name must be unique within this %Object's property table. @returns Reference to the new Property object stored in this object's property table. @see addProperty(), addListProperty() **/ template <class T> PropertyIndex addOptionalProperty(const std::string& name, const std::string& comment); /** Add an optional property, meaning it can contain either no value or a single value. Here an initial value is provided. The property must have a name (the empty string is not acceptable), and that name must be unique within this %Object's property table. @returns Reference to the new Property object stored in this object's property table. @see addProperty(), addListProperty() **/ template <class T> PropertyIndex addOptionalProperty(const std::string& name, const std::string& comment, const T& value); /** Define a new list-valued property of known type T, with the given \a name, associated \a comment, minimum (==0) and maximum (>0) allowable list lengths, and a zero-length initial value. The property must have a name (the empty string is not acceptable), and that name must be unique within this %Object's property table. @returns The PropertyIndex of this property in the property table for this object. @see addProperty(), addOptionalProperty() **/ template <class T> PropertyIndex addListProperty(const std::string& name, const std::string& comment, int minSize, int maxSize); /** Define a new list-valued property as above, but assigning an initial value via some templatized container class that supports size() and indexing. Here the minimum size may be greater than zero, provided that the initial value has at least that many element (and no more than the allowed maximum). @returns The PropertyIndex of this property in the property table for this object. @see addProperty(), addOptionalProperty() **/ template <class T, template<class> class Container> PropertyIndex addListProperty(const std::string& name, const std::string& comment, int minSize, int maxSize, const Container<T>& valueList); /** Look up a property by name and return its PropertyIndex if it is found. If no property of that name is present, the returned index will be invalid; check with isValid(). **/ // Note: only works for new properties. PropertyIndex getPropertyIndex(const std::string& name) const { const int ix = _propertyTable.findPropertyIndex(name); if (ix >= 0) return PropertyIndex(ix); return PropertyIndex(); } /** Look up an unnamed property by the type of object it contains, and return its PropertyIndex if it is found. If no unnamed property of that type is present, the returned index will be invalid; check with isValid(). **/ // Note: only works for new properties. template <class T> PropertyIndex getPropertyIndex() const { const int ix = _propertyTable.findPropertyIndex(T::getClassName()); if (ix >= 0) return PropertyIndex(ix); return PropertyIndex(); } //-------------------------------------------------------------------------- // PRIVATE METHODS //-------------------------------------------------------------------------- private: void setNull(); // Functions to support deserialization. //void generateXMLDocument(); //void updateDefaultObjectsFromXMLNode(); //void updateDefaultObjectsXMLNode(SimTK::Xml::Element& aParent); //============================================================================== // DATA //============================================================================== public: #ifndef SWIG /** Name used for default objects when they are serialized. */ static const std::string DEFAULT_NAME; #endif protected: /** OBSOLETE: Property_Deprecated set for serializable member variables of this and derived classes. */ PropertySet _propertySet; private: // Array holding a default value for each of the registered object types. // Each object type only appears once in this array. Renamed types usually // do not have separate registered objects; they are just used to locate // one of the current ones. static ArrayPtrs<Object> _registeredTypes; // Map from concrete object class name string to a default object of that // type kept in the above array of registered types. Renamed types are *not* // normally entered here; the names are mapped separately using the map // below. static std::map<std::string,Object*> _mapTypesToDefaultObjects; // Map types that have been renamed to their new names, which can // then be used to find them in the default object map. This lets us // recognize the old names while converting to the new ones internally // so that they will be updated when written out. It also allows one // to map one registered type to a different one programmatically, because // we'll look up the name in the rename table first prior to searching // the registered types list. static std::map<std::string,std::string> _renamedTypesMap; // Global flag to indicate if all registered objects are to be written in // a "defaults" section. static bool _serializeAllDefaults; // Debug level: // 0: Hides non fatal warnings // 1: Shows illegal tags // 2: level 1 + registration troubleshooting // 3: 2 + more verbose troubleshooting of Object (de)serialization. When // used from Java wrapping in GUI/Matlab this catches all exceptions // thrown by the low-level libraries which is slower but helpful in // troubleshooting. static int _debugLevel; // The name of this object. std::string _name; // A short description of the object. std::string _description; // List of authors who contributed to the implementation of concrete object. std::string _authors; // List of references that should be cited when using this concrete object. std::string _references; // Property table for serializable properties of this and derived classes. PropertyTable _propertyTable; // This flag is cleared automatically whenever a property is changed. It // is initialized to false and is only set manually. bool _objectIsUpToDate; // The XML document, if any, associated with this object. // This is mutable since it's cached on deserialization and is // kept up to date to maintain "defaults" and document file path //TODO: why does an Object need to know where it was last written? Seems flaky and should be revisited mutable XMLDocument *_document; // Flag indicating whether the object is serialized to this _document or // to another fresh document, also cached for subsequent printing/writing. mutable bool _inlined; //============================================================================== }; // END of class Object //============================================================================== // OBJECT TEMPLATE METHOD IMPLEMENTATION //============================================================================== // This only works for the new properties -- it won't see deprecated ones. template <class T> bool Object:: hasProperty() const { // Look it up by T's object class name if that's allowed. if (Property<T>::TypeHelper::IsObjectType) { return _propertyTable.hasProperty (Property<T>::TypeHelper::getTypeName()); } throw OpenSim::Exception ("hasProperty<T>(): nameless property lookup by object class name " "only allowed when T is an Object-derived type, but T=" + std::string(SimTK::NiceTypeName<T>::name()) + ". For lookup by " "property name instead, use hasProperty(\"prop_name\")."); return false; } template <class T> const Property<T>& Object:: getProperty(const PropertyIndex& index) const { return _propertyTable.getProperty<T>(index); } template <class T> Property<T>& Object:: updProperty(const PropertyIndex& index) { _objectIsUpToDate = false; // property may be changed return _propertyTable.updProperty<T>(index); } template <class T> PropertyIndex Object:: addProperty(const std::string& name, const std::string& comment, const T& value) { // Restrict to exactly one value. If there is no name, this will throw // an exception if T is a simple (non-object) type. Property<T>* p = Property<T>::TypeHelper::create(name, true); p->setComment(comment); p->appendValue(value); p->setValueIsDefault(true); // Note that an unnamed, one-object property will use the object class name // as a name for lookup purposes. return PropertyIndex(_propertyTable.adoptProperty(p)); } template <class T> PropertyIndex Object:: addOptionalProperty(const std::string& name, const std::string& comment, const T& value) { if (name.empty()) throw OpenSim::Exception( "Object::addOptionalProperty(): an optional property must have " "a name. (Object " + getName() + ")."); Property<T>* p = Property<T>::TypeHelper::create(name, false); p->setAllowableListSize(0,1); p->setComment(comment); p->appendValue(value); p->setValueIsDefault(true); return PropertyIndex(_propertyTable.adoptProperty(p)); } template <class T> PropertyIndex Object:: addOptionalProperty(const std::string& name, const std::string& comment) { if (name.empty()) throw OpenSim::Exception( "Object::addOptionalProperty(): an optional property must have " "a name. (Object " + getName() + ")."); Property<T>* p = Property<T>::TypeHelper::create(name, false); p->setAllowableListSize(0,1); p->setComment(comment); p->setValueIsDefault(true); return PropertyIndex(_propertyTable.adoptProperty(p)); } template <class T> PropertyIndex Object:: addListProperty(const std::string& name, const std::string& comment, int minSize, int maxSize) { if (name.empty()) throw OpenSim::Exception( "Object::addListProperty(): a list property must have a name. " "(Object " + getName() + ")."); if (minSize > 0) throw OpenSim::Exception( "Object::addListProperty(): list property " + name + " has a minimum list size of " + SimTK::String(minSize) + " so must be given an initial value of at least that size " "(Object " + getName() + ")."); Property<T>* p = Property<T>::TypeHelper::create(name, false); p->setAllowableListSize(minSize, maxSize); p->setComment(comment); p->setValueIsDefault(true); return PropertyIndex(_propertyTable.adoptProperty(p)); } template <class T, template<class> class Container> PropertyIndex Object:: addListProperty(const std::string& name, const std::string& comment, int minSize, int maxSize, const Container<T>& valueList) { if (name.empty()) throw OpenSim::Exception( "Object::addListProperty(): a list property must have a name. " "(Object " + getName() + ")."); if (valueList.size() < minSize || valueList.size() > maxSize) throw OpenSim::Exception( "Object::addListProperty(): list property " + name + " has allowable list size " + SimTK::String(minSize) + ".." + SimTK::String(maxSize) + " but initial value had size " + SimTK::String(valueList.size()) + "."); Property<T>* p = Property<T>::TypeHelper::create(name, false); p->setAllowableListSize(minSize, maxSize); p->setComment(comment); for (int i=0; i < (int)valueList.size(); ++i) p->appendValue(valueList[i]); p->setValueIsDefault(true); return PropertyIndex(_propertyTable.adoptProperty(p)); } //============================================================================== // DERIVED OBJECT BOILERPLATE MACROS //============================================================================== /** @name Object Declaration Macros One of these macros must appear as the first line of any class declaration that derives directly or indirectly from %OpenSim's Object class. In almost all cases, the right macro to use is \c OpenSim_DECLARE_CONCRETE_OBJECT(). Use of these macros provides: - a public typedef Super that is the immediate parent class, - implementation of required Object pure virtual methods, including the clone() method that will create a new heap-allocated copy of any concrete Object, - uniform treatment of class names, which are used as tags in XML and for interfacing with Java using class names as strings to identify C++ objects. The static getClassName() returns the name of any class, and the member getConcreteClassName() returns the class name of the concrete object being referenced, and - an assortment of methods used only for interfacing with Java. **/ /**@{**/ /** Macro to be included as the first line of the class declaration for any non-templatized, concrete class that derives from OpenSim::Object. You should use this for any such class, even if you intend to derive more specific concrete objects from it. Don't use this for a still-abstract class, or a templatized concrete class like Set\<T>. @relates OpenSim::Object **/ #define OpenSim_DECLARE_CONCRETE_OBJECT(ConcreteClass, SuperClass) \ OpenSim_OBJECT_ANY_DEFS(ConcreteClass, SuperClass); \ OpenSim_OBJECT_NONTEMPLATE_DEFS(ConcreteClass, SuperClass); \ OpenSim_OBJECT_CONCRETE_DEFS(ConcreteClass); /** Macro to be included as the first line of the class declaration for any still-abstract class that derives from OpenSim::Object. These are classes that represent categories of objects, like Function and ModelComponent. This macro leaves Object pure virtuals clone() and getConcreteClassName() unimplemented, however it does redeclare the return type of clone() to be ConcreteClass*. @relates OpenSim::Object **/ #define OpenSim_DECLARE_ABSTRACT_OBJECT(ConcreteClass, SuperClass) \ OpenSim_OBJECT_ANY_DEFS(ConcreteClass, SuperClass); \ OpenSim_OBJECT_NONTEMPLATE_DEFS(ConcreteClass, SuperClass); \ OpenSim_OBJECT_ABSTRACT_DEFS(ConcreteClass); /** Macro to be included as the first line of the class declaration for any templatized, concrete class that derives from OpenSim::Object, like Set\<T>. @relates OpenSim::Object **/ #define OpenSim_DECLARE_CONCRETE_OBJECT_T(ConcreteClass, TArg, SuperClass) \ OpenSim_OBJECT_ANY_DEFS(ConcreteClass, SuperClass); \ OpenSim_OBJECT_TEMPLATE_DEFS(ConcreteClass, TArg, SuperClass); \ OpenSim_OBJECT_CONCRETE_DEFS(ConcreteClass); /** Macro to be included as the first line of the class declaration for any templatized, still-abstract class that derives from OpenSim::Object. @relates OpenSim::Object **/ #define OpenSim_DECLARE_ABSTRACT_OBJECT_T(ConcreteClass, TArg, SuperClass) \ OpenSim_OBJECT_ANY_DEFS(ConcreteClass, SuperClass); \ OpenSim_OBJECT_TEMPLATE_DEFS(ConcreteClass, TArg, SuperClass); \ OpenSim_OBJECT_ABSTRACT_DEFS(ConcreteClass); /**@}**/ // Hide helper macros from Doxygen -- they do not appear in code anywhere // but right here. They are used to construct the macros that are used in // various circumstances without duplicating any definitions. // This class allows us to get the class name for template arguments using // getClassName() when it is available, otherwise a specialization. template <class T> struct Object_GetClassName { static const std::string& name() {return T::getClassName();} }; template <> struct Object_GetClassName<bool> { static const std::string name() {return "bool";} }; template <> struct Object_GetClassName<signed char> { static const std::string name() {return "char";} }; template <> struct Object_GetClassName<unsigned char> { static const std::string name() {return "char";} }; template <> struct Object_GetClassName<char> { static const std::string name() {return "char";} }; template <> struct Object_GetClassName<short int> { static const std::string name() {return "int";} }; template <> struct Object_GetClassName<unsigned short int> { static const std::string name() {return "int";} }; template <> struct Object_GetClassName<int> { static const std::string name() {return "int";} }; template <> struct Object_GetClassName<unsigned int> { static const std::string name() {return "int";} }; template <> struct Object_GetClassName<long int> { static const std::string name() {return "int";} }; template <> struct Object_GetClassName<unsigned long int> { static const std::string name() {return "int";} }; template <> struct Object_GetClassName<long long int> { static const std::string name() {return "int";} }; template <> struct Object_GetClassName<unsigned long long int> { static const std::string name() {return "int";} }; template <> struct Object_GetClassName<float> { static const std::string name() {return "float";} }; //template <> struct Object_GetClassName<double> //{ static const std::string name() {return "double";} }; template <> struct Object_GetClassName<Recorder> { static const std::string name() { return "double"; } }; template <> struct Object_GetClassName<long double> { static const std::string name() {return "double";} }; template <> struct Object_GetClassName<std::string> { static const std::string name() {return "string";} }; template <> struct Object_GetClassName<SimTK::Vec2> { static const std::string name() {return "Vec2";} }; template <> struct Object_GetClassName<SimTK::Vec3> { static const std::string name() {return "Vec3";} }; template <> struct Object_GetClassName<SimTK::Vec6> { static const std::string name() {return "Vec6";} }; template <> struct Object_GetClassName<SimTK::Vector_<SimTK::Real>> { static const std::string name() {return "Vector"; } }; template <> struct Object_GetClassName<SimTK::Vector_<SimTK::Vec3>> { static const std::string name() {return "Vector_<Vec3>";} }; template <> struct Object_GetClassName<SimTK::Vector_<SimTK::Vec6>> { static const std::string name() {return "Vector_<Vec6>";} }; template <> struct Object_GetClassName<SimTK::Vector_<SimTK::SpatialVec>> { static const std::string name() {return "Vector_<SpatialVec>";} }; template <> struct Object_GetClassName<SimTK::SpatialVec> { static const std::string name() {return "SpatialVec";} }; template <> struct Object_GetClassName<SimTK::Transform> { static const std::string name() {return "Transform";} }; #define OpenSim_OBJECT_ANY_DEFS(ConcreteClass, SuperClass) \ public: \ /** @cond developer **/ \ /** This typedef might be useful within the member functions of this class. */ \ /** \internal This is generated by the `OpenSim_DECLARE_*_OBJECT` macros. */ \ typedef ConcreteClass Self; \ /** Use this typedef to refer to the superclass of this class. */ \ /** Avoid using the explicit type name of the superclass; this would */ \ /** introduce bugs if the superclass is changed. */ \ /** \internal This is generated by the `OpenSim_DECLARE_*_OBJECT` macros. */ \ typedef SuperClass Super; \ /** @endcond **/ \ OpenSim_OBJECT_JAVA_DEFS(ConcreteClass); // For non-template classes, the class name is identical to the supplied // ConcreteClass argument. #define OpenSim_OBJECT_NONTEMPLATE_DEFS(ConcreteClass, SuperClass) \ /** @name Auto-generated functions */ \ /** @{ */ \ /** This returns "##ConcreteClass##" */ \ /** See getConcreteClassName() if you want the class name of the underlying */ \ /** concrete object instead. */ \ /** \internal This is generated by the `OpenSim_DECLARE_*_OBJECT` macros. */ \ static const std::string& getClassName() \ { static std::string name(#ConcreteClass); return name; } \ /** @}*/ // For template classes ConcreteClass<TemplateArg>, we construct the class // name by assembling the pieces. #define OpenSim_OBJECT_TEMPLATE_DEFS(ConcreteClass, TArg, SuperClass) \ /** @name Auto-generated functions */ \ /** @{ */ \ /** This returns "##ConcreteClass##_<T>_". */ \ /** T is the template argument for this class. */ \ /** See getConcreteClassName() if you want the class name of the underlying */ \ /** concrete object instead. */ \ /** \internal This is generated by the `OpenSim_DECLARE_*_OBJECT` macros. */ \ static const std::string& getClassName() \ { static std::string name = #ConcreteClass "_" \ + Object_GetClassName<TArg>::name() \ + "_"; \ return name; } \ /** @}*/ // This provides definitions for the two Object pure virtuals clone() and // getConcreteClassName(). #define OpenSim_OBJECT_CONCRETE_DEFS(ConcreteClass) \ /** @name Auto-generated functions */ \ /** @{ */ \ ConcreteClass* clone() const override {return new ConcreteClass(*this);} \ const std::string& getConcreteClassName() const override \ { return getClassName(); } \ /** @}*/ \ private: // This leaves the two Object pure virtuals clone() and getConcreteClassName() // unimplemented, but changes the return type of clone() to ConcreteClass*, // which allows it to be invoked ConcreteClass::clone() and return the correct // pointer type. #define OpenSim_OBJECT_ABSTRACT_DEFS(ConcreteClass) \ /** @name Auto-generated functions */ \ /** @{ */ \ ConcreteClass* clone() const override = 0; \ const std::string& getConcreteClassName() const override = 0; \ /** @}*/ \ private: // Add public static method declaration in class to assist in downcasting // arbitrary objects to the new type to support dynamic casting across JNI. #define OpenSim_OBJECT_JAVA_DEFS(thisClass) \ public: \ /** @name Auto-generated functions */ \ /** @{ */ \ /** For use in MATLAB and Python to access the concrete class. */ \ /** Example: `cObj = %##thisClass##.safeDownCast(obj)`. */ \ /** This is equivalent to `dynamic_cast<##thisClass##*>(obj)` in C++. */ \ static thisClass* safeDownCast(OpenSim::Object *obj) \ { \ return dynamic_cast<thisClass *>(obj); \ } \ /** @cond developer */ \ /** This allows copy assignment in the Java GUI. */ \ /** @throws Exception if the argument is not of type thisClass##. */ \ void assign(Object &aObject) override \ { \ if (safeDownCast(&aObject)!=0) { \ *this = *((thisClass*)(&aObject)); \ } else { \ throw OpenSim::Exception(std::string(#thisClass)+ \ "::copy() called with object (name = " + aObject.getName() \ + ", type = " + aObject.getConcreteClassName()+").", \ __FILE__,__LINE__); \ } \ } \ /** @endcond */ \ /** @}*/ //============================================================================== // OBJECT PROPERTY IMPLEMENTATION //============================================================================== // These methods of ObjectProperty are defined here because they depend on // methods of Object. See Property.h for ObjectProperty's declaration. /** @cond **/ // Not for Doxygen. template <class T> inline std::string ObjectProperty<T>::toString() const { if (objects.empty()) return "(No Objects)"; std::string out; if (!this->isOneValueProperty()) out += '('; for (int i=0; i < objects.size(); ++i) { if (i != 0) out += ' '; out += objects[i]->getConcreteClassName(); } if (!this->isOneValueProperty()) out += ')'; return out; } template <class T> inline bool ObjectProperty<T>::isAcceptableObjectTag (const std::string& objectTypeTag) const { return Object::isObjectTypeDerivedFrom<T>(objectTypeTag); } template <class T> inline bool ObjectProperty<T>::isEqualTo(const AbstractProperty& other) const { // Check here rather than in base class because the old // Property_Deprecated implementation can't copy this flag right. if (this->getValueIsDefault() != other.getValueIsDefault()) return false; assert(this->size() == other.size()); // base class checked const ObjectProperty& otherO = ObjectProperty::getAs(other); for (int i=0; i<objects.size(); ++i) { const T* const thisp = objects[i].get(); const T* const otherp = otherO.objects[i].get(); if (thisp == otherp) continue; // same object or both null if (!(thisp && otherp)) return false; // only one is null; they are different if (!(*thisp == *otherp)) // delegate to object's operator==() return false; } return true; } // Property element is a compound element, consisting of subelements // each of which is one of the object values. //template <class T> inline void //ObjectProperty<T>::readFromXMLElement // (SimTK::Xml::Element& propertyElement, // int versionNumber) //{ // clearValues(); // // LOOP THROUGH PROPERTY ELEMENT'S CHILD ELEMENTS // // Each element is expected to be an Object of some type given // // by the element's tag; that type must be derived from O or we // // can't store it in this property. // int objectsFound = 0; // SimTK::Xml::element_iterator iter = propertyElement.element_begin(); // for (; iter != propertyElement.element_end(); ++iter) { // const SimTK::String& objTypeTag = iter->getElementTag(); // // const Object* registeredObj = // Object::getDefaultInstanceOfType(objTypeTag); // // if (!registeredObj) { // std::cerr // << "Encountered unrecognized Object typename " // << objTypeTag << " while reading property " << this->getName() // << ". There is no registered Object of this type; ignoring.\n"; // continue; // } // // // Check that the object type found is derived from T. // if (!dynamic_cast<const T*>(registeredObj)) { // std::cerr << "Object type " << objTypeTag // << " wrong for " << objectClassName // << " property " << this->getName() // << "; ignoring.\n"; // continue; // } // ++objectsFound; // // if (objectsFound > this->getMaxListSize()) // continue; // ignore this one // // // Create an Object of the element tag's type. // Object* object = Object::newInstanceOfType(objTypeTag); // assert(object); // we just checked above // object->readObjectFromXMLNodeOrFile(*iter, versionNumber); // // T* objectT = dynamic_cast<T*>(object); // assert(objectT); // should have worked by construction // adoptAndAppendValueVirtual(objectT); // don't copy // } // // if (objectsFound < this->getMinListSize()) { // std::cerr << "Got " << objectsFound // << " object values for Property " // << this->getName() << " but the minimum is " // << this->getMinListSize() << ". Continuing anyway.\n"; // } // if (objectsFound > this->getMaxListSize()) { // std::cerr << "Got " << objectsFound // << " object values for Property " // << this->getName() << " but the maximum is " // << this->getMaxListSize() << ". Ignoring the rest.\n"; // } //} // Each object value serializes itself into a subelement of the given // property element. //template <class T> inline void //ObjectProperty<T>::writeToXMLElement // (SimTK::Xml::Element& propertyElement) const //{ // for (int i=0; i < objects.size(); ++i) // (objects[i])->updateXMLNode(propertyElement); //} template <class T> inline void ObjectProperty<T>::setValueAsObject(const Object& obj, int index) { if (index < 0 && this->getMaxListSize()==1) index = 0; T* newObjT = dynamic_cast<T*>(obj.clone()); if (newObjT == NULL) throw OpenSim::Exception ("ObjectProperty<T>::setValueAsObject(): the supplied object" + obj.getName() + " was of type " + obj.getConcreteClassName() + " which can't be stored in this " + objectClassName + " property " + this->getName()); objects[index] = newObjT; } /** @endcond **/ //============================================================================== // ABSTRACT PROPERTY TEMPLATE METHODS //============================================================================== // TODO: these are defined here in order to provide support for the old // deprecated property system under the AbstractProperty umbrella. Move to // Property.h when the deprecated code is removed. template <class T> inline const T& AbstractProperty:: getValue(int index) const { //TODO: temporary support for obsolete properties const Property_Deprecated* pd = dynamic_cast<const Property_Deprecated*>(this); if (pd) { if (pd->isArrayProperty()) { return pd->getValueArray<T>()[index]; } else { return pd->getValue<T>(); } } const Property<T>* p = dynamic_cast<const Property<T>*>(this); if (p == NULL) throw Exception("AbstractProperty::getValue(): property " + getName() + " is not of type " + std::string(SimTK::NiceTypeName<T>::name())); return p->getValue(index); } template <class T> inline T& AbstractProperty:: updValue(int index) { setValueIsDefault(false); // assume it is being changed //TODO: temporary support for obsolete properties Property_Deprecated* pd = dynamic_cast<Property_Deprecated*>(this); if (pd) { return pd->isArrayProperty() ? pd->getValueArray<T>()[index] : pd->getValue<T>(); } Property<T>* p = dynamic_cast<Property<T>*>(this); if (p == NULL) throw Exception("AbstractProperty::updValue(): property " + getName() + " is not of type " + std::string(SimTK::NiceTypeName<T>::name())); return p->updValue(index); } template <class T> inline int AbstractProperty:: appendValue(const T& value) { setValueIsDefault(false); //TODO: temporary support for obsolete properties Property_Deprecated* pd = dynamic_cast<Property_Deprecated*>(this); if (pd) { if (!pd->isArrayProperty()) throw Exception ("AbstractProperty::appendValue(): deprecated property " + getName() + " is not an Array property; can't append."); pd->getValueArray<T>().append(value); return pd->getNumValues()-1; } Property<T>* p = dynamic_cast<Property<T>*>(this); if (p == NULL) throw Exception("AbstractProperty::appendValue(): property " + getName() + " is not of type " + std::string(SimTK::NiceTypeName<T>::name())); return p->appendValue(value); } }; //namespace #endif // OPENSIM_OBJECT_H_
[ "antoinefalisse@gmail.com" ]
antoinefalisse@gmail.com
0e7d6b26dd9a30e7308077ddac83dec2faa83ae5
62628dc5245c4612d001c7f0e7149e4e9a59429c
/Programas/c++/CIRCULO.CPP
84cd06fc0dac3378ddcfbd0895777e2d942e5082
[ "CC0-1.0" ]
permissive
felipeescallon/lenguajes_programacion
b3ae3477765b3100b8b454b1868e19f3a0cfc64c
5b88bf2a95492e799c94e414997365a14db05c05
refs/heads/main
2023-07-13T01:37:29.360547
2021-08-26T14:42:20
2021-08-26T14:42:20
386,758,230
1
0
null
null
null
null
IBM852
C++
false
false
403
cpp
//Archivo circulo.cpp //Definición de la clase circulo #include "figuras.h" circulo_figura::circulo_figura(double xc, double yc, double r) { x=xc; y=yc; radio=r; } double circulo_figura::calcular_area(void) const { return(3.141592*radio*radio); } void circulo_figura::dibujar(void) const { cout<<"Dibujar circulo de radio " <<radio<<"con centro en "<<x<<" , " <<y<<endl; }
[ "noreply@github.com" ]
felipeescallon.noreply@github.com
7617dbd123c1e8b8d26f318a6d4083cc39693096
b71b8bd385c207dffda39d96c7bee5f2ccce946c
/testcases/CWE127_Buffer_Underread/s03/CWE127_Buffer_Underread__new_wchar_t_loop_15.cpp
11025ea1cf2a212d1b277ccbd0d7ae41d4b34ede
[]
no_license
Sporknugget/Juliet_prep
e9bda84a30bdc7938bafe338b4ab2e361449eda5
97d8922244d3d79b62496ede4636199837e8b971
refs/heads/master
2023-05-05T14:41:30.243718
2021-05-25T16:18:13
2021-05-25T16:18:13
369,334,230
0
0
null
null
null
null
UTF-8
C++
false
false
4,382
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE127_Buffer_Underread__new_wchar_t_loop_15.cpp Label Definition File: CWE127_Buffer_Underread__new.label.xml Template File: sources-sink-15.tmpl.cpp */ /* * @description * CWE: 127 Buffer Under-read * BadSource: Set data pointer to before the allocated memory buffer * GoodSource: Set data pointer to the allocated memory buffer * Sink: loop * BadSink : Copy data to string using a loop * Flow Variant: 15 Control flow: switch(6) * * */ #include "std_testcase.h" #include <wchar.h> namespace CWE127_Buffer_Underread__new_wchar_t_loop_15 { #ifndef OMITBAD void bad() { wchar_t * data; data = NULL; { wchar_t * dataBuffer = new wchar_t[100]; wmemset(dataBuffer, L'A', 100-1); dataBuffer[100-1] = L'\0'; /* FLAW: Set data pointer to before the allocated memory buffer */ data = dataBuffer - 8; } { size_t i; wchar_t dest[100]; wmemset(dest, L'C', 100-1); /* fill with 'C's */ dest[100-1] = L'\0'; /* null terminate */ /* POTENTIAL FLAW: Possibly copy from a memory location located before the source buffer */ for (i = 0; i < 100; i++) { dest[i] = data[i]; } /* Ensure null termination */ dest[100-1] = L'\0'; printWLine(dest); /* INCIDENTAL CWE-401: Memory Leak - data may not point to location * returned by new [] so can't safely call delete [] on it */ } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B1() - use goodsource and badsink by changing the switch to switch(5) */ static void goodG2B1() { wchar_t * data; data = NULL; { wchar_t * dataBuffer = new wchar_t[100]; wmemset(dataBuffer, L'A', 100-1); dataBuffer[100-1] = L'\0'; /* FIX: Set data pointer to the allocated memory buffer */ data = dataBuffer; } { size_t i; wchar_t dest[100]; wmemset(dest, L'C', 100-1); /* fill with 'C's */ dest[100-1] = L'\0'; /* null terminate */ /* POTENTIAL FLAW: Possibly copy from a memory location located before the source buffer */ for (i = 0; i < 100; i++) { dest[i] = data[i]; } /* Ensure null termination */ dest[100-1] = L'\0'; printWLine(dest); /* INCIDENTAL CWE-401: Memory Leak - data may not point to location * returned by new [] so can't safely call delete [] on it */ } } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the switch */ static void goodG2B2() { wchar_t * data; data = NULL; { wchar_t * dataBuffer = new wchar_t[100]; wmemset(dataBuffer, L'A', 100-1); dataBuffer[100-1] = L'\0'; /* FIX: Set data pointer to the allocated memory buffer */ data = dataBuffer; } { size_t i; wchar_t dest[100]; wmemset(dest, L'C', 100-1); /* fill with 'C's */ dest[100-1] = L'\0'; /* null terminate */ /* POTENTIAL FLAW: Possibly copy from a memory location located before the source buffer */ for (i = 0; i < 100; i++) { dest[i] = data[i]; } /* Ensure null termination */ dest[100-1] = L'\0'; printWLine(dest); /* INCIDENTAL CWE-401: Memory Leak - data may not point to location * returned by new [] so can't safely call delete [] on it */ } } void good() { goodG2B1(); goodG2B2(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE127_Buffer_Underread__new_wchar_t_loop_15; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
[ "jaredzap@rams.colostate.edu" ]
jaredzap@rams.colostate.edu
bbc8feeb62ad445a0aee17e332d273fce65fb763
72b564d98e01af9a54c5735bdd894e7a18712cac
/C++/8.4.cpp
3267b9a6bcb86355d746a817edd9cff9f71e416b
[]
no_license
linyasha/BSU
0a16bfd87705034caa749b0bc5a3d48129c250f9
731e3d66e87a7fecb49abfc94187a06ec0dafff9
refs/heads/main
2023-04-16T03:46:25.949583
2021-04-22T23:17:05
2021-04-22T23:17:05
328,188,020
0
0
null
null
null
null
UTF-8
C++
false
false
4,430
cpp
#include <iostream> #include <initializer_list> #include <assert.h> using std::istream; using std::ostream; using std::cout; using std::cin; using std::initializer_list; template <typename T> struct Node { public: T symbol; Node<T>* next; }; template <typename T> class LinkedList { private: Node<T>* head; int count = 0; public: LinkedList() { this->head = nullptr; } Node<T>* ghead() const { return this->head; } bool is_empty() { return this->head == nullptr; } int size() const { return count; } void insert(T b) { Node<T>* a = new Node<T> {b}; if(is_empty()) { this->head = a; a->next = nullptr; } else { Node<T>* help = this->head; for(int i = 1; i < count; i++) { help = help->next; } help->next = a; a->next = nullptr; } count++; } void new_head(T value) { if(is_empty()) insert(value); else this->head->symbol = value; } Node<T>* element(int n) { assert(!(count == 0 || n > count)); Node<T>* a = this->head; for(int i = 1; i < n; i++) { a = a->next; } return a; } const Node<T>* element(int n) const { assert(!(count == 0 || n > count)); Node<T>* a = this->head; for(int i = 1; i < n; i++) { a = a->next; } return a; } LinkedList(initializer_list<T> other) { this->head = nullptr; for(int i = 0; i < other.size(); i++) { insert(*(other.begin() + i)); } cout << '\n'; } LinkedList(const LinkedList<T>& a ) { this->head = nullptr; Node<T>* help = a.ghead(); for(int i = 1; i <= a.size(); i++) { insert(help->symbol); help = help->next; } } void operator=(const LinkedList<T>& a) { while(!(is_empty())) { if(count == 1) remove(nullptr); else remove(this->head); } Node<T>* help = a.ghead(); for(int i = 1; i <= a.size(); i++) { insert(help->symbol); help = help->next; } } void remove(Node<T>* a) { if(a != nullptr) assert(!is_empty() && a->next != nullptr); if(a == nullptr){ Node<T>* help = this->head->next; delete this->head; this->head = help; } else { Node<T>* help = a->next->next; delete a->next; a->next = help; } count--; } void delete_list() { while(!(is_empty())) { if(count == 1) remove(nullptr); else remove(this->head); } } ~LinkedList() { delete_list(); } }; template<typename T> ostream& operator<<(ostream& out, LinkedList<T>& a) { if(a.ghead() == nullptr) { out << "Clear =(" << '\n'; return out; } Node<T>* help = a.ghead(); for(int i = 0; i < a.size(); i++) { out << help->symbol << ' '; help = help->next; } out << '\n'; return out; } template<typename T> LinkedList<T> func(const LinkedList<T>& l1, LinkedList<T>& l2) { LinkedList<T> new_list; int size_1 = l1.size(); int size_2 = l2.size(); Node<T>* help_1 = l1.ghead(); for(int i = 1; i <= size_1; i++) { bool help = false; T symbol = help_1->symbol; Node<T>* help_2 = l2.ghead(); Node<T>* help_2_before = nullptr; for(int j = 1; j <= size_2; j++) { if(symbol == help_2->symbol) { if(j == 1) l2.remove(nullptr); else l2.remove(help_2_before); j--; size_2--; help = 1; } help_2_before = help_2; help_2 = help_2->next; } if(help) new_list.insert(symbol); help_1 = help_1->next; } return new_list; } int main() { LinkedList<char> a {'h', 'e', 'l', 'l', '2'}; LinkedList<char> b {'l','w','e','a','s','d','h','l','1'}; LinkedList<char> help(b); LinkedList<char> c = func<char>(a, help); cout << c; }
[ "alynko17@gmail.com" ]
alynko17@gmail.com
2e97bd740ac111cad1791b3f459cfdeb17bf6636
fb381224be13ed84e8e63bd7bf013dd10d58d924
/Code/Editor/EditorFramework/Panels/CVarPanel/CVarPanel.moc.h
80d1f221ac2e9872bd1018407cf28b8ef3a847c8
[ "MIT" ]
permissive
bethau/ezEngine
1b768f95801dd2367dc30675f8febb5cbb625819
059684c8d9ed7e33f8e68f218ff42a7decf668ee
refs/heads/master
2022-08-22T06:48:55.549276
2020-02-11T23:36:43
2020-02-11T23:36:43
247,667,175
0
0
MIT
2020-03-16T09:57:54
2020-03-16T09:57:53
null
UTF-8
C++
false
false
1,156
h
#pragma once #include <Foundation/Basics.h> #include <EditorFramework/EditorFrameworkDLL.h> #include <EditorFramework/IPC/EngineProcessConnection.h> #include <GuiFoundation/DockPanels/ApplicationPanel.moc.h> #include <ToolsFoundation/Project/ToolsProject.h> #include <GuiFoundation/Widgets/CVarWidget.moc.h> #include <Foundation/Containers/Map.h> class ezQtCVarWidget; class EZ_EDITORFRAMEWORK_DLL ezQtCVarPanel : public ezQtApplicationPanel { Q_OBJECT EZ_DECLARE_SINGLETON(ezQtCVarPanel); public: ezQtCVarPanel(); ~ezQtCVarPanel(); protected: virtual void ToolsProjectEventHandler(const ezToolsProjectEvent& e) override; private Q_SLOTS: void UpdateUI(); void BoolChanged(const char* szCVar, bool newValue); void FloatChanged(const char* szCVar, float newValue); void IntChanged(const char* szCVar, int newValue); void StringChanged(const char* szCVar, const char* newValue); private: void EngineProcessMsgHandler(const ezEditorEngineProcessConnection::Event& e); ezQtCVarWidget* m_pCVarWidget = nullptr; ezMap<ezString, ezCVarWidgetData> m_EngineCVarState; bool m_bUpdateUI = false; bool m_bRebuildUI = false; };
[ "jan@krassnigg.de" ]
jan@krassnigg.de
1c13f5f3ff912e6322510a9b9a156a36059e7803
44611973ae357ec3cb078f0c0d95b8efd84c9eff
/Arduino/PragProg/ultrasonic/simple/simple.ino
65bcf0720e9995aa9561c6126b07dcf97a4b3689
[]
no_license
LeipeLeon/interactive
29e9fe5afb7dd81e9c1b3970310422ac76f007eb
642273fe10f51dfd40e14295792873bd047a1849
refs/heads/master
2021-01-01T18:34:37.042065
2012-01-06T18:38:36
2012-01-06T18:38:36
1,372,775
1
0
null
null
null
null
UTF-8
C++
false
false
1,027
ino
const unsigned int PING_SENSOR_IO_PIN = 7; const unsigned int BAUD_RATE = 9600; void setup() { Serial.begin(BAUD_RATE); } void loop() { pinMode(PING_SENSOR_IO_PIN, OUTPUT); // <label id="code.input.start_init_pin"/> digitalWrite(PING_SENSOR_IO_PIN, LOW); delayMicroseconds(2); // <label id="code.input.end_init_pin"/> digitalWrite(PING_SENSOR_IO_PIN, HIGH); // <label id="code.input.start_send_chirp"/> delayMicroseconds(5); digitalWrite(PING_SENSOR_IO_PIN, LOW); // <label id="code.input.end_send_chirp"/> pinMode(PING_SENSOR_IO_PIN, INPUT); const unsigned long duration = pulseIn(PING_SENSOR_IO_PIN, HIGH); // <label id="code.input.read_duration"/> if (duration == 0) { Serial.println("Warning: We did not get a pulse from sensor."); } else { Serial.print("Distance to nearest object: "); Serial.print(microseconds_to_cm(duration)); Serial.println(" cm"); } delay(100); } unsigned long microseconds_to_cm(const unsigned long microseconds) { return microseconds / 29 / 2; }
[ "leipeleon@gmail.com" ]
leipeleon@gmail.com
8e83e7c1e24e3fc8db907f42f5defc9a57b9c501
24d9a441a4eedfa92e6d10964b5efe390694845f
/CANIMAL.cpp
31eb3fb02453fcc8b656f8062459b32f06341c5c
[]
no_license
NguyenTrongDat1753038/KTLT_Project_CrossingRoad
13280d4d213177c8ce78130a0c3b6478da5924ca
56ccb1cf318ce7ce7b3da95fe0494dbfc8aefd75
refs/heads/master
2022-12-10T08:30:12.729874
2020-09-02T14:52:32
2020-09-02T14:52:32
292,188,148
0
0
null
null
null
null
UTF-8
C++
false
false
623
cpp
#include "Header.h" CANIMAL::CANIMAL(int x, int y) { mX = x; mY = y; if (x >= ENDLANE) Way = -1; else Way = 1; } void CANIMAL::Move(int x, int y) { if (mX <= ENDLANE + STARTLANE - 1 && mX >= STARTLANE + 1) { GotoXY(mX - 2, mY - 1); cout << " "; GotoXY(mX - 2, mY); cout << " "; GotoXY(mX - 1, mY + 1); cout << "___"; } Draw(mX, mY); Sleep(10); } bool CANIMAL::IsDone() { if ((Way == -1 && mX <= STARTLANE + 3) || (Way == 1 && mX >= ENDLANE)) { GotoXY(mX - 2, mY - 1); cout << " "; GotoXY(mX - 2, mY); cout << " "; GotoXY(mX - 1, mY + 1); cout << "___"; return true; } return false; }
[ "48618432+NguyenTrongDat1753038@users.noreply.github.com" ]
48618432+NguyenTrongDat1753038@users.noreply.github.com
bd004f47e0448d3542c25db477808467fa3e4e3c
bc45f9358eda08ed4a4800c4742341d0c2f3f984
/src/dmath/util.h
bda6ba0fddcbebb70cb7eb834eee010ac849f02c
[]
no_license
DamonDeng/katen
e89081aeaee81b4c510f0c4154a96dda03cc1efe
813462b61f8ad835fafb705f51ef2bd0d02670ec
refs/heads/master
2020-06-01T02:13:45.334160
2017-08-03T07:16:19
2017-08-03T07:16:19
94,058,673
0
0
null
null
null
null
UTF-8
C++
false
false
995
h
#ifndef DAMONDENG_KATEN_MATHUTIL #define DAMONDENG_KATEN_MATHUTIL #include <iostream> #include <time.h> #include <random> using namespace std; namespace katen{ namespace math{ class Util{ public: Util(); static vector<double> softmax(vector<double> inputValue); static double crossEntropy(const double inputValue[], size_t valueNumber, double labelValue[]); static vector<double> softmaxCrossEntropyBP(vector<double> softmaxOutput, long rightPosition); static double dotProduct(const double inputValue[], size_t valueNumber, const double weight[]); static double dotProduct(vector<double> inputValue, const vector<double> weight); //static int dotProductBP(const double inputValue[], double gradient[]); //static double randomDouble(double min, double max); private: //static std::default_random_engine random(time(NULL)); //static std::uniform_real_distribution<double> dis(-1.0, 1.0); }; } } #endif
[ "dengmingxuan@hotmail.com" ]
dengmingxuan@hotmail.com
9b42875c893db2ca76c90e85c4a8d0bf4591208e
53459785cde3f53732dcdb42ad96b65f7aa1fccc
/source/Network/NetworkAPI/Translator.h
7913c16a5355ea98e3c9ccf56ad6feed7052f8c1
[]
no_license
dean11/NoEdge
7f33f775c8083b9ba2861d45b68082059da3f870
2cc8a59b8155acd3a3f939716da339e5a90cc5db
refs/heads/master
2021-01-18T03:01:10.586525
2015-01-15T21:38:13
2015-01-15T21:38:13
29,315,116
1
0
null
null
null
null
UTF-8
C++
false
false
1,426
h
#ifndef NETWORK_DEPENDENCIES_TRANSLATOR_H #define NETWORK_DEPENDENCIES_TRANSLATOR_H ////////////////////////////////// // Created by Sam Svensson 2013 // // ----------------------------// // Packs our dynamic protocols // ////////////////////////////////// /* It packs a header in front of the actual message. Header looks like this: - Size of the entire package - String containing all the types of data that is packed in the package. */ /* Possible optimizing: If there are several of the same type of data in a row, we can instead of saving a character for each type we can instead save a number and the character. Example: If we are packing 100 floats. "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF..." Instead of that we can do this: "100F" */ #include "NetworkAPI_Preprocessor.h" namespace Oyster { namespace Network { extern "C" { class OysterByte; class CustomNetProtocol; class NET_API_EXPORT Translator { public: Translator (); ~Translator(); Translator(const Translator& obj); const Translator& operator=(const Translator& obj); void Pack(OysterByte &bytes, CustomNetProtocol& protocol); //Returns false if it discovers any faulty stuff with the package. bool Unpack(CustomNetProtocol& protocol, OysterByte &bytes); private: struct PrivateData; PrivateData* privateData; }; } } } #endif
[ "carl.dennis.andersen@gmail.com" ]
carl.dennis.andersen@gmail.com
70511c1171dbf5178920c412b2230b1c8341cc63
0b8a045ddacc213a48c45645e7f83ca23da6fa77
/Practica4v1/Practica5/claveValor.h
5fa2b3213f9a3ebaafd65a803e106a214348e2a9
[ "MIT" ]
permissive
gejors55/Programacion-en-C-
c077279708d681c5328f77a701bfaea4ac7bf981
09253535c7107773264b89a152eccdb542d83875
refs/heads/master
2020-04-13T11:52:05.711838
2018-12-26T14:44:23
2018-12-26T14:44:23
163,185,959
0
0
null
null
null
null
ISO-8859-1
C++
false
false
1,159
h
#ifndef claveValor_h #define claveValor_h #include <string> using namespace std; #include "listaCadenas.h" const int MAXCLAVES = 200; typedef struct{ string clave; tListaCadenas valor;//lista de archivo donde estan las claves }tRegistroIndicePalabras; typedef struct{ int tam; tRegistroIndicePalabras datos[MAXCLAVES]; }tIndicePalabras; //Devuelve el tamaño de la tabla; int getTamanno(const tIndicePalabras & l); //Devuelve elregistro en pos; tRegistroIndicePalabras getRegistro(const tIndicePalabras & l, int pos); //Devuelve si la palabra es una clave en la tabla; bool esta(const tIndicePalabras & l, const string & s, int & pos); //dada una clave que está en la tabla devuelve la lista de cadenas asociada a esa clave. tListaCadenas buscar(const tIndicePalabras & l, const string & s); //Si palabra es ya una clave de la tabla, añade nombreArchivo a la lista de archivos correspondiente. //Si no, crea un registro nuevo con esa información. void insertar(tIndicePalabras & idx, const string & palabra, const string & nombreArchivo); //Imprime la tabla; void imprimir(const tIndicePalabras & idx); #endif
[ "noreply@github.com" ]
gejors55.noreply@github.com
228d7628a84fda5e9f4bb32ee0a9238028dc8521
39719ced2451b97c266568e2d9364bfe90ab3498
/Source/zzExamples/CRagdoll.cpp
06a1727bb8d83b4a9700a7e5e1e0f7b0ece38a0e
[ "MIT" ]
permissive
shanefarris/CoreGameEngine
74ae026cdc443242fa80fe9802f5739c1064fb66
5bef275d1cd4e84aa059f2f4f9e97bfa2414d000
refs/heads/master
2020-05-07T12:19:23.055995
2019-04-11T14:10:16
2019-04-11T14:10:16
180,496,793
3
2
null
null
null
null
UTF-8
C++
false
false
15,311
cpp
#include "CRagdoll.h" #include "Nxp.h" #include "NxActor.h" using namespace Core; using namespace Core::Physics; CRagdoll::CRagdoll(String fileName, SceneNode *characterSN, String id, NxOgre::Scene *PHXScene, f32 bodyDensity) { m_CharacterNode = characterSN; m_PHYSScene=PHXScene; m_CharacterID=id; m_PositionControllingBone=NULL; m_BodyDensity=bodyDensity; m_BonesCounter=0; ConfigFile mRagDollCfgFile; mRagDollCfgFile.loadFromResourceSystem(fileName, "General"); ConfigFile::SectionIterator seci = mRagDollCfgFile.getSectionIterator(); String secName, paramName, valueName; while (seci.hasMoreElements()) { secName = seci.peekNextKey(); ConfigFile::SettingsMultiMap *settings = seci.getNext(); ConfigFile::SettingsMultiMap::iterator i; std::map<String, String> sectionData; for (i = settings->begin(); i != settings->end(); ++i) { paramName = i->first; valueName = i->second; sectionData[paramName]=valueName; } if (secName!="") { _parseSectionData(secName, sectionData); } } if (m_BonesCounter==15) { setControlToBones(); setAllBonesToManualControll(true); setRagdollBindPose(); setAllBonesToManualControll(false); addJoints(); //...as we dont have root bone attached to Bone Actor, we use Pelvis BA instead if (!m_PositionControllingBone) m_PositionControllingBone=getBoneBoneActorBindByName("Pelvis"); } else LogManager::getSingleton().logMessage( "Not enough bones declared in file: " + fileName + ". CRagdoll was not created!" ); } void CRagdoll::_parseSectionData( String secName, std::map<String, String> section ) { Vector3 dimensions = StringConverter::parseVector3( section["dimensions"] ); Vector3 offset = StringConverter::parseVector3( section["offset"] ); Entity* ent = ( Entity* ) m_CharacterNode->getAttachedObject( 0 ); m_BoneBoneActorBind[m_BonesCounter].name = secName; m_BoneBoneActorBind[m_BonesCounter].bone = ent->getSkeleton()->getBone( section["boneName"] ); m_BoneBoneActorBind[m_BonesCounter].BAoffset = offset; NxOgre::RigidBodyDescription desc; //desc.reset(); desc.mMass = 0.0; desc.mDensity = m_BodyDensity; desc.mType = NxOgre::Enums::RigidBodyType_Dynamic; desc.mBodyFlags = NxOgre::Enums::ActorFlags_DisableCollision; NxOgre::Actor* actor = NULL; if (section["actorShape"]==String("sphere")) { actor = m_BoneBoneActorBind[m_BonesCounter].BoneActor = m_PHYSScene->createActor( new NxOgre::Sphere(dimensions.x), Matrix44_Identity, desc); actor->setAngularDamping(actor->getAngularDamping() * 2); actor->setLinearDamping(actor->getLinearDamping() * 2); actor->setSleepAngularVelocity(actor->getSleepAngularVelocity() * 2); actor->setSleepLinearVelocity(actor->getSleepLinearVelocity() * 2); } if (section["actorShape"]==String("cube")) { actor = m_BoneBoneActorBind[m_BonesCounter].BoneActor = m_PHYSScene->createActor( new NxOgre::Box(dimensions.x,dimensions.y,dimensions.z), Matrix44_Identity, desc); actor->setAngularDamping(actor->getAngularDamping() * 2); actor->setLinearDamping(actor->getLinearDamping() * 2); actor->setSleepAngularVelocity(actor->getSleepAngularVelocity() * 2); actor->setSleepLinearVelocity(actor->getSleepLinearVelocity() * 2); } if (section["actorShape"]==String("capsule")) { actor = m_BoneBoneActorBind[m_BonesCounter].BoneActor = m_PHYSScene->createActor( new NxOgre::Capsule(dimensions.x,dimensions.y), Matrix44_Identity, desc); actor->setAngularDamping(actor->getAngularDamping() * 2); actor->setLinearDamping(actor->getLinearDamping() * 2); actor->setSleepAngularVelocity(actor->getSleepAngularVelocity() * 2); actor->setSleepLinearVelocity(actor->getSleepLinearVelocity() * 2); } //he have found a root bone - use it for character positioning if (!m_BoneBoneActorBind[m_BonesCounter].bone->getParent()) m_PositionControllingBone=&m_BoneBoneActorBind[m_BonesCounter]; else { String test = m_BoneBoneActorBind[m_BonesCounter].bone->getParent()->getName(); test = m_BoneBoneActorBind[m_BonesCounter].bone->getName(); int i = 0; } m_BonesCounter++; } void CRagdoll::setControlToBones() { m_ControlToBones=true; m_ControlToBoneActors=false; _setControlToBones(); } void CRagdoll::setControlToBoneActors() { m_ControlToBoneActors=true; m_ControlToBones=false; _setControlToBoneActors(); } void CRagdoll::_setControlToBones() { for (int i=0; i<15; i++) { m_BoneBoneActorBind[i].BoneActor->getNxActor()->raiseActorFlag( NX_AF_DISABLE_COLLISION ); m_BoneBoneActorBind[i].BoneActor->getNxActor()->raiseBodyFlag( NX_BF_KINEMATIC ); m_BoneBoneActorBind[i].BoneActor->putToSleep(); } } void CRagdoll::_setControlToBoneActors() { updateBoneActors(); setAllBonesToManualControll(true); resetAllBones(); //disabling all animations Entity* e = ( Entity* ) m_CharacterNode->getAttachedObject( 0 ); AnimationStateSet* set = e->getAllAnimationStates(); AnimationStateIterator it = set->getAnimationStateIterator(); AnimationState *anim; while( it.hasMoreElements() ) { anim = it.getNext(); anim->setTimePosition( 0 ); anim->setEnabled( false ); anim->setWeight( 0 ); } for( int i = 0; i < 15; i++ ) { m_BoneBoneActorBind[i].BoneActor->getNxActor()->clearActorFlag(NX_AF_DISABLE_COLLISION); m_BoneBoneActorBind[i].BoneActor->getNxActor()->clearBodyFlag(NX_BF_KINEMATIC); m_BoneBoneActorBind[i].BoneActor->wakeUp(Real(20.0 * 0.02)); m_BoneBoneActorBind[i].BoneActor->setAngularDamping(1.0); m_BoneBoneActorBind[i].BoneActor->setLinearDamping(1.0); } } void CRagdoll::updateBoneActors() { Vector3 OgrePosition; Quaternion PhysxRotation, OgreGlobalQuat; for( int i = 0; i < 15; i++ ) { //Get parent and child Positions Vector3 bonePos = m_BoneBoneActorBind[i].bone->_getDerivedPosition(); Vector3 nextBonePos = m_BoneBoneActorBind[i].bone->getChild(0)->_getDerivedPosition(); //get vector difference between parent and child Vector3 difference = nextBonePos - bonePos; Vector3 forward = difference.normalisedCopy(); //Get bone Orientation and re-align Quaternion new_orient = Vector3::UNIT_Y.getRotationTo( forward ); //mid point of bone Vector3 pos = bonePos + ( forward * ( difference.length() * 0.5f ) ); //adjust Bone Actor placement pos.x += m_BoneBoneActorBind[i].BAoffset.x; pos.y += m_BoneBoneActorBind[i].BAoffset.y; pos.z += m_BoneBoneActorBind[i].BAoffset.z; //update Bone Actor m_BoneBoneActorBind[i].BoneActor->setGlobalPosition( pos + m_CharacterNode->_getDerivedPosition()); m_BoneBoneActorBind[i].BoneActor->setGlobalOrientation( NxOgre::Matrix33(new_orient) ); } } void CRagdoll::updateBones() { Quaternion PhysxRotation, OgreGlobalQuat, NodeRotationInverse = m_CharacterNode->getParentSceneNode()->getOrientation().Inverse(); // Loop through all bones for( int i = 0; i < 15; i++ ) { PhysxRotation = m_BoneBoneActorBind[i].BoneActor->getGlobalOrientationQuat().as<Quaternion>() * m_BoneBoneActorBind[i].BoneActorGlobalBindOrientationInverse; Ogre::Quaternion ParentInverse = NodeRotationInverse; if ( m_BoneBoneActorBind[i].bone->getParent() ) ParentInverse = m_BoneBoneActorBind[i].bone->getParent()->_getDerivedOrientation().Inverse() * NodeRotationInverse; else { reVector3Df pos = m_BoneBoneActorBind[i].BoneActor->getGlobalPosition().as<reVector3Df>() - m_CharacterNode->getParentSceneNode()->getOrientation() * m_BoneBoneActorBind[i].bone->getPosition(); m_CharacterNode->getParentSceneNode()->setPosition( pos); } OgreGlobalQuat = PhysxRotation * m_BoneBoneActorBind[i].BoneGlobalBindOrientation; m_BoneBoneActorBind[i].bone->setOrientation( ParentInverse * OgreGlobalQuat ); } Ogre::Vector3 newPos = m_PositionControllingBone->BoneActor->getGlobalPosition().as<reVector3Df>() - m_CharacterNode->getParentSceneNode()->getOrientation() * m_PositionControllingBone->bone->getPosition() - m_PositionControllingBone->BAoffset; m_CharacterNode->getParentSceneNode()->setPosition( newPos ); } void CRagdoll::update() { if (m_ControlToBones) updateBoneActors(); if (m_ControlToBoneActors) updateBones(); } void CRagdoll::addJoints() { NxOgre::RevoluteJointDescription rjd; NxOgre::JointLimitPairDescription rjdLimit; NxOgre::JointLimitDescription limit1; limit1.mValue = -0.75*NxPi; NxOgre::JointLimitDescription limit2; limit2.mValue = 0; rjdLimit.first = limit1; rjdLimit.second = limit2; rjd.mLimit = rjdLimit; rjd.mJointFlags = 0; NxOgre::SphericalJointDescription sjd; sjd.mJointFlags = 0; NxOgre::JointLimitDescription limit3; limit3.mValue = -(NxReal)0.025*NxPi; limit3.mRestitution = 0.5; NxOgre::JointLimitDescription limit4; limit4.mValue = (NxReal)0.025*NxPi; limit4.mRestitution = 1; sjd.mTwistLimit.first = limit3; sjd.mTwistLimit.second = limit4; sjd.mSwingLimit.mValue = (NxReal)0.15*NxPi; sjd.mSwingLimit.mRestitution = 0.5; sjd.mTwistSpring.mDamper = 1; sjd.mTwistSpring.mSpring = 0.5; sjd.mSwingSpring.mDamper = 1; sjd.mSwingSpring.mSpring = 0.5; sjd.mProjectionDistance = 0.15; sjd.mProjectionMode = NxOgre::Enums::JointProjectionMode_Point_MiniumDistance; NxOgre::SphericalJointDescription sjd2 = sjd; sjd2.mSwingLimit.mValue = 0.45*NxPi; NxOgre::JointLimitDescription limit5; limit5.mValue = -(NxReal)0.15*NxPi; NxOgre::JointLimitDescription limit6; limit6.mValue = (NxReal)0.15*NxPi; sjd2.mTwistLimit.first = limit5; sjd2.mTwistLimit.second = limit6; NxOgre::JointDescription chestDesc; chestDesc.mJointFlags = 0; NxOgre::Joint* joint = NULL; //Neck joint = m_PHYSScene->createSphericalJoint( getBoneBoneActorBindByName("Head")->BoneActor, getBoneBoneActorBindByName("Torso")->BoneActor, sjd /*,pos ,sphJointParam*/); joint->setGlobalAxis(Vector3::UNIT_Y); //Chest joint = m_PHYSScene->createFixedJoint( getBoneBoneActorBindByName("Torso")->BoneActor, getBoneBoneActorBindByName("Pelvis")->BoneActor, chestDesc); //joint->setGlobalAxis(Vector3::UNIT_Y); //Left Leg joint=m_PHYSScene->createSphericalJoint( getBoneBoneActorBindByName("Pelvis")->BoneActor, getBoneBoneActorBindByName("LeftUpLeg")->BoneActor, sjd /*,pos,sphJointParam*/); joint->setGlobalAxis(Vector3::NEGATIVE_UNIT_Y); //Left knee joint = m_PHYSScene->createRevoluteJoint( getBoneBoneActorBindByName("LeftUpLeg")->BoneActor, getBoneBoneActorBindByName("LeftLoLeg")->BoneActor, rjd/*,-Vector3::UNIT_X,pos,jp*/); //Left ankle joint = m_PHYSScene->createRevoluteJoint( getBoneBoneActorBindByName("LeftLoLeg")->BoneActor, getBoneBoneActorBindByName("LeftFoot")->BoneActor, rjd/*,Vector3::UNIT_X,pos,jp*/); //Right Leg joint = m_PHYSScene->createSphericalJoint( getBoneBoneActorBindByName("Pelvis")->BoneActor, getBoneBoneActorBindByName("RightUpLeg")->BoneActor, sjd /*,pos,sphJointParam*/); joint->setGlobalAxis(Vector3::NEGATIVE_UNIT_Y); //Right knee joint = m_PHYSScene->createRevoluteJoint( getBoneBoneActorBindByName("RightUpLeg")->BoneActor, getBoneBoneActorBindByName("RightLoLeg")->BoneActor, rjd /*,-Vector3::UNIT_X,pos,jp*/); //Right ankle joint = m_PHYSScene->createRevoluteJoint( getBoneBoneActorBindByName("RightLoLeg")->BoneActor, getBoneBoneActorBindByName("RightFoot")->BoneActor, rjd /*,Vector3::UNIT_X,pos,jp*/); //Left shoulder joint = m_PHYSScene->createSphericalJoint( getBoneBoneActorBindByName("Torso")->BoneActor, getBoneBoneActorBindByName("LeftUpArm")->BoneActor, sjd2 /*, pos, sphJointParam2*/); joint->setGlobalAxis(Vector3::UNIT_X); //Left elbow joint = m_PHYSScene->createRevoluteJoint( getBoneBoneActorBindByName("LeftUpArm")->BoneActor, getBoneBoneActorBindByName("LeftLoArm")->BoneActor, rjd /*,Vector3::UNIT_Y,pos,jp*/); //Left hand joint = m_PHYSScene->createSphericalJoint( getBoneBoneActorBindByName("LeftLoArm")->BoneActor, getBoneBoneActorBindByName("LeftHand")->BoneActor, sjd /*, pos, sphJointParam*/); //Right shoulder joint = m_PHYSScene->createSphericalJoint( getBoneBoneActorBindByName("Torso")->BoneActor, getBoneBoneActorBindByName("RightUpArm")->BoneActor, sjd2 /*, pos, sphJointParam2*/); joint->setGlobalAxis(Vector3::NEGATIVE_UNIT_X); //Right elbow joint = m_PHYSScene->createRevoluteJoint( getBoneBoneActorBindByName("RightUpArm")->BoneActor, getBoneBoneActorBindByName("RightLoArm")->BoneActor, rjd /*,Vector3::UNIT_Y,pos,jp*/); //Right hand joint = m_PHYSScene->createSphericalJoint( getBoneBoneActorBindByName("RightLoArm")->BoneActor, getBoneBoneActorBindByName("RightHand")->BoneActor, sjd /*, pos,sphJointParam*/); } void CRagdoll::setRagdollBindPose() { updateBoneActors(); for (int i=0; i<15; i++) { m_BoneBoneActorBind[i].BoneGlobalBindOrientation = m_BoneBoneActorBind[i].bone->_getDerivedOrientation(); m_BoneBoneActorBind[i].BoneActorGlobalBindOrientationInverse = NxOgre::Quat::invert(m_BoneBoneActorBind[i].BoneActor->getGlobalOrientationQuat()).as<Quaternion>(); } } void CRagdoll::setAllBonesToManualControll(bool manual) { Entity* e = (Entity*) m_CharacterNode->getAttachedObject( 0 ); SkeletonInstance* skeletonInst = e->getSkeleton(); Skeleton::BoneIterator boneI=skeletonInst->getBoneIterator(); while(boneI.hasMoreElements()) boneI.getNext()->setManuallyControlled(manual); } void CRagdoll::resetAllBones() { Entity* e = (Entity*) m_CharacterNode->getAttachedObject( 0 ); SkeletonInstance* skeletonInst = e->getSkeleton(); Skeleton::BoneIterator boneI=skeletonInst->getBoneIterator(); while(boneI.hasMoreElements()) boneI.getNext()->reset(); } BoneBind* CRagdoll::getBoneBoneActorBindByName(String n) { for (int i=0; i<15; i++) { if (m_BoneBoneActorBind[i].name==n) return &m_BoneBoneActorBind[i]; } return NULL; } void CRagdoll::setCharacterPositionControllingBone(String n) { m_PositionControllingBone=getBoneBoneActorBindByName(n); } CRagdoll::CRagdoll(String outFileName, SceneNode* characterSN) { std::ofstream file(outFileName.c_str()); if (file) { Entity* e=(Entity*)characterSN->getAttachedObject(0); SkeletonInstance* skeletonInst = e->getSkeleton(); Skeleton::BoneIterator boneI=skeletonInst->getBoneIterator(); file<<"Creating bone lenght information from:\n"; file<<"Mesh name: "<<e->getMesh()->getName()<<"\n"; file<<"Skeleton name: "<<skeletonInst->getName()<<"\n\n"; while(boneI.hasMoreElements()) { Bone* bone=boneI.getNext(); String bName=bone->getName(); if (bone->getChild(0)) { Vector3 curr = bone->_getDerivedPosition(); Vector3 next = bone->getChild(0)->_getDerivedPosition(); Vector3 difference = next-curr; //length of bone f32 lenght = difference.length(); file<<bName<<"\t\t\t=\t"<<StringConverter::toString(lenght,3)<<"\n"; if (!bone->getParent()) file<<bName<<" is a Root Bone!\n"; } } } }
[ "farris.shane@gmail.com" ]
farris.shane@gmail.com
949ff76e485b27aa003cd533af98c42939737efe
98490ba4a6b318e9f1cc7f3c305f48ecc94342e8
/11_nibbler/nibbler/core/src/game/Party.class.hpp
7aa88a539172885df397c9326c682072532cc1d8
[]
no_license
tristandeborde/My42Projects
144266f3e561a75cffd166b5a85bf847d3052c1f
2bbfa1e060cbafeff0bf0cb334f6a27b879acc48
refs/heads/master
2021-07-09T01:13:36.432205
2020-09-28T15:25:09
2020-09-28T15:25:09
195,383,584
0
0
null
null
null
null
UTF-8
C++
false
false
1,828
hpp
#ifndef PARTY_CLASS_HPP #define PARTY_CLASS_HPP #include <unordered_set> #include <list> #include "Entity.class.hpp" #include "rules/RuleSet.class.hpp" class Party final { /* Typedefs *******************************************************************/ public: using t_dims = std::pair<size_t, size_t>; using t_entityList = std::list<Entity *>; /* Instantiation **************************************************************/ public: Party(void); ~Party(void); /* Party methods ***********************************************************/ public: // getters t_dims getDims(void) const; // game-related funcs void initGame(void); void update(void); // Entity list methods void addEntity(Entity * entity); void popEntity(Entity * entity); void popEntity(t_entity_id id); void removeAllAndResize(size_t height, size_t width); // Deleted Entity list methods void destroyEntity(Entity * entity); void removeDestroyedEntities(void); // Temporary getScore() func for Nibbler size_t getScore() const; private: // Entity list methods void _remove_all_entities(void); /* Attributes *****************************************************************/ public: // Entity list t_entityList entityList; // Rule set const RuleSet ruleSet; private: /* * List of entity to be destroyed. * This list is helpful when we need entities to be destroyed after computation. * we use an unordered_set in order to avoid duplicates. */ std::unordered_set<Entity *> _deletedEntityList; // dimensions of the map size_t _height {0}; size_t _width {0}; /* Coplien methods ************************************************************/ public: Party &operator=(Party const &rhs) = delete; Party(Party const &src) = delete; }; #endif // PARTY_CLASS_HPP
[ "tr.deborde@gmail.com" ]
tr.deborde@gmail.com
d582c4e12a57a63c7016b4511703ce213fb56cf5
70730e2e8c7709abb3079acc8d01c23414866cec
/training/3 Basic Paradigms/3.4 Greedy/CF1106B.cpp
661db9e21794ddb3c90361b58035584d66d6fe0c
[]
no_license
pratishkatiyar/competitive-programming
00113e2d5106660c087953f7e4caac0d7a08f15f
52c0436a94348169aadf51eb5d5ab8fa85429706
refs/heads/master
2022-01-08T01:25:51.988641
2019-05-04T16:59:29
2019-05-04T16:59:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,403
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; typedef complex<ld> cd; typedef pair<int, int> ii; typedef tuple<int, int, int> iii; typedef vector<int> vi; typedef vector<ii> vii; typedef vector<ld> vd; typedef vector<ll> vl; typedef set<int> si; typedef set<ii> sii; typedef set<ld> sd; typedef set<ll> sl; typedef map<int, int> mii; typedef priority_queue<int> pqi; typedef queue<int> qi; #define mp make_pair #define pb push_back #define f first #define s second int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n, m; cin >> n >> m; vl ct(n), cost(n); for (auto &x : ct) cin >> x; for (auto &x : cost) cin >> x; sii dishes; for (int i = 0; i < n; i++) dishes.insert({cost[i], i}); for (ll i = 0, t, d; i < m; i++) { cin >> t >> d, t--; ll ans = 0; while (d > 0) { if (ct[t] > 0) { if (d >= ct[t]) { ans += (ct[t] * cost[t]); d -= ct[t]; ct[t] = 0; dishes.erase({cost[t], t}); } else { ans += (d * cost[t]); ct[t] -= d; d = 0; } } else { if (dishes.empty()) { ans = 0; break; } ll use = min(d, ct[dishes.begin()->s]); ans += use * dishes.begin()->f; d -= use; ct[dishes.begin()->s] -= use; if (ct[dishes.begin()->s] == 0) dishes.erase(dishes.begin()); } } cout << ans << endl; // for (auto &x : ct) cout << x << " "; // cout << endl; } } /* USE LONG LONG!!!! :pray: :fishy15: :pray: :summitosity: .= , =. _ _ /'/ )\,/,/(_ \ \ `//-.| ( ,\\)\//\)\/_ ) | //___\ `\\\/\\/\/\\///' / ,-"~`-._ `"--'_ `"""` _ \`'"~-,_ \ `-. '_`. .'_` \ ,-"~`/ `.__.-'`/ (-\ /-) |-.__,' || | \O) /^\ (O/ | . <- BESSIE THE COW `\\ | / `\ / \\ \ / `\ / `\\ `-. /' .---.--.\ `\\/`~(, '() (' /(O) \\ _,.-.,_) // \\ `\'` / / | || `""""~"` /' |__|| `o */
[ "aryaman.arora2020@gmail.com" ]
aryaman.arora2020@gmail.com
8e24ebe86f3a8d8b946ba2ea80095c2ffd8cd11e
604835ee6216507bdebfdc6e13bf068f6710ff3e
/IOSTEST/Classes/Native/AssemblyU2DCSharpU2Dfirstpass_Valve_VR_IVRSettings3538756002.h
15e2cdb573bfe9663fb070b1c07c13ad5f2cbf25
[ "MIT" ]
permissive
pickettd/OpenBrushVR
d174c86a2364c2cd5b79e927c2f2686825211531
7f3aa4bc1f12bd5b4f6d5f7cc15a1a6af5d48dbe
refs/heads/master
2020-03-30T02:55:09.435323
2019-01-30T22:48:39
2019-01-30T22:48:39
150,658,280
2
0
null
2018-09-27T23:14:34
2018-09-27T23:14:34
null
UTF-8
C++
false
false
847
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include "mscorlib_System_MulticastDelegate3201952435.h" #include "mscorlib_System_Int322071877448.h" #include "AssemblyU2DCSharpU2Dfirstpass_Valve_VR_EVRSettings4124928198.h" // System.String struct String_t; // System.IAsyncResult struct IAsyncResult_t1999651008; // System.AsyncCallback struct AsyncCallback_t163412349; // System.Object struct Il2CppObject; #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // Valve.VR.IVRSettings/_GetInt32 struct _GetInt32_t3538756002 : public MulticastDelegate_t3201952435 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif
[ "andrew.nakas@gmail.com" ]
andrew.nakas@gmail.com
5b17ab633a5e3e1eb14bbd63afd63a1ac278dd5f
a66f43ebb6bebfe509f8aaeff3989c6153668de8
/LIGHTOJ/1202 - Bishops.cpp
23eda54eff9d9306654c005cff0e331bb7839485
[]
no_license
ShikariSohan/Problems-Solving
e6cbeaaa9a8a091364aee12cc28cce06165cf84d
26809bddfcb357ca232be5e8016ef1e705a94f9a
refs/heads/master
2023-02-24T08:05:27.161840
2021-01-26T12:44:55
2021-01-26T12:44:55
283,302,951
2
0
null
null
null
null
UTF-8
C++
false
false
1,588
cpp
/* """Bismillahir Rahmanur Rahim""" */ #include<bits/stdc++.h> using namespace std; #define pi 2*acos(0.0) #define ll long long int #define pb push_back #define pf push_front const ll sz = 1000001; #define mp make_pair #define ses '\n' #define stm istringstream #define ghora ios_base::sync_with_stdio(0);cin.tie(0); #define gcd __gcd ll lcm(ll x,ll y){return (x*y)/gcd(x,y);} #define tin ll T;cin>>T; for(ll o=1;o<=T;o++) #define tout cout<<"Case "<<o<<": "; ll a,b,c,d,p,q,w; int main() { // freopen ("input.txt","r",stdin); // freopen ("output.txt","w",stdout); tin { scanf("%lld %lld %lld %lld",&a,&b,&c,&d); p=(a+b)%2; q=(c+d)%2; tout; if(p!=q) { cout<<"impossible"<<ses;continue; } p=abs(a-c); q=abs(b-d); if(p==q) cout<<"1"<<ses; else cout<<"2"<<ses; } return 0; } /* -------------------- | ~SOHAN~ | | ~Chandler68~ | -------------------- || VALAR MORGULIS||==|| ALL MEN MUST DIE || \\ Power Is Power// || I Can Do This All day || // We are on a Break \\ // How you doin'? \\ || Say My Name || ~~ || I Am The Who Knocks || // I Am Ted Mosby Architect \\ || It Is Legen --wait for it -- dary ,Legendary || \\ Penny - Penny - Penny // -- Bazinga */
[ "moksedur.rahman.sohan@gmail.com" ]
moksedur.rahman.sohan@gmail.com
aa1fb9293d60dff748d24501b0f0abcd9646fefe
52a3c93c38bef127eaee4420f36a89d929a321c5
/SDK/SoT_BP_SmallShipAnchor_classes.hpp
210cd0a294cc66b6cb3687da7d22e26b5146f3e4
[]
no_license
RDTCREW/SoT-SDK_2_0_7_reserv
8e921275508d09e5f81b10f9a43e47597223cb35
db6a5fc4cdb9348ddfda88121ebe809047aa404a
refs/heads/master
2020-07-24T17:18:40.537329
2019-09-11T18:53:58
2019-09-11T18:53:58
207,991,316
0
0
null
null
null
null
UTF-8
C++
false
false
910
hpp
#pragma once // Sea of Thieves (2.0) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "SoT_BP_SmallShipAnchor_structs.hpp" namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass BP_SmallShipAnchor.BP_SmallShipAnchor_C // 0x0008 (0x04E8 - 0x04E0) class ABP_SmallShipAnchor_C : public AAnchor { public: class USceneComponent* DefaultSceneRoot; // 0x04E0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData) static UClass* StaticClass() { static auto ptr = UObject::FindObject<UClass>(_xor_("BlueprintGeneratedClass BP_SmallShipAnchor.BP_SmallShipAnchor_C")); return ptr; } void UserConstructionScript(); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "igromanru@yahoo.de" ]
igromanru@yahoo.de
3e6c7872c5478a899ff20bfaf0e3553d8b7f885a
29a8a6f51b2a94f6b1c1fcfa60e0058d5cd478fc
/sim/ReflectingBorder.hh
9f8da3d63fb72021fb139f0276410911fcfa46cf
[]
no_license
szczk/reflecting_absorbing
2b3670f0afee525a063fd0ceac287d192f57cebb
d5a5ba5d269d7af3a18c4551b1dbb721184e911a
refs/heads/master
2020-09-22T11:45:48.704471
2015-10-07T10:40:10
2015-10-07T10:40:10
225,180,400
0
0
null
null
null
null
UTF-8
C++
false
false
313
hh
#ifndef __REFLECTING_BORDER__ #define __REFLECTING_BORDER__ #include "Border.hh" class ReflectingBorder : public Border { public: ReflectingBorder ( double position ); virtual ~ReflectingBorder(); virtual const char * toString(); virtual bool operator() ( Particle * ); }; #endif
[ "krzysztof.sc@gmail.com" ]
krzysztof.sc@gmail.com
34e090df29ee291abaa6c69f41c8acc195548b83
71f7533a5bd98dc4c5010360a7946361e620053f
/k_sortedarray.cpp
784d8965a52222e737058359002060efbc63aa94
[]
no_license
Divyalok123/CN_Data_Structures_And_Algorithms
d573ef6e567ee6564c0daf1e186a02055a2f3f38
23e951a031708dab37e6699919767eadb4850b7f
refs/heads/master
2022-11-18T18:20:42.309700
2020-07-13T08:04:48
2020-07-13T08:04:48
256,801,998
0
0
null
null
null
null
UTF-8
C++
false
false
627
cpp
#include <iostream> using namespace std; #include <queue> void kSortedArray(int input[], int n, int k) { priority_queue<int> pq; for (int i = 0; i < k; i++) { pq.push(input[i]); } int j = 0; for (int i = k; i < n; i++) { input[j] = pq.top(); pq.pop(); pq.push(input[i]); j++; } while (!pq.empty()) { input[j] = pq.top(); pq.pop(); j++; } } int main() { int input[] = {10, 12, 6, 7, 9}; int k = 3; kSortedArray(input, 5, k); for (int i = 0; i < 5; i++) { cout << input[i] << " "; } }
[ "divyjais2001@gmail.com" ]
divyjais2001@gmail.com
84cb8b059cfa00ad10664674ce7427e862a62732
c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64
/Engine/Source/ThirdParty/CEF3/cef_binary_3.2623.1395.g3034273_linux64/include/base/cef_scoped_ptr.h
ed6c706f785d9491ed84f2b9dfbc9e2a3e7277aa
[ "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
windystrife/UnrealEngine_NVIDIAGameWorks
c3c7863083653caf1bc67d3ef104fb4b9f302e2a
b50e6338a7c5b26374d66306ebc7807541ff815e
refs/heads/4.18-GameWorks
2023-03-11T02:50:08.471040
2022-01-13T20:50:29
2022-01-13T20:50:29
124,100,479
262
179
MIT
2022-12-16T05:36:38
2018-03-06T15:44:09
C++
UTF-8
C++
false
false
24,795
h
// Copyright (c) 2014 Marshall A. Greenblatt. Portions copyright (c) 2012 // Google Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the name Chromium Embedded // Framework nor the names of its contributors may be used to endorse // or promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Scopers help you manage ownership of a pointer, helping you easily manage a // pointer within a scope, and automatically destroying the pointer at the end // of a scope. There are two main classes you will use, which correspond to the // operators new/delete and new[]/delete[]. // // Example usage (scoped_ptr<T>): // { // scoped_ptr<Foo> foo(new Foo("wee")); // } // foo goes out of scope, releasing the pointer with it. // // { // scoped_ptr<Foo> foo; // No pointer managed. // foo.reset(new Foo("wee")); // Now a pointer is managed. // foo.reset(new Foo("wee2")); // Foo("wee") was destroyed. // foo.reset(new Foo("wee3")); // Foo("wee2") was destroyed. // foo->Method(); // Foo::Method() called. // foo.get()->Method(); // Foo::Method() called. // SomeFunc(foo.release()); // SomeFunc takes ownership, foo no longer // // manages a pointer. // foo.reset(new Foo("wee4")); // foo manages a pointer again. // foo.reset(); // Foo("wee4") destroyed, foo no longer // // manages a pointer. // } // foo wasn't managing a pointer, so nothing was destroyed. // // Example usage (scoped_ptr<T[]>): // { // scoped_ptr<Foo[]> foo(new Foo[100]); // foo.get()->Method(); // Foo::Method on the 0th element. // foo[10].Method(); // Foo::Method on the 10th element. // } // // These scopers also implement part of the functionality of C++11 unique_ptr // in that they are "movable but not copyable." You can use the scopers in // the parameter and return types of functions to signify ownership transfer // in to and out of a function. When calling a function that has a scoper // as the argument type, it must be called with the result of an analogous // scoper's Pass() function or another function that generates a temporary; // passing by copy will NOT work. Here is an example using scoped_ptr: // // void TakesOwnership(scoped_ptr<Foo> arg) { // // Do something with arg // } // scoped_ptr<Foo> CreateFoo() { // // No need for calling Pass() because we are constructing a temporary // // for the return value. // return scoped_ptr<Foo>(new Foo("new")); // } // scoped_ptr<Foo> PassThru(scoped_ptr<Foo> arg) { // return arg.Pass(); // } // // { // scoped_ptr<Foo> ptr(new Foo("yay")); // ptr manages Foo("yay"). // TakesOwnership(ptr.Pass()); // ptr no longer owns Foo("yay"). // scoped_ptr<Foo> ptr2 = CreateFoo(); // ptr2 owns the return Foo. // scoped_ptr<Foo> ptr3 = // ptr3 now owns what was in ptr2. // PassThru(ptr2.Pass()); // ptr2 is correspondingly NULL. // } // // Notice that if you do not call Pass() when returning from PassThru(), or // when invoking TakesOwnership(), the code will not compile because scopers // are not copyable; they only implement move semantics which require calling // the Pass() function to signify a destructive transfer of state. CreateFoo() // is different though because we are constructing a temporary on the return // line and thus can avoid needing to call Pass(). // // Pass() properly handles upcast in initialization, i.e. you can use a // scoped_ptr<Child> to initialize a scoped_ptr<Parent>: // // scoped_ptr<Foo> foo(new Foo()); // scoped_ptr<FooParent> parent(foo.Pass()); // // PassAs<>() should be used to upcast return value in return statement: // // scoped_ptr<Foo> CreateFoo() { // scoped_ptr<FooChild> result(new FooChild()); // return result.PassAs<Foo>(); // } // // Note that PassAs<>() is implemented only for scoped_ptr<T>, but not for // scoped_ptr<T[]>. This is because casting array pointers may not be safe. #ifndef CEF_INCLUDE_BASE_CEF_MEMORY_SCOPED_PTR_H_ #define CEF_INCLUDE_BASE_CEF_MEMORY_SCOPED_PTR_H_ #pragma once #if defined(BASE_MEMORY_SCOPED_PTR_H_) // Do nothing if the Chromium header has already been included. // This can happen in cases where Chromium code is used directly by the // client application. When using Chromium code directly always include // the Chromium header first to avoid type conflicts. #elif defined(BUILDING_CEF_SHARED) // When building CEF include the Chromium header directly. #include "base/memory/scoped_ptr.h" #else // !BUILDING_CEF_SHARED // The following is substantially similar to the Chromium implementation. // If the Chromium implementation diverges the below implementation should be // updated to match. // This is an implementation designed to match the anticipated future TR2 // implementation of the scoped_ptr class. #include <assert.h> #include <stddef.h> #include <stdlib.h> #include <algorithm> // For std::swap(). #include "include/base/cef_basictypes.h" #include "include/base/cef_build.h" #include "include/base/cef_macros.h" #include "include/base/cef_move.h" #include "include/base/cef_template_util.h" namespace base { namespace subtle { class RefCountedBase; class RefCountedThreadSafeBase; } // namespace subtle // Function object which deletes its parameter, which must be a pointer. // If C is an array type, invokes 'delete[]' on the parameter; otherwise, // invokes 'delete'. The default deleter for scoped_ptr<T>. template <class T> struct DefaultDeleter { DefaultDeleter() {} template <typename U> DefaultDeleter(const DefaultDeleter<U>& other) { // IMPLEMENTATION NOTE: C++11 20.7.1.1.2p2 only provides this constructor // if U* is implicitly convertible to T* and U is not an array type. // // Correct implementation should use SFINAE to disable this // constructor. However, since there are no other 1-argument constructors, // using a COMPILE_ASSERT() based on is_convertible<> and requiring // complete types is simpler and will cause compile failures for equivalent // misuses. // // Note, the is_convertible<U*, T*> check also ensures that U is not an // array. T is guaranteed to be a non-array, so any U* where U is an array // cannot convert to T*. enum { T_must_be_complete = sizeof(T) }; enum { U_must_be_complete = sizeof(U) }; COMPILE_ASSERT((base::is_convertible<U*, T*>::value), U_ptr_must_implicitly_convert_to_T_ptr); } inline void operator()(T* ptr) const { enum { type_must_be_complete = sizeof(T) }; delete ptr; } }; // Specialization of DefaultDeleter for array types. template <class T> struct DefaultDeleter<T[]> { inline void operator()(T* ptr) const { enum { type_must_be_complete = sizeof(T) }; delete[] ptr; } private: // Disable this operator for any U != T because it is undefined to execute // an array delete when the static type of the array mismatches the dynamic // type. // // References: // C++98 [expr.delete]p3 // http://cplusplus.github.com/LWG/lwg-defects.html#938 template <typename U> void operator()(U* array) const; }; template <class T, int n> struct DefaultDeleter<T[n]> { // Never allow someone to declare something like scoped_ptr<int[10]>. COMPILE_ASSERT(sizeof(T) == -1, do_not_use_array_with_size_as_type); }; // Function object which invokes 'free' on its parameter, which must be // a pointer. Can be used to store malloc-allocated pointers in scoped_ptr: // // scoped_ptr<int, base::FreeDeleter> foo_ptr( // static_cast<int*>(malloc(sizeof(int)))); struct FreeDeleter { inline void operator()(void* ptr) const { free(ptr); } }; namespace cef_internal { template <typename T> struct IsNotRefCounted { enum { value = !base::is_convertible<T*, base::subtle::RefCountedBase*>::value && !base::is_convertible<T*, base::subtle::RefCountedThreadSafeBase*>:: value }; }; // Minimal implementation of the core logic of scoped_ptr, suitable for // reuse in both scoped_ptr and its specializations. template <class T, class D> class scoped_ptr_impl { public: explicit scoped_ptr_impl(T* p) : data_(p) { } // Initializer for deleters that have data parameters. scoped_ptr_impl(T* p, const D& d) : data_(p, d) {} // Templated constructor that destructively takes the value from another // scoped_ptr_impl. template <typename U, typename V> scoped_ptr_impl(scoped_ptr_impl<U, V>* other) : data_(other->release(), other->get_deleter()) { // We do not support move-only deleters. We could modify our move // emulation to have base::subtle::move() and base::subtle::forward() // functions that are imperfect emulations of their C++11 equivalents, // but until there's a requirement, just assume deleters are copyable. } template <typename U, typename V> void TakeState(scoped_ptr_impl<U, V>* other) { // See comment in templated constructor above regarding lack of support // for move-only deleters. reset(other->release()); get_deleter() = other->get_deleter(); } ~scoped_ptr_impl() { if (data_.ptr != NULL) { // Not using get_deleter() saves one function call in non-optimized // builds. static_cast<D&>(data_)(data_.ptr); } } void reset(T* p) { // This is a self-reset, which is no longer allowed: http://crbug.com/162971 if (p != NULL && p == data_.ptr) abort(); // Note that running data_.ptr = p can lead to undefined behavior if // get_deleter()(get()) deletes this. In order to prevent this, reset() // should update the stored pointer before deleting its old value. // // However, changing reset() to use that behavior may cause current code to // break in unexpected ways. If the destruction of the owned object // dereferences the scoped_ptr when it is destroyed by a call to reset(), // then it will incorrectly dispatch calls to |p| rather than the original // value of |data_.ptr|. // // During the transition period, set the stored pointer to NULL while // deleting the object. Eventually, this safety check will be removed to // prevent the scenario initially described from occuring and // http://crbug.com/176091 can be closed. T* old = data_.ptr; data_.ptr = NULL; if (old != NULL) static_cast<D&>(data_)(old); data_.ptr = p; } T* get() const { return data_.ptr; } D& get_deleter() { return data_; } const D& get_deleter() const { return data_; } void swap(scoped_ptr_impl& p2) { // Standard swap idiom: 'using std::swap' ensures that std::swap is // present in the overload set, but we call swap unqualified so that // any more-specific overloads can be used, if available. using std::swap; swap(static_cast<D&>(data_), static_cast<D&>(p2.data_)); swap(data_.ptr, p2.data_.ptr); } T* release() { T* old_ptr = data_.ptr; data_.ptr = NULL; return old_ptr; } private: // Needed to allow type-converting constructor. template <typename U, typename V> friend class scoped_ptr_impl; // Use the empty base class optimization to allow us to have a D // member, while avoiding any space overhead for it when D is an // empty class. See e.g. http://www.cantrip.org/emptyopt.html for a good // discussion of this technique. struct Data : public D { explicit Data(T* ptr_in) : ptr(ptr_in) {} Data(T* ptr_in, const D& other) : D(other), ptr(ptr_in) {} T* ptr; }; Data data_; DISALLOW_COPY_AND_ASSIGN(scoped_ptr_impl); }; } // namespace cef_internal } // namespace base // A scoped_ptr<T> is like a T*, except that the destructor of scoped_ptr<T> // automatically deletes the pointer it holds (if any). // That is, scoped_ptr<T> owns the T object that it points to. // Like a T*, a scoped_ptr<T> may hold either NULL or a pointer to a T object. // Also like T*, scoped_ptr<T> is thread-compatible, and once you // dereference it, you get the thread safety guarantees of T. // // The size of scoped_ptr is small. On most compilers, when using the // DefaultDeleter, sizeof(scoped_ptr<T>) == sizeof(T*). Custom deleters will // increase the size proportional to whatever state they need to have. See // comments inside scoped_ptr_impl<> for details. // // Current implementation targets having a strict subset of C++11's // unique_ptr<> features. Known deficiencies include not supporting move-only // deleteres, function pointers as deleters, and deleters with reference // types. template <class T, class D = base::DefaultDeleter<T> > class scoped_ptr { MOVE_ONLY_TYPE_FOR_CPP_03(scoped_ptr, RValue) COMPILE_ASSERT(base::cef_internal::IsNotRefCounted<T>::value, T_is_refcounted_type_and_needs_scoped_refptr); public: // The element and deleter types. typedef T element_type; typedef D deleter_type; // Constructor. Defaults to initializing with NULL. scoped_ptr() : impl_(NULL) { } // Constructor. Takes ownership of p. explicit scoped_ptr(element_type* p) : impl_(p) { } // Constructor. Allows initialization of a stateful deleter. scoped_ptr(element_type* p, const D& d) : impl_(p, d) { } // Constructor. Allows construction from a scoped_ptr rvalue for a // convertible type and deleter. // // IMPLEMENTATION NOTE: C++11 unique_ptr<> keeps this constructor distinct // from the normal move constructor. By C++11 20.7.1.2.1.21, this constructor // has different post-conditions if D is a reference type. Since this // implementation does not support deleters with reference type, // we do not need a separate move constructor allowing us to avoid one // use of SFINAE. You only need to care about this if you modify the // implementation of scoped_ptr. template <typename U, typename V> scoped_ptr(scoped_ptr<U, V> other) : impl_(&other.impl_) { COMPILE_ASSERT(!base::is_array<U>::value, U_cannot_be_an_array); } // Constructor. Move constructor for C++03 move emulation of this type. scoped_ptr(RValue rvalue) : impl_(&rvalue.object->impl_) { } // operator=. Allows assignment from a scoped_ptr rvalue for a convertible // type and deleter. // // IMPLEMENTATION NOTE: C++11 unique_ptr<> keeps this operator= distinct from // the normal move assignment operator. By C++11 20.7.1.2.3.4, this templated // form has different requirements on for move-only Deleters. Since this // implementation does not support move-only Deleters, we do not need a // separate move assignment operator allowing us to avoid one use of SFINAE. // You only need to care about this if you modify the implementation of // scoped_ptr. template <typename U, typename V> scoped_ptr& operator=(scoped_ptr<U, V> rhs) { COMPILE_ASSERT(!base::is_array<U>::value, U_cannot_be_an_array); impl_.TakeState(&rhs.impl_); return *this; } // Reset. Deletes the currently owned object, if any. // Then takes ownership of a new object, if given. void reset(element_type* p = NULL) { impl_.reset(p); } // Accessors to get the owned object. // operator* and operator-> will assert() if there is no current object. element_type& operator*() const { assert(impl_.get() != NULL); return *impl_.get(); } element_type* operator->() const { assert(impl_.get() != NULL); return impl_.get(); } element_type* get() const { return impl_.get(); } // Access to the deleter. deleter_type& get_deleter() { return impl_.get_deleter(); } const deleter_type& get_deleter() const { return impl_.get_deleter(); } // Allow scoped_ptr<element_type> to be used in boolean expressions, but not // implicitly convertible to a real bool (which is dangerous). // // Note that this trick is only safe when the == and != operators // are declared explicitly, as otherwise "scoped_ptr1 == // scoped_ptr2" will compile but do the wrong thing (i.e., convert // to Testable and then do the comparison). private: typedef base::cef_internal::scoped_ptr_impl<element_type, deleter_type> scoped_ptr::*Testable; public: operator Testable() const { return impl_.get() ? &scoped_ptr::impl_ : NULL; } // Comparison operators. // These return whether two scoped_ptr refer to the same object, not just to // two different but equal objects. bool operator==(const element_type* p) const { return impl_.get() == p; } bool operator!=(const element_type* p) const { return impl_.get() != p; } // Swap two scoped pointers. void swap(scoped_ptr& p2) { impl_.swap(p2.impl_); } // Release a pointer. // The return value is the current pointer held by this object. // If this object holds a NULL pointer, the return value is NULL. // After this operation, this object will hold a NULL pointer, // and will not own the object any more. element_type* release() WARN_UNUSED_RESULT { return impl_.release(); } // C++98 doesn't support functions templates with default parameters which // makes it hard to write a PassAs() that understands converting the deleter // while preserving simple calling semantics. // // Until there is a use case for PassAs() with custom deleters, just ignore // the custom deleter. template <typename PassAsType> scoped_ptr<PassAsType> PassAs() { return scoped_ptr<PassAsType>(Pass()); } private: // Needed to reach into |impl_| in the constructor. template <typename U, typename V> friend class scoped_ptr; base::cef_internal::scoped_ptr_impl<element_type, deleter_type> impl_; // Forbidden for API compatibility with std::unique_ptr. explicit scoped_ptr(int disallow_construction_from_null); // Forbid comparison of scoped_ptr types. If U != T, it totally // doesn't make sense, and if U == T, it still doesn't make sense // because you should never have the same object owned by two different // scoped_ptrs. template <class U> bool operator==(scoped_ptr<U> const& p2) const; template <class U> bool operator!=(scoped_ptr<U> const& p2) const; }; template <class T, class D> class scoped_ptr<T[], D> { MOVE_ONLY_TYPE_FOR_CPP_03(scoped_ptr, RValue) public: // The element and deleter types. typedef T element_type; typedef D deleter_type; // Constructor. Defaults to initializing with NULL. scoped_ptr() : impl_(NULL) { } // Constructor. Stores the given array. Note that the argument's type // must exactly match T*. In particular: // - it cannot be a pointer to a type derived from T, because it is // inherently unsafe in the general case to access an array through a // pointer whose dynamic type does not match its static type (eg., if // T and the derived types had different sizes access would be // incorrectly calculated). Deletion is also always undefined // (C++98 [expr.delete]p3). If you're doing this, fix your code. // - it cannot be NULL, because NULL is an integral expression, not a // pointer to T. Use the no-argument version instead of explicitly // passing NULL. // - it cannot be const-qualified differently from T per unique_ptr spec // (http://cplusplus.github.com/LWG/lwg-active.html#2118). Users wanting // to work around this may use implicit_cast<const T*>(). // However, because of the first bullet in this comment, users MUST // NOT use implicit_cast<Base*>() to upcast the static type of the array. explicit scoped_ptr(element_type* array) : impl_(array) { } // Constructor. Move constructor for C++03 move emulation of this type. scoped_ptr(RValue rvalue) : impl_(&rvalue.object->impl_) { } // operator=. Move operator= for C++03 move emulation of this type. scoped_ptr& operator=(RValue rhs) { impl_.TakeState(&rhs.object->impl_); return *this; } // Reset. Deletes the currently owned array, if any. // Then takes ownership of a new object, if given. void reset(element_type* array = NULL) { impl_.reset(array); } // Accessors to get the owned array. element_type& operator[](size_t i) const { assert(impl_.get() != NULL); return impl_.get()[i]; } element_type* get() const { return impl_.get(); } // Access to the deleter. deleter_type& get_deleter() { return impl_.get_deleter(); } const deleter_type& get_deleter() const { return impl_.get_deleter(); } // Allow scoped_ptr<element_type> to be used in boolean expressions, but not // implicitly convertible to a real bool (which is dangerous). private: typedef base::cef_internal::scoped_ptr_impl<element_type, deleter_type> scoped_ptr::*Testable; public: operator Testable() const { return impl_.get() ? &scoped_ptr::impl_ : NULL; } // Comparison operators. // These return whether two scoped_ptr refer to the same object, not just to // two different but equal objects. bool operator==(element_type* array) const { return impl_.get() == array; } bool operator!=(element_type* array) const { return impl_.get() != array; } // Swap two scoped pointers. void swap(scoped_ptr& p2) { impl_.swap(p2.impl_); } // Release a pointer. // The return value is the current pointer held by this object. // If this object holds a NULL pointer, the return value is NULL. // After this operation, this object will hold a NULL pointer, // and will not own the object any more. element_type* release() WARN_UNUSED_RESULT { return impl_.release(); } private: // Force element_type to be a complete type. enum { type_must_be_complete = sizeof(element_type) }; // Actually hold the data. base::cef_internal::scoped_ptr_impl<element_type, deleter_type> impl_; // Disable initialization from any type other than element_type*, by // providing a constructor that matches such an initialization, but is // private and has no definition. This is disabled because it is not safe to // call delete[] on an array whose static type does not match its dynamic // type. template <typename U> explicit scoped_ptr(U* array); explicit scoped_ptr(int disallow_construction_from_null); // Disable reset() from any type other than element_type*, for the same // reasons as the constructor above. template <typename U> void reset(U* array); void reset(int disallow_reset_from_null); // Forbid comparison of scoped_ptr types. If U != T, it totally // doesn't make sense, and if U == T, it still doesn't make sense // because you should never have the same object owned by two different // scoped_ptrs. template <class U> bool operator==(scoped_ptr<U> const& p2) const; template <class U> bool operator!=(scoped_ptr<U> const& p2) const; }; // Free functions template <class T, class D> void swap(scoped_ptr<T, D>& p1, scoped_ptr<T, D>& p2) { p1.swap(p2); } template <class T, class D> bool operator==(T* p1, const scoped_ptr<T, D>& p2) { return p1 == p2.get(); } template <class T, class D> bool operator!=(T* p1, const scoped_ptr<T, D>& p2) { return p1 != p2.get(); } // A function to convert T* into scoped_ptr<T> // Doing e.g. make_scoped_ptr(new FooBarBaz<type>(arg)) is a shorter notation // for scoped_ptr<FooBarBaz<type> >(new FooBarBaz<type>(arg)) template <typename T> scoped_ptr<T> make_scoped_ptr(T* ptr) { return scoped_ptr<T>(ptr); } #endif // !BUILDING_CEF_SHARED #endif // CEF_INCLUDE_BASE_CEF_MEMORY_SCOPED_PTR_H_
[ "tungnt.rec@gmail.com" ]
tungnt.rec@gmail.com
de601ae75765ebbfd2b2c58b2bfd149b880de721
ee93f5b1f47a9e4407099469fe573d3487931f17
/release/moc_contextview.cpp
aac39488b7a831d3e0412732ab979b64ea447413
[]
no_license
blaquee/QtSlothEmu
d149f417247fbc4c72087a78d6b6c15583432c89
3d24ff1e85d2d598441c52bc0af7b7db9db9fd80
refs/heads/master
2021-03-16T05:12:41.814041
2017-09-21T14:52:42
2017-09-21T14:52:42
103,222,749
0
1
null
null
null
null
UTF-8
C++
false
false
3,589
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'contextview.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.6.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../contextview.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'contextview.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.6.0. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_ContextView_t { QByteArrayData data[4]; char stringdata0[64]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_ContextView_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_ContextView_t qt_meta_stringdata_ContextView = { { QT_MOC_LITERAL(0, 0, 11), // "ContextView" QT_MOC_LITERAL(1, 12, 23), // "on_onDoneButton_clicked" QT_MOC_LITERAL(2, 36, 0), // "" QT_MOC_LITERAL(3, 37, 26) // "on_onUseCurContext_clicked" }, "ContextView\0on_onDoneButton_clicked\0" "\0on_onUseCurContext_clicked" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_ContextView[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 2, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 0, 24, 2, 0x08 /* Private */, 3, 0, 25, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, QMetaType::Void, 0 // eod }; void ContextView::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { ContextView *_t = static_cast<ContextView *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->on_onDoneButton_clicked(); break; case 1: _t->on_onUseCurContext_clicked(); break; default: ; } } Q_UNUSED(_a); } const QMetaObject ContextView::staticMetaObject = { { &QDialog::staticMetaObject, qt_meta_stringdata_ContextView.data, qt_meta_data_ContextView, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *ContextView::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *ContextView::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_ContextView.stringdata0)) return static_cast<void*>(const_cast< ContextView*>(this)); return QDialog::qt_metacast(_clname); } int ContextView::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QDialog::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 2) qt_static_metacall(this, _c, _id, _a); _id -= 2; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 2) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 2; } return _id; } QT_END_MOC_NAMESPACE
[ "1324227+blaquee@users.noreply.github.com" ]
1324227+blaquee@users.noreply.github.com
4c319097b4377a0e8cae343b3baa79defff1e59a
1afc2ba02aaa1170db5def78ef506503073ad45b
/StepperMotorDriver.ino
d39203a43cd8a9e0e91b5595f8cd2a4f3e66f982
[]
no_license
sjuim/STEMProject
937f3474862d43144ad02216b65c07539d9f34ab
a02727933affb5bbccc43658b8307e59ec91dc7f
refs/heads/master
2023-02-26T11:41:37.499517
2021-02-06T01:27:29
2021-02-06T01:27:29
336,429,631
0
0
null
null
null
null
UTF-8
C++
false
false
1,284
ino
int PUL=7; //define Pulse pin int DIR=6; //define Direction pin int ENA=5; //define Enable Pin void setup() { pinMode (PUL, OUTPUT); pinMode (DIR, OUTPUT); pinMode (ENA, OUTPUT); } void loop() { for(int i = 0; i < 20; i++){ moveForward(6400); rub(); } for(int i = 0; i < 20; i++){ moveBackward(6400); rub(); } pauseForWater(); } void moveForward(int steps){ setDirection(true); allowControl(true); for (int i=0; i<steps; i++) //Forward 5000 steps { giveCurrent(true); setDelay(); giveCurrent(false); setDelay(); } } void moveBackward(int steps){ setDirection(false); allowControl(true); for (int i=0; i<steps; i++) //Backward 5000 steps { giveCurrent(true); setDelay(); giveCurrent(false); setDelay(); } } void rub(){ for(int i = 0; i < 5; i++){ moveForward(2560); moveBackward(2560); } } void setDirection(boolean isForward){ int signal = isForward ? LOW : HIGH; digitalWrite(DIR, signal); } void giveCurrent(boolean cur){ int signal = cur ? HIGH : LOW; digitalWrite(PUL,signal); } void setDelay(){ delayMicroseconds(50); } void allowControl(boolean enable){ int signal = enable ? HIGH : LOW; digitalWrite(ENA, signal); } void pauseForWater(){ delay(5); }
[ "shreya.jui.majumdar@gmail.com" ]
shreya.jui.majumdar@gmail.com
26e4cef6795d48838cbac069a34f5ef946574f34
4fee29b4de44c68559e1e084151dc9b12f161287
/windows/resources.hpp
96bd5cf8bdd917fe15375c6ac5213ba4c31b9fd7
[ "MIT" ]
permissive
kristjanbb/libui
6e68b6f4f3a7115c9c5f735c7317d2a5bc675acb
d88233a0fb81524bff507b04fd710eb297b668ba
refs/heads/master
2021-01-18T13:00:18.504385
2016-05-29T08:53:49
2016-05-29T08:53:49
59,950,378
3
0
null
2016-05-29T15:33:30
2016-05-29T15:33:29
null
UTF-8
C++
false
false
761
hpp
// 30 may 2015 #define rcTabPageDialog 100 #define rcFontDialog 101 #define rcColorDialog 102 #define rcFontFamilyCombobox 1000 #define rcFontStyleCombobox 1001 #define rcFontSizeCombobox 1002 #define rcFontSamplePlacement 1003 #define rcColorSVChooser 1100 #define rcColorHSlider 1101 #define rcPreview 1102 #define rcOpacitySlider 1103 #define rcH 1104 #define rcS 1105 #define rcV 1106 #define rcRDouble 1107 #define rcRInt 1108 #define rcGDouble 1109 #define rcGInt 1110 #define rcBDouble 1111 #define rcBInt 1112 #define rcADouble 1113 #define rcAInt 1114 #define rcHex 1115 #define rcHLabel 1116 #define rcSLabel 1117 #define rcVLabel 1118 #define rcRLabel 1119 #define rcGLabel 1120 #define rcBLabel 1121 #define rcALabel 1122 #define rcHexLabel 1123
[ "pietro10@mac.com" ]
pietro10@mac.com
1239e15d7872b10da899f4cb2070d5d512039621
41a76318e5b9eef2c69bbf922724f8b191d7d124
/kokkos/core/src/Kokkos_ROCm.hpp
93f0ec430e66ea9f24925b8e590b5e712b14f123
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
zishengye/compadre
d0ff10deca224284e7e153371a738e053e66012a
75b738a6a613c89e3c3232cbf7b2589a6b28d0a3
refs/heads/master
2021-06-25T06:16:38.327543
2021-04-02T02:08:48
2021-04-02T02:08:48
223,650,267
0
0
NOASSERTION
2019-11-23T20:41:03
2019-11-23T20:41:02
null
UTF-8
C++
false
false
7,047
hpp
/* //@HEADER // ************************************************************************ // // Kokkos v. 3.0 // Copyright (2020) National Technology & Engineering // Solutions of Sandia, LLC (NTESS). // // Under the terms of Contract DE-NA0003525 with NTESS, // the U.S. Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Questions? Contact Christian R. Trott (crtrott@sandia.gov) // // ************************************************************************ //@HEADER */ #ifndef KOKKOS_ROCM_HPP #define KOKKOS_ROCM_HPP #include <Kokkos_Core_fwd.hpp> #if defined(KOKKOS_ENABLE_ROCM) class dim3 { public: int x, y, z; dim3(int _x, int _y, int _z) : x(_x), y(_y), z(_z){}; }; #include <ROCm/hc_math_std.hpp> //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- #include <cstddef> #include <iosfwd> #include <Kokkos_HostSpace.hpp> #include <Kokkos_ROCmSpace.hpp> #include <ROCm/Kokkos_ROCm_Exec.hpp> #include <Kokkos_ScratchSpace.hpp> #include <Kokkos_Parallel.hpp> #include <Kokkos_Layout.hpp> #include <impl/Kokkos_Tags.hpp> /*--------------------------------------------------------------------------*/ #include <hc.hpp> #include <hc_am.hpp> #include <amp_math.h> #if defined(__HCC_ACCELERATOR__) using namespace ::Concurrency::precise_math; #endif /*--------------------------------------------------------------------------*/ namespace Kokkos { namespace Impl { class ROCmExec; } // namespace Impl } // namespace Kokkos /*--------------------------------------------------------------------------*/ namespace Kokkos { namespace Experimental { /// \class ROCm /// \brief Kokkos device for multicore processors in the host memory space. class ROCm { public: //------------------------------------ //! \name Type declarations that all Kokkos devices must provide. //@{ //! Tag this class as a kokkos execution space typedef ROCm execution_space; typedef ROCmSpace memory_space; typedef Kokkos::Device<execution_space, memory_space> device_type; typedef LayoutLeft array_layout; typedef HostSpace::size_type size_type; typedef ScratchMemorySpace<ROCm> scratch_memory_space; ~ROCm() {} ROCm(); // explicit ROCm( const int instance_id ); ROCm(ROCm&&) = default; ROCm(const ROCm&) = default; ROCm& operator=(ROCm&&) = default; ROCm& operator=(const ROCm&) = default; //@} //------------------------------------ //! \name Functions that all Kokkos devices must implement. //@{ KOKKOS_INLINE_FUNCTION static int in_parallel() { #if defined(__HCC_ACCELERATOR__) return true; #else return false; #endif } /** \brief Set the device in a "sleep" state. */ static bool sleep(); /** \brief Wake the device from the 'sleep' state. A noop for OpenMP. */ static bool wake(); /** \brief Wait until all dispatched functors complete. A noop for OpenMP. */ static void impl_static_fence(); #ifdef KOKKOS_ENABLE_DEPRECATED_CODE static void fence(); #else void fence() const; #endif /// \brief Print configuration information to the given output stream. static void print_configuration(std::ostream&, const bool detail = false); /// \brief Free any resources being consumed by the device. static void finalize(); /** \brief Initialize the device. * */ struct SelectDevice { int rocm_device_id; SelectDevice() : rocm_device_id(1) {} explicit SelectDevice(int id) : rocm_device_id(id + 1) {} }; int rocm_device() const { return m_device; } bool isAPU(); bool isAPU(int device); static void initialize(const SelectDevice = SelectDevice()); static int is_initialized(); // static size_type device_arch(); // static size_type detect_device_count(); static int concurrency(); static const char* name(); private: int m_device; }; } // namespace Experimental } // namespace Kokkos namespace Kokkos { namespace Impl { template <> struct MemorySpaceAccess<Kokkos::Experimental::ROCmSpace, Kokkos::Experimental::ROCm::scratch_memory_space> { enum { assignable = false }; enum { accessible = true }; enum { deepcopy = false }; }; template <> struct VerifyExecutionCanAccessMemorySpace< Kokkos::Experimental::ROCm::memory_space, Kokkos::Experimental::ROCm::scratch_memory_space> { enum { value = true }; KOKKOS_INLINE_FUNCTION static void verify(void) {} KOKKOS_INLINE_FUNCTION static void verify(const void*) {} }; template <> struct VerifyExecutionCanAccessMemorySpace< Kokkos::HostSpace, Kokkos::Experimental::ROCm::scratch_memory_space> { enum { value = false }; inline static void verify(void) { Kokkos::Experimental::ROCmSpace::access_error(); } inline static void verify(const void* p) { Kokkos::Experimental::ROCmSpace::access_error(p); } }; } // namespace Impl } // namespace Kokkos #define threadIdx_x (hc_get_workitem_id(0)) #define threadIdx_y (hc_get_workitem_id(1)) #define threadIdx_z (hc_get_workitem_id(2)) #define blockIdx_x (hc_get_group_id(0)) #define blockIdx_y (hc_get_group_id(1)) #define blockIdx_z (hc_get_group_id(2)) #define blockDim_x (hc_get_group_size(0)) #define blockDim_y (hc_get_group_size(1)) #define blockDim_z (hc_get_group_size(2)) #define gridDim_x (hc_get_num_groups(0)) #define gridDim_y (hc_get_num_groups(1)) #define gridDim_z (hc_get_num_groups(2)) #include <ROCm/Kokkos_ROCm_Parallel.hpp> #include <ROCm/Kokkos_ROCm_Task.hpp> #endif #endif
[ "pakuber@sandia.gov" ]
pakuber@sandia.gov
fa24ce45b4cade70f92c8c0ee5d569570be0f414
1f530350dd396f64b20f0b47ebe1c447945d3502
/src/Shader.hpp
520e4985f538db5877257160f28d5887cf9abf5e
[]
no_license
MrTraan/minecrouft
b2831336e721bd02a7d64293158ee535d40f9685
08808ac5578bbf53fdd36f2060cd486012ca5c82
refs/heads/master
2022-02-05T01:33:47.749410
2020-06-11T12:09:11
2020-06-11T12:09:11
123,191,914
0
0
null
null
null
null
UTF-8
C++
false
false
1,368
hpp
#pragma once #include <GL/gl3w.h> #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include "ngLib/nglib.h" #include "packer.h" #include <fstream> #include <iostream> #include <sstream> #include <string> class Shader { public: u32 ID = 0; bool CompileFromPath( const char * vertexPath, const char * fragmentPath ); bool CompileFromCode( const char * vertexCode, int vertexSize, const char * fragmentCode, int fragmentSize ); bool CompileFromResource( const PackerResourceID & vertex, const PackerResourceID & frag ); void Use() { glUseProgram( this->ID ); } void SetBool( const char * name, bool value ) const { glUniform1i( glGetUniformLocation( this->ID, name ), ( int )value ); } void SetInt( const char * name, int value ) const { glUniform1i( glGetUniformLocation( this->ID, name ), value ); } void SetFloat( const char * name, float value ) const { glUniform1f( glGetUniformLocation( this->ID, name ), value ); } void SetVector( const char * name, const glm::vec3 & v ) const { glUniform3f( glGetUniformLocation( this->ID, name ), v.x, v.y, v.z ); } void SetMatrix( const char * name, const glm::mat4x4 & mat ) const { glUniformMatrix4fv( glGetUniformLocation( ID, name ), 1, GL_FALSE, glm::value_ptr( mat ) ); } private: int checkCompileErrors( unsigned int shader ); int checkLinkErrors( unsigned int shader ); };
[ "nathan.grasset@gmail.com" ]
nathan.grasset@gmail.com
23e8392d4bb1d86075c4f7f117043608c9acacfa
a0863d7dc1bddc6f3a3ee370f6b6e5f4de475550
/Tag/Array/611.ValidTriangleNumber/611.cpp
ad71c6a4996a90bfa82baae90d797cead3511473
[]
no_license
nisak0503/leetcode
c3a936da0d64eac2de9faa60d161d31f76c740b3
fa0f2e36c3ad554f96bef7f4e1e50952cde263e6
refs/heads/master
2021-01-20T10:50:11.220068
2017-11-30T02:53:31
2017-11-30T02:53:31
83,939,025
0
0
null
null
null
null
UTF-8
C++
false
false
2,400
cpp
#include <iostream> #include <fstream> #include <algorithm> #include <vector> using namespace std; ifstream fin("611.in"); class Solution { public: vector<int> nums; public: int triangleNumber(vector<int>& nums) { sort(nums.begin(), nums.begin()+nums.size()); int k = 2, cnt = 0; if(nums.size() < 3) return 0; for(int i = 0; i < nums.size()-2; ++i) { if(nums[i] <= 0) continue; for(int j = i+1; j < nums.size()-1; ++j) { if(nums[j] <= 0) continue; int k = j+1; while(nums[i] + nums[j] > nums[k]) { k++; if(k >= nums.size()) { break; } } k--; cout << nums[i]<<" + "<<nums[j]<<"> "<<nums[k]<<" +"<<k-j<<endl; cnt += max(0, k - j); } } return cnt > 0 ? cnt : 0; } void input() { int num; while(fin >> num) { nums.push_back(num); } } }; int main() { Solution s; s.input(); cout << s.triangleNumber(s.nums) << endl; } /* 自己做没有想出来qwq 好好反省一下 根据宋胖的算法,计算出 larger[i] 表示 比i大的数, 每次计算 max(i-j, j-i) < k < i+j 只要计算 larger(max(i-j), j-i) - larger(i+j) 即可 我的方法是维护一个smaller数组,保证两个数组都是非等号的。 但是这里出现的问题是,2,2,3这种组合会在 2,2时算1次,2,3,2中被算了两次,因为 2>3-1,两个2。等等,这样算下来,晕掉了。。 以上是solution中的思路。 sort之后,每次从j+1开始循环,做了一定的剪枝 232ms, 25.56% 原java代码如下: public class Solution { public int triangleNumber(int[] nums) { int count = 0; Arrays.sort(nums); for (int i = 0; i < nums.length - 2; i++) { int k = i + 2; for (int j = i + 1; j < nums.length - 1 && nums[i] != 0; j++) { while (k < nums.length && nums[i] + nums[j] > nums[k]) k++; count += k - j - 1; } } return count; } } 写第一遍出现的问题是, 3, 82 不拉不拉,算出来nums[k] = 84 紧接着 19, 22 算出来nums[k] 不应该从84开始 */
[ "kasin.xc@sjtu.edu.cn" ]
kasin.xc@sjtu.edu.cn
15cc173e38d70f18b2c0bf5ad3610b259b628133
045a72f9f0bbb81488f433c6e6d4b9973b8fe38a
/src/converter/lattice.cpp
00265939697237a0d76e72c46c5d543a7c1db125
[]
no_license
yoriyuki/tkd53
2597e7f3ecb54e024de2c29c98db3007f60091d9
a56d0da48c7a51ec59d3d3e52c2f2edac8a9a78d
refs/heads/master
2021-01-13T06:50:59.711273
2016-04-11T18:19:05
2016-04-11T18:19:05
55,995,936
0
0
null
2016-04-11T18:14:24
2016-04-11T18:14:24
null
UTF-8
C++
false
false
759
cpp
#include <iostream> #include "lattice.hpp" namespace lime { namespace converter { Lattice::Lattice(size_t column_count, unique_ptr<vector<shared_ptr<Node> > > nodes, unique_ptr<vector<vector<shared_ptr<Node> > > > begin_nodes, unique_ptr<vector<vector<shared_ptr<Node> > > > end_nodes) : column_count_(column_count), nodes_(move(nodes)), begin_nodes_(move(begin_nodes)), end_nodes_(move(end_nodes)) { } size_t Lattice::GetColumnCount() const { return column_count_; } vector<shared_ptr<Node> > &Lattice::GetBeginNodes(size_t pos) { return (*begin_nodes_)[pos]; } vector<shared_ptr<Node> > &Lattice::GetEndNodes(size_t pos) { return (*end_nodes_)[pos]; } } // converter } // lime
[ "hirokuni.maeta+github@gmail.com" ]
hirokuni.maeta+github@gmail.com
5b236fa686bb6dd64ba04aba7d3fcd477f229d43
73ee941896043f9b3e2ab40028d24ddd202f695f
/external/chromium_org/media/filters/decrypting_audio_decoder.cc
f516674a50ebcbaa8a61263b181c263e2f65faa4
[ "BSD-3-Clause" ]
permissive
CyFI-Lab-Public/RetroScope
d441ea28b33aceeb9888c330a54b033cd7d48b05
276b5b03d63f49235db74f2c501057abb9e79d89
refs/heads/master
2022-04-08T23:11:44.482107
2016-09-22T20:15:43
2016-09-22T20:15:43
58,890,600
5
3
null
null
null
null
UTF-8
C++
false
false
14,877
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/filters/decrypting_audio_decoder.h" #include <cstdlib> #include "base/bind.h" #include "base/callback_helpers.h" #include "base/location.h" #include "base/logging.h" #include "base/message_loop/message_loop_proxy.h" #include "media/base/audio_buffer.h" #include "media/base/audio_decoder_config.h" #include "media/base/audio_timestamp_helper.h" #include "media/base/bind_to_loop.h" #include "media/base/buffers.h" #include "media/base/decoder_buffer.h" #include "media/base/decryptor.h" #include "media/base/demuxer_stream.h" #include "media/base/pipeline.h" namespace media { const int DecryptingAudioDecoder::kSupportedBitsPerChannel = 16; static inline bool IsOutOfSync(const base::TimeDelta& timestamp_1, const base::TimeDelta& timestamp_2) { // Out of sync of 100ms would be pretty noticeable and we should keep any // drift below that. const int64 kOutOfSyncThresholdInMilliseconds = 100; return std::abs(timestamp_1.InMilliseconds() - timestamp_2.InMilliseconds()) > kOutOfSyncThresholdInMilliseconds; } DecryptingAudioDecoder::DecryptingAudioDecoder( const scoped_refptr<base::MessageLoopProxy>& message_loop, const SetDecryptorReadyCB& set_decryptor_ready_cb) : message_loop_(message_loop), weak_factory_(this), state_(kUninitialized), demuxer_stream_(NULL), set_decryptor_ready_cb_(set_decryptor_ready_cb), decryptor_(NULL), key_added_while_decode_pending_(false), bits_per_channel_(0), channel_layout_(CHANNEL_LAYOUT_NONE), samples_per_second_(0) { } void DecryptingAudioDecoder::Initialize( DemuxerStream* stream, const PipelineStatusCB& status_cb, const StatisticsCB& statistics_cb) { DVLOG(2) << "Initialize()"; DCHECK(message_loop_->BelongsToCurrentThread()); DCHECK_EQ(state_, kUninitialized) << state_; DCHECK(stream); weak_this_ = weak_factory_.GetWeakPtr(); init_cb_ = BindToCurrentLoop(status_cb); const AudioDecoderConfig& config = stream->audio_decoder_config(); if (!config.IsValidConfig()) { DLOG(ERROR) << "Invalid audio stream config."; base::ResetAndReturn(&init_cb_).Run(PIPELINE_ERROR_DECODE); return; } // DecryptingAudioDecoder only accepts potentially encrypted stream. if (!config.is_encrypted()) { base::ResetAndReturn(&init_cb_).Run(DECODER_ERROR_NOT_SUPPORTED); return; } DCHECK(!demuxer_stream_); demuxer_stream_ = stream; statistics_cb_ = statistics_cb; state_ = kDecryptorRequested; set_decryptor_ready_cb_.Run(BindToCurrentLoop( base::Bind(&DecryptingAudioDecoder::SetDecryptor, weak_this_))); } void DecryptingAudioDecoder::Read(const ReadCB& read_cb) { DVLOG(3) << "Read()"; DCHECK(message_loop_->BelongsToCurrentThread()); DCHECK(state_ == kIdle || state_ == kDecodeFinished) << state_; DCHECK(!read_cb.is_null()); CHECK(read_cb_.is_null()) << "Overlapping decodes are not supported."; read_cb_ = BindToCurrentLoop(read_cb); // Return empty (end-of-stream) frames if decoding has finished. if (state_ == kDecodeFinished) { base::ResetAndReturn(&read_cb_).Run(kOk, AudioBuffer::CreateEOSBuffer()); return; } if (!queued_audio_frames_.empty()) { base::ResetAndReturn(&read_cb_).Run(kOk, queued_audio_frames_.front()); queued_audio_frames_.pop_front(); return; } state_ = kPendingDemuxerRead; ReadFromDemuxerStream(); } void DecryptingAudioDecoder::Reset(const base::Closure& closure) { DVLOG(2) << "Reset() - state: " << state_; DCHECK(message_loop_->BelongsToCurrentThread()); DCHECK(state_ == kIdle || state_ == kPendingConfigChange || state_ == kPendingDemuxerRead || state_ == kPendingDecode || state_ == kWaitingForKey || state_ == kDecodeFinished) << state_; DCHECK(init_cb_.is_null()); // No Reset() during pending initialization. DCHECK(reset_cb_.is_null()); reset_cb_ = closure; decryptor_->ResetDecoder(Decryptor::kAudio); // Reset() cannot complete if the read callback is still pending. // Defer the resetting process in this case. The |reset_cb_| will be fired // after the read callback is fired - see DecryptAndDecodeBuffer() and // DeliverFrame(). if (state_ == kPendingConfigChange || state_ == kPendingDemuxerRead || state_ == kPendingDecode) { DCHECK(!read_cb_.is_null()); return; } if (state_ == kWaitingForKey) { DCHECK(!read_cb_.is_null()); pending_buffer_to_decode_ = NULL; base::ResetAndReturn(&read_cb_).Run(kAborted, NULL); } DCHECK(read_cb_.is_null()); DoReset(); } int DecryptingAudioDecoder::bits_per_channel() { DCHECK(message_loop_->BelongsToCurrentThread()); return bits_per_channel_; } ChannelLayout DecryptingAudioDecoder::channel_layout() { DCHECK(message_loop_->BelongsToCurrentThread()); return channel_layout_; } int DecryptingAudioDecoder::samples_per_second() { DCHECK(message_loop_->BelongsToCurrentThread()); return samples_per_second_; } DecryptingAudioDecoder::~DecryptingAudioDecoder() { } void DecryptingAudioDecoder::SetDecryptor(Decryptor* decryptor) { DVLOG(2) << "SetDecryptor()"; DCHECK(message_loop_->BelongsToCurrentThread()); DCHECK_EQ(state_, kDecryptorRequested) << state_; DCHECK(!init_cb_.is_null()); DCHECK(!set_decryptor_ready_cb_.is_null()); set_decryptor_ready_cb_.Reset(); if (!decryptor) { base::ResetAndReturn(&init_cb_).Run(DECODER_ERROR_NOT_SUPPORTED); // TODO(xhwang): Add kError state. See http://crbug.com/251503 state_ = kDecodeFinished; return; } decryptor_ = decryptor; const AudioDecoderConfig& input_config = demuxer_stream_->audio_decoder_config(); AudioDecoderConfig config; config.Initialize(input_config.codec(), kSampleFormatS16, input_config.channel_layout(), input_config.samples_per_second(), input_config.extra_data(), input_config.extra_data_size(), input_config.is_encrypted(), false); state_ = kPendingDecoderInit; decryptor_->InitializeAudioDecoder( config, BindToCurrentLoop(base::Bind( &DecryptingAudioDecoder::FinishInitialization, weak_this_))); } void DecryptingAudioDecoder::FinishInitialization(bool success) { DVLOG(2) << "FinishInitialization()"; DCHECK(message_loop_->BelongsToCurrentThread()); DCHECK_EQ(state_, kPendingDecoderInit) << state_; DCHECK(!init_cb_.is_null()); DCHECK(reset_cb_.is_null()); // No Reset() before initialization finished. DCHECK(read_cb_.is_null()); // No Read() before initialization finished. if (!success) { base::ResetAndReturn(&init_cb_).Run(DECODER_ERROR_NOT_SUPPORTED); state_ = kDecodeFinished; return; } // Success! UpdateDecoderConfig(); decryptor_->RegisterNewKeyCB( Decryptor::kAudio, BindToCurrentLoop(base::Bind( &DecryptingAudioDecoder::OnKeyAdded, weak_this_))); state_ = kIdle; base::ResetAndReturn(&init_cb_).Run(PIPELINE_OK); } void DecryptingAudioDecoder::FinishConfigChange(bool success) { DVLOG(2) << "FinishConfigChange()"; DCHECK(message_loop_->BelongsToCurrentThread()); DCHECK_EQ(state_, kPendingConfigChange) << state_; DCHECK(!read_cb_.is_null()); if (!success) { base::ResetAndReturn(&read_cb_).Run(kDecodeError, NULL); state_ = kDecodeFinished; if (!reset_cb_.is_null()) base::ResetAndReturn(&reset_cb_).Run(); return; } // Config change succeeded. UpdateDecoderConfig(); if (!reset_cb_.is_null()) { base::ResetAndReturn(&read_cb_).Run(kAborted, NULL); DoReset(); return; } state_ = kPendingDemuxerRead; ReadFromDemuxerStream(); } void DecryptingAudioDecoder::ReadFromDemuxerStream() { DCHECK_EQ(state_, kPendingDemuxerRead) << state_; DCHECK(!read_cb_.is_null()); demuxer_stream_->Read( base::Bind(&DecryptingAudioDecoder::DecryptAndDecodeBuffer, weak_this_)); } void DecryptingAudioDecoder::DecryptAndDecodeBuffer( DemuxerStream::Status status, const scoped_refptr<DecoderBuffer>& buffer) { DVLOG(3) << "DecryptAndDecodeBuffer()"; DCHECK(message_loop_->BelongsToCurrentThread()); DCHECK_EQ(state_, kPendingDemuxerRead) << state_; DCHECK(!read_cb_.is_null()); DCHECK_EQ(buffer.get() != NULL, status == DemuxerStream::kOk) << status; if (status == DemuxerStream::kConfigChanged) { DVLOG(2) << "DecryptAndDecodeBuffer() - kConfigChanged"; const AudioDecoderConfig& input_config = demuxer_stream_->audio_decoder_config(); AudioDecoderConfig config; config.Initialize(input_config.codec(), kSampleFormatS16, input_config.channel_layout(), input_config.samples_per_second(), input_config.extra_data(), input_config.extra_data_size(), input_config.is_encrypted(), false); state_ = kPendingConfigChange; decryptor_->DeinitializeDecoder(Decryptor::kAudio); decryptor_->InitializeAudioDecoder( config, BindToCurrentLoop(base::Bind( &DecryptingAudioDecoder::FinishConfigChange, weak_this_))); return; } if (!reset_cb_.is_null()) { base::ResetAndReturn(&read_cb_).Run(kAborted, NULL); DoReset(); return; } if (status == DemuxerStream::kAborted) { DVLOG(2) << "DecryptAndDecodeBuffer() - kAborted"; state_ = kIdle; base::ResetAndReturn(&read_cb_).Run(kAborted, NULL); return; } DCHECK_EQ(status, DemuxerStream::kOk); // Initialize the |next_output_timestamp_| to be the timestamp of the first // non-EOS buffer. if (timestamp_helper_->base_timestamp() == kNoTimestamp() && !buffer->end_of_stream()) { timestamp_helper_->SetBaseTimestamp(buffer->timestamp()); } pending_buffer_to_decode_ = buffer; state_ = kPendingDecode; DecodePendingBuffer(); } void DecryptingAudioDecoder::DecodePendingBuffer() { DCHECK(message_loop_->BelongsToCurrentThread()); DCHECK_EQ(state_, kPendingDecode) << state_; int buffer_size = 0; if (!pending_buffer_to_decode_->end_of_stream()) { buffer_size = pending_buffer_to_decode_->data_size(); } decryptor_->DecryptAndDecodeAudio( pending_buffer_to_decode_, BindToCurrentLoop(base::Bind( &DecryptingAudioDecoder::DeliverFrame, weak_this_, buffer_size))); } void DecryptingAudioDecoder::DeliverFrame( int buffer_size, Decryptor::Status status, const Decryptor::AudioBuffers& frames) { DVLOG(3) << "DeliverFrame() - status: " << status; DCHECK(message_loop_->BelongsToCurrentThread()); DCHECK_EQ(state_, kPendingDecode) << state_; DCHECK(!read_cb_.is_null()); DCHECK(pending_buffer_to_decode_.get()); DCHECK(queued_audio_frames_.empty()); bool need_to_try_again_if_nokey_is_returned = key_added_while_decode_pending_; key_added_while_decode_pending_ = false; scoped_refptr<DecoderBuffer> scoped_pending_buffer_to_decode = pending_buffer_to_decode_; pending_buffer_to_decode_ = NULL; if (!reset_cb_.is_null()) { base::ResetAndReturn(&read_cb_).Run(kAborted, NULL); DoReset(); return; } DCHECK_EQ(status == Decryptor::kSuccess, !frames.empty()); if (status == Decryptor::kError) { DVLOG(2) << "DeliverFrame() - kError"; state_ = kDecodeFinished; base::ResetAndReturn(&read_cb_).Run(kDecodeError, NULL); return; } if (status == Decryptor::kNoKey) { DVLOG(2) << "DeliverFrame() - kNoKey"; // Set |pending_buffer_to_decode_| back as we need to try decoding the // pending buffer again when new key is added to the decryptor. pending_buffer_to_decode_ = scoped_pending_buffer_to_decode; if (need_to_try_again_if_nokey_is_returned) { // The |state_| is still kPendingDecode. DecodePendingBuffer(); return; } state_ = kWaitingForKey; return; } // The buffer has been accepted by the decoder, let's report statistics. if (buffer_size) { PipelineStatistics statistics; statistics.audio_bytes_decoded = buffer_size; statistics_cb_.Run(statistics); } if (status == Decryptor::kNeedMoreData) { DVLOG(2) << "DeliverFrame() - kNeedMoreData"; if (scoped_pending_buffer_to_decode->end_of_stream()) { state_ = kDecodeFinished; base::ResetAndReturn(&read_cb_).Run(kOk, AudioBuffer::CreateEOSBuffer()); return; } state_ = kPendingDemuxerRead; ReadFromDemuxerStream(); return; } DCHECK_EQ(status, Decryptor::kSuccess); DCHECK(!frames.empty()); EnqueueFrames(frames); state_ = kIdle; base::ResetAndReturn(&read_cb_).Run(kOk, queued_audio_frames_.front()); queued_audio_frames_.pop_front(); } void DecryptingAudioDecoder::OnKeyAdded() { DCHECK(message_loop_->BelongsToCurrentThread()); if (state_ == kPendingDecode) { key_added_while_decode_pending_ = true; return; } if (state_ == kWaitingForKey) { state_ = kPendingDecode; DecodePendingBuffer(); } } void DecryptingAudioDecoder::DoReset() { DCHECK(init_cb_.is_null()); DCHECK(read_cb_.is_null()); timestamp_helper_->SetBaseTimestamp(kNoTimestamp()); state_ = kIdle; base::ResetAndReturn(&reset_cb_).Run(); } void DecryptingAudioDecoder::UpdateDecoderConfig() { const AudioDecoderConfig& config = demuxer_stream_->audio_decoder_config(); bits_per_channel_ = kSupportedBitsPerChannel; channel_layout_ = config.channel_layout(); samples_per_second_ = config.samples_per_second(); timestamp_helper_.reset(new AudioTimestampHelper(samples_per_second_)); } void DecryptingAudioDecoder::EnqueueFrames( const Decryptor::AudioBuffers& frames) { queued_audio_frames_ = frames; for (Decryptor::AudioBuffers::iterator iter = queued_audio_frames_.begin(); iter != queued_audio_frames_.end(); ++iter) { scoped_refptr<AudioBuffer>& frame = *iter; DCHECK(!frame->end_of_stream()) << "EOS frame returned."; DCHECK_GT(frame->frame_count(), 0) << "Empty frame returned."; base::TimeDelta current_time = timestamp_helper_->GetTimestamp(); if (IsOutOfSync(current_time, frame->timestamp())) { DVLOG(1) << "Timestamp returned by the decoder (" << frame->timestamp().InMilliseconds() << " ms)" << " does not match the input timestamp and number of samples" << " decoded (" << current_time.InMilliseconds() << " ms)."; } frame->set_timestamp(current_time); frame->set_duration( timestamp_helper_->GetFrameDuration(frame->frame_count())); timestamp_helper_->AddFrames(frame->frame_count()); } } } // namespace media
[ "ProjectRetroScope@gmail.com" ]
ProjectRetroScope@gmail.com
a273bf3e4195be4391760b8e66b9dfc77410b92c
c8358d07a468647ab80685e539cda1f195341d3b
/src/opencl_exclusive_scan.hpp
8ffe102809082239f351a3df5fdc27a7de00002f
[]
no_license
foduguay/exclusive_scan
ddcd73151607b6b91b8a29aa5238412b57534b37
f586c91786e3bac1c07e1cac8923617cc6a031fe
refs/heads/main
2023-02-13T20:22:52.783204
2021-01-16T12:00:45
2021-01-16T12:00:45
329,964,472
0
0
null
null
null
null
UTF-8
C++
false
false
6,765
hpp
#ifndef OPENCL_EXCLUSIVE_SCAN #define OPENCL_EXCLUSIVE_SCAN #define CL_TARGET_OPENCL_VERSION 120 #include <CL/cl.h> #define MAX_SOURCE_SIZE 100000 static char* value; static size_t valueSize; static cl_uint maxComputeUnits; static cl_platform_id platform_id[1]; static cl_device_id device_id[1]; static cl_uint ret_num_devices; static cl_uint ret_num_platforms; static cl_int ret; static cl_context context; static cl_command_queue command_queue; static cl_mem in_mem; static cl_mem out_mem; static cl_mem jump_mem; static cl_mem length; static cl_program program; static cl_kernel kernel, kernel_copy; static bool once = false; template<class IN_TYPE, class OUT_TYPE> bool exclusive_scan(const IN_TYPE* in, OUT_TYPE* out, int size) { // TODO make class if (!once) { once = true; ret = clGetPlatformIDs(1, platform_id, &ret_num_platforms); for (int i = 0; i < ret_num_platforms; i++) { ret = clGetDeviceIDs( platform_id[i], CL_DEVICE_TYPE_DEFAULT, 1, device_id, &ret_num_devices); // for each device print critical attributes for (int j = 0; j < ret_num_devices; j++) { // print device name clGetDeviceInfo(device_id[j], CL_DEVICE_NAME, 0, NULL, &valueSize); value = (char*) malloc(valueSize); clGetDeviceInfo(device_id[j], CL_DEVICE_NAME, valueSize, value, NULL); printf("%d. Device: %s\n", j+1, value); free(value); clGetDeviceInfo(device_id[j], CL_DEVICE_VERSION, 0, NULL, &valueSize); value = (char*) malloc(valueSize); clGetDeviceInfo(device_id[j], CL_DEVICE_VERSION, valueSize, value, NULL); printf(" %d.%d Hardware version: %s\n", j+1, 1, value); free(value); clGetDeviceInfo(device_id[j], CL_DRIVER_VERSION, 0, NULL, &valueSize); value = (char*) malloc(valueSize); clGetDeviceInfo(device_id[j], CL_DRIVER_VERSION, valueSize, value, NULL); printf(" %d.%d Software version: %s\n", j+1, 2, value); free(value); clGetDeviceInfo(device_id[j], CL_DEVICE_OPENCL_C_VERSION, 0, NULL, &valueSize); value = (char*) malloc(valueSize); clGetDeviceInfo(device_id[j], CL_DEVICE_OPENCL_C_VERSION, valueSize, value, NULL); printf(" %d.%d OpenCL C version: %s\n", j+1, 3, value); free(value); clGetDeviceInfo(device_id[j], CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(maxComputeUnits), &maxComputeUnits, NULL); printf(" %d.%d Parallel compute units: %d\n", j+1, 4, maxComputeUnits); } } context = clCreateContext( NULL, 1, device_id, NULL, NULL, &ret); command_queue = clCreateCommandQueue(context, device_id[0], 0, &ret); // Create memory buffers on the device for each vector in_mem = clCreateBuffer(context, CL_MEM_READ_ONLY, 32 * 1024 * 1024 * sizeof(int64_t), NULL, &ret); out_mem = clCreateBuffer(context, CL_MEM_READ_WRITE, 32 * 1024 * 1024 * sizeof(int64_t), NULL, &ret); jump_mem = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(int), NULL, &ret); length = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(int), NULL, &ret); FILE *fp; char *source_str; size_t source_size; fp = fopen("src/opencl_exclusive_scan.cl", "r"); if (!fp) { fprintf(stderr, "Failed to load kernel.\n"); exit(1); } source_str = (char*)malloc(MAX_SOURCE_SIZE); source_size = fread( source_str, 1, MAX_SOURCE_SIZE, fp); fclose( fp ); program = clCreateProgramWithSource(context, 1, (const char **)&source_str, (const size_t *)&source_size, &ret); ret = clBuildProgram(program, 1, device_id, NULL, NULL, NULL); assert(ret == CL_SUCCESS); auto kernel_name_copy = std::string("exclusive_copy_") + std::to_string(sizeof(IN_TYPE)) + "_" + std::to_string(sizeof(OUT_TYPE)); auto kernel_name = std::string("exclusive_scan_") + std::to_string(sizeof(IN_TYPE)) + "_" + std::to_string(sizeof(OUT_TYPE)); std::cout << kernel_name << std::endl; kernel_copy = clCreateKernel(program, kernel_name_copy.data(), &ret); assert(ret == CL_SUCCESS); ret = clSetKernelArg(kernel_copy, 0, sizeof(cl_mem), (void *)&in_mem); assert(ret == CL_SUCCESS); ret = clSetKernelArg(kernel_copy, 1, sizeof(cl_mem), (void *)&out_mem); assert(ret == CL_SUCCESS); ret = clSetKernelArg(kernel_copy, 2, sizeof(cl_mem), (void *)&jump_mem); assert(ret == CL_SUCCESS); ret = clSetKernelArg(kernel_copy, 3, sizeof(cl_mem), (void *)&length); assert(ret == CL_SUCCESS); kernel = clCreateKernel(program, kernel_name.data(), &ret); assert(ret == CL_SUCCESS); ret = clSetKernelArg(kernel, 0, sizeof(cl_mem), (void *)&in_mem); assert(ret == CL_SUCCESS); ret = clSetKernelArg(kernel, 1, sizeof(cl_mem), (void *)&out_mem); assert(ret == CL_SUCCESS); ret = clSetKernelArg(kernel, 2, sizeof(cl_mem), (void *)&jump_mem); assert(ret == CL_SUCCESS); ret = clSetKernelArg(kernel, 3, sizeof(cl_mem), (void *)&length); assert(ret == CL_SUCCESS); } ret = clEnqueueWriteBuffer(command_queue, in_mem, CL_FALSE, 0, size * sizeof(IN_TYPE), in, 0, NULL, NULL); assert(ret == CL_SUCCESS); ret = clEnqueueWriteBuffer(command_queue, length, CL_FALSE, 0, sizeof(int), &size, 0, NULL, NULL); assert(ret == CL_SUCCESS); size_t local_item_size = 960; size_t global_item_size = local_item_size * ((local_item_size - 1 + size) / local_item_size); ret = clEnqueueNDRangeKernel(command_queue, kernel_copy, 1, NULL, &global_item_size, &local_item_size, 0, NULL, NULL); assert(ret == CL_SUCCESS); for (int jump = 1; jump < size; jump *= 2) { ret = clEnqueueWriteBuffer(command_queue, jump_mem, CL_FALSE, 0, sizeof(int), &jump, 0, NULL, NULL); assert(ret == CL_SUCCESS); ret = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_item_size, &local_item_size, 0, NULL, NULL); assert(ret == CL_SUCCESS); } ret = clEnqueueReadBuffer(command_queue, out_mem, CL_TRUE, 0, size * sizeof(OUT_TYPE), out, 0, NULL, NULL); assert(ret == CL_SUCCESS); return true; } #endif // OPENCL_EXCLUSIVE_SCAN
[ "foduguay@gmail.com" ]
foduguay@gmail.com
8bed50582edac20d0ad6ada4d15fde70c938c54c
d096cfda35a174ca930b48944598aad67c6f7067
/KeybdName/KeybdName.cpp
23add1bc127cee3ddbe521d5b34001ea2bbc166e
[ "MIT" ]
permissive
katahiromz/ImeStudy
311c85671880bf72be198a77deb61634aef127c6
ce965f20b251ddf4d7ef0eb8229675d1373c598e
refs/heads/main
2023-06-08T21:34:59.032259
2023-06-04T07:29:52
2023-06-04T07:29:52
546,967,901
11
1
null
null
null
null
UTF-8
C++
false
false
267
cpp
// KeybdName.cpp by katahiromz // License: MIT #include <windows.h> #include <imm.h> #include <stdio.h> int main(int argc, char **argv) { char sz[KL_NAMELENGTH + 1]; GetKeyboardLayoutNameA(sz); printf("GetKeyboardLayoutNameA: %s\n", sz); return 0; }
[ "katayama.hirofumi.mz@gmail.com" ]
katayama.hirofumi.mz@gmail.com
66d374d3710f81bd9d763bcc52ce69fb87a71414
51ffd7b19109630911956fbf36cfd2ee5acc074c
/test/cpp/end2end/xds_end2end_test.cc
b876e062426acb78d2c126f6821d97acbd1e890e
[ "Apache-2.0" ]
permissive
zpdeng28/grpc
4022508cd0f4ee46de1d39347401ddc79eaaa58b
e39e7bc7c1df9f630c812ff1891e04cbd7c0829f
refs/heads/master
2022-12-01T20:05:39.798552
2019-05-20T07:01:07
2019-05-20T07:01:07
187,572,968
1
1
Apache-2.0
2022-11-16T14:50:06
2019-05-20T05:26:19
C++
UTF-8
C++
false
false
55,736
cc
/* * * Copyright 2017 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <memory> #include <mutex> #include <set> #include <sstream> #include <thread> #include <grpc/grpc.h> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/string_util.h> #include <grpc/support/time.h> #include <grpcpp/channel.h> #include <grpcpp/client_context.h> #include <grpcpp/create_channel.h> #include <grpcpp/server.h> #include <grpcpp/server_builder.h> #include "src/core/ext/filters/client_channel/backup_poller.h" #include "src/core/ext/filters/client_channel/parse_address.h" #include "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h" #include "src/core/ext/filters/client_channel/server_address.h" #include "src/core/lib/gpr/env.h" #include "src/core/lib/gprpp/ref_counted_ptr.h" #include "src/core/lib/iomgr/sockaddr.h" #include "src/core/lib/security/credentials/fake/fake_credentials.h" #include "src/cpp/client/secure_credentials.h" #include "src/cpp/server/secure_server_credentials.h" #include "test/core/util/port.h" #include "test/core/util/test_config.h" #include "test/cpp/end2end/test_service_impl.h" #include "src/proto/grpc/lb/v1/load_balancer.grpc.pb.h" #include "src/proto/grpc/testing/echo.grpc.pb.h" #include <gmock/gmock.h> #include <gtest/gtest.h> // TODO(dgq): Other scenarios in need of testing: // - Send a serverlist with faulty ip:port addresses (port > 2^16, etc). // - Test reception of invalid serverlist // - Test against a non-LB server. // - Random LB server closing the stream unexpectedly. // // Findings from end to end testing to be covered here: // - Handling of LB servers restart, including reconnection after backing-off // retries. // - Destruction of load balanced channel (and therefore of xds instance) // while: // 1) the internal LB call is still active. This should work by virtue // of the weak reference the LB call holds. The call should be terminated as // part of the xds shutdown process. // 2) the retry timer is active. Again, the weak reference it holds should // prevent a premature call to \a glb_destroy. using std::chrono::system_clock; using grpc::lb::v1::LoadBalanceRequest; using grpc::lb::v1::LoadBalanceResponse; using grpc::lb::v1::LoadBalancer; namespace grpc { namespace testing { namespace { template <typename ServiceType> class CountedService : public ServiceType { public: size_t request_count() { grpc::internal::MutexLock lock(&mu_); return request_count_; } size_t response_count() { grpc::internal::MutexLock lock(&mu_); return response_count_; } void IncreaseResponseCount() { grpc::internal::MutexLock lock(&mu_); ++response_count_; } void IncreaseRequestCount() { grpc::internal::MutexLock lock(&mu_); ++request_count_; } void ResetCounters() { grpc::internal::MutexLock lock(&mu_); request_count_ = 0; response_count_ = 0; } protected: grpc::internal::Mutex mu_; private: size_t request_count_ = 0; size_t response_count_ = 0; }; using BackendService = CountedService<TestServiceImpl>; using BalancerService = CountedService<LoadBalancer::Service>; const char g_kCallCredsMdKey[] = "Balancer should not ..."; const char g_kCallCredsMdValue[] = "... receive me"; class BackendServiceImpl : public BackendService { public: BackendServiceImpl() {} Status Echo(ServerContext* context, const EchoRequest* request, EchoResponse* response) override { // Backend should receive the call credentials metadata. auto call_credentials_entry = context->client_metadata().find(g_kCallCredsMdKey); EXPECT_NE(call_credentials_entry, context->client_metadata().end()); if (call_credentials_entry != context->client_metadata().end()) { EXPECT_EQ(call_credentials_entry->second, g_kCallCredsMdValue); } IncreaseRequestCount(); const auto status = TestServiceImpl::Echo(context, request, response); IncreaseResponseCount(); AddClient(context->peer()); return status; } void Shutdown() {} std::set<grpc::string> clients() { grpc::internal::MutexLock lock(&clients_mu_); return clients_; } private: void AddClient(const grpc::string& client) { grpc::internal::MutexLock lock(&clients_mu_); clients_.insert(client); } grpc::internal::Mutex mu_; grpc::internal::Mutex clients_mu_; std::set<grpc::string> clients_; }; grpc::string Ip4ToPackedString(const char* ip_str) { struct in_addr ip4; GPR_ASSERT(inet_pton(AF_INET, ip_str, &ip4) == 1); return grpc::string(reinterpret_cast<const char*>(&ip4), sizeof(ip4)); } struct ClientStats { size_t num_calls_started = 0; size_t num_calls_finished = 0; size_t num_calls_finished_with_client_failed_to_send = 0; size_t num_calls_finished_known_received = 0; std::map<grpc::string, size_t> drop_token_counts; ClientStats& operator+=(const ClientStats& other) { num_calls_started += other.num_calls_started; num_calls_finished += other.num_calls_finished; num_calls_finished_with_client_failed_to_send += other.num_calls_finished_with_client_failed_to_send; num_calls_finished_known_received += other.num_calls_finished_known_received; for (const auto& p : other.drop_token_counts) { drop_token_counts[p.first] += p.second; } return *this; } void Reset() { num_calls_started = 0; num_calls_finished = 0; num_calls_finished_with_client_failed_to_send = 0; num_calls_finished_known_received = 0; drop_token_counts.clear(); } }; class BalancerServiceImpl : public BalancerService { public: using Stream = ServerReaderWriter<LoadBalanceResponse, LoadBalanceRequest>; using ResponseDelayPair = std::pair<LoadBalanceResponse, int>; explicit BalancerServiceImpl(int client_load_reporting_interval_seconds) : client_load_reporting_interval_seconds_( client_load_reporting_interval_seconds) {} Status BalanceLoad(ServerContext* context, Stream* stream) override { // TODO(juanlishen): Clean up the scoping. gpr_log(GPR_INFO, "LB[%p]: BalanceLoad", this); { grpc::internal::MutexLock lock(&mu_); if (serverlist_done_) goto done; } { // Balancer shouldn't receive the call credentials metadata. EXPECT_EQ(context->client_metadata().find(g_kCallCredsMdKey), context->client_metadata().end()); LoadBalanceRequest request; std::vector<ResponseDelayPair> responses_and_delays; if (!stream->Read(&request)) { goto done; } IncreaseRequestCount(); gpr_log(GPR_INFO, "LB[%p]: received initial message '%s'", this, request.DebugString().c_str()); { LoadBalanceResponse initial_response; initial_response.mutable_initial_response() ->mutable_client_stats_report_interval() ->set_seconds(client_load_reporting_interval_seconds_); stream->Write(initial_response); } { grpc::internal::MutexLock lock(&mu_); responses_and_delays = responses_and_delays_; } for (const auto& response_and_delay : responses_and_delays) { SendResponse(stream, response_and_delay.first, response_and_delay.second); } { grpc::internal::MutexLock lock(&mu_); serverlist_cond_.WaitUntil(&mu_, [this] { return serverlist_done_; }); } if (client_load_reporting_interval_seconds_ > 0) { request.Clear(); if (stream->Read(&request)) { gpr_log(GPR_INFO, "LB[%p]: received client load report message '%s'", this, request.DebugString().c_str()); GPR_ASSERT(request.has_client_stats()); // We need to acquire the lock here in order to prevent the notify_one // below from firing before its corresponding wait is executed. grpc::internal::MutexLock lock(&mu_); client_stats_.num_calls_started += request.client_stats().num_calls_started(); client_stats_.num_calls_finished += request.client_stats().num_calls_finished(); client_stats_.num_calls_finished_with_client_failed_to_send += request.client_stats() .num_calls_finished_with_client_failed_to_send(); client_stats_.num_calls_finished_known_received += request.client_stats().num_calls_finished_known_received(); for (const auto& drop_token_count : request.client_stats().calls_finished_with_drop()) { client_stats_ .drop_token_counts[drop_token_count.load_balance_token()] += drop_token_count.num_calls(); } load_report_ready_ = true; load_report_cond_.Signal(); } } } done: gpr_log(GPR_INFO, "LB[%p]: done", this); return Status::OK; } void add_response(const LoadBalanceResponse& response, int send_after_ms) { grpc::internal::MutexLock lock(&mu_); responses_and_delays_.push_back(std::make_pair(response, send_after_ms)); } void Shutdown() { grpc::internal::MutexLock lock(&mu_); NotifyDoneWithServerlistsLocked(); responses_and_delays_.clear(); client_stats_.Reset(); gpr_log(GPR_INFO, "LB[%p]: shut down", this); } static LoadBalanceResponse BuildResponseForBackends( const std::vector<int>& backend_ports, const std::map<grpc::string, size_t>& drop_token_counts) { LoadBalanceResponse response; for (const auto& drop_token_count : drop_token_counts) { for (size_t i = 0; i < drop_token_count.second; ++i) { auto* server = response.mutable_server_list()->add_servers(); server->set_drop(true); server->set_load_balance_token(drop_token_count.first); } } for (const int& backend_port : backend_ports) { auto* server = response.mutable_server_list()->add_servers(); server->set_ip_address(Ip4ToPackedString("127.0.0.1")); server->set_port(backend_port); static int token_count = 0; char* token; gpr_asprintf(&token, "token%03d", ++token_count); server->set_load_balance_token(token); gpr_free(token); } return response; } const ClientStats& WaitForLoadReport() { grpc::internal::MutexLock lock(&mu_); load_report_cond_.WaitUntil(&mu_, [this] { return load_report_ready_; }); load_report_ready_ = false; return client_stats_; } void NotifyDoneWithServerlists() { grpc::internal::MutexLock lock(&mu_); NotifyDoneWithServerlistsLocked(); } void NotifyDoneWithServerlistsLocked() { if (!serverlist_done_) { serverlist_done_ = true; serverlist_cond_.Broadcast(); } } private: void SendResponse(Stream* stream, const LoadBalanceResponse& response, int delay_ms) { gpr_log(GPR_INFO, "LB[%p]: sleeping for %d ms...", this, delay_ms); if (delay_ms > 0) { gpr_sleep_until(grpc_timeout_milliseconds_to_deadline(delay_ms)); } gpr_log(GPR_INFO, "LB[%p]: Woke up! Sending response '%s'", this, response.DebugString().c_str()); IncreaseResponseCount(); stream->Write(response); } const int client_load_reporting_interval_seconds_; std::vector<ResponseDelayPair> responses_and_delays_; grpc::internal::Mutex mu_; grpc::internal::CondVar load_report_cond_; bool load_report_ready_ = false; grpc::internal::CondVar serverlist_cond_; bool serverlist_done_ = false; ClientStats client_stats_; }; class XdsEnd2endTest : public ::testing::Test { protected: XdsEnd2endTest(size_t num_backends, size_t num_balancers, int client_load_reporting_interval_seconds) : server_host_("localhost"), num_backends_(num_backends), num_balancers_(num_balancers), client_load_reporting_interval_seconds_( client_load_reporting_interval_seconds) { // Make the backup poller poll very frequently in order to pick up // updates from all the subchannels's FDs. GPR_GLOBAL_CONFIG_SET(grpc_client_channel_backup_poll_interval_ms, 1); } void SetUp() override { response_generator_ = grpc_core::MakeRefCounted<grpc_core::FakeResolverResponseGenerator>(); lb_channel_response_generator_ = grpc_core::MakeRefCounted<grpc_core::FakeResolverResponseGenerator>(); // Start the backends. for (size_t i = 0; i < num_backends_; ++i) { backends_.emplace_back(new ServerThread<BackendServiceImpl>("backend")); backends_.back()->Start(server_host_); } // Start the load balancers. for (size_t i = 0; i < num_balancers_; ++i) { balancers_.emplace_back(new ServerThread<BalancerServiceImpl>( "balancer", client_load_reporting_interval_seconds_)); balancers_.back()->Start(server_host_); } ResetStub(); } void TearDown() override { ShutdownAllBackends(); for (auto& balancer : balancers_) balancer->Shutdown(); } void StartAllBackends() { for (auto& backend : backends_) backend->Start(server_host_); } void StartBackend(size_t index) { backends_[index]->Start(server_host_); } void ShutdownAllBackends() { for (auto& backend : backends_) backend->Shutdown(); } void ShutdownBackend(size_t index) { backends_[index]->Shutdown(); } void ResetStub(int fallback_timeout = 0, const grpc::string& expected_targets = "") { ChannelArguments args; // TODO(juanlishen): Add setter to ChannelArguments. if (fallback_timeout > 0) { args.SetInt(GRPC_ARG_XDS_FALLBACK_TIMEOUT_MS, fallback_timeout); } args.SetPointer(GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR, response_generator_.get()); if (!expected_targets.empty()) { args.SetString(GRPC_ARG_FAKE_SECURITY_EXPECTED_TARGETS, expected_targets); } std::ostringstream uri; uri << "fake:///" << kApplicationTargetName_; // TODO(dgq): templatize tests to run everything using both secure and // insecure channel credentials. grpc_channel_credentials* channel_creds = grpc_fake_transport_security_credentials_create(); grpc_call_credentials* call_creds = grpc_md_only_test_credentials_create( g_kCallCredsMdKey, g_kCallCredsMdValue, false); std::shared_ptr<ChannelCredentials> creds( new SecureChannelCredentials(grpc_composite_channel_credentials_create( channel_creds, call_creds, nullptr))); call_creds->Unref(); channel_creds->Unref(); channel_ = ::grpc::CreateCustomChannel(uri.str(), creds, args); stub_ = grpc::testing::EchoTestService::NewStub(channel_); } void ResetBackendCounters() { for (auto& backend : backends_) backend->service_.ResetCounters(); } ClientStats WaitForLoadReports() { ClientStats client_stats; for (auto& balancer : balancers_) { client_stats += balancer->service_.WaitForLoadReport(); } return client_stats; } bool SeenAllBackends(size_t start_index = 0, size_t stop_index = 0) { if (stop_index == 0) stop_index = backends_.size(); for (size_t i = start_index; i < stop_index; ++i) { if (backends_[i]->service_.request_count() == 0) return false; } return true; } void SendRpcAndCount(int* num_total, int* num_ok, int* num_failure, int* num_drops) { const Status status = SendRpc(); if (status.ok()) { ++*num_ok; } else { if (status.error_message() == "Call dropped by load balancing policy") { ++*num_drops; } else { ++*num_failure; } } ++*num_total; } std::tuple<int, int, int> WaitForAllBackends(int num_requests_multiple_of = 1, size_t start_index = 0, size_t stop_index = 0) { int num_ok = 0; int num_failure = 0; int num_drops = 0; int num_total = 0; while (!SeenAllBackends(start_index, stop_index)) { SendRpcAndCount(&num_total, &num_ok, &num_failure, &num_drops); } while (num_total % num_requests_multiple_of != 0) { SendRpcAndCount(&num_total, &num_ok, &num_failure, &num_drops); } ResetBackendCounters(); gpr_log(GPR_INFO, "Performed %d warm up requests (a multiple of %d) against the " "backends. %d succeeded, %d failed, %d dropped.", num_total, num_requests_multiple_of, num_ok, num_failure, num_drops); return std::make_tuple(num_ok, num_failure, num_drops); } void WaitForBackend(size_t backend_idx) { do { (void)SendRpc(); } while (backends_[backend_idx]->service_.request_count() == 0); ResetBackendCounters(); } grpc_core::ServerAddressList CreateLbAddressesFromPortList( const std::vector<int>& ports) { grpc_core::ServerAddressList addresses; for (int port : ports) { char* lb_uri_str; gpr_asprintf(&lb_uri_str, "ipv4:127.0.0.1:%d", port); grpc_uri* lb_uri = grpc_uri_parse(lb_uri_str, true); GPR_ASSERT(lb_uri != nullptr); grpc_resolved_address address; GPR_ASSERT(grpc_parse_uri(lb_uri, &address)); std::vector<grpc_arg> args_to_add; grpc_channel_args* args = grpc_channel_args_copy_and_add( nullptr, args_to_add.data(), args_to_add.size()); addresses.emplace_back(address.addr, address.len, args); grpc_uri_destroy(lb_uri); gpr_free(lb_uri_str); } return addresses; } void SetNextResolution(const std::vector<int>& ports, const char* service_config_json = nullptr, grpc_core::FakeResolverResponseGenerator* lb_channel_response_generator = nullptr) { grpc_core::ExecCtx exec_ctx; grpc_core::Resolver::Result result; result.addresses = CreateLbAddressesFromPortList(ports); if (service_config_json != nullptr) { grpc_error* error = GRPC_ERROR_NONE; result.service_config = grpc_core::ServiceConfig::Create(service_config_json, &error); GRPC_ERROR_UNREF(error); } grpc_arg arg = grpc_core::FakeResolverResponseGenerator::MakeChannelArg( lb_channel_response_generator == nullptr ? lb_channel_response_generator_.get() : lb_channel_response_generator); result.args = grpc_channel_args_copy_and_add(nullptr, &arg, 1); response_generator_->SetResponse(std::move(result)); } void SetNextResolutionForLbChannelAllBalancers( const char* service_config_json = nullptr, grpc_core::FakeResolverResponseGenerator* lb_channel_response_generator = nullptr) { std::vector<int> ports; for (size_t i = 0; i < balancers_.size(); ++i) { ports.emplace_back(balancers_[i]->port_); } SetNextResolutionForLbChannel(ports, service_config_json, lb_channel_response_generator); } void SetNextResolutionForLbChannel( const std::vector<int>& ports, const char* service_config_json = nullptr, grpc_core::FakeResolverResponseGenerator* lb_channel_response_generator = nullptr) { grpc_core::ExecCtx exec_ctx; grpc_core::Resolver::Result result; result.addresses = CreateLbAddressesFromPortList(ports); if (service_config_json != nullptr) { grpc_error* error = GRPC_ERROR_NONE; result.service_config = grpc_core::ServiceConfig::Create(service_config_json, &error); GRPC_ERROR_UNREF(error); } if (lb_channel_response_generator == nullptr) { lb_channel_response_generator = lb_channel_response_generator_.get(); } lb_channel_response_generator->SetResponse(std::move(result)); } void SetNextReresolutionResponse(const std::vector<int>& ports) { grpc_core::ExecCtx exec_ctx; grpc_core::Resolver::Result result; result.addresses = CreateLbAddressesFromPortList(ports); response_generator_->SetReresolutionResponse(std::move(result)); } const std::vector<int> GetBackendPorts(size_t start_index = 0, size_t stop_index = 0) const { if (stop_index == 0) stop_index = backends_.size(); std::vector<int> backend_ports; for (size_t i = start_index; i < stop_index; ++i) { backend_ports.push_back(backends_[i]->port_); } return backend_ports; } void ScheduleResponseForBalancer(size_t i, const LoadBalanceResponse& response, int delay_ms) { balancers_[i]->service_.add_response(response, delay_ms); } Status SendRpc(EchoResponse* response = nullptr, int timeout_ms = 1000, bool wait_for_ready = false) { const bool local_response = (response == nullptr); if (local_response) response = new EchoResponse; EchoRequest request; request.set_message(kRequestMessage_); ClientContext context; context.set_deadline(grpc_timeout_milliseconds_to_deadline(timeout_ms)); if (wait_for_ready) context.set_wait_for_ready(true); Status status = stub_->Echo(&context, request, response); if (local_response) delete response; return status; } void CheckRpcSendOk(const size_t times = 1, const int timeout_ms = 1000, bool wait_for_ready = false) { for (size_t i = 0; i < times; ++i) { EchoResponse response; const Status status = SendRpc(&response, timeout_ms, wait_for_ready); EXPECT_TRUE(status.ok()) << "code=" << status.error_code() << " message=" << status.error_message(); EXPECT_EQ(response.message(), kRequestMessage_); } } void CheckRpcSendFailure() { const Status status = SendRpc(); EXPECT_FALSE(status.ok()); } template <typename T> struct ServerThread { template <typename... Args> explicit ServerThread(const grpc::string& type, Args&&... args) : port_(grpc_pick_unused_port_or_die()), type_(type), service_(std::forward<Args>(args)...) {} void Start(const grpc::string& server_host) { gpr_log(GPR_INFO, "starting %s server on port %d", type_.c_str(), port_); GPR_ASSERT(!running_); running_ = true; grpc::internal::Mutex mu; // We need to acquire the lock here in order to prevent the notify_one // by ServerThread::Serve from firing before the wait below is hit. grpc::internal::MutexLock lock(&mu); grpc::internal::CondVar cond; thread_.reset(new std::thread( std::bind(&ServerThread::Serve, this, server_host, &mu, &cond))); cond.Wait(&mu); gpr_log(GPR_INFO, "%s server startup complete", type_.c_str()); } void Serve(const grpc::string& server_host, grpc::internal::Mutex* mu, grpc::internal::CondVar* cond) { // We need to acquire the lock here in order to prevent the notify_one // below from firing before its corresponding wait is executed. grpc::internal::MutexLock lock(mu); std::ostringstream server_address; server_address << server_host << ":" << port_; ServerBuilder builder; std::shared_ptr<ServerCredentials> creds(new SecureServerCredentials( grpc_fake_transport_security_server_credentials_create())); builder.AddListeningPort(server_address.str(), creds); builder.RegisterService(&service_); server_ = builder.BuildAndStart(); cond->Signal(); } void Shutdown() { if (!running_) return; gpr_log(GPR_INFO, "%s about to shutdown", type_.c_str()); service_.Shutdown(); server_->Shutdown(grpc_timeout_milliseconds_to_deadline(0)); thread_->join(); gpr_log(GPR_INFO, "%s shutdown completed", type_.c_str()); running_ = false; } const int port_; grpc::string type_; T service_; std::unique_ptr<Server> server_; std::unique_ptr<std::thread> thread_; bool running_ = false; }; const grpc::string server_host_; const size_t num_backends_; const size_t num_balancers_; const int client_load_reporting_interval_seconds_; std::shared_ptr<Channel> channel_; std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_; std::vector<std::unique_ptr<ServerThread<BackendServiceImpl>>> backends_; std::vector<std::unique_ptr<ServerThread<BalancerServiceImpl>>> balancers_; grpc_core::RefCountedPtr<grpc_core::FakeResolverResponseGenerator> response_generator_; grpc_core::RefCountedPtr<grpc_core::FakeResolverResponseGenerator> lb_channel_response_generator_; const grpc::string kRequestMessage_ = "Live long and prosper."; const grpc::string kApplicationTargetName_ = "application_target_name"; const grpc::string kDefaultServiceConfig_ = "{\n" " \"loadBalancingConfig\":[\n" " { \"does_not_exist\":{} },\n" " { \"xds_experimental\":{ \"balancerName\": \"fake:///lb\" } }\n" " ]\n" "}"; }; class SingleBalancerTest : public XdsEnd2endTest { public: SingleBalancerTest() : XdsEnd2endTest(4, 1, 0) {} }; TEST_F(SingleBalancerTest, Vanilla) { SetNextResolution({}, kDefaultServiceConfig_.c_str()); SetNextResolutionForLbChannelAllBalancers(); const size_t kNumRpcsPerAddress = 100; ScheduleResponseForBalancer( 0, BalancerServiceImpl::BuildResponseForBackends(GetBackendPorts(), {}), 0); // Make sure that trying to connect works without a call. channel_->GetState(true /* try_to_connect */); // We need to wait for all backends to come online. WaitForAllBackends(); // Send kNumRpcsPerAddress RPCs per server. CheckRpcSendOk(kNumRpcsPerAddress * num_backends_); // Each backend should have gotten 100 requests. for (size_t i = 0; i < backends_.size(); ++i) { EXPECT_EQ(kNumRpcsPerAddress, backends_[i]->service_.request_count()); } balancers_[0]->service_.NotifyDoneWithServerlists(); // The balancer got a single request. EXPECT_EQ(1U, balancers_[0]->service_.request_count()); // and sent a single response. EXPECT_EQ(1U, balancers_[0]->service_.response_count()); // Check LB policy name for the channel. EXPECT_EQ("xds_experimental", channel_->GetLoadBalancingPolicyName()); } TEST_F(SingleBalancerTest, SameBackendListedMultipleTimes) { SetNextResolution({}, kDefaultServiceConfig_.c_str()); SetNextResolutionForLbChannelAllBalancers(); // Same backend listed twice. std::vector<int> ports; ports.push_back(backends_[0]->port_); ports.push_back(backends_[0]->port_); const size_t kNumRpcsPerAddress = 10; ScheduleResponseForBalancer( 0, BalancerServiceImpl::BuildResponseForBackends(ports, {}), 0); // We need to wait for the backend to come online. WaitForBackend(0); // Send kNumRpcsPerAddress RPCs per server. CheckRpcSendOk(kNumRpcsPerAddress * ports.size()); // Backend should have gotten 20 requests. EXPECT_EQ(kNumRpcsPerAddress * 2, backends_[0]->service_.request_count()); // And they should have come from a single client port, because of // subchannel sharing. EXPECT_EQ(1UL, backends_[0]->service_.clients().size()); balancers_[0]->service_.NotifyDoneWithServerlists(); } TEST_F(SingleBalancerTest, SecureNaming) { // TODO(juanlishen): Use separate fake creds for the balancer channel. ResetStub(0, kApplicationTargetName_ + ";lb"); SetNextResolution({}, kDefaultServiceConfig_.c_str()); SetNextResolutionForLbChannel({balancers_[0]->port_}); const size_t kNumRpcsPerAddress = 100; ScheduleResponseForBalancer( 0, BalancerServiceImpl::BuildResponseForBackends(GetBackendPorts(), {}), 0); // Make sure that trying to connect works without a call. channel_->GetState(true /* try_to_connect */); // We need to wait for all backends to come online. WaitForAllBackends(); // Send kNumRpcsPerAddress RPCs per server. CheckRpcSendOk(kNumRpcsPerAddress * num_backends_); // Each backend should have gotten 100 requests. for (size_t i = 0; i < backends_.size(); ++i) { EXPECT_EQ(kNumRpcsPerAddress, backends_[i]->service_.request_count()); } // The balancer got a single request. EXPECT_EQ(1U, balancers_[0]->service_.request_count()); // and sent a single response. EXPECT_EQ(1U, balancers_[0]->service_.response_count()); } TEST_F(SingleBalancerTest, SecureNamingDeathTest) { ::testing::FLAGS_gtest_death_test_style = "threadsafe"; // Make sure that we blow up (via abort() from the security connector) when // the name from the balancer doesn't match expectations. ASSERT_DEATH( { ResetStub(0, kApplicationTargetName_ + ";lb"); SetNextResolution({}, "{\n" " \"loadBalancingConfig\":[\n" " { \"does_not_exist\":{} },\n" " { \"xds_experimental\":{ \"balancerName\": " "\"fake:///wrong_lb\" } }\n" " ]\n" "}"); SetNextResolutionForLbChannel({balancers_[0]->port_}); channel_->WaitForConnected(grpc_timeout_seconds_to_deadline(1)); }, ""); } TEST_F(SingleBalancerTest, InitiallyEmptyServerlist) { SetNextResolution({}, kDefaultServiceConfig_.c_str()); SetNextResolutionForLbChannelAllBalancers(); const int kServerlistDelayMs = 500 * grpc_test_slowdown_factor(); const int kCallDeadlineMs = kServerlistDelayMs * 2; // First response is an empty serverlist, sent right away. ScheduleResponseForBalancer(0, LoadBalanceResponse(), 0); // Send non-empty serverlist only after kServerlistDelayMs ScheduleResponseForBalancer( 0, BalancerServiceImpl::BuildResponseForBackends(GetBackendPorts(), {}), kServerlistDelayMs); const auto t0 = system_clock::now(); // Client will block: LB will initially send empty serverlist. CheckRpcSendOk(1, kCallDeadlineMs, true /* wait_for_ready */); const auto ellapsed_ms = std::chrono::duration_cast<std::chrono::milliseconds>( system_clock::now() - t0); // but eventually, the LB sends a serverlist update that allows the call to // proceed. The call delay must be larger than the delay in sending the // populated serverlist but under the call's deadline (which is enforced by // the call's deadline). EXPECT_GT(ellapsed_ms.count(), kServerlistDelayMs); balancers_[0]->service_.NotifyDoneWithServerlists(); // The balancer got a single request. EXPECT_EQ(1U, balancers_[0]->service_.request_count()); // and sent two responses. EXPECT_EQ(2U, balancers_[0]->service_.response_count()); } TEST_F(SingleBalancerTest, AllServersUnreachableFailFast) { SetNextResolution({}, kDefaultServiceConfig_.c_str()); SetNextResolutionForLbChannelAllBalancers(); const size_t kNumUnreachableServers = 5; std::vector<int> ports; for (size_t i = 0; i < kNumUnreachableServers; ++i) { ports.push_back(grpc_pick_unused_port_or_die()); } ScheduleResponseForBalancer( 0, BalancerServiceImpl::BuildResponseForBackends(ports, {}), 0); const Status status = SendRpc(); // The error shouldn't be DEADLINE_EXCEEDED. EXPECT_EQ(StatusCode::UNAVAILABLE, status.error_code()); balancers_[0]->service_.NotifyDoneWithServerlists(); // The balancer got a single request. EXPECT_EQ(1U, balancers_[0]->service_.request_count()); // and sent a single response. EXPECT_EQ(1U, balancers_[0]->service_.response_count()); } TEST_F(SingleBalancerTest, Fallback) { const int kFallbackTimeoutMs = 200 * grpc_test_slowdown_factor(); const int kServerlistDelayMs = 500 * grpc_test_slowdown_factor(); const size_t kNumBackendsInResolution = backends_.size() / 2; ResetStub(kFallbackTimeoutMs); SetNextResolution(GetBackendPorts(0, kNumBackendsInResolution), kDefaultServiceConfig_.c_str()); SetNextResolutionForLbChannelAllBalancers(); // Send non-empty serverlist only after kServerlistDelayMs. ScheduleResponseForBalancer( 0, BalancerServiceImpl::BuildResponseForBackends( GetBackendPorts(kNumBackendsInResolution /* start_index */), {}), kServerlistDelayMs); // Wait until all the fallback backends are reachable. WaitForAllBackends(1 /* num_requests_multiple_of */, 0 /* start_index */, kNumBackendsInResolution /* stop_index */); gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH =========="); CheckRpcSendOk(kNumBackendsInResolution); gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH =========="); // Fallback is used: each backend returned by the resolver should have // gotten one request. for (size_t i = 0; i < kNumBackendsInResolution; ++i) { EXPECT_EQ(1U, backends_[i]->service_.request_count()); } for (size_t i = kNumBackendsInResolution; i < backends_.size(); ++i) { EXPECT_EQ(0U, backends_[i]->service_.request_count()); } // Wait until the serverlist reception has been processed and all backends // in the serverlist are reachable. WaitForAllBackends(1 /* num_requests_multiple_of */, kNumBackendsInResolution /* start_index */); gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH =========="); CheckRpcSendOk(backends_.size() - kNumBackendsInResolution); gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH =========="); // Serverlist is used: each backend returned by the balancer should // have gotten one request. for (size_t i = 0; i < kNumBackendsInResolution; ++i) { EXPECT_EQ(0U, backends_[i]->service_.request_count()); } for (size_t i = kNumBackendsInResolution; i < backends_.size(); ++i) { EXPECT_EQ(1U, backends_[i]->service_.request_count()); } // The balancer got a single request. EXPECT_EQ(1U, balancers_[0]->service_.request_count()); // and sent a single response. EXPECT_EQ(1U, balancers_[0]->service_.response_count()); } TEST_F(SingleBalancerTest, FallbackUpdate) { const int kFallbackTimeoutMs = 200 * grpc_test_slowdown_factor(); const int kServerlistDelayMs = 500 * grpc_test_slowdown_factor(); const size_t kNumBackendsInResolution = backends_.size() / 3; const size_t kNumBackendsInResolutionUpdate = backends_.size() / 3; ResetStub(kFallbackTimeoutMs); SetNextResolution(GetBackendPorts(0, kNumBackendsInResolution), kDefaultServiceConfig_.c_str()); SetNextResolutionForLbChannelAllBalancers(); // Send non-empty serverlist only after kServerlistDelayMs. ScheduleResponseForBalancer( 0, BalancerServiceImpl::BuildResponseForBackends( GetBackendPorts(kNumBackendsInResolution + kNumBackendsInResolutionUpdate /* start_index */), {}), kServerlistDelayMs); // Wait until all the fallback backends are reachable. WaitForAllBackends(1 /* num_requests_multiple_of */, 0 /* start_index */, kNumBackendsInResolution /* stop_index */); gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH =========="); CheckRpcSendOk(kNumBackendsInResolution); gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH =========="); // Fallback is used: each backend returned by the resolver should have // gotten one request. for (size_t i = 0; i < kNumBackendsInResolution; ++i) { EXPECT_EQ(1U, backends_[i]->service_.request_count()); } for (size_t i = kNumBackendsInResolution; i < backends_.size(); ++i) { EXPECT_EQ(0U, backends_[i]->service_.request_count()); } SetNextResolution(GetBackendPorts(kNumBackendsInResolution, kNumBackendsInResolution + kNumBackendsInResolutionUpdate), kDefaultServiceConfig_.c_str()); // Wait until the resolution update has been processed and all the new // fallback backends are reachable. WaitForAllBackends(1 /* num_requests_multiple_of */, kNumBackendsInResolution /* start_index */, kNumBackendsInResolution + kNumBackendsInResolutionUpdate /* stop_index */); gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH =========="); CheckRpcSendOk(kNumBackendsInResolutionUpdate); gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH =========="); // The resolution update is used: each backend in the resolution update should // have gotten one request. for (size_t i = 0; i < kNumBackendsInResolution; ++i) { EXPECT_EQ(0U, backends_[i]->service_.request_count()); } for (size_t i = kNumBackendsInResolution; i < kNumBackendsInResolution + kNumBackendsInResolutionUpdate; ++i) { EXPECT_EQ(1U, backends_[i]->service_.request_count()); } for (size_t i = kNumBackendsInResolution + kNumBackendsInResolutionUpdate; i < backends_.size(); ++i) { EXPECT_EQ(0U, backends_[i]->service_.request_count()); } // Wait until the serverlist reception has been processed and all backends // in the serverlist are reachable. WaitForAllBackends(1 /* num_requests_multiple_of */, kNumBackendsInResolution + kNumBackendsInResolutionUpdate /* start_index */); gpr_log(GPR_INFO, "========= BEFORE THIRD BATCH =========="); CheckRpcSendOk(backends_.size() - kNumBackendsInResolution - kNumBackendsInResolutionUpdate); gpr_log(GPR_INFO, "========= DONE WITH THIRD BATCH =========="); // Serverlist is used: each backend returned by the balancer should // have gotten one request. for (size_t i = 0; i < kNumBackendsInResolution + kNumBackendsInResolutionUpdate; ++i) { EXPECT_EQ(0U, backends_[i]->service_.request_count()); } for (size_t i = kNumBackendsInResolution + kNumBackendsInResolutionUpdate; i < backends_.size(); ++i) { EXPECT_EQ(1U, backends_[i]->service_.request_count()); } // The balancer got a single request. EXPECT_EQ(1U, balancers_[0]->service_.request_count()); // and sent a single response. EXPECT_EQ(1U, balancers_[0]->service_.response_count()); } TEST_F(SingleBalancerTest, FallbackEarlyWhenBalancerChannelFails) { const int kFallbackTimeoutMs = 10000 * grpc_test_slowdown_factor(); ResetStub(kFallbackTimeoutMs); // Return an unreachable balancer and one fallback backend. SetNextResolution({backends_[0]->port_}, kDefaultServiceConfig_.c_str()); SetNextResolutionForLbChannel({grpc_pick_unused_port_or_die()}); // Send RPC with deadline less than the fallback timeout and make sure it // succeeds. CheckRpcSendOk(/* times */ 1, /* timeout_ms */ 1000, /* wait_for_ready */ false); } TEST_F(SingleBalancerTest, FallbackEarlyWhenBalancerCallFails) { const int kFallbackTimeoutMs = 10000 * grpc_test_slowdown_factor(); ResetStub(kFallbackTimeoutMs); // Return one balancer and one fallback backend. SetNextResolution({backends_[0]->port_}, kDefaultServiceConfig_.c_str()); SetNextResolutionForLbChannelAllBalancers(); // Balancer drops call without sending a serverlist. balancers_[0]->service_.NotifyDoneWithServerlists(); // Send RPC with deadline less than the fallback timeout and make sure it // succeeds. CheckRpcSendOk(/* times */ 1, /* timeout_ms */ 1000, /* wait_for_ready */ false); } TEST_F(SingleBalancerTest, FallbackModeIsExitedWhenBalancerSaysToDropAllCalls) { // Return an unreachable balancer and one fallback backend. SetNextResolution({backends_[0]->port_}, kDefaultServiceConfig_.c_str()); SetNextResolutionForLbChannel({grpc_pick_unused_port_or_die()}); // Enter fallback mode because the LB channel fails to connect. WaitForBackend(0); // Return a new balancer that sends an empty serverlist. ScheduleResponseForBalancer( 0, BalancerServiceImpl::BuildResponseForBackends({}, {}), 0); SetNextResolutionForLbChannelAllBalancers(); // Send RPCs until failure. gpr_timespec deadline = gpr_time_add( gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_millis(5000, GPR_TIMESPAN)); do { auto status = SendRpc(); if (!status.ok()) break; } while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0); CheckRpcSendFailure(); } TEST_F(SingleBalancerTest, FallbackModeIsExitedAfterChildRready) { // Return an unreachable balancer and one fallback backend. SetNextResolution({backends_[0]->port_}, kDefaultServiceConfig_.c_str()); SetNextResolutionForLbChannel({grpc_pick_unused_port_or_die()}); // Enter fallback mode because the LB channel fails to connect. WaitForBackend(0); // Return a new balancer that sends a dead backend. ShutdownBackend(1); ScheduleResponseForBalancer( 0, BalancerServiceImpl::BuildResponseForBackends({backends_[1]->port_}, {}), 0); SetNextResolutionForLbChannelAllBalancers(); // The state (TRANSIENT_FAILURE) update from the child policy will be ignored // because we are still in fallback mode. gpr_timespec deadline = gpr_time_add( gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_millis(5000, GPR_TIMESPAN)); // Send 5 seconds worth of RPCs. do { CheckRpcSendOk(); } while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0); // After the backend is restarted, the child policy will eventually be READY, // and we will exit fallback mode. StartBackend(1); WaitForBackend(1); // We have exited fallback mode, so calls will go to the child policy // exclusively. CheckRpcSendOk(100); EXPECT_EQ(0U, backends_[0]->service_.request_count()); EXPECT_EQ(100U, backends_[1]->service_.request_count()); } TEST_F(SingleBalancerTest, BackendsRestart) { SetNextResolution({}, kDefaultServiceConfig_.c_str()); SetNextResolutionForLbChannelAllBalancers(); ScheduleResponseForBalancer( 0, BalancerServiceImpl::BuildResponseForBackends(GetBackendPorts(), {}), 0); WaitForAllBackends(); // Stop backends. RPCs should fail. ShutdownAllBackends(); CheckRpcSendFailure(); // Restart all backends. RPCs should start succeeding again. StartAllBackends(); CheckRpcSendOk(1 /* times */, 2000 /* timeout_ms */, true /* wait_for_ready */); } class UpdatesTest : public XdsEnd2endTest { public: UpdatesTest() : XdsEnd2endTest(4, 3, 0) {} }; TEST_F(UpdatesTest, UpdateBalancersButKeepUsingOriginalBalancer) { SetNextResolution({}, kDefaultServiceConfig_.c_str()); SetNextResolutionForLbChannelAllBalancers(); const std::vector<int> first_backend{GetBackendPorts()[0]}; const std::vector<int> second_backend{GetBackendPorts()[1]}; ScheduleResponseForBalancer( 0, BalancerServiceImpl::BuildResponseForBackends(first_backend, {}), 0); ScheduleResponseForBalancer( 1, BalancerServiceImpl::BuildResponseForBackends(second_backend, {}), 0); // Wait until the first backend is ready. WaitForBackend(0); // Send 10 requests. gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH =========="); CheckRpcSendOk(10); gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH =========="); // All 10 requests should have gone to the first backend. EXPECT_EQ(10U, backends_[0]->service_.request_count()); // Balancer 0 got a single request. EXPECT_EQ(1U, balancers_[0]->service_.request_count()); // and sent a single response. EXPECT_EQ(1U, balancers_[0]->service_.response_count()); EXPECT_EQ(0U, balancers_[1]->service_.request_count()); EXPECT_EQ(0U, balancers_[1]->service_.response_count()); EXPECT_EQ(0U, balancers_[2]->service_.request_count()); EXPECT_EQ(0U, balancers_[2]->service_.response_count()); gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 1 =========="); SetNextResolutionForLbChannel({balancers_[1]->port_}); gpr_log(GPR_INFO, "========= UPDATE 1 DONE =========="); EXPECT_EQ(0U, backends_[1]->service_.request_count()); gpr_timespec deadline = gpr_time_add( gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_millis(10000, GPR_TIMESPAN)); // Send 10 seconds worth of RPCs do { CheckRpcSendOk(); } while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0); // The current LB call is still working, so xds continued using it to the // first balancer, which doesn't assign the second backend. EXPECT_EQ(0U, backends_[1]->service_.request_count()); EXPECT_EQ(1U, balancers_[0]->service_.request_count()); EXPECT_EQ(1U, balancers_[0]->service_.response_count()); EXPECT_EQ(0U, balancers_[1]->service_.request_count()); EXPECT_EQ(0U, balancers_[1]->service_.response_count()); EXPECT_EQ(0U, balancers_[2]->service_.request_count()); EXPECT_EQ(0U, balancers_[2]->service_.response_count()); } TEST_F(UpdatesTest, UpdateBalancerName) { SetNextResolution({}, kDefaultServiceConfig_.c_str()); SetNextResolutionForLbChannelAllBalancers(); const std::vector<int> first_backend{GetBackendPorts()[0]}; const std::vector<int> second_backend{GetBackendPorts()[1]}; ScheduleResponseForBalancer( 0, BalancerServiceImpl::BuildResponseForBackends(first_backend, {}), 0); ScheduleResponseForBalancer( 1, BalancerServiceImpl::BuildResponseForBackends(second_backend, {}), 0); // Wait until the first backend is ready. WaitForBackend(0); // Send 10 requests. gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH =========="); CheckRpcSendOk(10); gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH =========="); // All 10 requests should have gone to the first backend. EXPECT_EQ(10U, backends_[0]->service_.request_count()); // Balancer 0 got a single request. EXPECT_EQ(1U, balancers_[0]->service_.request_count()); // and sent a single response. EXPECT_EQ(1U, balancers_[0]->service_.response_count()); EXPECT_EQ(0U, balancers_[1]->service_.request_count()); EXPECT_EQ(0U, balancers_[1]->service_.response_count()); EXPECT_EQ(0U, balancers_[2]->service_.request_count()); EXPECT_EQ(0U, balancers_[2]->service_.response_count()); std::vector<int> ports; ports.emplace_back(balancers_[1]->port_); auto new_lb_channel_response_generator = grpc_core::MakeRefCounted<grpc_core::FakeResolverResponseGenerator>(); SetNextResolutionForLbChannel(ports, nullptr, new_lb_channel_response_generator.get()); gpr_log(GPR_INFO, "========= ABOUT TO UPDATE BALANCER NAME =========="); SetNextResolution({}, "{\n" " \"loadBalancingConfig\":[\n" " { \"does_not_exist\":{} },\n" " { \"xds_experimental\":{ \"balancerName\": " "\"fake:///updated_lb\" } }\n" " ]\n" "}", new_lb_channel_response_generator.get()); gpr_log(GPR_INFO, "========= UPDATED BALANCER NAME =========="); // Wait until update has been processed, as signaled by the second backend // receiving a request. EXPECT_EQ(0U, backends_[1]->service_.request_count()); WaitForBackend(1); backends_[1]->service_.ResetCounters(); gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH =========="); CheckRpcSendOk(10); gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH =========="); // All 10 requests should have gone to the second backend. EXPECT_EQ(10U, backends_[1]->service_.request_count()); EXPECT_EQ(1U, balancers_[0]->service_.request_count()); EXPECT_EQ(1U, balancers_[0]->service_.response_count()); EXPECT_EQ(1U, balancers_[1]->service_.request_count()); EXPECT_EQ(1U, balancers_[1]->service_.response_count()); EXPECT_EQ(0U, balancers_[2]->service_.request_count()); EXPECT_EQ(0U, balancers_[2]->service_.response_count()); } // Send an update with the same set of LBs as the one in SetUp() in order to // verify that the LB channel inside xds keeps the initial connection (which // by definition is also present in the update). TEST_F(UpdatesTest, UpdateBalancersRepeated) { SetNextResolution({}, kDefaultServiceConfig_.c_str()); SetNextResolutionForLbChannelAllBalancers(); const std::vector<int> first_backend{GetBackendPorts()[0]}; const std::vector<int> second_backend{GetBackendPorts()[0]}; ScheduleResponseForBalancer( 0, BalancerServiceImpl::BuildResponseForBackends(first_backend, {}), 0); ScheduleResponseForBalancer( 1, BalancerServiceImpl::BuildResponseForBackends(second_backend, {}), 0); // Wait until the first backend is ready. WaitForBackend(0); // Send 10 requests. gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH =========="); CheckRpcSendOk(10); gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH =========="); // All 10 requests should have gone to the first backend. EXPECT_EQ(10U, backends_[0]->service_.request_count()); // Balancer 0 got a single request. EXPECT_EQ(1U, balancers_[0]->service_.request_count()); // and sent a single response. EXPECT_EQ(1U, balancers_[0]->service_.response_count()); EXPECT_EQ(0U, balancers_[1]->service_.request_count()); EXPECT_EQ(0U, balancers_[1]->service_.response_count()); EXPECT_EQ(0U, balancers_[2]->service_.request_count()); EXPECT_EQ(0U, balancers_[2]->service_.response_count()); std::vector<int> ports; ports.emplace_back(balancers_[0]->port_); ports.emplace_back(balancers_[1]->port_); ports.emplace_back(balancers_[2]->port_); gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 1 =========="); SetNextResolutionForLbChannel(ports); gpr_log(GPR_INFO, "========= UPDATE 1 DONE =========="); EXPECT_EQ(0U, backends_[1]->service_.request_count()); gpr_timespec deadline = gpr_time_add( gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_millis(10000, GPR_TIMESPAN)); // Send 10 seconds worth of RPCs do { CheckRpcSendOk(); } while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0); // xds continued using the original LB call to the first balancer, which // doesn't assign the second backend. EXPECT_EQ(0U, backends_[1]->service_.request_count()); ports.clear(); ports.emplace_back(balancers_[0]->port_); ports.emplace_back(balancers_[1]->port_); gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 2 =========="); SetNextResolutionForLbChannel(ports); gpr_log(GPR_INFO, "========= UPDATE 2 DONE =========="); EXPECT_EQ(0U, backends_[1]->service_.request_count()); deadline = gpr_time_add(gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_millis(10000, GPR_TIMESPAN)); // Send 10 seconds worth of RPCs do { CheckRpcSendOk(); } while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0); // xds continued using the original LB call to the first balancer, which // doesn't assign the second backend. EXPECT_EQ(0U, backends_[1]->service_.request_count()); } TEST_F(UpdatesTest, UpdateBalancersDeadUpdate) { SetNextResolution({}, kDefaultServiceConfig_.c_str()); SetNextResolutionForLbChannel({balancers_[0]->port_}); const std::vector<int> first_backend{GetBackendPorts()[0]}; const std::vector<int> second_backend{GetBackendPorts()[1]}; ScheduleResponseForBalancer( 0, BalancerServiceImpl::BuildResponseForBackends(first_backend, {}), 0); ScheduleResponseForBalancer( 1, BalancerServiceImpl::BuildResponseForBackends(second_backend, {}), 0); // Start servers and send 10 RPCs per server. gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH =========="); CheckRpcSendOk(10); gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH =========="); // All 10 requests should have gone to the first backend. EXPECT_EQ(10U, backends_[0]->service_.request_count()); // Kill balancer 0 gpr_log(GPR_INFO, "********** ABOUT TO KILL BALANCER 0 *************"); balancers_[0]->Shutdown(); gpr_log(GPR_INFO, "********** KILLED BALANCER 0 *************"); // This is serviced by the existing child policy. gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH =========="); CheckRpcSendOk(10); gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH =========="); // All 10 requests should again have gone to the first backend. EXPECT_EQ(20U, backends_[0]->service_.request_count()); EXPECT_EQ(0U, backends_[1]->service_.request_count()); // Balancer 0 got a single request. EXPECT_EQ(1U, balancers_[0]->service_.request_count()); // and sent a single response. EXPECT_EQ(1U, balancers_[0]->service_.response_count()); EXPECT_EQ(0U, balancers_[1]->service_.request_count()); EXPECT_EQ(0U, balancers_[1]->service_.response_count()); EXPECT_EQ(0U, balancers_[2]->service_.request_count()); EXPECT_EQ(0U, balancers_[2]->service_.response_count()); gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 1 =========="); SetNextResolutionForLbChannel({balancers_[1]->port_}); gpr_log(GPR_INFO, "========= UPDATE 1 DONE =========="); // Wait until update has been processed, as signaled by the second backend // receiving a request. In the meantime, the client continues to be serviced // (by the first backend) without interruption. EXPECT_EQ(0U, backends_[1]->service_.request_count()); WaitForBackend(1); // This is serviced by the updated RR policy backends_[1]->service_.ResetCounters(); gpr_log(GPR_INFO, "========= BEFORE THIRD BATCH =========="); CheckRpcSendOk(10); gpr_log(GPR_INFO, "========= DONE WITH THIRD BATCH =========="); // All 10 requests should have gone to the second backend. EXPECT_EQ(10U, backends_[1]->service_.request_count()); EXPECT_EQ(1U, balancers_[0]->service_.request_count()); EXPECT_EQ(1U, balancers_[0]->service_.response_count()); // The second balancer, published as part of the first update, may end up // getting two requests (that is, 1 <= #req <= 2) if the LB call retry timer // firing races with the arrival of the update containing the second // balancer. EXPECT_GE(balancers_[1]->service_.request_count(), 1U); EXPECT_GE(balancers_[1]->service_.response_count(), 1U); EXPECT_LE(balancers_[1]->service_.request_count(), 2U); EXPECT_LE(balancers_[1]->service_.response_count(), 2U); EXPECT_EQ(0U, balancers_[2]->service_.request_count()); EXPECT_EQ(0U, balancers_[2]->service_.response_count()); } // The re-resolution tests are deferred because they rely on the fallback mode, // which hasn't been supported. // TODO(juanlishen): Add TEST_F(UpdatesTest, ReresolveDeadBackend). // TODO(juanlishen): Add TEST_F(UpdatesWithClientLoadReportingTest, // ReresolveDeadBalancer) // The drop tests are deferred because the drop handling hasn't been added yet. // TODO(roth): Add TEST_F(SingleBalancerTest, Drop) // TODO(roth): Add TEST_F(SingleBalancerTest, DropAllFirst) // TODO(roth): Add TEST_F(SingleBalancerTest, DropAll) class SingleBalancerWithClientLoadReportingTest : public XdsEnd2endTest { public: SingleBalancerWithClientLoadReportingTest() : XdsEnd2endTest(4, 1, 3) {} }; // The client load reporting tests are deferred because the client load // reporting hasn't been supported yet. // TODO(vpowar): Add TEST_F(SingleBalancerWithClientLoadReportingTest, Vanilla) // TODO(roth): Add TEST_F(SingleBalancerWithClientLoadReportingTest, // BalancerRestart) // TODO(roth): Add TEST_F(SingleBalancerWithClientLoadReportingTest, Drop) } // namespace } // namespace testing } // namespace grpc int main(int argc, char** argv) { grpc_init(); grpc::testing::TestEnvironment env(argc, argv); ::testing::InitGoogleTest(&argc, argv); const auto result = RUN_ALL_TESTS(); grpc_shutdown(); return result; }
[ "dzp_whu@163.com" ]
dzp_whu@163.com
42e71c700761ec1b5bdc961c65e7d5f7aadc5a62
f3a2948ff49b11723f37123a11eedbdae171f7a4
/src/consumer/DefaultMQPushConsumer.cpp
e14da6866537ce3b90ddb9df9a1384928d39103b
[ "Apache-2.0" ]
permissive
hooligan520/rocketmq-client4cpp-linux
1656aed9f3de0e0c1b2a54d945ff560ab272cd5d
2f891c979229dfd78707150fa626ca3822f2d006
refs/heads/master
2021-01-11T05:12:45.678389
2017-05-08T03:58:49
2017-05-08T03:58:49
81,163,610
22
10
null
null
null
null
UTF-8
C++
false
false
10,090
cpp
/** * Copyright (C) 2013 kangliqiang ,kangliq@163.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "DefaultMQPushConsumer.h" #include <list> #include <string> #include "DefaultMQPushConsumerImpl.h" #include "MessageQueue.h" #include "MessageExt.h" #include "ClientConfig.h" #include "ConsumerStatManage.h" #include "MixAll.h" #include "AllocateMessageQueueStrategyInner.h" namespace rmq { class AllocateMessageQueueStrategy; DefaultMQPushConsumer::DefaultMQPushConsumer() { m_consumerGroup = MixAll::DEFAULT_CONSUMER_GROUP; m_messageModel = CLUSTERING; m_consumeFromWhere = CONSUME_FROM_LAST_OFFSET; m_pAllocateMessageQueueStrategy = new AllocateMessageQueueAveragely(); m_pMessageListener = NULL; m_consumeThreadMin = 5; m_consumeThreadMax = 25; m_consumeConcurrentlyMaxSpan = 2000; m_pullThresholdForQueue = 1000; m_pullInterval = 0; m_consumeMessageBatchMaxSize = 1; m_pullBatchSize = 32; m_postSubscriptionWhenPull = false; m_unitMode = false; m_maxReconsumeTimes = 16; m_suspendCurrentQueueTimeMillis = 1000; m_consumeTimeout = 15; m_pOffsetStore = NULL; m_pDefaultMQPushConsumerImpl = new DefaultMQPushConsumerImpl(this); } DefaultMQPushConsumer::DefaultMQPushConsumer(const std::string& consumerGroup) { m_consumerGroup = consumerGroup; m_messageModel = CLUSTERING; m_consumeFromWhere = CONSUME_FROM_LAST_OFFSET; m_pAllocateMessageQueueStrategy = new AllocateMessageQueueAveragely(); m_pMessageListener = NULL; m_consumeThreadMin = 5; m_consumeThreadMax = 25; m_consumeConcurrentlyMaxSpan = 2000; m_pullThresholdForQueue = 1000; m_pullInterval = 0; m_consumeMessageBatchMaxSize = 1; m_pullBatchSize = 32; m_postSubscriptionWhenPull = false; m_unitMode = false; m_maxReconsumeTimes = 16; m_suspendCurrentQueueTimeMillis = 1000; m_consumeTimeout = 15; m_pOffsetStore = NULL; m_pDefaultMQPushConsumerImpl = new DefaultMQPushConsumerImpl(this); } DefaultMQPushConsumer::~DefaultMQPushConsumer() { delete m_pAllocateMessageQueueStrategy; // memleak: 释放有可能core delete m_pDefaultMQPushConsumerImpl; } //MQAdmin void DefaultMQPushConsumer::createTopic(const std::string& key, const std::string& newTopic, int queueNum) { m_pDefaultMQPushConsumerImpl->createTopic(key, newTopic, queueNum); } long long DefaultMQPushConsumer::searchOffset(const MessageQueue& mq, long long timestamp) { return m_pDefaultMQPushConsumerImpl->searchOffset(mq, timestamp); } long long DefaultMQPushConsumer::maxOffset(const MessageQueue& mq) { return m_pDefaultMQPushConsumerImpl->maxOffset(mq); } long long DefaultMQPushConsumer::minOffset(const MessageQueue& mq) { return m_pDefaultMQPushConsumerImpl->minOffset(mq); } long long DefaultMQPushConsumer::earliestMsgStoreTime(const MessageQueue& mq) { return m_pDefaultMQPushConsumerImpl->earliestMsgStoreTime(mq); } MessageExt* DefaultMQPushConsumer::viewMessage(const std::string& msgId) { return m_pDefaultMQPushConsumerImpl->viewMessage(msgId); } QueryResult DefaultMQPushConsumer::queryMessage(const std::string& topic, const std::string& key, int maxNum, long long begin, long long end) { return m_pDefaultMQPushConsumerImpl->queryMessage(topic, key, maxNum, begin, end); } // MQadmin end AllocateMessageQueueStrategy* DefaultMQPushConsumer::getAllocateMessageQueueStrategy() { return m_pAllocateMessageQueueStrategy; } void DefaultMQPushConsumer::setAllocateMessageQueueStrategy(AllocateMessageQueueStrategy* pAllocateMessageQueueStrategy) { m_pAllocateMessageQueueStrategy = pAllocateMessageQueueStrategy; } int DefaultMQPushConsumer::getConsumeConcurrentlyMaxSpan() { return m_consumeConcurrentlyMaxSpan; } void DefaultMQPushConsumer::setConsumeConcurrentlyMaxSpan(int consumeConcurrentlyMaxSpan) { m_consumeConcurrentlyMaxSpan = consumeConcurrentlyMaxSpan; } ConsumeFromWhere DefaultMQPushConsumer::getConsumeFromWhere() { return m_consumeFromWhere; } void DefaultMQPushConsumer::setConsumeFromWhere(ConsumeFromWhere consumeFromWhere) { m_consumeFromWhere = consumeFromWhere; } int DefaultMQPushConsumer::getConsumeMessageBatchMaxSize() { return m_consumeMessageBatchMaxSize; } void DefaultMQPushConsumer::setConsumeMessageBatchMaxSize(int consumeMessageBatchMaxSize) { m_consumeMessageBatchMaxSize = consumeMessageBatchMaxSize; } std::string DefaultMQPushConsumer::getConsumerGroup() { return m_consumerGroup; } void DefaultMQPushConsumer::setConsumerGroup(const std::string& consumerGroup) { m_consumerGroup = consumerGroup; } int DefaultMQPushConsumer::getConsumeThreadMax() { return m_consumeThreadMax; } void DefaultMQPushConsumer::setConsumeThreadMax(int consumeThreadMax) { m_consumeThreadMax = consumeThreadMax; } int DefaultMQPushConsumer::getConsumeThreadMin() { return m_consumeThreadMin; } void DefaultMQPushConsumer::setConsumeThreadMin(int consumeThreadMin) { m_consumeThreadMin = consumeThreadMin; } DefaultMQPushConsumerImpl* DefaultMQPushConsumer::getDefaultMQPushConsumerImpl() { return m_pDefaultMQPushConsumerImpl; } MessageListener* DefaultMQPushConsumer::getMessageListener() { return m_pMessageListener; } void DefaultMQPushConsumer::setMessageListener(MessageListener* pMessageListener) { m_pMessageListener = pMessageListener; } MessageModel DefaultMQPushConsumer::getMessageModel() { return m_messageModel; } void DefaultMQPushConsumer::setMessageModel(MessageModel messageModel) { m_messageModel = messageModel; } int DefaultMQPushConsumer::getPullBatchSize() { return m_pullBatchSize; } void DefaultMQPushConsumer::setPullBatchSize(int pullBatchSize) { m_pullBatchSize = pullBatchSize; } long DefaultMQPushConsumer::getPullInterval() { return m_pullInterval; } void DefaultMQPushConsumer::setPullInterval(long pullInterval) { m_pullInterval = pullInterval; } int DefaultMQPushConsumer::getPullThresholdForQueue() { return m_pullThresholdForQueue; } void DefaultMQPushConsumer::setPullThresholdForQueue(int pullThresholdForQueue) { m_pullThresholdForQueue = pullThresholdForQueue; } std::map<std::string, std::string>& DefaultMQPushConsumer::getSubscription() { return m_subscription; } void DefaultMQPushConsumer::setSubscription(const std::map<std::string, std::string>& subscription) { m_subscription = subscription; } //MQConsumer void DefaultMQPushConsumer::sendMessageBack(MessageExt& msg, int delayLevel) { m_pDefaultMQPushConsumerImpl->sendMessageBack(msg, delayLevel, ""); } void DefaultMQPushConsumer::sendMessageBack(MessageExt& msg, int delayLevel, const std::string brokerName) { m_pDefaultMQPushConsumerImpl->sendMessageBack(msg, delayLevel, brokerName); } std::set<MessageQueue>* DefaultMQPushConsumer::fetchSubscribeMessageQueues(const std::string& topic) { return m_pDefaultMQPushConsumerImpl->fetchSubscribeMessageQueues(topic); } void DefaultMQPushConsumer::start() { m_pDefaultMQPushConsumerImpl->start(); } void DefaultMQPushConsumer::shutdown() { m_pDefaultMQPushConsumerImpl->shutdown(); } //MQConsumer end //MQPushConsumer void DefaultMQPushConsumer::registerMessageListener(MessageListener* pMessageListener) { m_pMessageListener = pMessageListener; m_pDefaultMQPushConsumerImpl->registerMessageListener(pMessageListener); } void DefaultMQPushConsumer::subscribe(const std::string& topic, const std::string& subExpression) { m_pDefaultMQPushConsumerImpl->subscribe(topic, subExpression); } void DefaultMQPushConsumer::unsubscribe(const std::string& topic) { m_pDefaultMQPushConsumerImpl->unsubscribe(topic); } void DefaultMQPushConsumer::updateCorePoolSize(int corePoolSize) { m_pDefaultMQPushConsumerImpl->updateCorePoolSize(corePoolSize); } void DefaultMQPushConsumer::suspend() { m_pDefaultMQPushConsumerImpl->suspend(); } void DefaultMQPushConsumer::resume() { m_pDefaultMQPushConsumerImpl->resume(); } //MQPushConsumer end OffsetStore* DefaultMQPushConsumer::getOffsetStore() { return m_pOffsetStore; } void DefaultMQPushConsumer::setOffsetStore(OffsetStore* pOffsetStore) { m_pOffsetStore = pOffsetStore; } std::string DefaultMQPushConsumer::getConsumeTimestamp() { return m_consumeTimestamp; } void DefaultMQPushConsumer::setConsumeTimestamp(std::string consumeTimestamp) { m_consumeTimestamp = consumeTimestamp; } bool DefaultMQPushConsumer::isPostSubscriptionWhenPull() { return m_postSubscriptionWhenPull; } void DefaultMQPushConsumer::setPostSubscriptionWhenPull(bool postSubscriptionWhenPull) { m_postSubscriptionWhenPull = postSubscriptionWhenPull; } bool DefaultMQPushConsumer::isUnitMode() { return m_unitMode; } void DefaultMQPushConsumer::setUnitMode(bool isUnitMode) { m_unitMode = isUnitMode; } int DefaultMQPushConsumer::getMaxReconsumeTimes() { return m_maxReconsumeTimes; } void DefaultMQPushConsumer::setMaxReconsumeTimes(int maxReconsumeTimes) { m_maxReconsumeTimes = maxReconsumeTimes; } int DefaultMQPushConsumer::getSuspendCurrentQueueTimeMillis() { return m_suspendCurrentQueueTimeMillis; } void DefaultMQPushConsumer::setSuspendCurrentQueueTimeMillis(int suspendCurrentQueueTimeMillis) { m_suspendCurrentQueueTimeMillis = suspendCurrentQueueTimeMillis; } int DefaultMQPushConsumer::getConsumeTimeout() { return m_consumeTimeout; } void DefaultMQPushConsumer::setConsumeTimeout(int consumeTimeout) { m_consumeTimeout = consumeTimeout; } }
[ "79015166@qq.com" ]
79015166@qq.com
461d5bb9867eff4b40fa6d755ed7a6a3dcfac310
da5fcf2b56a3b8e6417e1560650ce13fbae12f73
/Main.cpp
318d804d2963f1924869ada7d6716bae92b5419d
[]
no_license
gjbr5/airodump
8446de9dc5898c1a22883a41326fb8adb771e3eb
e980c27ccce22aae70cb0f8f175363055226de0a
refs/heads/master
2021-01-02T06:00:43.868707
2020-02-10T13:49:41
2020-02-10T13:49:41
239,520,281
0
0
null
null
null
null
UTF-8
C++
false
false
526
cpp
#include "Parser.h" #include <pcap.h> int main(int argc, char* argv[]) { const char* file = "C:\\Users\\gjbr5\\Desktop\\80211.pcapng"; char errbuf[PCAP_ERRBUF_SIZE]; pcap_t* handle = pcap_open_offline(file, errbuf); if (!handle) { std::cout << "File Open Failed.\n"; return 0; } Parser parser; while (true) { struct pcap_pkthdr* header; const uint8_t* packet; if (pcap_next_ex(handle, &header, &packet) < 0) break; parser.parse80211(packet, header->caplen); } pcap_close(handle); parser.print(); }
[ "wlwogud02@naver.com" ]
wlwogud02@naver.com
c6df38a808b465d0b4f922c0314caaf7be7ed935
558dece528927a181dcf8afdc6b6c85edaaeb584
/String/Z-algo/CF - 1138D with Z algo.cpp
35e6143afb6ce2148bf72630db27d3eaded7a99e
[]
no_license
rohannstu/Algorithms
dd5e9bc8d57ba512ad2b1d27bb761eda7d3ed1a9
b121d952d01687dd52279b91ef19d9533ba05be5
refs/heads/master
2023-04-09T12:30:21.547535
2021-04-08T11:23:54
2021-04-08T11:23:54
569,421,358
1
0
null
2022-11-22T19:40:43
2022-11-22T19:40:41
null
UTF-8
C++
false
false
5,122
cpp
#include<bits/stdc++.h> #define Input freopen("in.txt","r",stdin) #define Output freopen("out.txt","w",stdout) #define ll long long int #define ull unsigned long long int #define pii pair<int,int> #define pll pair<ll,ll> #define sc scanf #define scin(x) sc("%d",&(x)) #define scin2(x,y) sc("%d %d",&(x),&(y)) #define scln(x) sc("%lld",&(x)) #define scln2(x,y) sc("%lld %lld",&(x),&(y)) #define pf printf #define ms(a,b) memset(a,b,sizeof(a)) #define pb(a) push_back(a) #define mp make_pair #define db double #define EPS 10E-10 #define ff first #define ss second #define sqr(x) (x)*(x) #define vi vector<int> #define vl vector<ll> #define vii vector<vector<int> > #define vll vector<vector<ll> > #define DBG pf("HI\n") #define MOD 998244353 #define CIN ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0) #define RUN_CASE(t,T) for(__typeof(t) t=1;t<=T;t++) #define CASE(t) printf("Case %d: ",t) #define CASEl(t) printf("Case %d:\n",t) #define intlimit 214748369 #define longlimit 92233720368547758 #define infinity (1<<28) #define gcd(a,b) __gcd(a,b) #define lcm(a,b) ((a)*(b))/gcd(a,b) #define mxx 123456789 #define PI 2*acos(0.0) #define rep(i,a,b) for(__typeof(i) i=a;i<=b;i++) #define rev(i,a,b) for(__typeof(i) i=a;i>=b;i--) using namespace std; /** toint, tostring, BigMod, Power , sieve, Primefactorize ,frequency in n!**/ //ll toint(string s){ll n=0,k=1;for(int i=s.size()-1;i>=0;i--){n += ((s[i]-'0')*k);k*=10;}return n;} //string tostring(ll n){string s="";ll x;while(n > 0){x=n%10;s +=(char)(x+'0');n/=10;}reverse(s.begin(),s.end());return s;} //ll BigMod(ll a,ll b,ll m){if(b == 0)return 1%m;else if(b%2 == 0){ll temp=BigMod(a,b/2,m);return ((temp%m)*(temp%m))%m;}else{return ((a%m)*BigMod(a,b-1,m)%m)%m;}} //ll power(ll a,ll n){ll ans=1;if(n == 0)return 1;else if(n == 1)return a;else return a*power(a,n-1);} //vector<ll>Prime;bool mark[10000009]; //void sieve(ll n){ll i,j;mark[1]=1;for(i=4; i<=n; i+=2)mark[i]=1;Prime.push_back(2);for(i=3; i<=n; i+=2){if(!mark[i]){Prime.push_back(i);if(i*i<=n){for(j=i*i; j<=n; j+=(i*2))mark[j]=1;}}}} //vector<ll>List; //void Primefactorize(ll n){for(ll i=0; Prime[i]*Prime[i]<=n; i++){if(n%Prime[i] == 0){while(n%Prime[i] == 0){List.push_back(Prime[i]);n/=Prime[i];}}}if(n>1){List.push_back(n);}} //ll frequency(ll n,ll factor)/** Frequency of a factor in n! **/{ll cnt=0;while(n){cnt += (n/factor);n /= factor;}return cnt;} /** Order Set **/ //#include <ext/pb_ds/assoc_container.hpp> //using namespace __gnu_pbds; //template<typename T> using orderset = tree<T,null_type,less<T>,rb_tree_tag,tree_order_statistics_node_update>; //orderset<int> s ; //orderset<int>::iterator it ; //orderset<int> X; //X.insert(1); //X.insert(2); //X.insert(4); //X.insert(8); //X.insert(16); //cout<<*X.find_by_order(1)<<endl; // 2 //cout<<*X.find_by_order(2)<<endl; // 4 //cout<<*X.find_by_order(4)<<endl; // 16 //cout<<(end(X)==X.find_by_order(6))<<endl; // true //cout<<X.order_of_key(-5)<<endl; // 0 //cout<<X.order_of_key(1)<<endl; // 0 //cout<<X.order_of_key(3)<<endl; // 2 //cout<<X.order_of_key(4)<<endl; // 2 //cout<<X.order_of_key(400)<<endl; // 5 vi z_fun(string s) { int i,l,r,n; n = s.size(); vi z(n); for(i=1,l=0,r=0 ; i<n ; i++) { if(i <= r) z[i] = min(r-i+1,z[i-l]); while(i+z[i]<n && s[z[i]]==s[i+z[i]]) ++z[i]; if(i+z[i]-1 > r) { l=i; r=i+z[i]-1; } } return z; } int m[2]; int main() { int i,j,k,n,ans=0,cnt=0; vi Z; string s,t; cin>>s>>t; Z = z_fun(t); for(i=0;i<s.size();i++) { m[s[i] - '0']++; } n = t.size(); for(i=0 ; i<n ; i++) { if(i+Z[i] == n) { if(Z[i] > cnt) cnt = Z[i]; } } for(i=0;i<cnt;i++){ if(m[t[i] - '0'] > 0){ pf("%c",t[i]); m[t[i] - '0']--; } } while(1) { for(i=cnt ; i<n ; i++) { if(m[t[i] - '0'] > 0){ pf("%c",t[i]); m[t[i] - '0']--; } } if(m[0]==0 || m[1]==0) break; } while(m[0] > 0) { pf("0"); m[0]--; } while(m[1] > 0) { pf("1"); m[1]--; } pf("\n"); return 0; }
[ "noreply@github.com" ]
rohannstu.noreply@github.com
92435219f5f547606162ef8ea46418b6d66e0594
ba246ba78fbfa9980081705690cfc26ec5ca8859
/VAS_HeadtrackerConnect/build-VAS_HeadtrackerConnect_Android-Android_for_armeabi_v7a_arm64_v8a_x86_x86_64_Clang_Qt_5_15_2_android-Debug/armeabi-v7a/moc_serviceinfo.cpp
3174a2be6fdb01b572f141c99e61c302d1b1f7a0
[ "MIT" ]
permissive
funkerresch/vas_library
80d57a334f5a9575d9a27fe6910cc5dddb9b0f7f
0658616e49e86627614e9ad2382cb0b11e7d31eb
refs/heads/master
2022-12-21T22:00:33.957639
2022-07-20T09:06:35
2022-07-20T09:06:35
164,434,730
21
2
null
null
null
null
UTF-8
C++
false
false
3,935
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'serviceinfo.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.15.2) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include <memory> #include "../../../../rwacreator/bluetooth/serviceinfo.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'serviceinfo.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.15.2. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_ServiceInfo_t { QByteArrayData data[3]; char stringdata0[28]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_ServiceInfo_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_ServiceInfo_t qt_meta_stringdata_ServiceInfo = { { QT_MOC_LITERAL(0, 0, 11), // "ServiceInfo" QT_MOC_LITERAL(1, 12, 14), // "serviceChanged" QT_MOC_LITERAL(2, 27, 0) // "" }, "ServiceInfo\0serviceChanged\0" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_ServiceInfo[] = { // content: 8, // revision 0, // classname 0, 0, // classinfo 1, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 1, // signalCount // signals: name, argc, parameters, tag, flags 1, 0, 19, 2, 0x06 /* Public */, // signals: parameters QMetaType::Void, 0 // eod }; void ServiceInfo::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { auto *_t = static_cast<ServiceInfo *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->serviceChanged(); break; default: ; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast<int *>(_a[0]); { using _t = void (ServiceInfo::*)(); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ServiceInfo::serviceChanged)) { *result = 0; return; } } } Q_UNUSED(_a); } QT_INIT_METAOBJECT const QMetaObject ServiceInfo::staticMetaObject = { { QMetaObject::SuperData::link<QObject::staticMetaObject>(), qt_meta_stringdata_ServiceInfo.data, qt_meta_data_ServiceInfo, qt_static_metacall, nullptr, nullptr } }; const QMetaObject *ServiceInfo::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *ServiceInfo::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_ServiceInfo.stringdata0)) return static_cast<void*>(this); return QObject::qt_metacast(_clname); } int ServiceInfo::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QObject::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 1) qt_static_metacall(this, _c, _id, _a); _id -= 1; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 1) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 1; } return _id; } // SIGNAL 0 void ServiceInfo::serviceChanged() { QMetaObject::activate(this, &staticMetaObject, 0, nullptr); } QT_WARNING_POP QT_END_MOC_NAMESPACE
[ "funker@posteo.net" ]
funker@posteo.net
f46f705739f7b58fa95fc7eefaa83bd3cb308e3f
e16b292bdd2f409e843c55df31805e2d331f1a2d
/src/qt/optionsmodel.h
53f5f3c96ecc189d90cb940f52e1ec47fd5054af
[ "MIT" ]
permissive
Visco33/test
beeffb00d5593fee01703a341c7a46784db24ebf
3735d0d80f5f1d880bd5460cc223b1d05d937b12
refs/heads/master
2020-03-14T17:51:06.887931
2018-05-24T22:19:13
2018-05-24T22:19:13
130,040,474
0
0
null
null
null
null
UTF-8
C++
false
false
3,237
h
// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_QT_OPTIONSMODEL_H #define BITCOIN_QT_OPTIONSMODEL_H #include "amount.h" #include <QAbstractListModel> QT_BEGIN_NAMESPACE class QNetworkProxy; QT_END_NAMESPACE /** Interface from Qt to configuration data structure for Bitcoin client. To Qt, the options are presented as a list with the different options laid out vertically. This can be changed to a tree once the settings become sufficiently complex. */ class OptionsModel : public QAbstractListModel { Q_OBJECT public: explicit OptionsModel(QObject* parent = 0); enum OptionID { StartAtStartup, // bool MinimizeToTray, // bool MapPortUPnP, // bool MinimizeOnClose, // bool ProxyUse, // bool ProxyIP, // QString ProxyPort, // int DisplayUnit, // BitcoinUnits::Unit ThirdPartyTxUrls, // QString Digits, // QString Theme, // QString Language, // QString CoinControlFeatures, // bool ThreadsScriptVerif, // int DatabaseCache, // int SpendZeroConfChange, // bool ObfuscationRounds, // int AnonymizetestAmount, //int ShowMasternodesTab, // bool Listen, // bool OptionIDRowCount, }; void Init(); void Reset(); int rowCount(const QModelIndex& parent = QModelIndex()) const; QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const; bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole); /** Updates current unit in memory, settings and emits displayUnitChanged(newUnit) signal */ void setDisplayUnit(const QVariant& value); /* Explicit getters */ bool getMinimizeToTray() { return fMinimizeToTray; } bool getMinimizeOnClose() { return fMinimizeOnClose; } int getDisplayUnit() { return nDisplayUnit; } QString getThirdPartyTxUrls() { return strThirdPartyTxUrls; } bool getProxySettings(QNetworkProxy& proxy) const; bool getCoinControlFeatures() { return fCoinControlFeatures; } const QString& getOverriddenByCommandLine() { return strOverriddenByCommandLine; } /* Restart flag helper */ void setRestartRequired(bool fRequired); bool isRestartRequired(); bool resetSettings; private: /* Qt-only settings */ bool fMinimizeToTray; bool fMinimizeOnClose; QString language; int nDisplayUnit; QString strThirdPartyTxUrls; bool fCoinControlFeatures; /* settings that were overriden by command-line */ QString strOverriddenByCommandLine; /// Add option to list of GUI options overridden through command line/config file void addOverriddenOption(const std::string& option); signals: void displayUnitChanged(int unit); void obfuscationRoundsChanged(int); void anonymizetestAmountChanged(int); void coinControlFeaturesChanged(bool); }; #endif // BITCOIN_QT_OPTIONSMODEL_H
[ "37253340+Visco33@users.noreply.github.com" ]
37253340+Visco33@users.noreply.github.com
8de40e7deb5252a68a6f9fef0bd9d2c465a1db6e
5b690a51258bc44da0cb3a55c1d93c3673476c1d
/样例代码/T1017.cpp
57e0ce618fb127dcf10629d3a40cdf74096cce1b
[]
no_license
MythLucky/JSK2021
813da0ce1f27fb150b027fd5373e35dd5fd738ae
0f58e97fdddefc7bed8a0b2c9a330215344ec968
refs/heads/main
2023-02-26T16:56:09.025495
2021-01-26T12:26:25
2021-01-26T12:26:25
330,848,726
1
0
null
null
null
null
UTF-8
C++
false
false
134
cpp
#include<iostream> #include<cstdio> using namespace std; int main() { int a,b,c; cin>>a>>b>>c; cout<<(a+b)*c; return 0; }
[ "noreply@github.com" ]
MythLucky.noreply@github.com
f02a2a8ae4bb649e01aa2355138bc4c3cad4d5f9
ce1044f6dd1ab23aed435dd087283ece45f3f024
/include/Wallet/ExtendedKey.h
f0d071bca87617afccb07a1a0d64ca893a37e9ff
[ "MIT" ]
permissive
1div0/GrinPlusPlus
daf13ff87681903e0674d1f077f17d3730eebcba
44ba6474b971cd39a96b7ad9742b23d3cb5334c9
refs/heads/master
2021-07-12T20:23:20.039838
2020-12-02T11:18:41
2020-12-02T11:18:41
221,024,351
0
0
MIT
2019-11-11T16:37:06
2019-11-11T16:37:05
null
UTF-8
C++
false
false
2,054
h
#pragma once #include <Crypto/BigInteger.h> #include <Crypto/PublicKey.h> #include <Crypto/SecretKey.h> #include <Core/Serialization/Serializer.h> #include <Core/Serialization/ByteBuffer.h> // // Represents a BIP32 extended key. // class IExtendedKey { public: virtual ~IExtendedKey() = default; // // 4 byte: version bytes (mainnet: TODO: public, TODO: private; floonet: 0x033C08DF public, 0x033C04A4 private) // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 derived keys, .... // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) // 4 bytes: child number. This is ser32(i) for i in xi = xpar/i, with xi the key being serialized. (0x00000000 if master key) // 32 bytes: the chain code // 33 bytes: the public key or private key data (serP(K) for public keys, 0x00 || ser256(k) for private keys) // void Serialize(Serializer& serializer) const { serializer.Append<uint32_t>(m_network); serializer.Append<uint8_t>(m_depth); serializer.Append<uint32_t>(m_parentFingerprint); serializer.Append<uint32_t>(m_childNumber); serializer.AppendBigInteger<32>(m_chainCode.GetBytes()); m_keyBytes.Serialize(serializer); } uint32_t GetNetwork() const { return m_network; } uint8_t GetDepth() const { return m_depth; } uint32_t GetParentFingerprint() const { return m_parentFingerprint; } uint32_t GetChildNumber() const { return m_childNumber; } const SecretKey& GetChainCode() const { return m_chainCode; } protected: IExtendedKey(const uint32_t network, const uint8_t depth, const uint32_t parentFingerprint, const uint32_t childNumber, SecretKey&& chainCode, PublicKey&& keyBytes) : m_network(network), m_depth(depth), m_parentFingerprint(parentFingerprint), m_childNumber(childNumber), m_chainCode(std::move(chainCode)), m_keyBytes(std::move(keyBytes)) { } const PublicKey& GetKeyBytes() const noexcept { return m_keyBytes; } private: uint32_t m_network; uint8_t m_depth; uint32_t m_parentFingerprint; uint32_t m_childNumber; SecretKey m_chainCode; PublicKey m_keyBytes; };
[ "davidburkett38@gmail.com" ]
davidburkett38@gmail.com
cdac7c629d3ad4baf8d4568914afc30111a45a03
4a28104787a4ce3bf362fda9182e4f1fe6276c30
/graphs/bfs_shortReach.cpp
6187c87e472830c54e8f005b7efd6223f260b54d
[]
no_license
Ason4901/geeksforgeeks
d0538a22db00c86e97ec8b9f6c548ebd1ecef8ce
777aa4c0752bb0a9b942922e1ad99095a161cc6b
refs/heads/master
2023-02-24T07:51:15.469015
2021-01-30T15:36:20
2021-01-30T15:36:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,627
cpp
#include <bits/stdc++.h> #include <cstdio> #include <cstring> #include <cmath> #include <cstring> #include <chrono> #include <complex> #define endl "\n" #define ll long long int #define vi vector<int> #define vll vector<ll> #define vvi vector < vi > #define pii pair<int,int> #define pll pair<long long, long long> #define mod 1000000007 #define inf 1000000000000000001; #define all(c) c.begin(),c.end() #define mp(x,y) make_pair(x,y) #define mem(a,val) memset(a,val,sizeof(a)) #define eb emplace_back #define f first #define s second using namespace std; void solve(int num_of_nodes, int start_node, const vector<list<int>>& edges) { vi length_to_nodes(num_of_nodes + 1, -1); queue<int> q; length_to_nodes[start_node] = 0; q.push(start_node); while (!q.empty()) { int current_node = q.front(); q.pop(); for (auto node : edges[current_node]) { if (length_to_nodes[node] == -1) { length_to_nodes[node] = length_to_nodes[current_node] + 6; q.push(node); } } } for (int i = 1; i < length_to_nodes.size(); ++i) { if (length_to_nodes[i] != 0) cout << length_to_nodes[i] << " "; } cout << endl; } int main() { std::ios::sync_with_stdio(false); int T; cin >> T; // cin.ignore(); must be there when using getline(cin, s) while (T--) { int nodes, num_edge; cin >> nodes >> num_edge; vector<list<int>> edges(nodes + 1); for (int i = 0; i < num_edge; ++i) { int node_1, node_2; cin >> node_1 >> node_2; edges[node_1].push_back(node_2); edges[node_2].push_back(node_1); } int start_node; cin >> start_node; solve(nodes, start_node, edges); } return 0; }
[ "abhip13th@gmail.com" ]
abhip13th@gmail.com
8bd3315890b4f08a3b23d99f132acb62becef226
25d7fa8d57ff934ce1a9f42dd1fc55c7bcd7010d
/gcj2020_r1b/a.cpp
60499b714b183cff409ce9c161e6a6fdba7af8bb
[]
no_license
FMota0/yt-content
22b3e6f0595b348773c6faf1aef9a7c5e27390c4
9210dc3cc3974adf43eef7d9df7d0e7bd8b6e3ad
refs/heads/master
2022-11-25T22:10:31.395335
2020-08-07T13:26:39
2020-08-07T13:26:39
257,675,348
0
0
null
null
null
null
UTF-8
C++
false
false
1,518
cpp
#include <bits/stdc++.h> using namespace std; template<typename T = int> vector<T> create(size_t n){ return vector<T>(n); } template<typename T, typename... Args> auto create(size_t n, Args... args){ return vector<decltype(create<T>(args...))>(n, create<T>(args...)); } int main(){ ios::sync_with_stdio(false); cin.tie(0); int t; cin >> t; for(int _ = 1; _ <= t; _++){ cout << "Case #" << _ << ":"; using ll = long long; ll x, y; cin >> y >> x; int rx = 0, ry = 0; if(x < 0) rx = 1, x = -x; if(y < 0) ry = 1, y = -y; if((x + y) % 2 == 0){ cout << " IMPOSSIBLE\n"; continue; } auto covers = [&](ll x, ll y, int b){ return abs(x) + abs(y) <= ((1ll<<(b + 1)) - 1); }; string res; for(int i = 0; i <= 40 && res.empty(); i++){ if(covers(x, y, i)){ for(int j = i; j >= 0; j--){ long long delta = 1ll<<j; if(covers(x - delta, y, j - 1)){ x -= delta; res.push_back('N'); } else if(covers(x + delta, y, j - 1)){ x += delta; res.push_back('S'); } else if(covers(x, y - delta, j - 1)){ y -= delta; res.push_back('E'); } else if(covers(x, y + delta, j - 1)){ y += delta; res.push_back('W'); } else assert(0); } } } reverse(res.begin(), res.end()); if(rx){ for(auto & c : res){ if(c == 'N') c = 'S'; else if(c == 'S') c = 'N'; } } if(ry){ for(auto & c : res){ if(c == 'E') c = 'W'; else if(c == 'W') c = 'E'; } } cout << " " << res << '\n'; } return 0; }
[ "felipe.santos@ccc.ufcg.edu.br" ]
felipe.santos@ccc.ufcg.edu.br
e94163abd6c66a86135e241fc3190fcc7781b0d4
5753afcc204f5bc091768e70616dc641313062df
/tests/pxScene2d/test_utf8.cpp
e9d3650c57c47c8a66f088f1b62534aff5732ef8
[ "Apache-2.0" ]
permissive
spackianathan/pxCore
17cbf51cf834a316fd68689c858f435d30f2a854
1f3864a5fb7f3dbe108563afe75db87090c88bb2
refs/heads/master
2020-03-15T08:53:43.589044
2018-04-19T02:15:35
2018-04-19T02:15:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,923
cpp
#include <sstream> #include <string.h> #include <unistd.h> extern "C" { #include <utf8.h> } #include "test_includes.h" // Needs to be included last using namespace std; class UTF8Test : public testing::Test { public: virtual void SetUp() { } virtual void TearDown() { } void lengthTest() { char *str = "\x46\x6F\x6F\x20\xC2"; EXPECT_TRUE (u8_strlen(str) == 5); } void printTest() { char *str = "\x46\x6F\x6F"; EXPECT_TRUE (u8_printf("%s",str) == 3); } void charToUTF8Test() { char dest; u8_wc_toutf8(&dest,65); EXPECT_TRUE (dest == 'A'); } void charToByteOffsetTest() { char *str = "\x46\x6F\x6E"; EXPECT_TRUE(1 == u8_offset(str,1)); } void byteOffsetTocharNumTest() { char *str = "\x46\x6F\x6E"; EXPECT_TRUE(2 == u8_charnum(str,2)); } void isLocaleUTF8TrueTest() { EXPECT_TRUE (1 == u8_is_locale_utf8(".UTF-8")); } void isLocaleUTF8FalseTest() { EXPECT_TRUE (0 == u8_is_locale_utf8("UTF-8")); } void strcharPresentTest() { char *str = "\x46\x6F\x6E"; int index = -1; char* ptr = NULL; ptr = u8_strchr(str,70, &index); EXPECT_TRUE (NULL != ptr); EXPECT_TRUE (0 == index); } void strcharAbsentTest() { char *str = "\x46\x6F\x6E"; int index = -1; char* ptr = NULL; ptr = u8_strchr(str,65, &index); EXPECT_TRUE (NULL == ptr); EXPECT_TRUE (3 == index); } void memcharPresentTest() { char *str = "\x46\x6F\x6E"; int index = -1; char* ptr = NULL; ptr = u8_memchr(str,70, 2, &index); EXPECT_TRUE (NULL != ptr); EXPECT_TRUE (0 == index); } void memcharAbsentTest() { char *str = "\x46\x6F\x6E"; int index = -1; char* ptr = NULL; ptr = u8_memchr(str,70, 0,&index); EXPECT_TRUE (NULL == ptr); EXPECT_TRUE (0 == index); } void octalDigitTest() { EXPECT_TRUE (octal_digit('7') == 1); } void hexDigitTest() { EXPECT_TRUE (hex_digit('F') == 1); } void convertUTFToAsciiTest() { char *str = "\x46\x6F\x6E"; char buffer[10]; memset (buffer, 0, sizeof(buffer)); EXPECT_TRUE (3 == u8_escape(buffer, 3, str, 0)); } void convertAsciiToUTF8Test() { char *str = "Foo"; char buffer[20]; memset (buffer, 0, sizeof(buffer)); EXPECT_TRUE (3 == u8_toutf8(buffer, 20, (u_int32_t*)str, 3)); } void unescapeTest() { char *str = "\\u:"; char buffer[20]; memset (buffer, 0, sizeof(buffer)); int ret = u8_unescape(buffer,sizeof(str),str); EXPECT_TRUE (2 == ret); } void seqLengthTest() { char *str = "Foo"; EXPECT_TRUE (1 == u8_seqlen(str)); } void u8EscapeWcharTest() { char buffer[100]; memset(buffer,0,100); EXPECT_TRUE (2 == u8_escape_wchar(buffer, 100, L'\n')); EXPECT_TRUE (2 == u8_escape_wchar(buffer, 100, L'\t')); EXPECT_TRUE (2 == u8_escape_wchar(buffer, 100, L'\r')); EXPECT_TRUE (2 == u8_escape_wchar(buffer, 100, L'\b')); EXPECT_TRUE (2 == u8_escape_wchar(buffer, 100, L'\f')); EXPECT_TRUE (2 == u8_escape_wchar(buffer, 100, L'\f')); EXPECT_TRUE (2 == u8_escape_wchar(buffer, 100, L'\v')); EXPECT_TRUE (2 == u8_escape_wchar(buffer, 100, L'\a')); EXPECT_TRUE (2 == u8_escape_wchar(buffer, 100, L'\\')); } void toUTF8Test() { char dest[100]; u_int32_t src1 = 35; memset(dest,0,sizeof(dest)); EXPECT_TRUE (1 == u8_toutf8(dest, sizeof(dest), &src1,1)); EXPECT_TRUE (0 == u8_toutf8(dest, 0, &src1,1)); src1 = 131; EXPECT_TRUE (1 == u8_toutf8(dest, sizeof(dest), &src1,1)); EXPECT_TRUE (0 == u8_toutf8(dest, 0, &src1,1)); src1 = 65535; EXPECT_TRUE (1 == u8_toutf8(dest, sizeof(dest), &src1,1)); EXPECT_TRUE (0 == u8_toutf8(dest, 0, &src1,1)); src1 = 65537; EXPECT_TRUE (1 == u8_toutf8(dest, sizeof(dest), &src1,1)); EXPECT_TRUE (0 == u8_toutf8(dest, 0, &src1,1)); } void wctoUTF8Test() { char dest[100]; u_int32_t src1 = 131; memset(dest,0,sizeof(dest)); EXPECT_TRUE (2 == u8_wc_toutf8(dest, src1)); src1 = 65530; EXPECT_TRUE (3 == u8_wc_toutf8(dest, src1)); src1 = 65537; EXPECT_TRUE (4 == u8_wc_toutf8(dest, src1)); src1 = 1120000; EXPECT_TRUE (0 == u8_wc_toutf8(dest, src1)); } void readEscapeSequenceTest() { u_int32_t dest; char str[1]; str[0] = 'n'; u8_read_escape_sequence(str, &dest); EXPECT_TRUE (10 == dest); str[0] = 't'; u8_read_escape_sequence(str, &dest); EXPECT_TRUE ((uint32_t)('\t') == dest); str[0] = 'r'; u8_read_escape_sequence(str, &dest); EXPECT_TRUE ((uint32_t)('\r') == dest); str[0] = 'b'; u8_read_escape_sequence(str, &dest); EXPECT_TRUE ((uint32_t)('\b') == dest); str[0] = 'f'; u8_read_escape_sequence(str, &dest); EXPECT_TRUE ((uint32_t)('\f') == dest); str[0] = 'v'; u8_read_escape_sequence(str, &dest); EXPECT_TRUE ((uint32_t)('\v') == dest); str[0] = 'a'; u8_read_escape_sequence(str, &dest); EXPECT_TRUE ((uint32_t)('\a') == dest); } }; TEST_F(UTF8Test, UTF8Tests) { lengthTest(); printTest(); charToUTF8Test(); charToByteOffsetTest(); byteOffsetTocharNumTest(); isLocaleUTF8TrueTest(); isLocaleUTF8FalseTest(); strcharPresentTest(); strcharAbsentTest(); memcharPresentTest(); memcharAbsentTest(); octalDigitTest(); hexDigitTest(); convertUTFToAsciiTest(); convertAsciiToUTF8Test(); unescapeTest(); seqLengthTest(); u8EscapeWcharTest(); toUTF8Test(); wctoUTF8Test(); readEscapeSequenceTest(); }
[ "madanagopal123@gmail.com" ]
madanagopal123@gmail.com
bc9b12c31a635ee55f76d2b2a1ba9cbf6e3e6035
535d1b93fbe05923e2defac0f7c218bd64559e0d
/CarmenJuego/Proyecto/Carmen/bin/windows/obj/include/lime/ui/_ScanCode/ScanCode_Impl_.h
c96646baf3a2c533c6e3c1cfd7214422d197a857
[]
no_license
XxKarikyXx/ProgVJ1
af9a9f4d7608912e1b2bab9726266b9f4ef5f44d
d26e335379a001cce21d7cd87461d75169391222
refs/heads/develop
2020-03-13T12:44:19.172929
2018-06-05T17:58:01
2018-06-05T17:58:01
131,125,411
0
0
null
2018-05-09T05:12:42
2018-04-26T08:35:17
Haxe
UTF-8
C++
false
true
7,488
h
// Generated by Haxe 3.4.2 (git build master @ 890f8c7) #ifndef INCLUDED_lime_ui__ScanCode_ScanCode_Impl_ #define INCLUDED_lime_ui__ScanCode_ScanCode_Impl_ #ifndef HXCPP_H #include <hxcpp.h> #endif HX_DECLARE_CLASS3(lime,ui,_ScanCode,ScanCode_Impl_) namespace lime{ namespace ui{ namespace _ScanCode{ class HXCPP_CLASS_ATTRIBUTES ScanCode_Impl__obj : public hx::Object { public: typedef hx::Object super; typedef ScanCode_Impl__obj OBJ_; ScanCode_Impl__obj(); public: enum { _hx_ClassId = 0x237bda4a }; void __construct(); inline void *operator new(size_t inSize, bool inContainer=false,const char *inName="lime.ui._ScanCode.ScanCode_Impl_") { return hx::Object::operator new(inSize,inContainer,inName); } inline void *operator new(size_t inSize, int extra) { return hx::Object::operator new(inSize+extra,false,"lime.ui._ScanCode.ScanCode_Impl_"); } hx::ObjectPtr< ScanCode_Impl__obj > __new() { hx::ObjectPtr< ScanCode_Impl__obj > __this = new ScanCode_Impl__obj(); __this->__construct(); return __this; } static hx::ObjectPtr< ScanCode_Impl__obj > __alloc(hx::Ctx *_hx_ctx) { ScanCode_Impl__obj *__this = (ScanCode_Impl__obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(ScanCode_Impl__obj), false, "lime.ui._ScanCode.ScanCode_Impl_")); *(void **)__this = ScanCode_Impl__obj::_hx_vtable; return __this; } static void * _hx_vtable; static Dynamic __CreateEmpty(); static Dynamic __Create(hx::DynamicArray inArgs); //~ScanCode_Impl__obj(); HX_DO_RTTI_ALL; static bool __GetStatic(const ::String &inString, Dynamic &outValue, hx::PropertyAccess inCallProp); static void __register(); bool _hx_isInstanceOf(int inClassId); ::String __ToString() const { return HX_HCSTRING("ScanCode_Impl_","\x8a","\xc1","\x1c","\x37"); } static void __boot(); static int UNKNOWN; static int BACKSPACE; static int TAB; static int RETURN; static int ESCAPE; static int SPACE; static int SINGLE_QUOTE; static int COMMA; static int MINUS; static int PERIOD; static int SLASH; static int NUMBER_0; static int NUMBER_1; static int NUMBER_2; static int NUMBER_3; static int NUMBER_4; static int NUMBER_5; static int NUMBER_6; static int NUMBER_7; static int NUMBER_8; static int NUMBER_9; static int SEMICOLON; static int EQUALS; static int LEFT_BRACKET; static int BACKSLASH; static int RIGHT_BRACKET; static int GRAVE; static int A; static int B; static int C; static int D; static int E; static int F; static int G; static int H; static int I; static int J; static int K; static int L; static int M; static int N; static int O; static int P; static int Q; static int R; static int S; static int T; static int U; static int V; static int W; static int X; static int Y; static int Z; static int DELETE; static int CAPS_LOCK; static int F1; static int F2; static int F3; static int F4; static int F5; static int F6; static int F7; static int F8; static int F9; static int F10; static int F11; static int F12; static int PRINT_SCREEN; static int SCROLL_LOCK; static int PAUSE; static int INSERT; static int HOME; static int PAGE_UP; static int END; static int PAGE_DOWN; static int RIGHT; static int LEFT; static int DOWN; static int UP; static int NUM_LOCK; static int NUMPAD_DIVIDE; static int NUMPAD_MULTIPLY; static int NUMPAD_MINUS; static int NUMPAD_PLUS; static int NUMPAD_ENTER; static int NUMPAD_1; static int NUMPAD_2; static int NUMPAD_3; static int NUMPAD_4; static int NUMPAD_5; static int NUMPAD_6; static int NUMPAD_7; static int NUMPAD_8; static int NUMPAD_9; static int NUMPAD_0; static int NUMPAD_PERIOD; static int APPLICATION; static int POWER; static int NUMPAD_EQUALS; static int F13; static int F14; static int F15; static int F16; static int F17; static int F18; static int F19; static int F20; static int F21; static int F22; static int F23; static int F24; static int EXECUTE; static int HELP; static int MENU; static int SELECT; static int STOP; static int AGAIN; static int UNDO; static int CUT; static int COPY; static int PASTE; static int FIND; static int MUTE; static int VOLUME_UP; static int VOLUME_DOWN; static int NUMPAD_COMMA; static int ALT_ERASE; static int SYSTEM_REQUEST; static int CANCEL; static int CLEAR; static int PRIOR; static int RETURN2; static int SEPARATOR; static int OUT; static int OPER; static int CLEAR_AGAIN; static int CRSEL; static int EXSEL; static int NUMPAD_00; static int NUMPAD_000; static int THOUSAND_SEPARATOR; static int DECIMAL_SEPARATOR; static int CURRENCY_UNIT; static int CURRENCY_SUBUNIT; static int NUMPAD_LEFT_PARENTHESIS; static int NUMPAD_RIGHT_PARENTHESIS; static int NUMPAD_LEFT_BRACE; static int NUMPAD_RIGHT_BRACE; static int NUMPAD_TAB; static int NUMPAD_BACKSPACE; static int NUMPAD_A; static int NUMPAD_B; static int NUMPAD_C; static int NUMPAD_D; static int NUMPAD_E; static int NUMPAD_F; static int NUMPAD_XOR; static int NUMPAD_POWER; static int NUMPAD_PERCENT; static int NUMPAD_LESS_THAN; static int NUMPAD_GREATER_THAN; static int NUMPAD_AMPERSAND; static int NUMPAD_DOUBLE_AMPERSAND; static int NUMPAD_VERTICAL_BAR; static int NUMPAD_DOUBLE_VERTICAL_BAR; static int NUMPAD_COLON; static int NUMPAD_HASH; static int NUMPAD_SPACE; static int NUMPAD_AT; static int NUMPAD_EXCLAMATION; static int NUMPAD_MEM_STORE; static int NUMPAD_MEM_RECALL; static int NUMPAD_MEM_CLEAR; static int NUMPAD_MEM_ADD; static int NUMPAD_MEM_SUBTRACT; static int NUMPAD_MEM_MULTIPLY; static int NUMPAD_MEM_DIVIDE; static int NUMPAD_PLUS_MINUS; static int NUMPAD_CLEAR; static int NUMPAD_CLEAR_ENTRY; static int NUMPAD_BINARY; static int NUMPAD_OCTAL; static int NUMPAD_DECIMAL; static int NUMPAD_HEXADECIMAL; static int LEFT_CTRL; static int LEFT_SHIFT; static int LEFT_ALT; static int LEFT_META; static int RIGHT_CTRL; static int RIGHT_SHIFT; static int RIGHT_ALT; static int RIGHT_META; static int MODE; static int AUDIO_NEXT; static int AUDIO_PREVIOUS; static int AUDIO_STOP; static int AUDIO_PLAY; static int AUDIO_MUTE; static int MEDIA_SELECT; static int WWW; static int MAIL; static int CALCULATOR; static int COMPUTER; static int APP_CONTROL_SEARCH; static int APP_CONTROL_HOME; static int APP_CONTROL_BACK; static int APP_CONTROL_FORWARD; static int APP_CONTROL_STOP; static int APP_CONTROL_REFRESH; static int APP_CONTROL_BOOKMARKS; static int BRIGHTNESS_DOWN; static int BRIGHTNESS_UP; static int DISPLAY_SWITCH; static int BACKLIGHT_TOGGLE; static int BACKLIGHT_DOWN; static int BACKLIGHT_UP; static int EJECT; static int SLEEP; static int fromKeyCode(int keyCode); static ::Dynamic fromKeyCode_dyn(); static int toKeyCode(int scanCode); static ::Dynamic toKeyCode_dyn(); static bool gt(int a,int b); static ::Dynamic gt_dyn(); static bool gte(int a,int b); static ::Dynamic gte_dyn(); static bool lt(int a,int b); static ::Dynamic lt_dyn(); static bool lte(int a,int b); static ::Dynamic lte_dyn(); static int plus(int a,int b); static ::Dynamic plus_dyn(); }; } // end namespace lime } // end namespace ui } // end namespace _ScanCode #endif /* INCLUDED_lime_ui__ScanCode_ScanCode_Impl_ */
[ "kariky@hotmail.es" ]
kariky@hotmail.es
4c75480ce7758462fc99eff7f929067e9f480241
bb5fd447b839853918f1c9b1d27e81b2e1683bca
/simulate.cpp
e60223ae28d785f45427fca49220fa6ea8f940a0
[]
no_license
adhaase/adventure-RPG
013a7b1ab2d429377a78ba0282bf8af1577588d1
eb19281353838fbd18a6054c4f1863ebd0a79f63
refs/heads/master
2021-04-15T04:56:34.652415
2018-03-21T20:09:41
2018-03-21T20:09:41
126,144,522
0
0
null
null
null
null
UTF-8
C++
false
false
1,610
cpp
#include <iostream> #include <string> #include <vector> #include <sstream> #include <fstream> #include <random> #include <ctime> #include <chrono> #include <thread> #include "item.h" #include "player.h" #include "shop.h" using namespace std; void palletTownShop(Shop &palletShop, Player &player) { palletShop.name = "Pallet Town Shop"; palletShop.approachShopkeeper(palletShop); // approach shopkeeper cout << "------------------------------------------\n"; cout << "------------ PALLET TOWN SHOP ------------\n"; cout << "------------------------------------------\n"; // define Pallet Town Shop inventory // Name | Attack Power | Price Item rustySword = { "Rusty Sword", 4, 6 }; Item rustyDagger = { "Rusty Dagger", 2, 3 }; Item apprenticeWand = { "Apprentice Wand", 7, 11 }; Item wornShortBow = { "Worn Short Bow", 6, 9 }; // add items to Pallet Town Shop inventory palletShop.shopSupplies.push_back(rustySword); palletShop.shopSupplies.push_back(rustyDagger); palletShop.shopSupplies.push_back(apprenticeWand); palletShop.shopSupplies.push_back(wornShortBow); // print the items of Pallet Town Shop palletShop.printItems(palletShop.shopSupplies); cout << "\n"; // print player gold player.playerGold = 20; // The player initially starts with 20 gold player.printGold(player); // print player rucksack player.printRucksack(player.rucksack); // print shop choices palletShop.shopChoices(player, palletShop); } void simulate() { Shop palletShop; Player player; palletTownShop(palletShop, player); // TODO : don't always do this. If player chooses then simulate shop }
[ "adhaase@umich.edu" ]
adhaase@umich.edu
9a0ac34210bfd04546595f834e9794f560010be8
73c8a3179b944b63b2a798542896e4cdf0937b6e
/Codeforces/Divisibility.cpp
7211c930c2a8d2547c000976532f90ea2c790e00
[ "Apache-2.0" ]
permissive
aajjbb/contest-files
c151f1ab9b562ca91d2f8f4070cb0aac126a188d
71de602a798b598b0365c570dd5db539fecf5b8c
refs/heads/master
2023-07-23T19:34:12.565296
2023-07-16T00:57:55
2023-07-16T00:57:59
52,963,297
2
4
null
2017-08-03T20:12:19
2016-03-02T13:05:25
C++
UTF-8
C++
false
false
2,500
cpp
#include <bits/stdc++.h> template<typename T> T gcd(T a, T b) { if(!b) return a; return gcd(b, a % b); } template<typename T> T lcm(T a, T b) { return a * b / gcd(a, b); } template<typename T> void chmin(T& a, T b) { a = (a > b) ? b : a; } template<typename T> void chmax(T& a, T b) { a = (a < b) ? b : a; } int in() { int x; scanf("%d", &x); return x; } using namespace std; typedef long long Int; typedef unsigned long long uInt; typedef unsigned uint; const int MAX_TRY = 100; Int N; Int modPow(Int a, Int n, Int mod) { Int res = 1; while (n) { if (n & 1) { res = (res * a) % mod; } a = (a * a) % mod; n /= 2; } res %= mod; res += mod; res %= mod; return res; } Int llrand(){ Int a = rand(); a<<=32; a+=rand(); return a; } bool is_probably_prime(Int n) { if (n <= 1) return 0; if (n <= 3) return 1; Int s = 0, d = n - 1; while (d % 2 == 0) { d /= 2; s++; } for(int k = 0; k < 512; k++) { Int a = (llrand() % (n - 3)) + 2; Int x = modPow(a, d, n); if (x != 1 && x != n - 1) { for (int r = 1; r < s; r++) { x = modPow(x, 2, n); if(x == 1) { return 0; } if (x == n - 1) { break; } } if (x != n - 1) { return 0; } } } return 1; } Int rho(Int n) { Int d, c = rand() % n, x = rand() % n, xx = x; if (n % 2 == 0) { return 2; } do { x = (modPow(x, x, n) + c) % n; xx = (modPow(xx, xx, n) + c) % n; xx = (modPow(xx, xx, n) + c) % n; d = gcd(abs(x - xx) , n); } while (d == 1); return d; } map <Int, int > F; void factor (Int n) { // cout << n << endl; if (n == 1) { return; } if (is_probably_prime(n)) { F[n]++; return; } Int d = rho(n); while (d == n) { d = rho(n); } factor(d); factor(n / d); } int main(void) { cin >> N; srand(time(NULL)); if (is_probably_prime(N)) { cout << 2 << endl; } else { return 0; factor(N); Int ans = 1; for (auto& it : F) { ans *= (it.second + 1); } cout << ans << endl; } return 0; }
[ "jefersonlsiq@gmail.com" ]
jefersonlsiq@gmail.com
c7e1c5b871bef007ec63eb8056e13ada5472e65e
c9cf0586ace11aa32fa67606d237a130a06364ee
/circular-cylinder-2-20/w_20/59.5/uniform/functionObjects/functionObjectProperties
1f4a1c487d53f84e20a9f1b5f01c2039c1f7fbed
[]
no_license
jezvonek/CFD-Final-Project
c74cfa21f22545c27d97d85cf30eb6dc8c824dc1
7c9a7fb032d74f20888effa0a0b75b212bf899f4
refs/heads/master
2022-07-05T14:43:52.967657
2020-05-14T03:40:56
2020-05-14T03:40:56
262,370,756
1
1
null
null
null
null
UTF-8
C++
false
false
898
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: v1912 | | \\ / A nd | Website: www.openfoam.com | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; location "59.5/uniform/functionObjects"; object functionObjectProperties; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // // ************************************************************************* //
[ "jezvonek@gmail.com" ]
jezvonek@gmail.com
1a20a252f714c8b7dd79de895add8f06aff5e072
8beb7475ed7cb569596ad51bb0eede836a1fffa1
/aig.hpp
422b9ad8f51c33acb2c676de88aa1dc5cea87c10
[]
no_license
zkaiwen/AIG
525e7347e9e97f5e8e962e0069a01d7e85f2464e
4966401989fb1b8a0f2fbb80bf22cd8dc7e62e87
refs/heads/master
2021-01-10T18:07:30.552466
2013-08-12T23:54:59
2013-08-12T23:54:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,210
hpp
/*@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@ @ @ aig.hpp @ @ @AUTHOR:Kevin Zeng @ Copyright 2012 – 2013 Virginia Polytechnic Institute and State University @ @#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@*/ #ifndef AIG_GUARD #define AIG_GUARD #include <stdlib.h> #include <stdio.h> #include <vector> #include <map> #include <fstream> #include "graph.hpp" //Use to compare keys for "HASH TABLE" struct cmp_intp { bool operator()(int const *a, int const *b) { //printf("A: %d B:%d\nA:%d B:%d\n", a[0], b[0], a[1], b[1]); if(b[0] < a[0] ) return true; if(b[1] < a[1]) return true; return false; } }; class AIG{ private: std::vector<int*> m_AIG; std::vector<int> m_Outputs; void importAIG(const char*, std::vector<std::vector<int>*>&); std::map<int*, int, cmp_intp> m_HashTable; public: AIG(); ~AIG(); void importAIG(std::string); void convertGraph2AIG(Graph*); //Getters void getAIG(std::vector<std::vector<int>*>&); void getOutputs(std::vector<int>&); int create_and2(int, int); int create_input(); int new_and_vertex(int,int); void print(); void printHash(); }; #endif
[ "zkaiwen@gmail.com" ]
zkaiwen@gmail.com
c74884a7dbdad06327122af8856095d0e2beca1a
53ff492d492948bf6815c28789bd5dd0bb3f55f3
/Lab2/Projeto/ProjectFiles/thread.cpp
9d4fedf18274621978c64705f2d4b38346c3d1f0
[ "MIT" ]
permissive
MatheusBigarelli/sistemas-embarcados
3e2321dafdfab4fb5f12ddf5fd803164a15d459b
6a11e604d613fec762a25d1145f208ae268390ba
refs/heads/master
2020-07-04T09:26:17.842367
2019-12-07T17:55:18
2019-12-07T17:55:18
202,238,870
0
0
null
2019-11-08T01:18:00
2019-08-13T23:40:54
C
UTF-8
C++
false
false
995
cpp
#include "thread.h" #include "primes.h" #include "messages.h" #include "gpio.h" #include "uart.h" int current_iteration = 0; uint16_t key; bool key_ready = false; bool decode_ready = false; bool testOK = false; uint8_t message[MESSAGE_LENGTH] = {}; void initThreads(void) { osThreadCreate(osThread(getKeyThread), NULL); osThreadCreate(osThread(decodeMessageThread), NULL); osThreadCreate(osThread(testNextToLastWordThread), NULL); osThreadCreate(osThread(testLastWordThread), NULL); osThreadCreate(osThread(printMessageThread), NULL); } void getKeyThread(void const* arg) { while(1) { PortN_Output(1); } } void decodeMessageThread(void const* arg) { while(1) { PortN_Output(0); } } void testNextToLastWordThread(void const* arg) { while(1) { if(current_iteration < 3) { UART0_TxString("Mensagem decodificada:\r\n"); current_iteration++; } } } void testLastWordThread(void const* arg) { while(1); } void printMessageThread(void const* arg) { while(1); }
[ "victorbelinello17@gmail.com" ]
victorbelinello17@gmail.com
920c236b143c1804d94fa38c61fee7c00b503487
dd1e3221c0b9378457ef54a409788b42b8df66ea
/Include/ViewPerspectiveHighlight.h
ac01fe74996d17a953979865a614c45a593190b9
[ "MIT" ]
permissive
FTD2012/Hieroglyph3
b1b83bea2c7b8e08c2916d2b9006ae77264bfcc4
10adfe1639747ecb6aa0bb5a4d2618383758d361
refs/heads/master
2022-11-02T07:28:00.660292
2020-06-19T12:41:56
2020-06-19T12:41:56
273,384,411
2
2
null
null
null
null
UTF-8
C++
false
false
1,831
h
//-------------------------------------------------------------------------------- // This file is a portion of the Hieroglyph 3 Rendering Engine. It is distributed // under the MIT License, available in the root of this distribution and // at the following URL: // // http://www.opensource.org/licenses/mit-license.php // // Copyright (c) Jason Zink //-------------------------------------------------------------------------------- //-------------------------------------------------------------------------------- // ViewPerspectiveHighlight // //-------------------------------------------------------------------------------- #ifndef ViewPerspectiveHighlight_h #define ViewPerspectiveHighlight_h //-------------------------------------------------------------------------------- #include "SceneRenderTask.h" #include "FullscreenActor.h" //-------------------------------------------------------------------------------- namespace Glyph3 { class Entity3D; class ViewPerspectiveHighlight : public SceneRenderTask { public: ViewPerspectiveHighlight( RendererDX11& Renderer, ResourcePtr RenderTarget, ResourcePtr DepthTarget = 0 ); virtual ~ViewPerspectiveHighlight(); virtual void Update( float fTime ); virtual void QueuePreTasks( RendererDX11* pRenderer ); virtual void ExecuteTask( PipelineManagerDX11* pPipelineManager, IParameterManager* pParamManager ); virtual void Resize( UINT width, UINT height ); void SetRenderTargets( ResourcePtr RenderTarget, ResourcePtr DepthTarget = nullptr ); virtual std::wstring GetName(); ResourcePtr m_SilhouetteTarget; FullscreenActor m_SilhouetteActor; protected: ResourcePtr m_RenderTarget; ResourcePtr m_DepthTarget; }; }; //-------------------------------------------------------------------------------- #endif // ViewPerspectiveHighlight_h
[ "invokerleve@gmail.com" ]
invokerleve@gmail.com
c40b5c1b921f662e52e5f7d05e2d6ea17a54f470
9fad4848e43f4487730185e4f50e05a044f865ab
/src/remoting/protocol/message_reader.cc
fb3400159d98dcc161c04f3d0eb89ed2e40f7606
[ "BSD-3-Clause" ]
permissive
dummas2008/chromium
d1b30da64f0630823cb97f58ec82825998dbb93e
82d2e84ce3ed8a00dc26c948219192c3229dfdaa
refs/heads/master
2020-12-31T07:18:45.026190
2016-04-14T03:17:45
2016-04-14T03:17:45
56,194,439
4
0
null
null
null
null
UTF-8
C++
false
false
3,489
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/protocol/message_reader.h" #include <utility> #include "base/bind.h" #include "base/callback.h" #include "base/compiler_specific.h" #include "base/location.h" #include "base/memory/ptr_util.h" #include "base/single_thread_task_runner.h" #include "base/thread_task_runner_handle.h" #include "net/base/io_buffer.h" #include "net/base/net_errors.h" #include "remoting/base/compound_buffer.h" #include "remoting/proto/internal.pb.h" #include "remoting/protocol/p2p_stream_socket.h" namespace remoting { namespace protocol { static const int kReadBufferSize = 4096; MessageReader::MessageReader() : weak_factory_(this) {} MessageReader::~MessageReader() {} void MessageReader::StartReading( P2PStreamSocket* socket, const MessageReceivedCallback& message_received_callback, const ReadFailedCallback& read_failed_callback) { DCHECK(CalledOnValidThread()); DCHECK(!socket_); DCHECK(socket); DCHECK(!message_received_callback.is_null()); DCHECK(!read_failed_callback.is_null()); socket_ = socket; message_received_callback_ = message_received_callback; read_failed_callback_ = read_failed_callback; DoRead(); } void MessageReader::DoRead() { DCHECK(CalledOnValidThread()); // Don't try to read again if there is another read pending or we // have messages that we haven't finished processing yet. bool read_succeeded = true; while (read_succeeded && !closed_ && !read_pending_) { read_buffer_ = new net::IOBuffer(kReadBufferSize); int result = socket_->Read( read_buffer_.get(), kReadBufferSize, base::Bind(&MessageReader::OnRead, weak_factory_.GetWeakPtr())); HandleReadResult(result, &read_succeeded); } } void MessageReader::OnRead(int result) { DCHECK(CalledOnValidThread()); DCHECK(read_pending_); read_pending_ = false; if (!closed_) { bool read_succeeded; HandleReadResult(result, &read_succeeded); if (read_succeeded) DoRead(); } } void MessageReader::HandleReadResult(int result, bool* read_succeeded) { DCHECK(CalledOnValidThread()); if (closed_) return; *read_succeeded = true; if (result > 0) { OnDataReceived(read_buffer_.get(), result); *read_succeeded = true; } else if (result == net::ERR_IO_PENDING) { read_pending_ = true; } else { DCHECK_LT(result, 0); // Stop reading after any error. closed_ = true; *read_succeeded = false; LOG(ERROR) << "Read() returned error " << result; read_failed_callback_.Run(result); } } void MessageReader::OnDataReceived(net::IOBuffer* data, int data_size) { DCHECK(CalledOnValidThread()); message_decoder_.AddData(data, data_size); // Get list of all new messages first, and then call the callback // for all of them. while (true) { CompoundBuffer* buffer = message_decoder_.GetNextMessage(); if (!buffer) break; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&MessageReader::RunCallback, weak_factory_.GetWeakPtr(), base::Passed(base::WrapUnique(buffer)))); } } void MessageReader::RunCallback(std::unique_ptr<CompoundBuffer> message) { if (!message_received_callback_.is_null()) message_received_callback_.Run(std::move(message)); } } // namespace protocol } // namespace remoting
[ "dummas@163.com" ]
dummas@163.com
e0f17c3622e3a4d8e7650e87fe2e532c0056523f
802853a94d217b7937237b7fedebd29c71c7ac51
/Bs2KstKst/main/Bs2KstKst_PIDBDTTraining.cpp
36200e74928007a8ac3aaf2bf4eeb7265dd527a9
[]
no_license
BlaiseDelaney/LHCbAnalysis
7a019f979366eba7f58bc5fe3061405b0a977e82
8ee07d622e7df782b33f7f4ba68df5dd2aff784d
refs/heads/master
2021-04-06T00:42:31.343354
2018-03-13T13:50:45
2018-03-13T13:50:45
124,939,078
0
0
null
2018-03-12T19:16:59
2018-03-12T19:16:59
null
UTF-8
C++
false
false
708
cpp
#include "Utils.h" #include "RunEngine.h" #include "Variables_Analysis.h" #include "BDTForPID.h" using namespace std; using namespace Utils; int main(int argc, char **argv) { // create run engine RunEngine runner("RunEngine", argc, argv); // create the variables Bs2KstKst::Variables_Analysis *v = new Bs2KstKst::Variables_Analysis() ; // make the analysers Bs2KstKst::BDTForPID *bdtTrainer = new Bs2KstKst::BDTForPID ( "BDTForPID" , v ); bdtTrainer->setTrainMode(); // pass variables to runner runner.setVariables( v ); // pass analysers to runner runner.addAnalyser( bdtTrainer ); // run runner.run(); // clean up delete v; delete bdtTrainer; return 0; }
[ "matthew.william.kenzie@cern.ch" ]
matthew.william.kenzie@cern.ch
b8fc96ee3c9ae8f30eeb067994d424438c6566b5
dd6162081ec0ee0f8a9b63ec45669f202f8520dc
/src/duke/gl/Program.hpp
6d43714d863182c72280dbc72fb0dc64b27e7e49
[ "MIT" ]
permissive
virneo/duke
60364c8a548c6792030e70167c97360f17ee9b9c
efacf7139cd1d7c2cd2f5127079721bd263dda50
refs/heads/develop
2021-01-17T10:37:25.533907
2014-11-12T14:50:39
2014-11-12T14:50:39
45,284,061
1
0
null
2015-10-31T01:12:54
2015-10-31T01:12:54
null
UTF-8
C++
false
false
1,640
hpp
#pragma once #include "duke/gl/Shader.hpp" #include <map> namespace duke { struct Program : public noncopyable { Program(const SharedVertexShader& vertexShader, const SharedFragmentShader& fragmentShader); ~Program(); void use() const; GLint getUniformLocation(const char* pUniformName) const; void glUniform1f(const char* pUniformName, GLfloat v0); void glUniform2f(const char* pUniformName, GLfloat v0, GLfloat v1); void glUniform3f(const char* pUniformName, GLfloat v0, GLfloat v1, GLfloat v2); void glUniform4f(const char* pUniformName, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); void glUniform1i(const char* pUniformName, GLint v0); void glUniform2i(const char* pUniformName, GLint v0, GLint v1); void glUniform3i(const char* pUniformName, GLint v0, GLint v1, GLint v2); void glUniform4i(const char* pUniformName, GLint v0, GLint v1, GLint v2, GLint v3); void glUniform1ui(const char* pUniformName, GLuint v0); void glUniform2ui(const char* pUniformName, GLuint v0, GLuint v1); void glUniform3ui(const char* pUniformName, GLuint v0, GLuint v1, GLuint v2); void glUniform4ui(const char* pUniformName, GLuint v0, GLuint v1, GLuint v2, GLuint v3); private: const GLuint programId; const SharedVertexShader pVertexShader; const SharedFragmentShader pFragmentShader; enum { DATA_SIZE = 4 * sizeof(GLfloat) }; struct CacheEntry { GLint location; char data[DATA_SIZE]; }; typedef std::map<const char*, CacheEntry> Cache; Cache m_Cache; CacheEntry& getOrCreate(const char* pUniformName); }; typedef std::shared_ptr<Program> SharedProgram; } /* namespace duke */
[ "chatelet.guillaume@gmail.com" ]
chatelet.guillaume@gmail.com
37dd63086dc821c898fc88d427185202c9ef28d0
ee07ddcba41df8866b838d2749eb2c75bac76dca
/tests/simplest_web_wiznet/simplest_web_wiznet.ino
84100d96ac3adc9e73dd7a3b9d4696d33e71809a
[]
no_license
ioanvapi/arduino-sms-service
6f2e678c178998a75f5270b8cdb124f993e3e432
4459a89b6625ced4eaedd9af0800f7c9a8221cfc
refs/heads/master
2021-01-02T09:02:31.150839
2014-06-06T10:53:43
2014-06-06T10:53:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,454
ino
/* Built on Arduino Nano + Wiznet W5100 Ethernet shield and Ethernet library. Tested in a browser and a POSTMAN chrome plugin End of line = '13 10' = '\r \n' End of request = empty line = '13 10' = '\r \n' Note: It works with both GET and POST requests. */ #include <SPI.h> #include <Ethernet.h> byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; IPAddress ip(10, 220, 10 , 171); IPAddress mask(255, 255, 0 , 0); IPAddress gateway(10, 220, 0 , 1); IPAddress domain(10, 220, 10 , 1); EthernetServer server(80); EthernetClient client; void setup() { Serial.begin(9600); Ethernet.begin(mac, ip, domain, gateway, mask); server.begin(); Serial.print(F("## server is at ")); Serial.println(Ethernet.localIP()); } void loop() { if (client = server.available()) { Serial.println(F("\n## new client")); while (client.available()) { Serial.write((char) client.read()); } send_http_response(client); delay(5); client.stop(); Serial.println(F("\n## client disconnected")); } } void send_http_response(EthernetClient client) { // send a standard http response client.println(F("HTTP/1.1 200 OK")); client.println(F("Content-Type: text/html")); client.println(); client.println(F("<!DOCTYPE HTML>")); client.println(F("<html>")); client.print(F("Hello world from Arduino !!!")); client.println(F("</html>")); client.println(); }
[ "vapirovschi@synygy.com" ]
vapirovschi@synygy.com
480f0c2683585d8205711bfc067a74ad1c13973c
3907c73f0ed89978de37c1e3df13268e5464156f
/serialgrbl.h
b14ef7681f21f32d34091408fc674d0c0a1b02dc
[]
no_license
angelscutipa/OASIS-Publico
4178fd195f5eca4e18a53484f4786bd2b6294f23
798972a3c3f25893a15745c0cbd5f1b2e8fdb2ae
refs/heads/main
2023-03-14T02:10:15.737747
2021-03-07T03:21:08
2021-03-07T03:21:08
345,248,523
0
0
null
null
null
null
UTF-8
C++
false
false
3,147
h
#ifndef SERIALGRBL_H #define SERIALGRBL_H #include <iostream> #include <QtSerialPort/QSerialPort> #include <vector> #include <serialhp45.h> using namespace std; class SerialGRBL { public: // Definir el serial; // definir baudarte del serial // definir timeout del serial. serial ser; int connection_state = 0; int started_state = 0; int ok_state = 0; int error_state = 0; string motion_state = ""; int motion_state_index = 0; int motion_state_index_set = 0; int motion_state_changed = 1; int motion_state_index_limit = 100; int homed_state = 0; int send_get_status = 0; double motion_x_pos = 0.0; double motion_y_pos = 0.0; double motion_z_pos = 0.0; double motion_a_pos = 0.0; double printer_size_x = 480.0; double printer_size_y = 480.0; double printer_size_f = 480.0; double printer_size_b = 480.0; int spreader_state = 0; double nl_back_pos_x = 100.0; //where x starts feeding double nl_back_pos_y = 240.0; //where y starts and ends while feeding double nl_front_pos_x = 475.0; //where x ends double nl_travel_speed = 12000.0; //how fast new layer travels double nl_feed_speed = 6000.0; //how fast new layer feeds (default 3000) double nl_piston_speed = 150.0; //how fast the pistons move double nl_piston_clearance = 0.25; //how much the pistons lower after a new layer to clear the spreader double nl_piston_hysteresis = 1.00; //how much the piston needs to move down before it can move up double nl_piston_feed_overfill = 1.1; //the fraction which feed supplies more than built takes double nl_end_tolerance = 10.0; //how close to the end pos the gantry needs to be to consider new layer done int nl_state = 1; //state of new layer, 1 is done, 0 is in progress int printer_homing_dir_x = -1; //homing direction int printer_homing_dir_y = 1; //homing direction int printer_homing_pulloff = 5; //how much the printer steps back after a home string window_output_buffer = ""; string window_input_buffer = ""; float grbl_version = 0.0; vector<string> gcode_buffer; int gcode_buffer_left = 0; SerialGRBL(); int Connect(string port); int Disconnect(); void Update(); void SerialWriteRaw(string input_string, int temp_priority); void SerialWriteBufferRaw(string input_string); void SerialGotoXY(float temp_x, float temp_y, string temp_f=""); void SerialGotoHome(string temp_f); void Jog(string temp_axis, string temp_distance, string temp_feed); int SpreaderToggle(); void SpreaderSet(int temp_spreader_state); void NewLayer(double temp_thickness, int temp_override_build = 0); int BufferLeft(); void BufferNext(); void home(); void GetStatus(); string GetWindowOutput(); string GetWindowInput(); void StatusIndexSet(); int StatusIndexChanged(); }; #endif // SERIALGRBL_H
[ "noreply@github.com" ]
angelscutipa.noreply@github.com
3511eeb54a3cc16ff287121d4a2ce74496b37387
bb85dc81b94a1ec329399f011a04857102641ff7
/1.cpp
8386c26892a700d6e2778a1727cdd8fd1edc83a0
[]
no_license
akahana-1/JOI2012-2013p
86cc036e86b244fc5d2acacd38b266583361490c
e5522f5075815fe4087ab14fb43b6d07d2c53645
refs/heads/master
2021-01-02T22:51:41.703603
2013-01-09T19:27:40
2013-01-09T19:27:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
347
cpp
#include <iostream> #include <cmath> using namespace std; int main(){ int n,ta,tb; double a,b,c,d; cin >> n; cin >> a >> b >> c >> d; a /= c; b /= d; ta = (int)(ceil(a)); tb = (int)(ceil(b)); if(ta > tb){ cout << n - ta << endl; } else { cout << n - tb << endl; } return 0; }
[ "akahana@akahana-PC.(none)" ]
akahana@akahana-PC.(none)
584abc0c91d92ac1e606d85ff60caf750b6c5df7
cb38f5da8916a8c8192fd0d7729652f02417ede7
/BeagleBone_Blue_catkin_ws/src/navigation/src/prototype_mission_4_1.cpp
e0c1105d8daeb4b7e2a92d900a4f2826313cf412
[ "MIT" ]
permissive
raymondturrisi/MiniMAUV-software
fe42057687e4fc42436309bd7cc5f0d729f3d638
442c3238e3ca441a5fb9544da4163ef2afbaafda
refs/heads/main
2023-04-23T22:19:44.685960
2021-05-12T14:42:14
2021-05-12T14:42:14
306,679,229
2
0
null
null
null
null
UTF-8
C++
false
false
6,383
cpp
/* * @file prototype_mission_4_1.cpp * @Node name: prototype_mission_4_1 * @Publishing to: * All * @Subscribing to: * none * * @description * Prototype mission 4_1 with open loop controls * 1) Get into horizontal cruising configuration * 2) Test 2 PWMs for 10 seconds each [1510, 1520] * * @author | initials * Raymond Turrisi, raymond.turrisi@gmail.com | rt * @contributors | initials * - * - * @log * 11/14/2020: Created prototype_mission_4_1 * * */ #include <sstream> #include <thread> #include <chrono> #include <ctime> #include <cmath> #include <signal.h> #include <ratio> #include <unistd.h> #include "ros/ros.h" #include "std_msgs/Int32.h" #include "std_msgs/Bool.h" #include "std_msgs/Float32.h" //shuts down if ctrl^c void MySigintHandler(int sig) { ROS_INFO("Shutting down: prototype_mission_1"); ros::shutdown(); return; } //subscriber variables float vbs_cdist = 20, beat = 0; bool vbs_calibrated = false, leaking = false; //subscriber callbacks void vbs_cdistCallback(const std_msgs::Float32::ConstPtr& msg) { vbs_cdist = msg->data; } void vbs_calibratedCallback(const std_msgs::Bool::ConstPtr& msg) { vbs_calibrated = msg->data; } void beatCallback(const std_msgs::Float32::ConstPtr& msg) { beat = msg->data; } void leakingCallback(const std_msgs::Float32::ConstPtr& msg) { leaking = msg->data; } int main(int argc, char **argv) { // initialize a ros node (name used in ros context) ros::init(argc, argv, "prototype_mission_6"); // create a handle of the node (name used in the file) ros::NodeHandle pm4_1; signal(SIGINT, MySigintHandler); //subscribers: vbs_dist, vbs_calibrated, beat ros::Subscriber vbs_cdist_sub = pm4_1.subscribe("vbs/vbs_current_dist", 1, vbs_cdistCallback); ros::Subscriber vbs_calibrated_sub = pm4_1.subscribe("vbs/vbs_calibrated", 1, vbs_calibratedCallback); ros::Subscriber heartbeat_sub = pm4_1.subscribe("heartbeat/beat", 1, beatCallback); ros::Subscriber leaking_sub = pm4_1.subscribe("heartbeat/leaking", 1, leakingCallback); //publishers ros::Publisher hfleft_ang_pub = pm4_1.advertise<std_msgs::Float32>("dtt/hfleft_ang", 1); ros::Publisher hfright_ang_pub = pm4_1.advertise<std_msgs::Float32>("dtt/hfright_ang", 1); ros::Publisher escleft_pub = pm4_1.advertise<std_msgs::Float32>("dtt/escleft", 1); ros::Publisher escright_pub = pm4_1.advertise<std_msgs::Float32>("dtt/escright", 1); ros::Publisher vbs_desired_dist_pub = pm4_1.advertise<std_msgs::Float32>("vbs/vbs_desired_dist", 1); ros::Publisher mm_ang_pub = pm4_1.advertise<std_msgs::Float32>("mm/mm_ang", 1); ros::Publisher vbs_calibrated_pub = pm4_1.advertise<std_msgs::Bool>("vbs/vbs_calibrated", 1); //publishing variables std_msgs::Float32 hfleft_ang; std_msgs::Float32 hfright_ang; std_msgs::Float32 escleft; std_msgs::Float32 escright; std_msgs::Float32 vbs_desired_dist; std_msgs::Bool vbs_calibrated_pub_msg; std_msgs::Float32 mm_ang; ros::Rate loop_rate(10); while(ros::ok()) { ROS_INFO("T-10..\n"); for(int i = 10; i >= 0; i--) { ROS_INFO("%i\n", i); ros::Duration(1).sleep(); } ROS_INFO("Starting\n"); //1a) Get into horizontal cruising configuration hfleft_ang.data = 180; hfright_ang.data = 180; escleft.data = 1500; escright.data = 1500; vbs_desired_dist.data = 80; mm_ang.data = 90; while((std::abs(vbs_desired_dist.data - vbs_cdist) > 5) && !leaking) { ROS_INFO("1a) dist err %f\n", std::abs(vbs_desired_dist.data - vbs_cdist)); hfleft_ang_pub.publish(hfleft_ang); hfright_ang_pub.publish(hfright_ang); escleft_pub.publish(escleft); escright_pub.publish(escright); vbs_desired_dist_pub.publish(vbs_desired_dist); mm_ang_pub.publish(mm_ang); ros::spinOnce(); ros::Duration(0.5).sleep(); } //1b) Hold into horizontal cruising configuration for 5 seconds >> for ~~ hfleft_ang.data = 180; hfright_ang.data = 180; escleft.data = 1500; escright.data = 1500; vbs_desired_dist.data = 80; mm_ang.data = 90; for(int i = 0; i < 10; i++) { if(leaking) { break; } ROS_INFO("1b) i %i\n", i); hfleft_ang_pub.publish(hfleft_ang); hfright_ang_pub.publish(hfright_ang); escleft_pub.publish(escleft); escright_pub.publish(escright); vbs_desired_dist_pub.publish(vbs_desired_dist); mm_ang_pub.publish(mm_ang); ros::spinOnce(); ros::Duration(1).sleep(); } //2a) Cruise at 1540 PWM for 10 seconds >> for ~~ hfleft_ang.data = 180; hfright_ang.data = 180; escleft.data = 1540; escright.data = 1540; vbs_desired_dist.data = 80; mm_ang.data = 90; for(int i = 0; i < 10; i++) { if(leaking) { break; } ROS_INFO("2a) i %i\n", i); hfleft_ang_pub.publish(hfleft_ang); hfright_ang_pub.publish(hfright_ang); escleft_pub.publish(escleft); escright_pub.publish(escright); vbs_desired_dist_pub.publish(vbs_desired_dist); mm_ang_pub.publish(mm_ang); ros::spinOnce(); ros::Duration(1).sleep(); } //2b) Cruise at 1560 PWM for 10 seconds >> for ~~ hfleft_ang.data = 180; hfright_ang.data = 180; escleft.data = 1560; escright.data = 1560; vbs_desired_dist.data = 80; mm_ang.data = 90; for(int i = 0; i < 10; i++) { if(leaking) { break; } ROS_INFO("2b) i %i\n", i); hfleft_ang_pub.publish(hfleft_ang); hfright_ang_pub.publish(hfright_ang); escleft_pub.publish(escleft); escright_pub.publish(escright); vbs_desired_dist_pub.publish(vbs_desired_dist); mm_ang_pub.publish(mm_ang); ros::spinOnce(); ros::Duration(1).sleep(); } //3) Reset all actuators for 5 seconds >> for ~~ hfleft_ang.data = 180; hfright_ang.data = 180; escleft.data = 1500; escright.data = 1500; vbs_desired_dist.data = 80; mm_ang.data = 90; for(int i = 0; i < 10; i++) { ROS_INFO("exit) i %i\n", i); hfleft_ang_pub.publish(hfleft_ang); hfright_ang_pub.publish(hfright_ang); escleft_pub.publish(escleft); escright_pub.publish(escright); vbs_desired_dist_pub.publish(vbs_desired_dist); mm_ang_pub.publish(mm_ang); ros::spinOnce(); ros::Duration(1).sleep(); } ros::shutdown(); } return 0; }
[ "raymond.turrisi@gmail.com" ]
raymond.turrisi@gmail.com
b13de398af01c9d4f6fa5b358fd5a3e08267f8c7
b029b01a30c0c42f922f9eddeb5ff3f27c2b8984
/chrome/browser/prerender/prerender_test_utils.h
741d93f6a6e15531e228165dc03bad8cf607decc
[ "BSD-3-Clause" ]
permissive
Schlam/chromium-white-flash-fix
856fa057b44607cdb9835037a36fedc1fa234412
d80242b605bbf316d9908bc5fbe485ffeb51a748
refs/heads/master
2023-02-20T17:35:51.551838
2016-11-19T03:36:37
2016-11-19T03:39:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,616
h
// Copyright (c) 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_PRERENDER_PRERENDER_TEST_UTILS_H_ #define CHROME_BROWSER_PRERENDER_PRERENDER_TEST_UTILS_H_ #include <deque> #include <functional> #include <memory> #include <set> #include <string> #include <unordered_map> #include <vector> #include "base/memory/weak_ptr.h" #include "base/run_loop.h" #include "base/test/histogram_tester.h" #include "chrome/browser/external_protocol/external_protocol_handler.h" #include "chrome/browser/prerender/prerender_contents.h" #include "chrome/browser/prerender/prerender_manager.h" #include "chrome/browser/safe_browsing/test_safe_browsing_service.h" #include "chrome/test/base/in_process_browser_test.h" #include "components/safe_browsing_db/test_database_manager.h" #include "content/public/browser/browser_thread.h" #include "net/test/url_request/url_request_mock_http_job.h" #include "net/url_request/url_request_interceptor.h" #include "url/gurl.h" namespace base { class FilePath; } // namespace base namespace net { class URLRequest; class NetworkDelegate; } // namespace net namespace prerender { namespace test_utils { // Dummy counter class to live on the UI thread for counting requests. class RequestCounter : public base::SupportsWeakPtr<RequestCounter> { public: RequestCounter(); ~RequestCounter(); int count() const { return count_; } void RequestStarted(); void WaitForCount(int expected_count); private: int count_; int expected_count_; std::unique_ptr<base::RunLoop> loop_; }; // A SafeBrowsingDatabaseManager implementation that returns a fixed result for // a given URL. class FakeSafeBrowsingDatabaseManager : public safe_browsing::TestSafeBrowsingDatabaseManager { public: FakeSafeBrowsingDatabaseManager(); // Called on the IO thread to check if the given url is safe or not. If we // can synchronously determine that the url is safe, CheckUrl returns true. // Otherwise it returns false, and "client" is called asynchronously with the // result when it is ready. // Returns true, indicating a SAFE result, unless the URL is the fixed URL // specified by the user, and the user-specified result is not SAFE // (in which that result will be communicated back via a call into the // client, and false will be returned). // Overrides SafeBrowsingDatabaseManager::CheckBrowseUrl. bool CheckBrowseUrl(const GURL& gurl, Client* client) override; void SetThreatTypeForUrl(const GURL& url, safe_browsing::SBThreatType threat_type) { bad_urls_[url.spec()] = threat_type; } // These are called when checking URLs, so we implement them. bool IsSupported() const override; bool ChecksAreAlwaysAsync() const override; bool CanCheckResourceType( content::ResourceType /* resource_type */) const override; bool CheckExtensionIDs(const std::set<std::string>& extension_ids, Client* client) override; private: ~FakeSafeBrowsingDatabaseManager() override; void OnCheckBrowseURLDone(const GURL& gurl, Client* client); std::unordered_map<std::string, safe_browsing::SBThreatType> bad_urls_; DISALLOW_COPY_AND_ASSIGN(FakeSafeBrowsingDatabaseManager); }; // PrerenderContents that stops the UI message loop on DidStopLoading(). class TestPrerenderContents : public PrerenderContents { public: TestPrerenderContents(PrerenderManager* prerender_manager, Profile* profile, const GURL& url, const content::Referrer& referrer, Origin origin, FinalStatus expected_final_status); ~TestPrerenderContents() override; bool CheckURL(const GURL& url) override; // For tests that open the prerender in a new background tab, the RenderView // will not have been made visible when the PrerenderContents is destroyed // even though it is used. void set_should_be_shown(bool value) { should_be_shown_ = value; } // For tests which do not know whether the prerender will be used. void set_skip_final_checks(bool value) { skip_final_checks_ = value; } FinalStatus expected_final_status() const { return expected_final_status_; } private: void OnRenderViewHostCreated( content::RenderViewHost* new_render_view_host) override; void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) override; FinalStatus expected_final_status_; // The RenderViewHost created for the prerender, if any. content::RenderViewHost* new_render_view_host_; // Set to true when the prerendering RenderWidget is hidden. bool was_hidden_; // Set to true when the prerendering RenderWidget is shown, after having been // hidden. bool was_shown_; // Expected final value of was_shown_. Defaults to true for // FINAL_STATUS_USED, and false otherwise. bool should_be_shown_; // If true, |expected_final_status_| and other shutdown checks are skipped. bool skip_final_checks_; DISALLOW_COPY_AND_ASSIGN(TestPrerenderContents); }; // A handle to a TestPrerenderContents whose lifetime is under the caller's // control. A PrerenderContents may be destroyed at any point. This allows // tracking the FinalStatus. class TestPrerender : public PrerenderContents::Observer, public base::SupportsWeakPtr<TestPrerender> { public: TestPrerender(); ~TestPrerender() override; TestPrerenderContents* contents() const { return contents_; } int number_of_loads() const { return number_of_loads_; } FinalStatus GetFinalStatus() const; void WaitForCreate(); void WaitForStart(); void WaitForStop(); // Waits for |number_of_loads()| to be at least |expected_number_of_loads| OR // for the prerender to stop running (just to avoid a timeout if the prerender // dies). Note: this does not assert equality on the number of loads; the // caller must do it instead. void WaitForLoads(int expected_number_of_loads); void OnPrerenderCreated(TestPrerenderContents* contents); // PrerenderContents::Observer implementation: void OnPrerenderStart(PrerenderContents* contents) override; void OnPrerenderStopLoading(PrerenderContents* contents) override; void OnPrerenderStop(PrerenderContents* contents) override; private: TestPrerenderContents* contents_; FinalStatus final_status_; int number_of_loads_; int expected_number_of_loads_; std::unique_ptr<base::RunLoop> load_waiter_; bool started_; bool stopped_; base::RunLoop create_loop_; base::RunLoop start_loop_; base::RunLoop stop_loop_; DISALLOW_COPY_AND_ASSIGN(TestPrerender); }; // Blocks until a TestPrerenderContents has been destroyed with the given final // status. Should be created with a TestPrerenderContents, and then // WaitForDestroy should be called and its return value checked. class DestructionWaiter { public: // Does not own the prerender_contents, which must outlive any call to // WaitForDestroy(). DestructionWaiter(TestPrerenderContents* prerender_contents, FinalStatus expected_final_status); ~DestructionWaiter(); // Returns true if the TestPrerenderContents was destroyed with the correct // final status, or false otherwise. Note this also may hang if the contents // is never destroyed (which will presumably cause the test to time out). bool WaitForDestroy(); private: class DestructionMarker : public PrerenderContents::Observer { public: // Does not own the waiter which must outlive the TestPrerenderContents. explicit DestructionMarker(DestructionWaiter* waiter); ~DestructionMarker() override; void OnPrerenderStop(PrerenderContents* contents) override; private: DestructionWaiter* waiter_; DISALLOW_COPY_AND_ASSIGN(DestructionMarker); }; // To be called by a DestructionMarker. void MarkDestruction(FinalStatus reason); base::RunLoop wait_loop_; FinalStatus expected_final_status_; bool saw_correct_status_; std::unique_ptr<DestructionMarker> marker_; DISALLOW_COPY_AND_ASSIGN(DestructionWaiter); }; // PrerenderContentsFactory that uses TestPrerenderContents. class TestPrerenderContentsFactory : public PrerenderContents::Factory { public: TestPrerenderContentsFactory(); ~TestPrerenderContentsFactory() override; std::unique_ptr<TestPrerender> ExpectPrerenderContents( FinalStatus final_status); PrerenderContents* CreatePrerenderContents( PrerenderManager* prerender_manager, Profile* profile, const GURL& url, const content::Referrer& referrer, Origin origin) override; private: struct ExpectedContents { ExpectedContents(); ExpectedContents(const ExpectedContents& other); ExpectedContents(FinalStatus final_status, const base::WeakPtr<TestPrerender>& handle); ~ExpectedContents(); FinalStatus final_status; base::WeakPtr<TestPrerender> handle; }; std::deque<ExpectedContents> expected_contents_queue_; DISALLOW_COPY_AND_ASSIGN(TestPrerenderContentsFactory); }; class PrerenderInProcessBrowserTest : virtual public InProcessBrowserTest { public: PrerenderInProcessBrowserTest(); ~PrerenderInProcessBrowserTest() override; void SetUpCommandLine(base::CommandLine* command_line) override; void SetUpInProcessBrowserTestFixture() override; void TearDownInProcessBrowserTestFixture() override; void SetUpOnMainThread() override; content::SessionStorageNamespace* GetSessionStorageNamespace() const; // Many of the file and server manipulation commands are fussy about paths // being relative or absolute. This makes path absolute if it is not // already. The path must not be empty. std::string MakeAbsolute(const std::string& path); bool UrlIsInPrerenderManager(const std::string& html_file) const; bool UrlIsInPrerenderManager(const GURL& url) const; // Convenience function to get the currently active WebContents in // current_browser(). content::WebContents* GetActiveWebContents() const; PrerenderManager* GetPrerenderManager() const; TestPrerenderContents* GetPrerenderContentsFor(const GURL& url) const; // Set up an HTTPS server. void UseHttpsSrcServer(); // Returns the currently active server. See |UseHttpsSrcServer|. net::EmbeddedTestServer* src_server(); safe_browsing::TestSafeBrowsingServiceFactory* safe_browsing_factory() const { return safe_browsing_factory_.get(); } test_utils::FakeSafeBrowsingDatabaseManager* GetFakeSafeBrowsingDatabaseManager(); TestPrerenderContentsFactory* prerender_contents_factory() const { return prerender_contents_factory_; } void set_autostart_test_server(bool value) { autostart_test_server_ = value; } void set_browser(Browser* browser) { explicitly_set_browser_ = browser; } Browser* current_browser() const { return explicitly_set_browser_ ? explicitly_set_browser_ : browser(); } const base::HistogramTester& histogram_tester() { return histogram_tester_; } // Returns a string for pattern-matching TaskManager tab entries. base::string16 MatchTaskManagerTab(const char* page_title); // Returns a string for pattern-matching TaskManager prerender entries. base::string16 MatchTaskManagerPrerender(const char* page_title); protected: // For each FinalStatus in |expected_final_status_queue| creates a prerender // that is going to verify the correctness of its FinalStatus upon // destruction. Waits for creation of the first PrerenderContents. std::vector<std::unique_ptr<TestPrerender>> NavigateWithPrerenders( const GURL& loader_url, const std::vector<FinalStatus>& expected_final_status_queue); // Creates the URL that instructs the test server to substitute the text // |replacement_variable| in the contents of the file pointed to by // |loader_path| with |url_to_prerender|. Also appends the |loader_query| to // the URL. GURL ServeLoaderURL(const std::string& loader_path, const std::string& replacement_variable, const GURL& url_to_prerender, const std::string& loader_query); private: std::unique_ptr<ExternalProtocolHandler::Delegate> external_protocol_handler_delegate_; std::unique_ptr<safe_browsing::TestSafeBrowsingServiceFactory> safe_browsing_factory_; TestPrerenderContentsFactory* prerender_contents_factory_; Browser* explicitly_set_browser_; bool autostart_test_server_; base::HistogramTester histogram_tester_; std::unique_ptr<net::EmbeddedTestServer> https_src_server_; DISALLOW_COPY_AND_ASSIGN(PrerenderInProcessBrowserTest); }; // Makes |url| respond to requests with the contents of |file|, counting the // number that start in |counter|. void CreateCountingInterceptorOnIO( const GURL& url, const base::FilePath& file, const base::WeakPtr<RequestCounter>& counter); // Makes |url| respond to requests with the contents of |file|. void CreateMockInterceptorOnIO(const GURL& url, const base::FilePath& file); // Makes |url| never respond on the first load, and then with the contents of // |file| afterwards. When the first load has been scheduled, runs |callback| on // the UI thread. void CreateHangingFirstRequestInterceptorOnIO( const GURL& url, const base::FilePath& file, base::Closure callback); } // namespace test_utils } // namespace prerender #endif // CHROME_BROWSER_PRERENDER_PRERENDER_TEST_UTILS_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
b051f7590ffc3816de97ab40aab15261aaec2757
2d5957d3f96d068c74c266a2651eb61159ffed9f
/Project1/Camera.cpp
8aea93992a91e99f5a45ab74e13c3dfb32802568
[]
no_license
ceski23/GL_MICROCAR
1564716027e62b3e8646ffc76ce88f476f85022f
acfb1ecf98182088c8ecc879b32bc82d5f95fbf2
refs/heads/master
2020-06-02T13:27:22.260357
2019-06-23T14:11:20
2019-06-23T14:11:20
191,169,350
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
1,672
cpp
#include "Camera.h" Camera::Camera(glm::vec3 startPos, glm::vec3 upperStartVector, GLfloat startYaw, GLfloat startPitch, GLfloat speed, GLfloat rotation) { position = startPos; worldUpperVector = upperStartVector; yaw = startYaw; pitch = startPitch; direction = glm::vec3(0.0f, 0.0f, -1.0f); cameraSpeed = speed; rotationSpeed = rotation; update(); } void Camera::update() { direction.x = cos(glm::radians(yaw)) * cos(glm::radians(pitch)); direction.y = sin(glm::radians(pitch)); direction.z = sin(glm::radians(yaw)) * cos(glm::radians(pitch)); direction = glm::normalize(direction); rightAxis = glm::normalize(glm::cross(direction, worldUpperVector)); //iloczyn wektorowy kierunku kamery oraz wektora górnego (świata) topAxis = glm::normalize(glm::cross(rightAxis, direction)); //iloczyn wektorowy prawej osi kamery oraz kierunku kamery (prawdziwy kierunek "do góry") } void Camera::MouseControl(GLfloat deltaX, GLfloat deltaY) { deltaX = deltaX * rotationSpeed; deltaY = deltaY * rotationSpeed; yaw += deltaX; pitch += deltaY; if (pitch > 89.0f) pitch = 89.0f; if (pitch < -89.0f) pitch = -89.0f; update(); } void Camera::KeyboardControl(bool* keys, GLfloat timeUnit) { GLfloat deltaPos = cameraSpeed * timeUnit; if (keys[GLFW_KEY_W]) position += direction * deltaPos; if (keys[GLFW_KEY_S]) position -= direction * deltaPos; if (keys[GLFW_KEY_A]) position -= rightAxis * deltaPos; if (keys[GLFW_KEY_D]) position += rightAxis * deltaPos; } glm::mat4 Camera::ComputeCameraMatrix() { return glm::lookAt(position, position + direction, topAxis); //pozycja + kierunek --- zapewnia że kamera będzie skierowana na punkt docelowy }
[ "ceski23@gmail.com" ]
ceski23@gmail.com
7a15e70c74eaaa9cc36effe9a65cbc57bdca3251
dc6c4086a298b1fec186ba81814e535e18381042
/Template/src/collisions.hpp
6dd397bb08f372312ce142ef4b917e8e85b39538
[]
no_license
Loona22/Colored_Memories
6ec3a18f571328cd1cbc2c2bdcc5f18f656f9513
3cde28803c4aca78a5b88d4df8ab17f5898d5efd
refs/heads/master
2023-02-07T21:50:05.305005
2021-01-03T21:07:12
2021-01-03T21:07:12
326,487,626
0
0
null
null
null
null
UTF-8
C++
false
false
564
hpp
#ifndef COLLISIONS_HPP #define COLLISIONS_HPP #include <glimac/SDLWindowManager.hpp> #include <GL/glew.h> #include <iostream> #include <SDL/SDL.h> #include <glimac/glm.hpp> #include "glimac/FreeflyCamera.hpp" #include <glimac/Program.hpp> #include "tresor.hpp" using namespace glimac; //gestion des collisions // cubePositions pour récupérer la position du cube // float x, y, z pour comparer avec la position du cube // retourne vrai ou faux pour savoir quanc il y a collision bool CheckCollision(glm::vec3 cubePositions, float x, float y, float z); #endif
[ "loona.upem@gmail.com" ]
loona.upem@gmail.com
a861915426b9c355fe9254704debb2b87b798686
156ae94769a8b0644feb40d73cc4ac0cdc604a36
/fhe/shield_spark/PALISADE/src/core/unittest/UnitTestEncoding.cpp
531d7116a96f2c57fb5b255d57d9ba1112d8a4f9
[ "BSD-2-Clause" ]
permissive
marcelmon/react-fhe
42ecc2e2efb26e5cd64dd6cc865d63b07ead47f8
f6e388785eb608eecce55641b57c2b102724ddd7
refs/heads/master
2020-03-21T03:13:08.271195
2018-09-17T21:35:52
2018-09-17T21:35:52
138,042,108
0
0
null
2018-08-08T04:39:58
2018-06-20T14:13:13
C++
UTF-8
C++
false
false
6,410
cpp
/* * @file * @author TPOC: palisade@njit.edu * * @copyright Copyright (c) 2017, New Jersey Institute of Technology (NJIT) * All rights reserved. * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /* This code exercises the encoding libraries of the PALISADE lattice encryption library. */ #define PROFILE #include "include/gtest/gtest.h" #include <iostream> #include "../lib/lattice/dcrtpoly.h" #include "math/backend.h" #include "encoding/encodings.h" #include "utils/inttypes.h" #include "utils/utilities.h" #include "lattice/elemparamfactory.h" using namespace std; using namespace lbcrypto; class UTEncoding : public ::testing::Test { protected: virtual void SetUp() { } virtual void TearDown() { // Code here will be called immediately after each test // (right before the destructor). } }; TEST_F(UTEncoding,scalar_encoding) { int64_t value = 47; usint m = 8; PlaintextModulus ptm = 128; shared_ptr<ILParams> lp = ElemParamFactory::GenElemParams<ILParamsImpl<BigInteger>>(m); EncodingParams ep( new EncodingParamsImpl( ptm ) ); ScalarEncoding se(lp, ep, value); se.Encode(); EXPECT_EQ( se.GetElement<Poly>()[0].ConvertToInt(), (uint64_t)value ) << "encoding failed"; EXPECT_EQ( se.GetElement<Poly>()[1].ConvertToInt(), (uint64_t)0 ) << "encoding failed"; se.Decode(); EXPECT_EQ( se.GetScalarValue(), value ) << "positive scalar"; ScalarEncoding se2(lp, ep, -value); se2.Encode(); se2.Decode(); EXPECT_EQ( se2.GetScalarValue(), -value ) << "negative scalar"; ScalarEncoding se3(lp, ep, (ptm/2)+1); EXPECT_THROW( se3.Encode(), config_error ) << "Encode did not throw the proper exception"; ScalarEncoding se3n(lp, ep, ((-1*(int64_t)ptm)/2)); EXPECT_THROW( se3n.Encode(), config_error ) << "Encode did not throw the proper exception"; ScalarEncoding se4(lp, ep, ptm/2); se4.Encode(); se4.Decode(); EXPECT_EQ( se4.GetScalarValue(), (int64_t)ptm/2 ) << "largest number"; ScalarEncoding se5(lp, ep, (-1*(int64_t)ptm)/2 + 1); se5.Encode(); se5.Decode(); EXPECT_EQ( se5.GetScalarValue(), (-1*(int64_t)ptm)/2 + 1 ) << "smallest number"; } TEST_F(UTEncoding,coef_packed_encoding) { vector<int64_t> value = {32, 17, 8, -12, -32, 22, -101, 6 }; usint m = 16; shared_ptr<ILParams> lp = ElemParamFactory::GenElemParams<ILParamsImpl<BigInteger>>(m); EncodingParams ep( new EncodingParamsImpl(256) ); CoefPackedEncoding se(lp, ep, value); se.Encode(); se.Decode(); se.SetLength( value.size() ); EXPECT_EQ( se.GetCoefPackedValue(), value ) << "CoefPacked"; } TEST_F(UTEncoding,packed_int_ptxt_encoding) { usint m = 22; PlaintextModulus p = 89; BigInteger modulusQ("955263939794561"); BigInteger squareRootOfRoot("941018665059848"); BigInteger bigmodulus("80899135611688102162227204937217"); BigInteger bigroot("77936753846653065954043047918387"); auto cycloPoly = GetCyclotomicPolynomial<BigVector, BigInteger>(m, modulusQ); ChineseRemainderTransformArb<BigInteger, BigVector>::SetCylotomicPolynomial(cycloPoly, modulusQ); PackedEncoding::SetParams(m, p); shared_ptr<ILParams> lp(new ILParams(m, modulusQ, squareRootOfRoot, bigmodulus, bigroot)); EncodingParams ep(new EncodingParamsImpl(p,8)); std::vector<uint64_t> vectorOfInts1 = { 1,2,3,4,5,6,7,8,0,0 }; PackedEncoding se(lp, ep, vectorOfInts1); se.Encode(); se.Decode(); EXPECT_EQ( se.GetPackedValue(), vectorOfInts1 ) << "packed int"; } TEST_F(UTEncoding,string_encoding) { string value = "Hello, world!"; usint m = 64; shared_ptr<ILParams> lp = ElemParamFactory::GenElemParams<ILParamsImpl<BigInteger>>(m); EncodingParams ep( new EncodingParamsImpl(256) ); StringEncoding se(lp, ep, value); se.Encode(); se.Decode(); EXPECT_EQ( se.GetStringValue(), value ) << "string encode/decode"; // truncate! shared_ptr<ILParams> lp2 = ElemParamFactory::GenElemParams<ILParamsImpl<BigInteger>>(4); StringEncoding se2(lp2, ep, value); se2.Encode(); se2.Decode(); EXPECT_EQ( se2.GetStringValue(), value.substr(0, lp2->GetRingDimension()) ) << "string truncate encode/decode"; } TEST_F(UTEncoding,integer_encoding){ int m = 64; PlaintextModulus ptm = ((uint64_t)1<<30); shared_ptr<ILParams> lp = ElemParamFactory::GenElemParams<ILParamsImpl<BigInteger>>(m); EncodingParams ep( new EncodingParamsImpl(ptm) ); int64_t mv = ((uint64_t)1<<20) + (uint64_t)1; int64_t sv = 9; IntegerEncoding small(lp, ep, sv); IntegerEncoding smallS(lp, ep, -sv); IntegerEncoding medium(lp, ep, mv); IntegerEncoding mediumS(lp, ep, -mv); small.Encode(); smallS.Encode(); medium.Encode(); mediumS.Encode(); small.Decode(); smallS.Decode(); medium.Decode(); mediumS.Decode(); EXPECT_EQ( small.GetIntegerValue(), sv ) << "small"; EXPECT_EQ( smallS.GetIntegerValue(), -sv ) << "small negative"; EXPECT_EQ( medium.GetIntegerValue(), mv ) << "medium"; EXPECT_EQ( mediumS.GetIntegerValue(), -mv ) << "medium negative"; EncodingParams ep2( new EncodingParamsImpl(2) ); IntegerEncoding one(lp, ep2, 1); one.Encode(); one.Decode(); EXPECT_EQ( one.GetIntegerValue(), 1 ) << "one"; IntegerEncoding mone(lp, ep2, -1); EXPECT_THROW( mone.Encode(), config_error ) << "Encode did not throw the proper exception"; }
[ "marcel@crowdbabble.com" ]
marcel@crowdbabble.com
b3b3c78ae4790a1c1c98dfe1be849f7818aa41a2
784f176c759a464f9792fa9edacc4ac63634e24e
/src/libtsduck/base/tsSysUtils.cpp
27d0901bb0c8db0c01cc746c8b14de8002fcc347
[ "BSD-2-Clause" ]
permissive
ajithdesilva/tsduck
efe6475d9351a19dc12a5f9bb0503d9257507d8f
8dfb98034c7a5d86af52cbce0b6efd50123659b7
refs/heads/master
2023-04-29T01:31:16.919758
2021-05-09T18:09:02
2021-05-09T18:09:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
28,504
cpp
//---------------------------------------------------------------------------- // // TSDuck - The MPEG Transport Stream Toolkit // Copyright (c) 2005-2021, Thierry Lelegard // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // //---------------------------------------------------------------------------- #include "tsSysUtils.h" #include "tsStaticInstance.h" #include "tsMutex.h" #include "tsGuard.h" #include "tsTime.h" #include "tsArgs.h" TSDUCK_SOURCE; #if defined(TS_WINDOWS) #include <intrin.h> #include "tsWinUtils.h" #endif #if defined(TS_LINUX) #include "tsFileUtils.h" #endif #if defined(TS_MAC) #include <sys/resource.h> #include <mach/mach.h> #include <mach/message.h> #include <mach/kern_return.h> #include <mach/task_info.h> extern char **environ; // not defined in public headers #endif // External calls to environment variables are not reentrant. Use a global mutex. TS_STATIC_INSTANCE(ts::Mutex, (), EnvironmentMutex) //---------------------------------------------------------------------------- // Return the name of the current application executable file. //---------------------------------------------------------------------------- ts::UString ts::ExecutableFile() { #if defined(TS_WINDOWS) // Window implementation. std::array<::WCHAR, 2048> name; ::DWORD length = ::GetModuleFileNameW(nullptr, name.data(), ::DWORD(name.size())); return UString(name, length); #elif defined(TS_LINUX) // Linux implementation. // /proc/self/exe is a symbolic link to the executable. return ResolveSymbolicLinks(u"/proc/self/exe"); #elif defined(TS_MAC) // MacOS implementation. // The function proc_pidpath is documented as "private" and "subject to change". // Another option is _NSGetExecutablePath (not tested here yet). int length; char name[PROC_PIDPATHINFO_MAXSIZE]; if ((length = ::proc_pidpath(getpid(), name, sizeof(name))) < 0) { throw ts::Exception(u"proc_pidpath error", errno); } else { assert(length <= int(sizeof(name))); return UString::FromUTF8(name, length); } #else #error "ts::ExecutableFile not implemented on this system" #endif } //---------------------------------------------------------------------------- //! Get the name of the executable or shared library containing the caller. //---------------------------------------------------------------------------- ts::UString ts::CallerLibraryFile() { #if defined(TS_MSC) // Window implementation. // Get return address of current function (in caller code). void* const ret = _ReturnAddress(); // Get the module (DLL) into which this address can be found. ::HMODULE handle = nullptr; if (::GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, ::LPCWSTR(ret), &handle) == 0) { return UString(); } else { std::array<::WCHAR, 2048> name; ::DWORD length = ::GetModuleFileNameW(handle, name.data(), ::DWORD(name.size())); return UString(name, length); } #elif defined(TS_GCC) || defined(TS_LLVM) // GCC and LLVM/clang implementation. // Get return address of current function (in caller code). void* const ret = __builtin_return_address(0); // Get the shared library into which this address can be found. ::Dl_info info; TS_ZERO(info); if (ret != nullptr && ::dladdr(ret, &info) != 0 && info.dli_fname != nullptr) { return UString::FromUTF8(info.dli_fname); } else { return UString(); } #else #error "ts::CallerLibraryFile not implemented on this system" #endif } //---------------------------------------------------------------------------- // Suspend the current thread for the specified period //---------------------------------------------------------------------------- void ts::SleepThread(MilliSecond delay) { #if defined(TS_WINDOWS) // Window implementation. ::Sleep(::DWORD(delay)); #else // POSIX implementation. ::timespec requested, remain; requested.tv_sec = time_t(delay / 1000); // seconds requested.tv_nsec = long((delay % 1000) * 1000000); // nanoseconds while (::nanosleep(&requested, &remain) < 0) { if (errno == EINTR) { // Interrupted by a signal. Wait again. requested = remain; } else { // Actual error throw ts::Exception(u"nanosleep error", errno); } } #endif } //---------------------------------------------------------------------------- // Get current process characteristics. //---------------------------------------------------------------------------- ts::ProcessId ts::CurrentProcessId() { #if defined(TS_WINDOWS) return ::GetCurrentProcessId(); #else return ::getpid(); #endif } bool ts::IsPrivilegedUser() { #if defined(TS_UNIX) return ::geteuid() == 0; #else ::SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY; ::PSID AdministratorsGroup; ::BOOL ok = ::AllocateAndInitializeSid(&NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &AdministratorsGroup); if (ok) { if (!::CheckTokenMembership(nullptr, AdministratorsGroup, &ok)) { ok = false; } ::FreeSid(AdministratorsGroup); } return ok; #endif } //---------------------------------------------------------------------------- // Format an error code into a string //---------------------------------------------------------------------------- #if !defined(TS_WINDOWS) // Depending on GNU vs. POSIX, strerror_r returns an int or a char*. // There are two short functions to handle the strerror_r result. // The C++ compiler will automatically invoke the right one. // The other one is unused (disable unused warning). TS_PUSH_WARNING() TS_LLVM_NOWARNING(unused-function) TS_GCC_NOWARNING(unused-function) namespace { // POSIX version, strerror_r returns an int, leave result unmodified. inline void handle_strerror_r(bool& found, char*& result, int strerror_t_ret) { found = strerror_t_ret == 0; // success } // GNU version, strerror_r returns char*, not necessarily in buffer. inline void handle_strerror_r(bool& found, char*& result, char* strerror_t_ret) { result = strerror_t_ret; // actual message found = result != nullptr; } } TS_POP_WARNING() #endif // not Windows // Portable public interface: ts::UString ts::SysErrorCodeMessage(ts::SysErrorCode code) { #if defined(TS_WINDOWS) return WinErrorMessage(code); #else char message[1024]; TS_ZERO(message); char* result = message; bool found = false; handle_strerror_r(found, result, strerror_r(code, message, sizeof(message))); if (found) { // Make sure message is nul-terminated. message[sizeof(message) - 1] = 0; // Remove trailing newlines (if any) for (size_t i = ::strlen(result); i > 0 && (result[i - 1] == '\n' || result[i - 1] == '\r'); result[--i] = 0) {} return UString::FromUTF8(result); } // At this point, the message is not found. return UString::Format(u"System error %d (0x%X)", {code, code}); #endif } //---------------------------------------------------------------------------- // Get metrics for the current process //---------------------------------------------------------------------------- void ts::GetProcessMetrics(ProcessMetrics& metrics) { metrics.cpu_time = 0; metrics.vmem_size = 0; #if defined(TS_WINDOWS) // Windows implementation // Get a handle to the current process ::HANDLE proc(::GetCurrentProcess()); // Get process CPU time ::FILETIME creation_time, exit_time, kernel_time, user_time; if (::GetProcessTimes(proc, &creation_time, &exit_time, &kernel_time, &user_time) == 0) { throw ts::Exception(u"GetProcessTimes error", ::GetLastError()); } metrics.cpu_time = ts::Time::Win32FileTimeToMilliSecond(kernel_time) + ts::Time::Win32FileTimeToMilliSecond(user_time); // Get virtual memory size ::PROCESS_MEMORY_COUNTERS_EX mem_counters; if (::GetProcessMemoryInfo(proc, (::PROCESS_MEMORY_COUNTERS*)&mem_counters, sizeof(mem_counters)) == 0) { throw ts::Exception(u"GetProcessMemoryInfo error", ::GetLastError()); } metrics.vmem_size = mem_counters.PrivateUsage; #elif defined(TS_LINUX) // Linux implementation. // Definition of data available from /proc/<pid>/stat // See man page for proc(5) for more details. struct ProcessStatus { int pid; // The process id. char state; // One char from "RSDZTW" int ppid; // The PID of the parent. int pgrp; // The process group ID of the process. int session; // The session ID of the process. int tty_nr; // The tty the process uses. int tpgid; // Process group ID which owns the tty unsigned long flags; // The flags of the process. unsigned long minflt; // Minor faults the process made unsigned long cminflt; // Minor faults the process's children made unsigned long majflt; // Major faults the process made unsigned long cmajflt; // Major faults the process's children made unsigned long utime; // Number of jiffies in user mode unsigned long stime; // Number of jiffies in kernel mode long cutime; // Jiffies process's children in user mode long cstime; // Jiffies process's children in kernel mode long priority; // Standard nice value, plus fifteen. long nice; // Nice value, from 19 (nicest) to -19 (not nice) long itrealvalue; // Jiffies before the next SIGALRM unsigned long starttime; // Jiffies the process started after system boot unsigned long vsize; // Virtual memory size in bytes. long rss; // Resident Set Size unsigned long rlim; // Current limit in bytes on the rss unsigned long startcode; // Address above which program text can run. unsigned long endcode; // Address below which program text can run. unsigned long startstack; // Address of the start of the stack unsigned long kstkesp; // Current value of esp (stack pointer) unsigned long kstkeip; // Current EIP (instruction pointer). unsigned long signal; // Bitmap of pending signals (usually 0). unsigned long blocked; // Bitmap of blocked signals unsigned long sigignore; // Bitmap of ignored signals. unsigned long sigcatch; // Bitmap of catched signals. unsigned long wchan; // "Channel" in which the process is waiting unsigned long nswap; // Number of pages swapped - not maintained. unsigned long cnswap; // Cumulative nswap for child processes. int exit_signal; // Signal to be sent to parent when we die. int processor; // CPU number last executed on. }; static const char filename[] = "/proc/self/stat"; FILE* fp = fopen(filename, "r"); if (fp == nullptr) { throw ts::Exception(UString::Format(u"error opening %s", {filename}), errno); } ProcessStatus ps; int expected = 37; int count = fscanf(fp, "%d %*s %c %d %d %d %d %d %lu %lu %lu %lu %lu %lu %lu " "%ld %ld %ld %ld %*d %ld %lu %lu %ld %lu %lu %lu %lu " "%lu %lu %lu %lu %lu %lu %lu %lu %lu %d %d", &ps.pid, &ps.state, &ps.ppid, &ps.pgrp, &ps.session, &ps.tty_nr, &ps.tpgid, &ps.flags, &ps.minflt, &ps.cminflt, &ps.majflt, &ps.cmajflt, &ps.utime, &ps.stime, &ps.cutime, &ps.cstime, &ps.priority, &ps.nice, &ps.itrealvalue, &ps.starttime, &ps.vsize, &ps.rss, &ps.rlim, &ps.startcode, &ps.endcode, &ps.startstack, &ps.kstkesp, &ps.kstkeip, &ps.signal, &ps.blocked, &ps.sigignore, &ps.sigcatch, &ps.wchan, &ps.nswap, &ps.cnswap, &ps.exit_signal, &ps.processor); fclose(fp); if (count != expected) { throw ts::Exception(UString::Format(u"error reading %s, got %d values, expected %d", {filename, count, expected})); } // Get virtual memory size metrics.vmem_size = ps.vsize; // Evaluate CPU time unsigned long jps = sysconf(_SC_CLK_TCK); // jiffies per second unsigned long jiffies = ps.utime + ps.stime; // CPU time in jiffies metrics.cpu_time = (MilliSecond(jiffies) * 1000) / jps; #elif defined(TS_MAC) // MacOS implementation. // First, get the virtual memory size using task_info (mach kernel). ::mach_task_basic_info_data_t taskinfo; TS_ZERO(taskinfo); ::mach_msg_type_number_t count = MACH_TASK_BASIC_INFO_COUNT; const ::kern_return_t status1 = ::task_info(::mach_task_self(), MACH_TASK_BASIC_INFO, ::task_info_t(&taskinfo), &count); if (status1 != KERN_SUCCESS) { throw ts::Exception(u"task_info error"); } metrics.vmem_size = taskinfo.virtual_size; // Then get CPU time using getrusage. ::rusage usage; const int status2 = ::getrusage(RUSAGE_SELF, &usage); if (status2 < 0) { throw ts::Exception(u"getrusage error"); } // Add system time and user time, in milliseconds. metrics.cpu_time = MilliSecond(usage.ru_stime.tv_sec) * MilliSecPerSec + MilliSecond(usage.ru_stime.tv_usec) / MicroSecPerMilliSec + MilliSecond(usage.ru_utime.tv_sec) * MilliSecPerSec + MilliSecond(usage.ru_utime.tv_usec) / MicroSecPerMilliSec; #else #error "ts::GetProcessMetrics not implemented on this system" #endif } //---------------------------------------------------------------------------- // Ignore SIGPIPE. On UNIX systems: writing to a broken pipe returns an // error instead of killing the process. On Windows systems: does nothing. //---------------------------------------------------------------------------- void ts::IgnorePipeSignal() { #if !defined(TS_WINDOWS) ::signal(SIGPIPE, SIG_IGN); #endif } //---------------------------------------------------------------------------- // Put standard input / output stream in binary mode. // On UNIX systems, this does not make any difference. // On Windows systems, however, in a stream which is not open in // binary mode, there is automatic translation between LF and CR-LF. // The standard input / output are open in text mode (non-binary). // These functions force them into binary mode. // Return true on success, false on error. // If report is a subclass or ts::Args, also terminate application. //---------------------------------------------------------------------------- bool ts::SetBinaryModeStdin(Report& report) { #if defined(TS_WINDOWS) report.debug(u"setting standard input to binary mode"); if (::_setmode(_fileno(stdin), _O_BINARY) < 0) { report.error(u"cannot set standard input to binary mode"); Args* args = dynamic_cast<Args*>(&report); if (args != 0) { args->exitOnError(); } return false; } #endif return true; } bool ts::SetBinaryModeStdout(Report& report) { #if defined(TS_WINDOWS) report.debug(u"setting standard output to binary mode"); if (::_setmode(_fileno(stdout), _O_BINARY) < 0) { report.error(u"cannot set standard output to binary mode"); Args* args = dynamic_cast<Args*>(&report); if (args != 0) { args->exitOnError(); } return false; } #endif return true; } //---------------------------------------------------------------------------- // Check if an environment variable exists //---------------------------------------------------------------------------- bool ts::EnvironmentExists(const UString& name) { Guard lock(EnvironmentMutex::Instance()); #if defined(TS_WINDOWS) std::array <::WCHAR, 2> unused; return ::GetEnvironmentVariableW(name.wc_str(), unused.data(), ::DWORD(unused.size())) != 0; #else // Flawfinder: ignore: Environment variables are untrustable input. return ::getenv(name.toUTF8().c_str()) != nullptr; #endif } //---------------------------------------------------------------------------- // Get the value of an environment variable. // Return default value if does not exist. //---------------------------------------------------------------------------- ts::UString ts::GetEnvironment(const UString& name, const UString& def) { Guard lock(EnvironmentMutex::Instance()); #if defined(TS_WINDOWS) std::vector<::WCHAR> value; value.resize(512); ::DWORD size = ::GetEnvironmentVariableW(name.wc_str(), value.data(), ::DWORD(value.size())); if (size >= ::DWORD(value.size())) { value.resize(size_t(size + 1)); size = ::GetEnvironmentVariableW(name.wc_str(), value.data(), ::DWORD(value.size())); } return size <= 0 ? def : UString(value, size); #else // Flawfinder: ignore: Environment variables are untrustable input. const char* value = ::getenv(name.toUTF8().c_str()); return value != nullptr ? UString::FromUTF8(value) : def; #endif } //---------------------------------------------------------------------------- // Set the value of an environment variable. //---------------------------------------------------------------------------- bool ts::SetEnvironment(const UString& name, const UString& value) { Guard lock(EnvironmentMutex::Instance()); #if defined(TS_WINDOWS) return ::SetEnvironmentVariableW(name.wc_str(), value.wc_str()) != 0; #else // In case of error, setenv(3) is documented to return -1 but not setting errno. return ::setenv(name.toUTF8().c_str(), value.toUTF8().c_str(), 1) == 0; #endif } //---------------------------------------------------------------------------- // Delete an environment variable. //---------------------------------------------------------------------------- bool ts::DeleteEnvironment(const UString& name) { Guard lock(EnvironmentMutex::Instance()); #if defined(TS_WINDOWS) return ::SetEnvironmentVariableW(name.wc_str(), nullptr) != 0; #else // In case of error, unsetenv(3) is documented to return -1 but and set errno. // It is also documented to silently ignore non-existing variables. return ::unsetenv(name.toUTF8().c_str()) == 0; #endif } //---------------------------------------------------------------------------- // Expand environment variables inside a file path (or any string). // Environment variable references are '$name' or '${name}'. // In the first form, 'name' is the longest combination of letters, digits and underscore. // A combination \$ is interpreted as a literal $, not an environment variable reference. //---------------------------------------------------------------------------- ts::UString ts::ExpandEnvironment(const UString& path) { const size_t len = path.length(); UString expanded; expanded.reserve(2 * len); size_t index = 0; while (index < len) { if (path[index] == '\\' && index+1 < len && path[index+1] == '$') { // Escaped dollar expanded += '$'; index += 2; } else if (path[index] != '$') { // Regular character expanded += path[index++]; } else { // Environment variable reference. // First, locate variable name and move index in path. UString varname; if (++index < len) { if (path[index] == '{') { // '${name}' format const size_t last = path.find('}', index); if (last == NPOS) { varname = path.substr(index + 1); index = len; } else { varname = path.substr(index + 1, last - index - 1); index = last + 1; } } else { // '$name' format const size_t last = path.find_first_not_of(u"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_", index); if (last == NPOS) { varname = path.substr(index); index = len; } else { varname = path.substr(index, last - index); index = last; } } } // Second, replace environment variable expanded += GetEnvironment(varname); } } return expanded; } //---------------------------------------------------------------------------- // Add a "name=value" string to a container. // If exact is true, the definition is always valid. // Otherwise, cleanup the string and ignore lines without "=" //---------------------------------------------------------------------------- namespace { void AddNameValue(ts::Environment& env, const ts::UString& line, bool exact) { ts::UString s(line); // With loose line, do some initial cleanup. if (!exact) { s.trim(); if (s.empty() || s.front() == u'#') { // Empty or comment line return; } } // Locate the "=" between name and value. const size_t pos = s.find(u"="); if (pos == ts::NPOS) { // With exact line, no "=" means empty value. // With loose line, not a valid definition. if (exact) { env.insert(std::make_pair(s, ts::UString())); } } else { // Isolate name and value. ts::UString name(s.substr(0, pos)); ts::UString value(s.substr(pos + 1)); // With loose line, do some additional cleanup. if (!exact) { name.trim(); value.trim(); if (value.size() >= 2 && (value.front() == u'\'' || value.front() == u'"') && value.back() == value.front()) { // Remove surrounding quotes in the value. value.pop_back(); value.erase(0, 1); } } if (!name.empty()) { env.insert(std::make_pair(name, value)); } } } } //---------------------------------------------------------------------------- // Get the content of the entire environment (all environment variables). //---------------------------------------------------------------------------- void ts::GetEnvironment(Environment& env) { Guard lock(EnvironmentMutex::Instance()); env.clear(); #if defined(TS_WINDOWS) const ::LPWCH strings = ::GetEnvironmentStringsW(); if (strings != 0) { size_t len; for (const ::WCHAR* p = strings; (len = ::wcslen(p)) != 0; p += len + 1) { assert(sizeof(::WCHAR) == sizeof(UChar)); AddNameValue(env, UString(reinterpret_cast<const UChar*>(p), len), true); } ::FreeEnvironmentStringsW(strings); } #else for (char** p = ::environ; *p != nullptr; ++p) { AddNameValue(env, UString::FromUTF8(*p), true); } #endif } //---------------------------------------------------------------------------- // Load a text file containing environment variables. //---------------------------------------------------------------------------- bool ts::LoadEnvironment(Environment& env, const UString& fileName) { env.clear(); UStringList lines; const bool ok = UString::Load(lines, fileName); if (ok) { for (UStringList::const_iterator it = lines.begin(); it != lines.end(); ++it) { AddNameValue(env, *it, false); } } return ok; } //---------------------------------------------------------------------------- // Check if the standard input/output/error is a terminal. //---------------------------------------------------------------------------- #if defined(TS_WINDOWS) namespace { // On Windows, only the DOS and PowerShell consoles are considered as terminal. // We also want to recognize as terminals the Cygwin and Msys consoles (mintty). bool StdHandleIsATerminal(::DWORD ns) { const ::HANDLE handle = ::GetStdHandle(ns); switch (::GetFileType(handle)) { case FILE_TYPE_CHAR: { // A native console (DOS or PowerShell). return true; } case FILE_TYPE_PIPE: { // Check if associated file name matches Cygwin or Msys pty name. // With mintty, the standard devices are named pipes. With Cygwin, // the name starts with \cygwin. With Msys, the name starts with \msys. // Then, if the device is the mintty console, the name contains -pty. // For actual pipes, -pty is replaced by -pipe. const ts::UString name = ts::WinDeviceName(handle).toLower(); return (name.find(u"\\cygwin") != ts::NPOS || name.find(u"\\msys") != ts::NPOS) && name.find(u"-pty") != ts::NPOS; } default: { // Cannot be a terminal. return false; } } } } #endif bool ts::StdInIsTerminal() { #if defined(TS_WINDOWS) return StdHandleIsATerminal(STD_INPUT_HANDLE); #else return ::isatty(STDIN_FILENO); #endif } bool ts::StdOutIsTerminal() { #if defined(TS_WINDOWS) return StdHandleIsATerminal(STD_OUTPUT_HANDLE); #else return ::isatty(STDOUT_FILENO); #endif } bool ts::StdErrIsTerminal() { #if defined(TS_WINDOWS) return StdHandleIsATerminal(STD_ERROR_HANDLE); #else return ::isatty(STDERR_FILENO); #endif } //---------------------------------------------------------------------------- // Get the name of a class from the @c type_info of an object. //---------------------------------------------------------------------------- #if defined(TS_GCC) #include <cxxabi.h> #endif ts::UString ts::ClassName(const std::type_info& info) { UString name; const char* const rtti = info.name(); if (rtti != nullptr) { // By default, use the plain RTTI name. Not always a pretty name. name.assignFromUTF8(rtti); #if defined(TS_GCC) // With gcc and clang, this is a C++ mangled name. // Demangle it using the portable C++ ABI library. int status = 0; char* const demangled = abi::__cxa_demangle(rtti, nullptr, nullptr, &status); if (demangled != nullptr) { name.assignFromUTF8(demangled); ::free(demangled); } #endif // Cleanup various initial decoration, depending on compiler. if (name.startWith(u"class ")) { name.erase(0, 6); } // MSC: `anonymous namespace':: // GCC: (anonymous namespace):: if (name.find(u"anonymous namespace") == 1 && name.find(u"::") == 21) { name.erase(0, 23); } } return name; }
[ "thierry@lelegard.fr" ]
thierry@lelegard.fr
99532150b4454c47a2519d285ab4639b586cdd42
165bed04e37b33136ca693272e4b86f125840d09
/5658.cpp
a47eb31a10f03d55e30e41fc80d2b0358703fa4a
[]
no_license
kyu0901/SWExpertAcademy
bb9e22b0317039cb5cb0084baf2f4493929b290e
493e3b4b3c99f51dca544e1d35e2911d7e3da5e3
refs/heads/master
2020-05-04T17:06:26.470776
2019-04-05T11:43:14
2019-04-05T11:43:14
179,295,583
0
0
null
null
null
null
UHC
C++
false
false
1,817
cpp
//43개 맞음 #include <iostream> #include <vector> #include <algorithm> using namespace std; vector<char> v[4]; vector<long long> ans; int N , K; long long res; void To_Ten() { int cnt = N / 4; int a, k; for (int i = 0; i < 4; i++) { k = 0; for (int j = 0; j < cnt; j++) { if (v[i][j] >= 'A') a = v[i][j] - 'A' + 10; else a = v[i][j] - '0'; for (int k = j; k < cnt - 1; k++) { a *= 16; } k += a; } //cout << "값 : " << k << endl; //십진수를 집어넣기. ans.push_back(k); } } void Rot(int cnt) { if (cnt == N / 4) return; To_Ten(); char tmp; tmp = v[3][N / 4 - 1]; //cout << " Rot Start " << endl; for (int i = 3; 0 <= i; i--) { for (int j = N / 4 - 1; 0 < j; j--) { v[i][j] = v[i][j - 1]; } if(i>0) v[i][0] = v[i - 1][N / 4 - 1]; } v[0][0] = tmp; /* for (int i = 0; i < 4; i++) { for (int j = 0; j < 3; j++) { cout << v[i][j]; } cout << endl; } */ Rot(cnt + 1); } int main() { int T; char c; cin >> T; for (int tc = 1; tc <= T; tc++) { //초기화 ans.clear(); res = 0; for (int i = 0; i < 4; i++) { v[i].clear(); } cin >> N >> K; for (int i = 0; i < 4; i++) { for (int j = 0; j < N / 4; j++) { cin >> c; v[i].push_back(c); } } Rot(0); sort(ans.begin(), ans.end(), greater<int>()); int cnt = 1; for (int i = 0; i < ans.size()-1; i++) { if (cnt == K) { //cout << ans[i + 1] << endl; res = ans[i]; break; } if (ans[i] != ans[i + 1]){ //cout << ans[i] << endl; cnt++; } } if (res == 0) { res = ans[ans.size() - 1]; } cout << "#" << tc << ' ' << res << endl; } return 0; }
[ "noreply@github.com" ]
kyu0901.noreply@github.com
5259c6c15f1c9d57553be8c9535cb1e6c5e7a2f1
cf4659eacbd05ca334c5cd14b3e01d3128c74914
/src/Native/LdaNative/utils.hpp
7b71ec67da5881ec36aa9c46c593caa26a552c09
[ "MIT" ]
permissive
dotnet/machinelearning
86ae73e4ff43408307244681b8a78d287d7fb83b
d6927515d8014442d35ee22817ec7c40b9e7eec7
refs/heads/main
2023-09-03T19:56:28.278537
2023-09-02T04:06:55
2023-09-02T04:06:55
132,021,166
8,927
2,191
MIT
2023-09-13T17:12:31
2018-05-03T16:20:42
C#
UTF-8
C++
false
false
1,072
hpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #pragma once #define NOMINMAX #include <condition_variable> #include <deque> #include <atomic> #include <mutex> #include <list> namespace lda { double LogGamma(double xx); double get_time(); struct LDAEngineAtomics { LDAEngineAtomics() :doc_ll_(0), word_ll_(0), num_tokens_clock_(0), thread_counter_(0){} ~LDAEngineAtomics() {} std::atomic<double> doc_ll_; std::atomic<double> word_ll_; // # of tokens processed in a Clock() call. std::atomic<int> num_tokens_clock_; std::atomic<int> thread_counter_; std::mutex global_mutex_; }; class CBlockedIntQueue { public: void clear(); int pop(); void push(int value); private: std::mutex _mutex; std::condition_variable _condition; std::deque<int> _queue; }; }
[ "shauheen@users.noreply.github.com" ]
shauheen@users.noreply.github.com
19398f31d7e41d067532393ca851a1842437a5a6
a96c3be032187b3e23a47f1e893797616fb80a14
/Source/Encounters/Private/AI/BTTask_Guard.cpp
55bc66704397f1956b5d669001e0cb679b76088b
[]
no_license
lldvvbll/Encounters
0c7d9c90b5bbfc761038e1eea5ed0db10d760bfb
febbf3ab1f12bbee23877e3cdf6991fcd516d5f8
refs/heads/main
2023-04-13T06:16:50.603147
2021-04-11T14:19:47
2021-04-11T14:19:47
322,254,098
0
0
null
null
null
null
UTF-8
C++
false
false
530
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "AI/BTTask_Guard.h" #include "EncAIController.h" #include "Character/NpcCharacter.h" EBTNodeResult::Type UBTTask_Guard::ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory) { EBTNodeResult::Type Result = Super::ExecuteTask(OwnerComp, NodeMemory); auto Char = Cast<ANpcCharacter>(OwnerComp.GetAIOwner()->GetPawn()); if (Char == nullptr) return EBTNodeResult::Failed; Char->Guard(); return EBTNodeResult::Succeeded; }
[ "lldvvbll@nate.com" ]
lldvvbll@nate.com
051fb7a89077acfce9b348f22b8b4e293ba6ee6c
445caadc5c727df4b16a0b7bfbb713d408012bd2
/code/machine/interrupt.cc
4c1f593da5a12a47155d153e8a433b45cdadb103
[]
no_license
jamespeace/nachos
37506227f78cf0b0fe0ed1f4c11e711bfa8f6cf3
5a740473a88f0865aab9af8b28ce0ab29612346a
refs/heads/master
2020-06-02T07:54:34.388450
2019-06-19T14:01:23
2019-06-19T14:01:23
191,089,503
1
0
null
null
null
null
UTF-8
C++
false
false
11,609
cc
// interrupt.cc // Routines to simulate hardware interrupts. // // The hardware provides a routine (SetLevel) to enable or disable // interrupts. // // In order to emulate the hardware, we need to keep track of all // interrupts the hardware devices would cause, and when they // are supposed to occur. // // This module also keeps track of simulated time. Time advances // only when the following occur: // interrupts are re-enabled // a user instruction is executed // there is nothing in the ready queue // // DO NOT CHANGE -- part of the machine emulation // // Copyright (c) 1992-1996 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #include "interrupt.h" #include "main.h" #include "../userprog/synchconsole.h" // String definitions for debugging messages static char *intLevelNames[] = { "off", "on"}; static char *intTypeNames[] = { "timer", "disk", "console write", "console read", "elevator", "network send", "network recv"}; //---------------------------------------------------------------------- // PendingInterrupt::PendingInterrupt // Initialize a hardware device interrupt that is to be scheduled // to occur in the near future. // // "callOnInt" is the object to call when the interrupt occurs // "time" is when (in simulated time) the interrupt is to occur // "kind" is the hardware device that generated the interrupt //---------------------------------------------------------------------- PendingInterrupt::PendingInterrupt(CallBackObj *callOnInt, int time, IntType kind) { callOnInterrupt = callOnInt; when = time; type = kind; } //---------------------------------------------------------------------- // PendingCompare // Compare to interrupts based on which should occur first. //---------------------------------------------------------------------- static int PendingCompare (PendingInterrupt *x, PendingInterrupt *y) { if (x->when < y->when) { return -1; } else if (x->when > y->when) { return 1; } else { return 0; } } //---------------------------------------------------------------------- // Interrupt::Interrupt // Initialize the simulation of hardware device interrupts. // // Interrupts start disabled, with no interrupts pending, etc. //---------------------------------------------------------------------- Interrupt::Interrupt() { level = IntOff; pending = new SortedList<PendingInterrupt *>(PendingCompare); inHandler = FALSE; yieldOnReturn = FALSE; status = SystemMode; } //---------------------------------------------------------------------- // Interrupt::~Interrupt // De-allocate the data structures needed by the interrupt simulation. //---------------------------------------------------------------------- Interrupt::~Interrupt() { while (!pending->IsEmpty()) { delete pending->RemoveFront(); } delete pending; } //---------------------------------------------------------------------- // Interrupt::ChangeLevel // Change interrupts to be enabled or disabled, without advancing // the simulated time (normally, enabling interrupts advances the time). // // Used internally. // // "old" -- the old interrupt status // "now" -- the new interrupt status //---------------------------------------------------------------------- void Interrupt::ChangeLevel(IntStatus old, IntStatus now) { level = now; DEBUG(dbgInt, "\tinterrupts: " << intLevelNames[old] << " -> " << intLevelNames[now]); } //---------------------------------------------------------------------- // Interrupt::SetLevel // Change interrupts to be enabled or disabled, and if interrupts // are being enabled, advance simulated time by calling OneTick(). // // Returns: // The old interrupt status. // Parameters: // "now" -- the new interrupt status //---------------------------------------------------------------------- IntStatus Interrupt::SetLevel(IntStatus now) { IntStatus old = level; // interrupt handlers are prohibited from enabling interrupts ASSERT((now == IntOff) || (inHandler == FALSE)); ChangeLevel(old, now); // change to new state if ((now == IntOn) && (old == IntOff)) { OneTick(); // advance simulated time } return old; } //---------------------------------------------------------------------- // Interrupt::OneTick // Advance simulated time and check if there are any pending // interrupts to be called. // // Two things can cause OneTick to be called: // interrupts are re-enabled // a user instruction is executed //---------------------------------------------------------------------- void Interrupt::OneTick() { MachineStatus oldStatus = status; Statistics *stats = kernel->stats; // advance simulated time if (status == SystemMode) { stats->totalTicks += SystemTick; stats->systemTicks += SystemTick; } else { // USER_PROGRAM stats->totalTicks += UserTick; stats->userTicks += UserTick; } DEBUG(dbgInt, "== Tick " << stats->totalTicks << " =="); // check any pending interrupts are now ready to fire ChangeLevel(IntOn, IntOff); // first, turn off interrupts // (interrupt handlers run with // interrupts disabled) CheckIfDue(FALSE); // check for pending interrupts ChangeLevel(IntOff, IntOn); // re-enable interrupts if (yieldOnReturn) { // if the timer device handler asked // for a context switch, ok to do it now yieldOnReturn = FALSE; status = SystemMode; // yield is a kernel routine kernel->currentThread->Yield(); status = oldStatus; } } //---------------------------------------------------------------------- // Interrupt::YieldOnReturn // Called from within an interrupt handler, to cause a context switch // (for example, on a time slice) in the interrupted thread, // when the handler returns. // // We can't do the context switch here, because that would switch // out the interrupt handler, and we want to switch out the // interrupted thread. //---------------------------------------------------------------------- void Interrupt::YieldOnReturn() { ASSERT(inHandler == TRUE); yieldOnReturn = TRUE; } //---------------------------------------------------------------------- // Interrupt::Idle // Routine called when there is nothing in the ready queue. // // Since something has to be running in order to put a thread // on the ready queue, the only thing to do is to advance // simulated time until the next scheduled hardware interrupt. // // If there are no pending interrupts, stop. There's nothing // more for us to do. //---------------------------------------------------------------------- void Interrupt::Idle() { DEBUG(dbgInt, "Machine idling; checking for interrupts."); status = IdleMode; if (CheckIfDue(TRUE)) { // check for any pending interrupts status = SystemMode; return; // return in case there's now // a runnable thread } // if there are no pending interrupts, and nothing is on the ready // queue, it is time to stop. If the console or the network is // operating, there are *always* pending interrupts, so this code // is not reached. Instead, the halt must be invoked by the user program. DEBUG(dbgInt, "Machine idle. No interrupts to do."); cout << "No threads ready or runnable, and no pending interrupts.\n"; cout << "Assuming the program completed.\n"; Halt(); } //---------------------------------------------------------------------- // Interrupt::Halt // Shut down Nachos cleanly, printing out performance statistics. //---------------------------------------------------------------------- void Interrupt::Halt() { cout << "Machine halting!\n\n"; kernel->stats->Print(); delete kernel; // Never returns. } //---------------------------------------------------------------------- // Interrupt::Schedule // Arrange for the CPU to be interrupted when simulated time // reaches "now + when". // // Implementation: just put it on a sorted list. // // NOTE: the Nachos kernel should not call this routine directly. // Instead, it is only called by the hardware device simulators. // // "toCall" is the object to call when the interrupt occurs // "fromNow" is how far in the future (in simulated time) the // interrupt is to occur // "type" is the hardware device that generated the interrupt //---------------------------------------------------------------------- void Interrupt::Schedule(CallBackObj *toCall, int fromNow, IntType type) { int when = kernel->stats->totalTicks + fromNow; PendingInterrupt *toOccur = new PendingInterrupt(toCall, when, type); DEBUG(dbgInt, "Scheduling interrupt handler the " << intTypeNames[type] << " at time = " << when); ASSERT(fromNow > 0); pending->Insert(toOccur); } //---------------------------------------------------------------------- // Interrupt::CheckIfDue // Check if any interrupts are scheduled to occur, and if so, // fire them off. // // Returns: // TRUE, if we fired off any interrupt handlers // Params: // "advanceClock" -- if TRUE, there is nothing in the ready queue, // so we should simply advance the clock to when the next // pending interrupt would occur (if any). //---------------------------------------------------------------------- bool Interrupt::CheckIfDue(bool advanceClock) { PendingInterrupt *next; Statistics *stats = kernel->stats; ASSERT(level == IntOff); // interrupts need to be disabled, // to invoke an interrupt handler if (debug->IsEnabled(dbgInt)) { DumpState(); } if (pending->IsEmpty()) { // no pending interrupts return FALSE; } next = pending->Front(); if (next->when > stats->totalTicks) { if (!advanceClock) { // not time yet return FALSE; } else { // advance the clock to next interrupt stats->idleTicks += (next->when - stats->totalTicks); stats->totalTicks = next->when; } } DEBUG(dbgInt, "Invoking interrupt handler for the "); DEBUG(dbgInt, intTypeNames[next->type] << " at time " << next->when); #ifdef USER_PROGRAM if (kernel->machine != NULL) { kernel->machine->DelayedLoad(0, 0); } #endif inHandler = TRUE; do { next = pending->RemoveFront(); // pull interrupt off list next->callOnInterrupt->CallBack();// call the interrupt handler delete next; } while (!pending->IsEmpty() && (pending->Front()->when <= stats->totalTicks)); inHandler = FALSE; return TRUE; } //---------------------------------------------------------------------- // PrintPending // Print information about an interrupt that is scheduled to occur. // When, where, why, etc. //---------------------------------------------------------------------- static void PrintPending (PendingInterrupt *pending) { cout << "Interrupt handler "<< intTypeNames[pending->type]; cout << ", scheduled at " << pending->when; } //---------------------------------------------------------------------- // DumpState // Print the complete interrupt state - the status, and all interrupts // that are scheduled to occur in the future. //---------------------------------------------------------------------- void Interrupt::DumpState() { cout << "Time: " << kernel->stats->totalTicks; cout << ", interrupts " << intLevelNames[level] << "\n"; cout << "Pending interrupts:\n"; pending->Apply(PrintPending); cout << "\nEnd of pending interrupts\n"; }
[ "james.happylove@gmail.com" ]
james.happylove@gmail.com
1338ce97ba512d277f23cb5b5f42a916af00117b
eba2fadea4972b682edce710300ea280a210eee2
/leetcode/c++/1110.DeleteNodesAndReturnForest.cc
bcbd61b9cce2a3beff7c09a7e6a8905b38e15315
[]
no_license
seesealonely/leetcode
33b876968f08a0ddd00adc714d03ad6e4c0bfae9
1a371f3ad438bb70bf7a685843097535f5fc1c5d
refs/heads/master
2023-08-30T21:22:07.456531
2023-08-30T20:15:49
2023-08-30T20:15:49
87,525,147
1
0
null
null
null
null
UTF-8
C++
false
false
814
cc
/* Given the root of a binary tree, each node in the tree has a distinct value. After deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees). Return the roots of the trees in the remaining forest. You may return the result in any order. Example 1: Input: root = [1,2,3,4,5,6,7], to_delete = [3,5] Output: [[1,2,null,4],[6],[7]] Example 2: Input: root = [1,2,4,null,3], to_delete = [3] Output: [[1,2,4]] Constraints: The number of nodes in the given tree is at most 1000. Each node has a distinct value between 1 and 1000. to_delete.length <= 1000 to_delete contains distinct values between 1 and 1000. */ #include"1110.DeleteNodesAndReturnForest.h" int main() { Solution s; vector<int> v={3,5}; show(s.delNodes(buildTree(),v)); return 0; }
[ "seesealonely@gmail.com" ]
seesealonely@gmail.com
a61671589ff0838b6851ae6bacfaaa7929370ac3
53a430e12ef6f7565bca8fa1d0b944b9b734a6f0
/ex08/tree.cpp
85e1a54f222e603a5270b51e23cd0ef4cad048f0
[]
no_license
fmi-lab/fmi-lab-sdp-2019-kn-group2-sem
226a68f839b51c4d2ee945ea0f8f3fad7eef9a8f
978a806ce270a4ae07e9d3a7502d3cb11abddc15
refs/heads/master
2020-08-06T00:05:13.672204
2020-01-24T10:29:26
2020-01-24T10:29:26
212,764,777
1
1
null
null
null
null
UTF-8
C++
false
false
3,084
cpp
#include <iostream> using namespace std; template <class T> struct node { T data; node<T> * left; node<T> * right; }; node<int>* createTree( int data, node<int>* left = NULL, node<int>* right = NULL) { node<int>* root = new node<int>; root->data = data; root->left = left; root->right = right; return root; } template<class T> void deleteTree(node<T> * tree) { } node<int>* createSample() { return createTree(5, createTree(3, createTree(2, createTree(1), NULL), createTree(4)), createTree(10, createTree(7, createTree(6), NULL), createTree(15, NULL, createTree(17, NULL, createTree(20))))); } node<int>* createSampleBalanced() { return createTree(5, createTree(3, createTree(2, createTree(1), NULL), createTree(4)), createTree(10, createTree(7, createTree(6), NULL), createTree(15, NULL, createTree(17, NULL, NULL)))); } template <class T> node<T>* findElement(node<T>* tree, T element) { if (NULL == tree) { return NULL; } if (tree->data == element) { return tree; } else if (tree->data > element) { return findElement(tree->left, element); } else { return findElement(tree->right, element); } } void testFindElement() { node<int>* myTree = createSample(); cout << "Find 20: " << findElement(myTree, 20) << endl; cout << "Find -5: " << findElement(myTree, -5) << endl; deleteTree(myTree); } int sumLeafs(node<int> * tree) { if (NULL == tree) { return 0; } if (NULL == tree->left && NULL == tree->right) { return tree->data; } return sumLeafs(tree->left) + sumLeafs(tree->right); } void testSumLeafs() { node<int> * myTree = createSample(); cout << "31 == " << sumLeafs(myTree) << endl; deleteTree(myTree); } int sumLeafsByHeight(node<int> * tree, int height = 1) { if (NULL == tree) { return 0; } if (NULL == tree->left && NULL == tree->right) { return tree->data * height; } return sumLeafsByHeight(tree->left, height + 1) + sumLeafsByHeight(tree->right, height + 1); } void testSumLeafsByHeight() { node<int> * myTree = createSample(); cout << "140 == " << sumLeafsByHeight(myTree) << endl; deleteTree(myTree); } template <class T> int height(node<T> * tree) { if (NULL == tree) { return 0; } return 1 + max(height(tree->left), height(tree->right)); } template <class T> bool isAVLBalanced(node<T> * tree) { if (NULL == tree) { return true; } int balanceFactor = height(tree->left) - height(tree->right); if (-1 <= balanceFactor && balanceFactor <= 1) { return isAVLBalanced(tree->left) && isAVLBalanced(tree->right); } else { return false; } } void testAVLBalannced() { node<int> * unbalancedTree = createSample(); node<int> * balancedTree = createSampleBalanced(); cout << "false == " << isAVLBalanced(unbalancedTree) << endl; cout << "true == " << isAVLBalanced(balancedTree) << endl; } int main() { // testFindElement(); // testSumLeafs(); // testSumLeafsByHeight(); testAVLBalannced(); return 0; }
[ "stef.vartolomeev@gmail.com" ]
stef.vartolomeev@gmail.com
703dabe3b3940a6d10a423a765845796cba5e362
c776476e9d06b3779d744641e758ac3a2c15cddc
/examples/litmus/c/run-scripts/tmp_1/ISA2+po+ctrlisb+dmb.sy.c.cbmc.cpp
18b726f6293a03add68fe139a319d6569f4e27b7
[]
no_license
ashutosh0gupta/llvm_bmc
aaac7961c723ba6f7ffd77a39559e0e52432eade
0287c4fb180244e6b3c599a9902507f05c8a7234
refs/heads/master
2023-08-02T17:14:06.178723
2023-07-31T10:46:53
2023-07-31T10:46:53
143,100,825
3
4
null
2023-05-25T05:50:55
2018-08-01T03:47:00
C++
UTF-8
C++
false
false
43,422
cpp
// 0:vars:3 // 7:thr1:1 // 8:thr2:1 // 3:atom_1_X0_1:1 // 4:atom_2_X0_1:1 // 5:atom_2_X2_0:1 // 6:thr0:1 #define ADDRSIZE 9 #define NPROC 4 #define NCONTEXT 1 #define ASSUME(stmt) __CPROVER_assume(stmt) #define ASSERT(stmt) __CPROVER_assert(stmt, "error") #define max(a,b) (a>b?a:b) char __get_rng(); char get_rng( char from, char to ) { char ret = __get_rng(); ASSUME(ret >= from && ret <= to); return ret; } char get_rng_th( char from, char to ) { char ret = __get_rng(); ASSUME(ret >= from && ret <= to); return ret; } int main(int argc, char **argv) { // declare arrays for intial value version in contexts int meminit_[ADDRSIZE*NCONTEXT]; #define meminit(x,k) meminit_[(x)*NCONTEXT+k] int coinit_[ADDRSIZE*NCONTEXT]; #define coinit(x,k) coinit_[(x)*NCONTEXT+k] int deltainit_[ADDRSIZE*NCONTEXT]; #define deltainit(x,k) deltainit_[(x)*NCONTEXT+k] // declare arrays for running value version in contexts int mem_[ADDRSIZE*NCONTEXT]; #define mem(x,k) mem_[(x)*NCONTEXT+k] int co_[ADDRSIZE*NCONTEXT]; #define co(x,k) co_[(x)*NCONTEXT+k] int delta_[ADDRSIZE*NCONTEXT]; #define delta(x,k) delta_[(x)*NCONTEXT+k] // declare arrays for local buffer and observed writes int buff_[NPROC*ADDRSIZE]; #define buff(x,k) buff_[(x)*ADDRSIZE+k] int pw_[NPROC*ADDRSIZE]; #define pw(x,k) pw_[(x)*ADDRSIZE+k] // declare arrays for context stamps char cr_[NPROC*ADDRSIZE]; #define cr(x,k) cr_[(x)*ADDRSIZE+k] char iw_[NPROC*ADDRSIZE]; #define iw(x,k) iw_[(x)*ADDRSIZE+k] char cw_[NPROC*ADDRSIZE]; #define cw(x,k) cw_[(x)*ADDRSIZE+k] char cx_[NPROC*ADDRSIZE]; #define cx(x,k) cx_[(x)*ADDRSIZE+k] char is_[NPROC*ADDRSIZE]; #define is(x,k) is_[(x)*ADDRSIZE+k] char cs_[NPROC*ADDRSIZE]; #define cs(x,k) cs_[(x)*ADDRSIZE+k] char crmax_[NPROC*ADDRSIZE]; #define crmax(x,k) crmax_[(x)*ADDRSIZE+k] char sforbid_[ADDRSIZE*NCONTEXT]; #define sforbid(x,k) sforbid_[(x)*NCONTEXT+k] // declare arrays for synchronizations int cl[NPROC]; int cdy[NPROC]; int cds[NPROC]; int cdl[NPROC]; int cisb[NPROC]; int caddr[NPROC]; int cctrl[NPROC]; int cstart[NPROC]; int creturn[NPROC]; // declare arrays for contexts activity int active[NCONTEXT]; int ctx_used[NCONTEXT]; __LOCALS__ buff(0,0) = 0; pw(0,0) = 0; cr(0,0) = 0; iw(0,0) = 0; cw(0,0) = 0; cx(0,0) = 0; is(0,0) = 0; cs(0,0) = 0; crmax(0,0) = 0; buff(0,1) = 0; pw(0,1) = 0; cr(0,1) = 0; iw(0,1) = 0; cw(0,1) = 0; cx(0,1) = 0; is(0,1) = 0; cs(0,1) = 0; crmax(0,1) = 0; buff(0,2) = 0; pw(0,2) = 0; cr(0,2) = 0; iw(0,2) = 0; cw(0,2) = 0; cx(0,2) = 0; is(0,2) = 0; cs(0,2) = 0; crmax(0,2) = 0; buff(0,3) = 0; pw(0,3) = 0; cr(0,3) = 0; iw(0,3) = 0; cw(0,3) = 0; cx(0,3) = 0; is(0,3) = 0; cs(0,3) = 0; crmax(0,3) = 0; buff(0,4) = 0; pw(0,4) = 0; cr(0,4) = 0; iw(0,4) = 0; cw(0,4) = 0; cx(0,4) = 0; is(0,4) = 0; cs(0,4) = 0; crmax(0,4) = 0; buff(0,5) = 0; pw(0,5) = 0; cr(0,5) = 0; iw(0,5) = 0; cw(0,5) = 0; cx(0,5) = 0; is(0,5) = 0; cs(0,5) = 0; crmax(0,5) = 0; buff(0,6) = 0; pw(0,6) = 0; cr(0,6) = 0; iw(0,6) = 0; cw(0,6) = 0; cx(0,6) = 0; is(0,6) = 0; cs(0,6) = 0; crmax(0,6) = 0; buff(0,7) = 0; pw(0,7) = 0; cr(0,7) = 0; iw(0,7) = 0; cw(0,7) = 0; cx(0,7) = 0; is(0,7) = 0; cs(0,7) = 0; crmax(0,7) = 0; buff(0,8) = 0; pw(0,8) = 0; cr(0,8) = 0; iw(0,8) = 0; cw(0,8) = 0; cx(0,8) = 0; is(0,8) = 0; cs(0,8) = 0; crmax(0,8) = 0; cl[0] = 0; cdy[0] = 0; cds[0] = 0; cdl[0] = 0; cisb[0] = 0; caddr[0] = 0; cctrl[0] = 0; cstart[0] = get_rng(0,NCONTEXT-1); creturn[0] = get_rng(0,NCONTEXT-1); buff(1,0) = 0; pw(1,0) = 0; cr(1,0) = 0; iw(1,0) = 0; cw(1,0) = 0; cx(1,0) = 0; is(1,0) = 0; cs(1,0) = 0; crmax(1,0) = 0; buff(1,1) = 0; pw(1,1) = 0; cr(1,1) = 0; iw(1,1) = 0; cw(1,1) = 0; cx(1,1) = 0; is(1,1) = 0; cs(1,1) = 0; crmax(1,1) = 0; buff(1,2) = 0; pw(1,2) = 0; cr(1,2) = 0; iw(1,2) = 0; cw(1,2) = 0; cx(1,2) = 0; is(1,2) = 0; cs(1,2) = 0; crmax(1,2) = 0; buff(1,3) = 0; pw(1,3) = 0; cr(1,3) = 0; iw(1,3) = 0; cw(1,3) = 0; cx(1,3) = 0; is(1,3) = 0; cs(1,3) = 0; crmax(1,3) = 0; buff(1,4) = 0; pw(1,4) = 0; cr(1,4) = 0; iw(1,4) = 0; cw(1,4) = 0; cx(1,4) = 0; is(1,4) = 0; cs(1,4) = 0; crmax(1,4) = 0; buff(1,5) = 0; pw(1,5) = 0; cr(1,5) = 0; iw(1,5) = 0; cw(1,5) = 0; cx(1,5) = 0; is(1,5) = 0; cs(1,5) = 0; crmax(1,5) = 0; buff(1,6) = 0; pw(1,6) = 0; cr(1,6) = 0; iw(1,6) = 0; cw(1,6) = 0; cx(1,6) = 0; is(1,6) = 0; cs(1,6) = 0; crmax(1,6) = 0; buff(1,7) = 0; pw(1,7) = 0; cr(1,7) = 0; iw(1,7) = 0; cw(1,7) = 0; cx(1,7) = 0; is(1,7) = 0; cs(1,7) = 0; crmax(1,7) = 0; buff(1,8) = 0; pw(1,8) = 0; cr(1,8) = 0; iw(1,8) = 0; cw(1,8) = 0; cx(1,8) = 0; is(1,8) = 0; cs(1,8) = 0; crmax(1,8) = 0; cl[1] = 0; cdy[1] = 0; cds[1] = 0; cdl[1] = 0; cisb[1] = 0; caddr[1] = 0; cctrl[1] = 0; cstart[1] = get_rng(0,NCONTEXT-1); creturn[1] = get_rng(0,NCONTEXT-1); buff(2,0) = 0; pw(2,0) = 0; cr(2,0) = 0; iw(2,0) = 0; cw(2,0) = 0; cx(2,0) = 0; is(2,0) = 0; cs(2,0) = 0; crmax(2,0) = 0; buff(2,1) = 0; pw(2,1) = 0; cr(2,1) = 0; iw(2,1) = 0; cw(2,1) = 0; cx(2,1) = 0; is(2,1) = 0; cs(2,1) = 0; crmax(2,1) = 0; buff(2,2) = 0; pw(2,2) = 0; cr(2,2) = 0; iw(2,2) = 0; cw(2,2) = 0; cx(2,2) = 0; is(2,2) = 0; cs(2,2) = 0; crmax(2,2) = 0; buff(2,3) = 0; pw(2,3) = 0; cr(2,3) = 0; iw(2,3) = 0; cw(2,3) = 0; cx(2,3) = 0; is(2,3) = 0; cs(2,3) = 0; crmax(2,3) = 0; buff(2,4) = 0; pw(2,4) = 0; cr(2,4) = 0; iw(2,4) = 0; cw(2,4) = 0; cx(2,4) = 0; is(2,4) = 0; cs(2,4) = 0; crmax(2,4) = 0; buff(2,5) = 0; pw(2,5) = 0; cr(2,5) = 0; iw(2,5) = 0; cw(2,5) = 0; cx(2,5) = 0; is(2,5) = 0; cs(2,5) = 0; crmax(2,5) = 0; buff(2,6) = 0; pw(2,6) = 0; cr(2,6) = 0; iw(2,6) = 0; cw(2,6) = 0; cx(2,6) = 0; is(2,6) = 0; cs(2,6) = 0; crmax(2,6) = 0; buff(2,7) = 0; pw(2,7) = 0; cr(2,7) = 0; iw(2,7) = 0; cw(2,7) = 0; cx(2,7) = 0; is(2,7) = 0; cs(2,7) = 0; crmax(2,7) = 0; buff(2,8) = 0; pw(2,8) = 0; cr(2,8) = 0; iw(2,8) = 0; cw(2,8) = 0; cx(2,8) = 0; is(2,8) = 0; cs(2,8) = 0; crmax(2,8) = 0; cl[2] = 0; cdy[2] = 0; cds[2] = 0; cdl[2] = 0; cisb[2] = 0; caddr[2] = 0; cctrl[2] = 0; cstart[2] = get_rng(0,NCONTEXT-1); creturn[2] = get_rng(0,NCONTEXT-1); buff(3,0) = 0; pw(3,0) = 0; cr(3,0) = 0; iw(3,0) = 0; cw(3,0) = 0; cx(3,0) = 0; is(3,0) = 0; cs(3,0) = 0; crmax(3,0) = 0; buff(3,1) = 0; pw(3,1) = 0; cr(3,1) = 0; iw(3,1) = 0; cw(3,1) = 0; cx(3,1) = 0; is(3,1) = 0; cs(3,1) = 0; crmax(3,1) = 0; buff(3,2) = 0; pw(3,2) = 0; cr(3,2) = 0; iw(3,2) = 0; cw(3,2) = 0; cx(3,2) = 0; is(3,2) = 0; cs(3,2) = 0; crmax(3,2) = 0; buff(3,3) = 0; pw(3,3) = 0; cr(3,3) = 0; iw(3,3) = 0; cw(3,3) = 0; cx(3,3) = 0; is(3,3) = 0; cs(3,3) = 0; crmax(3,3) = 0; buff(3,4) = 0; pw(3,4) = 0; cr(3,4) = 0; iw(3,4) = 0; cw(3,4) = 0; cx(3,4) = 0; is(3,4) = 0; cs(3,4) = 0; crmax(3,4) = 0; buff(3,5) = 0; pw(3,5) = 0; cr(3,5) = 0; iw(3,5) = 0; cw(3,5) = 0; cx(3,5) = 0; is(3,5) = 0; cs(3,5) = 0; crmax(3,5) = 0; buff(3,6) = 0; pw(3,6) = 0; cr(3,6) = 0; iw(3,6) = 0; cw(3,6) = 0; cx(3,6) = 0; is(3,6) = 0; cs(3,6) = 0; crmax(3,6) = 0; buff(3,7) = 0; pw(3,7) = 0; cr(3,7) = 0; iw(3,7) = 0; cw(3,7) = 0; cx(3,7) = 0; is(3,7) = 0; cs(3,7) = 0; crmax(3,7) = 0; buff(3,8) = 0; pw(3,8) = 0; cr(3,8) = 0; iw(3,8) = 0; cw(3,8) = 0; cx(3,8) = 0; is(3,8) = 0; cs(3,8) = 0; crmax(3,8) = 0; cl[3] = 0; cdy[3] = 0; cds[3] = 0; cdl[3] = 0; cisb[3] = 0; caddr[3] = 0; cctrl[3] = 0; cstart[3] = get_rng(0,NCONTEXT-1); creturn[3] = get_rng(0,NCONTEXT-1); // Dumping initializations mem(0+0,0) = 0; mem(0+1,0) = 0; mem(0+2,0) = 0; mem(7+0,0) = 0; mem(8+0,0) = 0; mem(3+0,0) = 0; mem(4+0,0) = 0; mem(5+0,0) = 0; mem(6+0,0) = 0; // Dumping context matching equalities co(0,0) = 0; delta(0,0) = -1; co(1,0) = 0; delta(1,0) = -1; co(2,0) = 0; delta(2,0) = -1; co(3,0) = 0; delta(3,0) = -1; co(4,0) = 0; delta(4,0) = -1; co(5,0) = 0; delta(5,0) = -1; co(6,0) = 0; delta(6,0) = -1; co(7,0) = 0; delta(7,0) = -1; co(8,0) = 0; delta(8,0) = -1; // Dumping thread 1 int ret_thread_1 = 0; cdy[1] = get_rng(0,NCONTEXT-1); ASSUME(cdy[1] >= cstart[1]); T1BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !37, metadata !DIExpression()), !dbg !46 // br label %label_1, !dbg !47 goto T1BLOCK1; T1BLOCK1: // call void @llvm.dbg.label(metadata !45), !dbg !48 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !38, metadata !DIExpression()), !dbg !49 // call void @llvm.dbg.value(metadata i64 1, metadata !41, metadata !DIExpression()), !dbg !49 // store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !50 // ST: Guess iw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW old_cw = cw(1,0); cw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM // Check ASSUME(active[iw(1,0)] == 1); ASSUME(active[cw(1,0)] == 1); ASSUME(sforbid(0,cw(1,0))== 0); ASSUME(iw(1,0) >= 0); ASSUME(iw(1,0) >= 0); ASSUME(cw(1,0) >= iw(1,0)); ASSUME(cw(1,0) >= old_cw); ASSUME(cw(1,0) >= cr(1,0)); ASSUME(cw(1,0) >= cl[1]); ASSUME(cw(1,0) >= cisb[1]); ASSUME(cw(1,0) >= cdy[1]); ASSUME(cw(1,0) >= cdl[1]); ASSUME(cw(1,0) >= cds[1]); ASSUME(cw(1,0) >= cctrl[1]); ASSUME(cw(1,0) >= caddr[1]); // Update caddr[1] = max(caddr[1],0); buff(1,0) = 1; mem(0,cw(1,0)) = 1; co(0,cw(1,0))+=1; delta(0,cw(1,0)) = -1; ASSUME(creturn[1] >= cw(1,0)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !42, metadata !DIExpression()), !dbg !51 // call void @llvm.dbg.value(metadata i64 1, metadata !44, metadata !DIExpression()), !dbg !51 // store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !52 // ST: Guess iw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW old_cw = cw(1,0+1*1); cw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM // Check ASSUME(active[iw(1,0+1*1)] == 1); ASSUME(active[cw(1,0+1*1)] == 1); ASSUME(sforbid(0+1*1,cw(1,0+1*1))== 0); ASSUME(iw(1,0+1*1) >= 0); ASSUME(iw(1,0+1*1) >= 0); ASSUME(cw(1,0+1*1) >= iw(1,0+1*1)); ASSUME(cw(1,0+1*1) >= old_cw); ASSUME(cw(1,0+1*1) >= cr(1,0+1*1)); ASSUME(cw(1,0+1*1) >= cl[1]); ASSUME(cw(1,0+1*1) >= cisb[1]); ASSUME(cw(1,0+1*1) >= cdy[1]); ASSUME(cw(1,0+1*1) >= cdl[1]); ASSUME(cw(1,0+1*1) >= cds[1]); ASSUME(cw(1,0+1*1) >= cctrl[1]); ASSUME(cw(1,0+1*1) >= caddr[1]); // Update caddr[1] = max(caddr[1],0); buff(1,0+1*1) = 1; mem(0+1*1,cw(1,0+1*1)) = 1; co(0+1*1,cw(1,0+1*1))+=1; delta(0+1*1,cw(1,0+1*1)) = -1; ASSUME(creturn[1] >= cw(1,0+1*1)); // ret i8* null, !dbg !53 ret_thread_1 = (- 1); // Dumping thread 2 int ret_thread_2 = 0; cdy[2] = get_rng(0,NCONTEXT-1); ASSUME(cdy[2] >= cstart[2]); T2BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !56, metadata !DIExpression()), !dbg !71 // br label %label_2, !dbg !54 goto T2BLOCK1; T2BLOCK1: // call void @llvm.dbg.label(metadata !69), !dbg !73 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !59, metadata !DIExpression()), !dbg !74 // %0 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !57 // LD: Guess old_cr = cr(2,0+1*1); cr(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM // Check ASSUME(active[cr(2,0+1*1)] == 2); ASSUME(cr(2,0+1*1) >= iw(2,0+1*1)); ASSUME(cr(2,0+1*1) >= 0); ASSUME(cr(2,0+1*1) >= cdy[2]); ASSUME(cr(2,0+1*1) >= cisb[2]); ASSUME(cr(2,0+1*1) >= cdl[2]); ASSUME(cr(2,0+1*1) >= cl[2]); // Update creg_r0 = cr(2,0+1*1); crmax(2,0+1*1) = max(crmax(2,0+1*1),cr(2,0+1*1)); caddr[2] = max(caddr[2],0); if(cr(2,0+1*1) < cw(2,0+1*1)) { r0 = buff(2,0+1*1); } else { if(pw(2,0+1*1) != co(0+1*1,cr(2,0+1*1))) { ASSUME(cr(2,0+1*1) >= old_cr); } pw(2,0+1*1) = co(0+1*1,cr(2,0+1*1)); r0 = mem(0+1*1,cr(2,0+1*1)); } ASSUME(creturn[2] >= cr(2,0+1*1)); // call void @llvm.dbg.value(metadata i64 %0, metadata !61, metadata !DIExpression()), !dbg !74 // %conv = trunc i64 %0 to i32, !dbg !58 // call void @llvm.dbg.value(metadata i32 %conv, metadata !57, metadata !DIExpression()), !dbg !71 // %tobool = icmp ne i32 %conv, 0, !dbg !59 // br i1 %tobool, label %if.then, label %if.else, !dbg !61 old_cctrl = cctrl[2]; cctrl[2] = get_rng(0,NCONTEXT-1); ASSUME(cctrl[2] >= old_cctrl); ASSUME(cctrl[2] >= creg_r0); ASSUME(cctrl[2] >= 0); if((r0!=0)) { goto T2BLOCK2; } else { goto T2BLOCK3; } T2BLOCK2: // br label %lbl_LC00, !dbg !62 goto T2BLOCK4; T2BLOCK3: // br label %lbl_LC00, !dbg !63 goto T2BLOCK4; T2BLOCK4: // call void @llvm.dbg.label(metadata !70), !dbg !82 // call void (...) @isb(), !dbg !65 // isb: Guess cisb[2] = get_rng(0,NCONTEXT-1); // Check ASSUME(cisb[2] >= cdy[2]); ASSUME(cisb[2] >= cctrl[2]); ASSUME(cisb[2] >= caddr[2]); ASSUME(creturn[2] >= cisb[2]); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !62, metadata !DIExpression()), !dbg !84 // call void @llvm.dbg.value(metadata i64 1, metadata !64, metadata !DIExpression()), !dbg !84 // store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !67 // ST: Guess iw(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW old_cw = cw(2,0+2*1); cw(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM // Check ASSUME(active[iw(2,0+2*1)] == 2); ASSUME(active[cw(2,0+2*1)] == 2); ASSUME(sforbid(0+2*1,cw(2,0+2*1))== 0); ASSUME(iw(2,0+2*1) >= 0); ASSUME(iw(2,0+2*1) >= 0); ASSUME(cw(2,0+2*1) >= iw(2,0+2*1)); ASSUME(cw(2,0+2*1) >= old_cw); ASSUME(cw(2,0+2*1) >= cr(2,0+2*1)); ASSUME(cw(2,0+2*1) >= cl[2]); ASSUME(cw(2,0+2*1) >= cisb[2]); ASSUME(cw(2,0+2*1) >= cdy[2]); ASSUME(cw(2,0+2*1) >= cdl[2]); ASSUME(cw(2,0+2*1) >= cds[2]); ASSUME(cw(2,0+2*1) >= cctrl[2]); ASSUME(cw(2,0+2*1) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,0+2*1) = 1; mem(0+2*1,cw(2,0+2*1)) = 1; co(0+2*1,cw(2,0+2*1))+=1; delta(0+2*1,cw(2,0+2*1)) = -1; ASSUME(creturn[2] >= cw(2,0+2*1)); // %cmp = icmp eq i32 %conv, 1, !dbg !68 // %conv1 = zext i1 %cmp to i32, !dbg !68 // call void @llvm.dbg.value(metadata i32 %conv1, metadata !65, metadata !DIExpression()), !dbg !71 // call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !66, metadata !DIExpression()), !dbg !87 // %1 = zext i32 %conv1 to i64 // call void @llvm.dbg.value(metadata i64 %1, metadata !68, metadata !DIExpression()), !dbg !87 // store atomic i64 %1, i64* @atom_1_X0_1 seq_cst, align 8, !dbg !70 // ST: Guess iw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW old_cw = cw(2,3); cw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM // Check ASSUME(active[iw(2,3)] == 2); ASSUME(active[cw(2,3)] == 2); ASSUME(sforbid(3,cw(2,3))== 0); ASSUME(iw(2,3) >= max(creg_r0,0)); ASSUME(iw(2,3) >= 0); ASSUME(cw(2,3) >= iw(2,3)); ASSUME(cw(2,3) >= old_cw); ASSUME(cw(2,3) >= cr(2,3)); ASSUME(cw(2,3) >= cl[2]); ASSUME(cw(2,3) >= cisb[2]); ASSUME(cw(2,3) >= cdy[2]); ASSUME(cw(2,3) >= cdl[2]); ASSUME(cw(2,3) >= cds[2]); ASSUME(cw(2,3) >= cctrl[2]); ASSUME(cw(2,3) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,3) = (r0==1); mem(3,cw(2,3)) = (r0==1); co(3,cw(2,3))+=1; delta(3,cw(2,3)) = -1; ASSUME(creturn[2] >= cw(2,3)); // ret i8* null, !dbg !71 ret_thread_2 = (- 1); // Dumping thread 3 int ret_thread_3 = 0; cdy[3] = get_rng(0,NCONTEXT-1); ASSUME(cdy[3] >= cstart[3]); T3BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !92, metadata !DIExpression()), !dbg !110 // br label %label_3, !dbg !58 goto T3BLOCK1; T3BLOCK1: // call void @llvm.dbg.label(metadata !109), !dbg !112 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !94, metadata !DIExpression()), !dbg !113 // %0 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !61 // LD: Guess old_cr = cr(3,0+2*1); cr(3,0+2*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN LDCOM // Check ASSUME(active[cr(3,0+2*1)] == 3); ASSUME(cr(3,0+2*1) >= iw(3,0+2*1)); ASSUME(cr(3,0+2*1) >= 0); ASSUME(cr(3,0+2*1) >= cdy[3]); ASSUME(cr(3,0+2*1) >= cisb[3]); ASSUME(cr(3,0+2*1) >= cdl[3]); ASSUME(cr(3,0+2*1) >= cl[3]); // Update creg_r1 = cr(3,0+2*1); crmax(3,0+2*1) = max(crmax(3,0+2*1),cr(3,0+2*1)); caddr[3] = max(caddr[3],0); if(cr(3,0+2*1) < cw(3,0+2*1)) { r1 = buff(3,0+2*1); } else { if(pw(3,0+2*1) != co(0+2*1,cr(3,0+2*1))) { ASSUME(cr(3,0+2*1) >= old_cr); } pw(3,0+2*1) = co(0+2*1,cr(3,0+2*1)); r1 = mem(0+2*1,cr(3,0+2*1)); } ASSUME(creturn[3] >= cr(3,0+2*1)); // call void @llvm.dbg.value(metadata i64 %0, metadata !96, metadata !DIExpression()), !dbg !113 // %conv = trunc i64 %0 to i32, !dbg !62 // call void @llvm.dbg.value(metadata i32 %conv, metadata !93, metadata !DIExpression()), !dbg !110 // call void (...) @dmbsy(), !dbg !63 // dumbsy: Guess old_cdy = cdy[3]; cdy[3] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[3] >= old_cdy); ASSUME(cdy[3] >= cisb[3]); ASSUME(cdy[3] >= cdl[3]); ASSUME(cdy[3] >= cds[3]); ASSUME(cdy[3] >= cctrl[3]); ASSUME(cdy[3] >= cw(3,0+0)); ASSUME(cdy[3] >= cw(3,0+1)); ASSUME(cdy[3] >= cw(3,0+2)); ASSUME(cdy[3] >= cw(3,7+0)); ASSUME(cdy[3] >= cw(3,8+0)); ASSUME(cdy[3] >= cw(3,3+0)); ASSUME(cdy[3] >= cw(3,4+0)); ASSUME(cdy[3] >= cw(3,5+0)); ASSUME(cdy[3] >= cw(3,6+0)); ASSUME(cdy[3] >= cr(3,0+0)); ASSUME(cdy[3] >= cr(3,0+1)); ASSUME(cdy[3] >= cr(3,0+2)); ASSUME(cdy[3] >= cr(3,7+0)); ASSUME(cdy[3] >= cr(3,8+0)); ASSUME(cdy[3] >= cr(3,3+0)); ASSUME(cdy[3] >= cr(3,4+0)); ASSUME(cdy[3] >= cr(3,5+0)); ASSUME(cdy[3] >= cr(3,6+0)); ASSUME(creturn[3] >= cdy[3]); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !98, metadata !DIExpression()), !dbg !117 // %1 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !65 // LD: Guess old_cr = cr(3,0); cr(3,0) = get_rng(0,NCONTEXT-1);// 3 ASSIGN LDCOM // Check ASSUME(active[cr(3,0)] == 3); ASSUME(cr(3,0) >= iw(3,0)); ASSUME(cr(3,0) >= 0); ASSUME(cr(3,0) >= cdy[3]); ASSUME(cr(3,0) >= cisb[3]); ASSUME(cr(3,0) >= cdl[3]); ASSUME(cr(3,0) >= cl[3]); // Update creg_r2 = cr(3,0); crmax(3,0) = max(crmax(3,0),cr(3,0)); caddr[3] = max(caddr[3],0); if(cr(3,0) < cw(3,0)) { r2 = buff(3,0); } else { if(pw(3,0) != co(0,cr(3,0))) { ASSUME(cr(3,0) >= old_cr); } pw(3,0) = co(0,cr(3,0)); r2 = mem(0,cr(3,0)); } ASSUME(creturn[3] >= cr(3,0)); // call void @llvm.dbg.value(metadata i64 %1, metadata !100, metadata !DIExpression()), !dbg !117 // %conv4 = trunc i64 %1 to i32, !dbg !66 // call void @llvm.dbg.value(metadata i32 %conv4, metadata !97, metadata !DIExpression()), !dbg !110 // %cmp = icmp eq i32 %conv, 1, !dbg !67 // %conv5 = zext i1 %cmp to i32, !dbg !67 // call void @llvm.dbg.value(metadata i32 %conv5, metadata !101, metadata !DIExpression()), !dbg !110 // call void @llvm.dbg.value(metadata i64* @atom_2_X0_1, metadata !102, metadata !DIExpression()), !dbg !121 // %2 = zext i32 %conv5 to i64 // call void @llvm.dbg.value(metadata i64 %2, metadata !104, metadata !DIExpression()), !dbg !121 // store atomic i64 %2, i64* @atom_2_X0_1 seq_cst, align 8, !dbg !69 // ST: Guess iw(3,4) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW old_cw = cw(3,4); cw(3,4) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM // Check ASSUME(active[iw(3,4)] == 3); ASSUME(active[cw(3,4)] == 3); ASSUME(sforbid(4,cw(3,4))== 0); ASSUME(iw(3,4) >= max(creg_r1,0)); ASSUME(iw(3,4) >= 0); ASSUME(cw(3,4) >= iw(3,4)); ASSUME(cw(3,4) >= old_cw); ASSUME(cw(3,4) >= cr(3,4)); ASSUME(cw(3,4) >= cl[3]); ASSUME(cw(3,4) >= cisb[3]); ASSUME(cw(3,4) >= cdy[3]); ASSUME(cw(3,4) >= cdl[3]); ASSUME(cw(3,4) >= cds[3]); ASSUME(cw(3,4) >= cctrl[3]); ASSUME(cw(3,4) >= caddr[3]); // Update caddr[3] = max(caddr[3],0); buff(3,4) = (r1==1); mem(4,cw(3,4)) = (r1==1); co(4,cw(3,4))+=1; delta(4,cw(3,4)) = -1; ASSUME(creturn[3] >= cw(3,4)); // %cmp7 = icmp eq i32 %conv4, 0, !dbg !70 // %conv8 = zext i1 %cmp7 to i32, !dbg !70 // call void @llvm.dbg.value(metadata i32 %conv8, metadata !105, metadata !DIExpression()), !dbg !110 // call void @llvm.dbg.value(metadata i64* @atom_2_X2_0, metadata !106, metadata !DIExpression()), !dbg !124 // %3 = zext i32 %conv8 to i64 // call void @llvm.dbg.value(metadata i64 %3, metadata !108, metadata !DIExpression()), !dbg !124 // store atomic i64 %3, i64* @atom_2_X2_0 seq_cst, align 8, !dbg !72 // ST: Guess iw(3,5) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW old_cw = cw(3,5); cw(3,5) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM // Check ASSUME(active[iw(3,5)] == 3); ASSUME(active[cw(3,5)] == 3); ASSUME(sforbid(5,cw(3,5))== 0); ASSUME(iw(3,5) >= max(creg_r2,0)); ASSUME(iw(3,5) >= 0); ASSUME(cw(3,5) >= iw(3,5)); ASSUME(cw(3,5) >= old_cw); ASSUME(cw(3,5) >= cr(3,5)); ASSUME(cw(3,5) >= cl[3]); ASSUME(cw(3,5) >= cisb[3]); ASSUME(cw(3,5) >= cdy[3]); ASSUME(cw(3,5) >= cdl[3]); ASSUME(cw(3,5) >= cds[3]); ASSUME(cw(3,5) >= cctrl[3]); ASSUME(cw(3,5) >= caddr[3]); // Update caddr[3] = max(caddr[3],0); buff(3,5) = (r2==0); mem(5,cw(3,5)) = (r2==0); co(5,cw(3,5))+=1; delta(5,cw(3,5)) = -1; ASSUME(creturn[3] >= cw(3,5)); // ret i8* null, !dbg !73 ret_thread_3 = (- 1); // Dumping thread 0 int ret_thread_0 = 0; cdy[0] = get_rng(0,NCONTEXT-1); ASSUME(cdy[0] >= cstart[0]); T0BLOCK0: // %thr0 = alloca i64, align 8 // %thr1 = alloca i64, align 8 // %thr2 = alloca i64, align 8 // call void @llvm.dbg.value(metadata i32 %argc, metadata !134, metadata !DIExpression()), !dbg !174 // call void @llvm.dbg.value(metadata i8** %argv, metadata !135, metadata !DIExpression()), !dbg !174 // %0 = bitcast i64* %thr0 to i8*, !dbg !83 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %0) #7, !dbg !83 // call void @llvm.dbg.declare(metadata i64* %thr0, metadata !136, metadata !DIExpression()), !dbg !176 // %1 = bitcast i64* %thr1 to i8*, !dbg !85 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %1) #7, !dbg !85 // call void @llvm.dbg.declare(metadata i64* %thr1, metadata !140, metadata !DIExpression()), !dbg !178 // %2 = bitcast i64* %thr2 to i8*, !dbg !87 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %2) #7, !dbg !87 // call void @llvm.dbg.declare(metadata i64* %thr2, metadata !141, metadata !DIExpression()), !dbg !180 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !142, metadata !DIExpression()), !dbg !181 // call void @llvm.dbg.value(metadata i64 0, metadata !144, metadata !DIExpression()), !dbg !181 // store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !90 // ST: Guess iw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,0+2*1); cw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,0+2*1)] == 0); ASSUME(active[cw(0,0+2*1)] == 0); ASSUME(sforbid(0+2*1,cw(0,0+2*1))== 0); ASSUME(iw(0,0+2*1) >= 0); ASSUME(iw(0,0+2*1) >= 0); ASSUME(cw(0,0+2*1) >= iw(0,0+2*1)); ASSUME(cw(0,0+2*1) >= old_cw); ASSUME(cw(0,0+2*1) >= cr(0,0+2*1)); ASSUME(cw(0,0+2*1) >= cl[0]); ASSUME(cw(0,0+2*1) >= cisb[0]); ASSUME(cw(0,0+2*1) >= cdy[0]); ASSUME(cw(0,0+2*1) >= cdl[0]); ASSUME(cw(0,0+2*1) >= cds[0]); ASSUME(cw(0,0+2*1) >= cctrl[0]); ASSUME(cw(0,0+2*1) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0+2*1) = 0; mem(0+2*1,cw(0,0+2*1)) = 0; co(0+2*1,cw(0,0+2*1))+=1; delta(0+2*1,cw(0,0+2*1)) = -1; ASSUME(creturn[0] >= cw(0,0+2*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !145, metadata !DIExpression()), !dbg !183 // call void @llvm.dbg.value(metadata i64 0, metadata !147, metadata !DIExpression()), !dbg !183 // store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !92 // ST: Guess iw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,0+1*1); cw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,0+1*1)] == 0); ASSUME(active[cw(0,0+1*1)] == 0); ASSUME(sforbid(0+1*1,cw(0,0+1*1))== 0); ASSUME(iw(0,0+1*1) >= 0); ASSUME(iw(0,0+1*1) >= 0); ASSUME(cw(0,0+1*1) >= iw(0,0+1*1)); ASSUME(cw(0,0+1*1) >= old_cw); ASSUME(cw(0,0+1*1) >= cr(0,0+1*1)); ASSUME(cw(0,0+1*1) >= cl[0]); ASSUME(cw(0,0+1*1) >= cisb[0]); ASSUME(cw(0,0+1*1) >= cdy[0]); ASSUME(cw(0,0+1*1) >= cdl[0]); ASSUME(cw(0,0+1*1) >= cds[0]); ASSUME(cw(0,0+1*1) >= cctrl[0]); ASSUME(cw(0,0+1*1) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0+1*1) = 0; mem(0+1*1,cw(0,0+1*1)) = 0; co(0+1*1,cw(0,0+1*1))+=1; delta(0+1*1,cw(0,0+1*1)) = -1; ASSUME(creturn[0] >= cw(0,0+1*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !148, metadata !DIExpression()), !dbg !185 // call void @llvm.dbg.value(metadata i64 0, metadata !150, metadata !DIExpression()), !dbg !185 // store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !94 // ST: Guess iw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,0); cw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,0)] == 0); ASSUME(active[cw(0,0)] == 0); ASSUME(sforbid(0,cw(0,0))== 0); ASSUME(iw(0,0) >= 0); ASSUME(iw(0,0) >= 0); ASSUME(cw(0,0) >= iw(0,0)); ASSUME(cw(0,0) >= old_cw); ASSUME(cw(0,0) >= cr(0,0)); ASSUME(cw(0,0) >= cl[0]); ASSUME(cw(0,0) >= cisb[0]); ASSUME(cw(0,0) >= cdy[0]); ASSUME(cw(0,0) >= cdl[0]); ASSUME(cw(0,0) >= cds[0]); ASSUME(cw(0,0) >= cctrl[0]); ASSUME(cw(0,0) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0) = 0; mem(0,cw(0,0)) = 0; co(0,cw(0,0))+=1; delta(0,cw(0,0)) = -1; ASSUME(creturn[0] >= cw(0,0)); // call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !151, metadata !DIExpression()), !dbg !187 // call void @llvm.dbg.value(metadata i64 0, metadata !153, metadata !DIExpression()), !dbg !187 // store atomic i64 0, i64* @atom_1_X0_1 monotonic, align 8, !dbg !96 // ST: Guess iw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,3); cw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,3)] == 0); ASSUME(active[cw(0,3)] == 0); ASSUME(sforbid(3,cw(0,3))== 0); ASSUME(iw(0,3) >= 0); ASSUME(iw(0,3) >= 0); ASSUME(cw(0,3) >= iw(0,3)); ASSUME(cw(0,3) >= old_cw); ASSUME(cw(0,3) >= cr(0,3)); ASSUME(cw(0,3) >= cl[0]); ASSUME(cw(0,3) >= cisb[0]); ASSUME(cw(0,3) >= cdy[0]); ASSUME(cw(0,3) >= cdl[0]); ASSUME(cw(0,3) >= cds[0]); ASSUME(cw(0,3) >= cctrl[0]); ASSUME(cw(0,3) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,3) = 0; mem(3,cw(0,3)) = 0; co(3,cw(0,3))+=1; delta(3,cw(0,3)) = -1; ASSUME(creturn[0] >= cw(0,3)); // call void @llvm.dbg.value(metadata i64* @atom_2_X0_1, metadata !154, metadata !DIExpression()), !dbg !189 // call void @llvm.dbg.value(metadata i64 0, metadata !156, metadata !DIExpression()), !dbg !189 // store atomic i64 0, i64* @atom_2_X0_1 monotonic, align 8, !dbg !98 // ST: Guess iw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,4); cw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,4)] == 0); ASSUME(active[cw(0,4)] == 0); ASSUME(sforbid(4,cw(0,4))== 0); ASSUME(iw(0,4) >= 0); ASSUME(iw(0,4) >= 0); ASSUME(cw(0,4) >= iw(0,4)); ASSUME(cw(0,4) >= old_cw); ASSUME(cw(0,4) >= cr(0,4)); ASSUME(cw(0,4) >= cl[0]); ASSUME(cw(0,4) >= cisb[0]); ASSUME(cw(0,4) >= cdy[0]); ASSUME(cw(0,4) >= cdl[0]); ASSUME(cw(0,4) >= cds[0]); ASSUME(cw(0,4) >= cctrl[0]); ASSUME(cw(0,4) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,4) = 0; mem(4,cw(0,4)) = 0; co(4,cw(0,4))+=1; delta(4,cw(0,4)) = -1; ASSUME(creturn[0] >= cw(0,4)); // call void @llvm.dbg.value(metadata i64* @atom_2_X2_0, metadata !157, metadata !DIExpression()), !dbg !191 // call void @llvm.dbg.value(metadata i64 0, metadata !159, metadata !DIExpression()), !dbg !191 // store atomic i64 0, i64* @atom_2_X2_0 monotonic, align 8, !dbg !100 // ST: Guess iw(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,5); cw(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,5)] == 0); ASSUME(active[cw(0,5)] == 0); ASSUME(sforbid(5,cw(0,5))== 0); ASSUME(iw(0,5) >= 0); ASSUME(iw(0,5) >= 0); ASSUME(cw(0,5) >= iw(0,5)); ASSUME(cw(0,5) >= old_cw); ASSUME(cw(0,5) >= cr(0,5)); ASSUME(cw(0,5) >= cl[0]); ASSUME(cw(0,5) >= cisb[0]); ASSUME(cw(0,5) >= cdy[0]); ASSUME(cw(0,5) >= cdl[0]); ASSUME(cw(0,5) >= cds[0]); ASSUME(cw(0,5) >= cctrl[0]); ASSUME(cw(0,5) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,5) = 0; mem(5,cw(0,5)) = 0; co(5,cw(0,5))+=1; delta(5,cw(0,5)) = -1; ASSUME(creturn[0] >= cw(0,5)); // %call = call i32 @pthread_create(i64* noundef %thr0, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t0, i8* noundef null) #7, !dbg !101 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cw(0,8+0)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(cdy[0] >= cr(0,8+0)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[1] >= cdy[0]); // %call11 = call i32 @pthread_create(i64* noundef %thr1, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t1, i8* noundef null) #7, !dbg !102 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cw(0,8+0)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(cdy[0] >= cr(0,8+0)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[2] >= cdy[0]); // %call12 = call i32 @pthread_create(i64* noundef %thr2, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t2, i8* noundef null) #7, !dbg !103 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cw(0,8+0)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(cdy[0] >= cr(0,8+0)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[3] >= cdy[0]); // %3 = load i64, i64* %thr0, align 8, !dbg !104, !tbaa !105 // LD: Guess old_cr = cr(0,6); cr(0,6) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,6)] == 0); ASSUME(cr(0,6) >= iw(0,6)); ASSUME(cr(0,6) >= 0); ASSUME(cr(0,6) >= cdy[0]); ASSUME(cr(0,6) >= cisb[0]); ASSUME(cr(0,6) >= cdl[0]); ASSUME(cr(0,6) >= cl[0]); // Update creg_r4 = cr(0,6); crmax(0,6) = max(crmax(0,6),cr(0,6)); caddr[0] = max(caddr[0],0); if(cr(0,6) < cw(0,6)) { r4 = buff(0,6); } else { if(pw(0,6) != co(6,cr(0,6))) { ASSUME(cr(0,6) >= old_cr); } pw(0,6) = co(6,cr(0,6)); r4 = mem(6,cr(0,6)); } ASSUME(creturn[0] >= cr(0,6)); // %call13 = call i32 @pthread_join(i64 noundef %3, i8** noundef null), !dbg !109 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cw(0,8+0)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(cdy[0] >= cr(0,8+0)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[1]); // %4 = load i64, i64* %thr1, align 8, !dbg !110, !tbaa !105 // LD: Guess old_cr = cr(0,7); cr(0,7) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,7)] == 0); ASSUME(cr(0,7) >= iw(0,7)); ASSUME(cr(0,7) >= 0); ASSUME(cr(0,7) >= cdy[0]); ASSUME(cr(0,7) >= cisb[0]); ASSUME(cr(0,7) >= cdl[0]); ASSUME(cr(0,7) >= cl[0]); // Update creg_r5 = cr(0,7); crmax(0,7) = max(crmax(0,7),cr(0,7)); caddr[0] = max(caddr[0],0); if(cr(0,7) < cw(0,7)) { r5 = buff(0,7); } else { if(pw(0,7) != co(7,cr(0,7))) { ASSUME(cr(0,7) >= old_cr); } pw(0,7) = co(7,cr(0,7)); r5 = mem(7,cr(0,7)); } ASSUME(creturn[0] >= cr(0,7)); // %call14 = call i32 @pthread_join(i64 noundef %4, i8** noundef null), !dbg !111 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cw(0,8+0)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(cdy[0] >= cr(0,8+0)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[2]); // %5 = load i64, i64* %thr2, align 8, !dbg !112, !tbaa !105 // LD: Guess old_cr = cr(0,8); cr(0,8) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,8)] == 0); ASSUME(cr(0,8) >= iw(0,8)); ASSUME(cr(0,8) >= 0); ASSUME(cr(0,8) >= cdy[0]); ASSUME(cr(0,8) >= cisb[0]); ASSUME(cr(0,8) >= cdl[0]); ASSUME(cr(0,8) >= cl[0]); // Update creg_r6 = cr(0,8); crmax(0,8) = max(crmax(0,8),cr(0,8)); caddr[0] = max(caddr[0],0); if(cr(0,8) < cw(0,8)) { r6 = buff(0,8); } else { if(pw(0,8) != co(8,cr(0,8))) { ASSUME(cr(0,8) >= old_cr); } pw(0,8) = co(8,cr(0,8)); r6 = mem(8,cr(0,8)); } ASSUME(creturn[0] >= cr(0,8)); // %call15 = call i32 @pthread_join(i64 noundef %5, i8** noundef null), !dbg !113 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cw(0,8+0)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(cdy[0] >= cr(0,8+0)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[3]); // call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !161, metadata !DIExpression()), !dbg !206 // %6 = load atomic i64, i64* @atom_1_X0_1 seq_cst, align 8, !dbg !115 // LD: Guess old_cr = cr(0,3); cr(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,3)] == 0); ASSUME(cr(0,3) >= iw(0,3)); ASSUME(cr(0,3) >= 0); ASSUME(cr(0,3) >= cdy[0]); ASSUME(cr(0,3) >= cisb[0]); ASSUME(cr(0,3) >= cdl[0]); ASSUME(cr(0,3) >= cl[0]); // Update creg_r7 = cr(0,3); crmax(0,3) = max(crmax(0,3),cr(0,3)); caddr[0] = max(caddr[0],0); if(cr(0,3) < cw(0,3)) { r7 = buff(0,3); } else { if(pw(0,3) != co(3,cr(0,3))) { ASSUME(cr(0,3) >= old_cr); } pw(0,3) = co(3,cr(0,3)); r7 = mem(3,cr(0,3)); } ASSUME(creturn[0] >= cr(0,3)); // call void @llvm.dbg.value(metadata i64 %6, metadata !163, metadata !DIExpression()), !dbg !206 // %conv = trunc i64 %6 to i32, !dbg !116 // call void @llvm.dbg.value(metadata i32 %conv, metadata !160, metadata !DIExpression()), !dbg !174 // call void @llvm.dbg.value(metadata i64* @atom_2_X0_1, metadata !165, metadata !DIExpression()), !dbg !209 // %7 = load atomic i64, i64* @atom_2_X0_1 seq_cst, align 8, !dbg !118 // LD: Guess old_cr = cr(0,4); cr(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,4)] == 0); ASSUME(cr(0,4) >= iw(0,4)); ASSUME(cr(0,4) >= 0); ASSUME(cr(0,4) >= cdy[0]); ASSUME(cr(0,4) >= cisb[0]); ASSUME(cr(0,4) >= cdl[0]); ASSUME(cr(0,4) >= cl[0]); // Update creg_r8 = cr(0,4); crmax(0,4) = max(crmax(0,4),cr(0,4)); caddr[0] = max(caddr[0],0); if(cr(0,4) < cw(0,4)) { r8 = buff(0,4); } else { if(pw(0,4) != co(4,cr(0,4))) { ASSUME(cr(0,4) >= old_cr); } pw(0,4) = co(4,cr(0,4)); r8 = mem(4,cr(0,4)); } ASSUME(creturn[0] >= cr(0,4)); // call void @llvm.dbg.value(metadata i64 %7, metadata !167, metadata !DIExpression()), !dbg !209 // %conv19 = trunc i64 %7 to i32, !dbg !119 // call void @llvm.dbg.value(metadata i32 %conv19, metadata !164, metadata !DIExpression()), !dbg !174 // call void @llvm.dbg.value(metadata i64* @atom_2_X2_0, metadata !169, metadata !DIExpression()), !dbg !212 // %8 = load atomic i64, i64* @atom_2_X2_0 seq_cst, align 8, !dbg !121 // LD: Guess old_cr = cr(0,5); cr(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,5)] == 0); ASSUME(cr(0,5) >= iw(0,5)); ASSUME(cr(0,5) >= 0); ASSUME(cr(0,5) >= cdy[0]); ASSUME(cr(0,5) >= cisb[0]); ASSUME(cr(0,5) >= cdl[0]); ASSUME(cr(0,5) >= cl[0]); // Update creg_r9 = cr(0,5); crmax(0,5) = max(crmax(0,5),cr(0,5)); caddr[0] = max(caddr[0],0); if(cr(0,5) < cw(0,5)) { r9 = buff(0,5); } else { if(pw(0,5) != co(5,cr(0,5))) { ASSUME(cr(0,5) >= old_cr); } pw(0,5) = co(5,cr(0,5)); r9 = mem(5,cr(0,5)); } ASSUME(creturn[0] >= cr(0,5)); // call void @llvm.dbg.value(metadata i64 %8, metadata !171, metadata !DIExpression()), !dbg !212 // %conv23 = trunc i64 %8 to i32, !dbg !122 // call void @llvm.dbg.value(metadata i32 %conv23, metadata !168, metadata !DIExpression()), !dbg !174 // %and = and i32 %conv19, %conv23, !dbg !123 creg_r10 = max(creg_r8,creg_r9); ASSUME(active[creg_r10] == 0); r10 = r8 & r9; // call void @llvm.dbg.value(metadata i32 %and, metadata !172, metadata !DIExpression()), !dbg !174 // %and24 = and i32 %conv, %and, !dbg !124 creg_r11 = max(creg_r7,creg_r10); ASSUME(active[creg_r11] == 0); r11 = r7 & r10; // call void @llvm.dbg.value(metadata i32 %and24, metadata !173, metadata !DIExpression()), !dbg !174 // %cmp = icmp eq i32 %and24, 1, !dbg !125 // br i1 %cmp, label %if.then, label %if.end, !dbg !127 old_cctrl = cctrl[0]; cctrl[0] = get_rng(0,NCONTEXT-1); ASSUME(cctrl[0] >= old_cctrl); ASSUME(cctrl[0] >= creg_r11); ASSUME(cctrl[0] >= 0); if((r11==1)) { goto T0BLOCK1; } else { goto T0BLOCK2; } T0BLOCK1: // call void @__assert_fail(i8* noundef getelementptr inbounds ([2 x i8], [2 x i8]* @.str, i64 0, i64 0), i8* noundef getelementptr inbounds ([107 x i8], [107 x i8]* @.str.1, i64 0, i64 0), i32 noundef 75, i8* noundef getelementptr inbounds ([23 x i8], [23 x i8]* @__PRETTY_FUNCTION__.main, i64 0, i64 0)) #8, !dbg !128 // unreachable, !dbg !128 r12 = 1; T0BLOCK2: // %9 = bitcast i64* %thr2 to i8*, !dbg !131 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %9) #7, !dbg !131 // %10 = bitcast i64* %thr1 to i8*, !dbg !131 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %10) #7, !dbg !131 // %11 = bitcast i64* %thr0 to i8*, !dbg !131 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %11) #7, !dbg !131 // ret i32 0, !dbg !132 ret_thread_0 = 0; ASSERT(r12== 0); }
[ "tuan-phong.ngo@it.uu.se" ]
tuan-phong.ngo@it.uu.se
9eb3626a5c8114d970d313661b2eadfaae4f60ed
e020c8080f09a1a174a8a8841eab3ddb2b720b75
/MyStudy/02_WinAPI/DeadParticle.cpp
cde5078db417b8039882de107403755aba5a1128
[]
no_license
eazuooz/WindowsAPI_Portfolio
c19bcf912d5ff2fb55955b7ba390c036326e41d3
f9e6e3645a1a59e62c7522a0f45fa97c76e1c3e9
refs/heads/master
2023-07-02T16:13:15.996565
2021-07-27T03:22:13
2021-07-27T03:22:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
937
cpp
#include "stdafx.h" #include "DeadParticle.h" #include "AniRender.h" #include <JTIME.h> #include <Well512.h> #define m_PI 3.141592 DeadParticle::DeadParticle() : deathTime( 5.0f) { Well512Random::Init(); dPos = {Well512Random::GetFloatValue(-1.00f, 1.00f), Well512Random::GetFloatValue(-1.00f, 1.00f) }; } DeadParticle::~DeadParticle() { } bool DeadParticle::Init() { render = CreateRender<AniRender>(120); render->SubPivotMode(PIVOT::CENTER); render->CreateAnimation(L"CircleBombAll", L"DeadEffect.bmp", 0, 11, true, 0.08f); //render->CreateAnimation(L"CircleBomb", L"PlayerBigBullet.bmp", 7, 10, true, 0.05f); render->PlayAnimation(L"CircleBombAll"); render->RenderSize({60.0f , 60.0f }); return true; } void DeadParticle::Update() { pos += (dPos)* 100.0F * Time::DeltaTime(); deathTime -= Time::DeltaTime(); if (deathTime < 0.0f) { Die(); } }
[ "46310910+MYOMYO3@users.noreply.github.com" ]
46310910+MYOMYO3@users.noreply.github.com
160b9de6262f7ff863e6a4f18a37bba185f2612e
229f25ccda6d721f31c6d4de27a7bb85dcc0f929
/solutions/RPC/05-2019/B.cpp
70c3102697876f211658fb887f5a584033a518fe
[]
no_license
camil0palacios/Competitive-programming
e743378a8791a66c90ffaae29b4fd4cfb58fff59
4211fa61e516cb986b3404d87409ad1a49f78132
refs/heads/master
2022-11-01T20:35:21.541132
2022-10-27T03:13:42
2022-10-27T03:13:42
155,419,333
0
0
null
null
null
null
UTF-8
C++
false
false
1,258
cpp
#include <bits/stdc++.h> using namespace std; const int NM = 1e3 + 5; char g[NM][NM]; bool done[NM][NM]; int h, n, m; int dx_p[6] = {-1,-1, 0,0,1,1}; int dy_p[6] = { 0, 1,-1,1,0,1}; int dx[6] = {-1,-1, 0,0, 1,1}; int dy[6] = {-1, 0,-1,1,-1,0}; void dfs(int x, int y, int & cnt){ done[x][y] = 1; cnt++; for(int i = 0; i < 6; i++){ int mx, my; if(x % 2){ mx = x + dx_p[i], my = y + dy_p[i]; }else{ mx = x + dx[i], my = y + dy[i]; } if(mx >= 0 && mx < n && my >= 0 && my < m && !done[mx][my] && g[mx][my] == '.') dfs(mx,my,cnt); } } int main(){ cin >> h >> n >> m; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ cin >> g[i][j]; } } vector<int> v; memset(done, 0, sizeof done); for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ if(!done[i][j] && g[i][j] == '.'){ int cnt = 0; dfs(i,j,cnt); v.emplace_back(cnt); } } } sort(v.begin(), v.end(), greater<int>()); int ans = 0; for(auto & i : v){ if(h <= 0)break; h -= i; ans++; } cout << ans << endl; return 0; }
[ "camilopalacios772@gmail.com" ]
camilopalacios772@gmail.com
4990dbf5e1cdb0ae0ecd95bfc153cbd2c8af98e5
736dadbdbdcf1ee31ead243f793f229657f281bd
/RTCP/RTP/RtpConnect.cpp
f6b322e2bc395effc61e0c66eec2d07b18528e58
[]
no_license
demon060/IPC
3608dd590b8acde4b7f8f7bfa5c03b42dcd54b07
16be58dcfbec348b6844d959ae00034f4eccb699
refs/heads/master
2020-07-27T13:38:54.214149
2019-02-12T09:08:39
2019-02-12T09:08:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,769
cpp
#include "RtpConnect.h" #include <chrono> RtpConnect::RtpConnect(int port) { sockfd = socket(AF_INET, SOCK_DGRAM, 0); struct sockaddr_in addr = {0}; addr.sin_family = AF_INET; addr.sin_addr.s_addr = inet_addr("0.0.0.0"); addr.sin_port = htons(port); if(bind(sockfd, (struct sockaddr*)&addr, sizeof addr) == -1) { cout << "Sockfd bind error!" << endl; } int size = 50*1024; setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, (char *)&size, sizeof(size)); cout << "[RTP ==> " << port << "]" << endl; rtpHeader.version = RTP_VERSION; packetSeq = 1; //rd()&0xffff; rtpHeader.ssrc = htonl(10); rtpHeader.payload = 96; } RtpConnect::~RtpConnect() { close(sockfd); } uint32_t RtpConnect::getTimeStamp() { auto timePoint = chrono::time_point_cast<chrono::microseconds>(chrono::high_resolution_clock::now()); return (uint32_t)((timePoint.time_since_epoch().count() + 500) / 1000 * 90 ); } void RtpConnect::SetpeerRtpAdd(string ip, int port) { peerRtpAddr.sin_family = AF_INET; peerRtpAddr.sin_addr.s_addr = inet_addr(ip.c_str()); peerRtpAddr.sin_port = htons(port); } bool RtpConnect::pushFrame(AVFrame& frame) { char *frameBuf = frame.buffer.get(); uint32_t frameSize = frame.size; if(frame.timestamp == 0) frame.timestamp = getTimeStamp(); if(frameSize <= MAX_RTP_PAYLOAD_SIZE) { RtpPacketPtr rtpPkt(new char[1500]); memcpy(rtpPkt.get()+4+RTP_HEADER_SIZE, frameBuf, frameSize); // 预留12字节 rtp header sendFrame(frame.type, rtpPkt, frameSize+4+RTP_HEADER_SIZE, 1, frame.timestamp); } else { char FU_A[2] = {0}; // 分包参考live555 FU_A[0] = (frameBuf[0] & 0xE0) | 28; FU_A[1] = 0x80 | (frameBuf[0] & 0x1f); frameBuf += 1; frameSize -= 1; while(frameSize + 2 > MAX_RTP_PAYLOAD_SIZE) { RtpPacketPtr rtpPkt(new char[1500]); rtpPkt.get()[RTP_HEADER_SIZE+4] = FU_A[0]; rtpPkt.get()[RTP_HEADER_SIZE+5] = FU_A[1]; memcpy(rtpPkt.get()+4+RTP_HEADER_SIZE+2, frameBuf, MAX_RTP_PAYLOAD_SIZE-2); sendFrame(frame.type, rtpPkt, 4+RTP_HEADER_SIZE+MAX_RTP_PAYLOAD_SIZE, 0, frame.timestamp); frameBuf += MAX_RTP_PAYLOAD_SIZE - 2; frameSize -= MAX_RTP_PAYLOAD_SIZE - 2; FU_A[1] &= ~0x80; } { //RtpPacketPtr rtpPkt((char*)xop::Alloc(1500), xop::Free); RtpPacketPtr rtpPkt(new char[1500]); FU_A[1] |= 0x40; rtpPkt.get()[RTP_HEADER_SIZE+4] = FU_A[0]; rtpPkt.get()[RTP_HEADER_SIZE+5] = FU_A[1]; memcpy(rtpPkt.get()+4+RTP_HEADER_SIZE+2, frameBuf, frameSize); sendFrame(frame.type, rtpPkt, 4+RTP_HEADER_SIZE+2+frameSize, 1, frame.timestamp); } } return true; } bool RtpConnect::sendFrame(uint8_t frameType, RtpPacketPtr& rtpPkt, uint32_t pktSize, uint8_t last, uint32_t ts) { setFrameType(frameType); setRtpHeader(rtpPkt, last, ts); sendRtpPacket(rtpPkt, pktSize); return true; } void RtpConnect::setFrameType(uint8_t frameType) { //cout << frameType << endl; } void RtpConnect::setRtpHeader(RtpPacketPtr& rtpPkt, uint8_t last, uint32_t ts) { rtpHeader.marker = last; rtpHeader.ts = htonl(ts); rtpHeader.seq = htons(packetSeq++); memcpy(rtpPkt.get()+4, &rtpHeader, RTP_HEADER_SIZE); } int RtpConnect::sendRtpPacket(RtpPacketPtr& rtpPkt, uint32_t pktSize) { int ret = sendto(sockfd, rtpPkt.get()+4, pktSize-4, 0, (struct sockaddr *)&peerRtpAddr, sizeof(struct sockaddr_in)); if(ret < 0) { //teardown(); return -1; } return ret; }
[ "992802269@qq.com" ]
992802269@qq.com
d6937be260088ba40e2e46ae6cfe3b1ff4d41f39
a734f2ab729e2f36d4f5b3a7617dd3eaf5199c01
/Leetcode/LinkedList/445_Add_two_numbers_2.cpp
d4215bd6e831756f1b01fb3cac097c402010e876
[]
no_license
shash04/General_Coding
54b889d919b1de7d152a9e585ff604ed8c6a3b2b
7d12479db221c4324e6254b88869997ce110866f
refs/heads/master
2021-01-13T10:39:10.832265
2020-12-14T04:52:00
2020-12-14T04:52:00
69,840,301
1
1
null
null
null
null
UTF-8
C++
false
false
2,585
cpp
// You are given two non-empty linked lists representing two non-negative integers. // The most significant digit comes first and each of their nodes contain a single digit. // Add the two numbers and return it as a linked list. // You may assume the two numbers do not contain any leading zero, except the number 0 itself. // Follow up: // What if you cannot modify the input lists? In other words, reversing the lists is not allowed. // Example: // Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) // Output: 7 -> 8 -> 0 -> 7 // https://leetcode.com/problems/add-two-numbers-ii/ class Solution { public: void printStack(stack<int> s1){ while(!s1.empty()){ cout<<s1.top()<<endl; s1.pop(); } } ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { if(l1 == NULL && l2 == NULL) return NULL; stack<int> s1; stack<int> s2; stack<int> ans; ListNode* retHead; ListNode *iter1, *iter2; iter1 = l1; iter2 = l2; while(iter1){ s1.push(iter1->val); iter1 = iter1->next; } while(iter2){ s2.push(iter2->val); iter2 = iter2->next; } int rem = 0; int sum = 0; while(!s1.empty() && !s2.empty()){ sum = s1.top() + s2.top() + rem; rem = sum / 10; sum = sum % 10; ans.push(sum); s1.pop(); s2.pop(); } while(!s2.empty()){ sum = s2.top() + rem; rem = sum / 10; sum = sum % 10; ans.push(sum); s2.pop(); } while(!s1.empty()){ sum = s1.top() + rem; rem = sum / 10; sum = sum % 10; ans.push(sum); s1.pop(); } if(rem) ans.push(rem); retHead = new ListNode(ans.top()); ans.pop(); ListNode* temp = retHead; while(!ans.empty()) { ListNode* newNode = new ListNode(ans.top()); temp->next = newNode; ans.pop(); temp = temp->next; } return retHead; } }; /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */
[ "noreply@github.com" ]
shash04.noreply@github.com
36097b2812f67e4dfe80fc726ead8f8b73f6bcae
1391042fa29e096d42ee5a9488d6385ae2fcbffe
/bin/linux64/cpp/obj/src/zpp_nape/dynamics/ZPP_IContact.cpp
e54ff247817f562097435855611a621cbbaaa246
[]
no_license
TomBebbington/brains
8820de236a879c2199147906bf1d390cf44de6cc
c69b51e261fcbe3c1b7bea84568a92424da6a0aa
refs/heads/master
2021-01-10T18:33:08.105130
2013-08-25T23:20:45
2013-08-25T23:20:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
33,584
cpp
#include <hxcpp.h> #ifndef INCLUDED_zpp_nape_dynamics_ZPP_IContact #include <zpp_nape/dynamics/ZPP_IContact.h> #endif namespace zpp_nape{ namespace dynamics{ Void ZPP_IContact_obj::__construct() { HX_STACK_FRAME("ZPP_IContact","new","ZPP_IContact.new","zpp_nape/dynamics/Contact.hx",625) { HX_STACK_LINE(655) this->length = (int)0; HX_STACK_LINE(654) this->pushmod = false; HX_STACK_LINE(653) this->modified = false; HX_STACK_LINE(652) this->_inuse = false; HX_STACK_LINE(641) this->next = null(); HX_STACK_LINE(639) this->lr2y = 0.0; HX_STACK_LINE(638) this->lr2x = 0.0; HX_STACK_LINE(637) this->lr1y = 0.0; HX_STACK_LINE(636) this->lr1x = 0.0; HX_STACK_LINE(635) this->jtAcc = 0.0; HX_STACK_LINE(634) this->jnAcc = 0.0; HX_STACK_LINE(633) this->friction = 0.0; HX_STACK_LINE(632) this->bounce = 0.0; HX_STACK_LINE(631) this->tMass = 0.0; HX_STACK_LINE(630) this->nMass = 0.0; HX_STACK_LINE(629) this->r2y = 0.0; HX_STACK_LINE(628) this->r2x = 0.0; HX_STACK_LINE(627) this->r1y = 0.0; HX_STACK_LINE(626) this->r1x = 0.0; } ; return null(); } ZPP_IContact_obj::~ZPP_IContact_obj() { } Dynamic ZPP_IContact_obj::__CreateEmpty() { return new ZPP_IContact_obj; } hx::ObjectPtr< ZPP_IContact_obj > ZPP_IContact_obj::__new() { hx::ObjectPtr< ZPP_IContact_obj > result = new ZPP_IContact_obj(); result->__construct(); return result;} Dynamic ZPP_IContact_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< ZPP_IContact_obj > result = new ZPP_IContact_obj(); result->__construct(); return result;} ::zpp_nape::dynamics::ZPP_IContact ZPP_IContact_obj::at( int ind){ HX_STACK_FRAME("ZPP_IContact","at","ZPP_IContact.at","zpp_nape/dynamics/Contact.hx",984) HX_STACK_THIS(this) HX_STACK_ARG(ind,"ind") HX_STACK_LINE(993) ::zpp_nape::dynamics::ZPP_IContact it = this->iterator_at(ind); HX_STACK_VAR(it,"it"); HX_STACK_LINE(994) if (((it != null()))){ HX_STACK_LINE(994) return it; } else{ HX_STACK_LINE(994) return null(); } HX_STACK_LINE(994) return null(); } HX_DEFINE_DYNAMIC_FUNC1(ZPP_IContact_obj,at,return ) ::zpp_nape::dynamics::ZPP_IContact ZPP_IContact_obj::iterator_at( int ind){ HX_STACK_FRAME("ZPP_IContact","iterator_at","ZPP_IContact.iterator_at","zpp_nape/dynamics/Contact.hx",971) HX_STACK_THIS(this) HX_STACK_ARG(ind,"ind") HX_STACK_LINE(980) ::zpp_nape::dynamics::ZPP_IContact ret = this->next; HX_STACK_VAR(ret,"ret"); HX_STACK_LINE(981) while(((bool(((ind)-- > (int)0)) && bool((ret != null()))))){ HX_STACK_LINE(981) ret = ret->next; } HX_STACK_LINE(982) return ret; } HX_DEFINE_DYNAMIC_FUNC1(ZPP_IContact_obj,iterator_at,return ) ::zpp_nape::dynamics::ZPP_IContact ZPP_IContact_obj::back( ){ HX_STACK_FRAME("ZPP_IContact","back","ZPP_IContact.back","zpp_nape/dynamics/Contact.hx",962) HX_STACK_THIS(this) HX_STACK_LINE(963) ::zpp_nape::dynamics::ZPP_IContact ret = this->next; HX_STACK_VAR(ret,"ret"); HX_STACK_LINE(964) ::zpp_nape::dynamics::ZPP_IContact cur = ret; HX_STACK_VAR(cur,"cur"); HX_STACK_LINE(965) while(((cur != null()))){ HX_STACK_LINE(966) ret = cur; HX_STACK_LINE(967) cur = cur->next; } HX_STACK_LINE(969) return ret; } HX_DEFINE_DYNAMIC_FUNC0(ZPP_IContact_obj,back,return ) ::zpp_nape::dynamics::ZPP_IContact ZPP_IContact_obj::front( ){ HX_STACK_FRAME("ZPP_IContact","front","ZPP_IContact.front","zpp_nape/dynamics/Contact.hx",960) HX_STACK_THIS(this) HX_STACK_LINE(960) return this->next; } HX_DEFINE_DYNAMIC_FUNC0(ZPP_IContact_obj,front,return ) bool ZPP_IContact_obj::inlined_has( ::zpp_nape::dynamics::ZPP_IContact obj){ HX_STACK_FRAME("ZPP_IContact","inlined_has","ZPP_IContact.inlined_has","zpp_nape/dynamics/Contact.hx",929) HX_STACK_THIS(this) HX_STACK_ARG(obj,"obj") HX_STACK_LINE(938) bool ret; HX_STACK_VAR(ret,"ret"); HX_STACK_LINE(939) { HX_STACK_LINE(940) ret = false; HX_STACK_LINE(941) { HX_STACK_LINE(942) ::zpp_nape::dynamics::ZPP_IContact cx_ite = this->next; HX_STACK_VAR(cx_ite,"cx_ite"); HX_STACK_LINE(943) while(((cx_ite != null()))){ HX_STACK_LINE(944) ::zpp_nape::dynamics::ZPP_IContact npite = cx_ite; HX_STACK_VAR(npite,"npite"); HX_STACK_LINE(946) if (((npite == obj))){ HX_STACK_LINE(947) ret = true; HX_STACK_LINE(948) break; } HX_STACK_LINE(951) cx_ite = cx_ite->next; } } } HX_STACK_LINE(955) return ret; } HX_DEFINE_DYNAMIC_FUNC1(ZPP_IContact_obj,inlined_has,return ) bool ZPP_IContact_obj::has( ::zpp_nape::dynamics::ZPP_IContact obj){ HX_STACK_FRAME("ZPP_IContact","has","ZPP_IContact.has","zpp_nape/dynamics/Contact.hx",925) HX_STACK_THIS(this) HX_STACK_ARG(obj,"obj") HX_STACK_LINE(925) bool ret; HX_STACK_VAR(ret,"ret"); HX_STACK_LINE(925) { HX_STACK_LINE(925) ret = false; HX_STACK_LINE(925) { HX_STACK_LINE(925) ::zpp_nape::dynamics::ZPP_IContact cx_ite = this->next; HX_STACK_VAR(cx_ite,"cx_ite"); HX_STACK_LINE(925) while(((cx_ite != null()))){ HX_STACK_LINE(925) ::zpp_nape::dynamics::ZPP_IContact npite = cx_ite; HX_STACK_VAR(npite,"npite"); HX_STACK_LINE(925) if (((npite == obj))){ HX_STACK_LINE(925) ret = true; HX_STACK_LINE(925) break; } HX_STACK_LINE(925) cx_ite = cx_ite->next; } } } HX_STACK_LINE(925) return ret; } HX_DEFINE_DYNAMIC_FUNC1(ZPP_IContact_obj,has,return ) int ZPP_IContact_obj::size( ){ HX_STACK_FRAME("ZPP_IContact","size","ZPP_IContact.size","zpp_nape/dynamics/Contact.hx",922) HX_STACK_THIS(this) HX_STACK_LINE(922) return this->length; } HX_DEFINE_DYNAMIC_FUNC0(ZPP_IContact_obj,size,return ) bool ZPP_IContact_obj::empty( ){ HX_STACK_FRAME("ZPP_IContact","empty","ZPP_IContact.empty","zpp_nape/dynamics/Contact.hx",917) HX_STACK_THIS(this) HX_STACK_LINE(917) return (this->next == null()); } HX_DEFINE_DYNAMIC_FUNC0(ZPP_IContact_obj,empty,return ) Void ZPP_IContact_obj::reverse( ){ { HX_STACK_FRAME("ZPP_IContact","reverse","ZPP_IContact.reverse","zpp_nape/dynamics/Contact.hx",901) HX_STACK_THIS(this) HX_STACK_LINE(902) ::zpp_nape::dynamics::ZPP_IContact cur = this->next; HX_STACK_VAR(cur,"cur"); HX_STACK_LINE(903) ::zpp_nape::dynamics::ZPP_IContact pre = null(); HX_STACK_VAR(pre,"pre"); HX_STACK_LINE(904) while(((cur != null()))){ HX_STACK_LINE(905) ::zpp_nape::dynamics::ZPP_IContact nx = cur->next; HX_STACK_VAR(nx,"nx"); HX_STACK_LINE(906) cur->next = pre; HX_STACK_LINE(907) this->next = cur; HX_STACK_LINE(908) pre = cur; HX_STACK_LINE(909) cur = nx; } HX_STACK_LINE(911) this->modified = true; HX_STACK_LINE(912) this->pushmod = true; } return null(); } HX_DEFINE_DYNAMIC_FUNC0(ZPP_IContact_obj,reverse,(void)) Void ZPP_IContact_obj::inlined_clear( ){ { HX_STACK_FRAME("ZPP_IContact","inlined_clear","ZPP_IContact.inlined_clear","zpp_nape/dynamics/Contact.hx",896) HX_STACK_THIS(this) } return null(); } HX_DEFINE_DYNAMIC_FUNC0(ZPP_IContact_obj,inlined_clear,(void)) Void ZPP_IContact_obj::clear( ){ { HX_STACK_FRAME("ZPP_IContact","clear","ZPP_IContact.clear","zpp_nape/dynamics/Contact.hx",891) HX_STACK_THIS(this) } return null(); } HX_DEFINE_DYNAMIC_FUNC0(ZPP_IContact_obj,clear,(void)) ::zpp_nape::dynamics::ZPP_IContact ZPP_IContact_obj::splice( ::zpp_nape::dynamics::ZPP_IContact pre,int n){ HX_STACK_FRAME("ZPP_IContact","splice","ZPP_IContact.splice","zpp_nape/dynamics/Contact.hx",886) HX_STACK_THIS(this) HX_STACK_ARG(pre,"pre") HX_STACK_ARG(n,"n") HX_STACK_LINE(887) while(((bool(((n)-- > (int)0)) && bool((pre->next != null()))))){ HX_STACK_LINE(887) this->erase(pre); } HX_STACK_LINE(888) return pre->next; } HX_DEFINE_DYNAMIC_FUNC2(ZPP_IContact_obj,splice,return ) ::zpp_nape::dynamics::ZPP_IContact ZPP_IContact_obj::inlined_erase( ::zpp_nape::dynamics::ZPP_IContact pre){ HX_STACK_FRAME("ZPP_IContact","inlined_erase","ZPP_IContact.inlined_erase","zpp_nape/dynamics/Contact.hx",854) HX_STACK_THIS(this) HX_STACK_ARG(pre,"pre") HX_STACK_LINE(863) ::zpp_nape::dynamics::ZPP_IContact old; HX_STACK_VAR(old,"old"); HX_STACK_LINE(864) ::zpp_nape::dynamics::ZPP_IContact ret; HX_STACK_VAR(ret,"ret"); HX_STACK_LINE(865) if (((pre == null()))){ HX_STACK_LINE(866) old = this->next; HX_STACK_LINE(867) ret = old->next; HX_STACK_LINE(868) this->next = ret; HX_STACK_LINE(869) if (((this->next == null()))){ HX_STACK_LINE(869) this->pushmod = true; } } else{ HX_STACK_LINE(872) old = pre->next; HX_STACK_LINE(873) ret = old->next; HX_STACK_LINE(874) pre->next = ret; HX_STACK_LINE(875) if (((ret == null()))){ HX_STACK_LINE(875) this->pushmod = true; } } HX_STACK_LINE(878) old->_inuse = false; HX_STACK_LINE(881) this->modified = true; HX_STACK_LINE(882) (this->length)--; HX_STACK_LINE(883) this->pushmod = true; HX_STACK_LINE(884) return ret; } HX_DEFINE_DYNAMIC_FUNC1(ZPP_IContact_obj,inlined_erase,return ) ::zpp_nape::dynamics::ZPP_IContact ZPP_IContact_obj::erase( ::zpp_nape::dynamics::ZPP_IContact pre){ HX_STACK_FRAME("ZPP_IContact","erase","ZPP_IContact.erase","zpp_nape/dynamics/Contact.hx",850) HX_STACK_THIS(this) HX_STACK_ARG(pre,"pre") HX_STACK_LINE(850) ::zpp_nape::dynamics::ZPP_IContact old; HX_STACK_VAR(old,"old"); HX_STACK_LINE(850) ::zpp_nape::dynamics::ZPP_IContact ret; HX_STACK_VAR(ret,"ret"); HX_STACK_LINE(850) if (((pre == null()))){ HX_STACK_LINE(850) old = this->next; HX_STACK_LINE(850) ret = old->next; HX_STACK_LINE(850) this->next = ret; HX_STACK_LINE(850) if (((this->next == null()))){ HX_STACK_LINE(850) this->pushmod = true; } } else{ HX_STACK_LINE(850) old = pre->next; HX_STACK_LINE(850) ret = old->next; HX_STACK_LINE(850) pre->next = ret; HX_STACK_LINE(850) if (((ret == null()))){ HX_STACK_LINE(850) this->pushmod = true; } } HX_STACK_LINE(850) old->_inuse = false; HX_STACK_LINE(850) this->modified = true; HX_STACK_LINE(850) (this->length)--; HX_STACK_LINE(850) this->pushmod = true; HX_STACK_LINE(850) return ret; } HX_DEFINE_DYNAMIC_FUNC1(ZPP_IContact_obj,erase,return ) bool ZPP_IContact_obj::inlined_try_remove( ::zpp_nape::dynamics::ZPP_IContact obj){ HX_STACK_FRAME("ZPP_IContact","inlined_try_remove","ZPP_IContact.inlined_try_remove","zpp_nape/dynamics/Contact.hx",826) HX_STACK_THIS(this) HX_STACK_ARG(obj,"obj") HX_STACK_LINE(835) ::zpp_nape::dynamics::ZPP_IContact pre = null(); HX_STACK_VAR(pre,"pre"); HX_STACK_LINE(836) ::zpp_nape::dynamics::ZPP_IContact cur = this->next; HX_STACK_VAR(cur,"cur"); HX_STACK_LINE(837) bool ret = false; HX_STACK_VAR(ret,"ret"); HX_STACK_LINE(838) while(((cur != null()))){ HX_STACK_LINE(839) if (((cur == obj))){ HX_STACK_LINE(840) { HX_STACK_LINE(840) ::zpp_nape::dynamics::ZPP_IContact old; HX_STACK_VAR(old,"old"); HX_STACK_LINE(840) ::zpp_nape::dynamics::ZPP_IContact ret1; HX_STACK_VAR(ret1,"ret1"); HX_STACK_LINE(840) if (((pre == null()))){ HX_STACK_LINE(840) old = this->next; HX_STACK_LINE(840) ret1 = old->next; HX_STACK_LINE(840) this->next = ret1; HX_STACK_LINE(840) if (((this->next == null()))){ HX_STACK_LINE(840) this->pushmod = true; } } else{ HX_STACK_LINE(840) old = pre->next; HX_STACK_LINE(840) ret1 = old->next; HX_STACK_LINE(840) pre->next = ret1; HX_STACK_LINE(840) if (((ret1 == null()))){ HX_STACK_LINE(840) this->pushmod = true; } } HX_STACK_LINE(840) old->_inuse = false; HX_STACK_LINE(840) this->modified = true; HX_STACK_LINE(840) (this->length)--; HX_STACK_LINE(840) this->pushmod = true; HX_STACK_LINE(840) ret1; } HX_STACK_LINE(841) ret = true; HX_STACK_LINE(842) break; } HX_STACK_LINE(844) pre = cur; HX_STACK_LINE(845) cur = cur->next; } HX_STACK_LINE(847) return ret; } HX_DEFINE_DYNAMIC_FUNC1(ZPP_IContact_obj,inlined_try_remove,return ) Void ZPP_IContact_obj::inlined_remove( ::zpp_nape::dynamics::ZPP_IContact obj){ { HX_STACK_FRAME("ZPP_IContact","inlined_remove","ZPP_IContact.inlined_remove","zpp_nape/dynamics/Contact.hx",822) HX_STACK_THIS(this) HX_STACK_ARG(obj,"obj") HX_STACK_LINE(822) ::zpp_nape::dynamics::ZPP_IContact pre = null(); HX_STACK_VAR(pre,"pre"); HX_STACK_LINE(822) ::zpp_nape::dynamics::ZPP_IContact cur = this->next; HX_STACK_VAR(cur,"cur"); HX_STACK_LINE(822) bool ret = false; HX_STACK_VAR(ret,"ret"); HX_STACK_LINE(822) while(((cur != null()))){ HX_STACK_LINE(822) if (((cur == obj))){ HX_STACK_LINE(822) { HX_STACK_LINE(822) ::zpp_nape::dynamics::ZPP_IContact old; HX_STACK_VAR(old,"old"); HX_STACK_LINE(822) ::zpp_nape::dynamics::ZPP_IContact ret1; HX_STACK_VAR(ret1,"ret1"); HX_STACK_LINE(822) if (((pre == null()))){ HX_STACK_LINE(822) old = this->next; HX_STACK_LINE(822) ret1 = old->next; HX_STACK_LINE(822) this->next = ret1; HX_STACK_LINE(822) if (((this->next == null()))){ HX_STACK_LINE(822) this->pushmod = true; } } else{ HX_STACK_LINE(822) old = pre->next; HX_STACK_LINE(822) ret1 = old->next; HX_STACK_LINE(822) pre->next = ret1; HX_STACK_LINE(822) if (((ret1 == null()))){ HX_STACK_LINE(822) this->pushmod = true; } } HX_STACK_LINE(822) old->_inuse = false; HX_STACK_LINE(822) this->modified = true; HX_STACK_LINE(822) (this->length)--; HX_STACK_LINE(822) this->pushmod = true; HX_STACK_LINE(822) ret1; } HX_STACK_LINE(822) ret = true; HX_STACK_LINE(822) break; } HX_STACK_LINE(822) pre = cur; HX_STACK_LINE(822) cur = cur->next; } HX_STACK_LINE(822) ret; } return null(); } HX_DEFINE_DYNAMIC_FUNC1(ZPP_IContact_obj,inlined_remove,(void)) bool ZPP_IContact_obj::try_remove( ::zpp_nape::dynamics::ZPP_IContact obj){ HX_STACK_FRAME("ZPP_IContact","try_remove","ZPP_IContact.try_remove","zpp_nape/dynamics/Contact.hx",788) HX_STACK_THIS(this) HX_STACK_ARG(obj,"obj") HX_STACK_LINE(797) ::zpp_nape::dynamics::ZPP_IContact pre = null(); HX_STACK_VAR(pre,"pre"); HX_STACK_LINE(798) ::zpp_nape::dynamics::ZPP_IContact cur = this->next; HX_STACK_VAR(cur,"cur"); HX_STACK_LINE(799) bool ret = false; HX_STACK_VAR(ret,"ret"); HX_STACK_LINE(800) while(((cur != null()))){ HX_STACK_LINE(801) if (((cur == obj))){ HX_STACK_LINE(802) this->erase(pre); HX_STACK_LINE(803) ret = true; HX_STACK_LINE(804) break; } HX_STACK_LINE(806) pre = cur; HX_STACK_LINE(807) cur = cur->next; } HX_STACK_LINE(809) return ret; } HX_DEFINE_DYNAMIC_FUNC1(ZPP_IContact_obj,try_remove,return ) Void ZPP_IContact_obj::remove( ::zpp_nape::dynamics::ZPP_IContact obj){ { HX_STACK_FRAME("ZPP_IContact","remove","ZPP_IContact.remove","zpp_nape/dynamics/Contact.hx",786) HX_STACK_THIS(this) HX_STACK_ARG(obj,"obj") HX_STACK_LINE(786) ::zpp_nape::dynamics::ZPP_IContact pre = null(); HX_STACK_VAR(pre,"pre"); HX_STACK_LINE(786) ::zpp_nape::dynamics::ZPP_IContact cur = this->next; HX_STACK_VAR(cur,"cur"); HX_STACK_LINE(786) bool ret = false; HX_STACK_VAR(ret,"ret"); HX_STACK_LINE(786) while(((cur != null()))){ HX_STACK_LINE(786) if (((cur == obj))){ HX_STACK_LINE(786) { HX_STACK_LINE(786) ::zpp_nape::dynamics::ZPP_IContact old; HX_STACK_VAR(old,"old"); HX_STACK_LINE(786) ::zpp_nape::dynamics::ZPP_IContact ret1; HX_STACK_VAR(ret1,"ret1"); HX_STACK_LINE(786) if (((pre == null()))){ HX_STACK_LINE(786) old = this->next; HX_STACK_LINE(786) ret1 = old->next; HX_STACK_LINE(786) this->next = ret1; HX_STACK_LINE(786) if (((this->next == null()))){ HX_STACK_LINE(786) this->pushmod = true; } } else{ HX_STACK_LINE(786) old = pre->next; HX_STACK_LINE(786) ret1 = old->next; HX_STACK_LINE(786) pre->next = ret1; HX_STACK_LINE(786) if (((ret1 == null()))){ HX_STACK_LINE(786) this->pushmod = true; } } HX_STACK_LINE(786) old->_inuse = false; HX_STACK_LINE(786) this->modified = true; HX_STACK_LINE(786) (this->length)--; HX_STACK_LINE(786) this->pushmod = true; HX_STACK_LINE(786) ret1; } HX_STACK_LINE(786) ret = true; HX_STACK_LINE(786) break; } HX_STACK_LINE(786) pre = cur; HX_STACK_LINE(786) cur = cur->next; } HX_STACK_LINE(786) ret; } return null(); } HX_DEFINE_DYNAMIC_FUNC1(ZPP_IContact_obj,remove,(void)) ::zpp_nape::dynamics::ZPP_IContact ZPP_IContact_obj::inlined_pop_unsafe( ){ HX_STACK_FRAME("ZPP_IContact","inlined_pop_unsafe","ZPP_IContact.inlined_pop_unsafe","zpp_nape/dynamics/Contact.hx",764) HX_STACK_THIS(this) HX_STACK_LINE(773) ::zpp_nape::dynamics::ZPP_IContact ret = this->next; HX_STACK_VAR(ret,"ret"); HX_STACK_LINE(774) this->pop(); HX_STACK_LINE(775) return ret; } HX_DEFINE_DYNAMIC_FUNC0(ZPP_IContact_obj,inlined_pop_unsafe,return ) ::zpp_nape::dynamics::ZPP_IContact ZPP_IContact_obj::pop_unsafe( ){ HX_STACK_FRAME("ZPP_IContact","pop_unsafe","ZPP_IContact.pop_unsafe","zpp_nape/dynamics/Contact.hx",760) HX_STACK_THIS(this) HX_STACK_LINE(760) ::zpp_nape::dynamics::ZPP_IContact ret = this->next; HX_STACK_VAR(ret,"ret"); HX_STACK_LINE(760) this->pop(); HX_STACK_LINE(760) return ret; } HX_DEFINE_DYNAMIC_FUNC0(ZPP_IContact_obj,pop_unsafe,return ) Void ZPP_IContact_obj::inlined_pop( ){ { HX_STACK_FRAME("ZPP_IContact","inlined_pop","ZPP_IContact.inlined_pop","zpp_nape/dynamics/Contact.hx",740) HX_STACK_THIS(this) HX_STACK_LINE(749) ::zpp_nape::dynamics::ZPP_IContact ret = this->next; HX_STACK_VAR(ret,"ret"); HX_STACK_LINE(750) this->next = ret->next; HX_STACK_LINE(752) ret->_inuse = false; HX_STACK_LINE(755) if (((this->next == null()))){ HX_STACK_LINE(755) this->pushmod = true; } HX_STACK_LINE(756) this->modified = true; HX_STACK_LINE(757) (this->length)--; } return null(); } HX_DEFINE_DYNAMIC_FUNC0(ZPP_IContact_obj,inlined_pop,(void)) Void ZPP_IContact_obj::pop( ){ { HX_STACK_FRAME("ZPP_IContact","pop","ZPP_IContact.pop","zpp_nape/dynamics/Contact.hx",736) HX_STACK_THIS(this) HX_STACK_LINE(736) ::zpp_nape::dynamics::ZPP_IContact ret = this->next; HX_STACK_VAR(ret,"ret"); HX_STACK_LINE(736) this->next = ret->next; HX_STACK_LINE(736) ret->_inuse = false; HX_STACK_LINE(736) if (((this->next == null()))){ HX_STACK_LINE(736) this->pushmod = true; } HX_STACK_LINE(736) this->modified = true; HX_STACK_LINE(736) (this->length)--; } return null(); } HX_DEFINE_DYNAMIC_FUNC0(ZPP_IContact_obj,pop,(void)) ::zpp_nape::dynamics::ZPP_IContact ZPP_IContact_obj::inlined_insert( ::zpp_nape::dynamics::ZPP_IContact cur,::zpp_nape::dynamics::ZPP_IContact o){ HX_STACK_FRAME("ZPP_IContact","inlined_insert","ZPP_IContact.inlined_insert","zpp_nape/dynamics/Contact.hx",710) HX_STACK_THIS(this) HX_STACK_ARG(cur,"cur") HX_STACK_ARG(o,"o") HX_STACK_LINE(719) ::zpp_nape::dynamics::ZPP_IContact temp; HX_STACK_VAR(temp,"temp"); HX_STACK_LINE(719) { HX_STACK_LINE(720) o->_inuse = true; HX_STACK_LINE(721) temp = o; } HX_STACK_LINE(723) if (((cur == null()))){ HX_STACK_LINE(724) temp->next = this->next; HX_STACK_LINE(725) this->next = temp; } else{ HX_STACK_LINE(728) temp->next = cur->next; HX_STACK_LINE(729) cur->next = temp; } HX_STACK_LINE(731) this->pushmod = this->modified = true; HX_STACK_LINE(732) (this->length)++; HX_STACK_LINE(733) return temp; } HX_DEFINE_DYNAMIC_FUNC2(ZPP_IContact_obj,inlined_insert,return ) ::zpp_nape::dynamics::ZPP_IContact ZPP_IContact_obj::insert( ::zpp_nape::dynamics::ZPP_IContact cur,::zpp_nape::dynamics::ZPP_IContact o){ HX_STACK_FRAME("ZPP_IContact","insert","ZPP_IContact.insert","zpp_nape/dynamics/Contact.hx",706) HX_STACK_THIS(this) HX_STACK_ARG(cur,"cur") HX_STACK_ARG(o,"o") HX_STACK_LINE(706) ::zpp_nape::dynamics::ZPP_IContact temp; HX_STACK_VAR(temp,"temp"); HX_STACK_LINE(706) { HX_STACK_LINE(706) o->_inuse = true; HX_STACK_LINE(706) temp = o; } HX_STACK_LINE(706) if (((cur == null()))){ HX_STACK_LINE(706) temp->next = this->next; HX_STACK_LINE(706) this->next = temp; } else{ HX_STACK_LINE(706) temp->next = cur->next; HX_STACK_LINE(706) cur->next = temp; } HX_STACK_LINE(706) this->pushmod = this->modified = true; HX_STACK_LINE(706) (this->length)++; HX_STACK_LINE(706) return temp; } HX_DEFINE_DYNAMIC_FUNC2(ZPP_IContact_obj,insert,return ) Void ZPP_IContact_obj::addAll( ::zpp_nape::dynamics::ZPP_IContact x){ { HX_STACK_FRAME("ZPP_IContact","addAll","ZPP_IContact.addAll","zpp_nape/dynamics/Contact.hx",696) HX_STACK_THIS(this) HX_STACK_ARG(x,"x") HX_STACK_LINE(697) ::zpp_nape::dynamics::ZPP_IContact cx_ite = x->next; HX_STACK_VAR(cx_ite,"cx_ite"); HX_STACK_LINE(698) while(((cx_ite != null()))){ HX_STACK_LINE(699) ::zpp_nape::dynamics::ZPP_IContact i = cx_ite; HX_STACK_VAR(i,"i"); HX_STACK_LINE(700) this->add(i); HX_STACK_LINE(701) cx_ite = cx_ite->next; } } return null(); } HX_DEFINE_DYNAMIC_FUNC1(ZPP_IContact_obj,addAll,(void)) ::zpp_nape::dynamics::ZPP_IContact ZPP_IContact_obj::inlined_add( ::zpp_nape::dynamics::ZPP_IContact o){ HX_STACK_FRAME("ZPP_IContact","inlined_add","ZPP_IContact.inlined_add","zpp_nape/dynamics/Contact.hx",668) HX_STACK_THIS(this) HX_STACK_ARG(o,"o") HX_STACK_LINE(677) ::zpp_nape::dynamics::ZPP_IContact temp; HX_STACK_VAR(temp,"temp"); HX_STACK_LINE(677) { HX_STACK_LINE(678) o->_inuse = true; HX_STACK_LINE(679) temp = o; } HX_STACK_LINE(681) temp->next = this->next; HX_STACK_LINE(682) this->next = temp; HX_STACK_LINE(683) this->modified = true; HX_STACK_LINE(684) (this->length)++; HX_STACK_LINE(685) return o; } HX_DEFINE_DYNAMIC_FUNC1(ZPP_IContact_obj,inlined_add,return ) ::zpp_nape::dynamics::ZPP_IContact ZPP_IContact_obj::add( ::zpp_nape::dynamics::ZPP_IContact o){ HX_STACK_FRAME("ZPP_IContact","add","ZPP_IContact.add","zpp_nape/dynamics/Contact.hx",664) HX_STACK_THIS(this) HX_STACK_ARG(o,"o") HX_STACK_LINE(664) ::zpp_nape::dynamics::ZPP_IContact temp; HX_STACK_VAR(temp,"temp"); HX_STACK_LINE(664) { HX_STACK_LINE(664) o->_inuse = true; HX_STACK_LINE(664) temp = o; } HX_STACK_LINE(664) temp->next = this->next; HX_STACK_LINE(664) this->next = temp; HX_STACK_LINE(664) this->modified = true; HX_STACK_LINE(664) (this->length)++; HX_STACK_LINE(664) return o; } HX_DEFINE_DYNAMIC_FUNC1(ZPP_IContact_obj,add,return ) Void ZPP_IContact_obj::setbegin( ::zpp_nape::dynamics::ZPP_IContact i){ { HX_STACK_FRAME("ZPP_IContact","setbegin","ZPP_IContact.setbegin","zpp_nape/dynamics/Contact.hx",658) HX_STACK_THIS(this) HX_STACK_ARG(i,"i") HX_STACK_LINE(659) this->next = i; HX_STACK_LINE(660) this->modified = true; HX_STACK_LINE(661) this->pushmod = true; } return null(); } HX_DEFINE_DYNAMIC_FUNC1(ZPP_IContact_obj,setbegin,(void)) ::zpp_nape::dynamics::ZPP_IContact ZPP_IContact_obj::begin( ){ HX_STACK_FRAME("ZPP_IContact","begin","ZPP_IContact.begin","zpp_nape/dynamics/Contact.hx",650) HX_STACK_THIS(this) HX_STACK_LINE(650) return this->next; } HX_DEFINE_DYNAMIC_FUNC0(ZPP_IContact_obj,begin,return ) ::zpp_nape::dynamics::ZPP_IContact ZPP_IContact_obj::elem( ){ HX_STACK_FRAME("ZPP_IContact","elem","ZPP_IContact.elem","zpp_nape/dynamics/Contact.hx",645) HX_STACK_THIS(this) HX_STACK_LINE(645) return hx::ObjectPtr<OBJ_>(this); } HX_DEFINE_DYNAMIC_FUNC0(ZPP_IContact_obj,elem,return ) ZPP_IContact_obj::ZPP_IContact_obj() { } void ZPP_IContact_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(ZPP_IContact); HX_MARK_MEMBER_NAME(length,"length"); HX_MARK_MEMBER_NAME(pushmod,"pushmod"); HX_MARK_MEMBER_NAME(modified,"modified"); HX_MARK_MEMBER_NAME(_inuse,"_inuse"); HX_MARK_MEMBER_NAME(next,"next"); HX_MARK_MEMBER_NAME(lr2y,"lr2y"); HX_MARK_MEMBER_NAME(lr2x,"lr2x"); HX_MARK_MEMBER_NAME(lr1y,"lr1y"); HX_MARK_MEMBER_NAME(lr1x,"lr1x"); HX_MARK_MEMBER_NAME(jtAcc,"jtAcc"); HX_MARK_MEMBER_NAME(jnAcc,"jnAcc"); HX_MARK_MEMBER_NAME(friction,"friction"); HX_MARK_MEMBER_NAME(bounce,"bounce"); HX_MARK_MEMBER_NAME(tMass,"tMass"); HX_MARK_MEMBER_NAME(nMass,"nMass"); HX_MARK_MEMBER_NAME(r2y,"r2y"); HX_MARK_MEMBER_NAME(r2x,"r2x"); HX_MARK_MEMBER_NAME(r1y,"r1y"); HX_MARK_MEMBER_NAME(r1x,"r1x"); HX_MARK_END_CLASS(); } void ZPP_IContact_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(length,"length"); HX_VISIT_MEMBER_NAME(pushmod,"pushmod"); HX_VISIT_MEMBER_NAME(modified,"modified"); HX_VISIT_MEMBER_NAME(_inuse,"_inuse"); HX_VISIT_MEMBER_NAME(next,"next"); HX_VISIT_MEMBER_NAME(lr2y,"lr2y"); HX_VISIT_MEMBER_NAME(lr2x,"lr2x"); HX_VISIT_MEMBER_NAME(lr1y,"lr1y"); HX_VISIT_MEMBER_NAME(lr1x,"lr1x"); HX_VISIT_MEMBER_NAME(jtAcc,"jtAcc"); HX_VISIT_MEMBER_NAME(jnAcc,"jnAcc"); HX_VISIT_MEMBER_NAME(friction,"friction"); HX_VISIT_MEMBER_NAME(bounce,"bounce"); HX_VISIT_MEMBER_NAME(tMass,"tMass"); HX_VISIT_MEMBER_NAME(nMass,"nMass"); HX_VISIT_MEMBER_NAME(r2y,"r2y"); HX_VISIT_MEMBER_NAME(r2x,"r2x"); HX_VISIT_MEMBER_NAME(r1y,"r1y"); HX_VISIT_MEMBER_NAME(r1x,"r1x"); } Dynamic ZPP_IContact_obj::__Field(const ::String &inName,bool inCallProp) { switch(inName.length) { case 2: if (HX_FIELD_EQ(inName,"at") ) { return at_dyn(); } break; case 3: if (HX_FIELD_EQ(inName,"has") ) { return has_dyn(); } if (HX_FIELD_EQ(inName,"pop") ) { return pop_dyn(); } if (HX_FIELD_EQ(inName,"add") ) { return add_dyn(); } if (HX_FIELD_EQ(inName,"r2y") ) { return r2y; } if (HX_FIELD_EQ(inName,"r2x") ) { return r2x; } if (HX_FIELD_EQ(inName,"r1y") ) { return r1y; } if (HX_FIELD_EQ(inName,"r1x") ) { return r1x; } break; case 4: if (HX_FIELD_EQ(inName,"back") ) { return back_dyn(); } if (HX_FIELD_EQ(inName,"size") ) { return size_dyn(); } if (HX_FIELD_EQ(inName,"elem") ) { return elem_dyn(); } if (HX_FIELD_EQ(inName,"next") ) { return next; } if (HX_FIELD_EQ(inName,"lr2y") ) { return lr2y; } if (HX_FIELD_EQ(inName,"lr2x") ) { return lr2x; } if (HX_FIELD_EQ(inName,"lr1y") ) { return lr1y; } if (HX_FIELD_EQ(inName,"lr1x") ) { return lr1x; } break; case 5: if (HX_FIELD_EQ(inName,"front") ) { return front_dyn(); } if (HX_FIELD_EQ(inName,"empty") ) { return empty_dyn(); } if (HX_FIELD_EQ(inName,"clear") ) { return clear_dyn(); } if (HX_FIELD_EQ(inName,"erase") ) { return erase_dyn(); } if (HX_FIELD_EQ(inName,"begin") ) { return begin_dyn(); } if (HX_FIELD_EQ(inName,"jtAcc") ) { return jtAcc; } if (HX_FIELD_EQ(inName,"jnAcc") ) { return jnAcc; } if (HX_FIELD_EQ(inName,"tMass") ) { return tMass; } if (HX_FIELD_EQ(inName,"nMass") ) { return nMass; } break; case 6: if (HX_FIELD_EQ(inName,"splice") ) { return splice_dyn(); } if (HX_FIELD_EQ(inName,"remove") ) { return remove_dyn(); } if (HX_FIELD_EQ(inName,"insert") ) { return insert_dyn(); } if (HX_FIELD_EQ(inName,"addAll") ) { return addAll_dyn(); } if (HX_FIELD_EQ(inName,"length") ) { return length; } if (HX_FIELD_EQ(inName,"_inuse") ) { return _inuse; } if (HX_FIELD_EQ(inName,"bounce") ) { return bounce; } break; case 7: if (HX_FIELD_EQ(inName,"reverse") ) { return reverse_dyn(); } if (HX_FIELD_EQ(inName,"pushmod") ) { return pushmod; } break; case 8: if (HX_FIELD_EQ(inName,"setbegin") ) { return setbegin_dyn(); } if (HX_FIELD_EQ(inName,"modified") ) { return modified; } if (HX_FIELD_EQ(inName,"friction") ) { return friction; } break; case 10: if (HX_FIELD_EQ(inName,"try_remove") ) { return try_remove_dyn(); } if (HX_FIELD_EQ(inName,"pop_unsafe") ) { return pop_unsafe_dyn(); } break; case 11: if (HX_FIELD_EQ(inName,"iterator_at") ) { return iterator_at_dyn(); } if (HX_FIELD_EQ(inName,"inlined_has") ) { return inlined_has_dyn(); } if (HX_FIELD_EQ(inName,"inlined_pop") ) { return inlined_pop_dyn(); } if (HX_FIELD_EQ(inName,"inlined_add") ) { return inlined_add_dyn(); } break; case 13: if (HX_FIELD_EQ(inName,"inlined_clear") ) { return inlined_clear_dyn(); } if (HX_FIELD_EQ(inName,"inlined_erase") ) { return inlined_erase_dyn(); } break; case 14: if (HX_FIELD_EQ(inName,"inlined_remove") ) { return inlined_remove_dyn(); } if (HX_FIELD_EQ(inName,"inlined_insert") ) { return inlined_insert_dyn(); } break; case 18: if (HX_FIELD_EQ(inName,"inlined_try_remove") ) { return inlined_try_remove_dyn(); } if (HX_FIELD_EQ(inName,"inlined_pop_unsafe") ) { return inlined_pop_unsafe_dyn(); } } return super::__Field(inName,inCallProp); } Dynamic ZPP_IContact_obj::__SetField(const ::String &inName,const Dynamic &inValue,bool inCallProp) { switch(inName.length) { case 3: if (HX_FIELD_EQ(inName,"r2y") ) { r2y=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"r2x") ) { r2x=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"r1y") ) { r1y=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"r1x") ) { r1x=inValue.Cast< Float >(); return inValue; } break; case 4: if (HX_FIELD_EQ(inName,"next") ) { next=inValue.Cast< ::zpp_nape::dynamics::ZPP_IContact >(); return inValue; } if (HX_FIELD_EQ(inName,"lr2y") ) { lr2y=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"lr2x") ) { lr2x=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"lr1y") ) { lr1y=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"lr1x") ) { lr1x=inValue.Cast< Float >(); return inValue; } break; case 5: if (HX_FIELD_EQ(inName,"jtAcc") ) { jtAcc=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"jnAcc") ) { jnAcc=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"tMass") ) { tMass=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"nMass") ) { nMass=inValue.Cast< Float >(); return inValue; } break; case 6: if (HX_FIELD_EQ(inName,"length") ) { length=inValue.Cast< int >(); return inValue; } if (HX_FIELD_EQ(inName,"_inuse") ) { _inuse=inValue.Cast< bool >(); return inValue; } if (HX_FIELD_EQ(inName,"bounce") ) { bounce=inValue.Cast< Float >(); return inValue; } break; case 7: if (HX_FIELD_EQ(inName,"pushmod") ) { pushmod=inValue.Cast< bool >(); return inValue; } break; case 8: if (HX_FIELD_EQ(inName,"modified") ) { modified=inValue.Cast< bool >(); return inValue; } if (HX_FIELD_EQ(inName,"friction") ) { friction=inValue.Cast< Float >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void ZPP_IContact_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_CSTRING("length")); outFields->push(HX_CSTRING("pushmod")); outFields->push(HX_CSTRING("modified")); outFields->push(HX_CSTRING("_inuse")); outFields->push(HX_CSTRING("next")); outFields->push(HX_CSTRING("lr2y")); outFields->push(HX_CSTRING("lr2x")); outFields->push(HX_CSTRING("lr1y")); outFields->push(HX_CSTRING("lr1x")); outFields->push(HX_CSTRING("jtAcc")); outFields->push(HX_CSTRING("jnAcc")); outFields->push(HX_CSTRING("friction")); outFields->push(HX_CSTRING("bounce")); outFields->push(HX_CSTRING("tMass")); outFields->push(HX_CSTRING("nMass")); outFields->push(HX_CSTRING("r2y")); outFields->push(HX_CSTRING("r2x")); outFields->push(HX_CSTRING("r1y")); outFields->push(HX_CSTRING("r1x")); super::__GetFields(outFields); }; static ::String sStaticFields[] = { String(null()) }; static ::String sMemberFields[] = { HX_CSTRING("at"), HX_CSTRING("iterator_at"), HX_CSTRING("back"), HX_CSTRING("front"), HX_CSTRING("inlined_has"), HX_CSTRING("has"), HX_CSTRING("size"), HX_CSTRING("empty"), HX_CSTRING("reverse"), HX_CSTRING("inlined_clear"), HX_CSTRING("clear"), HX_CSTRING("splice"), HX_CSTRING("inlined_erase"), HX_CSTRING("erase"), HX_CSTRING("inlined_try_remove"), HX_CSTRING("inlined_remove"), HX_CSTRING("try_remove"), HX_CSTRING("remove"), HX_CSTRING("inlined_pop_unsafe"), HX_CSTRING("pop_unsafe"), HX_CSTRING("inlined_pop"), HX_CSTRING("pop"), HX_CSTRING("inlined_insert"), HX_CSTRING("insert"), HX_CSTRING("addAll"), HX_CSTRING("inlined_add"), HX_CSTRING("add"), HX_CSTRING("setbegin"), HX_CSTRING("length"), HX_CSTRING("pushmod"), HX_CSTRING("modified"), HX_CSTRING("_inuse"), HX_CSTRING("begin"), HX_CSTRING("elem"), HX_CSTRING("next"), HX_CSTRING("lr2y"), HX_CSTRING("lr2x"), HX_CSTRING("lr1y"), HX_CSTRING("lr1x"), HX_CSTRING("jtAcc"), HX_CSTRING("jnAcc"), HX_CSTRING("friction"), HX_CSTRING("bounce"), HX_CSTRING("tMass"), HX_CSTRING("nMass"), HX_CSTRING("r2y"), HX_CSTRING("r2x"), HX_CSTRING("r1y"), HX_CSTRING("r1x"), String(null()) }; static void sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(ZPP_IContact_obj::__mClass,"__mClass"); }; #ifdef HXCPP_VISIT_ALLOCS static void sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(ZPP_IContact_obj::__mClass,"__mClass"); }; #endif Class ZPP_IContact_obj::__mClass; void ZPP_IContact_obj::__register() { hx::Static(__mClass) = hx::RegisterClass(HX_CSTRING("zpp_nape.dynamics.ZPP_IContact"), hx::TCanCast< ZPP_IContact_obj> ,sStaticFields,sMemberFields, &__CreateEmpty, &__Create, &super::__SGetClass(), 0, sMarkStatics #ifdef HXCPP_VISIT_ALLOCS , sVisitStatics #endif ); } void ZPP_IContact_obj::__boot() { } } // end namespace zpp_nape } // end namespace dynamics
[ "tophattedcoder@gmail.com" ]
tophattedcoder@gmail.com
9a89daa1224df9ba3d1b39887094c826f38182a7
4bf4d0d02cdddc354de34062df2d27182e1053d1
/Codeforces/1384A.cpp
f1ccb5c73bb42ef222107180d86c6b537b3b9155
[ "MIT" ]
permissive
DT3264/ProgrammingContestsSolutions
d61fbac7145d82b3262c41a880ac89a1a813f231
e94f344602b22d84751b1e0503bb6fbe389dcf77
refs/heads/master
2022-02-23T02:37:43.144589
2022-02-06T21:47:53
2022-02-06T21:47:53
160,301,185
0
0
null
null
null
null
UTF-8
C++
false
false
1,234
cpp
// Problem : A. Common Prefixes // Contest : Codeforces - Codeforces Round #659 (Div. 2) // URL : https://codeforces.com/contest/1384/problem/0 // Memory Limit : 256 MB // Time Limit : 1000 ms // Powered by CP Editor (https://github.com/cpeditor/cpeditor) #include<bits/stdc++.h> #define f first #define s second #define ll long long #define vi vector<int> #define pii pair<int, int> #define si set<int> #define y1 yy #define debug if(printDebug) using namespace std; bool printDebug=false; int main(){ //printDebug=true; /*freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout);//*/ ios_base::sync_with_stdio(false); cin.tie(NULL);//*/ int cases; cin >> cases; while(cases--){ int n; cin >> n; vector<int> vec(n); for(int &x : vec) cin >> x; string s1; string s2; for(int i=0; i<50; i++) s1+='a'; vector<string> strings={s1}; for(int i=0; i<n; i++){ s2=strings[i]; int pos=vec[i]; while(pos<50){ if(s2[pos]==strings[i][pos]){ s2[pos]++; if(s2[pos]>'z') s2[pos]='a'; pos++; } } strings.push_back(s2); } for(string &s : strings) cout << s << "\n"; } return 0; }
[ "cernadaniel32@gmail.com" ]
cernadaniel32@gmail.com
08a1891a0175e736a4064b9003eb1e27ef9ea85f
b81d88e418b72ce70d7350739b76bdc48f8ef468
/tesseract_python/swig/tesseract_environment_python_std_functions.h
5a172cad82df469000e18bf9f2ecc90645e58ecf
[ "BSD-3-Clause", "Apache-2.0", "BSD-2-Clause" ]
permissive
marip8/tesseract_python
e7605ee9b8879c12be14f215d68b88961fa0cfe8
0466e23dc6dbb404deae9b27b38d4cb8768d52fd
refs/heads/master
2023-02-12T04:14:31.733733
2021-01-11T03:05:45
2021-01-11T06:39:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,124
h
/** * @file tesseract_environment_python_std_functions.h * @brief Callback directors for tesseract_python module * * @author John Wason * @date December 18, 2020 * @version TODO * @bug No known bugs * * @copyright Copyright (c) 2020, Wason Technology, LLC * * @par License * Software License Agreement (Apache License) * @par * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * @par * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tesseract_environment/core/environment.h> #pragma once class FindTCPCallbackFnBase { public: virtual Eigen::Isometry3d call(const tesseract_common::ManipulatorInfo& a) = 0; virtual ~FindTCPCallbackFnBase() {} };
[ "levi.armstrong@gmail.com" ]
levi.armstrong@gmail.com
0c676c6b92957e22745b21071c641578a84cb990
90d62b5fc8bb764c7238e7db99da3459fa8be4ef
/Project_Prototype/src/examples/player_demo.cpp
678eb9225714d4601919937133870268d9d1e0d9
[ "MIT" ]
permissive
markoczy/2DGameSDK
1d57c6a2f77e91f73a4d47cb7ca42f21339d2795
53da378d604ace1d931dfe6ec336241045675667
refs/heads/master
2022-03-29T05:17:41.618959
2020-01-16T18:26:01
2020-01-16T18:26:01
177,466,808
4
0
MIT
2019-12-19T18:05:22
2019-03-24T20:40:44
C++
UTF-8
C++
false
false
3,187
cpp
#include <examples.h> using namespace std; using namespace game; // Type of player entity const int _PLAYER_TYPE = 200; /** * @brief Test Entity: Movement Controllable by given observables */ class PlayerEntity : public SpriteKinematicEntity { public: PlayerEntity(Game* game, sf::Texture* texture, float speed, Observable<sf::Keyboard::Key>* up, Observable<sf::Keyboard::Key>* down, Observable<sf::Keyboard::Key>* left, Observable<sf::Keyboard::Key>* right) : SpriteKinematicEntity(_PLAYER_TYPE, game, texture), mSpeed(speed) { // // // mUp = new MethodObserver<sf::Keyboard::Key, PlayerEntity>(this, &PlayerEntity::MoveUp); mDown = new MethodObserver<sf::Keyboard::Key, PlayerEntity>(this, &PlayerEntity::MoveDown); mLeft = new MethodObserver<sf::Keyboard::Key, PlayerEntity>(this, &PlayerEntity::MoveLeft); mRight = new MethodObserver<sf::Keyboard::Key, PlayerEntity>(this, &PlayerEntity::MoveRight); mUp->SubscribeTo(up); mDown->SubscribeTo(down); mLeft->SubscribeTo(left); mRight->SubscribeTo(right); } ~PlayerEntity() { delete mUp; delete mDown; delete mLeft; delete mRight; } void OnTick() { if(mDt.x != 0 || mDt.y != 0) { Transform(sf::Transform().translate(mDt)); mDt = sf::Vector2f(); } } void MoveUp(sf::Keyboard::Key) { mDt.y -= mSpeed; } void MoveDown(sf::Keyboard::Key) { mDt.y += mSpeed; } void MoveLeft(sf::Keyboard::Key) { mDt.x -= mSpeed; } void MoveRight(sf::Keyboard::Key) { mDt.x += mSpeed; } private: float mSpeed; // Delta Transform of current tick sf::Vector2f mDt; // Needed for cleanup Observer<sf::Keyboard::Key>* mUp; Observer<sf::Keyboard::Key>* mDown; Observer<sf::Keyboard::Key>* mLeft; Observer<sf::Keyboard::Key>* mRight; }; int playerDemo(float zoom) { cout << "Start playerDemo" << endl; // Create game auto options = GameOptions{"My Game", sf::Vector2i(512, 512), zoom, 50}; auto game = new Game(options); // Create Keyboard Events auto upPressed = new OnKeyPress(sf::Keyboard::Up); auto downPressed = new OnKeyPress(sf::Keyboard::Down); auto leftPressed = new OnKeyPress(sf::Keyboard::Left); auto rightPressed = new OnKeyPress(sf::Keyboard::Right); // Create Game World auto world = GameWorldFactory::CreateGameWorld(game, "res/maps/testmap/tilemap.json", "", "res/maps/testmap/tile_"); game->SetWorld(world); // Create Player entity and Rotating child entity auto tex = AssetManager::GetTexture("res/textures/sample.png"); auto ent = new PlayerEntity(game, tex, 2.0, upPressed, downPressed, leftPressed, rightPressed); // Layout entities in scene auto scene = new SceneGraph(game); auto parent = scene->AddEntity(ent); scene->AddEntity(ent, parent); // Send Events to controller game->AddEvent(upPressed); game->AddEvent(downPressed); game->AddEvent(leftPressed); game->AddEvent(rightPressed); // Run Game game->Run(); return 0; }
[ "a.markoczy@gmail.com" ]
a.markoczy@gmail.com