hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 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 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0643b563b583e1ccce1af68a31f29d10e0a2f560 | 811 | hpp | C++ | generator/borders_loader.hpp | bowlofstew/omim | 8045157c95244aa8f862d47324df42a19b87e335 | [
"Apache-2.0"
] | 1 | 2019-01-11T05:02:05.000Z | 2019-01-11T05:02:05.000Z | generator/borders_loader.hpp | bowlofstew/omim | 8045157c95244aa8f862d47324df42a19b87e335 | [
"Apache-2.0"
] | null | null | null | generator/borders_loader.hpp | bowlofstew/omim | 8045157c95244aa8f862d47324df42a19b87e335 | [
"Apache-2.0"
] | 1 | 2019-08-09T21:21:09.000Z | 2019-08-09T21:21:09.000Z | #pragma once
#include "geometry/region2d.hpp"
#include "geometry/tree4d.hpp"
#include "std/string.hpp"
#define BORDERS_DIR "borders/"
#define BORDERS_EXTENSION ".poly"
namespace borders
{
typedef m2::RegionD Region;
typedef m4::Tree<Region> RegionsContainerT;
struct CountryPolygons
{
CountryPolygons(string const & name = "") : m_name(name), m_index(-1) {}
bool IsEmpty() const { return m_regions.IsEmpty(); }
void Clear()
{
m_regions.Clear();
m_name.clear();
m_index = -1;
}
RegionsContainerT m_regions;
string m_name;
mutable int m_index;
};
typedef m4::Tree<CountryPolygons> CountriesContainerT;
bool LoadCountriesList(string const & baseDir, CountriesContainerT & countries);
void GeneratePackedBorders(string const & baseDir);
}
| 20.794872 | 82 | 0.696671 | bowlofstew |
06471850e2f566be10650a5176216815fb6e0acc | 128 | cpp | C++ | 1d/kill_waw_scalar/main.cpp | realincubus/clang_plugin_tests | 018e22f37baaa7c072de8d455ad16057c953fd96 | [
"MIT"
] | null | null | null | 1d/kill_waw_scalar/main.cpp | realincubus/clang_plugin_tests | 018e22f37baaa7c072de8d455ad16057c953fd96 | [
"MIT"
] | null | null | null | 1d/kill_waw_scalar/main.cpp | realincubus/clang_plugin_tests | 018e22f37baaa7c072de8d455ad16057c953fd96 | [
"MIT"
] | null | null | null |
int main(int argc, char** argv){
for (int i = 0; i < 100; ++i){
double x;
x = 0;
}
return 0;
}
| 9.846154 | 34 | 0.398438 | realincubus |
06478b1e2d9c4788f6910906e30f5f34f4c2ce66 | 552 | cpp | C++ | Cpp/298_binary_tree_longest_consecutive_sequence/solution.cpp | zszyellow/leetcode | 2ef6be04c3008068f8116bf28d70586e613a48c2 | [
"MIT"
] | 1 | 2015-12-19T23:05:35.000Z | 2015-12-19T23:05:35.000Z | Cpp/298_binary_tree_longest_consecutive_sequence/solution.cpp | zszyellow/leetcode | 2ef6be04c3008068f8116bf28d70586e613a48c2 | [
"MIT"
] | null | null | null | Cpp/298_binary_tree_longest_consecutive_sequence/solution.cpp | zszyellow/leetcode | 2ef6be04c3008068f8116bf28d70586e613a48c2 | [
"MIT"
] | null | null | null | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int longestConsecutive(TreeNode* root) {
return search(root, NULL, 0);
}
int search(TreeNode *root, TreeNode *parent, int len) {
if (!root) return len;
len = (parent && root->val == parent->val + 1) ? len+1 : 1;
return max(len, max(search(root->left, root, len), search(root->right, root, len)));
}
};
| 25.090909 | 88 | 0.586957 | zszyellow |
0647d760d8c25460239aa4c791a20256d53410ee | 3,694 | hh | C++ | net.ssa/xrLC/OpenMesh/Core/Utils/Noncopyable.hh | ixray-team/xray-vss-archive | b245c8601dcefb505b4b51f58142da6769d4dc92 | [
"Linux-OpenIB"
] | 1 | 2022-03-26T17:00:19.000Z | 2022-03-26T17:00:19.000Z | xrLC/OpenMesh/Core/Utils/Noncopyable.hh | ixray-team/xray-vss-archive | b245c8601dcefb505b4b51f58142da6769d4dc92 | [
"Linux-OpenIB"
] | null | null | null | xrLC/OpenMesh/Core/Utils/Noncopyable.hh | ixray-team/xray-vss-archive | b245c8601dcefb505b4b51f58142da6769d4dc92 | [
"Linux-OpenIB"
] | 1 | 2022-03-26T17:00:21.000Z | 2022-03-26T17:00:21.000Z | //=============================================================================
//
// OpenMesh
// Copyright (C) 2003 by Computer Graphics Group, RWTH Aachen
// www.openmesh.org
//
//-----------------------------------------------------------------------------
//
// License
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Library General Public License as published
// by the Free Software Foundation, version 2.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
//-----------------------------------------------------------------------------
//
// $Revision: 1.4 $
// $Date: 2003/11/14 14:03:25 $
//
//=============================================================================
//=============================================================================
//
// Implements the Non-Copyable metapher
//
//=============================================================================
#ifndef OPENMESH_NONCOPYABLE_HH
#define OPENMESH_NONCOPYABLE_HH
//-----------------------------------------------------------------------------
#include <OpenMesh/Core/System/config.h>
//-----------------------------------------------------------------------------
namespace OpenMesh {
namespace Utils {
//-----------------------------------------------------------------------------
/** This class demonstrates the non copyable idiom. In some cases it is
important an object can't be copied. Deriving from Noncopyable makes sure
all relevant constructor and operators are made inaccessable, for public
AND derived classes.
**/
class Noncopyable
{
public:
Noncopyable() { }
private:
/// Prevent access to copy constructor
Noncopyable( const Noncopyable& );
/// Prevent access to assignment operator
const Noncopyable& operator=( const Noncopyable& );
};
//=============================================================================
} // namespace Utils
} // namespace OpenMesh
//=============================================================================
#endif // OPENMESH_NONCOPYABLE_HH
//=============================================================================
| 47.974026 | 80 | 0.319708 | ixray-team |
064e9fd8c85114ba9966dba4b6453fda5a1af84f | 49,053 | cpp | C++ | src/Microsoft.DotNet.Wpf/src/WpfGfx/core/hw/hwpipelinebuilder.cpp | nsivov/wpf | d36941860f05dd7a09008e99d1bcd635b0a69fdb | [
"MIT"
] | 2 | 2020-05-18T17:00:43.000Z | 2021-12-01T10:00:29.000Z | src/Microsoft.DotNet.Wpf/src/WpfGfx/core/hw/hwpipelinebuilder.cpp | nsivov/wpf | d36941860f05dd7a09008e99d1bcd635b0a69fdb | [
"MIT"
] | 5 | 2020-05-05T08:05:01.000Z | 2021-12-11T21:35:37.000Z | src/Microsoft.DotNet.Wpf/src/WpfGfx/core/hw/hwpipelinebuilder.cpp | nsivov/wpf | d36941860f05dd7a09008e99d1bcd635b0a69fdb | [
"MIT"
] | 4 | 2020-05-04T06:43:25.000Z | 2022-02-20T12:02:50.000Z | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//+-----------------------------------------------------------------------------
//
//
// $TAG ENGR
// $Module: win_mil_graphics_d3d
// $Keywords:
//
// $Description:
// Contains implementation for CHwPipelineBuilder class.
//
// $ENDTAG
//
//------------------------------------------------------------------------------
#include "precomp.hpp"
//+-----------------------------------------------------------------------------
//
// Table:
// sc_PipeOpProperties
//
// Synopsis:
// Table of HwBlendOp properties
//
//------------------------------------------------------------------------------
static const
struct BlendOperationProperties {
bool AllowsAlphaMultiplyInEarlierStage;
} sc_BlendOpProperties[] =
{ // HBO_SelectSource
{
/* AllowsAlphaMultiplyInEarlierStage */ false
},
// HBO_Multiply
{
/* AllowsAlphaMultiplyInEarlierStage */ true
},
// HBO_SelectSourceColorIgnoreAlpha
{
/* AllowsAlphaMultiplyInEarlierStage */ false
},
// HBO_MultiplyColorIgnoreAlpha
{
/* AllowsAlphaMultiplyInEarlierStage */ true
},
// HBO_BumpMap
{
/* AllowsAlphaMultiplyInEarlierStage */ true
},
// HBO_MultiplyByAlpha
{
/* AllowsAlphaMultiplyInEarlierStage */ true
},
// HBO_MultiplyAlphaOnly
{
/* AllowsAlphaMultiplyInEarlierStage */ true
},
};
C_ASSERT(ARRAYSIZE(sc_BlendOpProperties)==HBO_Total);
//+-----------------------------------------------------------------------------
//
// Class:
// CHwPipelineBuilder
//
// Synopsis:
// Helper class for CHwPipeline that does the actual construction of the
// pipeline and to which other components interface
//
//------------------------------------------------------------------------------
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipelineBuilder::Builder
//
// Synopsis:
// ctor
//
//------------------------------------------------------------------------------
CHwPipelineBuilder::CHwPipelineBuilder(
__in_ecount(1) CHwPipeline * const pHP,
HwPipeline::Type oType
)
: m_pHP(pHP),
m_oPipelineType(oType)
{
Assert(pHP);
m_iCurrentSampler = INVALID_PIPELINE_SAMPLER;
m_iCurrentStage = INVALID_PIPELINE_STAGE;
m_mvfIn = MILVFAttrNone;
m_mvfGenerated = MILVFAttrNone;
m_fAntiAliasUsed = false;
m_eAlphaMultiplyOp = HBO_Nop;
m_iAlphaMultiplyOkayAtItem = INVALID_PIPELINE_STAGE;
m_iLastAlphaScalableItem = INVALID_PIPELINE_ITEM;
m_iAntiAliasingPiggybackedByItem = INVALID_PIPELINE_ITEM;
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipelineBuilder::InitializePipelineMembers
//
// Synopsis:
// Figure out the alpha multiply operation and obtain vertex info.
//
void
CHwPipelineBuilder::InitializePipelineMembers(
MilCompositingMode::Enum eCompositingMode,
__in_ecount(1) IGeometryGenerator const *pIGeometryGenerator
)
{
Assert(m_iCurrentSampler == INVALID_PIPELINE_SAMPLER);
Assert(m_iCurrentStage == INVALID_PIPELINE_STAGE);
Assert(m_iAlphaMultiplyOkayAtItem == INVALID_PIPELINE_STAGE);
Assert(m_iLastAlphaScalableItem == INVALID_PIPELINE_STAGE);
if (eCompositingMode == MilCompositingMode::SourceOverNonPremultiplied ||
eCompositingMode == MilCompositingMode::SourceInverseAlphaOverNonPremultiplied)
{
m_eAlphaMultiplyOp = HBO_MultiplyAlphaOnly;
}
else
{
m_eAlphaMultiplyOp = HBO_Multiply;
}
pIGeometryGenerator->GetPerVertexDataType(
OUT m_mvfIn
);
m_mvfAvailable = MILVFAttrXYZ | MILVFAttrDiffuse | MILVFAttrSpecular | MILVFAttrUV4;
m_mvfAvailable &= ~m_mvfIn;
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipelineBuilder::SendPipelineOperations
//
// Synopsis:
// Construct a full rendering pipeline for the given context from scratch
//
HRESULT
CHwPipelineBuilder::SendPipelineOperations(
__inout_ecount(1) IHwPrimaryColorSource *pIPCS,
__in_ecount_opt(1) const IMILEffectList *pIEffects,
__in_ecount(1) const CHwBrushContext *pEffectContext,
__inout_ecount(1) IGeometryGenerator *pIGeometryGenerator
)
{
HRESULT hr = S_OK;
// Determine incoming per vertex data included with geometry.
// Request primary color source to send primary rendering operations
IFC(pIPCS->SendOperations(this));
// Setup effects operations if any
if (pIEffects)
{
IFC(ProcessEffectList(
pIEffects,
pEffectContext
));
}
IFC(pIGeometryGenerator->SendGeometryModifiers(this));
IFC(pIGeometryGenerator->SendLighting(this));
// Setup operations to handle clipping
IFC(ProcessClip());
Cleanup:
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipelineBuilder::Set_BumpMap
//
// Synopsis:
// Take the given color source and set it as a bump map for the first
// texture color source
//
// This call must be followed by a Set_Texture call specifying the first
// real color source.
//
HRESULT
CHwPipelineBuilder::Set_BumpMap(
__in_ecount(1) CHwTexturedColorSource *pBumpMap
)
{
HRESULT hr = S_OK;
// Parameter Assertions
Assert(pBumpMap->GetSourceType() != CHwColorSource::Constant);
IFC(E_NOTIMPL);
Cleanup:
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipelineBuilder::Mul_AlphaMask
//
// Synopsis:
// Add a blend operation that uses the given color source's alpha
// components to scale previous rendering results
//
HRESULT
CHwPipelineBuilder::Mul_AlphaMask(
__in_ecount(1) CHwTexturedColorSource *pAlphaMaskColorSource
)
{
HRESULT hr = S_OK;
IFC(E_NOTIMPL);
Cleanup:
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipelineBuilder::ProcessClip
//
// Synopsis:
// Set up clipping operations and/or resources
//
HRESULT
CHwPipelineBuilder::ProcessClip(
)
{
HRESULT hr = S_OK;
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipelineBuilder::ProcessEffectList
//
// Synopsis:
// Read the effect list and add pipeline operations for each one
//
// This method and the ProcessXxxEffect helper methods make up the logical
// Hardware Effects Processor component.
//
// Responsibilities:
// - Decode effects list to create color sources and specify operation
// needed to pipeline
//
// Not responsible for:
// - Determining operation order or combining operations
//
// Inputs required:
// - Effects list
// - Pipeline builder object (this)
//
HRESULT
CHwPipelineBuilder::ProcessEffectList(
__in_ecount(1) const IMILEffectList *pIEffects,
__in_ecount(1) const CHwBrushContext *pEffectContext
)
{
HRESULT hr = S_OK;
UINT cEntries = 0;
// Get the count of the transform blocks in the effect object.
IFC(pIEffects->GetCount(&cEntries));
// Handle only alpha effects
for (UINT uIndex = 0; uIndex < cEntries; uIndex++)
{
CLSID clsid;
UINT cbSize;
UINT cResources;
IFC(pIEffects->GetCLSID(uIndex, &clsid));
IFC(pIEffects->GetParameterSize(uIndex, &cbSize));
IFC(pIEffects->GetResourceCount(uIndex, &cResources));
if (clsid == CLSID_MILEffectAlphaScale)
{
IFC(ProcessAlphaScaleEffect(pIEffects, uIndex, cbSize, cResources));
}
else if (clsid == CLSID_MILEffectAlphaMask)
{
IFC(ProcessAlphaMaskEffect(pEffectContext, pIEffects, uIndex, cbSize, cResources));
}
else
{
IFC(WGXERR_UNSUPPORTED_OPERATION);
}
}
Cleanup:
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipelineBuilder::ProcessAlphaScaleEffect
//
// Synopsis:
// Decode an alpha scale effect and add to pipeline
//
HRESULT
CHwPipelineBuilder::ProcessAlphaScaleEffect(
__in_ecount(1) const IMILEffectList *pIEffects,
UINT uIndex,
UINT cbSize,
UINT cResources
)
{
HRESULT hr = S_OK;
CHwConstantAlphaScalableColorSource *pNewAlphaColorSource = NULL;
AlphaScaleParams alphaScale;
// check the parameter size
if (cbSize != sizeof(alphaScale))
{
AssertMsg(FALSE, "AlphaScale parameter has unexpected size.");
IFC(WGXERR_UNSUPPORTED_OPERATION);
}
else if (cResources != 0)
{
AssertMsg(FALSE, "AlphaScale has unexpected number of resources.");
IFC(WGXERR_UNSUPPORTED_OPERATION);
}
IFC(pIEffects->GetParameters(uIndex, cbSize, &alphaScale));
if (0.0f > alphaScale.scale || alphaScale.scale > 1.0f)
{
IFC(WGXERR_UNSUPPORTED_OPERATION);
}
else
{
IFC(CHwConstantAlphaScalableColorSource::Create(
m_pHP->m_pDevice,
alphaScale.scale,
NULL,
&m_pHP->m_dbScratch,
&pNewAlphaColorSource
));
IFC(Mul_ConstAlpha(pNewAlphaColorSource));
}
Cleanup:
ReleaseInterfaceNoNULL(pNewAlphaColorSource);
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipelineBuilder::ProcessAlphaMaskEffect
//
// Synopsis:
// Decode an alpha mask effect and add to pipeline
//
HRESULT
CHwPipelineBuilder::ProcessAlphaMaskEffect(
__in_ecount(1) const CHwBrushContext *pEffectContext,
__in_ecount(1) const IMILEffectList *pIEffects,
UINT uIndex,
UINT cbSize,
UINT cResources
)
{
HRESULT hr = S_OK;
AlphaMaskParams alphaMaskParams;
IUnknown *pIUnknown = NULL;
IWGXBitmapSource *pMaskBitmap = NULL;
CHwTexturedColorSource *pMaskColorSource = NULL;
CMultiOutSpaceMatrix<CoordinateSpace::RealizationSampling> matBitmapToIdealRealization;
CDelayComputedBounds<CoordinateSpace::RealizationSampling> rcRealizationBounds;
BitmapToXSpaceTransform matRealizationToGivenSampleSpace;
// check the parameter size
if (cbSize != sizeof(alphaMaskParams))
{
AssertMsg(FALSE, "AlphaMask parameter has unexpected size.");
IFC(WGXERR_UNSUPPORTED_OPERATION);
}
else if (cResources != 1)
{
AssertMsg(FALSE, "AlphaMask has unexpected number of resources.");
IFC(WGXERR_UNSUPPORTED_OPERATION);
}
IFC(pIEffects->GetParameters(uIndex, cbSize, &alphaMaskParams));
IFC(pIEffects->GetResources(uIndex, cResources, &pIUnknown));
IFC(pIUnknown->QueryInterface(
IID_IWGXBitmapSource,
reinterpret_cast<void **>(&pMaskBitmap)));
pEffectContext->GetRealizationBoundsAndTransforms(
CMatrix<CoordinateSpace::RealizationSampling,CoordinateSpace::Effect>::ReinterpretBase(alphaMaskParams.matTransform),
OUT matBitmapToIdealRealization,
OUT matRealizationToGivenSampleSpace,
OUT rcRealizationBounds
);
{
CHwBitmapColorSource::CacheContextParameters oContextCacheParameters(
MilBitmapInterpolationMode::Linear,
pEffectContext->GetContextStatePtr()->RenderState->PrefilterEnable,
pEffectContext->GetFormat(),
MilBitmapWrapMode::Extend
);
IFC(CHwBitmapColorSource::DeriveFromBitmapAndContext(
m_pHP->m_pDevice,
pMaskBitmap,
NULL,
NULL,
rcRealizationBounds,
&matBitmapToIdealRealization,
&matRealizationToGivenSampleSpace,
pEffectContext->GetContextStatePtr()->RenderState->PrefilterThreshold,
pEffectContext->CanFallback(),
NULL,
oContextCacheParameters,
&pMaskColorSource
));
IFC(Mul_AlphaMask(pMaskColorSource));
}
Cleanup:
ReleaseInterfaceNoNULL(pIUnknown);
ReleaseInterfaceNoNULL(pMaskBitmap);
ReleaseInterfaceNoNULL(pMaskColorSource);
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipelineBuilder::ChooseVertexBuilder
//
// Synopsis:
// Create a vertex builder for the current pipeline
//
HRESULT
CHwPipelineBuilder::ChooseVertexBuilder(
__deref_out_ecount(1) CHwVertexBuffer::Builder **ppVertexBuilder
)
{
HRESULT hr = S_OK;
MilVertexFormatAttribute mvfaAALocation = MILVFAttrNone;
if (m_fAntiAliasUsed)
{
mvfaAALocation = HWPIPELINE_ANTIALIAS_LOCATION;
}
Assert((m_mvfIn & m_mvfGenerated) == 0);
IFC(CHwVertexBuffer::Builder::Create(
m_mvfIn,
m_mvfIn | m_mvfGenerated,
mvfaAALocation,
m_pHP,
m_pHP->m_pDevice,
&m_pHP->m_dbScratch,
ppVertexBuilder
));
Cleanup:
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipelineBuilder::TryToMultiplyConstantAlphaToExistingStage
//
// Synopsis:
// Tries to find an existing stage it can use to drop it's alpha multiply
// into. Should work on both shader and fixed function pipelines.
//
//------------------------------------------------------------------------------
bool
CHwPipelineBuilder::TryToMultiplyConstantAlphaToExistingStage(
__in_ecount(1) const CHwConstantAlphaColorSource *pAlphaColorSource
)
{
HRESULT hr = S_OK;
float flAlpha = pAlphaColorSource->GetAlpha();
CHwConstantAlphaScalableColorSource *pScalableAlphaSource = NULL;
bool fStageToMultiplyFound = false;
INT iItemCount = static_cast<INT>(m_pHP->m_rgItem.GetCount());
// Parameter Assertions
Assert(flAlpha >= 0.0f);
Assert(flAlpha <= 1.0f);
// Member Assertions
// There should be at least one stage
Assert(iItemCount > 0);
Assert(GetNumReservedStages() > 0);
// An alpha scale of 1.0 is a nop; do nothing
if (flAlpha == 1.0f)
{
fStageToMultiplyFound = true;
goto Cleanup;
}
int iLastAlphaScalableItem, iItemAvailableForAlphaMultiply;
iLastAlphaScalableItem = GetLastAlphaScalableItem();
iItemAvailableForAlphaMultiply = GetEarliestItemAvailableForAlphaMultiply();
// We can add logic to recognize that an alpha scale of 0 would give us a
// completely transparent result and then "compress" previous stages.
// Check for existing stage at which constant alpha scale may be applied
if (iItemAvailableForAlphaMultiply < iItemCount)
{
// Check for existing color source that will handle the alpha scale
if (iLastAlphaScalableItem >= iItemAvailableForAlphaMultiply)
{
Assert(m_pHP->m_rgItem[iLastAlphaScalableItem].pHwColorSource);
// Future Consideration: Shader pipe issue
// The if statement around the Assert is to prevent the Assert from
// firing on the shader path because the shader path does not set
// eBlendOp. We can remove this if in the future when the shader
// shader path uses the blend args.
HwBlendOp hwBlendOp = m_pHP->m_rgItem[iLastAlphaScalableItem].eBlendOp;
if (hwBlendOp == HBO_MultiplyAlphaOnly || hwBlendOp == HBO_Multiply)
{
Assert(hwBlendOp == m_eAlphaMultiplyOp);
}
// Multiply with new scale factor
m_pHP->m_rgItem[iLastAlphaScalableItem].pHwColorSource->AlphaScale(flAlpha);
fStageToMultiplyFound = true;
}
else
{
//
// Check for existing color source that can be reused to handle the
// alpha scale. Alpha scale can be applied to any constant color
// source using the ConstantAlphaScalable class.
//
// The scale should technically come at the end of the current
// operations; so, try to get as close to the end as possible.
//
for (INT iLastConstant = iItemCount-1;
iLastConstant >= iItemAvailableForAlphaMultiply;
iLastConstant--)
{
CHwColorSource *pHCS =
m_pHP->m_rgItem[iLastConstant].pHwColorSource;
if (pHCS && (pHCS->GetSourceType() & CHwColorSource::Constant))
{
// The ConstantAlphaScalable class only supports
// HBO_Multiply because it assumes premulitplied colors come
// in and go out.
Assert(m_eAlphaMultiplyOp == HBO_Multiply);
//
// Inject an alpha scalable color source in place
// of the current constant color source.
//
IFC(CHwConstantAlphaScalableColorSource::Create(
m_pHP->m_pDevice,
flAlpha,
DYNCAST(CHwConstantColorSource, pHCS),
&m_pHP->m_dbScratch,
&pScalableAlphaSource
));
// Transfer pScalableAlphaSource reference
m_pHP->m_rgItem[iLastConstant].pHwColorSource =
pScalableAlphaSource;
pHCS->Release();
//
// Color Sources being added to a pipeline are
// required to have their mappings reset. This
// normally happens when items are added to the
// pipeline, but since this is replacing an item
// we need to call it ourselves.
//
pScalableAlphaSource->ResetForPipelineReuse();
pScalableAlphaSource = NULL;
// Remember this location now holds an
// alpha scalable color source
SetLastAlphaScalableStage(iLastConstant);
fStageToMultiplyFound = true;
break;
}
}
}
}
Cleanup:
ReleaseInterfaceNoNULL(pScalableAlphaSource);
//
// We only want to consider success if our HRESULT is S_OK.
//
return (hr == S_OK && fStageToMultiplyFound);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipelineBuilder::CheckForBlendAlreadyPresentAtAALocation
//
// Synopsis:
// We may have already added a blend operation using the location we're
// going to generate anti-aliasing in. If this is the case we don't need
// to add another blend operation.
//
//------------------------------------------------------------------------------
HRESULT
CHwPipelineBuilder::CheckForBlendAlreadyPresentAtAALocation(
bool *pfNeedToAddAnotherStageToBlendAntiAliasing
)
{
HRESULT hr = S_OK;
INT iAAPiggybackItem = GetAAPiggybackItem();
*pfNeedToAddAnotherStageToBlendAntiAliasing = false;
//
// Validate that any AA piggybacking is okay. If first location (item)
// available for alpha multiply is greater than location of piggyback item,
// then piggybacking is not allowed.
//
// AA piggyback item is -1 when not set so that case will also be detected.
//
if (iAAPiggybackItem < GetEarliestItemAvailableForAlphaMultiply())
{
//
// Check if there was a piggyback item
//
if (iAAPiggybackItem != INVALID_PIPELINE_ITEM)
{
// Future Consideration: Find new attribute for AA piggybacker
// and modify pipeline item with new properties.
RIP("Fixed function pipeline does not expect invalid piggybacking");
IFC(WGXERR_NOTIMPLEMENTED);
}
*pfNeedToAddAnotherStageToBlendAntiAliasing = true;
}
else
{
Assert(GetGeneratedComponents() & MILVFAttrDiffuse);
}
Cleanup:
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipelineBuilder::SetupVertexBuilder
//
// Synopsis:
// Choose the appropriate vertex builder class for the pipeline that has
// just been set up and initialize the vertex builder
//
HRESULT
CHwPipelineBuilder::SetupVertexBuilder(
__deref_out_ecount(1) CHwVertexBuffer::Builder **ppVertexBuilder
)
{
HRESULT hr = S_OK;
// Select a vertex builder
IFC(ChooseVertexBuilder(ppVertexBuilder));
// Send vertex mappings for each color source
HwPipelineItem *pItem;
pItem = m_pHP->m_rgItem.GetDataBuffer();
CHwVertexBuffer::Builder *pVertexBuilder;
pVertexBuilder = *ppVertexBuilder;
if (VerticesArePreGenerated())
{
// Pass NULL builder to color source to indicate that vertices are
// pre-generated and should not be modified.
pVertexBuilder = NULL;
}
if (m_oPipelineType == HwPipeline::FixedFunction)
{
for (UINT uItem = 0; uItem < m_pHP->m_rgItem.GetCount(); uItem++, pItem++)
{
if (pItem->pHwColorSource)
{
IFC(pItem->pHwColorSource->SendVertexMapping(
pVertexBuilder,
pItem->mvfaSourceLocation
));
}
}
}
else
{
for (UINT uItem = 0; uItem < m_pHP->m_rgItem.GetCount(); uItem++, pItem++)
{
if (pItem->pHwColorSource && pItem->mvfaTextureCoordinates != MILVFAttrNone)
{
IFC(pItem->pHwColorSource->SendVertexMapping(
pVertexBuilder,
pItem->mvfaTextureCoordinates
));
}
}
}
// Let vertex builder know that is the end of the vertex mappings
IFC((*ppVertexBuilder)->FinalizeMappings());
Cleanup:
if (FAILED(hr))
{
delete *ppVertexBuilder;
*ppVertexBuilder = NULL;
}
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipelineBuilder::Mul_BlendColorsInternal
//
// Synopsis:
// Multiplies the pipeline by a set of blend colors.
//
//------------------------------------------------------------------------------
HRESULT
CHwPipelineBuilder::Mul_BlendColors(
__in_ecount(1) CHwColorComponentSource *pBlendColorSource
)
{
HRESULT hr = S_OK;
Assert(GetAvailableForReference() & MILVFAttrDiffuse);
Assert(GetAAPiggybackItem() < GetEarliestItemAvailableForAlphaMultiply());
IFC(Mul_BlendColorsInternal(
pBlendColorSource
));
Cleanup:
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipelineBuilder::Set_AAColorSource
//
// Synopsis:
// Adds an antialiasing colorsource.
//
//------------------------------------------------------------------------------
HRESULT
CHwPipelineBuilder::Set_AAColorSource(
__in_ecount(1) CHwColorComponentSource *pAAColorSource
)
{
HRESULT hr = S_OK;
//
// Use Geometry Generator specified AA location (none, falloff, UV) to
// 1) Append blend operation as needed
// 2) Otherwise set proper indicators to vertex builder
//
Assert(pAAColorSource->GetComponentLocation() == CHwColorComponentSource::Diffuse);
bool fNeedToAddAnotherStageToBlendAntiAliasing = true;
IFC(CheckForBlendAlreadyPresentAtAALocation(
&fNeedToAddAnotherStageToBlendAntiAliasing
));
if (fNeedToAddAnotherStageToBlendAntiAliasing)
{
IFC(Mul_BlendColorsInternal(
pAAColorSource
));
}
m_fAntiAliasUsed = true;
Cleanup:
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipeline::FFBuilder::Builder
//
// Synopsis:
// Create the fixed function pipeline builder.
//
CHwFFPipelineBuilder::CHwFFPipelineBuilder(
__inout_ecount(1) CHwFFPipeline *pHP
)
: CHwPipelineBuilder(
pHP,
HwPipeline::FixedFunction
)
{
m_pHP = pHP;
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipeline::FFBuilder::Setup
//
// Synopsis:
// Setup the fixed function pipeline for rendering
//
HRESULT
CHwFFPipelineBuilder::Setup(
MilCompositingMode::Enum eCompositingMode,
__inout_ecount(1) IGeometryGenerator *pIGeometryGenerator,
__inout_ecount(1) IHwPrimaryColorSource *pIPCS,
__in_ecount_opt(1) const IMILEffectList *pIEffects,
__in_ecount(1) const CHwBrushContext *pEffectContext
)
{
HRESULT hr = S_OK;
CHwPipelineBuilder::InitializePipelineMembers(
eCompositingMode,
pIGeometryGenerator
);
IFC(CHwPipelineBuilder::SendPipelineOperations(
pIPCS,
pIEffects,
pEffectContext,
pIGeometryGenerator
));
FinalizeBlendOperations(
eCompositingMode
);
Cleanup:
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwFFPipeline::FinalizeBlendOperations
//
// Synopsis:
// Examine the pipeline after all the basic operations have been added and
// make any adjustments to yield a valid pipeline
//
void
CHwFFPipelineBuilder::FinalizeBlendOperations(
MilCompositingMode::Enum eCompositingMode
)
{
//
// Assertions for the currently very limited pipeline
//
// Currently implemented pipeline operations are:
// Primary operation - from primary color source (required)
// Set_Constant
// or
// Set_Texture
//
// Secondary operations - from secondary color source (optional)
// Mul_ConstAlpha
//
// Tertiary operations
// SetupPerPrimitiveAntialiasingBlend (optional)
//
// There is always a primary operation so there should always be something
// in the pipeline
Assert(m_pHP->m_rgItem.GetCount() > 0);
Assert(m_mvfIn == MILVFAttrXY
|| m_mvfIn == (MILVFAttrXYZ | MILVFAttrDiffuse | MILVFAttrUV1)
|| m_mvfIn == (MILVFAttrXYZ | MILVFAttrUV1)
|| m_mvfIn == (MILVFAttrXYZ | MILVFAttrDiffuse | MILVFAttrUV1 | MILVFAttrUV2)
|| m_mvfIn == (MILVFAttrXYZ | MILVFAttrUV1 | MILVFAttrUV2));
#if DBG
MilVertexFormat mvfDbgUsed = GetAvailableForReference() | GetGeneratedComponents();
Assert(
// Set_Constant (+ Antialias)
(mvfDbgUsed == (MILVFAttrXY | MILVFAttrDiffuse))
// or Set_Texture
|| (mvfDbgUsed == (MILVFAttrXY | MILVFAttrUV1))
// or Set_Texture + (Mul_ConstAlpha | Antialias)
|| (mvfDbgUsed == (MILVFAttrXY | MILVFAttrDiffuse | MILVFAttrUV1))
|| (mvfDbgUsed == (MILVFAttrXYZ | MILVFAttrDiffuse | MILVFAttrUV1))
// or Set_Texture + Mul_AlphaMask (with texture coords)
|| (mvfDbgUsed == (MILVFAttrXY | MILVFAttrUV1 | MILVFAttrUV2))
// or Set_Texture + Mul_AlphaMask (with texture coords) + Antialias
|| (mvfDbgUsed == (MILVFAttrXY | MILVFAttrDiffuse | MILVFAttrUV1 | MILVFAttrUV2))
);
#endif
// At least one stage is guaranteed by the primary color source
Assert(GetNumReservedStages() > 0);
Assert(GetNumReservedSamplers() >= 0);
if (GetNumReservedStages() == 1)
{
//
// There is only one pipeline operation- (coming from Set_Constant or Set_Texture)
//
Assert(m_pHP->m_rgItem[0].dwStage == 0);
if (m_pHP->m_rgItem[0].oBlendParams.hbaSrc1 == HBA_Texture)
{
Assert(m_pHP->m_rgItem[0].dwSampler == 0);
}
else
{
Assert(m_pHP->m_rgItem[0].dwSampler == INVALID_PIPELINE_SAMPLER);
}
Assert(m_pHP->m_rgItem[0].oBlendParams.hbaSrc2 == HBA_None);
Assert(m_pHP->m_rgItem[0].eBlendOp == HBO_SelectSource
|| m_pHP->m_rgItem[0].eBlendOp == HBO_SelectSourceColorIgnoreAlpha );
}
else
{
//
// There are multiple pipeline items- see if we can combine several
// color sources into the same stage
//
// This combination is much easier if we can assume that
// the pipeline items are all re-orderable
Assert(GetEarliestItemAvailableForAlphaMultiply() == 0);
// The combination is further simplified knowing that we only
// have two items to deal with
Assert(GetNumReservedStages() <= 3);
int iFirstNonTextureStage = INVALID_PIPELINE_STAGE;
#if DBG
int iDbgNumTexturesEncountered = 0;
#endif
//
// Verifying the pipeline and looking for opportunities to consolidate it.
//
// All items after the first stage are going to involve some sort of multiply, which
// is going to take the current value and multiply it with another argument.
//
// The first stage however, is going to be selecting one parameter. This gives us
// an opportunity to collapse one of the later stages into the first stage, taking it
// from:
//
// Stage diagram
// Before
// Stage 0 Stage N
// Input 1 texture Diffuse
// Input 2 irrelevant Current
// Blend op SelectSource (1) Multiply
//
// After
// Stage 0
// Input 1 Diffuse
// Input 2 Texture
// Blend op Multiply
//
// It's easier for us to collapse a non-texture argument, because we don't have to
// worry about setting another texture stage. So while we validate the pipeline
// we search for a non-texture argument.
//
// Future Consideration: Could do further consolidation if stage 0 = diffuse && stage 1 = texture
for (int iStage = 0; iStage < GetNumReservedStages(); iStage++)
{
HwPipelineItem const &curItem = m_pHP->m_rgItem[iStage];
if (iStage == 0)
{
//
// Our First stage should be selecting the source.
//
Assert( curItem.eBlendOp == HBO_SelectSource
|| curItem.eBlendOp == HBO_SelectSourceColorIgnoreAlpha
);
}
else
{
//
// All non-first stages should involve a multiply
//
Assert( curItem.eBlendOp == HBO_Multiply
|| curItem.eBlendOp == HBO_MultiplyAlphaOnly
|| curItem.eBlendOp == HBO_MultiplyColorIgnoreAlpha
|| curItem.eBlendOp == HBO_MultiplyByAlpha
);
Assert(curItem.oBlendParams.hbaSrc2 == HBA_Current);
}
if (curItem.oBlendParams.hbaSrc1 != HBA_Texture)
{
if (iFirstNonTextureStage == INVALID_PIPELINE_STAGE)
{
iFirstNonTextureStage = iStage;
}
Assert(curItem.oBlendParams.hbaSrc1 == HBA_Diffuse);
}
else
{
#if DBG
Assert(curItem.dwSampler == static_cast<DWORD>(iDbgNumTexturesEncountered));
iDbgNumTexturesEncountered++;
#endif
}
}
//
// If we found a non-texture stage we can combine it with the 1st ("select")
// stage.
//
if (iFirstNonTextureStage != INVALID_PIPELINE_STAGE)
{
HwBlendOp eNewBlendOp;
HwBlendArg eNewBlendArg1;
HwBlendArg eNewBlendArg2;
HwPipelineItem &oFirstItem = m_pHP->m_rgItem[0];
HwPipelineItem &oCollapsableItem = m_pHP->m_rgItem[iFirstNonTextureStage];
//
// We're taking the first stage from a select source to a multiply, so
// determine which kind of multiply we need to do.
//
if (oFirstItem.eBlendOp == HBO_SelectSourceColorIgnoreAlpha)
{
Assert(oCollapsableItem.eBlendOp == HBO_Multiply);
eNewBlendOp = HBO_MultiplyColorIgnoreAlpha;
}
else
{
eNewBlendOp = oCollapsableItem.eBlendOp;
}
eNewBlendArg1 = oCollapsableItem.oBlendParams.hbaSrc1;
eNewBlendArg2 = oFirstItem.oBlendParams.hbaSrc1;
oFirstItem.eBlendOp = eNewBlendOp;
oFirstItem.oBlendParams.hbaSrc1 = eNewBlendArg1;
oFirstItem.oBlendParams.hbaSrc2 = eNewBlendArg2;
oCollapsableItem.eBlendOp = HBO_Nop;
//
// Decrease the stage number since we are using one less stage now
//
for (UINT i = iFirstNonTextureStage; static_cast<INT>(i) < GetNumReservedStages(); i++)
{
m_pHP->m_rgItem[i].dwStage--;
}
DecrementNumStages();
}
}
//
// Fix-up the need of SelectTextureIgnoreAlpha to have white as diffuse color
// The vertex builder is required (expected) to have white as the
// default value if nothing else has been specified. We could
// eliminate that requirement by adding a new solid white color
// source to the pipe line item list.
//
if ( m_pHP->m_rgItem[0].eBlendOp == HBO_SelectSourceColorIgnoreAlpha
&& m_pHP->m_rgItem[0].oBlendParams.hbaSrc1 == HBA_Texture
)
{
if (GetAvailableForGeneration() & MILVFAttrDiffuse)
{
//
// Make sure diffuse value gets set. No color source should try
// to use this location so it should default to solid white.
//
// We should only be here if we're rendering 2D aliased.
//
GenerateVertexAttribute(MILVFAttrDiffuse);
}
}
//
// Set first blend stage that should be disabled
//
m_pHP->m_dwFirstUnusedStage = GetNumReservedStages();
//
// Compute the final vertex attributes we must fill-in to send data to
// DrawPrimitive.
//
// We always leave Z test enabled so we must always specify Z in vertices.
//
if (GetAvailableForGeneration() & MILVFAttrZ)
{
GenerateVertexAttribute(MILVFAttrZ);
}
//
// Setup composition mode
//
// Source over without transparency is equivalent to source copy, but
// source copy is faster, so we check for it and promote the mode to
// sourcecopy.
//
if ( eCompositingMode == MilCompositingMode::SourceOver
&& !m_fAntiAliasUsed
&& m_pHP->m_dwFirstUnusedStage == 1
&& ( ( m_pHP->m_rgItem[0].eBlendOp == HBO_SelectSource
&& m_pHP->m_rgItem[0].pHwColorSource->IsOpaque())
|| m_pHP->m_rgItem[0].eBlendOp == HBO_SelectSourceColorIgnoreAlpha)
)
{
eCompositingMode = MilCompositingMode::SourceCopy;
}
m_pHP->SetupCompositionMode(
eCompositingMode
);
return;
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipeline::FFBuilder::AddPipelineItem
//
// Synopsis:
// Adds a new pipeline item to the pipeline
//
//------------------------------------------------------------------------------
HRESULT
CHwFFPipelineBuilder::AddFFPipelineItem(
HwBlendOp eBlendOp,
HwBlendArg hbaSrc1,
HwBlendArg hbaSrc2,
MilVertexFormatAttribute mvfaSourceLocation,
__in_ecount_opt(1) CHwColorSource *pHwColorSource
)
{
HRESULT hr = S_OK;
// No-op is designed for use in and after finalize blend operations only
Assert(eBlendOp != HBO_Nop);
// If we not performing a blend, there is no need for src 2
if ( eBlendOp == HBO_SelectSource
|| eBlendOp == HBO_SelectSourceColorIgnoreAlpha)
{
Assert(hbaSrc2 == HBA_None);
}
// It is not possible to put two textures in one pipeline item
// so let us enforce a convention that textures go in src 1
Assert(hbaSrc2 != HBA_Texture);
HwPipelineItem *pItem = NULL;
IFC(m_pHP->AddPipelineItem(&pItem));
Assert(pItem);
pItem->dwStage = ReserveCurrentStage();
if (hbaSrc1 == HBA_Texture)
{
// samplers are only needed for textures
pItem->dwSampler = ReserveCurrentTextureSampler();
}
else
{
pItem->dwSampler = UINT_MAX; // No sampler
}
pItem->eBlendOp = eBlendOp;
pItem->oBlendParams.hbaSrc1 = hbaSrc1;
pItem->oBlendParams.hbaSrc2 = hbaSrc2;
// If the operation does not allow alpha multiply in earlier stage advance
// tracking marker to this item (independent of whether the color sources
// support alpha scaling.)
if (!sc_BlendOpProperties[eBlendOp].AllowsAlphaMultiplyInEarlierStage)
{
SetLastItemAsEarliestAvailableForAlphaMultiply();
}
// Assert that the vertex attribute is not in use OR that we have special
// case of reuse when the attribute is for texture and is already provided.
// Having a constant source that does not truly require particular
// coordinates is not good enough because the pipeline builder just isn't
// prepared for the situation, which will likely result in three texture
// stages and require TexCoordinateIndex different than stage.
Assert( (GetAvailableForGeneration() & mvfaSourceLocation)
|| (GetAvailableForReference() & mvfaSourceLocation)
);
if ( (HWPIPELINE_ANTIALIAS_LOCATION == mvfaSourceLocation)
// NULL pHwColorSource indicates addition of AA scale factor; so
// skip piggyback marking for it.
&& pHwColorSource
)
{
SetLastItemAsAAPiggyback();
}
if (GetAvailableForGeneration() & mvfaSourceLocation)
{
Assert(!(GetAvailableForReference() & mvfaSourceLocation));
GenerateVertexAttribute(mvfaSourceLocation);
}
pItem->mvfaSourceLocation = mvfaSourceLocation;
pItem->pHwColorSource = pHwColorSource;
// This Addref will be handled by the base pipeline builder
if (pHwColorSource)
{
pHwColorSource->AddRef();
pHwColorSource->ResetForPipelineReuse();
}
Cleanup:
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipeline::FFBuilder::Set_Constant
//
// Synopsis:
// Takes the given color source and sets it as the first color source for
// the hardware blending pipeline
//
HRESULT
CHwFFPipelineBuilder::Set_Constant(
__in_ecount(1) CHwConstantColorSource *pConstant
)
{
HRESULT hr = S_OK;
// Parameter Assertions
Assert(pConstant->GetSourceType() & CHwColorSource::Constant);
// Member Assertions
// There shouldn't be any items or stages yet
Assert(m_pHP->m_rgItem.GetCount() == 0);
Assert(GetEarliestItemAvailableForAlphaMultiply() == INVALID_PIPELINE_ITEM);
Assert(GetNumReservedStages() == 0);
Assert(GetNumReservedSamplers() == 0);
MilVertexFormatAttribute mvfa;
HwBlendArg hba;
//
// Find an acceptable vertex field
//
if (GetAvailableForGeneration() & MILVFAttrDiffuse)
{
mvfa = MILVFAttrDiffuse;
hba = HBA_Diffuse;
}
else
{
//
// Future Consideration: Use a alpha scale texture stage instead.
//
// Setting the a texture stage to be an alpha scale value should be
// supported on all our hardware and should be more efficient than
// using a texture.
//
// Required for logic to work
Assert(GetAvailableForReference() & MILVFAttrUV1);
mvfa = MILVFAttrUV1;
hba = HBA_Texture;
}
//
// Add the first color source
//
IFC(AddFFPipelineItem(
HBO_SelectSource,
hba,
HBA_None,
mvfa,
pConstant
));
Cleanup:
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipeline::FFBuilder::Set_Texture
//
// Synopsis:
// Takes the given color source and sets it as the first color source for
// the hardware blending pipeline
//
// If it is to be bump mapped the bump map operation has to specified by a
// call to Set_BumpMap just before this call.
//
HRESULT
CHwFFPipelineBuilder::Set_Texture(
__in_ecount(1) CHwTexturedColorSource *pTexture
)
{
HRESULT hr = S_OK;
// Parameter Assertions
Assert(pTexture->GetSourceType() != CHwColorSource::Constant);
// Member Assertions
// There shouldn't be any items or stages yet
Assert(m_pHP->m_rgItem.GetCount() == 0);
Assert(GetEarliestItemAvailableForAlphaMultiply() == INVALID_PIPELINE_ITEM);
Assert(GetNumReservedStages() == 0);
Assert(GetNumReservedSamplers() == 0);
//
// Add the first color source
//
//
// Future Consideration: Seperate IgnoreAlpha BlendOp into multiple items
//
// This is dangerous. Select Source Color Ignore Alpha says it's the first stage,
// but its texture states specify that it's going to grab alpha from current.
// This works because specifying current on stage 0 will draw from diffuse, and
// we make sure to always fill diffuse.
//
// If the pipeline supports more rendering operations especially ones that don't
// allow re-ordering of the stages, we may have to break
// HBO_SelectSourceColorIgnoreAlpha into more than one stage.
//
IFC(AddFFPipelineItem(
HBO_SelectSource,
HBA_Texture,
HBA_None,
MILVFAttrUV1,
pTexture
));
Cleanup:
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwFFPipelineBuilder::Set_RadialGradient
//
// Synopsis:
// Not implemented in the fixed function pipeline
//
//------------------------------------------------------------------------------
HRESULT
CHwFFPipelineBuilder::Set_RadialGradient(
__in_ecount(1) CHwRadialGradientColorSource *pRadialGradient
)
{
RRETURN(E_NOTIMPL);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipeline::FFBuilder::Mul_ConstAlpha
//
// Synopsis:
// Add a blend operation that scales all previous rendering by the given
// alpha value
//
// This operation may be added as a modifier to an existing color source or
// as an independent operation. If added via modification to an existing
// color source then the results of the pipeline should be respected just
// as if it were added as a new operation.
//
HRESULT
CHwFFPipelineBuilder::Mul_ConstAlpha(
CHwConstantAlphaColorSource *pAlphaColorSource
)
{
HRESULT hr = S_OK;
float flAlpha = pAlphaColorSource->GetAlpha();
// There should be at least one item that has marked available alpha mul
Assert(m_pHP->m_rgItem.GetCount() > 0);
Assert(GetEarliestItemAvailableForAlphaMultiply() >= 0);
CHwConstantAlphaScalableColorSource *pScalableAlphaSource = NULL;
if (TryToMultiplyConstantAlphaToExistingStage(pAlphaColorSource))
{
//
// We've succeeded in multiplying the alpha color source to an existing
// stage, so early out.
//
goto Cleanup;
}
//
// There is no color source available to apply this scale to directly.
// Add an additional blending stage.
//
MilVertexFormatAttribute mvfa;
mvfa = MILVFAttrNone;
HwBlendArg hba;
hba = HBA_None;
//
// Find an acceptable vertex field
//
if (GetAvailableForGeneration() & MILVFAttrDiffuse)
{
mvfa = MILVFAttrDiffuse;
hba = HBA_Diffuse;
}
else if (GetAvailableForReference() & MILVFAttrUV1)
{
// Piggyback on a texture coordinate set that is already requested.
mvfa = MILVFAttrUV1;
hba = HBA_Texture;
}
else if (GetAvailableForGeneration() & MILVFAttrSpecular)
{
mvfa = MILVFAttrSpecular;
hba = HBA_Specular;
}
if (mvfa != MILVFAttrNone)
{
//
// Append alpha scale blend operation
//
IFC(CHwConstantAlphaScalableColorSource::Create(
m_pHP->m_pDevice,
flAlpha,
NULL, // No orignal color source
&m_pHP->m_dbScratch,
&pScalableAlphaSource
));
IFC(AddFFPipelineItem(
m_eAlphaMultiplyOp,
hba,
HBA_Current,
mvfa,
pScalableAlphaSource
));
// Remember this location holds an alpha scalable color source
SetLastItemAsAlphaScalable();
}
else
{
// No suitable vertex location could be found
IFC(E_NOTIMPL);
}
Cleanup:
ReleaseInterfaceNoNULL(pScalableAlphaSource);
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwFFPipelineBuilder::Mul_AlphaMask
//
// Synopsis:
//
HRESULT
CHwFFPipelineBuilder::Mul_AlphaMask(
__in_ecount(1) CHwTexturedColorSource *pAlphaMask
)
{
HRESULT hr = S_OK;
// There should be at least one item that has marked available alpha mul
Assert(m_pHP->m_rgItem.GetCount() > 0);
Assert(GetEarliestItemAvailableForAlphaMultiply() >= 0);
Assert( m_eAlphaMultiplyOp == HBO_Multiply
|| m_eAlphaMultiplyOp == HBO_MultiplyAlphaOnly );
HwBlendOp blendop = m_eAlphaMultiplyOp;
if (blendop == HBO_Multiply)
{
blendop = HBO_MultiplyByAlpha;
}
MilVertexFormatAttribute mvfaSource = VerticesArePreGenerated() ?
MILVFAttrUV1 :
MILVFAttrUV2;
IFC(AddFFPipelineItem(
blendop,
HBA_Texture,
HBA_Current,
mvfaSource,
pAlphaMask
));
if (pAlphaMask->IsAlphaScalable())
{
// Remember this location holds an alpha scalable color source
SetLastItemAsAlphaScalable();
}
Cleanup:
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwFFPipelineBuilder::Add_Lighting
//
// Synopsis:
// Adds an adds a lighting colorsource.
//
//------------------------------------------------------------------------------
HRESULT
CHwFFPipelineBuilder::Add_Lighting(
__in_ecount(1) CHwLightingColorSource *pLightingSource
)
{
HRESULT hr = S_OK;
IFC(AddFFPipelineItem(
m_eAlphaMultiplyOp,
HBA_Diffuse,
HBA_Current,
MILVFAttrDiffuse,
pLightingSource
));
Cleanup:
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwFFPipelineBuilder::Mul_BlendColors
//
// Synopsis:
// Multiplies the pipeline by a set of blend colors.
//
//------------------------------------------------------------------------------
HRESULT
CHwFFPipelineBuilder::Mul_BlendColorsInternal(
__in_ecount(1) CHwColorComponentSource *pBlendColorSource
)
{
HRESULT hr = S_OK;
HwBlendArg hbaParam1;
MilVertexFormatAttribute mvfaSource;
CHwColorComponentSource::VertexComponent eLocation = pBlendColorSource->GetComponentLocation();
switch(eLocation)
{
case CHwColorComponentSource::Diffuse:
{
hbaParam1 = HBA_Diffuse;
mvfaSource = MILVFAttrDiffuse;
}
break;
case CHwColorComponentSource::Specular:
{
hbaParam1 = HBA_Specular;
mvfaSource = MILVFAttrSpecular;
}
break;
default:
NO_DEFAULT("Unknown Color Component Source");
}
IFC(AddFFPipelineItem(
m_eAlphaMultiplyOp,
hbaParam1,
HBA_Current,
mvfaSource,
pBlendColorSource
));
Cleanup:
RRETURN(hr);
}
| 28.142857 | 125 | 0.586651 | nsivov |
064f37b6b6eea6975c4f88c8cdf53bf52b648497 | 6,375 | cc | C++ | chromium/chrome/browser/ui/passwords/manage_passwords_view_utils.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/chrome/browser/ui/passwords/manage_passwords_view_utils.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/chrome/browser/ui/passwords/manage_passwords_view_utils.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/passwords/manage_passwords_view_utils.h"
#include <stddef.h>
#include <algorithm>
#include "base/strings/utf_string_conversions.h"
#include "chrome/grit/chromium_strings.h"
#include "chrome/grit/generated_resources.h"
#include "components/autofill/core/common/password_form.h"
#include "components/password_manager/core/browser/affiliation_utils.h"
#include "components/url_formatter/elide_url.h"
#include "grit/components_strings.h"
#include "net/base/net_util.h"
#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/gfx/image/image_skia_operations.h"
#include "ui/gfx/range/range.h"
#include "url/gurl.h"
namespace {
// Checks whether two URLs are from the same domain or host.
bool SameDomainOrHost(const GURL& gurl1, const GURL& gurl2) {
return net::registry_controlled_domains::SameDomainOrHost(
gurl1, gurl2,
net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
}
} // namespace
const int kAvatarImageSize = 40;
gfx::ImageSkia ScaleImageForAccountAvatar(gfx::ImageSkia skia_image) {
gfx::Size size = skia_image.size();
if (size.height() != size.width()) {
gfx::Rect target(size);
int side = std::min(size.height(), size.width());
target.ClampToCenteredSize(gfx::Size(side, side));
skia_image = gfx::ImageSkiaOperations::ExtractSubset(skia_image, target);
}
return gfx::ImageSkiaOperations::CreateResizedImage(
skia_image,
skia::ImageOperations::RESIZE_BEST,
gfx::Size(kAvatarImageSize, kAvatarImageSize));
}
void GetSavePasswordDialogTitleTextAndLinkRange(
const GURL& user_visible_url,
const GURL& form_origin_url,
bool is_smartlock_branding_enabled,
PasswordTittleType dialog_type,
base::string16* title,
gfx::Range* title_link_range) {
std::vector<size_t> offsets;
std::vector<base::string16> replacements;
int title_id = 0;
switch (dialog_type) {
case PasswordTittleType::SAVE_PASSWORD:
title_id = IDS_SAVE_PASSWORD;
break;
case PasswordTittleType::SAVE_ACCOUNT:
title_id = IDS_SAVE_ACCOUNT;
break;
case PasswordTittleType::UPDATE_PASSWORD:
title_id = IDS_UPDATE_PASSWORD;
break;
}
// Check whether the registry controlled domains for user-visible URL (i.e.
// the one seen in the omnibox) and the password form post-submit navigation
// URL differs or not.
if (!SameDomainOrHost(user_visible_url, form_origin_url)) {
title_id = IDS_SAVE_PASSWORD_TITLE;
// TODO(palmer): Look into passing real language prefs here, not "".
// crbug.com/498069.
replacements.push_back(url_formatter::FormatUrlForSecurityDisplay(
form_origin_url, std::string()));
}
if (is_smartlock_branding_enabled) {
// "Google Smart Lock" should be a hyperlink.
base::string16 title_link =
l10n_util::GetStringUTF16(IDS_PASSWORD_MANAGER_SMART_LOCK);
replacements.insert(replacements.begin(), title_link);
*title = l10n_util::GetStringFUTF16(title_id, replacements, &offsets);
*title_link_range =
gfx::Range(offsets[0], offsets[0] + title_link.length());
} else {
replacements.insert(
replacements.begin(),
l10n_util::GetStringUTF16(IDS_PASSWORD_MANAGER_TITLE_BRAND));
*title = l10n_util::GetStringFUTF16(title_id, replacements, &offsets);
}
}
void GetManagePasswordsDialogTitleText(const GURL& user_visible_url,
const GURL& password_origin_url,
base::string16* title) {
// Check whether the registry controlled domains for user-visible URL
// (i.e. the one seen in the omnibox) and the managed password origin URL
// differ or not.
if (!SameDomainOrHost(user_visible_url, password_origin_url)) {
// TODO(palmer): Look into passing real language prefs here, not "".
base::string16 formatted_url = url_formatter::FormatUrlForSecurityDisplay(
password_origin_url, std::string());
*title = l10n_util::GetStringFUTF16(
IDS_MANAGE_PASSWORDS_TITLE_DIFFERENT_DOMAIN, formatted_url);
} else {
*title = l10n_util::GetStringUTF16(IDS_MANAGE_PASSWORDS_TITLE);
}
}
void GetAccountChooserDialogTitleTextAndLinkRange(
bool is_smartlock_branding_enabled,
base::string16* title,
gfx::Range* title_link_range) {
GetBrandedTextAndLinkRange(is_smartlock_branding_enabled,
IDS_PASSWORD_MANAGER_ACCOUNT_CHOOSER_TITLE,
IDS_PASSWORD_MANAGER_ACCOUNT_CHOOSER_TITLE,
title, title_link_range);
}
void GetAutoSigninPromptFirstRunExperienceExplanation(
bool is_smartlock_branding_enabled,
base::string16* explanation,
gfx::Range* explanation_link_range) {
GetBrandedTextAndLinkRange(
is_smartlock_branding_enabled,
IDS_MANAGE_PASSWORDS_AUTO_SIGNIN_SMART_LOCK_WELCOME,
IDS_MANAGE_PASSWORDS_AUTO_SIGNIN_DEFAULT_WELCOME,
explanation, explanation_link_range);
}
void GetBrandedTextAndLinkRange(bool is_smartlock_branding_enabled,
int smartlock_string_id,
int default_string_id,
base::string16* out_string,
gfx::Range* link_range) {
if (is_smartlock_branding_enabled) {
size_t offset;
base::string16 brand_name =
l10n_util::GetStringUTF16(IDS_PASSWORD_MANAGER_SMART_LOCK);
*out_string = l10n_util::GetStringFUTF16(smartlock_string_id, brand_name,
&offset);
*link_range = gfx::Range(offset, offset + brand_name.length());
} else {
*out_string = l10n_util::GetStringFUTF16(
default_string_id,
l10n_util::GetStringUTF16(IDS_PASSWORD_MANAGER_TITLE_BRAND));
*link_range = gfx::Range();
}
}
base::string16 GetDisplayUsername(const autofill::PasswordForm& form) {
return form.username_value.empty()
? l10n_util::GetStringUTF16(IDS_PASSWORD_MANAGER_EMPTY_LOGIN)
: form.username_value;
}
| 38.173653 | 78 | 0.713255 | wedataintelligence |
0650d75d16eac84dbc9aa8c85c38361f5d0cdfc7 | 834 | hpp | C++ | include/lastfmpp/image.hpp | chrismanning/lastfmpp | 59439e62d2654359a48f8244a4b69b95d398beb3 | [
"MIT"
] | null | null | null | include/lastfmpp/image.hpp | chrismanning/lastfmpp | 59439e62d2654359a48f8244a4b69b95d398beb3 | [
"MIT"
] | null | null | null | include/lastfmpp/image.hpp | chrismanning/lastfmpp | 59439e62d2654359a48f8244a4b69b95d398beb3 | [
"MIT"
] | null | null | null | /**************************************************************************
** Copyright (C) 2015 Christian Manning
**
** This software may be modified and distributed under the terms
** of the MIT license. See the LICENSE file for details.
**************************************************************************/
#ifndef LASTFM_IMAGE_HPP
#define LASTFM_IMAGE_HPP
#include <unordered_map>
#include <lastfmpp/lastfmpp.hpp>
#include <lastfmpp/uri.hpp>
namespace lastfmpp {
enum class image_size { small, medium, large, extralarge, mega };
struct LASTFM_EXPORT image {
image() = default;
const uri_t& uri() const;
void uri(uri_t);
image_size size() const;
void size(image_size);
private:
uri_t m_uri;
image_size m_size = image_size::small;
};
} // namespace lastfm
#endif // LASTFM_IMAGE_HPP
| 22.540541 | 75 | 0.585132 | chrismanning |
0652f4924c04ee0dae329934fb227a77443406ec | 3,607 | hpp | C++ | src/libraries/core/interpolation/surfaceInterpolation/limitedSchemes/Limited/Limited.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/core/interpolation/surfaceInterpolation/limitedSchemes/Limited/Limited.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/core/interpolation/surfaceInterpolation/limitedSchemes/Limited/Limited.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | /*---------------------------------------------------------------------------*\
Copyright (C) 2011-2105 OpenFOAM Foundation
-------------------------------------------------------------------------------
License
This file is part of CAELUS.
CAELUS is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
CAELUS 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 CAELUS. If not, see <http://www.gnu.org/licenses/>.
Class
CML::LimitedLimiter
Description
CML::LimitedLimiter
\*---------------------------------------------------------------------------*/
#ifndef Limited_H
#define Limited_H
#include "vector.hpp"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace CML
{
/*---------------------------------------------------------------------------*\
Class LimitedLimiter Declaration
\*---------------------------------------------------------------------------*/
template<class LimitedScheme>
class LimitedLimiter
:
public LimitedScheme
{
//- Lower and upper bound of the variable
scalar lowerBound_, upperBound_;
void checkParameters(Istream& is)
{
if (lowerBound_ > upperBound_)
{
FatalIOErrorInFunction(is)
<< "Invalid bounds. Lower = " << lowerBound_
<< " Upper = " << upperBound_
<< ". Lower bound is higher than the upper bound."
<< exit(FatalIOError);
}
}
public:
LimitedLimiter
(
const scalar lowerBound,
const scalar upperBound,
Istream& is
)
:
LimitedScheme(is),
lowerBound_(lowerBound),
upperBound_(upperBound)
{
checkParameters(is);
}
LimitedLimiter(Istream& is)
:
LimitedScheme(is),
lowerBound_(readScalar(is)),
upperBound_(readScalar(is))
{
checkParameters(is);
}
scalar limiter
(
const scalar cdWeight,
const scalar faceFlux,
const scalar phiP,
const scalar phiN,
const vector& gradcP,
const vector& gradcN,
const vector& d
) const
{
// If not between the lower and upper bounds use upwind
if
(
(faceFlux > 0 && (phiP < lowerBound_ || phiN > upperBound_))
|| (faceFlux < 0 && (phiN < lowerBound_ || phiP > upperBound_))
/*
phiP < lowerBound_
|| phiP > upperBound_
|| phiN < lowerBound_
|| phiN > upperBound_
*/
)
{
return 0;
}
else
{
return LimitedScheme::limiter
(
cdWeight,
faceFlux,
phiP,
phiN,
gradcP,
gradcN,
d
);
}
}
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace CML
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| 25.58156 | 79 | 0.450236 | MrAwesomeRocks |
0653790c4e7d89850c8d214c0d2d3add74b8d1ac | 598 | cpp | C++ | Primitive-Root.cpp | cirno99/Algorithms | 6425b143f406693caf8f882bdfe5497c81df255a | [
"Unlicense"
] | 1,210 | 2016-08-07T13:32:12.000Z | 2022-03-21T01:01:57.000Z | Primitive-Root.cpp | NeilQingqing/Algorithms-2 | c10d4c212fa1fbf8b9fb3c781d61f41e75e96aaa | [
"Unlicense"
] | 7 | 2016-09-11T11:41:03.000Z | 2017-10-29T02:12:57.000Z | Primitive-Root.cpp | NeilQingqing/Algorithms-2 | c10d4c212fa1fbf8b9fb3c781d61f41e75e96aaa | [
"Unlicense"
] | 514 | 2016-10-17T03:52:16.000Z | 2022-03-19T16:23:33.000Z | #include <cstdio>
typedef long long ll;
using namespace std;
ll p;
ll qpow(ll x, ll y)
{
if (y == 1) return x;
ll t = qpow(x, y >> 1);
t = t * t % p;
if ((y & 1) == 0) return t;
return t * x % p;
}
int main()
{
ll x;
while (true)
{
scanf("%lld", &p);
for (ll k = 2; ; k++)
{
x = p - 1;
for (ll i = 2; i * i <= x; i++)
{
if (x % i == 0)
{
if (qpow(k, (p - 1) / i) == 1) goto NEXT;
while (x % i == 0) x /= i;
}
}
if (x != 1)
{
if (qpow(k, (p - 1) / x) == 1) goto NEXT;
}
printf("%lld\n", k);
break;
NEXT:;
}
}
return 0;
}
| 13 | 46 | 0.404682 | cirno99 |
065b60abd82dd78935f3cfdc9cbc8c764ada5733 | 16,479 | hpp | C++ | include/morphotree/tree/mtree.hpp | dennisjosesilva/morphotree | 3be4ff7f36de65772ef273a61b0bc5916e2904d9 | [
"MIT"
] | null | null | null | include/morphotree/tree/mtree.hpp | dennisjosesilva/morphotree | 3be4ff7f36de65772ef273a61b0bc5916e2904d9 | [
"MIT"
] | 3 | 2022-03-23T19:16:08.000Z | 2022-03-28T00:40:19.000Z | include/morphotree/tree/mtree.hpp | dennisjosesilva/morphotree | 3be4ff7f36de65772ef273a61b0bc5916e2904d9 | [
"MIT"
] | null | null | null | #pragma once
#include "morphotree/core/alias.hpp"
#include "morphotree/core/box.hpp"
#include <memory>
#include <list>
#include <vector>
#include <limits>
#include "morphotree/tree/ct_builder.hpp"
#include "morphotree/adjacency/adjacency.hpp"
#include "morphotree/core/sort.hpp"
#include <queue>
#include <stack>
namespace morphotree
{
enum class MorphoTreeType
{
MaxTree,
MinTree,
TreeOfShapes
};
template<class WeightType>
class MTNode
{
public:
using ValueType = WeightType;
using NodePtr = std::shared_ptr<MTNode<WeightType>>;
MTNode(uint id=0);
inline uint id() const { return id_; }
inline uint& id() { return id_; }
inline void id(uint newid) { id_ = newid; }
inline uint32 representative() const { return representative_; }
inline uint32& representative() { return representative_; }
inline void representative(uint32 newrep) { representative_ = newrep; }
inline WeightType& level() { return level_; }
inline WeightType level() const { return level_; }
inline void level(WeightType v) { level_ = v; }
inline const std::vector<uint32>& cnps() const { return cnps_; }
inline void appendCNP(uint32 cnp) { cnps_.push_back(cnp); }
inline void includeCNPS(const std::vector<uint32> &cnps);
inline NodePtr parent() { return parent_; }
inline const NodePtr parent() const { return parent_; }
inline void parent(NodePtr parent) { parent_ = parent;}
inline void appendChild(std::shared_ptr<MTNode> child) { children_.push_back(child); }
inline void includeChildren(const std::vector<NodePtr> &children);
inline void removeChild(NodePtr c) { children_.remove(c); }
inline const std::list<NodePtr>& children() const { return children_; }
std::vector<uint32> reconstruct() const;
std::vector<bool> reconstruct(const Box &domain) const;
std::vector<WeightType> reconstructGrey(const Box &domain,
WeightType backgroundValue=0) const;
NodePtr copy() const;
private:
void reconstruct(std::vector<uint32> &pixels, const NodePtr node) const;
void reconstructGrey(NodePtr node, const Box &domain,
std::vector<WeightType> &f) const;
private:
uint32 id_;
uint32 representative_;
WeightType level_;
std::vector<uint32> cnps_;
NodePtr parent_;
std::list<NodePtr> children_;
};
template<class WeightType>
class MorphologicalTree
{
public:
using NodePtr = typename MTNode<WeightType>::NodePtr;
using NodeType = MTNode<WeightType>;
using TreeWeightType = WeightType;
MorphologicalTree(MorphoTreeType type, const std::vector<WeightType> &f, const CTBuilderResult &res);
MorphologicalTree(MorphoTreeType type, std::vector<uint32> &&cmap, std::vector<NodePtr> &&nodes);
MorphologicalTree(MorphoTreeType type);
const NodePtr node(uint id) const { return nodes_[id]; }
NodePtr node(uint id) { return nodes_[id]; }
const NodePtr root() const { return root_; }
NodePtr root() { return root_; }
inline std::vector<uint32> reconstructNode(uint32 nodeId) const { return nodes_[nodeId]->reconstruct(); }
std::vector<bool> reconstructNode(uint32 nodeId, const Box &domain) const { return nodes_[nodeId]->reconstruct(domain); };
std::vector<uint32> reconstructNodes(std::function<bool(NodePtr)> keep) const;
std::vector<bool> reconstructNodes(std::function<bool(NodePtr)> keep, const Box &domain) const;
uint32 numberOfNodes() const { return nodes_.size(); }
uint32 numberOfCNPs() const { return cmap_.size(); }
void tranverse(std::function<void(const NodePtr node)> visit) const;
std::vector<WeightType> reconstructImage() const;
std::vector<WeightType> reconstructImage(std::function<bool(const NodePtr)> keep) const;
void idirectFilter(std::function<bool(const NodePtr)> keep);
MorphologicalTree<WeightType> directFilter(std::function<bool(const NodePtr)> keep) const;
void traverseByLevel(std::function<void(const NodePtr)> visit) const;
void traverseByLevel(std::function<void(NodePtr)> visit);
inline NodePtr smallComponent(uint32 idx) { return nodes_[cmap_[idx]]; }
inline const NodePtr smallComponent(uint32 idx) const { return nodes_[cmap_[idx]]; }
NodePtr smallComponent(uint32 idx, const std::vector<bool> &mask);
const NodePtr smallComponent(uint32 idx, const std::vector<bool> &mask) const;
MorphologicalTree<WeightType> copy() const;
inline MorphoTreeType type() const { return type_; }
static const uint32 UndefinedIndex;
private:
void performDirectFilter(MorphologicalTree<WeightType> &tree, std::function<bool(const NodePtr)> keep) const;
private:
std::vector<NodePtr> nodes_;
std::vector<uint32> cmap_;
NodePtr root_;
MorphoTreeType type_;
};
template<class WeightType>
MorphologicalTree<WeightType> buildMaxTree(const std::vector<WeightType> &f,
std::shared_ptr<Adjacency> adj);
template<class WeightType>
MorphologicalTree<WeightType> buildMinTree(const std::vector<WeightType> &f,
std::shared_ptr<Adjacency> adj);
// ======================[ IMPLEMENTATION ] ===================================================================
template<typename WeightType>
const uint32 MorphologicalTree<WeightType>::UndefinedIndex = std::numeric_limits<uint32>::max();
template<class WeightType>
MTNode<WeightType>::MTNode(uint id)
:id_{id}, level_{0}, parent_{nullptr}
{}
template<class WeightType>
std::vector<uint32> MTNode<WeightType>::reconstruct() const
{
std::vector<uint32> pixels{cnps_};
for (NodePtr child : children_) {
reconstruct(pixels, child);
}
return pixels;
}
template<class WeightType>
void MTNode<WeightType>::reconstruct(std::vector<uint32> &pixels, const NodePtr node) const
{
pixels.insert(pixels.end(), node->cnps().begin(), node->cnps().end());
for (NodePtr child: node->children()) {
reconstruct(pixels, child);
}
}
template<class WeightType>
std::vector<bool> MTNode<WeightType>::reconstruct(const Box &domain) const
{
std::vector<uint32> indices = reconstruct();
std::vector<bool> img(domain.numberOfPoints(), false);
for (uint32 i : indices) {
img[i] = true;
}
return img;
}
template<class WeightType>
std::vector<WeightType> MTNode<WeightType>::reconstructGrey(const Box &domain,
WeightType backgroundValue) const
{
std::vector<WeightType> f(domain.numberOfPoints(), backgroundValue);
for (uint32 p : cnps()) {
f[p] = level();
}
for (NodePtr child :children()) {
reconstructGrey(child, domain, f);
}
return f;
}
template<class WeightType>
void MTNode<WeightType>::reconstructGrey(NodePtr node, const Box &domain,
std::vector<WeightType> &f) const
{
for (uint32 p : node->cnps()) {
f[p] = node->level();
}
for (NodePtr c : node->children()) {
reconstructGrey(c, domain, f);
}
}
template<class WeightType>
void MTNode<WeightType>::includeCNPS(const std::vector<uint32>& cnps)
{
cnps_.insert(cnps_.end(), cnps.begin(), cnps.end());
}
template<class WeightType>
void MTNode<WeightType>::includeChildren(const std::vector<NodePtr> &children)
{
children_.insert(children_.end(), children.begin(), children.end());
}
template<class WeightType>
typename MTNode<WeightType>::NodePtr MTNode<WeightType>::copy() const
{
NodePtr cnode = std::make_shared<MTNode<WeightType>>(id_);
cnode->level(level_);
cnode->cnps_ = cnps_;
cnode->representative_ = representative_;
return cnode;
}
// ========================== [TREEE] =========================================================================
template<class WeightType>
MorphologicalTree<WeightType>::MorphologicalTree(MorphoTreeType type)
:type_{type}
{ }
template<class WeightType>
MorphologicalTree<WeightType>::MorphologicalTree(MorphoTreeType type,
std::vector<uint32> &&cmap, std::vector<NodePtr> &&nodes)
:cmap_{cmap}, nodes_{nodes}, type_{type}
{
root_ = nodes_[0];
}
template<class WeightType>
MorphologicalTree<WeightType>::MorphologicalTree(MorphoTreeType type,
const std::vector<WeightType> &f, const CTBuilderResult &res)
:type_{type}
{
const uint32 UNDEF = std::numeric_limits<uint32>::max();
std::vector<uint32> sortedLevelRoots;
cmap_.resize(f.size(), UNDEF);
for (uint32 i = 0; i < res.R.size(); i++) {
uint32 p = res.R[i];
if (f[res.parent[p]] != f[p] || res.parent[p] == p)
sortedLevelRoots.push_back(p);
}
nodes_.resize(sortedLevelRoots.size(), nullptr);
uint32 p = sortedLevelRoots[sortedLevelRoots.size()-1];
NodePtr root = std::make_shared<NodeType>(0);
root->level(f[p]);
root->appendCNP(p);
root->representative(p);
root->parent(nullptr);
cmap_[p] = root->id();
nodes_[0] = root;
root_ = root;
for (uint32 i = 2; i <= sortedLevelRoots.size(); i++) {
uint32 p = sortedLevelRoots[sortedLevelRoots.size()-i];
cmap_[p] = i-1;
NodePtr node = std::make_shared<NodeType>(i-1);
NodePtr parentNode = nodes_[cmap_[res.parent[p]]];
node->id(i-1);
node->parent(parentNode);
node->level(f[p]);
node->appendCNP(p);
node->representative(p);
parentNode->appendChild(node);
nodes_[i-1] = node;
}
for (uint32 i = 0; i < f.size(); i++) {
if (cmap_[i] == UNDEF) {
cmap_[i] = cmap_[res.parent[i]];
nodes_[cmap_[i]]->appendCNP(i);
}
}
}
template<typename WeightType>
std::vector<uint32>
MorphologicalTree<WeightType>::reconstructNodes(std::function<bool(NodePtr)> keep) const
{
std::vector<uint32> rec;
std::stack<NodePtr> s;
s.push(root_);
while (!s.empty()) {
NodePtr n = s.top();
s.pop();
if ((n->id() != root_->id()) && keep(n)) {
std::vector<uint32> recn = n->reconstruct();
rec.insert(rec.end(), recn.begin(), recn.end());
}
else {
for (NodePtr c : n->children())
s.push(c);
}
}
return rec;
}
template<typename WeightType>
std::vector<bool> MorphologicalTree<WeightType>::reconstructNodes(std::function<
bool(NodePtr)> keep, const Box &domain) const
{
std::vector<bool> bin(domain.numberOfPoints(), false);
std::vector<uint32> pixels = reconstructNodes(keep);
for (const uint32 pidx : pixels) {
bin[pidx] = true;
}
return bin;
}
template<class WeightType>
void MorphologicalTree<WeightType>::tranverse(std::function<void(const NodePtr node)> visit) const
{
for(uint32 i = 1; i <= nodes_.size(); i++) {
visit(nodes_[nodes_.size() - i]);
}
}
template<class WeightType>
MorphologicalTree<WeightType> buildMaxTree(const std::vector<WeightType> &f,
std::shared_ptr<Adjacency> adj)
{
CTBuilder<WeightType> builder;
std::vector<uint32> R = sortIncreasing(f);
return MorphologicalTree<WeightType>(MorphoTreeType::MaxTree, f, builder.build(f, adj, R));
}
template<class WeightType>
MorphologicalTree<WeightType> buildMinTree(const std::vector<WeightType> &f,
std::shared_ptr<Adjacency> adj)
{
CTBuilder<WeightType> builder;
std::vector<uint32> R = sortDecreasing(f);
return MorphologicalTree<WeightType>(MorphoTreeType::MinTree, f, builder.build(f, adj, R));
}
template<typename WeightType>
std::vector<WeightType> MorphologicalTree<WeightType>::reconstructImage() const
{
std::vector<WeightType> f(cmap_.size());
for (NodePtr node : nodes_) {
for (uint idx : node->cnps()) {
f[idx] = node->level();
}
}
return f;
}
template<typename WeightType>
std::vector<WeightType> MorphologicalTree<WeightType>::reconstructImage(
std::function<bool(const NodePtr)> keep) const
{
using namespace std;
vector<vector<uint32>> up(numberOfNodes(), vector<uint32>());
vector<WeightType> f(cmap_.size(), 0);
tranverse([&up, &keep, &f](const NodePtr node){
if (keep(node)) {
for (uint32 pidx : node->cnps())
f[pidx] = node->level();
for (uint32 pidx : up[node->id()])
f[pidx] = node->level();
}
else {
const vector<uint32> &cnps = node->cnps();
const vector<uint32> &upCnps = up[node->id()];
vector<uint32> &upParent = up[node->parent()->id()];
upParent.insert(upParent.end(), cnps.begin(), cnps.end());
upParent.insert(upParent.end(), upCnps.begin(), upCnps.end());
}
});
return f;
}
template<class WeightType>
void MorphologicalTree<WeightType>::idirectFilter(std::function<bool(const NodePtr)> keep)
{
performDirectFilter(*this, keep);
}
template<class WeightType>
MorphologicalTree<WeightType> MorphologicalTree<WeightType>::directFilter(
std::function<bool(const NodePtr)> keep) const
{
MorphologicalTree<WeightType> ctree = copy();
performDirectFilter(ctree, keep);
return ctree;
}
template<typename WeightType>
void MorphologicalTree<WeightType>::performDirectFilter(MorphologicalTree<WeightType> &tree,
std::function<bool(const NodePtr)> keep) const
{
// remove node from data structure.
uint32 numRemovedNodes = 0;
std::queue<NodePtr> queue;
queue.push(tree.root());
while (!queue.empty())
{
NodePtr node = queue.front();
queue.pop();
for (NodePtr c : node->children()) {
queue.push(c);
}
if (!keep(node) && node->parent() != nullptr) {
numRemovedNodes++;
NodePtr parentNode = node->parent();
parentNode->includeCNPS(node->cnps());
parentNode->removeChild(node);
for (NodePtr c : node->children()) {
parentNode->appendChild(c);
c->parent(parentNode);
}
}
}
// fix cmap and nodes arrays
uint32 prevNumOfNodes = tree.numberOfNodes();
tree.nodes_.clear();
tree.nodes_.resize(prevNumOfNodes - numRemovedNodes);
uint32 newId = 0;
tree.traverseByLevel([&tree, &newId](NodePtr n) {
n->id(newId);
tree.nodes_[newId] = n;
for (uint32 idx : n->cnps()) {
tree.cmap_[idx] = newId;
}
newId++;
});
}
template<typename WeightType>
void MorphologicalTree<WeightType>::traverseByLevel(std::function<void(const NodePtr)> visit) const
{
std::queue<NodePtr> queue;
queue.push(root());
while (!queue.empty())
{
NodePtr node = queue.front();
queue.pop();
visit(node);
for (NodePtr c : node->children()) {
queue.push(c);
}
}
}
template<typename WeightType>
void MorphologicalTree<WeightType>::traverseByLevel(std::function<void(NodePtr)> visit)
{
std::queue<NodePtr> queue;
queue.push(root());
while (!queue.empty())
{
NodePtr node = queue.front();
queue.pop();
visit(node);
for (NodePtr c : node->children()) {
queue.push(c);
}
}
}
template<class WeightType>
typename MorphologicalTree<WeightType>::NodePtr
MorphologicalTree<WeightType>::smallComponent(uint32 idx, const std::vector<bool> &mask)
{
NodePtr node = nodes_[cmap_[idx]];
while (!mask[node->id()] && node->id() != 0)
node = node->parent();
return node;
}
template<class WeightType>
const typename MorphologicalTree<WeightType>::NodePtr
MorphologicalTree<WeightType>::smallComponent(uint32 idx, const std::vector<bool> &mask) const
{
NodePtr node = nodes_[cmap_[idx]];
while (!mask[node->id()] && node->id() != 0)
node = node->parent();
return node;
}
template<class WeightType>
MorphologicalTree<WeightType> MorphologicalTree<WeightType>::copy() const
{
MorphologicalTree ctree{type_};
ctree.nodes_.reserve(numberOfNodes());
ctree.cmap_ = cmap_;
for (NodePtr node : nodes_) {
ctree.nodes_.push_back(node->copy());
}
traverseByLevel([this, &ctree](NodePtr node) {
NodePtr cnode = ctree.nodes_[node->id()];
if (node->parent() != nullptr) {
NodePtr cparent = ctree.nodes_[node->parent()->id()];
cnode->parent(cparent);
cparent->appendChild(cnode);
}
});
ctree.root_ = ctree.nodes_[0];
return ctree;
}
} | 29.532258 | 126 | 0.642879 | dennisjosesilva |
065eb2982dc371822618bbd8de5a17b117a64f64 | 166 | cpp | C++ | C++/drawashape.cpp | nitinkumar30/Programming-Basics | 28b6640055a35fe338741fa772e1d7684976d8f9 | [
"MIT"
] | 68 | 2021-05-03T15:57:35.000Z | 2022-01-17T10:19:26.000Z | C++/drawashape.cpp | nitinkumar30/Programming-Basics | 28b6640055a35fe338741fa772e1d7684976d8f9 | [
"MIT"
] | 262 | 2021-09-26T18:18:55.000Z | 2022-02-18T15:43:38.000Z | C++/drawashape.cpp | nitinkumar30/Programming-Basics | 28b6640055a35fe338741fa772e1d7684976d8f9 | [
"MIT"
] | 168 | 2021-04-24T03:45:58.000Z | 2022-02-18T07:58:24.000Z | #include<iostream>
using namespace std;
int main()
{
cout<<"/___/|"<< endl;
cout<<" / |"<< endl;
cout<<" / |"<< endl;
cout<<" /___|"<< endl;
return 0;
} | 12.769231 | 23 | 0.506024 | nitinkumar30 |
06623c4a5e54afdd80e862ffdc06b39ad69895b3 | 42,167 | cpp | C++ | Source/WebSocketEntities.cpp | braindigitalis/DiscordCoreAPI | 1cc087ea8435051afb8a7ef9bb171665127df419 | [
"Apache-2.0"
] | null | null | null | Source/WebSocketEntities.cpp | braindigitalis/DiscordCoreAPI | 1cc087ea8435051afb8a7ef9bb171665127df419 | [
"Apache-2.0"
] | null | null | null | Source/WebSocketEntities.cpp | braindigitalis/DiscordCoreAPI | 1cc087ea8435051afb8a7ef9bb171665127df419 | [
"Apache-2.0"
] | null | null | null | // WebSocketEntities.cpp - Source file for the webSocket related classes and structs.
// May 13, 2021
// Chris M.
// https://github.com/RealTimeChris
#include "WebSocketEntities.hpp"
#include "JSONIfier.hpp"
#include "EventManager.hpp"
#include "CommandController.hpp"
#include "DiscordCoreClient.hpp"
namespace DiscordCoreInternal {
BaseSocketAgent::BaseSocketAgent(std::string botToken, std::string baseUrl, WebSocketOpCode opCode) {
this->authKey = DiscordCoreAPI::generateX64BaseEncodedKey();
this->state = WebSocketState::Initializing;
this->botToken = botToken;
this->dataOpcode = opCode;
this->baseUrl = baseUrl;
this->doWeReconnect.set();
this->theTask = this->run();
}
BaseSocketAgent::BaseSocketAgent(nullptr_t nullPtr) {};
void BaseSocketAgent::sendMessage(std::string& dataToSend) {
try {
std::lock_guard<std::recursive_mutex> accessLock{ this->accessorMutex01 };
std::cout << "Sending WebSocket Message: " << std::endl << dataToSend;
this->webSocket->writeData(dataToSend);
}
catch (...) {
DiscordCoreAPI::reportException("BaseSocketAgent::sendMessage()");
this->onClosedExternal();
}
}
DiscordCoreAPI::TSUnboundedMessageBlock<WebSocketWorkload>& BaseSocketAgent::getWorkloadTarget() {
return this->webSocketWorkloadTarget;
}
void BaseSocketAgent::sendMessage(nlohmann::json& dataToSend) {
try {
std::lock_guard<std::recursive_mutex> accessLock{ this->accessorMutex01 };
DiscordCoreAPI::StopWatch<std::chrono::milliseconds> stopWatch{ std::chrono::milliseconds{3500} };
while (!this->areWeConnected.load(std::memory_order_consume) && !(dataToSend.contains("op") && (dataToSend.at("op") == 2 || dataToSend.at("op") == 6))) {
if (stopWatch.hasTimePassed()) {
return;
}
}
std::cout << "Sending WebSocket Message: " << dataToSend.dump() << std::endl << std::endl;
std::vector<uint8_t> theVector = this->erlPacker.parseJsonToEtf(dataToSend);
std::string out{};
out.resize(this->maxHeaderSize);
size_t size = this->createHeader(out.data(), theVector.size(), this->dataOpcode);
std::string header(out.data(), size);
std::vector<uint8_t> theVectorNew{};
theVectorNew.insert(theVectorNew.begin(), header.begin(), header.end());
theVectorNew.insert(theVectorNew.begin() + header.size(), theVector.begin(), theVector.end());
this->webSocket->writeData(theVectorNew);
}
catch (...) {
DiscordCoreAPI::reportException("BaseSocketAgent::sendMessage()");
this->onClosedExternal();
}
}
uint64_t BaseSocketAgent::createHeader(char* outBuffer, uint64_t sendlength, WebSocketOpCode opCode) {
try {
size_t position{ 0 };
int32_t indexCount{ 0 };
outBuffer[position++] = this->webSocketFinishBit | static_cast<unsigned char>(opCode);
if (sendlength <= this->webSocketMaxPayloadLengthSmall) {
outBuffer[position++] = static_cast<unsigned char>(sendlength);
}
else if (sendlength <= this->webSocketMaxPayloadLengthLarge) {
outBuffer[position++] = static_cast<unsigned char>(this->webSocketPayloadLengthMagicLarge);
indexCount = 2;
}
else {
outBuffer[position++] = this->webSocketPayloadLengthMagicHuge;
indexCount = 8;
}
for (int32_t x = indexCount - 1; x >= 0; x--) {
outBuffer[position++] = static_cast<unsigned char>(sendlength >> x * 8);
}
outBuffer[1] |= this->webSocketMaskBit;
outBuffer[position++] = 0;
outBuffer[position++] = 0;
outBuffer[position++] = 0;
outBuffer[position++] = 0;
return position;
}
catch (...) {
DiscordCoreAPI::reportException("BaseSocketAgent::createHeader()");
this->onClosedExternal();
return uint64_t{};
}
}
std::vector<std::string> BaseSocketAgent::tokenize(std::string& dataIn, std::string separator) {
try {
std::string::size_type value{ 0 };
std::vector<std::string> dataOut{};
while ((value = dataIn.find_first_not_of(separator, value)) != std::string::npos) {
auto output = dataIn.find(separator, value);
dataOut.push_back(dataIn.substr(value, output - value));
value = output;
}
return dataOut;
}
catch (...) {
DiscordCoreAPI::reportException("BaseSocketAgent::tokenize()");
this->onClosedExternal();
return std::vector<std::string>{};
}
}
void BaseSocketAgent::getVoiceConnectionData(VoiceConnectInitData doWeCollect) {
try {
std::lock_guard<std::recursive_mutex> getVoiceConnectionDataLock{ this->accessorMutex01 };
this->voiceConnectInitData = doWeCollect;
DiscordCoreAPI::UpdateVoiceStateData dataPackage01;
dataPackage01.channelId = "";
dataPackage01.guildId = this->voiceConnectInitData.guildId;
dataPackage01.selfDeaf = false;
dataPackage01.selfMute = false;
nlohmann::json newString01 = JSONIFY(dataPackage01);
this->sendMessage(newString01);
std::this_thread::sleep_for(std::chrono::milliseconds(1500));
DiscordCoreAPI::UpdateVoiceStateData dataPackage;
dataPackage.channelId = doWeCollect.channelId;
dataPackage.guildId = doWeCollect.guildId;
dataPackage.selfDeaf = false;
dataPackage.selfMute = false;
nlohmann::json newString = JSONIFY(dataPackage);
this->areWeCollectingData = true;
this->sendMessage(newString);
}
catch (...) {
DiscordCoreAPI::reportException("BaseSocketAgent::getVoiceConnectionData()");
this->onClosedExternal();
}
}
DiscordCoreAPI::CoRoutine<void> BaseSocketAgent::run() {
try {
co_await DiscordCoreAPI::NewThreadAwaitable<void>();
this->connect();
while (!this->doWeQuit) {
if (this->doWeReconnect.wait(0) == 1) {
this->onClosedInternal();
}
if (this->webSocket != nullptr) {
if (!this->webSocket->processIO()) {
this->onClosedExternal();
}
this->handleBuffer();
}
}
co_return;
}
catch (...) {
DiscordCoreAPI::reportException("BaseSocketAgent::run()");
this->onClosedExternal();
co_return;
}
}
bool BaseSocketAgent::onMessageReceived() {
try {
std::string messageNew = this->webSocket->getData();
nlohmann::json payload{};
try {
payload = this->erlPacker.parseEtfToJson(&messageNew);
}
catch (...) {
return false;
}
if (this->areWeCollectingData && payload.at("t") == "VOICE_SERVER_UPDATE" && !this->serverUpdateCollected) {
if (!this->serverUpdateCollected && !this->stateUpdateCollected) {
this->voiceConnectionData = VoiceConnectionData();
this->voiceConnectionData.endPoint = payload.at("d").at("endpoint").get<std::string>();
this->voiceConnectionData.token = payload.at("d").at("token").get<std::string>();
this->serverUpdateCollected = true;
}
else {
this->voiceConnectionData.endPoint = payload.at("d").at("endpoint").get<std::string>();
this->voiceConnectionData.token = payload.at("d").at("token").get<std::string>();
this->voiceConnectionDataBufferMap.at(payload.at("d").at("guild_id"))->send(this->voiceConnectionData);
this->serverUpdateCollected = false;
this->stateUpdateCollected = false;
this->areWeCollectingData = false;
}
}
if (this->areWeCollectingData && payload.at("t") == "VOICE_STATE_UPDATE" && !this->stateUpdateCollected && payload.at("d").at("member").at("user").at("id") == this->voiceConnectInitData.userId) {
if (!this->stateUpdateCollected && !this->serverUpdateCollected) {
this->voiceConnectionData = VoiceConnectionData();
this->voiceConnectionData.sessionId = payload.at("d").at("session_id").get<std::string>();
this->stateUpdateCollected = true;
}
else {
this->voiceConnectionData.sessionId = payload.at("d").at("session_id").get<std::string>();
this->voiceConnectionDataBufferMap.at(payload.at("d").at("guild_id"))->send(this->voiceConnectionData);
this->serverUpdateCollected = false;
this->stateUpdateCollected = false;
this->areWeCollectingData = false;
}
}
if (payload.at("s") >= 0) {
this->lastNumberReceived = payload.at("s");
}
if (payload.at("t") == "RESUMED") {
this->areWeConnected.store(true, std::memory_order_release);
this->currentReconnectTries = 0;
this->areWeReadyToConnectEvent.set();
}
if (payload.at("t") == "READY") {
this->areWeConnected.store(true, std::memory_order_release);
this->sessionId = payload.at("d").at("session_id");
this->currentReconnectTries = 0;
this->areWeReadyToConnectEvent.set();
this->areWeAuthenticated = true;
}
if (payload.at("op") == 1) {
this->sendHeartBeat();
}
if (payload.at("op") == 7) {
std::cout << "Reconnecting (Type 7)!" << std::endl << std::endl;
this->areWeResuming = true;
this->currentReconnectTries += 1;
this->areWeConnected.store(false, std::memory_order_release);
this->heartbeatTimer.cancel();
this->webSocket.reset(nullptr);
this->connect();
}
if (payload.at("op") == 9) {
std::cout << "Reconnecting (Type 9)!" << std::endl << std::endl;
srand(static_cast<uint32_t>(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count()));
this->areWeConnected.store(false, std::memory_order_release);
this->currentReconnectTries += 1;
int32_t numOfMsToWait = static_cast<int32_t>(1000.0f + ((static_cast<float>(rand()) / static_cast<float>(RAND_MAX)) * static_cast<float>(4000.0f)));
std::this_thread::sleep_for(std::chrono::milliseconds(numOfMsToWait));
if (payload.at("d") == true) {
nlohmann::json identityJson = JSONIFY(this->botToken, this->intentsValue);
this->sendMessage(identityJson);
}
else {
this->heartbeatTimer.cancel();
this->webSocket.reset(nullptr);
this->areWeResuming = false;
this->areWeAuthenticated = false;
this->connect();
}
}
if (payload.at("op") == 10) {
this->heartbeatInterval = payload.at("d").at("heartbeat_interval");
DiscordCoreAPI::TimeElapsedHandler onHeartBeat = [this]() {
BaseSocketAgent::sendHeartBeat();
};
this->heartbeatTimer = DiscordCoreAPI::ThreadPoolTimer::createPeriodicTimer(onHeartBeat, this->heartbeatInterval);
if (!this->areWeAuthenticated) {
nlohmann::json identityJson = JSONIFY(this->botToken, this->intentsValue);
this->sendMessage(identityJson);
}
if (this->areWeResuming) {
std::this_thread::sleep_for(std::chrono::milliseconds{ 500 });
nlohmann::json resumePayload = JSONIFY(this->botToken, this->sessionId, this->lastNumberReceived);
this->sendMessage(resumePayload);
}
}
if (payload.at("op") == 11) {
this->haveWeReceivedHeartbeatAck = true;
}
if (payload.contains("d") && !payload.at("d").is_null() && payload.contains("t") && !payload.at("t").is_null()) {
WebSocketWorkload webSocketWorkload{};
webSocketWorkload.payLoad.update(std::move(payload.at("d")));
if (payload.at("t") == "APPLICATION_COMMAND_CREATE") {
webSocketWorkload.eventType = WebSocketEventType::Application_Command_Create;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "APPLICATION_COMMAND_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::Application_Command_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "APPLICATION_COMMAND_DELETE") {
webSocketWorkload.eventType = WebSocketEventType::Application_Command_Delete;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "CHANNEL_CREATE") {
webSocketWorkload.eventType = WebSocketEventType::Channel_Create;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "CHANNEL_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::Channel_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "CHANNEL_DELETE") {
webSocketWorkload.eventType = WebSocketEventType::Channel_Delete;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "CHANNEL_PINS_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::Channel_Pins_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "THREAD_CREATE") {
webSocketWorkload.eventType = WebSocketEventType::Thread_Create;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "THREAD_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::Thread_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "THREAD_DELETE") {
webSocketWorkload.eventType = WebSocketEventType::Thread_Delete;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "THREAD_LIST_SYNC") {
webSocketWorkload.eventType = WebSocketEventType::Thread_List_Sync;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "THREAD_MEMBER_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::Thread_Member_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "THREAD_MEMBERS_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::Thread_Members_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "GUILD_CREATE") {
webSocketWorkload.eventType = WebSocketEventType::Guild_Create;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
return true;
}
else if (payload.at("t") == "GUILD_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::Guild_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "GUILD_DELETE") {
webSocketWorkload.eventType = WebSocketEventType::Guild_Delete;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "GUILD_BAN_ADD") {
webSocketWorkload.eventType = WebSocketEventType::Guild_Ban_Add;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "GUILD_BAN_REMOVE") {
webSocketWorkload.eventType = WebSocketEventType::Guild_Ban_Remove;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "GUILD_EMOJIS_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::Guild_Emojis_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "GUILD_STICKERS_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::Guild_Stickers_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "GUILD_INTEGRATIONS_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::Guild_Integrations_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "GUILD_MEMBER_ADD") {
webSocketWorkload.eventType = WebSocketEventType::Guild_Member_Add;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "GUILD_MEMBER_REMOVE") {
webSocketWorkload.eventType = WebSocketEventType::Guild_Member_Remove;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "GUILD_MEMBER_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::Guild_Member_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "GUILD_MEMBERS_CHUNK") {
webSocketWorkload.eventType = WebSocketEventType::Guild_Members_Chunk;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "GUILD_ROLE_CREATE") {
webSocketWorkload.eventType = WebSocketEventType::Guild_Role_Create;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "GUILD_ROLE_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::Guild_Role_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "GUILD_ROLE_DELETE") {
webSocketWorkload.eventType = WebSocketEventType::Guild_Role_Delete;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "INTEGRATION_ROLE_CREATE") {
webSocketWorkload.eventType = WebSocketEventType::Integration_Create;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "INTEGRATION_ROLE_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::Integration_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "INTEGRATION_ROLE_DELETE") {
webSocketWorkload.eventType = WebSocketEventType::Integration_Delete;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "INTERACTION_CREATE") {
webSocketWorkload.eventType = WebSocketEventType::Interaction_Create;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "INVITE_CREATE") {
webSocketWorkload.eventType = WebSocketEventType::Invite_Create;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "INVITE_DELETE") {
webSocketWorkload.eventType = WebSocketEventType::Invite_Delete;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "MESSAGE_CREATE") {
webSocketWorkload.eventType = WebSocketEventType::Message_Create;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "MESSAGE_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::Message_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "MESSAGE_DELETE") {
webSocketWorkload.eventType = WebSocketEventType::Message_Delete;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "MESSAGE_DELETE_BULK") {
webSocketWorkload.eventType = WebSocketEventType::Message_Delete_Bulk;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "MESSAGE_REACTION_ADD") {
webSocketWorkload.eventType = WebSocketEventType::Message_Reaction_Add;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "MESSAGE_REACTION_REMOVE") {
webSocketWorkload.eventType = WebSocketEventType::Message_Reaction_Remove;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "MESSAGE_REACTION_REMOVE_ALL") {
webSocketWorkload.eventType = WebSocketEventType::Message_Reaction_Remove_All;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "MESSAGE_REACTION_REMOVE_EMOJI") {
webSocketWorkload.eventType = WebSocketEventType::Message_Reaction_Remove_Emoji;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "PRESENCE_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::Presence_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
return true;
}
else if (payload.at("t") == "STAGE_INSTANCE_CREATE") {
webSocketWorkload.eventType = WebSocketEventType::Stage_Instance_Create;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "STAGE_INSTANCE_DELETE") {
webSocketWorkload.eventType = WebSocketEventType::Stage_Instance_Delete;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "STAGE_INSTANCE_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::Stage_Instance_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "TYPING_START") {
webSocketWorkload.eventType = WebSocketEventType::Typing_Start;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "USER_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::User_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "VOICE_STATE_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::Voice_State_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "VOICE_SERVER_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::Voice_Server_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "WEBHOOKS_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::Webhooks_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
std::cout << "Message received from WebSocket: " << payload.dump() << std::endl << std::endl;
return true;
}
std::cout << "Message received from WebSocket: " << payload.dump() << std::endl << std::endl;
return true;
}
catch (...) {
DiscordCoreAPI::reportException("BaseSocketAgent::onMessageReceived()");
this->onClosedExternal();
return false;
}
}
void BaseSocketAgent::sendHeartBeat() {
try {
std::lock_guard<std::recursive_mutex> accesLock{ this->accessorMutex01 };
if (this->haveWeReceivedHeartbeatAck) {
nlohmann::json heartbeat = JSONIFY(this->lastNumberReceived);
this->sendMessage(heartbeat);
this->haveWeReceivedHeartbeatAck = false;
}
else {
this->onClosedExternal();
}
}
catch (...) {
DiscordCoreAPI::reportException("BaseSocketAgent::sendHeartBeat()");
this->onClosedExternal();
}
}
void BaseSocketAgent::handleBuffer() {
try {
std::string newVector{};
switch (this->state) {
case WebSocketState::Initializing:
newVector.insert(newVector.begin(), this->inputBuffer.begin(), this->inputBuffer.end());
if (newVector.find("\r\n\r\n") != std::string::npos) {
std::string headers = newVector.substr(0, newVector.find("\r\n\r\n"));
newVector.erase(0, newVector.find("\r\n\r\n") + 4);
std::vector<std::string> headerOut = tokenize(headers);
if (headerOut.size()) {
std::string statusLine = headerOut[0];
headerOut.erase(headerOut.begin());
std::vector<std::string> status = tokenize(statusLine, " ");
if (status.size() >= 3 && status[1] == "101") {
this->state = WebSocketState::Connected;
this->inputBuffer.clear();
this->inputBuffer.insert(this->inputBuffer.end(), newVector.begin(), newVector.end());
this->parseHeader();
}
else {
return;
}
}
}
break;
case WebSocketState::Connected:
while (this->parseHeader()) {};
return;
}
}
catch (...) {
DiscordCoreAPI::reportException("BaseSocketAgent::handleBuffer()");
this->onClosedExternal();
}
}
bool BaseSocketAgent::parseHeader() {
try {
std::vector<uint8_t> newVector = this->inputBuffer;
if (this->inputBuffer.size() < 4) {
return false;
}
else {
switch (static_cast<WebSocketOpCode>(this->inputBuffer[0] & ~this->webSocketMaskBit))
{
case WebSocketOpCode::Ws_Op_Continuation:
case WebSocketOpCode::Op_Text:
case WebSocketOpCode::Op_Binary:
case WebSocketOpCode::Op_Ping:
case WebSocketOpCode::Op_Pong:
{
uint8_t length01 = this->inputBuffer[1];
int32_t payloadStartOffset = 2;
if (length01 & this->webSocketMaskBit) {
return false;
}
uint64_t length02 = length01;
if (length01 == this->webSocketPayloadLengthMagicLarge) {
if (this->inputBuffer.size() < 8) {
return false;
}
uint8_t length03 = this->inputBuffer[2];
uint8_t length04 = this->inputBuffer[3];
length02 = static_cast<uint64_t>((length03 << 8) | length04);
payloadStartOffset += 2;
}
else if (length01 == this->webSocketPayloadLengthMagicHuge) {
if (this->inputBuffer.size() < 10) {
return false;
}
length02 = 0;
for (int32_t value = 2, shift = 56; value < 10; ++value, shift -= 8) {
uint8_t length05 = static_cast<uint8_t>(this->inputBuffer[value]);
length02 |= static_cast<uint64_t>(length05) << static_cast<uint64_t>(shift);
}
payloadStartOffset += 8;
}
if (this->inputBuffer.size() < payloadStartOffset + length02) {
return false;
}
else {
std::vector<uint8_t> newerVector{};
newerVector.reserve(length02);
for (uint32_t x = payloadStartOffset; x < payloadStartOffset + length02; x += 1) {
newerVector.push_back(this->inputBuffer[x]);
}
this->inputBuffer = std::move(newerVector);
this->onMessageReceived();
this->inputBuffer.insert(this->inputBuffer.begin(), newVector.begin() + payloadStartOffset + length02, newVector.end());
}
return true;
}
case WebSocketOpCode::Op_Close: {
uint16_t close = this->inputBuffer[2];
close <<= 8;
close |= (this->inputBuffer[3]);
this->closeCode = close;
std::cout << "WebSocket Closed; Code: " << this->closeCode << std::endl;
this->onClosedExternal();
return false;
}
default: {
this->closeCode = 0;
return false;
}
}
}
return false;
}
catch (...) {
DiscordCoreAPI::reportException("BaseSocketAgent::parseHeader()");
this->onClosedExternal();
return false;
}
}
void BaseSocketAgent::onClosedExternal() {
this->doWeReconnect.reset();
}
void BaseSocketAgent::onClosedInternal() {
this->areWeReadyToConnectEvent.reset();
if (this->maxReconnectTries > this->currentReconnectTries) {
this->areWeConnected.store(false, std::memory_order_release);
this->closeCode = 1000;
this->currentReconnectTries += 1;
this->webSocket.reset(nullptr);
this->areWeAuthenticated = false;
this->heartbeatTimer.cancel();
this->inputBuffer.clear();
this->haveWeReceivedHeartbeatAck = true;
this->connect();
}
else if (this->maxReconnectTries <= this->currentReconnectTries) {
this->doWeQuit = true;
}
}
void BaseSocketAgent::connect() {
try {
this->authKey = DiscordCoreAPI::generateX64BaseEncodedKey();
this->webSocket = std::make_unique<WebSocketSSLClient>(this->baseUrl, this->port, &this->inputBuffer);
this->state = WebSocketState::Initializing;
if (this->heartbeatTimer.running()) {
this->heartbeatTimer.cancel();
}
this->doWeReconnect.set();
std::string sendVector = "GET " + this->relativePath + " HTTP/1.1\r\nHost: " + this->baseUrl +
"\r\nPragma: no-cache\r\nUser-Agent: DiscordCoreAPI/1.0\r\nUpgrade: WebSocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: " +
this->authKey + "\r\nSec-WebSocket-Version: 13\r\n\r\n";
this->sendMessage(sendVector);
}
catch (...) {
DiscordCoreAPI::reportException("BaseSocketAgent::connect()");
this->onClosedExternal();
}
}
BaseSocketAgent::~BaseSocketAgent() {
this->doWeQuit = true;
this->theTask.cancel();
this->theTask.get();
this->heartbeatTimer.cancel();
}
VoiceSocketAgent::VoiceSocketAgent(VoiceConnectInitData initDataNew, BaseSocketAgent* baseBaseSocketAgentNew) {
this->authKey = DiscordCoreAPI::generateX64BaseEncodedKey();
this->baseSocketAgent = baseBaseSocketAgentNew;
this->voiceConnectInitData = initDataNew;
this->baseSocketAgent->getVoiceConnectionData(this->voiceConnectInitData);
this->doWeReconnect.set();
this->theTask = this->run();
}
void VoiceSocketAgent::sendVoiceData(std::vector<uint8_t>& responseData) {
try {
if (responseData.size() == 0) {
std::cout << "Please specify voice data to send" << std::endl << std::endl;
return;
}
else {
this->voiceSocket->writeData(responseData);
}
}
catch (...) {
DiscordCoreAPI::reportException("VoiceSocketAgent::sendVoiceData()");
this->onClosedExternal();
}
}
void VoiceSocketAgent::sendMessage(std::vector<uint8_t>& dataToSend) {
try {
std::string newString{};
newString.insert(newString.begin(), dataToSend.begin(), dataToSend.end());
std::cout << "Sending Voice WebSocket Message: " << newString << std::endl << std::endl;
std::vector<char> out{};
out.resize(this->maxHeaderSize);
size_t size = this->createHeader(out.data(), dataToSend.size(), this->dataOpcode);
std::string header(out.data(), size);
std::vector<uint8_t> theVectorNew{};
theVectorNew.insert(theVectorNew.begin(), header.begin(), header.end());
theVectorNew.insert(theVectorNew.begin() + header.size(), dataToSend.begin(), dataToSend.end());
this->webSocket->writeData(theVectorNew);
}
catch (...) {
DiscordCoreAPI::reportException("VoiceSocketAgent::sendMessage()");
this->onClosedExternal();
}
}
void VoiceSocketAgent::sendMessage(std::string& dataToSend) {
try {
std::cout << "Sending Voice WebSocket Message: " << std::endl << dataToSend;
this->webSocket->writeData(dataToSend);
}
catch (...) {
DiscordCoreAPI::reportException("VoiceSocketAgent::sendMessage()");
this->onClosedExternal();
}
}
uint64_t VoiceSocketAgent::createHeader(char* outBuffer, uint64_t sendlength, WebSocketOpCode opCode) {
try {
size_t position = 0;
outBuffer[position++] = this->webSocketFinishBit | static_cast<unsigned char>(opCode);
if (sendlength <= this->webSocketMaxPayloadLengthSmall)
{
outBuffer[position++] = static_cast<unsigned char>(sendlength);
}
else if (sendlength <= this->webSocketMaxPayloadLengthLarge)
{
outBuffer[position++] = static_cast<unsigned char>(this->webSocketPayloadLengthMagicLarge);
outBuffer[position++] = static_cast<unsigned char>(sendlength >> 8);
outBuffer[position++] = static_cast<unsigned char>(sendlength);
}
else
{
outBuffer[position++] = this->webSocketPayloadLengthMagicHuge;
const uint64_t length02 = sendlength;
for (int32_t x = sizeof(uint64_t) - 1; x >= 0; x--) {
outBuffer[position++] = static_cast<unsigned char>(length02 >> x * 8);
}
}
outBuffer[1] |= this->webSocketMaskBit;
outBuffer[position++] = 0;
outBuffer[position++] = 0;
outBuffer[position++] = 0;
outBuffer[position++] = 0;
return position;
}
catch (...) {
DiscordCoreAPI::reportException("VoiceSocketAgent::createHeader()");
this->onClosedExternal();
return size_t{};
}
}
std::vector<std::string> VoiceSocketAgent::tokenize(std::string& dataIn, std::string separator) {
try {
std::string::size_type value{ 0 };
std::vector<std::string> dataOut{};
while ((value = dataIn.find_first_not_of(separator, value)) != std::string::npos) {
auto output = dataIn.find(separator, value);
dataOut.push_back(dataIn.substr(value, output - value));
value = output;
}
return dataOut;
}
catch (...) {
DiscordCoreAPI::reportException("VoiceSocketAgent::tokenize()");
this->onClosedExternal();
return std::vector<std::string>{};
}
}
DiscordCoreAPI::CoRoutine<void> VoiceSocketAgent::run() {
try {
auto cancelHandle = co_await DiscordCoreAPI::NewThreadAwaitable<void>();
this->connect();
while (!this->doWeQuit && !cancelHandle.promise().isItStopped()) {
if (this->doWeReconnect.wait(0) == 1) {
this->onClosedInternal();
co_return;
}
if (this->webSocket != nullptr) {
if (!this->webSocket->processIO()) {
this->onClosedExternal();
}
}
if (this->voiceSocket != nullptr) {
this->voiceSocket->readData(true);
}
this->handleBuffer();
}
co_return;
}
catch (...) {
DiscordCoreAPI::reportException("VoiceSocketAgent::run()");
this->onClosedExternal();
co_return;
}
}
void VoiceSocketAgent::onMessageReceived() {
try {
std::string message = this->webSocket->getData();
nlohmann::json payload = payload.parse(message);
std::cout << "Message received from Voice WebSocket: " << message << std::endl << std::endl;
if (payload.contains("op")) {
if (payload.at("op") == 6) {
this->haveWeReceivedHeartbeatAck = true;
};
if (payload.at("op") == 2) {
this->voiceConnectionData.audioSSRC = payload.at("d").at("ssrc").get<uint32_t>();
this->voiceConnectionData.voiceIp = payload.at("d").at("ip").get<std::string>();
this->voiceConnectionData.voicePort = std::to_string(payload.at("d").at("port").get<int64_t>());
for (auto& value : payload.at("d").at("modes")) {
if (value == "xsalsa20_poly1305") {
this->voiceConnectionData.voiceEncryptionMode = value;
}
}
this->voiceConnect();
this->collectExternalIP();
int32_t counterValue{ 0 };
std::vector<uint8_t> protocolPayloadSelectString = JSONIFY(this->voiceConnectionData.voicePort, this->voiceConnectionData.externalIp, this->voiceConnectionData.voiceEncryptionMode, 0);
if (this->webSocket != nullptr) {
this->sendMessage(protocolPayloadSelectString);
}
}
if (payload.at("op") == 4) {
for (uint32_t x = 0; x < payload.at("d").at("secret_key").size(); x += 1) {
this->voiceConnectionData.secretKey.push_back(payload.at("d").at("secret_key").at(x).get<uint8_t>());
}
}
if (payload.at("op") == 9) {};
if (payload.at("op") == 8) {
if (payload.at("d").contains("heartbeat_interval")) {
this->heartbeatInterval = static_cast<int32_t>(payload.at("d").at("heartbeat_interval").get<float>());
}
DiscordCoreAPI::TimeElapsedHandler onHeartBeat{ [&, this]() ->void {
VoiceSocketAgent::sendHeartBeat();
} };
this->heartbeatTimer = DiscordCoreAPI::ThreadPoolTimer{ DiscordCoreAPI::ThreadPoolTimer::createPeriodicTimer(onHeartBeat, this->heartbeatInterval) };
this->haveWeReceivedHeartbeatAck = true;
std::vector<uint8_t> identifyPayload = JSONIFY(this->voiceConnectionData, this->voiceConnectInitData);
if (this->webSocket != nullptr) {
this->sendMessage(identifyPayload);
}
}
}
}
catch (...) {
DiscordCoreAPI::reportException("VoiceSocketAgent::onMessageReceived()");
this->onClosedExternal();
}
}
void VoiceSocketAgent::collectExternalIP() {
try {
std::vector<uint8_t> packet{};
packet.resize(74);
uint16_t val1601{ 0x01 };
uint16_t val1602{ 70 };
packet[0] = static_cast<uint8_t>(val1601 >> 8);
packet[1] = static_cast<uint8_t>(val1601 >> 0);
packet[2] = static_cast<uint8_t>(val1602 >> 8);
packet[3] = static_cast<uint8_t>(val1602 >> 0);
packet[4] = static_cast<uint8_t>(this->voiceConnectionData.audioSSRC >> 24);
packet[5] = static_cast<uint8_t>(this->voiceConnectionData.audioSSRC >> 16);
packet[6] = static_cast<uint8_t>(this->voiceConnectionData.audioSSRC >> 8);
packet[7] = static_cast<uint8_t>(this->voiceConnectionData.audioSSRC);
this->voiceSocket->writeData(packet);
while (this->inputBuffer01.size() < 74) {
this->voiceSocket->readData(false);
}
std::string message{};
message.insert(message.begin(), this->inputBuffer01.begin() + 8, this->inputBuffer01.begin() + 64);
if (message.find('\u0000') != std::string::npos) {
message = message.substr(0, message.find('\u0000', 5));
}
this->inputBuffer01.clear();
this->voiceConnectionData.externalIp = message;
}
catch (...) {
DiscordCoreAPI::reportException("VoiceSocketAgent::collectExternalIP()");
this->onClosedExternal();
}
}
void VoiceSocketAgent::sendHeartBeat() {
try {
if (this->haveWeReceivedHeartbeatAck) {
std::vector<uint8_t> heartbeatPayload = JSONIFY(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now().time_since_epoch()).count());
if (this->webSocket != nullptr) {
this->sendMessage(heartbeatPayload);
}
this->haveWeReceivedHeartbeatAck = false;
}
else {
this->onClosedExternal();
}
}
catch (...) {
DiscordCoreAPI::reportException("VoiceSocketAgent::sendHeartBeat()");
this->onClosedExternal();
}
}
void VoiceSocketAgent::voiceConnect() {
try {
this->voiceSocket = std::make_unique<DatagramSocketSSLClient>(this->voiceConnectionData.voiceIp, this->voiceConnectionData.voicePort, &this->inputBuffer01);
}
catch (...) {
DiscordCoreAPI::reportException("VoiceSocketAgent::voiceConnect()");
this->onClosedExternal();
}
}
void VoiceSocketAgent::handleBuffer() {
try {
std::string newVector{};
switch (this->state) {
case WebSocketState::Initializing:
newVector.insert(newVector.begin(), this->inputBuffer00.begin(), this->inputBuffer00.end());
if (newVector.find("\r\n\r\n") != std::string::npos) {
std::string headers = newVector.substr(0, newVector.find("\r\n\r\n"));
newVector.erase(0, newVector.find("\r\n\r\n") + 4);
std::vector<std::string> headerOut = tokenize(headers);
if (headerOut.size()) {
std::string statusLine = headerOut[0];
headerOut.erase(headerOut.begin());
std::vector<std::string> status = tokenize(statusLine, " ");
if (status.size() >= 3 && status[1] == "101") {
this->state = WebSocketState::Connected;
this->inputBuffer00.clear();
this->inputBuffer00.insert(this->inputBuffer00.end(), newVector.begin(), newVector.end());
this->parseHeader();
}
else {
return;
}
}
}
break;
case WebSocketState::Connected:
while (this->parseHeader()) {};
return;
}
}
catch (...) {
DiscordCoreAPI::reportException("VoiceSocketAgent::handleBuffer()");
this->onClosedExternal();
}
}
bool VoiceSocketAgent::parseHeader() {
try {
std::vector<uint8_t> newVector = this->inputBuffer00;
if (this->inputBuffer00.size() < 4) {
return false;
}
else {
switch (static_cast<WebSocketOpCode>(this->inputBuffer00[0] & ~this->webSocketMaskBit))
{
case WebSocketOpCode::Ws_Op_Continuation:
case WebSocketOpCode::Op_Text:
case WebSocketOpCode::Op_Binary:
case WebSocketOpCode::Op_Ping:
case WebSocketOpCode::Op_Pong:
{
uint8_t length01 = this->inputBuffer00[1];
int32_t payloadStartOffset = 2;
if (length01 & this->webSocketMaskBit) {
return false;
}
uint64_t length02 = length01;
if (length01 == this->webSocketPayloadLengthMagicLarge) {
if (this->inputBuffer00.size() < 8) {
return false;
}
uint8_t length03 = this->inputBuffer00[2];
uint8_t length04 = this->inputBuffer00[3];
length02 = static_cast<uint64_t>((length03 << 8) | length04);
payloadStartOffset += 2;
}
else if (length01 == this->webSocketPayloadLengthMagicHuge) {
if (this->inputBuffer00.size() < 10) {
return false;
}
length02 = 0;
for (int32_t value = 2, shift = 56; value < 10; ++value, shift -= 8) {
uint8_t length05 = static_cast<uint8_t>(this->inputBuffer00[value]);
length02 |= static_cast<uint64_t>(length05) << static_cast<uint64_t>(shift);
}
payloadStartOffset += 8;
}
if (this->inputBuffer00.size() < payloadStartOffset + length02) {
return false;
}
else {
std::vector<uint8_t> newerVector{};
newerVector.reserve(length02);
for (uint32_t x = payloadStartOffset; x < payloadStartOffset + length02; x += 1) {
newerVector.push_back(this->inputBuffer00[x]);
}
this->inputBuffer00 = std::move(newerVector);
this->onMessageReceived();
this->inputBuffer00.insert(this->inputBuffer00.begin(), newVector.begin() + payloadStartOffset + length02, newVector.end());
}
return true;
}
case WebSocketOpCode::Op_Close: {
uint16_t close = this->inputBuffer00[2];
close <<= 8;
close |= this->inputBuffer00[3];
this->closeCode = close;
std::cout << "Voice WebSocket Closed; Code: " << this->closeCode << std::endl;
this->onClosedExternal();
return false;
}
default: {
this->closeCode = 0;
return false;
}
}
}
return false;
}
catch (...) {
DiscordCoreAPI::reportException("VoiceSocketAgent::parseHeader()");
this->onClosedExternal();
return false;
}
}
void VoiceSocketAgent::onClosedExternal() {
this->doWeReconnect.reset();
}
void VoiceSocketAgent::onClosedInternal() {
this->closeCode = 1000;
this->voiceSocket.reset(nullptr);
this->webSocket.reset(nullptr);
this->heartbeatTimer.cancel();
this->inputBuffer00.clear();
this->inputBuffer01.clear();
}
void VoiceSocketAgent::connect() {
try {
this->authKey = DiscordCoreAPI::generateX64BaseEncodedKey();
DiscordCoreAPI::waitForTimeToPass(*this->baseSocketAgent->voiceConnectionDataBufferMap.at(this->voiceConnectInitData.guildId), this->voiceConnectionData, 20000);
this->baseUrl = this->voiceConnectionData.endPoint.substr(0, this->voiceConnectionData.endPoint.find(":"));
this->relativePath = "/?v=4";
this->heartbeatTimer.cancel();
this->webSocket = std::make_unique<WebSocketSSLClient>(this->baseUrl, "443", &this->inputBuffer00);
this->state = WebSocketState::Initializing;
std::string sendVector = "GET " + this->relativePath + " HTTP/1.1\r\nHost: " + this->baseUrl +
"\r\nPragma: no-cache\r\nUser-Agent: DiscordCoreAPI/1.0\r\nUpgrade: WebSocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: " +
this->authKey + "\r\nSec-WebSocket-Version: 13\r\n\r\n";
this->sendMessage(sendVector);
}
catch (...) {
DiscordCoreAPI::reportException("VoiceSocketAgent::connect()");
this->onClosedExternal();
}
}
VoiceSocketAgent::~VoiceSocketAgent() {
this->doWeQuit = true;
this->theTask.cancel();
this->theTask.get();
this->heartbeatTimer.cancel();
};
} | 38.264065 | 198 | 0.682548 | braindigitalis |
066252162f8ac7b556bc773ad897e96fdb3b70d2 | 813 | cpp | C++ | Algorithms/Sorting/selection_sort.cpp | TeacherManoj0131/HacktoberFest2020-Contributions | c7119202fdf211b8a6fc1eadd0760dbb706a679b | [
"MIT"
] | 256 | 2020-09-30T19:31:34.000Z | 2021-11-20T18:09:15.000Z | Algorithms/Sorting/selection_sort.cpp | TeacherManoj0131/HacktoberFest2020-Contributions | c7119202fdf211b8a6fc1eadd0760dbb706a679b | [
"MIT"
] | 293 | 2020-09-30T19:14:54.000Z | 2021-06-06T02:34:47.000Z | Algorithms/Sorting/selection_sort.cpp | TeacherManoj0131/HacktoberFest2020-Contributions | c7119202fdf211b8a6fc1eadd0760dbb706a679b | [
"MIT"
] | 1,620 | 2020-09-30T18:37:44.000Z | 2022-03-03T20:54:22.000Z | #include <bits/stdc++.h>
using namespace std;
void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
void selectionSort(int arr[], int n)
{
int i, j, min;
for (i = 0; i < n-1; i++)
{
min = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min])
min = j;
swap(&arr[min], &arr[i]);
}
}
void printArray(int arr[], int n)
{
for (int i=0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}
int main()
{
int n;
cout<<"enter the size of array : ";
cin>>n;
int arr[n];
for (int i = 0; i < n; i++){
cin>>arr[i];
}
selectionSort(arr, n);
cout << "Sorted array: \n";
printArray(arr, n);
return 0;
} | 17.673913 | 39 | 0.392374 | TeacherManoj0131 |
066469719d36c5564bf1b88e3a934da65e4363d3 | 13,371 | cpp | C++ | eval.cpp | maxime-tournier/slip | a3765b27280cb29880e448310fbcb2c9a40a88cd | [
"MIT"
] | 1 | 2017-03-19T21:43:42.000Z | 2017-03-19T21:43:42.000Z | eval.cpp | maxime-tournier/slip | a3765b27280cb29880e448310fbcb2c9a40a88cd | [
"MIT"
] | null | null | null | eval.cpp | maxime-tournier/slip | a3765b27280cb29880e448310fbcb2c9a40a88cd | [
"MIT"
] | null | null | null | #include "eval.hpp"
#include <vector>
#include "sexpr.hpp"
#include "package.hpp"
#include "gc.hpp"
#include "stack.hpp"
// #include "repr.hpp"
namespace eval {
////////////////////////////////////////////////////////////////////////////////
const symbol cons = "cons";
const symbol nil = "nil";
const symbol head = "head";
const symbol tail = "tail";
template<class T>
static value eval(state::ref env, const T& ) {
static_assert(sizeof(T) == 0, "eval implemented");
}
closure::closure(std::size_t argc, func_type func)
: func(func),
argc(argc) {
}
sum::sum(const value& data, symbol tag)
: value(data), tag(tag) { }
lambda::lambda(state::ref env, std::size_t argc, func_type func)
: closure(argc, func),
env(env) { }
state::state(ref parent): parent(parent) { }
state::ref scope(state::ref self) {
assert(self);
return gc::make_ref<state>(self);
}
state& state::def(symbol name, const value& self) {
auto err = locals.emplace(name, self); (void) err;
assert(err.second && "redefined variable");
return *this;
}
template<class NameIterator, class ValueIterator>
static state::ref augment(state::ref self,
NameIterator name_first, NameIterator name_last,
ValueIterator value_first, ValueIterator value_last) {
auto res = scope(self);
ValueIterator value = value_first;
for(NameIterator name = name_first; name != name_last; ++name) {
assert(value != value_last && "not enough values");
res->locals.emplace(*name, *value++);
}
assert(value == value_last && "too many values");
return res;
}
// apply a lambda to argument range
value apply(const value& self, const value* first, const value* last) {
const std::size_t argc = last - first;
const closure* ptr;
const std::size_t expected = self.match([&](const value& ) -> std::size_t {
throw std::runtime_error("type error in application");
},
[&](const closure& self) {
ptr = &self;
return self.argc;
});
if(argc < expected) {
// unsaturated call: build wrapper
const std::size_t remaining = expected - argc;
const std::vector<value> saved(first, last);
return closure(remaining, [self, saved, remaining](const value* args) {
std::vector<value> tmp = saved;
for(auto it = args, last = args + remaining; it != last; ++it) {
tmp.emplace_back(*it);
}
return apply(self, tmp.data(), tmp.data() + tmp.size());
});
}
if(argc > expected) {
// over-saturated call: call result with remaining args
const value* mid = first + expected;
assert(mid > first);
assert(mid < last);
const value func = apply(self, first, mid);
return apply(func, mid, last);
}
// saturated calls
return ptr->func(first);
}
template<class T>
static value eval(state::ref, const ast::lit<T>& self) {
return self.value;
}
static value eval(state::ref, const ast::lit<string>& self) {
return make_ref<string>(self.value);
}
static value eval(state::ref e, const ast::var& self) {
auto res = e->find(self.name); assert(res);
return *res;
}
using stack_type = stack<value>;
static stack_type stack{1000};
static value eval(state::ref e, const ast::app& self) {
// note: evaluate func first
const value func = eval(e, *self.func);
// TODO use allocator
using allocator_type = stack_allocator<value>;
std::vector<value, allocator_type> args{allocator_type{stack}};
args.reserve(self.argc);
for(const auto& arg : self.args) {
args.emplace_back(eval(e, arg));
};
return apply(func, args.data(), args.data() + args.size());
}
static value eval(state::ref e, const ast::abs& self) {
std::vector<symbol> names;
for(const auto& arg : self.args) {
names.emplace_back(arg.name());
}
const ast::expr body = *self.body;
return lambda(e, names.size(), [=](const value* args) {
auto sub = augment(e, names.begin(), names.end(),
args, args + names.size());
return eval(sub, body);
});
}
static value eval(state::ref e, const ast::bind& self) {
auto it = e->locals.emplace(self.id.name, eval(e, self.value)); (void) it;
assert(it.second && "redefined variable");
return unit();
}
static value eval(state::ref e, const ast::io& self) {
return self.match([&](const ast::expr& self) {
return eval(e, self);
},
[&](const ast::bind& self) {
return eval(e, self);
});
}
static value eval(state::ref e, const ast::seq& self) {
auto sub = scope(e);
const value init = unit();
foldl(init, self.items, [&](const value&, const ast::io& self) {
return eval(sub, self);
});
// return
return eval(sub, *self.last);
}
static value eval(state::ref e, const ast::run& self) {
return eval(e, *self.value);
}
static value eval(state::ref e, const ast::module& self) {
// just define the reified module type constructor
enum module::type type;
switch(self.type) {
case ast::module::product: type = module::product; break;
case ast::module::coproduct: type = module::coproduct; break;
}
return module{type};
}
static value eval(state::ref e, const ast::def& self) {
auto it = e->locals.emplace(self.id.name, eval(e, *self.value)); (void) it;
assert(it.second && "redefined variable");
return unit();
}
static value eval(state::ref e, const ast::let& self) {
auto sub = scope(e);
for(const ast::bind& def : self.defs) {
sub->locals.emplace(def.id.name, eval(sub, def.value));
}
return eval(sub, *self.body);
}
static value eval(state::ref e, const ast::cond& self) {
const value test = eval(e, *self.test);
assert(test.get<boolean>() && "type error");
if(test.cast<boolean>()) return eval(e, *self.conseq);
else return eval(e, *self.alt);
}
static value eval(state::ref e, const ast::record& self) {
auto res = make_ref<record>();
for(const auto& attr : self.attrs) {
res->emplace(attr.id.name, eval(e, attr.value));
}
return res;
}
static value eval(state::ref e, const ast::sel& self) {
const symbol name = self.id.name;
return closure(1, [name](const value* args) -> value {
return args[0].match([&](const value::list& self) -> value {
// note: the only possible way to call this is during a pattern
// match processing a non-empty list
assert(self && "type error");
if(name == head) return self->head;
if(name == tail) return self->tail;
assert(false && "type error");
},
[&](const ref<record>& self) {
const auto it = self->find(name); (void) it;
assert(it != self->end() && "attribute error");
return it->second;
},
[&](const value& self) -> value {
assert(false && "type error");
});
});
}
static value eval(state::ref e, const ast::inj& self) {
const symbol tag = self.id.name;
return closure(1, [tag](const value* args) -> value {
return make_ref<sum>(args[0], tag);
});
}
static value eval(state::ref e, const ast::make& self) {
switch(eval(e, *self.type).cast<module>().type) {
case module::product:
return eval(e, ast::record{self.attrs});
case module::coproduct: {
assert(size(self.attrs) == 1);
const auto& attr = self.attrs->head;
return make_ref<sum>(eval(e, attr.value), attr.id.name);
}
case module::list:
assert(size(self.attrs) == 1);
return eval(e, self.attrs->head.value);
};
}
static value eval(state::ref e, const ast::use& self) {
const value env = eval(e, *self.env);
assert(env.get<ref<record>>() && "type error");
// auto s = scope(e);
for(const auto& it : *env.cast<ref<record>>()) {
e->def(it.first, it.second);
}
// return eval(s, *self.body);
return unit();
}
static value eval(state::ref e, const ast::import& self) {
const auto pkg = package::import<state::ref>(self.package, [&] {
auto es = gc::make_ref<state>();
package::iter(self.package, [&](ast::expr self) {
eval(es, self);
});
return es;
});
e->def(self.package, make_ref<record>(pkg->locals));
return unit();
}
static value eval(state::ref e, const ast::match& self) {
std::map<symbol, std::pair<symbol, ast::expr>> dispatch;
for(const auto& handler : self.cases) {
auto err = dispatch.emplace(handler.id.name,
std::make_pair(handler.arg.name(),
handler.value));
(void) err; assert(err.second);
}
const ref<ast::expr> fallback = self.fallback;
return closure(1, [e, dispatch, fallback](const value* args) {
// matching on a list
return args[0].match([&](const value::list& self) {
auto it = dispatch.find(self ? cons : nil);
if(it != dispatch.end()) {
auto sub = scope(e);
sub->def(it->second.first, self);
return eval(sub, it->second.second);
} else {
assert(fallback);
return eval(e, *fallback);
}
},
[&](const ref<sum>& self) {
auto it = dispatch.find(self->tag);
if(it != dispatch.end()) {
auto sub = scope(e);
sub->def(it->second.first, *self);
return eval(sub, it->second.second);
} else {
assert(fallback);
return eval(e, *fallback);
}
},
[&](const value& self) -> value {
std::stringstream ss;
ss << "attempting to match on value " << self;
throw std::runtime_error(ss.str());
});
});
}
namespace {
struct eval_visitor {
template<class T>
value operator()(const T& self, state::ref e) const {
return eval(e, self);
}
};
}
static void debug(state::ref e) {
for(auto& it : e->locals) {
std::clog << it.first << ": " << it.second << std::endl;
}
}
value eval(state::ref e, const ast::expr& self) {
// std::clog << repr(self) << std::endl;
return self.visit(eval_visitor(), e);
}
namespace {
struct ostream_visitor {
void operator()(const ref<value>& self, std::ostream& out) const {
out << "#mut<" << *self << ">";
}
void operator()(const module& self, std::ostream& out) const {
out << "#<module>";
}
void operator()(const ref<string>& self, std::ostream& out) const {
out << '"' << *self << '"';
}
void operator()(const symbol& self, std::ostream& out) const {
out << self;
}
void operator()(const value::list& self, std::ostream& out) const {
out << self;
}
void operator()(const lambda& self, std::ostream& out) const {
out << "#<lambda>";
}
void operator()(const closure& self, std::ostream& out) const {
out << "#<closure>";
}
void operator()(const unit& self, std::ostream& out) const {
out << "()";
}
void operator()(const boolean& self, std::ostream& out) const {
out << (self ? "true" : "false");
}
void operator()(const integer& self, std::ostream& out) const {
out << self; // << "i";
}
void operator()(const real& self, std::ostream& out) const {
out << self; // << "d";
}
void operator()(const ref<record>& self, std::ostream& out) const {
out << "{";
bool first = true;
for(const auto& it : *self) {
if(first) first = false;
else out << "; ";
out << it.first << ": " << it.second;
}
out << "}";
}
void operator()(const ref<sum>& self, std::ostream& out) const {
out << "<" << self->tag << ": " << *self << ">";
}
};
}
std::ostream& operator<<(std::ostream& out, const value& self) {
self.visit(ostream_visitor(), out);
return out;
}
static void mark(const value& self, bool debug) {
self.match([&](const value& ) { },
[&](const ref<record>& self) {
for(const auto& it : *self) {
mark(it.second, debug);
}
},
[&](const ref<sum>& self) {
mark(*self, debug);
},
[&](const lambda& self) {
mark(self.env, debug);
});
}
void mark(state::ref e, bool debug) {
if(debug) std::clog << "marking:\t" << e.get() << std::endl;
if(e.marked()) return;
e.mark();
for(auto& it : e->locals) {
mark(it.second, debug);
}
if(e->parent) {
mark(e->parent, debug);
}
}
value* state::find(symbol name) {
auto it = locals.find(name);
if(it != locals.end()) return &it->second;
if(parent) return parent->find(name);
return nullptr;
}
}
| 25.468571 | 82 | 0.544238 | maxime-tournier |
06657b9629f5f8883f5c19899ccaa69c6e22bbe5 | 289 | cpp | C++ | src/liquid/string_std.cpp | kainjow/Jeqyll | 3a234a345087c5d3366b1eda98d3ed92d3888101 | [
"MIT"
] | 4 | 2018-02-01T04:46:37.000Z | 2021-01-13T18:20:38.000Z | src/liquid/string_std.cpp | kainjow/Jeqyll | 3a234a345087c5d3366b1eda98d3ed92d3888101 | [
"MIT"
] | null | null | null | src/liquid/string_std.cpp | kainjow/Jeqyll | 3a234a345087c5d3366b1eda98d3ed92d3888101 | [
"MIT"
] | 3 | 2017-03-27T19:12:56.000Z | 2021-03-23T04:24:51.000Z | #include "string.hpp"
Liquid::StringRef Liquid::String::midRef(size_type pos, size_type num) const
{
if (pos > size()) {
return {};
}
const size_type len = num == static_cast<size_type>(-1) || size() < num ? size() - pos : num;
return StringRef(this, pos, len);
}
| 26.272727 | 97 | 0.608997 | kainjow |
06666820f2556feae941ec03439afd62c07f5374 | 4,464 | cpp | C++ | OpenCTD_Particle_Boron/OpenCTD_SDCard/OpenCTD_SDCard/src/OpenCTD_SDCard.cpp | sio-testtank-makerspace/OpenCTD | 0595126c56dbd7e131d17491b5679a944ab44660 | [
"MIT"
] | 2 | 2019-05-30T23:44:24.000Z | 2019-09-04T00:50:38.000Z | OpenCTD_Particle_Boron/OpenCTD_SDCard/OpenCTD_SDCard/src/OpenCTD_SDCard.cpp | sio-testtank-makerspace/OpenCTD | 0595126c56dbd7e131d17491b5679a944ab44660 | [
"MIT"
] | null | null | null | OpenCTD_Particle_Boron/OpenCTD_SDCard/OpenCTD_SDCard/src/OpenCTD_SDCard.cpp | sio-testtank-makerspace/OpenCTD | 0595126c56dbd7e131d17491b5679a944ab44660 | [
"MIT"
] | null | null | null | #include "application.h"
#line 1 "/Users/pjb/Dropbox/Particle_Projects/OPO_OpenCTDTest/OpenCTD_SDCard/OpenCTD_SDCard/src/OpenCTD_SDCard.ino"
/*
* Simple data logger.
*/
#include <SPI.h>
#include "SdFat.h"
// SD chip select pin. Be sure to disable any other SPI devices such as Enet.
void writeHeader();
void logData();
void setup();
void loop();
#line 8 "/Users/pjb/Dropbox/Particle_Projects/OPO_OpenCTDTest/OpenCTD_SDCard/OpenCTD_SDCard/src/OpenCTD_SDCard.ino"
const uint8_t chipSelect = SS;
// Interval between data records in milliseconds.
// The interval must be greater than the maximum SD write latency plus the
// time to acquire and write data to the SD to avoid overrun errors.
// Run the bench example to check the quality of your SD card.
const uint32_t SAMPLE_INTERVAL_MS = 1000;
// Log file base name. Must be six characters or less.
#define FILE_BASE_NAME "Data"
//------------------------------------------------------------------------------
// File system object.
SdFat sd;
// Log file.
SdFile file;
// Time in micros for next data record.
uint32_t logTime;
//==============================================================================
// User functions. Edit writeHeader() and logData() for your requirements.
const uint8_t ANALOG_COUNT = 4;
//------------------------------------------------------------------------------
// Write data header.
void writeHeader() {
file.print(F("micros"));
for (uint8_t i = 0; i < ANALOG_COUNT; i++) {
file.print(F(",adc"));
file.print(i, DEC);
}
file.println();
}
//------------------------------------------------------------------------------
// Log a data record.
void logData() {
uint16_t data[ANALOG_COUNT];
// Read all channels to avoid SD write latency between readings.
for (uint8_t i = 0; i < ANALOG_COUNT; i++) {
data[i] = analogRead(i);
}
// Write data to file. Start with log time in micros.
file.print(logTime);
// Write ADC data to CSV record.
for (uint8_t i = 0; i < ANALOG_COUNT; i++) {
file.write(',');
file.print(data[i]);
}
file.println();
}
//==============================================================================
// Error messages stored in flash.
#define error(msg) sd.errorHalt(F(msg))
//------------------------------------------------------------------------------
SYSTEM_MODE(MANUAL);
void setup() {
Cellular.off();
const uint8_t BASE_NAME_SIZE = sizeof(FILE_BASE_NAME) - 1;
char fileName[13] = FILE_BASE_NAME "00.csv";
Serial.begin(9600);
// Wait for USB Serial
while (!Serial) {
SysCall::yield();
}
delay(1000);
Serial.println(F("Type any character to start"));
while (!Serial.available()) {
SysCall::yield();
}
// Initialize at the highest speed supported by the board that is
// not over 50 MHz. Try a lower speed if SPI errors occur.
if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) {
sd.initErrorHalt();
}
// Find an unused file name.
if (BASE_NAME_SIZE > 6) {
error("FILE_BASE_NAME too long");
}
while (sd.exists(fileName)) {
if (fileName[BASE_NAME_SIZE + 1] != '9') {
fileName[BASE_NAME_SIZE + 1]++;
} else if (fileName[BASE_NAME_SIZE] != '9') {
fileName[BASE_NAME_SIZE + 1] = '0';
fileName[BASE_NAME_SIZE]++;
} else {
error("Can't create file name");
}
}
if (!file.open(fileName, O_WRONLY | O_CREAT | O_EXCL)) {
error("file.open");
}
// Read any Serial data.
do {
delay(10);
} while (Serial.available() && Serial.read() >= 0);
Serial.print(F("Logging to: "));
Serial.println(fileName);
Serial.println(F("Type any character to stop"));
// Write data header.
writeHeader();
// Start on a multiple of the sample interval.
logTime = micros()/(1000UL*SAMPLE_INTERVAL_MS) + 1;
logTime *= 1000UL*SAMPLE_INTERVAL_MS;
}
//------------------------------------------------------------------------------
void loop() {
// Time for next record.
logTime += 1000UL*SAMPLE_INTERVAL_MS;
// Wait for log time.
int32_t diff;
do {
diff = micros() - logTime;
} while (diff < 0);
// Check for data rate too high.
if (diff > 10) {
error("Missed data record");
}
logData();
// Force data to SD and update the directory entry to avoid data loss.
if (!file.sync() || file.getWriteError()) {
error("write error");
}
if (Serial.available()) {
// Close file and stop.
file.close();
Serial.println(F("Done"));
SysCall::halt();
}
} | 27.9 | 115 | 0.575269 | sio-testtank-makerspace |
06674986cea465217ce96ee6d076534d4e889b67 | 5,916 | cpp | C++ | pi4home-core/src/pi4home/output/pca9685_output_component.cpp | khzd/pi4home | 937bcdcf77bab111cca10af1fe45c63a55c29aae | [
"MIT"
] | 1 | 2019-05-16T02:52:12.000Z | 2019-05-16T02:52:12.000Z | pi4home-core/src/pi4home/output/pca9685_output_component.cpp | khzd/pi4home | 937bcdcf77bab111cca10af1fe45c63a55c29aae | [
"MIT"
] | null | null | null | pi4home-core/src/pi4home/output/pca9685_output_component.cpp | khzd/pi4home | 937bcdcf77bab111cca10af1fe45c63a55c29aae | [
"MIT"
] | null | null | null | // Based on:
// - https://github.com/NachtRaveVL/PCA9685-Arduino
// - https://cdn-shop.adafruit.com/datasheets/PCA9685.pdf
#include "pi4home/defines.h"
#ifdef USE_PCA9685_OUTPUT
#include "pi4home/output/pca9685_output_component.h"
#include "pi4home/log.h"
PI4HOME_NAMESPACE_BEGIN
namespace output {
static const char *TAG = "output.pca9685";
const uint8_t PCA9685_MODE_INVERTED = 0x10;
const uint8_t PCA9685_MODE_OUTPUT_ONACK = 0x08;
const uint8_t PCA9685_MODE_OUTPUT_TOTEM_POLE = 0x04;
const uint8_t PCA9685_MODE_OUTNE_HIGHZ = 0x02;
const uint8_t PCA9685_MODE_OUTNE_LOW = 0x01;
static const uint8_t PCA9685_REGISTER_SOFTWARE_RESET = 0x06;
static const uint8_t PCA9685_REGISTER_MODE1 = 0x00;
static const uint8_t PCA9685_REGISTER_MODE2 = 0x01;
static const uint8_t PCA9685_REGISTER_LED0 = 0x06;
static const uint8_t PCA9685_REGISTER_PRE_SCALE = 0xFE;
static const uint8_t PCA9685_MODE1_RESTART = 0b10000000;
static const uint8_t PCA9685_MODE1_AUTOINC = 0b00100000;
static const uint8_t PCA9685_MODE1_SLEEP = 0b00010000;
static const uint16_t PCA9685_PWM_FULL = 4096;
static const uint8_t PCA9685_ADDRESS = 0x40;
PCA9685OutputComponent::PCA9685OutputComponent(I2CComponent *parent, float frequency, uint8_t mode)
: I2CDevice(parent, PCA9685_ADDRESS),
frequency_(frequency),
mode_(mode),
min_channel_(0xFF),
max_channel_(0x00),
update_(true) {
for (uint16_t &pwm_amount : this->pwm_amounts_)
pwm_amount = 0;
}
void PCA9685OutputComponent::setup() {
ESP_LOGCONFIG(TAG, "Setting up PCA9685OutputComponent...");
ESP_LOGV(TAG, " Resetting devices...");
if (!this->write_bytes(PCA9685_REGISTER_SOFTWARE_RESET, nullptr, 0)) {
this->mark_failed();
return;
}
if (!this->write_byte(PCA9685_REGISTER_MODE1, PCA9685_MODE1_RESTART | PCA9685_MODE1_AUTOINC)) {
this->mark_failed();
return;
}
if (!this->write_byte(PCA9685_REGISTER_MODE2, this->mode_)) {
this->mark_failed();
return;
}
int pre_scaler = static_cast<int>((25000000 / (4096 * this->frequency_)) - 1);
if (pre_scaler > 255)
pre_scaler = 255;
if (pre_scaler < 3)
pre_scaler = 3;
ESP_LOGV(TAG, " -> Prescaler: %d", pre_scaler);
uint8_t mode1;
if (!this->read_byte(PCA9685_REGISTER_MODE1, &mode1)) {
this->mark_failed();
return;
}
mode1 = (mode1 & ~PCA9685_MODE1_RESTART) | PCA9685_MODE1_SLEEP;
if (!this->write_byte(PCA9685_REGISTER_MODE1, mode1)) {
this->mark_failed();
return;
}
if (!this->write_byte(PCA9685_REGISTER_PRE_SCALE, pre_scaler)) {
this->mark_failed();
return;
}
mode1 = (mode1 & ~PCA9685_MODE1_SLEEP) | PCA9685_MODE1_RESTART;
if (!this->write_byte(PCA9685_REGISTER_MODE1, mode1)) {
this->mark_failed();
return;
}
delayMicroseconds(500);
this->loop();
}
void PCA9685OutputComponent::dump_config() {
ESP_LOGCONFIG(TAG, "PCA9685:");
ESP_LOGCONFIG(TAG, " Mode: 0x%02X", this->mode_);
ESP_LOGCONFIG(TAG, " Frequency: %.0f Hz", this->frequency_);
if (this->is_failed()) {
ESP_LOGE(TAG, "Setting up PCA9685 failed!");
}
}
void PCA9685OutputComponent::loop() {
if (this->min_channel_ == 0xFF || !this->update_)
return;
const uint16_t num_channels = this->max_channel_ - this->min_channel_ + 1;
for (uint8_t channel = this->min_channel_; channel <= this->max_channel_; channel++) {
uint16_t phase_begin = uint16_t(channel - this->min_channel_) / num_channels * 4096;
uint16_t phase_end;
uint16_t amount = this->pwm_amounts_[channel];
if (amount == 0) {
phase_end = 4096;
} else if (amount >= 4096) {
phase_begin = 4096;
phase_end = 0;
} else {
phase_end = phase_begin + amount;
if (phase_end >= 4096)
phase_end -= 4096;
}
ESP_LOGVV(TAG, "Channel %02u: amount=%04u phase_begin=%04u phase_end=%04u", channel, amount, phase_begin,
phase_end);
uint8_t data[4];
data[0] = phase_begin & 0xFF;
data[1] = (phase_begin >> 8) & 0xFF;
data[2] = phase_end & 0xFF;
data[3] = (phase_end >> 8) & 0xFF;
uint8_t reg = PCA9685_REGISTER_LED0 + 4 * channel;
if (!this->write_bytes(reg, data, 4)) {
this->status_set_warning();
return;
}
}
this->status_clear_warning();
this->update_ = false;
}
float PCA9685OutputComponent::get_setup_priority() const { return setup_priority::HARDWARE; }
void PCA9685OutputComponent::set_channel_value_(uint8_t channel, uint16_t value) {
if (this->pwm_amounts_[channel] != value)
this->update_ = true;
this->pwm_amounts_[channel] = value;
}
PCA9685OutputComponent::Channel *PCA9685OutputComponent::create_channel(uint8_t channel,
PowerSupplyComponent *power_supply,
float max_power) {
this->min_channel_ = std::min(this->min_channel_, channel);
this->max_channel_ = std::max(this->max_channel_, channel);
auto *c = new Channel(this, channel);
c->set_power_supply(power_supply);
c->set_max_power(max_power);
return c;
}
float PCA9685OutputComponent::get_frequency() const { return this->frequency_; }
void PCA9685OutputComponent::set_frequency(float frequency) { this->frequency_ = frequency; }
uint8_t PCA9685OutputComponent::get_mode() const { return this->mode_; }
void PCA9685OutputComponent::set_mode(uint8_t mode) { this->mode_ = mode; }
PCA9685OutputComponent::Channel::Channel(PCA9685OutputComponent *parent, uint8_t channel)
: FloatOutput(), parent_(parent), channel_(channel) {}
void PCA9685OutputComponent::Channel::write_state(float state) {
const uint16_t max_duty = 4096;
const float duty_rounded = roundf(state * max_duty);
auto duty = static_cast<uint16_t>(duty_rounded);
this->parent_->set_channel_value_(this->channel_, duty);
}
} // namespace output
PI4HOME_NAMESPACE_END
#endif // USE_PCA9685_OUTPUT
| 31.301587 | 109 | 0.698952 | khzd |
06691fe7604608f281cdf1b73c26e841e47ba944 | 4,319 | cc | C++ | physics/hadron/models/src/HadronicFinalStateModelStore.cc | Geant-RnD/geant | ffff95e23547531f3254ada2857c062a31f33e8f | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2016-10-16T14:37:42.000Z | 2018-04-05T15:49:09.000Z | physics/hadron/models/src/HadronicFinalStateModelStore.cc | Geant-RnD/geant | ffff95e23547531f3254ada2857c062a31f33e8f | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | physics/hadron/models/src/HadronicFinalStateModelStore.cc | Geant-RnD/geant | ffff95e23547531f3254ada2857c062a31f33e8f | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | #include "Geant/HadronicFinalStateModelStore.h"
#include "Geant/HadronicFinalStateModel.h"
#include "Geant/Isotope.h"
using namespace geantphysics;
//------------------------------------------------
// HadronicFinalStateModelStore non-inline methods
//------------------------------------------------
HadronicFinalStateModelStore::HadronicFinalStateModelStore() : fName("")
{
}
HadronicFinalStateModelStore::HadronicFinalStateModelStore(const std::string name) : fName(name)
{
}
HadronicFinalStateModelStore::HadronicFinalStateModelStore(const HadronicFinalStateModelStore &other)
: fName(other.fName)
{
for (size_t i = 0; i < other.fHadFsVec.size(); i++) {
fHadFsVec.push_back(other.fHadFsVec[i]);
}
}
HadronicFinalStateModelStore &HadronicFinalStateModelStore::operator=(const HadronicFinalStateModelStore &other)
{
if (this != &other) {
fHadFsVec.clear();
for (size_t i = 0; i < other.fHadFsVec.size(); i++) {
fHadFsVec.push_back(other.fHadFsVec[i]);
}
fName = other.fName;
}
return *this;
}
HadronicFinalStateModelStore::~HadronicFinalStateModelStore()
{
// We are assuming here that this class is the owner of the hadronic final-state models, therefore it is in charge
// of deleting them at the end.
for (size_t i = 0; i < fHadFsVec.size(); i++) {
delete fHadFsVec[i];
}
fHadFsVec.clear();
}
void HadronicFinalStateModelStore::Initialize(/* Not yet defined */)
{
}
void HadronicFinalStateModelStore::RegisterHadronicFinalStateModel(HadronicFinalStateModel *ptrhadfs)
{
if (ptrhadfs) {
fHadFsVec.push_back(ptrhadfs);
}
}
int HadronicFinalStateModelStore::GetIndexChosenFinalStateModel(const int projectilecode,
const double projectilekineticenergy,
const Isotope *targetisotope) const
{
int index = -1;
std::vector<int> indexApplicableModelVec;
for (size_t i = 0; i < fHadFsVec.size(); i++) {
if (fHadFsVec[i] && fHadFsVec[i]->IsApplicable(projectilecode, projectilekineticenergy, targetisotope)) {
indexApplicableModelVec.push_back(i);
}
}
if (indexApplicableModelVec.size() == 1) {
index = indexApplicableModelVec[0];
} else if (indexApplicableModelVec.size() == 2) {
// The "first" index corresponds to the model with the lowest minimal energy
int first = indexApplicableModelVec[0];
int second = indexApplicableModelVec[1];
if (fHadFsVec[first]->GetLowEnergyUsageLimit() > fHadFsVec[second]->GetLowEnergyUsageLimit()) {
first = second;
second = indexApplicableModelVec[0];
}
if (fHadFsVec[first]->GetHighEnergyUsageLimit() >= fHadFsVec[second]->GetHighEnergyUsageLimit()) {
std::cerr << "HadronicFinalStateModelStore::GetIndexChosenFinalState : projectilecode=" << projectilecode
<< " ; projectilekineticenergy=" << projectilekineticenergy
<< " GeV; targetisotope: Z=" << targetisotope->GetZ() << " N=" << targetisotope->GetN() << std::endl
<< "\t NOT allowed full overlapping between two models: " << fHadFsVec[first]->GetName() << " , "
<< fHadFsVec[second]->GetName() << std::endl;
} else { // All if fine: first model applicable to lower energies than the second model
// Select one of the two models with probability depending linearly on the projectilekineticenergy
double probFirst = (fHadFsVec[first]->GetHighEnergyUsageLimit() - projectilekineticenergy) /
(fHadFsVec[first]->GetHighEnergyUsageLimit() - fHadFsVec[second]->GetLowEnergyUsageLimit());
double randomNumber = 0.5; //***LOOKHERE*** TO-BE-REPLACED with a call to a random number generator.
if (randomNumber < probFirst) {
index = first;
} else {
index = second;
}
}
} else {
std::cerr << "HadronicFinalStateModelStore::GetIndexChosenFinalState : projectilecode=" << projectilecode
<< " ; projectilekineticenergy=" << projectilekineticenergy
<< " GeV; targetisotope: Z=" << targetisotope->GetZ() << " N=" << targetisotope->GetN() << std::endl
<< "\t wrong number of applicable final-state models: " << indexApplicableModelVec.size() << std::endl;
}
return index;
}
| 39.990741 | 117 | 0.656865 | Geant-RnD |
06696f0f06efe1d4c70f313abf88e6b996dec1cb | 954 | cpp | C++ | AYK/src/AYK/Renderer/OrthographicCamera.cpp | AreYouReal/AYK | c6859047cfed674291692cc31095d8bb61b27a35 | [
"Apache-2.0"
] | null | null | null | AYK/src/AYK/Renderer/OrthographicCamera.cpp | AreYouReal/AYK | c6859047cfed674291692cc31095d8bb61b27a35 | [
"Apache-2.0"
] | null | null | null | AYK/src/AYK/Renderer/OrthographicCamera.cpp | AreYouReal/AYK | c6859047cfed674291692cc31095d8bb61b27a35 | [
"Apache-2.0"
] | null | null | null | #include "aykpch.h"
#include "OrthographicCamera.h"
#include <glm/gtc/matrix_transform.hpp>
namespace AYK {
OrthographicCamera::OrthographicCamera(float Left, float Right, float Bottom, float Top) : ProjectionMatrix(glm::ortho(Left, Right, Bottom, Top, -1.0f, 1.0f)), ViewMatrix(1.0f){
AYK_PROFILE_FUNCTION();
ViewProjectionMatrix = ProjectionMatrix * ViewMatrix;
}
void OrthographicCamera::SetProjection(float Left, float Right, float Bottom, float Top) {
AYK_PROFILE_FUNCTION();
ProjectionMatrix = glm::ortho(Left, Right, Bottom, Top, -1.0f, 1.0f);
ViewProjectionMatrix = ProjectionMatrix * ViewMatrix;
}
void OrthographicCamera::RecalculateViewMatrix(){
AYK_PROFILE_FUNCTION();
glm::mat4 Transform = glm::translate(glm::mat4(1.0f), Position) * glm::rotate(glm::mat4(1.0f), glm::radians(Rotation), glm::vec3(0, 0, 1));
ViewMatrix = glm::inverse(Transform);
ViewProjectionMatrix = ProjectionMatrix * ViewMatrix;
}
}
| 28.058824 | 178 | 0.736897 | AreYouReal |
066a5658cb723db9cd81c7b8d2f19fbc9cc1c63a | 206,755 | hpp | C++ | cisco-ios-xe/ydk/models/cisco_ios_xe/fragmented/Cisco_IOS_XE_native_97.hpp | 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_97.hpp | 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_97.hpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 11 | 2016-12-02T05:45:52.000Z | 2019-11-07T08:28:17.000Z | #ifndef _CISCO_IOS_XE_NATIVE_97_
#define _CISCO_IOS_XE_NATIVE_97_
#include <memory>
#include <vector>
#include <string>
#include <ydk/types.hpp>
#include <ydk/errors.hpp>
#include "Cisco_IOS_XE_native_0.hpp"
#include "Cisco_IOS_XE_native_20.hpp"
#include "Cisco_IOS_XE_native_95.hpp"
#include "Cisco_IOS_XE_native_96.hpp"
namespace cisco_ios_xe {
namespace Cisco_IOS_XE_native {
class Native::Interface::Vlan::Ethernet::Oam::LinkMonitor::SymbolPeriod::Threshold::High : public ydk::Entity
{
public:
High();
~High();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf err_thresh; //type: uint16
ydk::YLeaf none; //type: empty
}; // Native::Interface::Vlan::Ethernet::Oam::LinkMonitor::SymbolPeriod::Threshold::High
class Native::Interface::Vlan::Ethernet::Oam::RemoteFailure : public ydk::Entity
{
public:
RemoteFailure();
~RemoteFailure();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class CriticalEvent; //type: Native::Interface::Vlan::Ethernet::Oam::RemoteFailure::CriticalEvent
class DyingGasp; //type: Native::Interface::Vlan::Ethernet::Oam::RemoteFailure::DyingGasp
class LinkFault; //type: Native::Interface::Vlan::Ethernet::Oam::RemoteFailure::LinkFault
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Ethernet::Oam::RemoteFailure::CriticalEvent> critical_event;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Ethernet::Oam::RemoteFailure::DyingGasp> dying_gasp;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Ethernet::Oam::RemoteFailure::LinkFault> link_fault;
}; // Native::Interface::Vlan::Ethernet::Oam::RemoteFailure
class Native::Interface::Vlan::Ethernet::Oam::RemoteFailure::CriticalEvent : public ydk::Entity
{
public:
CriticalEvent();
~CriticalEvent();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Action; //type: Native::Interface::Vlan::Ethernet::Oam::RemoteFailure::CriticalEvent::Action
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Ethernet::Oam::RemoteFailure::CriticalEvent::Action> action;
}; // Native::Interface::Vlan::Ethernet::Oam::RemoteFailure::CriticalEvent
class Native::Interface::Vlan::Ethernet::Oam::RemoteFailure::CriticalEvent::Action : public ydk::Entity
{
public:
Action();
~Action();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf error_disable_interface; //type: empty
}; // Native::Interface::Vlan::Ethernet::Oam::RemoteFailure::CriticalEvent::Action
class Native::Interface::Vlan::Ethernet::Oam::RemoteFailure::DyingGasp : public ydk::Entity
{
public:
DyingGasp();
~DyingGasp();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Action; //type: Native::Interface::Vlan::Ethernet::Oam::RemoteFailure::DyingGasp::Action
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Ethernet::Oam::RemoteFailure::DyingGasp::Action> action; // presence node
}; // Native::Interface::Vlan::Ethernet::Oam::RemoteFailure::DyingGasp
class Native::Interface::Vlan::Ethernet::Oam::RemoteFailure::DyingGasp::Action : public ydk::Entity
{
public:
Action();
~Action();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf error_disable_interface; //type: empty
}; // Native::Interface::Vlan::Ethernet::Oam::RemoteFailure::DyingGasp::Action
class Native::Interface::Vlan::Ethernet::Oam::RemoteFailure::LinkFault : public ydk::Entity
{
public:
LinkFault();
~LinkFault();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Action; //type: Native::Interface::Vlan::Ethernet::Oam::RemoteFailure::LinkFault::Action
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Ethernet::Oam::RemoteFailure::LinkFault::Action> action; // presence node
}; // Native::Interface::Vlan::Ethernet::Oam::RemoteFailure::LinkFault
class Native::Interface::Vlan::Ethernet::Oam::RemoteFailure::LinkFault::Action : public ydk::Entity
{
public:
Action();
~Action();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf error_disable_interface; //type: empty
}; // Native::Interface::Vlan::Ethernet::Oam::RemoteFailure::LinkFault::Action
class Native::Interface::Vlan::Ethernet::Oam::RemoteLoopback : public ydk::Entity
{
public:
RemoteLoopback();
~RemoteLoopback();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf supported; //type: empty
ydk::YLeaf timeout; //type: uint8
}; // Native::Interface::Vlan::Ethernet::Oam::RemoteLoopback
class Native::Interface::Vlan::Ethernet::Dot1ad : public ydk::Entity
{
public:
Dot1ad();
~Dot1ad();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf nni; //type: empty
class Uni; //type: Native::Interface::Vlan::Ethernet::Dot1ad::Uni
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Ethernet::Dot1ad::Uni> uni;
}; // Native::Interface::Vlan::Ethernet::Dot1ad
class Native::Interface::Vlan::Ethernet::Dot1ad::Uni : public ydk::Entity
{
public:
Uni();
~Uni();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf c_port; //type: empty
ydk::YLeaf s_port; //type: empty
}; // Native::Interface::Vlan::Ethernet::Dot1ad::Uni
class Native::Interface::Vlan::Eapol : public ydk::Entity
{
public:
Eapol();
~Eapol();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class DestinationAddress; //type: Native::Interface::Vlan::Eapol::DestinationAddress
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Eapol::DestinationAddress> destination_address;
}; // Native::Interface::Vlan::Eapol
class Native::Interface::Vlan::Eapol::DestinationAddress : public ydk::Entity
{
public:
DestinationAddress();
~DestinationAddress();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf broadcast_address; //type: empty
}; // Native::Interface::Vlan::Eapol::DestinationAddress
class Native::Interface::Vlan::Synchronous : public ydk::Entity
{
public:
Synchronous();
~Synchronous();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf mode; //type: empty
}; // Native::Interface::Vlan::Synchronous
class Native::Interface::Vlan::Speed : public ydk::Entity
{
public:
Speed();
~Speed();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf auto_; //type: empty
ydk::YLeaf value_10; //type: empty
ydk::YLeaf value_100; //type: empty
ydk::YLeaf value_1000; //type: empty
ydk::YLeaf value_10000; //type: empty
ydk::YLeaf nonegotiate; //type: empty
}; // Native::Interface::Vlan::Speed
class Native::Interface::Vlan::Negotiation : public ydk::Entity
{
public:
Negotiation();
~Negotiation();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf auto_; //type: boolean
}; // Native::Interface::Vlan::Negotiation
class Native::Interface::Vlan::Plim : public ydk::Entity
{
public:
Plim();
~Plim();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Ethernet; //type: Native::Interface::Vlan::Plim::Ethernet
class Qos; //type: Native::Interface::Vlan::Plim::Qos
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Plim::Ethernet> ethernet;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Plim::Qos> qos;
}; // Native::Interface::Vlan::Plim
class Native::Interface::Vlan::Plim::Ethernet : public ydk::Entity
{
public:
Ethernet();
~Ethernet();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Vlan_; //type: Native::Interface::Vlan::Plim::Ethernet::Vlan_
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Plim::Ethernet::Vlan_> vlan;
}; // Native::Interface::Vlan::Plim::Ethernet
class Native::Interface::Vlan::Plim::Ethernet::Vlan_ : public ydk::Entity
{
public:
Vlan_();
~Vlan_();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Filter; //type: Native::Interface::Vlan::Plim::Ethernet::Vlan_::Filter
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Plim::Ethernet::Vlan_::Filter> filter;
}; // Native::Interface::Vlan::Plim::Ethernet::Vlan_
class Native::Interface::Vlan::Plim::Ethernet::Vlan_::Filter : public ydk::Entity
{
public:
Filter();
~Filter();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf disable; //type: empty
}; // Native::Interface::Vlan::Plim::Ethernet::Vlan_::Filter
class Native::Interface::Vlan::Plim::Qos : public ydk::Entity
{
public:
Qos();
~Qos();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Input; //type: Native::Interface::Vlan::Plim::Qos::Input
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Plim::Qos::Input> input;
}; // Native::Interface::Vlan::Plim::Qos
class Native::Interface::Vlan::Plim::Qos::Input : public ydk::Entity
{
public:
Input();
~Input();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Queue; //type: Native::Interface::Vlan::Plim::Qos::Input::Queue
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Plim::Qos::Input::Queue> queue;
}; // Native::Interface::Vlan::Plim::Qos::Input
class Native::Interface::Vlan::Plim::Qos::Input::Queue : public ydk::Entity
{
public:
Queue();
~Queue();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Zero; //type: Native::Interface::Vlan::Plim::Qos::Input::Queue::Zero
class StrictPriority; //type: Native::Interface::Vlan::Plim::Qos::Input::Queue::StrictPriority
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Plim::Qos::Input::Queue::Zero> zero;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Plim::Qos::Input::Queue::StrictPriority> strict_priority;
}; // Native::Interface::Vlan::Plim::Qos::Input::Queue
class Native::Interface::Vlan::Plim::Qos::Input::Queue::Zero : public ydk::Entity
{
public:
Zero();
~Zero();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Pause; //type: Native::Interface::Vlan::Plim::Qos::Input::Queue::Zero::Pause
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Plim::Qos::Input::Queue::Zero::Pause> pause;
}; // Native::Interface::Vlan::Plim::Qos::Input::Queue::Zero
class Native::Interface::Vlan::Plim::Qos::Input::Queue::Zero::Pause : public ydk::Entity
{
public:
Pause();
~Pause();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf enable; //type: boolean
ydk::YLeaf threshold; //type: uint8
}; // Native::Interface::Vlan::Plim::Qos::Input::Queue::Zero::Pause
class Native::Interface::Vlan::Plim::Qos::Input::Queue::StrictPriority : public ydk::Entity
{
public:
StrictPriority();
~StrictPriority();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Pause; //type: Native::Interface::Vlan::Plim::Qos::Input::Queue::StrictPriority::Pause
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Plim::Qos::Input::Queue::StrictPriority::Pause> pause;
}; // Native::Interface::Vlan::Plim::Qos::Input::Queue::StrictPriority
class Native::Interface::Vlan::Plim::Qos::Input::Queue::StrictPriority::Pause : public ydk::Entity
{
public:
Pause();
~Pause();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf enable; //type: boolean
ydk::YLeaf threshold; //type: uint8
}; // Native::Interface::Vlan::Plim::Qos::Input::Queue::StrictPriority::Pause
class Native::Interface::Vlan::Pppoe : public ydk::Entity
{
public:
Pppoe();
~Pppoe();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf max_sessions; //type: uint16
class Enable; //type: Native::Interface::Vlan::Pppoe::Enable
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Pppoe::Enable> enable; // presence node
}; // Native::Interface::Vlan::Pppoe
class Native::Interface::Vlan::Pppoe::Enable : public ydk::Entity
{
public:
Enable();
~Enable();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf group; //type: one of string, enumeration
class Group;
}; // Native::Interface::Vlan::Pppoe::Enable
class Native::Interface::Vlan::Service : public ydk::Entity
{
public:
Service();
~Service();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Instance; //type: Native::Interface::Vlan::Service::Instance
ydk::YList instance;
}; // Native::Interface::Vlan::Service
class Native::Interface::Vlan::Service::Instance : public ydk::Entity
{
public:
Instance();
~Instance();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf id; //type: uint32
ydk::YLeaf trunk; //type: empty
ydk::YLeaf gigabitethernet; //type: empty
ydk::YLeaf ethernet; //type: empty
ydk::YLeaf ethernet_evc_name; //type: string
ydk::YLeaf description; //type: string
ydk::YLeaf evc_name; //type: string
ydk::YLeaf group; //type: uint32
ydk::YLeaf shutdown; //type: empty
class Encapsulation; //type: Native::Interface::Vlan::Service::Instance::Encapsulation
class Ip; //type: Native::Interface::Vlan::Service::Instance::Ip
class Ipv6; //type: Native::Interface::Vlan::Service::Instance::Ipv6
class Rewrite; //type: Native::Interface::Vlan::Service::Instance::Rewrite
class Errdisable; //type: Native::Interface::Vlan::Service::Instance::Errdisable
class EthernetContainer; //type: Native::Interface::Vlan::Service::Instance::EthernetContainer
class Snmp; //type: Native::Interface::Vlan::Service::Instance::Snmp
class BridgeDomain; //type: Native::Interface::Vlan::Service::Instance::BridgeDomain
class Mac; //type: Native::Interface::Vlan::Service::Instance::Mac
class ServicePolicy; //type: Native::Interface::Vlan::Service::Instance::ServicePolicy
class Cfm; //type: Native::Interface::Vlan::Service::Instance::Cfm
class L2protocol; //type: Native::Interface::Vlan::Service::Instance::L2protocol
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Encapsulation> encapsulation;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Ip> ip;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Ipv6> ipv6;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Rewrite> rewrite;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Errdisable> errdisable;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::EthernetContainer> ethernet_container;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Snmp> snmp;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::BridgeDomain> bridge_domain;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Mac> mac;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::ServicePolicy> service_policy;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Cfm> cfm;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::L2protocol> l2protocol;
}; // Native::Interface::Vlan::Service::Instance
class Native::Interface::Vlan::Service::Instance::Encapsulation : public ydk::Entity
{
public:
Encapsulation();
~Encapsulation();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf default_; //type: empty
class Dot1ad; //type: Native::Interface::Vlan::Service::Instance::Encapsulation::Dot1ad
class Dot1q; //type: Native::Interface::Vlan::Service::Instance::Encapsulation::Dot1q
class PriorityTagged; //type: Native::Interface::Vlan::Service::Instance::Encapsulation::PriorityTagged
class Untagged; //type: Native::Interface::Vlan::Service::Instance::Encapsulation::Untagged
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Encapsulation::Dot1ad> dot1ad;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Encapsulation::Dot1q> dot1q;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Encapsulation::PriorityTagged> priority_tagged; // presence node
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Encapsulation::Untagged> untagged; // presence node
}; // Native::Interface::Vlan::Service::Instance::Encapsulation
class Native::Interface::Vlan::Service::Instance::Encapsulation::Dot1ad : public ydk::Entity
{
public:
Dot1ad();
~Dot1ad();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf exact; //type: empty
ydk::YLeafList id; //type: list of one of uint16, string, enumeration
ydk::YLeafList cos; //type: list of uint8
ydk::YLeafList dot1q; //type: list of one of uint16, string, enumeration
ydk::YLeafList etype; //type: list of Etype
class Cos2; //type: Native::Interface::Vlan::Service::Instance::Encapsulation::Dot1ad::Cos2
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Encapsulation::Dot1ad::Cos2> cos2;
class Id;
class Dot1q;
class Etype;
}; // Native::Interface::Vlan::Service::Instance::Encapsulation::Dot1ad
class Native::Interface::Vlan::Service::Instance::Encapsulation::Dot1ad::Cos2 : public ydk::Entity
{
public:
Cos2();
~Cos2();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeafList cos; //type: list of uint8
}; // Native::Interface::Vlan::Service::Instance::Encapsulation::Dot1ad::Cos2
class Native::Interface::Vlan::Service::Instance::Encapsulation::Dot1q : public ydk::Entity
{
public:
Dot1q();
~Dot1q();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf exact; //type: empty
ydk::YLeaf vlan_type; //type: VlanType
ydk::YLeafList id; //type: list of one of uint16, string, enumeration
ydk::YLeafList cos; //type: list of uint8
ydk::YLeafList second_dot1q; //type: list of one of uint16, string, enumeration
ydk::YLeafList etype; //type: list of Etype
class Cos2; //type: Native::Interface::Vlan::Service::Instance::Encapsulation::Dot1q::Cos2
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Encapsulation::Dot1q::Cos2> cos2;
class Id;
class SecondDot1q;
class Etype;
class VlanType;
}; // Native::Interface::Vlan::Service::Instance::Encapsulation::Dot1q
class Native::Interface::Vlan::Service::Instance::Encapsulation::Dot1q::Cos2 : public ydk::Entity
{
public:
Cos2();
~Cos2();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeafList cos; //type: list of uint8
}; // Native::Interface::Vlan::Service::Instance::Encapsulation::Dot1q::Cos2
class Native::Interface::Vlan::Service::Instance::Encapsulation::PriorityTagged : public ydk::Entity
{
public:
PriorityTagged();
~PriorityTagged();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeafList etype; //type: list of Etype
class CosContainer; //type: Native::Interface::Vlan::Service::Instance::Encapsulation::PriorityTagged::CosContainer
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Encapsulation::PriorityTagged::CosContainer> cos_container;
class Etype;
}; // Native::Interface::Vlan::Service::Instance::Encapsulation::PriorityTagged
class Native::Interface::Vlan::Service::Instance::Encapsulation::PriorityTagged::CosContainer : public ydk::Entity
{
public:
CosContainer();
~CosContainer();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeafList cos; //type: list of uint8
}; // Native::Interface::Vlan::Service::Instance::Encapsulation::PriorityTagged::CosContainer
class Native::Interface::Vlan::Service::Instance::Encapsulation::Untagged : public ydk::Entity
{
public:
Untagged();
~Untagged();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
}; // Native::Interface::Vlan::Service::Instance::Encapsulation::Untagged
class Native::Interface::Vlan::Service::Instance::Ip : public ydk::Entity
{
public:
Ip();
~Ip();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Acl; //type: Native::Interface::Vlan::Service::Instance::Ip::Acl
class Dhcp; //type: Native::Interface::Vlan::Service::Instance::Ip::Dhcp
class Verify; //type: Native::Interface::Vlan::Service::Instance::Ip::Verify
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Ip::Acl> acl;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Ip::Dhcp> dhcp;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Ip::Verify> verify;
}; // Native::Interface::Vlan::Service::Instance::Ip
class Native::Interface::Vlan::Service::Instance::Ip::Acl : public ydk::Entity
{
public:
Acl();
~Acl();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf access_group; //type: one of uint16, string
ydk::YLeaf in; //type: empty
ydk::YLeaf out; //type: empty
}; // Native::Interface::Vlan::Service::Instance::Ip::Acl
class Native::Interface::Vlan::Service::Instance::Ip::Dhcp : public ydk::Entity
{
public:
Dhcp();
~Dhcp();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Relay; //type: Native::Interface::Vlan::Service::Instance::Ip::Dhcp::Relay
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Ip::Dhcp::Relay> relay;
}; // Native::Interface::Vlan::Service::Instance::Ip::Dhcp
class Native::Interface::Vlan::Service::Instance::Ip::Dhcp::Relay : public ydk::Entity
{
public:
Relay();
~Relay();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Information; //type: Native::Interface::Vlan::Service::Instance::Ip::Dhcp::Relay::Information
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Ip::Dhcp::Relay::Information> information;
}; // Native::Interface::Vlan::Service::Instance::Ip::Dhcp::Relay
class Native::Interface::Vlan::Service::Instance::Ip::Dhcp::Relay::Information : public ydk::Entity
{
public:
Information();
~Information();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Option; //type: Native::Interface::Vlan::Service::Instance::Ip::Dhcp::Relay::Information::Option
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Ip::Dhcp::Relay::Information::Option> option;
}; // Native::Interface::Vlan::Service::Instance::Ip::Dhcp::Relay::Information
class Native::Interface::Vlan::Service::Instance::Ip::Dhcp::Relay::Information::Option : public ydk::Entity
{
public:
Option();
~Option();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf subscriber_id; //type: string
}; // Native::Interface::Vlan::Service::Instance::Ip::Dhcp::Relay::Information::Option
class Native::Interface::Vlan::Service::Instance::Ip::Verify : public ydk::Entity
{
public:
Verify();
~Verify();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf source; //type: empty
ydk::YLeaf vlan; //type: empty
ydk::YLeaf dhcp_snooping; //type: empty
ydk::YLeaf port_security; //type: empty
}; // Native::Interface::Vlan::Service::Instance::Ip::Verify
class Native::Interface::Vlan::Service::Instance::Ipv6 : public ydk::Entity
{
public:
Ipv6();
~Ipv6();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf traffic_filter; //type: string
ydk::YLeaf in; //type: empty
ydk::YLeaf out; //type: empty
}; // Native::Interface::Vlan::Service::Instance::Ipv6
class Native::Interface::Vlan::Service::Instance::Rewrite : public ydk::Entity
{
public:
Rewrite();
~Rewrite();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Ingress; //type: Native::Interface::Vlan::Service::Instance::Rewrite::Ingress
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Rewrite::Ingress> ingress;
}; // Native::Interface::Vlan::Service::Instance::Rewrite
class Native::Interface::Vlan::Service::Instance::Rewrite::Ingress : public ydk::Entity
{
public:
Ingress();
~Ingress();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Tag; //type: Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag> tag;
}; // Native::Interface::Vlan::Service::Instance::Rewrite::Ingress
class Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag : public ydk::Entity
{
public:
Tag();
~Tag();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Pop; //type: Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag::Pop
class Push; //type: Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag::Push
class Translate; //type: Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag::Translate
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag::Pop> pop;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag::Push> push;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag::Translate> translate;
}; // Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag
class Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag::Pop : public ydk::Entity
{
public:
Pop();
~Pop();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf way; //type: Way
ydk::YLeaf mode; //type: Mode
class Way;
class Mode;
}; // Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag::Pop
class Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag::Push : public ydk::Entity
{
public:
Push();
~Push();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf dot1q; //type: uint16
ydk::YLeaf mode; //type: Mode
class Mode;
}; // Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag::Push
class Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag::Translate : public ydk::Entity
{
public:
Translate();
~Translate();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class T1To1; //type: Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag::Translate::T1To1
class T1To2; //type: Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag::Translate::T1To2
class T2To1; //type: Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag::Translate::T2To1
class T2To2; //type: Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag::Translate::T2To2
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag::Translate::T1To1> t1_to_1;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag::Translate::T1To2> t1_to_2;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag::Translate::T2To1> t2_to_1;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag::Translate::T2To2> t2_to_2;
}; // Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag::Translate
class Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag::Translate::T1To1 : public ydk::Entity
{
public:
T1To1();
~T1To1();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf dot1q; //type: uint16
ydk::YLeaf mode; //type: Mode
class Mode;
}; // Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag::Translate::T1To1
class Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag::Translate::T1To2 : public ydk::Entity
{
public:
T1To2();
~T1To2();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf dot1q; //type: uint16
ydk::YLeaf second_dot1q; //type: uint16
ydk::YLeaf mode; //type: Mode
class Mode;
}; // Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag::Translate::T1To2
class Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag::Translate::T2To1 : public ydk::Entity
{
public:
T2To1();
~T2To1();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf dot1q; //type: uint16
ydk::YLeaf mode; //type: Mode
class Mode;
}; // Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag::Translate::T2To1
class Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag::Translate::T2To2 : public ydk::Entity
{
public:
T2To2();
~T2To2();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf dot1q; //type: uint16
ydk::YLeaf second_dot1q; //type: uint16
ydk::YLeaf mode; //type: Mode
class Mode;
}; // Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag::Translate::T2To2
class Native::Interface::Vlan::Service::Instance::Errdisable : public ydk::Entity
{
public:
Errdisable();
~Errdisable();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Recovery; //type: Native::Interface::Vlan::Service::Instance::Errdisable::Recovery
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Errdisable::Recovery> recovery;
}; // Native::Interface::Vlan::Service::Instance::Errdisable
class Native::Interface::Vlan::Service::Instance::Errdisable::Recovery : public ydk::Entity
{
public:
Recovery();
~Recovery();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Cause; //type: Native::Interface::Vlan::Service::Instance::Errdisable::Recovery::Cause
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Errdisable::Recovery::Cause> cause;
}; // Native::Interface::Vlan::Service::Instance::Errdisable::Recovery
class Native::Interface::Vlan::Service::Instance::Errdisable::Recovery::Cause : public ydk::Entity
{
public:
Cause();
~Cause();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf mac_security; //type: uint32
}; // Native::Interface::Vlan::Service::Instance::Errdisable::Recovery::Cause
class Native::Interface::Vlan::Service::Instance::EthernetContainer : public ydk::Entity
{
public:
EthernetContainer();
~EthernetContainer();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Ethernet; //type: Native::Interface::Vlan::Service::Instance::EthernetContainer::Ethernet
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::EthernetContainer::Ethernet> ethernet;
}; // Native::Interface::Vlan::Service::Instance::EthernetContainer
class Native::Interface::Vlan::Service::Instance::EthernetContainer::Ethernet : public ydk::Entity
{
public:
Ethernet();
~Ethernet();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Lmi; //type: Native::Interface::Vlan::Service::Instance::EthernetContainer::Ethernet::Lmi
class Loopback; //type: Native::Interface::Vlan::Service::Instance::EthernetContainer::Ethernet::Loopback
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::EthernetContainer::Ethernet::Lmi> lmi;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::EthernetContainer::Ethernet::Loopback> loopback;
}; // Native::Interface::Vlan::Service::Instance::EthernetContainer::Ethernet
class Native::Interface::Vlan::Service::Instance::EthernetContainer::Ethernet::Lmi : public ydk::Entity
{
public:
Lmi();
~Lmi();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class CeVlan; //type: Native::Interface::Vlan::Service::Instance::EthernetContainer::Ethernet::Lmi::CeVlan
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::EthernetContainer::Ethernet::Lmi::CeVlan> ce_vlan;
}; // Native::Interface::Vlan::Service::Instance::EthernetContainer::Ethernet::Lmi
class Native::Interface::Vlan::Service::Instance::EthernetContainer::Ethernet::Lmi::CeVlan : public ydk::Entity
{
public:
CeVlan();
~CeVlan();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Map; //type: Native::Interface::Vlan::Service::Instance::EthernetContainer::Ethernet::Lmi::CeVlan::Map
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::EthernetContainer::Ethernet::Lmi::CeVlan::Map> map;
}; // Native::Interface::Vlan::Service::Instance::EthernetContainer::Ethernet::Lmi::CeVlan
class Native::Interface::Vlan::Service::Instance::EthernetContainer::Ethernet::Lmi::CeVlan::Map : public ydk::Entity
{
public:
Map();
~Map();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf any; //type: empty
ydk::YLeaf default_; //type: empty
ydk::YLeaf untagged; //type: empty
ydk::YLeaf vlan_range; //type: string
}; // Native::Interface::Vlan::Service::Instance::EthernetContainer::Ethernet::Lmi::CeVlan::Map
class Native::Interface::Vlan::Service::Instance::EthernetContainer::Ethernet::Loopback : public ydk::Entity
{
public:
Loopback();
~Loopback();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Permit; //type: Native::Interface::Vlan::Service::Instance::EthernetContainer::Ethernet::Loopback::Permit
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::EthernetContainer::Ethernet::Loopback::Permit> permit;
}; // Native::Interface::Vlan::Service::Instance::EthernetContainer::Ethernet::Loopback
class Native::Interface::Vlan::Service::Instance::EthernetContainer::Ethernet::Loopback::Permit : public ydk::Entity
{
public:
Permit();
~Permit();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf external; //type: empty
ydk::YLeaf internal; //type: empty
}; // Native::Interface::Vlan::Service::Instance::EthernetContainer::Ethernet::Loopback::Permit
class Native::Interface::Vlan::Service::Instance::Snmp : public ydk::Entity
{
public:
Snmp();
~Snmp();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Trap; //type: Native::Interface::Vlan::Service::Instance::Snmp::Trap
class Ifindex; //type: Native::Interface::Vlan::Service::Instance::Snmp::Ifindex
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Snmp::Trap> trap;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Snmp::Ifindex> ifindex;
}; // Native::Interface::Vlan::Service::Instance::Snmp
class Native::Interface::Vlan::Service::Instance::Snmp::Trap : public ydk::Entity
{
public:
Trap();
~Trap();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf link_status; //type: empty
}; // Native::Interface::Vlan::Service::Instance::Snmp::Trap
class Native::Interface::Vlan::Service::Instance::Snmp::Ifindex : public ydk::Entity
{
public:
Ifindex();
~Ifindex();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf persist; //type: empty
}; // Native::Interface::Vlan::Service::Instance::Snmp::Ifindex
class Native::Interface::Vlan::Service::Instance::BridgeDomain : public ydk::Entity
{
public:
BridgeDomain();
~BridgeDomain();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf bridge_id; //type: uint16
ydk::YLeaf from_encapsulation; //type: empty
class SplitHorizon; //type: Native::Interface::Vlan::Service::Instance::BridgeDomain::SplitHorizon
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::BridgeDomain::SplitHorizon> split_horizon;
}; // Native::Interface::Vlan::Service::Instance::BridgeDomain
class Native::Interface::Vlan::Service::Instance::BridgeDomain::SplitHorizon : public ydk::Entity
{
public:
SplitHorizon();
~SplitHorizon();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf group; //type: uint8
}; // Native::Interface::Vlan::Service::Instance::BridgeDomain::SplitHorizon
class Native::Interface::Vlan::Service::Instance::Mac : public ydk::Entity
{
public:
Mac();
~Mac();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Security; //type: Native::Interface::Vlan::Service::Instance::Mac::Security
class AccessGroup; //type: Native::Interface::Vlan::Service::Instance::Mac::AccessGroup
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Mac::Security> security; // presence node
ydk::YList access_group;
}; // Native::Interface::Vlan::Service::Instance::Mac
class Native::Interface::Vlan::Service::Instance::Mac::Security : public ydk::Entity
{
public:
Security();
~Security();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf violation; //type: Violation
class Maximum; //type: Native::Interface::Vlan::Service::Instance::Mac::Security::Maximum
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Mac::Security::Maximum> maximum;
class Violation;
}; // Native::Interface::Vlan::Service::Instance::Mac::Security
class Native::Interface::Vlan::Service::Instance::Mac::Security::Maximum : public ydk::Entity
{
public:
Maximum();
~Maximum();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf addresses; //type: uint16
}; // Native::Interface::Vlan::Service::Instance::Mac::Security::Maximum
class Native::Interface::Vlan::Service::Instance::Mac::AccessGroup : public ydk::Entity
{
public:
AccessGroup();
~AccessGroup();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf acl_name; //type: string
ydk::YLeaf in; //type: empty
ydk::YLeaf out; //type: empty
}; // Native::Interface::Vlan::Service::Instance::Mac::AccessGroup
class Native::Interface::Vlan::Service::Instance::ServicePolicy : public ydk::Entity
{
public:
ServicePolicy();
~ServicePolicy();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Input; //type: Native::Interface::Vlan::Service::Instance::ServicePolicy::Input
class Output; //type: Native::Interface::Vlan::Service::Instance::ServicePolicy::Output
ydk::YList input;
ydk::YList output;
}; // Native::Interface::Vlan::Service::Instance::ServicePolicy
class Native::Interface::Vlan::Service::Instance::ServicePolicy::Input : public ydk::Entity
{
public:
Input();
~Input();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf name; //type: string
}; // Native::Interface::Vlan::Service::Instance::ServicePolicy::Input
class Native::Interface::Vlan::Service::Instance::ServicePolicy::Output : public ydk::Entity
{
public:
Output();
~Output();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf name; //type: string
}; // Native::Interface::Vlan::Service::Instance::ServicePolicy::Output
class Native::Interface::Vlan::Service::Instance::Cfm : public ydk::Entity
{
public:
Cfm();
~Cfm();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Encapsulation; //type: Native::Interface::Vlan::Service::Instance::Cfm::Encapsulation
class Mep; //type: Native::Interface::Vlan::Service::Instance::Cfm::Mep
class Mip; //type: Native::Interface::Vlan::Service::Instance::Cfm::Mip
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Cfm::Encapsulation> encapsulation;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Cfm::Mep> mep;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Cfm::Mip> mip;
}; // Native::Interface::Vlan::Service::Instance::Cfm
class Native::Interface::Vlan::Service::Instance::Cfm::Encapsulation : public ydk::Entity
{
public:
Encapsulation();
~Encapsulation();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Dot1ad; //type: Native::Interface::Vlan::Service::Instance::Cfm::Encapsulation::Dot1ad
class Dot1q; //type: Native::Interface::Vlan::Service::Instance::Cfm::Encapsulation::Dot1q
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Cfm::Encapsulation::Dot1ad> dot1ad;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::Cfm::Encapsulation::Dot1q> dot1q;
}; // Native::Interface::Vlan::Service::Instance::Cfm::Encapsulation
class Native::Interface::Vlan::Service::Instance::Cfm::Encapsulation::Dot1ad : public ydk::Entity
{
public:
Dot1ad();
~Dot1ad();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf vlan_id; //type: uint16
ydk::YLeaf cos; //type: uint8
ydk::YLeaf dot1q; //type: uint16
}; // Native::Interface::Vlan::Service::Instance::Cfm::Encapsulation::Dot1ad
class Native::Interface::Vlan::Service::Instance::Cfm::Encapsulation::Dot1q : public ydk::Entity
{
public:
Dot1q();
~Dot1q();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf vlan_id; //type: uint16
ydk::YLeaf cos; //type: uint8
ydk::YLeaf second_dot1q; //type: uint16
}; // Native::Interface::Vlan::Service::Instance::Cfm::Encapsulation::Dot1q
class Native::Interface::Vlan::Service::Instance::Cfm::Mep : public ydk::Entity
{
public:
Mep();
~Mep();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf domain; //type: string
ydk::YLeaf mpid; //type: uint16
}; // Native::Interface::Vlan::Service::Instance::Cfm::Mep
class Native::Interface::Vlan::Service::Instance::Cfm::Mip : public ydk::Entity
{
public:
Mip();
~Mip();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf level; //type: uint8
}; // Native::Interface::Vlan::Service::Instance::Cfm::Mip
class Native::Interface::Vlan::Service::Instance::L2protocol : public ydk::Entity
{
public:
L2protocol();
~L2protocol();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Discard; //type: Native::Interface::Vlan::Service::Instance::L2protocol::Discard
class Peer; //type: Native::Interface::Vlan::Service::Instance::L2protocol::Peer
class Forward; //type: Native::Interface::Vlan::Service::Instance::L2protocol::Forward
class Tunnel; //type: Native::Interface::Vlan::Service::Instance::L2protocol::Tunnel
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::L2protocol::Discard> discard; // presence node
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::L2protocol::Peer> peer; // presence node
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::L2protocol::Forward> forward; // presence node
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Service::Instance::L2protocol::Tunnel> tunnel; // presence node
}; // Native::Interface::Vlan::Service::Instance::L2protocol
class Native::Interface::Vlan::Service::Instance::L2protocol::Discard : public ydk::Entity
{
public:
Discard();
~Discard();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeafList protocol; //type: list of Protocol
class Protocol;
}; // Native::Interface::Vlan::Service::Instance::L2protocol::Discard
class Native::Interface::Vlan::Service::Instance::L2protocol::Peer : public ydk::Entity
{
public:
Peer();
~Peer();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeafList protocol; //type: list of Protocol
class Protocol;
}; // Native::Interface::Vlan::Service::Instance::L2protocol::Peer
class Native::Interface::Vlan::Service::Instance::L2protocol::Forward : public ydk::Entity
{
public:
Forward();
~Forward();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeafList protocol; //type: list of Protocol
class Protocol;
}; // Native::Interface::Vlan::Service::Instance::L2protocol::Forward
class Native::Interface::Vlan::Service::Instance::L2protocol::Tunnel : public ydk::Entity
{
public:
Tunnel();
~Tunnel();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeafList protocol; //type: list of Protocol
class Protocol;
}; // Native::Interface::Vlan::Service::Instance::L2protocol::Tunnel
class Native::Interface::Vlan::EtAnalytics : public ydk::Entity
{
public:
EtAnalytics();
~EtAnalytics();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf enable; //type: empty
}; // Native::Interface::Vlan::EtAnalytics
class Native::Interface::Vlan::ServicePolicy : public ydk::Entity
{
public:
ServicePolicy();
~ServicePolicy();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf history; //type: empty
ydk::YLeaf input; //type: string
ydk::YLeaf output; //type: string
class Type; //type: Native::Interface::Vlan::ServicePolicy::Type
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::ServicePolicy::Type> type;
}; // Native::Interface::Vlan::ServicePolicy
class Native::Interface::Vlan::ServicePolicy::Type : public ydk::Entity
{
public:
Type();
~Type();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Control; //type: Native::Interface::Vlan::ServicePolicy::Type::Control
class PerformanceMonitor; //type: Native::Interface::Vlan::ServicePolicy::Type::PerformanceMonitor
class ServiceChain; //type: Native::Interface::Vlan::ServicePolicy::Type::ServiceChain
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::ServicePolicy::Type::Control> control;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::ServicePolicy::Type::PerformanceMonitor> performance_monitor;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::ServicePolicy::Type::ServiceChain> service_chain;
}; // Native::Interface::Vlan::ServicePolicy::Type
class Native::Interface::Vlan::ServicePolicy::Type::Control : public ydk::Entity
{
public:
Control();
~Control();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf subscriber; //type: string
}; // Native::Interface::Vlan::ServicePolicy::Type::Control
class Native::Interface::Vlan::ServicePolicy::Type::PerformanceMonitor : public ydk::Entity
{
public:
PerformanceMonitor();
~PerformanceMonitor();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf direction; //type: Direction
ydk::YLeaf name; //type: string
class Direction;
}; // Native::Interface::Vlan::ServicePolicy::Type::PerformanceMonitor
class Native::Interface::Vlan::ServicePolicy::Type::ServiceChain : public ydk::Entity
{
public:
ServiceChain();
~ServiceChain();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Input; //type: Native::Interface::Vlan::ServicePolicy::Type::ServiceChain::Input
class Output; //type: Native::Interface::Vlan::ServicePolicy::Type::ServiceChain::Output
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::ServicePolicy::Type::ServiceChain::Input> input;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::ServicePolicy::Type::ServiceChain::Output> output;
}; // Native::Interface::Vlan::ServicePolicy::Type::ServiceChain
class Native::Interface::Vlan::ServicePolicy::Type::ServiceChain::Input : public ydk::Entity
{
public:
Input();
~Input();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf name; //type: string
}; // Native::Interface::Vlan::ServicePolicy::Type::ServiceChain::Input
class Native::Interface::Vlan::ServicePolicy::Type::ServiceChain::Output : public ydk::Entity
{
public:
Output();
~Output();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf name; //type: string
}; // Native::Interface::Vlan::ServicePolicy::Type::ServiceChain::Output
class Native::Interface::Vlan::Lisp : public ydk::Entity
{
public:
Lisp();
~Lisp();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf extended_subnet_mode; //type: empty
class Mobility; //type: Native::Interface::Vlan::Lisp::Mobility
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Lisp::Mobility> mobility;
}; // Native::Interface::Vlan::Lisp
class Native::Interface::Vlan::Lisp::Mobility : public ydk::Entity
{
public:
Mobility();
~Mobility();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class DynamicEid; //type: Native::Interface::Vlan::Lisp::Mobility::DynamicEid
class Discover; //type: Native::Interface::Vlan::Lisp::Mobility::Discover
class Liveness; //type: Native::Interface::Vlan::Lisp::Mobility::Liveness
ydk::YList dynamic_eid;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Lisp::Mobility::Discover> discover;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Lisp::Mobility::Liveness> liveness;
}; // Native::Interface::Vlan::Lisp::Mobility
class Native::Interface::Vlan::Lisp::Mobility::DynamicEid : public ydk::Entity
{
public:
DynamicEid();
~DynamicEid();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf dynamic_eid_name; //type: string
class NbrProxyReply; //type: Native::Interface::Vlan::Lisp::Mobility::DynamicEid::NbrProxyReply
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Lisp::Mobility::DynamicEid::NbrProxyReply> nbr_proxy_reply; // presence node
}; // Native::Interface::Vlan::Lisp::Mobility::DynamicEid
class Native::Interface::Vlan::Lisp::Mobility::DynamicEid::NbrProxyReply : public ydk::Entity
{
public:
NbrProxyReply();
~NbrProxyReply();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf requests; //type: uint8
}; // Native::Interface::Vlan::Lisp::Mobility::DynamicEid::NbrProxyReply
class Native::Interface::Vlan::Lisp::Mobility::Discover : public ydk::Entity
{
public:
Discover();
~Discover();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf arp; //type: boolean
}; // Native::Interface::Vlan::Lisp::Mobility::Discover
class Native::Interface::Vlan::Lisp::Mobility::Liveness : public ydk::Entity
{
public:
Liveness();
~Liveness();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf test; //type: boolean
ydk::YLeaf ttl; //type: uint8
}; // Native::Interface::Vlan::Lisp::Mobility::Liveness
class Native::Interface::Vlan::SpanningTree : public ydk::Entity
{
public:
SpanningTree();
~SpanningTree();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf bpdufilter; //type: Bpdufilter
ydk::YLeaf cost; //type: uint32
ydk::YLeaf guard; //type: Guard
ydk::YLeaf link_type; //type: LinkType
ydk::YLeaf port_priority; //type: uint8
class Bpduguard; //type: Native::Interface::Vlan::SpanningTree::Bpduguard
class Portfast; //type: Native::Interface::Vlan::SpanningTree::Portfast
class Vlan_; //type: Native::Interface::Vlan::SpanningTree::Vlan_
class Loopguard; //type: Native::Interface::Vlan::SpanningTree::Loopguard
class Mst; //type: Native::Interface::Vlan::SpanningTree::Mst
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::SpanningTree::Bpduguard> bpduguard;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::SpanningTree::Portfast> portfast; // presence node
ydk::YList vlan;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::SpanningTree::Loopguard> loopguard;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::SpanningTree::Mst> mst;
class Bpdufilter;
class Guard;
class LinkType;
}; // Native::Interface::Vlan::SpanningTree
class Native::Interface::Vlan::SpanningTree::Bpduguard : public ydk::Entity
{
public:
Bpduguard();
~Bpduguard();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf disable; //type: empty
ydk::YLeaf enable; //type: empty
}; // Native::Interface::Vlan::SpanningTree::Bpduguard
class Native::Interface::Vlan::SpanningTree::Portfast : public ydk::Entity
{
public:
Portfast();
~Portfast();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf disable; //type: empty
ydk::YLeaf trunk; //type: empty
ydk::YLeaf edge; //type: empty
}; // Native::Interface::Vlan::SpanningTree::Portfast
class Native::Interface::Vlan::SpanningTree::Vlan_ : public ydk::Entity
{
public:
Vlan_();
~Vlan_();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf vlan_ids; //type: string
ydk::YLeaf cost; //type: uint32
ydk::YLeaf port_priority; //type: uint16
}; // Native::Interface::Vlan::SpanningTree::Vlan_
class Native::Interface::Vlan::SpanningTree::Loopguard : public ydk::Entity
{
public:
Loopguard();
~Loopguard();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf default_; //type: empty
}; // Native::Interface::Vlan::SpanningTree::Loopguard
class Native::Interface::Vlan::SpanningTree::Mst : public ydk::Entity
{
public:
Mst();
~Mst();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf pre_standard; //type: empty
class MstInstance; //type: Native::Interface::Vlan::SpanningTree::Mst::MstInstance
ydk::YList mst_instance;
}; // Native::Interface::Vlan::SpanningTree::Mst
class Native::Interface::Vlan::SpanningTree::Mst::MstInstance : public ydk::Entity
{
public:
MstInstance();
~MstInstance();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf instance; //type: string
ydk::YLeaf cost; //type: uint32
ydk::YLeaf port_priority; //type: uint16
}; // Native::Interface::Vlan::SpanningTree::Mst::MstInstance
class Native::Interface::Vlan::Umbrella : public ydk::Entity
{
public:
Umbrella();
~Umbrella();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf out; //type: empty
ydk::YLeaf in; //type: string
}; // Native::Interface::Vlan::Umbrella
class Native::Interface::Vlan::Crypto : public ydk::Entity
{
public:
Crypto();
~Crypto();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Map; //type: Native::Interface::Vlan::Crypto::Map
class Ipsec; //type: Native::Interface::Vlan::Crypto::Ipsec
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Crypto::Map> map;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Crypto::Ipsec> ipsec;
}; // Native::Interface::Vlan::Crypto
class Native::Interface::Vlan::Crypto::Map : public ydk::Entity
{
public:
Map();
~Map();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf tag; //type: string
ydk::YLeaf redundancy; //type: string
ydk::YLeaf stateful; //type: empty
}; // Native::Interface::Vlan::Crypto::Map
class Native::Interface::Vlan::Crypto::Ipsec : public ydk::Entity
{
public:
Ipsec();
~Ipsec();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf df_bit; //type: DfBit
ydk::YLeaf fragmentation; //type: Fragmentation
class DfBit;
class Fragmentation;
}; // Native::Interface::Vlan::Crypto::Ipsec
class Native::Interface::Vlan::ZoneMember : public ydk::Entity
{
public:
ZoneMember();
~ZoneMember();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf security; //type: string
}; // Native::Interface::Vlan::ZoneMember
class Native::Interface::Vlan::Vrrp : public ydk::Entity
{
public:
Vrrp();
~Vrrp();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class VrrpGroup; //type: Native::Interface::Vlan::Vrrp::VrrpGroup
class VrrpGroupV2; //type: Native::Interface::Vlan::Vrrp::VrrpGroupV2
class Delay; //type: Native::Interface::Vlan::Vrrp::Delay
ydk::YList vrrp_group;
ydk::YList vrrp_group_v2;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Vrrp::Delay> delay;
}; // Native::Interface::Vlan::Vrrp
class Native::Interface::Vlan::Vrrp::VrrpGroup : public ydk::Entity
{
public:
VrrpGroup();
~VrrpGroup();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf group_id; //type: uint8
class AddressFamily; //type: Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily> address_family;
}; // Native::Interface::Vlan::Vrrp::VrrpGroup
class Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily : public ydk::Entity
{
public:
AddressFamily();
~AddressFamily();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Ipv4; //type: Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4
class Ipv6; //type: Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4> ipv4; // presence node
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6> ipv6; // presence node
}; // Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily
class Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4 : public ydk::Entity
{
public:
Ipv4();
~Ipv4();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf vrrpv2; //type: empty
ydk::YLeaf description; //type: string
ydk::YLeaf match_address; //type: empty
ydk::YLeaf priority; //type: uint8
ydk::YLeaf shutdown; //type: empty
class Address; //type: Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4::Address
class PreemptConfig; //type: Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4::PreemptConfig
class Preempt; //type: Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4::Preempt
class Timers; //type: Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4::Timers
class Track; //type: Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4::Track
class Vrrs; //type: Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4::Vrrs
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4::Address> address;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4::PreemptConfig> preempt_config;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4::Preempt> preempt;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4::Timers> timers;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4::Track> track;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4::Vrrs> vrrs;
}; // Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4
class Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4::Address : public ydk::Entity
{
public:
Address();
~Address();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Primary; //type: Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4::Address::Primary
class Secondary; //type: Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4::Address::Secondary
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4::Address::Primary> primary;
ydk::YList secondary;
}; // Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4::Address
class Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4::Address::Primary : public ydk::Entity
{
public:
Primary();
~Primary();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf address; //type: string
ydk::YLeaf primary; //type: empty
}; // Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4::Address::Primary
class Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4::Address::Secondary : public ydk::Entity
{
public:
Secondary();
~Secondary();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf address; //type: string
ydk::YLeaf secondary; //type: empty
}; // Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4::Address::Secondary
class Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4::PreemptConfig : public ydk::Entity
{
public:
PreemptConfig();
~PreemptConfig();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf preempt; //type: boolean
}; // Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4::PreemptConfig
class Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4::Preempt : public ydk::Entity
{
public:
Preempt();
~Preempt();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Delay; //type: Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4::Preempt::Delay
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4::Preempt::Delay> delay;
}; // Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4::Preempt
class Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4::Preempt::Delay : public ydk::Entity
{
public:
Delay();
~Delay();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf minimum; //type: uint16
}; // Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4::Preempt::Delay
class Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4::Timers : public ydk::Entity
{
public:
Timers();
~Timers();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf advertise; //type: uint16
}; // Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4::Timers
class Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4::Track : public ydk::Entity
{
public:
Track();
~Track();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Event; //type: Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4::Track::Event
ydk::YList event;
}; // Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4::Track
class Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4::Track::Event : public ydk::Entity
{
public:
Event();
~Event();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf object_id; //type: uint16
ydk::YLeaf decrement; //type: uint8
ydk::YLeaf shutdown; //type: empty
}; // Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4::Track::Event
class Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4::Vrrs : public ydk::Entity
{
public:
Vrrs();
~Vrrs();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf leader; //type: string
}; // Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv4::Vrrs
class Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6 : public ydk::Entity
{
public:
Ipv6();
~Ipv6();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf description; //type: string
ydk::YLeaf match_address; //type: empty
ydk::YLeaf priority; //type: uint8
ydk::YLeaf shutdown; //type: empty
class Address; //type: Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6::Address
class PreemptConfig; //type: Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6::PreemptConfig
class Preempt; //type: Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6::Preempt
class Timers; //type: Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6::Timers
class Track; //type: Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6::Track
class Vrrs; //type: Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6::Vrrs
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6::Address> address;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6::PreemptConfig> preempt_config;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6::Preempt> preempt;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6::Timers> timers;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6::Track> track;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6::Vrrs> vrrs;
}; // Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6
class Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6::Address : public ydk::Entity
{
public:
Address();
~Address();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Primary; //type: Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6::Address::Primary
class Ipv6Prefix; //type: Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6::Address::Ipv6Prefix
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6::Address::Primary> primary;
ydk::YList ipv6_prefix;
}; // Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6::Address
class Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6::Address::Primary : public ydk::Entity
{
public:
Primary();
~Primary();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf ipv6_link_local; //type: string
ydk::YLeaf primary; //type: empty
}; // Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6::Address::Primary
class Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6::Address::Ipv6Prefix : public ydk::Entity
{
public:
Ipv6Prefix();
~Ipv6Prefix();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf prefix; //type: string
}; // Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6::Address::Ipv6Prefix
class Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6::PreemptConfig : public ydk::Entity
{
public:
PreemptConfig();
~PreemptConfig();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf preempt; //type: boolean
}; // Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6::PreemptConfig
class Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6::Preempt : public ydk::Entity
{
public:
Preempt();
~Preempt();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Delay; //type: Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6::Preempt::Delay
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6::Preempt::Delay> delay;
}; // Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6::Preempt
class Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6::Preempt::Delay : public ydk::Entity
{
public:
Delay();
~Delay();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf minimum; //type: uint16
}; // Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6::Preempt::Delay
class Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6::Timers : public ydk::Entity
{
public:
Timers();
~Timers();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf advertise; //type: uint16
}; // Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6::Timers
class Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6::Track : public ydk::Entity
{
public:
Track();
~Track();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Event; //type: Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6::Track::Event
ydk::YList event;
}; // Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6::Track
class Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6::Track::Event : public ydk::Entity
{
public:
Event();
~Event();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf object_id; //type: uint16
ydk::YLeaf decrement; //type: uint8
ydk::YLeaf shutdown; //type: empty
}; // Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6::Track::Event
class Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6::Vrrs : public ydk::Entity
{
public:
Vrrs();
~Vrrs();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf leader; //type: string
}; // Native::Interface::Vlan::Vrrp::VrrpGroup::AddressFamily::Ipv6::Vrrs
class Native::Interface::Vlan::Vrrp::VrrpGroupV2 : public ydk::Entity
{
public:
VrrpGroupV2();
~VrrpGroupV2();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf group_id; //type: uint8
ydk::YLeaf description; //type: string
ydk::YLeaf name; //type: string
ydk::YLeaf priority; //type: uint8
ydk::YLeaf shutdown; //type: empty
class Authentication; //type: Native::Interface::Vlan::Vrrp::VrrpGroupV2::Authentication
class Ip; //type: Native::Interface::Vlan::Vrrp::VrrpGroupV2::Ip
class PreemptConfig; //type: Native::Interface::Vlan::Vrrp::VrrpGroupV2::PreemptConfig
class Preempt; //type: Native::Interface::Vlan::Vrrp::VrrpGroupV2::Preempt
class Timers; //type: Native::Interface::Vlan::Vrrp::VrrpGroupV2::Timers
class Track; //type: Native::Interface::Vlan::Vrrp::VrrpGroupV2::Track
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Vrrp::VrrpGroupV2::Authentication> authentication;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Vrrp::VrrpGroupV2::Ip> ip;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Vrrp::VrrpGroupV2::PreemptConfig> preempt_config;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Vrrp::VrrpGroupV2::Preempt> preempt;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Vrrp::VrrpGroupV2::Timers> timers;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Vrrp::VrrpGroupV2::Track> track;
}; // Native::Interface::Vlan::Vrrp::VrrpGroupV2
class Native::Interface::Vlan::Vrrp::VrrpGroupV2::Authentication : public ydk::Entity
{
public:
Authentication();
~Authentication();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf text; //type: string
}; // Native::Interface::Vlan::Vrrp::VrrpGroupV2::Authentication
class Native::Interface::Vlan::Vrrp::VrrpGroupV2::Ip : public ydk::Entity
{
public:
Ip();
~Ip();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Primary; //type: Native::Interface::Vlan::Vrrp::VrrpGroupV2::Ip::Primary
class Secondary; //type: Native::Interface::Vlan::Vrrp::VrrpGroupV2::Ip::Secondary
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Vrrp::VrrpGroupV2::Ip::Primary> primary;
ydk::YList secondary;
}; // Native::Interface::Vlan::Vrrp::VrrpGroupV2::Ip
class Native::Interface::Vlan::Vrrp::VrrpGroupV2::Ip::Primary : public ydk::Entity
{
public:
Primary();
~Primary();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf address; //type: string
}; // Native::Interface::Vlan::Vrrp::VrrpGroupV2::Ip::Primary
class Native::Interface::Vlan::Vrrp::VrrpGroupV2::Ip::Secondary : public ydk::Entity
{
public:
Secondary();
~Secondary();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf address; //type: string
ydk::YLeaf secondary; //type: empty
}; // Native::Interface::Vlan::Vrrp::VrrpGroupV2::Ip::Secondary
class Native::Interface::Vlan::Vrrp::VrrpGroupV2::PreemptConfig : public ydk::Entity
{
public:
PreemptConfig();
~PreemptConfig();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf preempt; //type: boolean
}; // Native::Interface::Vlan::Vrrp::VrrpGroupV2::PreemptConfig
class Native::Interface::Vlan::Vrrp::VrrpGroupV2::Preempt : public ydk::Entity
{
public:
Preempt();
~Preempt();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Delay; //type: Native::Interface::Vlan::Vrrp::VrrpGroupV2::Preempt::Delay
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Vrrp::VrrpGroupV2::Preempt::Delay> delay;
}; // Native::Interface::Vlan::Vrrp::VrrpGroupV2::Preempt
class Native::Interface::Vlan::Vrrp::VrrpGroupV2::Preempt::Delay : public ydk::Entity
{
public:
Delay();
~Delay();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf minimum; //type: uint16
}; // Native::Interface::Vlan::Vrrp::VrrpGroupV2::Preempt::Delay
class Native::Interface::Vlan::Vrrp::VrrpGroupV2::Timers : public ydk::Entity
{
public:
Timers();
~Timers();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf learn; //type: empty
class Advertise; //type: Native::Interface::Vlan::Vrrp::VrrpGroupV2::Timers::Advertise
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_native::Native::Interface::Vlan::Vrrp::VrrpGroupV2::Timers::Advertise> advertise;
}; // Native::Interface::Vlan::Vrrp::VrrpGroupV2::Timers
class Native::Interface::Vlan::Pppoe::Enable::Group : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf global;
static int get_enum_value(const std::string & name) {
if (name == "global") return 0;
return -1;
}
};
class Native::Interface::Vlan::Service::Instance::Encapsulation::Dot1ad::Id : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf any;
static int get_enum_value(const std::string & name) {
if (name == "any") return 0;
return -1;
}
};
class Native::Interface::Vlan::Service::Instance::Encapsulation::Dot1ad::Dot1q : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf any;
static int get_enum_value(const std::string & name) {
if (name == "any") return 0;
return -1;
}
};
class Native::Interface::Vlan::Service::Instance::Encapsulation::Dot1ad::Etype : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf ipv4;
static const ydk::Enum::YLeaf ipv6;
static const ydk::Enum::YLeaf pppoe_all;
static const ydk::Enum::YLeaf pppoe_discovery;
static const ydk::Enum::YLeaf pppoe_session;
static int get_enum_value(const std::string & name) {
if (name == "ipv4") return 0;
if (name == "ipv6") return 1;
if (name == "pppoe-all") return 2;
if (name == "pppoe-discovery") return 3;
if (name == "pppoe-session") return 4;
return -1;
}
};
class Native::Interface::Vlan::Service::Instance::Encapsulation::Dot1q::Id : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf any;
static int get_enum_value(const std::string & name) {
if (name == "any") return 0;
return -1;
}
};
class Native::Interface::Vlan::Service::Instance::Encapsulation::Dot1q::SecondDot1q : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf any;
static int get_enum_value(const std::string & name) {
if (name == "any") return 0;
return -1;
}
};
class Native::Interface::Vlan::Service::Instance::Encapsulation::Dot1q::Etype : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf ipv4;
static const ydk::Enum::YLeaf ipv6;
static const ydk::Enum::YLeaf pppoe_all;
static const ydk::Enum::YLeaf pppoe_discovery;
static const ydk::Enum::YLeaf pppoe_session;
static int get_enum_value(const std::string & name) {
if (name == "ipv4") return 0;
if (name == "ipv6") return 1;
if (name == "pppoe-all") return 2;
if (name == "pppoe-discovery") return 3;
if (name == "pppoe-session") return 4;
return -1;
}
};
class Native::Interface::Vlan::Service::Instance::Encapsulation::Dot1q::VlanType : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf Y_0x88A8;
static const ydk::Enum::YLeaf Y_0x9100;
static const ydk::Enum::YLeaf Y_0x9200;
static int get_enum_value(const std::string & name) {
if (name == "0x88A8") return 0;
if (name == "0x9100") return 1;
if (name == "0x9200") return 2;
return -1;
}
};
class Native::Interface::Vlan::Service::Instance::Encapsulation::PriorityTagged::Etype : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf ipv4;
static const ydk::Enum::YLeaf ipv6;
static const ydk::Enum::YLeaf pppoe_all;
static const ydk::Enum::YLeaf pppoe_discovery;
static const ydk::Enum::YLeaf pppoe_session;
static int get_enum_value(const std::string & name) {
if (name == "ipv4") return 0;
if (name == "ipv6") return 1;
if (name == "pppoe-all") return 2;
if (name == "pppoe-discovery") return 3;
if (name == "pppoe-session") return 4;
return -1;
}
};
class Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag::Pop::Way : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf Y_1;
static const ydk::Enum::YLeaf Y_2;
static int get_enum_value(const std::string & name) {
if (name == "1") return 0;
if (name == "2") return 1;
return -1;
}
};
class Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag::Pop::Mode : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf symmetric;
static int get_enum_value(const std::string & name) {
if (name == "symmetric") return 0;
return -1;
}
};
class Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag::Push::Mode : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf symmetric;
static int get_enum_value(const std::string & name) {
if (name == "symmetric") return 0;
return -1;
}
};
class Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag::Translate::T1To1::Mode : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf symmetric;
static int get_enum_value(const std::string & name) {
if (name == "symmetric") return 0;
return -1;
}
};
class Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag::Translate::T1To2::Mode : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf symmetric;
static int get_enum_value(const std::string & name) {
if (name == "symmetric") return 0;
return -1;
}
};
class Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag::Translate::T2To1::Mode : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf symmetric;
static int get_enum_value(const std::string & name) {
if (name == "symmetric") return 0;
return -1;
}
};
class Native::Interface::Vlan::Service::Instance::Rewrite::Ingress::Tag::Translate::T2To2::Mode : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf symmetric;
static int get_enum_value(const std::string & name) {
if (name == "symmetric") return 0;
return -1;
}
};
class Native::Interface::Vlan::Service::Instance::Mac::Security::Violation : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf protect;
static const ydk::Enum::YLeaf restrict;
static int get_enum_value(const std::string & name) {
if (name == "protect") return 0;
if (name == "restrict") return 1;
return -1;
}
};
class Native::Interface::Vlan::Service::Instance::L2protocol::Discard::Protocol : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf R4;
static const ydk::Enum::YLeaf R5;
static const ydk::Enum::YLeaf R6;
static const ydk::Enum::YLeaf R8;
static const ydk::Enum::YLeaf R9;
static const ydk::Enum::YLeaf RA;
static const ydk::Enum::YLeaf RB;
static const ydk::Enum::YLeaf RC;
static const ydk::Enum::YLeaf RD;
static const ydk::Enum::YLeaf RF;
static const ydk::Enum::YLeaf cdp;
static const ydk::Enum::YLeaf dtp;
static const ydk::Enum::YLeaf elmi;
static const ydk::Enum::YLeaf esmc;
static const ydk::Enum::YLeaf lacp;
static const ydk::Enum::YLeaf lldp;
static const ydk::Enum::YLeaf loam;
static const ydk::Enum::YLeaf pagp;
static const ydk::Enum::YLeaf ptppd;
static const ydk::Enum::YLeaf stp;
static const ydk::Enum::YLeaf udld;
static const ydk::Enum::YLeaf vtp;
static int get_enum_value(const std::string & name) {
if (name == "R4") return 0;
if (name == "R5") return 1;
if (name == "R6") return 2;
if (name == "R8") return 3;
if (name == "R9") return 4;
if (name == "RA") return 5;
if (name == "RB") return 6;
if (name == "RC") return 7;
if (name == "RD") return 8;
if (name == "RF") return 9;
if (name == "cdp") return 10;
if (name == "dtp") return 11;
if (name == "elmi") return 12;
if (name == "esmc") return 13;
if (name == "lacp") return 14;
if (name == "lldp") return 15;
if (name == "loam") return 16;
if (name == "pagp") return 17;
if (name == "ptppd") return 18;
if (name == "stp") return 19;
if (name == "udld") return 20;
if (name == "vtp") return 21;
return -1;
}
};
class Native::Interface::Vlan::Service::Instance::L2protocol::Peer::Protocol : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf R4;
static const ydk::Enum::YLeaf R5;
static const ydk::Enum::YLeaf R6;
static const ydk::Enum::YLeaf R8;
static const ydk::Enum::YLeaf R9;
static const ydk::Enum::YLeaf RA;
static const ydk::Enum::YLeaf RB;
static const ydk::Enum::YLeaf RC;
static const ydk::Enum::YLeaf RD;
static const ydk::Enum::YLeaf RF;
static const ydk::Enum::YLeaf cdp;
static const ydk::Enum::YLeaf dtp;
static const ydk::Enum::YLeaf elmi;
static const ydk::Enum::YLeaf esmc;
static const ydk::Enum::YLeaf lacp;
static const ydk::Enum::YLeaf lldp;
static const ydk::Enum::YLeaf loam;
static const ydk::Enum::YLeaf pagp;
static const ydk::Enum::YLeaf ptppd;
static const ydk::Enum::YLeaf stp;
static const ydk::Enum::YLeaf udld;
static const ydk::Enum::YLeaf vtp;
static int get_enum_value(const std::string & name) {
if (name == "R4") return 0;
if (name == "R5") return 1;
if (name == "R6") return 2;
if (name == "R8") return 3;
if (name == "R9") return 4;
if (name == "RA") return 5;
if (name == "RB") return 6;
if (name == "RC") return 7;
if (name == "RD") return 8;
if (name == "RF") return 9;
if (name == "cdp") return 10;
if (name == "dtp") return 11;
if (name == "elmi") return 12;
if (name == "esmc") return 13;
if (name == "lacp") return 14;
if (name == "lldp") return 15;
if (name == "loam") return 16;
if (name == "pagp") return 17;
if (name == "ptppd") return 18;
if (name == "stp") return 19;
if (name == "udld") return 20;
if (name == "vtp") return 21;
return -1;
}
};
class Native::Interface::Vlan::Service::Instance::L2protocol::Forward::Protocol : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf R4;
static const ydk::Enum::YLeaf R5;
static const ydk::Enum::YLeaf R6;
static const ydk::Enum::YLeaf R8;
static const ydk::Enum::YLeaf R9;
static const ydk::Enum::YLeaf RA;
static const ydk::Enum::YLeaf RB;
static const ydk::Enum::YLeaf RC;
static const ydk::Enum::YLeaf RD;
static const ydk::Enum::YLeaf RF;
static const ydk::Enum::YLeaf cdp;
static const ydk::Enum::YLeaf dtp;
static const ydk::Enum::YLeaf elmi;
static const ydk::Enum::YLeaf esmc;
static const ydk::Enum::YLeaf lacp;
static const ydk::Enum::YLeaf lldp;
static const ydk::Enum::YLeaf loam;
static const ydk::Enum::YLeaf pagp;
static const ydk::Enum::YLeaf ptppd;
static const ydk::Enum::YLeaf stp;
static const ydk::Enum::YLeaf udld;
static const ydk::Enum::YLeaf vtp;
static int get_enum_value(const std::string & name) {
if (name == "R4") return 0;
if (name == "R5") return 1;
if (name == "R6") return 2;
if (name == "R8") return 3;
if (name == "R9") return 4;
if (name == "RA") return 5;
if (name == "RB") return 6;
if (name == "RC") return 7;
if (name == "RD") return 8;
if (name == "RF") return 9;
if (name == "cdp") return 10;
if (name == "dtp") return 11;
if (name == "elmi") return 12;
if (name == "esmc") return 13;
if (name == "lacp") return 14;
if (name == "lldp") return 15;
if (name == "loam") return 16;
if (name == "pagp") return 17;
if (name == "ptppd") return 18;
if (name == "stp") return 19;
if (name == "udld") return 20;
if (name == "vtp") return 21;
return -1;
}
};
class Native::Interface::Vlan::Service::Instance::L2protocol::Tunnel::Protocol : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf R4;
static const ydk::Enum::YLeaf R5;
static const ydk::Enum::YLeaf R6;
static const ydk::Enum::YLeaf R8;
static const ydk::Enum::YLeaf R9;
static const ydk::Enum::YLeaf RA;
static const ydk::Enum::YLeaf RB;
static const ydk::Enum::YLeaf RC;
static const ydk::Enum::YLeaf RD;
static const ydk::Enum::YLeaf RF;
static const ydk::Enum::YLeaf cdp;
static const ydk::Enum::YLeaf dtp;
static const ydk::Enum::YLeaf elmi;
static const ydk::Enum::YLeaf esmc;
static const ydk::Enum::YLeaf lacp;
static const ydk::Enum::YLeaf lldp;
static const ydk::Enum::YLeaf loam;
static const ydk::Enum::YLeaf pagp;
static const ydk::Enum::YLeaf ptppd;
static const ydk::Enum::YLeaf stp;
static const ydk::Enum::YLeaf udld;
static const ydk::Enum::YLeaf vtp;
static int get_enum_value(const std::string & name) {
if (name == "R4") return 0;
if (name == "R5") return 1;
if (name == "R6") return 2;
if (name == "R8") return 3;
if (name == "R9") return 4;
if (name == "RA") return 5;
if (name == "RB") return 6;
if (name == "RC") return 7;
if (name == "RD") return 8;
if (name == "RF") return 9;
if (name == "cdp") return 10;
if (name == "dtp") return 11;
if (name == "elmi") return 12;
if (name == "esmc") return 13;
if (name == "lacp") return 14;
if (name == "lldp") return 15;
if (name == "loam") return 16;
if (name == "pagp") return 17;
if (name == "ptppd") return 18;
if (name == "stp") return 19;
if (name == "udld") return 20;
if (name == "vtp") return 21;
return -1;
}
};
class Native::Interface::Vlan::ServicePolicy::Type::PerformanceMonitor::Direction : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf input;
static const ydk::Enum::YLeaf output;
static int get_enum_value(const std::string & name) {
if (name == "input") return 0;
if (name == "output") return 1;
return -1;
}
};
class Native::Interface::Vlan::SpanningTree::Bpdufilter : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf disable;
static const ydk::Enum::YLeaf enable;
static int get_enum_value(const std::string & name) {
if (name == "disable") return 0;
if (name == "enable") return 1;
return -1;
}
};
class Native::Interface::Vlan::SpanningTree::Guard : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf loop;
static const ydk::Enum::YLeaf none;
static const ydk::Enum::YLeaf root;
static int get_enum_value(const std::string & name) {
if (name == "loop") return 0;
if (name == "none") return 1;
if (name == "root") return 2;
return -1;
}
};
class Native::Interface::Vlan::SpanningTree::LinkType : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf point_to_point;
static const ydk::Enum::YLeaf shared;
static int get_enum_value(const std::string & name) {
if (name == "point-to-point") return 0;
if (name == "shared") return 1;
return -1;
}
};
class Native::Interface::Vlan::Crypto::Ipsec::DfBit : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf clear;
static const ydk::Enum::YLeaf copy;
static const ydk::Enum::YLeaf set;
static int get_enum_value(const std::string & name) {
if (name == "clear") return 0;
if (name == "copy") return 1;
if (name == "set") return 2;
return -1;
}
};
class Native::Interface::Vlan::Crypto::Ipsec::Fragmentation : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf after_encryption;
static const ydk::Enum::YLeaf before_encryption;
static int get_enum_value(const std::string & name) {
if (name == "after-encryption") return 0;
if (name == "before-encryption") return 1;
return -1;
}
};
}
}
#endif /* _CISCO_IOS_XE_NATIVE_97_ */
| 50.526637 | 167 | 0.680032 | CiscoDevNet |
066beba3c0647677cff0bddc2d0c969a82cda3f3 | 1,054 | cpp | C++ | FlyEngine/Source/FlyVariable.cpp | rogerta97/FlyEngine | 33abd70c5b4307cd552e2b6269b401772b4327ba | [
"MIT"
] | null | null | null | FlyEngine/Source/FlyVariable.cpp | rogerta97/FlyEngine | 33abd70c5b4307cd552e2b6269b401772b4327ba | [
"MIT"
] | null | null | null | FlyEngine/Source/FlyVariable.cpp | rogerta97/FlyEngine | 33abd70c5b4307cd552e2b6269b401772b4327ba | [
"MIT"
] | null | null | null | #include "FlyVariable.h"
#include "RandomNumberGenerator.h"
#include "mmgr.h"
FlyVariable::FlyVariable()
{
}
FlyVariable::~FlyVariable()
{
}
void FlyVariable::CleanUp()
{
}
void FlyVariable::SetDefault()
{
name = "";
varType = Var_Integer;
varIntegerValue = 0;
varToogleValue = true;
uniqueID = RandomNumberGenerator::getInstance()->GenerateUID();
}
void FlyVariable::Serialize(JSON_Object* jsonObject, std::string _baseObjectStr)
{
std::string saveString = _baseObjectStr + "VariableType";
json_object_dotset_number(jsonObject, saveString.c_str(), varType);
saveString = _baseObjectStr + "VariableName";
json_object_dotset_string(jsonObject, saveString.c_str(), name.c_str());
saveString = _baseObjectStr + "IntegerValue";
json_object_dotset_number(jsonObject, saveString.c_str(), varIntegerValue);
saveString = _baseObjectStr + "ToggleValue";
json_object_dotset_boolean(jsonObject, saveString.c_str(), varToogleValue);
saveString = _baseObjectStr + "UID";
json_object_dotset_number(jsonObject, saveString.c_str(), uniqueID);
}
| 23.954545 | 80 | 0.767552 | rogerta97 |
066f9426ba98e9c4f33791fd877a1ed30b71d398 | 3,010 | cpp | C++ | src/MexUtils.cpp | markjolah/MexIface | 42118754e7d4175d452fa7cdbd9335561ff69900 | [
"Apache-2.0"
] | 4 | 2019-03-04T08:28:50.000Z | 2021-09-30T16:50:51.000Z | src/MexUtils.cpp | markjolah/MexIFace | 42118754e7d4175d452fa7cdbd9335561ff69900 | [
"Apache-2.0"
] | null | null | null | src/MexUtils.cpp | markjolah/MexIFace | 42118754e7d4175d452fa7cdbd9335561ff69900 | [
"Apache-2.0"
] | null | null | null | /** @file MexUtils.cpp
* @author Mark J. Olah (mjo\@cs.unm DOT edu)
* @date 2013-2017
* @copyright Licensed under the Apache License, Version 2.0. See LICENSE file.
* @brief Helper functions for working with Matlab mxArrays and mxClassIDs
*/
#include <memory>
#include <cxxabi.h>
#include "MexIFace/MexUtils.h"
#include "MexIFace/explore.h"
namespace mexiface {
const char* get_mx_class_name(mxClassID id)
{
switch (id) {
case mxINT8_CLASS: return "int8";
case mxUINT8_CLASS: return "uint8";
case mxINT16_CLASS: return "int16";
case mxUINT16_CLASS:return "uint16";
case mxINT32_CLASS: return "int32";
case mxUINT32_CLASS: return "uint32";
case mxINT64_CLASS: return "int64";
case mxUINT64_CLASS:return "uint64";
case mxSINGLE_CLASS: return "single";
case mxDOUBLE_CLASS:return "double";
case mxLOGICAL_CLASS: return "logical";
case mxCHAR_CLASS: return "char";
case mxSTRUCT_CLASS: return "struct";
case mxCELL_CLASS: return "cell";
case mxUNKNOWN_CLASS: return "unknownclass";
default: return "mysteryclass???";
}
}
/** Templates for get_mx_class
* Can't use uint64_t as sometimes it may be long or long long.
* best to set mxClassID for long and long long individually
*/
template<> mxClassID get_mx_class<double>() {return mxDOUBLE_CLASS;}
template<> mxClassID get_mx_class<float>() {return mxSINGLE_CLASS;}
template<> mxClassID get_mx_class<int8_t>() {return mxINT8_CLASS;}
template<> mxClassID get_mx_class<int16_t>() {return mxINT16_CLASS;}
template<> mxClassID get_mx_class<int32_t>() {return mxINT32_CLASS;}
template<> mxClassID get_mx_class<long>() {return mxINT64_CLASS;}
template<> mxClassID get_mx_class<long long>() {return mxINT64_CLASS;}
template<> mxClassID get_mx_class<uint8_t>() {return mxUINT8_CLASS;}
template<> mxClassID get_mx_class<uint16_t>() {return mxUINT16_CLASS;}
template<> mxClassID get_mx_class<uint32_t>() {return mxUINT32_CLASS;}
template<> mxClassID get_mx_class<unsigned long long>() {return mxUINT64_CLASS;}
template<> mxClassID get_mx_class<unsigned long>() {return mxUINT64_CLASS;}
/* TODO Finish this method to replace matlab .c code dependencies */
// void get_characteristics(const mxArray *arr)
// {
// auto ndims = mxGetNumberOfDimensions(arr);
// auto size = mxGetDimensions(arr);
// auto name = mxGetClassName(arr);
// auto id = mxGetClassID(arr);
//
// }
void exploreMexArgs(int nargs, const mxArray *args[] )
{
mexPrintf("#Args: %d\n",nargs);
for (int i=0; i<nargs; i++) {
mexPrintf("\n\n");
mexPrintf("arg[%i]: ",i);
explore::get_characteristics(args[i]);
explore::analyze_class(args[i]);
}
}
std::string demangle(const char* name)
{
int status = -4;
std::unique_ptr<char, void(*)(void*)> res{abi::__cxa_demangle(name, NULL, NULL, &status),std::free};
return (status==0) ? res.get() : name;
}
} /* namespace mexiface */
| 35.411765 | 104 | 0.690033 | markjolah |
067009b97de9b3c912abfa77d7276ea3f9ff39be | 34,300 | cpp | C++ | RC.cpp | eanmcgilvery/Embedded-Sys-Visualizer | 412b23f0f90f5e9ee68d139f73f15df48c88d5a4 | [
"MIT"
] | null | null | null | RC.cpp | eanmcgilvery/Embedded-Sys-Visualizer | 412b23f0f90f5e9ee68d139f73f15df48c88d5a4 | [
"MIT"
] | null | null | null | RC.cpp | eanmcgilvery/Embedded-Sys-Visualizer | 412b23f0f90f5e9ee68d139f73f15df48c88d5a4 | [
"MIT"
] | null | null | null | /*MIT License
Copyright (c) 2021 Ean McGilvery, Janeen Yamak
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/*************************************************************************************************
* File: RC.cpp
* Description:
* This file contains all the major compenents of the RC Graphicial Library and the RC Hardware Component
* Requires C++ 14 or later (Smart Pointers)
*
**************************************************************************************************/
#ifndef RC_CPP
#define RC_CPP
#include "RC.hpp"
#include "cpputils/graphics/image.h"
#include "cpputils/graphics/image_event.h"
#include "orientation.h"
#include <memory>
#include <fstream> //std::ofstream
#include <curl/curl.h>
#include <sys/stat.h>
#include <math.h>
/*====================================================================================================================*/
/* MUTATORS */
/*====================================================================================================================*/
/***************************************************************************
* Function: SetRC
* Description:
* This function shall decide whether the user would like to use the Graphical Interface or the Hardware Component
* Parameters:
* bool usingRCGraphics : 'true' enables the user to work with the Graphical Interface
* 'false' enables the user to work with the Hardware Component
* Return:
* None
***************************************************************************/
void RC::SetRC(bool usingRCGraphics){ UsingRCGraphics_ = usingRCGraphics; }
/***************************************************************************
* Function: SetSpeed
* Description:
* This Function sets the speed of the RC Car for the Graphical Interface
* Parameters:
* int speed : the speed of the car in ms
* Return:
* None
***************************************************************************/
void RC::SetSpeed(int speed){ Speed_ = speed; }
/*====================================================================================================================*/
/* END OF MUTATORS */
/*====================================================================================================================*/
/*====================================================================================================================*/
/* ACCESSORS */
/*====================================================================================================================*/
/***************************************************************************
* Function: RCWorldImage
* Description:
* Returns the underlying image object
* Parameters:
* None
* Return:
* Image: the underlying image object
***************************************************************************/
graphics::Image& RC::RCWorldImage(){ return RCWorldImage_; }
/***************************************************************************
* Function: XDim
* Description:
* Returns the X Dimention of the graphical interface
* Parameters:
* None
* Return:
* int: The X Dimention of the graphical interface
***************************************************************************/
int RC::XDim(){ return XDim_; }
/***************************************************************************
* Function: YDim
* Description:
* Returns the Y Dimention of the graphical interface
* Parameters:
* None
* Return:
* int: The Y Dimention of the graphical interface
***************************************************************************/
int RC::YDim(){ return YDim_; }
/***************************************************************************
* Function: UsingGraphics
* Description:
* Returns true/false depending on whether the use of the graphical interface has been enabled or not
* Parameters:
* None
* Return:
* bool: 'true': the graphical interface is enabled
* 'false': the RC Hardware compenent is enabled
***************************************************************************/
bool RC::UsingGraphics(){ return UsingRCGraphics_; }
/***************************************************************************
* Function: Speed
* Description:
* Returns the speed in ms
* Parameters:
* None
* Return:
* int: the speed in ms
***************************************************************************/
int RC::Speed(){ return Speed_; }
/***************************************************************************
* Function: positions
* Description:
* Returns the current x and y value of the car
* Parameters:
* None
* Return:
* DirectionAndOrientation: is an object that contains the x and y value of the RC car's position
***************************************************************************/
DirectionAndOrientation RC::positions(){ return position_; }
/***************************************************************************
* Function: pxPerCell
* Description:
* Returns the number of pixels per cell
* Parameters:
* None
* Return:
* int: the number of pixels per cell
***************************************************************************/
int RC::pxPerCell(){ return pxPerCell_; }
/*====================================================================================================================*/
/* END OF ACCESSORS */
/*====================================================================================================================*/
/*====================================================================================================================*/
/* HELPER FUNCTIONS (NOT TO BE EXPLICITLY CALLED) */
/*====================================================================================================================*/
/***************************************************************************
* Function: DrawRCCar
* Description:
* Passes the X and Y px position that represent the middle of a cell
* Parameters:
* None
* Return:
* None
***************************************************************************/
void RC::DrawRCCar(){
if(UsingRCGraphics_){
DrawRCCar(position_.x_ * pxPerCell_ + pxPerCell_ / 2,
position_.y_* pxPerCell_ + pxPerCell_ / 2);
}
}
/***************************************************************************
* Function: ParseWorldFileError
* Description:
* This Function will display an error if the syntax of the file is not correct
* Parameters:
* error_text: is a description of what caused this function to be prompted
* line_number: specifies which line number caused the syntax error in the 'file' object
* Return:
* None
***************************************************************************/
void RC::ParseWorldFileError(std::string error_text, int line_number) {
if (line_number > 0) {
error_text += " (line " + std::to_string(line_number) + ")";
}
std::cout << error_text << std::endl << std::flush;
throw error_text;
}
/***************************************************************************
* Function: ParsePosition
* Description:
* Grabs the X and Y position of an object
* Parameters:
* fstream file: is a file object that is being read
* int line_number: specifies which line you are currently reading
* Return:
* DirectionAndOrientation: returns the coordinates of the object you read from the file
***************************************************************************/
DirectionAndOrientation RC::ParsePosition(std::fstream& file,int line_number) {
char open_paren, comma, closed_paren;
int x, y;
if (!(file >> open_paren >> x >> comma >> y >> closed_paren)) {
ParseWorldFileError("Error reading position", line_number);
}
CheckParsePosition(open_paren, comma, closed_paren, line_number);
DirectionAndOrientation result;
// Convert y in the file to y on-screen. In the file, (1, 1) is the
// bottom left corner.
// In car coordinates, that's (0, YDim_ - 1).
result.y_ = YDim_ - y;
result.x_ = x - 1;
return result;
}
/***************************************************************************
* Function: ParsePositionAndOrientation
* Description:
* Reads the Direction the RC Car
* Parameters:
* fstream file: is a file object that is being read
* int line_number: specifies which line you are currently reading
* Return:
* DirectionAndOrientation: returns the orientation of the RC Car
***************************************************************************/
DirectionAndOrientation RC::ParsePositionAndOrientation(std::fstream& file, int line_number) {
DirectionAndOrientation result = ParsePosition(file, line_number);
std::string direction;
if (!(file >> direction)) {
ParseWorldFileError("Error reading orientation", line_number);
}
// Ensure the first character is lower cased.
direction[0] = tolower(direction[0]);
if (direction == "north") {
result.orientation_ = Direction::North;
} else if (direction == "east") {
result.orientation_ = Direction::East;
} else if (direction == "south") {
result.orientation_ = Direction::South;
} else if (direction == "west") {
result.orientation_ = Direction::West;
} else {
ParseWorldFileError("Unknown orientation " + direction, line_number);
}
return result;
}
/***************************************************************************
* Function: CheckParsePosition
* Description:
* Checks to see if the following Syntax "(,)" is valid in the file
* Parameters:
* char open_paren: '('
* char comm: ','
* char closed_paren: ')'
* int line_number: is the line number the pareser is currently at
* Return:
* None
***************************************************************************/
void RC::CheckParsePosition(char open_paren, char comma, char closed_paren,int line_number) {
if (open_paren != '(') {
ParseWorldFileError("Invalid syntax: expected open parenthesis but found " +
std::string(1, open_paren),
line_number);
}
if (comma != ',') {
ParseWorldFileError(
"Invalid syntax: expected a comma but found " + std::string(1, comma),
line_number);
}
if (closed_paren != ')') {
ParseWorldFileError(
"Invalid syntax: expected closed parenthesis but found " +
std::string(1, closed_paren),
line_number);
}
}
/*====================================================================================================================*/
/* END OF HELPER FUNCTIONS */
/*====================================================================================================================*/
/*====================================================================================================================*/
/* OTHER FUNCTIONS USED TO MANIPULATE THE IMAGE */
/*====================================================================================================================*/
/***************************************************************************
* Function: PopulateBoard
* Description:
* Creates the graphical interface a user may be interacting with. It may contain rocks, roads if it was initialized.
* By Default the grpahical interface will contain a blank grid with the RC Car image starting at the Top Left of the grid.
* Parameters:
* None
* Return:
* None
***************************************************************************/
void RC::PopulateBoard(){
if(UsingRCGraphics_){
//color constants
const graphics::Color kWallColor(50, 50, 50);
const graphics::Color backGroundColor(245,245,245);
const graphics::Color green1(143,202,92);
const graphics::Color green2(112,178,55);
const graphics::Color grey(128, 126, 120);
const graphics::Color yellow (247,181,0);
const int lineThickness = 4;
const int wallThickness_ = 3;
const int fontsize = 16;
const int margin = 32;
RCWorldImage_.DrawRectangle(0,0,XDim_*pxPerCell_-1,YDim_*pxPerCell_-1,backGroundColor);
//Horizontal Lines
for (int i = 0; i <= YDim_; i++) {
// Draw horizontal lines and indexes.
int x = pxPerCell_ * XDim_;
int y = i * pxPerCell_;
RCWorldImage_.DrawLine(0, y, x, y, kWallColor, wallThickness_);
//Adding Green Horizonal lines that look like grass
if(y < YDim_*pxPerCell_){
if(y%100==0)
RCWorldImage_.DrawRectangle(0,y,x,pxPerCell_,green1);
else
RCWorldImage_.DrawRectangle(0,y,x,pxPerCell_,green2);
}
//Add the index to the cell
if (i < YDim_) {
RCWorldImage_.DrawText(x + fontsize / 2, y + (pxPerCell_ - fontsize) / 2,
std::to_string(YDim_ - i), fontsize, kWallColor);
}
}
//Verticle Lines
for (int i = 0; i <= XDim_; i++) {
// Draw vertical lines and indexes.
int x = i * pxPerCell_;
int y = pxPerCell_ * YDim_;
RCWorldImage_.DrawLine(x, 0, x, y, kWallColor, wallThickness_);
//adding the text of the index of the specified cell
if (i < XDim_) {
RCWorldImage_.DrawText(x + (pxPerCell_ - fontsize) / 2, y + fontsize / 2,
std::to_string(i + 1), fontsize, kWallColor);
}
}
// Adding Roads and Rocks at to the Grids
for(int i = 0; i < XDim_; i++){
for(int j = 0; j < YDim_; j++){
int x_center = i * pxPerCell_ + pxPerCell_ / 2;
int y_center = j * pxPerCell_ + pxPerCell_ / 2;
Cell& cell = world_[i][j];
int rockCount = cell.GetNumOfRocks();
//Draw the Roads
if(cell.containsRoadNorth()){
//Set the positions for the upper left corner for the rectangle drawing
int x =i * pxPerCell_ + pxPerCell_/2;
int y = j * pxPerCell_;
//Set the height of the rectangle
int height = (YDim_-1) - j;
//Draw the road and a Yellow Line in the middle of the road
RCWorldImage_.DrawRectangle(i*pxPerCell_, 0, 1*pxPerCell_+1,(j+1)*pxPerCell_,grey);
RCWorldImage_.DrawLine(x,(j+1)*pxPerCell_,x,0, yellow,lineThickness);
}
if(cell.containsRoadEast()){
//Set the positions for the upper left corner for the rectangle drawing
int x = i * pxPerCell_;
int y = j * pxPerCell_+pxPerCell_/2;
//Set the width of the Rectangle
int width = XDim_ -i;
//Draw the road and a Yellow Line in the middle of the road
RCWorldImage_.DrawRectangle(i*pxPerCell_, j*pxPerCell_, width*pxPerCell_-1,1*pxPerCell_-1,grey);
RCWorldImage_.DrawLine(x,y,XDim_*pxPerCell_-1,y , yellow,4);
}
if(cell.containsRoadSouth()){
//Set the positions for the upper left corner for the rectangle drawing
int x =i * pxPerCell_ + pxPerCell_/2;
int y = j * pxPerCell_;
//Set the height of the rectangle
int height = YDim_ - j;
//Draw the road and a Yellow Line in the middle of the road
RCWorldImage_.DrawRectangle(i*pxPerCell_, j*pxPerCell_, 1*pxPerCell_+1,height*pxPerCell_,grey);
RCWorldImage_.DrawLine(x,y,x, YDim_*pxPerCell_-1 , yellow,4);
}
if(cell.containsRoadWest()){
//Set the positions for the upper left corner for the rectangle drawing
int x = i * pxPerCell_;
int y = j * pxPerCell_+pxPerCell_/2;
//Draw the road and a Yellow Line in the middle of the road
RCWorldImage_.DrawRectangle(0, j*pxPerCell_, (i+1)*pxPerCell_,1*pxPerCell_,grey);
RCWorldImage_.DrawLine((i+1)*pxPerCell_,y,0,y , yellow,4);
}
//Draw Rocks and Number of Rocks
if(rockCount > 0){
//Draw the rocks. Rocks are stacked so you cant tell if theres
//more than one in a stack
//Offset consts to make sure the color is set in the center of the square
const int widthOffset = 15;
const int heightOffset = 15;
graphics::Image rockImage;
rockImage.Load("./resources/rock.bmp");
graphics::Color black(0,0,0);
//Iterate throught the rock image and print it on the World
int temp = y_center;
for(int i = 0; i < rockImage.GetWidth(); i++ ){
for(int j = 0; j < rockImage.GetHeight(); j++){
graphics::Color color = rockImage.GetColor(i,j);
//Get rid of the black pixels that boarders the image
if(color != black){
RCWorldImage_.SetColor(x_center-widthOffset,y_center-heightOffset,color);
}
y_center++;
}
y_center = temp;
x_center++;
}
if (rockCount > 1) {
// Draw the rock count in the cell if it's biger than 1.
RCWorldImage_.DrawText(x_center-widthOffset- fontsize / 4, y_center - heightOffset - fontsize / 2,
std::to_string(rockCount), fontsize, kWallColor);
}
}
}
}
}
}
/***************************************************************************
* Function: Initialize
* Description:
* parces through a file and stores the "roads", "rocks", "RC",
* in the associated index of a 2D vector
* Parameters:
* string filename: is the filename that the user can pass so we can
* prepopulate the board with "rocks" and "roads"
* Return:
* None
***************************************************************************/
void RC::Initialize(std::string filename){
if(UsingRCGraphics_){
if (!filename.size()) {
// No file. Default 10x10 blank world with no roads or rocks.
for (int i = 0; i < XDim_; i++) {
world_.push_back(std::vector<Cell>());
for (int j = 0; j < YDim_; j++) {
world_[i].push_back(Cell());
}
}
position_.orientation_ = East;
}
else { //If file exists, read the file
std::fstream world_file;
try {
world_file.open(filename);
} catch (std::ifstream::failure e) {
ParseWorldFileError("Error opening file " + filename, -1);
}
if (!world_file.is_open()) {
ParseWorldFileError("Error opening file " + filename, -1);
}
std::string line;
int line_number = 1;
//File keywords
const std::string dimension_prefix = "Dimension:";
const std::string rock_prefix = "Rock:";
const std::string road_prefix = "Road:";
const std::string rccar_prefix = "RCCar:";
//Checks if "Dimensions" exists within the file
std::string line_prefix;
char open_paren, comma, closed_paren;
if (!(world_file >> line_prefix >> open_paren >> XDim_ >> comma >>
YDim_ >> closed_paren)) {
ParseWorldFileError(
"Could not parse world dimensions from the first line", line_number);
}
if (line_prefix != dimension_prefix) {
ParseWorldFileError("Could not find \"Dimension:\" in first line",
line_number);
}
CheckParsePosition(open_paren, comma, closed_paren, line_number);
//throws an error if the "Dimentions " is less then 1 cell wide or tall
if (XDim_ < 1 || YDim_ < 1) {
ParseWorldFileError(
"Cannot load a world less than 1 cell wide or less than 1 cell "
"tall",
line_number);
}
for (int i = 0; i < XDim_; i++) {
world_.push_back(std::vector<Cell>());
for (int j = 0; j < YDim_; j++) {
world_[i].push_back(Cell());
}
}
//Read the rest of the file to get rocks and road locations.
while (world_file >> line_prefix) {
line_number++;
if (line_prefix == road_prefix) {
DirectionAndOrientation wall = ParsePositionAndOrientation(world_file, line_number);
world_[wall.x_][wall.y_].AddRoad(wall.orientation_);
}
else if (line_prefix == rock_prefix) {
DirectionAndOrientation rock = ParsePosition(world_file, line_number);
int count;
if (!(world_file >> count)) {
ParseWorldFileError("Error reading Beeper count", line_number);
}
world_[rock.x_][rock.y_].SetNumOfRock(count);
world_[rock.x_][rock.y_].setContainsRock(true);
}
else if (line_prefix == rccar_prefix) {
position_ = ParsePositionAndOrientation(world_file, line_number);
}
else{
ParseWorldFileError("Unexpected token in file: " + line_prefix, line_number);
break;
}
}
world_file.close();
}
const int margin = 32;
int min_width = 5 * pxPerCell_ + margin;
RCWorldImage_.Initialize(std::max(XDim_*pxPerCell_+margin, min_width),YDim_*pxPerCell_+margin);
PopulateBoard();
Show();
DrawRCCar();
}
}
/***************************************************************************
* Function: DrawRCCar
* Description:
* Draws the RC Car given the position and the orientation of the car
* Parameters:
* int x_pixel: is the X position of the RC Car
* int y_pixel: is the Y position of the RC Car
* Return:
* None
***************************************************************************/
void RC::DrawRCCar(int x_pixel, int y_pixel){
//depending on the direction the car is facing print out a certain pixel image to the board
switch(position_.orientation_){
case Direction::North:{
//Offset consts to make sure the color is set in the center of the square
const int widthOffset = 30;
const int heightOffset = 32;
graphics::Image upCarImage;
upCarImage.Load("./resources/up.bmp");
graphics::Color black(0,0,0);
int temp = y_pixel;
for(int i = 0; i < upCarImage.GetWidth(); i++ ){
for(int j = 0; j < upCarImage.GetHeight(); j++){
graphics::Color color = upCarImage.GetColor(i,j);
if(color != black){
RCWorldImage_.SetColor(x_pixel-widthOffset,y_pixel-heightOffset,color);
}
y_pixel++;
}
y_pixel = temp;
x_pixel++;
}
break;
}
case Direction::East:{
//Offset consts to make sure the color is set in the center of the square
const int widthOffset = 32;
const int heightOffset = 30;
graphics::Image rightCarImage;
rightCarImage.Load("./resources/right.bmp");
graphics::Color black(0,0,0);
int temp = y_pixel;
for(int i = 0; i < rightCarImage.GetWidth(); i++ ){
for(int j = 0; j < rightCarImage.GetHeight(); j++){
graphics::Color color = rightCarImage.GetColor(i,j);
if(color != black){
RCWorldImage_.SetColor(x_pixel-widthOffset,y_pixel-heightOffset,color);
}
y_pixel++;
}
y_pixel = temp;
x_pixel++;
}
break;
}
case Direction::West:{
//Offset consts to make sure the color is set in the center of the square
const int widthOffset = 30;
const int heightOffset = 30;
graphics::Image leftCarImage;
leftCarImage.Load("./resources/left.bmp");
graphics::Color black(0,0,0);
int temp = y_pixel;
for(int i = 0; i < leftCarImage.GetWidth(); i++ ){
for(int j = 0; j < leftCarImage.GetHeight(); j++){
graphics::Color color = leftCarImage.GetColor(i,j);
if(color != black){
RCWorldImage_.SetColor(x_pixel-widthOffset,y_pixel-heightOffset,color);
}
y_pixel++;
}
y_pixel = temp;
x_pixel++;
}
break;
}
case Direction::South:{
//Offset consts to make sure the color is set in the center of the square
const int widthOffset = 32;
const int heightOffset = 30;
graphics::Image downCarImage;
downCarImage.Load("./resources/down.bmp");
graphics::Color black(0,0,0);
int temp = y_pixel;
for(int i = 0; i < downCarImage.GetWidth(); i++ ){
for(int j = 0; j < downCarImage.GetHeight(); j++){
graphics::Color color = downCarImage.GetColor(i,j);
if(color != black){
RCWorldImage_.SetColor(x_pixel-widthOffset,y_pixel-heightOffset,color);
}
y_pixel++;
}
y_pixel = temp;
x_pixel++;
}
break;
}
}
Show();
}
/***************************************************************************
* Function: MoveForward
* Description:
* The RC Car will move one cell forward in their current direction
* Parameters:
* None
* Return:
* None
***************************************************************************/
void RC::MoveForward(){
if(UsingRCGraphics_){
switch(position_.orientation_){
case Direction::North:{
if(position_.y_==-1){
std::cout << "ERROR cannot move north\n"; //x will be out of bounds
}
else{
position_.y_-=1;//Decrease x axis by 1
}
break;
}
case Direction::East:{
if(position_.x_==YDim_-1){
std::cout << "ERROR cannot move east\n"; //y will be out of bounds
}
else{
position_.x_+=1; //increase y axis by 1
}
break;
}
case Direction::South:{
if(position_.y_==XDim_-1){
std::cout << "ERROR: cannot move south"; //x will be out of bounds
}
else{
position_.y_+=1; //increase x by 1
}
break;
}
case Direction::West:{
if(position_.x_==-1){
std::cout << "ERROR: cannot move west"; //y will be out of bounds
}
else{
position_.x_-=1; //Decrease y by 1
}
break;
}
}
PopulateBoard();
DrawRCCar();
}
else
{
commandVec_.push_back('F');
}
}
/***************************************************************************
* Function: MoveBack
* Description:
* The RC Car will move one cell backward in the opposite direction
* Parameters:
* None
* Return:
* None
***************************************************************************/
void RC::MoveBack(){
if(UsingRCGraphics_){
switch(position_.orientation_){
case Direction::North:{
if(position_.x_==0){
std::cout << "ERROR cannot move north\n"; //x will be out of bounds
}
else{
position_.y_+=1;//Increase y axis by 1
}
break;
}
case Direction::East:{
if(position_.y_==YDim_-1){
std::cout << "ERROR cannot move east\n"; //y will be out of bounds
}
else{
position_.x_-=1; //decrease x axis by 1
}
break;
}
case Direction::South:{
if(position_.x_==XDim_-1){
std::cout << "ERROR: cannot move south"; //x will be out of bounds
}
else{
position_.y_-=1; //Decrease y by 1
}
break;
}
case Direction::West:{
if(position_.y_==0){
std::cout << "ERROR: cannot move west"; //y will be out of bounds
}
else{
position_.x_+=1; //Increase x by 1
}
break;
}
}
PopulateBoard();
DrawRCCar();
}
else
{
commandVec_.push_back('B');
}
}
/***************************************************************************
* Function: TurnLeft
* Description:
* The RC Car will rotate Left of their current orientation
* Parameters:
* None
* Return:
* None
***************************************************************************/
void RC::TurnLeft(){
if(UsingRCGraphics_){
//given what the current direction of the car, the car will change the direction appropriatly
switch(position_.orientation_){
case Direction::North:{
position_.orientation_=Direction::West;
break;
}
case Direction::East:{
position_.orientation_=Direction::North;
break;
}
case Direction::South:{
position_.orientation_=Direction::East;
break;
}
case Direction::West:{
position_.orientation_=Direction::South;
break;
}
}
PopulateBoard();
DrawRCCar();
}
else
{
commandVec_.push_back('L');
}
}
/***************************************************************************
* Function: MoveRight
* Description:
* The RC Car will rotate to the Right of their current orientation
* Parameters:
* None
* Return:
* None
***************************************************************************/
void RC::TurnRight(){
if(UsingRCGraphics_){
switch(position_.orientation_){
case Direction::North:{
position_.orientation_=Direction::East;
break;
}
case Direction::East:{
position_.orientation_=Direction::South;
break;
}
case Direction::South:{
position_.orientation_=Direction::West;
break;
}
case Direction::West:{
position_.orientation_=Direction::North;
break;
}
}
PopulateBoard();
DrawRCCar();
}
else
{
commandVec_.push_back('R');
}
}
/***************************************************************************
* Function: MoveForward
* Description:
* Display the current instance of the car for N ms
* Parameters:
* None
* Return:
* None
***************************************************************************/
void RC::Show(){
if(UsingRCGraphics_){
RCWorldImage_.ShowForMs(Speed_,"RC World");
}
}
void RC::CreateCommandFile()
{
// Extra insurance this function is only called when using the RC
if(UsingRCGraphics_)
return;
// Attempt to create file and write to it
try
{
std::ofstream fout(fileName_);
// Loop through and vector and print it to the file.
for(int i = 0; i < commandVec_.size(); i++)
fout << commandVec_[i];
fout.close();
}
catch(std::ofstream::failure e)
{
std::cerr << e.what() << '\n';
}
for(int i = 0; i < commandVec_.size(); i++)
std::cout << "VEC: " << commandVec_[i] << '\n';
}
void RC::SendFileToServer()
{
// Check to ensure the file we wish to send exists
// std::ifstream fin("temp.txt");
//if(!fin.good())
// throw std::runtime_error("ERROR: Couldn't find file to send to server.");
CURL* curl_ptr;
CURLcode res;
struct stat fileInfo;
curl_off_t u_speed, total_speed;
// Open the file and ensure contents are okay
FILE* fd = fopen(fileName_.c_str(), "rb");
if(!fd || fstat(fileno(fd), &fileInfo) != 0) {throw std::runtime_error("FAILED TO OPEN FILE or FILE IS EMPTY");}
// Initlaize Windows socket stuff
curl_global_init(CURL_GLOBAL_ALL);
// Initalize curl handle
curl_ptr = curl_easy_init();
if(curl_ptr)
{
// Give Curl the server address
curl_easy_setopt(curl_ptr, CURLOPT_URL, "http://107.221.75.87/");
// Tell curl we're going to be "Uploading" to the URL
curl_easy_setopt(curl_ptr, CURLOPT_UPLOAD, 1L);
curl_easy_setopt(curl_ptr, CURLOPT_READDATA, fd);
curl_easy_setopt(curl_ptr, CURLOPT_VERBOSE, 1L);
// Set the File Size to what we shall upload
curl_easy_setopt(curl_ptr, CURLOPT_INFILESIZE_LARGE, (curl_off_t)fileInfo.st_size);
// Perform the Request, and grab the return code
res = curl_easy_perform(curl_ptr);
if(res != CURLE_OK)
std::cout << "CURL FAILED: " << curl_easy_strerror(res) << '\n';
else
{
curl_easy_getinfo(curl_ptr, CURLINFO_SPEED_UPLOAD_T, &u_speed);
curl_easy_getinfo(curl_ptr, CURLINFO_TOTAL_TIME_T, &total_speed);
fprintf(stderr, "UPLOAD SPEED: %" CURL_FORMAT_CURL_OFF_T " bytes/sec during %"
CURL_FORMAT_CURL_OFF_T ".%01d ~seconds\n",u_speed, (total_speed /(pow(10,6))), (long)(total_speed % 1000000));
}
// Cleanup Resources
curl_easy_cleanup(curl_ptr);
}
curl_global_cleanup();
}
#endif | 34.857724 | 128 | 0.504169 | eanmcgilvery |
0673d8a0bb1d3dbb436e0614d53d563f245fa063 | 8,212 | cc | C++ | deploy/pptracking/cpp/src/jde_predictor.cc | Amanda-Barbara/PaddleDetection | 65ac13074eaaa2447c644a2df71969d8a3dd1fae | [
"Apache-2.0"
] | 3 | 2022-03-23T08:48:06.000Z | 2022-03-28T01:59:34.000Z | deploy/pptracking/cpp/src/jde_predictor.cc | Amanda-Barbara/PaddleDetection | 65ac13074eaaa2447c644a2df71969d8a3dd1fae | [
"Apache-2.0"
] | null | null | null | deploy/pptracking/cpp/src/jde_predictor.cc | Amanda-Barbara/PaddleDetection | 65ac13074eaaa2447c644a2df71969d8a3dd1fae | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2021 PaddlePaddle 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 <sstream>
// for setprecision
#include <chrono>
#include <iomanip>
#include "include/jde_predictor.h"
using namespace paddle_infer; // NOLINT
namespace PaddleDetection {
// Load Model and create model predictor
void JDEPredictor::LoadModel(const std::string& model_dir,
const std::string& run_mode) {
paddle_infer::Config config;
std::string prog_file = model_dir + OS_PATH_SEP + "model.pdmodel";
std::string params_file = model_dir + OS_PATH_SEP + "model.pdiparams";
config.SetModel(prog_file, params_file);
if (this->device_ == "GPU") {
config.EnableUseGpu(200, this->gpu_id_);
config.SwitchIrOptim(true);
// use tensorrt
if (run_mode != "paddle") {
auto precision = paddle_infer::Config::Precision::kFloat32;
if (run_mode == "trt_fp32") {
precision = paddle_infer::Config::Precision::kFloat32;
} else if (run_mode == "trt_fp16") {
precision = paddle_infer::Config::Precision::kHalf;
} else if (run_mode == "trt_int8") {
precision = paddle_infer::Config::Precision::kInt8;
} else {
printf(
"run_mode should be 'paddle', 'trt_fp32', 'trt_fp16' or "
"'trt_int8'");
}
// set tensorrt
config.EnableTensorRtEngine(1 << 30,
1,
this->min_subgraph_size_,
precision,
false,
this->trt_calib_mode_);
}
} else if (this->device_ == "XPU") {
config.EnableXpu(10 * 1024 * 1024);
} else {
config.DisableGpu();
if (this->use_mkldnn_) {
config.EnableMKLDNN();
// cache 10 different shapes for mkldnn to avoid memory leak
config.SetMkldnnCacheCapacity(10);
}
config.SetCpuMathLibraryNumThreads(this->cpu_math_library_num_threads_);
}
config.SwitchUseFeedFetchOps(false);
config.SwitchIrOptim(true);
config.DisableGlogInfo();
// Memory optimization
config.EnableMemoryOptim();
predictor_ = std::move(CreatePredictor(config));
}
void FilterDets(const float conf_thresh,
const cv::Mat dets,
std::vector<int>* index) {
for (int i = 0; i < dets.rows; ++i) {
float score = *dets.ptr<float>(i, 4);
if (score > conf_thresh) {
index->push_back(i);
}
}
}
void JDEPredictor::Preprocess(const cv::Mat& ori_im) {
// Clone the image : keep the original mat for postprocess
cv::Mat im = ori_im.clone();
preprocessor_.Run(&im, &inputs_);
}
void JDEPredictor::Postprocess(const cv::Mat dets,
const cv::Mat emb,
MOTResult* result) {
result->clear();
std::vector<Track> tracks;
std::vector<int> valid;
FilterDets(conf_thresh_, dets, &valid);
cv::Mat new_dets, new_emb;
for (int i = 0; i < valid.size(); ++i) {
new_dets.push_back(dets.row(valid[i]));
new_emb.push_back(emb.row(valid[i]));
}
JDETracker::instance()->update(new_dets, new_emb, &tracks);
if (tracks.size() == 0) {
MOTTrack mot_track;
Rect ret = {*dets.ptr<float>(0, 0),
*dets.ptr<float>(0, 1),
*dets.ptr<float>(0, 2),
*dets.ptr<float>(0, 3)};
mot_track.ids = 1;
mot_track.score = *dets.ptr<float>(0, 4);
mot_track.rects = ret;
result->push_back(mot_track);
} else {
std::vector<Track>::iterator titer;
for (titer = tracks.begin(); titer != tracks.end(); ++titer) {
if (titer->score < threshold_) {
continue;
} else {
float w = titer->ltrb[2] - titer->ltrb[0];
float h = titer->ltrb[3] - titer->ltrb[1];
bool vertical = w / h > 1.6;
float area = w * h;
if (area > min_box_area_ && !vertical) {
MOTTrack mot_track;
Rect ret = {
titer->ltrb[0], titer->ltrb[1], titer->ltrb[2], titer->ltrb[3]};
mot_track.rects = ret;
mot_track.score = titer->score;
mot_track.ids = titer->id;
result->push_back(mot_track);
}
}
}
}
}
void JDEPredictor::Predict(const std::vector<cv::Mat> imgs,
const double threshold,
MOTResult* result,
std::vector<double>* times) {
auto preprocess_start = std::chrono::steady_clock::now();
int batch_size = imgs.size();
// in_data_batch
std::vector<float> in_data_all;
std::vector<float> im_shape_all(batch_size * 2);
std::vector<float> scale_factor_all(batch_size * 2);
// Preprocess image
for (int bs_idx = 0; bs_idx < batch_size; bs_idx++) {
cv::Mat im = imgs.at(bs_idx);
Preprocess(im);
im_shape_all[bs_idx * 2] = inputs_.im_shape_[0];
im_shape_all[bs_idx * 2 + 1] = inputs_.im_shape_[1];
scale_factor_all[bs_idx * 2] = inputs_.scale_factor_[0];
scale_factor_all[bs_idx * 2 + 1] = inputs_.scale_factor_[1];
in_data_all.insert(
in_data_all.end(), inputs_.im_data_.begin(), inputs_.im_data_.end());
}
// Prepare input tensor
auto input_names = predictor_->GetInputNames();
for (const auto& tensor_name : input_names) {
auto in_tensor = predictor_->GetInputHandle(tensor_name);
if (tensor_name == "image") {
int rh = inputs_.in_net_shape_[0];
int rw = inputs_.in_net_shape_[1];
in_tensor->Reshape({batch_size, 3, rh, rw});
in_tensor->CopyFromCpu(in_data_all.data());
} else if (tensor_name == "im_shape") {
in_tensor->Reshape({batch_size, 2});
in_tensor->CopyFromCpu(im_shape_all.data());
} else if (tensor_name == "scale_factor") {
in_tensor->Reshape({batch_size, 2});
in_tensor->CopyFromCpu(scale_factor_all.data());
}
}
auto preprocess_end = std::chrono::steady_clock::now();
std::vector<int> bbox_shape;
std::vector<int> emb_shape;
// Run predictor
auto inference_start = std::chrono::steady_clock::now();
predictor_->Run();
// Get output tensor
auto output_names = predictor_->GetOutputNames();
auto bbox_tensor = predictor_->GetOutputHandle(output_names[0]);
bbox_shape = bbox_tensor->shape();
auto emb_tensor = predictor_->GetOutputHandle(output_names[1]);
emb_shape = emb_tensor->shape();
// Calculate bbox length
int bbox_size = 1;
for (int j = 0; j < bbox_shape.size(); ++j) {
bbox_size *= bbox_shape[j];
}
// Calculate emb length
int emb_size = 1;
for (int j = 0; j < emb_shape.size(); ++j) {
emb_size *= emb_shape[j];
}
bbox_data_.resize(bbox_size);
bbox_tensor->CopyToCpu(bbox_data_.data());
emb_data_.resize(emb_size);
emb_tensor->CopyToCpu(emb_data_.data());
auto inference_end = std::chrono::steady_clock::now();
// Postprocessing result
auto postprocess_start = std::chrono::steady_clock::now();
result->clear();
cv::Mat dets(bbox_shape[0], 6, CV_32FC1, bbox_data_.data());
cv::Mat emb(bbox_shape[0], emb_shape[1], CV_32FC1, emb_data_.data());
Postprocess(dets, emb, result);
auto postprocess_end = std::chrono::steady_clock::now();
std::chrono::duration<float> preprocess_diff =
preprocess_end - preprocess_start;
(*times)[0] += static_cast<double>(preprocess_diff.count() * 1000);
std::chrono::duration<float> inference_diff = inference_end - inference_start;
(*times)[1] += static_cast<double>(inference_diff.count() * 1000);
std::chrono::duration<float> postprocess_diff =
postprocess_end - postprocess_start;
(*times)[2] += static_cast<double>(postprocess_diff.count() * 1000);
}
} // namespace PaddleDetection
| 34.79661 | 80 | 0.629445 | Amanda-Barbara |
067538bdca83fd2d62096ca981783b95168c04bf | 1,271 | cpp | C++ | Engine/Source/honey.cpp | bugsbycarlin/Honey | 56902979eb746c8dff5c8bcfc531fbf855c0bae5 | [
"MIT"
] | null | null | null | Engine/Source/honey.cpp | bugsbycarlin/Honey | 56902979eb746c8dff5c8bcfc531fbf855c0bae5 | [
"MIT"
] | null | null | null | Engine/Source/honey.cpp | bugsbycarlin/Honey | 56902979eb746c8dff5c8bcfc531fbf855c0bae5 | [
"MIT"
] | null | null | null | /*
Honey
Copyright 2018 - Matthew Carlin
*/
#include "honey.h"
using namespace std;
namespace Honey {
Window& window = Window::instance();
ScreenManager& screenmanager = ScreenManager::instance();
Timing& timing = Timing::instance();
MathUtilities& math_utils = MathUtilities::instance();
Config& config = Config::instance();
Config& conf = config;
Config& hot_config = config;
Input& input = Input::instance();
Collisions& collisions = Collisions::instance();
Effects& effects = Effects::instance();
Layouts& layouts = Layouts::instance();
Graphics& graphics = Graphics::instance();
Sound& sound = Sound::instance();
void StartHoney(string title, int screen_width, int screen_height, bool full_screen) {
window.initialize(title, screen_width, screen_height, full_screen);
graphics.initialize();
sound.initialize();
}
void StartHoney(string title) {
// Load configuration
if (config.checkAndUpdate() != config.SUCCESS) {
exit(1);
}
int screen_width = config.getInt("layout", "screen_width");
int screen_height = config.getInt("layout", "screen_height");
bool full_screen = config.getBool("layout", "full_screen");
StartHoney(title, screen_width, screen_height, full_screen);
}
} | 28.244444 | 88 | 0.697876 | bugsbycarlin |
0679cdcc3547a36811b82bd645ed2b20d5e6bf7d | 2,787 | cpp | C++ | src/Graphics/Model.cpp | llGuy/Ondine | 325c2d3ea5bd5ef5456b0181c53ad227571fada3 | [
"MIT"
] | 1 | 2022-01-24T18:15:56.000Z | 2022-01-24T18:15:56.000Z | src/Graphics/Model.cpp | llGuy/Ondine | 325c2d3ea5bd5ef5456b0181c53ad227571fada3 | [
"MIT"
] | null | null | null | src/Graphics/Model.cpp | llGuy/Ondine | 325c2d3ea5bd5ef5456b0181c53ad227571fada3 | [
"MIT"
] | null | null | null | #include <assert.h>
#include "Model.hpp"
namespace Ondine::Graphics {
ModelConfig::ModelConfig(uint32_t vertexCount)
: mVertexCount(vertexCount),
mAttributeCount(0),
mAttributes{},
mIndexCount(0),
mIndexType(VkIndexType(0)),
mIndices{} {
}
void ModelConfig::pushAttribute(
const Attribute &attribute, const Buffer &data) {
assert(mAttributeCount < MAX_ATTRIBUTE_COUNT);
mAttributes[mAttributeCount++] = {
attribute.size,
attribute.format,
data
};
}
void ModelConfig::configureIndices(
uint32_t indexCount, VkIndexType type, const Buffer &data) {
mIndexCount = indexCount;
mIndexType = type;
mIndices = data;
}
void ModelConfig::configureVertexInput(VulkanPipelineConfig &config) {
config.configureVertexInput(mAttributeCount, mAttributeCount);
for (int i = 0; i < mAttributeCount; ++i) {
config.setBinding(i, mAttributes[i].attribSize, VK_VERTEX_INPUT_RATE_VERTEX);
config.setBindingAttribute(i, i, mAttributes[i].format, 0);
}
}
void Model::init(const ModelConfig &def, VulkanContext &context) {
mVertexCount = def.mVertexCount;
if (def.mIndexCount > 0) {
mIndexBuffer.init(
context.device(), def.mIndices.size,
(VulkanBufferFlagBits)VulkanBufferFlag::IndexBuffer);
mIndexBuffer.fillWithStaging(
context.device(), context.commandPool(),
def.mIndices);
}
mVertexBufferCount = 0;
// For now, store each attribute in a separate vertex buffer
for (int i = 0; i < def.mAttributeCount; ++i) {
auto &attribute = def.mAttributes[i];
auto &buf = mVertexBuffers[mVertexBufferCount++];
buf.init(
context.device(), attribute.data.size,
(VulkanBufferFlagBits)VulkanBufferFlag::VertexBuffer);
buf.fillWithStaging(
context.device(), context.commandPool(),
attribute.data);
mVertexBuffersRaw[i] = buf.mBuffer;
}
mVertexBufferCount = def.mAttributeCount;
mIndexType = def.mIndexType;
mIndexCount = def.mIndexCount;
}
void Model::bindVertexBuffers(const VulkanCommandBuffer &commandBuffer) const {
VkDeviceSize *offsets = STACK_ALLOC(VkDeviceSize, mVertexBufferCount);
memset(offsets, 0, sizeof(VkDeviceSize) * mVertexBufferCount);
commandBuffer.bindVertexBuffers(
0, mVertexBufferCount, mVertexBuffersRaw, offsets);
}
void Model::bindIndexBuffer(const VulkanCommandBuffer &commandBuffer) const {
commandBuffer.bindIndexBuffer(0, mIndexType, mIndexBuffer);
}
void Model::submitForRenderIndexed(
const VulkanCommandBuffer &commandBuffer,
uint32_t instanceCount) const {
commandBuffer.drawIndexed(mIndexCount, instanceCount, 0, 0, 0);
}
void Model::submitForRender(
const VulkanCommandBuffer &commandBuffer,
uint32_t instanceCount) const {
commandBuffer.draw(mVertexCount, instanceCount, 0, 0);
}
}
| 27.323529 | 81 | 0.735199 | llGuy |
067a56a19902ba8198fa931e4187327ca6afaa62 | 2,647 | cpp | C++ | lldb/unittests/Target/StackFrameRecognizerTest.cpp | AnthonyLatsis/llvm-project | 2acd6cdb9a4bfb2c34b701527e04dd4ffe791d74 | [
"Apache-2.0"
] | 27 | 2020-02-18T20:48:54.000Z | 2022-02-14T01:30:00.000Z | lldb/unittests/Target/StackFrameRecognizerTest.cpp | coolstar/llvm-project | e21ccdd5b5667de50de65ee8903a89a21020e89a | [
"Apache-2.0"
] | 9 | 2020-04-24T21:51:04.000Z | 2020-11-06T01:04:09.000Z | lldb/unittests/Target/StackFrameRecognizerTest.cpp | coolstar/llvm-project | e21ccdd5b5667de50de65ee8903a89a21020e89a | [
"Apache-2.0"
] | 7 | 2020-04-14T09:12:18.000Z | 2021-09-20T10:31:12.000Z | //===-- StackFrameRecognizerTest.cpp --------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "lldb/Target/StackFrameRecognizer.h"
#include "Plugins/Platform/Linux/PlatformLinux.h"
#include "lldb/Core/Debugger.h"
#include "lldb/Host/FileSystem.h"
#include "lldb/Host/HostInfo.h"
#include "lldb/Utility/Reproducer.h"
#include "lldb/lldb-enumerations.h"
#include "lldb/lldb-forward.h"
#include "lldb/lldb-private-enumerations.h"
#include "lldb/lldb-private.h"
#include "llvm/Support/FormatVariadic.h"
#include "gtest/gtest.h"
using namespace lldb_private;
using namespace lldb_private::repro;
using namespace lldb;
namespace {
class StackFrameRecognizerTest : public ::testing::Test {
public:
void SetUp() override {
llvm::cantFail(Reproducer::Initialize(ReproducerMode::Off, llvm::None));
FileSystem::Initialize();
HostInfo::Initialize();
// Pretend Linux is the host platform.
platform_linux::PlatformLinux::Initialize();
ArchSpec arch("powerpc64-pc-linux");
Platform::SetHostPlatform(
platform_linux::PlatformLinux::CreateInstance(true, &arch));
}
void TearDown() override {
platform_linux::PlatformLinux::Terminate();
HostInfo::Terminate();
FileSystem::Terminate();
Reproducer::Terminate();
}
};
class DummyStackFrameRecognizer : public StackFrameRecognizer {
public:
std::string GetName() override { return "Dummy StackFrame Recognizer"; }
};
void RegisterDummyStackFrameRecognizer() {
static llvm::once_flag g_once_flag;
llvm::call_once(g_once_flag, []() {
RegularExpressionSP module_regex_sp = nullptr;
RegularExpressionSP symbol_regex_sp(new RegularExpression("boom"));
StackFrameRecognizerSP dummy_recognizer_sp(new DummyStackFrameRecognizer());
StackFrameRecognizerManager::AddRecognizer(
dummy_recognizer_sp, module_regex_sp, symbol_regex_sp, false);
});
}
} // namespace
TEST_F(StackFrameRecognizerTest, NullModuleRegex) {
DebuggerSP debugger_sp = Debugger::CreateInstance();
ASSERT_TRUE(debugger_sp);
RegisterDummyStackFrameRecognizer();
bool any_printed = false;
StackFrameRecognizerManager::ForEach(
[&any_printed](uint32_t recognizer_id, std::string name,
std::string function, llvm::ArrayRef<ConstString> symbols,
bool regexp) { any_printed = true; });
EXPECT_TRUE(any_printed);
}
| 31.511905 | 80 | 0.703816 | AnthonyLatsis |
067cf9785dac34b7f808b923e415dea463b94629 | 50,800 | cpp | C++ | tests/codegen.cpp | ajor/bpftrace | 691e1264b526b9179a610c3ae706e439efd132d3 | [
"Apache-2.0"
] | 278 | 2016-12-28T00:51:17.000Z | 2022-02-09T10:32:31.000Z | tests/codegen.cpp | brendangregg/bpftrace | 4cc2e864a9bbbcb97a508bfc5a3db1cd0b5d7f95 | [
"Apache-2.0"
] | 48 | 2017-07-10T20:17:55.000Z | 2020-01-20T23:41:51.000Z | tests/codegen.cpp | ajor/bpftrace | 691e1264b526b9179a610c3ae706e439efd132d3 | [
"Apache-2.0"
] | 19 | 2017-07-28T05:49:00.000Z | 2022-02-22T22:05:37.000Z | #include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "bpforc.h"
#include "bpftrace.h"
#include "codegen_llvm.h"
#include "driver.h"
#include "fake_map.h"
#include "semantic_analyser.h"
namespace bpftrace {
namespace test {
namespace codegen {
using ::testing::_;
TEST(codegen, populate_sections)
{
BPFtrace bpftrace;
Driver driver;
ASSERT_EQ(driver.parse_str("kprobe:foo { 1 } kprobe:bar { 1 }"), 0);
ast::SemanticAnalyser semantics(driver.root_, bpftrace);
ASSERT_EQ(semantics.analyse(), 0);
std::stringstream out;
ast::CodegenLLVM codegen(driver.root_, bpftrace);
auto bpforc = codegen.compile(true, out);
// Check sections are populated
ASSERT_EQ(bpforc->sections_.size(), 2);
ASSERT_EQ(bpforc->sections_.count("s_kprobe:foo"), 1);
ASSERT_EQ(bpforc->sections_.count("s_kprobe:bar"), 1);
}
std::string header = R"HEAD(; ModuleID = 'bpftrace'
source_filename = "bpftrace"
target datalayout = "e-m:e-p:64:64-i64:64-n32:64-S128"
target triple = "bpf-pc-linux"
)HEAD";
void test(const std::string &input, const std::string expected_output)
{
BPFtrace bpftrace;
Driver driver;
FakeMap::next_mapfd_ = 1;
ASSERT_EQ(driver.parse_str(input), 0);
ast::SemanticAnalyser semantics(driver.root_, bpftrace);
ASSERT_EQ(semantics.analyse(), 0);
ASSERT_EQ(semantics.create_maps(true), 0);
std::stringstream out;
ast::CodegenLLVM codegen(driver.root_, bpftrace);
codegen.compile(true, out);
std::string full_expected_output = header + expected_output;
EXPECT_EQ(full_expected_output, out.str());
}
TEST(codegen, empty_function)
{
test("kprobe:f { 1; }",
R"EXPECTED(; Function Attrs: norecurse nounwind readnone
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr #0 section "s_kprobe:f" {
entry:
ret i64 0
}
attributes #0 = { norecurse nounwind readnone }
)EXPECTED");
}
TEST(codegen, map_assign_int)
{
test("kprobe:f { @x = 1; }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%1 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
store i64 0, i64* %"@x_key", align 8
%2 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %2)
store i64 1, i64* %"@x_val", align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %2)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, map_assign_string)
{
test("kprobe:f { @x = \"blah\"; }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_key" = alloca i64, align 8
%str = alloca [64 x i8], align 1
%1 = getelementptr inbounds [64 x i8], [64 x i8]* %str, i64 0, i64 0
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
store i8 98, i8* %1, align 1
%str.repack1 = getelementptr inbounds [64 x i8], [64 x i8]* %str, i64 0, i64 1
store i8 108, i8* %str.repack1, align 1
%str.repack2 = getelementptr inbounds [64 x i8], [64 x i8]* %str, i64 0, i64 2
store i8 97, i8* %str.repack2, align 1
%str.repack3 = getelementptr inbounds [64 x i8], [64 x i8]* %str, i64 0, i64 3
store i8 104, i8* %str.repack3, align 1
%str.repack4 = getelementptr inbounds [64 x i8], [64 x i8]* %str, i64 0, i64 4
%2 = bitcast i64* %"@x_key" to i8*
call void @llvm.memset.p0i8.i64(i8* %str.repack4, i8 0, i64 60, i32 1, i1 false)
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %2)
store i64 0, i64* %"@x_key", align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", [64 x i8]* nonnull %str, i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %2)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
; Function Attrs: argmemonly nounwind
declare void @llvm.memset.p0i8.i64(i8* nocapture writeonly, i8, i64, i32, i1) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, map_key_int)
{
test("kprobe:f { @x[11,22,33] = 44 }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca [24 x i8], align 8
%1 = getelementptr inbounds [24 x i8], [24 x i8]* %"@x_key", i64 0, i64 0
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
store i64 11, i8* %1, align 8
%2 = getelementptr inbounds [24 x i8], [24 x i8]* %"@x_key", i64 0, i64 8
store i64 22, i8* %2, align 8
%3 = getelementptr inbounds [24 x i8], [24 x i8]* %"@x_key", i64 0, i64 16
store i64 33, i8* %3, align 8
%4 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %4)
store i64 44, i64* %"@x_val", align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, [24 x i8]* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %4)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, map_key_string)
{
test("kprobe:f { @x[\"a\", \"b\"] = 44 }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca [128 x i8], align 1
%1 = getelementptr inbounds [128 x i8], [128 x i8]* %"@x_key", i64 0, i64 0
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
store i8 97, i8* %1, align 1
%str.sroa.3.0..sroa_idx = getelementptr inbounds [128 x i8], [128 x i8]* %"@x_key", i64 0, i64 1
%str1.sroa.0.0..sroa_idx = getelementptr inbounds [128 x i8], [128 x i8]* %"@x_key", i64 0, i64 64
call void @llvm.memset.p0i8.i64(i8* %str.sroa.3.0..sroa_idx, i8 0, i64 63, i32 1, i1 false)
store i8 98, i8* %str1.sroa.0.0..sroa_idx, align 1
%str1.sroa.3.0..sroa_idx = getelementptr inbounds [128 x i8], [128 x i8]* %"@x_key", i64 0, i64 65
%2 = bitcast i64* %"@x_val" to i8*
call void @llvm.memset.p0i8.i64(i8* %str1.sroa.3.0..sroa_idx, i8 0, i64 63, i32 1, i1 false)
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %2)
store i64 44, i64* %"@x_val", align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, [128 x i8]* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %2)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
; Function Attrs: argmemonly nounwind
declare void @llvm.memset.p0i8.i64(i8* nocapture writeonly, i8, i64, i32, i1) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, builtin_nsecs)
{
test("kprobe:f { @x = nsecs }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%get_ns = tail call i64 inttoptr (i64 5 to i64 ()*)()
%1 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
store i64 0, i64* %"@x_key", align 8
%2 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %2)
store i64 %get_ns, i64* %"@x_val", align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %2)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, builtin_stack)
{
test("kprobe:f { @x = stack }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8*) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 2)
%get_stackid = tail call i64 inttoptr (i64 27 to i64 (i8*, i8*, i64)*)(i8* %0, i64 %pseudo, i64 0)
%1 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
store i64 0, i64* %"@x_key", align 8
%2 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %2)
store i64 %get_stackid, i64* %"@x_val", align 8
%pseudo1 = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo1, i64* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %2)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, builtin_ustack)
{
test("kprobe:f { @x = ustack }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8*) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 2)
%get_stackid = tail call i64 inttoptr (i64 27 to i64 (i8*, i8*, i64)*)(i8* %0, i64 %pseudo, i64 256)
%1 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
store i64 0, i64* %"@x_key", align 8
%2 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %2)
store i64 %get_stackid, i64* %"@x_val", align 8
%pseudo1 = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo1, i64* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %2)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, builtin_pid_tid)
{
test("kprobe:f { @x = pid; @y = tid }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@y_val" = alloca i64, align 8
%"@y_key" = alloca i64, align 8
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%get_pid_tgid = tail call i64 inttoptr (i64 14 to i64 ()*)()
%1 = lshr i64 %get_pid_tgid, 32
%2 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %2)
store i64 0, i64* %"@x_key", align 8
%3 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %3)
store i64 %1, i64* %"@x_val", align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %2)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %3)
%get_pid_tgid1 = call i64 inttoptr (i64 14 to i64 ()*)()
%4 = and i64 %get_pid_tgid1, 4294967295
%5 = bitcast i64* %"@y_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %5)
store i64 0, i64* %"@y_key", align 8
%6 = bitcast i64* %"@y_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %6)
store i64 %4, i64* %"@y_val", align 8
%pseudo2 = call i64 @llvm.bpf.pseudo(i64 1, i64 2)
%update_elem3 = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo2, i64* nonnull %"@y_key", i64* nonnull %"@y_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %5)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %6)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, builtin_uid_gid)
{
test("kprobe:f { @x = uid; @y = gid }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@y_val" = alloca i64, align 8
%"@y_key" = alloca i64, align 8
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%get_uid_gid = tail call i64 inttoptr (i64 15 to i64 ()*)()
%1 = and i64 %get_uid_gid, 4294967295
%2 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %2)
store i64 0, i64* %"@x_key", align 8
%3 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %3)
store i64 %1, i64* %"@x_val", align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %2)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %3)
%get_uid_gid1 = call i64 inttoptr (i64 15 to i64 ()*)()
%4 = lshr i64 %get_uid_gid1, 32
%5 = bitcast i64* %"@y_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %5)
store i64 0, i64* %"@y_key", align 8
%6 = bitcast i64* %"@y_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %6)
store i64 %4, i64* %"@y_val", align 8
%pseudo2 = call i64 @llvm.bpf.pseudo(i64 1, i64 2)
%update_elem3 = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo2, i64* nonnull %"@y_key", i64* nonnull %"@y_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %5)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %6)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, builtin_cpu)
{
test("kprobe:f { @x = cpu }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%get_cpu_id = tail call i64 inttoptr (i64 8 to i64 ()*)()
%1 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
store i64 0, i64* %"@x_key", align 8
%2 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %2)
store i64 %get_cpu_id, i64* %"@x_val", align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %2)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, builtin_comm)
{
test("kprobe:f { @x = comm }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_key" = alloca i64, align 8
%comm = alloca [64 x i8], align 1
%1 = getelementptr inbounds [64 x i8], [64 x i8]* %comm, i64 0, i64 0
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
call void @llvm.memset.p0i8.i64(i8* nonnull %1, i8 0, i64 64, i32 1, i1 false)
%get_comm = call i64 inttoptr (i64 16 to i64 (i8*, i64)*)([64 x i8]* nonnull %comm, i64 64)
%2 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %2)
store i64 0, i64* %"@x_key", align 8
%pseudo = call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", [64 x i8]* nonnull %comm, i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %2)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.memset.p0i8.i64(i8* nocapture writeonly, i8, i64, i32, i1) #1
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, builtin_arg)
{
test("kprobe:f { @x = arg0; @y = arg2 }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8*) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@y_val" = alloca i64, align 8
%"@y_key" = alloca i64, align 8
%arg2 = alloca i64, align 8
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%arg0 = alloca i64, align 8
%1 = bitcast i64* %arg0 to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
%2 = getelementptr i8, i8* %0, i64 112
%probe_read = call i64 inttoptr (i64 4 to i64 (i8*, i64, i8*)*)(i64* nonnull %arg0, i64 8, i8* %2)
%3 = load i64, i64* %arg0, align 8
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
%4 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %4)
store i64 0, i64* %"@x_key", align 8
%5 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %5)
store i64 %3, i64* %"@x_val", align 8
%pseudo = call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %4)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %5)
%6 = bitcast i64* %arg2 to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %6)
%7 = getelementptr i8, i8* %0, i64 96
%probe_read1 = call i64 inttoptr (i64 4 to i64 (i8*, i64, i8*)*)(i64* nonnull %arg2, i64 8, i8* %7)
%8 = load i64, i64* %arg2, align 8
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %6)
%9 = bitcast i64* %"@y_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %9)
store i64 0, i64* %"@y_key", align 8
%10 = bitcast i64* %"@y_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %10)
store i64 %8, i64* %"@y_val", align 8
%pseudo2 = call i64 @llvm.bpf.pseudo(i64 1, i64 2)
%update_elem3 = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo2, i64* nonnull %"@y_key", i64* nonnull %"@y_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %9)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %10)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, builtin_retval)
{
test("kprobe:f { @x = retval }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8*) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%retval = alloca i64, align 8
%1 = bitcast i64* %retval to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
%2 = getelementptr i8, i8* %0, i64 80
%probe_read = call i64 inttoptr (i64 4 to i64 (i8*, i64, i8*)*)(i64* nonnull %retval, i64 8, i8* %2)
%3 = load i64, i64* %retval, align 8
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
%4 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %4)
store i64 0, i64* %"@x_key", align 8
%5 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %5)
store i64 %3, i64* %"@x_val", align 8
%pseudo = call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %4)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %5)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, builtin_func)
{
test("kprobe:f { @x = func }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8*) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%func = alloca i64, align 8
%1 = bitcast i64* %func to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
%2 = getelementptr i8, i8* %0, i64 128
%probe_read = call i64 inttoptr (i64 4 to i64 (i8*, i64, i8*)*)(i64* nonnull %func, i64 8, i8* %2)
%3 = load i64, i64* %func, align 8
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
%4 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %4)
store i64 0, i64* %"@x_key", align 8
%5 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %5)
store i64 %3, i64* %"@x_val", align 8
%pseudo = call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %4)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %5)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, call_reg) // Identical to builtin_func apart from variable names
{
test("kprobe:f { @x = reg(\"ip\") }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8*) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%reg_ip = alloca i64, align 8
%1 = bitcast i64* %reg_ip to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
%2 = getelementptr i8, i8* %0, i64 128
%probe_read = call i64 inttoptr (i64 4 to i64 (i8*, i64, i8*)*)(i64* nonnull %reg_ip, i64 8, i8* %2)
%3 = load i64, i64* %reg_ip, align 8
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
%4 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %4)
store i64 0, i64* %"@x_key", align 8
%5 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %5)
store i64 %3, i64* %"@x_val", align 8
%pseudo = call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %4)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %5)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, call_quantize)
{
test("kprobe:f { @x = quantize(pid) }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%get_pid_tgid = tail call i64 inttoptr (i64 14 to i64 ()*)()
%1 = lshr i64 %get_pid_tgid, 32
%2 = icmp ugt i64 %get_pid_tgid, 281474976710655
%3 = zext i1 %2 to i64
%4 = shl nuw nsw i64 %3, 4
%5 = lshr i64 %1, %4
%6 = icmp sgt i64 %5, 255
%7 = zext i1 %6 to i64
%8 = shl nuw nsw i64 %7, 3
%9 = lshr i64 %5, %8
%10 = or i64 %8, %4
%11 = icmp sgt i64 %9, 15
%12 = zext i1 %11 to i64
%13 = shl nuw nsw i64 %12, 2
%14 = lshr i64 %9, %13
%15 = or i64 %10, %13
%16 = icmp sgt i64 %14, 3
%17 = zext i1 %16 to i64
%18 = shl nuw nsw i64 %17, 1
%19 = lshr i64 %14, %18
%20 = or i64 %15, %18
%21 = icmp sgt i64 %19, 1
%22 = zext i1 %21 to i64
%23 = or i64 %20, %22
%24 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %24)
store i64 %23, i64* %"@x_key", align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%lookup_elem = call i8* inttoptr (i64 1 to i8* (i8*, i8*)*)(i64 %pseudo, i64* nonnull %"@x_key")
%map_lookup_cond = icmp eq i8* %lookup_elem, null
br i1 %map_lookup_cond, label %lookup_merge, label %lookup_success
lookup_success: ; preds = %entry
%25 = load i64, i8* %lookup_elem, align 8
%phitmp = add i64 %25, 1
br label %lookup_merge
lookup_merge: ; preds = %entry, %lookup_success
%lookup_elem_val.0 = phi i64 [ %phitmp, %lookup_success ], [ 1, %entry ]
%26 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %26)
store i64 %lookup_elem_val.0, i64* %"@x_val", align 8
%pseudo1 = call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo1, i64* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %24)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %26)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, call_count)
{
test("kprobe:f { @x = count() }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%1 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
store i64 0, i64* %"@x_key", align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%lookup_elem = call i8* inttoptr (i64 1 to i8* (i8*, i8*)*)(i64 %pseudo, i64* nonnull %"@x_key")
%map_lookup_cond = icmp eq i8* %lookup_elem, null
br i1 %map_lookup_cond, label %lookup_merge, label %lookup_success
lookup_success: ; preds = %entry
%2 = load i64, i8* %lookup_elem, align 8
%phitmp = add i64 %2, 1
br label %lookup_merge
lookup_merge: ; preds = %entry, %lookup_success
%lookup_elem_val.0 = phi i64 [ %phitmp, %lookup_success ], [ 1, %entry ]
%3 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %3)
store i64 %lookup_elem_val.0, i64* %"@x_val", align 8
%pseudo1 = call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo1, i64* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %3)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, call_str)
{
test("kprobe:f { @x = str(arg0) }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8*) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_key" = alloca i64, align 8
%arg0 = alloca i64, align 8
%str = alloca [64 x i8], align 1
%1 = getelementptr inbounds [64 x i8], [64 x i8]* %str, i64 0, i64 0
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
call void @llvm.memset.p0i8.i64(i8* nonnull %1, i8 0, i64 64, i32 1, i1 false)
%2 = bitcast i64* %arg0 to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %2)
%3 = getelementptr i8, i8* %0, i64 112
%probe_read = call i64 inttoptr (i64 4 to i64 (i8*, i64, i8*)*)(i64* nonnull %arg0, i64 8, i8* %3)
%4 = load i64, i64* %arg0, align 8
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %2)
%probe_read_str = call i64 inttoptr (i64 45 to i64 (i8*, i64, i8*)*)([64 x i8]* nonnull %str, i64 64, i64 %4)
%5 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %5)
store i64 0, i64* %"@x_key", align 8
%pseudo = call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", [64 x i8]* nonnull %str, i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %5)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.memset.p0i8.i64(i8* nocapture writeonly, i8, i64, i32, i1) #1
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, call_delete)
{
test("kprobe:f { @x = 1; delete(@x) }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_key1" = alloca i64, align 8
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%1 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
store i64 0, i64* %"@x_key", align 8
%2 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %2)
store i64 1, i64* %"@x_val", align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %2)
%3 = bitcast i64* %"@x_key1" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %3)
store i64 0, i64* %"@x_key1", align 8
%pseudo2 = call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%delete_elem = call i64 inttoptr (i64 3 to i64 (i8*, i8*)*)(i64 %pseudo2, i64* nonnull %"@x_key1")
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %3)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, call_printf)
{
test("kprobe:f { printf(\"hello\\n\") }",
R"EXPECTED(%printf_t = type { i64 }
; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8*) local_unnamed_addr section "s_kprobe:f" {
entry:
%printf_args = alloca %printf_t, align 8
%1 = bitcast %printf_t* %printf_args to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
store i64 0, %printf_t* %printf_args, align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%get_cpu_id = tail call i64 inttoptr (i64 8 to i64 ()*)()
%perf_event_output = call i64 inttoptr (i64 25 to i64 (i8*, i8*, i64, i8*, i64)*)(i8* %0, i64 %pseudo, i64 %get_cpu_id, %printf_t* nonnull %printf_args, i64 8)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, int_propagation)
{
test("kprobe:f { @x = 1234; @y = @x }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@y_val" = alloca i64, align 8
%"@y_key" = alloca i64, align 8
%"@x_key1" = alloca i64, align 8
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%1 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
store i64 0, i64* %"@x_key", align 8
%2 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %2)
store i64 1234, i64* %"@x_val", align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %2)
%3 = bitcast i64* %"@x_key1" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %3)
store i64 0, i64* %"@x_key1", align 8
%pseudo2 = call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%lookup_elem = call i8* inttoptr (i64 1 to i8* (i8*, i8*)*)(i64 %pseudo2, i64* nonnull %"@x_key1")
%map_lookup_cond = icmp eq i8* %lookup_elem, null
br i1 %map_lookup_cond, label %lookup_merge, label %lookup_success
lookup_success: ; preds = %entry
%4 = load i64, i8* %lookup_elem, align 8
br label %lookup_merge
lookup_merge: ; preds = %entry, %lookup_success
%lookup_elem_val.0 = phi i64 [ %4, %lookup_success ], [ 0, %entry ]
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %3)
%5 = bitcast i64* %"@y_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %5)
store i64 0, i64* %"@y_key", align 8
%6 = bitcast i64* %"@y_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %6)
store i64 %lookup_elem_val.0, i64* %"@y_val", align 8
%pseudo3 = call i64 @llvm.bpf.pseudo(i64 1, i64 2)
%update_elem4 = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo3, i64* nonnull %"@y_key", i64* nonnull %"@y_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %5)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %6)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, string_propagation)
{
test("kprobe:f { @x = \"asdf\"; @y = @x }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@y_key" = alloca i64, align 8
%lookup_elem_val = alloca [64 x i8], align 1
%"@x_key1" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%str = alloca [64 x i8], align 1
%1 = getelementptr inbounds [64 x i8], [64 x i8]* %str, i64 0, i64 0
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
store i8 97, i8* %1, align 1
%str.repack5 = getelementptr inbounds [64 x i8], [64 x i8]* %str, i64 0, i64 1
store i8 115, i8* %str.repack5, align 1
%str.repack6 = getelementptr inbounds [64 x i8], [64 x i8]* %str, i64 0, i64 2
store i8 100, i8* %str.repack6, align 1
%str.repack7 = getelementptr inbounds [64 x i8], [64 x i8]* %str, i64 0, i64 3
store i8 102, i8* %str.repack7, align 1
%str.repack8 = getelementptr inbounds [64 x i8], [64 x i8]* %str, i64 0, i64 4
%2 = bitcast i64* %"@x_key" to i8*
call void @llvm.memset.p0i8.i64(i8* %str.repack8, i8 0, i64 60, i32 1, i1 false)
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %2)
store i64 0, i64* %"@x_key", align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", [64 x i8]* nonnull %str, i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %2)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
%3 = bitcast i64* %"@x_key1" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %3)
store i64 0, i64* %"@x_key1", align 8
%pseudo2 = call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%lookup_elem = call i8* inttoptr (i64 1 to i8* (i8*, i8*)*)(i64 %pseudo2, i64* nonnull %"@x_key1")
%4 = getelementptr inbounds [64 x i8], [64 x i8]* %lookup_elem_val, i64 0, i64 0
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %4)
%map_lookup_cond = icmp eq i8* %lookup_elem, null
br i1 %map_lookup_cond, label %lookup_failure, label %lookup_success
lookup_success: ; preds = %entry
call void @llvm.memcpy.p0i8.p0i8.i64(i8* nonnull %4, i8* nonnull %lookup_elem, i64 64, i32 1, i1 false)
br label %lookup_merge
lookup_failure: ; preds = %entry
call void @llvm.memset.p0i8.i64(i8* nonnull %4, i8 0, i64 64, i32 1, i1 false)
br label %lookup_merge
lookup_merge: ; preds = %lookup_failure, %lookup_success
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %3)
%5 = bitcast i64* %"@y_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %5)
store i64 0, i64* %"@y_key", align 8
%pseudo3 = call i64 @llvm.bpf.pseudo(i64 1, i64 2)
%update_elem4 = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo3, i64* nonnull %"@y_key", [64 x i8]* nonnull %lookup_elem_val, i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %5)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %4)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
; Function Attrs: argmemonly nounwind
declare void @llvm.memcpy.p0i8.p0i8.i64(i8* nocapture writeonly, i8* nocapture readonly, i64, i32, i1) #1
; Function Attrs: argmemonly nounwind
declare void @llvm.memset.p0i8.i64(i8* nocapture writeonly, i8, i64, i32, i1) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, pred_binop)
{
test("kprobe:f / pid == 1234 / { @x = 1 }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%get_pid_tgid = tail call i64 inttoptr (i64 14 to i64 ()*)()
%.mask = and i64 %get_pid_tgid, -4294967296
%1 = icmp eq i64 %.mask, 5299989643264
br i1 %1, label %pred_true, label %pred_false
pred_false: ; preds = %entry
ret i64 0
pred_true: ; preds = %entry
%2 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %2)
store i64 0, i64* %"@x_key", align 8
%3 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %3)
store i64 1, i64* %"@x_val", align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %2)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %3)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, variable)
{
test("kprobe:f { $var = comm; @x = $var; @y = $var }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@y_key" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%comm = alloca [64 x i8], align 1
%1 = getelementptr inbounds [64 x i8], [64 x i8]* %comm, i64 0, i64 0
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
call void @llvm.memset.p0i8.i64(i8* nonnull %1, i8 0, i64 64, i32 1, i1 false)
%get_comm = call i64 inttoptr (i64 16 to i64 (i8*, i64)*)([64 x i8]* nonnull %comm, i64 64)
%2 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %2)
store i64 0, i64* %"@x_key", align 8
%pseudo = call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", [64 x i8]* nonnull %comm, i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %2)
%3 = bitcast i64* %"@y_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %3)
store i64 0, i64* %"@y_key", align 8
%pseudo1 = call i64 @llvm.bpf.pseudo(i64 1, i64 2)
%update_elem2 = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo1, i64* nonnull %"@y_key", [64 x i8]* nonnull %comm, i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %3)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.memset.p0i8.i64(i8* nocapture writeonly, i8, i64, i32, i1) #1
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, dereference)
{
test("kprobe:f { @x = *1234 }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%deref = alloca i64, align 8
%1 = bitcast i64* %deref to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
%probe_read = call i64 inttoptr (i64 4 to i64 (i8*, i64, i8*)*)(i64* nonnull %deref, i64 8, i64 1234)
%2 = load i64, i64* %deref, align 8
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
%3 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %3)
store i64 0, i64* %"@x_key", align 8
%4 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %4)
store i64 %2, i64* %"@x_val", align 8
%pseudo = call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %3)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %4)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, logical_or)
{
test("kprobe:f { @x = pid == 1234 || pid == 1235 }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%get_pid_tgid = tail call i64 inttoptr (i64 14 to i64 ()*)()
%.mask = and i64 %get_pid_tgid, -4294967296
%1 = icmp eq i64 %.mask, 5299989643264
br i1 %1, label %"||_true", label %"||_lhs_false"
"||_lhs_false": ; preds = %entry
%get_pid_tgid1 = tail call i64 inttoptr (i64 14 to i64 ()*)()
%.mask2 = and i64 %get_pid_tgid1, -4294967296
%2 = icmp eq i64 %.mask2, 5304284610560
br i1 %2, label %"||_true", label %"||_merge"
"||_true": ; preds = %"||_lhs_false", %entry
br label %"||_merge"
"||_merge": ; preds = %"||_lhs_false", %"||_true"
%"||_result.0" = phi i64 [ 1, %"||_true" ], [ 0, %"||_lhs_false" ]
%3 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %3)
store i64 0, i64* %"@x_key", align 8
%4 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %4)
store i64 %"||_result.0", i64* %"@x_val", align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %3)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %4)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, logical_and)
{
test("kprobe:f { @x = pid != 1234 && pid != 1235 }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%get_pid_tgid = tail call i64 inttoptr (i64 14 to i64 ()*)()
%.mask = and i64 %get_pid_tgid, -4294967296
%1 = icmp eq i64 %.mask, 5299989643264
br i1 %1, label %"&&_false", label %"&&_lhs_true"
"&&_lhs_true": ; preds = %entry
%get_pid_tgid1 = tail call i64 inttoptr (i64 14 to i64 ()*)()
%.mask2 = and i64 %get_pid_tgid1, -4294967296
%2 = icmp eq i64 %.mask2, 5304284610560
br i1 %2, label %"&&_false", label %"&&_merge"
"&&_false": ; preds = %"&&_lhs_true", %entry
br label %"&&_merge"
"&&_merge": ; preds = %"&&_lhs_true", %"&&_false"
%"&&_result.0" = phi i64 [ 0, %"&&_false" ], [ 1, %"&&_lhs_true" ]
%3 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %3)
store i64 0, i64* %"@x_key", align 8
%4 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %4)
store i64 %"&&_result.0", i64* %"@x_val", align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %3)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %4)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
} // namespace codegen
} // namespace test
} // namespace bpftrace
| 38.253012 | 161 | 0.657618 | ajor |
067d73d95df0b29938dd67d299227f270e8608d1 | 6,695 | inl | C++ | Library/Sources/Stroika/Foundation/Execution/WaitForIOReady.inl | SophistSolutions/Stroika | f4e5d84767903a054fba0a6b9c7c4bd1aaefd105 | [
"MIT"
] | 28 | 2015-09-22T21:43:32.000Z | 2022-02-28T01:35:01.000Z | Library/Sources/Stroika/Foundation/Execution/WaitForIOReady.inl | SophistSolutions/Stroika | f4e5d84767903a054fba0a6b9c7c4bd1aaefd105 | [
"MIT"
] | 98 | 2015-01-22T03:21:27.000Z | 2022-03-02T01:47:00.000Z | Library/Sources/Stroika/Foundation/Execution/WaitForIOReady.inl | SophistSolutions/Stroika | f4e5d84767903a054fba0a6b9c7c4bd1aaefd105 | [
"MIT"
] | 4 | 2019-02-21T16:45:25.000Z | 2022-02-18T13:40:04.000Z | /*
* Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved
*/
#ifndef _Stroika_Foundation_Execution_WaitForIOReady_inl_
#define _Stroika_Foundation_Execution_WaitForIOReady_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include "TimeOutException.h"
namespace Stroika::Foundation::Execution {
/*
********************************************************************************
************************** Execution::WaitForIOReady ***************************
********************************************************************************
*/
template <typename T, typename TRAITS>
inline WaitForIOReady<T, TRAITS>::WaitForIOReady (const Traversal::Iterable<pair<T, TypeOfMonitorSet>>& fds, optional<pair<SDKPollableType, TypeOfMonitorSet>> pollable2Wakeup)
// Containers::Collection{} to force CLONE/FREEZE of data, since elsewise it chould change without this class knowing (iterables not necessarily COW)
: fPollData_{Containers::Collection<pair<T, TypeOfMonitorSet>>{fds}}
, fPollable2Wakeup_{pollable2Wakeup}
{
//DbgTrace (L"WaitForIOReady::CTOR (%s, %s)", Characters::ToString (fds).c_str (), Characters::ToString (pollable2Wakeup).c_str ());
}
template <typename T, typename TRAITS>
WaitForIOReady<T, TRAITS>::WaitForIOReady (const Traversal::Iterable<T>& fds, const TypeOfMonitorSet& flags, optional<pair<SDKPollableType, TypeOfMonitorSet>> pollable2Wakeup)
: WaitForIOReady{fds.template Select<pair<T, TypeOfMonitorSet>> ([&] (const T& t) { return make_pair (t, flags); }), pollable2Wakeup}
{
}
template <typename T, typename TRAITS>
WaitForIOReady<T, TRAITS>::WaitForIOReady (T fd, const TypeOfMonitorSet& flags, optional<pair<SDKPollableType, TypeOfMonitorSet>> pollable2Wakeup)
: WaitForIOReady{Containers::Collection<pair<T, TypeOfMonitorSet>>{make_pair (fd, flags)}, pollable2Wakeup}
{
}
template <typename T, typename TRAITS>
inline auto WaitForIOReady<T, TRAITS>::GetDescriptors () const -> Traversal::Iterable<pair<T, TypeOfMonitorSet>>
{
return fPollData_;
}
template <typename T, typename TRAITS>
inline auto WaitForIOReady<T, TRAITS>::Wait (Time::DurationSecondsType waitFor) -> Containers::Set<T>
{
return WaitUntil (waitFor + Time::GetTickCount ());
}
template <typename T, typename TRAITS>
inline auto WaitForIOReady<T, TRAITS>::Wait (const Time::Duration& waitFor) -> Containers::Set<T>
{
return WaitUntil (waitFor.As<Time::DurationSecondsType> () + Time::GetTickCount ());
}
template <typename T, typename TRAITS>
inline auto WaitForIOReady<T, TRAITS>::WaitQuietly (Time::DurationSecondsType waitFor) -> Containers::Set<T>
{
return WaitQuietlyUntil (waitFor + Time::GetTickCount ());
}
template <typename T, typename TRAITS>
inline auto WaitForIOReady<T, TRAITS>::WaitQuietly (const Time::Duration& waitFor) -> Containers::Set<T>
{
return WaitQuietly (waitFor.As<Time::DurationSecondsType> ());
}
template <typename T, typename TRAITS>
auto WaitForIOReady<T, TRAITS>::WaitUntil (Time::DurationSecondsType timeoutAt) -> Containers::Set<T>
{
Containers::Set<T> result = WaitQuietlyUntil (timeoutAt);
if (result.empty ()) {
Execution::ThrowTimeoutExceptionAfter (timeoutAt); // maybe returning 0 entries without timeout, because of fPollable2Wakeup_
}
return result;
}
template <typename T, typename TRAITS>
auto WaitForIOReady<T, TRAITS>::WaitQuietlyUntil (Time::DurationSecondsType timeoutAt) -> Containers::Set<T>
{
Thread::CheckForInterruption ();
vector<pair<SDKPollableType, TypeOfMonitorSet>> pollBuffer;
vector<T> mappedObjectBuffer;
// @todo REDO THIS calling FillBuffer_ from CTOR (since always used at least once, but could be more than once.
FillBuffer_ (&pollBuffer, &mappedObjectBuffer);
Assert (pollBuffer.size () == mappedObjectBuffer.size () or pollBuffer.size () == mappedObjectBuffer.size () + 1);
Containers::Set<T> result;
for (size_t i : _WaitQuietlyUntil (Containers::Start (pollBuffer), Containers::End (pollBuffer), timeoutAt)) {
if (i == mappedObjectBuffer.size ()) {
Assert (fPollable2Wakeup_); // externally signalled to wakeup
}
else {
Assert (i < mappedObjectBuffer.size ());
result.Add (mappedObjectBuffer[i]);
}
}
return result;
}
template <typename T, typename TRAITS>
void WaitForIOReady<T, TRAITS>::FillBuffer_ (vector<pair<SDKPollableType, TypeOfMonitorSet>>* pollBuffer, vector<T>* mappedObjectBuffer)
{
RequireNotNull (pollBuffer);
RequireNotNull (mappedObjectBuffer);
Require (pollBuffer->size () == 0);
Require (mappedObjectBuffer->size () == 0);
pollBuffer->reserve (fPollData_.size ());
mappedObjectBuffer->reserve (fPollData_.size ());
for (const auto& i : fPollData_) {
pollBuffer->push_back (pair<SDKPollableType, TypeOfMonitorSet>{TRAITS::GetSDKPollable (i.first), i.second});
mappedObjectBuffer->push_back (i.first);
}
if (fPollable2Wakeup_) {
pollBuffer->push_back (pair<SDKPollableType, TypeOfMonitorSet>{fPollable2Wakeup_.value ().first, fPollable2Wakeup_.value ().second});
}
}
}
namespace Stroika::Foundation::Configuration {
#if !qCompilerAndStdLib_template_specialization_internalErrorWithSpecializationSignifier_Buggy
template <>
#endif
constexpr EnumNames<Execution::WaitForIOReady_Support::WaitForIOReady_Base::TypeOfMonitor> DefaultNames<Execution::WaitForIOReady_Support::WaitForIOReady_Base::TypeOfMonitor>::k{
EnumNames<Execution::WaitForIOReady_Support::WaitForIOReady_Base::TypeOfMonitor>::BasicArrayInitializer{{
{Execution::WaitForIOReady_Support::WaitForIOReady_Base::TypeOfMonitor::eRead, L"Read"},
{Execution::WaitForIOReady_Support::WaitForIOReady_Base::TypeOfMonitor::eWrite, L"Write"},
{Execution::WaitForIOReady_Support::WaitForIOReady_Base::TypeOfMonitor::eError, L"Error"},
{Execution::WaitForIOReady_Support::WaitForIOReady_Base::TypeOfMonitor::eHUP, L"HUP"},
}}};
}
#endif /*_Stroika_Foundation_Execution_WaitForIOReady_inl_*/
| 51.899225 | 182 | 0.645706 | SophistSolutions |
067f9303e31723e091d394718084d79cb76f3bd0 | 950 | cpp | C++ | sociality_model_cpp/main.cpp | pratikunterwegs/pathomove | be6b509442d975909bae2a46cc01d94e74e32a41 | [
"MIT"
] | 1 | 2022-03-16T11:20:02.000Z | 2022-03-16T11:20:02.000Z | sociality_model_cpp/main.cpp | pratikunterwegs/pathomove | be6b509442d975909bae2a46cc01d94e74e32a41 | [
"MIT"
] | 1 | 2022-01-18T12:08:44.000Z | 2022-01-18T12:08:44.000Z | sociality_model_cpp/main.cpp | pratikunterwegs/pathomove | be6b509442d975909bae2a46cc01d94e74e32a41 | [
"MIT"
] | 1 | 2022-01-18T20:29:28.000Z | 2022-01-18T20:29:28.000Z | #include <vector>
#include <random>
#include <cassert>
#include <iostream>
#include <fstream>
#include <algorithm>
#include "../src/simulations.hpp"
int main(int argc, char *argv[])
{
// process cliargs
std::vector<std::string> cliArgs(argv, argv+argc);
int nFood = 5;
float landsize = 5.0f;
int foodClusters = 2;
float clusterDispersal = 1.0f;
int popsize = 5;
int genmax = 1;
int tmax = 2;
int regen_time = 1;
// prepare landscape
Resources food (nFood, landsize, foodClusters, clusterDispersal, regen_time);
food.initResources();
food.countAvailable();
std::cout << "landscape with " << foodClusters << " clusters\n";
/// export landscape
// prepare population
Population pop (popsize, 0.1, 0.2, 1, 0.3);
// pop.initPop(popsize);
pop.setTrait();
std::cout << pop.nAgents << " agents over " << genmax << " gens of " << tmax << " timesteps\n";
return 0;
}
| 25 | 99 | 0.624211 | pratikunterwegs |
068288a499f0ade39ee6376837103bf8af844898 | 536 | cpp | C++ | PkTex-Atlas/jni/MPACK/Graphics/Texture/Image/PPMImage.cpp | links234/PkTex | 8f2d33e0794e57c33305c2eceab11f6f53f0aeee | [
"Apache-2.0"
] | null | null | null | PkTex-Atlas/jni/MPACK/Graphics/Texture/Image/PPMImage.cpp | links234/PkTex | 8f2d33e0794e57c33305c2eceab11f6f53f0aeee | [
"Apache-2.0"
] | null | null | null | PkTex-Atlas/jni/MPACK/Graphics/Texture/Image/PPMImage.cpp | links234/PkTex | 8f2d33e0794e57c33305c2eceab11f6f53f0aeee | [
"Apache-2.0"
] | null | null | null | #include "PNGImage.hpp"
#include <png.h>
#include "Image.hpp"
#include "Resources.hpp"
#include "Misc.hpp"
#include "Log.hpp"
using namespace MPACK::Core;
namespace MPACK
{
namespace Graphics
{
ReturnValue LoadPPM(Image *image, const std::string &path, bool flipForOpenGL)
{
LOGE("LoadPPM() error: not implemented");
return RETURN_VALUE_KO;
}
ReturnValue SavePPM(Image *image, const std::string &path)
{
LOGE("SavePPM() error: not implemented");
return RETURN_VALUE_KO;
}
}
}
| 18.482759 | 81 | 0.662313 | links234 |
0682d37d47eaa856a5c355dad4cd19f37b1362e4 | 23,594 | cpp | C++ | testing/core/CreateTestStructure.cpp | MIC-DKFZ/RTTB | 8b772501fd3fffcb67233a9307661b03dff72785 | [
"BSD-3-Clause"
] | 18 | 2018-04-19T12:57:32.000Z | 2022-03-12T17:43:02.000Z | testing/core/CreateTestStructure.cpp | MIC-DKFZ/RTTB | 8b772501fd3fffcb67233a9307661b03dff72785 | [
"BSD-3-Clause"
] | null | null | null | testing/core/CreateTestStructure.cpp | MIC-DKFZ/RTTB | 8b772501fd3fffcb67233a9307661b03dff72785 | [
"BSD-3-Clause"
] | 7 | 2018-06-24T21:09:56.000Z | 2021-09-09T09:30:49.000Z | // -----------------------------------------------------------------------
// RTToolbox - DKFZ radiotherapy quantitative evaluation library
//
// Copyright (c) German Cancer Research Center (DKFZ),
// Software development for Integrated Diagnostics and Therapy (SIDT).
// ALL RIGHTS RESERVED.
// See rttbCopyright.txt or
// http://www.dkfz.de/en/sidt/projects/rttb/copyright.html
//
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notices for more information.
//
//------------------------------------------------------------------------
// this file defines the rttbCoreTests for the test driver
// and all it expects is that you have a function called RegisterTests
#include <math.h>
#include "CreateTestStructure.h"
#include "rttbNullPointerException.h"
#include "rttbInvalidParameterException.h"
#include "rttbInvalidDoseException.h"
namespace rttb
{
namespace testing
{
CreateTestStructure::~CreateTestStructure() {}
CreateTestStructure::CreateTestStructure(const core::GeometricInfo& aGeoInfo)
{
_geoInfo = aGeoInfo;
}
PolygonType CreateTestStructure::createPolygonLeftUpper(std::vector<VoxelGridIndex2D> aVoxelVector,
GridIndexType sliceNumber)
{
PolygonType polygon;
for (size_t i = 0; i < aVoxelVector.size(); i++)
{
VoxelGridIndex3D voxelIndex;
voxelIndex(0) = (aVoxelVector.at(i)).x();
voxelIndex(1) = (aVoxelVector.at(i)).y();
voxelIndex(2) = sliceNumber;
WorldCoordinate3D p1;
_geoInfo.indexToWorldCoordinate(voxelIndex, p1);
polygon.push_back(p1);
std::cout << "(" << p1.x() << "," << p1.y() << "," << p1.z() << ")" << "; ";
}
std::cout << std::endl;
return polygon;
}
PolygonType CreateTestStructure::createPolygonCenter(std::vector<VoxelGridIndex2D> aVoxelVector,
GridIndexType sliceNumber)
{
PolygonType polygon;
for (size_t i = 0; i < aVoxelVector.size(); i++)
{
VoxelGridIndex3D voxelIndex;
voxelIndex(0) = (aVoxelVector.at(i)).x();
voxelIndex(1) = (aVoxelVector.at(i)).y();
voxelIndex(2) = sliceNumber;
WorldCoordinate3D p1;
_geoInfo.indexToWorldCoordinate(voxelIndex, p1);
WorldCoordinate3D p;
p(0) = p1.x() ;
p(1) = p1.y() ;
//This can be done directly for x/y coordinates, but not for z. Thus, we do it in this function.
p(2) = p1.z() - _geoInfo.getSpacing().z() / 2;
polygon.push_back(p);
}
return polygon;
}
PolygonType CreateTestStructure::createPolygonCenterOnPlaneCenter(std::vector<VoxelGridIndex2D> aVoxelVector,
GridIndexType sliceNumber)
{
PolygonType polygon;
for (size_t i = 0; i < aVoxelVector.size(); i++)
{
VoxelGridIndex3D voxelIndex;
ContinuousVoxelGridIndex3D indexDouble = ContinuousVoxelGridIndex3D((aVoxelVector.at(i)).x(), (aVoxelVector.at(i)).y(),
sliceNumber);
WorldCoordinate3D p1;
_geoInfo.continuousIndexToWorldCoordinate(indexDouble, p1);
polygon.push_back(p1);
}
return polygon;
}
PolygonType CreateTestStructure::createPolygonBetweenUpperLeftAndCenter(
std::vector<VoxelGridIndex2D> aVoxelVector, GridIndexType sliceNumber)
{
PolygonType polygon;
for (size_t i = 0; i < aVoxelVector.size(); i++)
{
VoxelGridIndex3D voxelIndex;
voxelIndex(0) = (aVoxelVector.at(i)).x();
voxelIndex(1) = (aVoxelVector.at(i)).y();
voxelIndex(2) = sliceNumber;
WorldCoordinate3D p1;
_geoInfo.indexToWorldCoordinate(voxelIndex, p1);
SpacingVectorType3D delta = _geoInfo.getSpacing();
WorldCoordinate3D p;
p(0) = p1.x() + delta.x() / 4;
p(1) = p1.y() + delta.y() / 4;
p(2) = p1.z();
polygon.push_back(p);
std::cout << "(" << p.x() << "," << p.y() << "," << p.z() << ")" << "; ";
}
std::cout << std::endl;
return polygon;
}
PolygonType CreateTestStructure::createPolygonBetweenLowerRightAndCenter(
std::vector<VoxelGridIndex2D> aVoxelVector, GridIndexType sliceNumber)
{
PolygonType polygon;
for (size_t i = 0; i < aVoxelVector.size(); i++)
{
VoxelGridIndex3D voxelIndex;
voxelIndex(0) = (aVoxelVector.at(i)).x();
voxelIndex(1) = (aVoxelVector.at(i)).y();
voxelIndex(2) = sliceNumber;
WorldCoordinate3D p1;
_geoInfo.indexToWorldCoordinate(voxelIndex, p1);
SpacingVectorType3D delta = _geoInfo.getSpacing();
WorldCoordinate3D p;
p(0) = p1.x() + delta.x() * 0.75;
p(1) = p1.y() + delta.y() * 0.75;
p(2) = p1.z();
polygon.push_back(p);
std::cout << "(" << p.x() << "," << p.y() << "," << p.z() << ")" << "; ";
}
std::cout << std::endl;
return polygon;
}
PolygonType CreateTestStructure::createPolygonLeftEdgeMiddle(std::vector<VoxelGridIndex2D>
aVoxelVector, GridIndexType sliceNumber)
{
PolygonType polygon;
for (size_t i = 0; i < aVoxelVector.size(); i++)
{
VoxelGridIndex3D voxelIndex;
voxelIndex(0) = (aVoxelVector.at(i)).x();
voxelIndex(1) = (aVoxelVector.at(i)).y();
voxelIndex(2) = sliceNumber;
WorldCoordinate3D p1;
_geoInfo.indexToWorldCoordinate(voxelIndex, p1);
SpacingVectorType3D delta = _geoInfo.getSpacing();
WorldCoordinate3D p;
p(0) = p1.x();
p(1) = p1.y() + delta.y() * 0.5;
p(2) = p1.z();
polygon.push_back(p);
std::cout << "(" << p.x() << "," << p.y() << "," << p.z() << ")" << "; ";
}
std::cout << std::endl;
return polygon;
}
PolygonType CreateTestStructure::createPolygonUpperCenter(std::vector<VoxelGridIndex2D>
aVoxelVector, GridIndexType sliceNumber)
{
PolygonType polygon;
for (size_t i = 0; i < aVoxelVector.size(); i++)
{
VoxelGridIndex3D voxelIndex;
voxelIndex(0) = (aVoxelVector.at(i)).x();
voxelIndex(1) = (aVoxelVector.at(i)).y();
voxelIndex(2) = sliceNumber;
WorldCoordinate3D p1;
_geoInfo.indexToWorldCoordinate(voxelIndex, p1);
SpacingVectorType3D delta = _geoInfo.getSpacing();
WorldCoordinate3D p;
p(0) = p1.x() + delta.x() * 0.5;
p(1) = p1.y();
p(2) = p1.z();
polygon.push_back(p);
std::cout << "(" << p.x() << "," << p.y() << "," << p.z() << ")" << "; ";
}
std::cout << std::endl;
return polygon;
}
PolygonType CreateTestStructure::createPolygonIntermediatePoints(std::vector<VoxelGridIndex2D>
aVoxelVector, GridIndexType sliceNumber)
{
PolygonType polygon;
for (size_t i = 0; i < aVoxelVector.size(); i++)
{
VoxelGridIndex3D voxelIndex;
VoxelGridIndex3D voxelIndex2;
voxelIndex(0) = (aVoxelVector.at(i)).x();
voxelIndex(1) = (aVoxelVector.at(i)).y();
voxelIndex(2) = sliceNumber;
if (i < (aVoxelVector.size() - 1))
{
voxelIndex2(0) = (aVoxelVector.at(i + 1)).x();
voxelIndex2(1) = (aVoxelVector.at(i + 1)).y();
voxelIndex2(2) = sliceNumber;
}
else
{
voxelIndex2(0) = (aVoxelVector.at(0)).x();
voxelIndex2(1) = (aVoxelVector.at(0)).y();
voxelIndex2(2) = sliceNumber;
}
WorldCoordinate3D p1;
_geoInfo.indexToWorldCoordinate(voxelIndex, p1);
SpacingVectorType3D delta = _geoInfo.getSpacing();
WorldCoordinate3D p2;
_geoInfo.indexToWorldCoordinate(voxelIndex2, p2);
SpacingVectorType3D delta2 = _geoInfo.getSpacing();
WorldCoordinate3D wp1;
wp1(0) = p1.x() + delta.x() * 0.75;
wp1(1) = p1.y() + delta.y() * 0.75;
wp1(2) = p1.z();
WorldCoordinate3D wp2;
wp2(0) = p2.x() + delta.x() * 0.75;
wp2(1) = p2.y() + delta.y() * 0.75;
wp2(2) = p2.z();
polygon.push_back(wp1);
double diffX = (wp2.x() - wp1.x()) / 1000.0;
double diffY = (wp2.y() - wp1.y()) / 1000.0;
WorldCoordinate3D wp_intermediate;
wp_intermediate(0) = 0;
wp_intermediate(1) = 0;
for (int j = 0; j < 1000; j++)
{
wp_intermediate(0) = wp1.x() + j * diffX;
wp_intermediate(1) = wp1.y() + j * diffY;
polygon.push_back(wp_intermediate);
}
}
std::cout << std::endl;
return polygon;
}
PolygonType CreateTestStructure::createPolygonCircle(std::vector<VoxelGridIndex2D> aVoxelVector,
GridIndexType sliceNumber)
{
PolygonType polygon;
if (aVoxelVector.size() > 0)
{
unsigned int i = 0;
VoxelGridIndex3D voxelIndex;
voxelIndex(0) = (aVoxelVector.at(i)).x();
voxelIndex(1) = (aVoxelVector.at(i)).y();
voxelIndex(2) = sliceNumber;
WorldCoordinate3D p1;
_geoInfo.indexToWorldCoordinate(voxelIndex, p1);
SpacingVectorType3D delta = _geoInfo.getSpacing();
WorldCoordinate3D wp1;
wp1(0) = p1.x();
wp1(1) = p1.y();
wp1(2) = p1.z();
WorldCoordinate3D wp_intermediate;
wp_intermediate(0) = 0;
wp_intermediate(1) = 0;
wp_intermediate(2) = p1.z();
double radius = 2 * delta.x();
double frac_radius = (radius * 0.001);
double correct_y = (delta.x() / delta.y());
for (unsigned int j = 0; j <= 1000; j++)
{
double y_offset = sqrt((radius * radius) - ((frac_radius * j) * (frac_radius * j)));
wp_intermediate(0) = wp1.x() + frac_radius * j;
wp_intermediate(1) = wp1.y() - (y_offset * correct_y);
polygon.push_back(wp_intermediate);
}
for (unsigned int j = 1000; j <= 1000; j--)
{
double y_offset = sqrt((radius * radius) - ((frac_radius * j) * (frac_radius * j)));
wp_intermediate(0) = wp1.x() + frac_radius * j;
wp_intermediate(1) = wp1.y() + (y_offset * correct_y);
polygon.push_back(wp_intermediate);
}
for (unsigned int j = 0; j <= 1000; j++)
{
double y_offset = sqrt((radius * radius) - ((frac_radius * j) * (frac_radius * j)));
wp_intermediate(0) = wp1.x() - frac_radius * j;
wp_intermediate(1) = wp1.y() + y_offset * correct_y;
polygon.push_back(wp_intermediate);
}
for (unsigned int j = 1000; j <= 1000; j--)
{
double y_offset = sqrt((radius * radius) - ((frac_radius * j) * (frac_radius * j)));
wp_intermediate(0) = wp1.x() + frac_radius * j;
wp_intermediate(1) = wp1.y() + (y_offset * correct_y);
polygon.push_back(wp_intermediate);
}
}
std::cout << std::endl;
return polygon;
}
PolygonType CreateTestStructure::createStructureSeveralSectionsInsideOneVoxelA(
std::vector<VoxelGridIndex2D> aVoxelVector, GridIndexType sliceNumber)
{
PolygonType polygon;
if (aVoxelVector.size() > 0)
{
int i = 0;
VoxelGridIndex3D voxelIndex;
voxelIndex(0) = (aVoxelVector.at(i)).x();
voxelIndex(1) = (aVoxelVector.at(i)).y();
voxelIndex(2) = sliceNumber;
WorldCoordinate3D p1;
_geoInfo.indexToWorldCoordinate(voxelIndex, p1);
SpacingVectorType3D delta = _geoInfo.getSpacing();
WorldCoordinate3D wp1;
wp1(0) = p1.x();
wp1(1) = p1.y();
wp1(2) = p1.z();
WorldCoordinate3D wp_intermediate;
wp_intermediate(0) = 0;
wp_intermediate(1) = 0;
wp_intermediate(2) = p1.z();
wp_intermediate(0) = wp1.x() + (delta.x() * 0.25);
wp_intermediate(1) = wp1.y() + (delta.y() * 0.75);
polygon.push_back(wp_intermediate);
wp_intermediate(0) = wp1.x() + (delta.x() * 0.25);
wp_intermediate(1) = wp1.y() + (delta.y() * 2.75);
polygon.push_back(wp_intermediate);
wp_intermediate(0) = wp1.x() + (delta.x() * 0.5);
wp_intermediate(1) = wp1.y() + (delta.y() * 2.75);
polygon.push_back(wp_intermediate);
wp_intermediate(0) = wp1.x() + (delta.x() * 0.5);
wp_intermediate(1) = wp1.y() + (delta.y() * 0.75);
polygon.push_back(wp_intermediate);
wp_intermediate(0) = wp1.x() + (delta.x() * 0.75);
wp_intermediate(1) = wp1.y() + (delta.y() * 0.75);
polygon.push_back(wp_intermediate);
wp_intermediate(0) = wp1.x() + (delta.x() * 0.75);
wp_intermediate(1) = wp1.y() + (delta.y() * 2.75);
polygon.push_back(wp_intermediate);
wp_intermediate(0) = wp1.x() + (delta.x() * 1.0);
wp_intermediate(1) = wp1.y() + (delta.y() * 2.75);
polygon.push_back(wp_intermediate);
wp_intermediate(0) = wp1.x() + (delta.x() * 1.0);
wp_intermediate(1) = wp1.y() + (delta.y() * 0.75);
polygon.push_back(wp_intermediate);
wp_intermediate(0) = wp1.x() + (delta.x() * 1.25);
wp_intermediate(1) = wp1.y() + (delta.y() * 0.75);
polygon.push_back(wp_intermediate);
wp_intermediate(0) = wp1.x() + (delta.x() * 1.25);
wp_intermediate(1) = wp1.y() + (delta.y() * 2.75);
polygon.push_back(wp_intermediate);
wp_intermediate(0) = wp1.x() + (delta.x() * 1.5);
wp_intermediate(1) = wp1.y() + (delta.y() * 2.75);
polygon.push_back(wp_intermediate);
wp_intermediate(0) = wp1.x() + (delta.x() * 1.5);
wp_intermediate(1) = wp1.y() + (delta.y() * 0.75);
polygon.push_back(wp_intermediate);
wp_intermediate(0) = wp1.x() + (delta.x() * 1.75);
wp_intermediate(1) = wp1.y() + (delta.y() * 0.75);
polygon.push_back(wp_intermediate);
wp_intermediate(0) = wp1.x() + (delta.x() * 1.75);
wp_intermediate(1) = wp1.y() + (delta.y() * 3.0);
polygon.push_back(wp_intermediate);
wp_intermediate(0) = wp1.x();
wp_intermediate(1) = wp1.y() + (delta.y() * 3.0);
polygon.push_back(wp_intermediate);
wp_intermediate(0) = wp1.x();
wp_intermediate(1) = wp1.y() + (delta.y() * 3.0);
polygon.push_back(wp_intermediate);
wp_intermediate(0) = wp1.x();
wp_intermediate(1) = wp1.y() + (delta.y() * 0.75);
polygon.push_back(wp_intermediate);
}
std::cout << std::endl;
return polygon;
}
PolygonType CreateTestStructure::createStructureSelfTouchingA(std::vector<VoxelGridIndex2D>
aVoxelVector, GridIndexType sliceNumber)
{
PolygonType polygon;
if (aVoxelVector.size() > 0)
{
int i = 0;
VoxelGridIndex3D voxelIndex;
voxelIndex(0) = (aVoxelVector.at(i)).x();
voxelIndex(1) = (aVoxelVector.at(i)).y();
voxelIndex(2) = sliceNumber;
WorldCoordinate3D p1;
_geoInfo.indexToWorldCoordinate(voxelIndex, p1);
SpacingVectorType3D delta = _geoInfo.getSpacing();
WorldCoordinate3D wp1;
wp1(0) = p1.x();
wp1(1) = p1.y();
wp1(2) = p1.z();
WorldCoordinate3D wp_intermediate;
wp_intermediate(0) = 0;
wp_intermediate(1) = 0;
wp_intermediate(2) = p1.z();
wp_intermediate(0) = wp1.x();
wp_intermediate(1) = wp1.y() + (delta.y() * 0.5);
polygon.push_back(wp_intermediate);
wp_intermediate(0) = wp1.x() + (delta.x() * 0.5);
wp_intermediate(1) = wp1.y();
polygon.push_back(wp_intermediate);
wp_intermediate(0) = wp1.x() + (delta.x() * 0.5);
wp_intermediate(1) = wp1.y() + (delta.y() * 0.5);
polygon.push_back(wp_intermediate);
wp_intermediate(0) = wp1.x() + (delta.x() * 1.0);
wp_intermediate(1) = wp1.y() + (delta.y() * 0.5);
polygon.push_back(wp_intermediate);
wp_intermediate(0) = wp1.x() + (delta.x() * 1.0);
wp_intermediate(1) = wp1.y() + (delta.y() * 1.0);
polygon.push_back(wp_intermediate);
wp_intermediate(0) = wp1.x() + (delta.x() * 0.5);
wp_intermediate(1) = wp1.y() + (delta.y() * 1.0);
polygon.push_back(wp_intermediate);
wp_intermediate(0) = wp1.x() + (delta.x() * 0.5);
wp_intermediate(1) = wp1.y() + (delta.y() * 0.5);
polygon.push_back(wp_intermediate);
wp_intermediate(0) = wp1.x() + (delta.x() * 0.5);
wp_intermediate(1) = wp1.y() + (delta.y() * 1.0);
polygon.push_back(wp_intermediate);
wp_intermediate(0) = wp1.x();
wp_intermediate(1) = wp1.y() + (delta.y() * 0.5);
polygon.push_back(wp_intermediate);
}
std::cout << std::endl;
return polygon;
}
PolygonType CreateTestStructure::createStructureSelfTouchingB(std::vector<VoxelGridIndex2D>
aVoxelVector, GridIndexType sliceNumber)
{
PolygonType polygon;
if (aVoxelVector.size() > 0)
{
int i = 0;
VoxelGridIndex3D voxelIndex;
voxelIndex(0) = (aVoxelVector.at(i)).x();
voxelIndex(1) = (aVoxelVector.at(i)).y();
voxelIndex(2) = sliceNumber;
WorldCoordinate3D p1;
_geoInfo.indexToWorldCoordinate(voxelIndex, p1);
SpacingVectorType3D delta = _geoInfo.getSpacing();
WorldCoordinate3D wp1;
wp1(0) = p1.x();
wp1(1) = p1.y();
wp1(2) = p1.z();
WorldCoordinate3D wp_intermediate;
wp_intermediate(0) = 0;
wp_intermediate(1) = 0;
wp_intermediate(2) = p1.z();
wp_intermediate(0) = wp1.x();
wp_intermediate(1) = wp1.y() + (delta.y() * 0.5);
polygon.push_back(wp_intermediate);
wp_intermediate(0) = wp1.x() + (delta.x() * 0.5);
wp_intermediate(1) = wp1.y();
polygon.push_back(wp_intermediate);
wp_intermediate(0) = wp1.x() + (delta.x() * 0.5);
wp_intermediate(1) = wp1.y() + (delta.y() * 0.5);
polygon.push_back(wp_intermediate);
wp_intermediate(0) = wp1.x() + (delta.x() * 1.0);
wp_intermediate(1) = wp1.y() + (delta.y() * 0.5);
polygon.push_back(wp_intermediate);
wp_intermediate(0) = wp1.x() + (delta.x() * 1.0);
wp_intermediate(1) = wp1.y() + (delta.y() * 1.0);
polygon.push_back(wp_intermediate);
wp_intermediate(0) = wp1.x() + (delta.x() * 0.5);
wp_intermediate(1) = wp1.y() + (delta.y() * 1.0);
polygon.push_back(wp_intermediate);
wp_intermediate(0) = wp1.x() + (delta.x() * 0.5);
wp_intermediate(1) = wp1.y() + (delta.y() * 0.5);
polygon.push_back(wp_intermediate);
wp_intermediate(0) = wp1.x();
wp_intermediate(1) = wp1.y() + (delta.y() * 0.5);
polygon.push_back(wp_intermediate);
wp_intermediate(0) = wp1.x() + (delta.x() * 0.5);
wp_intermediate(1) = wp1.y() + (delta.y() * 0.5);
polygon.push_back(wp_intermediate);
wp_intermediate(0) = wp1.x() + (delta.x() * 0.5);
wp_intermediate(1) = wp1.y() + (delta.y() * 1.0);
polygon.push_back(wp_intermediate);
wp_intermediate(0) = wp1.x();
wp_intermediate(1) = wp1.y() + (delta.y() * 0.5);
polygon.push_back(wp_intermediate);
}
std::cout << std::endl;
return polygon;
}
}//testing
}//rttb
| 34.595308 | 124 | 0.469357 | MIC-DKFZ |
068378d6af38e997dad71e711f19708f7238cf00 | 3,053 | cpp | C++ | tokenizer.cpp | CreativeGP/c2js | 8d06404d4d72918d83eacb49fe6e9353ab7aece4 | [
"MIT"
] | null | null | null | tokenizer.cpp | CreativeGP/c2js | 8d06404d4d72918d83eacb49fe6e9353ab7aece4 | [
"MIT"
] | null | null | null | tokenizer.cpp | CreativeGP/c2js | 8d06404d4d72918d83eacb49fe6e9353ab7aece4 | [
"MIT"
] | null | null | null | #include "tokenizer.h"
#include "util.h"
#include <fstream>
Tokenizer::Tokenizer() {}
Tokenizer::~Tokenizer() {}
int Tokenizer::add_token(string value, uint line, uint col) {
if (value == "")
return -1;
tokens.push_back(Token {value, line, col});
tokenvals.push_back(value);
return 0;
}
int Tokenizer::set(string key, string value) {
settings.insert(make_pair(key, value));
return 0;
}
int Tokenizer::preset(string name) {
if (name == "c" || name == "cpp") {
set("specials", "!#$%&()-^\\@[;:],./=~|`{+*}<>?");
set("escaper", "\"'");
set("ignores", "");
set("ignoresplit", " \t\n");
return 0;
}
return -1;
}
int Tokenizer::tokenize(string code) {
string specials = settings.at("specials");
string ignores = settings.at("ignores");
string escaper = settings.at("escaper");
string ignoresplit = settings.at("ignoresplit");
tokens.clear();
string little = "";
int mode = 0;
uint line = 1;
uint col = 1;
for (int i = 0; i < code.length(); ++i) {
col++;
if (code[i] == '\n') {
add_token(little, line, col);
little = "";
line++;
col = 0;
}
if (ignores.find(code[i]) != string::npos) continue;
if (ignoresplit.find(code[i]) != string::npos && mode == 0) {
add_token(little, line, col);
little = "";
continue;
}
if (mode != 0) {
char escape_chr = escaper[mode-escape_mode_padding];
if ((code[i-2] == '\\' || code[i-1] != '\\') && code[i] == escape_chr) {
add_token(little+escape_chr, line, col);
// add_token(little, line, col);
// tokens.push_back(Token {ctos(escape_chr), line, col});
// tokenvals.push_back(ctos(escape_chr));
mode = 0;
little = "";
} else little += code[i];
} else {
if (escaper.find(code[i]) != string::npos) {
mode = escape_mode_padding + escaper.find(code[i]);
// "foofoo" を " foofoo " とするか "foofoo" と解釈するか, 今は後者採用
little += code[i];
// add_token(ctos(code[i]), line, col);
continue;
}
if (specials.find(code[i]) != string::npos) {
add_token(little, line, col);
little = "";
tokens.push_back(Token {ctos(code[i]), line, col});
tokenvals.push_back(ctos(code[i]));
} else little += code[i];
}
}
add_token(little, line, col);
return 0;
}
int Tokenizer::tokenize_file(string filename) {
ifstream ifs(filename);
if (!ifs) return -1;
ifs.seekg(0, ifs.end);
int length = ifs.tellg();
ifs.seekg(0, ifs.beg);
char *buffer = new char[length+1];
ifs.read(buffer, length+1);
buffer[length] = '\0';
tokenize(buffer);
delete[] buffer;
return 0;
}
| 25.655462 | 84 | 0.496561 | CreativeGP |
06848f70c9fa3faedd67ab90c09563ed731ad7eb | 17,354 | cpp | C++ | Source/HoudiniEngineEditor/Private/HoudiniEngineStyle.cpp | leaping-rhino/HoudiniEngineForUnreal | 7da6fea61907101071fb837e40c1902320604f7f | [
"BSD-3-Clause"
] | 1 | 2022-02-24T08:57:06.000Z | 2022-02-24T08:57:06.000Z | Source/HoudiniEngineEditor/Private/HoudiniEngineStyle.cpp | leaping-rhino/HoudiniEngineForUnreal | 7da6fea61907101071fb837e40c1902320604f7f | [
"BSD-3-Clause"
] | null | null | null | Source/HoudiniEngineEditor/Private/HoudiniEngineStyle.cpp | leaping-rhino/HoudiniEngineForUnreal | 7da6fea61907101071fb837e40c1902320604f7f | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) <2021> Side Effects Software 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. The name of Side Effects Software may not be used to endorse or
* promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "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 SIDE EFFECTS SOFTWARE 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 "HoudiniEngineStyle.h"
#include "HoudiniEngineEditor.h"
#include "HoudiniEngineUtils.h"
#include "EditorStyleSet.h"
#include "Styling/SlateStyleRegistry.h"
#include "Styling/SlateTypes.h"
#include "SlateOptMacros.h"
#define LOCTEXT_NAMESPACE HOUDINI_LOCTEXT_NAMESPACE
#define IMAGE_BRUSH( RelativePath, ... ) FSlateImageBrush( StyleSet->RootToContentDir( RelativePath, TEXT(".png") ), __VA_ARGS__ )
#define BOX_BRUSH( RelativePath, ... ) FSlateBoxBrush( StyleSet->RootToContentDir( RelativePath, TEXT(".png") ), __VA_ARGS__ )
#define BORDER_BRUSH( RelativePath, ... ) FSlateBorderBrush( StyleSet->RootToContentDir( RelativePath, TEXT(".png") ), __VA_ARGS__ )
#define TTF_FONT( RelativePath, ... ) FSlateFontInfo( StyleSet->RootToContentDir( RelativePath, TEXT(".ttf") ), __VA_ARGS__ )
#define TTF_CORE_FONT( RelativePath, ... ) FSlateFontInfo( StyleSet->RootToCoreContentDir( RelativePath, TEXT(".ttf") ), __VA_ARGS__ )
#define OTF_FONT( RelativePath, ... ) FSlateFontInfo( StyleSet->RootToContentDir( RelativePath, TEXT(".otf") ), __VA_ARGS__ )
#define OTF_CORE_FONT( RelativePath, ... ) FSlateFontInfo( StyleSet->RootToCoreContentDir( RelativePath, TEXT(".otf") ), __VA_ARGS__ )
TSharedPtr<FSlateStyleSet> FHoudiniEngineStyle::StyleSet = nullptr;
TSharedPtr<class ISlateStyle>
FHoudiniEngineStyle::Get()
{
return StyleSet;
}
FName
FHoudiniEngineStyle::GetStyleSetName()
{
static FName HoudiniStyleName(TEXT("HoudiniEngineStyle"));
return HoudiniStyleName;
}
BEGIN_SLATE_FUNCTION_BUILD_OPTIMIZATION
void
FHoudiniEngineStyle::Initialize()
{
// Only register the StyleSet once
if (StyleSet.IsValid())
return;
StyleSet = MakeShareable(new FSlateStyleSet(GetStyleSetName()));
StyleSet->SetContentRoot(FPaths::EngineContentDir() / TEXT("Editor/Slate"));
StyleSet->SetCoreContentRoot(FPaths::EngineContentDir() / TEXT("Slate"));
// Note, these sizes are in Slate Units.
// Slate Units do NOT have to map to pixels.
const FVector2D Icon5x16(5.0f, 16.0f);
const FVector2D Icon8x4(8.0f, 4.0f);
const FVector2D Icon8x8(8.0f, 8.0f);
const FVector2D Icon10x10(10.0f, 10.0f);
const FVector2D Icon12x12(12.0f, 12.0f);
const FVector2D Icon12x16(12.0f, 16.0f);
const FVector2D Icon14x14(14.0f, 14.0f);
const FVector2D Icon16x16(16.0f, 16.0f);
const FVector2D Icon20x20(20.0f, 20.0f);
const FVector2D Icon22x22(22.0f, 22.0f);
const FVector2D Icon24x24(24.0f, 24.0f);
const FVector2D Icon25x25(25.0f, 25.0f);
const FVector2D Icon32x32(32.0f, 32.0f);
const FVector2D Icon40x40(40.0f, 40.0f);
const FVector2D Icon64x64(64.0f, 64.0f);
const FVector2D Icon36x24(36.0f, 24.0f);
const FVector2D Icon128x128(128.0f, 128.0f);
static FString IconsDir = FHoudiniEngineUtils::GetHoudiniEnginePluginDir() / TEXT("Resources/Icons/");
StyleSet->Set(
"HoudiniEngine.HoudiniEngineLogo",
new FSlateImageBrush(IconsDir + TEXT("icon_houdini_logo_16.png"), Icon16x16));
StyleSet->Set(
"ClassIcon.HoudiniAssetActor",
new FSlateImageBrush(IconsDir + TEXT("icon_houdini_logo_16.png"), Icon16x16));
StyleSet->Set(
"ClassThumbnail.HoudiniAssetActor",
new FSlateImageBrush(IconsDir + TEXT("icon_houdini_logo_128.png"), Icon64x64));
StyleSet->Set(
"HoudiniEngine.HoudiniEngineLogo40",
new FSlateImageBrush(IconsDir + TEXT("icon_houdini_logo_40.png"), Icon40x40));
StyleSet->Set(
"ClassIcon.HoudiniAsset",
new FSlateImageBrush(IconsDir + TEXT("houdini_digital_asset.png"), Icon16x16));
StyleSet->Set(
"ClassThumbnail.HoudiniAsset",
new FSlateImageBrush(IconsDir + TEXT("houdini_digital_asset_128.png"), Icon64x64));
static FString ResourcesDir = FHoudiniEngineUtils::GetHoudiniEnginePluginDir() / TEXT("Resources/");
FString AssetHelpIcon = IconsDir + TEXT("asset_help16x16.png");
FString BakeAllIcon = IconsDir + TEXT("bake_all16x16.png");
FString BakeSelIcon = IconsDir + TEXT("bake_selected16x16.png");
FString CleanTempIcon = IconsDir + TEXT("clean_temp16x16.png");
FString CookAllIcon = IconsDir + TEXT("cook_all16x16.png");
FString CookLogIcon = IconsDir + TEXT("cook_log16x16.png");
FString CookSelIcon = IconsDir + TEXT("cook_selected16x16.png");
FString DigitalAssetIcon = IconsDir + TEXT("digital_asset16x16.png");
FString OnlineForumIcon = IconsDir + TEXT("online_forum16x16.png");
FString OnlineHelpIcon = IconsDir + TEXT("online_help16x16.png");
FString OpenInHIcon = IconsDir + TEXT("open_in_houdini16x16.png");
FString PauseIcon = IconsDir + TEXT("pause16x16.png");
FString PDGCancelIcon = IconsDir + TEXT("pdg_cancel16x16.png");
FString PDGDirtyAllIcon = IconsDir + TEXT("pdg_dirty_all16x16.png");
FString PDGDirtyNodeIcon = IconsDir + TEXT("pdg_dirty_node16x16.png");
FString PDGLinkIcon = IconsDir + TEXT("pdg_link16x16.png");
FString PDGPauseIcon = IconsDir + TEXT("pdg_pause16x16.png");
FString PDGRefreshIcon = IconsDir + TEXT("pdg_refresh16x16.png");
FString PDGResetIcon = IconsDir + TEXT("pdg_reset16x16.png");
FString RebuildAllIcon = IconsDir + TEXT("rebuild_all16x16.png");
FString RebuildSelIcon = IconsDir + TEXT("rebuild_selected16x16.png");
FString RefineAllIcon = IconsDir + TEXT("refine_all16x16.png");
FString RefineSelIcon = IconsDir + TEXT("refine_selected16x16.png");
FString ReportBugIcon = IconsDir + TEXT("report_bug16x16.png");
FString ResetIcon = IconsDir + TEXT("reset16x16.png");
FString ResetParamIcon = IconsDir + TEXT("reset_parameters16x16.png");
FString SaveToHipIcon = IconsDir + TEXT("save_to_hip16x16.png");
FString SessionConnectIcon = IconsDir + TEXT("session_connect16x16.png");
FString SessionCreateIcon = IconsDir + TEXT("session_create16x16.png");
FString SessionRestartIcon = IconsDir + TEXT("session_restart16x16.png");
FString SessionStopIcon = IconsDir + TEXT("session_stop16x16.png");
FString SessionSyncIcon = IconsDir + TEXT("session_sync16x16.png");
FString SessionSyncStartIcon = IconsDir + TEXT("session_sync_start16x16.png");
FString SessionSyncStopIcon = IconsDir + TEXT("session_sync_stop16x16.png");
FString ViewportSyncIcon = IconsDir + TEXT("viewport_sync16x16.png");
FString ViewportSyncBothIcon = IconsDir + TEXT("viewport_sync_both16x16.png");
FString ViewportSyncHoudiniIcon = IconsDir + TEXT("viewport_sync_houdini16x16.png");
FString ViewportSyncOffIcon = IconsDir + TEXT("viewport_sync_off16x16.png");
FString ViewportSyncUnrealIcon = IconsDir + TEXT("viewport_sync_unreal16x16.png");
FString InfoIcon = FEditorStyle::GetBrush("Icons.Info")->GetResourceName().ToString();
FString SettingsIcon = FEditorStyle::GetBrush("Launcher.EditSettings")->GetResourceName().ToString();
StyleSet->Set("HoudiniEngine._CreateSession", new FSlateImageBrush(SessionCreateIcon, Icon16x16));
StyleSet->Set("HoudiniEngine._ConnectSession", new FSlateImageBrush(SessionConnectIcon, Icon16x16));
StyleSet->Set("HoudiniEngine._StopSession", new FSlateImageBrush(SessionStopIcon, Icon16x16));
StyleSet->Set("HoudiniEngine._RestartSession", new FSlateImageBrush(SessionRestartIcon, Icon16x16));
StyleSet->Set("HoudiniEngine._SessionSync", new FSlateImageBrush(SessionSyncIcon, Icon16x16));
StyleSet->Set("HoudiniEngine._OpenSessionSync", new FSlateImageBrush(SessionSyncStartIcon, Icon16x16));
StyleSet->Set("HoudiniEngine._CloseSessionSync", new FSlateImageBrush(SessionSyncStopIcon, Icon16x16));
StyleSet->Set("HoudiniEngine._SyncViewport", new FSlateImageBrush(ViewportSyncIcon, Icon16x16));
StyleSet->Set("HoudiniEngine._ViewportSyncNone", new FSlateImageBrush(ViewportSyncOffIcon, Icon16x16));
StyleSet->Set("HoudiniEngine._ViewportSyncBoth", new FSlateImageBrush(ViewportSyncBothIcon, Icon16x16));
StyleSet->Set("HoudiniEngine._ViewportSyncUnreal", new FSlateImageBrush(ViewportSyncUnrealIcon, Icon16x16));
StyleSet->Set("HoudiniEngine._ViewportSyncHoudini", new FSlateImageBrush(ViewportSyncHoudiniIcon, Icon16x16));
StyleSet->Set("HoudiniEngine._InstallInfo", new FSlateImageBrush(InfoIcon, Icon16x16));
StyleSet->Set("HoudiniEngine._PluginSettings", new FSlateImageBrush(SettingsIcon, Icon16x16));
StyleSet->Set("HoudiniEngine._OpenInHoudini", new FSlateImageBrush(OpenInHIcon, Icon16x16));
StyleSet->Set("HoudiniEngine._SaveHIPFile", new FSlateImageBrush(SaveToHipIcon, Icon16x16));
StyleSet->Set("HoudiniEngine._CleanUpTempFolder", new FSlateImageBrush(CleanTempIcon, Icon16x16));
StyleSet->Set("HoudiniEngine._OnlineDoc", new FSlateImageBrush(OnlineHelpIcon, Icon16x16));
StyleSet->Set("HoudiniEngine._OnlineForum", new FSlateImageBrush(OnlineForumIcon, Icon16x16));
StyleSet->Set("HoudiniEngine._ReportBug", new FSlateImageBrush(ReportBugIcon, Icon16x16));
StyleSet->Set("HoudiniEngine._CookAll", new FSlateImageBrush(CookAllIcon, Icon16x16));
StyleSet->Set("HoudiniEngine._CookSelected", new FSlateImageBrush(CookSelIcon, Icon16x16));
StyleSet->Set("HoudiniEngine._BakeSelected", new FSlateImageBrush(BakeSelIcon, Icon16x16));
StyleSet->Set("HoudiniEngine._BakeAll", new FSlateImageBrush(BakeAllIcon, Icon16x16));
StyleSet->Set("HoudiniEngine._RebuildAll", new FSlateImageBrush(RebuildAllIcon, Icon16x16));
StyleSet->Set("HoudiniEngine._RebuildSelected", new FSlateImageBrush(RebuildSelIcon, Icon16x16));
StyleSet->Set("HoudiniEngine._RefineAll", new FSlateImageBrush(RefineAllIcon, Icon16x16));
StyleSet->Set("HoudiniEngine._RefineSelected", new FSlateImageBrush(RefineSelIcon, Icon16x16));
StyleSet->Set("HoudiniEngine._PauseAssetCooking", new FSlateImageBrush(PauseIcon, Icon16x16));
StyleSet->Set("HoudiniEngine._Reset", new FSlateImageBrush(ResetIcon, Icon16x16));
StyleSet->Set("HoudiniEngine.DigitalAsset", new FSlateImageBrush(DigitalAssetIcon, Icon16x16));
StyleSet->Set("HoudiniEngine.PDGLink", new FSlateImageBrush(PDGLinkIcon, Icon16x16));
/*
FString StopIcon = FEditorStyle::GetBrush("PropertyWindow.Button_Clear")->GetResourceName().ToString();
FString RestartIcon = FEditorStyle::GetBrush("Tutorials.Browser.RestartButton")->GetResourceName().ToString();
FString InfoIcon = FEditorStyle::GetBrush("Icons.Info")->GetResourceName().ToString();
FString SettingsIcon = FEditorStyle::GetBrush("Launcher.EditSettings")->GetResourceName().ToString();
FString ClearIcon = FEditorStyle::GetBrush("PropertyWindow.Button_Delete")->GetResourceName().ToString();
FString HelpIcon = FEditorStyle::GetBrush("Icons.Help")->GetResourceName().ToString();
FString WarningIcon = FEditorStyle::GetBrush("Icons.Warning")->GetResourceName().ToString();
FString BPIcon = FEditorStyle::GetBrush("PropertyWindow.Button_CreateNewBlueprint")->GetResourceName().ToString();
FString PauseIcon = FEditorStyle::GetBrush("Profiler.Pause")->GetResourceName().ToString();
StyleSet->Set("HoudiniEngine._CreateSession", new FSlateImageBrush(IconsDir + TEXT("icon_houdini_logo_16.png"), Icon16x16));
StyleSet->Set("HoudiniEngine._ConnectSession", new FSlateImageBrush(IconsDir + TEXT("icon_houdini_logo_16.png"), Icon16x16));
StyleSet->Set("HoudiniEngine._StopSession", new FSlateImageBrush(StopIcon, Icon16x16));
StyleSet->Set("HoudiniEngine._RestartSession", new FSlateImageBrush(RestartIcon, Icon16x16));
StyleSet->Set("HoudiniEngine._OpenSessionSync", new FSlateImageBrush(IconsDir + TEXT("icon_houdini_logo_16.png"), Icon16x16));
StyleSet->Set("HoudiniEngine._CloseSessionSync", new FSlateImageBrush(StopIcon, Icon16x16));
StyleSet->Set("HoudiniEngine._InstallInfo", new FSlateImageBrush(InfoIcon, Icon16x16));
StyleSet->Set("HoudiniEngine._PluginSettings", new FSlateImageBrush(SettingsIcon, Icon16x16));
StyleSet->Set("HoudiniEngine._OpenInHoudini", new FSlateImageBrush(IconsDir + TEXT("icon_houdini_logo_16.png"), Icon16x16));
StyleSet->Set("HoudiniEngine._SaveHIPFile", new FSlateImageBrush(IconsDir + TEXT("icon_houdini_logo_16.png"), Icon16x16));
StyleSet->Set("HoudiniEngine._CleanUpTempFolder", new FSlateImageBrush(IconsDir + TEXT("icon_houdini_logo_16.png"), Icon16x16));
StyleSet->Set("HoudiniEngine._OnlineDoc", new FSlateImageBrush(HelpIcon, Icon16x16));
StyleSet->Set("HoudiniEngine._OnlineForum", new FSlateImageBrush(InfoIcon, Icon16x16));
StyleSet->Set("HoudiniEngine._ReportBug", new FSlateImageBrush(WarningIcon, Icon16x16));
StyleSet->Set("HoudiniEngine._CookAll", new FSlateImageBrush(ResourcesDir + TEXT("hengine_recook_icon.png"), Icon16x16));
StyleSet->Set("HoudiniEngine._CookSelected", new FSlateImageBrush(ResourcesDir + TEXT("hengine_recook_icon.png"), Icon16x16));
StyleSet->Set("HoudiniEngine._BakeSelected", new FSlateImageBrush(IconsDir + TEXT("icon_houdini_logo_16.png"), Icon16x16));
StyleSet->Set("HoudiniEngine._BakeAll", new FSlateImageBrush(IconsDir + TEXT("icon_houdini_logo_16.png"), Icon16x16));
StyleSet->Set("HoudiniEngine._RebuildAll", new FSlateImageBrush(ResourcesDir + TEXT("hengine_reload_icon.png"), Icon16x16));
StyleSet->Set("HoudiniEngine._RebuildSelected", new FSlateImageBrush(ResourcesDir + TEXT("hengine_reload_icon.png"), Icon16x16));
StyleSet->Set("HoudiniEngine._RefineAll", new FSlateImageBrush(IconsDir + TEXT("icon_houdini_logo_16.png"), Icon16x16));
StyleSet->Set("HoudiniEngine._RefineSelected", new FSlateImageBrush(IconsDir + TEXT("icon_houdini_logo_16.png"), Icon16x16));
StyleSet->Set("HoudiniEngine._PauseAssetCooking", new FSlateImageBrush(IconsDir + TEXT("icon_houdini_logo_16.png"), Icon16x16));
*/
// We need some colors from Editor Style & this is the only way to do this at the moment
const FSlateColor DefaultForeground = FEditorStyle::GetSlateColor("DefaultForeground");
const FSlateColor InvertedForeground = FEditorStyle::GetSlateColor("InvertedForeground");
const FSlateColor SelectorColor = FEditorStyle::GetSlateColor("SelectorColor");
const FSlateColor SelectionColor = FEditorStyle::GetSlateColor("SelectionColor");
const FSlateColor SelectionColor_Inactive = FEditorStyle::GetSlateColor("SelectionColor_Inactive");
const FTableRowStyle &NormalTableRowStyle = FEditorStyle::Get().GetWidgetStyle<FTableRowStyle>("TableView.Row");
StyleSet->Set(
"HoudiniEngine.TableRow", FTableRowStyle(NormalTableRowStyle)
.SetEvenRowBackgroundBrush(FSlateNoResource())
.SetEvenRowBackgroundHoveredBrush(IMAGE_BRUSH("Common/Selection", Icon8x8, FLinearColor(1.0f, 1.0f, 1.0f, 0.1f)))
.SetOddRowBackgroundBrush(FSlateNoResource())
.SetOddRowBackgroundHoveredBrush(IMAGE_BRUSH("Common/Selection", Icon8x8, FLinearColor(1.0f, 1.0f, 1.0f, 0.1f)))
.SetSelectorFocusedBrush(BORDER_BRUSH("Common/Selector", FMargin(4.f / 16.f), SelectorColor))
.SetActiveBrush(IMAGE_BRUSH("Common/Selection", Icon8x8, SelectionColor))
.SetActiveHoveredBrush(IMAGE_BRUSH("Common/Selection", Icon8x8, SelectionColor))
.SetInactiveBrush(IMAGE_BRUSH("Common/Selection", Icon8x8, SelectionColor_Inactive))
.SetInactiveHoveredBrush(IMAGE_BRUSH("Common/Selection", Icon8x8, SelectionColor_Inactive))
.SetTextColor(DefaultForeground)
.SetSelectedTextColor(InvertedForeground)
);
// Normal Text
const FTextBlockStyle& NormalText = FEditorStyle::Get().GetWidgetStyle<FTextBlockStyle>("NormalText");
StyleSet->Set(
"HoudiniEngine.ThumbnailText", FTextBlockStyle(NormalText)
.SetFont(TTF_CORE_FONT("Fonts/Roboto-Regular", 9))
.SetColorAndOpacity(FSlateColor::UseForeground())
.SetShadowOffset(FVector2D::ZeroVector)
.SetShadowColorAndOpacity(FLinearColor::Black)
.SetHighlightColor(FLinearColor(0.02f, 0.3f, 0.0f))
.SetHighlightShape(BOX_BRUSH("Common/TextBlockHighlightShape", FMargin(3.f / 8.f)))
);
StyleSet->Set("HoudiniEngine.ThumbnailShadow", new BOX_BRUSH("ContentBrowser/ThumbnailShadow", FMargin(4.0f / 64.0f)));
StyleSet->Set("HoudiniEngine.ThumbnailBackground", new IMAGE_BRUSH("Common/ClassBackground_64x", FVector2D(64.f, 64.f), FLinearColor(0.75f, 0.75f, 0.75f, 1.0f)));
// Register Slate style.
FSlateStyleRegistry::RegisterSlateStyle(*StyleSet.Get());
};
END_SLATE_FUNCTION_BUILD_OPTIMIZATION
#undef IMAGE_BRUSH
#undef BOX_BRUSH
#undef BORDER_BRUSH
#undef TTF_FONT
#undef TTF_CORE_FONT
#undef OTF_FONT
#undef OTF_CORE_FONT
void
FHoudiniEngineStyle::Shutdown()
{
if (StyleSet.IsValid())
{
FSlateStyleRegistry::UnRegisterSlateStyle(*StyleSet.Get());
ensure(StyleSet.IsUnique());
StyleSet.Reset();
}
}
#undef LOCTEXT_NAMESPACE | 54.744479 | 163 | 0.789904 | leaping-rhino |
0685080ea1d0902c50715059a6c6edb190b3fd37 | 1,065 | cpp | C++ | Volume110/11088 - End up with More Teams/11088.cpp | rstancioiu/uva-online-judge | 31c536d764462d389b48b4299b9731534824c9f5 | [
"MIT"
] | 1 | 2017-01-25T18:07:49.000Z | 2017-01-25T18:07:49.000Z | Volume110/11088 - End up with More Teams/11088.cpp | rstancioiu/uva-online-judge | 31c536d764462d389b48b4299b9731534824c9f5 | [
"MIT"
] | null | null | null | Volume110/11088 - End up with More Teams/11088.cpp | rstancioiu/uva-online-judge | 31c536d764462d389b48b4299b9731534824c9f5 | [
"MIT"
] | null | null | null | // Author: Stancioiu Nicu Razvan
// Problem: http://uva.onlinejudge.org/external/110/11088.html
#include <cstdio>
#define INF 0x1f1f1f1f
#define N 16
using namespace std;
int teams,n,c;
int p[N];
int visited[N];
int BackTrack(int nbTeams,int l)
{
int sum=INF;
int maxNbTeams=nbTeams;
for(int i=l;i<n;++i)
{
if(!visited[i] && maxNbTeams<nbTeams + (n-i)/3)
{
for(int j=i+1;j<n;++j)
{
if(!visited[j] && maxNbTeams<nbTeams + (n-i)/3 )
{
for(int k=j+1;k<n;++k)
{
if(!visited[k] && maxNbTeams<nbTeams + (n-i)/3)
{
int sump=p[i]+p[j]+p[k];
if(sump>=20)
{
visited[i]=visited[j]=visited[k]=1;
int nbT=BackTrack(nbTeams+1,i+1);
if(nbT>maxNbTeams)
maxNbTeams=nbT;
visited[i]=visited[j]=visited[k]=0;
}
}
}
}
}
}
}
return maxNbTeams;
}
int main()
{
c=1;
while(scanf("%d",&n)==1 && n!=0)
{
for(int i=0;i<n;++i)
{
scanf("%d",&p[i]);
visited[i]=0;
}
teams=BackTrack(0,0);
printf("Case %d: %d\n",c++,teams);
}
return 0;
} | 17.459016 | 62 | 0.53615 | rstancioiu |
068638527269bdc8b38aa4b45d95301f6697a5d2 | 15,390 | hpp | C++ | include/memoria/core/memory/smart_ptrs.hpp | victor-smirnov/memoria | c36a957c63532176b042b411b1646c536e71a658 | [
"BSL-1.0",
"Apache-2.0",
"OLDAP-2.8",
"BSD-3-Clause"
] | 2 | 2021-07-30T16:54:24.000Z | 2021-09-08T15:48:17.000Z | include/memoria/core/memory/smart_ptrs.hpp | victor-smirnov/memoria | c36a957c63532176b042b411b1646c536e71a658 | [
"BSL-1.0",
"Apache-2.0",
"OLDAP-2.8",
"BSD-3-Clause"
] | null | null | null | include/memoria/core/memory/smart_ptrs.hpp | victor-smirnov/memoria | c36a957c63532176b042b411b1646c536e71a658 | [
"BSL-1.0",
"Apache-2.0",
"OLDAP-2.8",
"BSD-3-Clause"
] | 2 | 2020-03-14T15:15:25.000Z | 2020-06-15T11:26:56.000Z |
// Copyright 2018 Victor Smirnov
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <memoria/core/types.hpp>
#include <boost/smart_ptr.hpp>
#include <boost/smart_ptr/local_shared_ptr.hpp>
#include <boost/smart_ptr/make_local_shared.hpp>
#include <boost/smart_ptr/atomic_shared_ptr.hpp>
namespace memoria {
#ifdef MMA_NO_REACTOR
static inline int32_t current_cpu() {return 0;}
static inline int32_t number_of_cpus() {return 1;}
template <typename T>
using SharedPtr = boost::shared_ptr<T>;
template <typename T>
using LocalSharedPtr = boost::local_shared_ptr<T>;
template <typename T, typename... Args>
auto MakeShared(Args&&... args) {
return boost::make_shared<T>(std::forward<Args>(args)...);
}
template <typename T, typename... Args>
auto MakeSharedAt(int cpu, Args&&... args) {
return boost::make_shared<T>(std::forward<Args>(args)...);
}
template <typename T, typename... Args>
auto MakeLocalShared(Args&&... args) {
return boost::make_local_shared<T>(std::forward<Args>(args)...);
}
template <typename T, typename Allocator, typename... Args>
auto AllocateShared(const Allocator& alloc, Args&&... args) {
return boost::allocate_shared<T>(alloc, std::forward<Args>(args)...);
}
template <typename T, typename Allocator, typename... Args>
auto AllocateSharedAt(int32_t cpu, const Allocator& alloc, Args&&... args) {
return boost::allocate_shared<T>(alloc, std::forward<Args>(args)...);
}
template <typename T, typename Allocator, typename... Args>
auto AllocateLocalShared(const Allocator& alloc, Args&&... args) {
return boost::allocate_local_shared<T>(alloc, std::forward<Args>(args)...);
}
template <typename T>
using EnableSharedFromThis = boost::enable_shared_from_this<T>;
using EnableSharedFromRaw = boost::enable_shared_from_raw;
template <typename T>
using WeakPtr = boost::weak_ptr<T>;
template<typename T, typename U>
boost::shared_ptr<T> StaticPointerCast( const boost::shared_ptr<U>& r ) noexcept {
return boost::static_pointer_cast<T>(r);
}
template<typename T, typename U>
boost::shared_ptr<T> StaticPointerCast( boost::shared_ptr<U>&& r ) noexcept {
return boost::static_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
boost::shared_ptr<T> DynamicPointerCast( const boost::shared_ptr<U>& r ) noexcept {
return boost::dynamic_pointer_cast<T>(r);
}
template<typename T, typename U>
boost::shared_ptr<T> DynamicPointerCast( boost::shared_ptr<U>&& r ) noexcept {
return boost::dynamic_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
boost::shared_ptr<T> ReinterpretPointerCast( const boost::shared_ptr<U>& r ) noexcept {
return boost::reinterpret_pointer_cast<T>(r);
}
template<typename T, typename U>
boost::shared_ptr<T> ReinterpretPointerCast( boost::shared_ptr<U>&& r ) noexcept {
return boost::reinterpret_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
boost::shared_ptr<T> ConstPointerCast( const boost::shared_ptr<U>& r ) noexcept {
return boost::const_pointer_cast<T>(r);
}
template<typename T, typename U>
boost::shared_ptr<T> ConstPointerCast( boost::shared_ptr<U>&& r ) noexcept {
return boost::const_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
boost::local_shared_ptr<T> StaticPointerCast( const boost::local_shared_ptr<U>& r ) noexcept {
return boost::static_pointer_cast<T>(r);
}
template<typename T, typename U>
boost::local_shared_ptr<T> StaticPointerCast( boost::local_shared_ptr<U>&& r ) noexcept {
return boost::static_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
boost::local_shared_ptr<T> DynamicPointerCast( const boost::local_shared_ptr<U>& r ) noexcept {
return boost::dynamic_pointer_cast<T>(r);
}
template<typename T, typename U>
boost::local_shared_ptr<T> DynamicPointerCast( boost::local_shared_ptr<U>&& r ) noexcept {
return boost::dynamic_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
boost::local_shared_ptr<T> ReinterpretPointerCast( const boost::local_shared_ptr<U>& r ) noexcept {
return boost::reinterpret_pointer_cast<T>(r);
}
template<typename T, typename U>
boost::local_shared_ptr<T> ReinterpretPointerCast( boost::local_shared_ptr<U>&& r ) noexcept {
return boost::reinterpret_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
boost::local_shared_ptr<T> ConstPointerCast( const boost::local_shared_ptr<U>& r ) noexcept {
return boost::const_pointer_cast<T>(r);
}
template<typename T, typename U>
boost::local_shared_ptr<T> ConstPointerCast( boost::local_shared_ptr<U>&& r ) noexcept {
return boost::const_pointer_cast<T>(std::move(r));
}
#else
namespace reactor {
int32_t current_cpu();
int32_t number_of_cpus();
}
/*
template <typename T>
using SharedPtr = reactor::shared_ptr<T>;
template <typename T>
using LocalSharedPtr = reactor::local_shared_ptr<T>;
template <typename T, typename... Args>
auto MakeShared(Args&&... args) {
return reactor::make_shared_at<T>(reactor::current_cpu(), std::forward<Args>(args)...);
}
template <typename T, typename... Args>
auto MakeSharedAt(int32_t cpu, Args&&... args) {
return reactor::make_shared_at<T>(cpu, std::forward<Args>(args)...);
}
template <typename T, typename... Args>
auto MakeLocalShared(Args&&... args) {
return reactor::make_local_shared<T>(std::forward<Args>(args)...);
}
template <typename T, typename Allocator, typename... Args>
auto AllocateShared(const Allocator& alloc, Args&&... args) {
return reactor::allocate_shared_at<T>(reactor::current_cpu(), alloc, std::forward<Args>(args)...);
}
template <typename T, typename Allocator, typename... Args>
auto AllocateLocalShared(int32_t cpu, const Allocator& alloc, Args&&... args) {
return reactor::allocate_shared_at<T>(cpu, alloc, std::forward<Args>(args)...);
}
template <typename T, typename Allocator, typename... Args>
auto AllocateLocalShared(const Allocator& alloc, Args&&... args) {
return reactor::allocate_local_shared<T>(alloc, std::forward<Args>(args)...);
}
template <typename T>
using EnableSharedFromThis = reactor::enable_shared_from_this<T>;
using EnableSharedFromRaw = reactor::enable_shared_from_raw;
template <typename T>
using WeakPtr = reactor::weak_ptr<T>;
template<typename T, typename U>
reactor::shared_ptr<T> StaticPointerCast( const reactor::shared_ptr<U>& r ) noexcept {
return reactor::static_pointer_cast<T>(r);
}
template<typename T, typename U>
reactor::shared_ptr<T> StaticPointerCast( reactor::shared_ptr<U>&& r ) noexcept {
return reactor::static_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
reactor::shared_ptr<T> DynamicPointerCast( const reactor::shared_ptr<U>& r ) noexcept {
return reactor::dynamic_pointer_cast<T>(r);
}
template<typename T, typename U>
reactor::shared_ptr<T> DynamicPointerCast( reactor::shared_ptr<U>&& r ) noexcept {
return reactor::dynamic_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
reactor::shared_ptr<T> ReinterpretPointerCast( const reactor::shared_ptr<U>& r ) noexcept {
return reactor::reinterpret_pointer_cast<T>(r);
}
template<typename T, typename U>
reactor::shared_ptr<T> ReinterpretPointerCast( reactor::shared_ptr<U>&& r ) noexcept {
return reactor::reinterpret_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
reactor::shared_ptr<T> ConstPointerCast( const reactor::shared_ptr<U>& r ) noexcept {
return reactor::const_pointer_cast<T>(r);
}
template<typename T, typename U>
reactor::shared_ptr<T> ConstPointerCast( reactor::shared_ptr<U>&& r ) noexcept {
return reactor::const_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
reactor::local_shared_ptr<T> StaticPointerCast( const reactor::local_shared_ptr<U>& r ) noexcept {
return reactor::static_pointer_cast<T>(r);
}
template<typename T, typename U>
reactor::local_shared_ptr<T> StaticPointerCast( reactor::local_shared_ptr<U>&& r ) noexcept {
return reactor::static_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
reactor::local_shared_ptr<T> DynamicPointerCast( const reactor::local_shared_ptr<U>& r ) noexcept {
return reactor::dynamic_pointer_cast<T>(r);
}
template<typename T, typename U>
reactor::local_shared_ptr<T> DynamicPointerCast( reactor::local_shared_ptr<U>&& r ) noexcept {
return reactor::dynamic_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
reactor::local_shared_ptr<T> ReinterpretPointerCast( const reactor::local_shared_ptr<U>& r ) noexcept {
return reactor::reinterpret_pointer_cast<T>(r);
}
template<typename T, typename U>
reactor::local_shared_ptr<T> ReinterpretPointerCast( reactor::local_shared_ptr<U>&& r ) noexcept {
return reactor::reinterpret_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
reactor::local_shared_ptr<T> ConstPointerCast( const reactor::local_shared_ptr<U>& r ) noexcept {
return reactor::const_pointer_cast<T>(r);
}
template<typename T, typename U>
reactor::local_shared_ptr<T> ConstPointerCast( reactor::local_shared_ptr<U>&& r ) noexcept {
return reactor::const_pointer_cast<T>(std::move(r));
}
*/
template <typename T>
using SharedPtr = boost::shared_ptr<T>;
template <typename T>
using LocalSharedPtr = boost::local_shared_ptr<T>;
template <typename T, typename... Args>
auto MakeShared(Args&&... args) {
return boost::make_shared<T>(std::forward<Args>(args)...);
}
template <typename T, typename... Args>
auto MakeSharedAt(int cpu, Args&&... args) {
return boost::make_shared<T>(std::forward<Args>(args)...);
}
template <typename T, typename... Args>
auto MakeLocalShared(Args&&... args) {
return boost::make_local_shared<T>(std::forward<Args>(args)...);
}
template <typename T, typename Allocator, typename... Args>
auto AllocateShared(const Allocator& alloc, Args&&... args) {
return boost::allocate_shared<T>(alloc, std::forward<Args>(args)...);
}
template <typename T, typename Allocator, typename... Args>
auto AllocateSharedAt(int32_t cpu, const Allocator& alloc, Args&&... args) {
return boost::allocate_shared<T>(alloc, std::forward<Args>(args)...);
}
template <typename T, typename Allocator, typename... Args>
auto AllocateLocalShared(const Allocator& alloc, Args&&... args) {
return boost::allocate_local_shared<T>(alloc, std::forward<Args>(args)...);
}
template <typename T>
using EnableSharedFromThis = boost::enable_shared_from_this<T>;
using EnableSharedFromRaw = boost::enable_shared_from_raw;
template <typename T>
using WeakPtr = boost::weak_ptr<T>;
template<typename T, typename U>
boost::shared_ptr<T> StaticPointerCast( const boost::shared_ptr<U>& r ) noexcept {
return boost::static_pointer_cast<T>(r);
}
template<typename T, typename U>
boost::shared_ptr<T> StaticPointerCast( boost::shared_ptr<U>&& r ) noexcept {
return boost::static_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
boost::shared_ptr<T> DynamicPointerCast( const boost::shared_ptr<U>& r ) noexcept {
return boost::dynamic_pointer_cast<T>(r);
}
template<typename T, typename U>
boost::shared_ptr<T> DynamicPointerCast( boost::shared_ptr<U>&& r ) noexcept {
return boost::dynamic_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
boost::shared_ptr<T> ReinterpretPointerCast( const boost::shared_ptr<U>& r ) noexcept {
return boost::reinterpret_pointer_cast<T>(r);
}
template<typename T, typename U>
boost::shared_ptr<T> ReinterpretPointerCast( boost::shared_ptr<U>&& r ) noexcept {
return boost::reinterpret_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
boost::shared_ptr<T> ConstPointerCast( const boost::shared_ptr<U>& r ) noexcept {
return boost::const_pointer_cast<T>(r);
}
template<typename T, typename U>
boost::shared_ptr<T> ConstPointerCast( boost::shared_ptr<U>&& r ) noexcept {
return boost::const_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
boost::local_shared_ptr<T> StaticPointerCast( const boost::local_shared_ptr<U>& r ) noexcept {
return boost::static_pointer_cast<T>(r);
}
template<typename T, typename U>
boost::local_shared_ptr<T> StaticPointerCast( boost::local_shared_ptr<U>&& r ) noexcept {
return boost::static_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
boost::local_shared_ptr<T> DynamicPointerCast( const boost::local_shared_ptr<U>& r ) noexcept {
return boost::dynamic_pointer_cast<T>(r);
}
template<typename T, typename U>
boost::local_shared_ptr<T> DynamicPointerCast( boost::local_shared_ptr<U>&& r ) noexcept {
return boost::dynamic_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
boost::local_shared_ptr<T> ReinterpretPointerCast( const boost::local_shared_ptr<U>& r ) noexcept {
return boost::reinterpret_pointer_cast<T>(r);
}
template<typename T, typename U>
boost::local_shared_ptr<T> ReinterpretPointerCast( boost::local_shared_ptr<U>&& r ) noexcept {
return boost::reinterpret_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
boost::local_shared_ptr<T> ConstPointerCast( const boost::local_shared_ptr<U>& r ) noexcept {
return boost::const_pointer_cast<T>(r);
}
template<typename T, typename U>
boost::local_shared_ptr<T> ConstPointerCast( boost::local_shared_ptr<U>&& r ) noexcept {
return boost::const_pointer_cast<T>(std::move(r));
}
#endif
template <typename T, typename DtrT>
class ScopedDtr {
T* ptr_;
DtrT dtr_;
public:
ScopedDtr(T* ptr, DtrT dtr = [](T* ptr) { delete ptr; }) :
ptr_(ptr), dtr_(std::move(dtr))
{}
ScopedDtr(ScopedDtr&& other) :
ptr_(other.ptr_), dtr_(std::move(other.dtr_))
{
other.ptr_ = nullptr;
}
ScopedDtr(const ScopedDtr&) = delete;
~ScopedDtr() noexcept {
if (ptr_) dtr_(ptr_);
}
ScopedDtr& operator=(ScopedDtr&& other)
{
if (&other != this)
{
if (ptr_) {
dtr_(ptr_);
}
ptr_ = other.ptr_;
other.ptr_ = nullptr;
dtr_ = std::move(other.dtr_);
}
return this;
}
template <typename TT, typename FFn>
bool operator==(const ScopedDtr<TT, FFn>& other) const {
return ptr_ == other.get();
}
T* operator->() const {
return ptr_;
}
T* get() const {
return ptr_;
}
operator bool() const {
return ptr_ != nullptr;
}
};
template <typename T, typename Fn>
auto MakeScopedDtr(T* ptr, Fn&& dtr) {
return ScopedDtr<T, Fn>(ptr, std::forward<Fn>(dtr));
}
template <typename DtrT>
class OnScopeExit {
DtrT dtr_;
public:
OnScopeExit(DtrT&& dtr) :
dtr_(std::move(dtr))
{}
OnScopeExit(OnScopeExit&& other): dtr_(std::move(other.dtr_)) {}
OnScopeExit(const OnScopeExit&) = delete;
~OnScopeExit() noexcept {
dtr_();
}
};
template <typename Fn>
auto MakeOnScopeExit(Fn&& dtr) {
return OnScopeExit<Fn>(std::forward<Fn>(dtr));
}
}
| 27.190813 | 103 | 0.724756 | victor-smirnov |
0686a5698dd52188c98f89517463a3b51439758b | 24,457 | cc | C++ | chrome/renderer/webplugin_delegate_pepper.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | 11 | 2015-03-20T04:08:08.000Z | 2021-11-15T15:51:36.000Z | chrome/renderer/webplugin_delegate_pepper.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | null | null | null | chrome/renderer/webplugin_delegate_pepper.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2009 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.
#define PEPPER_APIS_ENABLED 1
#include "chrome/renderer/webplugin_delegate_pepper.h"
#include <string>
#include <vector>
#include "app/gfx/blit.h"
#include "base/file_util.h"
#include "base/message_loop.h"
#include "base/process_util.h"
#include "base/scoped_ptr.h"
#include "base/stats_counters.h"
#include "base/string_util.h"
#include "chrome/common/render_messages.h"
#include "chrome/renderer/render_thread.h"
#include "chrome/renderer/webplugin_delegate_proxy.h"
#include "third_party/npapi/bindings/npapi_extensions.h"
#include "third_party/WebKit/WebKit/chromium/public/WebInputEvent.h"
#include "webkit/glue/glue_util.h"
#include "webkit/glue/plugins/plugin_constants_win.h"
#include "webkit/glue/plugins/plugin_instance.h"
#include "webkit/glue/plugins/plugin_lib.h"
#include "webkit/glue/plugins/plugin_list.h"
#include "webkit/glue/plugins/plugin_stream_url.h"
#include "webkit/glue/webkit_glue.h"
#if defined(ENABLE_GPU)
#include "webkit/glue/plugins/plugin_constants_win.h"
#endif
using gpu::Buffer;
using webkit_glue::WebPlugin;
using webkit_glue::WebPluginDelegate;
using webkit_glue::WebPluginResourceClient;
using WebKit::WebCursorInfo;
using WebKit::WebKeyboardEvent;
using WebKit::WebInputEvent;
using WebKit::WebMouseEvent;
using WebKit::WebMouseWheelEvent;
namespace {
const uint32 kBytesPerPixel = 4; // Only 8888 RGBA for now.
} // namespace
// Implementation artifacts for a context
struct Device2DImpl {
TransportDIB* dib;
};
uint32 WebPluginDelegatePepper::next_buffer_id = 0;
WebPluginDelegatePepper* WebPluginDelegatePepper::Create(
const FilePath& filename,
const std::string& mime_type,
const base::WeakPtr<RenderView>& render_view,
gfx::PluginWindowHandle containing_view) {
scoped_refptr<NPAPI::PluginLib> plugin_lib =
NPAPI::PluginLib::CreatePluginLib(filename);
if (plugin_lib.get() == NULL)
return NULL;
NPError err = plugin_lib->NP_Initialize();
if (err != NPERR_NO_ERROR)
return NULL;
scoped_refptr<NPAPI::PluginInstance> instance =
plugin_lib->CreateInstance(mime_type);
return new WebPluginDelegatePepper(render_view,
containing_view,
instance.get());
}
bool WebPluginDelegatePepper::Initialize(
const GURL& url,
const std::vector<std::string>& arg_names,
const std::vector<std::string>& arg_values,
WebPlugin* plugin,
bool load_manually) {
plugin_ = plugin;
instance_->set_web_plugin(plugin_);
int argc = 0;
scoped_array<char*> argn(new char*[arg_names.size()]);
scoped_array<char*> argv(new char*[arg_names.size()]);
for (size_t i = 0; i < arg_names.size(); ++i) {
argn[argc] = const_cast<char*>(arg_names[i].c_str());
argv[argc] = const_cast<char*>(arg_values[i].c_str());
argc++;
}
bool start_result = instance_->Start(
url, argn.get(), argv.get(), argc, load_manually);
if (!start_result)
return false;
// For windowless plugins we should set the containing window handle
// as the instance window handle. This is what Safari does. Not having
// a valid window handle causes subtle bugs with plugins which retreive
// the window handle and validate the same. The window handle can be
// retreived via NPN_GetValue of NPNVnetscapeWindow.
instance_->set_window_handle(parent_);
plugin_url_ = url.spec();
return true;
}
void WebPluginDelegatePepper::DestroyInstance() {
if (instance_ && (instance_->npp()->ndata != NULL)) {
// Shutdown all streams before destroying so that
// no streams are left "in progress". Need to do
// this before calling set_web_plugin(NULL) because the
// instance uses the helper to do the download.
instance_->CloseStreams();
window_.window = NULL;
instance_->NPP_SetWindow(&window_);
instance_->NPP_Destroy();
instance_->set_web_plugin(NULL);
instance_ = 0;
}
// Destroy the nested GPU plugin only after first destroying the underlying
// Pepper plugin. This is so the Pepper plugin does not attempt to issue
// rendering commands after the GPU plugin has stopped processing them and
// responding to them.
if (nested_delegate_) {
nested_delegate_->PluginDestroyed();
nested_delegate_ = NULL;
}
}
void WebPluginDelegatePepper::UpdateGeometry(
const gfx::Rect& window_rect,
const gfx::Rect& clip_rect) {
// Only resend to the instance if the geometry has changed.
if (window_rect == window_rect_ && clip_rect == clip_rect_)
return;
clip_rect_ = clip_rect;
cutout_rects_.clear();
if (window_rect_ == window_rect)
return;
window_rect_ = window_rect;
// TODO(brettw) figure out how to tell the plugin that the size changed and it
// needs to repaint?
SkBitmap new_committed;
new_committed.setConfig(SkBitmap::kARGB_8888_Config,
window_rect_.width(), window_rect.height());
new_committed.allocPixels();
committed_bitmap_ = new_committed;
// Forward the new geometry to the nested plugin instance.
if (nested_delegate_)
nested_delegate_->UpdateGeometry(window_rect, clip_rect);
if (!instance())
return;
// TODO(sehr): do we need all this?
window_.clipRect.top = clip_rect_.y();
window_.clipRect.left = clip_rect_.x();
window_.clipRect.bottom = clip_rect_.y() + clip_rect_.height();
window_.clipRect.right = clip_rect_.x() + clip_rect_.width();
window_.height = window_rect_.height();
window_.width = window_rect_.width();
window_.x = window_rect_.x();
window_.y = window_rect_.y();
window_.type = NPWindowTypeDrawable;
instance()->NPP_SetWindow(&window_);
}
NPObject* WebPluginDelegatePepper::GetPluginScriptableObject() {
return instance_->GetPluginScriptableObject();
}
void WebPluginDelegatePepper::DidFinishLoadWithReason(
const GURL& url,
NPReason reason,
intptr_t notify_data) {
instance()->DidFinishLoadWithReason(
url, reason, reinterpret_cast<void*>(notify_data));
}
int WebPluginDelegatePepper::GetProcessId() {
// We are in process, so the plugin pid is this current process pid.
return base::GetCurrentProcId();
}
void WebPluginDelegatePepper::SendJavaScriptStream(
const GURL& url,
const std::string& result,
bool success,
bool notify_needed,
intptr_t notify_data) {
instance()->SendJavaScriptStream(url, result, success, notify_needed,
notify_data);
}
void WebPluginDelegatePepper::DidReceiveManualResponse(
const GURL& url, const std::string& mime_type,
const std::string& headers, uint32 expected_length, uint32 last_modified) {
instance()->DidReceiveManualResponse(url, mime_type, headers,
expected_length, last_modified);
}
void WebPluginDelegatePepper::DidReceiveManualData(const char* buffer,
int length) {
instance()->DidReceiveManualData(buffer, length);
}
void WebPluginDelegatePepper::DidFinishManualLoading() {
instance()->DidFinishManualLoading();
}
void WebPluginDelegatePepper::DidManualLoadFail() {
instance()->DidManualLoadFail();
}
FilePath WebPluginDelegatePepper::GetPluginPath() {
return instance()->plugin_lib()->plugin_info().path;
}
WebPluginResourceClient* WebPluginDelegatePepper::CreateResourceClient(
unsigned long resource_id, const GURL& url, bool notify_needed,
intptr_t notify_data, intptr_t existing_stream) {
// Stream already exists. This typically happens for range requests
// initiated via NPN_RequestRead.
if (existing_stream) {
NPAPI::PluginStream* plugin_stream =
reinterpret_cast<NPAPI::PluginStream*>(existing_stream);
return plugin_stream->AsResourceClient();
}
std::string mime_type;
NPAPI::PluginStreamUrl *stream = instance()->CreateStream(
resource_id, url, mime_type, notify_needed,
reinterpret_cast<void*>(notify_data));
return stream;
}
NPError WebPluginDelegatePepper::Device2DQueryCapability(int32 capability,
int32* value) {
return NPERR_GENERIC_ERROR;
}
NPError WebPluginDelegatePepper::Device2DQueryConfig(
const NPDeviceContext2DConfig* request,
NPDeviceContext2DConfig* obtain) {
return NPERR_GENERIC_ERROR;
}
NPError WebPluginDelegatePepper::Device2DInitializeContext(
const NPDeviceContext2DConfig* config,
NPDeviceContext2D* context) {
// This is a windowless plugin, so set it to have a NULL handle. Defer this
// until we know the plugin will use the 2D device. If it uses the 3D device
// it will have a window handle.
plugin_->SetWindow(NULL);
int width = window_rect_.width();
int height = window_rect_.height();
uint32 buffer_size = width * height * kBytesPerPixel;
// Initialize the impelementation information in case of failure.
context->reserved = NULL;
// Allocate the transport DIB and the PlatformCanvas pointing to it.
scoped_ptr<OpenPaintContext> paint_context(new OpenPaintContext);
paint_context->transport_dib.reset(
TransportDIB::Create(buffer_size, ++next_buffer_id));
if (!paint_context->transport_dib.get())
return NPERR_OUT_OF_MEMORY_ERROR;
paint_context->canvas.reset(
paint_context->transport_dib->GetPlatformCanvas(width, height));
if (!paint_context->canvas.get())
return NPERR_OUT_OF_MEMORY_ERROR;
// Note that we need to get the address out of the bitmap rather than
// using plugin_buffer_->memory(). The memory() is when the bitmap data
// has had "Map" called on it. For Windows, this is separate than making a
// bitmap using the shared section.
const SkBitmap& plugin_bitmap =
paint_context->canvas->getTopPlatformDevice().accessBitmap(true);
SkAutoLockPixels locker(plugin_bitmap);
// TODO(brettw) this theoretically shouldn't be necessary. But the
// platform device on Windows will fill itself with green to help you
// catch areas you didn't paint.
plugin_bitmap.eraseARGB(0, 0, 0, 0);
// Save the implementation information (the TransportDIB).
Device2DImpl* impl = new Device2DImpl;
if (impl == NULL) {
// TODO(sehr,brettw): cleanup the context if we fail.
return NPERR_GENERIC_ERROR;
}
impl->dib = paint_context->transport_dib.get();
context->reserved = reinterpret_cast<void*>(impl);
// Save the canvas to the output context structure and save the
// OpenPaintContext for future reference.
context->region = plugin_bitmap.getAddr32(0, 0);
context->stride = width * kBytesPerPixel;
context->dirty.left = 0;
context->dirty.top = 0;
context->dirty.right = width;
context->dirty.bottom = height;
open_paint_contexts_[context->region] =
linked_ptr<OpenPaintContext>(paint_context.release());
return NPERR_NO_ERROR;
}
NPError WebPluginDelegatePepper::Device2DSetStateContext(
NPDeviceContext2D* context,
int32 state,
int32 value) {
return NPERR_GENERIC_ERROR;
}
NPError WebPluginDelegatePepper::Device2DGetStateContext(
NPDeviceContext2D* context,
int32 state,
int32* value) {
return NPERR_GENERIC_ERROR;
}
NPError WebPluginDelegatePepper::Device2DFlushContext(
NPP id,
NPDeviceContext2D* context,
NPDeviceFlushContextCallbackPtr callback,
void* user_data) {
// Get the bitmap data associated with the incoming context.
OpenPaintContextMap::iterator found = open_paint_contexts_.find(
context->region);
if (found == open_paint_contexts_.end())
return NPERR_INVALID_PARAM; // TODO(brettw) call callback.
OpenPaintContext* paint_context = found->second.get();
// Draw the bitmap to the backing store.
//
// TODO(brettw) we can optimize this in the case where the entire canvas is
// updated by actually taking ownership of the buffer and not telling the
// plugin we're done using it. This wat we can avoid the copy when the entire
// canvas has been updated.
SkIRect src_rect = { context->dirty.left,
context->dirty.top,
context->dirty.right,
context->dirty.bottom };
SkRect dest_rect = { SkIntToScalar(context->dirty.left),
SkIntToScalar(context->dirty.top),
SkIntToScalar(context->dirty.right),
SkIntToScalar(context->dirty.bottom) };
SkCanvas committed_canvas(committed_bitmap_);
// We want to replace the contents of the bitmap rather than blend.
SkPaint paint;
paint.setXfermodeMode(SkXfermode::kSrc_Mode);
committed_canvas.drawBitmapRect(
paint_context->canvas->getTopPlatformDevice().accessBitmap(false),
&src_rect, dest_rect);
committed_bitmap_.setIsOpaque(false);
// Invoke the callback to inform the caller the work was done.
// TODO(brettw) this is not how we want this to work, this should
// happen when the frame is painted so the plugin knows when it can draw
// the next frame.
//
// This should also be called in the failure cases as well.
if (callback != NULL)
(*callback)(id, context, NPERR_NO_ERROR, user_data);
return NPERR_NO_ERROR;
}
NPError WebPluginDelegatePepper::Device2DDestroyContext(
NPDeviceContext2D* context) {
OpenPaintContextMap::iterator found = open_paint_contexts_.find(
context->region);
if (found == open_paint_contexts_.end())
return NPERR_INVALID_PARAM;
open_paint_contexts_.erase(found);
// Free the implementation information.
delete reinterpret_cast<Device2DImpl*>(context->reserved);
return NPERR_NO_ERROR;
}
NPError WebPluginDelegatePepper::Device3DQueryCapability(int32 capability,
int32* value) {
return NPERR_GENERIC_ERROR;
}
NPError WebPluginDelegatePepper::Device3DQueryConfig(
const NPDeviceContext3DConfig* request,
NPDeviceContext3DConfig* obtain) {
return NPERR_GENERIC_ERROR;
}
NPError WebPluginDelegatePepper::Device3DInitializeContext(
const NPDeviceContext3DConfig* config,
NPDeviceContext3D* context) {
#if defined(ENABLE_GPU)
// Check to see if the GPU plugin is already initialized and fail if so.
if (nested_delegate_)
return NPERR_GENERIC_ERROR;
// Create an instance of the GPU plugin that is responsible for 3D
// rendering.
nested_delegate_ = new WebPluginDelegateProxy(kGPUPluginMimeType,
render_view_);
// TODO(apatrick): should the GPU plugin be attached to plugin_?
if (nested_delegate_->Initialize(GURL(),
std::vector<std::string>(),
std::vector<std::string>(),
plugin_,
false)) {
// Ask the GPU plugin to create a command buffer and return a proxy.
command_buffer_.reset(nested_delegate_->CreateCommandBuffer());
if (command_buffer_.get()) {
// Initialize the proxy command buffer.
if (command_buffer_->Initialize(config->commandBufferEntries)) {
// Initialize the 3D context.
context->reserved = NULL;
Buffer ring_buffer = command_buffer_->GetRingBuffer();
context->commandBuffer = ring_buffer.ptr;
context->commandBufferEntries = command_buffer_->GetSize();
context->getOffset = command_buffer_->GetGetOffset();
context->putOffset = command_buffer_->GetPutOffset();
// Ensure the service knows the window size before rendering anything.
nested_delegate_->UpdateGeometry(window_rect_, clip_rect_);
return NPERR_NO_ERROR;
}
}
command_buffer_.reset();
}
nested_delegate_->PluginDestroyed();
nested_delegate_ = NULL;
#endif // ENABLE_GPU
return NPERR_GENERIC_ERROR;
}
NPError WebPluginDelegatePepper::Device3DSetStateContext(
NPDeviceContext3D* context,
int32 state,
int32 value) {
return NPERR_GENERIC_ERROR;
}
NPError WebPluginDelegatePepper::Device3DGetStateContext(
NPDeviceContext3D* context,
int32 state,
int32* value) {
#if defined(ENABLE_GPU)
if (!command_buffer_.get())
return NPERR_GENERIC_ERROR;
switch (state) {
case NPDeviceContext3DState_GetOffset:
context->getOffset = *value = command_buffer_->GetGetOffset();
break;
case NPDeviceContext3DState_PutOffset:
*value = command_buffer_->GetPutOffset();
break;
case NPDeviceContext3DState_Token:
*value = command_buffer_->GetToken();
break;
case NPDeviceContext3DState_ParseError:
*value = command_buffer_->ResetParseError();
break;
case NPDeviceContext3DState_ErrorStatus:
*value = command_buffer_->GetErrorStatus() ? 1 : 0;
break;
default:
return NPERR_GENERIC_ERROR;
};
#endif // ENABLE_GPU
return NPERR_NO_ERROR;
}
NPError WebPluginDelegatePepper::Device3DFlushContext(
NPP id,
NPDeviceContext3D* context,
NPDeviceFlushContextCallbackPtr callback,
void* user_data) {
#if defined(ENABLE_GPU)
DCHECK(callback == NULL);
context->getOffset = command_buffer_->SyncOffsets(context->putOffset);
#endif // ENABLE_GPU
return NPERR_NO_ERROR;
}
NPError WebPluginDelegatePepper::Device3DDestroyContext(
NPDeviceContext3D* context) {
#if defined(ENABLE_GPU)
command_buffer_.reset();
if (nested_delegate_) {
nested_delegate_->PluginDestroyed();
nested_delegate_ = NULL;
}
#endif // ENABLE_GPU
return NPERR_NO_ERROR;
}
NPError WebPluginDelegatePepper::Device3DCreateBuffer(
NPDeviceContext3D* context,
size_t size,
int32* id) {
#if defined(ENABLE_GPU)
*id = command_buffer_->CreateTransferBuffer(size);
if (*id < 0)
return NPERR_GENERIC_ERROR;
#endif // ENABLE_GPU
return NPERR_NO_ERROR;
}
NPError WebPluginDelegatePepper::Device3DDestroyBuffer(
NPDeviceContext3D* context,
int32 id) {
#if defined(ENABLE_GPU)
command_buffer_->DestroyTransferBuffer(id);
#endif // ENABLE_GPU
return NPERR_NO_ERROR;
}
NPError WebPluginDelegatePepper::Device3DMapBuffer(
NPDeviceContext3D* context,
int32 id,
NPDeviceBuffer* np_buffer) {
#if defined(ENABLE_GPU)
Buffer gpu_buffer = command_buffer_->GetTransferBuffer(id);
np_buffer->ptr = gpu_buffer.ptr;
np_buffer->size = gpu_buffer.size;
if (!np_buffer->ptr)
return NPERR_GENERIC_ERROR;
#endif // ENABLE_GPU
return NPERR_NO_ERROR;
}
WebPluginDelegatePepper::WebPluginDelegatePepper(
const base::WeakPtr<RenderView>& render_view,
gfx::PluginWindowHandle containing_view,
NPAPI::PluginInstance *instance)
: render_view_(render_view),
plugin_(NULL),
instance_(instance),
parent_(containing_view),
buffer_size_(0),
plugin_buffer_(0),
nested_delegate_(NULL) {
// For now we keep a window struct, although it isn't used.
memset(&window_, 0, sizeof(window_));
// All Pepper plugins are windowless and transparent.
// TODO(sehr): disable resetting these NPPVs by plugins.
instance->set_windowless(true);
instance->set_transparent(true);
}
WebPluginDelegatePepper::~WebPluginDelegatePepper() {
DestroyInstance();
}
void WebPluginDelegatePepper::PluginDestroyed() {
delete this;
}
void WebPluginDelegatePepper::Paint(WebKit::WebCanvas* canvas,
const gfx::Rect& rect) {
#if defined(OS_WIN)
if (nested_delegate_) {
// TODO(apatrick): The GPU plugin will render to an offscreen render target.
// Need to copy it to the screen here.
} else {
// Blit from background_context to context.
if (!committed_bitmap_.isNull()) {
gfx::Point origin(window_rect_.origin().x(), window_rect_.origin().y());
canvas->drawBitmap(committed_bitmap_,
SkIntToScalar(window_rect_.origin().x()),
SkIntToScalar(window_rect_.origin().y()));
}
}
#endif
}
void WebPluginDelegatePepper::Print(gfx::NativeDrawingContext context) {
NOTIMPLEMENTED();
}
void WebPluginDelegatePepper::InstallMissingPlugin() {
NOTIMPLEMENTED();
}
void WebPluginDelegatePepper::SetFocus() {
NPPepperEvent npevent;
npevent.type = NPEventType_Focus;
npevent.size = sizeof(npevent);
// TODO(sehr): what timestamp should this have?
npevent.timeStampSeconds = 0.0;
// Currently this API only supports gaining focus.
npevent.u.focus.value = 1;
instance()->NPP_HandleEvent(&npevent);
}
// Anonymous namespace for functions converting WebInputEvents to NPAPI types.
namespace {
NPEventTypes ConvertEventTypes(WebInputEvent::Type wetype) {
switch (wetype) {
case WebInputEvent::MouseDown:
return NPEventType_MouseDown;
case WebInputEvent::MouseUp:
return NPEventType_MouseUp;
case WebInputEvent::MouseMove:
return NPEventType_MouseMove;
case WebInputEvent::MouseEnter:
return NPEventType_MouseEnter;
case WebInputEvent::MouseLeave:
return NPEventType_MouseLeave;
case WebInputEvent::MouseWheel:
return NPEventType_MouseWheel;
case WebInputEvent::RawKeyDown:
return NPEventType_RawKeyDown;
case WebInputEvent::KeyDown:
return NPEventType_KeyDown;
case WebInputEvent::KeyUp:
return NPEventType_KeyUp;
case WebInputEvent::Char:
return NPEventType_Char;
case WebInputEvent::Undefined:
default:
return NPEventType_Undefined;
}
}
void BuildKeyEvent(const WebInputEvent* event, NPPepperEvent* npevent) {
const WebKeyboardEvent* key_event =
reinterpret_cast<const WebKeyboardEvent*>(event);
npevent->u.key.modifier = key_event->modifiers;
npevent->u.key.normalizedKeyCode = key_event->windowsKeyCode;
}
void BuildCharEvent(const WebInputEvent* event, NPPepperEvent* npevent) {
const WebKeyboardEvent* key_event =
reinterpret_cast<const WebKeyboardEvent*>(event);
npevent->u.character.modifier = key_event->modifiers;
// For consistency, check that the sizes of the texts agree.
DCHECK(sizeof(npevent->u.character.text) == sizeof(key_event->text));
DCHECK(sizeof(npevent->u.character.unmodifiedText) ==
sizeof(key_event->unmodifiedText));
for (size_t i = 0; i < WebKeyboardEvent::textLengthCap; ++i) {
npevent->u.character.text[i] = key_event->text[i];
npevent->u.character.unmodifiedText[i] = key_event->unmodifiedText[i];
}
}
void BuildMouseEvent(const WebInputEvent* event, NPPepperEvent* npevent) {
const WebMouseEvent* mouse_event =
reinterpret_cast<const WebMouseEvent*>(event);
npevent->u.mouse.modifier = mouse_event->modifiers;
npevent->u.mouse.button = mouse_event->button;
npevent->u.mouse.x = mouse_event->x;
npevent->u.mouse.y = mouse_event->y;
npevent->u.mouse.clickCount = mouse_event->clickCount;
}
void BuildMouseWheelEvent(const WebInputEvent* event, NPPepperEvent* npevent) {
const WebMouseWheelEvent* mouse_wheel_event =
reinterpret_cast<const WebMouseWheelEvent*>(event);
npevent->u.wheel.modifier = mouse_wheel_event->modifiers;
npevent->u.wheel.deltaX = mouse_wheel_event->deltaX;
npevent->u.wheel.deltaY = mouse_wheel_event->deltaY;
npevent->u.wheel.wheelTicksX = mouse_wheel_event->wheelTicksX;
npevent->u.wheel.wheelTicksY = mouse_wheel_event->wheelTicksY;
npevent->u.wheel.scrollByPage = mouse_wheel_event->scrollByPage;
}
} // namespace
bool WebPluginDelegatePepper::HandleInputEvent(const WebInputEvent& event,
WebCursorInfo* cursor_info) {
NPPepperEvent npevent;
npevent.type = ConvertEventTypes(event.type);
npevent.size = sizeof(npevent);
npevent.timeStampSeconds = event.timeStampSeconds;
switch (npevent.type) {
case NPEventType_Undefined:
return false;
case NPEventType_MouseDown:
case NPEventType_MouseUp:
case NPEventType_MouseMove:
case NPEventType_MouseEnter:
case NPEventType_MouseLeave:
BuildMouseEvent(&event, &npevent);
break;
case NPEventType_MouseWheel:
BuildMouseWheelEvent(&event, &npevent);
break;
case NPEventType_RawKeyDown:
case NPEventType_KeyDown:
case NPEventType_KeyUp:
BuildKeyEvent(&event, &npevent);
break;
case NPEventType_Char:
BuildCharEvent(&event, &npevent);
break;
case NPEventType_Minimize:
case NPEventType_Focus:
case NPEventType_Device:
// NOTIMPLEMENTED();
break;
}
return instance()->NPP_HandleEvent(&npevent) != 0;
}
| 33.005398 | 80 | 0.716973 | rwatson |
068f41ee5c4d1a547e30fde1bd45ff15e98483af | 2,335 | cpp | C++ | ch13-02-single-segment/src/main.cpp | pulpobot/C-SFML-html5-animation | 14154008b853d1235e8ca35a5b23b6a70366f914 | [
"MIT"
] | 73 | 2017-12-14T00:33:23.000Z | 2022-02-09T12:04:52.000Z | ch13-02-single-segment/src/main.cpp | threaderic/C-SFML-html5-animation | 22f302cdf7c7c00247609da30e1bcf472d134583 | [
"MIT"
] | null | null | null | ch13-02-single-segment/src/main.cpp | threaderic/C-SFML-html5-animation | 22f302cdf7c7c00247609da30e1bcf472d134583 | [
"MIT"
] | 5 | 2017-12-26T03:30:07.000Z | 2020-07-05T04:58:24.000Z | #include <iostream>
#include "SFML\Graphics.hpp"
#include "Segment.h"
#include "Utils.h"
#include "Slider.h"
void OnHandleMoveCallback(Slider *slider){
slider->handle.setPosition(slider->background.getPosition().x, slider->handleY + slider->background.getPosition().y);
}
int main() {
//You can turn off antialiasing if your graphics card doesn't support it
sf::ContextSettings context;
context.antialiasingLevel = 4;
sf::RenderWindow window(sf::VideoMode(400, 400), "Single Segment", sf::Style::Titlebar | sf::Style::Close,
context);
window.setFramerateLimit(60);
sf::Font font;
if(!font.loadFromFile("res/cour.ttf")){
std::cerr << "Error loading cour.ttf file" << std::endl;
return -1;
}
sf::Text infoText;
infoText.setFont(font);
infoText.setCharacterSize(15);
infoText.setFillColor(sf::Color::Black);
infoText.setPosition(sf::Vector2f(10,window.getSize().y - 30));
infoText.setString("Press and drag slider handle with mouse.");
Segment segment = Segment(100, 20);
segment.SetX(100);
segment.SetY(100);
Slider slider = Slider(-90,90,0);
slider.SetX(300);
slider.SetY(20);
slider.onChange = &OnHandleMoveCallback;
bool mouseOnSlider = false;
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
sf::Vector2f mousePos;
switch (event.type) {
case sf::Event::Closed:
window.close();
break;
case sf::Event::MouseButtonPressed:
mousePos = sf::Vector2f(event.mouseButton.x, event.mouseButton.y);
slider.CaptureMouse(mousePos);
break;
case sf::Event::MouseButtonReleased:
slider.OnMouseRelease();
break;
case sf::Event::MouseMoved:
mousePos = sf::Vector2f(event.mouseMove.x, event.mouseMove.y);
slider.OnMouseMove(mousePos);
break;
}
}
segment.SetRotation(slider.value);
window.clear(sf::Color::White);
segment.Draw(window);
slider.Draw(window);
window.draw(infoText);
window.display();
}
} | 32.430556 | 121 | 0.582441 | pulpobot |
06985a43292318fac4c3ffbe711bfb3098f0548c | 1,192 | hpp | C++ | include/mold/domain/mustache/parser.hpp | duzy/mold | 52a813bf2858e9719b89b1250702c82be4c2a78d | [
"BSL-1.0"
] | 7 | 2016-10-02T13:29:55.000Z | 2022-02-06T09:21:00.000Z | include/mold/domain/mustache/parser.hpp | extbit/mold | 68cc3dd815c4e7a39ab5f68f7525a6c36a1e036f | [
"BSL-1.0"
] | 1 | 2020-06-09T01:26:21.000Z | 2020-06-09T01:26:21.000Z | include/mold/domain/mustache/parser.hpp | extbit/mold | 68cc3dd815c4e7a39ab5f68f7525a6c36a1e036f | [
"BSL-1.0"
] | 2 | 2019-09-08T05:30:31.000Z | 2020-08-27T13:03:49.000Z | /**
* \file boost/mold/domain/mustache/grammar.hpp
*
* Copyright 2016~2019 Duzy Chan <code@extbit.io>, ExtBit Limited
*
* 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)
*/
#ifndef _BOOST_MOLD_DOMAIN_MUSTACHE_PARSER_HPP_
#define _BOOST_MOLD_DOMAIN_MUSTACHE_PARSER_HPP_ 1
#include <mold/domain/mustache/ast.hpp>
#include <boost/spirit/home/x3/support/traits/is_variant.hpp>
#include <boost/spirit/home/x3/support/traits/tuple_traits.hpp>
#include <boost/spirit/home/x3/nonterminal/rule.hpp>
namespace mold { namespace domain { namespace mustache
{
namespace parser
{
namespace x3 = boost::spirit::x3;
using mustache_type = x3::rule<struct mustache_class, ast::node_list>;
BOOST_SPIRIT_DECLARE(mustache_type)
}
const parser::mustache_type &spec();
}}} // namespace mold::domain::mustache
#define BOOST_MOLD_MUSTACHE_INSTANTIATE(iterator_type) \
namespace mold { namespace domain { namespace mustache { namespace parser \
{ BOOST_SPIRIT_INSTANTIATE(mustache_type, iterator_type, ::mold::value) }}}}
#endif//_BOOST_MOLD_DOMAIN_MUSTACHE_PARSER_HPP_
| 36.121212 | 80 | 0.765101 | duzy |
06985cb70c970a359b7b5e380300257ab4998709 | 383 | cpp | C++ | src/ccw.cpp | hgu-sit22005/telloproject-NaGyungMin15 | 30429e7cc922cf811db4c85d1aa266029c6c29b6 | [
"MIT"
] | null | null | null | src/ccw.cpp | hgu-sit22005/telloproject-NaGyungMin15 | 30429e7cc922cf811db4c85d1aa266029c6c29b6 | [
"MIT"
] | null | null | null | src/ccw.cpp | hgu-sit22005/telloproject-NaGyungMin15 | 30429e7cc922cf811db4c85d1aa266029c6c29b6 | [
"MIT"
] | null | null | null | #include "ccw.h"
#include <cstring>
#include <sstream>
ccw::ccw()
{
command = new char[strlen("ccw 90")+1];
strcpy(command, "ccw 90");
}
ccw::ccw(int _val)
{
std::stringstream sstream;
sstream << "ccw " << _val;
command = new char[strlen(sstream.str().c_str())+1];
strcpy(command, sstream.str().c_str());
}
double ccw::get_delay()
{
return 2;
} | 15.32 | 54 | 0.592689 | hgu-sit22005 |
069917eabac71dc9c402d5ee286ea3ee8ea2d6e0 | 15,795 | cpp | C++ | sycl/source/detail/program_manager/program_manager.cpp | Ralender/sycl | 1fcd1e6d3da10024be92148501aced30ae3aa2be | [
"Apache-2.0"
] | 1 | 2020-09-25T23:33:05.000Z | 2020-09-25T23:33:05.000Z | sycl/source/detail/program_manager/program_manager.cpp | Ralender/sycl | 1fcd1e6d3da10024be92148501aced30ae3aa2be | [
"Apache-2.0"
] | null | null | null | sycl/source/detail/program_manager/program_manager.cpp | Ralender/sycl | 1fcd1e6d3da10024be92148501aced30ae3aa2be | [
"Apache-2.0"
] | null | null | null | //==------ program_manager.cpp --- SYCL program manager---------------------==//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include <CL/sycl/context.hpp>
#include <CL/sycl/detail/common.hpp>
#include <CL/sycl/detail/os_util.hpp>
#include <CL/sycl/detail/program_manager/program_manager.hpp>
#include <CL/sycl/detail/util.hpp>
#include <CL/sycl/device.hpp>
#include <CL/sycl/exception.hpp>
#include <CL/sycl/stl.hpp>
#include <boost/container_hash/hash.hpp> // uuid_hasher
#include <boost/uuid/uuid_generators.hpp> // sha name_gen/generator
#include <boost/uuid/uuid_io.hpp> // uuid to_string
#include <assert.h>
#include <cstdlib>
#include <fstream>
#include <memory>
#include <mutex>
#include <sstream>
namespace cl {
namespace sycl {
namespace detail {
static constexpr int DbgProgMgr = 0;
ProgramManager &ProgramManager::getInstance() {
// The singleton ProgramManager instance, uses the "magic static" idiom.
static ProgramManager Instance;
return Instance;
}
static RT::PiDevice getFirstDevice(RT::PiContext Context) {
cl_uint NumDevices = 0;
PI_CALL(RT::piContextGetInfo(Context, PI_CONTEXT_INFO_NUM_DEVICES,
sizeof(NumDevices), &NumDevices,
/*param_value_size_ret=*/nullptr));
assert(NumDevices > 0 && "Context without devices?");
vector_class<RT::PiDevice> Devices(NumDevices);
size_t ParamValueSize = 0;
PI_CALL(RT::piContextGetInfo(Context, PI_CONTEXT_INFO_DEVICES,
sizeof(cl_device_id) * NumDevices, &Devices[0],
&ParamValueSize));
assert(ParamValueSize == sizeof(cl_device_id) * NumDevices &&
"Number of CL_CONTEXT_DEVICES should match CL_CONTEXT_NUM_DEVICES.");
return Devices[0];
}
static RT::PiProgram createBinaryProgram(const RT::PiContext Context,
const unsigned char *Data,
size_t DataLen) {
// FIXME: we don't yet support multiple devices with a single binary.
#ifndef _NDEBUG
cl_uint NumDevices = 0;
PI_CALL(RT::piContextGetInfo(Context, PI_CONTEXT_INFO_NUM_DEVICES,
sizeof(NumDevices), &NumDevices,
/*param_value_size_ret=*/nullptr));
assert(NumDevices > 0 &&
"Only a single device is supported for AOT compilation");
#endif
RT::PiDevice Device = getFirstDevice(Context);
RT::PiResult Err = PI_SUCCESS;
pi_int32 BinaryStatus = CL_SUCCESS;
RT::PiProgram Program;
PI_CALL((Program = RT::piclProgramCreateWithBinary(
Context, 1 /*one binary*/, &Device,
&DataLen, &Data, &BinaryStatus, &Err), Err));
return Program;
}
static RT::PiProgram createSpirvProgram(const RT::PiContext Context,
const unsigned char *Data,
size_t DataLen) {
RT::PiResult Err = PI_SUCCESS;
RT::PiProgram Program;
PI_CALL((Program = pi::pi_cast<pi_program>(
pi::piProgramCreate(pi::pi_cast<pi_context>(Context), Data, DataLen,
pi::pi_cast<pi_result *>(&Err))),
Err));
return Program;
}
RT::PiProgram ProgramManager::getBuiltOpenCLProgram(OSModuleHandle M,
const context &Context) {
RT::PiProgram &Program = m_CachedSpirvPrograms[std::make_pair(Context, M)];
if (!Program) {
DeviceImage *Img = nullptr;
Program = loadProgram(M, Context, &Img);
build(Program, Img->BuildOptions);
}
return Program;
}
// Gets a unique name to a kernel name which is currently computed from a SHA-1
// hash of the kernel name. This unique name is used in place of the kernels
// mangled name inside of xocc computed binaries containing the kernels.
//
// This is in part due to a limitation of xocc in which it requires kernel names
// to be passed to it when compiling kernels and it doesn't handle certain
// characters in mangled names very well e.g. '$'.
static std::string getUniqueName(const char *KernelName) {
boost::uuids::name_generator_latest gen{boost::uuids::ns::dns()};
boost::uuids::uuid udoc = gen(KernelName);
boost::hash<boost::uuids::uuid> uuid_hasher;
std::size_t uuid_hash_value = uuid_hasher(udoc);
return "xSYCL" + std::to_string(uuid_hash_value);
}
RT::PiKernel ProgramManager::getOrCreateKernel(OSModuleHandle M,
const context &Context,
const string_class &KernelName) {
/// \todo: Extend this to work for more than the first device in the context
/// most of the run-time only works with a single device right now, but this
/// should be changed long term.
/// \todo: This works at the moment, but there needs to be a change earlier on
/// in the runtime to exchange the real kernel name with the hashed kernel
/// name so the hashed variant is always used when its a Xilinx device.
auto Devices = Context.get_devices();
std::string uniqueName = KernelName;
if (!Devices.empty()
&& Devices[0].get_info<info::device::vendor>() == "Xilinx")
uniqueName = getUniqueName(uniqueName.c_str());
if (DbgProgMgr > 0) {
std::cerr << ">>> ProgramManager::getOrCreateKernel(" << M << ", "
<< getRawSyclObjImpl(Context) << ", " << uniqueName << ")\n";
}
RT::PiProgram Program = getBuiltOpenCLProgram(M, Context);
std::map<string_class, RT::PiKernel> &KernelsCache = m_CachedKernels[Program];
RT::PiKernel &Kernel = KernelsCache[uniqueName];
if (!Kernel) {
RT::PiResult Err = PI_SUCCESS;
PI_CALL((Kernel = RT::piKernelCreate(
Program, uniqueName.c_str(), &Err), Err));
}
return Kernel;
}
RT::PiProgram ProgramManager::getClProgramFromClKernel(RT::PiKernel Kernel) {
RT::PiProgram Program;
PI_CALL(RT::piKernelGetInfo(
Kernel, CL_KERNEL_PROGRAM, sizeof(cl_program), &Program, nullptr));
return Program;
}
void ProgramManager::build(RT::PiProgram &Program, const string_class &Options,
std::vector<RT::PiDevice> Devices) {
if (DbgProgMgr > 0) {
std::cerr << ">>> ProgramManager::build(" << Program << ", " << Options
<< ", ... " << Devices.size() << ")\n";
}
const char *Opts = std::getenv("SYCL_PROGRAM_BUILD_OPTIONS");
for (const auto &DeviceId : Devices) {
if (!createSyclObjFromImpl<device>(std::make_shared<device_impl_pi>(DeviceId)).
get_info<info::device::is_compiler_available>()) {
throw feature_not_supported(
"Online compilation is not supported by this device");
}
}
if (!Opts)
Opts = Options.c_str();
if (PI_CALL_RESULT(RT::piProgramBuild(
Program, Devices.size(), Devices.data(),
Opts, nullptr, nullptr)) == PI_SUCCESS)
return;
// Get OpenCL build log and add it to the exception message.
size_t Size = 0;
PI_CALL(RT::piProgramGetInfo(
Program, CL_PROGRAM_DEVICES, 0, nullptr, &Size));
std::vector<RT::PiDevice> DevIds(Size / sizeof(RT::PiDevice));
PI_CALL(RT::piProgramGetInfo(
Program, CL_PROGRAM_DEVICES, Size, DevIds.data(), nullptr));
std::string Log;
for (RT::PiDevice &DevId : DevIds) {
PI_CALL(RT::piProgramGetBuildInfo(
Program, DevId, CL_PROGRAM_BUILD_LOG, 0, nullptr, &Size));
std::vector<char> BuildLog(Size);
PI_CALL(RT::piProgramGetBuildInfo(
Program, DevId, CL_PROGRAM_BUILD_LOG, Size,
BuildLog.data(), nullptr));
device Dev = createSyclObjFromImpl<device>(
std::make_shared<device_impl_pi>(DevId));
Log += "\nBuild program fail log for '" +
Dev.get_info<info::device::name>() + "':\n" + BuildLog.data();
}
throw compile_program_error(Log.c_str());
}
bool ProgramManager::ContextAndModuleLess::
operator()(const std::pair<context, OSModuleHandle> &LHS,
const std::pair<context, OSModuleHandle> &RHS) const {
if (LHS.first != RHS.first)
return getRawSyclObjImpl(LHS.first) < getRawSyclObjImpl(RHS.first);
return reinterpret_cast<intptr_t>(LHS.second) <
reinterpret_cast<intptr_t>(RHS.second);
}
void ProgramManager::addImages(pi_device_binaries DeviceBinary) {
std::lock_guard<std::mutex> Guard(Sync::getGlobalLock());
for (int I = 0; I < DeviceBinary->NumDeviceBinaries; I++) {
pi_device_binary Img = &(DeviceBinary->DeviceBinaries[I]);
OSModuleHandle M = OSUtil::getOSModuleHandle(Img);
auto &Imgs = m_DeviceImages[M];
if (Imgs == nullptr)
Imgs.reset(new std::vector<DeviceImage *>());
Imgs->push_back(Img);
}
}
void ProgramManager::debugDumpBinaryImage(const DeviceImage *Img) const {
std::cerr << " --- Image " << Img << "\n";
if (!Img)
return;
std::cerr << " Version : " << (int)Img->Version << "\n";
std::cerr << " Kind : " << (int)Img->Kind << "\n";
std::cerr << " Format : " << (int)Img->Format << "\n";
std::cerr << " Target : " << Img->DeviceTargetSpec << "\n";
std::cerr << " Options : "
<< (Img->BuildOptions ? Img->BuildOptions : "NULL") << "\n";
std::cerr << " Bin size : "
<< ((intptr_t)Img->BinaryEnd - (intptr_t)Img->BinaryStart) << "\n";
}
void ProgramManager::debugDumpBinaryImages() const {
for (const auto &ModImgvec : m_DeviceImages) {
std::cerr << " ++++++ Module: " << ModImgvec.first << "\n";
for (const auto *Img : *(ModImgvec.second)) {
debugDumpBinaryImage(Img);
}
}
}
struct ImageDeleter {
void operator()(DeviceImage *I) {
delete[] I->BinaryStart;
delete I;
}
};
RT::PiProgram ProgramManager::loadProgram(OSModuleHandle M,
const context &Context,
DeviceImage **I) {
std::lock_guard<std::mutex> Guard(Sync::getGlobalLock());
if (DbgProgMgr > 0) {
std::cerr << ">>> ProgramManager::loadProgram(" << M << ","
<< getRawSyclObjImpl(Context) << ")\n";
}
DeviceImage *Img = nullptr;
bool UseKernelSpv = false;
const std::string UseSpvEnv("SYCL_USE_KERNEL_SPV");
if (const char *Spv = std::getenv(UseSpvEnv.c_str())) {
// The env var requests that the program is loaded from a SPIRV file on disk
UseKernelSpv = true;
std::string Fname(Spv);
std::ifstream File(Fname, std::ios::binary);
if (!File.is_open()) {
throw runtime_error(std::string("Can't open file specified via ") +
UseSpvEnv + ": " + Fname);
}
File.seekg(0, std::ios::end);
size_t Size = File.tellg();
auto *Data = new unsigned char[Size];
File.seekg(0);
File.read(reinterpret_cast<char *>(Data), Size);
File.close();
if (!File.good()) {
delete[] Data;
throw runtime_error(std::string("read from ") + Fname +
std::string(" failed"));
}
Img = new DeviceImage();
Img->Version = PI_DEVICE_BINARY_VERSION;
Img->Kind = PI_DEVICE_BINARY_OFFLOAD_KIND_SYCL;
Img->Format = PI_DEVICE_BINARY_TYPE_NONE;
Img->DeviceTargetSpec = PI_DEVICE_BINARY_TARGET_UNKNOWN;
Img->BuildOptions = "";
Img->ManifestStart = nullptr;
Img->ManifestEnd = nullptr;
Img->BinaryStart = Data;
Img->BinaryEnd = Data + Size;
Img->EntriesBegin = nullptr;
Img->EntriesEnd = nullptr;
std::unique_ptr<DeviceImage, ImageDeleter> ImgPtr(Img, ImageDeleter());
m_OrphanDeviceImages.emplace_back(std::move(ImgPtr));
if (DbgProgMgr > 0) {
std::cerr << "loaded device image from " << Fname << "\n";
}
} else {
// Take all device images in module M and ask the native runtime under the
// given context to choose one it prefers.
auto ImgIt = m_DeviceImages.find(M);
if (ImgIt == m_DeviceImages.end()) {
throw runtime_error("No device program image found");
}
std::vector<DeviceImage *> *Imgs = (ImgIt->second).get();
PI_CALL(RT::piextDeviceSelectBinary(
0, Imgs->data(), (cl_uint)Imgs->size(), &Img));
if (DbgProgMgr > 0) {
std::cerr << "available device images:\n";
debugDumpBinaryImages();
std::cerr << "selected device image: " << Img << "\n";
debugDumpBinaryImage(Img);
}
}
// perform minimal sanity checks on the device image and the descriptor
if (Img->BinaryEnd < Img->BinaryStart) {
throw runtime_error("Malformed device program image descriptor");
}
if (Img->BinaryEnd == Img->BinaryStart) {
throw runtime_error("Invalid device program image: size is zero");
}
size_t ImgSize = static_cast<size_t>(Img->BinaryEnd - Img->BinaryStart);
auto Format = pi::pi_cast<RT::PiDeviceBinaryType>(Img->Format);
// Determine the format of the image if not set already
if (Format == PI_DEVICE_BINARY_TYPE_NONE) {
struct {
RT::PiDeviceBinaryType Fmt;
const uint32_t Magic;
} Fmts[] = {{PI_DEVICE_BINARY_TYPE_SPIRV, 0x07230203},
{PI_DEVICE_BINARY_TYPE_LLVMIR_BITCODE, 0xDEC04342}};
if (ImgSize >= sizeof(Fmts[0].Magic)) {
std::remove_const<decltype(Fmts[0].Magic)>::type Hdr = 0;
std::copy(Img->BinaryStart, Img->BinaryStart + sizeof(Hdr),
reinterpret_cast<char *>(&Hdr));
for (const auto &Fmt : Fmts) {
if (Hdr == Fmt.Magic) {
Format = Fmt.Fmt;
// Image binary format wasn't set but determined above - update it;
if (UseKernelSpv) {
Img->Format = Format;
} else {
// TODO the binary image is a part of the fat binary, the clang
// driver should have set proper format option to the
// clang-offload-wrapper. The fix depends on AOT compilation
// implementation, so will be implemented together with it.
// Img->Format can't be updated as it is inside of the in-memory
// OS module binary.
// throw runtime_error("Image format not set");
}
if (DbgProgMgr > 1) {
std::cerr << "determined image format: " << (int)Format << "\n";
}
break;
}
}
}
}
// Dump program image if requested
if (std::getenv("SYCL_DUMP_IMAGES") && !UseKernelSpv) {
std::string Fname("sycl_");
Fname += Img->DeviceTargetSpec;
std::string Ext;
if (Format == PI_DEVICE_BINARY_TYPE_SPIRV) {
Ext = ".spv";
} else if (Format == PI_DEVICE_BINARY_TYPE_LLVMIR_BITCODE) {
Ext = ".bc";
} else {
Ext = ".bin";
}
Fname += Ext;
std::ofstream F(Fname, std::ios::binary);
if (!F.is_open()) {
throw runtime_error(std::string("Can not write ") + Fname);
}
F.write(reinterpret_cast<const char *>(Img->BinaryStart), ImgSize);
F.close();
}
// Load the selected image
const RT::PiContext &Ctx = getRawSyclObjImpl(Context)->getHandleRef();
RT::PiProgram Res = nullptr;
Res = Format == PI_DEVICE_BINARY_TYPE_SPIRV
? createSpirvProgram(Ctx, Img->BinaryStart, ImgSize)
: createBinaryProgram(Ctx, Img->BinaryStart, ImgSize);
if (I)
*I = Img;
if (DbgProgMgr > 1) {
std::cerr << "created native program: " << Res << "\n";
}
return Res;
}
} // namespace detail
} // namespace sycl
} // namespace cl
extern "C" void __tgt_register_lib(pi_device_binaries desc) {
cl::sycl::detail::ProgramManager::getInstance().addImages(desc);
}
// Executed as a part of current module's (.exe, .dll) static initialization
extern "C" void __tgt_unregister_lib(pi_device_binaries desc) {
// TODO implement the function
}
| 36.394009 | 83 | 0.628807 | Ralender |
069b203acdc3a69df518b9e00da0d094acb6c7d8 | 1,149 | cpp | C++ | Algorithms/Dynamic-Programming-Algorithms/levenstein_distance.cpp | tensorush/Computer-Scientists-Toolkit | f48aadf6387b935ac593f6a5513352c3bf562cb0 | [
"MIT"
] | 9 | 2021-07-11T19:53:36.000Z | 2022-03-28T15:04:38.000Z | Algorithms/Dynamic-Programming-Algorithms/levenstein_distance.cpp | geotrush/Computer-Scientists-Toolkit | f48aadf6387b935ac593f6a5513352c3bf562cb0 | [
"MIT"
] | 1 | 2022-01-18T09:49:36.000Z | 2022-01-18T17:50:12.000Z | Algorithms/Dynamic-Programming-Algorithms/levenstein_distance.cpp | geotrush/Computer-Scientists-Toolkit | f48aadf6387b935ac593f6a5513352c3bf562cb0 | [
"MIT"
] | 2 | 2021-11-15T08:02:25.000Z | 2022-03-21T14:29:15.000Z | /*
Levenshtein Distance
--------------------
Time: O(n*m)
Space: O(n*m)
*/
#include <algorithm>
#include <iostream>
#include <vector>
#include <string>
int LevensteinDistance(const std::string& string_1, const std::string& string_2) {
unsigned n = string_1.size(), m = string_2.size();
std::vector<std::vector<int>> distances(2, std::vector<int>(m + 1));
for (unsigned i = 0; i <= n; ++i) {
for (unsigned j = 0; j <= m; ++j) {
if (i == 0 || j == 0) {
distances[i & 1][j] = i + j;
continue;
}
int insert_distance = distances[i & 1][j - 1] + 1;
int delete_distance = distances[(i - 1) & 1][j] + 1;
int match_distance = distances[(i - 1) & 1][j - 1] + (string_1[n - i] != string_2[m - j]);
distances[i & 1][j] = std::min({ insert_distance, delete_distance, match_distance });
}
}
return distances[n & 1][m];
}
int main() {
std::string string_1, string_2;
std::cin >> string_1 >> string_2;
std::cout << LevensteinDistance(string_1, string_2) << std::endl;
return EXIT_SUCCESS;
} | 31.916667 | 102 | 0.530896 | tensorush |
069ce545b7142abfb5d8fb450aa5255937f6ae1c | 1,772 | cpp | C++ | Modules/MitkExt/Testing/mitkSurfaceToImageFilterTest.cpp | rfloca/MITK | b7dcb830dc36a5d3011b9828c3d71e496d3936ad | [
"BSD-3-Clause"
] | null | null | null | Modules/MitkExt/Testing/mitkSurfaceToImageFilterTest.cpp | rfloca/MITK | b7dcb830dc36a5d3011b9828c3d71e496d3936ad | [
"BSD-3-Clause"
] | null | null | null | Modules/MitkExt/Testing/mitkSurfaceToImageFilterTest.cpp | rfloca/MITK | b7dcb830dc36a5d3011b9828c3d71e496d3936ad | [
"BSD-3-Clause"
] | null | null | null | /*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include <mitkTestingMacros.h>
#include <mitkIOUtil.h>
#include "mitkSurfaceToImageFilter.h"
#include <vtkPolyData.h>
int mitkSurfaceToImageFilterTest(int argc, char* argv[])
{
MITK_TEST_BEGIN( "mitkSurfaceToImageFilterTest");
mitk::SurfaceToImageFilter::Pointer surfaceToImageFilter = mitk::SurfaceToImageFilter::New();
mitk::Surface::Pointer inputSurface = mitk::IOUtil::LoadSurface( std::string(argv[1]) );
//todo I don't know if this image is always needed. There is no documentation of the filter. Use git blame and ask the author.
mitk::Image::Pointer additionalInputImage = mitk::Image::New();
additionalInputImage->Initialize( mitk::MakeScalarPixelType<unsigned int>(), *inputSurface->GetGeometry());
//Arrange the filter
//The docu does not really tell if this is always needed. Could we skip SetImage in any case?
surfaceToImageFilter->MakeOutputBinaryOn();
surfaceToImageFilter->SetInput(inputSurface);
surfaceToImageFilter->SetImage(additionalInputImage);
surfaceToImageFilter->Update();
MITK_TEST_CONDITION_REQUIRED( surfaceToImageFilter->GetOutput()->GetPixelType().GetComponentType() == itk::ImageIOBase::UCHAR, "SurfaceToImageFilter_AnyInputImageAndModeSetToBinary_ResultIsImageWithUCHARPixelType");
MITK_TEST_END();
}
| 37.702128 | 217 | 0.727991 | rfloca |
069d4c08c678210af0599ce85b3a48e5dc35b848 | 3,116 | hpp | C++ | dev/Code/CryEngine/RenderDll/XRenderD3D9/DXGL/Interfaces/CCryDXGLShader.hpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 1,738 | 2017-09-21T10:59:12.000Z | 2022-03-31T21:05:46.000Z | dev/Code/CryEngine/RenderDll/XRenderD3D9/DXGL/Interfaces/CCryDXGLShader.hpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 427 | 2017-09-29T22:54:36.000Z | 2022-02-15T19:26:50.000Z | dev/Code/CryEngine/RenderDll/XRenderD3D9/DXGL/Interfaces/CCryDXGLShader.hpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 671 | 2017-09-21T08:04:01.000Z | 2022-03-29T14:30:07.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
// Description : Declaration of the DXGL wrapper for D3D11 shader interfaces
#ifndef __CRYDXGLSHADER__
#define __CRYDXGLSHADER__
#include "CCryDXGLDeviceChild.hpp"
namespace NCryOpenGL
{
struct SShader;
}
class CCryDXGLShader
: public CCryDXGLDeviceChild
{
public:
CCryDXGLShader(NCryOpenGL::SShader* pGLShader, CCryDXGLDevice* pDevice);
virtual ~CCryDXGLShader();
NCryOpenGL::SShader* GetGLShader();
private:
_smart_ptr<NCryOpenGL::SShader> m_spGLShader;
};
class CCryDXGLVertexShader
: public CCryDXGLShader
{
public:
DXGL_IMPLEMENT_INTERFACE(CCryDXGLVertexShader, D3D11VertexShader)
CCryDXGLVertexShader(NCryOpenGL::SShader* pGLShader, CCryDXGLDevice* pDevice)
: CCryDXGLShader(pGLShader, pDevice)
{
DXGL_INITIALIZE_INTERFACE(D3D11VertexShader)
}
};
class CCryDXGLHullShader
: public CCryDXGLShader
{
public:
DXGL_IMPLEMENT_INTERFACE(CCryDXGLHullShader, D3D11HullShader)
CCryDXGLHullShader(NCryOpenGL::SShader* pGLShader, CCryDXGLDevice* pDevice)
: CCryDXGLShader(pGLShader, pDevice)
{
DXGL_INITIALIZE_INTERFACE(D3D11HullShader)
}
};
class CCryDXGLDomainShader
: public CCryDXGLShader
{
public:
DXGL_IMPLEMENT_INTERFACE(CCryDXGLDomainShader, D3D11DomainShader)
CCryDXGLDomainShader(NCryOpenGL::SShader* pGLShader, CCryDXGLDevice* pDevice)
: CCryDXGLShader(pGLShader, pDevice)
{
DXGL_INITIALIZE_INTERFACE(D3D11DomainShader)
}
};
class CCryDXGLGeometryShader
: public CCryDXGLShader
{
public:
DXGL_IMPLEMENT_INTERFACE(CCryDXGLGeometryShader, D3D11GeometryShader)
CCryDXGLGeometryShader(NCryOpenGL::SShader* pGLShader, CCryDXGLDevice* pDevice)
: CCryDXGLShader(pGLShader, pDevice)
{
DXGL_INITIALIZE_INTERFACE(D3D11GeometryShader)
}
};
class CCryDXGLPixelShader
: public CCryDXGLShader
{
public:
DXGL_IMPLEMENT_INTERFACE(CCryDXGLPixelShader, D3D11PixelShader)
CCryDXGLPixelShader(NCryOpenGL::SShader* pGLShader, CCryDXGLDevice* pDevice)
: CCryDXGLShader(pGLShader, pDevice)
{
DXGL_INITIALIZE_INTERFACE(D3D11PixelShader)
}
};
class CCryDXGLComputeShader
: public CCryDXGLShader
{
public:
DXGL_IMPLEMENT_INTERFACE(CCryDXGLComputeShader, D3D11ComputeShader)
CCryDXGLComputeShader(NCryOpenGL::SShader* pGLShader, CCryDXGLDevice* pDevice)
: CCryDXGLShader(pGLShader, pDevice)
{
DXGL_INITIALIZE_INTERFACE(D3D11ComputeShader)
}
};
#endif //__CRYDXGLSHADER__ | 26.632479 | 85 | 0.758344 | jeikabu |
069e66fc88cbf726fc258b498a056d146fcd611a | 370 | cpp | C++ | docs/examples/problems/addition/submissions/js.cpp | bilsen/omogenexec | 331f8e4ac48a190de289b5e1737741bac0d7a09a | [
"MIT"
] | null | null | null | docs/examples/problems/addition/submissions/js.cpp | bilsen/omogenexec | 331f8e4ac48a190de289b5e1737741bac0d7a09a | [
"MIT"
] | null | null | null | docs/examples/problems/addition/submissions/js.cpp | bilsen/omogenexec | 331f8e4ac48a190de289b5e1737741bac0d7a09a | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int add(int a, int b) {
if (a == 0) return b;
int what[1000];
what[0] = add(a - 1, b + 1);
what[1] = add(0, -10);
what[2] = add(0, 10);
return what[0] + what[1] + what[2];
}
int main() {
int a, b;
cin >> a >> b;
if (a + b <= 2000) {
cout << add(a, b) << endl;
} else {
cout << a + b << endl;
}
}
| 16.086957 | 37 | 0.472973 | bilsen |
069e6fe49b5580546b2126a25991a5c1c243a6be | 3,403 | cpp | C++ | ArrayList/ArrayList/ArrayListLib.cpp | UnicornMane/spbu-homework1 | 665c71cfa1e37a5b88fb1d58ad0070842d0b6b2b | [
"Apache-2.0"
] | null | null | null | ArrayList/ArrayList/ArrayListLib.cpp | UnicornMane/spbu-homework1 | 665c71cfa1e37a5b88fb1d58ad0070842d0b6b2b | [
"Apache-2.0"
] | null | null | null | ArrayList/ArrayList/ArrayListLib.cpp | UnicornMane/spbu-homework1 | 665c71cfa1e37a5b88fb1d58ad0070842d0b6b2b | [
"Apache-2.0"
] | null | null | null | #include "ArrayListLib.h"
#include <iostream>
void ArrayList::expand(int count)
{
int* newdata = new int[count + this->capacity];
for (int i = 0; i < this->capacity; ++i)
{
newdata[i] = this->data[i];
}
delete[] this->data;
this->data = newdata;
this->capacity += count;
}
void ArrayList::swap(int posi, int posj)
{
int tmp = this->data[posi];
this->data[posi] = this->data[posj];
this->data[posj] = tmp;
}
int ArrayList::ind(int index)
{
if (index < 0)
{
pushbegin(0);
return 0;
}
if (index >= this->count)
{
pushend(0);
return this->count - 1;
}
return index;
}
ArrayList::ArrayList(int capacity)
{
this->capacity = capacity;
this->count = 0;
this->data = new int[capacity];
}
ArrayList::ArrayList(const ArrayList& list)
{
this->capacity = list.count;
this->count = list.count;
this->data = new int[list.count];
for (int i = 0; i < list.count; ++i)
{
this->data[i] = list.data[i];
}
}
ArrayList::~ArrayList()
{
for (int i = 0; i < this->capacity; ++i)
{
this->data[i] = 0;
}
this->count = 0;
this->capacity = 0;
delete[] this->data;
}
int ArrayList::size()
{
return this->count;
}
void ArrayList::pushend(int element)
{
if (this->count == this->capacity)
{
expand(this->capacity);
}
this->data[this->count] = element;
this->count++;
}
void ArrayList::insert(int element, int position)
{
if (this->count == this->capacity)
{
expand(this->capacity);
}
this->count++;
for (int i = this->count - 1; i > position; --i)
{
this->data[i] = this->data[i - 1];
}
this->data[position] = element;
}
void ArrayList::pushbegin(int element)
{
this->insert(element, 0);
}
int ArrayList::extract(int position)
{
int ans = this->data[position];
this->count--;
for (int i = position; i < this->count; ++i)
{
this->data[i] = this->data[i + 1];
}
this->data[this->count] = 0;
return ans;
}
int ArrayList::extractbegin()
{
return extract(0);
}
int ArrayList::extractend()
{
this->count--;
int tmp = this->data[this->count];
this->data[this->count] = 0;
return tmp;
}
int& ArrayList::operator[](int pos)
{
return data[ind(pos)];
}
ArrayList merge(ArrayList l, ArrayList r)
{
if (l.size() == 0)
{
return r;
}
else if (r.size() == 0)
{
return l;
}
ArrayList ans(l.size() + r.size());
int i = 0;
int j = 0;
while ((i != l.size()) || (j != r.size()))
{
if ((j == r.size()) || ((i != l.size()) && (l[i] <= r[j])))
{
ans.pushend(l[i]);
i++;
}
else
{
ans.pushend(r[j]);
j++;
}
}
return ans;
}
ArrayList quickSort(ArrayList arr)
{
int l = 0;
int r = arr.size();
if (r - l == 1)
{
ArrayList tmp(1);
tmp.pushend(arr[l]);
return tmp;
}
int mid = ((l + r) >> 1);
ArrayList arr_l(mid);
ArrayList arr_r(r - mid);
for (int i = 0; i < mid; ++i)
{
arr_l.pushend(arr[i]);
}
for (int i = mid; i < r; ++i)
{
arr_r.pushend(arr[i]);
}
return merge(quickSort(arr_l), quickSort(arr_r));
}
void ArrayList::sort()
{
ArrayList tmp(quickSort(*this));
for (int i = 0; i < tmp.count; ++i)
{
this->data[i] = tmp.data[i];
}
}
std::ostream& operator<<(std::ostream& stream, ArrayList& list)
{
stream << "[" << list.count << "/" << list.capacity << "] {";
if (list.count == 0)
{
stream << "EMPTY";
}
else
{
for (int i = 0; i < list.count - 1; ++i)
{
stream << list.data[i] << ", ";
}
stream << list.data[list.count - 1];
}
stream << "}";
return stream;
} | 15.610092 | 63 | 0.577432 | UnicornMane |
069e92ce79b2fd81b8500829e6ce9e536bfe2d3c | 4,896 | cpp | C++ | include/delfem2/opengl/old/rigv3.cpp | mmer547/delfem2 | 4f4b28931c96467ac30948e6b3f83150ea530c92 | [
"MIT"
] | 1 | 2020-07-18T17:03:36.000Z | 2020-07-18T17:03:36.000Z | include/delfem2/opengl/old/rigv3.cpp | mmer547/delfem2 | 4f4b28931c96467ac30948e6b3f83150ea530c92 | [
"MIT"
] | null | null | null | include/delfem2/opengl/old/rigv3.cpp | mmer547/delfem2 | 4f4b28931c96467ac30948e6b3f83150ea530c92 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2019 Nobuyuki Umetani
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "delfem2/opengl/old/funcs.h"
#include "delfem2/opengl/old/v3q.h"
#include "delfem2/opengl/old/rigv3.h"
#include "delfem2/rig_geo3.h"
#if defined(_WIN32) // windows
#define NOMINMAX // to remove min,max macro
#include <windows.h>
#endif
#if defined(__APPLE__) && defined(__MACH__) // mac
#define GL_SILENCE_DEPRECATION
#include <OpenGL/gl.h>
#else
#include <GL/gl.h>
#endif
#ifndef M_PI
#define M_PI 3.1415926535
#endif
// -------------------------------------------------------
DFM2_INLINE void delfem2::opengl::Draw_RigBone(
int ibone,
bool is_selected,
[[maybe_unused]] int ielem_selected,
const std::vector<CRigBone>& aBone,
double rad_bone_sphere,
[[maybe_unused]] double rad_rot_hndlr) {
{ // draw point
if (is_selected) { ::glColor3d(0, 1, 1); }
else { ::glColor3d(1, 0, 0); }
const CVec3d pos = aBone[ibone].RootPosition();
delfem2::opengl::DrawSphereAt(32, 32, rad_bone_sphere, pos.x, pos.y, pos.z);
}
/*
if(is_selected){
opengl::DrawHandlerRotation_Mat4(aBone[ibone].affmat3Global, rad_rot_hndlr, ielem_selected);
int ibone_parent = aBone[ibone].ibone_parent;
if( ibone_parent>=0&&ibone_parent<(int)aBone.size() ){
const CVec3d pp(aBone[ibone_parent].Pos());
}
else{
}
}
*/
}
DFM2_INLINE void delfem2::opengl::DrawBone_Line(
const std::vector<CRigBone>& aBone,
int ibone_selected,
int ielem_selected,
double rad_bone_sphere,
double rad_rot_hndlr)
{
glDisable(GL_LIGHTING);
glDisable(GL_TEXTURE_2D);
for(unsigned int iskel=0;iskel<aBone.size();++iskel){
const bool is_selected = (int)iskel==ibone_selected;
Draw_RigBone(iskel,
is_selected,ielem_selected,aBone,
rad_bone_sphere,rad_rot_hndlr);
}
for(unsigned int ibone=0;ibone<aBone.size();++ibone){
const CRigBone& bone = aBone[ibone];
const int ibone_p = aBone[ibone].ibone_parent;
if( ibone_p < 0 || ibone_p >= (int)aBone.size() ){ continue; }
const CRigBone& bone_p = aBone[ibone_p];
bool is_selected_p = (ibone_p == ibone_selected);
if(is_selected_p){ ::glColor3d(1.0,1.0,1.0); } // white if selected
else{ ::glColor3d(0.0,0.0,0.0); } // black if not selected
::glBegin(GL_LINES);
opengl::myGlVertex(bone.RootPosition());
opengl::myGlVertex(bone_p.RootPosition());
::glEnd();
}
}
DFM2_INLINE void delfem2::opengl::DrawBone_Octahedron(
const std::vector<CRigBone>& aBone,
unsigned int ibone_selected,
[[maybe_unused]] unsigned int ielem_selected,
[[maybe_unused]] double rad_bone_sphere,
[[maybe_unused]] double rad_rot_hndlr)
{
namespace dfm2 = delfem2;
glDisable(GL_LIGHTING);
glDisable(GL_TEXTURE_2D);
/*
for(unsigned int iskel=0;iskel<aBone.size();++iskel){
const bool is_selected = (iskel==ibone_selected);
Draw_RigBone(
iskel,
is_selected,ielem_selected,aBone,
rad_bone_sphere,rad_rot_hndlr);
}
*/
for(unsigned int ibone=0;ibone<aBone.size();++ibone){
const CRigBone& bone = aBone[ibone];
const int ibone_p = aBone[ibone].ibone_parent;
if( ibone_p < 0 || ibone_p >= (int)aBone.size() ){ continue; }
const CRigBone& bone_p = aBone[ibone_p];
bool is_selected_p = (ibone_p == (int)ibone_selected);
const CVec3d p0(bone_p.invBindMat[3], bone_p.invBindMat[7], bone_p.invBindMat[11]);
const CVec3d p1(bone.invBindMat[3], bone.invBindMat[7], bone.invBindMat[11]);
::glPushMatrix();
double At[16]; dfm2::Transpose_Mat4(At,bone_p.affmat3Global);
::glMultMatrixd(At);
::glEnable(GL_LIGHTING);
delfem2::opengl::DrawArrowOcta_FaceNrm(
dfm2::CVec3d(0,0,0),
p0-p1,
0.1,
0.2);
//
::glDisable(GL_LIGHTING);
if(is_selected_p){ ::glColor3d(1.0,1.0,1.0); } // white if selected
else{ ::glColor3d(0.0,0.0,0.0); } // black if not selected
delfem2::opengl::DrawArrowOcta_Edge(
dfm2::CVec3d(0,0,0),
p0-p1,
0.1,
0.2);
/*
delfem2::opengl::DrawArrow(
dfm2::CVec3d(0,0,0),
p0-p1);
*/
::glPopMatrix();
}
}
DFM2_INLINE void delfem2::opengl::DrawJoints(
const std::vector<double>& aJntPos,
const std::vector<int>& aIndBoneParent)
{
for(unsigned int ib=0;ib<aJntPos.size()/3;++ib){
const double* p = aJntPos.data()+ib*3;
::glColor3d(0,0,1);
::glDisable(GL_LIGHTING);
::glDisable(GL_DEPTH_TEST);
opengl::DrawSphereAt(8, 8, 0.01, p[0], p[1], p[2]);
int ibp = aIndBoneParent[ib];
if( ibp == -1 ){ continue; }
const double* pp = aJntPos.data()+ibp*3;
::glColor3d(0,0,0);
::glBegin(GL_LINES);
::glVertex3dv(p);
::glVertex3dv(pp);
::glEnd();
}
}
| 30.222222 | 96 | 0.642565 | mmer547 |
069efb2b5b3595ecabae8c74dbc4dd26699bb3b0 | 4,460 | cpp | C++ | src/68. Text Justification/main.cpp | sheepduke/leetcode | 7808b3370e4c3e19b2b0bc2bcee62f659906c3eb | [
"MIT"
] | null | null | null | src/68. Text Justification/main.cpp | sheepduke/leetcode | 7808b3370e4c3e19b2b0bc2bcee62f659906c3eb | [
"MIT"
] | null | null | null | src/68. Text Justification/main.cpp | sheepduke/leetcode | 7808b3370e4c3e19b2b0bc2bcee62f659906c3eb | [
"MIT"
] | null | null | null | /*
Given an array of words and a width maxWidth, format the text such that each
line has exactly maxWidth characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as
you can in each line. Pad extra spaces ' ' when necessary so that each line has
exactly maxWidth characters.
Extra spaces between words should be distributed as evenly as possible. If the
number of spaces on a line do not divide evenly between words, the empty slots
on the left will be assigned more spaces than the slots on the right.
For the last line of text, it should be left justified and no extra space is
inserted between words.
Note:
A word is defined as a character sequence consisting of non-space characters only.
Each word's length is guaranteed to be greater than 0 and not exceed maxWidth.
The input array words contains at least one word.
Example 1:
Input:
words = ["This", "is", "an", "example", "of", "text", "justification."]
maxWidth = 16
Output:
[
"This is an",
"example of text",
"justification. "
]
Example 2:
Input:
words = ["What","must","be","acknowledgment","shall","be"]
maxWidth = 16
Output:
[
"What must be",
"acknowledgment ",
"shall be "
]
Explanation: Note that the last line is "shall be " instead of "shall be",
because the last line must be left-justified instead of fully-justified.
Note that the second line is also left-justified becase it contains only one word.
Example 3:
Input:
words = ["Science","is","what","we","understand","well","enough","to","explain",
"to","a","computer.","Art","is","everything","else","we","do"]
maxWidth = 20
Output:
[
"Science is what we",
"understand well",
"enough to explain to",
"a computer. Art is",
"everything else we",
"do "
]
*/
#include "../util/common.hpp"
class Solution {
public:
vector<string> fullJustify(vector<string>& words, int max_width) {
// Group the words into lines.
auto lines = vector<vector<vector<string>::iterator>>{{}};
auto total_width = 0;
for (auto it = begin(words); it != end(words); it++) {
if (total_width + it->length() > max_width) {
lines.push_back(vector<vector<string>::iterator>{it});
total_width = it->length() + 1;
}
else {
lines.back().push_back(it);
total_width += it->length() + 1;
}
}
// For each line, justify the words.
auto result = vector<string>();
for (auto it = begin(lines); it != end(lines); it++) {
result.push_back(get_justified_string(*it, max_width,
(it == end(lines) - 1 ? true : false)));
}
return result;
}
private:
string get_justified_string(const vector<vector<string>::iterator> &iterators,
int max_width, bool left_justified = false) {
if (iterators.size() == 1) left_justified = true;
stringstream ss;
if (left_justified) {
ss << *iterators.front();
auto width = iterators.front()->length();
for (auto word = next(begin(iterators)); word != end(iterators); word++) {
ss << " " << **word;
width += (*word)->length() + 1;
}
ss << string(max_width - width, ' ');
}
else {
auto total_width = 0;
for (auto it: iterators) {
total_width += it->length();
}
auto base_space_width = (max_width - total_width) / (iterators.size() - 1);
auto extra_sapce_count = (max_width - total_width) % (iterators.size() - 1);
ss << *iterators.front();
for (auto itt = begin(iterators) + 1; itt != end(iterators); itt++) {
auto space_count = base_space_width;
if (extra_sapce_count > 0) {
space_count++;
extra_sapce_count--;
}
ss << string(space_count, ' ');
ss << **itt;
}
}
return ss.str();
}
};
void run(vector<string> &words, int max_width) {
cout << "Input: " << words << endl;
auto result = Solution().fullJustify(words, max_width);
cout << "Result: " << endl;
for (auto line: result) {
cout << "\"" << line << "\"" << endl;
}
}
int main() {
Solution solution;
auto words = vector<string>{"This", "is", "an", "example", "of", "text", "justification."};
run(words, 16);
words = {"What", "must", "be", "acknowledgment", "shall", "be"};
run(words, 16);
return 0;
}
| 30.135135 | 95 | 0.606054 | sheepduke |
06a061758728508aa54e85df8d53f1b10cb29e2e | 8,069 | cpp | C++ | src/tut27/Engine/Engine/graphicsclass.cpp | Scillman/rastertek-dx11-tutorials | 3aee1e19eaf6e4e8e9a44c88a83ac50acdcb05c6 | [
"Unlicense"
] | null | null | null | src/tut27/Engine/Engine/graphicsclass.cpp | Scillman/rastertek-dx11-tutorials | 3aee1e19eaf6e4e8e9a44c88a83ac50acdcb05c6 | [
"Unlicense"
] | null | null | null | src/tut27/Engine/Engine/graphicsclass.cpp | Scillman/rastertek-dx11-tutorials | 3aee1e19eaf6e4e8e9a44c88a83ac50acdcb05c6 | [
"Unlicense"
] | 1 | 2018-06-26T01:29:41.000Z | 2018-06-26T01:29:41.000Z | ////////////////////////////////////////////////////////////////////////////////
// Filename: graphicsclass.cpp
////////////////////////////////////////////////////////////////////////////////
#include "graphicsclass.h"
GraphicsClass::GraphicsClass()
{
m_D3D = 0;
m_Camera = 0;
m_Model = 0;
m_TextureShader = 0;
m_RenderTexture = 0;
m_FloorModel = 0;
m_ReflectionShader = 0;
}
GraphicsClass::GraphicsClass(const GraphicsClass& other)
{
}
GraphicsClass::~GraphicsClass()
{
}
bool GraphicsClass::Initialize(int screenWidth, int screenHeight, HWND hwnd)
{
bool result;
// Create the Direct3D object.
m_D3D = new D3DClass;
if(!m_D3D)
{
return false;
}
// Initialize the Direct3D object.
result = m_D3D->Initialize(screenWidth, screenHeight, VSYNC_ENABLED, hwnd, FULL_SCREEN, SCREEN_DEPTH, SCREEN_NEAR);
if(!result)
{
MessageBox(hwnd, L"Could not initialize Direct3D.", L"Error", MB_OK);
return false;
}
// Create the camera object.
m_Camera = new CameraClass;
if(!m_Camera)
{
return false;
}
// Create the model object.
m_Model = new ModelClass;
if(!m_Model)
{
return false;
}
// Initialize the model object.
result = m_Model->Initialize(m_D3D->GetDevice(), L"../Engine/data/seafloor.dds", "../Engine/data/cube.txt");
if(!result)
{
MessageBox(hwnd, L"Could not initialize the model object.", L"Error", MB_OK);
return false;
}
// Create the texture shader object.
m_TextureShader = new TextureShaderClass;
if(!m_TextureShader)
{
return false;
}
// Initialize the texture shader object.
result = m_TextureShader->Initialize(m_D3D->GetDevice(), hwnd);
if(!result)
{
MessageBox(hwnd, L"Could not initialize the texture shader object.", L"Error", MB_OK);
return false;
}
// Create the render to texture object.
m_RenderTexture = new RenderTextureClass;
if(!m_RenderTexture)
{
return false;
}
// Initialize the render to texture object.
result = m_RenderTexture->Initialize(m_D3D->GetDevice(), screenWidth, screenHeight);
if(!result)
{
return false;
}
// Create the floor model object.
m_FloorModel = new ModelClass;
if(!m_FloorModel)
{
return false;
}
// Initialize the floor model object.
result = m_FloorModel->Initialize(m_D3D->GetDevice(), L"../Engine/data/blue01.dds", "../Engine/data/floor.txt");
if(!result)
{
MessageBox(hwnd, L"Could not initialize the floor model object.", L"Error", MB_OK);
return false;
}
// Create the reflection shader object.
m_ReflectionShader = new ReflectionShaderClass;
if(!m_ReflectionShader)
{
return false;
}
// Initialize the reflection shader object.
result = m_ReflectionShader->Initialize(m_D3D->GetDevice(), hwnd);
if(!result)
{
MessageBox(hwnd, L"Could not initialize the reflection shader object.", L"Error", MB_OK);
return false;
}
return true;
}
void GraphicsClass::Shutdown()
{
// Release the reflection shader object.
if(m_ReflectionShader)
{
m_ReflectionShader->Shutdown();
delete m_ReflectionShader;
m_ReflectionShader = 0;
}
// Release the floor model object.
if(m_FloorModel)
{
m_FloorModel->Shutdown();
delete m_FloorModel;
m_FloorModel = 0;
}
// Release the render to texture object.
if(m_RenderTexture)
{
m_RenderTexture->Shutdown();
delete m_RenderTexture;
m_RenderTexture = 0;
}
// Release the texture shader object.
if(m_TextureShader)
{
m_TextureShader->Shutdown();
delete m_TextureShader;
m_TextureShader = 0;
}
// Release the model object.
if(m_Model)
{
m_Model->Shutdown();
delete m_Model;
m_Model = 0;
}
// Release the camera object.
if(m_Camera)
{
delete m_Camera;
m_Camera = 0;
}
// Release the D3D object.
if(m_D3D)
{
m_D3D->Shutdown();
delete m_D3D;
m_D3D = 0;
}
return;
}
bool GraphicsClass::Frame()
{
// Set the position of the camera.
m_Camera->SetPosition(0.0f, 0.0f, -10.0f);
return true;
}
bool GraphicsClass::Render()
{
bool result;
// Render the entire scene as a reflection to the texture first.
result = RenderToTexture();
if(!result)
{
return false;
}
// Render the scene as normal to the back buffer.
result = RenderScene();
if(!result)
{
return false;
}
return true;
}
bool GraphicsClass::RenderToTexture()
{
D3DXMATRIX worldMatrix, reflectionViewMatrix, projectionMatrix;
static float rotation = 0.0f;
// Set the render target to be the render to texture.
m_RenderTexture->SetRenderTarget(m_D3D->GetDeviceContext(), m_D3D->GetDepthStencilView());
// Clear the render to texture.
m_RenderTexture->ClearRenderTarget(m_D3D->GetDeviceContext(), m_D3D->GetDepthStencilView(), 0.0f, 0.0f, 0.0f, 1.0f);
// Use the camera to calculate the reflection matrix.
m_Camera->RenderReflection(-1.5f);
// Get the camera reflection view matrix instead of the normal view matrix.
reflectionViewMatrix = m_Camera->GetReflectionViewMatrix();
// Get the world and projection matrices.
m_D3D->GetWorldMatrix(worldMatrix);
m_D3D->GetProjectionMatrix(projectionMatrix);
// Update the rotation variable each frame.
rotation += (float)D3DX_PI * 0.005f;
if(rotation > 360.0f)
{
rotation -= 360.0f;
}
D3DXMatrixRotationY(&worldMatrix, rotation);
// Put the model vertex and index buffers on the graphics pipeline to prepare them for drawing.
m_Model->Render(m_D3D->GetDeviceContext());
// Render the model using the texture shader and the reflection view matrix.
m_TextureShader->Render(m_D3D->GetDeviceContext(), m_Model->GetIndexCount(), worldMatrix, reflectionViewMatrix,
projectionMatrix, m_Model->GetTexture());
// Reset the render target back to the original back buffer and not the render to texture anymore.
m_D3D->SetBackBufferRenderTarget();
return true;
}
bool GraphicsClass::RenderScene()
{
D3DXMATRIX worldMatrix, viewMatrix, projectionMatrix, reflectionMatrix;
bool result;
static float rotation = 0.0f;
// Clear the buffers to begin the scene.
m_D3D->BeginScene(0.0f, 0.0f, 0.0f, 1.0f);
// Generate the view matrix based on the camera's position.
m_Camera->Render();
// Get the world, view, and projection matrices from the camera and d3d objects.
m_D3D->GetWorldMatrix(worldMatrix);
m_Camera->GetViewMatrix(viewMatrix);
m_D3D->GetProjectionMatrix(projectionMatrix);
// Update the rotation variable each frame.
rotation += (float)D3DX_PI * 0.005f;
if(rotation > 360.0f)
{
rotation -= 360.0f;
}
// Multiply the world matrix by the rotation.
D3DXMatrixRotationY(&worldMatrix, rotation);
// Put the model vertex and index buffers on the graphics pipeline to prepare them for drawing.
m_Model->Render(m_D3D->GetDeviceContext());
// Render the model with the texture shader.
result = m_TextureShader->Render(m_D3D->GetDeviceContext(), m_Model->GetIndexCount(), worldMatrix, viewMatrix,
projectionMatrix, m_Model->GetTexture());
if(!result)
{
return false;
}
// Get the world matrix again and translate down for the floor model to render underneath the cube.
m_D3D->GetWorldMatrix(worldMatrix);
D3DXMatrixTranslation(&worldMatrix, 0.0f, -1.5f, 0.0f);
// Get the camera reflection view matrix.
reflectionMatrix = m_Camera->GetReflectionViewMatrix();
// Put the floor model vertex and index buffers on the graphics pipeline to prepare them for drawing.
m_FloorModel->Render(m_D3D->GetDeviceContext());
// Render the floor model using the reflection shader, reflection texture, and reflection view matrix.
result = m_ReflectionShader->Render(m_D3D->GetDeviceContext(), m_FloorModel->GetIndexCount(), worldMatrix, viewMatrix,
projectionMatrix, m_FloorModel->GetTexture(), m_RenderTexture->GetShaderResourceView(),
reflectionMatrix);
// Present the rendered scene to the screen.
m_D3D->EndScene();
return true;
} | 24.451515 | 120 | 0.681125 | Scillman |
a628cd64c745f4515c57ae13c584c08c20132222 | 832 | cpp | C++ | extern/shiny/Main/MaterialInstancePass.cpp | Bodillium/openmw | 5fdd264d0704e33b44b1ccf17ab4fb721f362e34 | [
"Unlicense"
] | 4 | 2020-07-04T06:05:05.000Z | 2022-02-14T22:53:27.000Z | extern/shiny/Main/MaterialInstancePass.cpp | Bodillium/openmw | 5fdd264d0704e33b44b1ccf17ab4fb721f362e34 | [
"Unlicense"
] | null | null | null | extern/shiny/Main/MaterialInstancePass.cpp | Bodillium/openmw | 5fdd264d0704e33b44b1ccf17ab4fb721f362e34 | [
"Unlicense"
] | 1 | 2018-10-20T08:17:41.000Z | 2018-10-20T08:17:41.000Z | #include "MaterialInstancePass.hpp"
#include <fstream>
namespace sh
{
MaterialInstanceTextureUnit* MaterialInstancePass::createTextureUnit (const std::string& name)
{
mTexUnits.push_back(MaterialInstanceTextureUnit(name));
return &mTexUnits.back();
}
void MaterialInstancePass::save(std::ofstream &stream)
{
if (mShaderProperties.listProperties().size())
{
stream << "\t\t" << "shader_properties" << '\n';
stream << "\t\t{\n";
mShaderProperties.save(stream, "\t\t\t");
stream << "\t\t}\n";
}
PropertySetGet::save(stream, "\t\t");
for (std::vector <MaterialInstanceTextureUnit>::iterator it = mTexUnits.begin();
it != mTexUnits.end(); ++it)
{
stream << "\t\ttexture_unit " << it->getName() << '\n';
stream << "\t\t{\n";
it->save(stream, "\t\t\t");
stream << "\t\t}\n";
}
}
}
| 23.111111 | 95 | 0.635817 | Bodillium |
a62b718533981567bed358140f97ff07c7a0c58e | 2,634 | cpp | C++ | src/ScoreEvaluation/VCValueEvaluator.cpp | AhmedSalemElhady/Scrabble-Game.ai | b75e19dac5f3096a82b4cbe54e9c66501b9a051b | [
"MIT"
] | 8 | 2019-02-25T17:32:09.000Z | 2022-02-25T04:00:40.000Z | src/ScoreEvaluation/VCValueEvaluator.cpp | AhmedSalemElhady/Scrabble-Game.ai | b75e19dac5f3096a82b4cbe54e9c66501b9a051b | [
"MIT"
] | 2 | 2019-04-20T15:49:47.000Z | 2019-04-28T16:48:55.000Z | src/ScoreEvaluation/VCValueEvaluator.cpp | AhmedSalemElhady/Scrabble-Game.ai | b75e19dac5f3096a82b4cbe54e9c66501b9a051b | [
"MIT"
] | 9 | 2019-02-19T18:00:11.000Z | 2021-01-26T16:36:26.000Z | #include "VCValueEvaluator.hpp"
VCValueEvaluator::VCValueEvaluator(int bagSize, bool isEmptyBoard) : RackLeaveEvaluator(bagSize, isEmptyBoard)
{
}
VCValueEvaluator::VCValueEvaluator(LoadHeuristics *heuristicsValues, std::vector<char> *opponentRack, int bagSize, bool isEmptyBoard) : RackLeaveEvaluator(heuristicsValues, bagSize, isEmptyBoard)
{
this->heuristicsValues = heuristicsValues;
this->opponentRack = opponentRack;
}
double VCValueEvaluator::equity(std::vector<char> *Rack, Move *move)
{
if (this->isEmptyBoard)
{
double adjustment = 0; //if (move.action == Move::Place) //
//{
if (move->word == "pawed")
{
std::cout << "HERE:" << std::endl;
}
int start = move->startPosition.COL;
if (move->startPosition.ROW < start)
{
start = move->startPosition.ROW;
}
std::string wordString = Options::regularWordString(move);
std::vector<char> *wordTiles = Options::moveTiles(move);
int length = wordTiles->size();
int consbits = 0;
for (signed int index = wordTiles->size() - 1; index >= 0; --index)
{
consbits <<= 1;
if (Options::isVowel(&(*wordTiles)[index]))
{
consbits |= 1;
}
}
adjustment = heuristicsValues->vcPlace(start, length, consbits);
// else
// {
// adjustment = 3.5;
// }
move->testHScore = RackLeaveEvaluator::equity(Rack, move);
return move->testHScore + adjustment;
}
else if (this->bagSize > 0)
{
int leftInBagPlusSeven = bagSize - move->moveUsedTiles + 7; // ! BAG BEFORE PLAY
double heuristicArray[13] =
{
0.0, -8.0, 0.0, -0.5, -2.0, -3.5, -2.0,
2.0, 10.0, 7.0, 4.0, -1.0, -2.0};
double timingHeuristic = 0.0;
if (leftInBagPlusSeven < 13)
{
timingHeuristic = heuristicArray[leftInBagPlusSeven];
}
return RackLeaveEvaluator::equity(Rack, move) + timingHeuristic;
}
else
{
return endgameResult(Rack, move); // + move->moveScore;
}
}
double VCValueEvaluator::endgameResult(std::vector<char> *Rack, Move *move)
{
std::vector<char> *remainingRack = Options::unusedRackTiles(Rack, move);
if (remainingRack->empty())
{
double deadwood = 0;
deadwood += Options::rackScore(opponentRack);
// deadwood = move->moveScore;
return deadwood * 2;
}
return -8.00 - 2.61 * Options::rackScore(remainingRack);
} | 30.988235 | 195 | 0.572893 | AhmedSalemElhady |
a62c78e2650b294cdab375d5bf97bbcedaa27e1a | 5,818 | cpp | C++ | Processor/Processor.cpp | Inpher/XorPublic | 63f0bc679b618230bb786f0b7dea09bf8bdddd7a | [
"BSD-4-Clause-UC"
] | 2 | 2021-04-24T11:36:29.000Z | 2021-04-24T11:43:15.000Z | Processor/Processor.cpp | Inpher/Inpher-SPDZ | 63f0bc679b618230bb786f0b7dea09bf8bdddd7a | [
"BSD-4-Clause-UC"
] | 2 | 2017-03-21T20:05:23.000Z | 2017-03-27T17:36:55.000Z | Processor/Processor.cpp | Inpher/Inpher-SPDZ | 63f0bc679b618230bb786f0b7dea09bf8bdddd7a | [
"BSD-4-Clause-UC"
] | 1 | 2018-10-01T11:48:30.000Z | 2018-10-01T11:48:30.000Z | // (C) 2016 University of Bristol. See License.txt
#include "Processor/Processor.h"
#include "Auth/MAC_Check.h"
#include "Auth/fake-stuff.h"
Processor::Processor(int thread_num,Data_Files& DataF,Player& P,
MAC_Check<gf2n>& MC2,MAC_Check<gfp>& MCp,Machine& machine,
int num_regs2,int num_regsp,int num_regi)
: thread_num(thread_num),socket_is_open(false),DataF(DataF),P(P),MC2(MC2),MCp(MCp),machine(machine),
input2(*this,MC2),inputp(*this,MCp),privateOutput2(*this),privateOutputp(*this),sent(0),rounds(0)
{
reset(num_regs2,num_regsp,num_regi,0);
public_input.open(get_filename("Programs/Public-Input/",false).c_str());
private_input.open(get_filename("Player-Data/Private-Input-",true).c_str());
public_output.open(get_filename("Player-Data/Public-Output-",true).c_str(), ios_base::out);
private_output.open(get_filename("Player-Data/Private-Output-",true).c_str(), ios_base::out);
}
Processor::~Processor()
{
cerr << "Sent " << sent << " elements in " << rounds << " rounds" << endl;
}
string Processor::get_filename(const char* prefix, bool use_number)
{
stringstream filename;
filename << prefix;
if (!use_number)
filename << machine.progname;
if (use_number)
filename << P.my_num();
if (thread_num > 0)
filename << "-" << thread_num;
cerr << "Opening file " << filename.str() << endl;
return filename.str();
}
void Processor::reset(int num_regs2,int num_regsp,int num_regi,int arg)
{
reg_max2 = num_regs2;
reg_maxp = num_regsp;
reg_maxi = num_regi;
C2.resize(reg_max2); Cp.resize(reg_maxp);
S2.resize(reg_max2); Sp.resize(reg_maxp);
Ci.resize(reg_maxi);
this->arg = arg;
close_socket();
#ifdef DEBUG
rw2.resize(2*reg_max2);
for (int i=0; i<2*reg_max2; i++) { rw2[i]=0; }
rwp.resize(2*reg_maxp);
for (int i=0; i<2*reg_maxp; i++) { rwp[i]=0; }
rwi.resize(2*reg_maxi);
for (int i=0; i<2*reg_maxi; i++) { rwi[i]=0; }
#endif
}
#include "Networking/sockets.h"
// Set up a server socket for some client
void Processor::open_socket(int portnum_base)
{
if (!socket_is_open)
{
socket_is_open = true;
sockaddr_in dest;
set_up_server_socket(dest, final_socket_fd, socket_fd, portnum_base + P.my_num());
}
}
void Processor::close_socket()
{
if (socket_is_open)
{
socket_is_open = false;
close_server_socket(final_socket_fd, socket_fd);
}
}
// Receive 32-bit int
void Processor::read_socket(int& x)
{
octet bytes[4];
receive(final_socket_fd, bytes, 4);
x = BYTES_TO_INT(bytes);
}
// Send 32-bit int
void Processor::write_socket(int x)
{
octet bytes[4];
INT_TO_BYTES(bytes, x);
send(final_socket_fd, bytes, 4);
}
// Receive field element
template <class T>
void Processor::read_socket(T& x)
{
socket_stream.reset_write_head();
socket_stream.Receive(final_socket_fd);
x.unpack(socket_stream);
}
// Send field element
template <class T>
void Processor::write_socket(const T& x)
{
socket_stream.reset_write_head();
x.pack(socket_stream);
socket_stream.Send(final_socket_fd);
}
template <class T>
void Processor::POpen_Start(const vector<int>& reg,const Player& P,MAC_Check<T>& MC,int size)
{
int sz=reg.size();
vector< Share<T> >& Sh_PO = get_Sh_PO<T>();
vector<T>& PO = get_PO<T>();
Sh_PO.clear();
Sh_PO.reserve(sz*size);
if (size>1)
{
for (typename vector<int>::const_iterator reg_it=reg.begin();
reg_it!=reg.end(); reg_it++)
{
typename vector<Share<T> >::iterator begin=get_S<T>().begin()+*reg_it;
Sh_PO.insert(Sh_PO.end(),begin,begin+size);
}
}
else
{
for (int i=0; i<sz; i++)
{ Sh_PO.push_back(get_S_ref<T>(reg[i])); }
}
PO.resize(sz*size);
MC.POpen_Begin(PO,Sh_PO,P);
}
template <class T>
void Processor::POpen_Stop(const vector<int>& reg,const Player& P,MAC_Check<T>& MC,int size)
{
vector< Share<T> >& Sh_PO = get_Sh_PO<T>();
vector<T>& PO = get_PO<T>();
vector<T>& C = get_C<T>();
int sz=reg.size();
PO.resize(sz*size);
MC.POpen_End(PO,Sh_PO,P);
if (size>1)
{
typename vector<T>::iterator PO_it=PO.begin();
for (typename vector<int>::const_iterator reg_it=reg.begin();
reg_it!=reg.end(); reg_it++)
{
for (typename vector<T>::iterator C_it=C.begin()+*reg_it;
C_it!=C.begin()+*reg_it+size; C_it++)
{
*C_it=*PO_it;
PO_it++;
}
}
}
else
{
for (unsigned int i=0; i<reg.size(); i++)
{ get_C_ref<T>(reg[i]) = PO[i]; }
}
sent += reg.size() * size;
rounds++;
}
ostream& operator<<(ostream& s,const Processor& P)
{
s << "Processor State" << endl;
s << "Char 2 Registers" << endl;
s << "Val\tClearReg\tSharedReg" << endl;
for (int i=0; i<P.reg_max2; i++)
{ s << i << "\t";
P.read_C2(i).output(s,true);
s << "\t";
P.read_S2(i).output(s,true);
s << endl;
}
s << "Char p Registers" << endl;
s << "Val\tClearReg\tSharedReg" << endl;
for (int i=0; i<P.reg_maxp; i++)
{ s << i << "\t";
P.read_Cp(i).output(s,true);
s << "\t";
P.read_Sp(i).output(s,true);
s << endl;
}
return s;
}
template void Processor::POpen_Start(const vector<int>& reg,const Player& P,MAC_Check<gf2n>& MC,int size);
template void Processor::POpen_Start(const vector<int>& reg,const Player& P,MAC_Check<gfp>& MC,int size);
template void Processor::POpen_Stop(const vector<int>& reg,const Player& P,MAC_Check<gf2n>& MC,int size);
template void Processor::POpen_Stop(const vector<int>& reg,const Player& P,MAC_Check<gfp>& MC,int size);
template void Processor::read_socket(gfp& x);
template void Processor::read_socket(gf2n& x);
template void Processor::write_socket(const gfp& x);
template void Processor::write_socket(const gf2n& x);
| 26.089686 | 106 | 0.642661 | Inpher |
a62f25a7d04eb7d3ebfb3348eb9d6b9d81cb56f1 | 16,297 | cpp | C++ | gpe/Array.cpp | erli1/GPE-Solver | 636fc84bc50144471596ff99cc99edb92a6ef5c1 | [
"MIT"
] | 8 | 2015-08-23T09:12:00.000Z | 2021-09-10T21:41:27.000Z | gpe/Array.cpp | erli1/GPE-Solver | 636fc84bc50144471596ff99cc99edb92a6ef5c1 | [
"MIT"
] | 1 | 2018-02-23T19:33:26.000Z | 2018-02-24T09:43:18.000Z | gpe/Array.cpp | erli1/GPE-Solver | 636fc84bc50144471596ff99cc99edb92a6ef5c1 | [
"MIT"
] | 5 | 2015-02-18T17:31:41.000Z | 2021-11-09T22:18:45.000Z | #include "Array.h"
#include "omp.h"
#include <cmath>
#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
bool Array::_fftwInitialized = false;
bool Array::_fftwWisdomLoaded = false;
bool Array::_fftwWisdomExported = false;
Array::Array(const SimulationParameters & sp) :
Field(sp) {
_initialized = false;
_space = SPACE_UNDEFINED;
_fourierPlan = 0;
_fourierPlanInverse = 0;
_values = new complex_t[_sp.size()];
}
void Array::initialize() {
int i, j, k;
#pragma omp parallel for private(i, j, k)
for (i = 0; i < _sp.sizeX(); i++) {
for (j = 0; j < _sp.sizeY(); j++) {
for (k = 0; k < _sp.sizeZ(); k++) {
(*this)(i, j, k) = initialValue(i, j, k);
}
}
}
_initialized = true;
}
complex_t Array::operator()(int i, int j, int k, double t) const {
#ifdef DEBUG_GPE
assureInitialized();
if (i < 0 || j < 0 || k < 0 || i > _sp.sizeX() || j > _sp.sizeY() || k > _sp.sizeZ()) {
cerr << "Error: out-of-bound access to array" << endl;
exit(1);
}
#endif
return _values[(i * _sp.sizeY() + j) * _sp.sizeZ() + k];
}
complex_t & Array::operator()(int i, int j, int k, double t) {
#ifdef DEBUG_GPE
if (i < 0 || j < 0 || k < 0 || i > _sp.sizeX() || j > _sp.sizeY() || k > _sp.sizeZ()) {
cerr << "Error: out-of-bound access to array" << endl;
exit(1);
}
#endif
return _values[(i * _sp.sizeY() + j) * _sp.sizeZ() + k];
}
Array & Array::operator=(const Array & a) {
#ifdef DEBUG_GPE
a.assureInitialized();
#endif
if (this != &a) {
int i;
#pragma omp parallel for private(i)
for (i = 0; i < _sp.size(); i++) {
_values[i] = a._values[i];
}
}
_initialized = true;
_space = a._space;
return *this;
}
Array & Array::operator*=(const Array & a) {
#ifdef DEBUG_GPE
assureInitialized();
#endif
int i;
#pragma omp parallel for private(i)
for (i = 0; i < _sp.size(); i++) {
_values[i] *= a._values[i];
}
return *this;
}
Array & Array::operator*=(complex_t factor) {
#ifdef DEBUG_GPE
assureInitialized();
#endif
int i;
#pragma omp parallel for private(i)
for (i = 0; i < _sp.size(); i++) {
_values[i] *= factor;
}
return *this;
}
double Array::integral(const Field & f) const {
// Calculates the following integral (a = this Array object):
// int dr^3 (conj(a) * f * a)
//
// warning: the real part of conj(a) * f * a is taken
// to make the whole integral real.
#ifdef DEBUG_GPE
assureInitialized();
#endif
double sum = 0.0;
int i, j, k;
#pragma omp parallel for private (i, j, k) reduction(+:sum)
for (i = 0; i < _sp.sizeX(); i++) {
for (j = 0; j < _sp.sizeY(); j++) {
for (k = 0; k < _sp.sizeZ(); k++) {
sum += real(conj((*this)(i, j, k)) * f(i, j, k) * (*this)(i, j, k));
}
}
}
// The multiplication by dx*dy*dz is also correct
// in fourier space (due to some scaling during the FFT)!
return sum * (_sp.dX() * _sp.dY() * _sp.dZ());
}
#ifndef __INTEL_COMPILER
double Array::integral(function<complex_t (double, double, double)> lambdaExpression) const {
double sum = 0.0;
#ifdef DEBUG_GPE
assureInitialized();
#endif
int i, j, k;
#pragma omp parallel for private (i, j, k) reduction(+:sum)
for (i = 0; i < _sp.sizeX(); i++) {
for (j = 0; j < _sp.sizeY(); j++) {
for (k = 0; k < _sp.sizeZ(); k++) {
sum += real(conj((*this)(i, j, k)) * lambdaExpression(_sp.x(i), _sp.y(j), _sp.z(k)) * (*this)(i, j, k));
}
}
}
return sum * (_sp.dX() * _sp.dY() * _sp.dZ());
}
#endif
void Array::initFourierPlans() {
int mx = _sp.sizeX();
int my = _sp.sizeY();
int mz = _sp.sizeZ();
if (!_fftwInitialized) {
if (!fftw_init_threads()) {
cerr << "Error during FFTW thread initialization." << endl;
exit(1);
}
#ifdef _OPENMP
int nthreads;
#pragma omp parallel
{
nthreads = omp_get_num_threads();
}
fftw_plan_with_nthreads(nthreads);
#ifdef DEBUG_GPE
cerr << "Initializing FFTW for " << nthreads << " thread(s)" << endl;
#endif
#endif
_fftwInitialized = true;
}
// Read FFTW wisdom from file
if (!_fftwWisdomLoaded) {
#ifdef DEBUG_GPE
cerr << "Importing FFTW wisdom" << endl;
#endif
FILE * wisdomFile = fopen("fftw.wisdom", "r");
if (wisdomFile) {
fftw_import_wisdom_from_file(wisdomFile);
fclose(wisdomFile);
} else {
#ifdef DEBUG_GPE
cerr << "No wisdom file available" << endl;
#endif
}
_fftwWisdomLoaded = true;
}
#ifdef DEBUG_GPE
cerr << "Creating FFTW plans" << endl;
#endif
// -1 = Fourier Transform, +1 = Inverse Fourier Transform
_fourierPlan = fftw_plan_dft_3d(mx, my, mz, reinterpret_cast<fftw_complex*>(_values), reinterpret_cast<fftw_complex*>(_values), -1, FFTW_PATIENT);
_fourierPlanInverse = fftw_plan_dft_3d(mx, my, mz, reinterpret_cast<fftw_complex*>(_values), reinterpret_cast<fftw_complex*>(_values), +1, FFTW_PATIENT);
}
void Array::fourierTransform() {
#ifdef DEBUG_GPE
assureInitialized();
if (_space == SPACE_MOMENTUM) {
cerr << "Array is already in momentum space" << endl;
}
#endif
if (!_fourierPlan) {
cerr << "Fourier plan has not been initialized!" << endl;
exit(1);
}
fftw_execute(_fourierPlan);
_space = SPACE_MOMENTUM;
}
void Array::fourierTransformInverse() {
#ifdef DEBUG_GPE
assureInitialized();
if (_space == SPACE_POSITION) {
cerr << "Array is already in position space" << endl;
}
#endif
if (!_fourierPlanInverse) {
cerr << "Fourier plan has not been initialized!" << endl;
exit(1);
}
fftw_execute(_fourierPlanInverse);
_space = SPACE_POSITION;
}
double Array::dispersion(int direction, bool realSpace) {
// Calculates the following integral (a = this Array object):
// int dr^3 (conj(a) * * a)
#ifdef DEBUG_GPE
assureInitialized();
#endif
if (!realSpace) {
fftw_execute(_fourierPlan);
}
double sum = 0.0;
int i, j, k;
#pragma omp parallel for private (i, j, k) reduction(+:sum)
for (i = 0; i < _sp.sizeX(); i++) {
for (j = 0; j < _sp.sizeY(); j++) {
for (k = 0; k < _sp.sizeZ(); k++) {
if (direction == 0) {
sum += real(conj((*this)(i, j, k)) * pow(_sp.coord(direction, i, realSpace) , 2.0) * (*this)(i, j, k));
} else if (direction == 1) {
sum += real(conj((*this)(i, j, k)) * pow(_sp.coord(direction, j, realSpace) , 2.0) * (*this)(i, j, k));
} else {
sum += real(conj((*this)(i, j, k)) * pow(_sp.coord(direction, k, realSpace) , 2.0) * (*this)(i, j, k));
}
}
}
}
if (!realSpace) {
#pragma omp parallel for private (i, j, k) reduction(+:sum)
for (i = 0; i < _sp.sizeX(); ++i) {
for (j = 0; j < _sp.sizeY(); ++j) {
for (k = 0; k < _sp.sizeZ(); ++k) {
(*this)(i, j, k) *= 1.0 / (_sp.sizeX() * _sp.sizeY() * _sp.sizeZ());
}
}
}
fftw_execute(_fourierPlanInverse);
}
// The multiplication by dx*dy*dz is also correct
// in fourier space (due to some scaling during the FFT)!
return real( sqrt( 2.0 * sum * (_sp.dX() * _sp.dY() * _sp.dZ()) ) );
}
double Array::averageXK(int direction) const {
// Calculates the following integral (a = this Array object):
// int dr^3 (conj(a) * * a)
#ifdef DEBUG_GPE
assureInitialized();
#endif
double sum = 0.0;
bool realSpace = 1;
int i, j, k;
// #pragma omp parallel for private (i, j, k) reduction(+:sum)
for (i = 0; i < _sp.sizeX()-1; i++) {
for (j = 0; j < _sp.sizeY()-1; j++) {
for (k = 0; k < _sp.sizeZ()-1; k++) {
if (direction == 0) {
sum += imag( (*this)(i, j, k) * _sp.coord(direction, i, realSpace) * (*this)(i+1, j, k) / ( _sp.dX() ) );
} else if (direction == 1) {
sum += imag( (*this)(i, j, k) * _sp.coord(direction, j, realSpace) * (*this)(i, j+1, k) / ( _sp.dY() ) );
} else {
sum += imag( (*this)(i, j, k) * _sp.coord(direction, k, realSpace) * (*this)(i, j, k+1) / ( _sp.dZ() ) );
}
}
}
}
return sum;
}
void Array::cut1D(string fileName, int direction) const {
#ifdef DEBUG_GPE
assureInitialized();
#endif
bool realSpace = (_space == SPACE_POSITION);
int k, kmax, sx, sy, sz, c1, c2, index;
ofstream fout;
fout.open(fileName.c_str());
kmax = _sp.size(direction);
sx = _sp.size(0);
sy = _sp.size(1);
sz = _sp.size(2);
if (direction == 0) {
c1 = (sy * sz + sz) * realSpace / 2;
c2 = sy * sz;
} else if (direction == 1) {
c1 = (sy * sz * sx + sz) * realSpace / 2;
c2 = sz;
} else {
c1 = (sy * sz * sx + sz * sy) * realSpace / 2;
c2 = 1;
}
for (k = 0; k < kmax; ++k) {
index = c1 + c2 * k;
fout << _sp.coord(direction, k, realSpace) << " " << real(_values[index]) << " " << imag(_values[index]) << "\n";
}
fout.close();
}
void Array::projectMatlab2D(string fileName) const {
#ifdef DEBUG_GPE
assureInitialized();
#endif
int sx, sy, sz;
int i, j, k;
double sum;
ofstream fout;
fout.open(fileName.c_str());
sx = _sp.size(0);
sy = _sp.size(1);
sz = _sp.size(2);
fout << "x = [";
for (i = 0; i < sx; i++) {
fout << _sp.x(i) << " ";
}
fout << "];";
fout << "z = [";
for (k = 0; k < sz; k++) {
fout << _sp.z(k) << " ";
}
fout << "];";
fout << "density = [";
for (i = 0; i < sx; ++i) {
for (k = 0; k < sz; ++k) {
sum = 0.0;
for (j = 0; j < sy/2; ++j) {
sum += abs( (*this)(i, j, k) );
}
fout << sum << " ";
}
fout << ";" << endl;
}
fout << "];" << endl;
fout.close();
}
void Array::projectFourierMatlab2D(string fileName) {
#ifdef DEBUG_GPE
assureInitialized();
#endif
fftw_execute(_fourierPlan);
int sx, sy, sz;
int i, j, k;
double sum;
ofstream fout;
fout.open(fileName.c_str());
sx = _sp.size(0);
sy = _sp.size(1);
sz = _sp.size(2);
for (j = 0; j < sy/2; ++j) {
for (k = 0; k < sz/2; ++k) {
sum = 0.0;
for (i = 0; i < sx; ++i) {
sum += abs( (*this)(i, j, k) );
}
fout << sum << " ";
}
fout << endl;
}
for (i = 0; i < sx; ++i) {
for (j = 0; j < sy; ++j) {
for (k = 0; k < sz; ++k) {
(*this)(i, j, k) *= 1.0 / (sx * sy * sz);
}
}
}
fftw_execute(_fourierPlanInverse);
fout.close();
}
void Array::cut2D(string fileName, int direction) const {
#ifdef DEBUG_GPE
assureInitialized();
#endif
bool realSpace = (_space == SPACE_POSITION);
int sx, sy, sz, c1, c2, c3, index;
int dir1, dir2;
int imax, jmax;
int i, j, i1, j1;
ofstream fout;
fout.open(fileName.c_str());
sx = _sp.size(0);
sy = _sp.size(1);
sz = _sp.size(2);
if (direction == 0) {
dir1 = 1;
dir2 = 2;
c1 = (sy * sz * sx) * realSpace / 2;
c2 = 1;
c3 = sz;
imax = sy;
jmax = sz;
} else if (direction == 1) {
dir1 = 0;
dir2 = 2;
c1 = (sy * sz) * realSpace / 2;
c2 = 1;
c3 = sy * sz;
imax = sx;
jmax = sz;
} else {
dir1 = 0;
dir2 = 1;
c1 = sz * realSpace / 2;
c2 = sz;
c3 = sy * sz;
imax = sx;
jmax = sy;
}
for (i1 = 0; i1 < imax - 1; ++i1) {
for (j1 = 0; j1 < jmax - 1; ++j1) {
i = (i1 + imax / 2 * (realSpace + 1)) % imax;
j = (j1 + jmax / 2 * (realSpace + 1)) % jmax;
index = c1 + c2 * j + c3 * i;
fout << _sp.coord(dir1, i, realSpace) << " ";
fout << _sp.coord(dir2, j, realSpace) << " ";
fout << abs(_values[index]) << "\n";
fout << _sp.coord(dir1, i, realSpace) << " ";
fout << _sp.coord(dir2, j + 1, realSpace) << " ";
fout << abs(_values[index]) << "\n";
}
fout << "\n";
for (j1 = 0; j1 < jmax - 1; ++j1) {
i = (i1 + imax / 2 * (realSpace + 1)) % imax;
j = (j1 + jmax / 2 * (realSpace + 1)) % jmax;
index = c1 + c2 * j + c3 * i;
fout << _sp.coord(dir1, i + 1, realSpace) << " ";
fout << _sp.coord(dir2, j, realSpace) << " ";
fout << abs(_values[index]) << "\n";
fout << _sp.coord(dir1, i + 1, realSpace) << " ";
fout << _sp.coord(dir2, j + 1, realSpace) << " ";
fout << abs(_values[index]) << "\n";
}
fout << "\n";
}
fout.close();
}
void Array::project1D(string fileName, int direction) const {
#ifdef DEBUG_GPE
assureInitialized();
#endif
double sum;
// The two "other" directions which are summed over
int d_2 = (direction + 1) % 3;
int d_3 = (direction + 2) % 3;
int i, j, k;
ofstream fout;
fout.open(fileName.c_str());
for (i = 0; i < _sp.size(direction); i++) {
sum = 0.0;
for (j = 0; j < _sp.size(d_2); j++) {
for (k = 0; k < _sp.size(d_3); k++) {
if (direction == 0) {
sum += abs((*this)(i, j, k));
} else if (direction == 1) {
sum += abs((*this)(k, i, j));
} else {
sum += abs((*this)(j, k, i));
}
}
}
sum *= _sp.d(d_2, _space) * _sp.d(d_3, _space);
fout << _sp.coord(direction, i, _space) << " " << sum << "\n";
}
fout.close();
}
void Array::project2D(string fileName) const {
// Print column density profile in YZ plane
// TODO generalize for arbitrary direction
#ifdef DEBUG_GPE
assureInitialized();
#endif
double sum;
int i, j, k;
bool realSpace = _space;
ofstream fout;
fout.open(fileName.c_str());
for (j = 0; j < _sp.size(1) - 1; ++j) {
for (k = 0; k < _sp.size(2) - 1; ++k) {
sum = 0.0;
for (i = 0; i < _sp.size(0); ++i) {
sum += abs((*this)(i, j, k));
}
sum *= _sp.dX();
fout << _sp.coord(1, j, realSpace) << " ";
fout << _sp.coord(2, k, realSpace) << " ";
fout << sum << "\n";
fout << _sp.coord(1, j, realSpace) << " ";
fout << _sp.coord(2, k + 1, realSpace) << " ";
fout << sum << "\n";
}
fout << "\n";
for (k = 0; k < _sp.size(2) - 1; ++k) {
sum = 0.0;
for (i = 0; i < _sp.size(0); ++i) {
sum += abs((*this)(i, j, k));
}
sum *= _sp.dX();
fout << _sp.coord(1, j + 1, realSpace) << " ";
fout << _sp.coord(2, k, realSpace) << " ";
fout << sum << "\n";
fout << _sp.coord(1, j + 1, realSpace) << " ";
fout << _sp.coord(2, k + 1, realSpace) << " ";
fout << sum << "\n";
}
fout << "\n";
}
fout.close();
}
Array::~Array() {
delete[] _values;
if (_fourierPlan) {
#ifdef DEBUG_GPE
cerr << "Destroying Fourier Plans" << endl;
#endif
fftw_destroy_plan(_fourierPlan);
fftw_destroy_plan(_fourierPlanInverse);
if (!_fftwWisdomExported) {
// Export FFTW wisdom
#ifdef DEBUG_GPE
cerr << "Exporting FFTW wisdom" << endl;
#endif
FILE * wisdomFile = fopen("fftw.wisdom", "w");
fftw_export_wisdom_to_file(wisdomFile);
fclose(wisdomFile);
_fftwWisdomExported = true;
}
}
}
| 25.033794 | 157 | 0.483709 | erli1 |
a62fa6151e44bacc43b40a2ec1766e4d7e39cda1 | 1,094 | hpp | C++ | lumino/LuminoEngine/include/LuminoEngine/PostEffect/TonePostEffect.hpp | lriki/Lumino | 1a80430f4a83dbdfbe965b3d5b16064991b3edb0 | [
"MIT"
] | 30 | 2016-01-24T05:35:45.000Z | 2020-03-03T09:54:27.000Z | lumino/LuminoEngine/include/LuminoEngine/PostEffect/TonePostEffect.hpp | lriki/Lumino | 1a80430f4a83dbdfbe965b3d5b16064991b3edb0 | [
"MIT"
] | 35 | 2016-04-18T06:14:08.000Z | 2020-02-09T15:51:58.000Z | lumino/LuminoEngine/include/LuminoEngine/PostEffect/TonePostEffect.hpp | lriki/Lumino | 1a80430f4a83dbdfbe965b3d5b16064991b3edb0 | [
"MIT"
] | 5 | 2016-04-03T02:52:05.000Z | 2018-01-02T16:53:06.000Z | #pragma once
#include <LuminoGraphics/Animation/EasingFunctions.hpp>
#include "PostEffect.hpp"
namespace ln {
namespace detail { class TonePostEffectInstance; }
class TonePostEffect
: public PostEffect
{
public:
static Ref<TonePostEffect> create();
// [experimental]
void play(const ColorTone& tone, double time);
protected:
virtual void onUpdateFrame(float elapsedSeconds) override;
virtual Ref<PostEffectInstance> onCreateInstance() override;
LN_CONSTRUCT_ACCESS:
TonePostEffect();
virtual ~TonePostEffect();
void init();
private:
EasingValue<Vector4> m_toneValue;
friend class detail::TonePostEffectInstance;
};
namespace detail {
class TonePostEffectInstance
: public PostEffectInstance
{
protected:
bool onRender(RenderView* renderView, CommandList* context, RenderTargetTexture* source, RenderTargetTexture* destination) override;
LN_CONSTRUCT_ACCESS:
TonePostEffectInstance();
bool init(TonePostEffect* owner);
private:
TonePostEffect* m_owner;
Ref<Material> m_material;
};
} // namespace detail
} // namespace ln
| 21.038462 | 136 | 0.75777 | lriki |
a630f575527f809cbe2afc68d4de1a542df4ffc1 | 194 | cpp | C++ | Foreign/SonyLE/LevelEditorNativeRendering/LvEdRenderingEngine/GobSystem/MeshComponent.cpp | alexgithubber/XLE-Another-Fork | cdd8682367d9e9fdbdda9f79d72bb5b1499cec46 | [
"MIT"
] | 796 | 2015-01-02T12:25:52.000Z | 2022-03-22T18:45:03.000Z | Foreign/SonyLE/LevelEditorNativeRendering/LvEdRenderingEngine/GobSystem/MeshComponent.cpp | yorung/XLE | 083ce4c9d3fe32002ff5168e571cada2715bece4 | [
"MIT"
] | 22 | 2015-02-06T03:41:40.000Z | 2020-09-29T19:21:20.000Z | Foreign/SonyLE/LevelEditorNativeRendering/LvEdRenderingEngine/GobSystem/MeshComponent.cpp | yorung/XLE | 083ce4c9d3fe32002ff5168e571cada2715bece4 | [
"MIT"
] | 218 | 2015-01-01T15:58:25.000Z | 2022-02-21T05:17:37.000Z | #include "MeshComponent.h"
using namespace LvEdEngine;
void MeshComponent::SetRef(const wchar_t* path)
{
}
void MeshComponent::Update(const FrameTime& fr, UpdateTypeEnum updateType)
{
}
| 14.923077 | 74 | 0.757732 | alexgithubber |
a63176e26125bff1f6d71a354977b2b764ea837e | 1,211 | cpp | C++ | src/interfaces/DMSUT.cpp | dotweiba/dbt5 | 39e23b0a0bfd4dfcb80cb2231270324f6bbf4b42 | [
"Artistic-1.0"
] | 3 | 2017-08-30T12:57:33.000Z | 2022-02-08T14:25:03.000Z | src/interfaces/DMSUT.cpp | dotweiba/dbt5 | 39e23b0a0bfd4dfcb80cb2231270324f6bbf4b42 | [
"Artistic-1.0"
] | 1 | 2020-09-28T05:36:28.000Z | 2021-03-15T10:38:29.000Z | src/interfaces/DMSUT.cpp | dotweiba/dbt5 | 39e23b0a0bfd4dfcb80cb2231270324f6bbf4b42 | [
"Artistic-1.0"
] | 5 | 2017-01-18T20:16:06.000Z | 2021-03-09T12:23:50.000Z | /*
* This file is released under the terms of the Artistic License. Please see
* the file LICENSE, included in this package, for details.
*
* Copyright (C) 2006-2010 Rilson Nascimento
*
* 12 August 2006
*/
#include "DMSUT.h"
// constructor
CDMSUT::CDMSUT(char *addr, const int iListenPort, ofstream *pflog,
ofstream *pfmix, CMutex *pLogLock, CMutex *pMixLock)
: CBaseInterface(addr, iListenPort, pflog, pfmix, pLogLock, pMixLock)
{
}
// destructor
CDMSUT::~CDMSUT()
{
}
// Data Maintenance
bool CDMSUT::DataMaintenance(PDataMaintenanceTxnInput pTxnInput)
{
PMsgDriverBrokerage pRequest = new TMsgDriverBrokerage;
memset(pRequest, 0, sizeof(TMsgDriverBrokerage));
pRequest->TxnType = DATA_MAINTENANCE;
memcpy(&(pRequest->TxnInput.DataMaintenanceTxnInput), pTxnInput,
sizeof(TDataMaintenanceTxnInput));
return talkToSUT(pRequest);
}
// Trade Cleanup
bool CDMSUT::TradeCleanup(PTradeCleanupTxnInput pTxnInput)
{
PMsgDriverBrokerage pRequest = new TMsgDriverBrokerage;
memset(pRequest, 0, sizeof(TMsgDriverBrokerage));
pRequest->TxnType = TRADE_CLEANUP;
memcpy(&(pRequest->TxnInput.TradeCleanupTxnInput), pTxnInput,
sizeof(TTradeCleanupTxnInput));
return talkToSUT(pRequest);
}
| 24.714286 | 77 | 0.765483 | dotweiba |
a637e5dd24975ed0666d5db68dce64baa2c72e35 | 19,864 | cpp | C++ | 3rdparty/LibCluster/src/scluster.cpp | mfkiwl/ICE | e660d031bb1bcea664db1de4946fd8781be5b627 | [
"MIT"
] | 50 | 2019-10-12T01:22:20.000Z | 2022-02-15T23:28:26.000Z | 3rdparty/LibCluster/src/scluster.cpp | wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation | 2f1ff054b7c5059da80bb3b2f80c05861a02cc36 | [
"MIT"
] | null | null | null | 3rdparty/LibCluster/src/scluster.cpp | wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation | 2f1ff054b7c5059da80bb3b2f80c05861a02cc36 | [
"MIT"
] | 14 | 2019-11-05T01:50:29.000Z | 2021-08-06T06:23:44.000Z | /*
* libcluster -- A collection of hierarchical Bayesian clustering algorithms.
* Copyright (C) 2013 Daniel M. Steinberg (daniel.m.steinberg@gmail.com)
*
* This file is part of libcluster.
*
* libcluster 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 3 of the License, or (at your option)
* any later version.
*
* libcluster 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 libcluster. If not, see <http://www.gnu.org/licenses/>.
*/
#include <limits>
#include "libcluster.h"
#include "probutils.h"
#include "comutils.h"
//
// Namespaces
//
using namespace std;
using namespace Eigen;
using namespace probutils;
using namespace distributions;
using namespace comutils;
using namespace libcluster;
//
// Variational Bayes Private Functions
//
/* The Variational Bayes Expectation step for weights in each group.
*
* mutable: Top-level cluster assignment probabilities, qYj
* returns: The complete-data free energy, Y and Y+Z dep. terms, for group j.
* throws: invalid_argument rethrown from other functions.
*/
template <class WJ, class WT> double vbeY (
const vMatrixXd& qZj, // Cluster assignments for group j
const WJ& weightsj, // Group top-level cluster weights
const vector<WT>& weights_t, // Top-level cluster parameters
MatrixXd& qYj // Top-level cluster assignments for group j
)
{
const unsigned int T = weights_t.size(),
Ij = qZj.size(),
K = qZj[0].cols();
// Get log marginal weight likelihoods
const ArrayXd E_logwj = weightsj.Elogweight();
MatrixXd Njik(Ij, K), logqYj(Ij, T);
ArrayXXd qZjiLike(Ij, T);
// Get bottom-level cluster counts per top-level cluster
for (unsigned int i = 0; i < Ij; ++i)
Njik.row(i) = qZj[i].colwise().sum();
// Find Expectations of log joint observation probs
for (unsigned int t = 0; t < T; ++t)
{
qZjiLike.col(t) = Njik * weights_t[t].Elogweight().matrix();
logqYj.col(t) = E_logwj(t) + qZjiLike.col(t);
}
// Log normalisation constant of log observation likelihoods
VectorXd logZyj = logsumexp(logqYj);
// Normalise and Compute Responsibilities
qYj = (logqYj.colwise() - logZyj).array().exp().matrix();
return ((qYj.array() * qZjiLike).rowwise().sum() - logZyj.array()).sum();
}
/* The Variational Bayes Expectation step for clusters in each "document"
*
* mutable: Bottom-level cluster assignment probabilities, qZji
* returns: The complete-data free energy, Z dep. terms, for group j.
* throws: invalid_argument rethrown from other functions.
*/
template <class WT, class C> double vbeZ (
const MatrixXd& Xji, // Observations in i in group j
const RowVectorXd& qYji, // Top-level cluster assignment of this doc
const vector<WT>& weights_t, // Top-level cluster parameters
const vector<C>& clusters, // Bottom-level cluster parameters
MatrixXd& qZji // Observation to cluster assignments
)
{
const int K = clusters.size(),
Nji = Xji.rows(),
T = weights_t.size();
// Make top-level cluster global weights from weighted label parameters
RowVectorXd E_logqYljt = RowVectorXd::Zero(K);
for (int t = 0; t < T; ++t)
E_logqYljt.noalias() += qYji(t) * weights_t[t].Elogweight().matrix();
// Find Expectations of log joint observation probs
MatrixXd logqZji = MatrixXd::Zero(Nji, K);
for (int k = 0; k < K; ++k)
logqZji.col(k) = E_logqYljt(k) + clusters[k].Eloglike(Xji).array();
// Log normalisation constant of log observation likelihoods
const VectorXd logZzji = logsumexp(logqZji);
// Normalise and Compute Responsibilities
qZji = (logqZji.colwise() - logZzji).array().exp().matrix();
return -logZzji.sum();
}
/* Calculates the free energy lower bound for the model parameter distributions.
*
* returns: the free energy of the model
*/
template <class WJ, class WT, class C> double fenergy (
const vector<WJ>& weights_j, // Group top-level cluster weights
const vector<WT>& weights_t, // Top-level cluster parameters
const vector<C>& clusters, // Bottom-level cluster parameters
const double Fyz, // Free energy Y and Z+Y terms
const double Fz // Free energy Z terms
)
{
const int T = weights_t.size(),
K = clusters.size(),
J = weights_j.size();
// Class parameter free energy
double Fc = 0;
for (int t = 0; t < T; ++t)
Fc += weights_t[t].fenergy();
// Cluster parameter free energy
double Fk = 0;
for (int k = 0; k < K; ++k)
Fk += clusters[k].fenergy();
// Weight parameter free energy
double Fw = 0;
for (int j = 0; j < J; ++j)
Fw += weights_j[j].fenergy();
return Fw + Fc + Fk + Fyz + Fz;
}
/* Variational Bayes EM.
*
* returns: Free energy of the whole model.
* mutable: the bottom-level cluster indicators, qZ
* mutable: the top-level cluster indicators, qY
* mutable: model parameters weights_j, weights_t, clusters
* throws: invalid_argument rethrown from other functions.
* throws: runtime_error if there is a negative free energy.
*/
template <class WJ, class WT, class C> double vbem (
const vvMatrixXd& X, // Observations JxIjx[NjixD]
vvMatrixXd& qZ, // Observations to cluster assigns JxIjx[NjixK]
vMatrixXd& qY, // Indicator to label assignments Jx[IjxT]
vector<WJ>& weights_j, // Group weight distributions
vector<WT>& weights_t, // Top-level cluster distributions
vector<C>& clusters, // Bottom-level cluster Distributions
const double prior_t, // Prior value top-level cluster dists.
const double prior_k, // Prior value bottom-level cluster dists.
const int maxit = -1, // Max VBEM iterations (-1 = no max, default)
const bool verbose = false // Verbose output (default false)
)
{
const unsigned int J = X.size(),
K = qZ[0][0].cols(),
T = qY[0].cols();
// Construct (empty) parameters
weights_j.resize(J, WJ());
weights_t.resize(T, WT(prior_t));
clusters.resize(K, C(prior_k, X[0][0].cols()));
// Other loop variables for initialisation
int it = 0;
double F = numeric_limits<double>::max(), Fold;
do
{
Fold = F;
MatrixXd Ntk = MatrixXd::Zero(T, K); // Clear Sufficient Stats
// VBM for top-level cluster weights
#pragma omp parallel for schedule(guided)
for (unsigned int j = 0; j < J; ++j)
{
for(unsigned int i = 0; i < X[j].size(); ++i)
{
MatrixXd Ntkji = qY[j].row(i).transpose() * qZ[j][i].colwise().sum();
#pragma omp critical
Ntk += Ntkji;
}
weights_j[j].update(qY[j].colwise().sum());
}
// VBM for top-level cluster parameters
#pragma omp parallel for schedule(guided)
for (unsigned int t = 0; t < T; ++t)
weights_t[t].update(Ntk.row(t)); // Weighted multinomials.
// VBM for bottom-level cluster parameters
#pragma omp parallel for schedule(guided)
for (unsigned int k = 0; k < K; ++k)
{
clusters[k].clearobs();
for (unsigned int j = 0; j < J; ++j)
for(unsigned int i = 0; i < X[j].size(); ++i)
clusters[k].addobs(qZ[j][i].col(k), X[j][i]);
clusters[k].update();
}
double Fz = 0, Fyz = 0;
// VBE for top-level cluster indicators
#pragma omp parallel for schedule(guided) reduction(+ : Fyz)
for (unsigned int j = 0; j < J; ++j)
Fyz += vbeY<WJ,WT>(qZ[j], weights_j[j], weights_t, qY[j]);
// VBE for bottom-level cluster indicators
for (unsigned int j = 0; j < J; ++j)
{
#pragma omp parallel for schedule(guided) reduction(+ : Fz)
for (unsigned int i = 0; i < X[j].size(); ++i)
Fz += vbeZ<WT,C>(X[j][i], qY[j].row(i), weights_t, clusters, qZ[j][i]);
}
// Calculate free energy of model
F = fenergy<WJ,WT,C>(weights_j, weights_t, clusters, Fyz, Fz);
// Check bad free energy step
if ((F-Fold)/abs(Fold) > libcluster::FENGYDEL)
throw runtime_error("Free energy increase!");
if (verbose == true) // Notify iteration
cout << '-' << flush;
}
while ( (abs((Fold-F)/Fold) > libcluster::CONVERGE)
&& ( (++it < maxit) || (maxit < 0) ) );
return F;
}
//
// Model Selection and Heuristics Private Functions
//
/* Search in a greedy fashion for a mixture split that lowers model free
* energy, or return false. An attempt is made at looking for good, untried,
* split candidates first, as soon as a split canditate is found that lowers
* model F, it is returned. This may not be the "best" split, but it is
* certainly faster than an exhaustive search for the "best" split.
*
* returns: true if a split was found, false if no splits can be found
* mutable: qZ is augmented with a new split if one is found, otherwise left
* mutable: qY is updated if a new split if one is found, otherwise left
* mutable tally is a tally of times a cluster has been unsuccessfully split
* throws: invalid_argument rethrown from other functions
* throws: runtime_error from its internal VBEM calls
*/
template <class WJ, class WT, class C> bool split_gr (
const vvMatrixXd& X, // Observations
const vector<C>& clusters, // Cluster Distributions
const double prior_t, // Prior value for top-level clusters
vMatrixXd& qY, // Top-level cluster labels qY
vvMatrixXd& qZ, // Bottom-level Cluster labels qZ
vector<int>& tally, // Count of unsuccessful splits
const double F, // Current model free energy
const int maxK, // max number of (bottom) clusters
const bool verbose // Verbose output
)
{
const unsigned int J = X.size(),
K = clusters.size();
// Check if we have reached the max number of clusters
if ( ((signed) K >= maxK) && (maxK >= 0) )
return false;
// Split order chooser and bottom-level cluster parameters
tally.resize(K, 0); // Make sure tally is the right size
vector<GreedOrder> ord(K);
// Get cluster parameters and their free energy
for (unsigned int k = 0; k < K; ++k)
{
ord[k].k = k;
ord[k].tally = tally[k];
ord[k].Fk = clusters[k].fenergy();
}
// Get bottom-level cluster likelihoods
for (unsigned int j = 0; j < J; ++j)
{
// Add in cluster log-likelihood, weighted by global responsability
#pragma omp parallel for schedule(guided)
for (unsigned int i = 0; i < X[j].size(); ++i)
for (unsigned int k = 0; k < K; ++k)
{
double LL = qZ[j][i].col(k).dot(clusters[k].Eloglike(X[j][i]));
#pragma omp atomic
ord[k].Fk -= LL;
}
}
// Sort clusters by split tally, then free energy contributions
sort(ord.begin(), ord.end(), greedcomp);
// Pre allocate big objects for loops (this makes a runtime difference)
vector< vector<ArrayXi> > mapidx(J);
vMatrixXd qYref(J);
vvMatrixXd qZref(J), qZaug(J), Xk(J);
// Loop through each potential cluster in order and split it
for (vector<GreedOrder>::iterator ko = ord.begin(); ko < ord.end(); ++ko)
{
const int k = ko->k;
++tally[k]; // increase this cluster's unsuccessful split tally by default
// Don't waste time with clusters that can't really be split min (2:2)
if (clusters[k].getN() < 4)
continue;
// Now split observations and qZ.
int scount = 0, Mtot = 0;
for (unsigned int j = 0; j < J; ++j)
{
mapidx[j].resize(X[j].size());
qZref[j].resize(X[j].size());
qZaug[j].resize(X[j].size());
Xk[j].resize(X[j].size());
qYref[j].setOnes(X[j].size(), 1);
#pragma omp parallel for schedule(guided) reduction(+ : Mtot, scount)
for (unsigned int i = 0; i < X[j].size(); ++i)
{
// Make COPY of the observations with only relevant data points, p > 0.5
mapidx[j][i] = partobs(X[j][i], (qZ[j][i].col(k).array() > 0.5),
Xk[j][i]);
Mtot += Xk[j][i].rows();
// Initial cluster split
ArrayXb splitk = clusters[k].splitobs(Xk[j][i]);
qZref[j][i].setZero(Xk[j][i].rows(), 2);
qZref[j][i].col(0) = (splitk == true).cast<double>();
qZref[j][i].col(1) = (splitk == false).cast<double>();
// keep a track of number of splits
scount += splitk.count();
}
}
// Don't waste time with clusters that haven't been split sufficiently
if ( (scount < 2) || (scount > (Mtot-2)) )
continue;
// Refine the split
vector<WJ> wspl;
vector<WT> lspl;
vector<C> cspl;
vbem<WJ,WT,C>(Xk, qZref, qYref, wspl, lspl, cspl, prior_t,
clusters[0].getprior(), SPLITITER);
if (anyempty<C>(cspl) == true) // One cluster only
continue;
// Map the refined splits back to original whole-data problem
for (unsigned int j = 0; j < J; ++j)
{
#pragma omp parallel for schedule(guided)
for (unsigned int i = 0; i < X[j].size(); ++i)
qZaug[j][i] = auglabels(k, mapidx[j][i],
(qZref[j][i].col(1).array() > 0.5), qZ[j][i]);
}
// Calculate free energy of this split with ALL data (and refine a bit)
vMatrixXd qYaug = qY; // Copy :-(
double Fs = vbem<WJ,WT,C>(X, qZaug, qYaug, wspl, lspl, cspl, prior_t,
clusters[0].getprior(), 1);
if (anyempty<C>(cspl) == true) // One cluster only
continue;
// Only notify here of split candidates
if (verbose == true)
cout << '=' << flush;
// Test whether this cluster split is a keeper
if ( (Fs < F) && (abs((F-Fs)/F) > CONVERGE) )
{
qY = qYaug;
qZ = qZaug;
tally[k] = 0; // Reset tally if successfully split
return true;
}
}
// Failed to find splits
return false;
}
/* Find and remove all empty top-level clusters.
*
* returns: true if any clusters have been deleted, false if all are kept.
* mutable: qY may have columns deleted if there are empty weights found.
* mutable: weights_t if there are empty top-level clusters found.
*/
template <class WT> bool prune_clusters_t (
vMatrixXd& qY, // Probabilities qY
vector<WT>& weights_t, // weights distributions
bool verbose = false // print status
)
{
const unsigned int T = weights_t.size(),
J = qY.size();
// Look for empty clusters
ArrayXd Nt(T);
for (unsigned int t = 0; t < T; ++t)
Nt(t) = weights_t[t].getNk().sum();
// Find location of empty and full clusters
ArrayXi eidx, fidx;
arrfind(Nt.array() < 1, eidx, fidx);
const unsigned int nempty = eidx.size();
// If everything is not empty, return false
if (nempty == 0)
return false;
if (verbose == true)
cout << '*' << flush;
// Delete empty cluster suff. stats.
for (int i = (nempty - 1); i >= 0; --i)
weights_t.erase(weights_t.begin() + eidx(i));
// Delete empty cluster indicators by copying only full indicators
const unsigned int newT = fidx.size();
vMatrixXd newqY(J);
for (unsigned int j = 0; j < J; ++j)
{
newqY[j].setZero(qY[j].rows(), newT);
for (unsigned int t = 0; t < newT; ++t)
newqY[j].col(t) = qY[j].col(fidx(t));
}
qY = newqY;
return true;
}
/* The model selection algorithm
*
* returns: Free energy of the final model
* mutable: qY the probabilistic top-level cluster assignments
* mutable: qZ the probabilistic observation to bottom-level cluster assigns.
* mutable: the top-level cluster weights and parameters.
* mutable: the bottom-level cluster weights and parameters.
* throws: invalid_argument from other functions.
* throws: runtime_error if free energy increases.
*/
template <class WJ, class WT, class C> double scluster (
const vvMatrixXd& X, // Observations
vMatrixXd& qY, // Top-level cluster assignments
vvMatrixXd& qZ, // Bottom-level cluster assignments
vector<WJ>& weights_j, // Group weight distributions
vector<WT>& weights_t, // Top-level cluster distributions
vector<C>& clusters, // Bottom-level cluster Distributions
const double prior_t, // Prior value for top-level cluster dists.
const double prior_k, // Prior value for bottom-level cluster dists.
const unsigned int maxT, // Truncation level for number of weights
const int maxK, // max number of (bottom) clusters
const bool verbose, // Verbose output
const unsigned int nthreads // Number of threads for OpenMP to use
)
{
if (nthreads < 1)
throw invalid_argument("Must specify at least one thread for execution!");
omp_set_num_threads(nthreads);
const unsigned int J = X.size();
unsigned int Itot = 0;
// Randomly initialise qY and initialise qZ to ones
qY.resize(J);
qZ.resize(J);
for (unsigned int j = 0; j < J; ++j)
{
const unsigned int Ij = X[j].size();
ArrayXXd randm = (ArrayXXd::Random(Ij, maxT)).abs();
ArrayXd norm = randm.rowwise().sum();
qY[j] = (randm.log().colwise() - norm.log()).exp();
qZ[j].resize(Ij);
for (unsigned int i = 0; i < Ij; ++i)
qZ[j][i].setOnes(X[j][i].rows(), 1);
Itot += Ij;
}
// Some input argument checking
if (maxT > Itot)
throw invalid_argument("maxT must be less than the number of documents of"
"X!");
// Initialise free energy and other loop variables
bool issplit = true, emptyclasses = true;
double F = 0;
vector<int> tally;
// Main loop
while ((issplit == true) || (emptyclasses == true))
{
// Variational Bayes
F = vbem<WJ,WT,C>(X, qZ, qY, weights_j, weights_t, clusters, prior_t,
prior_k, -1, verbose);
// Start model search heuristics
if (verbose == true)
cout << '<' << flush; // Notify start search
if (issplit == false) // Remove any empty weights
emptyclasses = prune_clusters_t<WT>(qY, weights_t, verbose);
else // Search for best split, augment qZ if found one
issplit = split_gr<WJ,WT,C>(X, clusters, prior_t, qY, qZ, tally, F, maxK,
verbose);
if (verbose == true)
cout << '>' << endl; // Notify end search
}
// Print finished notification if verbose
if (verbose == true)
{
cout << "Finished!" << endl;
cout << "Number of top level clusters = " << weights_t.size();
cout << ", and bottom level clusters = " << clusters.size() << endl;
cout << "Free energy = " << F << endl;
}
return F;
}
//
// Public Functions
//
double libcluster::learnSCM (
const vvMatrixXd& X,
vMatrixXd& qY,
vvMatrixXd& qZ,
vector<GDirichlet>& weights_j,
vector<Dirichlet>& weights_t,
vector<GaussWish>& clusters,
const double dirprior,
const double gausprior,
const unsigned int maxT,
const int maxK,
const bool verbose,
const unsigned int nthreads
)
{
if (verbose == true)
cout << "Learning SCM..." << endl;
// Model selection and Variational Bayes learning
double F = scluster<GDirichlet, Dirichlet, GaussWish>(X, qY, qZ,
weights_j, weights_t, clusters, dirprior, gausprior, maxT,
maxK, verbose, nthreads);
return F;
}
| 32.778878 | 80 | 0.616694 | mfkiwl |
a63af4b9241f79ff0f7e0899970a1a73062fca59 | 2,792 | cpp | C++ | dependencies/mozilla-js/1.8.5/js/src/jsapi-tests/testGCChunkAlloc.cpp | mosaic-cloud/mosaic-distribution-dependencies | 87b9fa3dcf24751abcc52c00849b85f4d7e77b16 | [
"Apache-2.0"
] | 1 | 2015-04-19T10:49:48.000Z | 2015-04-19T10:49:48.000Z | deps/spidermonkey/jsapi-tests/testGCChunkAlloc.cpp | havocp/hwf | a99e9a0461983226717b278513cfd9f1e53ba0f1 | [
"MIT"
] | 3 | 2015-05-15T18:56:54.000Z | 2015-05-15T20:58:57.000Z | deps/spidermonkey/jsapi-tests/testGCChunkAlloc.cpp | havocp/hwf | a99e9a0461983226717b278513cfd9f1e53ba0f1 | [
"MIT"
] | null | null | null | /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* vim: set ts=8 sw=4 et tw=99:
*
* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/licenses/publicdomain/
* Contributor: Igor Bukanov
*/
#include "tests.h"
#include "jsgcchunk.h"
#include "jscntxt.h"
/* We allow to allocate only single chunk. */
class CustomGCChunkAllocator: public js::GCChunkAllocator {
public:
CustomGCChunkAllocator() : pool(NULL) {}
void *pool;
private:
virtual void *doAlloc() {
if (!pool)
return NULL;
void *chunk = pool;
pool = NULL;
return chunk;
}
virtual void doFree(void *chunk) {
JS_ASSERT(!pool);
pool = chunk;
}
};
static CustomGCChunkAllocator customGCChunkAllocator;
static unsigned errorCount = 0;
static void
ErrorCounter(JSContext *cx, const char *message, JSErrorReport *report)
{
++errorCount;
}
BEGIN_TEST(testGCChunkAlloc)
{
JS_SetErrorReporter(cx, ErrorCounter);
jsvalRoot root(cx);
/*
* We loop until out-of-memory happens during the chunk allocation. But
* we have to disable the jit since it cannot tolerate OOM during the
* chunk allocation.
*/
JS_ToggleOptions(cx, JSOPTION_JIT);
static const char source[] =
"var max = 0; (function() {"
" var array = [];"
" for (; ; ++max)"
" array.push({});"
"})();";
JSBool ok = JS_EvaluateScript(cx, global, source, strlen(source), "", 1,
root.addr());
/* Check that we get OOM. */
CHECK(!ok);
CHECK(!JS_IsExceptionPending(cx));
CHECK(errorCount == 1);
CHECK(!customGCChunkAllocator.pool);
JS_GC(cx);
JS_ToggleOptions(cx, JSOPTION_JIT);
EVAL("(function() {"
" var array = [];"
" for (var i = max >> 1; i != 0;) {"
" --i;"
" array.push({});"
" }"
"})();", root.addr());
CHECK(errorCount == 1);
return true;
}
virtual JSRuntime * createRuntime() {
/*
* To test failure of chunk allocation allow to use GC twice the memory
* the single chunk contains.
*/
JSRuntime *rt = JS_NewRuntime(2 * js::GC_CHUNK_SIZE);
if (!rt)
return NULL;
customGCChunkAllocator.pool = js::AllocGCChunk();
JS_ASSERT(customGCChunkAllocator.pool);
rt->setCustomGCChunkAllocator(&customGCChunkAllocator);
return rt;
}
virtual void destroyRuntime() {
JS_DestroyRuntime(rt);
/* We should get the initial chunk back at this point. */
JS_ASSERT(customGCChunkAllocator.pool);
js::FreeGCChunk(customGCChunkAllocator.pool);
customGCChunkAllocator.pool = NULL;
}
END_TEST(testGCChunkAlloc)
| 24.928571 | 76 | 0.601361 | mosaic-cloud |
a63bf17f03622781852d02b01c1d36716300278b | 3,220 | cpp | C++ | lab7/150101033_1.cpp | mayank-myk/Basic-Datastructure-implementations | 4bf5f79c2c5ad636fe9d61c0be36a0a3e1238356 | [
"MIT"
] | null | null | null | lab7/150101033_1.cpp | mayank-myk/Basic-Datastructure-implementations | 4bf5f79c2c5ad636fe9d61c0be36a0a3e1238356 | [
"MIT"
] | null | null | null | lab7/150101033_1.cpp | mayank-myk/Basic-Datastructure-implementations | 4bf5f79c2c5ad636fe9d61c0be36a0a3e1238356 | [
"MIT"
] | null | null | null | //mayank agrawal
//150101033
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
using namespace std;
struct set{
int size;
struct node *head;
struct node *tail;
};
struct node{
int data;
struct set *rep ;
struct node *next;
};
//initializing struct node abject and struct set object
struct node *make_set(int a) {
struct set *newSet = new struct set;
newSet->head = new struct node;
newSet->tail = newSet->head;
newSet->size=1;
struct node *temp = newSet->head;
temp->data = a;
temp->rep = newSet;
temp->next = NULL;
return temp;
}
//returns the representative struct set of any struct node
struct set *find_set(struct node *a){
return a->rep;
}
void *unions(struct node *x,struct node *y){
struct set *a = find_set(x); //find_set returns representative of any node
struct set *b = find_set(y);
if (a->size > b->size) {
a->size=a->size + b->size;
a->tail->next=b->head ; //combining smaller set into bigger set
a->tail = b->tail;
struct node *temp=b->head; //changing representative pointer of all elements of smaller
while(temp){ //set to that of bigger set
temp->rep= a;
temp = temp->next;
}
}
else{
b->size =a->size + b->size ;
b->tail->next=a->head;
b->tail = a->tail;
struct node *temp=a->head ;
while(temp) {
temp->rep= b;
temp = temp->next;
}
}
}
//function to print the whole list
void pprint(struct node **arr,int arr1[],int k){
int i,j,check[100]={0} ;
cout << endl;
for(i=0;i<k;i++){
j=arr1[i];
if(check[j]==0){
struct node *temp=arr[j];
struct set *temp1=temp->rep;
struct node *temp2=temp1->head;
while(temp2){
cout << temp2->data << " " ;
check[temp2->data]=1;
temp2 = temp2->next;
}
cout << endl;
}
}
cout <<endl;
}
int main(){
int k,j,n=0;
cout<< "Input the value of k: ";
cin >> k ;
int arr1[k];
struct node ** arr=new struct node* [100]; //array to store all the struct node according to index
for(int i=0;i<k;i++){
cout << "input the data (between 0 to 99):" ;
cin >> j;
arr[j] = make_set(j);
arr1[i]=j; //array to store value of each node
}
while(1){
int m,a,b,c;
cout << "1 for union, 2 for find_set, 3 for exit" << endl;
cin >> m ;
switch(m){
case 1:
cout << "type the number whose union you want to find" << endl;
cin >> a >> b;
unions(arr[a],arr[b]);
pprint(arr,arr1,k);
break;
case 2:
cout << "type the number whose find_set you need" << endl;
cin >> c ;
struct set *y;
y=find_set(arr[c]);
cout << "the set representative is "<< y->head->data << endl;
break;
default: exit(0);
}
}
return 0;
}
| 25.555556 | 105 | 0.497205 | mayank-myk |
a63f2c38b77b58a5070fb4d338e1ed514a4d2a91 | 1,977 | tcc | C++ | nheqminer/zcash/circuit/utils.tcc | Maroc-OS/nheqminer | b1451be01151d535118900daf3b2309d91401fcb | [
"MIT"
] | 4 | 2017-06-30T08:19:05.000Z | 2017-11-26T21:29:35.000Z | nheqminer/zcash/circuit/utils.tcc | Maroc-OS/nheqminer | b1451be01151d535118900daf3b2309d91401fcb | [
"MIT"
] | null | null | null | nheqminer/zcash/circuit/utils.tcc | Maroc-OS/nheqminer | b1451be01151d535118900daf3b2309d91401fcb | [
"MIT"
] | 1 | 2019-07-04T22:36:20.000Z | 2019-07-04T22:36:20.000Z | #include "uint252.h"
template <typename FieldT>
pb_variable_array<FieldT> from_bits(std::vector<bool> bits,
pb_variable<FieldT> &ZERO) {
pb_variable_array<FieldT> acc;
BOOST_FOREACH (bool bit, bits) { acc.emplace_back(bit ? ONE : ZERO); }
return acc;
}
std::vector<bool> trailing252(std::vector<bool> input) {
if (input.size() != 256) {
throw std::length_error("trailing252 input invalid length");
}
return std::vector<bool>(input.begin() + 4, input.end());
}
template <typename T> std::vector<bool> to_bool_vector(T input) {
std::vector<unsigned char> input_v(input.begin(), input.end());
return convertBytesVectorToVector(input_v);
}
std::vector<bool> uint256_to_bool_vector(uint256 input) {
return to_bool_vector(input);
}
std::vector<bool> uint252_to_bool_vector(uint252 input) {
return trailing252(to_bool_vector(input));
}
std::vector<bool> uint64_to_bool_vector(uint64_t input) {
auto num_bv = convertIntToVectorLE(input);
return convertBytesVectorToVector(num_bv);
}
void insert_uint256(std::vector<bool> &into, uint256 from) {
std::vector<bool> blob = uint256_to_bool_vector(from);
into.insert(into.end(), blob.begin(), blob.end());
}
void insert_uint64(std::vector<bool> &into, uint64_t from) {
std::vector<bool> num = uint64_to_bool_vector(from);
into.insert(into.end(), num.begin(), num.end());
}
template <typename T> T swap_endianness_u64(T v) {
if (v.size() != 64) {
throw std::length_error("invalid bit length for 64-bit unsigned integer");
}
for (size_t i = 0; i < 4; i++) {
for (size_t j = 0; j < 8; j++) {
std::swap(v[i * 8 + j], v[((7 - i) * 8) + j]);
}
}
return v;
}
template <typename FieldT>
linear_combination<FieldT> packed_addition(pb_variable_array<FieldT> input) {
auto input_swapped = swap_endianness_u64(input);
return pb_packing_sum<FieldT>(
pb_variable_array<FieldT>(input_swapped.rbegin(), input_swapped.rend()));
}
| 27.458333 | 79 | 0.686394 | Maroc-OS |
a6401c29d834b945c4b36ef796c6cb507c8f0726 | 18,322 | cpp | C++ | src/dso_helpers/SODSOSystemOptimize.cpp | IRVLab/scale_optimization | 3eeb9cf8231e8336cea34cb12f1a87d04fcfbd64 | [
"Unlicense"
] | 38 | 2020-07-23T04:33:41.000Z | 2022-03-07T03:41:38.000Z | src/dso_helpers/SODSOSystemOptimize.cpp | IRVLab/scale_optimization | 3eeb9cf8231e8336cea34cb12f1a87d04fcfbd64 | [
"Unlicense"
] | 5 | 2019-12-21T06:25:35.000Z | 2020-10-23T06:25:12.000Z | src/dso_helpers/SODSOSystemOptimize.cpp | IRVLab/scale_optimization | 3eeb9cf8231e8336cea34cb12f1a87d04fcfbd64 | [
"Unlicense"
] | 10 | 2020-10-19T01:00:43.000Z | 2022-02-21T03:57:57.000Z | #include "SODSOSystem.h"
#include "FullSystem/ResidualProjections.h"
#include "IOWrapper/ImageDisplay.h"
#include "stdio.h"
#include "util/globalCalib.h"
#include "util/globalFuncs.h"
#include <Eigen/Eigenvalues>
#include <Eigen/LU>
#include <Eigen/SVD>
#include <algorithm>
#include "OptimizationBackend/EnergyFunctional.h"
#include "OptimizationBackend/EnergyFunctionalStructs.h"
#include <cmath>
#include <algorithm>
namespace dso {
void SODSOSystem::linearizeAll_Reductor(
bool fixLinearization, std::vector<PointFrameResidual *> *toRemove, int min,
int max, Vec10 *stats, int tid) {
for (int k = min; k < max; k++) {
PointFrameResidual *r = activeResiduals[k];
(*stats)[0] += r->linearize(&Hcalib);
if (fixLinearization) {
r->applyRes(true);
if (r->efResidual->isActive()) {
if (r->isNew) {
PointHessian *p = r->point;
Vec3f ptp_inf =
r->host->targetPrecalc[r->target->idx].PRE_KRKiTll *
Vec3f(p->u, p->v, 1); // projected point assuming infinite depth.
Vec3f ptp = ptp_inf +
r->host->targetPrecalc[r->target->idx].PRE_KtTll *
p->idepth_scaled; // projected point with real depth.
float relBS = 0.01 * ((ptp_inf.head<2>() / ptp_inf[2]) -
(ptp.head<2>() / ptp[2]))
.norm(); // 0.01 = one pixel.
if (relBS > p->maxRelBaseline)
p->maxRelBaseline = relBS;
p->numGoodResiduals++;
}
} else {
toRemove[tid].push_back(activeResiduals[k]);
}
}
}
}
void SODSOSystem::applyRes_Reductor(bool copyJacobians, int min, int max,
Vec10 *stats, int tid) {
for (int k = min; k < max; k++)
activeResiduals[k]->applyRes(true);
}
void SODSOSystem::setNewFrameEnergyTH() {
// collect all residuals and make decision on TH.
allResVec.clear();
allResVec.reserve(activeResiduals.size() * 2);
FrameHessian *newFrame = frameHessians.back();
for (PointFrameResidual *r : activeResiduals)
if (r->state_NewEnergyWithOutlier >= 0 && r->target == newFrame) {
allResVec.push_back(r->state_NewEnergyWithOutlier);
}
if (allResVec.size() == 0) {
newFrame->frameEnergyTH = 12 * 12 * patternNum;
return; // should never happen, but lets make sure.
}
int nthIdx = setting_frameEnergyTHN * allResVec.size();
assert(nthIdx < (int)allResVec.size());
assert(setting_frameEnergyTHN < 1);
std::nth_element(allResVec.begin(), allResVec.begin() + nthIdx,
allResVec.end());
float nthElement = sqrtf(allResVec[nthIdx]);
newFrame->frameEnergyTH = nthElement * setting_frameEnergyTHFacMedian;
newFrame->frameEnergyTH =
26.0f * setting_frameEnergyTHConstWeight +
newFrame->frameEnergyTH * (1 - setting_frameEnergyTHConstWeight);
newFrame->frameEnergyTH = newFrame->frameEnergyTH * newFrame->frameEnergyTH;
newFrame->frameEnergyTH *=
setting_overallEnergyTHWeight * setting_overallEnergyTHWeight;
//
// int good=0,bad=0;
// for(float f : allResVec) if(f<newFrame->frameEnergyTH) good++; else bad++;
// printf("EnergyTH: mean %f, median %f, result %f (in %d, out %d)! \n",
// meanElement, nthElement, sqrtf(newFrame->frameEnergyTH),
// good, bad);
}
Vec3 SODSOSystem::linearizeAll(bool fixLinearization) {
double lastEnergyP = 0;
double lastEnergyR = 0;
double num = 0;
std::vector<PointFrameResidual *> toRemove[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; i++)
toRemove[i].clear();
if (multiThreading) {
treadReduce.reduce(boost::bind(&SODSOSystem::linearizeAll_Reductor, this,
fixLinearization, toRemove, _1, _2, _3, _4),
0, activeResiduals.size(), 0);
lastEnergyP = treadReduce.stats[0];
} else {
Vec10 stats;
linearizeAll_Reductor(fixLinearization, toRemove, 0, activeResiduals.size(),
&stats, 0);
lastEnergyP = stats[0];
}
setNewFrameEnergyTH();
if (fixLinearization) {
for (PointFrameResidual *r : activeResiduals) {
PointHessian *ph = r->point;
if (ph->lastResiduals[0].first == r)
ph->lastResiduals[0].second = r->state_state;
else if (ph->lastResiduals[1].first == r)
ph->lastResiduals[1].second = r->state_state;
}
int nResRemoved = 0;
for (int i = 0; i < NUM_THREADS; i++) {
for (PointFrameResidual *r : toRemove[i]) {
PointHessian *ph = r->point;
if (ph->lastResiduals[0].first == r)
ph->lastResiduals[0].first = 0;
else if (ph->lastResiduals[1].first == r)
ph->lastResiduals[1].first = 0;
for (unsigned int k = 0; k < ph->residuals.size(); k++)
if (ph->residuals[k] == r) {
ef->dropResidual(r->efResidual);
deleteOut<PointFrameResidual>(ph->residuals, k);
nResRemoved++;
break;
}
}
}
// printf("FINAL LINEARIZATION: removed %d / %d residuals!\n", nResRemoved,
// (int)activeResiduals.size());
}
return Vec3(lastEnergyP, lastEnergyR, num);
}
// applies step to linearization point.
bool SODSOSystem::doStepFromBackup(float stepfacC, float stepfacT,
float stepfacR, float stepfacA,
float stepfacD) {
// float meanStepC=0,meanStepP=0,meanStepD=0;
// meanStepC += Hcalib.step.norm();
Vec10 pstepfac;
pstepfac.segment<3>(0).setConstant(stepfacT);
pstepfac.segment<3>(3).setConstant(stepfacR);
pstepfac.segment<4>(6).setConstant(stepfacA);
float sumA = 0, sumB = 0, sumT = 0, sumR = 0, sumID = 0, numID = 0;
float sumNID = 0;
if (setting_solverMode & SOLVER_MOMENTUM) {
Hcalib.setValue(Hcalib.value_backup + Hcalib.step);
for (FrameHessian *fh : frameHessians) {
Vec10 step = fh->step;
step.head<6>() += 0.5f * (fh->step_backup.head<6>());
fh->setState(fh->state_backup + step);
sumA += step[6] * step[6];
sumB += step[7] * step[7];
sumT += step.segment<3>(0).squaredNorm();
sumR += step.segment<3>(3).squaredNorm();
for (PointHessian *ph : fh->pointHessians) {
float step = ph->step + 0.5f * (ph->step_backup);
ph->setIdepth(ph->idepth_backup + step);
sumID += step * step;
sumNID += fabsf(ph->idepth_backup);
numID++;
ph->setIdepthZero(ph->idepth_backup + step);
}
}
} else {
Hcalib.setValue(Hcalib.value_backup + stepfacC * Hcalib.step);
for (FrameHessian *fh : frameHessians) {
fh->setState(fh->state_backup + pstepfac.cwiseProduct(fh->step));
sumA += fh->step[6] * fh->step[6];
sumB += fh->step[7] * fh->step[7];
sumT += fh->step.segment<3>(0).squaredNorm();
sumR += fh->step.segment<3>(3).squaredNorm();
for (PointHessian *ph : fh->pointHessians) {
ph->setIdepth(ph->idepth_backup + stepfacD * ph->step);
sumID += ph->step * ph->step;
sumNID += fabsf(ph->idepth_backup);
numID++;
ph->setIdepthZero(ph->idepth_backup + stepfacD * ph->step);
}
}
}
sumA /= frameHessians.size();
sumB /= frameHessians.size();
sumR /= frameHessians.size();
sumT /= frameHessians.size();
sumID /= numID;
sumNID /= numID;
if (!setting_debugout_runquiet)
printf("STEPS: A %.1f; B %.1f; R %.1f; T %.1f. \t",
sqrtf(sumA) / (0.0005 * setting_thOptIterations),
sqrtf(sumB) / (0.00005 * setting_thOptIterations),
sqrtf(sumR) / (0.00005 * setting_thOptIterations),
sqrtf(sumT) * sumNID / (0.00005 * setting_thOptIterations));
EFDeltaValid = false;
setPrecalcValues();
return sqrtf(sumA) < 0.0005 * setting_thOptIterations &&
sqrtf(sumB) < 0.00005 * setting_thOptIterations &&
sqrtf(sumR) < 0.00005 * setting_thOptIterations &&
sqrtf(sumT) * sumNID < 0.00005 * setting_thOptIterations;
//
// printf("mean steps: %f %f %f!\n",
// meanStepC, meanStepP, meanStepD);
}
// sets linearization point.
void SODSOSystem::backupState(bool backupLastStep) {
if (setting_solverMode & SOLVER_MOMENTUM) {
if (backupLastStep) {
Hcalib.step_backup = Hcalib.step;
Hcalib.value_backup = Hcalib.value;
for (FrameHessian *fh : frameHessians) {
fh->step_backup = fh->step;
fh->state_backup = fh->get_state();
for (PointHessian *ph : fh->pointHessians) {
ph->idepth_backup = ph->idepth;
ph->step_backup = ph->step;
}
}
} else {
Hcalib.step_backup.setZero();
Hcalib.value_backup = Hcalib.value;
for (FrameHessian *fh : frameHessians) {
fh->step_backup.setZero();
fh->state_backup = fh->get_state();
for (PointHessian *ph : fh->pointHessians) {
ph->idepth_backup = ph->idepth;
ph->step_backup = 0;
}
}
}
} else {
Hcalib.value_backup = Hcalib.value;
for (FrameHessian *fh : frameHessians) {
fh->state_backup = fh->get_state();
for (PointHessian *ph : fh->pointHessians)
ph->idepth_backup = ph->idepth;
}
}
}
// sets linearization point.
void SODSOSystem::loadSateBackup() {
Hcalib.setValue(Hcalib.value_backup);
for (FrameHessian *fh : frameHessians) {
fh->setState(fh->state_backup);
for (PointHessian *ph : fh->pointHessians) {
ph->setIdepth(ph->idepth_backup);
ph->setIdepthZero(ph->idepth_backup);
}
}
EFDeltaValid = false;
setPrecalcValues();
}
double SODSOSystem::calcMEnergy() {
if (setting_forceAceptStep)
return 0;
// calculate (x-x0)^T * [2b + H * (x-x0)] for everything saved in L.
// ef->makeIDX();
// ef->setDeltaF(&Hcalib);
return ef->calcMEnergyF();
}
void SODSOSystem::printOptRes(const Vec3 &res, double resL, double resM,
double resPrior, double LExact, float a,
float b) {
printf("A(%f)=(AV %.3f). Num: A(%'d) + M(%'d); ab %f %f!\n", res[0],
sqrtf((float)(res[0] / (patternNum * ef->resInA))), ef->resInA,
ef->resInM, a, b);
}
float SODSOSystem::optimize(int mnumOptIts) {
if (frameHessians.size() < 2)
return 0;
if (frameHessians.size() < 3)
mnumOptIts = 20;
if (frameHessians.size() < 4)
mnumOptIts = 15;
// get statistics and active residuals.
activeResiduals.clear();
int numPoints = 0;
int numLRes = 0;
for (FrameHessian *fh : frameHessians)
for (PointHessian *ph : fh->pointHessians) {
for (PointFrameResidual *r : ph->residuals) {
if (!r->efResidual->isLinearized) {
activeResiduals.push_back(r);
r->resetOOB();
} else
numLRes++;
}
numPoints++;
}
if (!setting_debugout_runquiet)
printf("OPTIMIZE %d pts, %d active res, %d lin res!\n", ef->nPoints,
(int)activeResiduals.size(), numLRes);
Vec3 lastEnergy = linearizeAll(false);
double lastEnergyL = calcLEnergy();
double lastEnergyM = calcMEnergy();
if (multiThreading)
treadReduce.reduce(boost::bind(&SODSOSystem::applyRes_Reductor, this, true,
_1, _2, _3, _4),
0, activeResiduals.size(), 50);
else
applyRes_Reductor(true, 0, activeResiduals.size(), 0, 0);
if (!setting_debugout_runquiet) {
printf("Initial Error \t");
printOptRes(lastEnergy, lastEnergyL, lastEnergyM, 0, 0,
frameHessians.back()->aff_g2l().a,
frameHessians.back()->aff_g2l().b);
}
debugPlotTracking();
double lambda = 1e-1;
float stepsize = 1;
VecX previousX = VecX::Constant(CPARS + 8 * frameHessians.size(), NAN);
for (int iteration = 0; iteration < mnumOptIts; iteration++) {
// solve!
backupState(iteration != 0);
// solveSystemNew(0);
solveSystem(iteration, lambda);
double incDirChange = (1e-20 + previousX.dot(ef->lastX)) /
(1e-20 + previousX.norm() * ef->lastX.norm());
previousX = ef->lastX;
if (std::isfinite(incDirChange) &&
(setting_solverMode & SOLVER_STEPMOMENTUM)) {
float newStepsize = exp(incDirChange * 1.4);
if (incDirChange < 0 && stepsize > 1)
stepsize = 1;
stepsize = sqrtf(sqrtf(newStepsize * stepsize * stepsize * stepsize));
if (stepsize > 2)
stepsize = 2;
if (stepsize < 0.25)
stepsize = 0.25;
}
bool canbreak =
doStepFromBackup(stepsize, stepsize, stepsize, stepsize, stepsize);
// eval new energy!
Vec3 newEnergy = linearizeAll(false);
double newEnergyL = calcLEnergy();
double newEnergyM = calcMEnergy();
if (!setting_debugout_runquiet) {
printf("%s %d (L %.2f, dir %.2f, ss %.1f): \t",
(newEnergy[0] + newEnergy[1] + newEnergyL + newEnergyM <
lastEnergy[0] + lastEnergy[1] + lastEnergyL + lastEnergyM)
? "ACCEPT"
: "REJECT",
iteration, log10(lambda), incDirChange, stepsize);
printOptRes(newEnergy, newEnergyL, newEnergyM, 0, 0,
frameHessians.back()->aff_g2l().a,
frameHessians.back()->aff_g2l().b);
}
if (setting_forceAceptStep ||
(newEnergy[0] + newEnergy[1] + newEnergyL + newEnergyM <
lastEnergy[0] + lastEnergy[1] + lastEnergyL + lastEnergyM)) {
if (multiThreading)
treadReduce.reduce(boost::bind(&SODSOSystem::applyRes_Reductor, this,
true, _1, _2, _3, _4),
0, activeResiduals.size(), 50);
else
applyRes_Reductor(true, 0, activeResiduals.size(), 0, 0);
lastEnergy = newEnergy;
lastEnergyL = newEnergyL;
lastEnergyM = newEnergyM;
lambda *= 0.25;
} else {
loadSateBackup();
lastEnergy = linearizeAll(false);
lastEnergyL = calcLEnergy();
lastEnergyM = calcMEnergy();
lambda *= 1e2;
}
if (canbreak && iteration >= setting_minOptIterations)
break;
}
Vec10 newStateZero = Vec10::Zero();
newStateZero.segment<2>(6) = frameHessians.back()->get_state().segment<2>(6);
frameHessians.back()->setEvalPT(frameHessians.back()->PRE_worldToCam,
newStateZero);
EFDeltaValid = false;
EFAdjointsValid = false;
ef->setAdjointsF(&Hcalib);
setPrecalcValues();
lastEnergy = linearizeAll(true);
if (!std::isfinite((double)lastEnergy[0]) ||
!std::isfinite((double)lastEnergy[1]) ||
!std::isfinite((double)lastEnergy[2])) {
printf("KF Tracking failed: LOST!\n");
isLost = true;
}
statistics_lastFineTrackRMSE =
sqrtf((float)(lastEnergy[0] / (patternNum * ef->resInA)));
if (calibLog != 0) {
(*calibLog) << Hcalib.value_scaled.transpose() << " "
<< frameHessians.back()->get_state_scaled().transpose() << " "
<< sqrtf((float)(lastEnergy[0] / (patternNum * ef->resInA)))
<< " " << ef->resInM << "\n";
calibLog->flush();
}
{
boost::unique_lock<boost::mutex> crlock(shellPoseMutex);
for (FrameHessian *fh : frameHessians) {
fh->shell->camToWorld = fh->PRE_camToWorld;
fh->shell->aff_g2l = fh->aff_g2l();
}
}
debugPlotTracking();
return sqrtf((float)(lastEnergy[0] / (patternNum * ef->resInA)));
}
void SODSOSystem::solveSystem(int iteration, double lambda) {
ef->lastNullspaces_forLogging =
getNullspaces(ef->lastNullspaces_pose, ef->lastNullspaces_scale,
ef->lastNullspaces_affA, ef->lastNullspaces_affB);
ef->solveSystemF(iteration, lambda, &Hcalib);
}
double SODSOSystem::calcLEnergy() {
if (setting_forceAceptStep)
return 0;
double Ef = ef->calcLEnergyF_MT();
return Ef;
}
void SODSOSystem::removeOutliers() {
int numPointsDropped = 0;
for (FrameHessian *fh : frameHessians) {
for (unsigned int i = 0; i < fh->pointHessians.size(); i++) {
PointHessian *ph = fh->pointHessians[i];
if (ph == 0)
continue;
if (ph->residuals.size() == 0) {
fh->pointHessiansOut.push_back(ph);
ph->efPoint->stateFlag = EFPointStatus::PS_DROP;
fh->pointHessians[i] = fh->pointHessians.back();
fh->pointHessians.pop_back();
i--;
numPointsDropped++;
}
}
}
ef->dropPointsF();
}
std::vector<VecX> SODSOSystem::getNullspaces(
std::vector<VecX> &nullspaces_pose, std::vector<VecX> &nullspaces_scale,
std::vector<VecX> &nullspaces_affA, std::vector<VecX> &nullspaces_affB) {
nullspaces_pose.clear();
nullspaces_scale.clear();
nullspaces_affA.clear();
nullspaces_affB.clear();
int n = CPARS + frameHessians.size() * 8;
std::vector<VecX> nullspaces_x0_pre;
for (int i = 0; i < 6; i++) {
VecX nullspace_x0(n);
nullspace_x0.setZero();
for (FrameHessian *fh : frameHessians) {
nullspace_x0.segment<6>(CPARS + fh->idx * 8) = fh->nullspaces_pose.col(i);
nullspace_x0.segment<3>(CPARS + fh->idx * 8) *= SCALE_XI_TRANS_INVERSE;
nullspace_x0.segment<3>(CPARS + fh->idx * 8 + 3) *= SCALE_XI_ROT_INVERSE;
}
nullspaces_x0_pre.push_back(nullspace_x0);
nullspaces_pose.push_back(nullspace_x0);
}
for (int i = 0; i < 2; i++) {
VecX nullspace_x0(n);
nullspace_x0.setZero();
for (FrameHessian *fh : frameHessians) {
nullspace_x0.segment<2>(CPARS + fh->idx * 8 + 6) =
fh->nullspaces_affine.col(i).head<2>();
nullspace_x0[CPARS + fh->idx * 8 + 6] *= SCALE_A_INVERSE;
nullspace_x0[CPARS + fh->idx * 8 + 7] *= SCALE_B_INVERSE;
}
nullspaces_x0_pre.push_back(nullspace_x0);
if (i == 0)
nullspaces_affA.push_back(nullspace_x0);
if (i == 1)
nullspaces_affB.push_back(nullspace_x0);
}
VecX nullspace_x0(n);
nullspace_x0.setZero();
for (FrameHessian *fh : frameHessians) {
nullspace_x0.segment<6>(CPARS + fh->idx * 8) = fh->nullspaces_scale;
nullspace_x0.segment<3>(CPARS + fh->idx * 8) *= SCALE_XI_TRANS_INVERSE;
nullspace_x0.segment<3>(CPARS + fh->idx * 8 + 3) *= SCALE_XI_ROT_INVERSE;
}
nullspaces_x0_pre.push_back(nullspace_x0);
nullspaces_scale.push_back(nullspace_x0);
return nullspaces_x0_pre;
}
} // namespace dso
| 32.200351 | 80 | 0.608831 | IRVLab |
a642cde904b2653f803d611e619385f7517164af | 6,022 | cpp | C++ | src/signal_handler.cpp | MyersResearchGroup/ATACS | d6eeec63fbc53794f0376592e7357ad08a7dddd1 | [
"Apache-2.0"
] | 6 | 2017-03-10T14:55:45.000Z | 2021-09-10T10:44:21.000Z | src/signal_handler.cpp | MyersResearchGroup/ATACS | d6eeec63fbc53794f0376592e7357ad08a7dddd1 | [
"Apache-2.0"
] | 77 | 2016-11-07T08:44:57.000Z | 2018-07-11T03:19:13.000Z | src/signal_handler.cpp | MyersResearchGroup/ATACS | d6eeec63fbc53794f0376592e7357ad08a7dddd1 | [
"Apache-2.0"
] | 1 | 2021-09-10T10:44:22.000Z | 2021-09-10T10:44:22.000Z | ///////////////////////////////////////////////////////////////////////////////
// @name Timed Asynchronous Circuit Optimization
// @version 0.1 alpha
//
// (c)opyright 1997 by Eric G. Mercer
//
// @author Eric G. Mercer
//
// Permission to use, copy, modify and/or distribute, but not sell, this
// software and its documentation for any purpose is hereby granted
// without fee, subject to the following terms and conditions:
//
// 1. The above copyright notice and this permission notice must
// appear in all copies of the software and related documentation.
//
// 2. The name of University of Utah may not be used in advertising or
// publicity pertaining to distribution of the software without the
// specific, prior written permission of Univsersity of Utah.
//
// 3. This software may not be called "Taco" if it has been modified
// in any way, without the specific prior written permission of
// Eric G. Mercer
//
// 4. THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
// EXPRESS, IMPLIED, OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
// WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
//
// IN NO EVENT SHALL THE UNIVERSITY OF UTAH OR THE AUTHORS OF THIS
// SOFTWARE BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL
// DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
// DATA OR PROFITS, WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON
// ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE
// OR PERFORMANCE OF THIS SOFTWARE.
///////////////////////////////////////////////////////////////////////////////
#include <sys/types.h>
#include <signal.h>
#include <cassert>
#include <unistd.h>
#include "signal_handler.h"
///////////////////////////////////////////////////////////////////////////////
// This is really a simple interface function that is only required to call
// the gCtrl_C_mngr.raise() function, which will take care of returning
// control to the location of the last call of sigsetjmp(...). If there is
// no call to sigsetjmp(...), then the old signal handler will be raised by
// gCtrl_C_mngr.raise().
// NOTE: When other signal_manager are created, follow this function for a
// pattern.
///////////////////////////////////////////////////////////////////////////////
static void control_C_signal_handler( int ) {
gCtrl_C_mngr.raise();
}
///////////////////////////////////////////////////////////////////////////////
// gCtrl_C_mngr is the interrupt stack for the ^C SIGINT signal. This should
// be used by any program wishing to use SIGINT. The usage of this object
// is explained in the class definition.
///////////////////////////////////////////////////////////////////////////////
signal_manager gCtrl_C_mngr( SIGINT,
control_C_signal_handler );
///////////////////////////////////////////////////////////////////////////////
// base construction where signum is the value of the interupt to manage,
// and signal_hander is the function used as the handler. Both arguments
// should be very simply. See void control_C_signal_handler( int ) in
// and gControl_C_mngr in signal_handler.cpp for an example of how the
// constructor is used.
///////////////////////////////////////////////////////////////////////////////
signal_manager::signal_manager( int signum, signal_handler s )
: m_context(),
m_signum( signum ) {
assert( signum );
m_old_handler = signal( signum, s );
}
///////////////////////////////////////////////////////////////////////////////
// Destructor, reinstalls the old signal handler.
///////////////////////////////////////////////////////////////////////////////
signal_manager::~signal_manager() {
signal( m_signum, m_old_handler );
}
///////////////////////////////////////////////////////////////////////////////
// Returns a reference to a new entry on the stack. This is used with any
// call to the sigsetjmp( .. ) function. sigsetjmp() must be used so future
// interupts are saved in the process block.
///////////////////////////////////////////////////////////////////////////////
jmp_buf& signal_manager::new_entry() {
m_context.push( jmp_buf_shell() );
return( (m_context.top()).m_jmp );
}
///////////////////////////////////////////////////////////////////////////////
// raise() is called by the actual interupt handler to deal with an signal.
// This function does the following things:
// 1) If the stack is empty
// a) Install the old signal handler
// b) ::raise( signum ) ( Through the signal ).
// 2) Stack isn't empty so pop of the top of the stack.
// 3) Return program control to the jmp_buf from the stack with
// signum as the return value.
// siglongjmp(..) is used to preserve other interupt calls.
///////////////////////////////////////////////////////////////////////////////
void signal_manager::raise() {
if ( m_context.empty() ) {
signal( m_signum, m_old_handler );
kill( getpid(), m_signum );
return;
}
jmp_buf_shell j = m_context.top();
//siglongjmp( j.m_jmp, m_signum );
}
///////////////////////////////////////////////////////////////////////////////
// Pop the top entry off the stack.
// NOTE: Must always be called before leaving a function that has used
// sigsetjmp( signal_handler::new_entry() );
///////////////////////////////////////////////////////////////////////////////
void signal_manager::pop() {
if ( m_context.empty() )
return;
m_context.pop();
}
| 48.564516 | 79 | 0.505812 | MyersResearchGroup |
a643ec41c2ff3108dce42925e50ea6574d7938e2 | 49,919 | cpp | C++ | src/render/IrradianceCube.cpp | liuhongyi0101/SaturnRender | c6ec7ee39ef14749b09be4ae47f76613c71533cf | [
"MIT"
] | 2 | 2019-12-24T04:00:36.000Z | 2022-01-26T02:44:04.000Z | src/render/IrradianceCube.cpp | liuhongyi0101/SaturnRender | c6ec7ee39ef14749b09be4ae47f76613c71533cf | [
"MIT"
] | null | null | null | src/render/IrradianceCube.cpp | liuhongyi0101/SaturnRender | c6ec7ee39ef14749b09be4ae47f76613c71533cf | [
"MIT"
] | 2 | 2020-09-26T04:19:40.000Z | 2021-02-19T07:24:57.000Z | #include "renderer/IrradianceCube.h"
#include "utils/loadshader.h"
IrradianceCube::IrradianceCube(vks::VulkanDevice *vulkanDevice, VkCommandPool &cmdPool, std::shared_ptr<VertexDescriptions> &vdo_, vks::Model &skybox, VkQueue &queue)
{
this->vulkanDevice = vulkanDevice;
this->cmdPool = cmdPool;
this->vdo_ = vdo_;
this->skybox = skybox;
this->queue = queue;
this->device = vulkanDevice->logicalDevice;
}
IrradianceCube::~IrradianceCube()
{
}
VkCommandBuffer IrradianceCube::createCommandBuffer(VkCommandBufferLevel level, bool begin)
{
VkCommandBuffer cmdBuffer;
VkCommandBufferAllocateInfo cmdBufAllocateInfo =
vks::initializers::commandBufferAllocateInfo(
cmdPool,
level,
1);
VK_CHECK_RESULT(vkAllocateCommandBuffers(device, &cmdBufAllocateInfo, &cmdBuffer));
// If requested, also start the new command buffer
if (begin)
{
VkCommandBufferBeginInfo cmdBufInfo = vks::initializers::commandBufferBeginInfo();
VK_CHECK_RESULT(vkBeginCommandBuffer(cmdBuffer, &cmdBufInfo));
}
return cmdBuffer;
}
void IrradianceCube::flushCommandBuffer(VkCommandBuffer commandBuffer, VkQueue queue, bool free)
{
if (commandBuffer == VK_NULL_HANDLE)
{
return;
}
VK_CHECK_RESULT(vkEndCommandBuffer(commandBuffer));
VkSubmitInfo submitInfo = {};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffer;
VK_CHECK_RESULT(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE));
VK_CHECK_RESULT(vkQueueWaitIdle(queue));
if (free)
{
vkFreeCommandBuffers(device, cmdPool, 1, &commandBuffer);
}
}
void IrradianceCube::generateIrradianceCube(vks::TextureCubeMap &cubeMap)
{
auto tStart = std::chrono::high_resolution_clock::now();
const VkFormat format = VK_FORMAT_R32G32B32A32_SFLOAT;
const int32_t dim = 64;
const uint32_t numMips = static_cast<uint32_t>(floor(log2(dim))) + 1;
// Pre-filtered cube map
// Image
VkImageCreateInfo imageCI = vks::initializers::imageCreateInfo();
imageCI.imageType = VK_IMAGE_TYPE_2D;
imageCI.format = format;
imageCI.extent.width = dim;
imageCI.extent.height = dim;
imageCI.extent.depth = 1;
imageCI.mipLevels = numMips;
imageCI.arrayLayers = 6;
imageCI.samples = VK_SAMPLE_COUNT_1_BIT;
imageCI.tiling = VK_IMAGE_TILING_OPTIMAL;
imageCI.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
imageCI.flags = VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT;
VK_CHECK_RESULT(vkCreateImage(device, &imageCI, nullptr, &textures.irradianceCube.image));
VkMemoryAllocateInfo memAlloc = vks::initializers::memoryAllocateInfo();
VkMemoryRequirements memReqs;
vkGetImageMemoryRequirements(device, textures.irradianceCube.image, &memReqs);
memAlloc.allocationSize = memReqs.size;
memAlloc.memoryTypeIndex = vulkanDevice->getMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
VK_CHECK_RESULT(vkAllocateMemory(device, &memAlloc, nullptr, &textures.irradianceCube.deviceMemory));
VK_CHECK_RESULT(vkBindImageMemory(device, textures.irradianceCube.image, textures.irradianceCube.deviceMemory, 0));
// Image view
VkImageViewCreateInfo viewCI = vks::initializers::imageViewCreateInfo();
viewCI.viewType = VK_IMAGE_VIEW_TYPE_CUBE;
viewCI.format = format;
viewCI.subresourceRange = {};
viewCI.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
viewCI.subresourceRange.levelCount = numMips;
viewCI.subresourceRange.layerCount = 6;
viewCI.image = textures.irradianceCube.image;
VK_CHECK_RESULT(vkCreateImageView(device, &viewCI, nullptr, &textures.irradianceCube.view));
// Sampler
VkSamplerCreateInfo samplerCI = vks::initializers::samplerCreateInfo();
samplerCI.magFilter = VK_FILTER_LINEAR;
samplerCI.minFilter = VK_FILTER_LINEAR;
samplerCI.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
samplerCI.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
samplerCI.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
samplerCI.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
samplerCI.minLod = 0.0f;
samplerCI.maxLod = static_cast<float>(numMips);
samplerCI.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE;
VK_CHECK_RESULT(vkCreateSampler(device, &samplerCI, nullptr, &textures.irradianceCube.sampler));
textures.irradianceCube.descriptor.imageView = textures.irradianceCube.view;
textures.irradianceCube.descriptor.sampler = textures.irradianceCube.sampler;
textures.irradianceCube.descriptor.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
textures.irradianceCube.device = vulkanDevice;
// FB, Att, RP, Pipe, etc.
VkAttachmentDescription attDesc = {};
// Color attachment
attDesc.format = format;
attDesc.samples = VK_SAMPLE_COUNT_1_BIT;
attDesc.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attDesc.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
attDesc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attDesc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attDesc.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
attDesc.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkAttachmentReference colorReference = { 0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL };
VkSubpassDescription subpassDescription = {};
subpassDescription.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpassDescription.colorAttachmentCount = 1;
subpassDescription.pColorAttachments = &colorReference;
// Use subpass dependencies for layout transitions
std::array<VkSubpassDependency, 2> dependencies;
dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL;
dependencies[0].dstSubpass = 0;
dependencies[0].srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
dependencies[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependencies[0].srcAccessMask = VK_ACCESS_MEMORY_READ_BIT;
dependencies[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
dependencies[0].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT;
dependencies[1].srcSubpass = 0;
dependencies[1].dstSubpass = VK_SUBPASS_EXTERNAL;
dependencies[1].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependencies[1].dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
dependencies[1].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
dependencies[1].dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;
dependencies[1].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT;
// Renderpass
VkRenderPassCreateInfo renderPassCI = vks::initializers::renderPassCreateInfo();
renderPassCI.attachmentCount = 1;
renderPassCI.pAttachments = &attDesc;
renderPassCI.subpassCount = 1;
renderPassCI.pSubpasses = &subpassDescription;
renderPassCI.dependencyCount = 2;
renderPassCI.pDependencies = dependencies.data();
VkRenderPass renderpass;
VK_CHECK_RESULT(vkCreateRenderPass(device, &renderPassCI, nullptr, &renderpass));
struct {
VkImage image;
VkImageView view;
VkDeviceMemory memory;
VkFramebuffer framebuffer;
} offscreen;
// Offfscreen framebuffer
{
// Color attachment
VkImageCreateInfo imageCreateInfo = vks::initializers::imageCreateInfo();
imageCreateInfo.imageType = VK_IMAGE_TYPE_2D;
imageCreateInfo.format = format;
imageCreateInfo.extent.width = dim;
imageCreateInfo.extent.height = dim;
imageCreateInfo.extent.depth = 1;
imageCreateInfo.mipLevels = 1;
imageCreateInfo.arrayLayers = 1;
imageCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT;
imageCreateInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
imageCreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
imageCreateInfo.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
imageCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
VK_CHECK_RESULT(vkCreateImage(device, &imageCreateInfo, nullptr, &offscreen.image));
VkMemoryAllocateInfo memAlloc = vks::initializers::memoryAllocateInfo();
VkMemoryRequirements memReqs;
vkGetImageMemoryRequirements(device, offscreen.image, &memReqs);
memAlloc.allocationSize = memReqs.size;
memAlloc.memoryTypeIndex = vulkanDevice->getMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
VK_CHECK_RESULT(vkAllocateMemory(device, &memAlloc, nullptr, &offscreen.memory));
VK_CHECK_RESULT(vkBindImageMemory(device, offscreen.image, offscreen.memory, 0));
VkImageViewCreateInfo colorImageView = vks::initializers::imageViewCreateInfo();
colorImageView.viewType = VK_IMAGE_VIEW_TYPE_2D;
colorImageView.format = format;
colorImageView.flags = 0;
colorImageView.subresourceRange = {};
colorImageView.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
colorImageView.subresourceRange.baseMipLevel = 0;
colorImageView.subresourceRange.levelCount = 1;
colorImageView.subresourceRange.baseArrayLayer = 0;
colorImageView.subresourceRange.layerCount = 1;
colorImageView.image = offscreen.image;
VK_CHECK_RESULT(vkCreateImageView(device, &colorImageView, nullptr, &offscreen.view));
VkFramebufferCreateInfo fbufCreateInfo = vks::initializers::framebufferCreateInfo();
fbufCreateInfo.renderPass = renderpass;
fbufCreateInfo.attachmentCount = 1;
fbufCreateInfo.pAttachments = &offscreen.view;
fbufCreateInfo.width = dim;
fbufCreateInfo.height = dim;
fbufCreateInfo.layers = 1;
VK_CHECK_RESULT(vkCreateFramebuffer(device, &fbufCreateInfo, nullptr, &offscreen.framebuffer));
VkCommandBuffer layoutCmd = createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true);
vks::tools::setImageLayout(
layoutCmd,
offscreen.image,
VK_IMAGE_ASPECT_COLOR_BIT,
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
flushCommandBuffer(layoutCmd, queue, true);
}
// Descriptors
VkDescriptorSetLayout descriptorsetlayout;
std::vector<VkDescriptorSetLayoutBinding> setLayoutBindings = {
vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 0),
};
VkDescriptorSetLayoutCreateInfo descriptorsetlayoutCI = vks::initializers::descriptorSetLayoutCreateInfo(setLayoutBindings);
VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorsetlayoutCI, nullptr, &descriptorsetlayout));
// Descriptor Pool
std::vector<VkDescriptorPoolSize> poolSizes = { vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1) };
VkDescriptorPoolCreateInfo descriptorPoolCI = vks::initializers::descriptorPoolCreateInfo(poolSizes, 2);
VkDescriptorPool descriptorpool;
VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolCI, nullptr, &descriptorpool));
// Descriptor sets
VkDescriptorSet descriptorset;
VkDescriptorSetAllocateInfo allocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorpool, &descriptorsetlayout, 1);
VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorset));
VkWriteDescriptorSet writeDescriptorSet = vks::initializers::writeDescriptorSet(descriptorset, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, &cubeMap.descriptor);
vkUpdateDescriptorSets(device, 1, &writeDescriptorSet, 0, nullptr);
// Pipeline layout
struct PushBlock {
glm::mat4 mvp;
// Sampling deltas
float deltaPhi = (2.0f * float(M_PI)) / 180.0f;
float deltaTheta = (0.5f * float(M_PI)) / 64.0f;
} pushBlock;
VkPipelineLayout pipelinelayout;
std::vector<VkPushConstantRange> pushConstantRanges = {
vks::initializers::pushConstantRange(VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, sizeof(PushBlock), 0),
};
VkPipelineLayoutCreateInfo pipelineLayoutCI = vks::initializers::pipelineLayoutCreateInfo(&descriptorsetlayout, 1);
pipelineLayoutCI.pushConstantRangeCount = 1;
pipelineLayoutCI.pPushConstantRanges = pushConstantRanges.data();
VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pipelineLayoutCI, nullptr, &pipelinelayout));
// Pipeline
VkPipelineInputAssemblyStateCreateInfo inputAssemblyState = vks::initializers::pipelineInputAssemblyStateCreateInfo(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE);
VkPipelineRasterizationStateCreateInfo rasterizationState = vks::initializers::pipelineRasterizationStateCreateInfo(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE);
VkPipelineColorBlendAttachmentState blendAttachmentState = vks::initializers::pipelineColorBlendAttachmentState(0xf, VK_FALSE);
VkPipelineColorBlendStateCreateInfo colorBlendState = vks::initializers::pipelineColorBlendStateCreateInfo(1, &blendAttachmentState);
VkPipelineDepthStencilStateCreateInfo depthStencilState = vks::initializers::pipelineDepthStencilStateCreateInfo(VK_FALSE, VK_FALSE, VK_COMPARE_OP_LESS_OR_EQUAL);
VkPipelineViewportStateCreateInfo viewportState = vks::initializers::pipelineViewportStateCreateInfo(1, 1);
VkPipelineMultisampleStateCreateInfo multisampleState = vks::initializers::pipelineMultisampleStateCreateInfo(VK_SAMPLE_COUNT_1_BIT);
std::vector<VkDynamicState> dynamicStateEnables = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR };
VkPipelineDynamicStateCreateInfo dynamicState = vks::initializers::pipelineDynamicStateCreateInfo(dynamicStateEnables);
// Vertex input state
VkVertexInputBindingDescription vertexInputBinding = vks::initializers::vertexInputBindingDescription(0, vdo_->vertexLayout.stride(), VK_VERTEX_INPUT_RATE_VERTEX);
VkVertexInputAttributeDescription vertexInputAttribute = vks::initializers::vertexInputAttributeDescription(0, 0, VK_FORMAT_R32G32B32_SFLOAT, 0);
VkPipelineVertexInputStateCreateInfo vertexInputState = vks::initializers::pipelineVertexInputStateCreateInfo();
vertexInputState.vertexBindingDescriptionCount = 1;
vertexInputState.pVertexBindingDescriptions = &vertexInputBinding;
vertexInputState.vertexAttributeDescriptionCount = 1;
vertexInputState.pVertexAttributeDescriptions = &vertexInputAttribute;
std::array<VkPipelineShaderStageCreateInfo, 2> shaderStages;
VkGraphicsPipelineCreateInfo pipelineCI = vks::initializers::pipelineCreateInfo(pipelinelayout, renderpass);
pipelineCI.pInputAssemblyState = &inputAssemblyState;
pipelineCI.pRasterizationState = &rasterizationState;
pipelineCI.pColorBlendState = &colorBlendState;
pipelineCI.pMultisampleState = &multisampleState;
pipelineCI.pViewportState = &viewportState;
pipelineCI.pDepthStencilState = &depthStencilState;
pipelineCI.pDynamicState = &dynamicState;
pipelineCI.stageCount = 2;
pipelineCI.pStages = shaderStages.data();
pipelineCI.pVertexInputState = &vertexInputState;
pipelineCI.renderPass = renderpass;
shaderStages[0] = loadShader(getAssetPath + "/pbribl/filtercube.vert.spv", VK_SHADER_STAGE_VERTEX_BIT,device, shaderModules);
shaderStages[1] = loadShader(getAssetPath + "/pbribl/irradiancecube.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT,device, shaderModules);
VkPipeline pipeline;
VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, 0, 1, &pipelineCI, nullptr, &pipeline));
// Render
VkClearValue clearValues[1];
clearValues[0].color = { { 0.0f, 0.0f, 0.2f, 0.0f } };
VkRenderPassBeginInfo renderPassBeginInfo = vks::initializers::renderPassBeginInfo();
// Reuse render pass from example pass
renderPassBeginInfo.renderPass = renderpass;
renderPassBeginInfo.framebuffer = offscreen.framebuffer;
renderPassBeginInfo.renderArea.extent.width = dim;
renderPassBeginInfo.renderArea.extent.height = dim;
renderPassBeginInfo.clearValueCount = 1;
renderPassBeginInfo.pClearValues = clearValues;
std::vector<glm::mat4> matrices = {
// POSITIVE_X
glm::rotate(glm::rotate(glm::mat4(1.0f), glm::radians(90.0f), glm::vec3(0.0f, 1.0f, 0.0f)), glm::radians(180.0f), glm::vec3(1.0f, 0.0f, 0.0f)),
// NEGATIVE_X
glm::rotate(glm::rotate(glm::mat4(1.0f), glm::radians(-90.0f), glm::vec3(0.0f, 1.0f, 0.0f)), glm::radians(180.0f), glm::vec3(1.0f, 0.0f, 0.0f)),
// POSITIVE_Y
glm::rotate(glm::mat4(1.0f), glm::radians(-90.0f), glm::vec3(1.0f, 0.0f, 0.0f)),
// NEGATIVE_Y
glm::rotate(glm::mat4(1.0f), glm::radians(90.0f), glm::vec3(1.0f, 0.0f, 0.0f)),
// POSITIVE_Z
glm::rotate(glm::mat4(1.0f), glm::radians(180.0f), glm::vec3(1.0f, 0.0f, 0.0f)),
// NEGATIVE_Z
glm::rotate(glm::mat4(1.0f), glm::radians(180.0f), glm::vec3(0.0f, 0.0f, 1.0f)),
};
VkCommandBuffer cmdBuf = vulkanDevice->createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true);
VkViewport viewport = vks::initializers::viewport((float)dim, (float)dim, 0.0f, 1.0f);
VkRect2D scissor = vks::initializers::rect2D(dim, dim, 0, 0);
vkCmdSetViewport(cmdBuf, 0, 1, &viewport);
vkCmdSetScissor(cmdBuf, 0, 1, &scissor);
VkImageSubresourceRange subresourceRange = {};
subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
subresourceRange.baseMipLevel = 0;
subresourceRange.levelCount = numMips;
subresourceRange.layerCount = 6;
// Change image layout for all cubemap faces to transfer destination
vks::tools::setImageLayout(
cmdBuf,
textures.irradianceCube.image,
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
subresourceRange);
for (uint32_t m = 0; m < numMips; m++) {
for (uint32_t f = 0; f < 6; f++) {
viewport.width = static_cast<float>(dim * std::pow(0.5f, m));
viewport.height = static_cast<float>(dim * std::pow(0.5f, m));
vkCmdSetViewport(cmdBuf, 0, 1, &viewport);
// Render scene from cube face's point of view
vkCmdBeginRenderPass(cmdBuf, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
// Update shader push constant block
pushBlock.mvp = glm::perspective((float)(M_PI / 2.0), 1.0f, 0.1f, 512.0f) * matrices[f];
vkCmdPushConstants(cmdBuf, pipelinelayout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(PushBlock), &pushBlock);
vkCmdBindPipeline(cmdBuf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
vkCmdBindDescriptorSets(cmdBuf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelinelayout, 0, 1, &descriptorset, 0, NULL);
VkDeviceSize offsets[1] = { 0 };
vkCmdBindVertexBuffers(cmdBuf, 0, 1, &skybox.vertices.buffer, offsets);
vkCmdBindIndexBuffer(cmdBuf, skybox.indices.buffer, 0, VK_INDEX_TYPE_UINT32);
vkCmdDrawIndexed(cmdBuf, skybox.indexCount, 1, 0, 0, 0);
vkCmdEndRenderPass(cmdBuf);
vks::tools::setImageLayout(
cmdBuf,
offscreen.image,
VK_IMAGE_ASPECT_COLOR_BIT,
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
// Copy region for transfer from framebuffer to cube face
VkImageCopy copyRegion = {};
copyRegion.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
copyRegion.srcSubresource.baseArrayLayer = 0;
copyRegion.srcSubresource.mipLevel = 0;
copyRegion.srcSubresource.layerCount = 1;
copyRegion.srcOffset = { 0, 0, 0 };
copyRegion.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
copyRegion.dstSubresource.baseArrayLayer = f;
copyRegion.dstSubresource.mipLevel = m;
copyRegion.dstSubresource.layerCount = 1;
copyRegion.dstOffset = { 0, 0, 0 };
copyRegion.extent.width = static_cast<uint32_t>(viewport.width);
copyRegion.extent.height = static_cast<uint32_t>(viewport.height);
copyRegion.extent.depth = 1;
vkCmdCopyImage(
cmdBuf,
offscreen.image,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
textures.irradianceCube.image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1,
©Region);
// Transform framebuffer color attachment back
vks::tools::setImageLayout(
cmdBuf,
offscreen.image,
VK_IMAGE_ASPECT_COLOR_BIT,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
}
}
vks::tools::setImageLayout(
cmdBuf,
textures.irradianceCube.image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
subresourceRange);
vulkanDevice->flushCommandBuffer(cmdBuf, queue);
// todo: cleanup
vkDestroyRenderPass(device, renderpass, nullptr);
vkDestroyFramebuffer(device, offscreen.framebuffer, nullptr);
vkFreeMemory(device, offscreen.memory, nullptr);
vkDestroyImageView(device, offscreen.view, nullptr);
vkDestroyImage(device, offscreen.image, nullptr);
vkDestroyDescriptorPool(device, descriptorpool, nullptr);
vkDestroyDescriptorSetLayout(device, descriptorsetlayout, nullptr);
vkDestroyPipeline(device, pipeline, nullptr);
vkDestroyPipelineLayout(device, pipelinelayout, nullptr);
auto tEnd = std::chrono::high_resolution_clock::now();
auto tDiff = std::chrono::duration<double, std::milli>(tEnd - tStart).count();
std::cout << "Generating irradiance cube with " << numMips << " mip levels took " << tDiff << " ms" << std::endl;
}
void IrradianceCube::generatePrefilteredCube(vks::TextureCubeMap &cubeMap)
{
auto tStart = std::chrono::high_resolution_clock::now();
const VkFormat format = VK_FORMAT_R16G16B16A16_SFLOAT;
const int32_t dim = 512;
const uint32_t numMips = static_cast<uint32_t>(floor(log2(dim))) + 1;
// Pre-filtered cube map
// Image
VkImageCreateInfo imageCI = vks::initializers::imageCreateInfo();
imageCI.imageType = VK_IMAGE_TYPE_2D;
imageCI.format = format;
imageCI.extent.width = dim;
imageCI.extent.height = dim;
imageCI.extent.depth = 1;
imageCI.mipLevels = numMips;
imageCI.arrayLayers = 6;
imageCI.samples = VK_SAMPLE_COUNT_1_BIT;
imageCI.tiling = VK_IMAGE_TILING_OPTIMAL;
imageCI.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
imageCI.flags = VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT;
VK_CHECK_RESULT(vkCreateImage(device, &imageCI, nullptr, &textures.prefilteredCube.image));
VkMemoryAllocateInfo memAlloc = vks::initializers::memoryAllocateInfo();
VkMemoryRequirements memReqs;
vkGetImageMemoryRequirements(device, textures.prefilteredCube.image, &memReqs);
memAlloc.allocationSize = memReqs.size;
memAlloc.memoryTypeIndex = vulkanDevice->getMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
VK_CHECK_RESULT(vkAllocateMemory(device, &memAlloc, nullptr, &textures.prefilteredCube.deviceMemory));
VK_CHECK_RESULT(vkBindImageMemory(device, textures.prefilteredCube.image, textures.prefilteredCube.deviceMemory, 0));
// Image view
VkImageViewCreateInfo viewCI = vks::initializers::imageViewCreateInfo();
viewCI.viewType = VK_IMAGE_VIEW_TYPE_CUBE;
viewCI.format = format;
viewCI.subresourceRange = {};
viewCI.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
viewCI.subresourceRange.levelCount = numMips;
viewCI.subresourceRange.layerCount = 6;
viewCI.image = textures.prefilteredCube.image;
VK_CHECK_RESULT(vkCreateImageView(device, &viewCI, nullptr, &textures.prefilteredCube.view));
// Sampler
VkSamplerCreateInfo samplerCI = vks::initializers::samplerCreateInfo();
samplerCI.magFilter = VK_FILTER_LINEAR;
samplerCI.minFilter = VK_FILTER_LINEAR;
samplerCI.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
samplerCI.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
samplerCI.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
samplerCI.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
samplerCI.minLod = 0.0f;
samplerCI.maxLod = static_cast<float>(numMips);
samplerCI.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE;
VK_CHECK_RESULT(vkCreateSampler(device, &samplerCI, nullptr, &textures.prefilteredCube.sampler));
textures.prefilteredCube.descriptor.imageView = textures.prefilteredCube.view;
textures.prefilteredCube.descriptor.sampler = textures.prefilteredCube.sampler;
textures.prefilteredCube.descriptor.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
textures.prefilteredCube.device = vulkanDevice;
// FB, Att, RP, Pipe, etc.
VkAttachmentDescription attDesc = {};
// Color attachment
attDesc.format = format;
attDesc.samples = VK_SAMPLE_COUNT_1_BIT;
attDesc.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attDesc.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
attDesc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attDesc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attDesc.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
attDesc.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkAttachmentReference colorReference = { 0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL };
VkSubpassDescription subpassDescription = {};
subpassDescription.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpassDescription.colorAttachmentCount = 1;
subpassDescription.pColorAttachments = &colorReference;
// Use subpass dependencies for layout transitions
std::array<VkSubpassDependency, 2> dependencies;
dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL;
dependencies[0].dstSubpass = 0;
dependencies[0].srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
dependencies[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependencies[0].srcAccessMask = VK_ACCESS_MEMORY_READ_BIT;
dependencies[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
dependencies[0].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT;
dependencies[1].srcSubpass = 0;
dependencies[1].dstSubpass = VK_SUBPASS_EXTERNAL;
dependencies[1].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependencies[1].dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
dependencies[1].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
dependencies[1].dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;
dependencies[1].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT;
// Renderpass
VkRenderPassCreateInfo renderPassCI = vks::initializers::renderPassCreateInfo();
renderPassCI.attachmentCount = 1;
renderPassCI.pAttachments = &attDesc;
renderPassCI.subpassCount = 1;
renderPassCI.pSubpasses = &subpassDescription;
renderPassCI.dependencyCount = 2;
renderPassCI.pDependencies = dependencies.data();
VkRenderPass renderpass;
VK_CHECK_RESULT(vkCreateRenderPass(device, &renderPassCI, nullptr, &renderpass));
struct {
VkImage image;
VkImageView view;
VkDeviceMemory memory;
VkFramebuffer framebuffer;
} offscreen;
// Offfscreen framebuffer
{
// Color attachment
VkImageCreateInfo imageCreateInfo = vks::initializers::imageCreateInfo();
imageCreateInfo.imageType = VK_IMAGE_TYPE_2D;
imageCreateInfo.format = format;
imageCreateInfo.extent.width = dim;
imageCreateInfo.extent.height = dim;
imageCreateInfo.extent.depth = 1;
imageCreateInfo.mipLevels = 1;
imageCreateInfo.arrayLayers = 1;
imageCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT;
imageCreateInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
imageCreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
imageCreateInfo.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
imageCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
VK_CHECK_RESULT(vkCreateImage(device, &imageCreateInfo, nullptr, &offscreen.image));
VkMemoryAllocateInfo memAlloc = vks::initializers::memoryAllocateInfo();
VkMemoryRequirements memReqs;
vkGetImageMemoryRequirements(device, offscreen.image, &memReqs);
memAlloc.allocationSize = memReqs.size;
memAlloc.memoryTypeIndex = vulkanDevice->getMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
VK_CHECK_RESULT(vkAllocateMemory(device, &memAlloc, nullptr, &offscreen.memory));
VK_CHECK_RESULT(vkBindImageMemory(device, offscreen.image, offscreen.memory, 0));
VkImageViewCreateInfo colorImageView = vks::initializers::imageViewCreateInfo();
colorImageView.viewType = VK_IMAGE_VIEW_TYPE_2D;
colorImageView.format = format;
colorImageView.flags = 0;
colorImageView.subresourceRange = {};
colorImageView.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
colorImageView.subresourceRange.baseMipLevel = 0;
colorImageView.subresourceRange.levelCount = 1;
colorImageView.subresourceRange.baseArrayLayer = 0;
colorImageView.subresourceRange.layerCount = 1;
colorImageView.image = offscreen.image;
VK_CHECK_RESULT(vkCreateImageView(device, &colorImageView, nullptr, &offscreen.view));
VkFramebufferCreateInfo fbufCreateInfo = vks::initializers::framebufferCreateInfo();
fbufCreateInfo.renderPass = renderpass;
fbufCreateInfo.attachmentCount = 1;
fbufCreateInfo.pAttachments = &offscreen.view;
fbufCreateInfo.width = dim;
fbufCreateInfo.height = dim;
fbufCreateInfo.layers = 1;
VK_CHECK_RESULT(vkCreateFramebuffer(device, &fbufCreateInfo, nullptr, &offscreen.framebuffer));
VkCommandBuffer layoutCmd = createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true);
vks::tools::setImageLayout(
layoutCmd,
offscreen.image,
VK_IMAGE_ASPECT_COLOR_BIT,
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
flushCommandBuffer(layoutCmd, queue, true);
}
// Descriptors
VkDescriptorSetLayout descriptorsetlayout;
std::vector<VkDescriptorSetLayoutBinding> setLayoutBindings = {
vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 0),
};
VkDescriptorSetLayoutCreateInfo descriptorsetlayoutCI = vks::initializers::descriptorSetLayoutCreateInfo(setLayoutBindings);
VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorsetlayoutCI, nullptr, &descriptorsetlayout));
// Descriptor Pool
std::vector<VkDescriptorPoolSize> poolSizes = { vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1) };
VkDescriptorPoolCreateInfo descriptorPoolCI = vks::initializers::descriptorPoolCreateInfo(poolSizes, 2);
VkDescriptorPool descriptorpool;
VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolCI, nullptr, &descriptorpool));
// Descriptor sets
VkDescriptorSet descriptorset;
VkDescriptorSetAllocateInfo allocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorpool, &descriptorsetlayout, 1);
VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorset));
VkWriteDescriptorSet writeDescriptorSet = vks::initializers::writeDescriptorSet(descriptorset, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, &cubeMap.descriptor);
vkUpdateDescriptorSets(device, 1, &writeDescriptorSet, 0, nullptr);
// Pipeline layout
struct PushBlock {
glm::mat4 mvp;
float roughness;
uint32_t numSamples = 32u;
} pushBlock;
VkPipelineLayout pipelinelayout;
std::vector<VkPushConstantRange> pushConstantRanges = {
vks::initializers::pushConstantRange(VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, sizeof(PushBlock), 0),
};
VkPipelineLayoutCreateInfo pipelineLayoutCI = vks::initializers::pipelineLayoutCreateInfo(&descriptorsetlayout, 1);
pipelineLayoutCI.pushConstantRangeCount = 1;
pipelineLayoutCI.pPushConstantRanges = pushConstantRanges.data();
VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pipelineLayoutCI, nullptr, &pipelinelayout));
// Pipeline
VkPipelineInputAssemblyStateCreateInfo inputAssemblyState = vks::initializers::pipelineInputAssemblyStateCreateInfo(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE);
VkPipelineRasterizationStateCreateInfo rasterizationState = vks::initializers::pipelineRasterizationStateCreateInfo(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE);
VkPipelineColorBlendAttachmentState blendAttachmentState = vks::initializers::pipelineColorBlendAttachmentState(0xf, VK_FALSE);
VkPipelineColorBlendStateCreateInfo colorBlendState = vks::initializers::pipelineColorBlendStateCreateInfo(1, &blendAttachmentState);
VkPipelineDepthStencilStateCreateInfo depthStencilState = vks::initializers::pipelineDepthStencilStateCreateInfo(VK_FALSE, VK_FALSE, VK_COMPARE_OP_LESS_OR_EQUAL);
VkPipelineViewportStateCreateInfo viewportState = vks::initializers::pipelineViewportStateCreateInfo(1, 1);
VkPipelineMultisampleStateCreateInfo multisampleState = vks::initializers::pipelineMultisampleStateCreateInfo(VK_SAMPLE_COUNT_1_BIT);
std::vector<VkDynamicState> dynamicStateEnables = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR };
VkPipelineDynamicStateCreateInfo dynamicState = vks::initializers::pipelineDynamicStateCreateInfo(dynamicStateEnables);
// Vertex input state
VkVertexInputBindingDescription vertexInputBinding = vks::initializers::vertexInputBindingDescription(0, vdo_->vertexLayout.stride(), VK_VERTEX_INPUT_RATE_VERTEX);
VkVertexInputAttributeDescription vertexInputAttribute = vks::initializers::vertexInputAttributeDescription(0, 0, VK_FORMAT_R32G32B32_SFLOAT, 0);
VkPipelineVertexInputStateCreateInfo vertexInputState = vks::initializers::pipelineVertexInputStateCreateInfo();
vertexInputState.vertexBindingDescriptionCount = 1;
vertexInputState.pVertexBindingDescriptions = &vertexInputBinding;
vertexInputState.vertexAttributeDescriptionCount = 1;
vertexInputState.pVertexAttributeDescriptions = &vertexInputAttribute;
std::array<VkPipelineShaderStageCreateInfo, 2> shaderStages;
VkGraphicsPipelineCreateInfo pipelineCI = vks::initializers::pipelineCreateInfo(pipelinelayout, renderpass);
pipelineCI.pInputAssemblyState = &inputAssemblyState;
pipelineCI.pRasterizationState = &rasterizationState;
pipelineCI.pColorBlendState = &colorBlendState;
pipelineCI.pMultisampleState = &multisampleState;
pipelineCI.pViewportState = &viewportState;
pipelineCI.pDepthStencilState = &depthStencilState;
pipelineCI.pDynamicState = &dynamicState;
pipelineCI.stageCount = 2;
pipelineCI.pStages = shaderStages.data();
pipelineCI.pVertexInputState = &vertexInputState;
pipelineCI.renderPass = renderpass;
shaderStages[0] = loadShader(getAssetPath + "/pbribl/filtercube.vert.spv", VK_SHADER_STAGE_VERTEX_BIT, device, shaderModules);
shaderStages[1] = loadShader(getAssetPath + "/pbribl/prefilterenvmap.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT, device, shaderModules);
VkPipeline pipeline;
VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, 0, 1, &pipelineCI, nullptr, &pipeline));
// Render
VkClearValue clearValues[1];
clearValues[0].color = { { 0.0f, 0.0f, 0.2f, 0.0f } };
VkRenderPassBeginInfo renderPassBeginInfo = vks::initializers::renderPassBeginInfo();
// Reuse render pass from example pass
renderPassBeginInfo.renderPass = renderpass;
renderPassBeginInfo.framebuffer = offscreen.framebuffer;
renderPassBeginInfo.renderArea.extent.width = dim;
renderPassBeginInfo.renderArea.extent.height = dim;
renderPassBeginInfo.clearValueCount = 1;
renderPassBeginInfo.pClearValues = clearValues;
std::vector<glm::mat4> matrices = {
// POSITIVE_X
glm::rotate(glm::rotate(glm::mat4(1.0f), glm::radians(90.0f), glm::vec3(0.0f, 1.0f, 0.0f)), glm::radians(180.0f), glm::vec3(1.0f, 0.0f, 0.0f)),
// NEGATIVE_X
glm::rotate(glm::rotate(glm::mat4(1.0f), glm::radians(-90.0f), glm::vec3(0.0f, 1.0f, 0.0f)), glm::radians(180.0f), glm::vec3(1.0f, 0.0f, 0.0f)),
// POSITIVE_Y
glm::rotate(glm::mat4(1.0f), glm::radians(-90.0f), glm::vec3(1.0f, 0.0f, 0.0f)),
// NEGATIVE_Y
glm::rotate(glm::mat4(1.0f), glm::radians(90.0f), glm::vec3(1.0f, 0.0f, 0.0f)),
// POSITIVE_Z
glm::rotate(glm::mat4(1.0f), glm::radians(180.0f), glm::vec3(1.0f, 0.0f, 0.0f)),
// NEGATIVE_Z
glm::rotate(glm::mat4(1.0f), glm::radians(180.0f), glm::vec3(0.0f, 0.0f, 1.0f)),
};
VkCommandBuffer cmdBuf = vulkanDevice->createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true);
VkViewport viewport = vks::initializers::viewport((float)dim, (float)dim, 0.0f, 1.0f);
VkRect2D scissor = vks::initializers::rect2D(dim, dim, 0, 0);
vkCmdSetViewport(cmdBuf, 0, 1, &viewport);
vkCmdSetScissor(cmdBuf, 0, 1, &scissor);
VkImageSubresourceRange subresourceRange = {};
subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
subresourceRange.baseMipLevel = 0;
subresourceRange.levelCount = numMips;
subresourceRange.layerCount = 6;
// Change image layout for all cubemap faces to transfer destination
vks::tools::setImageLayout(
cmdBuf,
textures.prefilteredCube.image,
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
subresourceRange);
for (uint32_t m = 0; m < numMips; m++) {
pushBlock.roughness = (float)m / (float)(numMips - 1);
for (uint32_t f = 0; f < 6; f++) {
viewport.width = static_cast<float>(dim * std::pow(0.5f, m));
viewport.height = static_cast<float>(dim * std::pow(0.5f, m));
vkCmdSetViewport(cmdBuf, 0, 1, &viewport);
// Render scene from cube face's point of view
vkCmdBeginRenderPass(cmdBuf, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
// Update shader push constant block
pushBlock.mvp = glm::perspective((float)(M_PI / 2.0), 1.0f, 0.1f, 512.0f) * matrices[f];
vkCmdPushConstants(cmdBuf, pipelinelayout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(PushBlock), &pushBlock);
vkCmdBindPipeline(cmdBuf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
vkCmdBindDescriptorSets(cmdBuf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelinelayout, 0, 1, &descriptorset, 0, NULL);
VkDeviceSize offsets[1] = { 0 };
vkCmdBindVertexBuffers(cmdBuf, 0, 1, &skybox.vertices.buffer, offsets);
vkCmdBindIndexBuffer(cmdBuf, skybox.indices.buffer, 0, VK_INDEX_TYPE_UINT32);
vkCmdDrawIndexed(cmdBuf, skybox.indexCount, 1, 0, 0, 0);
vkCmdEndRenderPass(cmdBuf);
vks::tools::setImageLayout(
cmdBuf,
offscreen.image,
VK_IMAGE_ASPECT_COLOR_BIT,
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
// Copy region for transfer from framebuffer to cube face
VkImageCopy copyRegion = {};
copyRegion.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
copyRegion.srcSubresource.baseArrayLayer = 0;
copyRegion.srcSubresource.mipLevel = 0;
copyRegion.srcSubresource.layerCount = 1;
copyRegion.srcOffset = { 0, 0, 0 };
copyRegion.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
copyRegion.dstSubresource.baseArrayLayer = f;
copyRegion.dstSubresource.mipLevel = m;
copyRegion.dstSubresource.layerCount = 1;
copyRegion.dstOffset = { 0, 0, 0 };
copyRegion.extent.width = static_cast<uint32_t>(viewport.width);
copyRegion.extent.height = static_cast<uint32_t>(viewport.height);
copyRegion.extent.depth = 1;
vkCmdCopyImage(
cmdBuf,
offscreen.image,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
textures.prefilteredCube.image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1,
©Region);
// Transform framebuffer color attachment back
vks::tools::setImageLayout(
cmdBuf,
offscreen.image,
VK_IMAGE_ASPECT_COLOR_BIT,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
}
}
vks::tools::setImageLayout(
cmdBuf,
textures.prefilteredCube.image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
subresourceRange);
vulkanDevice->flushCommandBuffer(cmdBuf, queue);
// todo: cleanup
vkDestroyRenderPass(device, renderpass, nullptr);
vkDestroyFramebuffer(device, offscreen.framebuffer, nullptr);
vkFreeMemory(device, offscreen.memory, nullptr);
vkDestroyImageView(device, offscreen.view, nullptr);
vkDestroyImage(device, offscreen.image, nullptr);
vkDestroyDescriptorPool(device, descriptorpool, nullptr);
vkDestroyDescriptorSetLayout(device, descriptorsetlayout, nullptr);
vkDestroyPipeline(device, pipeline, nullptr);
vkDestroyPipelineLayout(device, pipelinelayout, nullptr);
auto tEnd = std::chrono::high_resolution_clock::now();
auto tDiff = std::chrono::duration<double, std::milli>(tEnd - tStart).count();
std::cout << "Generating pre-filtered enivornment cube with " << numMips << " mip levels took " << tDiff << " ms" << std::endl;
}
// Generate a BRDF integration map used as a look-up-table (stores roughness / NdotV)
void IrradianceCube::generateBRDFLUT(vks::TextureCubeMap &cubeMap)
{
auto tStart = std::chrono::high_resolution_clock::now();
const VkFormat format = VK_FORMAT_R16G16_SFLOAT; // R16G16 is supported pretty much everywhere
const int32_t dim = 512;
// Image
VkImageCreateInfo imageCI = vks::initializers::imageCreateInfo();
imageCI.imageType = VK_IMAGE_TYPE_2D;
imageCI.format = format;
imageCI.extent.width = dim;
imageCI.extent.height = dim;
imageCI.extent.depth = 1;
imageCI.mipLevels = 1;
imageCI.arrayLayers = 1;
imageCI.samples = VK_SAMPLE_COUNT_1_BIT;
imageCI.tiling = VK_IMAGE_TILING_OPTIMAL;
imageCI.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
VK_CHECK_RESULT(vkCreateImage(device, &imageCI, nullptr, &textures.lutBrdf.image));
VkMemoryAllocateInfo memAlloc = vks::initializers::memoryAllocateInfo();
VkMemoryRequirements memReqs;
vkGetImageMemoryRequirements(device, textures.lutBrdf.image, &memReqs);
memAlloc.allocationSize = memReqs.size;
memAlloc.memoryTypeIndex = vulkanDevice->getMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
VK_CHECK_RESULT(vkAllocateMemory(device, &memAlloc, nullptr, &textures.lutBrdf.deviceMemory));
VK_CHECK_RESULT(vkBindImageMemory(device, textures.lutBrdf.image, textures.lutBrdf.deviceMemory, 0));
// Image view
VkImageViewCreateInfo viewCI = vks::initializers::imageViewCreateInfo();
viewCI.viewType = VK_IMAGE_VIEW_TYPE_2D;
viewCI.format = format;
viewCI.subresourceRange = {};
viewCI.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
viewCI.subresourceRange.levelCount = 1;
viewCI.subresourceRange.layerCount = 1;
viewCI.image = textures.lutBrdf.image;
VK_CHECK_RESULT(vkCreateImageView(device, &viewCI, nullptr, &textures.lutBrdf.view));
// Sampler
VkSamplerCreateInfo samplerCI = vks::initializers::samplerCreateInfo();
samplerCI.magFilter = VK_FILTER_LINEAR;
samplerCI.minFilter = VK_FILTER_LINEAR;
samplerCI.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
samplerCI.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
samplerCI.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
samplerCI.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
samplerCI.minLod = 0.0f;
samplerCI.maxLod = 1.0f;
samplerCI.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE;
VK_CHECK_RESULT(vkCreateSampler(device, &samplerCI, nullptr, &textures.lutBrdf.sampler));
textures.lutBrdf.descriptor.imageView = textures.lutBrdf.view;
textures.lutBrdf.descriptor.sampler = textures.lutBrdf.sampler;
textures.lutBrdf.descriptor.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
textures.lutBrdf.device = vulkanDevice;
// FB, Att, RP, Pipe, etc.
VkAttachmentDescription attDesc = {};
// Color attachment
attDesc.format = format;
attDesc.samples = VK_SAMPLE_COUNT_1_BIT;
attDesc.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attDesc.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
attDesc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attDesc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attDesc.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
attDesc.finalLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
VkAttachmentReference colorReference = { 0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL };
VkSubpassDescription subpassDescription = {};
subpassDescription.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpassDescription.colorAttachmentCount = 1;
subpassDescription.pColorAttachments = &colorReference;
// Use subpass dependencies for layout transitions
std::array<VkSubpassDependency, 2> dependencies;
dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL;
dependencies[0].dstSubpass = 0;
dependencies[0].srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
dependencies[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependencies[0].srcAccessMask = VK_ACCESS_MEMORY_READ_BIT;
dependencies[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
dependencies[0].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT;
dependencies[1].srcSubpass = 0;
dependencies[1].dstSubpass = VK_SUBPASS_EXTERNAL;
dependencies[1].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependencies[1].dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
dependencies[1].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
dependencies[1].dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;
dependencies[1].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT;
// Create the actual renderpass
VkRenderPassCreateInfo renderPassCI = vks::initializers::renderPassCreateInfo();
renderPassCI.attachmentCount = 1;
renderPassCI.pAttachments = &attDesc;
renderPassCI.subpassCount = 1;
renderPassCI.pSubpasses = &subpassDescription;
renderPassCI.dependencyCount = 2;
renderPassCI.pDependencies = dependencies.data();
VkRenderPass renderpass;
VK_CHECK_RESULT(vkCreateRenderPass(device, &renderPassCI, nullptr, &renderpass));
VkFramebufferCreateInfo framebufferCI = vks::initializers::framebufferCreateInfo();
framebufferCI.renderPass = renderpass;
framebufferCI.attachmentCount = 1;
framebufferCI.pAttachments = &textures.lutBrdf.view;
framebufferCI.width = dim;
framebufferCI.height = dim;
framebufferCI.layers = 1;
VkFramebuffer framebuffer;
VK_CHECK_RESULT(vkCreateFramebuffer(device, &framebufferCI, nullptr, &framebuffer));
// Desriptors
VkDescriptorSetLayout descriptorsetlayout;
std::vector<VkDescriptorSetLayoutBinding> setLayoutBindings = {};
VkDescriptorSetLayoutCreateInfo descriptorsetlayoutCI = vks::initializers::descriptorSetLayoutCreateInfo(setLayoutBindings);
VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorsetlayoutCI, nullptr, &descriptorsetlayout));
// Descriptor Pool
std::vector<VkDescriptorPoolSize> poolSizes = { vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1) };
VkDescriptorPoolCreateInfo descriptorPoolCI = vks::initializers::descriptorPoolCreateInfo(poolSizes, 2);
VkDescriptorPool descriptorpool;
VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolCI, nullptr, &descriptorpool));
// Descriptor sets
VkDescriptorSet descriptorset;
VkDescriptorSetAllocateInfo allocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorpool, &descriptorsetlayout, 1);
VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorset));
// Pipeline layout
VkPipelineLayout pipelinelayout;
VkPipelineLayoutCreateInfo pipelineLayoutCI = vks::initializers::pipelineLayoutCreateInfo(&descriptorsetlayout, 1);
VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pipelineLayoutCI, nullptr, &pipelinelayout));
// Pipeline
VkPipelineInputAssemblyStateCreateInfo inputAssemblyState = vks::initializers::pipelineInputAssemblyStateCreateInfo(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE);
VkPipelineRasterizationStateCreateInfo rasterizationState = vks::initializers::pipelineRasterizationStateCreateInfo(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE);
VkPipelineColorBlendAttachmentState blendAttachmentState = vks::initializers::pipelineColorBlendAttachmentState(0xf, VK_FALSE);
VkPipelineColorBlendStateCreateInfo colorBlendState = vks::initializers::pipelineColorBlendStateCreateInfo(1, &blendAttachmentState);
VkPipelineDepthStencilStateCreateInfo depthStencilState = vks::initializers::pipelineDepthStencilStateCreateInfo(VK_FALSE, VK_FALSE, VK_COMPARE_OP_LESS_OR_EQUAL);
VkPipelineViewportStateCreateInfo viewportState = vks::initializers::pipelineViewportStateCreateInfo(1, 1);
VkPipelineMultisampleStateCreateInfo multisampleState = vks::initializers::pipelineMultisampleStateCreateInfo(VK_SAMPLE_COUNT_1_BIT);
std::vector<VkDynamicState> dynamicStateEnables = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR };
VkPipelineDynamicStateCreateInfo dynamicState = vks::initializers::pipelineDynamicStateCreateInfo(dynamicStateEnables);
VkPipelineVertexInputStateCreateInfo emptyInputState = vks::initializers::pipelineVertexInputStateCreateInfo();
std::array<VkPipelineShaderStageCreateInfo, 2> shaderStages;
VkGraphicsPipelineCreateInfo pipelineCI = vks::initializers::pipelineCreateInfo(pipelinelayout, renderpass);
pipelineCI.pInputAssemblyState = &inputAssemblyState;
pipelineCI.pRasterizationState = &rasterizationState;
pipelineCI.pColorBlendState = &colorBlendState;
pipelineCI.pMultisampleState = &multisampleState;
pipelineCI.pViewportState = &viewportState;
pipelineCI.pDepthStencilState = &depthStencilState;
pipelineCI.pDynamicState = &dynamicState;
pipelineCI.stageCount = 2;
pipelineCI.pStages = shaderStages.data();
pipelineCI.pVertexInputState = &emptyInputState;
// Look-up-table (from BRDF) pipeline
shaderStages[0] = loadShader(getAssetPath + "/pbribl/genbrdflut.vert.spv", VK_SHADER_STAGE_VERTEX_BIT, device, shaderModules);
shaderStages[1] = loadShader(getAssetPath + "/pbribl/genbrdflut.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT, device, shaderModules);
VkPipeline pipeline;
VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, 0, 1, &pipelineCI, nullptr, &pipeline));
// Render
VkClearValue clearValues[1];
clearValues[0].color = { { 0.0f, 0.0f, 0.0f, 1.0f } };
VkRenderPassBeginInfo renderPassBeginInfo = vks::initializers::renderPassBeginInfo();
renderPassBeginInfo.renderPass = renderpass;
renderPassBeginInfo.renderArea.extent.width = dim;
renderPassBeginInfo.renderArea.extent.height = dim;
renderPassBeginInfo.clearValueCount = 1;
renderPassBeginInfo.pClearValues = clearValues;
renderPassBeginInfo.framebuffer = framebuffer;
VkCommandBuffer cmdBuf = vulkanDevice->createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true);
vkCmdBeginRenderPass(cmdBuf, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
VkViewport viewport = vks::initializers::viewport((float)dim, (float)dim, 0.0f, 1.0f);
VkRect2D scissor = vks::initializers::rect2D(dim, dim, 0, 0);
vkCmdSetViewport(cmdBuf, 0, 1, &viewport);
vkCmdSetScissor(cmdBuf, 0, 1, &scissor);
vkCmdBindPipeline(cmdBuf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
vkCmdDraw(cmdBuf, 3, 1, 0, 0);
vkCmdEndRenderPass(cmdBuf);
vulkanDevice->flushCommandBuffer(cmdBuf, queue);
vkQueueWaitIdle(queue);
// todo: cleanup
vkDestroyPipeline(device, pipeline, nullptr);
vkDestroyPipelineLayout(device, pipelinelayout, nullptr);
vkDestroyRenderPass(device, renderpass, nullptr);
vkDestroyFramebuffer(device, framebuffer, nullptr);
vkDestroyDescriptorSetLayout(device, descriptorsetlayout, nullptr);
vkDestroyDescriptorPool(device, descriptorpool, nullptr);
auto tEnd = std::chrono::high_resolution_clock::now();
auto tDiff = std::chrono::duration<double, std::milli>(tEnd - tStart).count();
std::cout << "Generating BRDF LUT took " << tDiff << " ms" << std::endl;
} | 47.678128 | 191 | 0.809131 | liuhongyi0101 |
a644162d87e582ffc312ceca6f64e1dcc19b38cb | 2,547 | cpp | C++ | Source/ThirdParty/strtk/strtk/strtk_random_line.cpp | morrow1nd/ToyUtility | 0df3364a516de7a396b1cbb7975263506f41121d | [
"MIT"
] | null | null | null | Source/ThirdParty/strtk/strtk/strtk_random_line.cpp | morrow1nd/ToyUtility | 0df3364a516de7a396b1cbb7975263506f41121d | [
"MIT"
] | null | null | null | Source/ThirdParty/strtk/strtk/strtk_random_line.cpp | morrow1nd/ToyUtility | 0df3364a516de7a396b1cbb7975263506f41121d | [
"MIT"
] | null | null | null | /*
*****************************************************************
* String Toolkit Library *
* *
* Random Line Selection *
* Author: Arash Partow (2002-2018) *
* URL: http://www.partow.net/programming/strtk/index.html *
* *
* Copyright notice: *
* Free use of the String Toolkit Library is permitted under the *
* guidelines and in accordance with the most current version of *
* the MIT License. *
* http://www.opensource.org/licenses/MIT *
* *
*****************************************************************
*/
/*
Description: This is a solution to the problem of randomly selecting a line
from a text file in the most efficient way possible taking into
account time and space complexities, also ensuring that the
probability of the line selected is exactly 1/N where N is the
number of lines in the text file - It should be noted that the
lines can be of varying length.
*/
#include <cstddef>
#include <iostream>
#include <iterator>
#include <string>
#include <deque>
#include <ctime>
#include <boost/random.hpp>
//#include <random>
#include "strtk.hpp"
#ifndef strtk_enable_random
#error This example requires random
#endif
class random_line_selector
{
public:
random_line_selector(std::string& line, const std::size_t& seed = 0xA5A5A5A5)
: line_count_(1),
line_(line),
rng_(seed)
{}
inline void operator()(const std::string& s)
{
if (rng_() < (1.0 / line_count_))
line_ = s;
++line_count_;
}
private:
random_line_selector operator=(const random_line_selector&);
std::size_t line_count_; // should be long long
std::string& line_;
strtk::uniform_real_rng rng_;
};
int main(int argc, char* argv[])
{
if (2 != argc)
{
std::cout << "usage: strtk_random_line <file name>" << std::endl;
return 1;
}
std::string file_name = argv[1];
std::string line;
strtk::for_each_line(file_name,
random_line_selector(line,static_cast<std::size_t>(::time(0))));
std::cout << line << std::endl;
return 0;
}
| 28.3 | 88 | 0.506086 | morrow1nd |
a64481e6bc733eaebbb065b5395c64d06c293ac8 | 5,122 | cpp | C++ | tileconv/tilethreadpool_win32.cpp | Argent77/tileconv | b1b4479e7223d7d3cc0ffe17b86ada60f7fd0b0e | [
"MIT"
] | 1 | 2015-03-03T21:30:28.000Z | 2015-03-03T21:30:28.000Z | tileconv/tilethreadpool_win32.cpp | InfinityTools/tileconv | b1b4479e7223d7d3cc0ffe17b86ada60f7fd0b0e | [
"MIT"
] | 1 | 2015-05-11T09:26:14.000Z | 2015-05-11T09:26:14.000Z | tileconv/tilethreadpool_win32.cpp | Argent77/tileconv | b1b4479e7223d7d3cc0ffe17b86ada60f7fd0b0e | [
"MIT"
] | 1 | 2022-02-16T17:47:50.000Z | 2022-02-16T17:47:50.000Z | /*
Copyright (c) 2014 Argent77
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.
*/
#ifdef USE_WINTHREADS
#include "tilethreadpool_win32.h"
namespace tc {
unsigned getThreadPoolAutoThreads()
{
SYSTEM_INFO sysinfo;
::GetSystemInfo(&sysinfo);
return std::max(1u, (unsigned)sysinfo.dwNumberOfProcessors);
}
ThreadPoolPtr createThreadPool(int threadNum, int tileNum)
{
return ThreadPoolPtr(new TileThreadPoolWin32(threadNum, tileNum));
}
TileThreadPoolWin32::TileThreadPoolWin32(unsigned threadNum, unsigned tileNum) noexcept
: TileThreadPool(tileNum)
, m_activeThreads(0)
, m_mainThread(::GetCurrentThread())
, m_activeMutex(::CreateMutex(NULL, FALSE, NULL))
, m_tilesMutex(::CreateMutex(NULL, FALSE, NULL))
, m_resultsMutex(::CreateMutex(NULL, FALSE, NULL))
, m_threadsNum()
, m_threads(nullptr)
{
m_threadsNum = std::max(1u, std::min(MAX_THREADS, threadNum));
m_threads.reset(new HANDLE[m_threadsNum], std::default_delete<HANDLE[]>());
for (unsigned i = 0; i < threadNum; i++) {
m_threads.get()[i] = ::CreateThread(NULL, 0, TileThreadPoolWin32::threadMain, this, 0, NULL);
}
}
TileThreadPoolWin32::~TileThreadPoolWin32() noexcept
{
setTerminate(true);
::WaitForMultipleObjects(m_threadsNum, m_threads.get(), TRUE, INFINITE);
for (unsigned i = 0; i < m_threadsNum; i++) {
::CloseHandle(m_threads.get()[i]);
}
::CloseHandle(m_activeMutex);
::CloseHandle(m_tilesMutex);
::CloseHandle(m_resultsMutex);
}
void TileThreadPoolWin32::addTileData(TileDataPtr tileData) noexcept
{
while (!canAddTileData()) {
::Sleep(50);
}
::WaitForSingleObject(m_tilesMutex, INFINITE);
getTileQueue().emplace(tileData);
::ReleaseMutex(m_tilesMutex);
}
TileDataPtr TileThreadPoolWin32::getResult() noexcept
{
::WaitForSingleObject(m_resultsMutex, INFINITE);
if (!getResultQueue().empty()) {
TileDataPtr retVal = getResultQueue().top();
getResultQueue().pop();
::ReleaseMutex(m_resultsMutex);
return retVal;
} else {
::ReleaseMutex(m_resultsMutex);
return TileDataPtr(nullptr);
}
}
const TileDataPtr TileThreadPoolWin32::peekResult() noexcept
{
::WaitForSingleObject(m_resultsMutex, INFINITE);
if (!getResultQueue().empty()) {
TileDataPtr retVal = getResultQueue().top();
::ReleaseMutex(m_resultsMutex);
return retVal;
} else {
::ReleaseMutex(m_resultsMutex);
return TileDataPtr(nullptr);
}
}
void TileThreadPoolWin32::waitForResult() noexcept
{
while (!hasResult() && !finished()) {
::Sleep(50);
}
}
bool TileThreadPoolWin32::finished() noexcept
{
HANDLE locks[] = { m_tilesMutex, m_activeMutex, m_resultsMutex };
::WaitForMultipleObjects(3, locks, TRUE, INFINITE);
bool retVal = (getTileQueue().empty() && getActiveThreads() == 0 && getResultQueue().empty());
::ReleaseMutex(m_tilesMutex);
::ReleaseMutex(m_activeMutex);
::ReleaseMutex(m_resultsMutex);
return retVal;
}
DWORD WINAPI TileThreadPoolWin32::threadMain(LPVOID lpParam)
{
TileThreadPoolWin32 *instance = (TileThreadPoolWin32*)lpParam;
if (instance != nullptr) {
while (!instance->terminate()) {
::WaitForSingleObject(instance->m_tilesMutex, INFINITE);
if (!instance->getTileQueue().empty()) {
instance->threadActivated();
TileDataPtr tileData = instance->getTileQueue().front();
instance->getTileQueue().pop();
::ReleaseMutex(instance->m_tilesMutex);
(*tileData)();
// storing results
::WaitForSingleObject(instance->m_resultsMutex, INFINITE);
instance->getResultQueue().push(tileData);
::ReleaseMutex(instance->m_resultsMutex);
instance->threadDeactivated();
} else {
::ReleaseMutex(instance->m_tilesMutex);
::Sleep(50);
}
}
}
return 0;
}
void TileThreadPoolWin32::threadActivated() noexcept
{
::WaitForSingleObject(m_activeMutex, INFINITE);
m_activeThreads++;
::ReleaseMutex(m_activeMutex);
}
void TileThreadPoolWin32::threadDeactivated() noexcept
{
::WaitForSingleObject(m_activeMutex, INFINITE);
m_activeThreads--;
::ReleaseMutex(m_activeMutex);
}
} // namespace tc
#endif // USE_WINTHREADS
| 28.142857 | 97 | 0.725303 | Argent77 |
a64663dbf8ae42e897766e4041e3c73ef67e2b08 | 720 | hpp | C++ | test/AccuracyOutputCountTest.hpp | glabmoris/SBET-decoder | 17bddc8017d30be8ab90324f2f1b92417cddef87 | [
"MIT"
] | null | null | null | test/AccuracyOutputCountTest.hpp | glabmoris/SBET-decoder | 17bddc8017d30be8ab90324f2f1b92417cddef87 | [
"MIT"
] | null | null | null | test/AccuracyOutputCountTest.hpp | glabmoris/SBET-decoder | 17bddc8017d30be8ab90324f2f1b92417cddef87 | [
"MIT"
] | null | null | null | /*
* Copyright 2017 © Centre Interdisciplinaire de développement en Cartographie des Océans (CIDCO), Tous droits réservés
*/
/*
* File: AccuracyOutputCountTest.hpp
* Author: Hugo Valcourt
*
* Created on November 9, 2018
*/
#include "catch.hpp"
#include "../src/AccuracyProcessor.hpp"
//A simple printer class
class AccuracyPrinter : public AccuracyProcessor {
public:
unsigned int lines = 0;
AccuracyPrinter() {
}
void processEntry(AccuracyEntry * entry) {
lines++;
}
};
TEST_CASE(" AccuracyOutputCountTest ") {
std::string inputFile = "test/data/2018-07-11.sbet";
AccuracyPrinter accuracy;
accuracy.readFile(inputFile);
REQUIRE(accuracy.lines == 7296);
} | 18.947368 | 119 | 0.686111 | glabmoris |
a6492cd038b8462ce1d77d5d4e1154f9c8b953ff | 5,608 | cpp | C++ | lib/data.cpp | bkj/delphi | 14972e783551029ddf7db83961b73cf99c4c48e9 | [
"Apache-2.0"
] | null | null | null | lib/data.cpp | bkj/delphi | 14972e783551029ddf7db83961b73cf99c4c48e9 | [
"Apache-2.0"
] | null | null | null | lib/data.cpp | bkj/delphi | 14972e783551029ddf7db83961b73cf99c4c48e9 | [
"Apache-2.0"
] | null | null | null | #include "data.hpp"
#include "utils.hpp"
#include <fmt/format.h>
#include <sqlite3.h>
#include <chrono>
#include <range/v3/all.hpp>
#include <thread>
using namespace std;
vector<double> get_observations_for(string indicator,
string country,
string state,
string county,
int year,
int month,
string unit,
bool use_heuristic) {
using fmt::print;
using namespace fmt::literals;
sqlite3* db = nullptr;
vector<double> observations = {};
int rc;
rc = sqlite3_open(getenv("DELPHI_DB"), &db);
if (rc != SQLITE_OK) {
throw runtime_error("Could not open db. Do you have the DELPHI_DB "
"environment correctly set to point to the Delphi database?");
}
sqlite3_stmt* stmt = nullptr;
string query =
"select Unit, Value from indicator where `Variable` like '{}'"_format(
indicator);
string check_q;
if (!country.empty()) {
check_q = "{0} and `Country` is '{1}'"_format(query, country);
rc = sqlite3_prepare_v2(db, check_q.c_str(), -1, &stmt, NULL);
if (rc == SQLITE_OK) {
rc = sqlite3_step(stmt);
if (rc == SQLITE_ROW) {
query = check_q;
}
else {
print("Could not find data for country {0}. Averaging data over all "
"countries for given axes (Default Setting)\n",
country);
}
sqlite3_finalize(stmt);
stmt = nullptr;
}
}
if (!state.empty()) {
check_q = "{0} and `State` is '{1}'"_format(query, state);
rc = sqlite3_prepare_v2(db, check_q.c_str(), -1, &stmt, NULL);
rc = sqlite3_step(stmt);
if (rc == SQLITE_ROW) {
query = check_q;
}
else {
print("Could not find data for state {0}. Only obtaining data "
"of the country level (Default Setting)\n",
state);
}
sqlite3_finalize(stmt);
stmt = nullptr;
}
if (!county.empty()) {
check_q = "{0} and `County` is '{1}'"_format(query, county);
rc = sqlite3_prepare_v2(db, check_q.c_str(), -1, &stmt, NULL);
rc = sqlite3_step(stmt);
if (rc == SQLITE_ROW) {
query = check_q;
}
else {
print("Could not find data for county {0}. Only obtaining data "
"of the state level (Default Setting)\n",
county);
}
sqlite3_finalize(stmt);
stmt = nullptr;
}
if (!unit.empty()) {
check_q = "{0} and `Unit` is '{1}'"_format(query, unit);
rc = sqlite3_prepare_v2(db, check_q.c_str(), -1, &stmt, NULL);
rc = sqlite3_step(stmt);
if (rc == SQLITE_ROW) {
query = check_q;
}
else {
sqlite3_finalize(stmt);
stmt = nullptr;
print("Could not find data for unit {0}. Using first unit in "
"alphabetical order (Default Setting)\n",
unit);
vector<string> units;
rc = sqlite3_prepare_v2(db, query.c_str(), -1, &stmt, NULL);
while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
string ind_unit =
string(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0)));
units.push_back(ind_unit);
}
sqlite3_finalize(stmt);
stmt = nullptr;
if (!units.empty()) {
ranges::sort(units);
query = "{0} and `Unit` is '{1}'"_format(query, units.front());
}
else {
print("No units found for indicator {0}", indicator);
}
}
}
sqlite3_finalize(stmt);
stmt = nullptr;
if (!(year == -1)) {
check_q = "{0} and `Year` is '{1}'"_format(query, year);
rc = sqlite3_prepare_v2(db, check_q.c_str(), -1, &stmt, NULL);
rc = sqlite3_step(stmt);
if (rc == SQLITE_ROW) {
query = check_q;
}
else {
print("Could not find data for year {0}. Aggregating data "
"over all years (Default Setting)\n",
year);
}
sqlite3_finalize(stmt);
stmt = nullptr;
}
if (month != 0) {
check_q = "{0} and `Month` is '{1}'"_format(query, month);
rc = sqlite3_prepare_v2(db, check_q.c_str(), -1, &stmt, NULL);
rc = sqlite3_step(stmt);
if (rc == SQLITE_ROW) {
query = check_q;
}
else {
print("Could not find data for month {0}. Aggregating data "
"over all months (Default Setting)\n",
month);
}
sqlite3_finalize(stmt);
stmt = nullptr;
}
double observation;
rc = sqlite3_prepare_v2(db, query.c_str(), -1, &stmt, NULL);
while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
observation = sqlite3_column_double(stmt, 1);
observations.push_back(observation);
}
sqlite3_finalize(stmt);
stmt = nullptr;
if (observations.empty() and use_heuristic) {
string final_query =
"{0} and `Year` is '{1}' and `Month` is '0'"_format(query, year);
sqlite3_prepare_v2(db, final_query.c_str(), -1, &stmt, NULL);
while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
observation = sqlite3_column_double(stmt, 1);
// TODO: This math is only valid if the observation we query is an annual
// aggregate. For example if it is an yearly sample or an yearly average
// this is not correct. We need a more intelligent way to handle this
// situation.
observation = observation / 12;
observations.push_back(observation);
}
sqlite3_finalize(stmt);
stmt = nullptr;
}
rc = sqlite3_finalize(stmt);
rc = sqlite3_close(db);
stmt = nullptr;
db = nullptr;
return observations;
}
| 28.907216 | 80 | 0.570078 | bkj |
a64bf3427ecce34d37cc506c30e5465e6f223b8f | 2,706 | cpp | C++ | src/frame/frame_list.cpp | monopoldesign/M5Paper | 27c49dab9340a82d7bb6748383217e80f9b2ac31 | [
"MIT"
] | 1 | 2021-10-10T09:45:36.000Z | 2021-10-10T09:45:36.000Z | src/frame/frame_list.cpp | monopoldesign/M5Paper | 27c49dab9340a82d7bb6748383217e80f9b2ac31 | [
"MIT"
] | null | null | null | src/frame/frame_list.cpp | monopoldesign/M5Paper | 27c49dab9340a82d7bb6748383217e80f9b2ac31 | [
"MIT"
] | null | null | null | #include "frame_list.h"
#include "frame_list_menu.h"
#include "../epdgui/epdgui_button.h"
Frame_List::Frame_List(bool isHorizontal) : Frame_Base()
{
_frame_name = "Frame_List";
const uint16_t kKeyBaseY = 628;
key_run1 = new EPDGUI_Button("RUN1", 4, kKeyBaseY, 250, 52);
key_run2 = new EPDGUI_Button("RUN2", 286, kKeyBaseY, 250, 52);
inputbox1 = new EPDGUI_Textbox(4, 100, 532, 250);
inputbox1->SetState(EPDGUI_Textbox::EVENT_PRESSED);
inputbox1->SetTextSize(48);
inputbox2 = new EPDGUI_Textbox(4, 360, 532, 250);
inputbox2->SetState(EPDGUI_Textbox::EVENT_PRESSED);
inputbox2->SetTextSize(48);
keyboard = new EPDGUI_Keyboard(isHorizontal);
exitbtn("Home");
menubtn("Menu");
_canvas_title->drawString("Keyboard", 270, 34);
key_run1->AddArgs(EPDGUI_Button::EVENT_RELEASED, 0, (void *)inputbox1);
key_run1->Bind(EPDGUI_Button::EVENT_RELEASED, key_run_cb);
key_run2->AddArgs(EPDGUI_Button::EVENT_RELEASED, 0, (void *)inputbox2);
key_run2->Bind(EPDGUI_Button::EVENT_RELEASED, key_run_cb);
_key_exit->AddArgs(EPDGUI_Button::EVENT_RELEASED, 0, (void *)(&_is_run));
_key_exit->Bind(EPDGUI_Button::EVENT_RELEASED, &Frame_Base::exit_cb);
_key_menu->AddArgs(EPDGUI_Button::EVENT_RELEASED, 0, (void *)(&_is_run));
_key_menu->Bind(EPDGUI_Button::EVENT_RELEASED, showMenu);
}
Frame_List::~Frame_List(void)
{
delete inputbox1;
delete inputbox2;
delete keyboard;
delete _key_exit;
delete _key_menu;
delete key_run1;
delete key_run2;
}
int Frame_List::init(epdgui_args_vector_t &args)
{
_is_run = 1;
M5.EPD.Clear();
_canvas_title->pushCanvas(0, 8, UPDATE_MODE_NONE);
EPDGUI_AddObject(_key_exit);
EPDGUI_AddObject(_key_menu);
EPDGUI_AddObject(key_run1);
EPDGUI_AddObject(key_run2);
EPDGUI_AddObject(inputbox1);
EPDGUI_AddObject(inputbox2);
EPDGUI_AddObject(keyboard);
if (args.size() > 0)
{
String *result = (String*)(args[0]);
inputbox2->SetText("");
inputbox2->AddText(*result);
delete result;
args.pop_back();
}
else
{
inputbox1->SetText("");
inputbox2->SetText("");
}
return 6;
}
int Frame_List::run()
{
Frame_Base::run();
if (inputbox1->isSelected())
inputbox1->AddText(keyboard->getData());
else if (inputbox2->isSelected())
inputbox2->AddText(keyboard->getData());
return 1;
}
void Frame_List::key_run_cb(epdgui_args_vector_t &args)
{
((EPDGUI_Textbox*)(args[0]))->SetText("");
}
void Frame_List::showMenu(epdgui_args_vector_t &args)
{
Frame_Base *frame = EPDGUI_GetFrame("Frame_List_Menu");
if (frame == NULL)
{
frame = new Frame_List_Menu();
EPDGUI_AddFrame("Frame_List_Menu", frame);
}
EPDGUI_PushFrame(frame);
*((int*)(args[0])) = 0;
}
| 23.736842 | 77 | 0.708795 | monopoldesign |
a64cdf35625182747eace5440734c4bc9171c2d9 | 27,773 | cpp | C++ | crnlib/crn_ktx_texture.cpp | bmorel/crunch | 78b8a3f290e417f39cdda5d2b1355958303cfbdd | [
"Zlib"
] | null | null | null | crnlib/crn_ktx_texture.cpp | bmorel/crunch | 78b8a3f290e417f39cdda5d2b1355958303cfbdd | [
"Zlib"
] | null | null | null | crnlib/crn_ktx_texture.cpp | bmorel/crunch | 78b8a3f290e417f39cdda5d2b1355958303cfbdd | [
"Zlib"
] | null | null | null | // File: crn_ktx_texture.cpp
#include "crn_core.h"
#include "crn_ktx_texture.h"
#include "crn_console.h"
// Set #if CRNLIB_KTX_PVRTEX_WORKAROUNDS to 1 to enable various workarounds for oddball KTX files written by PVRTexTool.
#define CRNLIB_KTX_PVRTEX_WORKAROUNDS 1
namespace crnlib {
const uint8 s_ktx_file_id[12] = {0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A};
bool is_packed_pixel_ogl_type(uint32 ogl_type) {
switch (ogl_type) {
case KTX_UNSIGNED_BYTE_3_3_2:
case KTX_UNSIGNED_BYTE_2_3_3_REV:
case KTX_UNSIGNED_SHORT_5_6_5:
case KTX_UNSIGNED_SHORT_5_6_5_REV:
case KTX_UNSIGNED_SHORT_4_4_4_4:
case KTX_UNSIGNED_SHORT_4_4_4_4_REV:
case KTX_UNSIGNED_SHORT_5_5_5_1:
case KTX_UNSIGNED_SHORT_1_5_5_5_REV:
case KTX_UNSIGNED_INT_8_8_8_8:
case KTX_UNSIGNED_INT_8_8_8_8_REV:
case KTX_UNSIGNED_INT_10_10_10_2:
case KTX_UNSIGNED_INT_2_10_10_10_REV:
case KTX_UNSIGNED_INT_24_8:
case KTX_UNSIGNED_INT_10F_11F_11F_REV:
case KTX_UNSIGNED_INT_5_9_9_9_REV:
return true;
}
return false;
}
uint get_ogl_type_size(uint32 ogl_type) {
switch (ogl_type) {
case KTX_UNSIGNED_BYTE:
case KTX_BYTE:
return 1;
case KTX_HALF_FLOAT:
case KTX_UNSIGNED_SHORT:
case KTX_SHORT:
return 2;
case KTX_FLOAT:
case KTX_UNSIGNED_INT:
case KTX_INT:
return 4;
case KTX_UNSIGNED_BYTE_3_3_2:
case KTX_UNSIGNED_BYTE_2_3_3_REV:
return 1;
case KTX_UNSIGNED_SHORT_5_6_5:
case KTX_UNSIGNED_SHORT_5_6_5_REV:
case KTX_UNSIGNED_SHORT_4_4_4_4:
case KTX_UNSIGNED_SHORT_4_4_4_4_REV:
case KTX_UNSIGNED_SHORT_5_5_5_1:
case KTX_UNSIGNED_SHORT_1_5_5_5_REV:
return 2;
case KTX_UNSIGNED_INT_8_8_8_8:
case KTX_UNSIGNED_INT_8_8_8_8_REV:
case KTX_UNSIGNED_INT_10_10_10_2:
case KTX_UNSIGNED_INT_2_10_10_10_REV:
case KTX_UNSIGNED_INT_24_8:
case KTX_UNSIGNED_INT_10F_11F_11F_REV:
case KTX_UNSIGNED_INT_5_9_9_9_REV:
return 4;
}
return 0;
}
uint32 get_ogl_base_internal_fmt(uint32 ogl_fmt) {
switch (ogl_fmt) {
case KTX_ETC1_RGB8_OES:
case KTX_COMPRESSED_RGB8_ETC2:
case KTX_RGB_S3TC:
case KTX_RGB4_S3TC:
case KTX_COMPRESSED_RGB_S3TC_DXT1_EXT:
case KTX_COMPRESSED_SRGB_S3TC_DXT1_EXT:
return KTX_RGB;
case KTX_COMPRESSED_RGBA8_ETC2_EAC:
case KTX_COMPRESSED_RGBA_S3TC_DXT1_EXT:
case KTX_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:
case KTX_RGBA_S3TC:
case KTX_RGBA4_S3TC:
case KTX_COMPRESSED_RGBA_S3TC_DXT3_EXT:
case KTX_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT:
case KTX_COMPRESSED_RGBA_S3TC_DXT5_EXT:
case KTX_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:
case KTX_RGBA_DXT5_S3TC:
case KTX_RGBA4_DXT5_S3TC:
return KTX_RGBA;
case 1:
case KTX_RED:
case KTX_RED_INTEGER:
case KTX_GREEN:
case KTX_GREEN_INTEGER:
case KTX_BLUE:
case KTX_BLUE_INTEGER:
case KTX_R8:
case KTX_R8UI:
case KTX_LUMINANCE8:
case KTX_ALPHA:
case KTX_LUMINANCE:
case KTX_COMPRESSED_RED_RGTC1_EXT:
case KTX_COMPRESSED_SIGNED_RED_RGTC1_EXT:
case KTX_COMPRESSED_LUMINANCE_LATC1_EXT:
case KTX_COMPRESSED_SIGNED_LUMINANCE_LATC1_EXT:
return KTX_RED;
case 2:
case KTX_RG:
case KTX_RG8:
case KTX_RG_INTEGER:
case KTX_LUMINANCE_ALPHA:
case KTX_COMPRESSED_RED_GREEN_RGTC2_EXT:
case KTX_COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT:
case KTX_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT:
case KTX_COMPRESSED_SIGNED_LUMINANCE_ALPHA_LATC2_EXT:
return KTX_RG;
case 3:
case KTX_SRGB:
case KTX_RGB:
case KTX_RGB_INTEGER:
case KTX_BGR:
case KTX_BGR_INTEGER:
case KTX_RGB8:
case KTX_SRGB8:
return KTX_RGB;
case 4:
case KTX_RGBA:
case KTX_BGRA:
case KTX_RGBA_INTEGER:
case KTX_BGRA_INTEGER:
case KTX_SRGB_ALPHA:
case KTX_SRGB8_ALPHA8:
case KTX_RGBA8:
return KTX_RGBA;
}
return 0;
}
bool get_ogl_fmt_desc(uint32 ogl_fmt, uint32 ogl_type, uint& block_dim, uint& bytes_per_block) {
uint ogl_type_size = get_ogl_type_size(ogl_type);
block_dim = 1;
bytes_per_block = 0;
switch (ogl_fmt) {
case KTX_COMPRESSED_RED_RGTC1_EXT:
case KTX_COMPRESSED_SIGNED_RED_RGTC1_EXT:
case KTX_COMPRESSED_LUMINANCE_LATC1_EXT:
case KTX_COMPRESSED_SIGNED_LUMINANCE_LATC1_EXT:
case KTX_ETC1_RGB8_OES:
case KTX_COMPRESSED_RGB8_ETC2:
case KTX_RGB_S3TC:
case KTX_RGB4_S3TC:
case KTX_COMPRESSED_RGB_S3TC_DXT1_EXT:
case KTX_COMPRESSED_RGBA_S3TC_DXT1_EXT:
case KTX_COMPRESSED_SRGB_S3TC_DXT1_EXT:
case KTX_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: {
block_dim = 4;
bytes_per_block = 8;
break;
}
case KTX_COMPRESSED_RGBA8_ETC2_EAC:
case KTX_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT:
case KTX_COMPRESSED_SIGNED_LUMINANCE_ALPHA_LATC2_EXT:
case KTX_COMPRESSED_RED_GREEN_RGTC2_EXT:
case KTX_COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT:
case KTX_RGBA_S3TC:
case KTX_RGBA4_S3TC:
case KTX_COMPRESSED_RGBA_S3TC_DXT3_EXT:
case KTX_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT:
case KTX_COMPRESSED_RGBA_S3TC_DXT5_EXT:
case KTX_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:
case KTX_RGBA_DXT5_S3TC:
case KTX_RGBA4_DXT5_S3TC: {
block_dim = 4;
bytes_per_block = 16;
break;
}
case 1:
case KTX_ALPHA:
case KTX_RED:
case KTX_GREEN:
case KTX_BLUE:
case KTX_RED_INTEGER:
case KTX_GREEN_INTEGER:
case KTX_BLUE_INTEGER:
case KTX_LUMINANCE: {
bytes_per_block = ogl_type_size;
break;
}
case KTX_R8:
case KTX_R8UI:
case KTX_ALPHA8:
case KTX_LUMINANCE8: {
bytes_per_block = 1;
break;
}
case 2:
case KTX_RG:
case KTX_RG_INTEGER:
case KTX_LUMINANCE_ALPHA: {
bytes_per_block = 2 * ogl_type_size;
break;
}
case KTX_RG8:
case KTX_LUMINANCE8_ALPHA8: {
bytes_per_block = 2;
break;
}
case 3:
case KTX_SRGB:
case KTX_RGB:
case KTX_BGR:
case KTX_RGB_INTEGER:
case KTX_BGR_INTEGER: {
bytes_per_block = is_packed_pixel_ogl_type(ogl_type) ? ogl_type_size : (3 * ogl_type_size);
break;
}
case KTX_RGB8:
case KTX_SRGB8: {
bytes_per_block = 3;
break;
}
case 4:
case KTX_RGBA:
case KTX_BGRA:
case KTX_RGBA_INTEGER:
case KTX_BGRA_INTEGER:
case KTX_SRGB_ALPHA: {
bytes_per_block = is_packed_pixel_ogl_type(ogl_type) ? ogl_type_size : (4 * ogl_type_size);
break;
}
case KTX_SRGB8_ALPHA8:
case KTX_RGBA8: {
bytes_per_block = 4;
break;
}
default:
return false;
}
return true;
}
bool ktx_texture::compute_pixel_info() {
if ((!m_header.m_glType) || (!m_header.m_glFormat)) {
if ((m_header.m_glType) || (m_header.m_glFormat))
return false;
// Must be a compressed format.
if (!get_ogl_fmt_desc(m_header.m_glInternalFormat, m_header.m_glType, m_block_dim, m_bytes_per_block)) {
#if CRNLIB_KTX_PVRTEX_WORKAROUNDS
if ((!m_header.m_glInternalFormat) && (!m_header.m_glType) && (!m_header.m_glTypeSize) && (!m_header.m_glBaseInternalFormat)) {
// PVRTexTool writes bogus headers when outputting ETC1.
console::warning("ktx_texture::compute_pixel_info: Header doesn't specify any format, assuming ETC1 and hoping for the best");
m_header.m_glBaseInternalFormat = KTX_RGB;
m_header.m_glInternalFormat = KTX_ETC1_RGB8_OES;
m_header.m_glTypeSize = 1;
m_block_dim = 4;
m_bytes_per_block = 8;
return true;
}
#endif
return false;
}
if (m_block_dim == 1)
return false;
} else {
// Must be an uncompressed format.
if (!get_ogl_fmt_desc(m_header.m_glFormat, m_header.m_glType, m_block_dim, m_bytes_per_block))
return false;
if (m_block_dim > 1)
return false;
}
return true;
}
bool ktx_texture::read_from_stream(data_stream_serializer& serializer) {
clear();
// Read header
if (serializer.read(&m_header, 1, sizeof(m_header)) != sizeof(ktx_header))
return false;
// Check header
if (memcmp(s_ktx_file_id, m_header.m_identifier, sizeof(m_header.m_identifier)))
return false;
if ((m_header.m_endianness != KTX_OPPOSITE_ENDIAN) && (m_header.m_endianness != KTX_ENDIAN))
return false;
m_opposite_endianness = (m_header.m_endianness == KTX_OPPOSITE_ENDIAN);
if (m_opposite_endianness) {
m_header.endian_swap();
if ((m_header.m_glTypeSize != sizeof(uint8)) && (m_header.m_glTypeSize != sizeof(uint16)) && (m_header.m_glTypeSize != sizeof(uint32)))
return false;
}
if (!check_header())
return false;
if (!compute_pixel_info())
return false;
uint8 pad_bytes[3];
// Read the key value entries
uint num_key_value_bytes_remaining = m_header.m_bytesOfKeyValueData;
while (num_key_value_bytes_remaining) {
if (num_key_value_bytes_remaining < sizeof(uint32))
return false;
uint32 key_value_byte_size;
if (serializer.read(&key_value_byte_size, 1, sizeof(uint32)) != sizeof(uint32))
return false;
num_key_value_bytes_remaining -= sizeof(uint32);
if (m_opposite_endianness)
key_value_byte_size = utils::swap32(key_value_byte_size);
if (key_value_byte_size > num_key_value_bytes_remaining)
return false;
uint8_vec key_value_data;
if (key_value_byte_size) {
key_value_data.resize(key_value_byte_size);
if (serializer.read(&key_value_data[0], 1, key_value_byte_size) != key_value_byte_size)
return false;
}
m_key_values.push_back(key_value_data);
uint padding = 3 - ((key_value_byte_size + 3) % 4);
if (padding) {
if (serializer.read(pad_bytes, 1, padding) != padding)
return false;
}
num_key_value_bytes_remaining -= key_value_byte_size;
if (num_key_value_bytes_remaining < padding)
return false;
num_key_value_bytes_remaining -= padding;
}
// Now read the mip levels
uint total_faces = get_num_mips() * get_array_size() * get_num_faces() * get_depth();
if ((!total_faces) || (total_faces > 65535))
return false;
// See Section 2.8 of KTX file format: No rounding to block sizes should be applied for block compressed textures.
// OK, I'm going to break that rule otherwise KTX can only store a subset of textures that DDS can handle for no good reason.
#if 0
const uint mip0_row_blocks = m_header.m_pixelWidth / m_block_dim;
const uint mip0_col_blocks = CRNLIB_MAX(1, m_header.m_pixelHeight) / m_block_dim;
#else
const uint mip0_row_blocks = (m_header.m_pixelWidth + m_block_dim - 1) / m_block_dim;
const uint mip0_col_blocks = (CRNLIB_MAX(1, m_header.m_pixelHeight) + m_block_dim - 1) / m_block_dim;
#endif
if ((!mip0_row_blocks) || (!mip0_col_blocks))
return false;
bool has_valid_image_size_fields = true;
bool disable_mip_and_cubemap_padding = false;
#if CRNLIB_KTX_PVRTEX_WORKAROUNDS
{
// PVRTexTool has a bogus KTX writer that doesn't write any imageSize fields. Nice.
size_t expected_bytes_remaining = 0;
for (uint mip_level = 0; mip_level < get_num_mips(); mip_level++) {
uint mip_width, mip_height, mip_depth;
get_mip_dim(mip_level, mip_width, mip_height, mip_depth);
const uint mip_row_blocks = (mip_width + m_block_dim - 1) / m_block_dim;
const uint mip_col_blocks = (mip_height + m_block_dim - 1) / m_block_dim;
if ((!mip_row_blocks) || (!mip_col_blocks))
return false;
expected_bytes_remaining += sizeof(uint32);
if ((!m_header.m_numberOfArrayElements) && (get_num_faces() == 6)) {
for (uint face = 0; face < get_num_faces(); face++) {
uint slice_size = mip_row_blocks * mip_col_blocks * m_bytes_per_block;
expected_bytes_remaining += slice_size;
uint num_cube_pad_bytes = 3 - ((slice_size + 3) % 4);
expected_bytes_remaining += num_cube_pad_bytes;
}
} else {
uint total_mip_size = 0;
for (uint array_element = 0; array_element < get_array_size(); array_element++) {
for (uint face = 0; face < get_num_faces(); face++) {
for (uint zslice = 0; zslice < mip_depth; zslice++) {
uint slice_size = mip_row_blocks * mip_col_blocks * m_bytes_per_block;
total_mip_size += slice_size;
}
}
}
expected_bytes_remaining += total_mip_size;
uint num_mip_pad_bytes = 3 - ((total_mip_size + 3) % 4);
expected_bytes_remaining += num_mip_pad_bytes;
}
}
if (serializer.get_stream()->get_remaining() < expected_bytes_remaining) {
has_valid_image_size_fields = false;
disable_mip_and_cubemap_padding = true;
console::warning("ktx_texture::read_from_stream: KTX file size is smaller than expected - trying to read anyway without imageSize fields");
}
}
#endif
for (uint mip_level = 0; mip_level < get_num_mips(); mip_level++) {
uint mip_width, mip_height, mip_depth;
get_mip_dim(mip_level, mip_width, mip_height, mip_depth);
const uint mip_row_blocks = (mip_width + m_block_dim - 1) / m_block_dim;
const uint mip_col_blocks = (mip_height + m_block_dim - 1) / m_block_dim;
if ((!mip_row_blocks) || (!mip_col_blocks))
return false;
uint32 image_size = 0;
if (!has_valid_image_size_fields)
image_size = mip_depth * mip_row_blocks * mip_col_blocks * m_bytes_per_block * get_array_size() * get_num_faces();
else {
if (serializer.read(&image_size, 1, sizeof(image_size)) != sizeof(image_size))
return false;
if (m_opposite_endianness)
image_size = utils::swap32(image_size);
}
if (!image_size)
return false;
uint total_mip_size = 0;
if ((!m_header.m_numberOfArrayElements) && (get_num_faces() == 6)) {
// plain non-array cubemap
for (uint face = 0; face < get_num_faces(); face++) {
CRNLIB_ASSERT(m_image_data.size() == get_image_index(mip_level, 0, face, 0));
m_image_data.push_back(uint8_vec());
uint8_vec& image_data = m_image_data.back();
image_data.resize(image_size);
if (serializer.read(&image_data[0], 1, image_size) != image_size)
return false;
if (m_opposite_endianness)
utils::endian_swap_mem(&image_data[0], image_size, m_header.m_glTypeSize);
uint num_cube_pad_bytes = disable_mip_and_cubemap_padding ? 0 : (3 - ((image_size + 3) % 4));
if (serializer.read(pad_bytes, 1, num_cube_pad_bytes) != num_cube_pad_bytes)
return false;
total_mip_size += image_size + num_cube_pad_bytes;
}
} else {
// 1D, 2D, 3D (normal or array texture), or array cubemap
uint num_image_bytes_remaining = image_size;
for (uint array_element = 0; array_element < get_array_size(); array_element++) {
for (uint face = 0; face < get_num_faces(); face++) {
for (uint zslice = 0; zslice < mip_depth; zslice++) {
CRNLIB_ASSERT(m_image_data.size() == get_image_index(mip_level, array_element, face, zslice));
uint slice_size = mip_row_blocks * mip_col_blocks * m_bytes_per_block;
if ((!slice_size) || (slice_size > num_image_bytes_remaining))
return false;
m_image_data.push_back(uint8_vec());
uint8_vec& image_data = m_image_data.back();
image_data.resize(slice_size);
if (serializer.read(&image_data[0], 1, slice_size) != slice_size)
return false;
if (m_opposite_endianness)
utils::endian_swap_mem(&image_data[0], slice_size, m_header.m_glTypeSize);
num_image_bytes_remaining -= slice_size;
total_mip_size += slice_size;
}
}
}
if (num_image_bytes_remaining)
return false;
}
uint num_mip_pad_bytes = disable_mip_and_cubemap_padding ? 0 : (3 - ((total_mip_size + 3) % 4));
if (serializer.read(pad_bytes, 1, num_mip_pad_bytes) != num_mip_pad_bytes)
return false;
}
return true;
}
bool ktx_texture::write_to_stream(data_stream_serializer& serializer, bool no_keyvalue_data) {
if (!consistency_check()) {
CRNLIB_ASSERT(0);
return false;
}
memcpy(m_header.m_identifier, s_ktx_file_id, sizeof(m_header.m_identifier));
m_header.m_endianness = m_opposite_endianness ? KTX_OPPOSITE_ENDIAN : KTX_ENDIAN;
if (m_block_dim == 1) {
m_header.m_glTypeSize = get_ogl_type_size(m_header.m_glType);
m_header.m_glBaseInternalFormat = m_header.m_glFormat;
} else {
m_header.m_glBaseInternalFormat = get_ogl_base_internal_fmt(m_header.m_glInternalFormat);
}
m_header.m_bytesOfKeyValueData = 0;
if (!no_keyvalue_data) {
for (uint i = 0; i < m_key_values.size(); i++)
m_header.m_bytesOfKeyValueData += sizeof(uint32) + ((m_key_values[i].size() + 3) & ~3);
}
if (m_opposite_endianness)
m_header.endian_swap();
bool success = (serializer.write(&m_header, sizeof(m_header), 1) == 1);
if (m_opposite_endianness)
m_header.endian_swap();
if (!success)
return success;
uint total_key_value_bytes = 0;
const uint8 padding[3] = {0, 0, 0};
if (!no_keyvalue_data) {
for (uint i = 0; i < m_key_values.size(); i++) {
uint32 key_value_size = m_key_values[i].size();
if (m_opposite_endianness)
key_value_size = utils::swap32(key_value_size);
success = (serializer.write(&key_value_size, sizeof(key_value_size), 1) == 1);
total_key_value_bytes += sizeof(key_value_size);
if (m_opposite_endianness)
key_value_size = utils::swap32(key_value_size);
if (!success)
return false;
if (key_value_size) {
if (serializer.write(&m_key_values[i][0], key_value_size, 1) != 1)
return false;
total_key_value_bytes += key_value_size;
uint num_padding = 3 - ((key_value_size + 3) % 4);
if ((num_padding) && (serializer.write(padding, num_padding, 1) != 1))
return false;
total_key_value_bytes += num_padding;
}
}
(void)total_key_value_bytes;
}
CRNLIB_ASSERT(total_key_value_bytes == m_header.m_bytesOfKeyValueData);
for (uint mip_level = 0; mip_level < get_num_mips(); mip_level++) {
uint mip_width, mip_height, mip_depth;
get_mip_dim(mip_level, mip_width, mip_height, mip_depth);
const uint mip_row_blocks = (mip_width + m_block_dim - 1) / m_block_dim;
const uint mip_col_blocks = (mip_height + m_block_dim - 1) / m_block_dim;
if ((!mip_row_blocks) || (!mip_col_blocks))
return false;
uint32 image_size = mip_row_blocks * mip_col_blocks * m_bytes_per_block;
if ((m_header.m_numberOfArrayElements) || (get_num_faces() == 1))
image_size *= (get_array_size() * get_num_faces() * get_depth());
if (!image_size)
return false;
if (m_opposite_endianness)
image_size = utils::swap32(image_size);
success = (serializer.write(&image_size, sizeof(image_size), 1) == 1);
if (m_opposite_endianness)
image_size = utils::swap32(image_size);
if (!success)
return false;
uint total_mip_size = 0;
if ((!m_header.m_numberOfArrayElements) && (get_num_faces() == 6)) {
// plain non-array cubemap
for (uint face = 0; face < get_num_faces(); face++) {
const uint8_vec& image_data = get_image_data(get_image_index(mip_level, 0, face, 0));
if ((!image_data.size()) || (image_data.size() != image_size))
return false;
if (m_opposite_endianness) {
uint8_vec tmp_image_data(image_data);
utils::endian_swap_mem(&tmp_image_data[0], tmp_image_data.size(), m_header.m_glTypeSize);
if (serializer.write(&tmp_image_data[0], tmp_image_data.size(), 1) != 1)
return false;
} else if (serializer.write(&image_data[0], image_data.size(), 1) != 1)
return false;
uint num_cube_pad_bytes = 3 - ((image_data.size() + 3) % 4);
if ((num_cube_pad_bytes) && (serializer.write(padding, num_cube_pad_bytes, 1) != 1))
return false;
total_mip_size += image_size + num_cube_pad_bytes;
}
} else {
// 1D, 2D, 3D (normal or array texture), or array cubemap
for (uint array_element = 0; array_element < get_array_size(); array_element++) {
for (uint face = 0; face < get_num_faces(); face++) {
for (uint zslice = 0; zslice < mip_depth; zslice++) {
const uint8_vec& image_data = get_image_data(get_image_index(mip_level, array_element, face, zslice));
if (!image_data.size())
return false;
if (m_opposite_endianness) {
uint8_vec tmp_image_data(image_data);
utils::endian_swap_mem(&tmp_image_data[0], tmp_image_data.size(), m_header.m_glTypeSize);
if (serializer.write(&tmp_image_data[0], tmp_image_data.size(), 1) != 1)
return false;
} else if (serializer.write(&image_data[0], image_data.size(), 1) != 1)
return false;
total_mip_size += image_data.size();
}
}
}
uint num_mip_pad_bytes = 3 - ((total_mip_size + 3) % 4);
if ((num_mip_pad_bytes) && (serializer.write(padding, num_mip_pad_bytes, 1) != 1))
return false;
total_mip_size += num_mip_pad_bytes;
}
CRNLIB_ASSERT((total_mip_size & 3) == 0);
}
return true;
}
bool ktx_texture::init_2D(uint width, uint height, uint num_mips, uint32 ogl_internal_fmt, uint32 ogl_fmt, uint32 ogl_type) {
clear();
m_header.m_pixelWidth = width;
m_header.m_pixelHeight = height;
m_header.m_numberOfMipmapLevels = num_mips;
m_header.m_glInternalFormat = ogl_internal_fmt;
m_header.m_glFormat = ogl_fmt;
m_header.m_glType = ogl_type;
m_header.m_numberOfFaces = 1;
if (!compute_pixel_info())
return false;
return true;
}
bool ktx_texture::init_2D_array(uint width, uint height, uint num_mips, uint array_size, uint32 ogl_internal_fmt, uint32 ogl_fmt, uint32 ogl_type) {
clear();
m_header.m_pixelWidth = width;
m_header.m_pixelHeight = height;
m_header.m_numberOfMipmapLevels = num_mips;
m_header.m_numberOfArrayElements = array_size;
m_header.m_glInternalFormat = ogl_internal_fmt;
m_header.m_glFormat = ogl_fmt;
m_header.m_glType = ogl_type;
m_header.m_numberOfFaces = 1;
if (!compute_pixel_info())
return false;
return true;
}
bool ktx_texture::init_3D(uint width, uint height, uint depth, uint num_mips, uint32 ogl_internal_fmt, uint32 ogl_fmt, uint32 ogl_type) {
clear();
m_header.m_pixelWidth = width;
m_header.m_pixelHeight = height;
m_header.m_pixelDepth = depth;
m_header.m_numberOfMipmapLevels = num_mips;
m_header.m_glInternalFormat = ogl_internal_fmt;
m_header.m_glFormat = ogl_fmt;
m_header.m_glType = ogl_type;
m_header.m_numberOfFaces = 1;
if (!compute_pixel_info())
return false;
return true;
}
bool ktx_texture::init_cubemap(uint dim, uint num_mips, uint32 ogl_internal_fmt, uint32 ogl_fmt, uint32 ogl_type) {
clear();
m_header.m_pixelWidth = dim;
m_header.m_pixelHeight = dim;
m_header.m_numberOfMipmapLevels = num_mips;
m_header.m_glInternalFormat = ogl_internal_fmt;
m_header.m_glFormat = ogl_fmt;
m_header.m_glType = ogl_type;
m_header.m_numberOfFaces = 6;
if (!compute_pixel_info())
return false;
return true;
}
bool ktx_texture::check_header() const {
if (((get_num_faces() != 1) && (get_num_faces() != 6)) || (!m_header.m_pixelWidth))
return false;
if ((!m_header.m_pixelHeight) && (m_header.m_pixelDepth))
return false;
if ((get_num_faces() == 6) && ((m_header.m_pixelDepth) || (!m_header.m_pixelHeight)))
return false;
if (m_header.m_numberOfMipmapLevels) {
const uint max_mipmap_dimension = 1U << (m_header.m_numberOfMipmapLevels - 1U);
if (max_mipmap_dimension > (CRNLIB_MAX(CRNLIB_MAX(m_header.m_pixelWidth, m_header.m_pixelHeight), m_header.m_pixelDepth)))
return false;
}
return true;
}
bool ktx_texture::consistency_check() const {
if (!check_header())
return false;
uint block_dim = 0, bytes_per_block = 0;
if ((!m_header.m_glType) || (!m_header.m_glFormat)) {
if ((m_header.m_glType) || (m_header.m_glFormat))
return false;
if (!get_ogl_fmt_desc(m_header.m_glInternalFormat, m_header.m_glType, block_dim, bytes_per_block))
return false;
if (block_dim == 1)
return false;
//if ((get_width() % block_dim) || (get_height() % block_dim))
// return false;
} else {
if (!get_ogl_fmt_desc(m_header.m_glFormat, m_header.m_glType, block_dim, bytes_per_block))
return false;
if (block_dim > 1)
return false;
}
if ((m_block_dim != block_dim) || (m_bytes_per_block != bytes_per_block))
return false;
if (m_image_data.size() != get_total_images())
return false;
for (uint mip_level = 0; mip_level < get_num_mips(); mip_level++) {
uint mip_width, mip_height, mip_depth;
get_mip_dim(mip_level, mip_width, mip_height, mip_depth);
const uint mip_row_blocks = (mip_width + m_block_dim - 1) / m_block_dim;
const uint mip_col_blocks = (mip_height + m_block_dim - 1) / m_block_dim;
if ((!mip_row_blocks) || (!mip_col_blocks))
return false;
for (uint array_element = 0; array_element < get_array_size(); array_element++) {
for (uint face = 0; face < get_num_faces(); face++) {
for (uint zslice = 0; zslice < mip_depth; zslice++) {
const uint8_vec& image_data = get_image_data(get_image_index(mip_level, array_element, face, zslice));
uint expected_image_size = mip_row_blocks * mip_col_blocks * m_bytes_per_block;
if (image_data.size() != expected_image_size)
return false;
}
}
}
}
return true;
}
const uint8_vec* ktx_texture::find_key(const char* pKey) const {
const size_t n = strlen(pKey) + 1;
for (uint i = 0; i < m_key_values.size(); i++) {
const uint8_vec& v = m_key_values[i];
if ((v.size() >= n) && (!memcmp(&v[0], pKey, n)))
return &v;
}
return nullptr;
}
bool ktx_texture::get_key_value_as_string(const char* pKey, dynamic_string& str) const {
const uint8_vec* p = find_key(pKey);
if (!p) {
str.clear();
return false;
}
const uint ofs = (static_cast<uint>(strlen(pKey)) + 1);
const uint8* pValue = p->get_ptr() + ofs;
const uint n = p->size() - ofs;
uint i;
for (i = 0; i < n; i++)
if (!pValue[i])
break;
str.set_from_buf(pValue, i);
return true;
}
uint ktx_texture::add_key_value(const char* pKey, const void* pVal, uint val_size) {
const uint idx = m_key_values.size();
m_key_values.resize(idx + 1);
uint8_vec& v = m_key_values.back();
v.append(reinterpret_cast<const uint8*>(pKey), static_cast<uint>(strlen(pKey)) + 1);
v.append(static_cast<const uint8*>(pVal), val_size);
return idx;
}
} // namespace crnlib
| 33.261078 | 149 | 0.666259 | bmorel |
a64d3be7ac72675ba9c8e33676a3c3756eae54cb | 1,128 | hpp | C++ | AbstractFactory.hpp | ValtoLibraries/PUtils | f30ebf21416654743ad2a05b14974acd27257da8 | [
"MIT"
] | null | null | null | AbstractFactory.hpp | ValtoLibraries/PUtils | f30ebf21416654743ad2a05b14974acd27257da8 | [
"MIT"
] | null | null | null | AbstractFactory.hpp | ValtoLibraries/PUtils | f30ebf21416654743ad2a05b14974acd27257da8 | [
"MIT"
] | null | null | null | #pragma once
#include <memory>
#include <tuple>
#include "meta/type.hpp"
#include "meta/GenLinearHierarchy.hpp"
#include "runTests.hpp"
namespace putils {
// Abstract Factory inherits from this for each type in TList
template<typename T>
class AbstractFactoryUnit {
// Create a T
public:
virtual std::unique_ptr<T> makeImpl(pmeta::type<T>) noexcept = 0;
};
//
// AbstractFactory able to build any type in TList
// To implement a concrete factory, simply inherit from AbstractFactory
// and overload std::unique_ptr<T> make(pmeta::type<T>)
//
// To build an object of type T, use factory.make<T>()
//
template<typename ...Types>
class AbstractFactory : public pmeta::GenLinearHierarchy<AbstractFactoryUnit, Types...> {
// Make an object of type T by casting myself to the right AbstractFactoryUnit
public:
template<typename T>
std::unique_ptr<T> make() noexcept {
AbstractFactoryUnit<T> & unit = static_cast<AbstractFactoryUnit<T> &>(*this);
return unit.makeImpl(pmeta::type<T>());
}
};
}
| 30.486486 | 93 | 0.654255 | ValtoLibraries |
a64e43083ff408bf380c68a25f3c9c8ab5a75320 | 1,193 | hh | C++ | Exos/Serie04/poisson/simulation.hh | vkeller/math-454 | 0bf3a81214f094dbddec868d3d133986b31f4b01 | [
"BSD-2-Clause"
] | 1 | 2021-05-19T13:31:49.000Z | 2021-05-19T13:31:49.000Z | Exos/Serie05/poisson/simulation.hh | vkeller/math-454 | 0bf3a81214f094dbddec868d3d133986b31f4b01 | [
"BSD-2-Clause"
] | null | null | null | Exos/Serie05/poisson/simulation.hh | vkeller/math-454 | 0bf3a81214f094dbddec868d3d133986b31f4b01 | [
"BSD-2-Clause"
] | null | null | null | #ifndef SIMULATION_HH
#define SIMULATION_HH
/* -------------------------------------------------------------------------- */
#include "double_buffer.hh"
#include "dumpers.hh"
#include "grid.hh"
/* -------------------------------------------------------------------------- */
#include <tuple>
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
class Simulation {
public:
Simulation(int m, int n);
/// set the initial conditions, Dirichlet and source term
virtual void set_initial_conditions();
/// perform the simulation
std::tuple<float, int> compute();
/// access the precision
void set_epsilon(float epsilon);
float epsilon() const;
protected:
/// compute one step and return an error
virtual float compute_step();
private:
/// Global problem size
int m_global_m, m_global_n;
/// Precision to achieve
float m_epsilon;
/// grid spacing
float m_h_m;
float m_h_n;
/// Grids storage
DoubleBuffer m_grids;
/// source term
Grid m_f;
/// Dumper to use for outputs
std::unique_ptr<Dumper> m_dumper;
};
#endif /* SIMULATION_HH */
| 22.509434 | 80 | 0.511316 | vkeller |
a64e65567c46b7fb53a5795b932de4def851d6a5 | 3,909 | hpp | C++ | C64/src/Emulator/UnitTest/TestEmulator.hpp | vividos/OldStuff | dbfcce086d1101b576d99d25ef051efbd8dd117c | [
"BSD-2-Clause"
] | 1 | 2015-03-26T02:35:13.000Z | 2015-03-26T02:35:13.000Z | C64/src/Emulator/UnitTest/TestEmulator.hpp | vividos/OldStuff | dbfcce086d1101b576d99d25ef051efbd8dd117c | [
"BSD-2-Clause"
] | null | null | null | C64/src/Emulator/UnitTest/TestEmulator.hpp | vividos/OldStuff | dbfcce086d1101b576d99d25ef051efbd8dd117c | [
"BSD-2-Clause"
] | null | null | null | //
// Emulator - Simple C64 emulator
// Copyright (C) 2003-2016 Michael Fink
//
/// \file TestEmulator.hpp Emulator implementation for unit tests
//
#pragma once
// includes
#include "Machine.hpp"
#include "PC64File.hpp"
#include "PETASCIIString.hpp"
/// Emulator for unit tests
class TestEmulator :
public C64::Machine,
public C64::IProcessorCallback
{
public:
/// ctor
TestEmulator()
:m_bExit(false),
m_bTestResult(false)
{
GetProcessor().AddProcessorCallback(this);
}
/// dtor
~TestEmulator()
{
GetProcessor().RemoveProcessorCallback(this);
}
/// Loads test from path, with filename
bool LoadTest(LPCTSTR pszTestPath, LPCTSTR pszTestName)
{
CString cszFilename;
cszFilename.Format(_T("%s\\%s.p00"), pszTestPath, pszTestName);
C64::PC64File file(cszFilename);
if (!file.IsValid())
return false;
return file.Load(GetMemoryManager().GetRAM());
}
/// Runs test and checks if test executes OK
bool Run()
{
C64::Processor6510& proc = GetProcessor();
proc.SetDebugOutput(true);
// set IRQ handler
GetMemoryManager().Poke(0xfffe, 0x48);
GetMemoryManager().Poke(0xffff, 0xff);
// set stack pointer to a reasonable value
proc.SetRegister(C64::regSP, 0xff);
m_bExit = m_bTestResult = false;
for (; !m_bExit;)
{
// check if program wants to exit per RTS
/*
if (proc.GetRegister(C64::regSP) == 0xff &&
GetMemoryManager().Peek(proc.GetProgramCounter()) == C64::opRTS)
{
m_bExit = true;
break;
}
*/
proc.Step();
}
// create output string
std::string output = m_strOutput.ToString();
ATLTRACE(_T("%hs\n"), output.c_str());
// search output for string " - OK"
m_bTestResult = std::string::npos != output.find("- OK");
return m_bTestResult;
}
private:
/// called when program counter has changed
virtual void OnProgramCounterChange()
{
C64::Processor6510& proc = GetProcessor();
C64::MemoryManager& mem = GetMemoryManager();
WORD wPC = proc.GetProgramCounter();
switch (wPC)
{
case 0x0000: // indirect jump to $0000
case 0xe16f: // LOAD command
m_bExit = true;
break;
case 0xff48:
{
ATLTRACE(_T("KERNAL: IRQ Handler\n"));
proc.Push(proc.GetRegister(C64::regA)); // save A
proc.SetRegister(C64::regA, proc.GetRegister(C64::regX)); // save X
proc.Push(proc.GetRegister(C64::regA));
proc.SetRegister(C64::regA, proc.GetRegister(C64::regY)); // save Y
proc.Push(proc.GetRegister(C64::regA));
proc.SetRegister(C64::regX, proc.GetRegister(C64::regSP)); // get stack pointer
// load status register from stack
BYTE bSR = mem.Peek(0x0100 + ((proc.GetRegister(C64::regX) + 4) & 0xff));
// decide which type of interrupt
WORD wAddr = (bSR & 0x10) == 0 ? 0x0314 : 0x0316;
proc.SetProgramCounter(mem.Peek16(wAddr));
}
break;
case 0xffd2: // BSOUT
{
BYTE bRegA = proc.GetRegister(C64::regA);
if (bRegA != 0)
m_strOutput += bRegA;
proc.Return();
//ATLTRACE(_T("KERNAL: BSOUT: %c #$%02x\n"), bRegA < 0x20 ? _T('?') : bRegA, bRegA);
}
break;
case 0xffe4: // GETIN
ATLTRACE(_T("KERNAL: GETIN\n"));
proc.SetRegister(C64::regA, 0x3); // simulate keypress with code 3
proc.Return();
break;
default:
//ATLTRACE("test emulator changed PC to $%04x\n", wPC);
break;
}
}
private:
/// set to true when test can exit
bool m_bExit;
/// test result
bool m_bTestResult;
/// output as PETASCII string
C64::PETASCIIString m_strOutput;
};
| 25.383117 | 93 | 0.585828 | vividos |
a65080732f7156bd13a0c3cf3b38673cade613ce | 50,152 | cpp | C++ | tests/auto/datasync/TestAppServer/tst_appserver.cpp | wangyangyangisme/QtDataSync | 0cc47ca4e8aeee2683aae52662c40f1a7c7b1d93 | [
"BSD-3-Clause"
] | 1 | 2022-02-22T07:18:33.000Z | 2022-02-22T07:18:33.000Z | tests/auto/datasync/TestAppServer/tst_appserver.cpp | wyyrepo/QtDataSync | 0cc47ca4e8aeee2683aae52662c40f1a7c7b1d93 | [
"BSD-3-Clause"
] | null | null | null | tests/auto/datasync/TestAppServer/tst_appserver.cpp | wyyrepo/QtDataSync | 0cc47ca4e8aeee2683aae52662c40f1a7c7b1d93 | [
"BSD-3-Clause"
] | 1 | 2018-12-20T04:31:16.000Z | 2018-12-20T04:31:16.000Z | #include <QString>
#include <QtTest>
#include <QCoreApplication>
#include <QProcess>
#include <testlib.h>
#include <mockclient.h>
#ifdef Q_OS_UNIX
#include <sys/types.h>
#include <signal.h>
#elif Q_OS_WIN
#include <qt_windows.h>
#endif
#include <QtDataSync/private/identifymessage_p.h>
#include <QtDataSync/private/registermessage_p.h>
#include <QtDataSync/private/accountmessage_p.h>
#include <QtDataSync/private/loginmessage_p.h>
#include <QtDataSync/private/welcomemessage_p.h>
#include <QtDataSync/private/accessmessage_p.h>
#include <QtDataSync/private/proofmessage_p.h>
#include <QtDataSync/private/grantmessage_p.h>
#include <QtDataSync/private/macupdatemessage_p.h>
#include <QtDataSync/private/changemessage_p.h>
#include <QtDataSync/private/changedmessage_p.h>
#include <QtDataSync/private/syncmessage_p.h>
#include <QtDataSync/private/devicechangemessage_p.h>
#include <QtDataSync/private/keychangemessage_p.h>
#include <QtDataSync/private/devicekeysmessage_p.h>
#include <QtDataSync/private/newkeymessage_p.h>
#include <QtDataSync/private/devicesmessage_p.h>
#include <QtDataSync/private/removemessage_p.h>
using namespace QtDataSync;
Q_DECLARE_METATYPE(QSharedPointer<Message>)
class TestAppServer : public QObject
{
Q_OBJECT
private Q_SLOTS:
void initTestCase();
void cleanupTestCase();
void testStart();
void testInvalidVersion();
void testInvalidRegisterNonce();
void testInvalidRegisterSignature();
void testRegister();
void testInvalidLoginNonce();
void testInvalidLoginSignature();
void testInvalidLoginDevId();
void testLogin();
void testAddDevice();
void testInvalidAccessNonce();
void testInvalidAccessSignature();
void testDenyAddDevice();
void testOfflineAddDevice();
void testInvalidAcceptSignature();
void testAddDeviceInvalidKeyIndex();
void testSendDoubleAccept();
void testChangeUpload();
void testChangeDownloadOnLogin();
void testLiveChanges();
void testSyncCommand();
void testDeviceUploading();
void testChangeKey();
void testChangeKeyInvalidIndex();
void testChangeKeyDuplicate();
void testChangeKeyPendingChanges();
void testAddNewKeyInvalidIndex();
void testAddNewKeyInvalidSignature();
void testAddNewKeyPendingChanges();
void testKeyChangeNoAck();
void testListAndRemoveDevices();
void testUnexpectedMessage_data();
void testUnexpectedMessage();
void testUnknownMessage();
void testBrokenMessage();
#ifdef TEST_PING_MSG
void testPingMessages();
#endif
void testRemoveSelf();
void testStop();
private:
QProcess *server;
MockClient *client;
QString devName;
QUuid devId;
ClientCrypto *crypto;
MockClient *partner;
QString partnerName;
QUuid partnerDevId;
ClientCrypto *partnerCrypto;
void testAddDevice(MockClient *&partner, QUuid &partnerDevId, bool keepPartner = false);
void clean(bool disconnect = true);
void clean(MockClient *&client, bool disconnect = true);
template <typename TMessage, typename... Args>
inline QSharedPointer<Message> create(Args... args);
template <typename TMessage, typename... Args>
inline QSharedPointer<Message> createNonced(Args... args);
};
void TestAppServer::initTestCase()
{
#ifdef Q_OS_LINUX
if(!qgetenv("LD_PRELOAD").contains("Qt5DataSync"))
qWarning() << "No LD_PRELOAD set - this may fail on systems with multiple version of the modules";
#endif
QByteArray confPath { SETUP_FILE };
QVERIFY(QFile::exists(QString::fromUtf8(confPath)));
qputenv("QDSAPP_CONFIG_FILE", confPath);
#ifdef Q_OS_UNIX
QString binPath { QStringLiteral(BUILD_BIN_DIR "qdsappd") };
#elif Q_OS_WIN
QString binPath { QStringLiteral(BUILD_BIN_DIR "qdsappsvc") };
#else
QString binPath { QStringLiteral(BUILD_BIN_DIR "qdsapp") };
#endif
QVERIFY(QFile::exists(binPath));
server = new QProcess(this);
server->setProgram(binPath);
server->setProcessChannelMode(QProcess::ForwardedErrorChannel);
try {
client = nullptr;
devName = QStringLiteral("client");
crypto = new ClientCrypto(this);
crypto->generate(Setup::RSA_PSS_SHA3_512, 2048,
Setup::RSA_OAEP_SHA3_512, 2048);
partner = nullptr;
partnerName = QStringLiteral("partner");
partnerCrypto = new ClientCrypto(this);
partnerCrypto->generate(Setup::RSA_PSS_SHA3_512, 2048,
Setup::RSA_OAEP_SHA3_512, 2048);
} catch(std::exception &e) {
QFAIL(e.what());
}
}
void TestAppServer::cleanupTestCase()
{
clean();
clean(partner);
if(server->isOpen()) {
server->kill();
QVERIFY(server->waitForFinished(5000));
}
server->deleteLater();
}
void TestAppServer::testStart()
{
server->start();
QVERIFY(server->waitForStarted(5000));
QVERIFY(!server->waitForFinished(5000));
}
void TestAppServer::testInvalidVersion()
{
try {
//establish connection
client = new MockClient(this);
QVERIFY(client->waitForConnected());
//wait for identify message
QByteArray mNonce;
QVERIFY(client->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) {
QVERIFY(message.nonce.size() >= InitMessage::NonceSize);
QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion);
mNonce = message.nonce;
ok = true;
}));
//send back a register message with invalid version
RegisterMessage reply {
devName,
mNonce,
crypto->signKey(),
crypto->cryptKey(),
crypto,
"cmac"
};
reply.protocolVersion = QVersionNumber(0,5);
client->send(reply);
//wait for the error
QVERIFY(client->waitForError(ErrorMessage::IncompatibleVersionError));
clean();
} catch(std::exception &e) {
QFAIL(e.what());
}
}
void TestAppServer::testInvalidRegisterNonce()
{
try {
//establish connection
client = new MockClient(this);
QVERIFY(client->waitForConnected());
//wait for identify message
QVERIFY(client->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) {
QVERIFY(message.nonce.size() >= InitMessage::NonceSize);
QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion);
ok = true;
}));
//send back a register message with invalid nonce
client->send(RegisterMessage {
devName,
"not the original nonce, but still long enough to be considered one",
crypto->signKey(),
crypto->cryptKey(),
crypto,
"cmac"
});
//wait for the error
QVERIFY(client->waitForError(ErrorMessage::ClientError));
clean();
} catch(std::exception &e) {
QFAIL(e.what());
}
}
void TestAppServer::testInvalidRegisterSignature()
{
try {
//establish connection
client = new MockClient(this);
QVERIFY(client->waitForConnected());
//wait for identify message
QByteArray mNonce;
QVERIFY(client->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) {
QVERIFY(message.nonce.size() >= InitMessage::NonceSize);
QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion);
mNonce = message.nonce;
ok = true;
}));
//send back a register message with invalid signature
QByteArray sData = RegisterMessage {
devName,
mNonce,
crypto->signKey(),
crypto->cryptKey(),
crypto,
"cmac"
}.serializeSigned(crypto->privateSignKey(), crypto->rng(), crypto);
sData[sData.size() - 1] = sData[sData.size() - 1] + 'x';
client->sendBytes(sData); //message + fake signature
//wait for the error
QVERIFY(client->waitForError(ErrorMessage::AuthenticationError));
clean();
} catch(std::exception &e) {
QFAIL(e.what());
}
}
void TestAppServer::testRegister()
{
try {
//establish connection
client = new MockClient(this);
QVERIFY(client->waitForConnected());
//wait for identify message
QByteArray mNonce;
QVERIFY(client->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) {
QVERIFY(message.nonce.size() >= InitMessage::NonceSize);
QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion);
mNonce = message.nonce;
ok = true;
}));
//send back a valid register message
client->sendSigned(RegisterMessage {
devName,
mNonce,
crypto->signKey(),
crypto->cryptKey(),
crypto,
devId.toByteArray() //dummy cmac
}, crypto);
//wait for the account message
QVERIFY(client->waitForReply<AccountMessage>([&](AccountMessage message, bool &ok) {
devId = message.deviceId;
ok = true;
}));
clean();
} catch(std::exception &e) {
QFAIL(e.what());
}
}
void TestAppServer::testInvalidLoginNonce()
{
try {
//establish connection
client = new MockClient(this);
QVERIFY(client->waitForConnected());
//wait for identify message
QVERIFY(client->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) {
QVERIFY(message.nonce.size() >= InitMessage::NonceSize);
QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion);
ok = true;
}));
//send back a valid login message
client->sendSigned(LoginMessage {
devId,
devName,
"not the original nonce, but still long enough to be considered one",
}, crypto);
//wait for the error
QVERIFY(client->waitForError(ErrorMessage::ClientError));
clean();
} catch(std::exception &e) {
QFAIL(e.what());
}
}
void TestAppServer::testInvalidLoginSignature()
{
try {
//establish connection
client = new MockClient(this);
QVERIFY(client->waitForConnected());
//wait for identify message
QByteArray mNonce;
QVERIFY(client->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) {
QVERIFY(message.nonce.size() >= InitMessage::NonceSize);
QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion);
mNonce = message.nonce;
ok = true;
}));
//send back a valid login message
QByteArray sData = LoginMessage {
devId,
devName,
mNonce
}.serializeSigned(crypto->privateSignKey(), crypto->rng(), crypto);
sData[sData.size() - 1] = sData[sData.size() - 1] + 'x';
client->sendBytes(sData); //message + fake signature
//wait for the error
QVERIFY(client->waitForError(ErrorMessage::AuthenticationError));
clean();
} catch(std::exception &e) {
QFAIL(e.what());
}
}
void TestAppServer::testInvalidLoginDevId()
{
try {
//establish connection
client = new MockClient(this);
QVERIFY(client->waitForConnected());
//wait for identify message
QByteArray mNonce;
QVERIFY(client->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) {
QVERIFY(message.nonce.size() >= InitMessage::NonceSize);
QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion);
mNonce = message.nonce;
ok = true;
}));
//send back a valid login message
client->sendSigned(LoginMessage {
QUuid::createUuid(), //wrong devId
devName,
mNonce
}, crypto);
//wait for the error
QVERIFY(client->waitForError(ErrorMessage::AuthenticationError));
clean();
} catch(std::exception &e) {
QFAIL(e.what());
}
}
void TestAppServer::testLogin()
{
try {
//establish connection
client = new MockClient(this);
QVERIFY(client->waitForConnected());
//wait for identify message
QByteArray mNonce;
QVERIFY(client->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) {
QVERIFY(message.nonce.size() >= InitMessage::NonceSize);
QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion);
mNonce = message.nonce;
ok = true;
}));
//send back a valid login message
client->sendSigned(LoginMessage {
devId,
devName,
mNonce
}, crypto);
//wait for the account message
QVERIFY(client->waitForReply<WelcomeMessage>([&](WelcomeMessage message, bool &ok) {
QVERIFY(!message.hasChanges);
QCOMPARE(message.keyIndex, 0u);
QVERIFY(message.scheme.isNull());
QVERIFY(message.key.isNull());
QVERIFY(message.cmac.isNull());
ok = true;
}));
//keep session active
} catch(std::exception &e) {
QFAIL(e.what());
}
}
void TestAppServer::testAddDevice()
{
testAddDevice(partner, partnerDevId);
}
void TestAppServer::testAddDevice(MockClient *&partner, QUuid &partnerDevId, bool keepPartner) //not executed as test
{
QByteArray pNonce = "partner_nonce";
QByteArray macscheme = "macscheme";
QByteArray cmac = "cmac";
QByteArray trustmac = "trustmac";
quint32 keyIndex = 0;
QByteArray keyScheme = "keyScheme";
QByteArray keySecret = "keySecret";
try {
QVERIFY(client);
//establish connection
partner = new MockClient(this);
QVERIFY(partner->waitForConnected());
//wait for identify message
QByteArray mNonce;
QVERIFY(partner->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) {
QVERIFY(message.nonce.size() >= InitMessage::NonceSize);
QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion);
mNonce = message.nonce;
ok = true;
}));
//Send access message
partner->sendSigned(AccessMessage {
partnerName,
mNonce,
partnerCrypto->signKey(),
partnerCrypto->cryptKey(),
partnerCrypto,
pNonce,
devId,
macscheme,
cmac,
trustmac
}, partnerCrypto);
//wait for proof message on client
QVERIFY(client->waitForReply<ProofMessage>([&](ProofMessage message, bool &ok) {
QCOMPARE(message.pNonce, pNonce);
QVERIFY(!message.deviceId.isNull());
partnerDevId = message.deviceId;
QCOMPARE(message.deviceName, partnerName);
QCOMPARE(message.macscheme, macscheme);
QCOMPARE(message.cmac, cmac);
QCOMPARE(message.trustmac, trustmac);
AsymmetricCryptoInfo cInfo {crypto->rng(),
message.signAlgorithm,
message.signKey,
message.cryptAlgorithm,
message.cryptKey
};
QCOMPARE(cInfo.ownFingerprint(), partnerCrypto->ownFingerprint());
ok = true;
}));
//accept the proof
AcceptMessage accMsg { partnerDevId };
accMsg.index = keyIndex;
accMsg.scheme = keyScheme;
accMsg.secret = keySecret;
client->sendSigned(accMsg, crypto);
QVERIFY(client->waitForReply<AcceptAckMessage>([&](AcceptAckMessage message, bool &ok) {
QCOMPARE(message.deviceId, partnerDevId);
ok = true;
}));
//wait for granted
QVERIFY(partner->waitForReply<GrantMessage>([&](GrantMessage message, bool &ok) {
QCOMPARE(message.deviceId, partnerDevId);
QCOMPARE(message.index, keyIndex);
QCOMPARE(message.scheme, keyScheme);
QCOMPARE(message.secret, keySecret);
ok = true;
}));
//send mac update
partner->send(MacUpdateMessage {
keyIndex,
partnerDevId.toByteArray() //dummy cmac
});
//wait for mac ack
QVERIFY(partner->waitForReply<MacUpdateAckMessage>([&](MacUpdateAckMessage message, bool &ok) {
Q_UNUSED(message);
ok = true;
}));
if(!keepPartner)
clean(partner);
} catch(std::exception &e) {
QFAIL(e.what());
}
}
void TestAppServer::testInvalidAccessNonce()
{
try {
QVERIFY(client);
MockClient *partner = nullptr;
//use crypto and name from real partner
//establish connection
partner = new MockClient(this);
QVERIFY(partner->waitForConnected());
//wait for identify message
QVERIFY(partner->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) {
QVERIFY(message.nonce.size() >= InitMessage::NonceSize);
QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion);
ok = true;
}));
//Send access message
partner->sendSigned(AccessMessage {
partnerName,
"not the original nonce, but still long enough to be considered one",
partnerCrypto->signKey(),
partnerCrypto->cryptKey(),
partnerCrypto,
"pNonce",
devId,
"macscheme",
"cmac",
"trustmac"
}, partnerCrypto);
QVERIFY(partner->waitForError(ErrorMessage::ClientError));
clean(partner);
} catch(std::exception &e) {
QFAIL(e.what());
}
}
void TestAppServer::testInvalidAccessSignature()
{
try {
QVERIFY(client);
MockClient *partner = nullptr;
//use crypto and name from real partner
//establish connection
partner = new MockClient(this);
QVERIFY(partner->waitForConnected());
//wait for identify message
QByteArray mNonce;
QVERIFY(partner->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) {
QVERIFY(message.nonce.size() >= InitMessage::NonceSize);
QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion);
mNonce = message.nonce;
ok = true;
}));
//Send access message
QByteArray sData = AccessMessage {
partnerName,
mNonce,
partnerCrypto->signKey(),
partnerCrypto->cryptKey(),
partnerCrypto,
"pNonce",
devId,
"macscheme",
"cmac",
"trustmac"
}.serializeSigned(partnerCrypto->privateSignKey(), partnerCrypto->rng(), partnerCrypto);
sData[sData.size() - 1] = sData[sData.size() - 1] + 'x';
partner->sendBytes(sData); //message + fake signature
QVERIFY(partner->waitForError(ErrorMessage::AuthenticationError));
clean(partner);
} catch(std::exception &e) {
QFAIL(e.what());
}
}
void TestAppServer::testDenyAddDevice()
{
QByteArray pNonce = "partner_nonce";
QByteArray macscheme = "macscheme";
QByteArray cmac = "cmac";
QByteArray trustmac = "trustmac";
try {
QVERIFY(client);
MockClient *partner = nullptr;
QUuid partnerDevId;
//use crypto and name from real partner
//establish connection
partner = new MockClient(this);
QVERIFY(partner->waitForConnected());
//wait for identify message
QByteArray mNonce;
QVERIFY(partner->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) {
QVERIFY(message.nonce.size() >= InitMessage::NonceSize);
QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion);
mNonce = message.nonce;
ok = true;
}));
//Send access message
partner->sendSigned(AccessMessage {
partnerName,
mNonce,
partnerCrypto->signKey(),
partnerCrypto->cryptKey(),
partnerCrypto,
pNonce,
devId,
macscheme,
cmac,
trustmac
}, partnerCrypto);
//wait for proof message on client
QVERIFY(client->waitForReply<ProofMessage>([&](ProofMessage message, bool &ok) {
QCOMPARE(message.pNonce, pNonce);
QVERIFY(!message.deviceId.isNull());
partnerDevId = message.deviceId;
QCOMPARE(message.deviceName, partnerName);
QCOMPARE(message.macscheme, macscheme);
QCOMPARE(message.cmac, cmac);
QCOMPARE(message.trustmac, trustmac);
AsymmetricCryptoInfo cInfo {crypto->rng(),
message.signAlgorithm,
message.signKey,
message.cryptAlgorithm,
message.cryptKey
};
QCOMPARE(cInfo.ownFingerprint(), partnerCrypto->ownFingerprint());
ok = true;
}));
//accept the proof
client->send(DenyMessage { partnerDevId });
QVERIFY(partner->waitForError(ErrorMessage::AccessError));
clean(partner);
} catch(std::exception &e) {
QFAIL(e.what());
}
}
void TestAppServer::testOfflineAddDevice()
{
try {
QVERIFY(client);
clean(client);
MockClient *partner = nullptr;
//use crypto and name from real partner
//establish connection
partner = new MockClient(this);
QVERIFY(partner->waitForConnected());
//wait for identify message
QByteArray mNonce;
QVERIFY(partner->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) {
QVERIFY(message.nonce.size() >= InitMessage::NonceSize);
QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion);
mNonce = message.nonce;
ok = true;
}));
//Send access message for offline device
partner->sendSigned(AccessMessage {
partnerName,
mNonce,
partnerCrypto->signKey(),
partnerCrypto->cryptKey(),
partnerCrypto,
"pNonce",
devId,
"macscheme",
"cmac",
"trustmac"
}, partnerCrypto);
QVERIFY(partner->waitForError(ErrorMessage::AccessError));
clean(partner);
//reconnect main device
testLogin();
} catch(std::exception &e) {
QFAIL(e.what());
}
}
void TestAppServer::testInvalidAcceptSignature()
{
try {
QVERIFY(client);
//invalid accept
AcceptMessage accMsg { QUuid::createUuid() };
accMsg.index = 42;
accMsg.scheme = "keyScheme";
accMsg.secret = "keySecret";
auto sData = accMsg.serializeSigned(crypto->privateSignKey(), crypto->rng(), crypto);
sData[sData.size() - 1] = sData[sData.size() - 1] + 'x';
client->sendBytes(sData); //message + fake signature
QVERIFY(client->waitForError(ErrorMessage::AuthenticationError));
clean(client);
testLogin();
} catch(std::exception &e) {
QFAIL(e.what());
}
}
void TestAppServer::testAddDeviceInvalidKeyIndex()
{
QByteArray pNonce = "partner_nonce";
QByteArray macscheme = "macscheme";
QByteArray cmac = "cmac";
QByteArray trustmac = "trustmac";
quint32 keyIndex = 5; //fake key index
QByteArray keyScheme = "keyScheme";
QByteArray keySecret = "keySecret";
try {
QVERIFY(client);
MockClient *partner = nullptr;
QUuid partnerDevId;
//establish connection
partner = new MockClient(this);
QVERIFY(partner->waitForConnected());
//wait for identify message
QByteArray mNonce;
QVERIFY(partner->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) {
QVERIFY(message.nonce.size() >= InitMessage::NonceSize);
QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion);
mNonce = message.nonce;
ok = true;
}));
//Send access message
partner->sendSigned(AccessMessage {
partnerName,
mNonce,
partnerCrypto->signKey(),
partnerCrypto->cryptKey(),
partnerCrypto,
pNonce,
devId,
macscheme,
cmac,
trustmac
}, partnerCrypto);
//wait for proof message on client
QVERIFY(client->waitForReply<ProofMessage>([&](ProofMessage message, bool &ok) {
QCOMPARE(message.pNonce, pNonce);
QVERIFY(!message.deviceId.isNull());
partnerDevId = message.deviceId;
QCOMPARE(message.deviceName, partnerName);
QCOMPARE(message.macscheme, macscheme);
QCOMPARE(message.cmac, cmac);
QCOMPARE(message.trustmac, trustmac);
AsymmetricCryptoInfo cInfo {crypto->rng(),
message.signAlgorithm,
message.signKey,
message.cryptAlgorithm,
message.cryptKey
};
QCOMPARE(cInfo.ownFingerprint(), partnerCrypto->ownFingerprint());
ok = true;
}));
//accept the proof
AcceptMessage accMsg { partnerDevId };
accMsg.index = keyIndex;
accMsg.scheme = keyScheme;
accMsg.secret = keySecret;
client->sendSigned(accMsg, crypto);
QVERIFY(client->waitForReply<AcceptAckMessage>([&](AcceptAckMessage message, bool &ok) {
QCOMPARE(message.deviceId, partnerDevId);
ok = true;
}));
//wait for granted
QVERIFY(partner->waitForReply<GrantMessage>([&](GrantMessage message, bool &ok) {
QCOMPARE(message.deviceId, partnerDevId);
QCOMPARE(message.index, keyIndex);
QCOMPARE(message.scheme, keyScheme);
QCOMPARE(message.secret, keySecret);
ok = true;
}));
//send mac update
partner->send(MacUpdateMessage {
keyIndex,
partnerDevId.toByteArray() //dummy cmac
});
QVERIFY(partner->waitForError(ErrorMessage::KeyIndexError));
clean(partner);
} catch(std::exception &e) {
QFAIL(e.what());
}
}
void TestAppServer::testSendDoubleAccept()
{
QByteArray pNonce = "partner_nonce";
QByteArray macscheme = "macscheme";
QByteArray cmac = "cmac";
QByteArray trustmac = "trustmac";
quint32 keyIndex = 0;
QByteArray keyScheme = "keyScheme";
QByteArray keySecret = "keySecret";
try {
QVERIFY(client);
MockClient *partner = nullptr;
QUuid partnerDevId;
//establish connection
partner = new MockClient(this);
QVERIFY(partner->waitForConnected());
//wait for identify message
QByteArray mNonce;
QVERIFY(partner->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) {
QVERIFY(message.nonce.size() >= InitMessage::NonceSize);
QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion);
mNonce = message.nonce;
ok = true;
}));
//Send access message
partner->sendSigned(AccessMessage {
partnerName,
mNonce,
partnerCrypto->signKey(),
partnerCrypto->cryptKey(),
partnerCrypto,
pNonce,
devId,
macscheme,
cmac,
trustmac
}, partnerCrypto);
//wait for proof message on client
QVERIFY(client->waitForReply<ProofMessage>([&](ProofMessage message, bool &ok) {
QCOMPARE(message.pNonce, pNonce);
QVERIFY(!message.deviceId.isNull());
partnerDevId = message.deviceId;
QCOMPARE(message.deviceName, partnerName);
QCOMPARE(message.macscheme, macscheme);
QCOMPARE(message.cmac, cmac);
QCOMPARE(message.trustmac, trustmac);
AsymmetricCryptoInfo cInfo {crypto->rng(),
message.signAlgorithm,
message.signKey,
message.cryptAlgorithm,
message.cryptKey
};
QCOMPARE(cInfo.ownFingerprint(), partnerCrypto->ownFingerprint());
ok = true;
}));
//accept the proof
AcceptMessage accMsg { partnerDevId };
accMsg.index = keyIndex;
accMsg.scheme = keyScheme;
accMsg.secret = keySecret;
client->sendSigned(accMsg, crypto);
QVERIFY(client->waitForReply<AcceptAckMessage>([&](AcceptAckMessage message, bool &ok) {
QCOMPARE(message.deviceId, partnerDevId);
ok = true;
}));
//wait for granted
QVERIFY(partner->waitForReply<GrantMessage>([&](GrantMessage message, bool &ok) {
QCOMPARE(message.deviceId, partnerDevId);
QCOMPARE(message.index, keyIndex);
QCOMPARE(message.scheme, keyScheme);
QCOMPARE(message.secret, keySecret);
ok = true;
}));
//send mac update
partner->send(MacUpdateMessage {
keyIndex,
partnerDevId.toByteArray() //dummy cmac
});
//wait for mac ack
QVERIFY(partner->waitForReply<MacUpdateAckMessage>([&](MacUpdateAckMessage message, bool &ok) {
Q_UNUSED(message);
ok = true;
}));
//send another proof accept
client->sendSigned(accMsg, crypto);
QVERIFY(client->waitForNothing()); //no accept ack
QVERIFY(partner->waitForNothing()); //no grant
//clean partner
clean(partner);
} catch(std::exception &e) {
QFAIL(e.what());
}
}
void TestAppServer::testChangeUpload()
{
QByteArray dataId1 = "dataId1";
QByteArray dataId2 = "dataId2";
quint32 keyIndex = 0;
QByteArray salt = "salt";
QByteArray data = "data";
try {
QVERIFY(client);
QVERIFY(!partner);
//send an upload 1 and 2
ChangeMessage changeMsg { dataId1 };
changeMsg.keyIndex = keyIndex;
changeMsg.salt = salt;
changeMsg.data = data;
client->send(changeMsg);
changeMsg.dataId = dataId2;
client->send(changeMsg);
//wait for ack
QVERIFY(client->waitForReply<ChangeAckMessage>([&](ChangeAckMessage message, bool &ok) {
QCOMPARE(message.dataId, dataId1);
ok = true;
}));
QVERIFY(client->waitForReply<ChangeAckMessage>([&](ChangeAckMessage message, bool &ok) {
QCOMPARE(message.dataId, dataId2);
ok = true;
}));
//send 1 again
changeMsg.dataId = dataId1;
client->send(changeMsg);
//wait for ack
QVERIFY(client->waitForReply<ChangeAckMessage>([&](ChangeAckMessage message, bool &ok) {
QCOMPARE(message.dataId, dataId1);
ok = true;
}));
} catch(std::exception &e) {
QFAIL(e.what());
}
}
void TestAppServer::testChangeDownloadOnLogin()
{
quint32 keyIndex = 0;
QByteArray salt = "salt";
QByteArray data = "data";
try {
QVERIFY(client);
QVERIFY(!partner);
//establish connection
partner = new MockClient(this);
QVERIFY(partner->waitForConnected());
//wait for identify message
QByteArray mNonce;
QVERIFY(partner->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) {
QVERIFY(message.nonce.size() >= InitMessage::NonceSize);
QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion);
mNonce = message.nonce;
ok = true;
}));
//send back a valid login message
partner->sendSigned(LoginMessage {
partnerDevId,
partnerName,
mNonce
}, partnerCrypto);
//wait for the account message
QVERIFY(partner->waitForReply<WelcomeMessage>([&](WelcomeMessage message, bool &ok) {
QVERIFY(message.hasChanges);//Must have changes now
QCOMPARE(message.keyIndex, 0u);
QVERIFY(message.scheme.isNull());
QVERIFY(message.key.isNull());
QVERIFY(message.cmac.isNull());
ok = true;
}));
//wait for change info message
quint64 dataId1 = 0;
QVERIFY(partner->waitForReply<ChangedInfoMessage>([&](ChangedInfoMessage message, bool &ok) {
QCOMPARE(message.changeEstimate, 2u);
QCOMPARE(message.keyIndex, keyIndex);
QCOMPARE(message.salt, salt);
QCOMPARE(message.data, data);
dataId1 = message.dataIndex;
ok = true;
}));
//wait for the second message
quint64 dataId2 = 0;
QVERIFY(partner->waitForReply<ChangedMessage>([&](ChangedMessage message, bool &ok) {
QCOMPARE(message.keyIndex, keyIndex);
QCOMPARE(message.salt, salt);
QCOMPARE(message.data, data);
dataId2 = message.dataIndex;
ok = true;
}));
//send the first ack
partner->send(ChangedAckMessage { dataId1 });
QVERIFY(partner->waitForNothing());
//send second ack
partner->send(ChangedAckMessage { dataId2 });
QVERIFY(partner->waitForReply<LastChangedMessage>([&](LastChangedMessage message, bool &ok) {
Q_UNUSED(message)
ok = true;
}));
} catch(std::exception &e) {
QFAIL(e.what());
}
}
void TestAppServer::testLiveChanges()
{
QByteArray dataId1 = "dataId3";
quint32 keyIndex = 0;
QByteArray salt = "salt";
QByteArray data = "data";
try {
QVERIFY(client);
QVERIFY(partner);
//send an upload
ChangeMessage changeMsg { dataId1 };
changeMsg.keyIndex = keyIndex;
changeMsg.salt = salt;
changeMsg.data = data;
client->send(changeMsg);
//wait for ack
QVERIFY(client->waitForReply<ChangeAckMessage>([&](ChangeAckMessage message, bool &ok) {
QCOMPARE(message.dataId, dataId1);
ok = true;
}));
//wait for change info message
quint64 dataId2 = 0;
QVERIFY(partner->waitForReply<ChangedInfoMessage>([&](ChangedInfoMessage message, bool &ok) {
QCOMPARE(message.changeEstimate, 1u);
QCOMPARE(message.keyIndex, keyIndex);
QCOMPARE(message.salt, salt);
QCOMPARE(message.data, data);
dataId2 = message.dataIndex;
ok = true;
}));
//send the ack
partner->send(ChangedAckMessage { dataId2 });
QVERIFY(partner->waitForReply<LastChangedMessage>([&](LastChangedMessage message, bool &ok) {
Q_UNUSED(message)
ok = true;
}));
} catch(std::exception &e) {
QFAIL(e.what());
}
}
void TestAppServer::testSyncCommand()
{
try {
QVERIFY(client);
//send sync
client->send(SyncMessage{});
//wait for last changed (as no changes are present)
QVERIFY(client->waitForReply<LastChangedMessage>([&](LastChangedMessage message, bool &ok) {
Q_UNUSED(message)
ok = true;
}));
} catch(std::exception &e) {
QFAIL(e.what());
}
}
void TestAppServer::testDeviceUploading()
{
QByteArray dataId1 = "dataId4";
quint32 keyIndex = 0;
QByteArray salt = "salt";
QByteArray data = "data";
try {
QVERIFY(client);
QVERIFY(partner);
MockClient *partner3 = nullptr;
QUuid partner3DevId;
testAddDevice(partner3, partner3DevId, true);
QVERIFY(partner3);
//send an upload for partner only
DeviceChangeMessage changeMsg { dataId1, partnerDevId };
changeMsg.keyIndex = keyIndex;
changeMsg.salt = salt;
changeMsg.data = data;
client->send(changeMsg);
//wait for ack
QVERIFY(client->waitForReply<DeviceChangeAckMessage>([&](DeviceChangeAckMessage message, bool &ok) {
QCOMPARE(message.deviceId, partnerDevId);
QCOMPARE(message.dataId, dataId1);
ok = true;
}));
//wait for change info message
quint64 dataId2 = 0;
QVERIFY(partner->waitForReply<ChangedInfoMessage>([&](ChangedInfoMessage message, bool &ok) {
QCOMPARE(message.changeEstimate, 1u);
QCOMPARE(message.keyIndex, keyIndex);
QCOMPARE(message.salt, salt);
QCOMPARE(message.data, data);
dataId2 = message.dataIndex;
ok = true;
}));
//send the ack
partner->send(ChangedAckMessage { dataId2 });
QVERIFY(partner->waitForReply<LastChangedMessage>([&](LastChangedMessage message, bool &ok) {
Q_UNUSED(message)
ok = true;
}));
//patner3: nothing
QVERIFY(partner3->waitForNothing());
clean(partner3);
} catch(std::exception &e) {
QFAIL(e.what());
}
}
void TestAppServer::testChangeKey()
{
quint32 nextIndex = 1;
QByteArray scheme = "scheme";
QByteArray key = "key";
QByteArray cmac = "cmac";
try {
QVERIFY(client);
QVERIFY(partner);
//Send the key change proposal
client->send(KeyChangeMessage { nextIndex });
QList<DeviceKeysMessage::DeviceKey> keys;
QVERIFY(client->waitForReply<DeviceKeysMessage>([&](DeviceKeysMessage message, bool &ok) {
QCOMPARE(message.keyIndex, nextIndex);
QVERIFY(!message.duplicated);
QCOMPARE(message.devices.size(), 4); //testAddDevice, testAddDeviceInvalidKeyIndex, testSendDoubleAccept, testDeviceUploading
keys = message.devices;
ok = true;
}));
//verify the keys, extract partner 1 key
DeviceKeysMessage::DeviceKey mKey;
do {
mKey = keys.takeFirst();
if(partnerDevId == std::get<0>(mKey))
break;
} while(!keys.isEmpty());
QCOMPARE(std::get<0>(mKey), partnerDevId);
QCOMPARE(std::get<3>(mKey), partnerDevId.toByteArray()); //dummy cmac
//send the actual key update message (ignoring the other 3)
NewKeyMessage keyMsg;
keyMsg.keyIndex = nextIndex;
keyMsg.cmac = devName.toUtf8();
keyMsg.scheme = scheme;
keyMsg.deviceKeys.append(std::make_tuple(partnerDevId, key, cmac));
client->sendSigned(keyMsg, crypto);
//wait for ack
QVERIFY(client->waitForReply<NewKeyAckMessage>([&](NewKeyAckMessage message, bool &ok) {
QCOMPARE(message.keyIndex, nextIndex);
ok = true;
}));
//wait for partner to be disconnected
QVERIFY(partner->waitForDisconnect());
partner->deleteLater();
partner = new MockClient(this);
QVERIFY(partner->waitForConnected());
//wait for identify message
QByteArray mNonce;
QVERIFY(partner->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) {
QVERIFY(message.nonce.size() >= InitMessage::NonceSize);
QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion);
mNonce = message.nonce;
ok = true;
}));
//send back a valid login message
partner->sendSigned(LoginMessage {
partnerDevId,
partnerName,
mNonce
}, partnerCrypto);
//wait for the account message
QVERIFY(partner->waitForReply<WelcomeMessage>([&](WelcomeMessage message, bool &ok) {
QVERIFY(!message.hasChanges);//Must have changes now
QCOMPARE(message.keyIndex, nextIndex);
QCOMPARE(message.scheme, scheme);
QCOMPARE(message.key, key);
QCOMPARE(message.cmac, cmac);
ok = true;
}));
//update the mac accordingly
partner->send(MacUpdateMessage { nextIndex, partnerName.toUtf8() });
QVERIFY(partner->waitForReply<MacUpdateAckMessage>([&](MacUpdateAckMessage message, bool &ok) {
Q_UNUSED(message)
ok = true;
}));
//connect again, to make shure the ack was stored
clean(partner);
partner = new MockClient(this);
QVERIFY(partner->waitForConnected());
//wait for identify message
QVERIFY(partner->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) {
QVERIFY(message.nonce.size() >= InitMessage::NonceSize);
QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion);
mNonce = message.nonce;
ok = true;
}));
//send back a valid login message
partner->sendSigned(LoginMessage {
partnerDevId,
partnerName,
mNonce
}, partnerCrypto);
//wait for the account message
QVERIFY(partner->waitForReply<WelcomeMessage>([&](WelcomeMessage message, bool &ok) {
QVERIFY(!message.hasChanges);//Must have changes now
QCOMPARE(message.keyIndex, 0u);
QVERIFY(message.scheme.isNull());
QVERIFY(message.key.isNull());
QVERIFY(message.cmac.isNull());
ok = true;
}));
} catch(std::exception &e) {
QFAIL(e.what());
}
}
void TestAppServer::testChangeKeyInvalidIndex()
{
try {
QVERIFY(partner);
//Send the key change proposal
partner->send(KeyChangeMessage { 42 });
QVERIFY(partner->waitForError(ErrorMessage::KeyIndexError));
clean(partner);
} catch(std::exception &e) {
QFAIL(e.what());
}
}
void TestAppServer::testChangeKeyDuplicate()
{
quint32 nextIndex = 1;//duplicate to current
try {
QVERIFY(client);
//Send the key change proposal
client->send(KeyChangeMessage { nextIndex });
QVERIFY(client->waitForReply<DeviceKeysMessage>([&](DeviceKeysMessage message, bool &ok) {
QCOMPARE(message.keyIndex, nextIndex);
QVERIFY(message.duplicated);
QVERIFY(message.devices.isEmpty());
ok = true;
}));
//make shure no disconnect
QVERIFY(client->waitForNothing());
} catch(std::exception &e) {
QFAIL(e.what());
}
}
void TestAppServer::testChangeKeyPendingChanges()
{
quint32 nextIndex = 2;//valid
QByteArray scheme = "scheme2";
QByteArray key = "key2";
QByteArray cmac = "cmac2";
try {
QVERIFY(client);
QVERIFY(!partner);
//Send the key change proposal
client->send(KeyChangeMessage { nextIndex });
QVERIFY(client->waitForReply<DeviceKeysMessage>([&](DeviceKeysMessage message, bool &ok) {
QCOMPARE(message.keyIndex, nextIndex);
QVERIFY(!message.duplicated);
//skip key checks
ok = true;
}));
//send the actual key update message (ignoring the other 3)
NewKeyMessage keyMsg;
keyMsg.keyIndex = nextIndex;
keyMsg.cmac = devName.toUtf8();
keyMsg.scheme = scheme;
keyMsg.deviceKeys.append(std::make_tuple(partnerDevId, key, cmac));
client->sendSigned(keyMsg, crypto);
//wait for ack
QVERIFY(client->waitForReply<NewKeyAckMessage>([&](NewKeyAckMessage message, bool &ok) {
QCOMPARE(message.keyIndex, nextIndex);
ok = true;
}));
//try to send another keychange
client->send(KeyChangeMessage { ++nextIndex });
QVERIFY(client->waitForError(ErrorMessage::KeyPendingError));//should have it's own error message
clean(client);
testLogin();
} catch(std::exception &e) {
QFAIL(e.what());
}
}
void TestAppServer::testAddNewKeyInvalidIndex()
{
quint32 nextIndex = 42;//invalid index
try {
QVERIFY(client);
NewKeyMessage keyMsg;
keyMsg.keyIndex = nextIndex;
keyMsg.cmac = "cmac";
keyMsg.scheme = "scheme";
keyMsg.deviceKeys.append(std::make_tuple(partnerDevId, "key", "cmac"));
client->sendSigned(keyMsg, crypto);
//make shure no disconnect
QVERIFY(client->waitForError(ErrorMessage::KeyIndexError));
clean(client);
testLogin();
} catch(std::exception &e) {
QFAIL(e.what());
}
}
void TestAppServer::testAddNewKeyInvalidSignature()
{
quint32 nextIndex = 3;//valid index
try {
QVERIFY(client);
NewKeyMessage keyMsg;
keyMsg.keyIndex = nextIndex;
keyMsg.cmac = "cmac";
keyMsg.scheme = "scheme";
keyMsg.deviceKeys.append(std::make_tuple(partnerDevId, "key", "cmac"));
auto sData = keyMsg.serializeSigned(crypto->privateSignKey(), crypto->rng(), crypto);
sData[sData.size() - 1] = sData[sData.size() - 1] + 'x';
client->sendBytes(sData); //message + fake signature
//make shure no disconnect
QVERIFY(client->waitForError(ErrorMessage::AuthenticationError));
clean(client);
testLogin();
} catch(std::exception &e) {
QFAIL(e.what());
}
}
void TestAppServer::testAddNewKeyPendingChanges()
{
//theoretical situtation, that cannot occur normally
quint32 nextIndex = 3;//valid index
try {
QVERIFY(client);
NewKeyMessage keyMsg;
keyMsg.keyIndex = nextIndex;
keyMsg.cmac = "cmac";
keyMsg.scheme = "scheme";
keyMsg.deviceKeys.append(std::make_tuple(partnerDevId, "key", "cmac"));
client->sendSigned(keyMsg, crypto);
//make shure no disconnect
QVERIFY(client->waitForError(ErrorMessage::ServerError, true));//is ok here, as this case is typically detected by the KeyChangeMessage.
clean(client);
testLogin();
} catch(std::exception &e) {
QFAIL(e.what());
}
}
void TestAppServer::testKeyChangeNoAck()
{
quint32 nextIndex = 2;
QByteArray scheme = "scheme2";
QByteArray key = "key2";
QByteArray cmac = "cmac2";
try {
QVERIFY(!partner);
partner = new MockClient(this);
QVERIFY(partner->waitForConnected());
//wait for identify message
QByteArray mNonce;
QVERIFY(partner->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) {
QVERIFY(message.nonce.size() >= InitMessage::NonceSize);
QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion);
mNonce = message.nonce;
ok = true;
}));
//send back a valid login message
partner->sendSigned(LoginMessage {
partnerDevId,
partnerName,
mNonce
}, partnerCrypto);
//wait for the account message
QVERIFY(partner->waitForReply<WelcomeMessage>([&](WelcomeMessage message, bool &ok) {
QVERIFY(!message.hasChanges);//Must have changes now
QCOMPARE(message.keyIndex, nextIndex);
QCOMPARE(message.scheme, scheme);
QCOMPARE(message.key, key);
QCOMPARE(message.cmac, cmac);
ok = true;
}));
//do NOT send the mac, but reconnect
clean(partner);
partner = new MockClient(this);
QVERIFY(partner->waitForConnected());
//wait for identify message
QVERIFY(partner->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) {
QVERIFY(message.nonce.size() >= InitMessage::NonceSize);
QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion);
mNonce = message.nonce;
ok = true;
}));
//send back a valid login message
partner->sendSigned(LoginMessage {
partnerDevId,
partnerName,
mNonce
}, partnerCrypto);
//wait for the account message
QVERIFY(partner->waitForReply<WelcomeMessage>([&](WelcomeMessage message, bool &ok) {
QVERIFY(!message.hasChanges);//Must have changes now
QCOMPARE(message.keyIndex, nextIndex);
QCOMPARE(message.scheme, scheme);
QCOMPARE(message.key, key);
QCOMPARE(message.cmac, cmac);
ok = true;
}));
//update the mac accordingly
partner->send(MacUpdateMessage { nextIndex, partnerName.toUtf8() });
QVERIFY(partner->waitForReply<MacUpdateAckMessage>([&](MacUpdateAckMessage message, bool &ok) {
Q_UNUSED(message)
ok = true;
}));
} catch(std::exception &e) {
QFAIL(e.what());
}
}
void TestAppServer::testListAndRemoveDevices()
{
try {
QVERIFY(client);
QVERIFY(partner);
//list devices
client->send(ListDevicesMessage {});
QList<DevicesMessage::DeviceInfo> infos;
QVERIFY(client->waitForReply<DevicesMessage>([&](DevicesMessage message, bool &ok) {
QCOMPARE(message.devices.size(), 4); //testAddDevice, testAddDeviceInvalidKeyIndex, testSendDoubleAccept, testDeviceUploading
infos = message.devices;
ok = true;
}));
//verify the keys, verify partner, remove others
auto ok = false;
for(auto info : infos) {
QVERIFY(std::get<0>(info) != devId);
if(std::get<0>(info) == partnerDevId) {
QCOMPARE(std::get<1>(info), partnerName);
QCOMPARE(std::get<2>(info), partnerCrypto->ownFingerprint());
ok = true;
} else {
client->send(RemoveMessage {std::get<0>(info)});
QVERIFY(client->waitForReply<RemoveAckMessage>([&](RemoveAckMessage message, bool &ok) {
QCOMPARE(message.deviceId, std::get<0>(info));
ok = true;
}));
}
}
QVERIFY(ok);
//list from partners side
partner->send(ListDevicesMessage {});
QVERIFY(partner->waitForReply<DevicesMessage>([&](DevicesMessage message, bool &ok) {
QCOMPARE(message.devices.size(), 1);
auto info = message.devices.first();
QCOMPARE(std::get<0>(info), devId);
QCOMPARE(std::get<1>(info), devName);
QCOMPARE(std::get<2>(info), crypto->ownFingerprint());
ok = true;
}));
//now delete partner
client->send(RemoveMessage {partnerDevId});
QVERIFY(client->waitForReply<RemoveAckMessage>([&](RemoveAckMessage message, bool &ok) {
QCOMPARE(message.deviceId, partnerDevId);
ok = true;
}));
//wait for partner disconnect and reconnect
QVERIFY(partner->waitForDisconnect());
partner->deleteLater();
partner = new MockClient(this);
QVERIFY(partner->waitForConnected());
//wait for identify message
QByteArray mNonce;
QVERIFY(partner->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) {
QVERIFY(message.nonce.size() >= InitMessage::NonceSize);
QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion);
mNonce = message.nonce;
ok = true;
}));
//send back a valid login message (but partner does not exist anymore
partner->sendSigned(LoginMessage {
partnerDevId,
partnerName,
mNonce
}, partnerCrypto);
QVERIFY(partner->waitForError(ErrorMessage::AuthenticationError));
clean(partner);
} catch(std::exception &e) {
QFAIL(e.what());
}
}
void TestAppServer::testUnexpectedMessage_data()
{
QTest::addColumn<QSharedPointer<Message>>("message");
QTest::addColumn<bool>("whenIdle");
QTest::addColumn<bool>("isSigned");
QTest::newRow("RegisterMessage") << createNonced<RegisterMessage>()
<< true
<< true;
QTest::newRow("LoginMessage") << createNonced<LoginMessage>(devId, devName, "nonce")
<< true
<< true;
QTest::newRow("AccessMessage") << createNonced<AccessMessage>()
<< true
<< true;
QTest::newRow("SyncMessage") << create<SyncMessage>()
<< false
<< false;
QTest::newRow("ChangeMessage") << create<ChangeMessage>("data_id")
<< false
<< false;
QTest::newRow("DeviceChangeMessage") << create<DeviceChangeMessage>("data_id", partnerDevId)
<< false
<< false;
QTest::newRow("ChangedAckMessage") << create<ChangedAckMessage>(42ull)
<< false
<< false;
QTest::newRow("ListDevicesMessage") << create<ListDevicesMessage>()
<< false
<< false;
QTest::newRow("RemoveMessage") << create<RemoveMessage>(partnerDevId)
<< false
<< false;
QTest::newRow("AcceptMessage") << create<AcceptMessage>(partnerDevId)
<< false
<< true;
QTest::newRow("DenyMessage") << create<DenyMessage>(partnerDevId)
<< false
<< false;
QTest::newRow("MacUpdateMessage") << create<MacUpdateMessage>(42, "cmac")
<< false
<< false;
QTest::newRow("KeyChangeMessage") << create<KeyChangeMessage>(42)
<< false
<< false;
QTest::newRow("NewKeyMessage") << create<NewKeyMessage>()
<< false
<< true;
}
void TestAppServer::testUnexpectedMessage()
{
QFETCH(QSharedPointer<Message>, message);
QFETCH(bool, whenIdle);
QFETCH(bool, isSigned);
QVERIFY(message);
try {
//assume already logged in
QVERIFY(client);
if(!whenIdle) {
clean(client);
client = new MockClient(this);
QVERIFY(client->waitForConnected());
//wait for identify message
QVERIFY(client->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) {
QVERIFY(message.nonce.size() >= InitMessage::NonceSize);
QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion);
ok = true;
}));
}
if(isSigned)
client->sendSigned(*message, crypto);
else
client->send(*message);
QVERIFY(client->waitForError(ErrorMessage::UnexpectedMessageError, true));
clean(client);
testLogin();
} catch(std::exception &e) {
QFAIL(e.what());
}
}
void TestAppServer::testUnknownMessage()
{
try {
//assume already logged in
QVERIFY(client);
client->send(LastChangedMessage()); //unknown of the server
QVERIFY(client->waitForError(ErrorMessage::IncompatibleVersionError));
clean(client);
testLogin();
} catch(std::exception &e) {
QFAIL(e.what());
}
}
void TestAppServer::testBrokenMessage()
{
try {
//assume already logged in
QVERIFY(client);
client->sendBytes("\x00\x00\x00\x06Change\x00followed_by_gibberish");//header looks right, but not the rest
QVERIFY(client->waitForError(ErrorMessage::ClientError));
clean(client);
testLogin();
} catch(std::exception &e) {
QFAIL(e.what());
}
}
void TestAppServer::testRemoveSelf()
{
try {
QVERIFY(client);
//list devices
client->send(ListDevicesMessage {});
QList<DevicesMessage::DeviceInfo> infos;
QVERIFY(client->waitForReply<DevicesMessage>([&](DevicesMessage message, bool &ok) {
QVERIFY(message.devices.isEmpty());
ok = true;
}));
//now delete self
client->send(RemoveMessage {devId});
QVERIFY(client->waitForReply<RemoveAckMessage>([&](RemoveAckMessage message, bool &ok) {
QCOMPARE(message.deviceId, devId);
ok = true;
}));
clean(client);
client = new MockClient(this);
QVERIFY(client->waitForConnected());
//wait for identify message
QByteArray mNonce;
QVERIFY(client->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) {
QVERIFY(message.nonce.size() >= InitMessage::NonceSize);
QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion);
mNonce = message.nonce;
ok = true;
}));
//send back a valid login message (but partner does not exist anymore
client->sendSigned(LoginMessage {
devId,
devName,
mNonce
}, crypto);
QVERIFY(client->waitForError(ErrorMessage::AuthenticationError));
clean(client);
} catch(std::exception &e) {
QFAIL(e.what());
}
}
void TestAppServer::testStop()
{
//send a signal to stop
#ifdef Q_OS_UNIX
server->terminate(); //same as kill(SIGTERM)
#elif Q_OS_WIN
GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, server->processId());
#endif
QVERIFY(server->waitForFinished(5000));
QCOMPARE(server->exitStatus(), QProcess::NormalExit);
QCOMPARE(server->exitCode(), 0);
server->close();
}
void TestAppServer::clean(bool disconnect)
{
clean(client, disconnect);
}
void TestAppServer::clean(MockClient *&client, bool disconnect)
{
if(!client)
return;
if(disconnect)
client->close();
QVERIFY(client->waitForDisconnect());
client->deleteLater();
client = nullptr;
}
template<typename TMessage, typename... Args>
inline QSharedPointer<Message> TestAppServer::create(Args... args)
{
return QSharedPointer<TMessage>::create(args...).template staticCast<Message>();
}
template<typename TMessage, typename... Args>
inline QSharedPointer<Message> TestAppServer::createNonced(Args... args)
{
auto msg = create<TMessage>(args...).template dynamicCast<InitMessage>();
msg->nonce = QByteArray(InitMessage::NonceSize, 'x');
return msg;
}
QTEST_MAIN(TestAppServer)
#include "tst_appserver.moc"
| 26.819251 | 138 | 0.695207 | wangyangyangisme |
a650c158002bc3fd7675ae8d83eac8d5ca2afca2 | 2,402 | cpp | C++ | app/handlers/normalizer.cpp | freelandy/RobustPalmRoi | c94ec3c2a9d14ffe4d5f544796abf3754764b809 | [
"MIT"
] | 1 | 2019-05-10T08:46:35.000Z | 2019-05-10T08:46:35.000Z | app/handlers/normalizer.cpp | freelandy/RobustPalmRoi | c94ec3c2a9d14ffe4d5f544796abf3754764b809 | [
"MIT"
] | null | null | null | app/handlers/normalizer.cpp | freelandy/RobustPalmRoi | c94ec3c2a9d14ffe4d5f544796abf3754764b809 | [
"MIT"
] | null | null | null | // Copyright (c) 2018 leosocy. All rights reserved.
// Use of this source code is governed by a MIT-style license
// that can be found in the LICENSE file.
#include "handlers/normalizer.h"
namespace rpr {
Status OrigNormalizer::Init(const YAML::Node& parameters) {
try {
scaling_= parameters["scaling"].IsNull() ? 0.0 : parameters["scaling"]["value"].as<double>();
width_ = parameters["width"].IsNull() ? 350 : parameters["width"]["value"].as<int>();
} catch (const std::exception& e) {
return Status::LoadConfigYamlError(e.what());
}
if (scaling_ <= 0 || scaling_ > 1) {
return Status::LoadConfigYamlError("Original image scaling must in range [0.0, 1.0]");
}
return Status::Ok();
}
Status OrigNormalizer::Handle(PalmInfoDTO& palm) {
using utility::ResizeImageOperator;
const cv::Mat& orig = palm.PrevHandleRes();
cv::Mat res;
ResizeImageOperator *op = new ResizeImageOperator(orig, width_ == 0 ? scaling_ * orig.cols : width_);
op->Do(&res);
palm.SetCurHandleRes(res);
palm.SetImageOperator(std::unique_ptr<rpr::utility::ImageOperator>(op));
return Status::Ok();
}
Status IncircleRoiNormalizer::Init(const YAML::Node& parameters) {
try {
width_ = parameters["width"].IsNull() ? 256 : parameters["width"]["value"].as<int>();
} catch (const std::exception& e) {
return Status::LoadConfigYamlError(e.what());
}
return Status::Ok();
}
Status IncircleRoiNormalizer::Normalize(PalmInfoDTO& palm) {
const cv::Mat& roi(palm.roi());
cv::Mat balance_roi;
ColorBalance(roi, &balance_roi);
cv::Mat mask_roi;
MaskIncircle(balance_roi, &mask_roi);
palm.SetRoi(mask_roi);
return Status::Ok();
}
void IncircleRoiNormalizer::MaskIncircle(const cv::Mat& src, cv::Mat* dst) {
int radius = src.cols / 2;
cv::Mat mask(cv::Mat::zeros(src.size(), CV_8UC1));
circle(mask, cv::Point(src.cols / 2, src.rows / 2), radius, cv::Scalar(255), CV_FILLED);
src.copyTo(*dst, mask);
}
void IncircleRoiNormalizer::ColorBalance(const cv::Mat& src, cv::Mat* dst) {
std::vector<cv::Mat> rgb;
split(src, rgb);
double r, g, b;
b = cv::mean(rgb[0])[0];
g = cv::mean(rgb[1])[0];
r = cv::mean(rgb[2])[0];
double kr, kg, kb;
kb = (r + g + b) / (3 * b);
kg = (r + g + b) / (3 * g);
kr = (r + g + b) / (3 * r);
rgb[0] = rgb[0] * kb;
rgb[1] = rgb[1] * kg;
rgb[2] = rgb[2] * kr;
merge(rgb, *dst);
}
} // namespace rpr
| 28.258824 | 103 | 0.641965 | freelandy |
a650c9e3aafddc87acc317170cd2c44a67081678 | 2,180 | hpp | C++ | p3iv_utils/include/p3iv_utils/finite_differences.hpp | fzi-forschungszentrum-informatik/P3IV | 51784e6dc03dcaa0ad58a5078475fa4daec774bd | [
"BSD-3-Clause"
] | 4 | 2021-07-27T06:56:22.000Z | 2022-03-22T11:21:30.000Z | p3iv_utils/include/p3iv_utils/finite_differences.hpp | fzi-forschungszentrum-informatik/P3IV | 51784e6dc03dcaa0ad58a5078475fa4daec774bd | [
"BSD-3-Clause"
] | null | null | null | p3iv_utils/include/p3iv_utils/finite_differences.hpp | fzi-forschungszentrum-informatik/P3IV | 51784e6dc03dcaa0ad58a5078475fa4daec774bd | [
"BSD-3-Clause"
] | 1 | 2021-10-10T01:56:44.000Z | 2021-10-10T01:56:44.000Z | /*
* This file is part of the Interpolated Polyline (https://github.com/fzi-forschungszentrum-informatik/P3IV),
* copyright by FZI Forschungszentrum Informatik, licensed under the BSD-3 license (see LICENSE file in main directory)
*/
#pragma once
#include <cmath>
#include <vector>
namespace p3iv_utils {
template <typename T>
inline T derive_1(const T& dt, const T* const p0, const T* const p1) {
/// first order finite differences
/// forward difference, if p0 is the current value
/// backward difference, if p1 is the current value
return (p1[0] - p0[0]) / (dt);
}
template <typename T>
inline T derive_1(const T& dt, const T& x0, const T& x1) {
/// first order finite differences
/// forward difference, if p0 is the current value
/// backward difference, if p1 is the current value
return (x1 - x0) / (dt);
}
template <typename T>
inline T derive_2(const T& dt, const T* const p0, const T* const p1, const T* const p2) {
/// second order finite differences
/// forward difference, if p0 is the current value
/// backward difference, if p2 is the current value
return (p0[0] - T(2) * p1[0] + p2[0]) / (dt * dt);
}
template <typename T>
inline T derive_2(const T& dt, const T& x0, const T& x1, const T& x2) {
/// second order finite differences
/// forward difference, if p0 is the current value
/// backward difference, if p2 is the current value
return (x0 - T(2) * x1 + x2) / (dt * dt);
}
template <typename T>
inline T derive_3(const T& dt, const T* const p0, const T* const p1, const T* const p2, const T* const p3) {
/// third order finite differences
/// forward difference, if p0 is the current value
/// backward difference, if p3 is the current value
return (-p0[0] + T(3) * p1[0] - T(3) * p2[0] + p3[0]) / (dt * dt * dt);
}
template <typename T>
inline T derive_3(const T& dt, const T& x0, const T& x1, const T& x2, const T& x3) {
/// third order finite differences
/// forward difference, if p0 is the current value
/// backward difference, if p3 is the current value
return (-x0 + T(3) * x1 - T(3) * x2 + x3) / (dt * dt * dt);
}
} // namespace p3iv_utils | 35.737705 | 119 | 0.655505 | fzi-forschungszentrum-informatik |
a650fe3a45c990c0b193fb6ca4bfad93c2741057 | 6,920 | cpp | C++ | remodet_repository_wdh_part/src/caffe/tracker/fe_roi_maker.cpp | UrwLee/Remo_experience | a59d5b9d6d009524672e415c77d056bc9dd88c72 | [
"MIT"
] | null | null | null | remodet_repository_wdh_part/src/caffe/tracker/fe_roi_maker.cpp | UrwLee/Remo_experience | a59d5b9d6d009524672e415c77d056bc9dd88c72 | [
"MIT"
] | null | null | null | remodet_repository_wdh_part/src/caffe/tracker/fe_roi_maker.cpp | UrwLee/Remo_experience | a59d5b9d6d009524672e415c77d056bc9dd88c72 | [
"MIT"
] | null | null | null | #include "caffe/tracker/fe_roi_maker.hpp"
namespace caffe {
template <typename Dtype>
FERoiMaker<Dtype>::FERoiMaker(const std::string& network_proto,
const std::string& caffe_model,
const int gpu_id,
const std::string& features,
const int resized_width,
const int resized_height) {
// Get Net
LOG(INFO) << "Using GPU mode in Caffe with device: " << gpu_id;
caffe::Caffe::SetDevice(gpu_id);
caffe::Caffe::set_mode(caffe::Caffe::GPU);
net_.reset(new Net<Dtype>(network_proto, caffe::TEST));
if (caffe_model != "NONE") {
net_->CopyTrainedLayersFrom(caffe_model);
} else {
LOG(FATAL) << "Must define a pre-trained model.";
}
CHECK_EQ(net_->num_outputs(), 1) << "Network should have exactly one output.";
Blob<Dtype>* input_layer = net_->input_blobs()[0];
input_width_ = input_layer->width();
input_height_ = input_layer->height();
LOG(INFO) << "Network requires input size: (width, height) "
<< input_width_ << ", " << input_height_;
CHECK_EQ(input_layer->channels(), 3) << "Input layer should have 3 channels.";
// Get Layer
LayerParameter layer_param;
layer_param.set_name("roi_resize_layer");
layer_param.set_type("RoiResize");
RoiResizeParameter* roi_resize_param = layer_param.mutable_roi_resize_param();
roi_resize_param->set_target_spatial_width(resized_width);
roi_resize_param->set_target_spatial_height(resized_height);
roi_resize_layer_ = LayerRegistry<Dtype>::CreateLayer(layer_param);
vector<Blob<Dtype>*> resize_bottom_vec;
vector<Blob<Dtype>*> resize_top_vec;
Blob<Dtype> bot_0(1,1,12,12);
Blob<Dtype> bot_1(1,1,1,4);
Blob<Dtype> top_0(1,1,resized_height,resized_width);
resize_bottom_vec.push_back(&bot_0);
resize_bottom_vec.push_back(&bot_1);
resize_top_vec.push_back(&top_0);
roi_resize_layer_->SetUp(resize_bottom_vec, resize_top_vec);
// features
features_ = features;
}
template <typename Dtype>
void FERoiMaker<Dtype>::getFeatures(const std::string& feature, const Blob<Dtype>* map) {
const boost::shared_ptr<Blob<Dtype> > feature_blob = net_->blob_by_name(feature.c_str());
map = feature_blob.get();
}
template <typename Dtype>
void FERoiMaker<Dtype>::load(const cv::Mat& image) {
Blob<Dtype>* input_blob = net_->input_blobs()[0];
CHECK_EQ(image.channels(), 3);
int w = image.cols;
int h = image.rows;
CHECK_GT(w,0);
CHECK_GT(h,0);
if (!image.data) {
LOG(FATAL) << "Image data open failed.";
}
Dtype scalar = sqrt(512*288/w/h);
cv::Mat resized_image;
cv::resize(image,resized_image,cv::Size(),scalar,scalar,CV_INTER_LINEAR);
input_blob->Reshape(1, 3, resized_image.rows, resized_image.cols);
net_->Reshape();
Dtype* transformed_data = input_blob->mutable_cpu_data();
const int offset = resized_image.rows * resized_image.cols;
bool normalize = false;
for (int i = 0; i < resized_image.rows; ++i) {
for (int j = 0; j < resized_image.cols; ++j) {
cv::Vec3b& rgb = resized_image.at<cv::Vec3b>(i, j);
if (normalize) {
transformed_data[i * resized_image.cols + j] = (rgb[0] - 128)/256.0;
transformed_data[offset + i * resized_image.cols + j] = (rgb[1] - 128)/256.0;
transformed_data[2 * offset + i * resized_image.cols + j] = (rgb[2] - 128)/256.0;
} else {
transformed_data[i * resized_image.cols + j] = rgb[0] - 104;
transformed_data[offset + i * resized_image.cols + j] = rgb[1] - 117;;
transformed_data[2 * offset + i * resized_image.cols + j] = rgb[2] - 123;;
}
}
}
}
template <typename Dtype>
void FERoiMaker<Dtype>::roi_resize(const Blob<Dtype>* feature, const BoundingBox<Dtype>& bbox,
Blob<Dtype>* resize_fmap) {
// get bbox
Blob<Dtype> bbox_blob(1,1,1,4);
Dtype* bbox_data = bbox_blob.mutable_cpu_data();
bbox_data[0] = bbox.x1_;
bbox_data[1] = bbox.y1_;
bbox_data[2] = bbox.x2_;
bbox_data[3] = bbox.y2_;
vector<Blob<Dtype>*> resize_bottom_vec;
vector<Blob<Dtype>*> resize_top_vec;
Blob<Dtype> fmap;
fmap.ReshapeLike(*feature);
fmap.ShareData(*feature);
resize_bottom_vec.push_back(&fmap);
resize_bottom_vec.push_back(&bbox_blob);
resize_top_vec.push_back(resize_fmap);
roi_resize_layer_->Reshape(resize_bottom_vec, resize_top_vec);
roi_resize_layer_->Forward(resize_bottom_vec, resize_top_vec);
}
template <typename Dtype>
void FERoiMaker<Dtype>::get_features(const cv::Mat& image, const BoundingBox<Dtype>& bbox,
Blob<Dtype>* resized_fmap) {
// Load
load(image);
// Forward
net_->Forward();
// Get features
const Blob<Dtype>* feature_blob = NULL;
getFeatures(features_, feature_blob);
// roi resize
roi_resize(feature_blob,bbox,resized_fmap);
// done.
}
template <typename Dtype>
void FERoiMaker<Dtype>::get_fmap(const cv::Mat& image, const BoundingBox<Dtype>& bbox,
Blob<Dtype>* resized_fmap, Blob<Dtype>* fmap) {
// Load
load(image);
// Forward
net_->Forward();
// Get features
getFeatures(features_, fmap);
// roi resize
roi_resize(fmap,bbox,resized_fmap);
}
template <typename Dtype>
void FERoiMaker<Dtype>::get_features(const cv::Mat& image_prev,
const cv::Mat& image_curr,
const BoundingBox<Dtype>& bbox_prev,
const BoundingBox<Dtype>& bbox_curr,
Blob<Dtype>* resized_prev,
Blob<Dtype>* resized_curr) {
get_features(image_prev, bbox_prev, resized_prev);
get_features(image_curr, bbox_curr, resized_curr);
}
template <typename Dtype>
void FERoiMaker<Dtype>::get_features(const cv::Mat& image_prev,
const cv::Mat& image_curr,
const BoundingBox<Dtype>& bbox_prev,
const BoundingBox<Dtype>& bbox_curr,
Blob<Dtype>* resized_unified_map) {
Blob<Dtype> resized_prev;
Blob<Dtype> resized_curr;
get_features(image_prev, bbox_prev, &resized_prev);
get_features(image_curr, bbox_curr, &resized_curr);
CHECK_EQ(resized_prev.num(), resized_curr.num());
CHECK_EQ(resized_prev.channels(), resized_curr.channels());
CHECK_EQ(resized_prev.height(), resized_curr.height());
CHECK_EQ(resized_prev.width(), resized_curr.width());
resized_unified_map->Reshape(1,2*resized_prev.channels(),resized_prev.height(),resized_prev.width());
caffe_copy(resized_prev.count(),resized_prev.cpu_data(),resized_unified_map->mutable_cpu_data());
caffe_copy(resized_curr.count(),resized_curr.cpu_data(),
resized_unified_map->mutable_cpu_data()+resized_prev.count());
}
INSTANTIATE_CLASS(FERoiMaker);
}
| 39.542857 | 103 | 0.656936 | UrwLee |
a6563881b008a1f94b1e58f6854fac0b380d3ebb | 65,831 | cc | C++ | graph/igraph-0.6/src/bliss_graph.cc | FlyerMaxwell/Bubble | 70ca988bca3a5debce5d9c61f203b08005bdefaf | [
"MIT"
] | 3 | 2017-09-05T03:06:12.000Z | 2019-04-28T13:17:11.000Z | graph/igraph-0.6/src/bliss_graph.cc | FlyerMaxwell/Bubble | 70ca988bca3a5debce5d9c61f203b08005bdefaf | [
"MIT"
] | null | null | null | graph/igraph-0.6/src/bliss_graph.cc | FlyerMaxwell/Bubble | 70ca988bca3a5debce5d9c61f203b08005bdefaf | [
"MIT"
] | 1 | 2019-03-05T06:24:02.000Z | 2019-03-05T06:24:02.000Z | /*
Copyright (C) 2003-2006 Tommi Junttila
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.
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 St, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* FSF address fixed in the above notice on 1 Oct 2009 by Tamas Nepusz */
#include <cstdio>
#include <cassert>
#include <cctype>
#include <set>
#include <list>
#include <algorithm>
#include "bliss_defs.hh"
#include "bliss_timer.hh"
#include "bliss_graph.hh"
#include "bliss_partition.hh"
#include <climits> // INT_MAX, etc
#include "igraph_datatype.h"
#include "igraph_interface.h"
#include "igraph_topology.h"
#include "igraph_statusbar.h"
using namespace std;
extern bool bliss_verbose;
// extern FILE *bliss_verbstr;
namespace igraph {
static const bool should_not_happen = false;
/*-------------------------------------------------------------------------
*
* Constructor and destructor routines for the abstract graph class
*
*-------------------------------------------------------------------------*/
AbstractGraph::AbstractGraph()
{
/* Initialize stuff */
first_path_labeling = 0;
first_path_labeling_inv = 0;
best_path_labeling = 0;
best_path_labeling_inv = 0;
first_path_automorphism = 0;
best_path_automorphism = 0;
//certificate = 0;
in_search = false;
}
AbstractGraph::~AbstractGraph()
{
if(first_path_labeling) {
free(first_path_labeling); first_path_labeling = 0; }
if(first_path_labeling_inv) {
free(first_path_labeling_inv); first_path_labeling_inv = 0; }
if(best_path_labeling) {
free(best_path_labeling); best_path_labeling = 0; }
if(best_path_labeling_inv) {
free(best_path_labeling_inv); best_path_labeling_inv = 0; }
if(first_path_automorphism) {
free(first_path_automorphism); first_path_automorphism = 0; }
if(best_path_automorphism) {
free(best_path_automorphism); best_path_automorphism = 0; }
//if(certificate) {
// free(certificate); certificate = 0; }
while(!long_prune_fixed.empty())
{
delete long_prune_fixed.back();
long_prune_fixed.pop_back();
}
while(!long_prune_mcrs.empty())
{
delete long_prune_mcrs.back();
long_prune_mcrs.pop_back();
}
}
/*-------------------------------------------------------------------------
*
* Routines for refinement to equitable partition
*
*-------------------------------------------------------------------------*/
void AbstractGraph::refine_to_equitable()
{
assert(p.splitting_queue.is_empty());
for(Cell *cell = p.first_cell; cell; cell = cell->next)
{
p.add_in_splitting_queue(cell);
}
return do_refine_to_equitable();
}
void AbstractGraph::refine_to_equitable(Cell *cell1)
{
DEBUG_ASSERT(cell1->length == 1);
#ifdef EXPENSIVE_CONSISTENCY_CHECKS
for(Cell *cell = p.first_cell; cell; cell = cell->next) {
assert(cell->in_splitting_queue == false);
assert(cell->in_neighbour_heap == false);
}
#endif
assert(p.splitting_queue.is_empty());
p.add_in_splitting_queue(cell1);
return do_refine_to_equitable();
}
void AbstractGraph::refine_to_equitable(Cell *cell1, Cell *cell2)
{
DEBUG_ASSERT(cell1->length == 1);
DEBUG_ASSERT(cell2->length == 1);
#ifdef EXPENSIVE_CONSISTENCY_CHECKS
for(Cell *cell = p.first_cell; cell; cell = cell->next) {
assert(cell->in_splitting_queue == false);
assert(cell->in_neighbour_heap == false);
}
#endif
assert(p.splitting_queue.is_empty());
p.add_in_splitting_queue(cell1);
p.add_in_splitting_queue(cell2);
return do_refine_to_equitable();
}
void AbstractGraph::do_refine_to_equitable()
{
assert(!p.splitting_queue.is_empty());
assert(neighbour_heap.is_empty());
eqref_hash.reset();
while(!p.splitting_queue.is_empty())
{
Cell *cell = p.splitting_queue.pop_front();
DEBUG_ASSERT(cell->in_splitting_queue);
cell->in_splitting_queue = false;
if(cell->length == 1)
{
if(in_search) {
if(first_path_automorphism) {
/* Build the (potential) automorphism on-the-fly */
assert(first_path_labeling_inv);
first_path_automorphism[first_path_labeling_inv[cell->first]] =
p.elements[cell->first];
}
if(best_path_automorphism)
{
/* Build the (potential) automorphism on-the-fly */
assert(best_path_labeling_inv);
best_path_automorphism[best_path_labeling_inv[cell->first]] =
p.elements[cell->first];
}
}
bool worse = split_neighbourhood_of_unit_cell(cell);
if(in_search && worse)
goto worse_exit;
}
else
{
split_neighbourhood_of_cell(cell);
}
}
eqref_worse_than_certificate = false;
return;
worse_exit:
/* Clear splitting_queue */
p.clear_splitting_queue();
eqref_worse_than_certificate = true;
return;
}
/*-------------------------------------------------------------------------
*
* Routines for handling the canonical labeling
*
*-------------------------------------------------------------------------*/
void AbstractGraph::update_labeling(unsigned int * const labeling)
{
const unsigned int N = get_nof_vertices();
unsigned int *ep = p.elements;
for(unsigned int i = 0; i < N; i++, ep++)
labeling[*ep] = i;
}
void AbstractGraph::update_labeling_and_its_inverse(unsigned int * const labeling,
unsigned int * const labeling_inv)
{
const unsigned int N = get_nof_vertices();
unsigned int *ep = p.elements;
unsigned int *clip = labeling_inv;
for(unsigned int i = 0; i < N; ) {
labeling[*ep] = i;
i++;
*clip = *ep;
ep++;
clip++;
}
}
/*-------------------------------------------------------------------------
*
* Routines for handling automorphisms
*
*-------------------------------------------------------------------------*/
void AbstractGraph::reset_permutation(unsigned int *perm)
{
const unsigned int N = get_nof_vertices();
for(unsigned int i = 0; i < N; i++, perm++)
*perm = i;
}
bool AbstractGraph::is_automorphism(unsigned int * const perm)
{
assert(should_not_happen);
return false;
}
/*-------------------------------------------------------------------------
*
* Long prune code
*
*-------------------------------------------------------------------------*/
void AbstractGraph::long_prune_init()
{
const unsigned int N = get_nof_vertices();
long_prune_temp.clear();
long_prune_temp.resize(N);
#ifdef DEBUG
for(unsigned int i = 0; i < N; i++)
assert(long_prune_temp[i] == false);
#endif
const unsigned int nof_fitting_in_max_mem =
(long_prune_options_max_mem * 1024 * 1024) / (((N * 2) / 8)+1);
long_prune_max_stored_autss = long_prune_options_max_stored_auts;
/* Had some problems with g++ in using (a<b)?a:b when constants involved,
so had to make this in a stupid way...*/
if(nof_fitting_in_max_mem < long_prune_options_max_stored_auts)
long_prune_max_stored_autss = nof_fitting_in_max_mem;
while(!long_prune_fixed.empty())
{
delete long_prune_fixed.back();
long_prune_fixed.pop_back();
}
while(!long_prune_mcrs.empty())
{
delete long_prune_mcrs.back();
long_prune_mcrs.pop_back();
}
for(unsigned int i = 0; i < long_prune_max_stored_autss; i++)
{
long_prune_fixed.push_back(new std::vector<bool>(N));
long_prune_mcrs.push_back(new std::vector<bool>(N));
}
long_prune_begin = 0;
long_prune_end = 0;
}
void AbstractGraph::long_prune_swap(const unsigned int i, const unsigned int j)
{
assert(long_prune_begin <= long_prune_end);
assert(long_prune_end - long_prune_end <= long_prune_max_stored_autss);
assert(i >= long_prune_begin);
assert(i < long_prune_end);
assert(j >= long_prune_begin);
assert(j < long_prune_end);
const unsigned int real_i = i % long_prune_max_stored_autss;
const unsigned int real_j = j % long_prune_max_stored_autss;
std::vector<bool> * tmp = long_prune_fixed[real_i];
long_prune_fixed[real_i] = long_prune_fixed[real_j];
long_prune_fixed[real_j] = tmp;
tmp = long_prune_mcrs[real_i];
long_prune_mcrs[real_i] = long_prune_mcrs[real_j];
long_prune_mcrs[real_j] = tmp;
}
std::vector<bool> &AbstractGraph::long_prune_get_fixed(const unsigned int index)
{
assert(long_prune_begin <= long_prune_end);
assert(long_prune_end - long_prune_end <= long_prune_max_stored_autss);
assert(index >= long_prune_begin);
assert(index < long_prune_end);
return *long_prune_fixed[index % long_prune_max_stored_autss];
}
std::vector<bool> &AbstractGraph::long_prune_get_mcrs(const unsigned int index)
{
assert(long_prune_begin <= long_prune_end);
assert(long_prune_end - long_prune_end <= long_prune_max_stored_autss);
assert(index >= long_prune_begin);
assert(index < long_prune_end);
return *long_prune_mcrs[index % long_prune_max_stored_autss];
}
void AbstractGraph::long_prune_add_automorphism(const unsigned int *aut)
{
if(long_prune_max_stored_autss == 0)
return;
const unsigned int N = get_nof_vertices();
#ifdef DEBUG
assert(long_prune_temp.size() == N);
for(unsigned int i = 0; i < N; i++)
assert(long_prune_temp[i] == false);
#endif
DEBUG_ASSERT(long_prune_fixed.size() == long_prune_mcrs.size());
assert(long_prune_begin <= long_prune_end);
assert(long_prune_end - long_prune_end <= long_prune_max_stored_autss);
if(long_prune_end - long_prune_begin == long_prune_max_stored_autss)
{
long_prune_begin++;
}
long_prune_end++;
std::vector<bool> &fixed = long_prune_get_fixed(long_prune_end-1);
std::vector<bool> &mcrs = long_prune_get_mcrs(long_prune_end-1);
for(unsigned int i = 0; i < N; i++)
{
fixed[i] = (aut[i] == i);
if(!long_prune_temp[i])
{
mcrs[i] = true;
unsigned int j = aut[i];
while(j != i)
{
assert(i <= j);
long_prune_temp[j] = true;
j = aut[j];
}
}
else
{
mcrs[i] = false;
}
long_prune_temp[i] = false;
}
#ifdef DEBUG
for(unsigned int i = 0; i < N; i++)
assert(long_prune_temp[i] == false);
#endif
}
/*-------------------------------------------------------------------------
*
* Routines for handling orbit information
*
*-------------------------------------------------------------------------*/
void AbstractGraph::update_orbit_information(Orbit &o, const unsigned int *p)
{
const unsigned int N = get_nof_vertices();
for(unsigned int i = 0; i < N; i++)
if(p[i] != i)
o.merge_orbits(i, p[i]);
}
/*-------------------------------------------------------------------------
*
* Print a permutation in cycle notation
*
*-------------------------------------------------------------------------*/
void AbstractGraph::print_permutation(FILE *fp, const unsigned int *perm)
{
const unsigned int N = get_nof_vertices();
for(unsigned int i = 0; i < N; i++) {
unsigned int j = perm[i];
if(j == i)
continue;
bool is_first = true;
while(j != i) {
if(j < i) {
is_first = false;
break;
}
j = perm[j];
}
if(!is_first)
continue;
fprintf(fp, "(%u,", i);
j = perm[i];
while(j != i) {
fprintf(fp, "%u", j);
j = perm[j];
if(j != i)
fprintf(fp, ",");
}
fprintf(fp, ")");
}
}
/*-------------------------------------------------------------------------
*
* The actual backtracking search
*
*-------------------------------------------------------------------------*/
typedef struct {
int split_element;
unsigned int split_cell_first;
unsigned int refinement_stack_size;
unsigned int certificate_index;
bool in_first_path;
bool in_best_path;
bool equal_to_first_path;
int cmp_to_best_path;
bool needs_long_prune;
unsigned int long_prune_begin;
std::set<unsigned int, std::less<unsigned int> > long_prune_redundant;
EqrefHash eqref_hash;
unsigned int subcertificate_length;
} LevelInfo;
typedef struct t_path_info {
unsigned int splitting_element;
unsigned int certificate_index;
unsigned int subcertificate_length;
EqrefHash eqref_hash;
} PathInfo;
void AbstractGraph::search(const bool canonical, Stats &stats)
{
const unsigned int N = get_nof_vertices();
// const bool write_automorphisms = 0;
unsigned int all_same_level = UINT_MAX;
p.graph = this;
/*
* Must be done!
*/
remove_duplicate_edges();
/*
* Reset search statistics
*/
stats.group_size.assign(1);
stats.nof_nodes = 1;
stats.nof_leaf_nodes = 1;
stats.nof_bad_nodes = 0;
stats.nof_canupdates = 0;
stats.nof_generators = 0;
stats.max_level = 0;
if(first_path_labeling)
{
free(first_path_labeling);
first_path_labeling = 0;
}
if(first_path_labeling_inv)
{
free(first_path_labeling_inv);
first_path_labeling_inv = 0;
}
if(first_path_automorphism)
{
free(first_path_automorphism);
first_path_automorphism = 0;
}
if(best_path_labeling)
{
free(best_path_labeling);
best_path_labeling = 0;
}
if(best_path_labeling_inv)
{
free(best_path_labeling_inv);
best_path_labeling_inv = 0;
}
if(best_path_automorphism)
{
free(best_path_automorphism);
best_path_automorphism = 0;
}
if(N == 0)
return;
p.init(N);
neighbour_heap.init(N);
in_search = false;
p.level = 0;
Timer t1;
t1.start();
make_initial_equitable_partition();
#if defined(VERIFY_EQUITABLEDNESS)
assert(is_equitable());
#endif
t1.stop();
igraph_statusf("Initial partition computed in %.2fs", 0,
t1.get_duration());
/*
* Allocate space for the labelings
*/
if(first_path_labeling)
free(first_path_labeling);
first_path_labeling = (unsigned int*)calloc(N, sizeof(unsigned int));
if(best_path_labeling)
free(best_path_labeling);
best_path_labeling = (unsigned int*)calloc(N, sizeof(unsigned int));
/*
* Are there any non-singleton cells?
*/
if(p.is_discrete())
{
update_labeling(best_path_labeling);
return;
}
//p.print_signature(stderr); fprintf(stderr, "\n");
/*
* Allocate space for the inverses of the labelings
*/
if(first_path_labeling_inv)
free(first_path_labeling_inv);
first_path_labeling_inv = (unsigned int*)calloc(N, sizeof(unsigned int));
if(best_path_labeling_inv)
free(best_path_labeling_inv);
best_path_labeling_inv = (unsigned int*)calloc(N, sizeof(unsigned int));
/*
* Allocate space for the automorphisms
*/
if(first_path_automorphism) free(first_path_automorphism);
first_path_automorphism = (unsigned int*)malloc(N * sizeof(unsigned int));
if(best_path_automorphism) free(best_path_automorphism);
best_path_automorphism = (unsigned int*)malloc(N * sizeof(unsigned int));
/*
* Initialize orbit information
*/
first_path_orbits.init(N);
best_path_orbits.init(N);
/*
* Initialize certificate memory
*/
initialize_certificate();
//assert(certificate);
assert(certificate_index == 0);
LevelInfo info;
std::vector<LevelInfo> search_stack;
std::vector<PathInfo> first_path_info;
std::vector<PathInfo> best_path_info;
search_stack.clear();
p.refinement_stack.clean();
assert(neighbour_heap.is_empty());
/*
* Initialize long prune
*/
long_prune_init();
/*
* Build the first level info
*/
info.split_cell_first = find_next_cell_to_be_splitted(p.first_cell)->first;
info.split_element = -1;
info.refinement_stack_size = p.refinement_stack.size();
info.certificate_index = 0;
info.in_first_path = false;
info.in_best_path = false;
info.long_prune_begin = 0;
search_stack.push_back(info);
/*
* Set status and global flags for search related procedures
*/
in_search = true;
refine_compare_certificate = false;
stats.nof_leaf_nodes = 0;
#ifdef PRINT_SEARCH_TREE_DOT
dotty_output = fopen("debug_stree.dot", "w");
fprintf(dotty_output, "digraph stree {\n");
fprintf(dotty_output, "\"n\" [label=\"");
fprintf(dotty_output, "M"); //p.print(dotty_output);
fprintf(dotty_output, "\"];\n");
#endif
p.consistency_check();
/*
* The actual backtracking search
*/
while(!search_stack.empty())
{
info = search_stack.back();
search_stack.pop_back();
p.consistency_check();
/*
* Restore partition, certificate index, and split cell
*/
p.unrefine(p.level, info.refinement_stack_size);
assert(info.certificate_index <= certificate_size);
certificate_index = info.certificate_index;
certificate_current_path.resize(certificate_index);
Cell * const cell = p.element_to_cell_map[p.elements[info.split_cell_first]];
assert(cell->length > 1);
p.consistency_check();
if(p.level > 0 && !info.in_first_path)
{
if(info.split_element == -1)
{
info.needs_long_prune = true;
}
else if(info.needs_long_prune)
{
info.needs_long_prune = false;
/* THIS IS A QUITE HORRIBLE HACK! */
unsigned int begin = (info.long_prune_begin>long_prune_begin)?info.long_prune_begin:long_prune_begin;
for(unsigned int i = begin; i < long_prune_end; i++)
{
const std::vector<bool> &fixed = long_prune_get_fixed(i);
bool fixes_all = true;
for(unsigned int l = 0; l < p.level; l++)
{
if(fixed[search_stack[l].split_element] == false)
{
fixes_all = false;
break;
}
}
if(!fixes_all)
{
long_prune_swap(begin, i);
begin++;
info.long_prune_begin = begin;
continue;
}
const std::vector<bool> &mcrs = long_prune_get_mcrs(i);
unsigned int *ep = p.elements + cell->first;
for(unsigned int j = cell->length; j > 0; j--, ep++) {
if(mcrs[*ep] == false)
{
info.long_prune_redundant.insert(*ep);
}
}
}
}
}
/*
* Find the next smallest element in cell
*/
unsigned int next_split_element = UINT_MAX;
unsigned int *next_split_element_pos = 0;
unsigned int *ep = p.elements + cell->first;
if(info.in_first_path)
{
/* Find the next larger splitting element that is a mor */
for(unsigned int i = cell->length; i > 0; i--, ep++) {
if((int)(*ep) > info.split_element &&
*ep < next_split_element &&
first_path_orbits.is_minimal_representative(*ep)) {
next_split_element = *ep;
next_split_element_pos = ep;
}
}
}
else if(info.in_best_path)
{
/* Find the next larger splitting element that is a mor */
for(unsigned int i = cell->length; i > 0; i--, ep++) {
if((int)(*ep) > info.split_element &&
*ep < next_split_element &&
best_path_orbits.is_minimal_representative(*ep) &&
(info.long_prune_redundant.find(*ep) ==
info.long_prune_redundant.end())) {
next_split_element = *ep;
next_split_element_pos = ep;
}
}
}
else
{
/* Find the next larger splitting element */
for(unsigned int i = cell->length; i > 0; i--, ep++) {
if((int)(*ep) > info.split_element &&
*ep < next_split_element &&
(info.long_prune_redundant.find(*ep) ==
info.long_prune_redundant.end())) {
next_split_element = *ep;
next_split_element_pos = ep;
}
}
}
if(next_split_element == UINT_MAX)
{
/*
* No more splitting elements (unexplored children) in the cell
*/
/* Update group size if required */
if(info.in_first_path == true) {
const unsigned int index =
first_path_orbits.orbit_size(first_path_info[p.level].splitting_element);
stats.group_size.multiply(index);
/*
* Update all_same_level
*/
if(index == cell->length && all_same_level == p.level+1)
all_same_level = p.level;
igraph_statusf("Level %u: orbits=%u, index=%u/%u, "
"all_same_level=%u", 0,
p.level,
first_path_orbits.nof_orbits(),
index, cell->length,
all_same_level);
}
/* Backtrack to the previous level */
p.level--;
continue;
}
/* Split on smallest */
info.split_element = next_split_element;
/*
* Save the current search situation
*/
search_stack.push_back(info);
/*
* No more in the first path
*/
info.in_first_path = false;
/*
* No more in the best path
*/
info.in_best_path = false;
p.level++;
stats.nof_nodes++;
if(p.level > stats.max_level)
stats.max_level = p.level;
p.consistency_check();
/*
* Move the split element to be the last in the cell
*/
*next_split_element_pos = p.elements[cell->first + cell->length - 1];
p.in_pos[*next_split_element_pos] = next_split_element_pos;
p.elements[cell->first + cell->length - 1] = next_split_element;
p.in_pos[next_split_element] = p.elements+ cell->first + cell->length -1;
/*
* Split the cell in two:
* the last element in the cell (split element) forms a singleton cell
*/
Cell * const new_cell = p.aux_split_in_two(cell, cell->length - 1);
p.element_to_cell_map[p.elements[new_cell->first]] = new_cell;
p.consistency_check();
/*
const bool prev_equal_to_first_path = info.equal_to_first_path;
const int prev_cmp_to_best_path = info.cmp_to_best_path;
*/
//assert(!(!info.equal_to_first_path && info.cmp_to_best_path < 0));
if(!first_path_info.empty())
{
refine_equal_to_first = info.equal_to_first_path;
if(refine_equal_to_first)
refine_first_path_subcertificate_end =
first_path_info[p.level-1].certificate_index +
first_path_info[p.level-1].subcertificate_length;
if(canonical)
{
refine_cmp_to_best = info.cmp_to_best_path;
if(refine_cmp_to_best == 0)
refine_best_path_subcertificate_end =
best_path_info[p.level-1].certificate_index +
best_path_info[p.level-1].subcertificate_length;
}
else
refine_cmp_to_best = -1;
}
/*
* Refine the new partition to equitable
*/
if(cell->length == 1)
refine_to_equitable(cell, new_cell);
else
refine_to_equitable(new_cell);
p.consistency_check();
#ifdef PRINT_SEARCH_TREE_DOT
fprintf(dotty_output, "\"n");
for(unsigned int i = 0; i < search_stack.size(); i++) {
fprintf(dotty_output, "%u", search_stack[i].split_element);
if(i < search_stack.size() - 1) fprintf(dotty_output, ".");
}
fprintf(dotty_output, "\"");
fprintf(dotty_output, " [label=\"");
fprintf(dotty_output, "%u",cell->first); /*p.print(dotty_output);*/
fprintf(dotty_output, "\"]");
if(!first_path_info.empty() && canonical && refine_cmp_to_best > 0) {
fprintf(dotty_output, "[color=green]");
}
fprintf(dotty_output, ";\n");
fprintf(dotty_output, "\"n");
for(unsigned int i = 0; i < search_stack.size() - 1; i++) {
fprintf(dotty_output, "%u", search_stack[i].split_element);
if(i < search_stack.size() - 2) fprintf(dotty_output, ".");
}
fprintf(dotty_output, "\" -> \"n");
for(unsigned int i = 0; i < search_stack.size(); i++) {
fprintf(dotty_output, "%u", search_stack[i].split_element);
if(i < search_stack.size() - 1) fprintf(dotty_output, ".");
}
fprintf(dotty_output, "\" [label=\"%d\"];\n", next_split_element);
#endif
/*
if(prev_cmp_to_best_path == 0 && refine_cmp_to_best < 0)
fprintf(stderr, "BP- ");
if(prev_cmp_to_best_path == 0 && refine_cmp_to_best > 0)
fprintf(stderr, "BP+ ");
*/
if(p.is_discrete())
{
/* Update statistics */
stats.nof_leaf_nodes++;
/*
if(stats.nof_leaf_nodes % 100 == 0) {
fprintf(stdout, "Nodes: %lu, Leafs: %lu, Bad: %lu\n",
stats.nof_nodes, stats.nof_leaf_nodes,
stats.nof_bad_nodes);
fflush(stdout);
}
*/
}
if(!first_path_info.empty())
{
/* We are no longer on the first path */
assert(best_path_info.size() > 0);
assert(certificate_current_path.size() >= certificate_index);
const unsigned int subcertificate_length =
certificate_current_path.size() - certificate_index;
if(refine_equal_to_first)
{
/* Was equal to the first path so far */
assert(first_path_info.size() >= p.level);
PathInfo &first_pinfo = first_path_info[p.level-1];
assert(first_pinfo.certificate_index == certificate_index);
if(subcertificate_length != first_pinfo.subcertificate_length)
{
refine_equal_to_first = false;
}
else if(first_pinfo.eqref_hash.cmp(eqref_hash) != 0)
{
refine_equal_to_first = false;
}
}
if(canonical && (refine_cmp_to_best == 0))
{
/* Was equal to the best path so far */
assert(best_path_info.size() >= p.level);
PathInfo &best_pinfo = best_path_info[p.level-1];
assert(best_pinfo.certificate_index == certificate_index);
if(subcertificate_length < best_pinfo.subcertificate_length)
{
refine_cmp_to_best = -1;
//fprintf(stderr, "BSCL- ");
}
else if(subcertificate_length > best_pinfo.subcertificate_length)
{
refine_cmp_to_best = 1;
//fprintf(stderr, "BSCL+ ");
}
else if(best_pinfo.eqref_hash.cmp(eqref_hash) > 0)
{
refine_cmp_to_best = -1;
//fprintf(stderr, "BHL- ");
}
else if(best_pinfo.eqref_hash.cmp(eqref_hash) < 0)
{
refine_cmp_to_best = 1;
//fprintf(stderr, "BHL+ ");
}
}
if(refine_equal_to_first == false &&
(!canonical || (refine_cmp_to_best < 0)))
{
/* Backtrack */
#ifdef PRINT_SEARCH_TREE_DOT
fprintf(dotty_output, "\"n");
for(unsigned int i = 0; i < search_stack.size(); i++) {
fprintf(dotty_output, "%u", search_stack[i].split_element);
if(i < search_stack.size() - 1) fprintf(dotty_output, ".");
}
fprintf(dotty_output, "\" [color=red];\n");
#endif
stats.nof_bad_nodes++;
if(search_stack.back().equal_to_first_path == true &&
p.level > all_same_level)
{
assert(all_same_level >= 1);
for(unsigned int i = all_same_level;
i < search_stack.size();
i++)
{
search_stack[i].equal_to_first_path = false;
}
}
while(!search_stack.empty())
{
p.level--;
LevelInfo &info2 = search_stack.back();
if(!(info2.equal_to_first_path == false &&
(!canonical || (info2.cmp_to_best_path < 0))))
break;
search_stack.pop_back();
}
continue;
}
}
#if defined(VERIFY_EQUITABLEDNESS)
/* The new partition should be equitable */
assert(is_equitable());
#endif
info.equal_to_first_path = refine_equal_to_first;
info.cmp_to_best_path = refine_cmp_to_best;
certificate_index = certificate_current_path.size();
search_stack.back().eqref_hash = eqref_hash;
search_stack.back().subcertificate_length =
certificate_index - info.certificate_index;
if(!p.is_discrete())
{
/*
* An internal, non-leaf node
*/
/* Build the next node info */
/* Find the next cell to be splitted */
assert(cell == p.element_to_cell_map[p.elements[info.split_cell_first]]);
Cell * const next_split_cell = find_next_cell_to_be_splitted(cell);
assert(next_split_cell);
/* Copy current info to the search stack */
search_stack.push_back(info);
LevelInfo &new_info = search_stack.back();
new_info.split_cell_first = next_split_cell->first;
new_info.split_element = -1;
new_info.certificate_index = certificate_index;
new_info.refinement_stack_size = p.refinement_stack.size();
new_info.long_prune_redundant.clear();
new_info.long_prune_begin = info.long_prune_begin;
continue;
}
/*
* A leaf node
*/
assert(certificate_index == certificate_size);
if(first_path_info.empty())
{
/* The first path, update first_path and best_path */
//fprintf(stdout, "Level %u: FIRST\n", p.level); fflush(stdout);
stats.nof_canupdates++;
/*
* Update labelings and their inverses
*/
update_labeling_and_its_inverse(first_path_labeling,
first_path_labeling_inv);
update_labeling_and_its_inverse(best_path_labeling,
best_path_labeling_inv);
/*
* Reset automorphism array
*/
reset_permutation(first_path_automorphism);
reset_permutation(best_path_automorphism);
/*
* Reset orbit information
*/
first_path_orbits.reset();
best_path_orbits.reset();
/*
* Reset group size
*/
stats.group_size.assign(1);
/*
* Reset all_same_level
*/
all_same_level = p.level;
/*
* Mark the current path to be the first and best one and save it
*/
const unsigned int base_size = search_stack.size();
assert(p.level == base_size);
best_path_info.clear();
//fprintf(stdout, " New base is: ");
for(unsigned int i = 0; i < base_size; i++) {
search_stack[i].in_first_path = true;
search_stack[i].in_best_path = true;
search_stack[i].equal_to_first_path = true;
search_stack[i].cmp_to_best_path = 0;
PathInfo path_info;
path_info.splitting_element = search_stack[i].split_element;
path_info.certificate_index = search_stack[i].certificate_index;
path_info.eqref_hash = search_stack[i].eqref_hash;
path_info.subcertificate_length = search_stack[i].subcertificate_length;
first_path_info.push_back(path_info);
best_path_info.push_back(path_info);
//fprintf(stdout, "%u ", search_stack[i].split_element);
}
//fprintf(stdout, "\n"); fflush(stdout);
certificate_first_path = certificate_current_path;
certificate_best_path = certificate_current_path;
refine_compare_certificate = true;
/*
* Backtrack to the previous level
*/
p.level--;
continue;
}
DEBUG_ASSERT(first_path_info.size() > 0);
//fprintf(stdout, "Level %u: LEAF %d %d\n", p.level, info.equal_to_first_path, info.cmp_to_best_path); fflush(stdout);
if(info.equal_to_first_path)
{
/*
* An automorphism found: aut[i] = elements[first_path_labeling[i]]
*/
assert(!info.in_first_path);
//fprintf(stdout, "A"); fflush(stdout);
#ifdef PRINT_SEARCH_TREE_DOT
fprintf(dotty_output, "\"n");
for(unsigned int i = 0; i < search_stack.size(); i++) {
fprintf(dotty_output, "%u", search_stack[i].split_element);
if(i < search_stack.size() - 1) fprintf(dotty_output, ".");
}
fprintf(dotty_output, "\" [color=blue];\n");
#endif
#if defined(DEBUG)
/* Verify that the automorphism is correctly built */
for(unsigned int i = 0; i < N; i++)
assert(first_path_automorphism[i] ==
p.elements[first_path_labeling[i]]);
#endif
#if defined(VERIFY_AUTOMORPHISMS)
/* Verify that it really is an automorphism */
assert(is_automorphism(first_path_automorphism));
#endif
long_prune_add_automorphism(first_path_automorphism);
/*
* Update orbit information
*/
update_orbit_information(first_path_orbits, first_path_automorphism);
/*
* Compute backjumping level
*/
unsigned int backjumping_level = 0;
for(unsigned int i = search_stack.size(); i > 0; i--) {
const unsigned int split_element =
search_stack[backjumping_level].split_element;
if(first_path_automorphism[split_element] != split_element)
break;
backjumping_level++;
}
assert(backjumping_level < p.level);
/*
* Go back to backjumping_level
*/
p.level = backjumping_level;
search_stack.resize(p.level + 1);
// if(write_automorphisms)
// {
// print_permutation(stdout, first_path_automorphism);
// fprintf(stdout, "\n");
// }
stats.nof_generators++;
continue;
}
assert(canonical);
assert(info.cmp_to_best_path >= 0);
if(info.cmp_to_best_path > 0)
{
/*
* A new, better representative found
*/
//fprintf(stdout, "Level %u: NEW BEST\n", p.level); fflush(stdout);
stats.nof_canupdates++;
/*
* Update canonical labeling and its inverse
*/
update_labeling_and_its_inverse(best_path_labeling,
best_path_labeling_inv);
/* Reset best path automorphism */
reset_permutation(best_path_automorphism);
/* Reset best path orbit structure */
best_path_orbits.reset();
/*
* Mark the current path to be the best one and save it
*/
const unsigned int base_size = search_stack.size();
assert(p.level == base_size);
best_path_info.clear();
//fprintf(stdout, " New base is: ");
for(unsigned int i = 0; i < base_size; i++) {
search_stack[i].cmp_to_best_path = 0;
search_stack[i].in_best_path = true;
PathInfo path_info;
path_info.splitting_element = search_stack[i].split_element;
path_info.certificate_index = search_stack[i].certificate_index;
path_info.eqref_hash = search_stack[i].eqref_hash;
path_info.subcertificate_length = search_stack[i].subcertificate_length;
best_path_info.push_back(path_info);
//fprintf(stdout, "%u ", search_stack[i].split_element);
}
certificate_best_path = certificate_current_path;
//fprintf(stdout, "\n"); fflush(stdout);
/*
* Backtrack to the previous level
*/
p.level--;
continue;
}
{
//fprintf(stderr, "BAUT ");
/*
* Equal to the previous best path
*/
#if defined(DEBUG)
/* Verify that the automorphism is correctly built */
for(unsigned int i = 0; i < N; i++)
assert(best_path_automorphism[i] ==
p.elements[best_path_labeling[i]]);
#endif
#if defined(VERIFY_AUTOMORPHISMS)
/* Verify that it really is an automorphism */
assert(is_automorphism(best_path_automorphism));
#endif
unsigned int gca_level_with_first = 0;
for(unsigned int i = search_stack.size(); i > 0; i--) {
if((int)first_path_info[gca_level_with_first].splitting_element !=
search_stack[gca_level_with_first].split_element)
break;
gca_level_with_first++;
}
assert(gca_level_with_first < p.level);
unsigned int gca_level_with_best = 0;
for(unsigned int i = search_stack.size(); i > 0; i--) {
if((int)best_path_info[gca_level_with_best].splitting_element !=
search_stack[gca_level_with_best].split_element)
break;
gca_level_with_best++;
}
assert(gca_level_with_best < p.level);
long_prune_add_automorphism(best_path_automorphism);
/*
* Update orbit information
*/
update_orbit_information(best_path_orbits, best_path_automorphism);
/*
* Update orbit information
*/
const unsigned int nof_old_orbits = first_path_orbits.nof_orbits();
update_orbit_information(first_path_orbits, best_path_automorphism);
if(nof_old_orbits != first_path_orbits.nof_orbits())
{
// if(write_automorphisms)
// {
// print_permutation(stdout, best_path_automorphism);
// fprintf(stdout, "\n");
// }
stats.nof_generators++;
}
/*
* Compute backjumping level
*/
unsigned int backjumping_level = p.level - 1;
if(!first_path_orbits.is_minimal_representative(search_stack[gca_level_with_first].split_element))
{
backjumping_level = gca_level_with_first;
/*fprintf(stderr, "bj1: %u %u\n", p.level, backjumping_level);*/
}
else
{
assert(!best_path_orbits.is_minimal_representative(search_stack[gca_level_with_best].split_element));
backjumping_level = gca_level_with_best;
/*fprintf(stderr, "bj2: %u %u\n", p.level, backjumping_level);*/
}
/* Backtrack */
search_stack.resize(backjumping_level + 1);
p.level = backjumping_level;
continue;
}
}
#ifdef PRINT_SEARCH_TREE_DOT
fprintf(dotty_output, "}\n");
fclose(dotty_output);
#endif
}
void AbstractGraph::find_automorphisms(Stats &stats)
{
search(false, stats);
if(first_path_labeling)
{
free(first_path_labeling);
first_path_labeling = 0;
}
if(best_path_labeling)
{
free(best_path_labeling);
best_path_labeling = 0;
}
}
const unsigned int *AbstractGraph::canonical_form(Stats &stats)
{
search(true, stats);
return best_path_labeling;
}
/*-------------------------------------------------------------------------
*
* Routines for undirected graphs
*
*-------------------------------------------------------------------------*/
Graph::Vertex::Vertex()
{
label = 1;
nof_edges = 0;
}
Graph::Vertex::~Vertex()
{
;
}
void Graph::Vertex::add_edge(const unsigned int other_vertex)
{
edges.push_back(other_vertex);
nof_edges++;
DEBUG_ASSERT(nof_edges == edges.size());
}
void Graph::Vertex::remove_duplicate_edges(bool * const duplicate_array)
{
for(std::vector<unsigned int>::iterator iter = edges.begin();
iter != edges.end(); )
{
const unsigned int dest_vertex = *iter;
if(duplicate_array[dest_vertex] == true)
{
/* A duplicate edge found! */
iter = edges.erase(iter);
nof_edges--;
DEBUG_ASSERT(nof_edges == edges.size());
}
else
{
/* Not seen earlier, mark as seen */
duplicate_array[dest_vertex] = true;
iter++;
}
}
/* Clear duplicate_array */
for(std::vector<unsigned int>::iterator iter = edges.begin();
iter != edges.end();
iter++)
{
duplicate_array[*iter] = false;
}
}
/*-------------------------------------------------------------------------
*
* Constructor and destructor for undirected graphs
*
*-------------------------------------------------------------------------*/
Graph::Graph(const unsigned int nof_vertices)
{
vertices.resize(nof_vertices);
sh = sh_flm;
}
Graph::~Graph()
{
;
}
unsigned int Graph::add_vertex(const unsigned int new_label)
{
const unsigned int new_vertex_num = vertices.size();
vertices.resize(new_vertex_num + 1);
vertices.back().label = new_label;
return new_vertex_num;
}
void Graph::add_edge(const unsigned int vertex1, const unsigned int vertex2)
{
//fprintf(stderr, "(%u,%u) ", vertex1, vertex2);
assert(vertex1 < vertices.size());
assert(vertex2 < vertices.size());
vertices[vertex1].add_edge(vertex2);
vertices[vertex2].add_edge(vertex1);
}
void Graph::change_label(const unsigned int vertex,
const unsigned int new_label)
{
assert(vertex < vertices.size());
vertices[vertex].label = new_label;
}
/*-------------------------------------------------------------------------
*
* Read graph in the DIMACS format
*
*-------------------------------------------------------------------------*/
// Graph *Graph::read_dimacs(FILE *fp)
// {
// Graph *g = 0;
// unsigned int nof_vertices, nof_edges;
// unsigned int line_num = 1;
// int c;
// /* read comments and problem line*/
// while(1) {
// c = getc(fp);
// if(c == 'c') {
// while((c = getc(fp)) != '\n') {
// if(c == EOF) {
// fprintf(stderr, "error in line %u: not in DIMACS format\n",
// line_num);
// goto error_exit;
// }
// }
// line_num++;
// continue;
// }
// if(c == 'p') {
// if(fscanf(fp, " edge %u %u\n", &nof_vertices, &nof_edges) != 2) {
// fprintf(stderr, "error in line %u: not in DIMACS format\n",
// line_num);
// goto error_exit; }
// line_num++;
// break;
// }
// fprintf(stderr, "error in line %u: not in DIMACS format\n", line_num);
// goto error_exit;
// }
// if(nof_vertices <= 0) {
// fprintf(stderr, "error: no vertices\n");
// goto error_exit;
// }
// #if 0
// if(nof_edges <= 0) {
// fprintf(stderr, "error: no edges\n");
// goto error_exit;
// }
// #endif
// if(bliss_verbose) {
// fprintf(bliss_verbstr, "Instance has %d vertices and %d edges\n",
// nof_vertices, nof_edges);
// fflush(bliss_verbstr);
// }
// g = new Graph(nof_vertices);
// //
// // Read vertex labels
// //
// if(bliss_verbose) {
// fprintf(bliss_verbstr, "Reading vertex labels...\n");
// fflush(bliss_verbstr); }
// while(1) {
// c = getc(fp);
// if(c != 'n') {
// ungetc(c, fp);
// break;
// }
// ungetc(c, fp);
// unsigned int vertex, label;
// if(fscanf(fp, "n %u %u\n", &vertex, &label) != 2) {
// fprintf(stderr, "error in line %u: not in DIMACS format\n",
// line_num);
// goto error_exit;
// }
// if(vertex > nof_vertices) {
// fprintf(stderr, "error in line %u: not in DIMACS format\n",
// line_num);
// goto error_exit;
// }
// line_num++;
// g->change_label(vertex - 1, label);
// }
// if(bliss_verbose) {
// fprintf(bliss_verbstr, "Done\n");
// fflush(bliss_verbstr); }
// //
// // Read edges
// //
// if(bliss_verbose) {
// fprintf(bliss_verbstr, "Reading edges...\n");
// fflush(bliss_verbstr); }
// for(unsigned i = 0; i < nof_edges; i++) {
// unsigned int from, to;
// if(fscanf(fp, "e %u %u\n", &from, &to) != 2) {
// fprintf(stderr, "error in line %u: not in DIMACS format\n",
// line_num);
// goto error_exit;
// }
// if(from > nof_vertices || to > nof_vertices) {
// fprintf(stderr, "error in line %u: not in DIMACS format\n",
// line_num);
// goto error_exit;
// }
// line_num++;
// g->add_edge(from - 1, to - 1);
// }
// if(bliss_verbose) {
// fprintf(bliss_verbstr, "Done\n");
// fflush(bliss_verbstr);
// }
// return g;
// error_exit:
// if(g)
// delete g;
// return 0;
// }
Graph *Graph::from_igraph(const igraph_t *graph) {
unsigned int nof_vertices= (unsigned int)igraph_vcount(graph);
unsigned int nof_edges= (unsigned int)igraph_ecount(graph);
Graph *g=new Graph(nof_vertices);
// for (unsigned int i=0; i<nof_vertices; i++) {
// g->change_label(i, i);
// }
for (unsigned int i=0; i<nof_edges; i++) {
g->add_edge((unsigned int)IGRAPH_FROM(graph, i),
(unsigned int)IGRAPH_TO(graph, i));
}
return g;
}
void Graph::print_dimacs(FILE *fp)
{
unsigned int nof_edges = 0;
for(unsigned int i = 0; i < get_nof_vertices(); i++)
{
Vertex &v = vertices[i];
for(std::vector<unsigned int>::const_iterator ei = v.edges.begin();
ei != v.edges.end();
ei++)
{
const unsigned int dest_i = *ei;
if(dest_i < i)
continue;
nof_edges++;
}
}
fprintf(fp, "p edge %u %u\n", get_nof_vertices(), nof_edges);
for(unsigned int i = 0; i < get_nof_vertices(); i++)
{
Vertex &v = vertices[i];
if(v.label != 1)
{
fprintf(fp, "n %u %u\n", i+1, v.label);
}
}
for(unsigned int i = 0; i < get_nof_vertices(); i++)
{
Vertex &v = vertices[i];
for(std::vector<unsigned int>::const_iterator ei = v.edges.begin();
ei != v.edges.end();
ei++)
{
const unsigned int dest_i = *ei;
if(dest_i < i)
continue;
fprintf(fp, "e %u %u\n", i+1, dest_i+1);
}
}
}
Graph *Graph::permute(const unsigned int *perm)
{
Graph *g = new Graph(get_nof_vertices());
for(unsigned int i = 0; i < get_nof_vertices(); i++)
{
Vertex &v = vertices[i];
Vertex &permuted_v = g->vertices[perm[i]];
permuted_v.label = v.label;
for(std::vector<unsigned int>::const_iterator ei = v.edges.begin();
ei != v.edges.end();
ei++)
{
const unsigned int dest_v = *ei;
permuted_v.add_edge(perm[dest_v]);
}
std::sort(permuted_v.edges.begin(), permuted_v.edges.end());
}
return g;
}
/*-------------------------------------------------------------------------
*
* Print graph in graphviz format
*
*-------------------------------------------------------------------------*/
void Graph::to_dot(const char *file_name)
{
FILE *fp = fopen(file_name, "w");
if(fp)
to_dot(fp);
fclose(fp);
}
void Graph::to_dot(FILE *fp)
{
remove_duplicate_edges();
fprintf(fp, "graph g {\n");
unsigned int vnum = 0;
for(std::vector<Vertex>::iterator vi = vertices.begin();
vi != vertices.end();
vi++, vnum++)
{
Vertex &v = *vi;
fprintf(fp, "v%u [label=\"%u:%u\"];\n", vnum, vnum, v.label);
for(std::vector<unsigned int>::const_iterator ei = v.edges.begin();
ei != v.edges.end();
ei++)
{
const unsigned int vnum2 = *ei;
if(vnum2 > vnum)
fprintf(fp, "v%u -- v%u\n", vnum, vnum2);
}
}
fprintf(fp, "}\n");
}
void Graph::remove_duplicate_edges()
{
bool *duplicate_array = (bool*)calloc(vertices.size(), sizeof(bool));
for(std::vector<Vertex>::iterator vi = vertices.begin();
vi != vertices.end();
vi++)
{
#ifdef EXPENSIVE_CONSISTENCY_CHECKS
for(unsigned int i = 0; i < vertices.size(); i++)
assert(duplicate_array[i] == false);
#endif
Vertex &v = *vi;
v.remove_duplicate_edges(duplicate_array);
}
free(duplicate_array);
}
/*-------------------------------------------------------------------------
*
* Partition independent invariants
*
*-------------------------------------------------------------------------*/
unsigned int Graph::label_invariant(Graph *g, unsigned int v)
{
DEBUG_ASSERT(v < g->vertices.size());
return g->vertices[v].label;
}
unsigned int Graph::degree_invariant(Graph *g, unsigned int v)
{
DEBUG_ASSERT(v < g->vertices.size());
DEBUG_ASSERT(g->vertices[v].edges.size() ==
g->vertices[v].nof_edges);
return g->vertices[v].nof_edges;
}
/*-------------------------------------------------------------------------
*
* Refine the partition p according to a partition independent invariant
*
*-------------------------------------------------------------------------*/
bool Graph::refine_according_to_invariant(unsigned int (*inv)(Graph * const g, unsigned int v))
{
bool refined = false;
for(Cell *cell = p.first_cell; cell; )
{
assert(cell->max_ival == 0);
assert(cell->max_ival_count == 0);
Cell * const next_cell = cell->next;
if(cell->length == 1)
{
cell = next_cell;
continue;
}
const unsigned int *ep = p.elements + cell->first;
for(unsigned int i = cell->length; i > 0; i--, ep++)
{
unsigned int ival = inv(this, *ep);
p.invariant_values[*ep] = ival;
if(ival > cell->max_ival) {
cell->max_ival = ival;
cell->max_ival_count = 1;
}
else if(ival == cell->max_ival) {
cell->max_ival_count++;
}
}
Cell * const last_new_cell = p.zplit_cell(cell, true);
refined = (last_new_cell != cell);
cell = next_cell;
}
return refined;
}
/*-------------------------------------------------------------------------
*
* Split the neighbourhood of a cell according to the equitable invariant
*
*-------------------------------------------------------------------------*/
void Graph::split_neighbourhood_of_cell(Cell * const cell)
{
DEBUG_ASSERT(neighbour_heap.is_empty());
DEBUG_ASSERT(cell->length > 1);
eqref_hash.update(cell->first);
eqref_hash.update(cell->length);
unsigned int *ep = p.elements + cell->first;
for(unsigned int i = cell->length; i > 0; i--)
{
const Vertex &v = vertices[*ep];
ep++;
std::vector<unsigned int>::const_iterator ei = v.edges.begin();
for(unsigned int j = v.nof_edges; j > 0; j--)
{
const unsigned int dest_vertex = *ei++;
Cell * const neighbour_cell = p.element_to_cell_map[dest_vertex];
if(neighbour_cell->length == 1)
continue;
const unsigned int ival = p.invariant_values[dest_vertex] + 1;
p.invariant_values[dest_vertex] = ival;
if(ival > neighbour_cell->max_ival) {
neighbour_cell->max_ival = ival;
neighbour_cell->max_ival_count = 1;
}
else if(ival == neighbour_cell->max_ival) {
neighbour_cell->max_ival_count++;
}
if(!neighbour_cell->in_neighbour_heap) {
neighbour_cell->in_neighbour_heap = true;
neighbour_heap.insert(neighbour_cell->first);
}
}
}
while(!neighbour_heap.is_empty())
{
const unsigned int start = neighbour_heap.remove();
Cell * const neighbour_cell = p.element_to_cell_map[p.elements[start]];
DEBUG_ASSERT(neighbour_cell->first == start);
DEBUG_ASSERT(neighbour_cell->in_neighbour_heap);
neighbour_cell->in_neighbour_heap = false;
DEBUG_ASSERT(neighbour_cell->length > 1);
DEBUG_ASSERT(neighbour_cell->max_ival >= 1);
DEBUG_ASSERT(neighbour_cell->max_ival_count >= 1);
eqref_hash.update(neighbour_cell->first);
eqref_hash.update(neighbour_cell->length);
eqref_hash.update(neighbour_cell->max_ival);
eqref_hash.update(neighbour_cell->max_ival_count);
Cell * const last_new_cell = p.zplit_cell(neighbour_cell, true);
/* Update hash */
const Cell *c = neighbour_cell;
while(1)
{
eqref_hash.update(c->first);
eqref_hash.update(c->length);
if(c == last_new_cell)
break;
c = c->next;
}
}
}
bool Graph::split_neighbourhood_of_unit_cell(Cell * const unit_cell)
{
DEBUG_ASSERT(neighbour_heap.is_empty());
DEBUG_ASSERT(unit_cell->length == 1);
DEBUG_ASSERT(p.element_to_cell_map[p.elements[unit_cell->first]] == unit_cell);
DEBUG_ASSERT(p.in_pos[p.elements[unit_cell->first]] ==
p.elements + unit_cell->first);
eqref_hash.update(0x87654321);
eqref_hash.update(unit_cell->first);
eqref_hash.update(1);
const Vertex &v = vertices[p.elements[unit_cell->first]];
std::vector<unsigned int>::const_iterator ei = v.edges.begin();
for(unsigned int j = v.nof_edges; j > 0; j--)
{
const unsigned int dest_vertex = *ei++;
Cell * const neighbour_cell = p.element_to_cell_map[dest_vertex];
DEBUG_ASSERT(*p.in_pos[dest_vertex] == dest_vertex);
if(neighbour_cell->length == 1) {
DEBUG_ASSERT(!neighbour_cell->in_neighbour_heap);
if(in_search) {
neighbour_cell->in_neighbour_heap = true;
neighbour_heap.insert(neighbour_cell->first);
}
continue;
}
if(!neighbour_cell->in_neighbour_heap) {
neighbour_cell->in_neighbour_heap = true;
neighbour_heap.insert(neighbour_cell->first);
}
neighbour_cell->max_ival_count++;
DEBUG_ASSERT(neighbour_cell->max_ival_count <= neighbour_cell->length);
unsigned int * const swap_position =
p.elements + neighbour_cell->first + neighbour_cell->length -
neighbour_cell->max_ival_count;
DEBUG_ASSERT(p.in_pos[dest_vertex] <= swap_position);
*p.in_pos[dest_vertex] = *swap_position;
p.in_pos[*swap_position] = p.in_pos[dest_vertex];
*swap_position = dest_vertex;
p.in_pos[dest_vertex] = swap_position;
}
while(!neighbour_heap.is_empty())
{
const unsigned int start = neighbour_heap.remove();
Cell *neighbour_cell = p.element_to_cell_map[p.elements[start]];
DEBUG_ASSERT(neighbour_cell->in_neighbour_heap);
neighbour_cell->in_neighbour_heap = false;
#ifdef DEBUG
assert(neighbour_cell->first == start);
if(neighbour_cell->length == 1) {
assert(neighbour_cell->max_ival_count == 0);
} else {
assert(neighbour_cell->max_ival_count > 0);
assert(neighbour_cell->max_ival_count <= neighbour_cell->length);
}
#endif
eqref_hash.update(neighbour_cell->first);
eqref_hash.update(neighbour_cell->length);
eqref_hash.update(neighbour_cell->max_ival_count);
if(neighbour_cell->length > 1 &&
neighbour_cell->max_ival_count != neighbour_cell->length) {
p.consistency_check();
Cell * const new_cell = p.aux_split_in_two(neighbour_cell, neighbour_cell->length - neighbour_cell->max_ival_count);
unsigned int *ep = p.elements + new_cell->first;
unsigned int * const lp = p.elements+new_cell->first+new_cell->length;
while(ep < lp) {
DEBUG_ASSERT(p.in_pos[*ep] == ep);
p.element_to_cell_map[*ep] = new_cell;
ep++;
}
neighbour_cell->max_ival_count = 0;
p.consistency_check();
/* update hash */
eqref_hash.update(neighbour_cell->first);
eqref_hash.update(neighbour_cell->length);
eqref_hash.update(0);
eqref_hash.update(new_cell->first);
eqref_hash.update(new_cell->length);
eqref_hash.update(1);
/* Add cells in splitting_queue */
DEBUG_ASSERT(!new_cell->in_splitting_queue);
if(neighbour_cell->in_splitting_queue) {
/* Both cells must be included in splitting_queue in order
to have refinement to equitable partition */
p.add_in_splitting_queue(new_cell);
} else {
Cell *min_cell, *max_cell;
if(neighbour_cell->length <= new_cell->length) {
min_cell = neighbour_cell;
max_cell = new_cell;
} else {
min_cell = new_cell;
max_cell = neighbour_cell;
}
/* Put the smaller cell in splitting_queue */
p.add_in_splitting_queue(min_cell);
if(max_cell->length == 1) {
/* Put the "larger" cell also in splitting_queue */
p.add_in_splitting_queue(max_cell);
}
}
/* Update pointer for certificate generation */
neighbour_cell = new_cell;
}
else
neighbour_cell->max_ival_count = 0;
/*
* Build certificate if required
*/
if(in_search)
{
for(unsigned int i = neighbour_cell->first,
j = neighbour_cell->length,
c_index = certificate_current_path.size();
j > 0;
j--, i++, c_index += 2)
{
if(refine_compare_certificate)
{
if(refine_equal_to_first)
{
if(c_index >= refine_first_path_subcertificate_end)
refine_equal_to_first = false;
else if(certificate_first_path[c_index] !=
unit_cell->first)
refine_equal_to_first = false;
else if(certificate_first_path[c_index+1] != i)
refine_equal_to_first = false;
}
if(refine_cmp_to_best == 0)
{
if(c_index >= refine_best_path_subcertificate_end)
{
refine_cmp_to_best = 1;
}
else if(unit_cell->first>certificate_best_path[c_index])
{
refine_cmp_to_best = 1;
}
else if(unit_cell->first<certificate_best_path[c_index])
{
refine_cmp_to_best = -1;
}
else if(i > certificate_best_path[c_index+1])
{
refine_cmp_to_best = 1;
}
else if(i < certificate_best_path[c_index+1])
{
refine_cmp_to_best = -1;
}
}
if((refine_equal_to_first == false) &&
(refine_cmp_to_best < 0))
goto worse_exit;
}
certificate_current_path.push_back(unit_cell->first);
certificate_current_path.push_back(i);
}
} /* if(in_search) */
} /* while(!neighbour_heap.is_empty()) */
return false;
worse_exit:
while(!neighbour_heap.is_empty())
{
const unsigned int start = neighbour_heap.remove();
Cell * const neighbour_cell = p.element_to_cell_map[p.elements[start]];
DEBUG_ASSERT(neighbour_cell->in_neighbour_heap);
neighbour_cell->in_neighbour_heap = false;
neighbour_cell->max_ival_count = 0;
}
return true;
}
/*-------------------------------------------------------------------------
*
* Check whether the current partition p is equitable
* Slow: use only for debugging purposes
* Side effect: resets max_ival and max_ival_count fields in cells
*
*-------------------------------------------------------------------------*/
bool Graph::is_equitable()
{
bool result = true;
/*
* Max ival and max_ival_count are used for counting purposes,
* they should be reset...
*/
for(Cell *cell = p.first_cell; cell; cell = cell->next)
{
assert(cell->prev_next_ptr && *(cell->prev_next_ptr) == cell);
assert(cell->max_ival == 0);
assert(cell->max_ival_count == 0);
}
for(Cell *cell = p.first_cell; cell; cell = cell->next)
{
if(cell->length == 1)
continue;
unsigned int *ep = p.elements + cell->first;
Vertex &first_vertex = vertices[*ep++];
/* Count edges of the first vertex for cells in max_ival */
std::vector<unsigned int>::const_iterator ei = first_vertex.edges.begin();
for(unsigned int j = first_vertex.nof_edges; j > 0; j--)
{
p.element_to_cell_map[*ei++]->max_ival++;
}
/* Count and compare edges of the other vertices */
for(unsigned int i = cell->length; i > 1; i--)
{
Vertex &vertex = vertices[*ep++];
std::vector<unsigned int>::const_iterator ei = vertex.edges.begin();
for(unsigned int j = vertex.nof_edges; j > 0; j--)
{
p.element_to_cell_map[*ei++]->max_ival_count++;
}
for(Cell *cell2 = p.first_cell; cell2; cell2 = cell2->next)
{
if(cell2->max_ival != cell2->max_ival_count)
{
result = false;
goto done;
}
cell2->max_ival_count = 0;
}
}
/* Reset max_ival */
for(Cell *cell2 = p.first_cell; cell2; cell2 = cell2->next)
{
cell2->max_ival = 0;
assert(cell2->max_ival_count == 0);
}
}
done:
for(Cell *cell = p.first_cell; cell; cell = cell->next)
{
cell->max_ival = 0;
cell->max_ival_count = 0;
}
return result;
}
/*-------------------------------------------------------------------------
*
* Build the initial equitable partition
*
*-------------------------------------------------------------------------*/
void Graph::make_initial_equitable_partition()
{
refine_according_to_invariant(&label_invariant);
p.clear_splitting_queue();
//p.print_signature(stderr); fprintf(stderr, "\n");
refine_according_to_invariant(°ree_invariant);
p.clear_splitting_queue();
//p.print_signature(stderr); fprintf(stderr, "\n");
/* To do: add loop invariant */
refine_to_equitable();
p.refinement_stack.clean();
//p.print_signature(stderr); fprintf(stderr, "\n");
}
/*-------------------------------------------------------------------------
*
* Find the next cell to be splitted
*
*-------------------------------------------------------------------------*/
Cell *Graph::find_next_cell_to_be_splitted(Cell *cell)
{
assert(!p.is_discrete());
switch(sh) {
case sh_f:
return sh_first(cell);
case sh_fs:
return sh_first_smallest(cell);
case sh_fl:
return sh_first_largest(cell);
case sh_fm:
return sh_first_max_neighbours(cell);
case sh_fsm:
return sh_first_smallest_max_neighbours(cell);
case sh_flm:
return sh_first_largest_max_neighbours(cell);
default:
assert(false && "Unknown splitting heuristics");
return 0;
}
}
/* First nonsingleton cell */
Cell *Graph::sh_first(Cell *cell)
{
return p.first_nonsingleton_cell;
}
/* First smallest nonsingleton cell. */
Cell *Graph::sh_first_smallest(Cell *cell)
{
Cell *best_cell = 0;
unsigned int best_size = UINT_MAX;
for(cell = p.first_nonsingleton_cell; cell; cell = cell->next_nonsingleton)
{
assert(cell->length > 1);
if(cell->length < best_size)
{
best_size = cell->length;
best_cell = cell;
}
}
assert(best_cell);
return best_cell;
}
/* First largest nonsingleton cell. */
Cell *Graph::sh_first_largest(Cell *cell)
{
Cell *best_cell = 0;
unsigned int best_size = 0;
for(cell = p.first_nonsingleton_cell; cell; cell = cell->next_nonsingleton)
{
assert(cell->length > 1);
if(cell->length > best_size)
{
best_size = cell->length;
best_cell = cell;
}
}
assert(best_cell);
return best_cell;
}
/* First nonsingleton cell with max number of neighbouring
* nonsingleton cells.
* Assumes that the partition p is equitable.
* Messes up in_neighbour_heap and max_ival fields of cells
* (assumes they are false/0).
*/
Cell *Graph::sh_first_max_neighbours(Cell *cell)
{
Cell *best_cell = 0;
int best_value = -1;
for(cell = p.first_nonsingleton_cell; cell; cell = cell->next_nonsingleton)
{
assert(cell->length > 1);
const Vertex &v = vertices[p.elements[cell->first]];
std::vector<unsigned int>::const_iterator ei = v.edges.begin();
std::list<Cell*> neighbour_cells_visited;
for(unsigned int j = v.nof_edges; j > 0; j--)
{
const unsigned int dest_vertex = *ei++;
Cell * const neighbour_cell = p.element_to_cell_map[dest_vertex];
if(neighbour_cell->length == 1)
continue;
neighbour_cell->max_ival++;
if(neighbour_cell->in_neighbour_heap)
continue;
neighbour_cell->in_neighbour_heap = true;
neighbour_cells_visited.push_back(neighbour_cell);
}
int value = 0;
while(!neighbour_cells_visited.empty())
{
Cell * const neighbour_cell = neighbour_cells_visited.front();
neighbour_cells_visited.pop_front();
assert(neighbour_cell->in_neighbour_heap);
neighbour_cell->in_neighbour_heap = false;
if(neighbour_cell->max_ival != neighbour_cell->length)
value++;
neighbour_cell->max_ival = 0;
}
if(value > best_value)
{
best_value = value;
best_cell = cell;
}
}
assert(best_cell);
return best_cell;
}
/* First smallest nonsingleton cell with max number of neighbouring
* nonsingleton cells.
* Assumes that the partition p is equitable.
* Messes up in_neighbour_heap and max_ival fields of cells
* (assumes they are false).
*/
Cell *Graph::sh_first_smallest_max_neighbours(Cell *cell)
{
Cell *best_cell = 0;
int best_value = -1;
int best_size = INT_MAX;
for(cell = p.first_nonsingleton_cell; cell; cell = cell->next_nonsingleton)
{
assert(cell->length > 1);
const Vertex &v = vertices[p.elements[cell->first]];
std::vector<unsigned int>::const_iterator ei = v.edges.begin();
std::list<Cell*> neighbour_cells_visited;
for(unsigned int j = v.nof_edges; j > 0; j--)
{
const unsigned int dest_vertex = *ei++;
Cell * const neighbour_cell = p.element_to_cell_map[dest_vertex];
if(neighbour_cell->length == 1)
continue;
neighbour_cell->max_ival++;
if(neighbour_cell->in_neighbour_heap)
continue;
neighbour_cell->in_neighbour_heap = true;
neighbour_cells_visited.push_back(neighbour_cell);
}
int value = 0;
while(!neighbour_cells_visited.empty())
{
Cell * const neighbour_cell = neighbour_cells_visited.front();
neighbour_cells_visited.pop_front();
assert(neighbour_cell->in_neighbour_heap);
neighbour_cell->in_neighbour_heap = false;
if(neighbour_cell->max_ival != neighbour_cell->length)
value++;
neighbour_cell->max_ival = 0;
}
if((value > best_value) ||
(value == best_value && (int)cell->length < best_size))
{
best_value = value;
best_size = cell->length;
best_cell = cell;
}
}
assert(best_cell);
return best_cell;
}
/* First largest nonsingleton cell with max number of neighbouring
* nonsingleton cells.
* Assumes that the partition p is equitable.
* Messes up in_neighbour_heap and max_ival fields of cells
* (assumes they are false/0).
*/
Cell *Graph::sh_first_largest_max_neighbours(Cell *cell)
{
Cell *best_cell = 0;
int best_value = -1;
int best_size = -1;
for(cell = p.first_nonsingleton_cell; cell; cell = cell->next_nonsingleton)
{
assert(cell->length > 1);
const Vertex &v = vertices[p.elements[cell->first]];
std::vector<unsigned int>::const_iterator ei = v.edges.begin();
std::list<Cell*> neighbour_cells_visited;
for(unsigned int j = v.nof_edges; j > 0; j--)
{
const unsigned int dest_vertex = *ei++;
Cell * const neighbour_cell = p.element_to_cell_map[dest_vertex];
if(neighbour_cell->length == 1)
continue;
neighbour_cell->max_ival++;
if(neighbour_cell->in_neighbour_heap)
continue;
neighbour_cell->in_neighbour_heap = true;
neighbour_cells_visited.push_back(neighbour_cell);
}
int value = 0;
while(!neighbour_cells_visited.empty())
{
Cell * const neighbour_cell = neighbour_cells_visited.front();
neighbour_cells_visited.pop_front();
assert(neighbour_cell->in_neighbour_heap);
neighbour_cell->in_neighbour_heap = false;
if(neighbour_cell->max_ival != neighbour_cell->length)
value++;
neighbour_cell->max_ival = 0;
}
if((value > best_value) ||
(value == best_value && (int)cell->length > best_size))
{
best_value = value;
best_size = cell->length;
best_cell = cell;
}
}
assert(best_cell);
return best_cell;
}
/*-------------------------------------------------------------------------
*
* Initialize the certificate size and memory
*
*-------------------------------------------------------------------------*/
void Graph::initialize_certificate()
{
certificate_size = 0;
for(Cell *cell = p.first_cell; cell; cell = cell->next)
{
if(cell->length > 1) {
certificate_size +=
vertices[p.elements[cell->first]].nof_edges * 2 * cell->length;
}
}
//if(certificate)
// free(certificate);
//certificate = (unsigned int*)malloc(certificate_size * sizeof(unsigned int));
certificate_index = 0;
certificate_current_path.clear();
certificate_first_path.clear();
certificate_best_path.clear();
}
/*-------------------------------------------------------------------------
*
* Check whether perm is an automorphism
*
*-------------------------------------------------------------------------*/
bool Graph::is_automorphism(unsigned int * const perm)
{
std::set<unsigned int, std::less<unsigned int> > edges1;
std::set<unsigned int, std::less<unsigned int> > edges2;
bool result = true;
for(unsigned int i = 0; i < vertices.size(); i++)
{
Vertex &v1 = vertices[i];
edges1.clear();
for(std::vector<unsigned int>::iterator ei = v1.edges.begin();
ei != v1.edges.end();
ei++)
edges1.insert(perm[*ei]);
Vertex &v2 = vertices[perm[i]];
edges2.clear();
for(std::vector<unsigned int>::iterator ei = v2.edges.begin();
ei != v2.edges.end();
ei++)
edges2.insert(*ei);
if(!(edges1 == edges2))
{
result = false;
goto done;
}
}
done:
return result;
}
}
| 26.353483 | 124 | 0.626589 | FlyerMaxwell |
a659a259e67a8172c5a4ac3047508f60291a54f2 | 433 | cpp | C++ | Ex4_3_master.cpp | DF4IAH/OpenMP | 9eb4c429d3d9da799fe0a5767d91b2c654358bdf | [
"MIT"
] | null | null | null | Ex4_3_master.cpp | DF4IAH/OpenMP | 9eb4c429d3d9da799fe0a5767d91b2c654358bdf | [
"MIT"
] | null | null | null | Ex4_3_master.cpp | DF4IAH/OpenMP | 9eb4c429d3d9da799fe0a5767d91b2c654358bdf | [
"MIT"
] | null | null | null | #include <stdio.h>
#include "omp.h"
const int NUM_SLICES = 16;
const int NUM_THREADS = 4;
int main(void)
{
long id;
omp_set_num_threads(NUM_THREADS);
#pragma omp parallel
{
id = omp_get_thread_num();
#pragma omp master
{
id += 100;
printf("master: id = %ld\r\n", id);
}
//#pragma omp barrier
id = omp_get_thread_num();
printf("id = %ld\r\n", id);
}
printf("done.\n");
return 0;
}
| 13.121212 | 38 | 0.591224 | DF4IAH |
a65adb063771c6bfc88c0a3bd474e16cb971570e | 3,065 | cpp | C++ | 03_elementaryDataStructure/stack/cpp/StackLinkedListMain.cpp | haxpor/algo-cpp-c | 5c88523072701765ad126d0a0946e2e76a09f3bb | [
"MIT"
] | 1 | 2019-11-17T09:03:30.000Z | 2019-11-17T09:03:30.000Z | 03_elementaryDataStructure/stack/cpp/StackLinkedListMain.cpp | haxpor/algocpp-study | 5c88523072701765ad126d0a0946e2e76a09f3bb | [
"MIT"
] | null | null | null | 03_elementaryDataStructure/stack/cpp/StackLinkedListMain.cpp | haxpor/algocpp-study | 5c88523072701765ad126d0a0946e2e76a09f3bb | [
"MIT"
] | null | null | null | #include <iostream>
#include <sstream>
#include "StackLinkedList.h"
/** compile-time logging functions for convenient **/
template<typename Arg>
constexpr void LOG(Arg && arg) {
std::cout << arg << "\n";
}
template<typename Arg1, typename Arg2>
constexpr void LOG2(Arg1 && arg1, Arg2 && arg2) {
std::cout << arg1 << arg2 << "\n";
}
template<typename Arg1, typename Arg2, typename Arg3>
constexpr void LOG3(Arg1 && arg1, Arg2 && arg2, Arg3 && arg3) {
std::cout << arg1 << arg2 << arg3 << "\n";
}
/** end of logging functions **/
struct Data {
int val;
inline friend std::ostream& operator <<(std::ostream& out, const Data& d) {
out << "val: " << d.val;
return out;
}
};
/**
* Convert fully parenthesized infix expression to postfix expression.
*/
std::string ConvertToPostfix(const std::string& infix) {
std::stringstream ss;
StackLinkedList<char> ts;
for (auto it = infix.begin(); it != infix.end(); ++it) {
char c = *it;
if (c == '+' ||
c == '-' ||
c == '*') {
ts.Push(c);
}
else if (c >= '0' && c <= '9') {
ss << c << " ";
}
else if (c == ')') {
ss << ts.Pop() << " ";
// if it's the last element
if (it == infix.end() - 1) {
while (!ts.IsEmpty()) {
ss << ts.Pop();
}
}
}
}
// usually if you check pointer address of ss.str() via std::addressof()
// and with normal compilation flags of gcc, it will be the same externally
// at the call site. This is because of RVO (return value optimization).
// We can disable it via -fno-elide-constructors
return ss.str();
}
/**
* Compute result from value from postfix expression.
*/
int ComputePostfix(const std::string& postfix) {
StackLinkedList<int> ts;
for (const char c : postfix) {
if (c >= '0' && c <= '9') {
ts.Push(static_cast<int>(c-'0'));
}
else if (c == '+') {
ts.Push((ts.Pop() + ts.Pop()));
}
else if (c == '-') {
ts.Push((ts.Pop() - ts.Pop()));
}
else if (c == '*') {
ts.Push((ts.Pop() * ts.Pop()));
}
}
return ts.Pop();
}
int main() {
/** Testing section **/
StackLinkedList<int> s;
s.Push(1);
s.Push(2);
LOG(s.Pop());
LOG2(std::boolalpha, s.IsEmpty());
LOG(s.Pop());
LOG2(std::boolalpha, s.IsEmpty());
StackLinkedList<Data> s2;
s2.Push(Data {100});
s2.Push(Data {200});
LOG(s2.Pop());
LOG2(std::boolalpha, s.IsEmpty());
LOG(s2.Pop());
LOG2(std::boolalpha, s.IsEmpty());
std::cout << "\n";
/** Infix/Postfix and its calculation **/
const std::string infix ( "5 * (((9+8) * (4*6)) + 7)" );
const std::string postfix = ConvertToPostfix(infix);
LOG2("Postfix: ", postfix);
int result = ComputePostfix(postfix);
LOG2("Result: ", result);
std::cout << std::endl;
return 0;
}
| 24.133858 | 79 | 0.511256 | haxpor |
a65b6fcd8ed428a1a9afe0fe9ae9b161228354b7 | 966 | cpp | C++ | UESTC/2505.cpp | HeRaNO/OI-ICPC-Codes | 4a4639cd3e347b472520065ca6ab8caadde6906d | [
"MIT"
] | 18 | 2019-01-01T13:16:59.000Z | 2022-02-28T04:51:50.000Z | UESTC/2505.cpp | HeRaNO/OI-ICPC-Codes | 4a4639cd3e347b472520065ca6ab8caadde6906d | [
"MIT"
] | null | null | null | UESTC/2505.cpp | HeRaNO/OI-ICPC-Codes | 4a4639cd3e347b472520065ca6ab8caadde6906d | [
"MIT"
] | 5 | 2019-09-13T08:48:17.000Z | 2022-02-19T06:59:03.000Z | #include <bits/stdc++.h>
using namespace std;
unordered_map <long long,long long> mp;
int T,a,m,b;
void exgcd(long long a,long long b,long long &x,long long &y)
{
if (!b){x=1;y=0;return ;}
exgcd(b,a%b,y,x);y-=x*(a/b);return ;
}
inline long long inv(long long a,long long m)
{
long long x,y;exgcd(a,m,x,y);
return (x+m)%m;
}
long long exBSGS(long long a,long long b,long long M)
{
if (b==1) return 0;
long long w=1;int c=0;
for (long long d;(d=__gcd(a,M))!=1;)
{
if (b%d) return -1;
b/=d;M/=d;++c;w=w*(a/d)%M;
if (w==b) return c;
}
b=b*inv(w,M)%M;mp.clear();
long long t=1LL,r=b,x,y,B=ceil(sqrt(M));
for (long long i=0;i<B;i++,t=t*a%M) if (!mp.count(t)) mp.insert({t,i});
t=inv(t,M);
for (long long i=0;i<B;i++,b=b*t%M) if (mp.count(b)) return i*B+mp[b]+c;
return -1LL;
}
int main()
{
scanf("%d",&T);
while (T--)
{
scanf("%d %d %d",&a,&b,&m);
int ret=exBSGS(a,b,m);
if (!~ret) puts("QAQ");
else printf("%d\n",ret);
}
return 0;
} | 20.125 | 73 | 0.569358 | HeRaNO |
a65eb8d53a4509a7318b92b9a0b2fc2a257836b9 | 8,704 | cpp | C++ | src/rviz/view_controller.cpp | fftn/rviz | a9de85555b040f625b0bac5d7c3eba3be9e8fa42 | [
"BSD-3-Clause-Clear"
] | null | null | null | src/rviz/view_controller.cpp | fftn/rviz | a9de85555b040f625b0bac5d7c3eba3be9e8fa42 | [
"BSD-3-Clause-Clear"
] | null | null | null | src/rviz/view_controller.cpp | fftn/rviz | a9de85555b040f625b0bac5d7c3eba3be9e8fa42 | [
"BSD-3-Clause-Clear"
] | null | null | null | /*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. 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 <QColor>
#include <QFont>
#include <QKeyEvent>
#include <OgreCamera.h>
#include <OgreSceneManager.h>
#include <OgreSceneNode.h>
#include <rviz/display_context.h>
#include <rviz/frame_manager.h>
#include <rviz/load_resource.h>
#include <rviz/properties/enum_property.h>
#include <rviz/properties/float_property.h>
#include <rviz/properties/bool_property.h>
#include <rviz/render_panel.h>
#include <rviz/selection/selection_manager.h>
#include <rviz/view_manager.h>
#include <rviz/viewport_mouse_event.h>
#include <rviz/window_manager_interface.h>
#include <rviz/ogre_helpers/render_system.h>
#include <rviz/view_controller.h>
namespace rviz
{
ViewController::ViewController()
: context_(nullptr), camera_(nullptr), is_active_(false), type_property_(nullptr)
{
near_clip_property_ =
new FloatProperty("Near Clip Distance", 0.01f,
"Anything closer to the camera than this threshold will not get rendered.", this,
SLOT(updateNearClipDistance()));
near_clip_property_->setMin(0.001);
near_clip_property_->setMax(10000);
stereo_enable_ = new BoolProperty("Enable Stereo Rendering", true,
"Render the main view in stereo if supported."
" On Linux this requires a recent version of Ogre and"
" an NVIDIA Quadro card with 3DVision glasses.",
this, SLOT(updateStereoProperties()));
stereo_eye_swap_ = new BoolProperty("Swap Stereo Eyes", false,
"Swap eyes if the monitor shows the left eye on the right.",
stereo_enable_, SLOT(updateStereoProperties()), this);
stereo_eye_separation_ =
new FloatProperty("Stereo Eye Separation", 0.06f, "Distance between eyes for stereo rendering.",
stereo_enable_, SLOT(updateStereoProperties()), this);
stereo_focal_distance_ = new FloatProperty("Stereo Focal Distance", 1.0f,
"Distance from eyes to screen. For stereo rendering.",
stereo_enable_, SLOT(updateStereoProperties()), this);
invert_z_ =
new BoolProperty("Invert Z Axis", false, "Invert camera's Z axis for Z-down environments/models.",
this, SLOT(updateStereoProperties()));
}
void ViewController::initialize(DisplayContext* context)
{
context_ = context;
std::stringstream ss;
static int count = 0;
ss << "ViewControllerCamera" << count++;
camera_ = context_->getSceneManager()->createCamera(ss.str());
context_->getSceneManager()->getRootSceneNode()->attachObject(camera_);
setValue(formatClassId(getClassId()));
setReadOnly(true);
// Do subclass initialization.
onInitialize();
cursor_ = getDefaultCursor();
standard_cursors_[Default] = getDefaultCursor();
standard_cursors_[Rotate2D] = makeIconCursor("package://rviz/icons/rotate.svg");
standard_cursors_[Rotate3D] = makeIconCursor("package://rviz/icons/rotate_cam.svg");
standard_cursors_[MoveXY] = makeIconCursor("package://rviz/icons/move2d.svg");
standard_cursors_[MoveZ] = makeIconCursor("package://rviz/icons/move_z.svg");
standard_cursors_[Zoom] = makeIconCursor("package://rviz/icons/zoom.svg");
standard_cursors_[Crosshair] = makeIconCursor("package://rviz/icons/crosshair.svg");
updateNearClipDistance();
updateStereoProperties();
if (!RenderSystem::get()->isStereoSupported())
{
stereo_enable_->setBool(false);
stereo_enable_->hide();
}
}
ViewController::~ViewController()
{
context_->getSceneManager()->destroyCamera(camera_);
}
QString ViewController::formatClassId(const QString& class_id)
{
QStringList id_parts = class_id.split("/");
if (id_parts.size() != 2)
{
// Should never happen with pluginlib class ids, which are
// formatted like "package_name/class_name". Not worth crashing
// over though.
return class_id;
}
else
{
return id_parts[1] + " (" + id_parts[0] + ")";
}
}
QVariant ViewController::getViewData(int column, int role) const
{
if (role == Qt::TextColorRole)
return QVariant();
if (is_active_)
{
switch (role)
{
case Qt::FontRole:
{
QFont font;
font.setBold(true);
return font;
}
}
}
return Property::getViewData(column, role);
}
Qt::ItemFlags ViewController::getViewFlags(int column) const
{
if (is_active_)
{
return Property::getViewFlags(column);
}
else
{
return Property::getViewFlags(column) | Qt::ItemIsDragEnabled;
}
}
void ViewController::activate()
{
is_active_ = true;
onActivate();
}
void ViewController::emitConfigChanged()
{
Q_EMIT configChanged();
}
void ViewController::load(const Config& config)
{
// Load the name by hand.
QString name;
if (config.mapGetString("Name", &name))
{
setName(name);
}
// Load all sub-properties the same way the base class does.
Property::load(config);
}
void ViewController::save(Config config) const
{
config.mapSetValue("Class", getClassId());
config.mapSetValue("Name", getName());
Property::save(config);
}
void ViewController::handleKeyEvent(QKeyEvent* event, RenderPanel* panel)
{
if (event->key() == Qt::Key_F && panel->getViewport() && context_->getSelectionManager())
{
QPoint mouse_rel_panel = panel->mapFromGlobal(QCursor::pos());
Ogre::Vector3 point_rel_world; // output of get3DPoint().
if (context_->getSelectionManager()->get3DPoint(panel->getViewport(), mouse_rel_panel.x(),
mouse_rel_panel.y(), point_rel_world))
{
lookAt(point_rel_world);
}
}
if (event->key() == Qt::Key_Z)
{
reset();
}
}
void ViewController::setCursor(CursorType cursor_type)
{
cursor_ = standard_cursors_[cursor_type];
}
void ViewController::lookAt(float x, float y, float z)
{
Ogre::Vector3 point(x, y, z);
lookAt(point);
}
void ViewController::setStatus(const QString& message)
{
if (context_)
{
context_->setStatus(message);
}
}
void ViewController::updateNearClipDistance()
{
float n = near_clip_property_->getFloat();
camera_->setNearClipDistance(n);
}
void ViewController::updateStereoProperties()
{
if (stereo_enable_->getBool())
{
float focal_dist = stereo_focal_distance_->getFloat();
float eye_sep = stereo_eye_swap_->getBool() ? -stereo_eye_separation_->getFloat() :
stereo_eye_separation_->getFloat();
camera_->setFrustumOffset(0.5f * eye_sep, 0.0f);
camera_->setFocalLength(focal_dist);
stereo_eye_swap_->show();
stereo_eye_separation_->show();
stereo_focal_distance_->show();
}
else
{
camera_->setFrustumOffset(0.0f, 0.0f);
camera_->setFocalLength(1.0f);
stereo_eye_swap_->hide();
stereo_eye_separation_->hide();
stereo_focal_distance_->hide();
}
}
void ViewController::updateInvertZAxis()
{
// We don't seem to need to do anything here.
}
} // end namespace rviz
| 31.422383 | 105 | 0.683364 | fftn |
a661edb27e91f66dde83c0237b810901875bc92b | 16,823 | cpp | C++ | bbs/diredit.cpp | uriel1998/wwiv | 623cca6862540a5dc4ce355d7966766bf5d0fd0d | [
"Apache-2.0"
] | null | null | null | bbs/diredit.cpp | uriel1998/wwiv | 623cca6862540a5dc4ce355d7966766bf5d0fd0d | [
"Apache-2.0"
] | null | null | null | bbs/diredit.cpp | uriel1998/wwiv | 623cca6862540a5dc4ce355d7966766bf5d0fd0d | [
"Apache-2.0"
] | null | null | null | /**************************************************************************/
/* */
/* WWIV Version 5.x */
/* Copyright (C)1998-2020, WWIV Software Services */
/* */
/* 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 "bbs/conf.h"
#include "bbs/acs.h"
#include "bbs/bbs.h"
#include "bbs/bbsutl.h"
#include "bbs/bbsutl1.h"
#include "bbs/confutil.h"
#include "bbs/wqscn.h"
#include "common/com.h"
#include "common/input.h"
#include "common/pause.h"
#include "core/datafile.h"
#include "core/stl.h"
#include "core/strings.h"
#include "fmt/printf.h"
#include "sdk/files/dirs.h"
#include "sdk/usermanager.h"
#include <string>
using std::string;
using wwiv::common::InputMode;
using wwiv::core::DataFile;
using namespace wwiv::core;
using namespace wwiv::sdk;
using namespace wwiv::stl;
using namespace wwiv::strings;
//
// Local Function Prototypes
//
void modify_dir(int n);
void swap_dirs(int dir1, int dir2);
void insert_dir(int n);
void delete_dir(int n);
static std::string tail(const std::string& s, int len) {
return len >= ssize(s) ? s : s.substr(s.size() - len);
}
static std::string dirdata(int n) {
const auto& r = a()->dirs()[n];
return fmt::sprintf("|#2%4d |#1%-24.24s |#2%-8s |#9%-3d |#3%-23.23s |#1%s", n, stripcolors(r.name), r.filename,
r.maxfiles, tail(r.path, 23), r.conf.to_string());
}
static void showdirs() {
bout.cls();
bout << "|#7(|#1File Areas Editor|#7) Enter Substring: ";
const auto pattern = bin.input_text(20);
bout.cls();
bool abort = false;
bout.bpla("|#2## Description Filename Num Path Conf", &abort);
bout.bpla("|#7==== ======================== -------- === ----------------------- -------",
&abort);
for (auto i = 0; i < wwiv::stl::ssize(a()->dirs()) && !abort; i++) {
auto text = StrCat(a()->dirs()[i].name, " ", a()->dirs()[i].filename);
if (ifind_first(text, pattern)) {
bout.bpla(dirdata(i), &abort);
}
}
}
std::optional<net_networks_rec> select_network() {
std::map<int, net_networks_rec> nets;
auto num = 0;
for (const auto& n : a()->nets().networks()) {
if (n.type == network_type_t::ftn) {
nets.emplace(++num, n);
}
}
bout << "|#5Networks: " << wwiv::endl;
for (const auto& n : nets) {
bout << "|#1" << n.first << "|#9) |#2" << n.second.name << wwiv::endl;
}
bout.nl();
bout << "|#2(Q=Quit) Select Network Number : ";
const auto r = bin.input_number_hotkey(0, {'Q'}, 1, num, false);
if (r.key == 'Q') {
return std::nullopt;
}
auto it = nets.find(r.num);
if (it == std::end(nets)) {
return std::nullopt;
}
return {it->second};
}
enum class list_area_tags_style_t { number, indent };
static void list_area_tags(const std::vector<wwiv::sdk::files::dir_area_t>& area_tags,
list_area_tags_style_t style) {
if (area_tags.empty()) {
bout << "|#6(None)" << wwiv::endl;
return;
}
net_networks_rec empty{};
empty.name = "(Unknown)";
auto nn = 0;
auto first{true};
for (const auto& t : area_tags) {
if (style == list_area_tags_style_t::number) {
bout << "|#2" << nn++ << "|#9) ";
} else if (style == list_area_tags_style_t::indent) {
if (!first) {
bout << " ";
}
first = false;
}
bout << "|#1" << t.area_tag << "|#9@|#5" << a()->nets().by_uuid(t.net_uuid).value_or(empty).name
<< wwiv::endl;
}
}
static void edit_ftn_area_tags(std::vector<wwiv::sdk::files::dir_area_t>& area_tags) {
auto done{false};
do {
bout.cls();
bout.litebar("Editing File Area Tags");
bout.nl();
list_area_tags(area_tags, list_area_tags_style_t::number);
bout.nl();
bout << "|#7(|#2Q|#7=|#1Quit|#7) Which (|#2A|#7dd, |#2E|#7dit, or |#2D|#7elete) : ";
const auto ch = onek("QAED", true);
switch (ch) {
case 'A': {
files::dir_area_t da{};
bout << "Enter Name? ";
da.area_tag = bin.input_upper(12);
const auto r = select_network();
if (!r) {
break;
}
da.net_uuid = r.value().uuid;
area_tags.push_back(da);
} break;
case 'D': {
if (area_tags.empty()) {
break;
}
bout << "(Q=Quit, 1=" << area_tags.size() << ") Enter Number? ";
const auto r = bin.input_number_hotkey(0, {'Q'}, 1, size_int(area_tags), false);
if (r.key == 'Q') {
break;
}
bout << "Are you sure?";
if (bin.noyes()) {
erase_at(area_tags, r.num - 1);
}
} break;
case 'E': {
bout << "Edit!";
if (area_tags.empty()) {
break;
}
bout << "(Q=Quit, 1=" << area_tags.size() << ") Enter Number? ";
const auto r = bin.input_number_hotkey(0, {'Q'}, 1, size_int(area_tags), false);
if (r.key == 'Q') {
break;
}
files::dir_area_t da{};
bout << "Enter Name? ";
da.area_tag = bin.input_upper(12);
const auto nr = select_network();
if (!nr) {
break;
}
da.net_uuid = nr.value().uuid;
bout << "Are you sure?";
if (bin.noyes()) {
area_tags[r.num - 1] = da;
}
} break;
case 'Q':
done = true;
break;
}
} while (!done && !a()->sess().hangup());
}
void modify_dir(int n) {
auto r = a()->dirs()[n];
auto done = false;
do {
bout.cls();
bout.litebar(StrCat("Editing File Area #", n));
bout << "|#9A) Name : |#2" << r.name << wwiv::endl;
bout << "|#9B) Filename : |#2" << r.filename << wwiv::endl;
bout << "|#9C) Path : |#2" << r.path << wwiv::endl;
bout << "|#9D) ACS : |#2" << r.acs << wwiv::endl;
bout << "|#9F) Max Files : |#2" << r.maxfiles << wwiv::endl;
bout << "|#9H) Require PD : |#2" << YesNoString((r.mask & mask_PD) ? true : false)
<< wwiv::endl;
bout << "|#9J) Uploads : |#2" << ((r.mask & mask_no_uploads) ? "Disallowed" : "Allowed")
<< wwiv::endl;
bout << "|#9K) Arch. only : |#2" << YesNoString((r.mask & mask_archive) ? true : false)
<< wwiv::endl;
bout << "|#9L) Drive Type : |#2" << ((r.mask & mask_cdrom) ? "|#3CD ROM" : "HARD DRIVE")
<< wwiv::endl;
if (r.mask & mask_cdrom) {
bout << "|#9M) Available : |#2" << YesNoString((r.mask & mask_offline) ? true : false)
<< wwiv::endl;
}
bout << "|#9N) //UPLOADALL : |#2" << YesNoString((r.mask & mask_uploadall) ? true : false)
<< wwiv::endl;
bout << "|#9O) WWIV Reg : |#2" << YesNoString((r.mask & mask_wwivreg) ? true : false)
<< wwiv::endl;
bout << "|#9T) FTN Area Tags: |#2";
list_area_tags(r.area_tags, list_area_tags_style_t::indent);
bout << "|#9 Conferences : |#2" << r.conf.to_string() << wwiv::endl;
bout.nl(2);
bout << "|#7(|#2Q|#7=|#1Quit|#7) Which (|#1A|#7-|#1O|#7,|#1[T|#7,|#1[|#7,|#1]|#7) : ";
const auto ch = onek("QABCDEFGHJKLMNOT[]", true);
switch (ch) {
case 'Q':
done = true;
break;
case '[':
a()->dirs()[n] = r;
if (--n < 0) {
n = a()->dirs().size() - 1;
}
r = a()->dirs()[n];
break;
case ']':
a()->dirs()[n] = r;
if (++n >= a()->dirs().size()) {
n = 0;
}
r = a()->dirs()[n];
break;
case 'A': {
bout.nl();
bout << "|#2New name? ";
auto s = bin.input_text(r.name, 40);
if (!s.empty()) {
r.name = s;
}
} break;
case 'B': {
bout.nl();
bout << "|#2New filename? ";
auto s = bin.input_filename(r.filename, 8);
if (!s.empty() && !contains(s, '.')) {
r.filename = s;
}
} break;
case 'C': {
bout.nl();
bout << "|#9Enter new path, optionally with drive specifier.\r\n"
<< "|#9No backslash on end.\r\n\n"
<< "|#9The current path is:\r\n"
<< "|#1" << r.path << wwiv::endl
<< wwiv::endl;
bout << " \b";
auto s = bin.input_path(r.path, 79);
if (!s.empty()) {
const string dir{s};
if (!File::Exists(dir)) {
File::set_current_directory(a()->bbspath());
if (!File::mkdirs(dir)) {
bout << "|#6Unable to create or change to directory." << wwiv::endl;
bout.pausescr();
s.clear();
}
}
if (!s.empty()) {
s = File::EnsureTrailingSlash(s);
r.path = s;
bout.nl(2);
bout << "|#3The path for this directory is changed.\r\n";
bout << "|#9If there are any files in it, you must manually move them to the new "
"directory.\r\n";
bout.pausescr();
}
}
} break;
case 'D': {
bout.nl();
bout << "|#2New ACS? \r\n:";
r.acs = wwiv::bbs::input_acs(bin, bout, r.acs, 77);
} break;
case 'F': {
bout.nl();
bout << "|#2New max files? ";
r.maxfiles = bin.input_number(r.maxfiles);
} break;
case 'H':
r.mask ^= mask_PD;
break;
case 'J':
r.mask ^= mask_no_uploads;
break;
case 'K':
r.mask ^= mask_archive;
break;
case 'L':
r.mask ^= mask_cdrom;
if (r.mask & mask_cdrom) {
r.mask |= mask_no_uploads;
} else {
r.mask &= ~mask_offline;
}
break;
case 'M':
if (r.mask & mask_cdrom) {
r.mask ^= mask_offline;
}
break;
case 'N':
r.mask ^= mask_uploadall;
break;
case 'O':
r.mask &= ~mask_wwivreg;
bout.nl();
bout << "|#5Require WWIV 4.xx registration? ";
if (bin.yesno()) {
r.mask |= mask_wwivreg;
}
break;
case 'T': {
edit_ftn_area_tags(r.area_tags);
} break;
}
} while (!done && !a()->sess().hangup());
a()->dirs()[n] = r;
}
void swap_dirs(int dir1, int dir2) {
if (dir1 < 0 || dir1 >= a()->dirs().size() || dir2 < 0 || dir2 >= a()->dirs().size()) {
return;
}
const int num_user_records = a()->users()->num_user_records();
auto* pTempQScan = static_cast<uint32_t*>(BbsAllocA(a()->config()->qscn_len()));
if (pTempQScan) {
for (auto i = 1; i <= num_user_records; i++) {
read_qscn(i, pTempQScan, true);
auto* pTempQScan_n = pTempQScan + 1;
int i1 = 0;
if (pTempQScan_n[dir1 / 32] & (1L << (dir1 % 32))) {
i1 = 1;
}
int i2 = 0;
if (pTempQScan_n[dir2 / 32] & (1L << (dir2 % 32))) {
i2 = 1;
}
if (i1 + i2 == 1) {
pTempQScan_n[dir1 / 32] ^= (1L << (dir1 % 32));
pTempQScan_n[dir2 / 32] ^= (1L << (dir2 % 32));
}
write_qscn(i, pTempQScan, true);
}
close_qscn();
free(pTempQScan);
}
const auto drt = a()->dirs()[dir1];
a()->dirs()[dir1] = a()->dirs()[dir2];
a()->dirs()[dir2] = drt;
}
void insert_dir(int n) {
if (n < 0 || n > a()->dirs().size()) {
return;
}
files::directory_t r{};
r.name = "** NEW DIR **";
r.filename = "noname";
r.path = a()->config()->dloadsdir();
r.acs = "user.sl >= 10";
r.maxfiles = 50;
r.mask = 0;
a()->dirs().insert(n, r);
const auto num_user_records = a()->users()->num_user_records();
auto* pTempQScan = static_cast<uint32_t*>(BbsAllocA(a()->config()->qscn_len()));
if (pTempQScan) {
auto* pTempQScan_n = pTempQScan + 1;
const uint32_t m1 = 1L << (n % 32);
const uint32_t m2 = 0xffffffff << ((n % 32) + 1);
const uint32_t m3 = 0xffffffff >> (32 - (n % 32));
for (int i = 1; i <= num_user_records; i++) {
read_qscn(i, pTempQScan, true);
int i1;
for (i1 = a()->dirs().size() / 32; i1 > n / 32; i1--) {
pTempQScan_n[i1] = (pTempQScan_n[i1] << 1) | (pTempQScan_n[i1 - 1] >> 31);
}
pTempQScan_n[i1] = m1 | (m2 & (pTempQScan_n[i1] << 1)) | (m3 & pTempQScan_n[i1]);
write_qscn(i, pTempQScan, true);
}
close_qscn();
free(pTempQScan);
}
}
void delete_dir(int n) {
if (n < 0 || n >= a()->dirs().size()) {
return;
}
a()->dirs().erase(n);
const auto num_users = a()->users()->num_user_records();
const auto pTempQScan = std::make_unique<uint32_t[]>(a()->config()->qscn_len());
if (pTempQScan) {
auto* pTempQScan_n = pTempQScan.get() + 1;
const uint32_t m2 = 0xffffffff << (n % 32);
const uint32_t m3 = 0xffffffff >> (32 - (n % 32));
for (auto i = 1; i <= num_users; i++) {
read_qscn(i, pTempQScan.get(), true);
pTempQScan_n[n / 32] = (pTempQScan_n[n / 32] & m3) | ((pTempQScan_n[n / 32] >> 1) & m2) |
(pTempQScan_n[(n / 32) + 1] << 31);
for (auto i1 = (n / 32) + 1; i1 <= a()->dirs().size() / 32; i1++) {
pTempQScan_n[i1] = (pTempQScan_n[i1] >> 1) | (pTempQScan_n[i1 + 1] << 31);
}
write_qscn(i, pTempQScan.get(), true);
}
close_qscn();
}
}
void dlboardedit() {
char s[81];
if (!ValidateSysopPassword()) {
return;
}
showdirs();
auto done = false;
do {
bout.nl();
bout << "|#9(|#2Q|#9)uit (|#2D|#9)elete, (|#2I|#9)nsert, (|#2M|#9)odify, (|#2S|#9)wapDirs, (|#2C|#9)onference : ";
const auto ch = onek("QSDIMC?");
switch (ch) {
case '?':
showdirs();
break;
case 'C':
edit_conf_subs(a()->all_confs().dirs_conf());
break;
case 'Q':
done = true;
break;
case 'M': {
bout.nl();
bout << "|#2(Q=Quit) Dir number? ";
const auto r = bin.input_number_hotkey(0, {'Q'}, 0, a()->dirs().size());
if (r.key == 'Q') {
break;
}
modify_dir(r.num);
} break;
case 'S':
if (a()->dirs().size() < a()->config()->max_dirs()) {
bout.nl();
bout << "|#2Take dir number? ";
bin.input(s, 4);
auto i1 = to_number<int>(s);
if (!s[0] || i1 < 0 || i1 >= a()->dirs().size()) {
break;
}
bout.nl();
bout << "|#2And put before dir number? ";
bin.input(s, 4);
const auto i2 = to_number<int>(s);
if (!s[0] || i2 < 0 || i2 % 32 == 0 || i2 > a()->dirs().size() || i1 == i2) {
break;
}
bout.nl();
if (i2 < i1) {
i1++;
}
write_qscn(a()->sess().user_num(), a()->sess().qsc, true);
bout << "|#1Moving dir now...Please wait...";
insert_dir(i2);
swap_dirs(i1, i2);
delete_dir(i1);
showdirs();
} else {
bout << "\r\n|#6You must increase the number of dirs in WWIVconfig first.\r\n";
}
break;
case 'I': {
if (a()->dirs().size() < a()->config()->max_dirs()) {
bout.nl();
bout << "|#2Insert before which dir? ";
bin.input(s, 4);
const auto i = to_number<int>(s);
if (s[0] != 0 && i >= 0 && i <= a()->dirs().size()) {
insert_dir(i);
modify_dir(i);
}
}
} break;
case 'D': {
bout.nl();
bout << "|#2Delete which dir? ";
bin.input(s, 4);
const auto i = to_number<int>(s);
if (s[0] != 0 && i >= 0 && i < a()->dirs().size()) {
bout.nl();
bout << "|#5Delete " << a()->dirs()[i].name << "? ";
if (bin.yesno()) {
delete_dir(i);
bout.nl();
bout << "|#5Delete data files (.DIR/.EXT) for dir also? ";
if (bin.yesno()) {
const auto& fn = a()->dirs()[i].filename;
File::Remove(FilePath(a()->config()->datadir(), StrCat(fn, ".dir")));
File::Remove(FilePath(a()->config()->datadir(), StrCat(fn, ".ext")));
}
}
}
} break;
}
} while (!done && !a()->sess().hangup());
a()->dirs().Save();
if (!a()->at_wfc()) {
changedsl();
}
}
| 30.257194 | 118 | 0.479641 | uriel1998 |
a666043a1d230cf277f15f679466ecd1536a973c | 28,089 | cc | C++ | chrome/browser/about_flags_unittest.cc | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2015-08-13T21:04:58.000Z | 2015-08-13T21:04:58.000Z | chrome/browser/about_flags_unittest.cc | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/about_flags_unittest.cc | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-11-04T06:34:36.000Z | 2020-11-04T06:34:36.000Z | // Copyright (c) 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 <stdint.h>
#include "base/files/file_path.h"
#include "base/memory/scoped_vector.h"
#include "base/path_service.h"
#include "base/prefs/pref_registry_simple.h"
#include "base/prefs/testing_pref_service.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/about_flags.h"
#include "chrome/browser/pref_service_flags_storage.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/grit/chromium_strings.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/libxml/chromium/libxml_utils.h"
namespace {
const char kFlags1[] = "flag1";
const char kFlags2[] = "flag2";
const char kFlags3[] = "flag3";
const char kFlags4[] = "flag4";
const char kFlags5[] = "flag5";
const char kSwitch1[] = "switch";
const char kSwitch2[] = "switch2";
const char kSwitch3[] = "switch3";
const char kValueForSwitch2[] = "value_for_switch2";
const char kMultiSwitch1[] = "multi_switch1";
const char kMultiSwitch2[] = "multi_switch2";
const char kValueForMultiSwitch2[] = "value_for_multi_switch2";
const char kEnableDisableValue1[] = "value1";
const char kEnableDisableValue2[] = "value2";
typedef base::HistogramBase::Sample Sample;
typedef std::map<std::string, Sample> SwitchToIdMap;
// This is a helper function to the ReadEnumFromHistogramsXml().
// Extracts single enum (with integer values) from histograms.xml.
// Expects |reader| to point at given enum.
// Returns map { value => label }.
// Returns empty map on error.
std::map<Sample, std::string> ParseEnumFromHistogramsXml(
const std::string& enum_name,
XmlReader* reader) {
int entries_index = -1;
std::map<Sample, std::string> result;
bool success = true;
while (true) {
const std::string node_name = reader->NodeName();
if (node_name == "enum" && reader->IsClosingElement())
break;
if (node_name == "int") {
++entries_index;
std::string value_str;
std::string label;
const bool has_value = reader->NodeAttribute("value", &value_str);
const bool has_label = reader->NodeAttribute("label", &label);
if (!has_value) {
ADD_FAILURE() << "Bad " << enum_name << " enum entry (at index "
<< entries_index << ", label='" << label
<< "'): No 'value' attribute.";
success = false;
}
if (!has_label) {
ADD_FAILURE() << "Bad " << enum_name << " enum entry (at index "
<< entries_index << ", value_str='" << value_str
<< "'): No 'label' attribute.";
success = false;
}
Sample value;
if (has_value && !base::StringToInt(value_str, &value)) {
ADD_FAILURE() << "Bad " << enum_name << " enum entry (at index "
<< entries_index << ", label='" << label
<< "', value_str='" << value_str
<< "'): 'value' attribute is not integer.";
success = false;
}
if (result.count(value)) {
ADD_FAILURE() << "Bad " << enum_name << " enum entry (at index "
<< entries_index << ", label='" << label
<< "', value_str='" << value_str
<< "'): duplicate value '" << value_str
<< "' found in enum. The previous one has label='"
<< result[value] << "'.";
success = false;
}
if (success) {
result[value] = label;
}
}
// All enum entries are on the same level, so it is enough to iterate
// until possible.
reader->Next();
}
return (success ? result : std::map<Sample, std::string>());
}
// Find and read given enum (with integer values) from histograms.xml.
// |enum_name| - enum name.
// |histograms_xml| - must be loaded histograms.xml file.
//
// Returns map { value => label } so that:
// <int value="9" label="enable-pinch-virtual-viewport"/>
// becomes:
// { 9 => "enable-pinch-virtual-viewport" }
// Returns empty map on error.
std::map<Sample, std::string> ReadEnumFromHistogramsXml(
const std::string& enum_name,
XmlReader* histograms_xml) {
std::map<Sample, std::string> login_custom_flags;
// Implement simple depth first search.
while (true) {
const std::string node_name = histograms_xml->NodeName();
if (node_name == "enum") {
std::string name;
if (histograms_xml->NodeAttribute("name", &name) && name == enum_name) {
if (!login_custom_flags.empty()) {
EXPECT_TRUE(login_custom_flags.empty())
<< "Duplicate enum '" << enum_name << "' found in histograms.xml";
return std::map<Sample, std::string>();
}
const bool got_into_enum = histograms_xml->Read();
if (got_into_enum) {
login_custom_flags =
ParseEnumFromHistogramsXml(enum_name, histograms_xml);
EXPECT_FALSE(login_custom_flags.empty())
<< "Bad enum '" << enum_name
<< "' found in histograms.xml (format error).";
} else {
EXPECT_TRUE(got_into_enum)
<< "Bad enum '" << enum_name
<< "' (looks empty) found in histograms.xml.";
}
if (login_custom_flags.empty())
return std::map<Sample, std::string>();
}
}
// Go deeper if possible (stops at the closing tag of the deepest node).
if (histograms_xml->Read())
continue;
// Try next node on the same level (skips closing tag).
if (histograms_xml->Next())
continue;
// Go up until next node on the same level exists.
while (histograms_xml->Depth() && !histograms_xml->SkipToElement()) {
}
// Reached top. histograms.xml consists of the single top level node
// 'histogram-configuration', so this is the end.
if (!histograms_xml->Depth())
break;
}
EXPECT_FALSE(login_custom_flags.empty())
<< "Enum '" << enum_name << "' is not found in histograms.xml.";
return login_custom_flags;
}
std::string FilePathStringTypeToString(const base::FilePath::StringType& path) {
#if defined(OS_WIN)
return base::UTF16ToUTF8(path);
#else
return path;
#endif
}
std::set<std::string> GetAllSwitchesForTesting() {
std::set<std::string> result;
size_t num_experiments = 0;
const about_flags::Experiment* experiments =
about_flags::testing::GetExperiments(&num_experiments);
for (size_t i = 0; i < num_experiments; ++i) {
const about_flags::Experiment& experiment = experiments[i];
if (experiment.type == about_flags::Experiment::SINGLE_VALUE) {
result.insert(experiment.command_line_switch);
} else if (experiment.type == about_flags::Experiment::MULTI_VALUE) {
for (int j = 0; j < experiment.num_choices; ++j) {
result.insert(experiment.choices[j].command_line_switch);
}
} else {
DCHECK_EQ(experiment.type, about_flags::Experiment::ENABLE_DISABLE_VALUE);
result.insert(experiment.command_line_switch);
result.insert(experiment.disable_command_line_switch);
}
}
return result;
}
} // anonymous namespace
namespace about_flags {
const Experiment::Choice kMultiChoices[] = {
{ IDS_PRODUCT_NAME, "", "" },
{ IDS_PRODUCT_NAME, kMultiSwitch1, "" },
{ IDS_PRODUCT_NAME, kMultiSwitch2, kValueForMultiSwitch2 },
};
// The experiments that are set for these tests. The 3rd experiment is not
// supported on the current platform, all others are.
static Experiment kExperiments[] = {
{
kFlags1,
IDS_PRODUCT_NAME,
IDS_PRODUCT_NAME,
0, // Ends up being mapped to the current platform.
Experiment::SINGLE_VALUE,
kSwitch1,
"",
NULL,
NULL,
NULL,
0
},
{
kFlags2,
IDS_PRODUCT_NAME,
IDS_PRODUCT_NAME,
0, // Ends up being mapped to the current platform.
Experiment::SINGLE_VALUE,
kSwitch2,
kValueForSwitch2,
NULL,
NULL,
NULL,
0
},
{
kFlags3,
IDS_PRODUCT_NAME,
IDS_PRODUCT_NAME,
0, // This ends up enabling for an OS other than the current.
Experiment::SINGLE_VALUE,
kSwitch3,
"",
NULL,
NULL,
NULL,
0
},
{
kFlags4,
IDS_PRODUCT_NAME,
IDS_PRODUCT_NAME,
0, // Ends up being mapped to the current platform.
Experiment::MULTI_VALUE,
"",
"",
"",
"",
kMultiChoices,
arraysize(kMultiChoices)
},
{
kFlags5,
IDS_PRODUCT_NAME,
IDS_PRODUCT_NAME,
0, // Ends up being mapped to the current platform.
Experiment::ENABLE_DISABLE_VALUE,
kSwitch1,
kEnableDisableValue1,
kSwitch2,
kEnableDisableValue2,
NULL,
3
},
};
class AboutFlagsTest : public ::testing::Test {
protected:
AboutFlagsTest() : flags_storage_(&prefs_) {
prefs_.registry()->RegisterListPref(prefs::kEnabledLabsExperiments);
testing::ClearState();
}
virtual void SetUp() OVERRIDE {
for (size_t i = 0; i < arraysize(kExperiments); ++i)
kExperiments[i].supported_platforms = GetCurrentPlatform();
int os_other_than_current = 1;
while (os_other_than_current == GetCurrentPlatform())
os_other_than_current <<= 1;
kExperiments[2].supported_platforms = os_other_than_current;
testing::SetExperiments(kExperiments, arraysize(kExperiments));
}
virtual void TearDown() OVERRIDE {
testing::SetExperiments(NULL, 0);
}
TestingPrefServiceSimple prefs_;
PrefServiceFlagsStorage flags_storage_;
};
TEST_F(AboutFlagsTest, NoChangeNoRestart) {
EXPECT_FALSE(IsRestartNeededToCommitChanges());
SetExperimentEnabled(&flags_storage_, kFlags1, false);
EXPECT_FALSE(IsRestartNeededToCommitChanges());
}
TEST_F(AboutFlagsTest, ChangeNeedsRestart) {
EXPECT_FALSE(IsRestartNeededToCommitChanges());
SetExperimentEnabled(&flags_storage_, kFlags1, true);
EXPECT_TRUE(IsRestartNeededToCommitChanges());
}
TEST_F(AboutFlagsTest, MultiFlagChangeNeedsRestart) {
const Experiment& experiment = kExperiments[3];
ASSERT_EQ(kFlags4, experiment.internal_name);
EXPECT_FALSE(IsRestartNeededToCommitChanges());
// Enable the 2nd choice of the multi-value.
SetExperimentEnabled(&flags_storage_, experiment.NameForChoice(2), true);
EXPECT_TRUE(IsRestartNeededToCommitChanges());
testing::ClearState();
EXPECT_FALSE(IsRestartNeededToCommitChanges());
// Enable the default choice now.
SetExperimentEnabled(&flags_storage_, experiment.NameForChoice(0), true);
EXPECT_TRUE(IsRestartNeededToCommitChanges());
}
TEST_F(AboutFlagsTest, AddTwoFlagsRemoveOne) {
// Add two experiments, check they're there.
SetExperimentEnabled(&flags_storage_, kFlags1, true);
SetExperimentEnabled(&flags_storage_, kFlags2, true);
const base::ListValue* experiments_list = prefs_.GetList(
prefs::kEnabledLabsExperiments);
ASSERT_TRUE(experiments_list != NULL);
ASSERT_EQ(2u, experiments_list->GetSize());
std::string s0;
ASSERT_TRUE(experiments_list->GetString(0, &s0));
std::string s1;
ASSERT_TRUE(experiments_list->GetString(1, &s1));
EXPECT_TRUE(s0 == kFlags1 || s1 == kFlags1);
EXPECT_TRUE(s0 == kFlags2 || s1 == kFlags2);
// Remove one experiment, check the other's still around.
SetExperimentEnabled(&flags_storage_, kFlags2, false);
experiments_list = prefs_.GetList(prefs::kEnabledLabsExperiments);
ASSERT_TRUE(experiments_list != NULL);
ASSERT_EQ(1u, experiments_list->GetSize());
ASSERT_TRUE(experiments_list->GetString(0, &s0));
EXPECT_TRUE(s0 == kFlags1);
}
TEST_F(AboutFlagsTest, AddTwoFlagsRemoveBoth) {
// Add two experiments, check the pref exists.
SetExperimentEnabled(&flags_storage_, kFlags1, true);
SetExperimentEnabled(&flags_storage_, kFlags2, true);
const base::ListValue* experiments_list = prefs_.GetList(
prefs::kEnabledLabsExperiments);
ASSERT_TRUE(experiments_list != NULL);
// Remove both, the pref should have been removed completely.
SetExperimentEnabled(&flags_storage_, kFlags1, false);
SetExperimentEnabled(&flags_storage_, kFlags2, false);
experiments_list = prefs_.GetList(prefs::kEnabledLabsExperiments);
EXPECT_TRUE(experiments_list == NULL || experiments_list->GetSize() == 0);
}
TEST_F(AboutFlagsTest, ConvertFlagsToSwitches) {
SetExperimentEnabled(&flags_storage_, kFlags1, true);
CommandLine command_line(CommandLine::NO_PROGRAM);
command_line.AppendSwitch("foo");
EXPECT_TRUE(command_line.HasSwitch("foo"));
EXPECT_FALSE(command_line.HasSwitch(kSwitch1));
ConvertFlagsToSwitches(&flags_storage_, &command_line, kAddSentinels);
EXPECT_TRUE(command_line.HasSwitch("foo"));
EXPECT_TRUE(command_line.HasSwitch(kSwitch1));
EXPECT_TRUE(command_line.HasSwitch(switches::kFlagSwitchesBegin));
EXPECT_TRUE(command_line.HasSwitch(switches::kFlagSwitchesEnd));
CommandLine command_line2(CommandLine::NO_PROGRAM);
ConvertFlagsToSwitches(&flags_storage_, &command_line2, kNoSentinels);
EXPECT_TRUE(command_line2.HasSwitch(kSwitch1));
EXPECT_FALSE(command_line2.HasSwitch(switches::kFlagSwitchesBegin));
EXPECT_FALSE(command_line2.HasSwitch(switches::kFlagSwitchesEnd));
}
CommandLine::StringType CreateSwitch(const std::string& value) {
#if defined(OS_WIN)
return base::ASCIIToUTF16(value);
#else
return value;
#endif
}
TEST_F(AboutFlagsTest, CompareSwitchesToCurrentCommandLine) {
SetExperimentEnabled(&flags_storage_, kFlags1, true);
const std::string kDoubleDash("--");
CommandLine command_line(CommandLine::NO_PROGRAM);
command_line.AppendSwitch("foo");
CommandLine new_command_line(CommandLine::NO_PROGRAM);
ConvertFlagsToSwitches(&flags_storage_, &new_command_line, kAddSentinels);
EXPECT_FALSE(AreSwitchesIdenticalToCurrentCommandLine(
new_command_line, command_line, NULL));
{
std::set<CommandLine::StringType> difference;
EXPECT_FALSE(AreSwitchesIdenticalToCurrentCommandLine(
new_command_line, command_line, &difference));
EXPECT_EQ(1U, difference.size());
EXPECT_EQ(1U, difference.count(CreateSwitch(kDoubleDash + kSwitch1)));
}
ConvertFlagsToSwitches(&flags_storage_, &command_line, kAddSentinels);
EXPECT_TRUE(AreSwitchesIdenticalToCurrentCommandLine(
new_command_line, command_line, NULL));
{
std::set<CommandLine::StringType> difference;
EXPECT_TRUE(AreSwitchesIdenticalToCurrentCommandLine(
new_command_line, command_line, &difference));
EXPECT_TRUE(difference.empty());
}
// Now both have flags but different.
SetExperimentEnabled(&flags_storage_, kFlags1, false);
SetExperimentEnabled(&flags_storage_, kFlags2, true);
CommandLine another_command_line(CommandLine::NO_PROGRAM);
ConvertFlagsToSwitches(&flags_storage_, &another_command_line, kAddSentinels);
EXPECT_FALSE(AreSwitchesIdenticalToCurrentCommandLine(
new_command_line, another_command_line, NULL));
{
std::set<CommandLine::StringType> difference;
EXPECT_FALSE(AreSwitchesIdenticalToCurrentCommandLine(
new_command_line, another_command_line, &difference));
EXPECT_EQ(2U, difference.size());
EXPECT_EQ(1U, difference.count(CreateSwitch(kDoubleDash + kSwitch1)));
EXPECT_EQ(1U,
difference.count(CreateSwitch(kDoubleDash + kSwitch2 + "=" +
kValueForSwitch2)));
}
}
TEST_F(AboutFlagsTest, RemoveFlagSwitches) {
std::map<std::string, CommandLine::StringType> switch_list;
switch_list[kSwitch1] = CommandLine::StringType();
switch_list[switches::kFlagSwitchesBegin] = CommandLine::StringType();
switch_list[switches::kFlagSwitchesEnd] = CommandLine::StringType();
switch_list["foo"] = CommandLine::StringType();
SetExperimentEnabled(&flags_storage_, kFlags1, true);
// This shouldn't do anything before ConvertFlagsToSwitches() wasn't called.
RemoveFlagsSwitches(&switch_list);
ASSERT_EQ(4u, switch_list.size());
EXPECT_TRUE(switch_list.find(kSwitch1) != switch_list.end());
EXPECT_TRUE(switch_list.find(switches::kFlagSwitchesBegin) !=
switch_list.end());
EXPECT_TRUE(switch_list.find(switches::kFlagSwitchesEnd) !=
switch_list.end());
EXPECT_TRUE(switch_list.find("foo") != switch_list.end());
// Call ConvertFlagsToSwitches(), then RemoveFlagsSwitches() again.
CommandLine command_line(CommandLine::NO_PROGRAM);
command_line.AppendSwitch("foo");
ConvertFlagsToSwitches(&flags_storage_, &command_line, kAddSentinels);
RemoveFlagsSwitches(&switch_list);
// Now the about:flags-related switch should have been removed.
ASSERT_EQ(1u, switch_list.size());
EXPECT_TRUE(switch_list.find("foo") != switch_list.end());
}
// Tests enabling experiments that aren't supported on the current platform.
TEST_F(AboutFlagsTest, PersistAndPrune) {
// Enable experiments 1 and 3.
SetExperimentEnabled(&flags_storage_, kFlags1, true);
SetExperimentEnabled(&flags_storage_, kFlags3, true);
CommandLine command_line(CommandLine::NO_PROGRAM);
EXPECT_FALSE(command_line.HasSwitch(kSwitch1));
EXPECT_FALSE(command_line.HasSwitch(kSwitch3));
// Convert the flags to switches. Experiment 3 shouldn't be among the switches
// as it is not applicable to the current platform.
ConvertFlagsToSwitches(&flags_storage_, &command_line, kAddSentinels);
EXPECT_TRUE(command_line.HasSwitch(kSwitch1));
EXPECT_FALSE(command_line.HasSwitch(kSwitch3));
// Experiment 3 should show still be persisted in preferences though.
const base::ListValue* experiments_list =
prefs_.GetList(prefs::kEnabledLabsExperiments);
ASSERT_TRUE(experiments_list);
EXPECT_EQ(2U, experiments_list->GetSize());
std::string s0;
ASSERT_TRUE(experiments_list->GetString(0, &s0));
EXPECT_EQ(kFlags1, s0);
std::string s1;
ASSERT_TRUE(experiments_list->GetString(1, &s1));
EXPECT_EQ(kFlags3, s1);
}
// Tests that switches which should have values get them in the command
// line.
TEST_F(AboutFlagsTest, CheckValues) {
// Enable experiments 1 and 2.
SetExperimentEnabled(&flags_storage_, kFlags1, true);
SetExperimentEnabled(&flags_storage_, kFlags2, true);
CommandLine command_line(CommandLine::NO_PROGRAM);
EXPECT_FALSE(command_line.HasSwitch(kSwitch1));
EXPECT_FALSE(command_line.HasSwitch(kSwitch2));
// Convert the flags to switches.
ConvertFlagsToSwitches(&flags_storage_, &command_line, kAddSentinels);
EXPECT_TRUE(command_line.HasSwitch(kSwitch1));
EXPECT_EQ(std::string(), command_line.GetSwitchValueASCII(kSwitch1));
EXPECT_TRUE(command_line.HasSwitch(kSwitch2));
EXPECT_EQ(std::string(kValueForSwitch2),
command_line.GetSwitchValueASCII(kSwitch2));
// Confirm that there is no '=' in the command line for simple switches.
std::string switch1_with_equals = std::string("--") +
std::string(kSwitch1) +
std::string("=");
#if defined(OS_WIN)
EXPECT_EQ(std::wstring::npos,
command_line.GetCommandLineString().find(
base::ASCIIToWide(switch1_with_equals)));
#else
EXPECT_EQ(std::string::npos,
command_line.GetCommandLineString().find(switch1_with_equals));
#endif
// And confirm there is a '=' for switches with values.
std::string switch2_with_equals = std::string("--") +
std::string(kSwitch2) +
std::string("=");
#if defined(OS_WIN)
EXPECT_NE(std::wstring::npos,
command_line.GetCommandLineString().find(
base::ASCIIToWide(switch2_with_equals)));
#else
EXPECT_NE(std::string::npos,
command_line.GetCommandLineString().find(switch2_with_equals));
#endif
// And it should persist.
const base::ListValue* experiments_list =
prefs_.GetList(prefs::kEnabledLabsExperiments);
ASSERT_TRUE(experiments_list);
EXPECT_EQ(2U, experiments_list->GetSize());
std::string s0;
ASSERT_TRUE(experiments_list->GetString(0, &s0));
EXPECT_EQ(kFlags1, s0);
std::string s1;
ASSERT_TRUE(experiments_list->GetString(1, &s1));
EXPECT_EQ(kFlags2, s1);
}
// Tests multi-value type experiments.
TEST_F(AboutFlagsTest, MultiValues) {
const Experiment& experiment = kExperiments[3];
ASSERT_EQ(kFlags4, experiment.internal_name);
// Initially, the first "deactivated" option of the multi experiment should
// be set.
{
CommandLine command_line(CommandLine::NO_PROGRAM);
ConvertFlagsToSwitches(&flags_storage_, &command_line, kAddSentinels);
EXPECT_FALSE(command_line.HasSwitch(kMultiSwitch1));
EXPECT_FALSE(command_line.HasSwitch(kMultiSwitch2));
}
// Enable the 2nd choice of the multi-value.
SetExperimentEnabled(&flags_storage_, experiment.NameForChoice(2), true);
{
CommandLine command_line(CommandLine::NO_PROGRAM);
ConvertFlagsToSwitches(&flags_storage_, &command_line, kAddSentinels);
EXPECT_FALSE(command_line.HasSwitch(kMultiSwitch1));
EXPECT_TRUE(command_line.HasSwitch(kMultiSwitch2));
EXPECT_EQ(std::string(kValueForMultiSwitch2),
command_line.GetSwitchValueASCII(kMultiSwitch2));
}
// Disable the multi-value experiment.
SetExperimentEnabled(&flags_storage_, experiment.NameForChoice(0), true);
{
CommandLine command_line(CommandLine::NO_PROGRAM);
ConvertFlagsToSwitches(&flags_storage_, &command_line, kAddSentinels);
EXPECT_FALSE(command_line.HasSwitch(kMultiSwitch1));
EXPECT_FALSE(command_line.HasSwitch(kMultiSwitch2));
}
}
TEST_F(AboutFlagsTest, EnableDisableValues) {
const Experiment& experiment = kExperiments[4];
ASSERT_EQ(kFlags5, experiment.internal_name);
// Nothing selected.
{
CommandLine command_line(CommandLine::NO_PROGRAM);
ConvertFlagsToSwitches(&flags_storage_, &command_line, kAddSentinels);
EXPECT_FALSE(command_line.HasSwitch(kSwitch1));
EXPECT_FALSE(command_line.HasSwitch(kSwitch2));
}
// "Enable" option selected.
SetExperimentEnabled(&flags_storage_, experiment.NameForChoice(1), true);
{
CommandLine command_line(CommandLine::NO_PROGRAM);
ConvertFlagsToSwitches(&flags_storage_, &command_line, kAddSentinels);
EXPECT_TRUE(command_line.HasSwitch(kSwitch1));
EXPECT_FALSE(command_line.HasSwitch(kSwitch2));
EXPECT_EQ(kEnableDisableValue1, command_line.GetSwitchValueASCII(kSwitch1));
}
// "Disable" option selected.
SetExperimentEnabled(&flags_storage_, experiment.NameForChoice(2), true);
{
CommandLine command_line(CommandLine::NO_PROGRAM);
ConvertFlagsToSwitches(&flags_storage_, &command_line, kAddSentinels);
EXPECT_FALSE(command_line.HasSwitch(kSwitch1));
EXPECT_TRUE(command_line.HasSwitch(kSwitch2));
EXPECT_EQ(kEnableDisableValue2, command_line.GetSwitchValueASCII(kSwitch2));
}
// "Default" option selected, same as nothing selected.
SetExperimentEnabled(&flags_storage_, experiment.NameForChoice(0), true);
{
CommandLine command_line(CommandLine::NO_PROGRAM);
ConvertFlagsToSwitches(&flags_storage_, &command_line, kAddSentinels);
EXPECT_FALSE(command_line.HasSwitch(kMultiSwitch1));
EXPECT_FALSE(command_line.HasSwitch(kMultiSwitch2));
}
}
// Makes sure there are no separators in any of the experiment names.
TEST_F(AboutFlagsTest, NoSeparators) {
testing::SetExperiments(NULL, 0);
size_t count;
const Experiment* experiments = testing::GetExperiments(&count);
for (size_t i = 0; i < count; ++i) {
std::string name = experiments->internal_name;
EXPECT_EQ(std::string::npos, name.find(testing::kMultiSeparator)) << i;
}
}
class AboutFlagsHistogramTest : public ::testing::Test {
protected:
// This is a helper function to check that all IDs in enum LoginCustomFlags in
// histograms.xml are unique.
void SetSwitchToHistogramIdMapping(const std::string& switch_name,
const Sample switch_histogram_id,
std::map<std::string, Sample>* out_map) {
const std::pair<std::map<std::string, Sample>::iterator, bool> status =
out_map->insert(std::make_pair(switch_name, switch_histogram_id));
if (!status.second) {
EXPECT_TRUE(status.first->second == switch_histogram_id)
<< "Duplicate switch '" << switch_name
<< "' found in enum 'LoginCustomFlags' in histograms.xml.";
}
}
// This method generates a hint for the user for what string should be added
// to the enum LoginCustomFlags to make in consistent.
std::string GetHistogramEnumEntryText(const std::string& switch_name,
Sample value) {
return base::StringPrintf(
"<int value=\"%d\" label=\"%s\"/>", value, switch_name.c_str());
}
};
TEST_F(AboutFlagsHistogramTest, CheckHistograms) {
base::FilePath histograms_xml_file_path;
ASSERT_TRUE(
PathService::Get(base::DIR_SOURCE_ROOT, &histograms_xml_file_path));
histograms_xml_file_path = histograms_xml_file_path.AppendASCII("tools")
.AppendASCII("metrics")
.AppendASCII("histograms")
.AppendASCII("histograms.xml");
XmlReader histograms_xml;
ASSERT_TRUE(histograms_xml.LoadFile(
FilePathStringTypeToString(histograms_xml_file_path.value())));
std::map<Sample, std::string> login_custom_flags =
ReadEnumFromHistogramsXml("LoginCustomFlags", &histograms_xml);
ASSERT_TRUE(login_custom_flags.size())
<< "Error reading enum 'LoginCustomFlags' from histograms.xml.";
// Build reverse map {switch_name => id} from login_custom_flags.
SwitchToIdMap histograms_xml_switches_ids;
EXPECT_TRUE(login_custom_flags.count(kBadSwitchFormatHistogramId))
<< "Entry for UMA ID of incorrect command-line flag is not found in "
"histograms.xml enum LoginCustomFlags. "
"Consider adding entry:\n"
<< " " << GetHistogramEnumEntryText("BAD_FLAG_FORMAT", 0);
// Check that all LoginCustomFlags entries have correct values.
for (std::map<Sample, std::string>::const_iterator it =
login_custom_flags.begin();
it != login_custom_flags.end();
++it) {
if (it->first == kBadSwitchFormatHistogramId) {
// Add eror value with empty name.
SetSwitchToHistogramIdMapping(
"", it->first, &histograms_xml_switches_ids);
continue;
}
const Sample uma_id = GetSwitchUMAId(it->second);
EXPECT_EQ(uma_id, it->first)
<< "histograms.xml enum LoginCustomFlags "
"entry '" << it->second << "' has incorrect value=" << it->first
<< ", but " << uma_id << " is expected. Consider changing entry to:\n"
<< " " << GetHistogramEnumEntryText(it->second, uma_id);
SetSwitchToHistogramIdMapping(
it->second, it->first, &histograms_xml_switches_ids);
}
// Check that all flags in about_flags.cc have entries in login_custom_flags.
std::set<std::string> all_switches = GetAllSwitchesForTesting();
for (std::set<std::string>::const_iterator it = all_switches.begin();
it != all_switches.end();
++it) {
// Skip empty placeholders.
if (it->empty())
continue;
const Sample uma_id = GetSwitchUMAId(*it);
EXPECT_NE(kBadSwitchFormatHistogramId, uma_id)
<< "Command-line switch '" << *it
<< "' from about_flags.cc has UMA ID equal to reserved value "
"kBadSwitchFormatHistogramId=" << kBadSwitchFormatHistogramId
<< ". Please modify switch name.";
SwitchToIdMap::iterator enum_entry =
histograms_xml_switches_ids.lower_bound(*it);
// Ignore case here when switch ID is incorrect - it has already been
// reported in the previous loop.
EXPECT_TRUE(enum_entry != histograms_xml_switches_ids.end() &&
enum_entry->first == *it)
<< "histograms.xml enum LoginCustomFlags doesn't contain switch '"
<< *it << "' (value=" << uma_id
<< " expected). Consider adding entry:\n"
<< " " << GetHistogramEnumEntryText(*it, uma_id);
}
}
} // namespace about_flags
| 36.243871 | 80 | 0.699776 | Fusion-Rom |
a66a3c4a91702d798805d30852d8385fdb0895a6 | 5,316 | cpp | C++ | tide/master/rest/HtmlContent.cpp | BlueBrain/Tide | 01e0518117509eaa0ccd9d79f067f385b641247c | [
"BSD-2-Clause"
] | 47 | 2016-07-12T02:00:11.000Z | 2021-07-06T17:50:53.000Z | tide/master/rest/HtmlContent.cpp | BlueBrain/Tide | 01e0518117509eaa0ccd9d79f067f385b641247c | [
"BSD-2-Clause"
] | 135 | 2016-03-24T14:02:26.000Z | 2019-10-25T09:43:59.000Z | tide/master/rest/HtmlContent.cpp | BlueBrain/Tide | 01e0518117509eaa0ccd9d79f067f385b641247c | [
"BSD-2-Clause"
] | 17 | 2016-03-23T13:34:48.000Z | 2022-03-21T03:21:54.000Z | /*********************************************************************/
/* Copyright (c) 2017, EPFL/Blue Brain Project */
/* Pawel Podhajski <pawel.podhajski@epfl.ch> */
/* Raphael Dumusc <raphael.dumusc@epfl.ch> */
/* All rights reserved. */
/* */
/* Redistribution and use in source and binary forms, with or */
/* without modification, are permitted provided that the following */
/* conditions are met: */
/* */
/* 1. Redistributions of source code must retain the above */
/* copyright notice, this list of conditions and the following */
/* disclaimer. */
/* */
/* 2. Redistributions in binary form must reproduce the above */
/* copyright notice, this list of conditions and the following */
/* disclaimer in the documentation and/or other materials */
/* provided with the distribution. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE ECOLE POLYTECHNIQUE */
/* FEDERALE DE LAUSANNE ''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 ECOLE */
/* POLYTECHNIQUE FEDERALE DE LAUSANNE 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. */
/* */
/* The views and conclusions contained in the software and */
/* documentation are those of the authors and should not be */
/* interpreted as representing official policies, either expressed */
/* or implied, of Ecole polytechnique federale de Lausanne. */
/*********************************************************************/
#include "HtmlContent.h"
#include <QFile>
#include <QMap>
#include <QStringList>
using namespace rockets;
namespace
{
constexpr auto HTML_TYPE = "text/html";
constexpr auto INDEX_PAGE = "index.html";
const QString resourcePath = ":///html/";
// clang-format off
const QMap<std::string, QStringList> resources {
{
"application/javascript",
{
"js/bootstrap-treeview.min.js",
"js/jquery-3.1.1.min.js",
"js/notify.min.js",
"js/jquery-ui.min.js",
"js/sweetalert.min.js",
"js/tide.js",
"js/tideVars.js",
"js/underscore-min.js"
}
},
{
"image/gif",
{
"img/loading.gif"
}
},
{
"image/svg+xml",
{
"img/close.svg",
"img/focus.svg",
"img/lock.svg",
"img/maximize.svg",
"img/screenOff.svg",
"img/screenOn.svg",
"img/unlock.svg"
}
},
{
"image/x-icon",
{
"favicon.ico"
}
},
{
"text/css",
{
"css/bootstrap.min.css",
"css/jquery-ui.css",
"css/styles.css",
"css/sweetalert.min.css"
}
},
{
HTML_TYPE,
{
INDEX_PAGE
}
}
};
// clang-format on
std::string _readFile(const QString& uri)
{
QFile file(resourcePath + uri);
file.open(QIODevice::ReadOnly);
return file.readAll().toStdString();
}
std::future<http::Response> _makeResponse(const QString& file,
const std::string& type)
{
using namespace http;
const auto body = _readFile(file);
if (body.empty())
return make_ready_response(Code::INTERNAL_SERVER_ERROR);
return make_ready_response(Code::OK, body, type);
}
}
HtmlContent::HtmlContent(rockets::Server& server)
{
server.handle(http::Method::GET, "", [](const http::Request&) {
return _makeResponse(INDEX_PAGE, HTML_TYPE);
});
for (auto it = resources.begin(); it != resources.end(); ++it)
{
const auto& type = it.key();
const auto& files = it.value();
for (const auto& file : files)
{
server.handle(http::Method::GET, file.toStdString(),
[file, type](const http::Request&) {
return _makeResponse(file, type);
});
}
}
}
| 35.44 | 71 | 0.48909 | BlueBrain |
a66b46c629e4b99993025f7d654d4477f0eaddf1 | 1,485 | cpp | C++ | chp3_oscillation/NOC_3_10_PendulumExample/src/ofApp.cpp | ikbenmacje/NatureOfCode | 98692398b0458765a6e77ae6f652392f99de050f | [
"MIT"
] | null | null | null | chp3_oscillation/NOC_3_10_PendulumExample/src/ofApp.cpp | ikbenmacje/NatureOfCode | 98692398b0458765a6e77ae6f652392f99de050f | [
"MIT"
] | null | null | null | chp3_oscillation/NOC_3_10_PendulumExample/src/ofApp.cpp | ikbenmacje/NatureOfCode | 98692398b0458765a6e77ae6f652392f99de050f | [
"MIT"
] | null | null | null | #include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
ofSetFrameRate(60);
p = new Pendulum(ofVec2f(ofGetWidth()/2,0),175);
}
//--------------------------------------------------------------
void ofApp::update(){
}
//--------------------------------------------------------------
void ofApp::draw(){
ofBackground(255);
p->go();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
p->clicked(ofGetMouseX(),ofGetMouseY());
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
p->stopDragging();
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
} | 22.5 | 64 | 0.307071 | ikbenmacje |
a66cbc27046f4d037707279a720e14667f19305b | 4,013 | cpp | C++ | catboost/libs/data_new/cat_feature_perfect_hash.cpp | EkaterinaPogodina/catboost | 4628e86e978da2ec5e4d42f6b8d05e0b5e8aab30 | [
"Apache-2.0"
] | 2 | 2019-07-10T10:49:09.000Z | 2020-06-19T11:40:04.000Z | catboost/libs/data_new/cat_feature_perfect_hash.cpp | EkaterinaPogodina/catboost | 4628e86e978da2ec5e4d42f6b8d05e0b5e8aab30 | [
"Apache-2.0"
] | null | null | null | catboost/libs/data_new/cat_feature_perfect_hash.cpp | EkaterinaPogodina/catboost | 4628e86e978da2ec5e4d42f6b8d05e0b5e8aab30 | [
"Apache-2.0"
] | null | null | null | #include "cat_feature_perfect_hash.h"
#include <util/generic/xrange.h>
#include <util/stream/output.h>
template <>
void Out<NCB::TCatFeatureUniqueValuesCounts>(IOutputStream& out, NCB::TCatFeatureUniqueValuesCounts counts) {
out << counts.OnLearnOnly << ',' << counts.OnAll;
}
template <>
void Out<NCB::TValueWithCount>(IOutputStream& out, NCB::TValueWithCount valueWithCount) {
out << "Value="<< valueWithCount.Value << ",Count=" << valueWithCount.Count;
}
namespace NCB {
bool TCatFeaturesPerfectHash::operator==(const TCatFeaturesPerfectHash& rhs) const {
if (CatFeatureUniqValuesCountsVector != rhs.CatFeatureUniqValuesCountsVector) {
return false;
}
if (!HasHashInRam) {
Load();
}
if (!rhs.HasHashInRam) {
rhs.Load();
}
return FeaturesPerfectHash == rhs.FeaturesPerfectHash;
}
bool TCatFeaturesPerfectHash::IsSupersetOf(const TCatFeaturesPerfectHash& rhs) const {
if (this == &rhs) { // shortcut
return true;
}
const size_t rhsSize = rhs.CatFeatureUniqValuesCountsVector.size();
if (rhsSize > CatFeatureUniqValuesCountsVector.size()) {
return false;
}
for (auto catFeatureIdx : xrange(rhsSize)) {
const auto& counts = CatFeatureUniqValuesCountsVector[catFeatureIdx];
const auto& rhsCounts = rhs.CatFeatureUniqValuesCountsVector[catFeatureIdx];
if (rhsCounts.OnLearnOnly != counts.OnLearnOnly) {
return false;
}
if (rhsCounts.OnAll > counts.OnAll) {
return false;
}
}
if (!HasHashInRam) {
Load();
}
if (!rhs.HasHashInRam) {
rhs.Load();
}
// count differences are ok
for (auto catFeatureIdx : xrange(rhsSize)) {
const auto& featurePerfectHash = FeaturesPerfectHash[catFeatureIdx];
for (const auto& [hashedCatValue, valueWithCount] : rhs.FeaturesPerfectHash[catFeatureIdx]) {
const auto it = featurePerfectHash.find(hashedCatValue);
if (it == featurePerfectHash.end()) {
return false;
} else if (valueWithCount.Value != it->second.Value) {
return false;
}
}
}
return true;
}
void TCatFeaturesPerfectHash::UpdateFeaturePerfectHash(
const TCatFeatureIdx catFeatureIdx,
TCatFeaturePerfectHash&& perfectHash
) {
CheckHasFeature(catFeatureIdx);
auto& counts = CatFeatureUniqValuesCountsVector[*catFeatureIdx];
if (counts.OnAll) {
// already have some data
// we must update with data that has not less elements than current
Y_VERIFY((size_t)counts.OnAll <= perfectHash.size());
} else {
// first initialization
counts.OnLearnOnly = (ui32)perfectHash.size();
}
// cast is safe because map from ui32 keys can't have more than Max<ui32>() keys
counts.OnAll = (ui32)perfectHash.size();
if (!HasHashInRam) {
Load();
}
FeaturesPerfectHash[*catFeatureIdx] = std::move(perfectHash);
}
int TCatFeaturesPerfectHash::operator&(IBinSaver& binSaver) {
if (!binSaver.IsReading()) {
if (!HasHashInRam) {
Load();
}
}
binSaver.AddMulti(CatFeatureUniqValuesCountsVector, FeaturesPerfectHash, AllowWriteFiles);
if (binSaver.IsReading()) {
HasHashInRam = true;
}
return 0;
}
ui32 TCatFeaturesPerfectHash::CalcCheckSum() const {
if (!HasHashInRam) {
Load();
}
ui32 checkSum = 0;
checkSum = UpdateCheckSum(checkSum, CatFeatureUniqValuesCountsVector);
checkSum = UpdateCheckSum(checkSum, FeaturesPerfectHash);
return checkSum;
}
}
| 30.869231 | 109 | 0.59382 | EkaterinaPogodina |
a671545285703c2885d3d08de0ed53d466aa666c | 2,203 | cpp | C++ | SGIPC practice contests/stl sgipc cntst/New folder/New folder/New folder/New folder/Codeforces Round #478 (Div. 2)A.cpp | YaminArafat/Vjudge | d8d2afc4b1a0fbada46d75cb080efc37965dfe9d | [
"Apache-2.0"
] | null | null | null | SGIPC practice contests/stl sgipc cntst/New folder/New folder/New folder/New folder/Codeforces Round #478 (Div. 2)A.cpp | YaminArafat/Vjudge | d8d2afc4b1a0fbada46d75cb080efc37965dfe9d | [
"Apache-2.0"
] | null | null | null | SGIPC practice contests/stl sgipc cntst/New folder/New folder/New folder/New folder/Codeforces Round #478 (Div. 2)A.cpp | YaminArafat/Vjudge | d8d2afc4b1a0fbada46d75cb080efc37965dfe9d | [
"Apache-2.0"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
bool flag2[100000];
//map<string,bool>mp2;
int main()
{
int n,ans=0;
//cout<<'a'-0<<endl;
scanf("%d",&n);
string str;
//vector<string>vec;
map<string,int>mp;
for(int i=0; i<n; i++)
{
cin>>str;
sort(str.begin(),str.end());
mp[str]++;
//vec.push_back(str);
}
//sort(mp.begin(),mp.end());
for(map<string,int>::iterator it=mp.begin(); it!=mp.end(); ++it)
{
string temp=it->first;
int i=0,cnt=0;
while(i<temp.size()-1)
{
if(temp[i]==temp[i+1])
{
cnt++;
}
else
{
break;
}
i++;
}
if(cnt==temp.size()-1)
{
temp.erase(temp.begin()+1,temp.end());
}
if(temp.size()==1)
{
if(!flag2[temp[0]-0])
{
ans++;
flag2[temp[0]-0]=1;
}
}
else
{
i=0;
cnt=0;
bool flag[500]= {0};
while(temp[i]!='\0')
{
if(!flag[temp[i]-0])
{
flag[temp[i]-0]=1;
cnt++;
}
else
{
break;
}
i++;
}
if(cnt==temp.size())
{
ans++;
//mp2[temp]=1;
//if(cnt==1)
//flag2[temp[0]-0]=1;
}
}
/*else if(cnt==1)
{
//string tmp=NULL;
//char s=temp[0];
//tmp.append(s);
if(!flag2[temp[0]-0])
ans++;
}*/
//cout<<temp<<" "<<cnt<<endl;
}
if(!ans)
ans++;
printf("%d\n",ans);
/*for(int i=0;i<n;i++)
{
sort(vec[i].begin(),vec[i].end());
}*/
return 0;
}
/*getline(cin,str);
for(int i=0;i<str.size();i++)
{
while(str[i]!=' ')
{
if(!flag[str[i]-'0'])
{
flag[]
}
}
}*/
| 20.588785 | 68 | 0.312301 | YaminArafat |
a6781fb6c2cb7877b84ebede973c7c65b071d2e7 | 7,998 | cpp | C++ | VideoGameAssistants/PathPix/Path.cpp | chiendarrendor/AlbertsMisc | f017b29f65d1d47eb22db66dff0b6d2145794fc8 | [
"MIT"
] | null | null | null | VideoGameAssistants/PathPix/Path.cpp | chiendarrendor/AlbertsMisc | f017b29f65d1d47eb22db66dff0b6d2145794fc8 | [
"MIT"
] | null | null | null | VideoGameAssistants/PathPix/Path.cpp | chiendarrendor/AlbertsMisc | f017b29f65d1d47eb22db66dff0b6d2145794fc8 | [
"MIT"
] | null | null | null | #include "Path.hpp"
#include <iostream>
#include "Board.hpp"
Path::Path(char i_color,int i_length,int i_x,int i_y) :
m_Color(i_color),
m_Length(i_length),
m_IsValid(true),
m_IsDone(i_length == 1),
m_NumWiggles(0),
m_PathList()
{
m_PathList.push_back(std::pair<int,int>(i_x,i_y));
m_OriginalCell = m_PathList[0];
}
Path::Path(const Path &i_right) :
m_Color(i_right.m_Color),
m_Length(i_right.m_Length),
m_IsValid(i_right.m_IsValid),
m_IsDone(i_right.m_IsDone),
m_NumWiggles(i_right.m_NumWiggles),
m_PathList(i_right.m_PathList),
m_OriginalCell(i_right.m_OriginalCell)
{
}
const std::pair<int,int> &Path::GetOriginalCell() const
{
return m_OriginalCell;
}
int Path::GetNumWiggles() const
{
return m_NumWiggles;
}
char Path::GetColor() const
{
return m_Color;
}
size_t Path::GetLength() const
{
return m_Length;
}
bool Path::IsValid() const
{
return m_IsValid;
}
bool Path::IsDone() const
{
return m_IsDone;
}
const std::vector<std::pair<int,int> > &Path::GetPathList() const
{
return m_PathList;
}
Direction Path::GetDirectionAt(int i_x,int i_y) const
{
size_t i;
for (i = 0 ; i < m_PathList.size() ; ++i)
{
if (m_PathList[i].first != i_x ||
m_PathList[i].second != i_y) continue;
// if we get here, we're looking at the path step we want
if (i == m_PathList.size() - 1) return NONE;
// if we get here, there is a next path step
int dx = m_PathList[i].first - m_PathList[i+1].first;
int dy = m_PathList[i].second - m_PathList[i+1].second;
if (dx == 0 && dy == -1) return DOWN;
if (dx == 0 && dy == 1) return UP;
if (dx == -1 && dy == 0) return RIGHT;
if (dx == 1 && dy == 0) return LEFT;
std::cout << "non-orthogonal relationship!" << std::endl;
exit(1);
}
std::cout << "Can't find that cell in path!" << std::endl;
exit(1);
}
// given that the path end is at the tail of m_PathList
// if pathlist.size is already m_Length, return
// try all four directions
// in each direction
// if direction is not legal (i.e. off the board or through wall) go to next direction
// if space in that direction is empty
// add space to PathList
// add self to board in that location
// WiggleIter(i_board,o_legalpaths)
// remove this space from PathList
// remove self from board in that location
// else
// if Path in that space:
// has different color, go to next direction
// has different length, go to next direction
// is done, go to next direction
// 's tail isn't that space (last space of m_PathList) go to next direction
// if sum of m_PathList.size() + other.m_PathList.size() != m_Length go to next direction
// // if we get here, our path and theirs is connectable
// for each space in other.m_Pathlist from tail back to head,
// add it to m_PathList (at this point m_PathList.size == m_Length
// o_legalpaths.push_back(Path(*this));
// remove from tail of m_PathList other.m_PathList.size entries
int dx[] = { 0,0,-1,1 };
int dy[] = { -1,1,0,0 };
void Path::WiggleIter(Board &i_board,std::vector<Path> &o_legalpaths)
{
if (m_PathList.size() == m_Length) return;
int dir;
int curx = m_PathList.back().first;
int cury = m_PathList.back().second;
for (dir = UP ; dir <= RIGHT ; ++dir)
{
/*
for (size_t i = 0 ; i < m_PathList.size() ; ++i) std::cout << " ";
std::cout << "cur: " << curx << "," << cury << "," ;
if (dir == UP) std::cout << "UP";
if (dir == LEFT) std::cout << "LEFT";
if (dir == RIGHT) std::cout << "RIGHT";
if (dir == DOWN) std::cout << "DOWN";
std::cout << " (" << m_PathList.size() << ")";
std::cout << " ... ";
*/
if (i_board.DividerInDirection(curx,cury,(Direction)dir))
{
// std::cout << "divider" << std::endl;
continue;
}
int nx = curx + dx[dir];
int ny = cury + dy[dir];
if (nx < 0 || ny < 0 || nx >= i_board.GetWidth() || ny >= i_board.GetHeight())
{
// std::cout << "Off Board" << std::endl;
continue;
}
// if we get here, we have an unobstructed path to a valid space in this direction
Path *pOPath = i_board.GetCellPath(nx,ny);
if (pOPath == NULL)
{
// std::cout << "empty space! iterating" << std::endl;
m_PathList.push_back(std::pair<int,int>(nx,ny));
i_board.SetCellPath(*this,nx,ny);
WiggleIter(i_board,o_legalpaths);
i_board.ClearCellPath(nx,ny);
m_PathList.pop_back();
}
else
{
if (this == pOPath)
{
// std::cout << "self" << std::endl;
continue;
}
if (pOPath->GetColor() != this->GetColor())
{
// std::cout << "color mismatch" << std::endl;
continue;
}
if (pOPath->GetLength() != this->GetLength())
{
// std::cout << "length mismatch" << std::endl;
continue;
}
if (pOPath->GetPathList().back().first != nx ||
pOPath->GetPathList().back().second != ny)
{
// std::cout << "Other path terminal end not here" << std::endl;
continue;
}
if (pOPath->GetPathList().size() + m_PathList.size() != this->GetLength())
{
// std::cout << "Length sum mismatch" << std::endl;
continue;
}
// std::cout << "Path Found!" << std::endl;
int i;
// if we get here, this other path and ours is connectable
for (i = (int)pOPath->GetPathList().size()-1 ; i >= 0 ; --i)
{
// std::cout << "Copy other i: " << i << std::endl;
m_PathList.push_back(pOPath->GetPathList()[i]);
}
o_legalpaths.push_back(Path(*this));
for (i = (int)pOPath->GetPathList().size()-1 ; i >= 0 ; --i)
{
m_PathList.pop_back();
}
}
}
}
WiggleResult Path::Wiggle(Board &i_board,int i_wiggleidx)
{
std::vector<Path> legalpaths;
// std::cout << "Wiggling " << GetColor() << GetLength() << " at " <<
// m_PathList[0].first << "," << m_PathList[0].second << std::endl;
WiggleIter(i_board,legalpaths);
m_NumWiggles = legalpaths.size();
if (legalpaths.size() == 0) return ILLEGAL;
size_t oldsize = m_PathList.size();
if (legalpaths.size() == 1 || i_wiggleidx != -1)
{
// legalpaths is of size 1
// set m_PathList to legalpaths[0].m_PathList
// set IsDone to true
// for each entry in m_PathList
// if cell on board is not null and not this, path->Invalidate()
// set board cell to this
// extension...if we have a non -1 wiggleidx, use that one.
size_t widx = (i_wiggleidx != -1) ? i_wiggleidx : 0;
m_PathList = legalpaths[widx].GetPathList();
m_IsDone = true;
size_t i;
for (i = 0 ; i < m_PathList.size() ; ++i)
{
Path *pPath = i_board.GetCellPath(m_PathList[i].first,m_PathList[i].second);
if (pPath != NULL && pPath != this)
{
pPath->Invalidate();
}
i_board.SetCellPath(*this,m_PathList[i].first,m_PathList[i].second);
}
}
else
{
// find the largest common left-subset of all paths, and set
// m_PathList to that subset, and alter i_board spaces appropriately.
m_PathList.clear();
size_t i,j;
for (i = 0 ; i < GetLength() ; ++i)
{
for (j = 1 ; j < legalpaths.size() ; ++j)
{
if (legalpaths[j].GetPathList()[i] != legalpaths[0].GetPathList()[i])
{
goto SUBSETEND;
}
}
// if we get here, all cells match for this step of the path
m_PathList.push_back(legalpaths[0].GetPathList()[i]);
i_board.SetCellPath(*this,
legalpaths[0].GetPathList()[i].first,
legalpaths[0].GetPathList()[i].second);
}
SUBSETEND: ;
// to do...calculate set of all cells not in common left-subset
// common to all paths
}
if (m_PathList.size() == oldsize)
{
return UNCHANGED;
}
else
{
return CHANGED;
}
}
void Path::Invalidate()
{
m_IsValid = false;
m_PathList.clear();
}
| 26.929293 | 96 | 0.588522 | chiendarrendor |
a67956139c4a2dad295eea2905a68856f7235af6 | 1,371 | hpp | C++ | ext/kintinuous/kfusion/include/kfusion/LVRPipeline.hpp | uos/lvr | 9bb03a30441b027c39db967318877e03725112d5 | [
"BSD-3-Clause"
] | 38 | 2019-06-19T15:10:35.000Z | 2022-02-16T03:08:24.000Z | ext/kintinuous/kfusion/include/kfusion/LVRPipeline.hpp | jtpils/lvr2 | b1010dfcc930d9ae0ff5cfa5c88d0810d65368ce | [
"BSD-3-Clause"
] | 9 | 2019-06-19T16:19:51.000Z | 2021-09-17T08:31:25.000Z | ext/kintinuous/kfusion/include/kfusion/LVRPipeline.hpp | jtpils/lvr2 | b1010dfcc930d9ae0ff5cfa5c88d0810d65368ce | [
"BSD-3-Clause"
] | 13 | 2019-04-16T11:50:32.000Z | 2020-11-26T07:47:44.000Z | #ifndef LVR2_PIPELINE_HPP_
#define LVR2_PIPELINE_HPP_
#include <lvr/reconstruction/FastReconstruction.hpp>
#include <lvr/reconstruction/TSDFGrid.hpp>
#include <lvr/reconstruction/PointsetSurface.hpp>
#include <lvr/reconstruction/FastBox.hpp>
#include <lvr/io/PointBuffer.hpp>
#include <lvr/io/DataStruct.hpp>
#include <lvr/io/Timestamp.hpp>
#include <lvr/geometry/HalfEdgeVertex.hpp>
#include <lvr/geometry/HalfEdgeKinFuMesh.hpp>
#include <lvr/geometry/BoundingBox.hpp>
#include <kfusion/types.hpp>
#include <kfusion/cuda/tsdf_volume.hpp>
#include <kfusion/cuda/projective_icp.hpp>
#include <kfusion/LinearPipeline.hpp>
#include <kfusion/GridStage.hpp>
#include <kfusion/MeshStage.hpp>
#include <kfusion/OptimizeStage.hpp>
#include <kfusion/FusionStage.hpp>
using namespace lvr;
typedef ColorVertex<float, unsigned char> cVertex;
typedef HalfEdgeKinFuMesh<cVertex, lvr::Normal<float> > HMesh;
typedef HMesh* MeshPtr;
namespace kfusion
{
class LVRPipeline
{
public:
LVRPipeline(KinFuParams params);
~LVRPipeline();
void addTSDFSlice(TSDFSlice slice, const bool last_shift);
void resetMesh();
MeshPtr getMesh() {return pl_.GetResult();}
double calcTimeStats();
private:
MeshPtr meshPtr_;
size_t slice_count_;
std::vector<double> timeStats_;
LinearPipeline<pair<TSDFSlice, bool> , MeshPtr> pl_;
};
}
#endif
| 23.637931 | 62 | 0.760759 | uos |
a679fae8c6775e32ac4f0f9439e1c9b4f12b3847 | 5,250 | cpp | C++ | projects/vs2019/mfc/iutest_mfc_sample.cpp | dsyoi/iutest | b7b08c6ac4c75f98f87aa5756244afc93e4b624f | [
"BSD-3-Clause"
] | 58 | 2015-07-20T04:30:18.000Z | 2021-12-28T17:18:00.000Z | projects/vs2019/mfc/iutest_mfc_sample.cpp | dsyoi/iutest | b7b08c6ac4c75f98f87aa5756244afc93e4b624f | [
"BSD-3-Clause"
] | 467 | 2015-05-07T10:42:47.000Z | 2022-03-26T04:01:00.000Z | projects/vs2019/mfc/iutest_mfc_sample.cpp | dsyoi/iutest | b7b08c6ac4c75f98f87aa5756244afc93e4b624f | [
"BSD-3-Clause"
] | 13 | 2015-10-05T08:30:27.000Z | 2021-04-30T18:56:03.000Z | // iutest_mfc_sample.cpp : コンソール アプリケーションのエントリ ポイントを定義します。
//
#include "stdafx.h"
#include "iutest_mfc_sample.h"
#include "iutest.hpp"
#include <map>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// 唯一のアプリケーション オブジェクトです。
CWinApp theApp;
using namespace std;
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
IUTEST_UNUSED_VAR(envp);
int nRetCode = 0;
HMODULE hModule = ::GetModuleHandle(NULL);
if (hModule != NULL)
{
// MFC を初期化して、エラーの場合は結果を印刷します。
if (!AfxWinInit(hModule, NULL, ::GetCommandLine(), 0))
{
// TODO: 必要に応じてエラー コードを変更してください。
_tprintf(_T("致命的なエラー: MFC の初期化ができませんでした。\n"));
nRetCode = 1;
}
else
{
// TODO: アプリケーションの動作を記述するコードをここに挿入してください。
IUTEST_INIT(&argc, argv);
nRetCode = IUTEST_RUN_ALL_TESTS();
}
}
else
{
// TODO: 必要に応じてエラー コードを変更してください。
_tprintf(_T("致命的なエラー: GetModuleHandle が失敗しました\n"));
nRetCode = 1;
}
return nRetCode;
}
IUTEST(MFC, String)
{
CString str = _T("Test");
IUTEST_ASSERT_EQ(_T("Test"), str);
IUTEST_ASSERT_STREQ(_T("Test"), str);
IUTEST_ASSERT_STREQ(str, str);
IUTEST_ASSERT_STRIN(str, _T("Test"));
}
IUTEST(MFC, Rect)
{
CRect r = { 0, 0, 100, 100 };
IUTEST_ASSERT_EQ(r, r);
}
template<typename T>
struct test_value
{
static T get(int index) { return static_cast<T>(index); }
};
template<typename T>
struct test_value< T* >
{
static T* get(int) { return NULL; }
};
template<>
struct test_value < CString >
{
static CString get(int index) { CString s; s.Format(_T("%d"), index); return s; }
};
template<typename T>
class MFCArrayTypedTest : public ::iutest::Test {};
IUTEST_TYPED_TEST_SUITE(MFCArrayTypedTest, ::iutest::Types<CArray<int>, CTypedPtrArray<CPtrArray, int*>
, CByteArray, CWordArray, CDWordArray, CUIntArray, CStringArray, CPtrArray, CObArray>);
IUTEST_TYPED_TEST(MFCArrayTypedTest, EqCollections)
{
typename iutest::mfc::CContainer<TypeParam>::BASE_TYPE a[10];
TypeParam ar;
ar.SetSize(IUTEST_PP_COUNTOF(a));
for(int i = 0; i < IUTEST_PP_COUNTOF(a); ++i)
{
a[i] = test_value<iutest::mfc::CContainer<TypeParam>::BASE_TYPE>::get(i);
ar[i] = test_value<iutest::mfc::CContainer<TypeParam>::BASE_TYPE>::get(i);
}
IUTEST_ASSERT_EQ_COLLECTIONS(
::iutest::mfc::begin(ar)
, ::iutest::mfc::end(ar)
, ::std::begin(a)
, ::std::end(a)
);
}
template<typename T>
class MFCListTypedTest : public ::iutest::Test {};
IUTEST_TYPED_TEST_SUITE(MFCListTypedTest, ::iutest::Types<CList<int>, CTypedPtrList<CPtrList, int*>
, CStringList, CPtrList, CObList>);
IUTEST_TYPED_TEST(MFCListTypedTest, EqCollections)
{
typename iutest::mfc::CContainer<TypeParam>::BASE_TYPE a[10];
TypeParam list;
for(int i = 0; i < IUTEST_PP_COUNTOF(a); ++i)
{
a[i] = test_value<iutest::mfc::CContainer<TypeParam>::BASE_TYPE>::get(i);
list.AddTail(test_value<iutest::mfc::CContainer<TypeParam>::BASE_TYPE>::get(i));
}
IUTEST_ASSERT_EQ_COLLECTIONS(
::iutest::mfc::begin(list)
, ::iutest::mfc::end(list)
, ::std::begin(a)
, ::std::end(a)
);
}
template<typename T>
class MFCMapTypedTest : public ::iutest::Test {};
IUTEST_TYPED_TEST_SUITE(MFCMapTypedTest, ::iutest::Types< CMap<int, int, int, int>
, CTypedPtrMap<CMapPtrToPtr, int*, int*>, CTypedPtrMap<CMapPtrToWord, int*, WORD>
, CTypedPtrMap<CMapWordToPtr, WORD, int*>, CTypedPtrMap<CMapStringToPtr, CString, int*>
, CMapWordToPtr, CMapWordToOb, CMapPtrToPtr, CMapPtrToWord
, CMapStringToPtr, CMapStringToOb, CMapStringToString >);
IUTEST_TYPED_TEST(MFCMapTypedTest, EqCollections)
{
TypeParam map;
for(int i = 0; i < 10; ++i)
{
map.SetAt(test_value<iutest::mfc::CContainer<TypeParam>::BASE_KEY>::get(i)
, test_value<iutest::mfc::CContainer<TypeParam>::BASE_VALUE>::get(i) );
}
IUTEST_ASSERT_EQ_COLLECTIONS(
::iutest::mfc::begin(map)
, ::iutest::mfc::end(map)
, ::iutest::mfc::begin(map)
, ::iutest::mfc::end(map)
);
}
#if IUTEST_HAS_MATCHERS
using namespace ::iutest::matchers;
IUTEST_TYPED_TEST(MFCArrayTypedTest, Matcher)
{
TypeParam ar;
ar.SetSize(10);
for(int i = 0; i < 10; ++i)
{
ar[i] = test_value<iutest::mfc::CContainer<TypeParam>::BASE_TYPE>::get(i);
}
IUTEST_EXPECT_THAT(::iutest::mfc::make_container(ar), Each(_));
}
IUTEST_TYPED_TEST(MFCListTypedTest, Matcher)
{
TypeParam list;
for(int i = 0; i < 10; ++i)
{
list.AddTail(test_value<iutest::mfc::CContainer<TypeParam>::BASE_TYPE>::get(i));
}
IUTEST_EXPECT_THAT(::iutest::mfc::make_container(list), Each(_));
}
IUTEST_TYPED_TEST(MFCMapTypedTest, Matcher)
{
TypeParam map;
for(int i = 0; i < 10; ++i) {
map.SetAt(test_value<iutest::mfc::CContainer<TypeParam>::BASE_KEY>::get(i)
, test_value<iutest::mfc::CContainer<TypeParam>::BASE_VALUE>::get(i));
}
IUTEST_EXPECT_THAT(::iutest::mfc::make_container(map), Each(Key(_)));
IUTEST_EXPECT_THAT(::iutest::mfc::make_container(map), Each(Pair(_, _)));
}
#endif
| 27.202073 | 103 | 0.640381 | dsyoi |
a67dc4421293d8499c9fc25db09eaba3ced3da83 | 656 | cpp | C++ | Demos/bitmap_demo_importexport.cpp | mstniy/MyBMPLib | d42f0d09f30a450a5beb04f83d24b36f6a9ee66a | [
"Apache-2.0"
] | null | null | null | Demos/bitmap_demo_importexport.cpp | mstniy/MyBMPLib | d42f0d09f30a450a5beb04f83d24b36f6a9ee66a | [
"Apache-2.0"
] | null | null | null | Demos/bitmap_demo_importexport.cpp | mstniy/MyBMPLib | d42f0d09f30a450a5beb04f83d24b36f6a9ee66a | [
"Apache-2.0"
] | null | null | null | #include<windows.h>
#include "..\bitmap.h"
#include<string>
#include<iostream>
#include<stdio.h>
using namespace std;
void Fail(const char *funcname,HWND hwnd=NULL)
{
DWORD error=GetLastError();
printf("%s failed (%d)\n",funcname,error);
FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE));
getchar();
ExitProcess(1);
}
int main()
{
string filename;
Bitmap bmp;
getline(cin,filename);
if (BImportFromFile(&bmp,filename.c_str())==false)
Fail("BImportFromFile");
BSetPixel(bmp,0,0,RGB(0,0,0));
BSetPixel(bmp,1,0,RGB(0,0,0));
if (BExportToFile(bmp,TEXT("output.bmp"))==false)
Fail("BExportToFile");
return 0;
}
| 23.428571 | 58 | 0.684451 | mstniy |
a67f0d4077a9ccfdeb0fe14925f327e622227730 | 2,720 | cpp | C++ | oneflow/user/ops/gpt_data_loader_op.cpp | wangyuyue/oneflow | 0a71c22fe8355392acc8dc0e301589faee4c4832 | [
"Apache-2.0"
] | 3,285 | 2020-07-31T05:51:22.000Z | 2022-03-31T15:20:16.000Z | oneflow/user/ops/gpt_data_loader_op.cpp | wangyuyue/oneflow | 0a71c22fe8355392acc8dc0e301589faee4c4832 | [
"Apache-2.0"
] | 2,417 | 2020-07-31T06:28:58.000Z | 2022-03-31T23:04:14.000Z | oneflow/user/ops/gpt_data_loader_op.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 "oneflow/core/framework/framework.h"
namespace oneflow {
REGISTER_NO_GRAD_CPU_ONLY_USER_OP("megatron_gpt_mmap_data_loader")
.OptionalInput("iteration")
.Output("out")
.Attr<std::string>("data_file_prefix")
.Attr<int64_t>("seq_length")
.Attr<int64_t>("label_length", 1)
.Attr<int64_t>("num_samples")
.Attr<int64_t>("batch_size")
.Attr<DataType>("dtype")
.Attr<std::vector<int64_t>>("split_sizes")
.Attr<int64_t>("split_index")
.Attr<bool>("shuffle")
.Attr<int64_t>("random_seed")
.Attr<std::vector<std::string>>("nd_sbp")
.SetLogicalTensorDescInferFn([](user_op::InferContext* ctx) -> Maybe<void> {
int64_t batch_size = ctx->Attr<int64_t>("batch_size");
int64_t sample_len = ctx->Attr<int64_t>("seq_length") + ctx->Attr<int64_t>("label_length");
user_op::TensorDesc* out_desc = ctx->OutputTensorDesc("out", 0);
*out_desc->mut_shape() = Shape({batch_size, sample_len});
return Maybe<void>::Ok();
})
.SetDataTypeInferFn([](user_op::InferContext* ctx) -> Maybe<void> {
*ctx->OutputTensorDesc("out", 0)->mut_data_type() = ctx->Attr<DataType>("dtype");
return Maybe<void>::Ok();
})
.SetGetSbpFn([](user_op::SbpContext* ctx) -> Maybe<void> {
ctx->NewBuilder().Split(ctx->outputs(), 0).Build();
return Maybe<void>::Ok();
})
.SetNdSbpInferFn([](user_op::InferNdSbpFnContext* ctx) -> Maybe<void> {
cfg::SbpParallel default_sbp;
default_sbp.mutable_split_parallel()->set_axis(0);
return user_op::InferNdSbp4SrcOp(ctx, default_sbp);
})
.SetInputArgModifyFn([](const user_op::GetInputArgModifier& GetInputArgModifierFn,
const user_op::UserOpConfWrapper& conf) -> Maybe<void> {
if (!conf.has_input("iteration", 0)) { return Maybe<void>::Ok(); }
user_op::InputArgModifier* input_modifier = GetInputArgModifierFn("iteration", 0);
CHECK_OR_RETURN(input_modifier != nullptr);
input_modifier->set_is_mutable(true);
input_modifier->set_requires_grad(false);
return Maybe<void>::Ok();
});
} // namespace oneflow
| 41.846154 | 97 | 0.6875 | wangyuyue |
a67fdd8870c208c19c891fc122c70fc83865786b | 1,583 | cpp | C++ | Plugins/Tweaks/ItemChargesCost.cpp | summonFox/unified | 47ab7d051fe52c26e2928b569e9fe7aec5aa8705 | [
"MIT"
] | 111 | 2018-01-16T18:49:19.000Z | 2022-03-13T12:33:54.000Z | Plugins/Tweaks/ItemChargesCost.cpp | summonFox/unified | 47ab7d051fe52c26e2928b569e9fe7aec5aa8705 | [
"MIT"
] | 636 | 2018-01-17T10:05:31.000Z | 2022-03-28T20:06:03.000Z | Plugins/Tweaks/ItemChargesCost.cpp | summonFox/unified | 47ab7d051fe52c26e2928b569e9fe7aec5aa8705 | [
"MIT"
] | 110 | 2018-01-16T19:05:54.000Z | 2022-03-28T03:44:16.000Z | #include "nwnx.hpp"
#include "API/CNWItemProperty.hpp"
#include "API/CNWRules.hpp"
#include "API/CNWSItem.hpp"
namespace Tweaks {
using namespace NWNXLib;
using namespace NWNXLib::API;
static int s_ChargesCostBehavior;
void ItemChargesCost() __attribute__((constructor));
void ItemChargesCost()
{
s_ChargesCostBehavior = Config::Get<int>("ITEM_CHARGES_COST_MODE", 0);
if (s_ChargesCostBehavior == 0)
return;
else if (s_ChargesCostBehavior < 0 || s_ChargesCostBehavior > 3)
{
LOG_INFO("Unknown value for NWNX_TWEAKS_ITEM_CHARGES_COST_MODE.");
return;
}
LOG_INFO("Changing cost for items with charges.");
static Hooks::Hook s_CalculateBaseCostsHook = Hooks::HookFunction(Functions::_ZN8CNWSItem18CalculateBaseCostsEv,
(void*)+[](CNWSItem* pThis) -> void
{
int32_t savedCharges = pThis->m_nNumCharges;
switch (s_ChargesCostBehavior)
{
case 1:
pThis->m_nNumCharges = std::min(pThis->m_nNumCharges * 5, 250);
break;
case 2:
pThis->m_nNumCharges = std::min(pThis->m_nNumCharges, 50) * 5 + std::max(pThis->m_nNumCharges - 50, 0) * 1.25;
break;
case 3:
pThis->m_nNumCharges *= 5;
break;
default:
break;
}
s_CalculateBaseCostsHook->CallOriginal<void>(pThis);
pThis->m_nNumCharges = savedCharges;
}, Hooks::Order::Early);
}
}
| 26.830508 | 130 | 0.587492 | summonFox |
a6804e9c6a6a50f611b51c279b00e6de74ad18ea | 1,136 | cpp | C++ | codes/CodeForces/Round #224/cf394C.cpp | JeraKrs/ACM | edcd61ec6764b8cd804bf1538dfde53d0ff572b5 | [
"Apache-2.0"
] | null | null | null | codes/CodeForces/Round #224/cf394C.cpp | JeraKrs/ACM | edcd61ec6764b8cd804bf1538dfde53d0ff572b5 | [
"Apache-2.0"
] | null | null | null | codes/CodeForces/Round #224/cf394C.cpp | JeraKrs/ACM | edcd61ec6764b8cd804bf1538dfde53d0ff572b5 | [
"Apache-2.0"
] | null | null | null | #include <stdio.h>
#include <string.h>
const int N = 1e3+10;
const int M = 4;
const char sign[M][M] = { "00", "01", "10", "11"};
int n, m, c[M], g[N][N];
void init() {
char str[M];
memset(g, 0, sizeof(g));
memset(c, 0, sizeof(c));
scanf("%d%d", &n, &m);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
scanf("%s", str);
if (str[0] == '1' && str[1] == '1') c[2]++;
else if (str[0] == '0' && str[1] == '0') c[0]++;
else c[1]++;
}
}
}
void set() {
for (int i = 0; i < n; i++) {
if (i&1) {
for (int j = m-1; j >= 0; j--) {
if (c[2]) {
g[i][j] = 3;
c[2]--;
} else if (c[1]) {
g[i][j] = 1;
c[1]--;
}
if (c[1] == 0 && c[2] == 0) return;
}
} else {
for (int j = 0; j < m; j++) {
if (c[2]) {
g[i][j] = 3;
c[2]--;
} else if (c[1]) {
g[i][j] = 2;
c[1]--;
}
if (c[1] == 0 && c[2] == 0) return ;
}
}
}
}
void solve() {
set();
for (int i = 0; i < n; i++) {
printf("%s", sign[g[i][0]]);
for (int j = 1; j < m; j++) printf(" %s", sign[g[i][j]]);
printf("\n");
}
}
int main () {
init();
solve();
return 0;
}
| 16.705882 | 59 | 0.37412 | JeraKrs |
a68226e4a30b9061509eba4a2e909e98f5380abf | 1,920 | cpp | C++ | src/snail/detail/sdl_impl.cpp | XrosFade/ElonaFoobar | c33880080e0b475103ae3ea7d546335f9d4abd02 | [
"MIT"
] | null | null | null | src/snail/detail/sdl_impl.cpp | XrosFade/ElonaFoobar | c33880080e0b475103ae3ea7d546335f9d4abd02 | [
"MIT"
] | null | null | null | src/snail/detail/sdl_impl.cpp | XrosFade/ElonaFoobar | c33880080e0b475103ae3ea7d546335f9d4abd02 | [
"MIT"
] | null | null | null | #ifdef ANDROID
#include "sdl.hpp"
#endif
namespace elona
{
namespace snail
{
namespace detail
{
void enforce_sdl(int result)
{
if (result != 0)
{
throw SDLError{::SDL_GetError()};
}
}
void enforce_ttf(int result)
{
if (result != 0)
{
throw SDLError{::TTF_GetError()};
}
}
void enforce_image(int result)
{
if (result != 0)
{
throw SDLError{::IMG_GetError()};
}
}
void enforce_mixer(int result)
{
if (result != 0)
{
throw SDLError{::Mix_GetError()};
}
}
void* enforce_sdl_internal(void* result)
{
return result ? result : throw SDLError(::SDL_GetError());
}
void* enforce_ttf_internal(void* result)
{
return result ? result : throw SDLError(::TTF_GetError());
}
void* enforce_img_internal(void* result)
{
return result ? result : throw SDLError(::IMG_GetError());
}
void* enforce_mixer_internal(void* result)
{
return result ? result : throw SDLError(::Mix_GetError());
}
SDLCore::SDLCore()
{
enforce_sdl(::SDL_Init(SDL_INIT_EVERYTHING));
}
SDLCore::~SDLCore()
{
::SDL_Quit();
}
SDLTTF::SDLTTF()
{
enforce_ttf(::TTF_Init());
}
SDLTTF::~SDLTTF()
{
::TTF_Quit();
}
SDLImage::SDLImage()
{
auto flags = IMG_INIT_PNG | IMG_INIT_JPG;
auto result = ::IMG_Init(flags);
if ((flags & result) != flags)
{
throw SDLError{"Failed to initialize SDL2Image"};
}
}
SDLImage::~SDLImage()
{
::IMG_Quit();
}
SDLMixer::SDLMixer()
{
// auto flags = MIX_INIT_OGG | MIX_INIT_MP3;
auto flags = 0;
auto result = ::Mix_Init(flags);
if ((flags & result) != flags)
{
throw SDLError{"Failed to initialize SDL2Mixer"};
}
enforce_mixer(::Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048));
}
SDLMixer::~SDLMixer()
{
::Mix_CloseAudio();
::Mix_Quit();
}
} // namespace detail
} // namespace snail
} // namespace elona
| 12.631579 | 71 | 0.610938 | XrosFade |
a6874da4708fe9f3e9010e7cc5f26a55dc68045e | 28,009 | cc | C++ | test/retic/fddTest.cc | enotnadoske/drunos | 79b72078e613c9c5d4e5c37721b726ca3374299b | [
"Apache-2.0"
] | 9 | 2019-04-04T18:03:36.000Z | 2019-05-03T23:48:59.000Z | test/retic/fddTest.cc | enotnadoske/drunos | 79b72078e613c9c5d4e5c37721b726ca3374299b | [
"Apache-2.0"
] | 16 | 2019-04-04T12:22:19.000Z | 2019-04-09T19:04:42.000Z | test/retic/fddTest.cc | enotnadoske/drunos | 79b72078e613c9c5d4e5c37721b726ca3374299b | [
"Apache-2.0"
] | 2 | 2019-10-11T14:17:26.000Z | 2022-03-15T10:06:08.000Z | #include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "common.hh"
#include "retic/fdd.hh"
#include "retic/fdd_compiler.hh"
#include "retic/policies.hh"
#include "retic/traverse_fdd.hh"
#include "oxm/openflow_basic.hh"
using namespace runos;
using namespace retic;
using namespace ::testing;
using sec = std::chrono::seconds;
TEST(TypeComprassion, Types) {
const auto ofb_switch_id = oxm::switch_id();
const auto ofb_eth_src = oxm::eth_src();
const auto ofb_eth_type = oxm::eth_type();
EXPECT_EQ(0, fdd::compare_types(ofb_switch_id, ofb_switch_id));
EXPECT_EQ(0, fdd::compare_types(ofb_eth_src, ofb_eth_src));
EXPECT_EQ(0, fdd::compare_types(ofb_eth_type, ofb_eth_type));
EXPECT_GT(0, fdd::compare_types(ofb_eth_type, ofb_switch_id));
EXPECT_GT(0, fdd::compare_types(ofb_eth_type, ofb_eth_src));
}
TEST(EqualFdd, EqualTest) {
fdd::diagram node1 = fdd::node{F<1>() == 1, fdd::leaf{}, fdd::leaf{}};
fdd::diagram node2 = fdd::node{F<1>() == 1, fdd::leaf{}, fdd::leaf{}};
fdd::diagram node3 = fdd::node{F<1>() == 1, fdd::leaf{}, fdd::leaf{{oxm::field_set{F<1>() == 1}}}};
fdd::diagram node4 = fdd::node{F<1>() == 2, fdd::leaf{}, fdd::leaf{}};
fdd::diagram node5 = fdd::node{F<2>() == 1, fdd::leaf{}, fdd::leaf{}};
fdd::diagram node6 = fdd::node{F<1>() == 1, fdd::leaf{{oxm::field_set{F<1>() == 1}}}, fdd::leaf{}};
fdd::diagram node7 = fdd::node{F<1>() == 1, fdd::leaf{}, fdd::leaf{{oxm::field_set{F<2>() == 2}, oxm::field_set{F<1>() == 1}}}};
fdd::diagram node8 = fdd::node{F<1>() == 1, fdd::leaf{}, fdd::leaf{{oxm::field_set{F<1>() == 1}, oxm::field_set{F<2>() == 2}}}};
EXPECT_EQ(node1, node2);
EXPECT_NE(node1, node3);
EXPECT_NE(node1, node4);
EXPECT_NE(node1, node5);
EXPECT_NE(node1, node5);
EXPECT_EQ(node7, node8);
}
TEST(EqualFdd, EqualWithFlowSettings) {
fdd::diagram d1 = fdd::leaf{{oxm::field_set{}}, FlowSettings{sec(10), sec(20)}};
fdd::diagram d2 = fdd::leaf{{oxm::field_set{}}, FlowSettings{sec(10), sec(20)}};
fdd::diagram d3 = fdd::leaf{{oxm::field_set{}}, FlowSettings{sec(1234), sec(20)}};
fdd::diagram d4 = fdd::leaf{{oxm::field_set{}}, FlowSettings{sec(10), sec(1234)}};
EXPECT_EQ(d1, d2);
EXPECT_NE(d1, d3);
EXPECT_NE(d1, d4);
}
TEST(FddCompilerTest, StopCompile) {
policy p = stop();
fdd::diagram diagram = fdd::compile(p);
fdd::leaf leaf = boost::get<fdd::leaf>(diagram);
ASSERT_TRUE(leaf.sets.empty());
}
TEST(FddCompilerTest, IdCompile) {
policy p = id();
fdd::diagram diagram = fdd::compile(p);
fdd::diagram true_value = fdd::leaf{{ oxm::field_set{} }};
ASSERT_EQ(diagram, true_value);
}
TEST(FddCompilerTest, Modify) {
policy p = modify(F<1>() << 100);
fdd::diagram diagram = fdd::compile(p);
fdd::leaf leaf = boost::get<fdd::leaf>(diagram);
ASSERT_THAT(leaf.sets, SizeIs(1));
ASSERT_EQ(oxm::field_set{F<1>() == 100}, leaf.sets[0]);
}
TEST(FddCompilerTest, Filter) {
policy p = filter(F<1>() == 100);
fdd::diagram diagram = fdd::compile(p);
fdd::node node = boost::get<fdd::node>(diagram);
fdd::diagram true_value = fdd::node {
F<1>() == 100,
fdd::leaf {{ oxm::field_set{} }},
fdd::leaf { }
};
ASSERT_EQ(true_value, diagram);
}
TEST(FddCompilerTest, ParallelLeafLeaf) {
policy p = modify(F<1>() << 100) + modify(F<2>() << 200);
fdd::diagram diagram = fdd::compile(p);
fdd::leaf leaf = boost::get<fdd::leaf>(diagram);
ASSERT_THAT(leaf.sets, SizeIs(2));
EXPECT_THAT(leaf.sets,
UnorderedElementsAre(
oxm::field_set{F<1>() == 100},
oxm::field_set{F<2>() == 200}
));
}
TEST(FddCompilerTest, ParallellNodeLeaf) {
policy p = filter(F<1>() == 1) + modify(F<3>() << 3);
fdd::diagram diagram = fdd::compile(p);
fdd::node node = boost::get<fdd::node>(diagram);
oxm::field<> true_value = F<1>() == 1;
EXPECT_EQ(true_value, node.field);
fdd::leaf pos = boost::get<fdd::leaf>(node.positive);
EXPECT_THAT(pos.sets, UnorderedElementsAre(
oxm::field_set{F<3>() == 3},
oxm::field_set() // filter empty value
));
fdd::leaf neg = boost::get<fdd::leaf>(node.negative);
EXPECT_THAT(neg.sets, UnorderedElementsAre(oxm::field_set{F<3>() == 3}));
}
TEST(FddCompilerTest, ParallellLeafNode) {
policy p = modify(F<3>() << 3) + filter(F<1>() == 1);
fdd::diagram diagram = fdd::compile(p);
fdd::node node = boost::get<fdd::node>(diagram);
oxm::field<> true_value = F<1>() == 1;
EXPECT_EQ(true_value, node.field);
fdd::leaf pos = boost::get<fdd::leaf>(node.positive);
EXPECT_THAT(pos.sets, UnorderedElementsAre(
oxm::field_set{F<3>() == 3},
oxm::field_set() // filter empty value
));
fdd::leaf neg = boost::get<fdd::leaf>(node.negative);
EXPECT_THAT(neg.sets, UnorderedElementsAre(oxm::field_set{F<3>() == 3}));
}
TEST(FddCompilerTest, ParallelNodeNodeEquals) {
fdd::diagram node1 = fdd::node{
{F<1>() == 1},
fdd::leaf{{oxm::field_set{F<2>() == 2}}},
fdd::leaf{{oxm::field_set{F<3>() == 3}}}
};
fdd::diagram node2 = fdd::node{
{F<1>() == 1},
fdd::leaf{{oxm::field_set{F<5>() == 5}}},
fdd::leaf{{oxm::field_set{F<6>() == 6}}}
};
fdd::parallel_composition pc;
fdd::diagram diagram = boost::apply_visitor(pc, node1, node2);
fdd::node node = boost::get<fdd::node>(diagram);
EXPECT_EQ(oxm::field<>(F<1>() == 1), node.field);
fdd::leaf pos = boost::get<fdd::leaf>(node.positive);
EXPECT_THAT(pos.sets, UnorderedElementsAre(
oxm::field_set{F<2>() == 2},
oxm::field_set{F<5>() == 5}
));
fdd::leaf neg = boost::get<fdd::leaf>(node.negative);
EXPECT_THAT(neg.sets, UnorderedElementsAre(
oxm::field_set{F<3>() == 3},
oxm::field_set{F<6>() == 6}
));
}
TEST(FddCompilerTest, ParallelNodeNodeEqualFields) {
fdd::diagram node1 = fdd::node{
{F<1>() == 1},
fdd::leaf{{oxm::field_set{F<2>() == 2}}},
fdd::leaf{{oxm::field_set{F<3>() == 3}}}
};
fdd::diagram node2 = fdd::node{
{F<1>() == 2},
fdd::leaf{{oxm::field_set{F<5>() == 5}}},
fdd::leaf{{oxm::field_set{F<6>() == 6}}}
};
fdd::parallel_composition pc;
fdd::diagram result_value1 = boost::apply_visitor(pc, node1, node2);
fdd::diagram result_value2 = boost::apply_visitor(pc, node2, node1);
fdd::diagram true_value = fdd::node {
{F<1>() == 1},
fdd::leaf {{
oxm::field_set{F<2>() == 2},
oxm::field_set{F<6>() == 6}
}},
fdd::node{
{F<1>() == 2},
fdd::leaf{{
oxm::field_set{F<3>() == 3},
oxm::field_set{F<5>() == 5}
}},
fdd::leaf{{
oxm::field_set{F<6>() == 6},
oxm::field_set{F<3>() == 3}
}}
}
};
EXPECT_EQ(true_value, result_value1);
EXPECT_EQ(true_value, result_value2);
}
TEST(FddCompilerTest, ParallelNodeNodeDiffFields) {
fdd::diagram node1 = fdd::node{
{F<1>() == 1},
fdd::leaf{{oxm::field_set{F<2>() == 2}}},
fdd::leaf{{oxm::field_set{F<3>() == 3}}}
};
fdd::diagram node2 = fdd::node{
{F<2>() == 2},
fdd::leaf{{oxm::field_set{F<5>() == 5}}},
fdd::leaf{{oxm::field_set{F<6>() == 6}}}
};
fdd::parallel_composition pc;
fdd::diagram result_value1 = boost::apply_visitor(pc, node1, node2);
fdd::diagram result_value2 = boost::apply_visitor(pc, node2, node1);
fdd::diagram true_value = fdd::node {
{F<1>() == 1},
fdd::node {
{F<2>() == 2},
fdd::leaf{{
oxm::field_set{F<2>() == 2},
oxm::field_set{F<5>() == 5}
}},
fdd::leaf{{
oxm::field_set{F<2>() == 2},
oxm::field_set{F<6>() == 6}
}}
},
fdd::node{
{F<2>() == 2},
fdd::leaf{{
oxm::field_set{F<3>() == 3},
oxm::field_set{F<5>() == 5}
}},
fdd::leaf{{
oxm::field_set{F<3>() == 3},
oxm::field_set{F<6>() == 6}
}}
}
};
EXPECT_EQ(true_value, result_value1);
EXPECT_EQ(true_value, result_value2);
}
TEST(FddCompilerTest, RestrictionLeafTrue) {
fdd::diagram d = fdd::leaf{{oxm::field_set{F<2>() == 2}}};
auto r = fdd::restriction{ F<1>() == 1, d, true };
fdd::diagram true_value = fdd::node {
F<1>() == 1,
fdd::leaf{{oxm::field_set{F<2>() == 2}}},
fdd::leaf{}
};
EXPECT_EQ(true_value, r.apply());
}
TEST(FddCompilerTest, RestrictionNodeEqualTrue) {
fdd::diagram d = fdd::node {
F<1>() == 1,
fdd::leaf{{oxm::field_set{F<2>() == 2}}},
fdd::leaf{{oxm::field_set{F<3>() == 3}}}
};
auto r = fdd::restriction{ F<1>() == 1, d, true };
fdd::diagram true_value = fdd::node {
F<1>() == 1,
fdd::leaf{{oxm::field_set{F<2>() == 2}}},
fdd::leaf{}
};
EXPECT_EQ(true_value, r.apply());
}
TEST(FddCompilerTest, RestrictionNodeEqualTypesTrue) {
fdd::diagram d = fdd::node {
F<1>() == 2,
fdd::leaf{{oxm::field_set{F<2>() == 2}}},
fdd::leaf{{oxm::field_set{F<3>() == 3}}}
};
auto r = fdd::restriction{ F<1>() == 1, d, true };
fdd::diagram true_value = fdd::node {
F<1>() == 1,
fdd::leaf{{oxm::field_set{F<3>() == 3}}},
fdd::leaf{}
};
EXPECT_EQ(true_value, r.apply());
}
TEST(FddCompilerTest, RestrictionNodeDiffTypes1Less2True) {
fdd::diagram d = fdd::node {
F<2>() == 2,
fdd::leaf{{oxm::field_set{F<2>() == 2}}},
fdd::leaf{{oxm::field_set{F<3>() == 3}}}
};
auto r = fdd::restriction{ F<1>() == 1, d, true };
fdd::diagram true_value = fdd::node {
F<1>() == 1,
fdd::node {
F<2>() == 2,
fdd::leaf{{oxm::field_set{F<2>() == 2}}},
fdd::leaf{{oxm::field_set{F<3>() == 3}}}
},
fdd::leaf{}
};
EXPECT_EQ(true_value, r.apply());
}
TEST(FddCompilerTest, RestrictionNodeOtherwiseTrue) {
fdd::diagram d = fdd::node {
F<1>() == 1,
fdd::leaf{{oxm::field_set{F<2>() == 2}}},
fdd::leaf{{oxm::field_set{F<3>() == 3}}}
};
auto r = fdd::restriction{ F<2>() == 2, d, true };
fdd::diagram true_value = fdd::node {
F<1>() == 1,
fdd::node {
F<2>() == 2,
fdd::leaf{{oxm::field_set{F<2>() == 2}}},
fdd::leaf{}
},
fdd::node {
F<2>() == 2,
fdd::leaf{{oxm::field_set{F<3>() == 3}}},
fdd::leaf{}
},
};
EXPECT_EQ(true_value, r.apply());
}
TEST(FddCompilerTest, RestrictionLeafFalse) {
fdd::diagram d = fdd::leaf{{oxm::field_set{F<2>() == 2}}};
auto r = fdd::restriction{ F<1>() == 1, d, false };
fdd::diagram true_value = fdd::node {
F<1>() == 1,
fdd::leaf{},
fdd::leaf{{oxm::field_set{F<2>() == 2}}}
};
EXPECT_EQ(true_value, r.apply());
}
TEST(FddCompilerTest, RestrictionNodeEqualFalse) {
fdd::diagram d = fdd::node {
F<1>() == 1,
fdd::leaf{{oxm::field_set{F<2>() == 2}}},
fdd::leaf{{oxm::field_set{F<3>() == 3}}}
};
auto r = fdd::restriction{ F<1>() == 1, d, false };
fdd::diagram true_value = fdd::node {
F<1>() == 1,
fdd::leaf{},
fdd::leaf{{oxm::field_set{F<3>() == 3}}}
};
EXPECT_EQ(true_value, r.apply());
}
TEST(FddCompilerTest, RestrictionNodeEqualTypesFalseOrdering1) {
fdd::diagram d = fdd::node {
F<1>() == 2,
fdd::leaf{{oxm::field_set{F<2>() == 2}}},
fdd::leaf{{oxm::field_set{F<3>() == 3}}}
};
auto r = fdd::restriction{ F<1>() == 1, d, false };
fdd::diagram true_value = fdd::node {
F<1>() == 1,
fdd::leaf{},
fdd::node {
F<1>() == 2,
fdd::leaf{{oxm::field_set{F<2>() == 2}}},
fdd::leaf{{oxm::field_set{F<3>() == 3}}}
}
};
EXPECT_EQ(true_value, r.apply());
}
TEST(FddCompilerTest, RestrictionNodeEqualTypesFalseOrdering2) {
fdd::diagram d = fdd::node {
F<1>() == 1,
fdd::leaf{{oxm::field_set{F<2>() == 2}}},
fdd::leaf{{oxm::field_set{F<3>() == 3}}}
};
auto r = fdd::restriction{ F<1>() == 2, d, false };
fdd::diagram true_value = fdd::node {
F<1>() == 1,
fdd::leaf{{oxm::field_set{F<2>() == 2}}},
fdd::node {
F<1>() == 2,
fdd::leaf{},
fdd::leaf{{oxm::field_set{F<3>() == 3}}}
}
};
EXPECT_EQ(true_value, r.apply());
}
TEST(FddCompilerTest, RestrictionNodeDiffTypesFalseOrdering1) {
fdd::diagram d = fdd::node {
F<2>() == 2,
fdd::leaf{{oxm::field_set{F<2>() == 2}}},
fdd::leaf{{oxm::field_set{F<3>() == 3}}}
};
auto r = fdd::restriction{ F<1>() == 1, d, false };
fdd::diagram true_value = fdd::node {
F<1>() == 1,
fdd::leaf{},
fdd::node {
F<2>() == 2,
fdd::leaf{{oxm::field_set{F<2>() == 2}}},
fdd::leaf{{oxm::field_set{F<3>() == 3}}}
}
};
EXPECT_EQ(true_value, r.apply());
}
TEST(FddCompilerTest, RestrictionNodeDiffTypesFalseOrdering2) {
fdd::diagram d = fdd::node {
F<1>() == 1,
fdd::leaf{{oxm::field_set{F<2>() == 2}}},
fdd::leaf{{oxm::field_set{F<3>() == 3}}}
};
auto r = fdd::restriction{ F<2>() == 2, d, false };
fdd::diagram true_value = fdd::node {
F<1>() == 1,
fdd::node {
F<2>() == 2,
fdd::leaf{},
fdd::leaf{{oxm::field_set{F<2>() == 2}}}
},
fdd::node {
F<2>() == 2,
fdd::leaf{},
fdd::leaf{{oxm::field_set{F<3>() == 3}}}
}
};
EXPECT_EQ(true_value, r.apply());
}
TEST(FddCompilerTest, SequentialLeafLeaf) {
fdd::diagram d1 = fdd::leaf {{
oxm::field_set{F<1>() == 1}
}};
fdd::diagram d2 = fdd::leaf {{
oxm::field_set{F<2>() == 2}
}};
fdd::sequential_composition composition;
fdd::diagram result = boost::apply_visitor(composition, d1, d2);
fdd::diagram true_value = fdd::leaf {{
oxm::field_set{
{F<1>() == 1},
{F<2>() == 2}
}
}};
EXPECT_EQ(true_value, result);
}
TEST(FddCompilerTest, SequentialLeafLeafOneField) {
fdd::diagram d1 = fdd::leaf {{
oxm::field_set{F<1>() == 1}
}};
fdd::diagram d2 = fdd::leaf {{
oxm::field_set{F<1>() == 2}
}};
fdd::sequential_composition composition;
fdd::diagram result = boost::apply_visitor(composition, d1, d2);
fdd::diagram true_value = fdd::leaf {{
oxm::field_set{
{F<1>() == 2}
}
}};
EXPECT_EQ(true_value, result);
}
TEST(FddCompilerTest, SequentialLeafLeafMulti) {
fdd::diagram d1 = fdd::leaf {{
oxm::field_set{F<1>() == 1},
oxm::field_set{F<3>() == 3},
oxm::field_set{F<4>() == 4}
}};
fdd::diagram d2 = fdd::leaf {{
oxm::field_set{F<2>() == 2},
oxm::field_set{F<3>() == 300},
}};
fdd::sequential_composition composition;
fdd::diagram result = boost::apply_visitor(composition, d1, d2);
fdd::diagram true_value = fdd::leaf {{
oxm::field_set{
{F<1>() == 1},
{F<2>() == 2}
},
oxm::field_set{
{F<1>() == 1},
{F<3>() == 300}
},
oxm::field_set{
{F<3>() == 3},
{F<2>() == 2}
},
oxm::field_set{
{F<3>() == 300}
},
oxm::field_set{
{F<4>() == 4},
{F<2>() == 2}
},
oxm::field_set{
{F<4>() == 4},
{F<3>() == 300}
}
}};
EXPECT_EQ(true_value, result);
}
TEST(FddCompilerTest, SequentialLeafNodeWriteThisValue) {
fdd::diagram d1 = fdd::leaf{{
oxm::field_set{F<1>() == 1}
}};
fdd::diagram d2 = fdd::node{
F<1>() == 1,
fdd::leaf{{oxm::field_set{F<2>() == 2}}},
fdd::leaf{{oxm::field_set{F<3>() == 3}}}
};
fdd::diagram result = boost::apply_visitor(fdd::sequential_composition{}, d1, d2);
fdd::diagram true_value = fdd::leaf {{
oxm::field_set{
{F<1>() == 1},
{F<2>() == 2}
}
}};
EXPECT_EQ(true_value, result);
}
TEST(FddCompilerTest, SequentialLeafNodeWriteAnotherValue) {
fdd::diagram d1 = fdd::leaf{{
oxm::field_set{F<1>() == 100}
}};
fdd::diagram d2 = fdd::node{
F<1>() == 1,
fdd::leaf{{oxm::field_set{F<2>() == 2}}},
fdd::leaf{{oxm::field_set{F<3>() == 3}}}
};
fdd::diagram result = boost::apply_visitor(fdd::sequential_composition{}, d1, d2);
fdd::diagram true_value = fdd::leaf {{
oxm::field_set{
{F<1>() == 100},
{F<3>() == 3}
}
}};
EXPECT_EQ(true_value, result);
}
TEST(FddCompilerTest, SequentialLeafNodeWriteAnotherType) {
fdd::diagram d1 = fdd::leaf{{
oxm::field_set{F<100>() == 100}
}};
fdd::diagram d2 = fdd::node{
F<1>() == 1,
fdd::leaf{{oxm::field_set{F<2>() == 2}}},
fdd::leaf{{oxm::field_set{F<3>() == 3}}}
};
fdd::diagram result = boost::apply_visitor(fdd::sequential_composition{}, d1, d2);
fdd::diagram true_value = fdd::node{
F<1>() == 1,
fdd::leaf{{
oxm::field_set{ {F<2>() == 2}, {F<100>() == 100} }
}},
fdd::leaf{{
oxm::field_set{ {F<3>() == 3}, {F<100>() == 100} }
}}
};
EXPECT_EQ(true_value, result);
}
TEST(FddCompilerTest, SequentialNodeLeaf) {
fdd::diagram d1 = fdd::node{
F<1>() == 1,
fdd::leaf{{oxm::field_set{F<2>() == 2}}},
fdd::leaf{{oxm::field_set{F<3>() == 3}}}
};
fdd::diagram d2 = fdd::leaf{{
oxm::field_set{F<100>() == 100}
}};
fdd::diagram result = boost::apply_visitor(fdd::sequential_composition{}, d1, d2);
fdd::diagram true_value = fdd::node{
F<1>() == 1,
fdd::leaf{{
oxm::field_set{ {F<2>() == 2}, {F<100>() == 100} }
}},
fdd::leaf{{
oxm::field_set{ {F<3>() == 3}, {F<100>() == 100} }
}}
};
EXPECT_EQ(true_value, result);
}
TEST(FddCompilerTest, CompileSequential) {
policy p = modify(F<1>() == 1) >> modify(F<2>() == 2);
fdd::diagram result = fdd::compile(p);
fdd::diagram true_value = fdd::leaf{{
oxm::field_set{ {F<1>() == 1}, {F<2>() == 2} }
}};
EXPECT_EQ(true_value, result);
}
TEST(FddCompilerTest, CompileParallel) {
policy p = modify(F<1>() == 1) + modify(F<2>() == 2);
fdd::diagram result = fdd::compile(p);
fdd::diagram true_value = fdd::leaf{{
oxm::field_set{F<1>() == 1},
oxm::field_set{F<2>() == 2}
}};
EXPECT_EQ(true_value, result);
}
TEST(FddCompilerTest, CompilePacketFunction) {
policy p = handler([](Packet& pkt){ return stop(); });
PacketFunction pf = boost::get<PacketFunction>(p);
fdd::diagram result = fdd::compile(p);
fdd::diagram true_value = fdd::leaf{{ {oxm::field_set{}, pf} }};
ASSERT_THAT(true_value, result);
}
TEST(FddCompilerTest, SeqAction1If) {
policy p1 = handler([](Packet& pkt){ return stop(); });
policy p2 = handler([](Packet& pkt){ return fwd(1); });
auto pf1 = boost::get<PacketFunction>(p1);
auto pf2 = boost::get<PacketFunction>(p2);
fdd::diagram d1 = fdd::leaf{{ {oxm::field_set{F<1>() == 1}, pf1} }};
fdd::diagram d2 = fdd::leaf{{ {oxm::field_set{F<2>() == 2}, pf2} }};
fdd::diagram result = boost::apply_visitor(fdd::sequential_composition{}, d1, d2);
fdd::action_unit au = fdd::action_unit{oxm::field_set{F<2>() == 2}, pf2};
fdd::diagram true_value = fdd::leaf{{ {oxm::field_set{F<1>() == 1}, pf1, au}}};
ASSERT_EQ(true_value, result);
}
TEST(FddCompilerTest, SeqAction2If) {
policy p2 = handler([](Packet& pkt){ return fwd(1); });
auto pf2 = boost::get<PacketFunction>(p2);
fdd::diagram d1 = fdd::leaf{{ {oxm::field_set{F<1>() == 1}} }};
fdd::diagram d2 = fdd::leaf{{ {oxm::field_set{F<2>() == 2}, pf2} }};
fdd::diagram result = boost::apply_visitor(fdd::sequential_composition{}, d1, d2);
fdd::diagram true_value = fdd::leaf{{ {oxm::field_set{F<1>() == 1, F<2>() == 2}, pf2}}};
ASSERT_EQ(true_value, result);
}
TEST(FddCompilerTest, FlowSettings) {
policy p = idle_timeout(sec(10));
auto settings = boost::get<FlowSettings>(p);
fdd::diagram d = fdd::compile(p);
fdd::diagram true_value = fdd::leaf{{oxm::field_set{}}, settings};
EXPECT_EQ(true_value, d);
}
TEST(FddCompilerTest, FlowSettingsSeq) {
policy p = idle_timeout(sec(10)) >> idle_timeout(sec(5));
fdd::diagram d = fdd::compile(p);
fdd::diagram true_value = fdd::leaf{{oxm::field_set{}}, FlowSettings{.idle_timeout = sec(5)}};
EXPECT_EQ(true_value, d);
}
TEST(FddCompilerTest, FlowSettingsSeq2) {
policy p = idle_timeout(sec(5)) >> idle_timeout(sec(10));
fdd::diagram d = fdd::compile(p);
fdd::diagram true_value = fdd::leaf{{oxm::field_set{}}, FlowSettings{.idle_timeout = sec(5)}};
EXPECT_EQ(true_value, d);
}
TEST(FddCompilerTest, FlowSettingsParallel) {
policy p = idle_timeout(sec(10)) + idle_timeout(sec(5));
fdd::diagram d = fdd::compile(p);
fdd::diagram true_value = fdd::leaf{{oxm::field_set{}}, FlowSettings{.idle_timeout = sec(5)}};
EXPECT_EQ(true_value, d);
}
TEST(FddCompilerTest, FlowSettingsWithTwoActions) {
policy p = (modify(F<1>() == 1) >> idle_timeout(sec(20))) +
(modify(F<2>() == 2) >> idle_timeout(sec(30)));
fdd::diagram d = fdd::compile(p);
fdd::diagram true_value = fdd::leaf {
{
oxm::field_set{F<1>() == 1},
oxm::field_set{F<2>() == 2}
},
FlowSettings{.idle_timeout = sec(20)}
};
EXPECT_EQ(true_value, d);
}
TEST(FddCompilerTest, FilterFlowSettings) {
policy p = filter(F<1>() == 1) >> idle_timeout(sec(20));
fdd::diagram d = fdd::compile(p);
fdd::diagram true_value = fdd::node {
F<1>() == 1,
fdd::leaf{{oxm::field_set{}}, FlowSettings{.idle_timeout=sec(20)}},
fdd::leaf{}
};
EXPECT_EQ(true_value, d);
}
TEST(FddCompilerTest, NegationTest) {
policy p = filter_not(F<1>() == 1);
fdd::diagram d = fdd::compile(p);
fdd::diagram true_value = fdd::node {
F<1>() == 1,
fdd::leaf{},
fdd::leaf{{oxm::field_set{}}}
};
EXPECT_EQ(true_value, d);
}
TEST(FddCompilerTest, NegationTestWithSettings) {
policy p = filter_not(F<1>() == 1) >> idle_timeout(sec(20));
fdd::diagram d = fdd::compile(p);
fdd::diagram true_value = fdd::node {
F<1>() == 1,
fdd::leaf{},
fdd::leaf{{oxm::field_set{}}, FlowSettings{.idle_timeout=sec(20)}}
};
EXPECT_EQ(true_value, d);
}
TEST(DISABLED_FddCompilerTest, NegationX2TestWithSettings) {
// I think this test should failed.
// But I have no idea why NegationTestWithSettings is works
//
policy p = filter_not(F<1>() == 1) >> (filter_not(F<1>() == 1) >> idle_timeout(sec(20)));
fdd::diagram d = fdd::compile(p);
fdd::diagram true_value = fdd::node {
F<1>() == 1,
fdd::leaf{{oxm::field_set{}}, FlowSettings{.idle_timeout=sec(20)}},
fdd::leaf{}
};
EXPECT_EQ(true_value, d);
}
TEST(FddCompilerTest, ComplexNegationTest) {
policy p = (filter(F<1>() == 1) >> modify(F<2>() == 1)) +
(filter_not(F<1>() == 1) >> modify(F<2>() == 2));
fdd::diagram d = fdd::compile(p);
fdd::diagram true_value = fdd::node {
F<1>() == 1,
fdd::leaf{{oxm::field_set{F<2>() == 1}}},
fdd::leaf{{oxm::field_set{F<2>() == 2}}}
};
EXPECT_EQ(true_value, d);
}
TEST(FddTraverseTest, FddTraverse) {
fdd::diagram d = fdd::node{
F<1>() == 1,
fdd::leaf{{ oxm::field_set{F<2>() == 2}}},
fdd::leaf{{ oxm::field_set{F<3>() == 3}}}
};
oxm::field_set fs1{F<1>() == 1};
oxm::field_set fs2{F<1>() == 2};
fdd::Traverser traverser1{fs1}, traverser2{fs2};
fdd::leaf l1 = boost::apply_visitor(traverser1, d);
fdd::leaf l2 = boost::apply_visitor(traverser2, d);
EXPECT_EQ(l1, fdd::leaf{{ oxm::field_set{F<2>() == 2}}});
EXPECT_EQ(l2, fdd::leaf{{ oxm::field_set{F<3>() == 3}}});
}
TEST(FddTraverseTest, FddTraverseWithMaple) {
policy p = handler([](Packet& pkt) {
// Test with nested function
return handler([](Packet& pkt) {
return modify(F<2>() << 2);
});
});
auto pf = boost::get<PacketFunction>(p);
fdd::diagram d = fdd::node {
F<1>() == 1,
fdd::leaf{{ {oxm::field_set{}, pf} }},
fdd::leaf{}
};
oxm::field_set fs{F<1>() == 1};
fdd::Traverser traverser{fs};
fdd::leaf& l = boost::apply_visitor(traverser, d);
EXPECT_EQ(l, fdd::leaf{{ oxm::field_set{F<2>() == 2} }});
}
TEST(FddTraverseTest, FddTraverseWithMapleCallMeTwice) {
int call_count = 0;
policy p = handler([&call_count](Packet& pkt) {
call_count++;
return hard_timeout(duration::zero());
});
oxm::field_set fs{F<1>() == 1};
fdd::diagram d = fdd::compile(p);
for (int i = 0; i < 2; i++) {
fdd::Traverser traverser{fs};
boost::apply_visitor(traverser, d);
}
EXPECT_EQ(call_count, 2);
}
using match = std::vector<oxm::field_set>;
TEST(FddTraverseTest, FddTraverseWithMapleWithBackend) {
MockBackend backend;
policy p = handler([](Packet& pkt) {
pkt.test(F<1>() == 1); // should't be called becouse of cache
pkt.test(F<3>() == 3); // should be called
return modify(F<2>() << 2);
});
auto pf = boost::get<PacketFunction>(p);
fdd::diagram d = fdd::node {
F<1>() == 1,
fdd::leaf{{ {oxm::field_set{}, pf} }},
fdd::leaf{}
};
oxm::field_set fs{F<1>() == 1, F<2>() == 2, F<3>() == 3};
fdd::Traverser traverser{fs, &backend};
EXPECT_CALL(backend, installBarrier(oxm::field_set{F<1>() == 1, F<3>() == 3}, _)).Times(1);
EXPECT_CALL(backend, installBarrier(oxm::field_set{F<1>() == 1}, _)).Times(0);
EXPECT_CALL(
backend,
install(
oxm::field_set{F<1>() == 1, F<3>() == 3},
match{oxm::field_set{F<2>() == 2}},
_, _
)
).Times(1);
fdd::leaf& l = boost::apply_visitor(traverser, d);
EXPECT_EQ(l, fdd::leaf{{ oxm::field_set{F<2>() == 2} }});
}
TEST(FddTraverseTest, FddTraverseWithMapleWithBackendNestedFunction) {
MockBackend backend;
policy p = handler([](Packet& pkt) {
// Test with nested function
pkt.test(F<1>() == 1); // should't be called becouse of cache
pkt.test(F<3>() == 3); // should be called
return handler([](Packet& pkt) {
return modify(F<2>() << 2);
});
});
auto pf = boost::get<PacketFunction>(p);
fdd::diagram d = fdd::node {
F<1>() == 1,
fdd::leaf{{ {oxm::field_set{}, pf} }},
fdd::leaf{}
};
oxm::field_set fs{F<1>() == 1, F<2>() == 2, F<3>() == 3};
fdd::Traverser traverser{fs, &backend};
EXPECT_CALL(backend, installBarrier(oxm::field_set{F<1>() == 1, F<3>() == 3}, _)).Times(Between(1,2));
EXPECT_CALL(backend, installBarrier(oxm::field_set{F<1>() == 1}, _)).Times(0);
EXPECT_CALL(
backend,
install(
oxm::field_set{F<1>() == 1, F<3>() == 3},
match{oxm::field_set{F<2>() == 2}},
_, _
)
).Times(1);
fdd::leaf& l = boost::apply_visitor(traverser, d);
EXPECT_EQ(l, fdd::leaf{{ oxm::field_set{F<2>() == 2} }});
}
| 31.260045 | 132 | 0.529009 | enotnadoske |
a687955d189ad55a59b1bc5a58fa1ecff1fc3a04 | 9,549 | cpp | C++ | src/lib/object_store/test/ObjectStoreTests.cpp | gecheim/SoftHSMv2 | 42fbff713e77afe27d7b466b24cfad9dea69df1f | [
"BSD-2-Clause"
] | 486 | 2015-01-04T05:57:25.000Z | 2022-03-30T02:40:52.000Z | src/lib/object_store/test/ObjectStoreTests.cpp | gecheim/SoftHSMv2 | 42fbff713e77afe27d7b466b24cfad9dea69df1f | [
"BSD-2-Clause"
] | 486 | 2015-01-12T08:51:33.000Z | 2022-03-22T09:06:15.000Z | src/lib/object_store/test/ObjectStoreTests.cpp | gecheim/SoftHSMv2 | 42fbff713e77afe27d7b466b24cfad9dea69df1f | [
"BSD-2-Clause"
] | 274 | 2015-01-21T21:41:45.000Z | 2022-03-30T15:05:54.000Z | /*
* Copyright (c) 2010 SURFnet bv
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
/*****************************************************************************
ObjectStoreTests.cpp
Contains test cases to test the object store implementation
*****************************************************************************/
#include <stdlib.h>
#include <string.h>
#include <cppunit/extensions/HelperMacros.h>
#include "ObjectStoreTests.h"
#include "ObjectStore.h"
#include "File.h"
#include "Directory.h"
#include "OSAttribute.h"
#include "OSAttributes.h"
#include "cryptoki.h"
CPPUNIT_TEST_SUITE_REGISTRATION(ObjectStoreTests);
// FIXME: all pathnames in this file are *NIX/BSD specific
void ObjectStoreTests::setUp()
{
CPPUNIT_ASSERT(!system("mkdir testdir"));
}
void ObjectStoreTests::tearDown()
{
#ifndef _WIN32
CPPUNIT_ASSERT(!system("rm -rf testdir"));
#else
CPPUNIT_ASSERT(!system("rmdir /s /q testdir 2> nul"));
#endif
}
void ObjectStoreTests::testEmptyStore()
{
// Create the store for an empty dir
#ifndef _WIN32
ObjectStore store("./testdir", DEFAULT_UMASK);
#else
ObjectStore store(".\\testdir", DEFAULT_UMASK);
#endif
CPPUNIT_ASSERT(store.getTokenCount() == 0);
}
void ObjectStoreTests::testNewTokens()
{
ByteString label1 = "DEADC0FFEE";
ByteString label2 = "DEADBEEF";
{
// Create an empty store
#ifndef _WIN32
ObjectStore store("./testdir", DEFAULT_UMASK);
#else
ObjectStore store(".\\testdir", DEFAULT_UMASK);
#endif
CPPUNIT_ASSERT(store.getTokenCount() == 0);
// Create a new token
ObjectStoreToken* token1 = store.newToken(label1);
CPPUNIT_ASSERT(token1 != NULL);
CPPUNIT_ASSERT(store.getTokenCount() == 1);
// Create another new token
ObjectStoreToken* token2 = store.newToken(label2);
CPPUNIT_ASSERT(token2 != NULL);
CPPUNIT_ASSERT(store.getTokenCount() == 2);
}
// Now reopen that same store
#ifndef _WIN32
ObjectStore store("./testdir", DEFAULT_UMASK);
#else
ObjectStore store(".\\testdir", DEFAULT_UMASK);
#endif
CPPUNIT_ASSERT(store.getTokenCount() == 2);
// Retrieve both tokens and check that both are present
ObjectStoreToken* token1 = store.getToken(0);
ObjectStoreToken* token2 = store.getToken(1);
ByteString retrieveLabel1, retrieveLabel2;
CPPUNIT_ASSERT(token1->getTokenLabel(retrieveLabel1));
CPPUNIT_ASSERT(token2->getTokenLabel(retrieveLabel2));
CPPUNIT_ASSERT((retrieveLabel1 == label1) || (retrieveLabel2 == label1));
CPPUNIT_ASSERT((retrieveLabel2 == label1) || (retrieveLabel2 == label2));
ByteString retrieveSerial1, retrieveSerial2;
CPPUNIT_ASSERT(token1->getTokenSerial(retrieveSerial1));
CPPUNIT_ASSERT(token2->getTokenSerial(retrieveSerial2));
CPPUNIT_ASSERT(retrieveSerial1 != retrieveSerial2);
}
void ObjectStoreTests::testExistingTokens()
{
// Create some tokens
ByteString label1 = "DEADC0FFEE";
ByteString label2 = "DEADBEEF";
ByteString serial1 = "0011001100110011";
ByteString serial2 = "2233223322332233";
#ifndef _WIN32
ObjectStoreToken* token1 = ObjectStoreToken::createToken("./testdir", "token1", DEFAULT_UMASK, label1, serial1);
ObjectStoreToken* token2 = ObjectStoreToken::createToken("./testdir", "token2", DEFAULT_UMASK, label2, serial2);
#else
ObjectStoreToken* token1 = ObjectStoreToken::createToken(".\\testdir", "token1", DEFAULT_UMASK, label1, serial1);
ObjectStoreToken* token2 = ObjectStoreToken::createToken(".\\testdir", "token2", DEFAULT_UMASK, label2, serial2);
#endif
CPPUNIT_ASSERT((token1 != NULL) && (token2 != NULL));
delete token1;
delete token2;
// Now associate a store with the test directory
#ifndef _WIN32
ObjectStore store("./testdir", DEFAULT_UMASK);
#else
ObjectStore store(".\\testdir", DEFAULT_UMASK);
#endif
CPPUNIT_ASSERT(store.getTokenCount() == 2);
// Retrieve both tokens and check that both are present
ObjectStoreToken* retrieveToken1 = store.getToken(0);
ObjectStoreToken* retrieveToken2 = store.getToken(1);
ByteString retrieveLabel1, retrieveLabel2, retrieveSerial1, retrieveSerial2;
CPPUNIT_ASSERT(retrieveToken1 != NULL);
CPPUNIT_ASSERT(retrieveToken2 != NULL);
CPPUNIT_ASSERT(retrieveToken1->getTokenLabel(retrieveLabel1));
CPPUNIT_ASSERT(retrieveToken2->getTokenLabel(retrieveLabel2));
CPPUNIT_ASSERT(retrieveToken1->getTokenSerial(retrieveSerial1));
CPPUNIT_ASSERT(retrieveToken2->getTokenSerial(retrieveSerial2));
CPPUNIT_ASSERT((retrieveLabel1 == label1) || (retrieveLabel1 == label2));
CPPUNIT_ASSERT((retrieveLabel2 == label1) || (retrieveLabel2 == label2));
CPPUNIT_ASSERT(retrieveLabel1 != retrieveLabel2);
CPPUNIT_ASSERT((retrieveSerial1 == serial1) || (retrieveSerial1 == serial2));
CPPUNIT_ASSERT((retrieveSerial2 == serial1) || (retrieveSerial2 == serial2));
CPPUNIT_ASSERT(retrieveSerial1 != retrieveSerial2);
}
void ObjectStoreTests::testDeleteToken()
{
// Create some tokens
ByteString label1 = "DEADC0FFEE";
ByteString label2 = "DEADBEEF";
ByteString serial1 = "0011001100110011";
ByteString serial2 = "2233223322332233";
#ifndef _WIN32
ObjectStoreToken* token1 = ObjectStoreToken::createToken("./testdir", "token1", DEFAULT_UMASK, label1, serial1);
ObjectStoreToken* token2 = ObjectStoreToken::createToken("./testdir", "token2", DEFAULT_UMASK, label2, serial2);
#else
ObjectStoreToken* token1 = ObjectStoreToken::createToken(".\\testdir", "token1", DEFAULT_UMASK, label1, serial1);
ObjectStoreToken* token2 = ObjectStoreToken::createToken(".\\testdir", "token2", DEFAULT_UMASK, label2, serial2);
#endif
CPPUNIT_ASSERT((token1 != NULL) && (token2 != NULL));
delete token1;
delete token2;
// Now associate a store with the test directory
#ifndef _WIN32
ObjectStore store("./testdir", DEFAULT_UMASK);
#else
ObjectStore store(".\\testdir", DEFAULT_UMASK);
#endif
CPPUNIT_ASSERT(store.getTokenCount() == 2);
// Retrieve both tokens and check that both are present
ObjectStoreToken* retrieveToken1 = store.getToken(0);
ObjectStoreToken* retrieveToken2 = store.getToken(1);
ByteString retrieveLabel1, retrieveLabel2, retrieveSerial1, retrieveSerial2;
CPPUNIT_ASSERT(retrieveToken1 != NULL);
CPPUNIT_ASSERT(retrieveToken2 != NULL);
CPPUNIT_ASSERT(retrieveToken1->getTokenLabel(retrieveLabel1));
CPPUNIT_ASSERT(retrieveToken2->getTokenLabel(retrieveLabel2));
CPPUNIT_ASSERT(retrieveToken1->getTokenSerial(retrieveSerial1));
CPPUNIT_ASSERT(retrieveToken2->getTokenSerial(retrieveSerial2));
CPPUNIT_ASSERT((retrieveLabel1 == label1) || (retrieveLabel1 == label2));
CPPUNIT_ASSERT((retrieveLabel2 == label1) || (retrieveLabel2 == label2));
CPPUNIT_ASSERT(retrieveLabel1 != retrieveLabel2);
CPPUNIT_ASSERT((retrieveSerial1 == serial1) || (retrieveSerial1 == serial2));
CPPUNIT_ASSERT((retrieveSerial2 == serial1) || (retrieveSerial2 == serial2));
CPPUNIT_ASSERT(retrieveSerial1 != retrieveSerial2);
// Now, delete token #1
CPPUNIT_ASSERT(store.destroyToken(retrieveToken1));
CPPUNIT_ASSERT(store.getTokenCount() == 1);
ObjectStoreToken* retrieveToken_ = store.getToken(0);
ByteString retrieveLabel_,retrieveSerial_;
CPPUNIT_ASSERT(retrieveToken_->getTokenLabel(retrieveLabel_));
CPPUNIT_ASSERT(retrieveToken_->getTokenSerial(retrieveSerial_));
CPPUNIT_ASSERT(((retrieveLabel_ == label1) && (retrieveSerial_ == serial1)) ||
((retrieveLabel_ == label2) && (retrieveSerial_ == serial2)));
// Now add a new token
ByteString label3 = "DEADC0FFEEBEEF";
// Create a new token
ObjectStoreToken* tokenNew = store.newToken(label3);
CPPUNIT_ASSERT(tokenNew != NULL);
CPPUNIT_ASSERT(store.getTokenCount() == 2);
// Retrieve both tokens and check that both are present
ObjectStoreToken* retrieveToken1_ = store.getToken(0);
ObjectStoreToken* retrieveToken2_ = store.getToken(1);
CPPUNIT_ASSERT(retrieveToken1_ != NULL);
CPPUNIT_ASSERT(retrieveToken2_ != NULL);
CPPUNIT_ASSERT(retrieveToken1_->getTokenLabel(retrieveLabel1));
CPPUNIT_ASSERT(retrieveToken2_->getTokenLabel(retrieveLabel2));
CPPUNIT_ASSERT(retrieveToken1_->getTokenSerial(retrieveSerial1));
CPPUNIT_ASSERT(retrieveToken2_->getTokenSerial(retrieveSerial2));
CPPUNIT_ASSERT((retrieveLabel1 == label3) || (retrieveLabel2 == label3));
CPPUNIT_ASSERT(((retrieveLabel1 == label1) && (retrieveLabel2 != label2)) ||
((retrieveLabel1 == label2) && (retrieveLabel2 != label1)));
CPPUNIT_ASSERT(retrieveLabel1 != retrieveLabel2);
}
| 34.225806 | 114 | 0.749084 | gecheim |
a68bd737c94e49440b86f9c0a481d1e3b408fdb3 | 574 | hpp | C++ | lab3/11_waterconsumer/waterconsumer.hpp | zaychenko-sergei/oop-ki13 | 97405077de1f66104ec95c1bb2785bc18445532d | [
"MIT"
] | 2 | 2015-10-08T15:07:07.000Z | 2017-09-17T10:08:36.000Z | lab3/11_waterconsumer/waterconsumer.hpp | zaychenko-sergei/oop-ki13 | 97405077de1f66104ec95c1bb2785bc18445532d | [
"MIT"
] | null | null | null | lab3/11_waterconsumer/waterconsumer.hpp | zaychenko-sergei/oop-ki13 | 97405077de1f66104ec95c1bb2785bc18445532d | [
"MIT"
] | null | null | null | // (C) 2013-2014, Sergei Zaychenko, KNURE, Kharkiv, Ukraine
#ifndef _WATERCONSUMER_HPP_
#define _WATERCONSUMER_HPP_
/*****************************************************************************/
class WaterConsumer
{
/*-----------------------------------------------------------------*/
public:
/*-----------------------------------------------------------------*/
// TODO ...
/*-----------------------------------------------------------------*/
};
/*****************************************************************************/
#endif // _WATERCONSUMER_HPP_
| 21.259259 | 79 | 0.252613 | zaychenko-sergei |
a68f8d7ab136d4466140f9c32749a7b5ce5b85d9 | 11,777 | cpp | C++ | willow/src/op/receptive.cpp | gglin001/popart | 3225214343f6d98550b6620e809a3544e8bcbfc6 | [
"MIT"
] | 61 | 2020-07-06T17:11:46.000Z | 2022-03-12T14:42:51.000Z | willow/src/op/receptive.cpp | gglin001/popart | 3225214343f6d98550b6620e809a3544e8bcbfc6 | [
"MIT"
] | 1 | 2021-02-25T01:30:29.000Z | 2021-11-09T11:13:14.000Z | willow/src/op/receptive.cpp | gglin001/popart | 3225214343f6d98550b6620e809a3544e8bcbfc6 | [
"MIT"
] | 6 | 2020-07-15T12:33:13.000Z | 2021-11-07T06:55:00.000Z | // Copyright (c) 2018 Graphcore Ltd. All rights reserved.
#include <iostream>
#include <math.h>
#include <memory>
#include <unordered_map>
#include <popart/error.hpp>
#include <popart/op/receptive.hpp>
#include <popart/opmanager.hpp>
#include <popart/opserialiser.hpp>
#include <popart/tensor.hpp>
#include <popart/util.hpp>
namespace popart {
HasReceptiveFieldOp::HasReceptiveFieldOp(
const OperatorIdentifier &_opid,
const HasReceptiveFieldOp::ReceptiveOpAttributes &attributes,
const Op::Settings &settings_)
: Op(_opid, settings_), basePads(attributes.pads),
baseOutPads(attributes.outPads), baseStrides(attributes.strides),
baseDilations(attributes.dilations),
baseInDilations(attributes.inDilations),
padType(getAutoPad(attributes.auto_pad)), ceilMode(attributes.ceil_mode) {
}
int HasReceptiveFieldOp::getNSpatialDims() const {
auto &inputInfo = inInfo(getInIndex());
return inputInfo.rank() - 2;
}
int64_t HasReceptiveFieldOp::getBatchSize() const {
return inInfo(getInIndex()).dim(0);
}
int64_t HasReceptiveFieldOp::getNInChans() const {
return inInfo(getInIndex()).dim(1);
}
std::vector<int64_t> HasReceptiveFieldOp::getSpatialD() const {
auto nSpatialDims = getNSpatialDims();
auto &inputInfo = inInfo(getInIndex());
std::vector<int64_t> spatialD(nSpatialDims);
for (int i = 0; i < nSpatialDims; ++i) {
spatialD[i] = inputInfo.dim(i + 2);
}
return spatialD;
}
std::vector<int64_t> HasReceptiveFieldOp::getSpatialO() const {
auto nSpatialDims = getNSpatialDims();
auto pads = basePads;
pads.resize(nSpatialDims * 2, 0);
Shape outShape = getOutShape(pads);
std::vector<int64_t> spatialO(nSpatialDims);
for (int i = 0; i < nSpatialDims; ++i) {
spatialO[i] = outShape[i + 2];
}
return spatialO;
}
Shape HasReceptiveFieldOp::getOutPads() const {
auto outPads = baseOutPads;
outPads.resize(getNSpatialDims() * 2, 0);
return outPads;
}
Shape HasReceptiveFieldOp::getPads() const {
auto nSpatialDims = getNSpatialDims();
auto pads = basePads;
pads.resize(nSpatialDims * 2, 0);
if (padType == AutoPad::SAME_LOWER || padType == AutoPad::SAME_UPPER) {
alterPads(pads, getSpatialO(), getSpatialD(), getSpatialK(), getStrides());
}
if (ceilMode) {
// Given the input parameters (pads, strides, dilations), if the calculated
// output shape is non-integer, add upper-padding to each spatial dimension
// such that the newly calculated output shape is the non-integer value
// rounded up to the nearest integer.
for (int i = 0; i < nSpatialDims; i++) {
auto inferredUpperPad = ((getSpatialO()[i] - 1) * getStrides()[i]) +
getSpatialK()[i] - getSpatialD()[i] - pads[i];
pads[i + nSpatialDims] = inferredUpperPad;
}
}
return pads;
}
Shape HasReceptiveFieldOp::getStrides() const {
auto nSpatialDims = getNSpatialDims();
auto strides = baseStrides;
strides.resize(nSpatialDims, 1);
return strides;
}
Shape HasReceptiveFieldOp::getDilations() const {
auto nSpatialDims = getNSpatialDims();
auto dilations = baseDilations;
dilations.resize(nSpatialDims, 1);
return dilations;
}
Shape HasReceptiveFieldOp::getInDilations() const {
int nSpatialDims = getNSpatialDims();
auto inDilations = baseInDilations;
inDilations.resize(nSpatialDims, 1);
return inDilations;
}
void HasReceptiveFieldOp::setup() {
// set-up whatever else the specific HasReceptiveFieldOp requires
// need to be careful with the ordering here.
setup0();
// we assume that the output type is the same as the input type
auto &inputInfo = inInfo(getInIndex());
auto outType = inputInfo.dataType();
outInfo(getOutIndex()).set(outType, getOutShape(getPads()));
}
std::vector<int64_t> HasReceptiveFieldOp::lowerPads() const {
return lowerPads(getPads(), getNSpatialDims(), padType);
}
std::vector<int64_t> HasReceptiveFieldOp::lowerPads(Shape pads_,
int nSpatialDims_,
AutoPad padType_) {
if (padType_ == AutoPad::SAME_UPPER) {
auto v = std::vector<int64_t>(pads_.begin(), pads_.begin() + nSpatialDims_);
for (auto i = 0; i < v.size(); i++) {
v[i] = int64_t(pads_[i] / 2);
}
return v;
} else if (padType_ == AutoPad::SAME_LOWER) {
auto v = std::vector<int64_t>(pads_.begin(), pads_.begin() + nSpatialDims_);
for (auto i = 0; i < v.size(); i++) {
v[i] = int64_t(pads_[i] - (pads_[i] / 2));
}
return v;
} else {
return std::vector<int64_t>(pads_.begin(), pads_.begin() + nSpatialDims_);
}
}
std::vector<int64_t> HasReceptiveFieldOp::upperPads() const {
return upperPads(getPads(), getNSpatialDims(), padType);
}
std::vector<int64_t> HasReceptiveFieldOp::upperPads(Shape pads_,
int nSpatialDims_,
AutoPad padType_) {
// For odd values of total padding, add more padding at the 'right' side
// of the given dimension.
if (padType_ == AutoPad::SAME_UPPER) {
auto v = std::vector<int64_t>(pads_.begin() + nSpatialDims_, pads_.end());
for (auto i = 0; i < v.size(); i++) {
v[i] = int64_t(pads_[i] - (pads_[i] / 2));
}
return v;
} else if (padType_ == AutoPad::SAME_LOWER) {
auto v = std::vector<int64_t>(pads_.begin() + nSpatialDims_, pads_.end());
for (auto i = 0; i < v.size(); i++) {
v[i] = int64_t(pads_[i] / 2);
}
return v;
} else {
return std::vector<int64_t>(pads_.begin() + nSpatialDims_, pads_.end());
}
}
std::vector<int64_t> HasReceptiveFieldOp::lowerOutPads() const {
auto outPads = getOutPads();
return std::vector<int64_t>(outPads.begin(),
outPads.begin() + getNSpatialDims());
}
std::vector<int64_t> HasReceptiveFieldOp::upperOutPads() const {
auto outPads = getOutPads();
return std::vector<int64_t>(outPads.begin() + getNSpatialDims(),
outPads.end());
}
void HasReceptiveFieldOp::alterPads(Shape &pads_,
Shape spatialO_,
Shape spatialD_,
Shape spatialK_,
std::vector<int64_t> strides_) {
for (auto i = 0; i < spatialO_.size(); i++) {
pads_[i] = (spatialO_[i] - 1) * strides_[i] + spatialK_[i] - spatialD_[i];
}
}
Shape HasReceptiveFieldOp::getOutShape(const Shape &pads) const {
Shape outShape(2 + getNSpatialDims(), 0);
outShape[0] = getBatchSize();
outShape[1] = getNOutChans();
Shape spatialOutShape = getSpatialOutShape(getSpatialD(),
getSpatialK(),
pads,
getOutPads(),
getStrides(),
getDilations(),
getInDilations(),
padType,
ceilMode);
for (int spDim = 0; spDim < getNSpatialDims(); ++spDim) {
outShape[spDim + 2] = spatialOutShape[spDim];
}
return outShape;
}
// see https://pytorch.org/docs/stable/nn.html for
// determining spatial output size from conv parameters
// it is essentially the same as for pooling
// (same link, maxpool2d)
Shape HasReceptiveFieldOp::getSpatialOutShape(Shape spatialD_,
Shape spatialK_,
std::vector<int64_t> pads_,
std::vector<int64_t> outPads_,
std::vector<int64_t> strides_,
std::vector<int64_t> dilations_,
std::vector<int64_t> inDilations_,
AutoPad auto_pad_,
bool ceil_mode_) {
Shape spatialOutShape;
int64_t numSpatialDims = spatialD_.size();
auto round = [ceil_mode_](float dim) -> int64_t {
if (ceil_mode_) {
return std::ceil(dim);
} else {
return std::floor(dim);
}
};
for (int spDim = 0; spDim < numSpatialDims; ++spDim) {
int64_t dimSize = inDilations_[spDim] * (spatialD_[spDim] - 1) + 1;
switch (auto_pad_) {
case AutoPad::VALID: {
dimSize = int(std::ceil(float(dimSize - (spatialK_[spDim] - 1)) /
float(strides_[spDim])));
break;
}
case AutoPad::SAME_LOWER:
case AutoPad::SAME_UPPER: {
dimSize = int(std::ceil(float(dimSize) / float(strides_[spDim])));
break;
}
case AutoPad::NOTSET: // default
default: {
dimSize += pads_[spDim] + pads_[numSpatialDims + spDim] - 1;
dimSize -= dilations_[spDim] * (spatialK_[spDim] - 1);
dimSize = int(round(float(dimSize) / float(strides_[spDim])));
dimSize += 1;
}
}
dimSize += outPads_[spDim] + outPads_[numSpatialDims + spDim];
spatialOutShape.push_back(dimSize);
}
return spatialOutShape;
}
std::vector<size_t> HasReceptiveFieldOp::spatialD_szt() const {
return vXtoY<int64_t, size_t>(getSpatialD());
}
std::vector<size_t> HasReceptiveFieldOp::spatialK_szt() const {
return vXtoY<int64_t, size_t>(getSpatialK());
}
std::vector<uint32_t> HasReceptiveFieldOp::lowerPads_u32() const {
return vXtoY<int64_t, uint32_t>(lowerPads());
}
std::vector<uint32_t> HasReceptiveFieldOp::upperPads_u32() const {
return vXtoY<int64_t, uint32_t>(upperPads());
}
std::vector<int> HasReceptiveFieldOp::lowerPads_i32() const {
return vXtoY<int64_t, int>(lowerPads());
}
std::vector<int> HasReceptiveFieldOp::upperPads_i32() const {
return vXtoY<int64_t, int>(upperPads());
}
std::vector<uint32_t> HasReceptiveFieldOp::dilations_u32() const {
return vXtoY<int64_t, uint32_t>(getDilations());
}
std::vector<uint32_t> HasReceptiveFieldOp::strides_u32() const {
return vXtoY<int64_t, uint32_t>(getStrides());
}
void HasReceptiveFieldOp::appendOutlineAttributes(OpSerialiserBase &os) const {
Op::appendOutlineAttributes(os);
os.appendAttribute("basePads", basePads);
os.appendAttribute("baseStrides", baseStrides);
os.appendAttribute("baseDilations", baseDilations);
os.appendAttribute("auto_pad", getAutoPadStr(padType));
}
AutoPad HasReceptiveFieldOp::getAutoPad(const std::string &autoPadStr) {
if (autoPadStr == "SAME_UPPER")
return AutoPad::SAME_UPPER;
if (autoPadStr == "SAME_LOWER")
return AutoPad::SAME_LOWER;
if (autoPadStr == "VALID")
return AutoPad::VALID;
if (autoPadStr == "NOTSET")
return AutoPad::NOTSET;
if (autoPadStr == "")
return AutoPad::NOTSET;
throw error("Invalid auto_pad provied: {}", autoPadStr);
}
std::string HasReceptiveFieldOp::getAutoPadStr(const AutoPad &x) const {
switch (x) {
case AutoPad::VALID:
return "VALID";
case AutoPad::SAME_UPPER:
return "SAME_UPPER";
case AutoPad::SAME_LOWER:
return "SAME_LOWER";
case AutoPad::NOTSET:
return "NOTSET";
default:
throw error("Bad AutoPad '{}'", static_cast<int>(x));
}
}
void HasReceptiveFieldOp::ReceptiveOpAttributes::setFromAttributes(
const Attributes &attributes) {
attributes.setIfPresent(pads, "pads");
attributes.setIfPresent(outPads, "outPads");
attributes.setIfPresent(strides, "strides");
attributes.setIfPresent(dilations, "dilations");
attributes.setIfPresent(inDilations, "inDilations");
attributes.setIfPresent(auto_pad, "auto_pad");
attributes.setIfPresent(ceil_mode, "ceil_mode");
}
} // namespace popart
| 32.354396 | 80 | 0.625202 | gglin001 |
a690b73000ae0b25e4d6a8f139f9512f647d9a36 | 12,398 | cpp | C++ | Source/Data/TLS/Base/NptTlsTrustAnchor_Base_0071.cpp | Dschee/Neptune | 016d132f8e4449e6b0f79fbc5ce25de365eab983 | [
"BSD-3-Clause"
] | 17 | 2015-09-17T06:53:47.000Z | 2021-08-09T03:41:21.000Z | Source/Data/TLS/Base/NptTlsTrustAnchor_Base_0071.cpp | Dschee/Neptune | 016d132f8e4449e6b0f79fbc5ce25de365eab983 | [
"BSD-3-Clause"
] | 17 | 2015-01-05T21:06:22.000Z | 2015-12-07T20:45:44.000Z | Source/Data/TLS/Base/NptTlsTrustAnchor_Base_0071.cpp | Dschee/Neptune | 016d132f8e4449e6b0f79fbc5ce25de365eab983 | [
"BSD-3-Clause"
] | 18 | 2015-12-09T21:27:41.000Z | 2020-11-27T11:38:49.000Z | /*****************************************************************
|
| Neptune - Trust Anchors
|
| This file is automatically generated by a script, do not edit!
|
| Copyright (c) 2002-2010, Axiomatic Systems, LLC.
| 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 Axiomatic Systems 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 AXIOMATIC SYSTEMS ''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 AXIOMATIC SYSTEMS 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.
|
****************************************************************/
/* IPS CLASEA1 root */
const unsigned char NptTlsTrustAnchor_Base_0071_Data[2043] = {
0x30,0x82,0x07,0xf7,0x30,0x82,0x07,0x60
,0xa0,0x03,0x02,0x01,0x02,0x02,0x01,0x00
,0x30,0x0d,0x06,0x09,0x2a,0x86,0x48,0x86
,0xf7,0x0d,0x01,0x01,0x05,0x05,0x00,0x30
,0x82,0x01,0x14,0x31,0x0b,0x30,0x09,0x06
,0x03,0x55,0x04,0x06,0x13,0x02,0x45,0x53
,0x31,0x12,0x30,0x10,0x06,0x03,0x55,0x04
,0x08,0x13,0x09,0x42,0x61,0x72,0x63,0x65
,0x6c,0x6f,0x6e,0x61,0x31,0x12,0x30,0x10
,0x06,0x03,0x55,0x04,0x07,0x13,0x09,0x42
,0x61,0x72,0x63,0x65,0x6c,0x6f,0x6e,0x61
,0x31,0x2e,0x30,0x2c,0x06,0x03,0x55,0x04
,0x0a,0x13,0x25,0x49,0x50,0x53,0x20,0x49
,0x6e,0x74,0x65,0x72,0x6e,0x65,0x74,0x20
,0x70,0x75,0x62,0x6c,0x69,0x73,0x68,0x69
,0x6e,0x67,0x20,0x53,0x65,0x72,0x76,0x69
,0x63,0x65,0x73,0x20,0x73,0x2e,0x6c,0x2e
,0x31,0x2b,0x30,0x29,0x06,0x03,0x55,0x04
,0x0a,0x14,0x22,0x69,0x70,0x73,0x40,0x6d
,0x61,0x69,0x6c,0x2e,0x69,0x70,0x73,0x2e
,0x65,0x73,0x20,0x43,0x2e,0x49,0x2e,0x46
,0x2e,0x20,0x20,0x42,0x2d,0x36,0x30,0x39
,0x32,0x39,0x34,0x35,0x32,0x31,0x2f,0x30
,0x2d,0x06,0x03,0x55,0x04,0x0b,0x13,0x26
,0x49,0x50,0x53,0x20,0x43,0x41,0x20,0x43
,0x4c,0x41,0x53,0x45,0x41,0x31,0x20,0x43
,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61
,0x74,0x69,0x6f,0x6e,0x20,0x41,0x75,0x74
,0x68,0x6f,0x72,0x69,0x74,0x79,0x31,0x2f
,0x30,0x2d,0x06,0x03,0x55,0x04,0x03,0x13
,0x26,0x49,0x50,0x53,0x20,0x43,0x41,0x20
,0x43,0x4c,0x41,0x53,0x45,0x41,0x31,0x20
,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63
,0x61,0x74,0x69,0x6f,0x6e,0x20,0x41,0x75
,0x74,0x68,0x6f,0x72,0x69,0x74,0x79,0x31
,0x1e,0x30,0x1c,0x06,0x09,0x2a,0x86,0x48
,0x86,0xf7,0x0d,0x01,0x09,0x01,0x16,0x0f
,0x69,0x70,0x73,0x40,0x6d,0x61,0x69,0x6c
,0x2e,0x69,0x70,0x73,0x2e,0x65,0x73,0x30
,0x1e,0x17,0x0d,0x30,0x31,0x31,0x32,0x32
,0x39,0x30,0x31,0x30,0x35,0x33,0x32,0x5a
,0x17,0x0d,0x32,0x35,0x31,0x32,0x32,0x37
,0x30,0x31,0x30,0x35,0x33,0x32,0x5a,0x30
,0x82,0x01,0x14,0x31,0x0b,0x30,0x09,0x06
,0x03,0x55,0x04,0x06,0x13,0x02,0x45,0x53
,0x31,0x12,0x30,0x10,0x06,0x03,0x55,0x04
,0x08,0x13,0x09,0x42,0x61,0x72,0x63,0x65
,0x6c,0x6f,0x6e,0x61,0x31,0x12,0x30,0x10
,0x06,0x03,0x55,0x04,0x07,0x13,0x09,0x42
,0x61,0x72,0x63,0x65,0x6c,0x6f,0x6e,0x61
,0x31,0x2e,0x30,0x2c,0x06,0x03,0x55,0x04
,0x0a,0x13,0x25,0x49,0x50,0x53,0x20,0x49
,0x6e,0x74,0x65,0x72,0x6e,0x65,0x74,0x20
,0x70,0x75,0x62,0x6c,0x69,0x73,0x68,0x69
,0x6e,0x67,0x20,0x53,0x65,0x72,0x76,0x69
,0x63,0x65,0x73,0x20,0x73,0x2e,0x6c,0x2e
,0x31,0x2b,0x30,0x29,0x06,0x03,0x55,0x04
,0x0a,0x14,0x22,0x69,0x70,0x73,0x40,0x6d
,0x61,0x69,0x6c,0x2e,0x69,0x70,0x73,0x2e
,0x65,0x73,0x20,0x43,0x2e,0x49,0x2e,0x46
,0x2e,0x20,0x20,0x42,0x2d,0x36,0x30,0x39
,0x32,0x39,0x34,0x35,0x32,0x31,0x2f,0x30
,0x2d,0x06,0x03,0x55,0x04,0x0b,0x13,0x26
,0x49,0x50,0x53,0x20,0x43,0x41,0x20,0x43
,0x4c,0x41,0x53,0x45,0x41,0x31,0x20,0x43
,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61
,0x74,0x69,0x6f,0x6e,0x20,0x41,0x75,0x74
,0x68,0x6f,0x72,0x69,0x74,0x79,0x31,0x2f
,0x30,0x2d,0x06,0x03,0x55,0x04,0x03,0x13
,0x26,0x49,0x50,0x53,0x20,0x43,0x41,0x20
,0x43,0x4c,0x41,0x53,0x45,0x41,0x31,0x20
,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63
,0x61,0x74,0x69,0x6f,0x6e,0x20,0x41,0x75
,0x74,0x68,0x6f,0x72,0x69,0x74,0x79,0x31
,0x1e,0x30,0x1c,0x06,0x09,0x2a,0x86,0x48
,0x86,0xf7,0x0d,0x01,0x09,0x01,0x16,0x0f
,0x69,0x70,0x73,0x40,0x6d,0x61,0x69,0x6c
,0x2e,0x69,0x70,0x73,0x2e,0x65,0x73,0x30
,0x81,0x9f,0x30,0x0d,0x06,0x09,0x2a,0x86
,0x48,0x86,0xf7,0x0d,0x01,0x01,0x01,0x05
,0x00,0x03,0x81,0x8d,0x00,0x30,0x81,0x89
,0x02,0x81,0x81,0x00,0xbb,0x30,0xd7,0xdc
,0xd0,0x54,0xbd,0x35,0x4e,0x9f,0xc5,0x4c
,0x82,0xea,0xd1,0x50,0x3c,0x47,0x98,0xfc
,0x9b,0x69,0x9d,0x77,0xcd,0x6e,0xe0,0x3f
,0xee,0xeb,0x32,0x5f,0x5f,0x9f,0xd2,0xd0
,0x79,0xe5,0x95,0x73,0x44,0x21,0x32,0xe0
,0x0a,0xdb,0x9d,0xd7,0xce,0x8d,0xab,0x52
,0x8b,0x2b,0x78,0xe0,0x9b,0x5b,0x7d,0xf4
,0xfd,0x6d,0x09,0xe5,0xae,0xe1,0x6c,0x1d
,0x07,0x23,0xa0,0x17,0xd1,0xf9,0x7d,0xa8
,0x46,0x46,0x91,0x22,0xa8,0xb2,0x69,0xc6
,0xad,0xf7,0xf5,0xf5,0x94,0xa1,0x30,0x94
,0xbd,0x00,0xcc,0x44,0x7f,0xee,0xc4,0x9e
,0xc9,0xc1,0xe6,0x8f,0x0a,0x36,0xc1,0xfd
,0x24,0x3d,0x01,0xa0,0xf5,0x7b,0xe2,0x7c
,0x78,0x66,0x43,0x8b,0x4f,0x59,0xf2,0x9b
,0xd9,0xfa,0x49,0xb3,0x02,0x03,0x01,0x00
,0x01,0xa3,0x82,0x04,0x53,0x30,0x82,0x04
,0x4f,0x30,0x1d,0x06,0x03,0x55,0x1d,0x0e
,0x04,0x16,0x04,0x14,0x67,0x26,0x96,0xe7
,0xa1,0xbf,0xd8,0xb5,0x03,0x9d,0xfe,0x3b
,0xdc,0xfe,0xf2,0x8a,0xe6,0x15,0xdd,0x30
,0x30,0x82,0x01,0x46,0x06,0x03,0x55,0x1d
,0x23,0x04,0x82,0x01,0x3d,0x30,0x82,0x01
,0x39,0x80,0x14,0x67,0x26,0x96,0xe7,0xa1
,0xbf,0xd8,0xb5,0x03,0x9d,0xfe,0x3b,0xdc
,0xfe,0xf2,0x8a,0xe6,0x15,0xdd,0x30,0xa1
,0x82,0x01,0x1c,0xa4,0x82,0x01,0x18,0x30
,0x82,0x01,0x14,0x31,0x0b,0x30,0x09,0x06
,0x03,0x55,0x04,0x06,0x13,0x02,0x45,0x53
,0x31,0x12,0x30,0x10,0x06,0x03,0x55,0x04
,0x08,0x13,0x09,0x42,0x61,0x72,0x63,0x65
,0x6c,0x6f,0x6e,0x61,0x31,0x12,0x30,0x10
,0x06,0x03,0x55,0x04,0x07,0x13,0x09,0x42
,0x61,0x72,0x63,0x65,0x6c,0x6f,0x6e,0x61
,0x31,0x2e,0x30,0x2c,0x06,0x03,0x55,0x04
,0x0a,0x13,0x25,0x49,0x50,0x53,0x20,0x49
,0x6e,0x74,0x65,0x72,0x6e,0x65,0x74,0x20
,0x70,0x75,0x62,0x6c,0x69,0x73,0x68,0x69
,0x6e,0x67,0x20,0x53,0x65,0x72,0x76,0x69
,0x63,0x65,0x73,0x20,0x73,0x2e,0x6c,0x2e
,0x31,0x2b,0x30,0x29,0x06,0x03,0x55,0x04
,0x0a,0x14,0x22,0x69,0x70,0x73,0x40,0x6d
,0x61,0x69,0x6c,0x2e,0x69,0x70,0x73,0x2e
,0x65,0x73,0x20,0x43,0x2e,0x49,0x2e,0x46
,0x2e,0x20,0x20,0x42,0x2d,0x36,0x30,0x39
,0x32,0x39,0x34,0x35,0x32,0x31,0x2f,0x30
,0x2d,0x06,0x03,0x55,0x04,0x0b,0x13,0x26
,0x49,0x50,0x53,0x20,0x43,0x41,0x20,0x43
,0x4c,0x41,0x53,0x45,0x41,0x31,0x20,0x43
,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61
,0x74,0x69,0x6f,0x6e,0x20,0x41,0x75,0x74
,0x68,0x6f,0x72,0x69,0x74,0x79,0x31,0x2f
,0x30,0x2d,0x06,0x03,0x55,0x04,0x03,0x13
,0x26,0x49,0x50,0x53,0x20,0x43,0x41,0x20
,0x43,0x4c,0x41,0x53,0x45,0x41,0x31,0x20
,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63
,0x61,0x74,0x69,0x6f,0x6e,0x20,0x41,0x75
,0x74,0x68,0x6f,0x72,0x69,0x74,0x79,0x31
,0x1e,0x30,0x1c,0x06,0x09,0x2a,0x86,0x48
,0x86,0xf7,0x0d,0x01,0x09,0x01,0x16,0x0f
,0x69,0x70,0x73,0x40,0x6d,0x61,0x69,0x6c
,0x2e,0x69,0x70,0x73,0x2e,0x65,0x73,0x82
,0x01,0x00,0x30,0x0c,0x06,0x03,0x55,0x1d
,0x13,0x04,0x05,0x30,0x03,0x01,0x01,0xff
,0x30,0x0c,0x06,0x03,0x55,0x1d,0x0f,0x04
,0x05,0x03,0x03,0x07,0xff,0x80,0x30,0x6b
,0x06,0x03,0x55,0x1d,0x25,0x04,0x64,0x30
,0x62,0x06,0x08,0x2b,0x06,0x01,0x05,0x05
,0x07,0x03,0x01,0x06,0x08,0x2b,0x06,0x01
,0x05,0x05,0x07,0x03,0x02,0x06,0x08,0x2b
,0x06,0x01,0x05,0x05,0x07,0x03,0x03,0x06
,0x08,0x2b,0x06,0x01,0x05,0x05,0x07,0x03
,0x04,0x06,0x08,0x2b,0x06,0x01,0x05,0x05
,0x07,0x03,0x08,0x06,0x0a,0x2b,0x06,0x01
,0x04,0x01,0x82,0x37,0x02,0x01,0x15,0x06
,0x0a,0x2b,0x06,0x01,0x04,0x01,0x82,0x37
,0x02,0x01,0x16,0x06,0x0a,0x2b,0x06,0x01
,0x04,0x01,0x82,0x37,0x0a,0x03,0x01,0x06
,0x0a,0x2b,0x06,0x01,0x04,0x01,0x82,0x37
,0x0a,0x03,0x04,0x30,0x11,0x06,0x09,0x60
,0x86,0x48,0x01,0x86,0xf8,0x42,0x01,0x01
,0x04,0x04,0x03,0x02,0x00,0x07,0x30,0x1a
,0x06,0x03,0x55,0x1d,0x11,0x04,0x13,0x30
,0x11,0x81,0x0f,0x69,0x70,0x73,0x40,0x6d
,0x61,0x69,0x6c,0x2e,0x69,0x70,0x73,0x2e
,0x65,0x73,0x30,0x1a,0x06,0x03,0x55,0x1d
,0x12,0x04,0x13,0x30,0x11,0x81,0x0f,0x69
,0x70,0x73,0x40,0x6d,0x61,0x69,0x6c,0x2e
,0x69,0x70,0x73,0x2e,0x65,0x73,0x30,0x42
,0x06,0x09,0x60,0x86,0x48,0x01,0x86,0xf8
,0x42,0x01,0x0d,0x04,0x35,0x16,0x33,0x43
,0x4c,0x41,0x53,0x45,0x41,0x31,0x20,0x43
,0x41,0x20,0x43,0x65,0x72,0x74,0x69,0x66
,0x69,0x63,0x61,0x74,0x65,0x20,0x69,0x73
,0x73,0x75,0x65,0x64,0x20,0x62,0x79,0x20
,0x68,0x74,0x74,0x70,0x3a,0x2f,0x2f,0x77
,0x77,0x77,0x2e,0x69,0x70,0x73,0x2e,0x65
,0x73,0x2f,0x30,0x29,0x06,0x09,0x60,0x86
,0x48,0x01,0x86,0xf8,0x42,0x01,0x02,0x04
,0x1c,0x16,0x1a,0x68,0x74,0x74,0x70,0x3a
,0x2f,0x2f,0x77,0x77,0x77,0x2e,0x69,0x70
,0x73,0x2e,0x65,0x73,0x2f,0x69,0x70,0x73
,0x32,0x30,0x30,0x32,0x2f,0x30,0x3b,0x06
,0x09,0x60,0x86,0x48,0x01,0x86,0xf8,0x42
,0x01,0x04,0x04,0x2e,0x16,0x2c,0x68,0x74
,0x74,0x70,0x3a,0x2f,0x2f,0x77,0x77,0x77
,0x2e,0x69,0x70,0x73,0x2e,0x65,0x73,0x2f
,0x69,0x70,0x73,0x32,0x30,0x30,0x32,0x2f
,0x69,0x70,0x73,0x32,0x30,0x30,0x32,0x43
,0x4c,0x41,0x53,0x45,0x41,0x31,0x2e,0x63
,0x72,0x6c,0x30,0x40,0x06,0x09,0x60,0x86
,0x48,0x01,0x86,0xf8,0x42,0x01,0x03,0x04
,0x33,0x16,0x31,0x68,0x74,0x74,0x70,0x3a
,0x2f,0x2f,0x77,0x77,0x77,0x2e,0x69,0x70
,0x73,0x2e,0x65,0x73,0x2f,0x69,0x70,0x73
,0x32,0x30,0x30,0x32,0x2f,0x72,0x65,0x76
,0x6f,0x63,0x61,0x74,0x69,0x6f,0x6e,0x43
,0x4c,0x41,0x53,0x45,0x41,0x31,0x2e,0x68
,0x74,0x6d,0x6c,0x3f,0x30,0x3d,0x06,0x09
,0x60,0x86,0x48,0x01,0x86,0xf8,0x42,0x01
,0x07,0x04,0x30,0x16,0x2e,0x68,0x74,0x74
,0x70,0x3a,0x2f,0x2f,0x77,0x77,0x77,0x2e
,0x69,0x70,0x73,0x2e,0x65,0x73,0x2f,0x69
,0x70,0x73,0x32,0x30,0x30,0x32,0x2f,0x72
,0x65,0x6e,0x65,0x77,0x61,0x6c,0x43,0x4c
,0x41,0x53,0x45,0x41,0x31,0x2e,0x68,0x74
,0x6d,0x6c,0x3f,0x30,0x3b,0x06,0x09,0x60
,0x86,0x48,0x01,0x86,0xf8,0x42,0x01,0x08
,0x04,0x2e,0x16,0x2c,0x68,0x74,0x74,0x70
,0x3a,0x2f,0x2f,0x77,0x77,0x77,0x2e,0x69
,0x70,0x73,0x2e,0x65,0x73,0x2f,0x69,0x70
,0x73,0x32,0x30,0x30,0x32,0x2f,0x70,0x6f
,0x6c,0x69,0x63,0x79,0x43,0x4c,0x41,0x53
,0x45,0x41,0x31,0x2e,0x68,0x74,0x6d,0x6c
,0x30,0x75,0x06,0x03,0x55,0x1d,0x1f,0x04
,0x6e,0x30,0x6c,0x30,0x32,0xa0,0x30,0xa0
,0x2e,0x86,0x2c,0x68,0x74,0x74,0x70,0x3a
,0x2f,0x2f,0x77,0x77,0x77,0x2e,0x69,0x70
,0x73,0x2e,0x65,0x73,0x2f,0x69,0x70,0x73
,0x32,0x30,0x30,0x32,0x2f,0x69,0x70,0x73
,0x32,0x30,0x30,0x32,0x43,0x4c,0x41,0x53
,0x45,0x41,0x31,0x2e,0x63,0x72,0x6c,0x30
,0x36,0xa0,0x34,0xa0,0x32,0x86,0x30,0x68
,0x74,0x74,0x70,0x3a,0x2f,0x2f,0x77,0x77
,0x77,0x62,0x61,0x63,0x6b,0x2e,0x69,0x70
,0x73,0x2e,0x65,0x73,0x2f,0x69,0x70,0x73
,0x32,0x30,0x30,0x32,0x2f,0x69,0x70,0x73
,0x32,0x30,0x30,0x32,0x43,0x4c,0x41,0x53
,0x45,0x41,0x31,0x2e,0x63,0x72,0x6c,0x30
,0x2f,0x06,0x08,0x2b,0x06,0x01,0x05,0x05
,0x07,0x01,0x01,0x04,0x23,0x30,0x21,0x30
,0x1f,0x06,0x08,0x2b,0x06,0x01,0x05,0x05
,0x07,0x30,0x01,0x86,0x13,0x68,0x74,0x74
,0x70,0x3a,0x2f,0x2f,0x6f,0x63,0x73,0x70
,0x2e,0x69,0x70,0x73,0x2e,0x65,0x73,0x2f
,0x30,0x0d,0x06,0x09,0x2a,0x86,0x48,0x86
,0xf7,0x0d,0x01,0x01,0x05,0x05,0x00,0x03
,0x81,0x81,0x00,0x7e,0xba,0x8a,0xac,0x80
,0x00,0x84,0x15,0x0a,0xd5,0x98,0x51,0x0c
,0x64,0xc5,0x9c,0x02,0x58,0x83,0x66,0xca
,0xad,0x1e,0x07,0xcd,0x7e,0x6a,0xda,0x80
,0x07,0xdf,0x03,0x34,0x4a,0x1c,0x93,0xc4
,0x4b,0x58,0x20,0x35,0x36,0x71,0xed,0xa2
,0x0a,0x35,0x12,0xa5,0xa6,0x65,0xa7,0x85
,0x69,0x0a,0x0e,0xe3,0x61,0xee,0xea,0xbe
,0x28,0x93,0x33,0xd5,0xec,0xe8,0xbe,0xc4
,0xdb,0x5f,0x7f,0xa8,0xf9,0x63,0x31,0xc8
,0x6b,0x96,0xe2,0x29,0xc2,0x5b,0xa0,0xe7
,0x97,0x36,0x9d,0x77,0x5e,0x31,0x6b,0xfe
,0xd3,0xa7,0xdb,0x2a,0xdb,0xdb,0x96,0x8b
,0x1f,0x66,0xde,0xb6,0x03,0xc0,0x2b,0xb3
,0x78,0xd6,0x55,0x07,0xe5,0x8f,0x39,0x50
,0xde,0x07,0x23,0x72,0xe6,0xbd,0x20,0x14
,0x4b,0xb4,0x86};
const unsigned int NptTlsTrustAnchor_Base_0071_Size = 2043;
| 42.313993 | 79 | 0.769882 | Dschee |