blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
6a71ba49ce9b65e6cc45b7e41e67d24fa6d7f2d0
630eae98c295889104a0a3828a10aafb579d70fe
/tests/smoozikxml/simplehttpserver.cpp
b092e151f0af223ff9500cfde0e309c68730eb21
[]
no_license
noviware/libsmoozik-qt
b7a927f577310a7854cb1c366a37402859ec8bc5
3bd5169f9e028724e60f982769645e72800691f1
refs/heads/master
2016-09-06T10:34:51.577488
2013-09-13T12:34:57
2013-09-13T12:34:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,465
cpp
/* Copyright 2013 Noviware SARL. - Primarily authored by Fabien Pierre-Nicolas This file is part of libsmoozk-qt. libsmoozk-qt is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. libsmoozk-qt is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libsmoozk-qt. If not, see <http://www.gnu.org/licenses/>. */ #include "simplehttpserver.h" #include <QStringList> SimpleHttpServer::SimpleHttpServer(quint16 port, QObject* parent) : QTcpServer(parent) { listen(QHostAddress("127.0.0.1"), port); } void SimpleHttpServer::incomingConnection(int socket) { // When a new client connects, the server constructs a QTcpSocket and all // communication with the client is done over this QTcpSocket. QTcpSocket // works asynchronously, this means that all the communication is done // in the two slots readClient() and discardClient(). QTcpSocket* s = new QTcpSocket(this); connect(s, SIGNAL(readyRead()), this, SLOT(readClient())); connect(s, SIGNAL(disconnected()), this, SLOT(discardClient())); s->setSocketDescriptor(socket); } void SimpleHttpServer::readClient() { // This slot is called when the client sent data to the server. The // server looks if it was a get request and sends a very simple HTML // document back. QTcpSocket* socket = (QTcpSocket*) sender(); if (socket->canReadLine()) { QStringList tokens = QString(socket->readLine()).split(QRegExp("[ \r\n][ \r\n]*")); if (tokens[0] == "GET") { QTextStream os(socket); os.setAutoDetectUnicode(true); os << "HTTP/1.0 200 Ok\r\n" "Content-Type: text/html; charset=\"utf-8\"\r\n" "\r\n" << response() << "\n"; socket->close(); if (socket->state() == QTcpSocket::UnconnectedState) { delete socket; } } } } void SimpleHttpServer::discardClient() { QTcpSocket* socket = (QTcpSocket*) sender(); socket->deleteLater(); }
[ "fpierrenicolas@noviware.com" ]
fpierrenicolas@noviware.com
d15acb95d82f4061947c236ee097e44e73544236
887f3a72757ff8f691c1481618944b727d4d9ff5
/third_party/gecko_1.8/linux/gecko_sdk/include/nsIDOMText.h
97df984a00485053cda979ab261216c89fb04cac
[]
no_license
zied-ellouze/gears
329f754f7f9e9baa3afbbd652e7893a82b5013d1
d3da1ed772ed5ae9b82f46f9ecafeb67070d6899
refs/heads/master
2020-04-05T08:27:05.806590
2015-09-03T13:07:39
2015-09-03T13:07:39
41,813,794
1
0
null
null
null
null
UTF-8
C++
false
false
2,635
h
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM /builds/moz-1-8-branch/mozilla/dom/public/idl/core/nsIDOMText.idl */ #ifndef __gen_nsIDOMText_h__ #define __gen_nsIDOMText_h__ #ifndef __gen_nsIDOMCharacterData_h__ #include "nsIDOMCharacterData.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif /* starting interface: nsIDOMText */ #define NS_IDOMTEXT_IID_STR "a6cf9082-15b3-11d2-932e-00805f8add32" #define NS_IDOMTEXT_IID \ {0xa6cf9082, 0x15b3, 0x11d2, \ { 0x93, 0x2e, 0x00, 0x80, 0x5f, 0x8a, 0xdd, 0x32 }} class NS_NO_VTABLE nsIDOMText : public nsIDOMCharacterData { public: NS_DEFINE_STATIC_IID_ACCESSOR(NS_IDOMTEXT_IID) /** * The nsIDOMText interface inherits from nsIDOMCharacterData and represents * the textual content (termed character data in XML) of an Element or Attr. * * For more information on this interface please see * http://www.w3.org/TR/DOM-Level-2-Core/ * * @status FROZEN */ /* nsIDOMText splitText (in unsigned long offset) raises (DOMException); */ NS_IMETHOD SplitText(PRUint32 offset, nsIDOMText **_retval) = 0; }; /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIDOMTEXT \ NS_IMETHOD SplitText(PRUint32 offset, nsIDOMText **_retval); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIDOMTEXT(_to) \ NS_IMETHOD SplitText(PRUint32 offset, nsIDOMText **_retval) { return _to SplitText(offset, _retval); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIDOMTEXT(_to) \ NS_IMETHOD SplitText(PRUint32 offset, nsIDOMText **_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->SplitText(offset, _retval); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsDOMText : public nsIDOMText { public: NS_DECL_ISUPPORTS NS_DECL_NSIDOMTEXT nsDOMText(); private: ~nsDOMText(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsDOMText, nsIDOMText) nsDOMText::nsDOMText() { /* member initializers and constructor code */ } nsDOMText::~nsDOMText() { /* destructor code */ } /* nsIDOMText splitText (in unsigned long offset) raises (DOMException); */ NS_IMETHODIMP nsDOMText::SplitText(PRUint32 offset, nsIDOMText **_retval) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #endif /* __gen_nsIDOMText_h__ */
[ "gears.daemon@fe895e04-df30-0410-9975-d76d301b4276" ]
gears.daemon@fe895e04-df30-0410-9975-d76d301b4276
840ffb5b07e89c1a75caa70bcb8a61c652af1bea
20138076fa90c707ab2c413b060a5741cd7d8fd2
/LocalizationMod/logger.cpp
629a378457e36edfb61ddedd29ea79188a7617f0
[ "MIT" ]
permissive
ZaneYork/CubeWorldMods
bd5d95ab1a4c0fe478b2827f2952c9b6ef23963f
5a86178f70505c02924bca86c718a5b93427c31f
refs/heads/master
2021-07-06T21:05:35.398261
2020-12-23T03:03:58
2020-12-23T03:03:58
214,765,179
5
1
null
null
null
null
GB18030
C++
false
false
7,000
cpp
//logger.cpp #include "logger.h" #include <time.h> #include <stdarg.h> #include <direct.h> #include <vector> using std::string; using std::vector; namespace LOGGER { CLogger::CLogger(EnumLogLevel nLogLevel, const std::string strLogPath, const std::string strLogName) :m_nLogLevel(nLogLevel), m_strLogPath(strLogPath), m_strLogName(strLogName) { //初始化 m_pFileStream = NULL; if (m_strLogPath.empty()) { m_strLogPath = GetAppPathA(); } if (m_strLogPath[m_strLogPath.length()-1] != '\\') { m_strLogPath.append("\\"); } //创建文件夹 //MakeSureDirectoryPathExists(m_strLogPath.c_str()); //创建日志文件 if (m_strLogName.empty()) { time_t curTime; time(&curTime); tm tm1; localtime_s(&tm1, &curTime); //日志的名称如:201601012130.log m_strLogName = FormatString("%04d%02d%02d_%02d%02d%02d.log", tm1.tm_year + 1900, tm1.tm_mon + 1, tm1.tm_mday, tm1.tm_hour, tm1.tm_min, tm1.tm_sec); } m_strLogFilePath = m_strLogPath.append(m_strLogName); //以追加的方式打开文件流 fopen_s(&m_pFileStream, m_strLogFilePath.c_str(), "a+"); InitializeCriticalSection(&m_cs); } //析构函数 CLogger::~CLogger() { //释放临界区 DeleteCriticalSection(&m_cs); //关闭文件流 if (m_pFileStream) { fclose(m_pFileStream); m_pFileStream = NULL; } } //文件全路径得到文件名 const char *CLogger::path_file(const char *path, char splitter) { return strrchr(path, splitter) ? strrchr(path, splitter) + 1 : path; } //写严重错误信息 void CLogger::TraceFatal(const char *lpcszFormat, ...) { //判断当前的写日志级别 if (EnumLogLevel::LogLevel_Fatal > m_nLogLevel) return; string strResult; if (NULL != lpcszFormat) { va_list marker = NULL; va_start(marker, lpcszFormat); //初始化变量参数 size_t nLength = _vscprintf(lpcszFormat, marker) + 1; //获取格式化字符串长度 std::vector<char> vBuffer(nLength, '\0'); //创建用于存储格式化字符串的字符数组 int nWritten = _vsnprintf_s(&vBuffer[0], vBuffer.size(), nLength, lpcszFormat, marker); if (nWritten > 0) { strResult = &vBuffer[0]; } va_end(marker); //重置变量参数 } if (strResult.empty()) { return; } string strLog = strFatalPrefix; strLog.append(GetTime()).append(strResult); //写日志文件 Trace(strLog); } //写错误信息 void CLogger::TraceError(const char *lpcszFormat, ...) { //判断当前的写日志级别 if (EnumLogLevel::LogLevel_Error > m_nLogLevel) return; string strResult; if (NULL != lpcszFormat) { va_list marker = NULL; va_start(marker, lpcszFormat); //初始化变量参数 size_t nLength = _vscprintf(lpcszFormat, marker) + 1; //获取格式化字符串长度 std::vector<char> vBuffer(nLength, '\0'); //创建用于存储格式化字符串的字符数组 int nWritten = _vsnprintf_s(&vBuffer[0], vBuffer.size(), nLength, lpcszFormat, marker); if (nWritten > 0) { strResult = &vBuffer[0]; } va_end(marker); //重置变量参数 } if (strResult.empty()) { return; } string strLog = strErrorPrefix; strLog.append(GetTime()).append(strResult); //写日志文件 Trace(strLog); } //写警告信息 void CLogger::TraceWarning(const char *lpcszFormat, ...) { //判断当前的写日志级别 if (EnumLogLevel::LogLevel_Warning > m_nLogLevel) return; string strResult; if (NULL != lpcszFormat) { va_list marker = NULL; va_start(marker, lpcszFormat); //初始化变量参数 size_t nLength = _vscprintf(lpcszFormat, marker) + 1; //获取格式化字符串长度 std::vector<char> vBuffer(nLength, '\0'); //创建用于存储格式化字符串的字符数组 int nWritten = _vsnprintf_s(&vBuffer[0], vBuffer.size(), nLength, lpcszFormat, marker); if (nWritten > 0) { strResult = &vBuffer[0]; } va_end(marker); //重置变量参数 } if (strResult.empty()) { return; } string strLog = strWarningPrefix; strLog.append(GetTime()).append(strResult); //写日志文件 Trace(strLog); } //写一般信息 void CLogger::TraceInfo(const char *lpcszFormat, ...) { //判断当前的写日志级别 if (EnumLogLevel::LogLevel_Info > m_nLogLevel) return; string strResult; if (NULL != lpcszFormat) { va_list marker = NULL; va_start(marker, lpcszFormat); //初始化变量参数 size_t nLength = _vscprintf(lpcszFormat, marker) + 1; //获取格式化字符串长度 std::vector<char> vBuffer(nLength, '\0'); //创建用于存储格式化字符串的字符数组 int nWritten = _vsnprintf_s(&vBuffer[0], vBuffer.size(), nLength, lpcszFormat, marker); if (nWritten > 0) { strResult = &vBuffer[0]; } va_end(marker); //重置变量参数 } if (strResult.empty()) { return; } string strLog = strInfoPrefix; strLog.append(GetTime()).append(strResult); //写日志文件 Trace(strLog); } //获取系统当前时间 string CLogger::GetTime() { time_t curTime; time(&curTime); tm tm1; localtime_s(&tm1, &curTime); //2016-01-01 21:30:00 string strTime = FormatString("%04d-%02d-%02d %02d:%02d:%02d ", tm1.tm_year + 1900, tm1.tm_mon + 1, tm1.tm_mday, tm1.tm_hour, tm1.tm_min, tm1.tm_sec); return strTime; } //改变写日志级别 void CLogger::ChangeLogLevel(EnumLogLevel nLevel) { m_nLogLevel = nLevel; } //写文件操作 void CLogger::Trace(const string &strLog) { try { //进入临界区 EnterCriticalSection(&m_cs); //若文件流没有打开,则重新打开 if (NULL == m_pFileStream) { fopen_s(&m_pFileStream, m_strLogFilePath.c_str(), "a+"); if (!m_pFileStream) { return; } } //写日志信息到文件流 fprintf(m_pFileStream, "%s\n", strLog.c_str()); fflush(m_pFileStream); //离开临界区 LeaveCriticalSection(&m_cs); } //若发生异常,则先离开临界区,防止死锁 catch (...) { LeaveCriticalSection(&m_cs); } } string CLogger::GetAppPathA() { char szFilePath[MAX_PATH] = { 0 }, szDrive[MAX_PATH] = { 0 }, szDir[MAX_PATH] = { 0 }, szFileName[MAX_PATH] = { 0 }, szExt[MAX_PATH] = { 0 }; GetModuleFileNameA(NULL, szFilePath, sizeof(szFilePath)); _splitpath_s(szFilePath, szDrive, szDir, szFileName, szExt); string str(szDrive); str.append(szDir); return str; } string CLogger::FormatString(const char *lpcszFormat, ...) { string strResult; if (NULL != lpcszFormat) { va_list marker = NULL; va_start(marker, lpcszFormat); //初始化变量参数 size_t nLength = _vscprintf(lpcszFormat, marker) + 1; //获取格式化字符串长度 std::vector<char> vBuffer(nLength, '\0'); //创建用于存储格式化字符串的字符数组 int nWritten = _vsnprintf_s(&vBuffer[0], vBuffer.size(), nLength, lpcszFormat, marker); if (nWritten > 0) { strResult = &vBuffer[0]; } va_end(marker); //重置变量参数 } return strResult; } }
[ "ZaneYork@qq.com" ]
ZaneYork@qq.com
df2ef0347ca8994b613abe6f98aa771947aa4b68
2c378ab9a3099d9286df6bbf7abe2ee3aa69ddcb
/old_bak/ClientEngine/UI/src/UIDialog.cpp
e3ca0f3c36938fd1027be801aa1d87dfd5edd974
[]
no_license
kerasking/HHHH
524bbbaabc26443cda7b29ca19aef7e9c1047a42
3c53a7e753ccf60c8c95121b3c4871df0aad315b
refs/heads/master
2021-05-26T18:18:43.087367
2012-12-28T02:50:52
2012-12-28T02:50:52
8,725,602
1
0
null
null
null
null
UTF-8
C++
false
false
7,592
cpp
/* * UIDialog.cpp * SMYS * * Created by jhzheng on 12-2-22. * Copyright 2012 __MyCompanyName__. All rights reserved. * */ #include "UIDialog.h" #include "NDTextNode.h" #include "NDDirector.h" #include "NDUtility.h" #include "NDUILoad.h" #include "CGPointExtension.h" IMPLEMENT_CLASS(CUIDlgOptBtn, NDUIButton) CUIDlgOptBtn::CUIDlgOptBtn() { m_textHpyerlink = NULL; m_sprTip = NULL; } CUIDlgOptBtn::~CUIDlgOptBtn() { } void CUIDlgOptBtn::Initialization() { NDUIButton::Initialization(); this->CloseFrame(); CGSize winsize = NDDirector::DefaultDirector()->GetWinSize(); CGRect rect = CGRectMake(0, 0, winsize.width * 0.04, winsize.height * 0.125); m_sprTip = new CUISpriteNode; m_sprTip->Initialization(); m_sprTip->SetFrameRect(rect); m_sprTip->ChangeSprite(GetAniPath("button.spr")); this->AddChild(m_sprTip); m_textHpyerlink = new CUIHyperlinkText; m_textHpyerlink->Initialization(); m_textHpyerlink->SetFrameRect(CGRectMake(rect.size.width, 0, 0, 0)); this->AddChild(m_textHpyerlink); } void CUIDlgOptBtn::SetFrameRect(CGRect rect) { if (m_sprTip) { CGRect rectSprite = m_sprTip->GetFrameRect(); rectSprite.size.height = rect.size.height; m_sprTip->SetFrameRect(rectSprite); } NDUIButton::SetFrameRect(rect); } void CUIDlgOptBtn::SetBoundRect(CGRect rect) { if (!m_textHpyerlink) { return; } if (m_sprTip) { CGRect rectTip = m_sprTip->GetFrameRect(); rect.origin.x = rectTip.size.width; rect.origin.y = 0; rect.size.width = rect.size.width - rectTip.size.width; } m_textHpyerlink->SetLinkBoundRect(rect); } void CUIDlgOptBtn::SetLinkText(const char* text) { if (!m_textHpyerlink) { return; } std::string strText = text ? text : ""; m_textHpyerlink->SetLinkText(strText.c_str()); CGRect rect = this->GetFrameRect(); rect.size.width = 0; if (m_sprTip) { rect.size.width += m_sprTip->GetFrameRect().size.width; } if (m_textHpyerlink) { rect.size.width += m_textHpyerlink->GetFrameRect().size.width; } this->SetFrameRect(rect); } void CUIDlgOptBtn::SetLinkTextFontSize(unsigned int uiFontSize) { if (!m_textHpyerlink) { return; } m_textHpyerlink->SetLinkTextFontSize(uiFontSize); } void CUIDlgOptBtn::SetLinkTextColor(ccColor4B color) { if (!m_textHpyerlink) { return; } m_textHpyerlink->SetLinkTextColor(color); } ////////////////////////////////////////////////////////////////////// const unsigned long ID_TASKCHAT_CTRL_UI_TEXT_NPC_INFO = 8; const unsigned long ID_TASKCHAT_CTRL_PICTURE_7 = 7; const unsigned long ID_TASKCHAT_CTRL_BUTTON_CLOSE = 6; const unsigned long ID_TASKCHAT_CTRL_UI_TEXT_INFO = 5; const unsigned long ID_TASKCHAT_CTRL_PICTURE_NPC = 3; const unsigned long ID_TASKCHAT_CTRL_TEXT_NPC_NAME = 2; const unsigned long ID_TASKCHAT_CTRL_PICTURE_9 = 9; IMPLEMENT_CLASS(CUIDialog, NDUILayer) CUIDialog::CUIDialog() { m_uiOptHeight = 20 * NDDirector::DefaultDirector()->GetScaleFactor(); } CUIDialog::~CUIDialog() { } void CUIDialog::Initialization() { NDUILayer::Initialization(); NDUILoad ui; ui.Load("TaskChat.ini", this, this, CGSizeMake(0, 0)); NDUINode* node = (NDUINode*)GetChild(ID_TASKCHAT_CTRL_PICTURE_9); if (!node) { return; } CGSize winsize = NDDirector::DefaultDirector()->GetWinSize(); CGRect rectNode = node->GetFrameRect(); this->SetFrameRect(CGRectMake((winsize.width - rectNode.size.width) / 2, (winsize.height - rectNode.size.height) / 2, rectNode.size.width, rectNode.size.height)); NDScene *scene = NDDirector::DefaultDirector()->GetRunningScene(); if (scene) { scene->AddChild(this, UI_TAG_DIALOG, UI_ZORDER_DIALOG); } } void CUIDialog::SetTitle(const char* title) { NDUINode* node = (NDUINode*)this->GetChild(ID_TASKCHAT_CTRL_TEXT_NPC_NAME); if (!node || !node->IsKindOfClass(RUNTIME_CLASS(NDUILabel))) { return; } ((NDUILabel*)node)->SetText(title); } void CUIDialog::SetContent(const char* content) { this->SetUIText(content, ID_TASKCHAT_CTRL_UI_TEXT_NPC_INFO); } void CUIDialog::SetInfo(const char* info) { this->SetUIText(info, ID_TASKCHAT_CTRL_UI_TEXT_INFO); } void CUIDialog::SetPicture(NDPicture* pic) { NDUINode* node = (NDUINode*)this->GetChild(ID_TASKCHAT_CTRL_PICTURE_NPC); if (!node || !node->IsKindOfClass(RUNTIME_CLASS(NDUIImage))) { return; } ((NDUIImage*)node)->SetPicture(pic, true); } void CUIDialog::SetOptions(VEC_DLG_OPTION& vOpt) { ClrOption(); for (VEC_DLG_OPTION_IT it = vOpt.begin(); it != vOpt.end(); it++) { AddOption(*it); } } void CUIDialog::AddOption(DLGOPION& dlgOpt) { this->AddOpt(dlgOpt.strOption.c_str(), dlgOpt.nAction); } void CUIDialog::AddOption(const char* opt, int nAction) { this->AddOpt(opt, nAction); } unsigned int CUIDialog::GetOptionCount() { return m_vUiOpt.size(); } void CUIDialog::ClearOptions() { ClrOption(); } void CUIDialog::Close() { this->RemoveFromParent(true); } void CUIDialog::OnClickOpt(int nOptIndex) { NDLog(@"\nDialog click [%d]", nOptIndex); } bool CUIDialog::OnClose() { return true; } void CUIDialog::ClrOption() { for (VEC_UI_OPT_IT it = m_vUiOpt.begin(); it != m_vUiOpt.end(); it++) { (*it)->RemoveFromParent(true); } m_vUiOpt.clear(); m_vId.clear(); } void CUIDialog::AddOpt(const char* text, int nAction) { if (!text) { return; } NDUINode* node = (NDUINode*)this->GetChild(ID_TASKCHAT_CTRL_PICTURE_7); if (!node || !node->IsKindOfClass(RUNTIME_CLASS(NDUIImage))) { return; } CGRect rectNode = node->GetFrameRect(); CGSize winsize = NDDirector::DefaultDirector()->GetWinSize(); CGRect rect; rect.origin = ccpAdd(rectNode.origin, ccp(0, winsize.height * 0.047f + m_vUiOpt.size() * m_uiOptHeight + rectNode.size.height)); rect.size = CGSizeMake(rectNode.size.width, m_uiOptHeight); CUIDlgOptBtn *uiOpt = new CUIDlgOptBtn; uiOpt->Initialization(); uiOpt->SetFrameRect(rect); uiOpt->SetBoundRect(rect); uiOpt->SetLinkTextFontSize(14); uiOpt->SetLinkTextColor(ccc4(255, 255, 0, 255)); uiOpt->SetLinkText(text); uiOpt->SetDelegate(this); this->AddChild(uiOpt); m_vUiOpt.push_back(uiOpt); m_vId.push_back(nAction); } void CUIDialog::SetUIText(const char* text, int nTag) { NDUINode* node = (NDUINode*)this->GetChild(nTag); if (!node || !node->IsKindOfClass(RUNTIME_CLASS(NDUIText))) { return; } CGRect rect = node->GetFrameRect(); unsigned int uiFontSize = ((NDUIText*)node)->GetFontSize(); ccColor4B color = ((NDUIText*)node)->GetFontColor(); this->RemoveChild(nTag, true); if (!text || 0 == strlen(text)) { NDUIText *uitext = new NDUIText; uitext->Initialization(false); uitext->SetFrameRect(rect); uitext->SetFontSize(uiFontSize); uitext->SetFontColor(color); uitext->SetTag(nTag); this->AddChild(uitext); uitext->SetVisible(this->IsVisibled()); return; } NDUIText* uitext = NDUITextBuilder::DefaultBuilder()->Build( text, uiFontSize, rect.size, color, false, false); uitext->SetFrameRect(rect); uitext->SetTag(nTag); uitext->SetFontSize(uiFontSize); uitext->SetFontColor(color); this->AddChild(uitext); uitext->SetVisible(this->IsVisibled()); } void CUIDialog::OnButtonClick(NDUIButton* button) { size_t size = m_vUiOpt.size(); for (size_t i = 0; i < size; i++) { if ( m_vUiOpt[i] == button ) { OnClickOpt(i); break; } } } bool CUIDialog::OnTargetBtnEvent(NDUINode* uinode, int targetEvent) { NDUINode* node = (NDUINode*)this->GetChild(ID_TASKCHAT_CTRL_BUTTON_CLOSE); if (node == uinode) { if (OnClose()) { Close(); } return true; } return false; }
[ "hubris6965@hotmail.com" ]
hubris6965@hotmail.com
1c25f082a9cd1c657725ac42d6d8b68b4dccabc1
036475befc2a953e5f7491d864d82443163294a7
/Material.h
408e5a57cf7cb1fbc162cc24f5b152ac920300c3
[]
no_license
whirlcache/BasicOpenGL
d3d80320ee09c433f7fa77c29088e702bff708ae
47bb08db69b0b2317de442b680808f3944804918
refs/heads/master
2022-12-08T14:15:50.634304
2020-09-02T08:22:54
2020-09-02T08:22:54
283,445,135
0
0
null
null
null
null
UTF-8
C++
false
false
374
h
#pragma once #include "Global.h" #include "Shader.h" class Material { public: Material(); Material(Shader shader); ~Material(); void SetMat4(const GLchar*, glm::mat4); void SetVec3(const GLchar*, glm::vec3); void SetInt(const GLchar*, int); void Render(); void SetTexture(const GLchar* src); private: Shader shader; GLuint texture = NULL; };
[ "max.jan@qq.com" ]
max.jan@qq.com
a92f6f6d388b2bf42709e0e66cbfeba83db8aec4
34d3d20d8c1e788ea214f0041be051499ba4e4ba
/US Constitution/WordMap.cpp
08e891497baf9f2ddf697c99ba4de91fa317b79c
[]
no_license
RKBOSAMIA/Cpp-Applications
73e1f2669d8b375399516e2655a0cc748041862d
177fc1fd602826934a93ffda4dbf36f7396f22cc
refs/heads/master
2022-11-18T08:38:20.093834
2020-07-16T20:09:11
2020-07-16T20:09:11
280,246,001
0
0
null
null
null
null
UTF-8
C++
false
false
902
cpp
#include "WordMap.h" void WordMap :: insert(const string text) { steady_clock::time_point start_time = steady_clock::now(); map<string,Word>:: iterator it = find(text); if(find(text) == end()) { map<string, Word>::insert({text,Word(text)}); } else { at(text).increment_count(); } steady_clock::time_point end_time = steady_clock::now(); this->increment_elapsed_time(start_time,end_time); } map<string, Word>::iterator WordMap::search(const string text) { steady_clock::time_point start_time = steady_clock::now(); map<string,Word>:: iterator it = find(text); steady_clock::time_point end_time = steady_clock::now(); this->increment_elapsed_time(start_time,end_time); return it; } int WordMap :: get_count(const string text) const { Word word = find(text)->second; int count = word.get_count(); return count; }
[ "noreply@github.com" ]
noreply@github.com
aa39be12fc5e135db3d3e899456302a9fd85077c
7fd5e6156d6a42b305809f474659f641450cea81
/boost/serialization/nvp.hpp
27e1bf8ffaec986798e3e2cbecdd27a1fe22131e
[]
no_license
imos/icfpc2015
5509b6cfc060108c9e5df8093c5bc5421c8480ea
e998055c0456c258aa86e8379180fad153878769
refs/heads/master
2020-04-11T04:30:08.777739
2015-08-10T11:53:12
2015-08-10T11:53:12
40,011,767
8
0
null
null
null
null
UTF-8
C++
false
false
4,488
hpp
#ifndef BOOST_SERIALIZATION_NVP_HPP #define BOOST_SERIALIZATION_NVP_HPP // MS compatible compilers support #pragma once #if defined(_MSC_VER) # pragma once #endif /////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 // nvp.hpp: interface for serialization system. // (C) Copyright 2002 Robert Ramey - http://www.rrsd.com . // Use, modification and distribution is subject to the Boost Software // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org for updates, documentation, and revision history. #include <utility> #include "boost/config.hpp" #include "boost/detail/workaround.hpp" #include "boost/mpl/integral_c.hpp" #include "boost/mpl/integral_c_tag.hpp" #include "boost/serialization/level.hpp" #include "boost/serialization/tracking.hpp" #include "boost/serialization/split_member.hpp" #include "boost/serialization/base_object.hpp" #include "boost/serialization/traits.hpp" #include "boost/serialization/wrapper.hpp" namespace boost { namespace serialization { template<class T> struct nvp : public std::pair<const char *, T *>, public wrapper_traits<const nvp< T > > { explicit nvp(const char * name_, T & t) : // note: redundant cast works around borland issue // note: added _ to suppress useless gcc warning std::pair<const char *, T *>(name_, (T*)(& t)) {} nvp(const nvp & rhs) : // note: redundant cast works around borland issue std::pair<const char *, T *>(rhs.first, (T*)rhs.second) {} const char * name() const { return this->first; } T & value() const { return *(this->second); } const T & const_value() const { return *(this->second); } // True64 compiler complains with a warning about the use of // the name "Archive" hiding some higher level usage. I'm sure this // is an error but I want to accomodated as it generates a long warning // listing and might be related to a lot of test failures. // default treatment for name-value pairs. The name is // just discarded and only the value is serialized. template<class Archivex> void save( Archivex & ar, const unsigned int /* file_version */ ) const { // CodeWarrior 8.x can't seem to resolve the << op for a rhs of "const T *" ar.operator<<(const_value()); } template<class Archivex> void load( Archivex & ar, const unsigned int /* file_version */ ){ // CodeWarrior 8.x can't seem to resolve the >> op for a rhs of "const T *" ar.operator>>(value()); } BOOST_SERIALIZATION_SPLIT_MEMBER() }; template<class T> inline #ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING const #endif nvp< T > make_nvp(const char * name, T & t){ return nvp< T >(name, t); } // to maintain efficiency and portability, we want to assign // specific serialization traits to all instances of this wrappers. // we can't strait forward method below as it depends upon // Partial Template Specialization and doing so would mean that wrappers // wouldn't be treated the same on different platforms. This would // break archive portability. Leave this here as reminder not to use it !!! template <class T> struct implementation_level<nvp< T > > { typedef mpl::integral_c_tag tag; typedef mpl::int_<object_serializable> type; BOOST_STATIC_CONSTANT(int, value = implementation_level::type::value); }; // nvp objects are generally created on the stack and are never tracked template<class T> struct tracking_level<nvp< T > > { typedef mpl::integral_c_tag tag; typedef mpl::int_<track_never> type; BOOST_STATIC_CONSTANT(int, value = tracking_level::type::value); }; } // seralization } // boost #include "boost/preprocessor/stringize.hpp" #define BOOST_SERIALIZATION_NVP(name) \ boost::serialization::make_nvp(BOOST_PP_STRINGIZE(name), name) /**/ #define BOOST_SERIALIZATION_BASE_OBJECT_NVP(name) \ boost::serialization::make_nvp( \ BOOST_PP_STRINGIZE(name), \ boost::serialization::base_object<name >(*this) \ ) /**/ #endif // BOOST_SERIALIZATION_NVP_HPP
[ "git@imoz.jp" ]
git@imoz.jp
5a933f5e85a9d03c40319ad560f542333bf45c42
6f5a476a54c6ee345ab3e5ae9783c66599496e96
/src/engine/win/os.cpp
00ff06273146915bccaa044d0a6d937b2619f7f3
[ "MIT" ]
permissive
zspark/LumixEngine
78fb6bbe3811a22dd238204ca00e5e5bf611840a
78e8d8f1b2ba5e3eaa94a82c5c65d24499bb5861
refs/heads/master
2020-12-14T15:28:23.579041
2020-01-17T19:56:43
2020-01-17T19:56:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
27,318
cpp
#include "engine/allocator.h" #include "engine/log.h" #include "engine/lumix.h" #include "engine/os.h" #include "engine/path_utils.h" #include "engine/string.h" #define UNICODE #pragma warning(push) #pragma warning(disable : 4091) #include <ShlObj.h> #pragma warning(pop) #include <Windows.h> namespace Lumix::OS { static struct { bool finished = false; Interface* iface = nullptr; Point relative_mode_pos = {}; bool relative_mouse = false; WindowHandle win = INVALID_WINDOW; } G; InputFile::InputFile() { m_handle = (void*)INVALID_HANDLE_VALUE; static_assert(sizeof(m_handle) >= sizeof(HANDLE), ""); } OutputFile::OutputFile() { m_is_error = false; m_handle = (void*)INVALID_HANDLE_VALUE; static_assert(sizeof(m_handle) >= sizeof(HANDLE), ""); } InputFile::~InputFile() { ASSERT((HANDLE)m_handle == INVALID_HANDLE_VALUE); } OutputFile::~OutputFile() { ASSERT((HANDLE)m_handle == INVALID_HANDLE_VALUE); } bool OutputFile::open(const char* path) { m_handle = (HANDLE)::CreateFileA(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); m_is_error = INVALID_HANDLE_VALUE == m_handle; return !m_is_error; } bool InputFile::open(const char* path) { m_handle = (HANDLE)::CreateFileA(path, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); return INVALID_HANDLE_VALUE != m_handle; } void OutputFile::flush() { ASSERT(nullptr != m_handle); FlushFileBuffers((HANDLE)m_handle); } void OutputFile::close() { if (INVALID_HANDLE_VALUE != (HANDLE)m_handle) { ::CloseHandle((HANDLE)m_handle); m_handle = (void*)INVALID_HANDLE_VALUE; } } void InputFile::close() { if (INVALID_HANDLE_VALUE != (HANDLE)m_handle) { ::CloseHandle((HANDLE)m_handle); m_handle = (void*)INVALID_HANDLE_VALUE; } } bool OutputFile::write(const void* data, u64 size) { ASSERT(INVALID_HANDLE_VALUE != (HANDLE)m_handle); u64 written = 0; ::WriteFile((HANDLE)m_handle, data, (DWORD)size, (LPDWORD)&written, nullptr); m_is_error = m_is_error || size != written; return !m_is_error; } bool InputFile::read(void* data, u64 size) { ASSERT(INVALID_HANDLE_VALUE != m_handle); DWORD readed = 0; BOOL success = ::ReadFile((HANDLE)m_handle, data, (DWORD)size, (LPDWORD)&readed, nullptr); return success && size == readed; } u64 InputFile::size() const { ASSERT(INVALID_HANDLE_VALUE != m_handle); return ::GetFileSize((HANDLE)m_handle, 0); } u64 OutputFile::pos() { ASSERT(INVALID_HANDLE_VALUE != m_handle); return ::SetFilePointer((HANDLE)m_handle, 0, nullptr, FILE_CURRENT); } u64 InputFile::pos() { ASSERT(INVALID_HANDLE_VALUE != m_handle); return ::SetFilePointer((HANDLE)m_handle, 0, nullptr, FILE_CURRENT); } bool InputFile::seek(u64 pos) { ASSERT(INVALID_HANDLE_VALUE != m_handle); LARGE_INTEGER dist; dist.QuadPart = pos; return ::SetFilePointer((HANDLE)m_handle, dist.u.LowPart, &dist.u.HighPart, FILE_BEGIN) != INVALID_SET_FILE_POINTER; } OutputFile& OutputFile::operator <<(const char* text) { write(text, stringLength(text)); return *this; } OutputFile& OutputFile::operator <<(i32 value) { char buf[20]; toCString(value, Span(buf)); write(buf, stringLength(buf)); return *this; } OutputFile& OutputFile::operator <<(u32 value) { char buf[20]; toCString(value, Span(buf)); write(buf, stringLength(buf)); return *this; } OutputFile& OutputFile::operator <<(u64 value) { char buf[30]; toCString(value, Span(buf)); write(buf, stringLength(buf)); return *this; } OutputFile& OutputFile::operator <<(float value) { char buf[128]; toCString(value, Span(buf), 7); write(buf, stringLength(buf)); return *this; } static void fromWChar(Span<char> out, const WCHAR* in) { const WCHAR* c = in; char* cout = out.begin(); const u32 size = out.length(); while (*c && c - in < size - 1) { *cout = (char)*c; ++cout; ++c; } *cout = 0; } template <int N> static void toWChar(WCHAR (&out)[N], const char* in) { const char* c = in; WCHAR* cout = out; while (*c && c - in < N - 1) { *cout = *c; ++cout; ++c; } *cout = 0; } template <int N> struct WCharStr { WCharStr(const char* rhs) { toWChar(data, rhs); } operator const WCHAR*() const { return data; } WCHAR data[N]; }; void logVersion() { DWORD dwVersion = 0; DWORD dwMajorVersion = 0; DWORD dwMinorVersion = 0; DWORD dwBuild = 0; dwVersion = GetVersion(); dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion))); dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion))); if (dwVersion < 0x80000000) dwBuild = (DWORD)(HIWORD(dwVersion)); logInfo("Engine") << "OS Version is " << (u32)dwMajorVersion << "." << (u32)dwMinorVersion << " (" << (u32)dwBuild << ")"; } void getDropFile(const Event& event, int idx, Span<char> out) { ASSERT(out.length() > 0); HDROP drop = (HDROP)event.file_drop.handle; WCHAR buffer[MAX_PATH]; if (DragQueryFile(drop, idx, buffer, MAX_PATH)) { fromWChar(out, buffer); } else { ASSERT(false); } } int getDropFileCount(const Event& event) { HDROP drop = (HDROP)event.file_drop.handle; return (int)DragQueryFile(drop, 0xFFFFFFFF, NULL, 0); } void finishDrag(const Event& event) { HDROP drop = (HDROP)event.file_drop.handle; DragFinish(drop); } static void processEvents() { MSG msg; while (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) { Event e; e.window = msg.hwnd; switch (msg.message) { case WM_DROPFILES: e.type = Event::Type::DROP_FILE; e.file_drop.handle = (HDROP)msg.wParam; G.iface->onEvent(e); break; case WM_QUIT: e.type = Event::Type::QUIT; G.iface->onEvent(e); break; case WM_CLOSE: e.type = Event::Type::WINDOW_CLOSE; G.iface->onEvent(e); break; case WM_KEYDOWN: e.type = Event::Type::KEY; e.key.down = true; e.key.keycode = (Keycode)msg.wParam; G.iface->onEvent(e); break; case WM_KEYUP: e.type = Event::Type::KEY; e.key.down = false; e.key.keycode = (Keycode)msg.wParam; G.iface->onEvent(e); break; case WM_CHAR: e.type = Event::Type::CHAR; e.text_input.utf32 = (u32)msg.wParam; // TODO msg.wParam is utf16, convert // e.g. https://github.com/SFML/SFML/blob/master/src/SFML/Window/Win32/WindowImplWin32.cpp#L694 G.iface->onEvent(e); break; case WM_INPUT: { HRAWINPUT hRawInput = (HRAWINPUT)msg.lParam; UINT dataSize; GetRawInputData(hRawInput, RID_INPUT, NULL, &dataSize, sizeof(RAWINPUTHEADER)); char dataBuf[1024]; if (dataSize == 0 || dataSize > sizeof(dataBuf)) break; GetRawInputData(hRawInput, RID_INPUT, dataBuf, &dataSize, sizeof(RAWINPUTHEADER)); const RAWINPUT* raw = (const RAWINPUT*)dataBuf; if (raw->header.dwType != RIM_TYPEMOUSE) break; const RAWMOUSE& mouseData = raw->data.mouse; const USHORT flags = mouseData.usButtonFlags; const short wheel_delta = (short)mouseData.usButtonData; const LONG x = mouseData.lLastX, y = mouseData.lLastY; if (wheel_delta) { e.mouse_wheel.amount = (float)wheel_delta / WHEEL_DELTA; e.type = Event::Type::MOUSE_WHEEL; G.iface->onEvent(e); } if(flags & RI_MOUSE_LEFT_BUTTON_DOWN) { e.type = Event::Type::MOUSE_BUTTON; e.mouse_button.button = MouseButton::LEFT; e.mouse_button.down = true; G.iface->onEvent(e); } if(flags & RI_MOUSE_LEFT_BUTTON_UP) { e.type = Event::Type::MOUSE_BUTTON; e.mouse_button.button = MouseButton::LEFT; e.mouse_button.down = false; G.iface->onEvent(e); } if(flags & RI_MOUSE_RIGHT_BUTTON_UP) { e.type = Event::Type::MOUSE_BUTTON; e.mouse_button.button = MouseButton::RIGHT; e.mouse_button.down = false; G.iface->onEvent(e); } if(flags & RI_MOUSE_RIGHT_BUTTON_DOWN) { e.type = Event::Type::MOUSE_BUTTON; e.mouse_button.button = MouseButton::RIGHT; e.mouse_button.down = true; G.iface->onEvent(e); } if(flags & RI_MOUSE_MIDDLE_BUTTON_UP) { e.type = Event::Type::MOUSE_BUTTON; e.mouse_button.button = MouseButton::MIDDLE; e.mouse_button.down = false; G.iface->onEvent(e); } if(flags & RI_MOUSE_MIDDLE_BUTTON_DOWN) { e.type = Event::Type::MOUSE_BUTTON; e.mouse_button.button = MouseButton::MIDDLE; e.mouse_button.down = true; G.iface->onEvent(e); } if (x != 0 || y != 0) { e.type = Event::Type::MOUSE_MOVE; e.mouse_move.xrel = x; e.mouse_move.yrel = y; G.iface->onEvent(e); } break; } } TranslateMessage(&msg); DispatchMessage(&msg); } } void destroyWindow(WindowHandle window) { DestroyWindow((HWND)window); G.win = INVALID_WINDOW; } void UTF32ToUTF8(u32 utf32, char* utf8) { if (utf32 <= 0x7F) { utf8[0] = (char) utf32; utf8[1] = '\0'; } else if (utf32 <= 0x7FF) { utf8[0] = 0xC0 | (char) ((utf32 >> 6) & 0x1F); utf8[1] = 0x80 | (char) (utf32 & 0x3F); utf8[2] = '\0'; } else if (utf32 <= 0xFFFF) { utf8[0] = 0xE0 | (char) ((utf32 >> 12) & 0x0F); utf8[1] = 0x80 | (char) ((utf32 >> 6) & 0x3F); utf8[2] = 0x80 | (char) (utf32 & 0x3F); utf8[3] = '\0'; } else if (utf32 <= 0x10FFFF) { utf8[0] = 0xF0 | (char) ((utf32 >> 18) & 0x0F); utf8[1] = 0x80 | (char) ((utf32 >> 12) & 0x3F); utf8[2] = 0x80 | (char) ((utf32 >> 6) & 0x3F); utf8[3] = 0x80 | (char) (utf32 & 0x3F); utf8[4] = '\0'; } else { ASSERT(false); } } Point toScreen(WindowHandle win, int x, int y) { POINT p; p.x = x; p.y = y; ::ClientToScreen((HWND)win, &p); Point res; res.x = p.x; res.y = p.y; return res; } WindowHandle createWindow(const InitWindowArgs& args) { WCharStr<MAX_PATH_LENGTH> cls_name("lunex_window"); static WNDCLASS wc = [&]() -> WNDCLASS { WNDCLASS wc = {}; auto WndProc = [](HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) -> LRESULT { Event e; e.window = hWnd; switch (Msg) { case WM_MOVE: e.type = Event::Type::WINDOW_MOVE; e.win_move.x = (i16)LOWORD(lParam); e.win_move.y = (i16)HIWORD(lParam); G.iface->onEvent(e); return 0; case WM_SIZE: e.type = Event::Type::WINDOW_SIZE; e.win_size.w = LOWORD(lParam); e.win_size.h = HIWORD(lParam); G.iface->onEvent(e); return 0; case WM_CLOSE: e.type = Event::Type::WINDOW_CLOSE; G.iface->onEvent(e); return 0; case WM_ACTIVATE: if (wParam == WA_INACTIVE) { showCursor(true); unclipCursor(); } e.type = Event::Type::FOCUS; e.focus.gained = wParam != WA_INACTIVE; G.iface->onEvent(e); break; } return DefWindowProc(hWnd, Msg, wParam, lParam); }; wc.style = 0; wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = GetModuleHandle(NULL); wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = NULL; wc.lpszClassName = cls_name; if (!RegisterClass(&wc)) { ASSERT(false); return {}; } return wc; }(); HWND parent_window = (HWND)args.parent; WCharStr<MAX_PATH_LENGTH> wname(args.name); DWORD style = args.flags & InitWindowArgs::NO_DECORATION ? WS_POPUP : WS_OVERLAPPEDWINDOW ; DWORD ext_style = args.flags & InitWindowArgs::NO_TASKBAR_ICON ? WS_EX_TOOLWINDOW : WS_EX_APPWINDOW; const HWND hwnd = CreateWindowEx( ext_style, cls_name, wname, style, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, parent_window, NULL, wc.hInstance, NULL); ASSERT(hwnd); if (args.handle_file_drops) { DragAcceptFiles(hwnd, TRUE); } ShowWindow(hwnd, SW_SHOW); UpdateWindow(hwnd); if (!G.win) { RAWINPUTDEVICE device; device.usUsagePage = 0x01; device.usUsage = 0x02; device.dwFlags = RIDEV_INPUTSINK; device.hwndTarget = hwnd; BOOL status = RegisterRawInputDevices(&device, 1, sizeof(device)); ASSERT(status); } G.win = hwnd; return hwnd; } void quit() { G.finished = true; } bool isKeyDown(Keycode keycode) { const SHORT res = GetAsyncKeyState((int)keycode); return (res & 0x8000) != 0; } void getKeyName(Keycode keycode, Span<char> out) { LONG scancode = MapVirtualKey((UINT)keycode, MAPVK_VK_TO_VSC); // because MapVirtualKey strips the extended bit for some keys switch ((UINT)keycode) { case VK_LEFT: case VK_UP: case VK_RIGHT: case VK_DOWN: case VK_PRIOR: case VK_NEXT: case VK_END: case VK_HOME: case VK_INSERT: case VK_DELETE: case VK_DIVIDE: case VK_NUMLOCK: scancode |= 0x100; break; } WCHAR tmp[256]; u32 size = out.length(); ASSERT(size <= 256 && size > 0); int res = GetKeyNameText(scancode << 16, tmp, size); if (res == 0) { out[0] = 0; } else { fromWChar(out, tmp); } } void showCursor(bool show) { if (show) { while(ShowCursor(show) < 0); } else { while(ShowCursor(show) >= 0); } } void setWindowTitle(WindowHandle win, const char* title) { WCharStr<256> tmp(title); SetWindowText((HWND)win, tmp); } Rect getWindowScreenRect(WindowHandle win) { RECT rect; GetWindowRect((HWND)win, &rect); return {rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top}; } Rect getWindowClientRect(WindowHandle win) { RECT rect; BOOL status = GetClientRect((HWND)win, &rect); ASSERT(status); return {rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top}; } void setWindowScreenRect(WindowHandle win, const Rect& rect) { MoveWindow((HWND)win, rect.left, rect.top, rect.width, rect.height, TRUE); } u32 getMonitors(Span<Monitor> monitors) { struct Callback { struct Data { Span<Monitor>* monitors; u32 index; }; static BOOL CALLBACK func(HMONITOR monitor, HDC, LPRECT, LPARAM lparam) { Data* data = reinterpret_cast<Data*>(lparam); if (data->index >= data->monitors->length()) return TRUE; MONITORINFO info = { 0 }; info.cbSize = sizeof(MONITORINFO); if (!::GetMonitorInfo(monitor, &info)) return TRUE; Monitor& m = (*data->monitors)[data->index]; m.monitor_rect.left = info.rcMonitor.left; m.monitor_rect.top = info.rcMonitor.top; m.monitor_rect.width = info.rcMonitor.right - info.rcMonitor.left; m.monitor_rect.height = info.rcMonitor.bottom - info.rcMonitor.top; m.work_rect.left = info.rcWork.left; m.work_rect.top = info.rcWork.top; m.work_rect.width = info.rcWork.right - info.rcWork.left; m.work_rect.height = info.rcWork.bottom - info.rcWork.top; m.primary = info.dwFlags & MONITORINFOF_PRIMARY; ++data->index; return TRUE; } }; Callback::Data data = { &monitors, 0 }; ::EnumDisplayMonitors(NULL, NULL, &Callback::func, (LPARAM)&data); return data.index; } void setMouseScreenPos(int x, int y) { SetCursorPos(x, y); } Point getMousePos(WindowHandle win) { POINT p; BOOL b = GetCursorPos(&p); ScreenToClient((HWND)win, &p); ASSERT(b); return {p.x, p.y}; } Point getMouseScreenPos() { POINT p; BOOL b = GetCursorPos(&p); ASSERT(b); return {p.x, p.y}; } WindowHandle getFocused() { return GetActiveWindow(); } bool isMaximized(WindowHandle win) { WINDOWPLACEMENT placement; BOOL res = GetWindowPlacement((HWND)win, &placement); ASSERT(res); return placement.showCmd == SW_SHOWMAXIMIZED; } void restore(WindowHandle win, WindowState state) { SetWindowLongPtr((HWND)win, GWL_STYLE, state.style); OS::setWindowScreenRect(win, state.rect); } WindowState setFullscreen(WindowHandle win) { WindowState res; res.rect = OS::getWindowScreenRect(win); res.style = SetWindowLongPtr((HWND)win, GWL_STYLE, WS_VISIBLE | WS_POPUP); int w = GetSystemMetrics(SM_CXSCREEN); int h = GetSystemMetrics(SM_CYSCREEN); SetWindowPos((HWND)win, HWND_TOP, 0, 0, w, h, SWP_FRAMECHANGED); return res; } void maximizeWindow(WindowHandle win) { ShowWindow((HWND)win, SW_SHOWMAXIMIZED); } bool isRelativeMouseMode() { return G.relative_mouse; } void run(Interface& iface) { G.iface = &iface; G.iface->onInit(); while (!G.finished) { processEvents(); G.iface->onIdle(); } } int getDPI() { const HDC hdc = GetDC(NULL); return GetDeviceCaps(hdc, LOGPIXELSX); } u32 getMemPageSize() { SYSTEM_INFO info; GetSystemInfo(&info); return info.dwPageSize; } void* memReserve(size_t size) { return VirtualAlloc(nullptr, size, MEM_RESERVE, PAGE_READWRITE); } void memCommit(void* ptr, size_t size) { VirtualAlloc(ptr, size, MEM_COMMIT, PAGE_READWRITE); } void memRelease(void* ptr) { VirtualFree(ptr, 0, MEM_RELEASE); } struct FileIterator { HANDLE handle; IAllocator* allocator; WIN32_FIND_DATA ffd; bool is_valid; }; FileIterator* createFileIterator(const char* path, IAllocator& allocator) { char tmp[MAX_PATH_LENGTH]; copyString(tmp, path); catString(tmp, "/*"); WCharStr<MAX_PATH_LENGTH> wtmp(tmp); auto* iter = LUMIX_NEW(allocator, FileIterator); iter->allocator = &allocator; iter->handle = FindFirstFile(wtmp, &iter->ffd); iter->is_valid = iter->handle != INVALID_HANDLE_VALUE; return iter; } void destroyFileIterator(FileIterator* iterator) { FindClose(iterator->handle); LUMIX_DELETE(*iterator->allocator, iterator); } bool getNextFile(FileIterator* iterator, FileInfo* info) { if (!iterator->is_valid) return false; info->is_directory = (iterator->ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0; fromWChar(Span(info->filename), iterator->ffd.cFileName); iterator->is_valid = FindNextFile(iterator->handle, &iterator->ffd) != FALSE; return true; } void setCurrentDirectory(const char* path) { WCharStr<MAX_PATH_LENGTH> tmp(path); SetCurrentDirectory(tmp); } void getCurrentDirectory(Span<char> output) { WCHAR tmp[MAX_PATH_LENGTH]; GetCurrentDirectory(lengthOf(tmp), tmp); fromWChar(output, tmp); } bool getSaveFilename(Span<char> out, const char* filter, const char* default_extension) { WCharStr<MAX_PATH_LENGTH> wtmp(""); WCHAR wfilter[MAX_PATH_LENGTH]; const char* c = filter; WCHAR* cout = wfilter; while ((*c || *(c + 1)) && (c - filter) < MAX_PATH_LENGTH - 2) { *cout = *c; ++cout; ++c; } *cout = 0; ++cout; *cout = 0; WCharStr<MAX_PATH_LENGTH> wdefault_extension(default_extension ? default_extension : ""); OPENFILENAME ofn; ZeroMemory(&ofn, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = NULL; ofn.lpstrFile = wtmp.data; ofn.lpstrFile[0] = '\0'; ofn.nMaxFile = lengthOf(wtmp.data); ofn.lpstrFilter = wfilter; ofn.nFilterIndex = 1; ofn.lpstrDefExt = default_extension ? wdefault_extension.data : nullptr; ofn.lpstrFileTitle = NULL; ofn.nMaxFileTitle = 0; ofn.lpstrInitialDir = NULL; ofn.Flags = OFN_OVERWRITEPROMPT | OFN_NOCHANGEDIR | OFN_NONETWORKBUTTON; bool res = GetSaveFileName(&ofn) != FALSE; char tmp[MAX_PATH_LENGTH]; fromWChar(Span(tmp), wtmp); if (res) PathUtils::normalize(tmp, out); return res; } bool getOpenFilename(Span<char> out, const char* filter, const char* starting_file) { OPENFILENAME ofn; ZeroMemory(&ofn, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = NULL; if (starting_file) { char* to = out.begin(); for (const char *from = starting_file; *from; ++from, ++to) { if (to - out.begin() > out.length() - 1) break; *to = *to == '/' ? '\\' : *from; } *to = '\0'; } else { out[0] = '\0'; } WCHAR wout[MAX_PATH_LENGTH] = {}; WCHAR wfilter[MAX_PATH_LENGTH]; const char* c = filter; WCHAR* cout = wfilter; while ((*c || *(c + 1)) && (c - filter) < MAX_PATH_LENGTH - 2) { *cout = *c; ++cout; ++c; } *cout = 0; ++cout; *cout = 0; ofn.lpstrFile = wout; ofn.nMaxFile = sizeof(wout); ofn.lpstrFilter = wfilter; ofn.nFilterIndex = 1; ofn.lpstrFileTitle = NULL; ofn.nMaxFileTitle = 0; ofn.lpstrInitialDir = nullptr; ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR | OFN_NONETWORKBUTTON; const bool res = GetOpenFileName(&ofn) != FALSE; if (res) { char tmp[MAX_PATH_LENGTH]; fromWChar(Span(tmp), wout); PathUtils::normalize(tmp, out); } else { auto err = CommDlgExtendedError(); ASSERT(err == 0); } return res; } bool getOpenDirectory(Span<char> output, const char* starting_dir) { bool ret = false; IFileDialog* pfd; if (SUCCEEDED(CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pfd)))) { if (starting_dir) { PIDLIST_ABSOLUTE pidl; WCHAR wstarting_dir[MAX_PATH]; WCHAR* wc = wstarting_dir; for (const char *c = starting_dir; *c && wc - wstarting_dir < MAX_PATH - 1; ++c, ++wc) { *wc = *c == '/' ? '\\' : *c; } *wc = 0; HRESULT hresult = ::SHParseDisplayName(wstarting_dir, 0, &pidl, SFGAO_FOLDER, 0); if (SUCCEEDED(hresult)) { IShellItem* psi; hresult = ::SHCreateShellItem(NULL, NULL, pidl, &psi); if (SUCCEEDED(hresult)) { pfd->SetFolder(psi); } ILFree(pidl); } } DWORD dwOptions; if (SUCCEEDED(pfd->GetOptions(&dwOptions))) { pfd->SetOptions(dwOptions | FOS_PICKFOLDERS); } if (SUCCEEDED(pfd->Show(NULL))) { IShellItem* psi; if (SUCCEEDED(pfd->GetResult(&psi))) { WCHAR* tmp; if (SUCCEEDED(psi->GetDisplayName(SIGDN_DESKTOPABSOLUTEPARSING, &tmp))) { char* c = output.begin(); const u32 max_size = output.length(); while (*tmp && c - output.begin() < max_size - 1) { *c = (char)*tmp; ++c; ++tmp; } *c = '\0'; if (!endsWith(output.begin(), "/") && !endsWith(output.begin(), "\\") && c - output.begin() < max_size - 1) { *c = '/'; ++c; *c = '\0'; } ret = true; } psi->Release(); } } pfd->Release(); } return ret; } void copyToClipboard(const char* text) { if (!OpenClipboard(NULL)) return; int len = stringLength(text); HGLOBAL mem_handle = GlobalAlloc(GMEM_MOVEABLE, len * sizeof(char)); if (!mem_handle) return; char* mem = (char*)GlobalLock(mem_handle); copyString(Span(mem, len), text); GlobalUnlock(mem_handle); EmptyClipboard(); SetClipboardData(CF_TEXT, mem_handle); CloseClipboard(); } ExecuteOpenResult shellExecuteOpen(const char* path) { const WCharStr<MAX_PATH_LENGTH> wpath(path); const uintptr_t res = (uintptr_t)ShellExecute(NULL, NULL, wpath, NULL, NULL, SW_SHOW); if (res > 32) return ExecuteOpenResult::SUCCESS; if (res == SE_ERR_NOASSOC) return ExecuteOpenResult::NO_ASSOCIATION; return ExecuteOpenResult::OTHER_ERROR; } ExecuteOpenResult openExplorer(const char* path) { const WCharStr<MAX_PATH_LENGTH> wpath(path); const uintptr_t res = (uintptr_t)ShellExecute(NULL, L"explore", wpath, NULL, NULL, SW_SHOWNORMAL); if (res > 32) return ExecuteOpenResult::SUCCESS; if (res == SE_ERR_NOASSOC) return ExecuteOpenResult::NO_ASSOCIATION; return ExecuteOpenResult::OTHER_ERROR; } bool deleteFile(const char* path) { const WCharStr<MAX_PATH_LENGTH> wpath(path); return DeleteFile(wpath) != FALSE; } bool moveFile(const char* from, const char* to) { const WCharStr<MAX_PATH_LENGTH> wfrom(from); const WCharStr<MAX_PATH_LENGTH> wto(to); return MoveFileEx(wfrom, wto, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED) != FALSE; } size_t getFileSize(const char* path) { WIN32_FILE_ATTRIBUTE_DATA fad; const WCharStr<MAX_PATH_LENGTH> wpath(path); if (!GetFileAttributesEx(wpath, GetFileExInfoStandard, &fad)) return -1; LARGE_INTEGER size; size.HighPart = fad.nFileSizeHigh; size.LowPart = fad.nFileSizeLow; return (size_t)size.QuadPart; } bool fileExists(const char* path) { const WCharStr<MAX_PATH_LENGTH> wpath(path); DWORD dwAttrib = GetFileAttributes(wpath); return (dwAttrib != INVALID_FILE_ATTRIBUTES && !(dwAttrib & FILE_ATTRIBUTE_DIRECTORY)); } bool dirExists(const char* path) { const WCharStr<MAX_PATH_LENGTH> wpath(path); DWORD dwAttrib = GetFileAttributes(wpath); return (dwAttrib != INVALID_FILE_ATTRIBUTES && (dwAttrib & FILE_ATTRIBUTE_DIRECTORY)); } u64 getLastModified(const char* path) { const WCharStr<MAX_PATH_LENGTH> wpath(path); FILETIME ft; HANDLE handle = CreateFile(wpath, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (handle == INVALID_HANDLE_VALUE) return 0; if (GetFileTime(handle, NULL, NULL, &ft) == FALSE) { CloseHandle(handle); return 0; } CloseHandle(handle); ULARGE_INTEGER i; i.LowPart = ft.dwLowDateTime; i.HighPart = ft.dwHighDateTime; return i.QuadPart; } bool makePath(const char* path) { char tmp[MAX_PATH]; char* out = tmp; const char* in = path; while (*in && out - tmp < lengthOf(tmp) - 1) { *out = *in == '/' ? '\\' : *in; ++out; ++in; } *out = '\0'; const WCharStr<MAX_PATH_LENGTH> wpath(tmp); int error_code = SHCreateDirectoryEx(NULL, wpath, NULL); return error_code == ERROR_SUCCESS; } void clipCursor(WindowHandle win, int x, int y, int w, int h) { POINT min; POINT max; min.x = LONG(x); min.y = LONG(y); max.x = LONG(x + w); max.y = LONG(y + h); ClientToScreen((HWND)win, &min); ClientToScreen((HWND)win, &max); RECT rect; rect.left = min.x; rect.right = max.x; rect.top = min.y; rect.bottom = max.y; ClipCursor(&rect); } void unclipCursor() { ClipCursor(NULL); } bool copyFile(const char* from, const char* to) { WCHAR tmp_from[MAX_PATH]; WCHAR tmp_to[MAX_PATH]; toWChar(tmp_from, from); toWChar(tmp_to, to); if (CopyFile(tmp_from, tmp_to, FALSE) == FALSE) return false; FILETIME ft; SYSTEMTIME st; GetSystemTime(&st); SystemTimeToFileTime(&st, &ft); HANDLE handle = CreateFile(tmp_to, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); bool f = SetFileTime(handle, (LPFILETIME)NULL, (LPFILETIME)NULL, &ft) != FALSE; ASSERT(f); CloseHandle(handle); return true; } void getExecutablePath(Span<char> buffer) { WCHAR tmp[MAX_PATH]; GetModuleFileName(NULL, tmp, sizeof(tmp)); fromWChar(buffer, tmp); } void messageBox(const char* text) { WCHAR tmp[2048]; toWChar(tmp, text); MessageBox(NULL, tmp, L"Message", MB_OK); } void setCommandLine(int, char**) { ASSERT(false); } bool getCommandLine(Span<char> output) { WCHAR* cl = GetCommandLine(); fromWChar(output, cl); return true; } void* loadLibrary(const char* path) { WCHAR tmp[MAX_PATH]; toWChar(tmp, path); return LoadLibrary(tmp); } void unloadLibrary(void* handle) { FreeLibrary((HMODULE)handle); } void* getLibrarySymbol(void* handle, const char* name) { return (void*)GetProcAddress((HMODULE)handle, name); } Timer::Timer() { LARGE_INTEGER f, n; QueryPerformanceFrequency(&f); QueryPerformanceCounter(&n); first_tick = last_tick = n.QuadPart; frequency = f.QuadPart; } float Timer::getTimeSinceStart() { LARGE_INTEGER n; QueryPerformanceCounter(&n); const u64 tick = n.QuadPart; float delta = static_cast<float>((double)(tick - first_tick) / (double)frequency); return delta; } float Timer::getTimeSinceTick() { LARGE_INTEGER n; QueryPerformanceCounter(&n); const u64 tick = n.QuadPart; float delta = static_cast<float>((double)(tick - last_tick) / (double)frequency); return delta; } float Timer::tick() { LARGE_INTEGER n; QueryPerformanceCounter(&n); const u64 tick = n.QuadPart; float delta = static_cast<float>((double)(tick - last_tick) / (double)frequency); last_tick = tick; return delta; } u64 Timer::getFrequency() { static u64 freq = []() { LARGE_INTEGER f; QueryPerformanceFrequency(&f); return f.QuadPart; }(); return freq; } u64 Timer::getRawTimestamp() { LARGE_INTEGER tick; QueryPerformanceCounter(&tick); return tick.QuadPart; } } // namespace Lumix::OS
[ "mikulas.florek@gamedev.sk" ]
mikulas.florek@gamedev.sk
efb4ab43ef940d6202b0f6f70f87a6ec92b1b12c
af78aa8f32bb48839daa1f0924abdd95e186489d
/learning2018.1.4/learning2018.1.4/main.cpp
bdfd61ad4da38813b98d2a91b4799c480f3881fd
[]
no_license
BangBreakfast/bendanbang-test
ae24a6f72ae9ef0fb6320988d0b5fbce36dd6d08
c0fddbcc10806122db95025f98e5733abc79db09
refs/heads/master
2021-09-24T14:27:00.303315
2018-03-21T02:09:05
2018-03-21T02:09:05
115,427,746
1
0
null
null
null
null
UTF-8
C++
false
false
1,468
cpp
// // main.cpp // learning2018.1.4 // // Created by 高立人 on 2018/1/4. // Copyright © 2018年 高立人. All rights reserved. // #include <iostream> #include <algorithm> using namespace std; struct linknote{ int num; struct linknote *next; }; linknote *createlinklist(int n) { int a=0; linknote *link=new linknote; cin>>a; link->num=a; link->next=NULL; linknote *tail=link; for(int i=1;i<n;i++) { tail->next=new linknote; cin>>a; tail->next->num=a; tail->next->next=NULL; tail=tail->next; } return link; } void mergelinklist(linknote *a,linknote *b) { linknote *move=a; while(move->next!=NULL) { move=move->next; } move->next=b; } void outputlinklist(linknote *a) { linknote *move=a; cout<<move->num; while(move->next!=NULL) { move=move->next; cout<<' '<<move->num; } delete move; } void deletelinklist(linknote *a) { linknote *move=a; while(1) { if(a->next!=NULL) { a=a->next; delete move; move=a; } else { break; } } } int main() { int n1=0,n2=0; cin>>n1; linknote *num1=NULL; linknote *num2=NULL; num1=createlinklist(n1); cin>>n2; num2=createlinklist(n2); mergelinklist(num1,num2); outputlinklist(num1); deletelinklist(num1); return 0; }
[ "gaoliren@gaolirendeMacBook-Pro.local" ]
gaoliren@gaolirendeMacBook-Pro.local
e192e285167f9e1abbc6c6649c8ce0b42cd38854
9e61c2390580b6982cf08a6417e29d69a6acb600
/480_Sliding_Window_Median/multiset.cpp
5627d3c67d0ad3b5b3992ca5f96e398657e8e7bc
[]
no_license
acnokego/LeetCode
3027e1987cee4d130c9db7e2af4ec4de8a0f43bd
3e04e79e05ffcaf423d5a148668e132ee090596f
refs/heads/master
2021-06-07T02:39:57.956371
2019-11-30T03:45:29
2019-11-30T03:45:29
133,643,518
0
0
null
null
null
null
UTF-8
C++
false
false
798
cpp
class Solution { public: /* * Complexity: O(nlgk) * Space: O(k) */ vector<double> medianSlidingWindow(vector<int>& nums, int k) { multiset<int>window(nums.begin(), nums.begin() + k); auto mid = next(window.begin(), k / 2); vector<double>ans; for(int i = k; i < nums.size(); ++i){ ans.push_back((double(*mid) + *prev(mid, 1-k%2)) / 2); window.insert(nums[i]); // insert if(*mid > nums[i]){ --mid; } // erase if( *mid >= nums[i-k]){ ++mid; } window.erase(window.lower_bound(nums[i-k])); } ans.push_back((double(*mid) + *prev(mid, 1-k%2)) / 2);; return ans; } };
[ "yuandychen@gmail.com" ]
yuandychen@gmail.com
8d94d470ee313ef1fdf3d473d9dc607aca93e8e0
548b10bf1d373eb461f907655a97ef7301b6e95e
/H264_camera/h264_xu_ctrls.cpp
089bab6d95ce18a9ff337fa8a27e7d0116445f64
[]
no_license
MagicPrince666/fpv_tx
3c846bb772416955bdc28bcde8d3b85d338e2256
8e7ed85401c49be5a63688a60328778e5540f5c1
refs/heads/master
2020-03-06T15:13:58.766443
2018-04-09T01:52:41
2018-04-09T01:52:41
126,951,924
2
1
null
null
null
null
UTF-8
C++
false
false
155,370
cpp
/***************************************************************************************** * 文件名 h264_xu_ctrls.cpp * 描述 :uvc摄像头控制 * 平台 :linux * 版本 :V1.0.0 * 作者 :Leo Huang QQ:846863428 * 邮箱 :Leo.huang@junchentech.cn * 修改时间 :2017-06-28 *****************************************************************************************/ #define N_(x) x #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <sys/ioctl.h> #include "h264_xu_ctrls.h" #include "debug.h" extern struct H264Format *gH264fmt; unsigned char m_CurrentFPS = 24; unsigned char m_CurrentFPS_9422 = 30; unsigned int chip_id = CHIP_NONE; #define Default_fwLen 13 const unsigned char Default_fwData[Default_fwLen] = {0x05, 0x00, 0x02, 0xD0, 0x01, // W=1280, H=720, NumOfFrmRate=1 0xFF, 0xFF, 0xFF, 0xFF, // Frame size 0x07, 0xA1, 0xFF, 0xFF, // 20 }; #define LENGTH_OF_RERVISION_XU_SYS_CTR (7) #define LENGTH_OF_RERVISION_XU_USR_CTR (9) #define RERVISION_RER9420_SERIES_CHIPID 0x90 #define RERVISION_RER9422_SERIES_CHIPID 0x92 #define RERVISION_RER9422_DDR_64M 0x00 #define RERVISION_RER9422_DDR_16M 0x03 extern int video_get_framerate(int dev, int *framerate); static struct uvc_xu_control_info rervision_xu_sys_ctrls[] = { { entity : UVC_GUID_RERVISION_SYS_HW_CTRL, index : 0, selector : XU_RERVISION_SYS_ASIC_RW, size : 4, flags : UVC_CONTROL_SET_CUR | UVC_CONTROL_GET_MIN | UVC_CONTROL_GET_MAX | UVC_CONTROL_GET_DEF | UVC_CONTROL_AUTO_UPDATE | UVC_CONTROL_GET_CUR }, { entity : UVC_GUID_RERVISION_SYS_HW_CTRL, index : 1, selector : XU_RERVISION_SYS_FRAME_INFO, size : 11, flags : UVC_CONTROL_SET_CUR | UVC_CONTROL_GET_MIN | UVC_CONTROL_GET_MAX | UVC_CONTROL_GET_DEF | UVC_CONTROL_AUTO_UPDATE | UVC_CONTROL_GET_CUR }, { entity : UVC_GUID_RERVISION_SYS_HW_CTRL, index : 2, selector : XU_RERVISION_SYS_H264_CTRL, size : 11, flags : UVC_CONTROL_SET_CUR | UVC_CONTROL_GET_MIN | UVC_CONTROL_GET_MAX | UVC_CONTROL_GET_DEF | UVC_CONTROL_AUTO_UPDATE | UVC_CONTROL_GET_CUR }, { entity : UVC_GUID_RERVISION_SYS_HW_CTRL, index : 3, selector : XU_RERVISION_SYS_MJPG_CTRL, size : 11, flags : UVC_CONTROL_SET_CUR | UVC_CONTROL_GET_CUR }, { entity : UVC_GUID_RERVISION_SYS_HW_CTRL, index : 4, selector : XU_RERVISION_SYS_OSD_CTRL, size : 11, flags : UVC_CONTROL_SET_CUR | UVC_CONTROL_GET_CUR }, { entity : UVC_GUID_RERVISION_SYS_HW_CTRL, index : 5, selector : XU_RERVISION_SYS_OSD_CTRL, size : 11, flags : UVC_CONTROL_SET_CUR | UVC_CONTROL_GET_MIN | UVC_CONTROL_GET_MAX | UVC_CONTROL_GET_DEF | UVC_CONTROL_AUTO_UPDATE | UVC_CONTROL_GET_CUR }, { entity : UVC_GUID_RERVISION_SYS_HW_CTRL, index : 6, selector : XU_RERVISION_SYS_MOTION_DETECTION, size : 11, flags : UVC_CONTROL_SET_CUR | UVC_CONTROL_GET_CUR }, { entity : UVC_GUID_RERVISION_SYS_HW_CTRL, index : 7, selector : XU_RERVISION_SYS_IMG_SETTING, size : 11, flags : UVC_CONTROL_SET_CUR | UVC_CONTROL_GET_CUR }, }; static struct uvc_xu_control_info rervision_xu_usr_ctrls[] = { { .entity = UVC_GUID_RERVISION_USR_HW_CTRL, .index = 0, .selector = XU_RERVISION_USR_FRAME_INFO, .size = 11, .flags = UVC_CONTROL_SET_CUR | UVC_CONTROL_GET_MIN | UVC_CONTROL_GET_MAX | UVC_CONTROL_GET_DEF | UVC_CONTROL_AUTO_UPDATE | UVC_CONTROL_GET_CUR }, { .entity = UVC_GUID_RERVISION_USR_HW_CTRL, .index = 1, .selector = XU_RERVISION_USR_H264_CTRL, .size = 11, .flags = UVC_CONTROL_SET_CUR | UVC_CONTROL_GET_CUR }, { .entity = UVC_GUID_RERVISION_USR_HW_CTRL, .index = 2, .selector = XU_RERVISION_USR_MJPG_CTRL, .size = 11, .flags = UVC_CONTROL_SET_CUR | UVC_CONTROL_GET_CUR }, { .entity = UVC_GUID_RERVISION_USR_HW_CTRL, .index = 3, .selector = XU_RERVISION_USR_OSD_CTRL, .size = 11, .flags = UVC_CONTROL_SET_CUR | UVC_CONTROL_GET_MIN | UVC_CONTROL_GET_MAX | UVC_CONTROL_GET_DEF | UVC_CONTROL_AUTO_UPDATE | UVC_CONTROL_GET_CUR }, { .entity = UVC_GUID_RERVISION_USR_HW_CTRL, .index = 4, .selector = XU_RERVISION_USR_MOTION_DETECTION, .size = 24, .flags = UVC_CONTROL_SET_CUR | UVC_CONTROL_GET_CUR }, { .entity = UVC_GUID_RERVISION_USR_HW_CTRL, .index = 5, .selector = XU_RERVISION_USR_IMG_SETTING, .size = 11, .flags = UVC_CONTROL_SET_CUR | UVC_CONTROL_GET_CUR }, { .entity = UVC_GUID_RERVISION_USR_HW_CTRL, .index = 6, .selector = XU_RERVISION_USR_MULTI_STREAM_CTRL, .size = 11, .flags = UVC_CONTROL_SET_CUR | UVC_CONTROL_GET_CUR }, { .entity = UVC_GUID_RERVISION_USR_HW_CTRL, .index = 7, .selector = XU_RERVISION_USR_GPIO_CTRL, .size = 11, .flags = UVC_CONTROL_SET_CUR | UVC_CONTROL_GET_CUR }, { .entity = UVC_GUID_RERVISION_USR_HW_CTRL, .index = 8, .selector = XU_RERVISION_USR_DYNAMIC_FPS_CTRL, .size = 11, .flags = UVC_CONTROL_SET_CUR | UVC_CONTROL_GET_CUR }, }; // RERVISION XU system Ctrls Mapping static struct uvc_xu_control_mapping rervision_xu_sys_mappings[] = { { V4L2_CID_ASIC_RW_RERVISION, "RERVISION: Asic Read", UVC_GUID_RERVISION_SYS_HW_CTRL, XU_RERVISION_SYS_ASIC_RW, 4, 0, V4L2_CTRL_TYPE_INTEGER, UVC_CTRL_DATA_TYPE_SIGNED }, { V4L2_CID_FLASH_CTRL, "RERVISION: Flash Control", UVC_GUID_RERVISION_SYS_HW_CTRL, XU_RERVISION_SYS_FLASH_CTRL, 11, 0, V4L2_CTRL_TYPE_INTEGER, UVC_CTRL_DATA_TYPE_SIGNED }, { V4L2_CID_FRAME_INFO_RERVISION, "RERVISION: H264 Format", UVC_GUID_RERVISION_SYS_HW_CTRL, XU_RERVISION_SYS_FRAME_INFO, 11, 0, V4L2_CTRL_TYPE_INTEGER, UVC_CTRL_DATA_TYPE_RAW }, { V4L2_CID_H264_CTRL_RERVISION, "RERVISION: H264 Control", UVC_GUID_RERVISION_SYS_HW_CTRL, XU_RERVISION_SYS_H264_CTRL, 11, 0, V4L2_CTRL_TYPE_INTEGER, UVC_CTRL_DATA_TYPE_UNSIGNED }, { V4L2_CID_MJPG_CTRL_RERVISION, "RERVISION: MJPG Control", UVC_GUID_RERVISION_SYS_HW_CTRL, XU_RERVISION_SYS_MJPG_CTRL, 11, 0, V4L2_CTRL_TYPE_INTEGER, UVC_CTRL_DATA_TYPE_UNSIGNED }, { V4L2_CID_OSD_CTRL_RERVISION, "RERVISION: OSD Control", UVC_GUID_RERVISION_SYS_HW_CTRL, XU_RERVISION_SYS_OSD_CTRL, 11, 0, V4L2_CTRL_TYPE_INTEGER, UVC_CTRL_DATA_TYPE_RAW }, { V4L2_CID_MOTION_DETECTION_RERVISION, "RERVISION: Motion Detection", UVC_GUID_RERVISION_SYS_HW_CTRL, XU_RERVISION_SYS_MOTION_DETECTION, 11, 0, V4L2_CTRL_TYPE_INTEGER, UVC_CTRL_DATA_TYPE_UNSIGNED }, { V4L2_CID_IMG_SETTING_RERVISION, "RERVISION: Image Setting", UVC_GUID_RERVISION_SYS_HW_CTRL, XU_RERVISION_SYS_IMG_SETTING, 11, 0, V4L2_CTRL_TYPE_INTEGER, UVC_CTRL_DATA_TYPE_UNSIGNED } }; // RERVISION XU user Ctrls Mapping static struct uvc_xu_control_mapping rervision_xu_usr_mappings[] = { { V4L2_CID_FRAME_INFO_RERVISION, "RERVISION: H264 Format", UVC_GUID_RERVISION_USR_HW_CTRL, XU_RERVISION_USR_FRAME_INFO, 11, 0, V4L2_CTRL_TYPE_INTEGER, UVC_CTRL_DATA_TYPE_RAW }, { V4L2_CID_H264_CTRL_RERVISION, "RERVISION: H264 Control", UVC_GUID_RERVISION_USR_HW_CTRL, XU_RERVISION_USR_H264_CTRL, 11, 0, V4L2_CTRL_TYPE_INTEGER, UVC_CTRL_DATA_TYPE_UNSIGNED }, { V4L2_CID_MJPG_CTRL_RERVISION, "RERVISION: MJPG Control", UVC_GUID_RERVISION_USR_HW_CTRL, XU_RERVISION_USR_MJPG_CTRL, 11, 0, V4L2_CTRL_TYPE_INTEGER, UVC_CTRL_DATA_TYPE_UNSIGNED }, { V4L2_CID_OSD_CTRL_RERVISION, "RERVISION: OSD Control", UVC_GUID_RERVISION_USR_HW_CTRL, XU_RERVISION_USR_OSD_CTRL, 11, 0, V4L2_CTRL_TYPE_INTEGER, UVC_CTRL_DATA_TYPE_RAW }, { V4L2_CID_MOTION_DETECTION_RERVISION, "RERVISION: Motion Detection", UVC_GUID_RERVISION_USR_HW_CTRL, XU_RERVISION_USR_MOTION_DETECTION, 24, 0, V4L2_CTRL_TYPE_INTEGER, UVC_CTRL_DATA_TYPE_UNSIGNED }, { V4L2_CID_IMG_SETTING_RERVISION, "RERVISION: Image Setting", UVC_GUID_RERVISION_USR_HW_CTRL, XU_RERVISION_USR_IMG_SETTING, 11, 0, V4L2_CTRL_TYPE_INTEGER, UVC_CTRL_DATA_TYPE_UNSIGNED }, { V4L2_CID_MULTI_STREAM_CTRL_RERVISION, "RERVISION: Multi Stram Control ", UVC_GUID_RERVISION_USR_HW_CTRL, XU_RERVISION_USR_MULTI_STREAM_CTRL, 11, 0, V4L2_CTRL_TYPE_INTEGER, UVC_CTRL_DATA_TYPE_UNSIGNED }, { V4L2_CID_GPIO_CTRL_RERVISION, "RERVISION: GPIO Control ", UVC_GUID_RERVISION_USR_HW_CTRL, XU_RERVISION_USR_GPIO_CTRL, 11, 0, V4L2_CTRL_TYPE_INTEGER, UVC_CTRL_DATA_TYPE_UNSIGNED }, { V4L2_CID_DYNAMIC_FPS_CTRL_RERVISION, "RERVISION: Dynamic fps Control ", UVC_GUID_RERVISION_USR_HW_CTRL, XU_RERVISION_USR_DYNAMIC_FPS_CTRL, 11, 0, V4L2_CTRL_TYPE_INTEGER, UVC_CTRL_DATA_TYPE_UNSIGNED } }; int XU_Set_Cur(int fd, __u8 xu_unit, __u8 xu_selector, __u16 xu_size, __u8 *xu_data) { int err=0; #if LINUX_VERSION_CODE > KERNEL_VERSION (3, 0, 36) struct uvc_xu_control_query xctrl; xctrl.unit = xu_unit; xctrl.selector = xu_selector; xctrl.query = UVC_SET_CUR; xctrl.size = xu_size; xctrl.data = xu_data; err=ioctl(fd, UVCIOC_CTRL_QUERY, &xctrl); #else struct uvc_xu_control xctrl; xctrl.unit = xu_unit; xctrl.selector = xu_selector; xctrl.size = xu_size; xctrl.data = xu_data; err=ioctl(fd, UVCIOC_CTRL_SET, &xctrl); #endif return err; } int XU_Get_Cur(int fd, __u8 xu_unit, __u8 xu_selector, __u16 xu_size, __u8 *xu_data) { int err=0; #if LINUX_VERSION_CODE > KERNEL_VERSION (3, 0, 36) struct uvc_xu_control_query xctrl; xctrl.unit = xu_unit; xctrl.selector = xu_selector; xctrl.query = UVC_GET_CUR; xctrl.size = xu_size; xctrl.data = xu_data; err=ioctl(fd, UVCIOC_CTRL_QUERY, &xctrl); #else struct uvc_xu_control xctrl; xctrl.unit = xu_unit; xctrl.selector = xu_selector; xctrl.size = xu_size; xctrl.data = xu_data; err=ioctl(fd, UVCIOC_CTRL_GET, &xctrl); #endif return err; } // XU ctrls ---------------------------------------------------------- int XU_Ctrl_Add(int fd, struct uvc_xu_control_info *info, struct uvc_xu_control_mapping *map) { // int i=0; int err=0; /* try to add controls listed */ #if LINUX_VERSION_CODE <= KERNEL_VERSION (3, 0, 36) TestAp_Printf(TESTAP_DBG_FLOW, "Adding XU Ctrls - %s\n", map->name); if ((err=ioctl(fd, UVCIOC_CTRL_ADD, info)) < 0 ) { if (errno == EEXIST ) { TestAp_Printf(TESTAP_DBG_ERR, "UVCIOC_CTRL_ADD - Ignored, uvc driver had already defined\n"); return (-EEXIST); } else if (errno == EACCES) { TestAp_Printf(TESTAP_DBG_ERR, "Need admin previledges for adding extension unit(XU) controls\n"); TestAp_Printf(TESTAP_DBG_ERR, "please run 'RERVISION_UVC_TestAP --add_ctrls' as root (or with sudo)\n"); return (-1); } else perror("Control exists"); } #endif /* after adding the controls, add the mapping now */ TestAp_Printf(TESTAP_DBG_FLOW, "Mapping XU Ctrls - %s\n", map->name); if ((err=ioctl(fd, UVCIOC_CTRL_MAP, map)) < 0) { if ((errno!=EEXIST) && (errno != EACCES)) { TestAp_Printf(TESTAP_DBG_ERR, "UVCIOC_CTRL_MAP - Error(err= %d)\n", err); return (-2); } else if (errno == EACCES) { TestAp_Printf(TESTAP_DBG_ERR, "Need admin previledges for adding extension unit(XU) controls\n"); TestAp_Printf(TESTAP_DBG_ERR, "please run 'RERVISION_UVC_TestAP --add_ctrls' as root (or with sudo)\n"); return (-1); } else perror("Mapping exists"); } return 0; } int XU_Init_Ctrl(int fd) { int i=0; int err=0; int length; struct uvc_xu_control_info *xu_infos; struct uvc_xu_control_mapping *xu_mappings; // Add xu READ ASIC first err = XU_Ctrl_Add(fd, &rervision_xu_sys_ctrls[i], &rervision_xu_sys_mappings[i]); if (err == EEXIST){} else if (err < 0) {return err;} // Read chip ID err = XU_Ctrl_ReadChipID(fd); if (err < 0) return err; // Add xu flash control i++; err = XU_Ctrl_Add(fd, &rervision_xu_sys_ctrls[i], &rervision_xu_sys_mappings[i]); if (err == EEXIST){} else if (err < 0) {return err;} // Decide which xu set had been add if(chip_id == CHIP_RER9420) { xu_infos = rervision_xu_sys_ctrls; xu_mappings = rervision_xu_sys_mappings; i = 2; length = LENGTH_OF_RERVISION_XU_SYS_CTR; TestAp_Printf(TESTAP_DBG_FLOW, "RER9420\n"); } else if((chip_id == CHIP_RER9421)||(chip_id == CHIP_RER9422)) { xu_infos = rervision_xu_usr_ctrls; xu_mappings = rervision_xu_usr_mappings; i = 0; length = LENGTH_OF_RERVISION_XU_USR_CTR; TestAp_Printf(TESTAP_DBG_FLOW, "RER9422\n"); } else { TestAp_Printf(TESTAP_DBG_ERR, "Unknown chip id 0x%x\n", chip_id); return -1; } // Add other xu accroding chip ID for ( ; i<length; i++ ) { err = XU_Ctrl_Add(fd, &xu_infos[i], &xu_mappings[i]); //if (err < 0) break; } return 0; } int XU_Ctrl_ReadChipID(int fd) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_Ctrl_ReadChipID ==>\n"); int ret = 0; int err = 0; __u8 ctrldata[4]; //uvc_xu_control parmeters __u8 xu_unit= 3; __u8 xu_selector= XU_RERVISION_SYS_ASIC_RW; __u16 xu_size= 4; __u8 *xu_data= ctrldata; xu_data[0] = 0x1f; xu_data[1] = 0x10; xu_data[2] = 0x0; xu_data[3] = 0xFF; /* Dummy Write */ /* Dummy Write */ if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR, " ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); return err; } /* Asic Read */ xu_data[3] = 0x00; if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR, " ioctl(UVCIOC_CTRL_GET) FAILED (%i) \n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR, " Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, " == XU_Ctrl_ReadChipID Success == \n"); TestAp_Printf(TESTAP_DBG_FLOW, " ASIC READ data[0] : %x\n", xu_data[0]); TestAp_Printf(TESTAP_DBG_FLOW, " ASIC READ data[1] : %x\n", xu_data[1]); TestAp_Printf(TESTAP_DBG_FLOW, " ASIC READ data[2] : %x (Chip ID)\n", xu_data[2]); TestAp_Printf(TESTAP_DBG_FLOW, " ASIC READ data[3] : %x\n", xu_data[3]); if(xu_data[2] == RERVISION_RER9420_SERIES_CHIPID) { chip_id = CHIP_RER9420; } if(xu_data[2] == RERVISION_RER9422_SERIES_CHIPID) { xu_data[0] = 0x07; //DRAM SIZE xu_data[1] = 0x16; xu_data[2] = 0x0; xu_data[3] = 0xFF; /* Dummy Write */ /* Dummy Write */ if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR, " ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); return err; } /* Asic Read */ xu_data[3] = 0x00; if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR, " ioctl(UVCIOC_CTRL_GET) FAILED (%i) \n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR, " Invalid arguments\n"); return err; } if(xu_data[2] == RERVISION_RER9422_DDR_64M) chip_id = CHIP_RER9422; else if(xu_data[2] == RERVISION_RER9422_DDR_16M) chip_id = CHIP_RER9421; } TestAp_Printf(TESTAP_DBG_FLOW, "ChipID = %d\n",chip_id); TestAp_Printf(TESTAP_DBG_FLOW, "XU_Ctrl_ReadChipID <==\n"); return ret; } int H264_GetFormat(int fd) { TestAp_Printf(TESTAP_DBG_FLOW, "H264_GetFormat ==>\n"); int i,j; int iH264FormatCount = 0; int success = 1; unsigned char *fwData = NULL; unsigned short fwLen = 0; // Init H264 XU Ctrl Format if( XU_H264_InitFormat(fd) < 0 ) { TestAp_Printf(TESTAP_DBG_ERR, " H264 XU Ctrl Format failed , use default Format\n"); fwLen = Default_fwLen; fwData = (unsigned char *)calloc(fwLen,sizeof(unsigned char)); memcpy(fwData, Default_fwData, fwLen); goto Skip_XU_GetFormat; } // Probe : Get format through XU ctrl success = XU_H264_GetFormatLength(fd, &fwLen); if( success < 0 || fwLen <= 0) { TestAp_Printf(TESTAP_DBG_ERR, " XU Get Format Length failed !\n"); } TestAp_Printf(TESTAP_DBG_FLOW, "fwLen = 0x%x\n", fwLen); // alloc memory fwData = (unsigned char *)calloc(fwLen,sizeof(unsigned char)); if( XU_H264_GetFormatData(fd, fwData,fwLen) < 0 ) { TestAp_Printf(TESTAP_DBG_ERR, " XU Get Format Data failed !\n"); } Skip_XU_GetFormat : // Get H.264 format count iH264FormatCount = H264_CountFormat(fwData, fwLen); TestAp_Printf(TESTAP_DBG_FLOW, "H264_GetFormat ==> FormatCount : %d \n", iH264FormatCount); if(iH264FormatCount>0) gH264fmt = (struct H264Format *)malloc(sizeof(struct H264Format)*iH264FormatCount); else { TestAp_Printf(TESTAP_DBG_ERR,"Get Resolution Data Failed\n"); } // Parse & Save Size/Framerate into structure success = H264_ParseFormat(fwData, fwLen, gH264fmt); if(success) { for(i=0; i<iH264FormatCount; i++) { TestAp_Printf(TESTAP_DBG_FLOW, "Format index: %d --- (%d x %d) ---\n", i+1, gH264fmt[i].wWidth, gH264fmt[i].wHeight); for(j=0; j<gH264fmt[i].fpsCnt; j++) { if(chip_id == CHIP_RER9420) { TestAp_Printf(TESTAP_DBG_FLOW, "(%d) %2d fps\n", j+1, H264_GetFPS(gH264fmt[i].FrPay[j])); } else if((chip_id == CHIP_RER9421)||(chip_id == CHIP_RER9422)) { TestAp_Printf(TESTAP_DBG_FLOW, "(%d) %2d fps\n", j+1, H264_GetFPS(gH264fmt[i].FrPay[j*2])); } } } } if(fwData) { free(fwData); fwData = NULL; } TestAp_Printf(TESTAP_DBG_FLOW, "H264_GetFormat <== \n"); return success; } int H264_CountFormat(unsigned char *Data, int len) { int fmtCnt = 0; // int fpsCnt = 0; int cur_len = 0; // int cur_fmtid = 0; int cur_fpsNum = 0; if( Data == NULL || len == 0) return 0; // count Format numbers while(cur_len < len) { cur_fpsNum = Data[cur_len+4]; TestAp_Printf(TESTAP_DBG_FLOW, "H264_CountFormat ==> cur_len = %d, cur_fpsNum= %d\n", cur_len , cur_fpsNum); if(chip_id == CHIP_RER9420) { cur_len += 9 + cur_fpsNum * 4; } else if((chip_id == CHIP_RER9421)||(chip_id == CHIP_RER9422)) { cur_len += 9 + cur_fpsNum * 6; } fmtCnt++; } if(cur_len != len) { TestAp_Printf(TESTAP_DBG_FLOW, "H264_CountFormat ==> cur_len = %d, fwLen= %d\n", cur_len , len); return 0; } TestAp_Printf(TESTAP_DBG_FLOW, " ======== fmtCnt=%d ======== \n",fmtCnt); return fmtCnt; } int H264_ParseFormat(unsigned char *Data, int len, struct H264Format *fmt) { TestAp_Printf(TESTAP_DBG_FLOW, "H264_ParseFormat ==>\n"); // int fpsCnt = 0; int cur_len = 0; int cur_fmtid = 0; int cur_fpsNum = 0; int i; while(cur_len < len) { // Copy Size fmt[cur_fmtid].wWidth = ((unsigned short)Data[cur_len]<<8) + (unsigned short)Data[cur_len+1]; fmt[cur_fmtid].wHeight = ((unsigned short)Data[cur_len+2]<<8) + (unsigned short)Data[cur_len+3]; fmt[cur_fmtid].fpsCnt = Data[cur_len+4]; fmt[cur_fmtid].FrameSize = ((unsigned int)Data[cur_len+5] << 24) | ((unsigned int)Data[cur_len+6] << 16) | ((unsigned int)Data[cur_len+7] << 8 ) | ((unsigned int)Data[cur_len+8]); TestAp_Printf(TESTAP_DBG_FLOW, "Data[5~8]: 0x%02x%02x%02x%02x \n", Data[cur_len+5],Data[cur_len+6],Data[cur_len+7],Data[cur_len+8]); TestAp_Printf(TESTAP_DBG_FLOW, "fmt[%d].FrameSize: 0x%08x \n", cur_fmtid, fmt[cur_fmtid].FrameSize); // Alloc memory for Frame rate cur_fpsNum = Data[cur_len+4]; if(chip_id == CHIP_RER9420) { fmt[cur_fmtid].FrPay = (unsigned int *)malloc(sizeof(unsigned int)*cur_fpsNum); } else if((chip_id == CHIP_RER9421)||(chip_id == CHIP_RER9422)) { fmt[cur_fmtid].FrPay = (unsigned int *)malloc(sizeof(unsigned int)*cur_fpsNum*2); } for(i=0; i<cur_fpsNum; i++) { if(chip_id == CHIP_RER9420) { fmt[cur_fmtid].FrPay[i] = (unsigned int)Data[cur_len+9+i*4] << 24 | (unsigned int)Data[cur_len+9+i*4+1] << 16 | (unsigned int)Data[cur_len+9+i*4+2] << 8 | (unsigned int)Data[cur_len+9+i*4+3] ; //TestAp_Printf(TESTAP_DBG_FLOW, "fmt[cur_fmtid].FrPay[%d]: 0x%08x \n", i, fmt[cur_fmtid].FrPay[i]); } else if((chip_id == CHIP_RER9421)||(chip_id == CHIP_RER9422)) { fmt[cur_fmtid].FrPay[i*2] = (unsigned int)Data[cur_len+9+i*6] << 8 | (unsigned int)Data[cur_len+9+i*6+1]; fmt[cur_fmtid].FrPay[i*2+1] = (unsigned int)Data[cur_len+9+i*6+2] << 24 | (unsigned int)Data[cur_len+9+i*6+3] << 16 | (unsigned int)Data[cur_len+9+i*6+4] << 8 | (unsigned int)Data[cur_len+9+i*6+5] ; TestAp_Printf(TESTAP_DBG_FLOW, "fmt[cur_fmtid].FrPay[%d]: 0x%04x 0x%08x \n", i, fmt[cur_fmtid].FrPay[i*2], fmt[cur_fmtid].FrPay[i*2+1]); } } // Do next format if(chip_id == CHIP_RER9420) { cur_len += 9 + cur_fpsNum * 4; } else if((chip_id == CHIP_RER9421)||(chip_id == CHIP_RER9422)) { cur_len += 9 + cur_fpsNum * 6; } cur_fmtid++; } if(cur_len != len) { TestAp_Printf(TESTAP_DBG_ERR,"H264_ParseFormat <== fail \n"); return 0; } TestAp_Printf(TESTAP_DBG_FLOW, "H264_ParseFormat <==\n"); return 1; } int H264_GetFPS(unsigned int FrPay) { int fps = 0; if(chip_id == CHIP_RER9420) { //TestAp_Printf(TESTAP_DBG_FLOW, "H264_GetFPS==> FrPay = 0x%04x\n", (FrPay & 0xFFFF0000)>>16); unsigned short frH = (FrPay & 0xFF000000)>>16; unsigned short frL = (FrPay & 0x00FF0000)>>16; unsigned short fr = (frH|frL); //TestAp_Printf(TESTAP_DBG_FLOW, "FrPay: 0x%x -> fr = 0x%x\n",FrPay,fr); fps = ((unsigned int)10000000/fr)>>8; //TestAp_Printf(TESTAP_DBG_FLOW, "fps : %d\n", fps); } else if((chip_id == CHIP_RER9421)||(chip_id == CHIP_RER9422)) { //TestAp_Printf(TESTAP_DBG_FLOW, "H264_GetFPS==> Fr = 0x%04x\n", (unsigned short)FrPay); fps = ((unsigned int)10000000/(unsigned short)FrPay)>>8; //TestAp_Printf(TESTAP_DBG_FLOW, "fps : %d\n", fps); } return fps; } int XU_H264_InitFormat(int fd) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_H264_InitFormat ==>\n"); int i = 0; int ret = 0; int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= 0; __u8 xu_selector= 0; __u16 xu_size= 11; __u8 *xu_data= ctrldata; if(chip_id == CHIP_RER9420) { xu_unit = XU_RERVISION_SYS_ID; xu_selector = XU_RERVISION_SYS_FRAME_INFO; } else if((chip_id == CHIP_RER9421)||(chip_id == CHIP_RER9422)) { xu_unit = XU_RERVISION_USR_ID; xu_selector = XU_RERVISION_USR_FRAME_INFO; } // Switch command : FMT_NUM_INFO // data[0] = 0x01; xu_data[0] = 0x9A; xu_data[1] = 0x01; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR," Set Switch command : FMT_NUM_INFO FAILED (%i)\n",err); return err; } //xu_data[0] = 0; memset(xu_data, 0, xu_size); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR," ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); return err; } for(i=0; i<xu_size; i++) TestAp_Printf(TESTAP_DBG_FLOW, " Get Data[%d] = 0x%x\n",i, xu_data[i]); TestAp_Printf(TESTAP_DBG_FLOW, " ubH264Idx_S1 = %d\n", xu_data[5]); TestAp_Printf(TESTAP_DBG_FLOW, "XU_H264_InitFormat <== Success\n"); return ret; } int XU_H264_GetFormatLength(int fd, unsigned short *fwLen) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_H264_GetFormatLength ==>\n"); int i = 0; int ret = 0; int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= 0; __u8 xu_selector= 0; __u16 xu_size= 11; __u8 *xu_data= ctrldata; if(chip_id == CHIP_RER9420) { xu_unit = XU_RERVISION_SYS_ID; xu_selector = XU_RERVISION_SYS_FRAME_INFO; } else if((chip_id == CHIP_RER9421)||(chip_id == CHIP_RER9422)) { xu_unit = XU_RERVISION_USR_ID; xu_selector = XU_RERVISION_USR_FRAME_INFO; } // Switch command : FMT_Data Length_INFO xu_data[0] = 0x9A; xu_data[1] = 0x02; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) >= 0) { //for(i=0; i<11; i++) xu_data[i] = 0; // clean data memset(xu_data, 0, xu_size); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) >= 0) { for (i=0 ; i<11 ; i+=2) TestAp_Printf(TESTAP_DBG_FLOW, " Get Data[%d] = 0x%x\n", i, (xu_data[i]<<8)+xu_data[i+1]); // Get H.264 format length *fwLen = ((unsigned short)xu_data[6]<<8) + xu_data[7]; TestAp_Printf(TESTAP_DBG_FLOW, " H.264 format Length = 0x%x\n", *fwLen); } else { TestAp_Printf(TESTAP_DBG_ERR," ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); return err; } } else { TestAp_Printf(TESTAP_DBG_ERR," Set Switch command : FMT_Data Length_INFO FAILED (%i)\n",err); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_H264_GetFormatLength <== Success\n"); return ret; } int XU_H264_GetFormatData(int fd, unsigned char *fwData, unsigned short fwLen) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_H264_GetFormatData ==>\n"); int i = 0; int ret = 0; int err = 0; __u8 ctrldata[11]={0}; int loop = 0; int LoopCnt = (fwLen%11) ? (fwLen/11)+1 : (fwLen/11) ; int Copyleft = fwLen; //uvc_xu_control parmeters __u8 xu_unit= 0; __u8 xu_selector= 0; __u16 xu_size= 11; __u8 *xu_data= ctrldata; if(chip_id == CHIP_RER9420) { xu_unit = XU_RERVISION_SYS_ID; xu_selector = XU_RERVISION_SYS_FRAME_INFO; } else if((chip_id == CHIP_RER9421)||(chip_id == CHIP_RER9422)) { xu_unit = XU_RERVISION_USR_ID; xu_selector = XU_RERVISION_USR_FRAME_INFO; } // Switch command xu_data[0] = 0x9A; xu_data[1] = 0x03; // FRM_DATA_INFO if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR," Set Switch command : FRM_DATA_INFO FAILED (%i)\n",err); return err; } // Get H.264 Format Data xu_data[0] = 0x02; // Stream: 1 xu_data[1] = 0x01; // Format: 1 (H.264) if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) >= 0) { // Read all H.264 format data for(loop = 0 ; loop < LoopCnt ; loop ++) { for(i=0; i<11; i++) xu_data[i] = 0; // clean data TestAp_Printf(TESTAP_DBG_FLOW, "--> Loop : %d <--\n", loop); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) >= 0) { for (i=0 ; i<11 ; i++) TestAp_Printf(TESTAP_DBG_FLOW, " Data[%d] = 0x%x\n", i, xu_data[i]); // Copy Data if(Copyleft >= 11) { memcpy( &fwData[loop*11] , xu_data, 11); Copyleft -= 11; } else { memcpy( &fwData[loop*11] , xu_data, Copyleft); Copyleft = 0; } } else { TestAp_Printf(TESTAP_DBG_ERR," ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); return err; } } } else { TestAp_Printf(TESTAP_DBG_ERR," Set Switch command : FRM_DATA_INFO FAILED (%i)\n",err); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_H264_GetFormatData <== Success\n"); return ret; } int XU_H264_SetFormat(int fd, struct Cur_H264Format fmt) { // Need to get H264 format first if(gH264fmt==NULL) { TestAp_Printf(TESTAP_DBG_FLOW, "RERVISION_UVC_TestAP @XU_H264_SetFormat : Do XU_H264_GetFormat before setting H264 format\n"); return -EINVAL; } if(chip_id == CHIP_RER9420) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_H264_SetFormat ==> %d-%d => (%d x %d):%d fps\n", fmt.FmtId+1, fmt.FrameRateId+1, gH264fmt[fmt.FmtId].wWidth, gH264fmt[fmt.FmtId].wHeight, H264_GetFPS(gH264fmt[fmt.FmtId].FrPay[fmt.FrameRateId])); } else if((chip_id == CHIP_RER9421)||(chip_id == CHIP_RER9422)) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_H264_SetFormat ==> %d-%d => (%d x %d):%d fps\n", fmt.FmtId+1, fmt.FrameRateId+1, gH264fmt[fmt.FmtId].wWidth, gH264fmt[fmt.FmtId].wHeight, H264_GetFPS(gH264fmt[fmt.FmtId].FrPay[fmt.FrameRateId*2])); } int ret = 0; int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= 0; __u8 xu_selector= 0; __u16 xu_size= 11; __u8 *xu_data= ctrldata; if(chip_id == CHIP_RER9420) { xu_unit = XU_RERVISION_SYS_ID; xu_selector = XU_RERVISION_SYS_FRAME_INFO; } else if((chip_id == CHIP_RER9421)||(chip_id == CHIP_RER9422)) { xu_unit = XU_RERVISION_USR_ID; xu_selector = XU_RERVISION_USR_FRAME_INFO; } // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x21; // Commit_INFO if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_H264_Set_FMT ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set H.264 format setting data xu_data[0] = 0x02; // Stream : 1 xu_data[1] = 0x01; // Format index : 1 (H.264) xu_data[2] = fmt.FmtId + 1; // Frame index (Resolution index), firmware index starts from 1 // xu_data[3] = ( gH264fmt[fmt.FmtId].FrPay[fmt.FrameRateId] & 0xFF000000 ) >> 24; // Frame interval // xu_data[4] = ( gH264fmt[fmt.FmtId].FrPay[fmt.FrameRateId] & 0x00FF0000 ) >> 16; xu_data[5] = ( gH264fmt[fmt.FmtId].FrameSize & 0x00FF0000) >> 16; xu_data[6] = ( gH264fmt[fmt.FmtId].FrameSize & 0x0000FF00) >> 8; xu_data[7] = ( gH264fmt[fmt.FmtId].FrameSize & 0x000000FF); // xu_data[8] = ( gH264fmt[fmt.FmtId].FrPay[fmt.FrameRateId] & 0x0000FF00 ) >> 8; // xu_data[9] = ( gH264fmt[fmt.FmtId].FrPay[fmt.FrameRateId] & 0x000000FF ) ; if(chip_id == CHIP_RER9420) { xu_data[3] = ( gH264fmt[fmt.FmtId].FrPay[fmt.FrameRateId] & 0xFF000000 ) >> 24; // Frame interval xu_data[4] = ( gH264fmt[fmt.FmtId].FrPay[fmt.FrameRateId] & 0x00FF0000 ) >> 16; xu_data[8] = ( gH264fmt[fmt.FmtId].FrPay[fmt.FrameRateId] & 0x0000FF00 ) >> 8; xu_data[9] = ( gH264fmt[fmt.FmtId].FrPay[fmt.FrameRateId] & 0x000000FF ) ; } else if((chip_id == CHIP_RER9421)||(chip_id == CHIP_RER9422)) { xu_data[3] = ( gH264fmt[fmt.FmtId].FrPay[fmt.FrameRateId*2] & 0x0000FF00 ) >> 8; // Frame interval xu_data[4] = ( gH264fmt[fmt.FmtId].FrPay[fmt.FrameRateId*2] & 0x000000FF ) ; xu_data[8] = ( gH264fmt[fmt.FmtId].FrPay[fmt.FrameRateId*2+1] & 0xFF000000 ) >> 24; xu_data[9] = ( gH264fmt[fmt.FmtId].FrPay[fmt.FrameRateId*2+1] & 0x00FF0000 ) >> 16; xu_data[10] = ( gH264fmt[fmt.FmtId].FrPay[fmt.FrameRateId*2+1] & 0x0000FF00 ) >> 8; } if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_H264_Set_FMT ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } if((chip_id == CHIP_RER9421)||(chip_id == CHIP_RER9422)) { memset(xu_data, 0, xu_size); xu_data[0] = ( gH264fmt[fmt.FmtId].FrPay[fmt.FrameRateId*2+1] & 0x000000FF ) ; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_H264_Set_FMT____2 ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } } TestAp_Printf(TESTAP_DBG_FLOW, "XU_H264_SetFormat <== Success \n"); return ret; } int XU_H264_Get_Mode(int fd, int *Mode) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_H264_Get_Mode ==>\n"); // int i = 0; int ret = 0; int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= 0; __u8 xu_selector= 0; __u16 xu_size= 11; __u8 *xu_data= ctrldata; if(chip_id == CHIP_RER9420) { xu_unit = XU_RERVISION_SYS_ID; xu_selector = XU_RERVISION_SYS_H264_CTRL; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x01; // H264_ctrl_type } else if((chip_id == CHIP_RER9421)||(chip_id == CHIP_RER9422)) { xu_unit = XU_RERVISION_USR_ID; xu_selector = XU_RERVISION_USR_H264_CTRL; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x06; // H264_mode } if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_H264_Get_Mode ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Get mode if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_H264_Get_Mode ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, " == XU_H264_Get_Mode Success == \n"); TestAp_Printf(TESTAP_DBG_FLOW, " Get data[%d] : 0x%x\n", 0, xu_data[0]); *Mode = xu_data[0]; TestAp_Printf(TESTAP_DBG_FLOW, "XU_H264_Get_Mode (%s)<==\n", *Mode==1?"CBR mode":(*Mode==2?"VBR mode":"error")); return ret; } int XU_H264_Set_Mode(int fd, int Mode) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_H264_Set_Mode (0x%x) ==>\n", Mode); int ret = 0; int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= 0; __u8 xu_selector= 0; __u16 xu_size= 11; __u8 *xu_data= ctrldata; if(chip_id == CHIP_RER9420) { xu_unit = XU_RERVISION_SYS_ID; xu_selector = XU_RERVISION_SYS_H264_CTRL; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x01; // H264_ctrl_type } else if((chip_id == CHIP_RER9421)||(chip_id == CHIP_RER9422)) { xu_unit = XU_RERVISION_USR_ID; xu_selector = XU_RERVISION_USR_H264_CTRL; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x06; // H264_mode } if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_H264_Set_Mode ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set CBR/VBR Mode memset(xu_data, 0, xu_size); xu_data[0] = Mode; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_H264_Set_Mode ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_H264_Set_Mode <== Success \n"); return ret; } int XU_H264_Get_QP_Limit(int fd, int *QP_Min, int *QP_Max) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_H264_Get_QP_Limit ==>\n"); int i = 0; int ret = 0; int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= 0; __u8 xu_selector= 0; __u16 xu_size= 11; __u8 *xu_data= ctrldata; if(chip_id == CHIP_RER9420) { xu_unit = XU_RERVISION_SYS_ID; xu_selector = XU_RERVISION_SYS_H264_CTRL; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x02; // H264_limit } else if((chip_id == CHIP_RER9421)||(chip_id == CHIP_RER9422)) { xu_unit = XU_RERVISION_USR_ID; xu_selector = XU_RERVISION_USR_H264_CTRL; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x01; // H264_limit } if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_H264_Get_QP_Limit ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } memset(xu_data, 0, xu_size); // Get QP value if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_H264_Get_QP_Limit ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, " == XU_H264_Get_QP_Limit Success == \n"); for(i=0; i<2; i++) TestAp_Printf(TESTAP_DBG_FLOW, " Get data[%d] : 0x%x\n", i, xu_data[i]); *QP_Min = xu_data[0]; *QP_Max = xu_data[1]; TestAp_Printf(TESTAP_DBG_FLOW, "XU_H264_Get_QP_Limit (0x%x, 0x%x)<==\n", *QP_Min, *QP_Max); return ret; } int XU_H264_Get_QP(int fd, int *QP_Val) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_H264_Get_QP ==>\n"); // int i = 0; int ret = 0; int err = 0; __u8 ctrldata[11]={0}; *QP_Val = -1; if(chip_id == CHIP_RER9420) { int qp_min, qp_max; XU_H264_Get_QP_Limit(fd, &qp_min, &qp_max); } //uvc_xu_control parmeters __u8 xu_unit= 0; __u8 xu_selector= 0; __u16 xu_size= 11; __u8 *xu_data= ctrldata; if(chip_id == CHIP_RER9420) { xu_unit = XU_RERVISION_SYS_ID; xu_selector = XU_RERVISION_SYS_H264_CTRL; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x05; // H264_VBR_QP } else if((chip_id == CHIP_RER9421)||(chip_id == CHIP_RER9422)) { xu_unit = XU_RERVISION_USR_ID; xu_selector = XU_RERVISION_USR_H264_CTRL; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x07; // H264_QP } if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_H264_Get_QP ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_FLOW, "Invalid arguments\n"); return err; } // Get QP value if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_H264_Get_QP ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, " == XU_H264_Get_QP Success == \n"); TestAp_Printf(TESTAP_DBG_FLOW, " Get data[%d] : 0x%x\n", 0, xu_data[0]); *QP_Val = xu_data[0]; TestAp_Printf(TESTAP_DBG_FLOW, "XU_H264_Get_QP (0x%x)<==\n", *QP_Val); return ret; } int XU_H264_Set_QP(int fd, int QP_Val) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_H264_Set_QP (0x%x) ==>\n", QP_Val); int ret = 0; int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= 0; __u8 xu_selector= 0; __u16 xu_size= 11; __u8 *xu_data= ctrldata; if(chip_id == CHIP_RER9420) { xu_unit = XU_RERVISION_SYS_ID; xu_selector = XU_RERVISION_SYS_H264_CTRL; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x05; // H264_VBR_QP } else if((chip_id == CHIP_RER9421)||(chip_id == CHIP_RER9422)) { xu_unit = XU_RERVISION_USR_ID; xu_selector = XU_RERVISION_USR_H264_CTRL; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x07; // H264_QP } if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_H264_Get_QP ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set QP value memset(xu_data, 0, xu_size); xu_data[0] = QP_Val; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_H264_Set_QP ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_H264_Set_QP <== Success \n"); return ret; } int XU_H264_Get_BitRate(int fd, double *BitRate) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_H264_Get_BitRate ==>\n"); int i = 0; int ret = 0; int err = 0; __u8 ctrldata[11]={0}; int BitRate_CtrlNum = 0; *BitRate = -1.0; //uvc_xu_control parmeters __u8 xu_unit= 0; __u8 xu_selector= 0; __u16 xu_size= 11; __u8 *xu_data= ctrldata; if(chip_id == CHIP_RER9420) { xu_unit = XU_RERVISION_SYS_ID; xu_selector = XU_RERVISION_SYS_H264_CTRL; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x03; // H264_BitRate } else if((chip_id == CHIP_RER9421)||(chip_id == CHIP_RER9422)) { xu_unit = XU_RERVISION_USR_ID; xu_selector = XU_RERVISION_USR_H264_CTRL; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x02; // H264_BitRate } if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_H264_Get_BitRate ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Get Bit rate ctrl number memset(xu_data, 0, xu_size); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_H264_Get_BitRate ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, " == XU_H264_Get_BitRate Success == \n"); if(chip_id == CHIP_RER9420) { for(i=0; i<2; i++) TestAp_Printf(TESTAP_DBG_FLOW, " Get data[%d] : 0x%x\n", i, xu_data[i]); BitRate_CtrlNum = ( xu_data[0]<<8 )| (xu_data[1]) ; // Bit Rate = BitRate_Ctrl_Num*512*fps*8 /1000(Kbps) *BitRate = (double)(BitRate_CtrlNum*512.0*m_CurrentFPS*8)/1024.0; } else if((chip_id == CHIP_RER9421)||(chip_id == CHIP_RER9422)) { for(i=0; i<3; i++) TestAp_Printf(TESTAP_DBG_FLOW, " Get data[%d] : 0x%x\n", i, xu_data[i]); BitRate_CtrlNum = ( xu_data[0]<<16 )| ( xu_data[1]<<8 )| (xu_data[2]) ; *BitRate = BitRate_CtrlNum; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_H264_Get_BitRate (%.2f)<==\n", *BitRate); return ret; } int XU_H264_Set_BitRate(int fd, double BitRate) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_H264_Set_BitRate (%.2f) ==>\n",BitRate); int ret = 0; int err = 0; __u8 ctrldata[11]={0}; int BitRate_CtrlNum = 0; //uvc_xu_control parmeters __u8 xu_unit= 0; __u8 xu_selector= 0; __u16 xu_size= 11; __u8 *xu_data= ctrldata; if(chip_id == CHIP_RER9420) { xu_unit = XU_RERVISION_SYS_ID; xu_selector = XU_RERVISION_SYS_H264_CTRL; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x03; // H264_BitRate } else if((chip_id == CHIP_RER9421)||(chip_id == CHIP_RER9422)) { xu_unit = XU_RERVISION_USR_ID; xu_selector = XU_RERVISION_USR_H264_CTRL; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x02; // H264_BitRate } if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_H264_Set_BitRate ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set Bit Rate Ctrl Number if(chip_id == CHIP_RER9420) { // Bit Rate = BitRate_Ctrl_Num*512*fps*8/1000 (Kbps) BitRate_CtrlNum = (int)((BitRate*1024)/(512*m_CurrentFPS*8)); xu_data[0] = (BitRate_CtrlNum & 0xFF00)>>8; // BitRate ctrl Num xu_data[1] = (BitRate_CtrlNum & 0x00FF); } else if((chip_id == CHIP_RER9421)||(chip_id == CHIP_RER9422)) { // Bit Rate = BitRate_Ctrl_Num*512*fps*8/1000 (Kbps) xu_data[0] = ((int)BitRate & 0x00FF0000)>>16; xu_data[1] = ((int)BitRate & 0x0000FF00)>>8; xu_data[2] = ((int)BitRate & 0x000000FF); } if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_H264_Set_BitRate ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_H264_Set_BitRate <== Success \n"); return ret; } int XU_H264_Set_IFRAME(int fd) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_H264_Set_IFRAME ==>\n"); int ret = 0; int err = 0; __u8 ctrldata[11]={0}; // int BitRate_CtrlNum = 0; //uvc_xu_control parmeters __u8 xu_unit= 0; __u8 xu_selector= 0; __u16 xu_size= 11; __u8 *xu_data= ctrldata; if(chip_id == CHIP_RER9420) { xu_unit = XU_RERVISION_SYS_ID; xu_selector = XU_RERVISION_SYS_H264_CTRL; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x06; // H264_IFRAME } else if((chip_id == CHIP_RER9421)||(chip_id == CHIP_RER9422)) { xu_unit = XU_RERVISION_USR_ID; xu_selector = XU_RERVISION_USR_H264_CTRL; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x04; // H264_IFRAME } if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_H264_Set_IFRAME ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set IFrame reset xu_data[0] = 1; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_H264_Set_IFRAME ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_H264_Set_IFRAME <== Success \n"); return ret; } int XU_H264_Get_SEI(int fd, unsigned char *SEI) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_H264_Get_SEI ==>\n"); int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_H264_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; if(chip_id == CHIP_RER9420) { TestAp_Printf(TESTAP_DBG_FLOW, " ==SN9C290 no support get SEI==\n"); return 0; } // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x05; // H264_SEI if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_H264_Get_SEI ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Get SEI memset(xu_data, 0, xu_size); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_H264_Get_SEI ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } *SEI = xu_data[0]; TestAp_Printf(TESTAP_DBG_FLOW, " SEI : 0x%x\n",*SEI); TestAp_Printf(TESTAP_DBG_FLOW, "XU_H264_Get_SEI <== Success \n"); return 0; } int XU_H264_Set_SEI(int fd, unsigned char SEI) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_H264_Set_SEI ==>\n"); int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_H264_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; if(chip_id == CHIP_RER9420) { TestAp_Printf(TESTAP_DBG_FLOW, " ==SN9C290 no support Set SEI==\n"); return 0; } // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x05; // H264_SEI if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_H264_Set_SEI ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set SEI xu_data[0] = SEI; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_H264_Set_SEI ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_H264_Set_SEI <== Success \n"); return 0; } int XU_H264_Get_GOP(int fd, unsigned int *GOP) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_H264_Get_GOP ==>\n"); int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_H264_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x03; // H264_GOP if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_H264_Get_GOP ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Get GOP memset(xu_data, 0, xu_size); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_H264_Get_GOP ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } *GOP = (xu_data[1] << 8) | xu_data[0]; TestAp_Printf(TESTAP_DBG_FLOW, " GOP : %d\n",*GOP); TestAp_Printf(TESTAP_DBG_FLOW, "XU_H264_Get_GOP <== Success \n"); return 0; } int XU_H264_Set_GOP(int fd, unsigned int GOP) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_H264_Set_GOP ==>\n"); int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_H264_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x03; // H264_GOP if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_H264_Set_GOP ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set GOP xu_data[0] = (GOP & 0xFF); xu_data[1] = (GOP >> 8) & 0xFF; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_H264_Set_GOP ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_H264_Set_GOP <== Success \n"); return 0; } int XU_Get(int fd, struct uvc_xu_control *xctrl) { TestAp_Printf(TESTAP_DBG_FLOW, "XU Get ==>\n"); int i = 0; int ret = 0; int err = 0; // XU Set if ((err=XU_Set_Cur(fd, xctrl->unit, xctrl->selector, xctrl->size, xctrl->data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU Get ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // XU Get if ((err=XU_Get_Cur(fd, xctrl->unit, xctrl->selector, xctrl->size, xctrl->data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU Get ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, " == XU Get Success == \n"); for(i=0; i<xctrl->size; i++) TestAp_Printf(TESTAP_DBG_FLOW, " Get data[%d] : 0x%x\n", i, xctrl->data[i]); return ret; } int XU_Set(int fd, struct uvc_xu_control xctrl) { TestAp_Printf(TESTAP_DBG_FLOW, "XU Set ==>\n"); int i = 0; int ret = 0; int err = 0; // XU Set for(i=0; i<xctrl.size; i++) TestAp_Printf(TESTAP_DBG_FLOW, " Set data[%d] : 0x%x\n", i, xctrl.data[i]); if ((err=XU_Set_Cur(fd, xctrl.unit, xctrl.selector, xctrl.size, xctrl.data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU Set ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, " == XU Set Success == \n"); return ret; } int XU_Asic_Read(int fd, unsigned int Addr, unsigned char *AsicData) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_Asic_Read ==>\n"); int ret = 0; __u8 ctrldata[4]; //uvc_xu_control parmeters __u8 xu_unit= 3; __u8 xu_selector= XU_RERVISION_SYS_ASIC_RW; __u16 xu_size= 4; __u8 *xu_data= ctrldata; xu_data[0] = (Addr & 0xFF); xu_data[1] = ((Addr >> 8) & 0xFF); xu_data[2] = 0x0; xu_data[3] = 0xFF; /* Dummy Write */ /* Dummy Write */ if ((ret=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR," ioctl(UVCIOC_CTRL_SET) FAILED (%i) \n",ret); if(ret==EINVAL) TestAp_Printf(TESTAP_DBG_ERR," Invalid arguments\n"); return ret; } /* Asic Read */ xu_data[3] = 0x00; if ((ret=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR," ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",ret); if(ret==EINVAL) TestAp_Printf(TESTAP_DBG_ERR," Invalid arguments\n"); return ret; } *AsicData = xu_data[2]; TestAp_Printf(TESTAP_DBG_FLOW, " == XU_Asic_Read Success ==\n"); TestAp_Printf(TESTAP_DBG_FLOW, " Address:0x%x = 0x%x \n", Addr, *AsicData); TestAp_Printf(TESTAP_DBG_FLOW, "XU_Asic_Read <== Success\n"); return ret; } int XU_Asic_Write(int fd, unsigned int Addr, unsigned char AsicData) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_Asic_Write ==>\n"); int ret = 0; __u8 ctrldata[4]; //uvc_xu_control parmeters __u8 xu_unit= 3; __u8 xu_selector= XU_RERVISION_SYS_ASIC_RW; __u16 xu_size= 4; __u8 *xu_data= ctrldata; xu_data[0] = (Addr & 0xFF); /* Addr Low */ xu_data[1] = ((Addr >> 8) & 0xFF); /* Addr High */ xu_data[2] = AsicData; xu_data[3] = 0x0; /* Normal Write */ /* Normal Write */ if ((ret=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR," ioctl(UVCIOC_CTRL_SET) FAILED (%i) \n",ret); if(ret==EINVAL) TestAp_Printf(TESTAP_DBG_ERR," Invalid arguments\n"); } TestAp_Printf(TESTAP_DBG_FLOW, "XU_Asic_Write <== %s\n",(ret<0?"Failed":"Success")); return ret; } int XU_Multi_Get_status(int fd, struct Multistream_Info *status) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_Multi_Get_status ==>\n"); int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_MULTI_STREAM_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x01; // Multi-Stream Status if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Get_status ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Get status memset(xu_data, 0, xu_size); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Get_status ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } status->strm_type = xu_data[0]; status->format = ( xu_data[1]<<8 )| (xu_data[2]) ; TestAp_Printf(TESTAP_DBG_FLOW, " == XU_Multi_Get_status Success == \n"); TestAp_Printf(TESTAP_DBG_FLOW, " Get strm_type %d\n", status->strm_type); TestAp_Printf(TESTAP_DBG_FLOW, " Get cur_format %d\n", status->format); return 0; } int XU_Multi_Get_Info(int fd, struct Multistream_Info *Info) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_Multi_Get_Info ==>\n"); int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_MULTI_STREAM_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x02; // Multi-Stream Stream Info if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Get_Info ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Get Info memset(xu_data, 0, xu_size); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Get_Info ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } Info->strm_type = xu_data[0]; Info->format = ( xu_data[1]<<8 )| (xu_data[2]) ; TestAp_Printf(TESTAP_DBG_FLOW, " == XU_Multi_Get_Info Success == \n"); TestAp_Printf(TESTAP_DBG_FLOW, " Get Support Stream %d\n", Info->strm_type); TestAp_Printf(TESTAP_DBG_FLOW, " Get Support Resolution 0x%x\n", Info->format); return 0; } int XU_Multi_Set_Type(int fd, unsigned int format) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_Multi_Set_Type (%d) ==>\n",format); int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_MULTI_STREAM_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x02; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Set_Type ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } if(chip_id == CHIP_RER9421 && (format==4 ||format==8 ||format==16)) { TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return -1; } // Set format xu_data[0] = format; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Set_Type ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_Multi_Set_Type <== Success \n"); return 0; } int XU_Multi_Set_Enable(int fd, unsigned char enable) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_Multi_Set_Enable ==>\n"); int err = 0; __u8 ctrldata[11]={0}; // int BitRate_CtrlNum = 0; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_MULTI_STREAM_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x03; // Enable Multi-Stream Flag if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Set_Enable ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set enable / disable multistream xu_data[0] = enable; xu_data[1] = 0; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Set_Enable ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "Set H264_Multi_Enable = %d \n",(xu_data[0] &0x01)); TestAp_Printf(TESTAP_DBG_FLOW, "Set MJPG_Multi_Enable = %d \n",((xu_data[0] >> 1) &0x01)); TestAp_Printf(TESTAP_DBG_FLOW, "XU_Multi_Set_Enable <== Success \n"); return 0; } int XU_Multi_Get_Enable(int fd, unsigned char *enable) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_Multi_Get_Enable ==>\n"); int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_MULTI_STREAM_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x03; // Enable Multi-Stream Flag if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Get_Enable ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Get Enable memset(xu_data, 0, xu_size); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Get_Enable ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } *enable = xu_data[0]; TestAp_Printf(TESTAP_DBG_FLOW, " Get H264 Multi Stream Enable = %d\n", xu_data[0] & 0x01); TestAp_Printf(TESTAP_DBG_FLOW, " Get MJPG Multi Stream Enable = %d\n", (xu_data[0] >> 1) & 0x01); TestAp_Printf(TESTAP_DBG_FLOW, "XU_Multi_Get_Enable <== Success\n"); return 0; } #if 0 int XU_Multi_Set_BitRate(int fd, unsigned int BitRate1, unsigned int BitRate2, unsigned int BitRate3) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_Multi_Set_BitRate BiteRate1=%d BiteRate2=%d BiteRate3=%d ==>\n",BitRate1, BitRate2, BitRate3); int err = 0; __u8 ctrldata[11]={0}; int BitRate_CtrlNum = 0; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_MULTI_STREAM_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; xu_data[1] = 0x04; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Set_BitRate ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set BitRate1~3 (unit:bps) xu_data[0] = (BitRate1 >> 16)&0xFF; xu_data[1] = (BitRate1 >> 8)&0xFF; xu_data[2] = BitRate1&0xFF; xu_data[3] = (BitRate2 >> 16)&0xFF; xu_data[4] = (BitRate2 >> 8)&0xFF; xu_data[5] = BitRate2&0xFF; xu_data[6] = (BitRate3 >> 16)&0xFF; xu_data[7] = (BitRate3 >> 8)&0xFF; xu_data[8] = BitRate3&0xFF; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Set_BitRate ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_Multi_Set_BitRate <== Success \n"); return 0; } int XU_Multi_Get_BitRate(int fd) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_Multi_Get_BitRate ==>\n"); int i = 0; int err = 0; int BitRate1 = 0; int BitRate2 = 0; int BitRate3 = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_MULTI_STREAM_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; xu_data[1] = 0x04; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Get_BitRate ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Get BitRate1~3 (unit:bps) memset(xu_data, 0, xu_size); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Get_BitRate ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_Multi_Get_BitRate <== Success \n"); for(i=0; i<9; i++) TestAp_Printf(TESTAP_DBG_FLOW, " Get data[%d] : 0x%x\n", i, xu_data[i]); BitRate1 = ( xu_data[0]<<16 )| ( xu_data[1]<<8 )| (xu_data[2]) ; BitRate2 = ( xu_data[3]<<16 )| ( xu_data[4]<<8 )| (xu_data[5]) ; BitRate3 = ( xu_data[6]<<16 )| ( xu_data[7]<<8 )| (xu_data[8]) ; TestAp_Printf(TESTAP_DBG_FLOW, " HD BitRate (%d)\n", BitRate1); TestAp_Printf(TESTAP_DBG_FLOW, " QVGA BitRate (%d)\n", BitRate2); TestAp_Printf(TESTAP_DBG_FLOW, " QQVGA BitRate (%d)\n", BitRate3); return 0; } #endif int XU_Multi_Set_BitRate(int fd, unsigned int StreamID, unsigned int BitRate) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_Multi_Set_BitRate StreamID=%d BiteRate=%d ==>\n",StreamID ,BitRate); int err = 0; __u8 ctrldata[11]={0}; // int BitRate_CtrlNum = 0; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_MULTI_STREAM_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; xu_data[1] = 0x04; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Set_BitRate ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set BitRate (unit:bps) xu_data[0] = StreamID; xu_data[1] = (BitRate >> 16)&0xFF; xu_data[2] = (BitRate >> 8)&0xFF; xu_data[3] = BitRate&0xFF; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Set_BitRate ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_Multi_Set_BitRate <== Success \n"); return 0; } int XU_Multi_Get_BitRate(int fd, unsigned int StreamID, unsigned int *BitRate) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_Multi_Get_BitRate ==>\n"); int i = 0; int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_MULTI_STREAM_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; xu_data[1] = 0x05; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Get_BitRate ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set Stream ID xu_data[0] = StreamID; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Get_BitRate ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Get BitRate (unit:bps) memset(xu_data, 0, xu_size); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Get_BitRate ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_Multi_Get_BitRate <== Success \n"); for(i=0; i<4; i++) TestAp_Printf(TESTAP_DBG_FLOW, " Get data[%d] : 0x%x\n", i, xu_data[i]); *BitRate = ( xu_data[1]<<16 ) | ( xu_data[2]<<8 ) | xu_data[3]; TestAp_Printf(TESTAP_DBG_FLOW, " Stream= %d BitRate= %d\n", xu_data[0], *BitRate); return 0; } int XU_Multi_Set_QP(int fd, unsigned int StreamID, unsigned int QP_Val) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_Multi_Set_QP StreamID=%d QP_Val=%d ==>\n",StreamID ,QP_Val); int err = 0; __u8 ctrldata[11]={0}; // int BitRate_CtrlNum = 0; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_MULTI_STREAM_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; xu_data[1] = 0x05; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Set_QP ==> Switch cmd(5) : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set Stream ID xu_data[0] = StreamID; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Set_QP ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Switch command xu_data[0] = 0x9A; xu_data[1] = 0x06; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Set_QP ==> Switch cmd(6) : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set QP xu_data[0] = StreamID; xu_data[1] = QP_Val; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Set_QP ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_Multi_Set_QP <== Success \n"); return 0; } int XU_Multi_Get_QP(int fd, unsigned int StreamID, unsigned int *QP_val) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_Multi_Get_QP ==>\n"); int i = 0; int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_MULTI_STREAM_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; xu_data[1] = 0x05; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Get_QP ==> Switch cmd(5) : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set Stream ID xu_data[0] = StreamID; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Get_QP ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Switch command xu_data[0] = 0x9A; xu_data[1] = 0x06; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Get_QP ==> Switch cmd(6) : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Get QP memset(xu_data, 0, xu_size); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Get_QP ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_Multi_Get_QP <== Success \n"); for(i=0; i<2; i++) TestAp_Printf(TESTAP_DBG_FLOW, " Get data[%d] : 0x%x\n", i, xu_data[i]); *QP_val = xu_data[1]; TestAp_Printf(TESTAP_DBG_FLOW, " Stream= %d QP_val = %d\n", xu_data[0], *QP_val); return 0; } int XU_Multi_Set_H264Mode(int fd, unsigned int StreamID, unsigned int Mode) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_Multi_Set_H264Mode StreamID=%d Mode=%d ==>\n",StreamID ,Mode); int err = 0; __u8 ctrldata[11]={0}; // int BitRate_CtrlNum = 0; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_MULTI_STREAM_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; xu_data[1] = 0x07; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Set_H264Mode ==> Switch cmd(7) : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set Stream ID xu_data[0] = StreamID; xu_data[1] = Mode; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Set_H264Mode ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_Multi_Set_H264Mode <== Success \n"); return 0; } int XU_Multi_Get_H264Mode(int fd, unsigned int StreamID, unsigned int *Mode) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_Multi_Get_H264Mode ==>\n"); int i = 0; int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_MULTI_STREAM_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; xu_data[1] = 0x05; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Get_H264Mode ==> Switch cmd(5) : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set Stream ID xu_data[0] = StreamID; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Get_H264Mode ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Switch command xu_data[0] = 0x9A; xu_data[1] = 0x07; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Get_H264Mode ==> Switch cmd(7) : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Get H264 Mode memset(xu_data, 0, xu_size); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Get_H264Mode ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_Multi_Get_H264Mode <== Success \n"); for(i=0; i<2; i++) TestAp_Printf(TESTAP_DBG_FLOW, " Get data[%d] : 0x%x\n", i, xu_data[i]); *Mode = xu_data[1]; TestAp_Printf(TESTAP_DBG_FLOW, " Stream= %d Mode = %d\n", xu_data[0], *Mode); return 0; } #if 0 int XU_Multi_Set_SubStream_FrameRate(int fd, unsigned int sub_fps) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_Multi_Set_SubStream_FrameRate sub_fps=%d ==>\n",sub_fps); int err = 0, main_fps = 0; __u8 ctrldata[11]={0}; int BitRate_CtrlNum = 0; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_MULTI_STREAM_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; video_get_framerate(fd, &main_fps); if(sub_fps>main_fps) { TestAp_Printf(TESTAP_DBG_ERR,"set sub_fps as %d, because sub_fps must less than or equal to main_fps\n", main_fps); sub_fps = main_fps; } // Switch command xu_data[0] = 0x9A; xu_data[1] = 0x08; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Set_SubStream_FrameRate ==> Switch cmd(8) : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set Stream ID xu_data[0] = sub_fps; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Set_SubStream_FrameRate ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_Multi_Set_SubStream_FrameRate <== Success \n"); return 0; } int XU_Multi_Get_SubStream_FrameRate(int fd, unsigned int *sub_fps) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_Multi_Get_SubStream_FrameRate ==>\n"); int i = 0; int err = 0, main_fps; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_MULTI_STREAM_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; video_get_framerate(fd, &main_fps); // Switch command xu_data[0] = 0x9A; xu_data[1] = 0x08; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Get_H264Mode ==> Switch cmd(8) : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Get substream fr memset(xu_data, 0, xu_size); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Get_SubStream_FrameRate ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_Multi_Get_SubStream_FrameRate <== Success \n"); *sub_fps = (xu_data[0]<main_fps?xu_data[0]:main_fps); TestAp_Printf(TESTAP_DBG_FLOW, "sub_fps = min(%d, %d)\n", xu_data[0],main_fps); return 0; } #endif int XU_Multi_Set_SubStream_GOP(int fd, unsigned int sub_gop) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_Multi_Set_SubStream_GOP sub_gop=%d ==>\n",sub_gop); int err = 0, main_gop = 0; __u8 ctrldata[11]={0}; // int BitRate_CtrlNum = 0; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_MULTI_STREAM_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; XU_H264_Get_GOP(fd, (unsigned int *)(&main_gop)); if(sub_gop > (unsigned int)main_gop) { TestAp_Printf(TESTAP_DBG_ERR,"set sub_gop as %d, because sub_gop must less than or equal to main_gop\n", main_gop); sub_gop= main_gop; } // Switch command xu_data[0] = 0x9A; xu_data[1] = 0x09; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Set_SubStream_GOP ==> Switch cmd(9) : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set sub_gop xu_data[0] = sub_gop&0xff; xu_data[1] = (sub_gop&0xff00)>>8; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Set_SubStream_GOP ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_Multi_Set_SubStream_GOP <== Success \n"); return 0; } int XU_Multi_Get_SubStream_GOP(int fd, unsigned int *sub_gop) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_Multi_Get_SubStream_GOP ==>\n"); // int i = 0; int err = 0, main_gop, get_gop; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_MULTI_STREAM_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; XU_H264_Get_GOP(fd, (unsigned int *)(&main_gop)); // Switch command xu_data[0] = 0x9A; xu_data[1] = 0x09; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Get_SubStream_GOP ==> Switch cmd(9) : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Get substream gop memset(xu_data, 0, xu_size); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Multi_Get_SubStream_GOP ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_Multi_Get_SubStream_GOP <== Success \n"); get_gop = (xu_data[1]<<8) | xu_data[0]; *sub_gop= (get_gop<main_gop?get_gop:main_gop); TestAp_Printf(TESTAP_DBG_FLOW, "sub_fps = min(%d, %d)\n", get_gop,main_gop); return 0; } int XU_OSD_Timer_Ctrl(int fd, unsigned char enable) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Timer_Ctrl ==>\n"); int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_OSD_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x00; // OSD Timer control if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Timer_Ctrl ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set enable / disable timer count xu_data[0] = enable; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Timer_Ctrl ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Timer_Ctrl <== Success \n"); return 0; } int XU_OSD_Set_RTC(int fd, unsigned int year, unsigned char month, unsigned char day, unsigned char hour, unsigned char minute, unsigned char second) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Set_RTC ==>\n"); int i = 0; int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_OSD_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x01; // OSD RTC control if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Set_RTC ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set RTC xu_data[0] = second; xu_data[1] = minute; xu_data[2] = hour; xu_data[3] = day; xu_data[4] = month; xu_data[5] = (year & 0xFF00) >> 8; xu_data[6] = (year & 0x00FF); if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Set_RTC ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } for(i=0; i<7; i++) TestAp_Printf(TESTAP_DBG_FLOW, " Set data[%d] : 0x%x\n", i, xu_data[i]); TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Set_RTC <== Success \n"); return 0; } int XU_OSD_Get_RTC(int fd, unsigned int *year, unsigned char *month, unsigned char *day, unsigned char *hour, unsigned char *minute, unsigned char *second) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Get_RTC ==>\n"); int i = 0; int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_OSD_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x01; // OSD RTC control if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Get_RTC ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Get data memset(xu_data, 0, xu_size); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Get_RTC ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } for(i=0; i<7; i++) TestAp_Printf(TESTAP_DBG_FLOW, " Get data[%d] : 0x%x\n", i, xu_data[i]); TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Get_RTC <== Success \n"); *year = (xu_data[5]<<8) | xu_data[6]; *month = xu_data[4]; *day = xu_data[3]; *hour = xu_data[2]; *minute = xu_data[1]; *second = xu_data[0]; TestAp_Printf(TESTAP_DBG_FLOW, " year = %d \n",*year); TestAp_Printf(TESTAP_DBG_FLOW, " month = %d \n",*month); TestAp_Printf(TESTAP_DBG_FLOW, " day = %d \n",*day); TestAp_Printf(TESTAP_DBG_FLOW, " hour = %d \n",*hour); TestAp_Printf(TESTAP_DBG_FLOW, " minute = %d \n",*minute); TestAp_Printf(TESTAP_DBG_FLOW, " second = %d \n",*second); return 0; } int XU_OSD_Set_Size(int fd, unsigned char LineSize, unsigned char BlockSize) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Set_Size ==>\n"); int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_OSD_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x02; // OSD Size control if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Set_Size ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } if(LineSize > 4) LineSize = 4; if(BlockSize > 4) BlockSize = 4; // Set data xu_data[0] = LineSize; xu_data[1] = BlockSize; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Set_Size ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Set_Size <== Success \n"); return 0; } int XU_OSD_Get_Size(int fd, unsigned char *LineSize, unsigned char *BlockSize) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Get_Size ==>\n"); int i = 0; int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_OSD_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x02; // OSD Size control if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Get_Size ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Get data memset(xu_data, 0, xu_size); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Get_Size ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } for(i=0; i<2; i++) TestAp_Printf(TESTAP_DBG_FLOW, " Get data[%d] : 0x%x\n", i, xu_data[i]); *LineSize = xu_data[0]; *BlockSize = xu_data[1]; TestAp_Printf(TESTAP_DBG_FLOW, "OSD Size (Line) = %d\n",*LineSize); TestAp_Printf(TESTAP_DBG_FLOW, "OSD Size (Block) = %d\n",*BlockSize); TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Get_Size <== Success \n"); return 0; } int XU_OSD_Set_Color(int fd, unsigned char FontColor, unsigned char BorderColor) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Set_Color ==>\n"); int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_OSD_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x03; // OSD Color control if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Set_Color ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } if(FontColor > 4) FontColor = 4; if(BorderColor > 4) BorderColor = 4; // Set data xu_data[0] = FontColor; xu_data[1] = BorderColor; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Set_Color ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Set_Color <== Success \n"); return 0; } int XU_OSD_Get_Color(int fd, unsigned char *FontColor, unsigned char *BorderColor) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Get_Color ==>\n"); int i = 0; int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_OSD_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x03; // OSD Color control if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Get_Color ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Get data memset(xu_data, 0, xu_size); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Get_Color ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } for(i=0; i<2; i++) TestAp_Printf(TESTAP_DBG_FLOW, " Get data[%d] : 0x%x\n", i, xu_data[i]); *FontColor = xu_data[0]; *BorderColor = xu_data[1]; TestAp_Printf(TESTAP_DBG_FLOW, "OSD Font Color = %d\n",*FontColor ); TestAp_Printf(TESTAP_DBG_FLOW, "OSD Border Color = %d\n",*BorderColor); TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Get_Color <== Success \n"); return 0; } int XU_OSD_Set_Enable(int fd, unsigned char Enable_Line, unsigned char Enable_Block) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Set_Enable ==>\n"); int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_OSD_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x04; // OSD enable if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Set_Enable ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set data xu_data[0] = Enable_Line; xu_data[1] = Enable_Block; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Set_Enable ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Set_Enable <== Success \n"); return 0; } int XU_OSD_Get_Enable(int fd, unsigned char *Enable_Line, unsigned char *Enable_Block) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Get_Enable ==>\n"); int i = 0; int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_OSD_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x04; // OSD Enable if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Get_Enable ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Get data memset(xu_data, 0, xu_size); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Get_Enable ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } for(i=0; i<2; i++) TestAp_Printf(TESTAP_DBG_FLOW, " Get data[%d] : 0x%x\n", i, xu_data[i]); *Enable_Line = xu_data[0]; *Enable_Block = xu_data[1]; TestAp_Printf(TESTAP_DBG_FLOW, "OSD Enable Line = %d\n",*Enable_Line); TestAp_Printf(TESTAP_DBG_FLOW, "OSD Enable Block = %d\n",*Enable_Block); TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Get_Enable <== Success \n"); return 0; } int XU_OSD_Set_AutoScale(int fd, unsigned char Enable_Line, unsigned char Enable_Block) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Set_AutoScale ==>\n"); int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_OSD_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x05; // OSD Auto Scale enable if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Set_AutoScale ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set data xu_data[0] = Enable_Line; xu_data[1] = Enable_Block; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Set_AutoScale ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Set_AutoScale <== Success \n"); return 0; } int XU_OSD_Get_AutoScale(int fd, unsigned char *Enable_Line, unsigned char *Enable_Block) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Get_AutoScale ==>\n"); int i = 0; int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_OSD_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x05; // OSD Auto Scale enable if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Get_AutoScale ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Get data memset(xu_data, 0, xu_size); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Get_AutoScale ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } for(i=0; i<2; i++) TestAp_Printf(TESTAP_DBG_FLOW, " Get data[%d] : 0x%x\n", i, xu_data[i]); *Enable_Line = xu_data[0]; *Enable_Block = xu_data[1]; TestAp_Printf(TESTAP_DBG_FLOW, "OSD Enable Line Auto Scale = %d\n",*Enable_Line); TestAp_Printf(TESTAP_DBG_FLOW, "OSD Enable Block Auto Scale = %d\n",*Enable_Block); TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Get_AutoScale <== Success \n"); return 0; } int XU_OSD_Set_Multi_Size(int fd, unsigned char Stream0, unsigned char Stream1, unsigned char Stream2) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Set_Multi_Size %d %d %d ==>\n",Stream0 ,Stream1 , Stream2); int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_OSD_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x06; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Set_Multi_Size ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set data xu_data[0] = Stream0; xu_data[1] = Stream1; xu_data[2] = Stream2; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Set_Multi_Size ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Set_Multi_Size <== Success \n"); return 0; } int XU_OSD_Get_Multi_Size(int fd, unsigned char *Stream0, unsigned char *Stream1, unsigned char *Stream2) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Get_Multi_Size ==>\n"); int i = 0; int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_OSD_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x06; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Get_Multi_Size ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Get data memset(xu_data, 0, xu_size); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Get_Multi_Size ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } for(i=0; i<3; i++) TestAp_Printf(TESTAP_DBG_FLOW, " Get data[%d] : 0x%x\n", i, xu_data[i]); *Stream0 = xu_data[0]; *Stream1 = xu_data[1]; *Stream2 = xu_data[2]; TestAp_Printf(TESTAP_DBG_FLOW, "OSD Multi Stream 0 Size = %d\n",*Stream0); TestAp_Printf(TESTAP_DBG_FLOW, "OSD Multi Stream 1 Size = %d\n",*Stream1); TestAp_Printf(TESTAP_DBG_FLOW, "OSD Multi Stream 2 Size = %d\n",*Stream2); TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Get_Multi_Size <== Success \n"); return 0; } int XU_OSD_Set_Start_Position(int fd, unsigned char OSD_Type, unsigned int RowStart, unsigned int ColStart) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Set_Start_Position ==>\n"); int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_OSD_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x08; // OSD Start Position if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Set_Start_Position ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } if(OSD_Type > 3) OSD_Type = 0; // Set data xu_data[0] = OSD_Type; xu_data[1] = (RowStart & 0xFF00) >> 8; //unit 16 lines xu_data[2] = RowStart & 0x00FF; xu_data[3] = (ColStart & 0xFF00) >> 8; //unit 16 pixels xu_data[4] = ColStart & 0x00FF; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Set_Start_Position ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Set_Start_Position <== Success \n"); return 0; } int XU_OSD_Get_Start_Position(int fd, unsigned int *LineRowStart, unsigned int *LineColStart, unsigned int *BlockRowStart, unsigned int *BlockColStart) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Set_Start_Position ==>\n"); int i = 0; int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_OSD_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x08; // OSD Start Position if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Set_Start_Position ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Get data memset(xu_data, 0, xu_size); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Set_Start_Position ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } for(i=0; i<8; i++) TestAp_Printf(TESTAP_DBG_FLOW, " Get data[%d] : 0x%x\n", i, xu_data[i]); *LineRowStart = (xu_data[0] << 8) | xu_data[1]; *LineColStart = (xu_data[2] << 8) | xu_data[3]; *BlockRowStart = (xu_data[4] << 8) | xu_data[5]; *BlockColStart = (xu_data[6] << 8) | xu_data[7]; TestAp_Printf(TESTAP_DBG_FLOW, "OSD Line Start Row =%d * 16lines\n",*LineRowStart); TestAp_Printf(TESTAP_DBG_FLOW, "OSD Line Start Col =%d * 16pixels\n",*LineColStart); TestAp_Printf(TESTAP_DBG_FLOW, "OSD Block Start Row =%d * 16lines\n",*BlockRowStart); TestAp_Printf(TESTAP_DBG_FLOW, "OSD Block Start Col =%d * 16pixels\n",*BlockColStart); TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Set_Start_Position <== Success \n"); return 0; } int XU_OSD_Set_MS_Start_Position(int fd, unsigned char StreamID, unsigned char RowStart, unsigned char ColStart) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Set_MS_Start_Position ==>\n"); int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_OSD_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x09; // OSD MS Start Position if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Set_MS_Start_Position ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set data xu_data[0] = StreamID; xu_data[1] = RowStart & 0x00FF; xu_data[2] = ColStart & 0x00FF; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Set_MS_Start_Position ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Set_MS_Start_Position %d %d %d<== Success \n", StreamID, RowStart, ColStart); return 0; } int XU_OSD_Get_MS_Start_Position(int fd, unsigned char *S0_Row, unsigned char *S0_Col, unsigned char *S1_Row, unsigned char *S1_Col, unsigned char *S2_Row, unsigned char *S2_Col) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Get_MS_Start_Position ==>\n"); int i = 0; int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_OSD_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x09; // OSD MS Start Position if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Get_MS_Start_Position ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Get data memset(xu_data, 0, xu_size); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Get_MS_Start_Position ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } for(i=0; i<6; i++) TestAp_Printf(TESTAP_DBG_FLOW, " Get data[%d] : 0x%x\n", i, xu_data[i]); *S0_Row = xu_data[0]; *S0_Col = xu_data[1]; *S1_Row = xu_data[2]; *S1_Col = xu_data[3]; *S2_Row = xu_data[4]; *S2_Col = xu_data[5]; TestAp_Printf(TESTAP_DBG_FLOW, "OSD Stream0 Start Row = %d * 16lines\n",*S0_Row); TestAp_Printf(TESTAP_DBG_FLOW, "OSD Stream0 Start Col = %d * 16pixels\n",*S0_Col); TestAp_Printf(TESTAP_DBG_FLOW, "OSD Stream1 Start Row = %d * 16lines\n",*S1_Row); TestAp_Printf(TESTAP_DBG_FLOW, "OSD Stream1 Start Col = %d * 16pixels\n",*S1_Col); TestAp_Printf(TESTAP_DBG_FLOW, "OSD Stream2 Start Row = %d * 16lines\n",*S2_Row); TestAp_Printf(TESTAP_DBG_FLOW, "OSD Stream2 Start Col = %d * 16pixels\n",*S2_Col); TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Get_MS_Start_Position <== Success \n"); return 0; } int XU_OSD_Set_String(int fd, unsigned char group, char *String) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Set_String ==>\n"); int i = 0; int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_OSD_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x07; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Set_String ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set data xu_data[0] = 1; xu_data[1] = group; for(i=0; i<8; i++) xu_data[i+2] = String[i]; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Set_String ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Set_String <== Success \n"); return 0; } int XU_OSD_Get_String(int fd, unsigned char group, char *String) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Get_String ==>\n"); int i = 0; int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_OSD_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x07; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Get_String ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set read mode xu_data[0] = 0; xu_data[1] = group; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Set_String ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Get data memset(xu_data, 0, xu_size); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Get_String ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } group = xu_data[1]; TestAp_Printf(TESTAP_DBG_FLOW, " Get data[0] : 0x%x\n", xu_data[0]); TestAp_Printf(TESTAP_DBG_FLOW, " Get data[1] : 0x%x\n", group); for(i=0; i<8; i++) { String[i] = xu_data[i+2]; TestAp_Printf(TESTAP_DBG_FLOW, " Get data[%d] : 0x%x\n", i+2, String[i]); } TestAp_Printf(TESTAP_DBG_FLOW, "OSD String = %s \n",String); TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Get_String <== Success \n"); return 0; } int XU_MD_Set_Mode(int fd, unsigned char Enable) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_MD_Set_Mode ==>\n"); int err = 0; __u8 ctrldata[24]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_MOTION_DETECTION; __u16 xu_size= 24; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x01; // Motion detection mode if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_MD_Set_Mode ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set data xu_data[0] = Enable; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_MD_Set_Mode ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_MD_Set_Mode <== Success \n"); return 0; } int XU_MD_Get_Mode(int fd, unsigned char *Enable) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_MD_Get_Mode ==>\n"); int err = 0; __u8 ctrldata[24]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_MOTION_DETECTION; __u16 xu_size= 24; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x01; // Motion detection mode if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_MD_Get_Mode ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Get data memset(xu_data, 0, xu_size); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_MD_Get_Mode ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } *Enable = xu_data[0]; TestAp_Printf(TESTAP_DBG_FLOW, "Motion Detect mode = %d\n",*Enable); TestAp_Printf(TESTAP_DBG_FLOW, "XU_MD_Get_Mode <== Success \n"); return 0; } int XU_MD_Set_Threshold(int fd, unsigned int MD_Threshold) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_MD_Set_Threshold ==>\n"); int err = 0; __u8 ctrldata[24]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_MOTION_DETECTION; __u16 xu_size= 24; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x02; // Motion detection threshold if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_MD_Set_Threshold ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set data xu_data[0] = (MD_Threshold & 0xFF00) >> 8; xu_data[1] = MD_Threshold & 0x00FF; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_MD_Set_Threshold ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_MD_Set_Threshold <== Success \n"); return 0; } int XU_MD_Get_Threshold(int fd, unsigned int *MD_Threshold) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_MD_Get_Threshold ==>\n"); int err = 0; __u8 ctrldata[24]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_MOTION_DETECTION; __u16 xu_size= 24; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x02; // Motion detection threshold if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_MD_Get_Threshold ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Get data memset(xu_data, 0, xu_size); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_MD_Get_Threshold ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } *MD_Threshold = (xu_data[0] << 8) | xu_data[1]; TestAp_Printf(TESTAP_DBG_FLOW, "Motion Detect threshold = %d\n",*MD_Threshold); TestAp_Printf(TESTAP_DBG_FLOW, "XU_MD_Get_Threshold <== Success \n"); return 0; } int XU_MD_Set_Mask(int fd, unsigned char *Mask) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_MD_Set_Mask ==>\n"); int err = 0; unsigned char i; __u8 ctrldata[24]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_MOTION_DETECTION; __u16 xu_size= 24; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x03; // Motion detection mask if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_MD_Set_Mask ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set data for(i=0; i < 24; i++) { xu_data[i] = Mask[i]; } if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_MD_Set_Mask ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_MD_Set_Mask <== Success \n"); return 0; } int XU_MD_Get_Mask(int fd, unsigned char *Mask) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_MD_Get_Mask ==>\n"); int err = 0; int i,j,k; __u8 ctrldata[24]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_MOTION_DETECTION; __u16 xu_size= 24; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x03; // Motion detection mask if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_MD_Get_Mask ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i) \n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Get data memset(xu_data, 0, xu_size); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_MD_Get_Mask ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i) \n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } for(i=0; i<24; i++) { TestAp_Printf(TESTAP_DBG_FLOW, " Get data[%d] : 0x%x\n", i, xu_data[i]); Mask[i] = xu_data[i]; } TestAp_Printf(TESTAP_DBG_FLOW, " ====== Motion Detect Mask ====== \n"); TestAp_Printf(TESTAP_DBG_FLOW, " 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 \n"); for(k=0; k<12; k++) { TestAp_Printf(TESTAP_DBG_FLOW, "%2d ",k+1); for(j=0; j<2; j++) { for(i=0; i<8; i++) TestAp_Printf(TESTAP_DBG_FLOW, "%d ",(Mask[k*2+j]>>i)&0x01); } TestAp_Printf(TESTAP_DBG_FLOW, "\n"); } TestAp_Printf(TESTAP_DBG_FLOW, "XU_MD_Get_Mask <== Success \n"); return 0; } int XU_MD_Set_RESULT(int fd, unsigned char *Result) { //TestAp_Printf(TESTAP_DBG_FLOW, "XU_MD_Set_RESULT ==>\n"); int err = 0; unsigned char i; __u8 ctrldata[24]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_MOTION_DETECTION; __u16 xu_size= 24; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x04; // Motion detection Result if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_MD_Set_RESULT ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set data for(i=0; i < 24; i++) { xu_data[i] = Result[i]; } if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_MD_Set_RESULT ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } //TestAp_Printf(TESTAP_DBG_FLOW, "XU_MD_Set_RESULT <== Success \n"); return 0; } int XU_MD_Get_RESULT(int fd, unsigned char *Result) { //TestAp_Printf(TESTAP_DBG_FLOW, "XU_MD_Get_RESULT ==>\n"); int err = 0; int i,j,k; __u8 ctrldata[24]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_MOTION_DETECTION; __u16 xu_size= 24; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x04; // Motion detection Result if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_MD_Get_RESULT ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i) \n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Get data memset(xu_data, 0, xu_size); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_MD_Get_RESULT ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i) \n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } for(i=0; i<24; i++) { //TestAp_Printf(TESTAP_DBG_FLOW, " Get data[%d] : 0x%x\n", i, xu_data[i]); Result[i] = xu_data[i]; } // system("clear"); TestAp_Printf(TESTAP_DBG_FLOW, " ------ Motion Detect Result ------ \n"); TestAp_Printf(TESTAP_DBG_FLOW, " 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 \n"); for(k=0; k<12; k++) { TestAp_Printf(TESTAP_DBG_FLOW, "%2d ",k+1); for(j=0; j<2; j++) { for(i=0; i<8; i++) TestAp_Printf(TESTAP_DBG_FLOW, "%d ",(Result[k*2+j]>>i)&0x01); } TestAp_Printf(TESTAP_DBG_FLOW, "\n"); } //TestAp_Printf(TESTAP_DBG_FLOW, "XU_MD_Get_RESULT <== Success \n"); return 0; } int XU_MJPG_Get_Bitrate(int fd, unsigned int *MJPG_Bitrate) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_MJPG_Get_Bitrate ==>\n"); int i = 0; int ret = 0; int err = 0; __u8 ctrldata[11]={0}; int BitRate_CtrlNum = 0; *MJPG_Bitrate = 0; //uvc_xu_control parmeters __u8 xu_unit= 0; __u8 xu_selector= 0; __u16 xu_size= 11; __u8 *xu_data= ctrldata; if(chip_id == CHIP_RER9420) { xu_unit = XU_RERVISION_SYS_ID; xu_selector = XU_RERVISION_SYS_MJPG_CTRL; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x02; } else if((chip_id == CHIP_RER9421)||(chip_id == CHIP_RER9422)) { xu_unit = XU_RERVISION_USR_ID; xu_selector = XU_RERVISION_USR_MJPG_CTRL; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x01; } if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_MJPG_Get_Bitrate ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Get Bit rate ctrl number memset(xu_data, 0, xu_size); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_MJPG_Get_Bitrate ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, " == XU_MJPG_Get_Bitrate Success == \n"); if(chip_id == CHIP_RER9420) { for(i=0; i<2; i++) TestAp_Printf(TESTAP_DBG_FLOW, " Get data[%d] : 0x%x\n", i, xu_data[i]); BitRate_CtrlNum = ( xu_data[0]<<8 )| (xu_data[1]) ; // Bit Rate = BitRate_Ctrl_Num*256*fps*8 /1024(Kbps) *MJPG_Bitrate = (BitRate_CtrlNum*256.0*m_CurrentFPS*8)/1024.0; } else if((chip_id == CHIP_RER9421)||(chip_id == CHIP_RER9422)) { for(i=0; i<4; i++) TestAp_Printf(TESTAP_DBG_FLOW, " Get data[%d] : 0x%x\n", i, xu_data[i]); *MJPG_Bitrate = (xu_data[0] << 24) | (xu_data[1] << 16) | (xu_data[2] << 8) | (xu_data[3]) ; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_MJPG_Get_Bitrate (%x)<==\n", *MJPG_Bitrate); return ret; } int XU_MJPG_Set_Bitrate(int fd, unsigned int MJPG_Bitrate) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_MJPG_Set_Bitrate (%x) ==>\n",MJPG_Bitrate); int ret = 0; int err = 0; __u8 ctrldata[11]={0}; int BitRate_CtrlNum = 0; //uvc_xu_control parmeters __u8 xu_unit= 0; __u8 xu_selector= 0; __u16 xu_size= 11; __u8 *xu_data= ctrldata; if(chip_id == CHIP_RER9420) { xu_unit = XU_RERVISION_SYS_ID; xu_selector = XU_RERVISION_SYS_MJPG_CTRL; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x02; } else if((chip_id == CHIP_RER9421)||(chip_id == CHIP_RER9422)) { xu_unit = XU_RERVISION_USR_ID; xu_selector = XU_RERVISION_USR_MJPG_CTRL; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x01; } if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_MJPG_Set_Bitrate ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set Bit Rate Ctrl Number if(chip_id == CHIP_RER9420) { // Bit Rate = BitRate_Ctrl_Num*256*fps*8/1024 (Kbps) BitRate_CtrlNum = ((MJPG_Bitrate*1024)/(256*m_CurrentFPS*8)); xu_data[0] = (BitRate_CtrlNum & 0xFF00) >> 8; xu_data[1] = (BitRate_CtrlNum & 0x00FF); } else if((chip_id == CHIP_RER9421)||(chip_id == CHIP_RER9422)) { xu_data[0] = (MJPG_Bitrate & 0xFF000000) >> 24; xu_data[1] = (MJPG_Bitrate & 0x00FF0000) >> 16; xu_data[2] = (MJPG_Bitrate & 0x0000FF00) >> 8; xu_data[3] = (MJPG_Bitrate & 0x000000FF); } if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_MJPG_Set_Bitrate ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_MJPG_Set_Bitrate <== Success \n"); return ret; } int XU_IMG_Set_Mirror(int fd, unsigned char Mirror) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_IMG_Set_Mirror ==>\n"); int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= 0; __u8 xu_selector= 0; __u16 xu_size= 11; __u8 *xu_data= ctrldata; if(chip_id == CHIP_RER9420) { xu_unit = XU_RERVISION_SYS_ID; xu_selector = XU_RERVISION_SYS_IMG_SETTING; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x01; } else if((chip_id == CHIP_RER9421)||(chip_id == CHIP_RER9422)) { xu_unit = XU_RERVISION_USR_ID; xu_selector = XU_RERVISION_USR_IMG_SETTING; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x01; } if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_IMG_Set_Mirror ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set data xu_data[0] = Mirror; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_IMG_Set_Mirror ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_IMG_Set_Mirror 0x%x <== Success \n",Mirror); return 0; } int XU_IMG_Get_Mirror(int fd, unsigned char *Mirror) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_IMG_Get_Mirror ==>\n"); int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= 0; __u8 xu_selector= 0; __u16 xu_size= 11; __u8 *xu_data= ctrldata; if(chip_id == CHIP_RER9420) { xu_unit = XU_RERVISION_SYS_ID; xu_selector = XU_RERVISION_SYS_IMG_SETTING; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x01; } else if((chip_id == CHIP_RER9421)||(chip_id == CHIP_RER9422)) { xu_unit = XU_RERVISION_USR_ID; xu_selector = XU_RERVISION_USR_IMG_SETTING; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x01; } if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_IMG_Get_Mirror ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Get data memset(xu_data, 0, xu_size); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_IMG_Get_Mirror ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } *Mirror = xu_data[0]; TestAp_Printf(TESTAP_DBG_FLOW, "Mirror = %d\n",*Mirror); TestAp_Printf(TESTAP_DBG_FLOW, "XU_IMG_Get_Mirror <== Success \n"); return 0; } int XU_IMG_Set_Flip(int fd, unsigned char Flip) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_IMG_Set_Flip ==>\n"); int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= 0; __u8 xu_selector= 0; __u16 xu_size= 11; __u8 *xu_data= ctrldata; if(chip_id == CHIP_RER9420) { xu_unit = XU_RERVISION_SYS_ID; xu_selector = XU_RERVISION_SYS_IMG_SETTING; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x02; } else if((chip_id == CHIP_RER9421)||(chip_id == CHIP_RER9422)) { xu_unit = XU_RERVISION_USR_ID; xu_selector = XU_RERVISION_USR_IMG_SETTING; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x02; } if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_IMG_Set_Flip ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set data xu_data[0] = Flip; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_IMG_Set_Flip ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_IMG_Set_Flip 0x%x <== Success \n",Flip); return 0; } int XU_IMG_Get_Flip(int fd, unsigned char *Flip) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_IMG_Get_Flip ==>\n"); int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= 0; __u8 xu_selector= 0; __u16 xu_size= 11; __u8 *xu_data= ctrldata; if(chip_id == CHIP_RER9420) { xu_unit = XU_RERVISION_SYS_ID; xu_selector = XU_RERVISION_SYS_IMG_SETTING; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x02; } else if((chip_id == CHIP_RER9421)||(chip_id == CHIP_RER9422)) { xu_unit = XU_RERVISION_USR_ID; xu_selector = XU_RERVISION_USR_IMG_SETTING; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x02; } if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_IMG_Get_Flip ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Get data memset(xu_data, 0, xu_size); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_IMG_Get_Flip ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } *Flip = xu_data[0]; TestAp_Printf(TESTAP_DBG_FLOW, "Flip = %d\n",*Flip); TestAp_Printf(TESTAP_DBG_FLOW, "XU_IMG_Get_Flip <== Success \n"); return 0; } int XU_IMG_Set_Color(int fd, unsigned char Color) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_IMG_Set_Color ==>\n"); int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= 0; __u8 xu_selector= 0; __u16 xu_size= 11; __u8 *xu_data= ctrldata; if(chip_id == CHIP_RER9420) { xu_unit = XU_RERVISION_SYS_ID; xu_selector = XU_RERVISION_SYS_IMG_SETTING; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x03; } else if((chip_id == CHIP_RER9421)||(chip_id == CHIP_RER9422)) { xu_unit = XU_RERVISION_USR_ID; xu_selector = XU_RERVISION_USR_IMG_SETTING; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x03; } if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_IMG_Set_Color ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set data xu_data[0] = Color; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_IMG_Set_Color ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_IMG_Set_Color 0x%x <== Success \n",Color); return 0; } int XU_IMG_Get_Color(int fd, unsigned char *Color) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_IMG_Get_Color ==>\n"); int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= 0; __u8 xu_selector= 0; __u16 xu_size= 11; __u8 *xu_data= ctrldata; if(chip_id == CHIP_RER9420) { xu_unit = XU_RERVISION_SYS_ID; xu_selector = XU_RERVISION_SYS_IMG_SETTING; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x03; } else if((chip_id == CHIP_RER9421)||(chip_id == CHIP_RER9422)) { xu_unit = XU_RERVISION_USR_ID; xu_selector = XU_RERVISION_USR_IMG_SETTING; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x03; } if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_IMG_Get_Color ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Get data memset(xu_data, 0, xu_size); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_IMG_Get_Color ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } *Color = xu_data[0]; TestAp_Printf(TESTAP_DBG_FLOW, "Image Color = %d\n",*Color); TestAp_Printf(TESTAP_DBG_FLOW, "XU_IMG_Get_Color <== Success \n"); return 0; } //-------------------------------------------------------------------------------------- int XU_OSD_Set_CarcamCtrl(int fd, unsigned char SpeedEn, unsigned char CoordinateEn, unsigned char CoordinateCtrl) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Set_CarcamCtrl ==>\n"); int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_OSD_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x0A; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Set_CarcamCtrl ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set data xu_data[0] = SpeedEn; xu_data[1] = CoordinateEn; xu_data[2] = CoordinateCtrl; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Set_CarcamCtrl ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Set_CarcamCtrl 0x%x 0x%x 0x%x <== Success \n", xu_data[0], xu_data[1], xu_data[2]); return 0; } int XU_OSD_Get_CarcamCtrl(int fd, unsigned char *SpeedEn, unsigned char *CoordinateEn, unsigned char *CoordinateCtrl) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Get_CarcamCtrl ==>\n"); int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_OSD_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x0A; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Get_CarcamCtrl ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Get data memset(xu_data, 0, xu_size); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Get_CarcamCtrl ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } *SpeedEn = xu_data[0]; *CoordinateEn = xu_data[1]; *CoordinateCtrl = xu_data[2]; TestAp_Printf(TESTAP_DBG_FLOW, "OSD speed en = %d\n",*SpeedEn); TestAp_Printf(TESTAP_DBG_FLOW, "OSD coordinate en = %d\n",*CoordinateEn); TestAp_Printf(TESTAP_DBG_FLOW, "OSD coordinate ctrl = %d\n",*CoordinateCtrl); TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Get_CarcamCtrl <== Success \n"); return 0; } int XU_OSD_Set_Speed(int fd, unsigned int Speed) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Set_Speed ==>\n"); int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_OSD_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x0B; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Set_Speed ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set data xu_data[0] = (Speed >> 8) & 0xFF; xu_data[1] = Speed & 0xFF; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Set_Speed ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Set_Speed 0x%x 0x%x <== Success \n", xu_data[0], xu_data[1]); return 0; } int XU_OSD_Get_Speed(int fd, unsigned int *Speed) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Get_Speed ==>\n"); int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_OSD_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x0B; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Get_Speed ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Get data memset(xu_data, 0, xu_size); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Get_Speed ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } *Speed = (xu_data[0]<<8) | (xu_data[1]); TestAp_Printf(TESTAP_DBG_FLOW, "OSD speed = %d \n",*Speed); TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Get_Speed <== Success \n"); return 0; } int XU_OSD_Set_Coordinate1(int fd, unsigned char Direction, unsigned char *Vaule) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Set_Coordinate1 ==>\n"); int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_OSD_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x0C; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Set_Coordinate1 ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set data xu_data[0] = Direction; xu_data[1] = Vaule[0]; xu_data[2] = Vaule[1]; xu_data[3] = Vaule[2]; xu_data[4] = 0; xu_data[5] = Vaule[3]; xu_data[6] = Vaule[4]; xu_data[7] = Vaule[5]; xu_data[8] = 0; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Set_Coordinate1 ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Set_Coordinate 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x <== Success \n", xu_data[0], xu_data[1], xu_data[2], xu_data[3], xu_data[4], xu_data[5], xu_data[6], xu_data[7], xu_data[8]); return 0; } int XU_OSD_Set_Coordinate2(int fd, unsigned char Direction, unsigned char Vaule1, unsigned long Vaule2, unsigned char Vaule3, unsigned long Vaule4) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Set_Coordinate2 ==>\n"); int err = 0; // char i; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_OSD_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x0C; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Set_Coordinate2 ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set data xu_data[0] = Direction; xu_data[1] = Vaule1; xu_data[2] = (Vaule2 >> 16) & 0xFF; xu_data[3] = (Vaule2 >> 8) & 0xFF; xu_data[4] = Vaule2 & 0xFF; xu_data[5] = Vaule3; xu_data[6] = (Vaule4 >> 16) & 0xFF; xu_data[7] = (Vaule4 >> 8) & 0xFF; xu_data[8] = Vaule4 & 0xFF; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Set_Coordinate2 ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Set_Coordinate2 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x <== Success \n", xu_data[0], xu_data[1], xu_data[2], xu_data[3], xu_data[4], xu_data[5], xu_data[6], xu_data[7], xu_data[8]); return 0; } int XU_OSD_Get_Coordinate1(int fd, unsigned char *Direction, unsigned char *Vaule) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Get_Coordinate1 ==>\n"); int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_OSD_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x0C; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Get_Coordinate1 ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Get data memset(xu_data, 0, xu_size); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Get_Coordinate1 ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } *Direction = xu_data[0]; Vaule[0] = xu_data[1]; Vaule[1] = xu_data[2]; Vaule[2] = xu_data[3]; Vaule[3] = xu_data[5]; Vaule[4] = xu_data[6]; Vaule[5] = xu_data[7]; TestAp_Printf(TESTAP_DBG_FLOW, "OSD Coordinate direction = %d\n",*Direction); TestAp_Printf(TESTAP_DBG_FLOW, "OSD Coordinate degree1 = %d\n",Vaule[0] ); TestAp_Printf(TESTAP_DBG_FLOW, "OSD Coordinate minute1 = %d\n",Vaule[1] ); TestAp_Printf(TESTAP_DBG_FLOW, "OSD Coordinate second1 = %d\n",Vaule[2] ); TestAp_Printf(TESTAP_DBG_FLOW, "OSD Coordinate degree2 = %d\n",Vaule[3] ); TestAp_Printf(TESTAP_DBG_FLOW, "OSD Coordinate minute2 = %d\n",Vaule[4] ); TestAp_Printf(TESTAP_DBG_FLOW, "OSD Coordinate second2 = %d\n",Vaule[5] ); TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Get_Coordinate1 <== Success \n"); return 0; } int XU_OSD_Get_Coordinate2(int fd, unsigned char *Direction, unsigned char *Vaule1, unsigned long *Vaule2, unsigned char *Vaule3, unsigned long *Vaule4) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Get_Coordinate2 ==>\n"); int err = 0; // char i; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_OSD_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x0C; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Get_Coordinate2 ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Get data memset(xu_data, 0, xu_size); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_OSD_Get_Coordinate2 ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } *Direction = xu_data[0]; *Vaule1 = xu_data[1]; *Vaule2 =(xu_data[2]<<16) | (xu_data[3]<<8) | (xu_data[4]); *Vaule3 = xu_data[5]; *Vaule4 =(xu_data[6]<<16) | (xu_data[7]<<8) | (xu_data[8]); TestAp_Printf(TESTAP_DBG_FLOW, "OSD Coordinate direction = %d\n",*Direction); TestAp_Printf(TESTAP_DBG_FLOW, "OSD Coordinate degree1 = %d.%05ld\n",*Vaule1, *Vaule2); TestAp_Printf(TESTAP_DBG_FLOW, "OSD Coordinate degree2 = %d.%05ld\n",*Vaule3, *Vaule4); TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Get_Coordinate2 <== Success \n"); return 0; } int XU_GPIO_Ctrl_Set(int fd, unsigned char GPIO_En, unsigned char GPIO_Value) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_GPIO_Ctrl_Set ==>\n"); int err = 0; // char i; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_GPIO_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x01; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_GPIO_Ctrl_Set ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set data xu_data[0] = GPIO_En; xu_data[1] = GPIO_Value; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_GPIO_Ctrl_Set ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_GPIO_Ctrl_Set 0x%x 0x%x <== Success \n", xu_data[0], xu_data[1]); return 0; } int XU_GPIO_Ctrl_Get(int fd, unsigned char *GPIO_En, unsigned char *GPIO_OutputValue, unsigned char *GPIO_InputValue) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_GPIO_Ctrl_Get ==>\n"); int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_GPIO_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x01; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_GPIO_Ctrl_Get ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Get data memset(xu_data, 0, xu_size); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_GPIO_Ctrl_Get ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } *GPIO_En = xu_data[0]; *GPIO_OutputValue = xu_data[1]; *GPIO_InputValue = xu_data[2]; TestAp_Printf(TESTAP_DBG_FLOW, "GPIO enable = 0x%x\n",*GPIO_En); TestAp_Printf(TESTAP_DBG_FLOW, "GPIO Output value = 0x%x, Input value = 0x%x\n",*GPIO_OutputValue,*GPIO_InputValue); TestAp_Printf(TESTAP_DBG_FLOW, "XU_GPIO_Ctrl_Get <== Success \n"); return 0; } int XU_Frame_Drop_En_Set(int fd, unsigned char Stream1_En, unsigned char Stream2_En) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_Frame_Drop_En_Set ==>\n"); int err = 0; // char i; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_DYNAMIC_FPS_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x01; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Frame_Drop_En_Set ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set data xu_data[0] = Stream1_En; xu_data[1] = Stream2_En; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Frame_Drop_En_Set ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_Frame_Drop_En_Set 0x%x 0x%x <== Success \n", xu_data[0], xu_data[1]); return 0; } int XU_Frame_Drop_En_Get(int fd, unsigned char *Stream1_En, unsigned char *Stream2_En) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_Frame_Drop_En_Get ==>\n"); int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_DYNAMIC_FPS_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x01; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Frame_Drop_En_Get ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Get data memset(xu_data, 0, xu_size); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Frame_Drop_En_Get ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } *Stream1_En = xu_data[0]; *Stream2_En = xu_data[1]; TestAp_Printf(TESTAP_DBG_FLOW, "Stream1 frame drop enable = %d\n",*Stream1_En); TestAp_Printf(TESTAP_DBG_FLOW, "Stream2 frame drop enable = %d\n",*Stream2_En); TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Get_Coordinate1 <== Success \n"); return 0; } int XU_Frame_Drop_Ctrl_Set(int fd, unsigned char Stream1_fps, unsigned char Stream2_fps) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_Frame_Drop_Ctrl_Set ==>\n"); int err = 0; // char i; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_DYNAMIC_FPS_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x02; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Frame_Drop_Ctrl_Set ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Set data xu_data[0] = Stream1_fps; xu_data[1] = Stream2_fps; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Frame_Drop_Ctrl_Set ==> ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } TestAp_Printf(TESTAP_DBG_FLOW, "XU_Frame_Drop_Ctrl_Set 0x%x 0x%x <== Success \n", xu_data[0], xu_data[1]); return 0; } int XU_Frame_Drop_Ctrl_Get(int fd, unsigned char *Stream1_fps, unsigned char *Stream2_fps) { TestAp_Printf(TESTAP_DBG_FLOW, "XU_Frame_Drop_Ctrl_Get ==>\n"); int err = 0; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_USR_ID; __u8 xu_selector= XU_RERVISION_USR_DYNAMIC_FPS_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; // Switch command xu_data[0] = 0x9A; // Tag xu_data[1] = 0x02; if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Frame_Drop_Ctrl_Get ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } // Get data memset(xu_data, 0, xu_size); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_Frame_Drop_Ctrl_Get ==> ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } *Stream1_fps = xu_data[0]; *Stream2_fps = xu_data[1]; TestAp_Printf(TESTAP_DBG_FLOW, "Stream1 frame = %d\n",*Stream1_fps); TestAp_Printf(TESTAP_DBG_FLOW, "Stream2 frame = %d\n",*Stream2_fps); TestAp_Printf(TESTAP_DBG_FLOW, "XU_OSD_Get_Coordinate1 <== Success \n"); return 0; } int XU_SF_Read(int fd, unsigned int Addr, unsigned char* pData,unsigned int Length) { #define DEF_SF_RW_LENGTH 8 #define min(a,b) a<b?a:b //TestAp_Printf(TESTAP_DBG_FLOW, "XU_SF_Read ==>\n"); int err = 0; unsigned int i,ValidLength = 0, loop = 0, remain = 0; unsigned char* pCopy = pData; __u8 ctrldata[11]={0}; //uvc_xu_control parmeters __u8 xu_unit= XU_RERVISION_SYS_ID; __u8 xu_selector= XU_RERVISION_SYS_FLASH_CTRL; __u16 xu_size= 11; __u8 *xu_data= ctrldata; if(Addr < 0x10000) ValidLength = min(0x10000 - Addr, Length); else ValidLength = min(0x20000 - Addr, Length); loop = ValidLength/DEF_SF_RW_LENGTH; remain = ValidLength%DEF_SF_RW_LENGTH; //TestAp_Printf(TESTAP_DBG_ERR,"valid = %d, loop = %d, remain = %d\n", ValidLength,loop,remain); //get sf data for(i = 0; i < loop; i++) { xu_data[0] = (Addr+i*DEF_SF_RW_LENGTH)&0xff; xu_data[1] = ((Addr+i*DEF_SF_RW_LENGTH)>>8)&0xff; if(Addr+i*DEF_SF_RW_LENGTH < 0x10000) xu_data[2] = 0x80 | DEF_SF_RW_LENGTH; else xu_data[2] = 0x90 | DEF_SF_RW_LENGTH; //set sf start addr if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_SF_Read ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } memset(xu_data, 0, xu_size*sizeof(__u8)); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_SF_Read ==> Switch cmd : ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Read SF error\n"); return err; } memcpy(pCopy,xu_data+3,DEF_SF_RW_LENGTH); pCopy += DEF_SF_RW_LENGTH; } if(remain) { xu_data[0] = (Addr+loop*DEF_SF_RW_LENGTH)&0xff; xu_data[1] = ((Addr+loop*DEF_SF_RW_LENGTH)>>8)&0xff; if(Addr < 0x10000) xu_data[2] = 0x80 | remain; else xu_data[2] = 0x90 | remain; //set addr and length of remain if ((err=XU_Set_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_SF_Read ==> Switch cmd : ioctl(UVCIOC_CTRL_SET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Invalid arguments\n"); return err; } //get data of remain memset(xu_data, 0, xu_size*sizeof(__u8)); if ((err=XU_Get_Cur(fd, xu_unit, xu_selector, xu_size, xu_data)) < 0) { TestAp_Printf(TESTAP_DBG_ERR,"XU_SF_Read ==> Switch cmd : ioctl(UVCIOC_CTRL_GET) FAILED (%i)\n",err); if(err==EINVAL) TestAp_Printf(TESTAP_DBG_ERR,"Read SF error\n"); return err; } memcpy(pCopy,xu_data+3,remain); } //TestAp_Printf(TESTAP_DBG_FLOW, "XU_SF_Read <== Success \n"); return 0; }
[ "846863428@qq.com" ]
846863428@qq.com
73ee379d420ed9973a3f079551563a1ddb3f1129
48c7c6b9c7a7ef7d2395b6b650d333e693221817
/StonePile Splitter/closing.cpp
17edc22268cfc471cd07d729bc5849bd550b5783
[]
no_license
davidlng8/StonepileSplitter
dec6c965f840aa44ce719828a91dd2a478f3585e
7cbc8d93135a859851e2af2819480cb069375f80
refs/heads/master
2016-09-05T13:23:45.428447
2014-03-17T22:41:46
2014-03-17T22:41:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
43
cpp
#include "StdAfx.h" #include "closeing.h"
[ "david_lng8@yahoo.com" ]
david_lng8@yahoo.com
4119edef8e34e67236a1f1133720bacf0e6affc0
a84d6cd1cbebea137ce0e98367dc7a0d003c2457
/aoapc/vol1/string/trie.cc
d87bea2404d508432f4a2d8b364ffe2d9f085426
[]
no_license
YigWoo/uva
58a32fd975798196061ca647b3f0df2a723dee97
fd4aaff915dd6bf9309c52d5f293f7de91ca93af
refs/heads/master
2020-03-30T03:36:21.149725
2013-10-01T16:09:03
2013-10-01T16:09:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,600
cc
#include "trie.h" #include <iostream> using namespace std; Trie::Node::Node():isKey(false) { for (int i = 0; i < R; i++) children.push_back(NULL); } Trie::Node::~Node() {} /* void Trie::Node::modChild(int n, Node *child) { */ /* if (n < children.size()) */ /* children[n] = child; */ /* else */ /* cout << "wrong index" << endl; */ /* } */ /* vector<Trie::Node*> Trie::Node::getChildren() {return children;} */ /* void Trie::Node::addChild(Node *child) {children.push_back(child);} */ /* char Trie::Node::getChar() {return content;} */ /* void Trie::Node::setChar(char c) {content = c;} */ /* bool Trie::Node::getIsKey() {return isKey;} */ /* void Trie::Node::setIsKey(bool b) {isKey = b;} */ /* Trie::Node* Trie::Node::findChild(char c) { */ /* for (size_t i = 0; i != children.size(); i++) { */ /* Node *tmp = children[i]; */ /* // if tmp != NULL is not added, there will be a bug */ /* // since addChild do not check for NULL nodes */ /* // if we add NULL node into children */ /* // and call findChild, NULL node will be used */ /* // cause NULL pointer exceptions */ /* if (tmp != NULL && tmp->getChar() == c) */ /* return tmp; */ /* } */ /* return NULL; */ /* } */ Trie::Trie() { root = new Node();} Trie::~Trie() { destory(root); } void Trie::destory(Node* x) { for (int i = 0; i < R; i++) if (x->children[i] != NULL) destory(x->children[i]); delete x; } size_t Trie::size() {return size(root);} size_t Trie::size(const Node* x) { if (x == NULL) return 0; size_t cnt = 0; if (x->isKey == true) cnt++; for (int i = 0; i < R; i++) cnt += size(x->children[i]); return cnt; } bool Trie::isEmpty() {return size(root) == 0;} void Trie::insert(const string& key) { root = put(root, key, 0); } Trie::Node* Trie::put(Node* x, const string& key, size_t d) { if (x == NULL) x = new Node(); if (d == key.length()) { x->isKey = true; return x; } char c = key[d]; x->children[c-'a'] = put(x->children[c-'a'], key, d+1); return x; } bool Trie::contains(const string& key) const{ /* const pointer as return type */ const Node* x = get(root, key, 0); if (x == NULL) return false; return x->isKey; } const Trie::Node* Trie::get(Node* x, const string& key, size_t d) const { if (x == NULL) return NULL; if (d == key.size()) return x; char c = key[d]; /* the next line is a little bit of hard coding */ /* some other lines in the code are similar */ return get(x->children[c-'a'], key, d+1); } void Trie::remove(const string& key) { root = remove(root, key, 0); } Trie::Node* Trie::remove(Node* x, const string& key, size_t d) { if (x == NULL) return NULL; if (d == key.size()) x->isKey = false; else { char c = key[d]; x->children[c-'a'] = remove(x->children[c-'a'], key, d+1); } /* The following line is a tricky line, * it ensures that if the node corresponds * to the last character of a key, recursive * deletion stops here, otherwise, program * check whether the node has non-NULL nodes, * if not, it will remove current node. */ if (x->isKey != false) return x; for (int c = 0; c < R; c++) if (x->children[c] != NULL) return x; delete x; return NULL; } string Trie::longestPrefixOf(string query) const { } vector<string> Trie::keys() const { return keysWithPrefix(""); } vector<string> Trie::keysWithPrefix(const string& prefix) const { vector<string> q; collect(get(root, prefix, 0), prefix, q); return q; } void Trie::collect(const Node* x, const string& key, vector<string>& q) const { if (x == NULL) return; if (x->isKey == true) q.push_back(key); for (int i = 0; i < R; i++) { char c = (char) (i + 'a'); collect(x->children[i], key+c, q); } } /* unit test */ int main() { /* Trie::Node *root = new Trie::Node(); */ /* for (int i = 0; i < 26; i++) */ /* root->addChild(NULL); */ /* root->setChar('a'); */ /* root->setIsKey(true); */ /* Trie::Node *child = new Trie::Node(); */ /* child->setChar('b'); */ /* child->setIsKey(true); */ /* for (int i = 0; i < 26; i++) */ /* child->addChild(NULL); */ /* root->modChild('b'-'a', child); */ /* vector<Trie::Node*> children = root->getChildren(); */ /* for (int i = 0; i < 26; i++) */ /* if (children[i] != NULL) */ /* cout << children[i]->getChar() << endl; */ /* cout << root->findChild('b')->getChar() << endl; */ Trie trie = Trie(); cout << trie.size() << endl; if (trie.isEmpty()) cout << "The trie is empty" << endl; trie.insert("she"); trie.insert("sells"); trie.insert("sea"); trie.insert("shells"); trie.insert("by"); trie.insert("the"); trie.insert("sea"); trie.insert("shore"); vector<string> vs; vs = trie.keys(); for (vector<string>::iterator it = vs.begin(); it != vs.end(); it++) { cout << *it << " "; } cout << endl; cout << "The size of the trie is: "; cout << trie.size() << endl; if (trie.contains("sea")) cout << "trie contains sea" << endl; if (!trie.contains("shell")) cout << "trie doesn't contains shell" << endl; trie.remove("sea"); trie.remove("by"); trie.remove("sells"); trie.remove("she"); cout << "The size of the trie is: "; cout << trie.size() << endl; cout << trie.contains("shells") << endl; cout << trie.contains("she") << endl; trie.insert("she"); cout << trie.contains("she") << endl; trie.remove("sh"); trie.remove("hah"); cout << trie.size() << endl; }
[ "wooyichao@gmail.com" ]
wooyichao@gmail.com
a1e8d699d8307fbd8bd0a9f1793bc1ebdb029350
53e48e584604b34a4e346963c7eca73212f8dd90
/random/507E.cpp
d0d8bb84740924d87bec702ff5251145c74bf801
[]
no_license
mark-ruuan/Codeforces-Solution
c8d9536aafeaf5d90897befbdf5115a7566d7ac6
f5a6d36766925a98e56076ceebd6ff9723d9d23e
refs/heads/master
2020-04-20T22:45:52.402384
2019-07-24T05:52:39
2019-07-24T05:52:39
169,150,633
3
0
null
null
null
null
UTF-8
C++
false
false
1,113
cpp
/* * @Author: a_kk * @Date: 2019-02-07 19:08:48 */ #include <bits/stdc++.h> #define fast ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL) #define ll long long int using namespace std; const long double pi = 3.14159265358979323; const double EPS = 1e-12; const int N = 1e6 + 5; const int MOD = 1e9 + 7; ll a[N]; vector<ll> v; map<ll, ll> mp; ll ct(ll x){ if(x == 1) return 1; return 1 + ct(x / 2); } int main(){ fast; ll q; for(int i = 2; i < 20; i++){ ll no = (1LL << i) - 1, out = 0; for(int j = 1; j < no; j += 2){ ll t = __gcd((no ^ j), (no & j)); out = max(out, t); } //cout << no << " " << out << endl; mp[no] = out; } //cout << (1LL << 20) - 1 << "\n"; mp[16777215] = 5592405; mp[8388607] = 178481; mp[4194303] = 1398101; mp[2097151] = 299593; mp[1048575] = 349525; mp[33554431] = 1082401; cin >> q; while(q--){ ll x; cin >> x; ll bit = ct(x); bool flag = 0; ll ans = 0; for(int i = 0; i < bit; i++){ if(!(x & (1LL << i))) flag = 1; ans += (1LL << i); } if(flag == 1) cout << ans; else cout << mp[x]; cout << "\n"; } return 0; }
[ "arunkk3127@gmail.com" ]
arunkk3127@gmail.com
4a094484470f3a7e8d90fdb09fc3877164258970
6c77cf237697f252d48b287ae60ccf61b3220044
/aws-cpp-sdk-autoscaling/source/model/MetricDimension.cpp
a975284878ebe173fe40f3308d0978d366bc58af
[ "MIT", "Apache-2.0", "JSON" ]
permissive
Gohan/aws-sdk-cpp
9a9672de05a96b89d82180a217ccb280537b9e8e
51aa785289d9a76ac27f026d169ddf71ec2d0686
refs/heads/master
2020-03-26T18:48:43.043121
2018-11-09T08:44:41
2018-11-09T08:44:41
145,232,234
1
0
Apache-2.0
2018-08-30T13:42:27
2018-08-18T15:42:39
C++
UTF-8
C++
false
false
2,522
cpp
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/autoscaling/model/MetricDimension.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <utility> using namespace Aws::Utils::Xml; using namespace Aws::Utils; namespace Aws { namespace AutoScaling { namespace Model { MetricDimension::MetricDimension() : m_nameHasBeenSet(false), m_valueHasBeenSet(false) { } MetricDimension::MetricDimension(const XmlNode& xmlNode) : m_nameHasBeenSet(false), m_valueHasBeenSet(false) { *this = xmlNode; } MetricDimension& MetricDimension::operator =(const XmlNode& xmlNode) { XmlNode resultNode = xmlNode; if(!resultNode.IsNull()) { XmlNode nameNode = resultNode.FirstChild("Name"); if(!nameNode.IsNull()) { m_name = StringUtils::Trim(nameNode.GetText().c_str()); m_nameHasBeenSet = true; } XmlNode valueNode = resultNode.FirstChild("Value"); if(!valueNode.IsNull()) { m_value = StringUtils::Trim(valueNode.GetText().c_str()); m_valueHasBeenSet = true; } } return *this; } void MetricDimension::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const { if(m_nameHasBeenSet) { oStream << location << index << locationValue << ".Name=" << StringUtils::URLEncode(m_name.c_str()) << "&"; } if(m_valueHasBeenSet) { oStream << location << index << locationValue << ".Value=" << StringUtils::URLEncode(m_value.c_str()) << "&"; } } void MetricDimension::OutputToStream(Aws::OStream& oStream, const char* location) const { if(m_nameHasBeenSet) { oStream << location << ".Name=" << StringUtils::URLEncode(m_name.c_str()) << "&"; } if(m_valueHasBeenSet) { oStream << location << ".Value=" << StringUtils::URLEncode(m_value.c_str()) << "&"; } } } // namespace Model } // namespace AutoScaling } // namespace Aws
[ "henso@amazon.com" ]
henso@amazon.com
d56da6a1ec8cacdf578d84da681732165b6b8b76
1004986e800d2d8d00205f39a9452ef51b70487f
/Electrical/Dwij Sukeshkumar Sheth/Optimized_rack.ino
054a9107b2b34b223c3b64d4bc2c5b82d5d9fc96
[]
no_license
TECHNOCRATSROBOTICS/ROBOCON_2018
4f1786369d217dc4a07525f13b123e185d89c10f
fdf1049c0775835c05b4a3e22a9cae9280984c22
refs/heads/master
2021-01-22T08:27:56.640475
2018-02-23T08:31:17
2018-02-23T08:31:17
92,615,967
5
16
null
2018-02-23T08:31:18
2017-05-27T18:14:11
C++
UTF-8
C++
false
false
3,276
ino
byte motorPin1 = 8; // Blue - 28BYJ48 pin 1 byte motorPin2 = 9; // Pink - 28BYJ48 pin 2 byte motorPin3 = 10; // Yellow - 28BYJ48 pin 3 byte motorPin4 = 11; // Orange - 28BYJ48 pin 4 // Red - 28BYJ48 pin 5 (VCC) int a=12; int c=0; int flag=0; int f=1; #define sensor A3 int motorSpeed = 1200; //variable to set stepper speed int count = 0; // count of steps made int countsperrev =512; // number of steps per full revolution int lookup[8] = {B01000, B01100, B00100, B00110, B00010, B00011, B00001, B01001}; byte buttonPin=6; int buttonState; byte pwm1=7; byte dir1=A0; int button; void setOutput(int ); int pos=1; int step_count=0; //byte pwm2=6; //byte dir2=7; ////////////////////////////////////////////////////////////////////////////// void setup() { pinMode(motorPin1, OUTPUT); pinMode(motorPin2, OUTPUT); pinMode(motorPin3, OUTPUT); pinMode(motorPin4, OUTPUT); pinMode(sensor,INPUT); pinMode(pwm1,OUTPUT); pinMode(dir1,OUTPUT); analogWrite(pwm1,0); pinMode(buttonPin,INPUT); buttonState=0; Serial.begin(9600); } ////////////////////////////////////////////////////////////////////////////// void loop(){ button = digitalRead(buttonPin); Serial.println("Button:"); Serial.print(digitalRead(buttonPin)); float volts = analogRead(sensor)*0.0048828125; // value from sensor * (5/1024) int distance = 13*pow(volts, -1); // worked out from datasheet graph if(button==1) { forward(); } else if (button==0){ Serial.println("Button Hitted"); step_count=pos; pos=0; for( ; ; ){ if( count == 128 ){ break ; } clockwise(); count++ ; } backward(); while(pos!=step_count+1){ Serial.println("Loop Execution Started"); float volts = analogRead(sensor)*0.0048828125; // value from sensor * (5/1024) int distance = 13*pow(volts, -1); // worked out from datasheet graph Serial.println("Distance is:"); Serial.print(distance); while((distance>=4)&&(distance<10)){ Serial.println("Distance has Reduced now"); float volts = analogRead(sensor)*0.0048828125; // value from sensor * (5/1024) int distance = 13*pow(volts, -1); // worked out from datasheet graph flag=1; if(distance>10){ Serial.println("Hand Removed"); pos+=1; Serial.println("The position value now is:"); Serial.print(pos); break; } } Serial.println("Loop Executed"); delay(200); } for( ; ; ){ if( count == 256 ){ break ; } anticlockwise(); count++; //Serial.print("Count:"); //Serial.println(count); } count = 0 ; } } void anticlockwise() { for(int i = 0; i < 8; i++) { setOutput(i); delayMicroseconds(motorSpeed); } } void clockwise() { for(int i = 8; i > 0; i--) { setOutput(i); delayMicroseconds(motorSpeed); } } void backward() { digitalWrite(dir1,LOW); analogWrite(pwm1,200); } void forward() { digitalWrite(dir1,HIGH); analogWrite(pwm1,200); } void setOutput(int out) { digitalWrite(motorPin1, bitRead(lookup[out], 0)); digitalWrite(motorPin2, bitRead(lookup[out], 1)); digitalWrite(motorPin3, bitRead(lookup[out], 2)); digitalWrite(motorPin4, bitRead(lookup[out], 3)); }
[ "noreply@github.com" ]
noreply@github.com
b48550f83d906c08e386deb884cbba095dfb0365
94a1ae89fa4fac16b3d2a6c56ca678d6c8af668a
/modules/client/user/rooms.cc
f1406c617267114ab0c4d46725e9e5c537e9535b
[ "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
matrix-construct/construct
99d677d0c2254cac2176d80690bbfd02b18a8658
0624b69246878da592d3f5c2c3737ad0b5ff6277
refs/heads/master
2023-05-28T12:16:23.661446
2023-04-28T05:33:46
2023-05-01T19:45:37
147,328,703
356
41
NOASSERTION
2022-07-22T03:45:21
2018-09-04T10:26:23
C++
UTF-8
C++
false
false
6,253
cc
// Matrix Construct // // Copyright (C) Matrix Construct Developers, Authors & Contributors // Copyright (C) 2016-2018 Jason Volk <jason@zemos.net> // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice is present in all copies. The // full license for this software is available in the LICENSE file. #include "user.h" using namespace ircd; static m::resource::response put__tags(client &client, const m::resource::request &request, const m::user &user, const m::room &room_id); static m::resource::response get__tags(client &client, const m::resource::request &request, const m::user &user, const m::room &room); static m::resource::response delete__tags(client &client, const m::resource::request &request, const m::user &user, const m::room &room); static m::resource::response put__account_data(client &client, const m::resource::request &request, const m::user &user, const m::room &room_id); static m::resource::response get__account_data(client &client, const m::resource::request &request, const m::user &user, const m::room &room); m::resource::response put__rooms(client &client, const m::resource::request &request, const m::user::id &user_id) { if(request.parv.size() < 3) throw m::NEED_MORE_PARAMS { "room_id required" }; m::room::id::buf room_id { url::decode(room_id, request.parv[2]) }; if(request.parv.size() < 4) throw m::NEED_MORE_PARAMS { "rooms command required" }; const string_view &cmd { request.parv[3] }; if(cmd == "account_data") return put__account_data(client, request, user_id, room_id); if(cmd == "tags") return put__tags(client, request, user_id, room_id); throw m::NOT_FOUND { "/user/rooms/ command not found" }; } m::resource::response get__rooms(client &client, const m::resource::request &request, const m::user::id &user_id) { if(request.parv.size() < 3) throw m::NEED_MORE_PARAMS { "room_id required" }; m::room::id::buf room_id { url::decode(room_id, request.parv[2]) }; if(request.parv.size() < 4) throw m::NEED_MORE_PARAMS { "rooms command required" }; const string_view &cmd { request.parv[3] }; if(cmd == "account_data") return get__account_data(client, request, user_id, room_id); if(cmd == "tags") return get__tags(client, request, user_id, room_id); throw m::NOT_FOUND { "/user/rooms/ command not found" }; } m::resource::response delete__rooms(client &client, const m::resource::request &request, const m::user::id &user_id) { if(request.parv.size() < 3) throw m::NEED_MORE_PARAMS { "room_id required" }; m::room::id::buf room_id { url::decode(room_id, request.parv[2]) }; if(request.parv.size() < 4) throw m::NEED_MORE_PARAMS { "rooms command required" }; const string_view &cmd { request.parv[3] }; if(cmd == "tags") return delete__tags(client, request, user_id, room_id); throw m::NOT_FOUND { "/user/rooms/ command not found" }; } m::resource::response put__tags(client &client, const m::resource::request &request, const m::user &user, const m::room &room) { if(request.parv.size() < 5) throw m::NEED_MORE_PARAMS { "tag path parameter required" }; char tagbuf[m::event::TYPE_MAX_SIZE]; const auto &tag { url::decode(tagbuf, request.parv[4]) }; const json::object &value { request }; const m::user::room_tags room_tags { user, room }; room_tags.set(tag, value); return m::resource::response { client, http::OK }; } m::resource::response get__tags(client &client, const m::resource::request &request, const m::user &user, const m::room &room) { const m::user::room_tags room_tags { user, room }; m::resource::response::chunked response { client, http::OK }; json::stack out { response.buf, response.flusher() }; json::stack::object top{out}; json::stack::object tags { top, "tags" }; room_tags.for_each([&tags] (const string_view &type, const json::object &content) { json::stack::member { tags, type, content }; return true; }); return response; } m::resource::response delete__tags(client &client, const m::resource::request &request, const m::user &user, const m::room &room) { if(request.parv.size() < 5) throw m::NEED_MORE_PARAMS { "tag path parameter required" }; char tagbuf[m::event::TYPE_MAX_SIZE]; const auto &tag { url::decode(tagbuf, request.parv[4]) }; const m::user::room_tags room_tags { user, room }; const bool deleted { room_tags.del(tag) }; return m::resource::response { client, http::OK }; } m::resource::response put__account_data(client &client, const m::resource::request &request, const m::user &user, const m::room &room) { if(request.parv.size() < 5) throw m::NEED_MORE_PARAMS { "type path parameter required" }; char typebuf[m::event::TYPE_MAX_SIZE]; const auto &type { url::decode(typebuf, request.parv[4]) }; const json::object &value { request }; const auto event_id { m::user::room_account_data{user, room}.set(type, value) }; return m::resource::response { client, http::OK }; } m::resource::response get__account_data(client &client, const m::resource::request &request, const m::user &user, const m::room &room) { if(request.parv.size() < 5) throw m::NEED_MORE_PARAMS { "type path parameter required" }; char typebuf[m::event::TYPE_MAX_SIZE]; const auto &type { url::decode(typebuf, request.parv[4]) }; m::user::room_account_data{user, room}.get(type, [&client] (const string_view &type, const json::object &value) { m::resource::response { client, value }; }); return {}; // responded from closure }
[ "jason@zemos.net" ]
jason@zemos.net
feb56438f053d018d0afb69fc61491cf7f954f0c
926b3c52070f6e309567c8598248fd5c57095be9
/src/mmdeploy/csrc/mmdeploy/core/operator.h
39c810da54cc50c1192ad64bd97dd521fd39515e
[ "Apache-2.0" ]
permissive
fengbingchun/PyTorch_Test
410f7cd2303707b0141d433fb9d144a961e1f4c8
df5c2169f0b699bcd6e74adb4cb0e57f7dcd9348
refs/heads/master
2023-05-23T16:42:29.711338
2023-03-25T11:31:43
2023-03-25T11:31:43
167,339,907
15
4
null
2023-03-25T11:31:45
2019-01-24T09:24:59
C++
UTF-8
C++
false
false
3,903
h
// Copyright (c) OpenMMLab. All rights reserved. #ifndef MMDEPLOY_SRC_EXPERIMENTAL_PIPELINE_OPERATOR_H_ #define MMDEPLOY_SRC_EXPERIMENTAL_PIPELINE_OPERATOR_H_ #include "mmdeploy/core/value.h" namespace mmdeploy::graph { using std::string; using std::tuple; using std::vector; MMDEPLOY_API Result<void> Gather(const Value::Array& array, const vector<int>& idxs, Value::Array& output); MMDEPLOY_API Result<void> Gather(Value::Array&& array, const vector<int>& idxs, Value::Array& output); MMDEPLOY_API Result<void> Gather(const Value::Object& object, const vector<std::string>& keys, Value::Array& output); MMDEPLOY_API Result<void> Gather(Value::Object&& object, const vector<std::string>& keys, Value::Array& output); MMDEPLOY_API Result<void> Scatter(Value::Array array, const vector<int>& idxs, Value::Array& output); MMDEPLOY_API Result<void> Scatter(Value::Array array, const vector<std::string>& keys, Value::Object& output); inline Result<Value::Array> Gather(const Value::Array& array, const vector<int>& idxs) { Value::Array output; OUTCOME_TRY(Gather(array, idxs, output)); return output; } inline Result<Value::Array> Gather(Value::Array&& array, const vector<int>& idxs) { Value::Array output; OUTCOME_TRY(Gather(std::move(array), idxs, output)); return output; } inline Result<Value::Array> Gather(const Value::Object& object, const vector<std::string>& keys) { Value::Array output; OUTCOME_TRY(Gather(object, keys, output)); return output; } inline Result<Value::Array> Gather(Value::Object&& object, const vector<std::string>& keys) { Value::Array output; OUTCOME_TRY(Gather(std::move(object), keys, output)); return output; } inline Result<Value::Array> Scatter(Value::Array array, const vector<int>& idxs) { Value::Array output(idxs.size(), Value::kNull); OUTCOME_TRY(Scatter(std::move(array), idxs, output)); return output; } inline Result<Value::Object> Scatter(Value::Array array, const vector<std::string>& keys) { Value::Object output; OUTCOME_TRY(Scatter(std::move(array), keys, output)); return output; } template <class V, std::enable_if_t<is_value_v<std::decay_t<V> >, bool> = true> Result<tuple<Value, vector<int> > > Flatten(V&& input) { if (!input.is_array()) { return Status(eInvalidArgument); } Value output = ValueType::kArray; std::vector<int> idxs; for (int i = 0; i < input.size(); ++i) { auto inner = std::forward<V>(input)[i]; if (!inner.is_array()) { return Status(eInvalidArgument); } for (auto& item : inner) { output.push_back(std::move(item)); idxs.push_back(i); } } idxs.push_back(static_cast<int>(input.size())); return {output, idxs}; } template <class V, std::enable_if_t<is_value_v<std::decay_t<V> >, bool> = true> Result<Value> Unflatten(V&& input, const vector<int>& idxs) { if (!input.is_array()) { return Status(eInvalidArgument); } Value output = ValueType::kArray; for (int i = 0; i < idxs.back(); ++i) { output.push_back(ValueType::kArray); } for (int i = 0; i < input.size(); ++i) { if (idxs[i] >= output.size()) { return Status(eInvalidArgument); } output[idxs[i]].push_back(std::forward<V>(input)[i]); } return output; } // object of arrays -> array of objects, all arrays must be of same length MMDEPLOY_API Result<Value> DistribOA(const Value& oa); // array of objects -> object of arrays, all objects must be isomorphic MMDEPLOY_API Result<Value> DistribAO(const Value& ao); // array of arrays -> array of arrays, this is equivalent to transpose MMDEPLOY_API Result<Value> DistribAA(const Value& a); } // namespace mmdeploy::graph #endif // MMDEPLOY_SRC_EXPERIMENTAL_PIPELINE_OPERATOR_H_
[ "fengbingchun@163.com" ]
fengbingchun@163.com
5b81576473bc4ad6b229fcc546139e33284dcce8
caefb5d41299691a7ee2c68b654e1d7e5b392718
/source/d3d9/d3d9_swapchain.cpp
64e0c91aad5b4db736ae383966dc7e83d69b3296
[ "BSD-3-Clause" ]
permissive
rovacado/Reshade-PSO2-Unlocked
5e2544f4440117823bef8d62c28810e7340a09ea
07ec4876fc1f9515a02ccd8484ef73434ea36def
refs/heads/main
2023-05-11T04:55:42.378489
2021-06-01T00:32:54
2021-06-01T00:32:54
372,659,527
0
0
null
null
null
null
UTF-8
C++
false
false
5,480
cpp
/* * Copyright (C) 2014 Patrick Mours. All rights reserved. * License: https://github.com/crosire/reshade#license */ #include "dll_log.hpp" #include "d3d9_device.hpp" #include "d3d9_swapchain.hpp" #include "runtime_d3d9.hpp" Direct3DSwapChain9::Direct3DSwapChain9(Direct3DDevice9 *device, IDirect3DSwapChain9 *original, const std::shared_ptr<reshade::d3d9::runtime_d3d9> &runtime) : _orig(original), _extended_interface(0), _device(device), _runtime(runtime) { assert(_orig != nullptr && _device != nullptr && _runtime != nullptr); } Direct3DSwapChain9::Direct3DSwapChain9(Direct3DDevice9 *device, IDirect3DSwapChain9Ex *original, const std::shared_ptr<reshade::d3d9::runtime_d3d9> &runtime) : _orig(original), _extended_interface(1), _device(device), _runtime(runtime) { assert(_orig != nullptr && _device != nullptr && _runtime != nullptr); } bool Direct3DSwapChain9::is_presenting_entire_surface(const RECT *source_rect, HWND hwnd) { if (source_rect == nullptr) return true; if (hwnd != nullptr) { RECT window_rect = {}; GetClientRect(hwnd, &window_rect); if (source_rect->left == window_rect.left && source_rect->top == window_rect.top && source_rect->right == window_rect.right && source_rect->bottom == window_rect.bottom) return true; } return false; } bool Direct3DSwapChain9::check_and_upgrade_interface(REFIID riid) { if (riid == __uuidof(this) || riid == __uuidof(IUnknown) || riid == __uuidof(IDirect3DSwapChain9)) return true; if (riid != __uuidof(IDirect3DSwapChain9Ex)) return false; if (!_extended_interface) { IDirect3DSwapChain9Ex *new_interface = nullptr; if (FAILED(_orig->QueryInterface(IID_PPV_ARGS(&new_interface)))) return false; #if RESHADE_VERBOSE_LOG LOG(DEBUG) << "Upgraded IDirect3DSwapChain9 object " << this << " to IDirect3DSwapChain9Ex."; #endif _orig->Release(); _orig = new_interface; _extended_interface = true; } return true; } HRESULT STDMETHODCALLTYPE Direct3DSwapChain9::QueryInterface(REFIID riid, void **ppvObj) { if (ppvObj == nullptr) return E_POINTER; if (check_and_upgrade_interface(riid)) { AddRef(); *ppvObj = this; return S_OK; } return _orig->QueryInterface(riid, ppvObj); } ULONG STDMETHODCALLTYPE Direct3DSwapChain9::AddRef() { _orig->AddRef(); return InterlockedIncrement(&_ref); } ULONG STDMETHODCALLTYPE Direct3DSwapChain9::Release() { const ULONG ref = InterlockedDecrement(&_ref); if (ref != 0) return _orig->Release(), ref; _runtime->on_reset(); _runtime.reset(); const auto it = std::find(_device->_additional_swapchains.begin(), _device->_additional_swapchains.end(), this); if (it != _device->_additional_swapchains.end()) { _device->_additional_swapchains.erase(it); _device->Release(); // Remove the reference that was added in 'Direct3DDevice9::CreateAdditionalSwapChain' } const ULONG ref_orig = _orig->Release(); if (ref_orig != 0) // Verify internal reference count LOG(WARN) << "Reference count for IDirect3DSwapChain9" << (_extended_interface ? "Ex" : "") << " object " << this << " is inconsistent."; #if RESHADE_VERBOSE_LOG LOG(DEBUG) << "Destroyed IDirect3DSwapChain9" << (_extended_interface ? "Ex" : "") << " object " << this << '.'; #endif delete this; return 0; } HRESULT STDMETHODCALLTYPE Direct3DSwapChain9::Present(const RECT *pSourceRect, const RECT *pDestRect, HWND hDestWindowOverride, const RGNDATA *pDirtyRegion, DWORD dwFlags) { // Only call into runtime if the entire surface is presented, to avoid partial updates messing up effects and the GUI if (is_presenting_entire_surface(pSourceRect, hDestWindowOverride)) _runtime->on_present(); _device->_state.reset(false); return _orig->Present(pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion, dwFlags); } HRESULT STDMETHODCALLTYPE Direct3DSwapChain9::GetFrontBufferData(IDirect3DSurface9 *pDestSurface) { return _orig->GetFrontBufferData(pDestSurface); } HRESULT STDMETHODCALLTYPE Direct3DSwapChain9::GetBackBuffer(UINT iBackBuffer, D3DBACKBUFFER_TYPE Type, IDirect3DSurface9 **ppBackBuffer) { return _orig->GetBackBuffer(iBackBuffer, Type, ppBackBuffer); } HRESULT STDMETHODCALLTYPE Direct3DSwapChain9::GetRasterStatus(D3DRASTER_STATUS *pRasterStatus) { return _orig->GetRasterStatus(pRasterStatus); } HRESULT STDMETHODCALLTYPE Direct3DSwapChain9::GetDisplayMode(D3DDISPLAYMODE *pMode) { return _orig->GetDisplayMode(pMode); } HRESULT STDMETHODCALLTYPE Direct3DSwapChain9::GetDevice(IDirect3DDevice9 **ppDevice) { if (ppDevice == nullptr) return D3DERR_INVALIDCALL; _device->AddRef(); *ppDevice = _device; return D3D_OK; } HRESULT STDMETHODCALLTYPE Direct3DSwapChain9::GetPresentParameters(D3DPRESENT_PARAMETERS *pPresentationParameters) { return _orig->GetPresentParameters(pPresentationParameters); } HRESULT STDMETHODCALLTYPE Direct3DSwapChain9::GetLastPresentCount(UINT *pLastPresentCount) { assert(_extended_interface); return static_cast<IDirect3DSwapChain9Ex *>(_orig)->GetLastPresentCount(pLastPresentCount); } HRESULT STDMETHODCALLTYPE Direct3DSwapChain9::GetPresentStats(D3DPRESENTSTATS *pPresentationStatistics) { assert(_extended_interface); return static_cast<IDirect3DSwapChain9Ex *>(_orig)->GetPresentStats(pPresentationStatistics); } HRESULT STDMETHODCALLTYPE Direct3DSwapChain9::GetDisplayModeEx(D3DDISPLAYMODEEX *pMode, D3DDISPLAYROTATION *pRotation) { assert(_extended_interface); return static_cast<IDirect3DSwapChain9Ex *>(_orig)->GetDisplayModeEx(pMode, pRotation); }
[ "noreply@github.com" ]
noreply@github.com
3faf2f6b6ad7427b43547f1c2798951e6f272f3c
e4cae7ffe09b19b3328826cc201e952179be3b94
/camera.cpp
3c2a9ba1a0a64e76f2989649ee764d83c7f52241
[]
no_license
solderspot/PiCamCVTest
333a8193d8c95f02a671e9c6923d7ae7c31bfa4d
be55ea6acd67a1d0962a0ae46fac10f8518d92c9
refs/heads/master
2016-08-07T21:06:06.151314
2016-02-08T11:14:45
2016-02-08T11:14:45
25,671,399
3
0
null
null
null
null
UTF-8
C++
false
false
19,709
cpp
/* Chris Cummings This is wraps up the camera system in a simple StartCamera, StopCamera and ReadFrame api to read data from the feed. Based on parts of raspivid, and the work done by Pierre Raus at http://raufast.org/download/camcv_vid0.c to get the camera feeding into opencv. It */ #include "camera.h" #include <stdio.h> // Standard port setting for the camera component #define MMAL_CAMERA_PREVIEW_PORT 0 #define MMAL_CAMERA_VIDEO_PORT 1 #define MMAL_CAMERA_CAPTURE_PORT 2 static CCamera* GCamera = NULL; CCamera* StartCamera(int width, int height, int framerate, int num_levels, bool do_argb_conversion, int awbmode, int flipv, int fliph) { //can't create more than one camera if(GCamera != NULL) { printf("Can't create more than one camera\n"); return NULL; } //create and attempt to initialize the camera GCamera = new CCamera(); if(!GCamera->Init(width,height,framerate,num_levels,do_argb_conversion, awbmode, flipv, fliph)) { //failed so clean up printf("Camera init failed\n"); delete GCamera; GCamera = NULL; } return GCamera; } void StopCamera() { if(GCamera) { GCamera->Release(); delete GCamera; GCamera = NULL; } } CCamera::CCamera() { CameraComponent = NULL; SplitterComponent = NULL; VidToSplitConn = NULL; memset(Outputs,0,sizeof(Outputs)); } CCamera::~CCamera() { } void CCamera::CameraControlCallback(MMAL_PORT_T *port, MMAL_BUFFER_HEADER_T *buffer) { GCamera->OnCameraControlCallback(port,buffer); } MMAL_COMPONENT_T* CCamera::CreateCameraComponentAndSetupPorts() { MMAL_COMPONENT_T *camera = 0; MMAL_ES_FORMAT_T *format; MMAL_PORT_T *preview_port = NULL, *video_port = NULL, *still_port = NULL; MMAL_STATUS_T status; //create the camera component status = mmal_component_create(MMAL_COMPONENT_DEFAULT_CAMERA, &camera); if (status != MMAL_SUCCESS) { printf("Failed to create camera component\n"); return NULL; } //check we have output ports if (!camera->output_num) { printf("Camera doesn't have output ports"); mmal_component_destroy(camera); return NULL; } //get the 3 ports preview_port = camera->output[MMAL_CAMERA_PREVIEW_PORT]; video_port = camera->output[MMAL_CAMERA_VIDEO_PORT]; still_port = camera->output[MMAL_CAMERA_CAPTURE_PORT]; // Enable the camera, and tell it its control callback function status = mmal_port_enable(camera->control, CameraControlCallback); if (status != MMAL_SUCCESS) { printf("Unable to enable control port : error %d", status); mmal_component_destroy(camera); return NULL; } // set up the camera configuration { MMAL_PARAMETER_CAMERA_CONFIG_T cam_config; cam_config.hdr.id = MMAL_PARAMETER_CAMERA_CONFIG; cam_config.hdr.size = sizeof(cam_config); cam_config.max_stills_w = Width; cam_config.max_stills_h = Height; cam_config.stills_yuv422 = 0; cam_config.one_shot_stills = 0; cam_config.max_preview_video_w = Width; cam_config.max_preview_video_h = Height; cam_config.num_preview_video_frames = 3; cam_config.stills_capture_circular_buffer_height = 0; cam_config.fast_preview_resume = 0; cam_config.use_stc_timestamp = MMAL_PARAM_TIMESTAMP_MODE_RESET_STC; mmal_port_parameter_set(camera->control, &cam_config.hdr); } // setup preview port format - QUESTION: Needed if we aren't using preview? format = preview_port->format; format->encoding = MMAL_ENCODING_OPAQUE; format->encoding_variant = MMAL_ENCODING_I420; format->es->video.width = Width; format->es->video.height = Height; format->es->video.crop.x = 0; format->es->video.crop.y = 0; format->es->video.crop.width = Width; format->es->video.crop.height = Height; format->es->video.frame_rate.num = FrameRate; format->es->video.frame_rate.den = 1; status = mmal_port_format_commit(preview_port); if (status != MMAL_SUCCESS) { printf("Couldn't set preview port format : error %d", status); mmal_component_destroy(camera); return NULL; } //setup video port format format = video_port->format; format->encoding = MMAL_ENCODING_I420; format->encoding_variant = MMAL_ENCODING_I420; format->es->video.width = Width; format->es->video.height = Height; format->es->video.crop.x = 0; format->es->video.crop.y = 0; format->es->video.crop.width = Width; format->es->video.crop.height = Height; format->es->video.frame_rate.num = FrameRate; format->es->video.frame_rate.den = 1; status = mmal_port_format_commit(video_port); if (status != MMAL_SUCCESS) { printf("Couldn't set video port format : error %d", status); mmal_component_destroy(camera); return NULL; } //setup still port format format = still_port->format; format->encoding = MMAL_ENCODING_OPAQUE; format->encoding_variant = MMAL_ENCODING_I420; format->es->video.width = Width; format->es->video.height = Height; format->es->video.crop.x = 0; format->es->video.crop.y = 0; format->es->video.crop.width = Width; format->es->video.crop.height = Height; format->es->video.frame_rate.num = 1; format->es->video.frame_rate.den = 1; status = mmal_port_format_commit(still_port); if (status != MMAL_SUCCESS) { printf("Couldn't set still port format : error %d", status); mmal_component_destroy(camera); return NULL; } //apply all camera parameters raspicamcontrol_set_all_parameters(camera, &CameraParameters); //enable the camera status = mmal_component_enable(camera); if (status != MMAL_SUCCESS) { printf("Couldn't enable camera\n"); mmal_component_destroy(camera); return NULL; } return camera; } MMAL_COMPONENT_T* CCamera::CreateSplitterComponentAndSetupPorts(MMAL_PORT_T* video_output_port) { MMAL_COMPONENT_T *splitter = 0; MMAL_ES_FORMAT_T *format; MMAL_PORT_T *input_port = NULL, *output_port = NULL; MMAL_STATUS_T status; //create the camera component status = mmal_component_create(MMAL_COMPONENT_DEFAULT_VIDEO_SPLITTER, &splitter); if (status != MMAL_SUCCESS) { printf("Failed to create splitter component\n"); goto error; } //check we have output ports if (splitter->output_num != 4 || splitter->input_num != 1) { printf("Splitter doesn't have correct ports: %d, %d\n",splitter->input_num,splitter->output_num); goto error; } //get the ports input_port = splitter->input[0]; mmal_format_copy(input_port->format,video_output_port->format); input_port->buffer_num = 3; status = mmal_port_format_commit(input_port); if (status != MMAL_SUCCESS) { printf("Couldn't set resizer input port format : error %d", status); goto error; } for(int i = 0; i < splitter->output_num; i++) { output_port = splitter->output[i]; output_port->buffer_num = 3; mmal_format_copy(output_port->format,input_port->format); status = mmal_port_format_commit(output_port); if (status != MMAL_SUCCESS) { printf("Couldn't set resizer output port format : error %d", status); goto error; } } return splitter; error: if(splitter) mmal_component_destroy(splitter); return NULL; } bool CCamera::Init(int width, int height, int framerate, int num_levels, bool do_argb_conversion, int awbmode, int flipv, int fliph) { //init broadcom host - QUESTION: can this be called more than once?? bcm_host_init(); //store basic parameters Width = width; Height = height; FrameRate = framerate; // Set up the camera_parameters to default raspicamcontrol_set_defaults(&CameraParameters); CameraParameters.awbMode = MMAL_PARAM_AWBMODE_T(awbmode); CameraParameters.hflip = fliph; CameraParameters.vflip = flipv; MMAL_COMPONENT_T *camera = 0; MMAL_COMPONENT_T *splitter = 0; MMAL_CONNECTION_T* vid_to_split_connection = 0; MMAL_PORT_T *video_port = NULL; MMAL_STATUS_T status; CCameraOutput* outputs[4]; memset(outputs,0,sizeof(outputs)); //create the camera component camera = CreateCameraComponentAndSetupPorts(); if (!camera) goto error; //get the video port video_port = camera->output[MMAL_CAMERA_VIDEO_PORT]; video_port->buffer_num = 3; //create the splitter component splitter = CreateSplitterComponentAndSetupPorts(video_port); if(!splitter) goto error; //create and enable a connection between the video output and the resizer input status = mmal_connection_create(&vid_to_split_connection, video_port, splitter->input[0], MMAL_CONNECTION_FLAG_TUNNELLING | MMAL_CONNECTION_FLAG_ALLOCATION_ON_INPUT); if (status != MMAL_SUCCESS) { printf("Failed to create connection\n"); goto error; } status = mmal_connection_enable(vid_to_split_connection); if (status != MMAL_SUCCESS) { printf("Failed to enable connection\n"); goto error; } //setup all the outputs for(int i = 0; i < num_levels; i++) { outputs[i] = new CCameraOutput(); if(!outputs[i]->Init(Width >> i,Height >> i,splitter,i, do_argb_conversion )) { printf("Failed to initialize output %d\n",i); goto error; } } //begin capture if (mmal_port_parameter_set_boolean(video_port, MMAL_PARAMETER_CAPTURE, 1) != MMAL_SUCCESS) { printf("Failed to start capture\n"); goto error; } //store created info CameraComponent = camera; SplitterComponent = splitter; VidToSplitConn = vid_to_split_connection; memcpy(Outputs,outputs,sizeof(outputs)); //return success printf("Camera successfully created\n"); return true; error: if(vid_to_split_connection) mmal_connection_destroy(vid_to_split_connection); if(camera) mmal_component_destroy(camera); if(splitter) mmal_component_destroy(splitter); for(int i = 0; i < 4; i++) { if(outputs[i]) { outputs[i]->Release(); delete outputs[i]; } } return false; } void CCamera::Release() { for(int i = 0; i < 4; i++) { if(Outputs[i]) { Outputs[i]->Release(); delete Outputs[i]; Outputs[i] = NULL; } } if(VidToSplitConn) mmal_connection_destroy(VidToSplitConn); if(CameraComponent) mmal_component_destroy(CameraComponent); if(SplitterComponent) mmal_component_destroy(SplitterComponent); VidToSplitConn = NULL; CameraComponent = NULL; SplitterComponent = NULL; } void CCamera::OnCameraControlCallback(MMAL_PORT_T *port, MMAL_BUFFER_HEADER_T *buffer) { printf("Camera control callback\n"); } bool CCamera::BeginReadFrame(int level, const void* &out_buffer, int& out_buffer_size) { return Outputs[level] ? Outputs[level]->BeginReadFrame(out_buffer,out_buffer_size) : false; } void CCamera::EndReadFrame(int level) { if(Outputs[level]) Outputs[level]->EndReadFrame(); } int CCamera::ReadFrame(int level, void* dest, int dest_size) { return Outputs[level] ? Outputs[level]->ReadFrame(dest,dest_size) : -1; } CCameraOutput::CCameraOutput() { memset(this,0,sizeof(CCameraOutput)); } CCameraOutput::~CCameraOutput() { } bool CCameraOutput::Init(int width, int height, MMAL_COMPONENT_T* input_component, int input_port_idx, bool do_argb_conversion) { printf("Init camera output with %d/%d\n",width,height); Width = width; Height = height; MMAL_COMPONENT_T *resizer = 0; MMAL_CONNECTION_T* connection = 0; MMAL_STATUS_T status; MMAL_POOL_T* video_buffer_pool = 0; MMAL_QUEUE_T* output_queue = 0; //got the port we're receiving from MMAL_PORT_T* input_port = input_component->output[input_port_idx]; //check if user wants conversion to argb or the width or height is different to the input if(do_argb_conversion || width != input_port->format->es->video.width || height != input_port->format->es->video.height) { //create the resizing component, reading from the splitter output resizer = CreateResizeComponentAndSetupPorts(input_port,do_argb_conversion); if(!resizer) goto error; //create and enable a connection between the video output and the resizer input status = mmal_connection_create(&connection, input_port, resizer->input[0], MMAL_CONNECTION_FLAG_TUNNELLING | MMAL_CONNECTION_FLAG_ALLOCATION_ON_INPUT); if (status != MMAL_SUCCESS) { printf("Failed to create connection\n"); goto error; } status = mmal_connection_enable(connection); if (status != MMAL_SUCCESS) { printf("Failed to enable connection\n"); goto error; } //set the buffer pool port to be the resizer output BufferPort = resizer->output[0]; } else { //no convert/resize needed so just set the buffer pool port to be the input port BufferPort = input_port; } //setup the video buffer callback video_buffer_pool = EnablePortCallbackAndCreateBufferPool(BufferPort,VideoBufferCallback,3); if(!video_buffer_pool) goto error; //create the output queue output_queue = mmal_queue_create(); if(!output_queue) { printf("Failed to create output queue\n"); goto error; } ResizerComponent = resizer; BufferPool = video_buffer_pool; OutputQueue = output_queue; Connection = connection; return true; error: if(output_queue) mmal_queue_destroy(output_queue); if(video_buffer_pool) mmal_port_pool_destroy(resizer->output[0],video_buffer_pool); if(connection) mmal_connection_destroy(connection); if(resizer) mmal_component_destroy(resizer); return false; } void CCameraOutput::Release() { if(OutputQueue) mmal_queue_destroy(OutputQueue); if(BufferPool) mmal_port_pool_destroy(BufferPort,BufferPool); if(Connection) mmal_connection_destroy(Connection); if(ResizerComponent) mmal_component_destroy(ResizerComponent); memset(this,0,sizeof(CCameraOutput)); } void CCameraOutput::OnVideoBufferCallback(MMAL_PORT_T *port, MMAL_BUFFER_HEADER_T *buffer) { //to handle the user not reading frames, remove and return any pre-existing ones if(mmal_queue_length(OutputQueue)>=2) { if(MMAL_BUFFER_HEADER_T* existing_buffer = mmal_queue_get(OutputQueue)) { mmal_buffer_header_release(existing_buffer); if (port->is_enabled) { MMAL_STATUS_T status; MMAL_BUFFER_HEADER_T *new_buffer; new_buffer = mmal_queue_get(BufferPool->queue); if (new_buffer) status = mmal_port_send_buffer(port, new_buffer); if (!new_buffer || status != MMAL_SUCCESS) printf("Unable to return a buffer to the video port\n"); } } } //add the buffer to the output queue mmal_queue_put(OutputQueue,buffer); //printf("Video buffer callback, output queue len=%d\n", mmal_queue_length(OutputQueue)); } void CCameraOutput::VideoBufferCallback(MMAL_PORT_T *port, MMAL_BUFFER_HEADER_T *buffer) { ((CCameraOutput*)port->userdata)->OnVideoBufferCallback(port,buffer); } int CCameraOutput::ReadFrame(void* dest, int dest_size) { //default result is 0 - no data available int res = 0; //get buffer const void* buffer; int buffer_len; if(BeginReadFrame(buffer,buffer_len)) { if(dest_size >= buffer_len) { //got space - copy it in and return size memcpy(dest,buffer,buffer_len); res = buffer_len; } else { //not enough space - return failure res = -1; } EndReadFrame(); } return res; } bool CCameraOutput::BeginReadFrame(const void* &out_buffer, int& out_buffer_size) { //printf("Attempting to read camera output\n"); //try and get buffer if(MMAL_BUFFER_HEADER_T *buffer = mmal_queue_get(OutputQueue)) { //printf("Reading buffer of %d bytes from output\n",buffer->length); //lock it mmal_buffer_header_mem_lock(buffer); //store it LockedBuffer = buffer; //fill out the output variables and return success out_buffer = buffer->data; out_buffer_size = buffer->length; return true; } //no buffer - return false return false; } void CCameraOutput::EndReadFrame() { if(LockedBuffer) { // unlock and then release buffer back to the pool from whence it came mmal_buffer_header_mem_unlock(LockedBuffer); mmal_buffer_header_release(LockedBuffer); LockedBuffer = NULL; // and send it back to the port (if still open) if (BufferPort->is_enabled) { MMAL_STATUS_T status; MMAL_BUFFER_HEADER_T *new_buffer; new_buffer = mmal_queue_get(BufferPool->queue); if (new_buffer) status = mmal_port_send_buffer(BufferPort, new_buffer); if (!new_buffer || status != MMAL_SUCCESS) printf("Unable to return a buffer to the video port\n"); } } } MMAL_COMPONENT_T* CCameraOutput::CreateResizeComponentAndSetupPorts(MMAL_PORT_T* video_output_port, bool do_argb_conversion) { MMAL_COMPONENT_T *resizer = 0; MMAL_ES_FORMAT_T *format; MMAL_PORT_T *input_port = NULL, *output_port = NULL; MMAL_STATUS_T status; //create the camera component status = mmal_component_create("vc.ril.resize", &resizer); if (status != MMAL_SUCCESS) { printf("Failed to create reszie component\n"); goto error; } //check we have output ports if (resizer->output_num != 1 || resizer->input_num != 1) { printf("Resizer doesn't have correct ports"); goto error; } //get the ports input_port = resizer->input[0]; output_port = resizer->output[0]; mmal_format_copy(input_port->format,video_output_port->format); input_port->buffer_num = 3; status = mmal_port_format_commit(input_port); if (status != MMAL_SUCCESS) { printf("Couldn't set resizer input port format : error %d", status); goto error; } mmal_format_copy(output_port->format,input_port->format); if(do_argb_conversion) { output_port->format->encoding = MMAL_ENCODING_RGBA; output_port->format->encoding_variant = MMAL_ENCODING_RGBA; } output_port->format->es->video.width = Width; output_port->format->es->video.height = Height; output_port->format->es->video.crop.x = 0; output_port->format->es->video.crop.y = 0; output_port->format->es->video.crop.width = Width; output_port->format->es->video.crop.height = Height; status = mmal_port_format_commit(output_port); if (status != MMAL_SUCCESS) { printf("Couldn't set resizer output port format : error %d", status); goto error; } return resizer; error: if(resizer) mmal_component_destroy(resizer); return NULL; } MMAL_POOL_T* CCameraOutput::EnablePortCallbackAndCreateBufferPool(MMAL_PORT_T* port, MMAL_PORT_BH_CB_T cb, int buffer_count) { MMAL_STATUS_T status; MMAL_POOL_T* buffer_pool = 0; //setup video port buffer and a pool to hold them port->buffer_num = buffer_count; port->buffer_size = port->buffer_size_recommended; printf("Creating pool with %d buffers of size %d\n", port->buffer_num, port->buffer_size); buffer_pool = mmal_port_pool_create(port, port->buffer_num, port->buffer_size); if (!buffer_pool) { printf("Couldn't create video buffer pool\n"); goto error; } //enable the port and hand it the callback port->userdata = (struct MMAL_PORT_USERDATA_T *)this; status = mmal_port_enable(port, cb); if (status != MMAL_SUCCESS) { printf("Failed to set video buffer callback\n"); goto error; } //send all the buffers in our pool to the video port ready for use { int num = mmal_queue_length(buffer_pool->queue); int q; for (q=0;q<num;q++) { MMAL_BUFFER_HEADER_T *buffer = mmal_queue_get(buffer_pool->queue); if (!buffer) { printf("Unable to get a required buffer %d from pool queue\n", q); goto error; } else if (mmal_port_send_buffer(port, buffer)!= MMAL_SUCCESS) { printf("Unable to send a buffer to port (%d)\n", q); goto error; } } } return buffer_pool; error: if(buffer_pool) mmal_port_pool_destroy(port,buffer_pool); return NULL; }
[ "solderspot@gmail.com" ]
solderspot@gmail.com
6b7c912b08e8439687eec86b45fb12ec9f5976fd
5181d788d3261b2183e1f9a6b043b9b4f2cd9452
/src/cpp/NewtonOMP.cpp
73f7a2eae572ad94f5eddad5229c8632fa649968
[]
no_license
mse-gpu/Newton
1c19104b79a52303ea14c358604b6e5657707d90
710dde71dc91434d9526364f66af309504a20310
refs/heads/master
2021-01-01T19:24:42.767801
2012-05-19T12:12:31
2012-05-19T12:12:31
3,594,619
0
0
null
null
null
null
UTF-8
C++
false
false
1,042
cpp
#include <iostream> #include <cmath> #include "omp.h" #include "NewtonOMP.hpp" //TODO That's ugly... namespace newton_omp { #include "Newton.hpp" } NewtonImageOMP::NewtonImageOMP(int m, int n, DomaineMaths domain) : FractaleImage(m,n,domain) { refreshAll(domain); } void NewtonImageOMP::refreshAll(const DomaineMaths& domainNew){ int w = getW(); int h = getH(); float dx = (float) (domainNew.dx / (float) w); float dy = (float) (domainNew.dy / (float) h); #pragma omp parallel { int tid = omp_get_thread_num(); int i = tid + 1; float y = domainNew.y0 + tid * dy; while(i <= h){ float x = domainNew.x0; for(int j = 1; j <= w; ++j){ int color = newton_omp::real_newton(x, y); if(color == 0){ setFloatRGBA(i, j, 0, 0, 0); } else if(color == 1){ setFloatRGBA(i, j, 1, 0, 0); } else if(color == 2){ setFloatRGBA(i, j, 0, 1, 0); } else if(color == 3){ setFloatRGBA(i, j, 0, 0, 1); } x += dx; } y += THREADS * dy; i += THREADS; } } }
[ "baptiste.wicht@gmail.com" ]
baptiste.wicht@gmail.com
a1f2f25f43edad6b8e37b34088225fd41ccfc8a1
f7d99ed9a236a1b86ef48fb3ca2f37f4e29885ae
/Untitled2.cpp
f13b7ed3bb8cc6f3842f1dbafcbcf642f4714ad7
[]
no_license
Thawatchai-Yango/OOP_with_CPP
cafcc94d0935fc81e4cf1b2736eb8fce69eff50f
05e281aad195a8c5ea2cdc45861e5a85e102c771
refs/heads/main
2023-08-02T13:48:33.972949
2021-09-19T12:46:02
2021-09-19T12:46:02
408,124,843
0
0
null
null
null
null
UTF-8
C++
false
false
1,690
cpp
/* * OBJECT ORIENTED PROGRAMMING * thawatchai Yango * ASSIGNMENT 7 * 203074 */ #include <iostream> #include <fstream> using namespace std; int main() { int rpt; fstream file; //object of fstream class char data[50]; file.open("file.dat",ios::out); if(!file) { cout<<"Error in creating file!!!"<<endl; return 0; } cout<<"File created successfully."<<endl; cout<<"Do you Want To Add Data In File?(1-Yes/0-No):"; cin>>rpt; while(rpt == 1) { cout<<"Enter Data"<<endl; cin.ignore(); cin.getline(data,100); file<<data<<endl; cout<<"Do you Want To Add Again In File?(1-Yes/0-No):"; cin>>rpt; } file.close(); //closing the file file.open("file.dat",ios::in); if(!file) { cout<<"Error in opening file!!!"<<endl; return 0; } char ch; cout<<"File content: "; while(!file.eof()) //read untill end of file is not found. { file>>ch; //read single character from file cout<<ch; } file.close(); //closing the file return 0; } /* ****OUTPUT**** File created successfully. Do you Want To Add Data In File?(1-Yes/0-No):1 Enter Data my name is Do you Want To Add Again In File?(1-Yes/0-No):1 Enter Data Thawatchai yango Do you Want To Add Again In File?(1-Yes/0-No):1 Enter Data from Thailand Do you Want To Add Again In File?(1-Yes/0-No):1 Enter Data studying at MIT Pune Do you Want To Add Again In File?(1-Yes/0-No):0 File content: mynameis Thawatchai yango fromThailand studying at MITPunee*/
[ "noreply@github.com" ]
noreply@github.com
8c00968046191d159f7953c764f5338e2eca81f1
6523f7b62390477ce5025428e55191fd40c5f951
/DataStructure/MazeSolver/MazeSolver/Stack.h
71234a41bab14dde16206eb16b1b5093a7d68795
[]
no_license
EmonMajumder/All-Code
28288ec4f84b35e2edf93ae3d3f43f06da40676c
77d2313898e8c4875c00689eb6f8ab55fdf62567
refs/heads/master
2023-01-11T00:53:11.959483
2020-07-28T03:07:28
2020-07-28T03:07:28
210,633,751
0
0
null
null
null
null
UTF-8
C++
false
false
202
h
#pragma once #include "StackNode.h" using namespace std; class Stack { private: StackNode *top; public: Stack(); void Push(int x, int y); void Pop(); StackNode *getTop(); virtual ~Stack(); };
[ "43067648+EmonMajumder@users.noreply.github.com" ]
43067648+EmonMajumder@users.noreply.github.com
6eebf23d82968577f544d90faa2c7622f5decda8
9dfbb9d251433b6f7d32cbdaf36231008b97162e
/Iditarod Challenge 2/Timer.hpp
94a685ef8af0220f956e8e9cf82ee7a6dc0fc90d
[]
no_license
Yaboi-Gengarboi/cs202
ab6562940687e481eed71820aaae5f082d094040
de547043f19d68a9ad2d4e1d2fbfee6d5ed5f9b4
refs/heads/master
2020-12-11T17:49:20.211545
2020-04-30T17:15:34
2020-04-30T17:15:34
233,916,514
0
0
null
null
null
null
UTF-8
C++
false
false
579
hpp
// Timer.hpp // Justyn Durnford // Created on 3/31/2020 // Last updated on 3/31/2020 #include <chrono> class Timer { std::chrono::time_point<std::chrono::system_clock> _start; std::chrono::time_point<std::chrono::system_clock> _end; bool _is_stopped = false; public: //Constructor Timer(); //Destructor ~Timer(); //Sets the value of _start. void start(); //Sets the value of _end. void stop(); //Returns the amount of seconds that have passed. double secondsPassed(); //Returns the amount of milliseconds that have passed. double millisecondsPassed(); };
[ "jpdurnford@alaska.edu" ]
jpdurnford@alaska.edu
dadfe15514869180985240046396d011dd4833d4
ab6f9267fbc5614b1fa635a07bfb5c858b85ccf7
/Debugger/DebugArrow.hpp
34249dc73d1b685288c9ffea2cb0f64650f93a68
[]
no_license
HoangNguyen174/SoulStoneEngine
b198ef87f174c81f267d3cd361d0eed5b9f0eed2
93183669b07778fc3fa472fb220d2f3a5469d9c8
refs/heads/master
2020-03-19T01:08:17.301041
2018-05-31T04:08:28
2018-05-31T04:08:28
135,525,298
0
0
null
null
null
null
UTF-8
C++
false
false
539
hpp
#ifndef DEBUG_ARROW_H #define DEBUG_ARROW_H #include "DebugObject.hpp" #include "../Utilities/GameCommon.hpp" class DebugArrow : public DebugObject { public: Vector3 m_startPosition; Vector3 m_endPosition; float m_size; RGBColor m_startPosColor; RGBColor m_endPosColor; public: DebugArrow() { m_size = 1.f; }; ~DebugArrow() {}; void Update(float elapsedTime) { DebugObject::Update(elapsedTime); }; void Render(); void RenderDepthTestOn(); void RenderDepthTestOff(); void RenderDualMode(); }; #endif
[ "hnguyen.programmer@gmail.com" ]
hnguyen.programmer@gmail.com
24b097e5dbf61e79513855fc80ff0d87ecef7edd
aaa56c93a97732f34a577c1f54bce47ccba7de62
/main/OpenCover.Test.Profiler/MockProfiler.h
eaf1359e1c3fcfce632990c7c654088f4ceb85e7
[ "MIT", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
danielpalme/opencover
5c8d90c5607471b7b4ae00f5a889d25fb3f4ad14
ef0a3f737fc39ea35609fbbfa1f54f32e425b7aa
refs/heads/master
2021-01-15T23:02:58.398334
2017-09-25T18:40:24
2017-09-25T18:40:24
2,208,832
1
1
null
null
null
null
UTF-8
C++
false
false
12,941
h
#pragma once #include "TestProfiler.h" class MockProfiler : public CTestProfiler { // ICorProfilerCallback public: MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, Initialize, HRESULT( /* [in] */ IUnknown *pICorProfilerInfoUnk)); MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, Shutdown, HRESULT()); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, AppDomainCreationStarted, HRESULT( /* [in] */ AppDomainID appDomainId)); MOCK_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, AppDomainCreationFinished, HRESULT( /* [in] */ AppDomainID appDomainId, /* [in] */ HRESULT hrStatus)); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, AppDomainShutdownStarted, HRESULT( /* [in] */ AppDomainID appDomainId)); MOCK_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, AppDomainShutdownFinished, HRESULT( /* [in] */ AppDomainID appDomainId, /* [in] */ HRESULT hrStatus)); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, AssemblyLoadStarted, HRESULT( /* [in] */ AssemblyID assemblyId)); MOCK_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, AssemblyLoadFinished, HRESULT( /* [in] */ AssemblyID assemblyId, /* [in] */ HRESULT hrStatus)); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, AssemblyUnloadStarted, HRESULT( /* [in] */ AssemblyID assemblyId)); MOCK_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, AssemblyUnloadFinished, HRESULT( /* [in] */ AssemblyID assemblyId, /* [in] */ HRESULT hrStatus)); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, ModuleLoadStarted, HRESULT( /* [in] */ ModuleID moduleId)); MOCK_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, ModuleLoadFinished, HRESULT( /* [in] */ ModuleID moduleId, /* [in] */ HRESULT hrStatus)); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, ModuleUnloadStarted, HRESULT( /* [in] */ ModuleID moduleId)); MOCK_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, ModuleUnloadFinished, HRESULT( /* [in] */ ModuleID moduleId, /* [in] */ HRESULT hrStatus)); MOCK_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, ModuleAttachedToAssembly, HRESULT( /* [in] */ ModuleID moduleId, /* [in] */ AssemblyID assemblyId)); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, ClassLoadStarted, HRESULT( /* [in] */ ClassID classId)); MOCK_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, ClassLoadFinished, HRESULT( /* [in] */ ClassID classId, /* [in] */ HRESULT hrStatus)); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, ClassUnloadStarted, HRESULT( /* [in] */ ClassID classId)); MOCK_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, ClassUnloadFinished, HRESULT( /* [in] */ ClassID classId, /* [in] */ HRESULT hrStatus)); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, FunctionUnloadStarted, HRESULT( /* [in] */ FunctionID functionId)); MOCK_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, JITCompilationStarted, HRESULT( /* [in] */ FunctionID functionId, /* [in] */ BOOL fIsSafeToBlock)); MOCK_METHOD3_WITH_CALLTYPE(STDMETHODCALLTYPE, JITCompilationFinished, HRESULT( /* [in] */ FunctionID functionId, /* [in] */ HRESULT hrStatus, /* [in] */ BOOL fIsSafeToBlock)); MOCK_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, JITCachedFunctionSearchStarted, HRESULT( /* [in] */ FunctionID functionId, /* [out] */ BOOL *pbUseCachedFunction)); MOCK_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, JITCachedFunctionSearchFinished, HRESULT( /* [in] */ FunctionID functionId, /* [in] */ COR_PRF_JIT_CACHE result)); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, JITFunctionPitched, HRESULT( /* [in] */ FunctionID functionId)); MOCK_METHOD3_WITH_CALLTYPE(STDMETHODCALLTYPE, JITInlining, HRESULT( /* [in] */ FunctionID callerId, /* [in] */ FunctionID calleeId, /* [out] */ BOOL *pfShouldInline)); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, ThreadCreated, HRESULT( /* [in] */ ThreadID functionId)); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, ThreadDestroyed, HRESULT( /* [in] */ ThreadID functionId)); MOCK_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, ThreadAssignedToOSThread, HRESULT( /* [in] */ ThreadID managedThreadId, /* [in] */ DWORD osThreadId)); MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, RemotingClientInvocationStarted, HRESULT()); MOCK_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, RemotingClientSendingMessage, HRESULT( /* [in] */ GUID *pCookie, /* [in] */ BOOL fIsAsync)); MOCK_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, RemotingClientReceivingReply, HRESULT( /* [in] */ GUID *pCookie, /* [in] */ BOOL fIsAsync)); MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, RemotingClientInvocationFinished, HRESULT()); MOCK_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, RemotingServerReceivingMessage, HRESULT( /* [in] */ GUID *pCookie, /* [in] */ BOOL fIsAsync)); MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, RemotingServerInvocationStarted, HRESULT()); MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, RemotingServerInvocationReturned, HRESULT()); MOCK_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, RemotingServerSendingReply, HRESULT( /* [in] */ GUID *pCookie, /* [in] */ BOOL fIsAsync)); MOCK_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, UnmanagedToManagedTransition, HRESULT( /* [in] */ FunctionID functionId, /* [in] */ COR_PRF_TRANSITION_REASON reason)); MOCK_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, ManagedToUnmanagedTransition, HRESULT( /* [in] */ FunctionID functionId, /* [in] */ COR_PRF_TRANSITION_REASON reason)); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, RuntimeSuspendStarted, HRESULT( /* [in] */ COR_PRF_SUSPEND_REASON suspendReason)); MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, RuntimeSuspendFinished, HRESULT()); MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, RuntimeSuspendAborted, HRESULT()); MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, RuntimeResumeStarted, HRESULT()); MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, RuntimeResumeFinished, HRESULT()); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, RuntimeThreadSuspended, HRESULT( /* [in] */ ThreadID threadId)); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, RuntimeThreadResumed, HRESULT( /* [in] */ ThreadID threadId)); MOCK_METHOD4_WITH_CALLTYPE(STDMETHODCALLTYPE, MovedReferences, HRESULT( /* [in] */ ULONG cMovedObjectIDRanges, /* [size_is][in] */ ObjectID oldObjectIDRangeStart[], /* [size_is][in] */ ObjectID newObjectIDRangeStart[], /* [size_is][in] */ ULONG cObjectIDRangeLength[])); MOCK_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, ObjectAllocated, HRESULT( /* [in] */ ObjectID objectId, /* [in] */ ClassID classId)); MOCK_METHOD3_WITH_CALLTYPE(STDMETHODCALLTYPE, ObjectsAllocatedByClass, HRESULT( /* [in] */ ULONG cClassCount, /* [size_is][in] */ ClassID classIds[], /* [size_is][in] */ ULONG cObjects[])); MOCK_METHOD4_WITH_CALLTYPE(STDMETHODCALLTYPE, ObjectReferences, HRESULT( /* [in] */ ObjectID objectId, /* [in] */ ClassID classId, /* [in] */ ULONG cObjectRefs, /* [size_is][in] */ ObjectID objectRefIds[])); MOCK_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, RootReferences, HRESULT( /* [in] */ ULONG cRootRefs, /* [size_is][in] */ ObjectID rootRefIds[])); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, ExceptionThrown, HRESULT( /* [in] */ ObjectID thrownObjectId)); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, ExceptionSearchFunctionEnter, HRESULT( /* [in] */ FunctionID functionId)); MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, ExceptionSearchFunctionLeave, HRESULT()); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, ExceptionSearchFilterEnter, HRESULT( /* [in] */ FunctionID functionId)); MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, ExceptionSearchFilterLeave, HRESULT()); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, ExceptionSearchCatcherFound, HRESULT( /* [in] */ FunctionID functionId)); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, ExceptionOSHandlerEnter, HRESULT( /* [in] */ UINT_PTR __unused)); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, ExceptionOSHandlerLeave, HRESULT( /* [in] */ UINT_PTR __unused)); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, ExceptionUnwindFunctionEnter, HRESULT( /* [in] */ FunctionID functionId)); MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, ExceptionUnwindFunctionLeave, HRESULT()); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, ExceptionUnwindFinallyEnter, HRESULT( /* [in] */ FunctionID functionId)); MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, ExceptionUnwindFinallyLeave, HRESULT()); MOCK_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, ExceptionCatcherEnter, HRESULT( /* [in] */ FunctionID functionId, /* [in] */ ObjectID objectId)); MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, ExceptionCatcherLeave, HRESULT()); MOCK_METHOD4_WITH_CALLTYPE(STDMETHODCALLTYPE, COMClassicVTableCreated, HRESULT( /* [in] */ ClassID wrappedClassId, /* [in] */ REFGUID implementedIID, /* [in] */ void *pVTable, /* [in] */ ULONG cSlots)); MOCK_METHOD3_WITH_CALLTYPE(STDMETHODCALLTYPE, COMClassicVTableDestroyed, HRESULT( /* [in] */ ClassID wrappedClassId, /* [in] */ REFGUID implementedIID, /* [in] */ void *pVTable)); MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, ExceptionCLRCatcherFound, HRESULT()); MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, ExceptionCLRCatcherExecute, HRESULT()); // ICorProfilerCallback2 public: MOCK_METHOD3_WITH_CALLTYPE(STDMETHODCALLTYPE, ThreadNameChanged, HRESULT( /* [in] */ ThreadID threadId, /* [in] */ ULONG cchName, /* [in] */ __in_ecount_opt(cchName) WCHAR name[])); MOCK_METHOD3_WITH_CALLTYPE(STDMETHODCALLTYPE, GarbageCollectionStarted, HRESULT( /* [in] */ int cGenerations, /* [size_is][in] */ BOOL generationCollected[], /* [in] */ COR_PRF_GC_REASON reason)); MOCK_METHOD3_WITH_CALLTYPE(STDMETHODCALLTYPE, SurvivingReferences, HRESULT( /* [in] */ ULONG cSurvivingObjectIDRanges, /* [size_is][in] */ ObjectID objectIDRangeStart[], /* [size_is][in] */ ULONG cObjectIDRangeLength[])); MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, GarbageCollectionFinished, HRESULT()); MOCK_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, FinalizeableObjectQueued, HRESULT( /* [in] */ DWORD finalizerFlags, /* [in] */ ObjectID objectID)); MOCK_METHOD5_WITH_CALLTYPE(STDMETHODCALLTYPE, RootReferences2, HRESULT( /* [in] */ ULONG cRootRefs, /* [size_is][in] */ ObjectID rootRefIds[], /* [size_is][in] */ COR_PRF_GC_ROOT_KIND rootKinds[], /* [size_is][in] */ COR_PRF_GC_ROOT_FLAGS rootFlags[], /* [size_is][in] */ UINT_PTR rootIds[])); MOCK_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, HandleCreated, HRESULT( /* [in] */ GCHandleID handleId, /* [in] */ ObjectID initialObjectId)); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, HandleDestroyed, HRESULT( /* [in] */ GCHandleID handleId)); // ICorProfilerCallback3 public: MOCK_METHOD3_WITH_CALLTYPE(STDMETHODCALLTYPE, InitializeForAttach, HRESULT( /* [in] */ IUnknown *pCorProfilerInfoUnk, /* [in] */ void *pvClientData, /* [in] */ UINT cbClientData)); MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, ProfilerAttachComplete, HRESULT()); MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, ProfilerDetachSucceeded, HRESULT()); // ICorProfilerCallback4 public: MOCK_METHOD3_WITH_CALLTYPE(STDMETHODCALLTYPE, ReJITCompilationStarted, HRESULT( /* [in] */ FunctionID functionId, /* [in] */ ReJITID rejitId, /* [in] */ BOOL fIsSafeToBlock)); MOCK_METHOD3_WITH_CALLTYPE(STDMETHODCALLTYPE, GetReJITParameters, HRESULT( /* [in] */ ModuleID moduleId, /* [in] */ mdMethodDef methodId, /* [in] */ ICorProfilerFunctionControl *pFunctionControl)); MOCK_METHOD4_WITH_CALLTYPE(STDMETHODCALLTYPE, ReJITCompilationFinished, HRESULT( /* [in] */ FunctionID functionId, /* [in] */ ReJITID rejitId, /* [in] */ HRESULT hrStatus, /* [in] */ BOOL fIsSafeToBlock)); MOCK_METHOD4_WITH_CALLTYPE(STDMETHODCALLTYPE, ReJITError, HRESULT( /* [in] */ ModuleID moduleId, /* [in] */ mdMethodDef methodId, /* [in] */ FunctionID functionId, /* [in] */ HRESULT hrStatus)); MOCK_METHOD4_WITH_CALLTYPE(STDMETHODCALLTYPE, MovedReferences2, HRESULT( /* [in] */ ULONG cMovedObjectIDRanges, /* [size_is][in] */ ObjectID oldObjectIDRangeStart[], /* [size_is][in] */ ObjectID newObjectIDRangeStart[], /* [size_is][in] */ SIZE_T cObjectIDRangeLength[])); MOCK_METHOD3_WITH_CALLTYPE(STDMETHODCALLTYPE, SurvivingReferences2, HRESULT( /* [in] */ ULONG cSurvivingObjectIDRanges, /* [size_is][in] */ ObjectID objectIDRangeStart[], /* [size_is][in] */ SIZE_T cObjectIDRangeLength[])); // ICorProfilerCallback5 public: MOCK_METHOD4_WITH_CALLTYPE(STDMETHODCALLTYPE, ConditionalWeakTableElementReferences, HRESULT( /* [in] */ ULONG cRootRefs, /* [size_is][in] */ ObjectID keyRefIds[], /* [size_is][in] */ ObjectID valueRefIds[], /* [size_is][in] */ GCHandleID rootIds[])); // ICorProfilerCallback6 public: MOCK_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, GetAssemblyReferences, HRESULT( /* [string][in] */ const WCHAR *wszAssemblyPath, /* [in] */ ICorProfilerAssemblyReferenceProvider *pAsmRefProvider)); // ICorProfilerCallback7 public: MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, ModuleInMemorySymbolsUpdated, HRESULT( /* [in] */ ModuleID moduleId)); };
[ "sawilde@users.noreply.github.com" ]
sawilde@users.noreply.github.com
82542b66f8ef792b7507277cc6d01fb4cc005c77
332ca801832e7e91f53bd42a6bf13d41000b752c
/renderer/utils/image_utils.hpp
277e252f17aa2599e59d91c015b9c0ad5e1b89bc
[ "MIT" ]
permissive
schwa423/Granite
d1ddb21ded8758e95d3252fb3a4afeb63ec93d3c
b609789ccfea07f9ca47ea1758411acd760ba757
refs/heads/master
2021-04-15T04:57:45.905705
2018-08-06T18:54:55
2018-08-06T18:54:55
126,874,476
1
0
null
null
null
null
UTF-8
C++
false
false
1,874
hpp
/* Copyright (c) 2017-2018 Hans-Kristian Arntzen * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include "device.hpp" namespace Granite { Vulkan::ImageHandle convert_equirect_to_cube(Vulkan::Device &device, Vulkan::ImageView &view, float scale); Vulkan::ImageHandle convert_cube_to_ibl_diffuse(Vulkan::Device &device, Vulkan::ImageView &view); Vulkan::ImageHandle convert_cube_to_ibl_specular(Vulkan::Device &device, Vulkan::ImageView &view); struct ImageReadback { Vulkan::Fence fence; Vulkan::BufferHandle buffer; Vulkan::ImageCreateInfo create_info; Vulkan::TextureFormatLayout layout; }; ImageReadback save_image_to_cpu_buffer(Vulkan::Device &device, const Vulkan::Image &image, Vulkan::CommandBuffer::Type type); bool save_image_buffer_to_gtx(Vulkan::Device &device, ImageReadback &readback, const char *path); }
[ "maister@archlinux.us" ]
maister@archlinux.us
7c2232c85c76211734986f8a6ba59e54307f0446
73bbd5c89687f068e6b6dddd640db4164407e240
/src/xrGame/HudItem.h
2d90f5ab93d0d9b5294a9a04a6fea66b35e5c8cf
[ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ]
permissive
mortany/stcop_legacy
204d679abd31ccaf202684aaa5339d5b614ba5d9
d5243489aafcbdf30601006cd653944dcb66315c
refs/heads/master
2023-08-29T23:12:29.329571
2021-10-22T22:06:21
2021-10-22T22:06:21
369,280,655
2
4
null
null
null
null
UTF-8
C++
false
false
6,496
h
#pragma once class CSE_Abstract; class CPhysicItem; class NET_Packet; class CInventoryItem; class CMotionDef; #include "actor_defs.h" #include "inventory_space.h" #include "hudsound.h" struct attachable_hud_item; class motion_marks; class CHUDState { public: enum EHudStates { eIdle = 0, eShowing, eHiding, eHidden, eBore, eLastBaseState = eBore, }; private: u32 m_hud_item_state; u32 m_nextState; u32 m_dw_curr_state_time; protected: u32 m_dw_curr_substate_time; public: CHUDState () {SetState(eHidden);} IC u32 GetNextState () const {return m_nextState;} IC u32 GetState () const {return m_hud_item_state;} IC void SetState (u32 v) {m_hud_item_state = v; m_dw_curr_state_time=Device.dwTimeGlobal;ResetSubStateTime();} IC void SetNextState (u32 v) {m_nextState = v;} IC u32 CurrStateTime () const {return Device.dwTimeGlobal-m_dw_curr_state_time;} IC void ResetSubStateTime () {m_dw_curr_substate_time=Device.dwTimeGlobal;} virtual void SwitchState (u32 S) = 0; virtual void OnStateSwitch (u32 S) = 0; }; class CHudItem :public CHUDState { protected: CHudItem (); virtual ~CHudItem (); virtual DLL_Pure* _construct (); Flags16 m_huditem_flags; enum{ fl_pending = (1<<0), fl_renderhud = (1<<1), fl_inertion_enable = (1<<2), fl_inertion_allow = (1<<3), }; struct{ const CMotionDef* m_current_motion_def; shared_str m_current_motion; u32 m_dwMotionCurrTm; u32 m_dwMotionStartTm; u32 m_dwMotionEndTm; u32 m_startedMotionState; u8 m_started_rnd_anim_idx; bool m_bStopAtEndAnimIsRunning; }; public: virtual void Load (LPCSTR section); virtual BOOL net_Spawn (CSE_Abstract* DC) {return TRUE;}; virtual void net_Destroy () {}; virtual void OnEvent (NET_Packet& P, u16 type); virtual void OnH_A_Chield (); virtual void OnH_B_Chield (); virtual void OnH_B_Independent (bool just_before_destroy); virtual void OnH_A_Independent (); virtual void PlaySound (LPCSTR alias, const Fvector& position); virtual bool Action (u16 cmd, u32 flags) {return false;} void OnMovementChanged (ACTOR_DEFS::EMoveCommand cmd) ; virtual u8 GetCurrentHudOffsetIdx () {return 0;} BOOL GetHUDmode (); IC BOOL IsPending () const { return !!m_huditem_flags.test(fl_pending);} virtual bool ActivateItem (); virtual void DeactivateItem (); virtual void SendDeactivateItem (); virtual void OnActiveItem () {}; virtual void OnHiddenItem () {}; virtual void SendHiddenItem (); //same as OnHiddenItem but for client... (sends message to a server)... virtual void OnMoveToRuck (const SInvItemPlace& prev); bool IsHidden () const { return GetState() == eHidden;} // Does weapon is in hidden state bool IsHiding () const { return GetState() == eHiding;} bool IsShowing () const { return GetState() == eShowing;} virtual void SwitchState (u32 S); virtual void OnStateSwitch (u32 S); virtual void OnAnimationEnd (u32 state); virtual void OnMotionMark (u32 state, const motion_marks&){}; virtual void PlayAnimIdle (); virtual void PlayAnimBore (); bool TryPlayAnimIdle (); virtual bool MovingAnimAllowedNow () {return true;} virtual void PlayAnimIdleMoving (); virtual void PlayAnimIdleSprint (); virtual void UpdateCL (); virtual void renderable_Render (); virtual void UpdateHudAdditonal (Fmatrix&); virtual void UpdateXForm () = 0; u32 PlayHUDMotion (const shared_str& M, BOOL bMixIn, CHudItem* W, u32 state); bool isHUDAnimationExist (LPCSTR anim_name); u32 PlayHUDMotion_noCB (const shared_str& M, BOOL bMixIn); void StopCurrentAnimWithoutCallback(); //Mortan: новые параметры для системы аддонов virtual void UpdateAddonsTransform(bool for_hud = false) {}; // FFT++ Обновление положения аддонов на худе каждый кадр virtual void UpdateAddonsHudParams() {}; // FFT++ Обновление параметров худа с помощью аддонов, вероятно не потребуется если будем использовать фейковый скелет bool NeedUpdateHudParams; // FFT++ Флаг обновления параметров с помощью аддонов IC void RenderHud (BOOL B) { m_huditem_flags.set(fl_renderhud, B);} IC BOOL RenderHud () { return m_huditem_flags.test(fl_renderhud);} attachable_hud_item* HudItemData (); virtual void on_a_hud_attach (); virtual void on_b_hud_detach (); IC BOOL HudInertionEnabled () const { return m_huditem_flags.test(fl_inertion_enable);} IC BOOL HudInertionAllowed () const { return m_huditem_flags.test(fl_inertion_allow);} virtual float GetInertionFactor () { return 1.f; }; //--#SM+#-- virtual float GetInertionPowerFactor () { return 1.f; }; //--#SM+#-- virtual void render_hud_mode () {}; virtual bool need_renderable () {return true;}; virtual void render_item_3d_ui () {} virtual bool render_item_3d_ui_query () {return false;} virtual bool CheckCompatibility (CHudItem*) {return true;} protected: IC void SetPending (BOOL H) { m_huditem_flags.set(fl_pending, H);} shared_str hud_sect; //кадры момента пересчета XFORM и FirePos u32 dwFP_Frame; u32 dwXF_Frame; IC void EnableHudInertion (BOOL B) { m_huditem_flags.set(fl_inertion_enable, B);} IC void AllowHudInertion (BOOL B) { m_huditem_flags.set(fl_inertion_allow, B);} u32 m_animation_slot; HUD_SOUND_COLLECTION m_sounds; private: CPhysicItem *m_object; CInventoryItem *m_item; public: const shared_str& HudSection () const { return hud_sect;} IC CPhysicItem& object () const { VERIFY(m_object); return(*m_object);} IC CInventoryItem& item () const { VERIFY(m_item); return(*m_item);} IC u32 animation_slot () { return m_animation_slot;} virtual void on_renderable_Render () = 0; virtual void debug_draw_firedeps () {}; virtual CHudItem* cast_hud_item () { return this; } };
[ "cheatmaster1@mail.ru" ]
cheatmaster1@mail.ru
83b114da5877d2b3602724c0cb3d03ed4c017644
107ada72e6c612733410971f954fb85d79db9af8
/Test/CMSSW_8_0_24/src/CondFormats/DataRecord/src/L1TwinMuxParamsRcd.cc
ae9be8551e8fe591ab95d232982f43dbc89f239d
[]
no_license
pradumnkumar009/serviceTask_HO_trigger_studies
3cf1c07112a34c23d2af361afa37c1df75968810
8cc271fd5a6959fcb48aadda9dae1e4ac9304a00
refs/heads/master
2020-04-14T15:18:09.862669
2018-12-30T07:38:57
2018-12-30T07:38:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
320
cc
// -*- C++ -*- // // Package: Subsystem/Package // Class : L1TwinMuxParamsRcd // // Author: Giannis Flouris // Created: #include "CondFormats/DataRecord/interface/L1TwinMuxParamsRcd.h" #include "FWCore/Framework/interface/eventsetuprecord_registration_macro.h" EVENTSETUP_RECORD_REG(L1TwinMuxParamsRcd);
[ "soham.elessar@gmail.com" ]
soham.elessar@gmail.com
be18045af77bd80487e95e51ca798f244a553b8e
04b1803adb6653ecb7cb827c4f4aa616afacf629
/chrome/browser/extensions/event_router_forwarder.h
485b15a89e096f11f940e638514c0fc17dd4452e
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
3,719
h
// 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. #ifndef CHROME_BROWSER_EXTENSIONS_EVENT_ROUTER_FORWARDER_H_ #define CHROME_BROWSER_EXTENSIONS_EVENT_ROUTER_FORWARDER_H_ #include <string> #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/values.h" #include "chrome/browser/profiles/profile.h" #include "extensions/browser/extension_event_histogram_value.h" class GURL; namespace extensions { // This class forwards events to EventRouters. // The advantages of this class over direct usage of EventRouters are: // - this class is thread-safe, you can call the functions from UI and IO // thread. // - the class can handle if a profile is deleted between the time of sending // the event from the IO thread to the UI thread. // - this class can be used in contexts that are not governed by a profile, e.g. // by system URLRequestContexts. In these cases the |restrict_to_profile| // parameter remains NULL and events are broadcasted to all profiles. class EventRouterForwarder : public base::RefCountedThreadSafe<EventRouterForwarder> { public: EventRouterForwarder(); // Calls // DispatchEventToRenderers(event_name, event_args, profile, event_url) // on all (original) profiles' EventRouters. // May be called on any thread. void BroadcastEventToRenderers(events::HistogramValue histogram_value, const std::string& event_name, std::unique_ptr<base::ListValue> event_args, const GURL& event_url); // Calls // DispatchEventToRenderers(event_name, event_args, // use_profile_to_restrict_events ? profile : NULL, event_url) // on |profile|'s EventRouter. May be called on any thread. void DispatchEventToRenderers(events::HistogramValue histogram_value, const std::string& event_name, std::unique_ptr<base::ListValue> event_args, void* profile, bool use_profile_to_restrict_events, const GURL& event_url); protected: // Protected for testing. virtual ~EventRouterForwarder(); // Helper function for {Broadcast,Dispatch}EventTo{Extension,Renderers}. // Virtual for testing. virtual void HandleEvent(const std::string& extension_id, events::HistogramValue histogram_value, const std::string& event_name, std::unique_ptr<base::ListValue> event_args, void* profile, bool use_profile_to_restrict_events, const GURL& event_url); // Calls DispatchEventToRenderers or DispatchEventToExtension (depending on // whether extension_id == "" or not) of |profile|'s EventRouter. // |profile| may never be NULL. // Virtual for testing. virtual void CallEventRouter(Profile* profile, const std::string& extension_id, events::HistogramValue histogram_value, const std::string& event_name, std::unique_ptr<base::ListValue> event_args, Profile* restrict_to_profile, const GURL& event_url); private: friend class base::RefCountedThreadSafe<EventRouterForwarder>; DISALLOW_COPY_AND_ASSIGN(EventRouterForwarder); }; } // namespace extensions #endif // CHROME_BROWSER_EXTENSIONS_EVENT_ROUTER_FORWARDER_H_
[ "sunny.nam@samsung.com" ]
sunny.nam@samsung.com
0bf4ffd7029fddc12ddb2f82a64c47466feb6891
67a53e3ba09a6b8f83fc1d40b85b5941310702bd
/src/lib/battery/battery.cpp
4c166e93034a2b441309c76f294987bf571a8716
[ "BSD-3-Clause" ]
permissive
Diksha-agg/Firmware_val
f3bd60c7356b2f21b8c8ea4db98955f41d43e848
1efc1ba06997d19df3ed9bd927cfb24401b0fe03
refs/heads/main
2023-07-13T11:12:47.831945
2021-08-26T02:06:15
2021-08-26T02:06:15
397,618,511
0
0
null
null
null
null
UTF-8
C++
false
false
130
cpp
version https://git-lfs.github.com/spec/v1 oid sha256:143e7a0f292c243c23da4444f051513f36e5c683682b4a3216142565d7bdab34 size 12089
[ "diksha.dtu@gmail.com" ]
diksha.dtu@gmail.com
6ab3231c906e4b8e32ba2a6d1e707b39b8c88ab9
bb2cca81ee55f761031acb64109a7cafad859c5c
/include/OGRE/OgreRenderTargetListener.h
5df48e2827bb1f404624d8b7a5d05b31c0359dc8
[]
no_license
iaco79/baseogre
4ecc3f98dbda329c75bb4acd0bcaacdb9ccbeded
cba63af47a9a1c83b0af44332218e2dae088fa91
refs/heads/master
2021-08-30T17:39:21.064785
2015-12-02T19:44:43
2015-12-02T19:44:43
114,685,645
0
1
null
null
null
null
UTF-8
C++
false
false
6,460
h
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #ifndef __RenderTargetListener_H__ #define __RenderTargetListener_H__ #include "OgrePrerequisites.h" namespace Ogre { /** \addtogroup Core * @{ */ /** \addtogroup RenderSystem * @{ */ /** Struct containing information about a RenderTarget event. */ struct RenderTargetEvent { /// The source of the event being raised RenderTarget* source; }; /** Struct containing information about a RenderTarget Viewport-specific event. */ struct RenderTargetViewportEvent { /// The source of the event being raised Viewport* source; }; /** A interface class defining a listener which can be used to receive notifications of RenderTarget events. @remarks A 'listener' is an interface designed to be called back when particular events are called. This class defines the interface relating to RenderTarget events. In order to receive notifications of RenderTarget events, you should create a subclass of RenderTargetListener and override the methods for which you would like to customise the resulting processing. You should then call RenderTarget::addListener passing an instance of this class. There is no limit to the number of RenderTarget listeners you can register, allowing you to register multiple listeners for different purposes. RenderTarget events occur before and after the target is updated as a whole, and before and after each viewport on that target is updated. Each RenderTarget holds it's own set of listeners, but you can register the same listener on multiple render targets if you like since the event contains details of the originating RenderTarget. */ class _OgreExport RenderTargetListener { /* Note that this could have been an abstract class, but I made the explicit choice not to do this, because I wanted to give people the option of only implementing the methods they wanted, rather than having to create 'do nothing' implementations for those they weren't interested in. As such this class follows the 'Adapter' classes in Java rather than pure interfaces. */ public: virtual ~RenderTargetListener() {} /** Called just before a RenderTarget is about to be rendered into. @remarks This event is raised just before any of the viewports on the target are rendered to. You can perform manual rendering operations here if you want, but please note that if the Viewport objects attached to this target are set up to clear the background, you will lose whatever you render. If you want some kind of backdrop in this event you should turn off background clearing off on the viewports, and either clear the viewports yourself in this event handler before doing your rendering or just render over the top if you don't need to. */ virtual void preRenderTargetUpdate(const RenderTargetEvent& evt) { (void)evt; } /** Called just after a RenderTarget has been rendered to. @remarks This event is called just after all the viewports attached to the target in question have been rendered to. You can perform your own manual rendering commands in this event handler if you like, these will be composited with the contents of the target already there (depending on the material settings you use etc). */ virtual void postRenderTargetUpdate(const RenderTargetEvent& evt) { (void)evt; } /* Called just before a Viewport on a RenderTarget is to be updated. @remarks This method is called before each viewport on the RenderTarget is rendered to. You can use this to perform per-viewport settings changes, such as showing / hiding particular overlays. */ virtual void preViewportUpdate(const RenderTargetViewportEvent& evt) { (void)evt; } /* Called just after a Viewport on a RenderTarget is to be updated. @remarks This method is called after each viewport on the RenderTarget is rendered to. */ virtual void postViewportUpdate(const RenderTargetViewportEvent& evt) { (void)evt; } /** Called to notify listener that a Viewport has been added to the target in question. */ virtual void viewportAdded(const RenderTargetViewportEvent& evt) { (void)evt; } /** Called to notify listener that a Viewport has been removed from the target in question. */ virtual void viewportRemoved(const RenderTargetViewportEvent& evt) { (void)evt; } }; /** @} */ /** @} */ } #endif
[ "othonic@gmail.com" ]
othonic@gmail.com
8a48e7d912040412d95bee63c93b863ec2f6c9b3
b8bbdfb81ed0ae9c1db9ff5ac3bf656c8573c214
/rds/include/alibabacloud/rds/model/PreCheckDBInstanceOperationResult.h
29fd73b3dee9ead2dcfc32c19404aeec48090cfb
[ "Apache-2.0" ]
permissive
rpdhunter/aliyun-openapi-cpp-sdk
01c2b60f865d80a15d90bf8f83999158027d7f79
f16c54ae8c085e84b44f75146c7d3547ad1753f6
refs/heads/master
2020-09-24T16:00:34.584234
2019-12-02T02:11:06
2019-12-02T02:11:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,633
h
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef ALIBABACLOUD_RDS_MODEL_PRECHECKDBINSTANCEOPERATIONRESULT_H_ #define ALIBABACLOUD_RDS_MODEL_PRECHECKDBINSTANCEOPERATIONRESULT_H_ #include <string> #include <vector> #include <utility> #include <alibabacloud/core/ServiceResult.h> #include <alibabacloud/rds/RdsExport.h> namespace AlibabaCloud { namespace Rds { namespace Model { class ALIBABACLOUD_RDS_EXPORT PreCheckDBInstanceOperationResult : public ServiceResult { public: struct FailuresItem { std::string message; std::string code; }; PreCheckDBInstanceOperationResult(); explicit PreCheckDBInstanceOperationResult(const std::string &payload); ~PreCheckDBInstanceOperationResult(); bool getPreCheckResult()const; std::vector<FailuresItem> getFailures()const; protected: void parse(const std::string &payload); private: bool preCheckResult_; std::vector<FailuresItem> failures_; }; } } } #endif // !ALIBABACLOUD_RDS_MODEL_PRECHECKDBINSTANCEOPERATIONRESULT_H_
[ "sdk-team@alibabacloud.com" ]
sdk-team@alibabacloud.com
fda801fe2a2083018e6dffbc22a86738c92df5e3
cd13341f077dabc28aac79eaf79ff5fb4622e293
/include/SL_Socket_TcpServer.h
0183c8d8bb81b195f8d6626f3f1d1ae28904b83e
[ "BSD-2-Clause" ]
permissive
cwschmidt/socketlite
2607eaeb414b8e7fa2bda6355ef2e17bcc2040e7
dcb8a03de50b95bcfe2ccd24dbc1ce347de21b3b
refs/heads/master
2016-09-09T21:34:34.832642
2014-02-28T07:20:06
2014-02-28T07:20:06
34,139,112
0
1
null
null
null
null
UTF-8
C++
false
false
7,013
h
#ifndef SOCKETLITE_SOCKET_TCP_SERVER_H #define SOCKETLITE_SOCKET_TCP_SERVER_H #include "SL_Config.h" #include "SL_Socket_INET_Addr.h" #include "SL_Socket_Source.h" #include "SL_Socket_Runner.h" #include "SL_Thread_Group.h" #include "SL_ObjectPool.h" #include "SL_Socket_TcpServer_Handler.h" template <typename TClientHandler, typename TObjectPool, typename TServerHandler=SL_Socket_TcpServer_Handler> class SL_Socket_TcpServer : public SL_Socket_Source { public: SL_Socket_TcpServer() { set_config(); } virtual ~SL_Socket_TcpServer() { close(); } int open(ushort local_port, int backlog=128, const char *local_name=NULL, bool is_ipv6=false) { close(); int ret = local_addr_.set(local_name, local_port, is_ipv6); if (ret < 0) { return -1; } int address_family = is_ipv6 ? AF_INET6:AF_INET; SL_SOCKET fd = SL_Socket_CommonAPI::socket_open(address_family, SOCK_STREAM, IPPROTO_TCP); if (SL_INVALID_SOCKET == fd) { return -2; } if (server_handler_.handle_open(fd, this, socket_runner_) < 0) { ret = -3; goto EXCEPTION_EXIT_PROC; } SL_Socket_CommonAPI::socket_set_reuseaddr(fd, 1); ret = SL_Socket_CommonAPI::socket_bind(fd, local_addr_.get_addr(), local_addr_.get_addr_size()); if (ret < 0) { ret = -4; goto EXCEPTION_EXIT_PROC; } ret = SL_Socket_CommonAPI::socket_listen(fd, backlog); if (ret < 0) { ret = -5; goto EXCEPTION_EXIT_PROC; } if (accept_thread_num_ > 0) { SL_Socket_CommonAPI::socket_set_block(fd, true); if (accept_thread_group_.start(accept_proc, this, accept_thread_num_, accept_thread_num_) < 0) { ret = -6; goto EXCEPTION_EXIT_PROC; } socket_handler_ = &server_handler_; return 0; } if (socket_runner_->add_handle(&server_handler_, SL_Socket_Handler::READ_EVENT_MASK) < 0) { ret = -7; goto EXCEPTION_EXIT_PROC; } socket_handler_ = &server_handler_; EXCEPTION_EXIT_PROC: server_handler_.set_socket(SL_INVALID_SOCKET); SL_Socket_CommonAPI::socket_close(fd); return ret; } int close() { if (NULL != socket_handler_) { if (accept_thread_num_ > 0) { accept_thread_group_.stop(); } SL_Socket_CommonAPI::socket_close(server_handler_.get_socket()); server_handler_.set_socket(SL_INVALID_SOCKET); server_handler_.handle_close(); socket_handler_ = NULL; } return 0; } int set_config(ushort accept_thread_num = 1, bool is_add_runner = true, uint maxconnect_num = 100000, uint recvbuffer_size = 4096, uint msgbuffer_size = 4096, uint8 msglen_bytes = 2, uint8 msg_byteorder = 0) { accept_thread_num_ = accept_thread_num; is_add_runner_ = is_add_runner; maxconnect_num_ = maxconnect_num; recvbuffer_size_ = recvbuffer_size; msgbuffer_size_ = msgbuffer_size; msglen_bytes_ = msglen_bytes; msg_byteorder_ = msg_byteorder; switch (msglen_bytes) { case 1: { get_msglen_proc_ = SL_Socket_Source::get_msglen_int8; set_msglen_proc_ = SL_Socket_Source::set_msglen_int8; } break; case 2: if (msg_byteorder) { get_msglen_proc_ = SL_Socket_Source::get_msglen_int16_network; set_msglen_proc_ = SL_Socket_Source::set_msglen_int16_network; } else { get_msglen_proc_ = SL_Socket_Source::get_msglen_int16_host; set_msglen_proc_ = SL_Socket_Source::set_msglen_int16_host; } break; case 4: if (msg_byteorder) { get_msglen_proc_ = SL_Socket_Source::get_msglen_int32_network; set_msglen_proc_ = SL_Socket_Source::set_msglen_int32_network; } else { get_msglen_proc_ = SL_Socket_Source::get_msglen_int32_host; set_msglen_proc_ = SL_Socket_Source::set_msglen_int32_host; } break; } return 0; } inline int set_interface(TObjectPool *object_pool, SL_Socket_Runner *socket_runner) { object_pool_ = object_pool; socket_runner_ = socket_runner; return 0; } inline SL_Socket_TcpServer_Handler* get_socket_handler() { return &server_handler_; } inline SL_Socket_INET_Addr* get_local_addr() { return &local_addr_; } inline SL_Socket_Handler* alloc_handler() { return object_pool_->alloc_object(); } inline void free_handler(SL_Socket_Handler *socket_handler) { if (socket_handler_ != socket_handler) { object_pool_->free_object((TClientHandler *)socket_handler); } return; } private: #ifdef SOCKETLITE_OS_WINDOWS static unsigned int WINAPI accept_proc(void *arg) #else static void* accept_proc(void *arg) #endif { SL_Socket_TcpServer *tcpserver = (SL_Socket_TcpServer*)arg; SL_Socket_INET_Addr sl_addr(tcpserver->get_local_addr()->is_ipv6()); sockaddr *addr = sl_addr.get_addr(); int addrlen = sl_addr.get_addr_size(); SL_SOCKET client_socket; SL_SOCKET listen_fd = tcpserver->server_handler_.get_socket(); while (1) { if (!tcpserver->accept_thread_group_.get_running()) { break; } client_socket = SL_Socket_CommonAPI::socket_accept(listen_fd, addr, &addrlen); if (SL_INVALID_SOCKET == client_socket) { continue; } if (tcpserver->get_socket_handler()->handle_accept(client_socket, sl_addr) < 0) { SL_Socket_CommonAPI::socket_close(client_socket); } } return 0; } protected: SL_Socket_INET_Addr local_addr_; uint maxconnect_num_; ushort accept_thread_num_; SL_Thread_Group accept_thread_group_; TServerHandler server_handler_; TObjectPool *object_pool_; }; #endif
[ "bolidezhang@gmail.com@e833b10f-1046-261c-ddef-a3d947df9845" ]
bolidezhang@gmail.com@e833b10f-1046-261c-ddef-a3d947df9845
b4b13048dd617a2c11172b989885921e56e65dca
0bbe0db077a6afd2a0f41dd9dad9b88b08d1c8d0
/OOP_TUT5/Game.h
74e98367920ffd7b77ad4f8a7422caef02e74457
[]
no_license
amjav/OOP-Dice
bcdc317397f88e249ec78d638d940404293ed44f
4b3a3b209c8744c3591c133f65727d3c097b6df5
refs/heads/main
2023-01-04T18:45:35.525853
2020-10-30T12:19:13
2020-10-30T12:19:13
308,619,450
0
0
null
null
null
null
UTF-8
C++
false
false
622
h
#pragma once #include "Player.h" #include "Dice.h" class Game { //pointers are used: //1: so you dont have to create more than one of the same class if it is being used by all. //example: 2 dice would use the same randomnumberobject rather than creating two seperate objects //2: for the player allows a change in player as you are able to change where the pointer for the player is pointing (a different player). public: Game(Player* player); Game() = default; private: Player* player = nullptr; //dont want composition therefore use a pointer //Create dice objects Dice Dice1; Dice Dice2; };
[ "61292170+amjav@users.noreply.github.com" ]
61292170+amjav@users.noreply.github.com
49dcf0464316186de7fe49967b5e215acb2568e9
be87a8f42f9bbd9b42999786b91e2e72873f25a3
/src/mesh.cpp
020feff3eb5666db641498c36dbb2b3594616c4c
[]
no_license
RachelVeer/stunts_remake
a6b5a4306e0a851548c43db92fcb78443b880521
c03402cd9e3ea437729b6a8a935a4e1c63ce9940
refs/heads/master
2022-01-18T01:47:57.384740
2019-07-03T08:58:14
2019-07-03T08:58:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,843
cpp
#include "mesh.hpp" Mesh::Mesh(const char* filename) { loadModel(filename); generateMeshInterface(); } Mesh::~Mesh() { delete meshInterface; } void Mesh::loadModel(const char* filename) { tinyobj::attrib_t attrib; std::vector<tinyobj::shape_t> shapes; std::string err; bool ret = tinyobj::LoadObj(&attrib, &shapes, &materials, &err, filename, "assets/models/"); if (!err.empty()) { printf("Error while loading obj: %s", err.c_str()); } if (!ret) { exit(1); } for (size_t s = 0; s < shapes.size(); s++) { size_t index_offset = 0; for (size_t f = 0; f < shapes[s].mesh.num_face_vertices.size(); f++) { int fv = shapes[s].mesh.num_face_vertices[f]; int materialId = shapes[s].mesh.material_ids[f]; std::vector<glm::vec3> face; for (size_t v = 0; v < fv; v++) { tinyobj::index_t idx = shapes[s].mesh.indices[index_offset + v]; tinyobj::real_t vx = attrib.vertices[3 * idx.vertex_index + 0]; tinyobj::real_t vy = attrib.vertices[3 * idx.vertex_index + 1]; tinyobj::real_t vz = attrib.vertices[3 * idx.vertex_index + 2]; face.push_back(glm::vec3(vx, vy, vz)); materialVertexMap[materialId].push_back({ vx, vy, vz }); tinyobj::real_t nx = attrib.normals[3 * idx.normal_index + 0]; tinyobj::real_t ny = attrib.normals[3 * idx.normal_index + 1]; tinyobj::real_t nz = attrib.normals[3 * idx.normal_index + 2]; materialNormalMap[materialId].push_back({ nx, ny, nz }); } faces.push_back(face); index_offset += fv; } } } void Mesh::generateMeshInterface() { meshInterface = new btTriangleMesh(); for (int i = 0; i < faces.size(); i++) { std::vector<glm::vec3> face = faces[i]; meshInterface->addTriangle( btVector3(face[0].x, face[0].y, face[0].z), btVector3(face[1].x, face[1].y, face[1].z), btVector3(face[2].x, face[2].y, face[2].z) ); } }
[ "marcin.sewastianowicz@gmail.com" ]
marcin.sewastianowicz@gmail.com
9d148d68ab6bdd07bf1b0dfeed0d10e9622307da
09ec1d6a02972af14d1e1ce8ea5bbc2241005428
/tests/test.cpp
e59dcf0d688e445ecf412ac3b73c7bc1b4c6fd02
[]
no_license
marcellocordeiro/Cpp
797e223de891b8d38f170ba22f71881917ff191d
a56954be990ce689769f605e064d0e51305e9862
refs/heads/master
2021-01-21T17:47:09.544292
2018-03-15T22:56:23
2018-03-15T22:56:23
91,990,448
0
0
null
null
null
null
UTF-8
C++
false
false
3,852
cpp
#include <iostream> #include <string> #include "src/algorithm.hpp" #include "src/array.hpp" #include "src/bst.hpp" #include "src/functional.hpp" #include "src/graph.hpp" #include "src/graph_io.hpp" #include "src/heap.hpp" #include "src/list.hpp" #include "src/list_io.hpp" #include "src/queue.hpp" #include "src/stack.hpp" #include "src/union_find.hpp" #include "src/utility.hpp" #include "src/vector.hpp" void vectorTest() { vector<int> a, b; a.push_back(4); a.push_back(5); a.push_back(7); b.push_back(1); b.push_back(2); b.push_back(3); // std::sort(a.begin(), a.end()); for (auto it : a) std::cout << it << " "; std::cout << std::endl; a = b; a[1] = 10; for (auto it : a) std::cout << it << " "; std::cout << std::endl; } void stackTest() { stack<int> s; s.push(2); s.push(3); s.pop(); s.push(2); s.push(66); std::cout << "pop " << s.top() << '\n'; s.pop(); std::cout << "pop " << s.top() << '\n'; // s.print(); } void bstTest() { int n, k; bst<int> t; std::cin >> n; for (int i = 0; i < n; i++) { std::cin >> k; t.insert(k); } std::cout << "Height: " << t.height() << "\n"; // t.print(); } void heapTest() { priority_queue<int, less<int>> h; /*std::*/ vector<int> v; /*v.push_back(2); v.push_back(3); v.push_back(6); v.push_back(8); v.push_back(1); h.build(v);*/ h.push(66); h.push(5); h.push(9); h.push(1); h.push(888); h.push(77); h.push(666); h.push(4); h.push(11); // h.printCap(); while (h.size()) { std::cout << "[" << h.top() << "] " << std::endl; h.pop(); } } void pairTest() { pair<int, std::string> p = {5, "huehuehu"}, k; p = {8, "kkk"}; p.second = "agoravai"; k = p; std::cout << k.first << ' ' << k.second << std::endl; } void graphTest() { std::cout << __cplusplus << std::endl; { graph G(5); G.add_edge({0, 1}, 10); G.add_edge({0, 4}, 3); G.add_edge({1, 2}, 2); G.add_edge({1, 4}, 4); G.add_edge({2, 3}, 9); G.add_edge({3, 2}, 7); G.add_edge({4, 1}, 1); G.add_edge({4, 2}, 8); G.add_edge({4, 3}, 2); #if __cplusplus >= 201703L auto[d, f] = G.dijkstra(0); #else auto df = G.dijkstra(0); auto d = df.first; auto f = df.second; #endif for (const auto& it : d) { std::cout << it << ' '; } std::cout << std::endl; for (const auto& it : f) { std::cout << it << ' '; } std::cout << std::endl; std::cout << G; } int V = 9; graph g(V); { g.add_edge({0, 1}, 4); g.add_edge({0, 7}, 8); g.add_edge({1, 2}, 8); g.add_edge({1, 7}, 11); g.add_edge({2, 3}, 7); g.add_edge({2, 8}, 2); g.add_edge({2, 5}, 4); g.add_edge({3, 4}, 9); g.add_edge({3, 5}, 14); g.add_edge({4, 5}, 10); g.add_edge({5, 6}, 2); g.add_edge({6, 7}, 1); g.add_edge({6, 8}, 6); g.add_edge({7, 8}, 7); g.bfs(2); g.dfs(2); #if __cplusplus >= 201703L auto[f, w] = g.prim(0); #else auto fw = g.prim(0); auto f = fw.first; auto w = fw.second; #endif for (unsigned int i = 1; i < f.size(); i++) { std::cout << f[i] << " - " << i << std::endl; } graph T(V); for (const auto& it : f) { std::cout << it << ' '; } std::cout << std::endl; for (const auto& it : w) { std::cout << it << ' '; } std::cout << std::endl; for (int i = 0; i < 9; i++) { if (f[i] != -1) { T.add_edge({i, f[i]}, w[i]); } } std::cout << g; std::cout << std::endl; std::cout << T; } } int main() { // queueTest(); // heapTest(); // vectorTest(); // pairTest(); // bstTest(); // graphTest(); // arrayTest(); // heap<pair<int, int>, less> h; // list<pair<int, int>> l; // list<pair<int, int>> l; // std::cin.get(); return 0; }
[ "msc3@cin.ufpe.br" ]
msc3@cin.ufpe.br
74532ef7ea3e2f654c9393819b80adfc8a52c351
7f33e5d8b124f899ab3f3a7e72c4624f1ef6d7ef
/1503-StructByLightning-LostSamurai-StrawManProject/Lost Samurai/Last Samurai/DestroyAllEntity.h
052a264987b2dd1766e5888523792a657d43bbfb
[]
no_license
CnoteSBL43/StructByLightningLastSamurai
7c7fbb379257f75f57c33dd20979c6a1fe080138
d316eab9a5751c8cea252bc55be3f1d30a7dc26f
refs/heads/master
2021-01-13T02:09:05.875368
2015-04-25T16:30:45
2015-04-25T16:30:45
32,112,849
0
0
null
null
null
null
UTF-8
C++
false
false
158
h
#pragma once #include "../SGD Wrappers//SGD_Message.h" #include "MessageID.h" class DestroyAllEntity { public: DestroyAllEntity(); ~DestroyAllEntity(); };
[ "blake186@fullsail.edu" ]
blake186@fullsail.edu
04862387609f133683c98267aec4506ce068ccc1
aabfbd4f6c940aa7c75195bd60d19a551fce3822
/summer_school_private/anymal_research/any_measurements/include/any_measurements/Twist.hpp
269eb594043c671162b8e923be8bd36b03b76178
[]
no_license
daoran/eth_supermegabot
9c5753507be243fc15133c9dfb1d0a5d4ff1d496
52b82300718c91344f41b4e11bbcf892d961af4b
refs/heads/master
2020-07-28T13:42:08.906212
2019-12-04T16:51:42
2019-12-04T16:51:42
209,428,875
1
1
null
2019-09-19T00:36:33
2019-09-19T00:36:33
null
UTF-8
C++
false
false
599
hpp
#pragma once #include "kindr/Core" #include "any_measurements/Time.hpp" namespace any_measurements { struct Twist { public: Twist() = default; Twist( const Time& time, const kindr::TwistLocalD& twist ): time_(time), twist_(twist) { } virtual ~Twist() = default; public: Time time_; kindr::TwistLocalD twist_; }; inline std::ostream& operator<<(std::ostream& os, const Twist& twist) { return os << "Twist (Time: " << twist.time_ << ")" << "\n Twist: " << twist.twist_; } } /* namespace any_measurements */
[ "hlin@ethz.ch" ]
hlin@ethz.ch
b2a60e37692807a1bab52cca19f60609e9103c53
95025210b9131d8bbddfe2f4b85e0cf683596c1f
/Src/GeneralInput/picture.cpp
4a8d45b01bdf177fb3baa7be6a022d066d652953
[]
no_license
SamuelBacaner1112/APlate
ece78b86f4cda173c7e1c3d3776d3aaf0ef1d341
0d89bd5beadc811d9d33c75f3110903f8b4f256e
refs/heads/master
2023-01-24T07:50:59.851986
2020-12-09T00:19:05
2020-12-09T00:19:05
319,794,441
0
2
null
null
null
null
UTF-8
C++
false
false
1,081
cpp
// Machine generated IDispatch wrapper class(es) created by Microsoft Visual C++ // NOTE: Do not modify the contents of this file. If this class is regenerated by // Microsoft Visual C++, your modifications will be overwritten. #include "stdafx.h" #include "picture.h" ///////////////////////////////////////////////////////////////////////////// // CPicture2 properties long CPicture2::GetHandle() { long result; GetProperty(0x0, VT_I4, (void*)&result); return result; } long CPicture2::GetHPal() { long result; GetProperty(0x2, VT_I4, (void*)&result); return result; } void CPicture2::SetHPal(long propVal) { SetProperty(0x2, VT_I4, propVal); } short CPicture2::GetType() { short result; GetProperty(0x3, VT_I2, (void*)&result); return result; } long CPicture2::GetWidth() { long result; GetProperty(0x4, VT_I4, (void*)&result); return result; } long CPicture2::GetHeight() { long result; GetProperty(0x5, VT_I4, (void*)&result); return result; } ///////////////////////////////////////////////////////////////////////////// // CPicture2 operations
[ "75705234+SamuelBacaner1112@users.noreply.github.com" ]
75705234+SamuelBacaner1112@users.noreply.github.com
30a5273221edf8665cf0a8f331b15c1ab437714c
46f2e7a10fca9f7e7b80b342240302c311c31914
/opposing_lid_driven_flow/cavity/0.0606/uniform/time
e9b817dcb0511a9994f85264b239fa6133575cb5
[]
no_license
patricksinclair/openfoam_warmups
696cb1950d40b967b8b455164134bde03e9179a1
03c982f7d46b4858e3b6bfdde7b8e8c3c4275df9
refs/heads/master
2020-12-26T12:50:00.615357
2020-02-04T20:22:35
2020-02-04T20:22:35
237,510,814
0
0
null
null
null
null
UTF-8
C++
false
false
832
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 7 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; location "0.0606/uniform"; object time; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // value 0.0606000000000012223; name "0.0606"; index 1212; deltaT 5e-05; deltaT0 5e-05; // ************************************************************************* //
[ "patricksinclair@hotmail.co.uk" ]
patricksinclair@hotmail.co.uk
74af1eb0d9488823564e38e8f41990e301345688
402bf9ff2d78941ae845adb360099c1c596232f8
/Week_08/56.合并区间.cpp
9d6cf388392ea7d941157e7ca65a08dd4389964a
[]
no_license
17ljsh/-algorithm015
ab533e8a21482d228d45472efbf48812bfe793ea
9caf00bb65d5ac3071d78eded5d19988bf072177
refs/heads/master
2023-01-30T08:37:32.580053
2020-12-18T14:12:25
2020-12-18T14:12:25
289,919,133
0
0
null
2020-08-24T12:17:14
2020-08-24T12:17:13
null
GB18030
C++
false
false
1,164
cpp
class Solution { public: vector<vector<int>> merge(vector<vector<int>>& intervals) { int size = intervals.size(); if (!size) { return {}; } vector<vector<int>> res; //受大佬启发,对数组排序,能合并的一定连续 sort(intervals.begin(),intervals.end()); //思路 //如[a,b] [c,d] [e,f]这样的数据,若[a,b] [c,d]可合并,需满足b>=c,合并后为[a,max(b,d)]. //初始化最开始的区间 int left = intervals[0][0], right = intervals[0][1]; for (int i = 0; i < size; i++) { //[a,b] [c,d],当b >= c的时候执行 if (right >= intervals[i][0]) { right = max(right, intervals[i][1]); } else { //[a,b] [c,d],b < c,即可放入最终结果 res.push_back({left,right}); //更新当前区间 left = intervals[i][0]; right = intervals[i][1]; } } //注意这里还有最后一个区间需要放进去。 res.push_back({left,right}); return res; } };
[ "1375423284@qq.com" ]
1375423284@qq.com
5fe8fbb08f505d918c66ef88214a2a37df1e9c39
c5553524da92ea50ecdb4c735e4df645b2453963
/vol 103/p10374.cpp
9a4bd361bfec361d415a855a698e640bc098f4df
[]
no_license
hk-117/UVa_solves
d68720287f05e6e997ffe3b2924b4b7db05e914f
692be8a95f438cd107149186ac2f6a0df4728f5d
refs/heads/master
2023-04-16T16:46:55.112583
2023-04-12T06:42:58
2023-04-12T06:42:58
210,403,514
0
0
null
null
null
null
UTF-8
C++
false
false
1,048
cpp
#include<bits/stdc++.h> #define R(i,a,b,c) for(int i=a;i<b;i+=c) using namespace std; int main(){ int tc; scanf("%d",&tc); while(tc--){ int n,m; char Name[85],Part[85]; map<string,string> Parties; map<string,bool> Candidates; map<string,int> Votes; scanf("%d\n",&n); R(i,0,n,1){ fgets(Name,sizeof(Name),stdin); Name[strlen(Name)-1]='\0'; fgets(Part,sizeof(Part),stdin); Part[strlen(Part)-1]='\0'; Parties[string(Name)]=Part; Candidates[string(Name)]=true; } int mx=0; string NM; scanf("%d\n",&m); R(i,0,m,1){ fgets(Name,sizeof(Name),stdin); Name[strlen(Name)-1]='\0'; if(Candidates[string(Name)]){ Votes[string(Name)]++; if(mx < Votes[string(Name)]){ mx=Votes[string(Name)]; NM=Parties[string(Name)]; } } } int cnt=0; for(auto it=Votes.begin();it!=Votes.end();it++){ if(it->second == mx) cnt++; } if(cnt>1 || cnt==0){ cout<<"tie"<<endl; } else{ cout<<NM<<endl; } if(tc) cout<<endl; } }
[ "noreply@github.com" ]
noreply@github.com
47c861e5536c0773329f9be198beb25d7ab4377d
dcbaf5fd71f1ddecb8cf70ee7cf54bed0d9acc3d
/HdmiCec_2/HdmiCec_2.cpp
002954e7cd8bd5dc0881c11c7b31162e3a001ddb
[ "Apache-2.0", "BSD-2-Clause" ]
permissive
venkataprasadk/rdkservices
07b95ced3735b3e4946751df5bb0c40f2347549b
388ea5ab2f5d4ba034d0fd5da98c7d5d44697b77
refs/heads/sprint/2009
2023-01-19T14:13:47.829283
2020-11-10T14:29:18
2020-11-10T14:29:18
295,765,377
0
0
Apache-2.0
2020-09-15T17:34:27
2020-09-15T15:08:52
null
UTF-8
C++
false
false
40,192
cpp
/** * If not stated otherwise in this file or this component's LICENSE * file the following copyright and licenses apply: * * Copyright 2019 RDK Management * * 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 "HdmiCec_2.h" #include "ccec/Connection.hpp" #include "ccec/CECFrame.hpp" #include "ccec/MessageEncoder.hpp" #include "host.hpp" #include "ccec/host/RDK.hpp" #include "ccec/drivers/iarmbus/CecIARMBusMgr.h" #include "pwrMgr.h" #include "dsMgr.h" #include "dsDisplay.h" #include "videoOutputPort.hpp" #include "manager.hpp" #include "websocket/URL.h" #include "utils.h" #define HDMICEC2_METHOD_SET_ENABLED "setEnabled" #define HDMICEC2_METHOD_GET_ENABLED "getEnabled" #define HDMICEC2_METHOD_OTP_SET_ENABLED "setOTPEnabled" #define HDMICEC2_METHOD_OTP_GET_ENABLED "getOTPEnabled" #define HDMICEC2_METHOD_SET_OSD_NAME "setOSDName" #define HDMICEC2_METHOD_GET_OSD_NAME "getOSDName" #define HDMICEC2_METHOD_SET_VENDOR_ID "setVendorId" #define HDMICEC2_METHOD_GET_VENDOR_ID "getVendorId" #define HDMICEC2_METHOD_PERFORM_OTP_ACTION "performOTPAction" #define HDMICEC_EVENT_ON_DEVICES_CHANGED "onDevicesChanged" #define HDMICEC_EVENT_ON_HDMI_HOT_PLUG "onHdmiHotPlug" #define DEV_TYPE_TUNER 1 #define HDMI_HOT_PLUG_EVENT_CONNECTED 0 #define CEC_SETTING_ENABLED_FILE "/opt/persistent/ds/cecData_2.json" #define CEC_SETTING_ENABLED "cecEnabled" #define CEC_SETTING_OTP_ENABLED "cecOTPEnabled" #define CEC_SETTING_OSD_NAME "cecOSDName" #define CEC_SETTING_VENDOR_ID "cecVendorId" static vector<uint8_t> defaultVendorId = {0x00,0x19,0xFB}; static VendorID appVendorId = {defaultVendorId.at(0),defaultVendorId.at(1),defaultVendorId.at(2)}; static VendorID lgVendorId = {0x00,0xE0,0x91}; static PhysicalAddress physical_addr = {0x0F,0x0F,0x0F,0x0F}; static LogicalAddress logicalAddress = 0xF; static OSDName osdName = "TV Box"; static int32_t powerState = 1; static PowerStatus tvPowerState = 1; static bool isDeviceActiveSource = true; static bool isLGTvConnected = false; namespace WPEFramework { namespace Plugin { SERVICE_REGISTRATION(HdmiCec_2, 1, 0); HdmiCec_2* HdmiCec_2::_instance = nullptr; static int libcecInitStatus = 0; //=========================================== HdmiCec_2FrameListener ========================================= void HdmiCec_2FrameListener::notify(const CECFrame &in) const { const uint8_t *buf = NULL; char strBuffer[512] = {0}; size_t len = 0; in.getBuffer(&buf, &len); for (int i = 0; i < len; i++) { sprintf(strBuffer + (i*3) , "%02X ",(uint8_t) *(buf + i)); } LOGINFO(" >>>>> Received CEC Frame: :%s \n",strBuffer); MessageDecoder(processor).decode(in); } //=========================================== HdmiCec_2Processor ========================================= void HdmiCec_2Processor::process (const ActiveSource &msg, const Header &header) { printHeader(header); LOGINFO("Command: ActiveSource %s : %s : %s \n",GetOpName(msg.opCode()),msg.physicalAddress.name().c_str(),msg.physicalAddress.toString().c_str()); if(msg.physicalAddress.toString() == physical_addr.toString()) isDeviceActiveSource = true; else isDeviceActiveSource = false; LOGINFO("ActiveSource isDeviceActiveSource status :%d \n", isDeviceActiveSource); } void HdmiCec_2Processor::process (const InActiveSource &msg, const Header &header) { printHeader(header); LOGINFO("Command: InActiveSource %s : %s : %s \n",GetOpName(msg.opCode()),msg.physicalAddress.name().c_str(),msg.physicalAddress.toString().c_str()); } void HdmiCec_2Processor::process (const ImageViewOn &msg, const Header &header) { printHeader(header); LOGINFO("Command: ImageViewOn \n"); } void HdmiCec_2Processor::process (const TextViewOn &msg, const Header &header) { printHeader(header); LOGINFO("Command: TextViewOn\n"); } void HdmiCec_2Processor::process (const RequestActiveSource &msg, const Header &header) { printHeader(header); LOGINFO("Command: RequestActiveSource\n"); if(isDeviceActiveSource) { LOGINFO("sending ActiveSource\n"); try { conn.sendTo(LogicalAddress::BROADCAST, MessageEncoder().encode(ActiveSource(physical_addr))); } catch(...) { LOGWARN("Exception while sending ActiveSource"); } } } void HdmiCec_2Processor::process (const Standby &msg, const Header &header) { printHeader(header); if(header.from.toInt() == LogicalAddress::TV) { tvPowerState = 1; LOGINFO("Command: Standby tvPowerState :%s \n",(tvPowerState.toInt())?"OFF":"ON"); } } void HdmiCec_2Processor::process (const GetCECVersion &msg, const Header &header) { printHeader(header); LOGINFO("Command: GetCECVersion sending CECVersion response \n"); try { conn.sendTo(header.from, MessageEncoder().encode(CECVersion(Version::V_1_4))); } catch(...) { LOGWARN("Exception while sending CECVersion "); } } void HdmiCec_2Processor::process (const CECVersion &msg, const Header &header) { printHeader(header); LOGINFO("Command: CECVersion Version : %s \n",msg.version.toString().c_str()); } void HdmiCec_2Processor::process (const SetMenuLanguage &msg, const Header &header) { printHeader(header); LOGINFO("Command: SetMenuLanguage Language : %s \n",msg.language.toString().c_str()); } void HdmiCec_2Processor::process (const GiveOSDName &msg, const Header &header) { printHeader(header); LOGINFO("Command: GiveOSDName sending SetOSDName : %s\n",osdName.toString().c_str()); try { conn.sendTo(header.from, MessageEncoder().encode(SetOSDName(osdName))); } catch(...) { LOGWARN("Exception while sending SetOSDName"); } } void HdmiCec_2Processor::process (const GivePhysicalAddress &msg, const Header &header) { LOGINFO("Command: GivePhysicalAddress\n"); if (!(header.from == LogicalAddress(LogicalAddress::BROADCAST))) { try { LOGINFO(" sending ReportPhysicalAddress response physical_addr :%s logicalAddress :%x \n",physical_addr.toString().c_str(), logicalAddress.toInt()); conn.sendTo(LogicalAddress(LogicalAddress::BROADCAST), MessageEncoder().encode(ReportPhysicalAddress(physical_addr,logicalAddress.toInt()))); } catch(...) { LOGWARN("Exception while sending ReportPhysicalAddress "); } } } void HdmiCec_2Processor::process (const GiveDeviceVendorID &msg, const Header &header) { printHeader(header); try { LOGINFO("Command: GiveDeviceVendorID sending VendorID response :%s\n",(isLGTvConnected)?lgVendorId.toString().c_str():appVendorId.toString().c_str()); if(isLGTvConnected) conn.sendTo(LogicalAddress(LogicalAddress::BROADCAST), MessageEncoder().encode(DeviceVendorID(lgVendorId))); else conn.sendTo(LogicalAddress(LogicalAddress::BROADCAST), MessageEncoder().encode(DeviceVendorID(appVendorId))); } catch(...) { LOGWARN("Exception while sending DeviceVendorID"); } } void HdmiCec_2Processor::process (const SetOSDString &msg, const Header &header) { printHeader(header); LOGINFO("Command: SetOSDString OSDString : %s\n",msg.osdString.toString().c_str()); } void HdmiCec_2Processor::process (const SetOSDName &msg, const Header &header) { printHeader(header); LOGINFO("Command: SetOSDName OSDName : %s\n",msg.osdName.toString().c_str()); } void HdmiCec_2Processor::process (const RoutingChange &msg, const Header &header) { printHeader(header); LOGINFO("Command: RoutingChange From : %s To: %s \n",msg.from.toString().c_str(),msg.to.toString().c_str()); if(msg.to.toString() == physical_addr.toString()) isDeviceActiveSource = true; else isDeviceActiveSource = false; LOGINFO("physical_addr : %s isDeviceActiveSource :%d \n",physical_addr.toString().c_str(),isDeviceActiveSource); } void HdmiCec_2Processor::process (const RoutingInformation &msg, const Header &header) { printHeader(header); LOGINFO("Command: RoutingInformation Routing Information to Sink : %s\n",msg.toSink.toString().c_str()); if(msg.toSink.toString() == physical_addr.toString()) isDeviceActiveSource = true; else isDeviceActiveSource = false; LOGINFO("physical_addr : %s isDeviceActiveSource :%d \n",physical_addr.toString().c_str(),isDeviceActiveSource); } void HdmiCec_2Processor::process (const SetStreamPath &msg, const Header &header) { printHeader(header); LOGINFO("Command: SetStreamPath Set Stream Path to Sink : %s\n",msg.toSink.toString().c_str()); if(msg.toSink.toString() == physical_addr.toString()) isDeviceActiveSource = true; else isDeviceActiveSource = false; LOGINFO("physical_addr : %s isDeviceActiveSource :%d \n",physical_addr.toString().c_str(),isDeviceActiveSource); } void HdmiCec_2Processor::process (const GetMenuLanguage &msg, const Header &header) { printHeader(header); LOGINFO("Command: GetMenuLanguage\n"); } void HdmiCec_2Processor::process (const ReportPhysicalAddress &msg, const Header &header) { printHeader(header); LOGINFO("Command: ReportPhysicalAddress\n"); } void HdmiCec_2Processor::process (const DeviceVendorID &msg, const Header &header) { printHeader(header); LOGINFO("Command: DeviceVendorID VendorID : %s\n",msg.vendorId.toString().c_str()); } void HdmiCec_2Processor::process (const GiveDevicePowerStatus &msg, const Header &header) { printHeader(header); LOGINFO("Command: GiveDevicePowerStatus sending powerState :%d \n",powerState); try { conn.sendTo(header.from, MessageEncoder().encode(ReportPowerStatus(PowerStatus(powerState)))); } catch(...) { LOGWARN("Exception while sending ReportPowerStatus"); } } void HdmiCec_2Processor::process (const ReportPowerStatus &msg, const Header &header) { printHeader(header); if ((header.from == LogicalAddress(LogicalAddress::TV))) tvPowerState = msg.status; LOGINFO("Command: ReportPowerStatus TV Power Status from:%s status : %s \n",header.from.toString().c_str(),msg.status.toString().c_str()); } void HdmiCec_2Processor::process (const FeatureAbort &msg, const Header &header) { printHeader(header); LOGINFO("Command: FeatureAbort\n"); } void HdmiCec_2Processor::process (const Abort &msg, const Header &header) { printHeader(header); LOGINFO("Command: Abort\n"); } void HdmiCec_2Processor::process (const Polling &msg, const Header &header) { printHeader(header); LOGINFO("Command: Polling\n"); } //=========================================== HdmiCec_2 ========================================= HdmiCec_2::HdmiCec_2() : AbstractPlugin() { LOGWARN("Initlaizing CEC_2"); HdmiCec_2::_instance = this; InitializeIARM(); registerMethod(HDMICEC2_METHOD_SET_ENABLED, &HdmiCec_2::setEnabledWrapper, this); registerMethod(HDMICEC2_METHOD_GET_ENABLED, &HdmiCec_2::getEnabledWrapper, this); registerMethod(HDMICEC2_METHOD_OTP_SET_ENABLED, &HdmiCec_2::setOTPEnabledWrapper, this); registerMethod(HDMICEC2_METHOD_OTP_GET_ENABLED, &HdmiCec_2::getOTPEnabledWrapper, this); registerMethod(HDMICEC2_METHOD_SET_OSD_NAME, &HdmiCec_2::setOSDNameWrapper, this); registerMethod(HDMICEC2_METHOD_GET_OSD_NAME, &HdmiCec_2::getOSDNameWrapper, this); registerMethod(HDMICEC2_METHOD_SET_VENDOR_ID, &HdmiCec_2::setVendorIdWrapper, this); registerMethod(HDMICEC2_METHOD_GET_VENDOR_ID, &HdmiCec_2::getVendorIdWrapper, this); registerMethod(HDMICEC2_METHOD_PERFORM_OTP_ACTION, &HdmiCec_2::performOTPActionWrapper, this); logicalAddressDeviceType = "None"; logicalAddress = 0xFF; // load persistence setting loadSettings(); try { //TODO(MROLLINS) this is probably per process so we either need to be running in our own process or be carefull no other plugin is calling it device::Manager::Initialize(); device::VideoOutputPort vPort = device::Host::getInstance().getVideoOutputPort("HDMI0"); if (vPort.isDisplayConnected()) { vector<uint8_t> edidVec; vPort.getDisplay().getEDIDBytes(edidVec); //Set LG vendor id if connected with LG TV if(edidVec.at(8) == 0x1E && edidVec.at(9) == 0x6D) { isLGTvConnected = true; } LOGINFO("manufacturer byte from edid :%x: %x isLGTvConnected :%d",edidVec.at(8),edidVec.at(9),isLGTvConnected); } } catch(...) { LOGWARN("Exception in getting edid info .\r\n"); } // get power state: IARM_Bus_PWRMgr_GetPowerState_Param_t param; int err = IARM_Bus_Call(IARM_BUS_PWRMGR_NAME, IARM_BUS_PWRMGR_API_GetPowerState, (void *)&param, sizeof(param)); if(err == IARM_RESULT_SUCCESS) { powerState = (param.curState == IARM_BUS_PWRMGR_POWERSTATE_ON)?0:1 ; LOGINFO("Current state is IARM: (%d) powerState :%d \n",param.curState,powerState); } if (cecSettingEnabled) { try { CECEnable(); } catch(...) { LOGWARN("Exception while enabling CEC settings .\r\n"); } } } HdmiCec_2::~HdmiCec_2() { LOGINFO(); HdmiCec_2::_instance = nullptr; DeinitializeIARM(); } const void HdmiCec_2::InitializeIARM() { LOGINFO(); if (Utils::IARM::init()) { IARM_Result_t res; IARM_CHECK( IARM_Bus_RegisterEventHandler(IARM_BUS_CECMGR_NAME, IARM_BUS_CECMGR_EVENT_DAEMON_INITIALIZED,cecMgrEventHandler) ); IARM_CHECK( IARM_Bus_RegisterEventHandler(IARM_BUS_CECMGR_NAME, IARM_BUS_CECMGR_EVENT_STATUS_UPDATED,cecMgrEventHandler) ); IARM_CHECK( IARM_Bus_RegisterEventHandler(IARM_BUS_DSMGR_NAME,IARM_BUS_DSMGR_EVENT_HDMI_HOTPLUG, dsHdmiEventHandler) ); IARM_CHECK( IARM_Bus_RegisterEventHandler(IARM_BUS_PWRMGR_NAME,IARM_BUS_PWRMGR_EVENT_MODECHANGED, pwrMgrModeChangeEventHandler) ); } } void HdmiCec_2::DeinitializeIARM() { LOGINFO(); if (Utils::IARM::isConnected()) { IARM_Result_t res; IARM_CHECK( IARM_Bus_UnRegisterEventHandler(IARM_BUS_CECMGR_NAME, IARM_BUS_CECMGR_EVENT_DAEMON_INITIALIZED) ); IARM_CHECK( IARM_Bus_UnRegisterEventHandler(IARM_BUS_CECMGR_NAME, IARM_BUS_CECMGR_EVENT_STATUS_UPDATED) ); IARM_CHECK( IARM_Bus_UnRegisterEventHandler(IARM_BUS_DSMGR_NAME,IARM_BUS_DSMGR_EVENT_HDMI_HOTPLUG) ); IARM_CHECK( IARM_Bus_UnRegisterEventHandler(IARM_BUS_PWRMGR_NAME,IARM_BUS_PWRMGR_EVENT_MODECHANGED) ); } } void HdmiCec_2::cecMgrEventHandler(const char *owner, IARM_EventId_t eventId, void *data, size_t len) { LOGINFO(); if(!HdmiCec_2::_instance) return; if( !strcmp(owner, IARM_BUS_CECMGR_NAME)) { switch (eventId) { case IARM_BUS_CECMGR_EVENT_DAEMON_INITIALIZED: { HdmiCec_2::_instance->onCECDaemonInit(); } break; case IARM_BUS_CECMGR_EVENT_STATUS_UPDATED: { IARM_Bus_CECMgr_Status_Updated_Param_t *evtData = new IARM_Bus_CECMgr_Status_Updated_Param_t; if(evtData) { memcpy(evtData,data,sizeof(IARM_Bus_CECMgr_Status_Updated_Param_t)); HdmiCec_2::_instance->cecStatusUpdated(evtData); } } break; default: /*Do nothing*/ break; } } } void HdmiCec_2::dsHdmiEventHandler(const char *owner, IARM_EventId_t eventId, void *data, size_t len) { LOGINFO(); if(!HdmiCec_2::_instance) return; if (IARM_BUS_DSMGR_EVENT_HDMI_HOTPLUG == eventId) { IARM_Bus_DSMgr_EventData_t *eventData = (IARM_Bus_DSMgr_EventData_t *)data; int hdmi_hotplug_event = eventData->data.hdmi_hpd.event; LOGINFO("Received IARM_BUS_DSMGR_EVENT_HDMI_HOTPLUG event data:%d \r\n", hdmi_hotplug_event); HdmiCec_2::_instance->onHdmiHotPlug(hdmi_hotplug_event); } } void HdmiCec_2::pwrMgrModeChangeEventHandler(const char *owner, IARM_EventId_t eventId, void *data, size_t len) { LOGINFO(); if(!HdmiCec_2::_instance) return; if (strcmp(owner, IARM_BUS_PWRMGR_NAME) == 0) { if (eventId == IARM_BUS_PWRMGR_EVENT_MODECHANGED ) { IARM_Bus_PWRMgr_EventData_t *param = (IARM_Bus_PWRMgr_EventData_t *)data; LOGINFO("Event IARM_BUS_PWRMGR_EVENT_MODECHANGED: State Changed %d -- > %d\r", param->data.state.curState, param->data.state.newState); if(param->data.state.newState == IARM_BUS_PWRMGR_POWERSTATE_ON) { powerState = 0; _instance->performOTPAction(); } else powerState = 1; } } } void HdmiCec_2::onCECDaemonInit() { LOGINFO(); if(true == getEnabled()) { setEnabled(false); setEnabled(true); } else { /*Do nothing as CEC is not already enabled*/ } } void HdmiCec_2::cecStatusUpdated(void *evtStatus) { LOGINFO(); IARM_Bus_CECMgr_Status_Updated_Param_t *evtData = (IARM_Bus_CECMgr_Status_Updated_Param_t *)evtStatus; if(evtData) { try{ getPhysicalAddress(); unsigned int logicalAddr = evtData->logicalAddress; std::string logicalAddrDeviceType = DeviceType(LogicalAddress(evtData->logicalAddress).getType()).toString().c_str(); LOGINFO("cecLogicalAddressUpdated: logical address updated: %d , saved : %d ", logicalAddr, logicalAddress.toInt()); if (logicalAddr != logicalAddress.toInt() || logicalAddrDeviceType != logicalAddressDeviceType) { logicalAddress = logicalAddr; logicalAddressDeviceType = logicalAddrDeviceType; } } catch (const std::exception e) { LOGWARN("CEC exception caught from cecStatusUpdated"); } delete evtData; } return; } void HdmiCec_2::onHdmiHotPlug(int connectStatus) { LOGINFO(); if (HDMI_HOT_PLUG_EVENT_CONNECTED == connectStatus) { LOGINFO ("onHdmiHotPlug Status : %d ", connectStatus); getPhysicalAddress(); getLogicalAddress(); try { device::VideoOutputPort vPort = device::Host::getInstance().getVideoOutputPort("HDMI0"); if (vPort.isDisplayConnected()) { vector<uint8_t> edidVec; vPort.getDisplay().getEDIDBytes(edidVec); //Set LG vendor id if connected with LG TV if(edidVec.at(8) == 0x1E && edidVec.at(9) == 0x6D) { isLGTvConnected = true; } LOGINFO("manufacturer byte from edid :%x: %x isLGTvConnected :%d",edidVec.at(8),edidVec.at(9),isLGTvConnected); } } catch(...) { LOGWARN("Exception in getting edid info .\r\n"); } } return; } uint32_t HdmiCec_2::setEnabledWrapper(const JsonObject& parameters, JsonObject& response) { LOGINFO(); bool enabled = false; if (parameters.HasLabel("enabled")) { getBoolParameter("enabled", enabled); } else { returnResponse(false); } setEnabled(enabled); returnResponse(true); } uint32_t HdmiCec_2::getEnabledWrapper(const JsonObject& parameters, JsonObject& response) { response["enabled"] = getEnabled(); returnResponse(true); } uint32_t HdmiCec_2::setOTPEnabledWrapper(const JsonObject& parameters, JsonObject& response) { LOGINFO(); bool enabled = false; if (parameters.HasLabel("enabled")) { getBoolParameter("enabled", enabled); } else { returnResponse(false); } setOTPEnabled(enabled); returnResponse(true); } uint32_t HdmiCec_2::getOTPEnabledWrapper(const JsonObject& parameters, JsonObject& response) { response["enabled"] = getOTPEnabled(); returnResponse(true); } uint32_t HdmiCec_2::setOSDNameWrapper(const JsonObject& parameters, JsonObject& response) { LOGINFO(); bool enabled = false; if (parameters.HasLabel("name")) { std::string osd = parameters["name"].String(); LOGINFO("setOSDNameWrapper osdName: %s",osd.c_str()); osdName = osd.c_str(); persistOSDName(osd.c_str()); } else { returnResponse(false); } returnResponse(true); } uint32_t HdmiCec_2::getOSDNameWrapper(const JsonObject& parameters, JsonObject& response) { response["name"] = osdName.toString(); LOGINFO("getOSDNameWrapper osdName : %s \n",osdName.toString().c_str()); returnResponse(true); } uint32_t HdmiCec_2::setVendorIdWrapper(const JsonObject& parameters, JsonObject& response) { LOGINFO(); bool enabled = false; if (parameters.HasLabel("vendorid")) { std::string id = parameters["vendorid"].String(); unsigned int vendorID = 0x00; try { vendorID = stoi(id,NULL,16); } catch (...) { LOGWARN("Exception in setVendorIdWrapper set default value\n"); vendorID = 0x0019FB; } appVendorId = {(uint8_t)(vendorID >> 16 & 0xff),(uint8_t)(vendorID>> 8 & 0xff),(uint8_t) (vendorID & 0xff)}; LOGINFO("appVendorId : %s vendorID :%x \n",appVendorId.toString().c_str(), vendorID ); persistVendorId(vendorID); } else { returnResponse(false); } returnResponse(true); } uint32_t HdmiCec_2::getVendorIdWrapper(const JsonObject& parameters, JsonObject& response) { LOGINFO("getVendorIdWrapper appVendorId : %s \n",appVendorId.toString().c_str()); response["vendorid"] = appVendorId.toString() ; returnResponse(true); } uint32_t HdmiCec_2::performOTPActionWrapper(const JsonObject& parameters, JsonObject& response) { if(performOTPAction()) { returnResponse(true); } else { returnResponse(false); } } bool HdmiCec_2::loadSettings() { Core::File file; file = CEC_SETTING_ENABLED_FILE; if( file.Open()) { JsonObject parameters; parameters.IElement::FromFile(file); bool isConfigAdded = false; if( parameters.HasLabel(CEC_SETTING_ENABLED)) { getBoolParameter(CEC_SETTING_ENABLED, cecSettingEnabled); LOGINFO("CEC_SETTING_ENABLED present value:%d",cecSettingEnabled); } else { parameters[CEC_SETTING_ENABLED] = true; cecSettingEnabled = true; isConfigAdded = true; LOGINFO("CEC_SETTING_ENABLED not present set dafult true:\n "); } if( parameters.HasLabel(CEC_SETTING_OTP_ENABLED)) { getBoolParameter(CEC_SETTING_OTP_ENABLED, cecOTPSettingEnabled); LOGINFO("CEC_SETTING_OTP_ENABLED present value :%d",cecOTPSettingEnabled); } else { parameters[CEC_SETTING_OTP_ENABLED] = true; cecOTPSettingEnabled = true; isConfigAdded = true; LOGINFO("CEC_SETTING_OTP_ENABLED not present set dafult true:\n "); } if( parameters.HasLabel(CEC_SETTING_OSD_NAME)) { std::string osd_name; getStringParameter(CEC_SETTING_OSD_NAME, osd_name); osdName = osd_name.c_str(); LOGINFO("CEC_SETTING_OTP_ENABLED present osd_name :%s",osdName.toString().c_str()); } else { parameters[CEC_SETTING_OSD_NAME] = osdName.toString(); LOGINFO("CEC_SETTING_OSD_NMAE not present set dafult value :%s\n ",osdName.toString().c_str()); isConfigAdded = true; } unsigned int vendorId = 0x0019FB; if( parameters.HasLabel(CEC_SETTING_VENDOR_ID)) { getNumberParameter(CEC_SETTING_VENDOR_ID, vendorId); LOGINFO("CEC_SETTING_VENDOR_ID present :%x ",vendorId); } else { LOGINFO("CEC_SETTING_OSD_NMAE not present set dafult value :\n "); parameters[CEC_SETTING_VENDOR_ID] = vendorId; isConfigAdded = true; } appVendorId = {(uint8_t)(vendorId >> 16 & 0xff),(uint8_t)(vendorId >> 8 & 0xff),(uint8_t) (vendorId & 0xff)}; LOGINFO("appVendorId : %s vendorId :%x \n",appVendorId.toString().c_str(), vendorId ); if(isConfigAdded) { LOGINFO("isConfigAdded true so update file:\n "); file.Destroy(); file.Create(); parameters.IElement::ToFile(file); } file.Close(); } else { LOGINFO("CEC_SETTING_ENABLED_FILE file not present create with default settings "); file.Open(false); if (!file.IsOpen()) file.Create(); JsonObject parameters; parameters[CEC_SETTING_ENABLED] = true; parameters[CEC_SETTING_OTP_ENABLED] = true; parameters[CEC_SETTING_OSD_NAME] = osdName.toString(); cecSettingEnabled = true; cecOTPSettingEnabled = true; parameters.IElement::ToFile(file); file.Close(); } return cecSettingEnabled; } void HdmiCec_2::persistSettings(bool enableStatus) { Core::File file; file = CEC_SETTING_ENABLED_FILE; file.Open(false); if (!file.IsOpen()) file.Create(); JsonObject cecSetting; cecSetting.IElement::FromFile(file); file.Destroy(); file.Create(); cecSetting[CEC_SETTING_ENABLED] = enableStatus; cecSetting.IElement::ToFile(file); file.Close(); return; } void HdmiCec_2::persistOTPSettings(bool enableStatus) { Core::File file; file = CEC_SETTING_ENABLED_FILE; file.Open(false); if (!file.IsOpen()) file.Create(); JsonObject cecSetting; cecSetting.IElement::FromFile(file); file.Destroy(); file.Create(); cecSetting[CEC_SETTING_OTP_ENABLED] = enableStatus; cecSetting.IElement::ToFile(file); file.Close(); return; } void HdmiCec_2::persistOSDName(const char *name) { Core::File file; file = CEC_SETTING_ENABLED_FILE; file.Open(false); if (!file.IsOpen()) file.Create(); JsonObject cecSetting; cecSetting.IElement::FromFile(file); file.Destroy(); file.Create(); cecSetting[CEC_SETTING_OSD_NAME] = name; cecSetting.IElement::ToFile(file); file.Close(); return; } void HdmiCec_2::persistVendorId(unsigned int vendorId) { Core::File file; file = CEC_SETTING_ENABLED_FILE; file.Open(false); if (!file.IsOpen()) file.Create(); JsonObject cecSetting; cecSetting.IElement::FromFile(file); file.Destroy(); file.Create(); cecSetting[CEC_SETTING_VENDOR_ID] = vendorId; cecSetting.IElement::ToFile(file); file.Close(); return; } void HdmiCec_2::setEnabled(bool enabled) { LOGINFO("Entered setEnabled "); if (cecSettingEnabled != enabled) { persistSettings(enabled); cecSettingEnabled = enabled; } if(true == enabled) { CECEnable(); } else { CECDisable(); } return; } void HdmiCec_2::setOTPEnabled(bool enabled) { if (cecOTPSettingEnabled != enabled) { LOGINFO("persist setOTPEnabled "); persistOTPSettings(enabled); cecOTPSettingEnabled = enabled; } return; } void HdmiCec_2::CECEnable(void) { LOGINFO("Entered CECEnable"); if (cecEnableStatus) { LOGWARN("CEC Already Enabled"); return; } if(0 == libcecInitStatus) { try { LibCCEC::getInstance().init(); } catch (const std::exception e) { LOGWARN("CEC exception caught from LibCCEC::getInstance().init()"); } } libcecInitStatus++; //Acquire CEC Addresses getPhysicalAddress(); getLogicalAddress(); smConnection = new Connection(logicalAddress.toInt(),false,"ServiceManager::Connection::"); smConnection->open(); msgProcessor = new HdmiCec_2Processor(*smConnection); msgFrameListener = new HdmiCec_2FrameListener(*msgProcessor); smConnection->addFrameListener(msgFrameListener); cecEnableStatus = true; if(smConnection) { LOGINFO("Command: sending GiveDevicePowerStatus \r\n"); smConnection->sendTo(LogicalAddress(LogicalAddress::TV), MessageEncoder().encode(GiveDevicePowerStatus()), 5000); LOGINFO("Command: sending request active Source\r\n"); smConnection->sendTo(LogicalAddress(LogicalAddress::BROADCAST), MessageEncoder().encode(RequestActiveSource()), 5000); isDeviceActiveSource = true; } return; } void HdmiCec_2::CECDisable(void) { LOGINFO("Entered CECDisable "); if(!cecEnableStatus) { LOGWARN("CEC Already Disabled "); return; } if (smConnection != NULL) { smConnection->close(); delete smConnection; smConnection = NULL; } cecEnableStatus = false; if(1 == libcecInitStatus) { try { LibCCEC::getInstance().term(); } catch (const std::exception e) { LOGWARN("CEC exception caught from LibCCEC::getInstance().term() "); } } libcecInitStatus--; return; } void HdmiCec_2::getPhysicalAddress() { LOGINFO("Entered getPhysicalAddress "); uint32_t physAddress = 0x0F0F0F0F; try { LibCCEC::getInstance().getPhysicalAddress(&physAddress); physical_addr = {(uint8_t)((physAddress >> 24) & 0xFF),(uint8_t)((physAddress >> 16) & 0xFF),(uint8_t) ((physAddress >> 8) & 0xFF),(uint8_t)((physAddress) & 0xFF)}; LOGINFO("getPhysicalAddress: physicalAddress: %s ", physical_addr.toString().c_str()); } catch (const std::exception e) { LOGWARN("exception caught from getPhysicalAddress"); } return; } void HdmiCec_2::getLogicalAddress() { LOGINFO("Entered getLogicalAddress "); try{ LogicalAddress addr = LibCCEC::getInstance().getLogicalAddress(DEV_TYPE_TUNER); std::string logicalAddrDeviceType = DeviceType(LogicalAddress(addr).getType()).toString().c_str(); LOGINFO("logical address obtained is %d , saved logical address is %d ", addr.toInt(), logicalAddress.toInt()); if (logicalAddress.toInt() != addr.toInt() || logicalAddressDeviceType != logicalAddrDeviceType) { logicalAddress = addr; logicalAddressDeviceType = logicalAddrDeviceType; } } catch (const std::exception e) { LOGWARN("CEC exception caught from getLogicalAddress "); } return; } bool HdmiCec_2::getEnabled() { if(true == cecEnableStatus) return true; else return false; LOGINFO("getEnabled :%d ",cecEnableStatus); } bool HdmiCec_2::getOTPEnabled() { if(true == cecOTPSettingEnabled) return true; else return false; LOGINFO("getOTPEnabled :%d ",cecOTPSettingEnabled); } bool HdmiCec_2::performOTPAction() { LOGINFO("performOTPAction "); bool ret = false; if((true == cecEnableStatus) && (cecOTPSettingEnabled == true)) { try { if(tvPowerState.toInt()) { LOGINFO("Command: sending ImageViewOn TV \r\n"); smConnection->sendTo(LogicalAddress(LogicalAddress::TV), MessageEncoder().encode(ImageViewOn()), 5000); usleep(10000); } if(!isDeviceActiveSource) { LOGINFO("Command: sending ActiveSource physical_addr :%s \r\n",physical_addr.toString().c_str()); smConnection->sendTo(LogicalAddress(LogicalAddress::BROADCAST), MessageEncoder().encode(ActiveSource(physical_addr)), 5000); usleep(10000); } LOGINFO("Command: sending GiveDevicePowerStatus \r\n"); smConnection->sendTo(LogicalAddress(LogicalAddress::TV), MessageEncoder().encode(GiveDevicePowerStatus()), 5000); ret = true; } catch(...) { LOGWARN("Exception while processing performOTPAction"); } } else LOGWARN("cecEnableStatus=false"); return ret; } } // namespace Plugin } // namespace WPEFramework
[ "vijay.selva@hotmail.com" ]
vijay.selva@hotmail.com
1e41ae5c243f4f4360ce743127011c335a278f57
cacf8948792373c68cd550c364e16bf743e6062c
/CC++/Demo6.cpp
18dd43d953655a32cf5d95357ddc6f70987d57b5
[]
no_license
himanshuadvani/Practice
763c938e9104cadfacc75d323e8bfff244dc2976
85d15413908824dfa185559e990e0eeb50fdb3b4
refs/heads/master
2020-05-07T18:52:37.193898
2019-04-11T12:26:49
2019-04-11T12:26:49
180,787,535
0
0
null
null
null
null
UTF-8
C++
false
false
649
cpp
#include<iostream> using namespace std; int main() { int i=0,j=0,count=1,row=0; int temp=row; printf("Enter size of matrix: "); scanf("%d",&row); int arr[row][row*2]={0}; for(i=0;i<row;i++) { printf("\n"); for(j=0;j<temp;j++) { arr[i][j]=count; count++; } temp--; } /* for(i=row-1;i>=0;i--) { j=0; temp=0; while(j<2*row) { if(arr[i][j]==0) { break; } } printf("j: %d",j); while(temp<=j) { arr[i][j]=count; count++; temp++; } } */ for(int i=0;i<row;i++) { for(j=0;j<2*row;j++) { printf("%d\t",arr[i][j]); } printf("\n"); } return 0; }
[ "adwani708@gmail.com" ]
adwani708@gmail.com
ed164d343a0152c2e072a46b9d781d47d531f90b
08c6cea925d33f21f6b3ed67d832968d455eb2e0
/src/FindBoardLocs.h
c289eaa8b1262775780a15f162f2978afc94845f
[ "BSD-3-Clause" ]
permissive
JohnTHenkel/CatanCV
c490518a6ba765b112ccef1aba26e39bf7a89afe
a148439583b16290cfec755e1f7ba886cbbc9d1d
refs/heads/master
2020-04-07T03:21:41.610466
2018-12-28T20:29:24
2018-12-28T20:29:24
158,013,135
0
0
null
null
null
null
UTF-8
C++
false
false
281
h
#include <iostream> #include <opencv2/opencv.hpp> #include <vector> #include <opencv2/xfeatures2d/nonfree.hpp> #include "opencv2/xfeatures2d.hpp" #include "Helpers.h" #include "Constants.h" using namespace std; using namespace cv; vector<Point2f> findBoardLocs(const Mat& image);
[ "rmcatee15@gmail.com" ]
rmcatee15@gmail.com
5dfde401e235d33b26d9e3337aa703b6876f6be6
88295378af9f8c651562d07d7746d8581989a640
/mp2/StickerSheet.cpp
01ef271731fbe7340509926b29cfba9df5cb4de8
[]
no_license
xinyig97/datastructure
ec564394a5e3091cff5bde6193aa854e287bd74c
d39c17de0d9cc63711f6871849d2ee625af35dd0
refs/heads/master
2020-04-05T05:08:42.748071
2018-11-07T17:22:34
2018-11-07T17:22:34
156,582,700
1
0
null
null
null
null
UTF-8
C++
false
false
6,098
cpp
#include "StickerSheet.h" #include "Image.h" #include<iostream> #include<string> //construtor of the StickSheet StickerSheet::StickerSheet(const Image&picture, unsigned max){ max_ = max; base_ = picture; Sticker_ = new sticker*[max]; //initialized new array for stickers, and make them NULL for(unsigned i=0; i<max_; i++){ Sticker_[i] = NULL; } } StickerSheet::~StickerSheet(){ //if not deleted, go through each one pointer if(Sticker_ != NULL){ for(unsigned i=0; i<max_; i++){ //if the pointer is not deleted, delete and make it to NULL if(Sticker_[i]!=NULL){ delete Sticker_[i]; Sticker_[i] =NULL; } } //delete the double array pointer and set to NULL delete[] Sticker_; Sticker_ = NULL; } } StickerSheet::StickerSheet(const StickerSheet & other){ //copy max_ and base_ max_ = other.max_; base_ = other.base_; //deep copy of the array Sticker_ = new sticker*[max_]; for(unsigned i=0; i<max_ ; i++){ if(other.Sticker_[i]!=NULL){ Sticker_[i] = new sticker(((other.Sticker_)[i])->addr,((other.Sticker_)[i])->x_co,((other.Sticker_)[i])->y_co); } else{ Sticker_[i] = NULL; } } } //private helper function of delete that being called by the assignment override //basically the same as destrutcor of StickerSheet class. void StickerSheet::delete_(){ if(Sticker_ != NULL){ for(unsigned i=0; i<max_; i++){ if(Sticker_[i]!=NULL){ delete Sticker_[i]; Sticker_[i]=NULL; } } delete[] Sticker_; Sticker_ =NULL; } return; } //privae helper function of copy taht being called by the assignment override //basically the same as the copy constuctor of StickerSheet class void StickerSheet::copy_(const StickerSheet& other){ max_ = other.max_; base_ = other.base_; Sticker_ = new sticker*[max_]; for(unsigned i=0; i<max_ ; i++){ if(other.Sticker_[i]!=NULL){ Sticker_[i] = new sticker(((other.Sticker_)[i])->addr,((other.Sticker_)[i])->x_co,((other.Sticker_)[i])->y_co); } else{ Sticker_[i] = NULL; } } return; } const StickerSheet& StickerSheet::operator=(const StickerSheet &other){ //override assignment operator delete_(); copy_(other); return *this; } void StickerSheet::changeMaxStickers(unsigned max){ //if the new max is smaller than the previous max, free the extra allocated memeory first if(max < max_){ for(unsigned i=max; i<max_; i++){ if(Sticker_[i]!=NULL){ delete Sticker_[i]; } } //create a new pointer array of the length of the new max sticker** temp = new sticker*[max]; for(unsigned i=0; i<max; i++){ //if the previous pointer is not NULL, copy to the corresponding position in the new array if(Sticker_[i]!=NULL){ temp[i] = Sticker_[i]; } //otherwise, initialzied with NULL else { temp[i] = NULL; } } //update the max_ max_ = max; delete[] Sticker_; Sticker_ = temp; } //if the new max is bigger than previous max_ else { //create a new pointer array sticker** temp = new sticker*[max]; for(unsigned i=0; i<max_; i++){ //copy the old array into the new array of corresponding positions if(Sticker_[i]!=NULL){ temp[i] = Sticker_[i]; } else{ temp[i]=NULL; } } //for extra space in new array, initialize with NULL. for(unsigned i = max_; i < max; i++) { temp[i]=NULL; } max_ = max; delete[] Sticker_; Sticker_ = temp; } } int StickerSheet::addSticker(Image &stickers, unsigned x, unsigned y){ //if there is extra space for a new sticker, add it and return the index for(unsigned i=0; i<max_; i++){ if(Sticker_[i] == NULL){ Sticker_[i] = new sticker(&stickers, x, y); return i; } } //otherwise if the array is already FULL, return -1 return -1; } bool StickerSheet::translate(unsigned index, unsigned x, unsigned y){ //if the index does not have a valid pointer, return false. if(Sticker_[index] == NULL || (Sticker_[index])->addr == NULL){ return 0; } //otherwise, change the location of copying (Sticker_[index])->x_co =x; (Sticker_[index])->y_co =y; return 1; } void StickerSheet::removeSticker(unsigned index){ //if the index has a pointer, delete it if(Sticker_[index]!=NULL){ delete Sticker_[index]; Sticker_[index]=NULL; return; } //otherwise, do nothing return; } Image* StickerSheet::getSticker(const unsigned index ){ //if the index has a sticker, return the addr of the sticker if(Sticker_[index]!=NULL){ return Sticker_[index]->addr; } //otherwise return NULL return NULL; } const Image StickerSheet::render(){ //figure out what is the final size of the pic unsigned int w = base_.width(); unsigned int h = base_.height(); if(Sticker_ !=NULL){ for(unsigned int i=0; i<max_;i++){ if(Sticker_[i]!=NULL && Sticker_[i]->addr!=NULL){ unsigned temp_w = Sticker_[i]->x_co+(Sticker_[i]->addr)->width(); unsigned temp_h = Sticker_[i]->y_co+(Sticker_[i]->addr)->height(); if(temp_w>w){ w = temp_w; } if(temp_h>h){ h = temp_h; } } } } //resize the base_ pic base_.resize(w,h); //render stickers for(unsigned i=0; i<max_; i++){ //if there is a sticker if(Sticker_[i]!=NULL&& Sticker_[i]->addr !=NULL){ //get the width and height of the sticker unsigned width = (Sticker_[i]->addr)->width(); unsigned height = ((Sticker_[i])->addr)->height(); for(unsigned y= 0; y<height; y++){ for(unsigned x= 0; x<width; x++){ //change the corresponding pixel of the base pic to print out the sticker HSLAPixel &cur = base_.getPixel(x + Sticker_[i]->x_co, y + Sticker_[i]->y_co); HSLAPixel &tem = (Sticker_[i]->addr)->getPixel(x,y); if(tem.a !=0){ cur.h = tem.h; cur.l = tem.l; cur.a = tem.a; cur.s = tem.s; } } } } } return base_; }
[ "xinyig2@illinois.edu" ]
xinyig2@illinois.edu
35c813ca9ac3eef713a2817dca210e0884d9616b
c5a80d50ab2aac0906881d4ef48f2599eb806055
/src/class_firmware/phoenix_drive.h
2f5e154406dc6420785f199baeda2d0a9d9ad73e
[ "MIT" ]
permissive
luziato/soccer-18-19
d00857858320cfcfdbfff399393e4da3a36dcfbb
7fcae4f192ce7fecdb940b47ae37e5c40b96d8ee
refs/heads/master
2020-03-30T03:47:24.867683
2019-04-13T11:34:32
2019-04-13T11:34:32
150,708,090
1
0
null
null
null
null
UTF-8
C++
false
false
500
h
//mine #include "Arduino.h" #include "phoenix_joint.h" typedef struct { double x_comp; double y_comp; uint8_t pins[3]; } JointParams; typedef struct { int16_t speed; uint8_t mode; } JointControl; class HolonomicDrive { Joint* joints; JointParams* params; JointControl* control; public: HolonomicDrive(); void init(Joint* joints, JointParams* params, JointControl* control); void move(double x, double y, double theta); void handle(); };
[ "arya01@hotmail.it" ]
arya01@hotmail.it
49688554ce555daff2678668b444178b4e7a4800
37565378c534132eee19426988ecf427c6e3f397
/tools/qt/dummyQmlProject/main.cpp
1ffdbc219bc4a70db31334f6762298157fa3b725
[]
no_license
TripleWhy/docker-qt-android
2b9936ce9abab13d9c2a098f7e93afcff2e742cd
7509f184b4307b007089e2b0a32a0060a3e94f9d
refs/heads/master
2023-03-25T22:00:16.859990
2021-03-26T12:26:03
2021-03-26T12:26:03
334,682,227
0
0
null
null
null
null
UTF-8
C++
false
false
586
cpp
#include <QGuiApplication> #include <QQmlApplicationEngine> int main(int argc, char *argv[]) { #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); #endif QGuiApplication app(argc, argv); QQmlApplicationEngine engine; const QUrl url(QStringLiteral("qrc:/main.qml")); QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) { if (!obj && url == objUrl) QCoreApplication::exit(-1); }, Qt::QueuedConnection); engine.load(url); return app.exec(); }
[ "TripleWhy@users.noreply.github.com" ]
TripleWhy@users.noreply.github.com
de15e442cb3339a4cb1133037969d6e02043fe69
76b61368799ca40a15ba24dbe8204d65ba101d0b
/src/testing/print_pmt_traces/pmt_traces.cpp
045c0a5479954e3eb6d9da99076b66e1159b0af4
[]
no_license
gasperkm/auger-analysis
68f3b875b4e46dd8f226496abb56ccd04c5b0ab5
c7df46e87cc836eebadfcdcccd1914c8b15d0d70
refs/heads/master
2021-06-19T16:04:56.161564
2019-09-27T07:09:17
2019-09-27T07:09:17
112,312,601
0
0
null
null
null
null
UTF-8
C++
false
false
71,144
cpp
#define _STANDALONE_ 1 #include "workstation.h" #include <time.h> #include <cstdlib> #include <iomanip> #include <algorithm> #include "separate_functions.h" #include "mva_methods.h" #include "mva_result_read.h" #include "root_style.h" #include "primary_type.h" #if OFFVER == 0 #include "OfflineIncludeOld.h" #elif OFFVER == 1 #include "OfflineIncludeNew.h" #endif using namespace std; class AdstFile { private: string *stemp; int *itemp; double *dtemp; RecEventFile *fFile; RecEvent *fRecEvent; DetectorGeometry *fDetGeo; SdRecShower *sdrecshw; vector<SdRecStation> stationVector; // Temporary variables and holders for number of stations and events int nrstations, nevents; bool goodrec; // Limits for risetime calculations double limitTankDistance[2]; double minSignal; bool includeSaturated; int minPoints; // Vectors and variables needed for calculation of risetime vector<double> tempVect; vector<float> time; vector<float> vemtrace; vector<float> yvem; vector<float> yintvem; vector<float> yvalue; vector<float> tempRise; int start_bin, stop_bin; double maxval; double xp, yp; double risemean, riseerr; double *byrange; double *bzrange; TFormula *fRTWeights; double eventThetaRec; double secZenith; double alpha; double gamma; double g; double zeta; RootStyle *mystyle; const int c_SignalLine = TColor::GetColor("#0000ee"); const int c_SignalFill = TColor::GetColor("#7d99d1"); const int c_BackgroundLine = TColor::GetColor("#ff0000"); const int c_BackgroundFill = TColor::GetColor("#ff0000"); const int c_DataLine = TColor::GetColor("#000000"); const int c_DataFill = TColor::GetColor("#808080"); const int c_DataNormLine = TColor::GetColor("#00bb00"); const int c_DataNormFill = TColor::GetColor("#00bb00"); const int c_ResidLine = TColor::GetColor("#000000"); const int c_ResidFill = TColor::GetColor("#808080"); public: AdstFile(); virtual ~AdstFile(); void ReadAdstFile(string inname, vector<double> *sdidVect, vector<bool> *HGsat, vector<double> *distVect, vector<double> *riseVect, vector<double> *energy, vector<double> *zenith, vector<double> *shwsize, vector<int> *eventVect, int *allcount, int *allevts, int *nrrun); void PlotCurrentVemTrace(int eventNr, int stationID, int pmtID, double max); // void PlotStationVemTrace(int eventNr, int stationID, double risetime); }; AdstFile::AdstFile() { fRecEvent = new RecEvent(); fDetGeo = new DetectorGeometry(); sdrecshw = new SdRecShower(); stemp = new string[3]; itemp = new int[4]; dtemp = new double[3]; limitTankDistance[0] = 300.; limitTankDistance[1] = 1400.; minSignal = 5.0; includeSaturated = false; minPoints = 3; byrange = new double[2]; bzrange = new double[2]; fRTWeights = new TFormula("RiseTimeWeights", "(80.0+(5.071e-7+6.48e-4*y-3.051e-4*y*y)*x*x)/z-16.46*y+36.16"); byrange[0] = 1.e+40; byrange[1] = -1.e+40; bzrange[0] = 1.e+40; bzrange[1] = -1.e+40; } AdstFile::~AdstFile() { delete fRTWeights; delete[] byrange; delete[] bzrange; delete[] dtemp; delete[] itemp; delete[] stemp; delete sdrecshw; delete fDetGeo; delete fRecEvent; } /*double AdstFile::GetDistanceLimit(int type) { return limitTankDistance[type]; }*/ void AdstFile::PlotCurrentVemTrace(int eventNr, int stationID, int pmtID, double max) { mystyle = new RootStyle(); mystyle->SetBaseStyle(); TCanvas *c1 = new TCanvas("c1", "", 1200, 900); TGraph *grVem = new TGraph(); TGraph *grIntVemNorm = new TGraph(); TGraph *grIntVem = new TGraph(); TH1F *histVem = new TH1F("histVem", "", yvem.size()-1, 0, time[yvem.size()-1]-time[0]); TH1F *histIntVemNorm = new TH1F("histIntVemNorm", "", yintvem.size()-1, 0, time[yintvem.size()-1]-time[0]); TH1F *histIntVem = new TH1F("histIntVem", "", yintvem.size()-1, 0, time[yintvem.size()-1]-time[0]); dtemp[2] = 0; for(int i = 0; i < yvem.size(); i++) { grVem->SetPoint(i, time[i]-time[0], yvem[i]); if(yvem[i] < 0) histVem->SetBinContent(i, 0); else histVem->SetBinContent(i, yvem[i]); if(yvem[i] > dtemp[2]) dtemp[2] = yvem[i]; } for(int i = 0; i < yintvem.size(); i++) { grIntVemNorm->SetPoint(i, time[i]-time[0], (yintvem[i]*dtemp[2])/max); grIntVem->SetPoint(i, time[i]-time[0], yintvem[i]/max); if(yintvem[i] < 0) { histIntVemNorm->SetBinContent(i, 0); histIntVem->SetBinContent(i, 0); } else { histIntVemNorm->SetBinContent(i, (yintvem[i]*dtemp[2])/max); histIntVem->SetBinContent(i, yintvem[i]/max); } } stemp[0] = "mkdir -p ./plots"; system(stemp[0].c_str()); mystyle->SetSinglePlot(0, -1, c1); // Create the PMT signal vs. integrated PMT signal for whole range mystyle->SetHistColor(histVem, 2); histVem->GetXaxis()->SetRangeUser(0, time[yvem.size()-1]-time[0]); histVem->GetYaxis()->SetRangeUser(0, dtemp[2]*1.2); histVem->GetYaxis()->SetTitleOffset(mystyle->GetSingleYoffset(c1)); histVem->GetXaxis()->SetTitleOffset(mystyle->GetSingleXoffset(c1)); mystyle->SetAxisTitles((TH1*)histVem, "Time (ns)", "PMT signal (VEM)"); histVem->Draw(); /* mystyle->SetGraphColor(grVem, 0); grVem->SetMarkerSize(0.6); grVem->GetXaxis()->SetRangeUser(0, time[yvem.size()-1]-time[0]); grVem->GetYaxis()->SetRangeUser(0, dtemp[2]*1.2); grVem->Draw("P;SAME");*/ mystyle->SetHistColor(histIntVemNorm, 1); histIntVemNorm->SetFillColorAlpha(c_SignalFill, 0.5); histIntVemNorm->GetXaxis()->SetRangeUser(0, time[yintvem.size()-1]-time[0]); histIntVemNorm->GetYaxis()->SetRangeUser(0, dtemp[2]*1.2); histIntVemNorm->GetYaxis()->SetTitleOffset(mystyle->GetSingleYoffset(c1)); histIntVemNorm->GetXaxis()->SetTitleOffset(mystyle->GetSingleXoffset(c1)); mystyle->SetAxisTitles((TH1*)histIntVemNorm, "Time (ns)", "PMT signal (VEM)"); histIntVemNorm->Draw("SAME"); /* mystyle->SetGraphColor(grIntVemNorm, 0); grIntVemNorm->SetMarkerSize(0.6); grIntVemNorm->GetXaxis()->SetRangeUser(0, time[yintvem.size()-1]-time[0]); grIntVemNorm->GetYaxis()->SetRangeUser(0, dtemp[2]*1.2); grIntVemNorm->Draw("P;SAME");*/ c1->Update(); TLine *line = new TLine(); line->SetLineWidth(2); line->SetLineStyle(7); line->SetLineColor(2); line->DrawLine(tempRise[0]-time[0], gPad->GetUymin(), tempRise[0]-time[0], gPad->GetUymax()); line->DrawLine(tempRise[1]-time[0], gPad->GetUymin(), tempRise[1]-time[0], gPad->GetUymax()); TLatex *risetext = new TLatex(); risetext->SetTextAlign(31); stemp[0] = "t_{i} = " + ToString(tempRise[1]-tempRise[0], 2) + " ns"; risetext->DrawLatex(gPad->GetUxmax()-(0.03*(gPad->GetUxmax()-gPad->GetUxmin())), gPad->GetUymax()-(0.065*(gPad->GetUymax()-gPad->GetUymin())), stemp[0].c_str()); stemp[0] = "./plots/current_vem_trace_event-" + ToString(eventNr) + "_pmt-" + ToString(pmtID) + "_station-" + ToString(stationID) + ".pdf"; c1->SaveAs(stemp[0].c_str()); // Create integrated PMT signal close to risetime counts mystyle->SetSinglePlot(0, -1, c1); mystyle->SetHistColor(histIntVem, 1); histIntVem->SetFillColorAlpha(c_SignalFill, 0.5); histIntVem->GetXaxis()->SetRangeUser(tempRise[0]-time[0]-100., tempRise[1]-time[0]+100.); histIntVem->GetYaxis()->SetRangeUser(0, 0.7); histIntVem->GetYaxis()->SetTitleOffset(mystyle->GetSingleYoffset(c1)); histIntVem->GetXaxis()->SetTitleOffset(mystyle->GetSingleXoffset(c1)); mystyle->SetAxisTitles((TH1*)histIntVem, "Time (ns)", "Integrated PMT signal (normalized)"); histIntVem->Draw(); mystyle->SetGraphColor(grIntVem, 0); grIntVem->GetXaxis()->SetRangeUser(tempRise[0]-time[0]-100., tempRise[1]-time[0]+100.); grIntVem->GetYaxis()->SetRangeUser(0, 0.7); grIntVem->GetYaxis()->SetTitleOffset(mystyle->GetSingleYoffset(c1)); grIntVem->GetXaxis()->SetTitleOffset(mystyle->GetSingleXoffset(c1)); mystyle->SetAxisTitles(grIntVem, "Time (ns)", "Integrated PMT signal (normalized)"); grIntVem->Draw("L;SAME"); c1->Update(); line->DrawLine(tempRise[0]-time[0], gPad->GetUymin(), tempRise[0]-time[0], tempRise[2]); line->DrawLine(tempRise[1]-time[0], gPad->GetUymin(), tempRise[1]-time[0], tempRise[3]); TMarker *mark = new TMarker(); mark->SetMarkerSize(1); mark->SetMarkerColor(2); mark->SetMarkerStyle(20); mark->DrawMarker(tempRise[0]-time[0], tempRise[2]); mark->DrawMarker(tempRise[1]-time[0], tempRise[3]); stemp[0] = "t_{i} = " + ToString(tempRise[1]-tempRise[0], 2) + " ns"; risetext->DrawLatex(gPad->GetUxmax()-(0.03*(gPad->GetUxmax()-gPad->GetUxmin())), gPad->GetUymax()-(0.065*(gPad->GetUymax()-gPad->GetUymin())), stemp[0].c_str()); stemp[0] = "./plots/current_vem_tracezoom_event-" + ToString(eventNr) + "_pmt-" + ToString(pmtID) + "_station-" + ToString(stationID) + ".pdf"; c1->SaveAs(stemp[0].c_str()); delete risetext; delete line; delete mark; delete histVem; delete histIntVemNorm; delete histIntVem; delete grVem; delete grIntVemNorm; delete grIntVem; delete c1; delete mystyle; } /*void AdstFile::PlotStationVemTrace(int eventNr, int stationID, double risetime) { }*/ void AdstFile::ReadAdstFile(string inname, vector<double> *sdidVect, vector<bool> *HGsat, vector<double> *distVect, vector<double> *riseVect, vector<double> *energy, vector<double> *zenith, vector<double> *shwsize, vector<int> *eventVect, int *allcount, int *allevts, int *nrrun) { cout << endl << "Opening file: " << inname << " -------------------------------------------------------" << endl; cerr << endl << "Opening file: " << inname << " -------------------------------------------------------" << endl; // Open and prepare the ADST files for reading fFile = new RecEventFile(inname.c_str(), RecEventFile::eRead); nevents = fFile->GetNEvents(); cout << "Number of events: " << nevents << endl; fFile->SetBuffers(&fRecEvent); fFile->ReadDetectorGeometry(*fDetGeo); for(int j = 0; j < *nrrun; j++) { fFile->ReadEvent(j); cout << "New event (" << j+1 << ", ID = " << fRecEvent->GetEventId() << ", Time = [" << fRecEvent->GetYYMMDD() << "," << fRecEvent->GetHHMMSS() << "], E = " << TMath::Log10(fRecEvent->GetSDEvent().GetSdRecShower().GetEnergy()) << ", sec(theta) = " <<SecTheta(fRecEvent->GetSDEvent().GetSdRecShower().GetZenith(),false) << ") -------" << endl; goodrec = true; // Prepare SD station events ------------------------------------------- *sdrecshw = fRecEvent->GetSDEvent().GetSdRecShower(); // Check if there are triggered SD stations if(!(fRecEvent->GetSDEvent().HasTriggeredStations())) goodrec = false; // Check if there are any SD stations in the event if(!(fRecEvent->GetSDEvent().HasStations())) goodrec = false; // Check if SD stations have a VEM trace if(!(fRecEvent->GetSDEvent().HasVEMTraces())) goodrec = false; if(goodrec) { dtemp[0] = 0; itemp[0] = 0; // Loop over all triggered SD stations stationVector = fRecEvent->GetSDEvent().GetStationVector(); itemp[3] = 0; tempVect.clear(); for(int i = 0; i < stationVector.size(); i++) { // Only use stations that are valid candidates if(stationVector[i].IsCandidate()) { cout << "New station (" << stationVector[i].GetId() << ")" << endl; // DEBUG start_bin = stationVector[i].GetSignalStartSlot() - 4; stop_bin = stationVector[i].GetSignalEndSlot(); if( (start_bin >= stop_bin) || (start_bin < 0) || (start_bin > 5000) ) start_bin = 0; dtemp[1] = 0; itemp[1] = 0; // Check all PMTs for(int iPMT = 1; iPMT <= 3; iPMT++) { time.clear(); yvem.clear(); yintvem.clear(); yvalue.clear(); vemtrace.clear(); yp = 0; maxval = -1.e40; vemtrace = stationVector[i].GetVEMTrace(iPMT); //cout << "PMT " << iPMT << ": Number of points in the VEM trace: " << vemtrace.size() << " --------------------------------------------------------" << endl; // DEBUG // Continue if there is a VEM trace if(vemtrace.size() > 0) { itemp[0]++; itemp[1]++; dtemp[2] = 0; // Prepare the time vector (each point is multiplied by 25 to get nanoseconds) cout << "VEM trace printout + integrated VEM trace for PMT " << iPMT << " and station ID " << stationVector[i].GetId() << endl; cout << "time\tVEM trace\tIntegrated VEM trace" << endl; for(int iVEM = 0; iVEM < vemtrace.size(); iVEM++) { if( (iVEM >= start_bin) && (iVEM <= stop_bin) ) { time.push_back((float)iVEM*25.); yp += vemtrace[iVEM]; if(yp > maxval) maxval = yp; yvem.push_back(vemtrace[iVEM]); yintvem.push_back(yp); yvalue.push_back(yp); dtemp[2] += yp; cout << iVEM*25. << "\t" << vemtrace[iVEM] << "\t" << yp << endl; } } cout << endl; //cout << "Number of points in the signal slot: " << yvalue.size() << ", Maxval: " << maxval << endl; // DEBUG if(dtemp[2] < 0) { cout << "Rejected PMT " << iPMT << " in tank " << stationVector[i].GetId() << ": Negative signal integral value = " << dtemp[2] << endl; itemp[0]--; itemp[1]--; } else { for(int iy = 0; iy < yvalue.size(); iy++) { //cout << time[iy]/25. << "\t" << yvalue[iy]/maxval << endl; // DEBUG if(yvalue[iy]/maxval > 0.95) break; if(yvalue[iy]/maxval <= 0.10) { byrange[0] = yvalue[iy]/maxval; byrange[1] = yvalue[iy+1]/maxval; yp = 0.1; //cout << "yp = " << yp << ", byrange = " << byrange[0] << ", " << byrange[1] << ", time = " << time[iy] << ", " << time[iy+1] << endl; // DEBUG // Find the x value of point with y value = yp = 0.1, that lies on a line between two points // y = k*x + a // k = (y2 - y1)/(x2 - x1) // a = y2 - (y2 - y1)/(x2 - x1)*x2 // x = ((x2 - x1)/(y2 - y1))*(y - y2) + x2 xp = ((time[iy+1] - time[iy])*(yp - byrange[1]))/(byrange[1] - byrange[0]) + time[iy+1]; byrange[0] = xp; byrange[1] = yp; } if(yvalue[iy]/maxval <= 0.50) { bzrange[0] = yvalue[iy]/maxval; bzrange[1] = yvalue[iy+1]/maxval; yp = 0.5; // Find the x value of point with y value = yp = 0.5, that lies on a line between two points // y = k*x + a // k = (y2 - y1)/(x2 - x1) // a = y2 - (y2 - y1)/(x2 - x1)*x2 // x = ((x2 - x1)/(y2 - y1))*(y - y2) + x2 xp = ((time[iy+1] - time[iy])*(yp - bzrange[1]))/(bzrange[1] - bzrange[0]) + time[iy+1]; bzrange[0] = xp; bzrange[1] = yp; } } cout << "Calculated risetime (" << byrange[0]/25. << "," << bzrange[0]/25. << ") = " << bzrange[0] - byrange[0] << endl; // DEBUG tempRise.clear(); tempRise.push_back(byrange[0]); tempRise.push_back(bzrange[0]); tempRise.push_back(byrange[1]); tempRise.push_back(bzrange[1]); PlotCurrentVemTrace(j+1, stationVector[i].GetId(), iPMT, maxval); dtemp[0] += bzrange[0] - byrange[0]; dtemp[1] += bzrange[0] - byrange[0]; } } } dtemp[1] = dtemp[1]/itemp[1]; cout << "Station " << stationVector[i].GetId() << ", " << stationVector[i].GetSPDistance() << " m: Calculated average risetime (for " << itemp[1] << " PMTs in the tank) = " << dtemp[1] << ", Total signal = " << stationVector[i].GetTotalSignal() << endl; // DEBUG } } } } /* for(int j = 0; j < nevents; j++) { if(nevents < 20) cerr << "Currently at " << j << "/" << nevents << endl; else if(j%((int)(nevents*0.05)) == 0) cerr << "Currently at " << j << "/" << nevents << endl; else { if(j%((int)(nevents*0.1)) == 0) cerr << "Currently at " << j << "/" << nevents << endl; } fFile->ReadEvent(j); cout << "New event (" << j+1 << ", ID = " << fRecEvent->GetEventId() << ", Time = [" << fRecEvent->GetYYMMDD() << "," << fRecEvent->GetHHMMSS() << "], E = " << TMath::Log10(fRecEvent->GetSDEvent().GetSdRecShower().GetEnergy()) << ", sec(theta) = " <<SecTheta(fRecEvent->GetSDEvent().GetSdRecShower().GetZenith(),false) << ") -------" << endl; goodrec = true; // Prepare SD station events ------------------------------------------- *sdrecshw = fRecEvent->GetSDEvent().GetSdRecShower(); // Check if there are triggered SD stations if(!(fRecEvent->GetSDEvent().HasTriggeredStations())) goodrec = false; // Check if there are any SD stations in the event if(!(fRecEvent->GetSDEvent().HasStations())) goodrec = false; // Check if SD stations have a VEM trace if(!(fRecEvent->GetSDEvent().HasVEMTraces())) goodrec = false; // Limit in energy if(energylimitFull[0] != -1) { if(TMath::Log10(sdrecshw->GetEnergy()) < energylimitFull[0]) goodrec = false; } if(energylimitFull[1] != -1) { if(TMath::Log10(sdrecshw->GetEnergy()) > energylimitFull[1]) goodrec = false; } // Full limit in zenith angle (will be further binned later) if(zenithlimitFull[0] != -1) { if(SecTheta(sdrecshw->GetZenith(),false) < zenithlimitFull[0]) goodrec = false; } if(zenithlimitFull[1] != -1) { if(SecTheta(sdrecshw->GetZenith(),false) > zenithlimitFull[1]) goodrec = false; } if(TMath::Log10(sdrecshw->GetEnergy()) > 19.6) limitTankDistance[1] = 2000.; else limitTankDistance[1] = 1400.; if(goodrec) { dtemp[0] = 0; itemp[0] = 0; // Loop over all triggered SD stations stationVector = fRecEvent->GetSDEvent().GetStationVector(); itemp[3] = 0; tempVect.clear(); for(int i = 0; i < stationVector.size(); i++) { // Only use stations that are valid candidates if(stationVector[i].IsCandidate()) { cout << "New station (" << stationVector[i].GetId() << ")" << endl; // DEBUG start_bin = stationVector[i].GetSignalStartSlot() - 4; stop_bin = stationVector[i].GetSignalEndSlot(); if( (start_bin >= stop_bin) || (start_bin < 0) || (start_bin > 5000) ) start_bin = 0; dtemp[1] = 0; itemp[1] = 0; // Check all PMTs for(int iPMT = 1; iPMT <= 3; iPMT++) { time.clear(); yvalue.clear(); vemtrace.clear(); yp = 0; maxval = -1.e40; vemtrace = stationVector[i].GetVEMTrace(iPMT); //cout << "PMT " << iPMT << ": Number of points in the VEM trace: " << vemtrace.size() << " --------------------------------------------------------" << endl; // DEBUG // Continue if there is a VEM trace if(vemtrace.size() > 0) { itemp[0]++; itemp[1]++; dtemp[2] = 0; // Prepare the time vector (each point is multiplied by 25 to get nanoseconds) for(int iVEM = 0; iVEM < vemtrace.size(); iVEM++) { if( (iVEM >= start_bin) && (iVEM <= stop_bin) ) { time.push_back((float)iVEM*25.); yp += vemtrace[iVEM]; if(yp > maxval) maxval = yp; yvalue.push_back(yp); dtemp[2] += yp; } } //cout << "Number of points in the signal slot: " << yvalue.size() << ", Maxval: " << maxval << endl; // DEBUG if(dtemp[2] < 0) { cout << "Rejected PMT " << iPMT << " in tank " << stationVector[i].GetId() << ": Negative signal integral value = " << dtemp[2] << endl; itemp[0]--; itemp[1]--; } else { for(int iy = 0; iy < yvalue.size(); iy++) { //cout << time[iy]/25. << "\t" << yvalue[iy]/maxval << endl; // DEBUG if(yvalue[iy]/maxval > 0.95) break; if(yvalue[iy]/maxval <= 0.10) { byrange[0] = yvalue[iy]/maxval; byrange[1] = yvalue[iy+1]/maxval; yp = 0.1; //cout << "yp = " << yp << ", byrange = " << byrange[0] << ", " << byrange[1] << ", time = " << time[iy] << ", " << time[iy+1] << endl; // DEBUG // Find the x value of point with y value = yp = 0.1, that lies on a line between two points // y = k*x + a // k = (y2 - y1)/(x2 - x1) // a = y2 - (y2 - y1)/(x2 - x1)*x2 // x = ((x2 - x1)/(y2 - y1))*(y - y2) + x2 xp = ((time[iy+1] - time[iy])*(yp - byrange[1]))/(byrange[1] - byrange[0]) + time[iy+1]; byrange[0] = xp; byrange[1] = yp; } if(yvalue[iy]/maxval <= 0.50) { bzrange[0] = yvalue[iy]/maxval; bzrange[1] = yvalue[iy+1]/maxval; yp = 0.5; // Find the x value of point with y value = yp = 0.5, that lies on a line between two points // y = k*x + a // k = (y2 - y1)/(x2 - x1) // a = y2 - (y2 - y1)/(x2 - x1)*x2 // x = ((x2 - x1)/(y2 - y1))*(y - y2) + x2 xp = ((time[iy+1] - time[iy])*(yp - bzrange[1]))/(bzrange[1] - bzrange[0]) + time[iy+1]; bzrange[0] = xp; bzrange[1] = yp; } } //cout << "Calculated risetime (" << byrange[0]/25. << "," << bzrange[0]/25. << ") = " << bzrange[0] - byrange[0] << endl; // DEBUG dtemp[0] += bzrange[0] - byrange[0]; dtemp[1] += bzrange[0] - byrange[0]; } } } dtemp[1] = dtemp[1]/itemp[1]; //cout << "Station " << stationVector[i].GetId() << ", " << stationVector[i].GetSPDistance() << " m: Calculated average risetime (for " << itemp[1] << " PMTs in the tank) = " << dtemp[1] << ", Total signal = " << stationVector[i].GetTotalSignal() << endl; // DEBUG // Asymmetry correction eventThetaRec = fRecEvent->GetSDEvent().GetSdRecShower().GetZenith(); secZenith = 1./cos(eventThetaRec); alpha = 96.73 + secZenith*(-282.40 + secZenith*(241.80 - 62.61*secZenith)); gamma = -0.0009572 + secZenith*(0.002068 + secZenith*(-0.001362 + 0.0002861*secZenith)); g = alpha + gamma * stationVector[i].GetSPDistance()*stationVector[i].GetSPDistance(); zeta = stationVector[i].GetAzimuthSP(); risemean = dtemp[1] - g*cos(zeta); riseerr = fRTWeights->Eval(stationVector[i].GetSPDistance(), secZenith, stationVector[i].GetTotalSignal()); if( (stationVector[i].GetTotalSignal() > minSignal) ) { if( (!stationVector[i].IsLowGainSaturated()) && (!includeSaturated) ) { if( (stationVector[i].GetSPDistance() >= limitTankDistance[0]) && (stationVector[i].GetSPDistance() <= limitTankDistance[1]) ) { tempVect.push_back(stationVector[i].GetId()); tempVect.push_back((double)stationVector[i].IsHighGainSaturated()); tempVect.push_back(stationVector[i].GetSPDistance()); tempVect.push_back(stationVector[i].GetSPDistanceError()); tempVect.push_back(risemean); tempVect.push_back(riseerr); tempVect.push_back(sdrecshw->GetEnergy()); tempVect.push_back(sdrecshw->GetEnergyError()); tempVect.push_back(sdrecshw->GetZenith()); tempVect.push_back(sdrecshw->GetZenithError()); tempVect.push_back(sdrecshw->GetShowerSize()); tempVect.push_back(sdrecshw->GetShowerSizeError()); itemp[3]++; } else cout << "Rejected: Station distance " << stationVector[i].GetSPDistance() << " is outside the limits (" << limitTankDistance[0] << "m, " << limitTankDistance[1] << "m)." << endl; } else cout << "Rejected: Station signal is low gain saturated." << endl; } else cout << "Rejected: Station signal " << stationVector[i].GetTotalSignal() << " is below the minimum accepted (" << minSignal << " VEM)." << endl; } } if(itemp[3] < minPoints) { goodrec = false; cout << "Rejected: Only " << itemp[3] << " valid tanks." << endl; cout << "Event reconstruction has failed." << endl; } else { for(int i = 0; i < itemp[3]; i++) { // Save SD station ID values sdidVect->push_back(tempVect[12*i]); // Save if station is high gain saturated HGsat->push_back((bool)tempVect[12*i+1]); // Save distance of station to shower axis distVect->push_back(tempVect[12*i+2]); distVect->push_back(tempVect[12*i+3]); // Save risetime for each station riseVect->push_back(tempVect[12*i+4]); riseVect->push_back(tempVect[12*i+5]); // Save event energy energy->push_back(tempVect[12*i+6]); energy->push_back(tempVect[12*i+7]); // Save event zenith angle zenith->push_back(tempVect[12*i+8]); zenith->push_back(tempVect[12*i+9]); // Save event S1000 value shwsize->push_back(tempVect[12*i+10]); shwsize->push_back(tempVect[12*i+11]); // Save the current event number eventVect->push_back(*allevts); (*allcount)++; if(i == itemp[3]-1) cout << "Risetime value from " << itemp[3] << " SD stations for event " << *allevts << " = " << tempVect[12*i+4] << " ± " << tempVect[12*i+5] << endl; } (*allevts)++; } } else cout << "Event reconstruction has failed." << endl; }*/ fFile->Close(); delete fFile; } void BinNaming(string *instring, double *energy, double *zenith) { if( (energy[0] != -1) || (energy[1] != -1) ) *instring += "_en_"; if(energy[0] != -1) *instring += ToString(energy[0],2); if(energy[1] != -1) *instring += "-" + ToString(energy[1],2); if( (zenith[0] != -1) || (zenith[1] != -1) ) *instring += "_zen_"; if(zenith[0] != -1) *instring += ToString(zenith[0],2); if(zenith[1] != -1) *instring += "-" + ToString(zenith[1],2); } int ReadCustomBinning(string infile, vector<double> *outBins, double *maxRange) { outBins->clear(); ifstream *ifs = new ifstream; double *dtemp = new double[4]; int itemp; ifs->open(infile.c_str(), ifstream::in); dtemp[2] = 1e+20; dtemp[3] = -1; if(ifs->is_open()) { itemp = 0; cout << "Writing out custom binning:" << endl; while(1) { *ifs >> dtemp[0] >> dtemp[1]; if(dtemp[0] < dtemp[2]) dtemp[2] = dtemp[0]; if(dtemp[1] > dtemp[3]) dtemp[3] = dtemp[1]; outBins->push_back(dtemp[0]); outBins->push_back(dtemp[1]); itemp++; ifs->ignore(1,' '); if(ifs->eof()) break; } cout << "Number of bins = " << itemp << ", Minimum bin value = " << dtemp[2] << ", Maximum bin value = " << dtemp[3] << endl; maxRange[0] = dtemp[2]; maxRange[1] = dtemp[3]; } ifs->close(); delete ifs; delete[] dtemp; return itemp; } // Calculate SD fit parameters A, B and N from zenith angle void CalculateSdFitParams(double *inpar, double *outpar, double zenith, double zenithErr) { double *dtemp = new double[6]; dtemp[0] = SecTheta(zenith,false); dtemp[1] = TMath::Sin(zenith); dtemp[2] = TMath::Cos(zenith); dtemp[3] = TMath::Tan(zenith); // A = a0 + a1*(sec(theta))^-4 = (inpar[0]+inpar[2]*TMath::Power(SecTheta(zenith,false),-4)) outpar[0] = inpar[0]+inpar[2]*TMath::Power(dtemp[0],-4); // B = b0 + b1*(sec(theta))^-4 = (inpar[4]+inpar[6]*TMath::Power(SecTheta(zenith,false),-4)) outpar[2] = inpar[4]+inpar[6]*TMath::Power(dtemp[0],-4); // N = n0 + n1*(sec(theta))^2 + n2*exp(sec(theta)) = (inpar[8]+inpar[10]*TMath::Power(SecTheta(zenith,false),2) + inpar[12]*TMath::Exp(SecTheta(zenith,false))) outpar[4] = inpar[8]+inpar[10]*TMath::Power(dtemp[0],2) + inpar[12]*TMath::Exp(dtemp[0]); // dA = sqrt( da0^2 + (da1/sec(theta)^4)^2 + (-4*dtheta*a1*sin(theta)*cos(theta)^3)^2 ) // a0 = inpar[0], da0 = inpar[1], a1 = inpar[2], da1 = inpar[3] dtemp[4] = inpar[1]; dtemp[5] = TMath::Power(dtemp[4],2); cout << " da0 = " << dtemp[4]; dtemp[4] = inpar[3]*TMath::Power(dtemp[0],-4); dtemp[5] += TMath::Power(dtemp[4],2); cout << ", da1 = " << dtemp[4]; dtemp[4] = -4*zenithErr*inpar[2]*dtemp[1]*TMath::Power(dtemp[2],3); dtemp[5] += TMath::Power(dtemp[4],2); cout << ", dtheta = " << dtemp[4] << endl; outpar[1] = TMath::Sqrt(dtemp[5]); // dB = sqrt( db0^2 + (db1/sec(theta)^4)^2 + (-4*dtheta*b1*sin(theta)*cos(theta)^3)^2 ) // b0 = inpar[4], db0 = inpar[5], b1 = inpar[6], db1 = inpar[7] dtemp[4] = inpar[5]; dtemp[5] = TMath::Power(dtemp[4],2); cout << " db0 = " << dtemp[4]; dtemp[4] = inpar[7]*TMath::Power(dtemp[0],-4); dtemp[5] += TMath::Power(dtemp[4],2); cout << ", db1 = " << dtemp[4]; dtemp[4] = -4*zenithErr*inpar[6]*dtemp[1]*TMath::Power(dtemp[2],3); dtemp[5] += TMath::Power(dtemp[4],2); cout << ", dtheta = " << dtemp[4] << endl; outpar[3] = TMath::Sqrt(dtemp[5]); // dN = sqrt( dn0^2 + (dn1*sec(theta)^2)^2 + (dn2*exp(sec(theta)))^2 + (dtheta*tan(theta)*sec(theta)*(2*n1*sec(theta)+n2*exp(sec(theta))))^2 ) // n0 = inpar[8], dn0 = inpar[9], n1 = inpar[10], dn1 = inpar[11], n2 = inpar[12], dn2 = inpar[13] dtemp[4] = inpar[9]; dtemp[5] = TMath::Power(dtemp[4],2); cout << " dn0 = " << dtemp[4]; dtemp[4] = inpar[11]*TMath::Power(dtemp[0],2); dtemp[5] += TMath::Power(dtemp[4],2); cout << ", dn1 = " << dtemp[4]; dtemp[4] = inpar[13]*TMath::Exp(dtemp[0]); dtemp[5] += TMath::Power(dtemp[4],2); cout << ", dn2 = " << dtemp[4]; dtemp[4] = zenithErr*dtemp[3]*dtemp[0]*(2*inpar[10]*dtemp[0]+inpar[12]*TMath::Exp(dtemp[0])); dtemp[5] += TMath::Power(dtemp[4],2); cout << ", dtheta = " << dtemp[4] << endl; outpar[5] = TMath::Sqrt(dtemp[5]); delete[] dtemp; } // Calculate benchmark functions void CalculateBenchmark(double *tbench, double *fitparam, double dist, double distErr, bool sat) { double *dtemp = new double[2]; // The SD station is high-gain saturated // tbench = 40 + sqrt(A^2 + B*r^2) - A if(sat) { tbench[0] = 40 + TMath::Sqrt(TMath::Power(fitparam[0],2) + fitparam[2]*TMath::Power(dist,2)) - fitparam[0]; cout << " tbench[0] = " << tbench[0]; // (dA)^2 = (dA*(A/sqrt(A^2 + B*r^2) - 1))^2 dtemp[0] = fitparam[1]*(fitparam[0]/TMath::Sqrt(TMath::Power(fitparam[0],2) + fitparam[2]*TMath::Power(dist,2)) - 1); dtemp[1] = TMath::Power(dtemp[0],2); cout << ", dA = " << dtemp[0]; // (dB)^2 = (dB*r^2/(2*sqrt(A^2 + B*r^2)))^2 dtemp[0] = fitparam[3]*TMath::Power(dist,2)/(2*TMath::Sqrt(TMath::Power(fitparam[0],2) + fitparam[2]*TMath::Power(dist,2))); dtemp[1] += TMath::Power(dtemp[0],2); cout << ", dB = " << dtemp[0]; // (dr)^2 = (dr*B*r/(sqrt(A^2 + B*r^2)))^2 dtemp[0] = distErr*fitparam[2]*dist/(TMath::Sqrt(TMath::Power(fitparam[0],2) + fitparam[2]*TMath::Power(dist,2))); dtemp[1] += TMath::Power(dtemp[0],2); cout << ", dr = " << dtemp[0]; } // The SD station has a valid high-gain trace // tbench = 40 + N*(sqrt(A^2 + B*r^2) - A) else { tbench[0] = 40 + fitparam[4]*(TMath::Sqrt(TMath::Power(fitparam[0],2) + fitparam[2]*TMath::Power(dist,2)) - fitparam[0]); cout << " tbench[0] = " << tbench[0]; // (dA)^2 = (N*dA*(A/sqrt(A^2 + B*r^2) - 1))^2 dtemp[0] = fitparam[4]*fitparam[1]*(fitparam[0]/TMath::Sqrt(TMath::Power(fitparam[0],2) + fitparam[2]*TMath::Power(dist,2)) - 1); dtemp[1] = TMath::Power(dtemp[0],2); cout << ", dA = " << dtemp[0]; // (dB)^2 = (N*dB*r^2/(2*sqrt(A^2 + B*r^2)))^2 dtemp[0] = fitparam[4]*fitparam[3]*TMath::Power(dist,2)/(2*TMath::Sqrt(TMath::Power(fitparam[0],2) + fitparam[2]*TMath::Power(dist,2))); dtemp[1] += TMath::Power(dtemp[0],2); cout << ", dB = " << dtemp[0]; // (dN)^2 = (dN*(sqrt(A^2 + B*r^2) - A))^2 dtemp[0] = fitparam[5]*(TMath::Sqrt(TMath::Power(fitparam[0],2) + fitparam[2]*TMath::Power(dist,2)) - fitparam[0]); dtemp[1] += TMath::Power(dtemp[0],2); cout << ", dN = " << dtemp[0]; // (dr)^2 = (dr*B*N*r/(sqrt(A^2 + B*r^2)))^2 dtemp[0] = distErr*fitparam[2]*fitparam[4]*dist/(TMath::Sqrt(TMath::Power(fitparam[0],2) + fitparam[2]*TMath::Power(dist,2))); dtemp[1] += TMath::Power(dtemp[0],2); cout << ", dr = " << dtemp[0]; } tbench[1] = TMath::Sqrt(dtemp[1]); cout << ", tbench[1] = " << tbench[1] << endl; delete[] dtemp; } int main(int argc, char **argv) { gSystem->Load("libTree.so"); // Reading ADST files /* RecEventFile *fFile; RecEvent *fRecEvent = new RecEvent(); DetectorGeometry *fDetGeo = new DetectorGeometry(); SdRecShower *sdrecshw = new SdRecShower(); vector<SdRecStation> stationVector;*/ // Temporary variables and holders for number of stations and events // int nrstations, nevents; string *stemp = new string[3]; int *itemp = new int[4]; double *dtemp = new double[7]; bool goodrec; int printEvent = -1; string inname; // Vectors for distance, risetime and station ID vector<double> *distVect = new vector<double>; vector<double> *riseVect = new vector<double>; vector<double> *sdidVect = new vector<double>; vector<double> *energy = new vector<double>; vector<double> *zenith = new vector<double>; vector<double> *shwsize = new vector<double>; vector<int> *eventVect = new vector<int>; vector<bool> *HGsat = new vector<bool>; int allcount = 0; int allevts = 0; if(argc > 1) { cerr << "Select number of events for which you wish to print the PMT trace: "; cin >> printEvent; if(printEvent > 0) { AdstFile *adfile = new AdstFile(); inname = string(argv[1]); adfile->ReadAdstFile(inname, sdidVect, HGsat, distVect, riseVect, energy, zenith, shwsize, eventVect, &allcount, &allevts, &printEvent); delete adfile; } } else { cerr << "Error! No input files supplied. Rerun program and add input files as arguments (ADST files)." << endl; return 1; } // Limits for risetime calculations /* double limitTankDistance[2] = {300., 1400.}; double minSignal = 5.0; bool includeSaturated = false; int minPoints = 3;*/ // Vectors for distance, risetime and station ID /* vector<double> *distVect = new vector<double>; vector<double> *riseVect = new vector<double>; vector<double> *sdidVect = new vector<double>; vector<double> *energy = new vector<double>; vector<double> *zenith = new vector<double>; vector<double> *shwsize = new vector<double>; vector<int> *eventVect = new vector<int>; vector<bool> *HGsat = new vector<bool>; vector<double> distVectLow; vector<double> riseVectLow; vector<double> distVectHigh; vector<double> riseVectHigh; vector<double> energyVect; vector<double> deltaVect; // vector<double> tempVect;*/ // Vectors and variables needed for calculation of risetime /* vector<float> time; vector<float> vemtrace; vector<float> yvalue; int start_bin, stop_bin; double maxval; double xp, yp; double risemean, riseerr; double *byrange = new double[2]; double *bzrange = new double[2]; byrange[0] = 1.e+40; byrange[1] = -1.e+40; bzrange[0] = 1.e+40; bzrange[1] = -1.e+40; TFormula *fRTWeights = new TFormula("RiseTimeWeights", "(80.0+(5.071e-7+6.48e-4*y-3.051e-4*y*y)*x*x)/z-16.46*y+36.16");*/ // Graphing variables for risetimes /* RootStyle *mystyle; TCanvas *c1; TGraphErrors *allRise, *allRiseLowGain, *allRiseHighGain; TGraphErrors *allDelta; TH1D *riseErrDist, *riseErrDistLow, *riseErrDistHigh; TLine *line = new TLine(); line->SetLineWidth(2); line->SetLineStyle(7); line->SetLineColor(28); TLine *line2 = new TLine(); line2->SetLineWidth(2); line2->SetLineStyle(7); line2->SetLineColor(28); int allcount = 0; int allcountLow = 0; int allcountHigh = 0; int allevts = 0; double fitparamLow[4]; double fitparamLowErr[4]; double fitparamHigh[4]; double fitparamHighErr[4]; double fitparam[6]; double sdfitparam[14]; // Fitting parameters of benchmark functions from the SD analysis sdfitparam[0] = -72.; sdfitparam[1] = 10.; sdfitparam[2] = 410.; sdfitparam[3] = 30.; sdfitparam[4] = -0.049; sdfitparam[5] = 0.007; sdfitparam[6] = 0.36; sdfitparam[7] = 0.02; sdfitparam[8] = -0.07; sdfitparam[9] = 0.02; sdfitparam[10] = -1.14; sdfitparam[11] = 0.02; sdfitparam[12] = 0.84; sdfitparam[13] = 0.02; double tbench[2]; // Graphing variables for A, B and N parameters TGraphErrors *parA, *parB, *parN; TF1 *parfit[3]; TF1 *tempfunc; // Variables for setting energy and zenith angle limits double energylimit[2] = {-1,-1}; double energylimitFull[2] = {-1,-1}; int energynr = 12; vector<double> *energybins = new vector<double>; int energyref = -1; double zenithlimit[2] = {-1,-1}; double zenithlimitFull[2] = {-1,-1}; int zenithnr = 9; vector<double> *zenithbins = new vector<double>; int sdBenchmark = 1; stemp[0] = string(rootdir) + "/input/custom_energy_bins.txt"; energynr = ReadCustomBinning(stemp[0], energybins, energylimitFull); stemp[0] = string(rootdir) + "/input/custom_zenith_bins.txt"; zenithnr = ReadCustomBinning(stemp[0], zenithbins, zenithlimitFull); ofstream *ofs = new ofstream; ifstream *ifs = new ifstream; AdstFile *adfile = new AdstFile(); string inname; if(argc > 1) { cerr << "Use fitted benchmark functions (0) or those defined in SD analysis (1): "; cin >> sdBenchmark; if(sdBenchmark == 1) { cerr << "Using benchmark functions defined in the SD analysis." << endl; cout << "Using benchmark functions defined in the SD analysis." << endl; for(int i = 0; i < energynr; i++) { if(energybins->at(2*i) == 19.1) energyref = i; } } else { cerr << "Using fitted benchmark functions from this analysis." << endl; cout << "Using fitted benchmark functions from this analysis." << endl; cerr << "Energy bins:" << endl; for(int i = 0; i < energynr; i++) cerr << "[" << i << "] = " << energybins->at(2*i) << ", " << energybins->at(2*i+1) << endl; cerr << "Select the energy bin to be used as reference (use number in square brackets): "; cin >> energyref; } cerr << "Energy bin used for reference = (" << energybins->at(2*energyref) << ", " << energybins->at(2*energyref+1) << ")" << endl; cout << "Energy bin used for reference = (" << energybins->at(2*energyref) << ", " << energybins->at(2*energyref+1) << ")" << endl; mystyle = new RootStyle(); mystyle->SetBaseStyle(); c1 = new TCanvas("c1","",1200,900); gStyle->SetEndErrorSize(3); stemp[0] = "mkdir -p ./plots"; system(stemp[0].c_str()); distVect->clear(); riseVect->clear(); sdidVect->clear(); energy->clear(); zenith->clear(); shwsize->clear(); eventVect->clear(); HGsat->clear(); for(int k = 0; k < argc-1; k++) { inname = string(argv[k+1]); adfile->ReadAdstFile(inname, energylimitFull, zenithlimitFull, sdidVect, HGsat, distVect, riseVect, energy, zenith, shwsize, eventVect, &allcount, &allevts); } cout << "Surviving a total of " << allcount << " risetimes from " << allevts << " valid events." << endl; cerr << "Surviving a total of " << allcount << " risetimes from " << allevts << " valid events." << endl; TF1 *fitfuncLow; TF1 *fitfuncHigh; itemp[0] = 0; if(sdBenchmark != 1) { parA = new TGraphErrors(); parB = new TGraphErrors(); parN = new TGraphErrors(); stemp[0] = "./benchmark_functions_en_" + ToString(energybins->at(2*energyref),2) + "-" + ToString(energybins->at(2*energyref+1),2) + ".txt"; ofs->open(stemp[0].c_str(), ofstream::out); } for(int iZen = 0; iZen < zenithnr; iZen++) { zenithlimit[0] = zenithbins->at(2*iZen); zenithlimit[1] = zenithbins->at(2*iZen+1); energylimit[0] = energybins->at(2*energyref); energylimit[1] = energybins->at(2*energyref+1); cout << "Reference energy limit = " << energylimit[0] << ", " << energylimit[1] << endl; cout << "Chosen zenith angle limit = " << zenithlimit[0] << ", " << zenithlimit[1] << endl; // cout << "distVect size = " << distVect.size() << ", riseVect size = " << riseVect.size() << ", energy size = " << energy.size() << ", zenith size = " << zenith.size() << ", sdidVect size = " << sdidVect.size() << ", HGsat size = " << HGsat.size() << endl; distVectLow.clear(); riseVectLow.clear(); distVectHigh.clear(); riseVectHigh.clear(); for(int i = 0; i < sdidVect->size(); i++) { goodrec = true; if(SecTheta(zenith->at(2*i),false) < zenithlimit[0]) goodrec = false; if(SecTheta(zenith->at(2*i),false) > zenithlimit[1]) goodrec = false; if(TMath::Log10(energy->at(2*i)) < energylimit[0]) goodrec = false; if(TMath::Log10(energy->at(2*i)) > energylimit[1]) goodrec = false; if(goodrec) { cout << "Event " << eventVect->at(i) << ", station " << sdidVect->at(i) << ", energy = " << energy->at(2*i) << " ± " << energy->at(2*i+1) << ", zenith = " << SecTheta(zenith->at(2*i),false) << " ± " << (TMath::Sin(zenith->at(2*i))*zenith->at(2*i+1))/TMath::Power(TMath::Cos(zenith->at(2*i)),2) << endl; if(HGsat->at(i)) { // Save distance of station to shower axis distVectLow.push_back(distVect->at(2*i)); distVectLow.push_back(distVect->at(2*i+1)); // Save risetime for each station riseVectLow.push_back(riseVect->at(2*i)); riseVectLow.push_back(riseVect->at(2*i+1)); cout << "Important: Station signal (" << sdidVect->at(i) << ") is high gain saturated." << endl; } else { // Save distance of station to shower axis distVectHigh.push_back(distVect->at(2*i)); distVectHigh.push_back(distVect->at(2*i+1)); // Save risetime for each station riseVectHigh.push_back(riseVect->at(2*i)); riseVectHigh.push_back(riseVect->at(2*i+1)); } } } allcount = 0; allcountLow = 0; allcountHigh = 0; allRise = new TGraphErrors(); allRiseLowGain = new TGraphErrors(); allRiseHighGain = new TGraphErrors(); for(int i = 0; i < distVectLow.size()/2; i++) { cout << "(" << allcount << "," << allcountLow << ") Low: " << distVectLow[2*i] << " (" << distVectLow[2*i+1] << ")\t" << riseVectLow[2*i] << " (" << riseVectLow[2*i+1] << ")" << endl; allRise->SetPoint(allcount, distVectLow[2*i], riseVectLow[2*i]); allRise->SetPointError(allcount, distVectLow[2*i+1], riseVectLow[2*i+1]); allRiseLowGain->SetPoint(allcountLow, distVectLow[2*i], riseVectLow[2*i]); allRiseLowGain->SetPointError(allcountLow, distVectLow[2*i+1], riseVectLow[2*i+1]); allcount++; allcountLow++; } for(int i = 0; i < distVectHigh.size()/2; i++) { cout << "(" << allcount << "," << allcountHigh << ") High: " << distVectHigh[2*i] << " (" << distVectHigh[2*i+1] << ")\t" << riseVectHigh[2*i] << " (" << riseVectHigh[2*i+1] << ")" << endl; allRise->SetPoint(allcount, distVectHigh[2*i], riseVectHigh[2*i]); allRise->SetPointError(allcount, distVectHigh[2*i+1], riseVectHigh[2*i+1]); allRiseHighGain->SetPoint(allcountHigh, distVectHigh[2*i], riseVectHigh[2*i]); allRiseHighGain->SetPointError(allcountHigh, distVectHigh[2*i+1], riseVectHigh[2*i+1]); allcount++; allcountHigh++; } if(allcount == 0) { cout << "No risetime values found in this zenith angle bin. Skipping plotting procedures." << endl; cerr << "No risetime values found in this zenith angle bin. Skipping plotting procedures." << endl; } else { cout << "Plotting " << allcount << " risetimes, " << allcountLow << " are high gain saturated and " << allcountHigh << " are not." << endl; cerr << "Plotting " << allcount << " risetimes, " << allcountLow << " are high gain saturated and " << allcountHigh << " are not." << endl; mystyle->SetGraphColor(allRise, 2); allRise->SetMarkerStyle(20); allRise->SetMarkerSize(0.8); mystyle->SetAxisTitles(allRise, "Distance from shower axis [m]", "t_{1/2} [ns]"); c1->SetLogx(kFALSE); c1->SetLogy(kFALSE); allRise->Draw("AP"); mystyle->SetGraphColor(allRiseLowGain, 0); allRiseLowGain->SetMarkerStyle(20); allRiseLowGain->SetMarkerSize(0.8); mystyle->SetAxisTitles(allRiseLowGain, "Distance from shower axis [m]", "t_{1/2} [ns]"); allRiseLowGain->Draw("P;SAME"); mystyle->SetGraphColor(allRiseHighGain, 1); allRiseHighGain->SetMarkerStyle(21); allRiseHighGain->SetMarkerSize(0.8); mystyle->SetAxisTitles(allRiseHighGain, "Distance from shower axis [m]", "t_{1/2} [ns]"); allRiseHighGain->Draw("P;SAME"); if(sdBenchmark == 1) { fitfuncLow = new TF1("fitfuncLow", "40+TMath::Sqrt(TMath::Power(([0]+[1]*TMath::Power([4],-4)),2)+([2]+[3]*TMath::Power([4],-4))*TMath::Power(x,2))-([0]+[1]*TMath::Power([4],-4))", adfile->GetDistanceLimit(0), adfile->GetDistanceLimit(1)); fitfuncLow->SetParameter(0, sdfitparam[0]); fitfuncLow->SetParameter(1, sdfitparam[2]); fitfuncLow->SetParameter(2, sdfitparam[4]); fitfuncLow->SetParameter(3, sdfitparam[6]); fitfuncLow->SetParameter(4, (zenithlimit[0]+zenithlimit[1])/2.); fitfuncLow->SetParError(0, sdfitparam[1]); fitfuncLow->SetParError(1, sdfitparam[3]); fitfuncLow->SetParError(2, sdfitparam[5]); fitfuncLow->SetParError(3, sdfitparam[7]); cout << endl << "Fitting parameters from low gain fit (SD analysis):" << endl; cout << "- a0 = " << fitfuncLow->GetParameter(0) << " ± " << fitfuncLow->GetParError(0) << endl; cout << "- a1 = " << fitfuncLow->GetParameter(1) << " ± " << fitfuncLow->GetParError(1) << endl; cout << "- b0 = " << fitfuncLow->GetParameter(2) << " ± " << fitfuncLow->GetParError(2) << endl; cout << "- b1 = " << fitfuncLow->GetParameter(3) << " ± " << fitfuncLow->GetParError(3) << endl; cout << endl; fitfuncLow->SetLineColor(1); fitfuncLow->SetLineWidth(2); fitfuncLow->SetLineStyle(1); fitfuncLow->Draw("SAME"); fitfuncHigh = new TF1("fitfuncHigh", "40+([4]+[5]*TMath::Power([7],2)+[6]*TMath::Exp([7]))*(TMath::Sqrt(TMath::Power(([0]+[1]*TMath::Power([7],-4)),2)+([2]+[3]*TMath::Power([7],-4))*TMath::Power(x,2))-([0]+[1]*TMath::Power([7],-4)))", adfile->GetDistanceLimit(0), adfile->GetDistanceLimit(1)); fitfuncHigh->SetParameter(0, sdfitparam[0]); fitfuncHigh->SetParameter(1, sdfitparam[2]); fitfuncHigh->SetParameter(2, sdfitparam[4]); fitfuncHigh->SetParameter(3, sdfitparam[6]); fitfuncHigh->SetParameter(4, sdfitparam[8]); fitfuncHigh->SetParameter(5, sdfitparam[10]); fitfuncHigh->SetParameter(6, sdfitparam[12]); fitfuncHigh->SetParameter(7, (zenithlimit[0]+zenithlimit[1])/2.); fitfuncHigh->SetParError(0, sdfitparam[1]); fitfuncHigh->SetParError(1, sdfitparam[3]); fitfuncHigh->SetParError(2, sdfitparam[5]); fitfuncHigh->SetParError(3, sdfitparam[7]); fitfuncHigh->SetParError(4, sdfitparam[9]); fitfuncHigh->SetParError(5, sdfitparam[11]); fitfuncHigh->SetParError(6, sdfitparam[13]); cout << endl << "Fitting parameters from high gain fit (SD analysis):" << endl; cout << "- n0 = " << fitfuncHigh->GetParameter(4) << " ± " << fitfuncHigh->GetParError(4) << endl; cout << "- n1 = " << fitfuncHigh->GetParameter(5) << " ± " << fitfuncHigh->GetParError(5) << endl; cout << "- n2 = " << fitfuncHigh->GetParameter(6) << " ± " << fitfuncHigh->GetParError(6) << endl; cout << endl; fitfuncHigh->SetLineColor(1); fitfuncHigh->SetLineWidth(2); fitfuncHigh->SetLineStyle(9); fitfuncHigh->Draw("SAME"); } else { fitfuncLow = new TF1("fitfuncLow", "40+TMath::Sqrt(TMath::Power([0],2)+[1]*TMath::Power(x,2))-[0]", adfile->GetDistanceLimit(0), adfile->GetDistanceLimit(1)); fitfuncLow->SetParameters(100.,0.1); fitfuncLow->SetParLimits(0,0.,1000.); fitfuncLow->SetParLimits(1,0.,1.); allRiseLowGain->Fit("fitfuncLow","0"); tempfunc = (TF1*)allRiseLowGain->GetFunction("fitfuncLow"); tempfunc->SetLineColor(1); tempfunc->SetLineWidth(2); tempfunc->SetLineStyle(1); tempfunc->Draw("SAME"); for(int j = 0; j < 2; j++) { fitparamLow[j] = fitfuncLow->GetParameter(j); fitparamLowErr[j] = fitfuncLow->GetParError(j); } cout << endl << "Fitting parameters from low gain fit (chi2/ndf = " << fitfuncLow->GetChisquare() << "/" << fitfuncLow->GetNDF() << " = " << (fitfuncLow->GetChisquare())/(fitfuncLow->GetNDF()) << "):" << endl; cout << "- A = " << fitparamLow[0] << " ± " << fitparamLowErr[0] << endl; cout << "- B = " << fitparamLow[1] << " ± " << fitparamLowErr[1] << endl; cout << endl; parA->SetPoint(itemp[0], (zenithlimit[0]+zenithlimit[1])/2., fitparamLow[0]); parA->SetPointError(itemp[0], 0., fitparamLowErr[0]); parB->SetPoint(itemp[0], (zenithlimit[0]+zenithlimit[1])/2., fitparamLow[1]); parB->SetPointError(itemp[0], 0., fitparamLowErr[1]); *ofs << energylimit[0] << "\t" << energylimit[1] << "\t" << zenithlimit[0] << "\t" << zenithlimit[1] << "\t" << fitparamLow[0] << "\t" << fitparamLowErr[0] << "\t" << fitparamLow[1] << "\t" << fitparamLowErr[1] << "\t"; fitfuncHigh = new TF1("fitfuncHigh", "40+[2]*(TMath::Sqrt(TMath::Power([0],2)+[1]*TMath::Power(x,2))-[0])", adfile->GetDistanceLimit(0), adfile->GetDistanceLimit(1)); fitfuncHigh->FixParameter(0, fitfuncLow->GetParameter(0)); fitfuncHigh->FixParameter(1, fitfuncLow->GetParameter(1)); fitfuncHigh->SetParameter(2, 1.1); allRiseHighGain->Fit("fitfuncHigh","0"); tempfunc = (TF1*)allRiseHighGain->GetFunction("fitfuncHigh"); tempfunc->SetLineColor(1); tempfunc->SetLineWidth(2); tempfunc->SetLineStyle(9); tempfunc->Draw("SAME"); for(int j = 0; j < 3; j++) { fitparamHigh[j] = fitfuncHigh->GetParameter(j); fitparamHighErr[j] = fitfuncHigh->GetParError(j); } cout << endl << "Fitting parameters from high gain fit (chi2/ndf = " << fitfuncHigh->GetChisquare() << "/" << fitfuncHigh->GetNDF() << " = " << (fitfuncHigh->GetChisquare())/(fitfuncHigh->GetNDF()) << "):" << endl; cout << "- A = " << fitparamHigh[0] << " ± " << fitparamHighErr[0] << endl; cout << "- B = " << fitparamHigh[1] << " ± " << fitparamHighErr[1] << endl; cout << "- N = " << fitparamHigh[2] << " ± " << fitparamHighErr[2] << endl; cout << endl; parN->SetPoint(itemp[0], (zenithlimit[0]+zenithlimit[1])/2., fitparamHigh[2]); parN->SetPointError(itemp[0], 0., fitparamHighErr[2]); *ofs << fitparamHigh[2] << "\t" << fitparamHighErr[2] << endl; } itemp[0]++; allRise->GetXaxis()->SetRange((adfile->GetDistanceLimit(0)-50.), (adfile->GetDistanceLimit(1)+150.)); allRise->GetXaxis()->SetRangeUser((adfile->GetDistanceLimit(0)-50.), (adfile->GetDistanceLimit(1)+150.)); allRise->GetXaxis()->SetLimits((adfile->GetDistanceLimit(0)-50.), (adfile->GetDistanceLimit(1)+150.)); allRiseLowGain->GetXaxis()->SetRange((adfile->GetDistanceLimit(0)-50.), (adfile->GetDistanceLimit(1)+150.)); allRiseLowGain->GetXaxis()->SetRangeUser((adfile->GetDistanceLimit(0)-50.), (adfile->GetDistanceLimit(1)+150.)); allRiseLowGain->GetXaxis()->SetLimits((adfile->GetDistanceLimit(0)-50.), (adfile->GetDistanceLimit(1)+150.)); allRiseHighGain->GetXaxis()->SetRange((adfile->GetDistanceLimit(0)-50.), (adfile->GetDistanceLimit(1)+150.)); allRiseHighGain->GetXaxis()->SetRangeUser((adfile->GetDistanceLimit(0)-50.), (adfile->GetDistanceLimit(1)+150.)); allRiseHighGain->GetXaxis()->SetLimits((adfile->GetDistanceLimit(0)-50.), (adfile->GetDistanceLimit(1)+150.)); allRise->GetYaxis()->SetRange(0., 1100.); allRise->GetYaxis()->SetRangeUser(0., 1100.); allRise->GetYaxis()->SetLimits(0., 1100.); stemp[0] = "rm ./plots/risetime_vs_distance"; BinNaming(&stemp[0], energylimit, zenithlimit); stemp[0] += "*"; system(stemp[0].c_str()); stemp[0] = "./plots/risetime_vs_distance"; BinNaming(&stemp[0], energylimit, zenithlimit); stemp[1] = stemp[0] + ".pdf"; cout << stemp[1] << endl; c1->SaveAs(stemp[1].c_str()); stemp[1] = stemp[0] + ".C"; cout << stemp[1] << endl; c1->SaveAs(stemp[1].c_str()); delete fitfuncLow; delete fitfuncHigh; } delete allRise; delete allRiseLowGain; delete allRiseHighGain; } if(sdBenchmark != 1) { mystyle->SetGraphColor(parA, 0); parA->SetMarkerStyle(20); parA->SetMarkerSize(0.8); mystyle->SetAxisTitles(parA, "SD zenith angle [sec(#theta)]", "Fitting parameter A [ns]"); c1->SetLogx(kFALSE); c1->SetLogy(kFALSE); parA->Draw("AP"); parfit[0] = new TF1("parfit0", "[0]+[1]*TMath::Power(x,-4)", 1.0, 2.0); parfit[0]->SetParameters(-50.,100.); parA->Fit("parfit0"); cout << endl << "Fitting parameters from sec(theta) vs A (chi2/ndf = " << parfit[0]->GetChisquare() << "/" << parfit[0]->GetNDF() << " = " << (parfit[0]->GetChisquare())/(parfit[0]->GetNDF()) << "):" << endl; cout << "- a0 = " << parfit[0]->GetParameter(0) << " ± " << parfit[0]->GetParError(0) << endl; cout << "- a1 = " << parfit[0]->GetParameter(1) << " ± " << parfit[0]->GetParError(1) << endl; cout << endl; stemp[0] = "rm ./plots/fitting_parA.*"; system(stemp[0].c_str()); stemp[0] = "./plots/fitting_parA.pdf"; c1->SaveAs(stemp[0].c_str()); // stemp[0] = "./plots/fitting_parA.C"; // c1->SaveAs(stemp[0].c_str()); mystyle->SetGraphColor(parB, 0); parB->SetMarkerStyle(20); parB->SetMarkerSize(0.8); mystyle->SetAxisTitles(parB, "SD zenith angle [sec(#theta)]", "Fitting parameter B [ns^{2}/m^{2}]"); c1->SetLogx(kFALSE); c1->SetLogy(kFALSE); parB->Draw("AP"); parfit[1] = new TF1("parfit1", "[0]+[1]*TMath::Power(x,-4)", 1.0, 2.0); parfit[1]->SetParameters(-0.1,0.1); parB->Fit("parfit1"); cout << endl << "Fitting parameters from sec(theta) vs B (chi2/ndf = " << parfit[1]->GetChisquare() << "/" << parfit[1]->GetNDF() << " = " << (parfit[1]->GetChisquare())/(parfit[1]->GetNDF()) << "):" << endl; cout << "- b0 = " << parfit[1]->GetParameter(0) << " ± " << parfit[1]->GetParError(0) << endl; cout << "- b1 = " << parfit[1]->GetParameter(1) << " ± " << parfit[1]->GetParError(1) << endl; cout << endl; stemp[0] = "rm ./plots/fitting_parB.*"; system(stemp[0].c_str()); stemp[0] = "./plots/fitting_parB.pdf"; c1->SaveAs(stemp[0].c_str()); // stemp[0] = "./plots/fitting_parB.C"; // c1->SaveAs(stemp[0].c_str()); mystyle->SetGraphColor(parN, 0); parN->SetMarkerStyle(20); parN->SetMarkerSize(0.8); mystyle->SetAxisTitles(parN, "SD zenith angle [sec(#theta)]", "Fitting parameter N"); c1->SetLogx(kFALSE); c1->SetLogy(kFALSE); parN->Draw("AP"); parfit[2] = new TF1("parfit2", "[0]+[1]*TMath::Power(x,2)+[2]*TMath::Exp(x)", 1.0, 2.0); parfit[2]->SetParameters(-0.1,-1.1,1.); parN->Fit("parfit2"); cout << endl << "Fitting parameters from sec(theta) vs N (chi2/ndf = " << parfit[2]->GetChisquare() << "/" << parfit[2]->GetNDF() << " = " << (parfit[2]->GetChisquare())/(parfit[2]->GetNDF()) << "):" << endl; cout << "- n0 = " << parfit[2]->GetParameter(0) << " ± " << parfit[2]->GetParError(0) << endl; cout << "- n1 = " << parfit[2]->GetParameter(1) << " ± " << parfit[2]->GetParError(1) << endl; cout << "- n2 = " << parfit[2]->GetParameter(2) << " ± " << parfit[2]->GetParError(2) << endl; cout << endl; stemp[0] = "rm ./plots/fitting_parN.*"; system(stemp[0].c_str()); stemp[0] = "./plots/fitting_parN.pdf"; c1->SaveAs(stemp[0].c_str()); // stemp[0] = "./plots/fitting_parN.C"; // c1->SaveAs(stemp[0].c_str()); ofs->close(); } delete ofs; if(sdBenchmark != 1) { // Convert risetimes into delta, using benchmark functions from before stemp[0] = "./benchmark_functions_en_" + ToString(energybins->at(2*energyref),2) + "-" + ToString(energybins->at(2*energyref+1),2) + ".txt"; ifs->open(stemp[0].c_str(), ifstream::in); } allcount = 0; allevts = 0; cout << "Converting risetimes into delta values" << endl; allDelta = new TGraphErrors(); energyVect.clear(); deltaVect.clear(); dtemp[6] = 0.; for(int iZen = 0; iZen < zenithnr; iZen++) { zenithlimit[0] = zenithbins->at(2*iZen); zenithlimit[1] = zenithbins->at(2*iZen+1); cout << "Chosen zenith angle limit = " << zenithlimit[0] << ", " << zenithlimit[1] << endl; if(sdBenchmark != 1) { for(int i = 0; i < 4; i++) *ifs >> dtemp[0]; for(int i = 0; i < 6; i++) *ifs >> fitparam[i]; cout << "Fitting parameters for benchmark function:" << endl; for(int i = 0; i < 3; i++) cout << "- fitparam[" << i << "] = " << fitparam[2*i] << " ± " << fitparam[2*i+1] << endl; cout << endl; } dtemp[0] = 0.; itemp[1] = 0; itemp[2] = 0; for(int i = 0; i < sdidVect->size(); i++) { goodrec = true; if(SecTheta(zenith->at(2*i),false) < zenithlimit[0]) goodrec = false; if(SecTheta(zenith->at(2*i),false) > zenithlimit[1]) goodrec = false; if(i == sdidVect->size()-1) { if(itemp[1] == 0) cout << "Error! No valid events found!" << endl; else { dtemp[1] = dtemp[1]/itemp[0]; dtemp[2] = TMath::Sqrt(dtemp[2])/itemp[0]; if(deltaVect[2*(allevts-1)] == dtemp[1]) cout << "Error! Last value already inserted!" << endl; else { cout << "Last: Delta value from " << itemp[0] << " SD stations for event " << allevts << " (evt " << itemp[2] << ") = " << dtemp[1] << " ± " << dtemp[2] << endl; // Save energy of the event energyVect.push_back(energy->at(2*i)); energyVect.push_back(energy->at(2*i+1)); // Save Delta of the event deltaVect.push_back(dtemp[1]); deltaVect.push_back(dtemp[2]); allevts++; if(TMath::Abs(dtemp[1]) > dtemp[6]) dtemp[6] = TMath::Abs(dtemp[1]); } } } if(goodrec) { // Calculate parameters A, B and N for the event if(sdBenchmark == 1) { CalculateSdFitParams(sdfitparam, fitparam, zenith->at(2*i), zenith->at(2*i+1)); cout << "Fitting parameters for benchmark function (from SD analysis):" << endl; for(int i = 0; i < 3; i++) cout << "- fitparam[" << i << "] = " << fitparam[2*i] << " ± " << fitparam[2*i+1] << endl; cout << endl; } // Check if this is already a new event or not // if(dtemp[0] != energy->at(2*i)) if(itemp[2] != eventVect->at(i)) { if(allcount > 0) { dtemp[1] = dtemp[1]/itemp[0]; dtemp[2] = TMath::Sqrt(dtemp[2])/itemp[0]; cout << "Delta value from " << itemp[0] << " SD stations for event " << allevts << " (evt " << itemp[2] << ") = " << dtemp[1] << " ± " << dtemp[2] << endl; // Save energy of the event energyVect.push_back(energy->at(2*i)); energyVect.push_back(energy->at(2*i+1)); // Save Delta of the event deltaVect.push_back(dtemp[1]); deltaVect.push_back(dtemp[2]); allevts++; if(TMath::Abs(dtemp[1]) > dtemp[6]) dtemp[6] = TMath::Abs(dtemp[1]); } itemp[0] = 0; dtemp[1] = 0.; dtemp[2] = 0.; cout << "New event (" << allevts << ")" << endl; } cout << "Event " << eventVect->at(i) << ", station " << sdidVect->at(i) << ", energy = " << energy->at(2*i)/1.e+18 << " ± " << energy->at(2*i+1)/1.e+18 << ", zenith = " << SecTheta(zenith->at(2*i),false) << " ± " << (TMath::Sin(zenith->at(2*i))*zenith->at(2*i+1))/TMath::Power(TMath::Cos(zenith->at(2*i)),2) << ", A = " << fitparam[0] << " ± " << fitparam[1] << ", B = " << fitparam[2] << " ± " << fitparam[3] << ", N = " << fitparam[4] << " ± " << fitparam[5] << endl; CalculateBenchmark(tbench, fitparam, distVect->at(2*i), distVect->at(2*i+1), HGsat->at(i)); // Benchmark function (HGsat) and its uncertainty // tbench = 40 + sqrt(A^2 + B*r^2) - A dtemp[3] = riseVect->at(2*i); dtemp[4] = riseVect->at(2*i+1); cout << itemp[0] << ": distance = " << distVect->at(2*i) << " ± " << distVect->at(2*i+1) << ", t_bench = " << tbench[0] << " ± " << tbench[1] << ", risetime = " << dtemp[3] << " ± " << dtemp[4] << ", delta = " << dtemp[3] - tbench[0] << " ± " << TMath::Sqrt(TMath::Power(dtemp[4],2) + TMath::Power(tbench[1],2)) << endl; // dtemp[1] += (dtemp[3] - tbench[0])/dtemp[4]; dtemp[1] += dtemp[3] - tbench[0]; dtemp[2] += TMath::Power(dtemp[4],2) + TMath::Power(tbench[1],2); itemp[0]++; itemp[1]++; allcount++; // dtemp[0] = energy->at(2*i); itemp[2] = eventVect->at(i); } } } cout << "Surviving a total of " << allcount << " deltas from " << allevts << " valid events." << endl; cerr << "Surviving a total of " << allcount << " deltas from " << allevts << " valid events." << endl; for(int i = 0; i < energyVect.size()/2; i++) { allDelta->SetPoint(i, energyVect[2*i]/1.e+18, deltaVect[2*i]); allDelta->SetPointError(i, energyVect[2*i+1]/1.e+18, deltaVect[2*i+1]); // cout << i << ": " << energyVect[2*i]/1.e+18 << " ± " << energyVect[2*i+1]/1.e+18 << ", " << deltaVect[2*i] << " ± " << deltaVect[2*i+1] << endl; } mystyle->SetGraphColor(allDelta, 0); allDelta->SetMarkerStyle(21); allDelta->SetMarkerSize(0.8); // mystyle->SetAxisTitles(allDelta, "SD energy (EeV)", "#Delta_{s}"); mystyle->SetAxisTitles(allDelta, "SD energy (EeV)", "t_{1/2} - t_{1/2}^{bench} (ns)"); c1->SetLogx(kTRUE); c1->SetLogy(kFALSE); allDelta->GetXaxis()->SetMoreLogLabels(kTRUE); allDelta->GetYaxis()->SetRange(-400., 500.); allDelta->GetYaxis()->SetRangeUser(-400., 500.); allDelta->Draw("AP"); c1->Update(); cout << TMath::Power(10.,energylimit[0])/1.e+18 << "\t" << TMath::Power(10.,energylimit[1])/1.e+18 << "\t" << gPad->GetUymin() << "\t" << gPad->GetUymax() << endl; line->DrawLine(TMath::Power(10.,energylimit[0])/1.e+18, gPad->GetUymin(), TMath::Power(10.,energylimit[0])/1.e+18, gPad->GetUymax()); line2->DrawLine(TMath::Power(10.,energylimit[1])/1.e+18, gPad->GetUymin(), TMath::Power(10.,energylimit[1])/1.e+18, gPad->GetUymax()); stemp[0] = "rm ./plots/delta_vs_energySD.pdf"; // BinNaming(&stemp[0], energylimit, zenithlimit); // stemp[0] += "*"; system(stemp[0].c_str()); stemp[1] = "./plots/delta_vs_energySD.pdf"; // BinNaming(&stemp[0], energylimit, zenithlimit); // stemp[1] = stemp[0] + ".pdf"; cout << stemp[1] << endl; c1->SaveAs(stemp[1].c_str()); stemp[1] = "./plots/delta_vs_energySD.C"; c1->SaveAs(stemp[1].c_str()); delete allDelta; delete adfile; if(sdBenchmark != 1) { ifs->close(); delete parfit[0]; delete parfit[1]; delete parfit[2]; delete parA; delete parB; delete parN; } delete ifs; delete mystyle; delete c1; } else { cerr << "Error! No input files supplied. Rerun program and add input files as arguments (ADST files)." << endl; return 1; } delete distVect; delete riseVect; delete sdidVect; delete energy; delete zenith; delete shwsize; delete HGsat; delete line; delete line2;*/ delete[] stemp; delete[] itemp; delete[] dtemp; return 0; }
[ "gasperkm@gmail.com" ]
gasperkm@gmail.com
65cd0db292111a2579d1bb414cda4b209d08c44a
0990f8898c00077ff97b41a147a1cae8f32a380a
/src/qt/splashscreen.cpp
4924e1cee3c857009dffb4f136caed4f369f2c85
[ "MIT" ]
permissive
TheUCoin/theucoin
12ddf35d29cd89e1b34afa4ca974383d85334967
886ed0cff8758e6e625ade8d52597d4cb03ec73a
refs/heads/master
2020-06-14T10:26:15.640967
2019-07-03T04:53:01
2019-07-03T04:53:01
194,981,049
0
0
null
null
null
null
UTF-8
C++
false
false
5,873
cpp
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "splashscreen.h" #include "clientversion.h" #include "init.h" #include "networkstyle.h" #include "ui_interface.h" #include "util.h" #include "version.h" #ifdef ENABLE_WALLET #include "wallet.h" #endif #include <QApplication> #include <QCloseEvent> #include <QDesktopWidget> #include <QPainter> SplashScreen::SplashScreen(Qt::WindowFlags f, const NetworkStyle* networkStyle) : QWidget(0, f), curAlignment(0) { // set reference point, paddings int paddingLeft = 14; int paddingTop = 400; int titleVersionVSpace = 17; int titleCopyrightVSpace = 32; float fontFactor = 1.0; // define text to place QString titleText = tr("TheUCoin Core"); QString versionText = QString(tr("Version %1")).arg(QString::fromStdString(FormatFullVersion())); QString copyrightTextBtc = QChar(0xA9) + QString(" 2009-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Bitcoin Core developers")); QString copyrightTextDash = QChar(0xA9) + QString(" 2014-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Dash Core developers")); QString copyrightTextPIVX = QChar(0xA9) + QString(" 2015-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The PIVX Core developers")); QString copyrightTextTUC = QChar(0xA9) + QString(" 2017-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The TheUCoin Core developers")); QString titleAddText = networkStyle->getTitleAddText(); QString font = QApplication::font().toString(); // load the bitmap for writing some text over it pixmap = networkStyle->getSplashImage(); QPainter pixPaint(&pixmap); pixPaint.setPen(QColor(100, 100, 100)); // check font size and drawing with pixPaint.setFont(QFont(font, 28 * fontFactor)); QFontMetrics fm = pixPaint.fontMetrics(); int titleTextWidth = fm.width(titleText); if (titleTextWidth > 160) { // strange font rendering, Arial probably not found fontFactor = 0.75; } pixPaint.setFont(QFont(font, 28 * fontFactor)); fm = pixPaint.fontMetrics(); //titleTextWidth = fm.width(titleText); pixPaint.drawText(paddingLeft, paddingTop, titleText); pixPaint.setFont(QFont(font, 15 * fontFactor)); pixPaint.drawText(paddingLeft, paddingTop + titleVersionVSpace, versionText); // draw copyright stuff pixPaint.setFont(QFont(font, 10 * fontFactor)); pixPaint.drawText(paddingLeft, paddingTop + titleCopyrightVSpace, copyrightTextBtc); pixPaint.drawText(paddingLeft, paddingTop + titleCopyrightVSpace + 12, copyrightTextDash); pixPaint.drawText(paddingLeft, paddingTop + titleCopyrightVSpace + 24, copyrightTextPIVX); pixPaint.drawText(paddingLeft, paddingTop + titleCopyrightVSpace + 36, copyrightTextTUC); // draw additional text if special network if (!titleAddText.isEmpty()) { QFont boldFont = QFont(font, 10 * fontFactor); boldFont.setWeight(QFont::Bold); pixPaint.setFont(boldFont); fm = pixPaint.fontMetrics(); int titleAddTextWidth = fm.width(titleAddText); pixPaint.drawText(pixmap.width() - titleAddTextWidth - 10, pixmap.height() - 25, titleAddText); } pixPaint.end(); // Set window title setWindowTitle(titleText + " " + titleAddText); // Resize window and move to center of desktop, disallow resizing QRect r(QPoint(), pixmap.size()); resize(r.size()); setFixedSize(r.size()); move(QApplication::desktop()->screenGeometry().center() - r.center()); subscribeToCoreSignals(); } SplashScreen::~SplashScreen() { unsubscribeFromCoreSignals(); } void SplashScreen::slotFinish(QWidget* mainWin) { Q_UNUSED(mainWin); hide(); } static void InitMessage(SplashScreen* splash, const std::string& message) { QMetaObject::invokeMethod(splash, "showMessage", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(message)), Q_ARG(int, Qt::AlignBottom | Qt::AlignHCenter), Q_ARG(QColor, QColor(100, 100, 100))); } static void ShowProgress(SplashScreen* splash, const std::string& title, int nProgress) { InitMessage(splash, title + strprintf("%d", nProgress) + "%"); } #ifdef ENABLE_WALLET static void ConnectWallet(SplashScreen* splash, CWallet* wallet) { wallet->ShowProgress.connect(boost::bind(ShowProgress, splash, _1, _2)); } #endif void SplashScreen::subscribeToCoreSignals() { // Connect signals to client uiInterface.InitMessage.connect(boost::bind(InitMessage, this, _1)); uiInterface.ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2)); #ifdef ENABLE_WALLET uiInterface.LoadWallet.connect(boost::bind(ConnectWallet, this, _1)); #endif } void SplashScreen::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.InitMessage.disconnect(boost::bind(InitMessage, this, _1)); uiInterface.ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2)); #ifdef ENABLE_WALLET if (pwalletMain) pwalletMain->ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2)); #endif } void SplashScreen::showMessage(const QString& message, int alignment, const QColor& color) { curMessage = message; curAlignment = alignment; curColor = color; update(); } void SplashScreen::paintEvent(QPaintEvent* event) { QPainter painter(this); painter.drawPixmap(0, 0, pixmap); QRect r = rect().adjusted(5, 5, -5, -5); painter.setPen(curColor); painter.drawText(r, curAlignment, curMessage); } void SplashScreen::closeEvent(QCloseEvent* event) { StartShutdown(); // allows an "emergency" shutdown during startup event->ignore(); }
[ "vric.team@gmail.com" ]
vric.team@gmail.com
4fc3659c5adc9b9b7fc3e603146b5e101b03214b
e4ba0ea5d3ae130338186fe94d5491cd35965b47
/cc/metrics/dropped_frame_counter.h
1fa5e318c7804bc53d76e49db7930e9d15f695cb
[ "BSD-3-Clause" ]
permissive
CesarMarcanoQ/chromium
e156dc7a2bee6d3a8b923f14a2e3c9a673420e41
c1516b70e49c4278614f34e76f7f6ded2b1fe921
refs/heads/master
2023-01-02T14:16:20.069180
2020-11-23T16:28:39
2020-11-23T16:28:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,133
h
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CC_METRICS_DROPPED_FRAME_COUNTER_H_ #define CC_METRICS_DROPPED_FRAME_COUNTER_H_ #include <stddef.h> #include <queue> #include <utility> #include "base/containers/ring_buffer.h" #include "cc/cc_export.h" #include "cc/metrics/frame_sorter.h" namespace cc { class TotalFrameCounter; struct UkmSmoothnessDataShared; // This class maintains a counter for produced/dropped frames, and can be used // to estimate the recent throughput. class CC_EXPORT DroppedFrameCounter { public: enum FrameState { kFrameStateDropped, kFrameStatePartial, kFrameStateComplete }; DroppedFrameCounter(); ~DroppedFrameCounter(); DroppedFrameCounter(const DroppedFrameCounter&) = delete; DroppedFrameCounter& operator=(const DroppedFrameCounter&) = delete; size_t frame_history_size() const { return ring_buffer_.BufferSize(); } size_t total_frames() const { return total_frames_; } size_t total_compositor_dropped() const { return total_dropped_; } size_t total_main_dropped() const { return total_partial_; } size_t total_smoothness_dropped() const { return total_smoothness_dropped_; } uint32_t GetAverageThroughput() const; typedef base::RingBuffer<FrameState, 180> RingBufferType; RingBufferType::Iterator begin() const { return ring_buffer_.Begin(); } RingBufferType::Iterator end() const { return ring_buffer_.End(); } void AddGoodFrame(); void AddPartialFrame(); void AddDroppedFrame(); void ReportFrames(); void OnBeginFrame(const viz::BeginFrameArgs& args); void OnEndFrame(const viz::BeginFrameArgs& args, bool is_dropped); void SetUkmSmoothnessDestination(UkmSmoothnessDataShared* smoothness_data); void OnFcpReceived(); // Reset is used on navigation, which resets frame statistics as well as // frame sorter. void Reset(); // ResetFrameSorter is used when we need to keep track of frame statistics // but not to track the frames prior to reset in frame sorter. void ResetFrameSorter(); void set_total_counter(TotalFrameCounter* total_counter) { total_counter_ = total_counter; } double sliding_window_max_percent_dropped() const { return sliding_window_max_percent_dropped_; } private: void NotifyFrameResult(const viz::BeginFrameArgs& args, bool is_dropped); base::TimeDelta ComputeCurrentWindowSize() const; const base::TimeDelta kSlidingWindowInterval = base::TimeDelta::FromSeconds(1); std::queue<std::pair<const viz::BeginFrameArgs, bool>> sliding_window_; uint32_t dropped_frame_count_in_window_ = 0; RingBufferType ring_buffer_; size_t total_frames_ = 0; size_t total_partial_ = 0; size_t total_dropped_ = 0; size_t total_smoothness_dropped_ = 0; bool fcp_received_ = false; double sliding_window_max_percent_dropped_ = 0; UkmSmoothnessDataShared* ukm_smoothness_data_ = nullptr; FrameSorter frame_sorter_; TotalFrameCounter* total_counter_ = nullptr; }; } // namespace cc #endif // CC_METRICS_DROPPED_FRAME_COUNTER_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
30923c2d97d1c430e003fc21db9523125fd813d9
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5769900270288896_0/C++/hec/b.cpp
ad07593d55e7798df889c35e971ea5abe7816201
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
1,633
cpp
#include <bits/stdc++.h> using namespace std; inline int toInt(string s) {int v; istringstream sin(s);sin>>v;return v;} template<class T> inline string toString(T x) {ostringstream sout;sout<<x;return sout.str();} template<class T> inline T sqr(T x) {return x*x;} typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<string> vs; typedef pair<int, int> pii; typedef long long ll; #define all(a) (a).begin(),(a).end() #define rall(a) (a).rbegin(), (a).rend() #define pb push_back #define mp make_pair #define each(i,c) for(typeof((c).begin()) i=(c).begin(); i!=(c).end(); ++i) #define exist(s,e) ((s).find(e)!=(s).end()) #define range(i,a,b) for(int i=(a);i<(b);++i) #define rep(i,n) range(i,0,n) #define clr(a,b) memset((a), (b) ,sizeof(a)) #define dump(x) cerr << #x << " = " << (x) << endl; #define debug(x) cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" << " " << __FILE__ << endl; const double eps = 1e-10; const double pi = acos(-1.0); const ll INF =1LL << 62; const int inf =1 << 29; int r,c,n; int appart[16][16]; int main(void){ int TestCase; cin >> TestCase; range(Number,1,TestCase+1){ cin >> r >> c >> n; int ans=inf; rep(mask,1<<(r*c)){ if(__builtin_popcount(mask)!=n) continue; rep(i,r*c){ if(mask&(1<<i)) appart[i/c][i%c]=1; else appart[i/c][i%c]=0; } int cur=0; rep(i,r)rep(j,c){ if(i+1<r&&appart[i][j]&&appart[i+1][j]) cur++; if(j+1<c&&appart[i][j]&&appart[i][j+1]) cur++; } ans=min(ans,cur); } cout << "Case #"<< Number << ": "; cout << ans << endl; } return 0; }
[ "eewestman@gmail.com" ]
eewestman@gmail.com
deffaf3052bcb0c1317ed606dab69028a07abb7c
9934512da4a541a3e6654dd3a71512df9a9bfe14
/AGM6/sensor.cpp
1b1ffa22dba06c35dd53bd78be740bd99baaea2d
[]
no_license
missiondesignsolutions/CADAC
a534eda151c6d8d3afba8e5d48d60201a2a591ff
8aa2f73e551554a48abeac5416d1ec3a34ae660f
refs/heads/main
2023-05-01T04:32:40.710534
2021-05-24T07:44:03
2021-05-24T07:44:03
370,660,263
3
1
null
2021-05-25T10:55:36
2021-05-25T10:55:36
null
UTF-8
C++
false
false
24,312
cpp
/////////////////////////////////////////////////////////////////////////////// //FILE: 'sensor.cpp' // //Contains 'sensor' module of class 'Missile' // //011221 Created from FORTRAN code SRAAM6 by Peter H Zipfel //030410 Upgraded to SM Item32, PZi //081007 Modified for GENSIM6, PZi /////////////////////////////////////////////////////////////////////////////// #include "class_hierarchy.hpp" using namespace std; /////////////////////////////////////////////////////////////////////////////// //Definition of 'sensor' module-variables //Member function of class 'Missile' //Module-variable locations are assigned to missile[200-299] // //Defining and initializing module-variables // includes also target variables downloaded from 'combus' // and placed into reserved location missile[0-9] (used here and in 'guidance' module) // // mseek = 0: Sensor turned off // 2: Sensor enabled (input,or set internally if break-lock occured) // 3: Acquis. mode (set internally, when missile is within 'racq') // 4: Sensor lock-on (set internally, when 'dtimac' has elapsed) // 5: Sensor within blind range (set internally). Output held const // // skr_dyn = 0 kinematic sensor // 1 dynamic sensor // //020607 Created by Peter H Zipfel //081007 Modified for GENSIM6, PZi /////////////////////////////////////////////////////////////////////////////// void Missile::def_sensor() { //Definition and initialization of module-variables missile[1].init("tgt_num","int",0,"Target tail # attacked by 'this' missile","combus","data",""); missile[2].init("STEL",0,0,0,"Position of target#, downloaded from 'combus' - m","combus","",""); missile[3].init("VTEL",0,0,0,"Velocity of target#, downloaded from 'combus' - m","combus","",""); missile[5].init("tgt_com_slot","int",0,"'This' target slot in combus - ND","combus","out",""); missile[200].init("mseek","int",0,"See table in module 'sensor'","sensor","data/diag","com"); missile[201].init("skr_dyn","int",0,"=0: Kinemtic, =1:Dynamic","sensor","data",""); missile[202].init("isets1","int",0,"Sensor flag","sensor","init",""); missile[203].init("epchac",0,"Epoch of start of sensor acquisition - s","sensor","init",""); missile[204].init("ibreak","int",0,"Flag for sensor break-lock ND","sensor","init",""); missile[206].init("dblind",0,"Blind range - m","sensor","data",""); missile[233].init("racq",0,"Acquisition range - m","sensor","data",""); missile[234].init("dtimac",0,"Target acquisition time - s","sensor","data",""); missile[250].init("gk",0,"K.F. gain - 1/s","sensor","data",""); missile[251].init("zetak",0,"K.F. damping","sensor","data",""); missile[252].init("wnk",0,"K.F. natural frequency - rad/s","sensor","data",""); missile[253].init("biast",0,"Pitch gimbal bias errors - rad","sensor","data",""); missile[254].init("randt",0,"Pitch gimbal random errors - rad","sensor","data",""); missile[255].init("biasp",0,"Roll gimbal bias error - rad","sensor","data",""); missile[256].init("randp",0,"Roll gimbal bias error - rad","sensor","data",""); missile[257].init("wlq1d",0,"Pitch sight line spin derivative - rad/s^2","sensor","state",""); missile[258].init("wlq1",0,"Pitch sight line spin - rad/s","sensor","state",""); missile[259].init("wlqd",0,"Pitch pointing rate derivative - rad/s^2","sensor","state",""); missile[260].init("wlq",0,"Pitch pointing rate - rad/s","sensor","state",""); missile[261].init("wlr1d",0,"Yaw sight line spin derivative - rad/s^2","sensor","state",""); missile[262].init("wlr1",0,"Yaw sight line spin - rad/s","sensor","state",""); missile[263].init("wlrd",0,"Yaw pointing rate derivative - rad/s^2","sensor","state",""); missile[264].init("wlr",0,"Yaw pointing rate - rad/s","sensor","state",""); missile[265].init("wlq2d",0,"Second state variable deriv in K.F. - rad/s^3","sensor","state",""); missile[266].init("wlq2",0,"Second state variable in K.F. - rad/s^2","sensor","state",""); missile[267].init("wlr2d",0,"Second state variable der in K.F. - rad/s^3","sensor","state",""); missile[268].init("wlr2",0,"Second state variable in K.F. - rad/s^2","sensor","state",""); missile[269].init("fovyaw",0,"Half yaw field-of-view at acquisition - rad","sensor","data",""); missile[270].init("fovpitch",0,"Half positive pitch field-of-view at acquis. - rad","sensor","data",""); missile[271].init("dba",0,"Distance between active sensor and its aimpoint - m","sensor","diag",""); missile[272].init("daim",0,"Dist from targ to initiate aimpoint mode - m","sensor","data",""); missile[273].init("BIASAI",0,0,0,"Bias error of aimpoint mode in target coor - m","sensor","data",""); missile[274].init("BIASSC",0,0,0,"Bias error of hot spot mode in target coor - m","sensor","data",""); missile[275].init("RANDSC",0,0,0,"Random error of hot spot mode in targ coor - m","sensor","data",""); missile[276].init("epy",0,"Error of pointing in pitch - rad","sensor","diag","plot"); missile[278].init("epz",0,"Error of pointing in yaw - rad","sensor","diag","plot"); missile[279].init("thtpb",0,"Pitch pointing angle - rad","sensor","out","plot"); missile[280].init("psipb",0,"Yaw pointing angle - rad","sensor","out","plot"); missile[281].init("ththb",0,"Head pitch angle - rad","sensor","diag","plot"); missile[282].init("phihb",0,"Head roll angle - rad","sensor","diag","plot"); missile[283].init("TPB",0,0,0,0,0,0,0,0,0,"I/G TM of pointing axes wrt body axes","sensor","init",""); missile[284].init("THB",0,0,0,0,0,0,0,0,0,"I/G TM of head axes wrt body axes","sensor","init",""); missile[285].init("dvbtc",0,"Closing velocity computed by INS - m/s","sensor","diag",""); missile[286].init("EAHH",0,0,0,"Aimpoint displacement wrt center of F.P. - rad","sensor","diag","plot"); missile[287].init("EPHH",0,0,0,"Computer pointing error of sensor wrt center of F.P.","sensor","diag",""); missile[288].init("EAPH",0,0,0,"Aimpoint to computer pointing displacement - rad","sensor","diag",""); missile[289].init("thtpbx",0,"Pitch pointing angle - deg","sensor","diag",""); missile[290].init("psipbx",0,"Yaw pointing angle - deg","sensor","diag",""); missile[291].init("sigdpy",0,"Pitch sight line spin - rad/s","sensor","out","plot"); missile[292].init("sigdpz",0,"Yaw sight line spin - rad/s","sensor","out","plot"); missile[293].init("biaseh",0,"Image blur and pixel bias errors - rad","sensor","data",""); missile[294].init("randeh",0,"Image blur and pixel random errors - rad","sensor","data",""); missile[295].init("SBTL",0,0,0,"True missile wrt target displacement - m","sensor","diag","scrn"); missile[296].init("epaz_saved",0,"Saving Markov az-error - rad","sensor","save",""); missile[297].init("epel_saved",0,"Saving Markov el-error - rad","sensor","save",""); missile[298].init("range_saved",0,"Saving Markov range-error - m","sensor","save",""); missile[299].init("rate_saved",0,"Saving Markov range-rate-error - m/s","sensor","save",""); } /////////////////////////////////////////////////////////////////////////////// //Sensor module //Member function of class 'Missile' // // mseek = 0: Sensor turned off // 2: Sensor enabled (input,or set internally if break-lock occurred) // 3: Acquis. mode (set internally, when missile is within 'racq') // 4: Sensor lock-on (set internally, when 'dtimac' has elapsed) // 5: Sensor within blind range (set internally). Output held const // // skr_dyn = 0 kinematic sensor // 1 dynamic sensor // // Notes: // (1) Value of 'racq' determines whether Sensor is locked-on before (LOBL) or after launch // For LOBL, the time delay 'dtimac' represents the sensor lock-out time // // (2) The target states are subscribed from 'combus'. They must be located in // the 'combus Packet' at the following positions: STEL @ 2 and VTEL @ 3. // They are loaded into 'missile[2]' and 'missile[3]' for further use in 'this' missile // //020605 Created by Peter H Zipfel //021115 Incorporated IIR sensor, PZi //081007 Modified for GENSIM6, PZi /////////////////////////////////////////////////////////////////////////////// void Missile::sensor(Packet *combus,int num_vehicles,double sim_time,double int_step) { //local variables Variable *data_t; double sigdy(0),sigdz(0); double ehz(0),ehy(0); //local module-variables double dbt(0),dbtk(0); Matrix STEL(3,1); Matrix VTEL(3,1); Matrix SBTL(3,1); int tgt_com_slot(0); Matrix TTL(3,3);TTL.identity(); //shortcut, eventually should be subsribed from 'combus' double psipb(0),thtpb(0); double sigdpy(0),sigdpz(0); double ththb(0),phihb(0); double psiot1(0),thtot1(0); double psipbx(0),thtpbx(0); //localizing module-variables //input data int tgt_num=missile[1].integer(); int mseek=missile[200].integer(); int skr_dyn=missile[201].integer(); int isets1=missile[202].integer(); double fovlimx=missile[232].real(); double racq=missile[233].real(); double dtimac=missile[234].real(); double fovyaw=missile[269].real(); double fovpitch=missile[270].real(); double racq_irs=missile[806].real(); double fovyawx_irs=missile[807].real(); double fovpitchx_irs=missile[808].real(); //getting saved value double epchac=missile[203].real(); double timeac=missile[238].real(); Matrix THB=missile[284].mat(); //input from other modules double time=flat6[0].real(); Matrix SBEL=flat6[219].vec(); int trcond=missile[180].integer(); int mguid=missile[400].integer(); //------------------------------------------------------------------------- //downloading from 'combus' target variables //building target id = t(j+1) char number[4]; sprintf(number,"%i",tgt_num); string target_id="t"+string(number); //finding slot 'i' of target in 'combus' (same as in 'vehicle_list') for(int i=0;i<num_vehicles;i++) { string id=combus[i].get_id(); if (id==target_id) { //downloading data from target packet tgt_com_slot=i; data_t=combus[i].get_data(); STEL=data_t[2].vec(); VTEL=data_t[3].vec(); } } //IIR gimbaled sensor //target aspect angles SBTL=SBEL-STEL; Matrix SBTT=TTL*SBTL; Matrix POLAR=SBTT.pol_from_cart(); dbtk=POLAR.get_loc(0,0); psiot1=POLAR.get_loc(1,0); thtot1=POLAR.get_loc(2,0); //sensor is enabled if(mseek==2){ //within acquisition range isets1=1; if(dbtk<racq) mseek=3; } //sensor in acquisition mode if(mseek==3){ //initializing TM matrix, state variables and time counter if(isets1==1){ sensor_ir_kin(thtpb,psipb,sigdy,sigdz, SBTL,VTEL,dbtk); sensor_ir_uthpb(ththb,phihb, psipb,thtpb); THB=sensor_ir_thb(ththb,phihb); isets1=0; epchac=time; } //acquisition(for dynamic sensor, target must be in field-of-view) if(skr_dyn==1){ sensor_ir_dyn(mseek,mguid,thtpb,psipb,sigdy,sigdz,ehz,ehy,THB,trcond, SBTL,dbtk,int_step); timeac=time-epchac; if(timeac>dtimac){ if((fabs(ehz)<=fovyaw)&&(fabs(ehy)<=fovpitch)) mseek=4; else trcond=5; } } else{ sensor_ir_kin(thtpb,psipb,sigdy,sigdz, SBTL,VTEL,dbtk); timeac=time-epchac; if(timeac>dtimac) mseek=4; } } //sensor lock-on (dynamic or kinematic) if(mseek==4){ if(skr_dyn==1){ sensor_ir_dyn(mseek,mguid,thtpb,psipb,sigdy,sigdz,ehz,ehy,THB,trcond, SBTL,dbtk,int_step); } else{ sensor_ir_kin(thtpb,psipb,sigdy,sigdz, SBTL,VTEL,dbtk); } //LOS rate output to the guidance module sigdpy=sigdy; sigdpz=sigdz; } thtpbx=thtpb*DEG; psipbx=psipb*DEG; //------------------------------------------------------------------------- //loading module-variables //output to other modules missile[2].gets_vec(STEL); missile[3].gets_vec(VTEL); missile[5].gets(tgt_com_slot); missile[180].gets(trcond); //output to other modules //IIR sensor missile[279].gets(thtpb); missile[280].gets(psipb); missile[291].gets(sigdpy); missile[292].gets(sigdpz); missile[400].gets(mguid); //saving value for next cycle missile[203].gets(epchac); missile[238].gets(timeac); missile[284].gets_mat(THB); //diagnostics missile[200].gets(mseek); missile[202].gets(isets1); missile[237].gets(dbtk); missile[289].gets(thtpbx); missile[290].gets(psipbx); missile[295].gets_vec(SBTL); } /////////////////////////////////////////////////////////////////////////////// //Kinematic sensor //Member function of class 'Missile' // (1) Calculates error free LOS rates and angles // (2) Also used to initialize the dynamic sensor subroutine // // Argument Output: // thtpb=Pitch pointing angle - rad // psipb=Yaw pointing angle - rad // sigdy=Pitch sight line spin - rad/s // sigdpz=Yaw sight line spin - rad/s // Argument Input: // SBTL(3)=Position of missile wrt target - m // VTEL(3)=Target velocity vector - m/s // dbtk=Distance between missile and target - m // //011221 Converted from SRAAM6 by Peter Zipfel /////////////////////////////////////////////////////////////////////////////// void Missile::sensor_ir_kin(double &thtpb,double &psipb,double &sigdy,double &sigdz, Matrix SBTL,Matrix VTEL,double dbtk) { //local module-variables double dvbtc=0; //localizing module-variables //from other modules Matrix TBL=flat6[120].mat(); Matrix VBEL=flat6[233].vec(); //------------------------------------------------------------------------- //LOS kinematics Matrix STBL=SBTL*(-1); Matrix STBB=TBL*STBL; Matrix UTBL=STBL/dbtk; //relative velocity Matrix VTBL=VTEL-VBEL; //closing velocity dvbtc=fabs(UTBL^VTBL); //LOS rate output in body coordinates Matrix WOEB=TBL*UTBL.skew_sym()*VTBL/dbtk; //building pointing wrt body T.M. Matrix POLAR=STBB.pol_from_cart(); psipb=POLAR.get_loc(1,0); thtpb=POLAR.get_loc(2,0); Matrix TPB=mat2tr(psipb,thtpb); //LOS rate output in pointing coordinates Matrix WOEP=TPB*WOEB; sigdy=WOEP.get_loc(1,0); sigdz=WOEP.get_loc(2,0); //------------------------------------------------------------------------- //loading module-variables //diagnostics missile[274].gets(dvbtc); } /////////////////////////////////////////////////////////////////////////////// //IIR sensor function //Member function of class 'Missile' // (1) Given true target relative geometry it determines inertial // LOS rates in pitch and yaw, corrupted by these errors: // Target Scintillation // Blur, pixel quatization and bias // Gimbal dynamics, quantization and bias // (2) Determines Aimpoint off-set from computer determined sensor axis // in Focal Plane (F.P.) array EAPH(3) // (3) Models Kalman Filter dynamics (generates inertial LOS rates) // (4) Models strap-down gyro feedback and gimbal kinematics // (5) Allows for aimpoint selection and correction. // // Argument Output: // mseek: If break lock occured reset to 2 (acquisition) // mguid: If break lock occured reset to 2 (midcourse) // thtpb= Pitch pointing angle - rad // psipb= Yaw pointing angle - rad // sigdy= Pitch sight line spin - rad/s // sigdz= Yaw sight line spin - rad/s // ehz= Yaw sensor error angle - rad // ehy= Pitch sensor error angle - rad // THB(3,3)= Transf matrix of head wrt body axes // Argument Input: // SBTL(3)= Position of missile wrt target - m // dbtk= Distance between missile and target - m // int_step= Integration step size - s // //020102 Converted from SRAAM6 by Peter Zipfel //100526 Corrected 'trcond' pass-through, PZi /////////////////////////////////////////////////////////////////////////////// void Missile::sensor_ir_dyn(int &mseek,int &mguid,double &thtpb,double &psipb,double &sigdy, double &sigdz,double &ehz,double &ehy,Matrix &THB,int &trcond, Matrix SBTL, double dbtk,double int_step) { //local variables Matrix EAPP(3,1); Matrix U1PP(3,1),U1HH(3,1); Matrix WBEP(3,1); double thtpbd,psipbd; double ththbc,phihbc,phihbd; //local module-variables double epz(0),epy(0); double ththb(0),phihb(0); Matrix EAHH(3,1); Matrix EPHH(3,1); Matrix EAPH(3,1); //localizing module-variables //input data int ibreak=missile[204].integer(); double dblind=missile[206].real(); double gk=missile[250].real(); double zetak=missile[251].real(); double wnk=missile[252].real(); double biast=missile[253].real(); double randt=missile[254].real(); double biasp=missile[255].real(); double randp=missile[256].real(); double biaseh=missile[293].real(); double randeh=missile[294].real(); //initialization Matrix TPB=missile[283].mat(); //input from other modules double trtht=missile[187].real(); double trthtd=missile[189].real(); double trphid=missile[190].real(); double trate=missile[191].real(); Matrix TBL=flat6[120].mat(); Matrix TTL=missile[3].mat(); Matrix WBECB=missile[306].vec(); //state variables double wlq1d=missile[257].real(); double wlq1=missile[258].real(); double wlqd=missile[259].real(); double wlq=missile[260].real(); double wlr1d=missile[261].real(); double wlr1=missile[262].real(); double wlrd=missile[263].real(); double wlr=missile[264].real(); double wlq2d=missile[265].real(); double wlq2=missile[266].real(); double wlr2d=missile[267].real(); double wlr2=missile[268].real(); //diagnostic double time=flat6[0].real(); //------------------------------------------------------------------------- //aimpoint modulation Matrix THL=THB*TBL; Matrix SBTH=THL*SBTL; Matrix SATH=sensor_ir_aimp(THL,TTL,dbtk); Matrix SABH=SATH-SBTH; //error angles double sabh1=SABH.get_loc(0,0); double sabh2=SABH.get_loc(1,0); double sabh3=SABH.get_loc(2,0); double ey=atan2(-sabh3,sabh1); double ez=atan2(sabh2,sabh1); //error angle corrupted by blur and bias ehy=ey+biaseh+randeh; ehz=ez+biaseh+randeh; EAHH.build_vec3(0,ehz,-ehy); //T.M. matrices Matrix TBH=THB.trans();//THB of previous integration cycle is used Matrix TPH=TPB*TBH; Matrix THP=TPH.trans(); //pointing error angles U1PP.build_vec3(1,0,0); U1HH.build_vec3(1,0,0); EPHH=THP*U1PP-U1HH; EAPH=EAHH-EPHH; EAPP=TPH*EAPH; epy=-EAPP.get_loc(2,0); epz=EAPP.get_loc(1,0); //sight line spin estimator (kalman filter represented by 2nd order lag) double wsq=wnk*wnk; double gg=gk*wsq; //yaw channel double wlr1d_new=wlr2; wlr1=integrate(wlr1d_new,wlr1d,wlr1,int_step); wlr1d=wlr1d_new; double wlr2d_new=gg*epz-2.*zetak*wnk*wlr1d-wsq*wlr1; wlr2=integrate(wlr2d_new,wlr2d,wlr2,int_step); wlr2d=wlr2d_new; //pitch channel double wlq1d_new=wlq2; wlq1=integrate(wlq1d_new,wlq1d,wlq1,int_step); wlq1d=wlq1d_new; double wlq2d_new=gg*epy-2.*zetak*wnk*wlq1d-wsq*wlq1; wlq2=integrate(wlq2d_new,wlq2d,wlq2,int_step); wlq2d=wlq2d_new; //output to guidance module: LOS rates in pointing coord sigdz=wlr1; sigdy=wlq1; //look angle control WBEP=TPB*WBECB; double wbep2=WBEP.get_loc(1,0); double wbep3=WBEP.get_loc(2,0); //yaw channel double wlrd_new=wlr1-wbep3; wlr=integrate(wlrd_new,wlrd,wlr,int_step); wlrd=wlrd_new; psipb=wlr; psipbd=wlrd; //pitch channel double wlqd_new=wlq1-wbep2; wlq=integrate(wlqd_new,wlqd,wlq,int_step); wlqd=wlqd_new; thtpb=wlq; thtpbd=wlqd; //calculating the TPB matrix TPB=mat2tr(psipb,thtpb); //caculating gimbal dynamics and THB for the next integration cycle sensor_ir_uthpb(ththbc,phihbc,psipb,thtpb); ththb=ththbc+biast+randt; phihb=phihbc+biasp+randp; THB=sensor_ir_thb(ththb,phihb); //flagging break-lock and blind range conditions if(mseek==4){ ibreak=0; phihbd=-thtpbd*sin(psipb); double eh=sqrt(ehy*ehy+ehz*ehz); if(fabs(ththb)>trtht){ trcond=6; ibreak=1; } else if(fabs(thtpbd)>trthtd){ trcond=7; ibreak=1; } else if(fabs(phihbd)>trphid){ trcond=8; ibreak=1; } else if(eh>trate){ trcond=9; ibreak=1; } if(ibreak==1){ mseek=2; mguid=40; } if(dbtk<dblind) mseek=5; } //------------------------------------------------------------------------- //loading module-variables //state variables missile[257].gets(wlq1d); missile[258].gets(wlq1); missile[259].gets(wlqd); missile[260].gets(wlq); missile[261].gets(wlr1d); missile[262].gets(wlr1); missile[263].gets(wlrd); missile[264].gets(wlr); missile[265].gets(wlq2d); missile[266].gets(wlq2); missile[267].gets(wlr2d); missile[268].gets(wlr2); //diagnostics // missile[234].gets(dba); missile[276].gets(epy); missile[278].gets(epz); missile[281].gets(ththb); missile[282].gets(phihb); missile[283].gets_mat(TPB); missile[286].gets_vec(EAHH); missile[287].gets_vec(EPHH); missile[288].gets_vec(EAPH); } /////////////////////////////////////////////////////////////////////////////// //Aimpoint selection and corruption function //Member function of class 'Missile' // (1) Introduces aimpoint tracking errors // (2) Introduces hot spot jitter and bias errors // Both are initiated at distance 'daim' from the target // // Return output: // SATH(3)=Aimpoint error in head axes (focal plane array) // // Argument input: // THL(3,3)=Tran Matrix of head wrt local level axes // dbtk=Distance of vehicle wrt target - m // //020102 Converted from SRAAM6 by Peter Zipfel /////////////////////////////////////////////////////////////////////////////// Matrix Missile::sensor_ir_aimp(Matrix THL,Matrix TTL,double dbtk) { //local variables Matrix SATH(3,1); Matrix THT(3,3); //localizing module-variables //input data double daim=missile[272].real(); Matrix BIASAI=missile[273].vec(); Matrix BIASSC=missile[274].vec(); Matrix RANDSC=missile[275].vec(); //from other modules //------------------------------------------------------------------------- THT=THL*TTL.trans(); if(dbtk<daim) //aimpoint update SATH=THT*BIASAI; else //hot spot mode SATH=THT*(BIASSC+RANDSC); return SATH; //------------------------------------------------------------------------- } /////////////////////////////////////////////////////////////////////////////// //Angle conversion function //Member function of class 'Missile' // Converts pointing angles (computer) to head angles (gimbals) // // Argument Output: // ththb=Gimbal head pitch angle - rad // phihb=Gimbal roll angle - rad // // Argument Input: // psipb=Yaw computer pointing angle - rad // thtpb=Pitch computer pointing angle - rad // //020102 Converted from SRAAM6 by Peter Zipfel /////////////////////////////////////////////////////////////////////////////// void Missile::sensor_ir_uthpb(double &ththb,double &phihb, double psipb,double thtpb) { //local variables double sinpsi,tantht; //------------------------------------------------------------------------- ththb=acos(cos(thtpb)*cos(psipb)); sinpsi=sin(psipb); tantht=tan(thtpb); if(fabs(sinpsi)&&fabs(tantht)<SMALL) phihb=0.; else phihb=atan2(sinpsi,tantht); //------------------------------------------------------------------------- } /////////////////////////////////////////////////////////////////////////////// //THB tranformation matrix function //Member function of class 'Missile' // Calculates T.M. of head axes wrt body axes // Argument Output // THB=Transformation matrix of head angles wrt missile body axes // Argument Input: // ththb=Gimbal head pitch angle - rad // phihb=Gimbal roll angle - rad // //020102 Converted from SRAAM6 by Peter Zipfel ///////////////////////////////////////////////////////////////////////////////// Matrix Missile::sensor_ir_thb(double tht,double phi) { //local variables Matrix THB(3,3); //------------------------------------------------------------------------- THB.assign_loc(0,0,cos(tht)); THB.assign_loc(2,0,sin(tht)); THB.assign_loc(1,1,cos(phi)); THB.assign_loc(1,2,sin(phi)); THB.assign_loc(0,1,THB.get_loc(2,0)*THB.get_loc(1,2)); THB.assign_loc(0,2,(-THB.get_loc(2,0))*THB.get_loc(1,1)); THB.assign_loc(2,1,(-THB.get_loc(0,0))*THB.get_loc(1,2)); THB.assign_loc(2,2,THB.get_loc(0,0)*THB.get_loc(1,1)); THB.assign_loc(1,0,0.); return THB; //------------------------------------------------------------------------- }
[ "rads2995@gmail.com" ]
rads2995@gmail.com
c7a37c626f7c9e94c2bacd3c02c87e3a875171b7
9424d6b5b8ec0c803a233518ff564400d65bbe3a
/src/particle_filter.cpp
52625ad0f67a7a3b007b8333b865402040955873
[]
no_license
cipher982/CarND-Kidnapped-Vehicle-Project
41eebeb3a55a0ac90f2c7d610f13f963444a9bc3
4e0875e1f3d6694a999856f657c6feada34229d2
refs/heads/master
2021-08-23T11:18:19.643464
2017-12-04T17:14:05
2017-12-04T17:14:05
112,524,269
0
0
null
null
null
null
UTF-8
C++
false
false
10,649
cpp
/* * particle_filter.cpp * * Created on: Dec 12, 2016 * Author: Tiffany Huang */ #include <random> #include <algorithm> #include <iostream> #include <numeric> #include <math.h> #include <iostream> #include <sstream> #include <string> #include <iterator> #include "particle_filter.h" using namespace std; void ParticleFilter::init(double x, double y, double theta, double std[]) { // TODO: Set the number of particles. Initialize all particles to first position (based on estimates of // x, y, theta and their uncertainties from GPS) and all weights to 1. // Add random Gaussian noise to each particle. // NOTE: Consult particle_filter.h for more information about this method (and others in this file). num_particles = 50; cout << "Start - init" << endl; default_random_engine gen; normal_distribution<double> x_gauss(x, std[0]); normal_distribution<double> y_gauss(y, std[1]); normal_distribution<double> theta_gauss(theta, std[2]); for (int i = 0; i < num_particles; ++i) { cout << "init - num_particles loop" << endl; cout << "init - i:" << i << endl; cout << "init - x:" << x_gauss << endl; cout << "init - y:" << y_gauss << endl; cout << "init - theta:" << theta_gauss << endl; Particle particle; particle.id = i; particle.x = x_gauss(gen); particle.y = y_gauss(gen); particle.theta = theta_gauss(gen); particle.weight = 1.0; weights.push_back(1.0); particles.push_back(particle); } is_initialized = true; return; } void ParticleFilter::prediction(double delta_t, double std_pos[], double velocity, double yaw_rate) { // TODO: Add measurements to each particle and add random Gaussian noise. // NOTE: When adding noise you may find std::normal_distribution and std::default_random_engine useful. // http://en.cppreference.com/w/cpp/numeric/random/normal_distribution // http://www.cplusplus.com/reference/random/default_random_engine/ cout << "======================= Start - prediction =======================" << endl; for (int i = 0; i < num_particles; ++i) { // if no yaw (driving straight): if (fabs(yaw_rate) == 0) { // use formulas from lessons particles[i].x += velocity * delta_t * cos(particles[i].theta); // cos > adjacent > x particles[i].y += velocity * delta_t * sin(particles[i].theta); // sin > opposite > y particles[i].theta = 0; // going straight } // if yaw (steering/turning front wheels): else { particles[i].x += velocity/yaw_rate * (sin(particles[i].theta + (yaw_rate * delta_t)) - sin(particles[i].theta)); particles[i].y += velocity/yaw_rate * (cos(particles[i].theta) - cos(particles[i].theta + (yaw_rate * delta_t))); particles[i].theta += yaw_rate * delta_t; } cout << "prediction - x: " << particles[i].x << endl; cout << "prediction - y: " << particles[i].y << endl; cout << "prediction - theta: " << particles[i].theta << endl; } } void ParticleFilter::dataAssociation(std::vector<LandmarkObs> predicted, std::vector<LandmarkObs>& observations) { // TODO: Find the predicted measurement that is closest to each observed measurement and assign the // observed measurement to this particular landmark. // NOTE: this method will NOT be called by the grading code. But you will probably find it useful to // implement this method and use it as a helper during the updateWeights phase. std:vector<LandmarkObs> closest_landmarks; LandmarkObs closest; double big_start = 9007199254740991; // big number! cout << "======================= Start - dataAssociation =======================" << endl; for (int i = 0; i < observations.size(); i++){ int current_j; double current_smallest_distance = big_start; //cout << "first ass loop" << endl; for (int j = 0; j < predicted.size(); j++) { //cout << "second j ass loop" << endl; double distance = dist(observations[i].x,observations[i].y,predicted[j].x,predicted[j].y); cout << "Ix["<< j << "] Transformed Obs: = (" << observations[i].x << "," << observations[i].y << ")"; cout << " Landmark Seen = (" << predicted[i].x << "," << predicted[i].y << ")"; cout << " Distance = " << distance << "(" << current_smallest_distance << ")"; if (distance < current_smallest_distance) { cout << " shorter!" << endl; //cout << "previous distance: " << current_smallest_distance << endl; //cout << "new smallest distance: " << distance << endl; current_j = j; current_smallest_distance = distance; //closest = predicted[j]; } else { cout << endl;} } //cout << "before observations[i]" << endl; observations[i].id = current_j; //cout << "after observations[i]" << endl; } } void ParticleFilter::updateWeights(double sensor_range, double std_landmark[], const std::vector<LandmarkObs> &observations, const Map &map_landmarks) { double sigma_x = std_landmark[0]; double sigma_y = std_landmark[1]; cout << "======================= Start - updateWeights =======================" << endl; for (int i = 0; i < particles.size(); ++i) { // simpler to call p instead of this index Particle p = particles[i]; // transform (translate / rotate) observations from particle POV to Map POV std::vector<LandmarkObs> transformed_observations; // for( auto it = x.begin(); it != x.end(); i++) for (auto& observation: observations) { LandmarkObs transformed_observation; // to hold transformed observation transformed_observation.x = p.x + (observation.x * cos(p.theta)) - (observation.y * sin(p.theta)); transformed_observation.y = p.y + (observation.x * sin(p.theta)) + (observation.y * cos(p.theta)); transformed_observation.id = observation.id; transformed_observations.push_back(transformed_observation); } // gather all landmarks that can be seen by the particle std::vector<LandmarkObs> landmarks_seen; for (auto& landmark: map_landmarks.landmark_list) { double distance = dist(p.x, p.y, landmark.x_f, landmark.y_f); //cout << "Distance is:================================== " << distance << endl; //cout << "Sensor r is:================================== " << sensor_range << endl; if (distance < sensor_range) { LandmarkObs current_landmark; current_landmark.id = landmark.id_i; current_landmark.x = landmark.x_f; current_landmark.y = landmark.y_f; landmarks_seen.push_back(current_landmark); } } double weight = 1.0; //double gauss_norm; dataAssociation(landmarks_seen, transformed_observations); cout << "=============== Now compare vehicle/particle observations, update weights ===============" << endl; for (int j=0; j < transformed_observations.size(); ++j) { //cout << "transformed observations loop" << endl; double dx = transformed_observations[j].x - landmarks_seen[j-1].x; double dy = transformed_observations[j].y - landmarks_seen[j-1].y; // multivariate-gaussian probability - normalization term double gauss_norm = 1.0 / (2 * M_PI * sigma_x * sigma_y); //double exponent = exp(-dx*dx / (2*sigma_x*sigma_x))* exp(-dy*dy / (2*sigma_y*sigma_y)); double exponent = ((dx*dx) / (2 * sigma_x * sigma_x)) + ((dy*dy) / (2 * sigma_y * sigma_y)); weight *= gauss_norm * exponent; cout << "gauss norm: " << gauss_norm << " exponent: " << exponent << " weight: " << weight << endl; //cout << "trans obs loop end" << endl; } // TODO: create a push_back() instead particles[i].weight = weight; cout << "particles[" << i << "].weight is: " << weight << endl; weights[i] = weight; } for (int i=0; i < particles.size(); ++i) { cout << "Particle[" << i << "] weight is: " << particles[i].weight << endl; } } void ParticleFilter::resample() { discrete_distribution<int> d(weights.begin(), weights.end()); vector<Particle> weighted_samples(num_particles); default_random_engine gen; cout << "======================= Start - resample =======================" << endl; for (int i = 0; i < num_particles; i++) { //cout << "begin for loop"; int j = d(gen); weighted_samples[i] = particles[j]; } particles = weighted_samples; } Particle ParticleFilter::SetAssociations(Particle& particle, const std::vector<int>& associations, const std::vector<double>& sense_x, const std::vector<double>& sense_y) { // particle: the particle to assign each listed association, and association's (x,y) world coordinates // mapping to associations: The landmark id that goes along with each listed association // sense_x: the associations x mapping already converted to world coordinates // sense_y: the associations y mapping already converted to world coordinates cout << "======================= Start - setAssociations =======================" << endl; particle.associations= associations; particle.sense_x = sense_x; particle.sense_y = sense_y; } string ParticleFilter::getAssociations(Particle best) { vector<int> v = best.associations; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<int>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; } string ParticleFilter::getSenseX(Particle best) { vector<double> v = best.sense_x; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<float>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; } string ParticleFilter::getSenseY(Particle best) { vector<double> v = best.sense_y; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<float>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; }
[ "david010@gmail.com" ]
david010@gmail.com
75b34972b7ea8caa0aece110e7df0fd1b9fe0a67
61c011135910da155840afac4d3ce254ef77fb9b
/CoreBase/JWRectangle.h
b78e03ad1844ae33a64bf5dc979c85c1d788bb7c
[]
no_license
principal6/JWEngine
0b661db4f3ce68cdf87261135ecf5b806042a043
ac5806d7c12cec321527ffa836c8db9101159e84
refs/heads/master
2020-04-18T10:16:15.497704
2019-04-08T07:25:49
2019-04-08T07:25:49
167,462,277
1
0
null
null
null
null
UTF-8
C++
false
false
1,216
h
#pragma once #include "JWCommon.h" namespace JWENGINE { // *** // *** Forward declaration *** class JWWindow; // *** class JWRectangle { public: JWRectangle() {}; virtual ~JWRectangle(); virtual void Create(const JWWindow& Window, const WSTRING& BaseDir, UINT MaxNumBox = 1) noexcept; virtual void ClearAllRectangles() noexcept; virtual void AddRectangle(const D3DXVECTOR2& Size, const D3DXVECTOR2& Position) noexcept; virtual void Draw() const noexcept; virtual void SetRectangleColor(DWORD Color) noexcept; protected: virtual void CreateVertexBuffer() noexcept; virtual void CreateIndexBuffer() noexcept; virtual void UpdateVertexBuffer() noexcept; virtual void UpdateIndexBuffer() noexcept; protected: static constexpr DWORD DEFAULT_COLOR_RECTANGLE{ D3DCOLOR_ARGB(255, 80, 255, 0) }; const JWWindow* m_pJWWindow{ nullptr }; WSTRING m_BaseDir; LPDIRECT3DDEVICE9 m_pDevice{ nullptr }; LPDIRECT3DVERTEXBUFFER9 m_pVertexBuffer{ nullptr }; LPDIRECT3DINDEXBUFFER9 m_pIndexBuffer{ nullptr }; VECTOR<SVertexImage> m_Vertices; VECTOR<SIndex3> m_Indices; UINT m_MaxNumBox{}; UINT m_BoxCount{}; DWORD m_RectangleColor{ DEFAULT_COLOR_RECTANGLE }; }; };
[ "jesuskim666@gmail.com" ]
jesuskim666@gmail.com
b86d5837b70a327fccbaefee0a22a5d885e59874
f5dc059a4311bc542af480aa8e8784965d78c6e7
/components/ComponentModels/FluxStandard.h
ed98beb1cea124c2ecc3b58c3b3c1e38bc1ac7cf
[]
no_license
astro-informatics/casacore-1.7.0_patched
ec166dc4a13a34ed433dd799393e407d077a8599
8a7cbf4aa79937fba132cf36fea98f448cc230ea
refs/heads/master
2021-01-17T05:26:35.733411
2015-03-24T11:08:55
2015-03-24T11:08:55
32,793,738
2
0
null
null
null
null
UTF-8
C++
false
false
7,324
h
//# FluxStandard.h: Compute flux densities for standard reference sources //# Copyright (C) 1996,1997,1999,2001 //# Associated Universities, Inc. Washington DC, USA. //# //# This library is free software; you can redistribute it and/or modify it //# under the terms of the GNU Library General Public License as published by //# the Free Software Foundation; either version 2 of the License, or (at your //# option) any later version. //# //# This library is distributed in the hope that it will be useful, but WITHOUT //# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or //# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public //# License for more details. //# //# You should have received a copy of the GNU Library General Public License //# along with this library; if not, write to the Free Software Foundation, //# Inc., 675 Massachusetts Ave, Cambridge, MA 02139, USA. //# //# Correspondence concerning AIPS++ should be adressed as follows: //# Internet email: aips2-request@nrao.edu. //# Postal address: AIPS++ Project Office //# National Radio Astronomy Observatory //# 520 Edgemont Road //# Charlottesville, VA 22903-2475 USA //# //# //# $Id: FluxStandard.h 21229 2012-04-02 12:00:20Z gervandiepen $ #ifndef COMPONENTS_FLUXSTANDARD_H #define COMPONENTS_FLUXSTANDARD_H #include <casa/aips.h> #include <components/ComponentModels/Flux.h> #include <measures/Measures/MDirection.h> namespace casa { //# NAMESPACE CASA - BEGIN // Forward declarations class String; //#include <casa/BasicSL/String.h> class MEpoch; //#include <measures/Measures/MEpoch.h> class MFrequency; //#include <measures/Measures/MFrequency.h> class SpectralModel; //#include <components/ComponentModels/SpectralModel.h> // <summary> // FluxStandard: Compute flux densities for standard reference sources // </summary> // <use visibility=export> // <reviewed reviewer="" date="" tests="" demos=""> // <prerequisite> // <li><linkto class="Flux">Flux</linkto> module // </prerequisite> // // <etymology> // From "flux density" and "standard". // </etymology> // // <synopsis> // The FluxStandard class provides a means to compute total flux // densities for specified non-variable sources on a standard // flux density scale, such as that established by Baars or // Perley and Taylor. // </synopsis> // // <example> // <srcblock> // </srcblock> // </example> // // <motivation> // Encapsulate information on standard flux density computation in one class. // </motivation> // // <todo asof="99/06/01"> // <li> closer integration into component models. // </todo> class FluxStandard { public: // Flux scale types. // Standards which do not include resolution info must come before // HAS_RESOLUTION_INFO, and those with it must come after. enum FluxScale { // Perley (1990); plus Reynolds (1934-638; 7/94); Baars (3C138) PERLEY_90 = 0, // Perley and Taylor (1995.2); plus Reynolds (1934-638; 7/94) PERLEY_TAYLOR_95, // Perley and Taylor (1999.2); plus Reynolds (1934-638; 7/94) PERLEY_TAYLOR_99, // Baars scale // Baars J. W. M., Genzel R., Pauliny-Toth I. I. K., et al., 1977, // A&A, 61, 99 // http://cdsads.u-strasbg.fr/abs/1977A%26A....61...99B BAARS, // Perley-Butler 2010 Scale (using VLA [not EVLA!] data) PERLEY_BUTLER_2010, HAS_RESOLUTION_INFO, // Estimate the flux density for a Solar System object using a JPL Horizons // ephemeris/data page and model provided by Bryan Butler. SS_JPL_BUTLER = HAS_RESOLUTION_INFO, // The number of standards in this enumerator. NUMBER_STANDARDS }; // Default constructor, and destructor FluxStandard(const FluxStandard::FluxScale scale = FluxStandard::PERLEY_TAYLOR_99); ~FluxStandard(); // Compute the flux density for a specified source at a specified frequency Bool compute (const String& sourceName, const MFrequency& mfreq, Flux<Double>& value, Flux<Double>& error); // Compute the flux densities and their uncertainties for a specified source // at a set of specified frequencies. Bool compute(const String& sourceName, const Vector<MFrequency>& mfreqs, Vector<Flux<Double> >& values, Vector<Flux<Double> >& errors, const Bool verbose=True); // Compute the flux densities and their uncertainties for a specified source // for a set of sets of specified frequencies, i.e. mfreqs[spw] is a set of // frequencies for channels in spectral window spw, and values and errors are // arranged the same way. Bool compute(const String& sourceName, const Vector<Vector<MFrequency> >& mfreqs, Vector<Vector<Flux<Double> > >& values, Vector<Vector<Flux<Double> > >& errors); // Like compute, but it also saves a set of ComponentLists for the source to // disk and puts the paths (sourceName_mfreq_mtime.cl) in clnames, making it // suitable for resolved sources. // mtime is ignored for nonvariable objects. // Solar System objects are typically resolved and variable! // The ComponentList names are formed from prefix, sourceName, the // frequencies, and times. Bool computeCL(const String& sourceName, const Vector<Vector<MFrequency> >& mfreqs, const MEpoch& mtime, const MDirection& position, Vector<Vector<Flux<Double> > >& values, Vector<Vector<Flux<Double> > >& errors, Vector<String>& clnames, const String& prefix=""); // Take a component cmp and save it to a ComponentList on disk, returning the // pathname. ("" if unsuccessful, sourceName_mfreqGHzDateTime.cl otherwise) // // This is also used outside of FluxStandard, but it is declared here instead // of in ComponentList because it is somewhat specialized, mainly in setting // up the pathname. The ComponentList name is formed from prefix, sourceName, // mfreq, and mtime. // static String makeComponentList(const String& sourceName, const MFrequency& mfreq, const MEpoch& mtime, const Flux<Double>& fluxval, const ComponentShape& cmp, const SpectralModel& spectrum, const String& prefix=""); // Variation of the above that will fill a TabularSpectrum with mfreqs and // values if appropriate. static String makeComponentList(const String& sourceName, const Vector<MFrequency>& mfreqs, const MEpoch& mtime, const Vector<Flux<Double> >& values, const ComponentShape& cmp, const String& prefix=""); // Decode a string representation of the standard or catalog name static Bool matchStandard(const String& name, FluxStandard::FluxScale& stdEnum, String& stdName); // Return a standard string description for each scale or catalog static String standardName(const FluxStandard::FluxScale& stdEnum); private: // Flux scale in use FluxStandard::FluxScale itsFluxScale; Bool has_direction_p; MDirection direction_p; }; } //# NAMESPACE CASA - END #endif
[ "jason.mcewen@ucl.ac.uk" ]
jason.mcewen@ucl.ac.uk
f7b47c080afb12feb83a6dfb39461bc737ca9df1
e92ed58fde63b656eb39a15b572dddfa4e5d8678
/ThreadPool/global_thread_pool.cpp
4aec676abc6b520a92b821754f3238c724815d01
[ "MIT" ]
permissive
edwardx999/ExLib
892559df696c6515e9b0c4320adad98b2b94f0ec
aba6fb9faec699e5af1d8668268b5cac6fb486c5
refs/heads/master
2021-06-06T18:03:52.050756
2020-04-16T05:31:36
2020-04-16T05:31:36
109,876,488
2
0
null
null
null
null
UTF-8
C++
false
false
1,248
cpp
/* Copyright 2019 Edward Xie Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "global_thread_pool.h" namespace exlib { namespace global_thread_pool { namespace detail { thread_pool& get_pool() { static thread_pool pool; return pool; } } } }
[ "EdwardXie@DMPCPF0SV915" ]
EdwardXie@DMPCPF0SV915
6dc6e016049ae077b94cb86a515aa9e78a5dc6c7
0760fb4901a75766921a205b55686d6d6f049b30
/src/ray/gcs/gcs_server/gcs_redis_failure_detector.h
ff40aff0fac21aa15ed7d6f875c85feadadfc407
[ "MIT", "BSD-3-Clause", "Apache-2.0" ]
permissive
ray-project/ray
a4bb6940b08b59a61ef0b8e755a52d8563a2f867
edba68c3e7cf255d1d6479329f305adb7fa4c3ed
refs/heads/master
2023-08-31T03:36:48.164405
2023-08-31T03:20:38
2023-08-31T03:20:38
71,932,349
29,482
5,669
Apache-2.0
2023-09-14T21:48:14
2016-10-25T19:38:30
Python
UTF-8
C++
false
false
2,334
h
// Copyright 2017 The Ray 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. #pragma once #include <boost/asio.hpp> #include "ray/common/asio/instrumented_io_context.h" #include "ray/common/asio/periodical_runner.h" #include "ray/gcs/redis_client.h" namespace ray { namespace gcs { class RedisGcsClient; /// GcsRedisFailureDetector is responsible for monitoring redis and binding GCS server and /// redis life cycle together. GCS client subscribes to redis messages and it cannot sense /// whether the redis is inactive unless we go to ping redis voluntarily. But there are /// many GCS clients, if they all Ping redis, the redis load will be high. So we ping /// redis on GCS server and GCS client can sense whether redis is normal through RPC /// connection with GCS server. class GcsRedisFailureDetector { public: /// Create a GcsRedisFailureDetector. /// /// \param io_service The event loop to run the monitor on. /// \param redis_context The redis context is used to ping redis. /// \param callback Callback that will be called when redis is detected as not alive. explicit GcsRedisFailureDetector(instrumented_io_context &io_service, std::shared_ptr<RedisClient> redis_client, std::function<void()> callback); /// Start detecting redis. void Start(); /// Stop detecting redis. void Stop(); protected: /// Check that if redis is inactive. void DetectRedis(); private: instrumented_io_context &io_service_; std::shared_ptr<RedisClient> redis_client_; /// The runner to run function periodically. std::unique_ptr<PeriodicalRunner> periodical_runner_; /// A function is called when redis is detected to be unavailable. std::function<void()> callback_; }; } // namespace gcs } // namespace ray
[ "noreply@github.com" ]
noreply@github.com
834a819e6ec35fad9c4320db4cbb5b3dd8979d79
b63156da7d41e8705fc8bb68e09fcabb5525470e
/main.cpp
8cc6cd8626712a0071f7c400b9e8dd732fb8ac3d
[]
no_license
nrdurkin/Dogfight
be85f474a9868a9b74db436e25eea5121e87f6bc
d17743d69a8b924586e2a56c9af82587cf4522a0
refs/heads/master
2023-05-15T09:41:16.132237
2021-05-10T22:06:07
2021-05-10T22:06:07
366,187,178
0
0
null
null
null
null
UTF-8
C++
false
false
424
cpp
#define ALLEGRO_NO_MAGIC_MAIN #include "Controller.h" #include <allegro5/allegro.h> #include <allegro5/allegro_font.h> #include <allegro5/allegro_ttf.h> int real_main(int argc, char **argv) { Controller game; game.Begin(); return 0; } int main(int argc, char **argv) { al_init(); al_install_keyboard(); al_init_font_addon(); al_init_ttf_addon(); return al_run_main(argc, argv, real_main); }
[ "nrdurkin3@gmail.com" ]
nrdurkin3@gmail.com
5cef59a5b7e36adb76a949dd99eb4f7291190e14
fcf7eb8d235e0b91b75b9c76acb5d62d2bf520de
/clause_1/test.cpp
4aa90c46fde2128d1f28cf56bc559d952622e2e9
[]
no_license
1585243571/MoreEffectiveC-Pratice
c1fc8fdb9c1b462f3f3222856665c69015cc2e3b
65cb2b48faab271c66b9147b2c2dcf494661ace9
refs/heads/master
2020-08-31T19:49:12.018324
2020-04-26T07:53:39
2020-04-26T07:58:27
218,770,468
0
0
null
null
null
null
UTF-8
C++
false
false
1,319
cpp
/************************************************************************* > File Name: test.cpp > Author: zhangning > Mail: amoscykl@163.com > Created Time: 2019年10月31日 星期四 21时37分56秒 ************************************************************************/ #include<iostream> using namespace std; /* pointers 和 references的差异 * 1.pointers可以指向不同的对象,而reference 定义完后就只能代表定义时候的对象 * 2.reference不可以为null他只要定义完就代表一个有效的空间,而pointers未必如果是null我们就可能出现断错误,因此用pointers时候我们需要判读其的有效性而reference不需要 * * 注意:delete ptr;并不会将ptr变为null,所以我们要养成习惯delete完后ptr=null,尽管我们不使他为空他仍然可以被访问,而且不会报错,只不过是一个垃圾直,这个比不报错,更可怕。 * 还有注意delete null 并不会报错,所以delete完后将其设为null可以防止double free * *应用场景 如果我们指向一个对象后就不在改变那我们就用reference否则选用pointers * * */ void print(const int *ptr) { if(ptr){ cout<<*ptr<<endl; } } void print(const int &ptr) { cout<<ptr<<endl; } int main() { int a; print(a); print(&a); }
[ "zhangning@momenta.ai" ]
zhangning@momenta.ai
d2b2ce43d5c98e56050fbac06a256e5d8649aca7
79c95f5f78a513540d698bdef5228515462a0e8b
/Qt/FrdArmTemplate/x86/.ui/release-shared/template_base.h
b11e2dd1d7baca9bcfd132e7f8e8fb582d8afb98
[]
no_license
sigmax6/sigmav
b23c1e766c57d3630181eacaae4199a7fa551ef6
d6b1c9aed22b0d17c4f617ce4a6a7c8b38b470f2
refs/heads/master
2021-01-19T14:34:29.405290
2018-02-15T05:48:40
2018-02-15T05:48:40
2,058,063
1
1
null
null
null
null
UTF-8
C++
false
false
850
h
/**************************************************************************** ** Form interface generated from reading ui file 'template_base.ui' ** ** Created: Sat Sep 25 20:34:13 2010 ** by: The User Interface Compiler (uic) ** ** WARNING! All changes made in this file will be lost! ****************************************************************************/ #ifndef HELLOBASEFORM_H #define HELLOBASEFORM_H #include <qvariant.h> #include <qwidget.h> class QVBoxLayout; class QHBoxLayout; class QGridLayout; class QLabel; class QPushButton; class HelloBaseForm : public QWidget { Q_OBJECT public: HelloBaseForm( QWidget* parent = 0, const char* name = 0, WFlags fl = 0 ); ~HelloBaseForm(); QPushButton* dinosauPushButton; QLabel* girlPixmapLabel; QPushButton* helloPushButton; }; #endif // HELLOBASEFORM_H
[ "sigmax6@sigmav.x200" ]
sigmax6@sigmav.x200
a75d9f54532c9e8707342b9c2d18c9fe02e8e332
bf325d30bfc855b6a23ae9874c5bb801f2f57d6d
/homework/八/3.cpp
13380513e6476025e618bd747867c8c2dbbed07d
[]
no_license
sudekidesu/my-programes
6d606d2af19da3e6ab60c4e192571698256c0109
622cbef10dd46ec82f7d9b3f27e1ab6893f08bf5
refs/heads/master
2020-04-09T07:20:32.732517
2019-04-24T10:17:30
2019-04-24T10:17:30
160,151,449
0
1
null
null
null
null
UTF-8
C++
false
false
274
cpp
#include<stdio.h> #include<string.h> int main() { char s[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; char a[100]; int i=0,k; scanf("%d",&k); for(;k>0;) { a[i]=s[k%16]; k/=16; i++; } for(i=strlen(a)-1;i>=0;i--) printf("%c",a[i]); }
[ "33283268+sudekidesu@users.noreply.github.com" ]
33283268+sudekidesu@users.noreply.github.com
f31c92f0c399efd192bcc83d98332c98f42f8b5e
821ec32ff62d74e575501752b292540c98fe8952
/UsefulFunctions.cpp
20fa9a86f244ba4a279ea3de3ee87f879ee526e9
[]
no_license
fengjixuchui/ProjectPerun
aaa613ccf1f05999d36e95635338b0acf601b597
c8dfd626cd49b6af9fc0d978a6c518ff6d1043bc
refs/heads/master
2020-04-30T17:28:09.891322
2018-03-22T13:51:26
2018-03-22T13:51:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,831
cpp
#include "UsefulFunctions.h" #include <QDir> int binarySearch (std::fstream &file,const char* value,int first,int last, short recordSize) { //should be called only indirectly by calling binarySearchWrapper function if (first>last) { return -1; } int mid=(first+last)/2; file.seekg(mid*recordSize); char tmp[50]; //in tmp will be stored name of process of each game stored in gameslist.dat file file.read( tmp,50 ); if (strcmp(value,tmp)<0) { return binarySearch(file,value,first,mid-1,recordSize); } else if (strcmp(value,tmp)>0) { return binarySearch(file,value,mid+1,last,recordSize); } else { return mid; } } int binarySearchWrapper (std::fstream &file,const char* processName) { //for searching records in gameslist.dat file (by default) or in gamepath.dat file (if value of last parameter is true) - IT MUST BE PREVIOUSLY OPENED FOR READING! (opening a file takes a lot of time, so it is much more appropriate to manually set it's starting and ending lifecycle's point (especially when using nested loops)) file.seekg(0,std::ios::end); short recordSize = sizeof(tGames); return binarySearch ( file , processName , 0 , file.tellg()/recordSize -1 , recordSize ); } QString convertSecondsToHmsFormat(double durationDouble) { int duration = (int) durationDouble; int seconds = duration % 60; duration /= 60; int minutes = duration % 60; duration /= 60; int hours = duration; if(hours == 0) if (minutes == 0) return QString("%1s").arg( QString::number(seconds) ); else return QString("%1min:%2s").arg( QString::number(minutes) ).arg( QString::number(seconds).rightJustified(2,'0') ); return QString("%1h:%2min:%3s").arg( QString::number(hours) ).arg( QString::number(minutes).rightJustified(2,'0') ).arg( QString::number(seconds).rightJustified(2,'0') ); } const char* stringToLowerCase(const char* string) { char* tmp = new char [50]; int i; for (i=0 ; string[i]!='\0' ; i++) { if (string[i]>='A' && string[i]<='Z') { tmp[i] = string[i] + 32; } else { tmp[i] = string[i]; } } tmp[i] = '\0'; return tmp; } QString extractGameNameOnly (QString gameStatus) { QString ipPattern = "((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"; QString portPattern = "([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])"; QRegularExpression ipAndPortInsideBracketsPattern(((QString)" \\(%1:%2\\)$").arg(ipPattern, portPattern)); return gameStatus.remove(ipAndPortInsideBracketsPattern); } void createDirectoryIfDoesntExist(QString directoryName) { QDir dir(directoryName); if (!dir.exists()) { dir.mkpath("."); } }
[ "zeko868@hotmail.com" ]
zeko868@hotmail.com
f3c1d139db0e305f0c2df0051744e65f3e2c1f06
1577a53881c0d2bf13a7bc4a597037c08ac2e80d
/qt_code/v1.5/fileServerv1.5/fileServer_Receive/tcp_fileserver_recv.h
58130bf4b7189b510159d8f1ab166032a24fcf26
[]
no_license
xiaoweilai/wireless
ff3205de883cca17ad0a332705519d0235f81f8c
2130a7f4d7947ec7cd985160ed74a04410318189
refs/heads/master
2021-01-13T01:27:48.808776
2015-05-31T09:07:47
2015-05-31T09:07:47
29,049,725
0
0
null
null
null
null
GB18030
C++
false
false
1,869
h
#ifndef TCP_FILESERVER_RECV_H #define TCP_FILESERVER_RECV_H #include <QMainWindow> #include <QtGui> #include <QTcpServer> #include <QTcpSocket> #include <QAbstractSocket> #include <QIODevice> #if 0 //ok 2pic/s #define STREAM_PIC_FORT "PNG" #define SUFIXNAME "png" #elif 0 //err #define STREAM_PIC_FORT "BMP" #define SUFIXNAME "bmp" #elif 0 //ok, 6pic/s #define STREAM_PIC_FORT "JPG" #define SUFIXNAME "jpg" #elif 1 //ok, 6pic/s #define STREAM_PIC_FORT "JPEG" #define SUFIXNAME "jpeg" #elif 0 //err,size too little #define STREAM_PIC_FORT "GIF" #define SUFIXNAME "gif" #elif 0 //err,too big #define STREAM_PIC_FORT "TIFF" #define SUFIXNAME "tiff" #elif 1 //not show #define STREAM_PIC_FORT "PPM" #define SUFIXNAME "ppm" #endif namespace Ui { class Tcp_FileServer_Recv; } class Tcp_FileServer_Recv : public QMainWindow { Q_OBJECT public: explicit Tcp_FileServer_Recv(QWidget *parent = 0); ~Tcp_FileServer_Recv(); private: Ui::Tcp_FileServer_Recv *ui; public slots: void start(); void stop(); void acceptConnection(); void updateServerProgress(); void displayError(QAbstractSocket::SocketError socketError); QString bindIpAddr(); protected: quint8 getOnlyOneClient(); void setOnlyOneClient(); private: // QProgressBar *clientProgressBar; // QProgressBar *serverProgressBar; // QLabel *serverStatusLabel; // QPushButton *startButton; // QPushButton *quitButton; // QPushButton *openButton; // QDialogButtonBox *buttonBox; QTcpServer tcpServer; QTcpSocket *tcpServerConnection; qint64 TotalBytes; qint64 bytesReceived; qint64 fileNameSize; qint64 bytesNeedRecv; QString fileName; QFile *localFile; QByteArray inBlock; qint8 OnlyOneClient; //仅一个客户端 }; #endif // TCP_FILESERVER_RECV_H
[ "wxjlmr@126.com" ]
wxjlmr@126.com
8069be5cde68176b6850a7b91be52b2c2b4d6be4
c18ecd8ab305e21c3e6b8870105ad987113cfda5
/codeforces/3181/13868393_CE.cc
0f7f93c0f4ebac9c3c3c03fc076c24e152399960
[]
no_license
stmatengss/ICPC_practice_code
4db71e5c54129901794d4d0df6a04ebd73818759
c09f95495d8b57eb6fa2602f0bd66bd30c8e4a0c
refs/heads/master
2021-01-12T05:58:59.350393
2016-12-24T04:35:19
2016-12-24T04:35:19
77,265,840
0
0
null
null
null
null
UTF-8
C++
false
false
1,127
cc
//import java.io.*; //import java.lang.reflect.Array; //import java.math.*; //import java.util.Arrays; import java.util.Scanner; //import java.util.Scanner; public class Main{ public static void main(String[] args) { BigDecimal[] dp1 = new BigDecimal[1008]; BigDecimal[] dp0 = new BigDecimal[1008]; int n=0; int K=0; int i,j,k; Scanner cin = new Scanner(System.in); while(cin.hasNext()){ n=cin.nextInt(); K=cin.nextInt(); Arrays.fill(dp1,BigDecimal.ONE); Arrays.fill(dp0,BigDecimal.ZERO); for(i=2;i<=K;i++) { for(j=0;j<=n;j++) { for(k=0;k<=n;k=k+i) if(j-k>=0) { if(i%2==0){ dp0[j]=dp0[j].add(dp1[j-k]); } else { dp1[j]=dp1[j].add(dp0[j-k]); } } //dp[i%2][j]+=dp[(i-1)%2][j-k]; } if(i%2==0) Arrays.fill(dp1,BigDecimal.ZERO); else { Arrays.fill(dp0,BigDecimal.ZERO); } //memset(dp[(i-1)%2],0,sizeof(dp[(i-1)%2])); } if(K%2==0) System.out.println(dp0[n]); else { System.out.println(dp1[n]); } } } }
[ "stmatengss@Tengs-MacBook-Pro.local" ]
stmatengss@Tengs-MacBook-Pro.local
2a9e065e80db04407503686b9d6a3dcfff6b4f22
827405b8f9a56632db9f78ea6709efb137738b9d
/CodingWebsites/URAL/Volume4/1355.cpp
96e13431f1fe1c9d61c4853c16d71ca78061f786
[]
no_license
MingzhenY/code-warehouse
2ae037a671f952201cf9ca13992e58718d11a704
d87f0baa6529f76e41a448b8056e1f7ca0ab3fe7
refs/heads/master
2020-03-17T14:59:30.425939
2019-02-10T17:12:36
2019-02-10T17:12:36
133,694,119
0
0
null
null
null
null
UTF-8
C++
false
false
1,211
cpp
#include <iostream> #include <cstdio> #include <cmath> #include <cstring> #include <algorithm> #define inf 0x5fffffff #define FOR(i,n) for(long long (i)=1;(i)<=(n);(i)++) #define For(i,n) for(long long (i)=0;(i)<(n);(i)++) #define out(i) <<#i<<"="<<(i)<<" " #define OUT1(a1) cout out(a1) <<endl #define OUT2(a1,a2) cout out(a1) out(a2) <<endl #define OUT3(a1,a2,a3) cout out(a1) out(a2) out(a3)<<endl using namespace std; int prime[100000]; int p[10000];int Np; int d[10000]; int main(void) {freopen("1355.txt","r",stdin); Np=0;memset(prime,-1,sizeof(prime)); for(int i=2;i<100000;i++){ if(~prime[i]) continue; for(int j=i;j<100000;j+=i){ prime[j]=i; } p[Np++]=i; } int T;cin>>T; For(test,T){ int a,b; scanf("%d%d",&a,&b); int ANS=0,ERR=0; For(i,Np) { int D=0;d[i]=0; while(a%p[i]==0) d[i]--,a/=p[i]; while(b%p[i]==0) d[i]++,b/=p[i]; } if(a>1){ p[Np]=a;d[Np]=-1;Np++; } if(b>1){ if(p[Np-1]==b) d[Np-1]++; else { p[Np]=b;d[Np]++;Np++; } } for(int i=0;i<Np;i++){ if(d[i]>0) ANS+=d[i]; if(d[i]<0){ ANS=0;ERR=1;break; } } printf("%d\n",ANS+!ERR); } return 0; }
[ "mingzhenyan@yahoo.com" ]
mingzhenyan@yahoo.com
7358f549481e1aa7aca71a49897b5c9ab1cbc292
1d748f828ee16ac288db76b8d2751e1f244b9eb4
/this/Main.cpp
7131b6cadbed5552f25a4060f5bdad5f7ab3f4f8
[]
no_license
nunopereira4412/CPLUSPLUS-practice
89cbda11756304cb904ae0cb84cc4175dec3092a
b8baf96128ddb9a32a7411da02d3727d0f63b7cf
refs/heads/master
2023-02-27T22:56:24.708653
2021-02-10T15:13:08
2021-02-10T15:13:08
337,761,697
0
0
null
null
null
null
UTF-8
C++
false
false
209
cpp
#include <iostream> #include "test.h" using namespace std; int main() { Test t; Test t2("joao", 34); cout << t.toString() << endl; cout << t2.toString() << endl; cout << t2.name << endl; return 0; }
[ "nuno.pereira4412@gmail.com" ]
nuno.pereira4412@gmail.com
e2a83fdc3a1905974e053b99c8100525e1815f32
2a76efae74308f338e45b449002332a0cd8c16d7
/Coin3D/include/Inventor/lists/SoEngineOutputList.h
e61dcbf0e1c7032750086292ae1b2a0b3770420a
[]
no_license
misrayazgan/Digital-Geometry-Processing
5e687646aa08c95856fef06d5fd2f13bd5f6f934
9237f84ec783a1cdfdbadea7b55f4cfe99e32996
refs/heads/master
2022-11-20T04:04:54.070115
2020-07-19T16:41:44
2020-07-19T16:41:44
280,908,013
0
0
null
null
null
null
UTF-8
C++
false
false
1,880
h
#ifndef COIN_SOENGINEOUTPUTLIST_H #define COIN_SOENGINEOUTPUTLIST_H /**************************************************************************\ * * This file is part of the Coin 3D visualization library. * Copyright (C) 1998-2005 by Systems in Motion. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * ("GPL") version 2 as published by the Free Software Foundation. * See the file LICENSE.GPL at the root directory of this source * distribution for additional information about the GNU GPL. * * For using Coin with software that can not be combined with the GNU * GPL, and for taking advantage of the additional benefits of our * support services, please contact Systems in Motion about acquiring * a Coin Professional Edition License. * * See <URL:http://www.coin3d.org/> for more information. * * Systems in Motion, Postboks 1283, Pirsenteret, 7462 Trondheim, NORWAY. * <URL:http://www.sim.no/>. * \**************************************************************************/ #include <Inventor/lists/SbPList.h> class SoEngineOutput; class COIN_DLL_API SoEngineOutputList : public SbPList { public: SoEngineOutputList(void) : SbPList() { } SoEngineOutputList(const int sizehint) : SbPList(sizehint) { } SoEngineOutputList(const SoEngineOutputList & l) : SbPList(l) { } void append(SoEngineOutput * output) { SbPList::append((void *) output); } void insert(SoEngineOutput * output, const int insertbefore) { SbPList::insert((void *) output, insertbefore); } SoEngineOutput * operator [](const int idx) const { return (SoEngineOutput*) SbPList::operator[](idx); } void set(const int idx, SoEngineOutput * item) { SbPList::operator[](idx) = (void*) item; } }; #endif // !COIN_SOENGINEOUTPUTLIST_H
[ "e2099489@ceng.metu.edu.tr" ]
e2099489@ceng.metu.edu.tr
83485484a8048d112b5d4f47a8d686522964b916
b39e187e9d47d9fd3470d6f25fdd3a92eb25f11b
/source/directwrite/GlyphRunDescription.cpp
0c23f8cf023820b9842f0c6657de30ed9591e34c
[ "MIT" ]
permissive
SlimDX/slimdx
b0e22cb26b5da34ad3dd522ced54768b71b3e929
284f3ab1ddadc17b4091bfa7c7b9faed8bf0ded8
refs/heads/master
2022-09-02T19:14:14.879176
2022-08-31T03:04:57
2022-08-31T03:04:57
32,283,841
93
49
MIT
2022-08-31T03:04:58
2015-03-15T21:01:40
C++
UTF-8
C++
false
false
1,650
cpp
/* * Copyright (c) 2007-2012 SlimDX Group * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "stdafx.h" #include "GlyphRunDescription.h" using namespace System; namespace SlimDX { namespace DirectWrite { GlyphRunDescription::GlyphRunDescription(const DWRITE_GLYPH_RUN_DESCRIPTION &desc) { LocaleName = gcnew String(desc.localeName); Text = gcnew String(desc.string); StringLength = desc.stringLength; TextPosition = desc.textPosition; ClusterMap = gcnew array<short>(StringLength); for (int i = 0; i < StringLength; i++) ClusterMap[i] = desc.clusterMap[i]; } } }
[ "mike.popoloski@090eb97a-982f-0410-b69a-795f42cc130f" ]
mike.popoloski@090eb97a-982f-0410-b69a-795f42cc130f
4faf2eed282ecca96153ad20e67062e3660a4917
7e65d0d0e2be8088a38d489f83dbab7d8af7b318
/MinHeap.cpp
b36ab9a692f5382d8684e1b5e7aa142276dac2af
[]
no_license
kdcouture/PracticeCode
f2cd3cf0a6191b5c5a137a503291d9f6c72c077e
56af7d61536f7de3c9ebdce4e30ee2890d148898
refs/heads/master
2020-04-07T18:37:50.589097
2019-02-07T05:09:56
2019-02-07T05:09:56
158,617,535
0
0
null
null
null
null
UTF-8
C++
false
false
3,597
cpp
/* Min heap class This file contains the min heap class and its related functions. Note: the heap size determins the vaild heap bound. */ #include <iostream> using namespace std; // Uitility function // Heap sort int* heapSort(int* arr, int size); // Swaps two integers. void swap(int* a, int* b) { int temp = *a; *a = *b; *b = temp; } class MinHeap { // array of elements int* heapEls; // Maximum size of heap int capacity; // Current size int heapSize; public: // Consturctor MinHeap(int cap); // Tree utilities // Gets parent node ((idx - 1) /2) int parent(int idx) { return (idx - 1) / 2; } // Gets left child (idx*2 + 1) int left(int idx) { return (idx * 2 + 1); } // Gets right child (idx*2 + 2) int right(int idx) { return (idx * 2 + 2); } // Gets the min value int getMin() { return heapEls[0]; } // Print arry for debug use void printHeapArray() { for (int i = 0; i < heapSize; i++) { cout << heapEls[i] << " "; } cout << endl; } // Class prototypes void MinHeapify(int idx); int removeMin(); void insertEle(int data); void deleteEle(int data); }; // Heap constructor MinHeap::MinHeap(int cap) { capacity = cap; heapEls = new int[capacity]; heapSize = 0; for (int i = 0; i < capacity; i++) { heapEls[i] = 999; } } /* @func MinHeapify @param int idx @ret VOID @desc This function min heapifies from idx down to heap boundry (heapSize). */ void MinHeap::MinHeapify(int idx) { int lChild = left(idx); int rChild = right(idx); int minIdx = idx; // Look for smallest while staying inside current heap bounds if (lChild < heapSize && heapEls[lChild] < heapEls[idx]) { minIdx = lChild; } if (rChild < heapSize && heapEls[rChild] < heapEls[minIdx]) { minIdx = rChild; } if (minIdx != idx) { swap(&heapEls[idx], &heapEls[minIdx]); MinHeapify(minIdx); } } int MinHeap::removeMin() { // Check for empty heap if (heapSize <= 0) { return -1; } // If size = 1, return top element else if (heapSize == 1) { heapSize--; return heapEls[0]; } // Remove top element and reheapify else { int minEle = heapEls[0]; heapEls[0] = heapEls[heapSize - 1]; heapSize--; MinHeapify(0); return minEle; } return -1; } void MinHeap::insertEle(int data) { // Check if space exists if (heapSize == capacity) { cout << "Heap is full" << endl; return; } // Increment heap size heapSize++; // Place new element at bottom of heap int i = heapSize - 1; heapEls[i] = data; // Modify heap until valid min heap while (i != 0 && heapEls[parent(i)] > heapEls[i]) { swap(&heapEls[i], &heapEls[parent(i)]); i = parent(i); } } void MinHeap::deleteEle(int data) { for (int i = 0; i < heapSize; i++) { if (heapEls[i] == data) { heapEls[i] = heapEls[heapSize - 1]; heapSize--; MinHeapify(i); break; } } } int* heapSort(int* arr, int size) { MinHeap h(arr[0]); int* sortedArr = new int[size]; for (int i = 0; i < size; i++) { h.insertEle(arr[i]); } for (int j = 0; j < size; j++) { sortedArr[j] = h.removeMin(); } return sortedArr; } int main() { MinHeap h(10); h.insertEle(7); h.insertEle(6); h.deleteEle(1); h.insertEle(16); h.insertEle(8); h.printHeapArray(); cout << h.getMin() << endl; cout << h.removeMin() << endl; h.printHeapArray(); cout << h.removeMin() << endl; h.printHeapArray(); cout << h.getMin() << endl; int* arr = new int[7]; int size = 7; for (int i = 0; i < size; i++) { arr[i] = 52 - i; } int* sorted = heapSort(arr, size); for (int j = 0; j < size; j++) { cout << sorted[j] << " "; } cout << endl; system("pause"); return 0; }
[ "kcouture939@gmail.com" ]
kcouture939@gmail.com
c9415ba298567feca29640807ae32887376639df
ee20d5f0983ce8bc7466090b135519d1114ede9d
/Contests/VII Maratona Mineira de Programação - Open Contest/C.cpp
e5430ba0cfe4089e8e162c1ddf3b5606e7e2c75c
[]
no_license
rodrigoAMF/competitive-programming
a12038dd17144044365c1126fa17f968186479d4
06b38197a042bfbd27b20f707493e0a19fda7234
refs/heads/master
2020-03-31T18:28:11.301068
2019-08-02T21:35:53
2019-08-02T21:35:53
152,459,900
5
0
null
null
null
null
UTF-8
C++
false
false
4,295
cpp
#include <bits/stdc++.h> // Nome de Tipos typedef long long ll; typedef unsigned long long ull; typedef long double ld; // Valores #define INF 0x3F3F3F3F #define LINF 0x3F3F3F3F3F3F3F3FLL #define DINF (double)1e+30 #define EPS (double)1e-9 #define RAD(x) (double)(x*PI)/180.0 #define PCT(x,y) (double)x*100.0/y // Atalhos #define F first #define S second #define PB push_back #define MP make_pair #define forn(i, n) for ( int i = 0; i < (n); ++i ) using namespace std; // iPair ==> Integer Pair typedef pair<int, int> iPair; // This class represents a directed graph using // adjacency list representation class Graph { int V; // No. of vertices // In a weighted graph, we need to store vertex // and weight pair for every edge list< pair<int, int> > *adj; public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int u, int v, int w); // prints shortest path from s int shortestPath(int s, int dst); }; // Allocates memory for adjacency list Graph::Graph(int V) { this->V = V; adj = new list<iPair> [V]; } void Graph::addEdge(int u, int v, int w) { adj[u].push_back(make_pair(v, w)); adj[v].push_back(make_pair(u, w)); } // Prints shortest paths from src to all other vertices int Graph::shortestPath(int src, int dst) { // Create a priority queue to store vertices that // are being preprocessed. This is weird syntax in C++. // Refer below link for details of this syntax // http://geeksquiz.com/implement-min-heap-using-stl/ priority_queue< iPair, vector <iPair> , greater<iPair> > pq; // Create a vector for distances and initialize all // distances as infinite (INF) vector<int> dist(V, INF); // Insert source itself in priority queue and initialize // its distance as 0. pq.push(make_pair(0, src)); dist[src] = 0; /* Looping till priority queue becomes empty (or all distances are not finalized) */ while (!pq.empty()) { // The first vertex in pair is the minimum distance // vertex, extract it from priority queue. // vertex label is stored in second of pair (it // has to be done this way to keep the vertices // sorted distance (distance must be first item // in pair) int u = pq.top().second; pq.pop(); // 'i' is used to get all adjacent vertices of a vertex list< pair<int, int> >::iterator i; for (i = adj[u].begin(); i != adj[u].end(); ++i) { // Get vertex label and weight of current adjacent // of u. int v = (*i).first; int weight = (*i).second; // If there is shorted path to v through u. if (dist[v] > dist[u] + weight) { // Updating distance of v dist[v] = dist[u] + weight; pq.push(make_pair(dist[v], v)); } } } // Print shortest distances stored in dist[] return dist[dst]; } int main(){ #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif int n; cin >> n; int valores[n]; int quantidade[7]; memset(quantidade, 0, sizeof(quantidade)); int maior = -1; int n_maior = 1; forn(i, n){ cin >> valores[i]; quantidade[valores[i]]++; if(quantidade[valores[i]] > maior){ maior = quantidade[valores[i]]; n_maior = valores[i]; } } int V = 7; Graph g(V); // making above shown graph g.addEdge(0, 1, 1); g.addEdge(0, 2, 1); g.addEdge(0, 3, 1); g.addEdge(0, 4, 1); g.addEdge(1, 0, 1); g.addEdge(1, 2, 1); g.addEdge(1, 3, 1); g.addEdge(1, 5, 1); g.addEdge(2, 0, 1); g.addEdge(2, 4, 1); g.addEdge(2, 5, 1); g.addEdge(2, 1, 1); g.addEdge(3, 0, 1); g.addEdge(3, 1, 1); g.addEdge(3, 5, 1); g.addEdge(3, 4, 1); g.addEdge(4, 0, 1); g.addEdge(4, 2, 1); g.addEdge(4, 3, 1); g.addEdge(4, 5, 1); g.addEdge(5, 1, 1); g.addEdge(5, 2, 1); g.addEdge(5, 3, 1); g.addEdge(5, 4, 1); int movimentos = 0; forn(i, n){ if(valores[i] != n_maior){ movimentos += g.shortestPath(valores[i]-1, n_maior-1); } } cout << movimentos << endl; return 0; }
[ "rodrigoamf@outlook.com" ]
rodrigoamf@outlook.com
6a6af31235b41118789c6b79d7593299c497d18a
8b6a286bad8738683aa0931064e8a62f9bb7ad2c
/classes.h
21d93f1cd7651347eaddc2b7465e7c11ff88eec9
[]
no_license
rozybaeva6/Laba-2
a9ce73eaf167e4e67440891ec03d4b24aca87b9a
c80f984fd636b8dc164223506d066acfaa0c41f0
refs/heads/master
2022-10-12T00:01:12.241430
2020-06-14T18:03:47
2020-06-14T18:03:47
272,250,701
0
0
null
2020-06-14T17:27:38
2020-06-14T17:27:37
null
UTF-8
C++
false
false
2,993
h
#include <cstdlib> #include <iostream> #include <fstream> #include <string> using namespace std; class Order { private: int ido; // id заказа int price; // цена заказа int deadline; // срок доставки заказа string address; // адрес доставки int courierid; // id сотрудника int dtime; // время доставки заказа public: friend void allorderclear(string courierfile, string orderfile); // очистить файл заказов friend void allorderwrite(string orderfile); // вывести список заказов friend void oselect(string courierfile, string orderfile); // распределение заказов по курьерам friend void addorder (string orderfile); // добавить заказ friend void osearchid(string orderfile); // поиск по id friend void runtime(string courierfile, string orderfile); // промотать время вперед на n минут }; class Courier { private: int idc; // id сотрудника string name; // имя сотрудника string phone; // телефон сотрудника int orderid1; // текущий заказ int orderid2; // будущущий заказ int car; // машина для доставки int deliverytime; // время через которое курьер освободится public: friend void runtime(string courierfile, string orderfile); // промотать время вперед на n минут friend void csearchid(string courierfile); // найти курьера по id friend void addcourier(string courierfile); // добавить курьера friend void courierdeleting(string courierfile, string orderfile); // удалить курьера friend void csearchname(string courierfile); // найти курьера по имени friend void csearchphone(string courierfile); // найти курьера по телефону friend void allcourierclear(string courierfile, string orderfile); // очистить список курьеров friend void allcourierwrite(string namefile); // вывести список курьеров friend void oselect(string courierfile, string orderfile); // распределение заказов по курьерам }; void allorderwrite(string orderfile); void allorderclear(string courierfile, string orderfile); void allcourierwrite(string courierfile); void allcourierclear(string courierfile, string orderfile); void courierdeleting(string courierfile, string orderfile); void oselect(string courierfile, string orderfile); void addorder (string orderfile); void osearchid(string orderfile); void runtime(string courierfile, string orderfile); void csearchid(string courierfile); void csearchname(string courierfile); void csearchphone(string courierfile); void addcourier(string courierfile);
[ "noreply@github.com" ]
noreply@github.com
0b9b18f8865b78aa93b100df10353bb14a826188
01e2f6bc6035b52b7649800424820d2da4fea717
/Part-4/Apartment.cpp
e0cb0b3a621d26bad159bd04651a5b9e67f87ba0
[]
no_license
RazLandau/Yad3---C-CPP-BASH
c8ea5427c2f3e224fad9e9d64f385f9d588597f4
baf8a45013330ce3d69f607ba50db875e3f2e9a0
refs/heads/master
2021-01-11T04:35:38.725449
2016-10-17T17:54:21
2016-10-17T17:54:21
71,158,492
0
0
null
null
null
null
UTF-8
C++
false
false
6,570
cpp
/* * Apartment.cpp * * Created on: Jun 8, 2016 * Author: Lioz */ #include <iostream> #include "Apartment.h" Apartment::Apartment(SquareType** squares, int length, int width, int price) : squares(NULL), length(0), width(0), price(0) { if (price < 0 || length <= 0 || width <= 0 || squares == NULL) { throw IllegalArgException(); } this->squares = new SquareType*[length]; for (int i = 0; i < length; ++i) { this->squares[i] = new SquareType[width]; for (int j = 0; j < width; ++j) { this->squares[i][j] = squares[i][j]; } } this->length = length; this->width = width; this->price = price; } Apartment::Apartment(const Apartment& apartment) : squares(new SquareType*[apartment.length]), length(apartment.length), width( apartment.width), price(apartment.price) { for (int i = 0; i < length; i++) { this->squares[i] = new SquareType[width]; for (int j = 0; j < width; j++) { squares[i][j] = apartment.squares[i][j]; } } } int Apartment::getPrice() const { return price; } int Apartment::getLength() const { return length; } int Apartment::getWidth() const { return width; } int Apartment::getTotalArea() const { int counter = 0; for (int i = 0; i < length; i++) { for (int j = 0; j < width; j++) { if (squares[i][j] == EMPTY) { counter++; } } } return counter; } Apartment::~Apartment() { for (int i = 0; i < length; i++) { delete[] squares[i]; } delete[] squares; } Apartment& Apartment::operator=(const Apartment& apartment) { if (this == &apartment) { return *this; } for (int i = 0; i < length; i++) { delete[] squares[i]; } delete[] squares; length = apartment.length; width = apartment.width; price = apartment.price; SquareType** temp = new SquareType*[apartment.length]; for (int i = 0; i < length; ++i) { temp[i] = new SquareType[apartment.width]; for (int j = 0; j < width; ++j) { temp[i][j] = apartment.squares[i][j]; } } squares = temp; return *this; } Apartment& Apartment::operator+=(const Apartment& apartment) { price += apartment.price; const int old_length = length; SquareType** newSquares; if (width == apartment.width) { newSquares = MergeSameWidth(*this, apartment); length += apartment.length; } else if (length == apartment.length) { newSquares = MergeSameLength(*this, apartment); width += apartment.width; } else { if (width > apartment.width) { newSquares = MergeApt1Wider(*this, apartment); } else { newSquares = MergeApt2Wider(*this, apartment); width = apartment.width; } length += apartment.length; } SquareType** ptr; ptr = this->squares; this->squares = newSquares; for (int i = 0; i < old_length; i++) { delete[] ptr[i]; } delete[] ptr; return *this; } Apartment operator+(const Apartment& apartment1, const Apartment& apartment2) { return (Apartment(apartment1) += apartment2); } Apartment::SquareType** Apartment::MergeSameWidth(const Apartment& apt1, const Apartment& apt2) { const int old_length = apt1.length; const int length = apt1.length + apt2.length; SquareType** newSquares = new SquareType*[length]; for (int i = 0; i < length; i++) { newSquares[i] = new SquareType[apt1.width]; } for (int i = 0; i < old_length; i++) { for (int j = 0; j < apt1.width; j++) { newSquares[i][j] = apt1.squares[i][j]; } } for (int i = old_length; i < length; i++) { for (int j = 0; j < apt1.width; j++) { newSquares[i][j] = apt2.squares[(i - old_length)][j]; } } return newSquares; } Apartment::SquareType** Apartment::MergeSameLength(const Apartment& apt1, const Apartment& apt2) { const int old_width = apt1.width; const int new_width = apt1.width + apt2.width; SquareType** newSquares = new SquareType*[new_width]; for (int i = 0; i < apt1.length; i++) { newSquares[i] = new SquareType[new_width]; } for (int i = 0; i < apt1.length; i++) { for (int j = 0; j < old_width; j++) { newSquares[i][j] = apt1.squares[i][j]; } for (int j = old_width; j < new_width; j++) { newSquares[i][j] = apt2.squares[i][(j - old_width)]; } } return newSquares; } Apartment::SquareType** Apartment::MergeApt1Wider(const Apartment& apt1, const Apartment& apt2) { const int old_length = apt1.length; const int new_length = apt1.length + apt2.length; SquareType** newSquares = new SquareType*[new_length]; for (int i = 0; i < new_length; i++) { newSquares[i] = new SquareType[apt1.width]; } for (int i = 0; i < old_length; i++) { for (int j = 0; j < apt1.width; j++) { newSquares[i][j] = apt1.squares[i][j]; } } for (int i = old_length; i < new_length; i++) { for (int j = 0; j < apt2.width; j++) { newSquares[i][j] = apt2.squares[(i - old_length)][j]; } for (int j = apt2.width; j < apt1.width; j++) { newSquares[i][j] = WALL; } } return newSquares; } Apartment::SquareType** Apartment::MergeApt2Wider(const Apartment& apt1, const Apartment& apt2) { const int old_length = apt1.length; const int new_length = apt1.length + apt2.length; SquareType** newSquares = new SquareType*[new_length]; for (int i = 0; i < new_length; i++) { newSquares[i] = new SquareType[apt2.width]; } for (int i = 0; i < old_length; i++) { for (int j = 0; j < apt1.width; j++) { newSquares[i][j] = apt1.squares[i][j]; } for (int j = apt1.width; j < apt2.width; j++) { newSquares[i][j] = WALL; } } for (int i = old_length; i < new_length; i++) { for (int j = 0; j < apt2.width; j++) { newSquares[i][j] = apt2.squares[(i - old_length)][j]; } } return newSquares; } bool operator<(const Apartment& apartment1, const Apartment& apartment2) { const int area1 = apartment1.getTotalArea(), area2 = apartment2.getTotalArea(), price1 = apartment1.getPrice(), price2 = apartment2.getPrice(); if (price1 * area2 == price2 * area1) { return price1 < price2; } else { return (price1 * area2) < (price2 * area1); } } Apartment::SquareType& Apartment::operator()(int row, int col) { if (row < 0 || row >= length || col < 0 || col >= width) { throw OutOfApartmentBoundsException(); } return squares[row][col]; } const Apartment::SquareType& Apartment::operator()(int row, int col) const { if (row < 0 || row >= length || col < 0 || col >= width) { throw OutOfApartmentBoundsException(); } Apartment::SquareType& square = squares[row][col]; return square; }
[ "noreply@github.com" ]
noreply@github.com
ef69b06352fc430063264a220f2ebee482779cea
f090a5185d7bdd47608346d9ed94fe522d4cbe2b
/ADS1/ADS_Pritz_UE4/Teil_2/Source.cpp
0cba20885c5d8b2705924781d3e8c243673ffaf2
[]
no_license
Breenori/Programs
71c08eac6bca815e5df62ff9191e62585275019b
4cbe74d7efa02cbb4d7910bc601bcbbbc21aeebf
refs/heads/master
2020-12-06T10:29:01.485633
2020-10-31T13:45:30
2020-10-31T13:45:30
232,439,000
0
0
null
null
null
null
UTF-8
C++
false
false
2,052
cpp
#include<iostream> #include<string> using std::cout; using std::cin; using std::string; // Finds the longest matching occurence between two strings and returns it. string find_longest_match(string string1, string string2); int main() { cout << "Please enter first string: "; string string1(""); std::getline(cin, string1); cout << "Please enter second string: "; string string2(""); std::getline(cin, string2); string match(find_longest_match(string1, string2)); if (string1.length() > 0 && string2.length() > 0) { if (match.length() > 0) { cout << "The longest matching occurence is: \n"; cout << match; } else { cout << "No matches found."; } } else { cout << "One or more strings are empty! 0 matches."; } } string find_longest_match(string string1, string string2) { // if both strings are empty, we don't have to check for similarities if (string1.length() == 0 && string2.length() == 0) { return ""; } // Check if s2 is longer than s1 and if that's the case: swap them to ensure that s1 is always bigger. // This way we can reduce the amount of substrings we have to build (the longer word cant fully be part of the shorter word) if (string1.length() < string2.length()) { string tmp = string1; string1 = string2; string2 = tmp; } string max_string(""); string current_substring(""); for (int i(0); i < string2.length(); i++) { // assign tmp the first char of string2 current_substring = string2[i]; // loop as long as a substring beginning at position i can be found and the end of s2 hasn't been reached. while (string1.find(current_substring) != string::npos && (i + current_substring.length()) <= string2.length()) { if (current_substring.length() > max_string.length()) { max_string = current_substring; } // Add the next char of s2 to tmp, to increase substring length current_substring += string2[i + current_substring.length()]; } } return max_string; }
[ "bastianbreetz@gmail.com" ]
bastianbreetz@gmail.com
1bc450a760463ea9559496705b1638666ce9b691
87cab40982491da86314acc20338a737100ca4f2
/src/rpcwallet.cpp
6005f417e39eda3c820e652150801e9cc43e8b13
[ "MIT" ]
permissive
montero-altcoin/MTR
2a8f313057bd05a7c5c3bd3cd6251b5cccd79e5a
aaf3146924fba6ee3e49a490abfc39745d046b02
refs/heads/master
2023-08-11T01:50:40.834478
2021-10-08T21:14:06
2021-10-08T21:14:06
415,111,306
0
0
null
null
null
null
UTF-8
C++
false
false
55,051
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> #include "wallet.h" #include "walletdb.h" #include "bitcoinrpc.h" #include "init.h" #include "base58.h" using namespace std; using namespace boost; using namespace boost::assign; using namespace json_spirit; int64 nWalletUnlockTime; static CCriticalSection cs_nWalletUnlockTime; std::string HelpRequiringPassphrase() { return pwalletMain && pwalletMain->IsCrypted() ? "\nrequires wallet passphrase to be set with walletpassphrase first" : ""; } void EnsureWalletIsUnlocked() { if (pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); } void WalletTxToJSON(const CWalletTx& wtx, Object& entry) { int confirms = wtx.GetDepthInMainChain(); entry.push_back(Pair("confirmations", confirms)); if (wtx.IsCoinBase()) entry.push_back(Pair("generated", true)); if (confirms > 0) { entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex())); entry.push_back(Pair("blockindex", wtx.nIndex)); entry.push_back(Pair("blocktime", (boost::int64_t)(mapBlockIndex[wtx.hashBlock]->nTime))); } entry.push_back(Pair("txid", wtx.GetHash().GetHex())); entry.push_back(Pair("normtxid", wtx.GetNormalizedHash().GetHex())); entry.push_back(Pair("time", (boost::int64_t)wtx.GetTxTime())); entry.push_back(Pair("timereceived", (boost::int64_t)wtx.nTimeReceived)); BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue) entry.push_back(Pair(item.first, item.second)); } string AccountFromValue(const Value& value) { string strAccount = value.get_str(); if (strAccount == "*") throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name"); return strAccount; } Value getinfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getinfo\n" "Returns an object containing various state info."); proxyType proxy; GetProxy(NET_IPV4, proxy); Object obj; obj.push_back(Pair("version", (int)CLIENT_VERSION)); obj.push_back(Pair("protocolversion",(int)PROTOCOL_VERSION)); if (pwalletMain) { obj.push_back(Pair("walletversion", pwalletMain->GetVersion())); obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance()))); } obj.push_back(Pair("blocks", (int)nBestHeight)); obj.push_back(Pair("timeoffset", (boost::int64_t)GetTimeOffset())); obj.push_back(Pair("connections", (int)vNodes.size())); obj.push_back(Pair("proxy", (proxy.first.IsValid() ? proxy.first.ToStringIPPort() : string()))); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("testnet", fTestNet)); if (pwalletMain) { obj.push_back(Pair("keypoololdest", (boost::int64_t)pwalletMain->GetOldestKeyPoolTime())); obj.push_back(Pair("keypoolsize", (int)pwalletMain->GetKeyPoolSize())); } obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee))); obj.push_back(Pair("mininput", ValueFromAmount(nMinimumInputValue))); if (pwalletMain && pwalletMain->IsCrypted()) obj.push_back(Pair("unlocked_until", (boost::int64_t)nWalletUnlockTime)); obj.push_back(Pair("errors", GetWarnings("statusbar"))); return obj; } Value getnewaddress(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getnewaddress [account]\n" "Returns a new Montero address for receiving payments. " "If [account] is specified (recommended), it is added to the address book " "so payments received with the address will be credited to [account]."); // Parse the account first so we don't generate a key if there's an error string strAccount; if (params.size() > 0) strAccount = AccountFromValue(params[0]); if (!pwalletMain->IsLocked()) pwalletMain->TopUpKeyPool(); // Generate a new key that is added to wallet CPubKey newKey; if (!pwalletMain->GetKeyFromPool(newKey, false)) throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); CKeyID keyID = newKey.GetID(); pwalletMain->SetAddressBookName(keyID, strAccount); return CBitcoinAddress(keyID).ToString(); } CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew=false) { CWalletDB walletdb(pwalletMain->strWalletFile); CAccount account; walletdb.ReadAccount(strAccount, account); bool bKeyUsed = false; // Check if the current key has been used if (account.vchPubKey.IsValid()) { CScript scriptPubKey; scriptPubKey.SetDestination(account.vchPubKey.GetID()); for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid(); ++it) { const CWalletTx& wtx = (*it).second; BOOST_FOREACH(const CTxOut& txout, wtx.vout) if (txout.scriptPubKey == scriptPubKey) bKeyUsed = true; } } // Generate a new key if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed) { if (!pwalletMain->GetKeyFromPool(account.vchPubKey, false)) throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); pwalletMain->SetAddressBookName(account.vchPubKey.GetID(), strAccount); walletdb.WriteAccount(strAccount, account); } return CBitcoinAddress(account.vchPubKey.GetID()); } Value getaccountaddress(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaccountaddress <account>\n" "Returns the current Montero address for receiving payments to this account."); // Parse the account first so we don't generate a key if there's an error string strAccount = AccountFromValue(params[0]); Value ret; ret = GetAccountAddress(strAccount).ToString(); return ret; } Value setaccount(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "setaccount <Monteroaddress> <account>\n" "Sets the account associated with the given address."); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Montero address"); string strAccount; if (params.size() > 1) strAccount = AccountFromValue(params[1]); // Detect when changing the account of an address that is the 'unused current key' of another account: if (pwalletMain->mapAddressBook.count(address.Get())) { string strOldAccount = pwalletMain->mapAddressBook[address.Get()]; if (address == GetAccountAddress(strOldAccount)) GetAccountAddress(strOldAccount, true); } pwalletMain->SetAddressBookName(address.Get(), strAccount); return Value::null; } Value getaccount(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaccount <Monteroaddress>\n" "Returns the account associated with the given address."); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Montero address"); string strAccount; map<CTxDestination, string>::iterator mi = pwalletMain->mapAddressBook.find(address.Get()); if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.empty()) strAccount = (*mi).second; return strAccount; } Value getaddressesbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaddressesbyaccount <account>\n" "Returns the list of addresses for the given account."); string strAccount = AccountFromValue(params[0]); // Find all addresses that have the given account Array ret; BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook) { const CBitcoinAddress& address = item.first; const string& strName = item.second; if (strName == strAccount) ret.push_back(address.ToString()); } return ret; } Value setmininput(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 1) throw runtime_error( "setmininput <amount>\n" "<amount> is a real and is rounded to the nearest 0.00000001"); // Amount int64 nAmount = 0; if (params[0].get_real() != 0.0) nAmount = AmountFromValue(params[0]); // rejects 0.0 amounts nMinimumInputValue = nAmount; return true; } Value sendtoaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 4) throw runtime_error( "sendtoaddress <Monteroaddress> <amount> [comment] [comment-to]\n" "<amount> is a real and is rounded to the nearest 0.00000001" + HelpRequiringPassphrase()); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Montero address"); // Amount int64 nAmount = AmountFromValue(params[1]); // Wallet comments CWalletTx wtx; if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty()) wtx.mapValue["comment"] = params[2].get_str(); if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty()) wtx.mapValue["to"] = params[3].get_str(); if (pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx); if (strError != "") throw JSONRPCError(RPC_WALLET_ERROR, strError); return wtx.GetHash().GetHex(); } Value listaddressgroupings(const Array& params, bool fHelp) { if (fHelp) throw runtime_error( "listaddressgroupings\n" "Lists groups of addresses which have had their common ownership\n" "made public by common use as inputs or as the resulting change\n" "in past transactions"); Array jsonGroupings; map<CTxDestination, int64> balances = pwalletMain->GetAddressBalances(); BOOST_FOREACH(set<CTxDestination> grouping, pwalletMain->GetAddressGroupings()) { Array jsonGrouping; BOOST_FOREACH(CTxDestination address, grouping) { Array addressInfo; addressInfo.push_back(CBitcoinAddress(address).ToString()); addressInfo.push_back(ValueFromAmount(balances[address])); { LOCK(pwalletMain->cs_wallet); if (pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get()) != pwalletMain->mapAddressBook.end()) addressInfo.push_back(pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get())->second); } jsonGrouping.push_back(addressInfo); } jsonGroupings.push_back(jsonGrouping); } return jsonGroupings; } Value signmessage(const Array& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "signmessage <Monteroaddress> <message>\n" "Sign a message with the private key of an address"); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); string strMessage = params[1].get_str(); CBitcoinAddress addr(strAddress); if (!addr.IsValid()) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address"); CKeyID keyID; if (!addr.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key"); CKey key; if (!pwalletMain->GetKey(keyID, key)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available"); CHashWriter ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; vector<unsigned char> vchSig; if (!key.SignCompact(ss.GetHash(), vchSig)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed"); return EncodeBase64(&vchSig[0], vchSig.size()); } Value verifymessage(const Array& params, bool fHelp) { if (fHelp || params.size() != 3) throw runtime_error( "verifymessage <Monteroaddress> <signature> <message>\n" "Verify a signed message"); string strAddress = params[0].get_str(); string strSign = params[1].get_str(); string strMessage = params[2].get_str(); CBitcoinAddress addr(strAddress); if (!addr.IsValid()) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address"); CKeyID keyID; if (!addr.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key"); bool fInvalid = false; vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid); if (fInvalid) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding"); CHashWriter ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; CPubKey pubkey; if (!pubkey.RecoverCompact(ss.GetHash(), vchSig)) return false; return (pubkey.GetID() == keyID); } Value getreceivedbyaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getreceivedbyaddress <Monteroaddress> [minconf=1]\n" "Returns the total amount received by <Monteroaddress> in transactions with at least [minconf] confirmations."); // Bitcoin address CBitcoinAddress address = CBitcoinAddress(params[0].get_str()); CScript scriptPubKey; if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Montero address"); scriptPubKey.SetDestination(address.Get()); if (!IsMine(*pwalletMain,scriptPubKey)) return (double)0.0; // Minimum confirmations int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); // Tally int64 nAmount = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || !wtx.IsFinal()) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) if (txout.scriptPubKey == scriptPubKey) if (wtx.GetDepthInMainChain() >= nMinDepth) nAmount += txout.nValue; } return ValueFromAmount(nAmount); } void GetAccountAddresses(string strAccount, set<CTxDestination>& setAddress) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& item, pwalletMain->mapAddressBook) { const CTxDestination& address = item.first; const string& strName = item.second; if (strName == strAccount) setAddress.insert(address); } } Value getreceivedbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getreceivedbyaccount <account> [minconf=1]\n" "Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations."); // Minimum confirmations int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); // Get the set of pub keys assigned to account string strAccount = AccountFromValue(params[0]); set<CTxDestination> setAddress; GetAccountAddresses(strAccount, setAddress); // Tally int64 nAmount = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || !wtx.IsFinal()) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) { CTxDestination address; if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address)) if (wtx.GetDepthInMainChain() >= nMinDepth) nAmount += txout.nValue; } } return (double)nAmount / (double)COIN; } int64 GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth) { int64 nBalance = 0; // Tally wallet transactions for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (!wtx.IsFinal()) continue; int64 nReceived, nSent, nFee; wtx.GetAccountAmounts(strAccount, nReceived, nSent, nFee); if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth) nBalance += nReceived; nBalance -= nSent + nFee; } // Tally internal accounting entries nBalance += walletdb.GetAccountCreditDebit(strAccount); return nBalance; } int64 GetAccountBalance(const string& strAccount, int nMinDepth) { CWalletDB walletdb(pwalletMain->strWalletFile); return GetAccountBalance(walletdb, strAccount, nMinDepth); } Value getbalance(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "getbalance [account] [minconf=1]\n" "If [account] is not specified, returns the server's total available balance.\n" "If [account] is specified, returns the balance in the account."); if (params.size() == 0) return ValueFromAmount(pwalletMain->GetBalance()); int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); if (params[0].get_str() == "*") { // Calculate total balance a different way from GetBalance() // (GetBalance() sums up all unspent TxOuts) // getbalance and getbalance '*' 0 should return the same number int64 nBalance = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (!wtx.IsConfirmed()) continue; int64 allFee; string strSentAccount; list<pair<CTxDestination, int64> > listReceived; list<pair<CTxDestination, int64> > listSent; wtx.GetAmounts(listReceived, listSent, allFee, strSentAccount); if (wtx.GetDepthInMainChain() >= nMinDepth) { BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived) nBalance += r.second; } BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listSent) nBalance -= r.second; nBalance -= allFee; } return ValueFromAmount(nBalance); } string strAccount = AccountFromValue(params[0]); int64 nBalance = GetAccountBalance(strAccount, nMinDepth); return ValueFromAmount(nBalance); } Value movecmd(const Array& params, bool fHelp) { if (fHelp || params.size() < 3 || params.size() > 5) throw runtime_error( "move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n" "Move from one account in your wallet to another."); string strFrom = AccountFromValue(params[0]); string strTo = AccountFromValue(params[1]); int64 nAmount = AmountFromValue(params[2]); if (params.size() > 3) // unused parameter, used to be nMinDepth, keep type-checking it though (void)params[3].get_int(); string strComment; if (params.size() > 4) strComment = params[4].get_str(); CWalletDB walletdb(pwalletMain->strWalletFile); if (!walletdb.TxnBegin()) throw JSONRPCError(RPC_DATABASE_ERROR, "database error"); int64 nNow = GetAdjustedTime(); // Debit CAccountingEntry debit; debit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb); debit.strAccount = strFrom; debit.nCreditDebit = -nAmount; debit.nTime = nNow; debit.strOtherAccount = strTo; debit.strComment = strComment; walletdb.WriteAccountingEntry(debit); // Credit CAccountingEntry credit; credit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb); credit.strAccount = strTo; credit.nCreditDebit = nAmount; credit.nTime = nNow; credit.strOtherAccount = strFrom; credit.strComment = strComment; walletdb.WriteAccountingEntry(credit); if (!walletdb.TxnCommit()) throw JSONRPCError(RPC_DATABASE_ERROR, "database error"); return true; } Value sendfrom(const Array& params, bool fHelp) { if (fHelp || params.size() < 3 || params.size() > 6) throw runtime_error( "sendfrom <fromaccount> <toMonteroaddress> <amount> [minconf=1] [comment] [comment-to]\n" "<amount> is a real and is rounded to the nearest 0.00000001" + HelpRequiringPassphrase()); string strAccount = AccountFromValue(params[0]); CBitcoinAddress address(params[1].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Montero address"); int64 nAmount = AmountFromValue(params[2]); int nMinDepth = 1; if (params.size() > 3) nMinDepth = params[3].get_int(); CWalletTx wtx; wtx.strFromAccount = strAccount; if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty()) wtx.mapValue["comment"] = params[4].get_str(); if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty()) wtx.mapValue["to"] = params[5].get_str(); EnsureWalletIsUnlocked(); // Check funds int64 nBalance = GetAccountBalance(strAccount, nMinDepth); if (nAmount > nBalance) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds"); // Send string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx); if (strError != "") throw JSONRPCError(RPC_WALLET_ERROR, strError); return wtx.GetHash().GetHex(); } Value sendmany(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 4) throw runtime_error( "sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n" "amounts are double-precision floating point numbers" + HelpRequiringPassphrase()); string strAccount = AccountFromValue(params[0]); Object sendTo = params[1].get_obj(); int nMinDepth = 1; if (params.size() > 2) nMinDepth = params[2].get_int(); CWalletTx wtx; wtx.strFromAccount = strAccount; if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty()) wtx.mapValue["comment"] = params[3].get_str(); set<CBitcoinAddress> setAddress; vector<pair<CScript, int64> > vecSend; int64 totalAmount = 0; BOOST_FOREACH(const Pair& s, sendTo) { CBitcoinAddress address(s.name_); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Montero address: ")+s.name_); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_); setAddress.insert(address); CScript scriptPubKey; scriptPubKey.SetDestination(address.Get()); int64 nAmount = AmountFromValue(s.value_); totalAmount += nAmount; vecSend.push_back(make_pair(scriptPubKey, nAmount)); } EnsureWalletIsUnlocked(); // Check funds int64 nBalance = GetAccountBalance(strAccount, nMinDepth); if (totalAmount > nBalance) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds"); // Send CReserveKey keyChange(pwalletMain); int64 nFeeRequired = 0; string strFailReason; bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, strFailReason); if (!fCreated) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, strFailReason); if (!pwalletMain->CommitTransaction(wtx, keyChange)) throw JSONRPCError(RPC_WALLET_ERROR, "Transaction commit failed"); return wtx.GetHash().GetHex(); } // // Used by addmultisigaddress / createmultisig: // static CScript _createmultisig(const Array& params) { int nRequired = params[0].get_int(); const Array& keys = params[1].get_array(); // Gather public keys if (nRequired < 1) throw runtime_error("a multisignature address must require at least one key to redeem"); if ((int)keys.size() < nRequired) throw runtime_error( strprintf("not enough keys supplied " "(got %"PRIszu" keys, but need at least %d to redeem)", keys.size(), nRequired)); std::vector<CPubKey> pubkeys; pubkeys.resize(keys.size()); for (unsigned int i = 0; i < keys.size(); i++) { const std::string& ks = keys[i].get_str(); // Case 1: Montero address and we have full public key: CBitcoinAddress address(ks); if (pwalletMain && address.IsValid()) { CKeyID keyID; if (!address.GetKeyID(keyID)) throw runtime_error( strprintf("%s does not refer to a key",ks.c_str())); CPubKey vchPubKey; if (!pwalletMain->GetPubKey(keyID, vchPubKey)) throw runtime_error( strprintf("no full public key for address %s",ks.c_str())); if (!vchPubKey.IsFullyValid()) throw runtime_error(" Invalid public key: "+ks); pubkeys[i] = vchPubKey; } // Case 2: hex public key else if (IsHex(ks)) { CPubKey vchPubKey(ParseHex(ks)); if (!vchPubKey.IsFullyValid()) throw runtime_error(" Invalid public key: "+ks); pubkeys[i] = vchPubKey; } else { throw runtime_error(" Invalid public key: "+ks); } } CScript result; result.SetMultisig(nRequired, pubkeys); return result; } Value addmultisigaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 3) { string msg = "addmultisigaddress <nrequired> <'[\"key\",\"key\"]'> [account]\n" "Add a nrequired-to-sign multisignature address to the wallet\"\n" "each key is a Montero address or hex-encoded public key\n" "If [account] is specified, assign address to [account]."; throw runtime_error(msg); } string strAccount; if (params.size() > 2) strAccount = AccountFromValue(params[2]); // Construct using pay-to-script-hash: CScript inner = _createmultisig(params); CScriptID innerID = inner.GetID(); pwalletMain->AddCScript(inner); pwalletMain->SetAddressBookName(innerID, strAccount); return CBitcoinAddress(innerID).ToString(); } Value createmultisig(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 2) { string msg = "createmultisig <nrequired> <'[\"key\",\"key\"]'>\n" "Creates a multi-signature address and returns a json object\n" "with keys:\n" "address : Montero address\n" "redeemScript : hex-encoded redemption script"; throw runtime_error(msg); } // Construct using pay-to-script-hash: CScript inner = _createmultisig(params); CScriptID innerID = inner.GetID(); CBitcoinAddress address(innerID); Object result; result.push_back(Pair("address", address.ToString())); result.push_back(Pair("redeemScript", HexStr(inner.begin(), inner.end()))); return result; } struct tallyitem { int64 nAmount; int nConf; vector<uint256> txids; tallyitem() { nAmount = 0; nConf = std::numeric_limits<int>::max(); } }; Value ListReceived(const Array& params, bool fByAccounts) { // Minimum confirmations int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); // Whether to include empty accounts bool fIncludeEmpty = false; if (params.size() > 1) fIncludeEmpty = params[1].get_bool(); // Tally map<CBitcoinAddress, tallyitem> mapTally; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || !wtx.IsFinal()) continue; int nDepth = wtx.GetDepthInMainChain(); if (nDepth < nMinDepth) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) { CTxDestination address; if (!ExtractDestination(txout.scriptPubKey, address) || !IsMine(*pwalletMain, address)) continue; tallyitem& item = mapTally[address]; item.nAmount += txout.nValue; item.nConf = min(item.nConf, nDepth); item.txids.push_back(wtx.GetHash()); } } // Reply Array ret; map<string, tallyitem> mapAccountTally; BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook) { const CBitcoinAddress& address = item.first; const string& strAccount = item.second; map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address); if (it == mapTally.end() && !fIncludeEmpty) continue; int64 nAmount = 0; int nConf = std::numeric_limits<int>::max(); if (it != mapTally.end()) { nAmount = (*it).second.nAmount; nConf = (*it).second.nConf; } if (fByAccounts) { tallyitem& item = mapAccountTally[strAccount]; item.nAmount += nAmount; item.nConf = min(item.nConf, nConf); } else { Object obj; obj.push_back(Pair("address", address.ToString())); obj.push_back(Pair("account", strAccount)); obj.push_back(Pair("amount", ValueFromAmount(nAmount))); obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf))); Array transactions; if (it != mapTally.end()) { BOOST_FOREACH(const uint256& item, (*it).second.txids) { transactions.push_back(item.GetHex()); } } obj.push_back(Pair("txids", transactions)); ret.push_back(obj); } } if (fByAccounts) { for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it) { int64 nAmount = (*it).second.nAmount; int nConf = (*it).second.nConf; Object obj; obj.push_back(Pair("account", (*it).first)); obj.push_back(Pair("amount", ValueFromAmount(nAmount))); obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf))); ret.push_back(obj); } } return ret; } Value listreceivedbyaddress(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "listreceivedbyaddress [minconf=1] [includeempty=false]\n" "[minconf] is the minimum number of confirmations before payments are included.\n" "[includeempty] whether to include addresses that haven't received any payments.\n" "Returns an array of objects containing:\n" " \"address\" : receiving address\n" " \"account\" : the account of the receiving address\n" " \"amount\" : total amount received by the address\n" " \"confirmations\" : number of confirmations of the most recent transaction included\n" " \"txids\" : list of transactions with outputs to the address\n"); return ListReceived(params, false); } Value listreceivedbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "listreceivedbyaccount [minconf=1] [includeempty=false]\n" "[minconf] is the minimum number of confirmations before payments are included.\n" "[includeempty] whether to include accounts that haven't received any payments.\n" "Returns an array of objects containing:\n" " \"account\" : the account of the receiving addresses\n" " \"amount\" : total amount received by addresses with this account\n" " \"confirmations\" : number of confirmations of the most recent transaction included"); return ListReceived(params, true); } static void MaybePushAddress(Object & entry, const CTxDestination &dest) { CBitcoinAddress addr; if (addr.Set(dest)) entry.push_back(Pair("address", addr.ToString())); } void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, Array& ret) { int64 nFee; string strSentAccount; list<pair<CTxDestination, int64> > listReceived; list<pair<CTxDestination, int64> > listSent; wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount); bool fAllAccounts = (strAccount == string("*")); // Sent if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount)) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent) { Object entry; entry.push_back(Pair("account", strSentAccount)); MaybePushAddress(entry, s.first); entry.push_back(Pair("category", "send")); entry.push_back(Pair("amount", ValueFromAmount(-s.second))); entry.push_back(Pair("fee", ValueFromAmount(-nFee))); if (fLong) WalletTxToJSON(wtx, entry); ret.push_back(entry); } } // Received if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived) { string account; if (pwalletMain->mapAddressBook.count(r.first)) account = pwalletMain->mapAddressBook[r.first]; if (fAllAccounts || (account == strAccount)) { Object entry; entry.push_back(Pair("account", account)); MaybePushAddress(entry, r.first); if (wtx.IsCoinBase()) { if (wtx.GetDepthInMainChain() < 1) entry.push_back(Pair("category", "orphan")); else if (wtx.GetBlocksToMaturity() > 0) entry.push_back(Pair("category", "immature")); else entry.push_back(Pair("category", "generate")); } else { entry.push_back(Pair("category", "receive")); } entry.push_back(Pair("amount", ValueFromAmount(r.second))); if (fLong) WalletTxToJSON(wtx, entry); ret.push_back(entry); } } } } void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Array& ret) { bool fAllAccounts = (strAccount == string("*")); if (fAllAccounts || acentry.strAccount == strAccount) { Object entry; entry.push_back(Pair("account", acentry.strAccount)); entry.push_back(Pair("category", "move")); entry.push_back(Pair("time", (boost::int64_t)acentry.nTime)); entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit))); entry.push_back(Pair("otheraccount", acentry.strOtherAccount)); entry.push_back(Pair("comment", acentry.strComment)); ret.push_back(entry); } } Value listtransactions(const Array& params, bool fHelp) { if (fHelp || params.size() > 3) throw runtime_error( "listtransactions [account] [count=10] [from=0]\n" "Returns up to [count] most recent transactions skipping the first [from] transactions for account [account]."); string strAccount = "*"; if (params.size() > 0) strAccount = params[0].get_str(); int nCount = 10; if (params.size() > 1) nCount = params[1].get_int(); int nFrom = 0; if (params.size() > 2) nFrom = params[2].get_int(); if (nCount < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count"); if (nFrom < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from"); Array ret; std::list<CAccountingEntry> acentries; CWallet::TxItems txOrdered = pwalletMain->OrderedTxItems(acentries, strAccount); // iterate backwards until we have nCount items to return: for (CWallet::TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) { CWalletTx *const pwtx = (*it).second.first; if (pwtx != 0) ListTransactions(*pwtx, strAccount, 0, true, ret); CAccountingEntry *const pacentry = (*it).second.second; if (pacentry != 0) AcentryToJSON(*pacentry, strAccount, ret); if ((int)ret.size() >= (nCount+nFrom)) break; } // ret is newest to oldest if (nFrom > (int)ret.size()) nFrom = ret.size(); if ((nFrom + nCount) > (int)ret.size()) nCount = ret.size() - nFrom; Array::iterator first = ret.begin(); std::advance(first, nFrom); Array::iterator last = ret.begin(); std::advance(last, nFrom+nCount); if (last != ret.end()) ret.erase(last, ret.end()); if (first != ret.begin()) ret.erase(ret.begin(), first); std::reverse(ret.begin(), ret.end()); // Return oldest to newest return ret; } Value listaccounts(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "listaccounts [minconf=1]\n" "Returns Object that has account names as keys, account balances as values."); int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); map<string, int64> mapAccountBalances; BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& entry, pwalletMain->mapAddressBook) { if (IsMine(*pwalletMain, entry.first)) // This address belongs to me mapAccountBalances[entry.second] = 0; } for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; int64 nFee; string strSentAccount; list<pair<CTxDestination, int64> > listReceived; list<pair<CTxDestination, int64> > listSent; wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount); mapAccountBalances[strSentAccount] -= nFee; BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent) mapAccountBalances[strSentAccount] -= s.second; if (wtx.GetDepthInMainChain() >= nMinDepth) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived) if (pwalletMain->mapAddressBook.count(r.first)) mapAccountBalances[pwalletMain->mapAddressBook[r.first]] += r.second; else mapAccountBalances[""] += r.second; } } list<CAccountingEntry> acentries; CWalletDB(pwalletMain->strWalletFile).ListAccountCreditDebit("*", acentries); BOOST_FOREACH(const CAccountingEntry& entry, acentries) mapAccountBalances[entry.strAccount] += entry.nCreditDebit; Object ret; BOOST_FOREACH(const PAIRTYPE(string, int64)& accountBalance, mapAccountBalances) { ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second))); } return ret; } Value listsinceblock(const Array& params, bool fHelp) { if (fHelp) throw runtime_error( "listsinceblock [blockhash] [target-confirmations]\n" "Get all transactions in blocks since block [blockhash], or all transactions if omitted"); CBlockIndex *pindex = NULL; int target_confirms = 1; if (params.size() > 0) { uint256 blockId = 0; blockId.SetHex(params[0].get_str()); pindex = CBlockLocator(blockId).GetBlockIndex(); } if (params.size() > 1) { target_confirms = params[1].get_int(); if (target_confirms < 1) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter"); } int depth = pindex ? (1 + nBestHeight - pindex->nHeight) : -1; Array transactions; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++) { CWalletTx tx = (*it).second; if (depth == -1 || tx.GetDepthInMainChain() < depth) ListTransactions(tx, "*", 0, true, transactions); } uint256 lastblock; if (target_confirms == 1) { lastblock = hashBestChain; } else { int target_height = pindexBest->nHeight + 1 - target_confirms; CBlockIndex *block; for (block = pindexBest; block && block->nHeight > target_height; block = block->pprev) { } lastblock = block ? block->GetBlockHash() : 0; } Object ret; ret.push_back(Pair("transactions", transactions)); ret.push_back(Pair("lastblock", lastblock.GetHex())); return ret; } Value gettransaction(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "gettransaction <txid>\n" "Get detailed information about in-wallet transaction <txid>"); uint256 hash; hash.SetHex(params[0].get_str()); Object entry; if (!pwalletMain->mapWallet.count(hash)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id"); const CWalletTx& wtx = pwalletMain->mapWallet[hash]; int64 nCredit = wtx.GetCredit(); int64 nDebit = wtx.GetDebit(); int64 nNet = nCredit - nDebit; int64 nFee = (wtx.IsFromMe() ? wtx.GetValueOut() - nDebit : 0); entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee))); if (wtx.IsFromMe()) entry.push_back(Pair("fee", ValueFromAmount(nFee))); WalletTxToJSON(wtx, entry); Array details; ListTransactions(wtx, "*", 0, false, details); entry.push_back(Pair("details", details)); return entry; } Value backupwallet(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "backupwallet <destination>\n" "Safely copies wallet.dat to destination, which can be a directory or a path with filename."); string strDest = params[0].get_str(); if (!BackupWallet(*pwalletMain, strDest)) throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!"); return Value::null; } Value keypoolrefill(const Array& params, bool fHelp) { if (fHelp || params.size() > 0) throw runtime_error( "keypoolrefill\n" "Fills the keypool." + HelpRequiringPassphrase()); EnsureWalletIsUnlocked(); pwalletMain->TopUpKeyPool(); if (pwalletMain->GetKeyPoolSize() < GetArg("-keypool", 100)) throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool."); return Value::null; } void ThreadTopUpKeyPool(void* parg) { // Make this thread recognisable as the key-topping-up thread RenameThread("bitcoin-key-top"); pwalletMain->TopUpKeyPool(); } void ThreadCleanWalletPassphrase(void* parg) { // Make this thread recognisable as the wallet relocking thread RenameThread("bitcoin-lock-wa"); int64 nMyWakeTime = GetTimeMillis() + *((int64*)parg) * 1000; ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime); if (nWalletUnlockTime == 0) { nWalletUnlockTime = nMyWakeTime; do { if (nWalletUnlockTime==0) break; int64 nToSleep = nWalletUnlockTime - GetTimeMillis(); if (nToSleep <= 0) break; LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime); MilliSleep(nToSleep); ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime); } while(1); if (nWalletUnlockTime) { nWalletUnlockTime = 0; pwalletMain->Lock(); } } else { if (nWalletUnlockTime < nMyWakeTime) nWalletUnlockTime = nMyWakeTime; } LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime); delete (int64*)parg; } Value walletpassphrase(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2)) throw runtime_error( "walletpassphrase <passphrase> <timeout>\n" "Stores the wallet decryption key in memory for <timeout> seconds."); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called."); if (!pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_ALREADY_UNLOCKED, "Error: Wallet is already unlocked."); // Note that the walletpassphrase is stored in params[0] which is not mlock()ed SecureString strWalletPass; strWalletPass.reserve(100); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. strWalletPass = params[0].get_str().c_str(); if (strWalletPass.length() > 0) { if (!pwalletMain->Unlock(strWalletPass)) throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect."); } else throw runtime_error( "walletpassphrase <passphrase> <timeout>\n" "Stores the wallet decryption key in memory for <timeout> seconds."); NewThread(ThreadTopUpKeyPool, NULL); int64* pnSleepTime = new int64(params[1].get_int64()); NewThread(ThreadCleanWalletPassphrase, pnSleepTime); return Value::null; } Value walletpassphrasechange(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2)) throw runtime_error( "walletpassphrasechange <oldpassphrase> <newpassphrase>\n" "Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>."); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called."); // TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. SecureString strOldWalletPass; strOldWalletPass.reserve(100); strOldWalletPass = params[0].get_str().c_str(); SecureString strNewWalletPass; strNewWalletPass.reserve(100); strNewWalletPass = params[1].get_str().c_str(); if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1) throw runtime_error( "walletpassphrasechange <oldpassphrase> <newpassphrase>\n" "Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>."); if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass)) throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect."); return Value::null; } Value walletlock(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0)) throw runtime_error( "walletlock\n" "Removes the wallet encryption key from memory, locking the wallet.\n" "After calling this method, you will need to call walletpassphrase again\n" "before being able to call any methods which require the wallet to be unlocked."); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called."); { LOCK(cs_nWalletUnlockTime); pwalletMain->Lock(); nWalletUnlockTime = 0; } return Value::null; } Value encryptwallet(const Array& params, bool fHelp) { if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1)) throw runtime_error( "encryptwallet <passphrase>\n" "Encrypts the wallet with <passphrase>."); if (fHelp) return true; if (pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called."); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. SecureString strWalletPass; strWalletPass.reserve(100); strWalletPass = params[0].get_str().c_str(); if (strWalletPass.length() < 1) throw runtime_error( "encryptwallet <passphrase>\n" "Encrypts the wallet with <passphrase>."); if (!pwalletMain->EncryptWallet(strWalletPass)) throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet."); // BDB seems to have a bad habit of writing old data into // slack space in .dat files; that is bad if the old data is // unencrypted private keys. So: StartShutdown(); return "wallet encrypted; Montero server stopping, restart to run with encrypted wallet. The keypool has been flushed, you need to make a new backup."; } class DescribeAddressVisitor : public boost::static_visitor<Object> { public: Object operator()(const CNoDestination &dest) const { return Object(); } Object operator()(const CKeyID &keyID) const { Object obj; CPubKey vchPubKey; pwalletMain->GetPubKey(keyID, vchPubKey); obj.push_back(Pair("isscript", false)); obj.push_back(Pair("pubkey", HexStr(vchPubKey))); obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed())); return obj; } Object operator()(const CScriptID &scriptID) const { Object obj; obj.push_back(Pair("isscript", true)); CScript subscript; pwalletMain->GetCScript(scriptID, subscript); std::vector<CTxDestination> addresses; txnouttype whichType; int nRequired; ExtractDestinations(subscript, whichType, addresses, nRequired); obj.push_back(Pair("script", GetTxnOutputType(whichType))); Array a; BOOST_FOREACH(const CTxDestination& addr, addresses) a.push_back(CBitcoinAddress(addr).ToString()); obj.push_back(Pair("addresses", a)); if (whichType == TX_MULTISIG) obj.push_back(Pair("sigsrequired", nRequired)); return obj; } }; Value validateaddress(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "validateaddress <Monteroaddress>\n" "Return information about <Monteroaddress>."); CBitcoinAddress address(params[0].get_str()); bool isValid = address.IsValid(); Object ret; ret.push_back(Pair("isvalid", isValid)); if (isValid) { CTxDestination dest = address.Get(); string currentAddress = address.ToString(); ret.push_back(Pair("address", currentAddress)); bool fMine = pwalletMain ? IsMine(*pwalletMain, dest) : false; ret.push_back(Pair("ismine", fMine)); if (fMine) { Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest); ret.insert(ret.end(), detail.begin(), detail.end()); } if (pwalletMain && pwalletMain->mapAddressBook.count(dest)) ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest])); } return ret; } Value lockunspent(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "lockunspent unlock? [array-of-Objects]\n" "Updates list of temporarily unspendable outputs."); if (params.size() == 1) RPCTypeCheck(params, list_of(bool_type)); else RPCTypeCheck(params, list_of(bool_type)(array_type)); bool fUnlock = params[0].get_bool(); if (params.size() == 1) { if (fUnlock) pwalletMain->UnlockAllCoins(); return true; } Array outputs = params[1].get_array(); BOOST_FOREACH(Value& output, outputs) { if (output.type() != obj_type) throw JSONRPCError(-8, "Invalid parameter, expected object"); const Object& o = output.get_obj(); RPCTypeCheck(o, map_list_of("txid", str_type)("vout", int_type)); string txid = find_value(o, "txid").get_str(); if (!IsHex(txid)) throw JSONRPCError(-8, "Invalid parameter, expected hex txid"); int nOutput = find_value(o, "vout").get_int(); if (nOutput < 0) throw JSONRPCError(-8, "Invalid parameter, vout must be positive"); COutPoint outpt(uint256(txid), nOutput); if (fUnlock) pwalletMain->UnlockCoin(outpt); else pwalletMain->LockCoin(outpt); } return true; } Value listlockunspent(const Array& params, bool fHelp) { if (fHelp || params.size() > 0) throw runtime_error( "listlockunspent\n" "Returns list of temporarily unspendable outputs."); vector<COutPoint> vOutpts; pwalletMain->ListLockedCoins(vOutpts); Array ret; BOOST_FOREACH(COutPoint &outpt, vOutpts) { Object o; o.push_back(Pair("txid", outpt.hash.GetHex())); o.push_back(Pair("vout", (int)outpt.n)); ret.push_back(o); } return ret; }
[ "bjnsa94@gmail.com" ]
bjnsa94@gmail.com
046621303ffdd50ec93646244bad0ab84d0149a0
65834746597ab5160debf5df07e02f7fbe2299e2
/QLearning/test/RewardLambda.cpp
54dc0e81f7d9e89d6fe01f12e8b541d79748555e
[]
no_license
hans00/GeneralML
8f28448c2cad791c6c024dcfbed4328d84501dae
91dd4994c16abfe82642209ff2c7d119c4ee5a34
refs/heads/master
2021-01-23T04:59:13.254565
2017-06-02T06:27:58
2017-06-02T06:27:58
92,948,199
0
1
null
null
null
null
UTF-8
C++
false
false
919
cpp
// // main.cpp // QLearn // // Created by Hans on 2017/5/27. // Copyright © 2017年 Hans. All rights reserved. // #include <iostream> #include <QLearn/QLearn.hpp> #include "Memory.h" using namespace std; int RewardLambda() { cout << "Q-Learning with lambda reward function." << endl; volatile size_t before = memory_used(); QLearn<3, 3> qlearn([] (uint s, uint a)->LearnType { return s + a; }); cout << "Memory used: " << memory_used()-before << "B" << endl; cout << "Learning test"; uint stat, prev_stat = 0; for (uint t=0; t < 100; t++) { uint act = t % 3; stat = prev_stat/5.0 + act/5.0 + (t%3)/5.0 + ((act*act)%3)/5.0 + ((prev_stat*prev_stat*prev_stat)%3)/5.0; qlearn.Learn(prev_stat, stat, act, 0.89, 0.8); prev_stat = stat; if (!(t%15)) cout << "."; } cout << " OK" << endl; qlearn.PrintMatrix(); return 0; }
[ "jy29825377@gmail.com" ]
jy29825377@gmail.com
3420939a66031708bc46a01ea337209748bc8515
cc0e498dc6a2f5dd9309bb2fdf6a9b75c6b57f97
/ExaHyPE/exahype/parser/ParserView.cpp
a599131a1e4f8c33cf5a6c5e8050155c827d81d7
[ "BSD-3-Clause", "LicenseRef-scancode-free-unknown" ]
permissive
annereinarz/ExaHyPE-Workshop-Engine
cbae7c7e40ed4184205e6f723c2ac91105d6a210
714a6052a8accace0235fd2483566d7e9cbacb0a
refs/heads/master
2022-02-25T15:56:50.652168
2019-10-17T09:11:30
2019-10-17T09:11:30
198,189,738
2
3
BSD-3-Clause
2019-07-22T11:56:14
2019-07-22T09:20:56
C++
UTF-8
C++
false
false
6,680
cpp
/** * This file is part of the ExaHyPE project. * Copyright (c) 2016 http://exahype.eu * All rights reserved. * * The project has received funding from the European Union's Horizon * 2020 research and innovation programme under grant agreement * No 671698. For copyrights and licensing, please consult the webpage. * * Released under the BSD 3 Open Source License. * For the full license text, see LICENSE.txt **/ #include "exahype/parser/ParserView.h" #include "tarch/Assertions.h" #include <fstream> #include <stdio.h> #include <string.h> #include <string> #include <regex> #include <cstdlib> // getenv, exit #include <sstream> #include "tarch/la/ScalarOperations.h" #include "exahype/parser/Parser.h" tarch::logging::Log exahype::parser::ParserView::_log( "exahype::parser::ParserView" ); exahype::parser::ParserView::ParserView(const exahype::parser::Parser* parser, std::string basePath) : _parser(parser), _basePath(basePath) {} std::string exahype::parser::ParserView::getPath(const std::string& key) const { return (key.empty() ? _basePath : (_basePath + "/" + key)); } bool exahype::parser::ParserView::isEmpty() const { return _parser==nullptr; // TODO: Actually this check should check wether the _basePath exists and, if so, // check wether it holds an empty dictionary, cf. empty() call on // https://nlohmann.github.io/json/ -- however, such an API has to be exposed // by the parser itself // // || ( getParser().hasPath(getPath("")) && getParser() // assertion(getParser().isValid()); } bool exahype::parser::ParserView::hasKey(const std::string& key) const { if (_parser!=nullptr) { assertion(getParser().isValid()); return getParser().hasPath(getPath(key)); } else { return false; } } int exahype::parser::ParserView::getValueAsInt(const std::string& key) const { if (_parser!=nullptr) { return getParser().getIntFromPath(getPath(key)); } else { logError("getValueAsInt()", "No parameters found at all!"); std::abort(); return 0; } } bool exahype::parser::ParserView::getValueAsBool(const std::string& key) const { if (_parser!=nullptr) { return getParser().getBoolFromPath(getPath(key)); } else { logError("getValueAsBool()", "No parameters found at all!"); std::abort(); return false; } } double exahype::parser::ParserView::getValueAsDouble( const std::string& key) const { if (_parser!=nullptr) { return getParser().getDoubleFromPath(getPath(key)); } else { logError("getValueAsDouble()", "No parameters found at all!"); std::abort(); return 0.0; } } std::string exahype::parser::ParserView::getValueAsString( const std::string& key) const { if (_parser!=nullptr) { return getParser().getStringFromPath(getPath(key)); } else { logError("getValueAsString()", "No parameters found at all!"); std::abort(); return ""; } } bool exahype::parser::ParserView::isValueValidInt( const std::string& key) const { if (_parser!=nullptr) { return getParser().isValueValidInt(getPath(key)); } else { logError("isValueValidInt()", "No parameters found at all!"); std::abort(); return false; } } bool exahype::parser::ParserView::isValueValidDouble( const std::string& key) const { if (_parser!=nullptr) { return getParser().isValueValidDouble(getPath(key)); } else { logError("isValueValidDouble()", "No parameters found at all!"); std::abort(); return false; } } bool exahype::parser::ParserView::isValueValidBool( const std::string& key) const { if (_parser!=nullptr) { return getParser().isValueValidBool(getPath(key)); } else { logError("isValueValidBool()", "No parameters found at all!"); std::abort(); return false; } } bool exahype::parser::ParserView::getValueAsBoolOrDefault(const std::string& key, bool default_value) const { return isValueValidBool(key) ? getValueAsBool(key) : default_value; } int exahype::parser::ParserView::getValueAsIntOrDefault(const std::string& key, int default_value) const { return isValueValidInt(key) ? getValueAsInt(key) : default_value; } double exahype::parser::ParserView::getValueAsDoubleOrDefault(const std::string& key, double default_value) const { return isValueValidDouble(key) ? getValueAsDouble(key) : default_value; } std::string exahype::parser::ParserView::getValueAsStringOrDefault(const std::string& key, std::string default_value) const { return isValueValidString(key) ? getValueAsString(key) : default_value; } std::vector< std::pair<std::string, std::string> > exahype::parser::ParserView::getAllAsOrderedMap() const { // Expect the data to be in an object, if not then fail. if (_parser!=nullptr && getParser().hasPath(_basePath)) { return getParser().getObjectAsVectorOfStringPair(_basePath, true); } else { logError("getAllAsOrderedMap()", "No parameters found at all!"); std::abort(); std::vector< std::pair<std::string, std::string> > retvec; return retvec; } } std::map<std::string, std::string> exahype::parser::ParserView::getAllAsMap() const { std::map<std::string, std::string> retmap; // Well, this makes no sense in the moment and therefore I won't implement it. // It does not make sense anymore because constants may be any kind of nested // data. logError("getAllAsMap()", "Not yet implemented"); return retmap; } bool exahype::parser::ParserView::isValueValidString( const std::string& key) const { if (_parser!=nullptr) { return getParser().isValueValidString(getPath(key)); } else { logError("isValueValidString()", "No parameters found at all!"); std::abort(); return false; } } const exahype::parser::Parser& exahype::parser::ParserView::getParser() const { if(!_parser) { logError("getParser()", "Trying to use a non-initialised parserView!"); std::abort(); } return *_parser; } std::string exahype::parser::ParserView::toString() const { std::ostringstream stringstr; toString(stringstr); return stringstr.str(); } void exahype::parser::ParserView::toString(std::ostream& out) const { if (_parser!=nullptr) { out << "ParserView("; out << "specfile:" << getParser().getSpecfileName(); out << ","; out << "basePath:" << _basePath; out << ")"; } { out << "ParserView(<empty>)"; } } std::string exahype::parser::ParserView::dump(const std::string path) const { if (_parser!=nullptr) { return getParser().dumpPath(getPath(path)); } else { return std::string("<") + getPath(path) + "> not available"; } }
[ "reinarz@in.tum.de" ]
reinarz@in.tum.de
54136217db304288c0e7d768639e3bc9e94b91fc
e94443ce5161d70f799f096dbf74b58e52f311cf
/src/sgs_data/sgsdata_skill.h
72231aba9ad6d594964610847a1ab87d5b25f600
[]
no_license
zwsatan/Sanguosha
dd455d437b4e9e30b907ed04e5e87686bf877e13
0ce4264f832fd3f7e35674885c8c277ec464d12f
refs/heads/master
2016-09-05T13:59:59.673946
2013-08-22T14:28:22
2013-08-22T14:28:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
731
h
#ifndef _SGSDATA_SKILL_H #define _SGSDATA_SKILL_H #include "sgsdata_enum.h" #include "sgsdata_namespace.h" class sgs::DataType::Skill { public: Skill(); // 转换构造 Skill(sgs::ConstData::HeroSkill heroSkill); // 访问技能类型 sgs::ConstData::HeroSkill skill() const; // 调用处理器函数 sgs::DataType::Message* settle(sgs::DataType::Message * msg) const; private: // 由技能类型找到函数 void protrans(sgs::ConstData::HeroSkill skill); private: typedef sgs::DataType::Message* (*SkillProcessHandle)(sgs::DataType::Message*); sgs::ConstData::HeroSkill m_skill; // 技能类型 SkillProcessHandle m_processor; // 处理器 }; #endif /*_SGSDATA_SKILL_H*/
[ "zwsatan420@163.com" ]
zwsatan420@163.com
31e205941e6f73882169b9d2d3d2b48e978103a5
e84e19c5d52f511ae280bb02d2febb8e0650a116
/code105.cpp
16b69e0a49ddfc0212d5e21e6d04267a5a51c513
[]
no_license
AlJamilSuvo/LeetCode
2e3afe0c588d003aa15ea3eb08a8d2ca381c35dd
9ad26f2974ad4a41a9654a5564fe1ad27ae2463c
refs/heads/master
2022-03-15T15:43:21.826485
2022-03-04T20:40:50
2022-03-04T20:40:50
174,458,244
1
0
null
null
null
null
UTF-8
C++
false
false
1,274
cpp
#include "tree_node_util.hpp" class Solution { public: TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { int val = preorder[0]; int len = preorder.size(); TreeNode *node = new TreeNode(val); if (len == 1) return node; int leftTreeSize = 0; int rightTreeSize = 0; for (int i = 0; i < inorder.size(); i++) { if (inorder[i] == val) break; leftTreeSize += 1; } rightTreeSize = len - leftTreeSize - 1; if (leftTreeSize > 0) { vector<int> leftPre, leftIn; for (int i = 0; i < leftTreeSize; i++) { leftPre.push_back(preorder[1 + i]); leftIn.push_back(inorder[i]); } node->left = buildTree(leftPre, leftIn); } if (rightTreeSize > 0) { vector<int> rightPre, rightIn; for (int i = 0; i < rightTreeSize; i++) { rightPre.push_back(preorder[1 + leftTreeSize + i]); rightIn.push_back(inorder[1 + leftTreeSize + i]); } node->right = buildTree(rightPre, rightIn); } return node; } };
[ "aljamilsuvo@gmail.com" ]
aljamilsuvo@gmail.com
640e2265b760b42db1eaa03646b1ccfa04d37a13
1f183a2b4ced386f4917685b8c01cbafab021306
/ChaosEngine/src/Platform/Vulkan/VulkanInitalizers.h
0c8615716beeea42c6e6cb005bccc7df43c8754e
[ "Apache-2.0" ]
permissive
JJRWalker/ChaosEngine
379004396be5a6e51bef5f5969ad0299c00c865d
47efb82cf8fac75af50ae639b85423304c90a52f
refs/heads/master
2023-07-08T23:06:21.734779
2021-08-09T16:04:39
2021-08-09T16:04:39
238,705,660
3
0
null
null
null
null
UTF-8
C++
false
false
2,445
h
/* date = April 22nd 2021 8:40 am */ #ifndef _VULKAN_INITALIZERS_H #define _VULKAN_INITALIZERS_H #include "VulkanTypes.h" namespace VkInit { VkCommandPoolCreateInfo CommandPoolCreateInfo(uint32_t queueFamilyIndex, VkCommandPoolCreateFlags flags = 0); VkCommandBufferAllocateInfo CommandBufferAllocateInfo(VkCommandPool pool, uint32_t count = 1, VkCommandBufferLevel level = VK_COMMAND_BUFFER_LEVEL_PRIMARY); VkCommandBufferBeginInfo CommandBufferBeginInfo(VkCommandBufferUsageFlags flags = 0); VkFramebufferCreateInfo FramebufferCreateInfo(VkRenderPass renderpass, VkExtent2D extent); VkFenceCreateInfo FenceCreateInfo(VkFenceCreateFlags flags = 0); VkSemaphoreCreateInfo SemaphoreCreateInfo(VkSemaphoreCreateFlags flags = 0); VkSubmitInfo SubmitInfo(VkCommandBuffer* cmd); VkPresentInfoKHR PresentInfo(); VkRenderPassBeginInfo RenderpassBeginInfo(VkRenderPass renderpass, VkExtent2D windowExtent, VkFramebuffer framebuffer); VkPipelineShaderStageCreateInfo PipelineShaderStageCreateInfo(VkShaderStageFlagBits stage, VkShaderModule shaderModule); VkPipelineVertexInputStateCreateInfo VertexInputCreateInfo(); VkPipelineInputAssemblyStateCreateInfo InputAssemblyCreateInfo(VkPrimitiveTopology topology); VkPipelineRasterizationStateCreateInfo RasterizationStateCreateInfo(VkPolygonMode polygonMode); VkPipelineMultisampleStateCreateInfo MultisamlingStateCreateInfo(); VkPipelineColorBlendAttachmentState ColourBlendAttachmentState(); VkPipelineLayoutCreateInfo PipelineLayoutCreateInfo(); VkImageCreateInfo ImageCreateInfo(VkFormat format, VkImageUsageFlags usageFlags, VkExtent3D extent); VkImageViewCreateInfo ImageViewCreateInfo(VkFormat format, VkImage image, VkImageAspectFlags aspectFlags); VkPipelineDepthStencilStateCreateInfo DepthStencilCreateInfo(bool bDepthTest, bool bDepthWrite, VkCompareOp compareOp); VkDescriptorSetLayoutBinding DescriptorSetLayoutBinding(VkDescriptorType type, VkShaderStageFlags stageFlags, uint32_t binding); VkWriteDescriptorSet WriteDescriptorBuffer(VkDescriptorType type, VkDescriptorSet dstSet, VkDescriptorBufferInfo* bufferInfo, uint32_t binding); VkSamplerCreateInfo SamplerCreateInfo(VkFilter filters, VkSamplerAddressMode samplerAddressMode = VK_SAMPLER_ADDRESS_MODE_REPEAT); VkWriteDescriptorSet WriteDescriptorImage(VkDescriptorType type, VkDescriptorSet dstSet, VkDescriptorImageInfo* imageInfo, uint32_t binding); } #endif //_VULKAN_INITALIZERS_H
[ "jjrwalkerdev@gmail.com" ]
jjrwalkerdev@gmail.com
8839b780f218686b3526d6cee113072a6d6db1f8
0938bc4861ceb6c93a3bea2ce4a3f641b42da6af
/Arduino/2_Button/Button/Button.ino
4dfb660fcbe58bdc2ccc2b3bacf482ad8c2af468
[]
no_license
Zikt/robolab_bmo
8e4d1f6c85f1019cdbd0eef8435f9e77e664fd4c
7adc858275d66a832fbf1f3674fe709285798c98
refs/heads/master
2023-01-31T20:21:48.134038
2020-12-18T14:58:35
2020-12-18T14:58:35
313,338,113
0
0
null
null
null
null
UTF-8
C++
false
false
2,346
ino
/* О чтении сигнала на дискретном пине... (https://alexgyver.ru/lessons/digital/) Подключаем к пину значение +5В через кнопку: _____/ ____ | | + pin */ /* const int button_pin = 2; boolean button; void setup() { pinMode(button_pin, INPUT); Serial.begin(9600); } void loop() { button = digitalRead(button_pin); Serial.print("Button: ");Serial.println(button); } */ /* ...в результате получаем наводки, когда кнопка разомкнута. Чтобы избежать наводок необхоидмо подключить резистор большого сопротивления 10 кОм и замкнуть пин к земле: ___/ ____rrrrr____ | | | + pin - Теперь при размыкании кнопки все наводки уходят "в землю". Такой резистор называется PULL-DOWN (тянет к земле) Однако схема усложнилась, появился лишний резистор. К счастью, эту проблему решили и пины Arduino уже имеют подтягивающие резисторы, но с одной оговоркой, он подключен не к земле, как на схеме выше, а к питанию: ___/ ____rrrrr____ | | | - pin + Такой подтягивающий резистор называется PULL-UP (тянущий к питанию). Как видим, для корректной работы необходимо подключить пин через ключ к земле. При разомкнутой кнопке на пин поступает сигнал 1, при замкнутой - сигнал уходит в землю и на пине - 0. Чтобы задействовать, встроенный резистор, необходимо установить его в режим INPUT_PULLUP: */ const int button_pin = 2; boolean button; void setup() { pinMode(button_pin, INPUT_PULLUP); Serial.begin(9600); } void loop() { button = !digitalRead(button_pin); // инвертировать! Serial.print("Button: ");Serial.println(button); }
[ "farscince@gmail.com" ]
farscince@gmail.com
f3dad8db80828be1f10a17c59e645fd6d261ad1b
724c0ee36c0e6262f143d965f2e5f894a31cbb16
/c,c++/ImpPrograms/template1.cpp
7654d9f8669bcc667c13a11f6b41db5ca8d6dbb1
[]
no_license
amit-mittal/Programming-Questions-Practice
bf5fe47ba1b074960ad33eb2e525baaf99a85336
899995ff49cdf1ef77cc9327feb2fbed7b5c94fe
refs/heads/master
2021-09-04T15:27:52.569111
2018-01-19T21:03:31
2018-01-19T21:03:31
117,618,138
2
0
null
null
null
null
UTF-8
C++
false
false
1,963
cpp
#include <algorithm> #include <cmath> #include <cstdio> #include <deque> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <set> #include <stack> #include <stdlib.h> #include <string> #include <vector> using namespace std; #define LL long long #define LD long double #define VI vector<int> #define sd(x) x = GetNextInt() #define slld(x) scanf("%lld",&x) #define PB push_back #define MP make_pair #define F first #define S second #define PII pair<int,int> #define PPII pair< PI , PI > #define INF 2000000009 #if 0 #define get getchar_unlocked #else #define get getchar #endif int next_int; char in_char; inline int GetNextInt(){ in_char = ' '; while((in_char < '0') || (in_char > '9')){ in_char = get(); } next_int = 0; while((in_char >= '0') && (in_char <= '9')){ next_int *= 10; next_int += in_char - 48; in_char = get(); } return next_int; } LL PowerMod(LL base,LL power,LL mod){ LL ret = 1; if(base >= mod){ base %= mod; } while(power > 0){ if((power & 1) == 1){ ret *= base; if(ret >= mod){ ret %= mod; } } power >>= 1; base *= base; if(base >= mod){ base %= mod; } } return ret; } inline bool validchar(char ch){ if((ch >= 'a') && (ch <= 'z')){ return true; } if((ch >= 'A') && (ch <= 'Z')){ return true; } if((ch >= '0') && (ch <= '9')){ return true; } return false; } vector<string> GetStringsFromLine(){ vector<string> ret; char ch; string s; ch = ' '; while(true){ while(!validchar(ch)){ if(ch == '\n'){ return ret; } ch = get(); } s = ""; while(validchar(ch)){ s = s + ch; ch = get(); } ret.PB(s); } } /* Main Code */ #define MAXN 100111 #define MAXX 51 #define MOD 1000000007 int nop, prime[MAXN]; int sop[MAXN], dp[MAXN][MAXX]; bool isp[MAXN]; vector<int> pf[MAXN]; inline void takemod(int &x){ if(x >= MOD){ x -= MOD; } } int main(){ Pre(); int t; sd(t); while(t--){ Solve(); } return 0; }
[ "Administrator@Amit-Laptop.fareast.corp.microsoft.com" ]
Administrator@Amit-Laptop.fareast.corp.microsoft.com
2f126845ae7b6acaf39c13a6bc7a1c54a5af1e0a
bcc319655913ae55671ce3b4e213ef454b8b5f94
/include/ReplicationHelper.hpp
2c3b5d21bf69b334141ef6ffcc7e2e4235bdbc97
[]
no_license
camargodev/dropbox
d5b693c556ebc11041c8715bdf189df552e8c860
5447aaf44e15f870b526b5872323e1484e85a078
refs/heads/master
2020-05-07T16:10:11.009339
2019-06-27T02:00:44
2019-06-27T02:00:44
180,670,422
6
0
null
2019-06-25T16:13:10
2019-04-10T22:04:15
C++
UTF-8
C++
false
false
1,182
hpp
#ifndef REPLICATION_HELPER_HPP #define REPLICATION_HELPER_HPP #include "SocketWrapper.hpp" #include "AddressGetter.hpp" #include <semaphore.h> #include <time.h> using Clock = clock_t; struct Mirror { int socket; char ip[INET_ADDRSTRLEN]; int port; Mirror(int socket, char ip[INET6_ADDRSTRLEN], int port) { this->socket = socket; strcpy(this->ip, ip); this->port = port; } Mirror(char ip[INET6_ADDRSTRLEN], int port) { this->socket = -1; strcpy(this->ip, ip); this->port = port; } }; class ReplicationHelper { public: const static int LIVENESS_NOTIFICATION_DELAY = 1; const static int TIMEOUT_TO_START_ELECTION = 5; const static int PORT_TO_NEW_SERVER = 4020; ReplicationHelper(); bool isMainServer(); void setAsMainServer(); void setAsBackupServer(); void addMirror(Mirror mirro); vector<Mirror> getMirrors(); Clock lastSignalFromServer; void removeMirrorFromList(Mirror mirror); void addSocketToMirror(Mirror mirror, SocketDescriptor socket); private: vector<Mirror> mirrors; bool isTheMainServer; sem_t processing; }; #endif
[ "camargodev@gmail.com" ]
camargodev@gmail.com
7d428741f3b334ebf469e3f0fd73264a5d498c4f
1ae40287c5705f341886bbb5cc9e9e9cfba073f7
/Osmium/SDK/FN_FriendNotification_functions.cpp
04cfcbfceb76725f63332396de2ff9e9a28b086c
[]
no_license
NeoniteDev/Osmium
183094adee1e8fdb0d6cbf86be8f98c3e18ce7c0
aec854e60beca3c6804f18f21b6a0a0549e8fbf6
refs/heads/master
2023-07-05T16:40:30.662392
2023-06-28T23:17:42
2023-06-28T23:17:42
340,056,499
14
8
null
null
null
null
UTF-8
C++
false
false
2,346
cpp
// Fortnite (4.5-CL-4159770) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function FriendNotification.FriendNotification_C.ShowFriendInvites // (Public, BlueprintCallable, BlueprintEvent) void UFriendNotification_C::ShowFriendInvites() { static auto fn = UObject::FindObject<UFunction>("Function FriendNotification.FriendNotification_C.ShowFriendInvites"); UFriendNotification_C_ShowFriendInvites_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function FriendNotification.FriendNotification_C.ShowPartyInvites // (Public, BlueprintCallable, BlueprintEvent) void UFriendNotification_C::ShowPartyInvites() { static auto fn = UObject::FindObject<UFunction>("Function FriendNotification.FriendNotification_C.ShowPartyInvites"); UFriendNotification_C_ShowPartyInvites_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function FriendNotification.FriendNotification_C.TakeAction // (Event, Public, BlueprintCallable, BlueprintEvent) void UFriendNotification_C::TakeAction() { static auto fn = UObject::FindObject<UFunction>("Function FriendNotification.FriendNotification_C.TakeAction"); UFriendNotification_C_TakeAction_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function FriendNotification.FriendNotification_C.ExecuteUbergraph_FriendNotification // () // Parameters: // int EntryPoint (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) void UFriendNotification_C::ExecuteUbergraph_FriendNotification(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function FriendNotification.FriendNotification_C.ExecuteUbergraph_FriendNotification"); UFriendNotification_C_ExecuteUbergraph_FriendNotification_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "kareemolim@gmail.com" ]
kareemolim@gmail.com
56e8020b77ebcc326940eb8a8ce154d400ad8bd1
25eda15859d45817ac22c428bf4a7f23f600bf7d
/src/qt/gamefrag.cpp
2c1761bc95e301aa92981906017ad6b3d409e632
[ "MIT" ]
permissive
SamiAhmed7777/game-frag-coin
3f7605af94168e7fbb0af85c085c8e975a91e227
1b450d26713aff7ef027fee3954fb96c99764a29
refs/heads/master
2023-04-14T17:56:48.819371
2021-04-26T16:06:26
2021-04-26T16:06:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
24,145
cpp
// Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2020 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/gamefrag-config.h" #endif #include "qt/gamefrag/gamefraggui.h" #include "clientmodel.h" #include "guiconstants.h" #include "guiutil.h" #include "intro.h" #include "net.h" #include "networkstyle.h" #include "optionsmodel.h" #include "qt/gamefrag/splash.h" #include "qt/gamefrag/welcomecontentwidget.h" #include "utilitydialog.h" #include "winshutdownmonitor.h" #ifdef ENABLE_WALLET #include "paymentserver.h" #include "walletmodel.h" #endif #include "masternodeconfig.h" #include "fs.h" #include "init.h" #include "rpc/server.h" #include "guiinterface.h" #include "util.h" #include "warnings.h" #ifdef ENABLE_WALLET #include "wallet/wallet.h" #endif #include <stdint.h> #include <QApplication> #include <QDebug> #include <QLibraryInfo> #include <QLocale> #include <QMessageBox> #include <QProcess> #include <QSettings> #include <QThread> #include <QTimer> #include <QTranslator> #if defined(QT_STATICPLUGIN) #include <QtPlugin> #if defined(QT_QPA_PLATFORM_XCB) Q_IMPORT_PLUGIN(QXcbIntegrationPlugin); #elif defined(QT_QPA_PLATFORM_WINDOWS) Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin); #elif defined(QT_QPA_PLATFORM_COCOA) Q_IMPORT_PLUGIN(QCocoaIntegrationPlugin); #endif Q_IMPORT_PLUGIN(QSvgPlugin); Q_IMPORT_PLUGIN(QSvgIconPlugin); Q_IMPORT_PLUGIN(QGifPlugin); #endif // Declare meta types used for QMetaObject::invokeMethod Q_DECLARE_METATYPE(bool*) Q_DECLARE_METATYPE(CAmount) static void InitMessage(const std::string& message) { LogPrintf("init message: %s\n", message); } /* Translate string to current locale using Qt. */ static std::string Translate(const char* psz) { return QCoreApplication::translate("gamefrag-core", psz).toStdString(); } static QString GetLangTerritory(bool forceLangFromSetting = false) { QSettings settings; // Get desired locale (e.g. "de_DE") // 1) System default language QString lang_territory = QLocale::system().name(); // 2) Language from QSettings QString lang_territory_qsettings = settings.value("language", "").toString(); if (!lang_territory_qsettings.isEmpty()) lang_territory = lang_territory_qsettings; // 3) -lang command line argument lang_territory = QString::fromStdString(gArgs.GetArg("-lang", lang_territory.toStdString())); return (forceLangFromSetting) ? lang_territory_qsettings : lang_territory; } /** Set up translations */ static void initTranslations(QTranslator& qtTranslatorBase, QTranslator& qtTranslator, QTranslator& translatorBase, QTranslator& translator, bool forceLangFromSettings = false) { // Remove old translators QApplication::removeTranslator(&qtTranslatorBase); QApplication::removeTranslator(&qtTranslator); QApplication::removeTranslator(&translatorBase); QApplication::removeTranslator(&translator); // Get desired locale (e.g. "de_DE") // 1) System default language QString lang_territory = GetLangTerritory(forceLangFromSettings); // Convert to "de" only by truncating "_DE" QString lang = lang_territory; lang.truncate(lang_territory.lastIndexOf('_')); // Load language files for configured locale: // - First load the translator for the base language, without territory // - Then load the more specific locale translator // Load e.g. qt_de.qm if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) QApplication::installTranslator(&qtTranslatorBase); // Load e.g. qt_de_DE.qm if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) QApplication::installTranslator(&qtTranslator); // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in gamefrag.qrc) if (translatorBase.load(lang, ":/translations/")) QApplication::installTranslator(&translatorBase); // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in gamefrag.qrc) if (translator.load(lang_territory, ":/translations/")) QApplication::installTranslator(&translator); } /* qDebug() message handler --> debug.log */ void DebugMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString& msg) { Q_UNUSED(context); if (type == QtDebugMsg) { LogPrint(BCLog::QT, "GUI: %s\n", msg.toStdString()); } else { LogPrintf("GUI: %s\n", msg.toStdString()); } } /** Class encapsulating GAMEFRAG Core startup and shutdown. * Allows running startup and shutdown in a different thread from the UI thread. */ class BitcoinCore : public QObject { Q_OBJECT public: explicit BitcoinCore(); public Q_SLOTS: void initialize(); void shutdown(); void restart(QStringList args); Q_SIGNALS: void initializeResult(int retval); void shutdownResult(int retval); void runawayException(const QString& message); private: /// Flag indicating a restart bool execute_restart; /// Pass fatal exception message to UI thread void handleRunawayException(const std::exception* e); }; /** Main GAMEFRAG application object */ class BitcoinApplication : public QApplication { Q_OBJECT public: explicit BitcoinApplication(int& argc, char** argv); ~BitcoinApplication(); #ifdef ENABLE_WALLET /// Create payment server void createPaymentServer(); #endif /// parameter interaction/setup based on rules void parameterSetup(); /// Create options model void createOptionsModel(); /// Create main window void createWindow(const NetworkStyle* networkStyle); /// Create splash screen void createSplashScreen(const NetworkStyle* networkStyle); /// Create tutorial screen bool createTutorialScreen(); /// Request core initialization void requestInitialize(); /// Request core shutdown void requestShutdown(); /// Get process return value int getReturnValue() { return returnValue; } /// Get window identifier of QMainWindow (GAMEFRAGGUI) WId getMainWinId() const; public Q_SLOTS: void initializeResult(int retval); void shutdownResult(int retval); /// Handle runaway exceptions. Shows a message box with the problem and quits the program. void handleRunawayException(const QString& message); void updateTranslation(bool forceLangFromSettings = false); Q_SIGNALS: void requestedInitialize(); void requestedRestart(QStringList args); void requestedShutdown(); void stopThread(); void splashFinished(QWidget* window); private: QThread* coreThread; OptionsModel* optionsModel; ClientModel* clientModel; GAMEFRAGGUI* window; QTimer* pollShutdownTimer; #ifdef ENABLE_WALLET PaymentServer* paymentServer; WalletModel* walletModel; #endif int returnValue; QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; void startThread(); }; #include "gamefrag.moc" BitcoinCore::BitcoinCore() : QObject() { } void BitcoinCore::handleRunawayException(const std::exception* e) { PrintExceptionContinue(e, "Runaway exception"); Q_EMIT runawayException(QString::fromStdString(GetWarnings("gui"))); } void BitcoinCore::initialize() { execute_restart = true; try { qDebug() << __func__ << ": Running AppInit2 in thread"; int rv = AppInit2(); Q_EMIT initializeResult(rv); } catch (const std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } } void BitcoinCore::restart(QStringList args) { if (execute_restart) { // Only restart 1x, no matter how often a user clicks on a restart-button execute_restart = false; try { qDebug() << __func__ << ": Running Restart in thread"; Interrupt(); PrepareShutdown(); qDebug() << __func__ << ": Shutdown finished"; Q_EMIT shutdownResult(1); CExplicitNetCleanup::callCleanup(); QProcess::startDetached(QApplication::applicationFilePath(), args); qDebug() << __func__ << ": Restart initiated..."; QApplication::quit(); } catch (const std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } } } void BitcoinCore::shutdown() { try { qDebug() << __func__ << ": Running Shutdown in thread"; Interrupt(); Shutdown(); qDebug() << __func__ << ": Shutdown finished"; Q_EMIT shutdownResult(1); } catch (const std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } } BitcoinApplication::BitcoinApplication(int& argc, char** argv) : QApplication(argc, argv), coreThread(0), optionsModel(0), clientModel(0), window(0), pollShutdownTimer(0), #ifdef ENABLE_WALLET paymentServer(0), walletModel(0), #endif returnValue(0) { setQuitOnLastWindowClosed(false); } BitcoinApplication::~BitcoinApplication() { if (coreThread) { qDebug() << __func__ << ": Stopping thread"; Q_EMIT stopThread(); coreThread->wait(); qDebug() << __func__ << ": Stopped thread"; } delete window; window = 0; #ifdef ENABLE_WALLET delete paymentServer; paymentServer = 0; #endif // Delete Qt-settings if user clicked on "Reset Options" QSettings settings; if (optionsModel && optionsModel->resetSettings) { settings.clear(); settings.sync(); } delete optionsModel; optionsModel = 0; } #ifdef ENABLE_WALLET void BitcoinApplication::createPaymentServer() { paymentServer = new PaymentServer(this); } #endif void BitcoinApplication::createOptionsModel() { optionsModel = new OptionsModel(); } void BitcoinApplication::createWindow(const NetworkStyle* networkStyle) { window = new GAMEFRAGGUI(networkStyle, 0); pollShutdownTimer = new QTimer(window); connect(pollShutdownTimer, &QTimer::timeout, window, &GAMEFRAGGUI::detectShutdown); pollShutdownTimer->start(200); } void BitcoinApplication::createSplashScreen(const NetworkStyle* networkStyle) { Splash* splash = new Splash(networkStyle); // We don't hold a direct pointer to the splash screen after creation, so use // Qt::WA_DeleteOnClose to make sure that the window will be deleted eventually. splash->setAttribute(Qt::WA_DeleteOnClose); splash->show(); connect(this, &BitcoinApplication::splashFinished, splash, &Splash::slotFinish); connect(this, &BitcoinApplication::requestedShutdown, splash, &QWidget::close); } bool BitcoinApplication::createTutorialScreen() { WelcomeContentWidget* widget = new WelcomeContentWidget(); connect(widget, &WelcomeContentWidget::onLanguageSelected, [this](){ updateTranslation(true); }); widget->exec(); bool ret = widget->isOk; widget->deleteLater(); return ret; } void BitcoinApplication::updateTranslation(bool forceLangFromSettings){ // Re-initialize translations after change them initTranslations(this->qtTranslatorBase, this->qtTranslator, this->translatorBase, this->translator, forceLangFromSettings); } void BitcoinApplication::startThread() { if (coreThread) return; coreThread = new QThread(this); BitcoinCore* executor = new BitcoinCore(); executor->moveToThread(coreThread); /* communication to and from thread */ connect(executor, &BitcoinCore::initializeResult, this, &BitcoinApplication::initializeResult); connect(executor, &BitcoinCore::shutdownResult, this, &BitcoinApplication::shutdownResult); connect(executor, &BitcoinCore::runawayException, this, &BitcoinApplication::handleRunawayException); connect(this, &BitcoinApplication::requestedInitialize, executor, &BitcoinCore::initialize); connect(this, &BitcoinApplication::requestedShutdown, executor, &BitcoinCore::shutdown); connect(window, &GAMEFRAGGUI::requestedRestart, executor, &BitcoinCore::restart); /* make sure executor object is deleted in its own thread */ connect(this, &BitcoinApplication::stopThread, executor, &QObject::deleteLater); connect(this, &BitcoinApplication::stopThread, coreThread, &QThread::quit); coreThread->start(); } void BitcoinApplication::parameterSetup() { // Default printtoconsole to false for the GUI. GUI programs should not // print to the console unnecessarily. gArgs.SoftSetBoolArg("-printtoconsole", false); InitLogging(); InitParameterInteraction(); } void BitcoinApplication::requestInitialize() { qDebug() << __func__ << ": Requesting initialize"; startThread(); Q_EMIT requestedInitialize(); } void BitcoinApplication::requestShutdown() { qDebug() << __func__ << ": Requesting shutdown"; startThread(); window->hide(); window->setClientModel(0); pollShutdownTimer->stop(); #ifdef ENABLE_WALLET window->removeAllWallets(); delete walletModel; walletModel = 0; #endif delete clientModel; clientModel = 0; // Show a simple window indicating shutdown status ShutdownWindow::showShutdownWindow(window); // Request shutdown from core thread Q_EMIT requestedShutdown(); } void BitcoinApplication::initializeResult(int retval) { qDebug() << __func__ << ": Initialization result: " << retval; // Set exit result: 0 if successful, 1 if failure returnValue = retval ? 0 : 1; if (retval) { #ifdef ENABLE_WALLET PaymentServer::LoadRootCAs(); paymentServer->setOptionsModel(optionsModel); #endif clientModel = new ClientModel(optionsModel); window->setClientModel(clientModel); #ifdef ENABLE_WALLET if (pwalletMain) { walletModel = new WalletModel(pwalletMain, optionsModel); window->addWallet(GAMEFRAGGUI::DEFAULT_WALLET, walletModel); window->setCurrentWallet(GAMEFRAGGUI::DEFAULT_WALLET); connect(walletModel, &WalletModel::coinsSent, paymentServer, &PaymentServer::fetchPaymentACK); } #endif // If -min option passed, start window minimized. if (gArgs.GetBoolArg("-min", false)) { window->showMinimized(); } else { window->show(); } Q_EMIT splashFinished(window); #ifdef ENABLE_WALLET // Now that initialization/startup is done, process any command-line // GAMEFRAG: URIs or payment requests: //connect(paymentServer, &PaymentServer::receivedPaymentRequest, window, &GAMEFRAGGUI::handlePaymentRequest); connect(window, &GAMEFRAGGUI::receivedURI, paymentServer, &PaymentServer::handleURIOrFile); connect(paymentServer, &PaymentServer::message, [this](const QString& title, const QString& message, unsigned int style) { window->message(title, message, style); }); QTimer::singleShot(100, paymentServer, &PaymentServer::uiReady); #endif } else { quit(); // Exit main loop } } void BitcoinApplication::shutdownResult(int retval) { qDebug() << __func__ << ": Shutdown result: " << retval; quit(); // Exit main loop after shutdown finished } void BitcoinApplication::handleRunawayException(const QString& message) { QMessageBox::critical(0, "Runaway exception", QObject::tr("A fatal error occurred. GAMEFRAG can no longer continue safely and will quit.") + QString("\n\n") + message); ::exit(1); } WId BitcoinApplication::getMainWinId() const { if (!window) return 0; return window->winId(); } #ifndef BITCOIN_QT_TEST int main(int argc, char* argv[]) { SetupEnvironment(); /// 1. Parse command-line options. These take precedence over anything else. // Command-line options take precedence: gArgs.ParseParameters(argc, argv); // Do not refer to data directory yet, this can be overridden by Intro::pickDataDirectory /// 2. Basic Qt initialization (not dependent on parameters or configuration) Q_INIT_RESOURCE(gamefrag_locale); Q_INIT_RESOURCE(gamefrag); // Generate high-dpi pixmaps QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); #if QT_VERSION >= 0x050600 QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling); #endif #ifdef Q_OS_MAC QApplication::setAttribute(Qt::AA_DontShowIconsInMenus); #endif BitcoinApplication app(argc, argv); // Register meta types used for QMetaObject::invokeMethod qRegisterMetaType<bool*>(); // Need to pass name here as CAmount is a typedef (see http://qt-project.org/doc/qt-5/qmetatype.html#qRegisterMetaType) // IMPORTANT if it is no longer a typedef use the normal variant above qRegisterMetaType<CAmount>("CAmount"); /// 3. Application identification // must be set before OptionsModel is initialized or translations are loaded, // as it is used to locate QSettings QApplication::setOrganizationName(QAPP_ORG_NAME); QApplication::setOrganizationDomain(QAPP_ORG_DOMAIN); QApplication::setApplicationName(QAPP_APP_NAME_DEFAULT); GUIUtil::SubstituteFonts(GetLangTerritory()); /// 4. Initialization of translations, so that intro dialog is in user's language // Now that QSettings are accessible, initialize translations //initTranslations(qtTranslatorBase, qtTranslator, translatorBase, translator); app.updateTranslation(); translationInterface.Translate.connect(Translate); // Show help message immediately after parsing command-line options (for "-lang") and setting locale, // but before showing splash screen. if (gArgs.IsArgSet("-?") || gArgs.IsArgSet("-h") || gArgs.IsArgSet("-help") || gArgs.IsArgSet("-version")) { HelpMessageDialog help(nullptr, gArgs.IsArgSet("-version")); help.showOrPrint(); return 1; } /// 5. Now that settings and translations are available, ask user for data directory // User language is set up: pick a data directory if (!Intro::pickDataDirectory()) return 0; /// 6. Determine availability of data directory and parse gamefrag.conf /// - Do not call GetDataDir(true) before this step finishes if (!fs::is_directory(GetDataDir(false))) { QMessageBox::critical(0, QObject::tr("GAMEFRAG Core"), QObject::tr("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(gArgs.GetArg("-datadir", "")))); return 1; } try { gArgs.ReadConfigFile(); } catch (const std::exception& e) { QMessageBox::critical(0, QObject::tr("GAMEFRAG Core"), QObject::tr("Error: Cannot parse configuration file: %1. Only use key=value syntax.").arg(e.what())); return 0; } /// 7. Determine network (and switch to network specific options) // - Do not call Params() before this step // - Do this after parsing the configuration file, as the network can be switched there // - QSettings() will use the new application name after this, resulting in network-specific settings // - Needs to be done before createOptionsModel // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) if (!SelectParamsFromCommandLine()) { QMessageBox::critical(0, QObject::tr("GAMEFRAG Core"), QObject::tr("Error: Invalid combination of -regtest and -testnet.")); return 1; } #ifdef ENABLE_WALLET // Parse URIs on command line -- this can affect Params() PaymentServer::ipcParseCommandLine(argc, argv); #endif QScopedPointer<const NetworkStyle> networkStyle(NetworkStyle::instantiate(QString::fromStdString(Params().NetworkIDString()))); assert(!networkStyle.isNull()); // Allow for separate UI settings for testnets QApplication::setApplicationName(networkStyle->getAppName()); // Re-initialize translations after changing application name (language in network-specific settings can be different) app.updateTranslation(); #ifdef ENABLE_WALLET /// 7a. parse masternode.conf std::string strErr; if (!masternodeConfig.read(strErr)) { QMessageBox::critical(0, QObject::tr("GAMEFRAG Core"), QObject::tr("Error reading masternode configuration file: %1").arg(strErr.c_str())); return 0; } /// 8. URI IPC sending // - Do this early as we don't want to bother initializing if we are just calling IPC // - Do this *after* setting up the data directory, as the data directory hash is used in the name // of the server. // - Do this after creating app and setting up translations, so errors are // translated properly. if (PaymentServer::ipcSendCommandLine()) exit(0); // Start up the payment server early, too, so impatient users that click on // gamefrag: links repeatedly have their payment requests routed to this process: app.createPaymentServer(); #endif /// 9. Main GUI initialization // Install global event filter that makes sure that long tooltips can be word-wrapped app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app)); #if defined(Q_OS_WIN) // Install global event filter for processing Windows session related Windows messages (WM_QUERYENDSESSION and WM_ENDSESSION) qApp->installNativeEventFilter(new WinShutdownMonitor()); #endif // Install qDebug() message handler to route to debug.log qInstallMessageHandler(DebugMessageHandler); // Allow parameter interaction before we create the options model app.parameterSetup(); // Load GUI settings from QSettings app.createOptionsModel(); // Subscribe to global signals from core uiInterface.InitMessage.connect(InitMessage); bool ret = true; #ifdef ENABLE_WALLET // Check if the wallet exists or need to be created std::string strWalletFile = gArgs.GetArg("-wallet", DEFAULT_WALLET_DAT); std::string strDataDir = GetDataDir().string(); // Wallet file must be a plain filename without a directory fs::path wallet_file_path(strWalletFile); if (strWalletFile != wallet_file_path.filename().string()) { throw std::runtime_error(strprintf(_("Wallet %s resides outside data directory %s"), strWalletFile, strDataDir)); } fs::path pathBootstrap = GetDataDir() / strWalletFile; if (!fs::exists(pathBootstrap)) { // wallet doesn't exist, popup tutorial screen. ret = app.createTutorialScreen(); } #endif if(!ret){ // wallet not loaded. return 0; } if (gArgs.GetBoolArg("-splash", true) && !gArgs.GetBoolArg("-min", false)) app.createSplashScreen(networkStyle.data()); try { app.createWindow(networkStyle.data()); app.requestInitialize(); #if defined(Q_OS_WIN) WinShutdownMonitor::registerShutdownBlockReason(QObject::tr("GAMEFRAG Core didn't yet exit safely..."), (HWND)app.getMainWinId()); #endif app.exec(); app.requestShutdown(); app.exec(); } catch (const std::exception& e) { PrintExceptionContinue(&e, "Runaway exception"); app.handleRunawayException(QString::fromStdString(GetWarnings("gui"))); } catch (...) { PrintExceptionContinue(NULL, "Runaway exception"); app.handleRunawayException(QString::fromStdString(GetWarnings("gui"))); } return app.getReturnValue(); } #endif // BITCOIN_QT_TEST
[ "development@SpectreSecurity.io" ]
development@SpectreSecurity.io
2a2368b92f1b6669596c3ba1db724f433ad361ad
b54882cf89639ad5a6d289fb478e90e95311ad39
/kthSmallestElement.cpp
f70fe816511d78ff9a29cdced952fa6bfaa8ad6d
[]
no_license
kk77777/geeksForGeeksSolutions
16111f7c39686db17e06e4213ab68159437900d0
4b51dd9699550b55b68766c6e22ff5cb9b205a7c
refs/heads/master
2021-08-07T09:36:49.380647
2021-08-01T08:37:08
2021-08-01T08:37:08
249,911,067
0
0
null
null
null
null
UTF-8
C++
false
false
654
cpp
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tc; cin >> tc; while (tc--) { int n; cin >> n; vector<int> a; for (int i = 0; i < n; i++) { int x; cin >> x; a.push_back(x); } int k; cin >> k; // priority_queue<int>mh; // for(int i=0;i<n;i++){ // mh.push(a[i]); // if(mh.size()>k){ // mh.pop(); // } // } sort(a.begin(), a.end()); cout << a[k - 1] << "\n"; } }
[ "kaushikgattani@gmail.com" ]
kaushikgattani@gmail.com
e47f1f64e8fccadd4d4d3173f411f24fd8d766cb
d493276f3a09b6f161b9d3a79d5df55f48a0557c
/2019_KAKAO_동계인턴십_No1.cpp
5509548c01de6d69e38486cbddb30ea60c978e13
[]
no_license
AnneMayor/algorithmstudy
31e034e9e7c8ffab0601f58b9ec29bea62aacf24
944870759ff43d0c275b28f0dcf54f5dd4b8f4b1
refs/heads/master
2023-04-26T21:25:21.679777
2023-04-15T09:08:02
2023-04-15T09:08:02
182,223,870
0
0
null
2021-06-20T06:49:02
2019-04-19T07:42:00
C++
UTF-8
C++
false
false
1,325
cpp
#include <iostream> #include <string> #include <vector> #include <stack> using namespace std; stack<int> basket; int solution(vector<vector<int>> board, vector<int> moves) { int answer = 0; vector<vector<int>> dollMap; int bSize = board.size(); dollMap.resize(bSize); for (int i = 0; i < bSize; i++) { for (int j = bSize-1; j >= 0; j--) { if (board[j][i] > 0) dollMap[i].push_back(board[j][i]); } } // for(int i = 0 ; i < bSize; i++) { // for(int j = 0; j < dollMap[i].size(); j++) { // cout << dollMap[i][j] << " "; // } // cout << endl; // } int numOfMoves = moves.size(); for (int i = 0; i < numOfMoves; i++) { if (dollMap[moves[i] - 1].size() > 0) { if (!basket.empty()) { if (basket.top() == dollMap[moves[i] - 1].back()) { answer += 2; basket.pop(); } else { basket.push(dollMap[moves[i] - 1].back()); } } else basket.push(dollMap[moves[i] - 1].back()); dollMap[moves[i] - 1].pop_back(); } } return answer; }
[ "melllamodahye@gmail.com" ]
melllamodahye@gmail.com
50c04dca023297cc4c8e80b8f601de9da4896f8e
bd1fea86d862456a2ec9f56d57f8948456d55ee6
/000/233/108/CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int_memcpy_81_bad.cpp
88d652aaed8f7aa83b0d93a61fa7074554e96f2e
[]
no_license
CU-0xff/juliet-cpp
d62b8485104d8a9160f29213368324c946f38274
d8586a217bc94cbcfeeec5d39b12d02e9c6045a2
refs/heads/master
2021-03-07T15:44:19.446957
2020-03-10T12:45:40
2020-03-10T12:45:40
246,275,244
0
1
null
null
null
null
UTF-8
C++
false
false
1,167
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int_memcpy_81_bad.cpp Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE805.label.xml Template File: sources-sink-81_bad.tmpl.cpp */ /* * @description * CWE: 122 Heap Based Buffer Overflow * BadSource: Allocate using malloc() and set data pointer to a small buffer * GoodSource: Allocate using malloc() and set data pointer to a large buffer * Sinks: memcpy * BadSink : Copy int array to data using memcpy * Flow Variant: 81 Data flow: data passed in a parameter to an virtual method called via a reference * * */ #ifndef OMITBAD #include "std_testcase.h" #include "CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int_memcpy_81.h" namespace CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int_memcpy_81 { void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int_memcpy_81_bad::action(int * data) const { { int source[100] = {0}; /* fill with 0's */ /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ memcpy(data, source, 100*sizeof(int)); printIntLine(data[0]); free(data); } } } #endif /* OMITBAD */
[ "frank@fischer.com.mt" ]
frank@fischer.com.mt
b50a9906c469a3c32dc13b81d0e6ab69fe2a75b5
52e430d46f0edbf72553b4ff513e8fcbdcb1c385
/Algorithms_on_Graphs/Week_2/3.2.1.cpp
3cbe5f34d1323800bc8b958105fc36025488567b
[]
no_license
ivk22/Data_Structures_and_Algorithm
5ffd040a26764428bf26cefd88219032d0dbdb93
8e6cceba2a9806b31dee54c89986f15b430c1639
refs/heads/master
2021-07-11T21:23:00.875599
2020-08-19T06:30:51
2020-08-19T06:30:51
191,723,271
0
0
null
null
null
null
UTF-8
C++
false
false
2,736
cpp
// 3.2.1.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> #include <string> #include <queue> #include <ostream> #include <sstream> #include <iterator> #include <cmath> #include <list> #include <algorithm> #include <vector> #include <random> using namespace std; void Explore(size_t v, bool*& visited, list<size_t>*& arr, size_t& post_order, size_t*& post_orders) { visited[v] = 1; for (const auto & val : arr[v]) { if (visited[val] == 0) { Explore(val, visited, arr, post_order, post_orders); } } ++post_order; post_orders[post_order] = v; } void Explore_cnt(size_t v, bool*& visited, list<size_t>*& arr, size_t& post_order) { visited[v] = 1; for (const auto & val : arr[v]) { if (visited[val] == 0) { Explore_cnt(val, visited, arr, post_order); } } ++post_order; } void DFS(size_t n, list<size_t>*& arr, size_t*& post_orders) { bool * visited = new bool[n + 1]; for (size_t i = 1; i <= n; ++i) { visited[i] = 0; post_orders[i] = 0; } size_t post_order = 0; for (size_t i = 1; i <= n; ++i) { if (visited[i] == 0) { Explore(i, visited, arr, post_order, post_orders); } } } bool SCC(size_t n, list<size_t>*& G, list<size_t>*& GR) { size_t* post_orders = new size_t[n + 1]; DFS(n, GR, post_orders); bool * visited = new bool[n + 1]; for (size_t i = 1; i <= n; ++i) { visited[i] = 0; } for (size_t i = n; i >= 1; --i) { if (visited[post_orders[i]] == 0) { size_t post_order = 0; Explore_cnt(post_orders[i], visited, G, post_order); if (post_order > 1) { return 1; } } } return 0; } int main() { size_t n = 0, m = 0; cin >> n >> m; list<size_t>* G = new list<size_t>[n + 1]; list<size_t>* GR = new list<size_t>[n + 1]; bool* visited = new bool[n + 1]; size_t v1 = 0, v2 = 0; for (size_t i = 0; i < m; ++i) { cin >> v1 >> v2; G[v1].push_back(v2); GR[v2].push_back(v1); } cout << SCC(n,G,GR); } // Run program: Ctrl + F5 or Debug > Start Without Debugging menu // Debug program: F5 or Debug > Start Debugging menu // Tips for Getting Started: // 1. Use the Solution Explorer window to add/manage files // 2. Use the Team Explorer window to connect to source control // 3. Use the Output window to see build output and other messages // 4. Use the Error List window to view errors // 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project // 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
[ "noreply@github.com" ]
noreply@github.com
174ba667124ada1372bfcd3f93386b8164a4e1a0
4adc9e3824783e11b76774d44e1f589ad3793f6c
/examples/MapperEx/MapperEx-generated-cpp/cpp-federates/MapperEx-rti-cpp/src/main/c++/Bonjour.cpp
8f496d72fdf29678dd57a757960f22c2b19fedac
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
usnistgov/ucef-cpp
95b6db1e8c887fd74e2b9082a102973f04caac83
ab4cb27096d1c5bd2af671cccdb990a79d347057
refs/heads/develop
2021-09-24T14:52:03.455891
2020-09-02T13:38:49
2020-09-02T13:38:49
97,056,858
1
0
null
2018-09-13T19:09:17
2017-07-12T22:24:57
C++
UTF-8
C++
false
false
6,262
cpp
// This code has been generated by the C2W code generator. // Do not edit manually! #include "Bonjour.hpp" void Bonjour::init( RTI::RTIambassador *rti ) { static bool isInitialized = false; if ( isInitialized ) { return; } isInitialized = true; C2WInteractionRoot::init( rti ); bool isNotInitialized = true; while( isNotInitialized ) { try { getHandle() = rti->getInteractionClassHandle( "InteractionRoot.C2WInteractionRoot.Bonjour" ); isNotInitialized = false; } catch ( RTI::FederateNotExecutionMember & ) { std::cerr << getInitErrorMessage() << "Federate Not Execution Member" << std::endl; return; } catch ( RTI::NameNotFound & ) { std::cerr << getInitErrorMessage() << "Name Not Found" << std::endl; return; } catch ( ... ) { std::cerr << getInitErrorMessage() << "Exception caught ... retry" << std::endl; } } getClassNameHandleMap().insert( std::make_pair( "Bonjour", get_handle() ) ); getClassHandleNameMap().insert( std::make_pair( get_handle(), "Bonjour" ) ); isNotInitialized = true; while( isNotInitialized ) { try { isNotInitialized = false; } catch ( RTI::FederateNotExecutionMember & ) { std::cerr << getInitErrorMessage() << "Federate Not Execution Member" << std::endl; return; } catch ( RTI::InteractionClassNotDefined & ) { std::cerr << getInitErrorMessage() << "Interaction Class Not Defined" << std::endl; return; } catch ( RTI::NameNotFound & ) { std::cerr << getInitErrorMessage() << "Name Not Found" << std::endl; return; } catch ( ... ) { std::cerr << getInitErrorMessage() << "Exception caught ... retry" << std::endl; } } } void Bonjour::publish( RTI::RTIambassador *rti ) { if ( getIsPublished() ) { return; } init( rti ); bool isNotPublished = true; while( isNotPublished ) { try { rti->publishInteractionClass( get_handle() ); isNotPublished = false; } catch ( RTI::FederateNotExecutionMember & ) { std::cerr << getPublishErrorMessage() << "Federate Not Execution Member" << std::endl; return; } catch ( RTI::InteractionClassNotDefined & ) { std::cerr << getPublishErrorMessage() << "Interaction Class Not Defined" << std::endl; return; } catch ( ... ) { std::cerr << getPublishErrorMessage() << "Exception caught ... retry" << std::endl; } } getIsPublished() = true; } void Bonjour::unpublish( RTI::RTIambassador *rti ) { if ( !getIsPublished() ) { return; } init( rti ); bool isNotUnpublished = true; while( isNotUnpublished ) { try { rti->unpublishInteractionClass( get_handle() ); isNotUnpublished = false; } catch ( RTI::FederateNotExecutionMember & ) { std::cerr << getUnpublishErrorMessage() + "Federate Not Execution Member" << std::endl; return; } catch ( RTI::InteractionClassNotDefined & ) { std::cerr << getUnpublishErrorMessage() + "Interaction Class Not Defined" << std::endl; return; } catch ( RTI::InteractionClassNotPublished & ) { std::cerr << getUnpublishErrorMessage() + "Interaction Class Not Published" << std::endl; return; } catch ( ... ) { std::cerr << getUnpublishErrorMessage() << "Exception caught ... retry" << std::endl; } } getIsPublished() = false; } void Bonjour::subscribe( RTI::RTIambassador *rti ) { if ( getIsSubscribed() ) { return; } init( rti ); bool isNotSubscribed = true; while( isNotSubscribed ) { try { rti->subscribeInteractionClass( get_handle() ); isNotSubscribed = false; } catch ( RTI::FederateNotExecutionMember & ) { std::cerr << getSubscribeErrorMessage() << "Federate Not Execution Member" << std::endl; return; } catch ( RTI::InteractionClassNotDefined & ) { std::cerr << getSubscribeErrorMessage() << "Interaction Class Not Defined" << std::endl; return; } catch ( ... ) { std::cerr << getSubscribeErrorMessage() << "Exception caught ... retry" << std::endl; } } getIsSubscribed() = true; } void Bonjour::unsubscribe( RTI::RTIambassador *rti ) { if ( !getIsSubscribed() ) { return; } init( rti ); bool isNotUnsubscribed = true; while( isNotUnsubscribed ) { try { rti->unsubscribeInteractionClass( get_handle() ); isNotUnsubscribed = false; } catch ( RTI::FederateNotExecutionMember & ) { std::cerr << getUnsubscribeErrorMessage() << "Federate Not Execution Member" << std::endl; return; } catch ( RTI::InteractionClassNotDefined & ) { std::cerr << getUnsubscribeErrorMessage() << "Interaction Class Not Defined" << std::endl; return; } catch ( RTI::InteractionClassNotSubscribed & ) { std::cerr << getUnsubscribeErrorMessage() << "Interaction Class Not Subscribed" << std::endl; return; } catch ( ... ) { std::cerr << getUnsubscribeErrorMessage() << "Exception caught ... retry" << std::endl; } } getIsSubscribed() = false; } bool Bonjour::static_init( void ) { static bool isInitialized = false; if ( isInitialized ) { return true; } isInitialized = true; getClassNameSet().insert( "Bonjour" ); getClassNameFactoryMap().insert( std::make_pair( "Bonjour", &Bonjour::factory ) ); getClassNamePublishMap().insert( std::make_pair( "Bonjour", (PubsubFunctionPtr)( &Bonjour::publish ) ) ); getClassNameUnpublishMap().insert( std::make_pair( "Bonjour", (PubsubFunctionPtr)( &Bonjour::unpublish ) ) ); getClassNameSubscribeMap().insert( std::make_pair( "Bonjour", (PubsubFunctionPtr)( &Bonjour::subscribe ) ) ); getClassNameUnsubscribeMap().insert( std::make_pair( "Bonjour", (PubsubFunctionPtr)( &Bonjour::unsubscribe ) ) ); getDatamemberClassNameVectorPtrMap().insert( std::make_pair( "Bonjour", &getDatamemberNames() ) ); getAllDatamemberClassNameVectorPtrMap().insert( std::make_pair( "Bonjour", &getAllDatamemberNames() ) ); return true; } std::ostream &operator<<( std::ostream &os, Bonjour::SP entitySP ) { return os << *entitySP; } std::ostream &operator<<( std::ostream &os, const Bonjour &entity ) { return os << "Bonjour(" << "sourceFed:" << entity.get_sourceFed() << ", " << "originFed:" << entity.get_originFed() << ", " << "federateFilter:" << entity.get_federateFilter() << ", " << "actualLogicalGenerationTime:" << entity.get_actualLogicalGenerationTime() << ")"; }
[ "ydbarve@isis.vanderbilt.edu" ]
ydbarve@isis.vanderbilt.edu
9351e60c8d702c5311b0c73072de3f4a8e7c7166
7a658c306de15be6ab59e1c5a7f81f10c540f2d2
/tests/integration/src/IntegTestRunner.cpp
419585b1dcad2f9475f444a6fa2f642e274c2edb
[ "Apache-2.0", "OpenSSL", "BSD-3-Clause", "MIT", "LicenseRef-scancode-openssl", "LicenseRef-scancode-ssleay-windows", "JSON", "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
pfried/aws-iot-device-sdk-cpp
a8c21409f585efcedb847e0cef7993ba762c3299
3b544dcba048897a8a9b2e3b29243d8035caa28c
refs/heads/master
2020-05-23T10:17:21.040830
2016-11-15T11:21:19
2016-11-15T11:21:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,959
cpp
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ /** * @file IntegTestRunner.cpp * @brief * */ #include "util/memory/stl/String.hpp" #include "util/logging/Logging.hpp" #include "util/logging/LogMacros.hpp" #include "util/logging/ConsoleLogSystem.hpp" #include "ConfigCommon.hpp" #include "IntegTestRunner.hpp" #include "SdkTestConfig.hpp" #include "PubSub.hpp" #include "AutoReconnect.hpp" #include "MultipleClients.hpp" #define INTEG_TEST_RUNNER_LOG_TAG "[Integration Test Runner]" namespace awsiotsdk { namespace tests { namespace integration { ResponseCode IntegTestRunner::Initialize() { ResponseCode rc = awsiotsdk::ConfigCommon::InitializeCommon("config/IntegrationTestConfig.json"); if(ResponseCode::SUCCESS != rc) { AWS_LOG_INFO(INTEG_TEST_RUNNER_LOG_TAG, "Initialize Test Config Failed with rc : %d", static_cast<int>(rc)); } return rc; } ResponseCode IntegTestRunner::RunAllTests() { ResponseCode rc = ResponseCode::SUCCESS; // Each test runs in its own scope to ensure complete cleanup /** * Run Subscribe Publish Tests */ { PubSub pub_sub_runner; rc = pub_sub_runner.RunTest(); if(ResponseCode::SUCCESS != rc) { return rc; } } /** * Run Autoreconnect test */ { AutoReconnect auto_reconnect_runner; rc = auto_reconnect_runner.RunTest(); if(ResponseCode::SUCCESS != rc) { return rc; } } /** * Run Multiple Clients test */ { MultipleClients multiple_client_runner; rc = multiple_client_runner.RunTest(); if(ResponseCode::SUCCESS != rc) { return rc; } } return rc; } } } } int main(int argc, char **argv) { std::shared_ptr<awsiotsdk::util::Logging::ConsoleLogSystem> p_log_system = std::make_shared<awsiotsdk::util::Logging::ConsoleLogSystem>(awsiotsdk::util::Logging::LogLevel::Info); awsiotsdk::util::Logging::InitializeAWSLogging(p_log_system); std::unique_ptr<awsiotsdk::tests::integration::IntegTestRunner> test_runner = std::unique_ptr<awsiotsdk::tests::integration::IntegTestRunner>(new awsiotsdk::tests::integration::IntegTestRunner()); awsiotsdk::ResponseCode rc = test_runner->Initialize(); if(awsiotsdk::ResponseCode::SUCCESS == rc) { rc = test_runner->RunAllTests(); } #ifdef WIN32 getchar(); #endif awsiotsdk::util::Logging::ShutdownAWSLogging(); return static_cast<int>(rc); }
[ "chaurah@amazon.com" ]
chaurah@amazon.com
a065d0acd861fc9f6e221262d36fd4129de177a3
4031f371704271d49c7d40c333387bc122ff90fc
/cpp/recept/zn_migration_queue.cpp
4e29a2b21d1e33f752610cae9b42268544f2c826
[]
no_license
elbertHome/myStudy
b6aca939e463785ac612cdf40919a4daff2c1092
0abbd82d8d0805c871016ce03b4429c92d947937
refs/heads/master
2020-04-12T09:01:58.018489
2017-01-14T14:19:34
2017-01-14T14:19:34
47,024,582
0
0
null
null
null
null
UTF-8
C++
false
false
4,959
cpp
#include <string> #include <sstream> #include "zn_migration_queue.hpp" #include "zn_misc.hpp" #include "zn_exception.hpp" #include "zn_retriable.hpp" #include "zn_logger.hpp" #include "zn_config_manager.hpp" bool zn_migration_queue::init() { _conn.set_option(new mysqlpp::MultiStatementsOption(true)); _conn.set_option(new mysqlpp::ConnectTimeoutOption(_timeout)); _conn.set_option(new mysqlpp::ReadTimeoutOption(_timeout)); _conn.set_option(new mysqlpp::WriteTimeoutOption(_timeout)); _conn.set_option(new mysqlpp::InteractiveOption(true)); _conn.connect(_db_name.c_str(), _mysql_server.c_str(), _mysql_user.c_str(), _mysql_password.c_str(), _mysql_port); _conn.select_db(_db_name); return true; } bool zn_migration_queue::_excute_sql(const std::string &sql) { mysqlpp::Query query = _conn.query(); query << sql; return query.exec(); } zn_migration_row zn_migration_queue::_excute_get_one_row(const std::string &sql) { mysqlpp::Query query = _conn.query(); query << sql; mysqlpp::StoreQueryResult res = query.store(); if (res) { if (res.num_rows() > 1) { ZN_THROW(zn_migration_queue_exception, "More than one row found.", sql); } else if (res.num_rows() == 0) { ZN_THROW(zn_migration_queue_exception, "No data found.", sql); } } zn_migration_row ret; mysqlpp::Row row = res[0]; row["LOGIN_ID"].to_string(ret.login_id); row["ZIMBRA_ID"].to_string(ret.zimbra_id); ret.node_id = row["NODE_ID"]; row["EAS_HOST"].to_string(ret.eas_host); ret.proc_status = row["PROC_STATUS"]; ret.imap_status = row["IMAP_STATUS"]; ret.imap_retry_count = row["IMAP_RETRY_COUNT"]; ret.imap_skip_count = row["IMAP_SKIP_COUNT"]; ret.restart_count = row["RESTART_COUNT"]; row["INSERT_TIME"].to_string(ret.insert_time); row["UPDATE_TIME"].to_string(ret.update_time); return ret; } // function only for test purpose bool zn_migration_queue::insert_migration_information(const std::string &login_id, unsigned int node_id, std::string eas_host, unsigned int proc_status) { std::ostringstream oss; oss << "INSERT INTO " << _table_name; oss << " (LOGIN_ID, NODE_ID, EAS_HOST, PROC_STATUS, INSERT_TIME)"; oss << " VALUES (" << "\"" << login_id << "\", " << node_id << ", " << "\"" << eas_host << "\", " << zn_migration_queue::NOT_PROCESS << ", " << "now())"; return _excute_sql(oss.str()); } zn_migration_row zn_migration_queue::get_migration_information(const std::string &login_id, bool recovery_flag) { std::ostringstream oss; oss << "SELECT * FROM " << _table_name; oss << " WHERE LOGIN_ID = \"" << login_id << "\""; if (!recovery_flag) { oss << " AND PROC_STATUS <> " << zn_migration_queue::MIGRATION_BREAKOUT; } return _excute_get_one_row(oss.str()); } bool zn_migration_queue::update_zimbra_id(const std::string &login_id, const std::string &zimbra_id) { std::ostringstream oss; oss << "UPDATE " << _table_name; oss << " SET ZIMBRA_ID = \"" << zimbra_id << "\""; oss << " WHERE LOGIN_ID = \"" << login_id << "\""; return _excute_sql(oss.str()); } bool zn_migration_queue::update_imap_status(const std::string &login_id, unsigned int imap_status) { std::ostringstream oss; oss << "UPDATE " << _table_name; oss << " SET IMAP_STATUS = \"" << imap_status << "\""; oss << " WHERE LOGIN_ID = \"" << login_id << "\""; return _excute_sql(oss.str()); } bool zn_migration_queue::update_proc_status(const std::string &login_id, unsigned int proc_status) { std::ostringstream oss; oss << "UPDATE " << _table_name; oss << " SET PROC_STATUS = \"" << proc_status << "\""; oss << " WHERE LOGIN_ID = \"" << login_id << "\""; return _excute_sql(oss.str()); } bool zn_migration_queue::_increment_count(const std::string &column_name, const std::string &login_id) { std::ostringstream oss; oss << "UPDATE " << _table_name; oss << " SET IMAP_RETRY_COUNT = " << column_name << " + 1"; oss << " WHERE LOGIN_ID = \"" << login_id << "\""; return _excute_sql(oss.str()); } bool zn_migration_queue::increment_retry_count(const std::string &login_id) { return _increment_count("IMAP_RETRY_COUNT", login_id); } bool zn_migration_queue::increment_skip_count(const std::string &login_id) { return _increment_count("IMAP_SKIP_COUNT", login_id); } bool zn_migration_queue::increment_restart_count(const std::string &login_id) { return _increment_count("RESTART_COUNT", login_id); } bool zn_migration_queue::delete_data(const std::string &login_id) { std::ostringstream oss; oss << "DELETE FROM " << _table_name; oss << " WHERE LOGIN_ID = \"" << login_id << "\""; return _excute_sql(oss.str()); } unsigned int zn_migration_queue::get_record_count(const std::string &condition) { unsigned int count = 0; mysqlpp::Query query = _conn.query(); query << "SELECT COUNT(*) FROM " << _table_name; if (condition.size() > 0) { query << " WHERE " << condition; } mysqlpp::StoreQueryResult res = query.store(); mysqlpp::Row row = res[0]; count = row["COUNT(*)"]; return count; }
[ "zhong-liang.xing@hpe.com" ]
zhong-liang.xing@hpe.com
fb452654e5854abdab620cf9b870f086f17fb14d
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_new_log_5964.cpp
0696e51f33e64246211a4bd3c552579979095af0
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
257
cpp
ap_log_rerror(APLOG_MARK, (ctx->flags & SSI_FLAG_PRINTING) ? APLOG_ERR : APLOG_WARNING, 0, r, APLOGNO(03195) "missing argument for exec element in %s", r->filename);
[ "993273596@qq.com" ]
993273596@qq.com
8e26bc6de0b6a505a9b854887bd613d221e744cf
30224146015595693911899123c42c952e539faa
/src/uint512.h
dc8839e989cb2aedf9ddd7ed7e648ef21471a1db
[ "MIT" ]
permissive
anandsinha095/coin
e0a0b56f49522e5a55152fbcfb2accc7665af32b
9a1aa71a71e4a17e82f114d30472cf2450f1070c
refs/heads/main
2023-02-02T18:53:17.466582
2020-12-22T18:40:23
2020-12-22T18:40:23
323,137,870
0
0
null
null
null
null
UTF-8
C++
false
false
1,303
h
// Copyright (c) 2017-2018 The PIVX developers // Copyright (c) 2018-2020 The Jdcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef Jdcoin_UINT512_H #define Jdcoin_UINT512_H #include "arith_uint256.h" #include "uint256.h" /** 512-bit unsigned big integer. */ class uint512 : public base_blob<512> { public: uint512() {} uint512(const base_blob<512>& b) : base_blob<512>(b) {} //explicit uint512(const std::vector<unsigned char>& vch) : base_uint<512>(vch) {} explicit uint512(const std::vector<unsigned char>& vch) : base_blob<512>(vch) {} //explicit uint512(const std::string& str) : base_blob<512>(str) {} uint256 trim256() const { std::vector<unsigned char> vch; const unsigned char* p = this->begin(); for (unsigned int i = 0; i < 32; i++) { vch.push_back(*p++); } uint256 retval(vch); return retval; } }; /* uint256 from const char *. * This is a separate function because the constructor uint256(const char*) can result * in dangerously catching uint256(0). */ inline uint512 uint512S(const char* str) { uint512 rv; rv.SetHex(str); return rv; } #endif // Jdcoin_UINT512_H
[ "anandsinha095@gmail.com" ]
anandsinha095@gmail.com
469de492a27dbcf9853287f2ae28f53b1e092f19
bac7267590c6267b489178c8717e42a1865bb46b
/WildMagic5/LibGraphics/SceneGraph/Wm5StandardMesh.cpp
623578158aed8bc41ed504317df0feab3dfce647
[]
no_license
VB6Hobbyst7/GeometricTools-Apple
1e53f260e84f8942e12adf7591b83ba2dd46a7f1
07b9764871a9dbe1240b6181039dd703e118a628
refs/heads/master
2021-02-11T11:17:56.813941
2013-11-26T15:25:10
2013-11-26T15:25:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
42,219
cpp
// Geometric Tools, LLC // Copyright (c) 1998-2013 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // // File Version: 5.0.0 (2010/01/01) #include "Wm5GraphicsPCH.h" #include "Wm5StandardMesh.h" #include "Wm5Float2.h" using namespace Wm5; //---------------------------------------------------------------------------- StandardMesh::StandardMesh (VertexFormat* vformat, bool isStatic, bool inside, const Transform* transform) : mVFormat(vformat), mIsStatic(isStatic), mInside(inside), mHasNormals(false), mUsage(isStatic ? Buffer::BU_STATIC : Buffer::BU_DYNAMIC) { int posIndex = mVFormat->GetIndex(VertexFormat::AU_POSITION); assertion(posIndex >= 0, "Vertex format must have positions\n"); VertexFormat::AttributeType posType = mVFormat->GetAttributeType(posIndex); assertion(posType == VertexFormat::AT_FLOAT3, "Positions must be 3-tuples of floats\n"); WM5_UNUSED(posType); int norIndex = mVFormat->GetIndex(VertexFormat::AU_NORMAL); if (norIndex >= 0) { VertexFormat::AttributeType norType = mVFormat->GetAttributeType(norIndex); if (norType == VertexFormat::AT_FLOAT3) { mHasNormals = true; } } for (int unit = 0; unit < MAX_UNITS; ++unit) { mHasTCoords[unit] = false; int tcdIndex = mVFormat->GetIndex(VertexFormat::AU_TEXCOORD, unit); if (tcdIndex >= 0) { VertexFormat::AttributeType tcdType = mVFormat->GetAttributeType(tcdIndex); if (tcdType == VertexFormat::AT_FLOAT2) { mHasTCoords[unit] = true; } } } if (transform) { mTransform = *transform; } } //---------------------------------------------------------------------------- StandardMesh::~StandardMesh () { } //---------------------------------------------------------------------------- void StandardMesh::SetTransform (const Transform& transform) { mTransform = transform; } //---------------------------------------------------------------------------- const Transform& StandardMesh::GetTransform () const { return mTransform; } //---------------------------------------------------------------------------- TriMesh* StandardMesh::Rectangle (int xSamples, int ySamples, float xExtent, float yExtent) { int numVertices = xSamples*ySamples; int numTriangles = 2*(xSamples-1)*(ySamples-1); int numIndices = 3*numTriangles; int stride = mVFormat->GetStride(); // Create a vertex buffer. VertexBuffer* vbuffer = new0 VertexBuffer(numVertices, stride, mUsage); VertexBufferAccessor vba(mVFormat, vbuffer); // Generate geometry. float inv0 = 1.0f/(xSamples - 1.0f); float inv1 = 1.0f/(ySamples - 1.0f); float u, v, x, y; int i, i0, i1; for (i1 = 0, i = 0; i1 < ySamples; ++i1) { v = i1*inv1; y = (2.0f*v - 1.0f)*yExtent; for (i0 = 0; i0 < xSamples; ++i0, ++i) { u = i0*inv0; x = (2.0f*u - 1.0f)*xExtent; vba.Position<Float3>(i) = Float3(x, y, 0.0f); if (mHasNormals) { vba.Normal<Float3>(i) = Float3(0.0f, 0.0f, 1.0f); } Float2 tcoord(u, v); for (int unit = 0; unit < MAX_UNITS; ++unit) { if (mHasTCoords[unit]) { vba.TCoord<Float2>(unit, i) = tcoord; } } } } TransformData(vba); // Generate indices. IndexBuffer* ibuffer = new0 IndexBuffer(numIndices, 4, mUsage); int* indices = (int*)ibuffer->GetData(); for (i1 = 0; i1 < ySamples - 1; ++i1) { for (i0 = 0; i0 < xSamples - 1; ++i0) { int v0 = i0 + xSamples * i1; int v1 = v0 + 1; int v2 = v1 + xSamples; int v3 = v0 + xSamples; *indices++ = v0; *indices++ = v1; *indices++ = v2; *indices++ = v0; *indices++ = v2; *indices++ = v3; } } return new0 TriMesh(mVFormat, vbuffer, ibuffer); } //---------------------------------------------------------------------------- TriMesh* StandardMesh::Disk (int shellSamples, int radialSamples, float radius) { int rsm1 = radialSamples - 1, ssm1 = shellSamples - 1; int numVertices = 1 + radialSamples*ssm1; int numTriangles = radialSamples*(2*ssm1-1); int numIndices = 3*numTriangles; int stride = mVFormat->GetStride(); // Create a vertex buffer. VertexBuffer* vbuffer = new0 VertexBuffer(numVertices, stride, mUsage); VertexBufferAccessor vba(mVFormat, vbuffer); // Generate geometry. // Center of disk. vba.Position<Float3>(0) = Float3(0.0f, 0.0f, 0.0f); if (mHasNormals) { vba.Normal<Float3>(0) = Float3(0.0f, 0.0f, 1.0f); } Float2 tcoord(0.5f, 0.5f); int unit; for (unit = 0; unit < MAX_UNITS; ++unit) { if (mHasTCoords[unit]) { vba.TCoord<Float2>(unit, 0) = tcoord; } } float invSSm1 = 1.0f/(float)ssm1; float invRS = 1.0f/(float)radialSamples; for (int r = 0; r < radialSamples; ++r) { float angle = Mathf::TWO_PI*invRS*r; float cs = Mathf::Cos(angle); float sn = Mathf::Sin(angle); AVector radial(cs, sn, 0.0f); for (int s = 1; s < shellSamples; ++s) { float fraction = invSSm1*s; // in (0,R] AVector fracRadial = fraction*radial; int i = s + ssm1*r; vba.Position<Float3>(i) = radius*fracRadial; if (mHasNormals) { vba.Normal<Float3>(i) = Float3(0.0f, 0.0f, 1.0f); } tcoord[0] = 0.5f + 0.5f*fracRadial[0]; tcoord[1] = 0.5f + 0.5f*fracRadial[1]; for (unit = 0; unit < MAX_UNITS; ++unit) { if (mHasTCoords[unit]) { vba.TCoord<Float2>(unit, i) = tcoord; } } } } TransformData(vba); // Generate indices. IndexBuffer* ibuffer = new0 IndexBuffer(numIndices, 4, mUsage); int* indices = (int*)ibuffer->GetData(); for (int r0 = rsm1, r1 = 0, t = 0; r1 < radialSamples; r0 = r1++) { indices[0] = 0; indices[1] = 1 + ssm1*r0; indices[2] = 1 + ssm1*r1; indices += 3; ++t; for (int s = 1; s < ssm1; ++s, indices += 6) { int i00 = s + ssm1*r0; int i01 = s + ssm1*r1; int i10 = i00 + 1; int i11 = i01 + 1; indices[0] = i00; indices[1] = i10; indices[2] = i11; indices[3] = i00; indices[4] = i11; indices[5] = i01; t += 2; } } return new0 TriMesh(mVFormat, vbuffer, ibuffer); } //---------------------------------------------------------------------------- TriMesh* StandardMesh::Box (float xExtent, float yExtent, float zExtent) { int numVertices = 8; int numTriangles = 12; int numIndices = 3*numTriangles; int stride = mVFormat->GetStride(); // Create a vertex buffer. VertexBuffer* vbuffer = new0 VertexBuffer(numVertices, stride, mUsage); VertexBufferAccessor vba(mVFormat, vbuffer); // Generate geometry. vba.Position<Float3>(0) = Float3(-xExtent, -yExtent, -zExtent); vba.Position<Float3>(1) = Float3(+xExtent, -yExtent, -zExtent); vba.Position<Float3>(2) = Float3(+xExtent, +yExtent, -zExtent); vba.Position<Float3>(3) = Float3(-xExtent, +yExtent, -zExtent); vba.Position<Float3>(4) = Float3(-xExtent, -yExtent, +zExtent); vba.Position<Float3>(5) = Float3(+xExtent, -yExtent, +zExtent); vba.Position<Float3>(6) = Float3(+xExtent, +yExtent, +zExtent); vba.Position<Float3>(7) = Float3(-xExtent, +yExtent, +zExtent); for (int unit = 0; unit < MAX_UNITS; ++unit) { if (mHasTCoords[unit]) { vba.TCoord<Float2>(unit, 0) = Float2(0.25f, 0.75f); vba.TCoord<Float2>(unit, 1) = Float2(0.75f, 0.75f); vba.TCoord<Float2>(unit, 2) = Float2(0.75f, 0.25f); vba.TCoord<Float2>(unit, 3) = Float2(0.25f, 0.25f); vba.TCoord<Float2>(unit, 4) = Float2(0.0f, 1.0f); vba.TCoord<Float2>(unit, 5) = Float2(1.0f, 1.0f); vba.TCoord<Float2>(unit, 6) = Float2(1.0f, 0.0f); vba.TCoord<Float2>(unit, 7) = Float2(0.0f, 0.0f); } } TransformData(vba); // Generate indices (outside view). IndexBuffer* ibuffer = new0 IndexBuffer(numIndices, 4, mUsage); int* indices = (int*)ibuffer->GetData(); indices[ 0] = 0; indices[ 1] = 2; indices[ 2] = 1; indices[ 3] = 0; indices[ 4] = 3; indices[ 5] = 2; indices[ 6] = 0; indices[ 7] = 1; indices[ 8] = 5; indices[ 9] = 0; indices[10] = 5; indices[11] = 4; indices[12] = 0; indices[13] = 4; indices[14] = 7; indices[15] = 0; indices[16] = 7; indices[17] = 3; indices[18] = 6; indices[19] = 4; indices[20] = 5; indices[21] = 6; indices[22] = 7; indices[23] = 4; indices[24] = 6; indices[25] = 5; indices[26] = 1; indices[27] = 6; indices[28] = 1; indices[29] = 2; indices[30] = 6; indices[31] = 2; indices[32] = 3; indices[33] = 6; indices[34] = 3; indices[35] = 7; if (mInside) { ReverseTriangleOrder(numTriangles, indices); } TriMesh* mesh = new0 TriMesh(mVFormat, vbuffer, ibuffer); if (mHasNormals) { mesh->UpdateModelSpace(Visual::GU_NORMALS); } return mesh; } //---------------------------------------------------------------------------- TriMesh* StandardMesh::Cylinder (int axisSamples, int radialSamples, float radius, float height, bool open) { TriMesh* mesh; int unit; Float2 tcoord; if (open) { int numVertices = axisSamples*(radialSamples+1); int numTriangles = 2*(axisSamples-1)*radialSamples; int numIndices = 3*numTriangles; int stride = mVFormat->GetStride(); // Create a vertex buffer. VertexBuffer* vbuffer = new0 VertexBuffer(numVertices, stride, mUsage); VertexBufferAccessor vba(mVFormat, vbuffer); // Generate geometry. float invRS = 1.0f/(float)radialSamples; float invASm1 = 1.0f/(float)(axisSamples-1); float halfHeight = 0.5f*height; int r, a, aStart, i; // Generate points on the unit circle to be used in computing the // mesh points on a cylinder slice. float* cs = new1<float>(radialSamples + 1); float* sn = new1<float>(radialSamples + 1); for (r = 0; r < radialSamples; ++r) { float angle = Mathf::TWO_PI*invRS*r; cs[r] = Mathf::Cos(angle); sn[r] = Mathf::Sin(angle); } cs[radialSamples] = cs[0]; sn[radialSamples] = sn[0]; // Generate the cylinder itself. for (a = 0, i = 0; a < axisSamples; ++a) { float axisFraction = a*invASm1; // in [0,1] float z = -halfHeight + height*axisFraction; // Compute center of slice. APoint sliceCenter(0.0f, 0.0f, z); // Compute slice vertices with duplication at endpoint. int save = i; for (r = 0; r < radialSamples; ++r) { float radialFraction = r*invRS; // in [0,1) AVector normal(cs[r], sn[r], 0.0f); vba.Position<Float3>(i) = sliceCenter + radius*normal; if (mHasNormals) { if (mInside) { vba.Normal<Float3>(i) = -normal; } else { vba.Normal<Float3>(i) = normal; } } tcoord = Float2(radialFraction, axisFraction); for (unit = 0; unit < MAX_UNITS; ++unit) { if (mHasTCoords[unit]) { vba.TCoord<Float2>(unit, i) = tcoord; } } ++i; } vba.Position<Float3>(i) = vba.Position<Float3>(save); if (mHasNormals) { vba.Normal<Float3>(i) = vba.Normal<Float3>(save); } tcoord = Float2(1.0f, axisFraction); for (unit = 0; unit < MAX_UNITS; ++unit) { if (mHasTCoords[unit]) { vba.TCoord<Float2>(0, i) = tcoord; } } ++i; } TransformData(vba); // Generate indices. IndexBuffer* ibuffer = new0 IndexBuffer(numIndices, 4, mUsage); int* indices = (int*)ibuffer->GetData(); for (a = 0, aStart = 0; a < axisSamples-1; ++a) { int i0 = aStart; int i1 = i0 + 1; aStart += radialSamples + 1; int i2 = aStart; int i3 = i2 + 1; for (i = 0; i < radialSamples; ++i, indices += 6) { if (mInside) { indices[0] = i0++; indices[1] = i2; indices[2] = i1; indices[3] = i1++; indices[4] = i2++; indices[5] = i3++; } else // outside view { indices[0] = i0++; indices[1] = i1; indices[2] = i2; indices[3] = i1++; indices[4] = i3++; indices[5] = i2++; } } } delete1(cs); delete1(sn); mesh = new0 TriMesh(mVFormat, vbuffer, ibuffer); } else { mesh = Sphere(axisSamples, radialSamples, radius); VertexBuffer* vbuffer = mesh->GetVertexBuffer(); int numVertices = vbuffer->GetNumElements(); VertexBufferAccessor vba(mVFormat, vbuffer); // Flatten sphere at poles. float hDiv2 = 0.5f*height; vba.Position<Float3>(numVertices-2)[2] = -hDiv2; // south pole vba.Position<Float3>(numVertices-1)[2] = +hDiv2; // north pole // Remap z-values to [-h/2,h/2]. float zFactor = 2.0f/(axisSamples-1); float tmp0 = radius*(-1.0f + zFactor); float tmp1 = 1.0f/(radius*(+1.0f - zFactor)); for (int i = 0; i < numVertices-2; ++i) { Float3& pos = vba.Position<Float3>(i); pos[2] = hDiv2*(-1.0f + tmp1*(pos[2] - tmp0)); float adjust = radius*Mathf::InvSqrt(pos[0]*pos[0] + pos[1]*pos[1]); pos[0] *= adjust; pos[1] *= adjust; } TransformData(vba); if (mHasNormals) { mesh->UpdateModelSpace(Visual::GU_NORMALS); } } // The duplication of vertices at the seam causes the automatically // generated bounding volume to be slightly off center. Reset the bound // to use the true information. float maxDist = Mathf::Sqrt(radius*radius + height*height); mesh->GetModelBound().SetCenter(APoint::ORIGIN); mesh->GetModelBound().SetRadius(maxDist); return mesh; } //---------------------------------------------------------------------------- TriMesh* StandardMesh::Sphere (int zSamples, int radialSamples, float radius) { int zsm1 = zSamples-1, zsm2 = zSamples-2, zsm3 = zSamples-3; int rsp1 = radialSamples+1; int numVertices = zsm2*rsp1 + 2; int numTriangles = 2*zsm2*radialSamples; int numIndices = 3*numTriangles; int stride = mVFormat->GetStride(); // Create a vertex buffer. VertexBuffer* vbuffer = new0 VertexBuffer(numVertices, stride, mUsage); VertexBufferAccessor vba(mVFormat, vbuffer); // Generate geometry. float invRS = 1.0f/(float)radialSamples; float zFactor = 2.0f/(float)zsm1; int r, z, zStart, i, unit; Float2 tcoord; // Generate points on the unit circle to be used in computing the mesh // points on a cylinder slice. float* sn = new1<float>(rsp1); float* cs = new1<float>(rsp1); for (r = 0; r < radialSamples; ++r) { float angle = Mathf::TWO_PI*invRS*r; cs[r] = Mathf::Cos(angle); sn[r] = Mathf::Sin(angle); } sn[radialSamples] = sn[0]; cs[radialSamples] = cs[0]; // Generate the cylinder itself. for (z = 1, i = 0; z < zsm1; ++z) { float zFraction = -1.0f + zFactor*z; // in (-1,1) float zValue = radius*zFraction; // Compute center of slice. APoint sliceCenter(0.0f, 0.0f, zValue); // Compute radius of slice. float sliceRadius = Mathf::Sqrt(Mathf::FAbs( radius*radius - zValue*zValue)); // Compute slice vertices with duplication at endpoint. AVector normal; int save = i; for (r = 0; r < radialSamples; ++r) { float radialFraction = r*invRS; // in [0,1) AVector radial(cs[r], sn[r], 0.0f); vba.Position<Float3>(i) = sliceCenter + sliceRadius*radial; if (mHasNormals) { normal = vba.Position<Float3>(i); normal.Normalize(); if (mInside) { vba.Normal<Float3>(i) = -normal; } else { vba.Normal<Float3>(i) = normal; } } tcoord[0] = radialFraction; tcoord[1] = 0.5f*(zFraction + 1.0f); for (unit = 0; unit < MAX_UNITS; ++unit) { if (mHasTCoords[unit]) { vba.TCoord<Float2>(unit, i) = tcoord; } } ++i; } vba.Position<Float3>(i) = vba.Position<Float3>(save); if (mHasNormals) { vba.Normal<Float3>(i) = vba.Normal<Float3>(save); } tcoord[0] = 1.0f; tcoord[1] = 0.5f*(zFraction + 1.0f); for (unit = 0; unit < MAX_UNITS; ++unit) { if (mHasTCoords[unit]) { vba.TCoord<Float2>(unit, i) = tcoord; } } ++i; } // south pole vba.Position<Float3>(i) = Float3(0.0f, 0.0f, -radius); if (mHasNormals) { if (mInside) { vba.Normal<Float3>(i) = Float3(0.0f, 0.0f, 1.0f); } else { vba.Normal<Float3>(i) = Float3(0.0f, 0.0f, -1.0f); } } tcoord = Float2(0.5f, 0.5f); for (unit = 0; unit < MAX_UNITS; ++unit) { if (mHasTCoords[unit]) { vba.TCoord<Float2>(unit, i) = tcoord; } } ++i; // north pole vba.Position<Float3>(i) = Float3(0.0f, 0.0f, radius); if (mHasNormals) { if (mInside) { vba.Normal<Float3>(i) = Float3(0.0f, 0.0f, -1.0f); } else { vba.Normal<Float3>(i) = Float3(0.0f, 0.0f, 1.0f); } } tcoord = Float2(0.5f, 1.0f); for (unit = 0; unit < MAX_UNITS; ++unit) { if (mHasTCoords[unit]) { vba.TCoord<Float2>(unit, i) = tcoord; } } ++i; TransformData(vba); // Generate indices. IndexBuffer* ibuffer = new0 IndexBuffer(numIndices, 4, mUsage); int* indices = (int*)ibuffer->GetData(); for (z = 0, zStart = 0; z < zsm3; ++z) { int i0 = zStart; int i1 = i0 + 1; zStart += rsp1; int i2 = zStart; int i3 = i2 + 1; for (i = 0; i < radialSamples; ++i, indices += 6) { if (mInside) { indices[0] = i0++; indices[1] = i2; indices[2] = i1; indices[3] = i1++; indices[4] = i2++; indices[5] = i3++; } else // inside view { indices[0] = i0++; indices[1] = i1; indices[2] = i2; indices[3] = i1++; indices[4] = i3++; indices[5] = i2++; } } } // south pole triangles int numVerticesM2 = numVertices - 2; for (i = 0; i < radialSamples; ++i, indices += 3) { if (mInside) { indices[0] = i; indices[1] = i + 1; indices[2] = numVerticesM2; } else { indices[0] = i; indices[1] = numVerticesM2; indices[2] = i + 1; } } // north pole triangles int numVerticesM1 = numVertices-1, offset = zsm3*rsp1; for (i = 0; i < radialSamples; ++i, indices += 3) { if (mInside) { indices[0] = i + offset; indices[1] = numVerticesM1; indices[2] = i + 1 + offset; } else { indices[0] = i + offset; indices[1] = i + 1 + offset; indices[2] = numVerticesM1; } } delete1(cs); delete1(sn); // The duplication of vertices at the seam cause the automatically // generated bounding volume to be slightly off center. Reset the bound // to use the true information. TriMesh* mesh = new0 TriMesh(mVFormat, vbuffer, ibuffer); mesh->GetModelBound().SetCenter(APoint::ORIGIN); mesh->GetModelBound().SetRadius(radius); return mesh; } //---------------------------------------------------------------------------- TriMesh* StandardMesh::Torus (int circleSamples, int radialSamples, float outerRadius, float innerRadius) { int numVertices = (circleSamples+1)*(radialSamples+1); int numTriangles = 2*circleSamples*radialSamples; int numIndices = 3*numTriangles; int stride = mVFormat->GetStride(); // Create a vertex buffer. VertexBuffer* vbuffer = new0 VertexBuffer(numVertices, stride, mUsage); VertexBufferAccessor vba(mVFormat, vbuffer); // Generate geometry. float invCS = 1.0f/(float)circleSamples; float invRS = 1.0f/(float)radialSamples; int c, r, i, unit; Float2 tcoord; // Generate the cylinder itself. for (c = 0, i = 0; c < circleSamples; ++c) { // Compute center point on torus circle at specified angle. float circleFraction = c*invCS; // in [0,1) float theta = Mathf::TWO_PI*circleFraction; float cosTheta = Mathf::Cos(theta); float sinTheta = Mathf::Sin(theta); AVector radial(cosTheta, sinTheta, 0.0f); AVector torusMiddle = outerRadius*radial; // Compute slice vertices with duplication at endpoint. int save = i; for (r = 0; r < radialSamples; ++r) { float radialFraction = r*invRS; // in [0,1) float phi = Mathf::TWO_PI*radialFraction; float cosPhi = Mathf::Cos(phi); float sinPhi = Mathf::Sin(phi); AVector normal = cosPhi*radial + sinPhi*AVector::UNIT_Z; vba.Position<Float3>(i) = torusMiddle + innerRadius*normal; if (mHasNormals) { if (mInside) { vba.Normal<Float3>(i) = -normal; } else { vba.Normal<Float3>(i) = normal; } } tcoord = Float2(radialFraction, circleFraction); for (unit = 0; unit < MAX_UNITS; ++unit) { if (mHasTCoords[unit]) { vba.TCoord<Float2>(unit, i) = tcoord; } } ++i; } vba.Position<Float3>(i) = vba.Position<Float3>(save); if (mHasNormals) { vba.Normal<Float3>(i) = vba.Normal<Float3>(save); } tcoord = Float2(1.0f, circleFraction); for (unit = 0; unit < MAX_UNITS; ++unit) { if (mHasTCoords[unit]) { vba.TCoord<Float2>(unit, i) = tcoord; } } ++i; } // Duplicate the cylinder ends to form a torus. for (r = 0; r <= radialSamples; ++r, ++i) { vba.Position<Float3>(i) = vba.Position<Float3>(r); if (mHasNormals) { vba.Normal<Float3>(i) = vba.Normal<Float3>(r); } for (unit = 0; unit < MAX_UNITS; ++unit) { if (mHasTCoords[unit]) { vba.TCoord<Float2>(unit, i) = Float2(vba.TCoord<Float2>(unit, r)[0], 1.0f); } } } TransformData(vba); // Generate indices. IndexBuffer* ibuffer = new0 IndexBuffer(numIndices, 4, mUsage); int* indices = (int*)ibuffer->GetData(); int cStart = 0; for (c = 0; c < circleSamples; ++c) { int i0 = cStart; int i1 = i0 + 1; cStart += radialSamples + 1; int i2 = cStart; int i3 = i2 + 1; for (i = 0; i < radialSamples; ++i, indices += 6) { if (mInside) { indices[0] = i0++; indices[1] = i1; indices[2] = i2; indices[3] = i1++; indices[4] = i3++; indices[5] = i2++; } else // inside view { indices[0] = i0++; indices[1] = i2; indices[2] = i1; indices[3] = i1++; indices[4] = i2++; indices[5] = i3++; } } } // The duplication of vertices at the seam cause the automatically // generated bounding volume to be slightly off center. Reset the bound // to use the true information. TriMesh* mesh = new0 TriMesh(mVFormat, vbuffer, ibuffer); mesh->GetModelBound().SetCenter(APoint::ORIGIN); mesh->GetModelBound().SetRadius(outerRadius); return mesh; } //---------------------------------------------------------------------------- TriMesh* StandardMesh::Tetrahedron () { float fSqrt2Div3 = Mathf::Sqrt(2.0f)/3.0f; float fSqrt6Div3 = Mathf::Sqrt(6.0f)/3.0f; float fOneThird = 1.0f/3.0f; int numVertices = 4; int numTriangles = 4; int numIndices = 3*numTriangles; int stride = mVFormat->GetStride(); // Create a vertex buffer. VertexBuffer* vbuffer = new0 VertexBuffer(numVertices, stride, mUsage); VertexBufferAccessor vba(mVFormat, vbuffer); // Generate geometry. vba.Position<Float3>(0) = Float3(0.0f, 0.0f, 1.0f); vba.Position<Float3>(1) = Float3(2.0f*fSqrt2Div3, 0.0f, -fOneThird); vba.Position<Float3>(2) = Float3(-fSqrt2Div3, fSqrt6Div3, -fOneThird); vba.Position<Float3>(3) = Float3(-fSqrt2Div3, -fSqrt6Div3, -fOneThird); CreatePlatonicNormals(vba); CreatePlatonicUVs(vba); TransformData(vba); // Generate indices. IndexBuffer* ibuffer = new0 IndexBuffer(numIndices, 4, mUsage); int* indices = (int*)ibuffer->GetData(); indices[ 0] = 0; indices[ 1] = 1; indices[ 2] = 2; indices[ 3] = 0; indices[ 4] = 2; indices[ 5] = 3; indices[ 6] = 0; indices[ 7] = 3; indices[ 8] = 1; indices[ 9] = 1; indices[10] = 3; indices[11] = 2; if (mInside) { ReverseTriangleOrder(numTriangles,indices); } return new0 TriMesh(mVFormat, vbuffer, ibuffer); } //---------------------------------------------------------------------------- TriMesh* StandardMesh::Hexahedron () { float fSqrtThird = Mathf::Sqrt(1.0f/3.0f); int numVertices = 8; int numTriangles = 12; int numIndices = 3*numTriangles; int stride = mVFormat->GetStride(); // Create a vertex buffer. VertexBuffer* vbuffer = new0 VertexBuffer(numVertices, stride, mUsage); VertexBufferAccessor vba(mVFormat, vbuffer); // Generate geometry. vba.Position<Float3>(0) = Float3(-fSqrtThird, -fSqrtThird, -fSqrtThird); vba.Position<Float3>(1) = Float3( fSqrtThird, -fSqrtThird, -fSqrtThird); vba.Position<Float3>(2) = Float3( fSqrtThird, fSqrtThird, -fSqrtThird); vba.Position<Float3>(3) = Float3(-fSqrtThird, fSqrtThird, -fSqrtThird); vba.Position<Float3>(4) = Float3(-fSqrtThird, -fSqrtThird, fSqrtThird); vba.Position<Float3>(5) = Float3( fSqrtThird, -fSqrtThird, fSqrtThird); vba.Position<Float3>(6) = Float3( fSqrtThird, fSqrtThird, fSqrtThird); vba.Position<Float3>(7) = Float3(-fSqrtThird, fSqrtThird, fSqrtThird); CreatePlatonicNormals(vba); CreatePlatonicUVs(vba); TransformData(vba); // Generate indices. IndexBuffer* ibuffer = new0 IndexBuffer(numIndices, 4, mUsage); int* indices = (int*)ibuffer->GetData(); indices[ 0] = 0; indices[ 1] = 3; indices[ 2] = 2; indices[ 3] = 0; indices[ 4] = 2; indices[ 5] = 1; indices[ 6] = 0; indices[ 7] = 1; indices[ 8] = 5; indices[ 9] = 0; indices[10] = 5; indices[11] = 4; indices[12] = 0; indices[13] = 4; indices[14] = 7; indices[15] = 0; indices[16] = 7; indices[17] = 3; indices[18] = 6; indices[19] = 5; indices[20] = 1; indices[21] = 6; indices[22] = 1; indices[23] = 2; indices[24] = 6; indices[25] = 2; indices[26] = 3; indices[27] = 6; indices[28] = 3; indices[29] = 7; indices[30] = 6; indices[31] = 7; indices[32] = 4; indices[33] = 6; indices[34] = 4; indices[35] = 5; if (mInside) { ReverseTriangleOrder(numTriangles,indices); } return new0 TriMesh(mVFormat, vbuffer, ibuffer); } //---------------------------------------------------------------------------- TriMesh* StandardMesh::Octahedron () { int numVertices = 6; int numTriangles = 8; int numIndices = 3*numTriangles; int stride = mVFormat->GetStride(); // Create a vertex buffer. VertexBuffer* vbuffer = new0 VertexBuffer(numVertices, stride, mUsage); VertexBufferAccessor vba(mVFormat, vbuffer); // Generate geometry. vba.Position<Float3>(0) = Float3( 1.0f, 0.0f, 0.0f); vba.Position<Float3>(1) = Float3(-1.0f, 0.0f, 0.0f); vba.Position<Float3>(2) = Float3( 0.0f, 1.0f, 0.0f); vba.Position<Float3>(3) = Float3( 0.0f,-1.0f, 0.0f); vba.Position<Float3>(4) = Float3( 0.0f, 0.0f, 1.0f); vba.Position<Float3>(5) = Float3( 0.0f, 0.0f,-1.0f); CreatePlatonicNormals(vba); CreatePlatonicUVs(vba); TransformData(vba); // Generate indices. IndexBuffer* ibuffer = new0 IndexBuffer(numIndices, 4, mUsage); int* indices = (int*)ibuffer->GetData(); indices[ 0] = 4; indices[ 1] = 0; indices[ 2] = 2; indices[ 3] = 4; indices[ 4] = 2; indices[ 5] = 1; indices[ 6] = 4; indices[ 7] = 1; indices[ 8] = 3; indices[ 9] = 4; indices[10] = 3; indices[11] = 0; indices[12] = 5; indices[13] = 2; indices[14] = 0; indices[15] = 5; indices[16] = 1; indices[17] = 2; indices[18] = 5; indices[19] = 3; indices[20] = 1; indices[21] = 5; indices[22] = 0; indices[23] = 3; if (mInside) { ReverseTriangleOrder(numTriangles,indices); } return new0 TriMesh(mVFormat, vbuffer, ibuffer); } //---------------------------------------------------------------------------- TriMesh* StandardMesh::Dodecahedron () { float a = 1.0f/Mathf::Sqrt(3.0f); float b = Mathf::Sqrt((3.0f-Mathf::Sqrt(5.0f))/6.0f); float c = Mathf::Sqrt((3.0f+Mathf::Sqrt(5.0f))/6.0f); int numVertices = 20; int numTriangles = 36; int numIndices = 3*numTriangles; int stride = mVFormat->GetStride(); // Create a vertex buffer. VertexBuffer* vbuffer = new0 VertexBuffer(numVertices, stride, mUsage); VertexBufferAccessor vba(mVFormat, vbuffer); // Generate geometry. vba.Position<Float3>( 0) = Float3( a, a, a); vba.Position<Float3>( 1) = Float3( a, a,-a); vba.Position<Float3>( 2) = Float3( a,-a, a); vba.Position<Float3>( 3) = Float3( a,-a,-a); vba.Position<Float3>( 4) = Float3(-a, a, a); vba.Position<Float3>( 5) = Float3(-a, a,-a); vba.Position<Float3>( 6) = Float3(-a,-a, a); vba.Position<Float3>( 7) = Float3(-a,-a,-a); vba.Position<Float3>( 8) = Float3( b, c, 0.0f); vba.Position<Float3>( 9) = Float3( -b, c, 0.0f); vba.Position<Float3>(10) = Float3( b, -c, 0.0f); vba.Position<Float3>(11) = Float3( -b, -c, 0.0f); vba.Position<Float3>(12) = Float3( c, 0.0f, b); vba.Position<Float3>(13) = Float3( c, 0.0f, -b); vba.Position<Float3>(14) = Float3( -c, 0.0f, b); vba.Position<Float3>(15) = Float3( -c, 0.0f, -b); vba.Position<Float3>(16) = Float3(0.0f, b, c); vba.Position<Float3>(17) = Float3(0.0f, -b, c); vba.Position<Float3>(18) = Float3(0.0f, b, -c); vba.Position<Float3>(19) = Float3(0.0f, -b, -c); CreatePlatonicNormals(vba); CreatePlatonicUVs(vba); TransformData(vba); // Generate indices. IndexBuffer* ibuffer = new0 IndexBuffer(numIndices, 4, mUsage); int* indices = (int*)ibuffer->GetData(); indices[ 0] = 0; indices[ 1] = 8; indices[ 2] = 9; indices[ 3] = 0; indices[ 4] = 9; indices[ 5] = 4; indices[ 6] = 0; indices[ 7] = 4; indices[ 8] = 16; indices[ 9] = 0; indices[ 10] = 12; indices[ 11] = 13; indices[ 12] = 0; indices[ 13] = 13; indices[ 14] = 1; indices[ 15] = 0; indices[ 16] = 1; indices[ 17] = 8; indices[ 18] = 0; indices[ 19] = 16; indices[ 20] = 17; indices[ 21] = 0; indices[ 22] = 17; indices[ 23] = 2; indices[ 24] = 0; indices[ 25] = 2; indices[ 26] = 12; indices[ 27] = 8; indices[ 28] = 1; indices[ 29] = 18; indices[ 30] = 8; indices[ 31] = 18; indices[ 32] = 5; indices[ 33] = 8; indices[ 34] = 5; indices[ 35] = 9; indices[ 36] = 12; indices[ 37] = 2; indices[ 38] = 10; indices[ 39] = 12; indices[ 40] = 10; indices[ 41] = 3; indices[ 42] = 12; indices[ 43] = 3; indices[ 44] = 13; indices[ 45] = 16; indices[ 46] = 4; indices[ 47] = 14; indices[ 48] = 16; indices[ 49] = 14; indices[ 50] = 6; indices[ 51] = 16; indices[ 52] = 6; indices[ 53] = 17; indices[ 54] = 9; indices[ 55] = 5; indices[ 56] = 15; indices[ 57] = 9; indices[ 58] = 15; indices[ 59] = 14; indices[ 60] = 9; indices[ 61] = 14; indices[ 62] = 4; indices[ 63] = 6; indices[ 64] = 11; indices[ 65] = 10; indices[ 66] = 6; indices[ 67] = 10; indices[ 68] = 2; indices[ 69] = 6; indices[ 70] = 2; indices[ 71] = 17; indices[ 72] = 3; indices[ 73] = 19; indices[ 74] = 18; indices[ 75] = 3; indices[ 76] = 18; indices[ 77] = 1; indices[ 78] = 3; indices[ 79] = 1; indices[ 80] = 13; indices[ 81] = 7; indices[ 82] = 15; indices[ 83] = 5; indices[ 84] = 7; indices[ 85] = 5; indices[ 86] = 18; indices[ 87] = 7; indices[ 88] = 18; indices[ 89] = 19; indices[ 90] = 7; indices[ 91] = 11; indices[ 92] = 6; indices[ 93] = 7; indices[ 94] = 6; indices[ 95] = 14; indices[ 96] = 7; indices[ 97] = 14; indices[ 98] = 15; indices[ 99] = 7; indices[100] = 19; indices[101] = 3; indices[102] = 7; indices[103] = 3; indices[104] = 10; indices[105] = 7; indices[106] = 10; indices[107] = 11; if (mInside) { ReverseTriangleOrder(numTriangles,indices); } return new0 TriMesh(mVFormat, vbuffer, ibuffer); } //---------------------------------------------------------------------------- TriMesh* StandardMesh::Icosahedron () { float goldenRatio = 0.5f*(1.0f + Mathf::Sqrt(5.0f)); float invRoot = 1.0f/Mathf::Sqrt(1.0f + goldenRatio*goldenRatio); float u = goldenRatio*invRoot; float v = invRoot; int numVertices = 12; int numTriangles = 20; int numIndices = 3*numTriangles; int stride = mVFormat->GetStride(); // Create a vertex buffer. VertexBuffer* vbuffer = new0 VertexBuffer(numVertices, stride, mUsage); VertexBufferAccessor vba(mVFormat, vbuffer); // Generate geometry. vba.Position<Float3>( 0) = Float3( u, v,0.0f); vba.Position<Float3>( 1) = Float3( -u, v,0.0f); vba.Position<Float3>( 2) = Float3( u, -v,0.0f); vba.Position<Float3>( 3) = Float3( -u, -v,0.0f); vba.Position<Float3>( 4) = Float3( v,0.0f, u); vba.Position<Float3>( 5) = Float3( v,0.0f, -u); vba.Position<Float3>( 6) = Float3( -v,0.0f, u); vba.Position<Float3>( 7) = Float3( -v,0.0f, -u); vba.Position<Float3>( 8) = Float3(0.0f, u, v); vba.Position<Float3>( 9) = Float3(0.0f, -u, v); vba.Position<Float3>(10) = Float3(0.0f, u, -v); vba.Position<Float3>(11) = Float3(0.0f, -u, -v); CreatePlatonicNormals(vba); CreatePlatonicUVs(vba); TransformData(vba); // Generate indices. IndexBuffer* ibuffer = new0 IndexBuffer(numIndices, 4, mUsage); int* indices = (int*)ibuffer->GetData(); indices[ 0] = 0; indices[ 1] = 8; indices[ 2] = 4; indices[ 3] = 0; indices[ 4] = 5; indices[ 5] = 10; indices[ 6] = 2; indices[ 7] = 4; indices[ 8] = 9; indices[ 9] = 2; indices[10] = 11; indices[11] = 5; indices[12] = 1; indices[13] = 6; indices[14] = 8; indices[15] = 1; indices[16] = 10; indices[17] = 7; indices[18] = 3; indices[19] = 9; indices[20] = 6; indices[21] = 3; indices[22] = 7; indices[23] = 11; indices[24] = 0; indices[25] = 10; indices[26] = 8; indices[27] = 1; indices[28] = 8; indices[29] = 10; indices[30] = 2; indices[31] = 9; indices[32] = 11; indices[33] = 3; indices[34] = 11; indices[35] = 9; indices[36] = 4; indices[37] = 2; indices[38] = 0; indices[39] = 5; indices[40] = 0; indices[41] = 2; indices[42] = 6; indices[43] = 1; indices[44] = 3; indices[45] = 7; indices[46] = 3; indices[47] = 1; indices[48] = 8; indices[49] = 6; indices[50] = 4; indices[51] = 9; indices[52] = 4; indices[53] = 6; indices[54] = 10; indices[55] = 5; indices[56] = 7; indices[57] = 11; indices[58] = 7; indices[59] = 5; if (mInside) { ReverseTriangleOrder(numTriangles,indices); } return new0 TriMesh(mVFormat, vbuffer, ibuffer); } //---------------------------------------------------------------------------- void StandardMesh::TransformData (VertexBufferAccessor& vba) { if (mTransform.IsIdentity()) { return; } const int numVertices = vba.GetNumVertices(); int i; for (i = 0; i < numVertices; ++i) { APoint position = vba.Position<Float3>(i); vba.Position<Float3>(i) = mTransform*position; } if (mHasNormals) { for (i = 0; i < numVertices; ++i) { vba.Normal<AVector>(i).Normalize(); } } } //---------------------------------------------------------------------------- void StandardMesh::ReverseTriangleOrder (int numTriangles, int* indices) { for (int i = 0; i < numTriangles; ++i) { int j1 = 3*i + 1; int j2 = j1 + 1; int save = indices[j1]; indices[j1] = indices[j2]; indices[j2] = save; } } //---------------------------------------------------------------------------- void StandardMesh::CreatePlatonicNormals (VertexBufferAccessor& vba) { if (mHasNormals) { const int numVertices = vba.GetNumVertices(); for (int i = 0; i < numVertices; ++i) { vba.Normal<Float3>(i) = vba.Position<Float3>(i); } } } //---------------------------------------------------------------------------- void StandardMesh::CreatePlatonicUVs (VertexBufferAccessor& vba) { for (int unit = 0; unit < MAX_UNITS; ++unit) { if (mHasTCoords[unit]) { const int numVertices = vba.GetNumVertices(); for (int i = 0; i < numVertices; ++i) { if (Mathf::FAbs(vba.Position<Float3>(i)[2]) < 1.0f) { vba.TCoord<Float2>(unit, i)[0] = 0.5f*(1.0f + Mathf::ATan2(vba.Position<Float3>(i)[1], vba.Position<Float3>(i)[0])*Mathf::INV_PI); } else { vba.TCoord<Float2>(unit, i)[0] = 0.5f; } vba.TCoord<Float2>(unit, i)[1] = Mathf::ACos( vba.Position<Float3>(i)[2])*Mathf::INV_PI; } } } } //----------------------------------------------------------------------------
[ "tprepscius" ]
tprepscius
5c5b1747812c2f1a60c8a8e96d19dbac1b24f145
dfdee3c98beed3c47d7820b0ab85286c630b4ff5
/13-TrabajoFinal/Color.h
46f6dc8546300581547d3f701b2057266b693cac
[]
no_license
MosmannJuan/AED
79a08ceb02b879fe18b11f0cc77f9618f603a808
be452c34bf7dbdadf8bd1040cda4696e06881e02
refs/heads/master
2023-01-21T01:57:41.226826
2020-11-24T22:43:14
2020-11-24T22:43:14
254,676,436
0
0
null
2020-04-10T16:19:11
2020-04-10T15:59:42
null
UTF-8
C++
false
false
2,025
h
/*Mosmann, Juan Ignacio AED 2020 Curso K1051 Color Header 15/09/2020*/ #pragma once #include <string> #include <cstdint> struct Color {uint8_t r, g, b ;}; //Prototipo de funciones Color LeerColor(); //Pide los valores correspondientes a r, g y b de un color al usuario por teclado y retorna el color que forma. Color Mezclar(const Color&, const Color&); //Retorna un color correspondiente a la mezcla de dos colores en partes iguales (promedio) Color MezclarConPartes (const unsigned& , const Color& , const unsigned& , const Color& ); //Retorna un color correspondiente a la mezcla permitiendo mezclar en partes desiguales, cada color es precedido por la cantidad de partes correspondientes Color SumarColores (const Color& , const Color&); //Retorna un Color correspondiente a la suma de cada parte de dos colores Color RestarColores (const Color& , const Color&); //Retorna un Color correspondiente a la resta de cada parte de dos colores Color GetComplementario (const Color&); //Retorna el color complementario al ingresado en el argumento std::string GetHtmlHex (const Color&); //Retorna una cadena correspondiente al color en hexadecimal siguiendo la siguiente forma "#rgb" std::string GetHtmlrgb (const Color&); //Retorna una cadena correspondiente al color en formato "rgb(r,g,b)" bool IsIgualColor (const Color&, const Color&); //Compara dos colores y retorna un booleano true si son iguales o false si no lo son void CrearSvgConTextoEscritoEnAltoContraste (const std::string&, const std::string&, const Color&); //Declaración de las constantes const Color rojo {255, 0, 0}; const Color verde {0, 255, 0}; const Color azul {0, 0, 255}; const Color cyan = SumarColores(verde, azul); const Color magenta = SumarColores(rojo, azul); const Color amarillo = SumarColores(rojo, verde); const Color blanco = SumarColores(SumarColores(rojo, verde), azul); const Color negro = RestarColores(RestarColores(RestarColores (blanco, rojo), verde), azul);
[ "noreply@github.com" ]
noreply@github.com
5434d80acbc60d2cc8dc3183797f0d8d69044bb5
dccd1058e723b6617148824dc0243dbec4c9bd48
/aoj/vol30/3023.cpp
a02b9adef2fb9cc2358839b0b5834d16da73b6c4
[]
no_license
imulan/procon
488e49de3bcbab36c624290cf9e370abfc8735bf
2a86f47614fe0c34e403ffb35108705522785092
refs/heads/master
2021-05-22T09:24:19.691191
2021-01-02T14:27:13
2021-01-02T14:27:13
46,834,567
7
1
null
null
null
null
UTF-8
C++
false
false
3,894
cpp
#include <bits/stdc++.h> using namespace std; using ll = long long; #define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i)) #define all(x) (x).begin(),(x).end() #define pb push_back #define fi first #define se second #define dbg(x) cout<<#x" = "<<((x))<<endl template<class T,class U> ostream& operator<<(ostream& o, const pair<T,U> &p){o<<"("<<p.fi<<","<<p.se<<")";return o;} template<class T> ostream& operator<<(ostream& o, const vector<T> &v){o<<"[";for(T t:v){o<<t<<",";}o<<"]";return o;} struct SCC{ int V; vector<vector<int>> G, rG; vector<int> vs; // 帰りがけ順の並び vector<int> cmp; //属する強連結成分トポロジカル順序 vector<bool> used; SCC(){} SCC(int n){ V = n; G = vector<vector<int>>(n); rG = vector<vector<int>>(n); } void add_edge(int from, int to){ G[from].push_back(to); rG[to].push_back(from); } void dfs(int v){ used[v] = true; rep(i,G[v].size())if(!used[G[v][i]]) dfs(G[v][i]); vs.push_back(v); } void rdfs(int v, int k){ used[v]=true; cmp[v]=k; rep(i,rG[v].size())if(!used[rG[v][i]]) rdfs(rG[v][i],k); } int scc(){ used = vector<bool>(V,false); vs.clear(); rep(i,V)if(!used[i]) dfs(i); used = vector<bool>(V,false); cmp = vector<int>(V); int num_scc = 0; for(int i=vs.size()-1; i>=0; --i)if(!used[vs[i]]) rdfs(vs[i],num_scc++); return num_scc; } }; struct TwoSat{ int v; SCC graph; // v literals // 0~v-1: true // v~2v-1: false TwoSat(int num_literal){ v = num_literal; graph = SCC(2*v); } inline int num(int id, bool b){return id+(b?0:v);} void add_clause(int x, bool X, int y, bool Y){ graph.add_edge(num(x,!X), num(y,Y)); graph.add_edge(num(y,!Y), num(x,X)); } // 割り当てが可能か調べる bool calc(){ graph.scc(); rep(i,v)if(graph.cmp[i]==graph.cmp[v+i]) return false; return true; } // リテラルの真偽値を返す vector<bool> get_literals(){ assert(calc()); vector<bool> res(v); rep(i,v) res[i] = (graph.cmp[i]>graph.cmp[v+i]); return res; } }; struct P{ int x,y; void READ(){ cin >>x >>y; } }; double calc_dist(P p, P q){ double X = abs(p.x-q.x); double Y = abs(p.y-q.y); return sqrt(X*X + Y*Y); } const int N = 15; const double INF = 1e6; double dist[N][N]; double d[N][N]; double dp[1<<N][N]; double D[200][2][200][2]; void calc(int start, int n){ fill(dp[0],dp[1<<N],INF); dp[1<<start][start] = 0; rep(mask,1<<n)rep(i,n)if(mask>>i&1){ rep(j,n)if(!(mask>>j&1)){ int nmask = mask|(1<<j); dp[nmask][j] = min(dp[nmask][j], dp[mask][i]+dist[i][j]); } } rep(i,n) d[start][i] = dp[(1<<n)-1][i]; } int main(){ int n,m; cin >>n >>m; vector<vector<P>> store(n,vector<P>(2)); vector<P> factory(m); rep(i,n)rep(j,2) store[i][j].READ(); rep(i,m) factory[i].READ(); rep(i,m)rep(j,m) dist[i][j] = calc_dist(factory[i], factory[j]); rep(i,m) calc(i,m); rep(i,n)rep(j,i)rep(ii,2)rep(jj,2){ double tt = INF; rep(from,m)rep(to,m){ double tmp = calc_dist(store[i][ii], factory[from]) + d[from][to] + calc_dist(factory[to], store[j][jj]); tt = min(tt,tmp); } D[i][ii][j][jj] = tt; } auto valid = [&](double lim){ TwoSat solver(n); rep(i,n)rep(j,i)rep(ii,2)rep(jj,2){ if(D[i][ii][j][jj]>lim) solver.add_clause(i,!ii,j,!jj); } return solver.calc(); }; double l=0, r=INF; rep(_,50){ double mid=(l+r)/2; if(valid(mid)) r=mid; else l=mid; } printf("%.10f\n", r); return 0; }
[ "k0223.teru@gmail.com" ]
k0223.teru@gmail.com
ef31a662f0295d5fc961e4c0d2d368ebb5a91db6
3e748add9061e62a9f8b55a60729ebaf9cff2645
/minEASYOSD/EASYTalk.ino
5ed1d7b5d04a7aafe4299cbd5115fe7b43dbfb78
[]
no_license
pelrun/mineasyosd
99cf11d235e6835435ded87b35980700511aff49
0886efec433e082dc0d093fccd6177b3ddc6468e
refs/heads/master
2021-01-25T12:07:36.789132
2015-07-13T10:57:15
2015-07-13T10:57:15
37,831,933
1
0
null
null
null
null
UTF-8
C++
false
false
4,182
ino
/** ****************************************************************************** * * @file EASYTalk.ino * @author Joerg-D. Rothfuchs * @brief Implements a easy GPS feeded FPV OSD. * @see The GNU Public License (GPL) Version 3 * *****************************************************************************/ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see <http://www.gnu.org/licenses/> or write to the * Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifdef PROTOCOL_EASYTALK #include "EASYTalk.h" #ifdef GPS_PROTOCOL_UBX // see http://openpilot.org #include "GPS_UBX.h" #endif #ifdef GPS_PROTOCOL_NMEA // untested !!! // see http://arduiniana.org/libraries/tinygps/ #include <TinyGPS.h> TinyGPS gps; #endif //---------------------------------------------------------------------------------- // // stage 1 using a GPS at the MinimOSD // // GPS lat/lon ok // distance to home ok // altitude ok // groundspeed ok // course ok // direction to home ok // sat count ok // sat fix ok // climb rate ok // radar ok // time display ok // // // stage 2a advanced soldering solder 2 cables at Atmel 328P pin and up to 4 resistors and use voltage/current sensor // battery voltage ok 2 resistors + 1 ADC // battery current ok 2 resistors + 1 ADC // // stage 2b advanced soldering solder 1 cable at Atmel 328P pin and 2 resistors // analog RSSI ok 2 resistors + 1 ADC // //---------------------------------------------------------------------------------- int easytalk_read(void) { static uint8_t gps_seen = 0; static uint8_t crlf_count = 0; int ret = 0; // TODO implement some of the following // fake the info till available if (!osd_armed) { osd_armed = 2; osd_mode = 0; osd_roll = (int16_t) 0; osd_pitch = (int16_t) 0; osd_throttle = 0; ch_toggle = 6; osd_chan5_raw = 1100; osd_chan6_raw = 1100; osd_chan7_raw = 1100; osd_chan8_raw = 1100; } // grabbing data while (Serial.available() > 0) { uint8_t c = Serial.read(); // needed for MinimOSD char set upload if (!gps_seen && millis() < 20000 && millis() > 5000) { if (c == '\n' || c == '\r') { crlf_count++; } else { crlf_count = 0; } if (crlf_count == 3) { uploadFont(); } } #ifdef GPS_PROTOCOL_UBX if (parse_ubx(c) == PARSER_COMPLETE_SET) { gps_seen = 1; osd_fix_type = get_ubx_status(); osd_satellites_visible = get_ubx_satellites(); osd_lat = get_ubx_latitude(); osd_lon = get_ubx_longitude(); osd_alt = get_ubx_altitude(); osd_heading = get_ubx_heading(); osd_groundspeed = get_ubx_groundspeed(); osd_climb = -1.0 * get_ubx_down(); } #endif #ifdef GPS_PROTOCOL_NMEA long lat, lon; unsigned long fix_age; if (gps.encode(c)) { // process new gps info gps_seen = 1; gps.get_position(&lat, &lon, &fix_age); osd_lat = lat / 1000000.0; osd_lon = lon / 1000000.0; // osd_fix_type should be 0-1=no fix, 2=2D, 3=3D if (fix_age == TinyGPS::GPS_INVALID_AGE) // TODO temporary solution, optionally use info from GSA message (but not implemented in TinyGPS lib yet) osd_fix_type = 0; else if (fix_age > 5000) osd_fix_type = 2; else osd_fix_type = 3; osd_satellites_visible = gps.satellites(); osd_heading = gps.f_course(); osd_alt = gps.f_altitude(); osd_groundspeed = gps.f_speed_mps(); //osd_climb = 0; // TODO not implemented yet } #endif } return ret; } int easytalk_state(void) { return 1; } #endif // PROTOCOL_EASYTALK
[ "TeamRedFox001@gmail.com" ]
TeamRedFox001@gmail.com
e553574052aaa9b0748ea0353db4e8ab5d5e7b40
90f2c544bee5520a7bd1d5bb27a64ab16e6b0047
/Faky++/stream-main.cpp
b270127b281128b8bd71e0ab29e1c44dda3208fd
[]
no_license
pienjo/FakyLight
8a0b32e3f10de5508eaab123386c6e380ffb31a3
a18dec6a0f37f71f80cea09edd652700d6ac9e3c
refs/heads/master
2021-10-26T06:48:35.899910
2021-10-07T13:36:07
2021-10-07T13:36:07
153,744,234
2
0
null
null
null
null
UTF-8
C++
false
false
393
cpp
#include "RoapSource.h" #include "ProcessingRoutines.h" #include "UDPStrip.h" #include "LEDSink.h" #include "Scheduler.h" int main(void) { RoapSource source("192.168.64.5", 855905); UDPStrip strip("192.168.64.27", 5628); LEDSink sink( 28, 50, strip); sink.setGain(RGBGain{0.5f, 0.5f, 0.5}); Scheduler scheduler(source, sink); scheduler.Run(); printf("Uh-oh\n"); return 0; }
[ "martijn.van.buul@gmail.com" ]
martijn.van.buul@gmail.com