hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k โ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 โ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 โ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k โ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 โ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 โ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k โ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 โ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 โ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a1b9989269085c133ec57497dd498f406b48261b | 723 | cpp | C++ | SequenceEquation.cpp | sachanakshat/Competitive_Practice | 63170d87398bf5bd163febecdcfef8db21c632c7 | [
"MIT"
] | null | null | null | SequenceEquation.cpp | sachanakshat/Competitive_Practice | 63170d87398bf5bd163febecdcfef8db21c632c7 | [
"MIT"
] | null | null | null | SequenceEquation.cpp | sachanakshat/Competitive_Practice | 63170d87398bf5bd163febecdcfef8db21c632c7 | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
#include <vector>
#include <chrono>
#include<bits/stdc++.h>
using namespace std;
using namespace std::chrono;
// Complete the squares function below.
int squares(int a, int b) {
int n1 = ceil(sqrt(a));
int n2 = floor(sqrt(b));
return n2-n1+1;
}
int main()
{
auto start = high_resolution_clock::now();
int t,a,b,sol;
cin>>t;
for(int i = 0; i<t; i++)
{
cin>>a>>b;
sol = squares(a,b);
cout<<"\n"<<sol;
}
cout<<"\n";
auto stop = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop - start);
cout <<"\nExecution time: "<<duration.count() <<" microseconds"<<endl;
return 0;
} | 20.083333 | 74 | 0.591978 | [
"vector"
] |
a1ba01ab644ce757093ddb30fde79b1a4e9c2c9c | 624 | cpp | C++ | BashuOJ-Code/2321.cpp | magicgh/algorithm-contest-code | c21a90b11f73535c61e6363a4305b74cff24a85b | [
"MIT"
] | null | null | null | BashuOJ-Code/2321.cpp | magicgh/algorithm-contest-code | c21a90b11f73535c61e6363a4305b74cff24a85b | [
"MIT"
] | null | null | null | BashuOJ-Code/2321.cpp | magicgh/algorithm-contest-code | c21a90b11f73535c61e6363a4305b74cff24a85b | [
"MIT"
] | null | null | null | #include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstring>
#include<iomanip>
#include<algorithm>
#include<vector>
using namespace std;
inline int getint()
{
int num=0,bj=1;
char c=getchar();
while(c<'0'||c>'9')bj=(c=='-'||bj==-1)?-1:1,c=getchar();
while(c>='0'&&c<='9')num=(num<<1)+(num<<3)+c-'0',c=getchar();
return num*bj;
}
int n;
double a[105],f1[105],f2[105];
int main()
{
n=getint();
for(int i=1;i<=n;i++)scanf("%lf",&a[i]);
f1[0]=100;
for(int i=1;i<=n;i++)
{
f1[i]=max(f1[i-1],f2[i-1]/a[i]*100);
f2[i]=max(f2[i-1],f1[i-1]/100*a[i]);
}
printf("%.2lf",f1[n]);
return 0;
}
| 18.352941 | 62 | 0.581731 | [
"vector"
] |
a1ba9427a7019521551053f4bf08d7f48aace3de | 25,813 | cpp | C++ | XGF/Src/Core/GDI.cpp | kadds/XGF | 610c98a93c0f287546f97efc654b95dc846721ad | [
"MIT"
] | 5 | 2017-11-09T05:02:52.000Z | 2020-06-23T09:50:25.000Z | XGF/Src/Core/GDI.cpp | kadds/XGF | 610c98a93c0f287546f97efc654b95dc846721ad | [
"MIT"
] | null | null | null | XGF/Src/Core/GDI.cpp | kadds/XGF | 610c98a93c0f287546f97efc654b95dc846721ad | [
"MIT"
] | null | null | null | #include "../../Include/GDI.hpp"
#include "../../Include/Logger.hpp"
#include <DirectXMath.h>
#include "../../Include/Context.hpp"
namespace XGF
{
void GDI::Create()
{
mDisplayMode = DisplayMode::Windowed;
mDisplayFormat = DXGI_FORMAT_R8G8B8A8_UNORM;
XGF_Error_Check(Framework, CreateDXGIFactory1(__uuidof(IDXGIFactory1), (void**)(&mFactory1)), "CreateDXGIFactory Failed!");
XGF_Info_Check(Framework, mFactory1->QueryInterface(__uuidof(IDXGIFactory2), (void**)(&mFactory2)), "Find DXGIFactory2 Failed! Use DXGIFactory1 Now!");
PutDebugString(mFactory1);
if (mFactory2)
{
PutDebugString(mFactory2);
}
IDXGIAdapter1* dxgi_adapter = nullptr;
DXGI_ADAPTER_DESC1 dc;
int i = 0;
int j = 0;
while (mFactory1->EnumAdapters1(i, &dxgi_adapter) != DXGI_ERROR_NOT_FOUND)
{
if (dxgi_adapter != nullptr)
{
dxgi_adapter->GetDesc1(&dc);
XGF_Debug(Framework, "Adapter List", "Adpapter:", i, ",DeviceID:", dc.DeviceId, ",DedicatedSystemMemory:", (dc.DedicatedSystemMemory >> 20), "MB,DedicatedVideoMemory", (dc.DedicatedVideoMemory >> 20)
, "MB,SharedSystemMemory:", dc.SharedSystemMemory >> 20, "MB,AdapterLuid:", dc.AdapterLuid.LowPart, ",Revision:", dc.Revision, ",VendorId:", dc.VendorId
, ",SubSysId:", dc.SubSysId, ",Description:", Logger::WCharToChar((wchar_t *)dc.Description))
;
mAdapters.push_back(dxgi_adapter);
IDXGIOutput * output;
DXGI_OUTPUT_DESC desc;
j = 0;
while (dxgi_adapter->EnumOutputs(j++, &output) != DXGI_ERROR_NOT_FOUND)
{
output->GetDesc(&desc);
XGF_Debug(Framework, "OutPut:", j, ",name:", Logger::WCharToChar(desc.DeviceName));
mOutputs.push_back(output);
SaveDisplayMode(j, output);
}
}
++i;
}
if (mAdapters.empty())
{
XGF_Error(Framework, "None Adapters");
}
XGF_Warn_Check(Framework, mFactory1->MakeWindowAssociation(mTopHwnd, DXGI_MWA_NO_ALT_ENTER | DXGI_MWA_NO_WINDOW_CHANGES), "MakeWindowAssociation Error");
int flag = 0;
#ifdef _DEBUG
flag |= D3D11_CREATE_DEVICE_DEBUG;
#endif
// view https://msdn.microsoft.com/zh-cn/library/windows/apps/ff476082.aspx#code-snippet-2
D3D_FEATURE_LEVEL featureLevels[] = {
D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_10_0, };
D3D_FEATURE_LEVEL curLevel;
D3D_FEATURE_LEVEL featureLevels111[] = {
D3D_FEATURE_LEVEL_11_1
};
if (FAILED(D3D11CreateDevice(mAdapters[0], D3D_DRIVER_TYPE_UNKNOWN, 0, flag, featureLevels111, 1, D3D11_SDK_VERSION, &mD3dDevice, &curLevel, &mDeviceContext)))
{
XGF_Error_Check(Framework, D3D11CreateDevice(mAdapters[0], D3D_DRIVER_TYPE_UNKNOWN, 0, flag, featureLevels, sizeof(featureLevels) / sizeof(featureLevels[0]), D3D11_SDK_VERSION, &mD3dDevice, &curLevel, &mDeviceContext)
, "CreateDevice Error");
}
else
{
XGF_Debug(Framework, "We can use d3d11.1");
}
XGF_Warn_Check(Framework, mD3dDevice->CheckMultisampleQualityLevels(
mDisplayFormat, 4, &m4xMsaaQuality), "CheckMultisampleQualityLevels Warn");
#ifdef _DEBUG
char const *levelstr[] = { "11","10.1","10" };
for (size_t i = 0; i < sizeof(featureLevels) / sizeof(featureLevels[0]); i++)
{
if (curLevel == featureLevels[i])
{
XGF_Debug(Framework, "D3D Level:", levelstr[i]);
break;
}
}
#endif
mFeatureLevel = curLevel;
XGF_Debug(Framework, "4xMsaaQuality:", m4xMsaaQuality);
PutDebugString(mDeviceContext);
PutDebugString(mD3dDevice);
CreateSwapChain();
OnReSize(mWidth, mHeight);
}
void GDI::SaveDisplayMode(int c, IDXGIOutput * pDXGIOutput)
{
UINT num = 0;
pDXGIOutput->GetDisplayModeList(mDisplayFormat, 0, &num, 0);
DXGI_MODE_DESC * pdsk = new DXGI_MODE_DESC[num];
mScreenMode.push_back(std::make_pair(num, pdsk));
pDXGIOutput->GetDisplayModeList(mDisplayFormat, 0, &num, pdsk);
XGF_Debug(Framework, "DisplayMode has ", num);
}
void GDI::Destroy()
{
mSwapChain->SetFullscreenState(false, nullptr);
mDisplayFrameBuffer.Shutdown();
for(auto & it : mRasterizerStates.GetMap())
{
it.second.GetPtr<ID3D11RasterizerState>()->Release();
}
mRasterizerStates.GetMap().clear();
for (auto & it : mDepthStencilStates.GetMap())
{
it.second.GetPtr<ID3D11DepthStencilState>()->Release();
}
mDepthStencilStates.GetMap().clear();
for (auto & it : mBlendStates.GetMap())
{
it.second.GetPtr<ID3D11BlendState>()->Release();
}
mBlendStates.GetMap().clear();
for (auto & it : mSamplerStates.GetMap())
{
it.second.GetPtr<ID3D11SamplerState>()->Release();
}
mSamplerStates.GetMap().clear();
for (auto & it : mAdapters)
{
it->Release();
}
for (auto & it : mOutputs)
{
it->Release();
}
for (auto & it : mScreenMode)
{
delete[] it.second;
}
if (mSwapChain1)
mSwapChain1->Release();
mSwapChain1 = nullptr;
if (mSwapChain)
mSwapChain->Release();
mSwapChain = nullptr;
if (mDeviceContext)
mDeviceContext->Release();
mDeviceContext = nullptr;
if (mFactory1)
mFactory1->Release();
if (mFactory2)
mFactory2->Release();
#ifdef _DEBUG
QueryDebugInterface();
#endif
if (mD3dDevice)
mD3dDevice->Release();
mD3dDevice = nullptr;
}
void GDI::Present(bool isVsync)
{
if (!mIsStandby)
{
HRESULT hr;
if (mSwapChain1) {
DXGI_PRESENT_PARAMETERS dpp;
dpp.DirtyRectsCount = 0;
dpp.pScrollOffset = 0;
dpp.pScrollRect = nullptr;
hr = mSwapChain1->Present1(isVsync, 0, &dpp);
}
else {
hr = mSwapChain->Present(isVsync, 0);
}
if (hr == DXGI_STATUS_OCCLUDED)
{
mIsStandby = true;
XGF_Debug(Framework, "ERROR IN Present! ", "DXGI_STATUS_OCCLUDED");
ShowWindow(mHwnd, SW_MINIMIZE);
CheckFullScreenForce(false);
}
}
else
{
HRESULT hr;
hr = mSwapChain->Present(isVsync, DXGI_PRESENT_TEST);
if (hr == S_OK)
{
mIsStandby = false;
}
}
}
void GDI::Initialize(HINSTANCE instance, HWND WndHwnd, HWND TopHwnd, UINT ClientWidth, UINT ClientHeight)
{
mTopHwnd = TopHwnd;
mInstance = instance;
mHwnd = WndHwnd;
mWidth = ClientWidth;
mHeight = ClientHeight;
}
void GDI::OnReSize(UINT cx, UINT cy)
{
if (!mSwapChain1 && !mSwapChain)
return;
XGF_Debug(Framework, "SIZE Changed:", cx, ",", cy);
if (cx < 1)
cx = 1;
if (cy < 1)
cy = 1;
mDisplayFrameBuffer.Shutdown();
XGF_Error_Check(Framework, mSwapChain->ResizeBuffers(1, cx, cy, mDisplayFormat, DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH), "ResizeBuffers Error");
PutDebugString(mSwapChain);
ID3D11Texture2D* backBufferPtr;
XGF_Error_Check(Framework, mSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr), "GetSwapChainBuffer is Error");
mDisplayFrameBuffer.Initialize(backBufferPtr, DepthStencilFormat::Depth24FloatStencil8Uint);
backBufferPtr->Release();
backBufferPtr = 0;
mDisplayFrameBuffer.Bind();
mWidth = cx;
mHeight = cy;
}
void GDI::ResizeTarget(UINT x, UINT y)
{
BOOL bl;
mSwapChain->GetFullscreenState(&bl, NULL);
DXGI_MODE_DESC mode;
mode.Width = x;
mode.Height = y;
mode.Format = mDisplayFormat;
mode.RefreshRate.Numerator = 0;
mSwapChain->ResizeTarget(&mode);
}
void GDI::SetFullScreen(bool isFullscreen, int pos)
{
BOOL bl;
mSwapChain->GetFullscreenState(&bl, NULL);
if (isFullscreen && bl == FALSE)
{
GetClientRect(mHwnd, &mLastWinRc);
DXGI_MODE_DESC dxm = mScreenMode.at(0).second[pos];
dxm.Format = DXGI_FORMAT_UNKNOWN;
XGF_Info(Framework, "full screen");
XGF_Warn_Check(Framework, mSwapChain->SetFullscreenState(isFullscreen, 0), "Can't switch fullscreenState");
XGF_Warn_Check(Framework, mSwapChain->ResizeTarget(&dxm), "ResizeTarget Error");
}
else if (isFullscreen && bl == TRUE)
{
return;
}
else if (!isFullscreen && bl == TRUE)
{
mSwapChain->SetFullscreenState(isFullscreen, 0);
DXGI_MODE_DESC dxm = mScreenMode.at(0).second[0];
dxm.Width = mLastWinRc.right;
dxm.Height = mLastWinRc.bottom;
dxm.Format = mDisplayFormat;
dxm.RefreshRate.Numerator = 0;
mSwapChain->ResizeTarget(&dxm);
}
}
GpuBuffer GDI::CreateIndexBuffer(unsigned len, GpuBufferType type, void* dataAddress)
{
auto *indexList = new Index[len];
D3D11_BUFFER_DESC ibd;
ZeroMemory(&ibd, sizeof(ibd));
ibd.Usage = D3D11_USAGE_DYNAMIC;
ibd.ByteWidth = sizeof(Index) *(len);
ibd.BindFlags = D3D11_BIND_INDEX_BUFFER;
ibd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
D3D11_SUBRESOURCE_DATA iinitData;
ZeroMemory(&iinitData, sizeof(iinitData));
iinitData.pSysMem = indexList;
ID3D11Buffer * indexBuffer;
XGF_Error_Check(Render, mD3dDevice->CreateBuffer(&ibd, &iinitData, &indexBuffer), "CreateIndexBuffer Error");
//mIndexBuffer = CreateBuffer(mGDI, D3D11_BIND_INDEX_BUFFER, 0, sizeof(index) *(mMaxIndexCount * mMaxPreRenderFrameCount), 0, D3D11_USAGE_DYNAMIC, D3D11_CPU_ACCESS_WRITE);
PutDebugString(indexBuffer);
delete[] indexList;
return GpuBuffer(indexBuffer, len);
}
GpuBuffer GDI::CreateVertexBuffer(unsigned len, GpuBufferType type, void* dataAddress)
{
ID3D11Buffer * buffer;
D3D11_BUFFER_DESC vertexDesc;
if (len == 0) {
XGF_Error(Render, "content len is zero");
}
char * data = (char *)dataAddress;
if (!dataAddress)
data = new char[len];
ZeroMemory(&vertexDesc, sizeof(vertexDesc));
vertexDesc.Usage = D3D11_USAGE_DYNAMIC;
vertexDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertexDesc.ByteWidth = len;
vertexDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
D3D11_SUBRESOURCE_DATA resourceData;
ZeroMemory(&resourceData, sizeof(resourceData));
resourceData.pSysMem = data;
XGF_Error_Check(Render, mD3dDevice->CreateBuffer(&vertexDesc, &resourceData, &buffer), "CreateVertexBuffer Error");
PutDebugString((buffer));
if (!dataAddress)
delete[] data;
return GpuBuffer(buffer, len);
}
GpuBuffer GDI::CreateConstantBuffer(unsigned size)
{
XGF_ASSERT(size % 4 == 0);
ID3D11Buffer * buffer;
D3D11_BUFFER_DESC desc;
ZeroMemory(&desc, sizeof(desc));
desc.Usage = D3D11_USAGE_DYNAMIC;
desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
desc.ByteWidth = size;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
XGF_Error_Check(Render, mD3dDevice->CreateBuffer(&desc, 0, &buffer), "CreateVertexBuffer Error");
PutDebugString((buffer));
return GpuBuffer(buffer, size);
}
void* GDI::Map(GpuBuffer& gpuBuffer)
{
D3D11_MAPPED_SUBRESOURCE mappedResource;
mDeviceContext->Map(gpuBuffer.buffer, 0, D3D11_MAP_WRITE_NO_OVERWRITE, 0, &mappedResource);
return mappedResource.pData;
}
void GDI::UnMap(GpuBuffer & gpuBuffer)
{
mDeviceContext->Unmap(gpuBuffer.buffer, 0);
}
void GDI::CopyToBuffer(GpuBuffer& buffer, void* src)
{
auto * d = Map(buffer);
memcpy(d, src, buffer.size);
UnMap(buffer);
}
#ifdef _DEBUG
void GDI::QueryDebugInterface()
{
ID3D11Debug *d3dDebug;
mD3dDevice->QueryInterface(__uuidof(ID3D11Debug), reinterpret_cast<void**>(&d3dDebug));
d3dDebug->ReportLiveDeviceObjects(D3D11_RLDO_DETAIL);
d3dDebug->Release();
}
#endif
HWND GDI::GetHwnd()
{
return mHwnd;
}
HWND GDI::GetTopHwnd()
{
return mTopHwnd;
}
HINSTANCE GDI::GetInstance()
{
return mInstance;
}
bool GDI::SetDisplayMode(DisplayMode dm, int left, int top, int cx, int cy, bool move, bool isClientSize)
{
mLastMode = mDisplayMode;
mDisplayMode = dm;
if (dm == DisplayMode::Windowed)
{
SetFullScreen(false, 0);
UINT newtype = ::GetWindowLong(mHwnd, GWL_STYLE);
if (!(newtype & WS_CAPTION))
{
newtype |= (WS_CAPTION | WS_SYSMENU | WS_SIZEBOX);
::SetWindowLong(mHwnd, GWL_STYLE, newtype);
}
RECT rect = { 0,0,cx,cy };
if (!isClientSize)
{
AdjustWindowRect(&rect, newtype, FALSE);
}
SetWindowPos(mHwnd, NULL, left, top, rect.right - rect.left, rect.bottom - rect.top, SWP_NOACTIVATE | (!move ? SWP_NOMOVE | SWP_NOZORDER : SWP_NOZORDER));
ResizeTarget(rect.right - rect.left, rect.bottom - rect.top);
return true;
}
else if (dm == DisplayMode::Borderless)
{
SetFullScreen(false, 0);
UINT newtype = ::GetWindowLong(mHwnd, GWL_STYLE);
if (newtype & WS_CAPTION)
{
newtype &= ~WS_CAPTION & ~WS_SYSMENU & ~WS_SIZEBOX;
::SetWindowLong(mHwnd, GWL_STYLE, newtype);
}
RECT rect = { 0,0,cx,cy };
if (!isClientSize)
{
AdjustWindowRect(&rect, newtype, FALSE);
}
SetWindowPos(mHwnd, 0, left, top, rect.right - rect.left, rect.bottom - rect.top, SWP_NOACTIVATE | (!move ? SWP_NOMOVE | SWP_NOZORDER : SWP_NOZORDER));
ResizeTarget(rect.right - rect.left, rect.bottom - rect.top);
return true;
}
else
{
if (mScreenMode.empty()) return false;
auto var = mScreenMode[0];
for (int i = 0; i < var.first; i++)
{
DXGI_MODE_DESC * k = &var.second[i];
if (k->Height == cy && k->Width == cx
&& k->Format == mDisplayFormat && k->ScanlineOrdering == DXGI_MODE_SCANLINE_ORDER_PROGRESSIVE && k->Scaling == 0
&& k->RefreshRate.Numerator / k->RefreshRate.Denominator > 40)
{
mFullScreenSize.cx = cx;
mFullScreenSize.cy = cy;
SetFullScreen(true, i);
return true;
}
}
return false;
}
return true;
}
ID3D11ShaderResourceView * GDI::CreateRenderableTexture(unsigned width, unsigned height, DXGI_FORMAT format, char * ptrContent, int pitch, int slicePitch)
{
char * ptr = ptrContent;
if (!ptr)
{
ptr = new char[width * height];
memset(ptr, 0, width * height * sizeof(char));
}
ID3D11Texture2D * texutre;
D3D11_SUBRESOURCE_DATA __subData;
__subData.pSysMem = ptr;
__subData.SysMemPitch = pitch;
__subData.SysMemSlicePitch = slicePitch;
D3D11_TEXTURE2D_DESC texture2d;
texture2d.Width = width;
texture2d.Height = height;
texture2d.MipLevels = 1;
texture2d.ArraySize = 1;
texture2d.SampleDesc.Count = 1;
texture2d.SampleDesc.Quality = 0;
texture2d.Usage = D3D11_USAGE_DEFAULT;
texture2d.Format = format;
texture2d.BindFlags = D3D11_BIND_SHADER_RESOURCE;
texture2d.CPUAccessFlags = 0;
texture2d.MiscFlags = 0;
XGF_Error_Check(Application, GetDevice()->CreateTexture2D(&texture2d, &__subData, &texutre), "CreateTexture2D at font class failed");
PutDebugString(texutre);
D3D11_SHADER_RESOURCE_VIEW_DESC viewDesc;
viewDesc.Format = texture2d.Format;
viewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
viewDesc.Texture2D.MipLevels = texture2d.MipLevels;
viewDesc.Texture2D.MostDetailedMip = 0;
ID3D11ShaderResourceView * srv;
XGF_Error_Check(Application, GetDevice()->CreateShaderResourceView(texutre, &viewDesc, &srv), "Create font SRV failed");
PutDebugString(srv);
if (!ptrContent)
{
delete[] ptr;
}
texutre->Release();
return srv;
}
void GDI::CheckFullScreenForce(bool isforce)
{
BOOL bl;
mSwapChain->GetFullscreenState(&bl, NULL);
if (isforce)
{
if (bl == FALSE && mDisplayMode == DisplayMode::FullScreen)
{
SetDisplayMode(DisplayMode::FullScreen, 0, 0, mFullScreenSize.cx, mFullScreenSize.cy, true);
}
}
else
{
if (mDisplayMode == DisplayMode::FullScreen)
{
SetDisplayMode(mLastMode, mLastWinRc.left, mLastWinRc.top, mLastWinRc.right, mLastWinRc.bottom, true, true);
mDisplayMode = DisplayMode::FullScreen;
}
}
}
void CopyBlendStateToDesc(D3D11_RENDER_TARGET_BLEND_DESC & desc, const BlendStateTarget & target)
{
desc.BlendEnable = target.GetBlendEnable();
desc.BlendOp = (D3D11_BLEND_OP) target.GetBlendOp();
desc.BlendOpAlpha = (D3D11_BLEND_OP)target.GetBlendOpAlpha();
desc.DestBlend = (D3D11_BLEND)target.GetDestBlend();
desc.DestBlendAlpha = (D3D11_BLEND)target.GetDestBlendAlpha();
desc.RenderTargetWriteMask = target.GetRenderTargetWriteMask();
desc.SrcBlend = (D3D11_BLEND)target.GetSrcBlend();
desc.SrcBlendAlpha = (D3D11_BLEND)target.GetSrcBlendAlpha();
}
RawBlendState GDI::CreateBlendState(const BlendState& bs)
{
D3D11_BLEND_DESC blendDesc;
blendDesc.AlphaToCoverageEnable = bs.GetAlphaToCoverageEnable();
blendDesc.IndependentBlendEnable = bs.GetIndependentBlendEnable();
CopyBlendStateToDesc(blendDesc.RenderTarget[0], bs.GetRenderTarget(0));
if(bs.GetIndependentBlendEnable())
{
const size_t c = bs.GetRenderTargetCount();
for(size_t i = 1; i < c; i++)
{
CopyBlendStateToDesc(blendDesc.RenderTarget[i], bs.GetRenderTarget(i));
}
}
ID3D11BlendState * state;
mD3dDevice->CreateBlendState(&blendDesc, &state);
PutDebugString(state);
return RawBlendState(state);
}
RawBlendState GDI::GetBlendState(const BlendState& bs)
{
auto s = mBlendStates.GetRawState(bs);
if (s.has_value())
{
return s.value();
}
auto rawBS = CreateBlendState(bs);
mBlendStates.SaveRawState(bs, rawBS);
return rawBS;
}
RawDepthStencilState GDI::CreateDepthStencilState(const DepthStencilState& ds)
{
D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
depthStencilDesc.DepthEnable = ds.GetDepthEnable();
depthStencilDesc.DepthWriteMask = (D3D11_DEPTH_WRITE_MASK) ds.GetDepthWriteMask();
depthStencilDesc.DepthFunc = (D3D11_COMPARISON_FUNC) ds.GetDepthFunc();
depthStencilDesc.StencilEnable = ds.GetStencilEnable();
depthStencilDesc.StencilReadMask = ds.GetStencilReadMask();
depthStencilDesc.StencilWriteMask = ds.GetStencilWriteMask();
depthStencilDesc.FrontFace.StencilFailOp = (D3D11_STENCIL_OP)ds.GetFrontFaceStencilFailOp();
depthStencilDesc.FrontFace.StencilDepthFailOp = (D3D11_STENCIL_OP) ds.GetFrontFaceStencilDepthFailOp();
depthStencilDesc.FrontFace.StencilPassOp = (D3D11_STENCIL_OP)ds.GetFrontFaceStencilPassOp();
depthStencilDesc.FrontFace.StencilFunc = (D3D11_COMPARISON_FUNC) ds.GetFrontFaceStencilFunc();
depthStencilDesc.BackFace.StencilFailOp = (D3D11_STENCIL_OP)ds.GetBackFaceStencilFailOp();
depthStencilDesc.BackFace.StencilDepthFailOp = (D3D11_STENCIL_OP)ds.GetBackFaceStencilDepthFailOp();
depthStencilDesc.BackFace.StencilPassOp = (D3D11_STENCIL_OP)ds.GetBackFaceStencilPassOp();
depthStencilDesc.BackFace.StencilFunc = (D3D11_COMPARISON_FUNC)ds.GetBackFaceStencilFunc();
ID3D11DepthStencilState * state;
XGF_Error_Check(Framework, mD3dDevice->CreateDepthStencilState(&depthStencilDesc, &state), "CreateDepthStencilState Error");
PutDebugString(state);
return RawDepthStencilState(state);
}
RawDepthStencilState GDI::GetDepthStencilState(const DepthStencilState& ds)
{
auto s = mDepthStencilStates.GetRawState(ds);
if (s.has_value())
{
return s.value();
}
auto rawDS = CreateDepthStencilState(ds);
mDepthStencilStates.SaveRawState(ds, rawDS);
return rawDS;
}
RawRasterizerState GDI::CreateRasterizerState(const RasterizerState& rs)
{
D3D11_RASTERIZER_DESC rasterDesc;
rasterDesc.AntialiasedLineEnable = rs.GetAntialiasedLineEnable();
rasterDesc.CullMode = (D3D11_CULL_MODE)rs.GetCullMode();
rasterDesc.DepthBias = rs.GetDepthBias();
rasterDesc.DepthBiasClamp = rs.GetDepthBiasClamp();
rasterDesc.DepthClipEnable = rs.GetDepthClipEnable();
rasterDesc.FillMode = (D3D11_FILL_MODE)rs.GetFillMode();
rasterDesc.FrontCounterClockwise = rs.GetFrontCounterClockwise();
rasterDesc.MultisampleEnable = rs.GetMultisampleEnable();
rasterDesc.ScissorEnable = rs.GetScissorEnable();
rasterDesc.SlopeScaledDepthBias = rs.GetSlopeScaledDepthBias();
ID3D11RasterizerState * state;
XGF_Error_Check(Framework, mD3dDevice->CreateRasterizerState(&rasterDesc, &state), "CreateRasterizerState Error");
PutDebugString(state);
return RawRasterizerState(state);
}
RawRasterizerState GDI::GetRasterizerState(const RasterizerState& rs)
{
auto s = mRasterizerStates.GetRawState(rs);
if (s.has_value())
{
return s.value();
}
auto rawRS = CreateRasterizerState(rs);
mRasterizerStates.SaveRawState(rs, rawRS);
return rawRS;
}
RawSamplerState GDI::CreateSamplerState(const SamplerState & s)
{
D3D11_SAMPLER_DESC samplerDesc;
samplerDesc.Filter = (D3D11_FILTER)s.GetFilter();
samplerDesc.AddressU = (D3D11_TEXTURE_ADDRESS_MODE)s.GetAddressU();
samplerDesc.AddressV = (D3D11_TEXTURE_ADDRESS_MODE)s.GetAddressV();
samplerDesc.AddressW = (D3D11_TEXTURE_ADDRESS_MODE)s.GetAddressW();
samplerDesc.MipLODBias = s.GetMipLODBias();
samplerDesc.MaxAnisotropy = s.GetMaxAnisotropy();
samplerDesc.ComparisonFunc = (D3D11_COMPARISON_FUNC)s.GetComparisonFunc();
samplerDesc.BorderColor[0] = s.GetBorderColor().x;
samplerDesc.BorderColor[1] = s.GetBorderColor().y;
samplerDesc.BorderColor[2] = s.GetBorderColor().z;
samplerDesc.BorderColor[3] = s.GetBorderColor().w;
samplerDesc.MinLOD = s.GetMinLOD();
samplerDesc.MaxLOD = s.GetMaxLOD();
ID3D11SamplerState* state;
GetDevice()->CreateSamplerState(&samplerDesc, &state);
PutDebugString(state);
return RawSamplerState(state);
}
RawSamplerState GDI::GetSamplerState(const SamplerState & ss)
{
auto s = mSamplerStates.GetRawState(ss);
if(s.has_value())
{
return s.value();
}
auto rawSS = CreateSamplerState(ss);
mSamplerStates.SaveRawState(ss, rawSS);
return rawSS;
}
D3D_FEATURE_LEVEL GDI::CheckFeatureLevel()
{
return mFeatureLevel;
}
void GDI::SetBlendState(RawBlendState bb)
{
float factor[] = { 0,0,0,0,0,0 };
mDeviceContext->OMSetBlendState(bb.GetPtr<ID3D11BlendState>(), factor, 0xffffffff);
}
void GDI::SetDepthStencilState(RawDepthStencilState ds)
{
mDeviceContext->OMSetDepthStencilState(ds.GetPtr<ID3D11DepthStencilState>(), 0);
}
void GDI::SetRasterizerState(RawRasterizerState rs)
{
mDeviceContext->RSSetState(rs.GetPtr<ID3D11RasterizerState>());
}
void GDI::CreateSwapChain()
{
if (mFactory2) {
DXGI_SWAP_CHAIN_DESC1 sd;
ZeroMemory(&sd, sizeof(sd));
sd.Width = mWidth;
sd.Height = mHeight;
sd.Format = mDisplayFormat;
sd.Stereo = FALSE;
sd.Scaling = DXGI_SCALING_STRETCH;
if (mEnable4xMsaa && m4xMsaaQuality > 0)
{
sd.SampleDesc.Count = 4;
sd.SampleDesc.Quality = m4xMsaaQuality - 1;
}
else
{
sd.SampleDesc.Count = 1;
sd.SampleDesc.Quality = 0;
}
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.BufferCount = 1;
sd.AlphaMode = DXGI_ALPHA_MODE::DXGI_ALPHA_MODE_UNSPECIFIED;
sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
XGF_Error_Check(Framework, mFactory2->CreateSwapChainForHwnd(mD3dDevice, mHwnd, &sd, NULL, NULL, &mSwapChain1), "CreateSwapChain Error?? ");
PutDebugString(mSwapChain1);
XGF_Error_Check(Framework, mSwapChain1->QueryInterface(__uuidof(IDXGISwapChain), (void**)(&mSwapChain)), "Find SwapChain Failed!");
PutDebugString(mSwapChain);
XGF_Debug(Framework, "The swapChain1 and swapChain are created from IDXGIFactory2");
}
else { // CreateSwapChainFromFactory1
DXGI_SWAP_CHAIN_DESC sd;
ZeroMemory(&sd, sizeof(sd));
sd.OutputWindow = mHwnd;
sd.Windowed = TRUE;
sd.BufferDesc.Format = mDisplayFormat;
sd.BufferDesc.Width = mWidth;
sd.BufferDesc.Height = mHeight;
sd.BufferDesc.Scaling = DXGI_MODE_SCALING::DXGI_MODE_SCALING_STRETCHED;
sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER::DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.BufferDesc.RefreshRate.Denominator = 1;
sd.BufferDesc.RefreshRate.Numerator = 60;
if (mEnable4xMsaa && m4xMsaaQuality > 0)
{
sd.SampleDesc.Count = 4;
sd.SampleDesc.Quality = m4xMsaaQuality - 1;
}
else
{
sd.SampleDesc.Count = 1;
sd.SampleDesc.Quality = 0;
}
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.BufferCount = 1;
sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
XGF_Error_Check(Framework, mFactory1->CreateSwapChain(mD3dDevice, &sd, &mSwapChain), "CreateSwapChain Error?? ");
PutDebugString(mSwapChain);
XGF_Debug(Framework, "A swapChain is created from IDXGIFactory1");
}
}
void GDI::ReCreateSwapChain()
{
BOOL bl;
IDXGIOutput * output;
mSwapChain->GetFullscreenState(&bl, &output);
mSwapChain->SetFullscreenState(false, nullptr);
if (mSwapChain1)
{
mSwapChain1->Release();
}
if (mSwapChain)
{
mSwapChain->Release();
}
CreateSwapChain();
// TODO: Fullscreen logic
SetFullScreen(bl, 0);
}
void GDI::Able4xMsaa()
{
if (!mEnable4xMsaa)
{
mEnable4xMsaa = true;
ReCreateSwapChain();
}
}
void GDI::Disable4xMsaa()
{
if (mEnable4xMsaa)
{
mEnable4xMsaa = false;
ReCreateSwapChain();
}
}
bool GDI::IsEnable4xMsaa() const
{
return mEnable4xMsaa;
}
int GDI::Query4xMsaaQuality() const
{
return m4xMsaaQuality;
}
bool GDI::CanEnable4xMsaa() const
{
return m4xMsaaQuality > 0;
}
bool GDI::IsDisplayMode(DisplayMode displayMode) const
{
return mDisplayMode == displayMode;
}
void GDI::SetViewPorts(const ViewPort* viewports, unsigned int count)
{
if (count == 0)
{
SetFullViewPort();
}
else
{
if (mViewports.size() == count)
{
for (int i = 0; i < count; i++)
{
if (mViewports[i] != viewports[i])
{
goto set;
}
}
return;
}
set:
mDeviceContext->RSSetViewports(count, (const D3D11_VIEWPORT*)viewports);
mViewports.resize(count);
for (int i = 0; i < count; i++)
{
mViewports[i] = viewports[i];
}
}
}
void GDI::SetFullViewPort(int cx, int cy)
{
if (cx <= -1)
cx = GetWidth();
if (cy <= -1)
cy = GetHeight();
mViewports = std::vector<ViewPort>(1);
mViewports[0] = { 0.f, 0.f, (float)cx, (float)cy, 0.f, 1.f };;
mDeviceContext->RSSetViewports((UINT)mViewports.size(), (const D3D11_VIEWPORT*)mViewports.data());
}
void GDI::SetScissorRectangle(const Rect * rects, unsigned int count)
{
if (mScissorRects.size() == count)
{
for (int i = 0; i < count; i++)
{
if (mScissorRects[i] != rects[i])
{
goto set;
}
}
return;
}
set:
mDeviceContext->RSSetScissorRects(count, (const D3D11_RECT*)rects);
mScissorRects.resize(count);
for (int i = 0; i < count; i++)
{
mScissorRects[i] = rects[i];
}
}
}
| 28.617517 | 220 | 0.716616 | [
"render",
"vector"
] |
a1bd22c107e7e4a10751e8d1e6a7cf7e18844432 | 10,798 | cpp | C++ | weex_core/Source/core/api/WeexJSCoreApi.cpp | zhhao226/incubator-weex | 6ba255365a12b5c41422ce0a48f1f5d2a5f96207 | [
"Apache-2.0"
] | null | null | null | weex_core/Source/core/api/WeexJSCoreApi.cpp | zhhao226/incubator-weex | 6ba255365a12b5c41422ce0a48f1f5d2a5f96207 | [
"Apache-2.0"
] | null | null | null | weex_core/Source/core/api/WeexJSCoreApi.cpp | zhhao226/incubator-weex | 6ba255365a12b5c41422ce0a48f1f5d2a5f96207 | [
"Apache-2.0"
] | null | null | null | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
//
// Created by Darin on 13/02/2018.
//
#include "WeexJSCoreApi.h"
#include <android/bridge/impl/bridge_impl_android.h>
#include <core/render/manager/render_manager.h>
#include <android/jsengine/multiprocess/ExtendJSApi.h>
#include <android/base/string/string_utils.h>
#include <wson/wson_parser.h>
using namespace WeexCore;
extern WeexCore::FunType gCanvasFunc;
extern WeexCore::FunTypeT3d t3dFunc;
void _setJSVersion(const char *jsVersion) {
LOGA("init JSFrm version %s", jsVersion);
Bridge_Impl_Android::getInstance()->setJSVersion(jsVersion);
}
void _reportException(const char *pageId, const char *func, const char *exception_string) {
Bridge_Impl_Android::getInstance()->reportException(pageId, func, exception_string);
}
void _callNative(const char *pageId, const char *task, const char *callback) {
if (pageId == nullptr || task == nullptr)
return;
#if JSAPI_LOG
LOGD("[ExtendJSApi] handleCallNative >>>> pageId: %s, task: %s", pageId, task);
#endif
if (strcmp(task, "[{\"module\":\"dom\",\"method\":\"createFinish\",\"args\":[]}]") == 0) {
RenderManager::GetInstance()->CreateFinish(pageId) ? 0 : -1;
} else {
Bridge_Impl_Android::getInstance()->callNative(pageId, task, callback);
}
};
std::unique_ptr<IPCResult>
_callNativeModule(const char *pageId, const char *module, const char *method,
const char *arguments, int argumentsLength, const char *options, int optionsLength) {
std::unique_ptr<IPCResult> ret = createInt32Result(-1);
if (pageId != nullptr && module != nullptr && method != nullptr) {
#if JSAPI_LOG
LOGD("[ExtendJSApi] handleCallNativeModule >>>> pageId: %s, module: %s, method: %s, arg: %s, opt: %s",
pageId, module, method, argString, optString);
#endif
// add for android support
jobject result;
result = static_cast<jobject>(Bridge_Impl_Android::getInstance()->callNativeModule(pageId, module, method,
arguments, argumentsLength, options, optionsLength));
if (result == nullptr){
return ret;
}
JNIEnv *env = getJNIEnv();
jfieldID jTypeId = env->GetFieldID(jWXJSObject, "type", "I");
jint jTypeInt = env->GetIntField(result, jTypeId);
jfieldID jDataId = env->GetFieldID(jWXJSObject, "data", "Ljava/lang/Object;");
jobject jDataObj = env->GetObjectField(result, jDataId);
if (jTypeInt == 1) {
if (jDoubleValueMethodId == NULL) {
jclass jDoubleClazz = env->FindClass("java/lang/Double");
jDoubleValueMethodId = env->GetMethodID(jDoubleClazz, "doubleValue", "()D");
env->DeleteLocalRef(jDoubleClazz);
}
jdouble jDoubleObj = env->CallDoubleMethod(jDataObj, jDoubleValueMethodId);
ret = std::move(createDoubleResult(jDoubleObj));
} else if (jTypeInt == 2) {
jstring jDataStr = (jstring) jDataObj;
ret = std::move(createStringResult(env, jDataStr));
} else if (jTypeInt == 3) {
jstring jDataStr = (jstring) jDataObj;
ret = std::move(createJSONStringResult(env, jDataStr));
} else if (jTypeInt == 4) {
jbyteArray array = (jbyteArray)jDataObj;
if(array != nullptr){
int length = env->GetArrayLength(array);
void* data = env->GetByteArrayElements(array, 0);
ret = std::move(createByteArrayResult((const char*)data, length));
env->ReleaseByteArrayElements(array, (jbyte*)data, 0);
}
}
env->DeleteLocalRef(jDataObj);
if(result != nullptr){
env->DeleteLocalRef(result);
}
}
return ret;
}
void _callNativeComponent(const char *pageId, const char *ref, const char *method,
const char *arguments, int argumentsLength, const char *options, int optionsLength) {
if (pageId != nullptr && ref != nullptr && method != nullptr) {
#if JSAPI_LOG
LOGD("[ExtendJSApi] handleCallNativeComponent >>>> pageId: %s, ref: %s, method: %s, arg: %s, opt: %s",
pageId, ref, method, argString, optString);
#endif
Bridge_Impl_Android::getInstance()->callNativeComponent(pageId, ref, method,
arguments, argumentsLength, options, optionsLength);
}
}
void _callAddElement(const char *pageId, const char *parentRef, const char *domStr,
const char *index_cstr) {
const char *indexChar = index_cstr == nullptr ? "\0" : index_cstr;
int index = atoi(indexChar);
if (pageId == nullptr || parentRef == nullptr || domStr == nullptr || index < -1)
return;
#if JSAPI_LOG
std::string log = "";
log.append("pageId: ").append(pageId).append(", parentRef: ").append(parentRef).append(", domStr: ").append(domStr);
int log_index = 0;
int maxLength = 800;
std::string sub;
while (log_index < log.length()) {
if (log.length() <= log_index + maxLength) {
sub = log.substr(log_index);
} else {
sub = log.substr(log_index, maxLength);
}
if (log_index == 0)
LOGD("[ExtendJSApi] functionCallAddElement >>>> %s", sub.c_str());
else
LOGD(" [ExtendJSApi] functionCallAddElement >>>> %s", sub.c_str());
log_index += maxLength;
}
#endif
RenderManager::GetInstance()->AddRenderObject(pageId, parentRef, index, domStr);
}
void _setTimeout(const char *callbackId, const char *time) {
Bridge_Impl_Android::getInstance()->setTimeout(callbackId, time);
}
void _callNativeLog(const char *str_array) {
Bridge_Impl_Android::getInstance()->callNativeLog(str_array);
}
void _callCreateBody(const char *pageId, const char *domStr) {
#if JSAPI_LOG
LOGD("[ExtendJSApi] functionCallCreateBody >>>> pageId: %s, domStr: %s", pageId, domStr);
#endif
RenderManager::GetInstance()->CreatePage(pageId, domStr) ? 0 : -1;
}
int _callUpdateFinish(const char *pageId, const char *task, const char *callback) {
return Bridge_Impl_Android::getInstance()->callUpdateFinish(pageId, task, callback);
}
void _callCreateFinish(const char *pageId) {
#if JSAPI_LOG
LOGD("[ExtendJSApi] functionCallCreateFinish >>>> pageId: %s", pageId);
#endif
RenderManager::GetInstance()->CreateFinish(pageId);
}
int _callRefreshFinish(const char *pageId, const char *task, const char *callback) {
if (pageId == nullptr)
return -1;
return Bridge_Impl_Android::getInstance()->callRefreshFinish(pageId, task, callback);
}
void _callUpdateAttrs(const char *pageId, const char *ref, const char *data) {
#if JSAPI_LOG
LOGD("[ExtendJSApi] functionCallUpdateAttrs >>>> pageId: %s, ref: %s, data: %s", pageId,
ref, data);
#endif
RenderManager::GetInstance()->UpdateAttr(pageId, ref, data);
}
void _callUpdateStyle(const char *pageId, const char *ref, const char *data) {
#if JSAPI_LOG
LOGD("[ExtendJSApi] functionCallUpdateStyle >>>> pageId: %s, ref: %s, data: %s", pageId,
ref, data);
#endif
RenderManager::GetInstance()->UpdateStyle(pageId, ref, data);
}
void _callRemoveElement(const char *pageId, const char *ref) {
#if JSAPI_LOG
LOGD("[ExtendJSApi] functionCallRemoveElement >>>> pageId: %s, ref: %s", pageId,
ref);
#endif
RenderManager::GetInstance()->RemoveRenderObject(pageId, ref);
}
void _callMoveElement(const char *pageId, const char *ref, const char *parentRef, int index) {
#if JSAPI_LOG
LOGD("[ExtendJSApi] functionCallRemoveElement >>>> pageId: %s, ref: %s, parentRef: %s, index: %d",
pageId, ref, parentRef, index);
#endif
RenderManager::GetInstance()->MoveRenderObject(pageId, ref, parentRef, index);
}
void _callAddEvent(const char *pageId, const char *ref, const char *event) {
#if JSAPI_LOG
LOGD("[ExtendJSApi] functionCallAddEvent >>>> pageId: %s, ref: %s, event: %s", pageId,
ref, event);
#endif
RenderManager::GetInstance()->AddEvent(pageId, ref, event);
}
void _callRemoveEvent(const char *pageId, const char *ref, const char *event) {
#if JSAPI_LOG
LOGD("[ExtendJSApi] functionCallRemoveEvent >>>> pageId: %s, ref: %s, event: %s", pageId,
ref, event);
#endif
RenderManager::GetInstance()->RemoveEvent(pageId, ref, event);
}
int _setInterval(const char *pageId, const char *callbackId, const char *_time) {
return (atoi(pageId) << 16) | (atoi(callbackId));
}
void _clearInterval(const char *pageId, const char *callbackId) {
return;
}
const char *_callGCanvasLinkNative(const char *pageId, int type, const char *args) {
const char *retVal = NULL;
if (gCanvasFunc) {
retVal = callGCanvasFun(gCanvasFunc, pageId, type, args);
}
return retVal;
}
const char *_t3dLinkNative(int type, const char *args) {
const char *retVal = NULL;
if (t3dFunc) {
retVal = WeexCore::weexCallT3dFunc(t3dFunc, type, args);
}
return retVal;
}
void callHandlePostMessage(const char *vimId, const char *data) {
JNIEnv *pEnv = getJNIEnv();
jstring pJstring = pEnv->NewStringUTF(vimId);
jbyteArray pArray = newJByteArray(pEnv, data);
Bridge_Impl_Android::getInstance()->handlePostMessage(pJstring, pArray);
pEnv->DeleteLocalRef(pJstring);
pEnv->DeleteLocalRef(pArray);
}
void
callDIspatchMessage(const char *clientId, const char *data, const char *callback,
const char *vmId) {
JNIEnv *pEnv = getJNIEnv();
jstring pClientId = newJString(pEnv, clientId);
jbyteArray pArray = newJByteArray(pEnv, data);
jstring pCallback = newJString(pEnv, callback);
jstring pVmId = newJString(pEnv, vmId);
Bridge_Impl_Android::getInstance()->handleDispatchMessage(pClientId, pVmId, pArray, pCallback);
pEnv->DeleteLocalRef(pClientId);
pEnv->DeleteLocalRef(pArray);
pEnv->DeleteLocalRef(pCallback);
pEnv->DeleteLocalRef(pVmId);
}
| 35.519737 | 144 | 0.660493 | [
"render",
"object"
] |
a1bed247e7a124de7bc27f827c58f8c6ff304549 | 10,203 | cpp | C++ | third_party/geogram/src/examples/graphics/demo_Raytrace/main.cpp | ringmesh/RINGMesh | 82a0a0fb0a119492c6747265de6ec24006c4741f | [
"BSD-3-Clause"
] | 74 | 2017-10-26T15:40:23.000Z | 2022-03-22T09:27:39.000Z | third_party/geogram/src/examples/graphics/demo_Raytrace/main.cpp | ringmesh/ringmesh | 82a0a0fb0a119492c6747265de6ec24006c4741f | [
"BSD-3-Clause"
] | 45 | 2017-10-26T15:54:01.000Z | 2021-01-27T10:16:34.000Z | third_party/geogram/src/examples/graphics/demo_Raytrace/main.cpp | ringmesh/ringmesh | 82a0a0fb0a119492c6747265de6ec24006c4741f | [
"BSD-3-Clause"
] | 17 | 2018-03-27T11:31:24.000Z | 2022-03-06T18:41:52.000Z | /*
* Copyright (c) 2012-2014, Bruno Levy All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the ALICE Project-Team nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* If you modify this software, you should include a notice giving the
* name of the person performing the modification, the date of modification,
* and the reason for such modification.
*
* Contact: Bruno Levy
*
* Bruno.Levy@inria.fr
* http://www.loria.fr/~levy
*
* ALICE Project
* LORIA, INRIA Lorraine,
* Campus Scientifique, BP 239
* 54506 VANDOEUVRE LES NANCY CEDEX
* FRANCE
*
*/
/*
* GEOGRAM example program:
* simple mesh raytracing using AABB tree.
* GUI version of geogram/simple_raytrace
* disclaimer: not the fastest, lighting model is ridiculous, there is no
* antialiasing etc... (just a demo program for the mesh AABB class).
* mouse interaction is nearly unusable...
* usage: geogram_demo_Raytrace
* geogram_demo_Raytrace meshfile.(obj|ply|mesh|...)
*/
#include <geogram_gfx/glup_viewer/glup_viewer.h>
#define RAYTRACE_GUI
#include "../../geogram/simple_raytrace/raytracing.h"
namespace {
using namespace GEO;
/**
* \brief An application that demonstrates both
* GLUP primitives and glup_viewer application
* framework.
*/
class DemoRaytraceApplication : public Application {
public:
/**
* \brief DemoRaytraceApplication constructor.
*/
DemoRaytraceApplication(
int argc, char** argv,
const std::string& usage
) :
Application(argc, argv, usage),
camera_(
vec3(2.0, 2.0, 1.5), // Position
vec3(0.5, 0.5, 0.5), // Target
#ifdef GEO_OS_EMSCRIPTEN
512, 512, // OpenGL ES needs power of two textures
#else
800, 800, // Image size
#endif
50.0 // zoom angle (in degrees)
)
{
texture_ = 0;
scene_.add_object(new HorizontalCheckerboardPlane(0.0)) // The tradition !
->rename("Checkerboard");
scene_.add_object( // A sphere
new Sphere(vec3(-0.7, -0.7, 1.0),0.7)
)->set_reflection_coefficient(vec3(0.8, 0.8, 0.8))
->set_diffuse_coefficient(vec3(0.2, 0.2, 0.2))
->rename("Sphere 1");
scene_.add_object( // Another sphere
new Sphere(vec3( 0.0, 0.0, 0.0),0.25)
)->set_diffuse_coefficient(vec3(0.0, 1.0, 0.5))
->rename("Sphere 2");
// Let there be (two) lights !
scene_.add_object(new Light(
vec3(0.5, 1.3, 0.5), // Position
0.02, // Radius
vec3(0.0, 0.5, 1.0) // Color
)
)->rename("Light 1");
scene_.add_object(new Light(
vec3(1.0, 0.2, 1.0), // Position
0.02, // Radius
vec3(1.5, 1.5, 0.5) // Color
)
)->rename("Light 2");
scene_changed_ = true;
zoom_ = 0.0f;
left_pane_visible_ = false;
background_color_1_ = vec4f(0.0f, 0.0f, 0.2f, 1.0f);
background_color_2_ = vec4f(0.0f, 0.0f, 0.2f, 1.0f);
for(index_t i=0; i<4; ++i) {
quaternion_[i] = 0.0f;
}
for(index_t i=0; i<3; ++i) {
translation_[i] = 0.0f;
}
}
/**
* \brief DemoRaytraceApplication destructor.
*/
~DemoRaytraceApplication() override {
if(texture_ != 0) {
glDeleteTextures(1,&texture_);
}
}
void update() {
float* new_quaternion = glup_viewer_get_scene_quaternion();
for(index_t i=0; i<4; ++i) {
if(new_quaternion[i] != quaternion_[i]) {
scene_changed_ = true;
quaternion_[i] = new_quaternion[i];
}
}
float* new_translation = glup_viewer_get_scene_translation();
for(index_t i=0; i<3; ++i) {
if(new_translation[i] != translation_[i]) {
scene_changed_ = true;
translation_[i] = new_translation[i];
}
}
float new_zoom = glup_viewer_get_float(GLUP_VIEWER_ZOOM);
if(new_zoom != zoom_) {
scene_changed_ = true;
zoom_ = new_zoom;
}
if(scene_changed_) {
vec3 pos(2.0, 2.0, 1.5);
mat4 M;
set_mat4_from_translation_and_quaternion(
M,
double(translation_[0]),
double(translation_[1]),
double(translation_[2]),
double(quaternion_[2]),
double(quaternion_[0]),
double(quaternion_[1]),
double(quaternion_[3])
);
//M = M.inverse();
pos = transform_point(pos,M);
vec3 target(
0.5 + double(translation_[0]),
0.5 + double(translation_[1]),
0.5 + double(translation_[2])
);
camera_.update(
pos, target, 50.0 / double(zoom_)
);
#ifdef GEO_OPENMP
#pragma omp parallel for
#endif
for(index_t Y=0; Y<camera_.image_height(); ++Y) {
for(index_t X=0; X<camera_.image_width(); ++X) {
Ray R = camera_.launch_ray(X,Y);
vec3 K = scene_.raytrace(R);
camera_.set_pixel(X,Y,K);
}
}
}
if(scene_changed_ && texture_ != 0) {
glTexImage2D(
GL_TEXTURE_2D,
0,
GL_RGB,
GLsizei(camera_.image_width()),
GLsizei(camera_.image_height()),
0,
GL_RGB,
GL_UNSIGNED_BYTE,
camera_.image_data()
);
}
scene_changed_ = false;
}
/**
* \brief Displays and handles the GUI for object properties.
* \details Overloads Application::draw_object_properties().
*/
void draw_object_properties() override {
if(ImGui::Button("Home",ImVec2(-1.0f, 0.0f))) {
glup_viewer_home();
zoom_ = 40.0;
scene_changed_ = true;
}
if(scene_.draw_gui()) {
scene_changed_ = true;
}
update();
}
/**
* \brief Draws the scene according to currently set primitive and
* drawing modes.
*/
void draw_scene() override {
update();
glupMatrixMode(GLUP_PROJECTION_MATRIX);
glupLoadIdentity();
glupMatrixMode(GLUP_MODELVIEW_MATRIX);
glupLoadIdentity();
int w,h;
glup_viewer_get_screen_size(&w,&h);
glupScalef(2.0f*float(h)/float(w), 2.0f, 1.0f);
glupTranslatef(-0.5f, -0.5f, 0.0f);
glupEnable(GLUP_TEXTURING);
glupDisable(GLUP_LIGHTING);
glActiveTexture(GL_TEXTURE0 + GLUP_TEXTURE_2D_UNIT);
glBindTexture(GL_TEXTURE_2D, texture_);
glupBegin(GLUP_QUADS);
glupTexCoord2d(0.0, 0.0);
glupVertex2d(0.0, 1.0);
glupTexCoord2d(1.0, 0.0);
glupVertex2d(1.0, 1.0);
glupTexCoord2d(1.0, 1.0);
glupVertex2d(1.0, 0.0);
glupTexCoord2d(0.0, 1.0);
glupVertex2d(0.0, 0.0);
glupEnd();
glupDisable(GLUP_TEXTURING);
}
/**
* \brief Creates the texture.
* \details This function overloads Application::init_graphics(). It
* is called as soon as the OpenGL context is ready for rendering. It
* is meant to initialize the graphic objects used by the application.
*/
void init_graphics() override {
Application::init_graphics();
// Create the texture and initialize its texturing modes
glGenTextures(1, &texture_);
glActiveTexture(GL_TEXTURE0 + GLUP_TEXTURE_2D_UNIT);
glBindTexture(GL_TEXTURE_2D, texture_);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glupTextureType(GLUP_TEXTURE_2D);
glupTextureMode(GLUP_TEXTURE_REPLACE);
}
bool load(const std::string& filename) override {
mesh_load(filename, mesh_);
normalize_mesh(mesh_);
scene_.add_object(new MeshObject(mesh_));
scene_changed_ = true;
return true;
}
void draw_application_menus() override {
if(ImGui::BeginMenu("New...")) {
if(ImGui::MenuItem("Sphere")) {
scene_.add_object(
new Sphere(vec3(0.5, 0.5, 0.5),0.25)
)->set_diffuse_coefficient(random_color());
scene_changed_ = true;
}
if(ImGui::MenuItem("Light")) {
scene_.add_object(
new Light(vec3(0.5, 0.5, 1.5),0.15,random_color())
);
scene_changed_ = true;
}
if(ImGui::MenuItem("Checkerboard")) {
scene_.add_object(new HorizontalCheckerboardPlane(0.0));
scene_changed_ = true;
}
ImGui::EndMenu();
}
}
private:
Camera camera_;
Scene scene_;
Mesh mesh_;
GLuint texture_;
bool scene_changed_;
float translation_[3];
float quaternion_[4];
float zoom_;
};
}
int main(int argc, char** argv) {
DemoRaytraceApplication app(argc, argv, "<filename>");
app.start();
return 0;
}
| 29.833333 | 80 | 0.613251 | [
"mesh",
"object",
"model"
] |
a1c039479a736edee45f1e5900da8bf766771aa0 | 18,860 | cpp | C++ | lib/src/ChannelImplCarrier.cpp | luocf/Elastos.SDK.ElephantWallet.Contact | 361167b010483b0cc99ed094e376d4486a9fe001 | [
"MIT"
] | null | null | null | lib/src/ChannelImplCarrier.cpp | luocf/Elastos.SDK.ElephantWallet.Contact | 361167b010483b0cc99ed094e376d4486a9fe001 | [
"MIT"
] | null | null | null | lib/src/ChannelImplCarrier.cpp | luocf/Elastos.SDK.ElephantWallet.Contact | 361167b010483b0cc99ed094e376d4486a9fe001 | [
"MIT"
] | null | null | null | //
// ChannelImplCarrier.cpp
//
// Created by mengxk on 19/03/16.
// Copyright ยฉ 2016 mengxk. All rights reserved.
//
#include <ChannelImplCarrier.hpp>
#include <ela_session.h>
#include <cstring>
#include <Log.hpp>
#include <SafePtr.hpp>
#include <Platform.hpp>
namespace elastos {
/***********************************************/
/***** static variables initialize *************/
/***********************************************/
/***********************************************/
/***** static function implement ***************/
/***********************************************/
bool ChannelImplCarrier::IsValidCarrierAddress(const std::string& address)
{
bool valid = ela_address_is_valid(address.c_str());
return valid;
}
bool ChannelImplCarrier::IsValidCarrierUsrId(const std::string& usrId)
{
bool valid = ela_id_is_valid(usrId.c_str());
return valid;
}
int ChannelImplCarrier::GetCarrierUsrIdByAddress(const std::string& address, std::string& usrId)
{
char buf[ELA_MAX_ID_LEN + 1] = {0};
auto ret = ela_get_id_by_address(address.c_str(), buf, sizeof(buf));
if(ret == nullptr) {
int err = ela_get_error();
char strerr_buf[512] = {0};
ela_get_strerror(err, strerr_buf, sizeof(strerr_buf));
Log::E(Log::TAG, "Failed to get carrier usr id from:%s! ret=%s(0x%x)", address.c_str(), strerr_buf, err);
return ErrCode::ChannelFailedCarrier;
}
usrId = ret;
return 0;
}
/***********************************************/
/***** class public function implement ********/
/***********************************************/
ChannelImplCarrier::ChannelImplCarrier(uint32_t chType,
std::shared_ptr<ChannelListener> chListener,
std::shared_ptr<ChannelDataListener> dataListener,
std::weak_ptr<Config> config)
: MessageChannelStrategy(chType, chListener, dataListener)
, mConfig(config)
, mCarrier()
, mTaskThread()
, mChannelStatus(ChannelListener::ChannelStatus::Pending)
, mRecvDataCache()
, mCarrierDataTrans()
{
#if defined(__ANDROID__)
Platform::CallOnload(ela_session_jni_onload);
#endif // defined(__ANDROID__)
}
ChannelImplCarrier::~ChannelImplCarrier()
{
close();
}
int ChannelImplCarrier::preset(const std::string& profile)
{
if(mCarrier != nullptr) {
return ErrCode::ChannelFailedMultiOpen;
}
int ret = initCarrier();
if(ret < 0) {
return ret;
}
ret = ela_set_self_nospam(mCarrier.get(), 0);
if(ret != 0) {
int err = ela_get_error();
char strerr_buf[512] = {0};
ela_get_strerror(err, strerr_buf, sizeof(strerr_buf));
Log::E(Log::TAG, "Failed to set carrier nospam! ret=%s(0x%x)", strerr_buf, err);
return ErrCode::ChannelFailedCarrier;
}
std::string address;
ret = ChannelImplCarrier::getAddress(address);
CHECK_ERROR(ret)
Log::I(Log::TAG, "ChannelImplCarrier::preset() Success preset carrier on address: %s.", address.c_str());
return 0;
}
int ChannelImplCarrier::open()
{
if(mTaskThread == nullptr) {
mTaskThread = std::make_unique<ThreadPool>("carrier-channel");
}
mTaskThread->post(std::bind(&ChannelImplCarrier::runCarrier, this));
return 0;
}
int ChannelImplCarrier::close()
{
if (mCarrier == nullptr) {
ela_session_cleanup(mCarrier.get());
ela_kill(mCarrier.get());
}
mCarrier = nullptr;
return 0;
}
int ChannelImplCarrier::getAddress(std::string& address)
{
char addr[ELA_MAX_ADDRESS_LEN + 1] = {0};
auto ret = ela_get_address(mCarrier.get(), addr, sizeof(addr));
if(ret == nullptr) {
int err = ela_get_error();
char strerr_buf[512] = {0};
ela_get_strerror(err, strerr_buf, sizeof(strerr_buf));
Log::E(Log::TAG, "Failed to get address! ret=%s(0x%x)", strerr_buf, err);
return ErrCode::ChannelFailedCarrier;
}
address = addr;
return 0;
}
bool ChannelImplCarrier::isReady()
{
return (mChannelStatus == ChannelListener::ChannelStatus::Online);
}
int ChannelImplCarrier::requestFriend(const std::string& friendCode,
const std::string& summary,
bool remoteRequest,
bool forceRequest)
{
std::function<bool(const char*)> validCheckFun = (remoteRequest ? ela_address_is_valid : ela_id_is_valid);
bool valid = validCheckFun(friendCode.c_str());
if(valid != true) {
return ErrCode::InvalidArgument;
}
std::string selfAddr, selfUsrId;
getAddress(selfAddr);
GetCarrierUsrIdByAddress(selfAddr, selfUsrId);
if(friendCode == selfAddr
|| friendCode == selfUsrId) {
return ErrCode::ChannelFailedFriendSelf;
}
int ret = ErrCode::UnknownError;
if(remoteRequest == true) {
std::string usrId;
ret = GetCarrierUsrIdByAddress(friendCode, usrId);
CHECK_ERROR(ret)
const char* hello = (summary.empty() ? " " : summary.c_str());
bool isAdded = ela_is_friend(mCarrier.get(), usrId.c_str());
if(isAdded == true) {
if(forceRequest == false) {
Log::I(Log::TAG, "ChannelImplCarrier::requestFriend() Friend is already exists. friendCode=%s summary=%s", friendCode.c_str(), hello);
return ErrCode::ChannelFailedFriendExists;
}
ela_remove_friend(mCarrier.get(), usrId.c_str());
}
Log::I(Log::TAG, "ChannelImplCarrier::requestFriend() friendCode=%s summary=%s", friendCode.c_str(), hello);
ret = ela_add_friend(mCarrier.get(), friendCode.c_str(), hello);
} else {
Log::I(Log::TAG, "ChannelImplCarrier::requestFriend() friendCode=%s", friendCode.c_str());
ret = ela_accept_friend(mCarrier.get(), friendCode.c_str());
}
if(ret != 0) {
int err = ela_get_error();
if(err == ELA_GENERAL_ERROR(ELAERR_ALREADY_EXIST)) {
return ErrCode::ChannelFailedFriendExists;
}
char strerr_buf[512] = {0};
ela_get_strerror(err, strerr_buf, sizeof(strerr_buf));
Log::E(Log::TAG, "Failed to add friend! ret=%s(0x%x)", strerr_buf, err);
return ErrCode::ChannelFailedCarrier;
}
return 0;
}
int ChannelImplCarrier::removeFriend(const std::string& friendCode)
{
std::string usrId;
bool valid = IsValidCarrierUsrId(friendCode);
if(valid == true) {
usrId = friendCode;
} else {
bool valid = IsValidCarrierAddress(friendCode);
if (valid == true) {
GetCarrierUsrIdByAddress(friendCode, usrId);
}
}
if(usrId.empty() == true) {
return ErrCode::InvalidArgument;
}
bool isFriend = ela_is_friend(mCarrier.get(), usrId.c_str());
if(isFriend == false) {
Log::W(Log::TAG, "Ignore to remove a friend: %s, it's not exists.", usrId.c_str());
return 0;
}
int ret = ela_remove_friend(mCarrier.get(), usrId.c_str());
if(ret != 0) {
int err = ela_get_error();
if(err == ELA_GENERAL_ERROR(ELAERR_ALREADY_EXIST)) {
return ErrCode::ChannelFailedFriendExists;
}
char strerr_buf[512] = {0};
ela_get_strerror(err, strerr_buf, sizeof(strerr_buf));
Log::E(Log::TAG, "Failed to remove friend! ret=%s(0x%x)", strerr_buf, err);
return ErrCode::ChannelFailedCarrier;
}
return 0;
}
int ChannelImplCarrier::sendMessage(const std::string& friendCode,
std::vector<uint8_t> msgContent)
{
uint64_t pkgCount = msgContent.size() / MaxPkgSize + 1;
Log::D(Log::TAG, "ChannelImplCarrier::sendMessage() size=%d count=%lld", msgContent.size(), pkgCount);
if(pkgCount > MaxPkgCount) {
return ErrCode::ChannelDataTooLarge;
}
for(uint64_t pkgIdx = 0; pkgIdx < pkgCount; pkgIdx++) {
std::vector<uint8_t> data {std::begin(PkgMagic), std::end(PkgMagic)};
uint16_t pkgVal = static_cast<uint16_t>(pkgIdx);
data[PkgMagicDataIdx] = (pkgVal >> 8 ) & 0xFF;
data[PkgMagicDataIdx + 1] = pkgVal & 0xFF;
pkgVal = static_cast<uint16_t>(pkgCount);
data[PkgMagicDataCnt] = (pkgVal >> 8 ) & 0xFF;
data[PkgMagicDataCnt + 1] = pkgVal & 0xFF;
auto dataBegin = msgContent.begin() + pkgIdx * MaxPkgSize;
auto dataRemains = msgContent.end() - dataBegin;
auto dataEnd = (MaxPkgSize < dataRemains ? dataBegin + MaxPkgSize : dataBegin + dataRemains);
data.insert(data.end(), dataBegin, dataEnd);
bool offlineMsg;
int ret = ela_send_friend_message(mCarrier.get(), friendCode.c_str(), data.data(), data.size(), &offlineMsg);
if(ret != 0) {
int err = ela_get_error();
char strerr_buf[512] = {0};
ela_get_strerror(err, strerr_buf, sizeof(strerr_buf));
Log::E(Log::TAG, "Failed to send message! ret=%s(0x%x)", strerr_buf, err);
return ErrCode::ChannelNotSendMessage;
}
Log::D(Log::TAG, "ChannelImplCarrier::sendMessage PkgMagicData Idx/Cnt=%05lld[%02x,%02x]/%05lld[%02x,%02x]",
pkgIdx, data[PkgMagicDataIdx], data[PkgMagicDataIdx + 1], pkgCount, data[PkgMagicDataCnt], data[PkgMagicDataCnt + 1]);
}
return 0;
}
int ChannelImplCarrier::sendData(const std::string& friendCode,
const std::string& dataId)
{
Log::I(Log::TAG, "%s friendCode=%s dataId=%s", __PRETTY_FUNCTION__, friendCode.c_str(), dataId.c_str());
mCarrierDataTrans = std::make_unique<ChannelImplCarrierDataTrans>(mChannelType, mCarrier, mChannelDataListener);
int ret = mCarrierDataTrans->start(ChannelImplCarrierDataTrans::Direction::Sender, friendCode, dataId);
CHECK_ERROR(ret);
return 0;
}
int ChannelImplCarrier::cancelSendData(const std::string& friendCode,
const std::string& dataId)
{
Log::I(Log::TAG, "%s friendCode=%s dataId=%s", __PRETTY_FUNCTION__, friendCode.c_str(), dataId.c_str());
mCarrierDataTrans.reset();
return 0;
}
/***********************************************/
/***** class protected function implement *****/
/***********************************************/
int ChannelImplCarrier::initCarrier()
{
auto config = SAFE_GET_PTR(mConfig);
ElaOptions carrierOpts;
ElaCallbacks carrierCallbacks;
memset(&carrierOpts, 0, sizeof(carrierOpts));
memset(&carrierCallbacks, 0, sizeof(carrierCallbacks));
carrierCallbacks.connection_status = OnCarrierConnection;
carrierCallbacks.friend_request = OnCarrierFriendRequest;
carrierCallbacks.friend_connection = OnCarrierFriendConnection;
carrierCallbacks.friend_message = OnCarrierFriendMessage;
carrierOpts.udp_enabled = config->mCarrierConfig->mEnableUdp;
carrierOpts.persistent_location = config->mUserDataDir.c_str();
// Log::W(Log::TAG, "========= Recover carrier by secret key: %s", profile.c_str());
// if(profile.empty() == false) {
// carrierOpts.secret_key = profile.c_str();
// }
// set BootstrapNode
size_t carrierNodeSize = config->mCarrierConfig->mBootstrapNodes.size();
BootstrapNode carrierNodeArray[carrierNodeSize];
memset (carrierNodeArray, 0, sizeof(carrierNodeArray));
for(int idx = 0; idx < carrierNodeSize; idx++) {
const auto& node = config->mCarrierConfig->mBootstrapNodes[idx];
carrierNodeArray[idx].ipv4 = node.mIpv4.c_str();
carrierNodeArray[idx].port = node.mPort.c_str();
carrierNodeArray[idx].public_key = node.mPublicKey.c_str();
}
carrierOpts.bootstraps_size = carrierNodeSize;
carrierOpts.bootstraps = carrierNodeArray;
// set HiveBootstrapNode
size_t hiveNodeSize = config->mCarrierConfig->mHiveNodes.size();
HiveBootstrapNode hiveNodeArray[hiveNodeSize];
memset (hiveNodeArray, 0, sizeof(hiveNodeArray));
for(int idx = 0; idx < hiveNodeSize; idx++) {
const auto& node = config->mCarrierConfig->mHiveNodes[idx];
hiveNodeArray[idx].ipv4 = node.mIpv4.c_str();
hiveNodeArray[idx].port = node.mPort.c_str();
}
//carrierOpts.hive_bootstraps_size = hiveNodeSize;
//carrierOpts.hive_bootstraps = hiveNodeArray;
carrierOpts.log_level = static_cast<ElaLogLevel>(config->mCarrierConfig->mLogLevel);
auto creater = [&]() -> ElaCarrier* {
auto ptr = ela_new(&carrierOpts, &carrierCallbacks, this);
return ptr;
};
auto deleter = [=](ElaCarrier* ptr) -> void {
if(ptr != nullptr) {
ela_filetransfer_cleanup(ptr);
ela_session_cleanup(ptr);
ela_kill(ptr);
}
};
mCarrier = std::shared_ptr<ElaCarrier>(creater(), deleter);
if (mCarrier.get() == nullptr) {
Log::E(Log::TAG, "Failed to new carrier!");
return ErrCode::ChannelFailedCarrier;
}
int ret = ela_filetransfer_init(mCarrier.get(), OnCarrierFileTransConnect, this);
if (ret < 0) {
Log::E(Log::TAG, "Failed to init filetransfer!");
return ErrCode::ChannelFailedCarrier;
}
return 0;
}
void ChannelImplCarrier::runCarrier()
{
int ret = ela_run(mCarrier.get(), 500);
if(ret < 0) {
ela_kill(mCarrier.get());
Log::E(Log::TAG, "Failed to run carrier!");
return;
}
}
void ChannelImplCarrier::OnCarrierConnection(ElaCarrier *carrier,
ElaConnectionStatus status, void *context)
{
auto thiz = reinterpret_cast<ChannelImplCarrier*>(context);
std::string carrierAddr, carrierUsrId;
thiz->getAddress(carrierAddr);
GetCarrierUsrIdByAddress(carrierAddr, carrierUsrId);
thiz->mChannelStatus = ( status == ElaConnectionStatus_Connected
? ChannelListener::ChannelStatus::Online
: ChannelListener::ChannelStatus::Offline);
Log::D(Log::TAG, "ChannelImplCarrier::OnCarrierConnection status: %d", thiz->mChannelStatus);
if(thiz->mChannelListener.get() != nullptr) {
thiz->mChannelListener->onStatusChanged(carrierUsrId, thiz->mChannelType, thiz->mChannelStatus);
}
if(status == ElaConnectionStatus_Disconnected) {
thiz->cancelSendData("", "");
}
}
void ChannelImplCarrier::OnCarrierFriendRequest(ElaCarrier *carrier, const char *friendid,
const ElaUserInfo *info,
const char *hello, void *context)
{
Log::D(Log::TAG, "ChannelImplCarrier::OnCarrierFriendRequest from: %s", friendid);
auto thiz = reinterpret_cast<ChannelImplCarrier*>(context);
if(thiz->mChannelListener.get() != nullptr) {
thiz->mChannelListener->onFriendRequest(friendid, thiz->mChannelType, hello);
}
}
void ChannelImplCarrier::OnCarrierFriendConnection(ElaCarrier *carrier,const char *friendid,
ElaConnectionStatus status, void *context)
{
Log::D(Log::TAG, "=-=-=-=-= ChannelImplCarrier::OnCarrierFriendConnection from: %s %d", friendid, status);
auto thiz = reinterpret_cast<ChannelImplCarrier*>(context);
if(thiz->mChannelListener.get() != nullptr) {
auto chStatus = ( status == ElaConnectionStatus_Connected
? ChannelListener::ChannelStatus::Online
: ChannelListener::ChannelStatus::Offline);
thiz->mChannelListener->onFriendStatusChanged(friendid, thiz->mChannelType, chStatus);
}
if(status == ElaConnectionStatus_Disconnected) {
thiz->cancelSendData(friendid, "");
}
}
void ChannelImplCarrier::OnCarrierFriendMessage(ElaCarrier *carrier, const char *from,
const void *msg, size_t len,
bool offline, void *context)
{
Log::D(Log::TAG, "ChannelImplCarrier::OnCarrierFriendMessage from: %s len=%d", from, len);
auto thiz = reinterpret_cast<ChannelImplCarrier*>(context);
if(thiz->mChannelListener.get() == nullptr) {
Log::W(Log::TAG, "ChannelListener is not set. ignore to process");
return;
}
auto data = reinterpret_cast<const uint8_t*>(msg);
int32_t dataOffset = 0;
bool dataComplete = true;
bool isPkgData = true;
for(auto idx = 0; idx < PkgMagicHeadSize; idx++) {
if(data[idx] != PkgMagic[idx]) {
isPkgData = false;
break;
}
dataOffset = PkgMagicSize;
}
auto dataSection = std::vector<uint8_t>(data + dataOffset, data + len);
if(isPkgData == true) {
uint64_t pkgIdx = data[PkgMagicDataIdx];
pkgIdx = (pkgIdx << 8) + data[PkgMagicDataIdx + 1];
uint64_t pkgCount = data[PkgMagicDataCnt];
pkgCount = (pkgCount << 8) + data[PkgMagicDataCnt + 1];
// dataComplete = (pkgIdx == pkgCount - 1 ? true : false);
Log::D(Log::TAG, "ChannelImplCarrier::OnCarrierFriendMessage PkgMagicData Idx/Cnt=%05lld[%02x,%02x]/%05lld[%02x,%02x]",
pkgIdx, data[PkgMagicDataIdx], data[PkgMagicDataIdx + 1], pkgCount, data[PkgMagicDataCnt], data[PkgMagicDataCnt + 1]);
auto& dataCache = thiz->mRecvDataCache[from];
dataCache[pkgIdx] = std::move(dataSection);
if(dataCache.size() == pkgCount) {
std::vector<uint8_t> dataPkg;
for(int idx = 0; idx < dataCache.size(); idx++) {
dataPkg.insert(dataPkg.end(), dataCache[idx].begin(), dataCache[idx].end());
}
thiz->mChannelListener->onReceivedMessage(from, thiz->mChannelType, dataPkg);
dataCache.clear();
}
} else {
thiz->mChannelListener->onReceivedMessage(from, thiz->mChannelType, dataSection);
}
}
void ChannelImplCarrier::OnCarrierFileTransConnect(ElaCarrier *carrier,
const char *from,
const ElaFileTransferInfo *fileinfo,
void *context)
{
Log::I(Log::TAG, "%s from=%s fileinfo=%p", __PRETTY_FUNCTION__, from, fileinfo);
if(fileinfo != nullptr) {
Log::I(Log::TAG, "filename=%s", fileinfo->filename);
}
auto thiz = reinterpret_cast<ChannelImplCarrier*>(context);
thiz->mCarrierDataTrans = std::make_unique<ChannelImplCarrierDataTrans>(thiz->mChannelType, thiz->mCarrier, thiz->mChannelDataListener);
int ret = thiz->mCarrierDataTrans->start(ChannelImplCarrierDataTrans::Direction::Receiver, from);
CHECK_RETVAL(ret);
}
/***********************************************/
/***** class private function implement *******/
/***********************************************/
} // namespace elastos
| 36.339114 | 150 | 0.613839 | [
"vector"
] |
a1c489b51d9db6c8451599723ffd286dccd7b226 | 4,735 | cxx | C++ | TOF/TOFbase/AliTOFFEEDump.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | TOF/TOFbase/AliTOFFEEDump.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | TOF/TOFbase/AliTOFFEEDump.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z | /**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/*
author: Roberto Preghenella (preghenella@bo.infn.it)
*/
///////////////////////////////////////////////////////////////
// //
// This classes provide the object to store the full dump //
// of TOF FEE configuration database. //
// //
///////////////////////////////////////////////////////////////
#include "AliTOFFEEDump.h"
#include <string.h>
#include <iostream>
#include <fstream>
#include "TSystem.h"
#include "AliLog.h"
ClassImp(AliTOFFEEDump)
//_______________________________________________________________
AliTOFFEEDump::AliTOFFEEDump() :
TObject(),
fSize(0),
fData(NULL)
{
/* default constructor */
}
#if 0
//_______________________________________________________________
AliTOFFEEDump::AliTOFFEEDump(const AliTOFFEEDump &source) :
TObject(source),
fSize(source.fSize),
fData(NULL)
{
/* copy constructor */
/* check size */
if (fSize == 0) return;
/* allocate and copy data */
fData = new UChar_t[fSize];
memcpy(fData, source.fData, fSize);
}
//_______________________________________________________________
AliTOFFEEDump &
AliTOFFEEDump::operator=(const AliTOFFEEDump &source)
{
/* operator= */
/* check source and destination size */
if (source.fSize == 0 || fSize != source.fSize) return *this;
/* copy data */
memcpy(fData, source.fData, fSize);
return *this;
}
#endif
//_______________________________________________________________
AliTOFFEEDump::~AliTOFFEEDump()
{
/* default destructor */
if (fData) delete [] fData;
}
//_______________________________________________________________
Bool_t
AliTOFFEEDump::operator!=(const AliTOFFEEDump &source)
{
/* operator!= */
/* check size */
if (fSize != source.fSize) return kTRUE;
/* check data */
if (memcmp(fData, source.fData, fSize) != 0) return kTRUE;
return kFALSE;
}
//_______________________________________________________________
Bool_t
AliTOFFEEDump::ReadFromFile(const Char_t *filename)
{
/* read from file */
/* open file */
Char_t *expandedFileName = gSystem->ExpandPathName(filename);
std::ifstream is;
is.open(expandedFileName, std::ios::binary);
if (!is.is_open()) {
AliError(Form("error while opening TOF FEE dump file: %s", filename));
return kFALSE;
}
AliInfo(Form("TOF FEE dump file opened: %s", filename));
/* get file size */
Int_t begin = is.tellg();
is.seekg(0, std::ios::end); /* end */
Int_t end = is.tellg();
Int_t size = end - begin;
is.seekg(0, std::ios::beg); /* rewind file */
if (size <= 0) {
AliError(Form("error while getting TOF FEE dump file size: %d", size));
return kFALSE;
}
AliInfo(Form("got TOF FEE dump file size: %d", size));
/* check previous allocation */
if (fData) {
AliWarning("data already allocated, old data will be overwritten");
delete [] fData;
}
/* allocate and read data */
fSize = size;
fData = new UChar_t[fSize];
is.read((Char_t *)fData, fSize);
AliInfo(Form("TOF FEE dump file stored"));
/* close file */
is.close();
return kTRUE;
}
//_______________________________________________________________
void
AliTOFFEEDump::DumpData() {
/* dump data */
printf("*** TOF FEE dump data ***\n");
printf("data size = %d bytes\n", fSize);
printf("*************************\n");
Int_t nwords = fSize / 4;
UInt_t *data = (UInt_t *)fData;
for (Int_t iword = 0; iword < nwords; iword++) {
if (iword != 0 && iword % 4 == 0) printf("\n");
printf("%08x ", data[iword]);
}
printf("\n*************************\n");
}
| 28.017751 | 76 | 0.586061 | [
"object"
] |
a1c5e49f0843ec0c2795ac1cb1cff333e2d95f41 | 8,045 | cc | C++ | src/developer/shell/josh/lib/task_test.cc | EnderNightLord-ChromeBook/fuchsia-pine64-pinephone | 05e2c059b57b6217089090a0315971d1735ecf57 | [
"BSD-3-Clause"
] | 14 | 2020-10-25T05:48:36.000Z | 2021-09-20T02:46:20.000Z | src/developer/shell/josh/lib/task_test.cc | JokeZhang/fuchsia | d6e9dea8dca7a1c8fa89d03e131367e284b30d23 | [
"BSD-3-Clause"
] | null | null | null | src/developer/shell/josh/lib/task_test.cc | JokeZhang/fuchsia | d6e9dea8dca7a1c8fa89d03e131367e284b30d23 | [
"BSD-3-Clause"
] | 2 | 2020-10-25T01:13:49.000Z | 2020-10-26T02:32:13.000Z | // Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <lib/async-loop/cpp/loop.h>
#include <lib/async-loop/default.h>
#include <lib/fdio/spawn.h>
#include <zircon/process.h>
#include <zircon/syscalls.h>
#include <array>
#include <fstream>
#include <string>
#include <gtest/gtest.h>
#include <task-utils/walker.h>
#include "src/developer/shell/josh/lib/js_testing_utils.h"
#include "zx.h"
namespace shell {
class TaskTest : public JsTest {
protected:
void SetUp() override { JsTest::SetUp(); }
};
TEST_F(TaskTest, SimplePs) {
InitBuiltins("/pkg/data/fidling", "/pkg/data/lib");
// Loop up-front to populate the svc object, which is done via a promise.
js_std_loop(ctx_->Get());
std::string test_string = R"(
globalThis.resultOne = undefined;
task.ps().
then((result) => {
globalThis.resultOne = result; }).
catch((e) => { std.printf(e); std.printf(e.stack); globalThis.resultOne = e;});
)";
ASSERT_TRUE(Eval(test_string));
js_std_loop(ctx_->Get());
test_string = R"(
let res = globalThis.resultOne;
if (res instanceof Error) {
throw res;
}
if (res.size <= 0) {
throw "No tasks found by ps?";
}
res.forEach((value, key, map) => {
if (!key.hasOwnProperty("name") || !key.hasOwnProperty("info")) {
throw "Missing task information in " + JSON.stringify(key);
}
});
)";
ASSERT_TRUE(Eval(test_string));
}
TEST_F(TaskTest, Kill) {
async::Loop loop(&kAsyncLoopConfigNoAttachToCurrentThread);
ASSERT_EQ(loop.StartThread(), ZX_OK);
InitBuiltins("/pkg/data/fidling", "/pkg/data/lib");
// get root job, to create a subprocess of it, that will be dicoverable in the job tree
js_std_loop(ctx_->Get());
std::string test_string0 = R"(
fidl.loadLibrary('fuchsia.kernel');
let promiseRootJobResult = svc.fuchsia_kernel_RootJob.Get();
promiseRootJobResult.
then((result) => {
globalThis.resultOne = result; })
)";
ASSERT_TRUE(Eval(test_string0));
js_std_loop(ctx_->Get());
std::string test_string1 = R"(
globalThis.resultOne['job']._handle;
)";
JSValue handle_to_root_js =
JS_Eval(ctx_->Get(), test_string1.c_str(), test_string1.length(), "<evalScript>", 0);
if (JS_IsException(handle_to_root_js)) {
ctx_->DumpError();
}
ASSERT_FALSE(JS_IsException(handle_to_root_js));
zx_handle_info_t handle_to_root = zx::HandleFromJsval(handle_to_root_js);
// spawn a proccess, child of root job and get its koid
const char* argv[] = {"/pkg/bin/spawn_child_test_util", nullptr};
std::vector<fdio_spawn_action_t> actions;
char err_msg[FDIO_SPAWN_ERR_MSG_MAX_LENGTH];
zx_handle_t process_handle;
zx_status_t status2 = fdio_spawn_etc(handle_to_root.handle, FDIO_SPAWN_CLONE_ALL, argv[0], argv,
nullptr, // Environ
actions.size(), actions.data(), &process_handle, err_msg);
ASSERT_EQ(status2, ZX_OK) << "Failed to spawn command (" << status2 << "): " << err_msg;
zx_info_handle_basic_t info;
ASSERT_EQ(
zx_object_get_info(process_handle, ZX_INFO_HANDLE_BASIC, &info, sizeof(info), NULL, NULL),
ZX_OK);
loop.RunUntilIdle();
// kill the process
std::string test_string2 =
"globalThis.resultTwo = undefined;"
"task.kill(" +
std::to_string(info.koid) +
").then((result) => {"
"globalThis.resultTwo = result; })."
"catch((e) => { std.printf(e); std.printf(e.stack); globalThis.resultTwo = e;});";
ASSERT_TRUE(Eval(test_string2));
// task.kill() is async, the loop is needed to ensure it is executed
js_std_loop(ctx_->Get());
std::string test_string3 = R"(
let res = globalThis.resultTwo;
if (res instanceof Error) {
throw res;
}
if (res != undefined) {
throw res;
}
)";
ASSERT_TRUE(Eval(test_string3));
}
TEST_F(TaskTest, KillAll) {
async::Loop loop(&kAsyncLoopConfigNoAttachToCurrentThread);
ASSERT_EQ(loop.StartThread(), ZX_OK);
InitBuiltins("/pkg/data/fidling", "/pkg/data/lib");
// get root job, to create a subprocess of it, that will be dicoverable in the job tree
js_std_loop(ctx_->Get());
std::string test_string0 = R"(
fidl.loadLibrary('fuchsia.kernel');
let promiseRootJobResult = svc.fuchsia_kernel_RootJob.Get();
promiseRootJobResult.
then((result) => {
globalThis.resultOne = result; })
)";
ASSERT_TRUE(Eval(test_string0));
js_std_loop(ctx_->Get());
std::string test_string1 = R"(
globalThis.resultOne['job']._handle;
)";
JSValue handle_to_root_js =
JS_Eval(ctx_->Get(), test_string1.c_str(), test_string1.length(), "<evalScript>", 0);
if (JS_IsException(handle_to_root_js)) {
ctx_->DumpError();
}
ASSERT_FALSE(JS_IsException(handle_to_root_js));
zx_handle_info_t handle_to_root = zx::HandleFromJsval(handle_to_root_js);
// get koid of current process to make the spawned name unique
zx_handle_t cur_process_handle = zx_process_self();
zx_info_handle_basic_t info_cur_process;
ASSERT_EQ(zx_object_get_info(cur_process_handle, ZX_INFO_HANDLE_BASIC, &info_cur_process,
sizeof(info_cur_process), NULL, NULL),
ZX_OK);
// spawn a proccess, child of root job, named spawnChild+cur_process_koid
const char* argv[] = {"/pkg/bin/spawn_child_test_util", nullptr};
std::string process_name = "spawnChild" + std::to_string(info_cur_process.koid);
std::vector<fdio_spawn_action_t> actions;
actions.push_back({.action = FDIO_SPAWN_ACTION_SET_NAME, .name = {.data = process_name.c_str()}});
char err_msg[FDIO_SPAWN_ERR_MSG_MAX_LENGTH];
zx_handle_t process_handle;
zx_status_t status2 = fdio_spawn_etc(handle_to_root.handle, FDIO_SPAWN_CLONE_ALL, argv[0], argv,
nullptr, // Environ
actions.size(), actions.data(), &process_handle, err_msg);
ASSERT_EQ(status2, ZX_OK) << "Failed to spawn command (" << status2 << "): " << err_msg;
loop.RunUntilIdle();
// kill the process by name
std::string test_string2 =
"globalThis.resultTwo = undefined;"
"task.killall(\"" +
process_name +
"\").then((result) => {"
"globalThis.resultTwo = result; })."
"catch((e) => { std.printf(e); std.printf(e.stack); globalThis.resultTwo = e;});";
ASSERT_TRUE(Eval(test_string2));
// task.kill() is async, the loop is needed to ensure it is executed
js_std_loop(ctx_->Get());
std::string test_string3 = R"(
let res = globalThis.resultTwo;
if (res instanceof Error) {
throw res;
}
if (res != undefined) {
throw res;
}
)";
ASSERT_TRUE(Eval(test_string3));
// launch the same process again, to kill it using a regex
status2 = fdio_spawn_etc(handle_to_root.handle, FDIO_SPAWN_CLONE_ALL, argv[0], argv,
nullptr, // Environ
actions.size(), actions.data(), &process_handle, err_msg);
ASSERT_EQ(status2, ZX_OK) << "Failed to spawn command (" << status2 << "): " << err_msg;
loop.RunUntilIdle();
// kill the process by regex
std::string test_string4 =
"globalThis.resultTwo = undefined;"
"task.killall(\"[a-z]" +
process_name.substr(1) +
"\", \"r\").then((result) => {"
"globalThis.resultTwo = result; })."
"catch((e) => { std.printf(e); std.printf(e.stack); globalThis.resultTwo = e;});";
ASSERT_TRUE(Eval(test_string4));
// task.kill() is async, the loop is needed to ensure it is executed
js_std_loop(ctx_->Get());
std::string test_string5 = R"(
res = globalThis.resultTwo;
if (res instanceof Error) {
throw res;
}
if (res != undefined) {
throw res;
}
)";
ASSERT_TRUE(Eval(test_string5));
}
} // namespace shell
| 35.915179 | 100 | 0.6445 | [
"object",
"vector"
] |
a1c6cd74c5bf4e680ea89f7b47ec640dc2d011ee | 13,320 | hpp | C++ | SamSrc/sam/Tokens.hpp | dirkcgrunwald/SAM | 0478925c506ad38fd405954cc4415a3e96e77d90 | [
"MIT"
] | 6 | 2019-08-16T07:13:17.000Z | 2021-06-08T21:15:52.000Z | SamSrc/sam/Tokens.hpp | dirkcgrunwald/SAM | 0478925c506ad38fd405954cc4415a3e96e77d90 | [
"MIT"
] | 1 | 2020-05-30T20:35:18.000Z | 2020-05-30T20:35:18.000Z | SamSrc/sam/Tokens.hpp | dirkcgrunwald/SAM | 0478925c506ad38fd405954cc4415a3e96e77d90 | [
"MIT"
] | 3 | 2020-02-17T18:38:14.000Z | 2021-03-28T02:47:57.000Z | #ifndef TOKENS_HPP
#define TOKENS_HPP
#include <boost/variant/recursive_variant.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <iostream>
#include <vector>
#include <stack>
#include <sam/FeatureMap.hpp>
namespace sam {
class ExpressionTokenException : public std::runtime_error {
public:
ExpressionTokenException(char const * message) : std::runtime_error(message) { }
ExpressionTokenException(std::string message) : std::runtime_error(message) { }
};
template <typename... Ts>
class ExpressionToken
{};
template <typename... Ts>
class ExpressionToken<std::tuple<Ts...>>
{
protected:
// When tokens are created, they are always created in the context of a
// feature map. Thus, while not all tokens need a feature map to evaluate
// them, all tokens have a reference to a feature map.
std::shared_ptr<FeatureMap> featureMap;
public:
/**
* Constructor for the base class.
* \param _featureMap The feature map that some tokens need to evaluate.
*/
ExpressionToken(std::shared_ptr<FeatureMap> featureMap)
{
this->featureMap = featureMap;
}
/**
* Returns a string representation. Mostly for debugging. Should be
* overriden by child classes.
*/
virtual std::string toString() const { return "ExpressionToken";}
/**
* Evaluates the token. Changes are made to the stack to reflect the
* change from evaluating the token.
* \param mystack The stack used in evaluating the postfix expression.
* \param key The key that is used to find relevant entries in the feature
* map.
* \return Returns true if the token evaluating correctly. False otherwise.
* For example, sometimes data is unavailable (e.g. for PrevToken) so the
* token can't be evaluating this iteration.
*/
virtual bool evaluate(std::stack<double> & mystack,
std::string const& key,
std::tuple<Ts...> const& input)
{ return false; }
/**
* Returns true if the token is an operator. False otherwise
*/
virtual bool isOperator() const { return false; }
};
template <typename... Ts>
class NumberToken : public ExpressionToken<Ts...>
{};
/**
* Token representing a simple number like 1 or 6.5
*/
template <typename... Ts>
class NumberToken<std::tuple<Ts...>> :
public ExpressionToken<std::tuple<Ts...>>
{
private:
double number;
public:
NumberToken(std::shared_ptr<FeatureMap> featureMap, double d) :
ExpressionToken<std::tuple<Ts...>>(featureMap), number(d) {}
std::string toString() const {
return "NumberToken: " + boost::lexical_cast<std::string>(number);
}
/**
* Simply pushes the number to the top of the stack.
*/
bool evaluate(std::stack<double> & mystack,
std::string const& key,
std::tuple<Ts...> const& input)
{
//std::cout << "NumberToken evaluate " << std::endl;
mystack.push(number);
return true;
}
bool isOperator() const { return false; }
};
template <typename... Ts>
class OperatorToken : public ExpressionToken<Ts...>
{};
template <typename... Ts>
class OperatorToken<std::tuple<Ts...>> :
public ExpressionToken<std::tuple<Ts...>>
{
private:
int precedence;
int associativity;
public:
const static int RIGHT_ASSOCIATIVE = 0;
const static int LEFT_ASSOCIATIVE = 1;
OperatorToken(std::shared_ptr<FeatureMap> featureMap,
int associativity,
int precedence) :
ExpressionToken<std::tuple<Ts...>>(featureMap)
{
this->associativity = associativity;
this->precedence = precedence;
}
bool isOperator() const { return true; }
bool isLeftAssociative() const { return associativity == LEFT_ASSOCIATIVE; }
bool isRightAssociative() const { return associativity == RIGHT_ASSOCIATIVE; }
int getPrecedence() const { return precedence; }
};
template <typename... Ts>
class AddOperator : public OperatorToken<Ts...>
{};
template <typename... Ts>
class AddOperator<std::tuple<Ts...>> :
public OperatorToken<std::tuple<Ts...>>
{
public:
AddOperator(std::shared_ptr<FeatureMap> featureMap) :
OperatorToken<std::tuple<Ts...>>(featureMap, 2, this->LEFT_ASSOCIATIVE) {}
std::string toString() const {
return "AddOperator";
}
bool evaluate(std::stack<double> & mystack,
std::string const& key,
std::tuple<Ts...> const& input)
{
//std::cout << "AddOperator evaluate " << std::endl;
if (mystack.size() >= 2) {
double o2 = mystack.top();
mystack.pop();
double o1 = mystack.top();
mystack.pop();
double result = o1 + o2;
mystack.push(result);
return true;
}
return false;
}
};
template <typename... Ts>
class SubOperator : public OperatorToken<Ts...>
{};
template <typename... Ts>
class SubOperator<std::tuple<Ts...>> :
public OperatorToken<std::tuple<Ts...>>
{
public:
SubOperator(std::shared_ptr<FeatureMap> featureMap) :
OperatorToken<std::tuple<Ts...>>(featureMap, 2, this->LEFT_ASSOCIATIVE) {}
std::string toString() const {
return "SubOperator";
}
bool evaluate(std::stack<double> & mystack,
std::string const& key,
std::tuple<Ts...> const& input)
{
//std::cout << "SubOperator evaluate " << std::endl;
if (mystack.size() >= 2) {
double o2 = mystack.top();
mystack.pop();
double o1 = mystack.top();
mystack.pop();
double result = o1 - o2;
mystack.push(result);
return true;
}
return false;
}
};
template <typename... Ts>
class MultOperator : public OperatorToken<Ts...>
{};
template <typename... Ts>
class MultOperator<std::tuple<Ts...>> :
public OperatorToken<std::tuple<Ts...>>
{
public:
MultOperator(std::shared_ptr<FeatureMap> featureMap) :
OperatorToken<std::tuple<Ts...>>(featureMap, 3, this->LEFT_ASSOCIATIVE) {}
std::string toString() const {
return "MultOperator";
}
bool evaluate(std::stack<double> & mystack,
std::string const& key,
std::tuple<Ts...> const& input)
{
//std::cout << "MultOperator evaluate " << std::endl;
if (mystack.size() >= 2) {
double o2 = mystack.top();
mystack.pop();
double o1 = mystack.top();
mystack.pop();
double result = o1 * o2;
mystack.push(result);
return true;
}
return false;
}
};
template <typename... Ts>
class LessThanOperator : public OperatorToken<Ts...>
{};
template <typename... Ts>
class LessThanOperator<std::tuple<Ts...>> :
public OperatorToken<std::tuple<Ts...>>
{
public:
LessThanOperator(std::shared_ptr<FeatureMap> featureMap) :
OperatorToken<std::tuple<Ts...>>(featureMap, 1, this->LEFT_ASSOCIATIVE) {}
std::string toString() const {
return "LessThanOperator";
}
bool evaluate(std::stack<double> & mystack,
std::string const& key,
std::tuple<Ts...> const& input)
{
if (mystack.size() >= 2) {
double o2 = mystack.top();
mystack.pop();
double o1 = mystack.top();
mystack.pop();
double result = o1 < o2;
mystack.push(result);
return true;
}
return false;
}
};
template <typename... Ts>
class GreaterThanOperator : public OperatorToken<Ts...>
{};
template <typename... Ts>
class GreaterThanOperator<std::tuple<Ts...>> :
public OperatorToken<std::tuple<Ts...>>
{
public:
GreaterThanOperator(std::shared_ptr<FeatureMap> featureMap) :
OperatorToken<std::tuple<Ts...>>(featureMap, 1, this->LEFT_ASSOCIATIVE) {}
std::string toString() const {
return "GreaterThanOperator";
}
bool evaluate(std::stack<double> & mystack,
std::string const& key,
std::tuple<Ts...> const& input)
{
if (mystack.size() >= 2) {
double o2 = mystack.top();
mystack.pop();
double o1 = mystack.top();
mystack.pop();
double result = o1 > o2;
mystack.push(result);
return true;
}
return false;
}
};
template <size_t field, typename... Ts>
class FieldToken : public ExpressionToken<Ts...>
{
};
/**
* Represents one field of an input
*/
template <size_t field, typename... Ts>
class FieldToken<field, std::tuple<Ts...>> :
public ExpressionToken<std::tuple<Ts...>>
{
private:
std::string identifier;
public:
FieldToken(std::shared_ptr<FeatureMap> featureMap) :
ExpressionToken<std::tuple<Ts...>>(featureMap) {}
bool evaluate(std::stack<double> & mystack,
std::string const& key,
std::tuple<Ts...> const& input)
{
//std::cout << "FieldToken evaluate " << std::endl;
try {
double d = std::get<0>(input);
auto data = std::get<field>(input);
mystack.push(data);
return true;
} catch (std::exception e) {
std::cout << e.what() << std::endl;
return false;
}
}
bool isOperator() const { return false; }
};
template <typename... Ts>
class FuncToken : public ExpressionToken<Ts...>
{};
/**
* Represents tokens of the form identifier.function(parameters), e.g.
* top2.value(1)
*/
template <typename... Ts>
class FuncToken<std::tuple<Ts...>> :
public ExpressionToken<std::tuple<Ts...>>
{
private:
std::string identifier; ///> The name of the variable, e.g. top2
std::function<double(Feature const *)> function;
public:
FuncToken(std::shared_ptr<FeatureMap> featureMap,
std::function<double(Feature const *)> function,
std::string identifier)
:
//std::string function,
//std::vector<double> parameters) :
ExpressionToken<std::tuple<Ts...>>(featureMap)
{
this->identifier = identifier;
this->function = function;
//this->parameters = parameters;
}
bool evaluate(std::stack<double> & mystack,
std::string const& key,
std::tuple<Ts...> const& input)
{
//std::cout << "FuncToken evaluate " << std::endl;
if (this->featureMap->exists(key, identifier)) {
//std::cout << "Key identifier exists in feature map " << key << " "
// << identifier << std::endl;
try {
double d = this->featureMap->at(key, identifier)->evaluate(function);
//std::cout << "Got d " << d << std::endl;
mystack.push(d);
} catch (std::exception e) {
printf("Caught exception %s\n", e.what());
}
return true;
}
return false;
}
bool isOperator() const { return false; }
};
template <size_t field, typename... Ts>
class PrevToken : public ExpressionToken<Ts...>
{};
template <size_t field, typename... Ts>
class PrevToken<field, std::tuple<Ts...>> :
public ExpressionToken<std::tuple<Ts...>>
{
private:
// The identifier used to uniquely identify features produced by this
// ExpressionToken.
std::string identifier;
public:
PrevToken(std::shared_ptr<FeatureMap> featureMap) :
ExpressionToken<std::tuple<Ts...>>(featureMap)
{
identifier = createPreviousIdentifierString();
}
std::string getIdentifier() {
return identifier;
}
bool evaluate(std::stack<double> & mystack,
std::string const& key,
std::tuple<Ts...> const& input)
{
//std::cout << "PrevToken evaluate " << std::endl;
// Get the current value of the field.
double currentData;
try {
auto item = std::get<field>(input);
currentData = boost::lexical_cast<double>(item);
} catch (std::exception e) {
std::string message = std::string("In PrevToken::evaluate, tried to") +
" convert " + boost::lexical_cast<std::string>(std::get<field>(input)) +
" to double and failed.";
throw ExpressionTokenException(message);
}
// Create a feature out of the current data
std::shared_ptr<Feature> feature
= std::make_shared<SingleFeature>(currentData);
// Check to see if the feature has been added before
bool exists = false;
if (this->featureMap->exists(key, identifier)) {
// If the feature exists, we can return previous value
exists = true;
auto feature = this->featureMap->at(key, identifier);
// Getting the value of the feature through this function
auto valueFunc = [](Feature const * feature)->double {
return feature->getValue();
};
// Pushing back the previous value onto the stack.
double result = feature->template evaluate<double>(valueFunc);
mystack.push(result);
}
// Inserting the current data to become the past data
feature = std::make_shared<SingleFeature>(currentData);
this->featureMap->updateInsert(key, identifier, *feature);
return exists;
}
bool isOperator() const { return false; }
private:
/**
* We need to create a unique identifier for created features so that we
* can insert them into the featureMap. This, along with the key generated
* from the input, should be a unique combination.
*/
std::string createPreviousIdentifierString()
{
boost::uuids::uuid a = boost::uuids::random_generator()();
return "previous_" + boost::lexical_cast<std::string>(field) + "_" +
boost::uuids::to_string(a);
}
};
}
#endif
| 26.909091 | 83 | 0.62958 | [
"vector"
] |
a1c86c8fd3970157d8223eb9ed535a9db0923d87 | 2,964 | cpp | C++ | source/other/polygonreduction.cpp | PluginCafe/cinema4d_cpp_sdk | c613f6104f05649b909451f20014c3c923c43bfa | [
"Apache-2.0"
] | 26 | 2015-02-10T11:39:56.000Z | 2022-02-15T02:37:37.000Z | source/other/polygonreduction.cpp | PluginCafe/cinema4d_cpp_sdk | c613f6104f05649b909451f20014c3c923c43bfa | [
"Apache-2.0"
] | 5 | 2015-04-06T01:13:09.000Z | 2018-09-06T14:00:25.000Z | source/other/polygonreduction.cpp | PluginCafe/cinema4d_cpp_sdk | c613f6104f05649b909451f20014c3c923c43bfa | [
"Apache-2.0"
] | 18 | 2015-03-13T17:13:36.000Z | 2020-11-25T10:37:59.000Z | /////////////////////////////////////////////////////////////
// CINEMA 4D SDK //
/////////////////////////////////////////////////////////////
// (c) MAXON Computer GmbH, all rights reserved //
/////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
// Polygon Reduction API example
////////////////////////////////////////////////////////////////////////////////////
#include "c4d.h"
#include "lib_polygonreduction.h"
#include "c4d_symbols.h"
#include "main.h"
static const Int32 ID_POLYREDUCTON_TEST = 1038949;
class PolygonReductionCommand : public CommandData
{
public:
virtual Int32 GetState(BaseDocument* doc);
virtual Bool Execute(BaseDocument* doc);
};
Int32 PolygonReductionCommand::GetState(BaseDocument* doc)
{
BaseObject* activeObject = doc->GetActiveObject();
if (!doc || !activeObject || !activeObject->IsInstanceOf(Opolygon))
return 0;
return CMD_ENABLED;
}
Bool PolygonReductionCommand::Execute(BaseDocument* doc)
{
if (!doc)
return false;
// Get the selected object in the scene.
BaseObject* activeObject = doc->GetActiveObject();
if (!activeObject)
return true;
// Ensure the object is a polygon object.
// We need to make sure that only polygon objects are passed to the polygon reduction.
if (!activeObject->IsInstanceOf(Opolygon))
return true;
doc->StartUndo();
// Make a copy of the active object.
BaseObject* activeClone = static_cast<BaseObject*>(activeObject->GetClone(COPYFLAGS_0, nullptr));
if (!activeClone)
return false;
doc->InsertObject(activeClone, nullptr, nullptr);
// Undo for new object must be called always after the object is inserted in the document.
doc->AddUndo(UNDOTYPE_NEW, activeClone);
// Hide the original object
doc->AddUndo(UNDOTYPE_CHANGE, activeObject);
activeObject->SetEditorMode(MODE_OFF);
// Prepare the polygon reduction data and allocate the polygon reduction instance.
// Notice that thread is nullptr in PolygonReductionData. This means that the reduction will occur immediately and synchronously in the current thread.
PolygonReductionData polyReductionData = PolygonReductionData(doc, ToPoly(activeClone), nullptr);
AutoAlloc<PolygonReduction> polygonReduction;
if (!polygonReduction)
{
BaseObject::Free(activeClone);
doc->DoUndo();
return false;
}
// Prepare the reduction cache.
if (!polygonReduction->PreProcess(polyReductionData))
{
doc->DoUndo();
return false;
}
// Set the desired reduction level.
polygonReduction->SetReductionStrengthLevel(0.9);
doc->EndUndo();
activeClone->Message(MSG_UPDATE);
EventAdd();
return true;
}
Bool RegisterPolygonReductionTest()
{
return RegisterCommandPlugin(ID_POLYREDUCTON_TEST, String("Sync Polygon Reduction"), 0, nullptr, String("Apply Polygon Reduction to the selected Polygon Object"), NewObjClear(PolygonReductionCommand));
}
| 29.939394 | 203 | 0.65587 | [
"object"
] |
a1d297c5cf6ecf57a8ee26f7e3bec9fa416aaf74 | 4,867 | hpp | C++ | modules/3d/src/ptcloud/sac_segmentation.hpp | HattrickGenerator/opencv | 7554b53adfff8996e576691af4242f6f4acdc8f3 | [
"Apache-2.0"
] | null | null | null | modules/3d/src/ptcloud/sac_segmentation.hpp | HattrickGenerator/opencv | 7554b53adfff8996e576691af4242f6f4acdc8f3 | [
"Apache-2.0"
] | null | null | null | modules/3d/src/ptcloud/sac_segmentation.hpp | HattrickGenerator/opencv | 7554b53adfff8996e576691af4242f6f4acdc8f3 | [
"Apache-2.0"
] | 1 | 2021-04-30T18:00:41.000Z | 2021-04-30T18:00:41.000Z | // This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#ifndef OPENCV_3D_SAC_SEGMENTATION_HPP
#define OPENCV_3D_SAC_SEGMENTATION_HPP
#include "opencv2/3d/ptcloud.hpp"
namespace cv {
class SACSegmentationImpl : public SACSegmentation
{
private:
//! The type of sample consensus model used.
SacModelType sac_model_type;
//! The type of sample consensus method used.
SacMethod sac_method;
//! Considered as inlier point if distance to the model less than threshold.
double threshold;
//! The minimum and maximum radius limits for the model.
//! Only used for models whose model parameters include a radius.
double radius_min, radius_max;
//! The maximum number of iterations to attempt.
int max_iterations;
//! Confidence that ensure at least one of selections is an error-free set of data points.
double confidence;
//! Expected number of models.
int number_of_models_expected;
bool is_parallel;
//! 64-bit value used to initialize the RNG(Random Number Generator).
uint64 rng_state;
//! A user defined function that takes model coefficients and returns whether the model is acceptable or not.
ModelConstraintFunction custom_model_constraints;
/**
* @brief Execute segmentation of a single model using the sample consensus method.
*
* @param model_coeffs Point cloud data, it must be a 3xN CV_32F Mat.
* @param label label[i] is 1 means point i is inlier point of model
* @param model_coefficients The resultant model coefficients.
* @return number of model inliers
*/
int segmentSingle(Mat &model_coeffs, std::vector<bool> &label, Mat &model_coefficients);
public:
//! No-argument constructor using default configuration
SACSegmentationImpl(SacModelType sac_model_type_, SacMethod sac_method_,
double threshold_, int max_iterations_)
: sac_model_type(sac_model_type_), sac_method(sac_method_), threshold(threshold_),
radius_min(DBL_MIN), radius_max(DBL_MAX),
max_iterations(max_iterations_), confidence(0.999), number_of_models_expected(1),
is_parallel(false), rng_state(0),
custom_model_constraints()
{
}
int segment(InputArray input_pts, OutputArray labels, OutputArray models_coefficients) override;
//-------------------------- Getter and Setter -----------------------
void setSacModelType(SacModelType sac_model_type_) override
{ sac_model_type = sac_model_type_; }
SacModelType getSacModelType() const override
{ return sac_model_type; }
void setSacMethodType(SacMethod sac_method_) override
{ sac_method = sac_method_; }
SacMethod getSacMethodType() const override
{ return sac_method; }
void setDistanceThreshold(double threshold_) override
{ threshold = threshold_; }
double getDistanceThreshold() const override
{ return threshold; }
void setRadiusLimits(double radius_min_, double radius_max_) override
{ radius_min = radius_min_;
radius_max = radius_max_; }
void getRadiusLimits(double &radius_min_, double &radius_max_) const override
{ radius_min_ = radius_min;
radius_max_ = radius_max; }
void setMaxIterations(int max_iterations_) override
{ max_iterations = max_iterations_; }
int getMaxIterations() const override
{ return max_iterations; }
void setConfidence(double confidence_) override
{ confidence = confidence_; }
double getConfidence() const override
{ return confidence; }
void setNumberOfModelsExpected(int number_of_models_expected_) override
{ number_of_models_expected = number_of_models_expected_; }
int getNumberOfModelsExpected() const override
{ return number_of_models_expected; }
void setParallel(bool is_parallel_) override { is_parallel = is_parallel_; }
bool isParallel() const override { return is_parallel; }
void setRandomGeneratorState(uint64 rng_state_) override
{ rng_state = rng_state_; }
uint64 getRandomGeneratorState() const override
{ return rng_state; }
void
setCustomModelConstraints(const ModelConstraintFunction &custom_model_constraints_) override
{ custom_model_constraints = custom_model_constraints_; }
const ModelConstraintFunction &getCustomModelConstraints() const override
{ return custom_model_constraints; }
};
Ptr <SACSegmentation> SACSegmentation::create(SacModelType sac_model_type_, SacMethod sac_method_,
double threshold_, int max_iterations_)
{
return makePtr<SACSegmentationImpl>(sac_model_type_, sac_method_, threshold_, max_iterations_);
}
} //end namespace cv
#endif //OPENCV_3D_SAC_SEGMENTATION_HPP
| 33.798611 | 113 | 0.731046 | [
"vector",
"model",
"3d"
] |
a1d35996589d66cfe99b971e70c0557416fe90c8 | 1,245 | cpp | C++ | leetcode/_283_move_zeros.cpp | WindyDarian/OJ_Submissions | a323595c3a32ed2e07af65374ef90c81d5333f96 | [
"Apache-2.0"
] | 3 | 2017-02-19T14:38:32.000Z | 2017-07-22T17:06:55.000Z | leetcode/_283_move_zeros.cpp | WindyDarian/OJ_Submissions | a323595c3a32ed2e07af65374ef90c81d5333f96 | [
"Apache-2.0"
] | null | null | null | leetcode/_283_move_zeros.cpp | WindyDarian/OJ_Submissions | a323595c3a32ed2e07af65374ef90c81d5333f96 | [
"Apache-2.0"
] | null | null | null | //==============================================================================
// Copyright 2016 Windy Darian (Ruoyu Fan)
//
// 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.
//==============================================================================
// Created on Feb 5, 2017
// https://leetcode.com/problems/move-zeroes/
class Solution {
public:
void moveZeroes(vector<int>& nums)
{
auto slow = nums.begin();
auto end = nums.cend();
for (auto fast = nums.cbegin();fast!=end;fast++)
{
if (*fast != 0)
{
*slow = *fast;
slow++;
}
}
for (;slow!=end;slow++)
{
*slow = 0;
}
}
};
| 31.125 | 80 | 0.519679 | [
"vector"
] |
a1d4fb689f7567adcf413bb1f99250d1beefa36e | 45,309 | cpp | C++ | library/src/main/cpp/openjpg.cpp | AnonymousGeekDev/JP2ForAndroid | 1e16070f060eec993f34da2401efd4abffbb792d | [
"BSD-2-Clause"
] | 12 | 2019-07-02T12:23:53.000Z | 2020-03-15T17:32:43.000Z | library/src/main/cpp/openjpg.cpp | AnonymousGeekDev/JP2ForAndroid | 1e16070f060eec993f34da2401efd4abffbb792d | [
"BSD-2-Clause"
] | 1 | 2021-05-17T19:53:51.000Z | 2022-02-25T10:31:17.000Z | library/src/main/cpp/openjpg.cpp | AnonymousGeekDev/JP2ForAndroid | 1e16070f060eec993f34da2401efd4abffbb792d | [
"BSD-2-Clause"
] | 8 | 2020-09-05T22:03:02.000Z | 2022-03-18T09:03:02.000Z | // based on openjpeg-2.1.1/jni/openjpeg/src/bin/jp2/opj_decompress.c and opj_compress.c
#include "opj_config.h"
#include <jni.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "openjpeg.h"
typedef unsigned int OPJ_BITFIELD;
#include "event.h"
#include "function_list.h"
#include "thread.h"
#include "cio.h"
#include "j2k.h"
#include "jp2.h"
#include "opj_codec.h"
#include <android/log.h>
#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, "OpenJPEG",__VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG , "OpenJPEG",__VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO , "OpenJPEG",__VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN , "OpenJPEG",__VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR , "OpenJPEG",__VA_ARGS__)
#ifdef __cplusplus
extern "C" {
#endif
#include "color.h"
#define JP2_RFC3745_MAGIC "\x00\x00\x00\x0c\x6a\x50\x20\x20\x0d\x0a\x87\x0a"
#define JP2_MAGIC "\x0d\x0a\x87\x0a"
/* position 45: "\xff\x52" */
#define J2K_CODESTREAM_MAGIC "\xff\x4f\xff\x51"
#define MIN(a,b) ((a) > (b) ? (b) : (a))
#define MAX(a,b) ((a) < (b) ? (b) : (a))
//stores decoded image data
typedef struct image_data {
jint width;
jint height;
jint hasAlpha; //0 = false; 1 = true
int* pixels;
} image_data_t;
//stores decoded image header
typedef struct image_header {
jint width;
jint height;
jint hasAlpha; //0 = false; 1 = true
jint numResolutions;
jint numQualityLayers;
} image_header_t;
#define J2K_CFMT 0
#define JP2_CFMT 1
#define EXIT_SUCCESS 0
#define EXIT_FAILURE 1
int get_file_format(const char *filename) {
unsigned int i;
static const char *extension[] = {"j2k", "jp2", "j2c", "jpc" };
static const int format[] = { J2K_CFMT, JP2_CFMT, J2K_CFMT, J2K_CFMT };
const char * ext = strrchr(filename, '.');
if (ext == NULL)
return -1;
ext++;
if(ext) {
for(i = 0; i < sizeof(format)/sizeof(*format); i++) {
if(strcasecmp(ext, extension[i]) == 0) {
return format[i];
}
}
}
return -1;
}
static int get_magic_format(char *buf) {
int magic_format;
if (memcmp(buf, JP2_RFC3745_MAGIC, 12) == 0 || memcmp(buf, JP2_MAGIC, 4) == 0) {
magic_format = JP2_CFMT;
}
else if (memcmp(buf, J2K_CODESTREAM_MAGIC, 4) == 0) {
magic_format = J2K_CFMT;
} else {
return -1;
}
return magic_format;
}
static int infile_format(const char *fname)
{
FILE *reader;
const char *s, *magic_s;
int ext_format, magic_format;
unsigned char buf[12];
unsigned int l_nb_read;
reader = fopen(fname, "rb");
if (reader == NULL) {
LOGE("Error opening file %s for reading", fname);
return -2;
}
memset(buf, 0, 12);
l_nb_read = fread(buf, 1, 12, reader);
fclose(reader);
if (l_nb_read != 12) {
LOGE("Error reading header from file %s", fname);
return -1;
}
ext_format = get_file_format(fname);
magic_format = get_magic_format((char *)buf);
if (magic_format == JP2_CFMT) {
magic_s = ".jp2";
} else if (magic_format == J2K_CFMT) {
magic_s = ".j2k or .jpc or .j2c";
} else if (magic_format == -1) {
LOGE("Unrecognized file format");
return -1;
}
if (magic_format == ext_format)
return ext_format;
s = fname + strlen(fname) - 4;
LOGE("The extension of this file is incorrect.\nFOUND %s. SHOULD BE %s", s, magic_s);
return magic_format;
}
static int imagetoargb(opj_image_t *image, image_data_t *outImage) {
int w, h;
int i;
int adjustR, adjustG, adjustB, adjustA;
outImage->hasAlpha = false;
if (image->comps[0].prec < 8) {
LOGE("Unsupported number of components: %d\n", image->comps[0].prec);
return 1;
}
if (image->numcomps >= 3 && image->comps[0].dx == image->comps[1].dx
&& image->comps[1].dx == image->comps[2].dx
&& image->comps[0].dy == image->comps[1].dy
&& image->comps[1].dy == image->comps[2].dy
&& image->comps[0].prec == image->comps[1].prec
&& image->comps[1].prec == image->comps[2].prec) {
/* -->> -->> -->> -->>
24/32 bits color
<<-- <<-- <<-- <<-- */
w = image->comps[0].w;
h = image->comps[0].h;
outImage->pixels = (int *) malloc(sizeof(int) * w * h);
outImage->height = h;
outImage->width = w;
if (!outImage->pixels) {
LOGE("Could not allocate %d bytes of memory.\n", w * h * sizeof(int));
return 1;
}
if (image->comps[0].prec > 8) {
adjustR = image->comps[0].prec - 8;
printf("RGB CONVERSION: Truncating component 0 from %d bits to 8 bits\n", image->comps[0].prec);
}
else
adjustR = 0;
if (image->comps[1].prec > 8) {
adjustG = image->comps[1].prec - 8;
printf("RGB CONVERSION: Truncating component 1 from %d bits to 8 bits\n", image->comps[1].prec);
}
else
adjustG = 0;
if (image->comps[2].prec > 8) {
adjustB = image->comps[2].prec - 8;
printf("RGB CONVERSION: Truncating component 2 from %d bits to 8 bits\n", image->comps[2].prec);
}
else
adjustB = 0;
if (image->numcomps >= 4) { //alpha
outImage->hasAlpha = true;
if (image->comps[3].prec > 8) {
adjustA = image->comps[3].prec - 8;
printf("RGB CONVERSION: Truncating component 3 from %d bits to 8 bits\n", image->comps[3].prec);
}
else
adjustA = 0;
}
for (i = 0; i < w * h; i++) {
OPJ_UINT8 rc, gc, bc, ac;
int r, g, b, a;
r = image->comps[0].data[i];
r += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
r = ((r >> adjustR)/*+((r >> (adjustR-1))%2)*/);
if(r > 255) r = 255; else if(r < 0) r = 0;
rc = (OPJ_UINT8)r;
g = image->comps[1].data[i];
g += (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
g = ((g >> adjustG)/*+((g >> (adjustG-1))%2)*/);
if(g > 255) g = 255; else if(g < 0) g = 0;
gc = (OPJ_UINT8)g;
b = image->comps[2].data[i];
b += (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
b = ((b >> adjustB)/*+((b >> (adjustB-1))%2)*/);
if(b > 255) b = 255; else if(b < 0) b = 0;
bc = (OPJ_UINT8)b;
if (outImage->hasAlpha) {
a = image->comps[3].data[i];
a += (image->comps[3].sgnd ? 1 << (image->comps[3].prec - 1) : 0);
a = ((a >> adjustA)/*+((a >> (adjustA-1))%2)*/);
if (a > 255) a = 255; else if (a < 0) a = 0;
ac = (OPJ_UINT8) a;
} else {
ac = 0xFF;
}
outImage->pixels[i] = (ac << 24) | (rc << 16) | (gc << 8) | bc;
}
} else { /* Gray-scale */
/* -->> -->> -->> -->>
8 bits non code (Gray scale)
<<-- <<-- <<-- <<-- */
w = image->comps[0].w;
h = image->comps[0].h;
outImage->pixels = (int *) malloc(sizeof(int) * w * h);
outImage->height = h;
outImage->width = w;
if (!outImage->pixels) {
LOGE("Could not allocate %d bytes of memory.\n", w * h * sizeof(int));
return 1;
}
if (image->comps[0].prec > 8) {
adjustR = image->comps[0].prec - 8;
printf("BMP CONVERSION: Truncating component 0 from %d bits to 8 bits\n", image->comps[0].prec);
}else
adjustR = 0;
if (image->numcomps >= 2) { //alpha
outImage->hasAlpha = true;
if (image->comps[1].prec > 8) {
adjustA = image->comps[1].prec - 8;
printf("RGB CONVERSION: Truncating component 1 from %d bits to 8 bits\n", image->comps[1].prec);
}
else
adjustA = 0;
}
for (i = 0; i < w * h; i++) {
int r, a;
r = image->comps[0].data[i];
r += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
r = ((r >> adjustR)/*+((r >> (adjustR-1))%2)*/);
if(r > 255) r = 255; else if(r < 0) r = 0;
if (outImage->hasAlpha) {
a = image->comps[1].data[i];
a += (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
a = ((a >> adjustA)/*+((a >> (adjustA-1))%2)*/);
if (a > 255) a = 255; else if (a < 0) a = 0;
} else {
a = 0xFF;
}
outImage->pixels[i] = (a << 24) | (r << 16) | (r << 8) | r;
}
}
return 0;
}
/**
sample error callback expecting a FILE* client object
*/
static void error_callback(const char *msg, void *client_data) {
(void)client_data;
LOGE("[ERROR] %s", msg);
}
/**
sample warning callback expecting a FILE* client object
*/
static void warning_callback(const char *msg, void *client_data) {
(void)client_data;
LOGW("[WARNING] %s", msg);
}
/**
sample debug callback expecting no client object
*/
static void info_callback(const char *msg, void *client_data) {
(void)client_data;
LOGI("[INFO] %s", msg);
}
jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
JNIEnv* env;
if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
return -1;
}
// Get jclass with env->FindClass.
// Register methods with env->RegisterNatives.
return JNI_VERSION_1_6;
}
int readJ2KHeader(opj_codec_t* l_codec, int decod_format, image_header_t *outHeader) {
int compno;
opj_j2k* header;
if (l_codec == NULL) {
LOGE("Codec is null");
return EXIT_FAILURE;
}
switch(decod_format) {
case J2K_CFMT: /* JPEG-2000 codestream */
{
header = (opj_j2k *)((opj_codec_private_t *)l_codec)->m_codec;
break;
}
case JP2_CFMT: /* JPEG 2000 compressed image data */
{
header = ((opj_jp2_t*)((opj_codec_private_t *)l_codec)->m_codec)->j2k;
break;
}
default:
LOGE("Unknown file format");
return EXIT_FAILURE;
}
if (header == NULL || header->m_private_image == NULL) {
LOGE("Error getting header");
opj_destroy_codec(l_codec);
return EXIT_FAILURE;
}
memset(outHeader, 0, sizeof(image_header_t));
//select the size of the largest component (they can be different in case of subsampling)
outHeader->width = outHeader->height = 0;
for (unsigned int i = 0; i < header->m_private_image->numcomps; i++) {
outHeader->width = MAX(outHeader->width, header->m_private_image->comps[i].w);
outHeader->height = MAX(outHeader->height, header->m_private_image->comps[i].h);
}
outHeader->hasAlpha = (header->m_private_image->numcomps == 2 || header->m_private_image->numcomps == 4);
opj_tcp_t * l_default_tile = header->m_specific_param.m_decoder.m_default_tcp;
if (l_default_tile) {
outHeader->numQualityLayers = l_default_tile->numlayers;
//return the lowest number of resolutions in all components
for (compno = 0; compno < header->m_private_image->numcomps; compno++) {
opj_tccp_t *l_tccp = &(l_default_tile->tccps[compno]);
if (outHeader->numResolutions == 0) outHeader->numResolutions = l_tccp->numresolutions;
else outHeader->numResolutions = MIN(outHeader->numResolutions, l_tccp->numresolutions);
}
} else {
LOGW("Error reading default tile. Number of resolutions and quality layers could not be obtained.");
outHeader->numResolutions = 1;
outHeader->numQualityLayers = 1;
}
return EXIT_SUCCESS;
}
int decodeJP2Header(opj_stream_t *l_stream, opj_dparameters_t *parameters, image_header_t *outHeader) {
opj_codec_t* l_codec = NULL; /* Handle to a decompressor */
opj_image_t* image = NULL;
parameters->flags |= OPJ_DPARAMETERS_DUMP_FLAG;
/* decode the JPEG2000 stream */
/* ---------------------- */
switch(parameters->decod_format) {
case J2K_CFMT: /* JPEG-2000 codestream */
{
/* Get a decoder handle */
l_codec = opj_create_decompress(OPJ_CODEC_J2K);
break;
}
case JP2_CFMT: /* JPEG 2000 compressed image data */
{
/* Get a decoder handle */
l_codec = opj_create_decompress(OPJ_CODEC_JP2);
break;
}
default:
LOGE("Unknown file format");
return EXIT_FAILURE;
}
/* catch events using our callbacks and give a local context */
opj_set_info_handler(l_codec, info_callback,00);
opj_set_warning_handler(l_codec, warning_callback,00);
opj_set_error_handler(l_codec, error_callback,00);
/* Setup the decoder decoding parameters using user parameters */
if ( !opj_setup_decoder(l_codec, parameters) ){
LOGE("ERROR -> j2k_dump: failed to setup the decoder\n");
opj_destroy_codec(l_codec);
return EXIT_FAILURE;
}
/* Read the main header of the codestream and if necessary the JP2 boxes*/
if(! opj_read_header(l_stream, l_codec, &image)){
LOGE("ERROR -> opj_decompress: failed to read the header\n");
opj_destroy_codec(l_codec);
opj_image_destroy(image);
return EXIT_FAILURE;
}
if (readJ2KHeader(l_codec, parameters->decod_format, outHeader) != EXIT_SUCCESS) {
LOGE("Could not read header");
return EXIT_FAILURE;
}
/* free remaining structures */
if (l_codec) {
opj_destroy_codec(l_codec);
}
/* free image data structure */
opj_image_destroy(image);
return EXIT_SUCCESS;
}
int decodeJP2Stream(opj_stream_t *l_stream, opj_dparameters_t *parameters, image_data_t *outImage, jint reduce) {
opj_codec_t* l_codec = NULL; /* Handle to a decompressor */
opj_image_t* image = NULL;
image_header_t outHeader;
/* decode the JPEG2000 stream */
/* ---------------------- */
switch(parameters->decod_format) {
case J2K_CFMT: /* JPEG-2000 codestream */
{
/* Get a decoder handle */
l_codec = opj_create_decompress(OPJ_CODEC_J2K);
break;
}
case JP2_CFMT: /* JPEG 2000 compressed image data */
{
/* Get a decoder handle */
l_codec = opj_create_decompress(OPJ_CODEC_JP2);
break;
}
default:
LOGE("Unknown file format");
return EXIT_FAILURE;
}
/* catch events using our callbacks and give a local context */
opj_set_info_handler(l_codec, info_callback,00);
opj_set_warning_handler(l_codec, warning_callback,00);
opj_set_error_handler(l_codec, error_callback,00);
/* Setup the decoder decoding parameters using user parameters */
if ( !opj_setup_decoder(l_codec, parameters) ){
LOGE("ERROR -> j2k_dump: failed to setup the decoder\n");
opj_destroy_codec(l_codec);
return EXIT_FAILURE;
}
/* Read the main header of the codestream and if necessary the JP2 boxes*/
if(! opj_read_header(l_stream, l_codec, &image)){
LOGE("ERROR -> opj_decompress: failed to read the header\n");
opj_destroy_codec(l_codec);
opj_image_destroy(image);
return EXIT_FAILURE;
}
parameters->cp_reduce = reduce;
//check the decode parameters against the header - fix them if necessary
if (readJ2KHeader(l_codec, parameters->decod_format, &outHeader) == EXIT_SUCCESS) {
if (parameters->cp_reduce >= outHeader.numResolutions) {
LOGE("The number of resolutions to remove (%d) is greater or equal than the number of resolutions of this image (%d). Changing to %d.", parameters->cp_reduce, outHeader.numResolutions, outHeader.numResolutions - 1);
parameters->cp_reduce = outHeader.numResolutions - 1;
}
if (parameters->cp_layer > 0 && parameters->cp_layer > outHeader.numQualityLayers) {
/* It's too late to change the cp_layer value; it was already used in opj_read_header().
* But in this case we don't actually need to change it, because OpenJPEG quietly ignores it
* if the value is too high. So we just log this.
*/
LOGE("The number of quality layers to decode (%d) is greater than the number of quality layers of this image (%d). Changing to %d.", parameters->cp_layer, outHeader.numQualityLayers, outHeader.numQualityLayers);
}
}
/* Setup the decoder again with fixed parameters */
if ( !opj_setup_decoder(l_codec, parameters) ){
LOGE("ERROR -> j2k_dump: failed to setup the decoder\n");
opj_destroy_codec(l_codec);
return EXIT_FAILURE;
}
/* Optional if you want decode the entire image */
if (!opj_set_decode_area(l_codec, image, parameters->DA_x0,
parameters->DA_y0, parameters->DA_x1, parameters->DA_y1)){
LOGE("ERROR -> opj_decompress: failed to set the decoded area\n");
opj_destroy_codec(l_codec);
opj_image_destroy(image);
return EXIT_FAILURE;
}
/* Get the decoded image */
if (!(opj_decode(l_codec, l_stream, image) && opj_end_decompress(l_codec, l_stream))) {
LOGE("ERROR -> opj_decompress: failed to decode image!\n");
opj_destroy_codec(l_codec);
opj_image_destroy(image);
return EXIT_FAILURE;
}
/* Convert the decoded image data to RGB with no subsampling */
if (image->color_space != OPJ_CLRSPC_SYCC
&& image->numcomps == 3 && image->comps[0].dx == image->comps[0].dy
&& image->comps[1].dx != 1) {
image->color_space = OPJ_CLRSPC_SYCC;
} else if (image->numcomps <= 2) {
image->color_space = OPJ_CLRSPC_GRAY;
}
if (image->color_space == OPJ_CLRSPC_SYCC) {
color_sycc_to_rgb(image);
} else if ((image->color_space == OPJ_CLRSPC_CMYK)/* &&
(parameters.cod_format != TIF_DFMT)*/) {
color_cmyk_to_rgb(image);
} else if (image->color_space == OPJ_CLRSPC_EYCC) {
color_esycc_to_rgb(image);
}
if (image->icc_profile_buf) {
#if defined(OPJ_HAVE_LIBLCMS1) || defined(OPJ_HAVE_LIBLCMS2)
if (image->icc_profile_len) {
color_apply_icc_profile(image);
} else {
color_cielab_to_rgb(image);
}
#endif
free(image->icc_profile_buf);
image->icc_profile_buf = NULL;
image->icc_profile_len = 0;
}
//convert the image data to image_data_t which will be returned to Java
imagetoargb(image, outImage);
/* free remaining structures */
if (l_codec) {
opj_destroy_codec(l_codec);
}
/* free image data structure */
opj_image_destroy(image);
return EXIT_SUCCESS;
}
#define BYTE_ARRAY_SRC_CHUNK_LENGTH 4096
typedef struct opj_byte_array_source {
char * data;
unsigned int offset;
unsigned int length;
unsigned int availableLength;
} opj_byte_array_source;
static OPJ_SIZE_T opj_read_from_byte_array (void * p_buffer, OPJ_SIZE_T p_nb_bytes, opj_byte_array_source * p_user_data)
{
//LOGD("opj_read_from_byte_array started");
size_t toRead = MIN(p_nb_bytes, p_user_data->length - p_user_data->offset);
memcpy(p_buffer, p_user_data->data + p_user_data->offset, toRead);
p_user_data->offset += toRead;
//LOGD("opj_read_from_byte_array finished");
return toRead > 0 ? toRead : (OPJ_SIZE_T)-1;
}
static OPJ_SIZE_T opj_write_from_byte_array (void * p_buffer, OPJ_SIZE_T p_nb_bytes, opj_byte_array_source * p_user_data)
{
//LOGD("opj_write_from_byte_array started");
while (p_nb_bytes + p_user_data->offset > p_user_data->availableLength) {
//allocate bigger buffer
//LOGD("opj_write_from_byte_array - realloc");
char * newBuffer = (char *)realloc(p_user_data->data, p_user_data->availableLength + BYTE_ARRAY_SRC_CHUNK_LENGTH);
//LOGD("opj_write_from_byte_array - realloc succeeded");
if (newBuffer) {
p_user_data->data = newBuffer;
p_user_data->availableLength += BYTE_ARRAY_SRC_CHUNK_LENGTH;
} else {
p_nb_bytes = p_user_data->availableLength - p_user_data->offset;
}
}
memcpy(p_user_data->data + p_user_data->offset, p_buffer, p_nb_bytes);
p_user_data->offset += p_nb_bytes;
p_user_data->length = MAX(p_user_data->length, p_user_data->offset);
//LOGD("opj_write_from_byte_array finished");
return p_nb_bytes;
}
static OPJ_OFF_T opj_skip_from_byte_array (OPJ_OFF_T p_nb_bytes, opj_byte_array_source * p_user_data)
{
//LOGD("opj_skip_from_byte_array started");
while (p_nb_bytes + p_user_data->offset > p_user_data->availableLength) {
//allocate bigger buffer
//LOGD("opj_skip_from_byte_array - realloc");
char * newBuffer = (char *)realloc(p_user_data->data, p_user_data->availableLength + BYTE_ARRAY_SRC_CHUNK_LENGTH);
//LOGD("opj_skip_from_byte_array - realloc succeeded");
if (newBuffer) {
p_user_data->data = newBuffer;
memset(newBuffer + p_user_data->availableLength, 0, BYTE_ARRAY_SRC_CHUNK_LENGTH);
p_user_data->availableLength += BYTE_ARRAY_SRC_CHUNK_LENGTH;
} else {
//LOGD("opj_skip_from_byte_array end - returns -1");
return -1;
}
}
p_user_data->offset += p_nb_bytes;
//LOGD("opj_skip_from_byte_array finished successfully");
return p_nb_bytes;
}
static OPJ_BOOL opj_seek_from_byte_array (OPJ_OFF_T p_nb_bytes, opj_byte_array_source * p_user_data)
{
//LOGD("opj_seek_from_byte_array started");
while (p_nb_bytes > p_user_data->availableLength) {
//allocate bigger buffer
//LOGD("opj_seek_from_byte_array - realloc");
char * newBuffer = (char *)realloc(p_user_data->data, p_user_data->availableLength + BYTE_ARRAY_SRC_CHUNK_LENGTH);
//LOGD("opj_seek_from_byte_array - realloc succeeded");
if (newBuffer) {
p_user_data->data = newBuffer;
memset(newBuffer + p_user_data->availableLength, 0, BYTE_ARRAY_SRC_CHUNK_LENGTH);
p_user_data->availableLength += BYTE_ARRAY_SRC_CHUNK_LENGTH;
} else {
//LOGD("opj_seek_from_byte_array finished unsuccessfully");
return OPJ_FALSE;
}
}
if (p_nb_bytes > p_user_data->length) {
//LOGD("opj_seek_from_byte_array finished unsuccessfully");
return OPJ_FALSE;
}
p_user_data->offset = p_nb_bytes;
//LOGD("opj_seek_from_byte_array finished successfully");
return OPJ_TRUE;
}
opj_stream_t* OPJ_CALLCONV opj_stream_create_byte_array_stream ( char * data, unsigned int length,
OPJ_SIZE_T p_size,
OPJ_BOOL p_is_read_stream)
{
opj_stream_t* l_stream = 00;
l_stream = opj_stream_create(p_size,p_is_read_stream);
if (! l_stream) {
return NULL;
}
opj_byte_array_source * data_src = (opj_byte_array_source *)malloc(sizeof(opj_byte_array_source));
data_src->data = data;
data_src->offset = 0;
data_src->length = length;
data_src->availableLength = length;
opj_stream_set_user_data(l_stream, data_src, NULL);
opj_stream_set_user_data_length(l_stream, length);
opj_stream_set_read_function(l_stream, (opj_stream_read_fn) opj_read_from_byte_array);
opj_stream_set_write_function(l_stream, (opj_stream_write_fn) opj_write_from_byte_array);
opj_stream_set_skip_function(l_stream, (opj_stream_skip_fn) opj_skip_from_byte_array);
opj_stream_set_seek_function(l_stream, (opj_stream_seek_fn) opj_seek_from_byte_array);
return l_stream;
}
int setEncoderParameters(opj_cparameters_t *parameters, JNIEnv *env, jint fileFormat, jint numResolutions, jfloatArray compressionRates, jfloatArray qualityValues) {
int i;
jfloat *bufferPtr;
jsize dataLength;
/* set encoding parameters to default values */
opj_set_default_encoder_parameters(parameters);
//LOGD("1");
parameters->numresolution = numResolutions;
parameters->cod_format = fileFormat;
if (compressionRates) {
dataLength = env->GetArrayLength(compressionRates);
if (dataLength > 100) dataLength = 100; //opj_cparameters supports maximum of 100 quality layers
if (dataLength > 0) {
bufferPtr = env->GetFloatArrayElements(compressionRates, NULL);
parameters->tcp_numlayers = dataLength;
parameters->cp_disto_alloc = 1;
for (i = 0; i < dataLength; i++) {
parameters->tcp_rates[i] = bufferPtr[i];
}
env->ReleaseFloatArrayElements(compressionRates, bufferPtr, JNI_ABORT);
}
}
if (qualityValues) {
dataLength = env->GetArrayLength(qualityValues);
if (dataLength > 100) dataLength = 100; //opj_cparameters supports maximum of 100 quality layers
if (dataLength > 0) {
bufferPtr = env->GetFloatArrayElements(qualityValues, NULL);
parameters->cp_fixed_quality = 1;
parameters->tcp_numlayers = dataLength;
for (i = 0; i < dataLength; i++) {
parameters->tcp_distoratio[i] = bufferPtr[i];
}
env->ReleaseFloatArrayElements(qualityValues, bufferPtr, JNI_ABORT);
}
}
/* check for possible errors */
if (parameters->cp_cinema){
if(parameters->tcp_numlayers > 1){
parameters->cp_rsiz = OPJ_STD_RSIZ;
LOGW("Warning: DC profiles do not allow more than one quality layer. The codestream created will not be compliant with the DC profile");
}
}
if ((parameters->cp_disto_alloc || parameters->cp_fixed_alloc || parameters->cp_fixed_quality)
&& (!(parameters->cp_disto_alloc ^ parameters->cp_fixed_alloc ^ parameters->cp_fixed_quality))) {
LOGE("Error: options -r -q and -f cannot be used together !!");
return EXIT_FAILURE;
} /* mod fixed_quality */
/* if no rate entered, lossless by default */
if (parameters->tcp_numlayers == 0) {
parameters->tcp_rates[0] = 0; /* MOD antonin : losslessbug */
parameters->tcp_numlayers++;
parameters->cp_disto_alloc = 1;
}
if((parameters->cp_tx0 > parameters->image_offset_x0) || (parameters->cp_ty0 > parameters->image_offset_y0)) {
LOGE("Error: Tile offset dimension is unnappropriate --> TX0(%d)<=IMG_X0(%d) TYO(%d)<=IMG_Y0(%d) \n",
parameters->cp_tx0, parameters->image_offset_x0, parameters->cp_ty0, parameters->image_offset_y0);
return EXIT_FAILURE;
}
for (i = 0; i < parameters->numpocs; i++) {
if (parameters->POC[i].prg == -1) {
LOGW("Unrecognized progression order in option -P (POC n %d) [LRCP, RLCP, RPCL, PCRL, CPRL] !!\n", i + 1);
}
}
/* Create comment for codestream */
if(parameters->cp_comment == NULL) {
const char comment[] = "Created by OpenJPEG version ";
const size_t clen = strlen(comment);
const char *version = opj_version();
/* UniPG>> */
#ifdef USE_JPWL
parameters->cp_comment = (char*)malloc(clen+strlen(version)+11);
sprintf(parameters->cp_comment,"%s%s with JPWL", comment, version);
#else
parameters->cp_comment = (char*)malloc(clen+strlen(version)+1);
sprintf(parameters->cp_comment,"%s%s", comment, version);
#endif
/* <<UniPG */
}
//LOGD("2");
return EXIT_SUCCESS;
}
//convert raw bitmap pixels to opj_image_t structure
opj_image_t * getImage(JNIEnv *env, jintArray pixels, jboolean hasAlpha, jint width, jint height, opj_cparameters_t * parameters) {
opj_image_t *image = NULL;
int i;
jint *bufferPtr;
jsize dataLength;
int numcomps = hasAlpha ? 4 : 3;
OPJ_COLOR_SPACE color_space;
opj_image_cmptparm_t cmptparm[numcomps]; /* maximum of 3 components */
color_space = OPJ_CLRSPC_SRGB;
/* initialize image components */
memset(&cmptparm[0], 0, numcomps * sizeof(opj_image_cmptparm_t));
for(i = 0; i < numcomps; i++) {
cmptparm[i].prec = 8;
cmptparm[i].bpp = 8;
cmptparm[i].sgnd = 0;
cmptparm[i].dx = parameters->subsampling_dx;
cmptparm[i].dy = parameters->subsampling_dy;
cmptparm[i].w = (int)width;
cmptparm[i].h = (int)height;
}
/* create the image */
image = opj_image_create(numcomps, &cmptparm[0], color_space);
if (!image) {
LOGE("could not create image data structure");
return NULL;
}
//LOGD("3");
/* set image offset and reference grid */
image->x0 = parameters->image_offset_x0;
image->y0 = parameters->image_offset_y0;
image->x1 = !image->x0 ? (width - 1) * parameters->subsampling_dx + 1 : image->x0 + (width - 1) * parameters->subsampling_dx + 1;
image->y1 = !image->y0 ? (height - 1) * parameters->subsampling_dy + 1 : image->y0 + (height - 1) * parameters->subsampling_dy + 1;
//LOGD("4");
//copy bytes from java to the image structure
dataLength = env->GetArrayLength(pixels);
bufferPtr = env->GetIntArrayElements(pixels, NULL);
for (i = 0; i < width * height; i++) {
image->comps[0].data[i] = (bufferPtr[i] >> 16) & 0xFF; /* R */
image->comps[1].data[i] = (bufferPtr[i] >> 8) & 0xFF; /* G */
image->comps[2].data[i] = (bufferPtr[i] ) & 0xFF; /* B */
if (hasAlpha) image->comps[3].data[i] = (bufferPtr[i] >> 24 ) & 0xFF; /* A */
}
env->ReleaseIntArrayElements(pixels, bufferPtr, JNI_ABORT);
//LOGD("5");
return image;
}
//encode a opj_image_t (prepared from the raw bitmap data) into a JPEG-2000 byte array
int encodeJP2(opj_cparameters_t *parameters, opj_image_t *image, opj_byte_array_source ** outByteArray) {
int i, j;
opj_stream_private_t * l_stream = NULL;
opj_codec_t* l_codec = NULL;
opj_byte_array_source * jp2data = NULL;
OPJ_BOOL bSuccess;
/* Decide if MCT should be used */
parameters->tcp_mct = image->numcomps == 3 ? 1 : 0;
/* encode the destination image */
/* ---------------------------- */
switch(parameters->cod_format) {
case J2K_CFMT: /* JPEG-2000 codestream */
{
/* Get a decoder handle */
l_codec = opj_create_compress(OPJ_CODEC_J2K);
break;
}
case JP2_CFMT: /* JPEG 2000 compressed image data */
{
/* Get a decoder handle */
l_codec = opj_create_compress(OPJ_CODEC_JP2);
break;
}
default:
LOGE("Unknown output format");
opj_image_destroy(image);
return EXIT_FAILURE;
}
//LOGD("6");
/* catch events using our callbacks and give a local context */
opj_set_info_handler(l_codec, info_callback,00);
opj_set_warning_handler(l_codec, warning_callback,00);
opj_set_error_handler(l_codec, error_callback,00);
opj_setup_encoder(l_codec, parameters, image);
//LOGD("7");
/* open a byte stream for writing and allocate memory for all tiles */
if (parameters->outfile[0] != 0) {
/* open a byte stream for writing and allocate memory for all tiles */
l_stream = (opj_stream_private_t *)opj_stream_create_default_file_stream(parameters->outfile, OPJ_FALSE);
} else {
l_stream = (opj_stream_private_t *)opj_stream_create_byte_array_stream(NULL, 0, OPJ_J2K_STREAM_CHUNK_SIZE, OPJ_FALSE);
jp2data = (opj_byte_array_source *)l_stream->m_user_data;
}
if (! l_stream){
opj_destroy_codec(l_codec);
opj_image_destroy(image);
return EXIT_FAILURE;
}
//LOGD("8");
/* encode the image */
bSuccess = opj_start_compress(l_codec,image,(opj_stream_t*)l_stream);
if (!bSuccess) {
LOGE("failed to encode image: opj_start_compress");
} else {
//LOGD("9");
bSuccess = bSuccess && opj_encode(l_codec, (opj_stream_t*)l_stream);
if (!bSuccess) {
LOGE("failed to encode image: opj_encode");
} else {
//LOGD("10");
bSuccess = bSuccess && opj_end_compress(l_codec, (opj_stream_t*)l_stream);
if (!bSuccess) {
LOGE("failed to encode image: opj_end_compress");
} else {
LOGI("Generated JPEG2000 data");
}
}
}
//LOGD("11");
/* close and free the byte stream */
opj_stream_destroy((opj_stream_t*)l_stream);
//LOGD("12");
/* free remaining compression structures */
opj_destroy_codec(l_codec);
//LOGD("13");
/* free image data */
opj_image_destroy(image);
//LOGD("14");
if (!bSuccess) {
if (jp2data) {
free(jp2data->data);
free(jp2data);
}
return EXIT_FAILURE;
}
if (outByteArray) *outByteArray = jp2data;
//LOGD("15");
return EXIT_SUCCESS;
}
//encode a raw bitmap into JPEG-2000, return the result in a byte array
JNIEXPORT jbyteArray JNICALL Java_com_gemalto_jp2_JP2Encoder_encodeJP2ByteArray(JNIEnv *env, jclass thiz, jintArray pixels, jboolean hasAlpha, jint width, jint height,
jint fileFormat, jint numResolutions, jfloatArray compressionRates, jfloatArray qualityValues) {
opj_byte_array_source * jp2data = NULL;
opj_cparameters_t parameters; /* compression parameters */
opj_image_t *image = NULL;
if (setEncoderParameters(¶meters, env, fileFormat, numResolutions, compressionRates, qualityValues) != EXIT_SUCCESS) {
return NULL;
}
parameters.outfile[0] = 0;
image = getImage(env, pixels, hasAlpha, width, height, ¶meters);
if (!image) {
return NULL;
}
if (encodeJP2(¶meters, image, &jp2data) != EXIT_SUCCESS) {
LOGE("Error encoding JP2 data");
return NULL;
}
jbyteArray ret = env->NewByteArray(jp2data->length);
//LOGD("16, jp2data->data = %d, jp2data->offset = %d, jp2data->length = %d, jp2data->availableLength = %d", jp2data->data, jp2data->offset, jp2data->length, jp2data->availableLength);
env->SetByteArrayRegion(ret, 0, jp2data->length, (jbyte *)jp2data->data);
//LOGD("17");
if (parameters.cp_comment != NULL) {
free(parameters.cp_comment);
}
free(jp2data->data);
free(jp2data);
return ret;
}
//encode a raw bitmap into JPEG-2000, store the result into a file, return success/failure
JNIEXPORT jint JNICALL Java_com_gemalto_jp2_JP2Encoder_encodeJP2File(JNIEnv *env, jclass thiz, jstring fileName, jintArray pixels, jboolean hasAlpha, jint width, jint height,
jint fileFormat, jint numResolutions, jfloatArray compressionRates, jfloatArray qualityValues) {
opj_cparameters_t parameters; /* compression parameters */
opj_image_t *image = NULL;
const char *c_file;
if (setEncoderParameters(¶meters, env, fileFormat, numResolutions, compressionRates, qualityValues) != EXIT_SUCCESS) {
return EXIT_FAILURE;
}
c_file = env->GetStringUTFChars(fileName, NULL);
strcpy(parameters.outfile, c_file);
env->ReleaseStringUTFChars(fileName, c_file);
image = getImage(env, pixels, hasAlpha, width, height, ¶meters);
if (!image) {
return EXIT_FAILURE;
}
return encodeJP2(¶meters, image, NULL);
}
//convert the image_data_t to integer array (use first 3 integers for width, height, and alpha information, then append the raw pixel data)
jintArray prepareReturnData(JNIEnv *env, image_data_t *outImage) {
//prepare return data: first three integers in the array are width, height, hasAlpha, then image pixels
jintArray ret = env->NewIntArray(outImage->width * outImage->height + 3);
env->SetIntArrayRegion(ret, 0, 3, (jint*)outImage);
env->SetIntArrayRegion(ret, 3, outImage->width * outImage->height, outImage->pixels);
free(outImage->pixels);
outImage->pixels = NULL;
return ret;
}
//convert a image_header_t to an integer array
jintArray prepareReturnHeaderData(JNIEnv *env, image_header_t *outHeader) {
//prepare return data: first three integers in the array are width, height, hasAlpha, then image pixels
int length = sizeof(image_header_t) / sizeof(jint);
jintArray ret = env->NewIntArray(length);
env->SetIntArrayRegion(ret, 0, length, (jint*)outHeader);
return ret;
}
//decode a JPEG-2000 encoded file, return in 32-bit raw RGBA pixels
JNIEXPORT jintArray JNICALL Java_com_gemalto_jp2_JP2Decoder_decodeJP2File(JNIEnv *env, jclass thiz, jstring fileName, jint reduce, jint layers) {
opj_stream_t *l_stream = NULL; /* Stream */
opj_dparameters_t parameters; /* decompression parameters */
image_data_t outImage; //output data
jintArray ret = NULL;
//sanity check
if (fileName == NULL) {
LOGE("fileName is NULL!");
return NULL;
}
/* set decoding parameters to default values */
opj_set_default_decoder_parameters(¶meters);
const char *c_file = env->GetStringUTFChars(fileName, NULL);
strcpy(parameters.infile, c_file);
env->ReleaseStringUTFChars(fileName, c_file);
parameters.decod_format = infile_format(parameters.infile);
parameters.cp_layer = layers;
//We don't set the reduce parameter yet, because if it's too high, it would throw an error.
//We will set it after we read the image header and find out actual number of resolutions.
/* read the input file and put it in memory */
/* ---------------------------------------- */
l_stream = opj_stream_create_default_file_stream(parameters.infile,1);
if (!l_stream){
LOGE("ERROR -> failed to create the stream from the file\n");
return NULL;
}
if (decodeJP2Stream(l_stream, ¶meters, &outImage, reduce) == EXIT_SUCCESS) {
ret = prepareReturnData(env, &outImage);
}
/* Close the byte stream */
opj_stream_destroy(l_stream);
return ret;
}
//decode a JPEG-2000 encoded byte array, return in 32-bit raw RGBA pixels
JNIEXPORT jintArray JNICALL Java_com_gemalto_jp2_JP2Decoder_decodeJP2ByteArray(JNIEnv *env, jclass thiz, jbyteArray data, jint reduce, jint layers) {
opj_stream_t *l_stream = NULL; /* Stream */
opj_dparameters_t parameters; /* decompression parameters */
char *imgData;
jbyte *bufferPtr;
jsize dataLength;
opj_byte_array_source * streamData = NULL;
image_data_t outImage; //output data
jintArray ret = NULL;
//sanity check
if (data == NULL) {
LOGE("data is NULL!");
return NULL;
}
/* set decoding parameters to default values */
opj_set_default_decoder_parameters(¶meters);
//copy bytes from java
dataLength = env->GetArrayLength(data);
bufferPtr = env->GetByteArrayElements(data, NULL);
imgData = (char *)malloc(dataLength * sizeof(char));
memcpy(imgData, bufferPtr, dataLength);
env->ReleaseByteArrayElements(data, bufferPtr, JNI_ABORT);
parameters.decod_format = get_magic_format(imgData);
parameters.cp_layer = layers;
//We don't set the reduce parameter yet, because if it's too high, it would throw an error.
//We will set it after we read the image header and find out actual number of resolutions.
l_stream = opj_stream_create_byte_array_stream(imgData,dataLength,OPJ_J2K_STREAM_CHUNK_SIZE,1);
if (!l_stream){
LOGE("ERROR -> failed to create the stream from the byte array");
free(imgData);
return NULL;
}
streamData = (opj_byte_array_source *)((opj_stream_private_t *)l_stream)->m_user_data;
if (decodeJP2Stream(l_stream, ¶meters, &outImage, reduce) == EXIT_SUCCESS) {
ret = prepareReturnData(env, &outImage);
}
/* Close the byte stream */
opj_stream_destroy(l_stream);
free(streamData->data); //this is where the imgData is stored now
free(streamData);
return ret;
}
//read meta-data information from a JPEG-2000 encoded file, return in an integer array (image_header_t representation)
JNIEXPORT jintArray JNICALL Java_com_gemalto_jp2_JP2Decoder_readJP2HeaderFile(JNIEnv *env, jclass thiz, jstring fileName) {
opj_stream_t *l_stream = NULL; /* Stream */
opj_dparameters_t parameters; /* decompression parameters */
image_header_t outHeader; //output data
jintArray ret = NULL;
//sanity check
if (fileName == NULL) {
LOGE("fileName is NULL!");
return NULL;
}
/* set decoding parameters to default values */
opj_set_default_decoder_parameters(¶meters);
parameters.flags |= OPJ_DPARAMETERS_DUMP_FLAG;
const char *c_file = env->GetStringUTFChars(fileName, NULL);
strcpy(parameters.infile, c_file);
env->ReleaseStringUTFChars(fileName, c_file);
parameters.decod_format = infile_format(parameters.infile);
/* read the input file and put it in memory */
/* ---------------------------------------- */
l_stream = opj_stream_create_default_file_stream(parameters.infile,1);
if (!l_stream){
LOGE("ERROR -> failed to create the stream from the file\n");
return NULL;
}
if (decodeJP2Header(l_stream, ¶meters, &outHeader) == EXIT_SUCCESS) {
ret = prepareReturnHeaderData(env, &outHeader);
}
/* Close the byte stream */
opj_stream_destroy(l_stream);
return ret;
}
//read meta-data information from a JPEG-2000 encoded byte array, return in an integer array (image_header_t representation)
JNIEXPORT jintArray JNICALL Java_com_gemalto_jp2_JP2Decoder_readJP2HeaderByteArray(JNIEnv *env, jclass thiz, jbyteArray data) {
opj_stream_t *l_stream = NULL; /* Stream */
opj_dparameters_t parameters; /* decompression parameters */
char *imgData;
jbyte *bufferPtr;
jsize dataLength;
opj_byte_array_source * streamData = NULL;
image_header_t outHeader; //output data
jintArray ret = NULL;
//sanity check
if (data == NULL) {
LOGE("data is NULL!");
return NULL;
}
/* set decoding parameters to default values */
opj_set_default_decoder_parameters(¶meters);
parameters.flags |= OPJ_DPARAMETERS_DUMP_FLAG;
//copy bytes from java
dataLength = env->GetArrayLength(data);
bufferPtr = env->GetByteArrayElements(data, NULL);
imgData = (char *)malloc(dataLength * sizeof(char));
memcpy(imgData, bufferPtr, dataLength);
env->ReleaseByteArrayElements(data, bufferPtr, JNI_ABORT);
parameters.decod_format = get_magic_format(imgData);
l_stream = opj_stream_create_byte_array_stream(imgData,dataLength,OPJ_J2K_STREAM_CHUNK_SIZE,1);
if (!l_stream){
LOGE("ERROR -> failed to create the stream from the byte array");
free(imgData);
return NULL;
}
streamData = (opj_byte_array_source *)((opj_stream_private_t *)l_stream)->m_user_data;
if (decodeJP2Header(l_stream, ¶meters, &outHeader) == EXIT_SUCCESS) {
ret = prepareReturnHeaderData(env, &outHeader);
}
/* Close the byte stream */
opj_stream_destroy(l_stream);
free(streamData->data); //this is where the imgData is stored now
free(streamData);
return ret;
}
#ifdef __cplusplus
}
#endif | 36.89658 | 228 | 0.604229 | [
"object"
] |
a1d662654e8b03acb266aa01907f345ee1de60d7 | 79,645 | hpp | C++ | Lib/Chip/CM3/NXP/LPC15xx_v0.7/C_CAN0.hpp | cjsmeele/Kvasir | c8d2acd8313ae52d78259ee2d409b963925f77d7 | [
"Apache-2.0"
] | 376 | 2015-07-17T01:41:20.000Z | 2022-03-26T04:02:49.000Z | Lib/Chip/CM3/NXP/LPC15xx_v0.7/C_CAN0.hpp | cjsmeele/Kvasir | c8d2acd8313ae52d78259ee2d409b963925f77d7 | [
"Apache-2.0"
] | 59 | 2015-07-03T21:30:13.000Z | 2021-03-05T11:30:08.000Z | Lib/Chip/CM3/NXP/LPC15xx_v0.7/C_CAN0.hpp | cjsmeele/Kvasir | c8d2acd8313ae52d78259ee2d409b963925f77d7 | [
"Apache-2.0"
] | 53 | 2015-07-14T12:17:06.000Z | 2021-06-04T07:28:40.000Z | #pragma once
#include <Register/Utility.hpp>
namespace Kvasir {
//Controller Area Network C_CAN0
namespace CCan0Cntl{ ///<CAN control
using Addr = Register::Address<0x400f0000,0x00000000,0x00000000,unsigned>;
///Initialization
enum class InitVal {
normalOperation=0x00000000, ///<Normal operation.
started=0x00000001, ///<Started. Initialization is started. On reset, software needs to initialize the CAN controller.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,InitVal> init{};
namespace InitValC{
constexpr Register::FieldValue<decltype(init)::Type,InitVal::normalOperation> normalOperation{};
constexpr Register::FieldValue<decltype(init)::Type,InitVal::started> started{};
}
///Module interrupt enable
enum class IeVal {
disableCanInterrup=0x00000000, ///<Disable CAN interrupts. The interrupt line is always HIGH.
enableCanInterrupt=0x00000001, ///<Enable CAN interrupts. The interrupt line is set to LOW and remains LOW until all pending interrupts are cleared.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,IeVal> ie{};
namespace IeValC{
constexpr Register::FieldValue<decltype(ie)::Type,IeVal::disableCanInterrup> disableCanInterrup{};
constexpr Register::FieldValue<decltype(ie)::Type,IeVal::enableCanInterrupt> enableCanInterrupt{};
}
///Status change interrupt enable
enum class SieVal {
disableStatusChang=0x00000000, ///<Disable status change interrupts. No status change interrupt will be generated.
enableStatusChange=0x00000001, ///<Enable status change interrupts. A status change interrupt will be generated when a message transfer is successfully completed or a CAN bus error is detected.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,SieVal> sie{};
namespace SieValC{
constexpr Register::FieldValue<decltype(sie)::Type,SieVal::disableStatusChang> disableStatusChang{};
constexpr Register::FieldValue<decltype(sie)::Type,SieVal::enableStatusChange> enableStatusChange{};
}
///Error interrupt enable
enum class EieVal {
disableErrorInterr=0x00000000, ///<Disable error interrupt. No error status interrupt will be generated.
enableErrorInterru=0x00000001, ///<Enable error interrupt. A change in the bits BOFF or EWARN in the CANSTAT registers will generate an interrupt.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,EieVal> eie{};
namespace EieValC{
constexpr Register::FieldValue<decltype(eie)::Type,EieVal::disableErrorInterr> disableErrorInterr{};
constexpr Register::FieldValue<decltype(eie)::Type,EieVal::enableErrorInterru> enableErrorInterru{};
}
///reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> reserved{};
///Disable automatic retransmission
enum class DarVal {
enabled=0x00000000, ///<Enabled. Automatic retransmission of disturbed messages enabled.
disabled=0x00000001, ///<Disabled. Automatic retransmission disabled.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,DarVal> dar{};
namespace DarValC{
constexpr Register::FieldValue<decltype(dar)::Type,DarVal::enabled> enabled{};
constexpr Register::FieldValue<decltype(dar)::Type,DarVal::disabled> disabled{};
}
///Configuration change enable
enum class CceVal {
noWriteAccess=0x00000000, ///<No write access. The CPU has no write access to the bit timing register.
writeAccess=0x00000001, ///<Write access. The CPU has write access to the CANBT register while the INIT bit is one.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,CceVal> cce{};
namespace CceValC{
constexpr Register::FieldValue<decltype(cce)::Type,CceVal::noWriteAccess> noWriteAccess{};
constexpr Register::FieldValue<decltype(cce)::Type,CceVal::writeAccess> writeAccess{};
}
///Test mode enable
enum class TestVal {
normalOperation=0x00000000, ///<Normal operation.
testMode=0x00000001, ///<Test mode.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,TestVal> test{};
namespace TestValC{
constexpr Register::FieldValue<decltype(test)::Type,TestVal::normalOperation> normalOperation{};
constexpr Register::FieldValue<decltype(test)::Type,TestVal::testMode> testMode{};
}
///reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,8),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0Stat{ ///<Status register
using Addr = Register::Address<0x400f0004,0x00000000,0x00000000,unsigned>;
///Last error code Type of the last error to occur on the CAN bus.The LEC field holds a code which indicates the type of the last error to occur on the CAN bus. This field will be cleared to 0 when a message has been transferred (reception or transmission) without error. The unused code 111 may be written by the CPU to check for updates.
enum class LecVal {
noError=0x00000000, ///<No error.
stuffError=0x00000001, ///<Stuff error. More than 5 equal bits in a sequence have occurred in a part of a received message where this is not allowed.
formError=0x00000002, ///<Form error. A fixed format part of a received frame has the wrong format.
ackerror=0x00000003, ///<AckError. The message this CAN core transmitted was not acknowledged.
bit1error=0x00000004, ///<Bit1Error. During the transmission of a message (with the exception of the arbitration field), the device wanted to send a HIGH/recessive level (bit of logical value 1), but the monitored bus value was LOW/dominant.
bit0error=0x00000005, ///<Bit0Error. During the transmission of a message (or acknowledge bit, or active error flag, or overload flag), the device wanted to send a LOW/dominant level (data or identifier bit logical value 0), but the monitored Bus value was HIGH/recessive. During busoff recovery this status is set each time a sequence of 11 HIGH/recessive bits has been monitored. This enables the CPU to monitor the proceeding of the busoff recovery sequence (indicating the bus is not stuck at LOW/dominant or continuously disturbed).
crcerror=0x00000006, ///<CRCError. The CRC checksum was incorrect in the message received.
unused=0x00000007, ///<Unused. No CAN bus event was detected (written by the CPU).
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,0),Register::ReadWriteAccess,LecVal> lec{};
namespace LecValC{
constexpr Register::FieldValue<decltype(lec)::Type,LecVal::noError> noError{};
constexpr Register::FieldValue<decltype(lec)::Type,LecVal::stuffError> stuffError{};
constexpr Register::FieldValue<decltype(lec)::Type,LecVal::formError> formError{};
constexpr Register::FieldValue<decltype(lec)::Type,LecVal::ackerror> ackerror{};
constexpr Register::FieldValue<decltype(lec)::Type,LecVal::bit1error> bit1error{};
constexpr Register::FieldValue<decltype(lec)::Type,LecVal::bit0error> bit0error{};
constexpr Register::FieldValue<decltype(lec)::Type,LecVal::crcerror> crcerror{};
constexpr Register::FieldValue<decltype(lec)::Type,LecVal::unused> unused{};
}
///Transmitted a message successfully This bit must be reset by the CPU. It is never reset by the CAN controller.
enum class TxokVal {
noTransmit=0x00000000, ///<No transmit. Since this bit was last reset by the CPU, no message has been successfully transmitted.
successfulTransmit=0x00000001, ///<Successful transmit. Since this bit was last reset by the CPU, a message has been successfully transmitted (error free and acknowledged by at least one other node).
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,TxokVal> txok{};
namespace TxokValC{
constexpr Register::FieldValue<decltype(txok)::Type,TxokVal::noTransmit> noTransmit{};
constexpr Register::FieldValue<decltype(txok)::Type,TxokVal::successfulTransmit> successfulTransmit{};
}
///Received a message successfully This bit must be reset by the CPU. It is never reset by the CAN controller.
enum class RxokVal {
noReceive=0x00000000, ///<No receive. Since this bit was last reset by the CPU, no message has been successfully received.
successfulReceive=0x00000001, ///<Successful receive.Since this bit was last set to zero by the CPU, a message has been successfully received independent of the result of acceptance filtering.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,RxokVal> rxok{};
namespace RxokValC{
constexpr Register::FieldValue<decltype(rxok)::Type,RxokVal::noReceive> noReceive{};
constexpr Register::FieldValue<decltype(rxok)::Type,RxokVal::successfulReceive> successfulReceive{};
}
///Error passive
enum class EpassVal {
active=0x00000000, ///<Active. The CAN controller is in the error active state.
passive=0x00000001, ///<Passive. The CAN controller is in the error passive state as defined in the CAN 2.0 specification.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,EpassVal> epass{};
namespace EpassValC{
constexpr Register::FieldValue<decltype(epass)::Type,EpassVal::active> active{};
constexpr Register::FieldValue<decltype(epass)::Type,EpassVal::passive> passive{};
}
///Warning status
enum class EwarnVal {
belowLimit=0x00000000, ///<Below limit. Both error counters are below the error warning limit of 96.
atLimit=0x00000001, ///<At limit. At least one of the error counters in the EC has reached the error warning limit of 96.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,EwarnVal> ewarn{};
namespace EwarnValC{
constexpr Register::FieldValue<decltype(ewarn)::Type,EwarnVal::belowLimit> belowLimit{};
constexpr Register::FieldValue<decltype(ewarn)::Type,EwarnVal::atLimit> atLimit{};
}
///Busoff status
enum class BoffVal {
theCanModuleIsNo=0x00000000, ///<The CAN module is not in busoff.
theCanControllerI=0x00000001, ///<The CAN controller is in busoff state.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,BoffVal> boff{};
namespace BoffValC{
constexpr Register::FieldValue<decltype(boff)::Type,BoffVal::theCanModuleIsNo> theCanModuleIsNo{};
constexpr Register::FieldValue<decltype(boff)::Type,BoffVal::theCanControllerI> theCanControllerI{};
}
///reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,8),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0Ec{ ///<Error counter
using Addr = Register::Address<0x400f0008,0x00000000,0x00000000,unsigned>;
///Transmit error counter Current value of the transmit error counter (maximum value 255)
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> tec70{};
///Receive error counter Current value of the receive error counter (maximum value 127).
constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,8),Register::ReadWriteAccess,unsigned> rec60{};
///Receive error passive
enum class RpVal {
belowErrorLevel=0x00000000, ///<Below error level. The receive counter is below the error passive level.
atErrorLevel=0x00000001, ///<At error level. The receive counter has reached the error passive level as defined in the CAN2.0 specification.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,RpVal> rp{};
namespace RpValC{
constexpr Register::FieldValue<decltype(rp)::Type,RpVal::belowErrorLevel> belowErrorLevel{};
constexpr Register::FieldValue<decltype(rp)::Type,RpVal::atErrorLevel> atErrorLevel{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0Bt{ ///<Bit timing register
using Addr = Register::Address<0x400f000c,0x00000000,0x00000000,unsigned>;
///Baud rate prescaler The value by which the oscillator frequency is divided for generating the bit time quanta. The bit time is built up from a multiple of this quanta. Valid values for the Baud Rate Prescaler are 0 to 63.[1]
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,0),Register::ReadWriteAccess,unsigned> brp{};
///(Re)synchronization jump width Valid programmed values are 0 to 3.[1]
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,6),Register::ReadWriteAccess,unsigned> sjw{};
///Time segment before the sample point Valid values are 1 to 15.[1]
constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,8),Register::ReadWriteAccess,unsigned> tseg1{};
///Time segment after the sample point Valid values are 0 to 7.[1]
constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,12),Register::ReadWriteAccess,unsigned> tseg2{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,15),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0Int{ ///<Interrupt register
using Addr = Register::Address<0x400f0010,0x00000000,0x00000000,unsigned>;
///0x0000 = No interrupt is pending. 0x0001 - 0x0020 = Number of message object which caused the interrupt. 0x0021 - 0x7FFF = Unused 0x8000 = Status interrupt 0x8001 - 0xFFFF = Unused
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> intid{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0Test{ ///<Test register
using Addr = Register::Address<0x400f0014,0x00000000,0x00000000,unsigned>;
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,unsigned> reserved{};
///Basic mode
enum class BasicVal {
disabled=0x00000000, ///<Disabled. Basic mode disabled.
enabled=0x00000001, ///<Enabled. IF1 registers used as TX buffer, IF2 registers used as RX buffer.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,BasicVal> basic{};
namespace BasicValC{
constexpr Register::FieldValue<decltype(basic)::Type,BasicVal::disabled> disabled{};
constexpr Register::FieldValue<decltype(basic)::Type,BasicVal::enabled> enabled{};
}
///Silent mode
enum class SilentVal {
normalOperation=0x00000000, ///<Normal operation.
silentMode=0x00000001, ///<Silent mode. The module is in silent mode.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,SilentVal> silent{};
namespace SilentValC{
constexpr Register::FieldValue<decltype(silent)::Type,SilentVal::normalOperation> normalOperation{};
constexpr Register::FieldValue<decltype(silent)::Type,SilentVal::silentMode> silentMode{};
}
///Loop back mode
enum class LbackVal {
disabled=0x00000000, ///<Disabled. Loop back mode is disabled.
enabled=0x00000001, ///<Enabled. Loop back mode is enabled.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,LbackVal> lback{};
namespace LbackValC{
constexpr Register::FieldValue<decltype(lback)::Type,LbackVal::disabled> disabled{};
constexpr Register::FieldValue<decltype(lback)::Type,LbackVal::enabled> enabled{};
}
///Control of CAN_TXD pins
enum class TxVal {
controller=0x00000000, ///<Controller. Level at the CAN_TXD pin is controlled by the CAN controller. This is the value at reset.
samplePoint=0x00000001, ///<Sample point. The sample point can be monitored at the CAN_TXD pin.
low=0x00000002, ///<Low. CAN_TXD pin is driven LOW/dominant.
hogh=0x00000003, ///<Hogh. CAN_TXD pin is driven HIGH/recessive.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,5),Register::ReadWriteAccess,TxVal> tx{};
namespace TxValC{
constexpr Register::FieldValue<decltype(tx)::Type,TxVal::controller> controller{};
constexpr Register::FieldValue<decltype(tx)::Type,TxVal::samplePoint> samplePoint{};
constexpr Register::FieldValue<decltype(tx)::Type,TxVal::low> low{};
constexpr Register::FieldValue<decltype(tx)::Type,TxVal::hogh> hogh{};
}
///Monitors the actual value of the CAN_RXD pin.
enum class RxVal {
recessive=0x00000000, ///<Recessive. The CAN bus is recessive (CAN_RXD = 1).
dominant=0x00000001, ///<Dominant. The CAN bus is dominant (CAN_RXD = 0).
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,RxVal> rx{};
namespace RxValC{
constexpr Register::FieldValue<decltype(rx)::Type,RxVal::recessive> recessive{};
constexpr Register::FieldValue<decltype(rx)::Type,RxVal::dominant> dominant{};
}
///R/W
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,8),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0Brpe{ ///<Baud rate prescaler extension register
using Addr = Register::Address<0x400f0018,0x00000000,0x00000000,unsigned>;
///Baud rate prescaler extension By programming BRPE the Baud Rate Prescaler can be extended to values up to 1023. Hardware interprets the value as the value of BRPE (MSBs) and BRP (LSBs) plus one. Allowed values are 0 to 15.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> brpe{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,4),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0Txreq1{ ///<Transmission request 1
using Addr = Register::Address<0x400f0100,0x00000000,0x00000000,unsigned>;
///Transmission request bit of message objects 16 to 1. 0 = This message object is not waiting for transmission. 1 = The transmission of this message object is requested and not yet done.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> txrqst161{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0Txreq2{ ///<Transmission request 2
using Addr = Register::Address<0x400f0104,0x00000000,0x00000000,unsigned>;
///Transmission request bit of message objects 32 to 17. 0 = This message object is not waiting for transmission. 1 = The transmission of this message object is requested and not yet done.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> txrqst3217{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0Nd1{ ///<New data 1
using Addr = Register::Address<0x400f0120,0x00000000,0x00000000,unsigned>;
///New data bits of message objects 16 to 1. 0 = No new data has been written into the data portion of this Message Object by the Message Handler since last time this flag was cleared by the CPU. 1 = The Message Handler or the CPU has written new data into the data portion of this Message Object.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> newdat161{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0Nd2{ ///<New data 2
using Addr = Register::Address<0x400f0124,0x00000000,0x00000000,unsigned>;
///New data bits of message objects 32 to 17. 0 = No new data has been written into the data portion of this Message Object by the Message Handler since last time this flag was cleared by the CPU. 1 = The Message Handler or the CPU has written new data into the data portion of this Message Object.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> newdat3217{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0Ir1{ ///<Interrupt pending 1
using Addr = Register::Address<0x400f0140,0x00000000,0x00000000,unsigned>;
///Interrupt pending bits of message objects 16 to 1. 0 = This message object is ignored by the message handler. 1 = This message object is the source of an interrupt.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> intpnd161{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0Ir2{ ///<Interrupt pending 2
using Addr = Register::Address<0x400f0144,0x00000000,0x00000000,unsigned>;
///Interrupt pending bits of message objects 32 to 17. 0 = This message object is ignored by the message handler. 1 = This message object is the source of an interrupt.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> intpnd3217{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0Msgv1{ ///<Message valid 1
using Addr = Register::Address<0x400f0160,0x00000000,0x00000000,unsigned>;
///Message valid bits of message objects 16 to 1. 0 = This message object is ignored by the message handler. 1 = This message object is configured and should be considered by the message handler.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> msgval161{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0Msgv2{ ///<Message valid 2
using Addr = Register::Address<0x400f0164,0x00000000,0x00000000,unsigned>;
///Message valid bits of message objects 32 to 17. 0 = This message object is ignored by the message handler. 1 = This message object is configured and should be considered by the message handler.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> msgval3217{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0Clkdiv{ ///<CAN clock divider register
using Addr = Register::Address<0x400f0180,0x00000000,0x00000000,unsigned>;
///Clock divider value. CAN_CLK = system clock/(CLKDIVVAL +1) 0000: CAN_CLK = system clock divided by 1. 0001: CAN_CLK = system clock divided by 2. 0010: CAN_CLK = system clockdivided by 3 0011: CAN_CLK = system clock divided by 4. ... 1111: CAN_CLK = system clock divided by 16.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> clkdivval{};
///reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,4),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0If1Cmdreq{ ///<Message interface command request
using Addr = Register::Address<0x400f0020,0x00000000,0x00000000,unsigned>;
///Message number 0x01 - 0x20 = Valid message numbers. The message object in the message RAM is selected for data transfer. 0x00 = Not a valid message number. This value is interpreted as 0x20.[1] 0x21 - 0x3F = Not a valid message number. This value is interpreted as 0x01 - 0x1F.[1]
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,0),Register::ReadWriteAccess,unsigned> mn{};
///reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,6),Register::ReadWriteAccess,unsigned> reserved{};
///BUSY flag
enum class BusyVal {
done=0x00000000, ///<Done. Set to zero by hardware when read/write action to this Command request register has finished.
busy=0x00000001, ///<Busy. Set to one by hardware when writing to this Command request register.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,BusyVal> busy{};
namespace BusyValC{
constexpr Register::FieldValue<decltype(busy)::Type,BusyVal::done> done{};
constexpr Register::FieldValue<decltype(busy)::Type,BusyVal::busy> busy{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0If2Cmdreq{ ///<Message interface command request
using Addr = Register::Address<0x400f0080,0x00000000,0x00000000,unsigned>;
///Message number 0x01 - 0x20 = Valid message numbers. The message object in the message RAM is selected for data transfer. 0x00 = Not a valid message number. This value is interpreted as 0x20.[1] 0x21 - 0x3F = Not a valid message number. This value is interpreted as 0x01 - 0x1F.[1]
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,0),Register::ReadWriteAccess,unsigned> mn{};
///reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,6),Register::ReadWriteAccess,unsigned> reserved{};
///BUSY flag
enum class BusyVal {
done=0x00000000, ///<Done. Set to zero by hardware when read/write action to this Command request register has finished.
busy=0x00000001, ///<Busy. Set to one by hardware when writing to this Command request register.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,BusyVal> busy{};
namespace BusyValC{
constexpr Register::FieldValue<decltype(busy)::Type,BusyVal::done> done{};
constexpr Register::FieldValue<decltype(busy)::Type,BusyVal::busy> busy{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0If1CmdmskW{ ///<Message interface command mask (write direction)
using Addr = Register::Address<0x400f0024,0x00000000,0x00000000,unsigned>;
///Access data bytes 4-7
enum class DatabVal {
unchanged=0x00000000, ///<Unchanged. Data bytes 4-7 unchanged.
transfer=0x00000001, ///<Transfer. Transfer data bytes 4-7 to message object.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,DatabVal> dataB{};
namespace DatabValC{
constexpr Register::FieldValue<decltype(dataB)::Type,DatabVal::unchanged> unchanged{};
constexpr Register::FieldValue<decltype(dataB)::Type,DatabVal::transfer> transfer{};
}
///Access data bytes 0-3
enum class DataaVal {
unchanged=0x00000000, ///<Unchanged. Data bytes 0-3 unchanged.
transfer=0x00000001, ///<Transfer. Transfer data bytes 0-3 to message object.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,DataaVal> dataA{};
namespace DataaValC{
constexpr Register::FieldValue<decltype(dataA)::Type,DataaVal::unchanged> unchanged{};
constexpr Register::FieldValue<decltype(dataA)::Type,DataaVal::transfer> transfer{};
}
///Access transmission request bit
enum class TxrqstVal {
noTransmissionRequ=0x00000000, ///<No transmission request. TXRQSRT bit unchanged in IF1/2_MCTRL. If a transmission is requested by programming this bit, the TXRQST bit in the CANIFn_MCTRL register is ignored.
requestATransmissi=0x00000001, ///<Request a transmission. Set the TXRQST bit IF1/2_MCTRL.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,TxrqstVal> txrqst{};
namespace TxrqstValC{
constexpr Register::FieldValue<decltype(txrqst)::Type,TxrqstVal::noTransmissionRequ> noTransmissionRequ{};
constexpr Register::FieldValue<decltype(txrqst)::Type,TxrqstVal::requestATransmissi> requestATransmissi{};
}
///This bit is ignored in the write direction.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> clrintpnd{};
///Access control bits
enum class CtrlVal {
unchanged=0x00000000, ///<Unchanged. Control bits unchanged.
transfer=0x00000001, ///<Transfer. Transfer control bits to message object
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,CtrlVal> ctrl{};
namespace CtrlValC{
constexpr Register::FieldValue<decltype(ctrl)::Type,CtrlVal::unchanged> unchanged{};
constexpr Register::FieldValue<decltype(ctrl)::Type,CtrlVal::transfer> transfer{};
}
///Access arbitration bits
enum class ArbVal {
unchanged=0x00000000, ///<Unchanged. Arbitration bits unchanged.
transfer=0x00000001, ///<Transfer. Transfer Identifier, DIR, XTD, and MSGVAL bits to message object.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,ArbVal> arb{};
namespace ArbValC{
constexpr Register::FieldValue<decltype(arb)::Type,ArbVal::unchanged> unchanged{};
constexpr Register::FieldValue<decltype(arb)::Type,ArbVal::transfer> transfer{};
}
///Access mask bits
enum class MaskVal {
unchanged=0x00000000, ///<Unchanged. Mask bits unchanged.
transfer=0x00000001, ///<Transfer. Transfer Identifier MASK + MDIR + MXTD to message object.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,MaskVal> mask{};
namespace MaskValC{
constexpr Register::FieldValue<decltype(mask)::Type,MaskVal::unchanged> unchanged{};
constexpr Register::FieldValue<decltype(mask)::Type,MaskVal::transfer> transfer{};
}
///Write transfer Transfer data from the selected message buffer registers to the message object addressed by the command request register CANIFn_CMDREQ.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> wrRd{};
///reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,8),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0If2CmdmskW{ ///<Message interface command mask (write direction)
using Addr = Register::Address<0x400f0084,0x00000000,0x00000000,unsigned>;
///Access data bytes 4-7
enum class DatabVal {
unchanged=0x00000000, ///<Unchanged. Data bytes 4-7 unchanged.
transfer=0x00000001, ///<Transfer. Transfer data bytes 4-7 to message object.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,DatabVal> dataB{};
namespace DatabValC{
constexpr Register::FieldValue<decltype(dataB)::Type,DatabVal::unchanged> unchanged{};
constexpr Register::FieldValue<decltype(dataB)::Type,DatabVal::transfer> transfer{};
}
///Access data bytes 0-3
enum class DataaVal {
unchanged=0x00000000, ///<Unchanged. Data bytes 0-3 unchanged.
transfer=0x00000001, ///<Transfer. Transfer data bytes 0-3 to message object.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,DataaVal> dataA{};
namespace DataaValC{
constexpr Register::FieldValue<decltype(dataA)::Type,DataaVal::unchanged> unchanged{};
constexpr Register::FieldValue<decltype(dataA)::Type,DataaVal::transfer> transfer{};
}
///Access transmission request bit
enum class TxrqstVal {
noTransmissionRequ=0x00000000, ///<No transmission request. TXRQSRT bit unchanged in IF1/2_MCTRL. If a transmission is requested by programming this bit, the TXRQST bit in the CANIFn_MCTRL register is ignored.
requestATransmissi=0x00000001, ///<Request a transmission. Set the TXRQST bit IF1/2_MCTRL.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,TxrqstVal> txrqst{};
namespace TxrqstValC{
constexpr Register::FieldValue<decltype(txrqst)::Type,TxrqstVal::noTransmissionRequ> noTransmissionRequ{};
constexpr Register::FieldValue<decltype(txrqst)::Type,TxrqstVal::requestATransmissi> requestATransmissi{};
}
///This bit is ignored in the write direction.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> clrintpnd{};
///Access control bits
enum class CtrlVal {
unchanged=0x00000000, ///<Unchanged. Control bits unchanged.
transfer=0x00000001, ///<Transfer. Transfer control bits to message object
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,CtrlVal> ctrl{};
namespace CtrlValC{
constexpr Register::FieldValue<decltype(ctrl)::Type,CtrlVal::unchanged> unchanged{};
constexpr Register::FieldValue<decltype(ctrl)::Type,CtrlVal::transfer> transfer{};
}
///Access arbitration bits
enum class ArbVal {
unchanged=0x00000000, ///<Unchanged. Arbitration bits unchanged.
transfer=0x00000001, ///<Transfer. Transfer Identifier, DIR, XTD, and MSGVAL bits to message object.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,ArbVal> arb{};
namespace ArbValC{
constexpr Register::FieldValue<decltype(arb)::Type,ArbVal::unchanged> unchanged{};
constexpr Register::FieldValue<decltype(arb)::Type,ArbVal::transfer> transfer{};
}
///Access mask bits
enum class MaskVal {
unchanged=0x00000000, ///<Unchanged. Mask bits unchanged.
transfer=0x00000001, ///<Transfer. Transfer Identifier MASK + MDIR + MXTD to message object.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,MaskVal> mask{};
namespace MaskValC{
constexpr Register::FieldValue<decltype(mask)::Type,MaskVal::unchanged> unchanged{};
constexpr Register::FieldValue<decltype(mask)::Type,MaskVal::transfer> transfer{};
}
///Write transfer Transfer data from the selected message buffer registers to the message object addressed by the command request register CANIFn_CMDREQ.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> wrRd{};
///reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,8),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0If1CmdmskR{ ///<Message interface command mask (read direction)
using Addr = Register::Address<0x400f0024,0x00000000,0x00000000,unsigned>;
///Access data bytes 4-7
enum class DatabVal {
unchanged=0x00000000, ///<Unchanged. Data bytes 4-7 unchanged.
transfer=0x00000001, ///<Transfer. Transfer data bytes 4-7 to IFx message buffer register.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,DatabVal> dataB{};
namespace DatabValC{
constexpr Register::FieldValue<decltype(dataB)::Type,DatabVal::unchanged> unchanged{};
constexpr Register::FieldValue<decltype(dataB)::Type,DatabVal::transfer> transfer{};
}
///Access data bytes 0-3
enum class DataaVal {
unchanged=0x00000000, ///<Unchanged. Data bytes 0-3 unchanged.
transfer=0x00000001, ///<Transfer. Transfer data bytes 0-3 to IFx message buffer.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,DataaVal> dataA{};
namespace DataaValC{
constexpr Register::FieldValue<decltype(dataA)::Type,DataaVal::unchanged> unchanged{};
constexpr Register::FieldValue<decltype(dataA)::Type,DataaVal::transfer> transfer{};
}
///Access new data bit
enum class NewdatVal {
unchanged=0x00000000, ///<Unchanged. NEWDAT bit remains unchanged. A read access to a message object can be combined with the reset of the control bits INTPND and NEWDAT in IF1/2_MCTRL. The values of these bits transferred to the IFx Message Control Register always reflect the status before resetting these bits.
clear=0x00000001, ///<Clear. Clear NEWDAT bit in the message object.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,NewdatVal> newdat{};
namespace NewdatValC{
constexpr Register::FieldValue<decltype(newdat)::Type,NewdatVal::unchanged> unchanged{};
constexpr Register::FieldValue<decltype(newdat)::Type,NewdatVal::clear> clear{};
}
///Clear interrupt pending bit.
enum class ClrintpndVal {
unchanged=0x00000000, ///<Unchanged. INTPND bit remains unchanged.
clear=0x00000001, ///<Clear. Clear INTPND bit in the message object.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,ClrintpndVal> clrintpnd{};
namespace ClrintpndValC{
constexpr Register::FieldValue<decltype(clrintpnd)::Type,ClrintpndVal::unchanged> unchanged{};
constexpr Register::FieldValue<decltype(clrintpnd)::Type,ClrintpndVal::clear> clear{};
}
///Access control bits
enum class CtrlVal {
unchanged=0x00000000, ///<Unchanged. Control bits unchanged.
transfer=0x00000001, ///<Transfer. Transfer control bits to IFx message buffer.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,CtrlVal> ctrl{};
namespace CtrlValC{
constexpr Register::FieldValue<decltype(ctrl)::Type,CtrlVal::unchanged> unchanged{};
constexpr Register::FieldValue<decltype(ctrl)::Type,CtrlVal::transfer> transfer{};
}
///Access arbitration bits
enum class ArbVal {
unchanged=0x00000000, ///<Unchanged. Arbitration bits unchanged.
transfer=0x00000001, ///<Transfer. Transfer Identifier, DIR, XTD, and MSGVAL bits to IFx message buffer register.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,ArbVal> arb{};
namespace ArbValC{
constexpr Register::FieldValue<decltype(arb)::Type,ArbVal::unchanged> unchanged{};
constexpr Register::FieldValue<decltype(arb)::Type,ArbVal::transfer> transfer{};
}
///Access mask bits
enum class MaskVal {
unchanged=0x00000000, ///<Unchanged. Mask bits unchanged.
transfer=0x00000001, ///<Transfer. Transfer Identifier MASK + MDIR + MXTD to IFx message buffer register.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,MaskVal> mask{};
namespace MaskValC{
constexpr Register::FieldValue<decltype(mask)::Type,MaskVal::unchanged> unchanged{};
constexpr Register::FieldValue<decltype(mask)::Type,MaskVal::transfer> transfer{};
}
///Read transfer Transfer data from the message object addressed by the command request register to the selected message buffer registers CANIFn_CMDREQ.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> wrRd{};
///reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,8),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0If2CmdmskR{ ///<Message interface command mask (read direction)
using Addr = Register::Address<0x400f0084,0x00000000,0x00000000,unsigned>;
///Access data bytes 4-7
enum class DatabVal {
unchanged=0x00000000, ///<Unchanged. Data bytes 4-7 unchanged.
transfer=0x00000001, ///<Transfer. Transfer data bytes 4-7 to IFx message buffer register.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,DatabVal> dataB{};
namespace DatabValC{
constexpr Register::FieldValue<decltype(dataB)::Type,DatabVal::unchanged> unchanged{};
constexpr Register::FieldValue<decltype(dataB)::Type,DatabVal::transfer> transfer{};
}
///Access data bytes 0-3
enum class DataaVal {
unchanged=0x00000000, ///<Unchanged. Data bytes 0-3 unchanged.
transfer=0x00000001, ///<Transfer. Transfer data bytes 0-3 to IFx message buffer.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,DataaVal> dataA{};
namespace DataaValC{
constexpr Register::FieldValue<decltype(dataA)::Type,DataaVal::unchanged> unchanged{};
constexpr Register::FieldValue<decltype(dataA)::Type,DataaVal::transfer> transfer{};
}
///Access new data bit
enum class NewdatVal {
unchanged=0x00000000, ///<Unchanged. NEWDAT bit remains unchanged. A read access to a message object can be combined with the reset of the control bits INTPND and NEWDAT in IF1/2_MCTRL. The values of these bits transferred to the IFx Message Control Register always reflect the status before resetting these bits.
clear=0x00000001, ///<Clear. Clear NEWDAT bit in the message object.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,NewdatVal> newdat{};
namespace NewdatValC{
constexpr Register::FieldValue<decltype(newdat)::Type,NewdatVal::unchanged> unchanged{};
constexpr Register::FieldValue<decltype(newdat)::Type,NewdatVal::clear> clear{};
}
///Clear interrupt pending bit.
enum class ClrintpndVal {
unchanged=0x00000000, ///<Unchanged. INTPND bit remains unchanged.
clear=0x00000001, ///<Clear. Clear INTPND bit in the message object.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,ClrintpndVal> clrintpnd{};
namespace ClrintpndValC{
constexpr Register::FieldValue<decltype(clrintpnd)::Type,ClrintpndVal::unchanged> unchanged{};
constexpr Register::FieldValue<decltype(clrintpnd)::Type,ClrintpndVal::clear> clear{};
}
///Access control bits
enum class CtrlVal {
unchanged=0x00000000, ///<Unchanged. Control bits unchanged.
transfer=0x00000001, ///<Transfer. Transfer control bits to IFx message buffer.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,CtrlVal> ctrl{};
namespace CtrlValC{
constexpr Register::FieldValue<decltype(ctrl)::Type,CtrlVal::unchanged> unchanged{};
constexpr Register::FieldValue<decltype(ctrl)::Type,CtrlVal::transfer> transfer{};
}
///Access arbitration bits
enum class ArbVal {
unchanged=0x00000000, ///<Unchanged. Arbitration bits unchanged.
transfer=0x00000001, ///<Transfer. Transfer Identifier, DIR, XTD, and MSGVAL bits to IFx message buffer register.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,ArbVal> arb{};
namespace ArbValC{
constexpr Register::FieldValue<decltype(arb)::Type,ArbVal::unchanged> unchanged{};
constexpr Register::FieldValue<decltype(arb)::Type,ArbVal::transfer> transfer{};
}
///Access mask bits
enum class MaskVal {
unchanged=0x00000000, ///<Unchanged. Mask bits unchanged.
transfer=0x00000001, ///<Transfer. Transfer Identifier MASK + MDIR + MXTD to IFx message buffer register.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,MaskVal> mask{};
namespace MaskValC{
constexpr Register::FieldValue<decltype(mask)::Type,MaskVal::unchanged> unchanged{};
constexpr Register::FieldValue<decltype(mask)::Type,MaskVal::transfer> transfer{};
}
///Read transfer Transfer data from the message object addressed by the command request register to the selected message buffer registers CANIFn_CMDREQ.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> wrRd{};
///reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,8),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0If1Msk1{ ///<Message interface mask 1
using Addr = Register::Address<0x400f0028,0x00000000,0x00000000,unsigned>;
///Identifier mask [15:0]
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> msk150{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0If2Msk1{ ///<Message interface mask 1
using Addr = Register::Address<0x400f0088,0x00000000,0x00000000,unsigned>;
///Identifier mask [15:0]
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> msk150{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0If1Msk2{ ///<Message interface mask 2
using Addr = Register::Address<0x400f002c,0x00000000,0x00000000,unsigned>;
///Identifier mask [28:16]
constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,0),Register::ReadWriteAccess,unsigned> msk2816{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> reserved{};
///Mask message direction
enum class MdirVal {
withoutDirBit=0x00000000, ///<Without DIR bit. The message direction bit (DIR) has no effect on acceptance filtering.
withDirBit=0x00000001, ///<With DIR bit. The message direction bit (DIR) is used for acceptance filtering.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,MdirVal> mdir{};
namespace MdirValC{
constexpr Register::FieldValue<decltype(mdir)::Type,MdirVal::withoutDirBit> withoutDirBit{};
constexpr Register::FieldValue<decltype(mdir)::Type,MdirVal::withDirBit> withDirBit{};
}
///Mask extend identifier
enum class MxtdVal {
withoutXtd=0x00000000, ///<Without XTD. The extended identifier bit (XTD) has no effect on acceptance filtering.
withXtd=0x00000001, ///<With XTD. The extended identifier bit (XTD) is used for acceptance filtering.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,MxtdVal> mxtd{};
namespace MxtdValC{
constexpr Register::FieldValue<decltype(mxtd)::Type,MxtdVal::withoutXtd> withoutXtd{};
constexpr Register::FieldValue<decltype(mxtd)::Type,MxtdVal::withXtd> withXtd{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0If2Msk2{ ///<Message interface mask 2
using Addr = Register::Address<0x400f008c,0x00000000,0x00000000,unsigned>;
///Identifier mask [28:16]
constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,0),Register::ReadWriteAccess,unsigned> msk2816{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> reserved{};
///Mask message direction
enum class MdirVal {
withoutDirBit=0x00000000, ///<Without DIR bit. The message direction bit (DIR) has no effect on acceptance filtering.
withDirBit=0x00000001, ///<With DIR bit. The message direction bit (DIR) is used for acceptance filtering.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,MdirVal> mdir{};
namespace MdirValC{
constexpr Register::FieldValue<decltype(mdir)::Type,MdirVal::withoutDirBit> withoutDirBit{};
constexpr Register::FieldValue<decltype(mdir)::Type,MdirVal::withDirBit> withDirBit{};
}
///Mask extend identifier
enum class MxtdVal {
withoutXtd=0x00000000, ///<Without XTD. The extended identifier bit (XTD) has no effect on acceptance filtering.
withXtd=0x00000001, ///<With XTD. The extended identifier bit (XTD) is used for acceptance filtering.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,MxtdVal> mxtd{};
namespace MxtdValC{
constexpr Register::FieldValue<decltype(mxtd)::Type,MxtdVal::withoutXtd> withoutXtd{};
constexpr Register::FieldValue<decltype(mxtd)::Type,MxtdVal::withXtd> withXtd{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0If1Arb1{ ///<Message interface arbitration 1
using Addr = Register::Address<0x400f0030,0x00000000,0x00000000,unsigned>;
///Message identifier [15:0] 29-bit identifier (extended frame) 11-bit identifier (standard frame)
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> id150{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0If2Arb1{ ///<Message interface arbitration 1
using Addr = Register::Address<0x400f0090,0x00000000,0x00000000,unsigned>;
///Message identifier [15:0] 29-bit identifier (extended frame) 11-bit identifier (standard frame)
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> id150{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0If1Arb2{ ///<Message interface arbitration 2
using Addr = Register::Address<0x400f0034,0x00000000,0x00000000,unsigned>;
///Message identifier 29-bit identifier (extended frame) 11-bit identifier (standard frame)
constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,0),Register::ReadWriteAccess,unsigned> id2816{};
///Message direction
enum class DirVal {
receive=0x00000000, ///<Receive. On TXRQST, a Remote Frame with the identifier of this Message Object is transmitted. On reception of a Data Frame with matching identifier, that message is stored in this Message Object.
tansmit=0x00000001, ///<Tansmit. On TXRQST, the respective Message Object is transmitted as a Data Frame. On reception of a Remote Frame with matching identifier, the TXRQST bit of this Message Object is set (if RMTEN = one).
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,DirVal> dir{};
namespace DirValC{
constexpr Register::FieldValue<decltype(dir)::Type,DirVal::receive> receive{};
constexpr Register::FieldValue<decltype(dir)::Type,DirVal::tansmit> tansmit{};
}
///Extend identifier
enum class XtdVal {
standard=0x00000000, ///<Standard. The 11-bit standard identifier will be used for this message object.
extended=0x00000001, ///<Extended. The 29-bit extended identifier will be used for this message object.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,XtdVal> xtd{};
namespace XtdValC{
constexpr Register::FieldValue<decltype(xtd)::Type,XtdVal::standard> standard{};
constexpr Register::FieldValue<decltype(xtd)::Type,XtdVal::extended> extended{};
}
///Message valid The CPU must reset the MSGVAL bit of all unused Messages Objects during the initialization before it resets bit INIT in the CAN Control Register. This bit must also be reset before the identifier ID28:0, the control bits XTD, DIR, or the Data Length Code DLC3:0 are modified, or if the Messages Object is no longer required.
enum class MsgvalVal {
invalid=0x00000000, ///<Invalid. The message object is ignored by the message handler.
valid=0x00000001, ///<Valid. The message object is configured and should be considered by the message handler.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,MsgvalVal> msgval{};
namespace MsgvalValC{
constexpr Register::FieldValue<decltype(msgval)::Type,MsgvalVal::invalid> invalid{};
constexpr Register::FieldValue<decltype(msgval)::Type,MsgvalVal::valid> valid{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0If2Arb2{ ///<Message interface arbitration 2
using Addr = Register::Address<0x400f0094,0x00000000,0x00000000,unsigned>;
///Message identifier 29-bit identifier (extended frame) 11-bit identifier (standard frame)
constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,0),Register::ReadWriteAccess,unsigned> id2816{};
///Message direction
enum class DirVal {
receive=0x00000000, ///<Receive. On TXRQST, a Remote Frame with the identifier of this Message Object is transmitted. On reception of a Data Frame with matching identifier, that message is stored in this Message Object.
tansmit=0x00000001, ///<Tansmit. On TXRQST, the respective Message Object is transmitted as a Data Frame. On reception of a Remote Frame with matching identifier, the TXRQST bit of this Message Object is set (if RMTEN = one).
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,DirVal> dir{};
namespace DirValC{
constexpr Register::FieldValue<decltype(dir)::Type,DirVal::receive> receive{};
constexpr Register::FieldValue<decltype(dir)::Type,DirVal::tansmit> tansmit{};
}
///Extend identifier
enum class XtdVal {
standard=0x00000000, ///<Standard. The 11-bit standard identifier will be used for this message object.
extended=0x00000001, ///<Extended. The 29-bit extended identifier will be used for this message object.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,XtdVal> xtd{};
namespace XtdValC{
constexpr Register::FieldValue<decltype(xtd)::Type,XtdVal::standard> standard{};
constexpr Register::FieldValue<decltype(xtd)::Type,XtdVal::extended> extended{};
}
///Message valid The CPU must reset the MSGVAL bit of all unused Messages Objects during the initialization before it resets bit INIT in the CAN Control Register. This bit must also be reset before the identifier ID28:0, the control bits XTD, DIR, or the Data Length Code DLC3:0 are modified, or if the Messages Object is no longer required.
enum class MsgvalVal {
invalid=0x00000000, ///<Invalid. The message object is ignored by the message handler.
valid=0x00000001, ///<Valid. The message object is configured and should be considered by the message handler.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,MsgvalVal> msgval{};
namespace MsgvalValC{
constexpr Register::FieldValue<decltype(msgval)::Type,MsgvalVal::invalid> invalid{};
constexpr Register::FieldValue<decltype(msgval)::Type,MsgvalVal::valid> valid{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0If1Mctrl{ ///<Message interface message control
using Addr = Register::Address<0x400f0038,0x00000000,0x00000000,unsigned>;
///Data length code 3:0 The Data Length Code of a Message Object must be defined the same as in all the corresponding objects with the same identifier at other nodes. When the Message Handler stores a data frame, it will write the DLC to the value given by the received message. 0000 - 1000 = Data frame has 0 - 8 data bytes. 1001 - 1111 = Data frame has 8 data bytes.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> dlc30{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,4),Register::ReadWriteAccess,unsigned> reserved{};
///End of buffer
enum class EobVal {
notEndOfBuffer=0x00000000, ///<Not end of buffer. Message object belongs to a FIFO buffer and is not the last message object of that FIFO buffer.
endOfBuffer=0x00000001, ///<End of buffer. Single message object or last message object of a FIFO buffer.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,EobVal> eob{};
namespace EobValC{
constexpr Register::FieldValue<decltype(eob)::Type,EobVal::notEndOfBuffer> notEndOfBuffer{};
constexpr Register::FieldValue<decltype(eob)::Type,EobVal::endOfBuffer> endOfBuffer{};
}
///Transmit request
enum class TxrqstVal {
notWaiting=0x00000000, ///<Not waiting. This message object is not waiting for transmission.
waiting=0x00000001, ///<Waiting. The transmission of this message object is requested and is not yet done
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,TxrqstVal> txrqst{};
namespace TxrqstValC{
constexpr Register::FieldValue<decltype(txrqst)::Type,TxrqstVal::notWaiting> notWaiting{};
constexpr Register::FieldValue<decltype(txrqst)::Type,TxrqstVal::waiting> waiting{};
}
///Remote enable
enum class RmtenVal {
txrqstUnchanged=0x00000000, ///<TXRQST unchanged. At the reception of a remote frame, TXRQST is left unchanged.
txrqstSet=0x00000001, ///<TXRQST set. At the reception of a remote frame, TXRQST is set.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,RmtenVal> rmten{};
namespace RmtenValC{
constexpr Register::FieldValue<decltype(rmten)::Type,RmtenVal::txrqstUnchanged> txrqstUnchanged{};
constexpr Register::FieldValue<decltype(rmten)::Type,RmtenVal::txrqstSet> txrqstSet{};
}
///Receive interrupt enable
enum class RxieVal {
intpndUnchanged=0x00000000, ///<INTPND unchanged. INTPND will be left unchanged after successful reception of a frame.
intpndSet=0x00000001, ///<INTPND set. INTPND will be set after successful reception of a frame.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,RxieVal> rxie{};
namespace RxieValC{
constexpr Register::FieldValue<decltype(rxie)::Type,RxieVal::intpndUnchanged> intpndUnchanged{};
constexpr Register::FieldValue<decltype(rxie)::Type,RxieVal::intpndSet> intpndSet{};
}
///Transmit interrupt enable
enum class TxieVal {
intpndUnchanged=0x00000000, ///<INTPND unchanged. The INTPND bit will be left unchanged after a successful transmission of a frame.
intpndSet=0x00000001, ///<INTPND set. INTPND will be set after a successful transmission of a frame.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,TxieVal> txie{};
namespace TxieValC{
constexpr Register::FieldValue<decltype(txie)::Type,TxieVal::intpndUnchanged> intpndUnchanged{};
constexpr Register::FieldValue<decltype(txie)::Type,TxieVal::intpndSet> intpndSet{};
}
///Use acceptance mask If UMASK is set to 1, the message object's mask bits have to be programmed during initialization of the message object before MAGVAL is set to 1.
enum class UmaskVal {
ignore=0x00000000, ///<Ignore. Mask ignored.
use=0x00000001, ///<Use. Use mask (MSK[28:0], MXTD, and MDIR) for acceptance filtering.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,UmaskVal> umask{};
namespace UmaskValC{
constexpr Register::FieldValue<decltype(umask)::Type,UmaskVal::ignore> ignore{};
constexpr Register::FieldValue<decltype(umask)::Type,UmaskVal::use> use{};
}
///Interrupt pending
enum class IntpndVal {
notPending=0x00000000, ///<Not pending. This message object is not the source of an interrupt.
pending=0x00000001, ///<Pending. This message object is the source of an interrupt. The Interrupt Identifier in the Interrupt Register will point to this message object if there is no other interrupt source with higher priority.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,IntpndVal> intpnd{};
namespace IntpndValC{
constexpr Register::FieldValue<decltype(intpnd)::Type,IntpndVal::notPending> notPending{};
constexpr Register::FieldValue<decltype(intpnd)::Type,IntpndVal::pending> pending{};
}
///Message lost (only valid for message objects in the direction receive).
enum class MsglstVal {
notLost=0x00000000, ///<Not lost. No message lost since this bit was reset last by the CPU.
lost=0x00000001, ///<Lost. The Message Handler stored a new message into this object when NEWDAT was still set, the CPU has lost a message.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,MsglstVal> msglst{};
namespace MsglstValC{
constexpr Register::FieldValue<decltype(msglst)::Type,MsglstVal::notLost> notLost{};
constexpr Register::FieldValue<decltype(msglst)::Type,MsglstVal::lost> lost{};
}
///New data
enum class NewdatVal {
noNewData=0x00000000, ///<No new data. No new data has been written into the data portion of this message object by the message handler since this flag was cleared last by the CPU.
newData=0x00000001, ///<New data. The message handler or the CPU has written new data into the data portion of this message object.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,NewdatVal> newdat{};
namespace NewdatValC{
constexpr Register::FieldValue<decltype(newdat)::Type,NewdatVal::noNewData> noNewData{};
constexpr Register::FieldValue<decltype(newdat)::Type,NewdatVal::newData> newData{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0If2Mctrl{ ///<Message interface message control
using Addr = Register::Address<0x400f0098,0x00000000,0x00000000,unsigned>;
///Data length code 3:0 The Data Length Code of a Message Object must be defined the same as in all the corresponding objects with the same identifier at other nodes. When the Message Handler stores a data frame, it will write the DLC to the value given by the received message. 0000 - 1000 = Data frame has 0 - 8 data bytes. 1001 - 1111 = Data frame has 8 data bytes.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> dlc30{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,4),Register::ReadWriteAccess,unsigned> reserved{};
///End of buffer
enum class EobVal {
notEndOfBuffer=0x00000000, ///<Not end of buffer. Message object belongs to a FIFO buffer and is not the last message object of that FIFO buffer.
endOfBuffer=0x00000001, ///<End of buffer. Single message object or last message object of a FIFO buffer.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,EobVal> eob{};
namespace EobValC{
constexpr Register::FieldValue<decltype(eob)::Type,EobVal::notEndOfBuffer> notEndOfBuffer{};
constexpr Register::FieldValue<decltype(eob)::Type,EobVal::endOfBuffer> endOfBuffer{};
}
///Transmit request
enum class TxrqstVal {
notWaiting=0x00000000, ///<Not waiting. This message object is not waiting for transmission.
waiting=0x00000001, ///<Waiting. The transmission of this message object is requested and is not yet done
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,TxrqstVal> txrqst{};
namespace TxrqstValC{
constexpr Register::FieldValue<decltype(txrqst)::Type,TxrqstVal::notWaiting> notWaiting{};
constexpr Register::FieldValue<decltype(txrqst)::Type,TxrqstVal::waiting> waiting{};
}
///Remote enable
enum class RmtenVal {
txrqstUnchanged=0x00000000, ///<TXRQST unchanged. At the reception of a remote frame, TXRQST is left unchanged.
txrqstSet=0x00000001, ///<TXRQST set. At the reception of a remote frame, TXRQST is set.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,RmtenVal> rmten{};
namespace RmtenValC{
constexpr Register::FieldValue<decltype(rmten)::Type,RmtenVal::txrqstUnchanged> txrqstUnchanged{};
constexpr Register::FieldValue<decltype(rmten)::Type,RmtenVal::txrqstSet> txrqstSet{};
}
///Receive interrupt enable
enum class RxieVal {
intpndUnchanged=0x00000000, ///<INTPND unchanged. INTPND will be left unchanged after successful reception of a frame.
intpndSet=0x00000001, ///<INTPND set. INTPND will be set after successful reception of a frame.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,RxieVal> rxie{};
namespace RxieValC{
constexpr Register::FieldValue<decltype(rxie)::Type,RxieVal::intpndUnchanged> intpndUnchanged{};
constexpr Register::FieldValue<decltype(rxie)::Type,RxieVal::intpndSet> intpndSet{};
}
///Transmit interrupt enable
enum class TxieVal {
intpndUnchanged=0x00000000, ///<INTPND unchanged. The INTPND bit will be left unchanged after a successful transmission of a frame.
intpndSet=0x00000001, ///<INTPND set. INTPND will be set after a successful transmission of a frame.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,TxieVal> txie{};
namespace TxieValC{
constexpr Register::FieldValue<decltype(txie)::Type,TxieVal::intpndUnchanged> intpndUnchanged{};
constexpr Register::FieldValue<decltype(txie)::Type,TxieVal::intpndSet> intpndSet{};
}
///Use acceptance mask If UMASK is set to 1, the message object's mask bits have to be programmed during initialization of the message object before MAGVAL is set to 1.
enum class UmaskVal {
ignore=0x00000000, ///<Ignore. Mask ignored.
use=0x00000001, ///<Use. Use mask (MSK[28:0], MXTD, and MDIR) for acceptance filtering.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,UmaskVal> umask{};
namespace UmaskValC{
constexpr Register::FieldValue<decltype(umask)::Type,UmaskVal::ignore> ignore{};
constexpr Register::FieldValue<decltype(umask)::Type,UmaskVal::use> use{};
}
///Interrupt pending
enum class IntpndVal {
notPending=0x00000000, ///<Not pending. This message object is not the source of an interrupt.
pending=0x00000001, ///<Pending. This message object is the source of an interrupt. The Interrupt Identifier in the Interrupt Register will point to this message object if there is no other interrupt source with higher priority.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,IntpndVal> intpnd{};
namespace IntpndValC{
constexpr Register::FieldValue<decltype(intpnd)::Type,IntpndVal::notPending> notPending{};
constexpr Register::FieldValue<decltype(intpnd)::Type,IntpndVal::pending> pending{};
}
///Message lost (only valid for message objects in the direction receive).
enum class MsglstVal {
notLost=0x00000000, ///<Not lost. No message lost since this bit was reset last by the CPU.
lost=0x00000001, ///<Lost. The Message Handler stored a new message into this object when NEWDAT was still set, the CPU has lost a message.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,MsglstVal> msglst{};
namespace MsglstValC{
constexpr Register::FieldValue<decltype(msglst)::Type,MsglstVal::notLost> notLost{};
constexpr Register::FieldValue<decltype(msglst)::Type,MsglstVal::lost> lost{};
}
///New data
enum class NewdatVal {
noNewData=0x00000000, ///<No new data. No new data has been written into the data portion of this message object by the message handler since this flag was cleared last by the CPU.
newData=0x00000001, ///<New data. The message handler or the CPU has written new data into the data portion of this message object.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,NewdatVal> newdat{};
namespace NewdatValC{
constexpr Register::FieldValue<decltype(newdat)::Type,NewdatVal::noNewData> noNewData{};
constexpr Register::FieldValue<decltype(newdat)::Type,NewdatVal::newData> newData{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0If1Da1{ ///<Message interface data A1
using Addr = Register::Address<0x400f003c,0x00000000,0x00000000,unsigned>;
///Data byte 0
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> data0{};
///Data byte 1
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,8),Register::ReadWriteAccess,unsigned> data1{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0If2Da1{ ///<Message interface data A1
using Addr = Register::Address<0x400f009c,0x00000000,0x00000000,unsigned>;
///Data byte 0
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> data0{};
///Data byte 1
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,8),Register::ReadWriteAccess,unsigned> data1{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0If1Da2{ ///<Message interface 1 data A2
using Addr = Register::Address<0x400f0040,0x00000000,0x00000000,unsigned>;
///Data byte 2
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> data2{};
///Data byte 3
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,8),Register::ReadWriteAccess,unsigned> data3{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0If2Da2{ ///<Message interface 1 data A2
using Addr = Register::Address<0x400f00a0,0x00000000,0x00000000,unsigned>;
///Data byte 2
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> data2{};
///Data byte 3
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,8),Register::ReadWriteAccess,unsigned> data3{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0If1Db1{ ///<Message interface 1 data B1
using Addr = Register::Address<0x400f0044,0x00000000,0x00000000,unsigned>;
///Data byte 4
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> data4{};
///Data byte 5
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,8),Register::ReadWriteAccess,unsigned> data5{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0If2Db1{ ///<Message interface 1 data B1
using Addr = Register::Address<0x400f00a4,0x00000000,0x00000000,unsigned>;
///Data byte 4
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> data4{};
///Data byte 5
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,8),Register::ReadWriteAccess,unsigned> data5{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0If1Db2{ ///<Message interface 1 data B2
using Addr = Register::Address<0x400f0048,0x00000000,0x00000000,unsigned>;
///Data byte 6
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> data6{};
///Data byte 7
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,8),Register::ReadWriteAccess,unsigned> data7{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace CCan0If2Db2{ ///<Message interface 1 data B2
using Addr = Register::Address<0x400f00a8,0x00000000,0x00000000,unsigned>;
///Data byte 6
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> data6{};
///Data byte 7
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,8),Register::ReadWriteAccess,unsigned> data7{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{};
}
}
| 73.068807 | 553 | 0.689497 | [
"object"
] |
a1db181b088fd81eb757f5077dccfb53d694b7ed | 5,101 | cpp | C++ | wled00/ColorPalette/PaletteManager.cpp | mdraper81/WLED | 408696ef02f7b2dd66300a6a2ddb67a74d037b88 | [
"MIT"
] | null | null | null | wled00/ColorPalette/PaletteManager.cpp | mdraper81/WLED | 408696ef02f7b2dd66300a6a2ddb67a74d037b88 | [
"MIT"
] | null | null | null | wled00/ColorPalette/PaletteManager.cpp | mdraper81/WLED | 408696ef02f7b2dd66300a6a2ddb67a74d037b88 | [
"MIT"
] | null | null | null | #include "PaletteManager.h"
#include "StandardColors.h"
namespace ColorPalette
{
/*
** ============================================================================
** Constructor
** ============================================================================
*/
PaletteManager::PaletteManager()
{
// There will always be a default color palette that is used
std::vector<Color> colorList;
colorList.clear();
colorList.push_back(StandardColors::STD_COLOR_YELLOW);
mDefaultPalette = new Palette("Yellow", colorList);
LoadPalettes();
}
/*
** ============================================================================
** Destructor
** ============================================================================
*/
PaletteManager::~PaletteManager()
{
}
/*
** ============================================================================
** Loads the available palettes from the save file
** ============================================================================
*/
void PaletteManager::LoadPalettes()
{
// MDR DEBUG - TODO: Actually load palettes from a file
// If there are no color palettes available then we should reset to the
// defaults.
if (0 == mAvailablePalettes.size())
{
ResetToDefaultPalettes();
}
}
/*
** ============================================================================
** Saves the available palettes to the save file
** ============================================================================
*/
void PaletteManager::SavePalettes()
{
// MDR DEBUG - TODO: Actually save palettes to a file
}
/*
** ============================================================================
** Returns the list of available palette names
** ============================================================================
*/
PaletteManager::PaletteNameList PaletteManager::GetAvailablePalettes() const
{
PaletteNameList paletteNameList;
for (auto entry : mAvailablePalettes)
{
std::string paletteName = entry.first;
paletteNameList.push_back(paletteName);
}
return paletteNameList;
}
/*
** ============================================================================
** Returns the color palette at the given index.
** param paletteName - name of the palette to get
** NOTE: If the index is out of bounds, this will return the default palette
** ============================================================================
*/
const Palette& PaletteManager::GetPalette(std::string paletteName) const
{
PaletteMap::const_iterator findIter = mAvailablePalettes.find(paletteName);
if (findIter == mAvailablePalettes.end())
{
return *mDefaultPalette;
}
return findIter->second;
}
/*
** ============================================================================
** This will reset the available palettes to the default list of palettes
** ============================================================================
*/
void PaletteManager::ResetToDefaultPalettes()
{
std::vector<Color> colorList;
colorList.clear();
colorList.push_back(StandardColors::STD_COLOR_RED);
colorList.push_back(StandardColors::STD_COLOR_WHITE);
Palette candyCane("Candy Cane", colorList);
mAvailablePalettes.insert({"Candy Cane", candyCane});
colorList.clear();
colorList.push_back(StandardColors::STD_COLOR_RED);
colorList.push_back(StandardColors::STD_COLOR_GREEN);
Palette christmas("Christmas", colorList);
mAvailablePalettes.insert({"Christmas", christmas});
colorList.clear();
colorList.push_back(StandardColors::STD_COLOR_RED);
colorList.push_back(StandardColors::STD_COLOR_BLUE);
Palette police("Police", colorList);
mAvailablePalettes.insert({"Police", police});
colorList.clear();
colorList.push_back(StandardColors::STD_COLOR_BLACK);
colorList.push_back(StandardColors::STD_COLOR_BLUE);
colorList.push_back(StandardColors::STD_COLOR_GREEN);
colorList.push_back(StandardColors::STD_COLOR_ORANGE);
colorList.push_back(StandardColors::STD_COLOR_PURPLE);
colorList.push_back(StandardColors::STD_COLOR_RED);
colorList.push_back(StandardColors::STD_COLOR_ULTRAWHITE);
colorList.push_back(StandardColors::STD_COLOR_WHITE);
colorList.push_back(StandardColors::STD_COLOR_YELLOW);
Palette testPattern("Test Pattern", colorList);
mAvailablePalettes.insert({"Test Pattern", testPattern});
colorList.clear();
colorList.push_back(StandardColors::STD_COLOR_RED);
colorList.push_back(StandardColors::STD_COLOR_ORANGE);
colorList.push_back(StandardColors::STD_COLOR_YELLOW);
colorList.push_back(StandardColors::STD_COLOR_GREEN);
colorList.push_back(StandardColors::STD_COLOR_BLUE);
colorList.push_back(StandardColors::STD_COLOR_PURPLE);
Palette rainbow("Rainbow", colorList);
mAvailablePalettes.insert({"Rainbow", rainbow});
colorList.clear();
colorList.push_back(StandardColors::STD_COLOR_YELLOW);
Palette yellow("Yellow", colorList);
mAvailablePalettes.insert({"Yellow", yellow});
}
} // namespace ColorPalette
| 33.339869 | 79 | 0.574005 | [
"vector"
] |
a1ddce1c14d5bfc03cc159705ee307c5cf127283 | 16,466 | cpp | C++ | be/src/serde/column_array_serde.cpp | stephen-shelby/starrocks | 67932670efddbc8c56e2aaf5d3758724dcb44b0a | [
"Zlib",
"PSF-2.0",
"BSD-2-Clause",
"Apache-2.0",
"ECL-2.0",
"BSD-3-Clause-Clear"
] | 1 | 2022-03-08T09:13:32.000Z | 2022-03-08T09:13:32.000Z | be/src/serde/column_array_serde.cpp | stephen-shelby/starrocks | 67932670efddbc8c56e2aaf5d3758724dcb44b0a | [
"Zlib",
"PSF-2.0",
"BSD-2-Clause",
"Apache-2.0",
"ECL-2.0",
"BSD-3-Clause-Clear"
] | null | null | null | be/src/serde/column_array_serde.cpp | stephen-shelby/starrocks | 67932670efddbc8c56e2aaf5d3758724dcb44b0a | [
"Zlib",
"PSF-2.0",
"BSD-2-Clause",
"Apache-2.0",
"ECL-2.0",
"BSD-3-Clause-Clear"
] | null | null | null | // This file is licensed under the Elastic License 2.0. Copyright 2021-present, StarRocks Limited.
#include "serde/column_array_serde.h"
#include <fmt/format.h>
#include "column/array_column.h"
#include "column/binary_column.h"
#include "column/column_visitor_adapter.h"
#include "column/const_column.h"
#include "column/decimalv3_column.h"
#include "column/fixed_length_column.h"
#include "column/json_column.h"
#include "column/nullable_column.h"
#include "column/object_column.h"
#include "gutil/strings/substitute.h"
#include "runtime/descriptors.h"
#include "types/hll.h"
#include "util/coding.h"
#include "util/json.h"
#include "util/percentile_value.h"
#include "util/phmap/phmap.h"
namespace starrocks::serde {
namespace {
uint8_t* write_little_endian_32(uint32_t value, uint8_t* buff) {
encode_fixed32_le(buff, value);
return buff + sizeof(value);
}
const uint8_t* read_little_endian_32(const uint8_t* buff, uint32_t* value) {
*value = decode_fixed32_le(buff);
return buff + sizeof(*value);
}
uint8_t* write_little_endian_64(uint64_t value, uint8_t* buff) {
encode_fixed64_le(buff, value);
return buff + sizeof(value);
}
const uint8_t* read_little_endian_64(const uint8_t* buff, uint64_t* value) {
*value = decode_fixed64_le(buff);
return buff + sizeof(*value);
}
uint8_t* write_raw(const void* data, size_t size, uint8_t* buff) {
strings::memcpy_inlined(buff, data, size);
return buff + size;
}
const uint8_t* read_raw(const uint8_t* buff, void* target, size_t size) {
strings::memcpy_inlined(target, buff, size);
return buff + size;
}
template <typename T>
class FixedLengthColumnSerde {
public:
static int64_t max_serialized_size(const vectorized::FixedLengthColumnBase<T>& column) {
return sizeof(uint32_t) + sizeof(T) * column.size();
}
static uint8_t* serialize(const vectorized::FixedLengthColumnBase<T>& column, uint8_t* buff) {
uint32_t size = sizeof(T) * column.size();
buff = write_little_endian_32(size, buff);
buff = write_raw(column.raw_data(), size, buff);
return buff;
}
static const uint8_t* deserialize(const uint8_t* buff, vectorized::FixedLengthColumnBase<T>* column) {
uint32_t size = 0;
buff = read_little_endian_32(buff, &size);
std::vector<T>& data = column->get_data();
raw::make_room(&data, size / sizeof(T));
buff = read_raw(buff, data.data(), size);
return buff;
}
};
class BinaryColumnSerde {
public:
template <typename T>
static int64_t max_serialized_size(const vectorized::BinaryColumnBase<T>& column) {
const auto& bytes = column.get_bytes();
const auto& offsets = column.get_offset();
return bytes.size() + offsets.size() * sizeof(typename vectorized::BinaryColumnBase<T>::Offset) + sizeof(T) * 2;
}
template <typename T>
static uint8_t* serialize(const vectorized::BinaryColumnBase<T>& column, uint8_t* buff) {
const auto& bytes = column.get_bytes();
const auto& offsets = column.get_offset();
T bytes_size = bytes.size() * sizeof(uint8_t);
if constexpr (std::is_same_v<T, uint32_t>) {
buff = write_little_endian_32(bytes_size, buff);
} else {
buff = write_little_endian_64(bytes_size, buff);
}
buff = write_raw(bytes.data(), bytes_size, buff);
//TODO: if T is uint32_t, `offsets_size` may be overflow
T offsets_size = offsets.size() * sizeof(typename vectorized::BinaryColumnBase<T>::Offset);
if constexpr (std::is_same_v<T, uint32_t>) {
buff = write_little_endian_32(offsets_size, buff);
} else {
buff = write_little_endian_64(offsets_size, buff);
}
buff = write_raw(offsets.data(), offsets_size, buff);
return buff;
}
template <typename T>
static const uint8_t* deserialize(const uint8_t* buff, vectorized::BinaryColumnBase<T>* column) {
T bytes_size = 0;
if constexpr (std::is_same_v<T, uint32_t>) {
buff = read_little_endian_32(buff, &bytes_size);
} else {
buff = read_little_endian_64(buff, &bytes_size);
}
column->get_bytes().resize(bytes_size);
buff = read_raw(buff, column->get_bytes().data(), bytes_size);
T offsets_size = 0;
if constexpr (std::is_same_v<T, uint32_t>) {
buff = read_little_endian_32(buff, &offsets_size);
} else {
buff = read_little_endian_64(buff, &offsets_size);
}
raw::make_room(&column->get_offset(), offsets_size / sizeof(typename vectorized::BinaryColumnBase<T>::Offset));
buff = read_raw(buff, column->get_offset().data(), offsets_size);
return buff;
}
};
template <typename T>
class ObjectColumnSerde {
public:
static int64_t max_serialized_size(const vectorized::ObjectColumn<T>& column) {
const std::vector<T>& pool = column.get_pool();
int64_t size = sizeof(uint32_t);
for (const auto& obj : pool) {
size += sizeof(uint64_t);
size += obj.serialize_size();
}
return size;
}
static uint8_t* serialize(const vectorized::ObjectColumn<T>& column, uint8_t* buff) {
buff = write_little_endian_32(column.get_pool().size(), buff);
for (const auto& obj : column.get_pool()) {
uint64_t actual = obj.serialize(buff + sizeof(uint64_t));
buff = write_little_endian_64(actual, buff);
buff += actual;
}
return buff;
}
static const uint8_t* deserialize(const uint8_t* buff, vectorized::ObjectColumn<T>* column) {
uint32_t num_objects = 0;
buff = read_little_endian_32(buff, &num_objects);
column->reset_column();
std::vector<T>& pool = column->get_pool();
pool.reserve(num_objects);
for (int i = 0; i < num_objects; i++) {
uint64_t serialized_size = 0;
buff = read_little_endian_64(buff, &serialized_size);
pool.emplace_back(Slice(buff, serialized_size));
buff += serialized_size;
}
return buff;
}
};
// TODO(mofei) embed the version into JsonColumn
// JsonColumnSerde: serialization of JSON column for network transimission
// The header include a format_version field, indicting the layout of column encoding
class JsonColumnSerde {
public:
static int64_t max_serialized_size(const vectorized::JsonColumn& column) {
const std::vector<JsonValue>& pool = column.get_pool();
int64_t size = 0;
size += sizeof(uint32_t); // format_version
size += sizeof(uint32_t); // num_objects
for (const auto& obj : pool) {
size += sizeof(uint64_t);
size += obj.serialize_size();
}
return size;
}
// Layout
// uint32: format_version (currently is hard-coded)
// uint32: number of datums
// datums: [size1[payload1][size2][payload2]
static uint8_t* serialize(const vectorized::JsonColumn& column, uint8_t* buff) {
buff = write_little_endian_32(kJsonMetaDefaultFormatVersion, buff);
buff = write_little_endian_32(column.get_pool().size(), buff);
for (const auto& obj : column.get_pool()) {
constexpr uint64_t size_field_length = sizeof(uint64_t);
uint64_t actual = obj.serialize(buff + size_field_length);
buff = write_little_endian_64(actual, buff);
buff += actual;
}
return buff;
}
static const uint8_t* deserialize(const uint8_t* buff, vectorized::JsonColumn* column) {
uint32_t actual_version = 0;
uint32_t num_objects = 0;
buff = read_little_endian_32(buff, &actual_version);
buff = read_little_endian_32(buff, &num_objects);
CHECK_EQ(actual_version, kJsonMetaDefaultFormatVersion) << "Only format_version=1 is supported";
column->reset_column();
std::vector<JsonValue>& pool = column->get_pool();
pool.reserve(num_objects);
for (int i = 0; i < num_objects; i++) {
uint64_t serialized_size = 0;
buff = read_little_endian_64(buff, &serialized_size);
pool.emplace_back(Slice(buff, serialized_size));
buff += serialized_size;
}
return buff;
}
};
class NullableColumnSerde {
public:
static int64_t max_serialized_size(const vectorized::NullableColumn& column) {
return serde::ColumnArraySerde::max_serialized_size(*column.null_column()) +
serde::ColumnArraySerde::max_serialized_size(*column.data_column());
}
static uint8_t* serialize(const vectorized::NullableColumn& column, uint8_t* buff) {
buff = serde::ColumnArraySerde::serialize(*column.null_column(), buff);
buff = serde::ColumnArraySerde::serialize(*column.data_column(), buff);
return buff;
}
static const uint8_t* deserialize(const uint8_t* buff, vectorized::NullableColumn* column) {
buff = serde::ColumnArraySerde::deserialize(buff, column->null_column().get());
buff = serde::ColumnArraySerde::deserialize(buff, column->data_column().get());
column->update_has_null();
return buff;
}
};
class ArrayColumnSerde {
public:
static int64_t max_serialized_size(const vectorized::ArrayColumn& column) {
return serde::ColumnArraySerde::max_serialized_size(column.offsets()) +
serde::ColumnArraySerde::max_serialized_size(column.elements());
}
static uint8_t* serialize(const vectorized::ArrayColumn& column, uint8_t* buff) {
buff = serde::ColumnArraySerde::serialize(column.offsets(), buff);
buff = serde::ColumnArraySerde::serialize(column.elements(), buff);
return buff;
}
static const uint8_t* deserialize(const uint8_t* buff, vectorized::ArrayColumn* column) {
buff = serde::ColumnArraySerde::deserialize(buff, column->offsets_column().get());
buff = serde::ColumnArraySerde::deserialize(buff, column->elements_column().get());
return buff;
}
};
class ConstColumnSerde {
public:
static int64_t max_serialized_size(const vectorized::ConstColumn& column) {
return /*sizeof(uint64_t)=*/8 + serde::ColumnArraySerde::max_serialized_size(*column.data_column());
}
static uint8_t* serialize(const vectorized::ConstColumn& column, uint8_t* buff) {
buff = write_little_endian_64(column.size(), buff);
buff = serde::ColumnArraySerde::serialize(*column.data_column(), buff);
return buff;
}
static const uint8_t* deserialize(const uint8_t* buff, vectorized::ConstColumn* column) {
uint64_t size = 0;
buff = read_little_endian_64(buff, &size);
buff = serde::ColumnArraySerde::deserialize(buff, column->data_column().get());
column->resize(size);
return buff;
}
};
class ColumnSerializedSizeVisitor final : public ColumnVisitorAdapter<ColumnSerializedSizeVisitor> {
public:
explicit ColumnSerializedSizeVisitor(int64_t init_size) : ColumnVisitorAdapter(this), _size(init_size) {}
Status do_visit(const vectorized::NullableColumn& column) {
_size += NullableColumnSerde::max_serialized_size(column);
return Status::OK();
}
Status do_visit(const vectorized::ConstColumn& column) {
_size += ConstColumnSerde::max_serialized_size(column);
return Status::OK();
}
Status do_visit(const vectorized::ArrayColumn& column) {
_size += ArrayColumnSerde::max_serialized_size(column);
return Status::OK();
}
template <typename T>
Status do_visit(const vectorized::BinaryColumnBase<T>& column) {
_size += BinaryColumnSerde::max_serialized_size(column);
return Status::OK();
}
template <typename T>
Status do_visit(const vectorized::FixedLengthColumnBase<T>& column) {
_size += FixedLengthColumnSerde<T>::max_serialized_size(column);
return Status::OK();
}
template <typename T>
Status do_visit(const vectorized::ObjectColumn<T>& column) {
_size += ObjectColumnSerde<T>::max_serialized_size(column);
return Status::OK();
}
Status do_visit(const vectorized::JsonColumn& column) {
_size += JsonColumnSerde::max_serialized_size(column);
return Status::OK();
}
int64_t size() const { return _size; }
private:
int64_t _size;
};
class ColumnSerializingVisitor final : public ColumnVisitorAdapter<ColumnSerializingVisitor> {
public:
explicit ColumnSerializingVisitor(uint8_t* buff) : ColumnVisitorAdapter(this), _buff(buff), _cur(buff) {}
Status do_visit(const vectorized::NullableColumn& column) {
_cur = NullableColumnSerde::serialize(column, _cur);
return Status::OK();
}
Status do_visit(const vectorized::ConstColumn& column) {
_cur = ConstColumnSerde::serialize(column, _cur);
return Status::OK();
}
Status do_visit(const vectorized::ArrayColumn& column) {
_cur = ArrayColumnSerde::serialize(column, _cur);
return Status::OK();
}
template <typename T>
Status do_visit(const vectorized::BinaryColumnBase<T>& column) {
_cur = BinaryColumnSerde::serialize(column, _cur);
return Status::OK();
}
template <typename T>
Status do_visit(const vectorized::FixedLengthColumnBase<T>& column) {
_cur = FixedLengthColumnSerde<T>::serialize(column, _cur);
return Status::OK();
}
template <typename T>
Status do_visit(const vectorized::ObjectColumn<T>& column) {
_cur = ObjectColumnSerde<T>::serialize(column, _cur);
return Status::OK();
}
Status do_visit(const vectorized::JsonColumn& column) {
_cur = JsonColumnSerde::serialize(column, _cur);
return Status::OK();
}
uint8_t* cur() const { return _cur; }
int64_t bytes() const { return _cur - _buff; }
private:
uint8_t* _buff;
uint8_t* _cur;
};
class ColumnDeserializingVisitor final : public ColumnVisitorMutableAdapter<ColumnDeserializingVisitor> {
public:
explicit ColumnDeserializingVisitor(const uint8_t* buff)
: ColumnVisitorMutableAdapter(this), _buff(buff), _cur(buff) {}
Status do_visit(vectorized::NullableColumn* column) {
_cur = NullableColumnSerde::deserialize(_cur, column);
return Status::OK();
}
Status do_visit(vectorized::ConstColumn* column) {
_cur = ConstColumnSerde::deserialize(_cur, column);
return Status::OK();
}
Status do_visit(vectorized::ArrayColumn* column) {
_cur = ArrayColumnSerde::deserialize(_cur, column);
return Status::OK();
}
template <typename T>
Status do_visit(vectorized::BinaryColumnBase<T>* column) {
_cur = BinaryColumnSerde::deserialize(_cur, column);
return Status::OK();
}
template <typename T>
Status do_visit(vectorized::FixedLengthColumnBase<T>* column) {
_cur = FixedLengthColumnSerde<T>::deserialize(_cur, column);
return Status::OK();
}
template <typename T>
Status do_visit(vectorized::ObjectColumn<T>* column) {
_cur = ObjectColumnSerde<T>::deserialize(_cur, column);
return Status::OK();
}
Status do_visit(vectorized::JsonColumn* column) {
_cur = JsonColumnSerde::deserialize(_cur, column);
return Status::OK();
}
const uint8_t* cur() const { return _cur; }
int64_t bytes() const { return _cur - _buff; }
private:
const uint8_t* _buff;
const uint8_t* _cur;
};
} // namespace
int64_t ColumnArraySerde::max_serialized_size(const vectorized::Column& column) {
ColumnSerializedSizeVisitor visitor(0);
auto st = column.accept(&visitor);
LOG_IF(WARNING, !st.ok()) << st;
return st.ok() ? visitor.size() : 0;
}
uint8_t* ColumnArraySerde::serialize(const vectorized::Column& column, uint8_t* buff) {
ColumnSerializingVisitor visitor(buff);
auto st = column.accept(&visitor);
LOG_IF(WARNING, !st.ok()) << st;
return st.ok() ? visitor.cur() : nullptr;
}
const uint8_t* ColumnArraySerde::deserialize(const uint8_t* data, vectorized::Column* column) {
ColumnDeserializingVisitor visitor(data);
auto st = column->accept_mutable(&visitor);
LOG_IF(WARNING, !st.ok()) << st;
return st.ok() ? visitor.cur() : nullptr;
}
} // namespace starrocks::serde
| 35.410753 | 120 | 0.66446 | [
"vector"
] |
a1e3a8ea1f84d776f0131e078ad055a422470c4e | 4,303 | cpp | C++ | caffe/src/caffe/test/test_local_layer.cpp | shaoxiaohu/Face-Alignment-with-Two-Stage-Re-initialization- | ccd26fee4dd0b6cd0d11de4d5b4d2d746e8cc66b | [
"MIT"
] | 92 | 2017-07-19T05:12:05.000Z | 2021-11-09T07:59:07.000Z | caffe/src/caffe/test/test_local_layer.cpp | mornydew/Face_Alignment_Two_Stage_Re-initialization | ccd26fee4dd0b6cd0d11de4d5b4d2d746e8cc66b | [
"MIT"
] | 11 | 2017-10-18T05:11:20.000Z | 2020-04-03T21:28:20.000Z | caffe/src/caffe/test/test_local_layer.cpp | mornydew/Face_Alignment_Two_Stage_Re-initialization | ccd26fee4dd0b6cd0d11de4d5b4d2d746e8cc66b | [
"MIT"
] | 31 | 2017-07-20T11:37:39.000Z | 2021-03-08T09:01:26.000Z | #include <cstring>
#include <vector>
#include "gtest/gtest.h"
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/filler.hpp"
#include "caffe/layers/local_layer.hpp"
#include "caffe/test/test_caffe_main.hpp"
#include "caffe/test/test_gradient_check_util.hpp"
namespace caffe {
template <typename TypeParam>
class LocalLayerTest: public MultiDeviceTest<TypeParam> {
typedef typename TypeParam::Dtype Dtype;
protected:
LocalLayerTest()
: blob_bottom_(new Blob<Dtype>()),
blob_top_(new Blob<Dtype>()) {}
virtual void SetUp() {
blob_bottom_->Reshape(2, 3, 6, 4);
// fill the values
FillerParameter filler_param;
filler_param.set_value(1.);
GaussianFiller<Dtype> filler(filler_param);
filler.Fill(this->blob_bottom_);
blob_bottom_vec_.push_back(blob_bottom_);
blob_top_vec_.push_back(blob_top_);
}
virtual ~LocalLayerTest() { delete blob_bottom_; delete blob_top_; }
Blob<Dtype>* const blob_bottom_;
Blob<Dtype>* const blob_top_;
vector<Blob<Dtype>*> blob_bottom_vec_;
vector<Blob<Dtype>*> blob_top_vec_;
};
TYPED_TEST_CASE(LocalLayerTest, TestDtypesAndDevices);
TYPED_TEST(LocalLayerTest, TestSetup) {
typedef typename TypeParam::Dtype Dtype;
LayerParameter layer_param;
LocalParameter* convolution_param =
layer_param.mutable_local_param();
convolution_param->set_kernel_size(3);
convolution_param->set_stride(2);
convolution_param->set_num_output(4);
shared_ptr<Layer<Dtype> > layer(
new LocalLayer<Dtype>(layer_param));
layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_);
EXPECT_EQ(this->blob_top_->num(), 2);
EXPECT_EQ(this->blob_top_->channels(), 4);
EXPECT_EQ(this->blob_top_->height(), 2);
EXPECT_EQ(this->blob_top_->width(), 1);
convolution_param->set_num_output(3);
layer.reset(new LocalLayer<Dtype>(layer_param));
layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_);
EXPECT_EQ(this->blob_top_->num(), 2);
EXPECT_EQ(this->blob_top_->channels(), 3);
EXPECT_EQ(this->blob_top_->height(), 2);
EXPECT_EQ(this->blob_top_->width(), 1);
}
TYPED_TEST(LocalLayerTest, TestSimpleConvolution) {
typedef typename TypeParam::Dtype Dtype;
// We will simply see if the convolution layer carries out averaging well.
FillerParameter filler_param;
filler_param.set_value(1.);
ConstantFiller<Dtype> filler(filler_param);
filler.Fill(this->blob_bottom_);
LayerParameter layer_param;
LocalParameter* convolution_param =
layer_param.mutable_local_param();
convolution_param->set_kernel_size(3);
convolution_param->set_stride(1);
convolution_param->set_num_output(1);
convolution_param->mutable_weight_filler()->set_type("test_local");
convolution_param->mutable_weight_filler()->set_value(1);
convolution_param->mutable_bias_filler()->set_type("constant");
convolution_param->mutable_bias_filler()->set_value(0.1);
shared_ptr<Layer<Dtype> > layer(
new LocalLayer<Dtype>(layer_param));
layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_);
layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_);
// After the convolution, the output should all have output values 27.1
const Dtype* top_data = this->blob_top_->cpu_data();
for (int n = 0; n < this->blob_top_->num(); n++) {
for (int k = 0; k < this->blob_top_->channels(); k++) {
for (int j = 0; j < this->blob_top_->height(); j++) {
for (int i = 0; i < this->blob_top_->width(); i++) {
int idx = j * this->blob_top_->width() + i;
EXPECT_NEAR(*(top_data + this->blob_top_->offset(n, k, j, i)),
idx * 27 + 0.1, 1e-4);
}
}
}
}
}
TYPED_TEST(LocalLayerTest, TestGradient) {
typedef typename TypeParam::Dtype Dtype;
LayerParameter layer_param;
LocalParameter* convolution_param =
layer_param.mutable_local_param();
convolution_param->set_kernel_size(3);
convolution_param->set_stride(2);
convolution_param->set_num_output(2);
convolution_param->mutable_weight_filler()->set_type("gaussian");
convolution_param->mutable_bias_filler()->set_type("gaussian");
LocalLayer<Dtype> layer(layer_param);
GradientChecker<Dtype> checker(1e-2, 1e-3);
checker.CheckGradientExhaustive(&layer,
this->blob_bottom_vec_,
this->blob_top_vec_);
}
} // namespace caffe
| 35.270492 | 76 | 0.723914 | [
"vector"
] |
a1ea3243327ac674004d97865465732b00326a19 | 8,693 | hpp | C++ | include/GlobalNamespace/MultiplayerSpectatorController.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/MultiplayerSpectatorController.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/MultiplayerSpectatorController.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: UnityEngine.MonoBehaviour
#include "UnityEngine/MonoBehaviour.hpp"
// Including type: MultiplayerController
#include "GlobalNamespace/MultiplayerController.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
// Forward declaring type: MultiplayerSpectatingSpotManager
class MultiplayerSpectatingSpotManager;
// Forward declaring type: MultiplayerLocalInactivePlayerSongSyncController
class MultiplayerLocalInactivePlayerSongSyncController;
// Forward declaring type: FadeInOutController
class FadeInOutController;
// Forward declaring type: IMultiplayerSpectatingSpot
class IMultiplayerSpectatingSpot;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Action`1<T>
template<typename T>
class Action_1;
}
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: Transform
class Transform;
}
// Forward declaring namespace: System::Collections
namespace System::Collections {
// Forward declaring type: IEnumerator
class IEnumerator;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Size: 0x50
#pragma pack(push, 1)
// Autogenerated type: MultiplayerSpectatorController
class MultiplayerSpectatorController : public UnityEngine::MonoBehaviour {
public:
// Nested type: GlobalNamespace::MultiplayerSpectatorController::$SwitchToDefaultSpotWithFadeCoroutine$d__17
class $SwitchToDefaultSpotWithFadeCoroutine$d__17;
// Nested type: GlobalNamespace::MultiplayerSpectatorController::$SwitchToDefaultSpotCoroutine$d__18
class $SwitchToDefaultSpotCoroutine$d__18;
// [InjectAttribute] Offset: 0xE1EFEC
// private readonly MultiplayerSpectatingSpotManager _spotManager
// Size: 0x8
// Offset: 0x18
GlobalNamespace::MultiplayerSpectatingSpotManager* spotManager;
// Field size check
static_assert(sizeof(GlobalNamespace::MultiplayerSpectatingSpotManager*) == 0x8);
// [InjectAttribute] Offset: 0xE1EFFC
// private readonly MultiplayerLocalInactivePlayerSongSyncController _songController
// Size: 0x8
// Offset: 0x20
GlobalNamespace::MultiplayerLocalInactivePlayerSongSyncController* songController;
// Field size check
static_assert(sizeof(GlobalNamespace::MultiplayerLocalInactivePlayerSongSyncController*) == 0x8);
// [InjectAttribute] Offset: 0xE1F00C
// private readonly MultiplayerController _multiplayerController
// Size: 0x8
// Offset: 0x28
GlobalNamespace::MultiplayerController* multiplayerController;
// Field size check
static_assert(sizeof(GlobalNamespace::MultiplayerController*) == 0x8);
// [InjectAttribute] Offset: 0xE1F01C
// private readonly FadeInOutController _fadeInOutController
// Size: 0x8
// Offset: 0x30
GlobalNamespace::FadeInOutController* fadeInOutController;
// Field size check
static_assert(sizeof(GlobalNamespace::FadeInOutController*) == 0x8);
// [CompilerGeneratedAttribute] Offset: 0xE1F02C
// private System.Action`1<IMultiplayerSpectatingSpot> spectatingSpotDidChangeEvent
// Size: 0x8
// Offset: 0x38
System::Action_1<GlobalNamespace::IMultiplayerSpectatingSpot*>* spectatingSpotDidChangeEvent;
// Field size check
static_assert(sizeof(System::Action_1<GlobalNamespace::IMultiplayerSpectatingSpot*>*) == 0x8);
// private UnityEngine.Transform _transform
// Size: 0x8
// Offset: 0x40
UnityEngine::Transform* transform;
// Field size check
static_assert(sizeof(UnityEngine::Transform*) == 0x8);
// private IMultiplayerSpectatingSpot _currentSpot
// Size: 0x8
// Offset: 0x48
GlobalNamespace::IMultiplayerSpectatingSpot* currentSpot;
// Field size check
static_assert(sizeof(GlobalNamespace::IMultiplayerSpectatingSpot*) == 0x8);
// Creating value type constructor for type: MultiplayerSpectatorController
MultiplayerSpectatorController(GlobalNamespace::MultiplayerSpectatingSpotManager* spotManager_ = {}, GlobalNamespace::MultiplayerLocalInactivePlayerSongSyncController* songController_ = {}, GlobalNamespace::MultiplayerController* multiplayerController_ = {}, GlobalNamespace::FadeInOutController* fadeInOutController_ = {}, System::Action_1<GlobalNamespace::IMultiplayerSpectatingSpot*>* spectatingSpotDidChangeEvent_ = {}, UnityEngine::Transform* transform_ = {}, GlobalNamespace::IMultiplayerSpectatingSpot* currentSpot_ = {}) noexcept : spotManager{spotManager_}, songController{songController_}, multiplayerController{multiplayerController_}, fadeInOutController{fadeInOutController_}, spectatingSpotDidChangeEvent{spectatingSpotDidChangeEvent_}, transform{transform_}, currentSpot{currentSpot_} {}
// Deleting conversion operator: operator System::IntPtr
constexpr operator System::IntPtr() const noexcept = delete;
// public System.Void add_spectatingSpotDidChangeEvent(System.Action`1<IMultiplayerSpectatingSpot> value)
// Offset: 0x23E84C4
void add_spectatingSpotDidChangeEvent(System::Action_1<GlobalNamespace::IMultiplayerSpectatingSpot*>* value);
// public System.Void remove_spectatingSpotDidChangeEvent(System.Action`1<IMultiplayerSpectatingSpot> value)
// Offset: 0x23E86F0
void remove_spectatingSpotDidChangeEvent(System::Action_1<GlobalNamespace::IMultiplayerSpectatingSpot*>* value);
// public IMultiplayerSpectatingSpot get_currentSpot()
// Offset: 0x23E8868
GlobalNamespace::IMultiplayerSpectatingSpot* get_currentSpot();
// protected System.Void Awake()
// Offset: 0x23E8870
void Awake();
// protected System.Void Start()
// Offset: 0x23E8898
void Start();
// protected System.Void OnDestroy()
// Offset: 0x23E892C
void OnDestroy();
// public System.Void SwitchToDefaultSpot()
// Offset: 0x23E1014
void SwitchToDefaultSpot();
// public System.Void SwitchToPrev()
// Offset: 0x23E8814
void SwitchToPrev();
// public System.Void SwitchToNext()
// Offset: 0x23E87B0
void SwitchToNext();
// private System.Collections.IEnumerator SwitchToDefaultSpotWithFadeCoroutine()
// Offset: 0x23E8CE4
System::Collections::IEnumerator* SwitchToDefaultSpotWithFadeCoroutine();
// private System.Collections.IEnumerator SwitchToDefaultSpotCoroutine()
// Offset: 0x23E8A08
System::Collections::IEnumerator* SwitchToDefaultSpotCoroutine();
// private System.Void SwitchToSpectatingSpot(IMultiplayerSpectatingSpot spectatingSpot)
// Offset: 0x23E8A78
void SwitchToSpectatingSpot(GlobalNamespace::IMultiplayerSpectatingSpot* spectatingSpot);
// private System.Void HandleStateChanged(MultiplayerController/State state)
// Offset: 0x23E8DAC
void HandleStateChanged(GlobalNamespace::MultiplayerController::State state);
// public System.Void .ctor()
// Offset: 0x23E8DE4
// Implemented from: UnityEngine.MonoBehaviour
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static MultiplayerSpectatorController* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::MultiplayerSpectatorController::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<MultiplayerSpectatorController*, creationType>()));
}
}; // MultiplayerSpectatorController
#pragma pack(pop)
static check_size<sizeof(MultiplayerSpectatorController), 72 + sizeof(GlobalNamespace::IMultiplayerSpectatingSpot*)> __GlobalNamespace_MultiplayerSpectatorControllerSizeCheck;
static_assert(sizeof(MultiplayerSpectatorController) == 0x50);
}
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::MultiplayerSpectatorController*, "", "MultiplayerSpectatorController");
| 52.684848 | 807 | 0.755896 | [
"object",
"transform"
] |
a1ef831084005be87a1b7838670c384005e27838 | 5,882 | cpp | C++ | unittest/utility.cpp | tsung-wei-huang/DtCraft | 80cc9e1195adc0026107814243401a1fc47b5be2 | [
"MIT"
] | 69 | 2019-03-16T20:13:26.000Z | 2022-03-24T14:12:19.000Z | unittest/utility.cpp | Tsung-Wei/DtCraft | 80cc9e1195adc0026107814243401a1fc47b5be2 | [
"MIT"
] | 12 | 2017-12-02T05:38:30.000Z | 2019-02-08T11:16:12.000Z | unittest/utility.cpp | Tsung-Wei/DtCraft | 80cc9e1195adc0026107814243401a1fc47b5be2 | [
"MIT"
] | 12 | 2019-04-13T16:27:29.000Z | 2022-01-07T14:42:46.000Z | /******************************************************************************
* *
* Copyright (c) 2018, Tsung-Wei Huang, Chun-Xun Lin, and Martin D. F. Wong, *
* University of Illinois at Urbana-Champaign (UIUC), IL, USA. *
* *
* All Rights Reserved. *
* *
* This program is free software. You can redistribute and/or modify *
* it in accordance with the terms of the accompanying license agreement. *
* See LICENSE in the top-level directory for details. *
* *
******************************************************************************/
#define CATCH_CONFIG_MAIN
#include <dtc/unittest/catch.hpp>
#include <dtc/dtc.hpp>
// ---- Utility.uuid ------------------------------------------------------------------------------
// Test case: Utility.uuid
TEST_CASE("Utility.uuid") {
dtc::UUID u1, u2, u3, u4;
// Comparator.
REQUIRE(u1 == u1);
// Copy
u2 = u1;
REQUIRE(u1 == u2);
// Move
u3 = std::move(u1);
REQUIRE(u2 == u3);
// Copy constructor
dtc::UUID u5(u4);
REQUIRE(u5 == u4);
// Move constructor.
dtc::UUID u6(std::move(u4));
REQUIRE(u5 == u6);
// Uniqueness
std::vector<dtc::UUID> uuids(65536);
std::sort(uuids.begin(), uuids.end());
std::unique(uuids.begin(), uuids.end());
REQUIRE(uuids.size() == 65536);
}
//-------------------------------------------------------------------------------------------------
// Operator ==
bool operator == (const struct timeval& lhs, const struct timeval& rhs) {
return lhs.tv_sec == rhs.tv_sec && lhs.tv_usec == rhs.tv_usec;
}
// Unittest: Utility.os.chrono
TEST_CASE("Utility.os.chrono") {
// Conversion between chrono and timeval
for(auto s=1; s<=1024; s<<=1) {
for(auto u=1; u<=1024; u<<=1) {
const struct timeval tv {s, u};
const auto N = std::chrono::nanoseconds((uint64_t)s*1000000000 + u*1000);
const auto B = std::chrono::duration_cast<std::chrono::microseconds>(N);
const auto M = std::chrono::duration_cast<std::chrono::milliseconds>(N);
const auto S = std::chrono::duration_cast<std::chrono::seconds>(N);
REQUIRE(dtc::duration_cast<std::chrono::nanoseconds>(tv) == N);
REQUIRE(dtc::duration_cast<std::chrono::microseconds>(tv) == B);
REQUIRE(dtc::duration_cast<std::chrono::milliseconds>(tv) == M);
REQUIRE(dtc::duration_cast<std::chrono::seconds>(tv) == S);
REQUIRE(dtc::duration_cast<struct timeval>(N) == tv);
}
}
}
//-------------------------------------------------------------------------------------------------
// Unittest: Literals
TEST_CASE("Utility.literals") {
using namespace dtc::literals;
// Byte as baseline.
static_assert(1_KB == 1024);
static_assert(1_MB == 1024*1024);
static_assert(1_GB == 1024*1024*1024);
// KB as baseline
static_assert(1024 == 1_KB);
static_assert(1_MB == 1024_KB);
static_assert(1_GB == 1048576_KB);
// MB as baseline
static_assert(1048576 == 1_MB);
static_assert(1_GB == 1024_MB);
}
//-------------------------------------------------------------------------------------------------
// Unittest: Utility.os.environment
TEST_CASE("Utility.os.environment") {
const auto key = "dtc";
const auto val = "dummy";
auto env = dtc::environment_variables();
REQUIRE(env.size() > 0);
REQUIRE(::unsetenv(key) != -1);
env = dtc::environment_variables();
REQUIRE(env.find(key) == env.end());
REQUIRE(::setenv(key, val, 1) != -1) ;
env = dtc::environment_variables();
REQUIRE((env.find(key) != env.end() && env.find(key)->second == val));
}
//-------------------------------------------------------------------------------------------------
// Unit test: Utility.os.descriptor
TEST_CASE("Utility.os.descriptor") {
int fd {-1};
// Invalid fd
REQUIRE_FALSE(dtc::is_fd_valid(fd));
REQUIRE_FALSE(dtc::is_fd_blocking(fd));
REQUIRE_FALSE(dtc::is_fd_nonblocking(fd));
REQUIRE_FALSE(dtc::is_fd_open_on_exec(fd));
REQUIRE_FALSE(dtc::is_fd_close_on_exec(fd));
// Check the file descriptor flag
// Basic operations
REQUIRE_THROWS_AS(dtc::make_fd_blocking(fd), std::system_error);
REQUIRE_THROWS_AS(dtc::make_fd_nonblocking(fd), std::system_error);
REQUIRE_THROWS_AS(dtc::make_fd_open_on_exec(fd), std::system_error);
REQUIRE_THROWS_AS(dtc::make_fd_close_on_exec(fd), std::system_error);
// Make a valid fd
fd = STDIN_FILENO;
REQUIRE(dtc::is_fd_valid(fd));
// Close or open on exec operations.
REQUIRE(dtc::is_fd_open_on_exec(fd));
REQUIRE_FALSE(dtc::is_fd_close_on_exec(fd));
REQUIRE_NOTHROW(dtc::make_fd_close_on_exec(fd));
REQUIRE(dtc::is_fd_close_on_exec(fd));
REQUIRE_FALSE(dtc::is_fd_open_on_exec(fd));
REQUIRE_NOTHROW(dtc::make_fd_open_on_exec(fd));
REQUIRE(dtc::is_fd_open_on_exec(fd));
REQUIRE_FALSE(dtc::is_fd_close_on_exec(fd));
REQUIRE_NOTHROW(dtc::make_fd_close_on_exec(fd));
REQUIRE_FALSE(dtc::is_fd_open_on_exec(fd));
REQUIRE(dtc::is_fd_close_on_exec(fd));
// Non-blocking and blocking operations.
REQUIRE_NOTHROW(dtc::make_fd_blocking(fd));
REQUIRE(dtc::is_fd_blocking(fd));
REQUIRE_FALSE(dtc::is_fd_nonblocking(fd));
REQUIRE_NOTHROW(dtc::make_fd_nonblocking(fd));
REQUIRE(dtc::is_fd_nonblocking(fd));
REQUIRE_FALSE(dtc::is_fd_blocking(fd));
REQUIRE_NOTHROW(dtc::make_fd_blocking(fd));
REQUIRE(dtc::is_fd_blocking(fd));
REQUIRE_FALSE(dtc::is_fd_nonblocking(fd));
REQUIRE_NOTHROW(dtc::make_fd_nonblocking(fd));
REQUIRE_FALSE(dtc::is_fd_blocking(fd));
REQUIRE(dtc::is_fd_nonblocking(fd));
}
| 33.231638 | 99 | 0.563754 | [
"vector"
] |
a1f194eb2a0d09a5709453b5308959803cb9fd2b | 719 | cpp | C++ | cpp/src/SpiralMatrixII.cpp | qianbinbin/leetcode | 915cecab0c940cd13847683ec55b17b77eb0f39b | [
"MIT"
] | 4 | 2018-03-05T02:27:16.000Z | 2021-03-15T14:19:44.000Z | cpp/src/SpiralMatrixII.cpp | qianbinbin/leetcode | 915cecab0c940cd13847683ec55b17b77eb0f39b | [
"MIT"
] | null | null | null | cpp/src/SpiralMatrixII.cpp | qianbinbin/leetcode | 915cecab0c940cd13847683ec55b17b77eb0f39b | [
"MIT"
] | 2 | 2018-07-22T10:32:10.000Z | 2018-10-20T03:14:28.000Z | #include "SpiralMatrixII.h"
using namespace lcpp;
std::vector<std::vector<int>> Solution59_1::generateMatrix(int n) {
std::vector<std::vector<int>> Matrix(n, std::vector<int>(n));
int Left = 0, Right = n - 1, Top = 0, Bottom = n - 1, I, J;
int Num = 1;
while (true) {
for (J = Left; J <= Right; ++J)
Matrix[Top][J] = Num++;
if (++Top > Bottom)
break;
for (I = Top; I <= Bottom; ++I)
Matrix[I][Right] = Num++;
if (--Right < Left)
break;
for (J = Right; J >= Left; --J)
Matrix[Bottom][J] = Num++;
if (--Bottom < Top)
break;
for (I = Bottom; I >= Top; --I)
Matrix[I][Left] = Num++;
if (++Left > Right)
break;
}
return Matrix;
}
| 24.793103 | 67 | 0.515994 | [
"vector"
] |
a1f2ae2c99e3e64d6d8b7420f1529fc10683e1ea | 22,373 | hpp | C++ | include/seqan3/argument_parser/detail/version_check.hpp | marehr/nomchop | a88bfb6f5d4a291a71b6b3192eeac81fdc450d43 | [
"CC-BY-4.0",
"CC0-1.0"
] | 1 | 2021-03-01T11:12:56.000Z | 2021-03-01T11:12:56.000Z | include/seqan3/argument_parser/detail/version_check.hpp | marehr/nomchop | a88bfb6f5d4a291a71b6b3192eeac81fdc450d43 | [
"CC-BY-4.0",
"CC0-1.0"
] | 2 | 2017-05-17T07:16:19.000Z | 2020-02-13T16:10:10.000Z | include/seqan3/argument_parser/detail/version_check.hpp | marehr/nomchop | a88bfb6f5d4a291a71b6b3192eeac81fdc450d43 | [
"CC-BY-4.0",
"CC0-1.0"
] | null | null | null | // -----------------------------------------------------------------------------------------------------
// Copyright (c) 2006-2020, Knut Reinert & Freie Universitรคt Berlin
// Copyright (c) 2016-2020, Knut Reinert & MPI fรผr molekulare Genetik
// This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License
// shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE
// -----------------------------------------------------------------------------------------------------
/*!\file
* \author Svenja Mehringer <svenja.mehringer AT fu-berlin.de>
* \brief Provides the version check functionality.
*/
#pragma once
#include <sys/stat.h>
#include <chrono>
#include <fstream>
#include <future>
#include <iostream>
#include <regex>
#include <seqan3/version.hpp>
#include <seqan3/core/detail/terminal.hpp>
#include <seqan3/io/detail/misc.hpp>
#include <seqan3/io/detail/safe_filesystem_entry.hpp>
#include <seqan3/std/charconv>
namespace seqan3::detail
{
// ---------------------------------------------------------------------------------------------------------------------
// function call_server()
// ---------------------------------------------------------------------------------------------------------------------
/*!\brief Writes a timestamp file and performs the server call to get the newest version information.
* \param[in] command The system command as a string. See seqan3::detail::version_checker::command for details.
* \param[in] prom A promise object used to track the detached thread which executes this command.
*
* This function performs a https server request by executing a hard coded command (string) as a system call.
*/
inline void call_server(std::string const & command, std::promise<bool> prom)
{
// system call - http response is stored in a file '.config/seqan/{appname}_version'
if (system(command.c_str()))
prom.set_value(false);
else
prom.set_value(true);
}
// ---------------------------------------------------------------------------------------------------------------------
// version_checker
// ---------------------------------------------------------------------------------------------------------------------
//!\brief A functor whose operator() performs the server http request and version checks.
class version_checker
{
public:
/*!\name Constructors, destructor and assignment
* \{
*/
//!\brief This class has to be initialised with name and version information.
version_checker() = delete;
version_checker(version_checker const &) = default; //!< Defaulted.
version_checker & operator=(version_checker const &) = default; //!< Defaulted.
version_checker(version_checker &&) = default; //!< Defaulted.
version_checker & operator=(version_checker &&) = default; //!< Defaulted.
~version_checker() = default; //!< Defaulted.
/*!\brief Initialises the version_checker with the application name and version.
* \param[in] name_ The application name.
* \param[in] version_ The application version.
* \param[in] app_url An (github) url with the newest release information of the application.
*/
version_checker(std::string name_, std::string const & version_, std::string const & app_url = std::string{}) :
name{std::move(name_)}
{
assert(std::regex_match(name, std::regex{"^[a-zA-Z0-9_-]+$"})); // check on construction of the argument parser
if (!app_url.empty())
{
message_app_update.pop_back(); // remove second newline
message_app_update.append("[APP INFO] :: Visit " + app_url + " for updates.\n\n");
}
#if defined(NDEBUG)
timestamp_filename = cookie_path / (name + "_usr.timestamp");
#else
timestamp_filename = cookie_path / (name + "_dev.timestamp");
#endif
std::smatch versionMatch;
// Ensure version string is not corrupt
if (!version_.empty() && /*regex allows version prefix instead of exact match */
std::regex_search(version_, versionMatch, std::regex("^([[:digit:]]+\\.[[:digit:]]+\\.[[:digit:]]+).*")))
{
version = versionMatch.str(1); // in case the git revision number is given take only version number
}
}
//!\}
/*!\brief Initialises the version_checker with the application name and version.
* \param[in] prom The promise to track the state of the detached thread which calls seqan3::detail::call_server.
*
* The operator performs the following steps:
*
* 1. If a timestamp file already exists, the following behaviour can be expected depending on the file contents:
* * content "NEVER": No server call is performed and no update information is printed.
* * content "ALWAYS": A server call is performed and update information is printed if a version file exists.
* * content is a timestamp: The "time-of-last-version-check" is read from file. The function only
* continues if the last version check is more than a day old.
*
* 2. If a version file exists, the app version and seqan3 version are compared to the current ones and the
* the following message may be printed:
* **Debug mode** (directed at the developer of the application)
* * If the app is unregistered (no version information is available at the server) the developer will be
* notified that he has the possibility of registering his application with us
* (see seqan3::version_checker::message_unregistered_app).
* * If the current seqan version is smaller then the one returned by the server call, the developer is notified
* that he may update to the newest seqan3 version (see seqan3::version_checker::message_seqan3_update).
* * If the current app version is greater than the one returned by the server call, we assume that the
* developer has released a new version and is notified to send us the new version
* (see seqan3::version_checker::message_registered_app_update).
* **Release mode** (directed at the user of the application):
* * If the current app version is lower than the one returned by the server call, the user is notified that
* a newer version exists.
*/
void operator()(std::promise<bool> prom)
{
std::array<int, 3> empty_version{0, 0, 0};
std::array<int, 3> srv_app_version{};
std::array<int, 3> srv_seqan_version{};
std::ifstream version_file{cookie_path / (name + ".version")};
if (version_file.is_open())
{
std::string line{};
std::getline(version_file, line); // get first line which should only contain the version number of the app
if (line != unregistered_app)
srv_app_version = get_numbers_from_version_string(line);
#if !defined(NDEBUG)
else
std::cerr << message_unregistered_app;
#endif // !defined(NDEBUG)
std::getline(version_file, line); // get second line which should only contain the version number of seqan
srv_seqan_version = get_numbers_from_version_string(line);
version_file.close();
}
#if !defined(NDEBUG) // only check seqan version in debug
if (srv_seqan_version != empty_version)
{
std::array<int, 3> seqan_version = {SEQAN3_VERSION_MAJOR, SEQAN3_VERSION_MINOR, SEQAN3_VERSION_PATCH};
if (seqan_version < srv_seqan_version)
std::cerr << message_seqan3_update;
}
#endif
if (srv_app_version != empty_version) // app version
{
#if defined(NDEBUG) // only check app version in release
if (get_numbers_from_version_string(version) < srv_app_version)
std::cerr << message_app_update;
#endif // defined(NDEBUG)
#if !defined(NDEBUG) // only notify developer that app version should be updated on server
if (get_numbers_from_version_string(version) > srv_app_version)
std::cerr << message_registered_app_update;
#endif // !defined(NDEBUG)
}
std::cerr << std::flush;
std::string program = get_program();
if (program.empty())
{
prom.set_value(false);
return;
}
// 'cookie_path' is no user input and `name` is escaped on construction of the argument parser.
std::filesystem::path out_file = cookie_path / (name + ".version");
// build up command for server call
std::string command = program + // no user defined input
" " +
out_file.string() +
" " +
std::string{"http://seqan-update.informatik.uni-tuebingen.de/check/SeqAn3_"} +
#ifdef __linux
"Linux" +
#elif __APPLE__
"MacOS" +
#elif defined(_WIN32)
"Windows" +
#elif __FreeBSD__
"FreeBSD" +
#elif __OpenBSD__
"OpenBSD" +
#else
"unknown" +
#endif
#if __x86_64__ || __ppc64__
"_64_" +
#else
"_32_" +
#endif
name + // !user input! escaped on construction of the argument parser
"_" +
version + // !user input! escaped on construction of the version_checker
#if defined(_WIN32)
"; exit [int] -not $?}\" > nul 2>&1";
#else
" > /dev/null 2>&1";
#endif
// launch a separate thread to not defer runtime.
std::thread(call_server, command, std::move(prom)).detach();
}
//!\brief Returns a writable path to store timestamp and version files or an empty path if none exists.
static std::filesystem::path get_path()
{
using namespace std::filesystem;
path tmp_path;
tmp_path = std::string{getenv(home_env_name)};
tmp_path /= ".config";
// First, create .config if it does not already exist.
std::error_code err;
create_directory(tmp_path, err);
// If this did not fail we, create the seqan subdirectory.
if (!err)
{
tmp_path /= "seqan";
create_directory(tmp_path, err);
}
// .config/seqan cannot be created, try tmp directory.
if (err)
tmp_path = temp_directory_path(); // choose temp dir instead
// check if files can be written inside dir
path dummy = tmp_path / "dummy.txt";
std::ofstream file{dummy};
detail::safe_filesystem_entry file_guard{dummy};
bool is_open = file.is_open();
bool is_good = file.good();
file.close();
file_guard.remove_no_throw();
if (!is_good || !is_open) // no write permissions
{
tmp_path.clear(); // empty path signals no available directory to write to, version check will not be done
}
return tmp_path;
}
/*!\brief The central decision whether to perform the version check or not.
* \param[in] developer_approval Whether the developer approved (true) or not (false).
* \param[in] user_approval Whether the user approved (true) or not (false) or did not decide (unset optional).
*
* The following rules apply:
*
* If the developer says no, it rules out all following decisions (even if the user specified --version-check 1).
* No cookie is ever written.
*
* If the environment variable SEQAN3_NO_VERSION_CHECK is set no version check is done (rules out all following).
* No cookie is written.
*
* If the user explicitly uses the --version-check option (user_approval is set) it rules out all following
* decisions. No cookie is written.
*
* If none of the above apply, version check was not explicitly handled so cookie content is checked:
* * NEVER: Do not perform the version check and do not change the cookie.
* * ALWAYS: Do perform the version check once a day and do not change the cookie.
* * ASK: Ask the user or default the decision once a day.
*
* If the cookie content is "ASK" and the timestamp is older than a day we ask the user,
* if possible (seqan3::detail::is_terminal()), what he wants to do, set the according cookie for the next time
* and continue. If we cannot ask the user, the default kicks in (do the check).
*/
bool decide_if_check_is_performed(bool developer_approval, std::optional<bool> user_approval)
{
if (!developer_approval)
return false;
if (std::getenv("SEQAN3_NO_VERSION_CHECK") != nullptr) // environment variable was set
return false;
if (user_approval.has_value())
return user_approval.value();
// version check was not explicitly handled so let's check the cookie
if (std::filesystem::exists(cookie_path))
{
std::ifstream timestamp_file{timestamp_filename};
std::string cookie_line{};
if (timestamp_file.is_open())
{
std::getline(timestamp_file, cookie_line); // first line contains the timestamp
if (get_time_diff_to_current(cookie_line) < 86400/*one day in seconds*/)
{
return false;
}
std::getline(timestamp_file, cookie_line); // second line contains the last user decision
if (cookie_line == "NEVER")
{
return false;
}
else if (cookie_line == "ALWAYS")
{
return true;
}
// else we do not return but continue to ask the user
timestamp_file.close();
}
}
// Up until now, the user did not specify the --version-check option, the environment variable was not set,
// nor did the the cookie tell us what to do. We will now ask the user if possible or do the check by default.
write_cookie("ASK"); // Ask again next time when we read the cookie, if this is not overwritten.
if (detail::is_terminal()) // LCOV_EXCL_START
{
std::cerr << R"(
#######################################################################
Automatic Update Notifications
#######################################################################
This app can look for updates automatically in the background,
do you want to do that?
[a] Always perform version checks for this app (the default).
[n] Never perform version checks for this app.
[y] Yes, perform a version check now, and ask again tomorrow.
[s] Skip the version check now, but ask again tomorrow.
Please enter one of [a, n, y, s] and press [RETURN].
For more information, see:
https://github.com/seqan/seqan3/wiki/Update-Notifications
#######################################################################
)";
std::string line{};
std::getline(std::cin, line);
line.resize(1); // ignore everything but the first char or resizes the empty string to the default
switch (line[0])
{
case 'y':
{
return true;
}
case 's':
{
return false;
}
case 'n':
{
write_cookie(std::string{"NEVER"}); // overwrite cookie
return false;
}
default:
{
write_cookie(std::string{"ALWAYS"}); // overwrite cookie
return true;
}
}
}
else // if !detail::is_terminal()
{
std::cerr << R"(
#######################################################################
Automatic Update Notifications
#######################################################################
This app performs automatic checks for updates. For more information
see: https://github.com/seqan/seqan3/wiki/Update-Notifications
#######################################################################
)";
return true; // default: check version if you cannot ask the user
}
} // LCOV_EXCL_STOP
//!\brief The identification string that may appear in the version file if an app is unregistered.
static constexpr std::string_view unregistered_app = "UNREGISTERED_APP";
//!\brief The message directed to the developer of the app if a new seqan3 version is available.
static constexpr std::string_view message_seqan3_update =
"[SEQAN3 INFO] :: A new SeqAn version is available online.\n"
"[SEQAN3 INFO] :: Please visit www.github.com/seqan/seqan3.git for an update\n"
"[SEQAN3 INFO] :: or inform the developer of this app.\n"
"[SEQAN3 INFO] :: If you don't wish to receive further notifications, set --version-check OFF.\n\n";
//!\brief The message directed to the developer of the app if the app is not yet registered with us.
static constexpr std::string_view message_unregistered_app =
"[SEQAN3 INFO] :: Thank you for using SeqAn!\n"
"[SEQAN3 INFO] :: Do you wish to register your app for update notifications?\n"
"[SEQAN3 INFO] :: Just send an email to support@seqan.de with your app name and version number.\n"
"[SEQAN3 INFO] :: If you don't wish to receive further notifications, set --version-check OFF.\n\n";
//!\brief The message directed to the developer if the application is registered but under a lower version.
static constexpr std::string_view message_registered_app_update =
"[APP INFO] :: We noticed the app version you use is newer than the one registered with us.\n"
"[APP INFO] :: Please send us an email with the new version so we can correct it (support@seqan.de)\n\n";
//!\brief The message directed to the user of the app if a new app version is available.
std::string message_app_update =
"[APP INFO] :: A new version of this application is now available.\n"
"[APP INFO] :: If you don't wish to receive further notifications, set --version-check OFF.\n\n";
/*Might be extended if a url is given on construction.*/
//!\brief The environment name of the home environment used by getenv()
static constexpr char const * home_env_name
{
#if defined(_WIN32)
"UserProfile"
#else
"HOME"
#endif
};
//!\brief The application name.
std::string name;
//!\brief The version of the application.
std::string version{"0.0.0"};
//!\brief The regex to verify a valid version string.
std::regex version_regex{"^[[:digit:]]+\\.[[:digit:]]+\\.[[:digit:]]+$"};
//!\brief The path to store timestamp and version files (either ~/.config/seqan or the tmp directory).
std::filesystem::path cookie_path = get_path();
//!\brief The timestamp filename.
std::filesystem::path timestamp_filename;
private:
//!\brief Returns the command line call as a std::string of an available program depending on the environment.
static std::string get_program()
{
#if defined(_WIN32)
return "powershell.exe -NoLogo -NonInteractive -Command \"& {Invoke-WebRequest -erroraction 'silentlycontinue' -OutFile";
#else // Unix based platforms.
if (!system("/usr/bin/env -i wget --version > /dev/null 2>&1"))
return "/usr/bin/env -i wget --timeout=10 --tries=1 -q -O";
else if (!system("/usr/bin/env -i curl --version > /dev/null 2>&1"))
return "/usr/bin/env -i curl --connect-timeout 10 -o";
// In case neither wget nor curl is available try ftp/fetch if system is OpenBSD/FreeBSD.
// Note, both systems have ftp/fetch command installed by default so we do not guard against it.
#if defined(__OpenBSD__)
return "/usr/bin/env -i ftp -w10 -Vo";
#elif defined(__FreeBSD__)
return "/usr/bin/env -i fetch --timeout=10 -o";
#else
return "";
#endif // __OpenBSD__
#endif // defined(_WIN32)
}
//!\brief Reads the timestamp file if possible and returns the time difference to the current time.
double get_time_diff_to_current(std::string const & str_time) const
{
namespace co = std::chrono;
double curr = co::duration_cast<co::seconds>(co::system_clock::now().time_since_epoch()).count();
double d_time{};
std::from_chars(str_time.data(), str_time.data() + str_time.size(), d_time);
return curr - d_time;
}
/*!\brief Parses a version string into an array of length 3.
* \param[in] str The version string that must match seqan3::detail::version_regex.
*/
std::array<int, 3> get_numbers_from_version_string(std::string const & str) const
{
std::array<int, 3> result{};
if (!std::regex_match(str, version_regex))
return result;
auto res = std::from_chars(str.data(), str.data() + str.size(), result[0]); // stops and sets res.ptr at '.'
res = std::from_chars(res.ptr + 1, str.data() + str.size(), result[1]);
res = std::from_chars(res.ptr + 1, str.data() + str.size(), result[2]);
return result;
}
/*!\brief Writes a cookie file with a specified message.
* \tparam msg_type The type of message.
* \param[in] msg The message to write into the file (no newline is appended).
*/
template <typename msg_type>
void write_cookie(msg_type && msg)
{
// The current time
namespace co = std::chrono;
auto curr = co::duration_cast<co::seconds>(co::system_clock::now().time_since_epoch()).count();
std::ofstream timestamp_file{timestamp_filename};
if (timestamp_file.is_open())
{
timestamp_file << curr << '\n' << msg;
timestamp_file.close();
}
}
};
} // namespace seqan3
| 42.778203 | 129 | 0.587226 | [
"object"
] |
a1fa34704038d03ba8f3258896d12110ec3d099b | 1,135 | hpp | C++ | Source/FL/ContextFreeGrammar.hpp | flawthegreat/FormalLanguagesPractice2 | ef3e80412ae8f31909259e6c3a64c209b01b32e8 | [
"MIT"
] | null | null | null | Source/FL/ContextFreeGrammar.hpp | flawthegreat/FormalLanguagesPractice2 | ef3e80412ae8f31909259e6c3a64c209b01b32e8 | [
"MIT"
] | null | null | null | Source/FL/ContextFreeGrammar.hpp | flawthegreat/FormalLanguagesPractice2 | ef3e80412ae8f31909259e6c3a64c209b01b32e8 | [
"MIT"
] | null | null | null | #pragma once
#include "Grammar.hpp"
#include <unordered_set>
namespace FL {
class ContextFreeGrammar: public Grammar {
public:
ContextFreeGrammar(Grammar const& grammar);
ContextFreeGrammar(
Alphabet const& terminals,
Alphabet const& nonterminals,
Symbol startSymbol,
std::vector<Rule> const& rules
);
bool isNormalized() const;
void normalize();
ContextFreeGrammar normalized() const;
protected:
bool hasLongRules() const;
void removeLongRules();
std::unordered_set<Symbol> findEpsilonGenerators() const;
void removeEmptyRules();
std::vector<std::pair<Symbol, Symbol>> findChainedPairs() const;
void removeChainRules();
std::unordered_set<Symbol> findGeneratingNonterminals() const;
void removeNonGeneratingRules();
std::unordered_set<Symbol> findReachableNonterminals() const;
void removeNonReachableRules();
void removeMixedRules();
};
struct NonContextFreeGrammarException: std::exception {
char const* what() const throw();
};
struct FoundLongRuleException: std::exception {
char const* what() const throw();
};
}
| 25.222222 | 68 | 0.712775 | [
"vector"
] |
b80049cb53002b08311b327ae31943b4a33bdb6b | 2,857 | hpp | C++ | ThirdParty-mod/java2cpp/org/apache/http/params/HttpAbstractParamBean.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | 1 | 2019-04-03T01:53:28.000Z | 2019-04-03T01:53:28.000Z | ThirdParty-mod/java2cpp/org/apache/http/params/HttpAbstractParamBean.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | null | null | null | ThirdParty-mod/java2cpp/org/apache/http/params/HttpAbstractParamBean.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | null | null | null | /*================================================================================
code generated by: java2cpp
author: Zoran Angelov, mailto://baldzar@gmail.com
class: org.apache.http.params.HttpAbstractParamBean
================================================================================*/
#ifndef J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_ORG_APACHE_HTTP_PARAMS_HTTPABSTRACTPARAMBEAN_HPP_DECL
#define J2CPP_ORG_APACHE_HTTP_PARAMS_HTTPABSTRACTPARAMBEAN_HPP_DECL
namespace j2cpp { namespace java { namespace lang { class Object; } } }
namespace j2cpp { namespace org { namespace apache { namespace http { namespace params { class HttpParams; } } } } }
#include <java/lang/Object.hpp>
#include <org/apache/http/params/HttpParams.hpp>
namespace j2cpp {
namespace org { namespace apache { namespace http { namespace params {
class HttpAbstractParamBean;
class HttpAbstractParamBean
: public object<HttpAbstractParamBean>
{
public:
J2CPP_DECLARE_CLASS
J2CPP_DECLARE_METHOD(0)
J2CPP_DECLARE_FIELD(0)
explicit HttpAbstractParamBean(jobject jobj)
: object<HttpAbstractParamBean>(jobj)
{
}
operator local_ref<java::lang::Object>() const;
HttpAbstractParamBean(local_ref< org::apache::http::params::HttpParams > const&);
}; //class HttpAbstractParamBean
} //namespace params
} //namespace http
} //namespace apache
} //namespace org
} //namespace j2cpp
#endif //J2CPP_ORG_APACHE_HTTP_PARAMS_HTTPABSTRACTPARAMBEAN_HPP_DECL
#else //J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_ORG_APACHE_HTTP_PARAMS_HTTPABSTRACTPARAMBEAN_HPP_IMPL
#define J2CPP_ORG_APACHE_HTTP_PARAMS_HTTPABSTRACTPARAMBEAN_HPP_IMPL
namespace j2cpp {
org::apache::http::params::HttpAbstractParamBean::operator local_ref<java::lang::Object>() const
{
return local_ref<java::lang::Object>(get_jobject());
}
org::apache::http::params::HttpAbstractParamBean::HttpAbstractParamBean(local_ref< org::apache::http::params::HttpParams > const &a0)
: object<org::apache::http::params::HttpAbstractParamBean>(
call_new_object<
org::apache::http::params::HttpAbstractParamBean::J2CPP_CLASS_NAME,
org::apache::http::params::HttpAbstractParamBean::J2CPP_METHOD_NAME(0),
org::apache::http::params::HttpAbstractParamBean::J2CPP_METHOD_SIGNATURE(0)
>(a0)
)
{
}
J2CPP_DEFINE_CLASS(org::apache::http::params::HttpAbstractParamBean,"org/apache/http/params/HttpAbstractParamBean")
J2CPP_DEFINE_METHOD(org::apache::http::params::HttpAbstractParamBean,0,"<init>","(Lorg/apache/http/params/HttpParams;)V")
J2CPP_DEFINE_FIELD(org::apache::http::params::HttpAbstractParamBean,0,"params","Lorg/apache/http/params/HttpParams;")
} //namespace j2cpp
#endif //J2CPP_ORG_APACHE_HTTP_PARAMS_HTTPABSTRACTPARAMBEAN_HPP_IMPL
#endif //J2CPP_INCLUDE_IMPLEMENTATION
| 29.760417 | 134 | 0.719636 | [
"object"
] |
b80171c23b706865af8642110c215b223ba8caf3 | 8,752 | cc | C++ | evpp/event_loop.cc | HLyoung/evpp | 30964e54ed7bb669c52c7daa2aeb01b4453a2c23 | [
"BSD-3-Clause"
] | null | null | null | evpp/event_loop.cc | HLyoung/evpp | 30964e54ed7bb669c52c7daa2aeb01b4453a2c23 | [
"BSD-3-Clause"
] | null | null | null | evpp/event_loop.cc | HLyoung/evpp | 30964e54ed7bb669c52c7daa2aeb01b4453a2c23 | [
"BSD-3-Clause"
] | null | null | null | #include "evpp/inner_pre.h"
#include "evpp/libevent_headers.h"
#include "evpp/libevent_watcher.h"
#include "evpp/event_loop.h"
#include "evpp/invoke_timer.h"
namespace evpp {
EventLoop::EventLoop()
: create_evbase_myself_(true), notified_(false), pending_functor_count_(0) {
#if LIBEVENT_VERSION_NUMBER >= 0x02001500
struct event_config* cfg = event_config_new();
if (cfg) {
// Does not cache time to get a preciser timer
event_config_set_flag(cfg, EVENT_BASE_FLAG_NO_CACHE_TIME);
evbase_ = event_base_new_with_config(cfg);
event_config_free(cfg);
}
#else
evbase_ = event_base_new();
#endif
Init();
}
EventLoop::EventLoop(struct event_base* base)
: evbase_(base), create_evbase_myself_(false), notified_(false), pending_functor_count_(0) {
Init();
// When we build an EventLoop object from an existing event_base object
// we won't call EventLoop::Run method.
// So we need to do the initialization work of watcher_ here.
InitEventWatcher();
}
void EventLoop::InitEventWatcher() {
watcher_.reset(new PipeEventWatcher(this, std::bind(&EventLoop::DoPendingFunctors, this)));
int rc = watcher_->Init();
assert(rc);
rc = rc && watcher_->AsyncWait();
assert(rc);
if (!rc) {
LOG_FATAL << "PipeEventWatcher init failed.";
}
}
EventLoop::~EventLoop() {
if (!create_evbase_myself_) {
assert(watcher_);
watcher_.reset();
}
assert(!watcher_.get());
if (evbase_ != nullptr && create_evbase_myself_) {
event_base_free(evbase_);
evbase_ = nullptr;
}
delete pending_functors_;
pending_functors_ = nullptr;
}
void EventLoop::Init() {
#ifdef H_HAVE_BOOST
enum { kPendingFunctorCount = 1024 * 16 };
this->pending_functors_ = new boost::lockfree::queue<Functor*>(kPendingFunctorCount);
#else
this->pending_functors_ = new std::vector<Functor>();
#endif
running_ = false;
tid_ = std::this_thread::get_id(); // The default thread id
}
void EventLoop::Run() {
tid_ = std::this_thread::get_id(); // The actual thread id
// Initialize it in the EventLoop thread
InitEventWatcher();
// After everything have initialized, mark this running_ flag to true
running_ = true;
int rc = event_base_dispatch(evbase_);
if (rc == 1) {
LOG_ERROR << "event_base_dispatch error: no event registered";
} else if (rc == -1) {
int serrno = errno;
LOG_ERROR << "event_base_dispatch error " << serrno << " " << strerror(serrno);
}
// Make sure watcher_ does construct,initialize and destruct in the same thread.
watcher_.reset();
running_ = false;
LOG_TRACE << "EventLoop stopped, tid: " << std::this_thread::get_id();
}
void EventLoop::Stop() {
assert(running_);
RunInLoop(std::bind(&EventLoop::StopInLoop, this));
}
void EventLoop::StopInLoop() {
LOG_TRACE << "EventLoop is stopping now, tid=" << std::this_thread::get_id();
assert(running_);
auto f = [this]() {
for (;;) {
DoPendingFunctors();
std::lock_guard<std::mutex> lock(mutex_);
if (pending_functors_->empty()) {
break;
}
}
};
f();
#ifdef H_BENCHMARK_TESTING
event_base_loopexit(evbase_, NULL);
#else
timeval tv = Duration(0.5).TimeVal(); // Trick : delay 0.5 second
event_base_loopexit(evbase_, &tv);
#endif
f();
running_ = false;
}
void EventLoop::AfterFork() {
int rc = event_reinit(evbase_);
assert(rc == 0);
if (rc != 0) {
fprintf(stderr, "event_reinit failed!\n");
abort();
}
}
InvokeTimerPtr EventLoop::RunAfter(double delay_ms, const Functor& f) {
return RunAfter(Duration(delay_ms / 1000.0), f);
}
InvokeTimerPtr EventLoop::RunAfter(Duration delay, const Functor& f) {
std::shared_ptr<InvokeTimer> t = InvokeTimer::Create(this, delay, f, false);
t->Start();
return t;
}
evpp::InvokeTimerPtr EventLoop::RunEvery(Duration interval, const Functor& f) {
std::shared_ptr<InvokeTimer> t = InvokeTimer::Create(this, interval, f, true);
t->Start();
return t;
}
void EventLoop::RunInLoop(const Functor& functor) {
if (IsInLoopThread()) {
functor();
} else {
QueueInLoop(functor);
}
}
void EventLoop::QueueInLoop(const Functor& cb) {
//LOG_INFO << "this=" << this << " tid=" << std::this_thread::get_id() << " QueueInLoop notified_=" << notified_.load() << " pending_functor_count_=" << pending_functor_count_;
{
#ifdef H_HAVE_BOOST
auto f = new Functor(cb);
while (!pending_functors_->push(f)) {
}
#else
std::lock_guard<std::mutex> lock(mutex_);
pending_functors_->emplace_back(cb);
#endif
}
++pending_functor_count_;
//LOG_INFO << "this=" << this << " tid=" << std::this_thread::get_id() << " QueueInLoop notified_=" << notified_.load() << ", queue a new Functor. pending_functor_count_=" << pending_functor_count_;
if (!notified_.load()) {
//LOG_INFO << "this=" << this << " tid=" << std::this_thread::get_id() << " QueueInLoop call watcher_->Nofity()";
watcher_->Notify();
//TODO This will cause a bug : miss the notify event and make the functor will never be called.
//TODO performance improvement.
//notified_.store(true);
} else {
//LOG_INFO << "this=" << this << " tid=" << std::this_thread::get_id() << " No need to call watcher_->Nofity()";
}
}
InvokeTimerPtr EventLoop::RunAfter(double delay_ms, Functor&& f) {
return RunAfter(Duration(delay_ms / 1000.0), std::move(f));
}
InvokeTimerPtr EventLoop::RunAfter(Duration delay, Functor&& f) {
std::shared_ptr<InvokeTimer> t = InvokeTimer::Create(this, delay, std::move(f), false);
t->Start();
return t;
}
evpp::InvokeTimerPtr EventLoop::RunEvery(Duration interval, Functor&& f) {
std::shared_ptr<InvokeTimer> t = InvokeTimer::Create(this, interval, std::move(f), true);
t->Start();
return t;
}
void EventLoop::RunInLoop(Functor&& functor) {
if (IsInLoopThread()) {
functor();
} else {
QueueInLoop(std::move(functor));
}
}
void EventLoop::QueueInLoop(Functor&& cb) {
//LOG_INFO << "this=" << this << " tid=" << std::this_thread::get_id() << " QueueInLoop notified_=" << notified_.load() << " pending_functor_count_=" << pending_functor_count_;
{
#ifdef H_HAVE_BOOST
auto f = new Functor(std::move(cb)); // TODO Add test code for it
while (!pending_functors_->push(f)) {
}
#else
std::lock_guard<std::mutex> lock(mutex_);
pending_functors_->emplace_back(std::move(cb));
#endif
}
++pending_functor_count_;
//LOG_INFO << "this=" << this << " tid=" << std::this_thread::get_id() << " QueueInLoop notified_=" << notified_.load() << ", queue a new Functor. pending_functor_count_=" << pending_functor_count_;
if (!notified_.load()) {
//LOG_INFO << "this=" << this << " tid=" << std::this_thread::get_id() << " QueueInLoop call watcher_->Nofity()";
watcher_->Notify();
//TODO This will cause a bug : miss the notify event and make the functor will never be called.
//TODO performance improvement.
//notified_.store(true);
} else {
//LOG_INFO << "this=" << this << " tid=" << std::this_thread::get_id() << " No need to call watcher_->Nofity()";
}
}
void EventLoop::DoPendingFunctors() {
//LOG_INFO << "this=" << this << " tid=" << std::this_thread::get_id() << " DoPendingFunctors pending_functor_count_=" << pending_functor_count_;
#ifdef H_HAVE_BOOST
Functor* f = nullptr;
while (pending_functors_->pop(f)) {
(*f)();
delete f;
--pending_functor_count_;
}
notified_.store(false);
#else
std::vector<Functor> functors;
{
std::lock_guard<std::mutex> lock(mutex_);
notified_.store(false);
pending_functors_->swap(functors);
//LOG_INFO << "this=" << this << " tid=" << std::this_thread::get_id() << " DoPendingFunctors pending_functor_count_=" << pending_functor_count_ << "notified_=" << notified_.load();
}
//LOG_INFO << "this=" << this << " tid=" << std::this_thread::get_id() << " DoPendingFunctors pending_functor_count_=" << pending_functor_count_ << "notified_=" << notified_.load();
for (size_t i = 0; i < functors.size(); ++i) {
functors[i]();
--pending_functor_count_;
}
//LOG_INFO << "this=" << this << " tid=" << std::this_thread::get_id() << " DoPendingFunctors pending_functor_count_=" << pending_functor_count_ << "notified_=" << notified_.load();
#endif
}
void EventLoop::AssertInLoopThread() const {
assert(IsInLoopThread());
}
}
| 32.295203 | 202 | 0.632998 | [
"object",
"vector"
] |
b8023dfe735a9646c376b6ea357dd885d9bedb97 | 467 | hpp | C++ | Algorithms/1Base/unionFind.hpp | CainHsu/ProgramStudy-leetcode | 23653e8927902aed64ba13a23a1d6c983b7ea5d5 | [
"Apache-2.0"
] | 1 | 2019-12-08T06:21:57.000Z | 2019-12-08T06:21:57.000Z | Algorithms/1Base/unionFind.hpp | CainHsu/ProgramStudy-leetcode | 23653e8927902aed64ba13a23a1d6c983b7ea5d5 | [
"Apache-2.0"
] | null | null | null | Algorithms/1Base/unionFind.hpp | CainHsu/ProgramStudy-leetcode | 23653e8927902aed64ba13a23a1d6c983b7ea5d5 | [
"Apache-2.0"
] | null | null | null | //
// Created by xuche on 2020/6/4.
//
#ifndef PROGRAMSTUDY_LEETCODE_UNIONFIND_HPP
#define PROGRAMSTUDY_LEETCODE_UNIONFIND_HPP
#include "vector"
using namespace std;
class UnionFind {
private:
vector<int> id;
vector<int> size;
static int count;
public:
explicit UnionFind(int N);
void unionNodes(int p, int q);
int find(int p);
bool connected(int p, int q);
static int getCount();
};
#endif //PROGRAMSTUDY_LEETCODE_UNIONFIND_HPP
| 17.296296 | 44 | 0.708779 | [
"vector"
] |
b802a179ac72f78a9e5df8044f3196e16041feb1 | 559 | hpp | C++ | images/imagedb/include/fs/fs.hpp | jeoygin/gadget | de703b53576eac7d11d625316a46a47e57596dcb | [
"MIT"
] | null | null | null | images/imagedb/include/fs/fs.hpp | jeoygin/gadget | de703b53576eac7d11d625316a46a47e57596dcb | [
"MIT"
] | null | null | null | images/imagedb/include/fs/fs.hpp | jeoygin/gadget | de703b53576eac7d11d625316a46a47e57596dcb | [
"MIT"
] | null | null | null | #ifndef FS_HPP
#define FS_HPP
#include <unistd.h>
#include <string>
#include <vector>
using namespace std;
namespace fs {
bool dir_exists(const char* dir);
bool dir_exists(const string& dir);
bool file_exists(const char* file);
bool file_exists(const string& file);
int make_dir(const char * dir, mode_t mode);
int make_dir(const string& dir);
string get_dirname(const string& path);
string get_basename(const string& path);
void list_file(const string& dir, vector<string>& files);
} // namespace fs
#endif // FS_HPP
| 23.291667 | 61 | 0.703041 | [
"vector"
] |
b805c21647d6916254e152b571f438e7fc54ffc5 | 2,508 | hpp | C++ | openstudiocore/src/openstudio_lib/OSAppBase.hpp | ORNL-BTRIC/OpenStudio | 878f94bebf6f025445d1373e8b2304ececac16d8 | [
"blessing"
] | null | null | null | openstudiocore/src/openstudio_lib/OSAppBase.hpp | ORNL-BTRIC/OpenStudio | 878f94bebf6f025445d1373e8b2304ececac16d8 | [
"blessing"
] | null | null | null | openstudiocore/src/openstudio_lib/OSAppBase.hpp | ORNL-BTRIC/OpenStudio | 878f94bebf6f025445d1373e8b2304ececac16d8 | [
"blessing"
] | null | null | null | /**********************************************************************
* Copyright (c) 2008-2014, Alliance for Sustainable Energy.
* All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********************************************************************/
#ifndef OPENSTUDIO_OSAPPBASE_H
#define OPENSTUDIO_OSAPPBASE_H
#include "../shared_gui_components/BaseApp.hpp"
#include <ruleset/RubyUserScriptArgumentGetter.hpp>
#include <openstudio_lib/OpenStudioAPI.hpp>
#include <utilities/core/Logger.hpp>
#include <QApplication>
#include <boost/smart_ptr.hpp>
namespace openstudio {
class OSDocument;
class OPENSTUDIO_API OSAppBase : public QApplication, public BaseApp
{
Q_OBJECT
public:
OSAppBase( int & argc, char ** argv, const QSharedPointer<MeasureManager> &t_measureManager);
virtual ~OSAppBase();
virtual boost::shared_ptr<OSDocument> currentDocument() const = 0;
static OSAppBase * instance();
virtual boost::optional<openstudio::analysisdriver::SimpleProject> project();
virtual QWidget *mainWidget();
virtual MeasureManager &measureManager();
virtual boost::optional<openstudio::model::Model> currentModel();
virtual void updateSelectedMeasureState();
virtual void addMeasure();
virtual void duplicateSelectedMeasure();
virtual void updateMyMeasures();
virtual void updateBCLMeasures();
virtual void downloadUpdatedBCLMeasures();
virtual void openBclDlg();
virtual void chooseHorizontalEditTab();
virtual QSharedPointer<openstudio::EditController> editController();
private:
REGISTER_LOGGER("openstudio.OSAppBase");
QSharedPointer<openstudio::MeasureManager> m_measureManager;
};
} // openstudio
#endif // OPENSTUDIO_OSAPPBASE_H
| 32.153846 | 96 | 0.698166 | [
"model"
] |
b80953f576121134e8ad1ab358250b69b83805f2 | 8,639 | cpp | C++ | plugins/mesh/src/MeshBakery.cpp | voei/megamol | 569b7b58c1f9bc5405b79549b86f84009329f668 | [
"BSD-3-Clause"
] | null | null | null | plugins/mesh/src/MeshBakery.cpp | voei/megamol | 569b7b58c1f9bc5405b79549b86f84009329f668 | [
"BSD-3-Clause"
] | null | null | null | plugins/mesh/src/MeshBakery.cpp | voei/megamol | 569b7b58c1f9bc5405b79549b86f84009329f668 | [
"BSD-3-Clause"
] | null | null | null | #include "MeshBakery.h"
#include "mmcore/param/EnumParam.h"
megamol::mesh::MeshBakery::MeshBakery()
: core::Module()
, m_version(0)
, m_mesh_access_collection(nullptr)
, m_geometry_type("GeometryType", "...")
, m_mesh_lhs_slot("deployMeshAccess", "...")
, m_mesh_rhs_slot("chainMeshAccess", "...")
{
this->m_geometry_type << new megamol::core::param::EnumParam(0);
this->m_geometry_type.Param<megamol::core::param::EnumParam>()->SetTypePair(0, "Quad");
this->m_geometry_type.Param<megamol::core::param::EnumParam>()->SetTypePair(1, "Cone");
this->MakeSlotAvailable(&this->m_geometry_type);
this->m_mesh_lhs_slot.SetCallback(CallMesh::ClassName(), "GetData", &MeshBakery::getDataCallback);
this->m_mesh_lhs_slot.SetCallback(CallMesh::ClassName(), "GetMetaData", &MeshBakery::getMetaDataCallback);
this->MakeSlotAvailable(&this->m_mesh_lhs_slot);
this->m_mesh_rhs_slot.SetCompatibleCall<CallMeshDescription>();
this->MakeSlotAvailable(&this->m_mesh_rhs_slot);
}
megamol::mesh::MeshBakery::~MeshBakery() { this->Release(); }
bool megamol::mesh::MeshBakery::create(void) {
this->m_mesh_access_collection = std::make_shared<MeshDataAccessCollection>();
return true;
}
void megamol::mesh::MeshBakery::release() {}
bool megamol::mesh::MeshBakery::getDataCallback(core::Call& caller) {
CallMesh* lhs_mesh_call = dynamic_cast<CallMesh*>(&caller);
CallMesh* rhs_mesh_call = m_mesh_rhs_slot.CallAs<CallMesh>();
if (lhs_mesh_call == NULL) return false;
std::shared_ptr<MeshDataAccessCollection> mesh_access_collection(nullptr);
if (lhs_mesh_call->getData() == nullptr) {
// no incoming mesh -> use your own mesh storage
mesh_access_collection = this->m_mesh_access_collection;
} else {
// incoming mesh -> use it (delete local?)
mesh_access_collection = lhs_mesh_call->getData();
}
//TODO check chain
if (m_geometry_type.IsDirty()) {
m_geometry_type.ResetDirty();
++m_version;
//TODO call geometry generating functions
createConeGeometry();
std::array<float, 6> bbox;
bbox[0] = std::numeric_limits<float>::max();
bbox[1] = std::numeric_limits<float>::max();
bbox[2] = std::numeric_limits<float>::max();
bbox[3] = std::numeric_limits<float>::min();
bbox[4] = std::numeric_limits<float>::min();
bbox[5] = std::numeric_limits<float>::min();
bbox[0] = -1.0f;
bbox[1] = -1.0f;
bbox[2] = -1.0f;
bbox[3] = 1.0f;
bbox[4] = 1.0f;
bbox[5] = 1.0f;
std::vector<MeshDataAccessCollection::VertexAttribute> mesh_attributes;
MeshDataAccessCollection::IndexData mesh_indices;
mesh_indices.byte_size = m_indices.size() * sizeof(uint32_t);
mesh_indices.data = reinterpret_cast<uint8_t*>(m_indices.data());
mesh_indices.type = MeshDataAccessCollection::UNSIGNED_INT;
mesh_attributes.emplace_back(MeshDataAccessCollection::VertexAttribute{
reinterpret_cast<uint8_t*>(m_vertex_normals.data()), m_vertex_normals.size() * sizeof(float), 3,
MeshDataAccessCollection::FLOAT, 0, 0, MeshDataAccessCollection::NORMAL});
mesh_attributes.emplace_back(MeshDataAccessCollection::VertexAttribute{
reinterpret_cast<uint8_t*>(m_vertex_positions.data()), m_vertex_positions.size() * sizeof(float), 3,
MeshDataAccessCollection::FLOAT, 0, 0, MeshDataAccessCollection::POSITION});
mesh_attributes.emplace_back(MeshDataAccessCollection::VertexAttribute{
reinterpret_cast<uint8_t*>(m_vertex_tangents.data()), m_vertex_tangents.size() * sizeof(float), 3,
MeshDataAccessCollection::FLOAT, 0, 0, MeshDataAccessCollection::TANGENT});
mesh_attributes.emplace_back(MeshDataAccessCollection::VertexAttribute{
reinterpret_cast<uint8_t*>(m_vertex_uvs.data()), m_vertex_uvs.size() * sizeof(float), 2,
MeshDataAccessCollection::FLOAT, 0, 0, MeshDataAccessCollection::TEXCOORD});
mesh_access_collection->addMesh(mesh_attributes, mesh_indices);
auto meta_data = lhs_mesh_call->getMetaData();
meta_data.m_bboxs.SetBoundingBox(bbox[0], bbox[1], bbox[2], bbox[3], bbox[4], bbox[5]);
meta_data.m_bboxs.SetClipBox(bbox[0], bbox[1], bbox[2], bbox[3], bbox[4], bbox[5]);
lhs_mesh_call->setMetaData(meta_data);
}
lhs_mesh_call->setData(mesh_access_collection, m_version);
return true;
}
bool megamol::mesh::MeshBakery::getMetaDataCallback(core::Call& caller) {
CallMesh* lhs_mesh_call = dynamic_cast<CallMesh*>(&caller);
CallMesh* rhs_mesh_call = m_mesh_rhs_slot.CallAs<CallMesh>();
if (lhs_mesh_call == NULL) return false;
auto lhs_meta_data = lhs_mesh_call->getMetaData();
bool something_has_changed = false; // something has changed in the neath...
unsigned int frame_cnt = std::numeric_limits<unsigned int>::max();
auto bbox = lhs_meta_data.m_bboxs.BoundingBox();
auto cbbox = lhs_meta_data.m_bboxs.ClipBox();
if (rhs_mesh_call != NULL) {
auto rhs_meta_data = rhs_mesh_call->getMetaData();
rhs_meta_data.m_frame_ID = lhs_meta_data.m_frame_ID;
rhs_mesh_call->setMetaData(rhs_meta_data);
if (!(*rhs_mesh_call)(1)) return false;
rhs_meta_data = rhs_mesh_call->getMetaData();
something_has_changed = rhs_mesh_call->hasUpdate();
frame_cnt = std::min(rhs_meta_data.m_frame_cnt, frame_cnt);
bbox.Union(rhs_meta_data.m_bboxs.BoundingBox());
cbbox.Union(rhs_meta_data.m_bboxs.ClipBox());
}
lhs_meta_data.m_frame_cnt = frame_cnt;
lhs_meta_data.m_bboxs.SetBoundingBox(bbox);
lhs_meta_data.m_bboxs.SetClipBox(cbbox);
lhs_mesh_call->setMetaData(lhs_meta_data);
return true;
}
void megamol::mesh::MeshBakery::createTriangleGeometry() {}
void megamol::mesh::MeshBakery::createConeGeometry() {
m_vertex_positions.clear();
m_vertex_normals.clear();
m_vertex_tangents.clear();
m_vertex_uvs.clear();
m_vertex_colors.clear();
m_indices.clear();
int segments = 8;
float radius = 0.05f;
float height = 1.0f;
float alpha = std::atan(radius / height);
//TODO create cone base
//TODO create cone side
for (int i = 0; i < segments; ++i) {
float x = 0.0f, y = 0.0f, z = 0.0f;
x = radius * std::sin(static_cast<float>(i) / static_cast<float>(segments) * 2.0f * 3.14159265359f);
y = radius * std::cos(static_cast<float>(i) / static_cast<float>(segments) * 2.0f * 3.14159265359f);
float nx = x, ny = y;
float nz = std::tan(alpha) * radius;
float nl = std::sqrt(nx * nx + ny * ny + nz * nz);
m_vertex_positions.push_back(x);
m_vertex_positions.push_back(y);
m_vertex_positions.push_back(z);
m_vertex_normals.push_back(nx/nl);
m_vertex_normals.push_back(ny/nl);
m_vertex_normals.push_back(nz/nl);
m_vertex_tangents.push_back(y/radius);
m_vertex_tangents.push_back(x/radius);
m_vertex_tangents.push_back(z/radius);
m_vertex_uvs.push_back(0.0f);
m_vertex_uvs.push_back(0.0f);
}
//TODO cone tip vertices
for (int i = 0; i < segments; ++i) {
float x = 0.0f, y = 0.0f, z = height;
float nx = (m_vertex_normals[i * 3 + 0] + m_vertex_normals[((i+1) % segments) * 3 + 0]) / 2.0f;
float ny = (m_vertex_normals[i * 3 + 1] + m_vertex_normals[((i+1) % segments) * 3 + 1]) / 2.0f;
float nz = (m_vertex_normals[i * 3 + 2] + m_vertex_normals[((i+1) % segments) * 3 + 2]) / 2.0f;
float tx = (m_vertex_tangents[i * 3 + 0] + m_vertex_tangents[((i + 1) % segments) * 3 + 0]) / 2.0f;
float ty = (m_vertex_tangents[i * 3 + 1] + m_vertex_tangents[((i + 1) % segments) * 3 + 1]) / 2.0f;
float tz = (m_vertex_tangents[i * 3 + 2] + m_vertex_tangents[((i + 1) % segments) * 3 + 2]) / 2.0f;
m_vertex_positions.push_back(x);
m_vertex_positions.push_back(y);
m_vertex_positions.push_back(z);
m_vertex_normals.push_back(nx);
m_vertex_normals.push_back(ny);
m_vertex_normals.push_back(nz);
m_vertex_tangents.push_back(tx);
m_vertex_tangents.push_back(tx);
m_vertex_tangents.push_back(tx);
m_vertex_uvs.push_back(0.0f);
m_vertex_uvs.push_back(0.0f);
}
for (uint32_t i = 0; i < segments; ++i) {
m_indices.push_back(i);
m_indices.push_back( (i+1) % segments );
m_indices.push_back(i + segments);
}
}
| 36.918803 | 112 | 0.660377 | [
"mesh",
"geometry",
"vector"
] |
b80d66ce6b6f67cd448694e458bbac3014c04cba | 4,849 | cpp | C++ | Tetrahedral_remeshing/test/Tetrahedral_remeshing/test_tetrahedral_remeshing_with_features.cpp | brucerennie/cgal | 314b94aafa9b08a1d086accd2cadff1aae1b57a9 | [
"CC0-1.0"
] | 3,227 | 2015-03-05T00:19:18.000Z | 2022-03-31T08:20:35.000Z | Tetrahedral_remeshing/test/Tetrahedral_remeshing/test_tetrahedral_remeshing_with_features.cpp | brucerennie/cgal | 314b94aafa9b08a1d086accd2cadff1aae1b57a9 | [
"CC0-1.0"
] | 5,574 | 2015-03-05T00:01:56.000Z | 2022-03-31T15:08:11.000Z | Tetrahedral_remeshing/test/Tetrahedral_remeshing/test_tetrahedral_remeshing_with_features.cpp | brucerennie/cgal | 314b94aafa9b08a1d086accd2cadff1aae1b57a9 | [
"CC0-1.0"
] | 1,274 | 2015-03-05T00:01:12.000Z | 2022-03-31T14:47:56.000Z | #define CGAL_TETRAHEDRAL_REMESHING_VERBOSE
#define CGAL_TETRAHEDRAL_REMESHING_GENERATE_INPUT_FILES
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Tetrahedral_remeshing/Remeshing_triangulation_3.h>
#include <CGAL/tetrahedral_remeshing.h>
#include <CGAL/Tetrahedral_remeshing/tetrahedral_remeshing_io.h>
#include <CGAL/Random.h>
#include <CGAL/property_map.h>
#include <boost/unordered_set.hpp>
#include <iostream>
#include <fstream>
#include <vector>
#include <utility>
typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
typedef CGAL::Tetrahedral_remeshing::Remeshing_triangulation_3<K> Remeshing_triangulation;
typedef Remeshing_triangulation::Point Point;
typedef Remeshing_triangulation::Vertex_handle Vertex_handle;
typedef Remeshing_triangulation::Cell_handle Cell_handle;
typedef Remeshing_triangulation::Edge Edge;
class Constrained_edges_property_map
{
public:
typedef bool value_type;
typedef bool reference;
typedef std::pair<Vertex_handle, Vertex_handle> key_type;
typedef boost::read_write_property_map_tag category;
private:
boost::unordered_set<key_type>* m_set_ptr;
public:
Constrained_edges_property_map()
: m_set_ptr(nullptr)
{}
Constrained_edges_property_map(boost::unordered_set<key_type>* set_)
: m_set_ptr(set_)
{}
public:
friend void put(Constrained_edges_property_map& map,
const key_type& k,
const value_type b)
{
CGAL_assertion(map.m_set_ptr != nullptr);
CGAL_assertion(k.first < k.second);
if (b) map.m_set_ptr->insert(k);
else map.m_set_ptr->erase(k);
}
friend value_type get(const Constrained_edges_property_map& map,
const key_type& k)
{
CGAL_assertion(map.m_set_ptr != nullptr);
CGAL_assertion(k.first < k.second);
return map.m_set_ptr->count(k) > 0;
}
};
void add_edge(Vertex_handle v1,
Vertex_handle v2,
const Remeshing_triangulation& tr,
boost::unordered_set<std::pair<Vertex_handle, Vertex_handle> >& constraints)
{
Cell_handle c;
int i, j;
if(tr.is_edge(v1, v2, c, i, j))
constraints.insert(std::make_pair(v1, v2));
}
void generate_input_cube(const std::size_t& n,
Remeshing_triangulation& tr,
boost::unordered_set<std::pair<Vertex_handle, Vertex_handle> >& constraints)
{
CGAL::Random rng;
// points in a sphere
std::vector<Point> pts;
while (pts.size() < n)
pts.push_back(Point(rng.get_double(-1., 1.), rng.get_double(-1., 1.), rng.get_double(-1., 1.)));
tr.insert(pts.begin(), pts.end());
// vertices of a larger cube
Vertex_handle v0 = tr.insert(Point(-2., -2., -2.));
Vertex_handle v1 = tr.insert(Point(-2., -2., 2.));
Vertex_handle v2 = tr.insert(Point( 2., -2., -2.));
Vertex_handle v3 = tr.insert(Point( 2., -2., 2.));
Vertex_handle v4 = tr.insert(Point(-2., 2., -2.));
Vertex_handle v5 = tr.insert(Point(-2., 2., 2.));
Vertex_handle v6 = tr.insert(Point( 2., 2., -2.));
Vertex_handle v7 = tr.insert(Point( 2., 2., 2.));
CGAL_assertion(tr.is_valid(true));
// writing file output
#ifdef CGAL_TETRAHEDRAL_REMESHING_GENERATE_INPUT_FILES
std::ofstream outfile("data/sphere_in_cube.tr.cgal",
std::ios_base::out | std::ios_base::binary);
CGAL::save_binary_triangulation(outfile, tr);
outfile.close();
#endif
// constrain cube edges
add_edge(v0, v1, tr, constraints);
add_edge(v1, v2, tr, constraints);
add_edge(v2, v3, tr, constraints);
add_edge(v3, v0, tr, constraints);
add_edge(v4, v5, tr, constraints);
add_edge(v5, v6, tr, constraints);
add_edge(v6, v7, tr, constraints);
add_edge(v7, v4, tr, constraints);
add_edge(v0, v4, tr, constraints);
add_edge(v1, v5, tr, constraints);
add_edge(v2, v6, tr, constraints);
add_edge(v3, v7, tr, constraints);
CGAL_assertion(tr.is_valid(true));
}
void set_subdomain(Remeshing_triangulation& tr, const int index)
{
for (Cell_handle c : tr.finite_cell_handles())
c->set_subdomain_index(index);
}
int main(int argc, char* argv[])
{
CGAL::Random rng;
std::cout << "CGAL Random seed = " << CGAL::get_default_random().get_seed() << std::endl;
Remeshing_triangulation tr;
boost::unordered_set<std::pair<Vertex_handle, Vertex_handle> > constraints;
generate_input_cube(1000, tr, constraints);
const double target_edge_length = (argc > 1) ? atof(argv[1]) : 0.02;
const int nb_iter = (argc > 2) ? atoi(argv[2]) : 1;
set_subdomain(tr, 1);
assert(tr.is_valid());
CGAL::tetrahedral_isotropic_remeshing(tr, target_edge_length,
CGAL::parameters::edge_is_constrained_map(
Constrained_edges_property_map(&constraints))
.number_of_iterations(nb_iter));
return EXIT_SUCCESS;
}
| 29.932099 | 100 | 0.693133 | [
"vector"
] |
b80fb1a288af28cec18e9395a5d27eec15b3e0b5 | 31,125 | cpp | C++ | odbc/src/DolphinDBODBC.cpp | hotpoor/DolphinDBPlugin | 9eed3f591929440630daf993d3552814bf7fde1a | [
"Apache-2.0"
] | null | null | null | odbc/src/DolphinDBODBC.cpp | hotpoor/DolphinDBPlugin | 9eed3f591929440630daf993d3552814bf7fde1a | [
"Apache-2.0"
] | null | null | null | odbc/src/DolphinDBODBC.cpp | hotpoor/DolphinDBPlugin | 9eed3f591929440630daf993d3552814bf7fde1a | [
"Apache-2.0"
] | null | null | null | /*
* DolphinDBODBC.cpp
*
* Created on: May 26, 2017
* Author: xinjing.zhou
*/
#include "DolphinDBODBC.h"
#include "Util.h"
#ifndef LINUX
#include <windows.h>
#endif
#include <sql.h>
#include <sqlext.h>
#include <cassert>
#include <climits>
#include <cstdio>
#include <iostream>
#include <locale>
#include <vector>
#include "cvt.h"
#include "nanodbc/nanodbc.h"
#include <fstream>
#include <iostream>
//#define DEBUGlog
#ifdef DEBUGlog
std::ofstream sqlodbcfs;
string sqlodbcfslog = "/home/ybzhang/DolphinDBPlugin/odbctable.log";
#endif
using namespace std;
static void odbcConnectionOnClose(Heap* heap, vector<ConstantSP>& args) {
nanodbc::connection* cp = (nanodbc::connection*)(args[0]->getLong());
if (cp != nullptr) {
delete cp;
args[0]->setLong(0);
}
}
static const int useStringSizeThreshold = 30;
static inline DATA_TYPE sqltype2DataType(int sqltype, long colsize) {
// https://docs.microsoft.com/en-us/sql/odbc/reference/appendixes/c-data-types
switch (sqltype) {
case SQL_BIT:
return DT_BOOL;
case SQL_TINYINT:
case SQL_SMALLINT:
return DT_SHORT;
case SQL_INTEGER:
return DT_INT;
case SQL_BIGINT:
return DT_LONG;
case SQL_REAL:
return DT_FLOAT;
case SQL_FLOAT:
case SQL_DOUBLE:
case SQL_DECIMAL:
case SQL_NUMERIC:
return DT_DOUBLE;
case SQL_DATE:
case SQL_TYPE_DATE:
return DT_DATE;
break;
case SQL_TIME:
case SQL_TYPE_TIME:
return DT_SECOND;
case SQL_TIMESTAMP:
case SQL_TYPE_TIMESTAMP:
return DT_NANOTIMESTAMP;
case SQL_CHAR:
if (colsize == 1) {
return DT_CHAR;
}
// fall-through
default:
if ((sqltype == SQL_CHAR || sqltype == SQL_VARCHAR) &&
colsize <= useStringSizeThreshold) {
return DT_SYMBOL;
}
return DT_STRING;
}
}
static bool compatible(DATA_TYPE dolphinType, int sqlType, int colsize) {
switch (dolphinType) {
case DT_BOOL:
case DT_CHAR:
case DT_SHORT:
case DT_INT:
case DT_LONG:
case DT_FLOAT:
case DT_DOUBLE:
switch (sqlType) {
case SQL_BIT:
case SQL_TINYINT:
case SQL_SMALLINT:
case SQL_INTEGER:
case SQL_BIGINT:
case SQL_REAL:
case SQL_FLOAT:
case SQL_DOUBLE:
case SQL_NUMERIC:
case SQL_DECIMAL:
return true;
case SQL_CHAR:
if (colsize == 1) return true;
default:
return false;
}
case DT_DATE:
case DT_TIMESTAMP:
case DT_NANOTIMESTAMP:
switch (sqlType) {
case SQL_DATE:
case SQL_TYPE_DATE:
case SQL_TIMESTAMP:
case SQL_TYPE_TIMESTAMP:
return true;
default:
return false;
}
case DT_SECOND:
case DT_TIME:
case DT_NANOTIME:
switch (sqlType) {
case SQL_TYPE_TIME:
case SQL_TIME:
return true;
default:
return false;
}
case DT_STRING:
case DT_SYMBOL:
return true;
default:
return false;
}
}
// creates a new native odbc connection if the first argument is a connection
// string. returns the native odbc connection if the first argument is a
// DT_RESOURCE type.
static ConstantSP odbcGetConnection(Heap* heap, vector<ConstantSP>& args,
const string& funcName) {
if (args[0]->getType() == DT_STRING) {
u16string connStr = utf8_to_utf16(args[0]->getString());
try {
unique_ptr<nanodbc::connection> cup(new nanodbc::connection(connStr));
const char* fmt = "odbc connection to [%s]";
vector<char> descBuf(connStr.size() + strlen(fmt));
sprintf(descBuf.data(), fmt, connStr.c_str());
FunctionDefSP onClose(Util::createSystemProcedure(
"odbc connection onClose()", odbcConnectionOnClose, 1, 1));
Constant* res =
Util::createResource((long long)cup.release(), descBuf.data(),
onClose, heap->currentSession());
return res;
} catch (const runtime_error& e) {
const char* fmt = "error connecting to [%s]: %s";
vector<char> errorMsgBuf(connStr.size() + strlen(e.what()) + strlen(fmt));
sprintf(errorMsgBuf.data(), fmt, connStr.c_str(), e.what());
throw TableRuntimeException(errorMsgBuf.data());
}
} else if (args[0]->getType() == DT_RESOURCE) {
return args[0];
} else {
throw IllegalArgumentException(
funcName,
"Unknown argument type, must be a connection string or odbc connection "
"handle");
}
}
static TableSP odbcGetOrCreateTable(const Heap* heap,
const vector<ConstantSP>& args,
const nanodbc::result& results,
vector<ConstantSP>& columnVecs) {
int symbolCount = 0;
if (args.size() >= 3 && args[2]->getType() != DT_VOID) {
if (args[2]->getForm() != DF_TABLE) {
throw TableRuntimeException("The 3rd argument must be a table");
}
TableSP tblSP(args[2]);
INDEX columns = tblSP->columns();
if (columns != results.columns()) {
throw TableRuntimeException(
"The given table schema is incompatible with the returned table from "
"ODBC (different column count)");
}
for (INDEX i = 0; i < columns; ++i) {
// Vector* col = (Vector*)tblSP->getColumn(i).get();
DATA_TYPE dolphinType = tblSP->getColumnType(i);
if (!compatible(dolphinType, results.column_datatype(i),
results.column_size(i))) {
const char* fmt =
"The given table schema is incompatible with the returned table "
"from ODBC at column %d[%s]";
vector<char> descBuf(10 + strlen(fmt) + results.column_name(i).size());
sprintf(descBuf.data(), fmt, i, results.column_name(i).c_str());
throw TableRuntimeException(descBuf.data());
}
if (dolphinType == DT_SYMBOL) {
// if(!tblSP->isSegmentedTable())
columnVecs[i] = Util::createSymbolVector(nullptr, 0);
symbolCount++;
} else {
columnVecs[i] = Util::createVector(dolphinType, 0);
}
}
return tblSP;
} else {
short columns = results.columns();
vector<string> columnNames(columns);
vector<DATA_TYPE> columnTypes(columns);
for (short i = 0; i < columns; ++i) {
columnNames[i] = utf16_to_utf8(results.column_name(i));
columnTypes[i] =
sqltype2DataType(results.column_datatype(i), results.column_size(i));
if (columnTypes[i] == DT_SYMBOL) {
symbolCount++;
}
}
// multiple columns share the same symbolbase
SymbolBaseSP symbolBaseSP;
if (symbolCount > 0) {
symbolBaseSP = new SymbolBase();
}
for (short i = 0; i < columns; ++i) {
if (columnTypes[i] == DT_SYMBOL) {
columnVecs[i] = Util::createSymbolVector(symbolBaseSP, 0);
} else {
columnVecs[i] = Util::createVector(columnTypes[i], 0);
}
}
return Util::createTable(columnNames, columnTypes, 0, 1);
}
}
ConstantSP odbcClose(Heap* heap, vector<ConstantSP>& args) {
assert(heap);
assert(args.size() == 1);
if (args[0]->getType() != DT_RESOURCE) {
throw IllegalArgumentException(
"odbc::close",
"Unknown argument type, must be an odbc connection handle");
}
ConstantSP csp = odbcGetConnection(heap, args, "odbc::close");
nanodbc::connection* cp = (nanodbc::connection*)(csp->getLong());
cp->disconnect();
return Util::createConstant(DT_VOID);
}
ConstantSP odbcConnect(Heap* heap, vector<ConstantSP>& args) {
assert(heap);
assert(args.size() == 1);
if (args[0]->getType() != DT_STRING) {
throw IllegalArgumentException(
"odbc::connect",
"Unknown argument type, must be an odbc connection string");
}
return odbcGetConnection(heap, args, "odbc::connect");
}
ConstantSP odbcQuery(Heap* heap, vector<ConstantSP>& args) {
const static int nanodbc_rowset_size = 4096;
assert(heap);
assert(args.size() >= 2);
// Encoding srcEncoding = Encoding::UTF8;
#ifdef WINDOWS
if (args.size() == 4 && args[3]->getType() != DT_VOID) {
if (args[3]->getType() != DT_STRING || args[3]->getForm() != DF_SCALAR) {
throw IllegalArgumentException(
"odbc::query",
"The 4th argument must be the name of encoding, e.g.(GB2312)");
}
if (Util::lower(args[3]->getString()) == "gb2312") {
auto srcEncoding = Encoding::GB2312;
} else {
throw IllegalArgumentException(
"odbc::query",
"The 4th argument must be the name of encoding, e.g.(GB2312)");
}
}
#endif
u16string querySql = utf8_to_utf16(args[1]->getString());
ConstantSP csp = odbcGetConnection(heap, args, "odbc::query");
nanodbc::connection* cp = (nanodbc::connection*)(csp->getLong());
nanodbc::result results;
try {
results = nanodbc::execute(*cp, querySql, nanodbc_rowset_size);
} catch (const runtime_error& e) {
const char* fmt = "Executed query [%s]: %s";
vector<char> errorMsgBuf(querySql.size() + strlen(e.what()) + strlen(fmt));
sprintf(errorMsgBuf.data(), fmt, querySql.c_str(), e.what());
throw TableRuntimeException(errorMsgBuf.data());
}
const short columns = results.columns();
vector<ConstantSP> columnVecs(columns);
vector<Vector*> arrCol(columns);
vector<DATA_TYPE> columnTypes(columns);
TableSP table = odbcGetOrCreateTable(heap, args, results, columnVecs);
for (short i = 0; i < columns; ++i) {
arrCol[i] = (Vector*)columnVecs[i].get();
columnTypes[i] = arrCol[i]->getType();
}
const int BUF_SIZE = 256 * 1024;
vector<vector<U8>> buffers =
vector<vector<U8>>(columns, vector<U8>(BUF_SIZE));
int curLine = 0, rowIdx = 0;
char charBuf[BUF_SIZE];
short shortBuf[BUF_SIZE];
U4 buf[BUF_SIZE];
bool hasNext = results.next();
vector<std::string> colNames(columns);
for (short i = 0; i < columns; ++i) {
colNames[i] = "col" + std::to_string(i);
}
bool isSegmentedTable = table->isSegmentedTable() || table->isDFSTable();
while (hasNext) {
for (short col = 0; col < columns; ++col) {
// nanodbc stores numeric & decimal types as strings
if (results.column_datatype(col) == SQL_DECIMAL ||
results.column_datatype(col) == SQL_NUMERIC) {
u16string _str;
results.get_ref<u16string>(col, u"", _str);
string str = utf16_to_utf8(_str);
if (str != "")
sscanf(str.c_str(), "%lf", &(buffers[col][curLine].doubleVal));
else
buffers[col][curLine].doubleVal = DBL_NMIN;
} else {
switch (columnTypes[col]) {
case DT_BOOL:
buffers[col][curLine].charVal = results.get<char>(col, CHAR_MIN);
if (buffers[col][curLine].charVal != CHAR_MIN) {
buffers[col][curLine].charVal = !!buffers[col][curLine].charVal;
}
break;
case DT_CHAR:
buffers[col][curLine].charVal = results.get<char>(col, CHAR_MIN);
break;
case DT_SHORT:
buffers[col][curLine].shortVal = results.get<short>(col, SHRT_MIN);
break;
case DT_INT:
buffers[col][curLine].intVal = results.get<int>(col, INT_MIN);
break;
case DT_LONG:
buffers[col][curLine].longVal =
results.get<int64_t>(col, LLONG_MIN);
break;
case DT_FLOAT:
buffers[col][curLine].floatVal = results.get<float>(col, FLT_NMIN);
break;
case DT_DOUBLE:
buffers[col][curLine].doubleVal =
results.get<double>(col, DBL_NMIN);
break;
case DT_DATE: {
nanodbc::date fallback = {0, 0, 0};
nanodbc::date date = {0, 0, 0};
results.get_ref<nanodbc::date>(col, fallback, date);
if (memcmp(&date, &fallback, sizeof(nanodbc::date)) == 0) {
buffers[col][curLine].intVal = INT_MIN;
} else {
buffers[col][curLine].intVal =
Util::countDays(date.year, date.month, date.day);
}
} break;
case DT_TIMESTAMP: {
nanodbc::timestamp fallback = {0, 0, 0, 0, 0, 0, 0};
nanodbc::timestamp ts = {0, 0, 0, 0, 0, 0, 0};
results.get_ref<nanodbc::timestamp>(col, fallback, ts);
if (memcmp(&ts, &fallback, sizeof(nanodbc::timestamp)) == 0) {
buffers[col][curLine].longVal = LLONG_MIN;
} else {
// ts.fract is the number of billionths of a second.
// https://docs.microsoft.com/en-us/sql/odbc/reference/appendixes/c-data-types
buffers[col][curLine].longVal =
Util::countDays(ts.year, ts.month, ts.day) * 86400000ll +
((ts.hour * 60 + ts.min) * 60 + ts.sec) * 1000 +
ts.fract / 1000000;
}
} break;
case DT_SECOND: {
nanodbc::time fallback = {0, 0, 0};
nanodbc::time ts = {0, 0, 0};
results.get_ref<nanodbc::time>(col, fallback, ts);
if (memcmp(&ts, &fallback, sizeof(nanodbc::time)) == 0) {
buffers[col][curLine].intVal = INT_MIN;
} else {
buffers[col][curLine].intVal =
(ts.hour * 60 + ts.min) * 60 + ts.sec;
}
} break;
case DT_TIME: {
nanodbc::time fallback = {0, 0, 0};
nanodbc::time ts = {0, 0, 0};
results.get_ref<nanodbc::time>(col, fallback, ts);
if (memcmp(&ts, &fallback, sizeof(nanodbc::time)) == 0) {
buffers[col][curLine].intVal = INT_MIN;
} else {
// ts.fract is the number of billionths of a second.
// https://docs.microsoft.com/en-us/sql/odbc/reference/appendixes/c-data-types
buffers[col][curLine].intVal =
((ts.hour * 60 + ts.min) * 60 + ts.sec) * 1000;
}
} break;
case DT_NANOTIME: {
nanodbc::timestamp fallback = {0, 0, 0, 0, 0, 0, 0};
nanodbc::timestamp ts = {0, 0, 0, 0, 0, 0, 0};
results.get_ref<nanodbc::timestamp>(col, fallback, ts);
if (memcmp(&ts, &fallback, sizeof(nanodbc::timestamp)) == 0) {
buffers[col][curLine].longVal = LLONG_MIN;
} else {
// ts.fract is the number of billionths of a second.
// https://docs.microsoft.com/en-us/sql/odbc/reference/appendixes/c-data-types
buffers[col][curLine].longVal =
((ts.hour * 60 + ts.min) * 60 + ts.sec) * 1000000000ll +
ts.fract;
}
} break;
case DT_NANOTIMESTAMP: {
nanodbc::timestamp fallback = {0, 0, 0, 0, 0, 0, 0};
nanodbc::timestamp ts = {0, 0, 0, 0, 0, 0, 0};
results.get_ref<nanodbc::timestamp>(col, fallback, ts);
if (memcmp(&ts, &fallback, sizeof(nanodbc::timestamp)) == 0) {
buffers[col][curLine].longVal = LLONG_MIN;
} else {
// ts.fract is the number of billionths of a second.
// https://docs.microsoft.com/en-us/sql/odbc/reference/appendixes/c-data-types
buffers[col][curLine].longVal =
Util::countDays(ts.year, ts.month, ts.day) *
86400000000000ll +
((ts.hour * 60 + ts.min) * 60 + ts.sec) * 1000000000ll +
ts.fract;
}
} break;
case DT_SYMBOL: {
SymbolBaseSP symbolBase = arrCol[col]->getSymbolBase();
u16string _str;
results.get_ref<u16string>(col, u"", _str);
string str = utf16_to_utf8(_str);
// cout << "{" << str << "} " << str.size() << " " <<
// symbolBase->findAndInsert(str) << endl;
buffers[col][curLine].intVal = symbolBase->findAndInsert(str);
} break;
default:
u16string _str;
results.get_ref<u16string>(col, u"", _str);
string str = utf16_to_utf8(_str);
buffers[col][curLine].pointer = new char[str.size() + 1];
if (str == "") {
*(buffers[col][curLine].pointer) = '\0';
} else {
strcpy(buffers[col][curLine].pointer, str.c_str());
}
}
}
}
++curLine;
rowIdx++;
hasNext = results.next();
if (hasNext == false || curLine == BUF_SIZE) {
for (short col = 0; col < columns; ++col) {
DATA_TYPE rawType = arrCol[col]->getRawType();
int sqltype = results.column_datatype(col);
vector<U8>& colBuf = buffers[col];
switch (rawType) {
case DT_BOOL:
if (sqltype == SQL_DECIMAL || sqltype == SQL_NUMERIC) {
for (int j = 0; j < curLine; ++j)
charBuf[j] = (bool)colBuf[j].doubleVal;
} else {
for (int j = 0; j < curLine; ++j) charBuf[j] = colBuf[j].charVal;
}
arrCol[col]->appendBool(charBuf, curLine);
break;
case DT_CHAR:
if (sqltype == SQL_DECIMAL || sqltype == SQL_NUMERIC) {
for (int j = 0; j < curLine; ++j)
charBuf[j] = (char)colBuf[j].doubleVal;
} else {
for (int j = 0; j < curLine; ++j) charBuf[j] = colBuf[j].charVal;
}
arrCol[col]->appendChar(charBuf, curLine);
break;
case DT_SHORT:
if (sqltype == SQL_DECIMAL || sqltype == SQL_NUMERIC) {
for (int j = 0; j < curLine; ++j)
shortBuf[j] = (short)colBuf[j].doubleVal;
} else {
for (int j = 0; j < curLine; ++j)
shortBuf[j] = colBuf[j].shortVal;
}
arrCol[col]->appendShort(shortBuf, curLine);
break;
case DT_INT:
if (sqltype == SQL_DECIMAL || sqltype == SQL_NUMERIC) {
for (int j = 0; j < curLine; ++j)
buf[j].intVal = (int)colBuf[j].doubleVal;
} else {
for (int j = 0; j < curLine; ++j)
buf[j].intVal = colBuf[j].intVal;
}
arrCol[col]->appendInt((int*)buf, curLine);
break;
case DT_LONG:
if (sqltype == SQL_DECIMAL || sqltype == SQL_NUMERIC) {
for (int j = 0; j < curLine; ++j)
colBuf[j].longVal = (long long)colBuf[j].doubleVal;
}
arrCol[col]->appendLong((long long*)(&colBuf[0]), curLine);
break;
case DT_FLOAT:
if (sqltype == SQL_DECIMAL || sqltype == SQL_NUMERIC) {
for (int j = 0; j < curLine; ++j)
buf[j].floatVal = (long long)colBuf[j].doubleVal;
} else {
for (int j = 0; j < curLine; ++j)
buf[j].floatVal = colBuf[j].floatVal;
}
arrCol[col]->appendFloat((float*)buf, curLine);
break;
case DT_DOUBLE:
arrCol[col]->appendDouble((double*)(&colBuf[0]), curLine);
break;
case DT_STRING:
#ifdef BIT32
if (sqltype == SQL_DECIMAL || sqltype == SQL_NUMERIC) {
for (int j = 0; j < curLine; ++j) {
char strBuf[120];
int nbytes = snprintf(strBuf, sizeof(strBuf), "%lf",
colBuf[j].doubleVal);
if (colBuf[j].doubleVal != DBL_NMIN) {
buf[j].pointer = new char[nbytes + 1];
strcpy(buf[j].pointer, strBuf);
} else {
buf[j].pointer = new char[1];
(*buf[j].pointer) = '\0'
}
}
} else {
for (int j = 0; j < curLine; ++j)
buf[j].pointer = colBuf[j].pointer;
}
arrCol[col]->appendString((char**)buf, curLine);
for (int j = 0; j < curLine; ++j) delete[] buf[j].pointer;
#else
if (sqltype == SQL_DECIMAL || sqltype == SQL_NUMERIC) {
for (int j = 0; j < curLine; ++j) {
char strBuf[120];
int nbytes = snprintf(strBuf, sizeof(strBuf), "%lf",
colBuf[j].doubleVal);
if (colBuf[j].doubleVal != DBL_NMIN) {
buffers[col][j].pointer = new char[nbytes + 1];
strcpy(buffers[col][j].pointer, strBuf);
} else {
buffers[col][j].pointer = new char[1];
*(buffers[col][j].pointer) = '\0';
}
}
}
arrCol[col]->appendString((char**)(&buffers[col][0]), curLine);
for (int j = 0; j < curLine; ++j) delete[] buffers[col][j].pointer;
#endif
break;
default:
assert(false);
}
}
curLine = 0;
for (short i = 0; i < columns; ++i) {
arrCol[i]->setNullFlag(arrCol[i]->hasNull());
}
if (arrCol[0]->size() > 0) {
if (isSegmentedTable) {
TableSP tmpTable = Util::createTable(colNames, columnVecs);
vector<ConstantSP> _{table, tmpTable};
static const FunctionDefSP func =
heap->currentSession()->getFunctionDef("append!");
func->call(heap, _);
} else {
string errMsg;
INDEX insertedRows = 0;
bool good = table->append(columnVecs, insertedRows, errMsg);
if (!good) {
throw TableRuntimeException(errMsg);
}
}
}
for (short i = 0; i < columns; ++i) {
arrCol[i]->clear();
}
}
}
return table;
}
ConstantSP odbcExecute(Heap* heap, vector<ConstantSP>& args) {
assert(heap);
assert(args.size() >= 2);
u16string querySql = utf8_to_utf16(args[1]->getString());
ConstantSP csp = odbcGetConnection(heap, args, "odbc::query");
nanodbc::connection* cp = (nanodbc::connection*)(csp->getLong());
try {
nanodbc::just_execute(*cp, querySql);
} catch (const runtime_error& e) {
const char* fmt = "Executed query [%s]: %s";
vector<char> errorMsgBuf(querySql.size() + strlen(e.what()) + strlen(fmt));
sprintf(errorMsgBuf.data(), fmt, querySql.c_str(), e.what());
throw TableRuntimeException(errorMsgBuf.data());
}
return Util::createConstant(DT_VOID);
}
string sqltypename(DATA_TYPE t) {
enum DATA_TYPE {
DT_VOID,
DT_BOOL,
DT_CHAR,
DT_SHORT,
DT_INT,
DT_LONG,
DT_DATE,
DT_MONTH,
DT_TIME,
DT_MINUTE,
DT_SECOND,
DT_DATETIME,
DT_TIMESTAMP,
DT_NANOTIME,
DT_NANOTIMESTAMP,
DT_FLOAT,
DT_DOUBLE,
DT_SYMBOL,
DT_STRING,
DT_UUID,
DT_FUNCTIONDEF,
DT_HANDLE,
DT_CODE,
DT_DATASOURCE,
DT_RESOURCE,
DT_ANY,
DT_COMPRESS,
DT_DICTIONARY,
DT_DATEHOUR,
DT_DATEMINUTE,
DT_OBJECT
};
switch (t) {
case DT_BOOL:
return "bit";
break;
case DT_CHAR:
return "char(1)";
break;
case DT_SHORT:
return "smallint";
break;
case DT_INT:
return "int";
break;
case DT_LONG:
return "bigint";
break;
case DT_DATE:
return "date";
break;
case DT_MONTH:
return "date";
break;
case DT_TIME:
return "time";
break;
case DT_MINUTE:
return "time";
break;
case DT_SECOND:
return "time";
break;
case DT_DATETIME:
return "datetime";
break;
case DT_TIMESTAMP:
return "datetime";
break;
case DT_NANOTIME:
return "time";
break;
case DT_NANOTIMESTAMP:
return "datetime";
break;
case DT_FLOAT:
return "float";
break;
case DT_DOUBLE:
return "double";
break;
case DT_SYMBOL:
return "varchar(255)";
break;
case DT_STRING:
return "varchar(255)";
break;
default:
break;
}
return "";
}
string getvaluestr(ConstantSP p, DATA_TYPE t) {
enum DATA_TYPE {
DT_VOID,
DT_BOOL,
DT_CHAR,
DT_SHORT,
DT_INT,
DT_LONG,
DT_DATE,
DT_MONTH,
DT_TIME,
DT_MINUTE,
DT_SECOND,
DT_DATETIME,
DT_TIMESTAMP,
DT_NANOTIME,
DT_NANOTIMESTAMP,
DT_FLOAT,
DT_DOUBLE,
DT_SYMBOL,
DT_STRING,
DT_UUID,
DT_FUNCTIONDEF,
DT_HANDLE,
DT_CODE,
DT_DATASOURCE,
DT_RESOURCE,
DT_ANY,
DT_COMPRESS,
DT_DICTIONARY,
DT_DATEHOUR,
DT_DATEMINUTE,
DT_OBJECT
};
if (p->isNull()) return "null";
string s;
switch (t) {
case DT_BOOL:
if (p->getBool())
return "1";
else
return "0";
break;
case DT_CHAR:
return "\'" + p->getString() + "\'";
break;
/// case DT_SHORT:
/// return "smallint";
/// break;
/// case DT_INT:
/// return "int";
/// break;
/// case DT_LONG:
/// return "bigint";
/// break;
case DT_DATE:
s = p->getString();
for (size_t i = 0; i < s.length(); i++)
if (s[i] == '.') s[i] = '-';
s = "\'" + s + "\'";
return s;
break;
case DT_MONTH:
s = p->getString();
for (size_t i = 0; i < s.length(); i++)
if (s[i] == '.') s[i] = '-';
s.erase(s.length() - 1, 1);
s += "-01";
s = "\'" + s + "\'";
return s;
break;
case DT_TIME:
s = p->getString();
s = s.substr(0, 8);
s = "\'" + s + "\'";
return s;
break;
case DT_MINUTE:
s = p->getString();
s = s.substr(0, 5);
s += ":00";
s = "\'" + s + "\'";
return s;
break;
case DT_SECOND:
s = p->getString();
s = "\'" + s + "\'";
return s;
break;
case DT_DATETIME:
s = p->getString();
for (size_t i = 0; i < s.length(); i++) {
if (s[i] == '.') s[i] = '-';
if (s[i] == 'T') s[i] = ' ';
}
s += ".000";
s = "\'" + s + "\'";
return s;
break;
case DT_TIMESTAMP:
s = p->getString();
for (size_t i = 0; i < s.length() - 5; i++) {
if (s[i] == '.') s[i] = '-';
if (s[i] == 'T') s[i] = ' ';
}
s = s.substr(0, 23);
s = "\'" + s + "\'";
return s;
break;
case DT_NANOTIME:
s = p->getString();
s = s.substr(0, 8);
s = "\'" + s + "\'";
return s;
break;
case DT_NANOTIMESTAMP:
s = p->getString();
s = s.substr(0, 23);
for (size_t i = 0; i < s.length() - 5; i++) {
if (s[i] == '.') s[i] = '-';
if (s[i] == 'T') s[i] = ' ';
}
s = "\'" + s + "\'";
return s;
break;
// case DT_FLOAT:
// return "float";
// break;
/// case DT_DOUBLE:
/// return "double";
/// break;
case DT_SYMBOL:
return "\'" + p->getString() + "\'";
break;
case DT_STRING:
return "\'" + p->getString() + "\'";
break;
default:
return p->getString();
break;
}
return "";
}
ConstantSP odbcAppend(Heap* heap, vector<ConstantSP>& args) {
#ifdef DEBUGlog
sqlodbcfs.open(sqlodbcfslog, std::ios::app);
sqlodbcfs << "function odbcExportTable" << std::endl;
sqlodbcfs.close();
#endif
assert(heap);
assert(args.size() >= 2);
// u16string querySql = utf8_to_utf16(args[1]->getString());
ConstantSP csp = odbcGetConnection(heap, args, "odbc::query");
nanodbc::connection* cp = (nanodbc::connection*)(csp->getLong());
TableSP t = args[1];
string tablename = args[2]->getString();
bool flag = true;
if (args.size() > 3) flag = args[3]->getBool();
bool insertIgnore = false;
if (args.size() > 4) insertIgnore = args[4]->getBool();
int inrows = 3000;
vector<VectorSP> cols;
vector<DATA_TYPE> coltype;
#ifdef DEBUGlog
sqlodbcfs.open(sqlodbcfslog, std::ios::app);
sqlodbcfs << "function odbcExportTable get connection success" << std::endl;
sqlodbcfs.close();
#endif
#ifdef DEBUGlog
sqlodbcfs.open(sqlodbcfslog, std::ios::app);
sqlodbcfs << "t is " << t->getString() << std::endl;
sqlodbcfs.close();
#endif
for (int i = 0; i < t->columns(); i++) {
cols.push_back(t->getColumn(i));
coltype.push_back(t->getColumnType(i));
}
u16string querySql;
if (flag) {
string createstring = "create table " + tablename + "(";
for (int i = 0; i < t->columns(); i++) {
createstring += t->getColumnName(i) + " " + sqltypename(coltype[i]);
if (i < t->columns() - 1) createstring += ",";
}
createstring += ")";
#ifdef DEBUGlog
sqlodbcfs.open(sqlodbcfslog, std::ios::app);
sqlodbcfs << createstring << std::endl;
sqlodbcfs.close();
#endif
querySql = utf8_to_utf16(createstring);
try {
nanodbc::just_execute(*cp, querySql);
} catch (const runtime_error& e) {
const char* fmt = "Executed query [%s]: %s";
vector<char> errorMsgBuf(querySql.size() + strlen(e.what()) +
strlen(fmt));
sprintf(errorMsgBuf.data(), fmt, querySql.c_str(), e.what());
throw TableRuntimeException(errorMsgBuf.data());
}
}
int rows = t->rows();
string q;
if (insertIgnore)
q = "INSERT IGNORE INTO " + tablename + " VALUES ";
else
q = "INSERT INTO " + tablename + " VALUES ";
for (int i = 0; i < rows; i++) {
string insertstring = "(";
for (int j = 0; j < t->columns(); j++) {
insertstring += getvaluestr(cols[j]->get(i), coltype[j]);
if (j < t->columns() - 1) insertstring += ",";
}
insertstring += ")";
if (i % inrows != inrows - 1) {
insertstring += ",";
}
#ifdef DEBUGlog
sqlodbcfs.open(sqlodbcfslog, std::ios::app);
sqlodbcfs << insertstring << std::endl;
sqlodbcfs.close();
#endif
q += insertstring;
if (i % inrows == inrows - 1) {
q += ";";
u16string querySql = utf8_to_utf16(q);
try {
nanodbc::just_execute(*cp, querySql);
} catch (const runtime_error& e) {
const char* fmt = "Executed query [%s]: %s";
vector<char> errorMsgBuf(querySql.size() + strlen(e.what()) +
strlen(fmt));
sprintf(errorMsgBuf.data(), fmt, querySql.c_str(), e.what());
throw TableRuntimeException(errorMsgBuf.data());
}
q = "INSERT INTO " + tablename + " VALUES ";
}
}
if (rows % inrows != 0) {
q[q.length() - 1] = ';';
querySql = utf8_to_utf16(q);
try {
nanodbc::just_execute(*cp, querySql);
} catch (const runtime_error& e) {
const char* fmt = "Executed query [%s]: %s";
vector<char> errorMsgBuf(querySql.size() + strlen(e.what()) +
strlen(fmt));
sprintf(errorMsgBuf.data(), fmt, querySql.c_str(), e.what());
throw TableRuntimeException(errorMsgBuf.data());
}
}
return Util::createConstant(DT_VOID);
}
| 31.156156 | 92 | 0.541365 | [
"vector"
] |
b8104ac0b58452e8344a7041ff823dbcd70150b1 | 2,217 | cpp | C++ | src/core/tests/visitors/op/deformable_psroi_pooling.cpp | pazamelin/openvino | b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48 | [
"Apache-2.0"
] | 2,406 | 2020-04-22T15:47:54.000Z | 2022-03-31T10:27:37.000Z | ngraph/test/visitors/op/deformable_psroi_pooling.cpp | thomas-yanxin/openvino | 031e998a15ec738c64cc2379d7f30fb73087c272 | [
"Apache-2.0"
] | 4,948 | 2020-04-22T15:12:39.000Z | 2022-03-31T18:45:42.000Z | ngraph/test/visitors/op/deformable_psroi_pooling.cpp | thomas-yanxin/openvino | 031e998a15ec738c64cc2379d7f30fb73087c272 | [
"Apache-2.0"
] | 991 | 2020-04-23T18:21:09.000Z | 2022-03-31T18:40:57.000Z | // Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "gtest/gtest.h"
#include "ngraph/ngraph.hpp"
#include "ngraph/op/util/attr_types.hpp"
#include "ngraph/opsets/opset1.hpp"
#include "util/visitor.hpp"
using namespace std;
using namespace ngraph;
using ngraph::test::NodeBuilder;
using ngraph::test::ValueMap;
TEST(attributes, deformable_psroi_pooling_op) {
NodeBuilder::get_ops().register_factory<opset1::DeformablePSROIPooling>();
auto input = make_shared<op::Parameter>(element::f32, Shape{2, 16, 67, 32});
auto coords = make_shared<op::Parameter>(element::f32, Shape{300, 5});
const int output_dim = 4;
const float spatial_scale = 0.0625;
const int group_size = 2;
string mode = "bilinear_deformable";
const int spatial_bins_x = 2;
const int spatial_bins_y = 3;
const float trans_std = 0.1;
const int part_size = 3;
auto op = make_shared<opset1::DeformablePSROIPooling>(input,
coords,
output_dim,
spatial_scale,
group_size,
mode,
spatial_bins_x,
spatial_bins_y,
trans_std,
part_size);
NodeBuilder builder(op);
auto g_op = ov::as_type_ptr<opset1::DeformablePSROIPooling>(builder.create());
EXPECT_EQ(g_op->get_output_dim(), op->get_output_dim());
EXPECT_EQ(g_op->get_spatial_scale(), op->get_spatial_scale());
EXPECT_EQ(g_op->get_group_size(), op->get_group_size());
EXPECT_EQ(g_op->get_mode(), op->get_mode());
EXPECT_EQ(g_op->get_spatial_bins_x(), op->get_spatial_bins_x());
EXPECT_EQ(g_op->get_spatial_bins_y(), op->get_spatial_bins_y());
EXPECT_EQ(g_op->get_trans_std(), op->get_trans_std());
EXPECT_EQ(g_op->get_part_size(), op->get_part_size());
}
| 42.634615 | 82 | 0.553902 | [
"shape"
] |
b811e35a4cbaa780154631c6f2db1bcb4f9543a3 | 3,262 | cpp | C++ | server/daemonize.cpp | ZmnSCPxj/cldcb | 4375d95cacee2a51fe5c4c1accc9fc616474bd41 | [
"MIT"
] | 9 | 2020-06-02T16:40:40.000Z | 2021-10-03T15:22:40.000Z | server/daemonize.cpp | ZmnSCPxj/cldcb | 4375d95cacee2a51fe5c4c1accc9fc616474bd41 | [
"MIT"
] | 2 | 2020-11-06T00:00:24.000Z | 2022-02-14T01:59:08.000Z | server/daemonize.cpp | ZmnSCPxj/cldcb | 4375d95cacee2a51fe5c4c1accc9fc616474bd41 | [
"MIT"
] | 2 | 2021-01-02T15:29:50.000Z | 2022-02-23T07:26:00.000Z | #include<errno.h>
#include<exception>
#include<fcntl.h>
#include<iostream>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include"daemonize.hpp"
#ifdef HAVE_CONFIG_H
# include"config.h"
#endif
#ifndef HAVE_WORKING_FORK
# error Require working fork().
#endif
namespace {
bool write_all(int fd, void const* data, size_t size) {
for (;;) {
auto res = write(fd, data, size);
if (res < 0 && errno == EINTR)
continue;
if (res <= 0)
return false;
if (size_t(res) == size)
return true;
data = (void const*)((char const*)data + res);
size -= (size_t)res;
}
}
void redirect_to_devnull(int fd, int o_flags) {
auto open_fd = open("/dev/null", o_flags);
if (open_fd < 0) {
std::cerr << "open: " << strerror(errno) << std::endl;
exit(250);
}
auto dup_fd = dup2(open_fd, fd);
if (dup_fd != fd) {
std::cerr << "dup2: " << strerror(errno) << std::endl;
exit(250);
}
close(open_fd);
}
}
int daemonize(std::function<void (std::function<void (int)>)> handler) {
int pipes[2];
auto exitcode = int();
auto piperes = pipe(pipes);
if (piperes < 0) {
std::cerr << "pipe: " << strerror(errno) << std::endl;
return 250;
}
auto forkres = fork();
if (forkres < 0) {
close(pipes[0]);
close(pipes[1]);
std::cerr << "fork: " << strerror(errno) << std::endl;
return 250;
}
if (forkres == 0) {
auto completed = false;
auto complete_daemonize = [&completed, &pipes](int exitcode) {
if (completed)
return;
completed = true;
auto setsid_res = setsid();
if (setsid_res < 0) {
std::cerr << "setsid: " << strerror(errno)
<< std::endl
;
exit(250);
}
redirect_to_devnull(STDIN_FILENO, O_RDONLY);
redirect_to_devnull(STDOUT_FILENO, O_WRONLY);
redirect_to_devnull(STDERR_FILENO, O_WRONLY);
/* Signal parent. */
auto write_res = write_all( pipes[1]
, &exitcode
, sizeof(exitcode)
);
if (!write_res) {
std::cerr << "write: " << strerror(errno)
<< std::endl
;
exit(250);
}
close(pipes[1]);
};
/* child. */
close(pipes[0]);
try {
handler(complete_daemonize);
} catch (std::exception const& e) {
if (!completed) {
std::cerr << "Uncaught exception: "
<< e.what() << std::endl
;
complete_daemonize(250);
}
} catch (...) {
if (!completed) {
std::cerr << "Uncaught unknown exception."
<< std::endl
;
complete_daemonize(250);
}
}
exit(0);
} else {
/* parent. */
close(pipes[1]);
auto res = ssize_t();
do {
res = read(pipes[0], &exitcode, sizeof(exitcode));
} while(res < 0 && errno == EINTR);
close(pipes[0]);
if (res < 0) {
std::cerr << "read: " << strerror(errno) << std::endl;
return 250;
}
if (res == sizeof(exitcode))
return exitcode;
/* Child exited; catch its exitcode instead. */
waitpid(forkres, &exitcode, 0);
if (WIFEXITED(exitcode)) {
exitcode = WEXITSTATUS(exitcode);
/* Not normal, so if it exited with 0, transform to
* 1.
*/
if (exitcode == 0)
exitcode = 1;
return exitcode;
} else {
std::cerr << "Child daemon died by signal: "
<< WTERMSIG(exitcode)
<< std::endl
;
return 250;
}
}
}
| 20.64557 | 72 | 0.584917 | [
"transform"
] |
b8139feb13db9e5eedc2d65a8825de36b2a9945c | 6,227 | cc | C++ | client/cxx/elf_util.cc | dzeromsk/goma | 350f67319eb985013515b533f03f2f95570c37d3 | [
"BSD-3-Clause"
] | 4 | 2018-12-26T10:54:24.000Z | 2022-03-31T21:19:47.000Z | client/cxx/elf_util.cc | dzeromsk/goma | 350f67319eb985013515b533f03f2f95570c37d3 | [
"BSD-3-Clause"
] | null | null | null | client/cxx/elf_util.cc | dzeromsk/goma | 350f67319eb985013515b533f03f2f95570c37d3 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2019 The Goma Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "elf_util.h"
#include "absl/strings/match.h"
#include "absl/strings/str_replace.h"
#include "absl/strings/str_split.h"
#include "absl/strings/strip.h"
#include "glog/logging.h"
#include "glog/stl_logging.h"
#include "path.h"
#include "path_resolver.h"
#include "util.h"
namespace {
absl::string_view GetContentInBrackets(absl::string_view line) {
absl::string_view::size_type pos = line.find('[');
line.remove_prefix(pos + 1);
pos = line.find(']');
return line.substr(0, pos);
}
std::string FindLibInternal(const string& cwd,
absl::string_view dir,
const absl::string_view lib_filename,
const absl::string_view origin) {
std::string new_dir = absl::StrReplaceAll(dir, {
{"$ORIGIN", origin},
});
if (devtools_goma::PathResolver::ResolvePath(new_dir) ==
devtools_goma::PathResolver::ResolvePath(origin)) {
dir = origin;
} else {
dir = new_dir;
}
if (absl::StrContains(dir, "$")) {
LOG(ERROR) << "found non supported $ pattern."
<< " dir=" << dir;
return string();
}
std::string path = file::JoinPathRespectAbsolute(dir, lib_filename);
if (access(file::JoinPathRespectAbsolute(cwd, path).c_str(), X_OK) == 0) {
return path;
}
return string();
}
} // namespace
namespace devtools_goma {
bool ElfDepParser::GetDeps(const absl::string_view cmd_or_lib,
absl::flat_hash_set<std::string>* deps) {
// TODO: can we expect readelf always exists in /usr/bin?
std::vector<std::string> readelf_argv = {"/usr/bin/readelf", "-d",
string(cmd_or_lib)};
int32_t status;
string output = ReadCommandOutput(readelf_argv[0], readelf_argv,
std::vector<std::string>(), cwd_,
MERGE_STDOUT_STDERR, &status);
if (status != 0) {
LOG(ERROR) << "ReadCommandOutput readelf with non-zero exit status code."
<< " cmd_or_lib=" << cmd_or_lib << " output=" << output
<< " status=" << status;
return false;
}
std::vector<absl::string_view> libs;
std::vector<absl::string_view> rpaths;
if (!ParseReadElf(output, &libs, &rpaths)) {
LOG(ERROR) << "failed to parse readelf result."
<< " output=" << output;
return false;
}
// keep libs for bredth first search.
std::vector<std::string> libs_to_search;
for (const auto& lib : libs) {
std::string lib_path = FindLib(lib, file::Dirname(cmd_or_lib), rpaths);
if (lib_path.empty()) {
LOG(ERROR) << "failed to find dependent library."
<< " lib=" << lib << " rpaths=" << rpaths
<< " default_search_path=" << default_search_paths_;
return false;
}
// No need to see a known library.
if (deps->contains(lib_path)) {
continue;
}
CHECK(deps->insert(lib_path).second);
libs_to_search.push_back(std::move(lib_path));
}
for (const auto& lib : libs_to_search) {
if (!GetDeps(lib, deps)) {
return false;
}
}
return true;
}
std::string ElfDepParser::FindLib(
const absl::string_view lib_filename,
const absl::string_view origin,
const std::vector<absl::string_view>& search_paths) const {
// According to GNU ls.so manual, libraries are searched in following order:
// 1. DT_RPATH (if --inhibit-cache is not empty string or ':' and no
// DT_RUNPATH)
// 2. LD_LIBRARY_PATH (which can be overwritten by --library-path)
// The value should be passed via |default_search_path|.
// 3. DT_RUNPATH (we do not support this)
// 4. path in ldconfig cache (we do not support this)
// 5. trusted default paths (we do not support this)
if (!ignore_rpath_) {
for (const auto& dir : search_paths) {
std::string lib = FindLibInternal(cwd_, dir, lib_filename, origin);
if (!lib.empty()) {
return lib;
}
}
}
for (const std::string& dir : default_search_paths_) {
std::string lib = FindLibInternal(cwd_, dir, lib_filename, origin);
if (!lib.empty()) {
return lib;
}
}
return string();
}
/* static */
bool ElfDepParser::ParseReadElf(absl::string_view content,
std::vector<absl::string_view>* libs,
std::vector<absl::string_view>* rpaths) {
DCHECK(libs);
DCHECK(rpaths);
static constexpr absl::string_view kSharedLibrary = "Shared library:";
static constexpr absl::string_view kLibraryRPath = "Library rpath:";
for (absl::string_view line :
absl::StrSplit(content, absl::ByAnyChar("\r\n"), absl::SkipEmpty())) {
if (absl::StrContains(line, kSharedLibrary)) {
absl::string_view lib = GetContentInBrackets(line);
if (lib.empty()) {
LOG(ERROR) << "unexpected shared library line found: " << line;
return false;
}
libs->push_back(std::move(lib));
} else if (absl::StrContains(line, kLibraryRPath)) {
absl::string_view rpath = GetContentInBrackets(line);
if (rpath.empty()) {
LOG(ERROR) << "unexpected rpath line found: " << line;
return false;
}
rpaths->push_back(std::move(rpath));
}
}
return true;
}
std::vector<std::string> ParseLdSoConf(absl::string_view content) {
std::vector<std::string> ret;
for (absl::string_view line :
absl::StrSplit(content, absl::ByAnyChar("\r\n"), absl::SkipEmpty())) {
// Omit anything after '#'.
absl::string_view::size_type pos = line.find('#');
line = line.substr(0, pos);
line = absl::StripAsciiWhitespace(line);
if (line.empty()) {
continue;
}
// TODO: support include and hwcap if we need.
if (absl::StartsWith(line, "include") || absl::StartsWith(line, "hwcap")) {
LOG(WARNING) << "non supported line:" << line;
continue;
}
ret.push_back(string(line));
}
return ret;
}
} // namespace devtools_goma
| 33.299465 | 79 | 0.605428 | [
"vector"
] |
b8187159a8d77d9d683a6eeb097b8a0aff6e59f4 | 7,749 | cpp | C++ | src/detection.cpp | SVPA-XudongYu/usbdetection | 6eb0aba31d2d51e3d9e0ba0c57ef1cba7a561f31 | [
"MIT"
] | 1 | 2016-12-13T03:03:05.000Z | 2016-12-13T03:03:05.000Z | src/detection.cpp | yuxhotmail/usbdetection | 6eb0aba31d2d51e3d9e0ba0c57ef1cba7a561f31 | [
"MIT"
] | null | null | null | src/detection.cpp | yuxhotmail/usbdetection | 6eb0aba31d2d51e3d9e0ba0c57ef1cba7a561f31 | [
"MIT"
] | 2 | 2016-12-13T03:03:06.000Z | 2018-01-07T18:25:30.000Z | #include "detection.h"
using namespace v8;
#define OBJECT_ITEM_LOCATION_ID "locationId"
#define OBJECT_ITEM_VENDOR_ID "vendorId"
#define OBJECT_ITEM_PRODUCT_ID "productId"
#define OBJECT_ITEM_DEVICE_NAME "deviceName"
#define OBJECT_ITEM_MANUFACTURER "manufacturer"
#define OBJECT_ITEM_SERIAL_NUMBER "serialNumber"
#define OBJECT_ITEM_DEVICE_ADDRESS "deviceAddress"
v8::Persistent<v8::Value> addedCallback;
bool isAddedRegistered = false;
v8::Persistent<v8::Value> removedCallback;
bool isRemovedRegistered = false;
v8::Handle<v8::Value> RegisterAdded(const v8::Arguments& args)
{
v8::HandleScope scope;
v8::Local<v8::Value> callback;
if (args.Length() == 0)
{
return scope.Close(v8::ThrowException(v8::Exception::TypeError(v8::String::New("First argument must be a function"))));
}
if (args.Length() == 1)
{
// callback
if(!args[0]->IsFunction())
{
return scope.Close(v8::ThrowException(v8::Exception::TypeError(v8::String::New("First argument must be a function"))));
}
callback = args[0];
}
addedCallback = v8::Persistent<v8::Value>::New(callback);
isAddedRegistered = true;
return scope.Close(v8::Undefined());
}
void NotifyAdded(ListResultItem_t* it)
{
if (isAddedRegistered)
{
v8::Handle<v8::Value> argv[1];
v8::Local<v8::Object> item = v8::Object::New();
item->Set(v8::String::New(OBJECT_ITEM_LOCATION_ID), v8::Number::New(it->locationId));
item->Set(v8::String::New(OBJECT_ITEM_VENDOR_ID), v8::Number::New(it->vendorId));
item->Set(v8::String::New(OBJECT_ITEM_PRODUCT_ID), v8::Number::New(it->productId));
item->Set(v8::String::New(OBJECT_ITEM_DEVICE_NAME), v8::String::New(it->deviceName.c_str()));
item->Set(v8::String::New(OBJECT_ITEM_MANUFACTURER), v8::String::New(it->manufacturer.c_str()));
item->Set(v8::String::New(OBJECT_ITEM_SERIAL_NUMBER), v8::String::New(it->serialNumber.c_str()));
item->Set(v8::String::New(OBJECT_ITEM_DEVICE_ADDRESS), v8::Number::New(it->deviceAddress));
argv[0] = item;
v8::Function::Cast(*addedCallback)->Call(v8::Context::GetCurrent()->Global(), 1, argv);
}
}
v8::Handle<v8::Value> RegisterRemoved(const v8::Arguments& args) {
v8::HandleScope scope;
v8::Local<v8::Value> callback;
if (args.Length() == 0)
{
return scope.Close(v8::ThrowException(v8::Exception::TypeError(v8::String::New("First argument must be a function"))));
}
if (args.Length() == 1)
{
// callback
if(!args[0]->IsFunction())
{
return scope.Close(v8::ThrowException(v8::Exception::TypeError(v8::String::New("First argument must be a function"))));
}
callback = args[0];
}
removedCallback = v8::Persistent<v8::Value>::New(callback);
isRemovedRegistered = true;
return scope.Close(v8::Undefined());
}
void NotifyRemoved(ListResultItem_t* it)
{
if (isRemovedRegistered)
{
v8::Handle<v8::Value> argv[1];
v8::Local<v8::Object> item = v8::Object::New();
item->Set(v8::String::New(OBJECT_ITEM_LOCATION_ID), v8::Number::New(it->locationId));
item->Set(v8::String::New(OBJECT_ITEM_VENDOR_ID), v8::Number::New(it->vendorId));
item->Set(v8::String::New(OBJECT_ITEM_PRODUCT_ID), v8::Number::New(it->productId));
item->Set(v8::String::New(OBJECT_ITEM_DEVICE_NAME), v8::String::New(it->deviceName.c_str()));
item->Set(v8::String::New(OBJECT_ITEM_MANUFACTURER), v8::String::New(it->manufacturer.c_str()));
item->Set(v8::String::New(OBJECT_ITEM_SERIAL_NUMBER), v8::String::New(it->serialNumber.c_str()));
item->Set(v8::String::New(OBJECT_ITEM_DEVICE_ADDRESS), v8::Number::New(it->deviceAddress));
argv[0] = item;
v8::Function::Cast(*removedCallback)->Call(v8::Context::GetCurrent()->Global(), 1, argv);
}
}
v8::Handle<v8::Value> Find(const v8::Arguments& args)
{
v8::HandleScope scope;
int vid = 0;
int pid = 0;
v8::Local<v8::Value> callback;
if (args.Length() == 0)
{
return scope.Close(v8::ThrowException(v8::Exception::TypeError(v8::String::New("First argument must be a function"))));
}
if (args.Length() == 3)
{
if (args[0]->IsNumber() && args[1]->IsNumber())
{
vid = (int) args[0]->NumberValue();
pid = (int) args[1]->NumberValue();
}
// callback
if(!args[2]->IsFunction())
{
return scope.Close(v8::ThrowException(v8::Exception::TypeError(v8::String::New("Third argument must be a function"))));
}
callback = args[2];
}
if (args.Length() == 2)
{
if (args[0]->IsNumber())
{
vid = (int) args[0]->NumberValue();
}
// callback
if(!args[1]->IsFunction())
{
return scope.Close(v8::ThrowException(v8::Exception::TypeError(v8::String::New("Second argument must be a function"))));
}
callback = args[1];
}
if (args.Length() == 1)
{
// callback
if(!args[0]->IsFunction())
{
return scope.Close(v8::ThrowException(v8::Exception::TypeError(v8::String::New("First argument must be a function"))));
}
callback = args[0];
}
ListBaton* baton = new ListBaton();
strcpy(baton->errorString, "");
baton->callback = v8::Persistent<v8::Value>::New(callback);
baton->vid = vid;
baton->pid = pid;
uv_work_t* req = new uv_work_t();
req->data = baton;
uv_queue_work(uv_default_loop(), req, EIO_Find, (uv_after_work_cb)EIO_AfterFind);
return scope.Close(v8::Undefined());
}
void EIO_AfterFind(uv_work_t* req)
{
ListBaton* data = static_cast<ListBaton*>(req->data);
v8::Handle<v8::Value> argv[2];
if(data->errorString[0])
{
argv[0] = v8::Exception::Error(v8::String::New(data->errorString));
argv[1] = v8::Undefined();
}
else
{
v8::Local<v8::Array> results = v8::Array::New();
int i = 0;
for(std::list<ListResultItem_t*>::iterator it = data->results.begin(); it != data->results.end(); it++, i++) {
v8::Local<v8::Object> item = v8::Object::New();
item->Set(v8::String::New(OBJECT_ITEM_LOCATION_ID), v8::Number::New((*it)->locationId));
item->Set(v8::String::New(OBJECT_ITEM_VENDOR_ID), v8::Number::New((*it)->vendorId));
item->Set(v8::String::New(OBJECT_ITEM_PRODUCT_ID), v8::Number::New((*it)->productId));
item->Set(v8::String::New(OBJECT_ITEM_DEVICE_NAME), v8::String::New((*it)->deviceName.c_str()));
item->Set(v8::String::New(OBJECT_ITEM_MANUFACTURER), v8::String::New((*it)->manufacturer.c_str()));
item->Set(v8::String::New(OBJECT_ITEM_SERIAL_NUMBER), v8::String::New((*it)->serialNumber.c_str()));
item->Set(v8::String::New(OBJECT_ITEM_DEVICE_ADDRESS), v8::Number::New((*it)->deviceAddress));
results->Set(i, item);
}
argv[0] = v8::Undefined();
argv[1] = results;
}
v8::Function::Cast(*data->callback)->Call(v8::Context::GetCurrent()->Global(), 2, argv);
data->callback.Dispose();
for(std::list<ListResultItem_t*>::iterator it = data->results.begin(); it != data->results.end(); it++)
{
delete *it;
}
delete data;
delete req;
}
v8::Handle<v8::Value> StartMonitoring(const v8::Arguments& args)
{
v8::HandleScope scope;
Start();
return scope.Close(v8::Undefined());
}
v8::Handle<v8::Value> StopMonitoring(const v8::Arguments& args)
{
v8::HandleScope scope;
Stop();
return scope.Close(v8::Undefined());
}
extern "C" {
void init (v8::Handle<v8::Object> target)
{
v8::HandleScope scope;
NODE_SET_METHOD(target, "find", Find);
NODE_SET_METHOD(target, "registerAdded", RegisterAdded);
NODE_SET_METHOD(target, "registerRemoved", RegisterRemoved);
NODE_SET_METHOD(target, "startMonitoring", StartMonitoring);
NODE_SET_METHOD(target, "stopMonitoring", StopMonitoring);
InitDetection();
}
}
NODE_MODULE(detection, init);
| 30.75 | 128 | 0.654665 | [
"object"
] |
b81b835dc671ecbda98fd02670964a4102573314 | 15,270 | cpp | C++ | bftengine/src/bftengine/SimpleClient.cpp | ashsek/concord-rcanopus | f979821f40433cf62ad0afa5bdc507e372e1367d | [
"Apache-2.0"
] | null | null | null | bftengine/src/bftengine/SimpleClient.cpp | ashsek/concord-rcanopus | f979821f40433cf62ad0afa5bdc507e372e1367d | [
"Apache-2.0"
] | null | null | null | bftengine/src/bftengine/SimpleClient.cpp | ashsek/concord-rcanopus | f979821f40433cf62ad0afa5bdc507e372e1367d | [
"Apache-2.0"
] | null | null | null | //Concord
//
//Copyright (c) 2018 VMware, Inc. All Rights Reserved.
//
//This product is licensed to you under the Apache 2.0 license (the "License"). You may not use this product except in compliance with the Apache 2.0 License.
//
//This product may include a number of subcomponents with separate copyright notices and license terms. Your use of these subcomponents is subject to the terms and conditions of the subcomponent's license, as noted in the LICENSE file.
#include <queue>
#include <thread>
#include <mutex>
#include <cmath>
#include <condition_variable>
#include "ClientMsgs.hpp"
#include "CheckpointMsg.hpp"
#include "SimpleClient.hpp"
#include "assertUtils.hpp"
#include "TimeUtils.hpp"
#include "MessageBase.hpp"
#include "ClientRequestMsg.hpp"
#include "ClientReplyMsg.hpp"
#include "MsgsCertificate.hpp"
#include "DynamicUpperLimitWithSimpleFilter2.hpp"
#include "Logger.hpp"
#include "Digest.hpp"
namespace bftEngine
{
namespace impl
{
class SimpleClientImp : public SimpleClient, public IReceiver
{
public:
SimpleClientImp(ICommunication* communication, uint16_t clientId,
uint16_t fVal, uint16_t cVal, SimpleClientParams &p);
// SimpleClient methods
virtual ~SimpleClientImp() override;
virtual int sendRequest(bool isReadOnly, const char* request, uint32_t lengthOfRequest, uint64_t reqSeqNum, uint64_t timeoutMilli, uint32_t lengthOfReplyBuffer, char* replyBuffer, uint32_t& actualReplyLength) override;
virtual int sendRequestToResetSeqNum() override;
virtual int sendRequestToReadLatestSeqNum(uint64_t timeoutMilli, uint64_t& outLatestReqSeqNum) override;
// IReceiver methods
virtual void onNewMessage(const NodeNum sourceNode,
const char* const message, const size_t messageLength) override;
virtual void onConnectionStatusChanged(const NodeNum node, const ConnectionStatus newStatus) override;
// used by MsgsCertificate
static bool equivalent(ClientReplyMsg *r1, ClientReplyMsg* r2)
{
if (r1->reqSeqNum() != r2->reqSeqNum()) return false;
if (r1->currentPrimaryId() != r2->currentPrimaryId()) return false;
if (r1->replyLength() != r2->replyLength()) return false;
char* p1 = r1->replyBuf();
char* p2 = r2->replyBuf();
if (memcmp(p1, p2, r1->replyLength()) != 0) return false;
return true;
}
protected:
static const uint32_t maxLegalMsgSize = 64 * 1024; // TODO(GG): ???
static const uint16_t timersResolutionMilli = 50;
const uint16_t _clientId;
const uint16_t _fVal;
const uint16_t _cVal;
const std::set<uint16_t> _replicas;
ICommunication* const _communication;
MsgsCertificate<ClientReplyMsg, false, false, true, SimpleClientImp> replysCertificate;
std::mutex _lock; // protects _msgQueue and pendingRequest
std::condition_variable _condVar;
queue<MessageBase*> _msgQueue;
ClientRequestMsg* pendingRequest = nullptr;
Time timeOfLastTransmission = MinTime;
uint16_t numberOfTransmissions = 0;
bool _primaryReplicaIsKnown = false;
uint16_t _knownPrimaryReplica;
DynamicUpperLimitWithSimpleFilter<uint64_t> limitOfExpectedOperationTime;
// configuration params
uint16_t clientSendsRequestToAllReplicasFirstThresh;
uint16_t clientSendsRequestToAllReplicasPeriodThresh;
uint16_t clientPeriodicResetThresh;
void sendPendingRequest();
void onMessageFromReplica(MessageBase* msg);
void onRetransmission();
void reset();
};
void SimpleClientImp::onMessageFromReplica(MessageBase* msg)
{
//Stephen: Gets message from a replic - may be execute-ack nsg
ClientReplyMsg* replyMsg = nullptr;
if (!ClientReplyMsg::ToActualMsgType(_clientId, msg, replyMsg))
{
delete msg;
return;
}
Assert(replyMsg != nullptr);
Assert(replyMsg->type() == REPLY_MSG_TYPE);
LOG_INFO_F(GL, "Client %d received ClientReplyMsg with seqNum=%"
PRIu64
" sender=%d size=%d primaryId=%d hash=%" PRIu64 " len=%d pendingReqNum=%d",
_clientId, replyMsg->reqSeqNum(), replyMsg->senderId(), replyMsg->size(), (int)replyMsg->currentPrimaryId(), replyMsg->debugHash(), replyMsg->replyLength(), pendingRequest->requestSeqNum());
if (replyMsg->reqSeqNum() != pendingRequest->requestSeqNum())
{
delete msg;
return;
}
replysCertificate.addMsg(replyMsg, replyMsg->senderId());
if (replysCertificate.isInconsistent())
{
// TODO(GG): print .....
replysCertificate.resetAndFree();
}
}
void SimpleClientImp::onRetransmission()
{
sendPendingRequest();
}
// in this version we assume that the set of replicas is 0,1,2,...,numberOfReplicas (TODO(GG): should be changed to support full dynamic reconfiguration)
static std::set<ReplicaId> generateSetOfReplicas_helpFunc(const int16_t numberOfReplicas)
{
std::set<ReplicaId> retVal;
for (int16_t i = 0; i < numberOfReplicas; i++)
retVal.insert(i);
return retVal;
}
SimpleClientImp::SimpleClientImp(ICommunication* communication,uint16_t clientId, uint16_t fVal, uint16_t cVal,SimpleClientParams &p) :
_clientId{ clientId },
_fVal{ fVal },
_cVal{ cVal },
_replicas{ generateSetOfReplicas_helpFunc(3 * fVal + 2 * cVal + 1) },
_communication{ communication },
replysCertificate(3 * fVal + 2 * cVal + 1, fVal, 2 * fVal + cVal + 1, clientId),
limitOfExpectedOperationTime(p.clientInitialRetryTimeoutMilli, 2,
p.clientMaxRetryTimeoutMilli, p.clientMinRetryTimeoutMilli,
32, 1000, 2, 2),
clientSendsRequestToAllReplicasFirstThresh{p.clientSendsRequestToAllReplicasFirstThresh},
clientSendsRequestToAllReplicasPeriodThresh{p.clientSendsRequestToAllReplicasPeriodThresh},
clientPeriodicResetThresh{p.clientPeriodicResetThresh}
{
Assert(_fVal >= 1);
//Assert(!_communication->isRunning());
pendingRequest = nullptr;
timeOfLastTransmission = MinTime;
numberOfTransmissions = 0;
_primaryReplicaIsKnown = false;
_knownPrimaryReplica = 0;
_communication->setReceiver(_clientId, this);
}
SimpleClientImp::~SimpleClientImp()
{
Assert(replysCertificate.isEmpty());
Assert(_msgQueue.empty());
Assert(pendingRequest == nullptr);
Assert(timeOfLastTransmission == MinTime);
Assert(numberOfTransmissions == 0);
}
int SimpleClientImp::sendRequest(bool isReadOnly, const char* request, uint32_t lengthOfRequest, uint64_t reqSeqNum, uint64_t timeoutMilli, uint32_t lengthOfReplyBuffer, char* replyBuffer, uint32_t& actualReplyLength)
{
// TODO(GG): check params ...
LOG_INFO_F(GL, "Client %d - sends request %" PRIu64 " (isRO=%d, "
"request "
"size=%zu, retransmissionMilli=%d) ",
_clientId, reqSeqNum, (int)isReadOnly, (size_t)lengthOfRequest, (int)limitOfExpectedOperationTime.upperLimit());
if (!_communication->isRunning())
{
_communication->Start(); // TODO(GG): patch ................ change
}
Assert(replysCertificate.isEmpty());
Assert(_msgQueue.empty());
Assert(pendingRequest == nullptr);
Assert(timeOfLastTransmission == MinTime);
Assert(numberOfTransmissions == 0);
static const std::chrono::milliseconds timersRes(timersResolutionMilli);
const Time beginTime = getMonotonicTime();
ClientRequestMsg* reqMsg = new ClientRequestMsg(_clientId, isReadOnly, reqSeqNum, lengthOfRequest, request);
pendingRequest = reqMsg;
sendPendingRequest();
bool requestTimeout = false;
bool requestCommitted = false;
while (true)
{
queue<MessageBase*> newMsgs;
{
std::unique_lock<std::mutex> mlock(_lock);
_condVar.wait_for(mlock, timersRes);
_msgQueue.swap(newMsgs);
}
while (!newMsgs.empty())
{
if (replysCertificate.isComplete())
{
delete newMsgs.front();
}
else
{
MessageBase* msg = newMsgs.front();
onMessageFromReplica(msg);
}
newMsgs.pop();
}
if (replysCertificate.isComplete())
{
requestCommitted = true;
break;
}
const Time currTime = getMonotonicTime();
if (timeoutMilli != INFINITE_TIMEOUT && (uint64_t)absDifference(beginTime, currTime) > timeoutMilli)
{
requestTimeout = true;
break;
}
if (((uint64_t)absDifference(timeOfLastTransmission, currTime))/1000 > limitOfExpectedOperationTime.upperLimit())
{
onRetransmission();
}
}
if (requestCommitted)
{
Assert(replysCertificate.isComplete());
uint64_t durationMilli = ((uint64_t)absDifference(getMonotonicTime(), beginTime)) / 1000;
limitOfExpectedOperationTime.add(durationMilli);
LOG_INFO_F(GL, "Client %d - request %" PRIu64 " has committed "
"(isRO=%d, request size=%zu, retransmissionMilli=%d) ",
_clientId, reqSeqNum, (int)isReadOnly, (size_t)lengthOfRequest, (int)limitOfExpectedOperationTime.upperLimit());
ClientReplyMsg* correctReply = replysCertificate.bestCorrectMsg();
_primaryReplicaIsKnown = true;
_knownPrimaryReplica = correctReply->currentPrimaryId();
if (correctReply->replyLength() <= lengthOfReplyBuffer)
{
//Stephen: copys the output to the reply buffer
memcpy(replyBuffer, correctReply->replyBuf(), correctReply->replyLength());
actualReplyLength = correctReply->replyLength();
reset();
return 0;
}
else
{
reset();
return (-2);
}
}
else if (requestTimeout)
{
//Logger::printInfo("Client %d - request %" PRIu64 " - timeout");
if (timeoutMilli >= limitOfExpectedOperationTime.upperLimit())
{
_primaryReplicaIsKnown = false;
limitOfExpectedOperationTime.add(timeoutMilli);
}
reset();
return (-1);
}
Assert(false);
return 0;
}
int SimpleClientImp::sendRequestToResetSeqNum()
{
Assert(false); // not implemented yet
return 0;
}
void SimpleClientImp::reset()
{
replysCertificate.resetAndFree();
queue<MessageBase*> newMsgs;
{
std::unique_lock<std::mutex> mlock(_lock);
_msgQueue.swap(newMsgs);
delete pendingRequest;
pendingRequest = nullptr;
}
while (!newMsgs.empty())
{
delete newMsgs.front();
newMsgs.pop();
}
timeOfLastTransmission = MinTime;
numberOfTransmissions = 0;
}
int SimpleClientImp::sendRequestToReadLatestSeqNum(uint64_t timeoutMilli, uint64_t& outLatestReqSeqNum)
{
Assert(false); // not implemented yet
return 0;
}
void SimpleClientImp::onNewMessage(const NodeNum sourceNode,
const char* const message, const size_t messageLength)
{
// check source
int16_t senderId = (int16_t)sourceNode;
if (_replicas.count(senderId) == 0) return;
// check length
if (messageLength > maxLegalMsgSize) return;
if (messageLength < sizeof(MessageBase::Header)) return;
MessageBase::Header* msgHeader = (MessageBase::Header*)message;
// check type
if (msgHeader->msgType != REPLY_MSG_TYPE) return;
std::unique_lock<std::mutex> mlock(_lock);
{
if (pendingRequest == nullptr) return;
// create msg object
MessageBase::Header* msgBody = (MessageBase::Header*)std::malloc(messageLength);
memcpy(msgBody, message, messageLength);
MessageBase* pMsg = new MessageBase(senderId, msgBody, messageLength, true);
_msgQueue.push(pMsg); // TODO(GG): handle overflow
_condVar.notify_one();
}
}
void SimpleClientImp::onConnectionStatusChanged(const NodeNum node, const ConnectionStatus newStatus)
{
}
void SimpleClientImp::sendPendingRequest()
{
Assert(pendingRequest != nullptr)
timeOfLastTransmission = getMonotonicTime();
numberOfTransmissions++;
const bool resetReplies = (numberOfTransmissions % clientPeriodicResetThresh == 0);
const bool sendToAll = pendingRequest->isReadOnly() || !_primaryReplicaIsKnown ||
(numberOfTransmissions == clientSendsRequestToAllReplicasFirstThresh) ||
(numberOfTransmissions > clientSendsRequestToAllReplicasFirstThresh && (numberOfTransmissions % clientSendsRequestToAllReplicasPeriodThresh == 0)) ||
resetReplies;
LOG_INFO_F(GL,"Client %d - sends request %" PRIu64 " "
"(isRO=%d, "
"request "
"size=%zu, "
" retransmissionMilli=%d, numberOfTransmissions=%d, resetReplies=%d, sendToAll=%d)",
_clientId, pendingRequest->requestSeqNum(), (int)pendingRequest->isReadOnly(), (size_t)pendingRequest->size(),
(int)limitOfExpectedOperationTime.upperLimit(), (int)numberOfTransmissions, (int)resetReplies, (int)sendToAll);
if (resetReplies)
{
replysCertificate.resetAndFree();
// TODO(GG): print ....
}
if (sendToAll)
{
for (uint16_t r : _replicas)
{
// int stat =
_communication->sendAsyncMessage(r, pendingRequest->body(), pendingRequest->size());
// TODO(GG): handle errors (print and/or ....)
}
}
else
{
// int stat =
_communication->sendAsyncMessage(_knownPrimaryReplica, pendingRequest->body(), pendingRequest->size());
// TODO(GG): handle errors (print and/or ....)
}
}
class SeqNumberGeneratorForClientRequestsImp : public SeqNumberGeneratorForClientRequests
{
virtual uint64_t generateUniqueSequenceNumberForRequest() override;
protected:
uint64_t lastMilliOfUniqueFetchID = 0;
uint32_t lastCountOfUniqueFetchID = 0;
};
uint64_t SeqNumberGeneratorForClientRequestsImp::generateUniqueSequenceNumberForRequest()
{
std::chrono::time_point<std::chrono::system_clock> n = std::chrono::system_clock::now();
uint64_t milli = std::chrono::duration_cast<std::chrono::milliseconds>(n.time_since_epoch()).count();
if (milli > lastMilliOfUniqueFetchID)
{
lastMilliOfUniqueFetchID = milli;
lastCountOfUniqueFetchID = 0;
}
else
{
if (lastCountOfUniqueFetchID == 0x3FFFFF) {
LOG_WARN(GL, "Client SeqNum Counter reached max value");
lastMilliOfUniqueFetchID++;
lastCountOfUniqueFetchID = 0;
} else {
lastCountOfUniqueFetchID++;
}
}
uint64_t r = (lastMilliOfUniqueFetchID << (64-42));
Assert(lastCountOfUniqueFetchID <= 0x3FFFFF);
r = r | ((uint64_t)lastCountOfUniqueFetchID);
return r;
}
}
}
namespace bftEngine
{
SimpleClient* SimpleClient::createSimpleClient(
ICommunication* communication,
uint16_t clientId,
uint16_t fVal,
uint16_t cVal,
SimpleClientParams p)
{
return new impl::SimpleClientImp(communication, clientId, fVal, cVal,p);
}
SimpleClient* SimpleClient::createSimpleClient(ICommunication* communication, uint16_t clientId, uint16_t fVal, uint16_t cVal)
{
SimpleClientParams p;
return SimpleClient::createSimpleClient(communication, clientId, fVal,cVal, p);
}
SimpleClient::~SimpleClient()
{
}
SeqNumberGeneratorForClientRequests* SeqNumberGeneratorForClientRequests::createSeqNumberGeneratorForClientRequests()
{
return new impl::SeqNumberGeneratorForClientRequestsImp();
}
}
| 29.766082 | 235 | 0.691814 | [
"object"
] |
b81d6441554e400dc5369827a330f11ff3b5e111 | 5,474 | hpp | C++ | external/boost/boost/extension/parameter.hpp | loafofpiecrust/lfant | a38826e325a50dffb5d030d71abcd58de59e8389 | [
"Apache-2.0"
] | 4 | 2017-03-06T16:59:27.000Z | 2021-07-23T12:57:07.000Z | external/boost/boost/extension/parameter.hpp | loafofpiecrust/lfant | a38826e325a50dffb5d030d71abcd58de59e8389 | [
"Apache-2.0"
] | null | null | null | external/boost/boost/extension/parameter.hpp | loafofpiecrust/lfant | a38826e325a50dffb5d030d71abcd58de59e8389 | [
"Apache-2.0"
] | null | null | null | /*
* Boost.Reflection / paramater map (store parameter information for calls)
*
* (C) Copyright Jeremy Pack 2008
* Distributed under the Boost Software License, Version 1.0. (See
* accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*
* See http://www.boost.org/ for latest version.
*/
#ifndef BOOST_EXTENSION_PARAMETER_HPP
#define BOOST_EXTENSION_PARAMETER_HPP
#include <boost/extension/impl/typeinfo.hpp>
#include <exception>
#include <map>
#include <vector>
namespace boost { namespace extensions {
using extensions::type_info_handler;
class conversion_not_found_exception : public std::exception {
public:
virtual const char* what() {
return "Cannot convert types";
}
};
/** \brief A container for a single item - similar to boost::any.
*
* The primary difference between generic_parameter and boost::any
* is that a generic_parameter can be declared to be convertible
* to arbitrary types, in addition to the base type that it holds.
* This allows an object to also be accessible through pointers to
* its base types, for example.
*/
template <class TypeInfo = extensions::default_type_info>
class generic_parameter {
public:
typedef void (*FunctionPtr)();
/** The destructor cleans up the converters contained
* in this generic_parameter.
*/
virtual ~generic_parameter() {
for (typename std::map<TypeInfo, basic_converter*>::iterator
it = converters_.begin();
it != converters_.end(); ++it) {
delete it->second;
}
}
/** Return the TypeInfo for the primary type of this generic_parameter.
*/
virtual TypeInfo type() const = 0;
/** \brief Returns true if the parameter can convert to T.
*
* Given a type T, this function returns true if the generic_parameter
* can convert its value to T.
* \tparam T The type to check for conversions for.
* \returns true if the conversion is possible.
*/
template <class T>
bool can_cast() const {
TypeInfo i = type_info_handler<TypeInfo, T>::get_class_type();
return (converters_.find(i) != converters_.end());
}
/** \brief Returns a type S, converted from the type in the parameter.
*
* This will attempt to convert the generic_parameter to type T.
* If it fails, it will throw an exception. To avoid the exception,
* the can_cast function can be called first.
* \tparam T
* \returns A value of T that was converted from the generic_parameter.
* \pre can_cast<T>() == true
* \post None.
*/
template <class T>
T cast() const {
T dest;
TypeInfo i = type_info_handler<TypeInfo, T>::get_class_type();
typename std::map<TypeInfo, basic_converter*>::const_iterator it =
converters_.find(i);
if (it != converters_.end()) {
it->second->convert(value_, reinterpret_cast<void*>(&dest));
return dest;
}
throw conversion_not_found_exception();
}
/** \brief Another form of cast.
*
* Identical to T cast(), but takes a pointer to T instead.
*/
template <class T>
void cast(T* dest) {
*dest = cast<T>();
}
protected:
generic_parameter(void* value) : value_(value) {
}
class basic_converter {
public:
virtual void convert(void* src, void* dest) const = 0;
virtual ~basic_converter() {}
};
std::map<TypeInfo, basic_converter*> converters_;
private:
void* value_;
};
template <class T, class TypeInfo = extensions::default_type_info>
class parameter : public generic_parameter<TypeInfo> {
public:
template <class A, class B>
friend class basic_parameter_map;
virtual TypeInfo type() const {
return extensions::type_info_handler<TypeInfo, T>::get_class_type();
}
explicit parameter(T value)
: generic_parameter<TypeInfo>(reinterpret_cast<void*>(&value_)),
value_(value) {
// Add converter for current type.
generic_parameter<TypeInfo>::converters_.insert
(std::make_pair(extensions::type_info_handler<TypeInfo, T>
::get_class_type(),
new default_converter<T>()));
}
template <class S>
void converts_to_with_func(void (*convert_func)(T*, S*)) {
generic_parameter<TypeInfo>::converters_.insert
(std::make_pair(extensions::type_info_handler<TypeInfo, S>
::get_class_type(),
new specialized_converter<S>(convert_func)));
}
template <class S>
void converts_to() {
generic_parameter<TypeInfo>::converters_.insert
(std::make_pair(extensions::type_info_handler<TypeInfo, S>
::get_class_type(),
new default_converter<S>()));
}
private:
template <class S>
class default_converter :
public generic_parameter<TypeInfo>::basic_converter {
public:
virtual void convert(void* val, void* dest) const {
S* s = reinterpret_cast<S*>(dest);
*s = static_cast<S>(*reinterpret_cast<T*>(val));
}
};
template <class S>
class specialized_converter :
public generic_parameter<TypeInfo>::basic_converter {
public:
explicit specialized_converter(void (*convert_function)(T*, S*))
: convert_function_(convert_function) {
}
virtual void convert(void* val, void* dest) const {
S* s = reinterpret_cast<S*>(dest);
(*convert_function_)(reinterpret_cast<T*>(val), s);
}
private:
void (*convert_function_)(T*, S*);
};
T value_;
};
}
}
#endif // BOOST_EXTENSION_PARAMETER_HPP
| 30.926554 | 75 | 0.672817 | [
"object",
"vector"
] |
b81e701e0ece211ecb1cf3751b5d15db48cb9c23 | 13,601 | cpp | C++ | cob_phidgets/ros/src/phidgetik_ros.cpp | ipa-fxm/cob_driver | 9b2928486058bc650a4b25305a8d842498504c3c | [
"Apache-2.0"
] | null | null | null | cob_phidgets/ros/src/phidgetik_ros.cpp | ipa-fxm/cob_driver | 9b2928486058bc650a4b25305a8d842498504c3c | [
"Apache-2.0"
] | null | null | null | cob_phidgets/ros/src/phidgetik_ros.cpp | ipa-fxm/cob_driver | 9b2928486058bc650a4b25305a8d842498504c3c | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2017 Fraunhofer Institute for Manufacturing Engineering and Automation (IPA)
*
* 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 <cob_phidgets/phidgetik_ros.h>
PhidgetIKROS::PhidgetIKROS(ros::NodeHandle nh, int serial_num, std::string board_name, XmlRpc::XmlRpcValue* sensor_params, SensingMode mode)
:PhidgetIK(mode), _nh(nh), _serial_num(serial_num), _board_name(board_name)
{
ros::NodeHandle tmpHandle("~");
ros::NodeHandle nodeHandle(tmpHandle, board_name);
_outputChanged.updated=false;
_outputChanged.index=-1;
_outputChanged.state=0;
_pubAnalog = _nh.advertise<cob_phidgets::AnalogSensor>("analog_sensors", 1);
_pubDigital = _nh.advertise<cob_phidgets::DigitalSensor>("digital_sensors", 1);
_subDigital = _nh.subscribe("set_digital_sensor", 1, &PhidgetIKROS::onDigitalOutCallback, this);
_srvDigitalOut = nodeHandle.advertiseService("set_digital", &PhidgetIKROS::setDigitalOutCallback, this);
_srvDataRate = nodeHandle.advertiseService("set_data_rate", &PhidgetIKROS::setDataRateCallback, this);
_srvTriggerValue = nodeHandle.advertiseService("set_trigger_value", &PhidgetIKROS::setTriggerValueCallback, this);
if(init(_serial_num) != EPHIDGET_OK)
{
ROS_ERROR("Error open Phidget Board on serial %d. Message: %s",_serial_num, this->getErrorDescription(this->getError()).c_str());
}
if(waitForAttachment(10000) != EPHIDGET_OK)
{
ROS_ERROR("Error waiting for Attachment. Message: %s",this->getErrorDescription(this->getError()).c_str());
}
readParams(sensor_params);
}
PhidgetIKROS::~PhidgetIKROS()
{
}
auto PhidgetIKROS::readParams(XmlRpc::XmlRpcValue* sensor_params) -> void
{
if(sensor_params != nullptr)
{
for(auto& sensor : *sensor_params)
{
std::string name = sensor.first;
XmlRpc::XmlRpcValue value = sensor.second;
if(!value.hasMember("type"))
{
ROS_ERROR("Sensor Param '%s' has no 'type' member. Ignoring param!", name.c_str());
continue;
}
if(!value.hasMember("index"))
{
ROS_ERROR("Sensor Param '%s' has no 'index' member. Ignoring param!", name.c_str());
continue;
}
XmlRpc::XmlRpcValue value_type = value["type"];
XmlRpc::XmlRpcValue value_index = value["index"];
std::string type = value_type;
int index = value_index;
if(type == "analog")
_indexNameMapAnalog.insert(std::make_pair(index, name));
else if(type == "digital_in")
_indexNameMapDigitalIn.insert(std::make_pair(index, name));
else if(type == "digital_out")
_indexNameMapDigitalOut.insert(std::make_pair(index, name));
else
ROS_ERROR("Type '%s' in sensor param '%s' is unkown", type.c_str(), name.c_str());
if(value.hasMember("change_trigger"))
{
XmlRpc::XmlRpcValue value_change_trigger = value["change_trigger"];
int change_trigger = value_change_trigger;
ROS_WARN("Setting change trigger to %d for sensor %s with index %d ",change_trigger, name.c_str(), index);
setSensorChangeTrigger(index, change_trigger);
}
if(value.hasMember("data_rate"))
{
XmlRpc::XmlRpcValue value_data_rate = value["data_rate"];
int data_rate = value_data_rate;
ROS_WARN("Setting data rate to %d for sensor %s with index %d ",data_rate, name.c_str(), index);
setDataRate(index, data_rate);
}
}
}
//fill up rest of maps with default values
int count = this->getInputCount();
for(int i = 0; i < count; i++)
{
_indexNameMapItr = _indexNameMapDigitalIn.find(i);
if(_indexNameMapItr == _indexNameMapDigitalIn.end())
{
std::stringstream ss;
ss << _board_name << "/" << "in/" << i;
_indexNameMapDigitalIn.insert(std::make_pair(i, ss.str()));
}
}
count = this->getOutputCount();
for(int i = 0; i < count; i++)
{
_indexNameMapItr = _indexNameMapDigitalOut.find(i);
if(_indexNameMapItr == _indexNameMapDigitalOut.end())
{
std::stringstream ss;
ss << _board_name << "/" << "out/" << i;
_indexNameMapDigitalOut.insert(std::make_pair(i, ss.str()));
}
}
count = this->getSensorCount();
for(int i = 0; i < count; i++)
{
_indexNameMapItr = _indexNameMapAnalog.find(i);
if(_indexNameMapItr == _indexNameMapAnalog.end())
{
std::stringstream ss;
ss << _board_name << "/" << i;
_indexNameMapAnalog.insert(std::make_pair(i, ss.str()));
}
}
//fill up reverse mapping
count = this->getInputCount();
for(int i = 0; i < count; i++)
{
_indexNameMapItr = _indexNameMapDigitalIn.find(i);
if(_indexNameMapItr != _indexNameMapDigitalIn.end())
{
std::stringstream ss;
ss << _board_name << "/" << "in/" << i;
_indexNameMapDigitalInRev.insert(std::make_pair(_indexNameMapDigitalIn[i],i));
}
}
count = this->getOutputCount();
for(int i = 0; i < count; i++)
{
_indexNameMapItr = _indexNameMapDigitalOut.find(i);
if(_indexNameMapItr != _indexNameMapDigitalOut.end())
{
_indexNameMapDigitalOutRev.insert(std::make_pair(_indexNameMapDigitalOut[i],i));
}
}
count = this->getSensorCount();
for(int i = 0; i < count; i++)
{
_indexNameMapItr = _indexNameMapAnalog.find(i);
if(_indexNameMapItr != _indexNameMapAnalog.end())
{
_indexNameMapAnalogRev.insert(std::make_pair(_indexNameMapAnalog[i],i));
}
}
}
auto PhidgetIKROS::update() -> void
{
int count = this->getInputCount();
cob_phidgets::DigitalSensor msg_digit;
std::vector<std::string> names;
std::vector<signed char> states;
//------- publish digital input states ----------//
for(int i = 0; i < count; i++)
{
std::string name;
_indexNameMapItr = _indexNameMapDigitalIn.find(i);
if(_indexNameMapItr != _indexNameMapDigitalIn.end())
name = (*_indexNameMapItr).second;
names.push_back(name);
states.push_back(this->getInputState(i));
}
msg_digit.header.stamp = ros::Time::now();
msg_digit.uri = names;
msg_digit.state = states;
_pubDigital.publish(msg_digit);
//------- publish digital output states ----------//
names.clear();
states.clear();
count = this->getOutputCount();
for(int i = 0; i < count; i++)
{
std::string name;
_indexNameMapItr = _indexNameMapDigitalOut.find(i);
if(_indexNameMapItr != _indexNameMapDigitalOut.end())
name = (*_indexNameMapItr).second;
names.push_back(name);
states.push_back(this->getOutputState(i));
}
msg_digit.header.stamp = ros::Time::now();
msg_digit.uri = names;
msg_digit.state = states;
_pubDigital.publish(msg_digit);
//------- publish analog input states ----------//
cob_phidgets::AnalogSensor msg_analog;
names.clear();
std::vector<short int> values;
count = this->getSensorCount();
for(int i = 0; i < count; i++)
{
std::string name;
_indexNameMapItr = _indexNameMapAnalog.find(i);
if(_indexNameMapItr != _indexNameMapAnalog.end())
name = (*_indexNameMapItr).second;
names.push_back(name);
values.push_back(this->getSensorValue(i));
}
msg_analog.header.stamp = ros::Time::now();
msg_analog.uri = names;
msg_analog.value = values;
_pubAnalog.publish(msg_analog);
}
auto PhidgetIKROS::inputChangeHandler(int index, int inputState) -> int
{
ROS_DEBUG("Board %s: Digital Input %d changed to State: %d", _board_name.c_str(), index, inputState);
cob_phidgets::DigitalSensor msg;
std::vector<std::string> names;
std::vector<signed char> states;
std::string name;
_indexNameMapItr = _indexNameMapAnalog.find(index);
if(_indexNameMapItr != _indexNameMapAnalog.end())
name = (*_indexNameMapItr).second;
names.push_back(name);
states.push_back(inputState);
msg.header.stamp = ros::Time::now();
msg.uri = names;
msg.state = states;
_pubDigital.publish(msg);
return 0;
}
auto PhidgetIKROS::outputChangeHandler(int index, int outputState) -> int
{
ROS_DEBUG("Board %s: Digital Output %d changed to State: %d", _board_name.c_str(), index, outputState);
std::lock_guard<std::mutex> lock{_mutex};
_outputChanged.updated = true;
_outputChanged.index = index;
_outputChanged.state = outputState;
return 0;
}
auto PhidgetIKROS::sensorChangeHandler(int index, int sensorValue) -> int
{
ROS_DEBUG("Board %s: Analog Input %d changed to Value: %d", _board_name.c_str(), index, sensorValue);
cob_phidgets::AnalogSensor msg;
std::vector<std::string> names;
std::vector<short int> values;
std::string name;
_indexNameMapItr = _indexNameMapAnalog.find(index);
if(_indexNameMapItr != _indexNameMapAnalog.end())
name = (*_indexNameMapItr).second;
names.push_back(name);
values.push_back(sensorValue);
msg.header.stamp = ros::Time::now();
msg.uri = names;
msg.value = values;
_pubAnalog.publish(msg);
return 0;
}
auto PhidgetIKROS::setDigitalOutCallback(cob_phidgets::SetDigitalSensor::Request &req,
cob_phidgets::SetDigitalSensor::Response &res) -> bool
{
bool ret = false;
_mutex.lock();
_outputChanged.updated=false;
_outputChanged.index=-1;
_outputChanged.state=0;
_mutex.unlock();
// this check is nessesary because [] operator on Maps inserts an element if it is not found
_indexNameMapRevItr = _indexNameMapDigitalOutRev.find(req.uri);
if(_indexNameMapRevItr != _indexNameMapDigitalOutRev.end())
{
if(this->getOutputState(_indexNameMapDigitalOutRev[req.uri]) == req.state)
{
ROS_INFO("Digital output %i is already at state %i", _indexNameMapDigitalOutRev[req.uri], req.state);
res.uri = req.uri;
res.state = req.state;
ret = true;
}
else
{
ROS_INFO("Setting digital output %i to state %i", _indexNameMapDigitalOutRev[req.uri], req.state);
this->setOutputState(_indexNameMapDigitalOutRev[req.uri], req.state);
ros::Time start = ros::Time::now();
while((ros::Time::now().toSec() - start.toSec()) < 1.0)
{
_mutex.lock();
if(_outputChanged.updated == true)
{
_mutex.unlock();
break;
}
_mutex.unlock();
ros::Duration(0.025).sleep();
}
_mutex.lock();
res.uri = _indexNameMapDigitalOut[_outputChanged.index];
res.state = _outputChanged.state;
ROS_DEBUG("Sending response: updated: %u, index: %d, state: %d",_outputChanged.updated, _outputChanged.index, _outputChanged.state);
ret = (_outputChanged.updated && (_outputChanged.index == _indexNameMapDigitalOutRev[req.uri]));
_mutex.unlock();
}
}
else
{
ROS_DEBUG("Could not find uri '%s' inside port uri mapping", req.uri.c_str());
res.uri = req.uri;
res.state = req.state;
ret = false;
}
return ret;
}
auto PhidgetIKROS::onDigitalOutCallback(const cob_phidgets::DigitalSensorConstPtr& msg) -> void
{
if(msg->uri.size() == msg->state.size())
{
for(size_t i = 0; i < msg->uri.size(); i++)
{
// this check is nessesary because [] operator on Maps inserts an element if it is not found
_indexNameMapRevItr = _indexNameMapDigitalOutRev.find(msg->uri[i]);
if(_indexNameMapRevItr != _indexNameMapDigitalOutRev.end())
{
ROS_INFO("Setting digital output %i to state %i", _indexNameMapDigitalOutRev[msg->uri[i]], msg->state[i]);
this->setOutputState(_indexNameMapDigitalOutRev[msg->uri[i]], msg->state[i]);
}
else
ROS_DEBUG("Could not find uri '%s' inside port uri mapping", msg->uri[i].c_str());
}
}
else
{
ROS_ERROR("Received message with different uri and state container sizes");
}
}
auto PhidgetIKROS::setDataRateCallback(cob_phidgets::SetDataRate::Request &req,
cob_phidgets::SetDataRate::Response &res) -> bool
{
this->setDataRate(req.index, req.data_rate);
return true;
}
auto PhidgetIKROS::setTriggerValueCallback(cob_phidgets::SetTriggerValue::Request &req,
cob_phidgets::SetTriggerValue::Response &res) -> bool
{
this->setSensorChangeTrigger(req.index, req.trigger_value);
return true;
}
auto PhidgetIKROS::attachHandler() -> int
{
int serialNo, version, numInputs, numOutputs, millis;
int numSensors, triggerVal, ratiometric;
const char *ptr, *name;
CPhidget_getDeviceName((CPhidgetHandle)_iKitHandle, &name);
CPhidget_getDeviceType((CPhidgetHandle)_iKitHandle, &ptr);
CPhidget_getSerialNumber((CPhidgetHandle)_iKitHandle, &serialNo);
CPhidget_getDeviceVersion((CPhidgetHandle)_iKitHandle, &version);
CPhidgetInterfaceKit_getInputCount(_iKitHandle, &numInputs);
CPhidgetInterfaceKit_getOutputCount(_iKitHandle, &numOutputs);
CPhidgetInterfaceKit_getSensorCount(_iKitHandle, &numSensors);
CPhidgetInterfaceKit_getRatiometric(_iKitHandle, &ratiometric);
ROS_INFO("%s %d attached!!", name, serialNo);
ROS_DEBUG("%s", ptr);
ROS_DEBUG("Serial Number: %d\tVersion: %d", serialNo, version);
ROS_DEBUG("Num Digital Inputs: %d\tNum Digital Outputs: %d", numInputs, numOutputs);
ROS_DEBUG("Num Sensors: %d", numSensors);
ROS_DEBUG("Ratiometric: %d", ratiometric);
for(int i = 0; i < numSensors; i++)
{
CPhidgetInterfaceKit_getSensorChangeTrigger(_iKitHandle, i, &triggerVal);
CPhidgetInterfaceKit_getDataRate(_iKitHandle, i, &millis);
ROS_DEBUG("Sensor#: %d > Sensitivity Trigger: %d", i, triggerVal);
ROS_DEBUG("Sensor#: %d > Data Rate: %d", i, millis);
}
return 0;
}
auto PhidgetIKROS::detachHandler() -> int
{
int serial_number;
const char *device_name;
CPhidget_getDeviceName ((CPhidgetHandle)_iKitHandle, &device_name);
CPhidget_getSerialNumber((CPhidgetHandle)_iKitHandle, &serial_number);
ROS_INFO("%s Serial number %d detached!", device_name, serial_number);
return 0;
}
| 31.92723 | 140 | 0.7148 | [
"vector"
] |
b81f8303945365cdd67bc7090abd5ad7270857e2 | 4,588 | cpp | C++ | source/blender/freestyle/intern/image/ImagePyramid.cpp | 1-MillionParanoidTterabytes/Blender-2.79b-blackened | e8d767324e69015aa66850d13bee7db1dc7d084b | [
"Unlicense"
] | 2 | 2018-06-18T01:50:25.000Z | 2018-06-18T01:50:32.000Z | source/blender/freestyle/intern/image/ImagePyramid.cpp | 1-MillionParanoidTterabytes/Blender-2.79b-blackened | e8d767324e69015aa66850d13bee7db1dc7d084b | [
"Unlicense"
] | null | null | null | source/blender/freestyle/intern/image/ImagePyramid.cpp | 1-MillionParanoidTterabytes/Blender-2.79b-blackened | e8d767324e69015aa66850d13bee7db1dc7d084b | [
"Unlicense"
] | null | null | null | /*
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* ***** END GPL LICENSE BLOCK *****
*/
/** \file blender/freestyle/intern/image/ImagePyramid.cpp
* \ingroup freestyle
* \brief Class to represent a pyramid of images
* \author Stephane Grabli
* \date 25/12/2003
*/
#include <iostream>
#include "GaussianFilter.h"
#include "Image.h"
#include "ImagePyramid.h"
using namespace std;
namespace Freestyle {
#if 0
ImagePyramid::ImagePyramid(const GrayImage& level0, unsigned nbLevels)
{
BuildPyramid(level0,nbLevels);
}
#endif
ImagePyramid::ImagePyramid(const ImagePyramid& /*iBrother*/)
{
if (!_levels.empty()) {
for (vector<GrayImage*>::iterator im = _levels.begin(), imend = _levels.end(); im != imend; ++im) {
_levels.push_back(new GrayImage(**im));
}
}
}
ImagePyramid::~ImagePyramid()
{
if (!_levels.empty()) {
for (vector<GrayImage*>::iterator im = _levels.begin(), imend = _levels.end(); im != imend; ++im) {
delete (*im);
}
_levels.clear();
}
}
GrayImage * ImagePyramid::getLevel(int l)
{
return _levels[l];
}
float ImagePyramid::pixel(int x, int y, int level)
{
GrayImage *img = _levels[level];
if (0 == level) {
return img->pixel(x, y);
}
unsigned int i = 1 << level;
unsigned int sx = x >> level;
unsigned int sy = y >> level;
if (sx >= img->width())
sx = img->width() - 1;
if (sy >= img->height())
sy = img->height() - 1;
// bilinear interpolation
float A = i * (sx + 1) - x;
float B = x - i * sx;
float C = i * (sy + 1) - y;
float D = y - i * sy;
float P1(0), P2(0);
P1 = A * img->pixel(sx, sy);
if (sx < img->width() - 1) {
if (x % i != 0)
P1 += B * img->pixel(sx + 1, sy);
}
else {
P1 += B * img->pixel(sx, sy);
}
if (sy < img->height() - 1) {
if (y % i != 0) {
P2 = A * img->pixel(sx, sy + 1);
if (sx < img->width() - 1) {
if (x % i != 0)
P2 += B * img->pixel(sx + 1, sy + 1);
}
else {
P2 += B * img->pixel(sx, sy + 1);
}
}
}
else {
P2 = P1;
}
return (1.0f / (float)(1 << (2 * level))) * (C * P1 + D * P2);
}
int ImagePyramid::width(int level)
{
return _levels[level]->width();
}
int ImagePyramid::height(int level)
{
return _levels[level]->height();
}
GaussianPyramid::GaussianPyramid(const GrayImage& level0, unsigned nbLevels, float iSigma) : ImagePyramid()
{
_sigma = iSigma;
BuildPyramid(level0, nbLevels);
}
GaussianPyramid::GaussianPyramid(GrayImage *level0, unsigned nbLevels, float iSigma) : ImagePyramid()
{
_sigma = iSigma;
BuildPyramid(level0, nbLevels);
}
GaussianPyramid::GaussianPyramid(const GaussianPyramid& iBrother) : ImagePyramid(iBrother)
{
_sigma = iBrother._sigma;
}
void GaussianPyramid::BuildPyramid(const GrayImage& level0, unsigned nbLevels)
{
GrayImage *pLevel = new GrayImage(level0);
BuildPyramid(pLevel, nbLevels);
}
void GaussianPyramid::BuildPyramid(GrayImage *level0, unsigned nbLevels)
{
GrayImage *pLevel = level0;
_levels.push_back(pLevel);
GaussianFilter gf(_sigma);
// build the nbLevels:
unsigned w = pLevel->width();
unsigned h = pLevel->height();
if (nbLevels != 0) {
for (unsigned int i = 0; i < nbLevels; ++i) { //soc
w = pLevel->width() >> 1;
h = pLevel->height() >> 1;
GrayImage *img = new GrayImage(w, h);
for (unsigned int y = 0; y < h; ++y) {
for (unsigned int x = 0; x < w; ++x) {
float v = gf.getSmoothedPixel<GrayImage>(pLevel, 2 * x, 2 * y);
img->setPixel(x, y, v);
}
}
_levels.push_back(img);
pLevel = img;
}
}
else {
while ((w > 1) && (h > 1)) {
w = pLevel->width() >> 1;
h = pLevel->height() >> 1;
GrayImage *img = new GrayImage(w, h);
for (unsigned int y = 0; y < h; ++y) {
for (unsigned int x = 0; x < w; ++x) {
float v = gf.getSmoothedPixel<GrayImage>(pLevel, 2 * x, 2 * y);
img->setPixel(x, y, v);
}
}
_levels.push_back(img);
pLevel = img;
}
}
}
} /* namespace Freestyle */
| 24.147368 | 107 | 0.627289 | [
"vector"
] |
b8249b681533ae56fe1d4ca61f0f1f4b5a9ff029 | 9,999 | hpp | C++ | Progvo-PM/GUI/IDE.hpp | Pttn/Progvo | afb2e70e4121a6455bd653a87d258085c18df9ec | [
"MIT"
] | 4 | 2021-01-05T23:20:34.000Z | 2022-03-20T10:11:05.000Z | Progvo-PM/GUI/IDE.hpp | Pttn/Progvo | afb2e70e4121a6455bd653a87d258085c18df9ec | [
"MIT"
] | null | null | null | Progvo-PM/GUI/IDE.hpp | Pttn/Progvo | afb2e70e4121a6455bd653a87d258085c18df9ec | [
"MIT"
] | 1 | 2022-03-20T10:16:04.000Z | 2022-03-20T10:16:04.000Z | // (c) 2019-2020 Pttn (https://Progvo.dev)
#ifndef HEADER_IDE_hpp
#define HEADER_IDE_hpp
#include <thread>
#include "Font.hpp"
#include "../Interpreter/Interpreter.hpp"
#include "Widgets/Widgets.hpp"
#include "../Interpreter/BuiltIn/BuiltIn.hpp"
#ifdef __linux__
#define Font X11_Font // X11 is already using something named "Font" :| ...
#include <X11/Xlib.h>
#undef Font
#endif
#define PROGVOPM_VERSION "0.9-skizo"
class Console {
Font _font;
std::shared_ptr<Ecii::String> _text;
Ecii::String _input;
Vect2<std::size_t> _size;
std::size_t _firstVisibleLine;
bool _show, _close, _inputting;
public:
Console(const Font &font) :
_font(font),
_text(builtInStandardOutput),
_size(Vect2<std::size_t>(80, 25)),
_firstVisibleLine(0),
_show(true),
_close(false),
_inputting(false) {
builtInStandardInputFunction = [&](){return input();};
}
void show() {_show = true;}
void hide() {_show = false;}
void close() {_close = true;}
Ecii::String input() {
Ecii::String es;
_inputting = true;
while (_inputting) {std::this_thread::sleep_for(std::chrono::milliseconds(20));}
es = _input;
_input = "";
return es;
}
void run() {
sf::RenderWindow consoleWindow(sf::VideoMode(_font.charSizes().x*_size.x, _font.charSizes().y*_size.y), "Progvo konzolo", sf::Style::Close);
consoleWindow.setFramerateLimit(60);
while (consoleWindow.isOpen()) {
if (_close) consoleWindow.close();
else {
if (_show) consoleWindow.setVisible(true);
sf::Event event;
while (consoleWindow.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
_show = false;
consoleWindow.setVisible(false);
}
else if (event.type == sf::Event::MouseWheelScrolled) {
if (event.mouseWheelScroll.wheel == sf::Mouse::VerticalWheel) {
if (event.mouseWheelScroll.delta > 0) {
if (_firstVisibleLine != 0) _firstVisibleLine--;
}
else if (event.mouseWheelScroll.delta < 0) {
_firstVisibleLine++;
}
}
}
if (_inputting) {
if (event.type == sf::Event::KeyPressed) {
if (event.key.code == sf::Keyboard::Enter)
_inputting = false;
}
if (event.type == sf::Event::TextEntered && _inputting) {
if (event.text.unicode == 8 && _input.size() != 0) {
_input.erase(_input.size());
_text->erase(_text->size());
}
else {
if (event.text.unicode <= 255) {
_input.add(Ecii::charToEcii((char) event.text.unicode, sf::Keyboard::isKeyPressed(sf::Keyboard::LAlt)));
_text->add(Ecii::charToEcii((char) event.text.unicode, sf::Keyboard::isKeyPressed(sf::Keyboard::LAlt)));
}
else {
_input.add(std::byte{252});
_text->add(std::byte{252});
}
}
}
}
}
consoleWindow.clear();
const std::vector<std::byte> chars(_text->vb());
TextPos tp(0, 0);
for (std::size_t i(0) ; i < chars.size() ; i++) {
if (chars[i] == Ecii::EOL) {
tp.column = 0;
tp.line++;
}
else {
if (tp.line >= _firstVisibleLine) {
sf::Sprite s(_font.getSprite((uint8_t) chars[i]));
s.setPosition(sf::Vector2f(tp.column*_font.charSizes().x, (tp.line - _firstVisibleLine)*_font.charSizes().y));
consoleWindow.draw(s);
}
tp.column++;
if (tp.column == _size.x) {
tp.column = 0;
tp.line++;
}
}
}
consoleWindow.display();
}
}
}
};
class IDE {
std::filesystem::path _curDir, _binDir, _incDir;
std::shared_ptr<Console> _console;
static std::shared_ptr<IDE> _ide;
bool _mustRefresh;
void _fillFileList(const std::filesystem::path& directory, const std::shared_ptr<ListBox> &list) {
list->clear();
std::vector<Ecii::String> folders, files;
for (const auto &file : std::filesystem::directory_iterator(directory)) {
if (file.is_directory()) folders.push_back(file.path().filename().string());
else if (file.is_regular_file()) {
if (file.path().extension() == ".Pvo")
files.push_back(file.path().filename().string());
}
}
std::sort(folders.begin(), folders.end());
std::sort(files.begin(), files.end());
list->add("..");
for (const auto &folder : folders) list->add(folder + "/");
for (const auto &file : files) list->add(file);
}
public:
IDE(const std::filesystem::path &binPath) {
_curDir = std::filesystem::current_path();
if (!std::filesystem::exists(binPath)) {
BUG("Malvalida dosierindiko de la plenumebla dosiero");
_binDir = _curDir;
}
else if (std::filesystem::is_directory(binPath)) _binDir = binPath;
else _binDir = binPath.parent_path();
_incDir = _binDir;
_console = nullptr;
_mustRefresh = true;
}
static void init(const std::filesystem::path &binPath) {_ide = std::make_shared<IDE>(binPath);}
static std::shared_ptr<IDE> get() {return _ide;}
std::shared_ptr<Console> getConsole() {return _console;}
std::filesystem::path getCurDir() const {return _curDir;}
void setCurDir(std::filesystem::path dir) {
if (!std::filesystem::exists(dir)) BUG("Malvalida dosierindiko");
else if (std::filesystem::is_directory(dir)) _curDir = dir;
else _curDir = dir.parent_path();
}
std::filesystem::path getIncDir() const {return _incDir;}
void start() {
#ifdef __linux__
XInitThreads();
#endif
uint64_t margin(4), rightPanelWidth(3*96 + 4*margin), rightPanelPosX(0);
sf::RenderWindow window(sf::VideoMode(800, 600), "Progvo Programada Medio " + std::string(PROGVOPM_VERSION));
window.setFramerateLimit(60);
std::shared_ptr<Widget> widgetGroup(std::make_shared<Widget>());
std::filesystem::path fontPath("EkioTiparo.png");
Font font((_binDir/fontPath).string(), Vect2<uint16_t>(8, 16));
_console = std::make_shared<Console>(font);
if (!font.isLoaded()) {
BUG("Ne eblas shargi la Ekio tiparon");
std::exit(-1);
}
else if (font.getSpriteCount() != 256) {
BUG("Malghusta nombro de kaheloj " << font.getSpriteCount() << ", devas esti 256");
std::exit(-1);
}
std::shared_ptr<TextBox> textBox(std::make_shared<TextBox>(Vect2<float>(1, 1), Vect2<float>(margin, margin), font));
textBox->setParent(widgetGroup);
std::shared_ptr<ListBox> fileList(std::make_shared<ListBox>(Vect2<float>(1, 1), Vect2<float>(0, 0), font));
fileList->setParent(widgetGroup);
std::shared_ptr<TextBoxInline> pathField = std::make_shared<TextBoxInline>(Vect2<float>(rightPanelWidth - 2*margin, 24), Vect2<float>(1, 1), font);
pathField->setParent(widgetGroup);
std::shared_ptr<Button> loadButton(std::make_shared<Button>(Vect2<float>(96, 24), Vect2<float>(0, 0), Ecii::String(std::byte{70}) + "argi", font)); // ลargi
loadButton->setParent(widgetGroup);
std::shared_ptr<Button> saveButton(std::make_shared<Button>(Vect2<float>(96, 24), Vect2<float>(0, 0), "Konservi", font));
saveButton->setParent(widgetGroup);
std::shared_ptr<Button> executeButton(std::make_shared<Button>(Vect2<float>(96, 24), Vect2<float>(0, 0), "Plenumi", font));
executeButton->setParent(widgetGroup);
_fillFileList(_curDir, fileList);
Interpreter interpreter;
std::thread consoleThread(&Console::run, _console);
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
interpreter.reset();
_console->close();
consoleThread.join();
window.close();
}
if (event.type == sf::Event::Resized) {
if (window.getSize().x < 2*rightPanelWidth)
window.setSize(sf::Vector2u(2*rightPanelWidth, window.getSize().y));
sf::FloatRect visibleArea(0, 0, window.getSize().x, window.getSize().y);
window.setView(sf::View(visibleArea));
_mustRefresh = true;
}
widgetGroup->action(event);
if (fileList->unclicked()) {
std::string selectedPath(fileList->selected().str());
if (std::filesystem::is_directory(_curDir/selectedPath)) {
pathField->setText("");
if (fileList->selected().str() == "..") _curDir = _curDir.parent_path();
else _curDir /= selectedPath;
_fillFileList(_curDir, fileList);
}
else
pathField->setText(fileList->selected());
}
if (saveButton->unclicked()) {
save(textBox->getText().vb(), (_curDir/pathField->getText().str()).string());
_fillFileList(_curDir, fileList);
}
if (loadButton->unclicked())
textBox->setText(load((_curDir/std::filesystem::path(pathField->getText().str())).string()));
if (executeButton->unclicked()) {
save(textBox->getText().vb(), (_curDir/pathField->getText().str()).string());
if (!interpreter.isRunning()) {
std::cout << "Plenumanta " << pathField->getText() << "..." << std::endl;
interpreter.run(pathField->getText());
}
else if (!interpreter.isStopping()) {
std::cout << "Haltanta de la programo..." << std::endl;
interpreter.stop();
}
}
}
rightPanelPosX = window.getSize().x - rightPanelWidth;
textBox->setSize(Vect2<float>(window.getSize().x - rightPanelWidth - margin, window.getSize().y - 2*margin));
fileList->setSize(Vect2<float>(rightPanelWidth - 2*margin, window.getSize().y - 2*24 - 4*margin));
fileList->setPosition(sf::Vector2f(rightPanelPosX + margin, margin));
pathField->setPosition(sf::Vector2f(rightPanelPosX + margin, window.getSize().y - 2*24 - 2*margin));
loadButton->setPosition(sf::Vector2f(rightPanelPosX + margin, window.getSize().y - 24 - margin));
saveButton->setPosition(sf::Vector2f(rightPanelPosX + 96 + 2*margin, window.getSize().y - 24 - margin));
executeButton->setPosition(sf::Vector2f(rightPanelPosX + 2*96 + 3*margin, window.getSize().y - 24 - margin));
if (!interpreter.isRunning()) executeButton->setText("Plenumi");
else if (interpreter.isStopping()) executeButton->setText("Haltanta...");
else executeButton->setText("Halti");
window.clear();
window.draw(*widgetGroup);
window.display();
}
}
};
inline std::shared_ptr<IDE> IDE::_ide = nullptr;
#endif | 35.207746 | 158 | 0.648965 | [
"vector"
] |
b8263a6e18abd09edbeedd3ee361b66e9b98700c | 2,578 | cc | C++ | src/raptor/interval_tree_builder.cc | isovic/raptor | 171e0f1b94366f20250a00389400a2fcd267bcc6 | [
"BSD-3-Clause-Clear"
] | 60 | 2019-07-09T14:57:48.000Z | 2022-03-29T06:53:39.000Z | src/raptor/interval_tree_builder.cc | isovic/raptor | 171e0f1b94366f20250a00389400a2fcd267bcc6 | [
"BSD-3-Clause-Clear"
] | 2 | 2019-05-28T01:59:50.000Z | 2021-05-18T13:15:10.000Z | src/raptor/interval_tree_builder.cc | isovic/raptor | 171e0f1b94366f20250a00389400a2fcd267bcc6 | [
"BSD-3-Clause-Clear"
] | 4 | 2019-05-25T15:41:56.000Z | 2019-07-10T11:44:22.000Z | /*
* interval_tree_builder.cc
*
* Created on: Jan 09, 2018
* Author: Ivan Sovic
*/
#include <raptor/interval_tree_builder.h>
namespace raptor {
std::unordered_map<int32_t, IntervalTreeInt64> BuildAnchorIntervalTrees(
const std::vector<raptor::AnchorPtr>& anchors) {
// This maps the target ID to the tree of all chain intervals.
std::unordered_map<int32_t, IntervalTreeInt64> trees;
// We need to poll intervals first, so that the trees can be constructed.
std::unordered_map<int32_t, IntervalVectorInt64> intervals;
for (size_t i = 0; i < anchors.size(); i++) {
auto& anchor = anchors[i];
int32_t t_id = anchor->TargetID();
int32_t t_start = anchor->TargetStart();
int32_t t_end = anchor->TargetEnd();
bool t_rev = anchor->TargetRev();
auto it = intervals.find(t_id);
if (it == intervals.end()) {
intervals[t_id] = IntervalVectorInt64{};
}
intervals[t_id].emplace_back(IntervalInt64(t_start, t_end, i));
}
for (auto it = intervals.begin(); it != intervals.end(); ++it) {
trees[it->first] = IntervalTreeInt64(std::move(it->second));
}
return trees;
}
std::unordered_map<int32_t, IntervalTreeInt64> BuildTargetAnchorIntervalTrees(
const std::vector<std::shared_ptr<raptor::TargetAnchorType>>& target_anchors) {
// This maps the target ID to the tree of all chain intervals.
std::unordered_map<int32_t, IntervalTreeInt64> trees;
// We need to poll intervals first, so that the trees can be constructed.
std::unordered_map<int32_t, IntervalVectorInt64> intervals;
for (size_t i = 0; i < target_anchors.size(); i++) {
// Uses `i` instead of `t_id` so that we know where exactly the
// anchors came from.
// int32_t t_id = target_anchors[i]->env()->t_id;
bool t_rev = target_anchors[i]->env()->t_rev;
auto it = intervals.find(i);
if (it == intervals.end()) {
intervals[i] = IntervalVectorInt64{};
it = intervals.find(i);
}
for (size_t j = 0; j < target_anchors[i]->hits().size(); j++) {
auto& hit = target_anchors[i]->hits()[j];
int32_t t_start = hit->TargetStart();
int32_t t_end = hit->TargetEnd();
it->second.emplace_back(IntervalInt64(t_start, t_end, j));
}
}
for (auto it = intervals.begin(); it != intervals.end(); ++it) {
trees[it->first] = IntervalTreeInt64(std::move(it->second));
}
return trees;
}
} // namespace raptor
| 33.051282 | 83 | 0.624127 | [
"vector"
] |
b829a7af15650085711b76c1340ba2275202ab0c | 40,284 | cc | C++ | src/pgesv/HPLAI_pdgesv.cc | ATestGroup233/HPL-AI | 2eb76d856d9ed2bd565014e1004d735755e061c9 | [
"MIT"
] | 11 | 2021-03-16T11:21:42.000Z | 2022-01-25T20:42:16.000Z | src/pgesv/HPLAI_pdgesv.cc | ATestGroup233/HPL-AI | 2eb76d856d9ed2bd565014e1004d735755e061c9 | [
"MIT"
] | 1 | 2021-03-13T18:19:54.000Z | 2021-03-20T14:07:31.000Z | src/pgesv/HPLAI_pdgesv.cc | ATestGroup233/HPL-AI | 2eb76d856d9ed2bd565014e1004d735755e061c9 | [
"MIT"
] | 5 | 2021-03-16T11:21:44.000Z | 2022-02-13T05:09:24.000Z | /*
* MIT License
*
* Copyright (c) 2021 WuK
*
* 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 files
*/
#include "hplai.hh"
// https://github.com/schuangs/hpl-ai-with-IR/blob/master/src/pgesv/HPL_pLdtrsv.c
static void HPL_pLdtrsv(
HPL_T_grid *GRID,
HPL_T_pmat *AMAT)
{
/*
* Purpose
* =======
*
* HPL_pdtrsv solves an lower triangular system of linear equations.
*
* The rhs is the last column of the N by N+1 matrix A. The solve starts
* in the process column owning the 1th column of A, so the rhs b may
* need to be moved one process column to the left at the beginning. The
* routine therefore needs a column vector in every process column but
* the one owning b. The result is replicated in all process rows, and
* returned in XR, i.e. XR is of size nq = LOCq( N ) in all processes.
*
* The algorithm uses decreasing one-ring broadcast in process rows and
* columns implemented in terms of synchronous communication point to
* point primitives. The lookahead of depth 1 is used to minimize the
* critical path. This entire operation is essentially ``latency'' bound
* and an estimate of its running time is given by:
*
* (move rhs) lat + N / ( P bdwth ) +
* (solve) ((N / NB)-1) 2 (lat + NB / bdwth) +
* gam2 N^2 / ( P Q ),
*
* where gam2 is an estimate of the Level 2 BLAS rate of execution.
* There are N / NB diagonal blocks. One must exchange 2 messages of
* length NB to compute the next NB entries of the vector solution, as
* well as performing a total of N^2 floating point operations.
*
* Arguments
* =========
*
* GRID (local input) HPL_T_grid *
* On entry, GRID points to the data structure containing the
* process grid information.
*
* AMAT (local input/output) HPL_T_pmat *
* On entry, AMAT points to the data structure containing the
* local array information.
*
* ---------------------------------------------------------------------
*/
/*
* .. Local Variables ..
*/
MPI_Comm Ccomm, Rcomm;
double *A = NULL, *Aprev = NULL, *Aptr, *XC = NULL,
*XR = NULL, *Xd = NULL, *Xdprev = NULL,
*W = NULL;
int Alcol, Alrow, Anpprev, Anp, Anq, Bcol,
Cmsgid, GridIsNotPx1, GridIsNot1xQ, Rmsgid,
Wfr = 0, colprev, kb, kbprev, lda, mycol,
myrow, n, n1, n1p, n1pprev = 0, nb, npcol,
nprow, rowprev, tmp1, tmp2, np, nq, N;
/* ..
* .. Executable Statements ..
*/
#ifdef HPL_DETAILED_TIMING
HPL_ptimer(HPL_TIMING_PTRSV);
#endif
if ((N = n = AMAT->n) <= 0)
return;
nb = AMAT->nb;
lda = AMAT->ld;
A = AMAT->A;
XR = AMAT->X;
(void)HPL_grid_info(GRID, &nprow, &npcol, &myrow, &mycol);
Rcomm = GRID->row_comm;
Rmsgid = MSGID_BEGIN_PTRSV;
Ccomm = GRID->col_comm;
Cmsgid = MSGID_BEGIN_PTRSV + 1;
GridIsNot1xQ = (nprow > 1);
GridIsNotPx1 = (npcol > 1);
/*
* Move the rhs in the process column owning the first column of A.
*/
/* np and nq are the local dimensions of of A */
Mnumroc(np, n, nb, nb, myrow, 0, nprow);
Mnumroc(nq, n, nb, nb, mycol, 0, npcol);
Anp = 0;
Anq = 0;
Alrow = 0;
Alcol = 0;
kb = Mmin(n, nb);
Aptr = (double *)(A);
XC = Mptr(Aptr, 0, nq, lda);
Mindxg2p(n, nb, nb, Bcol, 0, npcol);
if ((np > 0) && (Alcol != Bcol))
{
if (mycol == Bcol)
{
(void)HPL_send(XC, np, Alcol, Rmsgid, Rcomm);
}
else if (mycol == Alcol)
{
(void)HPL_recv(XC, np, Bcol, Rmsgid, Rcomm);
}
}
Rmsgid = (Rmsgid + 2 >
MSGID_END_PTRSV
? MSGID_BEGIN_PTRSV
: Rmsgid + 2);
/* other rhs area set to 0 */
if (mycol != Alcol)
{
for (tmp1 = 0; tmp1 < np; tmp1++)
XC[tmp1] = HPL_rzero;
}
/*
* Set up lookahead, that is to perform iteration on the first block column
*/
/* n1 is the global distance between two neighboring blocks of the same
process in a block row */
n1 = (npcol - 1) * nb;
n1 = Mmax(n1, nb);
/* allocate work space */
if (np > 0)
{
W = (double *)malloc((size_t)(Mmin(n1, np)) * sizeof(double));
if (W == NULL)
{
HPLAI_pabort(__LINE__, "HPL_pLdtrsv", "Memory allocation failed");
}
Wfr = 1;
}
/* previous version of parameters */
Anpprev = Anp;
Xdprev = Xd = XR;
Aprev = Aptr;
tmp1 = kb;
tmp2 = Mmin(n - kb, n1);
MnumrocI(n1pprev, tmp2, Mmin(N, tmp1), nb, nb, myrow, 0, nprow);
/* update local variables */
if (myrow == Alrow)
{
Anp += kb;
}
if (mycol == Alcol)
{
if (myrow == Alrow)
{
blas::trsv<double, double>(blas::Layout::ColMajor, blas::Uplo::Lower, blas::Op::NoTrans, blas::Diag::Unit,
kb, Aptr, lda, XC, 1);
blas::copy<double, double>(kb, XC, 1, Xd, 1);
}
/* update local variables */
Xd += kb;
Anq += kb;
Aptr += lda * kb;
}
/* update global variables */
rowprev = Alrow;
Alrow = MModAdd1(Alrow, nprow);
colprev = Alcol;
Alcol = MModAdd1(Alcol, npcol);
kbprev = kb;
n -= kb;
tmp1 = N - n + (kb = Mmin(n, nb));
tmp2 = Mmin(n - kb, n1);
MnumrocI(n1p, tmp2, Mmin(N, tmp1), nb, nb, myrow, 0, nprow);
/*
* Start the operations
*/
while (n > 0)
{
/*
* Broadcast (decreasing-ring) of previous solution block in previous
* process column, compute partial update of current block and send it
* to current process column.
*/
if (mycol == colprev)
{
/*
* Send previous solution block in process row below
*/
if (myrow == rowprev)
{
if (GridIsNot1xQ)
(void)HPL_send(Xdprev, kbprev, MModAdd1(myrow, nprow),
Cmsgid, Ccomm);
}
else
{
(void)HPL_recv(Xdprev, kbprev, MModSub1(myrow, nprow),
Cmsgid, Ccomm);
}
/*
* Compute partial update of previous solution block and send it to cur-
* rent column
*/
if (n1pprev > 0)
{
blas::gemv<double, double, double>(blas::Layout::ColMajor, blas::Op::NoTrans, n1pprev, kbprev,
-HPL_rone, Aprev + Anp, lda, Xdprev, 1, HPL_rone,
XC + Anp, 1);
if (GridIsNotPx1)
(void)HPL_send(XC + Anp, n1pprev, Alcol, Rmsgid, Rcomm);
}
/*
* Finish the (decreasing-ring) broadcast of the solution block in pre-
* vious process column
*/
if ((myrow != rowprev) &&
(myrow != MModSub1(rowprev, nprow)))
(void)HPL_send(Xdprev, kbprev, MModAdd1(myrow, nprow),
Cmsgid, Ccomm);
}
else if (mycol == Alcol)
{
/*
* Current column receives and accumulates partial update of previous
* solution block
*/
if (n1pprev > 0)
{
(void)HPL_recv(W, n1pprev, colprev, Rmsgid, Rcomm);
blas::axpy<double, double>(n1pprev, HPL_rone, W, 1, XC + Anp, 1);
}
}
/*
* Solve current diagonal block
*/
if ((mycol == Alcol) && (myrow == Alrow))
{
blas::trsv<double, double>(blas::Layout::ColMajor, blas::Uplo::Lower, blas::Op::NoTrans, blas::Diag::Unit,
kb, Aptr + Anp, lda, XC + Anp, 1);
blas::copy<double, double>(kb, XC + Anp, 1, Xd, 1);
}
/*
* Finish previous update
*/
if ((mycol == colprev) && ((tmp1 = Anp + n1pprev) < np))
blas::gemv<double, double, double>(blas::Layout::ColMajor, blas::Op::NoTrans, np - tmp1, kbprev, -HPL_rone,
Aprev + tmp1, lda, Xdprev, 1, HPL_rone, XC + tmp1, 1);
/*
* Save info of current step and update info for the next step
*/
if (mycol == Alcol)
{
Aprev = Aptr;
Aptr += lda * kb;
Anq += kb;
Xdprev = Xd;
Xd = XR + Anq;
}
if (myrow == Alrow)
{
Anpprev = Anp;
Anp += kb;
}
rowprev = Alrow;
colprev = Alcol;
n1pprev = n1p;
kbprev = kb;
n -= kb;
Alrow = MModAdd1(Alrow, nprow);
Alcol = MModAdd1(Alcol, npcol);
tmp1 = N - n + (kb = Mmin(n, nb));
tmp2 = Mmin(n - kb, n1);
MnumrocI(n1p, tmp2, Mmin(N, tmp1), nb, nb, myrow, 0, nprow);
Rmsgid = (Rmsgid + 2 > MSGID_END_PTRSV ? MSGID_BEGIN_PTRSV : Rmsgid + 2);
Cmsgid = (Cmsgid + 2 > MSGID_END_PTRSV ? MSGID_BEGIN_PTRSV + 1 : Cmsgid + 2);
}
/*
* Replicate last solution block
*/
if (mycol == colprev)
(void)HPL_broadcast((void *)Xdprev, kbprev, HPL_DOUBLE, rowprev,
Ccomm);
if (Wfr)
free(W);
#ifdef HPL_DETAILED_TIMING
HPL_ptimer(HPL_TIMING_PTRSV);
#endif
/*
* End of HPL_pdtrsv
*/
}
// https://github.com/schuangs/hpl-ai-with-IR/blob/master/src/pir/HPL_pgmres.c
/*
* by Junkang Huang, Dec. 2020
*
* based on the implementation of parallel GMRES:
* Parallelization Of The GMRES ---by Morgan Gรถrtz, Lund University.
*
* and the pioneer work implementing Householder Transformations into GMRES:
* Implementation Of The GMRES Method Using Householder Transformations Method
* ---by Homer F. Walker, 1988
*/
static double sign(double x)
{
return x < 0 ? -1 : 1;
}
/*
* givens_rotation():
*
* 1. perform:
* v <- Jk-1Jk-2...J1J0v
*
* 2. solve for Jk:
* s.t. Jkv = (v0,v1,...,vk-1,somevalue,0,...,0)
*
* 3. perform:
* v <- Jkv
* w <- Jkw
*
* 4. append v to R, that is:
* R = [R, v]
*/
static void givens_rotations(
HPL_T_grid *GRID, /* processes grid information */
HPL_T_pmat *A, /* local A */
double *v, /* kth column of H */
double *w, /* rhs */
double *R, /* R matrix */
double *sinus, /* sin(theta) */
double *cosus, /* cos(theta) */
const int k, /* offset */
const int MM /* restart size */
)
{
/* local variables */
int pi, pi1, ii, ii1, i;
double tmp;
/* update v */
for (i = 0; i < k; ++i)
{
/* calculate the process row which possess v[i] and v[i+1] */
HPL_indxg2lp(&ii, &pi, i, A->nb, A->nb, 0, GRID->nprow);
HPL_indxg2lp(&ii1, &pi1, i + 1, A->nb, A->nb, 0, GRID->nprow);
if (pi == pi1)
{ /* if two elememts in one process row, just perform local update */
if (GRID->myrow == pi)
{
/* update v */
tmp = cosus[i] * v[ii] - sinus[i] * v[ii1];
v[ii1] = sinus[i] * v[ii] + cosus[i] * v[ii1];
v[ii] = tmp;
}
}
else
{ /* if two elememts in different process rows, some communication required */
if (GRID->myrow == pi)
{
/* update v */
HPL_send(&v[ii], 1, pi1, 0, GRID->col_comm);
HPL_recv(&tmp, 1, pi1, 0, GRID->col_comm);
v[ii] = cosus[i] * v[ii] - sinus[i] * tmp;
}
if (GRID->myrow == pi1)
{
/* update v */
HPL_recv(&tmp, 1, pi, 0, GRID->col_comm);
HPL_send(&v[ii1], 1, pi, 0, GRID->col_comm);
v[ii1] = sinus[i] * tmp + cosus[i] * v[ii1];
}
}
}
/* solve for Jk */
/* calculate the process row which possess v[k] and v[k+1] */
HPL_indxg2lp(&ii, &pi, k, A->nb, A->nb, 0, GRID->nprow);
HPL_indxg2lp(&ii1, &pi1, k + 1, A->nb, A->nb, 0, GRID->nprow);
if (pi == pi1)
{ /* if two elements in the same process row */
if (GRID->myrow == pi)
{
if (v[ii] * v[ii] + v[ii1] * v[ii1] == 0)
{
printf("Error: divided by zero in givens_rotations()\n");
return;
}
/* calculate sin and cos for Jk */
cosus[k] = v[ii] / sqrt(v[ii] * v[ii] + v[ii1] * v[ii1]);
sinus[k] = -v[ii1] / sqrt(v[ii] * v[ii] + v[ii1] * v[ii1]);
/* update v */
v[ii] = cosus[k] * v[ii] - sinus[k] * v[ii1];
v[ii1] = 0;
}
}
else
{ /* if two elements not in the same process row */
/* calculate sin and cos for Jk */
if (GRID->myrow == pi)
{
HPL_recv(&tmp, 1, pi1, 1, GRID->col_comm);
if (v[ii] * v[ii] + tmp * tmp == 0)
{
printf("Error: divided by zero in givens_rotations()\n");
return;
}
cosus[k] = v[ii] / sqrt(v[ii] * v[ii] + tmp * tmp);
sinus[k] = -tmp / sqrt(v[ii] * v[ii] + tmp * tmp);
v[ii] = cosus[k] * v[ii] - sinus[k] * tmp;
}
if (GRID->myrow == pi1)
{
HPL_send(&v[ii1], 1, pi, 1, GRID->col_comm);
v[ii1] = 0;
}
}
/* broadcast sin and cos */
HPL_broadcast(&cosus[k], 1, HPL_DOUBLE, pi, GRID->col_comm);
HPL_broadcast(&sinus[k], 1, HPL_DOUBLE, pi, GRID->col_comm);
/* update w */
tmp = cosus[k] * w[k] - sinus[k] * w[k + 1];
w[k + 1] = sinus[k] * w[k] + cosus[k] * w[k + 1];
w[k] = tmp;
/* update R */
for (i = 0; i < k + 1; ++i)
{
HPL_indxg2lp(&ii, &pi, i, A->nb, A->nb, 0, GRID->nprow);
if (pi == 0)
{ /* if v[i] already in process row 0 */
if (GRID->myrow == 0)
{
/* just perform local R update on process row 0 */
*Mptr(R, i, k, MM) = v[ii];
}
}
else
{ /* if v[i] is in another process row */
if (GRID->myrow == pi)
{
/* send v[i] to process row 0, i+3 is just a tag
in case of message mismatch */
HPL_send(&v[ii], 1, 0, i + 3, GRID->col_comm);
}
if (GRID->myrow == 0)
{
/* process row 0 receive v[i], and update local R */
HPL_recv(Mptr(R, i, k, MM), 1, pi, i + 3, GRID->col_comm);
}
}
}
/* broadcast R in process row 0 to all */
HPL_broadcast(Mptr(R, 0, k, MM), k + 1, HPL_DOUBLE, 0, GRID->col_comm);
/* end of givens_rotations() */
}
/*
* generateHouseholder():
*
* solve for Householder vector u:
* s.t. Pkx = (I-2uuT)x = [x0,x1,..,xk-1,alpha,0,..0], alpha != 0
*/
static void generateHouseholder(
HPL_T_grid *GRID, /* processes grid information */
HPL_T_pmat *A, /* local A */
const double *x, /* local object vector pointer */
double *u, /* local result Householder Vector */
const int k, /* order of the Householder */
double *alpha /* result variable */
)
{
/* local variables */
const int myrow = GRID->myrow;
int i, ig, mp = A->mp, pi;
double r = 0;
for (i = 0; i < mp; ++i)
{
ig = HPL_indxl2g(i, A->nb, A->nb, GRID->myrow, 0, GRID->nprow);
if (ig >= k)
{
/* load u[k:] with x[k:] for further operation */
u[i] = x[i];
/* calculate (xk*xk) + (xk+1*xk+1) + ...*/
r += x[i] * x[i];
}
else
{
/* u[:k] should be 0 */
u[i] = 0;
}
}
HPL_indxg2lp(&i, &pi, k, A->nb, A->nb, 0, GRID->nprow);
/* Get the total r on process row which possess u[k] */
HPL_reduce(&r, 1, HPL_DOUBLE, HPL_sum, pi, GRID->col_comm);
if (myrow == pi)
{
/* perform computation on process pi */
/* calculate alpha and r */
*alpha = -sign(x[i]) * sqrt(r);
r = sqrt(0.5 * ((*alpha) * (*alpha) - x[i] * (*alpha)));
/* compute the first nonzero value of the transformation vector u */
u[i] = x[i] - *alpha;
}
/* send r and alpha to all process */
HPL_broadcast(&r, 1, HPL_DOUBLE, pi, GRID->col_comm);
HPL_broadcast(alpha, 1, HPL_DOUBLE, pi, GRID->col_comm);
/* apply 1/2r on u for all processes */
for (i = 0; i < mp; ++i)
{
u[i] /= 2. * r;
}
/* end of generateHouseholder() */
}
/*
* applyHouseholder()
*
* perform:
* y = Pkx = (I-2uuT)x = x - 2u(x, u)
*/
static void applyHouseholder(
HPL_T_grid *GRID, /* processes grid information */
HPL_T_pmat *A, /* local A */
const double *x, /* local object vector pointer */
const double *u, /* local result Householder Vector */
const int k, /* order of the Householder */
double *y /* target vector */
)
{
/* local variables */
double segsum = 0;
int i, ig;
/* calculate (x, u) */
for (i = 0; i < A->mp; ++i)
{
ig = HPL_indxl2g(i, A->nb, A->nb, GRID->myrow, 0, GRID->nprow);
if (ig >= k)
{
segsum += u[i] * x[i];
}
}
/* sum (x, u) */
HPL_all_reduce(&segsum, 1, HPL_DOUBLE, HPL_sum, GRID->col_comm);
/* calculate y = x - 2u(x, u) */
for (i = 0; i < A->mp; ++i)
{
ig = HPL_indxl2g(i, A->nb, A->nb, GRID->myrow, 0, GRID->nprow);
if (ig >= k)
{
y[i] = x[i] - 2 * segsum * u[i];
}
else
{
y[i] = x[i];
}
}
/* end of applyHouseholder() */
}
/*
* redB2X()
*
* when performing A*v, if v is distributed along different rows like b, some redistributions
* needed to perform to make v distributed along different columns like x.
*/
static void redB2X(
HPL_T_grid *GRID,
HPL_T_pmat *A, /* local A */
const double *v, /* the vector to be redistributed, size: mp */
double *vc /* the target space, size: nq */
)
{
int ig, i, j, jp;
for (i = 0; i < A->nq - 1; ++i)
{
/* find the global index of local vc[i] */
ig = HPL_indxl2g(i, A->nb, A->nb, GRID->mycol, 0, GRID->npcol);
/* find the process row and local index of the element vc[i] stored in v */
HPL_indxg2lp(&j, &jp, ig, A->nb, A->nb, 0, GRID->nprow);
/* there is one and only one process who contains both vc[i] and v[j] in
this process column */
if (GRID->myrow == jp)
{
/* perform local replication */
vc[i] = v[j];
}
/* broadcast the correct vc to other processes in the column */
HPL_broadcast(&vc[i], 1, HPL_DOUBLE, jp, GRID->col_comm);
}
}
/*
* redX2B()
*
* v is distributed along different columns like x, some redistributions
* needed to perform to make v distributed along different columns like b.
*/
static void redX2B(
HPL_T_grid *GRID,
HPL_T_pmat *A, /* local A */
const double *v, /* the vector to be redistributed, size: nq */
double *vc /* the target space, size: mp */
)
{
int ig, i, j, jp;
for (i = 0; i < A->mp; ++i)
{
/* find the global index of local vc[i] */
ig = HPL_indxl2g(i, A->nb, A->nb, GRID->myrow, 0, GRID->nprow);
/* find the process column and local index of the element vc[i] stored in v */
HPL_indxg2lp(&j, &jp, ig, A->nb, A->nb, 0, GRID->npcol);
/* there is one and only one process who contains both vc[i] and v[j] in */
if (GRID->mycol == jp)
{
/* perform local replication */
vc[i] = v[j];
}
/* broadcast the correct vc to other processes in the rows */
HPL_broadcast(&vc[i], 1, HPL_DOUBLE, jp, GRID->row_comm);
}
}
/*
* HPL_pgmres():
*
*/
static int HPL_pgmres(
HPL_T_grid *GRID,
HPL_T_pmat *A, /* local A */
HPL_T_pmat *factors, /* local LU factors */
const double *b, /* local rhs */
double *x, /* local solution vector */
double TOL, /* tolerance of residual */
const int MM, /* restart size */
const int MAXIT /* maximum # of total iteration */
)
{
int prec = 1; /* whether or not to precondition, for debugging */
/* local variables */
int i, j, k = 0, start, ready = 0, index, pindex, tarcol;
double norm, currenterror, tmp;
int mp = A->mp, nq = A->nq - 1;
/* bptr point to the rhs area of factors */
double *bptr = Mptr(factors->A, 0, nq, factors->ld);
/* distributed storages: each process row stores a part of data */
double *v = (double *)malloc(mp * sizeof(double));
double *u = (double *)malloc(mp * sizeof(double));
double *xt = (double *)malloc(nq * sizeof(double));
double *H = (double *)malloc(mp * (MM + 1) * sizeof(double));
double *rhs = (double *)malloc(mp * sizeof(double));
/* replicated storage: all processes store the whole data */
double *cosus = (double *)malloc((MM + 1) * sizeof(double));
double *sinus = (double *)malloc((MM + 1) * sizeof(double));
double *w = (double *)malloc((MM + 1) * sizeof(double));
double *R = (double *)malloc(MM * (MM + 1) * sizeof(double));
/* precondition b into rhs, that is: rhs = U-1L-1b */
tarcol = HPL_indxg2p(factors->n, factors->nb, factors->nb, 0, GRID->npcol);
if (prec)
{
/* solve Lx = b, then x = L-1b, x is returned at factors->X, which is replicated in process rows */
if (GRID->mycol == tarcol)
{
memcpy(bptr, b, mp * sizeof(double));
}
HPL_pLdtrsv(GRID, factors);
/* redistribute x into column-distributing pattern for next pdtrsv */
redX2B(GRID, factors, factors->X, rhs);
/* solve Ux = b, then x = U-1b */
if (GRID->mycol == tarcol)
{
memcpy(bptr, rhs, mp * sizeof(double));
}
HPL_pdtrsv(GRID, factors);
redX2B(GRID, factors, factors->X, rhs);
}
else
{
memcpy(rhs, b, mp * sizeof(double));
}
/* no initial guess so the first residual r0 is just b */
memcpy(v, rhs, mp * sizeof(double));
norm = 0;
/* calculate the norm of r0 */
for (i = 0; i < mp; ++i)
{
norm += v[i] * v[i];
}
HPL_all_reduce(&norm, 1, HPL_DOUBLE, HPL_sum, GRID->col_comm);
norm = sqrt(norm);
/* store the current error */
currenterror = norm;
/* creating w */
memset(w, 0, (MM + 1) * sizeof(double));
/* generate and apply the first Housholder transformation
Householder vector stored in u */
generateHouseholder(GRID, A, v, u, 0, &w[0]);
/* stop if approximation is good enough, zero solution returned. */
if (currenterror < TOL)
{
ready = 1;
}
/* ------------------------------------------------- */
/* Restart Iterations */
/* ------------------------------------------------- */
for (start = 0; (start < MAXIT) && !ready; ++start)
{
/* do the same as above to start the method */
if (start)
{
/* there is initial guess stored in x here from last iteration */
/* calculate v = Ax */
blas::gemv<double, double, double>(blas::Layout::ColMajor, blas::Op::NoTrans, mp, nq, HPL_rone,
A->A, A->ld, x, 1, 0, v, 1);
HPL_all_reduce(v, mp, HPL_DOUBLE, HPL_sum, GRID->row_comm);
/* preconditioning A */
if (prec)
{
if (GRID->mycol == tarcol)
{
memcpy(bptr, v, mp * sizeof(double));
}
HPL_pLdtrsv(GRID, factors);
redX2B(GRID, factors, factors->X, v);
if (GRID->mycol == tarcol)
{
memcpy(bptr, v, mp * sizeof(double));
}
HPL_pdtrsv(GRID, factors);
redX2B(GRID, factors, factors->X, v);
}
/* v = rhs - v = rhs - Ax */
for (i = 0; i < mp; ++i)
{
v[i] = rhs[i] - v[i];
}
/* generate P0v = [alpha,0,..,0] */
memset(w, 0, (MM + 1) * sizeof(double));
generateHouseholder(GRID, A, v, u, 0, &w[0]);
}
/* ------------------------------------------------ */
/* Householder transformations and Givens rotations */
/* ------------------------------------------------ */
for (k = 0; k < MM; ++k)
{
if (k >= A->n - 1)
{
--k;
break;
}
/* store the current trasformation vector u in H */
memcpy(Mptr(H, 0, k, mp), u, mp * sizeof(double));
/* load ek into v */
memset(v, 0, mp * sizeof(double));
HPL_indxg2lp(&index, &pindex, k, A->nb, A->nb, 0, GRID->nprow);
if (GRID->myrow == pindex)
{
v[index] = 1;
}
/* apply the last k + 1 Householder transformations in reverse order:
that is : v = P0P1..Pkv */
for (i = k; i >= 0; --i)
{
applyHouseholder(GRID, A, v, Mptr(H, 0, i, mp), i, v);
}
/* calculate v = AP0P1..Pkv */
redB2X(GRID, A, v, xt);
blas::gemv<double, double, double>(blas::Layout::ColMajor, blas::Op::NoTrans, mp, nq, HPL_rone,
A->A, A->ld, xt, 1, 0, v, 1);
HPL_all_reduce(v, mp, HPL_DOUBLE, HPL_sum, GRID->row_comm);
/* preconditioning A */
if (prec)
{
if (GRID->mycol == tarcol)
{
memcpy(bptr, v, mp * sizeof(double));
}
HPL_pLdtrsv(GRID, factors);
redX2B(GRID, factors, factors->X, v);
if (GRID->mycol == tarcol)
{
memcpy(bptr, v, mp * sizeof(double));
}
HPL_pdtrsv(GRID, factors);
redX2B(GRID, factors, factors->X, v);
}
/* apply last k + 1 Householder transformations:
that is : v = PkPk-1...P0AP0P1...Pkek*/
for (i = 0; i <= k; i++)
{
applyHouseholder(GRID, A, v, Mptr(H, 0, i, mp), i, v);
}
/* generate and apply the last transformation */
generateHouseholder(GRID, A, v, u, k + 1, &tmp);
/* apply this transformation: v<-Pk+1v */
HPL_indxg2lp(&index, &pindex, k + 1, A->nb, A->nb, 0, GRID->nprow);
if (GRID->myrow == pindex)
{
v[index] = tmp;
}
for (i = 0; i < mp; ++i)
{
index = HPL_indxl2g(i, A->nb, A->nb, GRID->myrow, 0, GRID->nprow);
if (index > k + 1)
{
v[i] = 0;
}
}
/* now v is the kth column of Hm. Apply Givens rotations on v */
tmp = 0;
/* generate and apply Givens rotations on v and w */
/* sinus and cosus store the previous rotation parameters */
givens_rotations(GRID, A, v, w, R, sinus, cosus, k, MM);
/* tmp stored the last element of w, which is the current residual */
tmp = w[k + 1];
/* store the current error */
currenterror = fabs(tmp);
// HPL_barrier(GRID->all_comm);
// if (GRID->iam == 0)
// printf("Err: %.16f, start = %d\n", currenterror, start);fflush(stdout);
// HPL_barrier(GRID->all_comm);
/* check if the solution is good enough */
if (currenterror < TOL)
{
ready = 1;
break;
}
}
/* ------------------------------------ */
/* Solve for new solution x */
/* ------------------------------------ */
if (k == MM)
{
--k;
}
// if (GRID->iam == 0)
// {
// printf("Before:\n");
// printf("w = :\n");
// print_vector(w, MM, 1);
// printf("R = :\n");
// print_matrix(R, MM, MM, MM, 1);
// }
/* solve Ry = w, R is upper-tri, and w will be overwritten by solution y */
blas::trsv<double, double>(blas::Layout::ColMajor, blas::Uplo::Upper, blas::Op::NoTrans, blas::Diag::NonUnit, k + 1, R, MM, w, 1);
// if (GRID->iam == 0)
// {
// printf("After:\n");
// printf("w = :\n");
// print_vector(w, MM, 1);
// }
/* calculate the new solution */
for (i = 0; i <= k; ++i)
{
/* load v with unit vector, with v[i] = 1 */
memset(v, 0, mp * sizeof(double));
HPL_indxg2lp(&index, &pindex, i, A->nb, A->nb, 0, GRID->nprow);
if (GRID->myrow == pindex)
{
v[index] = 1;
}
/* apply last i + 1 householder transformations in reverse order */
for (j = i; j >= 0; --j)
{
applyHouseholder(GRID, A, v, Mptr(H, 0, j, mp), j, v);
}
redB2X(GRID, A, v, xt);
/* update x: perform x += yi*vi */
for (j = 0; j < nq; ++j)
{
x[j] += xt[j] * w[i];
}
}
// /* there is initial guess stored in x here from last iteration */
// /* calculate v = Ax */
// blas::gemv<double, double, double>( blas::Layout::ColMajor, blas::Op::NoTrans, mp, nq, HPL_rone,
// A->A, A->ld, x, 1, 0, v, 1 );
// HPL_all_reduce(v, mp, HPL_DOUBLE, HPL_sum, GRID->row_comm);
// /* preconditioning A */
// if (prec)
// {
// if (GRID->mycol == tarcol)
// {
// memcpy(bptr, v, mp*sizeof(double));
// }
// HPL_pLdtrsv(GRID, factors);
// redX2B(GRID, factors, factors->X, v);
// if (GRID->mycol == tarcol)
// {
// memcpy(bptr, v, mp*sizeof(double));
// }
// HPL_pdtrsv(GRID, factors);
// redX2B(GRID, factors, factors->X, v);
// }
// norm = 0;
// /* v = rhs - v = rhs - Ax */
// for (i = 0; i < mp; ++i)
// {
// v[i] = rhs[i] - v[i];
// norm += v[i]*v[i];
// }
// HPL_all_reduce(&norm, 1, HPL_DOUBLE, HPL_sum, GRID->col_comm);
// norm = sqrt(norm);
// HPL_barrier(GRID->all_comm);
// if (GRID->iam == 0)
// printf("currenterror = %.16f, norm = %.16f\n", currenterror, norm);
// fflush(stdout);
// HPL_barrier(GRID->all_comm);
/* if the error is small enough, stop.
otherwise another iteration will be initiated. */
if (currenterror < TOL)
{
ready = 1;
}
// printf("Restart!\n");
// fflush(stdout);
}
// printf("Final! From process %d\n", GRID->iam);
// fflush(stdout);
/* check if we have done maximum number of starts */
if (start > MAXIT)
{
start = MAXIT;
}
if (v)
free(v);
if (u)
free(u);
if (H)
free(H);
if (rhs)
free(rhs);
if (cosus)
free(cosus);
if (sinus)
free(sinus);
if (w)
free(w);
if (R)
free(R);
if (xt)
free(xt);
/* return total number of iterations performed */
return (start * MM + k + 1);
/* end of HPL_pgmres() */
}
// https://github.com/schuangs/hpl-ai-with-IR/blob/master/src/pir/HPL_pir.c
/*
* By Junkang Huang, August, 2020
*
* based on the paper:
* A New Analysis Of Iterative Refinement And Its Application To
* Accurate Solution Of Ill Conditioned Sparse Linear Systems
* ---by Carson, Erin & Higham, Nicholas J., 2017
*/
static void HPL_pir(
HPL_T_grid *GRID,
HPLAI_T_palg *ALGO,
HPL_T_pmat *A,
HPL_T_pmat *factors,
double PRE, /* solution tolerance */
int IR,
int MM, /* restart size for GMRES */
int MAXIT, /* maximum number of GMRES iteration */
double TOL)
{
/*
* Purpose
* =======
*
* HPL_pir performs iterative refinement procesure to enhance the accur-
* acy of the solution of linear system obtained by LU factorization.
* Parallel GMRES algorithm is used as the inner solver to solve the
* inner correct equation Ad = r.
*
* Arguments
* =========
*
* GRID (local input) HPL_T_grid *
* On entry, GRID points to the data structure containing the
* process grid information.
*
* ALGO (global input) HPL_T_palg *
* On entry, ALGO points to the data structure containing the
* algorithmic parameters to be used for this test.
*
* A (local input/output) HPL_T_pmat *
* On entry, A points to the data structure containing the local
* array information.
* FA (local input/output) HPL_T_pmat *
* On entry, A points to the data structure containing the local
* array information. It serves as lower precision version if A.
*
* ---------------------------------------------------------------------
*/
/*
* .. Local Variables ..
*/
int i, j;
int mp, nq, n, nb, npcol, nprow, myrow, mycol, tarcol;
double *Bptr, *res, *d;
double norm;
/* ..
* .. Executable Statements ..
*/
mp = A->mp;
nq = A->nq - 1;
n = A->n;
nb = A->nb;
npcol = GRID->npcol;
nprow = GRID->nprow;
mycol = GRID->mycol;
myrow = GRID->myrow;
/* point to local rhs area */
Bptr = Mptr(A->A, 0, nq, A->ld);
/*
* allocate space for factors, which contains LU factors of double
* precision, which is in fact of lower precision, just stored in double.
*/
/*
* Convert initial solution ( which is obtained through lower precision
* LU factorization) into higher precision
*/
/*
for (i = 0; i < nq; ++i)
{
*(A->X + i) = (double)(*(factors->X + i));
*(factors->X + i) = 0;
}
*/
blas::copy<double, double>(nq, factors->X, 1, A->X, 1);
//ๅพ
ๆฃๆฅ่ฝไธ่ฝๆนๆไธ้ข่ฟไธช
/*
* allocate space for residual vector, correction vectors.
*/
res = (double *)malloc(mp * sizeof(double));
d = (double *)malloc(nq * sizeof(double));
/*
* tarcol is the process column containing b
*/
tarcol = HPL_indxg2p(n, nb, nb, 0, npcol);
/*
* Iterative Refinement
*/
for (i = 0; i < IR; ++i)
{
/*
if (GRID->iam == 0)
printf("IR Loop %d\n", i);
*/
/* Calculate residual in double precision */
if (mycol == tarcol)
{
memcpy(res, Bptr, mp * sizeof(double));
blas::gemv<double, double, double>(blas::Layout::ColMajor, blas::Op::NoTrans, mp, nq, -HPL_rone,
A->A, A->ld, A->X, 1, HPL_rone, res, 1);
}
else if (nq > 0)
{
memset(res, 0, mp * sizeof(double));
blas::gemv<double, double, double>(blas::Layout::ColMajor, blas::Op::NoTrans, mp, nq, -HPL_rone,
A->A, A->ld, A->X, 1, HPL_rzero, res, 1);
}
else
{
for (j = 0; j < mp; ++j)
res[j] = HPL_rzero;
}
if (mp > 0)
HPL_all_reduce(res, mp, HPL_DOUBLE, HPL_sum, GRID->row_comm);
norm = 0;
for (j = 0; j < mp; ++j)
{
norm += res[j] * res[j];
}
HPL_all_reduce(&norm, 1, HPL_DOUBLE, HPL_sum, GRID->col_comm);
norm = sqrt(norm);
if (norm < PRE)
break;
/*
* Solve correction equation using preconditioned GMRES method in mix
* precision.
*/
memset(d, 0, nq * sizeof(double));
HPL_pgmres(GRID, A, factors, res, d, TOL, MM, MAXIT);
/*
* update X with d
*/
blas::axpy<double, double>(nq, 1, d, 1, A->X, 1);
}
/* free dynamic memories */
if (d)
free(d);
if (res)
free(res);
/*
* End of HPL_pir
*/
}
template <typename T1, typename T2>
static void HPLAI_pmat_cpy(
T1 *DST,
const T2 *SRC)
{
DST->n = SRC->n;
DST->nb = SRC->nb;
DST->ld = SRC->ld;
DST->mp = SRC->mp;
DST->nq = SRC->nq;
DST->info = SRC->info;
int64_t len = SRC->nq * (int64_t)SRC->ld;
#if !defined(BLAS_ILP64)
int64_t max_len = std::numeric_limits<int>::max();
if (len > max_len)
{
int64_t offset = len % max_len;
blas::copy(offset, SRC->A, 1, DST->A, 1);
for (int64_t i = offset; i + max_len <= len; i += max_len)
blas::copy(max_len, SRC->A + i, 1, DST->A + i, 1);
}
else
#endif
blas::copy(len, SRC->A, 1, DST->A, 1);
blas::copy(SRC->nq, SRC->X, 1, DST->X, 1);
}
template <typename T1, typename T2, typename T3>
static void HPLAI_pmat_new(
T1 *DST,
const T2 *SRC,
HPLAI_T_palg *ALGO,
void **vptr,
T3 *DSTA)
{
*vptr = (void *)malloc(
((size_t)(ALGO->align) + (size_t)(SRC->ld + 1) * (size_t)(SRC->nq)) * sizeof(DST->A[0]));
if (*vptr == NULL)
HPLAI_pabort(__LINE__, "HPLAI_pmat_new", "Memory allocation failed");
#ifdef HPL_CALL_VSIPL
DST->block = vsip_blockbind_d((vsip_scalar_d *)(SRC->A),
(vsip_length)(SRC->ld * SRC->nq),
VSIP_MEM_NONE);
#endif
DST->A = (T3 *)HPL_PTR((*vptr), ((size_t)(ALGO->align) * sizeof(DST->A[0])));
DST->X = Mptr(DST->A, 0, SRC->nq, SRC->ld);
HPLAI_pmat_cpy(DST, SRC);
}
#ifdef __cplusplus
extern "C"
{
#endif
#ifdef STDC_HEADERS
void HPLAI_pdgesv(
HPL_T_grid *GRID,
HPLAI_T_palg *ALGO,
HPL_T_pmat *A)
#else
void HPLAI_pdgesv(GRID, ALGO, A)
HPL_T_grid *GRID;
HPL_T_palg *ALGO;
HPLAI_T_pmat *A;
#endif
{
void *vptr_FA, *vptr_factors;
HPLAI_T_pmat FA;
HPL_T_pmat factors;
HPLAI_pmat_new(&FA, A, ALGO, &vptr_FA, FA.A);
HPLAI_pagesv(GRID, ALGO, &FA);
#ifdef HPLAI_PMAT_REGEN
HPLAI_pmat_cpy(A, &FA);
if (vptr_FA)
free(vptr_FA);
HPLAI_pmat_new(&factors, A, ALGO, &vptr_factors, factors.A);
HPLAI_pdmatgen(GRID, A->n, A->n + 1, A->nb, A->A, A->ld, HPL_ISEED);
#else
HPLAI_pmat_new(&factors, &FA, ALGO, &vptr_factors, factors.A);
if (vptr_FA)
free(vptr_FA);
#endif
#ifdef HPLAI_NO_IR
HPLAI_pmat_cpy(A, &factors);
#else
HPL_pir(GRID, ALGO, A, &factors, 1e-14, 1, 50, 1, DBL_EPSILON / 2.0 / ((double)A->n / 4.0));
#endif
if (vptr_factors)
free(vptr_factors);
}
#ifdef __cplusplus
}
#endif
| 30.657534 | 138 | 0.494067 | [
"object",
"vector"
] |
b82d68be3af3befd5a6066de64338ed0385c0788 | 10,103 | cpp | C++ | ProjetEquipe2/ProjetEquipe2/Boss.cpp | dev1ous/Great-Steamrogue | 2519632f1af2d49ae68559afb615b8157416672d | [
"Apache-2.0"
] | null | null | null | ProjetEquipe2/ProjetEquipe2/Boss.cpp | dev1ous/Great-Steamrogue | 2519632f1af2d49ae68559afb615b8157416672d | [
"Apache-2.0"
] | null | null | null | ProjetEquipe2/ProjetEquipe2/Boss.cpp | dev1ous/Great-Steamrogue | 2519632f1af2d49ae68559afb615b8157416672d | [
"Apache-2.0"
] | null | null | null | #include "Boss.h"
void Boss::InitPlayerDetection()
{
this->playerDetection.setSize(sf::Vector2f(
data::WIDTH * 2,
data::HEIGHT
));
/*this->playerDetection.setFillColor(sf::Color(sf::Color::Transparent));
this->playerDetection.setOutlineColor(sf::Color(sf::Color::Yellow));
this->playerDetection.setOutlineThickness(-1.f);*/
this->playerDetection.setOrigin(
this->playerDetection.getGlobalBounds().width / 2,
this->playerDetection.getGlobalBounds().height / 2);
this->playerDetection.setPosition(sf::Vector2f(
this->m_shape.getPosition()
));
}
void Boss::InitAnim()
{
this->anim.emplace("IDLE", Animator(sf::IntRect(0, 0, 186, 256), 4, .1f));
this->anim.emplace("MOVE", Animator(sf::IntRect(0, 256, 186, 256), 3, .1f));
this->anim.emplace("PRE_ATTACK", Animator(sf::IntRect(0, 513, 240, 272), 3, .1f));
this->anim.emplace("ATTACK", Animator(sf::IntRect(0, 785, 702, 472), 3, .1f));
this->anim.emplace("DEATH", Animator(sf::IntRect(0, 1443, 1300, 1300), 8, .1f));
this->anim.emplace("ARM_IDLE", Animator(sf::IntRect(0, 0, 186, 256), 4, .1f));
this->anim.emplace("ARM_MOVE", Animator(sf::IntRect(0, 256, 186, 256), 1, .1f));
}
void Boss::InitArm()
{
this->arm.setTexture(&gm::CacheSystem::AddAnyRessources<sf::Texture>("boss_bras"));
this->arm.setSize(sf::Vector2f(
this->arm.getTextureRect().width,
this->arm.getTextureRect().height
));
this->arm.setOrigin(sf::Vector2f(
this->arm.getTextureRect().width / 2,
this->arm.getTextureRect().height / 2
));
this->arm.setPosition(this->m_position);
}
void Boss::InitWeapon()
{
this->canon = std::make_unique<Canon>("boss_arme", m_position, 2);
}
Boss::Boss(float _posX, float _posY, Player& _player)
:AI(_posX, _posY, _player), timeBeetwenShoot(0.f), attackTimer(0.f), gonnaExplode(false), attack(false), onePass(false), isShooting(false), moveRight(false), isPatrolling(true)
{
this->hp = 1.f;
this->movementSpeed = 300.f;
this->timeExplode = 0.f;
this->InitShape("Boss", _posX, _posY);
m_shape.setTextureRect(sf::IntRect(0, 0, 186, 256));
m_shape.setOrigin(93, 128);
m_shape.setPosition(_posX, _posY);
this->InitComponent();
this->InitAnim();
this->InitGroundDetection();
this->InitPlayerDetection();
this->InitArm();
this->InitWeapon();
}
void Boss::FollowPlayer(sf::Image& _collid, const float& _dt)
{
if (DetectPlayer(this->playerDetection))
{
if (Check_Colid(_collid, this->groundDetection[2].getPosition()) ||
Check_Colid(_collid, this->groundDetection[3].getPosition()))
{
this->m_movementComponent->StopVelocityX();
return;
}
this->isPatrolling = false;
if (Get_NextPosDown(_collid, _dt) &&
abs(func::distance(this->player->GetPos(), this->m_shape.getPosition())) <= 200.f)
{
attackTimer += _dt;
this->gonnaExplode = true;
//Attack
if (this->attackTimer >= 1.f)
{
this->attack = true;
this->gonnaExplode = false;
}
}
else if (Get_NextPosDown(_collid, _dt) &&
abs(func::distance(this->player->GetPos(), this->m_shape.getPosition())) > 200.f)
{
if (sqrt(pow((this->player->GetPos().x - this->m_position.x), 2) + pow((this->player->GetPos().y - this->m_position.y), 2)) >= 500.f) {
this->Shoot(_dt);
return;
}
this->attackTimer = 0;
this->attack = false;
this->gonnaExplode = false;
this->direction = this->player->GetPos() - this->m_shape.getPosition();
this->normailizeDir.x = this->direction.x / sqrt(pow(this->direction.x, 2) + pow(this->direction.y, 2));
if (Get_NextPosDown(_collid, _dt))
this->normailizeDir.y = 0;
else
this->normailizeDir.y += 1.f * _dt;
this->m_movementComponent->SetVelocity(this->normailizeDir * this->movementSpeed);
}
}
else
this->Patrol(_collid, _dt);
}
void Boss::Patrol(sf::Image& _collid, const float& _dt)
{
this->attackTimer = 0.f;
this->isPatrolling = true;
this->gonnaExplode = false;
this->attack = false;
if (Check_Colid(_collid, this->groundDetection[2].getPosition()))
this->moveRight = false;
else if (Check_Colid(_collid, this->groundDetection[3].getPosition()))
this->moveRight = true;
if (Check_Colid(_collid, this->groundDetection[0].getPosition()) &&
!Check_Colid(_collid, this->groundDetection[1].getPosition()))
this->moveRight = true;
else if (Check_Colid(_collid, this->groundDetection[1].getPosition()) &&
!Check_Colid(_collid, this->groundDetection[0].getPosition()))
this->moveRight = false;
if (this->moveRight)
this->direction = this->groundDetection[0].getPosition() - this->m_shape.getPosition();
else
this->direction = this->groundDetection[1].getPosition() - this->m_shape.getPosition();
this->normailizeDir.x = this->direction.x / sqrt(pow(this->direction.x, 2) + pow(this->direction.y, 2));
if (Get_NextPosDown(_collid, _dt))
this->normailizeDir.y = 0;
else
this->normailizeDir.y += 1.f * _dt;
this->m_movementComponent->SetVelocity(this->normailizeDir * this->movementSpeed);
}
void Boss::Shoot(const float& _dt)
{
this->gonnaExplode = false;
this->attack = false;
this->isShooting = true;
if (!this->isDead() &&
this->timeBeetwenShoot >= 1.5f &&
this->bullets.size() <= 5)
{
if (this->m_shape.getPosition().x >= this->player->GetPos().x)
{
this->bullets.push_back(std::make_shared<Bullet>(sf::Vector2f(
this->canon->GetPos().x,
this->canon->GetPos().y
),
this->player->GetShape(), this->canon->GetAngle()));
}
else
{
this->bullets.push_back(std::make_shared<Bullet>(sf::Vector2f(
this->canon->GetPos().x,
this->canon->GetPos().y
),
this->player->GetShape(), this->canon->GetAngle() - 180.f));
}
this->timeBeetwenShoot = 0;
}
}
void Boss::deleteBullets(sf::Image& _collid)
{
int i = 0;
for (auto& b : bullets)
{
bool hit = b->BulletCol(this->player);
if (hit)
player->Life = false;
if (hit ||
Check_Colid(_collid, b->GetPos()))
{
if (i != 0)
i--;
bullets.erase(bullets.begin() + i);
break;
}
i++;
}
}
void Boss::Update(sf::Image& _collid, Shield* shield, std::vector<BulletPlayer>* bullet, const float& _dt)
{
if (!shield->getLife())
this->timerDamage += _dt;
else
this->timerDamage = 0;
this->timeBeetwenShoot += _dt;
AI::Update(_collid, shield, bullet, _dt);
this->FollowPlayer(_collid, _dt);
if (!this->gonnaExplode && !this->attack)
Movable::Move(_dt);
this->UpdateGroundDetection();
this->UpdateAnim(_dt);
this->UpdateArm();
this->UpdateWeapon(_dt);
this->UpdateDetection();
this->UpdateBullets(_dt);
this->deleteBullets(_collid);
if (this->attack && shield->getLife()) {
shield->setLife(false);
}
else if (this->attack && !shield->getLife() && this->timerDamage >= 1.f) {
this->player->Life = false;
}
if (!shield->inLife)
this->deleteBullets(_collid);
else {
int i = 0;
for (auto& it : bullets) {
if (func::isCollide(it.get()->GetShape(), shield->getShapeShield())) {
shield->setLife(false);
bullets.erase(std::begin(bullets) + i);
break;
}
i++;
}
}
int j = 0;
for (auto& m : *bullet) {
if (func::isCollide(m_shape, m.getBShape())) {
hp -= 5;
bullet->erase(std::begin(*bullet) + j);
break;
}
j++;
}
}
void Boss::UpdateAnim(const float& _dt)
{
if (this->m_movementComponent->GetVelocity().x == 0)
this->anim.at("ARM_IDLE").Animation(this->arm, _dt);
else
this->anim.at("ARM_MOVE").Animation(this->arm, _dt);
if (this->m_shape.getPosition().x < this->player->GetPos().x)
{
this->m_shape.setScale(-1, 1);
this->arm.setScale(-1, 1);
this->canon->GetShape().setScale(-1, 1);
}
else
{
this->m_shape.setScale(1, 1);
this->arm.setScale(1, 1);
this->canon->GetShape().setScale(1, 1);
}
if (!this->isShooting &&
!this->gonnaExplode &&
!this->attack)
{
this->anim.at("MOVE").Animation(this->m_shape, _dt);
}
else
this->anim.at("IDLE").Animation(this->m_shape, _dt);
if (this->gonnaExplode && !this->attack)
this->anim.at("PRE_ATTACK").Animation(this->m_shape, _dt);
else if (!this->gonnaExplode && this->attack)
{
this->anim.at("ATTACK").Animation(this->m_shape, _dt);
this->m_shape.setOrigin(sf::Vector2f(
this->m_shape.getTextureRect().width / 2,
this->m_shape.getTextureRect().height / 2 + 110
));
}
if (isDead())
{
this->m_movementComponent->StopVelocity();
this->gonnaExplode = false;
this->attack = false;
this->timeExplode += _dt;
this->m_movementComponent->StopVelocity();
this->anim.at("DEATH").Animation_NoRestart(this->m_shape, _dt);
if (timeExplode >= 0.8f)
{
this->explode = true;
this->timeExplode = 0.f;
}
}
}
void Boss::UpdateDetection()
{
this->playerDetection.setPosition
(
this->m_shape.getPosition().x,
this->m_shape.getPosition().y
);
}
void Boss::UpdateArm()
{
this->arm.setPosition(this->m_position);
}
void Boss::UpdateWeapon(const float& _dt)
{
this->diff = this->canon->GetPos() - this->player->GetPos();
theta = arg(std::complex<float>(diff.x, diff.y));
if (this->m_shape.getPosition().x < this->player->GetPos().x)
{
this->canon->SetPos(
this->m_shape.getPosition().x + this->m_shape.getGlobalBounds().width / 2 - 44,
this->m_shape.getPosition().y + 30
);
this->canon->SetSpeed(-30.f, 30.f, &this->player->GetShape(), theta, _dt);
this->canon->SetRotation(this->canon->GetAngle());
}
else
{
this->canon->SetPos(
this->m_shape.getPosition().x - 50,
this->m_shape.getPosition().y + 30
);
this->canon->SetSpeed(-30.f, 30.f, &this->player->GetShape(), theta, _dt);
this->canon->SetRotation(this->canon->GetAngle());
}
}
void Boss::UpdateBullets(const float& _dt)
{
for (auto& it : this->bullets)
it->move(_dt);
}
void Boss::Render(sf::RenderWindow* _target)
{
Entity::Render(_target);
std::for_each(std::begin(bullets), std::end(bullets), [&_target](std::vector<std::shared_ptr<Bullet>>::reference b) {
b->draw(_target);
});
if (!this->isDead() && !this->attack) {
this->canon->Render(_target);
_target->draw(this->arm);
}
/*std::for_each(std::begin(groundDetection), std::end(groundDetection), [&_target](std::vector<sf::RectangleShape>::reference r) {
_target->draw(r);
});*/
} | 24.945679 | 177 | 0.657923 | [
"render",
"vector"
] |
b832d0cc436278636e5ea58dcbf85778e5119ea9 | 2,359 | cc | C++ | mindspore/lite/tools/converter/legacy_optimizer/graph/convert_fp32_to_fp16_pass.cc | PowerOlive/mindspore | bda20724a94113cedd12c3ed9083141012da1f15 | [
"Apache-2.0"
] | 3,200 | 2020-02-17T12:45:41.000Z | 2022-03-31T20:21:16.000Z | mindspore/lite/tools/converter/legacy_optimizer/graph/convert_fp32_to_fp16_pass.cc | zimo-geek/mindspore | 665ec683d4af85c71b2a1f0d6829356f2bc0e1ff | [
"Apache-2.0"
] | 176 | 2020-02-12T02:52:11.000Z | 2022-03-28T22:15:55.000Z | mindspore/lite/tools/converter/legacy_optimizer/graph/convert_fp32_to_fp16_pass.cc | zimo-geek/mindspore | 665ec683d4af85c71b2a1f0d6829356f2bc0e1ff | [
"Apache-2.0"
] | 621 | 2020-03-09T01:31:41.000Z | 2022-03-30T03:43:19.000Z | /**
* Copyright 2021 Huawei Technologies Co., Ltd
*
* 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 "tools/converter/legacy_optimizer/graph/convert_fp32_to_fp16_pass.h"
#include <queue>
#include <vector>
#include "tools/converter/converter_context.h"
#include "src/common/log_adapter.h"
#include "tools/common/graph_util.h"
#include "tools/common/tensor_util.h"
#include "include/errorcode.h"
#include "schema/inner/model_generated.h"
#include "base/float16.h"
#include "src/common/log_util.h"
namespace mindspore {
namespace lite {
namespace {
constexpr int kFp16ToFp32Multiply = 2;
}
STATUS ConvertFP32ToFP16Pass::Run(schema::MetaGraphT *graph) {
if (!need_convert_) {
return RET_NO_CHANGE;
}
CHECK_NULL_RETURN(graph);
bool if_changed = false;
for (auto &tensor : graph->allTensors) {
if (tensor->dataType != kNumberTypeFloat32 || tensor->data.empty()) {
continue;
}
auto ele_num = lite::GetShapeSize(tensor->dims);
auto origin_data = tensor->data;
if (origin_data.size() != ele_num * sizeof(float) || origin_data.size() % kFp16ToFp32Multiply != 0) {
MS_LOG(ERROR) << "Tensor data length error.";
ReturnCode::GetSingleReturnCode()->UpdateReturnCode(RET_ERROR);
return RET_ERROR;
}
std::vector<uint8_t> new_data(origin_data.size() / kFp16ToFp32Multiply);
auto fp32_data = reinterpret_cast<float *>(origin_data.data());
auto fp16_data = reinterpret_cast<float16 *>(new_data.data());
CHECK_NULL_RETURN(fp32_data);
CHECK_NULL_RETURN(fp16_data);
for (size_t i = 0; i < ele_num; i++) {
fp16_data[i] = float16(fp32_data[i]);
}
tensor->data.swap(new_data);
tensor->dataType = kNumberTypeFloat16;
new_data.clear();
if_changed = true;
}
return if_changed ? RET_OK : RET_NO_CHANGE;
}
} // namespace lite
} // namespace mindspore
| 34.188406 | 105 | 0.716405 | [
"vector"
] |
b83523c9eb3f38796e8650ef96a5f24dcd761626 | 4,619 | cc | C++ | testcases/AES/src/artifact_utility.cc | zhanghongce/VMCAI-2020-AE | bf4e191ca12b587a2c5813b0b9ca58734ea22971 | [
"BSL-1.0"
] | null | null | null | testcases/AES/src/artifact_utility.cc | zhanghongce/VMCAI-2020-AE | bf4e191ca12b587a2c5813b0b9ca58734ea22971 | [
"BSL-1.0"
] | null | null | null | testcases/AES/src/artifact_utility.cc | zhanghongce/VMCAI-2020-AE | bf4e191ca12b587a2c5813b0b9ca58734ea22971 | [
"BSL-1.0"
] | 1 | 2022-02-17T02:00:38.000Z | 2022-02-17T02:00:38.000Z | #include "artifact_utility.h"
#include <iostream>
#include <string>
#include <set>
#include <vector>
#include <fstream>
#include <signal.h>
#include <unistd.h>
#include <stdbool.h>
#include <string.h>
int get_timeout(int argc, char ** argv) {
int timeout;
if (argc <= 1)
return 3600*10;
else {
try {
timeout = std::stoi(argv[1]);
} catch (...) {
timeout=3600*10;
}
}
return timeout;
}
void set_result(const std::string & outDir, bool succeeded, double total_sec, int cegar_iter, double syn_time, double eq_time) {
std::ofstream fout (outDir + "result-stat.txt");
std::cerr << "CWD:" << get_current_dir_name() << std::endl;
std::cerr << "Opening " << outDir + "result-stat.txt" << " for write" << std::endl;
if (!fout.is_open()) {
std::cerr << "Error open " << outDir + "result-stat.txt" << " for write" << std::endl;
std::cerr << "Error: " << strerror(errno);
return;
}
if (succeeded)
fout << "DONE\n";
else
fout << "KILLED\n";
fout << total_sec << std::endl;
fout << cegar_iter<< std::endl; // iter
fout << syn_time << std::endl; // syn
fout << eq_time << std::endl; // eqcheck
fout.flush();
}
/*volatile*//*sig_atomic_t*/ int * glb_cegar_iter = NULL;
/*volatile*//*sig_atomic_t*/ double * glb_syn_time = NULL;
/*volatile*//*sig_atomic_t*/ double * glb_eq_time = NULL;
/*volatile*//*sig_atomic_t*/ std::string glb_outDir;
std::string init_cwd;
void handle_alarm( int sig ) {
int cegar_iter = glb_cegar_iter ? * glb_cegar_iter : 0;
double syn_time = glb_syn_time ? * glb_syn_time : 0;
double eq_time = glb_eq_time ? * glb_eq_time : 0;
chdir(init_cwd.c_str());
set_result(glb_outDir, false, syn_time + eq_time, cegar_iter, syn_time, eq_time);
kill(-getpid(), SIGTERM);
exit(0);
}
void set_timeout(int sec, const std::string & outDir, int * cegar_iter, double * syn_time, double * eq_time) {
glb_cegar_iter = cegar_iter;
glb_syn_time = syn_time;
glb_eq_time = eq_time;
glb_outDir = outDir;
init_cwd = get_current_dir_name();
//std::cout << "pid:" << getpid()<<std::end;
signal( SIGALRM, handle_alarm );
alarm (sec);
}
std::set<std::string> Split2Set(const std::string& str,
const std::string& delim) {
std::set<std::string> tokens;
size_t prev = 0, pos = 0;
do {
pos = str.find(delim, prev);
if (pos == std::string::npos)
pos = str.length();
std::string token = str.substr(prev, pos - prev);
if (!token.empty())
tokens.insert(token);
prev = pos + delim.length();
} while (pos < str.length() && prev < str.length());
return tokens;
}
/// Replace all occurrance of substring a by substring b
std::string ReplaceAll(const std::string& str, const std::string& a,
const std::string& b) {
std::string result;
size_t find_len = a.size();
size_t pos, from = 0;
while (std::string::npos != (pos = str.find(a, from))) {
result.append(str, from, pos - from);
result.append(b);
from = pos + find_len;
}
result.append(str, from, std::string::npos);
return result;
}
void get_grm_stat(const char * grm_fname, int & ncs, int & ncio, int & ndsrc, int & nddst, int & nvargrp) {
std::set<std::string> CSvar, COvar, DIvar, DOvar;
std::string CSnames, CInames, COnames, DInames, DOnames;
std::string Group;
std::vector<std::set<std::string>> Groupings;
std::string buf;
std::ifstream gf(grm_fname);
while (gf.good())
{
getline(gf, buf);
if (buf.substr(0, 12) == "CTRL-STATE: ") CSnames += buf.substr(12);
else if (buf.substr(0, 9) == "CTRL-IN: ") CInames += buf.substr(9);
else if (buf.substr(0, 10) == "CTRL-OUT: ") COnames += buf.substr(10);
else if (buf.substr(0, 9) == "CTRL-IO: ") COnames += buf.substr(9);
else if (buf.substr(0, 9) == "DATA-IN: ") DInames += buf.substr(9);
else if (buf.substr(0, 10) == "DATA-SRC: ") DInames += buf.substr(10);
else if (buf.substr(0, 10) == "DATA-OUT: ") DOnames += buf.substr(10);
else if (buf.substr(0, 10) == "DATA-DST: ") DOnames += buf.substr(10);
else if (buf.substr(0, 11) == "VAR-GROUP: ") Groupings.push_back( Split2Set(ReplaceAll(buf.substr(11)," ", ""), ",") );
}
CSvar = Split2Set(ReplaceAll(CSnames," ", ""), ",");
COvar = Split2Set(ReplaceAll(COnames," ", ""), ",");
DIvar = Split2Set(ReplaceAll(DInames," ", ""), ",");
DOvar = Split2Set(ReplaceAll(DOnames," ", ""), ",");
ncs = CSvar.size();
ncio= COvar.size();
ndsrc=DIvar.size();
nddst=DOvar.size();
nvargrp = Groupings.size();
}
| 32.300699 | 128 | 0.605542 | [
"vector"
] |
b8359e993ee647decf21354427c32e7ce273d8f5 | 570 | hpp | C++ | include/my_exceptions.hpp | Envq/panda_simulation | 41044fc3b91eb15ac54da8fc84a0facedaac8f1d | [
"MIT"
] | 1 | 2019-12-12T13:14:18.000Z | 2019-12-12T13:14:18.000Z | include/my_exceptions.hpp | Envq/panda_simulation | 41044fc3b91eb15ac54da8fc84a0facedaac8f1d | [
"MIT"
] | null | null | null | include/my_exceptions.hpp | Envq/panda_simulation | 41044fc3b91eb15ac54da8fc84a0facedaac8f1d | [
"MIT"
] | null | null | null | #pragma once
#include <stdexcept>
class collision_object_creation_error : public std::runtime_error {
public:
collision_object_creation_error(const std::string &msg = "Collision Object creation error")
: std::runtime_error(msg) {}
};
class json_field_error : public std::runtime_error {
public:
json_field_error(const std::string &msg = "Json field error") : std::runtime_error(msg) {}
};
class planning_error : public std::runtime_error {
public:
planning_error(const std::string &msg = "Planning error") : std::runtime_error(msg) {}
}; | 25.909091 | 95 | 0.719298 | [
"object"
] |
b837749e2cdbdc64b033d8d84b877b08fe799c0c | 381 | cpp | C++ | Arrays 101/findMaxConsecutiveOnes.cpp | AasthaVarma/LeetCode | d654aadb4c32e8ae90d7d9418c5d1fe3bd23ae2b | [
"MIT"
] | null | null | null | Arrays 101/findMaxConsecutiveOnes.cpp | AasthaVarma/LeetCode | d654aadb4c32e8ae90d7d9418c5d1fe3bd23ae2b | [
"MIT"
] | null | null | null | Arrays 101/findMaxConsecutiveOnes.cpp | AasthaVarma/LeetCode | d654aadb4c32e8ae90d7d9418c5d1fe3bd23ae2b | [
"MIT"
] | null | null | null | class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& a) {
int res = INT_MIN, running_cnt = 0;
for(auto e: a){
if(e == 0){
res = max(res, running_cnt);
running_cnt = 0;
}
else
running_cnt++;
}
res = max(res, running_cnt);
return res;
}
};
| 22.411765 | 48 | 0.440945 | [
"vector"
] |
b8406ed4d387ac0fffe15d80beb917036163c0e3 | 3,962 | cpp | C++ | src/sdlecs.cpp | rogerthat52/snackman | 7d0bf2fd1a8343f44b1a0ab61be16f6ace35af95 | [
"MIT"
] | null | null | null | src/sdlecs.cpp | rogerthat52/snackman | 7d0bf2fd1a8343f44b1a0ab61be16f6ace35af95 | [
"MIT"
] | null | null | null | src/sdlecs.cpp | rogerthat52/snackman | 7d0bf2fd1a8343f44b1a0ab61be16f6ace35af95 | [
"MIT"
] | null | null | null |
// sdl helper class
// provides and interface between ECS and SDL
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <string>
using std::string;
#include "sdlecs.h"
// ------- SDLRenderComponent ------- //
SDL_Texture* SDLRendererComponent::loadTexture(string fileName){
// get texture pointer ready
SDL_Texture* texture;
// set path up
string path("res/" + fileName);
// check if texture entry exists
if(textures.find(fileName) != textures.end()){
// if so, pull from list
texture = getTexture(fileName);
} else {
// else, load texture
texture = IMG_LoadTexture(renderer, path.c_str());
if( texture == NULL )
{
std::cout << "Failed to load texture image!" << std::endl;
std::cout << path.c_str() << std::endl;
std::cout << IMG_GetError() << std::endl;
}
// create new entry
textures.insert({fileName, texture});
// note we don't have to return a reference to the textures entry bc it's already a pointer to something else
}
return texture;
}
SDL_Texture* SDLRendererComponent::getTexture(string fileName){
// get texture reference
SDL_Texture* texture = textures.at(fileName);
// return
return texture;
}
void SDLRendererComponent::destroyTexture(string& fileName){
// get texture reference
SDL_Texture* texture = textures.at(fileName);
// remove from sdl
SDL_DestroyTexture(texture);
// remove reference from map
textures.erase(fileName);
}
SDL_Renderer* SDLRendererComponent::getRenderer(){
return renderer;
}
// ------- SDLEventComponent ------- //
void SDLEventComponent::flushEvents(){
// move from keydown to keypressed
keyPressed.insert(keyDown.begin(), keyDown.end());
// clear up/down events
keyDown.clear();
keyUp.clear();
// for every event
while(SDL_PollEvent(&event)){
switch (event.type){
case SDL_KEYDOWN:
keyDown.emplace(event.key.keysym.scancode);
break;
case SDL_KEYUP:
keyUp.emplace(event.key.keysym.scancode);
break;
case SDL_QUIT:
quit = true;
break;
}
}
// check keyup and remove from keypressed
for(SDL_Scancode key : keyUp){
keyPressed.erase(key);
}
}
// ------- SDLDeltaTimeComponent ------- //
double SDLDeltaTimeComponent::getDeltaTimeS(){
return deltaTime * 0.001;
}
double SDLDeltaTimeComponent::getDeltaTimeMS(){
return deltaTime;
}
void SDLDeltaTimeComponent::updateTime(){
// set delta time
currentTime = SDL_GetPerformanceCounter();
deltaTime = (currentTime - lastTime) * 1000 / (double)SDL_GetPerformanceFrequency();
lastTime = currentTime;
}
// ------- Scene ------- //
Scene::Scene(SDL_Renderer* renderer){
// initalize render component
SDLRendererComponent render(renderer);
// initalize event component
SDLEventComponent event;
// initalize deltaTime component
SDLDeltaTimeComponent deltaTime;
addComponent(render);
addComponent(event);
addComponent(deltaTime);
groupEntities<SDLRendererComponent>();
groupEntities<SDLEventComponent>();
groupEntities<SDLDeltaTimeComponent>();
};
SDLRendererComponent& Scene::getRenderer(){
return getComponent<SDLRendererComponent>();
};
void Scene::update(){
// update delta time
getComponent<SDLDeltaTimeComponent>().updateTime();
// update events
getComponent<SDLEventComponent>().flushEvents();
// render all render systems
ECSManager::update();
}
void Scene::render(){
// get renderer
SDL_Renderer* renderer = getComponent<SDLRendererComponent>().getRenderer();
// clear renderer
SDL_RenderClear(renderer);
// render all render systems
ECSManager::render();
// send it boii
SDL_RenderPresent(renderer);
} | 26.065789 | 117 | 0.64109 | [
"render"
] |
cdc6e19277985f311a2dc24c81e363f5d8ee7595 | 865 | cpp | C++ | 979.cpp | Alex-Amber/LeetCode | c8d09e86cee52648f84ca2afed8dd0f13e51ab58 | [
"MIT"
] | null | null | null | 979.cpp | Alex-Amber/LeetCode | c8d09e86cee52648f84ca2afed8dd0f13e51ab58 | [
"MIT"
] | null | null | null | 979.cpp | Alex-Amber/LeetCode | c8d09e86cee52648f84ca2afed8dd0f13e51ab58 | [
"MIT"
] | null | null | null | /*
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x): val(x), left(NULL), right(NULL) {}
};
*/
class Solution {
public:
int moves;
vector<int> dfs(TreeNode *root) {
if (!root)
return vector<int>(2, 0);
int total_coins = root->val, total_nodes = 1;
vector<int> left = dfs(root->left);
moves += abs(left[0] - left[1]);
vector<int> right = dfs(root->right);
moves += abs(right[0] - right[1]);
total_coins += left[0];
total_coins += right[0];
total_nodes += left[1];
total_nodes += right[1];
vector<int> res;
res.push_back(total_coins);
res.push_back(total_nodes);
return res;
}
int distributeCoins(TreeNode* root) {
moves = 0;
dfs(root);
return moves;
}
};
| 24.027778 | 55 | 0.531792 | [
"vector"
] |
cdd0e21edfd38a7d983a355419dd29bae6a8132e | 1,866 | hpp | C++ | src/slave/process_based_isolation_module.hpp | benh/twesos | 194e1976d474005d807f37e7204ea08766e4b42a | [
"BSD-3-Clause"
] | 1 | 2019-02-17T15:56:26.000Z | 2019-02-17T15:56:26.000Z | src/slave/process_based_isolation_module.hpp | benh/twesos | 194e1976d474005d807f37e7204ea08766e4b42a | [
"BSD-3-Clause"
] | null | null | null | src/slave/process_based_isolation_module.hpp | benh/twesos | 194e1976d474005d807f37e7204ea08766e4b42a | [
"BSD-3-Clause"
] | 3 | 2017-07-10T07:28:30.000Z | 2020-07-25T19:48:07.000Z | #ifndef __PROCESS_BASED_ISOLATION_MODULE_HPP__
#define __PROCESS_BASED_ISOLATION_MODULE_HPP__
#include <sys/types.h>
#include <boost/unordered_map.hpp>
#include "isolation_module.hpp"
#include "slave.hpp"
#include "launcher/launcher.hpp"
#include "messaging/messages.hpp"
namespace mesos { namespace internal { namespace slave {
using boost::unordered_map;
using mesos::internal::launcher::ExecutorLauncher;
class ProcessBasedIsolationModule : public IsolationModule {
public:
// Reaps child processes and tells the slave if they exit
class Reaper : public Process {
ProcessBasedIsolationModule* module;
protected:
void operator () ();
public:
Reaper(ProcessBasedIsolationModule* module);
};
// Extra shutdown message for reaper
enum { SHUTDOWN_REAPER = PROCESS_MSGID };
private:
bool initialized;
Slave* slave;
unordered_map<FrameworkID, pid_t> pgids;
Reaper* reaper;
public:
ProcessBasedIsolationModule();
virtual ~ProcessBasedIsolationModule();
virtual void initialize(Slave *slave);
virtual void startExecutor(Framework *framework);
virtual void killExecutor(Framework* framework);
virtual void resourcesChanged(Framework* framework);
protected:
// Main method executed after a fork() to create a Launcher for launching
// an executor's process. The Launcher will create the child's working
// directory, chdir() to it, fetch the executor, set environment varibles,
// switch user, etc, and finally exec() the executor process.
// Subclasses of ProcessBasedIsolationModule that wish to override the
// default launching behavior should override createLauncher() and return
// their own Launcher object (including possibly a subclass of Launcher).
virtual ExecutorLauncher* createExecutorLauncher(Framework* framework);
};
}}}
#endif /* __PROCESS_BASED_ISOLATION_MODULE_HPP__ */
| 26.657143 | 76 | 0.769025 | [
"object"
] |
cdd2ff89d94a9907d2e80afcc9d4ac6549f04ec3 | 9,019 | cpp | C++ | tools/nitpick/src/ui/Nitpick.cpp | neurealdesktop/hifi | 22c2954423dd352a0703bb400722bedb12e8271f | [
"Apache-2.0"
] | null | null | null | tools/nitpick/src/ui/Nitpick.cpp | neurealdesktop/hifi | 22c2954423dd352a0703bb400722bedb12e8271f | [
"Apache-2.0"
] | null | null | null | tools/nitpick/src/ui/Nitpick.cpp | neurealdesktop/hifi | 22c2954423dd352a0703bb400722bedb12e8271f | [
"Apache-2.0"
] | null | null | null | //
// Nitpick.cpp
// zone/ambientLightInheritence
//
// Created by Nissim Hadar on 2 Nov 2017.
// Copyright 2013 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#include "Nitpick.h"
#ifdef Q_OS_WIN
#include <windows.h>
#include <shellapi.h>
#endif
Nitpick::Nitpick(QWidget* parent) : QMainWindow(parent) {
_ui.setupUi(this);
_ui.checkBoxInteractiveMode->setChecked(true);
_ui.progressBar->setVisible(false);
_ui.tabWidget->setCurrentIndex(0);
_signalMapper = new QSignalMapper();
connect(_ui.actionClose, &QAction::triggered, this, &Nitpick::on_closeButton_clicked);
connect(_ui.actionAbout, &QAction::triggered, this, &Nitpick::about);
connect(_ui.actionContent, &QAction::triggered, this, &Nitpick::content);
// The second tab hides and shows the Windows task bar
#ifndef Q_OS_WIN
_ui.tabWidget->removeTab(1);
#endif
_ui.statusLabel->setText("");
_ui.plainTextEdit->setReadOnly(true);
setWindowTitle("Nitpick - v1.2");
// Coming soon to a nitpick near you...
//// _helpWindow.textBrowser->setText()
}
Nitpick::~Nitpick() {
delete _signalMapper;
if (_test) {
delete _test;
}
if (_testRunner) {
delete _testRunner;
}
}
void Nitpick::setup() {
if (_test) {
delete _test;
}
_test = new Test(_ui.progressBar, _ui.checkBoxInteractiveMode);
std::vector<QCheckBox*> dayCheckboxes;
dayCheckboxes.emplace_back(_ui.mondayCheckBox);
dayCheckboxes.emplace_back(_ui.tuesdayCheckBox);
dayCheckboxes.emplace_back(_ui.wednesdayCheckBox);
dayCheckboxes.emplace_back(_ui.thursdayCheckBox);
dayCheckboxes.emplace_back(_ui.fridayCheckBox);
dayCheckboxes.emplace_back(_ui.saturdayCheckBox);
dayCheckboxes.emplace_back(_ui.sundayCheckBox);
std::vector<QCheckBox*> timeEditCheckboxes;
timeEditCheckboxes.emplace_back(_ui.timeEdit1checkBox);
timeEditCheckboxes.emplace_back(_ui.timeEdit2checkBox);
timeEditCheckboxes.emplace_back(_ui.timeEdit3checkBox);
timeEditCheckboxes.emplace_back(_ui.timeEdit4checkBox);
std::vector<QTimeEdit*> timeEdits;
timeEdits.emplace_back(_ui.timeEdit1);
timeEdits.emplace_back(_ui.timeEdit2);
timeEdits.emplace_back(_ui.timeEdit3);
timeEdits.emplace_back(_ui.timeEdit4);
if (_testRunner) {
delete _testRunner;
}
_testRunner = new TestRunner(dayCheckboxes, timeEditCheckboxes, timeEdits, _ui.workingFolderLabel, _ui.checkBoxServerless, _ui.checkBoxRunLatest, _ui.urlLineEdit, _ui.runNowButton);
}
void Nitpick::startTestsEvaluation(const bool isRunningFromCommandLine,
const bool isRunningInAutomaticTestRun,
const QString& snapshotDirectory,
const QString& branch,
const QString& user
) {
_test->startTestsEvaluation(isRunningFromCommandLine, isRunningInAutomaticTestRun, snapshotDirectory, branch, user);
}
void Nitpick::on_tabWidget_currentChanged(int index) {
// Enable the GitHub edit boxes as required
#ifdef Q_OS_WIN
if (index == 0 || index == 2 || index == 3) {
#else
if (index == 0 || index == 1 || index == 2) {
#endif
_ui.userLineEdit->setDisabled(false);
_ui.branchLineEdit->setDisabled(false);
} else {
_ui.userLineEdit->setDisabled(true);
_ui.branchLineEdit->setDisabled(true);
}
}
void Nitpick::on_evaluateTestsButton_clicked() {
_test->startTestsEvaluation(false, false);
}
void Nitpick::on_createRecursiveScriptButton_clicked() {
_test->createRecursiveScript();
}
void Nitpick::on_createAllRecursiveScriptsButton_clicked() {
_test->createAllRecursiveScripts();
}
void Nitpick::on_createTestsButton_clicked() {
_test->createTests();
}
void Nitpick::on_createMDFileButton_clicked() {
_test->createMDFile();
}
void Nitpick::on_createAllMDFilesButton_clicked() {
_test->createAllMDFiles();
}
void Nitpick::on_createTestAutoScriptButton_clicked() {
_test->createTestAutoScript();
}
void Nitpick::on_createAllTestAutoScriptsButton_clicked() {
_test->createAllTestAutoScripts();
}
void Nitpick::on_createTestsOutlineButton_clicked() {
_test->createTestsOutline();
}
void Nitpick::on_createTestRailTestCasesButton_clicked() {
_test->createTestRailTestCases();
}
void Nitpick::on_createTestRailRunButton_clicked() {
_test->createTestRailRun();
}
void Nitpick::on_setWorkingFolderButton_clicked() {
_testRunner->setWorkingFolder();
}
void Nitpick::enableRunTabControls() {
_ui.runNowButton->setEnabled(true);
_ui.daysGroupBox->setEnabled(true);
_ui.timesGroupBox->setEnabled(true);
}
void Nitpick::on_runNowButton_clicked() {
_testRunner->run();
}
void Nitpick::on_checkBoxRunLatest_clicked() {
_ui.urlLineEdit->setEnabled(!_ui.checkBoxRunLatest->isChecked());
}
void Nitpick::automaticTestRunEvaluationComplete(QString zippedFolderName, int numberOfFailures) {
_testRunner->automaticTestRunEvaluationComplete(zippedFolderName, numberOfFailures);
}
void Nitpick::on_updateTestRailRunResultsButton_clicked() {
_test->updateTestRailRunResult();
}
// To toggle between show and hide
// if (uState & ABS_AUTOHIDE) on_showTaskbarButton_clicked();
// else on_hideTaskbarButton_clicked();
//
void Nitpick::on_hideTaskbarButton_clicked() {
#ifdef Q_OS_WIN
APPBARDATA abd = { sizeof abd };
UINT uState = (UINT)SHAppBarMessage(ABM_GETSTATE, &abd);
LPARAM param = uState & ABS_ALWAYSONTOP;
abd.lParam = ABS_AUTOHIDE | param;
SHAppBarMessage(ABM_SETSTATE, &abd);
#endif
}
void Nitpick::on_showTaskbarButton_clicked() {
#ifdef Q_OS_WIN
APPBARDATA abd = { sizeof abd };
UINT uState = (UINT)SHAppBarMessage(ABM_GETSTATE, &abd);
LPARAM param = uState & ABS_ALWAYSONTOP;
abd.lParam = param;
SHAppBarMessage(ABM_SETSTATE, &abd);
#endif
}
void Nitpick::on_closeButton_clicked() {
exit(0);
}
void Nitpick::on_createPythonScriptRadioButton_clicked() {
_test->setTestRailCreateMode(PYTHON);
}
void Nitpick::on_createXMLScriptRadioButton_clicked() {
_test->setTestRailCreateMode(XML);
}
void Nitpick::on_createWebPagePushButton_clicked() {
_test->createWebPage(_ui.updateAWSCheckBox, _ui.awsURLLineEdit);
}
void Nitpick::downloadFile(const QUrl& url) {
_downloaders.emplace_back(new Downloader(url, this));
connect(_downloaders[_index], SIGNAL(downloaded()), _signalMapper, SLOT(map()));
_signalMapper->setMapping(_downloaders[_index], _index);
++_index;
}
void Nitpick::downloadFiles(const QStringList& URLs, const QString& directoryName, const QStringList& filenames, void *caller) {
connect(_signalMapper, SIGNAL(mapped(int)), this, SLOT(saveFile(int)));
_directoryName = directoryName;
_filenames = filenames;
_caller = caller;
_numberOfFilesToDownload = URLs.size();
_numberOfFilesDownloaded = 0;
_index = 0;
_ui.progressBar->setMinimum(0);
_ui.progressBar->setMaximum(_numberOfFilesToDownload - 1);
_ui.progressBar->setValue(0);
_ui.progressBar->setVisible(true);
foreach (auto downloader, _downloaders) {
delete downloader;
}
_downloaders.clear();
for (int i = 0; i < _numberOfFilesToDownload; ++i) {
downloadFile(URLs[i]);
}
}
void Nitpick::saveFile(int index) {
try {
QFile file(_directoryName + "/" + _filenames[index]);
file.open(QIODevice::WriteOnly);
file.write(_downloaders[index]->downloadedData());
file.close();
} catch (...) {
QMessageBox::information(0, "Test Aborted", "Failed to save file: " + _filenames[index]);
_ui.progressBar->setVisible(false);
return;
}
++_numberOfFilesDownloaded;
if (_numberOfFilesDownloaded == _numberOfFilesToDownload) {
disconnect(_signalMapper, SIGNAL(mapped(int)), this, SLOT(saveFile(int)));
if (_caller == _test) {
_test->finishTestsEvaluation();
} else if (_caller == _testRunner) {
_testRunner->downloadComplete();
}
} else {
_ui.progressBar->setValue(_numberOfFilesDownloaded);
}
}
void Nitpick::about() {
QMessageBox::information(0, "About", QString("Built ") + __DATE__ + ", " + __TIME__);
}
void Nitpick::content() {
_helpWindow.show();
}
void Nitpick::setUserText(const QString& user) {
_ui.userLineEdit->setText(user);
}
QString Nitpick::getSelectedUser() {
return _ui.userLineEdit->text();
}
void Nitpick::setBranchText(const QString& branch) {
_ui.branchLineEdit->setText(branch);
}
QString Nitpick::getSelectedBranch() {
return _ui.branchLineEdit->text();
}
void Nitpick::updateStatusLabel(const QString& status) {
_ui.statusLabel->setText(status);
}
void Nitpick::appendLogWindow(const QString& message) {
_ui.plainTextEdit->appendPlainText(message);
}
| 28.541139 | 185 | 0.707174 | [
"vector"
] |
cdd3d6e556baf8ad80817b30d92d8039499ea71b | 9,761 | cc | C++ | oommf/app/oxs/ext/stagezeeman.cc | fangohr/oommf | 67fa0d69eadbbb9eef320babd07910f6d7b4e089 | [
"TCL"
] | 18 | 2016-04-29T10:11:29.000Z | 2022-02-13T08:48:39.000Z | oommf/app/oxs/ext/stagezeeman.cc | fangohr/oommf | 67fa0d69eadbbb9eef320babd07910f6d7b4e089 | [
"TCL"
] | 29 | 2017-11-01T20:00:28.000Z | 2021-10-05T12:22:50.000Z | oommf/app/oxs/ext/stagezeeman.cc | fangohr/oommf | 67fa0d69eadbbb9eef320babd07910f6d7b4e089 | [
"TCL"
] | 11 | 2015-10-17T19:41:29.000Z | 2021-05-12T08:32:37.000Z | /* FILE: stagezeeman.cc -*-Mode: c++-*-
*
* Uniform Zeeman (applied field) energy, derived from Oxs_ChunkEnergy class,
* specified from a Tcl proc.
*
*/
#include "oc.h"
#include "nb.h"
#include "director.h"
#include "stagezeeman.h"
// Oxs_Ext registration support
OXS_EXT_REGISTER(Oxs_StageZeeman);
/* End includes */
// Constructor
Oxs_StageZeeman::Oxs_StageZeeman(
const char* name, // Child instance id
Oxs_Director* newdtr, // App director
const char* argstr) // MIF input block parameters
: Oxs_ChunkEnergy(name,newdtr,argstr),
number_of_stages(0), mesh_id(0), stage_valid(0),
energy_density_error_estimate(-1.0)
{
working_stage = static_cast<OC_UINT4m>(static_cast<OC_INT4m>(-1));
/// Safety; First ChangeFileInitializer() call should be
/// be triggered by the stage_valid boolean.
// Process arguments
hmult = GetRealInitValue("multiplier",1.0);
OC_BOOL use_file_list = HasInitValue("files");
OC_BOOL use_script = HasInitValue("script");
if(use_file_list && use_script) {
const char *cptr =
"Initialization string specifies both \"files\""
" and \"script\". These are mutually exclusive"
" options; select only one.";
throw Oxs_ExtError(this,cptr);
}
if(!use_file_list && !use_script) {
const char *cptr =
"Initialization string specifies neither \"files\""
" nor \"script\". These are mutually exclusive"
" options, but one or the other must be specified.";
throw Oxs_ExtError(this,cptr);
}
if(use_file_list) {
// Make certain list contains at least 1 file, because
// length of filelist is used as a flag to determine
// whether to call cmd or not.
GetGroupedStringListInitValue("files",filelist);
if(filelist.empty()) {
throw Oxs_ExtError(this,"\"files\" parameter value is empty."
" At least one filename is required.");
}
// As a failsafe, set up a dummy command that generates
// a clear error message if in fact cmd is accidentally
// called.
String dummy_cmd =
"error \"Programming error; Oxs_StageZeeman script called"
" from filelist mode.\" ;# ";
cmd.SetBaseCommand(InstanceName(),
director->GetMifInterp(),
dummy_cmd,1);
number_of_stages
= GetUIntInitValue("stage_count",
static_cast<OC_UINT4m>(filelist.size()));
/// Default number_of_stages in this case is the length
/// of filelist.
} else {
cmd.SetBaseCommand(InstanceName(),
director->GetMifInterp(),
GetStringInitValue("script"),1);
/// cmd takes 1 integer argument: the current stage.
/// Return value should be a vector field spec, i.e.,
/// a vector field reference or an initialization
/// list.
number_of_stages = GetUIntInitValue("stage_count",0);
/// Default number_of_stages in this case is 0, i.e.,
/// no preference.
}
// Initialize outputs.
Bapp_output.Setup(this,InstanceName(),"B max","mT",1,
&Oxs_StageZeeman::Fill__Bapp_output);
Bappx_output.Setup(this,InstanceName(),"Bx max","mT",1,
&Oxs_StageZeeman::Fill__Bapp_output);
Bappy_output.Setup(this,InstanceName(),"By max","mT",1,
&Oxs_StageZeeman::Fill__Bapp_output);
Bappz_output.Setup(this,InstanceName(),"Bz max","mT",1,
&Oxs_StageZeeman::Fill__Bapp_output);
// Register outputs.
Bapp_output.Register(director,0);
Bappx_output.Register(director,0);
Bappy_output.Register(director,0);
Bappz_output.Register(director,0);
VerifyAllInitArgsUsed();
}
Oxs_StageZeeman::~Oxs_StageZeeman()
{}
OC_BOOL Oxs_StageZeeman::Init()
{
stage_valid = 0;
mesh_id = 0;
stagefield.Release();
energy_density_error_estimate = -1.0;
// Run parent initializer.
return Oxs_ChunkEnergy::Init();
}
void Oxs_StageZeeman::StageRequestCount(unsigned int& min,
unsigned int& max) const
{
if(number_of_stages==0) {
min=0; max=UINT_MAX;
} else {
min = max = number_of_stages;
}
}
void
Oxs_StageZeeman::ChangeFieldInitializer
(OC_UINT4m stage,
const Oxs_Mesh* mesh) const
{ // Setup stagefield_init
vector<String> params;
if(filelist.empty()) {
// Use cmd to generate field initializer
cmd.SaveInterpResult();
cmd.SetCommandArg(0,stage);
cmd.Eval();
cmd.GetResultList(params);
cmd.RestoreInterpResult();
} else {
// Construct field initializer using Oxs_FileVectorField
// with filename from filelist and range from mesh.
OC_UINT4m index = stage;
OC_UINT4m filecount = static_cast<OC_UINT4m>(filelist.size());
if(index >= filecount) index = filecount - 1;
vector<String> options;
options.push_back(String("file"));
options.push_back(filelist[index]);
Oxs_Box bbox; mesh->GetBoundingBox(bbox);
char buf[64];
options.push_back(String("xrange"));
Oc_Snprintf(buf,sizeof(buf),"%.17g %.17g",
static_cast<double>(bbox.GetMinX()),
static_cast<double>(bbox.GetMaxX()));
options.push_back(String(buf));
options.push_back(String("yrange"));
Oc_Snprintf(buf,sizeof(buf),"%.17g %.17g",
static_cast<double>(bbox.GetMinY()),
static_cast<double>(bbox.GetMaxY()));
options.push_back(String(buf));
options.push_back(String("zrange"));
Oc_Snprintf(buf,sizeof(buf),"%.17g %.17g",
static_cast<double>(bbox.GetMinZ()),
static_cast<double>(bbox.GetMaxZ()));
options.push_back(String(buf));
params.push_back(String("Oxs_FileVectorField"));
params.push_back(Nb_MergeList(options));
}
OXS_GET_EXT_OBJECT(params,Oxs_VectorField,stagefield_init);
working_stage = stage;
stage_valid = 1;
}
void
Oxs_StageZeeman::FillStageFieldCache(const Oxs_SimState& state) const
{
const Oxs_Mesh* mesh = state.mesh;
max_field.Set(0.,0.,0.);
energy_density_error_estimate=0.0;
stagefield_init->FillMeshValue(mesh,stagefield);
OC_INDEX size = mesh->Size();
if(size>0) {
const Oxs_MeshValue<OC_REAL8m>& Ms = *(state.Ms);
if(hmult!=1.0) stagefield *= hmult;
OC_INDEX max_i=0;
OC_REAL8m max_magsq = stagefield[OC_INDEX(0)].MagSq();
OC_REAL8m max_energysq = max_magsq*Ms[OC_INDEX(0)]*Ms[OC_INDEX(0)];
for(OC_INDEX i=1;i<size;i++) {
OC_REAL8m magsq = stagefield[i].MagSq();
if(magsq>max_magsq) {
max_magsq = magsq;
max_i = i;
}
OC_REAL8m energy_test = magsq*Ms[i]*Ms[i];
if(energy_test>max_energysq) max_energysq = energy_test;
}
max_field = stagefield[max_i];
energy_density_error_estimate
= 4*OC_REAL8m_EPSILON*MU0*sqrt(max_energysq);
}
}
void Oxs_StageZeeman::UpdateCache(const Oxs_SimState& state) const
{
// Update cache as necessary.
if(!stage_valid || working_stage!=state.stage_number) {
mesh_id = 0;
ChangeFieldInitializer(state.stage_number,state.mesh);
FillStageFieldCache(state);
mesh_id = state.mesh->Id();
} else if(mesh_id != state.mesh->Id()) {
mesh_id = 0;
FillStageFieldCache(state);
mesh_id = state.mesh->Id();
}
}
void Oxs_StageZeeman::ComputeEnergyChunkInitialize
(const Oxs_SimState& state,
Oxs_ComputeEnergyDataThreaded& ocedt,
Oc_AlignedVector<Oxs_ComputeEnergyDataThreadedAux>& /* thread_ocedtaux */,
int /* number_of_threads */) const
{
UpdateCache(state);
if(!stagefield.CheckMesh(state.mesh)) {
throw Oxs_ExtError(this,"Programming error; stagefield size"
" incompatible with mesh.");
}
ocedt.energy_density_error_estimate
= energy_density_error_estimate;
}
void Oxs_StageZeeman::ComputeEnergyChunk
(const Oxs_SimState& state,
Oxs_ComputeEnergyDataThreaded& ocedt,
Oxs_ComputeEnergyDataThreadedAux& ocedtaux,
OC_INDEX node_start,OC_INDEX node_stop,
int /* threadnumber */) const
{
const Oxs_MeshValue<ThreeVector>& spin = state.spin;
const Oxs_MeshValue<OC_REAL8m>& Ms = *(state.Ms);
Nb_Xpfloat energy_sum = 0.0;
for(OC_INDEX i=node_start;i<node_stop;++i) {
OC_REAL8m ei,tx,ty,tz;
OC_REAL8m Msi = Ms[i];
if(0.0 != Msi) {
const ThreeVector& m = spin[i];
const ThreeVector& H = stagefield[i];
tz = m.x*H.y; // t = m x H
ty = m.x*H.z;
tx = m.y*H.z;
ei = -MU0*Msi*(m.x*H.x + m.y*H.y + m.z*H.z);
tz -= m.y*H.x;
ty = m.z*H.x - ty;
tx -= m.z*H.y;
energy_sum += ei * state.mesh->Volume(i);
if(ocedt.energy_accum) (*ocedt.energy_accum)[i] += ei;
if(ocedt.mxH_accum) (*ocedt.mxH_accum)[i] += ThreeVector(tx,ty,tz);
} else {
ei = tx = ty = tz = 0.0;
}
if(ocedt.energy) (*ocedt.energy)[i] = ei;
if(ocedt.mxH) (*ocedt.mxH)[i] = ThreeVector(tx,ty,tz);
}
ocedtaux.energy_total_accum += energy_sum;
// ocedtaux.pE_pt_accum += 0.0;
}
void
Oxs_StageZeeman::Fill__Bapp_output(const Oxs_SimState& state)
{
UpdateCache(state);
ThreeVector B = max_field;
B *= MU0 * 1000; /// Report Bapp in mT
if(Bapp_output.GetCacheRequestCount()>0) {
Bapp_output.cache.state_id=0;
Bapp_output.cache.value = sqrt(B.MagSq());
Bapp_output.cache.state_id=state.Id();
}
if(Bappx_output.GetCacheRequestCount()>0) {
Bappx_output.cache.state_id=0;
Bappx_output.cache.value = B.x;
Bappx_output.cache.state_id=state.Id();
}
if(Bappy_output.GetCacheRequestCount()>0) {
Bappy_output.cache.state_id=0;
Bappy_output.cache.value = B.y;
Bappy_output.cache.state_id=state.Id();
}
if(Bappz_output.GetCacheRequestCount()>0) {
Bappz_output.cache.state_id=0;
Bappz_output.cache.value = B.z;
Bappz_output.cache.state_id=state.Id();
}
}
| 30.694969 | 77 | 0.659666 | [
"mesh",
"vector"
] |
cdd57343333df4c4f917a494f8409a91fbe49ce6 | 3,907 | cc | C++ | r-kvstore/src/model/CreateInstancesRequest.cc | sdk-team/aliyun-openapi-cpp-sdk | d0e92f6f33126dcdc7e40f60582304faf2c229b7 | [
"Apache-2.0"
] | 3 | 2020-01-06T08:23:14.000Z | 2022-01-22T04:41:35.000Z | r-kvstore/src/model/CreateInstancesRequest.cc | sdk-team/aliyun-openapi-cpp-sdk | d0e92f6f33126dcdc7e40f60582304faf2c229b7 | [
"Apache-2.0"
] | null | null | null | r-kvstore/src/model/CreateInstancesRequest.cc | sdk-team/aliyun-openapi-cpp-sdk | d0e92f6f33126dcdc7e40f60582304faf2c229b7 | [
"Apache-2.0"
] | null | null | null | /*
* 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.
*/
#include <alibabacloud/r-kvstore/model/CreateInstancesRequest.h>
using AlibabaCloud::R_kvstore::Model::CreateInstancesRequest;
CreateInstancesRequest::CreateInstancesRequest() :
RpcServiceRequest("r-kvstore", "2015-01-01", "CreateInstances")
{}
CreateInstancesRequest::~CreateInstancesRequest()
{}
long CreateInstancesRequest::getResourceOwnerId()const
{
return resourceOwnerId_;
}
void CreateInstancesRequest::setResourceOwnerId(long resourceOwnerId)
{
resourceOwnerId_ = resourceOwnerId;
setCoreParameter("ResourceOwnerId", std::to_string(resourceOwnerId));
}
std::string CreateInstancesRequest::getAgentId()const
{
return agentId_;
}
void CreateInstancesRequest::setAgentId(const std::string& agentId)
{
agentId_ = agentId;
setCoreParameter("AgentId", agentId);
}
bool CreateInstancesRequest::getAutoPay()const
{
return autoPay_;
}
void CreateInstancesRequest::setAutoPay(bool autoPay)
{
autoPay_ = autoPay;
setCoreParameter("AutoPay", autoPay ? "true" : "false");
}
std::string CreateInstancesRequest::getResourceOwnerAccount()const
{
return resourceOwnerAccount_;
}
void CreateInstancesRequest::setResourceOwnerAccount(const std::string& resourceOwnerAccount)
{
resourceOwnerAccount_ = resourceOwnerAccount;
setCoreParameter("ResourceOwnerAccount", resourceOwnerAccount);
}
std::string CreateInstancesRequest::getInstances()const
{
return instances_;
}
void CreateInstancesRequest::setInstances(const std::string& instances)
{
instances_ = instances;
setCoreParameter("Instances", instances);
}
std::string CreateInstancesRequest::getOwnerAccount()const
{
return ownerAccount_;
}
void CreateInstancesRequest::setOwnerAccount(const std::string& ownerAccount)
{
ownerAccount_ = ownerAccount;
setCoreParameter("OwnerAccount", ownerAccount);
}
long CreateInstancesRequest::getOwnerId()const
{
return ownerId_;
}
void CreateInstancesRequest::setOwnerId(long ownerId)
{
ownerId_ = ownerId;
setCoreParameter("OwnerId", std::to_string(ownerId));
}
std::string CreateInstancesRequest::getAccessKeyId()const
{
return accessKeyId_;
}
void CreateInstancesRequest::setAccessKeyId(const std::string& accessKeyId)
{
accessKeyId_ = accessKeyId;
setCoreParameter("AccessKeyId", accessKeyId);
}
std::string CreateInstancesRequest::getToken()const
{
return token_;
}
void CreateInstancesRequest::setToken(const std::string& token)
{
token_ = token;
setCoreParameter("Token", token);
}
std::string CreateInstancesRequest::getSecurityToken()const
{
return securityToken_;
}
void CreateInstancesRequest::setSecurityToken(const std::string& securityToken)
{
securityToken_ = securityToken;
setCoreParameter("SecurityToken", securityToken);
}
std::string CreateInstancesRequest::getRegionId()const
{
return regionId_;
}
void CreateInstancesRequest::setRegionId(const std::string& regionId)
{
regionId_ = regionId;
setCoreParameter("RegionId", regionId);
}
std::string CreateInstancesRequest::getBusinessInfo()const
{
return businessInfo_;
}
void CreateInstancesRequest::setBusinessInfo(const std::string& businessInfo)
{
businessInfo_ = businessInfo;
setCoreParameter("BusinessInfo", businessInfo);
}
| 24.41875 | 94 | 0.761198 | [
"model"
] |
cdd77c63f41c21757da86eb2629a920a910b03ae | 3,638 | hpp | C++ | QuantExt/qle/pricingengines/discountingfxforwardengine.hpp | mrslezak/Engine | c46ff278a2c5f4162db91a7ab500a0bb8cef7657 | [
"BSD-3-Clause"
] | 335 | 2016-10-07T16:31:10.000Z | 2022-03-02T07:12:03.000Z | QuantExt/qle/pricingengines/discountingfxforwardengine.hpp | mrslezak/Engine | c46ff278a2c5f4162db91a7ab500a0bb8cef7657 | [
"BSD-3-Clause"
] | 59 | 2016-10-31T04:20:24.000Z | 2022-01-03T16:39:57.000Z | QuantExt/qle/pricingengines/discountingfxforwardengine.hpp | mrslezak/Engine | c46ff278a2c5f4162db91a7ab500a0bb8cef7657 | [
"BSD-3-Clause"
] | 180 | 2016-10-08T14:23:50.000Z | 2022-03-28T10:43:05.000Z | /*
Copyright (C) 2016 Quaternion Risk Management Ltd
All rights reserved.
This file is part of ORE, a free-software/open-source library
for transparent pricing and risk analysis - http://opensourcerisk.org
ORE is free software: you can redistribute it and/or modify it
under the terms of the Modified BSD License. You should have received a
copy of the license along with this program.
The license is also available online at <http://opensourcerisk.org>
This program is distributed on the basis that it will form a useful
contribution to risk analytics and model standardisation, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
*/
/*! \file qle/pricingengines/discountingfxforwardengine.hpp
\brief Engine to value an FX Forward off two yield curves
\ingroup engines
*/
#ifndef quantext_discounting_fxforward_engine_hpp
#define quantext_discounting_fxforward_engine_hpp
#include <ql/termstructures/yieldtermstructure.hpp>
#include <qle/instruments/fxforward.hpp>
namespace QuantExt {
//! Discounting FX Forward Engine
/*! This class implements pricing of FX Forwards by discounting the future
nominal cash flows using the respective yield curves. The npv is
expressed in ccy1. The given currencies ccy1 and ccy2 are matched
to the correct fx forward legs. The evaluation date is the
reference date of either discounting curve (which must be equal).
\ingroup engines
*/
class DiscountingFxForwardEngine : public FxForward::engine {
public:
/*! \param ccy1, currency1Discountcurve
Currency 1 and its discount curve.
\param ccy2, currency2Discountcurve
Currency 2 and its discount curve.
\param spotFX
The market spot rate quote, given as units of ccy1
for one unit of ccy2. The spot rate must be given
w.r.t. a settlement equal to the npv date.
\param includeSettlementDateFlows, settlementDate
If includeSettlementDateFlows is true (false), cashflows
on the settlementDate are (not) included in the NPV.
If not given the settlement date is set to the
npv date.
\param npvDate
Discount to this date. If not given the npv date
is set to the evaluation date
*/
DiscountingFxForwardEngine(const Currency& ccy1, const Handle<YieldTermStructure>& currency1Discountcurve,
const Currency& ccy2, const Handle<YieldTermStructure>& currency2Discountcurve,
const Handle<Quote>& spotFX,
boost::optional<bool> includeSettlementDateFlows = boost::none,
const Date& settlementDate = Date(), const Date& npvDate = Date());
void calculate() const;
const Handle<YieldTermStructure>& currency1Discountcurve() const { return currency1Discountcurve_; }
const Handle<YieldTermStructure>& currency2Discountcurve() const { return currency2Discountcurve_; }
const Currency& currency1() const { return ccy1_; }
const Currency& currency2() const { return ccy2_; }
const Handle<Quote>& spotFX() const { return spotFX_; }
private:
Currency ccy1_;
Handle<YieldTermStructure> currency1Discountcurve_;
Currency ccy2_;
Handle<YieldTermStructure> currency2Discountcurve_;
Handle<Quote> spotFX_;
boost::optional<bool> includeSettlementDateFlows_;
Date settlementDate_;
Date npvDate_;
};
} // namespace QuantExt
#endif | 39.543478 | 110 | 0.707257 | [
"model"
] |
cdda92465133084033b0feb667444509a0e28f9a | 519 | cpp | C++ | codeforces/1253c.cpp | sogapalag/problems | 0ea7d65448e1177f8b3f81124a82d187980d659c | [
"MIT"
] | 1 | 2020-04-04T14:56:12.000Z | 2020-04-04T14:56:12.000Z | codeforces/1253c.cpp | sogapalag/problems | 0ea7d65448e1177f8b3f81124a82d187980d659c | [
"MIT"
] | null | null | null | codeforces/1253c.cpp | sogapalag/problems | 0ea7d65448e1177f8b3f81124a82d187980d659c | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
using ll=long long;
void solve() {
int n, m;
cin >> n >> m;
vector<int> a(n);
for (auto& x: a) {
cin >> x;
}
sort(a.begin(), a.end());
vector<ll> sum(n+1), res(n+1);
for (int i = 0; i < n; i++) {
sum[i+1] = sum[i] + a[i];
res[i+1] = sum[i+1] + (i+1>=m? res[i+1-m] : 0);
cout << res[i+1] << ' ';
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
solve();
cout << endl;
}
| 18.535714 | 55 | 0.447013 | [
"vector"
] |
cddb65103ad5fe54e6d89f3ab766f13e1c65cd12 | 38,229 | cpp | C++ | parser/mpParserBase.cpp | Silverlan/muparserx | 1d4656bd671ab856a79f767c483a78c0a036918b | [
"BSD-2-Clause"
] | 1 | 2021-03-07T13:17:37.000Z | 2021-03-07T13:17:37.000Z | parser/mpParserBase.cpp | Silverlan/muparserx | 1d4656bd671ab856a79f767c483a78c0a036918b | [
"BSD-2-Clause"
] | null | null | null | parser/mpParserBase.cpp | Silverlan/muparserx | 1d4656bd671ab856a79f767c483a78c0a036918b | [
"BSD-2-Clause"
] | null | null | null | /** \file
\brief Implementation of the muParserX engine.
<pre>
__________ ____ ___
_____ __ _\______ \_____ _______ ______ __________\ \/ /
/ \| | \ ___/\__ \\_ __ \/ ___// __ \_ __ \ /
| Y Y \ | / | / __ \| | \/\___ \\ ___/| | \/ \
|__|_| /____/|____| (____ /__| /____ >\___ >__| /___/\ \
\/ \/ \/ \/ \_/
Copyright (C) 2016 Ingo Berg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
</pre>
*/
#include "mpParserBase.h"
#include <cmath>
#include <memory>
#include <vector>
#include <sstream>
#include "utGeneric.h"
#include "mpDefines.h"
#include "mpIfThenElse.h"
#include "mpScriptTokens.h"
using namespace std;
MUP_NAMESPACE_START
//------------------------------------------------------------------------------
const char_type *g_sCmdCode[] = {
_T("BRCK. OPEN "),
_T("BRCK. CLOSE "),
_T("IDX OPEN "),
_T("IDX CLOSE "),
_T("CURLY BRCK. OPEN "),
_T("CURLY BRCK. CLOSE"),
_T("ARG_SEP "),
_T("IF "),
_T("ELSE "),
_T("ENDIF "),
_T("JMP "),
_T("VAL "),
_T("FUNC "),
_T("OPRT_BIN "),
_T("OPRT_IFX "),
_T("OPRT_PFX "),
_T("END "),
_T("SCR_ENDL "),
_T("SCR_CMT "),
_T("SCR_WHILE "),
_T("SCR_GOTO "),
_T("SCR_LABEL "),
_T("SCR_FOR "),
_T("SCR_IF "),
_T("SCR_ELSE "),
_T("SCR_ELIF "),
_T("SCR_ENDIF "),
_T("SCR_FUNC "),
_T("UNKNOWN "),
nullptr };
//------------------------------------------------------------------------------
bool ParserXBase::s_bDumpStack = false;
bool ParserXBase::s_bDumpRPN = false;
//------------------------------------------------------------------------------
/** \brief Identifiers for built in binary operators.
When defining custom binary operators with AddOprt(...) make sure not to choose
names conflicting with these definitions.
*/
const char_type* ParserXBase::c_DefaultOprt[] = {
_T("("),
_T(")"),
_T("["),
_T("]"),
_T("{"),
_T("}"),
_T(","),
_T("?"),
_T(":"),
0 };
//------------------------------------------------------------------------------
/** \brief Default constructor. */
ParserXBase::ParserXBase()
:m_FunDef()
, m_PostOprtDef()
, m_InfixOprtDef()
, m_OprtDef()
, m_valDef()
, m_varDef()
, m_pParserEngine(&ParserXBase::ParseFromString)
, m_pTokenReader()
, m_valDynVarShadow()
, m_sNameChars()
, m_sOprtChars()
, m_sInfixOprtChars()
, m_bIsQueryingExprVar(false)
, m_bAutoCreateVar(false)
, m_rpn()
, m_vStackBuffer()
{
InitTokenReader();
}
//---------------------------------------------------------------------------
/** \brief Copy constructor.
\param a_Parser Reference to the other parser object
Implemented by calling Assign(a_Parser)
*/
ParserXBase::ParserXBase(const ParserXBase &a_Parser)
:m_FunDef()
, m_PostOprtDef()
, m_InfixOprtDef()
, m_OprtDef()
, m_valDef()
, m_varDef()
, m_pParserEngine(&ParserXBase::ParseFromString)
, m_pTokenReader()
, m_valDynVarShadow()
, m_sNameChars()
, m_sOprtChars()
, m_sInfixOprtChars()
, m_bAutoCreateVar()
, m_rpn()
, m_vStackBuffer()
{
m_pTokenReader.reset(new TokenReader(this));
Assign(a_Parser);
}
//---------------------------------------------------------------------------
/** \brief Destructor.
\throw nothrow
*/
ParserXBase::~ParserXBase()
{
// It is important to release the stack buffer before
// releasing the value cache. Since it may contain
// Values referencing the cache.
m_vStackBuffer.clear();
m_cache.ReleaseAll();
}
//---------------------------------------------------------------------------
/** \brief Assignement operator.
\param a_Parser Object to copy to this.
\return *this
\throw nothrow
Implemented by calling Assign(a_Parser). Self assignement is suppressed.
*/
ParserXBase& ParserXBase::operator=(const ParserXBase &a_Parser)
{
Assign(a_Parser);
return *this;
}
//---------------------------------------------------------------------------
/** \brief Copy state of a parser object to this.
\param a_Parser the source object.
Clears Variables and Functions of this parser.
Copies the states of all internal variables.
Resets parse function to string parse mode.
*/
void ParserXBase::Assign(const ParserXBase &ref)
{
if (&ref == this)
return;
// Don't copy bytecode instead cause the parser to create new bytecode
// by resetting the parse function.
ReInit();
m_pTokenReader.reset(ref.m_pTokenReader->Clone(this));
m_OprtDef = ref.m_OprtDef;
m_FunDef = ref.m_FunDef;
m_PostOprtDef = ref.m_PostOprtDef;
m_InfixOprtDef = ref.m_InfixOprtDef;
m_valDef = ref.m_valDef;
m_valDynVarShadow = ref.m_valDynVarShadow;
m_varDef = ref.m_varDef; // Copy user defined variables
// Copy charsets
m_sNameChars = ref.m_sNameChars;
m_sOprtChars = ref.m_sOprtChars;
m_sInfixOprtChars = ref.m_sInfixOprtChars;
m_bAutoCreateVar = ref.m_bAutoCreateVar;
// Things that should not be copied:
// - m_vStackBuffer
// - m_cache
// - m_rpn
}
//---------------------------------------------------------------------------
/** \brief Evaluate the expression.
\pre A formula must be set.
\pre Variables must have been set (if needed)
\sa SetExpr
\return The evaluation result
\throw ParseException if no Formula is set or in case of any other error related to the formula.
A note on const correctness:
I consider it important that Calc is a const function.
Due to caching operations Calc changes only the state of internal variables with one exception
m_UsedVar this is reset during string parsing and accessible from the outside. Instead of making
Calc non const GetExprVar is non const because it explicitely calls Eval() forcing this update.
*/
const IValue& ParserXBase::Eval() const
{
return (this->*m_pParserEngine)();
}
//---------------------------------------------------------------------------
/** \brief Return the strings of all Operator identifiers.
\return Returns a pointer to the c_DefaultOprt array of const char *.
\throw nothrow
GetOprt is a const function returning a pinter to an array of const char pointers.
*/
const char_type** ParserXBase::GetOprtDef() const
{
return (const char_type **)(&c_DefaultOprt[0]);
}
//---------------------------------------------------------------------------
/** \brief Define the set of valid characters to be used in names of
functions, variables, constants.
*/
void ParserXBase::DefineNameChars(const char_type *a_szCharset)
{
m_sNameChars = a_szCharset;
}
//---------------------------------------------------------------------------
/** \brief Define the set of valid characters to be used in names of
binary operators and postfix operators.
\param a_szCharset A string containing all characters that can be used
in operator identifiers.
*/
void ParserXBase::DefineOprtChars(const char_type *a_szCharset)
{
m_sOprtChars = a_szCharset;
}
//---------------------------------------------------------------------------
/** \brief Define the set of valid characters to be used in names of
infix operators.
\param a_szCharset A string containing all characters that can be used
in infix operator identifiers.
*/
void ParserXBase::DefineInfixOprtChars(const char_type *a_szCharset)
{
m_sInfixOprtChars = a_szCharset;
}
//---------------------------------------------------------------------------
/** \brief Virtual function that defines the characters allowed in name identifiers.
\sa #ValidOprtChars, #ValidPrefixOprtChars
*/
const char_type* ParserXBase::ValidNameChars() const
{
MUP_VERIFY(m_sNameChars.size());
return m_sNameChars.c_str();
}
//---------------------------------------------------------------------------
/** \brief Virtual function that defines the characters allowed in operator definitions.
\sa #ValidNameChars, #ValidPrefixOprtChars
*/
const char_type* ParserXBase::ValidOprtChars() const
{
MUP_VERIFY(m_sOprtChars.size());
return m_sOprtChars.c_str();
}
//---------------------------------------------------------------------------
/** \brief Virtual function that defines the characters allowed in infix operator definitions.
\sa #ValidNameChars, #ValidOprtChars
*/
const char_type* ParserXBase::ValidInfixOprtChars() const
{
MUP_VERIFY(m_sInfixOprtChars.size());
return m_sInfixOprtChars.c_str();
}
//---------------------------------------------------------------------------
/** \brief Initialize the token reader.
\post m_pTokenReader.Get()!=0
\throw nothrow
Create new token reader object and submit pointers to function, operator,
constant and variable definitions.
*/
void ParserXBase::InitTokenReader()
{
m_pTokenReader.reset(new TokenReader(this));
}
//---------------------------------------------------------------------------
/** \brief Reset parser to string parsing mode and clear internal buffers.
\throw nothrow
Resets the token reader.
*/
void ParserXBase::ReInit() const
{
m_pParserEngine = &ParserXBase::ParseFromString;
m_pTokenReader->ReInit();
m_rpn.Reset();
m_vStackBuffer.clear();
m_nPos = 0;
}
//---------------------------------------------------------------------------
/** \brief Adds a new package to the parser.
The parser becomes the owner of the package pointer and is responsible for
its deletion.
*/
void ParserXBase::AddPackage(IPackage *p)
{
p->AddToParser(this);
}
//---------------------------------------------------------------------------
/** \brief Add a value reader object to muParserX.
\param a_pReader Pointer to the value reader object.
*/
void ParserXBase::AddValueReader(IValueReader *a_pReader)
{
m_pTokenReader->AddValueReader(a_pReader);
}
//---------------------------------------------------------------------------
/** \brief Check if a given name contains invalid characters.
\param a_strName The name to check
\param a_szCharSet The characterset
\throw ParserException if the name contains invalid charakters.
*/
void ParserXBase::CheckName(const string_type &a_strName,
const string_type &a_szCharSet) const
{
if (!a_strName.length() ||
(a_strName.find_first_not_of(a_szCharSet) != string_type::npos) ||
(a_strName[0] >= (char_type)'0' && a_strName[0] <= (char_type)'9'))
{
Error(ecINVALID_NAME);
}
}
//---------------------------------------------------------------------------
/** \brief Set the mathematical expression.
\param a_sExpr String with the expression
\throw ParserException in case of syntax errors.
Triggers first time calculation thus the creation of the bytecode and
scanning of used variables.
*/
void ParserXBase::SetExpr(const string_type &a_sExpr)
{
m_pTokenReader->SetExpr(a_sExpr);
ReInit();
}
//---------------------------------------------------------------------------
/** \brief Add a user defined variable.
\param a_sName The variable name
\param a_Var The variable to be added to muParserX
*/
void ParserXBase::DefineVar(const string_type &ident, const Variable &var)
{
CheckName(ident, ValidNameChars());
CheckForEntityExistence(ident, ecVARIABLE_DEFINED);
m_varDef[ident] = ptr_tok_type(var.Clone());
}
void ParserXBase::CheckForEntityExistence(const string_type &ident, EErrorCodes error_code)
{
if (IsVarDefined(ident) ||
IsConstDefined(ident) ||
IsFunDefined(ident) ||
IsOprtDefined(ident) ||
IsPostfixOprtDefined(ident) ||
IsInfixOprtDefined(ident))
throw ParserError(ErrorContext(error_code, 0, ident));
}
//---------------------------------------------------------------------------
/** \brief Define a parser Constant.
\param a_sName The name of the constant
\param a_Val Const reference to the constants value
Parser constants are handed over by const reference as opposed to variables
which are handed over by reference. Consequently the parser can not change
their value.
*/
void ParserXBase::DefineConst(const string_type &ident, const Value &val)
{
CheckName(ident, ValidNameChars());
CheckForEntityExistence(ident, ecCONSTANT_DEFINED);
m_valDef[ident] = ptr_tok_type(val.Clone());
}
//---------------------------------------------------------------------------
/** \brief Add a callback object to the parser.
\param a_pFunc Pointer to the intance of a parser callback object
representing the function.
\sa GetFunDef, functions
The parser takes ownership over the callback object.
*/
void ParserXBase::DefineFun(const ptr_cal_type &fun)
{
if (IsFunDefined(fun->GetIdent()))
throw ParserError(ErrorContext(ecFUNOPRT_DEFINED, 0, fun->GetIdent()));
fun->SetParent(this);
m_FunDef[fun->GetIdent()] = ptr_tok_type(fun->Clone());
}
//---------------------------------------------------------------------------
/** \brief Define a binary operator.
\param a_pCallback Pointer to the callback object
*/
void ParserXBase::DefineOprt(const TokenPtr<IOprtBin> &oprt)
{
if (IsOprtDefined(oprt->GetIdent()))
throw ParserError(ErrorContext(ecFUNOPRT_DEFINED, 0, oprt->GetIdent()));
oprt->SetParent(this);
m_OprtDef[oprt->GetIdent()] = ptr_tok_type(oprt->Clone());
}
//---------------------------------------------------------------------------
/** \brief Add a user defined operator.
\post Will reset the Parser to string parsing mode.
\param a_pOprt Pointer to a unary postfix operator object. The parser will
become the new owner of this object hence will destroy it.
*/
void ParserXBase::DefinePostfixOprt(const TokenPtr<IOprtPostfix> &oprt)
{
if (IsPostfixOprtDefined(oprt->GetIdent()))
throw ParserError(ErrorContext(ecFUNOPRT_DEFINED, 0, oprt->GetIdent()));
// Operator is not added yet, add it.
oprt->SetParent(this);
m_PostOprtDef[oprt->GetIdent()] = ptr_tok_type(oprt->Clone());
}
//---------------------------------------------------------------------------
/** \brief Add a user defined operator.
\param a_pOprt Pointer to a unary postfix operator object. The parser will
become the new owner of this object hence will destroy it.
*/
void ParserXBase::DefineInfixOprt(const TokenPtr<IOprtInfix> &oprt)
{
if (IsInfixOprtDefined(oprt->GetIdent()))
throw ParserError(ErrorContext(ecFUNOPRT_DEFINED, 0, oprt->GetIdent()));
// Function is not added yet, add it.
oprt->SetParent(this);
m_InfixOprtDef[oprt->GetIdent()] = ptr_tok_type(oprt->Clone());
}
//---------------------------------------------------------------------------
void ParserXBase::RemoveVar(const string_type &ident)
{
m_varDef.erase(ident);
ReInit();
}
//---------------------------------------------------------------------------
void ParserXBase::RemoveConst(const string_type &ident)
{
m_valDef.erase(ident);
ReInit();
}
//---------------------------------------------------------------------------
void ParserXBase::RemoveFun(const string_type &ident)
{
m_FunDef.erase(ident);
ReInit();
}
//---------------------------------------------------------------------------
void ParserXBase::RemoveOprt(const string_type &ident)
{
m_OprtDef.erase(ident);
ReInit();
}
//---------------------------------------------------------------------------
void ParserXBase::RemovePostfixOprt(const string_type &ident)
{
m_PostOprtDef.erase(ident);
ReInit();
}
//---------------------------------------------------------------------------
void ParserXBase::RemoveInfixOprt(const string_type &ident)
{
m_InfixOprtDef.erase(ident);
ReInit();
}
//---------------------------------------------------------------------------
bool ParserXBase::IsVarDefined(const string_type &ident) const
{
return m_varDef.find(ident) != m_varDef.end();
}
//---------------------------------------------------------------------------
bool ParserXBase::IsConstDefined(const string_type &ident) const
{
return m_valDef.find(ident) != m_valDef.end();
}
//---------------------------------------------------------------------------
bool ParserXBase::IsFunDefined(const string_type &ident) const
{
return m_FunDef.find(ident) != m_FunDef.end();
}
//---------------------------------------------------------------------------
bool ParserXBase::IsOprtDefined(const string_type &ident) const
{
return m_OprtDef.find(ident) != m_OprtDef.end();
}
//---------------------------------------------------------------------------
bool ParserXBase::IsPostfixOprtDefined(const string_type &ident) const
{
return m_PostOprtDef.find(ident) != m_PostOprtDef.end();
}
//---------------------------------------------------------------------------
bool ParserXBase::IsInfixOprtDefined(const string_type &ident) const
{
return m_InfixOprtDef.find(ident) != m_InfixOprtDef.end();
}
//---------------------------------------------------------------------------
/** \brief Return a map containing the used variables only. */
const var_maptype& ParserXBase::GetExprVar() const
{
utils::scoped_setter<bool> guard(m_bIsQueryingExprVar, true);
// Create RPN, but do not compute the result or switch to RPN
// parsing mode. The expression may contain yet to be defined variables.
CreateRPN();
return m_pTokenReader->GetUsedVar();
}
//---------------------------------------------------------------------------
/** \brief Return a map containing the used variables only. */
const var_maptype& ParserXBase::GetVar() const
{
return m_varDef;
}
//---------------------------------------------------------------------------
/** \brief Return a map containing all parser constants. */
const val_maptype& ParserXBase::GetConst() const
{
return m_valDef;
}
//---------------------------------------------------------------------------
/** \brief Return prototypes of all parser functions.
\return #m_FunDef
\sa FunProt, functions
\throw nothrow
The return type is a map of the public type #funmap_type containing the prototype
definitions for all numerical parser functions. String functions are not part of
this map. The Prototype definition is encapsulated in objects of the class FunProt
one per parser function each associated with function names via a map construct.
*/
const fun_maptype& ParserXBase::GetFunDef() const
{
return m_FunDef;
}
//---------------------------------------------------------------------------
/** \brief Retrieve the mathematical expression. */
const string_type& ParserXBase::GetExpr() const
{
return m_pTokenReader->GetExpr();
}
//---------------------------------------------------------------------------
/** \brief Get the version number of muParserX.
\return A string containing the version number of muParserX.
*/
string_type ParserXBase::GetVersion()
{
return MUP_PARSER_VERSION;
}
//---------------------------------------------------------------------------
void ParserXBase::ApplyRemainingOprt(Stack<ptr_tok_type> &stOpt) const
{
while (stOpt.size() &&
stOpt.top()->GetCode() != cmBO &&
stOpt.top()->GetCode() != cmIO &&
stOpt.top()->GetCode() != cmCBO &&
stOpt.top()->GetCode() != cmIF)
{
ptr_tok_type &op = stOpt.top();
switch (op->GetCode())
{
case cmOPRT_INFIX:
case cmOPRT_BIN: ApplyFunc(stOpt, 2); break;
case cmELSE: ApplyIfElse(stOpt); break;
default: Error(ecINTERNAL_ERROR);
} // switch operator token type
} // While operator stack not empty
}
//---------------------------------------------------------------------------
/** \brief Simulates the call of a parser function with its corresponding arguments.
\param a_stOpt The operator stack
\param a_stVal The value stack
\param a_iArgCount The number of function arguments
*/
void ParserXBase::ApplyFunc(Stack<ptr_tok_type> &a_stOpt,
int a_iArgCount) const
{
if (a_stOpt.empty())
return;
ptr_tok_type tok = a_stOpt.pop();
ICallback *pFun = tok->AsICallback();
int iArgCount = (pFun->GetArgc() >= 0) ? pFun->GetArgc() : a_iArgCount;
pFun->SetNumArgsPresent(iArgCount);
m_nPos -= (iArgCount - 1);
m_rpn.Add(tok);
}
//---------------------------------------------------------------------------
/** \brief Simulates the effect of the execution of an if-then-else block.
*/
void ParserXBase::ApplyIfElse(Stack<ptr_tok_type> &a_stOpt) const
{
while (a_stOpt.size() && a_stOpt.top()->GetCode() == cmELSE)
{
MUP_VERIFY(a_stOpt.size() > 0);
MUP_VERIFY(m_nPos >= 3);
MUP_VERIFY(a_stOpt.top()->GetCode() == cmELSE);
ptr_tok_type opElse = a_stOpt.pop();
ptr_tok_type opIf = a_stOpt.pop();
MUP_VERIFY(opElse->GetCode() == cmELSE)
MUP_VERIFY(opIf->GetCode() == cmIF)
// If then else hat 3 argumente und erzeugt einen rรผckgabewert (3-1=2)
m_nPos -= 2;
m_rpn.Add(ptr_tok_type(new TokenIfThenElse(cmENDIF)));
}
}
//---------------------------------------------------------------------------
void ParserXBase::DumpRPN() const
{
m_rpn.AsciiDump();
}
//---------------------------------------------------------------------------
void ParserXBase::CreateRPN() const
{
if (!m_pTokenReader->GetExpr().length())
Error(ecUNEXPECTED_EOF, 0);
// The Stacks take the ownership over the tokens
Stack<ptr_tok_type> stOpt;
Stack<int> stArgCount;
Stack<int> stIdxCount;
ptr_tok_type pTok, pTokPrev;
Value val;
ReInit();
for (;;)
{
pTokPrev = pTok;
pTok = m_pTokenReader->ReadNextToken();
#if defined(MUP_DUMP_TOKENS)
console() << pTok->AsciiDump() << endl;
#endif
ECmdCode eCmd = pTok->GetCode();
switch (eCmd)
{
case cmVAL:
m_nPos++;
m_rpn.Add(pTok);
break;
case cmCBC:
case cmIC:
{
ECmdCode eStarter = (ECmdCode)(eCmd - 1);
MUP_VERIFY(eStarter == cmCBO || eStarter == cmIO);
// The argument count for parameterless functions is zero
// by default an opening bracket sets parameter count to 1
// in preparation of arguments to come. If the last token
// was an opening bracket we know better...
if (pTokPrev.Get() != nullptr && pTokPrev->GetCode() == eStarter)
--stArgCount.top();
ApplyRemainingOprt(stOpt);
// if opt is "]" and opta is "[" the bracket content has been evaluated.
// Now check whether there is an index operator on the stack.
if (stOpt.size() && stOpt.top()->GetCode() == eStarter)
{
//
// Find out how many dimensions were used in the index operator.
//
int iArgc = stArgCount.pop();
stOpt.pop(); // Take opening bracket from stack
ICallback *pOprtIndex = pTok->AsICallback();
MUP_VERIFY(pOprtIndex != nullptr);
pOprtIndex->SetNumArgsPresent(iArgc);
m_rpn.Add(pOprtIndex);
// If this is an index operator there must be something else in the register (the variable to index)
MUP_VERIFY(eCmd != cmIC || m_nPos >= (int)iArgc + 1);
// Reduce the index into the value registers accordingly
m_nPos -= iArgc;
if (eCmd == cmCBC)
{
++m_nPos;
}
} // if opening index bracket is on top of operator stack
}
break;
case cmBC:
{
// The argument count for parameterless functions is zero
// by default an opening bracket sets parameter count to 1
// in preparation of arguments to come. If the last token
// was an opening bracket we know better...
if (pTokPrev.Get() != nullptr && pTokPrev->GetCode() == cmBO)
--stArgCount.top();
ApplyRemainingOprt(stOpt);
// if opt is ")" and opta is "(" the bracket content has been evaluated.
// Now its time to check if there is either a function or a sign pending.
// - Neither the opening nor the closing bracket will be pushed back to
// the operator stack
// - Check if a function is standing in front of the opening bracket,
// if so evaluate it afterwards to apply an infix operator.
if (stOpt.size() && stOpt.top()->GetCode() == cmBO)
{
//
// Here is the stuff to evaluate a function token
//
int iArgc = stArgCount.pop();
stOpt.pop(); // Take opening bracket from stack
if (stOpt.empty())
break;
if ((stOpt.top()->GetCode() != cmFUNC) && (stOpt.top()->GetCode() != cmOPRT_INFIX))
break;
ICallback *pFun = stOpt.top()->AsICallback();
if (pFun->GetArgc() != -1 && iArgc > pFun->GetArgc())
Error(ecTOO_MANY_PARAMS, pTok->GetExprPos(), pFun);
if (iArgc < pFun->GetArgc())
Error(ecTOO_FEW_PARAMS, pTok->GetExprPos(), pFun);
// Apply function, if present
if (stOpt.size() &&
stOpt.top()->GetCode() != cmOPRT_INFIX &&
stOpt.top()->GetCode() != cmOPRT_BIN)
{
ApplyFunc(stOpt, iArgc);
}
}
}
break;
case cmELSE:
ApplyRemainingOprt(stOpt);
m_rpn.Add(pTok);
stOpt.push(pTok);
break;
case cmSCRIPT_NEWLINE:
ApplyRemainingOprt(stOpt);
m_rpn.AddNewline(pTok, m_nPos);
stOpt.clear();
m_nPos = 0;
break;
case cmARG_SEP:
if (stArgCount.empty())
Error(ecUNEXPECTED_COMMA, m_pTokenReader->GetPos() - 1);
++stArgCount.top();
ApplyRemainingOprt(stOpt);
break;
case cmEOE:
ApplyRemainingOprt(stOpt);
m_rpn.Finalize();
break;
case cmIF:
case cmOPRT_BIN:
{
while (stOpt.size() &&
stOpt.top()->GetCode() != cmBO &&
stOpt.top()->GetCode() != cmIO &&
stOpt.top()->GetCode() != cmCBO &&
stOpt.top()->GetCode() != cmELSE &&
stOpt.top()->GetCode() != cmIF)
{
IToken *pOprt1 = stOpt.top().Get();
IToken *pOprt2 = pTok.Get();
MUP_VERIFY(pOprt1 != nullptr && pOprt2 != nullptr);
MUP_VERIFY(pOprt1->AsIPrecedence() && pOprt2->AsIPrecedence());
int nPrec1 = pOprt1->AsIPrecedence()->GetPri(),
nPrec2 = pOprt2->AsIPrecedence()->GetPri();
if (pOprt1->GetCode() == pOprt2->GetCode())
{
// Deal with operator associativity
EOprtAsct eOprtAsct = pOprt1->AsIPrecedence()->GetAssociativity();
if ((eOprtAsct == oaRIGHT && (nPrec1 <= nPrec2)) ||
(eOprtAsct == oaLEFT && (nPrec1 < nPrec2)))
{
break;
}
}
else if (nPrec1 < nPrec2)
{
break;
}
// apply the operator now
// (binary operators are identic to functions with two arguments)
ApplyFunc(stOpt, 2);
} // while ( ... )
if (pTok->GetCode() == cmIF)
m_rpn.Add(pTok);
stOpt.push(pTok);
}
break;
//
// Postfix Operators
//
case cmOPRT_POSTFIX:
MUP_VERIFY(m_nPos);
m_rpn.Add(pTok);
break;
case cmCBO:
case cmIO:
case cmBO:
stOpt.push(pTok);
stArgCount.push(1);
break;
//
// Functions
//
case cmOPRT_INFIX:
case cmFUNC:
{
ICallback *pFunc = pTok->AsICallback();
MUP_VERIFY(pFunc != nullptr);
stOpt.push(pTok);
}
break;
default:
Error(ecINTERNAL_ERROR);
} // switch Code
if (ParserXBase::s_bDumpStack)
{
StackDump(stOpt);
}
if (pTok->GetCode() == cmEOE)
break;
} // for (all tokens)
if (ParserXBase::s_bDumpRPN)
{
m_rpn.AsciiDump();
}
if (m_nPos > 1)
{
Error(ecUNEXPECTED_COMMA, -1);
}
}
//---------------------------------------------------------------------------
/** \brief One of the two main parse functions.
\sa ParseCmdCode(), ParseValue()
Parse expression from input string. Perform syntax checking and create bytecode.
After parsing the string and creating the bytecode the function pointer
#m_pParseFormula will be changed to the second parse routine the uses bytecode instead of string parsing.
*/
const IValue& ParserXBase::ParseFromString() const
{
CreateRPN();
// Umsachalten auf RPN
m_vStackBuffer.assign(m_rpn.GetRequiredStackSize(), ptr_val_type());
for (std::size_t i = 0; i < m_vStackBuffer.size(); ++i)
{
Value *pValue = new Value;
pValue->BindToCache(&m_cache);
m_vStackBuffer[i].Reset(pValue);
}
m_pParserEngine = &ParserXBase::ParseFromRPN;
return (this->*m_pParserEngine)();
}
//---------------------------------------------------------------------------
const IValue& ParserXBase::ParseFromRPN() const
{
ptr_val_type *pStack = &m_vStackBuffer[0];
if (m_rpn.GetSize() == 0)
{
// Passiert bei leeren strings oder solchen, die nur Leerzeichen enthalten
ErrorContext err;
err.Expr = m_pTokenReader->GetExpr();
err.Errc = ecUNEXPECTED_EOF;
err.Pos = 0;
throw ParserError(err);
}
const ptr_tok_type *pRPN = &(m_rpn.GetData()[0]);
int sidx = -1;
std::size_t lenRPN = m_rpn.GetSize();
for (std::size_t i = 0; i < lenRPN; ++i)
{
IToken *pTok = pRPN[i].Get();
ECmdCode eCode = pTok->GetCode();
switch (eCode)
{
case cmSCRIPT_NEWLINE:
sidx = -1;
continue;
case cmVAL:
{
IValue *pVal = static_cast<IValue*>(pTok);
sidx++;
MUP_VERIFY(sidx < (int)m_vStackBuffer.size());
if (pVal->IsVariable())
{
pStack[sidx].Reset(pVal);
}
else
{
ptr_val_type &val = pStack[sidx];
if (val->IsVariable())
val.Reset(m_cache.CreateFromCache());
*val = *(static_cast<IValue*>(pTok));
}
}
continue;
/*
// Deal with:
// - Index operator: [,,,]
// - Array constrution operator: {,,,}
case cmCBC:
{
ICallback *pFun = static_cast<ICallback*>(pTok);
int nArgs = pFun->GetArgsPresent();
sidx -= nArgs - 1;
MUP_VERIFY(sidx >= 0);
ptr_val_type &val = pStack[sidx]; // Pointer to the variable or value beeing indexed
if (val->IsVariable())
{
ptr_val_type buf(m_cache.CreateFromCache());
pFun->Eval(buf, &val, nArgs);
val = buf;
}
else
{
pFun->Eval(val, &val, nArgs);
}
}
continue;
*/
case cmIC:
{
ICallback *pIdxOprt = static_cast<ICallback*>(pTok);
int nArgs = pIdxOprt->GetArgsPresent();
sidx -= nArgs - 1;
MUP_VERIFY(sidx >= 0);
ptr_val_type &idx = pStack[sidx]; // Pointer to the first index
ptr_val_type &val = pStack[--sidx]; // Pointer to the variable or value beeing indexed
pIdxOprt->Eval(val, &idx, nArgs);
}
continue;
case cmCBC:
case cmOPRT_POSTFIX:
case cmFUNC:
case cmOPRT_BIN:
case cmOPRT_INFIX:
{
ICallback *pFun = static_cast<ICallback*>(pTok);
int nArgs = pFun->GetArgsPresent();
sidx -= nArgs - 1;
MUP_VERIFY(sidx >= 0);
ptr_val_type &val = pStack[sidx];
try
{
if (val->IsVariable())
{
ptr_val_type buf(m_cache.CreateFromCache());
pFun->Eval(buf, &val, nArgs);
val = buf;
}
else
{
pFun->Eval(val, &val, nArgs);
}
}
catch (ParserError &exc)
{
// <ibg 20130131> Not too happy about that:
// Multiarg functions may throw specific error codes when evaluating.
// These codes would be converted to ecEVAL here. I omit the conversion
// for certain handpicked errors. (The reason this catch block exists is
// that not all exceptions contain proper metadata when thrown out of
// a function.)
if (exc.GetCode() == ecTOO_FEW_PARAMS ||
exc.GetCode() == ecDOMAIN_ERROR ||
exc.GetCode() == ecOVERFLOW ||
exc.GetCode() == ecINVALID_NUMBER_OF_PARAMETERS ||
exc.GetCode() == ecASSIGNEMENT_TO_VALUE)
{
exc.GetContext().Pos = pFun->GetExprPos();
throw;
}
// </ibg>
else
{
ErrorContext err;
err.Expr = m_pTokenReader->GetExpr();
err.Ident = pFun->GetIdent();
err.Errc = ecEVAL;
err.Pos = pFun->GetExprPos();
err.Hint = exc.GetMsg();
throw ParserError(err);
}
}
catch (MatrixError & /*exc*/)
{
ErrorContext err;
err.Expr = m_pTokenReader->GetExpr();
err.Ident = pFun->GetIdent();
err.Errc = ecMATRIX_DIMENSION_MISMATCH;
err.Pos = pFun->GetExprPos();
throw ParserError(err);
}
}
continue;
case cmIF:
MUP_VERIFY(sidx >= 0);
if (pStack[sidx--]->GetBool() == false)
i += static_cast<TokenIfThenElse*>(pTok)->GetOffset();
continue;
case cmELSE:
case cmJMP:
i += static_cast<TokenIfThenElse*>(pTok)->GetOffset();
continue;
case cmENDIF:
continue;
default:
Error(ecINTERNAL_ERROR);
} // switch token
} // for all RPN tokens
return *pStack[0];
}
//---------------------------------------------------------------------------
void ParserXBase::Error(EErrorCodes a_iErrc, int a_iPos, const IToken *a_pTok) const
{
ErrorContext err;
err.Errc = a_iErrc;
err.Pos = a_iPos;
err.Expr = m_pTokenReader->GetExpr();
err.Ident = (a_pTok) ? a_pTok->GetIdent() : _T("");
throw ParserError(err);
}
//------------------------------------------------------------------------------
/** \brief Clear all user defined variables.
\throw nothrow
Resets the parser to string parsing mode by calling #ReInit.
*/
void ParserXBase::ClearVar()
{
m_varDef.clear();
m_valDynVarShadow.clear();
ReInit();
}
//------------------------------------------------------------------------------
/** \brief Clear the expression.
\throw nothrow
Clear the expression and existing bytecode.
*/
void ParserXBase::ClearExpr()
{
m_pTokenReader->SetExpr(_T(""));
ReInit();
}
//------------------------------------------------------------------------------
/** \brief Clear all function definitions.
\throw nothrow
*/
void ParserXBase::ClearFun()
{
m_FunDef.clear();
ReInit();
}
//------------------------------------------------------------------------------
/** \brief Clear all user defined constants.
\throw nothrow
Both numeric and string constants will be removed from the internal storage.
*/
void ParserXBase::ClearConst()
{
m_valDef.clear();
ReInit();
}
//------------------------------------------------------------------------------
/** \brief Clear all user defined postfix operators.
\throw nothrow
*/
void ParserXBase::ClearPostfixOprt()
{
m_PostOprtDef.clear();
ReInit();
}
//------------------------------------------------------------------------------
/** \brief Clear all user defined binary operators.
\throw nothrow
*/
void ParserXBase::ClearOprt()
{
m_OprtDef.clear();
ReInit();
}
//------------------------------------------------------------------------------
/** \brief Clear the user defined Prefix operators.
\throw nothrow
*/
void ParserXBase::ClearInfixOprt()
{
m_InfixOprtDef.clear();
ReInit();
}
//------------------------------------------------------------------------------
void ParserXBase::EnableAutoCreateVar(bool bStat)
{
m_bAutoCreateVar = bStat;
}
//------------------------------------------------------------------------------
void ParserXBase::EnableOptimizer(bool bStat)
{
m_rpn.EnableOptimizer(bStat);
}
//---------------------------------------------------------------------------
/** \brief Enable the dumping of bytecode amd stack content on the console.
\param bDumpCmd Flag to enable dumping of the current bytecode to the console.
\param bDumpStack Flag to enable dumping of the stack content is written to the console.
This function is for debug purposes only!
*/
void ParserXBase::EnableDebugDump(bool bDumpRPN, bool bDumpStack)
{
ParserXBase::s_bDumpRPN = bDumpRPN;
ParserXBase::s_bDumpStack = bDumpStack;
}
//------------------------------------------------------------------------------
bool ParserXBase::IsAutoCreateVarEnabled() const
{
return m_bAutoCreateVar;
}
//------------------------------------------------------------------------------
/** \brief Dump stack content.
This function is used for debugging only.
*/
void ParserXBase::StackDump(const Stack<ptr_tok_type> &a_stOprt) const
{
using std::cout;
Stack<ptr_tok_type> stOprt(a_stOprt);
string_type sInfo = _T("StackDump> ");
console() << sInfo;
if (stOprt.empty())
console() << _T("\n") << sInfo << _T("Operator stack is empty.\n");
else
console() << _T("\n") << sInfo << _T("Operator stack:\n");
while (!stOprt.empty())
{
ptr_tok_type tok = stOprt.pop();
console() << sInfo << _T(" ") << g_sCmdCode[tok->GetCode()] << _T(" \"") << tok->GetIdent() << _T("\" \n");
}
console() << endl;
}
} // namespace mu
| 29.361751 | 110 | 0.565592 | [
"object",
"vector"
] |
cddd8b248c6dd563333c9399fdd9f28c7c1b8b08 | 40,942 | cc | C++ | FELICITY/Code_Generation/Matrix_Assembly/Unit_Test/Hdiv/RT1_Dim3/Assembly_Code_AutoGen/Basis_Functions/Data_Type_RT1_phi_restricted_to_Omega.cc | brianchowlab/BcLOV4-FEM | f54bd8efa0e0f2c7ca2de4a6688ef1a403376285 | [
"MIT"
] | null | null | null | FELICITY/Code_Generation/Matrix_Assembly/Unit_Test/Hdiv/RT1_Dim3/Assembly_Code_AutoGen/Basis_Functions/Data_Type_RT1_phi_restricted_to_Omega.cc | brianchowlab/BcLOV4-FEM | f54bd8efa0e0f2c7ca2de4a6688ef1a403376285 | [
"MIT"
] | null | null | null | FELICITY/Code_Generation/Matrix_Assembly/Unit_Test/Hdiv/RT1_Dim3/Assembly_Code_AutoGen/Basis_Functions/Data_Type_RT1_phi_restricted_to_Omega.cc | brianchowlab/BcLOV4-FEM | f54bd8efa0e0f2c7ca2de4a6688ef1a403376285 | [
"MIT"
] | null | null | null | /*
============================================================================================
This class contains data about a given FE function space, and methods for computing
transformations of the local basis functions.
This code references the header files:
matrix_vector_defn.h
matrix_vector_ops.h
geometric_computations.h
basis_function_computations.h
NOTE: portions of this code are automatically generated!
Copyright (c) 01-15-2018, Shawn W. Walker
============================================================================================
*/
/*------------ BEGIN: Auto Generate ------------*/
// define the name of the FE basis function (should be the same as the filename of this file)
#define SpecificFUNC Data_Type_RT1_phi_restricted_to_Omega
#define SpecificFUNC_str "Data_Type_RT1_phi_restricted_to_Omega"
// set the type of function space
#define SPACE_type "CG - raviart_thomas_deg1_dim3"
// set the name of function space
#define SPACE_name "RT1"
// set the Subdomain topological dimension
#define SUB_TD 3
// set the Domain of Integration (DoI) topological dimension
#define DOI_TD 3
// set the geometric dimension
#define GD 3
// set the number of cartesian tuple components (m*n) = 1 * 1
#define NC 1
// NOTE: the (i,j) tuple component is accessed by the linear index k = i + (j-1)*m
// set the number of quad points
#define NQ 10
// set the number of basis functions
#define NB 15
/*------------ END: Auto Generate ------------*/
/* C++ (Specific) FE Function class definition */
class SpecificFUNC: public ABSTRACT_FEM_Function_Class // derive from base class
{
public:
int* Elem_DoF[NB]; // element DoF list
// data structure containing information on the function evaluations.
// Note: this data is evaluated at several quadrature points!
// vector valued H(div) basis functions
VEC_3x1 Func_vv_Value[NB][NQ];
// divergence of vector valued H(div) basis functions
SCALAR Func_vv_Div[NB][NQ];
// constructor
SpecificFUNC ();
~SpecificFUNC (); // destructor
void Setup_Function_Space(const mxArray*);
void Get_Local_to_Global_DoFmap(const int&, int*) const;
// need the "const" to ENSURE that nothing in this object will change!
void Transform_Basis_Functions();
const CLASS_geom_Omega_embedded_in_Omega_restricted_to_Omega* Mesh;
private:
void Get_Basis_Sign_Change(const double Mesh_Orient[SUB_TD+1], double Basis_Sign[NB]) const;
void Map_Basis_p1();
};
/*------------ BEGIN: Auto Generate ------------*/
/***************************************************************************************/
/* constructor */
SpecificFUNC::SpecificFUNC () :
ABSTRACT_FEM_Function_Class () // call the base class constructor
{
Name = (char*) SpecificFUNC_str;
Type = (char*) SPACE_type;
Space_Name = (char*) SPACE_name;
Sub_TopDim = SUB_TD;
DoI_TopDim = DOI_TD;
GeoDim = GD;
Num_Basis = NB;
Num_Comp = NC;
Num_QP = NQ;
Mesh = NULL;
// init DoF information to NULL
for (int basis_i = 0; (basis_i < Num_Basis); basis_i++)
Elem_DoF[basis_i] = NULL;
// init everything to zero
for (int qp_i = 0; (qp_i < Num_QP); qp_i++)
for (int basis_i = 0; (basis_i < Num_Basis); basis_i++)
Func_vv_Value[basis_i][qp_i].Set_To_Zero();
for (int qp_i = 0; (qp_i < Num_QP); qp_i++)
for (int basis_i = 0; (basis_i < Num_Basis); basis_i++)
Func_vv_Div[basis_i][qp_i].Set_To_Zero();
}
/***************************************************************************************/
/*------------ END: Auto Generate ------------*/
/***************************************************************************************/
/* DE-structor */
SpecificFUNC::~SpecificFUNC ()
{
}
/***************************************************************************************/
/***************************************************************************************/
/* put incoming function data from MATLAB into a nice struct */
void SpecificFUNC::Setup_Function_Space(const mxArray* Elem) // inputs
{
Init_Function_Space(Elem);
// split up the columns of the element data
Elem_DoF[0] = (int *) mxGetPr(Elem);
for (int basis_i = 1; (basis_i < Num_Basis); basis_i++)
Elem_DoF[basis_i] = Elem_DoF[basis_i-1] + Num_Elem;
}
/***************************************************************************************/
/***************************************************************************************/
/* get the local DoFs on the given element.
Note: elem_index is in the C-style (i.e. 0 <= elem_index <= Num_Elem - 1),
Indices is in the MATLAB-style (i.e. 1 <= Indices[:] <= max(Elem_DoF)). */
void SpecificFUNC::Get_Local_to_Global_DoFmap(const int& elem_index, int* Indices) const // inputs
{
/* error check: */
if (elem_index < 0)
{
mexPrintf("ERROR: Given element index #%d is not positive. It must be > 0!\n",elem_index+1);
mexPrintf("ERROR: There is an issue with the Finite Element Space = %s!\n",Space_Name);
mexErrMsgTxt("ERROR: Make sure your inputs are valid!");
}
else if (elem_index >= Num_Elem)
{
mexPrintf("ERROR: Given element index #%d exceeds the number of elements in the finite element (FE) space.\n",elem_index+1);
mexPrintf("It must be <= %d! OR Your FE space DoFmap is not defined correctly!\n",Num_Elem);
mexPrintf(" For example, the number of rows in DoFmap should *equal*\n");
mexPrintf(" the number of mesh elements in the (sub)-domain.\n");
mexPrintf("ERROR: There is an issue with the Finite Element Space = %s!\n",Space_Name);
mexErrMsgTxt("ERROR: Make sure your inputs are valid!");
}
// get local to global index map for the current element
for (int basis_i = 0; (basis_i < Num_Basis); basis_i++)
{
int DoF_index = Elem_DoF[basis_i][elem_index] - 1; // shifted for C - style indexing
Indices[basis_i] = DoF_index;
}
}
/***************************************************************************************/
/*------------ BEGIN: Auto Generate ------------*/
/***************************************************************************************/
/* get sign changes to apply to basis functions to account for changes in orientation
(with respect to the "standard" reference orientation) on the current mesh element. */
void SpecificFUNC::Get_Basis_Sign_Change(const double Mesh_Orient[SUB_TD+1], double Basis_Sign[NB]) const
{
// get facet (face) orientation "signature" (takes values from 0 to 15)
const int Facet_Orientation_Signature = (int) ( (Mesh_Orient[0] < 0.0) * 1 +
(Mesh_Orient[1] < 0.0) * 2 +
(Mesh_Orient[2] < 0.0) * 4 +
(Mesh_Orient[3] < 0.0) * 8 );
// BEGIN: determine which basis functions must change their signs
/* 3-D tetrahedron element has 4 facets */
switch (Facet_Orientation_Signature)
{
case 1: // (-1, 1, 1, 1) facet orientation
Basis_Sign[0] = -1.0;
Basis_Sign[1] = -1.0;
Basis_Sign[2] = -1.0;
break;
case 2: // (1, -1, 1, 1) facet orientation
Basis_Sign[3] = -1.0;
Basis_Sign[4] = -1.0;
Basis_Sign[5] = -1.0;
break;
case 3: // (-1, -1, 1, 1) facet orientation
Basis_Sign[0] = -1.0;
Basis_Sign[1] = -1.0;
Basis_Sign[2] = -1.0;
Basis_Sign[3] = -1.0;
Basis_Sign[4] = -1.0;
Basis_Sign[5] = -1.0;
break;
case 4: // (1, 1, -1, 1) facet orientation
Basis_Sign[6] = -1.0;
Basis_Sign[7] = -1.0;
Basis_Sign[8] = -1.0;
break;
case 5: // (-1, 1, -1, 1) facet orientation
Basis_Sign[0] = -1.0;
Basis_Sign[1] = -1.0;
Basis_Sign[2] = -1.0;
Basis_Sign[6] = -1.0;
Basis_Sign[7] = -1.0;
Basis_Sign[8] = -1.0;
break;
case 6: // (1, -1, -1, 1) facet orientation
Basis_Sign[3] = -1.0;
Basis_Sign[4] = -1.0;
Basis_Sign[5] = -1.0;
Basis_Sign[6] = -1.0;
Basis_Sign[7] = -1.0;
Basis_Sign[8] = -1.0;
break;
case 7: // (-1, -1, -1, 1) facet orientation
Basis_Sign[0] = -1.0;
Basis_Sign[1] = -1.0;
Basis_Sign[2] = -1.0;
Basis_Sign[3] = -1.0;
Basis_Sign[4] = -1.0;
Basis_Sign[5] = -1.0;
Basis_Sign[6] = -1.0;
Basis_Sign[7] = -1.0;
Basis_Sign[8] = -1.0;
break;
case 8: // (1, 1, 1, -1) facet orientation
Basis_Sign[9] = -1.0;
Basis_Sign[10] = -1.0;
Basis_Sign[11] = -1.0;
break;
case 9: // (-1, 1, 1, -1) facet orientation
Basis_Sign[0] = -1.0;
Basis_Sign[1] = -1.0;
Basis_Sign[2] = -1.0;
Basis_Sign[9] = -1.0;
Basis_Sign[10] = -1.0;
Basis_Sign[11] = -1.0;
break;
case 10: // (1, -1, 1, -1) facet orientation
Basis_Sign[3] = -1.0;
Basis_Sign[4] = -1.0;
Basis_Sign[5] = -1.0;
Basis_Sign[9] = -1.0;
Basis_Sign[10] = -1.0;
Basis_Sign[11] = -1.0;
break;
case 11: // (-1, -1, 1, -1) facet orientation
Basis_Sign[0] = -1.0;
Basis_Sign[1] = -1.0;
Basis_Sign[2] = -1.0;
Basis_Sign[3] = -1.0;
Basis_Sign[4] = -1.0;
Basis_Sign[5] = -1.0;
Basis_Sign[9] = -1.0;
Basis_Sign[10] = -1.0;
Basis_Sign[11] = -1.0;
break;
case 12: // (1, 1, -1, -1) facet orientation
Basis_Sign[6] = -1.0;
Basis_Sign[7] = -1.0;
Basis_Sign[8] = -1.0;
Basis_Sign[9] = -1.0;
Basis_Sign[10] = -1.0;
Basis_Sign[11] = -1.0;
break;
case 13: // (-1, 1, -1, -1) facet orientation
Basis_Sign[0] = -1.0;
Basis_Sign[1] = -1.0;
Basis_Sign[2] = -1.0;
Basis_Sign[6] = -1.0;
Basis_Sign[7] = -1.0;
Basis_Sign[8] = -1.0;
Basis_Sign[9] = -1.0;
Basis_Sign[10] = -1.0;
Basis_Sign[11] = -1.0;
break;
case 14: // (1, -1, -1, -1) facet orientation
Basis_Sign[3] = -1.0;
Basis_Sign[4] = -1.0;
Basis_Sign[5] = -1.0;
Basis_Sign[6] = -1.0;
Basis_Sign[7] = -1.0;
Basis_Sign[8] = -1.0;
Basis_Sign[9] = -1.0;
Basis_Sign[10] = -1.0;
Basis_Sign[11] = -1.0;
break;
case 15: // (-1, -1, -1, -1) facet orientation
Basis_Sign[0] = -1.0;
Basis_Sign[1] = -1.0;
Basis_Sign[2] = -1.0;
Basis_Sign[3] = -1.0;
Basis_Sign[4] = -1.0;
Basis_Sign[5] = -1.0;
Basis_Sign[6] = -1.0;
Basis_Sign[7] = -1.0;
Basis_Sign[8] = -1.0;
Basis_Sign[9] = -1.0;
Basis_Sign[10] = -1.0;
Basis_Sign[11] = -1.0;
break;
default: ; // Facet_Orientation_Signature==0 (1, 1, 1, 1) facet orientation
// do nothing; everything is positive already
}
// END: determine which basis functions must change their signs
}
/***************************************************************************************/
/*------------ END: Auto Generate ------------*/
/*------------ BEGIN: Auto Generate ------------*/
/***************************************************************************************/
/* compute the correct local transformation */
void SpecificFUNC::Transform_Basis_Functions()
{
Map_Basis_p1();
}
/***************************************************************************************/
/*------------ END: Auto Generate ------------*/
/*------------ BEGIN: Auto Generate ------------*/
/***************************************************************************************/
/* map basis functions from the standard reference element
to an actual element in the Domain. */
void SpecificFUNC::Map_Basis_p1()
{
/*------------ BEGIN: Auto Generate ------------*/
/* call sub-routine to determine sign flips for H(div) basis functions */
double Basis_Sign[NB] = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0}; // init to all positive (no sign change)
Get_Basis_Sign_Change(Mesh->Orientation, Basis_Sign);
/*------------ END: Auto Generate ------------*/
/*------------ BEGIN: Auto Generate ------------*/
// Local Element defined on Subdomain: CG, raviart_thomas_deg1_dim3
// the Subdomain has topological dimension = 3
// the Domain of Integration has topological dimension = 3
// geometric dimension = 3
// Number of Quadrature Points = 10
// get "Val" of basis functions
VEC_3x1 phi_Val[NQ][NB];
// get "Div" of basis functions
SCALAR phi_Div[NQ][NB];
phi_Val[0][0].Set_Equal_To(2.87223286114884235E+00, 1.59003371985847486E+00, 1.59003371985847486E+00);
phi_Val[0][1].Set_Equal_To(-9.57410953716280710E-01, -1.10543712769036562E+00, -2.42298296084054510E-01);
phi_Val[0][2].Set_Equal_To(-9.57410953716280710E-01, -2.42298296084054510E-01, -1.10543712769036562E+00);
phi_Val[0][3].Set_Equal_To(1.59003371985847486E+00, -2.42298296084054621E-01, -2.42298296084054621E-01);
phi_Val[0][4].Set_Equal_To(1.59003371985847464E+00, -2.42298296084054510E-01, -1.10543712769036562E+00);
phi_Val[0][5].Set_Equal_To(1.59003371985847464E+00, -1.10543712769036562E+00, -2.42298296084054510E-01);
phi_Val[0][6].Set_Equal_To(-9.57410953716281155E-01, 2.30514637749070150E+00, -2.42298296084054621E-01);
phi_Val[0][7].Set_Equal_To(2.87223286114884235E+00, -6.05230030086579163E+00, 1.59003371985847486E+00);
phi_Val[0][8].Set_Equal_To(-9.57410953716280710E-01, 2.30514637749070062E+00, -1.10543712769036562E+00);
phi_Val[0][9].Set_Equal_To(-9.57410953716281155E-01, -2.42298296084054621E-01, 2.30514637749070150E+00);
phi_Val[0][10].Set_Equal_To(-9.57410953716280710E-01, -1.10543712769036562E+00, 2.30514637749070062E+00);
phi_Val[0][11].Set_Equal_To(2.87223286114884235E+00, 1.59003371985847486E+00, -6.05230030086579163E+00);
phi_Val[0][12].Set_Equal_To(9.81269020585914298E+00, -1.83233201594252937E+00, -1.83233201594252937E+00);
phi_Val[0][13].Set_Equal_To(-4.73313541857348988E-16, 4.31569415803155554E+00, -1.19784575537172798E-16);
phi_Val[0][14].Set_Equal_To(-4.73313541857348988E-16, -1.19784575537172798E-16, 4.31569415803155554E+00);
phi_Val[1][0].Set_Equal_To(-1.10543712769036562E+00, -2.42298296084054510E-01, -2.42298296084054510E-01);
phi_Val[1][1].Set_Equal_To(-2.42298296084054510E-01, -1.10543712769036562E+00, -2.42298296084054510E-01);
phi_Val[1][2].Set_Equal_To(-2.42298296084054510E-01, -2.42298296084054510E-01, -1.10543712769036562E+00);
phi_Val[1][3].Set_Equal_To(-6.05230030086579163E+00, 1.59003371985847464E+00, 1.59003371985847464E+00);
phi_Val[1][4].Set_Equal_To(2.30514637749070062E+00, -2.42298296084054510E-01, -1.10543712769036562E+00);
phi_Val[1][5].Set_Equal_To(2.30514637749070062E+00, -1.10543712769036562E+00, -2.42298296084054510E-01);
phi_Val[1][6].Set_Equal_To(1.59003371985847464E+00, -6.05230030086579163E+00, 1.59003371985847464E+00);
phi_Val[1][7].Set_Equal_To(-1.10543712769036562E+00, 2.30514637749070062E+00, -2.42298296084054510E-01);
phi_Val[1][8].Set_Equal_To(-2.42298296084054510E-01, 2.30514637749070062E+00, -1.10543712769036562E+00);
phi_Val[1][9].Set_Equal_To(1.59003371985847464E+00, 1.59003371985847464E+00, -6.05230030086579163E+00);
phi_Val[1][10].Set_Equal_To(-2.42298296084054510E-01, -1.10543712769036562E+00, 2.30514637749070062E+00);
phi_Val[1][11].Set_Equal_To(-1.10543712769036562E+00, -2.42298296084054510E-01, 2.30514637749070062E+00);
phi_Val[1][12].Set_Equal_To(6.14802617397408468E+00, 1.83233201594252915E+00, 1.83233201594252915E+00);
phi_Val[1][13].Set_Equal_To(1.83233201594252915E+00, 6.14802617397408468E+00, 1.83233201594252915E+00);
phi_Val[1][14].Set_Equal_To(1.83233201594252915E+00, 1.83233201594252915E+00, 6.14802617397408468E+00);
phi_Val[2][0].Set_Equal_To(-1.10543712769036562E+00, -2.42298296084054510E-01, -9.57410953716280710E-01);
phi_Val[2][1].Set_Equal_To(-2.42298296084054510E-01, -1.10543712769036562E+00, -9.57410953716280710E-01);
phi_Val[2][2].Set_Equal_To(1.59003371985847486E+00, 1.59003371985847486E+00, 2.87223286114884235E+00);
phi_Val[2][3].Set_Equal_To(2.30514637749070150E+00, -2.42298296084054621E-01, -9.57410953716281155E-01);
phi_Val[2][4].Set_Equal_To(-6.05230030086579163E+00, 1.59003371985847486E+00, 2.87223286114884235E+00);
phi_Val[2][5].Set_Equal_To(2.30514637749070062E+00, -1.10543712769036562E+00, -9.57410953716280710E-01);
phi_Val[2][6].Set_Equal_To(-2.42298296084054621E-01, 2.30514637749070150E+00, -9.57410953716281155E-01);
phi_Val[2][7].Set_Equal_To(-1.10543712769036562E+00, 2.30514637749070062E+00, -9.57410953716280710E-01);
phi_Val[2][8].Set_Equal_To(1.59003371985847486E+00, -6.05230030086579163E+00, 2.87223286114884235E+00);
phi_Val[2][9].Set_Equal_To(-2.42298296084054621E-01, -2.42298296084054621E-01, 1.59003371985847486E+00);
phi_Val[2][10].Set_Equal_To(-2.42298296084054510E-01, -1.10543712769036562E+00, 1.59003371985847464E+00);
phi_Val[2][11].Set_Equal_To(-1.10543712769036562E+00, -2.42298296084054510E-01, 1.59003371985847464E+00);
phi_Val[2][12].Set_Equal_To(4.31569415803155554E+00, -1.19784575537172798E-16, -4.73313541857348988E-16);
phi_Val[2][13].Set_Equal_To(-1.19784575537172798E-16, 4.31569415803155554E+00, -4.73313541857348988E-16);
phi_Val[2][14].Set_Equal_To(-1.83233201594252937E+00, -1.83233201594252937E+00, 9.81269020585914298E+00);
phi_Val[3][0].Set_Equal_To(-1.10543712769036562E+00, -9.57410953716280710E-01, -2.42298296084054510E-01);
phi_Val[3][1].Set_Equal_To(1.59003371985847486E+00, 2.87223286114884235E+00, 1.59003371985847486E+00);
phi_Val[3][2].Set_Equal_To(-2.42298296084054510E-01, -9.57410953716280710E-01, -1.10543712769036562E+00);
phi_Val[3][3].Set_Equal_To(2.30514637749070150E+00, -9.57410953716281155E-01, -2.42298296084054621E-01);
phi_Val[3][4].Set_Equal_To(2.30514637749070062E+00, -9.57410953716280710E-01, -1.10543712769036562E+00);
phi_Val[3][5].Set_Equal_To(-6.05230030086579163E+00, 2.87223286114884235E+00, 1.59003371985847486E+00);
phi_Val[3][6].Set_Equal_To(-2.42298296084054621E-01, 1.59003371985847486E+00, -2.42298296084054621E-01);
phi_Val[3][7].Set_Equal_To(-1.10543712769036562E+00, 1.59003371985847464E+00, -2.42298296084054510E-01);
phi_Val[3][8].Set_Equal_To(-2.42298296084054510E-01, 1.59003371985847464E+00, -1.10543712769036562E+00);
phi_Val[3][9].Set_Equal_To(-2.42298296084054621E-01, -9.57410953716281155E-01, 2.30514637749070150E+00);
phi_Val[3][10].Set_Equal_To(1.59003371985847486E+00, 2.87223286114884235E+00, -6.05230030086579163E+00);
phi_Val[3][11].Set_Equal_To(-1.10543712769036562E+00, -9.57410953716280710E-01, 2.30514637749070062E+00);
phi_Val[3][12].Set_Equal_To(4.31569415803155554E+00, -4.73313541857348988E-16, -1.19784575537172798E-16);
phi_Val[3][13].Set_Equal_To(-1.83233201594252937E+00, 9.81269020585914298E+00, -1.83233201594252937E+00);
phi_Val[3][14].Set_Equal_To(-1.19784575537172798E-16, -4.73313541857348988E-16, 4.31569415803155554E+00);
phi_Val[4][0].Set_Equal_To(0.00000000000000000E+00, -3.00000000000000000E+00, -3.00000000000000000E+00);
phi_Val[4][1].Set_Equal_To(0.00000000000000000E+00, 1.50000000000000000E+00, 4.50000000000000000E+00);
phi_Val[4][2].Set_Equal_To(0.00000000000000000E+00, 4.50000000000000000E+00, 1.50000000000000000E+00);
phi_Val[4][3].Set_Equal_To(6.00000000000000000E+00, -3.00000000000000000E+00, -3.00000000000000000E+00);
phi_Val[4][4].Set_Equal_To(-6.00000000000000000E+00, 4.50000000000000000E+00, 1.50000000000000000E+00);
phi_Val[4][5].Set_Equal_To(-6.00000000000000000E+00, 1.50000000000000000E+00, 4.50000000000000000E+00);
phi_Val[4][6].Set_Equal_To(0.00000000000000000E+00, 3.00000000000000000E+00, -3.00000000000000000E+00);
phi_Val[4][7].Set_Equal_To(0.00000000000000000E+00, 3.00000000000000000E+00, -3.00000000000000000E+00);
phi_Val[4][8].Set_Equal_To(0.00000000000000000E+00, -1.50000000000000000E+00, 1.50000000000000000E+00);
phi_Val[4][9].Set_Equal_To(0.00000000000000000E+00, -3.00000000000000000E+00, 3.00000000000000000E+00);
phi_Val[4][10].Set_Equal_To(0.00000000000000000E+00, 1.50000000000000000E+00, -1.50000000000000000E+00);
phi_Val[4][11].Set_Equal_To(0.00000000000000000E+00, -3.00000000000000000E+00, 3.00000000000000000E+00);
phi_Val[4][12].Set_Equal_To(0.00000000000000000E+00, 0.00000000000000000E+00, 0.00000000000000000E+00);
phi_Val[4][13].Set_Equal_To(0.00000000000000000E+00, 7.50000000000000000E+00, -7.50000000000000000E+00);
phi_Val[4][14].Set_Equal_To(0.00000000000000000E+00, -7.50000000000000000E+00, 7.50000000000000000E+00);
phi_Val[5][0].Set_Equal_To(1.50000000000000000E+00, 0.00000000000000000E+00, 4.50000000000000000E+00);
phi_Val[5][1].Set_Equal_To(-3.00000000000000000E+00, 0.00000000000000000E+00, -3.00000000000000000E+00);
phi_Val[5][2].Set_Equal_To(4.50000000000000000E+00, 0.00000000000000000E+00, 1.50000000000000000E+00);
phi_Val[5][3].Set_Equal_To(3.00000000000000000E+00, 0.00000000000000000E+00, -3.00000000000000000E+00);
phi_Val[5][4].Set_Equal_To(-1.50000000000000000E+00, 0.00000000000000000E+00, 1.50000000000000000E+00);
phi_Val[5][5].Set_Equal_To(3.00000000000000000E+00, 0.00000000000000000E+00, -3.00000000000000000E+00);
phi_Val[5][6].Set_Equal_To(-3.00000000000000000E+00, 6.00000000000000000E+00, -3.00000000000000000E+00);
phi_Val[5][7].Set_Equal_To(1.50000000000000000E+00, -6.00000000000000000E+00, 4.50000000000000000E+00);
phi_Val[5][8].Set_Equal_To(4.50000000000000000E+00, -6.00000000000000000E+00, 1.50000000000000000E+00);
phi_Val[5][9].Set_Equal_To(-3.00000000000000000E+00, 0.00000000000000000E+00, 3.00000000000000000E+00);
phi_Val[5][10].Set_Equal_To(-3.00000000000000000E+00, 0.00000000000000000E+00, 3.00000000000000000E+00);
phi_Val[5][11].Set_Equal_To(1.50000000000000000E+00, 0.00000000000000000E+00, -1.50000000000000000E+00);
phi_Val[5][12].Set_Equal_To(7.50000000000000000E+00, 0.00000000000000000E+00, -7.50000000000000000E+00);
phi_Val[5][13].Set_Equal_To(0.00000000000000000E+00, 0.00000000000000000E+00, 0.00000000000000000E+00);
phi_Val[5][14].Set_Equal_To(-7.50000000000000000E+00, 0.00000000000000000E+00, 7.50000000000000000E+00);
phi_Val[6][0].Set_Equal_To(1.50000000000000000E+00, 4.50000000000000000E+00, 0.00000000000000000E+00);
phi_Val[6][1].Set_Equal_To(4.50000000000000000E+00, 1.50000000000000000E+00, 0.00000000000000000E+00);
phi_Val[6][2].Set_Equal_To(-3.00000000000000000E+00, -3.00000000000000000E+00, 0.00000000000000000E+00);
phi_Val[6][3].Set_Equal_To(3.00000000000000000E+00, -3.00000000000000000E+00, 0.00000000000000000E+00);
phi_Val[6][4].Set_Equal_To(3.00000000000000000E+00, -3.00000000000000000E+00, 0.00000000000000000E+00);
phi_Val[6][5].Set_Equal_To(-1.50000000000000000E+00, 1.50000000000000000E+00, 0.00000000000000000E+00);
phi_Val[6][6].Set_Equal_To(-3.00000000000000000E+00, 3.00000000000000000E+00, 0.00000000000000000E+00);
phi_Val[6][7].Set_Equal_To(1.50000000000000000E+00, -1.50000000000000000E+00, 0.00000000000000000E+00);
phi_Val[6][8].Set_Equal_To(-3.00000000000000000E+00, 3.00000000000000000E+00, 0.00000000000000000E+00);
phi_Val[6][9].Set_Equal_To(-3.00000000000000000E+00, -3.00000000000000000E+00, 6.00000000000000000E+00);
phi_Val[6][10].Set_Equal_To(4.50000000000000000E+00, 1.50000000000000000E+00, -6.00000000000000000E+00);
phi_Val[6][11].Set_Equal_To(1.50000000000000000E+00, 4.50000000000000000E+00, -6.00000000000000000E+00);
phi_Val[6][12].Set_Equal_To(7.50000000000000000E+00, -7.50000000000000000E+00, 0.00000000000000000E+00);
phi_Val[6][13].Set_Equal_To(-7.50000000000000000E+00, 7.50000000000000000E+00, 0.00000000000000000E+00);
phi_Val[6][14].Set_Equal_To(0.00000000000000000E+00, 0.00000000000000000E+00, 0.00000000000000000E+00);
phi_Val[7][0].Set_Equal_To(1.50000000000000000E+00, 0.00000000000000000E+00, 0.00000000000000000E+00);
phi_Val[7][1].Set_Equal_To(-3.00000000000000000E+00, 0.00000000000000000E+00, 0.00000000000000000E+00);
phi_Val[7][2].Set_Equal_To(-3.00000000000000000E+00, 0.00000000000000000E+00, 0.00000000000000000E+00);
phi_Val[7][3].Set_Equal_To(-1.50000000000000000E+00, 0.00000000000000000E+00, 0.00000000000000000E+00);
phi_Val[7][4].Set_Equal_To(3.00000000000000000E+00, 0.00000000000000000E+00, 0.00000000000000000E+00);
phi_Val[7][5].Set_Equal_To(3.00000000000000000E+00, 0.00000000000000000E+00, 0.00000000000000000E+00);
phi_Val[7][6].Set_Equal_To(4.50000000000000000E+00, -6.00000000000000000E+00, 0.00000000000000000E+00);
phi_Val[7][7].Set_Equal_To(1.50000000000000000E+00, -6.00000000000000000E+00, 0.00000000000000000E+00);
phi_Val[7][8].Set_Equal_To(-3.00000000000000000E+00, 6.00000000000000000E+00, 0.00000000000000000E+00);
phi_Val[7][9].Set_Equal_To(4.50000000000000000E+00, 0.00000000000000000E+00, -6.00000000000000000E+00);
phi_Val[7][10].Set_Equal_To(-3.00000000000000000E+00, 0.00000000000000000E+00, 6.00000000000000000E+00);
phi_Val[7][11].Set_Equal_To(1.50000000000000000E+00, 0.00000000000000000E+00, -6.00000000000000000E+00);
phi_Val[7][12].Set_Equal_To(1.50000000000000000E+01, 0.00000000000000000E+00, 0.00000000000000000E+00);
phi_Val[7][13].Set_Equal_To(7.50000000000000000E+00, 0.00000000000000000E+00, 0.00000000000000000E+00);
phi_Val[7][14].Set_Equal_To(7.50000000000000000E+00, 0.00000000000000000E+00, 0.00000000000000000E+00);
phi_Val[8][0].Set_Equal_To(0.00000000000000000E+00, -3.00000000000000000E+00, 0.00000000000000000E+00);
phi_Val[8][1].Set_Equal_To(0.00000000000000000E+00, 1.50000000000000000E+00, 0.00000000000000000E+00);
phi_Val[8][2].Set_Equal_To(0.00000000000000000E+00, -3.00000000000000000E+00, 0.00000000000000000E+00);
phi_Val[8][3].Set_Equal_To(-6.00000000000000000E+00, 4.50000000000000000E+00, 0.00000000000000000E+00);
phi_Val[8][4].Set_Equal_To(6.00000000000000000E+00, -3.00000000000000000E+00, 0.00000000000000000E+00);
phi_Val[8][5].Set_Equal_To(-6.00000000000000000E+00, 1.50000000000000000E+00, 0.00000000000000000E+00);
phi_Val[8][6].Set_Equal_To(0.00000000000000000E+00, -1.50000000000000000E+00, 0.00000000000000000E+00);
phi_Val[8][7].Set_Equal_To(0.00000000000000000E+00, 3.00000000000000000E+00, 0.00000000000000000E+00);
phi_Val[8][8].Set_Equal_To(0.00000000000000000E+00, 3.00000000000000000E+00, 0.00000000000000000E+00);
phi_Val[8][9].Set_Equal_To(0.00000000000000000E+00, 4.50000000000000000E+00, -6.00000000000000000E+00);
phi_Val[8][10].Set_Equal_To(0.00000000000000000E+00, 1.50000000000000000E+00, -6.00000000000000000E+00);
phi_Val[8][11].Set_Equal_To(0.00000000000000000E+00, -3.00000000000000000E+00, 6.00000000000000000E+00);
phi_Val[8][12].Set_Equal_To(0.00000000000000000E+00, 7.50000000000000000E+00, 0.00000000000000000E+00);
phi_Val[8][13].Set_Equal_To(0.00000000000000000E+00, 1.50000000000000000E+01, 0.00000000000000000E+00);
phi_Val[8][14].Set_Equal_To(0.00000000000000000E+00, 7.50000000000000000E+00, 0.00000000000000000E+00);
phi_Val[9][0].Set_Equal_To(0.00000000000000000E+00, 0.00000000000000000E+00, -3.00000000000000000E+00);
phi_Val[9][1].Set_Equal_To(0.00000000000000000E+00, 0.00000000000000000E+00, -3.00000000000000000E+00);
phi_Val[9][2].Set_Equal_To(0.00000000000000000E+00, 0.00000000000000000E+00, 1.50000000000000000E+00);
phi_Val[9][3].Set_Equal_To(-6.00000000000000000E+00, 0.00000000000000000E+00, 4.50000000000000000E+00);
phi_Val[9][4].Set_Equal_To(-6.00000000000000000E+00, 0.00000000000000000E+00, 1.50000000000000000E+00);
phi_Val[9][5].Set_Equal_To(6.00000000000000000E+00, 0.00000000000000000E+00, -3.00000000000000000E+00);
phi_Val[9][6].Set_Equal_To(0.00000000000000000E+00, -6.00000000000000000E+00, 4.50000000000000000E+00);
phi_Val[9][7].Set_Equal_To(0.00000000000000000E+00, 6.00000000000000000E+00, -3.00000000000000000E+00);
phi_Val[9][8].Set_Equal_To(0.00000000000000000E+00, -6.00000000000000000E+00, 1.50000000000000000E+00);
phi_Val[9][9].Set_Equal_To(0.00000000000000000E+00, 0.00000000000000000E+00, -1.50000000000000000E+00);
phi_Val[9][10].Set_Equal_To(0.00000000000000000E+00, 0.00000000000000000E+00, 3.00000000000000000E+00);
phi_Val[9][11].Set_Equal_To(0.00000000000000000E+00, 0.00000000000000000E+00, 3.00000000000000000E+00);
phi_Val[9][12].Set_Equal_To(0.00000000000000000E+00, 0.00000000000000000E+00, 7.50000000000000000E+00);
phi_Val[9][13].Set_Equal_To(0.00000000000000000E+00, 0.00000000000000000E+00, 7.50000000000000000E+00);
phi_Val[9][14].Set_Equal_To(0.00000000000000000E+00, 0.00000000000000000E+00, 1.50000000000000000E+01);
phi_Div[0][0].Set_Equal_To(4.42116701036213300E+01);
phi_Div[0][1].Set_Equal_To(-6.73722336787377696E+00);
phi_Div[0][2].Set_Equal_To(-6.73722336787377696E+00);
phi_Div[0][3].Set_Equal_To(-6.73722336787377962E+00);
phi_Div[0][4].Set_Equal_To(-6.73722336787377696E+00);
phi_Div[0][5].Set_Equal_To(-6.73722336787377696E+00);
phi_Div[0][6].Set_Equal_To(-6.73722336787377962E+00);
phi_Div[0][7].Set_Equal_To(4.42116701036213300E+01);
phi_Div[0][8].Set_Equal_To(-6.73722336787377696E+00);
phi_Div[0][9].Set_Equal_To(-6.73722336787377962E+00);
phi_Div[0][10].Set_Equal_To(-6.73722336787377696E+00);
phi_Div[0][11].Set_Equal_To(4.42116701036213300E+01);
phi_Div[0][12].Set_Equal_To(-5.09488934714951114E+01);
phi_Div[0][13].Set_Equal_To(-3.33066907387546962E-15);
phi_Div[0][14].Set_Equal_To(-3.33066907387546962E-15);
phi_Div[1][0].Set_Equal_To(-6.73722336787377696E+00);
phi_Div[1][1].Set_Equal_To(-6.73722336787377696E+00);
phi_Div[1][2].Set_Equal_To(-6.73722336787377696E+00);
phi_Div[1][3].Set_Equal_To(4.42116701036213300E+01);
phi_Div[1][4].Set_Equal_To(-6.73722336787377696E+00);
phi_Div[1][5].Set_Equal_To(-6.73722336787377696E+00);
phi_Div[1][6].Set_Equal_To(4.42116701036213300E+01);
phi_Div[1][7].Set_Equal_To(-6.73722336787377696E+00);
phi_Div[1][8].Set_Equal_To(-6.73722336787377696E+00);
phi_Div[1][9].Set_Equal_To(4.42116701036213300E+01);
phi_Div[1][10].Set_Equal_To(-6.73722336787377696E+00);
phi_Div[1][11].Set_Equal_To(-6.73722336787377696E+00);
phi_Div[1][12].Set_Equal_To(5.09488934714951043E+01);
phi_Div[1][13].Set_Equal_To(5.09488934714951043E+01);
phi_Div[1][14].Set_Equal_To(5.09488934714951043E+01);
phi_Div[2][0].Set_Equal_To(-6.73722336787377696E+00);
phi_Div[2][1].Set_Equal_To(-6.73722336787377696E+00);
phi_Div[2][2].Set_Equal_To(4.42116701036213300E+01);
phi_Div[2][3].Set_Equal_To(-6.73722336787377962E+00);
phi_Div[2][4].Set_Equal_To(4.42116701036213300E+01);
phi_Div[2][5].Set_Equal_To(-6.73722336787377696E+00);
phi_Div[2][6].Set_Equal_To(-6.73722336787377962E+00);
phi_Div[2][7].Set_Equal_To(-6.73722336787377696E+00);
phi_Div[2][8].Set_Equal_To(4.42116701036213300E+01);
phi_Div[2][9].Set_Equal_To(-6.73722336787377962E+00);
phi_Div[2][10].Set_Equal_To(-6.73722336787377696E+00);
phi_Div[2][11].Set_Equal_To(-6.73722336787377696E+00);
phi_Div[2][12].Set_Equal_To(-3.33066907387546962E-15);
phi_Div[2][13].Set_Equal_To(-3.33066907387546962E-15);
phi_Div[2][14].Set_Equal_To(-5.09488934714951114E+01);
phi_Div[3][0].Set_Equal_To(-6.73722336787377696E+00);
phi_Div[3][1].Set_Equal_To(4.42116701036213300E+01);
phi_Div[3][2].Set_Equal_To(-6.73722336787377696E+00);
phi_Div[3][3].Set_Equal_To(-6.73722336787377962E+00);
phi_Div[3][4].Set_Equal_To(-6.73722336787377696E+00);
phi_Div[3][5].Set_Equal_To(4.42116701036213300E+01);
phi_Div[3][6].Set_Equal_To(-6.73722336787377962E+00);
phi_Div[3][7].Set_Equal_To(-6.73722336787377696E+00);
phi_Div[3][8].Set_Equal_To(-6.73722336787377696E+00);
phi_Div[3][9].Set_Equal_To(-6.73722336787377962E+00);
phi_Div[3][10].Set_Equal_To(4.42116701036213300E+01);
phi_Div[3][11].Set_Equal_To(-6.73722336787377696E+00);
phi_Div[3][12].Set_Equal_To(-3.33066907387546962E-15);
phi_Div[3][13].Set_Equal_To(-5.09488934714951114E+01);
phi_Div[3][14].Set_Equal_To(-3.33066907387546962E-15);
phi_Div[4][0].Set_Equal_To(-2.40000000000000000E+01);
phi_Div[4][1].Set_Equal_To(3.60000000000000000E+01);
phi_Div[4][2].Set_Equal_To(3.60000000000000000E+01);
phi_Div[4][3].Set_Equal_To(-2.40000000000000000E+01);
phi_Div[4][4].Set_Equal_To(3.60000000000000000E+01);
phi_Div[4][5].Set_Equal_To(3.60000000000000000E+01);
phi_Div[4][6].Set_Equal_To(-2.40000000000000000E+01);
phi_Div[4][7].Set_Equal_To(-2.40000000000000000E+01);
phi_Div[4][8].Set_Equal_To(3.60000000000000000E+01);
phi_Div[4][9].Set_Equal_To(-2.40000000000000000E+01);
phi_Div[4][10].Set_Equal_To(3.60000000000000000E+01);
phi_Div[4][11].Set_Equal_To(-2.40000000000000000E+01);
phi_Div[4][12].Set_Equal_To(0.00000000000000000E+00);
phi_Div[4][13].Set_Equal_To(-6.00000000000000000E+01);
phi_Div[4][14].Set_Equal_To(-6.00000000000000000E+01);
phi_Div[5][0].Set_Equal_To(3.60000000000000000E+01);
phi_Div[5][1].Set_Equal_To(-2.40000000000000000E+01);
phi_Div[5][2].Set_Equal_To(3.60000000000000000E+01);
phi_Div[5][3].Set_Equal_To(-2.40000000000000000E+01);
phi_Div[5][4].Set_Equal_To(3.60000000000000000E+01);
phi_Div[5][5].Set_Equal_To(-2.40000000000000000E+01);
phi_Div[5][6].Set_Equal_To(-2.40000000000000000E+01);
phi_Div[5][7].Set_Equal_To(3.60000000000000000E+01);
phi_Div[5][8].Set_Equal_To(3.60000000000000000E+01);
phi_Div[5][9].Set_Equal_To(-2.40000000000000000E+01);
phi_Div[5][10].Set_Equal_To(-2.40000000000000000E+01);
phi_Div[5][11].Set_Equal_To(3.60000000000000000E+01);
phi_Div[5][12].Set_Equal_To(-6.00000000000000000E+01);
phi_Div[5][13].Set_Equal_To(0.00000000000000000E+00);
phi_Div[5][14].Set_Equal_To(-6.00000000000000000E+01);
phi_Div[6][0].Set_Equal_To(3.60000000000000000E+01);
phi_Div[6][1].Set_Equal_To(3.60000000000000000E+01);
phi_Div[6][2].Set_Equal_To(-2.40000000000000000E+01);
phi_Div[6][3].Set_Equal_To(-2.40000000000000000E+01);
phi_Div[6][4].Set_Equal_To(-2.40000000000000000E+01);
phi_Div[6][5].Set_Equal_To(3.60000000000000000E+01);
phi_Div[6][6].Set_Equal_To(-2.40000000000000000E+01);
phi_Div[6][7].Set_Equal_To(3.60000000000000000E+01);
phi_Div[6][8].Set_Equal_To(-2.40000000000000000E+01);
phi_Div[6][9].Set_Equal_To(-2.40000000000000000E+01);
phi_Div[6][10].Set_Equal_To(3.60000000000000000E+01);
phi_Div[6][11].Set_Equal_To(3.60000000000000000E+01);
phi_Div[6][12].Set_Equal_To(-6.00000000000000000E+01);
phi_Div[6][13].Set_Equal_To(-6.00000000000000000E+01);
phi_Div[6][14].Set_Equal_To(0.00000000000000000E+00);
phi_Div[7][0].Set_Equal_To(3.60000000000000000E+01);
phi_Div[7][1].Set_Equal_To(-2.40000000000000000E+01);
phi_Div[7][2].Set_Equal_To(-2.40000000000000000E+01);
phi_Div[7][3].Set_Equal_To(3.60000000000000000E+01);
phi_Div[7][4].Set_Equal_To(-2.40000000000000000E+01);
phi_Div[7][5].Set_Equal_To(-2.40000000000000000E+01);
phi_Div[7][6].Set_Equal_To(3.60000000000000000E+01);
phi_Div[7][7].Set_Equal_To(3.60000000000000000E+01);
phi_Div[7][8].Set_Equal_To(-2.40000000000000000E+01);
phi_Div[7][9].Set_Equal_To(3.60000000000000000E+01);
phi_Div[7][10].Set_Equal_To(-2.40000000000000000E+01);
phi_Div[7][11].Set_Equal_To(3.60000000000000000E+01);
phi_Div[7][12].Set_Equal_To(0.00000000000000000E+00);
phi_Div[7][13].Set_Equal_To(6.00000000000000000E+01);
phi_Div[7][14].Set_Equal_To(6.00000000000000000E+01);
phi_Div[8][0].Set_Equal_To(-2.40000000000000000E+01);
phi_Div[8][1].Set_Equal_To(3.60000000000000000E+01);
phi_Div[8][2].Set_Equal_To(-2.40000000000000000E+01);
phi_Div[8][3].Set_Equal_To(3.60000000000000000E+01);
phi_Div[8][4].Set_Equal_To(-2.40000000000000000E+01);
phi_Div[8][5].Set_Equal_To(3.60000000000000000E+01);
phi_Div[8][6].Set_Equal_To(3.60000000000000000E+01);
phi_Div[8][7].Set_Equal_To(-2.40000000000000000E+01);
phi_Div[8][8].Set_Equal_To(-2.40000000000000000E+01);
phi_Div[8][9].Set_Equal_To(3.60000000000000000E+01);
phi_Div[8][10].Set_Equal_To(3.60000000000000000E+01);
phi_Div[8][11].Set_Equal_To(-2.40000000000000000E+01);
phi_Div[8][12].Set_Equal_To(6.00000000000000000E+01);
phi_Div[8][13].Set_Equal_To(0.00000000000000000E+00);
phi_Div[8][14].Set_Equal_To(6.00000000000000000E+01);
phi_Div[9][0].Set_Equal_To(-2.40000000000000000E+01);
phi_Div[9][1].Set_Equal_To(-2.40000000000000000E+01);
phi_Div[9][2].Set_Equal_To(3.60000000000000000E+01);
phi_Div[9][3].Set_Equal_To(3.60000000000000000E+01);
phi_Div[9][4].Set_Equal_To(3.60000000000000000E+01);
phi_Div[9][5].Set_Equal_To(-2.40000000000000000E+01);
phi_Div[9][6].Set_Equal_To(3.60000000000000000E+01);
phi_Div[9][7].Set_Equal_To(-2.40000000000000000E+01);
phi_Div[9][8].Set_Equal_To(3.60000000000000000E+01);
phi_Div[9][9].Set_Equal_To(3.60000000000000000E+01);
phi_Div[9][10].Set_Equal_To(-2.40000000000000000E+01);
phi_Div[9][11].Set_Equal_To(-2.40000000000000000E+01);
phi_Div[9][12].Set_Equal_To(6.00000000000000000E+01);
phi_Div[9][13].Set_Equal_To(6.00000000000000000E+01);
phi_Div[9][14].Set_Equal_To(0.00000000000000000E+00);
// // set of quadrature points
// static const double Quad_Points[NQ][SUB_TD] = { \
// {5.68430584196844446E-01, 1.43856471934385194E-01, 1.43856471934385194E-01}, \
// {1.43856471934385194E-01, 1.43856471934385194E-01, 1.43856471934385194E-01}, \
// {1.43856471934385194E-01, 1.43856471934385194E-01, 5.68430584196844446E-01}, \
// {1.43856471934385194E-01, 5.68430584196844446E-01, 1.43856471934385194E-01}, \
// {0.00000000000000000E+00, 5.00000000000000000E-01, 5.00000000000000000E-01}, \
// {5.00000000000000000E-01, 0.00000000000000000E+00, 5.00000000000000000E-01}, \
// {5.00000000000000000E-01, 5.00000000000000000E-01, 0.00000000000000000E+00}, \
// {5.00000000000000000E-01, 0.00000000000000000E+00, 0.00000000000000000E+00}, \
// {0.00000000000000000E+00, 5.00000000000000000E-01, 0.00000000000000000E+00}, \
// {0.00000000000000000E+00, 0.00000000000000000E+00, 5.00000000000000000E-01} \
// };
// // set of quadrature weights
// static const double Quad_Weights[NQ] = { \
// 3.62941783134008988E-02, \
// 3.62941783134008988E-02, \
// 3.62941783134008988E-02, \
// 3.62941783134008988E-02, \
// 3.58165890217718337E-03, \
// 3.58165890217718337E-03, \
// 3.58165890217718337E-03, \
// 3.58165890217718337E-03, \
// 3.58165890217718337E-03, \
// 3.58165890217718337E-03 \
// };
/*------------ END: Auto Generate ------------*/
/*------------ BEGIN: Auto Generate ------------*/
/*** compute basis function quantities ***/
// map basis vectors over (indexing is in the C style)
// loop through quad points
for (int qp_i = 0; (qp_i < Num_QP); qp_i++)
{
// evaluate for each basis function
for (int basis_i = 0; (basis_i < Num_Basis); basis_i++)
{
VEC_3x1 vv_temp;
// pre-multiply by sign change
const double INV_DET_SIGN_FLIP = Basis_Sign[basis_i] * Mesh->Map_Inv_Det_Jac[0].a;
// pre-multiply by 1/det(Jac)
Scalar_Mult_Vector(phi_Val[qp_i][basis_i], INV_DET_SIGN_FLIP, vv_temp);
Mat_Vec(Mesh->Map_PHI_Grad[0], vv_temp, Func_vv_Value[basis_i][qp_i]);
}
}
// map divergence of basis vectors over (indexing is in the C style)
// loop through quad points
for (int qp_i = 0; (qp_i < Num_QP); qp_i++)
{
// evaluate for each basis function
for (int basis_i = 0; (basis_i < Num_Basis); basis_i++)
{
// pre-multiply by 1/det(Jac) (and flip sign if necessary)
Func_vv_Div[basis_i][qp_i].a = Basis_Sign[basis_i] * (phi_Div[qp_i][basis_i].a) * Mesh->Map_Inv_Det_Jac[0].a;
}
}
/*------------ END: Auto Generate ------------*/
}
/***************************************************************************************/
/*------------ END: Auto Generate ------------*/
// remove those macros!
#undef SpecificFUNC
#undef SpecificFUNC_str
#undef SPACE_type
#undef SPACE_name
#undef SUB_TD
#undef DOI_TD
#undef GD
#undef NC
#undef NB
#undef NQ
/***/
| 56.549724 | 145 | 0.670876 | [
"mesh",
"object",
"vector"
] |
cde057cec630dc28c9a156150a33b2410a474c30 | 4,031 | cpp | C++ | oneflow/core/framework/session_util.cpp | wangyuyue/oneflow | 0a71c22fe8355392acc8dc0e301589faee4c4832 | [
"Apache-2.0"
] | 3,285 | 2020-07-31T05:51:22.000Z | 2022-03-31T15:20:16.000Z | oneflow/core/framework/session_util.cpp | wangyuyue/oneflow | 0a71c22fe8355392acc8dc0e301589faee4c4832 | [
"Apache-2.0"
] | 2,417 | 2020-07-31T06:28:58.000Z | 2022-03-31T23:04:14.000Z | oneflow/core/framework/session_util.cpp | wangyuyue/oneflow | 0a71c22fe8355392acc8dc0e301589faee4c4832 | [
"Apache-2.0"
] | 520 | 2020-07-31T05:52:42.000Z | 2022-03-29T02:38:11.000Z | /*
Copyright 2020 The OneFlow Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <mutex>
#include "oneflow/core/common/util.h"
#include "oneflow/core/framework/session_util.h"
namespace oneflow {
namespace {
std::mutex* GlobalSessionUtilMutex() {
static std::mutex global_id2session_map_mutex;
return &global_id2session_map_mutex;
}
HashMap<int64_t, std::shared_ptr<Session>>* GlobalId2SessionMap() {
static HashMap<int64_t, std::shared_ptr<Session>> id2session_map;
return &id2session_map;
}
std::vector<int64_t>* RegsiteredSessionIds() {
static std::vector<int64_t> default_sess_id;
return &default_sess_id;
}
Maybe<void> SetDefaultSessionId(int64_t val) {
std::vector<int64_t>* ids = RegsiteredSessionIds();
ids->push_back(val);
return Maybe<void>::Ok();
}
} // namespace
Session::Session(int64_t id)
: id_(id), is_mirrored_strategy_enabled_stack_(new std::vector<bool>()) {
instruction_list_.reset(new vm::InstructionMsgList());
eager_symbol_list_.reset(new vm::cfg::EagerSymbolList());
}
int64_t Session::id() const { return id_; }
const std::shared_ptr<vm::InstructionMsgList>& Session::instruction_list() const {
return instruction_list_;
}
std::shared_ptr<vm::cfg::EagerSymbolList> Session::eager_symbol_list() const {
return eager_symbol_list_;
}
Maybe<void> Session::PushMirroredStrategyEnabled(bool is_mirrored) {
is_mirrored_strategy_enabled_stack_->push_back(is_mirrored);
return Maybe<void>::Ok();
}
Maybe<void> Session::PopMirroredStrategyEnabled() {
is_mirrored_strategy_enabled_stack_->pop_back();
return Maybe<void>::Ok();
}
Maybe<bool> Session::IsMirroredStrategyEnabled() const {
return is_mirrored_strategy_enabled_stack_->size() > 0
&& is_mirrored_strategy_enabled_stack_->back();
}
Maybe<bool> Session::IsConsistentStrategyEnabled() const {
return is_mirrored_strategy_enabled_stack_->size() > 0
&& !is_mirrored_strategy_enabled_stack_->back();
}
Maybe<int64_t> GetDefaultSessionId() {
std::unique_lock<std::mutex> lock(*GlobalSessionUtilMutex());
const auto& regsitered_ids = *(RegsiteredSessionIds());
CHECK_GT_OR_RETURN(regsitered_ids.size(), 0);
return regsitered_ids.back();
}
Maybe<Session> RegsiterSession(int64_t id) {
std::shared_ptr<Session> sess = std::make_shared<Session>(id);
std::unique_lock<std::mutex> lock(*GlobalSessionUtilMutex());
auto* id2session_map = GlobalId2SessionMap();
CHECK_OR_RETURN(id2session_map->find(id) == id2session_map->end());
(*id2session_map)[id] = sess;
JUST(SetDefaultSessionId(id));
return id2session_map->at(id);
}
Maybe<Session> GetDefaultSession() {
std::unique_lock<std::mutex> lock(*GlobalSessionUtilMutex());
const auto& regsitered_ids = *(RegsiteredSessionIds());
CHECK_GT_OR_RETURN(regsitered_ids.size(), 0);
int64_t default_sess_id = regsitered_ids.back();
auto* id2session_map = GlobalId2SessionMap();
CHECK_OR_RETURN(id2session_map->find(default_sess_id) != id2session_map->end());
return id2session_map->at(default_sess_id);
}
Maybe<void> ClearSessionById(int64_t id) {
std::unique_lock<std::mutex> lock(*GlobalSessionUtilMutex());
auto* id2session_map = GlobalId2SessionMap();
CHECK_OR_RETURN(id2session_map->find(id) != id2session_map->end());
id2session_map->erase(id);
auto* sess_ids = RegsiteredSessionIds();
int32_t i = 0;
for (; i < sess_ids->size(); ++i) {
if (sess_ids->at(i) == id) { break; }
}
sess_ids->erase(sess_ids->begin() + i);
return Maybe<void>::Ok();
}
} // namespace oneflow
| 32.772358 | 82 | 0.749442 | [
"vector"
] |
cdec447e4d6cb716cc3ad23e26cbdf84c2b9d383 | 30,281 | hh | C++ | Misc/Opencores/c16_latest.tar/c16/trunk/compiler/Node.hh | Main-Project-MEC/Systolic-Processor-On-FPGA | 35f7b94b5abb2614070d136c5811ab70d7385fc7 | [
"MIT"
] | 3 | 2015-10-19T17:51:26.000Z | 2018-01-31T09:52:35.000Z | Misc/Opencores/c16_latest.tar/c16/trunk/compiler/Node.hh | Main-Project-MEC/Systolic-Processor-On-FPGA | 35f7b94b5abb2614070d136c5811ab70d7385fc7 | [
"MIT"
] | null | null | null | Misc/Opencores/c16_latest.tar/c16/trunk/compiler/Node.hh | Main-Project-MEC/Systolic-Processor-On-FPGA | 35f7b94b5abb2614070d136c5811ab70d7385fc7 | [
"MIT"
] | 2 | 2018-03-27T06:34:03.000Z | 2021-01-12T11:28:18.000Z | // Node.hh
#ifndef __NODE_HH_DEFINED__
#define __NODE_HH_DEFINED__
#include <assert.h>
#include "List.hh"
//-----------------------------------------------------------------------------
class TypeSpecifier;
class DeclItem;
class Initializer;
class TypeName;
class Expression;
const char * GetDeclaredName(Declarator * decl);
ParameterDeclarationList * GetParameters(Declarator * decl);
bool IsFunPtr(Declarator * decl);
bool IsPointer(Declarator * decl);
Expression * ArrayLength(Declarator * decl);
void SetArrayLength(Declarator * decl, int len);
bool IsFunction(Declarator * decl);
bool IsArray(Declarator * decl);
enum SUW { SB, UB, WO };
//-----------------------------------------------------------------------------
class Constant : public Node
{
public:
Constant(const char * name)
: Node(name)
{};
virtual void EmitValue_RR(FILE * out) = 0;
virtual void EmitValue_LL(FILE * out) = 0;
};
//-----------------------------------------------------------------------------
class NumericConstant : public Constant
{
public:
NumericConstant(const char * txt);
NumericConstant(int val, int siz = 0)
: Constant("NumericConstant"),
value(val),
size(siz)
{};
virtual void EmitValue_RR(FILE * out);
virtual void EmitValue_LL(FILE * out);
int GetValue() const { return value; };
int GetSize() const { return size; };
void Negate() { value = -value; };
void Complement() { value = ~value; };
void LogNot() { if (value) value = 0; else value = -1; };
private:
int value;
int size;
};
//-----------------------------------------------------------------------------
class StringConstant : public Constant
{
public:
StringConstant();
~StringConstant();
virtual void EmitValue_RR(FILE * out);
virtual void EmitValue_LL(FILE * out);
void operator += (char txt);
StringConstant * operator & (StringConstant * other);
void operator += (const char * txt)
{ while (*txt) *this += *txt++; };
int GetStringNumber() const { return string_number; };
int GetLength() const { return value_len; };
char * Kill()
{ char * ret = buffer; buffer = 0; delete this; return ret; };
void EmitAndRemove(FILE * out, int length);
static void EmitAll(FILE * out);
private:
char * buffer;
int buffer_len;
int value_len;
int string_number;
static int str_count;
enum { MAX_STRINGS = 5000 };
static StringConstant * all_strings[MAX_STRINGS];
};
//-----------------------------------------------------------------------------
// how an expression is created...
// //
enum BinExprType
{
// binary
ET_LIST, // expr , expr
ET_ARGLIST, // expr , expr in function argument
ET_ASSIGN, // expr = expr
ET_MULT_ASSIGN, // expr *= expr
ET_DIV_ASSIGN, // expr /= expr
ET_MOD_ASSIGN, // expr %= expr
ET_ADD_ASSIGN, // expr += expr
ET_SUB_ASSIGN, // expr -= expr
ET_LEFT_ASSIGN, // expr <<= expr
ET_RIGHT_ASSIGN, // expr >>= expr
ET_AND_ASSIGN, // expr &= expr
ET_XOR_ASSIGN, // expr ^= expr
ET_OR_ASSIGN, // expr |= expr
ET_BIT_OR, // expr | expr
ET_BIT_AND, // expr & expr
ET_BIT_XOR, // expr ^ expr
ET_LOG_OR, // expr || expr
ET_LOG_AND, // expr && expr
ET_EQUAL, // expr == expr
ET_NOT_EQUAL, // expr != expr
ET_LESS_EQUAL, // expr <= expr
ET_LESS, // expr < expr
ET_GREATER_EQUAL, // expr >= expr
ET_GREATER, // expr > expr
ET_LEFT, // expr << expr
ET_RIGHT, // expr >> expr
ET_ADD, // expr + expr
ET_SUB, // expr - expr
ET_MULT, // expr * expr
ET_DIV, // expr / expr
ET_MOD, // expr % expr
ET_ELEMENT, // expr [ expr ]
ET_FUNCALL // expr ( ... )
};
enum UnaExprType
{
ET_CAST, // (type) expr
ET_ADDRESS, // & expr
ET_CONTENT, // * expr
ET_CONJUGATE, // + expr
ET_NEGATE, // - expr
ET_COMPLEMENT, // ~ expr
ET_LOG_NOT, // ! expr
ET_POSTINC, // ++ expr
ET_POSTDEC, // -- expr
ET_PREINC, // ++ expr
ET_PREDEC // -- expr
};
class Expression : public Node
{
public:
Expression(const char * nodename)
: Node(nodename),
type_name(0)
{};
virtual void Emit(FILE * out) = 0;
virtual void Emit_to_ll(FILE * out) { assert(0); };
void EmitCall(FILE * out, Expression * right);
virtual void EmitInitialization(FILE * out, int size);
virtual void EmitAddress(FILE * out);
virtual void AddAddress(FILE * out);
virtual int EmitPush(FILE * out, ParameterDeclarationList * params);
virtual void EmitAssign(FILE * out) { assert(0); };
virtual int GetParaLength() const { return 1; };
virtual bool IsConstant() const { return false; };
virtual bool IsNumericConstant() const { return false; };
virtual bool IsStringConstant() const { return false; };
virtual bool IsVariable() const { return false; };
virtual const char * GetVarname() const { return 0; };
virtual int GetConstantNumericValue() const;
virtual StringConstant * GetStringConstant() const;
virtual TypeName * FunReturnType();
virtual TypeName * SetType() = 0;
virtual SUW GetSUW();
void SetType(TypeName * t);
bool IsPointer();
bool IsArray();
int PointeeSize();
int GetSize();
TypeName * GetType();
bool IsUnsigned();
int FunReturnSize();
static const char * GetPrettyName(const char * pretty);
virtual Expression * OptNegate() { assert(0); };
virtual Expression * OptComplement() { assert(0); };
virtual Expression * OptLogNot() { assert(0); };
private:
TypeName * type_name;
};
//-----------------------------------------------------------------------------
class IdentifierExpression : public Expression
{
public:
static Expression * New(const char * s);
virtual void Emit(FILE * out);
virtual void EmitAssign(FILE * out);
virtual void Emit_to_ll(FILE * out);
virtual TypeName * SetType();
virtual bool IsVariable() const { return true; };
virtual const char * GetVarname() const { return varname; };
virtual void EmitAddress(FILE * out);
virtual void EmitInitialization(FILE * out, int size);
virtual void AddAddress(FILE * out);
virtual TypeName * FunReturnType();
private:
IdentifierExpression(const char * s)
: Expression("Expression (variable name)"),
varname(s)
{};
const char * varname;
};
//-----------------------------------------------------------------------------
class MemberExpression : public Expression
{
public:
MemberExpression(bool is_pointer, Expression * r, const char * s);
virtual void Emit(FILE * out);
virtual void EmitAddress(FILE * out);
void EmitAddress(FILE * out, bool content);
virtual TypeName * SetType();
private:
Expression * left;
const char * membername;
};
//-----------------------------------------------------------------------------
class StringExpression : public Expression
{
public:
StringExpression(StringConstant * s);
virtual void Emit(FILE * out);
virtual void EmitAddress(FILE * out);
virtual void Emit_to_ll(FILE * out);
virtual TypeName * SetType();
virtual void EmitInitialization(FILE * out, int size);
virtual bool IsConstant() const { return true; };
virtual bool IsStringConstant() const { return true; };
virtual StringConstant * GetStringConstant() const
{ return string_constant; }
private:
StringConstant * string_constant;
};
//-----------------------------------------------------------------------------
class NumericExpression : public Expression
{
public:
NumericExpression(NumericConstant * n);
NumericExpression(TypeName * t);
NumericExpression(Expression * r);
NumericExpression(int value);
virtual void Emit(FILE * out);
virtual void Emit_to_ll(FILE * out);
virtual bool IsConstant() const { return true; };
virtual bool IsNumericConstant() const { return true; };
virtual int GetConstantNumericValue() const;
virtual TypeName * SetType();
virtual void EmitInitialization(FILE * out, int size);
static const char * GetPretty(int value);
virtual Expression * OptNegate();
virtual Expression * OptComplement();
virtual Expression * OptLogNot();
private:
NumericConstant * int_value;
};
//-----------------------------------------------------------------------------
class CondExpression : public Expression
{
public:
CondExpression(Expression * l, Expression * m, Expression * r)
: Expression("Expression (l ? m : r)"),
left(l),
middle(m),
right(r)
{};
virtual void Emit(FILE * out);
virtual TypeName * SetType();
private:
Expression * left;
Expression * middle;
Expression * right;
};
//-----------------------------------------------------------------------------
class BinaryExpression : public Expression
{
public:
static Expression * New(BinExprType et, Expression * l, Expression * r);
virtual void Emit(FILE * out);
virtual TypeName * SetType();
virtual void EmitAddress(FILE * out);
TypeName * MaxType(Expression * l, Expression * r);
static const char * GetPretty(BinExprType expr_type);
static BinExprType MapAssign(BinExprType et);
protected:
BinaryExpression(BinExprType et, Expression * l, Expression * r);
BinExprType expr_type;
Expression * left;
Expression * right;
};
//-----------------------------------------------------------------------------
class ArgListExpression : public BinaryExpression
{
public:
ArgListExpression(Expression * l, Expression * r)
: BinaryExpression(ET_ARGLIST, l, r)
{};
virtual void Emit(FILE * out) {}; // done vy EmitPush()
virtual int EmitPush(FILE * out, ParameterDeclarationList * params);
virtual int GetParaLength() const;
virtual TypeName * SetType();
};
//-----------------------------------------------------------------------------
class AdditionExpression : public BinaryExpression
{
public:
static Expression * New(Expression * l, Expression * r);
virtual void Emit(FILE * out);
virtual TypeName * SetType();
private:
AdditionExpression(Expression * l, Expression * r)
: BinaryExpression(ET_ADD, l, r)
{};
};
//-----------------------------------------------------------------------------
class SubtractionExpression : public BinaryExpression
{
public:
static Expression * New(Expression * l, Expression * r);
virtual void Emit(FILE * out);
virtual TypeName * SetType();
private:
SubtractionExpression(Expression * l, Expression * r)
: BinaryExpression(ET_SUB, l, r)
{};
};
//-----------------------------------------------------------------------------
class UnaryExpression : public Expression
{
public:
UnaryExpression(TypeName * t, Expression * r);
virtual void Emit(FILE * out);
virtual void EmitAddress(FILE * out);
virtual void EmitInitialization(FILE * out, int size);
virtual TypeName * SetType();
static const char * GetPretty(UnaExprType expr_type);
static Expression * New(UnaExprType et, Expression * r);
private:
UnaryExpression(UnaExprType et, Expression * r)
: Expression(GetPrettyName(GetPretty(et))),
expr_type(et),
right(r)
{};
UnaExprType expr_type;
Expression * right;
};
//-----------------------------------------------------------------------------
class AsmExpression : public Expression
{
public:
AsmExpression(StringConstant * string);
virtual void Emit(FILE * out);
virtual TypeName * SetType();
private:
char * asm_string;
};
//-----------------------------------------------------------------------------
enum Specifier
{
// storage class
SC_TYPEDEF = 0x00000001,
SC_EXTERN = 0x00000002,
SC_STATIC = 0x00000004,
SC_AUTO = 0x00000008,
SC_REGISTER = 0x00000010,
SC_MASK = SC_TYPEDEF | SC_EXTERN | SC_STATIC | SC_AUTO | SC_REGISTER,
// type qualifiers
TQ_CONST = 0x00000100,
TQ_VOLATILE = 0x00000200,
TQ_MASK = TQ_CONST | TQ_VOLATILE,
// type specifiers
TS_SIGNED = 0x00001000,
TS_UNSIGNED = 0x00002000,
TS_SIGN_MASK = TS_SIGNED | TS_UNSIGNED,
TS_VOID = 0x00010000,
TS_CHAR = 0x00020000,
TS_SHORT = 0x00040000,
TS_INT = 0x00080000,
TS_LONG = 0x00100000,
TS_FLOAT = 0x00200000,
TS_DOUBLE = 0x00400000,
TS_STRUCT = 0x00800000,
TS_UNION = 0x01000000,
TS_ENUM = 0x02000000,
TS_TYPE_NAME = 0x04000000,
TS_MASK = TS_VOID | TS_CHAR | TS_SHORT | TS_INT | TS_LONG |
TS_FLOAT | TS_DOUBLE | TS_STRUCT |
TS_UNION | TS_ENUM | TS_TYPE_NAME,
TS_NUMERIC = TS_CHAR | TS_SHORT | TS_INT | TS_LONG |
TS_FLOAT | TS_DOUBLE | TS_ENUM,
};
//-----------------------------------------------------------------------------
class Ptr : public Node
{
public:
Ptr(TypeSpecifier * ds)
: Node("Ptr"),
decl_specs(ds)
{};
virtual void Emit(FILE * out);
int Print(FILE * out) const;
private:
TypeSpecifier * decl_specs;
};
//-----------------------------------------------------------------------------
class Identifier : public Node
{
public:
Identifier(const char * n)
: Node("Identifier"),
name(n)
{};
private:
const char * name;
};
//-----------------------------------------------------------------------------
class Initializer : public Node
{
public:
Initializer(Expression * expr)
: Node("Initializer (skalar)"),
skalar_value(expr),
array_value(0)
{};
Initializer(InitializerList * list)
: Node("Initializer (vector)"),
skalar_value(0),
array_value(list)
{};
virtual void Emit(FILE * out);
virtual void EmitValue(FILE * out, TypeName * tn);
int InitAutovar(FILE * out, TypeName * type);
int ElementCount() const;
private:
Expression * skalar_value;
InitializerList * array_value;
};
//-----------------------------------------------------------------------------
class ParameterDeclaration : public Node
{
public:
ParameterDeclaration(TypeSpecifier * ds, Declarator * dec);
virtual void Emit(FILE * out);
int AllocateParameters(int position);
const char * GetDeclaredName(int skip);
TypeName * GetTypeName() const { return type; };
bool IsEllipsis() const { return isEllipsis; };
ParameterDeclaration * SetEllipsis() { isEllipsis = true; return this; };
private:
TypeName * type;
bool isEllipsis;
};
//-----------------------------------------------------------------------------
enum DECL_WHAT
{
DECL_NAME = 1,
DECL_FUNPTR = 2,
DECL_ARRAY = 3,
DECL_FUN = 4,
DECL_POINTER = 5
};
class DeclItem : public Node
{
public:
DeclItem(DECL_WHAT w)
: Node("DeclItem"),
what(w),
name(0),
funptr(0),
array_size(0),
fun_params(0),
fun_identifiers(0),
pointer(0)
{};
DeclItem(const char * n)
: Node("DeclItem"),
what(DECL_NAME),
name(n),
funptr(0),
array_size(0),
fun_params(0),
fun_identifiers(0),
pointer(0)
{};
DeclItem(Declarator * fp)
: Node("DeclItem"),
what(DECL_FUNPTR),
name(0),
funptr(fp),
array_size(0),
fun_params(0),
fun_identifiers(0),
pointer(0)
{};
DeclItem(Expression * ep)
: Node("DeclItem"),
what(DECL_ARRAY),
name(0),
funptr(0),
array_size(ep),
fun_params(0),
fun_identifiers(0),
pointer(0)
{};
DeclItem(ParameterDeclarationList * pl)
: Node("DeclItem"),
what(DECL_FUN),
name(0),
funptr(0),
array_size(0),
fun_params(pl),
fun_identifiers(0),
pointer(0)
{};
DeclItem(IdentifierList * il)
: Node("DeclItem"),
what(DECL_FUN),
name(0),
funptr(0),
array_size(0),
fun_params(0),
fun_identifiers(il),
pointer(0)
{};
DeclItem(Pointer * p)
: Node("DeclItem"),
what(DECL_POINTER),
name(0),
funptr(0),
array_size(0),
fun_params(0),
fun_identifiers(0),
pointer(p)
{};
virtual void Emit(FILE * out);
int Print(FILE * out) const;
const char * GetName() const { return name; };
DECL_WHAT GetWhat() const { return what; };
Declarator * GetFunptr() const { return funptr; };
Pointer * GetPointer() const { return pointer; };
Expression * GetArraySize() const { return array_size; };
void SetArraySize(int n);
ParameterDeclarationList * GetParameters() const { return fun_params; };
private:
const DECL_WHAT what;
const char * name;
Declarator * funptr;
Expression * array_size;
ParameterDeclarationList * fun_params;
IdentifierList * fun_identifiers;
Pointer * pointer;
};
//-----------------------------------------------------------------------------
class Enumerator : public Node
{
public:
Enumerator(const char * n, Expression * v)
: Node("Enumerator"),
name(n),
value(v)
{};
virtual void Emit(FILE * out);
static int current;
private:
const char * name;
Expression * value;
};
//-----------------------------------------------------------------------------
class StructDeclarator : public Node
{
public:
StructDeclarator(Declarator * dcl, Expression * exp)
: Node("StructDeclarator"),
declarator(dcl),
expression(exp),
position(-1)
{};
virtual void Emit(FILE * out);
int EmitMember(FILE * out, const char * struct_name,
TypeSpecifier * tspec, int pos, bool is_union);
TypeName * GetMemberType(TypeSpecifier * tspec, const char * member);
int GetMemberPosition(const char * member) const;
Declarator * GetDeclarator() const { return declarator; };
TypeName * FirstUnionMember(TypeSpecifier * tspec, int union_size) const;
const char * GetMemberName() const;
private:
Declarator * declarator;
Expression * expression; // : bitfield
int position;
};
//-----------------------------------------------------------------------------
class StructDeclaration : public Node
{
public:
StructDeclaration(TypeSpecifier * ds, StructDeclaratorList * sdl)
: Node("StructDeclaration"),
decl_specifiers(ds),
struct_decl_list(sdl),
size(-1)
{ };
int Emit(FILE * out, const char * struct_name, int pos, bool is_union);
TypeName * GetMemberType(const char * struct_name, const char * member);
TypeName * GetMemberType(int pos);
int GetMemberPosition(const char * struct_name,
const char * member, bool is_union) const;
int GetSize() const { assert(size != -1); return size; };
TypeSpecifier * GetSpecifier() const { return decl_specifiers; };
StructDeclaratorList * GetDeclarators() const { return struct_decl_list; };
TypeName * FirstUnionMember(int size) const;
int GetDeclaratorCount() const
{ return StructDeclaratorList::Length(struct_decl_list); };
private:
TypeSpecifier * decl_specifiers;
StructDeclaratorList * struct_decl_list;
int size;
};
TypeName * GetMemberType(StructDeclarationList * sdl, int pos);
//-----------------------------------------------------------------------------
class TypeSpecifier : public Node
{
public:
// all types
TypeSpecifier(Specifier sp)
: Node("TypeSpecifier (all)"),
spec(sp),
name(0),
struct_decl_list(0),
enum_list(0)
{};
// structs, unions, typedef(name)
TypeSpecifier(Specifier sp, const char * n, StructDeclarationList * sdl);
// enums
TypeSpecifier(const char * n, EnumeratorList * el)
: Node("TypeSpecifier (enum)"),
spec(TS_ENUM),
name(n),
struct_decl_list(0),
enum_list(el)
{};
virtual void Emit(FILE * out);
int Print(FILE * out) const;
TypeSpecifier * operator +(TypeSpecifier & other);
TypeSpecifier * self() { return this; };
Specifier GetType() const { return spec; };
const char * GetName() const { return name; };
StructDeclarationList * GetStructDecl() const
{ return struct_decl_list; };
bool IsUnsigned() const { return spec & TS_UNSIGNED; };
int GetFunReturnSize(Declarator * decl) const;
int GetSize(Declarator * decl) const;
int GetBaseSize() const;
TypeName * GetMemberType(const char * member);
bool IsNumericType() const; // char, short, or int
bool IsUnion() const
{ if (spec & TS_UNION) return true; return false; };
bool IsStruct() const
{ if (spec & TS_STRUCT) return true; return false; };
private:
Specifier spec; // all types
const char * name; // enums, structs and unions
StructDeclarationList * struct_decl_list; // structs and unions
EnumeratorList * enum_list; // enums
static int anonymous_number;
};
//-----------------------------------------------------------------------------
class InitDeclarator : public Node
{
public:
InitDeclarator(Declarator * decl, Initializer * init)
: Node("InitDeclarator"),
declarator(decl),
initializer(init)
{};
virtual void Emit(FILE * out);
Declarator * GetDeclarator() const { return declarator; };
const char * GetDeclaredName(int skip);
void Allocate(FILE * out, TypeSpecifier * spec);
int EmitAutovars(FILE * out, TypeSpecifier * spec);
private:
Declarator * declarator;
Initializer * initializer;
};
//-----------------------------------------------------------------------------
class Declaration : public Node
{
public:
Declaration(TypeSpecifier * ds, InitDeclaratorList * il);
virtual void Emit(FILE * out);
void Allocate(FILE * out);
int EmitAutovars(FILE * out);
private:
TypeSpecifier * base_type;
InitDeclaratorList * init_list;
};
//-----------------------------------------------------------------------------
class TypeName : public Node
{
public:
TypeName(TypeSpecifier * ds, Declarator * ad);
TypeName(Specifier sp);
virtual void Emit(FILE * out);
int Print(FILE * out) const;
Declarator * GetDeclarator() const { return abs_declarator; };
TypeSpecifier * GetTypeSpecifier() const { return decl_spec; };
const char * GetDeclaredName();
TypeName * GetFunReturnType();
TypeName * AddressOf() const;
TypeName * ContentOf() const;
TypeName * GetElementType() const;
bool IsNumericType() const; // char, short, or int
bool IsPointer() const;
Expression * ArrayLength() const;
void SetArrayLength(int len);
bool IsStruct() const;
bool IsUnion() const;
bool IsArray() const;
int GetPointeeSize() const;
TypeName * GetMemberType(const char * member);
TypeName * FirstUnionMember(int size) const;
int GetFunReturnSize()
{ return decl_spec->GetFunReturnSize(abs_declarator); };
int GetSize() const
{ return decl_spec->GetSize(abs_declarator); };
SUW GetSUW();
bool IsUnsigned() const;
bool IsFunPtr() const
{ return ::IsFunPtr(abs_declarator); };
ParameterDeclarationList * GetParameters() const
{ return ::GetParameters(abs_declarator); };
private:
TypeSpecifier * decl_spec;
Declarator * abs_declarator;
};
//-----------------------------------------------------------------------------
class Statement : public Node
{
public:
Statement(const char * ntype)
: Node(ntype)
{};
virtual void Emit(FILE * out) = 0;
virtual bool NotEmpty() const { return true; };
virtual bool EmitCaseJump(FILE * out, bool def, int loop, int size)
{ return false; };
};
//-----------------------------------------------------------------------------
class LabelStatement : public Statement
{
public:
LabelStatement(const char * n, Statement * stat)
: Statement("Label Statement"),
label_name(n),
statement(stat)
{};
virtual void Emit(FILE * out);
private:
const char * label_name;
Statement * statement;
};
//-----------------------------------------------------------------------------
class CaseStatement : public Statement
{
public:
CaseStatement(Expression * exp, Statement * stat)
: Statement("case Statement"),
case_value(exp),
statement(stat)
{};
virtual void Emit(FILE * out);
virtual bool EmitCaseJump(FILE * out, bool def, int loop, int size);
private:
Expression * case_value; // case, or 0 for default
Statement * statement;
};
//-----------------------------------------------------------------------------
class CompoundStatement : public Statement
{
public:
CompoundStatement(DeclarationList * dl, StatementList * sl)
: Statement("CompoundStatement"),
decl_list(dl),
stat_list(sl)
{};
virtual void Emit(FILE * out);
virtual bool NotEmpty() const { return decl_list || stat_list; };
void EmitCaseJumps(FILE * out, int size);
int EmitAutovars(FILE * out);
private:
DeclarationList * decl_list;
StatementList * stat_list;
};
//-----------------------------------------------------------------------------
class ExpressionStatement : public Statement
{
public:
ExpressionStatement(Expression * expr)
: Statement("ExpressionStatement"),
expression(expr)
{};
virtual void Emit(FILE * out);
virtual bool NotEmpty() const { return expression; };
Expression * GetExpression() const { return expression; };
private:
Expression * expression;
};
//-----------------------------------------------------------------------------
class SwitchStatement : public Statement
{
public:
SwitchStatement(Expression * cond, CompoundStatement * cas)
: Statement("SwitchStatement"),
condition(cond),
case_stat(cas)
{};
virtual void Emit(FILE * out);
private:
Expression * condition;
CompoundStatement * case_stat;
};
//-----------------------------------------------------------------------------
class IfElseStatement : public Statement
{
public:
IfElseStatement(Expression * cond, Statement * ifs, Statement * els)
: Statement("IfElseStatement"),
condition(cond),
if_stat(ifs),
else_stat(els)
{};
virtual void Emit(FILE * out);
private:
Expression * condition;
Statement * if_stat;
Statement * else_stat;
};
//-----------------------------------------------------------------------------
class DoWhileStatement : public Statement
{
public:
DoWhileStatement(Statement * bdy, Expression * cond)
: Statement("do while Statement"),
condition(cond),
body(bdy)
{};
virtual void Emit(FILE * out);
private:
Expression * condition;
Statement * body;
};
//-----------------------------------------------------------------------------
class WhileStatement : public Statement
{
public:
WhileStatement(Expression * cond, Statement * bdy)
: Statement("while Statement"),
condition(cond),
body(bdy)
{};
virtual void Emit(FILE * out);
private:
Expression * condition;
Statement * body;
};
//-----------------------------------------------------------------------------
class ForStatement : public Statement
{
public:
ForStatement(ExpressionStatement * f1, ExpressionStatement * f2,
Expression * f3, Statement * bdy)
: Statement("for Statement"),
for_1(f1),
for_2(f2),
for_3(f3),
body(bdy)
{};
virtual void Emit(FILE * out);
private:
ExpressionStatement * for_1;
ExpressionStatement * for_2;
Expression * for_3;
Statement * body;
};
//-----------------------------------------------------------------------------
class GotoStatement : public Statement
{
public:
GotoStatement(const char * lab)
: Statement("goto Statement"),
label_name(lab)
{};
virtual void Emit(FILE * out);
private:
const char * label_name;
};
//-----------------------------------------------------------------------------
class ReturnStatement : public Statement
{
public:
ReturnStatement(Expression * expr)
: Statement("return Statement"),
retval(expr)
{};
virtual void Emit(FILE * out);
private:
Expression * retval;
};
//-----------------------------------------------------------------------------
class ContStatement : public Statement
{
public:
ContStatement(bool do_brk)
: Statement("break/continue Statement"),
do_break(do_brk)
{};
virtual void Emit(FILE * out);
private:
bool do_break; // true for break, false for continue
};
//-----------------------------------------------------------------------------
class FunctionDefinition : public Node
{
public:
FunctionDefinition(TypeSpecifier * ds, Declarator * decl,
DeclarationList * dl);
virtual void Emit(FILE * out);
FunctionDefinition * SetBody(CompoundStatement * bdy)
{ body = bdy; return this; };
private:
TypeName * ret_type;
Declarator * fun_declarator;
DeclarationList * decl_list;
CompoundStatement * body;
};
//-----------------------------------------------------------------------------
#endif
| 28.513183 | 79 | 0.548925 | [
"vector"
] |
cdf2d513b79d6ad5b84e0ce46f6bf1613831eebe | 4,942 | hpp | C++ | CSGOSimple/valve_sdk/interfaces/IClientEntity.hpp | D1ckRider/Dickware | d0b2417505437c7f67fe687a81a43d459f09af7f | [
"MIT"
] | 3 | 2019-11-17T19:52:44.000Z | 2020-02-26T18:22:25.000Z | CSGOSimple/valve_sdk/interfaces/IClientEntity.hpp | Renji-kun/Dickware | d0b2417505437c7f67fe687a81a43d459f09af7f | [
"MIT"
] | 12 | 2019-01-17T14:52:06.000Z | 2019-03-21T17:01:09.000Z | CSGOSimple/valve_sdk/interfaces/IClientEntity.hpp | D1ckRider/Dickware | d0b2417505437c7f67fe687a81a43d459f09af7f | [
"MIT"
] | 9 | 2019-06-02T18:26:13.000Z | 2020-04-21T19:21:48.000Z | #pragma once
#include "IClientNetworkable.hpp"
#include "IClientRenderable.hpp"
#include "IClientUnknown.hpp"
#include "IClientThinkable.hpp"
struct SpatializationInfo_t;
class IClientEntity : public IClientUnknown, public IClientRenderable, public IClientNetworkable, public IClientThinkable
{
public:
virtual void Release(void) = 0;
virtual const Vector& GetAbsOrigin(void) const = 0;
virtual const QAngle& GetAbsAngles(void) const = 0;
};
#pragma pack(push, 1)
class CCSWeaponInfo { //xSeeker
public:
char pad_0x0000[4]; // 0x0000
char* consoleName; // 0x0004
char pad_0008[12]; // 0x0008
int iMaxClip1; // 0x0014
int iMaxClip2; // 0x0018
int iDefaultClip1; // 0x001C
int iDefaultClip2; // 0x0020
char pad_0024[8]; // 0x0024
char* szWorldModel; // 0x002C
char* szViewModel; // 0x0030
char* szDroppedModel; // 0x0034
char pad_0038[4]; // 0x0038
char* N0000023E; // 0x003C
char pad_0040[56]; // 0x0040
char* szEmptySound; // 0x0078
char pad_007C[4]; // 0x007C
char* szBulletType; // 0x0080
char pad_0084[4]; // 0x0084
char* szHudName; // 0x0088
char* szWeaponName; // 0x008C
char pad_0090[56]; // 0x0090
int WeaponType; // 0x00C8
int iWeaponPrice; // 0x00CC
int iKillAward; // 0x00D0
char _0x00D8[24];
bool bFullAuto; //0x00EC
char _0x00ED[3];
int iDamage; //0x00F0
/*
char* szAnimationPrefix; // 0x00D4
float flCycleTime; // 0x00D8
float flCycleTimeAlt; // 0x00DC
float flTimeToIdle; // 0x00E0
float flIdleInterval; // 0x00E4
bool bFullAuto; // 0x00E8
char pad_0x00E5[3]; // 0x00E9
int iDamage; // 0x00EC
*/
/*
char _0x0000[20];
__int32 max_clip; //0x0014
char _0x0018[12];
__int32 max_reserved_ammo; //0x0024
char _0x0028[96];
char* hud_name; //0x0088
char* szWeaponName; //0x008C
char _0x0090[64]; //custom
int WeaponType; //0x00CC
__int32 price; //0x00D0
__int32 reward; //0x00D4
char _0x00D8[16];
BYTE bFullAuto; //0x00EC
char _0x00ED[3];
__int32 iDamage; //0x00F0
*/
//
float flArmorRatio; // 0x00F0
int iBullets; // 0x00F4
float flPenetration; // 0x00F8
char _0x0100[8];
float flRange; // 0x0104
float flRangeModifier; // 0x0108
float flThrowVelocity; // 0x010C
char pad_0x010C[12]; // 0x0110
bool bHasSilencer; // 0x011C
char pad_0x0119[3]; // 0x011D
char* pSilencerModel; // 0x0120
int iCrosshairMinDistance; // 0x0124
int iCrosshairDeltaDistance;// 0x0128 - iTeam?
float flMaxPlayerSpeed; // 0x012C
float flMaxPlayerSpeedAlt; // 0x0130
float flSpread; // 0x0134
float flSpreadAlt; // 0x0138
float flInaccuracyCrouch; // 0x013C
float flInaccuracyCrouchAlt; // 0x0140
float flInaccuracyStand; // 0x0144
float flInaccuracyStandAlt; // 0x0148
float flInaccuracyJumpInitial;// 0x014C
float flInaccuracyJump; // 0x0150
float flInaccuracyJumpAlt; // 0x0154
float flInaccuracyLand; // 0x0158
float flInaccuracyLandAlt; // 0x015C
float flInaccuracyLadder; // 0x0160
float flInaccuracyLadderAlt; // 0x0164
float flInaccuracyFire; // 0x0168
float flInaccuracyFireAlt; // 0x016C
float flInaccuracyMove; // 0x0170
float flInaccuracyMoveAlt; // 0x0174
float flInaccuracyReload; // 0x0178
int iRecoilSeed; // 0x017C
float flRecoilAngle; // 0x0180
float flRecoilAngleAlt; // 0x0184
float flRecoilAngleVariance; // 0x0188
float flRecoilAngleVarianceAlt; // 0x018C
float flRecoilMagnitude; // 0x0190
float flRecoilMagnitudeAlt; // 0x0194
float flRecoilMagnitudeVariance; // 0x0198
float flRecoilMagnitudeVarianceAlt; // 0x019C
float flRecoveryTimeCrouch; // 0x01A0
float flRecoveryTimeStand; // 0x01A4
float flRecoveryTimeCrouchFinal; // 0x01A8
float flRecoveryTimeStandFinal; // 0x01AC
int iRecoveryTransitionStartBullet;// 0x01B0
int iRecoveryTransitionEndBullet; // 0x01B4
bool bUnzoomAfterShot; // 0x01B8
bool bHideViewModelZoomed; // 0x01B9
char pad_0x01B5[2]; // 0x01BA
char iZoomLevels[3]; // 0x01BC
int iZoomFOV[2]; // 0x01C0
float fZoomTime[3]; // 0x01C4
char* szWeaponClass; // 0x01D4
float flAddonScale; // 0x01D8
char pad_0x01DC[4]; // 0x01DC
char* szEjectBrassEffect; // 0x01E0
char* szTracerEffect; // 0x01E4
int iTracerFrequency; // 0x01E8
int iTracerFrequencyAlt; // 0x01EC
char* szMuzzleFlashEffect_1stPerson; // 0x01F0
char pad_0x01F4[4]; // 0x01F4
char* szMuzzleFlashEffect_3rdPerson; // 0x01F8
char pad_0x01FC[4]; // 0x01FC
char* szMuzzleSmokeEffect; // 0x0200
float flHeatPerShot; // 0x0204
char* szZoomInSound; // 0x0208
char* szZoomOutSound; // 0x020C
float flInaccuracyPitchShift; // 0x0210
float flInaccuracySoundThreshold; // 0x0214
float flBotAudibleRange; // 0x0218
BYTE pad_0x0218[8]; // 0x0220
char* pWrongTeamMsg; // 0x0224
bool bHasBurstMode; // 0x0228
BYTE pad_0x0225[3]; // 0x0229
bool bIsRevolver; // 0x022C
bool bCannotShootUnderwater; // 0x0230 };
};
#pragma pack(pop)
class IWeaponSystem
{
virtual void unused0() = 0;
virtual void unused1() = 0;
public:
virtual const CCSWeaponInfo* GetWpnData(unsigned ItemDefinitionIndex) = 0;
}; | 28.900585 | 121 | 0.739984 | [
"vector"
] |
a80272177e09d50b97dda1ba00c9697b698b1ba7 | 3,091 | cpp | C++ | tf2_src/game/server/tf/bot_npc/bot_npc_mini.cpp | IamIndeedGamingAsHardAsICan03489/TeamFortress2 | 1b81dded673d49adebf4d0958e52236ecc28a956 | [
"MIT"
] | 4 | 2021-10-03T05:16:55.000Z | 2021-12-28T16:49:27.000Z | tf2_src/game/server/tf/bot_npc/bot_npc_mini.cpp | Counter2828/TeamFortress2 | 1b81dded673d49adebf4d0958e52236ecc28a956 | [
"MIT"
] | null | null | null | tf2_src/game/server/tf/bot_npc/bot_npc_mini.cpp | Counter2828/TeamFortress2 | 1b81dded673d49adebf4d0958e52236ecc28a956 | [
"MIT"
] | 3 | 2022-02-02T18:09:58.000Z | 2022-03-06T18:54:39.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
// bot_npc_mini.cpp
// A NextBot non-player derived actor
// Michael Booth, March 2011
#include "cbase.h"
#ifdef TF_RAID_MODE
#include "tf_player.h"
#include "tf_gamerules.h"
#include "tf_team.h"
#include "tf_projectile_arrow.h"
#include "tf_projectile_rocket.h"
#include "tf_weapon_grenade_pipebomb.h"
#include "tf_ammo_pack.h"
#include "tf_obj_sentrygun.h"
#include "nav_mesh/tf_nav_area.h"
#include "bot_npc_mini.h"
#include "NextBot/Path/NextBotChasePath.h"
#include "econ_wearable.h"
#include "team_control_point_master.h"
#include "particle_parse.h"
#include "CRagdollMagnet.h"
#include "nav_mesh/tf_path_follower.h"
#include "bot_npc_minion.h"
#include "player_vs_environment/monster_resource.h"
extern ConVar tf_bot_npc_reaction_time;
extern ConVar tf_bot_npc_grenade_interval;
extern float ModifyBossDamage( const CTakeDamageInfo &info );
ConVar tf_raid_mini_rocket_boss_health( "tf_raid_mini_rocket_boss_health", "5000", 0/*FCVAR_CHEAT*/ );
//-----------------------------------------------------------------------------------------------------
// The Bot NPC mini-boss
//-----------------------------------------------------------------------------------------------------
LINK_ENTITY_TO_CLASS( bot_boss_mini_rockets, CBotNPCMiniRockets );
PRECACHE_REGISTER( bot_boss_mini_rockets );
//-----------------------------------------------------------------------------------------------------
void CBotNPCMiniRockets::Precache()
{
BaseClass::Precache();
int model = PrecacheModel( "models/bots/knight/knight_mini.mdl" );
PrecacheGibsForModel( model );
PrecacheScriptSound( "RobotMiniBoss.LaunchRocket" );
}
//-----------------------------------------------------------------------------------------------------
void CBotNPCMiniRockets::Spawn( void )
{
BaseClass::Spawn();
SetModel( "models/bots/knight/knight_mini.mdl" );
int health = tf_raid_mini_rocket_boss_health.GetInt();
SetHealth( health );
SetMaxHealth( health );
}
//-----------------------------------------------------------------------------------------------------
// The Bot NPC mini-boss
//-----------------------------------------------------------------------------------------------------
LINK_ENTITY_TO_CLASS( bot_boss_mini_nuker, CBotNPCMiniNuker );
PRECACHE_REGISTER( bot_boss_mini_nuker );
ConVar tf_raid_mini_nuker_boss_health( "tf_raid_mini_nuker_boss_health", "5000", 0/*FCVAR_CHEAT*/ );
//-----------------------------------------------------------------------------------------------------
void CBotNPCMiniNuker::Precache()
{
BaseClass::Precache();
int model = PrecacheModel( "models/bots/knight/knight_mini.mdl" );
PrecacheGibsForModel( model );
}
//-----------------------------------------------------------------------------------------------------
void CBotNPCMiniNuker::Spawn( void )
{
BaseClass::Spawn();
SetModel( "models/bots/knight/knight_mini.mdl" );
int health = tf_raid_mini_nuker_boss_health.GetInt();
SetHealth( health );
SetMaxHealth( health );
}
#endif // TF_RAID_MODE
| 30.303922 | 103 | 0.563248 | [
"model"
] |
a804f41b42c157b222d9ec8748ed3830e8fa5040 | 19,729 | cpp | C++ | src/branchingratios.cpp | pgdeniverville/MyMC | 6cba825ccc6ee9cc4f5ac6a131f677b14215e1ea | [
"MIT"
] | 5 | 2017-03-28T16:10:24.000Z | 2020-02-26T18:57:26.000Z | src/branchingratios.cpp | pgdeniverville/MyMC | 6cba825ccc6ee9cc4f5ac6a131f677b14215e1ea | [
"MIT"
] | null | null | null | src/branchingratios.cpp | pgdeniverville/MyMC | 6cba825ccc6ee9cc4f5ac6a131f677b14215e1ea | [
"MIT"
] | 4 | 2019-10-08T08:18:22.000Z | 2020-07-14T09:15:42.000Z | #include "branchingratios.h"
#include "Integrator.h"
#include "Random.h"
#include "Kinematics.h"
#include "constants.h"
#include <functional>
#include <cmath>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <memory>
using std::cout; using std::endl;
const double mp = MASS_PROTON;
//const double mpim = MASS_PION_CHARGED;
const double metap = 0.95778;
const double Br_etap_to_gamma_gamma=0.022;
const double Br_etap_to_gamma_rho=0.291;
const double Br_etap_to_gamma_omega=0.0275;
const double Br_phi_to_e_e=2.9e-4;
const double Br_rho_to_e_e = 4.72e-5;
const double Br_omega_to_e_e = 7.28e-5;
const double mmuon = MASS_MUON;
const double etafactor = 0.61;
const std::string rratio_filename = "data/rratio.dat";
static std::shared_ptr<Linear_Interpolation> rratio;
bool rratio_loaded=false;
/********************
* R-RATIO
********************/
//Should just write a general function for reading in data files.
void Load_2D_Interpolation(const std::string& filename, std::shared_ptr<Linear_Interpolation>& ff){
std::ifstream instream(filename);
if(!instream.is_open()){
std::cerr << "Cannot open " << filename << std::endl;
throw -1;
}
std::vector<double> dist;
double in, x_min, x_max;
instream >> x_min;
instream >> in;
dist.push_back(in);
while(instream >> x_max){
instream >> in;
dist.push_back(in);
}
ff = std::shared_ptr<Linear_Interpolation>(new Linear_Interpolation(dist, x_min,x_max));
}
/********************
*KINETIC COUPLING
********************/
double brpi0toVgamma(double mv, double mx, double kappa, double alphaD){
if(mv>mpi0)
return 0;
return 2*pow(kappa,2)*pow(1-mv*mv/pow(mpi0,2),3)*brpi0to2gamma;
}
double bretatoVgamma(double mv, double mx, double kappa, double alphaD){
if(mv>meta)
return 0;
return 2*pow(kappa,2)*pow(1-mv*mv/pow(meta,2),3)*bretato2gamma;
}
double rhofunc(double x){
if(x<0.77)
return exp(-14*(0.77-x));
else
return exp(20*(0.77-x));
}
double brrho_to_V_1(double mv, double mx, double kappa, double alphaD){
return 3.0*pow(kappa,2.0)/alphaEM*Br_rho_to_e_e*pow(mrho,3)*GammaV_to_dm_dm(mv,mx,kappa,alphaD)/
(pow(pow(mrho,2)-mv*mv,2)+pow(mv*GammaV(mv,mx,kappa,alphaD),2));
}
double brrho_to_V(double mv, double mx, double kappa, double alphaD){
if(mv>1.6)
return 0.0;
return brrho_to_V_1(0.77, mx, kappa, alphaD)*rhofunc(mv);
}
double bromega_to_V(double mv, double mx, double kappa, double alphaD){
if(mv-momega>0.1||momega-mv>0.1)
return 0.0;
return 3.0*pow(kappa,2)/alphaEM*Br_omega_to_e_e*pow(momega,3)*GammaV_to_dm_dm(mv,mx,kappa,alphaD)/
(pow(pow(momega,2)-mv*mv,2)+pow(mv*GammaV(mv,mx,kappa,alphaD),2));
}
//I could give this the off-shell treatment, but probably not worth it.
double br_eta_prime_to_V(double mv, double mx, double kappa, double alphaD){
if(mv>=metap)
return 0;
double tot = 2*pow(1-pow(mv/metap,2),3)*Br_etap_to_gamma_gamma;
if(mv<metap-mrho)
tot+=pow(1-pow(mv/(metap-mrho),2),1.5)*Br_etap_to_gamma_rho;
if(mv<metap-momega)
tot+=pow(1-pow(mv/(metap-momega),2),1.5)*Br_etap_to_gamma_omega;
return tot*pow(kappa,2);
}
double brphi_to_V(double mv, double mx, double kappa, double alphaD){
if(mv-mphi>0.15||mphi-mv>0.15)
return 0.0;
return 3.0*pow(kappa,2)/alphaEM*Br_phi_to_e_e*pow(mphi,3)*GammaV_to_dm_dm(mv,mx,kappa,alphaD)/
(pow(pow(mphi,2)-mv*mv,2)+pow(mv*GammaV(mv,mx,kappa,alphaD),2));
}
double brmasstoVgamma(double mass, double mv, double mx, double kappa, double alphaD){
if(mv>mass)
return 0;
return 2*pow(kappa,2)*pow(1-mv*mv/pow(mass,2),3);//scaling less dubious
}
//V to l+l-
double Gamma_V_to_leptons(double mA, double eps, double ml){
if(mA<2*ml){
return 0;
}
return pow(eps*G_ELEC,2)*sqrt(pow(mA,2)-4*ml*ml)*(mA*mA+2*ml*ml)/(12*pi*mA*mA);
}
double Gamma_V_to_hadrons(double mv, double kappa){
if(mv>MASS_MUON)
return Gamma_V_to_leptons(mv,kappa,MASS_MUON)*RRATIO(mv);
return 0;
}
double RRATIO(double mv){
if(!rratio_loaded){
Load_2D_Interpolation(rratio_filename,rratio);
rratio_loaded=true;
}
return rratio->Interpolate(mv);
}
double Gamma_V_to_visible(double mv, double kappa){
return Gamma_V_to_leptons(mv, kappa, MASS_ELECTRON)+Gamma_V_to_leptons(mv, kappa, MASS_MUON)+Gamma_V_to_hadrons(mv, kappa);
}
double Gamma_V(double mv, double mx, double kappa, double alphaD){
return Gamma_V_to_visible(mv, kappa)+GammaV_to_dm_dm(mv, mx, kappa, alphaD);
}
double GammaV(double mv, double mx, double kappa, double alphaD){
double term = 0;
if(mv>2*mx){
term = alphaD*(mv*mv-4*mx*mx)*sqrt(mv*mv/4-mx*mx);
}
if(mv>2*MASS_ELECTRON){
term += 4*pow(kappa,2)*alphaEM*(2*pow(MASS_ELECTRON,2)+mv*mv)*sqrt(mv*mv/4-pow(MASS_ELECTRON,2));
}
if(mv>2*mmuon){
term += 4*pow(kappa,2)*alphaEM*(2*pow(mmuon,2)+mv*mv)*sqrt(mv*mv/4-pow(mmuon,2));//I need to multiply this by the RRatio, but it's a minor overall effect when V->DM+DM is available;
}
return 1.0/(6.0*mv*mv)*(term);
}
double GammaV_to_dm_dm(double mv, double mx, double kappa, double alphaD){
if(mv<=2*mx)
return 0;
return alphaD*(mv*mv-4*mx*mx)*sqrt(mv*mv/4.0-mx*mx)/(6.0*mv*mv);
}
double brV_to_dm_dm(double mv, double mx, double kappa, double alphaD){
if(mv<=2*mx)
return 0;
return GammaV_to_dm_dm(mv, mx, kappa, alphaD)/GammaV(mv, mx, kappa, alphaD);
}
double d2brpi0_to_gamma_dm_dm(double mv, double mx, double kappa, double alphaD, double s, double theta){
return sqrt(1-4*mx*mx/s)*pow(pow(mpi0,2)-s,3)*(s-4*mx*mx)*alphaD*pow(kappa,2)*pow(sin(theta),3)/(8*pow(mpi0,6)*pi*(pow(s-mv*mv,2)+pow(mv*GammaV(mv,mx,kappa,alphaD),2)));
}
double dbrpi0_to_gamma_dm_dm(double mv, double mx, double kappa, double alphaD, double s){
return sqrt(1.0-4.0*mx*mx/s)*pow(pow(mpi0,2)-s,3)*(s-4.0*mx*mx)*alphaD*pow(kappa,2)/(6.0*pow(mpi0,6)*pi*(pow(s-mv*mv,2)+pow(mv*GammaV(mv,mx,kappa,alphaD),2)));
}
double brpi0_to_gamma_dm_dm(double mv, double mx, double kappa, double alphaD){
using namespace std::placeholders;
auto dbr = std::bind(dbrpi0_to_gamma_dm_dm,mv,mx,kappa,alphaD,_1);
return DoubleExponential_adapt(dbr,4*mx*mx,pow(mpi0,2),100,0.1,1e-4);
}
double d2breta_to_gamma_dm_dm(double mv, double mx, double kappa, double alphaD, double s, double theta){
return bretato2gamma/brpi0to2gamma*sqrt(1-4*mx*mx/s)*pow(pow(meta,2)-s,3)*(s-4*mx*mx)*alphaD*pow(kappa,2)*pow(sin(theta),3)/(8*pow(meta,6)*pi*(pow(s-mv*mv,2)+pow(mv*GammaV(mv,mx,kappa,alphaD),2)));
}
double dbreta_to_gamma_dm_dm(double mv, double mx, double kappa, double alphaD, double s){
return bretato2gamma/brpi0to2gamma*sqrt(1.0-4.0*mx*mx/s)*pow(pow(meta,2)-s,3)*(s-4.0*mx*mx)*alphaD*pow(kappa,2)/(6.0*pow(meta,6)*pi*(pow(s-mv*mv,2)+pow(mv*GammaV(mv,mx,kappa,alphaD),2)));
}
double breta_to_gamma_dm_dm(double mv, double mx, double kappa, double alphaD){
using namespace std::placeholders;
auto dbr = std::bind(dbreta_to_gamma_dm_dm,mv,mx,kappa,alphaD,_1);
return DoubleExponential_adapt(dbr,4*mx*mx,pow(meta,2),100,0.1,1e-4);
}
//This is a nebulous placeholder function. I don't know how well it will work!
double brmasstoV(double mass, double mv, double mx, double kappa, double alphaD){
if(mv>mass){
return 0;
}
return pow(kappa,2)*pow(1-mv*mv/pow(mass,2),3)*0.5;
}
double d2brmass_to_dm_dm(double mmeson, double mv, double mx, double kappa, double alphaD, double s, double theta){
// return alphaD*pow(kappa,2)*sqrt(1-4*mx*mx/s)*(1-s/pow(mpi0,2))*(pow(pow(mpi0,2)-s,2)-16*pow(TriangleFunction(mpi0,s,0)*TriangleFunction(s,mx,mx)*cos(theta),2)*s)*Sin(theta)/(8*mpi0^4*pi*(pow(s-mv*mv,2)+pow(mv*GammaV(mv,mx,kappa,alphaD),2)))
return sqrt(1-4*mx*mx/s)*pow(pow(mmeson,2)-s,3)*(s-4*mx*mx)*alphaD*pow(kappa,2)*pow(sin(theta),3)/(8*pow(mmeson,6)*pi*(pow(s-mv*mv,2)+pow(mv*GammaV(mv,mx,kappa,alphaD),2)));
}
double dbrmass_to_dm_dm(double mmeson, double mv, double mx, double kappa, double alphaD, double s){
return sqrt(1.0-4.0*mx*mx/s)*pow(pow(mmeson,2)-s,3)*(s-4.0*mx*mx)*alphaD*pow(kappa,2)/(6.0*pow(mmeson,6)*pi*(pow(s-mv*mv,2)+pow(mv*GammaV(mv,mx,kappa,alphaD),2)));
}
double brmass_to_dm_dm(double mmeson, double mv, double mx, double kappa, double alphaD){
using namespace std::placeholders;
auto dbr = std::bind(dbrmass_to_dm_dm,mmeson, mv,mx,kappa,alphaD,_1);
return DoubleExponential_adapt(dbr,4*mx*mx,pow(mmeson,2),100,0.1,1e-4);
}
//divide by 4?
double wpp(double z, double pt2, double mA){
double H = pt2+(1-z)*mA*mA + pow(z*mp,2);
return 1.0/4.0/(2*pi*H)*((1+pow(1-z,2))/z-2*z*(1-z)*((2*mp*mp+mA*mA)/H-2*pow(z*mp*mp/H,2))+2*z*(1-z)*(z+pow(1-z,2))*pow(mp*mA/H,2)+2*z*pow((1-z)*mA*mA/H,2));
}
double wpp_scalar(double z, double pt2, double mA, double epsilon){
double H = pt2+(1-z)*mA*mA + pow(z*mp,2);
return pow(epsilon,2)*alphaEM/(8*pi)*(8*pow(mp,4)*(z-1)*pow(z,3)/pow(H,3)+4*pow(mp*mA,2)*(z-1)*pow(z,3)/pow(H,3)-8*pow(mp,2)*(z-1)*z/pow(H,2)+z/H);
}
/*
double wpp_v_scalar(double z, double pt2, double ma){
double H = pt2+(1-z)*ma*ma+pow(z*mp,2);
return 1.0/16.0/pi/pi
}*/
/********************
*BARYONIC COUPLING
********************/
//Not implemented for masses above the three pion threshold.
double GammaVB_to_dm_dm(double mv, double mx, double kappa, double alphaD){
if(mv>2*mx){
return alphaD*(mv*mv-4*mx*mx)*sqrt(mv*mv/4-mx*mx)/(6*mv*mv);
}
return 0;
}
double GammaVB(double mv, double mx, double kappa, double alphaD){
return GammaVB_to_dm_dm(mv, mx, kappa, alphaD);
}
double brVB_to_dm_dm(double mv, double mx, double kappa, double alphaD){
if(mv<=2*mx)
return 0;
return GammaVB_to_dm_dm(mv, mx, kappa, alphaD)/GammaVB(mv, mx, kappa, alphaD);
}
double brpi0toVBgamma(double mv, double mx, double kappa, double alphaD){
if(mv>mpi0)
return 0;
return 2*pow(sqrt(alphaD/alphaEM)-kappa,2)*pow(1-mv*mv/pow(mpi0,2),3)*brpi0to2gamma;
}
double d2brpi0_to_gamma_dm_dm_baryonic(double mv, double mx, double kappa, double alphaD, double s, double theta){
return sqrt(1-4*mx*mx/s)*pow(pow(mpi0,2)-s,3)*(s-4*mx*mx)*pow(alphaD,1)*pow(sqrt(alphaD/alphaEM)-kappa,2)*pow(sin(theta),3)/(8*pow(mpi0,6)*pi*(pow(s-mv*mv,2)+pow(mv*GammaVB(mv,mx,kappa,alphaD),2)));
}
double dbrpi0_to_gamma_dm_dm_baryonic(double mv, double mx, double kappa, double alphaD, double s){
return sqrt(1.0-4.0*mx*mx/s)*pow(pow(mpi0,2)-s,3)*(s-4.0*mx*mx)*pow(alphaD,1)*pow(sqrt(alphaD/alphaEM)-kappa,2)/(6.0*pow(mpi0,6)*pi*(pow(s-mv*mv,2)+pow(mv*GammaVB(mv,mx,kappa,alphaD),2)));
}
double brpi0_to_gamma_dm_dm_baryonic(double mv, double mx, double kappa, double alphaD){
using namespace std::placeholders;
auto dbr = std::bind(dbrpi0_to_gamma_dm_dm_baryonic,mv,mx,kappa,alphaD,_1);
if(mv>2*mx&&mv<mpi0){
double up = mv*mv+5*mv*GammaVB(mv, mx, kappa, alphaD);
double down = mv*mv-5*mv*GammaVB(mv, mx, kappa, alphaD);
if(down<4*mx*mx)
down = 4*mx*mx;
if(up>pow(mpi0,2))
up = pow(mpi0,2);
double low = DoubleExponential_adapt(dbr,4*mx*mx,down, 2 ,0.1,1e-4);
double mid = DoubleExponential_adapt(dbr,down, up, 2 ,0.1,1e-5);
double high = DoubleExponential_adapt(dbr, up, pow(mpi0,2), 2 ,0.1,1e-4);
return low+mid+high;
}
else{
return DoubleExponential_adapt(dbr,4*mx*mx,pow(mpi0,2),100,0.1,1e-4);
}
}
double bretatoVBgamma(double mv, double mx, double kappa, double alphaD){
if(mv>meta)
return 0;
return 2*pow(etafactor*sqrt(alphaD/alphaEM)-kappa,2)*pow(1-mv*mv/pow(meta,2),3)*bretato2gamma;
}
double d2breta_to_gamma_dm_dm_baryonic(double mv, double mx, double kappa, double alphaD, double s, double theta){
return bretato2gamma*sqrt(1-4*mx*mx/s)*pow(pow(meta,2)-s,3)*(s-4*mx*mx)*pow(alphaD,1)*pow(etafactor*sqrt(alphaD/alphaEM)-kappa,2)*pow(sin(theta),3)/(8*pow(meta,6)*pi*(pow(s-mv*mv,2)+pow(mv*GammaVB(mv,mx,kappa,alphaD),2)));
}
double dbreta_to_gamma_dm_dm_baryonic(double mv, double mx, double kappa, double alphaD, double s){
return bretato2gamma*sqrt(1.0-4.0*mx*mx/s)*pow(pow(meta,2)-s,3)*(s-4.0*mx*mx)*pow(alphaD,1)*pow(etafactor*sqrt(alphaD/alphaEM)-kappa,2)/(6.0*pow(meta,6)*pi*(pow(s-mv*mv,2)+pow(mv*GammaVB(mv,mx,kappa,alphaD),2)));
}
double breta_to_gamma_dm_dm_baryonic(double mv, double mx, double kappa, double alphaD){
using namespace std::placeholders;
auto dbr = std::bind(dbreta_to_gamma_dm_dm_baryonic,mv,mx,kappa,alphaD,_1);
if(mv>2*mx&&mv<meta){
double up = mv*mv+5*mv*GammaVB(mv, mx, kappa, alphaD);
double down = mv*mv-5*mv*GammaVB(mv, mx, kappa, alphaD);
if(down<4*mx*mx)
down = 4*mx*mx;
if(up>pow(meta,2))
up = pow(meta,2);
double low = DoubleExponential_adapt(dbr,4*mx*mx,down, 100 ,0.1,1e-4);
double mid = DoubleExponential_adapt(dbr,down, up, 100 ,0.1,1e-4);
double high = DoubleExponential_adapt(dbr, up, pow(meta,2), 100 ,0.1,1e-4);
return low+mid+high;
}
else{
return DoubleExponential_adapt(dbr,4*mx*mx,pow(meta,2),100,0.1,1e-4);
}
}
double bromega_to_Vb(double mv, double mx, double kappa, double alphaD){
return 0.25*pow(2*sqrt(alphaD/alphaEM)-kappa,2)*alphaD/alphaEM*Br_omega_to_e_e*pow(momega,4)/ \
(pow(pow(momega,2)-pow(mv,2),2)+1e-4*pow(momega,4))*pow(1-4*pow(mx/mv,2),1.5);//Where does that 1e-4 come from? Must be the width of Omega.
}
double brphi_to_Vb(double mv, double mx, double kappa, double alphaD){
if(mv-mphi>0.25||mphi-mv>0.25)
return 0.0;
return 0.25*pow(-sqrt(alphaD/alphaEM)-kappa,2)*alphaD/alphaEM*Br_phi_to_e_e*pow(momega,4)/ \
(pow(pow(mphi,2)-pow(mv,2),2)+1e-4*pow(mphi,4))*pow(1-4*pow(mx/mv,2),1.5);
}
namespace Inelastic_DM{
double Gamma_A_to_dm1_dm2(double mass_dp, double mass_dm1,double mass_dm2,double alpha_D){
if(mass_dp<mass_dm1+mass_dm2){
return 0;
}
else{//Needs testing
return -alpha_D*one_to_two_decay::two_body_momentum(mass_dp,mass_dm1,mass_dm2)/(3*pow(mass_dp,4))*\
(mass_dm1-mass_dm2-mass_dp)*(mass_dm1-mass_dm2+mass_dp)*(pow(mass_dm1+mass_dm2,2)+2*pow(mass_dp,2));
}
}
}
namespace Dark_Scalar{
using namespace std::complex_literals;
double betha(double m_S, double m){
return sqrt(1-pow(2*m/m_S,2));
}
double S_to_2leptons(double epsilon, double m_S, double m_lepton){
if(m_S <= 2*m_lepton)
return 0;
return (m_S*pow(epsilon,2)*pow(betha(m_S,m_lepton),3))/(8*pi)*pow(m_lepton/Vacuum_Expectation_Value,2);
}
std::complex<double> form_factor(double x){
if (x<=1){
return pow(asin(sqrt(x)),2);
}
else{
return -1.0/4.0*pow(log((1+sqrt(1.0-1.0/x))/(1-sqrt(1.0-1.0/x))) -1i*pi,2);
}
}
double S_to_2photon(double epsilon_l, double epsilon_q, double epsilon_w, double m_S){
double m_quark_uplike[3] = {MASS_UP, MASS_CHARM, MASS_TOP};
double m_quark_downlike[3] = {MASS_DOWN, MASS_STRANGE, MASS_BOTTOM};
double m_lepton[3] = {MASS_ELECTRON, MASS_MUON, MASS_TAU};
double v = Vacuum_Expectation_Value;
double x_w = pow(m_S/(2*MASS_W),2);
std::complex<double> A_W = -(2*x_w*x_w + 3*x_w + 3*(2*x_w-1)*form_factor(x_w))/pow(x_w,2);
std::complex<double> A_l = 0;
std::complex<double> A_q = 0;
double x_l,x_q;
for(int i=0; i!=3; i++){
x_l = pow(m_S/(2*m_lepton[i]),2);
A_l += 2.0*(x_l + (x_l-1)*form_factor(x_l))/pow(x_l,2);
}
for(int i=0; i!=3; i++){
x_q = pow(m_S/(2*m_quark_uplike[i]),2);
A_q += 3.0*pow(2.0/3.0,2)*(2.0*(x_q + (x_q-1.0)*form_factor(x_q))/pow(x_q,2));
}
for(int i=0; i!=3; i++){
x_q = pow(m_S/(2.0*m_quark_downlike[i]),2);
A_q += 3.0*pow(1.0/3.0,2)*(2.0*(x_q + (x_q-1)*form_factor(x_q))/pow(x_q,2));
}
std::complex<double> form_factor_photon = epsilon_q*A_q + epsilon_l*A_l + epsilon_w*A_W;
return pow(m_S,3)*pow(alphaEM/(4.0*pi),2)/(16*pi*v*v)*pow(abs(form_factor_photon),2);
}
}
/*
* DARK AXION WITH DARK PHOTON
*/
//This is currently incomplete, there are a bunch of processes I have
//yet to consider. Maybe I should go to Madgraph instead of doing it by hand?
namespace Ax_DP{
//From https://arxiv.org/abs/1611.01466
double Gamma_dp_to_a_gamma(double mA, double ma, double Gaggp){
if(ma>=mA){
return 0;
}
return pow(Gaggp,2)/(96*pi)*pow(mA,3)*pow(1-pow(ma/mA,2),3);
}
//From https://arxiv.org/abs/1611.01466
double Gamma_dp_to_lepton(double mA, double ml, double eps){
if(2*ml>mA)
return 0;
return pow(eps*G_ELEC,2)*sqrt(pow(mA,2)-4*ml*ml)*(mA*mA+2*ml*ml)/(12*pi*mA*mA);
}
double Gamma_dp_to_hadrons(double mA, double eps){
return Gamma_dp_to_lepton(mA, MASS_MUON, eps)*RRATIO(mA);
}
//From https://arxiv.org/abs/0807.3279
double Gamma_dp_to_3gamma(double mA, double eps, double ep){
if(3*mA>MASS_ELECTRON){
return 0;
}
return 17.0/288000.0/pow(pi,3)*pow(alphaEM,3)*ep*pow(mA,9)/pow(MASS_ELECTRON,8);
}
//This does not currently contain the R-Ratio. I will need to figure out a good way of including it at some point.
double Gamma_dp(double mA, double ma, double Gagpg, double eps, double ep){
return Gamma_dp_to_a_gamma( mA, ma, Gagpg) + Gamma_dp_to_lepton(mA, MASS_ELECTRON, eps) + Gamma_dp_to_lepton(mA, MASS_MUON, eps) + Gamma_dp_to_hadrons(mA, eps)+ Gamma_dp_to_3gamma( mA, eps, ep);
}
double Br_dp_to_a_gamma(double mA, double ma, double Gagpg, double eps, double ep){
/*cout << "Testing Br_dp_to_a_gamma\n";
cout << Gamma_dp_to_a_gamma(mA, ma, Gagpg) << endl;
cout << Gamma_dp_to_lepton(mA, MASS_MUON, eps) << endl;
cout << rratio->Interpolate(mA*mA) << endl;
cout << Gamma_dp(mA, ma, Gagpg, eps, ep) << endl;
cout << Gamma_dp_to_a_gamma(mA, ma, Gagpg)/Gamma_dp(mA, ma, Gagpg, eps, ep) << endl;*/
return Gamma_dp_to_a_gamma(mA, ma, Gagpg)/Gamma_dp(mA, ma, Gagpg, eps, ep);
}
double Br_dp_to_lepton(double mA, double ma, double ml, double Gagpg, double eps, double ep){
return Gamma_dp_to_lepton(mA, ml, eps)/Gamma_dp(mA, ma, Gagpg, eps, ep);
}
//Uses rratio, might not be valid at higher s?
double Br_dp_to_hadrons(double mA, double ma, double Gagpg, double eps, double ep){
if(!rratio_loaded){
Load_2D_Interpolation(rratio_filename,rratio);
rratio_loaded=true;
}
return Gamma_dp_to_hadrons(mA,eps)/Gamma_dp(mA, ma, Gagpg, eps, ep);
}
double Br_dp_to_3gamma(double mA, double ma, double Gagpg, double eps, double ep){
return Gamma_dp_to_3gamma(mA, eps, ep)/Gamma_dp(mA, ma, Gagpg, eps, ep);
}
}//End of namespace Ax_DP
/*******************
**GENERIC FUNCTIONS*
********************/
//mA is the mass of the emitted pseudoscalar, g is its coupling to the proton.
double brem_split_pseudoscalar(double z, double pt2, double ma, double g){
double H = pt2+(1-z)*ma*ma + pow(z*mp,2);
return pow(g,2)*z*(H*H+2*H*ma*ma*(z-1)-2*ma*ma*(z-1)*(pow(MASS_PROTON*z,2)-ma*ma*(z-1)))/(16*pow(pi*H,2));
}
double Gamma_pseudoscalar_to_2fermion(double g, double m_parent, double m_daughter){
return 3*g*g/8.0*m_parent*sqrt(1-pow(4*m_daughter/m_parent,2));
}
//Add Vector to two fermions, vector to two scalars. | 38.760314 | 245 | 0.652339 | [
"vector"
] |
a8060f5ed3c842f15a76cae524fc566becaea8bc | 7,167 | cpp | C++ | external_libs/link/src/ableton/link/tst_Peers.cpp | llloret/sp_link | b87ee622517fc68845b8f1d19c735c0e3bd05176 | [
"MIT"
] | null | null | null | external_libs/link/src/ableton/link/tst_Peers.cpp | llloret/sp_link | b87ee622517fc68845b8f1d19c735c0e3bd05176 | [
"MIT"
] | null | null | null | external_libs/link/src/ableton/link/tst_Peers.cpp | llloret/sp_link | b87ee622517fc68845b8f1d19c735c0e3bd05176 | [
"MIT"
] | 1 | 2021-02-22T11:37:41.000Z | 2021-02-22T11:37:41.000Z | /* Copyright 2016, Ableton AG, Berlin. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* If you would like to incorporate Link into a proprietary software application,
* please contact <link-devs@ableton.com>.
*/
#include <ableton/link/Peers.hpp>
#include <ableton/platforms/stl/Random.hpp>
#include <ableton/test/CatchWrapper.hpp>
#include <ableton/test/serial_io/Fixture.hpp>
namespace ableton
{
namespace link
{
namespace
{
using Random = ableton::platforms::stl::Random;
struct SessionMembershipCallback
{
void operator()()
{
++calls;
}
std::size_t calls = 0;
};
struct SessionTimelineCallback
{
void operator()(const SessionId& sessionId, const Timeline& timeline)
{
sessionTimelines.push_back(std::make_pair(sessionId, timeline));
}
std::vector<std::pair<SessionId, Timeline>> sessionTimelines;
};
struct SessionStartStopStateCallback
{
void operator()(const SessionId& sessionId, const StartStopState& startStopState)
{
sessionStartStopStates.push_back(std::make_pair(sessionId, startStopState));
}
std::vector<std::pair<SessionId, StartStopState>> sessionStartStopStates;
};
const auto fooPeer =
PeerState{{NodeId::random<Random>(), NodeId::random<Random>(),
Timeline{Tempo{60.}, Beats{1.}, std::chrono::microseconds{1234}},
StartStopState{false, Beats{0.}, std::chrono::microseconds{2345}}},
{}};
const auto barPeer =
PeerState{{NodeId::random<Random>(), NodeId::random<Random>(),
Timeline{Tempo{120.}, Beats{10.}, std::chrono::microseconds{500}}, {}},
{}};
const auto bazPeer =
PeerState{{NodeId::random<Random>(), NodeId::random<Random>(),
Timeline{Tempo{100.}, Beats{4.}, std::chrono::microseconds{100}}, {}},
{}};
const auto gateway1 = asio::ip::address::from_string("123.123.123.123");
const auto gateway2 = asio::ip::address::from_string("210.210.210.210");
using PeerVector = std::vector<typename Peers<test::serial_io::Context,
SessionMembershipCallback,
SessionTimelineCallback,
SessionStartStopStateCallback>::Peer>;
void expectPeers(const PeerVector& expected, const PeerVector& actual)
{
CHECK(expected == actual);
}
void expectSessionTimelines(const std::vector<std::pair<SessionId, Timeline>>& expected,
const SessionTimelineCallback& callback)
{
CHECK(expected == callback.sessionTimelines);
}
void expectStartStopStates(
const std::vector<std::pair<SessionId, StartStopState>>& expected,
const SessionStartStopStateCallback& callback)
{
CHECK(expected == callback.sessionStartStopStates);
}
} // anonymous namespace
TEST_CASE("Peers | EmptySessionPeersAfterInit", "[Peers]")
{
test::serial_io::Fixture io;
auto peers = makePeers(util::injectVal(io.makeIoContext()), SessionMembershipCallback{},
SessionTimelineCallback{}, SessionStartStopStateCallback{});
io.flush();
expectPeers({}, peers.sessionPeers(fooPeer.sessionId()));
}
TEST_CASE("Peers | AddAndFindPeer", "[Peers]")
{
auto membership = SessionMembershipCallback{};
auto sessions = SessionTimelineCallback{};
auto startStops = SessionStartStopStateCallback{};
test::serial_io::Fixture io;
auto peers = makePeers(util::injectVal(io.makeIoContext()), std::ref(membership),
std::ref(sessions), std::ref(startStops));
auto observer = makeGatewayObserver(peers, gateway1);
sawPeer(observer, fooPeer);
io.flush();
expectPeers({{fooPeer, gateway1}}, peers.sessionPeers(fooPeer.sessionId()));
CHECK(1u == membership.calls);
expectSessionTimelines({make_pair(fooPeer.sessionId(), fooPeer.timeline())}, sessions);
expectStartStopStates(
{make_pair(fooPeer.sessionId(), fooPeer.startStopState())}, startStops);
}
TEST_CASE("Peers | AddAndRemovePeer", "[Peers]")
{
auto membership = SessionMembershipCallback{};
test::serial_io::Fixture io;
auto peers = makePeers(util::injectVal(io.makeIoContext()), std::ref(membership),
SessionTimelineCallback{}, SessionStartStopStateCallback{});
auto observer = makeGatewayObserver(peers, gateway1);
sawPeer(observer, fooPeer);
peerLeft(observer, fooPeer.ident());
io.flush();
expectPeers({}, peers.sessionPeers(fooPeer.sessionId()));
CHECK(2u == membership.calls);
}
TEST_CASE("Peers | AddTwoPeersRemoveOne", "[Peers]")
{
auto membership = SessionMembershipCallback{};
auto sessions = SessionTimelineCallback{};
auto startStops = SessionStartStopStateCallback{};
test::serial_io::Fixture io;
auto peers = makePeers(util::injectVal(io.makeIoContext()), std::ref(membership),
std::ref(sessions), std::ref(startStops));
auto observer = makeGatewayObserver(peers, gateway1);
sawPeer(observer, fooPeer);
sawPeer(observer, barPeer);
peerLeft(observer, fooPeer.ident());
io.flush();
expectPeers({}, peers.sessionPeers(fooPeer.sessionId()));
expectPeers({{barPeer, gateway1}}, peers.sessionPeers(barPeer.sessionId()));
CHECK(3u == membership.calls);
}
TEST_CASE("Peers | AddThreePeersTwoOnSameGateway", "[Peers]")
{
auto membership = SessionMembershipCallback{};
auto sessions = SessionTimelineCallback{};
auto startStops = SessionStartStopStateCallback{};
test::serial_io::Fixture io;
auto peers = makePeers(util::injectVal(io.makeIoContext()), std::ref(membership),
std::ref(sessions), std::ref(startStops));
auto observer1 = makeGatewayObserver(peers, gateway1);
auto observer2 = makeGatewayObserver(peers, gateway2);
sawPeer(observer1, fooPeer);
sawPeer(observer2, fooPeer);
sawPeer(observer1, barPeer);
sawPeer(observer1, bazPeer);
io.flush();
expectPeers(
{{fooPeer, gateway1}, {fooPeer, gateway2}}, peers.sessionPeers(fooPeer.sessionId()));
CHECK(3 == membership.calls);
}
TEST_CASE("Peers | CloseGateway", "[Peers]")
{
auto membership = SessionMembershipCallback{};
auto sessions = SessionTimelineCallback{};
auto startStops = SessionStartStopStateCallback{};
test::serial_io::Fixture io;
auto peers = makePeers(util::injectVal(io.makeIoContext()), std::ref(membership),
std::ref(sessions), std::ref(startStops));
auto observer1 = makeGatewayObserver(peers, gateway1);
{
// The observer will close the gateway when it goes out of scope
auto observer2 = makeGatewayObserver(peers, gateway2);
sawPeer(observer2, fooPeer);
sawPeer(observer2, barPeer);
sawPeer(observer1, fooPeer);
sawPeer(observer2, bazPeer);
}
io.flush();
expectPeers({{fooPeer, gateway1}}, peers.sessionPeers(fooPeer.sessionId()));
CHECK(4 == membership.calls);
}
} // namespace link
} // namespace ableton
| 32.577273 | 90 | 0.726524 | [
"vector"
] |
a80810059e4386031e4db6dce9fc4beae68b131e | 1,707 | cpp | C++ | opencv_contrib/src/+cv/boardDump.cpp | 1123852253/mexopencv | 17db690133299f561924a45e9092673a4df66c5b | [
"BSD-3-Clause"
] | 571 | 2015-01-04T06:23:19.000Z | 2022-03-31T07:37:19.000Z | opencv_contrib/src/+cv/boardDump.cpp | 1123852253/mexopencv | 17db690133299f561924a45e9092673a4df66c5b | [
"BSD-3-Clause"
] | 362 | 2015-01-06T14:20:46.000Z | 2022-01-20T08:10:46.000Z | opencv_contrib/src/+cv/boardDump.cpp | 1123852253/mexopencv | 17db690133299f561924a45e9092673a4df66c5b | [
"BSD-3-Clause"
] | 300 | 2015-01-20T03:21:27.000Z | 2022-03-31T07:36:37.000Z | /**
* @file boardDump.cpp
* @brief mex interface for cv::aruco::Board
* @ingroup aruco
* @author Amro
* @date 2016
*/
#include "mexopencv.hpp"
#include "mexopencv_aruco.hpp"
#include "opencv2/aruco.hpp"
using namespace std;
using namespace cv;
using namespace cv::aruco;
/**
* Main entry called from Matlab
* @param nlhs number of left-hand-side arguments
* @param plhs pointers to mxArrays in the left-hand-side
* @param nrhs number of right-hand-side arguments
* @param prhs pointers to mxArrays in the right-hand-side
*/
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
// Check the number of arguments
nargchk(nrhs==1 && nlhs<=1);
// Argument vector
vector<MxArray> rhs(prhs, prhs+nrhs);
// Process
if (rhs[0].isStruct()) {
Ptr<Board> board = MxArrayToBoard(rhs[0]);
plhs[0] = toStruct(board);
}
else {
vector<MxArray> args(rhs[0].toVector<MxArray>());
nargchk(args.size() >= 1);
string type(args[0].toString());
if (type == "Board") {
Ptr<Board> board = create_Board(args.begin() + 1, args.end());
plhs[0] = toStruct(board);
}
else if (type == "GridBoard") {
Ptr<GridBoard> board = create_GridBoard(
args.begin() + 1, args.end());
plhs[0] = toStruct(board);
}
else if (type == "CharucoBoard") {
Ptr<CharucoBoard> board = create_CharucoBoard(
args.begin() + 1, args.end());
plhs[0] = toStruct(board);
}
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized board type %s", type.c_str());
}
}
| 29.431034 | 76 | 0.584651 | [
"vector"
] |
a80971ee05545a93156187cae6366fd7005e0082 | 3,507 | cpp | C++ | test/unit/module/math/cotd.cpp | clayne/eve | dc268b5db474376e1c53f5a474f5bb42b7c4cb59 | [
"MIT"
] | null | null | null | test/unit/module/math/cotd.cpp | clayne/eve | dc268b5db474376e1c53f5a474f5bb42b7c4cb59 | [
"MIT"
] | null | null | null | test/unit/module/math/cotd.cpp | clayne/eve | dc268b5db474376e1c53f5a474f5bb42b7c4cb59 | [
"MIT"
] | null | null | null | //==================================================================================================
/**
EVE - Expressive Vector Engine
Copyright : EVE Contributors & Maintainers
SPDX-License-Identifier: MIT
**/
//==================================================================================================
#include "test.hpp"
#include <eve/module/core.hpp>
#include <eve/module/core.hpp>
#include <eve/module/math.hpp>
#include <cmath>
//==================================================================================================
// Types tests
//==================================================================================================
EVE_TEST_TYPES( "Check return types of cotd"
, eve::test::simd::ieee_reals
)
<typename T>(eve::as<T>)
{
using v_t = eve::element_type_t<T>;
TTS_EXPR_IS( eve::cotd(T()) , T);
TTS_EXPR_IS( eve::cotd(v_t()), v_t);
};
//==================================================================================================
//== cotd tests
//==================================================================================================
auto mquarter_c = []<typename T>(eve::as<T> const & ){ return T(-45); };
auto quarter_c = []<typename T>(eve::as<T> const & ){ return T( 45); };
auto mhalf_c = []<typename T>(eve::as<T> const & ){ return T(-90 ); };
auto half_c = []<typename T>(eve::as<T> const & ){ return T( 90 ); };
auto mmed = []<typename T>(eve::as<T> const & ){ return -5000; };
auto med = []<typename T>(eve::as<T> const & ){ return 5000; };
EVE_TEST( "Check behavior of cotd on wide"
, eve::test::simd::ieee_reals
, eve::test::generate( eve::test::randoms(mquarter_c, quarter_c)
, eve::test::randoms(mhalf_c, half_c)
, eve::test::randoms(mmed, med))
)
<typename T>(T const& a0, T const& a1, T const& a2)
{
using eve::detail::map;
using eve::cotd;
using eve::diff;
using eve::deginrad;
using v_t = eve::element_type_t<T>;
auto ref = [](auto e) -> v_t { auto d = eve::sind(e); return d ? eve::cosd(e)/eve::sind(e): eve::nan(eve::as(e)); };
TTS_ULP_EQUAL(eve::quarter_circle(cotd)(a0) , map(ref, a0), 2);
TTS_ULP_EQUAL(eve::half_circle(cotd)(a0) , map(ref, a0), 2);
TTS_ULP_EQUAL(eve::half_circle(cotd)(a1) , map(ref, a1), 40);
TTS_ULP_EQUAL(eve::cotd(a0) , map(ref, a0), 2);
TTS_ULP_EQUAL(eve::cotd(a1) , map(ref, a1), 2);
TTS_ULP_EQUAL(eve::cotd(a2) , map(ref, a2), 2);
auto dinr = 1.7453292519943295769236907684886127134428718885417e-2l;
TTS_ULP_EQUAL(diff(cotd)(a0), map([dinr](auto e) -> v_t { return -dinr*eve::sqr(eve::cscd(e)); }, a0), 4);
};
EVE_TEST_TYPES( "Check corner cases of cotd"
, eve::test::simd::ieee_reals
)
<typename T>(eve::as<T>)
{
using eve::cotd;
TTS_ULP_EQUAL(cotd( T( 1)) , T(57.289961630759424687278147537112577980217522235144) , 2);
TTS_ULP_EQUAL(cotd(-T( 1)) , T(-57.289961630759424687278147537112577980217522235144) , 2);
TTS_ULP_EQUAL(cotd( T( 45)) , T(1) , 2);
TTS_ULP_EQUAL(cotd(-T( 45)) , T(-1) , 2);
TTS_ULP_EQUAL(cotd( T(500.0)) , T(-1.19175359259420995870530807186041933693070040770853) , 2);
TTS_ULP_EQUAL(cotd(-T(500.0)) , T(1.19175359259420995870530807186041933693070040770853) , 2);
};
| 44.392405 | 118 | 0.478757 | [
"vector"
] |
a80b161d34cb15a7d070d09ac9d67a8b17fe1b49 | 4,534 | cc | C++ | src/monster.cc | CS126SP20/final-project-agpai2 | 7e1b0730096ecfd77c5e60cc9999b9d6c920df4d | [
"MIT"
] | null | null | null | src/monster.cc | CS126SP20/final-project-agpai2 | 7e1b0730096ecfd77c5e60cc9999b9d6c920df4d | [
"MIT"
] | null | null | null | src/monster.cc | CS126SP20/final-project-agpai2 | 7e1b0730096ecfd77c5e60cc9999b9d6c920df4d | [
"MIT"
] | null | null | null | //
// Created by Aniruddha Pai on 4/26/20.
//
#include "zelda/monster.h"
#include <zelda/map.h>
using zelda::Map;
using zelda::Direction;
namespace zelda {
int rand_direction = 0;
Monster::Monster() {}
void Monster::SetUpMaps(Map maps) {
map_screens_ = maps.GetScreen();
}
void Monster::SetIsPlayerAttack(bool set_is_player_attack) {
is_player_attack_ = set_is_player_attack;
}
Direction Monster::GetMonsterDirection() { return monster_direction_; }
int Monster::GetMonstersKilled() { return monsters_killed_; }
bool Monster::IsMonstersAttacked(Direction d, Location l, int map_num) {
int p_row = l.Col();
int p_col = l.Row();
if (is_player_attack_) {
if (map_screens_[map_num].coordinates_[p_row - 1][p_col] == monster_ &&
d == Direction::kUp) {
map_screens_[map_num].coordinates_[p_row - 1][p_col] = empty_tile_;
monsters_killed_++;
is_monster_attacked_ = true;
} else if (map_screens_[map_num].coordinates_[p_row + 1][p_col] == monster_ &&
d == Direction::kDown) {
map_screens_[map_num].coordinates_[p_row + 1][p_col] = empty_tile_;
monsters_killed_++;
is_monster_attacked_ = true;
} else if (map_screens_[map_num].coordinates_[p_row][p_col - 1] == monster_ &&
d == Direction::kLeft) {
map_screens_[map_num].coordinates_[p_row][p_col - 1] = empty_tile_;
monsters_killed_++;
is_monster_attacked_ = true;
} else if (map_screens_[map_num].coordinates_[p_row][p_col + 1] == monster_ &&
d == Direction::kRight) {
map_screens_[map_num].coordinates_[p_row][p_col + 1] = empty_tile_;
monsters_killed_++;
is_monster_attacked_ = true;
} else if (map_screens_[map_num].coordinates_[p_row][p_col] == monster_) {
map_screens_[map_num].coordinates_[p_row][p_col] = empty_tile_;
monsters_killed_++;
is_monster_attacked_ = true;
}
}
is_player_attack_ = false;
return is_monster_attacked_;
}
int slow_monster_move = 0;
std::vector<Map> Monster::MoveMonster(Direction d, Location l, int map_num) {
slow_monster_move++;
is_monster_move_ = false;
if (IsMonstersAttacked(d, l, map_num)) {
goto exit_loops;
}
if (slow_monster_move % kRowTiles == 0) {
for (int i = 0; i < kColTiles; i++) {
for (int j = 0; j < kRowTiles; j++) {
if (map_screens_[map_num].coordinates_[i][j] == monster_) {
rand_direction = rand() % 4;
if (rand_direction == 0) {
if (map_screens_[map_num].coordinates_[i + 1][j] ==
empty_tile_) { // down
monster_direction_ = Direction::kDown;
map_screens_[map_num].coordinates_[i + 1][j] = monster_;
map_screens_[map_num].coordinates_[i][j] = empty_tile_;
is_monster_move_ = true;
}
} else if (rand_direction == 1) {
if (map_screens_[map_num].coordinates_[i - 1][j] ==
empty_tile_) { // up
monster_direction_ = Direction::kUp;
map_screens_[map_num].coordinates_[i - 1][j] = monster_;
map_screens_[map_num].coordinates_[i][j] = empty_tile_;
is_monster_move_ = true;
}
} else if (rand_direction == 2) {
if (map_screens_[map_num].coordinates_[i][j - 1] ==
empty_tile_) { // left
monster_direction_ = Direction::kLeft;
map_screens_[map_num].coordinates_[i][j - 1] = monster_;
map_screens_[map_num].coordinates_[i][j] = empty_tile_;
is_monster_move_ = true;
}
} else if (rand_direction == 3) {
if (map_screens_[map_num].coordinates_[i][j + 1] ==
empty_tile_) { // right
monster_direction_ = Direction::kRight;
map_screens_[map_num].coordinates_[i][j + 1] = monster_;
map_screens_[map_num].coordinates_[i][j] = empty_tile_;
is_monster_move_ = true;
}
}
}
}
}
}
exit_loops:;
is_monster_attacked_ = false;
return map_screens_;
}
bool Monster::IsMonsterAttackLink(Location location, int map_num) {
attack_delay_++;
int p_row = location.Col();
int p_col = location.Row();
if (attack_delay_ % kColTiles == 0) {
return map_screens_[map_num].coordinates_[p_row][p_col] == monster_;
}
}
bool Monster::IsMonsterMove() { return is_monster_move_; }
bool Monster::IsPlayerAttack() { return is_player_attack_; }
} // namespace zelda | 32.855072 | 82 | 0.619762 | [
"vector"
] |
a80faaed17dd77d6318c9df24230b56c9def160e | 6,550 | cpp | C++ | compiler/main.cpp | yuezuegu/sosa-compiler | 32384c221781f724cfc67c82ac3855d381eea22d | [
"MIT"
] | null | null | null | compiler/main.cpp | yuezuegu/sosa-compiler | 32384c221781f724cfc67c82ac3855d381eea22d | [
"MIT"
] | null | null | null | compiler/main.cpp | yuezuegu/sosa-compiler | 32384c221781f724cfc67c82ac3855d381eea22d | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <assert.h>
#include <map>
#include <tuple>
#include <string>
#include <list>
#include "compiler.hpp"
#include "array.hpp"
#include "interconnect.hpp"
#include "post_processor.hpp"
#include "logger_setup.hpp"
#include "dram.hpp"
#include <boost/log/trivial.hpp>
#include <boost/program_options.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
using namespace std;
namespace po = boost::program_options;
int main(int ac, char* av[]){
int no_array, no_rows, no_cols;
int bank_size;
float bandwidth;
int prefetch_limit;
InterconnectType interconnect_type;
boost::log::trivial::severity_level log_level;
string work_dir;
po::options_description desc("Allowed options");
desc.add_options()
("help", "show options")
("no_rows,r", po::value<int>(&no_rows)->default_value(32), "number of rows in a systolic array")
("no_cols,c", po::value<int>(&no_cols)->default_value(32), "number of columns in a systolic array")
("no_array,N", po::value<int>(&no_array)->default_value(128), "number of systolic arrays")
("memory_bw,M", po::value<float>(&bandwidth)->default_value(1200), "memory bandwidth in GB/s")
("prefetch,P", po::value<int>(&prefetch_limit)->default_value(100), "No of rounds allowed for prefetching")
("bank_size,S", po::value<int>(&bank_size)->default_value(524288), "SRAM bank size")
("ict_type,I", po::value<InterconnectType>(&interconnect_type)->default_value(InterconnectType::banyan_exp_1), "interconnect type (see enum members)")
//Possible options for ict_type: crossbar, benes_copy, benes_vanilla, banyan_exp_0, banyan_exp_1, banyan_exp_2, banyan_exp_3, banyan_exp_4
("work_dir,d", po::value<string>(&work_dir)->default_value("experiments/tmp"), "directory for input/output files")
("log_level,l", po::value<boost::log::trivial::severity_level>(&log_level)->default_value(boost::log::trivial::severity_level::error), "log level");
po::variables_map vm;
po::store(po::parse_command_line(ac, av, desc), vm);
po::notify(vm);
if (vm.count("help")) {
cout << desc << "\n";
return 1;
}
logger_setup(log_level);
std::cout << (unsigned) interconnect_type << "\n";
std::cout << "Running with: " <<
"no_array = " << no_array << " " <<
"no_rows = " << no_rows << " " <<
"no_cols = " << no_cols << " " <<
"memory bandwidth = " << bandwidth << " " <<
"bank size = " << bank_size << " " <<
"prefetch = " << prefetch_limit << " " <<
"interconnect_type = " << interconnect_type << " " <<
"\n";
// Load the precompiled model in the JSON format. Precompiler must be invoked first to generate this file.
json jin;
ifstream input_file;
string ifname = work_dir + "/precompiled_model.json";
input_file.open(ifname, ifstream::in);
if(!input_file.is_open()){
cout << "Input file " << ifname << " cannot be opened." << endl;
exit(1);
}
input_file >> jin;
input_file.close();
Arrays* arrays = new Arrays(no_array, no_rows, no_cols);
PostProcessors* post_processors = new PostProcessors(no_array);
Banks* banks = new Banks(no_array, bank_size);
Interconnects* interconnects = new Interconnects(no_array, interconnect_type);
//TODO: Make this parametric
float freq = 1e9;
//Convert GB/s to Bytes per cycle
bandwidth = bandwidth * ((1 << 30) / freq);
Dram* dram = new Dram(bandwidth, prefetch_limit);
Compiler* compiler = new Compiler(arrays, banks, interconnects, post_processors, dram);
#ifdef COMPILER_MULTITHREADING
// TODO enable passing the number of workers as a command-line argument argument
compiler->enable_multithreading(48);
#endif
// Run the compilation for each DNN model provided
Model* model = new Model();
for (json::iterator it = jin.begin(); it != jin.end(); ++it) {
string key = it.key();
if (!key.compare("args")) continue;
string model_name (key);
json j (jin[model_name]);
model = new Model(model_name, j);
compiler->compile(model);
compiler->duplicate_schedule(model, model->no_repeat);
}
cout << "Finished succesfully" << endl;
cout << "# of main rounds: " << compiler->no_main_rounds() << endl;
cout << "# of post rounds: " << compiler->no_post_rounds() << endl;
compiler->run_cycle_model();
cout << "Total no. of cycles: " << compiler->no_cycles << endl;
// Save results in the JSON format
ofstream output_file;
string ofname = work_dir + "/sim_results.json";
output_file.open(ofname, ofstream::out);
if(!output_file.is_open()){
cout << "Output file " << ofname << " cannot be opened." << endl;
exit(1);
}
json jout(jin["args"]);
jout["no_array"] = no_array;
jout["interconnect_type"] = interconnect_type; //TODO: Replace with string value
jout["bank_size"] = bank_size;
jout["bandwidth"] = bandwidth;
jout["no_cycles"] = compiler->no_cycles;
jout["no_main_rounds"] = compiler->no_main_rounds();
jout["no_post_rounds"] = compiler->no_post_rounds();
jout["interconnect_tdp"] = interconnects->tdp(no_cols);
//jout["no_ops"] = jin["no_ops"].get<long>();
jout["x_tiles_bw_usage"] = dram->x_tiles_bw_usage;
jout["w_tiles_bw_usage"] = dram->w_tiles_bw_usage;
jout["p_tiles_bw_usage"] = dram->p_tiles_bw_usage;
jout["total_bw_usage"] = dram->x_tiles_bw_usage + dram->w_tiles_bw_usage + dram->p_tiles_bw_usage;
jout["no_post_ops"] = post_processors->total_no_ops(); //INT operation (elementwise)
jout["no_ops"] = arrays->total_no_ops(); //INT operation (elementwise)
jout["total_sram_read_bytes"] = arrays->total_sram_read_bytes() + post_processors->total_sram_read_bytes(); //Bytes
jout["total_sram_write_bytes"] = arrays->total_sram_write_bytes() + post_processors->total_sram_write_bytes(); //Bytes
jout["memory_stall_cycles"] = compiler->memory_stall_cycles;
jout["no_layers"] = model->layer_list->size();
jout["total_no_gemm_ops"] = model->total_no_gemm_ops();
cout << "total_no_gemm_ops: " << model->total_no_gemm_ops() << endl;
cout << jout.dump() << endl;
output_file << jout.dump();
output_file.close();
delete arrays;
delete post_processors;
delete banks;
delete interconnects;
delete compiler;
return 0;
}
| 38.304094 | 158 | 0.655878 | [
"model"
] |
a81018551a9ff7dcc39eaf5f3895df1c2892a26f | 313 | hpp | C++ | include/domain/structure/structure_define.hpp | hyperpower/Nablla | 5a9be9f3b064a235572a1a2c9c5c2c19118697c5 | [
"MIT"
] | null | null | null | include/domain/structure/structure_define.hpp | hyperpower/Nablla | 5a9be9f3b064a235572a1a2c9c5c2c19118697c5 | [
"MIT"
] | null | null | null | include/domain/structure/structure_define.hpp | hyperpower/Nablla | 5a9be9f3b064a235572a1a2c9c5c2c19118697c5 | [
"MIT"
] | null | null | null | #ifndef _S_DEFINE_HPP
#define _S_DEFINE_HPP
#include "domain/domain_define.hpp"
#include "algebra/algebra.hpp"
#include "geometry/geometry.hpp"
#include <map>
#include <memory>
#include <iomanip>
#include <iostream>
#include <utility>
#include <unordered_map>
#include <cmath>
namespace carpio {
}
#endif | 13.041667 | 35 | 0.750799 | [
"geometry"
] |
a816e786eb3edabe4dcae78e01f43a2e1b18f6b0 | 8,440 | hpp | C++ | include/System/Reflection/RuntimeAssembly.hpp | sc2ad/BeatSaber-Quest-Codegen | ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab | [
"Unlicense"
] | 23 | 2020-08-07T04:09:00.000Z | 2022-03-31T22:10:29.000Z | include/System/Reflection/RuntimeAssembly.hpp | sc2ad/BeatSaber-Quest-Codegen | ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab | [
"Unlicense"
] | 6 | 2021-09-29T23:47:31.000Z | 2022-03-30T20:49:23.000Z | include/System/Reflection/RuntimeAssembly.hpp | sc2ad/BeatSaber-Quest-Codegen | ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab | [
"Unlicense"
] | 17 | 2020-08-20T19:36:52.000Z | 2022-03-30T18:28:24.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.Reflection.Assembly
#include "System/Reflection/Assembly.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Security::Policy
namespace System::Security::Policy {
// Forward declaring type: Evidence
class Evidence;
}
// Forward declaring namespace: System::Threading
namespace System::Threading {
// Forward declaring type: StackCrawlMark
struct StackCrawlMark;
}
// Forward declaring namespace: System::Reflection
namespace System::Reflection {
// Forward declaring type: AssemblyName
class AssemblyName;
}
// Forward declaring namespace: System::Runtime::Serialization
namespace System::Runtime::Serialization {
// Forward declaring type: SerializationInfo
class SerializationInfo;
// Forward declaring type: StreamingContext
struct StreamingContext;
}
// Completed forward declares
// Type namespace: System.Reflection
namespace System::Reflection {
// Forward declaring type: RuntimeAssembly
class RuntimeAssembly;
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(System::Reflection::RuntimeAssembly);
DEFINE_IL2CPP_ARG_TYPE(System::Reflection::RuntimeAssembly*, "System.Reflection", "RuntimeAssembly");
// Type namespace: System.Reflection
namespace System::Reflection {
// Size: 0x60
#pragma pack(push, 1)
// Autogenerated type: System.Reflection.RuntimeAssembly
// [TokenAttribute] Offset: FFFFFFFF
class RuntimeAssembly : public System::Reflection::Assembly {
public:
// static System.Reflection.RuntimeAssembly LoadWithPartialNameInternal(System.String partialName, System.Security.Policy.Evidence securityEvidence, ref System.Threading.StackCrawlMark stackMark)
// Offset: 0x1E982C4
static System::Reflection::RuntimeAssembly* LoadWithPartialNameInternal(::Il2CppString* partialName, System::Security::Policy::Evidence* securityEvidence, ByRef<System::Threading::StackCrawlMark> stackMark);
// static System.Reflection.RuntimeAssembly LoadWithPartialNameInternal(System.Reflection.AssemblyName an, System.Security.Policy.Evidence securityEvidence, ref System.Threading.StackCrawlMark stackMark)
// Offset: 0x1E9835C
static System::Reflection::RuntimeAssembly* LoadWithPartialNameInternal(System::Reflection::AssemblyName* an, System::Security::Policy::Evidence* securityEvidence, ByRef<System::Threading::StackCrawlMark> stackMark);
// protected System.Void .ctor()
// Offset: 0x1E92AA4
// Implemented from: System.Reflection.Assembly
// Base method: System.Void Assembly::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static RuntimeAssembly* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("System::Reflection::RuntimeAssembly::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<RuntimeAssembly*, creationType>()));
}
// public override System.Void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
// Offset: 0x1E98214
// Implemented from: System.Reflection.Assembly
// Base method: System.Void Assembly::GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
void GetObjectData(System::Runtime::Serialization::SerializationInfo* info, System::Runtime::Serialization::StreamingContext context);
// public override System.Reflection.AssemblyName GetName(System.Boolean copiedName)
// Offset: 0x1E98390
// Implemented from: System.Reflection.Assembly
// Base method: System.Reflection.AssemblyName Assembly::GetName(System.Boolean copiedName)
System::Reflection::AssemblyName* GetName(bool copiedName);
}; // System.Reflection.RuntimeAssembly
#pragma pack(pop)
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: System::Reflection::RuntimeAssembly::LoadWithPartialNameInternal
// Il2CppName: LoadWithPartialNameInternal
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::Reflection::RuntimeAssembly* (*)(::Il2CppString*, System::Security::Policy::Evidence*, ByRef<System::Threading::StackCrawlMark>)>(&System::Reflection::RuntimeAssembly::LoadWithPartialNameInternal)> {
static const MethodInfo* get() {
static auto* partialName = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* securityEvidence = &::il2cpp_utils::GetClassFromName("System.Security.Policy", "Evidence")->byval_arg;
static auto* stackMark = &::il2cpp_utils::GetClassFromName("System.Threading", "StackCrawlMark")->this_arg;
return ::il2cpp_utils::FindMethod(classof(System::Reflection::RuntimeAssembly*), "LoadWithPartialNameInternal", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{partialName, securityEvidence, stackMark});
}
};
// Writing MetadataGetter for method: System::Reflection::RuntimeAssembly::LoadWithPartialNameInternal
// Il2CppName: LoadWithPartialNameInternal
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::Reflection::RuntimeAssembly* (*)(System::Reflection::AssemblyName*, System::Security::Policy::Evidence*, ByRef<System::Threading::StackCrawlMark>)>(&System::Reflection::RuntimeAssembly::LoadWithPartialNameInternal)> {
static const MethodInfo* get() {
static auto* an = &::il2cpp_utils::GetClassFromName("System.Reflection", "AssemblyName")->byval_arg;
static auto* securityEvidence = &::il2cpp_utils::GetClassFromName("System.Security.Policy", "Evidence")->byval_arg;
static auto* stackMark = &::il2cpp_utils::GetClassFromName("System.Threading", "StackCrawlMark")->this_arg;
return ::il2cpp_utils::FindMethod(classof(System::Reflection::RuntimeAssembly*), "LoadWithPartialNameInternal", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{an, securityEvidence, stackMark});
}
};
// Writing MetadataGetter for method: System::Reflection::RuntimeAssembly::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: System::Reflection::RuntimeAssembly::GetObjectData
// Il2CppName: GetObjectData
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Reflection::RuntimeAssembly::*)(System::Runtime::Serialization::SerializationInfo*, System::Runtime::Serialization::StreamingContext)>(&System::Reflection::RuntimeAssembly::GetObjectData)> {
static const MethodInfo* get() {
static auto* info = &::il2cpp_utils::GetClassFromName("System.Runtime.Serialization", "SerializationInfo")->byval_arg;
static auto* context = &::il2cpp_utils::GetClassFromName("System.Runtime.Serialization", "StreamingContext")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Reflection::RuntimeAssembly*), "GetObjectData", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{info, context});
}
};
// Writing MetadataGetter for method: System::Reflection::RuntimeAssembly::GetName
// Il2CppName: GetName
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::Reflection::AssemblyName* (System::Reflection::RuntimeAssembly::*)(bool)>(&System::Reflection::RuntimeAssembly::GetName)> {
static const MethodInfo* get() {
static auto* copiedName = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Reflection::RuntimeAssembly*), "GetName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{copiedName});
}
};
| 64.923077 | 295 | 0.760782 | [
"object",
"vector"
] |
a818c92c0e5ae13b879b5acb7a439cc96e14d7c2 | 604,210 | cpp | C++ | cisco-ios-xe/ydk/models/cisco_ios_xe/fragmented/Cisco_IOS_XE_native_219.cpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 17 | 2016-12-02T05:45:49.000Z | 2022-02-10T19:32:54.000Z | cisco-ios-xe/ydk/models/cisco_ios_xe/fragmented/Cisco_IOS_XE_native_219.cpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2017-03-27T15:22:38.000Z | 2019-11-05T08:30:16.000Z | cisco-ios-xe/ydk/models/cisco_ios_xe/fragmented/Cisco_IOS_XE_native_219.cpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 11 | 2016-12-02T05:45:52.000Z | 2019-11-07T08:28:17.000Z |
#include <sstream>
#include <iostream>
#include <ydk/entity_util.hpp>
#include "bundle_info.hpp"
#include "generated_entity_lookup.hpp"
#include "Cisco_IOS_XE_native_219.hpp"
#include "Cisco_IOS_XE_native_220.hpp"
using namespace ydk;
namespace cisco_ios_xe {
namespace Cisco_IOS_XE_native {
Native::Router::Rip::Default::Timers::Timers()
:
basic{YType::empty, "basic"}
{
yang_name = "timers"; yang_parent_name = "default"; is_top_level_class = false; has_list_ancestor = false;
}
Native::Router::Rip::Default::Timers::~Timers()
{
}
bool Native::Router::Rip::Default::Timers::has_data() const
{
if (is_presence_container) return true;
return basic.is_set;
}
bool Native::Router::Rip::Default::Timers::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(basic.yfilter);
}
std::string Native::Router::Rip::Default::Timers::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/router/Cisco-IOS-XE-rip:rip/default/" << get_segment_path();
return path_buffer.str();
}
std::string Native::Router::Rip::Default::Timers::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "timers";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Router::Rip::Default::Timers::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (basic.is_set || is_set(basic.yfilter)) leaf_name_data.push_back(basic.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Router::Rip::Default::Timers::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Router::Rip::Default::Timers::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Router::Rip::Default::Timers::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "basic")
{
basic = value;
basic.value_namespace = name_space;
basic.value_namespace_prefix = name_space_prefix;
}
}
void Native::Router::Rip::Default::Timers::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "basic")
{
basic.yfilter = yfilter;
}
}
bool Native::Router::Rip::Default::Timers::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "basic")
return true;
return false;
}
Native::Router::Rip::Default::TrafficShare::TrafficShare()
:
min(std::make_shared<Native::Router::Rip::Default::TrafficShare::Min>())
{
min->parent = this;
yang_name = "traffic-share"; yang_parent_name = "default"; is_top_level_class = false; has_list_ancestor = false;
}
Native::Router::Rip::Default::TrafficShare::~TrafficShare()
{
}
bool Native::Router::Rip::Default::TrafficShare::has_data() const
{
if (is_presence_container) return true;
return (min != nullptr && min->has_data());
}
bool Native::Router::Rip::Default::TrafficShare::has_operation() const
{
return is_set(yfilter)
|| (min != nullptr && min->has_operation());
}
std::string Native::Router::Rip::Default::TrafficShare::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/router/Cisco-IOS-XE-rip:rip/default/" << get_segment_path();
return path_buffer.str();
}
std::string Native::Router::Rip::Default::TrafficShare::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "traffic-share";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Router::Rip::Default::TrafficShare::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Router::Rip::Default::TrafficShare::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "min")
{
if(min == nullptr)
{
min = std::make_shared<Native::Router::Rip::Default::TrafficShare::Min>();
}
return min;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Router::Rip::Default::TrafficShare::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(min != nullptr)
{
_children["min"] = min;
}
return _children;
}
void Native::Router::Rip::Default::TrafficShare::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::Router::Rip::Default::TrafficShare::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::Router::Rip::Default::TrafficShare::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "min")
return true;
return false;
}
Native::Router::Rip::Default::TrafficShare::Min::Min()
:
across_interfaces{YType::empty, "across-interfaces"}
{
yang_name = "min"; yang_parent_name = "traffic-share"; is_top_level_class = false; has_list_ancestor = false;
}
Native::Router::Rip::Default::TrafficShare::Min::~Min()
{
}
bool Native::Router::Rip::Default::TrafficShare::Min::has_data() const
{
if (is_presence_container) return true;
return across_interfaces.is_set;
}
bool Native::Router::Rip::Default::TrafficShare::Min::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(across_interfaces.yfilter);
}
std::string Native::Router::Rip::Default::TrafficShare::Min::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/router/Cisco-IOS-XE-rip:rip/default/traffic-share/" << get_segment_path();
return path_buffer.str();
}
std::string Native::Router::Rip::Default::TrafficShare::Min::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "min";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Router::Rip::Default::TrafficShare::Min::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (across_interfaces.is_set || is_set(across_interfaces.yfilter)) leaf_name_data.push_back(across_interfaces.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Router::Rip::Default::TrafficShare::Min::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Router::Rip::Default::TrafficShare::Min::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Router::Rip::Default::TrafficShare::Min::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "across-interfaces")
{
across_interfaces = value;
across_interfaces.value_namespace = name_space;
across_interfaces.value_namespace_prefix = name_space_prefix;
}
}
void Native::Router::Rip::Default::TrafficShare::Min::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "across-interfaces")
{
across_interfaces.yfilter = yfilter;
}
}
bool Native::Router::Rip::Default::TrafficShare::Min::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "across-interfaces")
return true;
return false;
}
Native::ServiceChain::ServiceChain()
:
service_function(this, {"name"})
, service_function_forwarder(std::make_shared<Native::ServiceChain::ServiceFunctionForwarder>())
, service_path(this, {"service_path_id"})
{
service_function_forwarder->parent = this;
yang_name = "service-chain"; yang_parent_name = "native"; is_top_level_class = false; has_list_ancestor = false;
}
Native::ServiceChain::~ServiceChain()
{
}
bool Native::ServiceChain::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<service_function.len(); index++)
{
if(service_function[index]->has_data())
return true;
}
for (std::size_t index=0; index<service_path.len(); index++)
{
if(service_path[index]->has_data())
return true;
}
return (service_function_forwarder != nullptr && service_function_forwarder->has_data());
}
bool Native::ServiceChain::has_operation() const
{
for (std::size_t index=0; index<service_function.len(); index++)
{
if(service_function[index]->has_operation())
return true;
}
for (std::size_t index=0; index<service_path.len(); index++)
{
if(service_path[index]->has_operation())
return true;
}
return is_set(yfilter)
|| (service_function_forwarder != nullptr && service_function_forwarder->has_operation());
}
std::string Native::ServiceChain::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/" << get_segment_path();
return path_buffer.str();
}
std::string Native::ServiceChain::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "service-chain";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::ServiceChain::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::ServiceChain::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "Cisco-IOS-XE-service-chain:service-function")
{
auto ent_ = std::make_shared<Native::ServiceChain::ServiceFunction>();
ent_->parent = this;
service_function.append(ent_);
return ent_;
}
if(child_yang_name == "Cisco-IOS-XE-service-chain:service-function-forwarder")
{
if(service_function_forwarder == nullptr)
{
service_function_forwarder = std::make_shared<Native::ServiceChain::ServiceFunctionForwarder>();
}
return service_function_forwarder;
}
if(child_yang_name == "Cisco-IOS-XE-service-chain:service-path")
{
auto ent_ = std::make_shared<Native::ServiceChain::ServicePath>();
ent_->parent = this;
service_path.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::ServiceChain::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : service_function.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
if(service_function_forwarder != nullptr)
{
_children["Cisco-IOS-XE-service-chain:service-function-forwarder"] = service_function_forwarder;
}
count_ = 0;
for (auto ent_ : service_path.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Native::ServiceChain::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::ServiceChain::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::ServiceChain::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "service-function" || name == "service-function-forwarder" || name == "service-path")
return true;
return false;
}
Native::ServiceChain::ServiceFunction::ServiceFunction()
:
name{YType::str, "name"}
,
config_service_chain_sf_mode(std::make_shared<Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode>())
{
config_service_chain_sf_mode->parent = this;
yang_name = "service-function"; yang_parent_name = "service-chain"; is_top_level_class = false; has_list_ancestor = false;
}
Native::ServiceChain::ServiceFunction::~ServiceFunction()
{
}
bool Native::ServiceChain::ServiceFunction::has_data() const
{
if (is_presence_container) return true;
return name.is_set
|| (config_service_chain_sf_mode != nullptr && config_service_chain_sf_mode->has_data());
}
bool Native::ServiceChain::ServiceFunction::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(name.yfilter)
|| (config_service_chain_sf_mode != nullptr && config_service_chain_sf_mode->has_operation());
}
std::string Native::ServiceChain::ServiceFunction::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/service-chain/" << get_segment_path();
return path_buffer.str();
}
std::string Native::ServiceChain::ServiceFunction::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-service-chain:service-function";
ADD_KEY_TOKEN(name, "name");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::ServiceChain::ServiceFunction::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (name.is_set || is_set(name.yfilter)) leaf_name_data.push_back(name.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::ServiceChain::ServiceFunction::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "config-service-chain-sf-mode")
{
if(config_service_chain_sf_mode == nullptr)
{
config_service_chain_sf_mode = std::make_shared<Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode>();
}
return config_service_chain_sf_mode;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::ServiceChain::ServiceFunction::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(config_service_chain_sf_mode != nullptr)
{
_children["config-service-chain-sf-mode"] = config_service_chain_sf_mode;
}
return _children;
}
void Native::ServiceChain::ServiceFunction::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "name")
{
name = value;
name.value_namespace = name_space;
name.value_namespace_prefix = name_space_prefix;
}
}
void Native::ServiceChain::ServiceFunction::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "name")
{
name.yfilter = yfilter;
}
}
bool Native::ServiceChain::ServiceFunction::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "config-service-chain-sf-mode" || name == "name")
return true;
return false;
}
Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::ConfigServiceChainSfMode()
:
description{YType::str, "description"}
,
encapsulation(std::make_shared<Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Encapsulation>())
, ip(std::make_shared<Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Ip>())
{
encapsulation->parent = this;
ip->parent = this;
yang_name = "config-service-chain-sf-mode"; yang_parent_name = "service-function"; is_top_level_class = false; has_list_ancestor = true;
}
Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::~ConfigServiceChainSfMode()
{
}
bool Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::has_data() const
{
if (is_presence_container) return true;
return description.is_set
|| (encapsulation != nullptr && encapsulation->has_data())
|| (ip != nullptr && ip->has_data());
}
bool Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(description.yfilter)
|| (encapsulation != nullptr && encapsulation->has_operation())
|| (ip != nullptr && ip->has_operation());
}
std::string Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "config-service-chain-sf-mode";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (description.is_set || is_set(description.yfilter)) leaf_name_data.push_back(description.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "encapsulation")
{
if(encapsulation == nullptr)
{
encapsulation = std::make_shared<Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Encapsulation>();
}
return encapsulation;
}
if(child_yang_name == "ip")
{
if(ip == nullptr)
{
ip = std::make_shared<Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Ip>();
}
return ip;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(encapsulation != nullptr)
{
_children["encapsulation"] = encapsulation;
}
if(ip != nullptr)
{
_children["ip"] = ip;
}
return _children;
}
void Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "description")
{
description = value;
description.value_namespace = name_space;
description.value_namespace_prefix = name_space_prefix;
}
}
void Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "description")
{
description.yfilter = yfilter;
}
}
bool Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "encapsulation" || name == "ip" || name == "description")
return true;
return false;
}
Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Encapsulation::Encapsulation()
:
none{YType::empty, "none"}
,
gre(nullptr) // presence node
{
yang_name = "encapsulation"; yang_parent_name = "config-service-chain-sf-mode"; is_top_level_class = false; has_list_ancestor = true;
}
Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Encapsulation::~Encapsulation()
{
}
bool Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Encapsulation::has_data() const
{
if (is_presence_container) return true;
return none.is_set
|| (gre != nullptr && gre->has_data());
}
bool Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Encapsulation::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(none.yfilter)
|| (gre != nullptr && gre->has_operation());
}
std::string Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Encapsulation::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "encapsulation";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Encapsulation::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (none.is_set || is_set(none.yfilter)) leaf_name_data.push_back(none.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Encapsulation::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "gre")
{
if(gre == nullptr)
{
gre = std::make_shared<Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Encapsulation::Gre>();
}
return gre;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Encapsulation::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(gre != nullptr)
{
_children["gre"] = gre;
}
return _children;
}
void Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Encapsulation::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "none")
{
none = value;
none.value_namespace = name_space;
none.value_namespace_prefix = name_space_prefix;
}
}
void Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Encapsulation::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "none")
{
none.yfilter = yfilter;
}
}
bool Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Encapsulation::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "gre" || name == "none")
return true;
return false;
}
Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Encapsulation::Gre::Gre()
:
enhanced{YType::enumeration, "enhanced"}
{
yang_name = "gre"; yang_parent_name = "encapsulation"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true;
}
Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Encapsulation::Gre::~Gre()
{
}
bool Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Encapsulation::Gre::has_data() const
{
if (is_presence_container) return true;
return enhanced.is_set;
}
bool Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Encapsulation::Gre::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(enhanced.yfilter);
}
std::string Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Encapsulation::Gre::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "gre";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Encapsulation::Gre::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (enhanced.is_set || is_set(enhanced.yfilter)) leaf_name_data.push_back(enhanced.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Encapsulation::Gre::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Encapsulation::Gre::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Encapsulation::Gre::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "enhanced")
{
enhanced = value;
enhanced.value_namespace = name_space;
enhanced.value_namespace_prefix = name_space_prefix;
}
}
void Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Encapsulation::Gre::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "enhanced")
{
enhanced.yfilter = yfilter;
}
}
bool Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Encapsulation::Gre::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "enhanced")
return true;
return false;
}
Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Ip::Ip()
:
address{YType::str, "address"}
{
yang_name = "ip"; yang_parent_name = "config-service-chain-sf-mode"; is_top_level_class = false; has_list_ancestor = true;
}
Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Ip::~Ip()
{
}
bool Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Ip::has_data() const
{
if (is_presence_container) return true;
return address.is_set;
}
bool Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Ip::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(address.yfilter);
}
std::string Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Ip::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "ip";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Ip::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (address.is_set || is_set(address.yfilter)) leaf_name_data.push_back(address.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Ip::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Ip::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Ip::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "address")
{
address = value;
address.value_namespace = name_space;
address.value_namespace_prefix = name_space_prefix;
}
}
void Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Ip::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "address")
{
address.yfilter = yfilter;
}
}
bool Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Ip::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "address")
return true;
return false;
}
Native::ServiceChain::ServiceFunctionForwarder::ServiceFunctionForwarder()
:
service_ff_name(this, {"name"})
, local(nullptr) // presence node
{
yang_name = "service-function-forwarder"; yang_parent_name = "service-chain"; is_top_level_class = false; has_list_ancestor = false;
}
Native::ServiceChain::ServiceFunctionForwarder::~ServiceFunctionForwarder()
{
}
bool Native::ServiceChain::ServiceFunctionForwarder::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<service_ff_name.len(); index++)
{
if(service_ff_name[index]->has_data())
return true;
}
return (local != nullptr && local->has_data());
}
bool Native::ServiceChain::ServiceFunctionForwarder::has_operation() const
{
for (std::size_t index=0; index<service_ff_name.len(); index++)
{
if(service_ff_name[index]->has_operation())
return true;
}
return is_set(yfilter)
|| (local != nullptr && local->has_operation());
}
std::string Native::ServiceChain::ServiceFunctionForwarder::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/service-chain/" << get_segment_path();
return path_buffer.str();
}
std::string Native::ServiceChain::ServiceFunctionForwarder::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-service-chain:service-function-forwarder";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::ServiceChain::ServiceFunctionForwarder::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::ServiceChain::ServiceFunctionForwarder::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "service-ff-name")
{
auto ent_ = std::make_shared<Native::ServiceChain::ServiceFunctionForwarder::ServiceFfName>();
ent_->parent = this;
service_ff_name.append(ent_);
return ent_;
}
if(child_yang_name == "local")
{
if(local == nullptr)
{
local = std::make_shared<Native::ServiceChain::ServiceFunctionForwarder::Local>();
}
return local;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::ServiceChain::ServiceFunctionForwarder::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : service_ff_name.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
if(local != nullptr)
{
_children["local"] = local;
}
return _children;
}
void Native::ServiceChain::ServiceFunctionForwarder::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::ServiceChain::ServiceFunctionForwarder::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::ServiceChain::ServiceFunctionForwarder::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "service-ff-name" || name == "local")
return true;
return false;
}
Native::ServiceChain::ServiceFunctionForwarder::ServiceFfName::ServiceFfName()
:
name{YType::str, "name"},
description{YType::str, "description"}
,
ip(std::make_shared<Native::ServiceChain::ServiceFunctionForwarder::ServiceFfName::Ip>())
{
ip->parent = this;
yang_name = "service-ff-name"; yang_parent_name = "service-function-forwarder"; is_top_level_class = false; has_list_ancestor = false;
}
Native::ServiceChain::ServiceFunctionForwarder::ServiceFfName::~ServiceFfName()
{
}
bool Native::ServiceChain::ServiceFunctionForwarder::ServiceFfName::has_data() const
{
if (is_presence_container) return true;
return name.is_set
|| description.is_set
|| (ip != nullptr && ip->has_data());
}
bool Native::ServiceChain::ServiceFunctionForwarder::ServiceFfName::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(name.yfilter)
|| ydk::is_set(description.yfilter)
|| (ip != nullptr && ip->has_operation());
}
std::string Native::ServiceChain::ServiceFunctionForwarder::ServiceFfName::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/service-chain/Cisco-IOS-XE-service-chain:service-function-forwarder/" << get_segment_path();
return path_buffer.str();
}
std::string Native::ServiceChain::ServiceFunctionForwarder::ServiceFfName::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "service-ff-name";
ADD_KEY_TOKEN(name, "name");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::ServiceChain::ServiceFunctionForwarder::ServiceFfName::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (name.is_set || is_set(name.yfilter)) leaf_name_data.push_back(name.get_name_leafdata());
if (description.is_set || is_set(description.yfilter)) leaf_name_data.push_back(description.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::ServiceChain::ServiceFunctionForwarder::ServiceFfName::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "ip")
{
if(ip == nullptr)
{
ip = std::make_shared<Native::ServiceChain::ServiceFunctionForwarder::ServiceFfName::Ip>();
}
return ip;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::ServiceChain::ServiceFunctionForwarder::ServiceFfName::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(ip != nullptr)
{
_children["ip"] = ip;
}
return _children;
}
void Native::ServiceChain::ServiceFunctionForwarder::ServiceFfName::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "name")
{
name = value;
name.value_namespace = name_space;
name.value_namespace_prefix = name_space_prefix;
}
if(value_path == "description")
{
description = value;
description.value_namespace = name_space;
description.value_namespace_prefix = name_space_prefix;
}
}
void Native::ServiceChain::ServiceFunctionForwarder::ServiceFfName::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "name")
{
name.yfilter = yfilter;
}
if(value_path == "description")
{
description.yfilter = yfilter;
}
}
bool Native::ServiceChain::ServiceFunctionForwarder::ServiceFfName::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "ip" || name == "name" || name == "description")
return true;
return false;
}
Native::ServiceChain::ServiceFunctionForwarder::ServiceFfName::Ip::Ip()
:
address{YType::str, "address"}
{
yang_name = "ip"; yang_parent_name = "service-ff-name"; is_top_level_class = false; has_list_ancestor = true;
}
Native::ServiceChain::ServiceFunctionForwarder::ServiceFfName::Ip::~Ip()
{
}
bool Native::ServiceChain::ServiceFunctionForwarder::ServiceFfName::Ip::has_data() const
{
if (is_presence_container) return true;
return address.is_set;
}
bool Native::ServiceChain::ServiceFunctionForwarder::ServiceFfName::Ip::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(address.yfilter);
}
std::string Native::ServiceChain::ServiceFunctionForwarder::ServiceFfName::Ip::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "ip";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::ServiceChain::ServiceFunctionForwarder::ServiceFfName::Ip::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (address.is_set || is_set(address.yfilter)) leaf_name_data.push_back(address.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::ServiceChain::ServiceFunctionForwarder::ServiceFfName::Ip::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::ServiceChain::ServiceFunctionForwarder::ServiceFfName::Ip::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::ServiceChain::ServiceFunctionForwarder::ServiceFfName::Ip::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "address")
{
address = value;
address.value_namespace = name_space;
address.value_namespace_prefix = name_space_prefix;
}
}
void Native::ServiceChain::ServiceFunctionForwarder::ServiceFfName::Ip::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "address")
{
address.yfilter = yfilter;
}
}
bool Native::ServiceChain::ServiceFunctionForwarder::ServiceFfName::Ip::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "address")
return true;
return false;
}
Native::ServiceChain::ServiceFunctionForwarder::Local::Local()
:
description{YType::str, "description"}
,
ip(std::make_shared<Native::ServiceChain::ServiceFunctionForwarder::Local::Ip>())
{
ip->parent = this;
yang_name = "local"; yang_parent_name = "service-function-forwarder"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true;
}
Native::ServiceChain::ServiceFunctionForwarder::Local::~Local()
{
}
bool Native::ServiceChain::ServiceFunctionForwarder::Local::has_data() const
{
if (is_presence_container) return true;
return description.is_set
|| (ip != nullptr && ip->has_data());
}
bool Native::ServiceChain::ServiceFunctionForwarder::Local::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(description.yfilter)
|| (ip != nullptr && ip->has_operation());
}
std::string Native::ServiceChain::ServiceFunctionForwarder::Local::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/service-chain/Cisco-IOS-XE-service-chain:service-function-forwarder/" << get_segment_path();
return path_buffer.str();
}
std::string Native::ServiceChain::ServiceFunctionForwarder::Local::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "local";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::ServiceChain::ServiceFunctionForwarder::Local::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (description.is_set || is_set(description.yfilter)) leaf_name_data.push_back(description.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::ServiceChain::ServiceFunctionForwarder::Local::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "ip")
{
if(ip == nullptr)
{
ip = std::make_shared<Native::ServiceChain::ServiceFunctionForwarder::Local::Ip>();
}
return ip;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::ServiceChain::ServiceFunctionForwarder::Local::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(ip != nullptr)
{
_children["ip"] = ip;
}
return _children;
}
void Native::ServiceChain::ServiceFunctionForwarder::Local::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "description")
{
description = value;
description.value_namespace = name_space;
description.value_namespace_prefix = name_space_prefix;
}
}
void Native::ServiceChain::ServiceFunctionForwarder::Local::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "description")
{
description.yfilter = yfilter;
}
}
bool Native::ServiceChain::ServiceFunctionForwarder::Local::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "ip" || name == "description")
return true;
return false;
}
Native::ServiceChain::ServiceFunctionForwarder::Local::Ip::Ip()
:
address{YType::str, "address"}
{
yang_name = "ip"; yang_parent_name = "local"; is_top_level_class = false; has_list_ancestor = false;
}
Native::ServiceChain::ServiceFunctionForwarder::Local::Ip::~Ip()
{
}
bool Native::ServiceChain::ServiceFunctionForwarder::Local::Ip::has_data() const
{
if (is_presence_container) return true;
return address.is_set;
}
bool Native::ServiceChain::ServiceFunctionForwarder::Local::Ip::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(address.yfilter);
}
std::string Native::ServiceChain::ServiceFunctionForwarder::Local::Ip::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/service-chain/Cisco-IOS-XE-service-chain:service-function-forwarder/local/" << get_segment_path();
return path_buffer.str();
}
std::string Native::ServiceChain::ServiceFunctionForwarder::Local::Ip::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "ip";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::ServiceChain::ServiceFunctionForwarder::Local::Ip::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (address.is_set || is_set(address.yfilter)) leaf_name_data.push_back(address.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::ServiceChain::ServiceFunctionForwarder::Local::Ip::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::ServiceChain::ServiceFunctionForwarder::Local::Ip::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::ServiceChain::ServiceFunctionForwarder::Local::Ip::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "address")
{
address = value;
address.value_namespace = name_space;
address.value_namespace_prefix = name_space_prefix;
}
}
void Native::ServiceChain::ServiceFunctionForwarder::Local::Ip::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "address")
{
address.yfilter = yfilter;
}
}
bool Native::ServiceChain::ServiceFunctionForwarder::Local::Ip::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "address")
return true;
return false;
}
Native::ServiceChain::ServicePath::ServicePath()
:
service_path_id{YType::uint32, "service-path-id"}
,
config_service_chain_path_mode(std::make_shared<Native::ServiceChain::ServicePath::ConfigServiceChainPathMode>())
{
config_service_chain_path_mode->parent = this;
yang_name = "service-path"; yang_parent_name = "service-chain"; is_top_level_class = false; has_list_ancestor = false;
}
Native::ServiceChain::ServicePath::~ServicePath()
{
}
bool Native::ServiceChain::ServicePath::has_data() const
{
if (is_presence_container) return true;
return service_path_id.is_set
|| (config_service_chain_path_mode != nullptr && config_service_chain_path_mode->has_data());
}
bool Native::ServiceChain::ServicePath::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(service_path_id.yfilter)
|| (config_service_chain_path_mode != nullptr && config_service_chain_path_mode->has_operation());
}
std::string Native::ServiceChain::ServicePath::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/service-chain/" << get_segment_path();
return path_buffer.str();
}
std::string Native::ServiceChain::ServicePath::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-service-chain:service-path";
ADD_KEY_TOKEN(service_path_id, "service-path-id");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::ServiceChain::ServicePath::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (service_path_id.is_set || is_set(service_path_id.yfilter)) leaf_name_data.push_back(service_path_id.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::ServiceChain::ServicePath::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "config-service-chain-path-mode")
{
if(config_service_chain_path_mode == nullptr)
{
config_service_chain_path_mode = std::make_shared<Native::ServiceChain::ServicePath::ConfigServiceChainPathMode>();
}
return config_service_chain_path_mode;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::ServiceChain::ServicePath::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(config_service_chain_path_mode != nullptr)
{
_children["config-service-chain-path-mode"] = config_service_chain_path_mode;
}
return _children;
}
void Native::ServiceChain::ServicePath::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "service-path-id")
{
service_path_id = value;
service_path_id.value_namespace = name_space;
service_path_id.value_namespace_prefix = name_space_prefix;
}
}
void Native::ServiceChain::ServicePath::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "service-path-id")
{
service_path_id.yfilter = yfilter;
}
}
bool Native::ServiceChain::ServicePath::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "config-service-chain-path-mode" || name == "service-path-id")
return true;
return false;
}
Native::ServiceChain::ServicePath::ConfigServiceChainPathMode::ConfigServiceChainPathMode()
:
description{YType::str, "description"}
,
service_index(std::make_shared<Native::ServiceChain::ServicePath::ConfigServiceChainPathMode::ServiceIndex>())
{
service_index->parent = this;
yang_name = "config-service-chain-path-mode"; yang_parent_name = "service-path"; is_top_level_class = false; has_list_ancestor = true;
}
Native::ServiceChain::ServicePath::ConfigServiceChainPathMode::~ConfigServiceChainPathMode()
{
}
bool Native::ServiceChain::ServicePath::ConfigServiceChainPathMode::has_data() const
{
if (is_presence_container) return true;
return description.is_set
|| (service_index != nullptr && service_index->has_data());
}
bool Native::ServiceChain::ServicePath::ConfigServiceChainPathMode::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(description.yfilter)
|| (service_index != nullptr && service_index->has_operation());
}
std::string Native::ServiceChain::ServicePath::ConfigServiceChainPathMode::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "config-service-chain-path-mode";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::ServiceChain::ServicePath::ConfigServiceChainPathMode::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (description.is_set || is_set(description.yfilter)) leaf_name_data.push_back(description.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::ServiceChain::ServicePath::ConfigServiceChainPathMode::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "service-index")
{
if(service_index == nullptr)
{
service_index = std::make_shared<Native::ServiceChain::ServicePath::ConfigServiceChainPathMode::ServiceIndex>();
}
return service_index;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::ServiceChain::ServicePath::ConfigServiceChainPathMode::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(service_index != nullptr)
{
_children["service-index"] = service_index;
}
return _children;
}
void Native::ServiceChain::ServicePath::ConfigServiceChainPathMode::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "description")
{
description = value;
description.value_namespace = name_space;
description.value_namespace_prefix = name_space_prefix;
}
}
void Native::ServiceChain::ServicePath::ConfigServiceChainPathMode::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "description")
{
description.yfilter = yfilter;
}
}
bool Native::ServiceChain::ServicePath::ConfigServiceChainPathMode::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "service-index" || name == "description")
return true;
return false;
}
Native::ServiceChain::ServicePath::ConfigServiceChainPathMode::ServiceIndex::ServiceIndex()
:
services(this, {"service_index_id"})
{
yang_name = "service-index"; yang_parent_name = "config-service-chain-path-mode"; is_top_level_class = false; has_list_ancestor = true;
}
Native::ServiceChain::ServicePath::ConfigServiceChainPathMode::ServiceIndex::~ServiceIndex()
{
}
bool Native::ServiceChain::ServicePath::ConfigServiceChainPathMode::ServiceIndex::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<services.len(); index++)
{
if(services[index]->has_data())
return true;
}
return false;
}
bool Native::ServiceChain::ServicePath::ConfigServiceChainPathMode::ServiceIndex::has_operation() const
{
for (std::size_t index=0; index<services.len(); index++)
{
if(services[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Native::ServiceChain::ServicePath::ConfigServiceChainPathMode::ServiceIndex::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "service-index";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::ServiceChain::ServicePath::ConfigServiceChainPathMode::ServiceIndex::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::ServiceChain::ServicePath::ConfigServiceChainPathMode::ServiceIndex::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "services")
{
auto ent_ = std::make_shared<Native::ServiceChain::ServicePath::ConfigServiceChainPathMode::ServiceIndex::Services>();
ent_->parent = this;
services.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::ServiceChain::ServicePath::ConfigServiceChainPathMode::ServiceIndex::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : services.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Native::ServiceChain::ServicePath::ConfigServiceChainPathMode::ServiceIndex::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::ServiceChain::ServicePath::ConfigServiceChainPathMode::ServiceIndex::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::ServiceChain::ServicePath::ConfigServiceChainPathMode::ServiceIndex::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "services")
return true;
return false;
}
Native::ServiceChain::ServicePath::ConfigServiceChainPathMode::ServiceIndex::Services::Services()
:
service_index_id{YType::uint8, "service-index-id"},
service_function{YType::str, "service-function"},
service_function_forwarder{YType::str, "service-function-forwarder"},
terminate{YType::empty, "terminate"}
{
yang_name = "services"; yang_parent_name = "service-index"; is_top_level_class = false; has_list_ancestor = true;
}
Native::ServiceChain::ServicePath::ConfigServiceChainPathMode::ServiceIndex::Services::~Services()
{
}
bool Native::ServiceChain::ServicePath::ConfigServiceChainPathMode::ServiceIndex::Services::has_data() const
{
if (is_presence_container) return true;
return service_index_id.is_set
|| service_function.is_set
|| service_function_forwarder.is_set
|| terminate.is_set;
}
bool Native::ServiceChain::ServicePath::ConfigServiceChainPathMode::ServiceIndex::Services::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(service_index_id.yfilter)
|| ydk::is_set(service_function.yfilter)
|| ydk::is_set(service_function_forwarder.yfilter)
|| ydk::is_set(terminate.yfilter);
}
std::string Native::ServiceChain::ServicePath::ConfigServiceChainPathMode::ServiceIndex::Services::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "services";
ADD_KEY_TOKEN(service_index_id, "service-index-id");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::ServiceChain::ServicePath::ConfigServiceChainPathMode::ServiceIndex::Services::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (service_index_id.is_set || is_set(service_index_id.yfilter)) leaf_name_data.push_back(service_index_id.get_name_leafdata());
if (service_function.is_set || is_set(service_function.yfilter)) leaf_name_data.push_back(service_function.get_name_leafdata());
if (service_function_forwarder.is_set || is_set(service_function_forwarder.yfilter)) leaf_name_data.push_back(service_function_forwarder.get_name_leafdata());
if (terminate.is_set || is_set(terminate.yfilter)) leaf_name_data.push_back(terminate.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::ServiceChain::ServicePath::ConfigServiceChainPathMode::ServiceIndex::Services::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::ServiceChain::ServicePath::ConfigServiceChainPathMode::ServiceIndex::Services::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::ServiceChain::ServicePath::ConfigServiceChainPathMode::ServiceIndex::Services::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "service-index-id")
{
service_index_id = value;
service_index_id.value_namespace = name_space;
service_index_id.value_namespace_prefix = name_space_prefix;
}
if(value_path == "service-function")
{
service_function = value;
service_function.value_namespace = name_space;
service_function.value_namespace_prefix = name_space_prefix;
}
if(value_path == "service-function-forwarder")
{
service_function_forwarder = value;
service_function_forwarder.value_namespace = name_space;
service_function_forwarder.value_namespace_prefix = name_space_prefix;
}
if(value_path == "terminate")
{
terminate = value;
terminate.value_namespace = name_space;
terminate.value_namespace_prefix = name_space_prefix;
}
}
void Native::ServiceChain::ServicePath::ConfigServiceChainPathMode::ServiceIndex::Services::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "service-index-id")
{
service_index_id.yfilter = yfilter;
}
if(value_path == "service-function")
{
service_function.yfilter = yfilter;
}
if(value_path == "service-function-forwarder")
{
service_function_forwarder.yfilter = yfilter;
}
if(value_path == "terminate")
{
terminate.yfilter = yfilter;
}
}
bool Native::ServiceChain::ServicePath::ConfigServiceChainPathMode::ServiceIndex::Services::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "service-index-id" || name == "service-function" || name == "service-function-forwarder" || name == "terminate")
return true;
return false;
}
Native::Performance::Performance()
:
monitor(std::make_shared<Native::Performance::Monitor>())
{
monitor->parent = this;
yang_name = "performance"; yang_parent_name = "native"; is_top_level_class = false; has_list_ancestor = false;
}
Native::Performance::~Performance()
{
}
bool Native::Performance::has_data() const
{
if (is_presence_container) return true;
return (monitor != nullptr && monitor->has_data());
}
bool Native::Performance::has_operation() const
{
return is_set(yfilter)
|| (monitor != nullptr && monitor->has_operation());
}
std::string Native::Performance::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/" << get_segment_path();
return path_buffer.str();
}
std::string Native::Performance::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "performance";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Performance::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Performance::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "Cisco-IOS-XE-ezpm:monitor")
{
if(monitor == nullptr)
{
monitor = std::make_shared<Native::Performance::Monitor>();
}
return monitor;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Performance::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(monitor != nullptr)
{
_children["Cisco-IOS-XE-ezpm:monitor"] = monitor;
}
return _children;
}
void Native::Performance::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::Performance::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::Performance::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "monitor")
return true;
return false;
}
Native::Performance::Monitor::Monitor()
:
context(this, {"name"})
, observation_point(std::make_shared<Native::Performance::Monitor::ObservationPoint>())
{
observation_point->parent = this;
yang_name = "monitor"; yang_parent_name = "performance"; is_top_level_class = false; has_list_ancestor = false;
}
Native::Performance::Monitor::~Monitor()
{
}
bool Native::Performance::Monitor::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<context.len(); index++)
{
if(context[index]->has_data())
return true;
}
return (observation_point != nullptr && observation_point->has_data());
}
bool Native::Performance::Monitor::has_operation() const
{
for (std::size_t index=0; index<context.len(); index++)
{
if(context[index]->has_operation())
return true;
}
return is_set(yfilter)
|| (observation_point != nullptr && observation_point->has_operation());
}
std::string Native::Performance::Monitor::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/performance/" << get_segment_path();
return path_buffer.str();
}
std::string Native::Performance::Monitor::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-ezpm:monitor";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Performance::Monitor::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Performance::Monitor::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "context")
{
auto ent_ = std::make_shared<Native::Performance::Monitor::Context>();
ent_->parent = this;
context.append(ent_);
return ent_;
}
if(child_yang_name == "observation-point")
{
if(observation_point == nullptr)
{
observation_point = std::make_shared<Native::Performance::Monitor::ObservationPoint>();
}
return observation_point;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Performance::Monitor::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : context.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
if(observation_point != nullptr)
{
_children["observation-point"] = observation_point;
}
return _children;
}
void Native::Performance::Monitor::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::Performance::Monitor::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::Performance::Monitor::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "context" || name == "observation-point")
return true;
return false;
}
Native::Performance::Monitor::Context::Context()
:
name{YType::str, "name"},
profile{YType::enumeration, "profile"},
description{YType::str, "description"}
,
default_(std::make_shared<Native::Performance::Monitor::Context::Default>())
, exporter(std::make_shared<Native::Performance::Monitor::Context::Exporter>())
, traffic_monitor(std::make_shared<Native::Performance::Monitor::Context::TrafficMonitor>())
{
default_->parent = this;
exporter->parent = this;
traffic_monitor->parent = this;
yang_name = "context"; yang_parent_name = "monitor"; is_top_level_class = false; has_list_ancestor = false;
}
Native::Performance::Monitor::Context::~Context()
{
}
bool Native::Performance::Monitor::Context::has_data() const
{
if (is_presence_container) return true;
return name.is_set
|| profile.is_set
|| description.is_set
|| (default_ != nullptr && default_->has_data())
|| (exporter != nullptr && exporter->has_data())
|| (traffic_monitor != nullptr && traffic_monitor->has_data());
}
bool Native::Performance::Monitor::Context::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(name.yfilter)
|| ydk::is_set(profile.yfilter)
|| ydk::is_set(description.yfilter)
|| (default_ != nullptr && default_->has_operation())
|| (exporter != nullptr && exporter->has_operation())
|| (traffic_monitor != nullptr && traffic_monitor->has_operation());
}
std::string Native::Performance::Monitor::Context::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/performance/Cisco-IOS-XE-ezpm:monitor/" << get_segment_path();
return path_buffer.str();
}
std::string Native::Performance::Monitor::Context::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "context";
ADD_KEY_TOKEN(name, "name");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Performance::Monitor::Context::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (name.is_set || is_set(name.yfilter)) leaf_name_data.push_back(name.get_name_leafdata());
if (profile.is_set || is_set(profile.yfilter)) leaf_name_data.push_back(profile.get_name_leafdata());
if (description.is_set || is_set(description.yfilter)) leaf_name_data.push_back(description.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Performance::Monitor::Context::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "default")
{
if(default_ == nullptr)
{
default_ = std::make_shared<Native::Performance::Monitor::Context::Default>();
}
return default_;
}
if(child_yang_name == "exporter")
{
if(exporter == nullptr)
{
exporter = std::make_shared<Native::Performance::Monitor::Context::Exporter>();
}
return exporter;
}
if(child_yang_name == "traffic-monitor")
{
if(traffic_monitor == nullptr)
{
traffic_monitor = std::make_shared<Native::Performance::Monitor::Context::TrafficMonitor>();
}
return traffic_monitor;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Performance::Monitor::Context::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(default_ != nullptr)
{
_children["default"] = default_;
}
if(exporter != nullptr)
{
_children["exporter"] = exporter;
}
if(traffic_monitor != nullptr)
{
_children["traffic-monitor"] = traffic_monitor;
}
return _children;
}
void Native::Performance::Monitor::Context::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "name")
{
name = value;
name.value_namespace = name_space;
name.value_namespace_prefix = name_space_prefix;
}
if(value_path == "profile")
{
profile = value;
profile.value_namespace = name_space;
profile.value_namespace_prefix = name_space_prefix;
}
if(value_path == "description")
{
description = value;
description.value_namespace = name_space;
description.value_namespace_prefix = name_space_prefix;
}
}
void Native::Performance::Monitor::Context::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "name")
{
name.yfilter = yfilter;
}
if(value_path == "profile")
{
profile.yfilter = yfilter;
}
if(value_path == "description")
{
description.yfilter = yfilter;
}
}
bool Native::Performance::Monitor::Context::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "default" || name == "exporter" || name == "traffic-monitor" || name == "name" || name == "profile" || name == "description")
return true;
return false;
}
Native::Performance::Monitor::Context::Default::Default()
:
description{YType::empty, "description"}
,
exporter(std::make_shared<Native::Performance::Monitor::Context::Default::Exporter>())
, traffic_monitor(std::make_shared<Native::Performance::Monitor::Context::Default::TrafficMonitor>())
{
exporter->parent = this;
traffic_monitor->parent = this;
yang_name = "default"; yang_parent_name = "context"; is_top_level_class = false; has_list_ancestor = true;
}
Native::Performance::Monitor::Context::Default::~Default()
{
}
bool Native::Performance::Monitor::Context::Default::has_data() const
{
if (is_presence_container) return true;
return description.is_set
|| (exporter != nullptr && exporter->has_data())
|| (traffic_monitor != nullptr && traffic_monitor->has_data());
}
bool Native::Performance::Monitor::Context::Default::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(description.yfilter)
|| (exporter != nullptr && exporter->has_operation())
|| (traffic_monitor != nullptr && traffic_monitor->has_operation());
}
std::string Native::Performance::Monitor::Context::Default::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "default";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Performance::Monitor::Context::Default::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (description.is_set || is_set(description.yfilter)) leaf_name_data.push_back(description.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Performance::Monitor::Context::Default::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "exporter")
{
if(exporter == nullptr)
{
exporter = std::make_shared<Native::Performance::Monitor::Context::Default::Exporter>();
}
return exporter;
}
if(child_yang_name == "traffic-monitor")
{
if(traffic_monitor == nullptr)
{
traffic_monitor = std::make_shared<Native::Performance::Monitor::Context::Default::TrafficMonitor>();
}
return traffic_monitor;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Performance::Monitor::Context::Default::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(exporter != nullptr)
{
_children["exporter"] = exporter;
}
if(traffic_monitor != nullptr)
{
_children["traffic-monitor"] = traffic_monitor;
}
return _children;
}
void Native::Performance::Monitor::Context::Default::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "description")
{
description = value;
description.value_namespace = name_space;
description.value_namespace_prefix = name_space_prefix;
}
}
void Native::Performance::Monitor::Context::Default::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "description")
{
description.yfilter = yfilter;
}
}
bool Native::Performance::Monitor::Context::Default::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "exporter" || name == "traffic-monitor" || name == "description")
return true;
return false;
}
Native::Performance::Monitor::Context::Default::Exporter::Exporter()
:
destination{YType::str, "destination"},
source{YType::str, "source"},
port{YType::uint16, "port"},
transport{YType::enumeration, "transport"},
vrf{YType::str, "vrf"}
{
yang_name = "exporter"; yang_parent_name = "default"; is_top_level_class = false; has_list_ancestor = true;
}
Native::Performance::Monitor::Context::Default::Exporter::~Exporter()
{
}
bool Native::Performance::Monitor::Context::Default::Exporter::has_data() const
{
if (is_presence_container) return true;
return destination.is_set
|| source.is_set
|| port.is_set
|| transport.is_set
|| vrf.is_set;
}
bool Native::Performance::Monitor::Context::Default::Exporter::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(destination.yfilter)
|| ydk::is_set(source.yfilter)
|| ydk::is_set(port.yfilter)
|| ydk::is_set(transport.yfilter)
|| ydk::is_set(vrf.yfilter);
}
std::string Native::Performance::Monitor::Context::Default::Exporter::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "exporter";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Performance::Monitor::Context::Default::Exporter::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (destination.is_set || is_set(destination.yfilter)) leaf_name_data.push_back(destination.get_name_leafdata());
if (source.is_set || is_set(source.yfilter)) leaf_name_data.push_back(source.get_name_leafdata());
if (port.is_set || is_set(port.yfilter)) leaf_name_data.push_back(port.get_name_leafdata());
if (transport.is_set || is_set(transport.yfilter)) leaf_name_data.push_back(transport.get_name_leafdata());
if (vrf.is_set || is_set(vrf.yfilter)) leaf_name_data.push_back(vrf.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Performance::Monitor::Context::Default::Exporter::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Performance::Monitor::Context::Default::Exporter::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Performance::Monitor::Context::Default::Exporter::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "destination")
{
destination = value;
destination.value_namespace = name_space;
destination.value_namespace_prefix = name_space_prefix;
}
if(value_path == "source")
{
source = value;
source.value_namespace = name_space;
source.value_namespace_prefix = name_space_prefix;
}
if(value_path == "port")
{
port = value;
port.value_namespace = name_space;
port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "transport")
{
transport = value;
transport.value_namespace = name_space;
transport.value_namespace_prefix = name_space_prefix;
}
if(value_path == "vrf")
{
vrf = value;
vrf.value_namespace = name_space;
vrf.value_namespace_prefix = name_space_prefix;
}
}
void Native::Performance::Monitor::Context::Default::Exporter::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "destination")
{
destination.yfilter = yfilter;
}
if(value_path == "source")
{
source.yfilter = yfilter;
}
if(value_path == "port")
{
port.yfilter = yfilter;
}
if(value_path == "transport")
{
transport.yfilter = yfilter;
}
if(value_path == "vrf")
{
vrf.yfilter = yfilter;
}
}
bool Native::Performance::Monitor::Context::Default::Exporter::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "destination" || name == "source" || name == "port" || name == "transport" || name == "vrf")
return true;
return false;
}
Native::Performance::Monitor::Context::Default::TrafficMonitor::TrafficMonitor()
:
all(nullptr) // presence node
, application_response_time(nullptr) // presence node
, application_traffic_stats(nullptr) // presence node
, conversation_traffic_stats(nullptr) // presence node
, media(nullptr) // presence node
, url(nullptr) // presence node
, application_client_server_stats(nullptr) // presence node
, application_stats(nullptr) // presence node
{
yang_name = "traffic-monitor"; yang_parent_name = "default"; is_top_level_class = false; has_list_ancestor = true;
}
Native::Performance::Monitor::Context::Default::TrafficMonitor::~TrafficMonitor()
{
}
bool Native::Performance::Monitor::Context::Default::TrafficMonitor::has_data() const
{
if (is_presence_container) return true;
return (all != nullptr && all->has_data())
|| (application_response_time != nullptr && application_response_time->has_data())
|| (application_traffic_stats != nullptr && application_traffic_stats->has_data())
|| (conversation_traffic_stats != nullptr && conversation_traffic_stats->has_data())
|| (media != nullptr && media->has_data())
|| (url != nullptr && url->has_data())
|| (application_client_server_stats != nullptr && application_client_server_stats->has_data())
|| (application_stats != nullptr && application_stats->has_data());
}
bool Native::Performance::Monitor::Context::Default::TrafficMonitor::has_operation() const
{
return is_set(yfilter)
|| (all != nullptr && all->has_operation())
|| (application_response_time != nullptr && application_response_time->has_operation())
|| (application_traffic_stats != nullptr && application_traffic_stats->has_operation())
|| (conversation_traffic_stats != nullptr && conversation_traffic_stats->has_operation())
|| (media != nullptr && media->has_operation())
|| (url != nullptr && url->has_operation())
|| (application_client_server_stats != nullptr && application_client_server_stats->has_operation())
|| (application_stats != nullptr && application_stats->has_operation());
}
std::string Native::Performance::Monitor::Context::Default::TrafficMonitor::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "traffic-monitor";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Performance::Monitor::Context::Default::TrafficMonitor::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Performance::Monitor::Context::Default::TrafficMonitor::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "all")
{
if(all == nullptr)
{
all = std::make_shared<Native::Performance::Monitor::Context::Default::TrafficMonitor::All>();
}
return all;
}
if(child_yang_name == "application-response-time")
{
if(application_response_time == nullptr)
{
application_response_time = std::make_shared<Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationResponseTime>();
}
return application_response_time;
}
if(child_yang_name == "application-traffic-stats")
{
if(application_traffic_stats == nullptr)
{
application_traffic_stats = std::make_shared<Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationTrafficStats>();
}
return application_traffic_stats;
}
if(child_yang_name == "conversation-traffic-stats")
{
if(conversation_traffic_stats == nullptr)
{
conversation_traffic_stats = std::make_shared<Native::Performance::Monitor::Context::Default::TrafficMonitor::ConversationTrafficStats>();
}
return conversation_traffic_stats;
}
if(child_yang_name == "media")
{
if(media == nullptr)
{
media = std::make_shared<Native::Performance::Monitor::Context::Default::TrafficMonitor::Media>();
}
return media;
}
if(child_yang_name == "url")
{
if(url == nullptr)
{
url = std::make_shared<Native::Performance::Monitor::Context::Default::TrafficMonitor::Url>();
}
return url;
}
if(child_yang_name == "application-client-server-stats")
{
if(application_client_server_stats == nullptr)
{
application_client_server_stats = std::make_shared<Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationClientServerStats>();
}
return application_client_server_stats;
}
if(child_yang_name == "application-stats")
{
if(application_stats == nullptr)
{
application_stats = std::make_shared<Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationStats>();
}
return application_stats;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Performance::Monitor::Context::Default::TrafficMonitor::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(all != nullptr)
{
_children["all"] = all;
}
if(application_response_time != nullptr)
{
_children["application-response-time"] = application_response_time;
}
if(application_traffic_stats != nullptr)
{
_children["application-traffic-stats"] = application_traffic_stats;
}
if(conversation_traffic_stats != nullptr)
{
_children["conversation-traffic-stats"] = conversation_traffic_stats;
}
if(media != nullptr)
{
_children["media"] = media;
}
if(url != nullptr)
{
_children["url"] = url;
}
if(application_client_server_stats != nullptr)
{
_children["application-client-server-stats"] = application_client_server_stats;
}
if(application_stats != nullptr)
{
_children["application-stats"] = application_stats;
}
return _children;
}
void Native::Performance::Monitor::Context::Default::TrafficMonitor::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::Performance::Monitor::Context::Default::TrafficMonitor::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::Performance::Monitor::Context::Default::TrafficMonitor::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "all" || name == "application-response-time" || name == "application-traffic-stats" || name == "conversation-traffic-stats" || name == "media" || name == "url" || name == "application-client-server-stats" || name == "application-stats")
return true;
return false;
}
Native::Performance::Monitor::Context::Default::TrafficMonitor::All::All()
:
ipv4{YType::empty, "ipv4"},
ipv6{YType::empty, "ipv6"}
{
yang_name = "all"; yang_parent_name = "traffic-monitor"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true;
}
Native::Performance::Monitor::Context::Default::TrafficMonitor::All::~All()
{
}
bool Native::Performance::Monitor::Context::Default::TrafficMonitor::All::has_data() const
{
if (is_presence_container) return true;
return ipv4.is_set
|| ipv6.is_set;
}
bool Native::Performance::Monitor::Context::Default::TrafficMonitor::All::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(ipv4.yfilter)
|| ydk::is_set(ipv6.yfilter);
}
std::string Native::Performance::Monitor::Context::Default::TrafficMonitor::All::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "all";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Performance::Monitor::Context::Default::TrafficMonitor::All::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (ipv4.is_set || is_set(ipv4.yfilter)) leaf_name_data.push_back(ipv4.get_name_leafdata());
if (ipv6.is_set || is_set(ipv6.yfilter)) leaf_name_data.push_back(ipv6.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Performance::Monitor::Context::Default::TrafficMonitor::All::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Performance::Monitor::Context::Default::TrafficMonitor::All::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Performance::Monitor::Context::Default::TrafficMonitor::All::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "ipv4")
{
ipv4 = value;
ipv4.value_namespace = name_space;
ipv4.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ipv6")
{
ipv6 = value;
ipv6.value_namespace = name_space;
ipv6.value_namespace_prefix = name_space_prefix;
}
}
void Native::Performance::Monitor::Context::Default::TrafficMonitor::All::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "ipv4")
{
ipv4.yfilter = yfilter;
}
if(value_path == "ipv6")
{
ipv6.yfilter = yfilter;
}
}
bool Native::Performance::Monitor::Context::Default::TrafficMonitor::All::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "ipv4" || name == "ipv6")
return true;
return false;
}
Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationResponseTime::ApplicationResponseTime()
:
cache_size{YType::uint32, "cache-size"},
class_replace{YType::str, "class-replace"},
interval_timeout{YType::uint32, "interval-timeout"},
cache_type{YType::enumeration, "cache-type"},
class_and{YType::str, "class-and"},
ipv4{YType::empty, "ipv4"},
ipv6{YType::empty, "ipv6"}
{
yang_name = "application-response-time"; yang_parent_name = "traffic-monitor"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true;
}
Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationResponseTime::~ApplicationResponseTime()
{
}
bool Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationResponseTime::has_data() const
{
if (is_presence_container) return true;
return cache_size.is_set
|| class_replace.is_set
|| interval_timeout.is_set
|| cache_type.is_set
|| class_and.is_set
|| ipv4.is_set
|| ipv6.is_set;
}
bool Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationResponseTime::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(cache_size.yfilter)
|| ydk::is_set(class_replace.yfilter)
|| ydk::is_set(interval_timeout.yfilter)
|| ydk::is_set(cache_type.yfilter)
|| ydk::is_set(class_and.yfilter)
|| ydk::is_set(ipv4.yfilter)
|| ydk::is_set(ipv6.yfilter);
}
std::string Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationResponseTime::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "application-response-time";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationResponseTime::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (cache_size.is_set || is_set(cache_size.yfilter)) leaf_name_data.push_back(cache_size.get_name_leafdata());
if (class_replace.is_set || is_set(class_replace.yfilter)) leaf_name_data.push_back(class_replace.get_name_leafdata());
if (interval_timeout.is_set || is_set(interval_timeout.yfilter)) leaf_name_data.push_back(interval_timeout.get_name_leafdata());
if (cache_type.is_set || is_set(cache_type.yfilter)) leaf_name_data.push_back(cache_type.get_name_leafdata());
if (class_and.is_set || is_set(class_and.yfilter)) leaf_name_data.push_back(class_and.get_name_leafdata());
if (ipv4.is_set || is_set(ipv4.yfilter)) leaf_name_data.push_back(ipv4.get_name_leafdata());
if (ipv6.is_set || is_set(ipv6.yfilter)) leaf_name_data.push_back(ipv6.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationResponseTime::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationResponseTime::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationResponseTime::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "cache-size")
{
cache_size = value;
cache_size.value_namespace = name_space;
cache_size.value_namespace_prefix = name_space_prefix;
}
if(value_path == "class-replace")
{
class_replace = value;
class_replace.value_namespace = name_space;
class_replace.value_namespace_prefix = name_space_prefix;
}
if(value_path == "interval-timeout")
{
interval_timeout = value;
interval_timeout.value_namespace = name_space;
interval_timeout.value_namespace_prefix = name_space_prefix;
}
if(value_path == "cache-type")
{
cache_type = value;
cache_type.value_namespace = name_space;
cache_type.value_namespace_prefix = name_space_prefix;
}
if(value_path == "class-and")
{
class_and = value;
class_and.value_namespace = name_space;
class_and.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ipv4")
{
ipv4 = value;
ipv4.value_namespace = name_space;
ipv4.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ipv6")
{
ipv6 = value;
ipv6.value_namespace = name_space;
ipv6.value_namespace_prefix = name_space_prefix;
}
}
void Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationResponseTime::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "cache-size")
{
cache_size.yfilter = yfilter;
}
if(value_path == "class-replace")
{
class_replace.yfilter = yfilter;
}
if(value_path == "interval-timeout")
{
interval_timeout.yfilter = yfilter;
}
if(value_path == "cache-type")
{
cache_type.yfilter = yfilter;
}
if(value_path == "class-and")
{
class_and.yfilter = yfilter;
}
if(value_path == "ipv4")
{
ipv4.yfilter = yfilter;
}
if(value_path == "ipv6")
{
ipv6.yfilter = yfilter;
}
}
bool Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationResponseTime::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "cache-size" || name == "class-replace" || name == "interval-timeout" || name == "cache-type" || name == "class-and" || name == "ipv4" || name == "ipv6")
return true;
return false;
}
Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationTrafficStats::ApplicationTrafficStats()
:
cache_size{YType::uint32, "cache-size"},
class_replace{YType::str, "class-replace"},
interval_timeout{YType::uint32, "interval-timeout"}
{
yang_name = "application-traffic-stats"; yang_parent_name = "traffic-monitor"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true;
}
Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationTrafficStats::~ApplicationTrafficStats()
{
}
bool Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationTrafficStats::has_data() const
{
if (is_presence_container) return true;
return cache_size.is_set
|| class_replace.is_set
|| interval_timeout.is_set;
}
bool Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationTrafficStats::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(cache_size.yfilter)
|| ydk::is_set(class_replace.yfilter)
|| ydk::is_set(interval_timeout.yfilter);
}
std::string Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationTrafficStats::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "application-traffic-stats";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationTrafficStats::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (cache_size.is_set || is_set(cache_size.yfilter)) leaf_name_data.push_back(cache_size.get_name_leafdata());
if (class_replace.is_set || is_set(class_replace.yfilter)) leaf_name_data.push_back(class_replace.get_name_leafdata());
if (interval_timeout.is_set || is_set(interval_timeout.yfilter)) leaf_name_data.push_back(interval_timeout.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationTrafficStats::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationTrafficStats::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationTrafficStats::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "cache-size")
{
cache_size = value;
cache_size.value_namespace = name_space;
cache_size.value_namespace_prefix = name_space_prefix;
}
if(value_path == "class-replace")
{
class_replace = value;
class_replace.value_namespace = name_space;
class_replace.value_namespace_prefix = name_space_prefix;
}
if(value_path == "interval-timeout")
{
interval_timeout = value;
interval_timeout.value_namespace = name_space;
interval_timeout.value_namespace_prefix = name_space_prefix;
}
}
void Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationTrafficStats::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "cache-size")
{
cache_size.yfilter = yfilter;
}
if(value_path == "class-replace")
{
class_replace.yfilter = yfilter;
}
if(value_path == "interval-timeout")
{
interval_timeout.yfilter = yfilter;
}
}
bool Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationTrafficStats::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "cache-size" || name == "class-replace" || name == "interval-timeout")
return true;
return false;
}
Native::Performance::Monitor::Context::Default::TrafficMonitor::ConversationTrafficStats::ConversationTrafficStats()
:
cache_size{YType::uint32, "cache-size"},
class_replace{YType::str, "class-replace"},
interval_timeout{YType::uint32, "interval-timeout"},
cache_type{YType::enumeration, "cache-type"},
ipv4{YType::empty, "ipv4"},
ipv6{YType::empty, "ipv6"}
{
yang_name = "conversation-traffic-stats"; yang_parent_name = "traffic-monitor"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true;
}
Native::Performance::Monitor::Context::Default::TrafficMonitor::ConversationTrafficStats::~ConversationTrafficStats()
{
}
bool Native::Performance::Monitor::Context::Default::TrafficMonitor::ConversationTrafficStats::has_data() const
{
if (is_presence_container) return true;
return cache_size.is_set
|| class_replace.is_set
|| interval_timeout.is_set
|| cache_type.is_set
|| ipv4.is_set
|| ipv6.is_set;
}
bool Native::Performance::Monitor::Context::Default::TrafficMonitor::ConversationTrafficStats::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(cache_size.yfilter)
|| ydk::is_set(class_replace.yfilter)
|| ydk::is_set(interval_timeout.yfilter)
|| ydk::is_set(cache_type.yfilter)
|| ydk::is_set(ipv4.yfilter)
|| ydk::is_set(ipv6.yfilter);
}
std::string Native::Performance::Monitor::Context::Default::TrafficMonitor::ConversationTrafficStats::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "conversation-traffic-stats";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Performance::Monitor::Context::Default::TrafficMonitor::ConversationTrafficStats::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (cache_size.is_set || is_set(cache_size.yfilter)) leaf_name_data.push_back(cache_size.get_name_leafdata());
if (class_replace.is_set || is_set(class_replace.yfilter)) leaf_name_data.push_back(class_replace.get_name_leafdata());
if (interval_timeout.is_set || is_set(interval_timeout.yfilter)) leaf_name_data.push_back(interval_timeout.get_name_leafdata());
if (cache_type.is_set || is_set(cache_type.yfilter)) leaf_name_data.push_back(cache_type.get_name_leafdata());
if (ipv4.is_set || is_set(ipv4.yfilter)) leaf_name_data.push_back(ipv4.get_name_leafdata());
if (ipv6.is_set || is_set(ipv6.yfilter)) leaf_name_data.push_back(ipv6.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Performance::Monitor::Context::Default::TrafficMonitor::ConversationTrafficStats::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Performance::Monitor::Context::Default::TrafficMonitor::ConversationTrafficStats::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Performance::Monitor::Context::Default::TrafficMonitor::ConversationTrafficStats::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "cache-size")
{
cache_size = value;
cache_size.value_namespace = name_space;
cache_size.value_namespace_prefix = name_space_prefix;
}
if(value_path == "class-replace")
{
class_replace = value;
class_replace.value_namespace = name_space;
class_replace.value_namespace_prefix = name_space_prefix;
}
if(value_path == "interval-timeout")
{
interval_timeout = value;
interval_timeout.value_namespace = name_space;
interval_timeout.value_namespace_prefix = name_space_prefix;
}
if(value_path == "cache-type")
{
cache_type = value;
cache_type.value_namespace = name_space;
cache_type.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ipv4")
{
ipv4 = value;
ipv4.value_namespace = name_space;
ipv4.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ipv6")
{
ipv6 = value;
ipv6.value_namespace = name_space;
ipv6.value_namespace_prefix = name_space_prefix;
}
}
void Native::Performance::Monitor::Context::Default::TrafficMonitor::ConversationTrafficStats::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "cache-size")
{
cache_size.yfilter = yfilter;
}
if(value_path == "class-replace")
{
class_replace.yfilter = yfilter;
}
if(value_path == "interval-timeout")
{
interval_timeout.yfilter = yfilter;
}
if(value_path == "cache-type")
{
cache_type.yfilter = yfilter;
}
if(value_path == "ipv4")
{
ipv4.yfilter = yfilter;
}
if(value_path == "ipv6")
{
ipv6.yfilter = yfilter;
}
}
bool Native::Performance::Monitor::Context::Default::TrafficMonitor::ConversationTrafficStats::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "cache-size" || name == "class-replace" || name == "interval-timeout" || name == "cache-type" || name == "ipv4" || name == "ipv6")
return true;
return false;
}
Native::Performance::Monitor::Context::Default::TrafficMonitor::Media::Media()
:
cache_size{YType::uint32, "cache-size"},
class_replace{YType::str, "class-replace"},
interval_timeout{YType::uint32, "interval-timeout"},
class_and{YType::str, "class-and"},
egress{YType::empty, "egress"},
ingress{YType::empty, "ingress"},
ipv4{YType::empty, "ipv4"},
ipv6{YType::empty, "ipv6"}
{
yang_name = "media"; yang_parent_name = "traffic-monitor"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true;
}
Native::Performance::Monitor::Context::Default::TrafficMonitor::Media::~Media()
{
}
bool Native::Performance::Monitor::Context::Default::TrafficMonitor::Media::has_data() const
{
if (is_presence_container) return true;
return cache_size.is_set
|| class_replace.is_set
|| interval_timeout.is_set
|| class_and.is_set
|| egress.is_set
|| ingress.is_set
|| ipv4.is_set
|| ipv6.is_set;
}
bool Native::Performance::Monitor::Context::Default::TrafficMonitor::Media::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(cache_size.yfilter)
|| ydk::is_set(class_replace.yfilter)
|| ydk::is_set(interval_timeout.yfilter)
|| ydk::is_set(class_and.yfilter)
|| ydk::is_set(egress.yfilter)
|| ydk::is_set(ingress.yfilter)
|| ydk::is_set(ipv4.yfilter)
|| ydk::is_set(ipv6.yfilter);
}
std::string Native::Performance::Monitor::Context::Default::TrafficMonitor::Media::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "media";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Performance::Monitor::Context::Default::TrafficMonitor::Media::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (cache_size.is_set || is_set(cache_size.yfilter)) leaf_name_data.push_back(cache_size.get_name_leafdata());
if (class_replace.is_set || is_set(class_replace.yfilter)) leaf_name_data.push_back(class_replace.get_name_leafdata());
if (interval_timeout.is_set || is_set(interval_timeout.yfilter)) leaf_name_data.push_back(interval_timeout.get_name_leafdata());
if (class_and.is_set || is_set(class_and.yfilter)) leaf_name_data.push_back(class_and.get_name_leafdata());
if (egress.is_set || is_set(egress.yfilter)) leaf_name_data.push_back(egress.get_name_leafdata());
if (ingress.is_set || is_set(ingress.yfilter)) leaf_name_data.push_back(ingress.get_name_leafdata());
if (ipv4.is_set || is_set(ipv4.yfilter)) leaf_name_data.push_back(ipv4.get_name_leafdata());
if (ipv6.is_set || is_set(ipv6.yfilter)) leaf_name_data.push_back(ipv6.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Performance::Monitor::Context::Default::TrafficMonitor::Media::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Performance::Monitor::Context::Default::TrafficMonitor::Media::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Performance::Monitor::Context::Default::TrafficMonitor::Media::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "cache-size")
{
cache_size = value;
cache_size.value_namespace = name_space;
cache_size.value_namespace_prefix = name_space_prefix;
}
if(value_path == "class-replace")
{
class_replace = value;
class_replace.value_namespace = name_space;
class_replace.value_namespace_prefix = name_space_prefix;
}
if(value_path == "interval-timeout")
{
interval_timeout = value;
interval_timeout.value_namespace = name_space;
interval_timeout.value_namespace_prefix = name_space_prefix;
}
if(value_path == "class-and")
{
class_and = value;
class_and.value_namespace = name_space;
class_and.value_namespace_prefix = name_space_prefix;
}
if(value_path == "egress")
{
egress = value;
egress.value_namespace = name_space;
egress.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ingress")
{
ingress = value;
ingress.value_namespace = name_space;
ingress.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ipv4")
{
ipv4 = value;
ipv4.value_namespace = name_space;
ipv4.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ipv6")
{
ipv6 = value;
ipv6.value_namespace = name_space;
ipv6.value_namespace_prefix = name_space_prefix;
}
}
void Native::Performance::Monitor::Context::Default::TrafficMonitor::Media::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "cache-size")
{
cache_size.yfilter = yfilter;
}
if(value_path == "class-replace")
{
class_replace.yfilter = yfilter;
}
if(value_path == "interval-timeout")
{
interval_timeout.yfilter = yfilter;
}
if(value_path == "class-and")
{
class_and.yfilter = yfilter;
}
if(value_path == "egress")
{
egress.yfilter = yfilter;
}
if(value_path == "ingress")
{
ingress.yfilter = yfilter;
}
if(value_path == "ipv4")
{
ipv4.yfilter = yfilter;
}
if(value_path == "ipv6")
{
ipv6.yfilter = yfilter;
}
}
bool Native::Performance::Monitor::Context::Default::TrafficMonitor::Media::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "cache-size" || name == "class-replace" || name == "interval-timeout" || name == "class-and" || name == "egress" || name == "ingress" || name == "ipv4" || name == "ipv6")
return true;
return false;
}
Native::Performance::Monitor::Context::Default::TrafficMonitor::Url::Url()
:
cache_size{YType::uint32, "cache-size"},
class_and{YType::str, "class-and"},
class_replace{YType::str, "class-replace"},
ipv4{YType::empty, "ipv4"},
ipv6{YType::empty, "ipv6"},
sampling_rate{YType::uint32, "sampling-rate"}
{
yang_name = "url"; yang_parent_name = "traffic-monitor"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true;
}
Native::Performance::Monitor::Context::Default::TrafficMonitor::Url::~Url()
{
}
bool Native::Performance::Monitor::Context::Default::TrafficMonitor::Url::has_data() const
{
if (is_presence_container) return true;
return cache_size.is_set
|| class_and.is_set
|| class_replace.is_set
|| ipv4.is_set
|| ipv6.is_set
|| sampling_rate.is_set;
}
bool Native::Performance::Monitor::Context::Default::TrafficMonitor::Url::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(cache_size.yfilter)
|| ydk::is_set(class_and.yfilter)
|| ydk::is_set(class_replace.yfilter)
|| ydk::is_set(ipv4.yfilter)
|| ydk::is_set(ipv6.yfilter)
|| ydk::is_set(sampling_rate.yfilter);
}
std::string Native::Performance::Monitor::Context::Default::TrafficMonitor::Url::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "url";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Performance::Monitor::Context::Default::TrafficMonitor::Url::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (cache_size.is_set || is_set(cache_size.yfilter)) leaf_name_data.push_back(cache_size.get_name_leafdata());
if (class_and.is_set || is_set(class_and.yfilter)) leaf_name_data.push_back(class_and.get_name_leafdata());
if (class_replace.is_set || is_set(class_replace.yfilter)) leaf_name_data.push_back(class_replace.get_name_leafdata());
if (ipv4.is_set || is_set(ipv4.yfilter)) leaf_name_data.push_back(ipv4.get_name_leafdata());
if (ipv6.is_set || is_set(ipv6.yfilter)) leaf_name_data.push_back(ipv6.get_name_leafdata());
if (sampling_rate.is_set || is_set(sampling_rate.yfilter)) leaf_name_data.push_back(sampling_rate.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Performance::Monitor::Context::Default::TrafficMonitor::Url::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Performance::Monitor::Context::Default::TrafficMonitor::Url::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Performance::Monitor::Context::Default::TrafficMonitor::Url::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "cache-size")
{
cache_size = value;
cache_size.value_namespace = name_space;
cache_size.value_namespace_prefix = name_space_prefix;
}
if(value_path == "class-and")
{
class_and = value;
class_and.value_namespace = name_space;
class_and.value_namespace_prefix = name_space_prefix;
}
if(value_path == "class-replace")
{
class_replace = value;
class_replace.value_namespace = name_space;
class_replace.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ipv4")
{
ipv4 = value;
ipv4.value_namespace = name_space;
ipv4.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ipv6")
{
ipv6 = value;
ipv6.value_namespace = name_space;
ipv6.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sampling-rate")
{
sampling_rate = value;
sampling_rate.value_namespace = name_space;
sampling_rate.value_namespace_prefix = name_space_prefix;
}
}
void Native::Performance::Monitor::Context::Default::TrafficMonitor::Url::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "cache-size")
{
cache_size.yfilter = yfilter;
}
if(value_path == "class-and")
{
class_and.yfilter = yfilter;
}
if(value_path == "class-replace")
{
class_replace.yfilter = yfilter;
}
if(value_path == "ipv4")
{
ipv4.yfilter = yfilter;
}
if(value_path == "ipv6")
{
ipv6.yfilter = yfilter;
}
if(value_path == "sampling-rate")
{
sampling_rate.yfilter = yfilter;
}
}
bool Native::Performance::Monitor::Context::Default::TrafficMonitor::Url::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "cache-size" || name == "class-and" || name == "class-replace" || name == "ipv4" || name == "ipv6" || name == "sampling-rate")
return true;
return false;
}
Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationClientServerStats::ApplicationClientServerStats()
:
cache_size{YType::uint32, "cache-size"},
class_replace{YType::str, "class-replace"},
interval_timeout{YType::uint32, "interval-timeout"},
cache_type{YType::enumeration, "cache-type"},
ipv4{YType::empty, "ipv4"},
ipv6{YType::empty, "ipv6"}
{
yang_name = "application-client-server-stats"; yang_parent_name = "traffic-monitor"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true;
}
Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationClientServerStats::~ApplicationClientServerStats()
{
}
bool Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationClientServerStats::has_data() const
{
if (is_presence_container) return true;
return cache_size.is_set
|| class_replace.is_set
|| interval_timeout.is_set
|| cache_type.is_set
|| ipv4.is_set
|| ipv6.is_set;
}
bool Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationClientServerStats::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(cache_size.yfilter)
|| ydk::is_set(class_replace.yfilter)
|| ydk::is_set(interval_timeout.yfilter)
|| ydk::is_set(cache_type.yfilter)
|| ydk::is_set(ipv4.yfilter)
|| ydk::is_set(ipv6.yfilter);
}
std::string Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationClientServerStats::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "application-client-server-stats";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationClientServerStats::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (cache_size.is_set || is_set(cache_size.yfilter)) leaf_name_data.push_back(cache_size.get_name_leafdata());
if (class_replace.is_set || is_set(class_replace.yfilter)) leaf_name_data.push_back(class_replace.get_name_leafdata());
if (interval_timeout.is_set || is_set(interval_timeout.yfilter)) leaf_name_data.push_back(interval_timeout.get_name_leafdata());
if (cache_type.is_set || is_set(cache_type.yfilter)) leaf_name_data.push_back(cache_type.get_name_leafdata());
if (ipv4.is_set || is_set(ipv4.yfilter)) leaf_name_data.push_back(ipv4.get_name_leafdata());
if (ipv6.is_set || is_set(ipv6.yfilter)) leaf_name_data.push_back(ipv6.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationClientServerStats::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationClientServerStats::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationClientServerStats::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "cache-size")
{
cache_size = value;
cache_size.value_namespace = name_space;
cache_size.value_namespace_prefix = name_space_prefix;
}
if(value_path == "class-replace")
{
class_replace = value;
class_replace.value_namespace = name_space;
class_replace.value_namespace_prefix = name_space_prefix;
}
if(value_path == "interval-timeout")
{
interval_timeout = value;
interval_timeout.value_namespace = name_space;
interval_timeout.value_namespace_prefix = name_space_prefix;
}
if(value_path == "cache-type")
{
cache_type = value;
cache_type.value_namespace = name_space;
cache_type.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ipv4")
{
ipv4 = value;
ipv4.value_namespace = name_space;
ipv4.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ipv6")
{
ipv6 = value;
ipv6.value_namespace = name_space;
ipv6.value_namespace_prefix = name_space_prefix;
}
}
void Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationClientServerStats::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "cache-size")
{
cache_size.yfilter = yfilter;
}
if(value_path == "class-replace")
{
class_replace.yfilter = yfilter;
}
if(value_path == "interval-timeout")
{
interval_timeout.yfilter = yfilter;
}
if(value_path == "cache-type")
{
cache_type.yfilter = yfilter;
}
if(value_path == "ipv4")
{
ipv4.yfilter = yfilter;
}
if(value_path == "ipv6")
{
ipv6.yfilter = yfilter;
}
}
bool Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationClientServerStats::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "cache-size" || name == "class-replace" || name == "interval-timeout" || name == "cache-type" || name == "ipv4" || name == "ipv6")
return true;
return false;
}
Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationStats::ApplicationStats()
:
cache_size{YType::uint32, "cache-size"},
class_replace{YType::str, "class-replace"},
interval_timeout{YType::uint32, "interval-timeout"}
{
yang_name = "application-stats"; yang_parent_name = "traffic-monitor"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true;
}
Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationStats::~ApplicationStats()
{
}
bool Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationStats::has_data() const
{
if (is_presence_container) return true;
return cache_size.is_set
|| class_replace.is_set
|| interval_timeout.is_set;
}
bool Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationStats::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(cache_size.yfilter)
|| ydk::is_set(class_replace.yfilter)
|| ydk::is_set(interval_timeout.yfilter);
}
std::string Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationStats::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "application-stats";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationStats::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (cache_size.is_set || is_set(cache_size.yfilter)) leaf_name_data.push_back(cache_size.get_name_leafdata());
if (class_replace.is_set || is_set(class_replace.yfilter)) leaf_name_data.push_back(class_replace.get_name_leafdata());
if (interval_timeout.is_set || is_set(interval_timeout.yfilter)) leaf_name_data.push_back(interval_timeout.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationStats::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationStats::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationStats::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "cache-size")
{
cache_size = value;
cache_size.value_namespace = name_space;
cache_size.value_namespace_prefix = name_space_prefix;
}
if(value_path == "class-replace")
{
class_replace = value;
class_replace.value_namespace = name_space;
class_replace.value_namespace_prefix = name_space_prefix;
}
if(value_path == "interval-timeout")
{
interval_timeout = value;
interval_timeout.value_namespace = name_space;
interval_timeout.value_namespace_prefix = name_space_prefix;
}
}
void Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationStats::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "cache-size")
{
cache_size.yfilter = yfilter;
}
if(value_path == "class-replace")
{
class_replace.yfilter = yfilter;
}
if(value_path == "interval-timeout")
{
interval_timeout.yfilter = yfilter;
}
}
bool Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationStats::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "cache-size" || name == "class-replace" || name == "interval-timeout")
return true;
return false;
}
Native::Performance::Monitor::Context::Exporter::Exporter()
:
destination{YType::str, "destination"},
source{YType::str, "source"},
port{YType::uint16, "port"},
transport{YType::enumeration, "transport"},
vrf{YType::str, "vrf"}
{
yang_name = "exporter"; yang_parent_name = "context"; is_top_level_class = false; has_list_ancestor = true;
}
Native::Performance::Monitor::Context::Exporter::~Exporter()
{
}
bool Native::Performance::Monitor::Context::Exporter::has_data() const
{
if (is_presence_container) return true;
return destination.is_set
|| source.is_set
|| port.is_set
|| transport.is_set
|| vrf.is_set;
}
bool Native::Performance::Monitor::Context::Exporter::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(destination.yfilter)
|| ydk::is_set(source.yfilter)
|| ydk::is_set(port.yfilter)
|| ydk::is_set(transport.yfilter)
|| ydk::is_set(vrf.yfilter);
}
std::string Native::Performance::Monitor::Context::Exporter::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "exporter";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Performance::Monitor::Context::Exporter::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (destination.is_set || is_set(destination.yfilter)) leaf_name_data.push_back(destination.get_name_leafdata());
if (source.is_set || is_set(source.yfilter)) leaf_name_data.push_back(source.get_name_leafdata());
if (port.is_set || is_set(port.yfilter)) leaf_name_data.push_back(port.get_name_leafdata());
if (transport.is_set || is_set(transport.yfilter)) leaf_name_data.push_back(transport.get_name_leafdata());
if (vrf.is_set || is_set(vrf.yfilter)) leaf_name_data.push_back(vrf.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Performance::Monitor::Context::Exporter::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Performance::Monitor::Context::Exporter::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Performance::Monitor::Context::Exporter::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "destination")
{
destination = value;
destination.value_namespace = name_space;
destination.value_namespace_prefix = name_space_prefix;
}
if(value_path == "source")
{
source = value;
source.value_namespace = name_space;
source.value_namespace_prefix = name_space_prefix;
}
if(value_path == "port")
{
port = value;
port.value_namespace = name_space;
port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "transport")
{
transport = value;
transport.value_namespace = name_space;
transport.value_namespace_prefix = name_space_prefix;
}
if(value_path == "vrf")
{
vrf = value;
vrf.value_namespace = name_space;
vrf.value_namespace_prefix = name_space_prefix;
}
}
void Native::Performance::Monitor::Context::Exporter::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "destination")
{
destination.yfilter = yfilter;
}
if(value_path == "source")
{
source.yfilter = yfilter;
}
if(value_path == "port")
{
port.yfilter = yfilter;
}
if(value_path == "transport")
{
transport.yfilter = yfilter;
}
if(value_path == "vrf")
{
vrf.yfilter = yfilter;
}
}
bool Native::Performance::Monitor::Context::Exporter::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "destination" || name == "source" || name == "port" || name == "transport" || name == "vrf")
return true;
return false;
}
Native::Performance::Monitor::Context::TrafficMonitor::TrafficMonitor()
:
all(nullptr) // presence node
, application_response_time(nullptr) // presence node
, application_traffic_stats(nullptr) // presence node
, conversation_traffic_stats(nullptr) // presence node
, media(nullptr) // presence node
, url(nullptr) // presence node
, application_client_server_stats(nullptr) // presence node
, application_stats(nullptr) // presence node
{
yang_name = "traffic-monitor"; yang_parent_name = "context"; is_top_level_class = false; has_list_ancestor = true;
}
Native::Performance::Monitor::Context::TrafficMonitor::~TrafficMonitor()
{
}
bool Native::Performance::Monitor::Context::TrafficMonitor::has_data() const
{
if (is_presence_container) return true;
return (all != nullptr && all->has_data())
|| (application_response_time != nullptr && application_response_time->has_data())
|| (application_traffic_stats != nullptr && application_traffic_stats->has_data())
|| (conversation_traffic_stats != nullptr && conversation_traffic_stats->has_data())
|| (media != nullptr && media->has_data())
|| (url != nullptr && url->has_data())
|| (application_client_server_stats != nullptr && application_client_server_stats->has_data())
|| (application_stats != nullptr && application_stats->has_data());
}
bool Native::Performance::Monitor::Context::TrafficMonitor::has_operation() const
{
return is_set(yfilter)
|| (all != nullptr && all->has_operation())
|| (application_response_time != nullptr && application_response_time->has_operation())
|| (application_traffic_stats != nullptr && application_traffic_stats->has_operation())
|| (conversation_traffic_stats != nullptr && conversation_traffic_stats->has_operation())
|| (media != nullptr && media->has_operation())
|| (url != nullptr && url->has_operation())
|| (application_client_server_stats != nullptr && application_client_server_stats->has_operation())
|| (application_stats != nullptr && application_stats->has_operation());
}
std::string Native::Performance::Monitor::Context::TrafficMonitor::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "traffic-monitor";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Performance::Monitor::Context::TrafficMonitor::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Performance::Monitor::Context::TrafficMonitor::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "all")
{
if(all == nullptr)
{
all = std::make_shared<Native::Performance::Monitor::Context::TrafficMonitor::All>();
}
return all;
}
if(child_yang_name == "application-response-time")
{
if(application_response_time == nullptr)
{
application_response_time = std::make_shared<Native::Performance::Monitor::Context::TrafficMonitor::ApplicationResponseTime>();
}
return application_response_time;
}
if(child_yang_name == "application-traffic-stats")
{
if(application_traffic_stats == nullptr)
{
application_traffic_stats = std::make_shared<Native::Performance::Monitor::Context::TrafficMonitor::ApplicationTrafficStats>();
}
return application_traffic_stats;
}
if(child_yang_name == "conversation-traffic-stats")
{
if(conversation_traffic_stats == nullptr)
{
conversation_traffic_stats = std::make_shared<Native::Performance::Monitor::Context::TrafficMonitor::ConversationTrafficStats>();
}
return conversation_traffic_stats;
}
if(child_yang_name == "media")
{
if(media == nullptr)
{
media = std::make_shared<Native::Performance::Monitor::Context::TrafficMonitor::Media>();
}
return media;
}
if(child_yang_name == "url")
{
if(url == nullptr)
{
url = std::make_shared<Native::Performance::Monitor::Context::TrafficMonitor::Url>();
}
return url;
}
if(child_yang_name == "application-client-server-stats")
{
if(application_client_server_stats == nullptr)
{
application_client_server_stats = std::make_shared<Native::Performance::Monitor::Context::TrafficMonitor::ApplicationClientServerStats>();
}
return application_client_server_stats;
}
if(child_yang_name == "application-stats")
{
if(application_stats == nullptr)
{
application_stats = std::make_shared<Native::Performance::Monitor::Context::TrafficMonitor::ApplicationStats>();
}
return application_stats;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Performance::Monitor::Context::TrafficMonitor::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(all != nullptr)
{
_children["all"] = all;
}
if(application_response_time != nullptr)
{
_children["application-response-time"] = application_response_time;
}
if(application_traffic_stats != nullptr)
{
_children["application-traffic-stats"] = application_traffic_stats;
}
if(conversation_traffic_stats != nullptr)
{
_children["conversation-traffic-stats"] = conversation_traffic_stats;
}
if(media != nullptr)
{
_children["media"] = media;
}
if(url != nullptr)
{
_children["url"] = url;
}
if(application_client_server_stats != nullptr)
{
_children["application-client-server-stats"] = application_client_server_stats;
}
if(application_stats != nullptr)
{
_children["application-stats"] = application_stats;
}
return _children;
}
void Native::Performance::Monitor::Context::TrafficMonitor::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::Performance::Monitor::Context::TrafficMonitor::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::Performance::Monitor::Context::TrafficMonitor::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "all" || name == "application-response-time" || name == "application-traffic-stats" || name == "conversation-traffic-stats" || name == "media" || name == "url" || name == "application-client-server-stats" || name == "application-stats")
return true;
return false;
}
Native::Performance::Monitor::Context::TrafficMonitor::All::All()
:
ipv4{YType::empty, "ipv4"},
ipv6{YType::empty, "ipv6"}
{
yang_name = "all"; yang_parent_name = "traffic-monitor"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true;
}
Native::Performance::Monitor::Context::TrafficMonitor::All::~All()
{
}
bool Native::Performance::Monitor::Context::TrafficMonitor::All::has_data() const
{
if (is_presence_container) return true;
return ipv4.is_set
|| ipv6.is_set;
}
bool Native::Performance::Monitor::Context::TrafficMonitor::All::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(ipv4.yfilter)
|| ydk::is_set(ipv6.yfilter);
}
std::string Native::Performance::Monitor::Context::TrafficMonitor::All::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "all";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Performance::Monitor::Context::TrafficMonitor::All::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (ipv4.is_set || is_set(ipv4.yfilter)) leaf_name_data.push_back(ipv4.get_name_leafdata());
if (ipv6.is_set || is_set(ipv6.yfilter)) leaf_name_data.push_back(ipv6.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Performance::Monitor::Context::TrafficMonitor::All::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Performance::Monitor::Context::TrafficMonitor::All::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Performance::Monitor::Context::TrafficMonitor::All::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "ipv4")
{
ipv4 = value;
ipv4.value_namespace = name_space;
ipv4.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ipv6")
{
ipv6 = value;
ipv6.value_namespace = name_space;
ipv6.value_namespace_prefix = name_space_prefix;
}
}
void Native::Performance::Monitor::Context::TrafficMonitor::All::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "ipv4")
{
ipv4.yfilter = yfilter;
}
if(value_path == "ipv6")
{
ipv6.yfilter = yfilter;
}
}
bool Native::Performance::Monitor::Context::TrafficMonitor::All::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "ipv4" || name == "ipv6")
return true;
return false;
}
Native::Performance::Monitor::Context::TrafficMonitor::ApplicationResponseTime::ApplicationResponseTime()
:
cache_size{YType::uint32, "cache-size"},
class_replace{YType::str, "class-replace"},
interval_timeout{YType::uint32, "interval-timeout"},
cache_type{YType::enumeration, "cache-type"},
class_and{YType::str, "class-and"},
ipv4{YType::empty, "ipv4"},
ipv6{YType::empty, "ipv6"}
{
yang_name = "application-response-time"; yang_parent_name = "traffic-monitor"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true;
}
Native::Performance::Monitor::Context::TrafficMonitor::ApplicationResponseTime::~ApplicationResponseTime()
{
}
bool Native::Performance::Monitor::Context::TrafficMonitor::ApplicationResponseTime::has_data() const
{
if (is_presence_container) return true;
return cache_size.is_set
|| class_replace.is_set
|| interval_timeout.is_set
|| cache_type.is_set
|| class_and.is_set
|| ipv4.is_set
|| ipv6.is_set;
}
bool Native::Performance::Monitor::Context::TrafficMonitor::ApplicationResponseTime::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(cache_size.yfilter)
|| ydk::is_set(class_replace.yfilter)
|| ydk::is_set(interval_timeout.yfilter)
|| ydk::is_set(cache_type.yfilter)
|| ydk::is_set(class_and.yfilter)
|| ydk::is_set(ipv4.yfilter)
|| ydk::is_set(ipv6.yfilter);
}
std::string Native::Performance::Monitor::Context::TrafficMonitor::ApplicationResponseTime::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "application-response-time";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Performance::Monitor::Context::TrafficMonitor::ApplicationResponseTime::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (cache_size.is_set || is_set(cache_size.yfilter)) leaf_name_data.push_back(cache_size.get_name_leafdata());
if (class_replace.is_set || is_set(class_replace.yfilter)) leaf_name_data.push_back(class_replace.get_name_leafdata());
if (interval_timeout.is_set || is_set(interval_timeout.yfilter)) leaf_name_data.push_back(interval_timeout.get_name_leafdata());
if (cache_type.is_set || is_set(cache_type.yfilter)) leaf_name_data.push_back(cache_type.get_name_leafdata());
if (class_and.is_set || is_set(class_and.yfilter)) leaf_name_data.push_back(class_and.get_name_leafdata());
if (ipv4.is_set || is_set(ipv4.yfilter)) leaf_name_data.push_back(ipv4.get_name_leafdata());
if (ipv6.is_set || is_set(ipv6.yfilter)) leaf_name_data.push_back(ipv6.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Performance::Monitor::Context::TrafficMonitor::ApplicationResponseTime::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Performance::Monitor::Context::TrafficMonitor::ApplicationResponseTime::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Performance::Monitor::Context::TrafficMonitor::ApplicationResponseTime::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "cache-size")
{
cache_size = value;
cache_size.value_namespace = name_space;
cache_size.value_namespace_prefix = name_space_prefix;
}
if(value_path == "class-replace")
{
class_replace = value;
class_replace.value_namespace = name_space;
class_replace.value_namespace_prefix = name_space_prefix;
}
if(value_path == "interval-timeout")
{
interval_timeout = value;
interval_timeout.value_namespace = name_space;
interval_timeout.value_namespace_prefix = name_space_prefix;
}
if(value_path == "cache-type")
{
cache_type = value;
cache_type.value_namespace = name_space;
cache_type.value_namespace_prefix = name_space_prefix;
}
if(value_path == "class-and")
{
class_and = value;
class_and.value_namespace = name_space;
class_and.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ipv4")
{
ipv4 = value;
ipv4.value_namespace = name_space;
ipv4.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ipv6")
{
ipv6 = value;
ipv6.value_namespace = name_space;
ipv6.value_namespace_prefix = name_space_prefix;
}
}
void Native::Performance::Monitor::Context::TrafficMonitor::ApplicationResponseTime::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "cache-size")
{
cache_size.yfilter = yfilter;
}
if(value_path == "class-replace")
{
class_replace.yfilter = yfilter;
}
if(value_path == "interval-timeout")
{
interval_timeout.yfilter = yfilter;
}
if(value_path == "cache-type")
{
cache_type.yfilter = yfilter;
}
if(value_path == "class-and")
{
class_and.yfilter = yfilter;
}
if(value_path == "ipv4")
{
ipv4.yfilter = yfilter;
}
if(value_path == "ipv6")
{
ipv6.yfilter = yfilter;
}
}
bool Native::Performance::Monitor::Context::TrafficMonitor::ApplicationResponseTime::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "cache-size" || name == "class-replace" || name == "interval-timeout" || name == "cache-type" || name == "class-and" || name == "ipv4" || name == "ipv6")
return true;
return false;
}
Native::Performance::Monitor::Context::TrafficMonitor::ApplicationTrafficStats::ApplicationTrafficStats()
:
cache_size{YType::uint32, "cache-size"},
class_replace{YType::str, "class-replace"},
interval_timeout{YType::uint32, "interval-timeout"}
{
yang_name = "application-traffic-stats"; yang_parent_name = "traffic-monitor"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true;
}
Native::Performance::Monitor::Context::TrafficMonitor::ApplicationTrafficStats::~ApplicationTrafficStats()
{
}
bool Native::Performance::Monitor::Context::TrafficMonitor::ApplicationTrafficStats::has_data() const
{
if (is_presence_container) return true;
return cache_size.is_set
|| class_replace.is_set
|| interval_timeout.is_set;
}
bool Native::Performance::Monitor::Context::TrafficMonitor::ApplicationTrafficStats::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(cache_size.yfilter)
|| ydk::is_set(class_replace.yfilter)
|| ydk::is_set(interval_timeout.yfilter);
}
std::string Native::Performance::Monitor::Context::TrafficMonitor::ApplicationTrafficStats::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "application-traffic-stats";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Performance::Monitor::Context::TrafficMonitor::ApplicationTrafficStats::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (cache_size.is_set || is_set(cache_size.yfilter)) leaf_name_data.push_back(cache_size.get_name_leafdata());
if (class_replace.is_set || is_set(class_replace.yfilter)) leaf_name_data.push_back(class_replace.get_name_leafdata());
if (interval_timeout.is_set || is_set(interval_timeout.yfilter)) leaf_name_data.push_back(interval_timeout.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Performance::Monitor::Context::TrafficMonitor::ApplicationTrafficStats::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Performance::Monitor::Context::TrafficMonitor::ApplicationTrafficStats::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Performance::Monitor::Context::TrafficMonitor::ApplicationTrafficStats::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "cache-size")
{
cache_size = value;
cache_size.value_namespace = name_space;
cache_size.value_namespace_prefix = name_space_prefix;
}
if(value_path == "class-replace")
{
class_replace = value;
class_replace.value_namespace = name_space;
class_replace.value_namespace_prefix = name_space_prefix;
}
if(value_path == "interval-timeout")
{
interval_timeout = value;
interval_timeout.value_namespace = name_space;
interval_timeout.value_namespace_prefix = name_space_prefix;
}
}
void Native::Performance::Monitor::Context::TrafficMonitor::ApplicationTrafficStats::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "cache-size")
{
cache_size.yfilter = yfilter;
}
if(value_path == "class-replace")
{
class_replace.yfilter = yfilter;
}
if(value_path == "interval-timeout")
{
interval_timeout.yfilter = yfilter;
}
}
bool Native::Performance::Monitor::Context::TrafficMonitor::ApplicationTrafficStats::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "cache-size" || name == "class-replace" || name == "interval-timeout")
return true;
return false;
}
Native::Performance::Monitor::Context::TrafficMonitor::ConversationTrafficStats::ConversationTrafficStats()
:
cache_size{YType::uint32, "cache-size"},
class_replace{YType::str, "class-replace"},
interval_timeout{YType::uint32, "interval-timeout"},
cache_type{YType::enumeration, "cache-type"},
ipv4{YType::empty, "ipv4"},
ipv6{YType::empty, "ipv6"}
{
yang_name = "conversation-traffic-stats"; yang_parent_name = "traffic-monitor"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true;
}
Native::Performance::Monitor::Context::TrafficMonitor::ConversationTrafficStats::~ConversationTrafficStats()
{
}
bool Native::Performance::Monitor::Context::TrafficMonitor::ConversationTrafficStats::has_data() const
{
if (is_presence_container) return true;
return cache_size.is_set
|| class_replace.is_set
|| interval_timeout.is_set
|| cache_type.is_set
|| ipv4.is_set
|| ipv6.is_set;
}
bool Native::Performance::Monitor::Context::TrafficMonitor::ConversationTrafficStats::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(cache_size.yfilter)
|| ydk::is_set(class_replace.yfilter)
|| ydk::is_set(interval_timeout.yfilter)
|| ydk::is_set(cache_type.yfilter)
|| ydk::is_set(ipv4.yfilter)
|| ydk::is_set(ipv6.yfilter);
}
std::string Native::Performance::Monitor::Context::TrafficMonitor::ConversationTrafficStats::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "conversation-traffic-stats";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Performance::Monitor::Context::TrafficMonitor::ConversationTrafficStats::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (cache_size.is_set || is_set(cache_size.yfilter)) leaf_name_data.push_back(cache_size.get_name_leafdata());
if (class_replace.is_set || is_set(class_replace.yfilter)) leaf_name_data.push_back(class_replace.get_name_leafdata());
if (interval_timeout.is_set || is_set(interval_timeout.yfilter)) leaf_name_data.push_back(interval_timeout.get_name_leafdata());
if (cache_type.is_set || is_set(cache_type.yfilter)) leaf_name_data.push_back(cache_type.get_name_leafdata());
if (ipv4.is_set || is_set(ipv4.yfilter)) leaf_name_data.push_back(ipv4.get_name_leafdata());
if (ipv6.is_set || is_set(ipv6.yfilter)) leaf_name_data.push_back(ipv6.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Performance::Monitor::Context::TrafficMonitor::ConversationTrafficStats::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Performance::Monitor::Context::TrafficMonitor::ConversationTrafficStats::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Performance::Monitor::Context::TrafficMonitor::ConversationTrafficStats::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "cache-size")
{
cache_size = value;
cache_size.value_namespace = name_space;
cache_size.value_namespace_prefix = name_space_prefix;
}
if(value_path == "class-replace")
{
class_replace = value;
class_replace.value_namespace = name_space;
class_replace.value_namespace_prefix = name_space_prefix;
}
if(value_path == "interval-timeout")
{
interval_timeout = value;
interval_timeout.value_namespace = name_space;
interval_timeout.value_namespace_prefix = name_space_prefix;
}
if(value_path == "cache-type")
{
cache_type = value;
cache_type.value_namespace = name_space;
cache_type.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ipv4")
{
ipv4 = value;
ipv4.value_namespace = name_space;
ipv4.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ipv6")
{
ipv6 = value;
ipv6.value_namespace = name_space;
ipv6.value_namespace_prefix = name_space_prefix;
}
}
void Native::Performance::Monitor::Context::TrafficMonitor::ConversationTrafficStats::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "cache-size")
{
cache_size.yfilter = yfilter;
}
if(value_path == "class-replace")
{
class_replace.yfilter = yfilter;
}
if(value_path == "interval-timeout")
{
interval_timeout.yfilter = yfilter;
}
if(value_path == "cache-type")
{
cache_type.yfilter = yfilter;
}
if(value_path == "ipv4")
{
ipv4.yfilter = yfilter;
}
if(value_path == "ipv6")
{
ipv6.yfilter = yfilter;
}
}
bool Native::Performance::Monitor::Context::TrafficMonitor::ConversationTrafficStats::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "cache-size" || name == "class-replace" || name == "interval-timeout" || name == "cache-type" || name == "ipv4" || name == "ipv6")
return true;
return false;
}
Native::Performance::Monitor::Context::TrafficMonitor::Media::Media()
:
cache_size{YType::uint32, "cache-size"},
class_replace{YType::str, "class-replace"},
interval_timeout{YType::uint32, "interval-timeout"},
class_and{YType::str, "class-and"},
egress{YType::empty, "egress"},
ingress{YType::empty, "ingress"},
ipv4{YType::empty, "ipv4"},
ipv6{YType::empty, "ipv6"}
{
yang_name = "media"; yang_parent_name = "traffic-monitor"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true;
}
Native::Performance::Monitor::Context::TrafficMonitor::Media::~Media()
{
}
bool Native::Performance::Monitor::Context::TrafficMonitor::Media::has_data() const
{
if (is_presence_container) return true;
return cache_size.is_set
|| class_replace.is_set
|| interval_timeout.is_set
|| class_and.is_set
|| egress.is_set
|| ingress.is_set
|| ipv4.is_set
|| ipv6.is_set;
}
bool Native::Performance::Monitor::Context::TrafficMonitor::Media::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(cache_size.yfilter)
|| ydk::is_set(class_replace.yfilter)
|| ydk::is_set(interval_timeout.yfilter)
|| ydk::is_set(class_and.yfilter)
|| ydk::is_set(egress.yfilter)
|| ydk::is_set(ingress.yfilter)
|| ydk::is_set(ipv4.yfilter)
|| ydk::is_set(ipv6.yfilter);
}
std::string Native::Performance::Monitor::Context::TrafficMonitor::Media::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "media";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Performance::Monitor::Context::TrafficMonitor::Media::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (cache_size.is_set || is_set(cache_size.yfilter)) leaf_name_data.push_back(cache_size.get_name_leafdata());
if (class_replace.is_set || is_set(class_replace.yfilter)) leaf_name_data.push_back(class_replace.get_name_leafdata());
if (interval_timeout.is_set || is_set(interval_timeout.yfilter)) leaf_name_data.push_back(interval_timeout.get_name_leafdata());
if (class_and.is_set || is_set(class_and.yfilter)) leaf_name_data.push_back(class_and.get_name_leafdata());
if (egress.is_set || is_set(egress.yfilter)) leaf_name_data.push_back(egress.get_name_leafdata());
if (ingress.is_set || is_set(ingress.yfilter)) leaf_name_data.push_back(ingress.get_name_leafdata());
if (ipv4.is_set || is_set(ipv4.yfilter)) leaf_name_data.push_back(ipv4.get_name_leafdata());
if (ipv6.is_set || is_set(ipv6.yfilter)) leaf_name_data.push_back(ipv6.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Performance::Monitor::Context::TrafficMonitor::Media::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Performance::Monitor::Context::TrafficMonitor::Media::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Performance::Monitor::Context::TrafficMonitor::Media::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "cache-size")
{
cache_size = value;
cache_size.value_namespace = name_space;
cache_size.value_namespace_prefix = name_space_prefix;
}
if(value_path == "class-replace")
{
class_replace = value;
class_replace.value_namespace = name_space;
class_replace.value_namespace_prefix = name_space_prefix;
}
if(value_path == "interval-timeout")
{
interval_timeout = value;
interval_timeout.value_namespace = name_space;
interval_timeout.value_namespace_prefix = name_space_prefix;
}
if(value_path == "class-and")
{
class_and = value;
class_and.value_namespace = name_space;
class_and.value_namespace_prefix = name_space_prefix;
}
if(value_path == "egress")
{
egress = value;
egress.value_namespace = name_space;
egress.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ingress")
{
ingress = value;
ingress.value_namespace = name_space;
ingress.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ipv4")
{
ipv4 = value;
ipv4.value_namespace = name_space;
ipv4.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ipv6")
{
ipv6 = value;
ipv6.value_namespace = name_space;
ipv6.value_namespace_prefix = name_space_prefix;
}
}
void Native::Performance::Monitor::Context::TrafficMonitor::Media::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "cache-size")
{
cache_size.yfilter = yfilter;
}
if(value_path == "class-replace")
{
class_replace.yfilter = yfilter;
}
if(value_path == "interval-timeout")
{
interval_timeout.yfilter = yfilter;
}
if(value_path == "class-and")
{
class_and.yfilter = yfilter;
}
if(value_path == "egress")
{
egress.yfilter = yfilter;
}
if(value_path == "ingress")
{
ingress.yfilter = yfilter;
}
if(value_path == "ipv4")
{
ipv4.yfilter = yfilter;
}
if(value_path == "ipv6")
{
ipv6.yfilter = yfilter;
}
}
bool Native::Performance::Monitor::Context::TrafficMonitor::Media::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "cache-size" || name == "class-replace" || name == "interval-timeout" || name == "class-and" || name == "egress" || name == "ingress" || name == "ipv4" || name == "ipv6")
return true;
return false;
}
Native::Performance::Monitor::Context::TrafficMonitor::Url::Url()
:
cache_size{YType::uint32, "cache-size"},
class_and{YType::str, "class-and"},
class_replace{YType::str, "class-replace"},
ipv4{YType::empty, "ipv4"},
ipv6{YType::empty, "ipv6"},
sampling_rate{YType::uint32, "sampling-rate"}
{
yang_name = "url"; yang_parent_name = "traffic-monitor"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true;
}
Native::Performance::Monitor::Context::TrafficMonitor::Url::~Url()
{
}
bool Native::Performance::Monitor::Context::TrafficMonitor::Url::has_data() const
{
if (is_presence_container) return true;
return cache_size.is_set
|| class_and.is_set
|| class_replace.is_set
|| ipv4.is_set
|| ipv6.is_set
|| sampling_rate.is_set;
}
bool Native::Performance::Monitor::Context::TrafficMonitor::Url::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(cache_size.yfilter)
|| ydk::is_set(class_and.yfilter)
|| ydk::is_set(class_replace.yfilter)
|| ydk::is_set(ipv4.yfilter)
|| ydk::is_set(ipv6.yfilter)
|| ydk::is_set(sampling_rate.yfilter);
}
std::string Native::Performance::Monitor::Context::TrafficMonitor::Url::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "url";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Performance::Monitor::Context::TrafficMonitor::Url::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (cache_size.is_set || is_set(cache_size.yfilter)) leaf_name_data.push_back(cache_size.get_name_leafdata());
if (class_and.is_set || is_set(class_and.yfilter)) leaf_name_data.push_back(class_and.get_name_leafdata());
if (class_replace.is_set || is_set(class_replace.yfilter)) leaf_name_data.push_back(class_replace.get_name_leafdata());
if (ipv4.is_set || is_set(ipv4.yfilter)) leaf_name_data.push_back(ipv4.get_name_leafdata());
if (ipv6.is_set || is_set(ipv6.yfilter)) leaf_name_data.push_back(ipv6.get_name_leafdata());
if (sampling_rate.is_set || is_set(sampling_rate.yfilter)) leaf_name_data.push_back(sampling_rate.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Performance::Monitor::Context::TrafficMonitor::Url::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Performance::Monitor::Context::TrafficMonitor::Url::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Performance::Monitor::Context::TrafficMonitor::Url::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "cache-size")
{
cache_size = value;
cache_size.value_namespace = name_space;
cache_size.value_namespace_prefix = name_space_prefix;
}
if(value_path == "class-and")
{
class_and = value;
class_and.value_namespace = name_space;
class_and.value_namespace_prefix = name_space_prefix;
}
if(value_path == "class-replace")
{
class_replace = value;
class_replace.value_namespace = name_space;
class_replace.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ipv4")
{
ipv4 = value;
ipv4.value_namespace = name_space;
ipv4.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ipv6")
{
ipv6 = value;
ipv6.value_namespace = name_space;
ipv6.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sampling-rate")
{
sampling_rate = value;
sampling_rate.value_namespace = name_space;
sampling_rate.value_namespace_prefix = name_space_prefix;
}
}
void Native::Performance::Monitor::Context::TrafficMonitor::Url::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "cache-size")
{
cache_size.yfilter = yfilter;
}
if(value_path == "class-and")
{
class_and.yfilter = yfilter;
}
if(value_path == "class-replace")
{
class_replace.yfilter = yfilter;
}
if(value_path == "ipv4")
{
ipv4.yfilter = yfilter;
}
if(value_path == "ipv6")
{
ipv6.yfilter = yfilter;
}
if(value_path == "sampling-rate")
{
sampling_rate.yfilter = yfilter;
}
}
bool Native::Performance::Monitor::Context::TrafficMonitor::Url::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "cache-size" || name == "class-and" || name == "class-replace" || name == "ipv4" || name == "ipv6" || name == "sampling-rate")
return true;
return false;
}
Native::Performance::Monitor::Context::TrafficMonitor::ApplicationClientServerStats::ApplicationClientServerStats()
:
cache_size{YType::uint32, "cache-size"},
class_replace{YType::str, "class-replace"},
interval_timeout{YType::uint32, "interval-timeout"},
cache_type{YType::enumeration, "cache-type"},
ipv4{YType::empty, "ipv4"},
ipv6{YType::empty, "ipv6"}
{
yang_name = "application-client-server-stats"; yang_parent_name = "traffic-monitor"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true;
}
Native::Performance::Monitor::Context::TrafficMonitor::ApplicationClientServerStats::~ApplicationClientServerStats()
{
}
bool Native::Performance::Monitor::Context::TrafficMonitor::ApplicationClientServerStats::has_data() const
{
if (is_presence_container) return true;
return cache_size.is_set
|| class_replace.is_set
|| interval_timeout.is_set
|| cache_type.is_set
|| ipv4.is_set
|| ipv6.is_set;
}
bool Native::Performance::Monitor::Context::TrafficMonitor::ApplicationClientServerStats::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(cache_size.yfilter)
|| ydk::is_set(class_replace.yfilter)
|| ydk::is_set(interval_timeout.yfilter)
|| ydk::is_set(cache_type.yfilter)
|| ydk::is_set(ipv4.yfilter)
|| ydk::is_set(ipv6.yfilter);
}
std::string Native::Performance::Monitor::Context::TrafficMonitor::ApplicationClientServerStats::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "application-client-server-stats";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Performance::Monitor::Context::TrafficMonitor::ApplicationClientServerStats::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (cache_size.is_set || is_set(cache_size.yfilter)) leaf_name_data.push_back(cache_size.get_name_leafdata());
if (class_replace.is_set || is_set(class_replace.yfilter)) leaf_name_data.push_back(class_replace.get_name_leafdata());
if (interval_timeout.is_set || is_set(interval_timeout.yfilter)) leaf_name_data.push_back(interval_timeout.get_name_leafdata());
if (cache_type.is_set || is_set(cache_type.yfilter)) leaf_name_data.push_back(cache_type.get_name_leafdata());
if (ipv4.is_set || is_set(ipv4.yfilter)) leaf_name_data.push_back(ipv4.get_name_leafdata());
if (ipv6.is_set || is_set(ipv6.yfilter)) leaf_name_data.push_back(ipv6.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Performance::Monitor::Context::TrafficMonitor::ApplicationClientServerStats::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Performance::Monitor::Context::TrafficMonitor::ApplicationClientServerStats::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Performance::Monitor::Context::TrafficMonitor::ApplicationClientServerStats::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "cache-size")
{
cache_size = value;
cache_size.value_namespace = name_space;
cache_size.value_namespace_prefix = name_space_prefix;
}
if(value_path == "class-replace")
{
class_replace = value;
class_replace.value_namespace = name_space;
class_replace.value_namespace_prefix = name_space_prefix;
}
if(value_path == "interval-timeout")
{
interval_timeout = value;
interval_timeout.value_namespace = name_space;
interval_timeout.value_namespace_prefix = name_space_prefix;
}
if(value_path == "cache-type")
{
cache_type = value;
cache_type.value_namespace = name_space;
cache_type.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ipv4")
{
ipv4 = value;
ipv4.value_namespace = name_space;
ipv4.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ipv6")
{
ipv6 = value;
ipv6.value_namespace = name_space;
ipv6.value_namespace_prefix = name_space_prefix;
}
}
void Native::Performance::Monitor::Context::TrafficMonitor::ApplicationClientServerStats::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "cache-size")
{
cache_size.yfilter = yfilter;
}
if(value_path == "class-replace")
{
class_replace.yfilter = yfilter;
}
if(value_path == "interval-timeout")
{
interval_timeout.yfilter = yfilter;
}
if(value_path == "cache-type")
{
cache_type.yfilter = yfilter;
}
if(value_path == "ipv4")
{
ipv4.yfilter = yfilter;
}
if(value_path == "ipv6")
{
ipv6.yfilter = yfilter;
}
}
bool Native::Performance::Monitor::Context::TrafficMonitor::ApplicationClientServerStats::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "cache-size" || name == "class-replace" || name == "interval-timeout" || name == "cache-type" || name == "ipv4" || name == "ipv6")
return true;
return false;
}
Native::Performance::Monitor::Context::TrafficMonitor::ApplicationStats::ApplicationStats()
:
cache_size{YType::uint32, "cache-size"},
class_replace{YType::str, "class-replace"},
interval_timeout{YType::uint32, "interval-timeout"}
{
yang_name = "application-stats"; yang_parent_name = "traffic-monitor"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true;
}
Native::Performance::Monitor::Context::TrafficMonitor::ApplicationStats::~ApplicationStats()
{
}
bool Native::Performance::Monitor::Context::TrafficMonitor::ApplicationStats::has_data() const
{
if (is_presence_container) return true;
return cache_size.is_set
|| class_replace.is_set
|| interval_timeout.is_set;
}
bool Native::Performance::Monitor::Context::TrafficMonitor::ApplicationStats::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(cache_size.yfilter)
|| ydk::is_set(class_replace.yfilter)
|| ydk::is_set(interval_timeout.yfilter);
}
std::string Native::Performance::Monitor::Context::TrafficMonitor::ApplicationStats::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "application-stats";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Performance::Monitor::Context::TrafficMonitor::ApplicationStats::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (cache_size.is_set || is_set(cache_size.yfilter)) leaf_name_data.push_back(cache_size.get_name_leafdata());
if (class_replace.is_set || is_set(class_replace.yfilter)) leaf_name_data.push_back(class_replace.get_name_leafdata());
if (interval_timeout.is_set || is_set(interval_timeout.yfilter)) leaf_name_data.push_back(interval_timeout.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Performance::Monitor::Context::TrafficMonitor::ApplicationStats::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Performance::Monitor::Context::TrafficMonitor::ApplicationStats::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Performance::Monitor::Context::TrafficMonitor::ApplicationStats::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "cache-size")
{
cache_size = value;
cache_size.value_namespace = name_space;
cache_size.value_namespace_prefix = name_space_prefix;
}
if(value_path == "class-replace")
{
class_replace = value;
class_replace.value_namespace = name_space;
class_replace.value_namespace_prefix = name_space_prefix;
}
if(value_path == "interval-timeout")
{
interval_timeout = value;
interval_timeout.value_namespace = name_space;
interval_timeout.value_namespace_prefix = name_space_prefix;
}
}
void Native::Performance::Monitor::Context::TrafficMonitor::ApplicationStats::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "cache-size")
{
cache_size.yfilter = yfilter;
}
if(value_path == "class-replace")
{
class_replace.yfilter = yfilter;
}
if(value_path == "interval-timeout")
{
interval_timeout.yfilter = yfilter;
}
}
bool Native::Performance::Monitor::Context::TrafficMonitor::ApplicationStats::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "cache-size" || name == "class-replace" || name == "interval-timeout")
return true;
return false;
}
Native::Performance::Monitor::ObservationPoint::ObservationPoint()
:
encrypted_text{YType::empty, "encrypted-text"}
{
yang_name = "observation-point"; yang_parent_name = "monitor"; is_top_level_class = false; has_list_ancestor = false;
}
Native::Performance::Monitor::ObservationPoint::~ObservationPoint()
{
}
bool Native::Performance::Monitor::ObservationPoint::has_data() const
{
if (is_presence_container) return true;
return encrypted_text.is_set;
}
bool Native::Performance::Monitor::ObservationPoint::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(encrypted_text.yfilter);
}
std::string Native::Performance::Monitor::ObservationPoint::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/performance/Cisco-IOS-XE-ezpm:monitor/" << get_segment_path();
return path_buffer.str();
}
std::string Native::Performance::Monitor::ObservationPoint::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "observation-point";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Performance::Monitor::ObservationPoint::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (encrypted_text.is_set || is_set(encrypted_text.yfilter)) leaf_name_data.push_back(encrypted_text.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Performance::Monitor::ObservationPoint::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Performance::Monitor::ObservationPoint::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Performance::Monitor::ObservationPoint::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "encrypted-text")
{
encrypted_text = value;
encrypted_text.value_namespace = name_space;
encrypted_text.value_namespace_prefix = name_space_prefix;
}
}
void Native::Performance::Monitor::ObservationPoint::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "encrypted-text")
{
encrypted_text.yfilter = yfilter;
}
}
bool Native::Performance::Monitor::ObservationPoint::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "encrypted-text")
return true;
return false;
}
Native::Otv::Otv()
:
site_identifier{YType::str, "Cisco-IOS-XE-otv:site-identifier"}
,
fragmentation(std::make_shared<Native::Otv::Fragmentation>())
, isis(std::make_shared<Native::Otv::Isis>())
, site(this, {"bridge_domain"})
{
fragmentation->parent = this;
isis->parent = this;
yang_name = "otv"; yang_parent_name = "native"; is_top_level_class = false; has_list_ancestor = false;
}
Native::Otv::~Otv()
{
}
bool Native::Otv::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<site.len(); index++)
{
if(site[index]->has_data())
return true;
}
return site_identifier.is_set
|| (fragmentation != nullptr && fragmentation->has_data())
|| (isis != nullptr && isis->has_data());
}
bool Native::Otv::has_operation() const
{
for (std::size_t index=0; index<site.len(); index++)
{
if(site[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(site_identifier.yfilter)
|| (fragmentation != nullptr && fragmentation->has_operation())
|| (isis != nullptr && isis->has_operation());
}
std::string Native::Otv::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/" << get_segment_path();
return path_buffer.str();
}
std::string Native::Otv::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "otv";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (site_identifier.is_set || is_set(site_identifier.yfilter)) leaf_name_data.push_back(site_identifier.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "Cisco-IOS-XE-otv:fragmentation")
{
if(fragmentation == nullptr)
{
fragmentation = std::make_shared<Native::Otv::Fragmentation>();
}
return fragmentation;
}
if(child_yang_name == "Cisco-IOS-XE-otv:isis")
{
if(isis == nullptr)
{
isis = std::make_shared<Native::Otv::Isis>();
}
return isis;
}
if(child_yang_name == "Cisco-IOS-XE-otv:site")
{
auto ent_ = std::make_shared<Native::Otv::Site>();
ent_->parent = this;
site.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(fragmentation != nullptr)
{
_children["Cisco-IOS-XE-otv:fragmentation"] = fragmentation;
}
if(isis != nullptr)
{
_children["Cisco-IOS-XE-otv:isis"] = isis;
}
count_ = 0;
for (auto ent_ : site.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Native::Otv::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "Cisco-IOS-XE-otv:site-identifier")
{
site_identifier = value;
site_identifier.value_namespace = name_space;
site_identifier.value_namespace_prefix = name_space_prefix;
}
}
void Native::Otv::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "site-identifier")
{
site_identifier.yfilter = yfilter;
}
}
bool Native::Otv::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "fragmentation" || name == "isis" || name == "site" || name == "site-identifier")
return true;
return false;
}
Native::Otv::Fragmentation::Fragmentation()
:
join_interface(std::make_shared<Native::Otv::Fragmentation::JoinInterface>())
{
join_interface->parent = this;
yang_name = "fragmentation"; yang_parent_name = "otv"; is_top_level_class = false; has_list_ancestor = false;
}
Native::Otv::Fragmentation::~Fragmentation()
{
}
bool Native::Otv::Fragmentation::has_data() const
{
if (is_presence_container) return true;
return (join_interface != nullptr && join_interface->has_data());
}
bool Native::Otv::Fragmentation::has_operation() const
{
return is_set(yfilter)
|| (join_interface != nullptr && join_interface->has_operation());
}
std::string Native::Otv::Fragmentation::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/otv/" << get_segment_path();
return path_buffer.str();
}
std::string Native::Otv::Fragmentation::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-otv:fragmentation";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Fragmentation::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Fragmentation::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "join-interface")
{
if(join_interface == nullptr)
{
join_interface = std::make_shared<Native::Otv::Fragmentation::JoinInterface>();
}
return join_interface;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Fragmentation::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(join_interface != nullptr)
{
_children["join-interface"] = join_interface;
}
return _children;
}
void Native::Otv::Fragmentation::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::Otv::Fragmentation::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::Otv::Fragmentation::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "join-interface")
return true;
return false;
}
Native::Otv::Fragmentation::JoinInterface::JoinInterface()
:
appnav_compress{YType::uint16, "AppNav-Compress"},
appnav_uncompress{YType::uint16, "AppNav-UnCompress"},
atm{YType::str, "ATM"},
atm_acr{YType::str, "ATM-ACR"},
bdi{YType::str, "BDI"},
cem{YType::str, "CEM"},
cem_acr{YType::uint8, "CEM-ACR"},
embedded_service_engine{YType::str, "Embedded-Service-Engine"},
ethernet{YType::str, "Ethernet"},
fastethernet{YType::str, "FastEthernet"},
gigabitethernet{YType::str, "GigabitEthernet"},
fivegigabitethernet{YType::str, "FiveGigabitEthernet"},
twentyfivegige{YType::str, "TwentyFiveGigE"},
twogigabitethernet{YType::str, "TwoGigabitEthernet"},
fortygigabitethernet{YType::str, "FortyGigabitEthernet"},
hundredgige{YType::str, "HundredGigE"},
lisp{YType::str, "LISP"},
loopback{YType::uint32, "Loopback"},
multilink{YType::uint16, "Multilink"},
nve{YType::uint16, "nve"},
overlay{YType::uint16, "overlay"},
port_channel{YType::uint32, "Port-channel"},
pseudowire{YType::uint32, "pseudowire"},
sm{YType::str, "SM"},
cellular{YType::str, "Cellular"},
serial{YType::str, "Serial"},
tengigabitethernet{YType::str, "TenGigabitEthernet"},
tunnel{YType::uint32, "Tunnel"},
virtual_template{YType::uint16, "Virtual-Template"},
vlan{YType::uint16, "Vlan"},
virtualportgroup{YType::uint16, "VirtualPortGroup"},
vasileft{YType::uint16, "vasileft"},
vasiright{YType::uint16, "vasiright"}
,
atm_subinterface(std::make_shared<Native::Otv::Fragmentation::JoinInterface::ATMSubinterface>())
, atm_acrsubinterface(std::make_shared<Native::Otv::Fragmentation::JoinInterface::ATMACRsubinterface>())
, lisp_subinterface(std::make_shared<Native::Otv::Fragmentation::JoinInterface::LISPSubinterface>())
, port_channel_subinterface(std::make_shared<Native::Otv::Fragmentation::JoinInterface::PortChannelSubinterface>())
{
atm_subinterface->parent = this;
atm_acrsubinterface->parent = this;
lisp_subinterface->parent = this;
port_channel_subinterface->parent = this;
yang_name = "join-interface"; yang_parent_name = "fragmentation"; is_top_level_class = false; has_list_ancestor = false;
}
Native::Otv::Fragmentation::JoinInterface::~JoinInterface()
{
}
bool Native::Otv::Fragmentation::JoinInterface::has_data() const
{
if (is_presence_container) return true;
return appnav_compress.is_set
|| appnav_uncompress.is_set
|| atm.is_set
|| atm_acr.is_set
|| bdi.is_set
|| cem.is_set
|| cem_acr.is_set
|| embedded_service_engine.is_set
|| ethernet.is_set
|| fastethernet.is_set
|| gigabitethernet.is_set
|| fivegigabitethernet.is_set
|| twentyfivegige.is_set
|| twogigabitethernet.is_set
|| fortygigabitethernet.is_set
|| hundredgige.is_set
|| lisp.is_set
|| loopback.is_set
|| multilink.is_set
|| nve.is_set
|| overlay.is_set
|| port_channel.is_set
|| pseudowire.is_set
|| sm.is_set
|| cellular.is_set
|| serial.is_set
|| tengigabitethernet.is_set
|| tunnel.is_set
|| virtual_template.is_set
|| vlan.is_set
|| virtualportgroup.is_set
|| vasileft.is_set
|| vasiright.is_set
|| (atm_subinterface != nullptr && atm_subinterface->has_data())
|| (atm_acrsubinterface != nullptr && atm_acrsubinterface->has_data())
|| (lisp_subinterface != nullptr && lisp_subinterface->has_data())
|| (port_channel_subinterface != nullptr && port_channel_subinterface->has_data());
}
bool Native::Otv::Fragmentation::JoinInterface::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(appnav_compress.yfilter)
|| ydk::is_set(appnav_uncompress.yfilter)
|| ydk::is_set(atm.yfilter)
|| ydk::is_set(atm_acr.yfilter)
|| ydk::is_set(bdi.yfilter)
|| ydk::is_set(cem.yfilter)
|| ydk::is_set(cem_acr.yfilter)
|| ydk::is_set(embedded_service_engine.yfilter)
|| ydk::is_set(ethernet.yfilter)
|| ydk::is_set(fastethernet.yfilter)
|| ydk::is_set(gigabitethernet.yfilter)
|| ydk::is_set(fivegigabitethernet.yfilter)
|| ydk::is_set(twentyfivegige.yfilter)
|| ydk::is_set(twogigabitethernet.yfilter)
|| ydk::is_set(fortygigabitethernet.yfilter)
|| ydk::is_set(hundredgige.yfilter)
|| ydk::is_set(lisp.yfilter)
|| ydk::is_set(loopback.yfilter)
|| ydk::is_set(multilink.yfilter)
|| ydk::is_set(nve.yfilter)
|| ydk::is_set(overlay.yfilter)
|| ydk::is_set(port_channel.yfilter)
|| ydk::is_set(pseudowire.yfilter)
|| ydk::is_set(sm.yfilter)
|| ydk::is_set(cellular.yfilter)
|| ydk::is_set(serial.yfilter)
|| ydk::is_set(tengigabitethernet.yfilter)
|| ydk::is_set(tunnel.yfilter)
|| ydk::is_set(virtual_template.yfilter)
|| ydk::is_set(vlan.yfilter)
|| ydk::is_set(virtualportgroup.yfilter)
|| ydk::is_set(vasileft.yfilter)
|| ydk::is_set(vasiright.yfilter)
|| (atm_subinterface != nullptr && atm_subinterface->has_operation())
|| (atm_acrsubinterface != nullptr && atm_acrsubinterface->has_operation())
|| (lisp_subinterface != nullptr && lisp_subinterface->has_operation())
|| (port_channel_subinterface != nullptr && port_channel_subinterface->has_operation());
}
std::string Native::Otv::Fragmentation::JoinInterface::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/otv/Cisco-IOS-XE-otv:fragmentation/" << get_segment_path();
return path_buffer.str();
}
std::string Native::Otv::Fragmentation::JoinInterface::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "join-interface";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Fragmentation::JoinInterface::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (appnav_compress.is_set || is_set(appnav_compress.yfilter)) leaf_name_data.push_back(appnav_compress.get_name_leafdata());
if (appnav_uncompress.is_set || is_set(appnav_uncompress.yfilter)) leaf_name_data.push_back(appnav_uncompress.get_name_leafdata());
if (atm.is_set || is_set(atm.yfilter)) leaf_name_data.push_back(atm.get_name_leafdata());
if (atm_acr.is_set || is_set(atm_acr.yfilter)) leaf_name_data.push_back(atm_acr.get_name_leafdata());
if (bdi.is_set || is_set(bdi.yfilter)) leaf_name_data.push_back(bdi.get_name_leafdata());
if (cem.is_set || is_set(cem.yfilter)) leaf_name_data.push_back(cem.get_name_leafdata());
if (cem_acr.is_set || is_set(cem_acr.yfilter)) leaf_name_data.push_back(cem_acr.get_name_leafdata());
if (embedded_service_engine.is_set || is_set(embedded_service_engine.yfilter)) leaf_name_data.push_back(embedded_service_engine.get_name_leafdata());
if (ethernet.is_set || is_set(ethernet.yfilter)) leaf_name_data.push_back(ethernet.get_name_leafdata());
if (fastethernet.is_set || is_set(fastethernet.yfilter)) leaf_name_data.push_back(fastethernet.get_name_leafdata());
if (gigabitethernet.is_set || is_set(gigabitethernet.yfilter)) leaf_name_data.push_back(gigabitethernet.get_name_leafdata());
if (fivegigabitethernet.is_set || is_set(fivegigabitethernet.yfilter)) leaf_name_data.push_back(fivegigabitethernet.get_name_leafdata());
if (twentyfivegige.is_set || is_set(twentyfivegige.yfilter)) leaf_name_data.push_back(twentyfivegige.get_name_leafdata());
if (twogigabitethernet.is_set || is_set(twogigabitethernet.yfilter)) leaf_name_data.push_back(twogigabitethernet.get_name_leafdata());
if (fortygigabitethernet.is_set || is_set(fortygigabitethernet.yfilter)) leaf_name_data.push_back(fortygigabitethernet.get_name_leafdata());
if (hundredgige.is_set || is_set(hundredgige.yfilter)) leaf_name_data.push_back(hundredgige.get_name_leafdata());
if (lisp.is_set || is_set(lisp.yfilter)) leaf_name_data.push_back(lisp.get_name_leafdata());
if (loopback.is_set || is_set(loopback.yfilter)) leaf_name_data.push_back(loopback.get_name_leafdata());
if (multilink.is_set || is_set(multilink.yfilter)) leaf_name_data.push_back(multilink.get_name_leafdata());
if (nve.is_set || is_set(nve.yfilter)) leaf_name_data.push_back(nve.get_name_leafdata());
if (overlay.is_set || is_set(overlay.yfilter)) leaf_name_data.push_back(overlay.get_name_leafdata());
if (port_channel.is_set || is_set(port_channel.yfilter)) leaf_name_data.push_back(port_channel.get_name_leafdata());
if (pseudowire.is_set || is_set(pseudowire.yfilter)) leaf_name_data.push_back(pseudowire.get_name_leafdata());
if (sm.is_set || is_set(sm.yfilter)) leaf_name_data.push_back(sm.get_name_leafdata());
if (cellular.is_set || is_set(cellular.yfilter)) leaf_name_data.push_back(cellular.get_name_leafdata());
if (serial.is_set || is_set(serial.yfilter)) leaf_name_data.push_back(serial.get_name_leafdata());
if (tengigabitethernet.is_set || is_set(tengigabitethernet.yfilter)) leaf_name_data.push_back(tengigabitethernet.get_name_leafdata());
if (tunnel.is_set || is_set(tunnel.yfilter)) leaf_name_data.push_back(tunnel.get_name_leafdata());
if (virtual_template.is_set || is_set(virtual_template.yfilter)) leaf_name_data.push_back(virtual_template.get_name_leafdata());
if (vlan.is_set || is_set(vlan.yfilter)) leaf_name_data.push_back(vlan.get_name_leafdata());
if (virtualportgroup.is_set || is_set(virtualportgroup.yfilter)) leaf_name_data.push_back(virtualportgroup.get_name_leafdata());
if (vasileft.is_set || is_set(vasileft.yfilter)) leaf_name_data.push_back(vasileft.get_name_leafdata());
if (vasiright.is_set || is_set(vasiright.yfilter)) leaf_name_data.push_back(vasiright.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Fragmentation::JoinInterface::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "ATM-subinterface")
{
if(atm_subinterface == nullptr)
{
atm_subinterface = std::make_shared<Native::Otv::Fragmentation::JoinInterface::ATMSubinterface>();
}
return atm_subinterface;
}
if(child_yang_name == "ATM-ACRsubinterface")
{
if(atm_acrsubinterface == nullptr)
{
atm_acrsubinterface = std::make_shared<Native::Otv::Fragmentation::JoinInterface::ATMACRsubinterface>();
}
return atm_acrsubinterface;
}
if(child_yang_name == "LISP-subinterface")
{
if(lisp_subinterface == nullptr)
{
lisp_subinterface = std::make_shared<Native::Otv::Fragmentation::JoinInterface::LISPSubinterface>();
}
return lisp_subinterface;
}
if(child_yang_name == "Port-channel-subinterface")
{
if(port_channel_subinterface == nullptr)
{
port_channel_subinterface = std::make_shared<Native::Otv::Fragmentation::JoinInterface::PortChannelSubinterface>();
}
return port_channel_subinterface;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Fragmentation::JoinInterface::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(atm_subinterface != nullptr)
{
_children["ATM-subinterface"] = atm_subinterface;
}
if(atm_acrsubinterface != nullptr)
{
_children["ATM-ACRsubinterface"] = atm_acrsubinterface;
}
if(lisp_subinterface != nullptr)
{
_children["LISP-subinterface"] = lisp_subinterface;
}
if(port_channel_subinterface != nullptr)
{
_children["Port-channel-subinterface"] = port_channel_subinterface;
}
return _children;
}
void Native::Otv::Fragmentation::JoinInterface::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "AppNav-Compress")
{
appnav_compress = value;
appnav_compress.value_namespace = name_space;
appnav_compress.value_namespace_prefix = name_space_prefix;
}
if(value_path == "AppNav-UnCompress")
{
appnav_uncompress = value;
appnav_uncompress.value_namespace = name_space;
appnav_uncompress.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ATM")
{
atm = value;
atm.value_namespace = name_space;
atm.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ATM-ACR")
{
atm_acr = value;
atm_acr.value_namespace = name_space;
atm_acr.value_namespace_prefix = name_space_prefix;
}
if(value_path == "BDI")
{
bdi = value;
bdi.value_namespace = name_space;
bdi.value_namespace_prefix = name_space_prefix;
}
if(value_path == "CEM")
{
cem = value;
cem.value_namespace = name_space;
cem.value_namespace_prefix = name_space_prefix;
}
if(value_path == "CEM-ACR")
{
cem_acr = value;
cem_acr.value_namespace = name_space;
cem_acr.value_namespace_prefix = name_space_prefix;
}
if(value_path == "Embedded-Service-Engine")
{
embedded_service_engine = value;
embedded_service_engine.value_namespace = name_space;
embedded_service_engine.value_namespace_prefix = name_space_prefix;
}
if(value_path == "Ethernet")
{
ethernet = value;
ethernet.value_namespace = name_space;
ethernet.value_namespace_prefix = name_space_prefix;
}
if(value_path == "FastEthernet")
{
fastethernet = value;
fastethernet.value_namespace = name_space;
fastethernet.value_namespace_prefix = name_space_prefix;
}
if(value_path == "GigabitEthernet")
{
gigabitethernet = value;
gigabitethernet.value_namespace = name_space;
gigabitethernet.value_namespace_prefix = name_space_prefix;
}
if(value_path == "FiveGigabitEthernet")
{
fivegigabitethernet = value;
fivegigabitethernet.value_namespace = name_space;
fivegigabitethernet.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TwentyFiveGigE")
{
twentyfivegige = value;
twentyfivegige.value_namespace = name_space;
twentyfivegige.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TwoGigabitEthernet")
{
twogigabitethernet = value;
twogigabitethernet.value_namespace = name_space;
twogigabitethernet.value_namespace_prefix = name_space_prefix;
}
if(value_path == "FortyGigabitEthernet")
{
fortygigabitethernet = value;
fortygigabitethernet.value_namespace = name_space;
fortygigabitethernet.value_namespace_prefix = name_space_prefix;
}
if(value_path == "HundredGigE")
{
hundredgige = value;
hundredgige.value_namespace = name_space;
hundredgige.value_namespace_prefix = name_space_prefix;
}
if(value_path == "LISP")
{
lisp = value;
lisp.value_namespace = name_space;
lisp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "Loopback")
{
loopback = value;
loopback.value_namespace = name_space;
loopback.value_namespace_prefix = name_space_prefix;
}
if(value_path == "Multilink")
{
multilink = value;
multilink.value_namespace = name_space;
multilink.value_namespace_prefix = name_space_prefix;
}
if(value_path == "nve")
{
nve = value;
nve.value_namespace = name_space;
nve.value_namespace_prefix = name_space_prefix;
}
if(value_path == "overlay")
{
overlay = value;
overlay.value_namespace = name_space;
overlay.value_namespace_prefix = name_space_prefix;
}
if(value_path == "Port-channel")
{
port_channel = value;
port_channel.value_namespace = name_space;
port_channel.value_namespace_prefix = name_space_prefix;
}
if(value_path == "pseudowire")
{
pseudowire = value;
pseudowire.value_namespace = name_space;
pseudowire.value_namespace_prefix = name_space_prefix;
}
if(value_path == "SM")
{
sm = value;
sm.value_namespace = name_space;
sm.value_namespace_prefix = name_space_prefix;
}
if(value_path == "Cellular")
{
cellular = value;
cellular.value_namespace = name_space;
cellular.value_namespace_prefix = name_space_prefix;
}
if(value_path == "Serial")
{
serial = value;
serial.value_namespace = name_space;
serial.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TenGigabitEthernet")
{
tengigabitethernet = value;
tengigabitethernet.value_namespace = name_space;
tengigabitethernet.value_namespace_prefix = name_space_prefix;
}
if(value_path == "Tunnel")
{
tunnel = value;
tunnel.value_namespace = name_space;
tunnel.value_namespace_prefix = name_space_prefix;
}
if(value_path == "Virtual-Template")
{
virtual_template = value;
virtual_template.value_namespace = name_space;
virtual_template.value_namespace_prefix = name_space_prefix;
}
if(value_path == "Vlan")
{
vlan = value;
vlan.value_namespace = name_space;
vlan.value_namespace_prefix = name_space_prefix;
}
if(value_path == "VirtualPortGroup")
{
virtualportgroup = value;
virtualportgroup.value_namespace = name_space;
virtualportgroup.value_namespace_prefix = name_space_prefix;
}
if(value_path == "vasileft")
{
vasileft = value;
vasileft.value_namespace = name_space;
vasileft.value_namespace_prefix = name_space_prefix;
}
if(value_path == "vasiright")
{
vasiright = value;
vasiright.value_namespace = name_space;
vasiright.value_namespace_prefix = name_space_prefix;
}
}
void Native::Otv::Fragmentation::JoinInterface::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "AppNav-Compress")
{
appnav_compress.yfilter = yfilter;
}
if(value_path == "AppNav-UnCompress")
{
appnav_uncompress.yfilter = yfilter;
}
if(value_path == "ATM")
{
atm.yfilter = yfilter;
}
if(value_path == "ATM-ACR")
{
atm_acr.yfilter = yfilter;
}
if(value_path == "BDI")
{
bdi.yfilter = yfilter;
}
if(value_path == "CEM")
{
cem.yfilter = yfilter;
}
if(value_path == "CEM-ACR")
{
cem_acr.yfilter = yfilter;
}
if(value_path == "Embedded-Service-Engine")
{
embedded_service_engine.yfilter = yfilter;
}
if(value_path == "Ethernet")
{
ethernet.yfilter = yfilter;
}
if(value_path == "FastEthernet")
{
fastethernet.yfilter = yfilter;
}
if(value_path == "GigabitEthernet")
{
gigabitethernet.yfilter = yfilter;
}
if(value_path == "FiveGigabitEthernet")
{
fivegigabitethernet.yfilter = yfilter;
}
if(value_path == "TwentyFiveGigE")
{
twentyfivegige.yfilter = yfilter;
}
if(value_path == "TwoGigabitEthernet")
{
twogigabitethernet.yfilter = yfilter;
}
if(value_path == "FortyGigabitEthernet")
{
fortygigabitethernet.yfilter = yfilter;
}
if(value_path == "HundredGigE")
{
hundredgige.yfilter = yfilter;
}
if(value_path == "LISP")
{
lisp.yfilter = yfilter;
}
if(value_path == "Loopback")
{
loopback.yfilter = yfilter;
}
if(value_path == "Multilink")
{
multilink.yfilter = yfilter;
}
if(value_path == "nve")
{
nve.yfilter = yfilter;
}
if(value_path == "overlay")
{
overlay.yfilter = yfilter;
}
if(value_path == "Port-channel")
{
port_channel.yfilter = yfilter;
}
if(value_path == "pseudowire")
{
pseudowire.yfilter = yfilter;
}
if(value_path == "SM")
{
sm.yfilter = yfilter;
}
if(value_path == "Cellular")
{
cellular.yfilter = yfilter;
}
if(value_path == "Serial")
{
serial.yfilter = yfilter;
}
if(value_path == "TenGigabitEthernet")
{
tengigabitethernet.yfilter = yfilter;
}
if(value_path == "Tunnel")
{
tunnel.yfilter = yfilter;
}
if(value_path == "Virtual-Template")
{
virtual_template.yfilter = yfilter;
}
if(value_path == "Vlan")
{
vlan.yfilter = yfilter;
}
if(value_path == "VirtualPortGroup")
{
virtualportgroup.yfilter = yfilter;
}
if(value_path == "vasileft")
{
vasileft.yfilter = yfilter;
}
if(value_path == "vasiright")
{
vasiright.yfilter = yfilter;
}
}
bool Native::Otv::Fragmentation::JoinInterface::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "ATM-subinterface" || name == "ATM-ACRsubinterface" || name == "LISP-subinterface" || name == "Port-channel-subinterface" || name == "AppNav-Compress" || name == "AppNav-UnCompress" || name == "ATM" || name == "ATM-ACR" || name == "BDI" || name == "CEM" || name == "CEM-ACR" || name == "Embedded-Service-Engine" || name == "Ethernet" || name == "FastEthernet" || name == "GigabitEthernet" || name == "FiveGigabitEthernet" || name == "TwentyFiveGigE" || name == "TwoGigabitEthernet" || name == "FortyGigabitEthernet" || name == "HundredGigE" || name == "LISP" || name == "Loopback" || name == "Multilink" || name == "nve" || name == "overlay" || name == "Port-channel" || name == "pseudowire" || name == "SM" || name == "Cellular" || name == "Serial" || name == "TenGigabitEthernet" || name == "Tunnel" || name == "Virtual-Template" || name == "Vlan" || name == "VirtualPortGroup" || name == "vasileft" || name == "vasiright")
return true;
return false;
}
Native::Otv::Fragmentation::JoinInterface::ATMSubinterface::ATMSubinterface()
:
atm{YType::str, "ATM"}
{
yang_name = "ATM-subinterface"; yang_parent_name = "join-interface"; is_top_level_class = false; has_list_ancestor = false;
}
Native::Otv::Fragmentation::JoinInterface::ATMSubinterface::~ATMSubinterface()
{
}
bool Native::Otv::Fragmentation::JoinInterface::ATMSubinterface::has_data() const
{
if (is_presence_container) return true;
return atm.is_set;
}
bool Native::Otv::Fragmentation::JoinInterface::ATMSubinterface::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(atm.yfilter);
}
std::string Native::Otv::Fragmentation::JoinInterface::ATMSubinterface::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/otv/Cisco-IOS-XE-otv:fragmentation/join-interface/" << get_segment_path();
return path_buffer.str();
}
std::string Native::Otv::Fragmentation::JoinInterface::ATMSubinterface::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "ATM-subinterface";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Fragmentation::JoinInterface::ATMSubinterface::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (atm.is_set || is_set(atm.yfilter)) leaf_name_data.push_back(atm.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Fragmentation::JoinInterface::ATMSubinterface::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Fragmentation::JoinInterface::ATMSubinterface::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Otv::Fragmentation::JoinInterface::ATMSubinterface::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "ATM")
{
atm = value;
atm.value_namespace = name_space;
atm.value_namespace_prefix = name_space_prefix;
}
}
void Native::Otv::Fragmentation::JoinInterface::ATMSubinterface::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "ATM")
{
atm.yfilter = yfilter;
}
}
bool Native::Otv::Fragmentation::JoinInterface::ATMSubinterface::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "ATM")
return true;
return false;
}
Native::Otv::Fragmentation::JoinInterface::ATMACRsubinterface::ATMACRsubinterface()
:
atm_acr{YType::str, "ATM-ACR"}
{
yang_name = "ATM-ACRsubinterface"; yang_parent_name = "join-interface"; is_top_level_class = false; has_list_ancestor = false;
}
Native::Otv::Fragmentation::JoinInterface::ATMACRsubinterface::~ATMACRsubinterface()
{
}
bool Native::Otv::Fragmentation::JoinInterface::ATMACRsubinterface::has_data() const
{
if (is_presence_container) return true;
return atm_acr.is_set;
}
bool Native::Otv::Fragmentation::JoinInterface::ATMACRsubinterface::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(atm_acr.yfilter);
}
std::string Native::Otv::Fragmentation::JoinInterface::ATMACRsubinterface::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/otv/Cisco-IOS-XE-otv:fragmentation/join-interface/" << get_segment_path();
return path_buffer.str();
}
std::string Native::Otv::Fragmentation::JoinInterface::ATMACRsubinterface::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "ATM-ACRsubinterface";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Fragmentation::JoinInterface::ATMACRsubinterface::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (atm_acr.is_set || is_set(atm_acr.yfilter)) leaf_name_data.push_back(atm_acr.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Fragmentation::JoinInterface::ATMACRsubinterface::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Fragmentation::JoinInterface::ATMACRsubinterface::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Otv::Fragmentation::JoinInterface::ATMACRsubinterface::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "ATM-ACR")
{
atm_acr = value;
atm_acr.value_namespace = name_space;
atm_acr.value_namespace_prefix = name_space_prefix;
}
}
void Native::Otv::Fragmentation::JoinInterface::ATMACRsubinterface::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "ATM-ACR")
{
atm_acr.yfilter = yfilter;
}
}
bool Native::Otv::Fragmentation::JoinInterface::ATMACRsubinterface::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "ATM-ACR")
return true;
return false;
}
Native::Otv::Fragmentation::JoinInterface::LISPSubinterface::LISPSubinterface()
:
lisp{YType::str, "LISP"}
{
yang_name = "LISP-subinterface"; yang_parent_name = "join-interface"; is_top_level_class = false; has_list_ancestor = false;
}
Native::Otv::Fragmentation::JoinInterface::LISPSubinterface::~LISPSubinterface()
{
}
bool Native::Otv::Fragmentation::JoinInterface::LISPSubinterface::has_data() const
{
if (is_presence_container) return true;
return lisp.is_set;
}
bool Native::Otv::Fragmentation::JoinInterface::LISPSubinterface::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(lisp.yfilter);
}
std::string Native::Otv::Fragmentation::JoinInterface::LISPSubinterface::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/otv/Cisco-IOS-XE-otv:fragmentation/join-interface/" << get_segment_path();
return path_buffer.str();
}
std::string Native::Otv::Fragmentation::JoinInterface::LISPSubinterface::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "LISP-subinterface";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Fragmentation::JoinInterface::LISPSubinterface::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (lisp.is_set || is_set(lisp.yfilter)) leaf_name_data.push_back(lisp.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Fragmentation::JoinInterface::LISPSubinterface::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Fragmentation::JoinInterface::LISPSubinterface::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Otv::Fragmentation::JoinInterface::LISPSubinterface::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "LISP")
{
lisp = value;
lisp.value_namespace = name_space;
lisp.value_namespace_prefix = name_space_prefix;
}
}
void Native::Otv::Fragmentation::JoinInterface::LISPSubinterface::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "LISP")
{
lisp.yfilter = yfilter;
}
}
bool Native::Otv::Fragmentation::JoinInterface::LISPSubinterface::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "LISP")
return true;
return false;
}
Native::Otv::Fragmentation::JoinInterface::PortChannelSubinterface::PortChannelSubinterface()
:
port_channel{YType::str, "Port-channel"}
{
yang_name = "Port-channel-subinterface"; yang_parent_name = "join-interface"; is_top_level_class = false; has_list_ancestor = false;
}
Native::Otv::Fragmentation::JoinInterface::PortChannelSubinterface::~PortChannelSubinterface()
{
}
bool Native::Otv::Fragmentation::JoinInterface::PortChannelSubinterface::has_data() const
{
if (is_presence_container) return true;
return port_channel.is_set;
}
bool Native::Otv::Fragmentation::JoinInterface::PortChannelSubinterface::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(port_channel.yfilter);
}
std::string Native::Otv::Fragmentation::JoinInterface::PortChannelSubinterface::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/otv/Cisco-IOS-XE-otv:fragmentation/join-interface/" << get_segment_path();
return path_buffer.str();
}
std::string Native::Otv::Fragmentation::JoinInterface::PortChannelSubinterface::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "Port-channel-subinterface";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Fragmentation::JoinInterface::PortChannelSubinterface::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_channel.is_set || is_set(port_channel.yfilter)) leaf_name_data.push_back(port_channel.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Fragmentation::JoinInterface::PortChannelSubinterface::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Fragmentation::JoinInterface::PortChannelSubinterface::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Otv::Fragmentation::JoinInterface::PortChannelSubinterface::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "Port-channel")
{
port_channel = value;
port_channel.value_namespace = name_space;
port_channel.value_namespace_prefix = name_space_prefix;
}
}
void Native::Otv::Fragmentation::JoinInterface::PortChannelSubinterface::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "Port-channel")
{
port_channel.yfilter = yfilter;
}
}
bool Native::Otv::Fragmentation::JoinInterface::PortChannelSubinterface::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "Port-channel")
return true;
return false;
}
Native::Otv::Isis::Isis()
:
overlay(this, {"number"})
, site(std::make_shared<Native::Otv::Isis::Site>())
{
site->parent = this;
yang_name = "isis"; yang_parent_name = "otv"; is_top_level_class = false; has_list_ancestor = false;
}
Native::Otv::Isis::~Isis()
{
}
bool Native::Otv::Isis::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<overlay.len(); index++)
{
if(overlay[index]->has_data())
return true;
}
return (site != nullptr && site->has_data());
}
bool Native::Otv::Isis::has_operation() const
{
for (std::size_t index=0; index<overlay.len(); index++)
{
if(overlay[index]->has_operation())
return true;
}
return is_set(yfilter)
|| (site != nullptr && site->has_operation());
}
std::string Native::Otv::Isis::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/otv/" << get_segment_path();
return path_buffer.str();
}
std::string Native::Otv::Isis::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-otv:isis";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Isis::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Isis::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "Overlay")
{
auto ent_ = std::make_shared<Native::Otv::Isis::Overlay>();
ent_->parent = this;
overlay.append(ent_);
return ent_;
}
if(child_yang_name == "site")
{
if(site == nullptr)
{
site = std::make_shared<Native::Otv::Isis::Site>();
}
return site;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Isis::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : overlay.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
if(site != nullptr)
{
_children["site"] = site;
}
return _children;
}
void Native::Otv::Isis::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::Otv::Isis::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::Otv::Isis::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "Overlay" || name == "site")
return true;
return false;
}
Native::Otv::Isis::Overlay::Overlay()
:
number{YType::uint16, "number"},
delayed_deletion_interval{YType::uint32, "delayed-deletion-interval"},
lsp_mtu{YType::uint32, "lsp-mtu"},
lsp_refresh_interval{YType::uint32, "lsp-refresh-interval"},
max_lsp_lifetime{YType::uint32, "max-lsp-lifetime"}
,
authentication(std::make_shared<Native::Otv::Isis::Overlay::Authentication>())
, default_(std::make_shared<Native::Otv::Isis::Overlay::Default>())
, hostname(std::make_shared<Native::Otv::Isis::Overlay::Hostname>())
, log_adjacency_changes(nullptr) // presence node
, lsp_gen_interval(std::make_shared<Native::Otv::Isis::Overlay::LspGenInterval>())
, nsf(std::make_shared<Native::Otv::Isis::Overlay::Nsf>())
, prc_interval(std::make_shared<Native::Otv::Isis::Overlay::PrcInterval>())
, skeptical(std::make_shared<Native::Otv::Isis::Overlay::Skeptical>())
, spf_interval(std::make_shared<Native::Otv::Isis::Overlay::SpfInterval>())
{
authentication->parent = this;
default_->parent = this;
hostname->parent = this;
lsp_gen_interval->parent = this;
nsf->parent = this;
prc_interval->parent = this;
skeptical->parent = this;
spf_interval->parent = this;
yang_name = "Overlay"; yang_parent_name = "isis"; is_top_level_class = false; has_list_ancestor = false;
}
Native::Otv::Isis::Overlay::~Overlay()
{
}
bool Native::Otv::Isis::Overlay::has_data() const
{
if (is_presence_container) return true;
return number.is_set
|| delayed_deletion_interval.is_set
|| lsp_mtu.is_set
|| lsp_refresh_interval.is_set
|| max_lsp_lifetime.is_set
|| (authentication != nullptr && authentication->has_data())
|| (default_ != nullptr && default_->has_data())
|| (hostname != nullptr && hostname->has_data())
|| (log_adjacency_changes != nullptr && log_adjacency_changes->has_data())
|| (lsp_gen_interval != nullptr && lsp_gen_interval->has_data())
|| (nsf != nullptr && nsf->has_data())
|| (prc_interval != nullptr && prc_interval->has_data())
|| (skeptical != nullptr && skeptical->has_data())
|| (spf_interval != nullptr && spf_interval->has_data());
}
bool Native::Otv::Isis::Overlay::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(number.yfilter)
|| ydk::is_set(delayed_deletion_interval.yfilter)
|| ydk::is_set(lsp_mtu.yfilter)
|| ydk::is_set(lsp_refresh_interval.yfilter)
|| ydk::is_set(max_lsp_lifetime.yfilter)
|| (authentication != nullptr && authentication->has_operation())
|| (default_ != nullptr && default_->has_operation())
|| (hostname != nullptr && hostname->has_operation())
|| (log_adjacency_changes != nullptr && log_adjacency_changes->has_operation())
|| (lsp_gen_interval != nullptr && lsp_gen_interval->has_operation())
|| (nsf != nullptr && nsf->has_operation())
|| (prc_interval != nullptr && prc_interval->has_operation())
|| (skeptical != nullptr && skeptical->has_operation())
|| (spf_interval != nullptr && spf_interval->has_operation());
}
std::string Native::Otv::Isis::Overlay::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/otv/Cisco-IOS-XE-otv:isis/" << get_segment_path();
return path_buffer.str();
}
std::string Native::Otv::Isis::Overlay::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "Overlay";
ADD_KEY_TOKEN(number, "number");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Isis::Overlay::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (number.is_set || is_set(number.yfilter)) leaf_name_data.push_back(number.get_name_leafdata());
if (delayed_deletion_interval.is_set || is_set(delayed_deletion_interval.yfilter)) leaf_name_data.push_back(delayed_deletion_interval.get_name_leafdata());
if (lsp_mtu.is_set || is_set(lsp_mtu.yfilter)) leaf_name_data.push_back(lsp_mtu.get_name_leafdata());
if (lsp_refresh_interval.is_set || is_set(lsp_refresh_interval.yfilter)) leaf_name_data.push_back(lsp_refresh_interval.get_name_leafdata());
if (max_lsp_lifetime.is_set || is_set(max_lsp_lifetime.yfilter)) leaf_name_data.push_back(max_lsp_lifetime.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Isis::Overlay::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "authentication")
{
if(authentication == nullptr)
{
authentication = std::make_shared<Native::Otv::Isis::Overlay::Authentication>();
}
return authentication;
}
if(child_yang_name == "default")
{
if(default_ == nullptr)
{
default_ = std::make_shared<Native::Otv::Isis::Overlay::Default>();
}
return default_;
}
if(child_yang_name == "hostname")
{
if(hostname == nullptr)
{
hostname = std::make_shared<Native::Otv::Isis::Overlay::Hostname>();
}
return hostname;
}
if(child_yang_name == "log-adjacency-changes")
{
if(log_adjacency_changes == nullptr)
{
log_adjacency_changes = std::make_shared<Native::Otv::Isis::Overlay::LogAdjacencyChanges>();
}
return log_adjacency_changes;
}
if(child_yang_name == "lsp-gen-interval")
{
if(lsp_gen_interval == nullptr)
{
lsp_gen_interval = std::make_shared<Native::Otv::Isis::Overlay::LspGenInterval>();
}
return lsp_gen_interval;
}
if(child_yang_name == "nsf")
{
if(nsf == nullptr)
{
nsf = std::make_shared<Native::Otv::Isis::Overlay::Nsf>();
}
return nsf;
}
if(child_yang_name == "prc-interval")
{
if(prc_interval == nullptr)
{
prc_interval = std::make_shared<Native::Otv::Isis::Overlay::PrcInterval>();
}
return prc_interval;
}
if(child_yang_name == "skeptical")
{
if(skeptical == nullptr)
{
skeptical = std::make_shared<Native::Otv::Isis::Overlay::Skeptical>();
}
return skeptical;
}
if(child_yang_name == "spf-interval")
{
if(spf_interval == nullptr)
{
spf_interval = std::make_shared<Native::Otv::Isis::Overlay::SpfInterval>();
}
return spf_interval;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Isis::Overlay::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(authentication != nullptr)
{
_children["authentication"] = authentication;
}
if(default_ != nullptr)
{
_children["default"] = default_;
}
if(hostname != nullptr)
{
_children["hostname"] = hostname;
}
if(log_adjacency_changes != nullptr)
{
_children["log-adjacency-changes"] = log_adjacency_changes;
}
if(lsp_gen_interval != nullptr)
{
_children["lsp-gen-interval"] = lsp_gen_interval;
}
if(nsf != nullptr)
{
_children["nsf"] = nsf;
}
if(prc_interval != nullptr)
{
_children["prc-interval"] = prc_interval;
}
if(skeptical != nullptr)
{
_children["skeptical"] = skeptical;
}
if(spf_interval != nullptr)
{
_children["spf-interval"] = spf_interval;
}
return _children;
}
void Native::Otv::Isis::Overlay::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "number")
{
number = value;
number.value_namespace = name_space;
number.value_namespace_prefix = name_space_prefix;
}
if(value_path == "delayed-deletion-interval")
{
delayed_deletion_interval = value;
delayed_deletion_interval.value_namespace = name_space;
delayed_deletion_interval.value_namespace_prefix = name_space_prefix;
}
if(value_path == "lsp-mtu")
{
lsp_mtu = value;
lsp_mtu.value_namespace = name_space;
lsp_mtu.value_namespace_prefix = name_space_prefix;
}
if(value_path == "lsp-refresh-interval")
{
lsp_refresh_interval = value;
lsp_refresh_interval.value_namespace = name_space;
lsp_refresh_interval.value_namespace_prefix = name_space_prefix;
}
if(value_path == "max-lsp-lifetime")
{
max_lsp_lifetime = value;
max_lsp_lifetime.value_namespace = name_space;
max_lsp_lifetime.value_namespace_prefix = name_space_prefix;
}
}
void Native::Otv::Isis::Overlay::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "number")
{
number.yfilter = yfilter;
}
if(value_path == "delayed-deletion-interval")
{
delayed_deletion_interval.yfilter = yfilter;
}
if(value_path == "lsp-mtu")
{
lsp_mtu.yfilter = yfilter;
}
if(value_path == "lsp-refresh-interval")
{
lsp_refresh_interval.yfilter = yfilter;
}
if(value_path == "max-lsp-lifetime")
{
max_lsp_lifetime.yfilter = yfilter;
}
}
bool Native::Otv::Isis::Overlay::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "authentication" || name == "default" || name == "hostname" || name == "log-adjacency-changes" || name == "lsp-gen-interval" || name == "nsf" || name == "prc-interval" || name == "skeptical" || name == "spf-interval" || name == "number" || name == "delayed-deletion-interval" || name == "lsp-mtu" || name == "lsp-refresh-interval" || name == "max-lsp-lifetime")
return true;
return false;
}
Native::Otv::Isis::Overlay::Authentication::Authentication()
:
key_chain{YType::str, "key-chain"},
mode{YType::enumeration, "mode"},
send_only{YType::empty, "send-only"}
{
yang_name = "authentication"; yang_parent_name = "Overlay"; is_top_level_class = false; has_list_ancestor = true;
}
Native::Otv::Isis::Overlay::Authentication::~Authentication()
{
}
bool Native::Otv::Isis::Overlay::Authentication::has_data() const
{
if (is_presence_container) return true;
return key_chain.is_set
|| mode.is_set
|| send_only.is_set;
}
bool Native::Otv::Isis::Overlay::Authentication::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(key_chain.yfilter)
|| ydk::is_set(mode.yfilter)
|| ydk::is_set(send_only.yfilter);
}
std::string Native::Otv::Isis::Overlay::Authentication::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "authentication";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Isis::Overlay::Authentication::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (key_chain.is_set || is_set(key_chain.yfilter)) leaf_name_data.push_back(key_chain.get_name_leafdata());
if (mode.is_set || is_set(mode.yfilter)) leaf_name_data.push_back(mode.get_name_leafdata());
if (send_only.is_set || is_set(send_only.yfilter)) leaf_name_data.push_back(send_only.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Isis::Overlay::Authentication::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Isis::Overlay::Authentication::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Otv::Isis::Overlay::Authentication::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "key-chain")
{
key_chain = value;
key_chain.value_namespace = name_space;
key_chain.value_namespace_prefix = name_space_prefix;
}
if(value_path == "mode")
{
mode = value;
mode.value_namespace = name_space;
mode.value_namespace_prefix = name_space_prefix;
}
if(value_path == "send-only")
{
send_only = value;
send_only.value_namespace = name_space;
send_only.value_namespace_prefix = name_space_prefix;
}
}
void Native::Otv::Isis::Overlay::Authentication::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "key-chain")
{
key_chain.yfilter = yfilter;
}
if(value_path == "mode")
{
mode.yfilter = yfilter;
}
if(value_path == "send-only")
{
send_only.yfilter = yfilter;
}
}
bool Native::Otv::Isis::Overlay::Authentication::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "key-chain" || name == "mode" || name == "send-only")
return true;
return false;
}
Native::Otv::Isis::Overlay::Default::Default()
:
delayed_deletion_interval{YType::empty, "delayed-deletion-interval"},
log_adjacency_changes{YType::empty, "log-adjacency-changes"},
lsp_gen_interval{YType::empty, "lsp-gen-interval"},
lsp_mtu{YType::empty, "lsp-mtu"},
lsp_refresh_interval{YType::empty, "lsp-refresh-interval"},
max_lsp_lifetime{YType::empty, "max-lsp-lifetime"},
prc_interval{YType::empty, "prc-interval"},
spf_interval{YType::empty, "spf-interval"}
,
authentication(std::make_shared<Native::Otv::Isis::Overlay::Default::Authentication>())
, hostname(std::make_shared<Native::Otv::Isis::Overlay::Default::Hostname>())
, nsf(std::make_shared<Native::Otv::Isis::Overlay::Default::Nsf>())
, skeptical(std::make_shared<Native::Otv::Isis::Overlay::Default::Skeptical>())
{
authentication->parent = this;
hostname->parent = this;
nsf->parent = this;
skeptical->parent = this;
yang_name = "default"; yang_parent_name = "Overlay"; is_top_level_class = false; has_list_ancestor = true;
}
Native::Otv::Isis::Overlay::Default::~Default()
{
}
bool Native::Otv::Isis::Overlay::Default::has_data() const
{
if (is_presence_container) return true;
return delayed_deletion_interval.is_set
|| log_adjacency_changes.is_set
|| lsp_gen_interval.is_set
|| lsp_mtu.is_set
|| lsp_refresh_interval.is_set
|| max_lsp_lifetime.is_set
|| prc_interval.is_set
|| spf_interval.is_set
|| (authentication != nullptr && authentication->has_data())
|| (hostname != nullptr && hostname->has_data())
|| (nsf != nullptr && nsf->has_data())
|| (skeptical != nullptr && skeptical->has_data());
}
bool Native::Otv::Isis::Overlay::Default::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(delayed_deletion_interval.yfilter)
|| ydk::is_set(log_adjacency_changes.yfilter)
|| ydk::is_set(lsp_gen_interval.yfilter)
|| ydk::is_set(lsp_mtu.yfilter)
|| ydk::is_set(lsp_refresh_interval.yfilter)
|| ydk::is_set(max_lsp_lifetime.yfilter)
|| ydk::is_set(prc_interval.yfilter)
|| ydk::is_set(spf_interval.yfilter)
|| (authentication != nullptr && authentication->has_operation())
|| (hostname != nullptr && hostname->has_operation())
|| (nsf != nullptr && nsf->has_operation())
|| (skeptical != nullptr && skeptical->has_operation());
}
std::string Native::Otv::Isis::Overlay::Default::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "default";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Isis::Overlay::Default::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (delayed_deletion_interval.is_set || is_set(delayed_deletion_interval.yfilter)) leaf_name_data.push_back(delayed_deletion_interval.get_name_leafdata());
if (log_adjacency_changes.is_set || is_set(log_adjacency_changes.yfilter)) leaf_name_data.push_back(log_adjacency_changes.get_name_leafdata());
if (lsp_gen_interval.is_set || is_set(lsp_gen_interval.yfilter)) leaf_name_data.push_back(lsp_gen_interval.get_name_leafdata());
if (lsp_mtu.is_set || is_set(lsp_mtu.yfilter)) leaf_name_data.push_back(lsp_mtu.get_name_leafdata());
if (lsp_refresh_interval.is_set || is_set(lsp_refresh_interval.yfilter)) leaf_name_data.push_back(lsp_refresh_interval.get_name_leafdata());
if (max_lsp_lifetime.is_set || is_set(max_lsp_lifetime.yfilter)) leaf_name_data.push_back(max_lsp_lifetime.get_name_leafdata());
if (prc_interval.is_set || is_set(prc_interval.yfilter)) leaf_name_data.push_back(prc_interval.get_name_leafdata());
if (spf_interval.is_set || is_set(spf_interval.yfilter)) leaf_name_data.push_back(spf_interval.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Isis::Overlay::Default::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "authentication")
{
if(authentication == nullptr)
{
authentication = std::make_shared<Native::Otv::Isis::Overlay::Default::Authentication>();
}
return authentication;
}
if(child_yang_name == "hostname")
{
if(hostname == nullptr)
{
hostname = std::make_shared<Native::Otv::Isis::Overlay::Default::Hostname>();
}
return hostname;
}
if(child_yang_name == "nsf")
{
if(nsf == nullptr)
{
nsf = std::make_shared<Native::Otv::Isis::Overlay::Default::Nsf>();
}
return nsf;
}
if(child_yang_name == "skeptical")
{
if(skeptical == nullptr)
{
skeptical = std::make_shared<Native::Otv::Isis::Overlay::Default::Skeptical>();
}
return skeptical;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Isis::Overlay::Default::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(authentication != nullptr)
{
_children["authentication"] = authentication;
}
if(hostname != nullptr)
{
_children["hostname"] = hostname;
}
if(nsf != nullptr)
{
_children["nsf"] = nsf;
}
if(skeptical != nullptr)
{
_children["skeptical"] = skeptical;
}
return _children;
}
void Native::Otv::Isis::Overlay::Default::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "delayed-deletion-interval")
{
delayed_deletion_interval = value;
delayed_deletion_interval.value_namespace = name_space;
delayed_deletion_interval.value_namespace_prefix = name_space_prefix;
}
if(value_path == "log-adjacency-changes")
{
log_adjacency_changes = value;
log_adjacency_changes.value_namespace = name_space;
log_adjacency_changes.value_namespace_prefix = name_space_prefix;
}
if(value_path == "lsp-gen-interval")
{
lsp_gen_interval = value;
lsp_gen_interval.value_namespace = name_space;
lsp_gen_interval.value_namespace_prefix = name_space_prefix;
}
if(value_path == "lsp-mtu")
{
lsp_mtu = value;
lsp_mtu.value_namespace = name_space;
lsp_mtu.value_namespace_prefix = name_space_prefix;
}
if(value_path == "lsp-refresh-interval")
{
lsp_refresh_interval = value;
lsp_refresh_interval.value_namespace = name_space;
lsp_refresh_interval.value_namespace_prefix = name_space_prefix;
}
if(value_path == "max-lsp-lifetime")
{
max_lsp_lifetime = value;
max_lsp_lifetime.value_namespace = name_space;
max_lsp_lifetime.value_namespace_prefix = name_space_prefix;
}
if(value_path == "prc-interval")
{
prc_interval = value;
prc_interval.value_namespace = name_space;
prc_interval.value_namespace_prefix = name_space_prefix;
}
if(value_path == "spf-interval")
{
spf_interval = value;
spf_interval.value_namespace = name_space;
spf_interval.value_namespace_prefix = name_space_prefix;
}
}
void Native::Otv::Isis::Overlay::Default::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "delayed-deletion-interval")
{
delayed_deletion_interval.yfilter = yfilter;
}
if(value_path == "log-adjacency-changes")
{
log_adjacency_changes.yfilter = yfilter;
}
if(value_path == "lsp-gen-interval")
{
lsp_gen_interval.yfilter = yfilter;
}
if(value_path == "lsp-mtu")
{
lsp_mtu.yfilter = yfilter;
}
if(value_path == "lsp-refresh-interval")
{
lsp_refresh_interval.yfilter = yfilter;
}
if(value_path == "max-lsp-lifetime")
{
max_lsp_lifetime.yfilter = yfilter;
}
if(value_path == "prc-interval")
{
prc_interval.yfilter = yfilter;
}
if(value_path == "spf-interval")
{
spf_interval.yfilter = yfilter;
}
}
bool Native::Otv::Isis::Overlay::Default::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "authentication" || name == "hostname" || name == "nsf" || name == "skeptical" || name == "delayed-deletion-interval" || name == "log-adjacency-changes" || name == "lsp-gen-interval" || name == "lsp-mtu" || name == "lsp-refresh-interval" || name == "max-lsp-lifetime" || name == "prc-interval" || name == "spf-interval")
return true;
return false;
}
Native::Otv::Isis::Overlay::Default::Authentication::Authentication()
:
key_chain{YType::str, "key-chain"},
mode{YType::enumeration, "mode"},
send_only{YType::empty, "send-only"}
{
yang_name = "authentication"; yang_parent_name = "default"; is_top_level_class = false; has_list_ancestor = true;
}
Native::Otv::Isis::Overlay::Default::Authentication::~Authentication()
{
}
bool Native::Otv::Isis::Overlay::Default::Authentication::has_data() const
{
if (is_presence_container) return true;
return key_chain.is_set
|| mode.is_set
|| send_only.is_set;
}
bool Native::Otv::Isis::Overlay::Default::Authentication::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(key_chain.yfilter)
|| ydk::is_set(mode.yfilter)
|| ydk::is_set(send_only.yfilter);
}
std::string Native::Otv::Isis::Overlay::Default::Authentication::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "authentication";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Isis::Overlay::Default::Authentication::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (key_chain.is_set || is_set(key_chain.yfilter)) leaf_name_data.push_back(key_chain.get_name_leafdata());
if (mode.is_set || is_set(mode.yfilter)) leaf_name_data.push_back(mode.get_name_leafdata());
if (send_only.is_set || is_set(send_only.yfilter)) leaf_name_data.push_back(send_only.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Isis::Overlay::Default::Authentication::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Isis::Overlay::Default::Authentication::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Otv::Isis::Overlay::Default::Authentication::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "key-chain")
{
key_chain = value;
key_chain.value_namespace = name_space;
key_chain.value_namespace_prefix = name_space_prefix;
}
if(value_path == "mode")
{
mode = value;
mode.value_namespace = name_space;
mode.value_namespace_prefix = name_space_prefix;
}
if(value_path == "send-only")
{
send_only = value;
send_only.value_namespace = name_space;
send_only.value_namespace_prefix = name_space_prefix;
}
}
void Native::Otv::Isis::Overlay::Default::Authentication::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "key-chain")
{
key_chain.yfilter = yfilter;
}
if(value_path == "mode")
{
mode.yfilter = yfilter;
}
if(value_path == "send-only")
{
send_only.yfilter = yfilter;
}
}
bool Native::Otv::Isis::Overlay::Default::Authentication::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "key-chain" || name == "mode" || name == "send-only")
return true;
return false;
}
Native::Otv::Isis::Overlay::Default::Hostname::Hostname()
:
dynamic{YType::empty, "dynamic"}
{
yang_name = "hostname"; yang_parent_name = "default"; is_top_level_class = false; has_list_ancestor = true;
}
Native::Otv::Isis::Overlay::Default::Hostname::~Hostname()
{
}
bool Native::Otv::Isis::Overlay::Default::Hostname::has_data() const
{
if (is_presence_container) return true;
return dynamic.is_set;
}
bool Native::Otv::Isis::Overlay::Default::Hostname::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(dynamic.yfilter);
}
std::string Native::Otv::Isis::Overlay::Default::Hostname::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "hostname";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Isis::Overlay::Default::Hostname::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (dynamic.is_set || is_set(dynamic.yfilter)) leaf_name_data.push_back(dynamic.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Isis::Overlay::Default::Hostname::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Isis::Overlay::Default::Hostname::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Otv::Isis::Overlay::Default::Hostname::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "dynamic")
{
dynamic = value;
dynamic.value_namespace = name_space;
dynamic.value_namespace_prefix = name_space_prefix;
}
}
void Native::Otv::Isis::Overlay::Default::Hostname::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "dynamic")
{
dynamic.yfilter = yfilter;
}
}
bool Native::Otv::Isis::Overlay::Default::Hostname::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "dynamic")
return true;
return false;
}
Native::Otv::Isis::Overlay::Default::Nsf::Nsf()
:
cisco{YType::empty, "cisco"},
interval{YType::empty, "interval"}
{
yang_name = "nsf"; yang_parent_name = "default"; is_top_level_class = false; has_list_ancestor = true;
}
Native::Otv::Isis::Overlay::Default::Nsf::~Nsf()
{
}
bool Native::Otv::Isis::Overlay::Default::Nsf::has_data() const
{
if (is_presence_container) return true;
return cisco.is_set
|| interval.is_set;
}
bool Native::Otv::Isis::Overlay::Default::Nsf::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(cisco.yfilter)
|| ydk::is_set(interval.yfilter);
}
std::string Native::Otv::Isis::Overlay::Default::Nsf::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "nsf";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Isis::Overlay::Default::Nsf::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (cisco.is_set || is_set(cisco.yfilter)) leaf_name_data.push_back(cisco.get_name_leafdata());
if (interval.is_set || is_set(interval.yfilter)) leaf_name_data.push_back(interval.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Isis::Overlay::Default::Nsf::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Isis::Overlay::Default::Nsf::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Otv::Isis::Overlay::Default::Nsf::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "cisco")
{
cisco = value;
cisco.value_namespace = name_space;
cisco.value_namespace_prefix = name_space_prefix;
}
if(value_path == "interval")
{
interval = value;
interval.value_namespace = name_space;
interval.value_namespace_prefix = name_space_prefix;
}
}
void Native::Otv::Isis::Overlay::Default::Nsf::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "cisco")
{
cisco.yfilter = yfilter;
}
if(value_path == "interval")
{
interval.yfilter = yfilter;
}
}
bool Native::Otv::Isis::Overlay::Default::Nsf::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "cisco" || name == "interval")
return true;
return false;
}
Native::Otv::Isis::Overlay::Default::Skeptical::Skeptical()
:
interval{YType::empty, "interval"}
{
yang_name = "skeptical"; yang_parent_name = "default"; is_top_level_class = false; has_list_ancestor = true;
}
Native::Otv::Isis::Overlay::Default::Skeptical::~Skeptical()
{
}
bool Native::Otv::Isis::Overlay::Default::Skeptical::has_data() const
{
if (is_presence_container) return true;
return interval.is_set;
}
bool Native::Otv::Isis::Overlay::Default::Skeptical::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(interval.yfilter);
}
std::string Native::Otv::Isis::Overlay::Default::Skeptical::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "skeptical";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Isis::Overlay::Default::Skeptical::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (interval.is_set || is_set(interval.yfilter)) leaf_name_data.push_back(interval.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Isis::Overlay::Default::Skeptical::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Isis::Overlay::Default::Skeptical::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Otv::Isis::Overlay::Default::Skeptical::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "interval")
{
interval = value;
interval.value_namespace = name_space;
interval.value_namespace_prefix = name_space_prefix;
}
}
void Native::Otv::Isis::Overlay::Default::Skeptical::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "interval")
{
interval.yfilter = yfilter;
}
}
bool Native::Otv::Isis::Overlay::Default::Skeptical::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "interval")
return true;
return false;
}
Native::Otv::Isis::Overlay::Hostname::Hostname()
:
dynamic{YType::empty, "dynamic"}
{
yang_name = "hostname"; yang_parent_name = "Overlay"; is_top_level_class = false; has_list_ancestor = true;
}
Native::Otv::Isis::Overlay::Hostname::~Hostname()
{
}
bool Native::Otv::Isis::Overlay::Hostname::has_data() const
{
if (is_presence_container) return true;
return dynamic.is_set;
}
bool Native::Otv::Isis::Overlay::Hostname::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(dynamic.yfilter);
}
std::string Native::Otv::Isis::Overlay::Hostname::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "hostname";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Isis::Overlay::Hostname::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (dynamic.is_set || is_set(dynamic.yfilter)) leaf_name_data.push_back(dynamic.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Isis::Overlay::Hostname::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Isis::Overlay::Hostname::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Otv::Isis::Overlay::Hostname::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "dynamic")
{
dynamic = value;
dynamic.value_namespace = name_space;
dynamic.value_namespace_prefix = name_space_prefix;
}
}
void Native::Otv::Isis::Overlay::Hostname::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "dynamic")
{
dynamic.yfilter = yfilter;
}
}
bool Native::Otv::Isis::Overlay::Hostname::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "dynamic")
return true;
return false;
}
Native::Otv::Isis::Overlay::LogAdjacencyChanges::LogAdjacencyChanges()
:
all{YType::empty, "all"}
{
yang_name = "log-adjacency-changes"; yang_parent_name = "Overlay"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true;
}
Native::Otv::Isis::Overlay::LogAdjacencyChanges::~LogAdjacencyChanges()
{
}
bool Native::Otv::Isis::Overlay::LogAdjacencyChanges::has_data() const
{
if (is_presence_container) return true;
return all.is_set;
}
bool Native::Otv::Isis::Overlay::LogAdjacencyChanges::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(all.yfilter);
}
std::string Native::Otv::Isis::Overlay::LogAdjacencyChanges::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "log-adjacency-changes";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Isis::Overlay::LogAdjacencyChanges::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (all.is_set || is_set(all.yfilter)) leaf_name_data.push_back(all.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Isis::Overlay::LogAdjacencyChanges::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Isis::Overlay::LogAdjacencyChanges::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Otv::Isis::Overlay::LogAdjacencyChanges::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "all")
{
all = value;
all.value_namespace = name_space;
all.value_namespace_prefix = name_space_prefix;
}
}
void Native::Otv::Isis::Overlay::LogAdjacencyChanges::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "all")
{
all.yfilter = yfilter;
}
}
bool Native::Otv::Isis::Overlay::LogAdjacencyChanges::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "all")
return true;
return false;
}
Native::Otv::Isis::Overlay::LspGenInterval::LspGenInterval()
:
seconds{YType::uint8, "seconds"},
milliseconds{YType::uint32, "milliseconds"},
wait{YType::uint32, "wait"}
{
yang_name = "lsp-gen-interval"; yang_parent_name = "Overlay"; is_top_level_class = false; has_list_ancestor = true;
}
Native::Otv::Isis::Overlay::LspGenInterval::~LspGenInterval()
{
}
bool Native::Otv::Isis::Overlay::LspGenInterval::has_data() const
{
if (is_presence_container) return true;
return seconds.is_set
|| milliseconds.is_set
|| wait.is_set;
}
bool Native::Otv::Isis::Overlay::LspGenInterval::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(seconds.yfilter)
|| ydk::is_set(milliseconds.yfilter)
|| ydk::is_set(wait.yfilter);
}
std::string Native::Otv::Isis::Overlay::LspGenInterval::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "lsp-gen-interval";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Isis::Overlay::LspGenInterval::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (seconds.is_set || is_set(seconds.yfilter)) leaf_name_data.push_back(seconds.get_name_leafdata());
if (milliseconds.is_set || is_set(milliseconds.yfilter)) leaf_name_data.push_back(milliseconds.get_name_leafdata());
if (wait.is_set || is_set(wait.yfilter)) leaf_name_data.push_back(wait.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Isis::Overlay::LspGenInterval::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Isis::Overlay::LspGenInterval::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Otv::Isis::Overlay::LspGenInterval::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "seconds")
{
seconds = value;
seconds.value_namespace = name_space;
seconds.value_namespace_prefix = name_space_prefix;
}
if(value_path == "milliseconds")
{
milliseconds = value;
milliseconds.value_namespace = name_space;
milliseconds.value_namespace_prefix = name_space_prefix;
}
if(value_path == "wait")
{
wait = value;
wait.value_namespace = name_space;
wait.value_namespace_prefix = name_space_prefix;
}
}
void Native::Otv::Isis::Overlay::LspGenInterval::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "seconds")
{
seconds.yfilter = yfilter;
}
if(value_path == "milliseconds")
{
milliseconds.yfilter = yfilter;
}
if(value_path == "wait")
{
wait.yfilter = yfilter;
}
}
bool Native::Otv::Isis::Overlay::LspGenInterval::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "seconds" || name == "milliseconds" || name == "wait")
return true;
return false;
}
Native::Otv::Isis::Overlay::Nsf::Nsf()
:
cisco{YType::empty, "cisco"},
interval{YType::uint32, "interval"}
{
yang_name = "nsf"; yang_parent_name = "Overlay"; is_top_level_class = false; has_list_ancestor = true;
}
Native::Otv::Isis::Overlay::Nsf::~Nsf()
{
}
bool Native::Otv::Isis::Overlay::Nsf::has_data() const
{
if (is_presence_container) return true;
return cisco.is_set
|| interval.is_set;
}
bool Native::Otv::Isis::Overlay::Nsf::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(cisco.yfilter)
|| ydk::is_set(interval.yfilter);
}
std::string Native::Otv::Isis::Overlay::Nsf::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "nsf";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Isis::Overlay::Nsf::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (cisco.is_set || is_set(cisco.yfilter)) leaf_name_data.push_back(cisco.get_name_leafdata());
if (interval.is_set || is_set(interval.yfilter)) leaf_name_data.push_back(interval.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Isis::Overlay::Nsf::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Isis::Overlay::Nsf::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Otv::Isis::Overlay::Nsf::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "cisco")
{
cisco = value;
cisco.value_namespace = name_space;
cisco.value_namespace_prefix = name_space_prefix;
}
if(value_path == "interval")
{
interval = value;
interval.value_namespace = name_space;
interval.value_namespace_prefix = name_space_prefix;
}
}
void Native::Otv::Isis::Overlay::Nsf::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "cisco")
{
cisco.yfilter = yfilter;
}
if(value_path == "interval")
{
interval.yfilter = yfilter;
}
}
bool Native::Otv::Isis::Overlay::Nsf::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "cisco" || name == "interval")
return true;
return false;
}
Native::Otv::Isis::Overlay::PrcInterval::PrcInterval()
:
seconds{YType::uint8, "seconds"},
milliseconds{YType::uint32, "milliseconds"},
wait{YType::uint32, "wait"}
{
yang_name = "prc-interval"; yang_parent_name = "Overlay"; is_top_level_class = false; has_list_ancestor = true;
}
Native::Otv::Isis::Overlay::PrcInterval::~PrcInterval()
{
}
bool Native::Otv::Isis::Overlay::PrcInterval::has_data() const
{
if (is_presence_container) return true;
return seconds.is_set
|| milliseconds.is_set
|| wait.is_set;
}
bool Native::Otv::Isis::Overlay::PrcInterval::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(seconds.yfilter)
|| ydk::is_set(milliseconds.yfilter)
|| ydk::is_set(wait.yfilter);
}
std::string Native::Otv::Isis::Overlay::PrcInterval::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "prc-interval";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Isis::Overlay::PrcInterval::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (seconds.is_set || is_set(seconds.yfilter)) leaf_name_data.push_back(seconds.get_name_leafdata());
if (milliseconds.is_set || is_set(milliseconds.yfilter)) leaf_name_data.push_back(milliseconds.get_name_leafdata());
if (wait.is_set || is_set(wait.yfilter)) leaf_name_data.push_back(wait.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Isis::Overlay::PrcInterval::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Isis::Overlay::PrcInterval::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Otv::Isis::Overlay::PrcInterval::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "seconds")
{
seconds = value;
seconds.value_namespace = name_space;
seconds.value_namespace_prefix = name_space_prefix;
}
if(value_path == "milliseconds")
{
milliseconds = value;
milliseconds.value_namespace = name_space;
milliseconds.value_namespace_prefix = name_space_prefix;
}
if(value_path == "wait")
{
wait = value;
wait.value_namespace = name_space;
wait.value_namespace_prefix = name_space_prefix;
}
}
void Native::Otv::Isis::Overlay::PrcInterval::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "seconds")
{
seconds.yfilter = yfilter;
}
if(value_path == "milliseconds")
{
milliseconds.yfilter = yfilter;
}
if(value_path == "wait")
{
wait.yfilter = yfilter;
}
}
bool Native::Otv::Isis::Overlay::PrcInterval::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "seconds" || name == "milliseconds" || name == "wait")
return true;
return false;
}
Native::Otv::Isis::Overlay::Skeptical::Skeptical()
:
interval{YType::uint32, "interval"}
{
yang_name = "skeptical"; yang_parent_name = "Overlay"; is_top_level_class = false; has_list_ancestor = true;
}
Native::Otv::Isis::Overlay::Skeptical::~Skeptical()
{
}
bool Native::Otv::Isis::Overlay::Skeptical::has_data() const
{
if (is_presence_container) return true;
return interval.is_set;
}
bool Native::Otv::Isis::Overlay::Skeptical::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(interval.yfilter);
}
std::string Native::Otv::Isis::Overlay::Skeptical::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "skeptical";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Isis::Overlay::Skeptical::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (interval.is_set || is_set(interval.yfilter)) leaf_name_data.push_back(interval.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Isis::Overlay::Skeptical::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Isis::Overlay::Skeptical::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Otv::Isis::Overlay::Skeptical::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "interval")
{
interval = value;
interval.value_namespace = name_space;
interval.value_namespace_prefix = name_space_prefix;
}
}
void Native::Otv::Isis::Overlay::Skeptical::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "interval")
{
interval.yfilter = yfilter;
}
}
bool Native::Otv::Isis::Overlay::Skeptical::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "interval")
return true;
return false;
}
Native::Otv::Isis::Overlay::SpfInterval::SpfInterval()
:
seconds{YType::uint8, "seconds"},
milliseconds{YType::uint32, "milliseconds"},
wait{YType::uint32, "wait"}
{
yang_name = "spf-interval"; yang_parent_name = "Overlay"; is_top_level_class = false; has_list_ancestor = true;
}
Native::Otv::Isis::Overlay::SpfInterval::~SpfInterval()
{
}
bool Native::Otv::Isis::Overlay::SpfInterval::has_data() const
{
if (is_presence_container) return true;
return seconds.is_set
|| milliseconds.is_set
|| wait.is_set;
}
bool Native::Otv::Isis::Overlay::SpfInterval::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(seconds.yfilter)
|| ydk::is_set(milliseconds.yfilter)
|| ydk::is_set(wait.yfilter);
}
std::string Native::Otv::Isis::Overlay::SpfInterval::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "spf-interval";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Isis::Overlay::SpfInterval::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (seconds.is_set || is_set(seconds.yfilter)) leaf_name_data.push_back(seconds.get_name_leafdata());
if (milliseconds.is_set || is_set(milliseconds.yfilter)) leaf_name_data.push_back(milliseconds.get_name_leafdata());
if (wait.is_set || is_set(wait.yfilter)) leaf_name_data.push_back(wait.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Isis::Overlay::SpfInterval::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Isis::Overlay::SpfInterval::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Otv::Isis::Overlay::SpfInterval::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "seconds")
{
seconds = value;
seconds.value_namespace = name_space;
seconds.value_namespace_prefix = name_space_prefix;
}
if(value_path == "milliseconds")
{
milliseconds = value;
milliseconds.value_namespace = name_space;
milliseconds.value_namespace_prefix = name_space_prefix;
}
if(value_path == "wait")
{
wait = value;
wait.value_namespace = name_space;
wait.value_namespace_prefix = name_space_prefix;
}
}
void Native::Otv::Isis::Overlay::SpfInterval::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "seconds")
{
seconds.yfilter = yfilter;
}
if(value_path == "milliseconds")
{
milliseconds.yfilter = yfilter;
}
if(value_path == "wait")
{
wait.yfilter = yfilter;
}
}
bool Native::Otv::Isis::Overlay::SpfInterval::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "seconds" || name == "milliseconds" || name == "wait")
return true;
return false;
}
Native::Otv::Isis::Site::Site()
:
net{YType::str, "net"}
,
default_(std::make_shared<Native::Otv::Isis::Site::Default>())
, log_adjacency_changes(nullptr) // presence node
, skeptical(std::make_shared<Native::Otv::Isis::Site::Skeptical>())
{
default_->parent = this;
skeptical->parent = this;
yang_name = "site"; yang_parent_name = "isis"; is_top_level_class = false; has_list_ancestor = false;
}
Native::Otv::Isis::Site::~Site()
{
}
bool Native::Otv::Isis::Site::has_data() const
{
if (is_presence_container) return true;
return net.is_set
|| (default_ != nullptr && default_->has_data())
|| (log_adjacency_changes != nullptr && log_adjacency_changes->has_data())
|| (skeptical != nullptr && skeptical->has_data());
}
bool Native::Otv::Isis::Site::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(net.yfilter)
|| (default_ != nullptr && default_->has_operation())
|| (log_adjacency_changes != nullptr && log_adjacency_changes->has_operation())
|| (skeptical != nullptr && skeptical->has_operation());
}
std::string Native::Otv::Isis::Site::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/otv/Cisco-IOS-XE-otv:isis/" << get_segment_path();
return path_buffer.str();
}
std::string Native::Otv::Isis::Site::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "site";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Isis::Site::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (net.is_set || is_set(net.yfilter)) leaf_name_data.push_back(net.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Isis::Site::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "default")
{
if(default_ == nullptr)
{
default_ = std::make_shared<Native::Otv::Isis::Site::Default>();
}
return default_;
}
if(child_yang_name == "log-adjacency-changes")
{
if(log_adjacency_changes == nullptr)
{
log_adjacency_changes = std::make_shared<Native::Otv::Isis::Site::LogAdjacencyChanges>();
}
return log_adjacency_changes;
}
if(child_yang_name == "skeptical")
{
if(skeptical == nullptr)
{
skeptical = std::make_shared<Native::Otv::Isis::Site::Skeptical>();
}
return skeptical;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Isis::Site::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(default_ != nullptr)
{
_children["default"] = default_;
}
if(log_adjacency_changes != nullptr)
{
_children["log-adjacency-changes"] = log_adjacency_changes;
}
if(skeptical != nullptr)
{
_children["skeptical"] = skeptical;
}
return _children;
}
void Native::Otv::Isis::Site::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "net")
{
net = value;
net.value_namespace = name_space;
net.value_namespace_prefix = name_space_prefix;
}
}
void Native::Otv::Isis::Site::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "net")
{
net.yfilter = yfilter;
}
}
bool Native::Otv::Isis::Site::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "default" || name == "log-adjacency-changes" || name == "skeptical" || name == "net")
return true;
return false;
}
Native::Otv::Isis::Site::Default::Default()
:
log_adjacency_changes{YType::empty, "log-adjacency-changes"},
net{YType::empty, "net"}
,
skeptical(std::make_shared<Native::Otv::Isis::Site::Default::Skeptical>())
{
skeptical->parent = this;
yang_name = "default"; yang_parent_name = "site"; is_top_level_class = false; has_list_ancestor = false;
}
Native::Otv::Isis::Site::Default::~Default()
{
}
bool Native::Otv::Isis::Site::Default::has_data() const
{
if (is_presence_container) return true;
return log_adjacency_changes.is_set
|| net.is_set
|| (skeptical != nullptr && skeptical->has_data());
}
bool Native::Otv::Isis::Site::Default::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(log_adjacency_changes.yfilter)
|| ydk::is_set(net.yfilter)
|| (skeptical != nullptr && skeptical->has_operation());
}
std::string Native::Otv::Isis::Site::Default::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/otv/Cisco-IOS-XE-otv:isis/site/" << get_segment_path();
return path_buffer.str();
}
std::string Native::Otv::Isis::Site::Default::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "default";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Isis::Site::Default::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (log_adjacency_changes.is_set || is_set(log_adjacency_changes.yfilter)) leaf_name_data.push_back(log_adjacency_changes.get_name_leafdata());
if (net.is_set || is_set(net.yfilter)) leaf_name_data.push_back(net.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Isis::Site::Default::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "skeptical")
{
if(skeptical == nullptr)
{
skeptical = std::make_shared<Native::Otv::Isis::Site::Default::Skeptical>();
}
return skeptical;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Isis::Site::Default::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(skeptical != nullptr)
{
_children["skeptical"] = skeptical;
}
return _children;
}
void Native::Otv::Isis::Site::Default::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "log-adjacency-changes")
{
log_adjacency_changes = value;
log_adjacency_changes.value_namespace = name_space;
log_adjacency_changes.value_namespace_prefix = name_space_prefix;
}
if(value_path == "net")
{
net = value;
net.value_namespace = name_space;
net.value_namespace_prefix = name_space_prefix;
}
}
void Native::Otv::Isis::Site::Default::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "log-adjacency-changes")
{
log_adjacency_changes.yfilter = yfilter;
}
if(value_path == "net")
{
net.yfilter = yfilter;
}
}
bool Native::Otv::Isis::Site::Default::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "skeptical" || name == "log-adjacency-changes" || name == "net")
return true;
return false;
}
Native::Otv::Isis::Site::Default::Skeptical::Skeptical()
:
interval{YType::empty, "interval"}
{
yang_name = "skeptical"; yang_parent_name = "default"; is_top_level_class = false; has_list_ancestor = false;
}
Native::Otv::Isis::Site::Default::Skeptical::~Skeptical()
{
}
bool Native::Otv::Isis::Site::Default::Skeptical::has_data() const
{
if (is_presence_container) return true;
return interval.is_set;
}
bool Native::Otv::Isis::Site::Default::Skeptical::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(interval.yfilter);
}
std::string Native::Otv::Isis::Site::Default::Skeptical::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/otv/Cisco-IOS-XE-otv:isis/site/default/" << get_segment_path();
return path_buffer.str();
}
std::string Native::Otv::Isis::Site::Default::Skeptical::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "skeptical";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Isis::Site::Default::Skeptical::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (interval.is_set || is_set(interval.yfilter)) leaf_name_data.push_back(interval.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Isis::Site::Default::Skeptical::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Isis::Site::Default::Skeptical::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Otv::Isis::Site::Default::Skeptical::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "interval")
{
interval = value;
interval.value_namespace = name_space;
interval.value_namespace_prefix = name_space_prefix;
}
}
void Native::Otv::Isis::Site::Default::Skeptical::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "interval")
{
interval.yfilter = yfilter;
}
}
bool Native::Otv::Isis::Site::Default::Skeptical::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "interval")
return true;
return false;
}
Native::Otv::Isis::Site::LogAdjacencyChanges::LogAdjacencyChanges()
:
all{YType::empty, "all"}
{
yang_name = "log-adjacency-changes"; yang_parent_name = "site"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true;
}
Native::Otv::Isis::Site::LogAdjacencyChanges::~LogAdjacencyChanges()
{
}
bool Native::Otv::Isis::Site::LogAdjacencyChanges::has_data() const
{
if (is_presence_container) return true;
return all.is_set;
}
bool Native::Otv::Isis::Site::LogAdjacencyChanges::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(all.yfilter);
}
std::string Native::Otv::Isis::Site::LogAdjacencyChanges::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/otv/Cisco-IOS-XE-otv:isis/site/" << get_segment_path();
return path_buffer.str();
}
std::string Native::Otv::Isis::Site::LogAdjacencyChanges::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "log-adjacency-changes";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Isis::Site::LogAdjacencyChanges::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (all.is_set || is_set(all.yfilter)) leaf_name_data.push_back(all.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Isis::Site::LogAdjacencyChanges::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Isis::Site::LogAdjacencyChanges::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Otv::Isis::Site::LogAdjacencyChanges::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "all")
{
all = value;
all.value_namespace = name_space;
all.value_namespace_prefix = name_space_prefix;
}
}
void Native::Otv::Isis::Site::LogAdjacencyChanges::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "all")
{
all.yfilter = yfilter;
}
}
bool Native::Otv::Isis::Site::LogAdjacencyChanges::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "all")
return true;
return false;
}
Native::Otv::Isis::Site::Skeptical::Skeptical()
:
interval{YType::uint32, "interval"}
{
yang_name = "skeptical"; yang_parent_name = "site"; is_top_level_class = false; has_list_ancestor = false;
}
Native::Otv::Isis::Site::Skeptical::~Skeptical()
{
}
bool Native::Otv::Isis::Site::Skeptical::has_data() const
{
if (is_presence_container) return true;
return interval.is_set;
}
bool Native::Otv::Isis::Site::Skeptical::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(interval.yfilter);
}
std::string Native::Otv::Isis::Site::Skeptical::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/otv/Cisco-IOS-XE-otv:isis/site/" << get_segment_path();
return path_buffer.str();
}
std::string Native::Otv::Isis::Site::Skeptical::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "skeptical";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Isis::Site::Skeptical::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (interval.is_set || is_set(interval.yfilter)) leaf_name_data.push_back(interval.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Isis::Site::Skeptical::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Isis::Site::Skeptical::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Otv::Isis::Site::Skeptical::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "interval")
{
interval = value;
interval.value_namespace = name_space;
interval.value_namespace_prefix = name_space_prefix;
}
}
void Native::Otv::Isis::Site::Skeptical::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "interval")
{
interval.yfilter = yfilter;
}
}
bool Native::Otv::Isis::Site::Skeptical::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "interval")
return true;
return false;
}
Native::Otv::Site::Site()
:
bridge_domain{YType::uint16, "bridge-domain"}
,
default_(std::make_shared<Native::Otv::Site::Default>())
, otv(std::make_shared<Native::Otv::Site::Otv_>())
{
default_->parent = this;
otv->parent = this;
yang_name = "site"; yang_parent_name = "otv"; is_top_level_class = false; has_list_ancestor = false;
}
Native::Otv::Site::~Site()
{
}
bool Native::Otv::Site::has_data() const
{
if (is_presence_container) return true;
return bridge_domain.is_set
|| (default_ != nullptr && default_->has_data())
|| (otv != nullptr && otv->has_data());
}
bool Native::Otv::Site::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(bridge_domain.yfilter)
|| (default_ != nullptr && default_->has_operation())
|| (otv != nullptr && otv->has_operation());
}
std::string Native::Otv::Site::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/otv/" << get_segment_path();
return path_buffer.str();
}
std::string Native::Otv::Site::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-otv:site";
ADD_KEY_TOKEN(bridge_domain, "bridge-domain");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Site::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (bridge_domain.is_set || is_set(bridge_domain.yfilter)) leaf_name_data.push_back(bridge_domain.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Site::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "default")
{
if(default_ == nullptr)
{
default_ = std::make_shared<Native::Otv::Site::Default>();
}
return default_;
}
if(child_yang_name == "otv")
{
if(otv == nullptr)
{
otv = std::make_shared<Native::Otv::Site::Otv_>();
}
return otv;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Site::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(default_ != nullptr)
{
_children["default"] = default_;
}
if(otv != nullptr)
{
_children["otv"] = otv;
}
return _children;
}
void Native::Otv::Site::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "bridge-domain")
{
bridge_domain = value;
bridge_domain.value_namespace = name_space;
bridge_domain.value_namespace_prefix = name_space_prefix;
}
}
void Native::Otv::Site::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "bridge-domain")
{
bridge_domain.yfilter = yfilter;
}
}
bool Native::Otv::Site::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "default" || name == "otv" || name == "bridge-domain")
return true;
return false;
}
Native::Otv::Site::Default::Default()
:
otv(std::make_shared<Native::Otv::Site::Default::Otv_>())
{
otv->parent = this;
yang_name = "default"; yang_parent_name = "site"; is_top_level_class = false; has_list_ancestor = true;
}
Native::Otv::Site::Default::~Default()
{
}
bool Native::Otv::Site::Default::has_data() const
{
if (is_presence_container) return true;
return (otv != nullptr && otv->has_data());
}
bool Native::Otv::Site::Default::has_operation() const
{
return is_set(yfilter)
|| (otv != nullptr && otv->has_operation());
}
std::string Native::Otv::Site::Default::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "default";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Site::Default::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Site::Default::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "otv")
{
if(otv == nullptr)
{
otv = std::make_shared<Native::Otv::Site::Default::Otv_>();
}
return otv;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Site::Default::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(otv != nullptr)
{
_children["otv"] = otv;
}
return _children;
}
void Native::Otv::Site::Default::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::Otv::Site::Default::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::Otv::Site::Default::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "otv")
return true;
return false;
}
Native::Otv::Site::Default::Otv_::Otv_()
:
isis(std::make_shared<Native::Otv::Site::Default::Otv_::Isis>())
{
isis->parent = this;
yang_name = "otv"; yang_parent_name = "default"; is_top_level_class = false; has_list_ancestor = true;
}
Native::Otv::Site::Default::Otv_::~Otv_()
{
}
bool Native::Otv::Site::Default::Otv_::has_data() const
{
if (is_presence_container) return true;
return (isis != nullptr && isis->has_data());
}
bool Native::Otv::Site::Default::Otv_::has_operation() const
{
return is_set(yfilter)
|| (isis != nullptr && isis->has_operation());
}
std::string Native::Otv::Site::Default::Otv_::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "otv";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Site::Default::Otv_::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Site::Default::Otv_::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "isis")
{
if(isis == nullptr)
{
isis = std::make_shared<Native::Otv::Site::Default::Otv_::Isis>();
}
return isis;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Site::Default::Otv_::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(isis != nullptr)
{
_children["isis"] = isis;
}
return _children;
}
void Native::Otv::Site::Default::Otv_::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::Otv::Site::Default::Otv_::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::Otv::Site::Default::Otv_::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "isis")
return true;
return false;
}
Native::Otv::Site::Default::Otv_::Isis::Isis()
:
bfd{YType::empty, "bfd"},
hello_multiplier{YType::uint16, "hello-multiplier"},
priority{YType::uint8, "priority"}
,
authentication(std::make_shared<Native::Otv::Site::Default::Otv_::Isis::Authentication>())
, hello(std::make_shared<Native::Otv::Site::Default::Otv_::Isis::Hello>())
, hello_interval(std::make_shared<Native::Otv::Site::Default::Otv_::Isis::HelloInterval>())
{
authentication->parent = this;
hello->parent = this;
hello_interval->parent = this;
yang_name = "isis"; yang_parent_name = "otv"; is_top_level_class = false; has_list_ancestor = true;
}
Native::Otv::Site::Default::Otv_::Isis::~Isis()
{
}
bool Native::Otv::Site::Default::Otv_::Isis::has_data() const
{
if (is_presence_container) return true;
return bfd.is_set
|| hello_multiplier.is_set
|| priority.is_set
|| (authentication != nullptr && authentication->has_data())
|| (hello != nullptr && hello->has_data())
|| (hello_interval != nullptr && hello_interval->has_data());
}
bool Native::Otv::Site::Default::Otv_::Isis::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(bfd.yfilter)
|| ydk::is_set(hello_multiplier.yfilter)
|| ydk::is_set(priority.yfilter)
|| (authentication != nullptr && authentication->has_operation())
|| (hello != nullptr && hello->has_operation())
|| (hello_interval != nullptr && hello_interval->has_operation());
}
std::string Native::Otv::Site::Default::Otv_::Isis::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "isis";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Site::Default::Otv_::Isis::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (bfd.is_set || is_set(bfd.yfilter)) leaf_name_data.push_back(bfd.get_name_leafdata());
if (hello_multiplier.is_set || is_set(hello_multiplier.yfilter)) leaf_name_data.push_back(hello_multiplier.get_name_leafdata());
if (priority.is_set || is_set(priority.yfilter)) leaf_name_data.push_back(priority.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Site::Default::Otv_::Isis::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "authentication")
{
if(authentication == nullptr)
{
authentication = std::make_shared<Native::Otv::Site::Default::Otv_::Isis::Authentication>();
}
return authentication;
}
if(child_yang_name == "hello")
{
if(hello == nullptr)
{
hello = std::make_shared<Native::Otv::Site::Default::Otv_::Isis::Hello>();
}
return hello;
}
if(child_yang_name == "hello-interval")
{
if(hello_interval == nullptr)
{
hello_interval = std::make_shared<Native::Otv::Site::Default::Otv_::Isis::HelloInterval>();
}
return hello_interval;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Site::Default::Otv_::Isis::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(authentication != nullptr)
{
_children["authentication"] = authentication;
}
if(hello != nullptr)
{
_children["hello"] = hello;
}
if(hello_interval != nullptr)
{
_children["hello-interval"] = hello_interval;
}
return _children;
}
void Native::Otv::Site::Default::Otv_::Isis::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "bfd")
{
bfd = value;
bfd.value_namespace = name_space;
bfd.value_namespace_prefix = name_space_prefix;
}
if(value_path == "hello-multiplier")
{
hello_multiplier = value;
hello_multiplier.value_namespace = name_space;
hello_multiplier.value_namespace_prefix = name_space_prefix;
}
if(value_path == "priority")
{
priority = value;
priority.value_namespace = name_space;
priority.value_namespace_prefix = name_space_prefix;
}
}
void Native::Otv::Site::Default::Otv_::Isis::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "bfd")
{
bfd.yfilter = yfilter;
}
if(value_path == "hello-multiplier")
{
hello_multiplier.yfilter = yfilter;
}
if(value_path == "priority")
{
priority.yfilter = yfilter;
}
}
bool Native::Otv::Site::Default::Otv_::Isis::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "authentication" || name == "hello" || name == "hello-interval" || name == "bfd" || name == "hello-multiplier" || name == "priority")
return true;
return false;
}
Native::Otv::Site::Default::Otv_::Isis::Authentication::Authentication()
:
key_chain{YType::str, "key-chain"},
mode{YType::enumeration, "mode"},
send_only{YType::empty, "send-only"}
{
yang_name = "authentication"; yang_parent_name = "isis"; is_top_level_class = false; has_list_ancestor = true;
}
Native::Otv::Site::Default::Otv_::Isis::Authentication::~Authentication()
{
}
bool Native::Otv::Site::Default::Otv_::Isis::Authentication::has_data() const
{
if (is_presence_container) return true;
return key_chain.is_set
|| mode.is_set
|| send_only.is_set;
}
bool Native::Otv::Site::Default::Otv_::Isis::Authentication::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(key_chain.yfilter)
|| ydk::is_set(mode.yfilter)
|| ydk::is_set(send_only.yfilter);
}
std::string Native::Otv::Site::Default::Otv_::Isis::Authentication::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "authentication";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Site::Default::Otv_::Isis::Authentication::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (key_chain.is_set || is_set(key_chain.yfilter)) leaf_name_data.push_back(key_chain.get_name_leafdata());
if (mode.is_set || is_set(mode.yfilter)) leaf_name_data.push_back(mode.get_name_leafdata());
if (send_only.is_set || is_set(send_only.yfilter)) leaf_name_data.push_back(send_only.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Site::Default::Otv_::Isis::Authentication::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Site::Default::Otv_::Isis::Authentication::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Otv::Site::Default::Otv_::Isis::Authentication::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "key-chain")
{
key_chain = value;
key_chain.value_namespace = name_space;
key_chain.value_namespace_prefix = name_space_prefix;
}
if(value_path == "mode")
{
mode = value;
mode.value_namespace = name_space;
mode.value_namespace_prefix = name_space_prefix;
}
if(value_path == "send-only")
{
send_only = value;
send_only.value_namespace = name_space;
send_only.value_namespace_prefix = name_space_prefix;
}
}
void Native::Otv::Site::Default::Otv_::Isis::Authentication::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "key-chain")
{
key_chain.yfilter = yfilter;
}
if(value_path == "mode")
{
mode.yfilter = yfilter;
}
if(value_path == "send-only")
{
send_only.yfilter = yfilter;
}
}
bool Native::Otv::Site::Default::Otv_::Isis::Authentication::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "key-chain" || name == "mode" || name == "send-only")
return true;
return false;
}
Native::Otv::Site::Default::Otv_::Isis::Hello::Hello()
:
padding(nullptr) // presence node
{
yang_name = "hello"; yang_parent_name = "isis"; is_top_level_class = false; has_list_ancestor = true;
}
Native::Otv::Site::Default::Otv_::Isis::Hello::~Hello()
{
}
bool Native::Otv::Site::Default::Otv_::Isis::Hello::has_data() const
{
if (is_presence_container) return true;
return (padding != nullptr && padding->has_data());
}
bool Native::Otv::Site::Default::Otv_::Isis::Hello::has_operation() const
{
return is_set(yfilter)
|| (padding != nullptr && padding->has_operation());
}
std::string Native::Otv::Site::Default::Otv_::Isis::Hello::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "hello";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Site::Default::Otv_::Isis::Hello::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Site::Default::Otv_::Isis::Hello::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "padding")
{
if(padding == nullptr)
{
padding = std::make_shared<Native::Otv::Site::Default::Otv_::Isis::Hello::Padding>();
}
return padding;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Site::Default::Otv_::Isis::Hello::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(padding != nullptr)
{
_children["padding"] = padding;
}
return _children;
}
void Native::Otv::Site::Default::Otv_::Isis::Hello::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::Otv::Site::Default::Otv_::Isis::Hello::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::Otv::Site::Default::Otv_::Isis::Hello::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "padding")
return true;
return false;
}
Native::Otv::Site::Default::Otv_::Isis::Hello::Padding::Padding()
:
always{YType::empty, "always"}
{
yang_name = "padding"; yang_parent_name = "hello"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true;
}
Native::Otv::Site::Default::Otv_::Isis::Hello::Padding::~Padding()
{
}
bool Native::Otv::Site::Default::Otv_::Isis::Hello::Padding::has_data() const
{
if (is_presence_container) return true;
return always.is_set;
}
bool Native::Otv::Site::Default::Otv_::Isis::Hello::Padding::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(always.yfilter);
}
std::string Native::Otv::Site::Default::Otv_::Isis::Hello::Padding::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "padding";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Site::Default::Otv_::Isis::Hello::Padding::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (always.is_set || is_set(always.yfilter)) leaf_name_data.push_back(always.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Site::Default::Otv_::Isis::Hello::Padding::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Site::Default::Otv_::Isis::Hello::Padding::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Otv::Site::Default::Otv_::Isis::Hello::Padding::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "always")
{
always = value;
always.value_namespace = name_space;
always.value_namespace_prefix = name_space_prefix;
}
}
void Native::Otv::Site::Default::Otv_::Isis::Hello::Padding::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "always")
{
always.yfilter = yfilter;
}
}
bool Native::Otv::Site::Default::Otv_::Isis::Hello::Padding::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "always")
return true;
return false;
}
Native::Otv::Site::Default::Otv_::Isis::HelloInterval::HelloInterval()
:
value_{YType::uint16, "value"},
minimal{YType::empty, "minimal"}
{
yang_name = "hello-interval"; yang_parent_name = "isis"; is_top_level_class = false; has_list_ancestor = true;
}
Native::Otv::Site::Default::Otv_::Isis::HelloInterval::~HelloInterval()
{
}
bool Native::Otv::Site::Default::Otv_::Isis::HelloInterval::has_data() const
{
if (is_presence_container) return true;
return value_.is_set
|| minimal.is_set;
}
bool Native::Otv::Site::Default::Otv_::Isis::HelloInterval::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(value_.yfilter)
|| ydk::is_set(minimal.yfilter);
}
std::string Native::Otv::Site::Default::Otv_::Isis::HelloInterval::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "hello-interval";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Site::Default::Otv_::Isis::HelloInterval::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (value_.is_set || is_set(value_.yfilter)) leaf_name_data.push_back(value_.get_name_leafdata());
if (minimal.is_set || is_set(minimal.yfilter)) leaf_name_data.push_back(minimal.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Site::Default::Otv_::Isis::HelloInterval::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Site::Default::Otv_::Isis::HelloInterval::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Otv::Site::Default::Otv_::Isis::HelloInterval::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "value")
{
value_ = value;
value_.value_namespace = name_space;
value_.value_namespace_prefix = name_space_prefix;
}
if(value_path == "minimal")
{
minimal = value;
minimal.value_namespace = name_space;
minimal.value_namespace_prefix = name_space_prefix;
}
}
void Native::Otv::Site::Default::Otv_::Isis::HelloInterval::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "value")
{
value_.yfilter = yfilter;
}
if(value_path == "minimal")
{
minimal.yfilter = yfilter;
}
}
bool Native::Otv::Site::Default::Otv_::Isis::HelloInterval::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "value" || name == "minimal")
return true;
return false;
}
Native::Otv::Site::Otv_::Otv_()
:
isis(std::make_shared<Native::Otv::Site::Otv_::Isis>())
{
isis->parent = this;
yang_name = "otv"; yang_parent_name = "site"; is_top_level_class = false; has_list_ancestor = true;
}
Native::Otv::Site::Otv_::~Otv_()
{
}
bool Native::Otv::Site::Otv_::has_data() const
{
if (is_presence_container) return true;
return (isis != nullptr && isis->has_data());
}
bool Native::Otv::Site::Otv_::has_operation() const
{
return is_set(yfilter)
|| (isis != nullptr && isis->has_operation());
}
std::string Native::Otv::Site::Otv_::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "otv";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Site::Otv_::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Site::Otv_::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "isis")
{
if(isis == nullptr)
{
isis = std::make_shared<Native::Otv::Site::Otv_::Isis>();
}
return isis;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Site::Otv_::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(isis != nullptr)
{
_children["isis"] = isis;
}
return _children;
}
void Native::Otv::Site::Otv_::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::Otv::Site::Otv_::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::Otv::Site::Otv_::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "isis")
return true;
return false;
}
Native::Otv::Site::Otv_::Isis::Isis()
:
bfd{YType::empty, "bfd"},
hello_multiplier{YType::uint16, "hello-multiplier"},
priority{YType::uint8, "priority"}
,
authentication(std::make_shared<Native::Otv::Site::Otv_::Isis::Authentication>())
, hello(std::make_shared<Native::Otv::Site::Otv_::Isis::Hello>())
, hello_interval(std::make_shared<Native::Otv::Site::Otv_::Isis::HelloInterval>())
{
authentication->parent = this;
hello->parent = this;
hello_interval->parent = this;
yang_name = "isis"; yang_parent_name = "otv"; is_top_level_class = false; has_list_ancestor = true;
}
Native::Otv::Site::Otv_::Isis::~Isis()
{
}
bool Native::Otv::Site::Otv_::Isis::has_data() const
{
if (is_presence_container) return true;
return bfd.is_set
|| hello_multiplier.is_set
|| priority.is_set
|| (authentication != nullptr && authentication->has_data())
|| (hello != nullptr && hello->has_data())
|| (hello_interval != nullptr && hello_interval->has_data());
}
bool Native::Otv::Site::Otv_::Isis::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(bfd.yfilter)
|| ydk::is_set(hello_multiplier.yfilter)
|| ydk::is_set(priority.yfilter)
|| (authentication != nullptr && authentication->has_operation())
|| (hello != nullptr && hello->has_operation())
|| (hello_interval != nullptr && hello_interval->has_operation());
}
std::string Native::Otv::Site::Otv_::Isis::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "isis";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Site::Otv_::Isis::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (bfd.is_set || is_set(bfd.yfilter)) leaf_name_data.push_back(bfd.get_name_leafdata());
if (hello_multiplier.is_set || is_set(hello_multiplier.yfilter)) leaf_name_data.push_back(hello_multiplier.get_name_leafdata());
if (priority.is_set || is_set(priority.yfilter)) leaf_name_data.push_back(priority.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Site::Otv_::Isis::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "authentication")
{
if(authentication == nullptr)
{
authentication = std::make_shared<Native::Otv::Site::Otv_::Isis::Authentication>();
}
return authentication;
}
if(child_yang_name == "hello")
{
if(hello == nullptr)
{
hello = std::make_shared<Native::Otv::Site::Otv_::Isis::Hello>();
}
return hello;
}
if(child_yang_name == "hello-interval")
{
if(hello_interval == nullptr)
{
hello_interval = std::make_shared<Native::Otv::Site::Otv_::Isis::HelloInterval>();
}
return hello_interval;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Site::Otv_::Isis::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(authentication != nullptr)
{
_children["authentication"] = authentication;
}
if(hello != nullptr)
{
_children["hello"] = hello;
}
if(hello_interval != nullptr)
{
_children["hello-interval"] = hello_interval;
}
return _children;
}
void Native::Otv::Site::Otv_::Isis::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "bfd")
{
bfd = value;
bfd.value_namespace = name_space;
bfd.value_namespace_prefix = name_space_prefix;
}
if(value_path == "hello-multiplier")
{
hello_multiplier = value;
hello_multiplier.value_namespace = name_space;
hello_multiplier.value_namespace_prefix = name_space_prefix;
}
if(value_path == "priority")
{
priority = value;
priority.value_namespace = name_space;
priority.value_namespace_prefix = name_space_prefix;
}
}
void Native::Otv::Site::Otv_::Isis::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "bfd")
{
bfd.yfilter = yfilter;
}
if(value_path == "hello-multiplier")
{
hello_multiplier.yfilter = yfilter;
}
if(value_path == "priority")
{
priority.yfilter = yfilter;
}
}
bool Native::Otv::Site::Otv_::Isis::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "authentication" || name == "hello" || name == "hello-interval" || name == "bfd" || name == "hello-multiplier" || name == "priority")
return true;
return false;
}
Native::Otv::Site::Otv_::Isis::Authentication::Authentication()
:
key_chain{YType::str, "key-chain"},
mode{YType::enumeration, "mode"},
send_only{YType::empty, "send-only"}
{
yang_name = "authentication"; yang_parent_name = "isis"; is_top_level_class = false; has_list_ancestor = true;
}
Native::Otv::Site::Otv_::Isis::Authentication::~Authentication()
{
}
bool Native::Otv::Site::Otv_::Isis::Authentication::has_data() const
{
if (is_presence_container) return true;
return key_chain.is_set
|| mode.is_set
|| send_only.is_set;
}
bool Native::Otv::Site::Otv_::Isis::Authentication::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(key_chain.yfilter)
|| ydk::is_set(mode.yfilter)
|| ydk::is_set(send_only.yfilter);
}
std::string Native::Otv::Site::Otv_::Isis::Authentication::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "authentication";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Site::Otv_::Isis::Authentication::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (key_chain.is_set || is_set(key_chain.yfilter)) leaf_name_data.push_back(key_chain.get_name_leafdata());
if (mode.is_set || is_set(mode.yfilter)) leaf_name_data.push_back(mode.get_name_leafdata());
if (send_only.is_set || is_set(send_only.yfilter)) leaf_name_data.push_back(send_only.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Site::Otv_::Isis::Authentication::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Site::Otv_::Isis::Authentication::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Otv::Site::Otv_::Isis::Authentication::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "key-chain")
{
key_chain = value;
key_chain.value_namespace = name_space;
key_chain.value_namespace_prefix = name_space_prefix;
}
if(value_path == "mode")
{
mode = value;
mode.value_namespace = name_space;
mode.value_namespace_prefix = name_space_prefix;
}
if(value_path == "send-only")
{
send_only = value;
send_only.value_namespace = name_space;
send_only.value_namespace_prefix = name_space_prefix;
}
}
void Native::Otv::Site::Otv_::Isis::Authentication::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "key-chain")
{
key_chain.yfilter = yfilter;
}
if(value_path == "mode")
{
mode.yfilter = yfilter;
}
if(value_path == "send-only")
{
send_only.yfilter = yfilter;
}
}
bool Native::Otv::Site::Otv_::Isis::Authentication::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "key-chain" || name == "mode" || name == "send-only")
return true;
return false;
}
Native::Otv::Site::Otv_::Isis::Hello::Hello()
:
padding(nullptr) // presence node
{
yang_name = "hello"; yang_parent_name = "isis"; is_top_level_class = false; has_list_ancestor = true;
}
Native::Otv::Site::Otv_::Isis::Hello::~Hello()
{
}
bool Native::Otv::Site::Otv_::Isis::Hello::has_data() const
{
if (is_presence_container) return true;
return (padding != nullptr && padding->has_data());
}
bool Native::Otv::Site::Otv_::Isis::Hello::has_operation() const
{
return is_set(yfilter)
|| (padding != nullptr && padding->has_operation());
}
std::string Native::Otv::Site::Otv_::Isis::Hello::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "hello";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Site::Otv_::Isis::Hello::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Site::Otv_::Isis::Hello::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "padding")
{
if(padding == nullptr)
{
padding = std::make_shared<Native::Otv::Site::Otv_::Isis::Hello::Padding>();
}
return padding;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Site::Otv_::Isis::Hello::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(padding != nullptr)
{
_children["padding"] = padding;
}
return _children;
}
void Native::Otv::Site::Otv_::Isis::Hello::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::Otv::Site::Otv_::Isis::Hello::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::Otv::Site::Otv_::Isis::Hello::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "padding")
return true;
return false;
}
Native::Otv::Site::Otv_::Isis::Hello::Padding::Padding()
:
always{YType::empty, "always"}
{
yang_name = "padding"; yang_parent_name = "hello"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true;
}
Native::Otv::Site::Otv_::Isis::Hello::Padding::~Padding()
{
}
bool Native::Otv::Site::Otv_::Isis::Hello::Padding::has_data() const
{
if (is_presence_container) return true;
return always.is_set;
}
bool Native::Otv::Site::Otv_::Isis::Hello::Padding::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(always.yfilter);
}
std::string Native::Otv::Site::Otv_::Isis::Hello::Padding::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "padding";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Site::Otv_::Isis::Hello::Padding::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (always.is_set || is_set(always.yfilter)) leaf_name_data.push_back(always.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Site::Otv_::Isis::Hello::Padding::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Site::Otv_::Isis::Hello::Padding::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Otv::Site::Otv_::Isis::Hello::Padding::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "always")
{
always = value;
always.value_namespace = name_space;
always.value_namespace_prefix = name_space_prefix;
}
}
void Native::Otv::Site::Otv_::Isis::Hello::Padding::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "always")
{
always.yfilter = yfilter;
}
}
bool Native::Otv::Site::Otv_::Isis::Hello::Padding::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "always")
return true;
return false;
}
Native::Otv::Site::Otv_::Isis::HelloInterval::HelloInterval()
:
value_{YType::uint16, "value"},
minimal{YType::empty, "minimal"}
{
yang_name = "hello-interval"; yang_parent_name = "isis"; is_top_level_class = false; has_list_ancestor = true;
}
Native::Otv::Site::Otv_::Isis::HelloInterval::~HelloInterval()
{
}
bool Native::Otv::Site::Otv_::Isis::HelloInterval::has_data() const
{
if (is_presence_container) return true;
return value_.is_set
|| minimal.is_set;
}
bool Native::Otv::Site::Otv_::Isis::HelloInterval::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(value_.yfilter)
|| ydk::is_set(minimal.yfilter);
}
std::string Native::Otv::Site::Otv_::Isis::HelloInterval::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "hello-interval";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Otv::Site::Otv_::Isis::HelloInterval::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (value_.is_set || is_set(value_.yfilter)) leaf_name_data.push_back(value_.get_name_leafdata());
if (minimal.is_set || is_set(minimal.yfilter)) leaf_name_data.push_back(minimal.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Otv::Site::Otv_::Isis::HelloInterval::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Otv::Site::Otv_::Isis::HelloInterval::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Otv::Site::Otv_::Isis::HelloInterval::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "value")
{
value_ = value;
value_.value_namespace = name_space;
value_.value_namespace_prefix = name_space_prefix;
}
if(value_path == "minimal")
{
minimal = value;
minimal.value_namespace = name_space;
minimal.value_namespace_prefix = name_space_prefix;
}
}
void Native::Otv::Site::Otv_::Isis::HelloInterval::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "value")
{
value_.yfilter = yfilter;
}
if(value_path == "minimal")
{
minimal.yfilter = yfilter;
}
}
bool Native::Otv::Site::Otv_::Isis::HelloInterval::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "value" || name == "minimal")
return true;
return false;
}
Native::RemoteManagement::RemoteManagement()
:
dmi{YType::empty, "dmi"},
restful_api{YType::boolean, "restful-api"}
{
yang_name = "remote-management"; yang_parent_name = "native"; is_top_level_class = false; has_list_ancestor = false;
}
Native::RemoteManagement::~RemoteManagement()
{
}
bool Native::RemoteManagement::has_data() const
{
if (is_presence_container) return true;
return dmi.is_set
|| restful_api.is_set;
}
bool Native::RemoteManagement::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(dmi.yfilter)
|| ydk::is_set(restful_api.yfilter);
}
std::string Native::RemoteManagement::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/" << get_segment_path();
return path_buffer.str();
}
std::string Native::RemoteManagement::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "remote-management";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::RemoteManagement::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (dmi.is_set || is_set(dmi.yfilter)) leaf_name_data.push_back(dmi.get_name_leafdata());
if (restful_api.is_set || is_set(restful_api.yfilter)) leaf_name_data.push_back(restful_api.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::RemoteManagement::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::RemoteManagement::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::RemoteManagement::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "dmi")
{
dmi = value;
dmi.value_namespace = name_space;
dmi.value_namespace_prefix = name_space_prefix;
}
if(value_path == "restful-api")
{
restful_api = value;
restful_api.value_namespace = name_space;
restful_api.value_namespace_prefix = name_space_prefix;
}
}
void Native::RemoteManagement::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "dmi")
{
dmi.yfilter = yfilter;
}
if(value_path == "restful-api")
{
restful_api.yfilter = yfilter;
}
}
bool Native::RemoteManagement::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "dmi" || name == "restful-api")
return true;
return false;
}
Native::VirtualService::VirtualService()
:
name{YType::str, "name"},
activate{YType::empty, "Cisco-IOS-XE-vservice:activate"},
profile{YType::str, "Cisco-IOS-XE-vservice:profile"}
,
ip(std::make_shared<Native::VirtualService::Ip>())
, vnic(std::make_shared<Native::VirtualService::Vnic>())
{
ip->parent = this;
vnic->parent = this;
yang_name = "virtual-service"; yang_parent_name = "native"; is_top_level_class = false; has_list_ancestor = false;
}
Native::VirtualService::~VirtualService()
{
}
bool Native::VirtualService::has_data() const
{
if (is_presence_container) return true;
return name.is_set
|| activate.is_set
|| profile.is_set
|| (ip != nullptr && ip->has_data())
|| (vnic != nullptr && vnic->has_data());
}
bool Native::VirtualService::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(name.yfilter)
|| ydk::is_set(activate.yfilter)
|| ydk::is_set(profile.yfilter)
|| (ip != nullptr && ip->has_operation())
|| (vnic != nullptr && vnic->has_operation());
}
std::string Native::VirtualService::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/" << get_segment_path();
return path_buffer.str();
}
std::string Native::VirtualService::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "virtual-service";
ADD_KEY_TOKEN(name, "name");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::VirtualService::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (name.is_set || is_set(name.yfilter)) leaf_name_data.push_back(name.get_name_leafdata());
if (activate.is_set || is_set(activate.yfilter)) leaf_name_data.push_back(activate.get_name_leafdata());
if (profile.is_set || is_set(profile.yfilter)) leaf_name_data.push_back(profile.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::VirtualService::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "Cisco-IOS-XE-vservice:ip")
{
if(ip == nullptr)
{
ip = std::make_shared<Native::VirtualService::Ip>();
}
return ip;
}
if(child_yang_name == "Cisco-IOS-XE-vservice:vnic")
{
if(vnic == nullptr)
{
vnic = std::make_shared<Native::VirtualService::Vnic>();
}
return vnic;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::VirtualService::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(ip != nullptr)
{
_children["Cisco-IOS-XE-vservice:ip"] = ip;
}
if(vnic != nullptr)
{
_children["Cisco-IOS-XE-vservice:vnic"] = vnic;
}
return _children;
}
void Native::VirtualService::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "name")
{
name = value;
name.value_namespace = name_space;
name.value_namespace_prefix = name_space_prefix;
}
if(value_path == "Cisco-IOS-XE-vservice:activate")
{
activate = value;
activate.value_namespace = name_space;
activate.value_namespace_prefix = name_space_prefix;
}
if(value_path == "Cisco-IOS-XE-vservice:profile")
{
profile = value;
profile.value_namespace = name_space;
profile.value_namespace_prefix = name_space_prefix;
}
}
void Native::VirtualService::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "name")
{
name.yfilter = yfilter;
}
if(value_path == "activate")
{
activate.yfilter = yfilter;
}
if(value_path == "profile")
{
profile.yfilter = yfilter;
}
}
bool Native::VirtualService::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "ip" || name == "vnic" || name == "name" || name == "activate" || name == "profile")
return true;
return false;
}
Native::VirtualService::Ip::Ip()
:
shared(std::make_shared<Native::VirtualService::Ip::Shared>())
{
shared->parent = this;
yang_name = "ip"; yang_parent_name = "virtual-service"; is_top_level_class = false; has_list_ancestor = true;
}
Native::VirtualService::Ip::~Ip()
{
}
bool Native::VirtualService::Ip::has_data() const
{
if (is_presence_container) return true;
return (shared != nullptr && shared->has_data());
}
bool Native::VirtualService::Ip::has_operation() const
{
return is_set(yfilter)
|| (shared != nullptr && shared->has_operation());
}
std::string Native::VirtualService::Ip::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-vservice:ip";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::VirtualService::Ip::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::VirtualService::Ip::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "shared")
{
if(shared == nullptr)
{
shared = std::make_shared<Native::VirtualService::Ip::Shared>();
}
return shared;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::VirtualService::Ip::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(shared != nullptr)
{
_children["shared"] = shared;
}
return _children;
}
void Native::VirtualService::Ip::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::VirtualService::Ip::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::VirtualService::Ip::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "shared")
return true;
return false;
}
Native::VirtualService::Ip::Shared::Shared()
:
host_interface(std::make_shared<Native::VirtualService::Ip::Shared::HostInterface>())
{
host_interface->parent = this;
yang_name = "shared"; yang_parent_name = "ip"; is_top_level_class = false; has_list_ancestor = true;
}
Native::VirtualService::Ip::Shared::~Shared()
{
}
bool Native::VirtualService::Ip::Shared::has_data() const
{
if (is_presence_container) return true;
return (host_interface != nullptr && host_interface->has_data());
}
bool Native::VirtualService::Ip::Shared::has_operation() const
{
return is_set(yfilter)
|| (host_interface != nullptr && host_interface->has_operation());
}
std::string Native::VirtualService::Ip::Shared::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "shared";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::VirtualService::Ip::Shared::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::VirtualService::Ip::Shared::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "host-interface")
{
if(host_interface == nullptr)
{
host_interface = std::make_shared<Native::VirtualService::Ip::Shared::HostInterface>();
}
return host_interface;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::VirtualService::Ip::Shared::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(host_interface != nullptr)
{
_children["host-interface"] = host_interface;
}
return _children;
}
void Native::VirtualService::Ip::Shared::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::VirtualService::Ip::Shared::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::VirtualService::Ip::Shared::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "host-interface")
return true;
return false;
}
Native::VirtualService::Ip::Shared::HostInterface::HostInterface()
:
fastethernet{YType::str, "FastEthernet"},
tengigabitethernet{YType::str, "TenGigabitEthernet"},
gigabitethernet{YType::str, "GigabitEthernet"},
fivegigabitethernet{YType::str, "FiveGigabitEthernet"},
twentyfivegige{YType::str, "TwentyFiveGigE"},
twogigabitethernet{YType::str, "TwoGigabitEthernet"},
loopback{YType::uint64, "Loopback"},
vlan{YType::uint16, "Vlan"}
{
yang_name = "host-interface"; yang_parent_name = "shared"; is_top_level_class = false; has_list_ancestor = true;
}
Native::VirtualService::Ip::Shared::HostInterface::~HostInterface()
{
}
bool Native::VirtualService::Ip::Shared::HostInterface::has_data() const
{
if (is_presence_container) return true;
return fastethernet.is_set
|| tengigabitethernet.is_set
|| gigabitethernet.is_set
|| fivegigabitethernet.is_set
|| twentyfivegige.is_set
|| twogigabitethernet.is_set
|| loopback.is_set
|| vlan.is_set;
}
bool Native::VirtualService::Ip::Shared::HostInterface::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(fastethernet.yfilter)
|| ydk::is_set(tengigabitethernet.yfilter)
|| ydk::is_set(gigabitethernet.yfilter)
|| ydk::is_set(fivegigabitethernet.yfilter)
|| ydk::is_set(twentyfivegige.yfilter)
|| ydk::is_set(twogigabitethernet.yfilter)
|| ydk::is_set(loopback.yfilter)
|| ydk::is_set(vlan.yfilter);
}
std::string Native::VirtualService::Ip::Shared::HostInterface::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "host-interface";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::VirtualService::Ip::Shared::HostInterface::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (fastethernet.is_set || is_set(fastethernet.yfilter)) leaf_name_data.push_back(fastethernet.get_name_leafdata());
if (tengigabitethernet.is_set || is_set(tengigabitethernet.yfilter)) leaf_name_data.push_back(tengigabitethernet.get_name_leafdata());
if (gigabitethernet.is_set || is_set(gigabitethernet.yfilter)) leaf_name_data.push_back(gigabitethernet.get_name_leafdata());
if (fivegigabitethernet.is_set || is_set(fivegigabitethernet.yfilter)) leaf_name_data.push_back(fivegigabitethernet.get_name_leafdata());
if (twentyfivegige.is_set || is_set(twentyfivegige.yfilter)) leaf_name_data.push_back(twentyfivegige.get_name_leafdata());
if (twogigabitethernet.is_set || is_set(twogigabitethernet.yfilter)) leaf_name_data.push_back(twogigabitethernet.get_name_leafdata());
if (loopback.is_set || is_set(loopback.yfilter)) leaf_name_data.push_back(loopback.get_name_leafdata());
if (vlan.is_set || is_set(vlan.yfilter)) leaf_name_data.push_back(vlan.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::VirtualService::Ip::Shared::HostInterface::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::VirtualService::Ip::Shared::HostInterface::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::VirtualService::Ip::Shared::HostInterface::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "FastEthernet")
{
fastethernet = value;
fastethernet.value_namespace = name_space;
fastethernet.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TenGigabitEthernet")
{
tengigabitethernet = value;
tengigabitethernet.value_namespace = name_space;
tengigabitethernet.value_namespace_prefix = name_space_prefix;
}
if(value_path == "GigabitEthernet")
{
gigabitethernet = value;
gigabitethernet.value_namespace = name_space;
gigabitethernet.value_namespace_prefix = name_space_prefix;
}
if(value_path == "FiveGigabitEthernet")
{
fivegigabitethernet = value;
fivegigabitethernet.value_namespace = name_space;
fivegigabitethernet.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TwentyFiveGigE")
{
twentyfivegige = value;
twentyfivegige.value_namespace = name_space;
twentyfivegige.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TwoGigabitEthernet")
{
twogigabitethernet = value;
twogigabitethernet.value_namespace = name_space;
twogigabitethernet.value_namespace_prefix = name_space_prefix;
}
if(value_path == "Loopback")
{
loopback = value;
loopback.value_namespace = name_space;
loopback.value_namespace_prefix = name_space_prefix;
}
if(value_path == "Vlan")
{
vlan = value;
vlan.value_namespace = name_space;
vlan.value_namespace_prefix = name_space_prefix;
}
}
void Native::VirtualService::Ip::Shared::HostInterface::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "FastEthernet")
{
fastethernet.yfilter = yfilter;
}
if(value_path == "TenGigabitEthernet")
{
tengigabitethernet.yfilter = yfilter;
}
if(value_path == "GigabitEthernet")
{
gigabitethernet.yfilter = yfilter;
}
if(value_path == "FiveGigabitEthernet")
{
fivegigabitethernet.yfilter = yfilter;
}
if(value_path == "TwentyFiveGigE")
{
twentyfivegige.yfilter = yfilter;
}
if(value_path == "TwoGigabitEthernet")
{
twogigabitethernet.yfilter = yfilter;
}
if(value_path == "Loopback")
{
loopback.yfilter = yfilter;
}
if(value_path == "Vlan")
{
vlan.yfilter = yfilter;
}
}
bool Native::VirtualService::Ip::Shared::HostInterface::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "FastEthernet" || name == "TenGigabitEthernet" || name == "GigabitEthernet" || name == "FiveGigabitEthernet" || name == "TwentyFiveGigE" || name == "TwoGigabitEthernet" || name == "Loopback" || name == "Vlan")
return true;
return false;
}
Native::VirtualService::Vnic::Vnic()
:
gateway(std::make_shared<Native::VirtualService::Vnic::Gateway>())
, management(std::make_shared<Native::VirtualService::Vnic::Management>())
{
gateway->parent = this;
management->parent = this;
yang_name = "vnic"; yang_parent_name = "virtual-service"; is_top_level_class = false; has_list_ancestor = true;
}
Native::VirtualService::Vnic::~Vnic()
{
}
bool Native::VirtualService::Vnic::has_data() const
{
if (is_presence_container) return true;
return (gateway != nullptr && gateway->has_data())
|| (management != nullptr && management->has_data());
}
bool Native::VirtualService::Vnic::has_operation() const
{
return is_set(yfilter)
|| (gateway != nullptr && gateway->has_operation())
|| (management != nullptr && management->has_operation());
}
std::string Native::VirtualService::Vnic::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-vservice:vnic";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::VirtualService::Vnic::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::VirtualService::Vnic::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "gateway")
{
if(gateway == nullptr)
{
gateway = std::make_shared<Native::VirtualService::Vnic::Gateway>();
}
return gateway;
}
if(child_yang_name == "management")
{
if(management == nullptr)
{
management = std::make_shared<Native::VirtualService::Vnic::Management>();
}
return management;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::VirtualService::Vnic::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(gateway != nullptr)
{
_children["gateway"] = gateway;
}
if(management != nullptr)
{
_children["management"] = management;
}
return _children;
}
void Native::VirtualService::Vnic::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::VirtualService::Vnic::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::VirtualService::Vnic::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "gateway" || name == "management")
return true;
return false;
}
Native::VirtualService::Vnic::Gateway::Gateway()
:
virtualportgroup(this, {"number"})
{
yang_name = "gateway"; yang_parent_name = "vnic"; is_top_level_class = false; has_list_ancestor = true;
}
Native::VirtualService::Vnic::Gateway::~Gateway()
{
}
bool Native::VirtualService::Vnic::Gateway::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<virtualportgroup.len(); index++)
{
if(virtualportgroup[index]->has_data())
return true;
}
return false;
}
bool Native::VirtualService::Vnic::Gateway::has_operation() const
{
for (std::size_t index=0; index<virtualportgroup.len(); index++)
{
if(virtualportgroup[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Native::VirtualService::Vnic::Gateway::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "gateway";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::VirtualService::Vnic::Gateway::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::VirtualService::Vnic::Gateway::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "VirtualPortGroup")
{
auto ent_ = std::make_shared<Native::VirtualService::Vnic::Gateway::VirtualPortGroup>();
ent_->parent = this;
virtualportgroup.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::VirtualService::Vnic::Gateway::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : virtualportgroup.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Native::VirtualService::Vnic::Gateway::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::VirtualService::Vnic::Gateway::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::VirtualService::Vnic::Gateway::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "VirtualPortGroup")
return true;
return false;
}
Native::VirtualService::Vnic::Gateway::VirtualPortGroup::VirtualPortGroup()
:
number{YType::uint16, "number"}
,
guest(std::make_shared<Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest>())
{
guest->parent = this;
yang_name = "VirtualPortGroup"; yang_parent_name = "gateway"; is_top_level_class = false; has_list_ancestor = true;
}
Native::VirtualService::Vnic::Gateway::VirtualPortGroup::~VirtualPortGroup()
{
}
bool Native::VirtualService::Vnic::Gateway::VirtualPortGroup::has_data() const
{
if (is_presence_container) return true;
return number.is_set
|| (guest != nullptr && guest->has_data());
}
bool Native::VirtualService::Vnic::Gateway::VirtualPortGroup::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(number.yfilter)
|| (guest != nullptr && guest->has_operation());
}
std::string Native::VirtualService::Vnic::Gateway::VirtualPortGroup::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "VirtualPortGroup";
ADD_KEY_TOKEN(number, "number");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::VirtualService::Vnic::Gateway::VirtualPortGroup::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (number.is_set || is_set(number.yfilter)) leaf_name_data.push_back(number.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::VirtualService::Vnic::Gateway::VirtualPortGroup::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "guest")
{
if(guest == nullptr)
{
guest = std::make_shared<Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest>();
}
return guest;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::VirtualService::Vnic::Gateway::VirtualPortGroup::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(guest != nullptr)
{
_children["guest"] = guest;
}
return _children;
}
void Native::VirtualService::Vnic::Gateway::VirtualPortGroup::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "number")
{
number = value;
number.value_namespace = name_space;
number.value_namespace_prefix = name_space_prefix;
}
}
void Native::VirtualService::Vnic::Gateway::VirtualPortGroup::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "number")
{
number.yfilter = yfilter;
}
}
bool Native::VirtualService::Vnic::Gateway::VirtualPortGroup::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "guest" || name == "number")
return true;
return false;
}
Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest::Guest()
:
ip(std::make_shared<Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest::Ip>())
, ipv6(std::make_shared<Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest::Ipv6>())
{
ip->parent = this;
ipv6->parent = this;
yang_name = "guest"; yang_parent_name = "VirtualPortGroup"; is_top_level_class = false; has_list_ancestor = true;
}
Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest::~Guest()
{
}
bool Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest::has_data() const
{
if (is_presence_container) return true;
return (ip != nullptr && ip->has_data())
|| (ipv6 != nullptr && ipv6->has_data());
}
bool Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest::has_operation() const
{
return is_set(yfilter)
|| (ip != nullptr && ip->has_operation())
|| (ipv6 != nullptr && ipv6->has_operation());
}
std::string Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "guest";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "ip")
{
if(ip == nullptr)
{
ip = std::make_shared<Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest::Ip>();
}
return ip;
}
if(child_yang_name == "ipv6")
{
if(ipv6 == nullptr)
{
ipv6 = std::make_shared<Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest::Ipv6>();
}
return ipv6;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(ip != nullptr)
{
_children["ip"] = ip;
}
if(ipv6 != nullptr)
{
_children["ipv6"] = ipv6;
}
return _children;
}
void Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "ip" || name == "ipv6")
return true;
return false;
}
Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest::Ip::Ip()
:
address{YType::str, "address"}
{
yang_name = "ip"; yang_parent_name = "guest"; is_top_level_class = false; has_list_ancestor = true;
}
Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest::Ip::~Ip()
{
}
bool Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest::Ip::has_data() const
{
if (is_presence_container) return true;
return address.is_set;
}
bool Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest::Ip::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(address.yfilter);
}
std::string Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest::Ip::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "ip";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest::Ip::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (address.is_set || is_set(address.yfilter)) leaf_name_data.push_back(address.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest::Ip::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest::Ip::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest::Ip::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "address")
{
address = value;
address.value_namespace = name_space;
address.value_namespace_prefix = name_space_prefix;
}
}
void Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest::Ip::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "address")
{
address.yfilter = yfilter;
}
}
bool Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest::Ip::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "address")
return true;
return false;
}
Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest::Ipv6::Ipv6()
:
address{YType::str, "address"}
{
yang_name = "ipv6"; yang_parent_name = "guest"; is_top_level_class = false; has_list_ancestor = true;
}
Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest::Ipv6::~Ipv6()
{
}
bool Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest::Ipv6::has_data() const
{
if (is_presence_container) return true;
return address.is_set;
}
bool Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest::Ipv6::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(address.yfilter);
}
std::string Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest::Ipv6::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "ipv6";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest::Ipv6::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (address.is_set || is_set(address.yfilter)) leaf_name_data.push_back(address.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest::Ipv6::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest::Ipv6::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest::Ipv6::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "address")
{
address = value;
address.value_namespace = name_space;
address.value_namespace_prefix = name_space_prefix;
}
}
void Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest::Ipv6::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "address")
{
address.yfilter = yfilter;
}
}
bool Native::VirtualService::Vnic::Gateway::VirtualPortGroup::Guest::Ipv6::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "address")
return true;
return false;
}
Native::VirtualService::Vnic::Management::Management()
:
gigabitethernet0{YType::empty, "GigabitEthernet0"}
,
guest(std::make_shared<Native::VirtualService::Vnic::Management::Guest>())
{
guest->parent = this;
yang_name = "management"; yang_parent_name = "vnic"; is_top_level_class = false; has_list_ancestor = true;
}
Native::VirtualService::Vnic::Management::~Management()
{
}
bool Native::VirtualService::Vnic::Management::has_data() const
{
if (is_presence_container) return true;
return gigabitethernet0.is_set
|| (guest != nullptr && guest->has_data());
}
bool Native::VirtualService::Vnic::Management::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(gigabitethernet0.yfilter)
|| (guest != nullptr && guest->has_operation());
}
std::string Native::VirtualService::Vnic::Management::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "management";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::VirtualService::Vnic::Management::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (gigabitethernet0.is_set || is_set(gigabitethernet0.yfilter)) leaf_name_data.push_back(gigabitethernet0.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::VirtualService::Vnic::Management::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "guest")
{
if(guest == nullptr)
{
guest = std::make_shared<Native::VirtualService::Vnic::Management::Guest>();
}
return guest;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::VirtualService::Vnic::Management::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(guest != nullptr)
{
_children["guest"] = guest;
}
return _children;
}
void Native::VirtualService::Vnic::Management::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "GigabitEthernet0")
{
gigabitethernet0 = value;
gigabitethernet0.value_namespace = name_space;
gigabitethernet0.value_namespace_prefix = name_space_prefix;
}
}
void Native::VirtualService::Vnic::Management::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "GigabitEthernet0")
{
gigabitethernet0.yfilter = yfilter;
}
}
bool Native::VirtualService::Vnic::Management::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "guest" || name == "GigabitEthernet0")
return true;
return false;
}
Native::VirtualService::Vnic::Management::Guest::Guest()
:
ip(std::make_shared<Native::VirtualService::Vnic::Management::Guest::Ip>())
, ipv6(std::make_shared<Native::VirtualService::Vnic::Management::Guest::Ipv6>())
{
ip->parent = this;
ipv6->parent = this;
yang_name = "guest"; yang_parent_name = "management"; is_top_level_class = false; has_list_ancestor = true;
}
Native::VirtualService::Vnic::Management::Guest::~Guest()
{
}
bool Native::VirtualService::Vnic::Management::Guest::has_data() const
{
if (is_presence_container) return true;
return (ip != nullptr && ip->has_data())
|| (ipv6 != nullptr && ipv6->has_data());
}
bool Native::VirtualService::Vnic::Management::Guest::has_operation() const
{
return is_set(yfilter)
|| (ip != nullptr && ip->has_operation())
|| (ipv6 != nullptr && ipv6->has_operation());
}
std::string Native::VirtualService::Vnic::Management::Guest::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "guest";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::VirtualService::Vnic::Management::Guest::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::VirtualService::Vnic::Management::Guest::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "ip")
{
if(ip == nullptr)
{
ip = std::make_shared<Native::VirtualService::Vnic::Management::Guest::Ip>();
}
return ip;
}
if(child_yang_name == "ipv6")
{
if(ipv6 == nullptr)
{
ipv6 = std::make_shared<Native::VirtualService::Vnic::Management::Guest::Ipv6>();
}
return ipv6;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::VirtualService::Vnic::Management::Guest::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(ip != nullptr)
{
_children["ip"] = ip;
}
if(ipv6 != nullptr)
{
_children["ipv6"] = ipv6;
}
return _children;
}
void Native::VirtualService::Vnic::Management::Guest::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::VirtualService::Vnic::Management::Guest::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::VirtualService::Vnic::Management::Guest::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "ip" || name == "ipv6")
return true;
return false;
}
Native::VirtualService::Vnic::Management::Guest::Ip::Ip()
:
address{YType::str, "address"}
{
yang_name = "ip"; yang_parent_name = "guest"; is_top_level_class = false; has_list_ancestor = true;
}
Native::VirtualService::Vnic::Management::Guest::Ip::~Ip()
{
}
bool Native::VirtualService::Vnic::Management::Guest::Ip::has_data() const
{
if (is_presence_container) return true;
return address.is_set;
}
bool Native::VirtualService::Vnic::Management::Guest::Ip::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(address.yfilter);
}
std::string Native::VirtualService::Vnic::Management::Guest::Ip::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "ip";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::VirtualService::Vnic::Management::Guest::Ip::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (address.is_set || is_set(address.yfilter)) leaf_name_data.push_back(address.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::VirtualService::Vnic::Management::Guest::Ip::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::VirtualService::Vnic::Management::Guest::Ip::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::VirtualService::Vnic::Management::Guest::Ip::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "address")
{
address = value;
address.value_namespace = name_space;
address.value_namespace_prefix = name_space_prefix;
}
}
void Native::VirtualService::Vnic::Management::Guest::Ip::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "address")
{
address.yfilter = yfilter;
}
}
bool Native::VirtualService::Vnic::Management::Guest::Ip::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "address")
return true;
return false;
}
Native::VirtualService::Vnic::Management::Guest::Ipv6::Ipv6()
:
address{YType::str, "address"}
{
yang_name = "ipv6"; yang_parent_name = "guest"; is_top_level_class = false; has_list_ancestor = true;
}
Native::VirtualService::Vnic::Management::Guest::Ipv6::~Ipv6()
{
}
bool Native::VirtualService::Vnic::Management::Guest::Ipv6::has_data() const
{
if (is_presence_container) return true;
return address.is_set;
}
bool Native::VirtualService::Vnic::Management::Guest::Ipv6::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(address.yfilter);
}
std::string Native::VirtualService::Vnic::Management::Guest::Ipv6::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "ipv6";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::VirtualService::Vnic::Management::Guest::Ipv6::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (address.is_set || is_set(address.yfilter)) leaf_name_data.push_back(address.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::VirtualService::Vnic::Management::Guest::Ipv6::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::VirtualService::Vnic::Management::Guest::Ipv6::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::VirtualService::Vnic::Management::Guest::Ipv6::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "address")
{
address = value;
address.value_namespace = name_space;
address.value_namespace_prefix = name_space_prefix;
}
}
void Native::VirtualService::Vnic::Management::Guest::Ipv6::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "address")
{
address.yfilter = yfilter;
}
}
bool Native::VirtualService::Vnic::Management::Guest::Ipv6::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "address")
return true;
return false;
}
Native::Snmp::Snmp()
:
ifmib(std::make_shared<Native::Snmp::Ifmib>())
, mib(std::make_shared<Native::Snmp::Mib>())
{
ifmib->parent = this;
mib->parent = this;
yang_name = "snmp"; yang_parent_name = "native"; is_top_level_class = false; has_list_ancestor = false;
}
Native::Snmp::~Snmp()
{
}
bool Native::Snmp::has_data() const
{
if (is_presence_container) return true;
return (ifmib != nullptr && ifmib->has_data())
|| (mib != nullptr && mib->has_data());
}
bool Native::Snmp::has_operation() const
{
return is_set(yfilter)
|| (ifmib != nullptr && ifmib->has_operation())
|| (mib != nullptr && mib->has_operation());
}
std::string Native::Snmp::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/" << get_segment_path();
return path_buffer.str();
}
std::string Native::Snmp::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "snmp";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Snmp::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Snmp::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "Cisco-IOS-XE-snmp:ifmib")
{
if(ifmib == nullptr)
{
ifmib = std::make_shared<Native::Snmp::Ifmib>();
}
return ifmib;
}
if(child_yang_name == "Cisco-IOS-XE-snmp:mib")
{
if(mib == nullptr)
{
mib = std::make_shared<Native::Snmp::Mib>();
}
return mib;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Snmp::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(ifmib != nullptr)
{
_children["Cisco-IOS-XE-snmp:ifmib"] = ifmib;
}
if(mib != nullptr)
{
_children["Cisco-IOS-XE-snmp:mib"] = mib;
}
return _children;
}
void Native::Snmp::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::Snmp::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::Snmp::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "ifmib" || name == "mib")
return true;
return false;
}
Native::Snmp::Ifmib::Ifmib()
:
ifindex(std::make_shared<Native::Snmp::Ifmib::Ifindex>())
, ifalias(std::make_shared<Native::Snmp::Ifmib::Ifalias>())
{
ifindex->parent = this;
ifalias->parent = this;
yang_name = "ifmib"; yang_parent_name = "snmp"; is_top_level_class = false; has_list_ancestor = false;
}
Native::Snmp::Ifmib::~Ifmib()
{
}
bool Native::Snmp::Ifmib::has_data() const
{
if (is_presence_container) return true;
return (ifindex != nullptr && ifindex->has_data())
|| (ifalias != nullptr && ifalias->has_data());
}
bool Native::Snmp::Ifmib::has_operation() const
{
return is_set(yfilter)
|| (ifindex != nullptr && ifindex->has_operation())
|| (ifalias != nullptr && ifalias->has_operation());
}
std::string Native::Snmp::Ifmib::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp/" << get_segment_path();
return path_buffer.str();
}
std::string Native::Snmp::Ifmib::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-snmp:ifmib";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Snmp::Ifmib::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Snmp::Ifmib::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "ifindex")
{
if(ifindex == nullptr)
{
ifindex = std::make_shared<Native::Snmp::Ifmib::Ifindex>();
}
return ifindex;
}
if(child_yang_name == "ifalias")
{
if(ifalias == nullptr)
{
ifalias = std::make_shared<Native::Snmp::Ifmib::Ifalias>();
}
return ifalias;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Snmp::Ifmib::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(ifindex != nullptr)
{
_children["ifindex"] = ifindex;
}
if(ifalias != nullptr)
{
_children["ifalias"] = ifalias;
}
return _children;
}
void Native::Snmp::Ifmib::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::Snmp::Ifmib::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::Snmp::Ifmib::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "ifindex" || name == "ifalias")
return true;
return false;
}
Native::Snmp::Ifmib::Ifindex::Ifindex()
:
persist{YType::empty, "persist"}
{
yang_name = "ifindex"; yang_parent_name = "ifmib"; is_top_level_class = false; has_list_ancestor = false;
}
Native::Snmp::Ifmib::Ifindex::~Ifindex()
{
}
bool Native::Snmp::Ifmib::Ifindex::has_data() const
{
if (is_presence_container) return true;
return persist.is_set;
}
bool Native::Snmp::Ifmib::Ifindex::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(persist.yfilter);
}
std::string Native::Snmp::Ifmib::Ifindex::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp/Cisco-IOS-XE-snmp:ifmib/" << get_segment_path();
return path_buffer.str();
}
std::string Native::Snmp::Ifmib::Ifindex::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "ifindex";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Snmp::Ifmib::Ifindex::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (persist.is_set || is_set(persist.yfilter)) leaf_name_data.push_back(persist.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Snmp::Ifmib::Ifindex::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Snmp::Ifmib::Ifindex::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Snmp::Ifmib::Ifindex::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "persist")
{
persist = value;
persist.value_namespace = name_space;
persist.value_namespace_prefix = name_space_prefix;
}
}
void Native::Snmp::Ifmib::Ifindex::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "persist")
{
persist.yfilter = yfilter;
}
}
bool Native::Snmp::Ifmib::Ifindex::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "persist")
return true;
return false;
}
Native::Snmp::Ifmib::Ifalias::Ifalias()
:
long_{YType::empty, "long"}
{
yang_name = "ifalias"; yang_parent_name = "ifmib"; is_top_level_class = false; has_list_ancestor = false;
}
Native::Snmp::Ifmib::Ifalias::~Ifalias()
{
}
bool Native::Snmp::Ifmib::Ifalias::has_data() const
{
if (is_presence_container) return true;
return long_.is_set;
}
bool Native::Snmp::Ifmib::Ifalias::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(long_.yfilter);
}
std::string Native::Snmp::Ifmib::Ifalias::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp/Cisco-IOS-XE-snmp:ifmib/" << get_segment_path();
return path_buffer.str();
}
std::string Native::Snmp::Ifmib::Ifalias::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "ifalias";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Snmp::Ifmib::Ifalias::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (long_.is_set || is_set(long_.yfilter)) leaf_name_data.push_back(long_.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Snmp::Ifmib::Ifalias::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Snmp::Ifmib::Ifalias::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Snmp::Ifmib::Ifalias::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "long")
{
long_ = value;
long_.value_namespace = name_space;
long_.value_namespace_prefix = name_space_prefix;
}
}
void Native::Snmp::Ifmib::Ifalias::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "long")
{
long_.yfilter = yfilter;
}
}
bool Native::Snmp::Ifmib::Ifalias::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "long")
return true;
return false;
}
Native::Snmp::Mib::Mib()
:
community_map(std::make_shared<Native::Snmp::Mib::CommunityMap>())
, bulkstat(std::make_shared<Native::Snmp::Mib::Bulkstat>())
, persist(nullptr) // presence node
{
community_map->parent = this;
bulkstat->parent = this;
yang_name = "mib"; yang_parent_name = "snmp"; is_top_level_class = false; has_list_ancestor = false;
}
Native::Snmp::Mib::~Mib()
{
}
bool Native::Snmp::Mib::has_data() const
{
if (is_presence_container) return true;
return (community_map != nullptr && community_map->has_data())
|| (bulkstat != nullptr && bulkstat->has_data())
|| (persist != nullptr && persist->has_data());
}
bool Native::Snmp::Mib::has_operation() const
{
return is_set(yfilter)
|| (community_map != nullptr && community_map->has_operation())
|| (bulkstat != nullptr && bulkstat->has_operation())
|| (persist != nullptr && persist->has_operation());
}
std::string Native::Snmp::Mib::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp/" << get_segment_path();
return path_buffer.str();
}
std::string Native::Snmp::Mib::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-snmp:mib";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Snmp::Mib::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Snmp::Mib::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "community-map")
{
if(community_map == nullptr)
{
community_map = std::make_shared<Native::Snmp::Mib::CommunityMap>();
}
return community_map;
}
if(child_yang_name == "bulkstat")
{
if(bulkstat == nullptr)
{
bulkstat = std::make_shared<Native::Snmp::Mib::Bulkstat>();
}
return bulkstat;
}
if(child_yang_name == "persist")
{
if(persist == nullptr)
{
persist = std::make_shared<Native::Snmp::Mib::Persist>();
}
return persist;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Snmp::Mib::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(community_map != nullptr)
{
_children["community-map"] = community_map;
}
if(bulkstat != nullptr)
{
_children["bulkstat"] = bulkstat;
}
if(persist != nullptr)
{
_children["persist"] = persist;
}
return _children;
}
void Native::Snmp::Mib::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::Snmp::Mib::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::Snmp::Mib::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "community-map" || name == "bulkstat" || name == "persist")
return true;
return false;
}
Native::Snmp::Mib::CommunityMap::CommunityMap()
:
community_map_list(this, {"name"})
{
yang_name = "community-map"; yang_parent_name = "mib"; is_top_level_class = false; has_list_ancestor = false;
}
Native::Snmp::Mib::CommunityMap::~CommunityMap()
{
}
bool Native::Snmp::Mib::CommunityMap::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<community_map_list.len(); index++)
{
if(community_map_list[index]->has_data())
return true;
}
return false;
}
bool Native::Snmp::Mib::CommunityMap::has_operation() const
{
for (std::size_t index=0; index<community_map_list.len(); index++)
{
if(community_map_list[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Native::Snmp::Mib::CommunityMap::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp/Cisco-IOS-XE-snmp:mib/" << get_segment_path();
return path_buffer.str();
}
std::string Native::Snmp::Mib::CommunityMap::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "community-map";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Snmp::Mib::CommunityMap::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Snmp::Mib::CommunityMap::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "community-map-list")
{
auto ent_ = std::make_shared<Native::Snmp::Mib::CommunityMap::CommunityMapList>();
ent_->parent = this;
community_map_list.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Snmp::Mib::CommunityMap::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : community_map_list.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Native::Snmp::Mib::CommunityMap::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::Snmp::Mib::CommunityMap::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::Snmp::Mib::CommunityMap::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "community-map-list")
return true;
return false;
}
Native::Snmp::Mib::CommunityMap::CommunityMapList::CommunityMapList()
:
name{YType::str, "name"},
engineid{YType::str, "engineid"}
{
yang_name = "community-map-list"; yang_parent_name = "community-map"; is_top_level_class = false; has_list_ancestor = false;
}
Native::Snmp::Mib::CommunityMap::CommunityMapList::~CommunityMapList()
{
}
bool Native::Snmp::Mib::CommunityMap::CommunityMapList::has_data() const
{
if (is_presence_container) return true;
return name.is_set
|| engineid.is_set;
}
bool Native::Snmp::Mib::CommunityMap::CommunityMapList::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(name.yfilter)
|| ydk::is_set(engineid.yfilter);
}
std::string Native::Snmp::Mib::CommunityMap::CommunityMapList::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp/Cisco-IOS-XE-snmp:mib/community-map/" << get_segment_path();
return path_buffer.str();
}
std::string Native::Snmp::Mib::CommunityMap::CommunityMapList::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "community-map-list";
ADD_KEY_TOKEN(name, "name");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Snmp::Mib::CommunityMap::CommunityMapList::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (name.is_set || is_set(name.yfilter)) leaf_name_data.push_back(name.get_name_leafdata());
if (engineid.is_set || is_set(engineid.yfilter)) leaf_name_data.push_back(engineid.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Snmp::Mib::CommunityMap::CommunityMapList::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Snmp::Mib::CommunityMap::CommunityMapList::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Snmp::Mib::CommunityMap::CommunityMapList::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "name")
{
name = value;
name.value_namespace = name_space;
name.value_namespace_prefix = name_space_prefix;
}
if(value_path == "engineid")
{
engineid = value;
engineid.value_namespace = name_space;
engineid.value_namespace_prefix = name_space_prefix;
}
}
void Native::Snmp::Mib::CommunityMap::CommunityMapList::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "name")
{
name.yfilter = yfilter;
}
if(value_path == "engineid")
{
engineid.yfilter = yfilter;
}
}
bool Native::Snmp::Mib::CommunityMap::CommunityMapList::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "name" || name == "engineid")
return true;
return false;
}
Native::Snmp::Mib::Bulkstat::Bulkstat()
:
object_list(this, {"name"})
{
yang_name = "bulkstat"; yang_parent_name = "mib"; is_top_level_class = false; has_list_ancestor = false;
}
Native::Snmp::Mib::Bulkstat::~Bulkstat()
{
}
bool Native::Snmp::Mib::Bulkstat::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<object_list.len(); index++)
{
if(object_list[index]->has_data())
return true;
}
return false;
}
bool Native::Snmp::Mib::Bulkstat::has_operation() const
{
for (std::size_t index=0; index<object_list.len(); index++)
{
if(object_list[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Native::Snmp::Mib::Bulkstat::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp/Cisco-IOS-XE-snmp:mib/" << get_segment_path();
return path_buffer.str();
}
std::string Native::Snmp::Mib::Bulkstat::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "bulkstat";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Snmp::Mib::Bulkstat::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Snmp::Mib::Bulkstat::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "object-list")
{
auto ent_ = std::make_shared<Native::Snmp::Mib::Bulkstat::ObjectList>();
ent_->parent = this;
object_list.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Snmp::Mib::Bulkstat::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : object_list.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Native::Snmp::Mib::Bulkstat::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::Snmp::Mib::Bulkstat::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::Snmp::Mib::Bulkstat::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "object-list")
return true;
return false;
}
Native::Snmp::Mib::Bulkstat::ObjectList::ObjectList()
:
name{YType::str, "name"}
{
yang_name = "object-list"; yang_parent_name = "bulkstat"; is_top_level_class = false; has_list_ancestor = false;
}
Native::Snmp::Mib::Bulkstat::ObjectList::~ObjectList()
{
}
bool Native::Snmp::Mib::Bulkstat::ObjectList::has_data() const
{
if (is_presence_container) return true;
return name.is_set;
}
bool Native::Snmp::Mib::Bulkstat::ObjectList::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(name.yfilter);
}
std::string Native::Snmp::Mib::Bulkstat::ObjectList::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp/Cisco-IOS-XE-snmp:mib/bulkstat/" << get_segment_path();
return path_buffer.str();
}
std::string Native::Snmp::Mib::Bulkstat::ObjectList::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "object-list";
ADD_KEY_TOKEN(name, "name");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Snmp::Mib::Bulkstat::ObjectList::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (name.is_set || is_set(name.yfilter)) leaf_name_data.push_back(name.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Snmp::Mib::Bulkstat::ObjectList::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Snmp::Mib::Bulkstat::ObjectList::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Snmp::Mib::Bulkstat::ObjectList::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "name")
{
name = value;
name.value_namespace = name_space;
name.value_namespace_prefix = name_space_prefix;
}
}
void Native::Snmp::Mib::Bulkstat::ObjectList::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "name")
{
name.yfilter = yfilter;
}
}
bool Native::Snmp::Mib::Bulkstat::ObjectList::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "name")
return true;
return false;
}
Native::Snmp::Mib::Persist::Persist()
:
persist_enum{YType::enumeration, "persist-enum"}
{
yang_name = "persist"; yang_parent_name = "mib"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true;
}
Native::Snmp::Mib::Persist::~Persist()
{
}
bool Native::Snmp::Mib::Persist::has_data() const
{
if (is_presence_container) return true;
return persist_enum.is_set;
}
bool Native::Snmp::Mib::Persist::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(persist_enum.yfilter);
}
std::string Native::Snmp::Mib::Persist::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp/Cisco-IOS-XE-snmp:mib/" << get_segment_path();
return path_buffer.str();
}
std::string Native::Snmp::Mib::Persist::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "persist";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::Snmp::Mib::Persist::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (persist_enum.is_set || is_set(persist_enum.yfilter)) leaf_name_data.push_back(persist_enum.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::Snmp::Mib::Persist::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::Snmp::Mib::Persist::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::Snmp::Mib::Persist::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "persist-enum")
{
persist_enum = value;
persist_enum.value_namespace = name_space;
persist_enum.value_namespace_prefix = name_space_prefix;
}
}
void Native::Snmp::Mib::Persist::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "persist-enum")
{
persist_enum.yfilter = yfilter;
}
}
bool Native::Snmp::Mib::Persist::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "persist-enum")
return true;
return false;
}
Native::SnmpServer::SnmpServer()
:
chassis_id{YType::str, "Cisco-IOS-XE-snmp:chassis-id"},
contact{YType::str, "Cisco-IOS-XE-snmp:contact"},
location{YType::str, "Cisco-IOS-XE-snmp:location"},
packetsize{YType::uint32, "Cisco-IOS-XE-snmp:packetsize"},
queue_length{YType::uint16, "Cisco-IOS-XE-snmp:queue-length"},
system_shutdown{YType::empty, "Cisco-IOS-XE-snmp:system-shutdown"},
tftp_server_list{YType::str, "Cisco-IOS-XE-snmp:tftp-server-list"}
,
community(this, {"name"})
, context(this, {"name"})
, enable(std::make_shared<Native::SnmpServer::Enable>())
, engineid(std::make_shared<Native::SnmpServer::EngineID>())
, group(this, {"id"})
, host(this, {"ip_address", "community_or_user"})
, ip(std::make_shared<Native::SnmpServer::Ip>())
, ifindex(std::make_shared<Native::SnmpServer::Ifindex>())
, manager(nullptr) // presence node
, source_interface(std::make_shared<Native::SnmpServer::SourceInterface>())
, trap(std::make_shared<Native::SnmpServer::Trap>())
, trap_source(std::make_shared<Native::SnmpServer::TrapSource>())
, user(std::make_shared<Native::SnmpServer::User>())
, view(this, {"name", "mib"})
{
enable->parent = this;
engineid->parent = this;
ip->parent = this;
ifindex->parent = this;
source_interface->parent = this;
trap->parent = this;
trap_source->parent = this;
user->parent = this;
yang_name = "snmp-server"; yang_parent_name = "native"; is_top_level_class = false; has_list_ancestor = false;
}
Native::SnmpServer::~SnmpServer()
{
}
bool Native::SnmpServer::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<community.len(); index++)
{
if(community[index]->has_data())
return true;
}
for (std::size_t index=0; index<context.len(); index++)
{
if(context[index]->has_data())
return true;
}
for (std::size_t index=0; index<group.len(); index++)
{
if(group[index]->has_data())
return true;
}
for (std::size_t index=0; index<host.len(); index++)
{
if(host[index]->has_data())
return true;
}
for (std::size_t index=0; index<view.len(); index++)
{
if(view[index]->has_data())
return true;
}
return chassis_id.is_set
|| contact.is_set
|| location.is_set
|| packetsize.is_set
|| queue_length.is_set
|| system_shutdown.is_set
|| tftp_server_list.is_set
|| (enable != nullptr && enable->has_data())
|| (engineid != nullptr && engineid->has_data())
|| (ip != nullptr && ip->has_data())
|| (ifindex != nullptr && ifindex->has_data())
|| (manager != nullptr && manager->has_data())
|| (source_interface != nullptr && source_interface->has_data())
|| (trap != nullptr && trap->has_data())
|| (trap_source != nullptr && trap_source->has_data())
|| (user != nullptr && user->has_data());
}
bool Native::SnmpServer::has_operation() const
{
for (std::size_t index=0; index<community.len(); index++)
{
if(community[index]->has_operation())
return true;
}
for (std::size_t index=0; index<context.len(); index++)
{
if(context[index]->has_operation())
return true;
}
for (std::size_t index=0; index<group.len(); index++)
{
if(group[index]->has_operation())
return true;
}
for (std::size_t index=0; index<host.len(); index++)
{
if(host[index]->has_operation())
return true;
}
for (std::size_t index=0; index<view.len(); index++)
{
if(view[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(chassis_id.yfilter)
|| ydk::is_set(contact.yfilter)
|| ydk::is_set(location.yfilter)
|| ydk::is_set(packetsize.yfilter)
|| ydk::is_set(queue_length.yfilter)
|| ydk::is_set(system_shutdown.yfilter)
|| ydk::is_set(tftp_server_list.yfilter)
|| (enable != nullptr && enable->has_operation())
|| (engineid != nullptr && engineid->has_operation())
|| (ip != nullptr && ip->has_operation())
|| (ifindex != nullptr && ifindex->has_operation())
|| (manager != nullptr && manager->has_operation())
|| (source_interface != nullptr && source_interface->has_operation())
|| (trap != nullptr && trap->has_operation())
|| (trap_source != nullptr && trap_source->has_operation())
|| (user != nullptr && user->has_operation());
}
std::string Native::SnmpServer::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "snmp-server";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (chassis_id.is_set || is_set(chassis_id.yfilter)) leaf_name_data.push_back(chassis_id.get_name_leafdata());
if (contact.is_set || is_set(contact.yfilter)) leaf_name_data.push_back(contact.get_name_leafdata());
if (location.is_set || is_set(location.yfilter)) leaf_name_data.push_back(location.get_name_leafdata());
if (packetsize.is_set || is_set(packetsize.yfilter)) leaf_name_data.push_back(packetsize.get_name_leafdata());
if (queue_length.is_set || is_set(queue_length.yfilter)) leaf_name_data.push_back(queue_length.get_name_leafdata());
if (system_shutdown.is_set || is_set(system_shutdown.yfilter)) leaf_name_data.push_back(system_shutdown.get_name_leafdata());
if (tftp_server_list.is_set || is_set(tftp_server_list.yfilter)) leaf_name_data.push_back(tftp_server_list.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "Cisco-IOS-XE-snmp:community")
{
auto ent_ = std::make_shared<Native::SnmpServer::Community>();
ent_->parent = this;
community.append(ent_);
return ent_;
}
if(child_yang_name == "Cisco-IOS-XE-snmp:context")
{
auto ent_ = std::make_shared<Native::SnmpServer::Context>();
ent_->parent = this;
context.append(ent_);
return ent_;
}
if(child_yang_name == "Cisco-IOS-XE-snmp:enable")
{
if(enable == nullptr)
{
enable = std::make_shared<Native::SnmpServer::Enable>();
}
return enable;
}
if(child_yang_name == "Cisco-IOS-XE-snmp:engineID")
{
if(engineid == nullptr)
{
engineid = std::make_shared<Native::SnmpServer::EngineID>();
}
return engineid;
}
if(child_yang_name == "Cisco-IOS-XE-snmp:group")
{
auto ent_ = std::make_shared<Native::SnmpServer::Group>();
ent_->parent = this;
group.append(ent_);
return ent_;
}
if(child_yang_name == "Cisco-IOS-XE-snmp:host")
{
auto ent_ = std::make_shared<Native::SnmpServer::Host>();
ent_->parent = this;
host.append(ent_);
return ent_;
}
if(child_yang_name == "Cisco-IOS-XE-snmp:ip")
{
if(ip == nullptr)
{
ip = std::make_shared<Native::SnmpServer::Ip>();
}
return ip;
}
if(child_yang_name == "Cisco-IOS-XE-snmp:ifindex")
{
if(ifindex == nullptr)
{
ifindex = std::make_shared<Native::SnmpServer::Ifindex>();
}
return ifindex;
}
if(child_yang_name == "Cisco-IOS-XE-snmp:manager")
{
if(manager == nullptr)
{
manager = std::make_shared<Native::SnmpServer::Manager>();
}
return manager;
}
if(child_yang_name == "Cisco-IOS-XE-snmp:source-interface")
{
if(source_interface == nullptr)
{
source_interface = std::make_shared<Native::SnmpServer::SourceInterface>();
}
return source_interface;
}
if(child_yang_name == "Cisco-IOS-XE-snmp:trap")
{
if(trap == nullptr)
{
trap = std::make_shared<Native::SnmpServer::Trap>();
}
return trap;
}
if(child_yang_name == "Cisco-IOS-XE-snmp:trap-source")
{
if(trap_source == nullptr)
{
trap_source = std::make_shared<Native::SnmpServer::TrapSource>();
}
return trap_source;
}
if(child_yang_name == "Cisco-IOS-XE-snmp:user")
{
if(user == nullptr)
{
user = std::make_shared<Native::SnmpServer::User>();
}
return user;
}
if(child_yang_name == "Cisco-IOS-XE-snmp:view")
{
auto ent_ = std::make_shared<Native::SnmpServer::View>();
ent_->parent = this;
view.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : community.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
count_ = 0;
for (auto ent_ : context.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
if(enable != nullptr)
{
_children["Cisco-IOS-XE-snmp:enable"] = enable;
}
if(engineid != nullptr)
{
_children["Cisco-IOS-XE-snmp:engineID"] = engineid;
}
count_ = 0;
for (auto ent_ : group.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
count_ = 0;
for (auto ent_ : host.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
if(ip != nullptr)
{
_children["Cisco-IOS-XE-snmp:ip"] = ip;
}
if(ifindex != nullptr)
{
_children["Cisco-IOS-XE-snmp:ifindex"] = ifindex;
}
if(manager != nullptr)
{
_children["Cisco-IOS-XE-snmp:manager"] = manager;
}
if(source_interface != nullptr)
{
_children["Cisco-IOS-XE-snmp:source-interface"] = source_interface;
}
if(trap != nullptr)
{
_children["Cisco-IOS-XE-snmp:trap"] = trap;
}
if(trap_source != nullptr)
{
_children["Cisco-IOS-XE-snmp:trap-source"] = trap_source;
}
if(user != nullptr)
{
_children["Cisco-IOS-XE-snmp:user"] = user;
}
count_ = 0;
for (auto ent_ : view.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Native::SnmpServer::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "Cisco-IOS-XE-snmp:chassis-id")
{
chassis_id = value;
chassis_id.value_namespace = name_space;
chassis_id.value_namespace_prefix = name_space_prefix;
}
if(value_path == "Cisco-IOS-XE-snmp:contact")
{
contact = value;
contact.value_namespace = name_space;
contact.value_namespace_prefix = name_space_prefix;
}
if(value_path == "Cisco-IOS-XE-snmp:location")
{
location = value;
location.value_namespace = name_space;
location.value_namespace_prefix = name_space_prefix;
}
if(value_path == "Cisco-IOS-XE-snmp:packetsize")
{
packetsize = value;
packetsize.value_namespace = name_space;
packetsize.value_namespace_prefix = name_space_prefix;
}
if(value_path == "Cisco-IOS-XE-snmp:queue-length")
{
queue_length = value;
queue_length.value_namespace = name_space;
queue_length.value_namespace_prefix = name_space_prefix;
}
if(value_path == "Cisco-IOS-XE-snmp:system-shutdown")
{
system_shutdown = value;
system_shutdown.value_namespace = name_space;
system_shutdown.value_namespace_prefix = name_space_prefix;
}
if(value_path == "Cisco-IOS-XE-snmp:tftp-server-list")
{
tftp_server_list = value;
tftp_server_list.value_namespace = name_space;
tftp_server_list.value_namespace_prefix = name_space_prefix;
}
}
void Native::SnmpServer::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "chassis-id")
{
chassis_id.yfilter = yfilter;
}
if(value_path == "contact")
{
contact.yfilter = yfilter;
}
if(value_path == "location")
{
location.yfilter = yfilter;
}
if(value_path == "packetsize")
{
packetsize.yfilter = yfilter;
}
if(value_path == "queue-length")
{
queue_length.yfilter = yfilter;
}
if(value_path == "system-shutdown")
{
system_shutdown.yfilter = yfilter;
}
if(value_path == "tftp-server-list")
{
tftp_server_list.yfilter = yfilter;
}
}
bool Native::SnmpServer::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "community" || name == "context" || name == "enable" || name == "engineID" || name == "group" || name == "host" || name == "ip" || name == "ifindex" || name == "manager" || name == "source-interface" || name == "trap" || name == "trap-source" || name == "user" || name == "view" || name == "chassis-id" || name == "contact" || name == "location" || name == "packetsize" || name == "queue-length" || name == "system-shutdown" || name == "tftp-server-list")
return true;
return false;
}
Native::SnmpServer::Community::Community()
:
name{YType::str, "name"},
view{YType::str, "view"},
ro{YType::empty, "RO"},
rw{YType::empty, "RW"},
ipv6{YType::str, "ipv6"},
access_list_name{YType::str, "access-list-name"}
{
yang_name = "community"; yang_parent_name = "snmp-server"; is_top_level_class = false; has_list_ancestor = false;
}
Native::SnmpServer::Community::~Community()
{
}
bool Native::SnmpServer::Community::has_data() const
{
if (is_presence_container) return true;
return name.is_set
|| view.is_set
|| ro.is_set
|| rw.is_set
|| ipv6.is_set
|| access_list_name.is_set;
}
bool Native::SnmpServer::Community::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(name.yfilter)
|| ydk::is_set(view.yfilter)
|| ydk::is_set(ro.yfilter)
|| ydk::is_set(rw.yfilter)
|| ydk::is_set(ipv6.yfilter)
|| ydk::is_set(access_list_name.yfilter);
}
std::string Native::SnmpServer::Community::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Community::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-snmp:community";
ADD_KEY_TOKEN(name, "name");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Community::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (name.is_set || is_set(name.yfilter)) leaf_name_data.push_back(name.get_name_leafdata());
if (view.is_set || is_set(view.yfilter)) leaf_name_data.push_back(view.get_name_leafdata());
if (ro.is_set || is_set(ro.yfilter)) leaf_name_data.push_back(ro.get_name_leafdata());
if (rw.is_set || is_set(rw.yfilter)) leaf_name_data.push_back(rw.get_name_leafdata());
if (ipv6.is_set || is_set(ipv6.yfilter)) leaf_name_data.push_back(ipv6.get_name_leafdata());
if (access_list_name.is_set || is_set(access_list_name.yfilter)) leaf_name_data.push_back(access_list_name.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Community::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Community::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::SnmpServer::Community::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "name")
{
name = value;
name.value_namespace = name_space;
name.value_namespace_prefix = name_space_prefix;
}
if(value_path == "view")
{
view = value;
view.value_namespace = name_space;
view.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RO")
{
ro = value;
ro.value_namespace = name_space;
ro.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RW")
{
rw = value;
rw.value_namespace = name_space;
rw.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ipv6")
{
ipv6 = value;
ipv6.value_namespace = name_space;
ipv6.value_namespace_prefix = name_space_prefix;
}
if(value_path == "access-list-name")
{
access_list_name = value;
access_list_name.value_namespace = name_space;
access_list_name.value_namespace_prefix = name_space_prefix;
}
}
void Native::SnmpServer::Community::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "name")
{
name.yfilter = yfilter;
}
if(value_path == "view")
{
view.yfilter = yfilter;
}
if(value_path == "RO")
{
ro.yfilter = yfilter;
}
if(value_path == "RW")
{
rw.yfilter = yfilter;
}
if(value_path == "ipv6")
{
ipv6.yfilter = yfilter;
}
if(value_path == "access-list-name")
{
access_list_name.yfilter = yfilter;
}
}
bool Native::SnmpServer::Community::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "name" || name == "view" || name == "RO" || name == "RW" || name == "ipv6" || name == "access-list-name")
return true;
return false;
}
Native::SnmpServer::Context::Context()
:
name{YType::str, "name"}
{
yang_name = "context"; yang_parent_name = "snmp-server"; is_top_level_class = false; has_list_ancestor = false;
}
Native::SnmpServer::Context::~Context()
{
}
bool Native::SnmpServer::Context::has_data() const
{
if (is_presence_container) return true;
return name.is_set;
}
bool Native::SnmpServer::Context::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(name.yfilter);
}
std::string Native::SnmpServer::Context::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Context::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-snmp:context";
ADD_KEY_TOKEN(name, "name");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Context::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (name.is_set || is_set(name.yfilter)) leaf_name_data.push_back(name.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Context::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Context::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::SnmpServer::Context::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "name")
{
name = value;
name.value_namespace = name_space;
name.value_namespace_prefix = name_space_prefix;
}
}
void Native::SnmpServer::Context::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "name")
{
name.yfilter = yfilter;
}
}
bool Native::SnmpServer::Context::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "name")
return true;
return false;
}
Native::SnmpServer::Enable::Enable()
:
enable_choice(std::make_shared<Native::SnmpServer::Enable::EnableChoice>())
{
enable_choice->parent = this;
yang_name = "enable"; yang_parent_name = "snmp-server"; is_top_level_class = false; has_list_ancestor = false;
}
Native::SnmpServer::Enable::~Enable()
{
}
bool Native::SnmpServer::Enable::has_data() const
{
if (is_presence_container) return true;
return (enable_choice != nullptr && enable_choice->has_data());
}
bool Native::SnmpServer::Enable::has_operation() const
{
return is_set(yfilter)
|| (enable_choice != nullptr && enable_choice->has_operation());
}
std::string Native::SnmpServer::Enable::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Enable::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-snmp:enable";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Enable::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Enable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "enable-choice")
{
if(enable_choice == nullptr)
{
enable_choice = std::make_shared<Native::SnmpServer::Enable::EnableChoice>();
}
return enable_choice;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Enable::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(enable_choice != nullptr)
{
_children["enable-choice"] = enable_choice;
}
return _children;
}
void Native::SnmpServer::Enable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::SnmpServer::Enable::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::SnmpServer::Enable::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "enable-choice")
return true;
return false;
}
Native::SnmpServer::Enable::EnableChoice::EnableChoice()
:
informs{YType::empty, "informs"}
,
traps(nullptr) // presence node
{
yang_name = "enable-choice"; yang_parent_name = "enable"; is_top_level_class = false; has_list_ancestor = false;
}
Native::SnmpServer::Enable::EnableChoice::~EnableChoice()
{
}
bool Native::SnmpServer::Enable::EnableChoice::has_data() const
{
if (is_presence_container) return true;
return informs.is_set
|| (traps != nullptr && traps->has_data());
}
bool Native::SnmpServer::Enable::EnableChoice::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(informs.yfilter)
|| (traps != nullptr && traps->has_operation());
}
std::string Native::SnmpServer::Enable::EnableChoice::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/Cisco-IOS-XE-snmp:enable/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Enable::EnableChoice::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "enable-choice";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Enable::EnableChoice::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (informs.is_set || is_set(informs.yfilter)) leaf_name_data.push_back(informs.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Enable::EnableChoice::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "traps")
{
if(traps == nullptr)
{
traps = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps>();
}
return traps;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Enable::EnableChoice::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(traps != nullptr)
{
_children["traps"] = traps;
}
return _children;
}
void Native::SnmpServer::Enable::EnableChoice::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "informs")
{
informs = value;
informs.value_namespace = name_space;
informs.value_namespace_prefix = name_space_prefix;
}
}
void Native::SnmpServer::Enable::EnableChoice::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "informs")
{
informs.yfilter = yfilter;
}
}
bool Native::SnmpServer::Enable::EnableChoice::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "traps" || name == "informs")
return true;
return false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Traps()
:
aaa_server{YType::empty, "aaa_server"},
local_auth{YType::empty, "local-auth"},
authenticate_fail{YType::empty, "authenticate-fail"},
bfd{YType::empty, "bfd"},
bgp{YType::empty, "bgp"},
bstun{YType::empty, "bstun"},
c2900{YType::empty, "c2900"},
casa{YType::empty, "casa"},
ccme{YType::empty, "ccme"},
cluster{YType::empty, "cluster"},
channel{YType::empty, "channel"},
chassis{YType::empty, "chassis"},
cnpd{YType::empty, "cnpd"},
config{YType::empty, "config"},
copy_config{YType::empty, "copy-config"},
config_copy{YType::empty, "config-copy"},
config_ctid{YType::empty, "config-ctid"},
cpu_threshold{YType::empty, "cpu_threshold"},
dial{YType::empty, "dial"},
director{YType::empty, "director"},
dlsw{YType::empty, "dlsw"},
deauthenticate{YType::empty, "deauthenticate"},
disassociate{YType::empty, "disassociate"},
dnis{YType::empty, "dnis"},
dot11_qos{YType::empty, "dot11-qos"},
ds0_busyout{YType::empty, "ds0-busyout"},
ds1{YType::empty, "ds1"},
ds1_loopback{YType::empty, "ds1-loopback"},
ds3{YType::empty, "ds3"},
dhcp{YType::empty, "dhcp"},
eigrp{YType::empty, "eigrp"},
entity_{YType::empty, "entity"},
ether_oam{YType::empty, "ether-oam"},
event_manager{YType::empty, "event-manager"},
flowmon{YType::empty, "flowmon"},
fru_ctrl{YType::empty, "fru-ctrl"},
gatekeeper{YType::empty, "gatekeeper"},
hsrp{YType::empty, "hsrp"},
icsudsu{YType::empty, "icsudsu"},
ima{YType::empty, "ima"},
ipmobile{YType::empty, "ipmobile"},
ipmulticast{YType::empty, "ipmulticast"},
ipsla{YType::empty, "ipsla"},
isis{YType::empty, "isis"},
module{YType::empty, "module"},
msdp{YType::empty, "msdp"},
mvpn{YType::empty, "mvpn"},
pppoe{YType::empty, "pppoe"},
rep{YType::empty, "rep"},
resource_policy{YType::empty, "resource-policy"},
rf{YType::empty, "rf"},
rogue_ap{YType::empty, "rogue-ap"},
rsvp{YType::empty, "rsvp"},
rtr{YType::empty, "rtr"},
sonet{YType::empty, "sonet"},
srst{YType::empty, "srst"},
srp{YType::empty, "srp"},
stun{YType::empty, "stun"},
switch_over{YType::empty, "switch-over"},
syslog{YType::empty, "syslog"},
tty{YType::empty, "tty"},
vlancreate{YType::empty, "vlancreate"},
vlandelete{YType::empty, "vlandelete"},
vlan_mac_limit{YType::empty, "vlan-mac-limit"},
vlan_membership{YType::empty, "vlan-membership"},
voice{YType::empty, "voice"},
vrrp{YType::empty, "vrrp"},
vsimaster{YType::empty, "vsimaster"},
vtp{YType::empty, "vtp"},
wlan_wep{YType::empty, "wlan-wep"},
xgcp{YType::empty, "xgcp"}
,
trustsec_sxp(nullptr) // presence node
, vswitch(nullptr) // presence node
, trustsec_server(nullptr) // presence node
, trustsec(nullptr) // presence node
, trustsec_interface(nullptr) // presence node
, trustsec_policy(nullptr) // presence node
, ospfv3(std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Ospfv3>())
, ike(std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Ike>())
, alarms(nullptr) // presence node
, atm(std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Atm>())
, auth_framework(nullptr) // presence node
, bgp_conf(std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::BgpConf>())
, bridge(nullptr) // presence node
, bulkstat(nullptr) // presence node
, call_home(nullptr) // presence node
, c6kxbar(nullptr) // presence node
, cef(std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Cef>())
, cpu(nullptr) // presence node
, csg(nullptr) // presence node
, dot1x(std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Dot1x>())
, dsp(nullptr) // presence node
, energywise(nullptr) // presence node
, entity_diag(nullptr) // presence node
, envmon(nullptr) // presence node
, errdisable(nullptr) // presence node
, ethernet(std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Ethernet>())
, firewall(nullptr) // presence node
, flash(nullptr) // presence node
, flex_links(nullptr) // presence node
, frame_relay(nullptr) // presence node
, ipsec(std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Ipsec>())
, isakmp(std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Isakmp>())
, isdn(nullptr) // presence node
, l2tc(nullptr) // presence node
, l2tun(std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::L2tun>())
, license(nullptr) // presence node
, mac_notification(nullptr) // presence node
, mac_notification2(nullptr) // presence node
, memory(nullptr) // presence node
, mpls(nullptr) // presence node
, nhrp(nullptr) // presence node
, ospf(std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Ospf>())
, pim(nullptr) // presence node
, plogd(nullptr) // presence node
, port_security(nullptr) // presence node
, power_ethernet(std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::PowerEthernet>())
, pw(nullptr) // presence node
, slb(nullptr) // presence node
, snmp(std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Snmp>())
, stackwise(nullptr) // presence node
, stpx(nullptr) // presence node
, transceiver(std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Transceiver>())
, udld(nullptr) // presence node
, vrfmib(std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Vrfmib>())
, vstack(nullptr) // presence node
, wireless(nullptr) // presence node
{
ospfv3->parent = this;
ike->parent = this;
atm->parent = this;
bgp_conf->parent = this;
cef->parent = this;
dot1x->parent = this;
ethernet->parent = this;
ipsec->parent = this;
isakmp->parent = this;
l2tun->parent = this;
ospf->parent = this;
power_ethernet->parent = this;
snmp->parent = this;
transceiver->parent = this;
vrfmib->parent = this;
yang_name = "traps"; yang_parent_name = "enable-choice"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true;
}
Native::SnmpServer::Enable::EnableChoice::Traps::~Traps()
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::has_data() const
{
if (is_presence_container) return true;
return aaa_server.is_set
|| local_auth.is_set
|| authenticate_fail.is_set
|| bfd.is_set
|| bgp.is_set
|| bstun.is_set
|| c2900.is_set
|| casa.is_set
|| ccme.is_set
|| cluster.is_set
|| channel.is_set
|| chassis.is_set
|| cnpd.is_set
|| config.is_set
|| copy_config.is_set
|| config_copy.is_set
|| config_ctid.is_set
|| cpu_threshold.is_set
|| dial.is_set
|| director.is_set
|| dlsw.is_set
|| deauthenticate.is_set
|| disassociate.is_set
|| dnis.is_set
|| dot11_qos.is_set
|| ds0_busyout.is_set
|| ds1.is_set
|| ds1_loopback.is_set
|| ds3.is_set
|| dhcp.is_set
|| eigrp.is_set
|| entity_.is_set
|| ether_oam.is_set
|| event_manager.is_set
|| flowmon.is_set
|| fru_ctrl.is_set
|| gatekeeper.is_set
|| hsrp.is_set
|| icsudsu.is_set
|| ima.is_set
|| ipmobile.is_set
|| ipmulticast.is_set
|| ipsla.is_set
|| isis.is_set
|| module.is_set
|| msdp.is_set
|| mvpn.is_set
|| pppoe.is_set
|| rep.is_set
|| resource_policy.is_set
|| rf.is_set
|| rogue_ap.is_set
|| rsvp.is_set
|| rtr.is_set
|| sonet.is_set
|| srst.is_set
|| srp.is_set
|| stun.is_set
|| switch_over.is_set
|| syslog.is_set
|| tty.is_set
|| vlancreate.is_set
|| vlandelete.is_set
|| vlan_mac_limit.is_set
|| vlan_membership.is_set
|| voice.is_set
|| vrrp.is_set
|| vsimaster.is_set
|| vtp.is_set
|| wlan_wep.is_set
|| xgcp.is_set
|| (trustsec_sxp != nullptr && trustsec_sxp->has_data())
|| (vswitch != nullptr && vswitch->has_data())
|| (trustsec_server != nullptr && trustsec_server->has_data())
|| (trustsec != nullptr && trustsec->has_data())
|| (trustsec_interface != nullptr && trustsec_interface->has_data())
|| (trustsec_policy != nullptr && trustsec_policy->has_data())
|| (ospfv3 != nullptr && ospfv3->has_data())
|| (ike != nullptr && ike->has_data())
|| (alarms != nullptr && alarms->has_data())
|| (atm != nullptr && atm->has_data())
|| (auth_framework != nullptr && auth_framework->has_data())
|| (bgp_conf != nullptr && bgp_conf->has_data())
|| (bridge != nullptr && bridge->has_data())
|| (bulkstat != nullptr && bulkstat->has_data())
|| (call_home != nullptr && call_home->has_data())
|| (c6kxbar != nullptr && c6kxbar->has_data())
|| (cef != nullptr && cef->has_data())
|| (cpu != nullptr && cpu->has_data())
|| (csg != nullptr && csg->has_data())
|| (dot1x != nullptr && dot1x->has_data())
|| (dsp != nullptr && dsp->has_data())
|| (energywise != nullptr && energywise->has_data())
|| (entity_diag != nullptr && entity_diag->has_data())
|| (envmon != nullptr && envmon->has_data())
|| (errdisable != nullptr && errdisable->has_data())
|| (ethernet != nullptr && ethernet->has_data())
|| (firewall != nullptr && firewall->has_data())
|| (flash != nullptr && flash->has_data())
|| (flex_links != nullptr && flex_links->has_data())
|| (frame_relay != nullptr && frame_relay->has_data())
|| (ipsec != nullptr && ipsec->has_data())
|| (isakmp != nullptr && isakmp->has_data())
|| (isdn != nullptr && isdn->has_data())
|| (l2tc != nullptr && l2tc->has_data())
|| (l2tun != nullptr && l2tun->has_data())
|| (license != nullptr && license->has_data())
|| (mac_notification != nullptr && mac_notification->has_data())
|| (mac_notification2 != nullptr && mac_notification2->has_data())
|| (memory != nullptr && memory->has_data())
|| (mpls != nullptr && mpls->has_data())
|| (nhrp != nullptr && nhrp->has_data())
|| (ospf != nullptr && ospf->has_data())
|| (pim != nullptr && pim->has_data())
|| (plogd != nullptr && plogd->has_data())
|| (port_security != nullptr && port_security->has_data())
|| (power_ethernet != nullptr && power_ethernet->has_data())
|| (pw != nullptr && pw->has_data())
|| (slb != nullptr && slb->has_data())
|| (snmp != nullptr && snmp->has_data())
|| (stackwise != nullptr && stackwise->has_data())
|| (stpx != nullptr && stpx->has_data())
|| (transceiver != nullptr && transceiver->has_data())
|| (udld != nullptr && udld->has_data())
|| (vrfmib != nullptr && vrfmib->has_data())
|| (vstack != nullptr && vstack->has_data())
|| (wireless != nullptr && wireless->has_data());
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(aaa_server.yfilter)
|| ydk::is_set(local_auth.yfilter)
|| ydk::is_set(authenticate_fail.yfilter)
|| ydk::is_set(bfd.yfilter)
|| ydk::is_set(bgp.yfilter)
|| ydk::is_set(bstun.yfilter)
|| ydk::is_set(c2900.yfilter)
|| ydk::is_set(casa.yfilter)
|| ydk::is_set(ccme.yfilter)
|| ydk::is_set(cluster.yfilter)
|| ydk::is_set(channel.yfilter)
|| ydk::is_set(chassis.yfilter)
|| ydk::is_set(cnpd.yfilter)
|| ydk::is_set(config.yfilter)
|| ydk::is_set(copy_config.yfilter)
|| ydk::is_set(config_copy.yfilter)
|| ydk::is_set(config_ctid.yfilter)
|| ydk::is_set(cpu_threshold.yfilter)
|| ydk::is_set(dial.yfilter)
|| ydk::is_set(director.yfilter)
|| ydk::is_set(dlsw.yfilter)
|| ydk::is_set(deauthenticate.yfilter)
|| ydk::is_set(disassociate.yfilter)
|| ydk::is_set(dnis.yfilter)
|| ydk::is_set(dot11_qos.yfilter)
|| ydk::is_set(ds0_busyout.yfilter)
|| ydk::is_set(ds1.yfilter)
|| ydk::is_set(ds1_loopback.yfilter)
|| ydk::is_set(ds3.yfilter)
|| ydk::is_set(dhcp.yfilter)
|| ydk::is_set(eigrp.yfilter)
|| ydk::is_set(entity_.yfilter)
|| ydk::is_set(ether_oam.yfilter)
|| ydk::is_set(event_manager.yfilter)
|| ydk::is_set(flowmon.yfilter)
|| ydk::is_set(fru_ctrl.yfilter)
|| ydk::is_set(gatekeeper.yfilter)
|| ydk::is_set(hsrp.yfilter)
|| ydk::is_set(icsudsu.yfilter)
|| ydk::is_set(ima.yfilter)
|| ydk::is_set(ipmobile.yfilter)
|| ydk::is_set(ipmulticast.yfilter)
|| ydk::is_set(ipsla.yfilter)
|| ydk::is_set(isis.yfilter)
|| ydk::is_set(module.yfilter)
|| ydk::is_set(msdp.yfilter)
|| ydk::is_set(mvpn.yfilter)
|| ydk::is_set(pppoe.yfilter)
|| ydk::is_set(rep.yfilter)
|| ydk::is_set(resource_policy.yfilter)
|| ydk::is_set(rf.yfilter)
|| ydk::is_set(rogue_ap.yfilter)
|| ydk::is_set(rsvp.yfilter)
|| ydk::is_set(rtr.yfilter)
|| ydk::is_set(sonet.yfilter)
|| ydk::is_set(srst.yfilter)
|| ydk::is_set(srp.yfilter)
|| ydk::is_set(stun.yfilter)
|| ydk::is_set(switch_over.yfilter)
|| ydk::is_set(syslog.yfilter)
|| ydk::is_set(tty.yfilter)
|| ydk::is_set(vlancreate.yfilter)
|| ydk::is_set(vlandelete.yfilter)
|| ydk::is_set(vlan_mac_limit.yfilter)
|| ydk::is_set(vlan_membership.yfilter)
|| ydk::is_set(voice.yfilter)
|| ydk::is_set(vrrp.yfilter)
|| ydk::is_set(vsimaster.yfilter)
|| ydk::is_set(vtp.yfilter)
|| ydk::is_set(wlan_wep.yfilter)
|| ydk::is_set(xgcp.yfilter)
|| (trustsec_sxp != nullptr && trustsec_sxp->has_operation())
|| (vswitch != nullptr && vswitch->has_operation())
|| (trustsec_server != nullptr && trustsec_server->has_operation())
|| (trustsec != nullptr && trustsec->has_operation())
|| (trustsec_interface != nullptr && trustsec_interface->has_operation())
|| (trustsec_policy != nullptr && trustsec_policy->has_operation())
|| (ospfv3 != nullptr && ospfv3->has_operation())
|| (ike != nullptr && ike->has_operation())
|| (alarms != nullptr && alarms->has_operation())
|| (atm != nullptr && atm->has_operation())
|| (auth_framework != nullptr && auth_framework->has_operation())
|| (bgp_conf != nullptr && bgp_conf->has_operation())
|| (bridge != nullptr && bridge->has_operation())
|| (bulkstat != nullptr && bulkstat->has_operation())
|| (call_home != nullptr && call_home->has_operation())
|| (c6kxbar != nullptr && c6kxbar->has_operation())
|| (cef != nullptr && cef->has_operation())
|| (cpu != nullptr && cpu->has_operation())
|| (csg != nullptr && csg->has_operation())
|| (dot1x != nullptr && dot1x->has_operation())
|| (dsp != nullptr && dsp->has_operation())
|| (energywise != nullptr && energywise->has_operation())
|| (entity_diag != nullptr && entity_diag->has_operation())
|| (envmon != nullptr && envmon->has_operation())
|| (errdisable != nullptr && errdisable->has_operation())
|| (ethernet != nullptr && ethernet->has_operation())
|| (firewall != nullptr && firewall->has_operation())
|| (flash != nullptr && flash->has_operation())
|| (flex_links != nullptr && flex_links->has_operation())
|| (frame_relay != nullptr && frame_relay->has_operation())
|| (ipsec != nullptr && ipsec->has_operation())
|| (isakmp != nullptr && isakmp->has_operation())
|| (isdn != nullptr && isdn->has_operation())
|| (l2tc != nullptr && l2tc->has_operation())
|| (l2tun != nullptr && l2tun->has_operation())
|| (license != nullptr && license->has_operation())
|| (mac_notification != nullptr && mac_notification->has_operation())
|| (mac_notification2 != nullptr && mac_notification2->has_operation())
|| (memory != nullptr && memory->has_operation())
|| (mpls != nullptr && mpls->has_operation())
|| (nhrp != nullptr && nhrp->has_operation())
|| (ospf != nullptr && ospf->has_operation())
|| (pim != nullptr && pim->has_operation())
|| (plogd != nullptr && plogd->has_operation())
|| (port_security != nullptr && port_security->has_operation())
|| (power_ethernet != nullptr && power_ethernet->has_operation())
|| (pw != nullptr && pw->has_operation())
|| (slb != nullptr && slb->has_operation())
|| (snmp != nullptr && snmp->has_operation())
|| (stackwise != nullptr && stackwise->has_operation())
|| (stpx != nullptr && stpx->has_operation())
|| (transceiver != nullptr && transceiver->has_operation())
|| (udld != nullptr && udld->has_operation())
|| (vrfmib != nullptr && vrfmib->has_operation())
|| (vstack != nullptr && vstack->has_operation())
|| (wireless != nullptr && wireless->has_operation());
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/Cisco-IOS-XE-snmp:enable/enable-choice/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "traps";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Enable::EnableChoice::Traps::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (aaa_server.is_set || is_set(aaa_server.yfilter)) leaf_name_data.push_back(aaa_server.get_name_leafdata());
if (local_auth.is_set || is_set(local_auth.yfilter)) leaf_name_data.push_back(local_auth.get_name_leafdata());
if (authenticate_fail.is_set || is_set(authenticate_fail.yfilter)) leaf_name_data.push_back(authenticate_fail.get_name_leafdata());
if (bfd.is_set || is_set(bfd.yfilter)) leaf_name_data.push_back(bfd.get_name_leafdata());
if (bgp.is_set || is_set(bgp.yfilter)) leaf_name_data.push_back(bgp.get_name_leafdata());
if (bstun.is_set || is_set(bstun.yfilter)) leaf_name_data.push_back(bstun.get_name_leafdata());
if (c2900.is_set || is_set(c2900.yfilter)) leaf_name_data.push_back(c2900.get_name_leafdata());
if (casa.is_set || is_set(casa.yfilter)) leaf_name_data.push_back(casa.get_name_leafdata());
if (ccme.is_set || is_set(ccme.yfilter)) leaf_name_data.push_back(ccme.get_name_leafdata());
if (cluster.is_set || is_set(cluster.yfilter)) leaf_name_data.push_back(cluster.get_name_leafdata());
if (channel.is_set || is_set(channel.yfilter)) leaf_name_data.push_back(channel.get_name_leafdata());
if (chassis.is_set || is_set(chassis.yfilter)) leaf_name_data.push_back(chassis.get_name_leafdata());
if (cnpd.is_set || is_set(cnpd.yfilter)) leaf_name_data.push_back(cnpd.get_name_leafdata());
if (config.is_set || is_set(config.yfilter)) leaf_name_data.push_back(config.get_name_leafdata());
if (copy_config.is_set || is_set(copy_config.yfilter)) leaf_name_data.push_back(copy_config.get_name_leafdata());
if (config_copy.is_set || is_set(config_copy.yfilter)) leaf_name_data.push_back(config_copy.get_name_leafdata());
if (config_ctid.is_set || is_set(config_ctid.yfilter)) leaf_name_data.push_back(config_ctid.get_name_leafdata());
if (cpu_threshold.is_set || is_set(cpu_threshold.yfilter)) leaf_name_data.push_back(cpu_threshold.get_name_leafdata());
if (dial.is_set || is_set(dial.yfilter)) leaf_name_data.push_back(dial.get_name_leafdata());
if (director.is_set || is_set(director.yfilter)) leaf_name_data.push_back(director.get_name_leafdata());
if (dlsw.is_set || is_set(dlsw.yfilter)) leaf_name_data.push_back(dlsw.get_name_leafdata());
if (deauthenticate.is_set || is_set(deauthenticate.yfilter)) leaf_name_data.push_back(deauthenticate.get_name_leafdata());
if (disassociate.is_set || is_set(disassociate.yfilter)) leaf_name_data.push_back(disassociate.get_name_leafdata());
if (dnis.is_set || is_set(dnis.yfilter)) leaf_name_data.push_back(dnis.get_name_leafdata());
if (dot11_qos.is_set || is_set(dot11_qos.yfilter)) leaf_name_data.push_back(dot11_qos.get_name_leafdata());
if (ds0_busyout.is_set || is_set(ds0_busyout.yfilter)) leaf_name_data.push_back(ds0_busyout.get_name_leafdata());
if (ds1.is_set || is_set(ds1.yfilter)) leaf_name_data.push_back(ds1.get_name_leafdata());
if (ds1_loopback.is_set || is_set(ds1_loopback.yfilter)) leaf_name_data.push_back(ds1_loopback.get_name_leafdata());
if (ds3.is_set || is_set(ds3.yfilter)) leaf_name_data.push_back(ds3.get_name_leafdata());
if (dhcp.is_set || is_set(dhcp.yfilter)) leaf_name_data.push_back(dhcp.get_name_leafdata());
if (eigrp.is_set || is_set(eigrp.yfilter)) leaf_name_data.push_back(eigrp.get_name_leafdata());
if (entity_.is_set || is_set(entity_.yfilter)) leaf_name_data.push_back(entity_.get_name_leafdata());
if (ether_oam.is_set || is_set(ether_oam.yfilter)) leaf_name_data.push_back(ether_oam.get_name_leafdata());
if (event_manager.is_set || is_set(event_manager.yfilter)) leaf_name_data.push_back(event_manager.get_name_leafdata());
if (flowmon.is_set || is_set(flowmon.yfilter)) leaf_name_data.push_back(flowmon.get_name_leafdata());
if (fru_ctrl.is_set || is_set(fru_ctrl.yfilter)) leaf_name_data.push_back(fru_ctrl.get_name_leafdata());
if (gatekeeper.is_set || is_set(gatekeeper.yfilter)) leaf_name_data.push_back(gatekeeper.get_name_leafdata());
if (hsrp.is_set || is_set(hsrp.yfilter)) leaf_name_data.push_back(hsrp.get_name_leafdata());
if (icsudsu.is_set || is_set(icsudsu.yfilter)) leaf_name_data.push_back(icsudsu.get_name_leafdata());
if (ima.is_set || is_set(ima.yfilter)) leaf_name_data.push_back(ima.get_name_leafdata());
if (ipmobile.is_set || is_set(ipmobile.yfilter)) leaf_name_data.push_back(ipmobile.get_name_leafdata());
if (ipmulticast.is_set || is_set(ipmulticast.yfilter)) leaf_name_data.push_back(ipmulticast.get_name_leafdata());
if (ipsla.is_set || is_set(ipsla.yfilter)) leaf_name_data.push_back(ipsla.get_name_leafdata());
if (isis.is_set || is_set(isis.yfilter)) leaf_name_data.push_back(isis.get_name_leafdata());
if (module.is_set || is_set(module.yfilter)) leaf_name_data.push_back(module.get_name_leafdata());
if (msdp.is_set || is_set(msdp.yfilter)) leaf_name_data.push_back(msdp.get_name_leafdata());
if (mvpn.is_set || is_set(mvpn.yfilter)) leaf_name_data.push_back(mvpn.get_name_leafdata());
if (pppoe.is_set || is_set(pppoe.yfilter)) leaf_name_data.push_back(pppoe.get_name_leafdata());
if (rep.is_set || is_set(rep.yfilter)) leaf_name_data.push_back(rep.get_name_leafdata());
if (resource_policy.is_set || is_set(resource_policy.yfilter)) leaf_name_data.push_back(resource_policy.get_name_leafdata());
if (rf.is_set || is_set(rf.yfilter)) leaf_name_data.push_back(rf.get_name_leafdata());
if (rogue_ap.is_set || is_set(rogue_ap.yfilter)) leaf_name_data.push_back(rogue_ap.get_name_leafdata());
if (rsvp.is_set || is_set(rsvp.yfilter)) leaf_name_data.push_back(rsvp.get_name_leafdata());
if (rtr.is_set || is_set(rtr.yfilter)) leaf_name_data.push_back(rtr.get_name_leafdata());
if (sonet.is_set || is_set(sonet.yfilter)) leaf_name_data.push_back(sonet.get_name_leafdata());
if (srst.is_set || is_set(srst.yfilter)) leaf_name_data.push_back(srst.get_name_leafdata());
if (srp.is_set || is_set(srp.yfilter)) leaf_name_data.push_back(srp.get_name_leafdata());
if (stun.is_set || is_set(stun.yfilter)) leaf_name_data.push_back(stun.get_name_leafdata());
if (switch_over.is_set || is_set(switch_over.yfilter)) leaf_name_data.push_back(switch_over.get_name_leafdata());
if (syslog.is_set || is_set(syslog.yfilter)) leaf_name_data.push_back(syslog.get_name_leafdata());
if (tty.is_set || is_set(tty.yfilter)) leaf_name_data.push_back(tty.get_name_leafdata());
if (vlancreate.is_set || is_set(vlancreate.yfilter)) leaf_name_data.push_back(vlancreate.get_name_leafdata());
if (vlandelete.is_set || is_set(vlandelete.yfilter)) leaf_name_data.push_back(vlandelete.get_name_leafdata());
if (vlan_mac_limit.is_set || is_set(vlan_mac_limit.yfilter)) leaf_name_data.push_back(vlan_mac_limit.get_name_leafdata());
if (vlan_membership.is_set || is_set(vlan_membership.yfilter)) leaf_name_data.push_back(vlan_membership.get_name_leafdata());
if (voice.is_set || is_set(voice.yfilter)) leaf_name_data.push_back(voice.get_name_leafdata());
if (vrrp.is_set || is_set(vrrp.yfilter)) leaf_name_data.push_back(vrrp.get_name_leafdata());
if (vsimaster.is_set || is_set(vsimaster.yfilter)) leaf_name_data.push_back(vsimaster.get_name_leafdata());
if (vtp.is_set || is_set(vtp.yfilter)) leaf_name_data.push_back(vtp.get_name_leafdata());
if (wlan_wep.is_set || is_set(wlan_wep.yfilter)) leaf_name_data.push_back(wlan_wep.get_name_leafdata());
if (xgcp.is_set || is_set(xgcp.yfilter)) leaf_name_data.push_back(xgcp.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Enable::EnableChoice::Traps::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "trustsec-sxp")
{
if(trustsec_sxp == nullptr)
{
trustsec_sxp = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecSxp>();
}
return trustsec_sxp;
}
if(child_yang_name == "vswitch")
{
if(vswitch == nullptr)
{
vswitch = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Vswitch>();
}
return vswitch;
}
if(child_yang_name == "trustsec-server")
{
if(trustsec_server == nullptr)
{
trustsec_server = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecServer>();
}
return trustsec_server;
}
if(child_yang_name == "trustsec")
{
if(trustsec == nullptr)
{
trustsec = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec>();
}
return trustsec;
}
if(child_yang_name == "trustsec-interface")
{
if(trustsec_interface == nullptr)
{
trustsec_interface = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface>();
}
return trustsec_interface;
}
if(child_yang_name == "trustsec-policy")
{
if(trustsec_policy == nullptr)
{
trustsec_policy = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecPolicy>();
}
return trustsec_policy;
}
if(child_yang_name == "ospfv3")
{
if(ospfv3 == nullptr)
{
ospfv3 = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Ospfv3>();
}
return ospfv3;
}
if(child_yang_name == "ike")
{
if(ike == nullptr)
{
ike = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Ike>();
}
return ike;
}
if(child_yang_name == "alarms")
{
if(alarms == nullptr)
{
alarms = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Alarms>();
}
return alarms;
}
if(child_yang_name == "atm")
{
if(atm == nullptr)
{
atm = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Atm>();
}
return atm;
}
if(child_yang_name == "auth-framework")
{
if(auth_framework == nullptr)
{
auth_framework = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::AuthFramework>();
}
return auth_framework;
}
if(child_yang_name == "bgp-conf")
{
if(bgp_conf == nullptr)
{
bgp_conf = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::BgpConf>();
}
return bgp_conf;
}
if(child_yang_name == "bridge")
{
if(bridge == nullptr)
{
bridge = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Bridge>();
}
return bridge;
}
if(child_yang_name == "bulkstat")
{
if(bulkstat == nullptr)
{
bulkstat = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Bulkstat>();
}
return bulkstat;
}
if(child_yang_name == "call-home")
{
if(call_home == nullptr)
{
call_home = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::CallHome>();
}
return call_home;
}
if(child_yang_name == "c6kxbar")
{
if(c6kxbar == nullptr)
{
c6kxbar = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::C6kxbar>();
}
return c6kxbar;
}
if(child_yang_name == "cef")
{
if(cef == nullptr)
{
cef = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Cef>();
}
return cef;
}
if(child_yang_name == "cpu")
{
if(cpu == nullptr)
{
cpu = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Cpu>();
}
return cpu;
}
if(child_yang_name == "csg")
{
if(csg == nullptr)
{
csg = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Csg>();
}
return csg;
}
if(child_yang_name == "dot1x")
{
if(dot1x == nullptr)
{
dot1x = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Dot1x>();
}
return dot1x;
}
if(child_yang_name == "dsp")
{
if(dsp == nullptr)
{
dsp = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Dsp>();
}
return dsp;
}
if(child_yang_name == "energywise")
{
if(energywise == nullptr)
{
energywise = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Energywise>();
}
return energywise;
}
if(child_yang_name == "entity-diag")
{
if(entity_diag == nullptr)
{
entity_diag = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::EntityDiag>();
}
return entity_diag;
}
if(child_yang_name == "envmon")
{
if(envmon == nullptr)
{
envmon = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Envmon>();
}
return envmon;
}
if(child_yang_name == "errdisable")
{
if(errdisable == nullptr)
{
errdisable = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Errdisable>();
}
return errdisable;
}
if(child_yang_name == "ethernet")
{
if(ethernet == nullptr)
{
ethernet = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Ethernet>();
}
return ethernet;
}
if(child_yang_name == "firewall")
{
if(firewall == nullptr)
{
firewall = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Firewall>();
}
return firewall;
}
if(child_yang_name == "flash")
{
if(flash == nullptr)
{
flash = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Flash>();
}
return flash;
}
if(child_yang_name == "flex-links")
{
if(flex_links == nullptr)
{
flex_links = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::FlexLinks>();
}
return flex_links;
}
if(child_yang_name == "frame-relay")
{
if(frame_relay == nullptr)
{
frame_relay = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::FrameRelay>();
}
return frame_relay;
}
if(child_yang_name == "ipsec")
{
if(ipsec == nullptr)
{
ipsec = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Ipsec>();
}
return ipsec;
}
if(child_yang_name == "isakmp")
{
if(isakmp == nullptr)
{
isakmp = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Isakmp>();
}
return isakmp;
}
if(child_yang_name == "isdn")
{
if(isdn == nullptr)
{
isdn = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Isdn>();
}
return isdn;
}
if(child_yang_name == "l2tc")
{
if(l2tc == nullptr)
{
l2tc = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::L2tc>();
}
return l2tc;
}
if(child_yang_name == "l2tun")
{
if(l2tun == nullptr)
{
l2tun = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::L2tun>();
}
return l2tun;
}
if(child_yang_name == "license")
{
if(license == nullptr)
{
license = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::License>();
}
return license;
}
if(child_yang_name == "mac-notification")
{
if(mac_notification == nullptr)
{
mac_notification = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::MacNotification>();
}
return mac_notification;
}
if(child_yang_name == "mac-notification2")
{
if(mac_notification2 == nullptr)
{
mac_notification2 = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::MacNotification2>();
}
return mac_notification2;
}
if(child_yang_name == "memory")
{
if(memory == nullptr)
{
memory = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Memory>();
}
return memory;
}
if(child_yang_name == "mpls")
{
if(mpls == nullptr)
{
mpls = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Mpls>();
}
return mpls;
}
if(child_yang_name == "nhrp")
{
if(nhrp == nullptr)
{
nhrp = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Nhrp>();
}
return nhrp;
}
if(child_yang_name == "ospf")
{
if(ospf == nullptr)
{
ospf = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Ospf>();
}
return ospf;
}
if(child_yang_name == "pim")
{
if(pim == nullptr)
{
pim = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Pim>();
}
return pim;
}
if(child_yang_name == "plogd")
{
if(plogd == nullptr)
{
plogd = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Plogd>();
}
return plogd;
}
if(child_yang_name == "port-security")
{
if(port_security == nullptr)
{
port_security = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::PortSecurity>();
}
return port_security;
}
if(child_yang_name == "power-ethernet")
{
if(power_ethernet == nullptr)
{
power_ethernet = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::PowerEthernet>();
}
return power_ethernet;
}
if(child_yang_name == "pw")
{
if(pw == nullptr)
{
pw = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Pw>();
}
return pw;
}
if(child_yang_name == "slb")
{
if(slb == nullptr)
{
slb = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Slb>();
}
return slb;
}
if(child_yang_name == "snmp")
{
if(snmp == nullptr)
{
snmp = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Snmp>();
}
return snmp;
}
if(child_yang_name == "stackwise")
{
if(stackwise == nullptr)
{
stackwise = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Stackwise>();
}
return stackwise;
}
if(child_yang_name == "stpx")
{
if(stpx == nullptr)
{
stpx = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Stpx>();
}
return stpx;
}
if(child_yang_name == "transceiver")
{
if(transceiver == nullptr)
{
transceiver = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Transceiver>();
}
return transceiver;
}
if(child_yang_name == "udld")
{
if(udld == nullptr)
{
udld = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Udld>();
}
return udld;
}
if(child_yang_name == "vrfmib")
{
if(vrfmib == nullptr)
{
vrfmib = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Vrfmib>();
}
return vrfmib;
}
if(child_yang_name == "vstack")
{
if(vstack == nullptr)
{
vstack = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Vstack>();
}
return vstack;
}
if(child_yang_name == "wireless")
{
if(wireless == nullptr)
{
wireless = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Wireless>();
}
return wireless;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Enable::EnableChoice::Traps::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(trustsec_sxp != nullptr)
{
_children["trustsec-sxp"] = trustsec_sxp;
}
if(vswitch != nullptr)
{
_children["vswitch"] = vswitch;
}
if(trustsec_server != nullptr)
{
_children["trustsec-server"] = trustsec_server;
}
if(trustsec != nullptr)
{
_children["trustsec"] = trustsec;
}
if(trustsec_interface != nullptr)
{
_children["trustsec-interface"] = trustsec_interface;
}
if(trustsec_policy != nullptr)
{
_children["trustsec-policy"] = trustsec_policy;
}
if(ospfv3 != nullptr)
{
_children["ospfv3"] = ospfv3;
}
if(ike != nullptr)
{
_children["ike"] = ike;
}
if(alarms != nullptr)
{
_children["alarms"] = alarms;
}
if(atm != nullptr)
{
_children["atm"] = atm;
}
if(auth_framework != nullptr)
{
_children["auth-framework"] = auth_framework;
}
if(bgp_conf != nullptr)
{
_children["bgp-conf"] = bgp_conf;
}
if(bridge != nullptr)
{
_children["bridge"] = bridge;
}
if(bulkstat != nullptr)
{
_children["bulkstat"] = bulkstat;
}
if(call_home != nullptr)
{
_children["call-home"] = call_home;
}
if(c6kxbar != nullptr)
{
_children["c6kxbar"] = c6kxbar;
}
if(cef != nullptr)
{
_children["cef"] = cef;
}
if(cpu != nullptr)
{
_children["cpu"] = cpu;
}
if(csg != nullptr)
{
_children["csg"] = csg;
}
if(dot1x != nullptr)
{
_children["dot1x"] = dot1x;
}
if(dsp != nullptr)
{
_children["dsp"] = dsp;
}
if(energywise != nullptr)
{
_children["energywise"] = energywise;
}
if(entity_diag != nullptr)
{
_children["entity-diag"] = entity_diag;
}
if(envmon != nullptr)
{
_children["envmon"] = envmon;
}
if(errdisable != nullptr)
{
_children["errdisable"] = errdisable;
}
if(ethernet != nullptr)
{
_children["ethernet"] = ethernet;
}
if(firewall != nullptr)
{
_children["firewall"] = firewall;
}
if(flash != nullptr)
{
_children["flash"] = flash;
}
if(flex_links != nullptr)
{
_children["flex-links"] = flex_links;
}
if(frame_relay != nullptr)
{
_children["frame-relay"] = frame_relay;
}
if(ipsec != nullptr)
{
_children["ipsec"] = ipsec;
}
if(isakmp != nullptr)
{
_children["isakmp"] = isakmp;
}
if(isdn != nullptr)
{
_children["isdn"] = isdn;
}
if(l2tc != nullptr)
{
_children["l2tc"] = l2tc;
}
if(l2tun != nullptr)
{
_children["l2tun"] = l2tun;
}
if(license != nullptr)
{
_children["license"] = license;
}
if(mac_notification != nullptr)
{
_children["mac-notification"] = mac_notification;
}
if(mac_notification2 != nullptr)
{
_children["mac-notification2"] = mac_notification2;
}
if(memory != nullptr)
{
_children["memory"] = memory;
}
if(mpls != nullptr)
{
_children["mpls"] = mpls;
}
if(nhrp != nullptr)
{
_children["nhrp"] = nhrp;
}
if(ospf != nullptr)
{
_children["ospf"] = ospf;
}
if(pim != nullptr)
{
_children["pim"] = pim;
}
if(plogd != nullptr)
{
_children["plogd"] = plogd;
}
if(port_security != nullptr)
{
_children["port-security"] = port_security;
}
if(power_ethernet != nullptr)
{
_children["power-ethernet"] = power_ethernet;
}
if(pw != nullptr)
{
_children["pw"] = pw;
}
if(slb != nullptr)
{
_children["slb"] = slb;
}
if(snmp != nullptr)
{
_children["snmp"] = snmp;
}
if(stackwise != nullptr)
{
_children["stackwise"] = stackwise;
}
if(stpx != nullptr)
{
_children["stpx"] = stpx;
}
if(transceiver != nullptr)
{
_children["transceiver"] = transceiver;
}
if(udld != nullptr)
{
_children["udld"] = udld;
}
if(vrfmib != nullptr)
{
_children["vrfmib"] = vrfmib;
}
if(vstack != nullptr)
{
_children["vstack"] = vstack;
}
if(wireless != nullptr)
{
_children["wireless"] = wireless;
}
return _children;
}
void Native::SnmpServer::Enable::EnableChoice::Traps::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "aaa_server")
{
aaa_server = value;
aaa_server.value_namespace = name_space;
aaa_server.value_namespace_prefix = name_space_prefix;
}
if(value_path == "local-auth")
{
local_auth = value;
local_auth.value_namespace = name_space;
local_auth.value_namespace_prefix = name_space_prefix;
}
if(value_path == "authenticate-fail")
{
authenticate_fail = value;
authenticate_fail.value_namespace = name_space;
authenticate_fail.value_namespace_prefix = name_space_prefix;
}
if(value_path == "bfd")
{
bfd = value;
bfd.value_namespace = name_space;
bfd.value_namespace_prefix = name_space_prefix;
}
if(value_path == "bgp")
{
bgp = value;
bgp.value_namespace = name_space;
bgp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "bstun")
{
bstun = value;
bstun.value_namespace = name_space;
bstun.value_namespace_prefix = name_space_prefix;
}
if(value_path == "c2900")
{
c2900 = value;
c2900.value_namespace = name_space;
c2900.value_namespace_prefix = name_space_prefix;
}
if(value_path == "casa")
{
casa = value;
casa.value_namespace = name_space;
casa.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ccme")
{
ccme = value;
ccme.value_namespace = name_space;
ccme.value_namespace_prefix = name_space_prefix;
}
if(value_path == "cluster")
{
cluster = value;
cluster.value_namespace = name_space;
cluster.value_namespace_prefix = name_space_prefix;
}
if(value_path == "channel")
{
channel = value;
channel.value_namespace = name_space;
channel.value_namespace_prefix = name_space_prefix;
}
if(value_path == "chassis")
{
chassis = value;
chassis.value_namespace = name_space;
chassis.value_namespace_prefix = name_space_prefix;
}
if(value_path == "cnpd")
{
cnpd = value;
cnpd.value_namespace = name_space;
cnpd.value_namespace_prefix = name_space_prefix;
}
if(value_path == "config")
{
config = value;
config.value_namespace = name_space;
config.value_namespace_prefix = name_space_prefix;
}
if(value_path == "copy-config")
{
copy_config = value;
copy_config.value_namespace = name_space;
copy_config.value_namespace_prefix = name_space_prefix;
}
if(value_path == "config-copy")
{
config_copy = value;
config_copy.value_namespace = name_space;
config_copy.value_namespace_prefix = name_space_prefix;
}
if(value_path == "config-ctid")
{
config_ctid = value;
config_ctid.value_namespace = name_space;
config_ctid.value_namespace_prefix = name_space_prefix;
}
if(value_path == "cpu_threshold")
{
cpu_threshold = value;
cpu_threshold.value_namespace = name_space;
cpu_threshold.value_namespace_prefix = name_space_prefix;
}
if(value_path == "dial")
{
dial = value;
dial.value_namespace = name_space;
dial.value_namespace_prefix = name_space_prefix;
}
if(value_path == "director")
{
director = value;
director.value_namespace = name_space;
director.value_namespace_prefix = name_space_prefix;
}
if(value_path == "dlsw")
{
dlsw = value;
dlsw.value_namespace = name_space;
dlsw.value_namespace_prefix = name_space_prefix;
}
if(value_path == "deauthenticate")
{
deauthenticate = value;
deauthenticate.value_namespace = name_space;
deauthenticate.value_namespace_prefix = name_space_prefix;
}
if(value_path == "disassociate")
{
disassociate = value;
disassociate.value_namespace = name_space;
disassociate.value_namespace_prefix = name_space_prefix;
}
if(value_path == "dnis")
{
dnis = value;
dnis.value_namespace = name_space;
dnis.value_namespace_prefix = name_space_prefix;
}
if(value_path == "dot11-qos")
{
dot11_qos = value;
dot11_qos.value_namespace = name_space;
dot11_qos.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ds0-busyout")
{
ds0_busyout = value;
ds0_busyout.value_namespace = name_space;
ds0_busyout.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ds1")
{
ds1 = value;
ds1.value_namespace = name_space;
ds1.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ds1-loopback")
{
ds1_loopback = value;
ds1_loopback.value_namespace = name_space;
ds1_loopback.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ds3")
{
ds3 = value;
ds3.value_namespace = name_space;
ds3.value_namespace_prefix = name_space_prefix;
}
if(value_path == "dhcp")
{
dhcp = value;
dhcp.value_namespace = name_space;
dhcp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "eigrp")
{
eigrp = value;
eigrp.value_namespace = name_space;
eigrp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "entity")
{
entity_ = value;
entity_.value_namespace = name_space;
entity_.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ether-oam")
{
ether_oam = value;
ether_oam.value_namespace = name_space;
ether_oam.value_namespace_prefix = name_space_prefix;
}
if(value_path == "event-manager")
{
event_manager = value;
event_manager.value_namespace = name_space;
event_manager.value_namespace_prefix = name_space_prefix;
}
if(value_path == "flowmon")
{
flowmon = value;
flowmon.value_namespace = name_space;
flowmon.value_namespace_prefix = name_space_prefix;
}
if(value_path == "fru-ctrl")
{
fru_ctrl = value;
fru_ctrl.value_namespace = name_space;
fru_ctrl.value_namespace_prefix = name_space_prefix;
}
if(value_path == "gatekeeper")
{
gatekeeper = value;
gatekeeper.value_namespace = name_space;
gatekeeper.value_namespace_prefix = name_space_prefix;
}
if(value_path == "hsrp")
{
hsrp = value;
hsrp.value_namespace = name_space;
hsrp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "icsudsu")
{
icsudsu = value;
icsudsu.value_namespace = name_space;
icsudsu.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ima")
{
ima = value;
ima.value_namespace = name_space;
ima.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ipmobile")
{
ipmobile = value;
ipmobile.value_namespace = name_space;
ipmobile.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ipmulticast")
{
ipmulticast = value;
ipmulticast.value_namespace = name_space;
ipmulticast.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ipsla")
{
ipsla = value;
ipsla.value_namespace = name_space;
ipsla.value_namespace_prefix = name_space_prefix;
}
if(value_path == "isis")
{
isis = value;
isis.value_namespace = name_space;
isis.value_namespace_prefix = name_space_prefix;
}
if(value_path == "module")
{
module = value;
module.value_namespace = name_space;
module.value_namespace_prefix = name_space_prefix;
}
if(value_path == "msdp")
{
msdp = value;
msdp.value_namespace = name_space;
msdp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "mvpn")
{
mvpn = value;
mvpn.value_namespace = name_space;
mvpn.value_namespace_prefix = name_space_prefix;
}
if(value_path == "pppoe")
{
pppoe = value;
pppoe.value_namespace = name_space;
pppoe.value_namespace_prefix = name_space_prefix;
}
if(value_path == "rep")
{
rep = value;
rep.value_namespace = name_space;
rep.value_namespace_prefix = name_space_prefix;
}
if(value_path == "resource-policy")
{
resource_policy = value;
resource_policy.value_namespace = name_space;
resource_policy.value_namespace_prefix = name_space_prefix;
}
if(value_path == "rf")
{
rf = value;
rf.value_namespace = name_space;
rf.value_namespace_prefix = name_space_prefix;
}
if(value_path == "rogue-ap")
{
rogue_ap = value;
rogue_ap.value_namespace = name_space;
rogue_ap.value_namespace_prefix = name_space_prefix;
}
if(value_path == "rsvp")
{
rsvp = value;
rsvp.value_namespace = name_space;
rsvp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "rtr")
{
rtr = value;
rtr.value_namespace = name_space;
rtr.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sonet")
{
sonet = value;
sonet.value_namespace = name_space;
sonet.value_namespace_prefix = name_space_prefix;
}
if(value_path == "srst")
{
srst = value;
srst.value_namespace = name_space;
srst.value_namespace_prefix = name_space_prefix;
}
if(value_path == "srp")
{
srp = value;
srp.value_namespace = name_space;
srp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "stun")
{
stun = value;
stun.value_namespace = name_space;
stun.value_namespace_prefix = name_space_prefix;
}
if(value_path == "switch-over")
{
switch_over = value;
switch_over.value_namespace = name_space;
switch_over.value_namespace_prefix = name_space_prefix;
}
if(value_path == "syslog")
{
syslog = value;
syslog.value_namespace = name_space;
syslog.value_namespace_prefix = name_space_prefix;
}
if(value_path == "tty")
{
tty = value;
tty.value_namespace = name_space;
tty.value_namespace_prefix = name_space_prefix;
}
if(value_path == "vlancreate")
{
vlancreate = value;
vlancreate.value_namespace = name_space;
vlancreate.value_namespace_prefix = name_space_prefix;
}
if(value_path == "vlandelete")
{
vlandelete = value;
vlandelete.value_namespace = name_space;
vlandelete.value_namespace_prefix = name_space_prefix;
}
if(value_path == "vlan-mac-limit")
{
vlan_mac_limit = value;
vlan_mac_limit.value_namespace = name_space;
vlan_mac_limit.value_namespace_prefix = name_space_prefix;
}
if(value_path == "vlan-membership")
{
vlan_membership = value;
vlan_membership.value_namespace = name_space;
vlan_membership.value_namespace_prefix = name_space_prefix;
}
if(value_path == "voice")
{
voice = value;
voice.value_namespace = name_space;
voice.value_namespace_prefix = name_space_prefix;
}
if(value_path == "vrrp")
{
vrrp = value;
vrrp.value_namespace = name_space;
vrrp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "vsimaster")
{
vsimaster = value;
vsimaster.value_namespace = name_space;
vsimaster.value_namespace_prefix = name_space_prefix;
}
if(value_path == "vtp")
{
vtp = value;
vtp.value_namespace = name_space;
vtp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "wlan-wep")
{
wlan_wep = value;
wlan_wep.value_namespace = name_space;
wlan_wep.value_namespace_prefix = name_space_prefix;
}
if(value_path == "xgcp")
{
xgcp = value;
xgcp.value_namespace = name_space;
xgcp.value_namespace_prefix = name_space_prefix;
}
}
void Native::SnmpServer::Enable::EnableChoice::Traps::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "aaa_server")
{
aaa_server.yfilter = yfilter;
}
if(value_path == "local-auth")
{
local_auth.yfilter = yfilter;
}
if(value_path == "authenticate-fail")
{
authenticate_fail.yfilter = yfilter;
}
if(value_path == "bfd")
{
bfd.yfilter = yfilter;
}
if(value_path == "bgp")
{
bgp.yfilter = yfilter;
}
if(value_path == "bstun")
{
bstun.yfilter = yfilter;
}
if(value_path == "c2900")
{
c2900.yfilter = yfilter;
}
if(value_path == "casa")
{
casa.yfilter = yfilter;
}
if(value_path == "ccme")
{
ccme.yfilter = yfilter;
}
if(value_path == "cluster")
{
cluster.yfilter = yfilter;
}
if(value_path == "channel")
{
channel.yfilter = yfilter;
}
if(value_path == "chassis")
{
chassis.yfilter = yfilter;
}
if(value_path == "cnpd")
{
cnpd.yfilter = yfilter;
}
if(value_path == "config")
{
config.yfilter = yfilter;
}
if(value_path == "copy-config")
{
copy_config.yfilter = yfilter;
}
if(value_path == "config-copy")
{
config_copy.yfilter = yfilter;
}
if(value_path == "config-ctid")
{
config_ctid.yfilter = yfilter;
}
if(value_path == "cpu_threshold")
{
cpu_threshold.yfilter = yfilter;
}
if(value_path == "dial")
{
dial.yfilter = yfilter;
}
if(value_path == "director")
{
director.yfilter = yfilter;
}
if(value_path == "dlsw")
{
dlsw.yfilter = yfilter;
}
if(value_path == "deauthenticate")
{
deauthenticate.yfilter = yfilter;
}
if(value_path == "disassociate")
{
disassociate.yfilter = yfilter;
}
if(value_path == "dnis")
{
dnis.yfilter = yfilter;
}
if(value_path == "dot11-qos")
{
dot11_qos.yfilter = yfilter;
}
if(value_path == "ds0-busyout")
{
ds0_busyout.yfilter = yfilter;
}
if(value_path == "ds1")
{
ds1.yfilter = yfilter;
}
if(value_path == "ds1-loopback")
{
ds1_loopback.yfilter = yfilter;
}
if(value_path == "ds3")
{
ds3.yfilter = yfilter;
}
if(value_path == "dhcp")
{
dhcp.yfilter = yfilter;
}
if(value_path == "eigrp")
{
eigrp.yfilter = yfilter;
}
if(value_path == "entity")
{
entity_.yfilter = yfilter;
}
if(value_path == "ether-oam")
{
ether_oam.yfilter = yfilter;
}
if(value_path == "event-manager")
{
event_manager.yfilter = yfilter;
}
if(value_path == "flowmon")
{
flowmon.yfilter = yfilter;
}
if(value_path == "fru-ctrl")
{
fru_ctrl.yfilter = yfilter;
}
if(value_path == "gatekeeper")
{
gatekeeper.yfilter = yfilter;
}
if(value_path == "hsrp")
{
hsrp.yfilter = yfilter;
}
if(value_path == "icsudsu")
{
icsudsu.yfilter = yfilter;
}
if(value_path == "ima")
{
ima.yfilter = yfilter;
}
if(value_path == "ipmobile")
{
ipmobile.yfilter = yfilter;
}
if(value_path == "ipmulticast")
{
ipmulticast.yfilter = yfilter;
}
if(value_path == "ipsla")
{
ipsla.yfilter = yfilter;
}
if(value_path == "isis")
{
isis.yfilter = yfilter;
}
if(value_path == "module")
{
module.yfilter = yfilter;
}
if(value_path == "msdp")
{
msdp.yfilter = yfilter;
}
if(value_path == "mvpn")
{
mvpn.yfilter = yfilter;
}
if(value_path == "pppoe")
{
pppoe.yfilter = yfilter;
}
if(value_path == "rep")
{
rep.yfilter = yfilter;
}
if(value_path == "resource-policy")
{
resource_policy.yfilter = yfilter;
}
if(value_path == "rf")
{
rf.yfilter = yfilter;
}
if(value_path == "rogue-ap")
{
rogue_ap.yfilter = yfilter;
}
if(value_path == "rsvp")
{
rsvp.yfilter = yfilter;
}
if(value_path == "rtr")
{
rtr.yfilter = yfilter;
}
if(value_path == "sonet")
{
sonet.yfilter = yfilter;
}
if(value_path == "srst")
{
srst.yfilter = yfilter;
}
if(value_path == "srp")
{
srp.yfilter = yfilter;
}
if(value_path == "stun")
{
stun.yfilter = yfilter;
}
if(value_path == "switch-over")
{
switch_over.yfilter = yfilter;
}
if(value_path == "syslog")
{
syslog.yfilter = yfilter;
}
if(value_path == "tty")
{
tty.yfilter = yfilter;
}
if(value_path == "vlancreate")
{
vlancreate.yfilter = yfilter;
}
if(value_path == "vlandelete")
{
vlandelete.yfilter = yfilter;
}
if(value_path == "vlan-mac-limit")
{
vlan_mac_limit.yfilter = yfilter;
}
if(value_path == "vlan-membership")
{
vlan_membership.yfilter = yfilter;
}
if(value_path == "voice")
{
voice.yfilter = yfilter;
}
if(value_path == "vrrp")
{
vrrp.yfilter = yfilter;
}
if(value_path == "vsimaster")
{
vsimaster.yfilter = yfilter;
}
if(value_path == "vtp")
{
vtp.yfilter = yfilter;
}
if(value_path == "wlan-wep")
{
wlan_wep.yfilter = yfilter;
}
if(value_path == "xgcp")
{
xgcp.yfilter = yfilter;
}
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "trustsec-sxp" || name == "vswitch" || name == "trustsec-server" || name == "trustsec" || name == "trustsec-interface" || name == "trustsec-policy" || name == "ospfv3" || name == "ike" || name == "alarms" || name == "atm" || name == "auth-framework" || name == "bgp-conf" || name == "bridge" || name == "bulkstat" || name == "call-home" || name == "c6kxbar" || name == "cef" || name == "cpu" || name == "csg" || name == "dot1x" || name == "dsp" || name == "energywise" || name == "entity-diag" || name == "envmon" || name == "errdisable" || name == "ethernet" || name == "firewall" || name == "flash" || name == "flex-links" || name == "frame-relay" || name == "ipsec" || name == "isakmp" || name == "isdn" || name == "l2tc" || name == "l2tun" || name == "license" || name == "mac-notification" || name == "mac-notification2" || name == "memory" || name == "mpls" || name == "nhrp" || name == "ospf" || name == "pim" || name == "plogd" || name == "port-security" || name == "power-ethernet" || name == "pw" || name == "slb" || name == "snmp" || name == "stackwise" || name == "stpx" || name == "transceiver" || name == "udld" || name == "vrfmib" || name == "vstack" || name == "wireless" || name == "aaa_server" || name == "local-auth" || name == "authenticate-fail" || name == "bfd" || name == "bgp" || name == "bstun" || name == "c2900" || name == "casa" || name == "ccme" || name == "cluster" || name == "channel" || name == "chassis" || name == "cnpd" || name == "config" || name == "copy-config" || name == "config-copy" || name == "config-ctid" || name == "cpu_threshold" || name == "dial" || name == "director" || name == "dlsw" || name == "deauthenticate" || name == "disassociate" || name == "dnis" || name == "dot11-qos" || name == "ds0-busyout" || name == "ds1" || name == "ds1-loopback" || name == "ds3" || name == "dhcp" || name == "eigrp" || name == "entity" || name == "ether-oam" || name == "event-manager" || name == "flowmon" || name == "fru-ctrl" || name == "gatekeeper" || name == "hsrp" || name == "icsudsu" || name == "ima" || name == "ipmobile" || name == "ipmulticast" || name == "ipsla" || name == "isis" || name == "module" || name == "msdp" || name == "mvpn" || name == "pppoe" || name == "rep" || name == "resource-policy" || name == "rf" || name == "rogue-ap" || name == "rsvp" || name == "rtr" || name == "sonet" || name == "srst" || name == "srp" || name == "stun" || name == "switch-over" || name == "syslog" || name == "tty" || name == "vlancreate" || name == "vlandelete" || name == "vlan-mac-limit" || name == "vlan-membership" || name == "voice" || name == "vrrp" || name == "vsimaster" || name == "vtp" || name == "wlan-wep" || name == "xgcp")
return true;
return false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecSxp::TrustsecSxp()
:
binding_conflict{YType::empty, "binding-conflict"},
binding_err{YType::empty, "binding-err"},
binding_expn_fail{YType::empty, "binding-expn-fail"},
conn_config_err{YType::empty, "conn-config-err"},
conn_down{YType::empty, "conn-down"},
conn_srcaddr_err{YType::empty, "conn-srcaddr-err"},
conn_up{YType::empty, "conn-up"},
msg_parse_err{YType::empty, "msg-parse-err"},
oper_nodeid_change{YType::empty, "oper-nodeid-change"}
{
yang_name = "trustsec-sxp"; yang_parent_name = "traps"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true;
}
Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecSxp::~TrustsecSxp()
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecSxp::has_data() const
{
if (is_presence_container) return true;
return binding_conflict.is_set
|| binding_err.is_set
|| binding_expn_fail.is_set
|| conn_config_err.is_set
|| conn_down.is_set
|| conn_srcaddr_err.is_set
|| conn_up.is_set
|| msg_parse_err.is_set
|| oper_nodeid_change.is_set;
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecSxp::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(binding_conflict.yfilter)
|| ydk::is_set(binding_err.yfilter)
|| ydk::is_set(binding_expn_fail.yfilter)
|| ydk::is_set(conn_config_err.yfilter)
|| ydk::is_set(conn_down.yfilter)
|| ydk::is_set(conn_srcaddr_err.yfilter)
|| ydk::is_set(conn_up.yfilter)
|| ydk::is_set(msg_parse_err.yfilter)
|| ydk::is_set(oper_nodeid_change.yfilter);
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecSxp::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/Cisco-IOS-XE-snmp:enable/enable-choice/traps/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecSxp::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "trustsec-sxp";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecSxp::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (binding_conflict.is_set || is_set(binding_conflict.yfilter)) leaf_name_data.push_back(binding_conflict.get_name_leafdata());
if (binding_err.is_set || is_set(binding_err.yfilter)) leaf_name_data.push_back(binding_err.get_name_leafdata());
if (binding_expn_fail.is_set || is_set(binding_expn_fail.yfilter)) leaf_name_data.push_back(binding_expn_fail.get_name_leafdata());
if (conn_config_err.is_set || is_set(conn_config_err.yfilter)) leaf_name_data.push_back(conn_config_err.get_name_leafdata());
if (conn_down.is_set || is_set(conn_down.yfilter)) leaf_name_data.push_back(conn_down.get_name_leafdata());
if (conn_srcaddr_err.is_set || is_set(conn_srcaddr_err.yfilter)) leaf_name_data.push_back(conn_srcaddr_err.get_name_leafdata());
if (conn_up.is_set || is_set(conn_up.yfilter)) leaf_name_data.push_back(conn_up.get_name_leafdata());
if (msg_parse_err.is_set || is_set(msg_parse_err.yfilter)) leaf_name_data.push_back(msg_parse_err.get_name_leafdata());
if (oper_nodeid_change.is_set || is_set(oper_nodeid_change.yfilter)) leaf_name_data.push_back(oper_nodeid_change.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecSxp::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecSxp::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecSxp::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "binding-conflict")
{
binding_conflict = value;
binding_conflict.value_namespace = name_space;
binding_conflict.value_namespace_prefix = name_space_prefix;
}
if(value_path == "binding-err")
{
binding_err = value;
binding_err.value_namespace = name_space;
binding_err.value_namespace_prefix = name_space_prefix;
}
if(value_path == "binding-expn-fail")
{
binding_expn_fail = value;
binding_expn_fail.value_namespace = name_space;
binding_expn_fail.value_namespace_prefix = name_space_prefix;
}
if(value_path == "conn-config-err")
{
conn_config_err = value;
conn_config_err.value_namespace = name_space;
conn_config_err.value_namespace_prefix = name_space_prefix;
}
if(value_path == "conn-down")
{
conn_down = value;
conn_down.value_namespace = name_space;
conn_down.value_namespace_prefix = name_space_prefix;
}
if(value_path == "conn-srcaddr-err")
{
conn_srcaddr_err = value;
conn_srcaddr_err.value_namespace = name_space;
conn_srcaddr_err.value_namespace_prefix = name_space_prefix;
}
if(value_path == "conn-up")
{
conn_up = value;
conn_up.value_namespace = name_space;
conn_up.value_namespace_prefix = name_space_prefix;
}
if(value_path == "msg-parse-err")
{
msg_parse_err = value;
msg_parse_err.value_namespace = name_space;
msg_parse_err.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper-nodeid-change")
{
oper_nodeid_change = value;
oper_nodeid_change.value_namespace = name_space;
oper_nodeid_change.value_namespace_prefix = name_space_prefix;
}
}
void Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecSxp::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "binding-conflict")
{
binding_conflict.yfilter = yfilter;
}
if(value_path == "binding-err")
{
binding_err.yfilter = yfilter;
}
if(value_path == "binding-expn-fail")
{
binding_expn_fail.yfilter = yfilter;
}
if(value_path == "conn-config-err")
{
conn_config_err.yfilter = yfilter;
}
if(value_path == "conn-down")
{
conn_down.yfilter = yfilter;
}
if(value_path == "conn-srcaddr-err")
{
conn_srcaddr_err.yfilter = yfilter;
}
if(value_path == "conn-up")
{
conn_up.yfilter = yfilter;
}
if(value_path == "msg-parse-err")
{
msg_parse_err.yfilter = yfilter;
}
if(value_path == "oper-nodeid-change")
{
oper_nodeid_change.yfilter = yfilter;
}
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecSxp::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "binding-conflict" || name == "binding-err" || name == "binding-expn-fail" || name == "conn-config-err" || name == "conn-down" || name == "conn-srcaddr-err" || name == "conn-up" || name == "msg-parse-err" || name == "oper-nodeid-change")
return true;
return false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Vswitch::Vswitch()
:
dual_active(nullptr) // presence node
{
yang_name = "vswitch"; yang_parent_name = "traps"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Vswitch::~Vswitch()
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Vswitch::has_data() const
{
if (is_presence_container) return true;
return (dual_active != nullptr && dual_active->has_data());
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Vswitch::has_operation() const
{
return is_set(yfilter)
|| (dual_active != nullptr && dual_active->has_operation());
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Vswitch::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/Cisco-IOS-XE-snmp:enable/enable-choice/traps/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Vswitch::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "vswitch";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Enable::EnableChoice::Traps::Vswitch::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Enable::EnableChoice::Traps::Vswitch::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "dual-active")
{
if(dual_active == nullptr)
{
dual_active = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Vswitch::DualActive>();
}
return dual_active;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Enable::EnableChoice::Traps::Vswitch::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(dual_active != nullptr)
{
_children["dual-active"] = dual_active;
}
return _children;
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Vswitch::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Vswitch::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Vswitch::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "dual-active")
return true;
return false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Vswitch::DualActive::DualActive()
:
vsl{YType::empty, "vsl"}
{
yang_name = "dual-active"; yang_parent_name = "vswitch"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Vswitch::DualActive::~DualActive()
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Vswitch::DualActive::has_data() const
{
if (is_presence_container) return true;
return vsl.is_set;
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Vswitch::DualActive::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(vsl.yfilter);
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Vswitch::DualActive::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/Cisco-IOS-XE-snmp:enable/enable-choice/traps/vswitch/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Vswitch::DualActive::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "dual-active";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Enable::EnableChoice::Traps::Vswitch::DualActive::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (vsl.is_set || is_set(vsl.yfilter)) leaf_name_data.push_back(vsl.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Enable::EnableChoice::Traps::Vswitch::DualActive::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Enable::EnableChoice::Traps::Vswitch::DualActive::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Vswitch::DualActive::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "vsl")
{
vsl = value;
vsl.value_namespace = name_space;
vsl.value_namespace_prefix = name_space_prefix;
}
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Vswitch::DualActive::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "vsl")
{
vsl.yfilter = yfilter;
}
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Vswitch::DualActive::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "vsl")
return true;
return false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecServer::TrustsecServer()
:
radius_server(nullptr) // presence node
{
yang_name = "trustsec-server"; yang_parent_name = "traps"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true;
}
Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecServer::~TrustsecServer()
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecServer::has_data() const
{
if (is_presence_container) return true;
return (radius_server != nullptr && radius_server->has_data());
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecServer::has_operation() const
{
return is_set(yfilter)
|| (radius_server != nullptr && radius_server->has_operation());
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecServer::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/Cisco-IOS-XE-snmp:enable/enable-choice/traps/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecServer::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "trustsec-server";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecServer::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecServer::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "radius-server")
{
if(radius_server == nullptr)
{
radius_server = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecServer::RadiusServer>();
}
return radius_server;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecServer::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(radius_server != nullptr)
{
_children["radius-server"] = radius_server;
}
return _children;
}
void Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecServer::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecServer::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecServer::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "radius-server")
return true;
return false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecServer::RadiusServer::RadiusServer()
:
provision_secret{YType::empty, "provision-secret"}
{
yang_name = "radius-server"; yang_parent_name = "trustsec-server"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true;
}
Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecServer::RadiusServer::~RadiusServer()
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecServer::RadiusServer::has_data() const
{
if (is_presence_container) return true;
return provision_secret.is_set;
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecServer::RadiusServer::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(provision_secret.yfilter);
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecServer::RadiusServer::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/Cisco-IOS-XE-snmp:enable/enable-choice/traps/trustsec-server/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecServer::RadiusServer::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "radius-server";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecServer::RadiusServer::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (provision_secret.is_set || is_set(provision_secret.yfilter)) leaf_name_data.push_back(provision_secret.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecServer::RadiusServer::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecServer::RadiusServer::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecServer::RadiusServer::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "provision-secret")
{
provision_secret = value;
provision_secret.value_namespace = name_space;
provision_secret.value_namespace_prefix = name_space_prefix;
}
}
void Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecServer::RadiusServer::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "provision-secret")
{
provision_secret.yfilter = yfilter;
}
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecServer::RadiusServer::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "provision-secret")
return true;
return false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::Trustsec()
:
authz_file_error(nullptr) // presence node
{
yang_name = "trustsec"; yang_parent_name = "traps"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::~Trustsec()
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::has_data() const
{
if (is_presence_container) return true;
return (authz_file_error != nullptr && authz_file_error->has_data());
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::has_operation() const
{
return is_set(yfilter)
|| (authz_file_error != nullptr && authz_file_error->has_operation());
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/Cisco-IOS-XE-snmp:enable/enable-choice/traps/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "trustsec";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "authz-file-error")
{
if(authz_file_error == nullptr)
{
authz_file_error = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError>();
}
return authz_file_error;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(authz_file_error != nullptr)
{
_children["authz-file-error"] = authz_file_error;
}
return _children;
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "authz-file-error")
return true;
return false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::AuthzFileError()
:
cache_file_error(nullptr) // presence node
{
yang_name = "authz-file-error"; yang_parent_name = "trustsec"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::~AuthzFileError()
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::has_data() const
{
if (is_presence_container) return true;
return (cache_file_error != nullptr && cache_file_error->has_data());
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::has_operation() const
{
return is_set(yfilter)
|| (cache_file_error != nullptr && cache_file_error->has_operation());
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/Cisco-IOS-XE-snmp:enable/enable-choice/traps/trustsec/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "authz-file-error";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "cache-file-error")
{
if(cache_file_error == nullptr)
{
cache_file_error = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError>();
}
return cache_file_error;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(cache_file_error != nullptr)
{
_children["cache-file-error"] = cache_file_error;
}
return _children;
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "cache-file-error")
return true;
return false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::CacheFileError()
:
keystore_file_error(nullptr) // presence node
{
yang_name = "cache-file-error"; yang_parent_name = "authz-file-error"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::~CacheFileError()
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::has_data() const
{
if (is_presence_container) return true;
return (keystore_file_error != nullptr && keystore_file_error->has_data());
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::has_operation() const
{
return is_set(yfilter)
|| (keystore_file_error != nullptr && keystore_file_error->has_operation());
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/Cisco-IOS-XE-snmp:enable/enable-choice/traps/trustsec/authz-file-error/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "cache-file-error";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "keystore-file-error")
{
if(keystore_file_error == nullptr)
{
keystore_file_error = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError>();
}
return keystore_file_error;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(keystore_file_error != nullptr)
{
_children["keystore-file-error"] = keystore_file_error;
}
return _children;
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "keystore-file-error")
return true;
return false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError::KeystoreFileError()
:
keystore_sync_fail(nullptr) // presence node
{
yang_name = "keystore-file-error"; yang_parent_name = "cache-file-error"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError::~KeystoreFileError()
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError::has_data() const
{
if (is_presence_container) return true;
return (keystore_sync_fail != nullptr && keystore_sync_fail->has_data());
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError::has_operation() const
{
return is_set(yfilter)
|| (keystore_sync_fail != nullptr && keystore_sync_fail->has_operation());
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/Cisco-IOS-XE-snmp:enable/enable-choice/traps/trustsec/authz-file-error/cache-file-error/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "keystore-file-error";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "keystore-sync-fail")
{
if(keystore_sync_fail == nullptr)
{
keystore_sync_fail = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError::KeystoreSyncFail>();
}
return keystore_sync_fail;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(keystore_sync_fail != nullptr)
{
_children["keystore-sync-fail"] = keystore_sync_fail;
}
return _children;
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "keystore-sync-fail")
return true;
return false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError::KeystoreSyncFail::KeystoreSyncFail()
:
random_number_fail(nullptr) // presence node
{
yang_name = "keystore-sync-fail"; yang_parent_name = "keystore-file-error"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError::KeystoreSyncFail::~KeystoreSyncFail()
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError::KeystoreSyncFail::has_data() const
{
if (is_presence_container) return true;
return (random_number_fail != nullptr && random_number_fail->has_data());
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError::KeystoreSyncFail::has_operation() const
{
return is_set(yfilter)
|| (random_number_fail != nullptr && random_number_fail->has_operation());
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError::KeystoreSyncFail::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/Cisco-IOS-XE-snmp:enable/enable-choice/traps/trustsec/authz-file-error/cache-file-error/keystore-file-error/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError::KeystoreSyncFail::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "keystore-sync-fail";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError::KeystoreSyncFail::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError::KeystoreSyncFail::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "random-number-fail")
{
if(random_number_fail == nullptr)
{
random_number_fail = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError::KeystoreSyncFail::RandomNumberFail>();
}
return random_number_fail;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError::KeystoreSyncFail::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(random_number_fail != nullptr)
{
_children["random-number-fail"] = random_number_fail;
}
return _children;
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError::KeystoreSyncFail::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError::KeystoreSyncFail::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError::KeystoreSyncFail::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "random-number-fail")
return true;
return false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError::KeystoreSyncFail::RandomNumberFail::RandomNumberFail()
:
src_entropy_fail{YType::empty, "src-entropy-fail"}
{
yang_name = "random-number-fail"; yang_parent_name = "keystore-sync-fail"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError::KeystoreSyncFail::RandomNumberFail::~RandomNumberFail()
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError::KeystoreSyncFail::RandomNumberFail::has_data() const
{
if (is_presence_container) return true;
return src_entropy_fail.is_set;
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError::KeystoreSyncFail::RandomNumberFail::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(src_entropy_fail.yfilter);
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError::KeystoreSyncFail::RandomNumberFail::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/Cisco-IOS-XE-snmp:enable/enable-choice/traps/trustsec/authz-file-error/cache-file-error/keystore-file-error/keystore-sync-fail/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError::KeystoreSyncFail::RandomNumberFail::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "random-number-fail";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError::KeystoreSyncFail::RandomNumberFail::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (src_entropy_fail.is_set || is_set(src_entropy_fail.yfilter)) leaf_name_data.push_back(src_entropy_fail.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError::KeystoreSyncFail::RandomNumberFail::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError::KeystoreSyncFail::RandomNumberFail::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError::KeystoreSyncFail::RandomNumberFail::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "src-entropy-fail")
{
src_entropy_fail = value;
src_entropy_fail.value_namespace = name_space;
src_entropy_fail.value_namespace_prefix = name_space_prefix;
}
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError::KeystoreSyncFail::RandomNumberFail::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "src-entropy-fail")
{
src_entropy_fail.yfilter = yfilter;
}
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Trustsec::AuthzFileError::CacheFileError::KeystoreFileError::KeystoreSyncFail::RandomNumberFail::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "src-entropy-fail")
return true;
return false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::TrustsecInterface()
:
unauthorized(nullptr) // presence node
{
yang_name = "trustsec-interface"; yang_parent_name = "traps"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true;
}
Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::~TrustsecInterface()
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::has_data() const
{
if (is_presence_container) return true;
return (unauthorized != nullptr && unauthorized->has_data());
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::has_operation() const
{
return is_set(yfilter)
|| (unauthorized != nullptr && unauthorized->has_operation());
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/Cisco-IOS-XE-snmp:enable/enable-choice/traps/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "trustsec-interface";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "unauthorized")
{
if(unauthorized == nullptr)
{
unauthorized = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized>();
}
return unauthorized;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(unauthorized != nullptr)
{
_children["unauthorized"] = unauthorized;
}
return _children;
}
void Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "unauthorized")
return true;
return false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::Unauthorized()
:
sap_fail(nullptr) // presence node
{
yang_name = "unauthorized"; yang_parent_name = "trustsec-interface"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true;
}
Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::~Unauthorized()
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::has_data() const
{
if (is_presence_container) return true;
return (sap_fail != nullptr && sap_fail->has_data());
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::has_operation() const
{
return is_set(yfilter)
|| (sap_fail != nullptr && sap_fail->has_operation());
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/Cisco-IOS-XE-snmp:enable/enable-choice/traps/trustsec-interface/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "unauthorized";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "sap-fail")
{
if(sap_fail == nullptr)
{
sap_fail = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail>();
}
return sap_fail;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(sap_fail != nullptr)
{
_children["sap-fail"] = sap_fail;
}
return _children;
}
void Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "sap-fail")
return true;
return false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail::SapFail()
:
authc_fail(nullptr) // presence node
{
yang_name = "sap-fail"; yang_parent_name = "unauthorized"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true;
}
Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail::~SapFail()
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail::has_data() const
{
if (is_presence_container) return true;
return (authc_fail != nullptr && authc_fail->has_data());
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail::has_operation() const
{
return is_set(yfilter)
|| (authc_fail != nullptr && authc_fail->has_operation());
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/Cisco-IOS-XE-snmp:enable/enable-choice/traps/trustsec-interface/unauthorized/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "sap-fail";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "authc-fail")
{
if(authc_fail == nullptr)
{
authc_fail = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail::AuthcFail>();
}
return authc_fail;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(authc_fail != nullptr)
{
_children["authc-fail"] = authc_fail;
}
return _children;
}
void Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "authc-fail")
return true;
return false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail::AuthcFail::AuthcFail()
:
supplicant_fail(nullptr) // presence node
{
yang_name = "authc-fail"; yang_parent_name = "sap-fail"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true;
}
Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail::AuthcFail::~AuthcFail()
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail::AuthcFail::has_data() const
{
if (is_presence_container) return true;
return (supplicant_fail != nullptr && supplicant_fail->has_data());
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail::AuthcFail::has_operation() const
{
return is_set(yfilter)
|| (supplicant_fail != nullptr && supplicant_fail->has_operation());
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail::AuthcFail::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/Cisco-IOS-XE-snmp:enable/enable-choice/traps/trustsec-interface/unauthorized/sap-fail/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail::AuthcFail::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "authc-fail";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail::AuthcFail::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail::AuthcFail::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "supplicant-fail")
{
if(supplicant_fail == nullptr)
{
supplicant_fail = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail::AuthcFail::SupplicantFail>();
}
return supplicant_fail;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail::AuthcFail::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(supplicant_fail != nullptr)
{
_children["supplicant-fail"] = supplicant_fail;
}
return _children;
}
void Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail::AuthcFail::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail::AuthcFail::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail::AuthcFail::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "supplicant-fail")
return true;
return false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail::AuthcFail::SupplicantFail::SupplicantFail()
:
authz_fail{YType::empty, "authz-fail"}
{
yang_name = "supplicant-fail"; yang_parent_name = "authc-fail"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true;
}
Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail::AuthcFail::SupplicantFail::~SupplicantFail()
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail::AuthcFail::SupplicantFail::has_data() const
{
if (is_presence_container) return true;
return authz_fail.is_set;
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail::AuthcFail::SupplicantFail::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(authz_fail.yfilter);
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail::AuthcFail::SupplicantFail::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/Cisco-IOS-XE-snmp:enable/enable-choice/traps/trustsec-interface/unauthorized/sap-fail/authc-fail/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail::AuthcFail::SupplicantFail::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "supplicant-fail";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail::AuthcFail::SupplicantFail::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (authz_fail.is_set || is_set(authz_fail.yfilter)) leaf_name_data.push_back(authz_fail.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail::AuthcFail::SupplicantFail::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail::AuthcFail::SupplicantFail::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail::AuthcFail::SupplicantFail::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "authz-fail")
{
authz_fail = value;
authz_fail.value_namespace = name_space;
authz_fail.value_namespace_prefix = name_space_prefix;
}
}
void Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail::AuthcFail::SupplicantFail::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "authz-fail")
{
authz_fail.yfilter = yfilter;
}
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecInterface::Unauthorized::SapFail::AuthcFail::SupplicantFail::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "authz-fail")
return true;
return false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecPolicy::TrustsecPolicy()
:
peer_policy_updated(nullptr) // presence node
{
yang_name = "trustsec-policy"; yang_parent_name = "traps"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true;
}
Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecPolicy::~TrustsecPolicy()
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecPolicy::has_data() const
{
if (is_presence_container) return true;
return (peer_policy_updated != nullptr && peer_policy_updated->has_data());
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecPolicy::has_operation() const
{
return is_set(yfilter)
|| (peer_policy_updated != nullptr && peer_policy_updated->has_operation());
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecPolicy::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/Cisco-IOS-XE-snmp:enable/enable-choice/traps/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecPolicy::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "trustsec-policy";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecPolicy::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecPolicy::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "peer-policy-updated")
{
if(peer_policy_updated == nullptr)
{
peer_policy_updated = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecPolicy::PeerPolicyUpdated>();
}
return peer_policy_updated;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecPolicy::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(peer_policy_updated != nullptr)
{
_children["peer-policy-updated"] = peer_policy_updated;
}
return _children;
}
void Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecPolicy::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecPolicy::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecPolicy::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "peer-policy-updated")
return true;
return false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecPolicy::PeerPolicyUpdated::PeerPolicyUpdated()
:
authz_sgacl_fail{YType::empty, "authz-sgacl-fail"}
{
yang_name = "peer-policy-updated"; yang_parent_name = "trustsec-policy"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true;
}
Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecPolicy::PeerPolicyUpdated::~PeerPolicyUpdated()
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecPolicy::PeerPolicyUpdated::has_data() const
{
if (is_presence_container) return true;
return authz_sgacl_fail.is_set;
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecPolicy::PeerPolicyUpdated::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(authz_sgacl_fail.yfilter);
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecPolicy::PeerPolicyUpdated::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/Cisco-IOS-XE-snmp:enable/enable-choice/traps/trustsec-policy/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecPolicy::PeerPolicyUpdated::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "peer-policy-updated";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecPolicy::PeerPolicyUpdated::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (authz_sgacl_fail.is_set || is_set(authz_sgacl_fail.yfilter)) leaf_name_data.push_back(authz_sgacl_fail.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecPolicy::PeerPolicyUpdated::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecPolicy::PeerPolicyUpdated::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecPolicy::PeerPolicyUpdated::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "authz-sgacl-fail")
{
authz_sgacl_fail = value;
authz_sgacl_fail.value_namespace = name_space;
authz_sgacl_fail.value_namespace_prefix = name_space_prefix;
}
}
void Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecPolicy::PeerPolicyUpdated::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "authz-sgacl-fail")
{
authz_sgacl_fail.yfilter = yfilter;
}
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::TrustsecPolicy::PeerPolicyUpdated::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "authz-sgacl-fail")
return true;
return false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Ospfv3::Ospfv3()
:
state_change{YType::empty, "state-change"},
errors{YType::empty, "errors"}
{
yang_name = "ospfv3"; yang_parent_name = "traps"; is_top_level_class = false; has_list_ancestor = false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Ospfv3::~Ospfv3()
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Ospfv3::has_data() const
{
if (is_presence_container) return true;
return state_change.is_set
|| errors.is_set;
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Ospfv3::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(state_change.yfilter)
|| ydk::is_set(errors.yfilter);
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Ospfv3::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/Cisco-IOS-XE-snmp:enable/enable-choice/traps/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Ospfv3::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "ospfv3";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Enable::EnableChoice::Traps::Ospfv3::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (state_change.is_set || is_set(state_change.yfilter)) leaf_name_data.push_back(state_change.get_name_leafdata());
if (errors.is_set || is_set(errors.yfilter)) leaf_name_data.push_back(errors.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Enable::EnableChoice::Traps::Ospfv3::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Enable::EnableChoice::Traps::Ospfv3::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Ospfv3::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "state-change")
{
state_change = value;
state_change.value_namespace = name_space;
state_change.value_namespace_prefix = name_space_prefix;
}
if(value_path == "errors")
{
errors = value;
errors.value_namespace = name_space;
errors.value_namespace_prefix = name_space_prefix;
}
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Ospfv3::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "state-change")
{
state_change.yfilter = yfilter;
}
if(value_path == "errors")
{
errors.yfilter = yfilter;
}
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Ospfv3::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "state-change" || name == "errors")
return true;
return false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Ike::Ike()
:
policy(std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Ike::Policy>())
, tunnel(std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Ike::Tunnel>())
{
policy->parent = this;
tunnel->parent = this;
yang_name = "ike"; yang_parent_name = "traps"; is_top_level_class = false; has_list_ancestor = false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Ike::~Ike()
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Ike::has_data() const
{
if (is_presence_container) return true;
return (policy != nullptr && policy->has_data())
|| (tunnel != nullptr && tunnel->has_data());
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Ike::has_operation() const
{
return is_set(yfilter)
|| (policy != nullptr && policy->has_operation())
|| (tunnel != nullptr && tunnel->has_operation());
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Ike::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/Cisco-IOS-XE-snmp:enable/enable-choice/traps/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Ike::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "ike";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Enable::EnableChoice::Traps::Ike::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Enable::EnableChoice::Traps::Ike::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "policy")
{
if(policy == nullptr)
{
policy = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Ike::Policy>();
}
return policy;
}
if(child_yang_name == "tunnel")
{
if(tunnel == nullptr)
{
tunnel = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Ike::Tunnel>();
}
return tunnel;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Enable::EnableChoice::Traps::Ike::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(policy != nullptr)
{
_children["policy"] = policy;
}
if(tunnel != nullptr)
{
_children["tunnel"] = tunnel;
}
return _children;
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Ike::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Ike::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Ike::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "policy" || name == "tunnel")
return true;
return false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Ike::Policy::Policy()
:
add{YType::empty, "add"},
delete_{YType::empty, "delete"}
{
yang_name = "policy"; yang_parent_name = "ike"; is_top_level_class = false; has_list_ancestor = false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Ike::Policy::~Policy()
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Ike::Policy::has_data() const
{
if (is_presence_container) return true;
return add.is_set
|| delete_.is_set;
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Ike::Policy::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(add.yfilter)
|| ydk::is_set(delete_.yfilter);
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Ike::Policy::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/Cisco-IOS-XE-snmp:enable/enable-choice/traps/ike/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Ike::Policy::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "policy";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Enable::EnableChoice::Traps::Ike::Policy::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (add.is_set || is_set(add.yfilter)) leaf_name_data.push_back(add.get_name_leafdata());
if (delete_.is_set || is_set(delete_.yfilter)) leaf_name_data.push_back(delete_.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Enable::EnableChoice::Traps::Ike::Policy::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Enable::EnableChoice::Traps::Ike::Policy::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Ike::Policy::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "add")
{
add = value;
add.value_namespace = name_space;
add.value_namespace_prefix = name_space_prefix;
}
if(value_path == "delete")
{
delete_ = value;
delete_.value_namespace = name_space;
delete_.value_namespace_prefix = name_space_prefix;
}
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Ike::Policy::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "add")
{
add.yfilter = yfilter;
}
if(value_path == "delete")
{
delete_.yfilter = yfilter;
}
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Ike::Policy::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "add" || name == "delete")
return true;
return false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Ike::Tunnel::Tunnel()
:
start{YType::empty, "start"},
stop{YType::empty, "stop"}
{
yang_name = "tunnel"; yang_parent_name = "ike"; is_top_level_class = false; has_list_ancestor = false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Ike::Tunnel::~Tunnel()
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Ike::Tunnel::has_data() const
{
if (is_presence_container) return true;
return start.is_set
|| stop.is_set;
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Ike::Tunnel::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(start.yfilter)
|| ydk::is_set(stop.yfilter);
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Ike::Tunnel::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/Cisco-IOS-XE-snmp:enable/enable-choice/traps/ike/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Ike::Tunnel::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "tunnel";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Enable::EnableChoice::Traps::Ike::Tunnel::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (start.is_set || is_set(start.yfilter)) leaf_name_data.push_back(start.get_name_leafdata());
if (stop.is_set || is_set(stop.yfilter)) leaf_name_data.push_back(stop.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Enable::EnableChoice::Traps::Ike::Tunnel::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Enable::EnableChoice::Traps::Ike::Tunnel::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Ike::Tunnel::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "start")
{
start = value;
start.value_namespace = name_space;
start.value_namespace_prefix = name_space_prefix;
}
if(value_path == "stop")
{
stop = value;
stop.value_namespace = name_space;
stop.value_namespace_prefix = name_space_prefix;
}
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Ike::Tunnel::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "start")
{
start.yfilter = yfilter;
}
if(value_path == "stop")
{
stop.yfilter = yfilter;
}
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Ike::Tunnel::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "start" || name == "stop")
return true;
return false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Alarms::Alarms()
:
alarm_type{YType::str, "alarm-type"}
{
yang_name = "alarms"; yang_parent_name = "traps"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Alarms::~Alarms()
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Alarms::has_data() const
{
if (is_presence_container) return true;
return alarm_type.is_set;
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Alarms::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(alarm_type.yfilter);
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Alarms::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/Cisco-IOS-XE-snmp:enable/enable-choice/traps/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Alarms::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "alarms";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Enable::EnableChoice::Traps::Alarms::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (alarm_type.is_set || is_set(alarm_type.yfilter)) leaf_name_data.push_back(alarm_type.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Enable::EnableChoice::Traps::Alarms::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Enable::EnableChoice::Traps::Alarms::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Alarms::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "alarm-type")
{
alarm_type = value;
alarm_type.value_namespace = name_space;
alarm_type.value_namespace_prefix = name_space_prefix;
}
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Alarms::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "alarm-type")
{
alarm_type.yfilter = yfilter;
}
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Alarms::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "alarm-type")
return true;
return false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Atm()
:
pvc(nullptr) // presence node
, subif(nullptr) // presence node
{
yang_name = "atm"; yang_parent_name = "traps"; is_top_level_class = false; has_list_ancestor = false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Atm::~Atm()
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Atm::has_data() const
{
if (is_presence_container) return true;
return (pvc != nullptr && pvc->has_data())
|| (subif != nullptr && subif->has_data());
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Atm::has_operation() const
{
return is_set(yfilter)
|| (pvc != nullptr && pvc->has_operation())
|| (subif != nullptr && subif->has_operation());
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Atm::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/Cisco-IOS-XE-snmp:enable/enable-choice/traps/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Atm::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "atm";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Enable::EnableChoice::Traps::Atm::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Enable::EnableChoice::Traps::Atm::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "pvc")
{
if(pvc == nullptr)
{
pvc = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc>();
}
return pvc;
}
if(child_yang_name == "subif")
{
if(subif == nullptr)
{
subif = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Subif>();
}
return subif;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Enable::EnableChoice::Traps::Atm::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(pvc != nullptr)
{
_children["pvc"] = pvc;
}
if(subif != nullptr)
{
_children["subif"] = subif;
}
return _children;
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Atm::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Atm::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Atm::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "pvc" || name == "subif")
return true;
return false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Pvc()
:
interval{YType::uint16, "interval"},
fail_interval{YType::uint16, "fail-interval"}
,
extension(std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension>())
{
extension->parent = this;
yang_name = "pvc"; yang_parent_name = "atm"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::~Pvc()
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::has_data() const
{
if (is_presence_container) return true;
return interval.is_set
|| fail_interval.is_set
|| (extension != nullptr && extension->has_data());
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(interval.yfilter)
|| ydk::is_set(fail_interval.yfilter)
|| (extension != nullptr && extension->has_operation());
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/Cisco-IOS-XE-snmp:enable/enable-choice/traps/atm/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "pvc";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (interval.is_set || is_set(interval.yfilter)) leaf_name_data.push_back(interval.get_name_leafdata());
if (fail_interval.is_set || is_set(fail_interval.yfilter)) leaf_name_data.push_back(fail_interval.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "extension")
{
if(extension == nullptr)
{
extension = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension>();
}
return extension;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(extension != nullptr)
{
_children["extension"] = extension;
}
return _children;
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "interval")
{
interval = value;
interval.value_namespace = name_space;
interval.value_namespace_prefix = name_space_prefix;
}
if(value_path == "fail-interval")
{
fail_interval = value;
fail_interval.value_namespace = name_space;
fail_interval.value_namespace_prefix = name_space_prefix;
}
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "interval")
{
interval.yfilter = yfilter;
}
if(value_path == "fail-interval")
{
fail_interval.yfilter = yfilter;
}
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "extension" || name == "interval" || name == "fail-interval")
return true;
return false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::Extension()
:
down{YType::empty, "down"},
up{YType::empty, "up"},
mibversion{YType::enumeration, "mibversion"}
,
oam(std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::Oam>())
{
oam->parent = this;
yang_name = "extension"; yang_parent_name = "pvc"; is_top_level_class = false; has_list_ancestor = false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::~Extension()
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::has_data() const
{
if (is_presence_container) return true;
return down.is_set
|| up.is_set
|| mibversion.is_set
|| (oam != nullptr && oam->has_data());
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(down.yfilter)
|| ydk::is_set(up.yfilter)
|| ydk::is_set(mibversion.yfilter)
|| (oam != nullptr && oam->has_operation());
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/Cisco-IOS-XE-snmp:enable/enable-choice/traps/atm/pvc/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "extension";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (down.is_set || is_set(down.yfilter)) leaf_name_data.push_back(down.get_name_leafdata());
if (up.is_set || is_set(up.yfilter)) leaf_name_data.push_back(up.get_name_leafdata());
if (mibversion.is_set || is_set(mibversion.yfilter)) leaf_name_data.push_back(mibversion.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "oam")
{
if(oam == nullptr)
{
oam = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::Oam>();
}
return oam;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(oam != nullptr)
{
_children["oam"] = oam;
}
return _children;
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "down")
{
down = value;
down.value_namespace = name_space;
down.value_namespace_prefix = name_space_prefix;
}
if(value_path == "up")
{
up = value;
up.value_namespace = name_space;
up.value_namespace_prefix = name_space_prefix;
}
if(value_path == "mibversion")
{
mibversion = value;
mibversion.value_namespace = name_space;
mibversion.value_namespace_prefix = name_space_prefix;
}
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "down")
{
down.yfilter = yfilter;
}
if(value_path == "up")
{
up.yfilter = yfilter;
}
if(value_path == "mibversion")
{
mibversion.yfilter = yfilter;
}
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "oam" || name == "down" || name == "up" || name == "mibversion")
return true;
return false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::Oam::Oam()
:
failure(std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::Oam::Failure>())
{
failure->parent = this;
yang_name = "oam"; yang_parent_name = "extension"; is_top_level_class = false; has_list_ancestor = false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::Oam::~Oam()
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::Oam::has_data() const
{
if (is_presence_container) return true;
return (failure != nullptr && failure->has_data());
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::Oam::has_operation() const
{
return is_set(yfilter)
|| (failure != nullptr && failure->has_operation());
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::Oam::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/Cisco-IOS-XE-snmp:enable/enable-choice/traps/atm/pvc/extension/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::Oam::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "oam";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::Oam::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::Oam::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "failure")
{
if(failure == nullptr)
{
failure = std::make_shared<Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::Oam::Failure>();
}
return failure;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::Oam::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(failure != nullptr)
{
_children["failure"] = failure;
}
return _children;
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::Oam::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::Oam::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::Oam::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "failure")
return true;
return false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::Oam::Failure::Failure()
:
loopback{YType::empty, "loopback"}
{
yang_name = "failure"; yang_parent_name = "oam"; is_top_level_class = false; has_list_ancestor = false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::Oam::Failure::~Failure()
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::Oam::Failure::has_data() const
{
if (is_presence_container) return true;
return loopback.is_set;
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::Oam::Failure::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(loopback.yfilter);
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::Oam::Failure::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/Cisco-IOS-XE-snmp:enable/enable-choice/traps/atm/pvc/extension/oam/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::Oam::Failure::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "failure";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::Oam::Failure::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (loopback.is_set || is_set(loopback.yfilter)) leaf_name_data.push_back(loopback.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::Oam::Failure::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::Oam::Failure::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::Oam::Failure::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "loopback")
{
loopback = value;
loopback.value_namespace = name_space;
loopback.value_namespace_prefix = name_space_prefix;
}
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::Oam::Failure::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "loopback")
{
loopback.yfilter = yfilter;
}
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::Oam::Failure::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "loopback")
return true;
return false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Subif::Subif()
:
interval{YType::uint16, "interval"},
count{YType::uint16, "count"}
{
yang_name = "subif"; yang_parent_name = "atm"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Subif::~Subif()
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Subif::has_data() const
{
if (is_presence_container) return true;
return interval.is_set
|| count.is_set;
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Subif::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(interval.yfilter)
|| ydk::is_set(count.yfilter);
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Subif::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/Cisco-IOS-XE-snmp:enable/enable-choice/traps/atm/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Subif::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "subif";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Subif::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (interval.is_set || is_set(interval.yfilter)) leaf_name_data.push_back(interval.get_name_leafdata());
if (count.is_set || is_set(count.yfilter)) leaf_name_data.push_back(count.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Subif::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Subif::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Subif::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "interval")
{
interval = value;
interval.value_namespace = name_space;
interval.value_namespace_prefix = name_space_prefix;
}
if(value_path == "count")
{
count = value;
count.value_namespace = name_space;
count.value_namespace_prefix = name_space_prefix;
}
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Subif::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "interval")
{
interval.yfilter = yfilter;
}
if(value_path == "count")
{
count.yfilter = yfilter;
}
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Subif::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "interval" || name == "count")
return true;
return false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::AuthFramework::AuthFramework()
:
sec_violation{YType::empty, "sec-violation"}
{
yang_name = "auth-framework"; yang_parent_name = "traps"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true;
}
Native::SnmpServer::Enable::EnableChoice::Traps::AuthFramework::~AuthFramework()
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::AuthFramework::has_data() const
{
if (is_presence_container) return true;
return sec_violation.is_set;
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::AuthFramework::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(sec_violation.yfilter);
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::AuthFramework::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/Cisco-IOS-XE-snmp:enable/enable-choice/traps/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::AuthFramework::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "auth-framework";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Enable::EnableChoice::Traps::AuthFramework::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (sec_violation.is_set || is_set(sec_violation.yfilter)) leaf_name_data.push_back(sec_violation.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Enable::EnableChoice::Traps::AuthFramework::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Enable::EnableChoice::Traps::AuthFramework::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::SnmpServer::Enable::EnableChoice::Traps::AuthFramework::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "sec-violation")
{
sec_violation = value;
sec_violation.value_namespace = name_space;
sec_violation.value_namespace_prefix = name_space_prefix;
}
}
void Native::SnmpServer::Enable::EnableChoice::Traps::AuthFramework::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "sec-violation")
{
sec_violation.yfilter = yfilter;
}
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::AuthFramework::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "sec-violation")
return true;
return false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::BgpConf::BgpConf()
:
cbgp2{YType::empty, "cbgp2"}
{
yang_name = "bgp-conf"; yang_parent_name = "traps"; is_top_level_class = false; has_list_ancestor = false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::BgpConf::~BgpConf()
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::BgpConf::has_data() const
{
if (is_presence_container) return true;
return cbgp2.is_set;
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::BgpConf::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(cbgp2.yfilter);
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::BgpConf::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/Cisco-IOS-XE-snmp:enable/enable-choice/traps/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::BgpConf::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "bgp-conf";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Enable::EnableChoice::Traps::BgpConf::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (cbgp2.is_set || is_set(cbgp2.yfilter)) leaf_name_data.push_back(cbgp2.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Enable::EnableChoice::Traps::BgpConf::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Enable::EnableChoice::Traps::BgpConf::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::SnmpServer::Enable::EnableChoice::Traps::BgpConf::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "cbgp2")
{
cbgp2 = value;
cbgp2.value_namespace = name_space;
cbgp2.value_namespace_prefix = name_space_prefix;
}
}
void Native::SnmpServer::Enable::EnableChoice::Traps::BgpConf::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "cbgp2")
{
cbgp2.yfilter = yfilter;
}
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::BgpConf::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "cbgp2")
return true;
return false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Bridge::Bridge()
:
newroot{YType::empty, "newroot"},
topologychange{YType::empty, "topologychange"}
{
yang_name = "bridge"; yang_parent_name = "traps"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Bridge::~Bridge()
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Bridge::has_data() const
{
if (is_presence_container) return true;
return newroot.is_set
|| topologychange.is_set;
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Bridge::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(newroot.yfilter)
|| ydk::is_set(topologychange.yfilter);
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Bridge::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/Cisco-IOS-XE-snmp:enable/enable-choice/traps/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Bridge::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "bridge";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Enable::EnableChoice::Traps::Bridge::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (newroot.is_set || is_set(newroot.yfilter)) leaf_name_data.push_back(newroot.get_name_leafdata());
if (topologychange.is_set || is_set(topologychange.yfilter)) leaf_name_data.push_back(topologychange.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Enable::EnableChoice::Traps::Bridge::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Enable::EnableChoice::Traps::Bridge::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Bridge::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "newroot")
{
newroot = value;
newroot.value_namespace = name_space;
newroot.value_namespace_prefix = name_space_prefix;
}
if(value_path == "topologychange")
{
topologychange = value;
topologychange.value_namespace = name_space;
topologychange.value_namespace_prefix = name_space_prefix;
}
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Bridge::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "newroot")
{
newroot.yfilter = yfilter;
}
if(value_path == "topologychange")
{
topologychange.yfilter = yfilter;
}
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Bridge::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "newroot" || name == "topologychange")
return true;
return false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Bulkstat::Bulkstat()
:
collection{YType::empty, "collection"},
transfer{YType::empty, "transfer"}
{
yang_name = "bulkstat"; yang_parent_name = "traps"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true;
}
Native::SnmpServer::Enable::EnableChoice::Traps::Bulkstat::~Bulkstat()
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Bulkstat::has_data() const
{
if (is_presence_container) return true;
return collection.is_set
|| transfer.is_set;
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Bulkstat::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(collection.yfilter)
|| ydk::is_set(transfer.yfilter);
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Bulkstat::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/Cisco-IOS-XE-snmp:enable/enable-choice/traps/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::Bulkstat::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "bulkstat";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Enable::EnableChoice::Traps::Bulkstat::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (collection.is_set || is_set(collection.yfilter)) leaf_name_data.push_back(collection.get_name_leafdata());
if (transfer.is_set || is_set(transfer.yfilter)) leaf_name_data.push_back(transfer.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Enable::EnableChoice::Traps::Bulkstat::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Enable::EnableChoice::Traps::Bulkstat::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Bulkstat::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "collection")
{
collection = value;
collection.value_namespace = name_space;
collection.value_namespace_prefix = name_space_prefix;
}
if(value_path == "transfer")
{
transfer = value;
transfer.value_namespace = name_space;
transfer.value_namespace_prefix = name_space_prefix;
}
}
void Native::SnmpServer::Enable::EnableChoice::Traps::Bulkstat::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "collection")
{
collection.yfilter = yfilter;
}
if(value_path == "transfer")
{
transfer.yfilter = yfilter;
}
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::Bulkstat::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "collection" || name == "transfer")
return true;
return false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::CallHome::CallHome()
:
message_send_fail{YType::empty, "message-send-fail"},
server_fail{YType::empty, "server-fail"}
{
yang_name = "call-home"; yang_parent_name = "traps"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true;
}
Native::SnmpServer::Enable::EnableChoice::Traps::CallHome::~CallHome()
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::CallHome::has_data() const
{
if (is_presence_container) return true;
return message_send_fail.is_set
|| server_fail.is_set;
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::CallHome::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(message_send_fail.yfilter)
|| ydk::is_set(server_fail.yfilter);
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::CallHome::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/Cisco-IOS-XE-snmp:enable/enable-choice/traps/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::CallHome::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "call-home";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Enable::EnableChoice::Traps::CallHome::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (message_send_fail.is_set || is_set(message_send_fail.yfilter)) leaf_name_data.push_back(message_send_fail.get_name_leafdata());
if (server_fail.is_set || is_set(server_fail.yfilter)) leaf_name_data.push_back(server_fail.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Enable::EnableChoice::Traps::CallHome::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Enable::EnableChoice::Traps::CallHome::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::SnmpServer::Enable::EnableChoice::Traps::CallHome::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "message-send-fail")
{
message_send_fail = value;
message_send_fail.value_namespace = name_space;
message_send_fail.value_namespace_prefix = name_space_prefix;
}
if(value_path == "server-fail")
{
server_fail = value;
server_fail.value_namespace = name_space;
server_fail.value_namespace_prefix = name_space_prefix;
}
}
void Native::SnmpServer::Enable::EnableChoice::Traps::CallHome::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "message-send-fail")
{
message_send_fail.yfilter = yfilter;
}
if(value_path == "server-fail")
{
server_fail.yfilter = yfilter;
}
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::CallHome::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "message-send-fail" || name == "server-fail")
return true;
return false;
}
Native::SnmpServer::Enable::EnableChoice::Traps::C6kxbar::C6kxbar()
:
intbus_crcexcd{YType::empty, "intbus-crcexcd"},
intbus_crcrcvrd{YType::empty, "intbus-crcrcvrd"},
swbus{YType::empty, "swbus"}
{
yang_name = "c6kxbar"; yang_parent_name = "traps"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true;
}
Native::SnmpServer::Enable::EnableChoice::Traps::C6kxbar::~C6kxbar()
{
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::C6kxbar::has_data() const
{
if (is_presence_container) return true;
return intbus_crcexcd.is_set
|| intbus_crcrcvrd.is_set
|| swbus.is_set;
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::C6kxbar::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(intbus_crcexcd.yfilter)
|| ydk::is_set(intbus_crcrcvrd.yfilter)
|| ydk::is_set(swbus.yfilter);
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::C6kxbar::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XE-native:native/snmp-server/Cisco-IOS-XE-snmp:enable/enable-choice/traps/" << get_segment_path();
return path_buffer.str();
}
std::string Native::SnmpServer::Enable::EnableChoice::Traps::C6kxbar::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "c6kxbar";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Native::SnmpServer::Enable::EnableChoice::Traps::C6kxbar::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (intbus_crcexcd.is_set || is_set(intbus_crcexcd.yfilter)) leaf_name_data.push_back(intbus_crcexcd.get_name_leafdata());
if (intbus_crcrcvrd.is_set || is_set(intbus_crcrcvrd.yfilter)) leaf_name_data.push_back(intbus_crcrcvrd.get_name_leafdata());
if (swbus.is_set || is_set(swbus.yfilter)) leaf_name_data.push_back(swbus.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Native::SnmpServer::Enable::EnableChoice::Traps::C6kxbar::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Native::SnmpServer::Enable::EnableChoice::Traps::C6kxbar::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Native::SnmpServer::Enable::EnableChoice::Traps::C6kxbar::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "intbus-crcexcd")
{
intbus_crcexcd = value;
intbus_crcexcd.value_namespace = name_space;
intbus_crcexcd.value_namespace_prefix = name_space_prefix;
}
if(value_path == "intbus-crcrcvrd")
{
intbus_crcrcvrd = value;
intbus_crcrcvrd.value_namespace = name_space;
intbus_crcrcvrd.value_namespace_prefix = name_space_prefix;
}
if(value_path == "swbus")
{
swbus = value;
swbus.value_namespace = name_space;
swbus.value_namespace_prefix = name_space_prefix;
}
}
void Native::SnmpServer::Enable::EnableChoice::Traps::C6kxbar::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "intbus-crcexcd")
{
intbus_crcexcd.yfilter = yfilter;
}
if(value_path == "intbus-crcrcvrd")
{
intbus_crcrcvrd.yfilter = yfilter;
}
if(value_path == "swbus")
{
swbus.yfilter = yfilter;
}
}
bool Native::SnmpServer::Enable::EnableChoice::Traps::C6kxbar::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "intbus-crcexcd" || name == "intbus-crcrcvrd" || name == "swbus")
return true;
return false;
}
const Enum::YLeaf Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Encapsulation::Gre::Enhanced::copy {0, "copy"};
const Enum::YLeaf Native::ServiceChain::ServiceFunction::ConfigServiceChainSfMode::Encapsulation::Gre::Enhanced::divert {1, "divert"};
const Enum::YLeaf Native::Performance::Monitor::Context::Profile::application_experience {0, "application-experience"};
const Enum::YLeaf Native::Performance::Monitor::Context::Profile::application_performance {1, "application-performance"};
const Enum::YLeaf Native::Performance::Monitor::Context::Profile::application_statistics {2, "application-statistics"};
const Enum::YLeaf Native::Performance::Monitor::Context::Default::Exporter::Transport::udp {0, "udp"};
const Enum::YLeaf Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationResponseTime::CacheType::normal {0, "normal"};
const Enum::YLeaf Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationResponseTime::CacheType::synchronized {1, "synchronized"};
const Enum::YLeaf Native::Performance::Monitor::Context::Default::TrafficMonitor::ConversationTrafficStats::CacheType::normal {0, "normal"};
const Enum::YLeaf Native::Performance::Monitor::Context::Default::TrafficMonitor::ConversationTrafficStats::CacheType::synchronized {1, "synchronized"};
const Enum::YLeaf Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationClientServerStats::CacheType::normal {0, "normal"};
const Enum::YLeaf Native::Performance::Monitor::Context::Default::TrafficMonitor::ApplicationClientServerStats::CacheType::synchronized {1, "synchronized"};
const Enum::YLeaf Native::Performance::Monitor::Context::Exporter::Transport::udp {0, "udp"};
const Enum::YLeaf Native::Performance::Monitor::Context::TrafficMonitor::ApplicationResponseTime::CacheType::normal {0, "normal"};
const Enum::YLeaf Native::Performance::Monitor::Context::TrafficMonitor::ApplicationResponseTime::CacheType::synchronized {1, "synchronized"};
const Enum::YLeaf Native::Performance::Monitor::Context::TrafficMonitor::ConversationTrafficStats::CacheType::normal {0, "normal"};
const Enum::YLeaf Native::Performance::Monitor::Context::TrafficMonitor::ConversationTrafficStats::CacheType::synchronized {1, "synchronized"};
const Enum::YLeaf Native::Performance::Monitor::Context::TrafficMonitor::ApplicationClientServerStats::CacheType::normal {0, "normal"};
const Enum::YLeaf Native::Performance::Monitor::Context::TrafficMonitor::ApplicationClientServerStats::CacheType::synchronized {1, "synchronized"};
const Enum::YLeaf Native::Otv::Isis::Overlay::Authentication::Mode::md5 {0, "md5"};
const Enum::YLeaf Native::Otv::Isis::Overlay::Authentication::Mode::text {1, "text"};
const Enum::YLeaf Native::Otv::Isis::Overlay::Default::Authentication::Mode::md5 {0, "md5"};
const Enum::YLeaf Native::Otv::Isis::Overlay::Default::Authentication::Mode::text {1, "text"};
const Enum::YLeaf Native::Otv::Site::Default::Otv_::Isis::Authentication::Mode::md5 {0, "md5"};
const Enum::YLeaf Native::Otv::Site::Default::Otv_::Isis::Authentication::Mode::text {1, "text"};
const Enum::YLeaf Native::Otv::Site::Otv_::Isis::Authentication::Mode::md5 {0, "md5"};
const Enum::YLeaf Native::Otv::Site::Otv_::Isis::Authentication::Mode::text {1, "text"};
const Enum::YLeaf Native::Snmp::Mib::Persist::PersistEnum::cbqos {0, "cbqos"};
const Enum::YLeaf Native::Snmp::Mib::Persist::PersistEnum::circuit {1, "circuit"};
const Enum::YLeaf Native::Snmp::Mib::Persist::PersistEnum::v3mibs {2, "v3mibs"};
const Enum::YLeaf Native::SnmpServer::Enable::EnableChoice::Traps::Alarms::AlarmType::critical {0, "critical"};
const Enum::YLeaf Native::SnmpServer::Enable::EnableChoice::Traps::Alarms::AlarmType::informational {1, "informational"};
const Enum::YLeaf Native::SnmpServer::Enable::EnableChoice::Traps::Alarms::AlarmType::major_ {2, "major"};
const Enum::YLeaf Native::SnmpServer::Enable::EnableChoice::Traps::Alarms::AlarmType::minor {3, "minor"};
const Enum::YLeaf Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::Mibversion::Y_1 {0, "1"};
const Enum::YLeaf Native::SnmpServer::Enable::EnableChoice::Traps::Atm::Pvc::Extension::Mibversion::Y_2 {1, "2"};
}
}
| 31.902952 | 2,695 | 0.683832 | [
"object",
"vector"
] |
a818d03afa3bde5e1d6a6d039c621baa654c1162 | 45,676 | cpp | C++ | win32-OpenGL/MyGeometryOM.cpp | Peanoquio/fuzzy-logic-demo | 100a64094adb2d5274c32761ed4ede15b912dd90 | [
"MIT"
] | null | null | null | win32-OpenGL/MyGeometryOM.cpp | Peanoquio/fuzzy-logic-demo | 100a64094adb2d5274c32761ed4ede15b912dd90 | [
"MIT"
] | null | null | null | win32-OpenGL/MyGeometryOM.cpp | Peanoquio/fuzzy-logic-demo | 100a64094adb2d5274c32761ed4ede15b912dd90 | [
"MIT"
] | null | null | null | /******************************************************************************/
/*!
\file MyGeometryOM.cpp
\author Oliver Ryan Chong
\par email: oliver.chong\@digipen.edu
\par oliver.chong 900863
\par Course: CS1250
\par Project #01
\date 24/12/2011
\brief
This is the geometry object manager that will manage the generation of goemetries
Copyright (C) 2011 DigiPen Institute of Technology Singapore
*/
/******************************************************************************/
#include "MyGeometryOM.h"
#include "File\FileIO.h"
//#include "File\TGALoader.h"
#include "GeometryBuilder\Grid2DBuilder.h"
#include "GeometryBuilder\Polygon2DBuilder.h"
#include "GeometryBuilder\CubeBuilder.h"
#include "GeometryBuilder\CylinderBuilder.h"
#include "GeometryBuilder\ConeBuilder.h"
#include "GeometryBuilder\SphereBuilder.h"
//#include "GeometryBuilder\SatelliteBuilder.h"
#include <iostream>
#include <iomanip>
namespace
{
const char * FILE_NAME = "./File/GeometryParametersFile.txt";
}
namespace MyGeometryGame
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
The constructor for the MyGeometryOM class
\param
\return
*/
/******************************************************************************/
MyGeometryOM::MyGeometryOM( void )
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
The destructor for the MyGeometryOM class
\param
\return
*/
/******************************************************************************/
MyGeometryOM::~MyGeometryOM( void )
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
Computes for the normal of a line
\param objNameFromFile
the object name that will be used to retrieve the geometry parameters from the file
\param physicsObj
the physics object that contains the physics properties of the game object
\return
*/
/******************************************************************************/
void MyGeometryOM::ComputeLineNormal( const std::string objNameFromFile, PhysicsFramework::PhysicsObject & physicsObj ) const
{
//get the values from the physics object
const Math::Vector4 & scale = physicsObj.GetScale();
const Math::Vector4 & position = physicsObj.GetPosition();
const float angleDegrees = physicsObj.GetAngleDegreesZ();
//get the mesh parameters from the file
GraphicsFramework::MeshParameterContainer meshParameterContainer = this->GetMeshParametersFromFile( objNameFromFile, FILE_NAME );
//float yLimit = meshParameterContainer.m_height / 2.0F;
float xLimit = meshParameterContainer.m_width / 2.0F;
//compute for the cube normal
Math::Vector4 ptHead( xLimit, 0.0F, 0.0F, 1.0F );
Math::Vector4 ptTail( -xLimit, 0.0F, 0.0F, 1.0F );
Math::Mtx44 concatenatedMtx;
Math::Mtx44 rotateMtx;
Math::Mtx44 scaleMtx;
Math::Mtx44 translateMtx;
//set scale
scaleMtx.SetToScale(
scale.GetFloatX(),
scale.GetFloatY(),
scale.GetFloatZ() );
//set rotation
rotateMtx.SetToRotationDegreesZ( angleDegrees );
//set translation
translateMtx.SetToTranslation(
position.GetFloatX(),
position.GetFloatY(),
position.GetFloatZ() );
//pass the physics matrix
concatenatedMtx = translateMtx * rotateMtx * scaleMtx;
ptHead = concatenatedMtx * ptHead;
ptTail = concatenatedMtx * ptTail;
//compute for the normal
physicsObj.ComputeNormal( ptHead, ptTail );
/*
std::cout << std::setfill (' ') << std::setw( 0 ) << "=============================================================================" << std::endl;
std::cout << std::setfill (' ') << std::setw( 0 ) << "wall angle : " << angleDegrees << std::endl;
std::cout << std::setfill (' ') << std::setw( 0 ) << "wall position : " << physicsObj.GetPosition().GetFloatX() << ", "
<< physicsObj.GetPosition().GetFloatY() << ", " << physicsObj.GetPosition().GetFloatZ() << std::endl;
std::cout << std::setfill (' ') << std::setw( 0 ) << "wall scale : " << physicsObj.GetScale().GetFloatX() << ", "
<< physicsObj.GetScale().GetFloatY() << ", " << physicsObj.GetScale().GetFloatZ() << std::endl;
std::cout << std::setfill (' ') << std::setw( 0 ) << "wall normal : " << physicsObj.GetNormal().GetFloatX() << ", "
<< physicsObj.GetNormal().GetFloatY() << std::endl;
std::cout << std::setfill (' ') << std::setw( 0 ) << "wall span : " << ptTail.GetFloatX() << ", "
<< ptTail.GetFloatY() << " to " << ptHead.GetFloatX() << ", " << ptHead.GetFloatY() << std::endl;
*/
//test if vector is perpendicular to normal
//float val = physicsObj.GetNormal().Dot( ptHead - ptTail );
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
Computes for the normal of a plane
\param objNameFromFile
the object name that will be used to retrieve the geometry parameters from the file
\param physicsObj
the physics object that contains the physics properties of the game object
\return
*/
/******************************************************************************/
void MyGeometryOM::ComputePlaneNormal( const std::string objNameFromFile, PhysicsFramework::PhysicsObject & physicsObj ) const
{
//get the values from the physics object
const Math::Vector4 & scale = physicsObj.GetScale();
const Math::Vector4 & position = physicsObj.GetPosition();
//get the mesh parameters from the file
GraphicsFramework::MeshParameterContainer meshParameterContainer = this->GetMeshParametersFromFile( objNameFromFile, FILE_NAME );
float yLimit = meshParameterContainer.m_height / 2.0F;
float xLimit = meshParameterContainer.m_width / 2.0F;
//compute for the plane normal
Math::Vector4 ptHor( xLimit, 0.0F, 0.0F, 1.0F );
Math::Vector4 ptVert( 0.0F, yLimit, 0.0F, 1.0F );
Math::Vector4 ptCtr( 0.0F, 0.0F, 0.0F, 1.0F );
Math::Mtx44 concatenatedMtx;
Math::Mtx44 rotateMtx;
Math::Mtx44 scaleMtx;
Math::Mtx44 translateMtx;
//set scale
scaleMtx.SetToScale(
scale.GetFloatX(),
scale.GetFloatY(),
scale.GetFloatZ() );
//set rotation
rotateMtx.SetToRotationDegreesX( physicsObj.GetAngleDegreesX() );
rotateMtx.SetToRotationDegreesY( physicsObj.GetAngleDegreesY() );
rotateMtx.SetToRotationDegreesZ( physicsObj.GetAngleDegreesZ() );
//set translation
translateMtx.SetToTranslation(
position.GetFloatX(),
position.GetFloatY(),
position.GetFloatZ() );
//pass the physics matrix
concatenatedMtx = translateMtx * rotateMtx * scaleMtx;
ptHor = concatenatedMtx * ptHor;
ptVert = concatenatedMtx * ptVert;
ptCtr = concatenatedMtx * ptCtr;
//compute for the plane normal using the cross product
Math::Vector4 vectorU = ptHor - ptCtr;
Math::Vector4 vectorV = ptVert - ptCtr;
Math::Vector4 planeNormal = vectorU.Cross( vectorV );
planeNormal.Normalize();
//store the computed normal
physicsObj.SetNormal( planeNormal );
//store the center vertex of the object
physicsObj.SetCenterPt( ptCtr );
//test if vector is perpendicular to normal
//float val = physicsObj.GetNormal().Dot( vectorU );
//val = physicsObj.GetNormal().Dot( vectorV );
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
Generates the pending game object.
This also adds the generated pending game object to the vector so it can be reused by the game
\param gameObjIdentifier
the identifier of the game object
\param objectType
the type of the geometry
\param graphicsInterfacePtr
the graphics interface
\param position
the position of the object
\param velocity
the velocity of the object
\param scale
the scale of the object
\param rotation
the rotational angle direction in degrees of the object
\param movementSpeed
the movement speed of the object
\param rotationalSpeed
the rotational speed of the object
\param acceleration
the acceleration of the object
\param mass
the mass of the object
\param moveInitialFlag
the indicator to determine if the object will move upon initial rendering
\param row
the row of the game object
\param column
the column of the game object
\return
*/
/******************************************************************************/
void MyGeometryOM::GeneratePendingGameObject( const unsigned gameObjIdentifier, const unsigned objectType,
GraphicsFramework::GraphicsInterface* const graphicsInterfacePtr,
const Math::Vector4 & position,
const Math::Vector4 & velocity,
const Math::Vector4 & scale,
const Math::Vector4 & rotation,
const float movementSpeed,
const float rotationalSpeed,
const float acceleration,
const float mass,
const bool moveInitialFlag,
const unsigned row,
const unsigned column,
const unsigned index
)
{
GraphicsFramework::GraphicsObject graphicsObj;
PhysicsFramework::PhysicsObject physicsObj;
GameFramework::GameObject gameObj;
//retrieve the graphics object
graphicsObj = graphicsInterfacePtr->RetrieveGraphicsObject( objectType );
//set up the physics object
physicsObj = this->CreatePhysicsObject( position, velocity, scale, rotation, mass, movementSpeed, rotationalSpeed, acceleration, moveInitialFlag );
//////////////////////////////////////////////////////////////////////////////////////////////////////////
if ( objectType == CUBE_OBJTYPE || objectType == CUBE2_OBJTYPE )
{
std::string objNameFromFile;
if ( objectType == CUBE_OBJTYPE )
{
objNameFromFile = "cube";
}
else if ( objectType == CUBE2_OBJTYPE )
{
objNameFromFile = "cube2";
}
//compute for the line normal
this->ComputeLineNormal( objNameFromFile, physicsObj );
}
else if ( objectType == GRID_OBJTYPE )
{
//compute for the plane normal
this->ComputePlaneNormal( "grid2D", physicsObj );
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//create the game object
gameObj = this->CreateGameObject( graphicsObj, physicsObj );
gameObj.SetType( objectType );
gameObj.SetIdentifier( gameObjIdentifier );
gameObj.SetRow( row );
gameObj.SetColumn( column );
gameObj.SetIndex( index );
//contain the game object
this->ContainGameObject( gameObj );
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
Generates the pending game object.
This also adds the generated pending game object to the vector so it can be reused by the game
\param gameObjIdentifier
the identifier of the game object
\param objectType
the object type
\param graphicsInterfacePtr
the graphics interface
\param physicsVal
the physics properties of the game object
\param materialVal
the material properties of the game object
\param gameObjCategory
the category of the game object
\param moveInitialFlag
the indicator to determine if the object will move upon initial rendering
\return
*/
/******************************************************************************/
void MyGeometryOM::GeneratePendingGameObject( const unsigned gameObjIdentifier, const unsigned objectType,
GraphicsFramework::GraphicsInterface* const graphicsInterfacePtr,
const PhysicsFramework::PhysicsObject physicsVal,
const Light::Material materialVal,
const GameFramework::GameObjCategory gameObjCategory,
const bool moveInitialFlag )
{
GraphicsFramework::GraphicsObject graphicsObj;
PhysicsFramework::PhysicsObject physicsObj;
GameFramework::GameObject gameObj;
//retrieve the graphics object
graphicsObj = graphicsInterfacePtr->RetrieveGraphicsObject( objectType );
//set the material properties
graphicsObj.GetMaterial().SetMaterialProperties( materialVal.GetAmbient(), materialVal.GetEmissive(), materialVal.GetDiffuse(),
materialVal.GetSpecular(), materialVal.GetShininess() );
//set up the physics object
physicsObj = this->CreatePhysicsObject( physicsVal.GetPosition(), physicsVal.GetVelocity(), physicsVal.GetScale(), physicsVal.GetRotation(),
physicsVal.GetMass(), physicsVal.GetMovementSpeed(), physicsVal.GetRotationalSpeed(), physicsVal.GetAcceleration(), moveInitialFlag );
//////////////////////////////////////////////////////////////////////////////////////////////////////////
if ( objectType == CUBE_OBJTYPE || objectType == CUBE2_OBJTYPE )
{
std::string objNameFromFile;
if ( objectType == CUBE_OBJTYPE )
{
objNameFromFile = "cube";
}
else if ( objectType == CUBE2_OBJTYPE )
{
objNameFromFile = "cube2";
}
//compute for the line normal
this->ComputeLineNormal( objNameFromFile, physicsObj );
}
else if ( objectType == GRID_OBJTYPE )
{
//compute for the plane normal
this->ComputePlaneNormal( "grid2D", physicsObj );
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//create the game object
gameObj = this->CreateGameObject( graphicsObj, physicsObj );
gameObj.SetType( objectType );
gameObj.SetIdentifier( gameObjIdentifier );
gameObj.SetCategory( gameObjCategory );
//contain the game object
this->ContainGameObject( gameObj );
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
Generates the pending game object.
This also adds the generated pending game object to the vector so it can be reused by the game
\param gameObjIdentifier
the identifier of the game object
\param objectType
the type of the geometry
\param graphicsInterfacePtr
the graphics interface
\return
*/
/******************************************************************************/
void MyGeometryOM::GeneratePendingGameObject( const unsigned gameObjIdentifier, const unsigned objectType,
GraphicsFramework::GraphicsInterface* const graphicsInterfacePtr )
{
GraphicsFramework::GraphicsObject graphicsObj;
PhysicsFramework::PhysicsObject physicsObj;
GameFramework::GameObject gameObj;
//retrieve the graphics object
graphicsObj = graphicsInterfacePtr->RetrieveGraphicsObject( objectType );
//create the game object
gameObj = this->CreateGameObject( graphicsObj, physicsObj );
gameObj.SetType( objectType );
gameObj.SetIdentifier( gameObjIdentifier );
//contain the game object
this->ContainGameObject( gameObj );
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
Load texture objects
\param graphicsInterfacePtr
the pointer to the graphics interface
\return
*/
/******************************************************************************/
void MyGeometryOM::LoadTextureObjects( GraphicsFramework::GraphicsInterface* const graphicsInterfacePtr )
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//load the environment textures
/*
this->LoadCubeMapImages( graphicsInterfacePtr, "SpringCubeMap",
"SpringCubeMapRight", "SpringCubeMapRight.tga",
"SpringCubeMapLeft", "SpringCubeMapLeft.tga",
"SpringCubeMapTop", "SpringCubeMapTop.tga",
"SpringCubeMapBottom", "SpringCubeMapBottom.tga",
"SpringCubeMapFront", "SpringCubeMapFront.tga",
"SpringCubeMapBack", "SpringCubeMapBack.tga" );
*/
this->LoadDualParaboloidImages( graphicsInterfacePtr,
"TestFrontFaceEnvMap", "TestEnvMapFront.tga",
"TestBackFaceEnvMap", "TestEnvMapBack.tga" );
this->LoadCubeMapImages( graphicsInterfacePtr, "TestEnvMap",
"TestEnvMapRight", "TestEnvMapRight.tga",
"TestEnvMapLeft", "TestEnvMapLeft.tga",
"TestEnvMapTop", "TestEnvMapTop.tga",
"TestEnvMapBottom", "TestEnvMapBottom.tga",
"TestEnvMapFront", "TestEnvMapFront.tga",
"TestEnvMapBack", "TestEnvMapBack.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "TestEnvMapRight", "TestEnvMapRight.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "TestEnvMapLeft", "TestEnvMapLeft.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "TestEnvMapTop", "TestEnvMapTop.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "TestEnvMapBottom", "TestEnvMapBottom.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "TestEnvMapFront", "TestEnvMapFront.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "TestEnvMapBack", "TestEnvMapBack.tga" );
this->LoadCubeMapImages( graphicsInterfacePtr, "StellarEnvMap",
"StellarEnvMapRight", "interstellar_rt.tga",
"StellarEnvMapLeft", "interstellar_lf.tga",
"StellarEnvMapTop", "interstellar_up.tga",
"StellarEnvMapBottom", "interstellar_dn.tga",
"StellarEnvMapFront", "interstellar_bk.tga",
"StellarEnvMapBack", "interstellar_ft.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "StellarEnvMapRight", "interstellar_rt.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "StellarEnvMapLeft", "interstellar_lf.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "StellarEnvMapTop", "interstellar_up.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "StellarEnvMapBottom", "interstellar_dn.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "StellarEnvMapFront", "interstellar_bk.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "StellarEnvMapBack", "interstellar_ft.tga" );
//this->LoadTextureImage( graphicsInterfacePtr, "SpringCubeMapRight", "SpringCubeMapRight.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "EthanCochardLongboard", "EthanCochardLongboard.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "WoodenCrate", "WoodenCrate.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "Road", "Road.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "WallSpace", "WallSpace.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "CheckerStoneBlock", "CheckerStoneBlock.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "DirtyWindow", "DirtyWindow.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "EarthMap", "EarthMap.tga" );
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
//load the textures for the N puzzle
this->LoadTextureImage( graphicsInterfacePtr, "MarbleTexture1", "MarbleTexture1.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "MarbleTexture2", "MarbleTexture2.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "MarbleTexture3", "MarbleTexture3.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "MarbleTexture4", "MarbleTexture4.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "MarbleTexture5", "MarbleTexture5.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "MarbleTexture6", "MarbleTexture6.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "MarbleTexture7", "MarbleTexture7.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "MarbleTexture8", "MarbleTexture8.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "MarbleTexture9", "MarbleTexture9.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "MarbleTexture10", "MarbleTexture10.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "MarbleTexture11", "MarbleTexture11.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "MarbleTexture12", "MarbleTexture12.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "MarbleTexture13", "MarbleTexture13.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "MarbleTexture14", "MarbleTexture14.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "MarbleTexture15", "MarbleTexture15.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "MarbleTexture16", "MarbleTexture16.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "MarbleTextureP", "MarbleTextureP.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "MarbleTextureU", "MarbleTextureU.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "MarbleTextureZ", "MarbleTextureZ.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "MarbleTextureL", "MarbleTextureL.tga" );
this->LoadTextureImage( graphicsInterfacePtr, "MarbleTextureE", "MarbleTextureE.tga" );
*/
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
Load object meshes
\param graphicsInterfacePtr
the pointer to the graphics interface
\return
*/
/******************************************************************************/
void MyGeometryOM::LoadMeshObjects( GraphicsFramework::GraphicsInterface* const graphicsInterfacePtr )
{
//load the textures
this->LoadTextureObjects( graphicsInterfacePtr );
//Loads the mesh to the graphics object.
//This also adds the generated graphics object to the map so it can be reused when creating game objects
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
//for mesh objects for the N puzzle
const char * textureNamesBlock1[] = { "MarbleTexture1" };
this->LoadMeshToGraphicsObject( BLOCK_1_OBJTYPE, graphicsInterfacePtr, textureNamesBlock1, 1 );
const char * textureNamesBlock2[] = { "MarbleTexture2" };
this->LoadMeshToGraphicsObject( BLOCK_2_OBJTYPE, graphicsInterfacePtr, textureNamesBlock2, 1 );
const char * textureNamesBlock3[] = { "MarbleTexture3" };
this->LoadMeshToGraphicsObject( BLOCK_3_OBJTYPE, graphicsInterfacePtr, textureNamesBlock3, 1 );
const char * textureNamesBlock4[] = { "MarbleTexture4" };
this->LoadMeshToGraphicsObject( BLOCK_4_OBJTYPE, graphicsInterfacePtr, textureNamesBlock4, 1 );
const char * textureNamesBlock5[] = { "MarbleTexture5" };
this->LoadMeshToGraphicsObject( BLOCK_5_OBJTYPE, graphicsInterfacePtr, textureNamesBlock5, 1 );
const char * textureNamesBlock6[] = { "MarbleTexture6" };
this->LoadMeshToGraphicsObject( BLOCK_6_OBJTYPE, graphicsInterfacePtr, textureNamesBlock6, 1 );
const char * textureNamesBlock7[] = { "MarbleTexture7" };
this->LoadMeshToGraphicsObject( BLOCK_7_OBJTYPE, graphicsInterfacePtr, textureNamesBlock7, 1 );
const char * textureNamesBlock8[] = { "MarbleTexture8" };
this->LoadMeshToGraphicsObject( BLOCK_8_OBJTYPE, graphicsInterfacePtr, textureNamesBlock8, 1 );
const char * textureNamesBlock9[] = { "MarbleTexture9" };
this->LoadMeshToGraphicsObject( BLOCK_9_OBJTYPE, graphicsInterfacePtr, textureNamesBlock9, 1 );
const char * textureNamesBlock10[] = { "MarbleTexture10" };
this->LoadMeshToGraphicsObject( BLOCK_10_OBJTYPE, graphicsInterfacePtr, textureNamesBlock10, 1 );
const char * textureNamesBlock11[] = { "MarbleTexture11" };
this->LoadMeshToGraphicsObject( BLOCK_11_OBJTYPE, graphicsInterfacePtr, textureNamesBlock11, 1 );
const char * textureNamesBlock12[] = { "MarbleTexture12" };
this->LoadMeshToGraphicsObject( BLOCK_12_OBJTYPE, graphicsInterfacePtr, textureNamesBlock12, 1 );
const char * textureNamesBlock13[] = { "MarbleTexture13" };
this->LoadMeshToGraphicsObject( BLOCK_13_OBJTYPE, graphicsInterfacePtr, textureNamesBlock13, 1 );
const char * textureNamesBlock14[] = { "MarbleTexture14" };
this->LoadMeshToGraphicsObject( BLOCK_14_OBJTYPE, graphicsInterfacePtr, textureNamesBlock14, 1 );
const char * textureNamesBlock15[] = { "MarbleTexture15" };
this->LoadMeshToGraphicsObject( BLOCK_15_OBJTYPE, graphicsInterfacePtr, textureNamesBlock15, 1 );
const char * textureNamesBlock16[] = { "MarbleTexture16" };
this->LoadMeshToGraphicsObject( BLOCK_16_OBJTYPE, graphicsInterfacePtr, textureNamesBlock16, 1 );
const char * textureNamesBlockP[] = { "MarbleTextureP" };
this->LoadMeshToGraphicsObject( BLOCK_P_OBJTYPE, graphicsInterfacePtr, textureNamesBlockP, 1 );
const char * textureNamesBlockU[] = { "MarbleTextureU" };
this->LoadMeshToGraphicsObject( BLOCK_U_OBJTYPE, graphicsInterfacePtr, textureNamesBlockU, 1 );
const char * textureNamesBlockZ[] = { "MarbleTextureZ" };
this->LoadMeshToGraphicsObject( BLOCK_Z_OBJTYPE, graphicsInterfacePtr, textureNamesBlockZ, 1 );
const char * textureNamesBlockL[] = { "MarbleTextureL" };
this->LoadMeshToGraphicsObject( BLOCK_L_OBJTYPE, graphicsInterfacePtr, textureNamesBlockL, 1 );
const char * textureNamesBlockE[] = { "MarbleTextureE" };
this->LoadMeshToGraphicsObject( BLOCK_E_OBJTYPE, graphicsInterfacePtr, textureNamesBlockE, 1 );
*/
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
this->LoadMeshToGraphicsObject( GRID_OBJTYPE, graphicsInterfacePtr );
/*
const char * textureNamesFace1[] = { "TestEnvMapRight" };
const char * textureNamesFace2[] = { "TestEnvMapLeft" };
const char * textureNamesFace3[] = { "TestEnvMapTop" };
const char * textureNamesFace4[] = { "TestEnvMapBottom" };
const char * textureNamesFace5[] = { "TestEnvMapFront" };
const char * textureNamesFace6[] = { "TestEnvMapBack" };
*/
const char * textureNamesFace1[] = { "StellarEnvMapRight" };
const char * textureNamesFace2[] = { "StellarEnvMapLeft" };
const char * textureNamesFace3[] = { "StellarEnvMapTop" };
const char * textureNamesFace4[] = { "StellarEnvMapBottom" };
const char * textureNamesFace5[] = { "StellarEnvMapFront" };
const char * textureNamesFace6[] = { "StellarEnvMapBack" };
this->LoadMeshToGraphicsObject( GRID2_OBJTYPE, graphicsInterfacePtr, 0, textureNamesFace1, 1 );
this->LoadMeshToGraphicsObject( GRID3_OBJTYPE, graphicsInterfacePtr, 0, textureNamesFace2, 1 );
this->LoadMeshToGraphicsObject( GRID4_OBJTYPE, graphicsInterfacePtr, 0, textureNamesFace3, 1 );
this->LoadMeshToGraphicsObject( GRID5_OBJTYPE, graphicsInterfacePtr, 0, textureNamesFace4, 1 );
this->LoadMeshToGraphicsObject( GRID6_OBJTYPE, graphicsInterfacePtr, 0, textureNamesFace5, 1 );
this->LoadMeshToGraphicsObject( GRID7_OBJTYPE, graphicsInterfacePtr, 0, textureNamesFace6, 1 );
//const char * textureNames[] = { "EthanCochardLongboard" };
//this->LoadMeshToGraphicsObject( POLYGON_OBJTYPE, graphicsInterfacePtr, "SpringCubeMap", textureNames, 1 );
this->LoadMeshToGraphicsObject( POLYGON_OBJTYPE, graphicsInterfacePtr, "TestEnvMap" );
const char * textureNames2[] = { "WoodenCrate" };
this->LoadMeshToGraphicsObject( CUBE_OBJTYPE, graphicsInterfacePtr, 0, textureNames2, 1 );
const char * textureNames3[] = { "WallSpace" };
this->LoadMeshToGraphicsObject( CUBE2_OBJTYPE, graphicsInterfacePtr, 0, textureNames3, 1 );
const char * textureNames4[] = { "Road" };
this->LoadMeshToGraphicsObject( CUBE3_OBJTYPE, graphicsInterfacePtr, 0, textureNames4, 1 );
this->LoadMeshToGraphicsObject( CUBE4_OBJTYPE, graphicsInterfacePtr, "TestEnvMap" );
/*
const char * textureNames3[] = { "Road" };
this->LoadMeshToGraphicsObject( CUBE2_OBJTYPE, graphicsInterfacePtr, 0, textureNames3, 1 );
const char * textureNames4[] = { "WallSpace" };
this->LoadMeshToGraphicsObject( CUBE3_OBJTYPE, graphicsInterfacePtr, 0, textureNames4, 1 );
const char * textureNames5[] = { "DirtyWindow" };
this->LoadMeshToGraphicsObject( CUBE4_OBJTYPE, graphicsInterfacePtr, 0, textureNames5, 1 );
*/
const char * textureNames6[] = { "CheckerStoneBlock", "WallSpace", "Road" };
this->LoadMeshToGraphicsObject( CYLINDER_OBJTYPE, graphicsInterfacePtr, 0, textureNames6, 3 );
this->LoadMeshToGraphicsObject( CYLINDER2_OBJTYPE, graphicsInterfacePtr, "TestEnvMap" );
const char * textureNames7[] = { "WallSpace" };
this->LoadMeshToGraphicsObject( CYLINDER3_OBJTYPE, graphicsInterfacePtr, 0, textureNames7, 1 );
const char * textureNames8[] = { "DirtyWindow" };
this->LoadMeshToGraphicsObject( CYLINDER4_OBJTYPE, graphicsInterfacePtr, 0, textureNames8, 1 );
this->LoadMeshToGraphicsObject( SPHERE_OBJTYPE, graphicsInterfacePtr, "TestEnvMap" );
this->LoadMeshToGraphicsObject( SPHERE2_OBJTYPE, graphicsInterfacePtr );
const char * textureNames9[] = { "EarthMap" };
this->LoadMeshToGraphicsObject( SPHERE3_OBJTYPE, graphicsInterfacePtr, 0, textureNames9, 1 );
const char * textureNames10[] = { "CheckerStoneBlock" };
this->LoadMeshToGraphicsObject( CONE_OBJTYPE, graphicsInterfacePtr, 0, textureNames10, 1 );
/*
this->LoadMeshToGraphicsObject( CONE_OBJTYPE, graphicsInterfacePtr );
this->LoadMeshToGraphicsObject( CONE2_OBJTYPE, graphicsInterfacePtr );
this->LoadMeshToGraphicsObject( SPHERE_OBJTYPE, graphicsInterfacePtr );
this->LoadMeshToGraphicsObject( SPHERE2_OBJTYPE, graphicsInterfacePtr );
this->LoadMeshToGraphicsObject( SPHERE3_OBJTYPE, graphicsInterfacePtr );
this->LoadMeshToGraphicsObject( SPHERE4_OBJTYPE, graphicsInterfacePtr );
this->LoadMeshToGraphicsObject( HEXASPHERE_OBJTYPE, graphicsInterfacePtr );
this->LoadMeshToGraphicsObject( SATELLITE_OBJTYPE, graphicsInterfacePtr );
*/
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
The helper function to loadd the mesh to the graphics object.
This also adds the generated graphics object to the map so it can be reused when creating game objects
\param objName
the name of the object
\param geometryObjectType
the type of the geometry
\param graphicsInterfacePtr
the pointer to the graphics interface
\param baseGeometryBuilderPtr
the pointer to the base geometry builder
\param envTextureName
the name of the environment texture
\param textureName
the array containing the name of the textures
\param arrSize
the array size
\return
*/
/******************************************************************************/
void MyGeometryOM::LoadMeshToGraphicsObjectHelper( const std::string objName,
const GeometryObjectType geometryObjectType,
GraphicsFramework::GraphicsInterface* const graphicsInterfacePtr,
GraphicsFramework::BaseGeometryBuilder* const baseGeometryBuilderPtr,
const char * envTextureName,
const char ** textureName, const unsigned arrSize )
{
GraphicsFramework::GraphicsObject graphicsObj;
GraphicsFramework::Mesh mesh;
//get the mesh parameters from the file
GraphicsFramework::MeshParameterContainer meshParameterContainer = this->GetMeshParametersFromFile( objName, FILE_NAME );
//generate the mesh
this->GenerateMesh( meshParameterContainer, baseGeometryBuilderPtr, mesh );
//validate if there is a texture name being passed
if ( envTextureName == 0 && textureName == 0 && arrSize == 0 )
{
//create the graphics object
graphicsObj = this->CreateGraphicsObject( static_cast<unsigned>( geometryObjectType ), graphicsInterfacePtr, mesh );
}
else
{
//create the graphics object
graphicsObj = this->CreateGraphicsObject( static_cast<unsigned>( geometryObjectType ), graphicsInterfacePtr, mesh, envTextureName, textureName, arrSize );
}
//add the base geometry builder to the map
this->ContainBaseGeometryBuilder( static_cast<unsigned>( geometryObjectType ), baseGeometryBuilderPtr );
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
Loads the mesh to the graphics object.
\param geometryObjectType
the type of the geometry
\param graphicsInterfacePtr
the pointer to the graphics interface
\param envTextureName
the environment texture name
\param textureName
the array containing the name of the textures
\param arrSize
the array size
\return
*/
/******************************************************************************/
void MyGeometryOM::LoadMeshToGraphicsObject( const GeometryObjectType geometryObjectType,
GraphicsFramework::GraphicsInterface* const graphicsInterfacePtr,
const char * envTextureName,
const char ** textureName, const unsigned arrSize )
{
//these pointers will be destroyed by the game object manager base class destructor
GraphicsFramework::Grid2DBuilder * gridBuilder = 0;
GraphicsFramework::PolygonBuilder * polygonBuilder = 0;
GraphicsFramework::CubeBuilder * cubeBuilder = 0;
GraphicsFramework::CylinderBuilder * cylinderBuilder = 0;
GraphicsFramework::ConeBuilder * coneBuilder = 0;
GraphicsFramework::SphereBuilder * sphereBuilder = 0;
//GraphicsFramework::SatelliteBuilder * satelliteBuilder = 0;
if ( geometryObjectType == BLOCK_1_OBJTYPE || geometryObjectType == BLOCK_2_OBJTYPE || geometryObjectType == BLOCK_3_OBJTYPE || geometryObjectType == BLOCK_4_OBJTYPE
|| geometryObjectType == BLOCK_5_OBJTYPE || geometryObjectType == BLOCK_6_OBJTYPE || geometryObjectType == BLOCK_7_OBJTYPE || geometryObjectType == BLOCK_8_OBJTYPE
|| geometryObjectType == BLOCK_9_OBJTYPE || geometryObjectType == BLOCK_10_OBJTYPE || geometryObjectType == BLOCK_11_OBJTYPE || geometryObjectType == BLOCK_12_OBJTYPE
|| geometryObjectType == BLOCK_13_OBJTYPE || geometryObjectType == BLOCK_14_OBJTYPE || geometryObjectType == BLOCK_15_OBJTYPE || geometryObjectType == BLOCK_16_OBJTYPE
|| geometryObjectType == BLOCK_P_OBJTYPE || geometryObjectType == BLOCK_U_OBJTYPE || geometryObjectType == BLOCK_Z_OBJTYPE
|| geometryObjectType == BLOCK_L_OBJTYPE || geometryObjectType == BLOCK_E_OBJTYPE
)
{
if ( cubeBuilder == 0 )
{
cubeBuilder = new GraphicsFramework::CubeBuilder();
}
this->LoadMeshToGraphicsObjectHelper( "cube", geometryObjectType, graphicsInterfacePtr, cubeBuilder, envTextureName, textureName, arrSize );
}
if ( geometryObjectType == GRID2_OBJTYPE || geometryObjectType == GRID3_OBJTYPE || geometryObjectType == GRID4_OBJTYPE
|| geometryObjectType == GRID5_OBJTYPE || geometryObjectType == GRID6_OBJTYPE || geometryObjectType == GRID7_OBJTYPE )
{
if ( gridBuilder == 0 )
{
gridBuilder = new GraphicsFramework::Grid2DBuilder();
}
this->LoadMeshToGraphicsObjectHelper( "grid2D", geometryObjectType, graphicsInterfacePtr, gridBuilder, envTextureName, textureName, arrSize );
}
switch ( geometryObjectType )
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
case GRID_OBJTYPE:
{
if ( gridBuilder == 0 )
{
gridBuilder = new GraphicsFramework::Grid2DBuilder();
}
this->LoadMeshToGraphicsObjectHelper( "grid2D", geometryObjectType, graphicsInterfacePtr, gridBuilder, envTextureName, textureName, arrSize );
break;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
case POLYGON_OBJTYPE:
{
if ( polygonBuilder == 0 )
{
polygonBuilder = new GraphicsFramework::PolygonBuilder();
}
this->LoadMeshToGraphicsObjectHelper( "poly2D", geometryObjectType, graphicsInterfacePtr, polygonBuilder, envTextureName, textureName, arrSize );
break;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
case CUBE_OBJTYPE:
{
if ( cubeBuilder == 0 )
{
cubeBuilder = new GraphicsFramework::CubeBuilder();
}
this->LoadMeshToGraphicsObjectHelper( "cube", geometryObjectType, graphicsInterfacePtr, cubeBuilder, envTextureName, textureName, arrSize );
break;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
case CYLINDER_OBJTYPE:
{
if ( cylinderBuilder == 0 )
{
cylinderBuilder = new GraphicsFramework::CylinderBuilder();
}
this->LoadMeshToGraphicsObjectHelper( "cylinder", geometryObjectType, graphicsInterfacePtr, cylinderBuilder, envTextureName, textureName, arrSize );
break;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
case CONE_OBJTYPE:
{
if ( coneBuilder == 0 )
{
coneBuilder = new GraphicsFramework::ConeBuilder();
}
this->LoadMeshToGraphicsObjectHelper( "cone", geometryObjectType, graphicsInterfacePtr, coneBuilder, envTextureName, textureName, arrSize );
break;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
case SPHERE_OBJTYPE:
{
if ( sphereBuilder == 0 )
{
sphereBuilder = new GraphicsFramework::SphereBuilder();
}
this->LoadMeshToGraphicsObjectHelper( "sphere", geometryObjectType, graphicsInterfacePtr, sphereBuilder, envTextureName, textureName, arrSize );
break;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
case CYLINDER2_OBJTYPE:
{
if ( cylinderBuilder == 0 )
{
cylinderBuilder = new GraphicsFramework::CylinderBuilder();
}
this->LoadMeshToGraphicsObjectHelper( "cylinder2", geometryObjectType, graphicsInterfacePtr, cylinderBuilder, envTextureName, textureName, arrSize );
break;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
case CYLINDER3_OBJTYPE:
{
if ( cylinderBuilder == 0 )
{
cylinderBuilder = new GraphicsFramework::CylinderBuilder();
}
this->LoadMeshToGraphicsObjectHelper( "cylinder3", geometryObjectType, graphicsInterfacePtr, cylinderBuilder, envTextureName, textureName, arrSize );
break;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
case CYLINDER4_OBJTYPE:
{
if ( cylinderBuilder == 0 )
{
cylinderBuilder = new GraphicsFramework::CylinderBuilder();
}
this->LoadMeshToGraphicsObjectHelper( "cylinder4", geometryObjectType, graphicsInterfacePtr, cylinderBuilder, envTextureName, textureName, arrSize );
break;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
case SPHERE2_OBJTYPE:
{
if ( sphereBuilder == 0 )
{
sphereBuilder = new GraphicsFramework::SphereBuilder();
}
this->LoadMeshToGraphicsObjectHelper( "sphere2", geometryObjectType, graphicsInterfacePtr, sphereBuilder, envTextureName, textureName, arrSize );
break;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
case SPHERE3_OBJTYPE:
{
if ( sphereBuilder == 0 )
{
sphereBuilder = new GraphicsFramework::SphereBuilder();
}
this->LoadMeshToGraphicsObjectHelper( "sphere3", geometryObjectType, graphicsInterfacePtr, sphereBuilder, envTextureName, textureName, arrSize );
break;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
case SPHERE4_OBJTYPE:
{
if ( sphereBuilder == 0 )
{
sphereBuilder = new GraphicsFramework::SphereBuilder();
}
this->LoadMeshToGraphicsObjectHelper( "sphere4", geometryObjectType, graphicsInterfacePtr, sphereBuilder, envTextureName, textureName, arrSize );
break;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
case HEXASPHERE_OBJTYPE:
{
if ( sphereBuilder == 0 )
{
sphereBuilder = new GraphicsFramework::SphereBuilder();
}
this->LoadMeshToGraphicsObjectHelper( "hexaSphere", geometryObjectType, graphicsInterfacePtr, sphereBuilder, envTextureName, textureName, arrSize );
break;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
case CUBE2_OBJTYPE:
{
if ( cubeBuilder == 0 )
{
cubeBuilder = new GraphicsFramework::CubeBuilder();
}
this->LoadMeshToGraphicsObjectHelper( "cube2", geometryObjectType, graphicsInterfacePtr, cubeBuilder, envTextureName, textureName, arrSize );
break;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
case CUBE3_OBJTYPE:
{
if ( cubeBuilder == 0 )
{
cubeBuilder = new GraphicsFramework::CubeBuilder();
}
this->LoadMeshToGraphicsObjectHelper( "cube", geometryObjectType, graphicsInterfacePtr, cubeBuilder, envTextureName, textureName, arrSize );
break;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
case CUBE4_OBJTYPE:
{
if ( cubeBuilder == 0 )
{
cubeBuilder = new GraphicsFramework::CubeBuilder();
}
this->LoadMeshToGraphicsObjectHelper( "cube3", geometryObjectType, graphicsInterfacePtr, cubeBuilder, envTextureName, textureName, arrSize );
break;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
case CONE2_OBJTYPE:
{
if ( coneBuilder == 0 )
{
coneBuilder = new GraphicsFramework::ConeBuilder();
}
this->LoadMeshToGraphicsObjectHelper( "cone2", geometryObjectType, graphicsInterfacePtr, coneBuilder, envTextureName, textureName, arrSize );
break;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
case SATELLITE_OBJTYPE:
{
satelliteBuilder = new GraphicsFramework::SatelliteBuilder(
graphicsInterfacePtr->m_matrixStack,
graphicsInterfacePtr->GetGraphicsObjectMap(),
this->GetBaseGeometryBuilderMap() );
//add the graphics object to the graphics object map in the graphics interface
graphicsInterfacePtr->ContainGraphicsObject( static_cast<unsigned>( geometryObjectType ), GraphicsFramework::GraphicsObject() );
//add the base geometry builder to the map
this->ContainBaseGeometryBuilder( static_cast<unsigned>( geometryObjectType ), satelliteBuilder );
break;
}
*/
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
default:
break;
}//end switch
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
Reads the mesh parameters from the file
\param objName
the name of the object in the file
\param fileName
the file name
\return MeshParameterContainer
the container of mesh parameters
*/
/******************************************************************************/
const GraphicsFramework::MeshParameterContainer MyGeometryOM::GetMeshParametersFromFile( const std::string objName, const char * fileName ) const
{
GraphicsFramework::MeshParameterContainer meshParameterContainer;
//read the data from file
File::GeometryParameterContainer myGeomParam;
File::File myFile;
myFile.OpenFile( fileName, myGeomParam );
//get the mesh parameters needed to create the geometry
myGeomParam = myFile.GetFileDataMap().find( objName )->second;
meshParameterContainer.m_radius = myGeomParam.GetRadius();
meshParameterContainer.m_width = myGeomParam.GetWidth();
meshParameterContainer.m_height = myGeomParam.GetHeight();
meshParameterContainer.m_xSubdivisions = myGeomParam.GetXSubdivisions();
meshParameterContainer.m_ySubdivisions = myGeomParam.GetYSubdivisions();
meshParameterContainer.m_slices = myGeomParam.GetSlices();
meshParameterContainer.m_stacks = myGeomParam.GetStacks();
meshParameterContainer.m_hasCenterPoint = myGeomParam.GetHasCenterPoint();
meshParameterContainer.m_ctrPtVertPos = myGeomParam.GetCenterVerticalPosition();
meshParameterContainer.m_verticalPos = myGeomParam.GetVerticalPosition();
meshParameterContainer.m_red = myGeomParam.GetRed();
meshParameterContainer.m_green = myGeomParam.GetGreen();
meshParameterContainer.m_blue = myGeomParam.GetBlue();
meshParameterContainer.m_alpha = myGeomParam.GetAlpha();
return meshParameterContainer;
}
} //end namespace MyGeometryGame | 43.335863 | 171 | 0.621749 | [
"mesh",
"geometry",
"object",
"vector"
] |
a81ac167557c599a1dd76878e948b8a0bdea2d5b | 1,533 | cpp | C++ | backup/2/leetcode/c++/archive/14.cpp | yangyanzhan/code-camp | 4272564e916fc230a4a488f92ae32c07d355dee0 | [
"Apache-2.0"
] | 21 | 2019-11-16T19:08:35.000Z | 2021-11-12T12:26:01.000Z | backup/2/leetcode/c++/archive/14.cpp | yangyanzhan/code-camp | 4272564e916fc230a4a488f92ae32c07d355dee0 | [
"Apache-2.0"
] | 1 | 2022-02-04T16:02:53.000Z | 2022-02-04T16:02:53.000Z | backup/2/leetcode/c++/archive/14.cpp | yangyanzhan/code-camp | 4272564e916fc230a4a488f92ae32c07d355dee0 | [
"Apache-2.0"
] | 4 | 2020-05-15T19:39:41.000Z | 2021-10-30T06:40:31.000Z | // Hi, I'm Yanzhan. For more algothmic problems, visit my Youtube Channel (Yanzhan Yang's Youtube Channel) : https://www.youtube.com/channel/UCDkz-__gl3frqLexukpG0DA?view_as=subscriber or my Twitter Account (Yanzhan Yang's Twitter) : https://twitter.com/YangYanzhan or my GitHub HomePage (Yanzhan Yang's GitHub HomePage) : https://yanzhan.site .
// For this specific algothmic problem, visit my Youtube Video : .
// It's fascinating to solve algothmic problems, follow Yanzhan to learn more!
class Solution {
public:
string longestCommonPrefix(vector<string> &strs) {
if (strs.size() == 0) {
return "";
}
if (strs.size() == 1) {
return strs[0];
}
int n = strs[0].size();
for (int i = 1; i < strs.size(); i++) {
int m = strs[i].size();
if (m < n) {
n = m;
}
}
if (n == 0) {
return "";
}
char *chars = new char[n + 1];
int count = 0;
while (count < n) {
char ch = strs[0][count];
bool match = true;
for (int i = 1; i < strs.size(); i++) {
if (ch != strs[i][count]) {
match = false;
break;
}
}
if (!match) {
break;
}
chars[count++] = ch;
}
chars[count] = '\0';
string res(chars, chars + count);
delete[] chars;
return res;
}
};
| 33.326087 | 345 | 0.4788 | [
"vector"
] |
a81d6508850f42933a636f10a2ceb5842ebe7137 | 24,902 | cpp | C++ | velox/dwio/dwrf/reader/FlatMapColumnReader.cpp | vancexu/velox | fa076fd9eab6ae4090ed9b9b91c4e7658d4ee1e4 | [
"Apache-2.0"
] | null | null | null | velox/dwio/dwrf/reader/FlatMapColumnReader.cpp | vancexu/velox | fa076fd9eab6ae4090ed9b9b91c4e7658d4ee1e4 | [
"Apache-2.0"
] | null | null | null | velox/dwio/dwrf/reader/FlatMapColumnReader.cpp | vancexu/velox | fa076fd9eab6ae4090ed9b9b91c4e7658d4ee1e4 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "velox/dwio/dwrf/reader/FlatMapColumnReader.h"
#include <folly/json.h>
#include "velox/common/base/BitUtil.h"
#include "velox/dwio/dwrf/reader/FlatMapHelper.h"
namespace facebook::velox::dwrf {
using dwio::common::TypeWithId;
using memory::MemoryPool;
using namespace flatmap_helper;
StringKeyBuffer::StringKeyBuffer(
MemoryPool& pool,
const std::vector<std::unique_ptr<KeyNode<StringView>>>& nodes)
: data_{pool, nodes.size() + 1} {
uint64_t size = 0;
for (auto& node : nodes) {
auto& str = node->getKey().get();
size += str.size();
}
buffer_ = AlignedBuffer::allocate<char>(size, &pool);
auto data = buffer_->asMutable<char>();
uint32_t ordinal = 0;
for (auto& node : nodes) {
node->setOrdinal(ordinal);
auto& str = node->getKey().get();
std::memcpy(data, str.data(), str.size());
data_[ordinal++] = data;
data += str.size();
}
data_[ordinal] = data;
}
namespace {
template <typename T>
KeyValue<T> extractKey(const proto::KeyInfo& info) {
return KeyValue<T>(info.intkey());
}
template <>
KeyValue<StringView> extractKey<StringView>(const proto::KeyInfo& info) {
return KeyValue<StringView>(StringView(info.byteskey()));
}
template <typename T>
KeyValue<T> parseKeyValue(std::string_view str) {
return KeyValue<T>(folly::to<T>(str));
}
template <>
KeyValue<StringView> parseKeyValue<StringView>(std::string_view str) {
return KeyValue<StringView>(StringView(str));
}
template <typename T>
struct KeyProjection {
KeyProjectionMode mode = KeyProjectionMode::ALLOW;
KeyValue<T> value;
};
template <typename T>
KeyProjection<T> convertDynamic(const folly::dynamic& v) {
constexpr char reject_prefix = '!';
const auto str = v.asString();
const std::string_view view(str);
if (!view.empty() && view.front() == reject_prefix) {
return {
.mode = KeyProjectionMode::REJECT,
.value = parseKeyValue<T>(view.substr(1)),
};
} else {
return {
.mode = KeyProjectionMode::ALLOW,
.value = parseKeyValue<T>(view),
};
}
}
template <>
KeyProjection<StringView> convertDynamic<StringView>(const folly::dynamic& v) {
return {
.mode = KeyProjectionMode::ALLOW,
.value = KeyValue<StringView>(StringView(v.asString()))};
}
template <typename T>
void forEachConfiguredKey(
const std::function<void(KeyValue<T>&&)>& cb,
const std::shared_ptr<const TypeWithId>& requestedType,
const StripeStreams& stripe) {
// if keys filter is passed, translate them as the internal filter
const auto& cs = stripe.getColumnSelector();
const auto expr = cs.getNode(requestedType->id)->getNode().expression;
if (!expr.empty()) {
// JSON parse option?
const auto array = folly::parseJson(expr);
for (const auto& v : array) {
DWIO_ENSURE(!v.isNull(), "map key filter should not be null");
cb(convertDynamic<T>(v).value);
}
VLOG(1) << "[Flat-Map] key filters count: " << array.size();
}
}
template <typename T>
std::vector<std::unique_ptr<KeyNode<T>>> getKeyNodesFiltered(
const std::function<bool(const KeyValue<T>&)>& keyPredicate,
const std::shared_ptr<const TypeWithId>& requestedType,
const std::shared_ptr<const TypeWithId>& dataType,
StripeStreams& stripe,
memory::MemoryPool& memoryPool) {
std::vector<std::unique_ptr<KeyNode<T>>> keyNodes;
const auto requestedValueType = requestedType->childAt(1);
const auto dataValueType = dataType->childAt(1);
std::unordered_set<size_t> processed;
// load all sub streams
// fetch reader, in map bitmap and key object.
auto streams = stripe.visitStreamsOfNode(
dataValueType->id, [&](const StreamInformation& stream) {
auto sequence = stream.getSequence();
// No need to load shared dictionary stream here.
if (sequence == 0) {
return;
}
// if this branch (sequence) is not in the node list yet
if (processed.count(sequence) == 0) {
EncodingKey seqEk(dataValueType->id, sequence);
auto keyInfo = stripe.getEncoding(seqEk).key();
auto key = extractKey<T>(keyInfo);
// check if we have key filter passed through read schema
if (keyPredicate(key)) {
// fetch reader, in map bitmap and key object.
auto inMap = stripe.getStream(
seqEk.forKind(proto::Stream_Kind_IN_MAP), true);
DWIO_ENSURE_NOT_NULL(inMap, "In map stream is required");
// build seekable
auto inMapDecoder =
createBooleanRleDecoder(std::move(inMap), seqEk);
// std::unique_ptr<ColumnReader>
auto valueReader = ColumnReader::build(
requestedValueType,
dataValueType,
stripe,
FlatMapContext{sequence, inMapDecoder.get()});
keyNodes.push_back(std::make_unique<KeyNode<T>>(
std::move(valueReader),
std::move(inMapDecoder),
key,
sequence,
memoryPool));
processed.insert(sequence);
}
}
});
VLOG(1) << "[Flat-Map] Initialized a flat-map column reader for node "
<< dataType->id << ", keys=" << keyNodes.size()
<< ", streams=" << streams;
return keyNodes;
}
template <typename T>
struct ParsedKeyFilter {
KeyProjectionMode mode = KeyProjectionMode::ALLOW;
std::vector<KeyValue<T>> keys;
};
template <typename T>
ParsedKeyFilter<T> parseKeyFilter(
const std::shared_ptr<const TypeWithId>& requestedType,
const StripeStreams& stripe) {
std::vector<KeyProjectionMode> modes;
std::vector<KeyValue<T>> keys;
auto& cs = stripe.getColumnSelector();
const auto expr = cs.getNode(requestedType->id)->getNode().expression;
if (!expr.empty()) {
// JSON parse option?
auto array = folly::parseJson(expr);
for (auto v : array) {
DWIO_ENSURE(!v.isNull(), "map key filter should not be null");
auto converted = convertDynamic<T>(v);
modes.push_back(converted.mode);
keys.push_back(std::move(converted.value));
}
VLOG(1) << "[Flat-Map] key filters count: " << array.size();
}
DWIO_ENSURE_EQ(modes.size(), keys.size());
// You cannot mix allow key and reject key.
DWIO_ENSURE(
modes.empty() ||
std::all_of(modes.begin(), modes.end(), [&modes](const auto& v) {
return v == modes.front();
}));
return {
.mode = modes.empty() ? KeyProjectionMode::ALLOW : modes.front(),
.keys = std::move(keys)};
}
template <typename T>
KeyPredicate<T> prepareKeyPredicate(
const std::shared_ptr<const TypeWithId>& requestedType,
StripeStreams& stripe) {
auto parsedKeyFilter = parseKeyFilter<T>(requestedType, stripe);
return KeyPredicate<T>(
parsedKeyFilter.mode,
typename KeyPredicate<T>::Lookup(
parsedKeyFilter.keys.begin(), parsedKeyFilter.keys.end()));
}
template <typename T>
std::vector<std::unique_ptr<KeyNode<T>>> rearrangeKeyNodesAsProjectedOrder(
std::vector<std::unique_ptr<KeyNode<T>>>& availableKeyNodes,
const std::vector<std::string>& keys) {
std::vector<std::unique_ptr<KeyNode<T>>> keyNodes(keys.size());
std::unordered_map<KeyValue<T>, size_t, KeyValueHash<T>> keyLookup;
for (size_t i = 0; i < keys.size(); ++i) {
keyLookup[parseKeyValue<T>(keys[i])] = i;
}
for (auto& keyNode : availableKeyNodes) {
const auto it = keyLookup.find(keyNode->getKey());
if (it == keyLookup.end()) {
continue;
}
keyNodes[it->second] = std::move(keyNode);
}
return keyNodes;
}
} // namespace
template <typename T>
FlatMapColumnReader<T>::FlatMapColumnReader(
const std::shared_ptr<const TypeWithId>& requestedType,
const std::shared_ptr<const TypeWithId>& dataType,
StripeStreams& stripe,
FlatMapContext flatMapContext)
: ColumnReader(dataType, stripe, std::move(flatMapContext)),
requestedType_{requestedType},
returnFlatVector_{stripe.getRowReaderOptions().getReturnFlatVector()} {
DWIO_ENSURE_EQ(nodeType_->id, dataType->id);
const auto keyPredicate = prepareKeyPredicate<T>(requestedType, stripe);
keyNodes_ = getKeyNodesFiltered<T>(
[&keyPredicate](const auto& keyValue) { return keyPredicate(keyValue); },
requestedType,
dataType,
stripe,
memoryPool_);
// sort nodes by sequence id so order of keys is fixed
std::sort(keyNodes_.begin(), keyNodes_.end(), [](auto& a, auto& b) {
return a->getSequence() < b->getSequence();
});
initStringKeyBuffer();
}
template <typename T>
uint64_t FlatMapColumnReader<T>::skip(uint64_t numValues) {
// skip basic rows
numValues = ColumnReader::skip(numValues);
// skip every single node
for (auto& node : keyNodes_) {
node->skip(numValues);
}
return numValues;
}
template <typename T>
void resetIfWrongVectorType(VectorPtr& result) {
if (result && !result->as<T>()) {
result.reset();
}
}
template <typename T>
void FlatMapColumnReader<T>::initKeysVector(
VectorPtr& vector,
vector_size_t size) {
initializeFlatVector<T>(vector, memoryPool_, size, false);
vector->setSize(size);
}
template <>
void FlatMapColumnReader<StringView>::initKeysVector(
VectorPtr& vector,
vector_size_t size) {
initializeFlatVector<StringView>(
vector,
memoryPool_,
size,
false,
std::vector<BufferPtr>{stringKeyBuffer_->getBuffer()});
vector->setSize(size);
}
template <typename T>
void FlatMapColumnReader<T>::next(
uint64_t numValues,
VectorPtr& result,
const uint64_t* incomingNulls) {
BufferPtr nulls = readNulls(numValues, result, incomingNulls);
const auto* nullsPtr = nulls ? nulls->as<uint64_t>() : nullptr;
uint64_t nullCount = nullsPtr ? bits::countNulls(nullsPtr, 0, numValues) : 0;
resetIfWrongVectorType<MapVector>(result);
// reuse key/value vectors when possible
VectorPtr keysVector;
VectorPtr valuesVector;
BufferPtr offsets;
BufferPtr lengths;
if (result) {
auto mapVector = result->as<MapVector>();
keysVector = mapVector->mapKeys();
if (returnFlatVector_) {
valuesVector = mapVector->mapValues();
}
offsets = mapVector->mutableOffsets(numValues);
lengths = mapVector->mutableSizes(numValues);
} else {
offsets = AlignedBuffer::allocate<vector_size_t>(numValues, &memoryPool_);
lengths = AlignedBuffer::allocate<vector_size_t>(numValues, &memoryPool_);
}
auto nonNullMaps = numValues - nullCount;
// opt - only loop over nodes that have value
std::vector<KeyNode<T>*> nodes;
utils::BulkBitIterator<char> bulkInMapIter{};
std::vector<const BaseVector*> nodeBatches;
size_t totalChildren = 0;
if (nonNullMaps > 0) {
for (auto& node : keyNodes_) {
// if the node has value filled into key-value batch
// future optimization - enable batch to be sortable on row index
// and below next can be updated to next(keys, values, numValues)
// which writes row index into batch and offsets can be generated
auto batch = node->load(nonNullMaps);
if (batch) {
nodes.emplace_back(node.get());
node->addToBulkInMapBitIterator(bulkInMapIter);
nodeBatches.push_back(batch);
totalChildren += batch->size();
}
}
}
size_t startIndices[nodeBatches.size()];
size_t nodeIndices[nodeBatches.size()];
auto& mapValueType = requestedType_->type->asMap().valueType();
if (totalChildren > 0) {
size_t childOffset = 0;
for (size_t i = 0; i < nodeBatches.size(); i++) {
nodeIndices[i] = 0;
startIndices[i] = childOffset;
childOffset += nodeBatches[i]->size();
}
initKeysVector(keysVector, totalChildren);
initializeVector(valuesVector, mapValueType, memoryPool_, nodeBatches);
if (!returnFlatVector_) {
for (auto batch : nodeBatches) {
valuesVector->append(batch);
}
}
}
BufferPtr indices;
vector_size_t* indicesPtr = nullptr;
if (!returnFlatVector_) {
indices = AlignedBuffer::allocate<int32_t>(totalChildren, &memoryPool_);
indices->setSize(totalChildren * sizeof(vector_size_t));
indicesPtr = indices->asMutable<vector_size_t>();
}
// now we're doing the rotation concat for sure to fill data
vector_size_t offset = 0;
auto* offsetsPtr = offsets->asMutable<vector_size_t>();
auto* lengthsPtr = lengths->asMutable<vector_size_t>();
for (uint64_t i = 0; i < numValues; ++i) {
// case for having map on this row
offsetsPtr[i] = offset;
if (!nullsPtr || !bits::isBitNull(nullsPtr, i)) {
bulkInMapIter.loadNext();
for (size_t j = 0; j < nodes.size(); j++) {
if (bulkInMapIter.hasValueAt(j)) {
nodes[j]->fillKeysVector(keysVector, offset, stringKeyBuffer_.get());
if (returnFlatVector_) {
copyOne(
mapValueType,
*valuesVector,
offset,
*nodeBatches[j],
nodeIndices[j]);
} else {
indicesPtr[offset] = startIndices[j] + nodeIndices[j];
}
offset++;
nodeIndices[j]++;
}
}
}
lengthsPtr[i] = offset - offsetsPtr[i];
}
DWIO_ENSURE_EQ(totalChildren, offset, "fill the same amount of items");
VLOG(1) << "[Flat-Map] num elements: " << numValues
<< ", total children: " << totalChildren;
if (totalChildren > 0 && !returnFlatVector_) {
valuesVector = BaseVector::wrapInDictionary(
nullptr, indices, totalChildren, std::move(valuesVector));
}
// When read-string-as-row flag is on, string readers produce ROW(BIGINT,
// BIGINT) type instead of VARCHAR or VARBINARY. In these cases,
// requestedType_->type is not the right type of the final vector.
auto mapType = (keysVector == nullptr || valuesVector == nullptr)
? requestedType_->type
: MAP(keysVector->type(), valuesVector->type());
// TODO Reuse
result = std::make_shared<MapVector>(
&memoryPool_,
mapType,
nulls,
numValues,
offsets,
lengths,
keysVector,
valuesVector,
nullCount);
}
template <>
void FlatMapColumnReader<StringView>::initStringKeyBuffer() {
stringKeyBuffer_ = std::make_unique<StringKeyBuffer>(memoryPool_, keyNodes_);
}
template <typename T>
uint64_t KeyNode<T>::readInMapData(uint64_t numValues) {
// load a batch for current request
inMapData_.reserve(bits::nwords(numValues) * 8);
auto data = inMapData_.data();
inMap_->next(data, numValues, nullptr);
return bits::countBits(reinterpret_cast<uint64_t*>(data), 0, numValues);
}
// skip number of values in this node
template <typename T>
void KeyNode<T>::skip(uint64_t numValues) {
auto toSkip = readInMapData(numValues);
reader_->skip(toSkip);
}
template <typename T>
BaseVector* KeyNode<T>::load(uint64_t numValues) {
DWIO_ENSURE_GT(numValues, 0, "numValues should be positive");
auto numItems = readInMapData(numValues);
// we're going to load next count of data
if (numItems > 0) {
reader_->next(numItems, vector_);
DWIO_ENSURE_EQ(numItems, vector_->size(), "items loaded assurance");
return vector_.get();
}
return nullptr;
}
template <typename T>
void KeyNode<T>::loadAsChild(
VectorPtr& vec,
uint64_t numValues,
BufferPtr& mergedNulls,
uint64_t nonNullMaps,
const uint64_t* nulls) {
DWIO_ENSURE_GT(numValues, 0, "numValues should be positive");
reader_->next(
numValues, vec, mergeNulls(numValues, mergedNulls, nonNullMaps, nulls));
DWIO_ENSURE_EQ(numValues, vec->size(), "items loaded assurance");
}
template <typename T>
const uint64_t* FOLLY_NULLABLE KeyNode<T>::mergeNulls(
uint64_t numValues,
BufferPtr& mergedNulls,
uint64_t nonNullMaps,
const uint64_t* nulls) {
const auto numItems = readInMapData(nonNullMaps);
if (numItems == 0) {
return getAllNulls(numValues, mergedNulls);
}
const auto inmapNulls = reinterpret_cast<uint64_t*>(inMapData_.data());
if (nulls == nullptr) {
return inmapNulls;
}
auto* result = ensureNullBuffer(numValues, mergedNulls);
uint64_t offsetInMap = 0;
for (uint64_t i = 0; i < numValues; ++i) {
bits::setNull(
result,
i,
bits::isBitNull(nulls, i) ? bits::kNotNull
: bits::isBitNull(inmapNulls, offsetInMap++));
}
return result;
}
template <typename T>
uint64_t* FOLLY_NULLABLE
KeyNode<T>::ensureNullBuffer(uint64_t numValues, BufferPtr& mergedNulls) {
const auto numBytes = bits::nbytes(numValues);
if (!mergedNulls || mergedNulls->capacity() < numBytes) {
mergedNulls = AlignedBuffer::allocate<bool>(numValues, &memoryPool_);
}
return mergedNulls->asMutable<uint64_t>();
}
template <typename T>
const uint64_t* FOLLY_NULLABLE
KeyNode<T>::getAllNulls(uint64_t numValues, BufferPtr& mergedNulls) {
auto* result = ensureNullBuffer(numValues, mergedNulls);
for (uint64_t i = 0; i < numValues; ++i) {
bits::setNull(result, i, true);
}
return result;
}
template <>
void KeyNode<StringView>::fillKeysVector(
VectorPtr& vector,
vector_size_t offset,
const StringKeyBuffer* buffer) {
// Ideally, this should be dynamic_cast, but we would like to avoid the
// cost. We cannot make vector type template variable because for string
// type, we will have two different vector representations
auto& flatVec = static_cast<FlatVector<StringView>&>(*vector);
buffer->fillKey(ordinal_, [&](auto data, auto size) {
const_cast<StringView*>(flatVec.rawValues())[offset] =
StringView{data, size};
});
}
template <typename T>
std::vector<std::unique_ptr<KeyNode<T>>> getKeyNodesForStructEncoding(
const std::shared_ptr<const TypeWithId>& requestedType,
const std::shared_ptr<const TypeWithId>& dataType,
StripeStreams& stripe,
memory::MemoryPool& memoryPool) {
// `KeyNode` is ordered based on the projection. So if [3, 2, 1] is
// projected, the vector of key node will be created [3, 2, 1].
// If the key is not found in the stripe, the key node will be nullptr.
auto parsedKeyFilter = parseKeyFilter<T>(requestedType, stripe);
const KeyPredicate<T> keyPredicate(
parsedKeyFilter.mode,
typename KeyPredicate<T>::Lookup(
parsedKeyFilter.keys.begin(), parsedKeyFilter.keys.end()));
auto availableKeyNodes = getKeyNodesFiltered<T>(
[&keyPredicate](const auto& keyValue) { return keyPredicate(keyValue); },
requestedType,
dataType,
stripe,
memoryPool);
const auto& mapColumnIdAsStruct =
stripe.getRowReaderOptions().getMapColumnIdAsStruct();
auto it = mapColumnIdAsStruct.find(requestedType->id);
DWIO_ENSURE(it != mapColumnIdAsStruct.end());
return rearrangeKeyNodesAsProjectedOrder<T>(availableKeyNodes, it->second);
}
template <typename T>
FlatMapStructEncodingColumnReader<T>::FlatMapStructEncodingColumnReader(
const std::shared_ptr<const TypeWithId>& requestedType,
const std::shared_ptr<const TypeWithId>& dataType,
StripeStreams& stripe,
FlatMapContext flatMapContext)
: ColumnReader(requestedType, stripe, std::move(flatMapContext)),
requestedType_{requestedType},
keyNodes_{getKeyNodesForStructEncoding<T>(
requestedType,
dataType,
stripe,
memoryPool_)},
nullColumnReader_{std::make_unique<NullColumnReader>(
stripe,
requestedType_->type->asMap().valueType())} {
DWIO_ENSURE_EQ(nodeType_->id, dataType->id);
DWIO_ENSURE(!keyNodes_.empty()); // "For struct encoding, keys to project must
// be configured.";
}
template <typename T>
uint64_t FlatMapStructEncodingColumnReader<T>::skip(uint64_t numValues) {
// skip basic rows
numValues = ColumnReader::skip(numValues);
// skip every single node
for (auto& node : keyNodes_) {
if (node) {
node->skip(numValues);
}
}
return numValues;
}
template <typename T>
void FlatMapStructEncodingColumnReader<T>::next(
uint64_t numValues,
VectorPtr& result,
const uint64_t* FOLLY_NULLABLE incomingNulls) {
BufferPtr nulls = readNulls(numValues, result, incomingNulls);
const auto* nullsPtr = nulls ? nulls->as<uint64_t>() : nullptr;
const uint64_t nullCount =
nullsPtr ? bits::countNulls(nullsPtr, 0, numValues) : 0;
const auto nonNullMaps = numValues - nullCount;
resetIfWrongVectorType<RowVector>(result);
std::vector<VectorPtr> children;
std::vector<VectorPtr>* childrenPtr = nullptr;
if (result) {
auto* rowVector = result->as<RowVector>();
childrenPtr = &rowVector->children();
DWIO_ENSURE_EQ(childrenPtr->size(), keyNodes_.size());
} else {
children.resize(keyNodes_.size());
childrenPtr = &children;
}
for (size_t i = 0; i < keyNodes_.size(); ++i) {
auto& node = keyNodes_[i];
auto& child = (*childrenPtr)[i];
if (node) {
node->loadAsChild(child, numValues, mergedNulls_, nonNullMaps, nullsPtr);
} else {
nullColumnReader_->next(numValues, child, nullsPtr);
}
}
if (result) {
result->setSize(numValues);
result->setNullCount(nullCount);
} else {
result = std::make_shared<RowVector>(
&memoryPool_,
ROW(std::vector<std::string>(keyNodes_.size()),
std::vector<std::shared_ptr<const Type>>(
keyNodes_.size(), requestedType_->type->asMap().valueType())),
nulls,
numValues,
std::move(children),
nullCount);
}
}
inline bool isRequiringStructEncoding(
const std::shared_ptr<const dwio::common::TypeWithId>& requestedType,
const dwio::common::RowReaderOptions& rowOptions) {
return rowOptions.getMapColumnIdAsStruct().count(requestedType->id) > 0;
}
template <typename T>
std::unique_ptr<ColumnReader> createFlatMapColumnReader(
const std::shared_ptr<const dwio::common::TypeWithId>& requestedType,
const std::shared_ptr<const dwio::common::TypeWithId>& dataType,
StripeStreams& stripe,
FlatMapContext flatMapContext) {
if (isRequiringStructEncoding(requestedType, stripe.getRowReaderOptions())) {
return std::make_unique<FlatMapStructEncodingColumnReader<T>>(
requestedType, dataType, stripe, std::move(flatMapContext));
} else {
return std::make_unique<FlatMapColumnReader<T>>(
requestedType, dataType, stripe, std::move(flatMapContext));
}
}
/* static */ std::unique_ptr<ColumnReader> FlatMapColumnReaderFactory::create(
const std::shared_ptr<const dwio::common::TypeWithId>& requestedType,
const std::shared_ptr<const dwio::common::TypeWithId>& dataType,
StripeStreams& stripe,
FlatMapContext flatMapContext) {
// create flat map column reader based on key type
const auto kind = dataType->childAt(0)->type->kind();
switch (kind) {
case TypeKind::TINYINT:
return createFlatMapColumnReader<int8_t>(
requestedType, dataType, stripe, std::move(flatMapContext));
case TypeKind::SMALLINT:
return createFlatMapColumnReader<int16_t>(
requestedType, dataType, stripe, std::move(flatMapContext));
case TypeKind::INTEGER:
return createFlatMapColumnReader<int32_t>(
requestedType, dataType, stripe, std::move(flatMapContext));
case TypeKind::BIGINT:
return createFlatMapColumnReader<int64_t>(
requestedType, dataType, stripe, std::move(flatMapContext));
case TypeKind::VARBINARY:
case TypeKind::VARCHAR:
return createFlatMapColumnReader<StringView>(
requestedType, dataType, stripe, std::move(flatMapContext));
default:
DWIO_RAISE("Not supported key type: ", kind);
}
}
// declare all possible flat map column reader
template class FlatMapColumnReader<int8_t>;
template class FlatMapColumnReader<int16_t>;
template class FlatMapColumnReader<int32_t>;
template class FlatMapColumnReader<int64_t>;
template class FlatMapColumnReader<StringView>;
template class FlatMapStructEncodingColumnReader<int8_t>;
template class FlatMapStructEncodingColumnReader<int16_t>;
template class FlatMapStructEncodingColumnReader<int32_t>;
template class FlatMapStructEncodingColumnReader<int64_t>;
template class FlatMapStructEncodingColumnReader<StringView>;
} // namespace facebook::velox::dwrf
| 32.382315 | 80 | 0.67854 | [
"object",
"vector"
] |
a81dc47526e7302b252c95a0a962d5e46702cbad | 42,757 | cc | C++ | ash/wm/immersive_fullscreen_controller_unittest.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ash/wm/immersive_fullscreen_controller_unittest.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ash/wm/immersive_fullscreen_controller_unittest.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/public/cpp/immersive/immersive_fullscreen_controller.h"
#include "ash/public/cpp/config.h"
#include "ash/public/cpp/immersive/immersive_fullscreen_controller_delegate.h"
#include "ash/public/cpp/immersive/immersive_fullscreen_controller_test_api.h"
#include "ash/public/cpp/shelf_types.h"
#include "ash/root_window_controller.h"
#include "ash/shelf/shelf.h"
#include "ash/shell.h"
#include "ash/test/ash_test_base.h"
#include "ash/wm/window_state.h"
#include "ui/aura/client/aura_constants.h"
#include "ui/aura/client/cursor_client.h"
#include "ui/aura/env.h"
#include "ui/aura/test/test_window_delegate.h"
#include "ui/aura/window.h"
#include "ui/aura/window_event_dispatcher.h"
#include "ui/display/display_layout.h"
#include "ui/display/manager/display_manager.h"
#include "ui/display/test/display_manager_test_api.h"
#include "ui/events/event_utils.h"
#include "ui/events/test/event_generator.h"
#include "ui/events/test/test_event_handler.h"
#include "ui/gfx/animation/slide_animation.h"
#include "ui/views/bubble/bubble_dialog_delegate.h"
#include "ui/views/controls/native/native_view_host.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
namespace ash {
namespace {
class TestBubbleDialogDelegate : public views::BubbleDialogDelegateView {
public:
explicit TestBubbleDialogDelegate(views::View* anchor)
: BubbleDialogDelegateView(anchor, views::BubbleBorder::NONE) {}
~TestBubbleDialogDelegate() override {}
private:
DISALLOW_COPY_AND_ASSIGN(TestBubbleDialogDelegate);
};
class MockImmersiveFullscreenControllerDelegate
: public ImmersiveFullscreenControllerDelegate {
public:
MockImmersiveFullscreenControllerDelegate(views::View* top_container_view)
: top_container_view_(top_container_view),
enabled_(false),
visible_fraction_(1) {}
~MockImmersiveFullscreenControllerDelegate() override {}
// ImmersiveFullscreenControllerDelegate overrides:
void OnImmersiveRevealStarted() override {
enabled_ = true;
visible_fraction_ = 0;
}
void OnImmersiveRevealEnded() override { visible_fraction_ = 0; }
void OnImmersiveFullscreenExited() override {
enabled_ = false;
visible_fraction_ = 1;
}
void SetVisibleFraction(double visible_fraction) override {
visible_fraction_ = visible_fraction;
}
std::vector<gfx::Rect> GetVisibleBoundsInScreen() const override {
std::vector<gfx::Rect> bounds_in_screen;
bounds_in_screen.push_back(top_container_view_->GetBoundsInScreen());
return bounds_in_screen;
}
bool is_enabled() const { return enabled_; }
double visible_fraction() const { return visible_fraction_; }
private:
views::View* top_container_view_;
bool enabled_;
double visible_fraction_;
DISALLOW_COPY_AND_ASSIGN(MockImmersiveFullscreenControllerDelegate);
};
class ConsumeEventHandler : public ui::test::TestEventHandler {
public:
ConsumeEventHandler() {}
~ConsumeEventHandler() override {}
private:
void OnEvent(ui::Event* event) override {
ui::test::TestEventHandler::OnEvent(event);
if (event->cancelable())
event->SetHandled();
}
DISALLOW_COPY_AND_ASSIGN(ConsumeEventHandler);
};
} // namespace
/////////////////////////////////////////////////////////////////////////////
class ImmersiveFullscreenControllerTest : public AshTestBase {
public:
enum Modality {
MODALITY_MOUSE,
MODALITY_GESTURE_TAP,
MODALITY_GESTURE_SCROLL
};
ImmersiveFullscreenControllerTest()
: widget_(nullptr), top_container_(nullptr), content_view_(nullptr) {}
~ImmersiveFullscreenControllerTest() override {}
ImmersiveFullscreenController* controller() { return controller_.get(); }
views::NativeViewHost* content_view() { return content_view_; }
views::View* top_container() { return top_container_; }
views::Widget* widget() { return widget_; }
aura::Window* window() { return widget_->GetNativeWindow(); }
MockImmersiveFullscreenControllerDelegate* delegate() {
return delegate_.get();
}
// Access to private data from the controller.
bool top_edge_hover_timer_running() const {
return controller_->top_edge_hover_timer_.IsRunning();
}
int mouse_x_when_hit_top() const {
return controller_->mouse_x_when_hit_top_in_screen_;
}
// AshTestBase:
void SetUp() override {
AshTestBase::SetUp();
widget_ = new views::Widget();
views::Widget::InitParams params;
params.context = CurrentContext();
widget_->Init(params);
widget_->Show();
window()->SetProperty(aura::client::kShowStateKey,
ui::SHOW_STATE_FULLSCREEN);
gfx::Size window_size = widget_->GetWindowBoundsInScreen().size();
content_view_ = new views::NativeViewHost();
content_view_->SetBounds(0, 0, window_size.width(), window_size.height());
widget_->GetContentsView()->AddChildView(content_view_);
top_container_ = new views::View();
top_container_->SetBounds(0, 0, window_size.width(), 100);
top_container_->SetFocusBehavior(views::View::FocusBehavior::ALWAYS);
widget_->GetContentsView()->AddChildView(top_container_);
delegate_.reset(
new MockImmersiveFullscreenControllerDelegate(top_container_));
controller_.reset(new ImmersiveFullscreenController);
controller_->Init(delegate_.get(), widget_, top_container_);
ImmersiveFullscreenControllerTestApi(controller_.get()).SetupForTest();
// The mouse is moved so that it is not over |top_container_| by
// AshTestBase.
}
// Enables / disables immersive fullscreen.
void SetEnabled(bool enabled) {
controller_->SetEnabled(ImmersiveFullscreenController::WINDOW_TYPE_OTHER,
enabled);
}
// Attempt to reveal the top-of-window views via |modality|.
// The top-of-window views can only be revealed via mouse hover or a gesture.
void AttemptReveal(Modality modality) {
ASSERT_NE(modality, MODALITY_GESTURE_TAP);
AttemptRevealStateChange(true, modality);
}
// Attempt to unreveal the top-of-window views via |modality|. The
// top-of-window views can be unrevealed via any modality.
void AttemptUnreveal(Modality modality) {
AttemptRevealStateChange(false, modality);
}
// Sets whether the mouse is hovered above |top_container_|.
// SetHovered(true) moves the mouse over the |top_container_| but does not
// move it to the top of the screen so will not initiate a reveal.
void SetHovered(bool is_mouse_hovered) {
MoveMouse(0, is_mouse_hovered ? 10 : top_container_->height() + 100);
}
// Move the mouse to the given coordinates. The coordinates should be in
// |top_container_| coordinates.
void MoveMouse(int x, int y) {
gfx::Point screen_position(x, y);
views::View::ConvertPointToScreen(top_container_, &screen_position);
GetEventGenerator().MoveMouseTo(screen_position.x(), screen_position.y());
// If the top edge timer started running as a result of the mouse move, run
// the task which occurs after the timer delay. This reveals the
// top-of-window views synchronously if the mouse is hovered at the top of
// the screen.
if (controller()->top_edge_hover_timer_.IsRunning()) {
controller()->top_edge_hover_timer_.user_task().Run();
controller()->top_edge_hover_timer_.Stop();
}
}
private:
// Attempt to change the revealed state to |revealed| via |modality|.
void AttemptRevealStateChange(bool revealed, Modality modality) {
// Compute the event position in |top_container_| coordinates.
gfx::Point event_position(0, revealed ? 0 : top_container_->height() + 100);
switch (modality) {
case MODALITY_MOUSE: {
MoveMouse(event_position.x(), event_position.y());
break;
}
case MODALITY_GESTURE_TAP: {
gfx::Point screen_position = event_position;
views::View::ConvertPointToScreen(top_container_, &screen_position);
ui::test::EventGenerator& event_generator(GetEventGenerator());
event_generator.MoveTouch(event_position);
event_generator.PressTouch();
event_generator.ReleaseTouch();
break;
}
case MODALITY_GESTURE_SCROLL: {
gfx::Point start(0, revealed ? 0 : top_container_->height() - 2);
gfx::Vector2d scroll_delta(0, 40);
gfx::Point end = revealed ? start + scroll_delta : start - scroll_delta;
views::View::ConvertPointToScreen(top_container_, &start);
views::View::ConvertPointToScreen(top_container_, &end);
ui::test::EventGenerator& event_generator(GetEventGenerator());
event_generator.GestureScrollSequence(
start, end, base::TimeDelta::FromMilliseconds(30), 1);
break;
}
}
}
std::unique_ptr<ImmersiveFullscreenController> controller_;
std::unique_ptr<MockImmersiveFullscreenControllerDelegate> delegate_;
views::Widget* widget_; // Owned by the native widget.
views::View* top_container_; // Owned by |widget_|'s root-view.
views::NativeViewHost* content_view_; // Owned by |widget_|'s root-view.
DISALLOW_COPY_AND_ASSIGN(ImmersiveFullscreenControllerTest);
};
// Test the initial state and that the delegate gets notified of the
// top-of-window views getting hidden and revealed.
TEST_F(ImmersiveFullscreenControllerTest, Delegate) {
// TODO: investigate failure. http://crbug.com/698085.
if (Shell::GetAshConfig() == Config::MASH)
return;
// Initial state.
EXPECT_FALSE(controller()->IsEnabled());
EXPECT_FALSE(controller()->IsRevealed());
EXPECT_FALSE(delegate()->is_enabled());
// Enabling initially hides the top views.
SetEnabled(true);
EXPECT_TRUE(controller()->IsEnabled());
EXPECT_FALSE(controller()->IsRevealed());
EXPECT_TRUE(delegate()->is_enabled());
EXPECT_EQ(0, delegate()->visible_fraction());
// Revealing shows the top views.
AttemptReveal(MODALITY_MOUSE);
EXPECT_TRUE(controller()->IsEnabled());
EXPECT_TRUE(controller()->IsRevealed());
EXPECT_TRUE(delegate()->is_enabled());
EXPECT_EQ(1, delegate()->visible_fraction());
// Disabling ends the immersive reveal.
SetEnabled(false);
EXPECT_FALSE(controller()->IsEnabled());
EXPECT_FALSE(controller()->IsRevealed());
EXPECT_FALSE(delegate()->is_enabled());
}
// GetRevealedLock() specific tests.
TEST_F(ImmersiveFullscreenControllerTest, RevealedLock) {
std::unique_ptr<ImmersiveRevealedLock> lock1;
std::unique_ptr<ImmersiveRevealedLock> lock2;
// Immersive fullscreen is not on by default.
EXPECT_FALSE(controller()->IsEnabled());
// 1) Test acquiring and releasing a revealed state lock while immersive
// fullscreen is disabled. Acquiring or releasing the lock should have no
// effect till immersive fullscreen is enabled.
lock1.reset(controller()->GetRevealedLock(
ImmersiveFullscreenController::ANIMATE_REVEAL_NO));
EXPECT_FALSE(controller()->IsEnabled());
EXPECT_FALSE(controller()->IsRevealed());
// Immersive fullscreen should start in the revealed state due to the lock.
SetEnabled(true);
EXPECT_TRUE(controller()->IsEnabled());
EXPECT_TRUE(controller()->IsRevealed());
SetEnabled(false);
EXPECT_FALSE(controller()->IsEnabled());
EXPECT_FALSE(controller()->IsRevealed());
lock1.reset();
EXPECT_FALSE(controller()->IsEnabled());
EXPECT_FALSE(controller()->IsRevealed());
// Immersive fullscreen should start in the closed state because the lock is
// no longer held.
SetEnabled(true);
EXPECT_TRUE(controller()->IsEnabled());
EXPECT_FALSE(controller()->IsRevealed());
// 2) Test that acquiring a lock reveals the top-of-window views if they are
// hidden.
lock1.reset(controller()->GetRevealedLock(
ImmersiveFullscreenController::ANIMATE_REVEAL_NO));
EXPECT_TRUE(controller()->IsRevealed());
// 3) Test that the top-of-window views are only hidden when all of the locks
// are released.
lock2.reset(controller()->GetRevealedLock(
ImmersiveFullscreenController::ANIMATE_REVEAL_NO));
lock1.reset();
EXPECT_TRUE(controller()->IsRevealed());
lock2.reset();
EXPECT_FALSE(controller()->IsRevealed());
}
// Test mouse event processing for top-of-screen reveal triggering.
TEST_F(ImmersiveFullscreenControllerTest, OnMouseEvent) {
// TODO: investigate failure. http://crbug.com/698085.
if (Shell::GetAshConfig() == Config::MASH)
return;
// Set up initial state.
SetEnabled(true);
ASSERT_TRUE(controller()->IsEnabled());
ASSERT_FALSE(controller()->IsRevealed());
ui::test::EventGenerator& event_generator(GetEventGenerator());
gfx::Rect top_container_bounds_in_screen =
top_container()->GetBoundsInScreen();
// A position along the top edge of TopContainerView in screen coordinates.
gfx::Point top_edge_pos(top_container_bounds_in_screen.x() + 100,
top_container_bounds_in_screen.y());
// Mouse wheel event does nothing.
ui::MouseWheelEvent wheel(gfx::Vector2d(), top_edge_pos, top_edge_pos,
ui::EventTimeForNow(), ui::EF_NONE, ui::EF_NONE);
event_generator.Dispatch(&wheel);
EXPECT_FALSE(top_edge_hover_timer_running());
// Move to top edge of screen starts hover timer running. We cannot use
// MoveMouse() because MoveMouse() stops the timer if it started running.
event_generator.MoveMouseTo(top_edge_pos);
EXPECT_TRUE(top_edge_hover_timer_running());
EXPECT_EQ(top_edge_pos.x(), mouse_x_when_hit_top());
// Moving |ImmersiveFullscreenControllerTest::kMouseRevealBoundsHeight| down
// from the top edge stops it.
event_generator.MoveMouseBy(
0, ImmersiveFullscreenController::kMouseRevealBoundsHeight);
EXPECT_FALSE(top_edge_hover_timer_running());
// Moving back to the top starts the timer again.
event_generator.MoveMouseTo(top_edge_pos);
EXPECT_TRUE(top_edge_hover_timer_running());
EXPECT_EQ(top_edge_pos.x(), mouse_x_when_hit_top());
// Slight move to the right keeps the timer running for the same hit point.
event_generator.MoveMouseBy(1, 0);
EXPECT_TRUE(top_edge_hover_timer_running());
EXPECT_EQ(top_edge_pos.x(), mouse_x_when_hit_top());
// Moving back to the left also keeps the timer running.
event_generator.MoveMouseBy(-1, 0);
EXPECT_TRUE(top_edge_hover_timer_running());
EXPECT_EQ(top_edge_pos.x(), mouse_x_when_hit_top());
// Large move right restarts the timer (so it is still running) and considers
// this a new hit at the top.
event_generator.MoveMouseTo(top_edge_pos.x() + 100, top_edge_pos.y());
EXPECT_TRUE(top_edge_hover_timer_running());
EXPECT_EQ(top_edge_pos.x() + 100, mouse_x_when_hit_top());
// Moving off the top edge horizontally stops the timer.
event_generator.MoveMouseTo(top_container_bounds_in_screen.right() + 1,
top_container_bounds_in_screen.y());
EXPECT_FALSE(top_edge_hover_timer_running());
// Once revealed, a move just a little below the top container doesn't end a
// reveal.
AttemptReveal(MODALITY_MOUSE);
event_generator.MoveMouseTo(top_container_bounds_in_screen.x(),
top_container_bounds_in_screen.bottom() + 1);
EXPECT_TRUE(controller()->IsRevealed());
// Once revealed, clicking just below the top container ends the reveal.
event_generator.ClickLeftButton();
EXPECT_FALSE(controller()->IsRevealed());
// Moving a lot below the top container ends a reveal.
AttemptReveal(MODALITY_MOUSE);
EXPECT_TRUE(controller()->IsRevealed());
event_generator.MoveMouseTo(top_container_bounds_in_screen.x(),
top_container_bounds_in_screen.bottom() + 50);
EXPECT_FALSE(controller()->IsRevealed());
// The mouse position cannot cause a reveal when the top container's widget
// has capture.
views::Widget* widget = top_container()->GetWidget();
widget->SetCapture(top_container());
AttemptReveal(MODALITY_MOUSE);
EXPECT_FALSE(controller()->IsRevealed());
widget->ReleaseCapture();
// The mouse position cannot end the reveal while the top container's widget
// has capture.
AttemptReveal(MODALITY_MOUSE);
EXPECT_TRUE(controller()->IsRevealed());
widget->SetCapture(top_container());
event_generator.MoveMouseTo(top_container_bounds_in_screen.x(),
top_container_bounds_in_screen.bottom() + 51);
EXPECT_TRUE(controller()->IsRevealed());
// Releasing capture should end the reveal.
widget->ReleaseCapture();
EXPECT_FALSE(controller()->IsRevealed());
}
// Test mouse event processing for top-of-screen reveal triggering when the
// top container's widget is inactive.
TEST_F(ImmersiveFullscreenControllerTest, Inactive) {
// TODO: investigate failure. http://crbug.com/698085.
if (Shell::GetAshConfig() == Config::MASH)
return;
// Set up initial state.
views::Widget* popup_widget = views::Widget::CreateWindowWithContextAndBounds(
nullptr, CurrentContext(), gfx::Rect(0, 0, 200, 200));
popup_widget->Show();
ASSERT_FALSE(top_container()->GetWidget()->IsActive());
SetEnabled(true);
ASSERT_TRUE(controller()->IsEnabled());
ASSERT_FALSE(controller()->IsRevealed());
gfx::Rect top_container_bounds_in_screen =
top_container()->GetBoundsInScreen();
gfx::Rect popup_bounds_in_screen = popup_widget->GetWindowBoundsInScreen();
ASSERT_EQ(top_container_bounds_in_screen.origin().ToString(),
popup_bounds_in_screen.origin().ToString());
ASSERT_GT(top_container_bounds_in_screen.right(),
popup_bounds_in_screen.right());
// The top-of-window views should stay hidden if the cursor is at the top edge
// but above an obscured portion of the top-of-window views.
MoveMouse(popup_bounds_in_screen.x(), top_container_bounds_in_screen.y());
EXPECT_FALSE(controller()->IsRevealed());
// The top-of-window views should reveal if the cursor is at the top edge and
// above an unobscured portion of the top-of-window views.
MoveMouse(top_container_bounds_in_screen.right() - 1,
top_container_bounds_in_screen.y());
EXPECT_TRUE(controller()->IsRevealed());
// The top-of-window views should stay revealed if the cursor is moved off
// of the top edge.
MoveMouse(top_container_bounds_in_screen.right() - 1,
top_container_bounds_in_screen.bottom() - 1);
EXPECT_TRUE(controller()->IsRevealed());
// Moving way off of the top-of-window views should end the immersive reveal.
MoveMouse(top_container_bounds_in_screen.right() - 1,
top_container_bounds_in_screen.bottom() + 50);
EXPECT_FALSE(controller()->IsRevealed());
// Moving way off of the top-of-window views in a region where the
// top-of-window views are obscured should also end the immersive reveal.
// Ideally, the immersive reveal would end immediately when the cursor moves
// to an obscured portion of the top-of-window views.
MoveMouse(top_container_bounds_in_screen.right() - 1,
top_container_bounds_in_screen.y());
EXPECT_TRUE(controller()->IsRevealed());
MoveMouse(top_container_bounds_in_screen.x(),
top_container_bounds_in_screen.bottom() + 50);
EXPECT_FALSE(controller()->IsRevealed());
}
// Test mouse event processing for top-of-screen reveal triggering when the user
// has a vertical display layout (primary display above/below secondary display)
// and the immersive fullscreen window is on the bottom display.
TEST_F(ImmersiveFullscreenControllerTest, MouseEventsVerticalDisplayLayout) {
// TODO: SetLayoutForCurrentDisplays() needs to ported to mash.
// http://crbug.com/698043.
if (Shell::GetAshConfig() == Config::MASH)
return;
// Set up initial state.
UpdateDisplay("800x600,800x600");
ash::Shell::Get()->display_manager()->SetLayoutForCurrentDisplays(
display::test::CreateDisplayLayout(display_manager(),
display::DisplayPlacement::TOP, 0));
SetEnabled(true);
ASSERT_TRUE(controller()->IsEnabled());
ASSERT_FALSE(controller()->IsRevealed());
aura::Window::Windows root_windows = ash::Shell::GetAllRootWindows();
ASSERT_EQ(root_windows[0],
top_container()->GetWidget()->GetNativeWindow()->GetRootWindow());
gfx::Rect primary_root_window_bounds_in_screen =
root_windows[0]->GetBoundsInScreen();
// Do not set |x| to the root window's x position because the display's
// corners have special behavior.
int x = primary_root_window_bounds_in_screen.x() + 10;
// The y position of the top edge of the primary display.
int y_top_edge = primary_root_window_bounds_in_screen.y();
ui::test::EventGenerator& event_generator(GetEventGenerator());
// Moving right below the top edge starts the hover timer running. We
// cannot use MoveMouse() because MoveMouse() stops the timer if it started
// running.
event_generator.MoveMouseTo(x, y_top_edge + 1);
EXPECT_TRUE(top_edge_hover_timer_running());
EXPECT_EQ(y_top_edge + 1,
aura::Env::GetInstance()->last_mouse_location().y());
// The timer should continue running if the user moves the mouse to the top
// edge even though the mouse is warped to the secondary display.
event_generator.MoveMouseTo(x, y_top_edge);
EXPECT_TRUE(top_edge_hover_timer_running());
// The timer should continue running if the user overshoots the top edge
// a bit.
event_generator.MoveMouseTo(x, y_top_edge - 2);
EXPECT_TRUE(top_edge_hover_timer_running());
// The timer should stop running if the user overshoots the top edge by
// a lot.
event_generator.MoveMouseTo(x, y_top_edge - 20);
EXPECT_FALSE(top_edge_hover_timer_running());
// The timer should not start if the user moves the mouse to the bottom of the
// secondary display without crossing the top edge first.
event_generator.MoveMouseTo(x, y_top_edge - 2);
// Reveal the top-of-window views by overshooting the top edge slightly.
event_generator.MoveMouseTo(x, y_top_edge + 1);
// MoveMouse() runs the timer task.
MoveMouse(x, y_top_edge - 2);
EXPECT_TRUE(controller()->IsRevealed());
// The top-of-window views should stay revealed if the user moves the mouse
// around in the bottom region of the secondary display.
event_generator.MoveMouseTo(x + 10, y_top_edge - 3);
EXPECT_TRUE(controller()->IsRevealed());
// The top-of-window views should hide if the user moves the mouse away from
// the bottom region of the secondary display.
event_generator.MoveMouseTo(x, y_top_edge - 20);
EXPECT_FALSE(controller()->IsRevealed());
// Test that it is possible to reveal the top-of-window views by overshooting
// the top edge slightly when the top container's widget is not active.
views::Widget* popup_widget = views::Widget::CreateWindowWithContextAndBounds(
nullptr, CurrentContext(), gfx::Rect(0, 200, 100, 100));
popup_widget->Show();
ASSERT_FALSE(top_container()->GetWidget()->IsActive());
ASSERT_FALSE(top_container()->GetBoundsInScreen().Intersects(
popup_widget->GetWindowBoundsInScreen()));
event_generator.MoveMouseTo(x, y_top_edge + 1);
MoveMouse(x, y_top_edge - 2);
EXPECT_TRUE(controller()->IsRevealed());
}
// Test behavior when the mouse becomes hovered without moving.
TEST_F(ImmersiveFullscreenControllerTest, MouseHoveredWithoutMoving) {
// TODO: investigate failure. http://crbug.com/698085.
if (Shell::GetAshConfig() == Config::MASH)
return;
SetEnabled(true);
std::unique_ptr<ImmersiveRevealedLock> lock;
// 1) Test that if the mouse becomes hovered without the mouse moving due to a
// lock causing the top-of-window views to be revealed (and the mouse
// happening to be near the top of the screen), the top-of-window views do not
// hide till the mouse moves off of the top-of-window views.
SetHovered(true);
EXPECT_FALSE(controller()->IsRevealed());
lock.reset(controller()->GetRevealedLock(
ImmersiveFullscreenController::ANIMATE_REVEAL_NO));
EXPECT_TRUE(controller()->IsRevealed());
lock.reset();
EXPECT_TRUE(controller()->IsRevealed());
SetHovered(false);
EXPECT_FALSE(controller()->IsRevealed());
// 2) Test that if the mouse becomes hovered without moving because of a
// reveal in ImmersiveFullscreenController::SetEnabled(true) and there are no
// locks keeping the top-of-window views revealed, that mouse hover does not
// prevent the top-of-window views from closing.
SetEnabled(false);
SetHovered(true);
EXPECT_FALSE(controller()->IsRevealed());
SetEnabled(true);
EXPECT_FALSE(controller()->IsRevealed());
// 3) Test that if the mouse becomes hovered without moving because of a
// reveal in ImmersiveFullscreenController::SetEnabled(true) and there is a
// lock keeping the top-of-window views revealed, that the top-of-window views
// do not hide till the mouse moves off of the top-of-window views.
SetEnabled(false);
SetHovered(true);
lock.reset(controller()->GetRevealedLock(
ImmersiveFullscreenController::ANIMATE_REVEAL_NO));
EXPECT_FALSE(controller()->IsRevealed());
SetEnabled(true);
EXPECT_TRUE(controller()->IsRevealed());
lock.reset();
EXPECT_TRUE(controller()->IsRevealed());
SetHovered(false);
EXPECT_FALSE(controller()->IsRevealed());
}
// Test revealing the top-of-window views using one modality and ending
// the reveal via another. For instance, initiating the reveal via a SWIPE_OPEN
// edge gesture, switching to using the mouse and ending the reveal by moving
// the mouse off of the top-of-window views.
TEST_F(ImmersiveFullscreenControllerTest, DifferentModalityEnterExit) {
// TODO: investigate failure. http://crbug.com/698085.
if (Shell::GetAshConfig() == Config::MASH)
return;
SetEnabled(true);
EXPECT_TRUE(controller()->IsEnabled());
EXPECT_FALSE(controller()->IsRevealed());
// Initiate reveal via gesture, end reveal via mouse.
AttemptReveal(MODALITY_GESTURE_SCROLL);
EXPECT_TRUE(controller()->IsRevealed());
MoveMouse(1, 1);
EXPECT_TRUE(controller()->IsRevealed());
AttemptUnreveal(MODALITY_MOUSE);
EXPECT_FALSE(controller()->IsRevealed());
// Initiate reveal via gesture, end reveal via touch.
AttemptReveal(MODALITY_GESTURE_SCROLL);
EXPECT_TRUE(controller()->IsRevealed());
AttemptUnreveal(MODALITY_GESTURE_TAP);
EXPECT_FALSE(controller()->IsRevealed());
// Initiate reveal via mouse, end reveal via gesture.
AttemptReveal(MODALITY_MOUSE);
EXPECT_TRUE(controller()->IsRevealed());
AttemptUnreveal(MODALITY_GESTURE_SCROLL);
EXPECT_FALSE(controller()->IsRevealed());
// Initiate reveal via mouse, end reveal via touch.
AttemptReveal(MODALITY_MOUSE);
EXPECT_TRUE(controller()->IsRevealed());
AttemptUnreveal(MODALITY_GESTURE_TAP);
EXPECT_FALSE(controller()->IsRevealed());
}
// Test when the SWIPE_CLOSE edge gesture closes the top-of-window views.
TEST_F(ImmersiveFullscreenControllerTest, EndRevealViaGesture) {
// TODO: investigate failure. http://crbug.com/698085.
if (Shell::GetAshConfig() == Config::MASH)
return;
SetEnabled(true);
EXPECT_TRUE(controller()->IsEnabled());
EXPECT_FALSE(controller()->IsRevealed());
// A gesture should be able to close the top-of-window views when
// top-of-window views have focus.
AttemptReveal(MODALITY_MOUSE);
top_container()->RequestFocus();
EXPECT_TRUE(controller()->IsRevealed());
AttemptUnreveal(MODALITY_GESTURE_SCROLL);
EXPECT_FALSE(controller()->IsRevealed());
// The top-of-window views should no longer have focus. Clearing focus is
// important because it closes focus-related popup windows like the touch
// selection handles.
EXPECT_FALSE(top_container()->HasFocus());
// If some other code is holding onto a lock, a gesture should not be able to
// end the reveal.
AttemptReveal(MODALITY_MOUSE);
std::unique_ptr<ImmersiveRevealedLock> lock(controller()->GetRevealedLock(
ImmersiveFullscreenController::ANIMATE_REVEAL_NO));
EXPECT_TRUE(controller()->IsRevealed());
AttemptUnreveal(MODALITY_GESTURE_SCROLL);
EXPECT_TRUE(controller()->IsRevealed());
lock.reset();
EXPECT_FALSE(controller()->IsRevealed());
}
// Tests that touch-gesture can be used to reveal the top-of-window views when
// the child window consumes all events.
TEST_F(ImmersiveFullscreenControllerTest, RevealViaGestureChildConsumesEvents) {
// TODO: investigate failure. http://crbug.com/698085.
if (Shell::GetAshConfig() == Config::MASH)
return;
// Enabling initially hides the top views.
SetEnabled(true);
EXPECT_TRUE(controller()->IsEnabled());
EXPECT_FALSE(controller()->IsRevealed());
aura::test::TestWindowDelegate child_delegate;
std::unique_ptr<aura::Window> child(
CreateTestWindowInShellWithDelegateAndType(
&child_delegate, aura::client::WINDOW_TYPE_CONTROL, 1234,
gfx::Rect()));
content_view()->Attach(child.get());
child->Show();
ConsumeEventHandler handler;
child->AddPreTargetHandler(&handler);
// Reveal the top views using a touch-scroll gesture. The child window should
// not receive the touch events.
AttemptReveal(MODALITY_GESTURE_SCROLL);
EXPECT_TRUE(controller()->IsRevealed());
EXPECT_EQ(0, handler.num_touch_events());
AttemptUnreveal(MODALITY_GESTURE_TAP);
EXPECT_FALSE(controller()->IsRevealed());
EXPECT_GT(handler.num_touch_events(), 0);
child->RemovePreTargetHandler(&handler);
}
// Make sure touch events towards the top of the window do not leak through to
// windows underneath.
TEST_F(ImmersiveFullscreenControllerTest, EventsDoNotLeakToWindowUnderneath) {
gfx::Rect window_bounds = window()->GetBoundsInScreen();
aura::test::TestWindowDelegate child_delegate;
std::unique_ptr<aura::Window> behind(CreateTestWindowInShellWithDelegate(
&child_delegate, 1234, window_bounds));
behind->Show();
behind->SetBounds(window_bounds);
widget()->StackAbove(behind.get());
// Make sure the windows are aligned on top.
EXPECT_EQ(behind->GetBoundsInScreen().y(), window()->GetBoundsInScreen().y());
int top = behind->GetBoundsInScreen().y();
ui::TouchEvent touch(
ui::ET_TOUCH_MOVED, gfx::Point(10, top), ui::EventTimeForNow(),
ui::PointerDetails(ui::EventPointerType::POINTER_TYPE_TOUCH, 0));
aura::Window* root = window()->GetRootWindow();
ui::EventTargeter* targeter =
root->GetHost()->dispatcher()->GetDefaultEventTargeter();
EXPECT_EQ(window(), targeter->FindTargetForEvent(root, &touch));
SetEnabled(true);
EXPECT_FALSE(controller()->IsRevealed());
// Make sure the windows are still aligned on top.
EXPECT_EQ(behind->GetBoundsInScreen().y(), window()->GetBoundsInScreen().y());
top = behind->GetBoundsInScreen().y();
ui::TouchEvent touch2(
ui::ET_TOUCH_MOVED, gfx::Point(10, top), ui::EventTimeForNow(),
ui::PointerDetails(ui::EventPointerType::POINTER_TYPE_TOUCH, 0));
// The event should still be targeted to window().
EXPECT_EQ(window(), targeter->FindTargetForEvent(root, &touch2));
}
// Check that the window state gets properly marked for immersive fullscreen.
TEST_F(ImmersiveFullscreenControllerTest, WindowStateImmersiveFullscreen) {
ash::wm::WindowState* window_state = ash::wm::GetWindowState(window());
EXPECT_FALSE(window_state->in_immersive_fullscreen());
SetEnabled(true);
ASSERT_TRUE(controller()->IsEnabled());
EXPECT_TRUE(window_state->in_immersive_fullscreen());
SetEnabled(false);
ASSERT_FALSE(controller()->IsEnabled());
EXPECT_FALSE(window_state->in_immersive_fullscreen());
}
// Test how focus and activation affects whether the top-of-window views are
// revealed.
TEST_F(ImmersiveFullscreenControllerTest, Focus) {
// TODO: investigate failure. http://crbug.com/698085.
if (Shell::GetAshConfig() == Config::MASH)
return;
// Add views to the view hierarchy which we will focus and unfocus during the
// test.
views::View* child_view = new views::View();
child_view->SetBounds(0, 0, 10, 10);
child_view->SetFocusBehavior(views::View::FocusBehavior::ALWAYS);
top_container()->AddChildView(child_view);
views::View* unrelated_view = new views::View();
unrelated_view->SetBounds(0, 100, 10, 10);
unrelated_view->SetFocusBehavior(views::View::FocusBehavior::ALWAYS);
top_container()->parent()->AddChildView(unrelated_view);
views::FocusManager* focus_manager =
top_container()->GetWidget()->GetFocusManager();
SetEnabled(true);
// 1) Test that the top-of-window views stay revealed as long as either a
// |child_view| has focus or the mouse is hovered above the top-of-window
// views.
AttemptReveal(MODALITY_MOUSE);
child_view->RequestFocus();
focus_manager->ClearFocus();
EXPECT_TRUE(controller()->IsRevealed());
child_view->RequestFocus();
SetHovered(false);
EXPECT_TRUE(controller()->IsRevealed());
focus_manager->ClearFocus();
EXPECT_FALSE(controller()->IsRevealed());
// 2) Test that focusing |unrelated_view| hides the top-of-window views.
// Note: In this test we can cheat and trigger a reveal via focus because
// the top container does not hide when the top-of-window views are not
// revealed.
child_view->RequestFocus();
EXPECT_TRUE(controller()->IsRevealed());
unrelated_view->RequestFocus();
EXPECT_FALSE(controller()->IsRevealed());
// 3) Test that a loss of focus of |child_view| to |unrelated_view|
// while immersive mode is disabled is properly registered.
child_view->RequestFocus();
EXPECT_TRUE(controller()->IsRevealed());
SetEnabled(false);
EXPECT_FALSE(controller()->IsRevealed());
unrelated_view->RequestFocus();
SetEnabled(true);
EXPECT_FALSE(controller()->IsRevealed());
// Repeat test but with a revealed lock acquired when immersive mode is
// disabled because the code path is different.
child_view->RequestFocus();
EXPECT_TRUE(controller()->IsRevealed());
SetEnabled(false);
std::unique_ptr<ImmersiveRevealedLock> lock(controller()->GetRevealedLock(
ImmersiveFullscreenController::ANIMATE_REVEAL_NO));
EXPECT_FALSE(controller()->IsRevealed());
unrelated_view->RequestFocus();
SetEnabled(true);
EXPECT_TRUE(controller()->IsRevealed());
lock.reset();
EXPECT_FALSE(controller()->IsRevealed());
}
// Test how transient windows affect whether the top-of-window views are
// revealed.
TEST_F(ImmersiveFullscreenControllerTest, Transient) {
// TODO: investigate failure. http://crbug.com/698085.
if (Shell::GetAshConfig() == Config::MASH)
return;
views::Widget* top_container_widget = top_container()->GetWidget();
SetEnabled(true);
ASSERT_FALSE(controller()->IsRevealed());
// 1) Test that a transient window which is not a bubble does not trigger a
// reveal but does keep the top-of-window views revealed if they are already
// revealed.
views::Widget::InitParams transient_params;
transient_params.ownership =
views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
transient_params.parent = top_container_widget->GetNativeView();
transient_params.bounds = gfx::Rect(0, 100, 100, 100);
std::unique_ptr<views::Widget> transient_widget(new views::Widget());
transient_widget->Init(transient_params);
EXPECT_FALSE(controller()->IsRevealed());
AttemptReveal(MODALITY_MOUSE);
EXPECT_TRUE(controller()->IsRevealed());
transient_widget->Show();
SetHovered(false);
EXPECT_TRUE(controller()->IsRevealed());
transient_widget.reset();
EXPECT_FALSE(controller()->IsRevealed());
// 2) Test that activating a non-transient window does not keep the
// top-of-window views revealed.
views::Widget::InitParams non_transient_params;
non_transient_params.ownership =
views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
non_transient_params.context = top_container_widget->GetNativeView();
non_transient_params.bounds = gfx::Rect(0, 100, 100, 100);
std::unique_ptr<views::Widget> non_transient_widget(new views::Widget());
non_transient_widget->Init(non_transient_params);
EXPECT_FALSE(controller()->IsRevealed());
AttemptReveal(MODALITY_MOUSE);
EXPECT_TRUE(controller()->IsRevealed());
non_transient_widget->Show();
SetHovered(false);
EXPECT_FALSE(controller()->IsRevealed());
}
// Test how bubbles affect whether the top-of-window views are revealed.
TEST_F(ImmersiveFullscreenControllerTest, Bubbles) {
// TODO: investigate failure. http://crbug.com/698085.
if (Shell::GetAshConfig() == Config::MASH)
return;
std::unique_ptr<ImmersiveRevealedLock> revealed_lock;
views::Widget* top_container_widget = top_container()->GetWidget();
// Add views to the view hierarchy to which we will anchor bubbles.
views::View* child_view = new views::View();
child_view->SetBounds(0, 0, 10, 10);
top_container()->AddChildView(child_view);
views::View* unrelated_view = new views::View();
unrelated_view->SetBounds(0, 100, 10, 10);
top_container()->parent()->AddChildView(unrelated_view);
SetEnabled(true);
ASSERT_FALSE(controller()->IsRevealed());
// 1) Test that a bubble anchored to a child of the top container triggers
// a reveal and keeps the top-of-window views revealed for the duration of
// its visibility.
views::Widget* bubble_widget1(views::BubbleDialogDelegateView::CreateBubble(
new TestBubbleDialogDelegate(child_view)));
bubble_widget1->Show();
EXPECT_TRUE(controller()->IsRevealed());
// Activating |top_container_widget| will close |bubble_widget1|.
top_container_widget->Activate();
AttemptReveal(MODALITY_MOUSE);
revealed_lock.reset(controller()->GetRevealedLock(
ImmersiveFullscreenController::ANIMATE_REVEAL_NO));
EXPECT_TRUE(controller()->IsRevealed());
views::Widget* bubble_widget2 = views::BubbleDialogDelegateView::CreateBubble(
new TestBubbleDialogDelegate(child_view));
bubble_widget2->Show();
EXPECT_TRUE(controller()->IsRevealed());
revealed_lock.reset();
SetHovered(false);
EXPECT_TRUE(controller()->IsRevealed());
bubble_widget2->Close();
EXPECT_FALSE(controller()->IsRevealed());
// 2) Test that transitioning from keeping the top-of-window views revealed
// because of a bubble to keeping the top-of-window views revealed because of
// mouse hover by activating |top_container_widget| works.
views::Widget* bubble_widget3 = views::BubbleDialogDelegateView::CreateBubble(
new TestBubbleDialogDelegate(child_view));
bubble_widget3->Show();
SetHovered(true);
EXPECT_TRUE(controller()->IsRevealed());
top_container_widget->Activate();
EXPECT_TRUE(controller()->IsRevealed());
// 3) Test that the top-of-window views stay revealed as long as at least one
// bubble anchored to a child of the top container is visible.
SetHovered(false);
EXPECT_FALSE(controller()->IsRevealed());
views::BubbleDialogDelegateView* bubble_delegate4(
new TestBubbleDialogDelegate(child_view));
bubble_delegate4->set_can_activate(false);
views::Widget* bubble_widget4(
views::BubbleDialogDelegateView::CreateBubble(bubble_delegate4));
bubble_widget4->Show();
views::BubbleDialogDelegateView* bubble_delegate5(
new TestBubbleDialogDelegate(child_view));
bubble_delegate5->set_can_activate(false);
views::Widget* bubble_widget5(
views::BubbleDialogDelegateView::CreateBubble(bubble_delegate5));
bubble_widget5->Show();
EXPECT_TRUE(controller()->IsRevealed());
bubble_widget4->Hide();
EXPECT_TRUE(controller()->IsRevealed());
bubble_widget5->Hide();
EXPECT_FALSE(controller()->IsRevealed());
bubble_widget5->Show();
EXPECT_TRUE(controller()->IsRevealed());
// 4) Test that visibility changes which occur while immersive fullscreen is
// disabled are handled upon reenabling immersive fullscreen.
SetEnabled(false);
bubble_widget5->Hide();
SetEnabled(true);
EXPECT_FALSE(controller()->IsRevealed());
// We do not need |bubble_widget4| or |bubble_widget5| anymore, close them.
bubble_widget4->Close();
bubble_widget5->Close();
// 5) Test that a bubble added while immersive fullscreen is disabled is
// handled upon reenabling immersive fullscreen.
SetEnabled(false);
views::Widget* bubble_widget6 = views::BubbleDialogDelegateView::CreateBubble(
new TestBubbleDialogDelegate(child_view));
bubble_widget6->Show();
SetEnabled(true);
EXPECT_TRUE(controller()->IsRevealed());
bubble_widget6->Close();
// 6) Test that a bubble which is not anchored to a child of the
// TopContainerView does not trigger a reveal or keep the
// top-of-window views revealed if they are already revealed.
views::Widget* bubble_widget7 = views::BubbleDialogDelegateView::CreateBubble(
new TestBubbleDialogDelegate(unrelated_view));
bubble_widget7->Show();
EXPECT_FALSE(controller()->IsRevealed());
// Activating |top_container_widget| will close |bubble_widget6|.
top_container_widget->Activate();
AttemptReveal(MODALITY_MOUSE);
EXPECT_TRUE(controller()->IsRevealed());
views::Widget* bubble_widget8 = views::BubbleDialogDelegateView::CreateBubble(
new TestBubbleDialogDelegate(unrelated_view));
bubble_widget8->Show();
SetHovered(false);
EXPECT_FALSE(controller()->IsRevealed());
bubble_widget8->Close();
}
// Test that the shelf is set to auto hide as long as the window is in
// immersive fullscreen and that the shelf's state before entering immersive
// fullscreen is restored upon exiting immersive fullscreen.
TEST_F(ImmersiveFullscreenControllerTest, Shelf) {
Shelf* shelf = GetPrimaryShelf();
// Shelf is visible by default.
window()->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_NORMAL);
ASSERT_FALSE(controller()->IsEnabled());
ASSERT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState());
// Entering immersive fullscreen sets the shelf to auto hide.
window()->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_FULLSCREEN);
SetEnabled(true);
EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState());
// Disabling immersive fullscreen puts it back.
SetEnabled(false);
window()->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_NORMAL);
ASSERT_FALSE(controller()->IsEnabled());
EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState());
// The user could toggle the shelf auto-hide behavior.
shelf->SetAutoHideBehavior(SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS);
EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState());
// Entering immersive fullscreen keeps auto-hide.
window()->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_FULLSCREEN);
SetEnabled(true);
EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState());
// Disabling immersive fullscreen maintains the user's auto-hide selection.
SetEnabled(false);
window()->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_NORMAL);
EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState());
}
} // namespase ash
| 39.262626 | 80 | 0.73754 | [
"vector"
] |
a827821594080abacb1752137d05a52744015399 | 7,518 | cpp | C++ | Currency/main.cpp | sqeezelemon/itmo-programming | 731990c349c55c70ff4d1444068ddfe7f7e0e475 | [
"WTFPL"
] | null | null | null | Currency/main.cpp | sqeezelemon/itmo-programming | 731990c349c55c70ff4d1444068ddfe7f7e0e475 | [
"WTFPL"
] | null | null | null | Currency/main.cpp | sqeezelemon/itmo-programming | 731990c349c55c70ff4d1444068ddfe7f7e0e475 | [
"WTFPL"
] | null | null | null | #define DEBUG 1
// Collections
#include <vector>
#include <set>
// Other stdlib stuff
#include <string>
#include <iostream>
#include <csignal> // For the signal() function
// Third party
#include <nlohmann/json.hpp>
#include <curl/curl.h>
// Cross-platform sleep
#include <thread>
#include <chrono>
// Debug/showcase
# if (DEBUG)
#include <cstdlib> // for rand()
#endif
#define RED "\x1B[31m"
#define GRN "\x1B[32m"
#define YEL "\x1B[33m"
#define BLU "\x1B[34m"
#define MAG "\x1B[35m"
#define CYN "\x1B[36m"
#define WHT "\x1B[37m"
#define RESET "\x1B[0m"
#define BOLD "\e[1m"
#define ENDBOLD "\e[0m"
#define ERROR "[" RED BOLD "ERROR" ENDBOLD RESET "] "
#define WARNING "[" MAG BOLD "WARNING" ENDBOLD RESET "] "
const char* apiUrl = "http://www.cbr-xml-daily.ru/daily_json.js";
static std::string response;
CURL* curl;
CURLcode curlCode;
nlohmann::json json;
std::vector<std::string> currencyList;
// 0 - OK, 1 - ERROR
int fetch() {
curlCode = curl_easy_perform(curl);
if (curlCode != CURLE_OK) return 1;
json = nlohmann::json::parse(response);
response.clear();
if (json.find("Valute") == json.end()) {
fprintf(stderr, ERROR "Valute key not present\n");
return 1;
}
json = json["Valute"];
// DEBUG / SHOWCASE ONLY
#if (DEBUG)
for (auto curr : currencyList) {
if (!json.contains(curr)) continue;
double rnd = (double)(rand() % 100000) / (double)10000 * (double)(rand() % 2 == 1 ? -1 : 1);
json[curr]["Value"] = abs((double)json[curr]["Value"] + rnd);
}
#endif
return 0;
}
// All the analysis stuff
struct currencyCounter {
uint32_t value;
uint32_t count;
// For std::set
friend inline bool operator< (currencyCounter l, currencyCounter r) {
return l.value < r.value;
}
};
std::vector< std::set<currencyCounter> > currency;
void analyse() {
for (int i = 0; i < currencyList.size(); i++) {
uint32_t rate = (double)json[currencyList[i]]["Value"] * 10000;
currencyCounter temp { rate, 1 };
auto searchRes = currency[i].find(temp);
if (searchRes != currency[i].end()) {
temp = *searchRes;
temp.count++;
currency[i].erase(temp);
}
currency[i].insert(temp);
}
}
// Clears output using ANSI code magic
void clearLines(int amm) {
for (int i = 0; i < amm; i++) {
std::cout << "\u001b[1000D" // Move cursor left (CSI1000D)
<< "\u001b[2K" // Clear whole line (CSI2K)
<< "\u001b[1A"; // Move cursor up (CSI1A)
}
std::cout.flush();
}
// Executed when the program is terminated
void finish(int signum) {
if (currency[0].empty()) {
printf("ะัะพะณัะฐะผะผะฐ ะพะฑััะฒะธะปะฐ ะดะตัะพะปั!\n");
exit(0);
}
clearLines(currencyList.size());
std::cout << "\u001b[1000D" << "\u001b[2K"; // Remove line without going up to the line up (hense, why clearlines isn't used)
std::cout.flush();
curl_easy_cleanup(curl);
curl_global_cleanup();
printf(BOLD "CURR\tMIN\tMAX\tNMNL\tAVG\tMED\n" ENDBOLD);
for (int i = 0; i < currencyList.size(); i++) {
double min = (double)(*currency[i].begin()).value / 10000;
double max = (double)(*currency[i].rbegin()).value / 10000;
int nmnl = json[currencyList[i]]["Nominal"];
uint64_t avgint = 0;
uint64_t iterCount = 0;
for (auto rate : currency[i]) {
avgint += (uint64_t)rate.value * (uint64_t)rate.count;
iterCount += rate.count;
}
double avg = (double)avgint / (double)(10000*iterCount);
double med = 0;
uint64_t currpos = 0;
for (auto it = currency[i].begin(); it != currency[i].end(); it++) {
currpos += it->count;
if (currpos < iterCount/2) {
continue;
} else if (currpos == iterCount/2 && iterCount % 2 == 0) {
med = (double)it->value / (double)10000;
it++;
med = (med + ((double)it->value / (double)10000))/2;
break;
} else if (currpos == iterCount/2) {
it++;
med = (double)it->value / (double)10000;
break;
} else {
med = (double)it->value / (double)10000;
break;
}
}
std::cout << BOLD << currencyList[i] << ENDBOLD << '\t'
<< min << '\t' << max << '\t'
<< (nmnl > 1000 ? nmnl/1000 : nmnl) << (nmnl > 1000 ? "k\t" : "\t")
<< avg << '\t' << med << '\n';
}
exit(0);
}
// Used by CURL after data is received
size_t writeCallback(char *data, size_t size, size_t nitems, std::string *out) {
if (out == NULL) return 0;
out->append(data, size*nitems);
return size*nitems;
}
// Output the table
void output() {
for (auto curr : currencyList) {
double rate = json[curr]["Value"];
double prev = json[curr]["Previous"];
double nominal = json[curr]["Nominal"];
std::cout << '\n' << BOLD << curr << ENDBOLD
<< (rate == prev ? YEL : (rate > prev ? GRN : RED))
<< (rate == prev ? " ~" : (rate > prev ? " โฒ" : " โผ")) << '\t' << rate << RESET << '\t'
<< prev << '\t' << (nominal > 1000 ? nominal/1000 : nominal) << (nominal > 1000 ? "k\t" : "\t")
<< (std::string)json[curr]["Name"];
}
std::cout.flush();
}
int main(int argc, char** argv) {
signal(SIGINT, finish);
std::chrono::seconds updateInterval(10);
for (int i = 1; i < argc; i++) {
if ((strlen(argv[i]) == 3) && (strstr("-", argv[i]) == NULL)) {
std::string temp(argv[i]);
bool duplicate = false;
for (auto curr : currencyList) {
if (curr == temp) {
duplicate = true;
break;
}
}
if (!duplicate) currencyList.push_back(temp);
} else if ((strstr("--interval", argv[i]) != argv[i] || strstr("-i", argv[i]) != argv[i]) && i < argc-1) {
std::chrono::seconds temp(atoi(argv[i+1]));
updateInterval = temp;
i++;
}
}
// CURL setup
curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
curl_easy_setopt(curl, CURLOPT_URL, apiUrl);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 1);
// First fetch: get info
if (fetch()) {
fprintf(stderr, ERROR "First fetch failed, terminating\n");
return 1;
}
// Check if currency exists
for (int i = 0; i < currencyList.size(); i++) {
if (json.contains(currencyList[i])) continue;
fprintf(stderr, WARNING "Currency " BOLD "%s" ENDBOLD " not found!\n", currencyList[i].c_str());
currencyList.erase(std::next(currencyList.begin(), i));
}
// Add all available currencies if none were requested
if (currencyList.size() == 0) {
for (auto it = json.begin(); it != json.end(); it++) {
currencyList.push_back(it.key());
}
}
currency.resize(currencyList.size());
printf(BOLD "CURR\tRATE\tPREV\tNMNL\tNAME" ENDBOLD);
output();
analyse();
while (true) {
std::this_thread::sleep_for(updateInterval);
if (fetch()) {
continue;
}
clearLines(currencyList.size());
analyse();
output();
}
} | 30.685714 | 129 | 0.546954 | [
"vector"
] |
a82e356cbc5efe08d65e3120e9a4c36d8c2fbea7 | 3,385 | cpp | C++ | preferencesdialog.cpp | rossomah/waifu2x-converter-qt | 1e203ad160f6e69874f1dd391cec534abdc36324 | [
"MIT"
] | 31 | 2015-08-27T17:03:11.000Z | 2022-01-31T03:25:09.000Z | preferencesdialog.cpp | rossomah/waifu2x-converter-qt | 1e203ad160f6e69874f1dd391cec534abdc36324 | [
"MIT"
] | null | null | null | preferencesdialog.cpp | rossomah/waifu2x-converter-qt | 1e203ad160f6e69874f1dd391cec534abdc36324 | [
"MIT"
] | 9 | 2015-05-31T12:43:18.000Z | 2022-01-24T16:09:35.000Z | #include "preferencesdialog.h"
#include "ui_preferencesdialog.h"
#include "waifu2xconvertercppoptions.h"
#include "optionpreferencesform.h"
#include <QFileDialog>
#include <QMessageBox>
using namespace Waifu2xConverterQt;
PreferencesDialog::PreferencesDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::PreferencesDialog),
m_settings(new Waifu2xConverterQtSettings(this))
{
ui->setupUi(this);
init();
}
PreferencesDialog::~PreferencesDialog()
{
delete ui;
}
void PreferencesDialog::saveSettings()
{
m_settings->setWaifu2xConverterCppCommand(ui->waifu2xCommandLine->text());
m_settings->setModelDirectory(ui->modelDirectoryLine->text());
m_settings->setUseCustomFileName(ui->outputFilenameCheck->isChecked());
for (const auto& opt : optionList()) {
auto* form = findChild<OptionPreferencesForm *>(QString("option%1Widget").arg(optionToString(opt)));
Q_ASSERT(form);
if (form) {
m_settings->setOptionIgnored(opt, form->isCheckedIgnoreBox());
m_settings->setOptionString(opt, form->optionStringLineText());
m_settings->setOptionArgument(opt, form->optionArgumentLineText());
}
}
}
void PreferencesDialog::browseWaifu2xConverterCpp()
{
QFileDialog dialog(this, tr("Select waifu2x-converter-cpp"));
dialog.setAcceptMode(QFileDialog::AcceptOpen);
if (dialog.exec() == QFileDialog::Accepted)
ui->waifu2xCommandLine->setText(dialog.selectedFiles().first());
}
void PreferencesDialog::browseModelDirectory()
{
QFileDialog dialog(this, tr("Select model directory"));
dialog.setAcceptMode(QFileDialog::AcceptOpen);
dialog.setFileMode(QFileDialog::DirectoryOnly);
if (dialog.exec() == QFileDialog::Accepted)
ui->modelDirectoryLine->setText(dialog.selectedFiles().first());
}
void PreferencesDialog::restoreDefaults()
{
m_settings->restoreDefaults();
loadSettings();
QMessageBox::information(this,
"",
tr("Done."),
QMessageBox::Ok);
}
void PreferencesDialog::init()
{
connect(this, SIGNAL(accepted()), this, SLOT(saveSettings()));
connect(ui->browseButton, SIGNAL(clicked(bool)), this, SLOT(browseWaifu2xConverterCpp()));
connect(ui->browseModelDirectoryButton, SIGNAL(clicked(bool)), this, SLOT(browseModelDirectory()));
connect(ui->restoreButton, SIGNAL(clicked(bool)), this, SLOT(restoreDefaults()));
for (const auto& opt : optionList()) {
ui->optionBox->addItem(optionToString(opt));
ui->optionWidget->addWidget(new OptionPreferencesForm(opt, this));
}
loadSettings();
}
void PreferencesDialog::loadSettings()
{
ui->waifu2xCommandLine->setText(m_settings->waifu2xConverterCppCommand());
ui->modelDirectoryLine->setText(m_settings->modelDirectory());
ui->outputFilenameCheck->setChecked(m_settings->isUseCustomFileName());
for (const auto& opt : optionList()) {
auto* form = findChild<OptionPreferencesForm *>(QString("option%1Widget").arg(optionToString(opt)));
Q_ASSERT(form);
if (form) {
form->setIgnoreBoxChecked(m_settings->isOptionIgnored(opt));
form->setOptionStringLineText(m_settings->optionString(opt));
form->setOptionArgumentLineText(m_settings->optionArgument(opt));
}
}
}
| 32.238095 | 108 | 0.689513 | [
"model"
] |
a82e97ecaea8f69ee0562e4d3d0dc3c846de34fa | 7,593 | cpp | C++ | src/app/messagestorage.cpp | mf1910/communi-sailfish | e6d160ffa4ecb3affc762e5565e52b7bc482c2e1 | [
"CC-BY-4.0",
"BSD-3-Clause"
] | 18 | 2015-01-25T20:32:31.000Z | 2020-06-11T03:08:48.000Z | src/app/messagestorage.cpp | mf1910/communi-sailfish | e6d160ffa4ecb3affc762e5565e52b7bc482c2e1 | [
"CC-BY-4.0",
"BSD-3-Clause"
] | 80 | 2015-01-24T19:20:21.000Z | 2022-03-16T21:32:10.000Z | src/app/messagestorage.cpp | mf1910/communi-sailfish | e6d160ffa4ecb3affc762e5565e52b7bc482c2e1 | [
"CC-BY-4.0",
"BSD-3-Clause"
] | 15 | 2015-01-16T14:22:23.000Z | 2021-08-01T09:07:42.000Z | /*
Copyright (C) 2013-2015 The Communi Project
You may use this file under the terms of BSD license as follows:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "messagestorage.h"
#include "bufferproxymodel.h"
#include "messageformatter.h"
#include "messagemodel.h"
#include <IrcBufferModel>
#include <IrcBuffer>
#include <QTimerEvent>
#include <QDebug>
#include <QDBusConnection>
IRC_USE_NAMESPACE
class MessageService : public QObject
{
Q_OBJECT
Q_CLASSINFO("D-Bus Interface", "com.communi.irc")
public:
MessageService(QObject* parent = 0) : QObject(parent)
{
if (!QDBusConnection::sessionBus().registerService("com.communi.irc"))
qWarning() << "MessageService: failed to register com.communi.irc D-Bus service";
if (!QDBusConnection::sessionBus().registerObject("/", this, QDBusConnection::ExportAllSignals))
qWarning() << "MessageService: failed to register com.communi.irc D-Bus object";
}
signals:
void activeHighlightsChanged(int highlights);
void messageMissed(const QString& sender, const QString& message);
void messageHighlighted(const QString& buffer, const QString& sender, const QString& message);
private:
friend class MessageStorage;
};
MessageStorage::MessageStorage(BufferProxyModel* proxy) : QObject(proxy), m_dirty(0), m_highlights(0),
m_firstHiglight(-1), m_lastHighlight(-1), m_baseColor(QColor::fromHsl(359, 102, 116)),
m_service(new MessageService(this)), m_proxy(proxy)
{
connect(proxy, &BufferProxyModel::currentBufferChanged, this, &MessageStorage::onCurrentBufferChanged);
}
MessageModel* MessageStorage::model(IrcBuffer* buffer) const
{
return m_models.value(buffer);
}
QObject* MessageStorage::get(IrcBuffer* buffer) const
{
return m_models.value(buffer);
}
int MessageStorage::activeHighlights() const
{
return m_highlights;
}
void MessageStorage::setActiveHighlights(int highlights)
{
if (m_highlights != highlights) {
m_highlights = highlights;
emit activeHighlightsChanged(highlights);
emit m_service->activeHighlightsChanged(highlights);
}
}
int MessageStorage::firstActiveHighlight() const
{
return m_firstHiglight;
}
void MessageStorage::setFirstActiveHighlight(int highlight)
{
if (m_firstHiglight != highlight) {
m_firstHiglight = highlight;
emit firstActiveHighlightChanged();
}
}
int MessageStorage::lastActiveHighlight() const
{
return m_lastHighlight;
}
void MessageStorage::setLastActiveHighlight(int highlight)
{
if (m_lastHighlight != highlight) {
m_lastHighlight = highlight;
emit lastActiveHighlightChanged();
}
}
QColor MessageStorage::baseColor() const
{
return m_baseColor;
}
void MessageStorage::setBaseColor(const QColor& color)
{
if (m_baseColor != color) {
m_baseColor = color;
foreach (MessageModel* model, m_models)
model->formatter()->setBaseColor(color);
}
}
void MessageStorage::add(IrcBuffer* buffer)
{
if (buffer && !m_models.contains(buffer)) {
if (buffer->isSticky())
connect(buffer->model(), &IrcBufferModel::buffersChanged, this, &MessageStorage::invalidateActiveHighlights);
buffer->setPersistent(true);
MessageModel* model = new MessageModel(buffer);
model->formatter()->setBaseColor(m_baseColor);
connect(buffer, &IrcBuffer::destroyed, this, &MessageStorage::remove);
connect(model, &MessageModel::activeHighlightsChanged, this, &MessageStorage::updateActiveHighlights);
connect(model, &MessageModel::messageMissed, this, &MessageStorage::onMessageMissed);
connect(model, &MessageModel::messageHighlighted, this, &MessageStorage::onMessageHighlighted);
m_models.insert(buffer, model);
emit added(model);
invalidateActiveHighlights();
}
}
void MessageStorage::remove(IrcBuffer* buffer)
{
if (buffer && m_models.contains(buffer)) {
MessageModel* model = m_models.take(buffer);
if (model) {
emit removed(model);
delete model;
invalidateActiveHighlights();
}
}
}
void MessageStorage::timerEvent(QTimerEvent* event)
{
if (event->timerId() == m_dirty) {
updateActiveHighlights();
killTimer(m_dirty);
m_dirty = 0;
}
}
void MessageStorage::updateActiveHighlights()
{
int first = -1;
int last = -1;
int highlights = 0;
foreach (MessageModel* model, m_models) {
const int active = model->activeHighlights();
highlights += active;
if (active > 0) {
const int index = m_proxy->indexOf(model->buffer());
if (index != -1) {
first = first == -1 ? index : qMin(first, index);
last = qMax(last, index);
}
}
}
setActiveHighlights(highlights);
setFirstActiveHighlight(first);
setLastActiveHighlight(last);
}
void MessageStorage::invalidateActiveHighlights()
{
if (!m_dirty)
m_dirty = startTimer(100);
}
void MessageStorage::onMessageMissed(const QString& message)
{
MessageModel* model = qobject_cast<MessageModel*>(sender());
if (model) {
IrcBuffer* buffer = model->buffer();
if (buffer) {
emit missed(buffer, message);
emit m_service->messageMissed(buffer->title(), message);
}
}
}
void MessageStorage::onMessageHighlighted(const QString& sender, const QString& message)
{
MessageModel* model = qobject_cast<MessageModel*>(QObject::sender());
if (model) {
IrcBuffer* buffer = model->buffer();
if (buffer) {
emit highlighted(buffer, sender, message);
emit m_service->messageHighlighted(buffer->title(), sender, message);
}
}
}
void MessageStorage::onCurrentBufferChanged(IrcBuffer* buffer)
{
MessageModel* model = m_models.value(buffer);
if (m_current != model) {
if (m_current)
m_current->setCurrent(false);
if (model)
model->setCurrent(true);
m_current = model;
}
}
#include "messagestorage.moc"
| 31.903361 | 121 | 0.693665 | [
"object",
"model"
] |
a82f18431ad6b77099b95c40b8aa5b8d92705777 | 30,866 | cpp | C++ | Microsoft.WindowsAzure.Storage/src/cloud_blob_container.cpp | JasonDictos/azure-storage-cpp | 8accecace59ad631cd7686f9e11fa7498fe717ac | [
"Apache-2.0"
] | null | null | null | Microsoft.WindowsAzure.Storage/src/cloud_blob_container.cpp | JasonDictos/azure-storage-cpp | 8accecace59ad631cd7686f9e11fa7498fe717ac | [
"Apache-2.0"
] | null | null | null | Microsoft.WindowsAzure.Storage/src/cloud_blob_container.cpp | JasonDictos/azure-storage-cpp | 8accecace59ad631cd7686f9e11fa7498fe717ac | [
"Apache-2.0"
] | 2 | 2020-04-06T11:22:08.000Z | 2020-11-14T19:16:58.000Z | // -----------------------------------------------------------------------------------------
// <copyright file="cloud_blob_container.cpp" company="Microsoft">
// Copyright 2013 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// -----------------------------------------------------------------------------------------
#include "stdafx.h"
#include "was/blob.h"
#include "was/error_code_strings.h"
#include "wascore/protocol.h"
#include "wascore/protocol_xml.h"
#include "wascore/util.h"
#include "wascore/constants.h"
namespace azure { namespace storage {
cloud_blob_container::cloud_blob_container(storage_uri uri)
: m_uri(std::move(uri)), m_metadata(std::make_shared<cloud_metadata>()), m_properties(std::make_shared<cloud_blob_container_properties>())
{
init(storage_credentials());
}
cloud_blob_container::cloud_blob_container(storage_uri uri, storage_credentials credentials)
: m_uri(std::move(uri)), m_metadata(std::make_shared<cloud_metadata>()), m_properties(std::make_shared<cloud_blob_container_properties>())
{
init(std::move(credentials));
}
cloud_blob_container::cloud_blob_container(utility::string_t name, cloud_blob_client client)
: m_name(std::move(name)), m_client(std::move(client)), m_uri(core::append_path_to_uri(m_client.base_uri(), m_name)),
m_metadata(std::make_shared<cloud_metadata>()), m_properties(std::make_shared<cloud_blob_container_properties>())
{
}
cloud_blob_container::cloud_blob_container(utility::string_t name, cloud_blob_client client, cloud_blob_container_properties properties, cloud_metadata metadata)
: m_name(std::move(name)), m_client(std::move(client)), m_uri(core::append_path_to_uri(m_client.base_uri(), m_name)),
m_metadata(std::make_shared<cloud_metadata>(std::move(metadata))), m_properties(std::make_shared<cloud_blob_container_properties>(std::move(properties)))
{
}
void cloud_blob_container::init(storage_credentials credentials)
{
utility::string_t snapshot;
m_uri = core::verify_blob_uri(m_uri, credentials, snapshot);
if (!core::parse_container_uri(m_uri, m_name))
{
throw std::invalid_argument("uri");
}
m_client = cloud_blob_client(core::get_service_client_uri(m_uri), std::move(credentials));
}
utility::string_t cloud_blob_container::get_shared_access_signature(const blob_shared_access_policy& policy, const utility::string_t& stored_policy_identifier) const
{
if (!service_client().credentials().is_shared_key())
{
throw std::logic_error(protocol::error_sas_missing_credentials);
}
// since 2015-02-21, canonicalized resource is changed from "/account/name" to "/blob/account/name"
utility::string_t resource_str;
resource_str.reserve(service_client().credentials().account_name().size() + name().size() + 7);
resource_str.append(_XPLATSTR("/"));
resource_str.append(protocol::service_blob);
resource_str.append(_XPLATSTR("/"));
resource_str.append(service_client().credentials().account_name());
resource_str.append(_XPLATSTR("/"));
resource_str.append(name());
// Future resource type changes from "c" => "container"
return protocol::get_blob_sas_token(stored_policy_identifier, policy, cloud_blob_shared_access_headers(), _XPLATSTR("c"), resource_str, service_client().credentials());
}
cloud_blob cloud_blob_container::get_blob_reference(utility::string_t blob_name) const
{
return get_blob_reference(std::move(blob_name), utility::string_t());
}
cloud_blob cloud_blob_container::get_blob_reference(utility::string_t blob_name, utility::string_t snapshot_time) const
{
return cloud_blob(std::move(blob_name), std::move(snapshot_time), *this);
}
cloud_page_blob cloud_blob_container::get_page_blob_reference(utility::string_t blob_name) const
{
return get_page_blob_reference(std::move(blob_name), utility::string_t());
}
cloud_page_blob cloud_blob_container::get_page_blob_reference(utility::string_t blob_name, utility::string_t snapshot_time) const
{
return cloud_page_blob(std::move(blob_name), std::move(snapshot_time), *this);
}
cloud_block_blob cloud_blob_container::get_block_blob_reference(utility::string_t blob_name) const
{
return get_block_blob_reference(std::move(blob_name), utility::string_t());
}
cloud_block_blob cloud_blob_container::get_block_blob_reference(utility::string_t blob_name, utility::string_t snapshot_time) const
{
return cloud_block_blob(std::move(blob_name), std::move(snapshot_time), *this);
}
cloud_append_blob cloud_blob_container::get_append_blob_reference(utility::string_t blob_name) const
{
return get_append_blob_reference(std::move(blob_name), utility::string_t());
}
cloud_append_blob cloud_blob_container::get_append_blob_reference(utility::string_t blob_name, utility::string_t snapshot_time) const
{
return cloud_append_blob(std::move(blob_name), std::move(snapshot_time), *this);
}
cloud_blob_directory cloud_blob_container::get_directory_reference(utility::string_t directory_name) const
{
return cloud_blob_directory(std::move(directory_name), *this);
}
pplx::task<void> cloud_blob_container::download_attributes_async(const access_condition& condition, const blob_request_options& options, operation_context context)
{
blob_request_options modified_options(options);
modified_options.apply_defaults(service_client().default_request_options(), blob_type::unspecified);
auto properties = m_properties;
auto metadata = m_metadata;
auto command = std::make_shared<core::storage_command<void>>(uri());
command->set_build_request(std::bind(protocol::get_blob_container_properties, condition, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
command->set_authentication_handler(service_client().authentication_handler());
command->set_location_mode(core::command_location_mode::primary_or_secondary);
command->set_preprocess_response([properties, metadata] (const web::http::http_response& response, const request_result& result, operation_context context)
{
protocol::preprocess_response_void(response, result, context);
*properties = protocol::blob_response_parsers::parse_blob_container_properties(response);
*metadata = protocol::parse_metadata(response);
});
return core::executor<void>::execute_async(command, modified_options, context);
}
pplx::task<void> cloud_blob_container::upload_metadata_async(const access_condition& condition, const blob_request_options& options, operation_context context)
{
blob_request_options modified_options(options);
modified_options.apply_defaults(service_client().default_request_options(), blob_type::unspecified);
auto properties = m_properties;
auto command = std::make_shared<core::storage_command<void>>(uri());
command->set_build_request(std::bind(protocol::set_blob_container_metadata, metadata(), condition, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
command->set_authentication_handler(service_client().authentication_handler());
command->set_preprocess_response([properties] (const web::http::http_response& response, const request_result& result, operation_context context)
{
protocol::preprocess_response_void(response, result, context);
properties->update_etag_and_last_modified(protocol::blob_response_parsers::parse_blob_container_properties(response));
});
return core::executor<void>::execute_async(command, modified_options, context);
}
pplx::task<utility::string_t> cloud_blob_container::acquire_lease_async(const lease_time& duration, const utility::string_t& proposed_lease_id, const access_condition& condition, const blob_request_options& options, operation_context context) const
{
blob_request_options modified_options(options);
modified_options.apply_defaults(service_client().default_request_options(), blob_type::unspecified);
auto properties = m_properties;
auto command = std::make_shared<core::storage_command<utility::string_t>>(uri());
command->set_build_request(std::bind(protocol::lease_blob_container, protocol::header_value_lease_acquire, proposed_lease_id, duration, lease_break_period(), condition, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
command->set_authentication_handler(service_client().authentication_handler());
command->set_preprocess_response([properties] (const web::http::http_response& response, const request_result& result, operation_context context) -> utility::string_t
{
protocol::preprocess_response_void(response, result, context);
properties->update_etag_and_last_modified(protocol::blob_response_parsers::parse_blob_container_properties(response));
return protocol::parse_lease_id(response);
});
return core::executor<utility::string_t>::execute_async(command, modified_options, context);
}
pplx::task<void> cloud_blob_container::renew_lease_async(const access_condition& condition, const blob_request_options& options, operation_context context) const
{
if (condition.lease_id().empty())
{
throw std::invalid_argument("condition");
}
blob_request_options modified_options(options);
modified_options.apply_defaults(service_client().default_request_options(), blob_type::unspecified);
auto properties = m_properties;
auto command = std::make_shared<core::storage_command<void>>(uri());
command->set_build_request(std::bind(protocol::lease_blob_container, protocol::header_value_lease_renew, utility::string_t(), lease_time(), lease_break_period(), condition, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
command->set_authentication_handler(service_client().authentication_handler());
command->set_preprocess_response([properties] (const web::http::http_response& response, const request_result& result, operation_context context)
{
protocol::preprocess_response_void(response, result, context);
properties->update_etag_and_last_modified(protocol::blob_response_parsers::parse_blob_container_properties(response));
});
return core::executor<void>::execute_async(command, modified_options, context);
}
pplx::task<utility::string_t> cloud_blob_container::change_lease_async(const utility::string_t& proposed_lease_id, const access_condition& condition, const blob_request_options& options, operation_context context) const
{
if (condition.lease_id().empty())
{
throw std::invalid_argument("condition");
}
blob_request_options modified_options(options);
modified_options.apply_defaults(service_client().default_request_options(), blob_type::unspecified);
auto properties = m_properties;
auto command = std::make_shared<core::storage_command<utility::string_t>>(uri());
command->set_build_request(std::bind(protocol::lease_blob_container, protocol::header_value_lease_change, proposed_lease_id, lease_time(), lease_break_period(), condition, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
command->set_authentication_handler(service_client().authentication_handler());
command->set_preprocess_response([properties] (const web::http::http_response& response, const request_result& result, operation_context context) -> utility::string_t
{
protocol::preprocess_response_void(response, result, context);
properties->update_etag_and_last_modified(protocol::blob_response_parsers::parse_blob_container_properties(response));
return protocol::parse_lease_id(response);
});
return core::executor<utility::string_t>::execute_async(command, modified_options, context);
}
pplx::task<void> cloud_blob_container::release_lease_async(const access_condition& condition, const blob_request_options& options, operation_context context) const
{
if (condition.lease_id().empty())
{
throw std::invalid_argument("condition");
}
blob_request_options modified_options(options);
modified_options.apply_defaults(service_client().default_request_options(), blob_type::unspecified);
auto properties = m_properties;
auto command = std::make_shared<core::storage_command<void>>(uri());
command->set_build_request(std::bind(protocol::lease_blob_container, protocol::header_value_lease_release, utility::string_t(), lease_time(), lease_break_period(), condition, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
command->set_authentication_handler(service_client().authentication_handler());
command->set_preprocess_response([properties] (const web::http::http_response& response, const request_result& result, operation_context context)
{
protocol::preprocess_response_void(response, result, context);
properties->update_etag_and_last_modified(protocol::blob_response_parsers::parse_blob_container_properties(response));
});
return core::executor<void>::execute_async(command, modified_options, context);
}
pplx::task<std::chrono::seconds> cloud_blob_container::break_lease_async(const lease_break_period& break_period, const access_condition& condition, const blob_request_options& options, operation_context context) const
{
blob_request_options modified_options(options);
modified_options.apply_defaults(service_client().default_request_options(), blob_type::unspecified);
auto properties = m_properties;
auto command = std::make_shared<core::storage_command<std::chrono::seconds>>(uri());
command->set_build_request(std::bind(protocol::lease_blob_container, protocol::header_value_lease_break, utility::string_t(), lease_time(), break_period, condition, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
command->set_authentication_handler(service_client().authentication_handler());
command->set_preprocess_response([properties] (const web::http::http_response& response, const request_result& result, operation_context context) -> std::chrono::seconds
{
protocol::preprocess_response_void(response, result, context);
properties->update_etag_and_last_modified(protocol::blob_response_parsers::parse_blob_container_properties(response));
return protocol::parse_lease_time(response);
});
return core::executor<std::chrono::seconds>::execute_async(command, modified_options, context);
}
pplx::task<void> cloud_blob_container::create_async(blob_container_public_access_type public_access, const blob_request_options& options, operation_context context)
{
blob_request_options modified_options(options);
modified_options.apply_defaults(service_client().default_request_options(), blob_type::unspecified);
auto properties = m_properties;
auto command = std::make_shared<core::storage_command<void>>(uri());
command->set_build_request(std::bind(protocol::create_blob_container, public_access, metadata(), std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
command->set_authentication_handler(service_client().authentication_handler());
command->set_preprocess_response([properties, public_access] (const web::http::http_response& response, const request_result& result, operation_context context)
{
protocol::preprocess_response_void(response, result, context);
properties->m_public_access = public_access;
properties->update_etag_and_last_modified(protocol::blob_response_parsers::parse_blob_container_properties(response));
});
return core::executor<void>::execute_async(command, modified_options, context);
}
pplx::task<bool> cloud_blob_container::create_if_not_exists_async(blob_container_public_access_type public_access, const blob_request_options& options, operation_context context)
{
blob_request_options modified_options(options);
modified_options.apply_defaults(service_client().default_request_options(), blob_type::unspecified);
auto instance = std::make_shared<cloud_blob_container>(*this);
return exists_async(true, modified_options, context).then([instance, public_access, modified_options, context] (bool exists_result) -> pplx::task<bool>
{
if (!exists_result)
{
return instance->create_async(public_access, modified_options, context).then([] (pplx::task<void> create_task) -> bool
{
try
{
create_task.wait();
return true;
}
catch (const storage_exception& e)
{
const azure::storage::request_result& result = e.result();
if (result.is_response_available() &&
(result.http_status_code() == web::http::status_codes::Conflict) &&
(result.extended_error().code() == protocol::error_code_container_already_exists))
{
return false;
}
else
{
throw;
}
}
});
}
else
{
return pplx::task_from_result(false);
}
});
}
pplx::task<void> cloud_blob_container::delete_container_async(const access_condition& condition, const blob_request_options& options, operation_context context)
{
blob_request_options modified_options(options);
modified_options.apply_defaults(service_client().default_request_options(), blob_type::unspecified);
auto command = std::make_shared<core::storage_command<void>>(uri());
command->set_build_request(std::bind(protocol::delete_blob_container, condition, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
command->set_authentication_handler(service_client().authentication_handler());
auto properties = m_properties;
command->set_preprocess_response([properties](const web::http::http_response& response, const request_result& result, operation_context context)
{
protocol::preprocess_response_void(response, result, context);
properties->initialization();
});
return core::executor<void>::execute_async(command, modified_options, context);
}
pplx::task<bool> cloud_blob_container::delete_container_if_exists_async(const access_condition& condition, const blob_request_options& options, operation_context context)
{
blob_request_options modified_options(options);
modified_options.apply_defaults(service_client().default_request_options(), blob_type::unspecified);
auto instance = std::make_shared<cloud_blob_container>(*this);
return exists_async(true, modified_options, context).then([instance, condition, modified_options, context] (bool exists_result) -> pplx::task<bool>
{
if (exists_result)
{
return instance->delete_container_async(condition, modified_options, context).then([] (pplx::task<void> delete_task) -> bool
{
try
{
delete_task.wait();
return true;
}
catch (const storage_exception& e)
{
const azure::storage::request_result& result = e.result();
if (result.is_response_available() &&
(result.http_status_code() == web::http::status_codes::NotFound) &&
(result.extended_error().code() == protocol::error_code_container_not_found))
{
return false;
}
else
{
throw;
}
}
});
}
else
{
return pplx::task_from_result<bool>(false);
}
});
}
list_blob_item_iterator cloud_blob_container::list_blobs(const utility::string_t& prefix, bool use_flat_blob_listing, blob_listing_details::values includes, int max_results, const blob_request_options& options, operation_context context) const
{
auto instance = std::make_shared<cloud_blob_container>(*this);
return list_blob_item_iterator(
[instance, prefix, use_flat_blob_listing, includes, options, context](const continuation_token& token, size_t max_results_per_segment)
{
return instance->list_blobs_segmented(prefix, use_flat_blob_listing, includes, (int)max_results_per_segment, token, options, context);
},
max_results, 0);
}
pplx::task<list_blob_item_segment> cloud_blob_container::list_blobs_segmented_async(const utility::string_t& prefix, bool use_flat_blob_listing, blob_listing_details::values includes, int max_results, const continuation_token& token, const blob_request_options& options, operation_context context) const
{
blob_request_options modified_options(options);
modified_options.apply_defaults(service_client().default_request_options(), blob_type::unspecified);
auto container = *this;
utility::string_t delimiter;
if (!use_flat_blob_listing)
{
if ((includes & blob_listing_details::snapshots) != 0)
{
throw std::invalid_argument("includes");
}
delimiter = service_client().directory_delimiter();
}
auto command = std::make_shared<core::storage_command<list_blob_item_segment>>(uri());
command->set_build_request(std::bind(protocol::list_blobs, prefix, delimiter, includes, max_results, token, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
command->set_authentication_handler(service_client().authentication_handler());
command->set_location_mode(core::command_location_mode::primary_or_secondary, token.target_location());
command->set_preprocess_response(std::bind(protocol::preprocess_response<list_blob_item_segment>, list_blob_item_segment(), std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
command->set_postprocess_response([container, delimiter] (const web::http::http_response& response, const request_result& result, const core::ostream_descriptor&, operation_context context) -> pplx::task<list_blob_item_segment>
{
protocol::list_blobs_reader reader(response.body());
std::vector<protocol::cloud_blob_list_item> blob_items(reader.move_blob_items());
std::vector<protocol::cloud_blob_prefix_list_item> blob_prefix_items(reader.move_blob_prefix_items());
std::vector<list_blob_item> list_blob_items;
list_blob_items.reserve(blob_items.size() + blob_prefix_items.size());
for (auto iter = blob_items.begin(); iter != blob_items.end(); ++iter)
{
list_blob_items.push_back(list_blob_item(iter->move_name(), iter->move_snapshot_time(), container, iter->move_properties(), iter->move_metadata(), iter->move_copy_state()));
}
for (auto iter = blob_prefix_items.begin(); iter != blob_prefix_items.end(); ++iter)
{
list_blob_items.push_back(list_blob_item(iter->move_name(), container));
}
continuation_token next_token(reader.move_next_marker());
next_token.set_target_location(result.target_location());
return pplx::task_from_result(list_blob_item_segment(std::move(list_blob_items), std::move(next_token)));
});
return core::executor<list_blob_item_segment>::execute_async(command, modified_options, context);
}
pplx::task<void> cloud_blob_container::upload_permissions_async(const blob_container_permissions& permissions, const access_condition& condition, const blob_request_options& options, operation_context context)
{
blob_request_options modified_options(options);
modified_options.apply_defaults(service_client().default_request_options(), blob_type::unspecified);
protocol::access_policy_writer<blob_shared_access_policy> writer;
concurrency::streams::istream stream(concurrency::streams::bytestream::open_istream(writer.write(permissions.policies())));
auto properties = m_properties;
auto command = std::make_shared<core::storage_command<void>>(uri());
command->set_build_request(std::bind(protocol::set_blob_container_acl, permissions.public_access(), condition, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
command->set_authentication_handler(service_client().authentication_handler());
command->set_preprocess_response([properties] (const web::http::http_response& response, const request_result& result, operation_context context)
{
protocol::preprocess_response_void(response, result, context);
properties->update_etag_and_last_modified(protocol::blob_response_parsers::parse_blob_container_properties(response));
});
return core::istream_descriptor::create(stream).then([command, context, modified_options] (core::istream_descriptor request_body) -> pplx::task<void>
{
command->set_request_body(request_body);
return core::executor<void>::execute_async(command, modified_options, context);
});
}
pplx::task<blob_container_permissions> cloud_blob_container::download_permissions_async(const access_condition& condition, const blob_request_options& options, operation_context context)
{
blob_request_options modified_options(options);
modified_options.apply_defaults(service_client().default_request_options(), blob_type::unspecified);
auto properties = m_properties;
auto command = std::make_shared<core::storage_command<blob_container_permissions>>(uri());
command->set_build_request(std::bind(protocol::get_blob_container_acl, condition, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
command->set_authentication_handler(service_client().authentication_handler());
command->set_location_mode(core::command_location_mode::primary_or_secondary);
command->set_preprocess_response([properties] (const web::http::http_response& response, const request_result& result, operation_context context) -> blob_container_permissions
{
protocol::preprocess_response_void(response, result, context);
properties->update_etag_and_last_modified(protocol::blob_response_parsers::parse_blob_container_properties(response));
return blob_container_permissions();
});
command->set_postprocess_response([properties](const web::http::http_response& response, const request_result&, const core::ostream_descriptor&, operation_context context) -> pplx::task<blob_container_permissions>
{
blob_container_permissions permissions;
protocol::access_policy_reader<blob_shared_access_policy> reader(response.body());
permissions.set_policies(reader.move_policies());
auto public_access_type = protocol::parse_public_access_type(response);
permissions.set_public_access(public_access_type);
properties->m_public_access = public_access_type;
return pplx::task_from_result<blob_container_permissions>(permissions);
});
return core::executor<blob_container_permissions>::execute_async(command, modified_options, context);
}
pplx::task<bool> cloud_blob_container::exists_async(bool primary_only, const blob_request_options& options, operation_context context)
{
blob_request_options modified_options(options);
modified_options.apply_defaults(service_client().default_request_options(), blob_type::unspecified);
auto properties = m_properties;
auto metadata = m_metadata;
auto command = std::make_shared<core::storage_command<bool>>(uri());
command->set_build_request(std::bind(protocol::get_blob_container_properties, access_condition(), std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
command->set_authentication_handler(service_client().authentication_handler());
command->set_location_mode(primary_only ? core::command_location_mode::primary_only : core::command_location_mode::primary_or_secondary);
command->set_preprocess_response([properties, metadata] (const web::http::http_response& response, const request_result& result, operation_context context) -> bool
{
if (response.status_code() == web::http::status_codes::NotFound)
{
return false;
}
protocol::preprocess_response_void(response, result, context);
*properties = protocol::blob_response_parsers::parse_blob_container_properties(response);
*metadata = protocol::parse_metadata(response);
return true;
});
return core::executor<bool>::execute_async(command, modified_options, context);
}
}} // namespace azure::storage
| 56.948339 | 307 | 0.700965 | [
"vector"
] |
a830bcc9a380d73288aeead4f00e1351e2980a92 | 2,465 | cpp | C++ | examples/core/vsgarrays/vsgarrays.cpp | anormann1974/vsgExamples | 6c06316a41f63bb283f99a3c7a706360499e28fe | [
"MIT"
] | 89 | 2018-11-30T17:06:36.000Z | 2022-01-22T13:40:05.000Z | examples/core/vsgarrays/vsgarrays.cpp | anormann1974/vsgExamples | 6c06316a41f63bb283f99a3c7a706360499e28fe | [
"MIT"
] | 36 | 2019-05-18T01:36:10.000Z | 2022-03-18T14:43:43.000Z | examples/core/vsgarrays/vsgarrays.cpp | anormann1974/vsgExamples | 6c06316a41f63bb283f99a3c7a706360499e28fe | [
"MIT"
] | 30 | 2018-12-08T12:03:32.000Z | 2022-01-14T01:16:30.000Z | #include <vsg/core/Array.h>
#include <vsg/core/Auxiliary.h>
#include <vsg/core/Object.h>
#include <vsg/core/Visitor.h>
#include <vsg/io/stream.h>
#include <algorithm>
#include <array>
#include <iostream>
#include <mutex>
struct Unique
{
using StringIndexMap = std::map<std::string, std::size_t>;
using IndexStringMap = std::map<std::size_t, std::string>;
std::mutex _mutex;
StringIndexMap _stringIndexMap;
IndexStringMap _indexStringMap;
std::size_t getIndex(const std::string& name)
{
std::lock_guard<std::mutex> guard(_mutex);
StringIndexMap::iterator itr = _stringIndexMap.find(name);
if (itr != _stringIndexMap.end()) return itr->second;
std::size_t s = _stringIndexMap.size();
_stringIndexMap[name] = s;
_indexStringMap[s] = name;
return s;
}
std::string getName(std::size_t index)
{
std::lock_guard<std::mutex> guard(_mutex);
IndexStringMap::iterator itr = _indexStringMap.find(index);
if (itr != _indexStringMap.end()) return itr->second;
return std::string();
}
};
int main(int /*argc*/, char** /*argv*/)
{
auto floats = vsg::floatArray::create(10);
std::cout << "floats.size() = " << floats->size() << std::endl;
float value = 0.0f;
std::for_each(floats->begin(), floats->end(), [&value](float& v) {
v = value++;
});
std::for_each(floats->begin(), floats->end(), [](float& v) {
std::cout << " v[] = " << v << std::endl;
});
auto colours = vsg::vec4Array::create(40);
vsg::vec4 colour(0.25, 0.5, 0.75, 1.0);
for (std::size_t i = 0; i < colours->size(); ++i)
{
(*colours)[i] = colour;
colour = vsg::vec4(colour.g, colour.b, colour.a, colour.r);
}
std::for_each(colours->begin(), colours->end(), [](vsg::vec4& c) {
std::cout << " c[] = " << c << std::endl;
});
auto texCoords = vsg::vec2Array::create(
{{1.0f, 2.0f},
{3.0f, 4.0f},
{}});
std::cout << "texCoords.size() = " << texCoords->size() << std::endl;
for (auto p : *texCoords)
{
std::cout << " tc " << p.x << ", " << p.y << std::endl;
}
auto col = vsg::vec4Array::create({{}});
std::cout << "col.size() = " << col->size() << std::endl;
for (auto c : *col)
{
std::cout << " colour " << c.r << ", " << c.g << ", " << c.b << ", " << c.a << std::endl;
}
return 0;
}
| 27.388889 | 100 | 0.542394 | [
"object"
] |
a83196e0a457f1f97328da6800a58a7054e46745 | 417 | cpp | C++ | TrainingWithBook/GRAPH/Training on Codeforces/129B.cpp | andzh1/Competitive-programming | babb9494e03fe0feb2130e50887996d0ffc92c4e | [
"MIT"
] | null | null | null | TrainingWithBook/GRAPH/Training on Codeforces/129B.cpp | andzh1/Competitive-programming | babb9494e03fe0feb2130e50887996d0ffc92c4e | [
"MIT"
] | null | null | null | TrainingWithBook/GRAPH/Training on Codeforces/129B.cpp | andzh1/Competitive-programming | babb9494e03fe0feb2130e50887996d0ffc92c4e | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
//https://codeforces.com/problemset/problem/129/B
int main(){
int TT;
cin >> TT;
for(int UU = 0; UU < TT; UU++){
int n, m;
cin >> n >> m;
vector <int> adj[n];
int x, y;
for(int i = 0; i < m; i++){
cin >> x >> y;
adj[x-1].push_back(y-1);
adj[y-1].push_back(x-1);
}
}
}
| 19.857143 | 49 | 0.431655 | [
"vector"
] |
a835e582cc5c959fd2f5b65a74153588cdb16645 | 6,181 | cpp | C++ | aws-cpp-sdk-devicefarm/source/model/Device.cpp | ambasta/aws-sdk-cpp | c81192e00b572b76d175d84dff77185bd17ae1ac | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-devicefarm/source/model/Device.cpp | ambasta/aws-sdk-cpp | c81192e00b572b76d175d84dff77185bd17ae1ac | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-devicefarm/source/model/Device.cpp | ambasta/aws-sdk-cpp | c81192e00b572b76d175d84dff77185bd17ae1ac | [
"Apache-2.0"
] | null | null | null | ๏ปฟ/*
* 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.
*/
#include <aws/devicefarm/model/Device.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace DeviceFarm
{
namespace Model
{
Device::Device() :
m_arnHasBeenSet(false),
m_nameHasBeenSet(false),
m_manufacturerHasBeenSet(false),
m_modelHasBeenSet(false),
m_formFactorHasBeenSet(false),
m_platformHasBeenSet(false),
m_osHasBeenSet(false),
m_cpuHasBeenSet(false),
m_resolutionHasBeenSet(false),
m_heapSize(0),
m_heapSizeHasBeenSet(false),
m_memory(0),
m_memoryHasBeenSet(false),
m_imageHasBeenSet(false),
m_carrierHasBeenSet(false),
m_radioHasBeenSet(false),
m_remoteAccessEnabled(false),
m_remoteAccessEnabledHasBeenSet(false),
m_fleetTypeHasBeenSet(false),
m_fleetNameHasBeenSet(false)
{
}
Device::Device(const JsonValue& jsonValue) :
m_arnHasBeenSet(false),
m_nameHasBeenSet(false),
m_manufacturerHasBeenSet(false),
m_modelHasBeenSet(false),
m_formFactorHasBeenSet(false),
m_platformHasBeenSet(false),
m_osHasBeenSet(false),
m_cpuHasBeenSet(false),
m_resolutionHasBeenSet(false),
m_heapSize(0),
m_heapSizeHasBeenSet(false),
m_memory(0),
m_memoryHasBeenSet(false),
m_imageHasBeenSet(false),
m_carrierHasBeenSet(false),
m_radioHasBeenSet(false),
m_remoteAccessEnabled(false),
m_remoteAccessEnabledHasBeenSet(false),
m_fleetTypeHasBeenSet(false),
m_fleetNameHasBeenSet(false)
{
*this = jsonValue;
}
Device& Device::operator =(const JsonValue& jsonValue)
{
if(jsonValue.ValueExists("arn"))
{
m_arn = jsonValue.GetString("arn");
m_arnHasBeenSet = true;
}
if(jsonValue.ValueExists("name"))
{
m_name = jsonValue.GetString("name");
m_nameHasBeenSet = true;
}
if(jsonValue.ValueExists("manufacturer"))
{
m_manufacturer = jsonValue.GetString("manufacturer");
m_manufacturerHasBeenSet = true;
}
if(jsonValue.ValueExists("model"))
{
m_model = jsonValue.GetString("model");
m_modelHasBeenSet = true;
}
if(jsonValue.ValueExists("formFactor"))
{
m_formFactor = DeviceFormFactorMapper::GetDeviceFormFactorForName(jsonValue.GetString("formFactor"));
m_formFactorHasBeenSet = true;
}
if(jsonValue.ValueExists("platform"))
{
m_platform = DevicePlatformMapper::GetDevicePlatformForName(jsonValue.GetString("platform"));
m_platformHasBeenSet = true;
}
if(jsonValue.ValueExists("os"))
{
m_os = jsonValue.GetString("os");
m_osHasBeenSet = true;
}
if(jsonValue.ValueExists("cpu"))
{
m_cpu = jsonValue.GetObject("cpu");
m_cpuHasBeenSet = true;
}
if(jsonValue.ValueExists("resolution"))
{
m_resolution = jsonValue.GetObject("resolution");
m_resolutionHasBeenSet = true;
}
if(jsonValue.ValueExists("heapSize"))
{
m_heapSize = jsonValue.GetInt64("heapSize");
m_heapSizeHasBeenSet = true;
}
if(jsonValue.ValueExists("memory"))
{
m_memory = jsonValue.GetInt64("memory");
m_memoryHasBeenSet = true;
}
if(jsonValue.ValueExists("image"))
{
m_image = jsonValue.GetString("image");
m_imageHasBeenSet = true;
}
if(jsonValue.ValueExists("carrier"))
{
m_carrier = jsonValue.GetString("carrier");
m_carrierHasBeenSet = true;
}
if(jsonValue.ValueExists("radio"))
{
m_radio = jsonValue.GetString("radio");
m_radioHasBeenSet = true;
}
if(jsonValue.ValueExists("remoteAccessEnabled"))
{
m_remoteAccessEnabled = jsonValue.GetBool("remoteAccessEnabled");
m_remoteAccessEnabledHasBeenSet = true;
}
if(jsonValue.ValueExists("fleetType"))
{
m_fleetType = jsonValue.GetString("fleetType");
m_fleetTypeHasBeenSet = true;
}
if(jsonValue.ValueExists("fleetName"))
{
m_fleetName = jsonValue.GetString("fleetName");
m_fleetNameHasBeenSet = true;
}
return *this;
}
JsonValue Device::Jsonize() const
{
JsonValue payload;
if(m_arnHasBeenSet)
{
payload.WithString("arn", m_arn);
}
if(m_nameHasBeenSet)
{
payload.WithString("name", m_name);
}
if(m_manufacturerHasBeenSet)
{
payload.WithString("manufacturer", m_manufacturer);
}
if(m_modelHasBeenSet)
{
payload.WithString("model", m_model);
}
if(m_formFactorHasBeenSet)
{
payload.WithString("formFactor", DeviceFormFactorMapper::GetNameForDeviceFormFactor(m_formFactor));
}
if(m_platformHasBeenSet)
{
payload.WithString("platform", DevicePlatformMapper::GetNameForDevicePlatform(m_platform));
}
if(m_osHasBeenSet)
{
payload.WithString("os", m_os);
}
if(m_cpuHasBeenSet)
{
payload.WithObject("cpu", m_cpu.Jsonize());
}
if(m_resolutionHasBeenSet)
{
payload.WithObject("resolution", m_resolution.Jsonize());
}
if(m_heapSizeHasBeenSet)
{
payload.WithInt64("heapSize", m_heapSize);
}
if(m_memoryHasBeenSet)
{
payload.WithInt64("memory", m_memory);
}
if(m_imageHasBeenSet)
{
payload.WithString("image", m_image);
}
if(m_carrierHasBeenSet)
{
payload.WithString("carrier", m_carrier);
}
if(m_radioHasBeenSet)
{
payload.WithString("radio", m_radio);
}
if(m_remoteAccessEnabledHasBeenSet)
{
payload.WithBool("remoteAccessEnabled", m_remoteAccessEnabled);
}
if(m_fleetTypeHasBeenSet)
{
payload.WithString("fleetType", m_fleetType);
}
if(m_fleetNameHasBeenSet)
{
payload.WithString("fleetName", m_fleetName);
}
return payload;
}
} // namespace Model
} // namespace DeviceFarm
} // namespace Aws | 19.810897 | 105 | 0.704093 | [
"model"
] |
a836ce7189aac656f7b55fe8effedc2ac32deca3 | 28,704 | cpp | C++ | src/types/Mesh.cpp | kant/hilma | 13592d7705bd84624329889fa6c82815c007cc68 | [
"BSD-3-Clause"
] | null | null | null | src/types/Mesh.cpp | kant/hilma | 13592d7705bd84624329889fa6c82815c007cc68 | [
"BSD-3-Clause"
] | null | null | null | src/types/Mesh.cpp | kant/hilma | 13592d7705bd84624329889fa6c82815c007cc68 | [
"BSD-3-Clause"
] | null | null | null | #include <iostream>
#include <map>
#include "hilma/types/Mesh.h"
#include "hilma/text.h"
using namespace hilma;
Mesh::Mesh() : name("undefined"), faceMode(TRIANGLES), edgeMode(LINES) {
}
Mesh::Mesh(const std::string& _name) : name(_name), faceMode(TRIANGLES), edgeMode(LINES) {
}
Mesh::Mesh(const Mesh& _mother): name(_mother.name), faceMode(_mother.faceMode), edgeMode(_mother.edgeMode) {
append(_mother);
}
Mesh::~Mesh() {
}
void Mesh::clear() {
// Vertex data
if (!vertices.empty()) vertices.clear();
if (!colors.empty()) colors.clear();
if (!normals.empty()) normals.clear();
if (!texcoords.empty()) texcoords.clear();
if (!tangents.empty()) tangents.clear();
// Face data
if (!faceIndices.empty()) faceIndices.clear();
if (!materialsByName.empty()) materialsByName.clear();
if (!materialsByIndices.empty()) materialsByIndices.clear();
// Edges data
if (!edgeIndices.empty()) edgeIndices.clear();
}
void Mesh::append(const Mesh& _mesh) {
int vertexIndexOffset = (int)vertices.size();
// Vertex Data
if (_mesh.haveTexCoords()) {
if (haveVertices() && !haveTexCoords() )
std::cout << "Skipping appending TexCoords because destination don't have them" << std::endl;
else
texcoords.insert(texcoords.end(), _mesh.texcoords.begin(), _mesh.texcoords.end());
}
if (_mesh.haveColors()) {
if (haveVertices() && !haveColors() )
std::cout << "Skipping appending Colors because destination don't have them" << std::endl;
else
colors.insert(colors.end(),_mesh.colors.begin(),_mesh.colors.end());
}
if (_mesh.haveNormals()) {
if (haveVertices() && !haveNormals() )
std::cout << "Skipping appending Normals because destination don't have them" << std::endl;
else
normals.insert(normals.end(),_mesh.normals.begin(),_mesh.normals.end());
}
if (_mesh.haveVertices())
vertices.insert(vertices.end(), _mesh.vertices.begin(), _mesh.vertices.end());
// Face Data
if (_mesh.getFaceType() != faceMode) {
std::cout << "INCOMPATIBLE FACEMODES" << std::endl;
return;
}
if (_mesh.haveFaceIndices()) {
std::string lastMaterialName = "";
for (size_t i = 0; i < _mesh.faceIndices.size(); i++) {
if (_mesh.haveMaterials()) {
MaterialConstPtr material = _mesh.getMaterialForFaceIndex(i);
if (material != NULL) {
if (material->name != lastMaterialName) {
addMaterial( *material );
lastMaterialName = material->name;
}
}
}
addFaceIndex(vertexIndexOffset + _mesh.faceIndices[i]);
}
}
// Edge Data
if (_mesh.getEdgeType() != edgeMode) {
std::cout << "INCOMPATIBLE FACEMODES" << std::endl;
return;
}
if (_mesh.haveEdgeIndices())
for (size_t i = 0; i < _mesh.edgeIndices.size(); i++)
addEdgeIndex(vertexIndexOffset + _mesh.edgeIndices[i]);
}
// Vertices
//
void Mesh::addVertex(const glm::vec3& _point) {
vertices.push_back(_point);
}
void Mesh::addVertex(float _x, float _y, float _z) {
addVertex( glm::vec3(_x, _y, _z) );
}
void Mesh::addVertex(const float* _data, int _n) {
if (_n == 3)
addVertex(_data[0], _data[1], _data[2]);
else if (_n == 2)
addVertex(_data[0], _data[1], 0.0);
}
void Mesh::addVertices(const float* _data, int _m, int _n) {
for (int i = 0; i < _m; i++)
addVertex(&_data[i*_n], _n);
}
// Color
//
void Mesh::setColor(const glm::vec4& _color) {
colors.clear();
for (size_t i = 0; i < vertices.size(); i++)
colors.push_back(_color);
}
void Mesh::setColor(const float* _data, int _n) {
if (_n == 4)
setColor(_data[0], _data[1], _data[2], _data[3]);
else if (_n == 3)
setColor(_data[0], _data[1], _data[2], 1.0);
}
void Mesh::setColor(float _r, float _g, float _b, float _a) {
setColor(glm::vec4(_r, _g, _b, _a));
}
void Mesh::addColor(const glm::vec4& _color) {
colors.push_back(_color);
}
void Mesh::addColor(const float* _data, int _n) {
if (_n == 4)
addColor(_data[0], _data[1], _data[2], _data[3]);
else if (_n == 3)
addColor(_data[0], _data[1], _data[2], 1.0);
}
void Mesh::addColor(float _r, float _g, float _b, float _a) {
addColor(glm::vec4(_r, _g, _b, _a));
}
void Mesh::addColors(const float* _data, int _m, int _n) {
for (int i = 0; i < _m; i++)
addColor(&_data[i*_n], _n);
}
// Normals
//
void Mesh::addNormal(const glm::vec3& _normal) {
normals.push_back(_normal);
}
void Mesh::addNormal(const float* _data, int _n) {
if (_n != 3) return;
addNormal(_data[0], _data[1], _data[2]);
}
void Mesh::addNormal(float _nX, float _nY, float _nZ) {
addNormal( glm::vec3(_nX, _nY, _nZ) );
}
void Mesh::addNormals(const float* _data, int _m, int _n) {
for (int i = 0; i < _m; i++)
addNormal(&_data[i*_n], _n);
}
// TexCoords
//
void Mesh::addTexCoord(const glm::vec2& _uv) {
texcoords.push_back(_uv);
}
void Mesh::addTexCoord(const float* _data, int _n) {
if (_n == 2)
addTexCoord(_data[0], _data[1]);
}
void Mesh::addTexCoord(float _tX, float _tY) {
addTexCoord( glm::vec2(_tX, _tY) );
}
void Mesh::addTexCoords(const float* _data, int _m, int _n) {
for (int i = 0; i < _m; i++)
addTexCoord(&_data[i*_n], _n);
}
bool Mesh::computeNormals() {
if (getFaceType() != TRIANGLES)
return false;
//The number of the vertices
size_t nV = vertices.size();
//The number of the triangles
size_t nT = faceIndices.size() / 3;
std::vector<glm::vec3> norm( nV ); //Array for the normals
//Scan all the triangles. For each triangle add its
//normal to norm's vectors of triangle's vertices
for (size_t t=0; t < nT; t++) {
//Get indices of the triangle t
INDEX_TYPE i1 = faceIndices[ 3 * t ];
INDEX_TYPE i2 = faceIndices[ 3 * t + 1 ];
INDEX_TYPE i3 = faceIndices[ 3 * t + 2 ];
//Get vertices of the triangle
const glm::vec3 &v1 = vertices[ i1 ];
const glm::vec3 &v2 = vertices[ i2 ];
const glm::vec3 &v3 = vertices[ i3 ];
//Compute the triangle's normal
glm::vec3 dir = glm::normalize(glm::cross(v2-v1,v3-v1));
//Accumulate it to norm array for i1, i2, i3
norm[ i1 ] += dir;
norm[ i2 ] += dir;
norm[ i3 ] += dir;
}
//Normalize the normal's length and add it.
normals.clear();
for (size_t i=0; i < nV; i++)
addNormal( glm::normalize(norm[i]) );
return true;
}
void Mesh::invertWindingOrder() {
if ( getFaceType() == TRIANGLES) {
int tmp;
for (size_t i = 0; i < faceIndices.size(); i += 3) {
tmp = faceIndices[i+1];
faceIndices[i+1] = faceIndices[i+2];
faceIndices[i+2] = tmp;
}
}
}
void Mesh::invertNormals() {
for (std::vector<glm::vec3>::iterator it = normals.begin(); it != normals.end(); ++it)
*it *= -1.0f;
}
void Mesh::flatNormals() {
if ( getFaceType() == TRIANGLES) {
// get copy original mesh data
size_t numIndices = faceIndices.size();
std::vector<INDEX_TYPE> indices = faceIndices;
std::vector<glm::vec3> verts = vertices;
std::vector<glm::vec4> colors = colors;
std::vector<glm::vec2> texCoords = texcoords;
// remove all data to start from scratch
clear();
// add mesh data back, duplicating vertices and recalculating normals
glm::vec3 normal;
for (size_t i = 0; i < numIndices; i++) {
size_t indexCurr = indices[i];
if (i % 3 == 0) {
INDEX_TYPE indexNext1 = indices[i + 1];
INDEX_TYPE indexNext2 = indices[i + 2];
glm::vec3 e1 = verts[indexCurr] - verts[indexNext1];
glm::vec3 e2 = verts[indexNext2] - verts[indexNext1];
normal = glm::normalize(glm::cross(e1, e2));
}
addFaceIndex(i);
addNormal(normal);
if (indexCurr < texCoords.size()) addTexCoord(texCoords[indexCurr]);
if (indexCurr < verts.size()) addVertex(verts[indexCurr]);
if (indexCurr < colors.size()) addColor(colors[indexCurr]);
}
}
}
void Mesh::smoothNormals(float _angle) {
std::vector<Triangle> triangles = getTriangles();
std::vector<glm::vec3> verts;
for (size_t i = 0; i < triangles.size(); i++)
for (size_t j = 0; j < 3; j++)
verts.push_back( triangles[i][j] );
std::map<int, int> removeIds;
float epsilon = .01f;
for (size_t i = 0; i < verts.size()-1; i++) {
for (size_t j = i+1; j < verts.size(); j++) {
if (i != j) {
const glm::vec3& v1 = verts[i];
const glm::vec3& v2 = verts[j];
if ( glm::distance(v1, v2) <= epsilon ) {
// average the location //
verts[i] = (v1+v2)/2.f;
verts[j] = verts[i];
removeIds[j] = 1;
}
}
}
}
std::map<std::string, std::vector<int> > vertHash;
std::string xStr, yStr, zStr;
for (size_t i = 0; i < verts.size(); i++ ) {
xStr = "x" + toString(verts[i].x == -0 ? 0: verts[i].x);
yStr = "y" + toString(verts[i].y == -0 ? 0: verts[i].y);
zStr = "z" + toString(verts[i].z == -0 ? 0: verts[i].z);
std::string vstring = xStr+yStr+zStr;
if (vertHash.find(vstring) == vertHash.end())
for (size_t j = 0; j < triangles.size(); j++)
for (size_t k = 0; k < 3; k++)
if (verts[i].x == triangles[j][k].x)
if (verts[i].y == triangles[j][k].y)
if (verts[i].z == triangles[j][k].z)
vertHash[vstring].push_back( j );
}
glm::vec3 vert;
glm::vec3 normal;
float angleCos = cos(glm::radians(_angle));
float numNormals = 0.0f;
for (size_t j = 0; j < triangles.size(); j++) {
for (size_t k = 0; k < 3; k++) {
vert = triangles[j][k];
xStr = "x" + toString(vert.x==-0?0:vert.x);
yStr = "y" + toString(vert.y==-0?0:vert.y);
zStr = "z" + toString(vert.z==-0?0:vert.z);
std::string vstring = xStr+yStr+zStr;
numNormals=0;
normal = {0.f,0.f,0.f};
if (vertHash.find(vstring) != vertHash.end()) {
for (size_t i = 0; i < vertHash[vstring].size(); i++) {
glm::vec3 f1 = triangles[j].getNormal();
glm::vec3 f2 = triangles[vertHash[vstring][i]].getNormal();
if (glm::dot(f1, f2) >= angleCos ) {
normal += f2;
numNormals+=1.f;
}
}
//normal /= (float)vertHash[vstring].size();
normal /= numNormals;
triangles[j].setNormal(k, normal);
}
}
}
clear();
addTriangles( triangles.data(), triangles.size() );
}
void Mesh::addTangent(const glm::vec4 &_tangent) {
tangents.push_back(_tangent);
}
// http://www.terathon.com/code/tangent.html
bool Mesh::computeTangents() {
//The number of the vertices
size_t nV = vertices.size();
if (texcoords.size() != nV ||
normals.size() != nV ||
getFaceType() != TRIANGLES)
return false;
//The number of the triangles
size_t nT = faceIndices.size() / 3;
std::vector<glm::vec3> tan1( nV );
std::vector<glm::vec3> tan2( nV );
//Scan all the triangles. For each triangle add its
//normal to norm's vectors of triangle's vertices
for (size_t t = 0; t < nT; t++) {
//Get indices of the triangle t
INDEX_TYPE i1 = faceIndices[ 3 * t ];
INDEX_TYPE i2 = faceIndices[ 3 * t + 1 ];
INDEX_TYPE i3 = faceIndices[ 3 * t + 2 ];
//Get vertices of the triangle
const glm::vec3 &v1 = vertices[ i1 ];
const glm::vec3 &v2 = vertices[ i2 ];
const glm::vec3 &v3 = vertices[ i3 ];
const glm::vec2 &w1 = texcoords[i1];
const glm::vec2 &w2 = texcoords[i2];
const glm::vec2 &w3 = texcoords[i3];
float x1 = v2.x - v1.x;
float x2 = v3.x - v1.x;
float y1 = v2.y - v1.y;
float y2 = v3.y - v1.y;
float z1 = v2.z - v1.z;
float z2 = v3.z - v1.z;
float s1 = w2.x - w1.x;
float s2 = w3.x - w1.x;
float t1 = w2.y - w1.y;
float t2 = w3.y - w1.y;
float r = 1.0f / (s1 * t2 - s2 * t1);
glm::vec3 sdir( (t2 * x1 - t1 * x2) * r,
(t2 * y1 - t1 * y2) * r,
(t2 * z1 - t1 * z2) * r);
glm::vec3 tdir( (s1 * x2 - s2 * x1) * r,
(s1 * y2 - s2 * y1) * r,
(s1 * z2 - s2 * z1) * r);
tan1[i1] += sdir;
tan1[i2] += sdir;
tan1[i3] += sdir;
tan2[i1] += tdir;
tan2[i2] += tdir;
tan2[i3] += tdir;
}
//Normalize the normal's length and add it.
tangents.clear();
for (size_t i = 0; i < nV; i++) {
const glm::vec3 &n = normals[i];
const glm::vec3 &t = tan1[i];
// Gram-Schmidt orthogonalize
glm::vec3 tangent = t - n * glm::dot(n, t);
// Calculate handedness
float hardedness = (glm::dot( glm::cross(n, t), tan2[i]) < 0.0f) ? -1.0f : 1.0f;
tangents.push_back(glm::vec4(tangent, hardedness));
}
return true;
}
// Indices
//
void Mesh::addIndices(const INDEX_TYPE* _data, int _m, int _n) {
if (_n == 2) {
for (int i = 0; i < _m; i++)
addEdgeIndices(_data[i*_n], _data[i*_n+1]);
}
else if (_n == 3) {
for (int i = 0; i < _m; i++)
addTriangleIndices(_data[i*_n], _data[i*_n+1], _data[i*_n+2]);
}
else if (_n == 4) {
for (int i = 0; i < _m; i++)
addQuadIndices(_data[i*_n], _data[i*_n+1], _data[i*_n+2], _data[i*_n+3]);
}
}
// FACE GROUPING
//
void Mesh::setFaceType(FaceType _mode, bool _compute) {
faceMode = _mode;
if (!haveVertices())
return;
if (_compute) {
faceIndices.clear();
if (_mode == TRIANGLES) {
for (size_t j = 0; j < vertices.size(); j += 3)
addTriangleIndices(j, j + 1, j + 2);
}
}
}
void Mesh::addFaceIndex(INDEX_TYPE _i) {
faceIndices.push_back(_i);
}
size_t Mesh::getFaceIndex(size_t _index) {
return faceIndices[_index];
}
void Mesh::addFaceIndices(const INDEX_TYPE* _array1D, int _n) {
faceIndices.insert(faceIndices.end(),_array1D,_array1D+_n);
}
void Mesh::addTriangleIndices(INDEX_TYPE _index1, INDEX_TYPE _index2, INDEX_TYPE _index3) {
addFaceIndex(_index1);
addFaceIndex(_index2);
addFaceIndex(_index3);
}
void Mesh::addTriangle(const Triangle& _tri) {
INDEX_TYPE index = vertices.size();
addVertex(_tri[0]);
addVertex(_tri[1]);
addVertex(_tri[2]);
if (_tri.haveColors()) {
addColor(_tri.getColor(0));
addColor(_tri.getColor(1));
addColor(_tri.getColor(2));
}
if (_tri.haveNormals()) {
addNormal(_tri.getNormal(0));
addNormal(_tri.getNormal(1));
addNormal(_tri.getNormal(2));
}
else {
addNormal(_tri.getNormal());
addNormal(_tri.getNormal());
addNormal(_tri.getNormal());
}
if (_tri.haveTexCoords()) {
addTexCoord(_tri.getTexCoord(0));
addTexCoord(_tri.getTexCoord(1));
addTexCoord(_tri.getTexCoord(2));
}
addTriangleIndices(index, index+1, index+2);
}
void Mesh::addQuadIndices(INDEX_TYPE _index1, INDEX_TYPE _index2, INDEX_TYPE _index3, INDEX_TYPE _index4) {
addFaceIndex(_index1);
addFaceIndex(_index2);
addFaceIndex(_index3);
addFaceIndex(_index4);
}
std::vector<glm::ivec3> Mesh::getTrianglesIndices() const {
std::vector<glm::ivec3> triangles;
if (getFaceType() == TRIANGLES) {
if (haveFaceIndices()) {
for (size_t j = 0; j < faceIndices.size(); j += 3) {
glm::ivec3 tri;
for (int k = 0; k < 3; k++)
tri[k] = faceIndices[j+k];
triangles.push_back(tri);
}
}
else {
for (size_t j = 0; j < vertices.size(); j += 3) {
glm::ivec3 tri;
for (int k = 0; k < 3; k++)
tri[k] = j+k;
triangles.push_back(tri);
}
}
}
else if (getFaceType() == TRIANGLE_STRIP) {
if (faceIndices.size() > 2) {
int a = int(faceIndices[0]);
int b = int(faceIndices[1]);
int c;
bool CCW = true;
for (size_t j = 2; j < faceIndices.size(); j++) {
c = int(faceIndices[j]);
// Account for degenerate triangles
if (a != b && b != c && c != a) {
if (CCW) triangles.push_back(glm::ivec3(a, c, b));
else triangles.push_back(glm::ivec3(a, b, c));
}
a = b;
b = c;
CCW = !CCW;
}
}
else {
int a = 0;
int b = 1;
bool CCW = true;
for (size_t c = 2; c < vertices.size(); c++) {
if (CCW) triangles.push_back(glm::ivec3(a, c, b));
else triangles.push_back(glm::ivec3(a, b, c));
a = b;
b = c;
CCW = !CCW;
}
}
}
else if (getFaceType() == QUAD) {
if (haveFaceIndices()) {
for (size_t j = 0; j < faceIndices.size(); j += 4) {
triangles.push_back(glm::ivec3(faceIndices[j], faceIndices[j+2], faceIndices[j+1]));
triangles.push_back(glm::ivec3(faceIndices[j+2], faceIndices[j], faceIndices[j+3]));
}
}
else {
for (size_t j = 0; j < vertices.size(); j += 4) {
std::cout << "j " << j << std::endl;
triangles.push_back(glm::ivec3(j, j+2, j+1));
triangles.push_back(glm::ivec3(j+2, j, j+3));
}
}
}
else {
// TODO
//
std::cout << "ERROR: getTriangles(): Mesh only add TRIANGLES for NOW !!" << std::endl;
}
return triangles;
}
void Mesh::addTriangles(const Triangle* _array1D, int _n) {
for (int i = 0; i < _n; i++)
addTriangle(_array1D[i]);
}
std::vector<Triangle> Mesh::getTriangles() const {
std::vector<glm::ivec3> triIndices = getTrianglesIndices();
std::vector<Triangle> triangles;
int t = 0;
for (std::vector<glm::ivec3>::iterator it = triIndices.begin(); it != triIndices.end(); ++it) {
Triangle tri = Triangle(vertices[it->x], vertices[it->y], vertices[it->z]);
if (haveColors()) tri.setColors(colors[it->x], colors[it->y], colors[it->z]);
if (haveNormals()) tri.setNormals(normals[it->x], normals[it->y], normals[it->z]);
if (haveTexCoords()) tri.setTexCoords(texcoords[it->x], texcoords[it->y], texcoords[it->z]);
if (haveTangents()) tri.setTangents(tangents[it->x], tangents[it->y], tangents[it->z]);
if (haveMaterials()) tri.material = getMaterialForFaceIndex(it->x);
triangles.push_back( tri );
t++;
}
return triangles;
}
// EDGE GROUPING
//
void Mesh::addEdgeIndex(INDEX_TYPE _i) {
edgeIndices.push_back(_i);
}
void Mesh::addEdgeIndices(const INDEX_TYPE* _array1D, int _n) {
edgeIndices.insert(edgeIndices.end(), _array1D, _array1D+_n);
}
void Mesh::addEdgeIndices( INDEX_TYPE _index1, INDEX_TYPE _index2 ) {
addEdgeIndex(_index1);
addEdgeIndex(_index2);
}
void Mesh::addEdge(const Line& _line) {
// TODO
INDEX_TYPE index = vertices.size();
addVertex(_line[0]);
addVertex(_line[1]);
addEdgeIndices( index+0, index+1);
}
void Mesh::addEdges(const Line* _array1D, int _n) {
for (int i = 0; i < _n; i++)
addEdge(_array1D[i]);
}
void Mesh::setEdgeType(EdgeType _mode, bool _compute) {
edgeMode = _mode;
if (!haveVertices())
return;
if (_compute) {
edgeIndices.clear();
if (_mode == LINES) {
for (size_t j = 0; j < vertices.size(); j += 2)
addEdgeIndices(j, j + 1);
}
}
}
std::vector<glm::ivec2> Mesh::getLinesIndices() const {
std::vector<glm::ivec2> lines;
if (getEdgeType() == LINES) {
if (haveFaceIndices()) {
for (size_t j = 0; j < edgeIndices.size(); j += 2) {
glm::ivec2 line;
for (int k = 0; k < 2; k++)
line[k] = edgeIndices[j+k];
lines.push_back(line);
}
}
else {
for (size_t j = 0; j < vertices.size(); j += 2) {
glm::ivec2 line;
for (int k = 0; k < 2; k++)
line[k] = j+k;
lines.push_back(line);
}
}
}
return lines;
}
std::vector<Line> Mesh::getLinesEdges() const {
std::vector<glm::ivec2> linesIndices;
std::vector<Line> lines;
for (std::vector<glm::ivec2>::iterator it = linesIndices.begin(); it != linesIndices.end(); ++it)
lines.push_back( Line(vertices[it->x], vertices[it->y]) );
return lines;
}
void Mesh::mergeDuplicateVertices() {
std::vector<glm::vec3> verts = vertices;
std::vector<INDEX_TYPE> indices = faceIndices;
//get indexes to share single point - TODO: try j < i
for (INDEX_TYPE i = 0; i < indices.size(); i++) {
for (INDEX_TYPE j = 0; j < indices.size(); j++ ) {
if (i==j) continue;
INDEX_TYPE i1 = indices[i];
INDEX_TYPE i2 = indices[j];
const glm::vec3& v1 = verts[ i1 ];
const glm::vec3& v2 = verts[ i2 ];
if ( v1 == v2 && i1 != i2) {
indices[j] = i1;
break;
}
}
}
//indices array now has list of unique points we need
//but we need to delete the old points we're not using and that means the index values will change
//so we are going to create a new list of points and new indexes - we will use a map to map old index values to the new ones
std::vector<glm::vec3> newPoints;
std::vector<INDEX_TYPE> newIndexes;
std::map<INDEX_TYPE, bool> ptCreated;
std::map<INDEX_TYPE, INDEX_TYPE> oldIndexNewIndex;
std::vector<glm::vec4> newColors;
std::vector<glm::vec4>& colors = colors;
std::vector<glm::vec2> newTCoords;
std::vector<glm::vec2>& tcoords = texcoords;
std::vector<glm::vec3> newNormals;
std::vector<glm::vec3>& normals = normals;
for (INDEX_TYPE i = 0; i < indices.size(); i++)
ptCreated[i] = false;
for (INDEX_TYPE i = 0; i < indices.size(); i++){
INDEX_TYPE index = indices[i];
const glm::vec3& p = verts[ index ];
if ( ptCreated[index] == false ){
oldIndexNewIndex[index] = newPoints.size();
newPoints.push_back( p );
if (haveColors())
newColors.push_back(colors[index]);
if (haveTexCoords())
newTCoords.push_back(tcoords[index]);
if (haveNormals())
newNormals.push_back(normals[index]);
ptCreated[index] = true;
}
//ofLogNotice("ofMesh") << "[" << i << "]: old " << index << " --> " << oldIndexNewIndex[index];
newIndexes.push_back( oldIndexNewIndex[index] );
}
verts.clear();
verts = newPoints;
indices.clear();
indices = newIndexes;
clearFaceIndices();
addFaceIndices(&indices[0], indices.size());
clearVertices();
addVertices( &verts[0].x, verts.size(), 3);
if (haveColors()) {
clearColors();
addColors( &newColors[0].x, newColors.size(), 4);
}
if (haveTexCoords()) {
clearTexCoords();
addTexCoords( &newTCoords[0].x, newTCoords.size(), 2);
}
if (haveNormals()) {
clearNormals();
addNormals( &newNormals[0].x, newNormals.size(), 3);
}
}
void Mesh::setMaterial(const Material& _material) {
materialsByName.clear();
materialsByIndices.clear();
addMaterial(_material, 0);
}
void Mesh::addMaterial(const Material& _material, int _index) {
if (_index < 0)
_index = faceIndices.size();
if (materialsByName.find(_material.name) == materialsByName.end())
materialsByName[_material.name] = std::make_shared<Material>(_material);
IndexMaterial in_mat(_index, materialsByName[_material.name] );
materialsByIndices.push_back(in_mat);
}
MaterialPtr Mesh::getMaterial(const std::string& _name) const {
return materialsByName.find(_name)->second;
}
void Mesh::printMaterials() const {
for (size_t i = 0 ; i < materialsByIndices.size(); i++)
std::cout << materialsByIndices[i].first << " " << materialsByIndices[i].second->name << std::endl;
}
std::vector<std::string> Mesh::getMaterialsNames() const {
std::vector<std::string> names;
for (MaterialsByName::const_iterator it = materialsByName.begin(); it != materialsByName.end(); it++ )
names.push_back(it->first);
return names;
}
MaterialConstPtr Mesh::getMaterialForFaceIndex(size_t _index) const {
for (size_t i = materialsByIndices.size() - 1 ; i >= 0; i--)
if (_index >= materialsByIndices[i].first)
return std::const_pointer_cast<const Material>(materialsByIndices[i].second);
return nullptr;
}
Mesh Mesh::getMeshForIndices(size_t _start, size_t _end) const {
Mesh mesh;
mesh.setFaceType( getFaceType() );
std::map<size_t, INDEX_TYPE> unique_indices;
std::map<size_t, INDEX_TYPE>::iterator iter;
INDEX_TYPE iCounter = 0;
std::string lastMaterialName = "";
for (size_t i = _start; i < _end && i < faceIndices.size(); i++) {
INDEX_TYPE vi = faceIndices[i];
iter = unique_indices.find(vi);
// if already exist
if (iter != unique_indices.end())
mesh.addFaceIndex( iter->second );
// Other wise create a new one
else {
unique_indices[vi] = (int)iCounter;
mesh.addVertex( vertices[vi] );
// If there is a color add them
if (haveColors())
mesh.addColor( colors[vi] );
// If there is normals add them
if (haveNormals())
mesh.addNormal( normals[vi] );
// If there is texcoords add them
if (haveTexCoords())
mesh.addTexCoord( texcoords[vi] );
mesh.addFaceIndex( iCounter++ );
}
MaterialConstPtr material = getMaterialForFaceIndex(i);
if (material->name != lastMaterialName) {
mesh.addMaterial( *material );
lastMaterialName = material->name;
}
}
return mesh;
}
std::vector<Mesh> Mesh::getMeshesByMaterials() const {
std::vector<Mesh> meshes;
meshes.resize(materialsByIndices.size());
for (size_t i = 0; i < materialsByIndices.size(); i++ ) {
size_t firstFaceIndex = materialsByIndices[i].first;
size_t lastFaceIndex = firstFaceIndex;
if (i+1 < materialsByIndices.size())
lastFaceIndex = materialsByIndices[i+1].first;
else
lastFaceIndex = faceIndices.size()-1;
Mesh mesh = getMeshForIndices(firstFaceIndex, lastFaceIndex);
meshes[i] = mesh;
}
return meshes;
}
std::vector<INDEX_TYPE> Mesh::getFaceIndicesForMaterial(const std::string& _name) const {
std::vector<INDEX_TYPE> out;
for (size_t i = 0; i < materialsByIndices.size(); i++ ) {
if (materialsByIndices[i].second->name == _name) {
size_t first = materialsByIndices[i].first;
size_t last = first;
if (i+1 < materialsByIndices.size())
last = materialsByIndices[i+1].first;
else
last = faceIndices.size();
for (size_t j = first; j < last; j++)
out.push_back(faceIndices[j]);
}
}
return out;
} | 29.837838 | 128 | 0.542781 | [
"mesh",
"vector"
] |
a83920753f238a016134c757c8e4e82252e306d6 | 3,148 | cpp | C++ | bindings/ros/aditof_roscpp/src/examples/rviz_pointcloud.cpp | AkshayKurhade/aditof_sdk | dd6146e7cb65b56d4ce61e4fd771e94ea4976a89 | [
"BSD-3-Clause"
] | 1 | 2022-01-26T00:21:07.000Z | 2022-01-26T00:21:07.000Z | bindings/ros/aditof_roscpp/src/examples/rviz_pointcloud.cpp | AkshayKurhade/aditof_sdk | dd6146e7cb65b56d4ce61e4fd771e94ea4976a89 | [
"BSD-3-Clause"
] | null | null | null | bindings/ros/aditof_roscpp/src/examples/rviz_pointcloud.cpp | AkshayKurhade/aditof_sdk | dd6146e7cb65b56d4ce61e4fd771e94ea4976a89 | [
"BSD-3-Clause"
] | 1 | 2020-08-06T08:22:48.000Z | 2020-08-06T08:22:48.000Z | /*
* BSD 3-Clause License
*
* Copyright (c) 2019, Analog Devices, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "message_factory.h"
#include <aditof_utils.h>
#include <ros/ros.h>
using namespace aditof;
int main(int argc, char **argv) {
std::shared_ptr<Camera> camera = initCamera(argc, argv);
if (!camera) {
ROS_ERROR("initCamera call failed");
return -1;
}
std::vector<std::string> availableFrameTypes;
getAvailableFrameType(camera, availableFrameTypes);
if (availableFrameTypes.front().find("rgb") != std::string::npos) {
setFrameType(camera, "depth_ir_rgb");
} else {
setFrameType(camera, "depth_ir");
}
setMode(camera, "medium");
ros::init(argc, argv, "aditof_rviz_node");
ros::NodeHandle nHandle;
ros::Publisher frame_pubisher =
nHandle.advertise<sensor_msgs::PointCloud2>("aditof_pcloud", 100);
applyNoiseReduction(camera, 0);
Frame frame;
getNewFrame(camera, &frame);
AditofSensorMsg *msg = MessageFactory::create(
camera, &frame, MessageType::sensor_msgs_PointCloud2, ros::Time::now());
if (!msg) {
ROS_ERROR("pointcloud message creation failed");
return -1;
}
while (ros::ok()) {
getNewFrame(camera, &frame);
PointCloud2Msg *pclMsg = dynamic_cast<PointCloud2Msg *>(msg);
if (!pclMsg) {
ROS_ERROR("downcast from AditofSensorMsg to PointCloud2Msg failed");
return -1;
}
pclMsg->FrameDataToMsg(camera, &frame, ros::Time::now());
pclMsg->publishMsg(frame_pubisher);
}
delete msg;
return 0;
}
| 35.370787 | 81 | 0.699809 | [
"vector"
] |
a83a4b9c984ecad3a22b869bf42a233bc11f0b7c | 2,791 | hpp | C++ | include/objects/ProjectFolder.hpp | matthew-nagy/tileson | 6e3ddcc1365dd344a19ca267b8716aba00c8ff2a | [
"BSD-2-Clause"
] | null | null | null | include/objects/ProjectFolder.hpp | matthew-nagy/tileson | 6e3ddcc1365dd344a19ca267b8716aba00c8ff2a | [
"BSD-2-Clause"
] | null | null | null | include/objects/ProjectFolder.hpp | matthew-nagy/tileson | 6e3ddcc1365dd344a19ca267b8716aba00c8ff2a | [
"BSD-2-Clause"
] | null | null | null | //
// Created by robin on 01.08.2020.
//
#ifndef TILESON_PROJECTFOLDER_HPP
#define TILESON_PROJECTFOLDER_HPP
namespace tson
{
class ProjectFolder
{
public:
inline ProjectFolder(const fs::path &path);
inline const fs::path &getPath() const;
inline bool hasWorldFile() const;
inline const std::vector<ProjectFolder> &getSubFolders() const;
inline const std::vector<fs::path> &getFiles() const;
inline const World &getWorld() const;
private:
inline void loadData();
fs::path m_path;
bool m_hasWorldFile;
tson::World m_world;
std::vector<ProjectFolder> m_subFolders;
std::vector<fs::path> m_files;
};
ProjectFolder::ProjectFolder(const fs::path &path) : m_path {path}
{
loadData();
}
void ProjectFolder::loadData()
{
m_hasWorldFile = false;
m_subFolders.clear();
m_files.clear();
//Search and see if there is a World file .world file
fs::path worldPath;
for (const auto & entry : fs::directory_iterator(m_path))
{
if(fs::is_regular_file(entry.path()))
{
if(entry.path().extension() == ".world")
{
m_hasWorldFile = true;
worldPath = entry.path();
}
}
}
if(m_hasWorldFile)
m_world.parse(worldPath);
for (const auto & entry : fs::directory_iterator(m_path))
{
if (fs::is_directory(entry.path()))
m_subFolders.emplace_back(entry.path());//.loadData(); - loadData() is called in the constructor, so don't call again.
else if (fs::is_regular_file(entry.path()))
{
if(m_hasWorldFile && m_world.contains(entry.path().filename().generic_string()))
m_files.emplace_back(entry.path());
else if(!m_hasWorldFile)
m_files.emplace_back(entry.path());
}
}
}
const fs::path &ProjectFolder::getPath() const
{
return m_path;
}
bool ProjectFolder::hasWorldFile() const
{
return m_hasWorldFile;
}
const std::vector<ProjectFolder> &ProjectFolder::getSubFolders() const
{
return m_subFolders;
}
const std::vector<fs::path> &ProjectFolder::getFiles() const
{
return m_files;
}
/*!
* Only gives useful data if hasWorldFile() is true!
* @return
*/
const World &ProjectFolder::getWorld() const
{
return m_world;
}
}
#endif //TILESON_PROJECTFOLDER_HPP | 27.097087 | 134 | 0.538158 | [
"vector"
] |
a83c37298f003aa100d55acd9fde7dd7fe37be78 | 15,183 | cpp | C++ | examples/propagator_basic_cl2.cpp | Space-Systems/OPI | 3bbde50e1eaebb40e2f8714b401c8b6096bb718f | [
"MIT"
] | 3 | 2020-04-02T03:37:56.000Z | 2022-01-16T14:19:48.000Z | examples/propagator_basic_cl2.cpp | Space-Systems/OPI | 3bbde50e1eaebb40e2f8714b401c8b6096bb718f | [
"MIT"
] | null | null | null | examples/propagator_basic_cl2.cpp | Space-Systems/OPI | 3bbde50e1eaebb40e2f8714b401c8b6096bb718f | [
"MIT"
] | 1 | 2021-05-25T23:35:06.000Z | 2021-05-25T23:35:06.000Z | #define CL_TARGET_OPENCL_VERSION 120
#include "OPI/opi_cpp.h"
#include <string>
#include <iostream>
// For this example, we'll use the new C++ wrapper, cl2.hpp.
// This requires some additional casting, see comments below.
#define CL_HPP_TARGET_OPENCL_VERSION 120
#define CL_HPP_MINIMUM_OPENCL_VERSION 110
#include "CL/cl2.hpp"
// Basic information about the plugin that can be queried by the host.
// OPI_PLUGIN_NAME is the most important as it serves as an identifier
// for the host to request a specific propagator. It should be descriptive
// and closely match the plugin's file name.
#define OPI_PLUGIN_NAME "BasicCL"
#define OPI_PLUGIN_AUTHOR "ILR TU BS"
#define OPI_PLUGIN_DESC "Basic Mean Motion Converter - OpenCL version"
// Set the version number for the plugin here.
#define OPI_PLUGIN_VERSION_MAJOR 0
#define OPI_PLUGIN_VERSION_MINOR 1
#define OPI_PLUGIN_VERSION_PATCH 0
// Basic propagator that calculates cartesian position and unperturbed mean motion.
// This is the OpenCL version. There are equivalent C++ and CUDA plugins in the examples folder.
// OpenCL code is more complex to set up than CUDA but you'll get a much wider variety of
// supported platforms, including multicore CPUs.
class BasicCL: public OPI::Propagator
{
public:
BasicCL(OPI::Host& host)
{
// In general, you should avoid using global variables in a propagator!
// It's better to use PropagatorProperties or the Population's byte array. Only
// use globals when you know exactly what you're doing! Here, I'm only using them
// as a shortcut in order to keep the example shorter.
initialized = false;
baseDay = 0;
// Get GPU support module from host.
// The OpenCL version of the support module will provide important additional
// information compared to the CUDA version, such as the OpenCL context and
// default command queue which are required to run kernels.
clSupport = host.getGPUSupport();
}
virtual ~BasicCL()
{
}
// Auxiliary function to create the OpenCL kernel containing the propagation code.
// It is executed the first time runPropagation() is called.
cl::Kernel createPropagator()
{
// cl_int for OpenCL error reporting
cl_int err;
// Create the kernel program. OPI's OpenCL support module returns the context
// and device pointers as C types - to write a propagator using the OpenCL C++
// API, these need to be wrapped into their respective C++ objects.
// retainOwnership needs to be set to true to let OPI manage the context.
cl::Context context = cl::Context(*clSupport->getOpenCLContext(), true);
cl::Program program = cl::Program(context, kernelCode, false, &err);
if (err != CL_SUCCESS) std::cout << "Error creating program: " << err << std::endl;
// Build the kernel for the default device. Again, the C type from OPI's OpenCL
// module needs to be wrapped into the cl::Device class. Again, make sure
// retainOwnership is true to let OPI manage the device.
cl::Device device = cl::Device(*clSupport->getOpenCLDevice(), true);
err = program.build({device});
if (err != CL_SUCCESS) std::cout << "Error building: " << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device) << std::endl;
// create the kernel object
cl::Kernel kernel = cl::Kernel(program, "cl_propagate", &err);
if (err != CL_SUCCESS) {
std::cout << "Error creating kernel: " << err << std::endl;
}
else std::cout << "Kernel created." << std::endl;
return kernel;
}
// This is the main function every plugin needs to implement to do the actual propagation.
OPI::ErrorCode runPropagation(OPI::Population& population, double julian_day, double dt, OPI::PropagationMode mode, OPI::IndexList* indices)
{
if (mode == OPI::MODE_INDIVIDUAL_EPOCHS)
{
// If updating from OPI 2015, move code from runMultiTimePropagation() here instead.
return OPI::NOT_IMPLEMENTED;
}
if (indices != nullptr)
{
// If updating from OPI 2015, move code from runIndexedPropagation() here instead.
return OPI::NOT_IMPLEMENTED;
}
// In this simple example, we don't have to fiddle with Julian dates. Instead, we'll just
// look at the seconds that have elapsed since the first call of the propagator. The first
// time runPropagation() is called, the given day is saved and then subtracted from the
// following days. The remainder is converted to seconds and passed to the CUDA kernel.
if (baseDay == 0) baseDay = julian_day;
float seconds = (julian_day-baseDay)*86400.0 + dt;
// Create the OpenCL kernel on the first run.
if (!initialized) {
propagator = createPropagator();
initialized = true;
}
// cl_int for OpenCL error reporting.
cl_int err;
// Calling getOrbit, getObjectProperties, etc. with the DEVICE_CUDA flag will return
// cl_mem instances in the OpenCL implementation. They must be explicitly cast to
// cl_mem before they can be used as kernel arguments. This step will also trigger
// the memory transfer from host to OpenCL device if required.
cl_mem orbit = reinterpret_cast<cl_mem>(population.getOrbit(OPI::DEVICE_CUDA));
cl_mem position = reinterpret_cast<cl_mem>(population.getPosition(OPI::DEVICE_CUDA));
// To use the OpenCL C++ API, we also need to create a cl::Buffer object from
// the cl_mem instance. Again, the retainObject flag of the cl::Buffer constructor
// must be set to true, otherwise OPI will lose ownership of the memory pointer
// which will cause subsequent copy operations to fail.
cl::Buffer orbitBuffer = cl::Buffer(orbit, true);
cl::Buffer positionBuffer = cl::Buffer(position, true);
// The cl::Buffer objects can then be used as kernel arguments.
err = propagator.setArg(0, orbitBuffer);
if (err != CL_SUCCESS) std::cout << "Error setting orbit data: " << err << std::endl;
err = propagator.setArg(1, positionBuffer);
if (err != CL_SUCCESS) std::cout << "Error setting position data: " << err << std::endl;
// set remaining arguments (julian_day and dt)
propagator.setArg(2, seconds);
propagator.setArg(3, population.getSize());
// Get the command queue (retainOwnership = true, you get the idea...)
cl::CommandQueue queue = cl::CommandQueue(*clSupport->getOpenCLQueue(), true);
// Enqueue the kernel with a 1-dimensional NDRange matching the size of the population.
err = queue.enqueueNDRangeKernel(propagator, cl::NullRange, cl::NDRange(population.getSize()), cl::NullRange);
if (err != CL_SUCCESS) std::cout << "Error running kernel: " << err << std::endl;
// Wait for the kernel to finish.
queue.finish();
// The kernel writes to the Population's position and orbit vectors, so
// these two have to be marked for updated values on the OpenCL ("CUDA") device.
population.update(OPI::DATA_POSITION, OPI::DEVICE_CUDA);
population.update(OPI::DATA_ORBIT, OPI::DEVICE_CUDA);
return OPI::SUCCESS;
}
// Saving a member variable like baseDay in the propagator can lead to problems because
// the host might change the propagation times or even the entire population without
// notice. Therefore, plugin authors need to make sure that at least when disabling
// and subsquently enabling the propagator, hosts can expect the propagator to
// reset to its initial state.
virtual OPI::ErrorCode runDisable()
{
initialized = false;
baseDay = 0;
return OPI::SUCCESS;
}
virtual OPI::ErrorCode runEnable()
{
return OPI::SUCCESS;
}
// The following functions need to be overridden to provide some information on
// the plugin's capabilities.
// Theoretically, the algorithm can handle backward propagation,
// but the simplified handling of the input time cannot. Therefore, we'll
// return false in this function. Also defaults to false if not overridden.
bool backwardPropagation()
{
return false;
}
// This propagator returns a position vector so we'll set this to true.
// Defaults to false if not overridden.
bool cartesianCoordinates()
{
return true;
}
// This propagator generates state vectors in an Earth-centered intertial
// (ECI) reference frame. If not overridden, the default value is REF_NONE
// if no cartesian coordinates are generated, REF_UNSPECIFIED otherwise.
OPI::ReferenceFrame referenceFrame()
{
return OPI::REF_ECI;
}
// This plugin does not require CUDA so we return zero here.
// This is also the default if not overridden.
int requiresCUDA()
{
return 0;
}
// This plugin requires OpenCL version 1.0 or greater.
int requiresOpenCL()
{
return 1;
}
// This plugin is written for OPI version 2019.8
int minimumOPIVersionRequired()
{
return 2019;
}
int minorOPIVersionRequired()
{
return 8;
}
private:
cl::Kernel propagator;
OPI::GpuSupport* clSupport;
bool initialized;
double baseDay;
// Define kernel source code as a string literal (requires C++11).
std::string kernelCode = R"(
// The orbit and vector types need to be redefined in OpenCL.
// Make sure they are identical to their counterparts on the host!
struct Orbit {
double semi_major_axis;
double eccentricity;
double inclination;
double raan;
double arg_of_perigee;
double mean_anomaly;
double bol;
double eol;
};
struct Vector3 {
double x;
double y;
double z;
};
// Auxiliary OpenCL function to convert mean anomaly to eccentric anomaly.
// Identical to the function in the C++ example.
float mean2eccentric(float meanAnomaly, float eccentricity)
{
float eccentricAnomaly = meanAnomaly;
int maxloop = 5;
float fcte, fctes;
for (int i=0; i<maxloop; i++) {
fcte = eccentricAnomaly - eccentricity * sin(eccentricAnomaly) - meanAnomaly;
fctes = 1.0 - eccentricity * cos(eccentricAnomaly);
eccentricAnomaly -= fcte/fctes;
}
return eccentricAnomaly;
}
// OpenCL kernel that does the actual transformations. Equivalent to the basic CUDA
// and CPP examples with only minor changes.
kernel void cl_propagate(global struct Orbit* orbit, global struct Vector3* position, float seconds, int size)
{
// Get ID for this kernel...
int i = get_global_id(0);
// ...and make sure it doesn't exceed the Population size.
// Since we gave OpenCL the exact number of kernels to execute, this should not happen.
if (i < size)
{
// Store orbit data from the object this kernel is responsible for.
// We will use float internally since it is more efficient on the GPU.
// This is recommended for use cases where speed is more important than
// accuracy, such as visualization.
float sma = (float)orbit[i].semi_major_axis;
float ecc = (float)orbit[i].eccentricity;
float inc = (float)orbit[i].inclination;
float raan = (float)orbit[i].raan;
float aop = (float)orbit[i].arg_of_perigee;
float phi = (float)orbit[i].mean_anomaly;
// Define some auxiliary constants.
float PI = 3.1415926f;
float RMUE = 398600.5f;
float EPSILON = 0.00001f;
// Confine the input time to the object's orbit period.
float orbit_period = 2.0f * PI * sqrt(pow(sma,3.0f) / RMUE);
float t = fmod(seconds, orbit_period);
// Calculate the mean anomaly and eccentric anomaly.
// Note: This disregards the initial mean anomaly given in the Population -
// avoid this in production plugins.
// Use fmod, pow and sqrt in OpenCL instead of fmodf, powf and sqrtf.
float mean_anomaly = fmod(sqrt((RMUE * t * t) / pow(sma,3.0f)), 2.0f*PI);
float excentric_anomaly = mean2eccentric(mean_anomaly, ecc);
// Convert eccentric anomaly to true anomaly.
float sin_ea = sin(excentric_anomaly/2.0f);
float cos_ea = cos(excentric_anomaly/2.0f);
float true_anomaly = 2.0f * atan(sqrt((1.0f + ecc)/(1.0f - ecc)) * sin_ea/cos_ea);
// Based on the true anomaly, calculate cartesian object coordinates.
float u = true_anomaly + aop;
// This variable needs to be declared with the "struct" identifier in OpenCL.
struct Vector3 w;
w.x = cos(u) * cos(raan) - sin(u) * sin(raan) * cos(inc);
w.y = cos(u) * sin(raan) + sin(u) * cos(raan) * cos(inc);
w.z = sin(u) * sin(inc);
float p = sma * (1.0f - pow(ecc,2.0f));
float arg = 1.0f + (ecc * cos(true_anomaly));
float r = p / EPSILON;
if (arg > EPSILON) r = p / arg;
// Write the position vector into the OPI::Population array.
position[i].x = (double)(w.x*r);
position[i].y = (double)(w.y*r);
position[i].z = (double)(w.z*r);
// Finally, also write back the new mean anomaly into the orbit.
orbit[i].mean_anomaly = (double)mean_anomaly;
}
}
)";
};
#define OPI_IMPLEMENT_CPP_PROPAGATOR BasicCL
#include "OPI/opi_implement_plugin.h"
| 44.655882 | 148 | 0.591912 | [
"object",
"vector"
] |
a83f86e402b0ef0a5fdb81c47e729642f534a16f | 4,926 | cpp | C++ | src/sha1_hash.cpp | AmirAbrams/libtorrent | 3fb05d77d873675d2a213c7a3f243f2435398bdc | [
"BSL-1.0",
"BSD-3-Clause"
] | 2 | 2019-06-05T18:08:25.000Z | 2021-06-07T10:36:57.000Z | src/sha1_hash.cpp | AmirAbrams/libtorrent | 3fb05d77d873675d2a213c7a3f243f2435398bdc | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | src/sha1_hash.cpp | AmirAbrams/libtorrent | 3fb05d77d873675d2a213c7a3f243f2435398bdc | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 2016, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/sha1_hash.hpp"
#include "libtorrent/hex.hpp" // to_hex, from_hex
#if TORRENT_USE_IOSTREAM
#include <iostream>
#include <iomanip>
#endif // TORRENT_USE_IOSTREAM
namespace libtorrent {
#if TORRENT_USE_IOSTREAM
// print a sha1_hash object to an ostream as 40 hexadecimal digits
std::ostream& operator<<(std::ostream& os, sha1_hash const& peer)
{
return os << aux::to_hex(peer);
}
// read 40 hexadecimal digits from an istream into a sha1_hash
std::istream& operator>>(std::istream& is, sha1_hash& peer)
{
char hex[sha1_hash::size() * 2];
is.read(hex, sha1_hash::size() * 2);
if (!aux::from_hex(hex, peer.data()))
is.setstate(std::ios_base::failbit);
return is;
}
#endif // TORRENT_USE_IOSTREAM
namespace aux {
void bits_shift_left(typed_span<std::uint32_t> number, int n)
{
TORRENT_ASSERT(n >= 0);
int const num_words = n / 32;
int const number_size = number.end_index();
if (num_words >= number_size)
{
std::memset(number.data(), 0, number.size() * 4);
return;
}
if (num_words > 0)
{
std::memmove(number.data(), number.data() + num_words
, std::size_t(number_size - num_words) * sizeof(std::uint32_t));
std::memset(number.data() + (number_size - num_words)
, 0, std::size_t(num_words) * sizeof(std::uint32_t));
n -= num_words * 32;
}
if (n > 0)
{
// keep in mind that the uint32_t are stored in network
// byte order, so they have to be byteswapped before
// applying the shift operations, and then byteswapped
// back again.
number[0] = aux::network_to_host(number[0]);
for (int i = 0; i < number_size - 1; ++i)
{
number[i] <<= n;
number[i + 1] = aux::network_to_host(number[i + 1]);
number[i] |= number[i + 1] >> (32 - n);
number[i] = aux::host_to_network(number[i]);
}
number[number_size - 1] <<= n;
number[number_size - 1] = aux::host_to_network(number[number_size - 1]);
}
}
void bits_shift_right(typed_span<std::uint32_t> number, int n)
{
TORRENT_ASSERT(n >= 0);
int const num_words = n / 32;
int const number_size = number.end_index();
if (num_words >= number_size)
{
std::memset(number.data(), 0, number.size() * 4);
return;
}
if (num_words > 0)
{
std::memmove(number.data() + num_words
, number.data(), std::size_t(number_size - num_words) * sizeof(std::uint32_t));
std::memset(number.data(), 0, std::size_t(num_words) * sizeof(std::uint32_t));
n -= num_words * 32;
}
if (n > 0)
{
// keep in mind that the uint32_t are stored in network
// byte order, so they have to be byteswapped before
// applying the shift operations, and then byteswapped
// back again.
number[number_size - 1] = aux::network_to_host(number[number_size - 1]);
for (int i = number_size - 1; i > 0; --i)
{
number[i] >>= n;
number[i - 1] = aux::network_to_host(number[i - 1]);
number[i] |= (number[i - 1] << (32 - n)) & 0xffffffff;
number[i] = aux::host_to_network(number[i]);
}
number[0] >>= n;
number[0] = aux::host_to_network(number[0]);
}
}
}
static_assert(std::is_nothrow_move_constructible<sha1_hash>::value
, "should be nothrow move constructible");
static_assert(std::is_nothrow_move_assignable<sha1_hash>::value
, "should be nothrow move assignable");
static_assert(std::is_nothrow_default_constructible<sha1_hash>::value
, "should be nothrow default constructible");
}
| 33.283784 | 83 | 0.697523 | [
"object"
] |
61b624ce8dcb71bf42f036e3843eedee61105183 | 1,924 | cpp | C++ | questions/vds_cspad/master.cpp | slaclab/lc2-hdf5-5110 | 3298553da4fc9d2c4a9ae1528f157595a7b06b6a | [
"Apache-2.0"
] | null | null | null | questions/vds_cspad/master.cpp | slaclab/lc2-hdf5-5110 | 3298553da4fc9d2c4a9ae1528f157595a7b06b6a | [
"Apache-2.0"
] | null | null | null | questions/vds_cspad/master.cpp | slaclab/lc2-hdf5-5110 | 3298553da4fc9d2c4a9ae1528f157595a7b06b6a | [
"Apache-2.0"
] | null | null | null | #include <cstdio>
#include <cstdlib>
#include <vector>
#include "hdf5.h"
int main(int argc, char *argv[]) {
if (argc != 4) {
printf("ERROR, no args\n");
return -1;
}
int dim = atoi(argv[1]);
std::string src1 = std::string(argv[2]);
std::string src2 = std::string(argv[3]);
hid_t fapl = H5Pcreate(H5P_FILE_ACCESS);
H5Pset_libver_bounds(fapl, H5F_LIBVER_LATEST, H5F_LIBVER_LATEST);
hid_t fid = H5Fcreate("master.h5", H5F_ACC_TRUNC, H5P_DEFAULT, fapl);
hid_t h5type = H5T_NATIVE_SHORT;
hid_t dcpl = H5Pcreate(H5P_DATASET_CREATE);
short fill = -1;
H5Pset_fill_value(dcpl, H5T_NATIVE_SHORT, &fill);
hsize_t size0[3] = {0,dim,dim};
hsize_t start0[3] = {0,0,0};
hsize_t start1[3] = {1,0,0};
hsize_t stride2[3] = {2,1,1};
hsize_t stride1[3] = {1,1,1};
hsize_t blockOne[3] = {1,dim,dim};
hsize_t blockUnlimited[3] = {H5S_UNLIMITED,dim,dim};
hsize_t countUnlimited[3] = {H5S_UNLIMITED,1,1};
hsize_t countOne[3] = {1,1,1};
hsize_t sizeUnlimited[3] = {H5S_UNLIMITED, dim, dim};
int rank3 = 3;
hid_t vds_space = H5Screate_simple(rank3, size0, sizeUnlimited);
hid_t src_space = H5Screate_simple(rank3, size0, sizeUnlimited);
H5Sselect_hyperslab(vds_space, H5S_SELECT_SET, start0, stride2, countUnlimited, blockOne);
H5Sselect_hyperslab(src_space, H5S_SELECT_SET, start0, stride1, countOne, blockUnlimited);
H5Pset_virtual(dcpl, vds_space, src1.c_str(), "cspad", src_space);
H5Sselect_hyperslab(vds_space, H5S_SELECT_SET, start1, stride2, countUnlimited, blockOne);
H5Sselect_hyperslab(src_space, H5S_SELECT_SET, start0, stride1, countOne, blockUnlimited);
H5Pset_virtual(dcpl, vds_space, src2.c_str(), "cspad", src_space);
hid_t dset = H5Dcreate(fid, "vds", H5T_NATIVE_SHORT, vds_space, H5P_DEFAULT, dcpl, H5P_DEFAULT);
H5Dclose(dset);
H5Sclose(src_space);
H5Sclose(vds_space);
H5Pclose(dcpl);
H5Fclose(fid);
H5Pclose(fapl);
return 0;
}
| 33.754386 | 98 | 0.711538 | [
"vector"
] |
61b814fd9149835642da319a002e5a179e8de872 | 3,258 | hpp | C++ | examples/gui/dvh_view_2d.hpp | LoganBarnes/ltb-dvh | f9f4989c9f91f7121961d449e60e2a0da26f0b4c | [
"MIT"
] | null | null | null | examples/gui/dvh_view_2d.hpp | LoganBarnes/ltb-dvh | f9f4989c9f91f7121961d449e60e2a0da26f0b4c | [
"MIT"
] | null | null | null | examples/gui/dvh_view_2d.hpp | LoganBarnes/ltb-dvh | f9f4989c9f91f7121961d449e60e2a0da26f0b4c | [
"MIT"
] | null | null | null | // ///////////////////////////////////////////////////////////////////////////////////////
// LTB Distance Volume Hierarchy
// Copyright (c) 2020 Logan Barnes - All Rights Reserved
//
// 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
// project
#include "ltb/dvh/distance_volume_hierarchy.hpp"
#include "ltb/gvs/display/gui/error_alert_recorder.hpp"
#include "ltb/gvs/display/local_scene.hpp"
#include "ltb/sdf/sdf.hpp"
#include "view.hpp"
namespace ltb::example {
class DvhView2d : public View {
public:
explicit DvhView2d(gvs::ErrorAlertRecorder error_recorder);
~DvhView2d() override;
void update() override;
void render(const gvs::CameraPackage& camera_package) const override;
void configure_gui() override;
void resize(const Magnum::Vector2i& viewport) override;
void handleKeyPressEvent(Magnum::Platform::Application::KeyEvent& event) override;
void handleKeyReleaseEvent(Magnum::Platform::Application::KeyEvent& event) override;
void handleMousePressEvent(Magnum::Platform::Application::MouseEvent& event) override;
void handleMouseReleaseEvent(Magnum::Platform::Application::MouseEvent& event) override;
void handleMouseMoveEvent(Magnum::Platform::Application::MouseMoveEvent& event) override;
private:
// Errors
gvs::ErrorAlertRecorder error_recorder_;
// DVH
float base_resolution_ = 0.1f;
dvh::DistanceVolumeHierarchy<2> dvh_;
// Additive Volumes
std::vector<sdf::OrientedLine<>> additive_polygon_;
std::vector<sdf::TransformedGeometry<sdf::Box, 2>> additive_boxes_;
// Subtractive Volumes
std::vector<sdf::TransformedGeometry<sdf::Box, 2>> subtractive_boxes_;
std::vector<sdf::OffsetLine<2>> subtractive_lines_;
// Scene
std::unique_ptr<gvs::LocalScene> scene_;
gvs::SceneId dvh_root_scene_id_ = gvs::nil_id();
std::unordered_map<int, gvs::SceneId> index_scene_ids_;
// Feedback
std::string computation_time_message_;
void reset_volumes();
void reset_scene();
};
} // namespace ltb::example
| 40.222222 | 93 | 0.686311 | [
"render",
"vector"
] |
61b97d765e5b0cf1ee5cc7d3824aec0adc47978a | 1,377 | cc | C++ | orttraining/orttraining/test/training_ops/cpu/function_op_test.cc | dennyac/onnxruntime | d5175795d2b7f2db18b0390f394a49238f814668 | [
"MIT"
] | 6,036 | 2019-05-07T06:03:57.000Z | 2022-03-31T17:59:54.000Z | orttraining/orttraining/test/training_ops/cpu/function_op_test.cc | dennyac/onnxruntime | d5175795d2b7f2db18b0390f394a49238f814668 | [
"MIT"
] | 5,730 | 2019-05-06T23:04:55.000Z | 2022-03-31T23:55:56.000Z | orttraining/orttraining/test/training_ops/cpu/function_op_test.cc | dennyac/onnxruntime | d5175795d2b7f2db18b0390f394a49238f814668 | [
"MIT"
] | 1,566 | 2019-05-07T01:30:07.000Z | 2022-03-31T17:06:50.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "gtest/gtest.h"
#include "test/providers/provider_test_utils.h"
#include "core/providers/cpu/cpu_execution_provider.h"
#include "core/session/inference_session.h"
#include "core/graph/graph.h"
#include "orttraining/test/training_ops/function_op_test_utils.h"
#include "orttraining/core/graph/graph_augmenter.h"
namespace onnxruntime {
namespace test {
namespace testdata {
std::vector<float> x = {-1.0f, 0, 1.0f, 100.0f, -100.0f, 1000.0f, -1000.0f};
std::vector<float> dy(7, 1.0f);
} // namespace testdata
TEST(FunctionOpTest, DISABLED_Gelu) {
std::vector<std::vector<float>> input_data;
input_data.push_back(testdata::x);
const onnxruntime::training::OpDef& op_def{"Gelu"};
CompareResults(op_def,
input_data,
{{7, 1}},
{{7, 1}},
{},
9);
}
TEST(FunctionOpTest, DISABLED_GeluGrad) {
std::vector<std::vector<float>> input_data;
input_data.push_back(testdata::dy);
input_data.push_back(testdata::x);
const onnxruntime::training::OpDef& op_def{"GeluGrad"};
CompareResults(op_def,
input_data,
{{7, 1}, {7, 1}},
{{7, 1}},
{},
9);
}
} // namespace test
} // namespace onnxruntime
| 28.102041 | 76 | 0.631808 | [
"vector"
] |
61bb2710b1978dcdabc5c77b339c965ff5a06432 | 3,022 | cpp | C++ | tke/src/v20180525/model/DeleteEKSContainerInstancesRequest.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 43 | 2019-08-14T08:14:12.000Z | 2022-03-30T12:35:09.000Z | tke/src/v20180525/model/DeleteEKSContainerInstancesRequest.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 12 | 2019-07-15T10:44:59.000Z | 2021-11-02T12:35:00.000Z | tke/src/v20180525/model/DeleteEKSContainerInstancesRequest.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 28 | 2019-07-12T09:06:22.000Z | 2022-03-30T08:04:18.000Z | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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.
*/
#include <tencentcloud/tke/v20180525/model/DeleteEKSContainerInstancesRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Tke::V20180525::Model;
using namespace std;
DeleteEKSContainerInstancesRequest::DeleteEKSContainerInstancesRequest() :
m_eksCiIdsHasBeenSet(false),
m_releaseAutoCreatedEipHasBeenSet(false)
{
}
string DeleteEKSContainerInstancesRequest::ToJsonString() const
{
rapidjson::Document d;
d.SetObject();
rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
if (m_eksCiIdsHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "EksCiIds";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
for (auto itr = m_eksCiIds.begin(); itr != m_eksCiIds.end(); ++itr)
{
d[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator);
}
}
if (m_releaseAutoCreatedEipHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ReleaseAutoCreatedEip";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_releaseAutoCreatedEip, allocator);
}
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
vector<string> DeleteEKSContainerInstancesRequest::GetEksCiIds() const
{
return m_eksCiIds;
}
void DeleteEKSContainerInstancesRequest::SetEksCiIds(const vector<string>& _eksCiIds)
{
m_eksCiIds = _eksCiIds;
m_eksCiIdsHasBeenSet = true;
}
bool DeleteEKSContainerInstancesRequest::EksCiIdsHasBeenSet() const
{
return m_eksCiIdsHasBeenSet;
}
bool DeleteEKSContainerInstancesRequest::GetReleaseAutoCreatedEip() const
{
return m_releaseAutoCreatedEip;
}
void DeleteEKSContainerInstancesRequest::SetReleaseAutoCreatedEip(const bool& _releaseAutoCreatedEip)
{
m_releaseAutoCreatedEip = _releaseAutoCreatedEip;
m_releaseAutoCreatedEipHasBeenSet = true;
}
bool DeleteEKSContainerInstancesRequest::ReleaseAutoCreatedEipHasBeenSet() const
{
return m_releaseAutoCreatedEipHasBeenSet;
}
| 30.22 | 104 | 0.74454 | [
"vector",
"model"
] |
61bbf9f8380d90af7a8a6e99acddc4bd6bd0080e | 2,189 | cpp | C++ | code/week1/week1.cpp | llxxll12345/software-training | 1f56f73aa6d77b08c324d2fe582427da653072fd | [
"MIT"
] | null | null | null | code/week1/week1.cpp | llxxll12345/software-training | 1f56f73aa6d77b08c324d2fe582427da653072fd | [
"MIT"
] | null | null | null | code/week1/week1.cpp | llxxll12345/software-training | 1f56f73aa6d77b08c324d2fe582427da653072fd | [
"MIT"
] | null | null | null | // make sure to compile with g++
// to compile do
// g++ -o week1.out week1.cpp
// to run do
// ./week1.out
// This is including a header file for the standard library
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <vector>
// This is a comment!
/*
This is a block comment ...
C++ has more complicated rules involving global varibales
We will cover this in depth when we talk about pointers
and memory strucutre
*/
//////////Primitive Data Types//////////
int yearsInRoboJackets = 3;
double myBirthday = 8.11;
bool isRoboJacketsCool = true;
//////////Arrays//////////
//You can do this with any primitive data type
double gpas[] = {1.0, 2.6, 4.0, 3.6};
int membersInRoboJackets[200];
using namespace std;
int main() {
//Ignore the above line for now we will cover this later
//This is the main function that runs any logic!
//////////Local Variables/////////
vector<double> vec({1,2,3,4});
for (double d : vec) {
printf("GPA: %.2f\n", d);
}
int num = 0;
int length = 0;
int count = 0;
string str = "";
cout << ((3 + 3) == 9) << endl;
cout << ((2 + 2) != 5) << endl;
cout << true << endl;
cout << false << endl;
cout << (!false) << endl;
cout << (true || false) << endl;
cout << (true && false) << endl;
//If-ElseIf-Else
if (num == 0) {
num = 3;
cout << "I understand Loops!" << endl;
} else if (num > 4) {
num += 3;
cout << "Like John Cena, you can't see me" << endl;
} else {
num--;
cout << "Like George P. Burdell, I don't ever show up" << endl;
}
//////////Loops/////////
//For
for (int n = 0; n < sizeof(gpas)/sizeof(gpas[0]); n++) {
cout << "GPA: " << gpas[n] << endl;
}
//While
while (length < sizeof(gpas)/sizeof(gpas[0])) {
cout << "Adjusted GPA: " << (gpas[length] + 2) << endl;
length++;
}
//Do-While
do {
cout << "Count is: " << count << endl;
count++;
} while (count < 11);
// this is a status code that will be returned to whatever ran this executable
// 0 typically means no errors
return 0;
}
| 25.16092 | 82 | 0.539973 | [
"vector"
] |
61c027f213aafc9732728db16dfcbe0baa68420a | 1,854 | hpp | C++ | nvmes.hpp | openbmc/phosphor-nvme | 5022a4ee5cd4d3eaeabc4e991507e71b35b26a16 | [
"Apache-2.0"
] | null | null | null | nvmes.hpp | openbmc/phosphor-nvme | 5022a4ee5cd4d3eaeabc4e991507e71b35b26a16 | [
"Apache-2.0"
] | 4 | 2019-06-12T23:08:44.000Z | 2021-04-16T03:53:50.000Z | nvmes.hpp | openbmc/phosphor-nvme | 5022a4ee5cd4d3eaeabc4e991507e71b35b26a16 | [
"Apache-2.0"
] | 1 | 2020-05-12T13:30:46.000Z | 2020-05-12T13:30:46.000Z | #pragma once
#include <sdbusplus/bus.hpp>
#include <xyz/openbmc_project/Sensor/Threshold/Critical/server.hpp>
#include <xyz/openbmc_project/Sensor/Threshold/Warning/server.hpp>
#include <xyz/openbmc_project/Sensor/Value/server.hpp>
namespace phosphor
{
namespace nvme
{
using ValueIface = sdbusplus::xyz::openbmc_project::Sensor::server::Value;
using CriticalInterface =
sdbusplus::xyz::openbmc_project::Sensor::Threshold::server::Critical;
using WarningInterface =
sdbusplus::xyz::openbmc_project::Sensor::Threshold::server::Warning;
using NvmeIfaces =
sdbusplus::server::object::object<ValueIface, CriticalInterface,
WarningInterface>;
class NvmeSSD : public NvmeIfaces
{
public:
NvmeSSD() = delete;
NvmeSSD(const NvmeSSD&) = delete;
NvmeSSD& operator=(const NvmeSSD&) = delete;
NvmeSSD(NvmeSSD&&) = delete;
NvmeSSD& operator=(NvmeSSD&&) = delete;
virtual ~NvmeSSD() = default;
/** @brief Constructs NvmeSSD
*
* @param[in] bus - Handle to system dbus
* @param[in] objPath - The Dbus path of nvme
*/
NvmeSSD(sdbusplus::bus::bus& bus, const char* objPath) :
NvmeIfaces(bus, objPath), bus(bus)
{
}
/** @brief Set sensor value temperature to nvme D-bus */
void setSensorValueToDbus(const int8_t value);
/** @brief Check if sensor value higher or lower threshold */
void checkSensorThreshold();
/** @brief Set Sensor Threshold to D-bus at beginning */
void setSensorThreshold(int8_t criticalHigh, int8_t criticalLow,
int8_t warningHigh, int8_t warningLow);
/** @brief Set Sensor Max/Min value to D-bus at beginning */
void setSensorMaxMin(int8_t maxValue, int8_t minValue);
private:
sdbusplus::bus::bus& bus;
};
} // namespace nvme
} // namespace phosphor
| 30.9 | 74 | 0.68123 | [
"object"
] |
61c5f8bc4410af718203fea71f0b07e5278edc93 | 5,850 | cpp | C++ | CH01-GettingStarted/HelloTriangle/hellotriangle2.cpp | THISISAGOODNAME/learnopengl-glitter | a9b6eb22aea1e2c3b1d6bd9387f367bcbfc486ef | [
"MIT"
] | 38 | 2017-02-19T06:45:30.000Z | 2022-02-20T15:02:33.000Z | CH01-GettingStarted/HelloTriangle/hellotriangle2.cpp | THISISAGOODNAME/learnopengl-glitter | a9b6eb22aea1e2c3b1d6bd9387f367bcbfc486ef | [
"MIT"
] | null | null | null | CH01-GettingStarted/HelloTriangle/hellotriangle2.cpp | THISISAGOODNAME/learnopengl-glitter | a9b6eb22aea1e2c3b1d6bd9387f367bcbfc486ef | [
"MIT"
] | 12 | 2017-01-06T08:49:03.000Z | 2021-11-09T13:41:11.000Z | // Local Headers
#include "glitter.hpp"
// Console Color
#include "consoleColor.hpp"
// System Headers
#include <glad/glad.h>
#include <GLFW/glfw3.h>
// Standard Headers
//#include <cstdio>
//#include <cstdlib>
#include <iostream>
// ๅฃฐๆๆ้ฎๅฝๆฐ
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode);
// Shaders
const GLchar* vertexShaderSource = "#version 330 core\n"
"layout (location = 0) in vec3 position;\n"
"void main()\n"
"{\n"
"gl_Position = vec4(position.x, position.y, position.z, 1.0);\n"
"}\0";
const GLchar* fragmentShaderSource = "#version 330 core\n"
"out vec4 color;\n"
"void main()\n"
"{\n"
"color = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n"
"}\n\0";
int main(int argc, char * argv[]) {
// glfwๅๅงๅ
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // ๆญค่ก็จๆฅ็ปMac OS X็ณป็ปๅๅ
ผๅฎน
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
// ๅๅปบ็ชๅฃ,่ทๅ็ชๅฃไธไธไธๆ
GLFWwindow* window = glfwCreateWindow(mWidth, mHeight, "LearnOpenGL", nullptr, nullptr);
if (window == nullptr)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
// ้่ฟglfwๆณจๅๆ้ฎไบไปถๅ่ฐ
glfwSetKeyCallback(window, key_callback);
// Load OpenGL Functions
gladLoadGL();
// fprintf(stderr, "OpenGL %s\n", glGetString(GL_VERSION));
std::cout << BLUE << "OpenGL " << glGetString(GL_VERSION) << RESET << std::endl;
// ่ทๅ่งๅฃ
int width, height;
glfwGetFramebufferSize(window, &width, &height);
glViewport(0, 0, width, height);
// ็ผ่ฏ็่ฒๅจ
// ้กถ็น็่ฒๅจ
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
glCompileShader(vertexShader);
// ๆฃๆฅ็ผ่ฏๆฏๅฆๆๅ
GLint success;
GLchar infoLog[512];
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
if(!success)
{
glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
std::cout << RED << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << RESET << std::endl;
}
// ็ๆฎต็่ฒๅจ
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
glCompileShader(fragmentShader);
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);
std::cout << RED << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << RESET << std::endl;
}
// ้พๆฅ็่ฒๅจ
GLuint shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
// ๆฃๆฅ้พๆฅ้่ฏฏ
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
if (!success) {
glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
std::cout << RED << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << RESET << std::endl;
}
// ้พๆฅๅฎๆๅพๅฐprogramๅ,shaderๅฐฑไธ้่ฆไบ,ๅ ้ค้ๆพๅ
ๅญ
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
// ้กถ็น่พๅ
ฅ
// GLfloat vertices[] = {
// // ็ฌฌไธไธชไธ่งๅฝข
// 0.5f, 0.5f, 0.0f, // ๅณไธ่ง
// 0.5f, -0.5f, 0.0f, // ๅณไธ่ง
// -0.5f, 0.5f, 0.0f, // ๅทฆไธ่ง
// // ็ฌฌไบไธชไธ่งๅฝข
// 0.5f, -0.5f, 0.0f, // ๅณไธ่ง
// -0.5f, -0.5f, 0.0f, // ๅทฆไธ่ง
// -0.5f, 0.5f, 0.0f // ๅทฆไธ่ง
// };
GLfloat vertices[] = {
0.5f, 0.5f, 0.0f, // ๅณไธ่ง
0.5f, -0.5f, 0.0f, // ๅณไธ่ง
-0.5f, -0.5f, 0.0f, // ๅทฆไธ่ง
-0.5f, 0.5f, 0.0f // ๅทฆไธ่ง
};
GLuint indices[] = { // ๆณจๆ็ดขๅผไป0ๅผๅง!
0, 1, 3, // ็ฌฌไธไธชไธ่งๅฝข
1, 2, 3 // ็ฌฌไบไธชไธ่งๅฝข
};
// ้กถ็นๆฐ็ปๅฏน่ฑก Vertex Array Object, VAO
// ้กถ็น็ผๅฒๅฏน่ฑก Vertex Buffer Object๏ผVBO
// ็ดขๅผ็ผๅฒๅฏน่ฑก๏ผElement Buffer Object๏ผEBOๆIndex Buffer Object๏ผIBO
GLuint VAO, VBO, EBO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
// !!! Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s).
glBindVertexArray(VAO);
// ๆ้กถ็นๆฐ็ปๅคๅถๅฐ็ผๅฒไธญไพOpenGLไฝฟ็จ
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
// ่ฎพ็ฝฎ้กถ็นๅฑๆงๆ้
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(0);
glBindVertexArray(0);
glUseProgram(shaderProgram);
// ไฝฟ็จ็บฟๆกๆจกๅผ่ฟ่กๆธฒๆ
//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
// ๆธฒๆ
while (!glfwWindowShouldClose(window))
{
// ๆฃๆฅไบไปถ
glfwPollEvents();
// ๆธฒๆๆไปค
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
// ็ปๅพ
glUseProgram(shaderProgram);
glBindVertexArray(VAO);
// glDrawArrays(GL_TRIANGLES, 0, 6);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
// ไบคๆข็ผๅฒ
glfwSwapBuffers(window);
}
// ้ๆพVAO,VBO
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
glDeleteBuffers(1, &EBO);
// ้ๆพGLFWๅ้
็ๅ
ๅญ
glfwTerminate();
return 0;
}
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
// ๅฝ็จๆทๆไธESC้ฎ,ๆไปฌ่ฎพ็ฝฎwindow็ชๅฃ็WindowShouldCloseๅฑๆงไธบtrue
// ๅ
ณ้ญๅบ็จ็จๅบ
if(key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
} | 29.545455 | 109 | 0.625128 | [
"object"
] |
61c777c51919be26b6efd738fa87416c8b1dffe1 | 7,294 | cc | C++ | L1Trigger/L1CaloTrigger/plugins/L1EGammaEEProducer.cc | PKUfudawei/cmssw | 8fbb5ce74398269c8a32956d7c7943766770c093 | [
"Apache-2.0"
] | 1 | 2021-11-30T16:24:46.000Z | 2021-11-30T16:24:46.000Z | L1Trigger/L1CaloTrigger/plugins/L1EGammaEEProducer.cc | PKUfudawei/cmssw | 8fbb5ce74398269c8a32956d7c7943766770c093 | [
"Apache-2.0"
] | 4 | 2021-11-29T13:57:56.000Z | 2022-03-29T06:28:36.000Z | L1Trigger/L1CaloTrigger/plugins/L1EGammaEEProducer.cc | PKUfudawei/cmssw | 8fbb5ce74398269c8a32956d7c7943766770c093 | [
"Apache-2.0"
] | 1 | 2021-11-30T16:16:05.000Z | 2021-11-30T16:16:05.000Z | #include "FWCore/Framework/interface/stream/EDProducer.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "DataFormats/L1THGCal/interface/HGCalMulticluster.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "DataFormats/L1Trigger/interface/EGamma.h"
#include "L1Trigger/L1CaloTrigger/interface/L1EGammaEECalibrator.h"
#include "DataFormats/Math/interface/deltaPhi.h"
namespace l1tp2 {
// we sort the clusters in pt
bool compare_cluster_pt(const l1t::HGCalMulticluster *cl1, const l1t::HGCalMulticluster *cl2) {
return cl1->pt() > cl2->pt();
}
}; // namespace l1tp2
int etaBin(const l1t::HGCalMulticluster *cl) {
static float constexpr eta_min = 1.;
static float constexpr eta_max = 4.;
static unsigned constexpr n_eta_bins = 150;
int eta_bin = floor((std::abs(cl->eta()) - eta_min) / ((eta_max - eta_min) / n_eta_bins));
if (cl->eta() < 0)
return -1 * eta_bin; // bin 0 doesn't exist
return eta_bin;
}
int get_phi_bin(const l1t::HGCalMulticluster *cl) {
static constexpr float phi_min = -M_PI;
static constexpr float phi_max = M_PI;
static constexpr unsigned n_phi_bins = 63;
return floor(std::abs(reco::deltaPhi(cl->phi(), phi_min)) / ((phi_max - phi_min) / n_phi_bins));
}
pair<int, int> get_eta_phi_bin(const l1t::HGCalMulticluster *cl) { return std::make_pair(etaBin(cl), get_phi_bin(cl)); }
class L1EGammaEEProducer : public edm::stream::EDProducer<> {
public:
explicit L1EGammaEEProducer(const edm::ParameterSet &);
private:
void produce(edm::Event &, const edm::EventSetup &) override;
edm::EDGetToken multiclusters_token_;
L1EGammaEECalibrator calibrator_;
};
L1EGammaEEProducer::L1EGammaEEProducer(const edm::ParameterSet &iConfig)
: multiclusters_token_(
consumes<l1t::HGCalMulticlusterBxCollection>(iConfig.getParameter<edm::InputTag>("Multiclusters"))),
calibrator_(iConfig.getParameter<edm::ParameterSet>("calibrationConfig")) {
produces<BXVector<l1t::EGamma>>("L1EGammaCollectionBXVWithCuts");
}
void L1EGammaEEProducer::produce(edm::Event &iEvent, const edm::EventSetup &iSetup) {
float minEt_ = 0;
std::unique_ptr<BXVector<l1t::EGamma>> l1EgammaBxCollection(new l1t::EGammaBxCollection);
// retrieve clusters 3D
edm::Handle<l1t::HGCalMulticlusterBxCollection> multiclusters_h;
iEvent.getByToken(multiclusters_token_, multiclusters_h);
const l1t::HGCalMulticlusterBxCollection &multiclusters = *multiclusters_h;
std::vector<const l1t::HGCalMulticluster *> selected_multiclusters;
std::map<std::pair<int, int>, std::vector<const l1t::HGCalMulticluster *>> etaphi_bins;
// here we loop on the TPGs
for (auto cl3d = multiclusters.begin(0); cl3d != multiclusters.end(0); cl3d++) {
if (cl3d->hwQual()) {
if (cl3d->et() > minEt_) {
int hw_quality = 1; // baseline EG ID passed
if (std::abs(cl3d->eta()) >= 1.52) {
hw_quality = 2; // baseline EG ID passed + cleanup of transition region
}
float calib_factor = calibrator_.calibrationFactor(cl3d->pt(), cl3d->eta());
l1t::EGamma eg =
l1t::EGamma(reco::Candidate::PolarLorentzVector(cl3d->pt() / calib_factor, cl3d->eta(), cl3d->phi(), 0.));
eg.setHwQual(hw_quality);
eg.setHwIso(1);
eg.setIsoEt(-1); // just temporarily as a dummy value
l1EgammaBxCollection->push_back(0, eg);
if (hw_quality == 2) {
// we build the EM interpreted EG object
l1t::EGamma eg_emint = l1t::EGamma(reco::Candidate::PolarLorentzVector(
cl3d->iPt(l1t::HGCalMulticluster::EnergyInterpretation::EM), cl3d->eta(), cl3d->phi(), 0.));
eg_emint.setHwQual(4);
eg_emint.setHwIso(1);
eg_emint.setIsoEt(-1); // just temporarily as a dummy value
l1EgammaBxCollection->push_back(0, eg_emint);
// we also prepare for the brem recovery procedure
selected_multiclusters.push_back(&(*cl3d));
auto eta_phi_bin = get_eta_phi_bin(&(*cl3d));
auto bucket = etaphi_bins.find(eta_phi_bin);
if (bucket == etaphi_bins.end()) {
std::vector<const l1t::HGCalMulticluster *> vec;
vec.push_back(&(*cl3d));
etaphi_bins[eta_phi_bin] = vec;
} else {
bucket->second.push_back(&(*cl3d));
}
}
}
}
}
std::sort(selected_multiclusters.begin(), selected_multiclusters.end(), l1tp2::compare_cluster_pt);
std::set<const l1t::HGCalMulticluster *> used_clusters;
for (const auto &cl3d : selected_multiclusters) {
if (used_clusters.find(cl3d) == used_clusters.end()) {
float pt = cl3d->pt();
// we drop the Had component of the energy
if (cl3d->hOverE() != -1)
pt = cl3d->pt() / (1 + cl3d->hOverE());
reco::Candidate::PolarLorentzVector mom(pt, cl3d->eta(), cl3d->phi(), 0.);
reco::Candidate::PolarLorentzVector mom_eint(
cl3d->iPt(l1t::HGCalMulticluster::EnergyInterpretation::EM), cl3d->eta(), cl3d->phi(), 0.);
// this is not yet used
used_clusters.insert(cl3d);
auto eta_phi_bin = get_eta_phi_bin(cl3d);
for (int eta_bin : {eta_phi_bin.first - 1, eta_phi_bin.first, eta_phi_bin.first + 1}) {
for (int phi_bin : {eta_phi_bin.second - 1, eta_phi_bin.second, eta_phi_bin.second + 1}) {
auto bucket = etaphi_bins.find(std::make_pair(eta_bin, phi_bin));
if (bucket != etaphi_bins.end()) {
// this bucket is not empty
for (const auto &other_cl_ptr : bucket->second) {
if (used_clusters.find(other_cl_ptr) == used_clusters.end()) {
if (std::abs(other_cl_ptr->eta() - cl3d->eta()) < 0.02) {
if (std::abs(reco::deltaPhi(other_cl_ptr->phi(), cl3d->phi())) < 0.1) {
float pt_other = other_cl_ptr->pt();
if (other_cl_ptr->hOverE() != -1)
pt_other = other_cl_ptr->pt() / (1 + other_cl_ptr->hOverE());
mom += reco::Candidate::PolarLorentzVector(pt_other, other_cl_ptr->eta(), other_cl_ptr->phi(), 0.);
mom_eint += reco::Candidate::PolarLorentzVector(
other_cl_ptr->iPt(l1t::HGCalMulticluster::EnergyInterpretation::EM),
other_cl_ptr->eta(),
other_cl_ptr->phi(),
0.);
used_clusters.insert(other_cl_ptr);
}
}
}
}
}
}
}
float calib_factor = calibrator_.calibrationFactor(mom.pt(), mom.eta());
l1t::EGamma eg =
l1t::EGamma(reco::Candidate::PolarLorentzVector(mom.pt() / calib_factor, mom.eta(), mom.phi(), 0.));
eg.setHwQual(3);
eg.setHwIso(1);
l1EgammaBxCollection->push_back(0, eg);
l1t::EGamma eg_emint_brec =
l1t::EGamma(reco::Candidate::PolarLorentzVector(mom_eint.pt(), mom_eint.eta(), mom_eint.phi(), 0.));
eg_emint_brec.setHwQual(5);
eg_emint_brec.setHwIso(1);
l1EgammaBxCollection->push_back(0, eg_emint_brec);
}
}
iEvent.put(std::move(l1EgammaBxCollection), "L1EGammaCollectionBXVWithCuts");
}
DEFINE_FWK_MODULE(L1EGammaEEProducer);
| 43.159763 | 120 | 0.643406 | [
"object",
"vector",
"3d"
] |
61cdbe9932b4ff62542e4ac971b89dac33f13336 | 23,452 | cc | C++ | cc/scheduler/scheduler_unittest.cc | hujiajie/pa-chromium | 1816ff80336a6efd1616f9e936880af460b1e105 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2020-05-03T06:33:56.000Z | 2021-11-14T18:39:42.000Z | cc/scheduler/scheduler_unittest.cc | hujiajie/pa-chromium | 1816ff80336a6efd1616f9e936880af460b1e105 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | cc/scheduler/scheduler_unittest.cc | hujiajie/pa-chromium | 1816ff80336a6efd1616f9e936880af460b1e105 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "cc/scheduler/scheduler.h"
#include <string>
#include <vector>
#include "base/logging.h"
#include "cc/test/scheduler_test_common.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#define EXPECT_ACTION(action, client, action_index, expected_num_actions) \
EXPECT_EQ(expected_num_actions, client.num_actions_()); \
ASSERT_LT(action_index, client.num_actions_()); \
do { \
EXPECT_STREQ(action, client.Action(action_index)); \
for (int i = expected_num_actions; i < client.num_actions_(); ++i) \
ADD_FAILURE() << "Unexpected action: " << client.Action(i) << \
" with state:\n" << client.StateForAction(action_index); \
} while (false)
#define EXPECT_SINGLE_ACTION(action, client) \
EXPECT_ACTION(action, client, 0, 1)
namespace cc {
namespace {
class FakeSchedulerClient : public SchedulerClient {
public:
FakeSchedulerClient() { Reset(); }
void Reset() {
actions_.clear();
states_.clear();
draw_will_happen_ = true;
swap_will_happen_if_draw_happens_ = true;
num_draws_ = 0;
}
Scheduler* CreateScheduler(
scoped_ptr<FrameRateController> frame_rate_controller,
const SchedulerSettings& settings) {
scheduler_ =
Scheduler::Create(this, frame_rate_controller.Pass(), settings);
return scheduler_.get();
}
int num_draws() const { return num_draws_; }
int num_actions_() const { return static_cast<int>(actions_.size()); }
const char* Action(int i) const { return actions_[i]; }
std::string StateForAction(int i) const { return states_[i]; }
bool HasAction(const char* action) const {
for (size_t i = 0; i < actions_.size(); i++)
if (!strcmp(actions_[i], action))
return true;
return false;
}
void SetDrawWillHappen(bool draw_will_happen) {
draw_will_happen_ = draw_will_happen;
}
void SetSwapWillHappenIfDrawHappens(bool swap_will_happen_if_draw_happens) {
swap_will_happen_if_draw_happens_ = swap_will_happen_if_draw_happens;
}
// Scheduler Implementation.
virtual void ScheduledActionSendBeginFrameToMainThread() OVERRIDE {
actions_.push_back("ScheduledActionSendBeginFrameToMainThread");
states_.push_back(scheduler_->StateAsStringForTesting());
}
virtual ScheduledActionDrawAndSwapResult
ScheduledActionDrawAndSwapIfPossible() OVERRIDE {
actions_.push_back("ScheduledActionDrawAndSwapIfPossible");
states_.push_back(scheduler_->StateAsStringForTesting());
num_draws_++;
return ScheduledActionDrawAndSwapResult(draw_will_happen_,
draw_will_happen_ &&
swap_will_happen_if_draw_happens_);
}
virtual ScheduledActionDrawAndSwapResult ScheduledActionDrawAndSwapForced()
OVERRIDE {
actions_.push_back("ScheduledActionDrawAndSwapForced");
states_.push_back(scheduler_->StateAsStringForTesting());
return ScheduledActionDrawAndSwapResult(true,
swap_will_happen_if_draw_happens_);
}
virtual void ScheduledActionCommit() OVERRIDE {
actions_.push_back("ScheduledActionCommit");
states_.push_back(scheduler_->StateAsStringForTesting());
}
virtual void ScheduledActionCheckForCompletedTileUploads() OVERRIDE {
actions_.push_back("ScheduledActionCheckForCompletedTileUploads");
states_.push_back(scheduler_->StateAsStringForTesting());
}
virtual void ScheduledActionActivatePendingTreeIfNeeded() OVERRIDE {
actions_.push_back("ScheduledActionActivatePendingTreeIfNeeded");
states_.push_back(scheduler_->StateAsStringForTesting());
}
virtual void ScheduledActionBeginOutputSurfaceCreation() OVERRIDE {
actions_.push_back("ScheduledActionBeginOutputSurfaceCreation");
states_.push_back(scheduler_->StateAsStringForTesting());
}
virtual void ScheduledActionAcquireLayerTexturesForMainThread() OVERRIDE {
actions_.push_back("ScheduledActionAcquireLayerTexturesForMainThread");
states_.push_back(scheduler_->StateAsStringForTesting());
}
virtual void DidAnticipatedDrawTimeChange(base::TimeTicks) OVERRIDE {}
virtual base::TimeDelta DrawDurationEstimate() OVERRIDE {
return base::TimeDelta();
}
protected:
bool draw_will_happen_;
bool swap_will_happen_if_draw_happens_;
int num_draws_;
std::vector<const char*> actions_;
std::vector<std::string> states_;
scoped_ptr<Scheduler> scheduler_;
};
TEST(SchedulerTest, InitializeOutputSurfaceDoesNotBeginFrame) {
FakeSchedulerClient client;
scoped_refptr<FakeTimeSource> time_source(new FakeTimeSource());
SchedulerSettings default_scheduler_settings;
Scheduler* scheduler = client.CreateScheduler(
make_scoped_ptr(new FrameRateController(time_source)),
default_scheduler_settings);
scheduler->SetCanStart();
scheduler->SetVisible(true);
scheduler->SetCanDraw(true);
EXPECT_SINGLE_ACTION("ScheduledActionBeginOutputSurfaceCreation", client);
client.Reset();
scheduler->DidCreateAndInitializeOutputSurface();
EXPECT_EQ(0, client.num_actions_());
}
TEST(SchedulerTest, RequestCommit) {
FakeSchedulerClient client;
scoped_refptr<FakeTimeSource> time_source(new FakeTimeSource());
SchedulerSettings default_scheduler_settings;
Scheduler* scheduler = client.CreateScheduler(
make_scoped_ptr(new FrameRateController(time_source)),
default_scheduler_settings);
scheduler->SetCanStart();
scheduler->SetVisible(true);
scheduler->SetCanDraw(true);
EXPECT_SINGLE_ACTION("ScheduledActionBeginOutputSurfaceCreation", client);
client.Reset();
scheduler->DidCreateAndInitializeOutputSurface();
// SetNeedsCommit should begin the frame.
scheduler->SetNeedsCommit();
EXPECT_SINGLE_ACTION("ScheduledActionSendBeginFrameToMainThread", client);
EXPECT_FALSE(time_source->Active());
client.Reset();
// FinishCommit should commit
scheduler->FinishCommit();
EXPECT_SINGLE_ACTION("ScheduledActionCommit", client);
EXPECT_TRUE(time_source->Active());
client.Reset();
// Tick should draw.
time_source->Tick();
EXPECT_SINGLE_ACTION("ScheduledActionDrawAndSwapIfPossible", client);
EXPECT_FALSE(time_source->Active());
client.Reset();
// Timer should be off.
EXPECT_FALSE(time_source->Active());
}
TEST(SchedulerTest, RequestCommitAfterBeginFrameSentToMainThread) {
FakeSchedulerClient client;
scoped_refptr<FakeTimeSource> time_source(new FakeTimeSource());
SchedulerSettings default_scheduler_settings;
Scheduler* scheduler = client.CreateScheduler(
make_scoped_ptr(new FrameRateController(time_source)),
default_scheduler_settings);
scheduler->SetCanStart();
scheduler->SetVisible(true);
scheduler->SetCanDraw(true);
EXPECT_SINGLE_ACTION("ScheduledActionBeginOutputSurfaceCreation", client);
client.Reset();
scheduler->DidCreateAndInitializeOutputSurface();
// SetNedsCommit should begin the frame.
scheduler->SetNeedsCommit();
EXPECT_SINGLE_ACTION("ScheduledActionSendBeginFrameToMainThread", client);
client.Reset();
// Now SetNeedsCommit again. Calling here means we need a second frame.
scheduler->SetNeedsCommit();
// Since another commit is needed, FinishCommit should commit,
// then begin another frame.
scheduler->FinishCommit();
EXPECT_SINGLE_ACTION("ScheduledActionCommit", client);
client.Reset();
// Tick should draw but then begin another frame.
time_source->Tick();
EXPECT_FALSE(time_source->Active());
EXPECT_ACTION("ScheduledActionDrawAndSwapIfPossible", client, 0, 2);
EXPECT_ACTION("ScheduledActionSendBeginFrameToMainThread", client, 1, 2);
client.Reset();
}
TEST(SchedulerTest, TextureAcquisitionCausesCommitInsteadOfDraw) {
FakeSchedulerClient client;
scoped_refptr<FakeTimeSource> time_source(new FakeTimeSource());
SchedulerSettings default_scheduler_settings;
Scheduler* scheduler = client.CreateScheduler(
make_scoped_ptr(new FrameRateController(time_source)),
default_scheduler_settings);
scheduler->SetCanStart();
scheduler->SetVisible(true);
scheduler->SetCanDraw(true);
EXPECT_SINGLE_ACTION("ScheduledActionBeginOutputSurfaceCreation", client);
client.Reset();
scheduler->DidCreateAndInitializeOutputSurface();
scheduler->SetNeedsRedraw();
EXPECT_TRUE(scheduler->RedrawPending());
EXPECT_TRUE(time_source->Active());
time_source->Tick();
EXPECT_ACTION("ScheduledActionDrawAndSwapIfPossible", client, 0, 1);
EXPECT_FALSE(scheduler->RedrawPending());
EXPECT_FALSE(time_source->Active());
client.Reset();
scheduler->SetMainThreadNeedsLayerTextures();
EXPECT_ACTION("ScheduledActionAcquireLayerTexturesForMainThread",
client,
0,
2);
// A commit was started by SetMainThreadNeedsLayerTextures().
EXPECT_ACTION("ScheduledActionSendBeginFrameToMainThread", client, 1, 2);
client.Reset();
scheduler->SetNeedsRedraw();
EXPECT_TRUE(scheduler->RedrawPending());
EXPECT_TRUE(time_source->Active());
// No draw happens since the textures are acquired by the main thread.
time_source->Tick();
EXPECT_EQ(0, client.num_actions_());
EXPECT_TRUE(scheduler->RedrawPending());
EXPECT_TRUE(time_source->Active());
scheduler->FinishCommit();
EXPECT_ACTION("ScheduledActionCommit", client, 0, 1);
EXPECT_TRUE(scheduler->RedrawPending());
EXPECT_TRUE(time_source->Active());
client.Reset();
// Now we can draw again after the commit happens.
time_source->Tick();
EXPECT_ACTION("ScheduledActionDrawAndSwapIfPossible", client, 0, 1);
EXPECT_FALSE(scheduler->RedrawPending());
EXPECT_FALSE(time_source->Active());
client.Reset();
}
TEST(SchedulerTest, TextureAcquisitionCollision) {
FakeSchedulerClient client;
scoped_refptr<FakeTimeSource> time_source(new FakeTimeSource());
SchedulerSettings default_scheduler_settings;
Scheduler* scheduler = client.CreateScheduler(
make_scoped_ptr(new FrameRateController(time_source)),
default_scheduler_settings);
scheduler->SetCanStart();
scheduler->SetVisible(true);
scheduler->SetCanDraw(true);
EXPECT_SINGLE_ACTION("ScheduledActionBeginOutputSurfaceCreation", client);
client.Reset();
scheduler->DidCreateAndInitializeOutputSurface();
scheduler->SetNeedsCommit();
scheduler->SetMainThreadNeedsLayerTextures();
EXPECT_ACTION("ScheduledActionSendBeginFrameToMainThread", client, 0, 2);
EXPECT_ACTION("ScheduledActionAcquireLayerTexturesForMainThread",
client,
1,
2);
client.Reset();
// Compositor not scheduled to draw because textures are locked by main thread
EXPECT_FALSE(time_source->Active());
// Trigger the commit
scheduler->FinishCommit();
EXPECT_TRUE(time_source->Active());
client.Reset();
// Between commit and draw, texture acquisition for main thread delayed,
// and main thread blocks.
scheduler->SetMainThreadNeedsLayerTextures();
EXPECT_EQ(0, client.num_actions_());
client.Reset();
// Once compositor draw complete, the delayed texture acquisition fires.
time_source->Tick();
EXPECT_ACTION("ScheduledActionDrawAndSwapIfPossible", client, 0, 3);
EXPECT_ACTION("ScheduledActionAcquireLayerTexturesForMainThread",
client,
1,
3);
EXPECT_ACTION("ScheduledActionSendBeginFrameToMainThread", client, 2, 3);
client.Reset();
}
TEST(SchedulerTest, VisibilitySwitchWithTextureAcquisition) {
FakeSchedulerClient client;
scoped_refptr<FakeTimeSource> time_source(new FakeTimeSource());
SchedulerSettings default_scheduler_settings;
Scheduler* scheduler = client.CreateScheduler(
make_scoped_ptr(new FrameRateController(time_source)),
default_scheduler_settings);
scheduler->SetCanStart();
scheduler->SetVisible(true);
scheduler->SetCanDraw(true);
EXPECT_SINGLE_ACTION("ScheduledActionBeginOutputSurfaceCreation", client);
client.Reset();
scheduler->DidCreateAndInitializeOutputSurface();
scheduler->SetNeedsCommit();
scheduler->FinishCommit();
scheduler->SetMainThreadNeedsLayerTextures();
client.Reset();
// Verify that pending texture acquisition fires when visibility
// is lost in order to avoid a deadlock.
scheduler->SetVisible(false);
EXPECT_SINGLE_ACTION("ScheduledActionAcquireLayerTexturesForMainThread",
client);
client.Reset();
// Regaining visibility with textures acquired by main thread while
// compositor is waiting for first draw should result in a request
// for a new frame in order to escape a deadlock.
scheduler->SetVisible(true);
EXPECT_SINGLE_ACTION("ScheduledActionSendBeginFrameToMainThread", client);
client.Reset();
}
class SchedulerClientThatsetNeedsDrawInsideDraw : public FakeSchedulerClient {
public:
virtual void ScheduledActionSendBeginFrameToMainThread() OVERRIDE {}
virtual ScheduledActionDrawAndSwapResult
ScheduledActionDrawAndSwapIfPossible() OVERRIDE {
// Only SetNeedsRedraw the first time this is called
if (!num_draws_)
scheduler_->SetNeedsRedraw();
return FakeSchedulerClient::ScheduledActionDrawAndSwapIfPossible();
}
virtual ScheduledActionDrawAndSwapResult ScheduledActionDrawAndSwapForced()
OVERRIDE {
NOTREACHED();
return ScheduledActionDrawAndSwapResult(true, true);
}
virtual void ScheduledActionCommit() OVERRIDE {}
virtual void ScheduledActionBeginOutputSurfaceCreation() OVERRIDE {}
virtual void DidAnticipatedDrawTimeChange(base::TimeTicks) OVERRIDE {}
};
// Tests for two different situations:
// 1. the scheduler dropping SetNeedsRedraw requests that happen inside
// a ScheduledActionDrawAndSwap
// 2. the scheduler drawing twice inside a single tick
TEST(SchedulerTest, RequestRedrawInsideDraw) {
SchedulerClientThatsetNeedsDrawInsideDraw client;
scoped_refptr<FakeTimeSource> time_source(new FakeTimeSource());
SchedulerSettings default_scheduler_settings;
Scheduler* scheduler = client.CreateScheduler(
make_scoped_ptr(new FrameRateController(time_source)),
default_scheduler_settings);
scheduler->SetCanStart();
scheduler->SetVisible(true);
scheduler->SetCanDraw(true);
scheduler->DidCreateAndInitializeOutputSurface();
scheduler->SetNeedsRedraw();
EXPECT_TRUE(scheduler->RedrawPending());
EXPECT_TRUE(time_source->Active());
EXPECT_EQ(0, client.num_draws());
time_source->Tick();
EXPECT_EQ(1, client.num_draws());
EXPECT_TRUE(scheduler->RedrawPending());
EXPECT_TRUE(time_source->Active());
time_source->Tick();
EXPECT_EQ(2, client.num_draws());
EXPECT_FALSE(scheduler->RedrawPending());
EXPECT_FALSE(time_source->Active());
}
// Test that requesting redraw inside a failed draw doesn't lose the request.
TEST(SchedulerTest, RequestRedrawInsideFailedDraw) {
SchedulerClientThatsetNeedsDrawInsideDraw client;
scoped_refptr<FakeTimeSource> time_source(new FakeTimeSource());
SchedulerSettings default_scheduler_settings;
Scheduler* scheduler = client.CreateScheduler(
make_scoped_ptr(new FrameRateController(time_source)),
default_scheduler_settings);
scheduler->SetCanStart();
scheduler->SetVisible(true);
scheduler->SetCanDraw(true);
scheduler->DidCreateAndInitializeOutputSurface();
client.SetDrawWillHappen(false);
scheduler->SetNeedsRedraw();
EXPECT_TRUE(scheduler->RedrawPending());
EXPECT_TRUE(time_source->Active());
EXPECT_EQ(0, client.num_draws());
// Fail the draw.
time_source->Tick();
EXPECT_EQ(1, client.num_draws());
// We have a commit pending and the draw failed, and we didn't lose the redraw
// request.
EXPECT_TRUE(scheduler->CommitPending());
EXPECT_TRUE(scheduler->RedrawPending());
EXPECT_TRUE(time_source->Active());
// Fail the draw again.
time_source->Tick();
EXPECT_EQ(2, client.num_draws());
EXPECT_TRUE(scheduler->CommitPending());
EXPECT_TRUE(scheduler->RedrawPending());
EXPECT_TRUE(time_source->Active());
// Draw successfully.
client.SetDrawWillHappen(true);
time_source->Tick();
EXPECT_EQ(3, client.num_draws());
EXPECT_TRUE(scheduler->CommitPending());
EXPECT_FALSE(scheduler->RedrawPending());
EXPECT_FALSE(time_source->Active());
}
class SchedulerClientThatsetNeedsCommitInsideDraw : public FakeSchedulerClient {
public:
virtual void ScheduledActionSendBeginFrameToMainThread() OVERRIDE {}
virtual ScheduledActionDrawAndSwapResult
ScheduledActionDrawAndSwapIfPossible() OVERRIDE {
// Only SetNeedsCommit the first time this is called
if (!num_draws_)
scheduler_->SetNeedsCommit();
return FakeSchedulerClient::ScheduledActionDrawAndSwapIfPossible();
}
virtual ScheduledActionDrawAndSwapResult ScheduledActionDrawAndSwapForced()
OVERRIDE {
NOTREACHED();
return ScheduledActionDrawAndSwapResult(true, true);
}
virtual void ScheduledActionCommit() OVERRIDE {}
virtual void ScheduledActionBeginOutputSurfaceCreation() OVERRIDE {}
virtual void DidAnticipatedDrawTimeChange(base::TimeTicks) OVERRIDE {}
};
// Tests for the scheduler infinite-looping on SetNeedsCommit requests that
// happen inside a ScheduledActionDrawAndSwap
TEST(SchedulerTest, RequestCommitInsideDraw) {
SchedulerClientThatsetNeedsCommitInsideDraw client;
scoped_refptr<FakeTimeSource> time_source(new FakeTimeSource());
SchedulerSettings default_scheduler_settings;
Scheduler* scheduler = client.CreateScheduler(
make_scoped_ptr(new FrameRateController(time_source)),
default_scheduler_settings);
scheduler->SetCanStart();
scheduler->SetVisible(true);
scheduler->SetCanDraw(true);
scheduler->DidCreateAndInitializeOutputSurface();
scheduler->SetNeedsRedraw();
EXPECT_TRUE(scheduler->RedrawPending());
EXPECT_EQ(0, client.num_draws());
EXPECT_TRUE(time_source->Active());
time_source->Tick();
EXPECT_FALSE(time_source->Active());
EXPECT_EQ(1, client.num_draws());
EXPECT_TRUE(scheduler->CommitPending());
scheduler->FinishCommit();
time_source->Tick();
EXPECT_EQ(2, client.num_draws());
EXPECT_FALSE(time_source->Active());
EXPECT_FALSE(scheduler->RedrawPending());
}
// Tests that when a draw fails then the pending commit should not be dropped.
TEST(SchedulerTest, RequestCommitInsideFailedDraw) {
SchedulerClientThatsetNeedsDrawInsideDraw client;
scoped_refptr<FakeTimeSource> time_source(new FakeTimeSource());
SchedulerSettings default_scheduler_settings;
Scheduler* scheduler = client.CreateScheduler(
make_scoped_ptr(new FrameRateController(time_source)),
default_scheduler_settings);
scheduler->SetCanStart();
scheduler->SetVisible(true);
scheduler->SetCanDraw(true);
scheduler->DidCreateAndInitializeOutputSurface();
client.SetDrawWillHappen(false);
scheduler->SetNeedsRedraw();
EXPECT_TRUE(scheduler->RedrawPending());
EXPECT_TRUE(time_source->Active());
EXPECT_EQ(0, client.num_draws());
// Fail the draw.
time_source->Tick();
EXPECT_EQ(1, client.num_draws());
// We have a commit pending and the draw failed, and we didn't lose the commit
// request.
EXPECT_TRUE(scheduler->CommitPending());
EXPECT_TRUE(scheduler->RedrawPending());
EXPECT_TRUE(time_source->Active());
// Fail the draw again.
time_source->Tick();
EXPECT_EQ(2, client.num_draws());
EXPECT_TRUE(scheduler->CommitPending());
EXPECT_TRUE(scheduler->RedrawPending());
EXPECT_TRUE(time_source->Active());
// Draw successfully.
client.SetDrawWillHappen(true);
time_source->Tick();
EXPECT_EQ(3, client.num_draws());
EXPECT_TRUE(scheduler->CommitPending());
EXPECT_FALSE(scheduler->RedrawPending());
EXPECT_FALSE(time_source->Active());
}
TEST(SchedulerTest, NoSwapWhenDrawFails) {
scoped_refptr<FakeTimeSource> time_source(new FakeTimeSource());
SchedulerClientThatsetNeedsCommitInsideDraw client;
scoped_ptr<FakeFrameRateController> controller(
new FakeFrameRateController(time_source));
FakeFrameRateController* controller_ptr = controller.get();
SchedulerSettings default_scheduler_settings;
Scheduler* scheduler = client.CreateScheduler(
controller.PassAs<FrameRateController>(),
default_scheduler_settings);
scheduler->SetCanStart();
scheduler->SetVisible(true);
scheduler->SetCanDraw(true);
scheduler->DidCreateAndInitializeOutputSurface();
EXPECT_EQ(0, controller_ptr->NumFramesPending());
scheduler->SetNeedsRedraw();
EXPECT_TRUE(scheduler->RedrawPending());
EXPECT_TRUE(time_source->Active());
EXPECT_EQ(0, client.num_draws());
// Draw successfully, this starts a new frame.
time_source->Tick();
EXPECT_EQ(1, client.num_draws());
EXPECT_EQ(1, controller_ptr->NumFramesPending());
scheduler->DidSwapBuffersComplete();
EXPECT_EQ(0, controller_ptr->NumFramesPending());
scheduler->SetNeedsRedraw();
EXPECT_TRUE(scheduler->RedrawPending());
EXPECT_TRUE(time_source->Active());
// Fail to draw, this should not start a frame.
client.SetDrawWillHappen(false);
time_source->Tick();
EXPECT_EQ(2, client.num_draws());
EXPECT_EQ(0, controller_ptr->NumFramesPending());
}
TEST(SchedulerTest, NoSwapWhenSwapFailsDuringForcedCommit) {
scoped_refptr<FakeTimeSource> time_source(new FakeTimeSource());
FakeSchedulerClient client;
scoped_ptr<FakeFrameRateController> controller(
new FakeFrameRateController(time_source));
FakeFrameRateController* controller_ptr = controller.get();
SchedulerSettings default_scheduler_settings;
Scheduler* scheduler = client.CreateScheduler(
controller.PassAs<FrameRateController>(),
default_scheduler_settings);
EXPECT_EQ(0, controller_ptr->NumFramesPending());
// Tell the client that it will fail to swap.
client.SetDrawWillHappen(true);
client.SetSwapWillHappenIfDrawHappens(false);
// Get the compositor to do a ScheduledActionDrawAndSwapForced.
scheduler->SetNeedsRedraw();
scheduler->SetNeedsForcedRedraw();
EXPECT_TRUE(client.HasAction("ScheduledActionDrawAndSwapForced"));
// We should not have told the frame rate controller that we began a frame.
EXPECT_EQ(0, controller_ptr->NumFramesPending());
}
TEST(SchedulerTest, RecreateOutputSurfaceClearsPendingDrawCount) {
scoped_refptr<FakeTimeSource> time_source(new FakeTimeSource());
FakeSchedulerClient client;
scoped_ptr<FakeFrameRateController> controller(
new FakeFrameRateController(time_source));
FakeFrameRateController* controller_ptr = controller.get();
SchedulerSettings default_scheduler_settings;
Scheduler* scheduler = client.CreateScheduler(
controller.PassAs<FrameRateController>(),
default_scheduler_settings);
scheduler->SetCanStart();
scheduler->SetVisible(true);
scheduler->SetCanDraw(true);
scheduler->DidCreateAndInitializeOutputSurface();
// Draw successfully, this starts a new frame.
scheduler->SetNeedsRedraw();
time_source->Tick();
EXPECT_EQ(1, controller_ptr->NumFramesPending());
scheduler->DidLoseOutputSurface();
// Verifying that it's 1 so that we know that it's reset on recreate.
EXPECT_EQ(1, controller_ptr->NumFramesPending());
scheduler->DidCreateAndInitializeOutputSurface();
EXPECT_EQ(0, controller_ptr->NumFramesPending());
}
} // namespace
} // namespace cc
| 35.914242 | 80 | 0.758485 | [
"vector"
] |
61d2a89ef25e270c9e161bd40829550697703a09 | 19,418 | cpp | C++ | Glitter/Sources/main.cpp | pasannissanka/Glitter_LearnOpenGL | 95b6a66539edf5c4f39e569cf725ca4dd5665d68 | [
"Unlicense",
"MIT"
] | null | null | null | Glitter/Sources/main.cpp | pasannissanka/Glitter_LearnOpenGL | 95b6a66539edf5c4f39e569cf725ca4dd5665d68 | [
"Unlicense",
"MIT"
] | null | null | null | Glitter/Sources/main.cpp | pasannissanka/Glitter_LearnOpenGL | 95b6a66539edf5c4f39e569cf725ca4dd5665d68 | [
"Unlicense",
"MIT"
] | null | null | null | /* https://learnopengl.com/
*/
// Local Headers
#include "glitter.hpp"
#include "Shader.hpp"
#include "Camera.hpp"
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
// Imgui Headers
#include "imgui.h"
#include "backends/imgui_impl_glfw.h"
#include "backends/imgui_impl_opengl3.h"
// System Headers
#include <glad/glad.h>
#include <GLFW/glfw3.h>
// Standard Headers
#include <cstdlib>
#include <string>
#include <iostream>
// -------------------------------------------------------------------------------------------------------------
// FUNCTION PROTOTYPES
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void processInput(GLFWwindow* window);
void mouse_callback(GLFWwindow* window, double xpos, double ypos);
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset);
unsigned int loadTexture(std::string source);
void imguiWindow();
// -------------------------------------------------------------------------------------------------------------
// GLOBAL VARIABLES
// camera
Camera camera(glm::vec3(0.0f, 0.0f, 3.0f));
float lastX = mWidth / 2.0f;
float lastY = mHeight / 2.0f;
bool firstMouse = true;
bool cameraDisable = false;
// timing
float deltaTime = 0.0f; // Time between current frame and last frame
float lastFrame = 0.0f; // Time of last frame
// imgui
bool show_demo_window = false;
bool show_another_window = false;
ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
// light cube position
glm::vec3 lightPos(1.2f, 1.0f, 2.0f);
// -------------------------------------------------------------------------------------------------------------
int main(int argc, char* argv[])
{
// ---------------------------------------------------------------------------------------------------------
// Load GLFW and Create a Window
glfwInit();
const char* glsl_version = "#version 130";
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
auto mWindow = glfwCreateWindow(mWidth, mHeight, "OpenGL", nullptr, nullptr);
// Check for Valid Context
if (mWindow == nullptr) {
std::cout << "Failed to Create OpenGL Context" << std::endl;
return EXIT_FAILURE;
}
// Create Context and Load OpenGL Functions
glfwMakeContextCurrent(mWindow);
glfwSetFramebufferSizeCallback(mWindow, framebuffer_size_callback);
gladLoadGLLoader((GLADloadproc)glfwGetProcAddress);
std::cout << "OpenGL" << glGetString(GL_VERSION) << std::endl;
// Setup Dear ImGui context
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
//io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
//io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
// Setup Dear ImGui style
ImGui::StyleColorsDark(); //ImGui::StyleColorsClassic();
// Setup Platform/Renderer backends
ImGui_ImplGlfw_InitForOpenGL(mWindow, true); ImGui_ImplOpenGL3_Init(glsl_version);
glfwSetCursorPosCallback(mWindow, mouse_callback);
glfwSetScrollCallback(mWindow, scroll_callback);
glfwSetInputMode(mWindow, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
// configure global opengl state
glEnable(GL_DEPTH_TEST);
// ---------------------------------------------------------------------------------------------------------
// SHADER INIT
// Container's shaders
Shader lightingShader("vertex_shader_lighting.glsl", "fragment_shader_lighting.glsl");
// Light cube's shaders
Shader lightCubeShader("vertex_shader_light_cube.glsl", "fragment_shader_light_cube.glsl");
// ---------------------------------------------------------------------------------------------------------
// BUFFER
float vertices[] = {
// positions // normals // texture coords
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f,
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f,
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f,
0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f,
0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f
};
// world space positions of our cubes
glm::vec3 cubePositions[] = {
glm::vec3(0.0f, 0.0f, 0.0f),
glm::vec3(2.0f, 5.0f, -15.0f),
glm::vec3(-1.5f, -2.2f, -2.5f),
glm::vec3(-3.8f, -2.0f, -12.3f),
glm::vec3(2.4f, -0.4f, -3.5f),
glm::vec3(-1.7f, 3.0f, -7.5f),
glm::vec3(1.3f, -2.0f, -2.5f),
glm::vec3(1.5f, 2.0f, -2.5f),
glm::vec3(1.5f, 0.2f, -1.5f),
glm::vec3(-1.3f, 1.0f, -1.5f)
};
unsigned int VBO, VAO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glBindVertexArray(VAO);
// position attribute
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// normal attribute
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
// texture coord attribute
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float)));
glEnableVertexAttribArray(2);
// second, configure the light's VAO (VBO stays the same; the vertices are the same for the light object which is also a 3D cube)
unsigned int lightCubeVAO;
glGenVertexArrays(1, &lightCubeVAO);
glBindVertexArray(lightCubeVAO);
// we only need to bind to the VBO (to link it with glVertexAttribPointer),
// no need to fill it; the VBO's data already contains all we need (it's already bound, but we do it again for educational purposes)
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// ---------------------------------------------------------------------------------------------------------
// TEXTURE
unsigned int diffuseMap = loadTexture("container2.png");
unsigned int specularMap = loadTexture("container2_specular.png");
// ---------------------------------------------------------------------------------------------------------
lightingShader.Use();
lightingShader.setInt("material.diffuse", 0);
lightingShader.setInt("material.specular", 1);
// ---------------------------------------------------------------------------------------------------------
// Rendering Loop
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
while (glfwWindowShouldClose(mWindow) == false) {
// Background Fill Color
// glClearColor(0.25f, 0.25f, 0.25f, 1.0f);
glClearColor(0.1f, 0.1f, 0.1f, 1.0f); // Darker
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
double currentFrame = glfwGetTime();
deltaTime = currentFrame - lastFrame;
lastFrame = currentFrame;
processInput(mWindow);
// use Shader
lightingShader.Use();
lightingShader.setVec3("viewPos", camera.Position);
// lightingShader.setVec3("light.direction", -0.2f, -1.0f, -0.3f);
// lightingShader.setVec3("light.position", lightPos);
lightingShader.setVec3("light.position", camera.Position);
lightingShader.setVec3("light.direction", camera.Front);
lightingShader.setFloat("light.cutOff", glm::cos(glm::radians(12.5f)));
lightingShader.setFloat("light.outerCutOff", glm::cos(glm::radians(17.5f)));
// light properties
lightingShader.setVec3("light.ambient", 0.2f, 0.2f, 0.2f);
lightingShader.setVec3("light.diffuse", 0.5f, 0.5f, 0.5f);
lightingShader.setVec3("light.specular", 1.0f, 1.0f, 1.0f);
lightingShader.setFloat("light.constant", 1.0f);
lightingShader.setFloat("light.linear", 0.09f);
lightingShader.setFloat("light.quadratic", 0.032f);
// material properties
lightingShader.setFloat("material.shininess", 64.0f);
// -----------------------------------------------------------------------------------------------------
/*
// bind textures on corresponding texture units
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture1);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, texture2);
*/
// camera/view transformation
glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), (float)mWidth / (float)mHeight, 0.1f, 100.0f);
glm::mat4 view = camera.GetViewMatrix();
glm::mat4 model = glm::mat4(1.0f);
lightingShader.setMat4("projection", projection);
lightingShader.setMat4("view", view);
lightingShader.setMat4("model", model);
// bind diffuse map
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, diffuseMap);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, specularMap);
// render boxes
glBindVertexArray(VAO);
// glDrawArrays(GL_TRIANGLES, 0, 36);
for (unsigned int i = 0; i < 10; i++)
{
glm::mat4 model = glm::mat4(1.0f);
model = glm::translate(model, cubePositions[i]);
float angle = 20.0f * i;
model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f));
lightingShader.setMat4("model", model);
glDrawArrays(GL_TRIANGLES, 0, 36);
}
/*
// also draw the lamp object
lightCubeShader.Use();
lightCubeShader.setMat4("projection", projection);
lightCubeShader.setMat4("view", view);
model = glm::mat4(1.0f);
model = glm::translate(model, lightPos);
model = glm::scale(model, glm::vec3(0.2f)); // a smaller cube
lightCubeShader.setMat4("model", model);
glBindVertexArray(lightCubeVAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
*/
// -----------------------------------------------------------------------------------------------------
// Start the Dear ImGui frame
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
/*
// 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!).
if (cameraDisable)
ImGui::ShowDemoWindow(&show_demo_window);
*/
// 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window.
imguiWindow();
// 3. Show another simple window.
if (show_another_window)
{
ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked)
ImGui::Text("Hello from another window!");
if (ImGui::Button("Close Me"))
show_another_window = false;
ImGui::End();
}
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
// -----------------------------------------------------------------------------------------------------
// Flip Buffers and Draw
glfwSwapBuffers(mWindow);
glfwPollEvents();
}
// optional: de-allocate all resources once they've outlived their purpose:
glDeleteVertexArrays(1, &VAO);
glDeleteVertexArrays(1, &lightCubeVAO);
glDeleteBuffers(1, &VBO);
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
// glfw: terminate, clearing all previously allocated GLFW resources.
glfwTerminate();
return EXIT_SUCCESS;
}
// process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly
// ---------------------------------------------------------------------------------------------------------
void processInput(GLFWwindow* window)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
if (glfwGetKey(window, GLFW_KEY_TAB) == GLFW_PRESS) {
cameraDisable = glfwGetInputMode(window, GLFW_CURSOR) == GLFW_CURSOR_DISABLED;
if (cameraDisable)
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
else glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
}
// Movement
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
camera.ProcessKeyboard(Camera_Movement::FORWARD, deltaTime);
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
camera.ProcessKeyboard(Camera_Movement::BACKWARD, deltaTime);
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
camera.ProcessKeyboard(Camera_Movement::LEFT, deltaTime);
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
camera.ProcessKeyboard(Camera_Movement::RIGHT, deltaTime);
}
// glfw: whenever the window size changed (by OS or user resize) this callback function executes
// ---------------------------------------------------------------------------------------------------------
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
// make sure the viewport matches the new window dimensions; note that width and
// height will be significantly larger than specified on retina displays.
glViewport(0, 0, width, height);
}
// glfw: whenever the mouse moves, this callback is called
// ---------------------------------------------------------------------------------------------------------
void mouse_callback(GLFWwindow* window, double xpos, double ypos)
{
if (firstMouse)
{
lastX = xpos;
lastY = ypos;
firstMouse = false;
}
float xoffset = xpos - lastX;
float yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top
lastX = xpos;
lastY = ypos;
if (!cameraDisable)
camera.ProcessMouseMovement(xoffset, yoffset);
}
// glfw: whenever the mouse scroll wheel scrolls, this callback is called
// ---------------------------------------------------------------------------------------------------------
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
if (!cameraDisable)
camera.ProcessMouseScroll(yoffset);
}
// utility function for loading a 2D texture from file
// ---------------------------------------------------
unsigned int loadTexture(std::string source)
{
std::string texturePath = PROJECT_SOURCE_DIR "\\Glitter\\Shaders\\Assets\\";
unsigned int textureID;
glGenTextures(1, &textureID);
int width, height, nrComponents;
unsigned char* data = stbi_load((texturePath + source).c_str(), &width, &height, &nrComponents, 0);
if (data)
{
GLenum format;
if (nrComponents == 1)
format = GL_RED;
else if (nrComponents == 3)
format = GL_RGB;
else if (nrComponents == 4)
format = GL_RGBA;
glBindTexture(GL_TEXTURE_2D, textureID);
glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
stbi_image_free(data);
}
else
{
std::cout << "Texture failed to load at path: " << (texturePath + source) << std::endl;
stbi_image_free(data);
}
return textureID;
}
// ---------------------------------------------------------------------------------------------------------
void imguiWindow()
{
static float f = 0.0f;
static int counter = 0;
ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
ImGui::Checkbox("Another Window", &show_another_window);
ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
counter++;
ImGui::SameLine();
ImGui::Text("counter = %d", counter);
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
ImGui::End();
} | 41.849138 | 184 | 0.556648 | [
"render",
"object",
"model",
"3d"
] |
61d73627d9f9b74cd67bf51e9fc5aef8767a6545 | 4,805 | cpp | C++ | desktop/gl_helper/shape.cpp | astomih/rotation_master | a6647a956aaa5a3634356d6071f0fa2f00ed0907 | [
"Apache-2.0"
] | 2 | 2022-01-18T06:51:32.000Z | 2022-01-18T07:40:28.000Z | desktop/gl_helper/shape.cpp | astomih/rotation_master | a6647a956aaa5a3634356d6071f0fa2f00ed0907 | [
"Apache-2.0"
] | null | null | null | desktop/gl_helper/shape.cpp | astomih/rotation_master | a6647a956aaa5a3634356d6071f0fa2f00ed0907 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2022 iwatake2222
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 ***/
/* for general */
#include <cstdint>
#include <cstdio>
#include <vector>
#include <memory>
/* for GLFW */
#include <GL/glew.h> /* this must be before including glfw*/
#include <GLFW/glfw3.h>
/* for my modules */
#include "matrix.h"
#include "transformation_matrix.h"
#include "shader.h"
#include "shape.h"
/*** Macro ***/
/* macro function */
/* Setting */
/*** Global variable ***/
/*** Function ***/
Object::Object(GLuint position_loc, GLuint color_loc, const std::vector<Object::Vertex>& vertex_list, const std::vector<GLuint>& index_list)
{
glGenVertexArrays(1, &m_vao);
glBindVertexArray(m_vao);
glGenBuffers(1, &m_vbo);
glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
glBufferData(GL_ARRAY_BUFFER, vertex_list.size() * sizeof(Vertex), vertex_list.data(), GL_STATIC_DRAW);
glVertexAttribPointer(position_loc, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), static_cast<Vertex*>(0)->position);
glEnableVertexAttribArray(position_loc);
glVertexAttribPointer(color_loc, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), static_cast<Vertex*>(0)->color);
glEnableVertexAttribArray(color_loc);
glGenBuffers(1, &m_ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, index_list.size() * sizeof(GLuint), index_list.data(), GL_STATIC_DRAW);
}
Object::~Object()
{
glDeleteVertexArrays(1, &m_vao);
glDeleteBuffers(1, &m_vbo);
glDeleteBuffers(1, &m_ibo);
}
void Object::Bind() const
{
glBindVertexArray(m_vao);
}
Shape::Shape(const std::vector<Object::Vertex>& vertex_list, const std::vector<GLuint>& index_list)
{
/* Load Shader Program */
static const GLchar vsrc[] =
#ifdef __EMSCRIPTEN__
"#version 300 es\n"
"precision mediump float;\n"
#else
"#version 150 core\n"
#endif
"uniform mat4 modelviewprojection;\n"
"in vec4 position;\n"
"in vec4 color;\n"
"out vec4 vertex_color;\n"
"void main()\n"
"{\n"
" vertex_color = color;\n"
" gl_Position = modelviewprojection * position;\n"
"}";
static constexpr GLchar fsrc[] =
#ifdef __EMSCRIPTEN__
"#version 300 es\n"
"precision mediump float;\n"
#else
"#version 150 core\n"
#endif
"in vec4 vertex_color;\n"
"out vec4 fragment;\n"
"void main()\n"
"{\n"
" fragment = vertex_color;\n"
"}\n";
m_program_id = Shader::CreateShaderProgram(vsrc, fsrc);
GLint position_loc = glGetAttribLocation(m_program_id, "position");
GLint color_loc = glGetAttribLocation(m_program_id, "color");
m_modelviewprojection_loc = glGetUniformLocation(m_program_id, "modelviewprojection");
m_object = std::make_unique<Object>(position_loc, color_loc, vertex_list, index_list);
m_vertex_num = static_cast<GLsizei>(vertex_list.size());
m_index_num = static_cast<GLsizei>(index_list.size());
}
void Shape::Draw(const Matrix& viewprojection, const Matrix& model) const
{
glUseProgram(m_program_id);
const Matrix modelviewprojection = viewprojection * model;
glUniformMatrix4fv(m_modelviewprojection_loc, 1, GL_TRUE, modelviewprojection.Data());
m_object->Bind();
Execute();
}
void Shape::Execute() const
{
//glDrawArrays(GL_LINE_LOOP, 0, m_vertex_num);
glDrawArrays(GL_LINES, 0, m_vertex_num);
}
void Shape::SetLineWidth(float width)
{
glLineWidth(width);
}
ShapeIndex::ShapeIndex(const std::vector<Object::Vertex>& vertex_list, const std::vector<GLuint>& index_list)
: Shape(vertex_list, index_list)
{
// do nothing
}
void ShapeIndex::Execute() const
{
glDrawElements(GL_LINES, m_index_num, GL_UNSIGNED_INT, 0);
}
ShapeSolid::ShapeSolid(const std::vector<Object::Vertex>& vertex_list)
: Shape(vertex_list)
{
// do nothing
}
void ShapeSolid::Execute() const
{
glDrawArrays(GL_TRIANGLES, 0, m_vertex_num);
}
ShapeSolidIndex::ShapeSolidIndex(const std::vector<Object::Vertex>& vertex_list, const std::vector<GLuint>& index_list)
: Shape(vertex_list, index_list)
{
// do nothing
}
void ShapeSolidIndex::Execute() const
{
glDrawElements(GL_TRIANGLES, m_index_num, GL_UNSIGNED_INT, 0);
}
| 28.60119 | 140 | 0.690739 | [
"object",
"shape",
"vector",
"model"
] |
61e1ffb4c15342b58b13cce1bb13f8d416aad381 | 13,945 | cpp | C++ | ConnectionManagerDlg.cpp | wootpthomas/smagick | 55f36dcabfa9e987511f62fd50891c68c53903ba | [
"BSD-3-Clause"
] | null | null | null | ConnectionManagerDlg.cpp | wootpthomas/smagick | 55f36dcabfa9e987511f62fd50891c68c53903ba | [
"BSD-3-Clause"
] | null | null | null | ConnectionManagerDlg.cpp | wootpthomas/smagick | 55f36dcabfa9e987511f62fd50891c68c53903ba | [
"BSD-3-Clause"
] | null | null | null |
#include "MainWindowDlg.h"
#include "ConnectionManager.h"
#include "ConnectionManagerDlg.h"
#include "DataTypes.h"
ConnectionManagerDlg::ConnectionManagerDlg(MainWindowDlg *parent, ConnectionManager * const pConnectionMgr) :
QDialog(parent),
m_pConnManager(pConnectionMgr),
m_pConnectionModel(NULL)
{
setupUi(this);
init();
show();
}
ConnectionManagerDlg::~ConnectionManagerDlg()
{
if(m_pConnectionModel)
delete m_pConnectionModel;
if(m_pConnectionSelectionModel)
delete m_pConnectionSelectionModel;
if(m_pConnectionsInGroupModel)
delete m_pConnectionsInGroupModel;
if(m_pConnectionsInGroupSelectionModel)
delete m_pConnectionsInGroupSelectionModel;
if(m_pConnectionsAvailableToGroupSelectionModel)
delete m_pConnectionsAvailableToGroupSelectionModel;
//we don't delete the connection manager, we don't own it....
}
void ConnectionManagerDlg::init()
{
m_pConnectionModel = new ConnectionListModel();
m_pConnectionsInGroupModel = new ConnectionListModel();
//setup model/view for the list of individual connections
m_LstConnections->setModel(m_pConnectionModel);
m_pConnectionSelectionModel = m_LstConnections->selectionModel();
//setup model/view for the available groups
m_LstAvailableConnections->setModel( m_pConnectionModel );
m_pConnectionsAvailableToGroupSelectionModel = m_LstAvailableConnections->selectionModel();
//setup model/view for connections in group
m_LstConsInGroup->setModel( m_pConnectionsInGroupModel );
m_pConnectionsInGroupSelectionModel = m_LstConsInGroup->selectionModel();
m_HostPort->setValidator(new QIntValidator(1,65535, this));
//throw the connectionDetails into the model
populateConnectionList(m_pConnectionModel, m_pConnectionSelectionModel);
//throw the groupDetails into the model
populateGroupName();
//setup signals and slots
connect( m_OK, SIGNAL( clicked() ),
this, SLOT( slotOKClicked() ));
//Signals and slots for the individual connection stuff
connect( m_pConnectionSelectionModel, SIGNAL( selectionChanged(const QItemSelection &, const QItemSelection &) ),
this, SLOT( slotSelectConnection(const QItemSelection &, const QItemSelection &) ));
connect( m_NewConnection, SIGNAL( clicked() ),
this, SLOT( slotAddNewConnection() ));
connect( m_DeleteConnection, SIGNAL( clicked() ),
this, SLOT( slotRemoveConnection() ));
connect( m_HostAddress, SIGNAL( textEdited(const QString &) ),
this, SLOT( slotConnectionInformationChanged(const QString &) ));
connect( m_UserName, SIGNAL( textEdited(const QString &) ),
this, SLOT( slotConnectionInformationChanged(const QString &) ));
connect( m_Password, SIGNAL( textEdited(const QString &) ),
this, SLOT( slotConnectionInformationChanged(const QString &) ));
connect( m_PrivateKey, SIGNAL( textEdited(const QString &) ),
this, SLOT( slotConnectionInformationChanged(const QString &) ));
connect( m_HostPort, SIGNAL( textEdited(const QString &) ),
this, SLOT( slotConnectionInformationChanged(const QString &) ));
//Signals and slots for the group stuff
connect (m_GroupName, SIGNAL( editTextChanged(const QString &) ),
this, SLOT( slotSelectGroup(const QString &) ));
connect (m_NewGroup, SIGNAL( clicked() ),
this, SLOT( slotAddNewGroup() ));
connect (m_DeleteGroup, SIGNAL( clicked() ),
this, SLOT( slotRemoveGroup() ));
connect (m_AddToGroup, SIGNAL( clicked() ),
this, SLOT( slotAddToGroup() ));
connect (m_LstAvailableConnections, SIGNAL( doubleClicked(const QModelIndex &) ),
this, SLOT( slotAddToGroup() ));
connect (m_RemoveFromGroup, SIGNAL( clicked() ),
this, SLOT( slotRemoveFromGroup() ));
connect (m_LstConsInGroup, SIGNAL( doubleClicked(const QModelIndex &) ),
this, SLOT( slotRemoveFromGroup() ));
}
void ConnectionManagerDlg::slotOKClicked()
{
m_pConnectionSelectionModel->clear();
this->close();
}
void ConnectionManagerDlg::slotAddNewConnection()
{
QVariant tempVariant;
ConnectionDetails temp = ConnectionDetails::ConnectionDetails();
temp.hostAddress = "Host";
temp.username = "Username";
m_pConnectionModel->insertRows(0, 1);
tempVariant = qVariantFromValue<ConnectionDetails>(temp);
m_pConnectionModel->setData(m_pConnectionModel->index(0), tempVariant);
m_pConnectionSelectionModel->clear();
m_pConnectionSelectionModel->select( m_pConnectionModel->index(0), QItemSelectionModel::SelectCurrent);
m_HostAddress->setFocus();
m_HostAddress->selectAll();
}
void ConnectionManagerDlg::populateConnectionList(ConnectionListModel *model, QItemSelectionModel *selectionModel)
{
ConnectionDetails temp;
QVariant tempVariant;
QList<ConnectionDetails> myList = m_pConnManager->getConnectionDetails();
foreach(temp, myList) {
model->insertRows(0, 1);
tempVariant = qVariantFromValue<ConnectionDetails>(temp);
model->setData(model->index(0), tempVariant);
selectionModel->clear();
}
}
void ConnectionManagerDlg::populateGroupName()
{
m_GroupName->clear();
GroupDetails temp;
QVariant tempVariant;
QList<GroupDetails> myGroupList = m_pConnManager->getGroupDetails();
foreach(temp, myGroupList)
{
tempVariant = qVariantFromValue<GroupDetails>(temp);
m_GroupName->insertItem(0, temp.groupName, tempVariant);
m_GroupName->setCurrentIndex(-1);
}
}
void ConnectionManagerDlg::slotSelectGroup(const QString &text)
{
//setup variables to get the connections that are in the selected group
QList<ConnectionDetails> connectionList;
ConnectionDetails tempConnection;
GroupDetails tempGroup;
QVariant tempVariant;
int indexOfComboBox;
bool isSelectionValid = false;
indexOfComboBox = m_GroupName->findText(text);
if( indexOfComboBox == -1 )
{
//the text wasn't found the user is typing something unique.
if( m_GroupName->currentIndex() != -1 )
{
//we're renaming an existing one.
tempGroup = m_GroupName->itemData( m_GroupName->currentIndex() ).value<GroupDetails>();
tempGroup.groupName = text;
tempVariant = qVariantFromValue<GroupDetails>(tempGroup);
if( m_pConnManager->updateGroupDetails( tempGroup.groupID, tempGroup ) )
{
m_GroupName->setItemData( m_GroupName->currentIndex(), tempVariant );
m_GroupName->setItemText( m_GroupName->currentIndex(), tempGroup.groupName );
}
isSelectionValid = true;
}
} else {
//the data is valid populate the other information.
//get the details of the selected group
GroupDetails selectedGroupDetails = m_GroupName->itemData( indexOfComboBox).value<GroupDetails>();
//get the connections in the selected group
connectionList = m_pConnManager->getConnectionDetails( QString::number(selectedGroupDetails.groupID) );
//loop through the connections in the group
m_pConnectionsInGroupModel->removeRows(0, m_pConnectionsInGroupModel->rowCount());
foreach(tempConnection, connectionList)
{
m_pConnectionsInGroupModel->insertRows(0, 1);
tempVariant = qVariantFromValue<ConnectionDetails>(tempConnection);
m_pConnectionsInGroupModel->setData( m_pConnectionsInGroupModel->index(0), tempVariant );
m_pConnectionsInGroupSelectionModel->clear();
}
isSelectionValid = true;
}
//something happend to the group selection now set the enabled states of everything depending on isSelectionValid
m_AddToGroup->setEnabled(isSelectionValid);
m_RemoveFromGroup->setEnabled(isSelectionValid);
m_DeleteGroup->setEnabled(isSelectionValid);
m_LstAvailableConnections->setEnabled(isSelectionValid);
m_LstConsInGroup->setEnabled(isSelectionValid);
}
void ConnectionManagerDlg::slotSelectConnection(const QItemSelection ¤t, const QItemSelection &previous)
{
QModelIndexList indexes = current.indexes();
QModelIndexList oldIndexes = previous.indexes();
int countOfSelection = m_pConnectionSelectionModel->selectedIndexes().count();
if( current == previous )
return;
ConnectionDetails temp;
QModelIndex selectedIndex;
if( !previous.isEmpty() )
{
foreach(selectedIndex, previous.indexes() ) {
temp = m_pConnectionModel->data(selectedIndex, Qt::EditRole).value<ConnectionDetails>();
if( temp.isDirty )
{
if( m_pConnManager->updateConnectionDetails(temp.connectionID, &temp) )
{
m_pConnectionModel->setData(selectedIndex, qVariantFromValue(temp));
}
}
}
}
if( countOfSelection == 1 )
{
//only one selected this is the ideal state
this->m_HostAddress->setEnabled(true);
this->m_HostPort->setEnabled(true);
this->m_UserName->setEnabled(true);
this->m_Password->setEnabled(true);
this->m_PrivateKey->setEnabled(true);
this->m_Advanced->setEnabled(true);
this->m_DeleteConnection->setEnabled(true);
//Set the values of the gui fields
temp = m_pConnectionModel->data( m_pConnectionSelectionModel->selectedIndexes().at(0), Qt::EditRole).value<ConnectionDetails>();
this->m_HostAddress->setText(temp.hostAddress);
this->m_HostPort->setText(QString::number(temp.hostPort));
this->m_UserName->setText(temp.username);
this->m_Password->setText(temp.password);
this->m_PrivateKey->setText(temp.RSA_privateKey);
} else {
//current selection is undisplayable set the edit fields accordingly
m_HostAddress->setEnabled(false);
m_HostPort->setEnabled(false);
m_UserName->setEnabled(false);
m_Password->setEnabled(false);
m_PrivateKey->setEnabled(false);
m_Advanced->setEnabled(false);
m_HostAddress->setText("");
m_HostPort->setText("");
m_UserName->setText("");
m_Password->setText("");
m_PrivateKey->setText("");
if( countOfSelection > 1 )
{
//do specific things for the case multiple are selected
this->m_DeleteConnection->setEnabled(true);
} else {
// do specific things for the case none are selected.
this->m_DeleteConnection->setEnabled(false);
}
}
}
void ConnectionManagerDlg::slotConnectionInformationChanged(const QString & text)
{
QModelIndexList selected = this->m_pConnectionSelectionModel->selectedIndexes();
ConnectionDetails temp;
QVariant tempVariant;
if( selected.count() == 1 )
{
//ok lets put the changed stuff into the ConnectionDetails object of the model
QString hostName = this->m_HostAddress->text();
int hostPort = this->m_HostPort->text().toInt();
QString userName = this->m_UserName->text();
QString password = this->m_Password->text();
QString privateKey = this->m_PrivateKey->text();
temp = m_pConnectionModel->data( selected.at(0), Qt::EditRole ).value<ConnectionDetails>();
int connectionID = temp.connectionID;
temp.hostAddress = hostName;
temp.hostPort = hostPort;
temp.username = userName;
temp.password = password;
temp.RSA_privateKey = privateKey;
temp.isDirty = true;
tempVariant = qVariantFromValue<ConnectionDetails>(temp);
m_pConnectionModel->setData( selected.at(0), tempVariant);
}
}
void ConnectionManagerDlg::slotRemoveFromGroup()
{
QModelIndexList selected = m_pConnectionsInGroupSelectionModel->selectedIndexes();
int groupID = m_GroupName->itemData(m_GroupName->currentIndex()).value<GroupDetails>().groupID;
int selectedCount = selected.count();
QModelIndex index;
QVariant tempVariant;
ConnectionDetails temp;
foreach(index, selected)
{
temp = m_pConnectionsInGroupModel->data(index, Qt::EditRole).value<ConnectionDetails>();
if( m_pConnManager->removeConnectionFromGroup(groupID, temp.connectionID ) )
{
m_pConnectionsInGroupModel->removeRow(index);
}
}
m_pConnectionsInGroupSelectionModel->clear();
}
void ConnectionManagerDlg::slotAddToGroup()
{
QModelIndexList selected = m_pConnectionsAvailableToGroupSelectionModel->selectedIndexes();
int selectedCount = selected.count();
int currentGroupIndex = m_GroupName->currentIndex();
if( currentGroupIndex < 0 )
return; //no group was selected.
int groupID = m_GroupName->itemData(m_GroupName->currentIndex()).value<GroupDetails>().groupID;
QModelIndex index;
QVariant tempVariant;
ConnectionDetails temp;
foreach(index, selected)
{
temp = m_pConnectionModel->data(index, Qt::EditRole).value<ConnectionDetails>();
if( m_pConnManager->addConnectionToGroup(groupID, temp.connectionID) )
{
m_pConnectionsInGroupModel->insertRows(0, 1);
tempVariant = qVariantFromValue<ConnectionDetails>(temp);
m_pConnectionsInGroupModel->setData(m_pConnectionsInGroupModel->index(0), tempVariant);
m_pConnectionsInGroupSelectionModel->clear();
}
}
}
void ConnectionManagerDlg::slotAddNewGroup()
{
//first we call connection manager and get a new group
GroupDetails newGroup;
if( m_pConnManager->getNewGroup(newGroup) )
{
//then we repopulate the groupName dropDown
populateGroupName();
//then we select this new group
m_GroupName->setCurrentIndex( m_GroupName->findText(newGroup.groupName) );
m_GroupName->setFocus();
}
}
void ConnectionManagerDlg::slotRemoveConnection()
{
QModelIndexList selectionList = m_pConnectionSelectionModel->selectedIndexes();
QModelIndex currentSelection;
ConnectionDetails connectionToRemove;
if( selectionList.count() == 1 )
{
currentSelection = selectionList.at(0);
connectionToRemove = m_pConnectionModel->data(currentSelection, Qt::EditRole).value<ConnectionDetails>();
if( m_pConnManager->removeConnection(connectionToRemove.connectionID) )
{
m_pConnectionSelectionModel->clear();
m_pConnectionModel->removeRow(currentSelection);
}
}
}
void ConnectionManagerDlg::slotRemoveGroup()
{
//TODO: finish this
GroupDetails temp = m_GroupName->itemData( m_GroupName->currentIndex() ).value<GroupDetails>();
if( m_pConnManager->removeGroup(temp) )
{
m_GroupName->removeItem( m_GroupName->currentIndex() );
}
}
//TODO: add the functionality that it prepopulates the hostname and username fields when you make a new connection
| 35.483461 | 131 | 0.747723 | [
"object",
"model"
] |
61e5e3fcaa4b2ba6765cfb6e6f3319c354bae019 | 6,188 | cpp | C++ | project/Test/Source/Test/MyCharacter.cpp | ryulurala/study_unreal_cpp | f92bcf334f989555515659eac66c233763fb32c7 | [
"MIT"
] | null | null | null | project/Test/Source/Test/MyCharacter.cpp | ryulurala/study_unreal_cpp | f92bcf334f989555515659eac66c233763fb32c7 | [
"MIT"
] | null | null | null | project/Test/Source/Test/MyCharacter.cpp | ryulurala/study_unreal_cpp | f92bcf334f989555515659eac66c233763fb32c7 | [
"MIT"
] | null | null | null | ๏ปฟ// Fill out your copyright notice in the Description page of Project Settings.
#include "MyCharacter.h"
#include "GameFramework/SpringArmComponent.h"
#include "Camera/CameraComponent.h"
#include "Components/CapsuleComponent.h"
#include "MyAnimInstance.h"
#include "DrawDebugHelpers.h"
#include "MyHelm.h"
#include "MyStatComponent.h"
#include "Components/WidgetComponent.h"
#include "MyHpWidget.h"
#include "MyAIController.h"
// Sets default values
AMyCharacter::AMyCharacter()
{
// Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
SpringArm = CreateDefaultSubobject<USpringArmComponent>(TEXT("SPRINGARM"));
Camera = CreateDefaultSubobject<UCameraComponent>(TEXT("CAMERA"));
SpringArm->SetupAttachment(GetCapsuleComponent());
Camera->SetupAttachment(SpringArm);
SpringArm->TargetArmLength = 500.0f; // ๊ฑฐ๋ฆฌ
SpringArm->SetRelativeRotation(FRotator(-35.0f, 0.0f, 0.0f)); // ํ์
// -88.0f ๊ตญ๋ฃฐ: ๋
์์ 88.0f ๋งํผ ๊ณต์ค์ ๋ ์๋ ์ํ๋ฅผ ๋ฐ๋ฅ์ ๋ถ์ฌ๋๊ธฐ ์ํจ
// -90.0f: X๋ฐฉํฅ์ ์๋์ X๋ฐฉํฅ๊ณผ ๋ง์ถ๊ธฐ ์ํจ
GetMesh()->SetRelativeLocationAndRotation(FVector(0.0f, 0.0f, -88.0f), FRotator(0.0f, -90.0f, 0.0f));
ConstructorHelpers::FObjectFinder<USkeletalMesh> SK_PARAGON(TEXT("SkeletalMesh'/Game/ParagonGreystone/Characters/Heroes/Greystone/Meshes/Greystone.Greystone'"));
if (SK_PARAGON.Succeeded())
{
// Mesh๊ฐ ์ด๋ฏธ ์์๋ฐ์ Character class์ ์ ์ธ๋ผ์๋ค.
GetMesh()->SetSkeletalMesh(SK_PARAGON.Object);
}
Stat = CreateDefaultSubobject<UMyStatComponent>(TEXT("STAT"));
HpBar = CreateDefaultSubobject<UWidgetComponent>(TEXT("HPBAR"));
HpBar->SetupAttachment(GetMesh()); // Attach Mesh
HpBar->SetRelativeLocation(FVector(0.0f, 0.0f, 200.0f)); // ์บ๋ฆญํฐ ์์ ํ์
HpBar->SetWidgetSpace(EWidgetSpace::Screen); // Screen: never occluded
static ConstructorHelpers::FClassFinder<UUserWidget> WBP_HPBAR(TEXT("WidgetBlueprint'/Game/UI/WBP_HpBar.WBP_HpBar_C'"));
if (WBP_HPBAR.Succeeded())
{
HpBar->SetWidgetClass(WBP_HPBAR.Class);
HpBar->SetDrawSize(FVector2D(200.0f, 50.0f));
}
// AI Controller ํด๋์ค ์ง์
AIControllerClass = AMyAIController::StaticClass();
AutoPossessAI = EAutoPossessAI::PlacedInWorldOrSpawned; // AI ๋น์ ์์
}
void AMyCharacter::PostInitializeComponents()
{
Super::PostInitializeComponents();
AnimInstance = Cast<UMyAnimInstance>(GetMesh()->GetAnimInstance());
if (AnimInstance)
{
AnimInstance->OnMontageEnded.AddDynamic(this, &AMyCharacter::OnAttackMontageEnded);
AnimInstance->OnAttackHit.AddUObject(this, &AMyCharacter::AttackCheck);
}
// ์ด๊ธฐํ ๋ณด์ฅ
HpBar->InitWidget();
// Delegate Binding
auto HpWidget = Cast<UMyHpWidget>(HpBar->GetUserWidgetObject());
if (HpWidget)
HpWidget->BindHp(Stat);
}
// Called when the game starts or when spawned
void AMyCharacter::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void AMyCharacter::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
// Called to bind functionality to input
void AMyCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);
// ์ก์
์ ๋ฐ์ธ๋ฉํ๋ค.(๋๋ ๋ค ๋๋ค ์ ๋)
// Jump๋ ์ด๋ฏธ ๋ง๋ค์ด์ ธ์๋ค.
PlayerInputComponent->BindAction(TEXT("Jump"), EInputEvent::IE_Pressed, this, &AMyCharacter::Jump);
PlayerInputComponent->BindAction(TEXT("Attack"), EInputEvent::IE_Pressed, this, &AMyCharacter::Attack);
// Player Controller ์์ ๋ฐ์ธ๋ฉํ๋ฉด ๋จผ์ ์ ์ ๊ฐ๋ฅํ๋ค.
// Axis ๋ฐ์ธ๋ฉ
PlayerInputComponent->BindAxis(TEXT("UpDown"), this, &AMyCharacter::UpDown);
PlayerInputComponent->BindAxis(TEXT("LeftRight"), this, &AMyCharacter::LeftRight);
PlayerInputComponent->BindAxis(TEXT("Yaw"), this, &AMyCharacter::Yaw);
}
void AMyCharacter::UpDown(float Value)
{
UpDownValue = Value;
// Parameter: 1) ๋ฐฉํฅ, 2) ํฌ๊ธฐ
AddMovementInput(GetActorForwardVector(), Value);
}
void AMyCharacter::LeftRight(float Value)
{
LeftRightValue = Value;
// Parameter: 1) ๋ฐฉํฅ, 2) ํฌ๊ธฐ
AddMovementInput(GetActorRightVector(), Value);
}
void AMyCharacter::Yaw(float Value)
{
AddControllerYawInput(Value);
}
void AMyCharacter::Attack()
{
if (IsAttacking)
return;
AnimInstance->PlayAttackMontage();
AnimInstance->JumpToSection(AttackIndex);
AttackIndex = (AttackIndex + 1) % 3;
IsAttacking = true;
}
void AMyCharacter::AttackCheck()
{
FHitResult HitResult;
FCollisionQueryParams Params(NAME_None, false, this); // ํ๊ทธ ์ด๋ฆ, ๋ํ
์ผํ ํ์ ์ธ์ง, ๋ฌด์ํ ์กํฐ
float AttackRange = 100.0f;
float AttackRadius = 50.0f;
bool bResult = GetWorld()->SweepSingleByChannel(
OUT HitResult, // ์ถฉ๋ํ ๊ฒฐ๊ณผ๋ฌผ
GetActorLocation(), // ํ์ฌ ์กํฐ์ ์์น๋ถํฐ
GetActorLocation() + GetActorForwardVector() * AttackRange, // ์กํฐ์ ์ ๋ฐฉํฅ์์ AttachRange๊น์ง
FQuat::Identity, // ํ์ ์์ด
ECollisionChannel::ECC_GameTraceChannel2, // "Config/DefaultEngine.ini" ์ค์ ํ์ผ ์ฐธ๊ณ
FCollisionShape::MakeSphere(AttackRadius), // AttackRadius ๋งํผ์ ๊ตฌ์ฒด๋ก
Params // ์์ ์ ์ํ ์ฝ๋ฆฌ์ ํ๋ผ๋ฏธํฐ
);
if (bResult && HitResult.Actor.IsValid())
{
//UE_LOG(LogTemp, Log, TEXT("Hit Actor: %s"), *HitResult.Actor->GetName());
FDamageEvent DamageEvent;
HitResult.Actor->TakeDamage(Stat->GetAttack(), DamageEvent, GetController(), this);
}
// ๋๋ฒ๊น
FVector Direction = GetActorForwardVector() * AttackRange;
FVector Center = GetActorLocation() + Direction * 0.5f;
float HalfHeight = AttackRange * 0.5f + AttackRadius;
FQuat Rotation = FRotationMatrix::MakeFromZ(Direction).ToQuat(); // ๊ฐ์ฒด์ Z๋ฅผ ๊ณต๊ฒฉ ๋ฐฉํฅ์ผ๋ก ์ค์ (= Pitch: 90๋)
FColor DrawColor = bResult ? FColor::Green : FColor::Red; // ์ถฉ๋ ์ ์ด๋ก, ๊ธฐ๋ณธ์ ๋นจ๊ฐ
DrawDebugCapsule(
GetWorld(),
Center, // ์์ฑํ ์์น
HalfHeight, // Capsule์ ์ ๋ฐ ๋์ด
AttackRadius, // Capsule์ ๋ฐ์ง๋ฆ
Rotation, // ํ์
DrawColor, // ์๊น
false, // ์ง์์ ์ผ๋ก ๋ณด์ฌ์ค ๊ฑด์ง
2.0f // 2์ด ๋์๋ง ๋ณด์ฌ์ค
);
}
void AMyCharacter::OnAttackMontageEnded(UAnimMontage* Montage, bool bInterrupted)
{
IsAttacking = false;
OnAttackEnd.Broadcast();
}
float AMyCharacter::TakeDamage(float DamageAmount, FDamageEvent const& DamageEvent, AController* EventInstigator, AActor* DamageCauser)
{
Stat->OnAttacked(DamageAmount);
return DamageAmount;
}
| 30.185366 | 163 | 0.719619 | [
"mesh",
"object"
] |
61ece8aeabf83755ea64778913ac08f4b82214c0 | 3,946 | hh | C++ | source/types.hh | Rombur/adamantine | 45dd37397680fad1eaa64dbb311724c4f727a675 | [
"BSD-3-Clause"
] | 4 | 2016-09-03T02:08:26.000Z | 2021-03-03T01:26:41.000Z | source/types.hh | Rombur/adamantine | 45dd37397680fad1eaa64dbb311724c4f727a675 | [
"BSD-3-Clause"
] | 74 | 2016-08-31T18:10:46.000Z | 2021-04-08T01:51:44.000Z | source/types.hh | Rombur/adamantine | 45dd37397680fad1eaa64dbb311724c4f727a675 | [
"BSD-3-Clause"
] | 3 | 2019-11-12T15:43:38.000Z | 2021-01-19T02:58:56.000Z | /* Copyright (c) 2016 - 2021, the adamantine authors.
*
* This file is subject to the Modified BSD License and may not be distributed
* without copyright and license information. Please refer to the file LICENSE
* for the text and further information on this license.
*/
#ifndef TYPES_HH
#define TYPES_HH
namespace dealii
{
namespace LinearAlgebra
{
}
/**
* Shorten dealii::LinearAlgebra to dealii::LA.
*/
namespace LA = LinearAlgebra;
} // namespace dealii
namespace adamantine
{
/**
* Enum on the possible materials.
*/
enum class MaterialState
{
powder,
solid,
liquid,
SIZE
};
/**
* Enum on the possible material properties that depend on the state of the
* material.
*/
// TODO add AnisotropicStateProperty
enum class StateProperty
{
density,
specific_heat,
thermal_conductivity,
emissivity,
radiation_heat_transfer_coef,
convection_heat_transfer_coef,
SIZE
};
/**
* Enum on the possible material properties that do not depend on the state of
* the material.
*/
enum class Property
{
liquidus,
solidus,
latent_heat,
radiation_temperature_infty,
convection_temperature_infty,
SIZE
};
/**
* Enum on the possible timers.
*/
enum Timing
{
main,
refine,
add_material_search,
add_material_activate,
evol_time,
evol_time_eval_th_ph,
evol_time_J_inv,
evol_time_eval_mat_prop,
output,
n_timers
};
/**
* Structure that stores constants.
*/
struct Constant
{
/**
* Stefan-Boltzmann constant. Value from NIST [w/(m^2 k^4)].
*/
static double constexpr stefan_boltzmann = 5.670374419e-8;
};
/**
* This structure provides a mapping between the axes x, y, and z and the
* indices 0, 1, and 2. In 2D, the valid axes are x and z while in 3D x, y, and
* z are valid.
*/
template <int dim>
struct axis;
// dim == 2 specialization
template <>
struct axis<2>
{
static int constexpr x = 0;
static int constexpr y = -1;
static int constexpr z = 1;
};
// dim == 3 specialization
template <>
struct axis<3>
{
static int constexpr x = 0;
static int constexpr y = 1;
static int constexpr z = 2;
};
/**
* Enum on the different types of boundary condition supported. Some of them can
* be combined, for example radiative and convective.
*/
enum BoundaryType
{
invalid = 0,
adiabatic = 0x1,
radiative = 0x2,
convective = 0x4,
};
/**
* Global operator which returns an object in which all bits are set which are
* either set in the first or the second argument. This operator exists since if
* it did not then the result of the bit-or operator | would be an integer which
* would in turn trigger a compiler warning when we tried to assign it to an
* object of type BoundaryType.
*/
inline BoundaryType operator|(const BoundaryType b1, const BoundaryType b2)
{
return static_cast<BoundaryType>(static_cast<unsigned int>(b1) |
static_cast<unsigned int>(b2));
}
/**
* Global operator which sets the bits from the second argument also in the
* first one.
*/
inline BoundaryType &operator|=(BoundaryType &b1, const BoundaryType b2)
{
b1 = b1 | b2;
return b1;
}
/**
* Global operator which returns an object in which all bits are set which are
* set in the first as well as the second argument. This operator exists since
* if it did not then the result of the bit-and operator & would be an integer
* which would in turn trigger a compiler warning when we tried to assign it to
* an object of type BoundaryType.
*/
inline BoundaryType operator&(const BoundaryType b1, const BoundaryType b2)
{
return static_cast<BoundaryType>(static_cast<unsigned int>(b1) &
static_cast<unsigned int>(b2));
}
/**
* Global operator which clears all the bits in the first argument if they are
* not also set in the second argument.
*/
inline BoundaryType &operator&=(BoundaryType &b1, const BoundaryType b2)
{
b1 = b1 & b2;
return b1;
}
} // namespace adamantine
#endif
| 21.801105 | 80 | 0.706285 | [
"object",
"3d",
"solid"
] |
61f13ace3b54c21277c706cb151e8ba191d851b5 | 13,613 | cpp | C++ | cfw/src/v20190904/model/SwitchListsData.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | cfw/src/v20190904/model/SwitchListsData.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | cfw/src/v20190904/model/SwitchListsData.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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.
*/
#include <tencentcloud/cfw/v20190904/model/SwitchListsData.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Cfw::V20190904::Model;
using namespace std;
SwitchListsData::SwitchListsData() :
m_publicIpHasBeenSet(false),
m_intranetIpHasBeenSet(false),
m_instanceNameHasBeenSet(false),
m_instanceIdHasBeenSet(false),
m_assetTypeHasBeenSet(false),
m_areaHasBeenSet(false),
m_switchHasBeenSet(false),
m_idHasBeenSet(false),
m_publicIpTypeHasBeenSet(false),
m_portTimesHasBeenSet(false),
m_lastTimeHasBeenSet(false),
m_scanModeHasBeenSet(false),
m_scanStatusHasBeenSet(false)
{
}
CoreInternalOutcome SwitchListsData::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("PublicIp") && !value["PublicIp"].IsNull())
{
if (!value["PublicIp"].IsString())
{
return CoreInternalOutcome(Error("response `SwitchListsData.PublicIp` IsString=false incorrectly").SetRequestId(requestId));
}
m_publicIp = string(value["PublicIp"].GetString());
m_publicIpHasBeenSet = true;
}
if (value.HasMember("IntranetIp") && !value["IntranetIp"].IsNull())
{
if (!value["IntranetIp"].IsString())
{
return CoreInternalOutcome(Error("response `SwitchListsData.IntranetIp` IsString=false incorrectly").SetRequestId(requestId));
}
m_intranetIp = string(value["IntranetIp"].GetString());
m_intranetIpHasBeenSet = true;
}
if (value.HasMember("InstanceName") && !value["InstanceName"].IsNull())
{
if (!value["InstanceName"].IsString())
{
return CoreInternalOutcome(Error("response `SwitchListsData.InstanceName` IsString=false incorrectly").SetRequestId(requestId));
}
m_instanceName = string(value["InstanceName"].GetString());
m_instanceNameHasBeenSet = true;
}
if (value.HasMember("InstanceId") && !value["InstanceId"].IsNull())
{
if (!value["InstanceId"].IsString())
{
return CoreInternalOutcome(Error("response `SwitchListsData.InstanceId` IsString=false incorrectly").SetRequestId(requestId));
}
m_instanceId = string(value["InstanceId"].GetString());
m_instanceIdHasBeenSet = true;
}
if (value.HasMember("AssetType") && !value["AssetType"].IsNull())
{
if (!value["AssetType"].IsString())
{
return CoreInternalOutcome(Error("response `SwitchListsData.AssetType` IsString=false incorrectly").SetRequestId(requestId));
}
m_assetType = string(value["AssetType"].GetString());
m_assetTypeHasBeenSet = true;
}
if (value.HasMember("Area") && !value["Area"].IsNull())
{
if (!value["Area"].IsString())
{
return CoreInternalOutcome(Error("response `SwitchListsData.Area` IsString=false incorrectly").SetRequestId(requestId));
}
m_area = string(value["Area"].GetString());
m_areaHasBeenSet = true;
}
if (value.HasMember("Switch") && !value["Switch"].IsNull())
{
if (!value["Switch"].IsInt64())
{
return CoreInternalOutcome(Error("response `SwitchListsData.Switch` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_switch = value["Switch"].GetInt64();
m_switchHasBeenSet = true;
}
if (value.HasMember("Id") && !value["Id"].IsNull())
{
if (!value["Id"].IsUint64())
{
return CoreInternalOutcome(Error("response `SwitchListsData.Id` IsUint64=false incorrectly").SetRequestId(requestId));
}
m_id = value["Id"].GetUint64();
m_idHasBeenSet = true;
}
if (value.HasMember("PublicIpType") && !value["PublicIpType"].IsNull())
{
if (!value["PublicIpType"].IsUint64())
{
return CoreInternalOutcome(Error("response `SwitchListsData.PublicIpType` IsUint64=false incorrectly").SetRequestId(requestId));
}
m_publicIpType = value["PublicIpType"].GetUint64();
m_publicIpTypeHasBeenSet = true;
}
if (value.HasMember("PortTimes") && !value["PortTimes"].IsNull())
{
if (!value["PortTimes"].IsUint64())
{
return CoreInternalOutcome(Error("response `SwitchListsData.PortTimes` IsUint64=false incorrectly").SetRequestId(requestId));
}
m_portTimes = value["PortTimes"].GetUint64();
m_portTimesHasBeenSet = true;
}
if (value.HasMember("LastTime") && !value["LastTime"].IsNull())
{
if (!value["LastTime"].IsString())
{
return CoreInternalOutcome(Error("response `SwitchListsData.LastTime` IsString=false incorrectly").SetRequestId(requestId));
}
m_lastTime = string(value["LastTime"].GetString());
m_lastTimeHasBeenSet = true;
}
if (value.HasMember("ScanMode") && !value["ScanMode"].IsNull())
{
if (!value["ScanMode"].IsString())
{
return CoreInternalOutcome(Error("response `SwitchListsData.ScanMode` IsString=false incorrectly").SetRequestId(requestId));
}
m_scanMode = string(value["ScanMode"].GetString());
m_scanModeHasBeenSet = true;
}
if (value.HasMember("ScanStatus") && !value["ScanStatus"].IsNull())
{
if (!value["ScanStatus"].IsUint64())
{
return CoreInternalOutcome(Error("response `SwitchListsData.ScanStatus` IsUint64=false incorrectly").SetRequestId(requestId));
}
m_scanStatus = value["ScanStatus"].GetUint64();
m_scanStatusHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void SwitchListsData::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_publicIpHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "PublicIp";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_publicIp.c_str(), allocator).Move(), allocator);
}
if (m_intranetIpHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "IntranetIp";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_intranetIp.c_str(), allocator).Move(), allocator);
}
if (m_instanceNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "InstanceName";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_instanceName.c_str(), allocator).Move(), allocator);
}
if (m_instanceIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "InstanceId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_instanceId.c_str(), allocator).Move(), allocator);
}
if (m_assetTypeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "AssetType";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_assetType.c_str(), allocator).Move(), allocator);
}
if (m_areaHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Area";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_area.c_str(), allocator).Move(), allocator);
}
if (m_switchHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Switch";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_switch, allocator);
}
if (m_idHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Id";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_id, allocator);
}
if (m_publicIpTypeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "PublicIpType";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_publicIpType, allocator);
}
if (m_portTimesHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "PortTimes";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_portTimes, allocator);
}
if (m_lastTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "LastTime";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_lastTime.c_str(), allocator).Move(), allocator);
}
if (m_scanModeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ScanMode";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_scanMode.c_str(), allocator).Move(), allocator);
}
if (m_scanStatusHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ScanStatus";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_scanStatus, allocator);
}
}
string SwitchListsData::GetPublicIp() const
{
return m_publicIp;
}
void SwitchListsData::SetPublicIp(const string& _publicIp)
{
m_publicIp = _publicIp;
m_publicIpHasBeenSet = true;
}
bool SwitchListsData::PublicIpHasBeenSet() const
{
return m_publicIpHasBeenSet;
}
string SwitchListsData::GetIntranetIp() const
{
return m_intranetIp;
}
void SwitchListsData::SetIntranetIp(const string& _intranetIp)
{
m_intranetIp = _intranetIp;
m_intranetIpHasBeenSet = true;
}
bool SwitchListsData::IntranetIpHasBeenSet() const
{
return m_intranetIpHasBeenSet;
}
string SwitchListsData::GetInstanceName() const
{
return m_instanceName;
}
void SwitchListsData::SetInstanceName(const string& _instanceName)
{
m_instanceName = _instanceName;
m_instanceNameHasBeenSet = true;
}
bool SwitchListsData::InstanceNameHasBeenSet() const
{
return m_instanceNameHasBeenSet;
}
string SwitchListsData::GetInstanceId() const
{
return m_instanceId;
}
void SwitchListsData::SetInstanceId(const string& _instanceId)
{
m_instanceId = _instanceId;
m_instanceIdHasBeenSet = true;
}
bool SwitchListsData::InstanceIdHasBeenSet() const
{
return m_instanceIdHasBeenSet;
}
string SwitchListsData::GetAssetType() const
{
return m_assetType;
}
void SwitchListsData::SetAssetType(const string& _assetType)
{
m_assetType = _assetType;
m_assetTypeHasBeenSet = true;
}
bool SwitchListsData::AssetTypeHasBeenSet() const
{
return m_assetTypeHasBeenSet;
}
string SwitchListsData::GetArea() const
{
return m_area;
}
void SwitchListsData::SetArea(const string& _area)
{
m_area = _area;
m_areaHasBeenSet = true;
}
bool SwitchListsData::AreaHasBeenSet() const
{
return m_areaHasBeenSet;
}
int64_t SwitchListsData::GetSwitch() const
{
return m_switch;
}
void SwitchListsData::SetSwitch(const int64_t& _switch)
{
m_switch = _switch;
m_switchHasBeenSet = true;
}
bool SwitchListsData::SwitchHasBeenSet() const
{
return m_switchHasBeenSet;
}
uint64_t SwitchListsData::GetId() const
{
return m_id;
}
void SwitchListsData::SetId(const uint64_t& _id)
{
m_id = _id;
m_idHasBeenSet = true;
}
bool SwitchListsData::IdHasBeenSet() const
{
return m_idHasBeenSet;
}
uint64_t SwitchListsData::GetPublicIpType() const
{
return m_publicIpType;
}
void SwitchListsData::SetPublicIpType(const uint64_t& _publicIpType)
{
m_publicIpType = _publicIpType;
m_publicIpTypeHasBeenSet = true;
}
bool SwitchListsData::PublicIpTypeHasBeenSet() const
{
return m_publicIpTypeHasBeenSet;
}
uint64_t SwitchListsData::GetPortTimes() const
{
return m_portTimes;
}
void SwitchListsData::SetPortTimes(const uint64_t& _portTimes)
{
m_portTimes = _portTimes;
m_portTimesHasBeenSet = true;
}
bool SwitchListsData::PortTimesHasBeenSet() const
{
return m_portTimesHasBeenSet;
}
string SwitchListsData::GetLastTime() const
{
return m_lastTime;
}
void SwitchListsData::SetLastTime(const string& _lastTime)
{
m_lastTime = _lastTime;
m_lastTimeHasBeenSet = true;
}
bool SwitchListsData::LastTimeHasBeenSet() const
{
return m_lastTimeHasBeenSet;
}
string SwitchListsData::GetScanMode() const
{
return m_scanMode;
}
void SwitchListsData::SetScanMode(const string& _scanMode)
{
m_scanMode = _scanMode;
m_scanModeHasBeenSet = true;
}
bool SwitchListsData::ScanModeHasBeenSet() const
{
return m_scanModeHasBeenSet;
}
uint64_t SwitchListsData::GetScanStatus() const
{
return m_scanStatus;
}
void SwitchListsData::SetScanStatus(const uint64_t& _scanStatus)
{
m_scanStatus = _scanStatus;
m_scanStatusHasBeenSet = true;
}
bool SwitchListsData::ScanStatusHasBeenSet() const
{
return m_scanStatusHasBeenSet;
}
| 27.390342 | 140 | 0.676265 | [
"model"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.