text string | size int64 | token_count int64 |
|---|---|---|
#pragma once
#include "class.hpp"
namespace Testing
{
class ClassGenerator
{
public:
explicit ClassGenerator(std::wstring class_name = L"A", std::wstring header_file_name = L"a.hpp");
~ClassGenerator() = default;
operator Cda::ClassFiles() const;
ClassGenerator& addLine(std::wstring line);
private:
const std::wstring m_class_name;
const std::wstring m_header_file_name;
std::wstring m_content;
};
std::vector<Cda::File::Line> linesFromString(const std::wstring& str);
} // namespace Testing
| 530 | 178 |
#include "stdafx.h"
#include "SETTINGS_virtualBG_workflow.h"
CSDKVirtualBGSettingsWorkFlow::CSDKVirtualBGSettingsWorkFlow()
{
m_pSettingService = NULL;
m_pVBGSettingContext = NULL;
m_pVideoSettingsContext = NULL;
m_pTestVideoDeviceHelper = NULL;
Init();
}
CSDKVirtualBGSettingsWorkFlow::~CSDKVirtualBGSettingsWorkFlow()
{
m_pSettingService = NULL;
m_pVBGSettingContext = NULL;
m_pTestVideoDeviceHelper = NULL;
m_pVideoSettingsContext = NULL;
}
ZOOM_SDK_NAMESPACE::SDKError CSDKVirtualBGSettingsWorkFlow::Init()
{
if(NULL == m_pSettingService)
{
m_pSettingService = SDKInterfaceWrap::GetInst().GetSettingService();
}
if(m_pSettingService)
{
m_pVBGSettingContext = m_pSettingService->GetVirtualBGSettings();
m_pVideoSettingsContext = m_pSettingService->GetVideoSettings();
}
if(NULL == m_pVBGSettingContext)
{
return ZOOM_SDK_NAMESPACE::SDKERR_UNINITIALIZE;
}
if(m_pVideoSettingsContext)
{
m_pTestVideoDeviceHelper = m_pVideoSettingsContext->GetTestVideoDeviceHelper();
if(m_pTestVideoDeviceHelper)
{
ZOOM_SDK_NAMESPACE::SDKError err = ZOOM_SDK_NAMESPACE::SDKERR_SUCCESS;
err = m_pTestVideoDeviceHelper->SetEvent(this);
return err;
}
}
return ZOOM_SDK_NAMESPACE::SDKERR_SUCCESS;
}
bool CSDKVirtualBGSettingsWorkFlow::IsSupportVirtualBG()
{
if(m_pVBGSettingContext)
return m_pVBGSettingContext->IsSupportVirtualBG();
return false;
}
bool CSDKVirtualBGSettingsWorkFlow::IsSupportSmartVirtualBG()
{
if(m_pVBGSettingContext)
return m_pVBGSettingContext->IsSupportSmartVirtualBG();
return false;
}
bool CSDKVirtualBGSettingsWorkFlow::IsUsingGreenScreenOn()
{
if(m_pVBGSettingContext)
return m_pVBGSettingContext->IsUsingGreenScreenOn ();
return false;
}
DWORD CSDKVirtualBGSettingsWorkFlow::GetBGReplaceColor()
{
if(m_pVBGSettingContext)
return m_pVBGSettingContext->GetBGReplaceColor();
return 0;
}
ZOOM_SDK_NAMESPACE::SDKError CSDKVirtualBGSettingsWorkFlow::SetUsingGreenScreen(bool bUse)
{
if(m_pVBGSettingContext)
{
ZOOM_SDK_NAMESPACE::SDKError err = ZOOM_SDK_NAMESPACE::SDKERR_SUCCESS;
err = m_pVBGSettingContext->SetUsingGreenScreen(bUse);
return err;
}
return ZOOM_SDK_NAMESPACE::SDKERR_UNINITIALIZE;
}
ZOOM_SDK_NAMESPACE::SDKError CSDKVirtualBGSettingsWorkFlow::AddBGImage(const wchar_t* file_path)
{
if(m_pVBGSettingContext)
{
ZOOM_SDK_NAMESPACE::SDKError err = ZOOM_SDK_NAMESPACE::SDKERR_SUCCESS;
err = m_pVBGSettingContext->AddBGImage(file_path);
return err;
}
return ZOOM_SDK_NAMESPACE::SDKERR_UNINITIALIZE;
}
ZOOM_SDK_NAMESPACE::SDKError CSDKVirtualBGSettingsWorkFlow::RemoveBGImage(ZOOM_SDK_NAMESPACE::IVirtualBGImageInfo* pRemoveImage)
{
if(m_pVBGSettingContext)
{
ZOOM_SDK_NAMESPACE::SDKError err = ZOOM_SDK_NAMESPACE::SDKERR_SUCCESS;
err = m_pVBGSettingContext->RemoveBGImage(pRemoveImage);
return err;
}
return ZOOM_SDK_NAMESPACE::SDKERR_UNINITIALIZE;
}
ZOOM_SDK_NAMESPACE::IList<ZOOM_SDK_NAMESPACE::IVirtualBGImageInfo* >* CSDKVirtualBGSettingsWorkFlow::GetBGImageList()
{
if(m_pVBGSettingContext)
{
return m_pVBGSettingContext->GetBGImageList();
}
return NULL;
}
ZOOM_SDK_NAMESPACE::SDKError CSDKVirtualBGSettingsWorkFlow::UseBGImage(ZOOM_SDK_NAMESPACE::IVirtualBGImageInfo* pImage)
{
if(m_pVBGSettingContext)
{
ZOOM_SDK_NAMESPACE::SDKError err = ZOOM_SDK_NAMESPACE::SDKERR_SUCCESS;
err = m_pVBGSettingContext->UseBGImage(pImage);
return err;
}
return ZOOM_SDK_NAMESPACE::SDKERR_UNINITIALIZE;
}
ZOOM_SDK_NAMESPACE::SDKError CSDKVirtualBGSettingsWorkFlow::BeginSelectReplaceVBColor()
{
if(m_pVBGSettingContext)
{
ZOOM_SDK_NAMESPACE::SDKError err = ZOOM_SDK_NAMESPACE::SDKERR_SUCCESS;
err = m_pVBGSettingContext->BeginSelectReplaceVBColor();
return err;
}
return ZOOM_SDK_NAMESPACE::SDKERR_UNINITIALIZE;
}
ZOOM_SDK_NAMESPACE::SDKError CSDKVirtualBGSettingsWorkFlow::SetVideoPreviewParentWnd(HWND hParentWnd, RECT rc /* = _SDK_TEST_VIDEO_INIT_RECT */)
{
if(m_pTestVideoDeviceHelper)
{
ZOOM_SDK_NAMESPACE::SDKError err = ZOOM_SDK_NAMESPACE::SDKERR_SUCCESS;
err = m_pTestVideoDeviceHelper->SetVideoPreviewParentWnd(hParentWnd,rc);
return err;
}
return ZOOM_SDK_NAMESPACE::SDKERR_UNINITIALIZE;
}
ZOOM_SDK_NAMESPACE::SDKError CSDKVirtualBGSettingsWorkFlow::TestVideoStartPreview(const wchar_t* deviceID /* = NULL */)
{
if(m_pTestVideoDeviceHelper)
{
ZOOM_SDK_NAMESPACE::SDKError err = ZOOM_SDK_NAMESPACE::SDKERR_SUCCESS;
err = m_pTestVideoDeviceHelper->TestVideoStartPreview(deviceID);
return err;
}
return ZOOM_SDK_NAMESPACE::SDKERR_UNINITIALIZE;
}
ZOOM_SDK_NAMESPACE::SDKError CSDKVirtualBGSettingsWorkFlow::TestVideoStopPreview()
{
if(m_pTestVideoDeviceHelper)
{
ZOOM_SDK_NAMESPACE::SDKError err = ZOOM_SDK_NAMESPACE::SDKERR_SUCCESS;
err = m_pTestVideoDeviceHelper->TestVideoStopPreview();
return err;
}
return ZOOM_SDK_NAMESPACE::SDKERR_UNINITIALIZE;
}
| 4,825 | 1,972 |
/*------------------------------------------------------------------------
* Vulkan Conformance Tests
* ------------------------
*
* Copyright (c) 2021 The Khronos Group Inc.
* Copyright (c) 2021 Google LLC.
*
* 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.
*
*//*!
* \file
* \brief Shared memory layout test case.
*//*--------------------------------------------------------------------*/
#include <vkDefs.hpp>
#include "deRandom.hpp"
#include "gluContextInfo.hpp"
#include "gluVarTypeUtil.hpp"
#include "tcuTestLog.hpp"
#include "vkBuilderUtil.hpp"
#include "vkMemUtil.hpp"
#include "vkQueryUtil.hpp"
#include "vkRefUtil.hpp"
#include "vkRef.hpp"
#include "vkTypeUtil.hpp"
#include "vkCmdUtil.hpp"
#include "vktMemoryModelSharedLayoutCase.hpp"
#include "util/vktTypeComparisonUtil.hpp"
namespace vkt
{
namespace MemoryModel
{
using tcu::TestLog;
using std::string;
using std::vector;
using glu::VarType;
using glu::StructMember;
namespace
{
void computeReferenceLayout (const VarType& type, vector<SharedStructVarEntry>& entries)
{
if (type.isBasicType())
entries.push_back(SharedStructVarEntry(type.getBasicType(), 1));
else if (type.isArrayType())
{
const VarType &elemType = type.getElementType();
// Array of scalars, vectors or matrices.
if (elemType.isBasicType())
entries.push_back(SharedStructVarEntry(elemType.getBasicType(), type.getArraySize()));
else
{
DE_ASSERT(elemType.isStructType() || elemType.isArrayType());
for (int i = 0; i < type.getArraySize(); i++)
computeReferenceLayout(type.getElementType(), entries);
}
}
else
{
DE_ASSERT(type.isStructType());
for (const auto& member : *type.getStructPtr())
computeReferenceLayout(member.getType(), entries);
}
}
void computeReferenceLayout (SharedStructVar& var)
{
// Top-level arrays need special care.
if (var.type.isArrayType())
computeReferenceLayout(var.type.getElementType(), var.entries);
else
computeReferenceLayout(var.type, var.entries);
}
void generateValue (const SharedStructVarEntry& entry, de::Random& rnd, vector<string>& values)
{
const glu::DataType scalarType = glu::getDataTypeScalarType(entry.type);
const int scalarSize = glu::getDataTypeScalarSize(entry.type);
const int arraySize = entry.arraySize;
const bool isMatrix = glu::isDataTypeMatrix(entry.type);
const int numVecs = isMatrix ? glu::getDataTypeMatrixNumColumns(entry.type) : 1;
const int vecSize = scalarSize / numVecs;
DE_ASSERT(scalarSize % numVecs == 0);
DE_ASSERT(arraySize >= 0);
string generatedValue;
for (int elemNdx = 0; elemNdx < arraySize; elemNdx++)
{
for (int vecNdx = 0; vecNdx < numVecs; vecNdx++)
{
for (int compNdx = 0; compNdx < vecSize; compNdx++)
{
switch (scalarType)
{
case glu::TYPE_INT:
case glu::TYPE_INT8:
case glu::TYPE_INT16:
// Fall through. This fits into all the types above.
generatedValue = de::toString(rnd.getInt(-9, 9));
break;
case glu::TYPE_UINT:
case glu::TYPE_UINT8:
case glu::TYPE_UINT16:
// Fall through. This fits into all the types above.
generatedValue = de::toString(rnd.getInt(0, 9)).append("u");
break;
case glu::TYPE_FLOAT:
case glu::TYPE_FLOAT16:
// Fall through. This fits into all the types above.
generatedValue = de::floatToString(static_cast<float>(rnd.getInt(-9, 9)), 1);
break;
case glu::TYPE_BOOL:
generatedValue = rnd.getBool() ? "true" : "false";
break;
default:
DE_ASSERT(false);
}
values.push_back(generatedValue);
}
}
}
}
string getStructMemberName (const SharedStructVar& var, const glu::TypeComponentVector& accessPath)
{
std::ostringstream name;
name << "." << var.name;
for (auto pathComp = accessPath.begin(); pathComp != accessPath.end(); pathComp++)
{
if (pathComp->type == glu::VarTypeComponent::STRUCT_MEMBER)
{
const VarType curType = glu::getVarType(var.type, accessPath.begin(), pathComp);
const glu::StructType *structPtr = curType.getStructPtr();
name << "." << structPtr->getMember(pathComp->index).getName();
}
else if (pathComp->type == glu::VarTypeComponent::ARRAY_ELEMENT)
name << "[" << pathComp->index << "]";
else
DE_ASSERT(false);
}
return name.str();
}
} // anonymous
NamedStructSP ShaderInterface::allocStruct (const string& name)
{
m_structs.emplace_back(new glu::StructType(name.c_str()));
return m_structs.back();
}
SharedStruct& ShaderInterface::allocSharedObject (const string& name, const string& instanceName)
{
m_sharedMemoryObjects.emplace_back(name, instanceName);
return m_sharedMemoryObjects.back();
}
void generateCompareFuncs (std::ostream &str, const ShaderInterface &interface)
{
std::set<glu::DataType> types;
std::set<glu::DataType> compareFuncs;
// Collect unique basic types.
for (const auto& sharedObj : interface.getSharedObjects())
for (const auto& var : sharedObj)
vkt::typecomputil::collectUniqueBasicTypes(types, var.type);
// Set of compare functions required.
for (const auto& type : types)
vkt::typecomputil::getCompareDependencies(compareFuncs, type);
for (int type = 0; type < glu::TYPE_LAST; ++type)
if (compareFuncs.find(glu::DataType(type)) != compareFuncs.end())
str << vkt::typecomputil::getCompareFuncForType(glu::DataType(type));
}
void generateSharedMemoryWrites (std::ostream &src, const SharedStruct &object,
const SharedStructVar &var, const glu::SubTypeAccess &accessPath,
vector<string>::const_iterator &valueIter, bool compare)
{
const VarType curType = accessPath.getType();
if (curType.isArrayType())
{
const int arraySize = curType.getArraySize();
for (int i = 0; i < arraySize; i++)
generateSharedMemoryWrites(src, object, var, accessPath.element(i), valueIter, compare);
}
else if (curType.isStructType())
{
const int numMembers = curType.getStructPtr()->getNumMembers();
for (int i = 0; i < numMembers; i++)
generateSharedMemoryWrites(src, object, var, accessPath.member(i), valueIter, compare);
}
else
{
DE_ASSERT(curType.isBasicType());
const glu::DataType basicType = curType.getBasicType();
const string typeName = glu::getDataTypeName(basicType);
const string sharedObjectVarName = object.getInstanceName();
const string structMember = getStructMemberName(var, accessPath.getPath());
const glu::DataType promoteType = vkt::typecomputil::getPromoteType(basicType);
int numElements = glu::getDataTypeScalarSize(basicType);
if (glu::isDataTypeMatrix(basicType))
numElements = glu::getDataTypeMatrixNumColumns(basicType) * glu::getDataTypeMatrixNumRows(basicType);
if (compare)
{
src << "\t" << "allOk" << " = " << "allOk" << " && compare_" << typeName << "(";
// Comparison functions use 32-bit values. Convert 8/16-bit scalar and vector types if necessary.
// E.g. uint8_t becomes int.
if (basicType != promoteType || numElements > 1)
src << glu::getDataTypeName(promoteType) << "(";
}
else
{
src << "\t" << sharedObjectVarName << structMember << " = " << "";
// If multiple literals or a 8/16-bit literal is assigned, the variable must be
// initialized with the constructor.
if (basicType != promoteType || numElements > 1)
src << glu::getDataTypeName(basicType) << "(";
}
for (int i = 0; i < numElements; i++)
src << (i != 0 ? ", " : "") << *valueIter++;
if (basicType != promoteType)
src << ")";
else if (numElements > 1)
src << ")";
// Write the variable in the shared memory as the next argument for the comparison function.
// Initialize it as a new 32-bit variable in the case it's a 8-bit or a 16-bit variable.
if (compare)
{
if (basicType != promoteType)
src << ", " << glu::getDataTypeName(promoteType) << "(" << sharedObjectVarName
<< structMember
<< "))";
else
src << ", " << sharedObjectVarName << structMember << ")";
}
src << ";\n";
}
}
string generateComputeShader (ShaderInterface &interface)
{
std::ostringstream src;
src << "#version 450\n";
if (interface.is16BitTypesEnabled())
src << "#extension GL_EXT_shader_explicit_arithmetic_types : enable\n";
if (interface.is8BitTypesEnabled())
src << "#extension GL_EXT_shader_explicit_arithmetic_types_int8 : enable\n";
src << "layout(local_size_x = 1) in;\n";
src << "\n";
src << "layout(std140, binding = 0) buffer block { highp uint passed; };\n";
// Output definitions for the struct fields of the shared memory objects.
std::vector<NamedStructSP>& namedStructs = interface.getStructs();
for (const auto& s: namedStructs)
src << glu::declare(s.get()) << ";\n";
// Output definitions for the shared memory structs.
for (auto& sharedObj : interface.getSharedObjects())
{
src << "struct " << sharedObj.getName() << " {\n";
for (auto& var : sharedObj)
src << "\t" << glu::declare(var.type, var.name, 1) << ";\n";
src << "};\n";
}
// Comparison utilities.
src << "\n";
generateCompareFuncs(src, interface);
src << "\n";
for (auto& sharedObj : interface.getSharedObjects())
src << "shared " << sharedObj.getName() << " " << sharedObj.getInstanceName() << ";\n";
src << "\n";
src << "void main (void) {\n";
for (auto& sharedObj : interface.getSharedObjects())
{
for (const auto& var : sharedObj)
{
vector<string>::const_iterator valueIter = var.entryValues.begin();
generateSharedMemoryWrites(src, sharedObj, var, glu::SubTypeAccess(var.type), valueIter, false);
}
}
src << "\n";
src << "\tbarrier();\n";
src << "\tmemoryBarrier();\n";
src << "\tbool allOk = true;\n";
for (auto& sharedObj : interface.getSharedObjects())
{
for (const auto& var : sharedObj)
{
vector<string>::const_iterator valueIter = var.entryValues.begin();
generateSharedMemoryWrites(src, sharedObj, var, glu::SubTypeAccess(var.type), valueIter, true);
}
}
src << "\tif (allOk)\n"
<< "\t\tpassed++;\n"
<< "\n";
src << "}\n";
return src.str();
}
void SharedLayoutCase::checkSupport(Context& context) const
{
if ((m_interface.is16BitTypesEnabled() || m_interface.is8BitTypesEnabled())
&& !context.isDeviceFunctionalitySupported("VK_KHR_shader_float16_int8"))
TCU_THROW(NotSupportedError, "VK_KHR_shader_float16_int8 extension for 16-/8-bit types not supported");
const vk::VkPhysicalDeviceVulkan12Features features = context.getDeviceVulkan12Features();
if (m_interface.is16BitTypesEnabled() && !features.shaderFloat16)
TCU_THROW(NotSupportedError, "16-bit types not supported");
if (m_interface.is8BitTypesEnabled() && !features.shaderInt8)
TCU_THROW(NotSupportedError, "8-bit types not supported");
}
tcu::TestStatus SharedLayoutCaseInstance::iterate (void)
{
const vk::DeviceInterface &vk = m_context.getDeviceInterface();
const vk::VkDevice device = m_context.getDevice();
const vk::VkQueue queue = m_context.getUniversalQueue();
const deUint32 queueFamilyIndex = m_context.getUniversalQueueFamilyIndex();
const deUint32 bufferSize = 4;
// Create descriptor set
const vk::VkBufferCreateInfo params =
{
vk::VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, // sType
DE_NULL, // pNext
0u, // flags
bufferSize, // size
vk::VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, // usage
vk::VK_SHARING_MODE_EXCLUSIVE, // sharingMode
1u, // queueFamilyCount
&queueFamilyIndex // pQueueFamilyIndices
};
vk::Move<vk::VkBuffer> buffer (vk::createBuffer(vk, device, ¶ms));
de::MovePtr<vk::Allocation> bufferAlloc (vk::bindBuffer (m_context.getDeviceInterface(), m_context.getDevice(),
m_context.getDefaultAllocator(), *buffer, vk::MemoryRequirement::HostVisible));
deMemset(bufferAlloc->getHostPtr(), 0, bufferSize);
flushMappedMemoryRange(vk, device, bufferAlloc->getMemory(), bufferAlloc->getOffset(), bufferSize);
vk::DescriptorSetLayoutBuilder setLayoutBuilder;
vk::DescriptorPoolBuilder poolBuilder;
setLayoutBuilder.addSingleBinding(vk::VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, vk::VK_SHADER_STAGE_COMPUTE_BIT);
poolBuilder.addType(vk::VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, deUint32(1));
const vk::Unique<vk::VkDescriptorSetLayout> descriptorSetLayout (setLayoutBuilder.build(vk, device));
const vk::Unique<vk::VkDescriptorPool> descriptorPool (poolBuilder.build(vk, device,
vk::VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, 1u));
const vk::VkDescriptorSetAllocateInfo allocInfo =
{
vk::VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
*descriptorPool, // VkDescriptorPool descriptorPool;
1u, // deUint32 descriptorSetCount;
&descriptorSetLayout.get(), // const VkDescriptorSetLayout *pSetLayouts;
};
const vk::Unique<vk::VkDescriptorSet> descriptorSet (allocateDescriptorSet(vk, device, &allocInfo));
const vk::VkDescriptorBufferInfo descriptorInfo = makeDescriptorBufferInfo(*buffer, 0ull, bufferSize);
vk::DescriptorSetUpdateBuilder setUpdateBuilder;
std::vector<vk::VkDescriptorBufferInfo> descriptors;
setUpdateBuilder.writeSingle(*descriptorSet, vk::DescriptorSetUpdateBuilder::Location::binding(0u),
vk::VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, &descriptorInfo);
setUpdateBuilder.update(vk, device);
const vk::VkPipelineLayoutCreateInfo pipelineLayoutParams =
{
vk::VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
(vk::VkPipelineLayoutCreateFlags) 0, // VkPipelineLayoutCreateFlags flags;
1u, // deUint32 descriptorSetCount;
&*descriptorSetLayout, // const VkDescriptorSetLayout* pSetLayouts;
0u, // deUint32 pushConstantRangeCount;
DE_NULL // const VkPushConstantRange* pPushConstantRanges;
};
vk::Move<vk::VkPipelineLayout> pipelineLayout (createPipelineLayout(vk, device, &pipelineLayoutParams));
vk::Move<vk::VkShaderModule> shaderModule (createShaderModule(vk, device, m_context.getBinaryCollection().get("compute"), 0));
const vk::VkPipelineShaderStageCreateInfo pipelineShaderStageParams =
{
vk::VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
(vk::VkPipelineShaderStageCreateFlags) 0, // VkPipelineShaderStageCreateFlags flags;
vk::VK_SHADER_STAGE_COMPUTE_BIT, // VkShaderStage stage;
*shaderModule, // VkShaderModule module;
"main", // const char* pName;
DE_NULL, // const VkSpecializationInfo* pSpecializationInfo;
};
const vk::VkComputePipelineCreateInfo pipelineCreateInfo =
{
vk::VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
0, // VkPipelineCreateFlags flags;
pipelineShaderStageParams, // VkPipelineShaderStageCreateInfo stage;
*pipelineLayout, // VkPipelineLayout layout;
DE_NULL, // VkPipeline basePipelineHandle;
0, // deInt32 basePipelineIndex;
};
vk::Move<vk::VkPipeline> pipeline (createComputePipeline(vk, device, DE_NULL, &pipelineCreateInfo));
vk::Move<vk::VkCommandPool> cmdPool (createCommandPool(vk, device, vk::VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, queueFamilyIndex));
vk::Move<vk::VkCommandBuffer> cmdBuffer (allocateCommandBuffer(vk, device, *cmdPool, vk::VK_COMMAND_BUFFER_LEVEL_PRIMARY));
beginCommandBuffer(vk, *cmdBuffer, 0u);
vk.cmdBindPipeline(*cmdBuffer, vk::VK_PIPELINE_BIND_POINT_COMPUTE, *pipeline);
vk.cmdBindDescriptorSets(*cmdBuffer, vk::VK_PIPELINE_BIND_POINT_COMPUTE, *pipelineLayout,
0u, 1u, &descriptorSet.get(), 0u, DE_NULL);
vk.cmdDispatch(*cmdBuffer, 1, 1, 1);
endCommandBuffer(vk, *cmdBuffer);
submitCommandsAndWait(vk, device, queue, cmdBuffer.get());
// Read back passed data
bool counterOk;
const int refCount = 1;
int resCount = 0;
invalidateAlloc(vk, device, *bufferAlloc);
resCount = *(static_cast<const int *>(bufferAlloc->getHostPtr()));
counterOk = (refCount == resCount);
if (!counterOk)
m_context.getTestContext().getLog() << TestLog::Message << "Error: passed = " << resCount
<< ", expected " << refCount << TestLog::EndMessage;
// Validate result
if (counterOk)
return tcu::TestStatus::pass("Counter value OK");
return tcu::TestStatus::fail("Counter value incorrect");
}
void SharedLayoutCase::initPrograms (vk::SourceCollections &programCollection) const
{
DE_ASSERT(!m_computeShaderSrc.empty());
programCollection.glslSources.add("compute") << glu::ComputeSource(m_computeShaderSrc);
}
TestInstance* SharedLayoutCase::createInstance (Context &context) const
{
return new SharedLayoutCaseInstance(context);
}
void SharedLayoutCase::delayedInit (void)
{
for (auto& sharedObj : m_interface.getSharedObjects())
for (auto &var : sharedObj)
computeReferenceLayout(var);
deUint32 seed = deStringHash(getName()) ^ 0xad2f7214;
de::Random rnd (seed);
for (auto& sharedObj : m_interface.getSharedObjects())
for (auto &var : sharedObj)
for (int i = 0; i < var.topLevelArraySize; i++)
for (auto &entry : var.entries)
generateValue(entry, rnd, var.entryValues);
m_computeShaderSrc = generateComputeShader(m_interface);
}
} // MemoryModel
} // vkt
| 18,152 | 7,304 |
//
// Query.hpp
// File file is part of the "URI" project and released under the MIT License.
//
// Created by Samuel Williams on 17/7/2017.
// Copyright, 2017, by Samuel Williams. All rights reserved.
//
#pragma once
#include "Encoding.hpp"
#include <string>
#include <map>
namespace URI
{
/// Assumes application/x-www-form-urlencoded.
struct Query
{
std::string value;
Query() {}
template <typename ValueT>
Query(const ValueT & value_) : value(value_) {}
template <typename IteratorT>
Query(IteratorT begin, IteratorT end) : Query(Encoding::encode_query(begin, end)) {}
bool empty () const noexcept {return value.empty();}
explicit operator bool() const noexcept {return !empty();}
std::multimap<std::string, std::string> to_map() const;
Query operator+(const Query & other);
bool operator==(const Query & other) const {return value == other.value;}
bool operator!=(const Query & other) const {return value != other.value;}
bool operator<(const Query & other) const {return value < other.value;}
bool operator<=(const Query & other) const {return value <= other.value;}
bool operator>(const Query & other) const {return value > other.value;}
bool operator>=(const Query & other) const {return value >= other.value;}
};
std::ostream & operator<<(std::ostream & output, const Query & query);
}
| 1,363 | 448 |
#ifndef ICARUS_SOCKHELPER_HPP
#define ICARUS_SOCKHELPER_HPP
#include <cstdint>
#include <sys/uio.h>
namespace icarus
{
namespace sockets
{
int create_nonblocking_or_die();
int connect(int sockfd, const struct sockaddr* addr);
void bind_or_die(int sockfd, const struct sockaddr* addr);
void listen_or_die(int sockfd);
int accept(int sockfd, struct sockaddr_in* addr);
void close(int sockfd);
void shutdown_write(int sockfd);
void set_non_block_and_close_on_exec(int sockfd);
uint64_t host_to_network64(uint64_t hosst64);
uint32_t host_to_network32(uint32_t host32);
uint16_t host_to_network16(uint16_t host16);
uint64_t network_to_host64(uint64_t net64);
uint32_t network_to_host32(uint32_t net32);
uint16_t network_to_host16(uint16_t net16);
ssize_t write(int fd, const void *buf, size_t count);
ssize_t readv(int sockfd, const struct iovec *iov, int iovcnt);
int get_socket_error(int sockfd);
struct sockaddr_in get_local_addr(int sockfd);
struct sockaddr_in get_peer_addr(int sockfd);
bool is_self_connect(int sockfd);
} // namespace sockets
} // namespace icarus
#endif // ICARUS_SOCKHELPER_HPP
| 1,109 | 476 |
/*
In this problem we will be considering a game played with four wheels. Digits ranging from 0 to 9
are printed consecutively (clockwise) on the periphery of each wheel. The topmost digits of the wheels
form a four-digit integer. For example, in the following figure the wheels form the integer 8056. Each
wheel has two buttons associated with it. Pressing the button marked with a left arrow rotates the
wheel one digit in the clockwise direction and pressing the one marked with the right arrow rotates it
by one digit in the opposite direction.
The game starts with an initial configuration of the wheels. Say, in the initial configuration the
topmost digits form the integer S1S2S3S4. You will be given some (say, n) forbidden configurations
Fi1 Fi2 Fi3 Fi4
(1 ≤ i ≤ n) and a target configuration T1T2T3T4. Your job will be to write a program that
can calculate the minimum number of button presses required to transform the initial configuration to
the target configuration by never passing through a forbidden one.
Input:
The first line of the input contains an integer N giving the number of test cases to follow.
The first line of each test case contains the initial configuration of the wheels specified by 4 digits.
Two consecutive digits are separated by a space. The next line contains the target configuration. The
third line contains an integer n giving the number of forbidden configurations. Each of the following n
lines contains a forbidden configuration. There is a blank line between two consecutive input sets.
Output:
For each test case in the input print a line containing the minimum number of button presses required.
If the target configuration is not reachable then print ‘-1’.
Sample Input:
2
8 0 5 6
6 5 0 8
5
8 0 5 7
8 0 4 7
5 5 0 8
7 5 0 8
6 4 0 8
0 0 0 0
5 3 1 7
8
0 0 0 1
0 0 0 9
0 0 1 0
0 0 9 0
0 1 0 0
0 9 0 0
1 0 0 0
9 0 0 0
Sample Output:
14
-1
*/
#include <iostream>
#include <vector>
#include <set>
#include <queue>
#include <string>
using namespace std;
int start, target;
set<int> forbs;
vector<int> vet[10000];
int to_number(int* arr) {
return (arr[0] * 1000) + (arr[1] * 100) + (arr[2] * 10) + arr[3];
}
bool is_forbs(int v) {
if(forbs.find(v) != forbs.end())
return true;
return false;
}
void build_graph() {
int v;
string buf;
for(int i = 0; i < 10000; i++) {
//x--- +
buf = to_string(i);
buf[0]++;
if(buf[0] == ':') buf[0] = '0';
v = stoi(buf);
if(!is_forbs(v))
vet[i].push_back(v);
//x--- -
buf = to_string(i);
buf[0]--;
if(buf[0] == '/') buf[0] = '9';
v = stoi(buf);
if(!is_forbs(v))
vet[i].push_back(v);
//-x-- +
buf = to_string(i);
buf[1]++;
if(buf[1] == ':') buf[1] = '0';
v = stoi(buf);
if(!is_forbs(v))
vet[i].push_back(v);
//-x-- -
buf = to_string(i);
buf[1]--;
if(buf[1] == '/') buf[1] = '9';
v = stoi(buf);
if(!is_forbs(v))
vet[i].push_back(v);
//--x- +
buf = to_string(i);
buf[2]++;
if(buf[2] == ':') buf[2] = '0';
v = stoi(buf);
if(!is_forbs(v))
vet[i].push_back(v);
//--x- -
buf = to_string(i);
buf[2]--;
if(buf[2] == '/') buf[2] = '9';
v = stoi(buf);
if(!is_forbs(v))
vet[i].push_back(v);
//---x +
buf = to_string(i);
buf[3]++;
if(buf[3] == ':') buf[3] = '0';
v = stoi(buf);
if(!is_forbs(v))
vet[i].push_back(v);
//---x -
buf = to_string(i);
buf[3]--;
if(buf[3] == '/') buf[3] = '9';
v = stoi(buf);
if(!is_forbs(v))
vet[i].push_back(v);
}
}
int bfs() {
int vis[10000];
for(int i = 0; i < 10000; i++) {
vis[i] = -1;
}
queue<int> q;
q.push(start);
vis[start] = 0;
int u, v;
while(!q.empty()){
u = q.front();
q.pop();
for(size_t i = 0; i < vet[u].size(); i++) {
v = vet[u][i];
if(vis[v] == -1) {
vis[v] = vis[u] + 1;
q.push(v);
}
}
}
return vis[target];
}
int main(void) {
int n;
cin >> n;
for(int i = 0; i < n; i++) {
int temp[4];
cin >> temp[0] >> temp[1] >> temp[2] >> temp[3];
start = to_number(temp);
cin >> temp[0] >> temp[1] >> temp[2] >> temp[3];
target = to_number(temp);
int f;
cin >> f;
for(int j = 0; j < f; j++) {
cin >> temp[0] >> temp[1] >> temp[2] >> temp[3];
int fbr = to_number(temp);
forbs.insert(fbr);
}
for(int k = 0; k < 10000; k++)
vet[k].clear();
build_graph();
cout << bfs() << endl;
}
} | 4,986 | 1,871 |
#pragma once
#include <array>
#include <cassert>
#include <functional>
#include <iostream>
#include <memory>
#include <vector>
enum class Cell_type {
unfilled = -1,
empty,
one,
};
struct Cell {
Cell_type type = Cell_type::unfilled;
void print() const {
switch (type) {
case Cell_type::unfilled: {
std::cout << "-";
return;
}
case Cell_type::empty: {
std::cout << "x";
return;
}
case Cell_type::one: {
std::cout << "1";
return;
}
}
}
};
| 647 | 189 |
The gray code is a binary numeral system where two successive values differ in only one bit.
Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A
gray code sequence must begin with 0.
Example 1:
Input: 2
Output: [0,1,3,2]
Explanation:
00 - 0
01 - 1
11 - 3
10 - 2
For a given n, a gray code sequence may not be uniquely defined.
For example, [0,2,3,1] is also a valid gray code sequence.
00 - 0
10 - 2
11 - 3
01 - 1
Example 2:
Input: 0
Output: [0]
Explanation: We define the gray code sequence to begin with 0.
A gray code sequence of n has size = 2n, which for n = 0 the size is 20 = 1.
Therefore, for n = 0 the gray code sequence is [0].
class Solution {
public:
vector<int> grayCode(int n) {
}
};
| 807 | 288 |
#include "Mount.h"
Mount::Mount(double yawRatio, unsigned int yawOffset, unsigned int yawPin, double pitchRatio, unsigned int pitchOffset, unsigned int pitchPin)
: yawRatio(yawRatio), pitchRatio(pitchRatio)
{
yawServo.offset = yawOffset;
yawServo.pin = yawPin;
pitchServo.offset = pitchOffset;
pitchServo.pin = pitchPin;
}
void Mount::attach()
{
yawServo.attach();
pitchServo.attach();
}
void Mount::detach()
{
yawServo.detach();
pitchServo.detach();
}
Pair Mount::getState()
{
Pair temp;
temp.yaw = yawServo.readAngle();
temp.pitch = pitchServo.readAngle();
return temp;
} | 632 | 239 |
#include <iostream>
using namespace std;
int fibonacci(int x)
{
int a, b, c, i;
a = 0;
b = 1;
if (x == 1) {
return 0;
}
else if (x == 2) {
return 1;
}
else {
for (i = 3; i <= x; i++) {
c = a + b;
a = b;
b = c;
}
return c;
}
}
int main()
{
int n;
cout << "Enter the value of n\n";
cin >> n;
cout << n << "th Number in Fibonacci Series :- " << fibonacci(n);
return 0;
}
| 511 | 213 |
/**
* Copyright (c) 2021 OceanBase
* OceanBase CE is licensed under Mulan PubL v2.
* You can use this software according to the terms and conditions of the Mulan PubL v2.
* You may obtain a copy of Mulan PubL v2 at:
* http://license.coscl.org.cn/MulanPubL-2.0
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PubL v2 for more details.
*/
#include "lib/ob_name_id_def.h"
#include <stdlib.h>
#include <string.h>
namespace oceanbase {
namespace name {
static const char* ID_NAMES[NAME_COUNT + 1];
static const char* ID_DESCRIPTIONS[NAME_COUNT + 1];
struct RuntimeIdNameMapInit {
RuntimeIdNameMapInit()
{
#define DEF_NAME(name_sym, description) ID_NAMES[name_sym] = #name_sym;
#define DEF_NAME_PAIR(name_sym, description) \
DEF_NAME(name_sym##_begin, description " begin") \
DEF_NAME(name_sym##_end, description " end")
#include "ob_name_id_def.h"
#undef DEF_NAME
#undef DEF_NAME_PAIR
#define DEF_NAME(name_sym, description) ID_DESCRIPTIONS[name_sym] = description;
#define DEF_NAME_PAIR(name_sym, description) \
DEF_NAME(name_sym##_begin, description " begin") \
DEF_NAME(name_sym##_end, description " end")
#include "ob_name_id_def.h"
#undef DEF_NAME
#undef DEF_NAME_PAIR
}
};
static RuntimeIdNameMapInit INIT;
const char* get_name(int32_t id)
{
const char* ret = NULL;
if (id < NAME_COUNT && id >= 0) {
ret = oceanbase::name::ID_NAMES[id];
}
return ret;
}
const char* get_description(int32_t id)
{
const char* ret = NULL;
if (id < NAME_COUNT && id >= 0) {
ret = oceanbase::name::ID_DESCRIPTIONS[id];
}
return ret;
}
} // namespace name
} // end namespace oceanbase
| 1,815 | 709 |
#include "common.hpp"
#include <opencv2/superres.hpp>
#include "superres_types.hpp"
extern "C" {
Result<cv::Ptr<cv::superres::FrameSource>*> cv_superres_createFrameSource_Camera_int(int deviceId) {
try {
cv::Ptr<cv::superres::FrameSource> ret = cv::superres::createFrameSource_Camera(deviceId);
return Ok(new cv::Ptr<cv::superres::FrameSource>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::FrameSource>*>))
}
Result<cv::Ptr<cv::superres::FrameSource>*> cv_superres_createFrameSource_Empty() {
try {
cv::Ptr<cv::superres::FrameSource> ret = cv::superres::createFrameSource_Empty();
return Ok(new cv::Ptr<cv::superres::FrameSource>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::FrameSource>*>))
}
Result<cv::Ptr<cv::superres::FrameSource>*> cv_superres_createFrameSource_Video_CUDA_const_StringR(const char* fileName) {
try {
cv::Ptr<cv::superres::FrameSource> ret = cv::superres::createFrameSource_Video_CUDA(std::string(fileName));
return Ok(new cv::Ptr<cv::superres::FrameSource>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::FrameSource>*>))
}
Result<cv::Ptr<cv::superres::FrameSource>*> cv_superres_createFrameSource_Video_const_StringR(const char* fileName) {
try {
cv::Ptr<cv::superres::FrameSource> ret = cv::superres::createFrameSource_Video(std::string(fileName));
return Ok(new cv::Ptr<cv::superres::FrameSource>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::FrameSource>*>))
}
Result<cv::Ptr<cv::superres::BroxOpticalFlow>*> cv_superres_createOptFlow_Brox_CUDA() {
try {
cv::Ptr<cv::superres::BroxOpticalFlow> ret = cv::superres::createOptFlow_Brox_CUDA();
return Ok(new cv::Ptr<cv::superres::BroxOpticalFlow>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::BroxOpticalFlow>*>))
}
Result<cv::Ptr<cv::superres::DualTVL1OpticalFlow>*> cv_superres_createOptFlow_DualTVL1() {
try {
cv::Ptr<cv::superres::DualTVL1OpticalFlow> ret = cv::superres::createOptFlow_DualTVL1();
return Ok(new cv::Ptr<cv::superres::DualTVL1OpticalFlow>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::DualTVL1OpticalFlow>*>))
}
Result<cv::Ptr<cv::superres::DualTVL1OpticalFlow>*> cv_superres_createOptFlow_DualTVL1_CUDA() {
try {
cv::Ptr<cv::superres::DualTVL1OpticalFlow> ret = cv::superres::createOptFlow_DualTVL1_CUDA();
return Ok(new cv::Ptr<cv::superres::DualTVL1OpticalFlow>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::DualTVL1OpticalFlow>*>))
}
Result<cv::Ptr<cv::superres::FarnebackOpticalFlow>*> cv_superres_createOptFlow_Farneback() {
try {
cv::Ptr<cv::superres::FarnebackOpticalFlow> ret = cv::superres::createOptFlow_Farneback();
return Ok(new cv::Ptr<cv::superres::FarnebackOpticalFlow>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::FarnebackOpticalFlow>*>))
}
Result<cv::Ptr<cv::superres::FarnebackOpticalFlow>*> cv_superres_createOptFlow_Farneback_CUDA() {
try {
cv::Ptr<cv::superres::FarnebackOpticalFlow> ret = cv::superres::createOptFlow_Farneback_CUDA();
return Ok(new cv::Ptr<cv::superres::FarnebackOpticalFlow>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::FarnebackOpticalFlow>*>))
}
Result<cv::Ptr<cv::superres::PyrLKOpticalFlow>*> cv_superres_createOptFlow_PyrLK_CUDA() {
try {
cv::Ptr<cv::superres::PyrLKOpticalFlow> ret = cv::superres::createOptFlow_PyrLK_CUDA();
return Ok(new cv::Ptr<cv::superres::PyrLKOpticalFlow>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::PyrLKOpticalFlow>*>))
}
Result<cv::Ptr<cv::superres::SuperResolution>*> cv_superres_createSuperResolution_BTVL1() {
try {
cv::Ptr<cv::superres::SuperResolution> ret = cv::superres::createSuperResolution_BTVL1();
return Ok(new cv::Ptr<cv::superres::SuperResolution>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::SuperResolution>*>))
}
Result<cv::Ptr<cv::superres::SuperResolution>*> cv_superres_createSuperResolution_BTVL1_CUDA() {
try {
cv::Ptr<cv::superres::SuperResolution> ret = cv::superres::createSuperResolution_BTVL1_CUDA();
return Ok(new cv::Ptr<cv::superres::SuperResolution>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::SuperResolution>*>))
}
Result<double> cv_superres_BroxOpticalFlow_getAlpha_const(const cv::superres::BroxOpticalFlow* instance) {
try {
double ret = instance->getAlpha();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_BroxOpticalFlow_setAlpha_double(cv::superres::BroxOpticalFlow* instance, double val) {
try {
instance->setAlpha(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<double> cv_superres_BroxOpticalFlow_getGamma_const(const cv::superres::BroxOpticalFlow* instance) {
try {
double ret = instance->getGamma();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_BroxOpticalFlow_setGamma_double(cv::superres::BroxOpticalFlow* instance, double val) {
try {
instance->setGamma(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<double> cv_superres_BroxOpticalFlow_getScaleFactor_const(const cv::superres::BroxOpticalFlow* instance) {
try {
double ret = instance->getScaleFactor();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_BroxOpticalFlow_setScaleFactor_double(cv::superres::BroxOpticalFlow* instance, double val) {
try {
instance->setScaleFactor(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_BroxOpticalFlow_getInnerIterations_const(const cv::superres::BroxOpticalFlow* instance) {
try {
int ret = instance->getInnerIterations();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_BroxOpticalFlow_setInnerIterations_int(cv::superres::BroxOpticalFlow* instance, int val) {
try {
instance->setInnerIterations(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_BroxOpticalFlow_getOuterIterations_const(const cv::superres::BroxOpticalFlow* instance) {
try {
int ret = instance->getOuterIterations();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_BroxOpticalFlow_setOuterIterations_int(cv::superres::BroxOpticalFlow* instance, int val) {
try {
instance->setOuterIterations(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_BroxOpticalFlow_getSolverIterations_const(const cv::superres::BroxOpticalFlow* instance) {
try {
int ret = instance->getSolverIterations();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_BroxOpticalFlow_setSolverIterations_int(cv::superres::BroxOpticalFlow* instance, int val) {
try {
instance->setSolverIterations(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result_void cv_superres_DenseOpticalFlowExt_calc_const__InputArrayR_const__InputArrayR_const__OutputArrayR_const__OutputArrayR(cv::superres::DenseOpticalFlowExt* instance, const cv::_InputArray* frame0, const cv::_InputArray* frame1, const cv::_OutputArray* flow1, const cv::_OutputArray* flow2) {
try {
instance->calc(*frame0, *frame1, *flow1, *flow2);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result_void cv_superres_DenseOpticalFlowExt_collectGarbage(cv::superres::DenseOpticalFlowExt* instance) {
try {
instance->collectGarbage();
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<double> cv_superres_DualTVL1OpticalFlow_getTau_const(const cv::superres::DualTVL1OpticalFlow* instance) {
try {
double ret = instance->getTau();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_DualTVL1OpticalFlow_setTau_double(cv::superres::DualTVL1OpticalFlow* instance, double val) {
try {
instance->setTau(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<double> cv_superres_DualTVL1OpticalFlow_getLambda_const(const cv::superres::DualTVL1OpticalFlow* instance) {
try {
double ret = instance->getLambda();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_DualTVL1OpticalFlow_setLambda_double(cv::superres::DualTVL1OpticalFlow* instance, double val) {
try {
instance->setLambda(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<double> cv_superres_DualTVL1OpticalFlow_getTheta_const(const cv::superres::DualTVL1OpticalFlow* instance) {
try {
double ret = instance->getTheta();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_DualTVL1OpticalFlow_setTheta_double(cv::superres::DualTVL1OpticalFlow* instance, double val) {
try {
instance->setTheta(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_DualTVL1OpticalFlow_getScalesNumber_const(const cv::superres::DualTVL1OpticalFlow* instance) {
try {
int ret = instance->getScalesNumber();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_DualTVL1OpticalFlow_setScalesNumber_int(cv::superres::DualTVL1OpticalFlow* instance, int val) {
try {
instance->setScalesNumber(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_DualTVL1OpticalFlow_getWarpingsNumber_const(const cv::superres::DualTVL1OpticalFlow* instance) {
try {
int ret = instance->getWarpingsNumber();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_DualTVL1OpticalFlow_setWarpingsNumber_int(cv::superres::DualTVL1OpticalFlow* instance, int val) {
try {
instance->setWarpingsNumber(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<double> cv_superres_DualTVL1OpticalFlow_getEpsilon_const(const cv::superres::DualTVL1OpticalFlow* instance) {
try {
double ret = instance->getEpsilon();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_DualTVL1OpticalFlow_setEpsilon_double(cv::superres::DualTVL1OpticalFlow* instance, double val) {
try {
instance->setEpsilon(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_DualTVL1OpticalFlow_getIterations_const(const cv::superres::DualTVL1OpticalFlow* instance) {
try {
int ret = instance->getIterations();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_DualTVL1OpticalFlow_setIterations_int(cv::superres::DualTVL1OpticalFlow* instance, int val) {
try {
instance->setIterations(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<bool> cv_superres_DualTVL1OpticalFlow_getUseInitialFlow_const(const cv::superres::DualTVL1OpticalFlow* instance) {
try {
bool ret = instance->getUseInitialFlow();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<bool>))
}
Result_void cv_superres_DualTVL1OpticalFlow_setUseInitialFlow_bool(cv::superres::DualTVL1OpticalFlow* instance, bool val) {
try {
instance->setUseInitialFlow(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<double> cv_superres_FarnebackOpticalFlow_getPyrScale_const(const cv::superres::FarnebackOpticalFlow* instance) {
try {
double ret = instance->getPyrScale();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_FarnebackOpticalFlow_setPyrScale_double(cv::superres::FarnebackOpticalFlow* instance, double val) {
try {
instance->setPyrScale(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_FarnebackOpticalFlow_getLevelsNumber_const(const cv::superres::FarnebackOpticalFlow* instance) {
try {
int ret = instance->getLevelsNumber();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_FarnebackOpticalFlow_setLevelsNumber_int(cv::superres::FarnebackOpticalFlow* instance, int val) {
try {
instance->setLevelsNumber(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_FarnebackOpticalFlow_getWindowSize_const(const cv::superres::FarnebackOpticalFlow* instance) {
try {
int ret = instance->getWindowSize();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_FarnebackOpticalFlow_setWindowSize_int(cv::superres::FarnebackOpticalFlow* instance, int val) {
try {
instance->setWindowSize(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_FarnebackOpticalFlow_getIterations_const(const cv::superres::FarnebackOpticalFlow* instance) {
try {
int ret = instance->getIterations();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_FarnebackOpticalFlow_setIterations_int(cv::superres::FarnebackOpticalFlow* instance, int val) {
try {
instance->setIterations(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_FarnebackOpticalFlow_getPolyN_const(const cv::superres::FarnebackOpticalFlow* instance) {
try {
int ret = instance->getPolyN();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_FarnebackOpticalFlow_setPolyN_int(cv::superres::FarnebackOpticalFlow* instance, int val) {
try {
instance->setPolyN(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<double> cv_superres_FarnebackOpticalFlow_getPolySigma_const(const cv::superres::FarnebackOpticalFlow* instance) {
try {
double ret = instance->getPolySigma();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_FarnebackOpticalFlow_setPolySigma_double(cv::superres::FarnebackOpticalFlow* instance, double val) {
try {
instance->setPolySigma(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_FarnebackOpticalFlow_getFlags_const(const cv::superres::FarnebackOpticalFlow* instance) {
try {
int ret = instance->getFlags();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_FarnebackOpticalFlow_setFlags_int(cv::superres::FarnebackOpticalFlow* instance, int val) {
try {
instance->setFlags(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result_void cv_superres_FrameSource_nextFrame_const__OutputArrayR(cv::superres::FrameSource* instance, const cv::_OutputArray* frame) {
try {
instance->nextFrame(*frame);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result_void cv_superres_FrameSource_reset(cv::superres::FrameSource* instance) {
try {
instance->reset();
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_PyrLKOpticalFlow_getWindowSize_const(const cv::superres::PyrLKOpticalFlow* instance) {
try {
int ret = instance->getWindowSize();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_PyrLKOpticalFlow_setWindowSize_int(cv::superres::PyrLKOpticalFlow* instance, int val) {
try {
instance->setWindowSize(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_PyrLKOpticalFlow_getMaxLevel_const(const cv::superres::PyrLKOpticalFlow* instance) {
try {
int ret = instance->getMaxLevel();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_PyrLKOpticalFlow_setMaxLevel_int(cv::superres::PyrLKOpticalFlow* instance, int val) {
try {
instance->setMaxLevel(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_PyrLKOpticalFlow_getIterations_const(const cv::superres::PyrLKOpticalFlow* instance) {
try {
int ret = instance->getIterations();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_PyrLKOpticalFlow_setIterations_int(cv::superres::PyrLKOpticalFlow* instance, int val) {
try {
instance->setIterations(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result_void cv_superres_SuperResolution_setInput_const_Ptr_FrameSource_R(cv::superres::SuperResolution* instance, const cv::Ptr<cv::superres::FrameSource>* frameSource) {
try {
instance->setInput(*frameSource);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result_void cv_superres_SuperResolution_nextFrame_const__OutputArrayR(cv::superres::SuperResolution* instance, const cv::_OutputArray* frame) {
try {
instance->nextFrame(*frame);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result_void cv_superres_SuperResolution_reset(cv::superres::SuperResolution* instance) {
try {
instance->reset();
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result_void cv_superres_SuperResolution_collectGarbage(cv::superres::SuperResolution* instance) {
try {
instance->collectGarbage();
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_SuperResolution_getScale_const(const cv::superres::SuperResolution* instance) {
try {
int ret = instance->getScale();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_SuperResolution_setScale_int(cv::superres::SuperResolution* instance, int val) {
try {
instance->setScale(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_SuperResolution_getIterations_const(const cv::superres::SuperResolution* instance) {
try {
int ret = instance->getIterations();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_SuperResolution_setIterations_int(cv::superres::SuperResolution* instance, int val) {
try {
instance->setIterations(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<double> cv_superres_SuperResolution_getTau_const(const cv::superres::SuperResolution* instance) {
try {
double ret = instance->getTau();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_SuperResolution_setTau_double(cv::superres::SuperResolution* instance, double val) {
try {
instance->setTau(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<double> cv_superres_SuperResolution_getLambda_const(const cv::superres::SuperResolution* instance) {
try {
double ret = instance->getLambda();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_SuperResolution_setLambda_double(cv::superres::SuperResolution* instance, double val) {
try {
instance->setLambda(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<double> cv_superres_SuperResolution_getAlpha_const(const cv::superres::SuperResolution* instance) {
try {
double ret = instance->getAlpha();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_SuperResolution_setAlpha_double(cv::superres::SuperResolution* instance, double val) {
try {
instance->setAlpha(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_SuperResolution_getKernelSize_const(const cv::superres::SuperResolution* instance) {
try {
int ret = instance->getKernelSize();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_SuperResolution_setKernelSize_int(cv::superres::SuperResolution* instance, int val) {
try {
instance->setKernelSize(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_SuperResolution_getBlurKernelSize_const(const cv::superres::SuperResolution* instance) {
try {
int ret = instance->getBlurKernelSize();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_SuperResolution_setBlurKernelSize_int(cv::superres::SuperResolution* instance, int val) {
try {
instance->setBlurKernelSize(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<double> cv_superres_SuperResolution_getBlurSigma_const(const cv::superres::SuperResolution* instance) {
try {
double ret = instance->getBlurSigma();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_SuperResolution_setBlurSigma_double(cv::superres::SuperResolution* instance, double val) {
try {
instance->setBlurSigma(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_SuperResolution_getTemporalAreaRadius_const(const cv::superres::SuperResolution* instance) {
try {
int ret = instance->getTemporalAreaRadius();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_SuperResolution_setTemporalAreaRadius_int(cv::superres::SuperResolution* instance, int val) {
try {
instance->setTemporalAreaRadius(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<cv::Ptr<cv::superres::DenseOpticalFlowExt>*> cv_superres_SuperResolution_getOpticalFlow_const(const cv::superres::SuperResolution* instance) {
try {
cv::Ptr<cv::superres::DenseOpticalFlowExt> ret = instance->getOpticalFlow();
return Ok(new cv::Ptr<cv::superres::DenseOpticalFlowExt>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::DenseOpticalFlowExt>*>))
}
Result_void cv_superres_SuperResolution_setOpticalFlow_const_Ptr_DenseOpticalFlowExt_R(cv::superres::SuperResolution* instance, const cv::Ptr<cv::superres::DenseOpticalFlowExt>* val) {
try {
instance->setOpticalFlow(*val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
}
| 21,709 | 8,974 |
/**
* @file piecewiseLR_test.cpp
* @author Jiaoyi
* @brief
* @version 0.1
* @date 2021-11-03
*
* @copyright Copyright (c) 2021
*
*/
#include "../../include/nodes/rootNode/trainModel/piecewiseLR.h"
#include "../../experiment/dataset/lognormal_distribution.h"
#include "gtest/gtest.h"
std::vector<std::pair<double, double>> initData;
std::vector<std::pair<double, double>> insertData;
std::vector<std::pair<double, double>> testInsert;
const int kChildNum = 512;
const int kTestMaxValue = kMaxValue;
LognormalDataset logData(0.9);
PiecewiseLR<DataVecType, double> model;
TEST(TestTrain, TrainPLRModel) {
logData.GenerateDataset(&initData, &insertData, &testInsert);
model.maxChildIdx = kChildNum - 1;
model.Train(initData);
EXPECT_EQ(kChildNum - 1, model.maxChildIdx);
}
TEST(TestPredictInitData, PredictInitData) {
for (int i = 0; i < initData.size(); i++) {
int p = model.Predict(initData[i].first);
EXPECT_GE(p, 0);
EXPECT_LT(p, kChildNum);
}
}
TEST(TestPredictInsertData, PredictInsertData) {
for (int i = 0; i < insertData.size(); i++) {
int p = model.Predict(insertData[i].first);
EXPECT_GE(p, 0);
EXPECT_LT(p, kChildNum);
}
} | 1,187 | 480 |
// -*- C++ -*-
// Package: STFilter
// Class: STFilter
/**\class STFilter STFilter.cc MyEDFilter/STFilter/src/STFilter.cc
Description:
** used for single top t-channel events generated with MadEvent
and matched the "Karlsruhe way"
** filter on 2->2 process events, where the crucial candidate (the 2nd b quark)
is not available until parton showering is done
** filter criterion: transverse momentum of 2nd b quark "pT < pTMax" -> event accepted!
** How-To: include STFilter.cfg in your .cfg, replace pTMax by the desired value,
include module "STFilter" in outpath
Implementation:
<Notes on implementation>
*/
// Original Author: Julia Weinelt
// Created: Wed Jan 23 15:12:46 CET 2008
#include <memory>
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "GeneratorInterface/GenFilters/interface/STFilter.h"
#include "SimDataFormats/GeneratorProducts/interface/HepMCProduct.h"
#include "HepMC/GenEvent.h"
STFilter::STFilter(const edm::ParameterSet& iConfig)
: hepMCProductTag_(
iConfig.getUntrackedParameter<edm::InputTag>("hepMCProductTag", edm::InputTag("generator", "unsmeared"))) {
pTMax_ = iConfig.getParameter<double>("pTMax");
edm::LogInfo("SingleTopMatchingFilter") << "+++ maximum pt of associated-b pTMax = " << pTMax_;
DEBUGLVL = iConfig.getUntrackedParameter<int>("debuglvl", 0); // get debug level
input_events = 0;
accepted_events = 0; // counters
m_produceHistos = iConfig.getParameter<bool>("produceHistos"); // produce histograms?
fOutputFileName =
iConfig.getUntrackedParameter<std::string>("histOutFile"); // get name of output file with histograms
conf_ = iConfig;
}
STFilter::~STFilter() {}
bool STFilter::filter(edm::Event& iEvent, const edm::EventSetup& iSetup) {
using namespace edm;
bool accEvt = false;
bool lo = false;
int secBcount = 0;
double pTSecB = 100;
double etaSecB = 100;
++input_events;
Handle<HepMCProduct> evt;
iEvent.getByLabel(hepMCProductTag_, evt);
const HepMC::GenEvent* myEvt = evt->GetEvent(); // GET EVENT FROM HANDLE
bool bQuarksOpposite = false;
for (HepMC::GenEvent::particle_const_iterator i = myEvt->particles_begin(); (*i)->status() == 3;
++i) { // abort after status 3 particles
// logic:
// - in 2->2 matrix elements, the incoming (top production)
// b quark and the outgoing (top decay) b quark have same sign,
// so we flip the bQuarksOpposite flag twice -> false
// (opposite-sign b quark comes from the shower and has status 2)
// - in 2->3 matrix elements, we have two outgoing b quarks with status
// 3 and opposite signs -> true
if ((*i)->pdg_id() == -5)
bQuarksOpposite = !bQuarksOpposite;
}
// ---- 22 or 23? ----
if (!bQuarksOpposite) // 22
lo = true;
else
accEvt = true; // 23
// ---- filter only 22 events ----
if (lo) {
for (HepMC::GenEvent::particle_const_iterator p = myEvt->particles_begin(); p != myEvt->particles_end(); ++p) {
// ---- look in shower for 2nd b quark ----
if ((*p)->status() == 2 && abs((*p)->pdg_id()) == 5) {
// ---- if b quark is found, loop over its parents ----
for (HepMC::GenVertex::particle_iterator m = (*p)->production_vertex()->particles_begin(HepMC::parents);
m != (*p)->production_vertex()->particles_end(HepMC::parents);
++m) {
// ---- found 2ndb-candidate in shower ---- // ---- check mother of this candidate ----
if (abs((*m)->barcode()) < 5) {
if (secBcount == 1)
break;
secBcount++;
pTSecB = (*p)->operator HepMC::FourVector().perp();
etaSecB = (*p)->operator HepMC::FourVector().eta();
}
}
}
}
if (pTSecB < pTMax_)
accEvt = true;
// fill histos if requested
if (m_produceHistos) {
hbPt->Fill(pTSecB);
hbEta->Fill(etaSecB);
if (accEvt) {
hbPtFiltered->Fill(pTSecB);
hbEtaFiltered->Fill(etaSecB);
}
}
}
if (accEvt)
++accepted_events;
return accEvt;
}
void STFilter::beginJob() {
if (m_produceHistos) { // initialize histogram output file
edm::ParameterSet Parameters;
edm::LogInfo("SingleTopMatchingFilter)")
<< "beginJob : creating histogram file: " << fOutputFileName.c_str() << std::endl;
hOutputFile = new TFile(fOutputFileName.c_str(), "RECREATE");
hOutputFile->cd();
// book histograms
Parameters = conf_.getParameter<edm::ParameterSet>("TH1bPt");
hbPt = new TH1D("bPt",
"Pt of 2nd b quark",
Parameters.getParameter<int32_t>("Nbinx"),
Parameters.getParameter<double>("xmin"),
Parameters.getParameter<double>("xmax"));
Parameters = conf_.getParameter<edm::ParameterSet>("TH1bEta");
hbEta = new TH1D("bEta",
"Eta of 2nd b quark",
Parameters.getParameter<int32_t>("Nbinx"),
Parameters.getParameter<double>("xmin"),
Parameters.getParameter<double>("xmax"));
Parameters = conf_.getParameter<edm::ParameterSet>("TH1bPtFiltered");
hbPtFiltered = new TH1D("bPtFiltered",
"Pt of 2nd b quark filtered",
Parameters.getParameter<int32_t>("Nbinx"),
Parameters.getParameter<double>("xmin"),
Parameters.getParameter<double>("xmax"));
Parameters = conf_.getParameter<edm::ParameterSet>("TH1bEtaFiltered");
hbEtaFiltered = new TH1D("bEtaFiltered",
"Eta of 2nd b quark filtered",
Parameters.getParameter<int32_t>("Nbinx"),
Parameters.getParameter<double>("xmin"),
Parameters.getParameter<double>("xmax"));
}
}
void STFilter::endJob() {
if (m_produceHistos) {
hOutputFile->cd();
hbPt->Write();
hbEta->Write();
hbPtFiltered->Write();
hbEtaFiltered->Write();
hOutputFile->Write();
hOutputFile->Close();
} // Write out histograms to file, then close it
double fraction = (double)accepted_events / (double)input_events;
double percent = 100. * fraction;
double error = 100. * sqrt(fraction * (1 - fraction) / (double)input_events);
std::cout << "STFilter ++ accepted_events/input_events = " << accepted_events << "/" << input_events << " = "
<< fraction << std::endl;
std::cout << "STFilter ++ efficiency = " << percent << " % +/- " << error << " %" << std::endl;
}
//DEFINE_FWK_MODULE(STFilter);
| 6,703 | 2,278 |
#include<bits/stdc++.h>
using namespace std;
double allsquare;
double beginx,beginy,endx,endy,ans;
bool bj[10];
int n,i,j,k;
const double pi=3.1415926535;
struct oils
{
double x,y;
double r;
} oil[10];
void rget(int i)
{
oil[i].r=min(min(abs(oil[i].x-beginx),abs(oil[i].x-endx)),min(abs(oil[i].y-beginy),abs(oil[i].y-endy)));
for (int j=1;j<=n;j++)
{
if (i!=j&&bj[j]==1)
{
oil[i].r=min(oil[i].r,max(0.0,sqrt(pow(oil[i].x-oil[j].x,2)+pow(oil[i].y-oil[j].y,2))-oil[j].r));
}
}
}
void dfs(int now,double ansx)
{
if (now>n)
{
ans=max(ans,ansx);
return ;
}
for (int i=1;i<=n;i++)
{
if (bj[i]==0)
{
bj[i]=1;
rget(i);
dfs(now+1,ansx+pow(oil[i].r,2)*pi);
bj[i]=0;
}
}
}
int main()
{
cin>>n;
cin>>beginx>>beginy>>endx>>endy;
for (i=1;i<=n;i++)
{
cin>>oil[i].x>>oil[i].y;
}
allsquare=abs(beginx-endx)*abs(beginy-endy);
dfs(1,0);
cout<<int(allsquare-ans+0.5)<<endl;
return 0;
}
| 933 | 573 |
/*
* PseudoContact.cpp
*
* Created on: 2012-05-03
* Author: e4k2
*/
#include <algorithm>
#include <cassert>
#include "PseudoContact.h"
#include "Utilities.h"
PseudoContact::PseudoContact() : contacts(), res1(-1), res2(-1)
{
}
PseudoContact::PseudoContact(const Contact& c) : contacts(), res1(c.r1->num), res2(c.r2->num)
{
contacts.insert(c);
}
PseudoContact::~PseudoContact()
{
}
PseudoContact::PseudoContact(const PseudoContact& pc) : contacts(pc.contacts), res1(pc.res1), res2(pc.res2)
{
}
void swap(PseudoContact& first, PseudoContact& second)
{
using std::swap;
swap(first.contacts,second.contacts);
swap(first.res1,second.res1);
swap(first.res2,second.res2);
}
//PseudoContact::PseudoContact(PseudoContact&& pc) : contacts()
//{
// swap(*this,pc);
//}
PseudoContact& PseudoContact::operator=(PseudoContact pc)
{
swap(*this,pc);
return *this;
}
void PseudoContact::add(const Contact& c)
{
contacts.insert(c);
if (res1 < 0)
{
res1 = c.r1->num;
res2 = c.r2->num;
}
else
{
assert(c.r1->num == res1 && c.r2->num == res2);
}
}
int PseudoContact::numContacts() const
{
return contacts.size();
}
void PseudoContact::print() const
{
for (tr1::unordered_set<Contact>::const_iterator it = contacts.begin(); it != contacts.end(); ++it)
{
it->print();
}
}
bool PseudoContact::operator==(const PseudoContact& pc) const
{
if (contacts.size() != pc.contacts.size())
return false;
for (tr1::unordered_set<Contact>::const_iterator it = pc.contacts.begin(); it != pc.contacts.end(); ++it)
{
if (contacts.find(*it) == contacts.end())
return false;
}
return true;
}
bool PseudoContact::areSymmetric(const PseudoContact& pc) const
{
if (contacts.size() != pc.contacts.size())
return false;
for (tr1::unordered_set<Contact>::const_iterator it = pc.contacts.begin(); it != pc.contacts.end(); ++it)
{
Contact c = it->reverse();
if (contacts.find(c) == contacts.end())
return false;
}
return true;
}
bool PseudoContact::operator!=(const PseudoContact& pc) const
{
return !(*this == pc);
}
tr1::unordered_set<Contact>& PseudoContact::getContacts()
{
return contacts;
}
Contact PseudoContact::getOneContact()
{
return *(contacts.begin());
}
// returns res1 <= res2
void PseudoContact::getResPairOrdered(int& res1, int& res2) const
{
if (this->res1 <= this->res2)
{
res1 = this->res1;
res2 = this->res2;
}
else
{
res1 = this->res2;
res2 = this->res1;
}
}
void PseudoContact::getResPair(int& res1, int& res2) const
{
res1 = this->res1;
res2 = this->res2;
}
void PseudoContact::setReverse()
{
std::swap(res1,res2);
vector<Contact> temp(contacts.begin(),contacts.end());
contacts.clear();
for (vector<Contact>::iterator it = temp.begin(); it != temp.end(); ++it)
{
contacts.insert(it->reverse());
}
}
bool PseudoContact::overlaps(const PseudoContact& pc) const
{
if (res1 == pc.res1 && res2 == pc.res2)
{
for (tr1::unordered_set<Contact>::const_iterator it1 = contacts.begin(); it1 != contacts.end(); ++it1)
{
const Contact& c1 = *it1;
for (tr1::unordered_set<Contact>::const_iterator it2 = pc.contacts.begin(); it2 != pc.contacts.end(); ++it2)
{
const Contact& c2 = *it2;
if (c1 == c2)
return true;
}
}
}
else if (res1 == pc.res2 && res2 == pc.res1)
{
for (tr1::unordered_set<Contact>::const_iterator it1 = contacts.begin(); it1 != contacts.end(); ++it1)
{
const Contact& c1 = *it1;
for (tr1::unordered_set<Contact>::const_iterator it2 = pc.contacts.begin(); it2 != pc.contacts.end(); ++it2)
{
const Contact& c2 = it2->reverse();
if (c1 == c2)
return true;
}
}
}
return false;
}
void PseudoContact::addAll(const PseudoContact& pc)
{
if (res1 == pc.res1 && res2 == pc.res2)
{
contacts.insert(pc.contacts.begin(),pc.contacts.end());
}
else if (res1 == pc.res2 && res2 == pc.res1)
{
for (tr1::unordered_set<Contact>::const_iterator it2 = pc.contacts.begin(); it2 != pc.contacts.end(); ++it2)
{
const Contact& c2 = it2->reverse();
contacts.insert(c2);
}
}
}
int PseudoContact::getSeqSep() const
{
return abs(res1-res2);
}
| 4,095 | 1,712 |
/**
ATtiny85 Serial-like debug interface for the Wokwi.com simulator.
Copyright (C) 2021, Uri Shaked.
Released under the MIT license.
*/
#include <avr/io.h>
#include "TinyDebug.h"
#define TDDR _SFR_IO8(0x1A)
#define TDCR _SFR_IO8(0x1B)
#define TDEN 1
#define TDPEEK 2
TinyDebug Debug;
void TinyDebug::begin() {
TDCR |= TDEN;
}
size_t TinyDebug::write(uint8_t b)
{
TDDR = b;
return 1;
}
void TinyDebug::flush()
{
}
int TinyDebug::available()
{
return TDCR >> 4;
}
int TinyDebug::peek() {
asm("cli");
TDCR |= TDPEEK;
int result = TDCR >> 4 ? TDDR : -1;
TDCR &= ~TDPEEK;
asm("sei");
return result;
}
int TinyDebug::read()
{
asm("cli");
int result = TDCR >> 4 ? TDDR : -1;
asm("sei");
return result;
}
/* Zero SRAM functions: */
void tdPrint(char *message) {
TDCR |= TDEN;
for (;*message;message++) {
TDDR = *message;
}
}
void tdPrint(const __FlashStringHelper *message) {
PGM_P p = reinterpret_cast<PGM_P>(message);
TDCR |= TDEN;
for (;pgm_read_byte(p); p++) {
TDDR = pgm_read_byte(p);
}
}
void tdPrintln(char *message) {
tdPrint(message);
TDDR = '\n';
}
void tdPrintln(const __FlashStringHelper *message) {
tdPrint(message);
TDDR = '\n';
}
| 1,218 | 570 |
// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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.
/**
* @file PubSubWriter.hpp
*
*/
#ifndef _TEST_PROFILING_PUBSUBWRITER_HPP_
#define _TEST_PROFILING_PUBSUBWRITER_HPP_
#include <fastrtps/fastrtps_fwd.h>
#include <fastrtps/Domain.h>
#include <fastrtps/participant/Participant.h>
#include <fastrtps/attributes/ParticipantAttributes.h>
#include <fastrtps/publisher/Publisher.h>
#include <fastrtps/publisher/PublisherListener.h>
#include <fastrtps/attributes/PublisherAttributes.h>
#include <string>
#include <list>
#include <condition_variable>
#include <boost/asio.hpp>
#include <boost/interprocess/detail/os_thread_functions.hpp>
template<class TypeSupport>
class PubSubWriter
{
class Listener : public eprosima::fastrtps::PublisherListener
{
public:
Listener(PubSubWriter &writer) : writer_(writer){};
~Listener(){};
void onPublicationMatched(eprosima::fastrtps::Publisher* /*pub*/, MatchingInfo &info)
{
if (info.status == MATCHED_MATCHING)
writer_.matched();
else
writer_.unmatched();
}
private:
Listener& operator=(const Listener&) NON_COPYABLE_CXX11;
PubSubWriter &writer_;
} listener_;
public:
typedef TypeSupport type_support;
typedef typename type_support::type type;
PubSubWriter(const std::string &topic_name) : listener_(*this), participant_(nullptr),
publisher_(nullptr), topic_name_(topic_name), initialized_(false), matched_(0)
{
publisher_attr_.topic.topicDataType = type_.getName();
// Generate topic name
std::ostringstream t;
t << topic_name_ << "_" << boost::asio::ip::host_name() << "_" << boost::interprocess::ipcdetail::get_current_process_id();
publisher_attr_.topic.topicName = t.str();
}
~PubSubWriter()
{
if(participant_ != nullptr)
eprosima::fastrtps::Domain::removeParticipant(participant_);
}
void init()
{
//Create participant
eprosima::fastrtps::ParticipantAttributes pattr;
pattr.rtps.builtin.domainId = (uint32_t)boost::interprocess::ipcdetail::get_current_process_id() % 230;
participant_ = eprosima::fastrtps::Domain::createParticipant(pattr);
if(participant_ != nullptr)
{
// Register type
eprosima::fastrtps::Domain::registerType(participant_, &type_);
//Create publisher
publisher_ = eprosima::fastrtps::Domain::createPublisher(participant_, publisher_attr_, &listener_);
if(publisher_ != nullptr)
{
initialized_ = true;
return;
}
eprosima::fastrtps::Domain::removeParticipant(participant_);
}
}
bool isInitialized() const { return initialized_; }
void destroy()
{
if(participant_ != nullptr)
{
eprosima::fastrtps::Domain::removeParticipant(participant_);
participant_ = nullptr;
}
}
void send(std::list<type>& msgs)
{
auto it = msgs.begin();
while(it != msgs.end())
{
if(publisher_->write((void*)&(*it)))
{
it = msgs.erase(it);
}
else
break;
}
}
void waitDiscovery()
{
std::cout << "Writer waiting for discovery..." << std::endl;
std::unique_lock<std::mutex> lock(mutex_);
if(matched_ == 0)
cv_.wait_for(lock, std::chrono::seconds(10));
std::cout << "Writer discovery phase finished" << std::endl;
}
void waitRemoval()
{
std::unique_lock<std::mutex> lock(mutex_);
if(matched_ != 0)
cv_.wait_for(lock, std::chrono::seconds(10));
}
bool waitForAllAcked(const std::chrono::seconds& max_wait)
{
return publisher_->wait_for_all_acked(Time_t((int32_t)max_wait.count(), 0));
}
/*** Function to change QoS ***/
PubSubWriter& reliability(const eprosima::fastrtps::ReliabilityQosPolicyKind kind)
{
publisher_attr_.qos.m_reliability.kind = kind;
return *this;
}
PubSubWriter& asynchronously(const eprosima::fastrtps::PublishModeQosPolicyKind kind)
{
publisher_attr_.qos.m_publishMode.kind = kind;
return *this;
}
PubSubWriter& history_kind(const eprosima::fastrtps::HistoryQosPolicyKind kind)
{
publisher_attr_.topic.historyQos.kind = kind;
return *this;
}
PubSubWriter& history_depth(const int32_t depth)
{
publisher_attr_.topic.historyQos.depth = depth;
return *this;
}
PubSubWriter& durability_kind(const eprosima::fastrtps::DurabilityQosPolicyKind kind)
{
publisher_attr_.qos.m_durability.kind = kind;
return *this;
}
PubSubWriter& resource_limits_max_samples(const int32_t max)
{
publisher_attr_.topic.resourceLimitsQos.max_samples = max;
return *this;
}
PubSubWriter& heartbeat_period_seconds(int32_t sec)
{
publisher_attr_.times.heartbeatPeriod.seconds = sec;
return *this;
}
PubSubWriter& heartbeat_period_fraction(uint32_t frac)
{
publisher_attr_.times.heartbeatPeriod.fraction = frac;
return *this;
}
private:
void matched()
{
std::unique_lock<std::mutex> lock(mutex_);
++matched_;
cv_.notify_one();
}
void unmatched()
{
std::unique_lock<std::mutex> lock(mutex_);
--matched_;
cv_.notify_one();
}
PubSubWriter& operator=(const PubSubWriter&)NON_COPYABLE_CXX11;
eprosima::fastrtps::Participant *participant_;
eprosima::fastrtps::PublisherAttributes publisher_attr_;
eprosima::fastrtps::Publisher *publisher_;
std::string topic_name_;
bool initialized_;
std::mutex mutex_;
std::condition_variable cv_;
unsigned int matched_;
type_support type_;
};
#endif // _TEST_PROFILING_PUBSUBWRITER_HPP_
| 6,714 | 2,218 |
#ifndef PARSE_HPP
#define PARSE_HPP
#include "class.hpp"
#include <fstream>
#include <map>
#include <optional>
#include <string>
#include <utility>
std::optional<ClassMap> get_classes(const std::string &filename, bool pedantic);
#endif
| 240 | 91 |
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#include "easinggraph.h"
#include <QPainter>
#include <QStyleOptionGraphicsItem>
#include <math.h>
QT_BEGIN_NAMESPACE
EasingGraph::EasingGraph(QWidget *parent):QWidget(parent),
m_color(Qt::magenta), m_zeroColor(Qt::gray),m_duration(0),
m_easingExtremes(QLatin1String("In"))
{
// setFlag(QGraphicsItem::ItemHasNoContents, false);
// populate the hash
m_availableNames.insert(QLatin1String("Linear"), QEasingCurve::Linear);
m_availableNames.insert(QLatin1String("InQuad"), QEasingCurve::InQuad);
m_availableNames.insert(QLatin1String("OutQuad"), QEasingCurve::OutQuad);
m_availableNames.insert(QLatin1String("InOutQuad"), QEasingCurve::InOutQuad);
m_availableNames.insert(QLatin1String("OutInQuad"), QEasingCurve::OutInQuad);
m_availableNames.insert(QLatin1String("InCubic"), QEasingCurve::InCubic);
m_availableNames.insert(QLatin1String("OutCubic"), QEasingCurve::OutCubic);
m_availableNames.insert(QLatin1String("InOutCubic"), QEasingCurve::InOutCubic);
m_availableNames.insert(QLatin1String("OutInCubic"), QEasingCurve::OutInCubic);
m_availableNames.insert(QLatin1String("InQuart"), QEasingCurve::InQuart);
m_availableNames.insert(QLatin1String("OutQuart"), QEasingCurve::OutQuart);
m_availableNames.insert(QLatin1String("InOutQuart"), QEasingCurve::InOutQuart);
m_availableNames.insert(QLatin1String("OutInQuart"), QEasingCurve::OutInQuart);
m_availableNames.insert(QLatin1String("InQuint"), QEasingCurve::InQuint);
m_availableNames.insert(QLatin1String("OutQuint"), QEasingCurve::OutQuint);
m_availableNames.insert(QLatin1String("InOutQuint"), QEasingCurve::InOutQuint);
m_availableNames.insert(QLatin1String("OutInQuint"), QEasingCurve::OutInQuint);
m_availableNames.insert(QLatin1String("InSine"), QEasingCurve::InSine);
m_availableNames.insert(QLatin1String("OutSine"), QEasingCurve::OutSine);
m_availableNames.insert(QLatin1String("InOutSine"), QEasingCurve::InOutSine);
m_availableNames.insert(QLatin1String("OutInSine"), QEasingCurve::OutInSine);
m_availableNames.insert(QLatin1String("InExpo"), QEasingCurve::InExpo);
m_availableNames.insert(QLatin1String("OutExpo"), QEasingCurve::OutExpo);
m_availableNames.insert(QLatin1String("InOutExpo"), QEasingCurve::InOutExpo);
m_availableNames.insert(QLatin1String("OutInExpo"), QEasingCurve::OutInExpo);
m_availableNames.insert(QLatin1String("InCirc"), QEasingCurve::InCirc);
m_availableNames.insert(QLatin1String("OutCirc"), QEasingCurve::OutCirc);
m_availableNames.insert(QLatin1String("InOutCirc"), QEasingCurve::InOutCirc);
m_availableNames.insert(QLatin1String("OutInCirc"), QEasingCurve::OutInCirc);
m_availableNames.insert(QLatin1String("InElastic"), QEasingCurve::InElastic);
m_availableNames.insert(QLatin1String("OutElastic"), QEasingCurve::OutElastic);
m_availableNames.insert(QLatin1String("InOutElastic"), QEasingCurve::InOutElastic);
m_availableNames.insert(QLatin1String("OutInElastic"), QEasingCurve::OutInElastic);
m_availableNames.insert(QLatin1String("InBack"), QEasingCurve::InBack);
m_availableNames.insert(QLatin1String("OutBack"), QEasingCurve::OutBack);
m_availableNames.insert(QLatin1String("InOutBack"), QEasingCurve::InOutBack);
m_availableNames.insert(QLatin1String("OutInBack"), QEasingCurve::OutInBack);
m_availableNames.insert(QLatin1String("InBounce"), QEasingCurve::InBounce);
m_availableNames.insert(QLatin1String("OutBounce"), QEasingCurve::OutBounce);
m_availableNames.insert(QLatin1String("InOutBounce"), QEasingCurve::InOutBounce);
m_availableNames.insert(QLatin1String("OutInBounce"), QEasingCurve::OutInBounce);
m_availableNames.insert(QLatin1String("InCurve"), QEasingCurve::InCurve);
m_availableNames.insert(QLatin1String("OutCurve"), QEasingCurve::OutCurve);
m_availableNames.insert(QLatin1String("SineCurve"), QEasingCurve::SineCurve);
m_availableNames.insert(QLatin1String("CosineCurve"), QEasingCurve::CosineCurve);
}
EasingGraph::~EasingGraph()
{
}
QEasingCurve::Type EasingGraph::easingType() const
{
return m_curveFunction.type();
}
QEasingCurve EasingGraph::easingCurve() const
{
return m_curveFunction;
}
QString EasingGraph::easingShape() const
{
QString name = easingName();
if (name.left(5)==QLatin1String("InOut")) return name.right(name.length()-5);
if (name.left(5)==QLatin1String("OutIn")) return name.right(name.length()-5);
if (name.left(3)==QLatin1String("Out")) return name.right(name.length()-3);
if (name.left(2)==QLatin1String("In")) return name.right(name.length()-2);
return name;
}
void EasingGraph::setEasingShape(const QString &newShape)
{
if (easingShape() != newShape) {
if (newShape==QLatin1String("Linear"))
setEasingName(newShape);
else
setEasingName(m_easingExtremes+newShape);
}
}
QString EasingGraph::easingExtremes() const
{
QString name = easingName();
if (name.left(5)==QLatin1String("InOut")) return QLatin1String("InOut");
if (name.left(5)==QLatin1String("OutIn")) return QLatin1String("OutIn");
if (name.left(3)==QLatin1String("Out")) return QLatin1String("Out");
if (name.left(2)==QLatin1String("In")) return QLatin1String("In");
return QString();
}
void EasingGraph::setEasingExtremes(const QString &newExtremes)
{
if (m_easingExtremes != newExtremes) {
m_easingExtremes = newExtremes;
if (easingShape()!=QLatin1String("Linear"))
setEasingName(newExtremes+easingShape());
}
}
QString EasingGraph::easingName() const
{
return m_availableNames.key(m_curveFunction.type());
}
void EasingGraph::setEasingName(const QString &newName)
{
if (easingName() != newName) {
if (!m_availableNames.contains(newName)) return;
m_curveFunction = QEasingCurve(m_availableNames.value(newName));
emit easingNameChanged();
emit easingExtremesChanged();
emit easingShapeChanged();
update();
}
}
qreal EasingGraph::overshoot() const
{
return m_curveFunction.overshoot();
}
void EasingGraph::setOvershoot(qreal newOvershoot)
{
if ((overshoot() != newOvershoot) && (easingShape()==QLatin1String("Back"))) {
m_curveFunction.setOvershoot(newOvershoot);
emit overshootChanged();
update();
}
}
qreal EasingGraph::amplitude() const
{
return m_curveFunction.amplitude();
}
void EasingGraph::setAmplitude(qreal newAmplitude)
{
if ((amplitude() != newAmplitude) && ((easingShape()==QLatin1String("Bounce")) ||(easingShape()==QLatin1String("Elastic")))) {
m_curveFunction.setAmplitude(newAmplitude);
emit amplitudeChanged();
update();
}
}
qreal EasingGraph::period() const
{
return m_curveFunction.period();
}
void EasingGraph::setPeriod(qreal newPeriod)
{
if ((period() != newPeriod) && (easingShape()==QLatin1String("Elastic"))) {
m_curveFunction.setPeriod(newPeriod);
emit periodChanged();
update();
}
}
qreal EasingGraph::duration() const
{
return m_duration;
}
void EasingGraph::setDuration(qreal newDuration)
{
if (m_duration != newDuration) {
m_duration = newDuration;
emit durationChanged();
}
}
QColor EasingGraph::color() const
{
return m_color;
}
void EasingGraph::setColor(const QColor &newColor)
{
if (m_color != newColor) {
m_color = newColor;
emit colorChanged();
update();
}
}
QColor EasingGraph::zeroColor() const{
return m_zeroColor;
}
void EasingGraph::setZeroColor(const QColor &newColor)
{
if (m_zeroColor != newColor) {
m_zeroColor = newColor;
emit zeroColorChanged();
update();
}
}
QRectF EasingGraph::boundingRect() const
{
return QRectF(0, 0, width(), height());
}
void EasingGraph::paintEvent(QPaintEvent *event)
//void EasingGraph::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *)
{
QWidget::paintEvent(event);
QPainter *painter = new QPainter(this);
painter->save();
bool drawZero = false;
// no background
int length = width();
int breadth = height()-2;
QPainterPath path;
path.moveTo(0,int((1-m_curveFunction.valueForProgress(0))*breadth));
for (int i=0;i<length;i++) {
qreal progress = i/qreal(length);
qreal value = m_curveFunction.valueForProgress(progress);
int x = int(length*progress);
int y = int(breadth*(1-value));
path.lineTo(x,y);
}
QRectF pathRect = path.controlPointRect();
if ( (pathRect.height()>breadth)) {
// scale vertically
qreal scale = breadth/pathRect.height();
qreal displacement = -pathRect.top();
// reset path and recompute scaled version
path = QPainterPath();
path.moveTo(0,int(scale*((1-m_curveFunction.valueForProgress(0))*breadth+displacement)));
for (int i=0;i<length;i++) {
qreal progress = i/qreal(length);
qreal value = m_curveFunction.valueForProgress(progress);
int x = int(length*progress);
int y = int(scale*(breadth*(1-value)+displacement));
path.lineTo(x,y);
}
drawZero = true;
}
painter->setBrush(Qt::transparent);
if (drawZero) {
// "zero" and "one" lines
QPen zeroPen = QPen(m_zeroColor);
zeroPen.setStyle(Qt::DashLine);
painter->setPen(zeroPen);
int y = int(-pathRect.top()*breadth/pathRect.height());
if (y>0)
painter->drawLine(0,y,length,y);
y = int(breadth/pathRect.height()*(breadth-pathRect.top()));
if (y<breadth)
painter->drawLine(0,y,length,y);
}
painter->setPen(m_color);
painter->drawPath(path);
painter->restore();
delete painter;
}
QT_END_NAMESPACE
| 11,046 | 3,742 |
// Copyright (c) 2021 LibreSprite Authors (cf. AUTHORS.md)
// This file is released under the terms of the MIT license.
// Read LICENSE.txt for more information.
#pragma once
#include <memory>
#include <variant>
#include <common/Color.hpp>
#include <common/Rect.hpp>
#include <common/types.hpp>
#include <gui/Texture.hpp>
class Surface : public std::enable_shared_from_this<Surface> {
public:
using PixelType = U32;
private:
U32 _width = 0, _height = 0;
Vector<PixelType> pixels;
std::unique_ptr<TextureInfo> _textureInfo;
public:
U32 width() const {return _width;}
U32 height() const {return _height;}
Rect rect() const {return {0, 0, _width, _height};}
PixelType* data() {return pixels.data();}
U32 dataSize() {return _width * _height * sizeof(PixelType);};
const Vector<PixelType>& getPixels() {return pixels;}
std::shared_ptr<Surface> clone();
TextureInfo& info();
void resize(U32 width, U32 height);
void setDirty(const Rect& region);
void setPixels(const Vector<PixelType>& read);
Color getPixel(U32 x, U32 y) {
U32 index = x + y * _width;
return (index >= _width * _height) ? Color{} : getColor(pixels[index]);
}
PixelType getPixelUnsafe(U32 x, U32 y) {
return pixels[x + y * _width];
}
void setPixelUnsafe(U32 x, U32 y, PixelType pixel) {
U32 index = x + y * _width;
pixels[index] = pixel;
setDirty({S32(x), S32(y), 1, 1});
}
void setHLine(S32 x, S32 y, S32 w, PixelType pixel);
void antsHLine(S32 x, S32 y, S32 w, U32 age, PixelType A, PixelType B);
void setVLine(S32 x, S32 y, S32 h, PixelType pixel);
void antsVLine(S32 x, S32 y, S32 h, U32 age, PixelType A, PixelType B);
void fillRect(const Rect& rect, PixelType pixel);
void setPixel(U32 x, U32 y, PixelType pixel);
void setPixel(U32 x, U32 y, const Color& color) {
setPixel(x, y, color.toU32());
}
Color getColor(PixelType pixel) {
return pixel;
}
Surface& operator = (const Surface& other) {
_width = other._width;
_height = other._height;
pixels = other.pixels;
setDirty(rect());
return *this;
}
};
| 2,216 | 834 |
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include <jni.h>
#include "CallbackStore.h"
#include "edu_wpi_first_hal_simulation_CTREPCMDataJNI.h"
#include "hal/simulation/CTREPCMData.h"
using namespace hal;
extern "C" {
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: registerInitializedCallback
* Signature: (ILjava/lang/Object;Z)I
*/
JNIEXPORT jint JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_registerInitializedCallback
(JNIEnv* env, jclass, jint index, jobject callback, jboolean initialNotify)
{
return sim::AllocateCallback(env, index, callback, initialNotify,
&HALSIM_RegisterCTREPCMInitializedCallback);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: cancelInitializedCallback
* Signature: (II)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_cancelInitializedCallback
(JNIEnv* env, jclass, jint index, jint handle)
{
return sim::FreeCallback(env, handle, index,
&HALSIM_CancelCTREPCMInitializedCallback);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: getInitialized
* Signature: (I)Z
*/
JNIEXPORT jboolean JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_getInitialized
(JNIEnv*, jclass, jint index)
{
return HALSIM_GetCTREPCMInitialized(index);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: setInitialized
* Signature: (IZ)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_setInitialized
(JNIEnv*, jclass, jint index, jboolean value)
{
HALSIM_SetCTREPCMInitialized(index, value);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: registerSolenoidOutputCallback
* Signature: (IILjava/lang/Object;Z)I
*/
JNIEXPORT jint JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_registerSolenoidOutputCallback
(JNIEnv* env, jclass, jint index, jint channel, jobject callback,
jboolean initialNotify)
{
return sim::AllocateChannelCallback(
env, index, channel, callback, initialNotify,
&HALSIM_RegisterCTREPCMSolenoidOutputCallback);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: cancelSolenoidOutputCallback
* Signature: (III)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_cancelSolenoidOutputCallback
(JNIEnv* env, jclass, jint index, jint channel, jint handle)
{
return sim::FreeChannelCallback(env, handle, index, channel,
&HALSIM_CancelCTREPCMSolenoidOutputCallback);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: getSolenoidOutput
* Signature: (II)Z
*/
JNIEXPORT jboolean JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_getSolenoidOutput
(JNIEnv*, jclass, jint index, jint channel)
{
return HALSIM_GetCTREPCMSolenoidOutput(index, channel);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: setSolenoidOutput
* Signature: (IIZ)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_setSolenoidOutput
(JNIEnv*, jclass, jint index, jint channel, jboolean value)
{
HALSIM_SetCTREPCMSolenoidOutput(index, channel, value);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: registerCompressorOnCallback
* Signature: (ILjava/lang/Object;Z)I
*/
JNIEXPORT jint JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_registerCompressorOnCallback
(JNIEnv* env, jclass, jint index, jobject callback, jboolean initialNotify)
{
return sim::AllocateCallback(env, index, callback, initialNotify,
&HALSIM_RegisterCTREPCMCompressorOnCallback);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: cancelCompressorOnCallback
* Signature: (II)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_cancelCompressorOnCallback
(JNIEnv* env, jclass, jint index, jint handle)
{
return sim::FreeCallback(env, handle, index,
&HALSIM_CancelCTREPCMCompressorOnCallback);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: getCompressorOn
* Signature: (I)Z
*/
JNIEXPORT jboolean JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_getCompressorOn
(JNIEnv*, jclass, jint index)
{
return HALSIM_GetCTREPCMCompressorOn(index);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: setCompressorOn
* Signature: (IZ)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_setCompressorOn
(JNIEnv*, jclass, jint index, jboolean value)
{
HALSIM_SetCTREPCMCompressorOn(index, value);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: registerClosedLoopEnabledCallback
* Signature: (ILjava/lang/Object;Z)I
*/
JNIEXPORT jint JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_registerClosedLoopEnabledCallback
(JNIEnv* env, jclass, jint index, jobject callback, jboolean initialNotify)
{
return sim::AllocateCallback(
env, index, callback, initialNotify,
&HALSIM_RegisterCTREPCMClosedLoopEnabledCallback);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: cancelClosedLoopEnabledCallback
* Signature: (II)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_cancelClosedLoopEnabledCallback
(JNIEnv* env, jclass, jint index, jint handle)
{
return sim::FreeCallback(env, handle, index,
&HALSIM_CancelCTREPCMClosedLoopEnabledCallback);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: getClosedLoopEnabled
* Signature: (I)Z
*/
JNIEXPORT jboolean JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_getClosedLoopEnabled
(JNIEnv*, jclass, jint index)
{
return HALSIM_GetCTREPCMClosedLoopEnabled(index);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: setClosedLoopEnabled
* Signature: (IZ)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_setClosedLoopEnabled
(JNIEnv*, jclass, jint index, jboolean value)
{
HALSIM_SetCTREPCMClosedLoopEnabled(index, value);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: registerPressureSwitchCallback
* Signature: (ILjava/lang/Object;Z)I
*/
JNIEXPORT jint JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_registerPressureSwitchCallback
(JNIEnv* env, jclass, jint index, jobject callback, jboolean initialNotify)
{
return sim::AllocateCallback(env, index, callback, initialNotify,
&HALSIM_RegisterCTREPCMPressureSwitchCallback);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: cancelPressureSwitchCallback
* Signature: (II)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_cancelPressureSwitchCallback
(JNIEnv* env, jclass, jint index, jint handle)
{
return sim::FreeCallback(env, handle, index,
&HALSIM_CancelCTREPCMPressureSwitchCallback);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: getPressureSwitch
* Signature: (I)Z
*/
JNIEXPORT jboolean JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_getPressureSwitch
(JNIEnv*, jclass, jint index)
{
return HALSIM_GetCTREPCMPressureSwitch(index);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: setPressureSwitch
* Signature: (IZ)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_setPressureSwitch
(JNIEnv*, jclass, jint index, jboolean value)
{
HALSIM_SetCTREPCMPressureSwitch(index, value);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: registerCompressorCurrentCallback
* Signature: (ILjava/lang/Object;Z)I
*/
JNIEXPORT jint JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_registerCompressorCurrentCallback
(JNIEnv* env, jclass, jint index, jobject callback, jboolean initialNotify)
{
return sim::AllocateCallback(
env, index, callback, initialNotify,
&HALSIM_RegisterCTREPCMCompressorCurrentCallback);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: cancelCompressorCurrentCallback
* Signature: (II)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_cancelCompressorCurrentCallback
(JNIEnv* env, jclass, jint index, jint handle)
{
return sim::FreeCallback(env, handle, index,
&HALSIM_CancelCTREPCMCompressorCurrentCallback);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: getCompressorCurrent
* Signature: (I)D
*/
JNIEXPORT jdouble JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_getCompressorCurrent
(JNIEnv*, jclass, jint index)
{
return HALSIM_GetCTREPCMCompressorCurrent(index);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: setCompressorCurrent
* Signature: (ID)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_setCompressorCurrent
(JNIEnv*, jclass, jint index, jdouble value)
{
HALSIM_SetCTREPCMCompressorCurrent(index, value);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: registerAllNonSolenoidCallbacks
* Signature: (ILjava/lang/Object;Z)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_registerAllNonSolenoidCallbacks
(JNIEnv* env, jclass, jint index, jobject callback, jboolean initialNotify)
{
sim::AllocateCallback(
env, index, callback, initialNotify,
[](int32_t index, HAL_NotifyCallback cb, void* param, HAL_Bool in) {
HALSIM_RegisterCTREPCMAllNonSolenoidCallbacks(index, cb, param, in);
return 0;
});
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: registerAllSolenoidCallbacks
* Signature: (IILjava/lang/Object;Z)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_registerAllSolenoidCallbacks
(JNIEnv* env, jclass, jint index, jint channel, jobject callback,
jboolean initialNotify)
{
sim::AllocateChannelCallback(
env, index, channel, callback, initialNotify,
[](int32_t index, int32_t channel, HAL_NotifyCallback cb, void* param,
HAL_Bool in) {
HALSIM_RegisterCTREPCMAllSolenoidCallbacks(index, channel, cb, param,
in);
return 0;
});
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: resetData
* Signature: (I)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_resetData
(JNIEnv*, jclass, jint index)
{
HALSIM_ResetCTREPCMData(index);
}
} // extern "C"
| 10,946 | 4,129 |
/*! \file cmsSwap.hpp
\brief Cms Swap
Peter Caspers
*/
#include <ql/quantlib.hpp>
#include <CmsPricer.hpp>
#ifndef quantlib_cmsSwap_hpp
#define quantlib_cmsSwap_hpp
using namespace boost;
using namespace std;
namespace QuantLib {
/*! cms swap */
class CmsSwap {
public:
/*! construct cms swap
for the structured leg the curve in the cms pricer is used as estimation and discount curve
for the float leg the estimation curve is the curve of the floatIndex
the discount curve for the float leg must be specified separately */
CmsSwap(boost::shared_ptr<Schedule> fixingSchedule,
boost::shared_ptr<Schedule> paymentSchedule,
boost::shared_ptr<Schedule> calculationSchedule,
boost::shared_ptr<SwapIndex> swapIndex,
DayCounter couponDayCounter,
boost::shared_ptr<Schedule> floatLegFixingSchedule,
boost::shared_ptr<Schedule> floatLegPaymentSchedule,
boost::shared_ptr<Schedule> floatLegCalculationSchedule,
boost::shared_ptr<IborIndex> floatIndex,
DayCounter floatLegCouponDayCounter,
boost::shared_ptr<YieldTermStructure> floatDiscountCurve
);
CmsSwap(boost::shared_ptr<Schedule> calculationSchedule,
int fixingDays,
boost::shared_ptr<SwapIndex> swapIndex,
DayCounter couponDayCounter,
boost::shared_ptr<Schedule> floatLegCalculationSchedule,
int floatFixingDays,
boost::shared_ptr<IborIndex> iborIndex,
DayCounter floatLegCouponDayCounter,
boost::shared_ptr<YieldTermStructure> floatDiscountCurve,
double strike=0.0000,
int flavour=1);
/*! return schedules */
std::vector<Date> fixingSchedule();
std::vector<Date> paymentSchedule();
std::vector<Date> calculationSchedule();
/*! return cms rates
adjusted = false => forward swap rates
adjusted = true => convexity adjusted forward swap rates */
std::vector<double> rates(bool adjusted);
/*! return upper bound of hedge portfolio */
std::vector<double> upperBounds();
/*! set cap floor payoff
flavour = 1 cap, -1 floor
strike of cap or floor */
bool setCapPayoff(double strike, int flavour) {
strike_=strike;
flavour_=flavour;
return true;
}
/*! set margin this is added _after_ flooring / capping (!) to structured leg */
bool setMargin(double margin) {
margin_=margin;
return true;
}
/*! npv of structured leg
precomputedSwaplets is the number of already computed swaplet prices
precomputedPrice is the price of the precomputed swaplets
swapletUppterBound is the index of the first swaplet that will not be computed (if 0 all swaplets will be computed) */
Real npv(boost::shared_ptr<CmsPricer> pricer,int precomputedSwaplets=0,double precomputedPrice=0.0,int swapletUpperBound=0);
/*! total npv of swap (pay structured leg, receive float leg with flat margin) */
Real CmsSwap::totalNpv(boost::shared_ptr<CmsPricer> pricer);
/*! get implied margin for cms swap
if number of swaplets is given, only implied margin of this part is returned (but including precomputed swaplets)
precomputed floatlets and floatlets upper bound refer to the float leg of the swap
they must be given, because the frequency of this leg can be different
if the latter two numbers are zero they are set to the corresponding values of the cms leg */
Real margin(boost::shared_ptr<CmsPricer> pricer, int precomputedSwaplets=0, double precomputedMargin=0.0, int swapletUpperBound=0, int precomputedFloatlets=0, int floatletUpperBound=0);
private:
vector<Date> fixings_,payments_,calc_;
vector<Date> floatFixings_,floatPayments_,floatCalc_;
vector<double> rates_,adjustedRates_,upperBound_;
boost::shared_ptr<SwapIndex> swapIndex_;
boost::shared_ptr<IborIndex> floatIndex_;
DayCounter couponDayCounter_,floatLegCouponDayCounter_;
double strike_,margin_;
int flavour_;
boost::shared_ptr<YieldTermStructure> floatDiscountCurve_;
};
}
#endif
| 3,965 | 1,448 |
#include "../include/NeuralNetwork.hpp"
void NeuralNetwork::printToConsole()
{
for(int i = 0; i < this->layers.size(); i++)
{
if(i == 0) {
Matrix *m = this->layers.at(i)->matrixifyVals();
m->printToConsole();
}
else {
Matrix *m = this->layers.at(i)->matrixifyActivatedVals();
m->printToConsole();
}
}
}
void NeuralNetwork::setCurrentInput(vector<double> input)
{
this->input = input;
for(int i = 0; i < input.size(); i++) {
this->layers.at(0)->setVal(i, input.at(i));
}
this->layers.at(0);
}
NeuralNetwork::NeuralNetwork(vector<int> topology) {
this->topology = topology;
this->topologySize = topology.size();
for(int i = 0; i < topology.size(); i++)
{
Layer *l = new Layer(topology.at(i));
this->layers.push_back(l);
}
for(int i = 0; i < (topologySize - 1); i++)
{
Matrix *m = new Matrix(topology.at(i), topology.at(i + 1), true);
this->weightMatrices.push_back(m);
}
} | 1,056 | 379 |
#pragma once
#include "mruby.h"
void append_shapes_pixel(mrb_state*);
| 72 | 32 |
//===- MipsEmulation.cpp --------------------------------------------------===//
//
// The MCLinker Project
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Mips.h"
#include "mcld/LinkerScript.h"
#include "mcld/LinkerConfig.h"
#include "mcld/Support/TargetRegistry.h"
#include "mcld/Target/ELFEmulation.h"
namespace mcld {
static bool MCLDEmulateMipsELF(LinkerScript& pScript, LinkerConfig& pConfig) {
if (!MCLDEmulateELF(pScript, pConfig))
return false;
// set up bitclass and endian
pConfig.targets().setEndian(TargetOptions::Little);
llvm::Triple::ArchType arch = pConfig.targets().triple().getArch();
assert(arch == llvm::Triple::mipsel || arch == llvm::Triple::mips64el);
unsigned bitclass = arch == llvm::Triple::mipsel ? 32 : 64;
pConfig.targets().setBitClass(bitclass);
// set up target-dependent constraints of attributes
pConfig.attribute().constraint().enableWholeArchive();
pConfig.attribute().constraint().enableAsNeeded();
pConfig.attribute().constraint().setSharedSystem();
// set up the predefined attributes
pConfig.attribute().predefined().unsetWholeArchive();
pConfig.attribute().predefined().unsetAsNeeded();
pConfig.attribute().predefined().setDynamic();
return true;
}
//===----------------------------------------------------------------------===//
// emulateMipsLD - the help function to emulate Mips ld
//===----------------------------------------------------------------------===//
bool emulateMipsLD(LinkerScript& pScript, LinkerConfig& pConfig) {
if (pConfig.targets().triple().isOSDarwin()) {
assert(0 && "MachO linker has not supported yet");
return false;
}
if (pConfig.targets().triple().isOSWindows()) {
assert(0 && "COFF linker has not supported yet");
return false;
}
return MCLDEmulateMipsELF(pScript, pConfig);
}
} // namespace mcld
//===----------------------------------------------------------------------===//
// MipsEmulation
//===----------------------------------------------------------------------===//
extern "C" void MCLDInitializeMipsEmulation() {
mcld::TargetRegistry::RegisterEmulation(mcld::TheMipselTarget,
mcld::emulateMipsLD);
mcld::TargetRegistry::RegisterEmulation(mcld::TheMips64elTarget,
mcld::emulateMipsLD);
}
| 2,515 | 737 |
#include <iostream>
typedef float Real;
int main( )
{
int x=0;
#pragma skel loop iterate atleast(10)
for (int i=0; x < 100 ; i++) {
x = i + 1;
if (x % 2)
x += 5;
}
int j;
#pragma skel loop iterate atmost(30)
for (j=0; x < 100 ; j++) {
x = j + 1;
}
return x;
}
| 303 | 153 |
#include <iostream>
using namespace std;
int main(){
int a = 2;
int b = 6;
bool hasil;
// Operator NOT
cout << "Operator NOT : \n";
hasil = !(a == b);
cout << hasil << endl;
cout << endl;
// Operator AND
cout << "Operator AND : \n";
hasil = (a == 2) && (b == 6); // Benar dan Benar
cout << hasil << endl;
hasil = (a == 2) && (b == 5); // Benar dan Salah
cout << hasil << endl;
hasil = (a == 1) and (b == 5); // Salah dan Salah
cout << hasil << endl;
hasil = (a == 1) and (b == 6); // Salah dan Benar
cout << hasil << endl;
cout << endl;
// Operator OR
cout << "Operator OR : \n";
hasil = (a == 2) || (b == 6); // Benar dan Benar
cout << hasil << endl;
hasil = (a == 2) || (b == 5); // Benar dan Salah
cout << hasil << endl;
hasil = (a == 1) or (b == 5); // Salah dan Salah
cout << hasil << endl;
hasil = (a == 1) or (b == 6); // Salah dan Benar
cout << hasil << endl;
return 0;
} | 1,008 | 401 |
/*****************************************************************************
*
* demo program - part of CLIPP (command line interfaces for modern C++)
*
* released under MIT license
*
* (c) 2017-2018 André Müller; foss@andremueller-online.de
*
*****************************************************************************/
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
#include <clipp.h>
//-------------------------------------------------------------------
enum class mode {
none, train, validate, classify
};
struct settings {
mode selected = mode::none;
std::string imageFile;
std::string labelFile;
std::string modelFile = "out.mdl";
std::size_t batchSize = 128;
std::size_t threads = 0;
std::size_t inputLimit = 0;
std::vector<std::string> inputFiles;
};
//-------------------------------------------------------------------
settings configuration(int argc, char* argv[])
{
using namespace clipp;
settings s;
std::vector<std::string> unrecognized;
auto isfilename = clipp::match::prefix_not("-");
auto inputOptions = (
required("-i", "-I", "--img") & !value(isfilename, "image file", s.imageFile),
required("-l", "-L", "--lbl") & !value(isfilename, "label file", s.labelFile)
);
auto trainMode = (
command("train", "t", "T").set(s.selected,mode::train)
.if_conflicted([]{std::cerr << "conflicting modes\n"; }),
inputOptions,
(option("-n") & integer("limit", s.inputLimit))
% "limit number of input images",
(option("-o", "-O", "--out") & !value("model file", s.modelFile))
% "write model to specific file; default: 'out.mdl'",
(option("-b", "--batch-size") & integer("batch size", s.batchSize)),
(option("-p") & integer("threads", s.threads))
% "number of threads to use; default: optimum for machine"
);
auto validationMode = (
command("validate", "v", "V").set(s.selected,mode::validate),
!value(isfilename, "model", s.modelFile),
inputOptions
);
auto classificationMode = (
command("classify", "c", "C").set(s.selected,mode::classify),
!value(isfilename, "model", s.modelFile),
!values(isfilename, "images", s.inputFiles)
);
auto cli = (
trainMode | validationMode | classificationMode,
any_other(unrecognized)
);
auto res = parse(argc, argv, cli);
debug::print(std::cout, res);
if(!res || !unrecognized.empty()) {
std::string msg = "Wrong command line arguments!\n";
if(s.selected == mode::none) {
msg += "Please select a mode!\n";
}
else {
for(const auto& m : res.missing()) {
if(!m.param()->flags().empty()) {
msg += "Missing option: " + m.param()->flags().front() + '\n';
}
else if(!m.param()->label().empty()) {
msg += "Missing value: " + m.param()->label() + '\n';
}
}
for(const auto& arg : unrecognized) {
msg += "Argument not recognized: " + arg + '\n';
}
}
auto fmt = doc_formatting{}.first_column(8).doc_column(16);
//.max_flags_per_param_in_usage(3).surround_alternative_flags("(", ")");
msg += "\nUsage:\n" + usage_lines(cli, argv[0], fmt).str() + '\n';
msg += "\nOptions:\n" + documentation(cli, fmt).str() + '\n';
throw std::invalid_argument{msg};
}
return s;
}
//-------------------------------------------------------------------
int main(int argc, char* argv[])
{
try {
auto conf = configuration(argc, argv);
std::cout << "SUCCESS\n";
}
catch(std::exception& e) {
std::cerr << "ERROR: " << e.what() << '\n';
}
}
| 3,898 | 1,185 |
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/ecs/model/DescribeSecurityGroupsRequest.h>
using AlibabaCloud::Ecs::Model::DescribeSecurityGroupsRequest;
DescribeSecurityGroupsRequest::DescribeSecurityGroupsRequest() :
RpcServiceRequest("ecs", "2014-05-26", "DescribeSecurityGroups")
{
setMethod(HttpRequest::Method::Post);
}
DescribeSecurityGroupsRequest::~DescribeSecurityGroupsRequest()
{}
long DescribeSecurityGroupsRequest::getResourceOwnerId()const
{
return resourceOwnerId_;
}
void DescribeSecurityGroupsRequest::setResourceOwnerId(long resourceOwnerId)
{
resourceOwnerId_ = resourceOwnerId;
setParameter("ResourceOwnerId", std::to_string(resourceOwnerId));
}
bool DescribeSecurityGroupsRequest::getFuzzyQuery()const
{
return fuzzyQuery_;
}
void DescribeSecurityGroupsRequest::setFuzzyQuery(bool fuzzyQuery)
{
fuzzyQuery_ = fuzzyQuery;
setParameter("FuzzyQuery", fuzzyQuery ? "true" : "false");
}
std::string DescribeSecurityGroupsRequest::getSecurityGroupId()const
{
return securityGroupId_;
}
void DescribeSecurityGroupsRequest::setSecurityGroupId(const std::string& securityGroupId)
{
securityGroupId_ = securityGroupId;
setParameter("SecurityGroupId", securityGroupId);
}
bool DescribeSecurityGroupsRequest::getIsQueryEcsCount()const
{
return isQueryEcsCount_;
}
void DescribeSecurityGroupsRequest::setIsQueryEcsCount(bool isQueryEcsCount)
{
isQueryEcsCount_ = isQueryEcsCount;
setParameter("IsQueryEcsCount", isQueryEcsCount ? "true" : "false");
}
std::string DescribeSecurityGroupsRequest::getNetworkType()const
{
return networkType_;
}
void DescribeSecurityGroupsRequest::setNetworkType(const std::string& networkType)
{
networkType_ = networkType;
setParameter("NetworkType", networkType);
}
std::string DescribeSecurityGroupsRequest::getSecurityGroupName()const
{
return securityGroupName_;
}
void DescribeSecurityGroupsRequest::setSecurityGroupName(const std::string& securityGroupName)
{
securityGroupName_ = securityGroupName;
setParameter("SecurityGroupName", securityGroupName);
}
int DescribeSecurityGroupsRequest::getPageNumber()const
{
return pageNumber_;
}
void DescribeSecurityGroupsRequest::setPageNumber(int pageNumber)
{
pageNumber_ = pageNumber;
setParameter("PageNumber", std::to_string(pageNumber));
}
std::string DescribeSecurityGroupsRequest::getResourceGroupId()const
{
return resourceGroupId_;
}
void DescribeSecurityGroupsRequest::setResourceGroupId(const std::string& resourceGroupId)
{
resourceGroupId_ = resourceGroupId;
setParameter("ResourceGroupId", resourceGroupId);
}
std::string DescribeSecurityGroupsRequest::getRegionId()const
{
return regionId_;
}
void DescribeSecurityGroupsRequest::setRegionId(const std::string& regionId)
{
regionId_ = regionId;
setParameter("RegionId", regionId);
}
int DescribeSecurityGroupsRequest::getPageSize()const
{
return pageSize_;
}
void DescribeSecurityGroupsRequest::setPageSize(int pageSize)
{
pageSize_ = pageSize;
setParameter("PageSize", std::to_string(pageSize));
}
std::vector<DescribeSecurityGroupsRequest::Tag> DescribeSecurityGroupsRequest::getTag()const
{
return tag_;
}
void DescribeSecurityGroupsRequest::setTag(const std::vector<Tag>& tag)
{
tag_ = tag;
for(int dep1 = 0; dep1!= tag.size(); dep1++) {
auto tagObj = tag.at(dep1);
std::string tagObjStr = "Tag." + std::to_string(dep1 + 1);
setParameter(tagObjStr + ".Value", tagObj.value);
setParameter(tagObjStr + ".Key", tagObj.key);
}
}
bool DescribeSecurityGroupsRequest::getDryRun()const
{
return dryRun_;
}
void DescribeSecurityGroupsRequest::setDryRun(bool dryRun)
{
dryRun_ = dryRun;
setParameter("DryRun", dryRun ? "true" : "false");
}
std::string DescribeSecurityGroupsRequest::getResourceOwnerAccount()const
{
return resourceOwnerAccount_;
}
void DescribeSecurityGroupsRequest::setResourceOwnerAccount(const std::string& resourceOwnerAccount)
{
resourceOwnerAccount_ = resourceOwnerAccount;
setParameter("ResourceOwnerAccount", resourceOwnerAccount);
}
std::string DescribeSecurityGroupsRequest::getOwnerAccount()const
{
return ownerAccount_;
}
void DescribeSecurityGroupsRequest::setOwnerAccount(const std::string& ownerAccount)
{
ownerAccount_ = ownerAccount;
setParameter("OwnerAccount", ownerAccount);
}
long DescribeSecurityGroupsRequest::getOwnerId()const
{
return ownerId_;
}
void DescribeSecurityGroupsRequest::setOwnerId(long ownerId)
{
ownerId_ = ownerId;
setParameter("OwnerId", std::to_string(ownerId));
}
std::string DescribeSecurityGroupsRequest::getSecurityGroupIds()const
{
return securityGroupIds_;
}
void DescribeSecurityGroupsRequest::setSecurityGroupIds(const std::string& securityGroupIds)
{
securityGroupIds_ = securityGroupIds;
setParameter("SecurityGroupIds", securityGroupIds);
}
std::string DescribeSecurityGroupsRequest::getSecurityGroupType()const
{
return securityGroupType_;
}
void DescribeSecurityGroupsRequest::setSecurityGroupType(const std::string& securityGroupType)
{
securityGroupType_ = securityGroupType;
setParameter("SecurityGroupType", securityGroupType);
}
std::string DescribeSecurityGroupsRequest::getVpcId()const
{
return vpcId_;
}
void DescribeSecurityGroupsRequest::setVpcId(const std::string& vpcId)
{
vpcId_ = vpcId;
setParameter("VpcId", vpcId);
}
| 6,064 | 1,865 |
#pragma once
#include "../../Config/GpConfig.hpp"
#if defined(GP_USE_CONTAINERS)
#include "GpContainersT.hpp"
#include "../../Constexpr/GpConstexprIterator.hpp"
#include "../Pointers/GpRawPtr.hpp"
namespace GPlatform {
using GpBytesArray = GpVector<std::byte>;
class GpBytesArrayUtils
{
CLASS_REMOVE_CTRS_DEFAULT_MOVE_COPY(GpBytesArrayUtils)
public:
template<typename FROM, typename = std::enable_if_t<has_random_access_iter_v<FROM>, FROM>>
static GpBytesArray SMake (const FROM& aContainer)
{
GpBytesArray res;
const size_t size = aContainer.size();
res.resize(size);
MemOps::SCopy(res.data(),
reinterpret_cast<const std::byte*>(aContainer.data()),
count_t::SMake(size));
return res;
}
static GpBytesArray SMake (GpRawPtr<const std::byte*> aData)
{
GpBytesArray res;
res.resize(aData.CountLeft().As<size_t>());
GpRawPtr<std::byte*> resPtr(res);
resPtr.CopyFrom(aData);
return res;
}
};
}//GPlatform
#endif//#if defined(GP_USE_CONTAINERS)
| 1,173 | 421 |
/*=============================================================================
Copyright (c) 2011-2014 Bolero MURAKAMI
https://github.com/bolero-MURAKAMI/Sprout
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 SPROUT_TYPE_TRAITS_STD_TYPE_TRAITS_HPP
#define SPROUT_TYPE_TRAITS_STD_TYPE_TRAITS_HPP
#include <cstddef>
#include <type_traits>
#include <sprout/config.hpp>
#include <sprout/detail/predef.hpp>
#include <sprout/type_traits/detail/type_traits_wrapper.hpp>
#if !defined(_LIBCPP_VERSION) || (_LIBCPP_VERSION < 1101)
# include <sprout/tpp/algorithm/max_element.hpp>
#endif
namespace sprout {
// 20.10.4.1 Primary type categories
template<typename T>
struct is_void
: public sprout::detail::type_traits_wrapper<std::is_void<T> >
{};
template<typename T>
struct is_null_pointer
: public sprout::detail::type_traits_wrapper<std::is_same<typename std::remove_cv<T>::type, std::nullptr_t> >
{};
template<typename T>
struct is_integral
: public sprout::detail::type_traits_wrapper<std::is_integral<T> >
{};
template<typename T>
struct is_floating_point
: public sprout::detail::type_traits_wrapper<std::is_floating_point<T> >
{};
template<typename T>
struct is_array
: public sprout::detail::type_traits_wrapper<std::is_array<T> >
{};
template<typename T>
struct is_pointer
: public sprout::detail::type_traits_wrapper<std::is_pointer<T> >
{};
template<typename T>
struct is_lvalue_reference
: public sprout::detail::type_traits_wrapper<std::is_lvalue_reference<T> >
{};
template<typename T>
struct is_rvalue_reference
: public sprout::detail::type_traits_wrapper<std::is_rvalue_reference<T> >
{};
template<typename T>
struct is_member_object_pointer
: public sprout::detail::type_traits_wrapper<std::is_member_object_pointer<T> >
{};
template<typename T>
struct is_member_function_pointer
: public sprout::detail::type_traits_wrapper<std::is_member_function_pointer<T> >
{};
template<typename T>
struct is_enum
: public sprout::detail::type_traits_wrapper<std::is_enum<T> >
{};
template<typename T>
struct is_union
: public sprout::detail::type_traits_wrapper<std::is_union<T> >
{};
template<typename T>
struct is_class
: public sprout::detail::type_traits_wrapper<std::is_class<T> >
{};
template<typename T>
struct is_function
: public sprout::detail::type_traits_wrapper<std::is_function<T> >
{};
// 20.10.4.2 Composite type traits
template<typename T>
struct is_reference
: public sprout::detail::type_traits_wrapper<std::is_reference<T> >
{};
template<typename T>
struct is_arithmetic
: public sprout::detail::type_traits_wrapper<std::is_arithmetic<T> >
{};
template<typename T>
struct is_fundamental
: public sprout::detail::type_traits_wrapper<std::is_fundamental<T> >
{};
template<typename T>
struct is_object
: public sprout::detail::type_traits_wrapper<std::is_object<T> >
{};
template<typename T>
struct is_scalar
: public sprout::detail::type_traits_wrapper<std::is_scalar<T> >
{};
template<typename T>
struct is_compound
: public sprout::detail::type_traits_wrapper<std::is_compound<T> >
{};
template<typename T>
struct is_member_pointer
: public sprout::detail::type_traits_wrapper<std::is_member_pointer<T> >
{};
// 20.10.4.3 Type properties
template<typename T>
struct is_const
: public sprout::detail::type_traits_wrapper<std::is_const<T> >
{};
template<typename T>
struct is_volatile
: public sprout::detail::type_traits_wrapper<std::is_volatile<T> >
{};
template<typename T>
struct is_trivial
: public sprout::detail::type_traits_wrapper<std::is_trivial<T> >
{};
#if !defined(_LIBCPP_VERSION)
template<typename T>
struct is_trivially_copyable
: public sprout::is_scalar<typename std::remove_all_extents<T>::type>
{};
#else
template<typename T>
struct is_trivially_copyable
: public sprout::detail::type_traits_wrapper<std::is_trivially_copyable<T> >
{};
#endif
template<typename T>
struct is_standard_layout
: public sprout::detail::type_traits_wrapper<std::is_standard_layout<T> >
{};
template<typename T>
struct is_pod
: public sprout::detail::type_traits_wrapper<std::is_pod<T> >
{};
template<typename T>
struct is_literal_type
: public sprout::detail::type_traits_wrapper<std::is_literal_type<T> >
{};
template<typename T>
struct is_empty
: public sprout::detail::type_traits_wrapper<std::is_empty<T> >
{};
template<typename T>
struct is_polymorphic
: public sprout::detail::type_traits_wrapper<std::is_polymorphic<T> >
{};
template<typename T>
struct is_abstract
: public sprout::detail::type_traits_wrapper<std::is_abstract<T> >
{};
template<typename T>
struct is_signed
: public sprout::detail::type_traits_wrapper<std::is_signed<T> >
{};
template<typename T>
struct is_unsigned
: public sprout::detail::type_traits_wrapper<std::is_unsigned<T> >
{};
template<typename T, typename... Args>
struct is_constructible
: public sprout::detail::type_traits_wrapper<std::is_constructible<T, Args...> >
{};
template<typename T>
struct is_default_constructible
: public sprout::detail::type_traits_wrapper<std::is_default_constructible<T> >
{};
template<typename T>
struct is_copy_constructible
: public sprout::detail::type_traits_wrapper<std::is_copy_constructible<T> >
{};
template<typename T>
struct is_move_constructible
: public sprout::detail::type_traits_wrapper<std::is_move_constructible<T> >
{};
template<typename T, typename U>
struct is_assignable
: public sprout::detail::type_traits_wrapper<std::is_assignable<T, U> >
{};
template<typename T>
struct is_copy_assignable
: public sprout::detail::type_traits_wrapper<std::is_copy_assignable<T> >
{};
template<typename T>
struct is_move_assignable
: public sprout::detail::type_traits_wrapper<std::is_move_assignable<T> >
{};
template<typename T>
struct is_destructible
: public sprout::detail::type_traits_wrapper<std::is_destructible<T> >
{};
#if !defined(_LIBCPP_VERSION)
#if SPROUT_CLANG_HAS_FUTURE(is_trivially_constructible)
template<typename T, typename... Args>
struct is_trivially_constructible
: public sprout::integral_constant<bool, __is_trivially_constructible(T, Args...)>
{};
#else // #if SPROUT_CLANG_HAS_FUTURE(is_trivially_constructible)
template<typename T, typename... Args>
struct is_trivially_constructible
: public sprout::false_type
{};
#if SPROUT_CLANG_HAS_FUTURE(has_trivial_constructor) || SPROUT_GCC_OR_LATER(4, 3, 0)
template<typename T>
struct is_trivially_constructible<T>
: public sprout::integral_constant<bool, __has_trivial_constructor(T)>
{};
#else // #if SPROUT_CLANG_HAS_FUTURE(has_trivial_constructor) || SPROUT_GCC_OR_LATER(4, 3, 0)
template<typename T>
struct is_trivially_constructible<T>
: public sprout::is_scalar<T>
{};
#endif // #if SPROUT_CLANG_HAS_FUTURE(has_trivial_constructor) || SPROUT_GCC_OR_LATER(4, 3, 0)
template<typename T>
struct is_trivially_constructible<T, T&>
: public sprout::is_scalar<T>
{};
template<typename T>
struct is_trivially_constructible<T, T const&>
: public sprout::is_scalar<T>
{};
template<typename T>
struct is_trivially_constructible<T, T&&>
: public sprout::is_scalar<T>
{};
template<typename T>
struct is_trivially_constructible<T, T const&&>
: public sprout::is_scalar<T>
{};
#endif // #if SPROUT_CLANG_HAS_FUTURE(is_trivially_constructible)
template<typename T>
struct is_trivially_default_constructible
: public sprout::is_trivially_constructible<T>
{};
template<typename T>
struct is_trivially_copy_constructible
: public sprout::is_trivially_constructible<T, typename std::add_lvalue_reference<T>::type const>
{};
template<typename T>
struct is_trivially_move_constructible
: public sprout::is_trivially_constructible<T, typename std::add_rvalue_reference<T>::type const>
{};
#if SPROUT_CLANG_HAS_FUTURE(is_trivially_assignable)
template<typename T, typename U>
struct is_trivially_assignable
: public sprout::integral_constant<bool, __is_trivially_assignable(T, U)>
{};
#else // #if SPROUT_CLANG_HAS_FUTURE(is_trivially_assignable)
template<typename T, typename U>
struct is_trivially_assignable
: public sprout::false_type
{};
template<typename T>
struct is_trivially_assignable<T&, T>
: public sprout::is_scalar<T>
{};
template<typename T>
struct is_trivially_assignable<T&, T&>
: public sprout::is_scalar<T>
{};
template<typename T>
struct is_trivially_assignable<T&, T const&>
: public sprout::is_scalar<T>
{};
template<typename T>
struct is_trivially_assignable<T&, T&&>
: public sprout::is_scalar<T>
{};
template<typename T>
struct is_trivially_assignable<T&, T const&&>
: public sprout::is_scalar<T>
{};
#endif // #if SPROUT_CLANG_HAS_FUTURE(is_trivially_assignable)
template<typename T>
struct is_trivially_copy_assignable
: public sprout::is_trivially_assignable<
typename std::add_lvalue_reference<T>::type,
typename std::add_lvalue_reference<T>::type const
>
{};
template<typename T>
struct is_trivially_move_assignable
: public sprout::is_trivially_assignable<
typename std::add_lvalue_reference<T>::type,
typename std::add_rvalue_reference<T>::type
>
{};
#else // #if !defined(_LIBCPP_VERSION)
template<typename T, typename... Args>
struct is_trivially_constructible
: public sprout::detail::type_traits_wrapper<std::is_trivially_constructible<T, Args...> >
{};
template<typename T>
struct is_trivially_default_constructible
: public sprout::detail::type_traits_wrapper<std::is_trivially_default_constructible<T> >
{};
template<typename T>
struct is_trivially_copy_constructible
: public sprout::detail::type_traits_wrapper<std::is_trivially_copy_constructible<T> >
{};
template<typename T>
struct is_trivially_move_constructible
: public sprout::detail::type_traits_wrapper<std::is_trivially_move_constructible<T> >
{};
template<typename T, typename U>
struct is_trivially_assignable
: public sprout::detail::type_traits_wrapper<std::is_trivially_assignable<T, U> >
{};
template<typename T>
struct is_trivially_copy_assignable
: public sprout::detail::type_traits_wrapper<std::is_trivially_copy_assignable<T> >
{};
template<typename T>
struct is_trivially_move_assignable
: public sprout::detail::type_traits_wrapper<std::is_trivially_move_assignable<T> >
{};
#endif // #if !defined(_LIBCPP_VERSION)
#if !defined(_LIBCPP_VERSION) && SPROUT_GCC_EARLIER(4, 8, 0)
#if SPROUT_CLANG_HAS_FUTURE(has_trivial_destructor) || SPROUT_GCC_OR_LATER(4, 3, 0)
template<typename T>
struct is_trivially_destructible
: public sprout::integral_constant<bool, __has_trivial_destructor(T)>
{};
#else // #if SPROUT_CLANG_HAS_FUTURE(has_trivial_destructor) || SPROUT_GCC_OR_LATER(4, 3, 0)
template<typename T>
struct is_trivially_destructible
: public sprout::integral_constant<
bool,
std::is_scalar<typename std::remove_all_extents<T>::type>::value
|| std::is_reference<typename std::remove_all_extents<T>::type>::value
>
{};
#endif // #if SPROUT_CLANG_HAS_FUTURE(has_trivial_destructor) || SPROUT_GCC_OR_LATER(4, 3, 0)
#else // #if !defined(_LIBCPP_VERSION) && SPROUT_GCC_EARLIER(4, 8, 0)
template<typename T>
struct is_trivially_destructible
: public sprout::detail::type_traits_wrapper<std::is_trivially_destructible<T> >
{};
#endif // #if !defined(_LIBCPP_VERSION) && SPROUT_GCC_EARLIER(4, 8, 0)
template<typename T, typename... Args>
struct is_nothrow_constructible
: public sprout::detail::type_traits_wrapper<std::is_nothrow_constructible<T, Args...> >
{};
template<typename T>
struct is_nothrow_default_constructible
: public sprout::detail::type_traits_wrapper<std::is_nothrow_default_constructible<T> >
{};
template<typename T>
struct is_nothrow_copy_constructible
: public sprout::detail::type_traits_wrapper<std::is_nothrow_copy_constructible<T> >
{};
template<typename T>
struct is_nothrow_move_constructible
: public sprout::detail::type_traits_wrapper<std::is_nothrow_move_constructible<T> >
{};
template<typename T, typename U>
struct is_nothrow_assignable
: public sprout::detail::type_traits_wrapper<std::is_nothrow_assignable<T, U> >
{};
template<typename T>
struct is_nothrow_copy_assignable
: public sprout::detail::type_traits_wrapper<std::is_nothrow_copy_assignable<T> >
{};
template<typename T>
struct is_nothrow_move_assignable
: public sprout::detail::type_traits_wrapper<std::is_nothrow_move_assignable<T> >
{};
#if !defined(_LIBCPP_VERSION) && SPROUT_GCC_EARLIER(4, 8, 0)
template<typename T>
struct is_nothrow_destructible
: public sprout::integral_constant<
bool,
std::is_scalar<typename std::remove_all_extents<T>::type>::value
|| std::is_reference<typename std::remove_all_extents<T>::type>::value
>
{};
#else // #if !defined(_LIBCPP_VERSION) && SPROUT_GCC_EARLIER(4, 8, 0)
template<typename T>
struct is_nothrow_destructible
: public sprout::detail::type_traits_wrapper<std::is_nothrow_destructible<T> >
{};
#endif // #if !defined(_LIBCPP_VERSION) && SPROUT_GCC_EARLIER(4, 8, 0)
template<typename T>
struct has_virtual_destructor
: public sprout::detail::type_traits_wrapper<std::has_virtual_destructor<T> >
{};
// 20.10.5 Type property queries
template<typename T>
struct alignment_of
: public sprout::detail::type_traits_wrapper<std::alignment_of<T> >
{};
template<typename T>
struct rank
: public sprout::detail::type_traits_wrapper<std::rank<T> >
{};
template<typename T, unsigned I = 0>
struct extent
: public sprout::detail::type_traits_wrapper<std::extent<T, I> >
{};
// 20.10.6 Relationships between types
template<typename T, typename U>
struct is_same
: public sprout::detail::type_traits_wrapper<std::is_same<T, U> >
{};
template<typename From, typename To>
struct is_base_of
: public sprout::detail::type_traits_wrapper<std::is_base_of<From, To> >
{};
template<typename From, typename To>
struct is_convertible
: public sprout::detail::type_traits_wrapper<std::is_convertible<From, To> >
{};
// 20.10.7.1 Const-volatile modifications
using std::remove_const;
using std::remove_volatile;
using std::remove_cv;
using std::add_const;
using std::add_volatile;
using std::add_cv;
// 20.10.7.2 Reference modifications
using std::remove_reference;
using std::add_lvalue_reference;
using std::add_rvalue_reference;
// 20.10.7.3 Sign modifications
using std::make_signed;
using std::make_unsigned;
// 20.10.7.4 Array modifications
using std::remove_extent;
using std::remove_all_extents;
// 20.10.7.5 Pointer modifications
using std::remove_pointer;
using std::add_pointer;
// 20.10.7.6 Other transformations
using std::aligned_storage;
#if !defined(_LIBCPP_VERSION) || (_LIBCPP_VERSION < 1101)
template<std::size_t Len, typename... Types>
struct aligned_union
: public std::aligned_storage<
sprout::tpp::max_element_c<std::size_t, Len, sizeof(Types)...>::value,
sprout::tpp::max_element_c<std::size_t, std::alignment_of<Types>::value...>::value
>
{};
#else // #if !defined(_LIBCPP_VERSION) || (_LIBCPP_VERSION < 1101)
using std::aligned_union;
#endif // #if !defined(_LIBCPP_VERSION) || (_LIBCPP_VERSION < 1101)
using std::decay;
using std::enable_if;
using std::conditional;
using std::common_type;
using std::underlying_type;
using std::result_of;
} // namespace sprout
#endif // #ifndef SPROUT_TYPE_TRAITS_STD_TYPE_TRAITS_HPP
| 16,048 | 6,357 |
#include <iostream>
#include <iomanip>
#include <assert.h>
#include <common/term_tokenizer.hpp>
#include <common/token_chars.hpp>
using namespace prologcoin::common;
static void header( const std::string &str )
{
std::cout << "\n";
std::cout << "--- [" + str + "] " + std::string(60 - str.length(), '-') << "\n";
std::cout << "\n";
}
static void test_is_symbol_char()
{
header( "test_is_symbol_char()" );
std::string str;
bool in_seq = false;
for (int i = 0; i < 500; i++) {
if (term_tokenizer::is_symbol_char(i)) {
if (!in_seq && !str.empty()) {
str += ", ";
}
if (!in_seq) {
str += boost::lexical_cast<std::string>(i);
}
if (!in_seq &&
term_tokenizer::is_symbol_char(i+1) &&
term_tokenizer::is_symbol_char(i+2)) {
in_seq = true;
}
}
if (in_seq && !term_tokenizer::is_symbol_char(i)) {
str += "..";
str += boost::lexical_cast<std::string>(i-1);
in_seq = false;
}
}
std::cout << "Symbol chars: " + str + "\n";
assert( str ==
"35, 36, 38, 42, 43, 45..47, 58, 60..64, 92, 94, 96, 126, "
"160..191, 215, 247");
}
static void test_tokens()
{
header( "test_tokens()" );
std::string s = "this is a test'\\^?\\^Z\\^a'\t\n\t+=/*bla/* ha */ xx *q*/\001%To/*themoon\xf0\n'foo'!0'a0'\\^g4242 42.4711 42e3 47.11e-12Foo_Bar\"string\"\"\\^g\" _Baz__ 'bar\x55'[;].";
std::string expected[] = { "token<NAME>[this]@(L1,C1)",
"token<LAYOUT_TEXT>[\\x20]@(L1,C5)",
"token<NAME>[is]@(L1,C6)",
"token<LAYOUT_TEXT>[\\x20]@(L1,C8)",
"token<NAME>[a]@(L1,C9)",
"token<LAYOUT_TEXT>[\\x20]@(L1,C10)",
"token<NAME>[test]@(L1,C11)",
"token<NAME>[\\x7f\\x1a\\x01]@(L1,C15)",
"token<LAYOUT_TEXT>[\\x09\\x0a\\x09]@(L1,C26)",
"token<NAME>[+=]@(L2,C8)",
"token<LAYOUT_TEXT>[/*bla/*\\x20ha\\x20*/\\x20xx\\x20*q*/\\x01%To/*themoon\\xf0\\x0a]@(L2,C10)",
"token<NAME>[foo]@(L3,C1)",
"token<NAME>[!]@(L3,C6)",
"token<NATURAL_NUMBER>[97]@(L3,C7)",
"token<NATURAL_NUMBER>[7]@(L3,C10)",
"token<NATURAL_NUMBER>[4242]@(L3,C15)",
"token<LAYOUT_TEXT>[\\x20]@(L3,C19)",
"token<UNSIGNED_FLOAT>[42.4711]@(L3,C20)",
"token<LAYOUT_TEXT>[\\x20]@(L3,C27)",
"token<UNSIGNED_FLOAT>[42e3]@(L3,C28)",
"token<LAYOUT_TEXT>[\\x20]@(L3,C32)",
"token<UNSIGNED_FLOAT>[47.11e-12]@(L3,C33)",
"token<VARIABLE>[Foo_Bar]@(L3,C42)",
"token<STRING>[string\\x22\\x07]@(L3,C49)",
"token<LAYOUT_TEXT>[\\x20]@(L3,C62)",
"token<VARIABLE>[_Baz__]@(L3,C63)",
"token<LAYOUT_TEXT>[\\x20]@(L3,C69)",
"token<NAME>[barU]@(L3,C70)",
"token<PUNCTUATION_CHAR>[[]@(L3,C76)",
"token<NAME>[;]@(L3,C77)",
"token<PUNCTUATION_CHAR>[]]@(L3,C78)",
"token<FULL_STOP>[.]@(L3,C79)" };
std::stringstream ss(s, (std::stringstream::in | std::stringstream::binary));
term_tokenizer tt(ss);
int cnt = 0;
while (tt.has_more_tokens()) {
auto tok = tt.next_token();
std::cout << tok.str() << "\n";
if (tok.str() != expected[cnt]) {
std::cout << "Expected token: " << expected[cnt] << "\n";
std::cout << "But got : " << tok.str() << "\n";
}
assert( tok.str() == expected[cnt] );
cnt++;
}
}
static void test_negative_tokens()
{
header( "test_negative_tokens()" );
struct entry { std::string str;
token_exception *exc;
};
auto p = [](int line, int col) { return token_position(line,col); };
entry table[] =
{ { "'foo", new token_exception_unterminated_quoted_name("",p(1,1)) }
,{ "'esc\\", new token_exception_unterminated_escape("",p(1,1)) }
,{ "'esc\\x", new token_exception_unterminated_escape("",p(1,1)) }
,{ "'esc\\x3", new token_exception_unterminated_escape("",p(1,1)) }
,{ "'esc\\^", new token_exception_unterminated_escape("",p(1,1)) }
,{ "'esc\\^\t", new token_exception_control_char("",p(1,1)) }
,{ "'esc\\xg", new token_exception_hex_code("", p(1,1)) }
,{ "0'", new token_exception_no_char_code("", p(1,1)) }
,{ "11'", new token_exception_missing_number_after_base("", p(1,1)) }
,{ "1.x", new token_exception_missing_decimal("", p(1,1)) }
,{ "1.e", new token_exception_missing_decimal("", p(1,1)) }
,{ "1ex", new token_exception_missing_exponent("", p(1,1)) }
,{ "1e+", new token_exception_missing_exponent("", p(1,1)) }
,{ "1e-", new token_exception_missing_exponent("", p(1,1)) }
,{ "2E-", new token_exception_missing_exponent("", p(1,1)) }
,{ "\"foo", new token_exception_unterminated_string("", p(1,1)) }
};
for (auto e : table) {
std::stringstream ss(e.str);
term_tokenizer tt(ss);
try {
std::cout << "Testing token: " << e.str << "\n";
tt.next_token();
std::cout << " (Expected exception '" << typeid(e.exc).name() << "' not thrown)\n";
assert(false);
} catch (token_exception &exc) {
std::string actual = typeid(exc).name();
std::string expected = typeid(*e.exc).name();
std::cout << " Thrown: " << actual << "\n";
if (actual != expected) {
std::cout << " (Expected exception '" << expected
<< "' but got '" << actual << "'\n";
assert(false);
}
if (exc.pos() != e.exc->pos()) {
std::cout << " (Expected position " << e.exc->pos().str()
<< " but got " << exc.pos().str() << ")\n";
assert(false);
}
delete e.exc; // Free memory (good for valgrind)
}
}
}
int main( int argc, char *argv[] )
{
test_is_symbol_char();
test_tokens();
test_negative_tokens();
return 0;
}
| 5,772 | 2,627 |
#include "Route.h"
namespace winston {
} | 41 | 17 |
/*
* Copyright (c) 2015, Julien Bernard
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "Ground.h"
#include "Ball.h"
#include "Events.h"
#include "Singletons.h"
Ground::Ground() {
gEventManager().registerHandler<BallLocationEvent>(&Ground::onBallLocation, this);
}
void Ground::render(sf::RenderWindow& window) {
sf::RectangleShape shape({ WIDTH, HEIGHT });
shape.setOrigin(WIDTH / 2, HEIGHT / 2);
shape.setPosition(0.0f, 0.0f);
shape.setFillColor(sf::Color::Black);
window.draw(shape);
}
game::EventStatus Ground::onBallLocation(game::EventType type, game::Event *event) {
auto loc = static_cast<BallLocationEvent*>(event);
static constexpr float Y_LIMIT = HEIGHT / 2 - Ball::RADIUS;
if (loc->position.y > Y_LIMIT) {
loc->velocity.y = -loc->velocity.y;
loc->position.y = Y_LIMIT;
}
if (loc->position.y < -Y_LIMIT) {
loc->velocity.y = -loc->velocity.y;
loc->position.y = -Y_LIMIT;
}
static constexpr float X_LIMIT = WIDTH / 2 - Ball::RADIUS;
if (loc->position.x > X_LIMIT) {
PointEvent point;
point.location = Paddle::Location::RIGHT;
gEventManager().triggerEvent(&point);
loc->velocity.x = -loc->velocity.x;
loc->position = sf::Vector2f(0, 0);
}
if (loc->position.x < -X_LIMIT) {
PointEvent point;
point.location = Paddle::Location::LEFT;
gEventManager().triggerEvent(&point);
loc->velocity.x = -loc->velocity.x;
loc->position = sf::Vector2f(0, 0);
}
return game::EventStatus::KEEP;
}
| 2,530 | 908 |
// NET_Compressor.cpp: implementation of the NET_Compressor class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "NET_Common.h"
#include "NET_Compressor.h"
#include "xrCore/Threading/Lock.hpp"
#if NET_USE_COMPRESSION
#if NET_USE_LZO_COMPRESSION
#define ENCODE rtc9_compress
#define DECODE rtc9_decompress
#else // NET_USE_LZO_COMPRESSION
#include "xrCore/ppmd_compressor.h"
#define ENCODE ppmd_compress
#define DECODE ppmd_decompress
#endif // NET_USE_LZO_COMPRESSION
#endif // NET_USE_COMPRESSION
#if 1 // def DEBUG
// static FILE* OriginalTrafficDump = NULL;
// static FILE* CompressedTrafficDump = NULL;
static FILE* RawTrafficDump = nullptr;
static FILE* CompressionDump = nullptr;
#endif // DEBUG
#define NOWARN
// size of range encoding code values
#define PPM_CODE_BITS 32
#define PPM_TOP_VALUE ((NET_Compressor::code_value)1 << (PPM_CODE_BITS - 1))
#define SHIFT_BITS (PPM_CODE_BITS - 9)
#define EXTRA_BITS ((PPM_CODE_BITS - 2) % 8 + 1)
#define PPM_BOTTOM_VALUE (PPM_TOP_VALUE >> 8)
/*
// c is written as first byte in the datastream
// one could do without c, but then you have an additional if
// per outputbyte.
void NET_Compressor::start_encoding(BYTE* dest, u32 header_size)
{
dest += header_size - 1;
RNGC.low = 0; // Full code range
RNGC.range = PPM_TOP_VALUE;
RNGC.buffer = 0;
RNGC.help = 0; // No bytes to follow
RNGC.bytecount = 0;
RNGC.ptr = dest;
}
// I do the normalization before I need a defined state instead of
// after messing it up. This simplifies starting and ending.
void NET_Compressor::encode_normalize()
{
while (RNGC.range <= PPM_BOTTOM_VALUE) // do we need renormalisation?
{
if (RNGC.low < code_value(0xff) << SHIFT_BITS) // no carry possible --> output
{
RNGC.byte_out(RNGC.buffer);
for (; RNGC.help; RNGC.help--)
RNGC.byte_out(0xff);
RNGC.buffer = (BYTE)(RNGC.low >> SHIFT_BITS);
}
else if (RNGC.low & PPM_TOP_VALUE) // carry now, no future carry
{
RNGC.byte_out(RNGC.buffer + 1);
for (; RNGC.help; RNGC.help--)
RNGC.byte_out(0);
RNGC.buffer = (BYTE)(RNGC.low >> SHIFT_BITS);
}
else // passes on a potential carry
{
RNGC.help++;
}
RNGC.range <<= 8;
RNGC.low = (RNGC.low << 8) & (PPM_TOP_VALUE - 1);
RNGC.bytecount ++;
}
}
// Encode a symbol using frequencies
// sy_f is the interval length (frequency of the symbol)
// lt_f is the lower end (frequency sum of < symbols)
// tot_f is the total interval length (total frequency sum)
// or (faster): tot_f = (code_value)1<<shift
void NET_Compressor::encode_freq(freq sy_f, freq lt_f, freq tot_f)
{
encode_normalize();
code_value r = RNGC.range / tot_f;
code_value tmp = r * lt_f;
RNGC.low += tmp;
if (lt_f + sy_f < tot_f) RNGC.range = r * sy_f;
else RNGC.range -= tmp;
}
void NET_Compressor::encode_shift(freq sy_f, freq lt_f, freq shift)
{
encode_normalize();
code_value r = RNGC.range >> shift;
code_value tmp = r * lt_f;
RNGC.low += tmp;
if ((lt_f + sy_f) >> shift) RNGC.range -= tmp;
else RNGC.range = r * sy_f;
}
// Finish encoding
// actually not that many bytes need to be output, but who
// cares. I output them because decode will read them :)
// the return value is the number of bytes written
u32 NET_Compressor::done_encoding()
{
encode_normalize(); // now we have a normalized state
RNGC.bytecount += 3;
u32 tmp = ((RNGC.low & (PPM_BOTTOM_VALUE - 1)) < ((RNGC.bytecount & 0xffffffL) >> 1))
? (RNGC.low >> SHIFT_BITS)
: (RNGC.low >> SHIFT_BITS) + 1;
if (tmp > 0xff) // we have a carry
{
RNGC.byte_out(RNGC.buffer + 1);
for (; RNGC.help; RNGC.help--)
RNGC.byte_out(0);
}
else // no carry
{
RNGC.byte_out(RNGC.buffer);
for (; RNGC.help; RNGC.help--)
RNGC.byte_out(0xff);
}
RNGC.byte_out((BYTE)(tmp & 0xff));
RNGC.byte_out(0);
return RNGC.bytecount;
}
// Start the decoder
int NET_Compressor::start_decoding(BYTE* src, u32 header_size)
{
src += header_size;
RNGC.ptr = src;
RNGC.buffer = RNGC.byte_in();
RNGC.low = RNGC.buffer >> (8 - EXTRA_BITS);
RNGC.range = (code_value)1 << EXTRA_BITS;
return 0;
}
void NET_Compressor::decode_normalize()
{
while (RNGC.range <= PPM_BOTTOM_VALUE)
{
RNGC.low = (RNGC.low << 8) | ((RNGC.buffer << EXTRA_BITS) & 0xff);
RNGC.buffer = RNGC.byte_in();
RNGC.low |= RNGC.buffer >> (8 - EXTRA_BITS);
RNGC.range <<= 8;
}
}
// Calculate culmulative frequency for next symbol. Does NO update!
// tot_f is the total frequency
// or: totf is (code_value)1<<shift
// returns the culmulative frequency
NET_Compressor::freq NET_Compressor::decode_culfreq(freq tot_f)
{
decode_normalize();
RNGC.help = RNGC.range / tot_f;
freq tmp = RNGC.low / RNGC.help;
return (tmp >= tot_f) ? (tot_f - 1) : (tmp);
}
NET_Compressor::freq NET_Compressor::decode_culshift(freq shift)
{
decode_normalize();
RNGC.help = RNGC.range >> shift;
freq tmp = RNGC.low / RNGC.help;
return (tmp >> shift) ? ((code_value(1) << shift) - 1) : (tmp);
}
// Update decoding state
// sy_f is the interval length (frequency of the symbol)
// lt_f is the lower end (frequency sum of < symbols)
// tot_f is the total interval length (total frequency sum)
void NET_Compressor::decode_update(freq sy_f, freq lt_f, freq tot_f)
{
code_value tmp = RNGC.help * lt_f;
RNGC.low -= tmp;
if (lt_f + sy_f < tot_f) RNGC.range = RNGC.help * sy_f;
else RNGC.range -= tmp;
}
// Decode a byte/short without modelling
BYTE NET_Compressor::decode_byte()
{
u32 tmp = decode_culshift(8);
decode_update(1, tmp, (freq)1 << 8);
return BYTE(tmp);
}
u16 NET_Compressor::decode_short()
{
u32 tmp = decode_culshift(16);
decode_update(1, tmp, (freq)1 << 16);
return u16(tmp);
}
// Finish decoding
// rc is the range coder to be used
void NET_Compressor::done_decoding()
{
decode_normalize(); // normalize to use up all bytes
}
*/
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
#ifdef CONFIG_PROFILE_LOCKS
NET_Compressor::NET_Compressor() : pcs(xr_new<Lock>(MUTEX_PROFILE_ID(NET_Compressor))) {}
#else
NET_Compressor::NET_Compressor() : pcs(xr_new<Lock>()) {}
#endif
NET_Compressor::~NET_Compressor()
{
#if 1 // def DEBUG
//if (strstr(Core.Params, "-dump_traffic"))
//{
// fclose(OriginalTrafficDump);
// fclose(CompressedTrafficDump);
//}
if (CompressionDump)
{
fclose(CompressionDump);
CompressionDump = nullptr;
}
if (RawTrafficDump)
{
fclose(RawTrafficDump);
RawTrafficDump = nullptr;
}
#endif // DEBUG
delete pcs;
}
/*
void NET_Compressor::Initialize ()
{
pcs->Enter();
#if 1//def DEBUG
if (strstr(Core.Params, "-dump_traffic"))
{
OriginalTrafficDump = fopen("x:/network_out_original.dat", "wb");
CompressedTrafficDump = fopen("x:/network_out_compressed.dat", "wb");
}
#endif // DEBUG
pcs->Leave();
}*/
u16 NET_Compressor::compressed_size(const u32& count) const
{
#if NET_USE_COMPRESSION
#if NET_USE_LZO_COMPRESSION
u32 result = rtc_csize(count) + 1;
#else // NET_USE_LZO_COMPRESSION
u32 result = 64 + (count / 8 + 1) * 10;
#endif // NET_USE_LZO_COMPRESSION
R_ASSERT(result <= u32(u16(-1)));
return (u16)result;
#else
return (u16)count;
#endif // #if NET_USE_COMPRESSION
}
XRNETSERVER_API BOOL g_net_compressor_enabled = FALSE;
XRNETSERVER_API BOOL g_net_compressor_gather_stats = FALSE;
u16 NET_Compressor::Compress(u8* dest, const u32& dest_size, u8* src, const u32& count)
{
SCompressorStats::SStatPacket* _p = nullptr;
bool b_compress_packet = (count > 36);
if (g_net_compressor_gather_stats && b_compress_packet)
{
_p = m_stats.get(count);
_p->hit_count += 1;
m_stats.total_uncompressed_bytes += count;
}
VERIFY(dest);
VERIFY(src);
VERIFY(count);
#if 0 // def DEBUG
if (strstr(Core.Params, "-dump_traffic"))
{
fwrite(src, count, 1, OriginalTrafficDump);
fflush(OriginalTrafficDump);
}
#endif // DEBUG
#if !NET_USE_COMPRESSION
CopyMemory(dest, src, count);
return (u16(count));
#else // !NET_USE_COMPRESSION
R_ASSERT(dest_size >= compressed_size(count));
u32 compressed_size = count;
u32 offset = 1;
#if NET_USE_COMPRESSION_CRC
offset += sizeof(u32);
#endif // NET_USE_COMPRESSION_CRC
if (!psNET_direct_connect && g_net_compressor_enabled && b_compress_packet)
{
pcs->Enter();
compressed_size = offset + ENCODE(dest + offset, dest_size - offset, src, count);
if (g_net_compressor_gather_stats)
m_stats.total_compressed_bytes += compressed_size;
pcs->Leave();
}
if (compressed_size < count)
{
*dest = NET_TAG_COMPRESSED;
#if NET_USE_COMPRESSION_CRC
u32 crc = crc32(dest + offset, compressed_size);
*((u32*)(dest + 1)) = crc;
#endif // NET_USE_COMPRESSION_CRC
#if NET_LOG_COMPRESSION
Msg("# compress %u->%u %02X (%08X)", count, compressed_size, *dest, *((u32*)(src + 1)));
#endif
#if NET_DUMP_COMPRESSION
#if NET_USE_LZO_COMPRESSION
static const char* compressor_name = "LZO";
#else
static const char* compressor_name = "PPMd";
#endif
if (!CompressionDump)
CompressionDump = fopen("net-compression.log", "w+b");
fprintf(CompressionDump, "%s compress %2.0f%% %u->%u\r\n", compressor_name,
100.0f * float(compressed_size) / float(count), count, compressed_size);
#endif // NET_DUMP_COMPRESSION
}
else
{
if (g_net_compressor_gather_stats && b_compress_packet)
_p->unlucky_attempts += 1;
*dest = NET_TAG_NONCOMPRESSED;
compressed_size = count + 1;
CopyMemory(dest + 1, src, count);
#if NET_LOG_COMPRESSION
Msg("# compress/as-is %u->%u %02X", count, compressed_size, *dest);
#endif
}
if (g_net_compressor_gather_stats && b_compress_packet)
_p->compressed_size += compressed_size;
#if 0 // def DEBUG
if (strstr(Core.Params, "-dump_traffic"))
{
fwrite(dest, compressed_size, 1, CompressedTrafficDump);
fflush(CompressedTrafficDump);
}
#endif // DEBUG
#if 0 //def DEBUG
u8* src_back = (u8*)xr_alloca(count);
Decompress(src_back, count, dest, compressed_size);
u8* I = src_back;
u8* E = src_back + count;
u8* J = src;
for (; I != E; ++I , ++J)
VERIFY (*I == *J);
pcs->Leave();
#endif // DEBUG
return (u16(compressed_size));
#endif // if !NET_USE_COMPRESSION
}
u16 NET_Compressor::Decompress(u8* dest, const u32& dest_size, u8* src, const u32& count)
{
VERIFY(dest);
VERIFY(src);
VERIFY(count);
#if NET_LOG_COMPRESSION
Msg("# decompress %u %02X (%08X)", count, src[0], *((u32*)(src + 1)));
#endif
#if NET_USE_COMPRESSSION
if (src[0] != NET_TAG_COMPRESSED && src[0] != NET_TAG_NONCOMPRESSED)
{
Msg("! invalid compression-tag %02X", src[0]);
DEBUG_BREAK;
}
#endif // NET_USE_COMPRESSSION
#if !NET_USE_COMPRESSION
CopyMemory(dest, src, count);
return (u16(count));
#else
if (*src != NET_TAG_COMPRESSED)
{
if (count)
{
CopyMemory(dest, src + 1, count - 1);
return (u16(count - 1));
}
return (0);
}
u32 offset = 1;
#if NET_USE_COMPRESSION_CRC
offset += sizeof(u32);
#endif // NET_USE_COMPRESSION_CRC
#if NET_USE_COMPRESSION_CRC
u32 crc = crc32(src + offset, count);
//Msg("decompressed %d -> ? [0x%08x]", count, crc);
if (crc != *((u32*)(src + 1)))
Msg("! CRC mismatch");
R_ASSERT2(crc == *((u32*)(src + 1)), make_string("crc is different! (0x%08x != 0x%08x)", crc, *((u32*)(src + 1))));
#endif // NET_USE_COMPRESSION_CRC
pcs->Enter();
u32 uncompressed_size = DECODE(dest, dest_size, src + offset, count - offset);
pcs->Leave();
return (u16)uncompressed_size;
#endif // !NET_USE_COMPRESSION
}
void NET_Compressor::DumpStats(bool brief) const
{
auto cit = m_stats.m_packets.cbegin();
auto cit_e = m_stats.m_packets.cend();
Msg("---------NET_Compressor::DumpStats-----------");
Msg("Active=[%s]", g_net_compressor_enabled ? "yes" : "no");
Msg("uncompressed [%d]", m_stats.total_uncompressed_bytes);
Msg("compressed [%d]", m_stats.total_compressed_bytes);
u32 total_hits = 0;
u32 unlucky_hits = 0;
for (; cit != cit_e; ++cit)
{
total_hits += cit->second.hit_count;
unlucky_hits += cit->second.unlucky_attempts;
if (!brief)
{
Msg("size[%d] count[%d] unlucky[%d] avg_c[%d]", cit->first, cit->second.hit_count,
cit->second.unlucky_attempts, iFloor(float(cit->second.compressed_size) / float(cit->second.hit_count)));
}
}
Msg("total [%d]", total_hits);
Msg("unlucky [%d]", unlucky_hits);
}
| 13,341 | 5,362 |
#include <vector>
#include "catch.hpp"
#include "../headers/iterator_cast.h"
SCENARIO(" 'into' with only an input container, no transformation", "[into]") {
GIVEN(" a std::vector<char> vc") {
std::vector<char> vc{'a','b','c','d'};
WHEN( " make a string using into<std::string>(vc) " ) {
auto str = into<std::string>(vc);
THEN(" the size and value match ") {
REQUIRE( str.size() == vc.size() );
REQUIRE( str == "abcd" );
}
}
}
}
SCENARIO( " 'into' with a unary fn ", "[into], [transform]") {
GIVEN(" a std::vector<int> ") {
std::vector<int> vi{1,2,3,4};
WHEN(" transformed 'into' in a string ") {
auto str = into<std::string>([](const int& i) { return (char)(i+48); }, vi);
THEN(" must match in size and content ") {
REQUIRE( str.size() == vi.size() );
REQUIRE( str == "1234" );
}
}
}
}
| 1,002 | 348 |
#include <koinos/system/system_calls.hpp>
#include <koinos/buffer.hpp>
#include <koinos/common.h>
#include <calc.h>
using namespace koinos;
using namespace koinos::contracts;
enum entries : uint32_t
{
add_entry = 1,
sub_entry = 2,
mul_entry = 3,
div_entry = 4
};
class calculator
{
public:
calc::add_result add( int64_t x, int64_t y ) noexcept;
calc::sub_result sub( int64_t x, int64_t y ) noexcept;
calc::mul_result mul( int64_t x, int64_t y ) noexcept;
calc::div_result div( int64_t x, int64_t y ) noexcept;
};
calc::add_result calculator::add( int64_t x, int64_t y ) noexcept
{
calc::add_result res;
res.set_value( x + y );
return res;
}
calc::sub_result calculator::sub( int64_t x, int64_t y ) noexcept
{
calc::sub_result res;
res.set_value( x - y );
return res;
}
calc::mul_result calculator::mul( int64_t x, int64_t y ) noexcept
{
calc::mul_result res;
res.set_value( x * y );
return res;
}
calc::div_result calculator::div( int64_t x, int64_t y ) noexcept
{
calc::div_result res;
if ( y == 0 )
{
system::print( "cannot divide by zero" );
system::exit_contract( 1 );
}
res.set_value( x / y );
return res;
}
int main()
{
auto entry_point = system::get_entry_point();
auto args = system::get_contract_arguments();
std::array< uint8_t, 32 > retbuf;
koinos::read_buffer rdbuf( (uint8_t*)args.c_str(), args.size() );
koinos::write_buffer buffer( retbuf.data(), retbuf.size() );
calculator c;
switch( entry_point )
{
case entries::add_entry:
{
calc::add_arguments args;
args.deserialize( rdbuf );
auto res = c.add( args.x(), args.y() );
res.serialize( buffer );
break;
}
case entries::sub_entry:
{
calc::sub_arguments args;
args.deserialize( rdbuf );
auto res = c.sub( args.x(), args.y() );
res.serialize( buffer );
break;
}
case entries::mul_entry:
{
calc::mul_arguments args;
args.deserialize( rdbuf );
auto res = c.mul( args.x(), args.y() );
res.serialize( buffer );
break;
}
case entries::div_entry:
{
calc::div_arguments args;
args.deserialize( rdbuf );
auto res = c.div( args.x(), args.y() );
res.serialize( buffer );
break;
}
default:
system::exit_contract( 1 );
}
std::string retval( reinterpret_cast< const char* >( buffer.data() ), buffer.get_size() );
system::set_contract_result_bytes( retval );
system::exit_contract( 0 );
return 0;
}
| 2,658 | 992 |
//
// ASN1Codec.cpp
//
// $Id: //poco/1.4/Foundation/src/ASN1Codec.cpp#1 $
//
// Library: Foundation
// Package: Streams
// Module: ASN1Codec
//
// Copyright (c) 2010, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "Poco/ASN1Codec.h"
#include "Poco/ASN1FactoryDefault.h"
#include "Poco/BinaryReader.h"
#include "Poco/BinaryWriter.h"
namespace Poco {
ASN1Codec::ASN1Codec() : _factory(new ASN1FactoryDefault)
{
}
ASN1Codec::ASN1Codec(Poco::SharedPtr<ASN1Factory> factory) : _factory(factory)
{
if (factory.isNull())
throw InvalidArgumentException("Factory is required");
}
void ASN1Codec::setFactory(Poco::SharedPtr<ASN1Factory> factory)
{
if (factory.isNull())
throw InvalidArgumentException("Factory is required");
_factory = factory;
}
void ASN1Codec::encode(ASN1::Ptr data, std::ostream &stream)
{
Poco::BinaryWriter swrite(stream);
data->encode(swrite);
}
ASN1::Ptr ASN1Codec::decode(std::istream &stream)
{
ASN1::Ptr ret;
Poco::BinaryReader sread(stream);
ASN1Type tp;
tp.decodeData(sread);
ret = _factory->create(tp);
ret->decode(_factory, sread);
return ret;
}
} // namespace Poco
| 1,198 | 485 |
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unordered_map>
#include "ref-napi.h"
#ifdef _WIN32
#define __alignof__ __alignof
#define snprintf(buf, bufSize, format, arg) _snprintf_s(buf, bufSize, _TRUNCATE, format, arg)
#define strtoll _strtoi64
#define strtoull _strtoui64
#define PRId64 "lld"
#define PRIu64 "llu"
#else
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#include <inttypes.h>
#endif
using namespace Napi;
namespace {
#if !defined(NAPI_VERSION) || NAPI_VERSION < 6
napi_status napix_set_instance_data(
napi_env env, void* data, napi_finalize finalize_cb, void* finalize_hint) {
typedef napi_status (*napi_set_instance_data_fn)(
napi_env env, void* data, napi_finalize finalize_cb, void* finalize_hint);
static const napi_set_instance_data_fn napi_set_instance_data__ =
(napi_set_instance_data_fn)
get_symbol_from_current_process("napi_set_instance_data");
if (napi_set_instance_data__ == nullptr)
return napi_generic_failure;
return napi_set_instance_data__(env, data, finalize_cb, finalize_hint);
}
napi_status napix_get_instance_data(
napi_env env, void** data) {
typedef napi_status (*napi_get_instance_data_fn)(
napi_env env, void** data);
static const napi_get_instance_data_fn napi_get_instance_data__ =
(napi_get_instance_data_fn)
get_symbol_from_current_process("napi_get_instance_data");
*data = nullptr;
if (napi_get_instance_data__ == nullptr)
return napi_generic_failure;
return napi_get_instance_data__(env, data);
}
#else // NAPI_VERSION >= 6
napi_status napix_set_instance_data(
napi_env env, void* data, napi_finalize finalize_cb, void* finalize_hint) {
return napi_set_instance_data(env, data, finalize_cb, finalize_hint);
}
napi_status napix_get_instance_data(
napi_env env, void** data) {
return napi_get_instance_data(env, data);
}
#endif
// used by the Int64 functions to determine whether to return a Number
// or String based on whether or not a Number will lose precision.
// http://stackoverflow.com/q/307179/376773
#define JS_MAX_INT +9007199254740992LL
#define JS_MIN_INT -9007199254740992LL
// mirrors deps/v8/src/objects.h.
// we could use `node::Buffer::kMaxLength`, but it's not defined on node v0.6.x
static const size_t kMaxLength = 0x3fffffff;
enum ArrayBufferMode {
AB_CREATED_BY_REF,
AB_PASSED_TO_REF
};
// Since Node.js v14.0.0, we have to keep a global list of all ArrayBuffer
// instances that we work with, in order not to create any duplicates.
// Luckily, N-API instance data is available on v14.x and above.
class InstanceData final : public RefNapi::Instance {
public:
InstanceData(Env env) : env(env) {}
struct ArrayBufferEntry {
Reference<ArrayBuffer> ab;
size_t finalizer_count;
};
Env env;
std::unordered_map<char*, ArrayBufferEntry> pointer_to_orig_buffer;
FunctionReference buffer_from;
void RegisterArrayBuffer(napi_value val) override {
ArrayBuffer buf(env, val);
RegisterArrayBuffer(buf, AB_PASSED_TO_REF);
}
inline void RegisterArrayBuffer(ArrayBuffer buf, ArrayBufferMode mode) {
char* ptr = static_cast<char*>(buf.Data());
if (ptr == nullptr) return;
auto it = pointer_to_orig_buffer.find(ptr);
if (it != pointer_to_orig_buffer.end()) {
if (!it->second.ab.Value().IsEmpty()) {
// Already have a valid entry, nothing to do.
return;
}
it->second.ab.Reset(buf, 0);
it->second.finalizer_count++;
} else {
pointer_to_orig_buffer.emplace(ptr, ArrayBufferEntry {
Reference<ArrayBuffer>::New(buf, 0),
1
});
}
// If AB_CREATED_BY_REF, then another finalizer has been added before this
// as a "real" backing store finalizer.
if (mode != AB_CREATED_BY_REF) {
buf.AddFinalizer([this](Env env, char* ptr) {
UnregisterArrayBuffer(ptr);
}, ptr);
}
}
inline void UnregisterArrayBuffer(char* ptr) {
auto it = pointer_to_orig_buffer.find(ptr);
if (--it->second.finalizer_count == 0)
pointer_to_orig_buffer.erase(it);
}
inline ArrayBuffer LookupOrCreateArrayBuffer(char* ptr, size_t length) {
assert(ptr != nullptr);
ArrayBuffer ab;
auto it = pointer_to_orig_buffer.find(ptr);
if (it != pointer_to_orig_buffer.end())
ab = it->second.ab.Value();
if (ab.IsEmpty()) {
length = std::max<size_t>(length, kMaxLength);
ab = Buffer<char>::New(env, ptr, length, [this](Env env, char* ptr) {
UnregisterArrayBuffer(ptr);
}).ArrayBuffer();
RegisterArrayBuffer(ab, AB_CREATED_BY_REF);
}
return ab;
}
napi_value WrapPointer(char* ptr, size_t length) override;
char* GetBufferData(napi_value val) override;
static InstanceData* Get(Env env) {
void* d = nullptr;
if (napix_get_instance_data(env, &d) == napi_ok)
return static_cast<InstanceData*>(d);
return nullptr;
}
};
/**
* Converts an arbitrary pointer to a node Buffer with specified length
*/
Value WrapPointer(Env env, char* ptr, size_t length) {
if (ptr == nullptr)
length = 0;
InstanceData* data;
if (ptr != nullptr && (data = InstanceData::Get(env)) != nullptr) {
ArrayBuffer ab = data->LookupOrCreateArrayBuffer(ptr, length);
assert(!ab.IsEmpty());
return data->buffer_from.Call({
ab, Number::New(env, 0), Number::New(env, length)
});
}
return Buffer<char>::New(env, ptr, length, [](Env,char*){});
}
char* GetBufferData(Value val) {
Buffer<char> buf = val.As<Buffer<char>>();
InstanceData* data = InstanceData::Get(val.Env());
if (data != nullptr)
data->RegisterArrayBuffer(buf.ArrayBuffer());
return buf.Data();
}
napi_value InstanceData::WrapPointer(char* ptr, size_t length) {
return ::WrapPointer(env, ptr, length);
}
char* InstanceData::GetBufferData(napi_value val) {
return ::GetBufferData(Value(env, val));
}
char* AddressForArgs(const CallbackInfo& args, size_t offset_index = 1) {
Value buf = args[0];
if (!buf.IsBuffer()) {
throw TypeError::New(args.Env(), "Buffer instance expected");
}
int64_t offset = args[offset_index].ToNumber();
return GetBufferData(buf) + offset;
}
/**
* Returns the pointer address as a Number of the given Buffer instance.
* It's recommended to use `hexAddress()` in most cases instead of this function.
*
* WARNING: a JavaScript Number cannot precisely store a full 64-bit memory
* address, so there's a possibility of an inaccurate value being returned
* on 64-bit systems.
*
* args[0] - Buffer - the Buffer instance get the memory address of
* args[1] - Number - optional (0) - the offset of the Buffer start at
*/
Value Address (const CallbackInfo& args) {
char* ptr = AddressForArgs(args);
uintptr_t intptr = reinterpret_cast<uintptr_t>(ptr);
return Number::New(args.Env(), static_cast<double>(intptr));
}
/**
* Returns the pointer address as a hexadecimal String. This function
* is safe to use for displaying memory addresses, as compared to the
* `address()` function which could overflow since it returns a Number.
*
* args[0] - Buffer - the Buffer instance get the memory address of
* args[1] - Number - optional (0) - the offset of the Buffer start at
*/
Value HexAddress(const CallbackInfo& args) {
char* ptr = AddressForArgs(args);
char strbuf[30]; /* should be plenty... */
snprintf(strbuf, 30, "%p", ptr);
if (strbuf[0] == '0' && strbuf[1] == 'x') {
/* strip the leading "0x" from the address */
ptr = strbuf + 2;
} else {
ptr = strbuf;
}
return String::New(args.Env(), ptr);
}
/**
* Returns "true" if the given Buffer points to nullptr, "false" otherwise.
*
* args[0] - Buffer - the Buffer instance to check for nullptr
* args[1] - Number - optional (0) - the offset of the Buffer start at
*/
Value IsNull(const CallbackInfo& args) {
char* ptr = AddressForArgs(args);
return Boolean::New(args.Env(), ptr == nullptr);
}
/**
* Retreives a JS Object instance that was previously stored in
* the given Buffer instance at the given offset.
*
* args[0] - Buffer - the "buf" Buffer instance to read from
* args[1] - Number - the offset from the "buf" buffer's address to read from
*/
Value ReadObject(const CallbackInfo& args) {
char* ptr = AddressForArgs(args);
if (ptr == nullptr) {
throw Error::New(args.Env(), "readObject: Cannot read from nullptr pointer");
}
Reference<Object>* rptr = reinterpret_cast<Reference<Object>*>(ptr);
return rptr->Value();
}
/**
* Writes a weak reference to given Object to the given Buffer
* instance and offset.
*
* args[0] - Buffer - the "buf" Buffer instance to write to
* args[1] - Number - the offset from the "buf" buffer's address to write to
* args[2] - Object - the "obj" Object which will have a new Persistent reference
* created for the obj, whose memory address will be written.
*/
void WriteObject(const CallbackInfo& args) {
Env env = args.Env();
char* ptr = AddressForArgs(args);
if (ptr == nullptr) {
throw Error::New(env, "readObject: Cannot write to nullptr pointer");
}
Reference<Object>* rptr = reinterpret_cast<Reference<Object>*>(ptr);
if (args[2].IsObject()) {
Object val = args[2].As<Object>();
*rptr = std::move(Reference<Object>::New(val));
} else if (args[2].IsNull()) {
rptr->Reset();
} else {
throw TypeError::New(env, "WriteObject's 3rd argument needs to be an object");
}
}
/**
* Reads the memory address of the given "buf" pointer Buffer at the specified
* offset, and returns a new SlowBuffer instance from the memory address stored.
*
* args[0] - Buffer - the "buf" Buffer instance to read from
* args[1] - Number - the offset from the "buf" buffer's address to read from
* args[2] - Number - the length in bytes of the returned SlowBuffer instance
*/
Value ReadPointer(const CallbackInfo& args) {
Env env = args.Env();
char* ptr = AddressForArgs(args);
if (ptr == nullptr) {
throw Error::New(env, "readPointer: Cannot read from nullptr pointer");
}
int64_t size = args[2].ToNumber();
char* val = *reinterpret_cast<char**>(ptr);
return WrapPointer(env, val, size);
}
/**
* Writes the memory address of the "input" buffer (and optional offset) to the
* specified "buf" buffer and offset. Essentially making "buf" hold a reference
* to the "input" Buffer.
*
* args[0] - Buffer - the "buf" Buffer instance to write to
* args[1] - Number - the offset from the "buf" buffer's address to write to
* args[2] - Buffer - the "input" Buffer whose memory address will be written
*/
void WritePointer(const CallbackInfo& args) {
Env env = args.Env();
char* ptr = AddressForArgs(args);
Value input = args[2];
if (!input.IsNull() && !input.IsBuffer()) {
throw TypeError::New(env, "writePointer: Buffer instance expected as third argument");
}
if (input.IsNull()) {
*reinterpret_cast<char**>(ptr) = nullptr;
} else {
char* input_ptr = GetBufferData(input);
*reinterpret_cast<char**>(ptr) = input_ptr;
}
}
/**
* Reads a machine-endian int64_t from the given Buffer at the given offset.
*
* args[0] - Buffer - the "buf" Buffer instance to read from
* args[1] - Number - the offset from the "buf" buffer's address to read from
*/
Value ReadInt64(const CallbackInfo& args) {
Env env = args.Env();
char* ptr = AddressForArgs(args);
if (ptr == nullptr) {
throw TypeError::New(env, "readInt64: Cannot read from nullptr pointer");
}
int64_t val = *reinterpret_cast<int64_t*>(ptr);
if (val < JS_MIN_INT || val > JS_MAX_INT) {
char strbuf[128];
snprintf(strbuf, 128, "%" PRId64, val);
return String::New(env, strbuf);
} else {
return Number::New(env, val);
}
}
/**
* Writes the input Number/String int64 value as a machine-endian int64_t to
* the given Buffer at the given offset.
*
* args[0] - Buffer - the "buf" Buffer instance to write to
* args[1] - Number - the offset from the "buf" buffer's address to write to
* args[2] - String/Number - the "input" String or Number which will be written
*/
void WriteInt64(const CallbackInfo& args) {
Env env = args.Env();
char* ptr = AddressForArgs(args);
Value in = args[2];
int64_t val;
if (in.IsNumber()) {
val = in.As<Number>();
} else if (in.IsString()) {
char* endptr;
char* str;
int base = 0;
std::string _str = in.As<String>();
str = &_str[0];
errno = 0; /* To distinguish success/failure after call */
val = strtoll(str, &endptr, base);
if (endptr == str) {
throw TypeError::New(env, "writeInt64: no digits we found in input String");
} else if (errno == ERANGE && (val == INT64_MAX || val == INT64_MIN)) {
throw TypeError::New(env, "writeInt64: input String numerical value out of range");
} else if (errno != 0 && val == 0) {
char errmsg[200];
snprintf(errmsg, sizeof(errmsg), "writeInt64: %s", strerror(errno));
throw TypeError::New(env, errmsg);
}
} else {
throw TypeError::New(env, "writeInt64: Number/String 64-bit value required");
}
*reinterpret_cast<int64_t*>(ptr) = val;
}
/**
* Reads a machine-endian uint64_t from the given Buffer at the given offset.
*
* args[0] - Buffer - the "buf" Buffer instance to read from
* args[1] - Number - the offset from the "buf" buffer's address to read from
*/
Value ReadUInt64(const CallbackInfo& args) {
Env env = args.Env();
char* ptr = AddressForArgs(args);
if (ptr == nullptr) {
throw TypeError::New(env, "readUInt64: Cannot read from nullptr pointer");
}
uint64_t val = *reinterpret_cast<uint64_t*>(ptr);
if (val > JS_MAX_INT) {
char strbuf[128];
snprintf(strbuf, 128, "%" PRIu64, val);
return String::New(env, strbuf);
} else {
return Number::New(env, val);
}
}
/**
* Writes the input Number/String uint64 value as a machine-endian uint64_t to
* the given Buffer at the given offset.
*
* args[0] - Buffer - the "buf" Buffer instance to write to
* args[1] - Number - the offset from the "buf" buffer's address to write to
* args[2] - String/Number - the "input" String or Number which will be written
*/
void WriteUInt64(const CallbackInfo& args) {
Env env = args.Env();
char* ptr = AddressForArgs(args);
Value in = args[2];
uint64_t val;
if (in.IsNumber()) {
val = static_cast<int64_t>(in.As<Number>());
} else if (in.IsString()) {
char* endptr;
char* str;
int base = 0;
std::string _str = in.As<String>();
str = &_str[0];
errno = 0; /* To distinguish success/failure after call */
val = strtoull(str, &endptr, base);
if (endptr == str) {
throw TypeError::New(env, "writeUInt64: no digits we found in input String");
} else if (errno == ERANGE && (val == UINT64_MAX)) {
throw TypeError::New(env, "writeUInt64: input String numerical value out of range");
} else if (errno != 0 && val == 0) {
char errmsg[200];
snprintf(errmsg, sizeof(errmsg), "writeUInt64: %s", strerror(errno));
throw TypeError::New(env, errmsg);
}
} else {
throw TypeError::New(env, "writeUInt64: Number/String 64-bit value required");
}
*reinterpret_cast<uint64_t*>(ptr) = val;
}
/**
* Reads a Utf8 C String from the given pointer at the given offset (or 0).
* I didn't want to add this function but it ends up being necessary for reading
* past a 0 or 1 length Buffer's boundary in node-ffi :\
*
* args[0] - Buffer - the "buf" Buffer instance to read from
* args[1] - Number - the offset from the "buf" buffer's address to read from
*/
Value ReadCString(const CallbackInfo& args) {
Env env = args.Env();
char* ptr = AddressForArgs(args);
if (ptr == nullptr) {
throw Error::New(env, "readCString: Cannot read from nullptr pointer");
}
return String::New(env, ptr);
}
/**
* Returns a new Buffer instance that has the same memory address
* as the given buffer, but with the specified size.
*
* args[0] - Buffer - the "buf" Buffer instance to read the address from
* args[1] - Number - the size in bytes that the returned Buffer should be
* args[2] - Number - the offset from the "buf" buffer's address to read from
*/
Value ReinterpretBuffer(const CallbackInfo& args) {
Env env = args.Env();
char* ptr = AddressForArgs(args, 2);
if (ptr == nullptr) {
throw Error::New(env, "reinterpret: Cannot reinterpret from nullptr pointer");
}
int64_t size = args[1].ToNumber();
return WrapPointer(env, ptr, size);
}
/**
* Returns a new Buffer instance that has the same memory address
* as the given buffer, but with a length up to the first aligned set of values of
* 0 in a row for the given length.
*
* args[0] - Buffer - the "buf" Buffer instance to read the address from
* args[1] - Number - the number of sequential 0-byte values that need to be read
* args[2] - Number - the offset from the "buf" buffer's address to read from
*/
Value ReinterpretBufferUntilZeros(const CallbackInfo& args) {
Env env = args.Env();
char* ptr = AddressForArgs(args, 2);
if (ptr == nullptr) {
throw Error::New(env, "reinterpretUntilZeros: Cannot reinterpret from nullptr pointer");
}
uint32_t numZeros = args[1].ToNumber();
uint32_t i = 0;
size_t size = 0;
bool end = false;
while (!end && size < kMaxLength) {
end = true;
for (i = 0; i < numZeros; i++) {
if (ptr[size + i] != 0) {
end = false;
break;
}
}
if (!end) {
size += numZeros;
}
}
return WrapPointer(env, ptr, size);
}
} // anonymous namespace
Object Init(Env env, Object exports) {
InstanceData* data = new InstanceData(env);
{
Value buffer_ctor = env.Global()["Buffer"];
Value buffer_from = buffer_ctor.As<Object>()["from"];
data->buffer_from.Reset(buffer_from.As<Function>(), 1);
assert(!data->buffer_from.IsEmpty());
napi_status status = napix_set_instance_data(
env, data, [](napi_env env, void* data, void* hint) {
delete static_cast<InstanceData*>(data);
}, nullptr);
if (status != napi_ok) {
delete data;
data = nullptr;
} else {
// Hack around the fact that we can't reset buffer_from from the
// InstanceData dtor.
buffer_from.As<Object>().AddFinalizer([](Env env, InstanceData* data) {
data->buffer_from.Reset();
}, data);
}
}
exports["instance"] = External<RefNapi::Instance>::New(env, data);
// "sizeof" map
Object smap = Object::New(env);
// fixed sizes
#define SET_SIZEOF(name, type) \
smap[ #name ] = Number::New(env, sizeof(type));
SET_SIZEOF(int8, int8_t);
SET_SIZEOF(uint8, uint8_t);
SET_SIZEOF(int16, int16_t);
SET_SIZEOF(uint16, uint16_t);
SET_SIZEOF(int32, int32_t);
SET_SIZEOF(uint32, uint32_t);
SET_SIZEOF(int64, int64_t);
SET_SIZEOF(uint64, uint64_t);
SET_SIZEOF(float, float);
SET_SIZEOF(double, double);
// (potentially) variable sizes
SET_SIZEOF(bool, bool);
SET_SIZEOF(byte, unsigned char);
SET_SIZEOF(char, char);
SET_SIZEOF(uchar, unsigned char);
SET_SIZEOF(short, short);
SET_SIZEOF(ushort, unsigned short);
SET_SIZEOF(int, int);
SET_SIZEOF(uint, unsigned int);
SET_SIZEOF(long, long);
SET_SIZEOF(ulong, unsigned long);
SET_SIZEOF(longlong, long long);
SET_SIZEOF(ulonglong, unsigned long long);
SET_SIZEOF(pointer, char *);
SET_SIZEOF(size_t, size_t);
// size of a weak handle to a JS object
SET_SIZEOF(Object, Reference<Object>);
// "alignof" map
Object amap = Object::New(env);
#define SET_ALIGNOF(name, type) \
struct s_##name { type a; }; \
amap[ #name ] = Number::New(env, alignof(struct s_##name));
SET_ALIGNOF(int8, int8_t);
SET_ALIGNOF(uint8, uint8_t);
SET_ALIGNOF(int16, int16_t);
SET_ALIGNOF(uint16, uint16_t);
SET_ALIGNOF(int32, int32_t);
SET_ALIGNOF(uint32, uint32_t);
SET_ALIGNOF(int64, int64_t);
SET_ALIGNOF(uint64, uint64_t);
SET_ALIGNOF(float, float);
SET_ALIGNOF(double, double);
SET_ALIGNOF(bool, bool);
SET_ALIGNOF(char, char);
SET_ALIGNOF(uchar, unsigned char);
SET_ALIGNOF(short, short);
SET_ALIGNOF(ushort, unsigned short);
SET_ALIGNOF(int, int);
SET_ALIGNOF(uint, unsigned int);
SET_ALIGNOF(long, long);
SET_ALIGNOF(ulong, unsigned long);
SET_ALIGNOF(longlong, long long);
SET_ALIGNOF(ulonglong, unsigned long long);
SET_ALIGNOF(pointer, char *);
SET_ALIGNOF(size_t, size_t);
SET_ALIGNOF(Object, Reference<Object>);
// exports
exports["sizeof"] = smap;
exports["alignof"] = amap;
exports["nullptr"] = exports["NULL"] = WrapPointer(env, nullptr, 0);
exports["address"] = Function::New(env, Address);
exports["hexAddress"] = Function::New(env, HexAddress);
exports["isNull"] = Function::New(env, IsNull);
exports["readObject"] = Function::New(env, ReadObject);
exports["writeObject"] = Function::New(env, WriteObject);
exports["readPointer"] = Function::New(env, ReadPointer);
exports["writePointer"] = Function::New(env, WritePointer);
exports["readInt64"] = Function::New(env, ReadInt64);
exports["writeInt64"] = Function::New(env, WriteInt64);
exports["readUInt64"] = Function::New(env, ReadUInt64);
exports["writeUInt64"] = Function::New(env, WriteUInt64);
exports["readCString"] = Function::New(env, ReadCString);
exports["reinterpret"] = Function::New(env, ReinterpretBuffer);
exports["reinterpretUntilZeros"] = Function::New(env, ReinterpretBufferUntilZeros);
return exports;
}
NODE_API_MODULE(binding, Init)
| 21,487 | 7,520 |
#include <iostream>
#include "src/codegen/helpers.h"
namespace re2c {
static bool is_space(uint32_t c)
{
switch (c) {
case '\t':
case '\f':
case '\v':
case '\n':
case '\r':
case ' ': return true;
default: return false;
}
}
static inline char hex(uint32_t c)
{
static const char * sHex = "0123456789ABCDEF";
return sHex[c & 0x0F];
}
static void prtCh(std::ostream& o, uint32_t c, bool dot)
{
switch (c) {
case '\'': o << (dot ? "'" : "\\'"); break;
case '"': o << (dot ? "\\\"" : "\""); break;
case '\n': o << (dot ? "\\\\n" : "\\n"); break;
case '\t': o << (dot ? "\\\\t" : "\\t"); break;
case '\v': o << (dot ? "\\\\v" : "\\v"); break;
case '\b': o << (dot ? "\\\\b" : "\\b"); break;
case '\r': o << (dot ? "\\\\r" : "\\r"); break;
case '\f': o << (dot ? "\\\\f" : "\\f"); break;
case '\a': o << (dot ? "\\\\a" : "\\a"); break;
case '\\': o << "\\\\"; break; // both .dot and C/C++ code expect "\\"
default: o << static_cast<char> (c); break;
}
}
bool is_print(uint32_t c)
{
return c >= 0x20 && c < 0x7F;
}
void prtHex(std::ostream& o, uint32_t c, uint32_t szcunit)
{
o << "0x";
if (szcunit >= 4) {
o << hex(c >> 28u) << hex(c >> 24u) << hex(c >> 20u) << hex(c >> 16u);
}
if (szcunit >= 2) {
o << hex(c >> 12u) << hex(c >> 8u);
}
o << hex(c >> 4u) << hex(c);
}
void prtChOrHex(std::ostream& o, uint32_t c, uint32_t szcunit, bool ebcdic, bool dot)
{
if (!ebcdic && (is_print(c) || is_space(c))) {
o << '\'';
prtCh(o, c, dot);
o << '\'';
} else {
prtHex(o, c, szcunit);
}
}
static void prtChOrHexForSpan(std::ostream& o, uint32_t c, uint32_t szcunit, bool ebcdic, bool dot)
{
if (!ebcdic && c != ']' && is_print(c)) {
prtCh(o, c, dot);
} else {
prtHex(o, c, szcunit);
}
}
void printSpan(std::ostream& o, uint32_t l, uint32_t u, uint32_t szcunit, bool ebcdic, bool dot)
{
o << "[";
prtChOrHexForSpan(o, l, szcunit, ebcdic, dot);
if (u - l > 1) {
o << "-";
prtChOrHexForSpan(o, u - 1, szcunit, ebcdic, dot);
}
o << "]";
}
} // namespace re2c
| 2,233 | 1,011 |
#include <iostream>
using namespace std;
int main() {
char g;
cout<<"Input the grade : ";
cin>>g;
if(g=='E'){
cout<<"Excellent\n";
}
else if(g=='V'){
cout<<"Very Good\n";
}
else if(g=='G'){
cout<<"Good\n";
}
else if(g=='A'){
cout<<"Average\n";
}
else{
cout<<"Fail\n";
}
}
| 311 | 140 |
/*
* main.cpp
*
* Created on: Sep 10, 2021
* Author: djek-sweng
*/
#include "Command.h"
#include "CommandGetVersion.h"
#include "CommandGetSessionId.h"
#include "CommandFlashUnlock.h"
#include "CommandFlashLock.h"
#include "CommandFlashErase.h"
#include "CommandMemoryRead.h"
#include "CommandMemoryWrite.h"
#include "CommandSystemReset.h"
using namespace Bootloader;
int main(int argc, char** argv)
{
for (int i=0; i<argc; ++i)
{
cout << argv[i] << endl;
}
char* device = argv[1];
int select = atoi(argv[2]);
int param_0 = 0;/* argv[3] */
int param_1 = 0;/* argv[4] */
uint32_t baudRate = 115200;
Command* command;
int result;
switch (select)
{
case 1:
{
command = new CommandGetSessionId(device, baudRate);
break;
}
case 2:
{
command = new CommandFlashUnlock(device, baudRate);
break;
}
case 3:
{
command = new CommandFlashLock(device, baudRate);
break;
}
case 4:
{
param_0 = 0x20000000;
param_1 = 0x40;
command = (Command*)(new CommandMemoryRead(device, baudRate))
->SetAddress(param_0)
->SetLength(param_1);
break;
}
case 5:
{
param_0 = 4;
param_1 = 4;
command = (Command*)(new CommandFlashErase(device, baudRate))
->SetSector(param_0)
->SetTotalNumber(param_1);
break;
}
case 6:
{
param_0 = 2000;
command = (Command*)(new CommandSystemReset(device, baudRate))
->SetDelay(param_0);
break;
}
case 7:
{
param_0 = 0x08010000;
param_1 = 4;
uint8_t buffer[4] = {0xde, 0xad, 0xbe, 0xef};
command = (Command*)(new CommandMemoryWrite(device, baudRate))
->SetAddress(param_0)
->SetLength(param_1)
->SetBuffer(&buffer[0]);
break;
}
case 0:
default:
{
command = new CommandGetVersion(device, baudRate);
break;
}
}
result = command->Execute();
command->Close();
return result;
}
| 2,170 | 805 |
#include "CameraSystemProcessor.h"
namespace chaoskit::core {
void CameraSystemProcessor::setCameraSystem(const CameraSystem& cameraSystem) {
setSystem(cameraSystem.system);
setCamera(cameraSystem.camera);
}
SystemParticle CameraSystemProcessor::processCamera(
SystemParticle input) const {
if (!camera_) return input;
SystemParticle output = input;
output.applyParticle(interpreter_.interpret(
input.asParticle(), camera_->transform, camera_->params));
return output;
}
} // namespace chaoskit::core
| 529 | 152 |
/*
The MIT License (MIT)
Copyright (c) 2015 Dennis Wandschura
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "TextRenderer.h"
#include <vxLib/File/FileHandle.h>
#include "ResourceDesc.h"
#include "d3d.h"
#include <vxlib/Graphics/Font.h>
#include <vxlib/Graphics/Texture.h>
#include "UploadManager.h"
#include <gamelib/MainAllocator.h>
#include "GpuResourceManager.h"
//#include "RenderPassText.h"
//#include "ResourceView.h"
namespace Graphics
{
struct TextRenderer::Entry
{
char m_text[48];
vx::float4 m_color;
vx::float2 m_position;
u32 m_size;
};
struct TextRenderer::TextVertex
{
vx::float3 position;
vx::float2 uv;
vx::float4 color;
};
TextRenderer::TextRenderer()
:m_entries(),
m_vertices(),
m_drawTextProgram(nullptr),
m_size(0),
m_capacity(0),
m_texureIndex(0),
m_font(nullptr)
{
}
TextRenderer::~TextRenderer()
{
}
void TextRenderer::getRequiredMemory(u64* bufferSize, u32* bufferCount, u64* textureSize, u32*textureCount, ID3D12Device* device, u32 maxCharacters)
{
const auto verticesPerCharacter = 4u;
auto totalVertexCount = verticesPerCharacter * maxCharacters;
const auto indicesPerCharacter = 6u;
auto indexCount = indicesPerCharacter * maxCharacters;
auto vertexSizeInBytes = totalVertexCount * sizeof(TextVertex);
auto indexSizeInBytes = indexCount * sizeof(u32);
auto fontTexResDesc = d3d::ResourceDesc::createDescTexture2D(vx::uint3(1024, 1024, 1), DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, D3D12_RESOURCE_FLAG_NONE);
auto fontTexAllocInfo = device->GetResourceAllocationInfo(1, 1,&fontTexResDesc);
*textureSize += fontTexAllocInfo.SizeInBytes;
*bufferSize += vx::getAlignedSize(vertexSizeInBytes, 64llu KBYTE) + vx::getAlignedSize(indexSizeInBytes, 64llu KBYTE);
*bufferCount += 2;
*textureCount += 1;
}
bool TextRenderer::createData(ID3D12Device* device, GpuResourceManager* resourceManager, UploadManager* uploadManager, u32 maxCharacters)
{
//auto fontTexResDesc = d3d::ResourceDesc::createDescTexture2D(vx::uint3(1024, 1024, 3), DXGI_FORMAT_R8G8B8A8_UNORM_SRGB);
//auto fontTexAllocInfo = device->GetResourceAllocationInfo(1, 1, &fontTexResDesc);
const auto verticesPerCharacter = 4u;
auto totalVertexCount = verticesPerCharacter * maxCharacters;
const auto indicesPerCharacter = 6u;
auto indexCount = indicesPerCharacter * maxCharacters;
auto vertexSizeInBytes = vx::getAlignedSize(vx::getAlignedSize(totalVertexCount * sizeof(TextVertex), 256) * 2, 64llu KBYTE);
auto indexSizeInBytes = vx::getAlignedSize(vx::getAlignedSize(indexCount * sizeof(u32), 256), 64llu KBYTE);
if(!resourceManager->createTextureResource("fontTexture", vx::uint3(1024, 1024, 1), DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, nullptr))
{
return false;
}
if (!resourceManager->createBufferResource("textVertexBuffer", vertexSizeInBytes, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER))
{
return false;
}
if (!resourceManager->createBufferResource("textIndexBuffer", indexSizeInBytes, D3D12_RESOURCE_STATE_INDEX_BUFFER))
{
return false;
}
return true;
}
bool TextRenderer::initialize(u32 maxCharacters, Allocator::MainAllocator* allocator, UploadManager* uploadManager, ID3D12Device* device, GpuResourceManager* resourceManager, DrawTextProgram* drawTextProgram)
{
m_capacity = maxCharacters;
if (!createData(device, resourceManager, uploadManager, maxCharacters))
return false;
vx::array<Entry, DebugAllocatorRenderer<Allocator::MainAllocator>> entries(allocator, s_maxEntryCount);
m_entries.swap(entries);
const auto verticesPerCharacter = 4u;
auto totalVertexCount = verticesPerCharacter * m_capacity;
const auto indicesPerCharacter = 6u;
auto indexCount = indicesPerCharacter * m_capacity;
//auto vertexSizeInBytes = vx::getAlignedSize(totalVertexCount * sizeof(TextVertex), 64llu KBYTE);
//auto indexSizeInBytes = (indexCount * sizeof(u32), 64llu KBYTE);
/*
m_renderPassText = desc->m_renderPassText;
auto textVertexBuffer = desc->resourceManager->getBuffer(L"textVertexBuffer");
d3d::ResourceView vbv;
vbv.vbv.BufferLocation = textVertexBuffer->GetGPUVirtualAddress();
vbv.vbv.SizeInBytes = vertexSizeInBytes;
vbv.vbv.StrideInBytes = sizeof(TextVertex);
vbv.type = d3d::ResourceView::Type::VertexBufferView;
desc->resourceManager->insertResourceView("textVbv", vbv);
auto textIndexBuffer = desc->resourceManager->getBuffer(L"textIndexBuffer");
d3d::ResourceView textIbv;
textIbv.type = d3d::ResourceView::Type::IndexBufferView;
textIbv.ibv.BufferLocation = textIndexBuffer->GetGPUVirtualAddress();
textIbv.ibv.Format = DXGI_FORMAT_R32_UINT;
textIbv.ibv.SizeInBytes = indexSizeInBytes;
desc->resourceManager->insertResourceView("textIbv", textIbv);*/
vx::array<TextVertex, DebugAllocatorRenderer<Allocator::MainAllocator>> vertices(allocator, totalVertexCount);
m_vertices.swap(vertices);
/*auto indexDataSize = sizeof(u32) * indexCount;
auto indexBlock = allocator->allocate(indexDataSize, __alignof(u32), Allocator::Channels::Renderer, "text renderer indices");
auto incides = (u32*)indexBlock.ptr;
for (u32 i = 0, j = 0; i < indexCount; i += 6, j += 4)
{
incides[i] = j;
incides[i + 1] = j + 1;
incides[i + 2] = j + 2;
incides[i + 3] = j + 2;
incides[i + 4] = j + 3;
incides[i + 5] = j;
}
auto uploaded = uploadManager->pushUploadBuffer((u8*)incides, indexDataSize, 0, resourceManager->findBufferResource("textIndexBuffer"), 0, D3D12_RESOURCE_STATE_INDEX_BUFFER);
VX_ASSERT(uploaded);
auto indexSubBufferOffset = vx::getAlignedSize(indexDataSize, 256);
uploaded = uploadManager->pushUploadBuffer((u8*)incides, indexDataSize, indexSubBufferOffset, resourceManager->findBufferResource("textIndexBuffer"), D3D12_RESOURCE_STATE_INDEX_BUFFER);
VX_ASSERT(uploaded);
allocator->deallocate(indexBlock, Allocator::Channels::Renderer, "text renderer indices");*/
m_drawTextProgram = drawTextProgram;
return true;
}
void TextRenderer::shutdown()
{
m_vertices.release();
m_entries.release();
}
void TextRenderer::pushEntry(const char(&text)[48], u32 strSize, const vx::float2 &topLeftPosition, const vx::float3 &color)
{
VX_ASSERT(m_entries.size() < s_maxEntryCount);
Entry entry;
strncpy(entry.m_text, text, 48);
entry.m_position = topLeftPosition;
entry.m_color = vx::float4(color, 1.0f);
entry.m_size = strSize;
m_entries.push_back(entry);
m_size += strSize;
}
void TextRenderer::update(UploadManager* uploadManager, GpuResourceManager* resourceManager, bool upload)
{
if (m_size == 0 || m_font == nullptr)
return;
if (upload)
{
updateVertexBuffer(uploadManager, resourceManager);
m_entries.clear();
}
m_size = 0;
}
void TextRenderer::updateVertexBuffer(UploadManager* uploadManager, GpuResourceManager* resourceManager)
{
u32 offset = 0;
auto fontTexture = m_font->getTexture();
auto textureSize = fontTexture->getFace(0).getDimension().x;
vx::float4a invTextureSize;
invTextureSize.x = 1.0f / textureSize;
auto vInvTexSize = _mm_shuffle_ps(invTextureSize.v, invTextureSize.v, _MM_SHUFFLE(0, 0, 0, 0));
auto entryCount = m_entries.size();
auto entries = m_entries.data();
for (u32 i = 0; i < entryCount; ++i)
{
writeEntryToVertexBuffer(vInvTexSize, entries[i], &offset, textureSize);
}
if (offset != 0)
{
/*auto indexCount = offset * 6;
auto vertexCount = offset * 4;
auto textVertexBuffer = resourceManager->getBuffer(L"textVertexBuffer");
uploadManager->pushUploadBuffer((u8*)m_vertices.get(), textVertexBuffer->get(), 0, sizeof(TextVertex) * vertexCount, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER);
m_renderPassText->setIndexCount(indexCount);*/
}
}
void TextRenderer::writeEntryToVertexBuffer(const __m128 invTextureSize, const Entry &entry, u32* offset, u32 textureSize)
{
auto entryText = entry.m_text;
auto entryTextSize = entry.m_size;
auto entryOrigin = entry.m_position;
auto entryColor = vx::loadFloat4(&entry.m_color);
auto currentSize = m_size;
if (currentSize + entryTextSize >= m_capacity)
return;
u32 vertexOffset = (*offset) * 4;
*offset += entryTextSize;
auto vertices = &m_vertices[vertexOffset];
u32 vertexIndex = 0;
const f32 scale = 0.25f;
const __m128 vScale = { scale, scale, 0, 0 };
const __m128 tmp = { -1.0f, 0, 0, 0 };
auto cursorPosition = entryOrigin;
for (u32 i = 0; i < entryTextSize; ++i)
{
char ascii_code = entryText[i];
if (ascii_code == '\n')
{
cursorPosition.y -= 53.0f * scale;
cursorPosition.x = entryOrigin.x;
}
else
{
__m128 vCursorPos = { cursorPosition.x, cursorPosition.y, 0.0f, 0.0f };
auto pAtlasEntry = m_font->getAtlasEntry(ascii_code);
vx::float4a texRect(pAtlasEntry->x, textureSize - pAtlasEntry->y - pAtlasEntry->height, pAtlasEntry->width, pAtlasEntry->height);
__m128 vAtlasPos = { pAtlasEntry->offsetX, pAtlasEntry->offsetY, 0.0f, 0.0f };
__m128 vEntrySize = { texRect.z, -texRect.w, 0.0f, 0.0f };
__m128 vCurrentPosition = _mm_div_ps(vEntrySize, vx::g_VXTwo);
vCurrentPosition = _mm_add_ps(vCurrentPosition, vAtlasPos);
vCurrentPosition = vx::fma(vCurrentPosition, vScale, vCursorPos);
vCurrentPosition = _mm_movelh_ps(vCurrentPosition, tmp);
__m128 vSource = _mm_mul_ps(texRect, invTextureSize);
__m128 vSourceSize = _mm_shuffle_ps(vSource, vSource, _MM_SHUFFLE(3, 2, 3, 2));
static const __m128 texOffsets[4] =
{
{ 0, 0, 0, 0 },
{ 1, 0, 0, 0 },
{ 1, 1, 0, 0 },
{ 0, 1, 0, 0 }
};
static const __m128 posOffsets[4] =
{
{ -0.5f, -0.5f, 0, 0 },
{ 0.5f, -0.5f, 0, 0 },
{ 0.5f, 0.5f, 0, 0 },
{ -0.5f, 0.5f, 0, 0 }
};
vEntrySize = _mm_shuffle_ps(texRect, texRect, _MM_SHUFFLE(3, 2, 3, 2));
for (u32 k = 0; k < 4; ++k)
{
u32 index = vertexIndex + k;
auto pos = _mm_mul_ps(posOffsets[k], vEntrySize);
pos = vx::fma(pos, vScale, vCurrentPosition);
_mm_storeu_ps(&vertices[index].position.x, pos);
__m128 uv = vx::fma(texOffsets[k], vSourceSize, vSource);
_mm_storeu_ps(&vertices[index].uv.x, uv);
_mm_storeu_ps(&vertices[index].color.x, entryColor);
}
vertexIndex += 4;
cursorPosition.x = fmaf(pAtlasEntry->advanceX, scale, cursorPosition.x);
}
}
}
} | 11,356 | 4,679 |
// MIT License
//
// Copyright 2018 Abdelkader Amar
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include "util/fix_env.hxx"
#include "fixml/fixml_xsd_parser.hxx"
#include <boost/log/trivial.hpp>
using namespace fix2xml;
using namespace std;
int usage(const int ret) {
static string text = "Usage: xsd_parser {xsd_files}";
if (ret == 0) BOOST_LOG_TRIVIAL(info) << text;
else BOOST_LOG_TRIVIAL(error) << text;
return ret;
}
int main(int argc, char *argv[])
{
if (argc < 2) return usage(1);
if ( ! fix_env::init_xerces()) {
BOOST_LOG_TRIVIAL(error) << "Failed to initialize xerces environment";
return 1;
}
BOOST_LOG_TRIVIAL(info) << "xerces environment initialized";
{
fixml_xsd_parser parser;
BOOST_LOG_TRIVIAL(info) << "xsd parser created";
if (parser.parse(argv[1])) BOOST_LOG_TRIVIAL(info) << "parsing " << argv[1] << " done";
else BOOST_LOG_TRIVIAL(error) << "parsing " << argv[1] << " failed";
}
fix_env::terminate_xerces();
return 0;
}
| 2,036 | 736 |
// Copyright (c) 2012-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <policy/policy.h>
#include <script/interpreter.h>
#include <script/script.h>
#include <test/lcg.h>
#include <test/util/setup_common.h>
#include <boost/test/unit_test.hpp>
#include <core_io.h>
#include <util/strencodings.h>
BOOST_FIXTURE_TEST_SUITE(op_rawleftbitshift_tests, BasicTestingSetup)
typedef std::vector<uint8_t> valtype;
typedef std::vector<valtype> stacktype;
std::array<uint32_t, 2> flagset{{0, STANDARD_SCRIPT_VERIFY_FLAGS}};
static valtype FromUint64(uint64_t num) {
valtype num_item;
num_item.reserve(8);
for (int i = 7; i >= 0; --i) {
num_item.push_back((num >> (i * 8)) & 0xff);
}
return num_item;
}
static void CheckTestResultForAllFlags(const stacktype &original_stack,
const CScript &script,
const stacktype &expected) {
BaseSignatureChecker sigchecker;
for (uint32_t flags : flagset) {
ScriptError err = ScriptError::OK;
stacktype stack{original_stack};
bool r = EvalScript(stack, script, flags, sigchecker, &err);
BOOST_CHECK_MESSAGE(r, "Expected success but got failure for '"
<< ScriptToAsmStr(script) << "'");
BOOST_CHECK_MESSAGE(stack == expected,
"Expected stacks to be equal for '"
<< ScriptToAsmStr(script) << "'");
}
}
static void CheckTestLeftShift(const valtype &num, int32_t shift,
const valtype &expected) {
valtype test_num;
valtype test_expected;
test_num.reserve(num.size());
test_expected.reserve(num.size());
for (int i = num.size() - 1; i >= 0; --i) {
test_num.insert(test_num.begin(), num[i]);
test_expected.insert(test_expected.begin(), expected[i]);
CheckTestResultForAllFlags({test_num},
CScript() << shift << OP_RAWLEFTBITSHIFT,
{test_expected});
}
}
static void CheckTestRightShift(const valtype &num, int32_t shift,
const valtype &expected) {
valtype test_num;
valtype test_expected;
test_num.reserve(num.size());
test_expected.reserve(num.size());
for (size_t i = 0; i < num.size(); ++i) {
test_num.push_back(num[i]);
test_expected.push_back(expected[i]);
CheckTestResultForAllFlags({test_num},
CScript() << -shift << OP_RAWLEFTBITSHIFT,
{test_expected});
}
}
static void CheckTestU64Shift(uint64_t num, int32_t shift) {
valtype num_encoded = FromUint64(num);
valtype right_shifted_encoded = FromUint64(shift < 64 ? num >> shift : 0);
valtype left_shifted_encoded = FromUint64(shift < 64 ? num << shift : 0);
CheckTestRightShift(num_encoded, shift, right_shifted_encoded);
CheckTestLeftShift(num_encoded, shift, left_shifted_encoded);
}
static void CheckTestRightShiftHex(std::string num_hex, int32_t shift,
std::string expected_hex) {
CheckTestRightShift(ParseHex(num_hex), shift, ParseHex(expected_hex));
}
static void CheckTestLeftShiftHex(std::string num_hex, int32_t shift,
std::string expected_hex) {
CheckTestLeftShift(ParseHex(num_hex), shift, ParseHex(expected_hex));
}
BOOST_AUTO_TEST_CASE(u64_shift_test) {
MMIXLinearCongruentialGenerator lcg;
for (int test = 0; test < 20; ++test) {
uint64_t num = lcg.next();
num <<= 32;
num |= lcg.next();
for (uint32_t i = 0; i <= 100; ++i) {
CheckTestU64Shift(num, i);
}
}
}
BOOST_AUTO_TEST_CASE(left_shift_test) {
CheckTestLeftShiftHex("", 0, "");
CheckTestLeftShiftHex("", 1, "");
CheckTestLeftShiftHex("63", 0, "63");
CheckTestLeftShiftHex("63", 1, "c6");
CheckTestLeftShiftHex("63", 2, "8c");
CheckTestLeftShiftHex("63", 3, "18");
CheckTestLeftShiftHex("63", 4, "30");
CheckTestLeftShiftHex("63", 5, "60");
CheckTestLeftShiftHex("63", 6, "c0");
CheckTestLeftShiftHex("63", 7, "80");
CheckTestLeftShiftHex("63", 8, "00");
CheckTestLeftShiftHex("6347", 0, "6347");
CheckTestLeftShiftHex("6347", 1, "c68e");
CheckTestLeftShiftHex("6347", 7, "a380");
CheckTestLeftShiftHex("6347", 8, "4700");
CheckTestLeftShiftHex("6347", 9, "8e00");
CheckTestLeftShiftHex(
"ebd076435d1fe29d4bc6165d49e32b2d88d58919a8106bcc9afaeda9137c10ee7131b2"
"f45d61b781b9c1d29f8f87c8be440a27379ada1e811fd3cc9cdd06fb139d1c3e01becb"
"e8be85da9657859766de3add40b1f7345056866f33dc6ef85ec89e7d02805eca428195"
"31cc4fe5c2e692f1fa9f39e7f85eba444e378e024c693e089fbb46fe36781e36ce5be1"
"068b2f36cf9cd6dcd0bc480e53549bde70a3560e32dcc697299a0bdad2fcdf869bcf56"
"45aa5baa5b8560a3b7368072e2d4f4dee7a07b0c0d747089827c09f6dbf866f8f7d94a"
"8c3592e9d1bca02a9686cc3cb2eb3b6c932d1905f832e40d4559095a416d0e74c7259c"
"266b0ad9b18f12571093ec026ecb1d7e942228e5058f2d3c9b591cb79e4a53f84499b9"
"dda1f4bf26047ab591670c3b8939759f942f3ac4d6754a88a3c909126823dc4241ecea"
"de263e9e6ae603126eb7d6ca9510184a70effb2f424079237bc7e1243438dc44ae7467"
"f49cb3f46cfc5c98a72fe8b3a45c6e60f83444c5ba911596b82359b807271d0d3d8cd5"
"e6d5dca1034de6572306407e9e248f7edd6add140fd61709b040c0b44b2cf24e9207ba"
"2fbe5b851764485541cd8ad0e35c9bf6dc27579141dc8c6e1d6b96de06fca85b248dc1"
"36906eab64287864fd3dba3d3b8483e24495ae0e19471d0f51d847e7c5b088081e491c"
"fa39ae48eae4392fe499af54c0d6adc47deed067d106a129fbc7bd7f612e",
1,
"d7a0ec86ba3fc53a978c2cba93c6565b11ab12335020d79935f5db5226f821dce26365"
"e8bac36f037383a53f1f0f917c88144e6f35b43d023fa79939ba0df6273a387c037d97"
"d17d0bb52caf0b2ecdbc75ba8163ee68a0ad0cde67b8ddf0bd913cfa0500bd9485032a"
"63989fcb85cd25e3f53e73cff0bd74889c6f1c0498d27c113f768dfc6cf03c6d9cb7c2"
"0d165e6d9f39adb9a178901ca6a937bce146ac1c65b98d2e533417b5a5f9bf0d379eac"
"8b54b754b70ac1476e6d00e5c5a9e9bdcf40f6181ae8e11304f813edb7f0cdf1efb295"
"186b25d3a37940552d0d987965d676d9265a320bf065c81a8ab212b482da1ce98e4b38"
"4cd615b3631e24ae2127d804dd963afd284451ca0b1e5a7936b2396f3c94a7f0893373"
"bb43e97e4c08f56b22ce18771272eb3f285e7589acea951147921224d047b88483d9d5"
"bc4c7d3cd5cc0624dd6fad952a203094e1dff65e8480f246f78fc2486871b8895ce8cf"
"e93967e8d9f8b9314e5fd16748b8dcc1f068898b75222b2d7046b3700e4e3a1a7b19ab"
"cdabb942069bccae460c80fd3c491efdbad5ba281fac2e13608181689659e49d240f74"
"5f7cb70a2ec890aa839b15a1c6b937edb84eaf2283b918dc3ad72dbc0df950b6491b82"
"6d20dd56c850f0c9fa7b747a770907c4892b5c1c328e3a1ea3b08fcf8b6110103c9239"
"f4735c91d5c8725fc9335ea981ad5b88fbdda0cfa20d4253f78f7afec25c");
CheckTestLeftShiftHex(
"2a467c005ae83afa9d8df8b13a0e0d6a3d085e8c71e4ea210ceeeb30c84cd771c5c226"
"45091dc8e91619c4525b5986db05e54174bdc02cc5b5bf12c22fe377b60615666595ba"
"323d6b4a2f354f68c93481884d7a6aba0d235e45262eeeb93c3453dcd52faf35fb569d"
"b221305dadbc74c55a40806d9838be5c42de74481450e6a672adbdddd8f541edc26b27"
"b15e5487da9ab8f7f335e1fc97d137466d97bc737c74ef8f4dfcbdb0d11268981c7a83"
"313ca63a67dac5ecda6c06e6d69eae5b51171d6d32e577bc9d13e14789a148a97c7755"
"0b2225aec7179491e0e5bc04a2aba3244d9431e5272714a0b78b6284d0fd4e6802ce98"
"0802ac9637a2140219781fddcf45652c518e6602e59a7f35bca10543ded6552559ae9d"
"de1a6dcb9e4a7812511ec18cc9a9f2740190010392ea45961ef78370ad6f5d8e7516cb"
"6db3516c14aa42ea63011d065cca4d7a23d1e0b196da933d474c058639dee71da091b3"
"ec86f4cb30ea66175725ccf5c9c99e8b30c4faa1a83cb095d5b55d3882cf5c545bb515"
"a3607c46d32792f207ff13123f08bc0fc1d2605a890ad31895c5b22c180deed8a4736d"
"891afdb0409e0402cd326f596fca4439b131e8251e1c0ef437be6832ead0e458c64388"
"87776adc2d0aa92bacac6303ca48f0c7b6c91282dea7b86d312e687582eadf90be7774"
"e7f70f9189abb9690a80bf333574f6b249eead1244b0d14fe69e7cb12f56",
2,
"a919f0016ba0ebea7637e2c4e83835a8f4217a31c793a88433bbacc321335dc7170899"
"14247723a4586711496d661b6c179505d2f700b316d6fc4b08bf8dded81855999656e8"
"c8f5ad28bcd53da324d2062135e9aae8348d791498bbbae4f0d14f7354bebcd7ed5a76"
"c884c176b6f1d315690201b660e2f9710b79d12051439a99cab6f77763d507b709ac9e"
"c579521f6a6ae3dfccd787f25f44dd19b65ef1cdf1d3be3d37f2f6c34449a26071ea0c"
"c4f298e99f6b17b369b01b9b5a7ab96d445c75b4cb95def2744f851e268522a5f1dd54"
"2c8896bb1c5e52478396f0128aae8c913650c7949c9c5282de2d8a1343f539a00b3a60"
"200ab258de88500865e07f773d1594b14639980b9669fcd6f284150f7b59549566ba77"
"7869b72e7929e049447b063326a7c9d00640040e4ba916587bde0dc2b5bd7639d45b2d"
"b6cd45b052a90ba98c047419732935e88f4782c65b6a4cf51d301618e77b9c768246cf"
"b21bd32cc3a9985d5c9733d727267a2cc313ea86a0f2c25756d574e20b3d71516ed456"
"8d81f11b4c9e4bc81ffc4c48fc22f03f0749816a242b4c625716c8b06037bb6291cdb6"
"246bf6c10278100b34c9bd65bf2910e6c4c7a09478703bd0def9a0cbab439163190e22"
"1dddab70b42aa4aeb2b18c0f2923c31edb244a0b7a9ee1b4c4b9a1d60bab7e42f9ddd3"
"9fdc3e4626aee5a42a02fcccd5d3dac927bab44912c3453f9a79f2c4bd58");
return;
CheckTestLeftShiftHex(
"a98494f07b4dab376b2ab766f30fca375985cdc9b5de0774a98618702da6939883fa98"
"baed23fbe29cda508742ebd2120da4f680b58f69d7368c2ffef15c3571ea7b19cfcbef"
"31fbc998fe5b3548b6b935e067f4b9778a883c164edbf0cd7c4a8c9c4b53e80a9d6517"
"438c5034a6fec75924e40722ac1622972bbafed27ee574443ab1028ca2120ff7727cbe"
"471f0493afe8c8f196aed1e1a571769b495ccb04c1e1c19bab7f22bc29adebf1cb505a"
"d4a659d42dc06458d463826178f0c60d2ef594d3c587f1eec3b0aff01be5fab31dfa65"
"93a5a0d5aa295891fbb3a9a8d18eda9a9b8d78cde2a3e868493365796ac496e27a7876"
"c8d7b3c6b292ff13be312f610afbf5509c618f7e9def06c6d7ae88b36227838d02a8d6"
"65a8259b0ba7644a9445bd0d237d4626ce9a67f1653862df093e6aa8b09717dde3917f"
"44a4e5f4c35d0cc6b58fad65c42a5b5fb9bcdf1f716caddc9c0be86ef1726762858986"
"f9aa901e5963f73bc2ca5fada5bd4b14febe10910c32c72daae28107a3cda032115601"
"7c5b8ed36dc486bf41b8cf6ea54f3bfee549c515552cabb1f0e67af5cead0e24557732"
"bedeb2d2a4c7f37693389d38fd994166fd733b5b50e4dfd6b2df1b84612ba7f329e5be"
"4131e46299656011308426fd1b900956c1ea4a726b850e806ee8afb1f1ab2054d8b80d"
"5664ede7f7d827e49a7bbadc3a06dd490045207937cc5ef43f4607b992d7",
3,
"4c24a783da6d59bb5955bb37987e51bacc2e6e4daef03ba54c30c3816d349cc41fd4c5"
"d7691fdf14e6d2843a175e90906d27b405ac7b4eb9b4617ff78ae1ab8f53d8ce7e5f79"
"8fde4cc7f2d9aa45b5c9af033fa5cbbc5441e0b276df866be25464e25a9f4054eb28ba"
"1c6281a537f63ac92720391560b114b95dd7f693f72ba221d588146510907fbb93e5f2"
"38f8249d7f46478cb5768f0d2b8bb4da4ae658260f0e0cdd5bf915e14d6f5f8e5a82d6"
"a532cea16e0322c6a31c130bc786306977aca69e2c3f8f761d857f80df2fd598efd32c"
"9d2d06ad514ac48fdd9d4d468c76d4d4dc6bc66f151f4342499b2bcb5624b713d3c3b6"
"46bd9e359497f89df1897b0857dfaa84e30c7bf4ef783636bd74459b113c1c681546b3"
"2d412cd85d3b2254a22de8691bea313674d33f8b29c316f849f3554584b8beef1c8bfa"
"25272fa61ae86635ac7d6b2e2152dafdcde6f8fb8b656ee4e05f43778b933b142c4c37"
"cd5480f2cb1fb9de1652fd6d2dea58a7f5f084886196396d5714083d1e6d01908ab00b"
"e2dc769b6e2435fa0dc67b752a79dff72a4e28aaa9655d8f8733d7ae75687122abb995"
"f6f59695263f9bb499c4e9c7ecca0b37eb99dada8726feb596f8dc23095d3f994f2df2"
"098f2314cb2b0089842137e8dc804ab60f5253935c28740377457d8f8d5902a6c5c06a"
"b3276f3fbec13f24d3ddd6e1d036ea48022903c9be62f7a1fa303dcc96b8");
CheckTestLeftShiftHex(
"98660ce335e12462fb5c2be76c46443825e3da19fc21a01b93271e5a9b7da55503b1de"
"3778909a36ce44ff4983706091dfcf49e5d2a4c3743fa1f5451b4a60c87836149758b1"
"01be65dfb2442a01e5203da712b205ea4d202dc6aecfeb76cf0ebff9977f1ef90cf419"
"80907d74c36e45d0804bc340058fa75f0941d4b68ad179830fc6a4e4abaa99eb9be486"
"cff2486a768135f227c01aa15bfe066fcd1a89c09d794489f836165072e68c422ca508"
"804909206d135cdc5f893b4a1a99ed9bda7eba63dbe7583b8d87b794b8230fd1b8597c"
"9c352d0fefb2526c78a536349c31df3da254666809ff3eb89737bcc901030cefe13955"
"d379f555d9295fc4b8c0d7089ed0c9856f48fcbbb9a011b26490e2b70eb4a15e60cc1f"
"2978c8e53b974a1323da9b9f1ca2db98079c8ab44c3d5086949752a3d8383cd62abd21"
"7725c3f930f1a8f40ea90499a8055b1bf46c1d59af3192e9b3fd79f6e858ebc4c1a9aa"
"654f3bea4e3030c0d898558d7d0b8394188c48cd92e2cd8b11cef98743ef724d374e9b"
"d9fa7f47a77444686d2f6c578febae518649dc14b333e8a5b199d9f98350e35cc59b56"
"437770d524ae262869ef97c9e70b897399dd3e1ca642b7a78675c51d0799a58e5fc299"
"29ef66bf9ef458101ad03bea6adbb7ef7222bf8e2b0836c77ce70ea3a71c568f309549"
"7924079c108268493e1606c67ffbe8dcfe84b3e2382dace9e3d4fe5a666d",
7,
"3306719af092317dae15f3b623221c12f1ed0cfe10d00dc9938f2d4dbed2aa81d8ef1b"
"bc484d1b67227fa4c1b83048efe7a4f2e95261ba1fd0faa28da530643c1b0a4bac5880"
"df32efd9221500f2901ed3895902f5269016e35767f5bb67875ffccbbf8f7c867a0cc0"
"483eba61b722e84025e1a002c7d3af84a0ea5b4568bcc187e3527255d54cf5cdf24367"
"f924353b409af913e00d50adff0337e68d44e04ebca244fc1b0b283973462116528440"
"2484903689ae6e2fc49da50d4cf6cded3f5d31edf3ac1dc6c3dbca5c1187e8dc2cbe4e"
"1a9687f7d929363c529b1a4e18ef9ed12a333404ff9f5c4b9bde6480818677f09caae9"
"bcfaaaec94afe25c606b844f6864c2b7a47e5ddcd008d93248715b875a50af30660f94"
"bc64729dcba50991ed4dcf8e516dcc03ce455a261ea8434a4ba951ec1c1e6b155e90bb"
"92e1fc9878d47a0754824cd402ad8dfa360eacd798c974d9febcfb742c75e260d4d532"
"a79df5271818606c4c2ac6be85c1ca0c462466c97166c588e77cc3a1f7b9269ba74dec"
"fd3fa3d3ba22343697b62bc7f5d728c324ee0a5999f452d8ccecfcc1a871ae62cdab21"
"bbb86a9257131434f7cbe4f385c4b9ccee9f0e53215bd3c33ae28e83ccd2c72fe14c94"
"f7b35fcf7a2c080d681df5356ddbf7b9115fc715841b63be738751d38e2b47984aa4bc"
"9203ce084134249f0b03633ffdf46e7f4259f11c16d674f1ea7f2d333680");
CheckTestLeftShiftHex(
"ed9ff2b4ee2266892c3b73076199fceb72282b9d3bb617602257c97aee257c56601d1d"
"8526ddc75db4a791bf37cc524359475a5851df1bb7340b2b3c114170578d241ef2f625"
"67557964e588679b8f896c4a4ea1bb43a2088527705022b32056bd696c207b4d990c7b"
"6ee1aa88acef9c583da516d6338e2e77011d9c272c5805cf4ebf5508e926eb6c6d7235"
"339f1abe8aa897263ceb9fa77a4394bb7949eb6b1caf6364000c2bf5d3c650ccb39572"
"51689f7d26a4690150a623d471552dccbdcafe4d08b9eaa31863174d0f5e09f2058384"
"91f0cfa43f9eb0e77b7a1a19b12fb28997b7e667da7e9c8c46b10a45782810f52f1432"
"fa2d4860dea805e8953850e6f802e8c7ee00e4d8ae2010d9f562504796494259c7de41"
"29bd83f5a39c796ffa9c40e682198881f1d54a66497be452d80d1a3145880c67fe2086"
"49eaa2dca31bbd68aef2563b0e3d68c71e984000926291ab459c25fc16ab818ddd3ce4"
"69e826710b5f8c888ce56df3f524785cc6d17556436c2069964288e9587d644fb00558"
"b0aba76f2fad2df2130f4b030775b24b92f0d06d8bae4972e914ea9b11cb3c80197730"
"83d81de532fc43275a708a76a97e1e1f2a7d7269b2d01b2ff8095b3619cae0dd6879cf"
"3f88073db3c3e05fc27b294dd18992c32021456bf577324d996583d09681085fb42cc2"
"426433d354e8c6278db8433aa2cc7cc78af569b7c352427e9e68fd704cc8",
13,
"fe569dc44cd125876e60ec333f9d6e450573a776c2ec044af92f5dc4af8acc03a3b0a4"
"dbb8ebb694f237e6f98a486b28eb4b0a3be376e681656782282e0af1a483de5ec4acea"
"af2c9cb10cf371f12d8949d43768744110a4ee0a0456640ad7ad2d840f69b3218f6ddc"
"3551159df38b07b4a2dac671c5cee023b384e58b00b9e9d7eaa11d24dd6d8dae46a673"
"e357d15512e4c79d73f4ef4872976f293d6d6395ec6c8001857eba78ca199672ae4a2d"
"13efa4d48d202a14c47a8e2aa5b997b95fc9a1173d54630c62e9a1ebc13e40b070923e"
"19f487f3d61cef6f43433625f65132f6fcccfb4fd39188d62148af05021ea5e2865f45"
"a90c1bd500bd12a70a1cdf005d18fdc01c9b15c4021b3eac4a08f2c9284b38fbc82537"
"b07eb4738f2dff53881cd04331103e3aa94cc92f7c8a5b01a34628b1018cffc410c93d"
"545b946377ad15de4ac761c7ad18e3d30800124c523568b384bf82d57031bba79c8d3d"
"04ce216bf191119cadbe7ea48f0b98da2eaac86d840d32c8511d2b0fac89f600ab1615"
"74ede5f5a5be4261e96060eeb649725e1a0db175c92e5d229d5362396790032ee6107b"
"03bca65f8864eb4e114ed52fc3c3e54fae4d365a0365ff012b66c3395c1bad0f39e7f1"
"00e7b6787c0bf84f6529ba313258640428ad7eaee649b32cb07a12d0210bf68598484c"
"867a6a9d18c4f1b7086754598f98f15ead36f86a484fd3cd1fae09990000");
CheckTestLeftShiftHex(
"db80c7ae597014003cefd376acb535485a8fa13acb24e611b8f57dd752e88459512767"
"51a2360a2183dcea76da8dbbc04a94f7d2df715ad03ec69eb03ebbcf42251b5c4b3ecc"
"c5833c0c213e6e3c789e7595e3460842ae5930a1b01fcc265c6fd59f0ca6c6cb6ac6d0"
"49ec14f2fa94fc44f51c4be16233728f7908e806020cf1f01ed14fd11c5d04705cfe59"
"2b0ad022a3eaf02f52998c2702510c1804eab35cabe07e576999c6156263fd9654e8d9"
"ecc417dd5b935ac25396088b15d1a235725076fe35dceb05cd27a236b1f5c205feca69"
"a9495ccdfe81ade23d311a28cf45d58545caaf4485f2f61764f63d64991d85a6ce1181"
"85055d18099c66b1457a34bb8fc447e31e9c81c8dace80c34c63ffb07d198bb3ca2f79"
"1a54eeef3af7761192dcc152cdb9d0fdfb448aecb01d7c486f7e823462cf59a8eef23d"
"c42821104650a96330ff2b9d25e353d673df6ee0d47dff09835fcf537ee789ba27305b"
"b9f50a1b30a4ac107346452df736bb59488ee82353469a5dd70cf17fb6c6560581012c"
"a216c55c2720a658c3e45548bb5eef5e1682beadf81d0e8490a278c9b5d15bc2c2318e"
"27353b6b648b820859a1c4e878e24ec51e209067e004d094cbae59ed7cd4c2029320c2"
"979c46024dee84090ae3559155c84939dae8eca6b7771f464ad82e5fef1730c93a1457"
"af6f129d4c99b910d541a95761d9f6d990ff3b16cd981ae1e148a77a9ef7",
37,
"2e0280079dfa6ed596a6a90b51f42759649cc2371eafbaea5d108b2a24ecea3446c144"
"307b9d4edb51b77809529efa5bee2b5a07d8d3d607d779e844a36b8967d998b0678184"
"27cdc78f13ceb2bc68c10855cb26143603f984cb8dfab3e194d8d96d58da093d829e5f"
"529f889ea3897c2c466e51ef211d00c0419e3e03da29fa238ba08e0b9fcb25615a0454"
"7d5e05ea533184e04a2183009d566b957c0fcaed3338c2ac4c7fb2ca9d1b3d9882fbab"
"726b584a72c11162ba3446ae4a0edfc6bb9d60b9a4f446d63eb840bfd94d35292b99bf"
"d035bc47a6234519e8bab0a8b955e890be5ec2ec9ec7ac9323b0b4d9c23030a0aba301"
"338cd628af469771f888fc63d390391b59d018698c7ff60fa331767945ef234a9ddde7"
"5eeec2325b982a59b73a1fbf68915d9603af890defd0468c59eb351dde47b885042208"
"ca152c661fe573a4bc6a7ace7beddc1a8fbfe1306bf9ea6fdcf13744e60b773ea14366"
"1495820e68c8a5bee6d76b2911dd046a68d34bbae19e2ff6d8cac0b020259442d8ab84"
"e414cb187c8aa9176bddebc2d057d5bf03a1d092144f1936ba2b78584631c4e6a76d6c"
"9170410b34389d0f1c49d8a3c4120cfc009a129975cb3daf9a984052641852f388c049"
"bdd081215c6ab22ab909273b5d1d94d6eee3e8c95b05cbfde2e61927428af5ede253a9"
"9337221aa8352aec3b3edb321fe762d9b3035c3c2914ef53dee000000000");
CheckTestLeftShiftHex(
"91b89e3b793648555b4bf4c22263939848879ffcd9151a3d32c893ee81360bb0134822"
"cc6c990a3d3de9eeb8c90fbbf4d94d94c21c49bfe1a2dd6b6323ae20a2f7270c50411b"
"db851c7d2d226ddc2587e452bbfbd4962a72a898de3d93b294891c8099b8351fa3ccfb"
"7e20f96683190a8dff9382103ea653cabd6ae6f01d19d86e78054c5d89e5bb088f504b"
"a623c8a6d1db4085442a2122394a5037c1e5adaf31ecd491f9b460228fef50d2dd1e50"
"c46a73c8499cd4fc9552134b19fcfeb213b59cd1c718b385199b44304e3e4a8a680d43"
"2fbe1d9e63692b8694f4ec46b8316cec5eb01f096e13d55ddcc79c94b63c6feb3ca290"
"69267a6a8a0268b5394874bad4470b0feb17541ad1310298458360af0ccf09d7fa7026"
"3a9df7947351661fa8f7afaa9aa6744318b1f5ab7f30f92b8eda6af1cd2d712a44eb06"
"e66c715068163776ed0c72d23c951cb416464c8468b68a16d2b80b061fd79d1956b8cc"
"badd86c6bf1258444f216b21969bc1b514bafef04d6bf25bf610f71a88bf69a28176a9"
"4f72a79a99d382ec46b8f3114a6bd605f9a6246ca8d5cae14cdb6b5958c181ea70fb80"
"47a6e07671953e24b93e223f525c1f735b025ec9d619aca79e2b341df5b9e7ca91c4c4"
"7c3c867c7170cb737c93df5b45f8c2cd71d1f79385e2e5ae44f4a9047e9788ddac95a8"
"5d6e07fc5bd812d2e6d44c693fe6f1616475f038778c5d394299999f4113",
398,
"653087126ff868b75ad8c8eb8828bdc9c3141046f6e1471f4b489b770961f914aefef5"
"258a9caa26378f64eca5224720266e0d47e8f33edf883e59a0c642a37fe4e0840fa994"
"f2af5ab9bc0746761b9e01531762796ec223d412e988f229b476d021510a88488e5294"
"0df0796b6bcc7b35247e6d1808a3fbd434b74794311a9cf21267353f255484d2c67f3f"
"ac84ed673471c62ce14666d10c138f92a29a0350cbef876798da4ae1a53d3b11ae0c5b"
"3b17ac07c25b84f5577731e7252d8f1bfacf28a41a499e9aa2809a2d4e521d2eb511c2"
"c3fac5d506b44c40a61160d82bc333c275fe9c098ea77de51cd45987ea3debeaa6a99d"
"10c62c7d6adfcc3e4ae3b69abc734b5c4a913ac1b99b1c541a058dddbb431cb48f2547"
"2d059193211a2da285b4ae02c187f5e74655ae332eb761b1afc4961113c85ac865a6f0"
"6d452ebfbc135afc96fd843dc6a22fda68a05daa53dca9e6a674e0bb11ae3cc4529af5"
"817e69891b2a3572b85336dad65630607a9c3ee011e9b81d9c654f892e4f888fd49707"
"dcd6c097b275866b29e78acd077d6e79f2a471311f0f219f1c5c32dcdf24f7d6d17e30"
"b35c747de4e178b96b913d2a411fa5e2376b256a175b81ff16f604b4b9b5131a4ff9bc"
"58591d7c0e1de3174e50a66667d044c000000000000000000000000000000000000000"
"000000000000000000000000000000000000000000000000000000000000");
CheckTestLeftShiftHex(
"eb8baf207037a28801f631673410255a2b8f36e868f98793d4cdd5180907b801be38ef"
"aa1ab75420f57f80825d5c0638a7519a777bf85772b616e5883d3f5c6c424cb1f32d71"
"c051203ca1465b15729d0b2a865600c7614db607bc6fe8564ab0c2f2e4a12f252004dd"
"f82bb0d36b23b8f8f1efb2814bdd6a6fb17f90028494a67db72fda1d0c2ef72f170f30"
"4b4a28b3bc51c2e58e8e009785c6584dbdd665834326a6d59b98736836b9044608f3d6"
"37616570a83904b934e0db5c3741e3a83c7d209802cf8c89a6af2d74af2e313630411d"
"240f00c3aca3fb343d20be9f2ce48949ca291d9604963321d2eb4d5732e84749c4d9d1"
"5071595e1a10a665b62ec9da697952efa8f231dd7cb429447f607ec116b9eedfc0bb3f"
"a86366120306c27c5e3ee5918717148ee3481183a181726fa2de825cfbc3d922ff7b2f"
"003d7873f40853b2fa45128ef712df2a46f241907db643cadf5145fcb77cc1a11a2fad"
"fdfabc2b137e68300f2f4cc5d6d508f93f0bab9d5abab5952ebf0e12614801c78d8dde"
"7d43e243d165677ee2d0d92b2c2c98fb86ae736e796536757f54a68ee69e60f2c3c201"
"3418d16d67842414004b3da73ab0c2cc1625b18af0bc73c32e1fa44219f4a4bfcc3975"
"993a6935b6d056f37b14f38009ff817bd8f09139a7fcb065a5562d22976846f883588f"
"d5a7904a54c6b3997aab24aa09e85fb670cf9fe0e72c9fd2351177d18b0a",
2489,
"45fef65e007af0e7e810a765f48a251dee25be548de48320fb6c8795bea28bf96ef983"
"42345f5bfbf5785626fcd0601e5e998badaa11f27e17573ab5756b2a5d7e1c24c29003"
"8f1b1bbcfa87c487a2cacefdc5a1b256585931f70d5ce6dcf2ca6ceafea94d1dcd3cc1"
"e58784026831a2dacf08482800967b4e756185982c4b6315e178e7865c3f488433e949"
"7f9872eb3274d26b6da0ade6f629e70013ff02f7b1e122734ff960cb4aac5a452ed08d"
"f106b11fab4f2094a98d6732f556495413d0bf6ce19f3fc1ce593fa46a22efa3161400"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"000000000000000000000000000000000000000000000000000000000000");
CheckTestLeftShiftHex(
"0b0d15d774b99ba942850db1c241026d622134010042e6ee81030c23e4d6d4b0668cfb"
"1be94b064ed5d51ab700c999c41b2b6be0f4b75f3cd0dee87d682e2729f6d68ee2ab1e"
"0dd98ee038395fac6a8a7058a0ecf3353507324652e9277d9aebf6a37662cfe5cda9c3"
"10e2cf278b0a9bea20ad625dd6984fb7bb7918adae491a94293163eebdde9040652399"
"db552d312a2592fd7e7edfde6cff38c365f8f20a02fd26a124d46944381e67174c7225"
"656a5b8e41525c97cde1a5cf70b846670f1cafc655bbf115511d63d0d8db503807efc0"
"cef1716f637b8871035e092003f4709e690350b4c6ad520648a6d17b1964465ada5508"
"bd99df5e68c4915c0e389395e898fd3800d4da40010aca27cdb898126884fca767db34"
"cf03360126a2a848a4bdf28f900cc9cdf5bca267d98692d3dbf6217d9907ae8b4dac61"
"158ff7ca0b6737851967fb1cc4bf0ac841999066372472cff6143d1469bc21bae74f12"
"41f69b483b997e400b879fe90e079478b5f92c5c3c1c47837addcaac7933fedc345b7d"
"04b326d05ffbb1fc1eb10dcb833f1aa40b36c9475bbc8246d8fa5203ecd734d851ea7e"
"7ea56fda62a941016f00e36a4dd353ab6187d210dc37841357ec55b6e932ddbbf176c4"
"b2d3741f36f600a0aa6d40e8be663967a6cf46a8a941c3d5a49b6b59104aee36ab0759"
"f68d8045a2503c6090a9cf8d7daa81402774859948a779af8379b89f41db",
4134,
"27d076c000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"000000000000000000000000000000000000000000000000000000000000");
CheckTestLeftShiftHex(
"9eb21c29f8f88523b70828a457aeea014e3d1150c2f9ec6e3440672abb91272c264426"
"3b015d039aa3cfe035d34e6296867778bc476ec501e4bf944a4c29ef8f3ccc07aaed6c"
"2fa091cb67d8dfff9ae5ed254392d84211d9f600d6df7c7ef203db7cb9a9ca38c444c0"
"e977138597c39e794e54f59600eee3ca3e745624a02305ebc5d2312f7b5c67b810637a"
"06277b263e7daa6c14f80c6e7f85b6b61ec7d7c6cdcf9a62994b4c002006025d9c489c"
"120400abc37bc7ec2791b3c73237450d510f455e467c6e3f46a8a08840dd627bcf1920"
"387a207788b9c38e9c4138e03b16a54e5feb985fff0968c8de3fa0d69b6484df19ccaa"
"8faad14d3e53a57b41e13e634c31b8b7d63c8893ebc05336a38daf39b4dd226af4cc35"
"b23f93f83ebfb7168d9bbef9b5ee6403e697528e259f3cded4d6da552005f6b3033e95"
"c76a72a4c94b0ee09153ae1d16ddf451bb3f9cd1fac321417a4f0b1f3ed355635e9cd2"
"eb517cf8c051d6c29b51b4605e01af9ce415f7329cf366db4061add032f5b5c8f1d63e"
"8ae633130a6130ecd5c4751c6084b6878a548b8d4d0f3cc4e932b41b6a895238d0b8e0"
"dd04300a986524496ee5a6ef5734a36985328093c3c7a12a89bd0a304b45d85ef2c943"
"6bd8646aa6174756ec8edc5af20c79ec1a8d61b201ffe8343f31f86a6e0292968fc23a"
"aa006719ce79200dfc360bbb039004c0ecaf7448380bec2afac9542ae111",
4159,
"8000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"000000000000000000000000000000000000000000000000000000000000");
CheckTestLeftShiftHex(
"9eb21c29f8f88523b70828a457aeea014e3d1150c2f9ec6e3440672abb91272c264426"
"3b015d039aa3cfe035d34e6296867778bc476ec501e4bf944a4c29ef8f3ccc07aaed6c"
"2fa091cb67d8dfff9ae5ed254392d84211d9f600d6df7c7ef203db7cb9a9ca38c444c0"
"e977138597c39e794e54f59600eee3ca3e745624a02305ebc5d2312f7b5c67b810637a"
"06277b263e7daa6c14f80c6e7f85b6b61ec7d7c6cdcf9a62994b4c002006025d9c489c"
"120400abc37bc7ec2791b3c73237450d510f455e467c6e3f46a8a08840dd627bcf1920"
"387a207788b9c38e9c4138e03b16a54e5feb985fff0968c8de3fa0d69b6484df19ccaa"
"8faad14d3e53a57b41e13e634c31b8b7d63c8893ebc05336a38daf39b4dd226af4cc35"
"b23f93f83ebfb7168d9bbef9b5ee6403e697528e259f3cded4d6da552005f6b3033e95"
"c76a72a4c94b0ee09153ae1d16ddf451bb3f9cd1fac321417a4f0b1f3ed355635e9cd2"
"eb517cf8c051d6c29b51b4605e01af9ce415f7329cf366db4061add032f5b5c8f1d63e"
"8ae633130a6130ecd5c4751c6084b6878a548b8d4d0f3cc4e932b41b6a895238d0b8e0"
"dd04300a986524496ee5a6ef5734a36985328093c3c7a12a89bd0a304b45d85ef2c943"
"6bd8646aa6174756ec8edc5af20c79ec1a8d61b201ffe8343f31f86a6e0292968fc23a"
"aa006719ce79200dfc360bbb039004c0ecaf7448380bec2afac9542ae111",
4160,
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"000000000000000000000000000000000000000000000000000000000000");
}
BOOST_AUTO_TEST_CASE(right_shift_test) {
CheckTestRightShiftHex("", 0, "");
CheckTestRightShiftHex("", 1, "");
CheckTestRightShiftHex("63", 0, "63");
CheckTestRightShiftHex("63", 1, "31");
CheckTestRightShiftHex("63", 2, "18");
CheckTestRightShiftHex("63", 3, "0c");
CheckTestRightShiftHex("63", 4, "06");
CheckTestRightShiftHex("63", 5, "03");
CheckTestRightShiftHex("63", 6, "01");
CheckTestRightShiftHex("63", 7, "00");
CheckTestRightShiftHex("63", 8, "00");
CheckTestRightShiftHex("6347", 0, "6347");
CheckTestRightShiftHex("6347", 1, "31a3");
CheckTestRightShiftHex("6347", 7, "00c6");
CheckTestRightShiftHex("6347", 8, "0063");
CheckTestRightShiftHex("6347", 9, "0031");
CheckTestRightShiftHex(
"ebd076435d1fe29d4bc6165d49e32b2d88d58919a8106bcc9afaeda9137c10ee7131b2"
"f45d61b781b9c1d29f8f87c8be440a27379ada1e811fd3cc9cdd06fb139d1c3e01becb"
"e8be85da9657859766de3add40b1f7345056866f33dc6ef85ec89e7d02805eca428195"
"31cc4fe5c2e692f1fa9f39e7f85eba444e378e024c693e089fbb46fe36781e36ce5be1"
"068b2f36cf9cd6dcd0bc480e53549bde70a3560e32dcc697299a0bdad2fcdf869bcf56"
"45aa5baa5b8560a3b7368072e2d4f4dee7a07b0c0d747089827c09f6dbf866f8f7d94a"
"8c3592e9d1bca02a9686cc3cb2eb3b6c932d1905f832e40d4559095a416d0e74c7259c"
"266b0ad9b18f12571093ec026ecb1d7e942228e5058f2d3c9b591cb79e4a53f84499b9"
"dda1f4bf26047ab591670c3b8939759f942f3ac4d6754a88a3c909126823dc4241ecea"
"de263e9e6ae603126eb7d6ca9510184a70effb2f424079237bc7e1243438dc44ae7467"
"f49cb3f46cfc5c98a72fe8b3a45c6e60f83444c5ba911596b82359b807271d0d3d8cd5"
"e6d5dca1034de6572306407e9e248f7edd6add140fd61709b040c0b44b2cf24e9207ba"
"2fbe5b851764485541cd8ad0e35c9bf6dc27579141dc8c6e1d6b96de06fca85b248dc1"
"36906eab64287864fd3dba3d3b8483e24495ae0e19471d0f51d847e7c5b088081e491c"
"fa39ae48eae4392fe499af54c0d6adc47deed067d106a129fbc7bd7f612e",
1,
"75e83b21ae8ff14ea5e30b2ea4f19596c46ac48cd40835e64d7d76d489be08773898d9"
"7a2eb0dbc0dce0e94fc7c3e45f2205139bcd6d0f408fe9e64e6e837d89ce8e1f00df65"
"f45f42ed4b2bc2cbb36f1d6ea058fb9a282b433799ee377c2f644f3e81402f652140ca"
"98e627f2e1734978fd4f9cf3fc2f5d22271bc70126349f044fdda37f1b3c0f1b672df0"
"8345979b67ce6b6e685e240729aa4def3851ab07196e634b94cd05ed697e6fc34de7ab"
"22d52dd52dc2b051db9b4039716a7a6f73d03d8606ba3844c13e04fb6dfc337c7beca5"
"461ac974e8de50154b43661e59759db649968c82fc197206a2ac84ad20b6873a6392ce"
"1335856cd8c7892b8849f60137658ebf4a11147282c7969e4dac8e5bcf2529fc224cdc"
"eed0fa5f93023d5ac8b3861dc49cbacfca179d626b3aa54451e484893411ee2120f675"
"6f131f4f35730189375beb654a880c253877fd97a1203c91bde3f0921a1c6e22573a33"
"fa4e59fa367e2e4c5397f459d22e37307c1a2262dd488acb5c11acdc03938e869ec66a"
"f36aee5081a6f32b9183203f4f1247bf6eb56e8a07eb0b84d820605a259679274903dd"
"17df2dc28bb2242aa0e6c56871ae4dfb6e13abc8a0ee46370eb5cb6f037e542d9246e0"
"9b483755b2143c327e9edd1e9dc241f1224ad7070ca38e87a8ec23f3e2d844040f248e"
"7d1cd72475721c97f24cd7aa606b56e23ef76833e8835094fde3debfb097");
CheckTestRightShiftHex(
"2a467c005ae83afa9d8df8b13a0e0d6a3d085e8c71e4ea210ceeeb30c84cd771c5c226"
"45091dc8e91619c4525b5986db05e54174bdc02cc5b5bf12c22fe377b60615666595ba"
"323d6b4a2f354f68c93481884d7a6aba0d235e45262eeeb93c3453dcd52faf35fb569d"
"b221305dadbc74c55a40806d9838be5c42de74481450e6a672adbdddd8f541edc26b27"
"b15e5487da9ab8f7f335e1fc97d137466d97bc737c74ef8f4dfcbdb0d11268981c7a83"
"313ca63a67dac5ecda6c06e6d69eae5b51171d6d32e577bc9d13e14789a148a97c7755"
"0b2225aec7179491e0e5bc04a2aba3244d9431e5272714a0b78b6284d0fd4e6802ce98"
"0802ac9637a2140219781fddcf45652c518e6602e59a7f35bca10543ded6552559ae9d"
"de1a6dcb9e4a7812511ec18cc9a9f2740190010392ea45961ef78370ad6f5d8e7516cb"
"6db3516c14aa42ea63011d065cca4d7a23d1e0b196da933d474c058639dee71da091b3"
"ec86f4cb30ea66175725ccf5c9c99e8b30c4faa1a83cb095d5b55d3882cf5c545bb515"
"a3607c46d32792f207ff13123f08bc0fc1d2605a890ad31895c5b22c180deed8a4736d"
"891afdb0409e0402cd326f596fca4439b131e8251e1c0ef437be6832ead0e458c64388"
"87776adc2d0aa92bacac6303ca48f0c7b6c91282dea7b86d312e687582eadf90be7774"
"e7f70f9189abb9690a80bf333574f6b249eead1244b0d14fe69e7cb12f56",
2,
"0a919f0016ba0ebea7637e2c4e83835a8f4217a31c793a88433bbacc321335dc717089"
"914247723a4586711496d661b6c179505d2f700b316d6fc4b08bf8dded81855999656e"
"8c8f5ad28bcd53da324d2062135e9aae8348d791498bbbae4f0d14f7354bebcd7ed5a7"
"6c884c176b6f1d315690201b660e2f9710b79d12051439a99cab6f77763d507b709ac9"
"ec579521f6a6ae3dfccd787f25f44dd19b65ef1cdf1d3be3d37f2f6c34449a26071ea0"
"cc4f298e99f6b17b369b01b9b5a7ab96d445c75b4cb95def2744f851e268522a5f1dd5"
"42c8896bb1c5e52478396f0128aae8c913650c7949c9c5282de2d8a1343f539a00b3a6"
"0200ab258de88500865e07f773d1594b14639980b9669fcd6f284150f7b59549566ba7"
"77869b72e7929e049447b063326a7c9d00640040e4ba916587bde0dc2b5bd7639d45b2"
"db6cd45b052a90ba98c047419732935e88f4782c65b6a4cf51d301618e77b9c768246c"
"fb21bd32cc3a9985d5c9733d727267a2cc313ea86a0f2c25756d574e20b3d71516ed45"
"68d81f11b4c9e4bc81ffc4c48fc22f03f0749816a242b4c625716c8b06037bb6291cdb"
"6246bf6c10278100b34c9bd65bf2910e6c4c7a09478703bd0def9a0cbab439163190e2"
"21dddab70b42aa4aeb2b18c0f2923c31edb244a0b7a9ee1b4c4b9a1d60bab7e42f9ddd"
"39fdc3e4626aee5a42a02fcccd5d3dac927bab44912c3453f9a79f2c4bd5");
CheckTestRightShiftHex(
"a98494f07b4dab376b2ab766f30fca375985cdc9b5de0774a98618702da6939883fa98"
"baed23fbe29cda508742ebd2120da4f680b58f69d7368c2ffef15c3571ea7b19cfcbef"
"31fbc998fe5b3548b6b935e067f4b9778a883c164edbf0cd7c4a8c9c4b53e80a9d6517"
"438c5034a6fec75924e40722ac1622972bbafed27ee574443ab1028ca2120ff7727cbe"
"471f0493afe8c8f196aed1e1a571769b495ccb04c1e1c19bab7f22bc29adebf1cb505a"
"d4a659d42dc06458d463826178f0c60d2ef594d3c587f1eec3b0aff01be5fab31dfa65"
"93a5a0d5aa295891fbb3a9a8d18eda9a9b8d78cde2a3e868493365796ac496e27a7876"
"c8d7b3c6b292ff13be312f610afbf5509c618f7e9def06c6d7ae88b36227838d02a8d6"
"65a8259b0ba7644a9445bd0d237d4626ce9a67f1653862df093e6aa8b09717dde3917f"
"44a4e5f4c35d0cc6b58fad65c42a5b5fb9bcdf1f716caddc9c0be86ef1726762858986"
"f9aa901e5963f73bc2ca5fada5bd4b14febe10910c32c72daae28107a3cda032115601"
"7c5b8ed36dc486bf41b8cf6ea54f3bfee549c515552cabb1f0e67af5cead0e24557732"
"bedeb2d2a4c7f37693389d38fd994166fd733b5b50e4dfd6b2df1b84612ba7f329e5be"
"4131e46299656011308426fd1b900956c1ea4a726b850e806ee8afb1f1ab2054d8b80d"
"5664ede7f7d827e49a7bbadc3a06dd490045207937cc5ef43f4607b992d7",
3,
"1530929e0f69b566ed6556ecde61f946eb30b9b936bbc0ee9530c30e05b4d273107f53"
"175da47f7c539b4a10e85d7a4241b49ed016b1ed3ae6d185ffde2b86ae3d4f6339f97d"
"e63f79331fcb66a916d726bc0cfe972ef1510782c9db7e19af895193896a7d0153aca2"
"e8718a0694dfd8eb249c80e45582c452e5775fda4fdcae8887562051944241feee4f97"
"c8e3e09275fd191e32d5da3c34ae2ed3692b9960983c3833756fe4578535bd7e396a0b"
"5a94cb3a85b80c8b1a8c704c2f1e18c1a5deb29a78b0fe3dd87615fe037cbf5663bf4c"
"b274b41ab5452b123f7675351a31db535371af19bc547d0d09266caf2d5892dc4f4f0e"
"d91af678d6525fe277c625ec215f7eaa138c31efd3bde0d8daf5d1166c44f071a0551a"
"ccb504b36174ec895288b7a1a46fa8c4d9d34cfe2ca70c5be127cd551612e2fbbc722f"
"e8949cbe986ba198d6b1f5acb8854b6bf7379be3ee2d95bb93817d0dde2e4cec50b130"
"df355203cb2c7ee778594bf5b4b7a9629fd7c212218658e5b55c5020f479b406422ac0"
"2f8b71da6db890d7e83719edd4a9e77fdca938a2aaa595763e1ccf5eb9d5a1c48aaee6"
"57dbd65a5498fe6ed26713a71fb3282cdfae676b6a1c9bfad65be3708c2574fe653cb7"
"c8263c8c532cac02261084dfa372012ad83d494e4d70a1d00ddd15f63e35640a9b1701"
"aacc9dbcfefb04fc934f775b8740dba92008a40f26f98bde87e8c0f7325a");
CheckTestRightShiftHex(
"98660ce335e12462fb5c2be76c46443825e3da19fc21a01b93271e5a9b7da55503b1de"
"3778909a36ce44ff4983706091dfcf49e5d2a4c3743fa1f5451b4a60c87836149758b1"
"01be65dfb2442a01e5203da712b205ea4d202dc6aecfeb76cf0ebff9977f1ef90cf419"
"80907d74c36e45d0804bc340058fa75f0941d4b68ad179830fc6a4e4abaa99eb9be486"
"cff2486a768135f227c01aa15bfe066fcd1a89c09d794489f836165072e68c422ca508"
"804909206d135cdc5f893b4a1a99ed9bda7eba63dbe7583b8d87b794b8230fd1b8597c"
"9c352d0fefb2526c78a536349c31df3da254666809ff3eb89737bcc901030cefe13955"
"d379f555d9295fc4b8c0d7089ed0c9856f48fcbbb9a011b26490e2b70eb4a15e60cc1f"
"2978c8e53b974a1323da9b9f1ca2db98079c8ab44c3d5086949752a3d8383cd62abd21"
"7725c3f930f1a8f40ea90499a8055b1bf46c1d59af3192e9b3fd79f6e858ebc4c1a9aa"
"654f3bea4e3030c0d898558d7d0b8394188c48cd92e2cd8b11cef98743ef724d374e9b"
"d9fa7f47a77444686d2f6c578febae518649dc14b333e8a5b199d9f98350e35cc59b56"
"437770d524ae262869ef97c9e70b897399dd3e1ca642b7a78675c51d0799a58e5fc299"
"29ef66bf9ef458101ad03bea6adbb7ef7222bf8e2b0836c77ce70ea3a71c568f309549"
"7924079c108268493e1606c67ffbe8dcfe84b3e2382dace9e3d4fe5a666d",
7,
"0130cc19c66bc248c5f6b857ced88c88704bc7b433f8434037264e3cb536fb4aaa0763"
"bc6ef121346d9c89fe9306e0c123bf9e93cba54986e87f43ea8a3694c190f06c292eb1"
"62037ccbbf64885403ca407b4e25640bd49a405b8d5d9fd6ed9e1d7ff32efe3df219e8"
"330120fae986dc8ba1009786800b1f4ebe1283a96d15a2f3061f8d49c9575533d737c9"
"0d9fe490d4ed026be44f803542b7fc0cdf9a3513813af28913f06c2ca0e5cd1884594a"
"1100921240da26b9b8bf1276943533db37b4fd74c7b7ceb0771b0f6f2970461fa370b2"
"f9386a5a1fdf64a4d8f14a6c693863be7b44a8ccd013fe7d712e6f7992020619dfc272"
"aba6f3eaabb252bf897181ae113da1930ade91f97773402364c921c56e1d6942bcc198"
"3e52f191ca772e942647b5373e3945b7300f391568987aa10d292ea547b07079ac557a"
"42ee4b87f261e351e81d520933500ab637e8d83ab35e6325d367faf3edd0b1d7898353"
"54ca9e77d49c606181b130ab1afa1707283118919b25c59b16239df30e87dee49a6e9d"
"37b3f4fe8f4ee888d0da5ed8af1fd75ca30c93b8296667d14b6333b3f306a1c6b98b36"
"ac86eee1aa495c4c50d3df2f93ce1712e733ba7c394c856f4f0ceb8a3a0f334b1cbf85"
"3253decd7f3de8b02035a077d4d5b76fdee4457f1c56106d8ef9ce1d474e38ad1e612a"
"92f2480f382104d0927c2c0d8cfff7d1b9fd0967c4705b59d3c7a9fcb4cc");
CheckTestRightShiftHex(
"ed9ff2b4ee2266892c3b73076199fceb72282b9d3bb617602257c97aee257c56601d1d"
"8526ddc75db4a791bf37cc524359475a5851df1bb7340b2b3c114170578d241ef2f625"
"67557964e588679b8f896c4a4ea1bb43a2088527705022b32056bd696c207b4d990c7b"
"6ee1aa88acef9c583da516d6338e2e77011d9c272c5805cf4ebf5508e926eb6c6d7235"
"339f1abe8aa897263ceb9fa77a4394bb7949eb6b1caf6364000c2bf5d3c650ccb39572"
"51689f7d26a4690150a623d471552dccbdcafe4d08b9eaa31863174d0f5e09f2058384"
"91f0cfa43f9eb0e77b7a1a19b12fb28997b7e667da7e9c8c46b10a45782810f52f1432"
"fa2d4860dea805e8953850e6f802e8c7ee00e4d8ae2010d9f562504796494259c7de41"
"29bd83f5a39c796ffa9c40e682198881f1d54a66497be452d80d1a3145880c67fe2086"
"49eaa2dca31bbd68aef2563b0e3d68c71e984000926291ab459c25fc16ab818ddd3ce4"
"69e826710b5f8c888ce56df3f524785cc6d17556436c2069964288e9587d644fb00558"
"b0aba76f2fad2df2130f4b030775b24b92f0d06d8bae4972e914ea9b11cb3c80197730"
"83d81de532fc43275a708a76a97e1e1f2a7d7269b2d01b2ff8095b3619cae0dd6879cf"
"3f88073db3c3e05fc27b294dd18992c32021456bf577324d996583d09681085fb42cc2"
"426433d354e8c6278db8433aa2cc7cc78af569b7c352427e9e68fd704cc8",
13,
"00076cff95a77113344961db983b0ccfe75b91415ce9ddb0bb0112be4bd7712be2b300"
"e8ec2936ee3aeda53c8df9be62921aca3ad2c28ef8ddb9a05959e08a0b82bc6920f797"
"b12b3aabcb272c433cdc7c4b6252750dda1d1044293b8281159902b5eb4b6103da6cc8"
"63db770d5445677ce2c1ed28b6b19c7173b808ece13962c02e7a75faa84749375b636b"
"91a99cf8d5f45544b931e75cfd3bd21ca5dbca4f5b58e57b1b2000615fae9e3286659c"
"ab928b44fbe93523480a85311ea38aa96e65ee57f26845cf5518c318ba687af04f902c"
"1c248f867d21fcf5873bdbd0d0cd897d944cbdbf333ed3f4e4623588522bc14087a978"
"a197d16a4306f5402f44a9c28737c017463f700726c5710086cfab12823cb24a12ce3e"
"f2094dec1fad1ce3cb7fd4e2073410cc440f8eaa53324bdf2296c068d18a2c40633ff1"
"04324f5516e518ddeb457792b1d871eb4638f4c2000493148d5a2ce12fe0b55c0c6ee9"
"e7234f4133885afc6444672b6f9fa923c2e6368baab21b61034cb214474ac3eb227d80"
"2ac5855d3b797d696f90987a58183bad925c9786836c5d724b9748a754d88e59e400cb"
"b9841ec0ef2997e2193ad38453b54bf0f0f953eb934d9680d97fc04ad9b0ce5706eb43"
"ce79fc4039ed9e1f02fe13d94a6e8c4c9619010a2b5fabb9926ccb2c1e84b40842fda1"
"661213219e9aa746313c6dc219d51663e63c57ab4dbe1a9213f4f347eb82");
CheckTestRightShiftHex(
"db80c7ae597014003cefd376acb535485a8fa13acb24e611b8f57dd752e88459512767"
"51a2360a2183dcea76da8dbbc04a94f7d2df715ad03ec69eb03ebbcf42251b5c4b3ecc"
"c5833c0c213e6e3c789e7595e3460842ae5930a1b01fcc265c6fd59f0ca6c6cb6ac6d0"
"49ec14f2fa94fc44f51c4be16233728f7908e806020cf1f01ed14fd11c5d04705cfe59"
"2b0ad022a3eaf02f52998c2702510c1804eab35cabe07e576999c6156263fd9654e8d9"
"ecc417dd5b935ac25396088b15d1a235725076fe35dceb05cd27a236b1f5c205feca69"
"a9495ccdfe81ade23d311a28cf45d58545caaf4485f2f61764f63d64991d85a6ce1181"
"85055d18099c66b1457a34bb8fc447e31e9c81c8dace80c34c63ffb07d198bb3ca2f79"
"1a54eeef3af7761192dcc152cdb9d0fdfb448aecb01d7c486f7e823462cf59a8eef23d"
"c42821104650a96330ff2b9d25e353d673df6ee0d47dff09835fcf537ee789ba27305b"
"b9f50a1b30a4ac107346452df736bb59488ee82353469a5dd70cf17fb6c6560581012c"
"a216c55c2720a658c3e45548bb5eef5e1682beadf81d0e8490a278c9b5d15bc2c2318e"
"27353b6b648b820859a1c4e878e24ec51e209067e004d094cbae59ed7cd4c2029320c2"
"979c46024dee84090ae3559155c84939dae8eca6b7771f464ad82e5fef1730c93a1457"
"af6f129d4c99b910d541a95761d9f6d990ff3b16cd981ae1e148a77a9ef7",
37,
"0000000006dc063d72cb80a001e77e9bb565a9aa42d47d09d65927308dc7abeeba9744"
"22ca893b3a8d11b0510c1ee753b6d46dde0254a7be96fb8ad681f634f581f5de7a1128"
"dae259f6662c19e06109f371e3c4f3acaf1a30421572c9850d80fe6132e37eacf86536"
"365b5636824f60a797d4a7e227a8e25f0b119b947bc847403010678f80f68a7e88e2e8"
"2382e7f2c9585681151f57817a94cc6138128860c027559ae55f03f2bb4cce30ab131f"
"ecb2a746cf6620beeadc9ad6129cb04458ae8d11ab9283b7f1aee7582e693d11b58fae"
"102ff6534d4a4ae66ff40d6f11e988d1467a2eac2a2e557a242f97b0bb27b1eb24c8ec"
"2d36708c0c282ae8c04ce3358a2bd1a5dc7e223f18f4e40e46d674061a631ffd83e8cc"
"5d9e517bc8d2a77779d7bbb08c96e60a966dce87efda24576580ebe2437bf411a3167a"
"cd477791ee2141088232854b1987f95ce92f1a9eb39efb7706a3eff84c1afe7a9bf73c"
"4dd13982ddcfa850d9852560839a32296fb9b5daca4477411a9a34d2eeb8678bfdb632"
"b02c08096510b62ae1390532c61f22aa45daf77af0b415f56fc0e874248513c64dae8a"
"de16118c7139a9db5b245c1042cd0e2743c7127628f104833f002684a65d72cf6be6a6"
"1014990614bce230126f742048571aac8aae4249ced7476535bbb8fa3256c172ff78b9"
"8649d0a2bd7b7894ea64cdc886aa0d4abb0ecfb6cc87f9d8b66cc0d70f0a");
CheckTestRightShiftHex(
"91b89e3b793648555b4bf4c22263939848879ffcd9151a3d32c893ee81360bb0134822"
"cc6c990a3d3de9eeb8c90fbbf4d94d94c21c49bfe1a2dd6b6323ae20a2f7270c50411b"
"db851c7d2d226ddc2587e452bbfbd4962a72a898de3d93b294891c8099b8351fa3ccfb"
"7e20f96683190a8dff9382103ea653cabd6ae6f01d19d86e78054c5d89e5bb088f504b"
"a623c8a6d1db4085442a2122394a5037c1e5adaf31ecd491f9b460228fef50d2dd1e50"
"c46a73c8499cd4fc9552134b19fcfeb213b59cd1c718b385199b44304e3e4a8a680d43"
"2fbe1d9e63692b8694f4ec46b8316cec5eb01f096e13d55ddcc79c94b63c6feb3ca290"
"69267a6a8a0268b5394874bad4470b0feb17541ad1310298458360af0ccf09d7fa7026"
"3a9df7947351661fa8f7afaa9aa6744318b1f5ab7f30f92b8eda6af1cd2d712a44eb06"
"e66c715068163776ed0c72d23c951cb416464c8468b68a16d2b80b061fd79d1956b8cc"
"badd86c6bf1258444f216b21969bc1b514bafef04d6bf25bf610f71a88bf69a28176a9"
"4f72a79a99d382ec46b8f3114a6bd605f9a6246ca8d5cae14cdb6b5958c181ea70fb80"
"47a6e07671953e24b93e223f525c1f735b025ec9d619aca79e2b341df5b9e7ca91c4c4"
"7c3c867c7170cb737c93df5b45f8c2cd71d1f79385e2e5ae44f4a9047e9788ddac95a8"
"5d6e07fc5bd812d2e6d44c693fe6f1616475f038778c5d394299999f4113",
398,
"0000000000000000000000000000000000000000000000000000000000000000000000"
"00000000000000000000000000000246e278ede4d921556d2fd308898e4e61221e7ff3"
"645468f4cb224fba04d82ec04d208b31b26428f4f7a7bae3243eefd3653653087126ff"
"868b75ad8c8eb8828bdc9c3141046f6e1471f4b489b770961f914aefef5258a9caa263"
"78f64eca5224720266e0d47e8f33edf883e59a0c642a37fe4e0840fa994f2af5ab9bc0"
"746761b9e01531762796ec223d412e988f229b476d021510a88488e52940df0796b6bc"
"c7b35247e6d1808a3fbd434b74794311a9cf21267353f255484d2c67f3fac84ed67347"
"1c62ce14666d10c138f92a29a0350cbef876798da4ae1a53d3b11ae0c5b3b17ac07c25"
"b84f5577731e7252d8f1bfacf28a41a499e9aa2809a2d4e521d2eb511c2c3fac5d506b"
"44c40a61160d82bc333c275fe9c098ea77de51cd45987ea3debeaa6a99d10c62c7d6ad"
"fcc3e4ae3b69abc734b5c4a913ac1b99b1c541a058dddbb431cb48f25472d059193211"
"a2da285b4ae02c187f5e74655ae332eb761b1afc4961113c85ac865a6f06d452ebfbc1"
"35afc96fd843dc6a22fda68a05daa53dca9e6a674e0bb11ae3cc4529af5817e69891b2"
"a3572b85336dad65630607a9c3ee011e9b81d9c654f892e4f888fd49707dcd6c097b27"
"5866b29e78acd077d6e79f2a471311f0f219f1c5c32dcdf24f7d6d17e30b");
CheckTestRightShiftHex(
"eb8baf207037a28801f631673410255a2b8f36e868f98793d4cdd5180907b801be38ef"
"aa1ab75420f57f80825d5c0638a7519a777bf85772b616e5883d3f5c6c424cb1f32d71"
"c051203ca1465b15729d0b2a865600c7614db607bc6fe8564ab0c2f2e4a12f252004dd"
"f82bb0d36b23b8f8f1efb2814bdd6a6fb17f90028494a67db72fda1d0c2ef72f170f30"
"4b4a28b3bc51c2e58e8e009785c6584dbdd665834326a6d59b98736836b9044608f3d6"
"37616570a83904b934e0db5c3741e3a83c7d209802cf8c89a6af2d74af2e313630411d"
"240f00c3aca3fb343d20be9f2ce48949ca291d9604963321d2eb4d5732e84749c4d9d1"
"5071595e1a10a665b62ec9da697952efa8f231dd7cb429447f607ec116b9eedfc0bb3f"
"a86366120306c27c5e3ee5918717148ee3481183a181726fa2de825cfbc3d922ff7b2f"
"003d7873f40853b2fa45128ef712df2a46f241907db643cadf5145fcb77cc1a11a2fad"
"fdfabc2b137e68300f2f4cc5d6d508f93f0bab9d5abab5952ebf0e12614801c78d8dde"
"7d43e243d165677ee2d0d92b2c2c98fb86ae736e796536757f54a68ee69e60f2c3c201"
"3418d16d67842414004b3da73ab0c2cc1625b18af0bc73c32e1fa44219f4a4bfcc3975"
"993a6935b6d056f37b14f38009ff817bd8f09139a7fcb065a5562d22976846f883588f"
"d5a7904a54c6b3997aab24aa09e85fb670cf9fe0e72c9fd2351177d18b0a",
2489,
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000075c5d790"
"381bd14400fb18b39a0812ad15c79b74347cc3c9ea66ea8c0483dc00df1c77d50d5baa"
"107abfc0412eae031c53a8cd3bbdfc2bb95b0b72c41e9fae36212658f996b8e028901e"
"50a32d8ab94e8595432b0063b0a6db03de37f42b255861797250979290026efc15d869"
"b591dc7c78f7d940a5eeb537d8bfc801424a533edb97ed0e86177b978b879825a51459"
"de28e172c747004bc2e32c26deeb32c1a193536acdcc39b41b5c82230479eb1bb0b2b8"
"541c825c9a706dae1ba0f1d41e3e904c0167c644d35796ba5797189b1820");
CheckTestRightShiftHex(
"0b0d15d774b99ba942850db1c241026d622134010042e6ee81030c23e4d6d4b0668cfb"
"1be94b064ed5d51ab700c999c41b2b6be0f4b75f3cd0dee87d682e2729f6d68ee2ab1e"
"0dd98ee038395fac6a8a7058a0ecf3353507324652e9277d9aebf6a37662cfe5cda9c3"
"10e2cf278b0a9bea20ad625dd6984fb7bb7918adae491a94293163eebdde9040652399"
"db552d312a2592fd7e7edfde6cff38c365f8f20a02fd26a124d46944381e67174c7225"
"656a5b8e41525c97cde1a5cf70b846670f1cafc655bbf115511d63d0d8db503807efc0"
"cef1716f637b8871035e092003f4709e690350b4c6ad520648a6d17b1964465ada5508"
"bd99df5e68c4915c0e389395e898fd3800d4da40010aca27cdb898126884fca767db34"
"cf03360126a2a848a4bdf28f900cc9cdf5bca267d98692d3dbf6217d9907ae8b4dac61"
"158ff7ca0b6737851967fb1cc4bf0ac841999066372472cff6143d1469bc21bae74f12"
"41f69b483b997e400b879fe90e079478b5f92c5c3c1c47837addcaac7933fedc345b7d"
"04b326d05ffbb1fc1eb10dcb833f1aa40b36c9475bbc8246d8fa5203ecd734d851ea7e"
"7ea56fda62a941016f00e36a4dd353ab6187d210dc37841357ec55b6e932ddbbf176c4"
"b2d3741f36f600a0aa6d40e8be663967a6cf46a8a941c3d5a49b6b59104aee36ab0759"
"f68d8045a2503c6090a9cf8d7daa81402774859948a779af8379b89f41db",
4134,
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000002c3457");
CheckTestRightShiftHex(
"9eb21c29f8f88523b70828a457aeea014e3d1150c2f9ec6e3440672abb91272c264426"
"3b015d039aa3cfe035d34e6296867778bc476ec501e4bf944a4c29ef8f3ccc07aaed6c"
"2fa091cb67d8dfff9ae5ed254392d84211d9f600d6df7c7ef203db7cb9a9ca38c444c0"
"e977138597c39e794e54f59600eee3ca3e745624a02305ebc5d2312f7b5c67b810637a"
"06277b263e7daa6c14f80c6e7f85b6b61ec7d7c6cdcf9a62994b4c002006025d9c489c"
"120400abc37bc7ec2791b3c73237450d510f455e467c6e3f46a8a08840dd627bcf1920"
"387a207788b9c38e9c4138e03b16a54e5feb985fff0968c8de3fa0d69b6484df19ccaa"
"8faad14d3e53a57b41e13e634c31b8b7d63c8893ebc05336a38daf39b4dd226af4cc35"
"b23f93f83ebfb7168d9bbef9b5ee6403e697528e259f3cded4d6da552005f6b3033e95"
"c76a72a4c94b0ee09153ae1d16ddf451bb3f9cd1fac321417a4f0b1f3ed355635e9cd2"
"eb517cf8c051d6c29b51b4605e01af9ce415f7329cf366db4061add032f5b5c8f1d63e"
"8ae633130a6130ecd5c4751c6084b6878a548b8d4d0f3cc4e932b41b6a895238d0b8e0"
"dd04300a986524496ee5a6ef5734a36985328093c3c7a12a89bd0a304b45d85ef2c943"
"6bd8646aa6174756ec8edc5af20c79ec1a8d61b201ffe8343f31f86a6e0292968fc23a"
"aa006719ce79200dfc360bbb039004c0ecaf7448380bec2afac9542ae111",
4159,
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"000000000000000000000000000000000000000000000000000000000001");
CheckTestRightShiftHex(
"9eb21c29f8f88523b70828a457aeea014e3d1150c2f9ec6e3440672abb91272c264426"
"3b015d039aa3cfe035d34e6296867778bc476ec501e4bf944a4c29ef8f3ccc07aaed6c"
"2fa091cb67d8dfff9ae5ed254392d84211d9f600d6df7c7ef203db7cb9a9ca38c444c0"
"e977138597c39e794e54f59600eee3ca3e745624a02305ebc5d2312f7b5c67b810637a"
"06277b263e7daa6c14f80c6e7f85b6b61ec7d7c6cdcf9a62994b4c002006025d9c489c"
"120400abc37bc7ec2791b3c73237450d510f455e467c6e3f46a8a08840dd627bcf1920"
"387a207788b9c38e9c4138e03b16a54e5feb985fff0968c8de3fa0d69b6484df19ccaa"
"8faad14d3e53a57b41e13e634c31b8b7d63c8893ebc05336a38daf39b4dd226af4cc35"
"b23f93f83ebfb7168d9bbef9b5ee6403e697528e259f3cded4d6da552005f6b3033e95"
"c76a72a4c94b0ee09153ae1d16ddf451bb3f9cd1fac321417a4f0b1f3ed355635e9cd2"
"eb517cf8c051d6c29b51b4605e01af9ce415f7329cf366db4061add032f5b5c8f1d63e"
"8ae633130a6130ecd5c4751c6084b6878a548b8d4d0f3cc4e932b41b6a895238d0b8e0"
"dd04300a986524496ee5a6ef5734a36985328093c3c7a12a89bd0a304b45d85ef2c943"
"6bd8646aa6174756ec8edc5af20c79ec1a8d61b201ffe8343f31f86a6e0292968fc23a"
"aa006719ce79200dfc360bbb039004c0ecaf7448380bec2afac9542ae111",
4160,
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"000000000000000000000000000000000000000000000000000000000000");
}
BOOST_AUTO_TEST_SUITE_END()
| 59,379 | 46,928 |
#include "KvsSinkStreamCallbackProvider.h"
LOGGER_TAG("com.amazonaws.kinesis.video.gstkvs");
using namespace com::amazonaws::kinesis::video;
STATUS
KvsSinkStreamCallbackProvider::streamConnectionStaleHandler(UINT64 custom_data,
STREAM_HANDLE stream_handle,
UINT64 time_since_last_buffering_ack) {
UNUSED_PARAM(custom_data);
LOG_DEBUG("Reported streamConnectionStale callback for stream handle " << stream_handle << ". Time since last buffering ack in 100ns: " << time_since_last_buffering_ack);
return STATUS_SUCCESS;
}
STATUS
KvsSinkStreamCallbackProvider::streamErrorReportHandler(UINT64 custom_data,
STREAM_HANDLE stream_handle,
UPLOAD_HANDLE upload_handle,
UINT64 errored_timecode,
STATUS status_code) {
LOG_ERROR("Reported stream error. Errored timecode: " << errored_timecode << " Status: 0x" << std::hex << status_code);
auto customDataObj = reinterpret_cast<KvsSinkCustomData*>(custom_data);
// ignore if the sdk can recover from the error
if (!IS_RECOVERABLE_ERROR(status_code)) {
customDataObj->stream_status = status_code;
}
return STATUS_SUCCESS;
}
STATUS
KvsSinkStreamCallbackProvider::droppedFrameReportHandler(UINT64 custom_data,
STREAM_HANDLE stream_handle,
UINT64 dropped_frame_timecode) {
UNUSED_PARAM(custom_data);
LOG_WARN("Reported droppedFrame callback for stream handle " << stream_handle << ". Dropped frame timecode in 100ns: " << dropped_frame_timecode);
return STATUS_SUCCESS; // continue streaming
}
STATUS
KvsSinkStreamCallbackProvider::streamLatencyPressureHandler(UINT64 custom_data,
STREAM_HANDLE stream_handle,
UINT64 current_buffer_duration) {
UNUSED_PARAM(custom_data);
LOG_DEBUG("Reported streamLatencyPressure callback for stream handle " << stream_handle << ". Current buffer duration in 100ns: " << current_buffer_duration);
return STATUS_SUCCESS;
}
STATUS
KvsSinkStreamCallbackProvider::streamClosedHandler(UINT64 custom_data,
STREAM_HANDLE stream_handle,
UPLOAD_HANDLE upload_handle) {
UNUSED_PARAM(custom_data);
LOG_DEBUG("Reported streamClosed callback for stream handle " << stream_handle << ". Upload handle " << upload_handle);
return STATUS_SUCCESS;
}
| 2,870 | 775 |
#include <ctype.h>
#include "stringiterator.h"
#include "woopsistring.h"
using namespace WoopsiGfx;
StringIterator::StringIterator(const WoopsiString* string) {
_string = string;
_currentChar = _string->getCharArray();
_currentIndex = 0;
}
void StringIterator::moveToFirst() {
_currentChar = _string->getCharArray();
_currentIndex = 0;
}
u8 StringIterator::getCodePointSize() {
// Return 0 if string has no data
if (_string->getLength() == 0) return 0;
char value=*_currentChar;
if (value<0x80) return 1;
if (value<0xC2) return 0; // Can't be a leading char
if (value<0xE0) return 2;
if (value<0xF0) return 3;
if (value<0xF4) return 4; // Doesn't have legal unicode leading char after that
return 0;
}
void StringIterator::moveToLast() {
if (_string->getLength() > 0) {
_currentChar = _string->getCharArray() + _string->getByteCount() - 1;
while ((*_currentChar >= 0x80) && (*_currentChar < 0xC0)) _currentChar--;
// String has been filtered before; no need to check if value >=0xF4
_currentIndex = _string->getLength()-1;
}
}
bool StringIterator::moveToNext() {
if (_currentIndex < _string->getLength() - 1) {
_currentChar += getCodePointSize();
_currentIndex++;
return true;
}
return false;
}
bool StringIterator::moveToPrevious() {
// Abort if already at the start of the string
if (_currentIndex == 0) return false;
// Move back one char to ensure we're in the middle of a char sequence
do {
_currentChar--;
} while ((*_currentChar >= 0x80) && (*_currentChar < 0xC0));
// Loop has ended, so we must have found a valid codepoint; we know
// that we're looking at the previous character index
_currentIndex--;
return true;
}
void StringIterator::iterateForwardsTo(s32 index) {
do {
moveToNext();
} while (index > _currentIndex);
}
void StringIterator::iterateBackwardsTo(s32 index) {
do {
moveToPrevious();
} while (_currentIndex > index);
}
bool StringIterator::moveTo(s32 index) {
// Abort if index makes no sense
if (index < 0) return false;
// Abort if index exceeds the size of the string
if (index >= _string->getLength()) return false;
// Abort if new index matches current index
if (index == _currentIndex) return true;
// Move to end if requested index is at end of string
if (index == _string->getLength() - 1) {
moveToLast();
return true;
}
// Move to start if requested index is 0
if (index == 0) {
moveToFirst();
return true;
}
// Decide if it is faster to iterate over the string from the current point
// or from the front or back
if (index > _currentIndex) {
// Requested index is past current point
// Calculate distance to the requested index from the current point
u32 distanceFromHere = index - _currentIndex;
u32 distanceFromEnd = _string->getLength() - index - 1;
if (distanceFromHere <= distanceFromEnd) {
// Shorter distance from current point to the requested index, so
// scan through string from this point forwards
iterateForwardsTo(index);
return true;
} else {
// Shorter distance from end to the requested index, so
// jump to end of string and scan through string backwards
moveToLast();
iterateBackwardsTo(index);
return true;
}
} else {
// Requested index is before current point
// Calculate distance to the requested index from the current point
u32 distanceFromHere = _currentIndex - index;
u32 distanceFromStart = index;
if (distanceFromHere <= distanceFromStart) {
// Shorter distance from current point to the requested index, so
// scan through string from this point backwards
iterateBackwardsTo(index);
return true;
} else {
// Shorter distance from start to the requested index, so
// jump to start of string and scan through string forwards
moveToFirst();
iterateForwardsTo(index);
return true;
}
}
// Should never reach this
return false;
}
u32 StringIterator::getCodePoint() const {
return _string->getCodePoint(_currentChar, NULL);
}
u32 StringIterator::getInteger(u32* charCount) {
// strtoul() will discard any white space we might currently be looking at
// which isn't the desired behaviour. We prevent this by checking that
// we're looking at a digit before we start
if (isdigit(getCodePoint())) {
char *end = NULL;
u32 digits = strtoul(_currentChar, &end, 10);
if (charCount != NULL) *charCount = (u32)(end - _currentChar);
return digits;
} else {
if (charCount != NULL) *charCount = 0;
return 0;
}
}
| 4,503 | 1,566 |
/*
nmea.cpp - NMEA 0183 sentence decoding library for Wiring & Arduino
Copyright (c) 2008 Maarten Lamers, The Netherlands.
All right reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "Arduino.h"
#include "nmea.h"
#define _GPRMC_TERM "$GPRMC," // GPRMC datatype identifier
#define _LIB_VERSION 1 // software version of this library
//
// constructor method
//
NMEA::NMEA(int connect)
{
// private properties
_gprmc_only = connect;
_gprmc_utc = 0.0;
_gprmc_status = 'V';
_gprmc_lat = 0.0;
_gprmc_long = 0.0;
_gprmc_speed = 0.0;
_gprmc_angle = 0.0;
_terms = 0;
n = 0;
_state = 0;
_parity = 0;
_nt = 0;
f_sentence[0] = 0;
f_terms = 0;
// allocate memory for individual terms of sentence
for (int t=0; t<30; t++) {
_term[t] = (char*) malloc (15 * sizeof(char));
f_term[t] = (char*) malloc (15 * sizeof(char));
(f_term[t])[0] = 0;
}
}
//
// public methods
//
int NMEA::decode(char c) {
// avoid runaway sentences (>99 chars or >29 terms) and terms (>14 chars)
if ((n >= 100) || (_terms >= 30) || (_nt >= 15)) { _state = 0; }
// LF and CR always reset parser
if ((c == 0x0A) || (c == 0x0D)) { _state = 0; }
// '$' always starts a new sentence
if (c == '$') {
_gprmc_tag = 0;
_parity = 0;
_terms = 0;
_nt = 0;
_sentence[0] = c;
n = 1;
_state = 1;
return 0;
}
// parse other chars according to parser state
switch(_state) {
case 0:
// waiting for '$', do nothing
break;
case 1:
// decode chars after '$' and before '*' found
if (n < 7) {
// see if first seven chars match "$GPRMC,"
if (c == _GPRMC_TERM[n]) { _gprmc_tag++; }
}
// add received char to sentence
_sentence[n++] = c;
switch (c) {
case ',':
// ',' delimits the individual terms
(_term[_terms++])[_nt] = 0;
_nt = 0;
_parity = _parity ^ c;
break;
case '*':
// '*' delimits term and precedes checksum term
(_term[_terms++])[_nt] = 0;
_nt = 0;
_state++;
break;
default:
// all other chars between '$' and '*' are part of a term
(_term[_terms])[_nt++] = c;
_parity = _parity ^ c;
break;
}
break;
case 2:
// first char following '*' is checksum MSB
_sentence[n++] = c;
(_term[_terms])[_nt++] = c;
_parity = _parity - (16 * _dehex(c)); // replace with bitshift?
_state++;
break;
case 3:
// second char after '*' completes the checksum (LSB)
_sentence[n++] = c;
_sentence[n++] = 0;
(_term[_terms])[_nt++] = c;
(_term[_terms++])[_nt] = 0;
_state = 0;
_parity = _parity - _dehex(c);
// when parity is zero, checksum was correct!
if (_parity == 0) {
// accept all sentences, or only GPRMC datatype?
if ((!_gprmc_only) || (_gprmc_tag == 6)) {
// copy _sentence[] to f_sentence[]
while ((--n) >= 0) { f_sentence[n] = _sentence[n]; }
// copy all _terms[] to f_terms[]
for (f_terms=0; f_terms<_terms; f_terms++) {
_nt = 0;
while ((_term[f_terms])[_nt]) {
(f_term[f_terms])[_nt] = (_term[f_terms])[_nt];
_nt++;
}
(f_term[f_terms])[_nt] = 0;
}
// when sentence is of datatype GPRMC
if (_gprmc_tag == 6) {
// store values of relevant GPRMC terms
_gprmc_utc = _decimal(_term[1]);
_gprmc_status = (_term[2])[0];
// calculate signed degree-decimal value of latitude term
_gprmc_lat = _decimal(_term[3]) / 100.0;
_degs = floor(_gprmc_lat);
_gprmc_lat = (100.0 * (_gprmc_lat - _degs)) / 60.0;
_gprmc_lat += _degs;
// southern hemisphere is negative-valued
if ((_term[4])[0] == 'S') {
_gprmc_lat = 0.0 - _gprmc_lat;
}
// calculate signed degree-decimal value of longitude term
_gprmc_long = _decimal(_term[5]) / 100.0;
_degs = floor(_gprmc_long);
_gprmc_long = (100.0 * (_gprmc_long - _degs)) / 60.0;
_gprmc_long += _degs;
// western hemisphere is negative-valued
if ((_term[6])[0] == 'W') {
_gprmc_long = 0.0 - _gprmc_long;
}
_gprmc_speed = _decimal(_term[7]);
_gprmc_angle = _decimal(_term[8]);
}
// sentence accepted!
return 1;
}
}
break;
default:
_state = 0;
break;
}
return 0;
}
float NMEA::gprmc_utc() {
// returns decimal value of UTC term of last-known GPRMC sentence
return _gprmc_utc;
}
char NMEA::gprmc_status() {
// returns status character of last-known GPRMC sentence ('A' or 'V')
return _gprmc_status;
}
float NMEA::gprmc_latitude() {
// returns signed degree-decimal latitude value of last-known GPRMC position
return _gprmc_lat;
}
float NMEA::gprmc_longitude() {
// returns signed degree-decimal longitude value of last-known GPRMC position
return _gprmc_long;
}
float NMEA::gprmc_speed(float unit) {
// returns speed-over-ground from last-known GPRMC sentence
return (_gprmc_speed * unit);
}
float NMEA::gprmc_course() {
// returns decimal value of track-angle-made-good term in last-known GPRMC sentence
return _gprmc_angle;
}
float NMEA::gprmc_distance_to(float latitude, float longitude, float unit) {
// returns distance from last-known GPRMC position to given position
return distance_between( _gprmc_lat, _gprmc_long, latitude, longitude, unit);
}
float NMEA::gprmc_course_to(float latitude, float longitude) {
// returns initial course in degrees from last-known GPRMC position to given position
return initial_course( _gprmc_lat, _gprmc_long, latitude, longitude);
}
//float NMEA::gprmc_rel_course_to(float latitude, float longitude) {
// // returns course in degrees to given position, relative to last-known GPRMC track angle
// float rc = initial_course( _gprmc_lat, _gprmc_long, latitude, longitude) - _gprmc_angle;
// if (rc < 0.0) {
// rc += 360.0;
// }
// return rc;
//}
char* NMEA::sentence() {
// returns last received full sentence as zero terminated string
return f_sentence;
}
int NMEA::terms() {
// returns number of terms (including data type and checksum) in last received full sentence
return f_terms;
}
char* NMEA::term(int t) {
// returns term t of last received full sentence as zero terminated string
return f_term[t];
}
float NMEA::term_decimal(int t) {
// returns value of decimally coded term t
return _decimal(f_term[t]);
}
int NMEA::libversion() {
// returns software version of this library
return _LIB_VERSION;
}
//
// private methods
//
float NMEA::distance_between (float lat1, float long1, float lat2, float long2, float units_per_meter) {
// returns distance in meters between two positions, both specified
// as signed decimal-degrees latitude and longitude. Uses great-circle
// distance computation for hypothised sphere of radius 6372795 meters.
// Because Earth is no exact sphere, rounding errors may be upto 0.5%.
float delta = radians(long1-long2);
float sdlong = sin(delta);
float cdlong = cos(delta);
lat1 = radians(lat1);
lat2 = radians(lat2);
float slat1 = sin(lat1);
float clat1 = cos(lat1);
float slat2 = sin(lat2);
float clat2 = cos(lat2);
delta = (clat1 * slat2) - (slat1 * clat2 * cdlong);
delta = sq(delta);
delta += sq(clat2 * sdlong);
delta = sqrt(delta);
float denom = (slat1 * slat2) + (clat1 * clat2 * cdlong);
delta = atan2(delta, denom);
return delta * 6372795 * units_per_meter;
}
float NMEA::initial_course (float lat1, float long1, float lat2, float long2) {
// returns initial course in degrees (North=0, West=270) from
// position 1 to position 2, both specified as signed decimal-degrees
// latitude and longitude.
float dlon = radians(long2-long1);
lat1 = radians(lat1);
lat2 = radians(lat2);
float a1 = sin(dlon) * cos(lat2);
float a2 = sin(lat1) * cos(lat2) * cos(dlon);
a2 = cos(lat1) * sin(lat2) - a2;
a2 = atan2(a1, a2);
if (a2 < 0.0) {
a2 += TWO_PI; // modulo operator doesn't seem to work on floats
}
return degrees(a2);
}
int NMEA::_dehex(char a) {
// returns base-16 value of chars '0'-'9' and 'A'-'F';
// does not trap invalid chars!
if (int(a) >= 65) {
return int(a)-55;
}
else {
return int(a)-48;
}
}
float NMEA::_decimal(char* s) {
// returns base-10 value of zero-termindated string
// that contains only chars '+','-','0'-'9','.';
// does not trap invalid strings!
long rl = 0;
float rr = 0.0;
float rb = 0.1;
boolean dec = false;
int i = 0;
if ((s[i] == '-') || (s[i] == '+')) { i++; }
while (s[i] != 0) {
if (s[i] == '.') {
dec = true;
}
else{
if (!dec) {
rl = (10 * rl) + (s[i] - 48);
}
else {
rr += rb * (float)(s[i] - 48);
rb /= 10.0;
}
}
i++;
}
rr += (float)rl;
if (s[0] == '-') {
rr = 0.0 - rr;
}
return rr;
}
| 9,566 | 3,783 |
//
// Copyright (c) 2016 - 2017 Mesh Consultants Inc.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include "ModelEditLinear.h"
#include <Urho3D/Input/InputEvents.h>
#include <Urho3D/Scene/Node.h>
#include <Urho3D/Resource/ResourceCache.h>
#include <Urho3D/Graphics/Model.h>
#include <Urho3D/Graphics/Material.h>
#include <Urho3D/Graphics/Viewport.h>
#include <Urho3D/Graphics/Renderer.h>
#include <Urho3D/Graphics/Camera.h>
#include <Urho3D/Input/Input.h>
#include <Urho3D/UI/UIElement.h>
#include <Urho3D/UI/UI.h>
#include <Urho3D/Scene/Scene.h>
#include <Urho3D/Scene/SceneEvents.h>
#include <Urho3D/IO/Log.h>
#include "TriMesh.h"
using namespace Urho3D;
ModelEditLinear::ModelEditLinear(Context* context) : Component(context),
editing_(false),
radius_(1.0f),
primaryVertexID_(-1)
{
}
void ModelEditLinear::OnNodeSet(Urho3D::Node* node)
{
Component::OnNodeSet(node);
if (!node)
{
return;
}
// //create the editor
// CreateMeshEditor();
//subscribe to events
SubscribeToEvent(E_MOUSEBUTTONDOWN, URHO3D_HANDLER(ModelEditLinear, HandleMouseDown));
SubscribeToEvent(E_MOUSEMOVE, URHO3D_HANDLER(ModelEditLinear, HandleMouseMove));
SubscribeToEvent(E_MOUSEBUTTONUP, URHO3D_HANDLER(ModelEditLinear, HandleMouseUp));
SubscribeToEvent(E_COMPONENTREMOVED, URHO3D_HANDLER(ModelEditLinear, HandleComponentRemoved));
}
void ModelEditLinear::HandleComponentRemoved(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData)
{
using namespace ComponentRemoved;
URHO3D_LOGINFO("Check MB");
Component* c = (Component*)eventData[P_COMPONENT].GetPtr();
if (c == this)
{
UnsubscribeFromAllEvents();
if (meshEditor_)
{
meshEditor_->Remove();
}
}
}
void ModelEditLinear::CreateMeshEditor()
{
//create billboard set
VariantVector verts = TriMesh_GetVertexList(baseGeometry_);
ResourceCache* rc = GetSubsystem<ResourceCache>();
Material* mat = rc->GetResource<Material>("Materials/BasicPoints.xml");
SharedPtr<Material> clonedMat = mat->Clone();
//Texture* tex = rc->GetResource<Texture>("Textures/SpotWide.png");
float width = 10.0f;
Color col = Color::WHITE;
//clonedMat->SetTexture(TU_DIFFUSE, tex);
clonedMat->SetShaderParameter("MatDiffColor", col);
URHO3D_LOGINFO("Check MA");
meshEditor_ = GetNode()->CreateComponent<BillboardSet>();
meshEditor_->SetNumBillboards(verts.Size());
meshEditor_->SetMaterial(clonedMat);
meshEditor_->SetSorted(true);
meshEditor_->SetFaceCameraMode(FaceCameraMode::FC_ROTATE_XYZ);
meshEditor_->SetFixedScreenSize(true);
//create the vertex renderer
for (int i = 0; i < verts.Size(); i++)
{
Billboard* bb = meshEditor_->GetBillboard(i);
Vector3 vA = verts[i].GetVector3();
//render the point
bb = meshEditor_->GetBillboard(i);
bb->position_ = vA;
bb->size_ = Vector2(width, width);
bb->enabled_ = true;
bb->color_ = col;
}
//commit
meshEditor_->Commit();
}
void ModelEditLinear::SetBaseGeometry(const Urho3D::Variant& geometry)
{
baseGeometry_ = geometry;
//create the editor
CreateMeshEditor();
}
void ModelEditLinear::GetCurrentGeometry(Urho3D::Variant& geometryOut)
{
geometryOut = baseGeometry_;
}
IntVector2 ModelEditLinear::GetScaledMousePosition()
{
IntVector2 mPos = GetSubsystem<Input>()->GetMousePosition();
float scale = GetSubsystem<UI>()->GetScale();
mPos.x_ = (int)(mPos.x_ * (1.0f / scale));
mPos.y_ = (int)(mPos.y_ * (1.0f / scale));
return mPos;
}
void ModelEditLinear::HandleUpdate(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData)
{
}
void ModelEditLinear::HandleMouseDown(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData)
{
using namespace MouseButtonDown;
int mb = eventData[P_BUTTON].GetInt();
if (mb == MOUSEB_LEFT && !editing_) {
URHO3D_LOGINFO("About to raycast..");
if (Raycast()) {
URHO3D_LOGINFO("Hello mouse down!");
//UI* ui = GetSubsystem<UI>();
startScreenPos_ = GetScaledMousePosition();
primaryVertexID_ = raycastResult_.subObject_;
editing_ = true;
}
}
}
void ModelEditLinear::HandleMouseMove(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData)
{
using namespace MouseMove;
if (editing_) {
int x = eventData[P_X].GetInt();
int y = eventData[P_Y].GetInt();
//mpos
//UI* ui = GetSubsystem<UI>();
IntVector2 mPos = GetScaledMousePosition();
IntVector2 screenDeltaVec = mPos - startScreenPos_;
Ray screenRay;
bool res = GetScreenRay(mPos, screenRay);
if (!res)
return;
Vector3 sceneHint = screenRay.origin_ + raycastResult_.distance_ * screenRay.direction_;
Vector3 sceneDeltaVec = sceneHint - raycastResult_.position_;
//update node visuals
BillboardSet* bs = (BillboardSet*)raycastResult_.drawable_;
if (bs && primaryVertexID_ < bs->GetNumBillboards())
{
//retrieve original vertex position
VariantVector verts = TriMesh_GetVertexList(baseGeometry_);
//get the specific billboard
Billboard* b = bs->GetBillboard(primaryVertexID_);
if (primaryVertexID_ >= verts.Size())
{
return;
}
//move the vertex
Vector3 currVert = verts[primaryVertexID_].GetVector3();
//track displacement and index
primaryDelta_ = sceneDeltaVec;
//move the vertex
b->position_ = sceneHint;
bs->Commit();
}
}
}
void ModelEditLinear::HandleMouseUp(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData)
{
using namespace MouseButtonUp;
int mb = eventData[P_BUTTON].GetInt();
if (mb == MOUSEB_LEFT && editing_ && primaryVertexID_ >= 0) {
editing_ = false;
URHO3D_LOGINFO("Hello mouse up!");
//use delta and object transform to move object
Viewport* activeViewport = (Viewport*)GetGlobalVar("activeViewport").GetVoidPtr();
Camera* currentCamera = activeViewport->GetCamera();
if (!currentCamera || !activeViewport)
{
return;
}
VariantVector verts = TriMesh_GetVertexList(baseGeometry_);
VariantVector faces = TriMesh_GetFaceList(baseGeometry_);
// Need to get the billboard ID that was moved, and compute the vector from that billboard to the original vert
Vector3 disp = primaryDelta_;
int bIndex = primaryVertexID_;
Vector3 orgVert = verts[bIndex].GetVector3();
Variant geomOut;
Vector<Vector3> deltas;
Vector<int> ids;
//always push the moved vertex
deltas.Push(primaryDelta_);
ids.Push(primaryVertexID_);
//find deltas and ids
for (int i = 0; i < verts.Size(); i++)
{
Vector3 v = verts[i].GetVector3();
float dist = (v - orgVert).Length();
if (dist < radius_)
{
if (dist != 0 && radius_ != 0) {
deltas.Push(((radius_-dist)/radius_)*primaryDelta_);
ids.Push(i);
}
}
else
{
// deltas.Push(Vector3::ZERO);
// ids.Push(i);
}
}
//do deformation
DoLinearDeformation(deltas, ids, geomOut);
//update base geometry
baseGeometry_ = geomOut;
//update handles based on new geometry
UpdateHandles();
// this is roundabout
VariantMap data;
data["EditedMesh"] = geomOut;
//fill data
SendEvent("ModelEditChangeLinear", data);
//reset
primaryDelta_ = Vector3::ZERO;
primaryVertexID_ = -1;
}
}
void ModelEditLinear::UpdateHandles()
{
if (meshEditor_)
{
URHO3D_LOGINFO("Updating mesh editor");
VariantVector verts = TriMesh_GetVertexList(baseGeometry_);
if (verts.Size() == meshEditor_->GetNumBillboards())
{
for (int i = 0; i < verts.Size(); i++)
{
meshEditor_->GetBillboard(i)->position_ = verts[i].GetVector3();
}
}
meshEditor_->Commit();
}
}
void ModelEditLinear::DoHarmonicDeformation(Urho3D::Vector<Vector3> deltas, Urho3D::Vector<int> ids, Variant& geomOut)
{
//////do harmonic deformation
//init matrices
Eigen::MatrixXd V;
Eigen::MatrixXi F;
Eigen::VectorXi b;
Eigen::MatrixXd D_bc;
Eigen::MatrixXd D;
//TriMeshToMatrices(mesh, V, F);
VariantVector verts = TriMesh_GetVertexList(baseGeometry_);
TriMeshToDoubleMatrices(baseGeometry_, V, F);
//collect the disp vecs and indices
int numVecs = Min(deltas.Size(), ids.Size());
b.resize(numVecs);
D_bc.resize(numVecs, 3);
//create the handle and displacement vectors
for (int i = 0; i < numVecs; i++)
{
int idx = ids[i];
Vector3 v = deltas[i];
D_bc.row(i) = Eigen::RowVector3d(v.x_, v.y_, v.z_);
b[i] = idx;
}
//finally, proceed with calculation
int power = 2;
// igl::harmonic(V, F, b, D_bc, power, D);
int dRows = D.rows();
int dCols = D.cols();
VariantVector vecsOut;
for (int i = 0; i < D.rows(); i++)
{
Eigen::RowVector3d v = D.row(i);
Vector3 dV = Vector3(v.x(), v.y(), v.z());
vecsOut.Push(dV);
Vector3 orgVert = verts[i].GetVector3();
verts[i] = orgVert + dV;
}
//create new trimesh
geomOut = TriMesh_Make(verts, TriMesh_GetFaceList(baseGeometry_));
URHO3D_LOGINFO("Done Harmonic Deformation!");
}
void ModelEditLinear::DoLinearDeformation(Urho3D::Vector<Urho3D::Vector3> deltas, Urho3D::Vector<int> ids, Urho3D::Variant & geomOut)
{
// This will just add the deltas to the vertices specified by the vector of IDs.
VariantVector verts = TriMesh_GetVertexList(baseGeometry_);
VariantVector faces = TriMesh_GetFaceList(baseGeometry_);
for (int i = 0; i < ids.Size(); ++i) {
if (ids[i] > verts.Size())
return;
Vector3 currVert = verts[ids[i]].GetVector3();
verts[ids[i]] = currVert + deltas[i];
}
geomOut = TriMesh_Make(verts, faces);
}
bool ModelEditLinear::GetScreenRay(Urho3D::IntVector2 screenPos, Urho3D::Ray& ray)
{
//try to get default viewport first
Viewport* activeViewport = (Viewport*)GetGlobalVar("activeViewport").GetVoidPtr();
if (!activeViewport)
{
URHO3D_LOGINFO("No active viewport found...");
return false;
}
//also check if we are casting from inside a ui region
UIElement* uiRegion = (UIElement*)GetGlobalVar("activeUIRegion").GetPtr();
//get default ray
ray = activeViewport->GetScreenRay(screenPos.x_, screenPos.y_);
if (uiRegion)
{
IntVector2 ePos = uiRegion->GetScreenPosition();
IntVector2 eSize = uiRegion->GetSize();
float x = (screenPos.x_ - ePos.x_) / (float)eSize.x_;
float y = (screenPos.y_ - ePos.y_) / (float)eSize.y_;
ray = activeViewport->GetCamera()->GetScreenRay(x, y);
}
return true;
}
bool ModelEditLinear::Raycast()
{
//get mouse pos via ui system to account for scaling
UI* ui = GetSubsystem<UI>();
IntVector2 pos = GetScaledMousePosition();
//get general screen ray, taking ui stuff in to account
Ray cameraRay;
bool res = GetScreenRay(pos, cameraRay);
if(!res)
{
URHO3D_LOGINFO("Bad ray or no viewport found");
return false;
}
//do cast
PODVector<RayQueryResult> results;
RayOctreeQuery query(results, cameraRay, RAY_TRIANGLE, 600.0f, DRAWABLE_GEOMETRY);
GetScene()->GetComponent<Octree>()->Raycast(query);
if (results.Size() > 0)
{
for (int i = 0; i < results.Size(); i++)
{
BillboardSet* bs = (BillboardSet*)results[i].drawable_;
if (bs == meshEditor_)
{
raycastResult_ = results[i];
return true;
}
}
}
return false;
}
| 11,890 | 4,702 |
// -*- C++ -*-
// Copyright (C) 2021 Dmitry Igrishin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
// Dmitry Igrishin
// dmitigr@gmail.com
#include "basics.hpp"
#include "exceptions.hpp"
#include "server_connection.hpp"
#include "streambuf.hpp"
#include "../error/assert.hpp"
#include "../math.hpp"
#include <algorithm>
#include <array>
#include <cstdio>
#include <istream>
#include <limits>
#include <ostream>
/*
* By defining DMITIGR_FCGI_DEBUG some convenient stuff for debugging
* will be available, for example, server_Streambuf::print().
*/
//#define DMITIGR_FCGI_DEBUG
#ifdef DMITIGR_FCGI_DEBUG
#include <iostream>
#endif
namespace dmitigr::fcgi::detail {
/**
* @brief The base implementation of Streambuf.
*/
class iStreambuf : public Streambuf {
private:
friend server_Streambuf;
using Streambuf::Streambuf;
};
/**
* @brief The implementation of the `std::streambuf` for a FastCGI server.
*/
class server_Streambuf final : public iStreambuf {
public:
using Type = Stream_type;
~server_Streambuf() override
{
try {
close();
} catch (const std::exception& e) {
std::fprintf(stderr, "dmitigr::fcgi: %s\n", e.what());
} catch (...) {
std::fprintf(stderr, "dmitigr::fcgi: failure\n");
}
}
server_Streambuf(const server_Streambuf&) = delete;
server_Streambuf& operator=(const server_Streambuf&) = delete;
server_Streambuf(server_Streambuf&&) = delete;
server_Streambuf& operator=(server_Streambuf&&) = delete;
/**
* @brief The constructor.
*/
server_Streambuf(iServer_connection* const connection, char_type* const buffer,
const std::streamsize buffer_size, const Type type)
: type_{type}
, connection_{connection}
{
DMITIGR_ASSERT(connection);
setg(nullptr, nullptr, nullptr);
setp(nullptr, nullptr);
setbuf(buffer, buffer_size);
DMITIGR_ASSERT(is_invariant_ok());
}
/**
* @brief Closes the stream.
*
* If this instance represents the streambuf of the output stream (either
* Stream_type::err or Stream_type::out) then transmits the end records to
* the FastCGI client and sets `is_end_of_stream_` to `true`. (The
* transmission of the end records takes place if and only if it is not
* contradicts the protocol.)
*
* @par Effects
* `is_closed()`. Also, unsets both the get area and the put area.
*/
void close()
{
if (is_closed())
return;
if (!is_reader()) {
const auto* const inbuf = dynamic_cast<server_Streambuf*>(connection_->in().streambuf());
DMITIGR_ASSERT(inbuf && inbuf->is_reader() && !inbuf->is_closed());
const auto role = connection_->role();
DMITIGR_ASSERT(role == Role::authorizer || inbuf->type_ != Type::params);
if (role != Role::filter || inbuf->type_ == Type::data || inbuf->unread_content_length_ == 0) {
is_end_records_must_be_transmitted_ = true;
sync();
} else
throw Generic_exception{"not all FastCGI stdin has been read by Filter"};
DMITIGR_ASSERT(is_end_of_stream_ && !is_end_records_must_be_transmitted_);
}
setg(nullptr, nullptr, nullptr);
setp(nullptr, nullptr);
DMITIGR_ASSERT(is_closed());
DMITIGR_ASSERT(is_invariant_ok());
}
/**
* @returns `true` if this instance is for receiving the
* data from the FastCGI client, or `false` otherwise.
*/
bool is_reader() const
{
return (type_ == Type::in || type_ == Type::params || type_ == Type::data);
}
/**
* @returns `true` if this instance is unusable anymore, or `false` otherwise.
*/
bool is_closed() const
{
return is_reader() ? !eback() : !pbase();
}
/**
* @returns `true` if this instance is ready to switching to the filter mode.
*/
bool is_ready_to_filter_data() const
{
return !is_closed() && (connection_->role() == Role::filter) && (type_ == Type::in) && is_end_of_stream_;
}
/**
* @returns The stream type.
*/
Type stream_type() const
{
return type_;
}
protected:
// std::streambuf overridings:
server_Streambuf* setbuf(char_type* const buffer, const std::streamsize size) override
{
DMITIGR_ASSERT(buffer && (2048 <= size && size <= 65528));
if ((eback() != nullptr && eback() != buffer_) ||
(pbase() != nullptr && pbase() != buffer_ + sizeof(detail::Header)))
throw Generic_exception{"cannot set FastCGI buffer (there are pending data)"};
constexpr std::streamsize alignment = 8;
buffer_ = buffer;
buffer_size_ = size - (alignment - math::padding(size, alignment)) % alignment;
if (is_reader()) {
setg(buffer_, buffer_, buffer_);
buffer_end_ = buffer_;
setp(nullptr, nullptr);
} else {
/*
* First sizeof(detail::Header) bytes of the buffer_ are reserved for Header.
* Last byte of the buffer_ is reserved for byte passed to overflow(). Thus,
* epptr() can be used to store this byte.
*/
setg(nullptr, nullptr, nullptr);
setp(buffer_ + sizeof(detail::Header), buffer_ + buffer_size_ - 1);
}
DMITIGR_ASSERT(is_invariant_ok());
return this;
}
int sync() override
{
const auto ch = overflow(traits_type::eof());
return traits_type::eq_int_type(ch, traits_type::eof()) ? -1 : 0;
}
int_type underflow() override
{
DMITIGR_ASSERT(is_reader() && !is_closed());
if (is_end_of_stream_)
return traits_type::eof();
detail::Header header{};
std::size_t read_header_length{};
while (true) {
// Reading the stream records.
if (gptr() == buffer_end_) {
const std::streamsize count = connection_->io_->read(buffer_, buffer_size_);
if (count > 0) {
buffer_end_ = buffer_ + count;
setg(buffer_, buffer_, buffer_end_);
} else
throw Generic_exception{"FastCGI protocol violation"};
}
DMITIGR_ASSERT(buffer_end_ - gptr() > 0);
// Setting up the get area for the content.
if (unread_content_length_ > 0) {
const std::streamsize count = std::min(unread_content_length_, buffer_end_ - gptr());
unread_content_length_ -= count;
if (!is_content_must_be_discarded_) {
setg(gptr(), gptr(), gptr() + count); // Get area now contains all available content bytes at the moment.
DMITIGR_ASSERT(is_invariant_ok());
return traits_type::to_int_type(*gptr());
} else {
gbump(static_cast<int>(count)); // Discarding.
if (unread_content_length_ > 0)
continue;
else
is_content_must_be_discarded_ = false;
}
}
DMITIGR_ASSERT(unread_content_length_ == 0);
// Skipping the padding.
if (unread_padding_length_ > 0) {
const std::streamsize count = std::min(unread_padding_length_, buffer_end_ - gptr());
unread_padding_length_ -= count;
gbump(static_cast<int>(count)); // Skipping.
if (unread_padding_length_ > 0)
continue;
}
DMITIGR_ASSERT(unread_padding_length_ == 0);
// ---------------
// The start point
// ---------------
// Accumulating the header.
{
const std::size_t count = std::min(sizeof(header) - read_header_length, static_cast<std::size_t>(buffer_end_ - gptr()));
std::memcpy(reinterpret_cast<char*>(&header) + read_header_length, gptr(), count);
read_header_length += count;
gbump(static_cast<int>(count)); // Already consumed.
if (read_header_length < sizeof(header))
continue;
}
DMITIGR_ASSERT(read_header_length == sizeof(header));
// Processing the header.
{
const auto set_end_of_stream = [&]()
{
setg(gptr(), gptr(), gptr());
is_end_of_stream_ = true;
DMITIGR_ASSERT(is_invariant_ok());
};
setg(gptr(), gptr(), gptr());
const auto phr = process_header(header);
switch(phr) {
case Process_header_result::request_rejected:
set_end_of_stream();
return traits_type::eof();
case Process_header_result::management_processed:
continue;
case Process_header_result::content_must_be_consumed:
if (unread_content_length_ == 0) {
set_end_of_stream();
if (is_ready_to_filter_data())
reset_reader(Type::data);
return traits_type::eof();
} else
continue;
case Process_header_result::content_must_be_discarded:
is_content_must_be_discarded_ = true;
continue;
}
}
}
}
int_type overflow(const int_type ch) override
{
DMITIGR_ASSERT(!is_reader() && !is_closed());
if (is_end_of_stream_)
return traits_type::eof();
const bool is_eof = traits_type::eq_int_type(ch, traits_type::eof());
DMITIGR_ASSERT(pbase() == (buffer_ + sizeof(detail::Header)));
if (std::streamsize content_length = pptr() - pbase()) {
/*
* If `ch` is not EOF we need to place `ch` at the location pointed to by
* pptr(). (It's ok if pptr() == epptr() since that location is a valid
* writable location reserved for extra `ch`.)
* The content should be aligned by padding if necessary, and the record
* header must be injected at the reserved space [buffer_, pbase()).
* After that the result record will be ready to send to a client.
*/
// Store `ch` if it's not EOF.
if (!is_eof) {
DMITIGR_ASSERT(pptr() <= epptr());
*pptr() = static_cast<char>(ch);
pbump(1); // Yes, pptr() > epptr() is possible here, but this is ok.
content_length++;
}
// Aligning the content by padding if necessary.
const auto padding_length = dmitigr::math::padding<std::streamsize>(content_length, 8);
DMITIGR_ASSERT(padding_length <= epptr() - pptr() + 1);
std::memset(pptr(), 0, static_cast<std::size_t>(padding_length));
pbump(static_cast<int>(padding_length));
// Injecting the header.
auto* const header = reinterpret_cast<detail::Header*>(buffer_);
*header = detail::Header{static_cast<detail::Record_type>(type_),
connection_->request_id(),
static_cast<std::size_t>(content_length),
static_cast<std::size_t>(padding_length)};
// Sending the record.
if (const auto record_size = pptr() - buffer_; static_cast<std::size_t>(record_size) > sizeof(detail::Header)) {
const std::streamsize count = connection_->io_->write(static_cast<const char*>(buffer_), record_size);
DMITIGR_ASSERT(count == record_size);
is_put_area_at_least_once_consumed_ = true;
}
}
setp(buffer_ + sizeof(detail::Header), buffer_ + buffer_size_ - 1);
if (is_end_records_must_be_transmitted_) {
/*
* We'll use buffer_ directly here. (Space before pbase() will be used.)
* data_size is a size of data in the buffer_ to send.
*/
std::streamsize data_size{};
const auto is_empty = [this]()
{
return pptr() == pbase() && !is_put_area_at_least_once_consumed_;
};
if (type_ != Type::err || !is_empty()) {
/*
* When transmitting a stream other than stderr, at least one record of
* the stream type must be trasmitted, even if the stream is empty.
* When transmitting a stream of type stderr and there is no errors to
* report, either no stderr records or one zero-length stderr record
* must be transmitted. (As optimization, no stderr records are
* transmitted if the stream is empty.)
*/
auto* const header = reinterpret_cast<detail::Header*>(buffer_ + data_size);
*header = detail::Header{static_cast<detail::Record_type>(type_), connection_->request_id(), 0, 0};
data_size += sizeof(detail::Header);
}
/*
* Assume that the stream of type `out` is closes last. (This must be
* guaranteed by the implementation of Listener.)
*/
if (type_ == Type::out) {
auto* const record = reinterpret_cast<detail::End_request_record*>(buffer_ + data_size);
*record = detail::End_request_record{
connection_->request_id(),
connection_->application_status(),
detail::Protocol_status::request_complete};
data_size += sizeof(detail::End_request_record);
}
if (data_size > 0) {
const std::streamsize count = connection_->io_->write(static_cast<const char*>(buffer_), data_size);
DMITIGR_ASSERT(count == data_size);
}
is_end_records_must_be_transmitted_ = false;
is_end_of_stream_ = true;
}
DMITIGR_ASSERT(is_invariant_ok());
return is_eof ? traits_type::not_eof(ch) : ch;
}
private:
friend server_Istream;
/**
* @brief A result of process_header().
*/
enum class Process_header_result {
/** A request is rejected. */
request_rejected,
/** A management record processed. */
management_processed,
/** A content from a client must be consumed. */
content_must_be_consumed,
/** A content from a client must be discarded. */
content_must_be_discarded
};
Type type_{};
bool is_content_must_be_discarded_{};
bool is_end_of_stream_{};
bool is_end_records_must_be_transmitted_{};
bool is_put_area_at_least_once_consumed_{};
char_type* buffer_{};
char_type* buffer_end_{}; // Used by underflow() to mark the actual end of get area. (buffer_end_ <= buffer_ + buffer_size_).
std::streamsize buffer_size_{}; // The available size of the area pointed by buffer_.
std::streamsize unread_content_length_{};
std::streamsize unread_padding_length_{};
iServer_connection* const connection_{};
// ===========================================================================
bool is_invariant_ok() const
{
const bool connection_ok = (connection_ != nullptr);
const bool buffer_ok = (buffer_ != nullptr) &&
(!is_reader() || ((buffer_end_ != nullptr) && (buffer_end_ <= buffer_ + buffer_size_)));
const bool buffer_size_ok = (buffer_size_ >= 2048) && (buffer_size_ <= 65528) && (buffer_size_ % 8 == 0);
const bool unread_content_length_ok = (unread_content_length_ <= buffer_size_ &&
unread_content_length_ <= static_cast<std::streamsize>(detail::Header::max_content_length));
const bool unread_padding_length_ok = (unread_padding_length_ <= buffer_size_ &&
unread_padding_length_ <= static_cast<std::streamsize>(detail::Header::max_padding_length));
const bool reader_ok = (!is_reader() ||
(type_ == Type::params) ||
(connection_->role() == Role{0}) || // unread yet
(connection_->role() == Role::responder && type_ == Type::in) ||
(connection_->role() == Role::filter && (type_ == Type::in || type_ == Type::data)));
const bool closed_ok = (is_closed() && (is_reader() || is_end_of_stream_) &&
(eback() == nullptr && gptr() == nullptr && egptr() == nullptr) &&
(pbase() == nullptr && pptr() == nullptr && epptr() == nullptr))
||
(is_reader() &&
!(eback() == nullptr && gptr() == nullptr && egptr() == nullptr) &&
(pbase() == nullptr && pptr() == nullptr && epptr() == nullptr))
||
(!is_reader() &&
(eback() == nullptr && gptr() == nullptr && egptr() == nullptr) &&
!(pbase() == nullptr && pptr() == nullptr && epptr() == nullptr));
const bool put_area_ok = is_reader() ||
(is_closed() ||
((pbase() <= pptr() && pptr() <= epptr()) &&
(is_end_of_stream_ || (pbase() == buffer_ + sizeof(detail::Header)))));
const bool get_area_ok = !is_reader() ||
(is_closed() ||
(eback() <= gptr() && gptr() <= egptr() && egptr() <= buffer_end_));
const bool result = connection_ok && buffer_ok && buffer_size_ok && unread_content_length_ok && unread_padding_length_ok &&
reader_ok & closed_ok && put_area_ok && get_area_ok;
return result;
}
// ===========================================================================
/**
* @brief Processes a record by the header info.
*
* - (1) If `header` is the header of begin-request record then rejecting
* the request;
* - (2) If `header` is the header of management record, then responds with
* get-values-result or unknown-type record;
* - (3) If `header` is the header of stream record then do nothing.
*
* @returns
* In case (1): Process_header_result::request_rejected.
* In case (2): Process_header_result::management_processed.
* In case (3):
* a) Process_header_result::content_must_be_discarded
* if `(header.request_id() != connection_->request_id())`;
* b) Process_header_result::content_must_be_consumed
* if and only if `(header.record_type() == type_)`.
*
* @throws Generic_exception in case of (1) or on protocol violation.
*
* @par Effects
* In all cases: `(unread_content_length_ == header.content_length() && unread_padding_length_ == header.padding_length())`;
* In case (2): the effects of underflow().
*/
Process_header_result process_header(const detail::Header header)
{
header.check_validity();
unread_content_length_ = static_cast<decltype(unread_content_length_)>(header.content_length());
unread_padding_length_ = static_cast<decltype(unread_content_length_)>(header.padding_length());
const auto end_request = [&](const detail::Protocol_status protocol_status)
{
const detail::End_request_record record{header.request_id(), 0, protocol_status};
const auto count = connection_->io_->write(reinterpret_cast<const char*>(&record), sizeof(record));
DMITIGR_ASSERT(count == sizeof(record));
};
// Called in cases of protocol violation.
const auto end_request_protocol_violation = [&]()
{
end_request(detail::Protocol_status::cant_mpx_conn);
throw Generic_exception{"FastCGI protocol violation"};
};
const auto process_management_record = [&]()
{
namespace math = dmitigr::math;
if (header.record_type() == detail::Record_type::get_values) {
constexpr std::size_t max_variable_name_length = 15; // Length of "FCGI_MPXS_CONNS".
constexpr std::size_t max_body_length = 3 * (sizeof(char) + sizeof(char) + max_variable_name_length + sizeof(char));
constexpr std::streamsize max_record_length = sizeof(detail::Header) + max_body_length;
std::array<unsigned char, math::aligned<std::size_t>(max_record_length, 8)> record;
static_assert((record.size() % 8 == 0));
// Reading the requested variables.
const auto variables = [&]()
{
std::istream stream{this};
return detail::Names_values{stream, 3};
}();
if (unread_content_length_ > 0)
end_request_protocol_violation();
// Filling up the content of get-values-result.
const auto content_offset = std::begin(record) + sizeof(detail::Header);
auto p = content_offset;
const auto variables_count = variables.pair_count();
for (std::size_t i = 0; i < variables_count; ++i) {
const auto name = variables.pair(i)->name();
char value{};
if (name == "FCGI_MAX_CONNS")
value = '1';
else if (name == "FCGI_MAX_REQS")
value = '1';
else if (name == "FCGI_MPXS_CONNS")
value = '0';
else
continue; // Ignoring other variables specified in the get-values record.
const auto name_size = name.size();
if (name_size > std::numeric_limits<unsigned char>::max())
end_request_protocol_violation();
// Note: name_size + 3 - is a space required to store: {char(name_size), char(1), name.data(), char(value)} string.
DMITIGR_ASSERT(name_size + 3 <= static_cast<std::size_t>(std::cend(record) - p));
*p++ = static_cast<unsigned char>(name_size); // name_size
*p++ = static_cast<unsigned char>(1); // 1
p = std::copy(cbegin(name), cend(name), p); // name.data()
*p++ = static_cast<unsigned char>(value); // value
}
using detail::Header;
const auto content_length = p - content_offset;
const auto padding_length = math::padding<std::streamsize>(content_length, 8);
const auto record_length = static_cast<int>(sizeof(Header)) + content_length + padding_length;
auto* const h = reinterpret_cast<Header*>(record.data());
*h = detail::Header{detail::Record_type::get_values_result,
Header::null_request_id, static_cast<std::size_t>(content_length), static_cast<std::size_t>(padding_length)};
const auto count = connection_->io_->write(reinterpret_cast<const char*>(record.data()), record_length);
DMITIGR_ASSERT(count == record_length);
} else {
const detail::Unknown_type_record r{header.record_type()};
const std::streamsize record_length = sizeof(r);
const auto count = connection_->io_->write(reinterpret_cast<const char*>(&r), record_length);
DMITIGR_ASSERT(count == record_length);
}
return Process_header_result::management_processed;
};
Process_header_result result{};
if (header.record_type() == detail::Record_type::begin_request) {
end_request(detail::Protocol_status::cant_mpx_conn);
result = Process_header_result::content_must_be_discarded;
} else if (header.is_management_record())
result = process_management_record();
else if (header.request_id() != connection_->request_id())
result = Process_header_result::content_must_be_discarded;
else if (header.record_type() == static_cast<detail::Record_type>(type_))
result = Process_header_result::content_must_be_consumed;
else
end_request_protocol_violation();
DMITIGR_ASSERT(is_invariant_ok());
return result;
}
/**
* @brief Resets the input stream to read the data of the specified type.
*
* @par Requires
* `is_reader()`.
*/
void reset_reader(const Type type)
{
DMITIGR_ASSERT(is_reader() && !is_closed());
type_ = type;
is_end_of_stream_ = false;
is_content_must_be_discarded_ = false;
unread_content_length_ = 0;
unread_padding_length_ = 0;
DMITIGR_ASSERT(is_invariant_ok());
}
#ifdef DMITIGR_FCGI_DEBUG
template<typename ... Types>
void print(Types&& ... msgs) const
{
if (type_ == Stream_type::out) {
((std::cerr << std::forward<Types>(msgs) << " "), ...);
std::cerr << std::endl;
}
}
#endif
};
} // namespace dmitigr::fcgi::detail
| 23,537 | 7,572 |
// Copyright 2021 Long Le Phi. All rights reserved.
// Use of this source code is governed by a MIT license that can be
// found in the LICENSE file.
#include "problems/1_2/solution.hpp"
#include <numeric>
#if defined(_MSC_VER)
# include <intrin.h>
#endif
namespace {
using longlp::solution::Problem_1_2;
inline auto CountTrailingZeros(const uintmax_t u) -> uintmax_t {
#if defined(_MSC_VER)
unsigned long trailing_zero = 0;
if (_BitScanForward64(&trailing_zero, u) != 0U) {
return trailing_zero;
}
// This is undefined, I better choose 64 than 0
return 64;
#elif defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
return __builtin_ctzll(u);
#endif
}
} // namespace
// static
auto Problem_1_2::StandardGCD(const uintmax_t u, const uintmax_t v)
-> uintmax_t {
return std::gcd(u, v);
}
// https://lemire.me/blog/2013/12/26/fastest-way-to-compute-the-greatest-common-divisor/
// static
auto Problem_1_2::BinaryGCD(uintmax_t u, uintmax_t v) -> uintmax_t {
// Base cases: gcd(n, 0) = gcd(0, n) = n
if (u == 0) {
return v;
}
if (v == 0) {
return u;
}
// Using identity 2: gcd(2u, 2v) = 2*gcd(u, v)
// Using identity 3: gcd(2u, v) = gcd(u, v), if v is odd (2 is not a common
// divisor). Similarly, gcd(u, 2v) = gcd(u, v) if u is odd.
// gcd(u * 2^i, v * 2^j) = gcd(u, v) * 2^k with u, v odd and k = min(i, j).
// 2^k is the greatest power of two that divides both u and v
// The number of trailing 0-bits in x, starting at the least significant bit
// position, represent for k.
uintmax_t k = CountTrailingZeros(u | v);
// Identity 3: gcd(u, v * 2^j) = gcd(u, v) (u is known to be odd)
u >>= CountTrailingZeros(u);
do {
// Identity 3: gcd(u, v * 2^j) = gcd(u, v) (u is known to be odd)
v >>= CountTrailingZeros(v);
// swap to make sure u <= v
if (u > v) {
std::swap(u, v);
}
// Using identity 4 (gcd(u, v) = gcd(|v-u|, min(u, v))
v = v - u;
} while (v != 0);
// Identity 1: gcd(u, 0) = u
// The shift by k is necessary to add back the 2^k factor that was removed b
// fore the loop
return u << k;
}
| 2,145 | 905 |
//
// GammaLib: Computer Vision library
//
// Copyright (C) 1998-2015 Luca Ballan <ballanlu@gmail.com> http://lucaballan.altervista.org/
//
// Third party copyrights are property of their respective owners.
//
//
// The MIT License(MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
//
//
//
#include "../stdInclude.h"
#include "../common.h"
#include <string.h>
#include "Stack.h"
#include "IOBuffer.h"
#include "ListEntities.h"
#include "List.h"
#include "MathAddOn.h"
#include "IOAddOn.h"
#ifdef SYSTEM_WINDOWS
#include <Commdlg.h>
#endif
#pragma warning(3:4244)
ConsoleProgressBarr::ConsoleProgressBarr() {
printf("[ ] 0%%");
RelativeDisplayPos=36;
WritedPercent=0;
WritedPosition=0;
RemainTText[0]=0;
}
ConsoleProgressBarr::~ConsoleProgressBarr() {
for(UINT i=0;i<RelativeDisplayPos-36;i++) printf("\x08");
printf(" Completed.");
UINT CurDispPos=36+8+13;
for(UINT i=CurDispPos;i<RelativeDisplayPos;i++) printf(" ");
}
void ConsoleProgressBarr::Aggiorna(UINT Pos,UINT Max) {
Speed.CheckPoint(Pos);
char Out[70];
UINT CurDispPos;
bool AggiornaPercent=false;
bool AggiornaPosition=false;
bool AggiornaRemainTime=false;
double x=Pos/(double)Max;
Speed.RemainTime(Out,Max);
if (strcmp(RemainTText,Out)) {
AggiornaRemainTime=true;
strcpy(RemainTText,Out);
}
if (WritedPercent != (unsigned int)Approx(100 * x)) {
AggiornaPercent=true;
WritedPercent=Approx(100*x);
}
if (WritedPosition != (unsigned int)Approx(30 * x)) { // TODO??
AggiornaPosition=true;
WritedPosition=Approx(30*x);
}
if (AggiornaPosition) {
for(UINT i=0;i<RelativeDisplayPos;i++) printf("\x08");
for(UINT i=0;i<WritedPosition;i++) printf("=");
for(UINT i=WritedPosition;i<30;i++) printf(" ");
printf("] ");
printf("%3u%%",WritedPercent);
printf(" %s left",RemainTText);
CurDispPos=36+8+(int)strlen(RemainTText);
if (CurDispPos>RelativeDisplayPos) RelativeDisplayPos=CurDispPos;
else for(UINT i=CurDispPos;i<RelativeDisplayPos;i++) printf(" ");
} else {
if (AggiornaPercent) {
for(UINT i=0;i<RelativeDisplayPos-32;i++) printf("\x08");
printf("%3u%%",WritedPercent);
printf(" %s left",RemainTText);
CurDispPos=36+8+(int)strlen(RemainTText);
if (CurDispPos>RelativeDisplayPos) RelativeDisplayPos=CurDispPos;
else for(UINT i=CurDispPos;i<RelativeDisplayPos;i++) printf(" ");
} else {
if (AggiornaRemainTime) {
for(UINT i=0;i<RelativeDisplayPos-36;i++) printf("\x08");
printf(" %s left",RemainTText);
CurDispPos=36+8+(int)strlen(RemainTText);
if (CurDispPos>RelativeDisplayPos) RelativeDisplayPos=CurDispPos;
else for(UINT i=CurDispPos;i<RelativeDisplayPos;i++) printf(" ");
}
}
}
}
void PrintTime(UINT seconds) {
char Out[50];
PrintTime(Out,seconds);
printf(Out);
}
char *PluralSingular(int num,char *singular,char *plural) {
if (num==1) return singular;
return plural;
}
void PrintTime(char *Out,UINT seconds) {
UINT minutes,hours,days,years;
minutes=seconds/60;
seconds%=60;
hours=minutes/60;
minutes%=60;
days=hours/24;
hours%=24;
years=days/365;
days%=365;
if (years!=0) {
sprintf(Out,"%u %s, %u %s",years,PluralSingular(years,"year","years"),days,PluralSingular(days,"day","days"));
} else {
if (days!=0) {
sprintf(Out,"%u %s, %u %s",days,PluralSingular(days,"day","days"),hours,PluralSingular(hours,"hour","hours"));
} else {
if (hours!=0) {
sprintf(Out,"%u %s, %u min",hours,PluralSingular(hours,"hour","hours"),minutes);
} else {
if (minutes!=0) sprintf(Out,"%u min, %u sec",minutes,seconds);
else {
sprintf(Out,"%u sec",seconds);
}
}
}
}
}
void Add_File_Extension(char *filename,char *ext) {
size_t pos=strcspn(filename,".");
if (pos==strlen(filename)) {
strcat(filename,".");
strcat(filename,ext);
}
}
char *Get_File_Extension(char *filename) {
char *Ext=strrchr(filename,'.');
if (Ext==NULL) return NULL;
Ext++;
return Ext;
}
char *Get_File_Path(const char *filename) {
const char *Ext=strrchr(filename,'\\');
if (Ext==NULL) return NULL;
char *Path=new char[Ext-filename+1];
memcpy(Path,filename,Ext-filename);
Path[Ext-filename]=0;
return Path;
}
char *Set_File_Path(char *Path,char *filename) {
if (Path==NULL) {
char *filename_ext=new char[strlen(filename)+1];
strcpy(filename_ext,filename);
return filename_ext;
}
char *filename_ext=new char[strlen(Path)+strlen(filename)+2];
strcpy(filename_ext,Path);
strcat(filename_ext,"\\");
strcat(filename_ext,filename);
return filename_ext;
}
bool CompareFileExtension(char *filename,char *ext) {
char *Ext=Get_File_Extension(filename);
if (Ext==NULL) return false;
if (!_stricmp(Ext,ext)) return true;
return false;
}
void CenteredCout(char *text,int scr_width) {
int len=(int)strlen(text);
if (scr_width>=len) {
int padd=(scr_width-len)/2;
for(int i=0;i<padd;i++) std::cout<<" ";
std::cout<<text;
for(int i=padd+len;i<scr_width;i++) std::cout<<" ";
} else std::cout<<text;
}
#ifdef USE_FIGLET
#include "D:\Developer\Luca\Common Libs\figlet\figlet.hpp"
void AsciiArtCout(char *text) {
Figlet::standard.print(text);
}
#else
void AsciiArtCout(char *text) {
cout << text;
}
#endif
#ifdef SYSTEM_WINDOWS
MouseEvent_struct::MouseEvent_struct() {
Event[0]=Event[1]=Event[2]=Event[3]=0;
ButtonState[0]=ButtonState[1]=ButtonState[2]=-1;
pos_x=pos_y=0.0;
pos_x_pxs=pos_y_pxs=0;
last_pos_x=last_pos_y=0.0;
drag_bottom=-1;
dropped=false;
delta_x=delta_y=0.0;
TrackEvent=false;
}
bool GetMouseState(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam,MouseEvent_struct *MouseEvents_) {
bool mouse_event=false;
MouseEvent_struct MouseEvents=(*MouseEvents_);
MouseEvents.Event[0]=MouseEvents.Event[1]=MouseEvents.Event[2]=MouseEvents.Event[3]=0;
MouseEvents.pos_x=MouseEvents.pos_y=0.0;
MouseEvents.pos_x_pxs=MouseEvents.pos_y_pxs=0;
MouseEvents.start_dragging=false;
MouseEvents.dropped=false;
MouseEvents.delta_x=MouseEvents.delta_y=0.0;
MouseEvents.DBLClick[0]=MouseEvents.DBLClick[1]=MouseEvents.DBLClick[2]=0;
switch(uMsg) {
case WM_RBUTTONDOWN:
MouseEvents.Event[2]=1;
MouseEvents.ButtonState[2]=1;
mouse_event=true;
break;
case WM_LBUTTONDOWN:
MouseEvents.Event[0]=1;
MouseEvents.ButtonState[0]=1;
mouse_event=true;
break;
case WM_MBUTTONDOWN:
MouseEvents.Event[1]=1;
MouseEvents.ButtonState[1]=1;
mouse_event=true;
break;
case WM_RBUTTONUP:
MouseEvents.Event[2]=-1;
MouseEvents.ButtonState[2]=-1;
mouse_event=true;
break;
case WM_LBUTTONUP:
MouseEvents.Event[0]=-1;
MouseEvents.ButtonState[0]=-1;
mouse_event=true;
break;
case WM_MBUTTONUP:
MouseEvents.Event[1]=-1;
MouseEvents.ButtonState[1]=-1;
mouse_event=true;
break;
case WM_MOUSELEAVE:
MouseEvents.Event[3]=1;
mouse_event=true;
MouseEvents.TrackEvent=false;
break;
case WM_MOUSEMOVE:
if (!MouseEvents.TrackEvent) {
MouseEvents.TrackEvent=true;
TRACKMOUSEEVENT tm;
tm.cbSize=sizeof(TRACKMOUSEEVENT);
tm.dwFlags=TME_LEAVE;
tm.hwndTrack=hWnd;
tm.dwHoverTime=0;
TrackMouseEvent(&tm);
}
MouseEvents.Event[3]=1;
mouse_event=true;
break;
case WM_LBUTTONDBLCLK:
MouseEvents.DBLClick[0]=1;
mouse_event=true;
break;
case WM_MBUTTONDBLCLK:
MouseEvents.DBLClick[1]=1;
mouse_event=true;
break;
case WM_RBUTTONDBLCLK:
MouseEvents.DBLClick[2]=1;
mouse_event=true;
break;
}
if (mouse_event) {
int mx=LOWORD(lParam);
int my=HIWORD(lParam);
if (mx & 1 << 15) mx -= (1 << 16);
if (my & 1 << 15) my -= (1 << 16);
RECT Rect;int w,h;
GetClientRect(hWnd,&Rect);
w=Rect.right-Rect.left;
h=Rect.bottom-Rect.top;
MouseEvents.pos_x=(mx-(w/2.0))/(w/2.0);
MouseEvents.pos_y=(-my+(h/2.0))/(h/2.0);
MouseEvents.pos_x_pxs=mx;
MouseEvents.pos_y_pxs=my;
if (MouseEvents.drag_bottom==-1) {
if (MouseEvents.Event[1]==1) MouseEvents.drag_bottom=1;
if (MouseEvents.Event[2]==1) MouseEvents.drag_bottom=2;
if (MouseEvents.Event[0]==1) MouseEvents.drag_bottom=0;
if (MouseEvents.drag_bottom!=-1) {
MouseEvents.last_pos_x=MouseEvents.pos_x;
MouseEvents.last_pos_y=MouseEvents.pos_y;
MouseEvents.start_dragging=true;
SetCapture(hWnd);
}
} else {
MouseEvents.delta_x=MouseEvents.pos_x-MouseEvents.last_pos_x;
MouseEvents.delta_y=MouseEvents.pos_y-MouseEvents.last_pos_y;
if (MouseEvents.Event[MouseEvents.drag_bottom]==-1) {
MouseEvents.dropped=true;
MouseEvents.drag_bottom=-1;
ReleaseCapture();
}
}
(*MouseEvents_)=MouseEvents;
}
return mouse_event;
}
bool Get_File_Dialog(HWND hWnd,char *filename,int bufflen,char *filter,int action) {
OPENFILENAME ofn;
ZeroMemory(filename, bufflen);
ofn.lStructSize = sizeof(OPENFILENAME);
ofn.hInstance = GetModuleHandle(NULL);
ofn.hwndOwner = hWnd;
ofn.lpstrFile = filename;
ofn.nMaxFile = bufflen;
ofn.lpstrFilter = filter;
ofn.lpstrCustomFilter = NULL;
ofn.nMaxCustFilter=0;
ofn.nFilterIndex = 1;
ofn.nFileOffset = 0;
ofn.lpstrDefExt = NULL;
ofn.lpfnHook = NULL;
ofn.lCustData = 0;
ofn.lpTemplateName = NULL;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_EXPLORER | OFN_LONGNAMES | OFN_HIDEREADONLY | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR;
if (action==GFD_OPEN) {
ofn.lpstrTitle="Open...";
ofn.Flags=ofn.Flags|OFN_FILEMUSTEXIST;
if (GetOpenFileName(&ofn)) return true;
} else {
ofn.Flags=ofn.Flags|OFN_OVERWRITEPROMPT;
ofn.lpstrTitle="Save...";
if (GetSaveFileName(&ofn)) return true;
}
return false;
}
void PopUp(HWND hWnd,LPCTSTR Title,LPCTSTR fmt,...) {
char text[400];
va_list ap;
if (fmt == NULL) return;
va_start(ap,fmt); // Parses The String For Variables
vsprintf(text,fmt,ap); // And Converts Symbols To Actual Numbers
va_end(ap); // Results Are Stored In Text
MessageBox(hWnd,text,Title,MB_OK);
}
#endif
int Write_Over_last_index=-1;
void Write_Over(const char *fmt, ...) {
char text[256];
va_list ap;
if (fmt == NULL) return;
va_start(ap,fmt);
vsprintf(text,fmt,ap);
va_end(ap);
if (Write_Over_last_index!=-1) {
for(int i=0;i<Write_Over_last_index;i++) printf("\x08 \x08");
}
Write_Over_last_index=(int)strlen(text);
printf("%s",text);
}
void Reset_Write_Over() {
Write_Over_last_index=-1;
}
CommandParser::CommandParser(int argc,char* argv[]) {
num_elements=argc-1;
elements=argv+1;
used_ID[0]=0;
invalid_option_parameters=false;
}
CommandParser::~CommandParser() {
}
int CommandParser::GetOptionIndex(char ID) {
int index=0;
char ID_[2];ID_[0]=ID;ID_[1]=0;_strlwr(ID_);
if (strcspn(used_ID,ID_)==strlen(used_ID)) strcat(used_ID,ID_);
while (index<num_elements) {
if (elements[index][0]=='-') {
_strlwr(elements[index]);
if (elements[index][1]==ID_[0]) break;
}
index++;
}
return index;
}
int CommandParser::GetNumOptionParameters(int option_index) {
int i=1;
while(true) {
if (option_index+i>=num_elements) break;
if (elements[option_index+i][0]=='-') break;
i++;
}
i--;
return i;
}
bool CommandParser::GetParameter(char ID,int param_index,char **&Out) {
int index=GetOptionIndex(ID);
if (index==num_elements) return false;
if (param_index==0) {Out=NULL;return true;}
for(int i=1;i<=param_index;i++) {
if (index+i>=num_elements) return false;
if (elements[index+i][0]=='-') return false;
}
Out=elements+index+param_index;
return true;
}
bool CommandParser::GetParameter(char ID,char *type,...) {
char **Out;
int num=(int)strlen(type);
if (!GetParameter(ID,num,Out)) return false;
if (!GetParameter(ID,1,Out)) return false;
va_list marker;
va_start(marker,type);
for(int i=0;i<num;i++) {
if (Out[i][0]=='-') return false;
if (type[i]=='s') strcpy(va_arg(marker,char*),Out[i]);
if (type[i]=='i') *va_arg(marker,int*)=atoi(Out[i]);
if (type[i]=='c') *(va_arg(marker,char*))=Out[i][0];
if (type[i]=='f') *(va_arg(marker,float*))=(float)atof(Out[i]);
if (type[i]=='d') *(va_arg(marker,double*))=atof(Out[i]);
}
va_end(marker);
return true;
}
bool CommandParser::GetFlag(char ID) {
char **Out;
bool exists=GetParameter(ID,0,Out);
if (exists) {
if (GetNumOptionParameters(GetOptionIndex(ID))!=0) {
printf("Invalid number of parameters for option -%c.\n",ID);
invalid_option_parameters=true;
}
}
return exists;
}
bool CommandParser::GetParameterE(char ID,char *type,...) {
char **Out;
int opt_index=GetOptionIndex(ID);
if (opt_index==num_elements) return false;
int n_param=GetNumOptionParameters(opt_index);
int j=0;
int lenght=(int)strlen(type);
int num=-1;
char *typeB=new char[strlen(type)+2];
typeB[0]=0;
for(int i=0;i<lenght;i++) {
if (type[i]=='[') {
if (j<=n_param) num=j;
else break;
continue;
}
if (type[i]==']') {
if (j<=n_param) num=j;
else break;
continue;
}
typeB[j++]=type[i];
typeB[j]=0;
}
if (j<=n_param) num=j;
if (n_param!=num) {
printf("Invalid number of parameters for option -%c.\n",ID);
invalid_option_parameters=true;
delete[]typeB;
return false;
}
typeB[num]=0;
if (!GetParameter(ID,1,Out)) {delete[]typeB;return false;}
va_list marker;
va_start(marker,type);
for(int i=0;i<num;i++) {
if (Out[i][0]=='-') {delete[]typeB;return false;}
if (typeB[i]=='s') strcpy(va_arg(marker,char*),Out[i]);
if (typeB[i]=='i') *va_arg(marker,int*)=atoi(Out[i]);
if (typeB[i]=='c') *(va_arg(marker,char*))=Out[i][0];
if (typeB[i]=='f') *(va_arg(marker,float*))=(float)atof(Out[i]);
if (typeB[i]=='d') *(va_arg(marker,double*))=atof(Out[i]);
}
va_end(marker);
delete[]typeB;
return true;
}
bool CommandParser::CheckInvalid() {
int index=0;
if (invalid_option_parameters) return false;
while (index<num_elements) {
if (elements[index][0]=='-') {
char ID_[2];ID_[0]=elements[index][1];ID_[1]=0;_strlwr(ID_);
if (strcspn(used_ID,ID_)==strlen(used_ID)) {
printf("Invalid option -%s.\n",ID_);
return false;
}
}
index++;
}
return true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////// VERSIONE ESTESA ///////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
//////// TODO: TESTARE!! ///////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
/*
CommandParser::CommandParser(int argc,char* argv[]) {
num_elements=argc-1;
elements=argv+1;
used_ID[0]=0;
}
CommandParser::~CommandParser() {
}
bool CommandParser::GetParameter(char *ID,int param_index,char **&Out,int ricorrenza=1) {
int index=0;
char *ID_=strcln(ID);strlwr(ID_);
char *ID_S=strcln(ID_);strcat(ID_S,";");
if (strcspn(used_ID,ID_S)==strlen(used_ID)) strcat(used_ID,ID_S);
delete []ID_S;
int ricorrenza_corrente=0;
while (index<num_elements) {
if (elements[index][0]=='-') {
strlwr(elements[index]);
if (!strcmp((elements[index])+1,ID_)) {
ricorrenza_corrente++;
if (ricorrenza_corrente==ricorrenza) break;
}
}
index++;
}
delete []ID_;
if (index==num_elements) return false;
if (param_index==0) {Out=NULL;return true;}
for(int i=1;i<=param_index;i++) {
if (index+i>=num_elements) return false;
if (elements[index+i][0]=='-') return false;
}
Out=elements+index+param_index;
return true;
}
bool CommandParser::GetFlag(char *ID) {
char **Out;
return GetParameter(ID,0,Out);
}
// Note:
// Si puo' aggiungere un nome di parametro piu' lungo della singola lettera
// Si puo' aggiungere ricorrenza
// CheckInvalid giusto?
bool CommandParser::GetParameter(char *ID,char *type,...) {
char **Out;
int num=(int)strlen(type);
if (!GetParameter(ID,num,Out)) return false;
if (!GetParameter(ID,1,Out)) return false;
va_list marker;
va_start(marker,type);
for(int i=0;i<num;i++) {
if (Out[i][0]=='-') return false;
if (type[i]=='s') strcpy(va_arg(marker,char*),Out[i]);
if (type[i]=='i') *va_arg(marker,int*)=atoi(Out[i]);
if (type[i]=='c') *(va_arg(marker,char*))=Out[i][0];
if (type[i]=='f') *(va_arg(marker,float*))=(float)atof(Out[i]);
if (type[i]=='d') *(va_arg(marker,double*))=atof(Out[i]);
}
va_end(marker);
return true;
}
bool CommandParser::GetParameterE(char *ID,char *type,...) {
char **Out;
int j=0;
int lenght=(int)strlen(type);
int num=-1;
char *typeB=new char[strlen(type)+2];
typeB[0]=0;
for(int i=0;i<lenght;i++) {
if (type[i]=='[') {
if (GetParameter(ID,j,Out)) num=j;
else break;
continue;
}
if (type[i]==']') {
if (GetParameter(ID,j,Out)) num=j;
else break;
continue;
}
typeB[j++]=type[i];
typeB[j]=0;
}
if (GetParameter(ID,j,Out)) num=j;
if (num==-1) {delete typeB;return false;}
typeB[num]=0;
if (!GetParameter(ID,1,Out)) {delete typeB;return false;}
va_list marker;
va_start(marker,type);
for(int i=0;i<num;i++) {
if (Out[i][0]=='-') {delete typeB;return false;}
if (typeB[i]=='s') strcpy(va_arg(marker,char*),Out[i]);
if (typeB[i]=='i') *va_arg(marker,int*)=atoi(Out[i]);
if (typeB[i]=='c') *(va_arg(marker,char*))=Out[i][0];
if (typeB[i]=='f') *(va_arg(marker,float*))=(float)atof(Out[i]);
if (typeB[i]=='d') *(va_arg(marker,double*))=atof(Out[i]);
}
va_end(marker);
delete typeB;
return true;
}
bool CommandParser::GetParameter(char *ID,int recurrence,char *type,...) {
char **Out;
int num=(int)strlen(type);
if (!GetParameter(ID,num,Out,recurrence)) return false;
if (!GetParameter(ID,1,Out,recurrence)) return false;
va_list marker;
va_start(marker,type);
for(int i=0;i<num;i++) {
if (Out[i][0]=='-') return false;
if (type[i]=='s') strcpy(va_arg(marker,char*),Out[i]);
if (type[i]=='i') *va_arg(marker,int*)=atoi(Out[i]);
if (type[i]=='c') *(va_arg(marker,char*))=Out[i][0];
if (type[i]=='f') *(va_arg(marker,float*))=(float)atof(Out[i]);
if (type[i]=='d') *(va_arg(marker,double*))=atof(Out[i]);
}
va_end(marker);
return true;
}
bool CommandParser::GetParameterE(char *ID,int recurrence,char *type,...) {
char **Out;
int j=0;
int lenght=(int)strlen(type);
int num=-1;
char *typeB=new char[strlen(type)+2];
typeB[0]=0;
for(int i=0;i<lenght;i++) {
if (type[i]=='[') {
if (GetParameter(ID,j,Out,recurrence)) num=j;
else break;
continue;
}
if (type[i]==']') {
if (GetParameter(ID,j,Out,recurrence)) num=j;
else break;
continue;
}
typeB[j++]=type[i];
typeB[j]=0;
}
if (GetParameter(ID,j,Out,recurrence)) num=j;
if (num==-1) {delete typeB;return false;}
typeB[num]=0;
if (!GetParameter(ID,1,Out,recurrence)) {delete typeB;return false;}
va_list marker;
va_start(marker,type);
for(int i=0;i<num;i++) {
if (Out[i][0]=='-') {delete typeB;return false;}
if (typeB[i]=='s') strcpy(va_arg(marker,char*),Out[i]);
if (typeB[i]=='i') *va_arg(marker,int*)=atoi(Out[i]);
if (typeB[i]=='c') *(va_arg(marker,char*))=Out[i][0];
if (typeB[i]=='f') *(va_arg(marker,float*))=(float)atof(Out[i]);
if (typeB[i]=='d') *(va_arg(marker,double*))=atof(Out[i]);
}
va_end(marker);
delete typeB;
return true;
}
bool CommandParser::CheckInvalid() {
int index=0;
while (index<num_elements) {
if (elements[index][0]=='-') {
char *ID_S=strcln((elements[index])+1);strcat(ID_S,";");strlwr(ID_S);
if (strcspn(used_ID,ID_S)==strlen(used_ID)) {
printf("Invalid -%s option.\n",(elements[index])+1);
delete []ID_S;
return false;
}
delete []ID_S;
}
index++;
}
return true;
}
*/
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Text
//
char *OrdinalsPostFix[]={"st","nd","rd","th"};
char *OrdinalNumbersPostfix(int num) {
switch(num) {
case 1:
return OrdinalsPostFix[0];
case 2:
return OrdinalsPostFix[1];
case 3:
return OrdinalsPostFix[2];
default:
return OrdinalsPostFix[3];
}
}
//
// String Functions
//
char *strcln(const char *str) {
if (str==NULL) return NULL;
char *x=new char[strlen(str)+1];
strcpy(x,str);
return x;
}
void str_replace(char **str,const char *new_text) {
SDELETEA((*str));
(*str)=strcln(new_text);
}
wchar_t *CharToWChar(char *str) {
DWORD dwNum=MultiByteToWideChar(CP_ACP,0,str,-1,NULL,0);
wchar_t *n=new wchar_t[dwNum];
MultiByteToWideChar(CP_ACP,0,str,-1,n,dwNum);
return n;
}
bool str_begin(const char *str,const char *begin) {
// Ritorna true se str comincia con begin
int size_begin=(int)strlen(begin);
int size_str=(int)strlen(str);
if (size_str<size_begin) return false;
for(int i=0;i<size_begin;i++)
if (str[i]!=begin[i]) return false;
return true;
}
//
// Buffer Functions
//
BYTE *bsprintf(char *format,...) {
char *p;
size_t size,len;
va_list marker;
BYTE *buffer,*buffer_p;
len=strlen(format);
size=0;
p=format;
for(size_t i=0;i<len;i++) {
if (*p=='c') size+=sizeof(char);
if (*p=='i') size+=sizeof(int);
if (*p=='d') size+=sizeof(double);
if (*p=='p') size+=sizeof(void*);
p++;
}
buffer_p=buffer=new BYTE[size];
p=format;
va_start(marker,format);
for(size_t i=0;i<len;i++) {
if (*p=='c') {
*((char *)buffer_p)=va_arg(marker,char);
buffer_p+=sizeof(char);
}
if (*p=='i') {
*((int *)buffer_p)=va_arg(marker,int);
buffer_p+=sizeof(int);
}
if (*p=='d') {
*((double *)buffer_p)=va_arg(marker,double);
buffer_p+=sizeof(double);
}
if (*p=='p') {
*((void **)buffer_p)=va_arg(marker,void *);
buffer_p+=sizeof(void *);
}
p++;
}
va_end(marker);
return buffer;
}
void bscanf(BYTE *buffer,char *format,...) {
char *p;
size_t len=strlen(format);
BYTE *buffer_p;
buffer_p=buffer;
p=format;
va_list marker;
va_start(marker,format);
for(size_t i=0;i<len;i++) {
if (*p=='c') {
*(va_arg(marker,char *))=*((char *)buffer_p);
buffer_p+=sizeof(char);
}
if (*p=='i') {
*(va_arg(marker,int *))=*((int *)buffer_p);
buffer_p+=sizeof(int);
}
if (*p=='d') {
*(va_arg(marker,double *))=*((double *)buffer_p);
buffer_p+=sizeof(double);
}
if (*p=='p') {
*(va_arg(marker,void **))=*((void **)buffer_p);
buffer_p+=sizeof(void *);
}
p++;
}
va_end(marker);
}
void bscanf_pointers(BYTE *buffer,char *format,...) {
char *p;
size_t len=strlen(format);
BYTE *buffer_p;
buffer_p=buffer;
p=format;
va_list marker;
va_start(marker,format);
for(size_t i=0;i<len;i++) {
if (*p=='c') {
*(va_arg(marker,char **))=((char *)buffer_p);
buffer_p+=sizeof(char);
}
if (*p=='i') {
*(va_arg(marker,int **))=((int *)buffer_p);
buffer_p+=sizeof(int);
}
if (*p=='d') {
*(va_arg(marker,double **))=((double *)buffer_p);
buffer_p+=sizeof(double);
}
if (*p=='p') {
*(va_arg(marker,void ***))=((void **)buffer_p);
buffer_p+=sizeof(void *);
}
p++;
}
va_end(marker);
}
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
// ------------------- Console -----------------------------------------
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
void WindowsErrorExit() {
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
DWORD dw = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL );
lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
(lstrlen((LPCTSTR)lpMsgBuf)+40)*sizeof(TCHAR));
wsprintf((LPTSTR)lpDisplayBuf,
TEXT("Error %d: %s\n"),
dw, lpMsgBuf);
MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK);
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
ExitProcess(dw);
}
PCHAR* GetArgvArgc(int* _argc) {
PCHAR CmdLine=GetCommandLine();
PCHAR* argv;
PCHAR _argv;
ULONG len;
ULONG argc;
CHAR a;
ULONG i, j;
BOOLEAN in_QM;
BOOLEAN in_TEXT;
BOOLEAN in_SPACE;
len = (ULONG)strlen(CmdLine);
i = ((len+2)/2)*sizeof(PVOID) + sizeof(PVOID);
argv = (PCHAR*)GlobalAlloc(GMEM_FIXED,
i + (len+2)*sizeof(CHAR));
_argv = (PCHAR)(((PUCHAR)argv)+i);
argc = 0;
argv[argc] = _argv;
in_QM = FALSE;
in_TEXT = FALSE;
in_SPACE = TRUE;
i = 0;
j = 0;
while( a = CmdLine[i] ) {
if(in_QM) {
if(a == '\"') {
in_QM = FALSE;
} else {
_argv[j] = a;
j++;
}
} else {
switch(a) {
case '\"':
in_QM = TRUE;
in_TEXT = TRUE;
if(in_SPACE) {
argv[argc] = _argv+j;
argc++;
}
in_SPACE = FALSE;
break;
case ' ':
case '\t':
case '\n':
case '\r':
if(in_TEXT) {
_argv[j] = '\0';
j++;
}
in_TEXT = FALSE;
in_SPACE = TRUE;
break;
default:
in_TEXT = TRUE;
if(in_SPACE) {
argv[argc] = _argv+j;
argc++;
}
_argv[j] = a;
j++;
in_SPACE = FALSE;
break;
}
}
i++;
}
_argv[j] = '\0';
argv[argc] = NULL;
(*_argc) = argc;
return argv;
}
#include <io.h>
#include <stdio.h>
#include <fstream>
void getConsole() {
int fd;
FILE *fp;
HANDLE hCon;
AllocConsole();
// Make printf happy
hCon = GetStdHandle(STD_OUTPUT_HANDLE);
fd = _open_osfhandle((intptr_t)(hCon), 0);
fp = _fdopen(fd, "w");
*stdout = *fp;
setvbuf(stdout, NULL, _IONBF, 0);
}
void closeConsole() {
FreeConsole();
}
| 27,391 | 11,850 |
#include <aoc/pass.hpp>
#include <algorithm>
#include <cassert>
#include <string_view>
namespace
{
}
namespace aoc2020
{
Seat parse_pass(std::string const & seat)
{
assert(seat.length() == 10);
auto calculate_assignment = [](std::string_view info, int low, int high,
char left, char right) {
auto calculate_midpoint = [](int low, int high) {
auto const distance = high - low + 1;
return low + (distance / 2);
};
std::for_each(
std::begin(info), std::end(info),
[&low, &high, calculate_midpoint, left, right](auto ch) {
auto const new_boundary = calculate_midpoint(low, high);
if(ch == left)
{
high = new_boundary;
}
else
{
assert(ch == right);
low = new_boundary;
}
});
return low;
};
return Seat{calculate_assignment(std::string_view(seat.data(), 7), 0,
127, 'F', 'B'),
calculate_assignment(std::string_view(seat.data() + 7, 3),
0, 8, 'L', 'R')};
}
int calculate_id(Seat const & seat) noexcept
{
return (seat.row * 8) + seat.column;
}
} // namespace aoc2020
| 1,512 | 435 |
// Problem Link : https://www.codechef.com/LTIME101C/problems/PROBCAT
#include <iostream>
using namespace std;
int main() {
int t;cin>>t;
while(t--){
int x; cin>>x;
if(x>=1 && x<100)
cout<<"Easy";
else if(x>=100 && x<200)
cout<<"Medium";
else if(x>=200 && x<=300)
cout<<"Hard";
cout<<endl;
}
return 0;
}
| 347 | 170 |
#include "TestsPerformer.h"
#include "ObjectsGeneratorTest.h"
#include "MapGeneratorTest.h"
#include <memory>
#include <iostream>
using namespace std;
using namespace DeathMaskGame::Tests;
void TestsPerformer::perform() {
cout << "Tests started" << endl;
{
auto objectsGeneratorTest = make_shared<ObjectsGeneratorTest>();
auto result = objectsGeneratorTest->perform();
if (!result)
{
throw logic_error("Objects Generator Test failed");
}
}
{
auto mapGeneratorTest = make_shared<MapGeneratorTest>();
auto result = mapGeneratorTest->perform();
if (!result)
{
throw logic_error("Map Generator Test failed");
}
}
cout << "Tests ended" << endl;
}; | 683 | 227 |
#include "entity.h"
#include "render.h"
#include "global.h"
#include <GLFW/glfw3.h>
#include <glm/gtx/transform.hpp>
entity_data_base EntityDataBase = {};
internal void
UpdateModelMatrixComponents(std::vector<model_matrix_component> &Components
, std::vector<entity_data> &Entities)
{
model_matrix_component *End = &( Components.back() ) + 1;
for (model_matrix_component *Component = &( Components[0] )
; Component != End
; ++Component)
{
entity_data *Entity = &( Entities[Component->EntityID] );
glm::mat4 TranslateMatrix = glm::translate(Entity->Position3D);
glm::mat4 ScaleMatrix = glm::scale(Entity->Scale3D);
Component->TRS = TranslateMatrix * ScaleMatrix;
}
}
internal void
UpdateRenderComponents(std::vector<render_component> &Components
, std::vector<model_matrix_component> &ModelMatrices
, std::vector<entity_data> &Entities)
{
render_component *End = &( Components.back() ) + 1;
for (render_component *Component = &( Components[0] )
; Component != End
; ++Component)
{
entity_data *Entity = &Entities[Component->EntityID];
int32 ModelMatrixIndex = Entity->Components.ModelMatrixComponentIndex;
if (ModelMatrixIndex != MISSING_COMPONENT)
{
model_instance Instance{ Component->Model, ModelMatrices[ModelMatrixIndex].TRS };
Component->Layer->Instances.push_back(Instance);
}
}
}
internal void
UpdateKeyboardComponents(std::vector<keyboard_component> &Components
, std::vector<entity_data> &Entities)
{
local_persist auto GetLateral = [](const glm::vec3 &Vector) -> glm::vec3
{ return glm::normalize(glm::vec3(Vector.x, 0.0f, Vector.z)); };
keyboard_component *End = &( Components.back() ) + 1;
for (keyboard_component *Component = &( Components[0] )
; Component != End
; ++Component)
{
entity_data *Entity = &Entities[Component->EntityID];
if (Entity->Components.KeyboardComponentIndex != MISSING_COMPONENT)
{
glm::vec3 LateralDirection3D = GetLateral(Entity->Direction3D);
if (glm::all(glm::lessThan(Entity->Velocity3D
, glm::vec3(100000000.0f))))
{
if (WindowData.KeyMap[GLFW_KEY_W])
Entity->Velocity3D += LateralDirection3D;
if (WindowData.KeyMap[GLFW_KEY_A]) Entity->Velocity3D -= glm::cross(LateralDirection3D, glm::vec3(0.0f, 1.0f, 0.0f));
if (WindowData.KeyMap[GLFW_KEY_S]) Entity->Velocity3D -= LateralDirection3D;
if (WindowData.KeyMap[GLFW_KEY_D]) Entity->Velocity3D += glm::cross(LateralDirection3D, glm::vec3(0.0f, 1.0f, 0.0f));
if (WindowData.KeyMap[GLFW_KEY_SPACE]) Entity->Velocity3D += glm::vec3(0.0f, 1.0f, 0.0f);
if (WindowData.KeyMap[GLFW_KEY_LEFT_SHIFT]) Entity->Velocity3D += glm::vec3(0.0f, -1.0f, 0.0f);
}
}
}
}
// TODO Parameterize mouse sensitivity
#define MOUSE_SENSITIVITY 0.02f
internal void
UpdateMouseComponents(std::vector<mouse_component> &Components
, std::vector<entity_data> &Entities)
{
local_persist auto RotateDirection = [](const glm::vec2 &CursorDifference
, const glm::vec3 &Direction
, window_data &WindowData) -> glm::vec3
{
glm::vec3 NewDirection = Direction;
float XAngle = glm::radians(-CursorDifference.x) * MOUSE_SENSITIVITY;
float YAngle = glm::radians(-CursorDifference.y) * MOUSE_SENSITIVITY;
NewDirection = glm::mat3(glm::rotate(XAngle, glm::vec3(0.0f, 1.0f, 0.0f))) * NewDirection;
glm::vec3 YRotateAxis = glm::cross(NewDirection, glm::vec3(0.0f, 1.0f, 0.0f));
NewDirection = glm::mat3(glm::rotate(YAngle, YRotateAxis)) * NewDirection;
return NewDirection;
};
mouse_component *End = &( Components.back() ) + 1;
for (mouse_component *Component = &( Components[0] )
; Component != End
; ++Component)
{
entity_data *Entity = &Entities[Component->EntityID];
if (WindowData.MouseMoved)
{
glm::vec2 Difference = WindowData.CurrentMousePosition - Component->PreviousMousePosition;
Component->PreviousMousePosition = WindowData.CurrentMousePosition;
Entity->Direction3D = normalize(RotateDirection(Difference
, Entity->Direction3D
, WindowData));
}
}
}
#define SPEED 5.0f
internal void
UpdatePhysicsComponents(std::vector<physics_component> &Components
, std::vector<entity_data> &Entities)
{
physics_component *End = &( Components.back() ) + 1;
for (physics_component *Component = &( Components[0] )
; Component != End
; ++Component)
{
entity_data *Entity = &Entities[Component->EntityID];
Entity->Position3D += Entity->Velocity3D * TimeData.Elapsed() * SPEED;
Entity->Velocity3D = glm::vec3(0.0f);
}
}
uint32
entity_data_base::CreateEntity(const string_view &Name)
{
uint32 ID = Entities.size();
IndexMap[Name] = ID;
Entities.push_back(entity_data {});
return ID;
}
entity_data *
entity_data_base::GetEntity(uint32 ID)
{
return &Entities[ID];
}
void
entity_data_base::Update(void)
{
UpdateModelMatrixComponents(ModelMatrixComponents.List
, Entities);
UpdateRenderComponents(RenderComponents.List
, ModelMatrixComponents.List
, Entities);
UpdateKeyboardComponents(KeyboardComponents.List
, Entities);
UpdateMouseComponents(MouseComponents.List,
Entities);
UpdatePhysicsComponents(PhysicsComponents.List
, Entities);
}
| 5,493 | 2,077 |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "platform/platform.h"
#include "terrain/terrCellMaterial.h"
#include "core/util/safeRelease.h"
#include "terrain/terrData.h"
#include "terrain/terrCell.h"
#include "materials/materialFeatureTypes.h"
#include "materials/materialManager.h"
#include "terrain/terrFeatureTypes.h"
#include "terrain/terrMaterial.h"
#include "renderInstance/renderDeferredMgr.h"
#include "shaderGen/shaderGen.h"
#include "shaderGen/featureMgr.h"
#include "scene/sceneRenderState.h"
#include "materials/sceneData.h"
#include "gfx/util/screenspace.h"
#include "lighting/advanced/advancedLightBinManager.h"
S32 sgMaxTerrainMaterialsPerPass = 32;
AFTER_MODULE_INIT( MaterialManager )
{
Con::NotifyDelegate callabck( &TerrainCellMaterial::_updateDefaultAnisotropy );
Con::addVariableNotify( "$pref::Video::defaultAnisotropy", callabck );
}
Vector<TerrainCellMaterial*> TerrainCellMaterial::smAllMaterials;
Vector<String> _initSamplerNames()
{
Vector<String> samplerNames;
samplerNames.push_back("$baseTexMap");
samplerNames.push_back("$layerTex");
samplerNames.push_back("$lightMapTex");
samplerNames.push_back("$lightInfoBuffer");
samplerNames.push_back("$normalMapSampler");
samplerNames.push_back("$detailMapSampler");
samplerNames.push_back("$macroMapSampler");
samplerNames.push_back("$ormMapSampler");
return samplerNames;
}
const Vector<String> TerrainCellMaterial::mSamplerNames = _initSamplerNames();
TerrainCellMaterial::TerrainCellMaterial()
: mTerrain( NULL ),
mDeferredMat( NULL ),
mReflectMat( NULL ),
mShader( NULL ),
mCurrPass( 0 ),
mMaterials( 0 )
{
smAllMaterials.push_back( this );
}
TerrainCellMaterial::~TerrainCellMaterial()
{
SAFE_DELETE( mDeferredMat );
SAFE_DELETE( mReflectMat );
smAllMaterials.remove( this );
T3D::for_each(mMaterialInfos.begin(), mMaterialInfos.end(), T3D::delete_pointer());
mMaterialInfos.clear();
}
void TerrainCellMaterial::_updateDefaultAnisotropy()
{
// TODO: We need to split the stateblock initialization
// from the shader constant lookup and pass setup in a
// future version of terrain materials.
//
// For now use some custom code in a horrible loop to
// change the anisotropy directly and fast.
//
const U32 maxAnisotropy = MATMGR->getDefaultAnisotropy();
Vector<TerrainCellMaterial*>::iterator iter = smAllMaterials.begin();
for ( ; iter != smAllMaterials.end(); iter++ )
{
// Start from the existing state block.
GFXStateBlockDesc desc = (*iter)->mStateBlock->getDesc();
if ((*iter)->mDetailTexArrayConst->isValid())
{
const S32 sampler = (*iter)->mDetailTexArrayConst->getSamplerRegister();
if (maxAnisotropy > 1)
{
desc.samplers[sampler].minFilter = GFXTextureFilterAnisotropic;
desc.samplers[sampler].maxAnisotropy = maxAnisotropy;
}
else
desc.samplers[sampler].minFilter = GFXTextureFilterLinear;
}
if ((*iter)->mMacroTexArrayConst->isValid())
{
const S32 sampler = (*iter)->mMacroTexArrayConst->getSamplerRegister();
if (maxAnisotropy > 1)
{
desc.samplers[sampler].minFilter = GFXTextureFilterAnisotropic;
desc.samplers[sampler].maxAnisotropy = maxAnisotropy;
}
else
desc.samplers[sampler].minFilter = GFXTextureFilterLinear;
}
if ((*iter)->mNormalTexArrayConst->isValid())
{
const S32 sampler = (*iter)->mNormalTexArrayConst->getSamplerRegister();
if (maxAnisotropy > 1)
{
desc.samplers[sampler].minFilter = GFXTextureFilterAnisotropic;
desc.samplers[sampler].maxAnisotropy = maxAnisotropy;
}
else
desc.samplers[sampler].minFilter = GFXTextureFilterLinear;
}
if ((*iter)->mOrmTexArrayConst->isValid())
{
const S32 sampler = (*iter)->mOrmTexArrayConst->getSamplerRegister();
if (maxAnisotropy > 1)
{
desc.samplers[sampler].minFilter = GFXTextureFilterAnisotropic;
desc.samplers[sampler].maxAnisotropy = maxAnisotropy;
}
else
desc.samplers[sampler].minFilter = GFXTextureFilterLinear;
}
// Set the updated stateblock.
desc.setCullMode(GFXCullCCW);
(*iter)->mStateBlock = GFX->createStateBlock(desc);
//reflection
desc.setCullMode(GFXCullCW);
(*iter)->mReflectionStateBlock = GFX->createStateBlock(desc);
// Create the wireframe state blocks.
GFXStateBlockDesc wireframe(desc);
wireframe.fillMode = GFXFillWireframe;
wireframe.setCullMode(GFXCullCCW);
(*iter)->mWireframeStateBlock = GFX->createStateBlock(wireframe);
}
}
void TerrainCellMaterial::setTransformAndEye( const MatrixF &modelXfm,
const MatrixF &viewXfm,
const MatrixF &projectXfm,
F32 farPlane )
{
PROFILE_SCOPE( TerrainCellMaterial_SetTransformAndEye );
MatrixF modelViewProj = projectXfm * viewXfm * modelXfm;
MatrixF invViewXfm( viewXfm );
invViewXfm.inverse();
Point3F eyePos = invViewXfm.getPosition();
MatrixF invModelXfm( modelXfm );
invModelXfm.inverse();
Point3F objEyePos = eyePos;
invModelXfm.mulP( objEyePos );
VectorF vEye = invViewXfm.getForwardVector();
vEye.normalize( 1.0f / farPlane );
mConsts->setSafe(mModelViewProjConst, modelViewProj);
if (mViewToObjConst->isValid() || mWorldViewOnlyConst->isValid())
{
MatrixF worldViewOnly = viewXfm * modelXfm;
mConsts->setSafe(mWorldViewOnlyConst, worldViewOnly);
if (mViewToObjConst->isValid())
{
worldViewOnly.affineInverse();
mConsts->set(mViewToObjConst, worldViewOnly);
}
}
mConsts->setSafe(mEyePosWorldConst, eyePos);
mConsts->setSafe(mEyePosConst, objEyePos);
mConsts->setSafe(mObjTransConst, modelXfm);
mConsts->setSafe(mWorldToObjConst, invModelXfm);
mConsts->setSafe(mVEyeConst, vEye);
}
TerrainCellMaterial* TerrainCellMaterial::getDeferredMat()
{
if ( !mDeferredMat )
{
mDeferredMat = new TerrainCellMaterial();
mDeferredMat->init( mTerrain, mMaterials, true, false, mMaterials == 0 );
}
return mDeferredMat;
}
TerrainCellMaterial* TerrainCellMaterial::getReflectMat()
{
if ( !mReflectMat )
{
mReflectMat = new TerrainCellMaterial();
mReflectMat->init( mTerrain, mMaterials, false, true, true );
}
return mReflectMat;
}
void TerrainCellMaterial::init( TerrainBlock *block,
U64 activeMaterials,
bool deferredMat,
bool reflectMat,
bool baseOnly )
{
// This isn't allowed for now.
AssertFatal( !( deferredMat && reflectMat ), "TerrainCellMaterial::init - We shouldn't get deferred and reflection in the same material!" );
mTerrain = block;
mMaterials = activeMaterials;
mMaterialInfos.clear();
for ( U32 i = 0; i < 64; i++ )
{
if ( !( mMaterials & ((U64)1 << i ) ) )
continue;
TerrainMaterial *mat = block->getMaterial( i );
MaterialInfo *info = new MaterialInfo();
info->layerId = i;
info->mat = mat;
mMaterialInfos.push_back(info);
}
if (!_initShader(deferredMat,
reflectMat,
baseOnly))
{
Con::errorf("TerrainCellMaterial::init - Failed to init shader!");
T3D::for_each(mMaterialInfos.begin(), mMaterialInfos.end(), T3D::delete_pointer());
mMaterialInfos.clear();
return;
}
// If we have attached mats then update them too.
if ( mDeferredMat )
mDeferredMat->init( mTerrain, mMaterials, true, false, baseOnly );
if ( mReflectMat )
mReflectMat->init( mTerrain, mMaterials, false, true, baseOnly );
}
bool TerrainCellMaterial::_initShader(bool deferredMat,
bool reflectMat,
bool baseOnly)
{
if (GFX->getPixelShaderVersion() < 3.0f)
baseOnly = true;
// NOTE: At maximum we only try to combine sgMaxTerrainMaterialsPerPass materials
// into a single pass. This is sub-optimal for the simplest
// cases, but the most common case results in much fewer
// shader generation failures and permutations leading to
// faster load time and less hiccups during gameplay.
U32 matCount = getMin(sgMaxTerrainMaterialsPerPass, mMaterialInfos.size());
Vector<GFXTexHandle> normalMaps;
// See if we're currently running under the
// basic lighting manager.
//
// TODO: This seems ugly... we should trigger
// features like this differently in the future.
//
bool useBLM = String::compare(LIGHTMGR->getId(), "BLM") == 0;
// Do we need to disable normal mapping?
const bool disableNormalMaps = MATMGR->getExclusionFeatures().hasFeature(MFT_NormalMap) || useBLM;
// How about parallax?
const bool disableParallaxMaps = GFX->getPixelShaderVersion() < 3.0f ||
MATMGR->getExclusionFeatures().hasFeature(MFT_Parallax);
// Has advanced lightmap support been enabled for deferred.
bool advancedLightmapSupport = false;
if (deferredMat)
{
// This sucks... but it works.
AdvancedLightBinManager* lightBin;
if (Sim::findObject("AL_LightBinMgr", lightBin))
advancedLightmapSupport = lightBin->MRTLightmapsDuringDeferred();
}
// Loop till we create a valid shader!
while (true)
{
FeatureSet features;
features.addFeature(MFT_VertTransform);
features.addFeature(MFT_TerrainBaseMap);
if (deferredMat)
{
features.addFeature(MFT_EyeSpaceDepthOut);
features.addFeature(MFT_DeferredConditioner);
features.addFeature(MFT_isDeferred);
if (advancedLightmapSupport)
features.addFeature(MFT_RenderTarget3_Zero);
}
else
{
features.addFeature(MFT_RTLighting);
// The HDR feature is always added... it will compile out
// if HDR is not enabled in the engine.
features.addFeature(MFT_HDROut);
}
// Enable lightmaps and fogging if we're in BL.
if (reflectMat || useBLM)
{
features.addFeature(MFT_Fog);
features.addFeature(MFT_ForwardShading);
}
if (useBLM)
features.addFeature(MFT_TerrainLightMap);
normalMaps.clear();
S32 featureIndex = 0;
// Now add all the material layer features.
for (U32 i = 0; i < matCount && !baseOnly; i++)
{
TerrainMaterial* mat = mMaterialInfos[i]->mat;
if (mat == NULL)
continue;
// We only include materials that
// have more than a base texture.
if (mat->getDetailSize() <= 0 ||
mat->getDetailDistance() <= 0 ||
mat->getDetailMap().isEmpty())
continue;
// check for macro detail texture
if (!(mat->getMacroSize() <= 0 || mat->getMacroDistance() <= 0 || mat->getMacroMap().isEmpty()))
{
if (deferredMat)
features.addFeature(MFT_isDeferred, featureIndex);
features.addFeature(MFT_TerrainMacroMap, featureIndex);
}
if (deferredMat)
features.addFeature(MFT_isDeferred, featureIndex);
features.addFeature(MFT_TerrainDetailMap, featureIndex);
if (deferredMat)
{
if (!(mat->getORMConfigMap().isEmpty()))
{
features.addFeature(MFT_TerrainORMMap, featureIndex);
}
else
{
features.addFeature(MFT_DeferredTerrainBlankInfoMap, featureIndex);
}
}
if (mat->getInvertRoughness())
features.addFeature(MFT_InvertRoughness, featureIndex);
normalMaps.increment();
// Skip normal maps if we need to.
if (!disableNormalMaps && mat->getNormalMap().isNotEmpty())
{
features.addFeature(MFT_TerrainNormalMap, featureIndex);
normalMaps.last().set(mat->getNormalMap(),
&GFXNormalMapProfile, "TerrainCellMaterial::_initShader() - NormalMap");
GFXFormat normalFmt = normalMaps.last().getFormat();
if (normalFmt == GFXFormatBC3)
features.addFeature(MFT_IsBC3nm, featureIndex);
else if (normalFmt == GFXFormatBC5)
features.addFeature(MFT_IsBC5nm, featureIndex);
// Do we need and can we do parallax mapping?
if (!disableParallaxMaps &&
mat->getParallaxScale() > 0.0f &&
!mat->useSideProjection())
features.addFeature(MFT_TerrainParallaxMap, featureIndex);
}
// Is this layer got side projection?
if (mat->useSideProjection())
features.addFeature(MFT_TerrainSideProject, featureIndex);
featureIndex++;
}
// New blending
if (matCount > 0 && !Con::getBoolVariable("$Terrain::LerpBlend", false))
{
features.addFeature(MFT_TerrainHeightBlend);
}
MaterialFeatureData featureData;
featureData.features = features;
featureData.materialFeatures = features;
// Check to see how many vertex shader output
// registers we're gonna need.
U32 numTex = 0;
U32 numTexReg = 0;
for (U32 i = 0; i < features.getCount(); i++)
{
S32 index;
const FeatureType& type = features.getAt(i, &index);
ShaderFeature* sf = FEATUREMGR->getByType(type);
if (!sf)
continue;
sf->setProcessIndex(index);
ShaderFeature::Resources res = sf->getResources(featureData);
numTex += res.numTex;
numTexReg += res.numTexReg;
}
// Can we build the shader?
//
// NOTE: The 10 is sort of an abitrary SM 3.0
// limit. Its really supposed to be 11, but that
// always fails to compile so far.
//
if (numTex < GFX->getNumSamplers() &&
numTexReg <= 10)
{
// NOTE: We really shouldn't be getting errors building the shaders,
// but we can generate more instructions than the ps_2_x will allow.
//
// There is no way to deal with this case that i know of other than
// letting the compile fail then recovering by trying to build it
// with fewer materials.
//
// We normally disable the shader error logging so that the user
// isn't fooled into thinking there is a real bug. That is until
// we get down to a single material. If a single material case
// fails it means it cannot generate any passes at all!
const bool logErrors = true;// matCount == 1;
GFXShader::setLogging(logErrors, true);
mShader = SHADERGEN->getShader(featureData, getGFXVertexFormat<TerrVertex>(), NULL, mSamplerNames);
}
// If we got a shader then we can continue.
if (mShader)
break;
// If the material count is already 1 then this
// is a real shader error... give up!
if (matCount <= 1)
return false;
// If we failed we next try half the input materials
// so that we can more quickly arrive at a valid shader.
matCount -= matCount / 2;
}
// Setup the constant buffer.
mConsts = mShader->allocConstBuffer();
// Prepare the basic constants.
mModelViewProjConst = mShader->getShaderConstHandle("$modelview");
mWorldViewOnlyConst = mShader->getShaderConstHandle("$worldViewOnly");
mViewToObjConst = mShader->getShaderConstHandle("$viewToObj");
mEyePosWorldConst = mShader->getShaderConstHandle("$eyePosWorld");
mEyePosConst = mShader->getShaderConstHandle("$eyePos");
mVEyeConst = mShader->getShaderConstHandle("$vEye");
mLayerSizeConst = mShader->getShaderConstHandle("$layerSize");
mObjTransConst = mShader->getShaderConstHandle("$objTrans");
mWorldToObjConst = mShader->getShaderConstHandle("$worldToObj");
mLightInfoBufferConst = mShader->getShaderConstHandle("$lightInfoBuffer");
mBaseTexMapConst = mShader->getShaderConstHandle("$baseTexMap");
mLayerTexConst = mShader->getShaderConstHandle("$layerTex");
mFogDataConst = mShader->getShaderConstHandle("$fogData");
mFogColorConst = mShader->getShaderConstHandle("$fogColor");
mLightMapTexConst = mShader->getShaderConstHandle("$lightMapTex");
mOneOverTerrainSizeConst = mShader->getShaderConstHandle("$oneOverTerrainSize");
mSquareSizeConst = mShader->getShaderConstHandle("$squareSize");
mBlendDepthConst = mShader->getShaderConstHandle("$baseBlendDepth");
mLightParamsConst = mShader->getShaderConstHandle("$rtParamslightInfoBuffer");
// Now prepare the basic stateblock.
GFXStateBlockDesc desc;
// We write to the zbuffer if this is a deferred
// material or if the deferred is disabled.
desc.setZReadWrite(true, !MATMGR->getDeferredEnabled() ||
deferredMat ||
reflectMat);
desc.samplersDefined = true;
if (mBaseTexMapConst->isValid())
desc.samplers[mBaseTexMapConst->getSamplerRegister()] = GFXSamplerStateDesc::getWrapLinear();
if (mLayerTexConst->isValid())
desc.samplers[mLayerTexConst->getSamplerRegister()] = GFXSamplerStateDesc::getClampPoint();
if (mLightInfoBufferConst->isValid())
desc.samplers[mLightInfoBufferConst->getSamplerRegister()] = GFXSamplerStateDesc::getClampPoint();
if (mLightMapTexConst->isValid())
desc.samplers[mLightMapTexConst->getSamplerRegister()] = GFXSamplerStateDesc::getWrapLinear();
const U32 maxAnisotropy = MATMGR->getDefaultAnisotropy();
mDetailInfoVArrayConst = mShader->getShaderConstHandle("$detailScaleAndFade");
mDetailInfoPArrayConst = mShader->getShaderConstHandle("$detailIdStrengthParallax");
mMacroInfoVArrayConst = mShader->getShaderConstHandle("$macroIdStrengthParallax");
mMacroInfoPArrayConst = mShader->getShaderConstHandle("$macroIdStrengthParallax");
mDetailTexArrayConst = mShader->getShaderConstHandle("$detailMapSampler");
if (mDetailTexArrayConst->isValid())
{
const S32 sampler = mDetailTexArrayConst->getSamplerRegister();
desc.samplers[sampler] = GFXSamplerStateDesc::getWrapLinear();
desc.samplers[sampler].magFilter = GFXTextureFilterLinear;
desc.samplers[sampler].mipFilter = GFXTextureFilterLinear;
if (maxAnisotropy > 1)
{
desc.samplers[sampler].minFilter = GFXTextureFilterAnisotropic;
desc.samplers[sampler].maxAnisotropy = maxAnisotropy;
}
else
desc.samplers[sampler].minFilter = GFXTextureFilterLinear;
}
mMacroTexArrayConst = mShader->getShaderConstHandle("$macroMapSampler");
if (mMacroTexArrayConst->isValid())
{
const S32 sampler = mMacroTexArrayConst->getSamplerRegister();
desc.samplers[sampler] = GFXSamplerStateDesc::getWrapLinear();
desc.samplers[sampler].magFilter = GFXTextureFilterLinear;
desc.samplers[sampler].mipFilter = GFXTextureFilterLinear;
if (maxAnisotropy > 1)
{
desc.samplers[sampler].minFilter = GFXTextureFilterAnisotropic;
desc.samplers[sampler].maxAnisotropy = maxAnisotropy;
}
else
desc.samplers[sampler].minFilter = GFXTextureFilterLinear;
}
mNormalTexArrayConst = mShader->getShaderConstHandle("$normalMapSampler");
if (mNormalTexArrayConst->isValid())
{
const S32 sampler = mNormalTexArrayConst->getSamplerRegister();
desc.samplers[sampler] = GFXSamplerStateDesc::getWrapLinear();
desc.samplers[sampler].magFilter = GFXTextureFilterLinear;
desc.samplers[sampler].mipFilter = GFXTextureFilterLinear;
if (maxAnisotropy > 1)
{
desc.samplers[sampler].minFilter = GFXTextureFilterAnisotropic;
desc.samplers[sampler].maxAnisotropy = maxAnisotropy;
}
else
desc.samplers[sampler].minFilter = GFXTextureFilterLinear;
}
mOrmTexArrayConst = mShader->getShaderConstHandle("$ormMapSampler");
if (mOrmTexArrayConst->isValid())
{
GFXTextureProfile* profile = &GFXStaticTextureProfile;
const S32 sampler = mOrmTexArrayConst->getSamplerRegister();
desc.samplers[sampler] = GFXSamplerStateDesc::getWrapLinear();
desc.samplers[sampler].magFilter = GFXTextureFilterLinear;
desc.samplers[sampler].mipFilter = GFXTextureFilterLinear;
if (maxAnisotropy > 1)
{
desc.samplers[sampler].minFilter = GFXTextureFilterAnisotropic;
desc.samplers[sampler].maxAnisotropy = maxAnisotropy;
}
else
desc.samplers[sampler].minFilter = GFXTextureFilterLinear;
}
for (U32 i = 0; i < matCount && !baseOnly; i++)
{
TerrainMaterial* mat = mMaterialInfos[i]->mat;
if (mat == NULL)
continue;
// We only include materials that
// have more than a base texture.
if (mat->getDetailSize() <= 0 ||
mat->getDetailDistance() <= 0 ||
mat->getDetailMap().isEmpty())
continue;
mMaterialInfos[i]->mBlendDepthConst = mShader->getShaderConstHandle(avar("$blendDepth%d", i));
mMaterialInfos[i]->mBlendContrastConst = mShader->getShaderConstHandle(avar("$blendContrast%d", i));
}
// If we're doing deferred it requires some
// special stencil settings for it to work.
if ( deferredMat )
desc.addDesc( RenderDeferredMgr::getOpaqueStenciWriteDesc( false ) );
desc.setCullMode( GFXCullCCW );
mStateBlock = GFX->createStateBlock(desc);
//reflection stateblock
desc.setCullMode( GFXCullCW );
mReflectionStateBlock = GFX->createStateBlock(desc);
// Create the wireframe state blocks.
GFXStateBlockDesc wireframe( desc );
wireframe.fillMode = GFXFillWireframe;
wireframe.setCullMode( GFXCullCCW );
mWireframeStateBlock = GFX->createStateBlock( wireframe );
return true;
}
void TerrainCellMaterial::_updateMaterialConsts( )
{
PROFILE_SCOPE( TerrainCellMaterial_UpdateMaterialConsts );
int detailMatCount = 0;
for (MaterialInfo* materialInfo : mMaterialInfos)
{
if (materialInfo == NULL)
continue;
TerrainMaterial* mat = materialInfo->mat;
if (mat == NULL)
continue;
// We only include materials that
// have more than a base texture.
if (mat->getDetailSize() <= 0 ||
mat->getDetailDistance() <= 0 ||
mat->getDetailMap().isEmpty())
continue;
detailMatCount++;
}
if (detailMatCount == 0)
{
return;
}
AlignedArray<Point4F> detailInfoArray(detailMatCount, sizeof(Point4F));
AlignedArray<Point4F> detailScaleAndFadeArray(detailMatCount, sizeof(Point4F));
int detailIndex = 0;
for (MaterialInfo* matInfo : mMaterialInfos)
{
if (matInfo == NULL)
continue;
TerrainMaterial* mat = matInfo->mat;
if (mat == NULL)
continue;
// We only include materials that
// have more than a base texture.
if (mat->getDetailSize() <= 0 ||
mat->getDetailDistance() <= 0 ||
mat->getDetailMap().isEmpty())
continue;
F32 detailSize = matInfo->mat->getDetailSize();
F32 detailScale = 1.0f;
if ( !mIsZero( detailSize ) )
detailScale = mTerrain->getWorldBlockSize() / detailSize;
// Scale the distance by the global scalar.
const F32 distance = mTerrain->smDetailScale * matInfo->mat->getDetailDistance();
// NOTE: The negation of the y scale is to make up for
// my mistake early in development and passing the wrong
// y texture coord into the system.
//
// This negation fixes detail, normal, and parallax mapping
// without harming the layer id blending code.
//
// Eventually we should rework this to correct this little
// mistake, but there isn't really a hurry to.
//
Point4F detailScaleAndFade( detailScale,
-detailScale,
distance,
0 );
if ( !mIsZero( distance ) )
detailScaleAndFade.w = 1.0f / distance;
Point4F detailIdStrengthParallax( matInfo->layerId,
matInfo->mat->getDetailStrength(),
matInfo->mat->getParallaxScale(), 0 );
detailScaleAndFadeArray[detailIndex] = detailScaleAndFade;
detailInfoArray[detailIndex] = detailIdStrengthParallax;
if (matInfo->mBlendDepthConst != NULL)
{
mConsts->setSafe(matInfo->mBlendDepthConst, matInfo->mat->getBlendDepth());
}
if (matInfo->mBlendContrastConst != NULL)
{
mConsts->setSafe(matInfo->mBlendContrastConst, matInfo->mat->getBlendContrast());
}
detailIndex++;
}
mConsts->setSafe(mDetailInfoVArrayConst, detailScaleAndFadeArray);
mConsts->setSafe(mDetailInfoPArrayConst, detailInfoArray);
}
bool TerrainCellMaterial::setupPass( const SceneRenderState *state,
const SceneData &sceneData )
{
PROFILE_SCOPE( TerrainCellMaterial_SetupPass );
if (mCurrPass > 0)
{
mCurrPass = 0;
return false;
}
mCurrPass++;
_updateMaterialConsts();
if ( mBaseTexMapConst->isValid() )
GFX->setTexture( mBaseTexMapConst->getSamplerRegister(), mTerrain->mBaseTex.getPointer() );
if ( mLayerTexConst->isValid() )
GFX->setTexture( mLayerTexConst->getSamplerRegister(), mTerrain->mLayerTex.getPointer() );
if ( mLightMapTexConst->isValid() )
GFX->setTexture( mLightMapTexConst->getSamplerRegister(), mTerrain->getLightMapTex() );
if ( sceneData.wireframe )
GFX->setStateBlock( mWireframeStateBlock );
else if ( state->isReflectPass( ))
GFX->setStateBlock( mReflectionStateBlock );
else
GFX->setStateBlock( mStateBlock );
GFX->setShader( mShader );
GFX->setShaderConstBuffer( mConsts );
// Let the light manager prepare any light stuff it needs.
LIGHTMGR->setLightInfo( NULL,
NULL,
sceneData,
state,
0,
mConsts );
if (mDetailTexArrayConst->isValid() && mTerrain->getDetailTextureArray().isValid())
GFX->setTextureArray(mDetailTexArrayConst->getSamplerRegister(), mTerrain->getDetailTextureArray());
if (mMacroTexArrayConst->isValid() && mTerrain->getMacroTextureArray().isValid())
GFX->setTextureArray(mMacroTexArrayConst->getSamplerRegister(), mTerrain->getMacroTextureArray());
if (mNormalTexArrayConst->isValid() && mTerrain->getNormalTextureArray().isValid())
GFX->setTextureArray(mNormalTexArrayConst->getSamplerRegister(), mTerrain->getNormalTextureArray());
if (mOrmTexArrayConst->isValid() && mTerrain->getOrmTextureArray().isValid())
GFX->setTextureArray(mOrmTexArrayConst->getSamplerRegister(), mTerrain->getOrmTextureArray());
mConsts->setSafe( mLayerSizeConst, (F32)mTerrain->mLayerTex.getWidth() );
if ( mOneOverTerrainSizeConst->isValid() )
{
F32 oneOverTerrainSize = 1.0f / mTerrain->getWorldBlockSize();
mConsts->set( mOneOverTerrainSizeConst, oneOverTerrainSize );
}
mConsts->setSafe( mSquareSizeConst, mTerrain->getSquareSize() );
if ( mFogDataConst->isValid() )
{
Point3F fogData;
fogData.x = sceneData.fogDensity;
fogData.y = sceneData.fogDensityOffset;
fogData.z = sceneData.fogHeightFalloff;
mConsts->set( mFogDataConst, fogData );
}
if (String::isEmpty(Con::getVariable("$Terrain::BlendDepth")))
{
mConsts->setSafe(mBlendDepthConst, 0.2f);
}
else
{
mConsts->setSafe(mBlendDepthConst, Con::getFloatVariable("$Terrain::BlendDepth"));
}
mConsts->setSafe( mFogColorConst, sceneData.fogColor );
if ( mLightInfoBufferConst->isValid() &&
mLightParamsConst->isValid() )
{
if ( !mLightInfoTarget )
mLightInfoTarget = NamedTexTarget::find( "diffuseLighting" );
GFXTextureObject *texObject = mLightInfoTarget->getTexture();
// TODO: Sometimes during reset of the light manager we get a
// NULL texture here. This is corrected on the next frame, but
// we should still investigate why that happens.
if ( texObject )
{
GFX->setTexture( mLightInfoBufferConst->getSamplerRegister(), texObject );
const Point3I &targetSz = texObject->getSize();
const RectI &targetVp = mLightInfoTarget->getViewport();
Point4F rtParams;
ScreenSpace::RenderTargetParameters(targetSz, targetVp, rtParams);
mConsts->setSafe( mLightParamsConst, rtParams );
}
}
return true;
}
BaseMatInstance* TerrainCellMaterial::getShadowMat()
{
// Find our material which has some settings
// defined on it in script.
Material *mat = MATMGR->getMaterialDefinitionByName( "AL_DefaultShadowMaterial" );
// Create the material instance adding the feature which
// handles rendering terrain cut outs.
FeatureSet features = MATMGR->getDefaultFeatures();
BaseMatInstance *matInst = mat->createMatInstance();
if ( !matInst->init( features, getGFXVertexFormat<TerrVertex>() ) )
{
delete matInst;
matInst = NULL;
}
return matInst;
}
| 30,868 | 9,796 |
// Copyright 2014 The Crashpad 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 "snapshot/win/cpu_context_win.h"
#include <windows.h>
#include "base/macros.h"
#include "build/build_config.h"
#include "gtest/gtest.h"
#include "test/hex_string.h"
#include "snapshot/cpu_context.h"
namespace crashpad {
namespace test {
namespace {
template <typename T>
void TestInitializeX86Context() {
T context = {0};
context.ContextFlags = WOW64_CONTEXT_INTEGER |
WOW64_CONTEXT_DEBUG_REGISTERS |
WOW64_CONTEXT_EXTENDED_REGISTERS;
context.Eax = 1;
context.Dr0 = 3;
context.ExtendedRegisters[4] = 2; // FTW
// Test the simple case, where everything in the CPUContextX86 argument is set
// directly from the supplied thread, float, and debug state parameters.
{
CPUContextX86 cpu_context_x86 = {};
InitializeX86Context(context, &cpu_context_x86);
EXPECT_EQ(cpu_context_x86.eax, 1u);
EXPECT_EQ(cpu_context_x86.fxsave.ftw, 2u);
EXPECT_EQ(cpu_context_x86.dr0, 3u);
}
}
template <typename T>
void TestInitializeX86Context_FsaveWithoutFxsave() {
T context = {0};
context.ContextFlags = WOW64_CONTEXT_INTEGER |
WOW64_CONTEXT_FLOATING_POINT |
WOW64_CONTEXT_DEBUG_REGISTERS;
context.Eax = 1;
// In fields that are wider than they need to be, set the high bits to ensure
// that they’re masked off appropriately in the output.
context.FloatSave.ControlWord = 0xffff027f;
context.FloatSave.StatusWord = 0xffff0004;
context.FloatSave.TagWord = 0xffffa9ff;
context.FloatSave.ErrorOffset = 0x01234567;
context.FloatSave.ErrorSelector = 0x0bad0003;
context.FloatSave.DataOffset = 0x89abcdef;
context.FloatSave.DataSelector = 0xffff0007;
context.FloatSave.RegisterArea[77] = 0x80;
context.FloatSave.RegisterArea[78] = 0xff;
context.FloatSave.RegisterArea[79] = 0x7f;
context.Dr0 = 3;
{
CPUContextX86 cpu_context_x86 = {};
InitializeX86Context(context, &cpu_context_x86);
EXPECT_EQ(cpu_context_x86.eax, 1u);
EXPECT_EQ(cpu_context_x86.fxsave.fcw, 0x027f);
EXPECT_EQ(cpu_context_x86.fxsave.fsw, 0x0004);
EXPECT_EQ(cpu_context_x86.fxsave.ftw, 0x00f0);
EXPECT_EQ(cpu_context_x86.fxsave.fop, 0x0bad);
EXPECT_EQ(cpu_context_x86.fxsave.fpu_ip, 0x01234567);
EXPECT_EQ(cpu_context_x86.fxsave.fpu_cs, 0x0003);
EXPECT_EQ(cpu_context_x86.fxsave.fpu_dp, 0x89abcdef);
EXPECT_EQ(cpu_context_x86.fxsave.fpu_ds, 0x0007);
for (size_t st_mm = 0; st_mm < 7; ++st_mm) {
EXPECT_EQ(
BytesToHexString(cpu_context_x86.fxsave.st_mm[st_mm].st,
arraysize(cpu_context_x86.fxsave.st_mm[st_mm].st)),
std::string(arraysize(cpu_context_x86.fxsave.st_mm[st_mm].st) * 2,
'0'))
<< "st_mm " << st_mm;
}
EXPECT_EQ(BytesToHexString(cpu_context_x86.fxsave.st_mm[7].st,
arraysize(cpu_context_x86.fxsave.st_mm[7].st)),
"0000000000000080ff7f");
EXPECT_EQ(cpu_context_x86.dr0, 3u);
}
}
#if defined(ARCH_CPU_X86_FAMILY)
#if defined(ARCH_CPU_X86_64)
TEST(CPUContextWin, InitializeX64Context) {
CONTEXT context = {0};
context.Rax = 10;
context.FltSave.TagWord = 11;
context.Dr0 = 12;
context.ContextFlags =
CONTEXT_INTEGER | CONTEXT_FLOATING_POINT | CONTEXT_DEBUG_REGISTERS;
// Test the simple case, where everything in the CPUContextX86_64 argument is
// set directly from the supplied thread, float, and debug state parameters.
{
CPUContextX86_64 cpu_context_x86_64 = {};
InitializeX64Context(context, &cpu_context_x86_64);
EXPECT_EQ(cpu_context_x86_64.rax, 10u);
EXPECT_EQ(cpu_context_x86_64.fxsave.ftw, 11u);
EXPECT_EQ(cpu_context_x86_64.dr0, 12u);
}
}
#endif // ARCH_CPU_X86_64
TEST(CPUContextWin, InitializeX86Context) {
#if defined(ARCH_CPU_X86)
TestInitializeX86Context<CONTEXT>();
#else // ARCH_CPU_X86
TestInitializeX86Context<WOW64_CONTEXT>();
#endif // ARCH_CPU_X86
}
TEST(CPUContextWin, InitializeX86Context_FsaveWithoutFxsave) {
#if defined(ARCH_CPU_X86)
TestInitializeX86Context_FsaveWithoutFxsave<CONTEXT>();
#else // ARCH_CPU_X86
TestInitializeX86Context_FsaveWithoutFxsave<WOW64_CONTEXT>();
#endif // ARCH_CPU_X86
}
#endif // ARCH_CPU_X86_FAMILY
} // namespace
} // namespace test
} // namespace crashpad
| 4,938 | 2,044 |
#include "gli.hpp"
#include "GLES3Renderer.h"
CGLES3Texture::CGLES3Texture(void)
: m_bExtern(false)
, m_target(0)
, m_texture(0)
, m_type(GFX_TEXTURE_INVALID_ENUM)
, m_format(GFX_PIXELFORMAT_UNDEFINED)
, m_width(0)
, m_height(0)
, m_layers(0)
, m_levels(0)
, m_samples(0)
{
}
CGLES3Texture::~CGLES3Texture(void)
{
Destroy();
}
void CGLES3Texture::Release(void)
{
}
uint32_t CGLES3Texture::GetTarget(void) const
{
ASSERT(m_target);
return m_target;
}
uint32_t CGLES3Texture::GetTexture(void) const
{
ASSERT(m_texture);
return m_texture;
}
GfxTextureType CGLES3Texture::GetType(void) const
{
return m_type;
}
GfxPixelFormat CGLES3Texture::GetFormat(void) const
{
return m_format;
}
int CGLES3Texture::GetWidth(void) const
{
return m_width;
}
int CGLES3Texture::GetHeight(void) const
{
return m_height;
}
int CGLES3Texture::GetLayers(void) const
{
return m_layers;
}
int CGLES3Texture::GetLevels(void) const
{
return m_levels;
}
int CGLES3Texture::GetSamples(void) const
{
return m_samples;
}
bool CGLES3Texture::Create(GfxTextureType type, GfxPixelFormat format, int width, int height, int layers, int levels, int samples, uint32_t texture)
{
ASSERT(texture);
Destroy();
m_bExtern = true;
m_target = CGLES3Helper::TranslateTextureTarget(type);
m_texture = texture;
m_type = type;
m_format = format;
m_width = width;
m_height = height;
m_layers = layers;
m_levels = levels;
m_samples = samples;
return true;
}
bool CGLES3Texture::Create(GfxTextureType type, GfxPixelFormat format, int width, int height, int layers, int levels, int samples)
{
Destroy();
m_bExtern = false;
m_target = CGLES3Helper::TranslateTextureTarget(type);
m_texture = 0;
m_type = type;
m_format = format;
m_width = width;
m_height = height;
m_layers = layers;
m_levels = levels;
gli::gl GL(gli::gl::PROFILE_ES30);
gli::gl::format glFormat = GL.translate((gli::format)format);
switch (m_target) {
case GL_TEXTURE_2D_MULTISAMPLE:
m_samples = samples;
glGenTextures(1, &m_texture);
glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, m_texture);
glTexStorage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, samples, glFormat.Internal, width, height, GL_TRUE);
glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0);
CHECK_GL_ERROR_ASSERT();
return true;
case GL_TEXTURE_2D:
m_samples = 1;
glGenTextures(1, &m_texture);
glBindTexture(GL_TEXTURE_2D, m_texture);
glTexStorage2D(GL_TEXTURE_2D, levels, glFormat.Internal, width, height);
glBindTexture(GL_TEXTURE_2D, 0);
CHECK_GL_ERROR_ASSERT();
return true;
case GL_TEXTURE_2D_ARRAY:
m_samples = 1;
glGenTextures(1, &m_texture);
glBindTexture(GL_TEXTURE_2D_ARRAY, m_texture);
glTexStorage3D(GL_TEXTURE_2D_ARRAY, levels, glFormat.Internal, width, height, layers);
glBindTexture(GL_TEXTURE_2D_ARRAY, 0);
CHECK_GL_ERROR_ASSERT();
return true;
case GL_TEXTURE_CUBE_MAP:
m_samples = 1;
glGenTextures(1, &m_texture);
glBindTexture(GL_TEXTURE_CUBE_MAP, m_texture);
glTexStorage2D(GL_TEXTURE_CUBE_MAP, levels, glFormat.Internal, width, height);
glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
CHECK_GL_ERROR_ASSERT();
return true;
default:
Destroy();
return false;
}
}
void CGLES3Texture::Destroy(void)
{
if (m_bExtern == false) {
if (m_texture) {
glDeleteTextures(1, &m_texture);
}
}
m_bExtern = false;
m_target = 0;
m_texture = 0;
m_format = GFX_PIXELFORMAT_UNDEFINED;
m_width = 0;
m_height = 0;
m_layers = 0;
m_levels = 0;
m_samples = 0;
}
bool CGLES3Texture::Texture2DData(GfxPixelFormat format, int level, int xoffset, int yoffset, int width, int height, uint32_t size, const void* data)
{
ASSERT(size);
ASSERT(data);
ASSERT(m_texture);
ASSERT(m_bExtern == false);
ASSERT(m_target == GL_TEXTURE_2D);
ASSERT(m_format == format);
ASSERT(m_levels > level);
ASSERT(m_samples == 1);
ASSERT(xoffset >= 0 && width > 0 && xoffset + width <= m_width);
ASSERT(yoffset >= 0 && height > 0 && yoffset + height <= m_height);
gli::gl GL(gli::gl::PROFILE_ES30);
gli::gl::format glFormat = GL.translate((gli::format)format);
glBindTexture(m_target, m_texture);
glTexSubImage2D(m_target, level, xoffset, yoffset, width, height, glFormat.External, GL_UNSIGNED_BYTE, data);
glBindTexture(m_target, 0);
CHECK_GL_ERROR_ASSERT();
return true;
}
bool CGLES3Texture::Texture2DDataCompressed(GfxPixelFormat format, int level, int xoffset, int yoffset, int width, int height, uint32_t size, const void* data)
{
ASSERT(size);
ASSERT(data);
ASSERT(m_texture);
ASSERT(m_bExtern == false);
ASSERT(m_target == GL_TEXTURE_2D);
ASSERT(m_format == format);
ASSERT(m_levels > level);
ASSERT(m_samples == 1);
ASSERT(xoffset >= 0 && width > 0 && xoffset + width <= m_width);
ASSERT(yoffset >= 0 && height > 0 && yoffset + height <= m_height);
gli::gl GL(gli::gl::PROFILE_ES30);
gli::gl::format glFormat = GL.translate((gli::format)format);
glBindTexture(m_target, m_texture);
glCompressedTexSubImage2D(m_target, level, xoffset, yoffset, width, height, glFormat.Internal, size, data);
glBindTexture(m_target, 0);
CHECK_GL_ERROR_ASSERT();
return true;
}
bool CGLES3Texture::Texture2DArrayData(GfxPixelFormat format, int layer, int level, int xoffset, int yoffset, int width, int height, uint32_t size, const void* data)
{
ASSERT(size);
ASSERT(data);
ASSERT(m_texture);
ASSERT(m_bExtern == false);
ASSERT(m_target == GL_TEXTURE_2D_ARRAY);
ASSERT(m_format == format);
ASSERT(m_layers > layer);
ASSERT(m_levels > level);
ASSERT(m_samples == 1);
ASSERT(xoffset >= 0 && width > 0 && xoffset + width <= m_width);
ASSERT(yoffset >= 0 && height > 0 && yoffset + height <= m_height);
gli::gl GL(gli::gl::PROFILE_ES30);
gli::gl::format glFormat = GL.translate((gli::format)format);
glBindTexture(m_target, m_texture);
glTexSubImage3D(m_target, level, xoffset, yoffset, layer, width, height, 1, glFormat.External, GL_UNSIGNED_BYTE, data);
glBindTexture(m_target, 0);
CHECK_GL_ERROR_ASSERT();
return true;
}
bool CGLES3Texture::Texture2DArrayDataCompressed(GfxPixelFormat format, int layer, int level, int xoffset, int yoffset, int width, int height, uint32_t size, const void* data)
{
ASSERT(size);
ASSERT(data);
ASSERT(m_texture);
ASSERT(m_bExtern == false);
ASSERT(m_target == GL_TEXTURE_2D_ARRAY);
ASSERT(m_format == format);
ASSERT(m_layers > layer);
ASSERT(m_levels > level);
ASSERT(m_samples == 1);
ASSERT(xoffset >= 0 && width > 0 && xoffset + width <= m_width);
ASSERT(yoffset >= 0 && height > 0 && yoffset + height <= m_height);
gli::gl GL(gli::gl::PROFILE_ES30);
gli::gl::format glFormat = GL.translate((gli::format)format);
glBindTexture(m_target, m_texture);
glCompressedTexSubImage3D(m_target, level, xoffset, yoffset, layer, width, height, 1, glFormat.Internal, size, data);
glBindTexture(m_target, 0);
CHECK_GL_ERROR_ASSERT();
return true;
}
bool CGLES3Texture::TextureCubemapData(GfxPixelFormat format, GfxCubemapFace face, int level, int xoffset, int yoffset, int width, int height, uint32_t size, const void* data)
{
ASSERT(size);
ASSERT(data);
ASSERT(m_texture);
ASSERT(m_bExtern == false);
ASSERT(m_target == GL_TEXTURE_CUBE_MAP);
ASSERT(m_format == format);
ASSERT(m_levels > level);
ASSERT(m_samples == 1);
ASSERT(xoffset >= 0 && width > 0 && xoffset + width <= m_width);
ASSERT(yoffset >= 0 && height > 0 && yoffset + height <= m_height);
gli::gl GL(gli::gl::PROFILE_ES30);
gli::gl::format glFormat = GL.translate((gli::format)format);
glBindTexture(m_target, m_texture);
glTexSubImage2D(CGLES3Helper::TranslateTextureTarget(face), level, xoffset, yoffset, width, height, glFormat.External, GL_UNSIGNED_BYTE, data);
glBindTexture(m_target, 0);
CHECK_GL_ERROR_ASSERT();
return true;
}
bool CGLES3Texture::TextureCubemapDataCompressed(GfxPixelFormat format, GfxCubemapFace face, int level, int xoffset, int yoffset, int width, int height, uint32_t size, const void* data)
{
ASSERT(size);
ASSERT(data);
ASSERT(m_texture);
ASSERT(m_bExtern == false);
ASSERT(m_target == GL_TEXTURE_CUBE_MAP);
ASSERT(m_format == format);
ASSERT(m_levels > level);
ASSERT(m_samples == 1);
ASSERT(xoffset >= 0 && width > 0 && xoffset + width <= m_width);
ASSERT(yoffset >= 0 && height > 0 && yoffset + height <= m_height);
gli::gl GL(gli::gl::PROFILE_ES30);
gli::gl::format glFormat = GL.translate((gli::format)format);
glBindTexture(m_target, m_texture);
glCompressedTexSubImage2D(CGLES3Helper::TranslateTextureTarget(face), level, xoffset, yoffset, width, height, glFormat.Internal, size, data);
glBindTexture(m_target, 0);
CHECK_GL_ERROR_ASSERT();
return true;
}
void CGLES3Texture::Bind(uint32_t unit) const
{
ASSERT(m_target);
ASSERT(m_texture);
GLBindTexture(unit, m_target, m_texture);
CHECK_GL_ERROR_ASSERT();
}
| 8,741 | 3,635 |
//--------------------------------------------------------------------------
// Copyright (C) 2016-2018 Cisco and/or its affiliates. All rights reserved.
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License Version 2 as published
// by the Free Software Foundation. You may not use, modify or distribute
// this program under any other version of the GNU General Public License.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//--------------------------------------------------------------------------
// tp_mock.cc author Silviu Minut <sminut@cisco.com>
// Standalone compilation:
// g++ -g -Wall -I.. -I/path/to/snort3/src -c tp_mock.cc
// g++ -std=c++11 -g -Wall -I.. -I/path/to/snort3/src -shared -fPIC -o libtp_mock.so tp_mock.cc
// As a module (dynamically loaded) - see CMakeLists.txt
#include <iostream>
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "main/snort_types.h"
#include "tp_appid_module_api.h"
#include "tp_appid_session_api.h"
#define WhereMacro __FILE__ << ": " << __FUNCTION__ << ": " << __LINE__
using namespace std;
class ThirdPartyAppIDModuleImpl : public ThirdPartyAppIDModule
{
public:
ThirdPartyAppIDModuleImpl(uint32_t ver, const char* mname)
: ThirdPartyAppIDModule(ver, mname)
{
cerr << WhereMacro << endl;
}
~ThirdPartyAppIDModuleImpl()
{
cerr << WhereMacro << endl;
}
// Hack: use cfg to manipulate pinit to return 1, so we can hit the
// if (ret != 0) case in tp_lib_handler.cc.
int pinit(ThirdPartyConfig& cfg)
{
cerr << WhereMacro << endl;
return cfg.tp_appid_config.empty() ? 1 : 0;
}
int tinit() { return 0; }
int reconfigure(const ThirdPartyConfig&) { return 0; }
int pfini()
{
cerr << WhereMacro << endl;
return 0;
}
int tfini() { return 0; }
int print_stats() { return 0; }
int reset_stats() { return 0; }
};
class ThirdPartyAppIDSessionImpl : public ThirdPartyAppIDSession
{
public:
bool reset() { return 1; }
TPState process(const snort::Packet&, AppidSessionDirection, vector<AppId>&,
ThirdPartyAppIDAttributeData&) { return TP_STATE_INIT; }
int disable_flags(uint32_t) { return 0; }
TPState get_state() { return state; }
void set_state(TPState s) { state=s; }
void clear_attr(TPSessionAttr attr) { flags &= ~attr; }
void set_attr(TPSessionAttr attr) { flags |= attr; }
unsigned get_attr(TPSessionAttr attr) { return flags & attr; }
private:
unsigned flags = 0;
};
// Object factories to create module and session.
// This is the only way for outside callers to create module and session
// once the .so has been loaded.
extern "C"
{
SO_PUBLIC ThirdPartyAppIDModuleImpl* create_third_party_appid_module();
SO_PUBLIC ThirdPartyAppIDSessionImpl* create_third_party_appid_session();
SO_PUBLIC ThirdPartyAppIDModuleImpl* create_third_party_appid_module()
{
return new ThirdPartyAppIDModuleImpl(1,"foobar");
}
SO_PUBLIC ThirdPartyAppIDSessionImpl* create_third_party_appid_session()
{
return new ThirdPartyAppIDSessionImpl;
}
}
| 3,623 | 1,213 |
/****************************************************************************************
* @author: kzvd4729 created: Nov/12/2018 23:55
* solution_verdict: Wrong answer on test 3 language: GNU C++14
* run_time: 15 ms memory_used: 4900 KB
* problem: https://codeforces.com/contest/1076/problem/D
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
const int N=3e5;
int vis[N+2];
vector<pair<int,int> >adj[N+2];
map<pair<int,int>,int>mp;
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
int n,m,k;cin>>n>>m>>k;
for(int i=1;i<=m;i++)
{
int u,v,w;cin>>u>>v>>w;
adj[u].push_back({v,w});
adj[v].push_back({u,w});
if(u>v)swap(u,v);mp[{u,v}]=i;
}
priority_queue<pair<long,pair<int,int> > >pq;
for(auto x:adj[1])pq.push({-x.second,{1,x.first}});
set<int>ans;vis[1]=1;
while(pq.size())
{
pair<long,pair<int,int> >p=pq.top();pq.pop();
int u=p.second.first,v=p.second.second;
if(u>v)swap(u,v);long cs=-p.first;
if(ans.size()<k)ans.insert(mp[{u,v}]);
vis[p.second.second]=1;
for(auto x:adj[p.second.second])
{
if(vis[x.first])continue;
pq.push({-(cs+x.second),{p.second.second,x.first}});
}
}
cout<<ans.size()<<endl;
for(auto x:ans)
cout<<x<<" ";
cout<<endl;
return 0;
} | 1,552 | 610 |
#include <cdk/compiler.h>
| 26 | 12 |
// ArduinoJson - https://arduinojson.org
// Copyright Benoit Blanchon 2014-2021
// MIT License
#include <ArduinoJson.h>
#include <catch.hpp>
TEST_CASE("deserializeMsgPack() returns EmptyInput") {
StaticJsonDocument<100> doc;
SECTION("from sized buffer") {
DeserializationError err = deserializeMsgPack(doc, "", 0);
REQUIRE(err == DeserializationError::EmptyInput);
}
SECTION("from stream") {
std::istringstream input("");
DeserializationError err = deserializeMsgPack(doc, input);
REQUIRE(err == DeserializationError::EmptyInput);
}
}
| 572 | 206 |
/**
* @file character_tokenizer.cpp
* @author Chase Geigle
*/
#include "analyzers/tokenizers/character_tokenizer.h"
#include "corpus/document.h"
#include "io/mmap_file.h"
namespace meta
{
namespace analyzers
{
namespace tokenizers
{
const std::string character_tokenizer::id = "character-tokenizer";
character_tokenizer::character_tokenizer() : idx_{0}
{
// nothing
}
void character_tokenizer::set_content(const std::string& content)
{
idx_ = 0;
content_ = content;
}
std::string character_tokenizer::next()
{
if (!*this)
throw token_stream_exception{"next() called with no tokens left"};
return {1, content_[idx_++]};
}
character_tokenizer::operator bool() const
{
return idx_ < content_.size();
}
}
}
}
| 748 | 254 |
#include "exportexpressionmatrix.h"
#include "exportexpressionmatrix_input.h"
#include "datafactory.h"
#include "expressionmatrix_gene.h"
/*!
* Return the total number of blocks this analytic must process as steps
* or blocks of work. This implementation uses a work block for writing the
* sample names and a work block for writing each gene.
*/
int ExportExpressionMatrix::size() const
{
EDEBUG_FUNC(this);
return 1 + _input->geneSize();
}
/*!
* Process the given index with a possible block of results if this analytic
* produces work blocks. This implementation uses only the index of the result
* block to determine which piece of work to do.
*
* @param result
*/
void ExportExpressionMatrix::process(const EAbstractAnalyticBlock* result)
{
EDEBUG_FUNC(this,result);
// write the sample names in the first step
if ( result->index() == 0 )
{
// get sample names
EMetaArray sampleNames {_input->sampleNames()};
// initialize output file stream
_stream.setDevice(_output);
_stream.setRealNumberPrecision(_precision);
// write sample names
for ( int i = 0; i < _input->sampleSize(); i++ )
{
_stream << sampleNames.at(i).toString() << "\t";
}
_stream << "\n";
}
// write each gene to the output file in a separate step
else
{
// get gene index
int i = result->index() - 1;
// get gene name
QString geneName {_input->geneNames().at(i).toString()};
// load gene from expression matrix
ExpressionMatrix::Gene gene(_input);
gene.read(i);
// write gene name
_stream << geneName;
// write expression values
for ( int j = 0; j < _input->sampleSize(); j++ )
{
float value {gene.at(j)};
// if value is NAN use the no sample token
if ( std::isnan(value) )
{
_stream << "\t" << _nanToken;
}
// else this is a normal floating point expression
else
{
_stream << "\t" << value;
}
}
_stream << "\n";
}
// make sure writing output file worked
if ( _stream.status() != QTextStream::Ok )
{
E_MAKE_EXCEPTION(e);
e.setTitle(tr("File IO Error"));
e.setDetails(tr("Qt Text Stream encountered an unknown error."));
throw e;
}
}
/*!
* Make a new input object and return its pointer.
*/
EAbstractAnalyticInput* ExportExpressionMatrix::makeInput()
{
EDEBUG_FUNC(this);
return new Input(this);
}
/*!
* Initialize this analytic. This implementation checks to make sure the input
* data object and output file have been set.
*/
void ExportExpressionMatrix::initialize()
{
EDEBUG_FUNC(this);
if ( !_input || !_output )
{
E_MAKE_EXCEPTION(e);
e.setTitle(tr("Invalid Argument"));
e.setDetails(tr("Did not get valid input and/or output arguments."));
throw e;
}
}
| 3,065 | 895 |
#include <qapplication.h>
#include <qlayout.h>
#include "tunerfrm.h"
#include "ampfrm.h"
#include "radio.h"
MainWin::MainWin():
QWidget()
{
TunerFrame *frmTuner = new TunerFrame(this);
frmTuner->setFrameStyle(QFrame::Panel|QFrame::Raised);
AmpFrame *frmAmp = new AmpFrame(this);
frmAmp->setFrameStyle(QFrame::Panel|QFrame::Raised);
QVBoxLayout *layout = new QVBoxLayout(this);
layout->setMargin(0);
layout->setSpacing(0);
layout->addWidget(frmTuner);
layout->addWidget(frmAmp);
connect(frmTuner, SIGNAL(fieldChanged(double)),
frmAmp, SLOT(setMaster(double)));
frmTuner->setFreq(90.0);
}
int main (int argc, char **argv)
{
QApplication a(argc, argv);
MainWin w;
#if QT_VERSION < 0x040000
a.setMainWidget(&w);
#endif
w.show();
return a.exec();
}
| 879 | 365 |
#include "EntityLoader.hh"
#include <fstream>
#include <iostream>
namespace Mikan {
EntityLoader::EntityLoader() {
}
void EntityLoader::load_json(const std::string file_location) {
Json::Reader reader;
std::ifstream provinces_file;
provinces_file.open(file_location);
const bool parsingSuccessful = reader.parse(provinces_file, root);
if (!parsingSuccessful) {
// Should instead print to a log file
std::cout << "Failed to parse configuration"
<< std::endl
<< reader.getFormattedErrorMessages();
return;
}
}
} // namespace Mikan
| 589 | 177 |
// Copyright (C) 2015 SRG Technology, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "anyrpc/anyrpc.h"
#include <gtest/gtest.h>
#include <fstream>
using namespace std;
using namespace anyrpc;
static string ReadWriteData(char* inString)
{
ReadStringStream is(inString);
XmlReader reader(is);
Document doc;
reader >> doc;
WriteStringStream os;
XmlWriter writer(os);
writer << doc.GetValue();
return os.GetString();
}
static void WriteReadValue(Value& value, Value& outValue)
{
WriteStringStream os;
XmlWriter writer(os);
writer << value;
//cout << "Xml: " << os.GetBuffer() << endl;
ReadStringStream is(os.GetBuffer());
XmlReader reader(is);
Document doc;
reader >> doc;
outValue.Assign(doc.GetValue());
}
static int CheckParseError(const char* inString)
{
ReadStringStream is(inString);
XmlReader reader(is);
Document doc;
reader >> doc;
return reader.GetParseErrorCode();
}
TEST(Xml,Number)
{
char inString[] = "<value><i4>5736298</i4></value>";
string outString = ReadWriteData(inString);
EXPECT_STREQ( outString.c_str(), inString);
}
TEST(Xml,Double)
{
Value value, outValue;
value.SetDouble(0);
WriteReadValue(value, outValue);
EXPECT_DOUBLE_EQ(value.GetDouble(), outValue.GetDouble());
value.SetDouble(5);
WriteReadValue(value, outValue);
EXPECT_DOUBLE_EQ(value.GetDouble(), outValue.GetDouble());
value.SetDouble(2.2348282);
WriteReadValue(value, outValue);
EXPECT_DOUBLE_EQ(value.GetDouble(), outValue.GetDouble());
value.SetDouble(-728329);
WriteReadValue(value, outValue);
EXPECT_DOUBLE_EQ(value.GetDouble(), outValue.GetDouble());
value.SetDouble(5.12393e-5);
WriteReadValue(value, outValue);
EXPECT_DOUBLE_EQ(value.GetDouble(), outValue.GetDouble());
value.SetDouble(-7.192939e-300);
WriteReadValue(value, outValue);
EXPECT_DOUBLE_EQ(value.GetDouble(), outValue.GetDouble());
value.SetDouble(8e-315);
WriteReadValue(value, outValue);
EXPECT_DOUBLE_EQ(value.GetDouble(), outValue.GetDouble());
value.SetDouble(-9.12e50);
WriteReadValue(value, outValue);
EXPECT_DOUBLE_EQ(value.GetDouble(), outValue.GetDouble());
value.SetDouble(1.642e300);
WriteReadValue(value, outValue);
EXPECT_DOUBLE_EQ(value.GetDouble(), outValue.GetDouble());
value.SetDouble(-9.999e307);
WriteReadValue(value, outValue);
EXPECT_DOUBLE_EQ(value.GetDouble(), outValue.GetDouble());
}
TEST(Xml,String)
{
char inString[] = "<value>Test string data</value>";
string outString = ReadWriteData(inString);
EXPECT_STREQ( outString.c_str(), inString);
char inString2[] = "<value><string>Test string data</string></value>";
string outString2 = ReadWriteData(inString2);
EXPECT_STREQ( outString2.c_str(), inString);
}
TEST(Xml,Array)
{
char inString[] = "<value><array><data>"
"<value><i4>1</i4></value>"
"<value><i4>2</i4></value>"
"<value><i4>3</i4></value>"
"<value><i4>4</i4></value>"
"</data></array></value>";
string outString = ReadWriteData(inString);
EXPECT_STREQ( outString.c_str(), inString);
}
TEST(Xml,Map)
{
char inString[] = "<value><struct>"
"<member><name>item1</name><value><i4>57</i4></value></member>"
"<member><name>item2</name><value><i4>89</i4></value></member>"
"<member><name>item3</name><value><i4>45</i4></value></member>"
"</struct></value>";
string outString = ReadWriteData(inString);
EXPECT_STREQ( outString.c_str(), inString);
}
TEST(Xml,DateTime)
{
Value value;
time_t dt = time(NULL);
value.SetDateTime(dt);
Value outValue;
WriteReadValue(value, outValue);
EXPECT_TRUE(outValue.IsDateTime());
EXPECT_EQ(outValue.GetDateTime(), value.GetDateTime());
}
TEST(Xml,Binary)
{
Value value;
char* binData = (char*)"\x0a\x0b\x0c\x0d\xff\x00\xee\xdd\x00";
value.SetBinary( (unsigned char*)binData, 8);
Value outValue;
WriteReadValue(value, outValue);
EXPECT_TRUE(outValue.IsBinary());
EXPECT_EQ( strncmp((char*)outValue.GetBinary(), (char*)value.GetBinary(), 8), 0);
}
TEST(Xml,ParseError1)
{
char inString[] = "<value>Test string data</string></value>";
EXPECT_EQ(CheckParseError(inString), AnyRpcErrorTagInvalid);
}
TEST(Xml,ParseError2)
{
char inString[] = "<value><i4>5736298</value>";
EXPECT_EQ(CheckParseError(inString), AnyRpcErrorTagInvalid);
}
TEST(Xml,ParseError3)
{
char inString[] = "<value><i4>5736298<i4></value>";
EXPECT_EQ(CheckParseError(inString), AnyRpcErrorTagInvalid);
}
| 5,834 | 2,052 |
// Copyright (c) 2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <node_cudf/column.hpp>
#include <node_cudf/table.hpp>
#include <node_cudf/utilities/metadata.hpp>
#include <cudf/io/text/data_chunk_source_factories.hpp>
#include <cudf/io/text/multibyte_split.hpp>
namespace nv {
namespace {
Column::wrapper_t split_string_column(Napi::CallbackInfo const& info,
cudf::mutable_column_view const& col,
std::string const& delimiter) {
auto env = info.Env();
/* TODO: This only splits a string column. How to generalize */
// Check type
auto span = cudf::device_span<char const>(col.child(1).data<char const>(), col.child(1).size());
auto datasource = cudf::io::text::device_span_data_chunk_source(span);
return Column::New(env, cudf::io::text::multibyte_split(datasource, delimiter));
}
Column::wrapper_t read_text_files(Napi::CallbackInfo const& info,
std::string const& filename,
std::string const& delimiter) {
auto datasource = cudf::io::text::make_source_from_file(filename);
auto text_data = cudf::io::text::multibyte_split(*datasource, delimiter);
auto env = info.Env();
return Column::New(env, std::move(text_data));
}
} // namespace
Napi::Value Column::split(Napi::CallbackInfo const& info) {
CallbackArgs args{info};
if (args.Length() != 1) { NAPI_THROW(Napi::Error::New(info.Env(), "split expects a delimiter")); }
auto delimiter = args[0];
auto col = this->mutable_view();
try {
return split_string_column(info, col, delimiter);
} catch (cudf::logic_error const& err) { NAPI_THROW(Napi::Error::New(info.Env(), err.what())); }
}
Napi::Value Column::read_text(Napi::CallbackInfo const& info) {
CallbackArgs args{info};
if (args.Length() != 2) {
NAPI_THROW(
Napi::Error::New(info.Env(), "read_text expects a filename and an optional delimiter"));
}
std::string source = args[0];
std::string delimiter = args[1];
try {
return read_text_files(info, source, delimiter);
} catch (cudf::logic_error const& err) { NAPI_THROW(Napi::Error::New(info.Env(), err.what())); }
}
} // namespace nv
| 2,777 | 912 |
#ifndef DataProducts_ExtMonFNALModuleDenseId_hh
#define DataProducts_ExtMonFNALModuleDenseId_hh
// Sequential number of a silicon module in Mu2e ExtMonFNAL detector.
// Zero based.
//
// $Id: ExtMonFNALModuleDenseId.hh,v 1.1 2013/07/30 18:45:00 wieschie Exp $
// $Author: wieschie $
// $Date: 2013/07/30 18:45:00 $
//
// Original author Andrei Gaponenko
#include <ostream>
namespace mu2e {
class ExtMonFNALModuleDenseId {
public:
static const unsigned int NOMODULE = -1u;
explicit ExtMonFNALModuleDenseId(unsigned int did = NOMODULE) : did_(did) {}
bool operator==( ExtMonFNALModuleDenseId const& rhs) const{
return did_ == rhs.did_;
}
bool operator!=( ExtMonFNALModuleDenseId const& rhs) const{
return !(*this == rhs);
}
bool operator<( ExtMonFNALModuleDenseId const& rhs) const{
return did_ < rhs.did_;
}
unsigned int number() const { return did_; }
private:
unsigned int did_;
};
inline std::ostream& operator<<( std::ostream& os, const ExtMonFNALModuleDenseId& id) {
return os<<id.number();
}
}
#endif /* DataProducts_ExtMonFNALModuleDenseId_hh */
| 1,139 | 439 |
#include <iostream>
#include <Eigen/IterativeLinearSolvers>
#include <libv/lma/lm/solver/solver.hpp>
#include <libv/lma/lm/solver/verbose.hpp>
using namespace Eigen;
void eigen_pcg(const Eigen::MatrixXd& m, const Eigen::VectorXd& jte)
{
std::cout << "\n\n EIGEN PCG " << std::endl;
size_t n = jte.size();
VectorXd x(n), b(jte);
// typedef SparseMatrix<double> Mat;
typedef Eigen::MatrixXd Mat;
// Mat A(n,n);
Mat A = m;
// for(size_t i = 0 ; i < m.cols() ; ++i)
// for(size_t j = 0 ; j < m.rows() ; ++j)
// A.coeff(j,i) = m(j,i);
// for(size_t i = 0 ; i < n ; ++i)
// A.coeffRef(i,i) = 1.0;
// A.setIdentity();
std::cout << A << std::endl;
x.setZero();
std::cout <<"\n X = " << x.transpose() << std::endl;
std::cout <<"\n B = " << b.transpose() << std::endl;
// fill A and b
ConjugateGradient<Mat> cg;
cg.compute(A);
x = cg.solve(b);
std::cout << "#iterations: " << cg.iterations() << std::endl;
std::cout << "estimated error: " << cg.error() << std::endl;
// update b, and solve again
// x = cg.solve(b);
std::cout << "\n X = " << x.transpose() << std::endl;
}
// typedef Eigen::Matrix<double,2,1> Type0;
// typedef Eigen::Matrix<double,3,1> Type1;
// typedef Eigen::Matrix<double,1,1> Type2;
//
// struct F
// {
// bool operator()(const Type0& , const Type1& , const Type2&, Eigen::Matrix<double,2,1>&) const
// {
// return true;
// }
// };
int main()
{
/*
Type0 t0;
Type1 t1;
Type2 t2;
std::cout << " Test pcg " << std::endl;
lma::Solver<F> solver(1,1);
// solver.algo.norm_eq.seuil=0.9999;
// solver.algo.norm_eq.max_iteration=100000typedef typename SelectAlgo<Container,Container::NbClass,AlgoTag>::type Algorithm;
// Algorithm algo(config);;
auto i0 = ttt::Indice<Type0*>(0);
auto i1 = ttt::Indice<Type1*>(0);
auto i2 = ttt::Indice<Type2*>(0);
solver.add(F(),&t0,&t1,&t2);//lma::bf::make_vector(i0,i1,i2),F());
// solver.solve(lma::enable_verbose_output());
// solver.algo.compute_b(solver.algo.ba_);
// solver.algo.compute_delta_a(solver.algo.ba_);
using namespace lma;
typedef typename SelectAlgo<lma::Solver<F>::Container,lma::Solver<F>::Container::NbClass,ImplicitSchurTag<1>>::type Algorithm;
Algorithm algo(ImplicitSchurTag<1>(0.9999,100000));
algo.init(solver.bundle);
lma::bf::at_key<lma::bf::pair<Type0*,Type0*>>(algo.ba_.h())(i0,0) <<
1,0,
0,2;
lma::bf::at_key<lma::bf::pair<Type2*,Type2*>>(algo.ba_.h())(i2,0) <<
1;
lma::bf::at_key<lma::bf::pair<Type0*,Type1*>>(algo.ba_.h())(i0,0) <<
3.2,0.5,2,
0,-2.5,-1.5;
lma::bf::at_key<lma::bf::pair<Type1*,Type1*>>(algo.ba_.h())(i1,0) <<
3,0,0,
0,4,0,
0,0,5;
lma::bf::at_key<Type0*>(algo.ba_.jte())(i0) << 1,2;
lma::bf::at_key<Type1*>(algo.ba_.jte())(i1) << 3,4,5;
lma::bf::at_key<Type2*>(algo.ba_.jte())(i2) << 1;
std::cout << std::endl;
std::cout << " A = \n" << lma::to_mat(algo.ba_.h()) << std::endl;
// std::cout << " B = " << lma::to_vect(solver.algo.schur_.bs_).transpose() << std::endl;
std::cout << " B = " << lma::to_vect(algo.ba_.jte()).transpose() << std::endl;
algo.compute_y(algo.ba_);
algo.compute_b(algo.ba_);
algo.compute_delta_a(algo.ba_);
std::cout << " X = " << lma::to_vect(algo.ba_.delta()).transpose() << std::endl;
eigen_pcg(lma::to_mat(algo.ba_.h()),lma::to_vect(algo.ba_.jte()));*/
}
| 3,422 | 1,602 |
/****************************************************************
Following is the class structure of the Node class:
class Node
{
public:
int data;
Node *next;
Node(int data)
{
this->data = data;
this->next = NULL;
}
};
*****************************************************************/
void my_swap (Node *node_1, Node *node_2)
{
int temp = node_1->data;
node_1->data = node_2 -> data;
node_2 -> data = temp;
}
Node *bubbleSort(Node *head)
{
// Write your code here
if(head == NULL){
return head;
}
int swapped;
Node *lPtr; // left pointer will always point to the start of the list
Node *rPrt = NULL; // right pointer will always point to the end of the list
do
{
swapped = 0;
lPtr = head;
while(lPtr->next != rPrt)
{
if (lPtr->data > lPtr->next->data)
{
my_swap(lPtr, lPtr->next);
swapped = 1;
}
lPtr = lPtr->next;
}
//as the largest element is at the end of the list, assign that to rPtr as there is no need to
//check already sorted list
rPrt = lPtr;
}while(swapped);
return head;
} | 1,192 | 413 |
// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// 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.
/// \file
/// Tests for the LabJack specific checksum functions.
#include <gtest/gtest.h>
#include "SurgSim/Devices/LabJack/linux/LabJackConstants.h"
#include "SurgSim/Devices/LabJack/linux/LabJackChecksums.h"
using SurgSim::Devices::LabJack::extendedChecksum;
using SurgSim::Devices::LabJack::extendedChecksum8;
using SurgSim::Devices::LabJack::extendedChecksum16;
using SurgSim::Devices::LabJack::normalChecksum;
using SurgSim::Devices::LabJack::normalChecksum8;
TEST(LabJackChecksumsTest, NormalChecksum)
{
// Sum less than 256
std::array<unsigned char, SurgSim::Devices::LabJack::MAXIMUM_BUFFER> bytes;
unsigned char fillValue = 2;
bytes.fill(fillValue);
int count = 10;
int expectedValue = fillValue * (count - 1);
EXPECT_EQ(expectedValue, normalChecksum8(bytes, count));
normalChecksum(&bytes, count);
EXPECT_EQ(expectedValue, bytes[0]);
// Sum greater than 256, quotient + remainder < 256
fillValue = 100;
bytes.fill(fillValue);
count = 4;
int sum = fillValue * (count - 1); // 300
int quotient = sum / 256; // 1
int remainder = sum % 256; // 44
expectedValue = quotient + remainder;
EXPECT_EQ(expectedValue, normalChecksum8(bytes, count));
normalChecksum(&bytes, count);
EXPECT_EQ(expectedValue, bytes[0]);
// Sum greater than 256, quotient + remainder > 256
fillValue = 255;
bytes.fill(fillValue);
bytes[4] = 2;
count = 5;
// sum = 767, quotient = 2, remainder = 255, quotient + remainder = 257
// second_quotient = 1, second_remainder = 1, second_quotient + second_remainder = 2
expectedValue = 2;
EXPECT_EQ(expectedValue, normalChecksum8(bytes, count));
normalChecksum(&bytes, count);
EXPECT_EQ(expectedValue, bytes[0]);
}
TEST(LabJackChecksumsTest, ExtendedChecksum)
{
// Sums less than 256
std::array<unsigned char, SurgSim::Devices::LabJack::MAXIMUM_BUFFER> bytes;
unsigned char fillValue = 2;
bytes.fill(fillValue);
int count = 10;
int expectedValue16 = (count - 6) * fillValue; // 4 * 2 = 8
EXPECT_EQ(expectedValue16, extendedChecksum16(bytes, count));
int expectedValue8 = (6 - 1) * fillValue; // 5 * 2 = 10
EXPECT_EQ(expectedValue8, extendedChecksum8(bytes));
extendedChecksum(&bytes, count);
EXPECT_EQ(expectedValue16, bytes[4]);
EXPECT_EQ(0, bytes[5]);
// extendedChecksum alters the buffer before setting bytes[0] to the return value of extendedChecksum8.
EXPECT_EQ(expectedValue8 - 2 * fillValue + expectedValue16, bytes[0]);
// Sum greater than 256, quotient + remainder < 256
fillValue = 100;
bytes.fill(fillValue);
count = 20;
expectedValue16 = (count - 6) * fillValue; // 14 * 100 = 1400
EXPECT_EQ(expectedValue16, extendedChecksum16(bytes, count));
expectedValue8 = 245; // sum = 5 * 100 = 500, quotient = 1, remainder = 244, quotient + remainder = 245
EXPECT_EQ(expectedValue8, extendedChecksum8(bytes));
extendedChecksum(&bytes, count);
EXPECT_EQ(120, bytes[4]);
EXPECT_EQ(5, bytes[5]);
// extendedChecksum alters the buffer before setting bytes[0] to the return value of extendedChecksum8.
// sum = 100 + 100 + 100 + 120 + 5 = 425, quotient = 1, remainder = 169, quotient + remainder = 170
EXPECT_EQ(170, bytes[0]);
}
| 3,771 | 1,417 |
#define ANKERL_NANOBENCH_IMPLEMENT
#include "advent.hpp"
#include "util.hpp"
#include <functional>
#include "nanobench.h"
auto find_terms(std::vector<int> const& values, int n, int64_t sum, int64_t product = 1) -> std::optional<int64_t>
{
if (sum <= 0) {
return std::nullopt;
}
if (n == 2) {
for (auto x : values) {
auto y = sum - x;
if (std::binary_search(values.begin(), values.end(), y)) {
return std::make_optional(x * y * product);
}
}
} else if (n > 2) {
for (auto x : values) {
if (x > sum) continue;
if (auto res = find_terms(values, n - 1, sum - x, x * product); res.has_value()) {
return res;
}
}
}
return std::nullopt;
}
int day01(int argc, char** argv)
{
if (argc < 3) {
fmt::print("Provide an input file, a target sum and a number of terms.\n");
return 1;
}
int s;
int n;
if (auto res = parse_number<int>(argv[2]); res.has_value()) {
s = res.value();
} else {
throw std::runtime_error("Unable to parse target sum argument.");
}
if (auto res = parse_number<int>(argv[3]); res.has_value()) {
n = res.value();
} else {
throw std::runtime_error("Unable to parse number of terms argument.");
}
std::vector<int> values;
std::ifstream infile(argv[1]);
std::string line;
while (std::getline(infile, line)) {
if (auto v = parse_number<int>(line); v.has_value()) {
values.push_back(v.value());
}
}
std::sort(values.begin(), values.end());
auto res = find_terms(values, n, s);
if (res.has_value()) {
fmt::print("{}-term product = {}\n", n, res.value());
} else {
fmt::print("unable to find {}-term combination summing up to {}\n", n, s);
}
fmt::print("performance benchmark:\n");
ankerl::nanobench::Bench b;
b.run("day01", [&]() { find_terms(values, n, s); });
return 0;
}
| 2,048 | 734 |
/* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2018, Individual contributors, see AUTHORS file |
| See: http://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See details in http://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
#include <mrpt/hwdrivers/CBoardSonars.h>
#include <mrpt/system/CTicTac.h>
#include <mrpt/config/CConfigFile.h>
#include <mrpt/system/os.h>
#include <mrpt/system/filesystem.h>
#include <mrpt/gui/CDisplayWindow3D.h>
#include <mrpt/opengl/CCylinder.h>
#include <mrpt/opengl/COpenGLScene.h>
#include <mrpt/opengl/CGridPlaneXY.h>
#include <mrpt/opengl/stock_objects.h>
using namespace mrpt;
using namespace mrpt::hwdrivers;
using namespace mrpt::obs;
using namespace mrpt::gui;
using namespace mrpt::opengl;
using namespace mrpt::system;
using namespace mrpt::poses;
using namespace std;
int main()
{
try
{
CBoardSonars sonarBoard;
CObservationRange obs;
std::string firmVers;
CTicTac tictac;
CDisplayWindow3D wind("Sonar representation");
COpenGLScene::Ptr& scene = wind.get3DSceneAndLock();
scene->insert(
mrpt::make_aligned_shared<mrpt::opengl::CGridPlaneXY>(
-20, 20, -20, 20, 0, 1));
scene->insert(mrpt::opengl::stock_objects::RobotPioneer());
// scene->insert( mrpt::make_aligned_shared<mrpt::opengl::CCylinder>(1,
// 1, 2.0f)
// );
wind.unlockAccess3DScene();
// Load configuration:
ASSERT_(mrpt::system::fileExists("CONFIG_sonars.ini"));
CConfigFile conf("CONFIG_sonars.ini");
sonarBoard.loadConfig(conf, "BOARD_SONAR_CONFIG");
while (!mrpt::system::os::kbhit())
{
if (!sonarBoard.queryFirmwareVersion(firmVers))
{
cout << "Cannot connect to USB device... Retrying in 1 sec"
<< endl;
std::this_thread::sleep_for(1000ms);
}
else
{
cout << "FIRMWARE VERSION: " << firmVers << endl;
break;
}
}
cout << "Select operation:" << endl;
cout << " 1. Get measures from device" << endl;
cout << " 2. Program a new I2C address to a single sonar" << endl;
cout << "?";
char c = os::getch();
if (c == '1')
{
while (!mrpt::system::os::kbhit())
{
tictac.Tic();
if (sonarBoard.getObservation(obs))
{
double T = tictac.Tac();
mrpt::system::clearConsole();
printf(
"RX: %u ranges in %.03fms\n",
(unsigned int)obs.sensedData.size(), T * 1000);
scene = wind.get3DSceneAndLock();
for (size_t i = 0; i < obs.sensedData.size(); i++)
{
printf(
"[ID:%i]=%15f 0x%04X\n",
obs.sensedData[i].sensorID,
obs.sensedData[i].sensedDistance,
(int)(100 * obs.sensedData[i].sensedDistance));
// Show the distances
std::string obj =
format("sonar%i", obs.sensedData[i].sensorID);
mrpt::opengl::CCylinder::Ptr sonarRange;
mrpt::opengl::CRenderizable::Ptr objPtr =
scene->getByName(obj);
if (!objPtr)
{
sonarRange = mrpt::make_aligned_shared<
mrpt::opengl::CCylinder>(
0.0f, 0.0f, 1.0f, 30, 10);
sonarRange->setName(obj);
scene->insert(sonarRange);
}
else
sonarRange =
std::dynamic_pointer_cast<CCylinder>(objPtr);
sonarRange->setRadii(
0, tan(obs.sensorConeApperture) *
obs.sensedData[i].sensedDistance);
sonarRange->setPose(
mrpt::poses::CPose3D(obs.sensedData[i].sensorPose) +
CPose3D(0, 0, 0, 0, DEG2RAD(90.0), 0));
sonarRange->setHeight(obs.sensedData[i].sensedDistance);
sonarRange->enableShowName();
sonarRange->setColor(0, 0, 1, 0.25);
}
wind.unlockAccess3DScene();
wind.repaint();
}
else
{
cerr << "Error rx..." << endl;
// return -1;
}
std::this_thread::sleep_for(200ms);
}
}
else if (c == '2')
{
int curAddr, newAddr;
cout << "Enter current address: (decimal, 0 to 15)" << endl;
if (1 == scanf("%i", &curAddr))
{
cout << "Enter new address: (decimal, 0 to 15)" << endl;
if (1 == scanf("%i", &newAddr))
{
ASSERT_(curAddr >= 0 && curAddr < 16);
ASSERT_(newAddr >= 0 && newAddr < 16);
printf("Changing address %i --> %i... ", curAddr, newAddr);
if (sonarBoard.programI2CAddress(curAddr, newAddr))
printf(" DONE!\n");
else
printf(" ERROR!\n");
}
}
}
}
catch (std::exception& e)
{
cerr << e.what() << endl;
return -1;
}
return 0;
}
| 4,748 | 2,194 |
/**
* Author: Chungha Sung
* This is modified version of Markus' source code of his FSE 2017 submission.
*
* Original Author: Markus Kusano
*
* LLVM pass to perform abstract interpretation (using apron)
*/
#include "llvm/Pass.h"
#include "latticefact.h"
#include "varvisit.h"
#include "bbops.h"
#include "utils.h"
#include "cartesianprod.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Function.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Analysis/PostDominators.h"
#include "llvm/Analysis/DominanceFrontier.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/IR/InstIterator.h"
#include "../utils/mk_debug.h"
#include "../utils/z3_fp_helpers.h"
#include <vector>
#include <set>
#include <map>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <algorithm>
#include <cstdint>
#include "box.h"
#include "oct.h"
#include "pk.h"
#include "pkeq.h"
//#include "ap_abstract1.h"
#include <z3.h>
#include <z3++.h>
#include <z3_api.h>
#include <z3_fixedpoint.h>
using namespace llvm;
using namespace z3_fp_helpers;
ap_manager_t *manG;
int totalPairs = 0;
int filteredPairs = 0;
// Size of Z3 bitvector sort used in fixedpoint solver
//static const unsigned Z3_BV_SIZE = sizeof(uintptr_t) * 8;
// This size needs to be able to represent all the values used in the analysis.
// Increase it as necessary. If it gets too big, things seem to get pretty
// slow.
static const unsigned Z3_BV_SIZE = 16;
// Command line flags. These are used in other files!
// priority information flag
cl::opt<bool>
usePriG("priority"
, cl::desc("Use priority information")
, cl::init(false));
cl::opt<bool>
useBoxG("box"
, cl::desc("Use box abstract domain")
, cl::init(false));
cl::opt<bool>
useOctG("oct"
, cl::desc("Use octagon abstract domain")
, cl::init(false));
cl::opt<bool>
usePolyG("pkpoly"
, cl::desc("Use (strict) convex polyhedral abstract domain")
, cl::init(false));
cl::opt<bool>
useLinEqG("pklineq"
, cl::desc("Use linear inequality abstract domain")
, cl::init(false));
cl::opt<bool>
noCombinsG("nocombs"
, cl::desc("Combine all interferences into a single state (no "
"combinational exploration")
, cl::init(false));
cl::opt<bool>
useConstraintsG("constraints"
, cl::desc("Use constraint solver to prune infreasible interferences")
, cl::init(false));
cl::opt<bool>
assertSliceG("aslice"
, cl::desc("Slice on assertion(s) (requires PDG pass)")
, cl::init(false));
cl::opt<bool>
impactG("impact"
, cl::desc("Use change-impact analysis (equires change-impact pass).")
, cl::init(false));
// When true, the state at the time of a thread's creation is used instead of
// the initial state of the entire program.
cl::opt<bool>
dynInitG("dyninit"
, cl::desc("Calculate the initial state of a thread dynamically")
, cl::init(false));
cl::opt<bool>
filterMHB("filter-mhb"
, cl::desc("Filter interferences based on global program must-happen before")
, cl::init(false));
cl::opt<bool>
tsoConstrG("tso"
, cl::desc("Use TSO interference constraints")
, cl::init(false));
cl::opt<bool>
psoConstrG("pso"
, cl::desc("Use PSO interference constraints")
, cl::init(false));
cl::opt<bool>
rmoConstrG("rmo"
, cl::desc("Use RMO interference constraints")
, cl::init(false));
// The default behavior is to attempt to constrain branches on ICMP
// instructions. For example,
//
// br %1 label %2 label %3
//
// If %1 is an icmp instruction, e.g., icmp ne %5 %6 then the branch being
// true (resp. false) not only means %1 should be 1 (resp 0) but also that %5
// != %6 (resp. %5 == %6).
//
// So, when generating a fact to pass to either the true of false branch, using
// the icmp instruction allows for more acurrate facts being passed. Obviously,
// this comes with some extra overhead.
cl::opt<bool> constrICmp("-no-icmp-constr"
, cl::desc("Do not constrain branches using ICMP predicates")
, cl::init(true));
cl::opt<std::string>
z3BinLocG("z3"
, cl::desc("Location of Z3 binary")
, cl::init(""));
// Disable debugging output in debug build
#ifdef MK_DEBUG
cl::opt<bool>
nodebugG("nodebug"
, cl::desc("Disable debug output for debug build")
, cl::init(false));
#endif
// The maximum number of combinational interference permutations
static unsigned maxCombPermsG = 0;
struct WorklistAI : public ModulePass {
static char ID;
// The type of the worklist
typedef std::map<BasicBlock*, LatticeFact> worklist_t;
static constexpr const char * const constraintFile = "poconstr.smt2";
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
if (useConstraintsG || filterMHB) {
AU.addRequired<DominatorTreeWrapperPass>();
AU.addRequired<PostDominatorTree>();
}
}
// Print the passed map to stderr
void printFactMapStderr(std::map<BasicBlock*, LatticeFact> m) const {
for (auto i = m.begin(), e = m.end(); i != e; ++i) {
BasicBlock *b = i->first;
LatticeFact f = i->second;
errs() << "BasicBlock: " << *b ;
errs() << "Facts: ";
f.fprint(stderr);
errs() << '\n';
}
}
void printValToNameStderr(const std::map<Value*, std::string> m) const {
for (auto i = m.begin(), e = m.end(); i != e; ++i) {
Value *v = i->first;
std::string s = i->second;
errs() << s << ": " << *v << '\n';
}
}
WorklistAI() : ModulePass(ID) { }
// Given a lattice fact, return a map with each BasicBlock in the module
// mapped to the passed fact.
std::map<BasicBlock*, LatticeFact> initBBs(const LatticeFact &init
, Module &M) const {
std::map<BasicBlock *, LatticeFact> ret;
for (auto mi = M.begin(), me = M.end(); mi != me; ++mi) {
for (auto fi = mi->begin(), fe = mi->end(); fi != fe; ++fi) {
BasicBlock *bb = &*fi;
ret.emplace(bb, init);
}
}
return ret;
}
// Given a lattice fact, return a map with each BasicBlock in the function
// mapped to the passed fact
std::map<BasicBlock*, LatticeFact> initBBs(const LatticeFact &init
, Function *F) const {
std::map<BasicBlock *, LatticeFact> ret;
for (auto fi = F->begin(), fe = F->end(); fi != fe; ++fi) {
BasicBlock *bb = &*fi;
ret.emplace(bb, init);
}
return ret;
}
// Merge the passed vector of new facts into the passed worklist
void merge_worklist(
std::map<BasicBlock *, LatticeFact> *wl
, std::vector<std::pair<BasicBlock*, LatticeFact>> ps) const {
//errs() << "Size of ps: " << ps.size() << "\n";
for (auto p = ps.begin(), pe = ps.end(); p != pe; ++p) {
// Check if any of the basicblock are already in worklist.
// Merge if they are.
BasicBlock *newB = p->first;
DEBUG_MSG("Merging worklist: BB: " << *newB << '\n');
auto f = wl->find(newB);
if (f == wl->end()) {
DEBUG_MSG("Fact not in list: ");
DEBUG(p->second.fprint(stderr););
DEBUG_MSG("\n");
wl->emplace(newB, p->second);
}
else {
// TODO: Widen here
LatticeFact mergeFact = LatticeFact::factJoin(f->second, p->second);
//LatticeFact mergeFact = LatticeFact::factJoinWiden(f->second, p->second);
DEBUG_MSG("Fact in list, merged: ");
DEBUG(mergeFact.fprint(stderr););
DEBUG_MSG("\n");
wl->erase(f);
wl->emplace(newB, mergeFact);
}
}
return;
}
// Given a value, return its string name.
//
// This will always return a string. If the value has never been encountered
// before, it will be stored in the valToName map with a fresh name.
//
// This also updates nameToVal so a reverse lookup can be done (see
// getValue())
std::string getName(std::map<Value *, std::string> &valToName
, std::map<std::string, Value *> &nameToVal, Value *v) const {
auto f = valToName.find(v);
if (f == valToName.end()) {
size_t newSz = valToName.size();
std::string newName = "v" + std::to_string(newSz);
auto res = valToName.insert(std::make_pair(v, newName));
if (!res.second) {
assert(0 && "item already exists in valToName map");
}
nameToVal.emplace(newName, v);
return (res.first)->second;
}
return f->second;
}
// Given a string name of a value return the actual value.
//
// Note: this will crash if the value has never been saved in the map before.
Value *getValue(const std::map<std::string, Value*> nameToVal
, std::string s) const {
auto f = nameToVal.find(s);
if (f == nameToVal.end()) {
assert(0 && "item not found in nameToVal");
}
return f->second;
}
// Return the name of all the variables used in the program
VarVisitor::Vars getAllVarNames(Module &M) const {
VarVisitor vv;
vv.visit(M);
// Also add in the float/int globals variables
for (auto gi = M.global_begin(), ge = M.global_end(); gi != ge; ++gi) {
GlobalVariable &g = *gi;
if (Utils::isIntegerGlobal(&g)) {
vv.vars.ints.push_back(&g);
}
else if (Utils::isFloatGlobal(&g)) {
vv.vars.floats.push_back(&g);
}
else {
errs() << "[WARNING] Global which is neither Integer nor Float\n";
errs() << g << '\n';
errs() << "It is not being monitored (there may be errors en route)\n";
}
}
// TODO: Need to handle arrays here
return vv.vars;
}
// Return the function named "main" or NULL if the module does not have a
// "main" function
Function *getMainFuncOrNULL(Module &M) const {
for (auto mi = M.begin(), me = M.end(); mi != me; ++mi) {
Function &f = *mi;
if (f.getName() == "main") {
return &f;
}
}
return NULL;
}
// Return any function used in a pthread_create() call.
// This will crash if any indirect functions are found
std::set<Function *> getThreads(Module &M) const {
std::set<Function *> ret;
for (auto mi = M.begin(), me = M.end(); mi != me; ++mi) {
for (auto fi = mi->begin(), fe = mi->end(); fi != fe; ++fi) {
for (auto bi = fi->begin(), be = fi->end(); bi != be; ++bi) {
Instruction *I = &*bi;
if (CallInst* ci = dyn_cast<CallInst>(I)) {
Function *called = ci->getCalledFunction();
if (called->getName() == "pthread_create") {
// Found pthread_create. The 2nd argument (zero indexed) is the
// function being called
Value *v = ci->getArgOperand(2);
if (Function *tFunc = dyn_cast<Function>(v)) {
ret.insert(tFunc);
}
else {
errs() << "[ERROR] pthread_create with non function 2nd arg\n";
errs() << *v << '\n';
exit(EXIT_FAILURE);
}
}
}
} // for (bi ... )/
} // for (fi ... )
} // for (mi ... )
return ret;
}
std::vector<CallInst *> getThreadCreate(Module &M) const {
std::vector<CallInst *> ret;
for (auto mi = M.begin(), me = M.end(); mi != me; ++mi) {
Function *cur = &*mi;
Utils::addVector(ret, getThreadCreate(cur));
}
return ret;
}
std::vector<CallInst *> getThreadCreate(Function *F) const {
std::vector<CallInst *> ret;
for (auto bi = F->begin(), be = F->end(); bi != be; ++bi) {
for (auto ii = bi->begin(), ie = bi->end(); ii != ie; ++ii) {
Instruction *I = &*ii;
if (CallInst* ci = dyn_cast<CallInst>(I)) {
Function *called = ci->getCalledFunction();
if (called->getName() == "pthread_create") {
ret.push_back(ci);
}
}
} // for (ii ...)
} // for (bi ... )/
return ret;
}
// Collect the Integer/Floating point function parameters
VarVisitor::Vars getFuncParamNames(Module &M) const {
VarVisitor::Vars vars;
for (auto mi = M.begin(), me = M.end(); mi != me; ++mi) {
Function &f = *mi;
Function::ArgumentListType &al = f.getArgumentList();
for (auto ai = al.begin(), ae = al.end(); ai != ae; ++ai) {
Argument &a = *ai;
Type *at = a.getType();
if (at->isPointerTy() || at->isIntegerTy()) {
vars.ints.push_back(&a);
}
else if (at->isFloatingPointTy()) {
vars.floats.push_back(&a);
}
else {
errs() << "[ERROR] unhandled argument type: " << a << '\n';
assert(0 && "see above");
}
}
}
return vars;
}
// Given the list of integer and floating point values return an environment
// containing them all.
//
// Returns NULL if the environment could not be created
//
// Note: The user must manage the memory of the returned environment.
ap_environment_t *createEnvironment(std::map<Value *, std::string> &valToName
, std::map<std::string, Value *> &nameToVal, Module &M) const {
// TODO: Global variables should also be assigned to variable names?
VarVisitor::Vars vs = getAllVarNames(M);
vs = VarVisitor::mergeVars(vs, getFuncParamNames(M));
DEBUG_MSG("[DEBUG] Num Int vars: " << vs.ints.size() << '\n');
DEBUG_MSG("[DEBUG] Num Float vars: " << vs.floats.size() << '\n');
// Use sets to ensure no duplicates are added to the environment
std::set<const char *> intStrs;
std::set<const char *> floatStrs;
// This will create names for the all the int and float variables in the
// program and store them in the internal maps of this class (getName())
// Put all the ints in a set
for (size_t i = 0; i < vs.ints.size(); ++i) {
Value *v = vs.ints[i];
DEBUG_MSG("[DEBUG] getting int value: " << *v << '\n');
std::string vs = getName(valToName, nameToVal, v);
DEBUG_MSG("\tname: " << vs << '\n');
intStrs.insert(vs.c_str());
}
ap_var_t intVs[intStrs.size()];
size_t pos = 0;
for (auto it = intStrs.begin(), e = intStrs.end(); it != e; ++it) {
intVs[pos++] = (ap_var_t)(*it);
}
// Put all the floats in a set
for (size_t i = 0; i < vs.floats.size(); ++i) {
Value *v = vs.floats[i];
DEBUG_MSG("[DEBUG] getting float value: " << *v << '\n');
std::string vs = getName(valToName, nameToVal, v);
DEBUG_MSG("\tname: " << vs << '\n');
floatStrs.insert(vs.c_str());
}
ap_var_t floatVs[floatStrs.size()];
pos = 0;
for (auto it = floatStrs.begin(), e = floatStrs.end(); it != e; ++it) {
floatVs[pos++] = (ap_var_t)(*it);
}
ap_environment_t *env = ap_environment_alloc(intVs
, intStrs.size()
, floatVs
, floatStrs.size());
assert(env && "error creating environment");
return env;
}
// Return a vector of functions such that the parent of any thread always
// ocurrs at a lower index than the child.
std::vector<Function *> sortByCreation(Function *main
, const std::map<Function *, std::vector<Function*>> parent2child) {
std::vector<Function *> ret;
std::deque<Function *> toProcess;
// Main is the parent of everyone
toProcess.push_back(main);
while (toProcess.size()) {
Function *curParent = toProcess.front();
toProcess.pop_front();
// Add the parent
ret.push_back(curParent);
// Add all its children to be processed
auto iter = parent2child.find(curParent);
if (iter != parent2child.end()) {
std::vector<Function *> children = iter->second;
// The children of the children also need to be added to `ret`
for (Function *c : children) {
toProcess.push_back(c);
}
}
}
assert(ret.size() && "returning size zero vector");
return ret;
}
// Given the passed lattice fact with all variables at whatever initial value
// you want (e.g., undefined (top)) this will update the passed fact
// (initFact) such that all the globals are initialized to their starting
// value (from the source code).
// This assumes that all LLVM Values are mapped to name for apron to use
// (v2v).
LatticeFact getInitState(Module *M
, const LatticeFact initFact
, const std::map<Value *, std::string> v2v) const {
LatticeFact ret = initFact;
for (auto gi = M->global_begin(), ge = M->global_end(); gi != ge; ++gi) {
// Get the initializer for the global. Lookup the name, and set the value
// of the name to the initializer
GlobalVariable *g = &*gi;
if (!g->hasInitializer()) {
errs() << "[ERROR] Global without initializer (possibly external)\n"
<< *g << '\n';
assert(0 && "see above");
}
const Constant *c = g->getInitializer();
if (const ConstantInt *ci = dyn_cast<ConstantInt>(c)) {
std::string gName = Utils::valueToStringUnsafe(v2v, g);
int val = Utils::getConstantIntUnsafe(ci);
DEBUG_MSG("[DEBUG] Initializing Global: ");
DEBUG_MSG("\tGlobal Name: " << gName << '\n');
DEBUG_MSG("\tInit Val: " << val << '\n');
ret = ret.assign(gName, val);
DEBUG(ret.fprint(stderr););
}
// TODO: also need to handle floats (ConstantFloat::getValueAPF())
//if (isFloatGlobal(g)) {
// ...
//}
else {
errs() << "[WARNING] Initializing unhandled global type: " << *g
<< "\nSetting to default initial value\n";
}
} // for
return ret;
}
// Return all the stores in the passed function
std::vector<StoreInst *> getStores(Function *f) const {
std::vector<StoreInst *> ret;
for (auto fi = f->begin(), fe = f->end(); fi != fe; ++fi) {
BasicBlock &b = *fi;
for (auto bi = b.begin(), be = b.end(); bi != be; ++bi) {
Instruction *i = &*bi;
if (StoreInst *si = dyn_cast<StoreInst>(i)) {
ret.push_back(si);
}
}
}
return ret;
}
// Return all the stores in the passed BasicBlock
std::vector<StoreInst *> getStores(BasicBlock *b) {
std::vector<StoreInst *> ret;
for (auto bi = b->begin(), be = b->end(); bi != be; ++bi) {
Instruction *i = &*bi;
if (StoreInst *si = dyn_cast<StoreInst>(i)) {
ret.push_back(si);
}
}
return ret;
}
// Return all the loads in the passed function
std::vector<Instruction *> getLoads(Function *f) const {
std::vector<Instruction *> ret;
for (auto fi = f->begin(), fe = f->end(); fi != fe; ++fi) {
BasicBlock &b = *fi;
for (auto bi = b.begin(), be = b.end(); bi != be; ++bi) {
Instruction *i = &*bi;
//if (LoadInst *si = dyn_cast<LoadInst>(i)) {
if (Utils::isSomeLoad(i)) {
ret.push_back(i);
}
}
}
return ret;
}
bool loadStoreSameVal(Instruction *si, Instruction *li) const {
if (StoreInst *s = dyn_cast<StoreInst>(si)) {
if (LoadInst *l = dyn_cast<LoadInst>(li)) {
return loadStoreSameValSL(s, l);
}
else if (AtomicRMWInst *rmw = dyn_cast<AtomicRMWInst>(li)) {
return loadStoreSameValSRMW(s, rmw);
}
else {
assert(0 && "loadStoreSameVal: unhandled load type sub StoreInst");
}
}
else if (AtomicRMWInst *rmw = dyn_cast<AtomicRMWInst>(si)) {
if (LoadInst *l = dyn_cast<LoadInst>(li)) {
return loadStoreSameValRMWL(rmw, l);
}
else if (AtomicRMWInst *rmwl = dyn_cast<AtomicRMWInst>(li)) {
return loadStoreSameValRMWRMW(rmw, rmwl);
}
else {
assert(0 && "loadStoreSameVal: unhandled load type sub atomicrmw");
}
}
else {
assert(0 && "loadStoreSameVal: unhandled store type");
}
}
bool loadStoreSameValRMWL(AtomicRMWInst *rmw, LoadInst *l) const {
Value *stPtr = rmw->getPointerOperand();
Value *lPtr = l->getPointerOperand();
return stPtr == lPtr;
}
bool loadStoreSameValRMWRMW(AtomicRMWInst *rmws, AtomicRMWInst *rmwl) const {
Value *stPtr = rmws->getPointerOperand();
Value *lPtr = rmwl->getPointerOperand();
return stPtr == lPtr;
}
bool loadStoreSameValSRMW(StoreInst *s, AtomicRMWInst *rmw) const {
Value *stPtr = s->getPointerOperand();
Value *lPtr = rmw->getPointerOperand();
return stPtr == lPtr;
}
// Return true if the passed store stores into the memory location loaded by
// the load
bool loadStoreSameValSL(StoreInst *s, LoadInst *l) const {
Value *stPtr = s->getPointerOperand();
Value *lPtr = l->getPointerOperand();
return stPtr == lPtr;
}
// Given the set of possible interferences for each load in the passed
// thread, reanalyze the thread in the presense of the interferences.
//
// The fact at the start of each basicblock after the analysis
// stabalizes is returned.
//
// This will do a combinational exploration of the possible interferences for
// each load, e,g, if l1 has two interferences i1 and i2, and l2 has two
// interferences i3 and i4, we will explore all the combinations of reading
// ((i1,i2), (i3,i4)) as well as reading from the thread's own memory state
// (i.e., at most 9 combinations).
//
// The passed vector, rErrors, will contain any reachable error statements as
// well as the reachable fact at the statement.
std::map<BasicBlock *, LatticeFact> analyzeThreadInterf(
ap_manager_t *man
, ap_environment_t *env
, Function *f
, CallInst *createSite
, const std::map<Instruction *, std::vector<Instruction *>> interfs
, const std::map<Instruction *, LatticeFact> stFacts
//, std::vector<std::pair<Instruction *, LatticeFact>> &rErrors
, std::set<Instruction *> &rErrors
, std::map<Instruction *, LatticeFact> &reachableStores
, std::map<CallInst *, LatticeFact> &reachThreadCreate
, LatticeFact entryFact
, const std::set<Instruction *> assertSlice
, const std::set<Instruction *> impacted
, const std::set<Instruction *> mayImpact
, const std::map<Value *, std::string> v2n
, z3::context &ctx
, Z3_fixedpoint &zfp
) const {
DEBUG_MSG("[DEBUG] analyzeThreadIntefer(): number of interferences: "
<< interfs.size() << '\n');
//std::cout << "Interf size: " << interfs.size() << "\n";
if (!interfs.size()) {
// When there are no interferences, we do not need to do any
// combinational exploration
return analyzeFuncNoInterf(man, env, rErrors, reachableStores
, reachThreadCreate, entryFact, assertSlice, impacted, mayImpact, v2n, f);
}
if (noCombinsG) {
// If we are not doing a combinatorial exploration, join all the
// interferences for each load into a single fact
std::map<Instruction *, LatticeFact> allInterfs
= joinInterfs(interfs, stFacts);
// Then, perform the analysis as usual but inform the transfer functions
// to consider both the interference and the state of the thread
// simultaneously
return analyzeFunc(man, env, allInterfs, rErrors, reachableStores
, reachThreadCreate, assertSlice, impacted, mayImpact, v2n, entryFact, f, true);
}
// Calculate the cartesian product of all possible facts from which a load
// can read from including its own memory state.
// To do this, consider that 0 indicates a thread should read from its own
// memory state at the time of some load while a value higher than 0 is an
// index into the vector of StoreInsts in intefers (note: it will be off by
// one (indexed starting from one))
std::vector<int> choicesPerLoad;
// Each location in choicesPerLoad corresponds to a load instruction. The
// ordering of load instructions is based on the iterator order of interfs.
for (auto i = interfs.begin(), ie = interfs.end(); i != ie; ++i) {
// Incluce one extra choice, the thread reading the value from its own
// memory environment
int v = i->second.size() + 1;
assert(v > 0 && "making zero choices");
choicesPerLoad.push_back(v);
}
// The results of each permutation will be joined into this map
std::map<BasicBlock *, LatticeFact> res;
CartesianProduct cp(choicesPerLoad);
// Test each possible combination
unsigned count = 1;
for (; !cp.AtEnd(); cp.Increment()) {
std::vector<int> curPerm = cp.permutation();
bool ret = testCurPerm(man
, env
, f
, createSite
, curPerm
, interfs
, stFacts
, rErrors
, reachableStores
, reachThreadCreate
, entryFact
, assertSlice
, impacted
, mayImpact
, v2n
, ctx
, zfp
, res);
if (ret) {
// Only increment the number of permutations if the permutation is
// tested.
maxCombPermsG = std::max(maxCombPermsG, count);
count++;
}
} // for (; !cp.AtEnd(); cp.Increment())
return res;
}
// Test the passed permutation.
//
// Returns true if the abstract interperter was run (i.e., the solver could
// not prove the permutation was redundant)
//
// any facts in res will be merged with the facts produced by the analysis
bool testCurPerm(ap_manager_t *man
, ap_environment_t *env
, Function *f
, CallInst *createSite
, const std::vector<int> perm
, const std::map<Instruction *, std::vector<Instruction *>> interfs
, const std::map<Instruction *, LatticeFact> stFacts
//, std::vector<std::pair<Instruction *, LatticeFact>> &rErrors
, std::set<Instruction *> &rErrors
, std::map<Instruction *, LatticeFact> &reachableStores
, std::map<CallInst *, LatticeFact> &reachThreadCreate
, LatticeFact entryFact
, const std::set<Instruction *> assertSlice
, const std::set<Instruction *> impacted
, const std::set<Instruction *> mayImpact
, const std::map<Value *, std::string> v2n
, z3::context &ctx
, Z3_fixedpoint &zfp
, std::map<BasicBlock *, LatticeFact> &res ) const {
assert(perm.size() == interfs.size() && "choice number mismatch");
// Note: since the store and load instructions are all orded (they are in a
// map) the results for the same map of store instructions will lead to the
// same order in the permutation vector. Additionally, the interferences
// can only grow and not decrease (everything is monotonic). So, if we see
// the same _exact_ permutation again we can use a cached result.
//
// This works because the constraints are based on the entire program
// (i.e., the constraints will always be the same for each call).
//
// This is a map from the permutation vector to the cached result
static std::map<std::vector<int>, bool> permCache;
DEBUG_MSG("Permutation: ");
DEBUG(for (int i : perm) DEBUG_MSG(i << " "););
DEBUG_MSG('\n');
std::map<Instruction *, LatticeFact> curInterfMap;
// Same as curInterfMap but maps a Load to the store it is reading from
std::map<Instruction *, Instruction *> curInterfStoreMap;
// Map from an instruction reading from the thread-local to the
// corresponding store its reading from.
std::map<Instruction *, Instruction *> curSelfStoreMap;
int pos = 0;
// Given the indices in the permutation, gather up the corresponding facts
// at the interfering stores.
for (auto i = interfs.begin(), ie = interfs.end(); i != ie; ++i, ++pos) {
int curChoice = perm[pos];
Instruction *l = i->first;
DEBUG_MSG("[DEBUG] Adding load--fact interference\n");
DEBUG_MSG("\tload: " << *l << '\n');
if (curChoice == 0) {
// Not including the load in the map indicates that it should read
// from its own memory environment
DEBUG_MSG("\tstore: self\n");
std::vector<Instruction *> ss = getPreviousStoresWithCreate(l, createSite);
if (ss.size() == 1) {
DEBUG_MSG("\tfound predecessor store:" << *(ss[0]) << '\n');
curSelfStoreMap.emplace(l, ss[0]);
}
else {
// TODO: what constraints can we deduce when there is more than one
// preceeding store?
}
continue;
}
// Indecies in the permutation are one indexed (since zero is used in
// the previous `if`)
size_t idx = curChoice - 1;
std::vector<Instruction*> sts = i->second;
assert(idx < sts.size() && "out-of-bounds choice");
Instruction *st = sts[idx];
assert(curInterfMap.find(l) == curInterfMap.end() && "duplicate load");
assert(stFacts.find(st) != stFacts.end()
&& "fact not found for store");
DEBUG_MSG("\tstore: " << *st << '\n');
curInterfMap.emplace(l, Utils::mapAtUnsafe(stFacts, st));
if (useConstraintsG) {
curInterfStoreMap.emplace(l, st);
}
} // for (auto i = interfs.begin(), ie = interfs.end(); ...)
// Check if this interference is feasible
if (useConstraintsG) {
auto it = permCache.find(perm);
DEBUG_MSG("Checking perm cache\n");
if (it != permCache.end()) {
DEBUG_MSG("[DEBUG] perm cache hit!\n");
if (it->second) {
DEBUG_MSG("\tviolates program order\n");
// return without testing, can safely skip.
return false;
}
// falling through this if brach (if (it != permCache.end())) leads
// to the permutation being tested but violatesProgOrder() will not
// be called thus saving the solver call time
}
else {
// Since we have never seen this permutation before, test if it
// violates the program order
if (violatesProgOrder(curInterfStoreMap, curSelfStoreMap, ctx, zfp)) {
DEBUG_MSG("\tpermutation violates program order\n");
DEBUG_MSG("\t*Permutation: ");
DEBUG(for (int i : perm) DEBUG_MSG(i << " "););
DEBUG_MSG('\n');
permCache[perm] = true;
// Test can be safely skipped
return false;
}
else {
DEBUG_MSG("\tpermutation does not violate prog. order\n");
DEBUG_MSG("\t*Permutation: ");
DEBUG(for (int i : perm) DEBUG_MSG(i << " "););
DEBUG_MSG('\n');
permCache[perm] = false;
}
}
}
DEBUG_MSG("running abstract interpretation\n");
// Test the thread in the presense of this round of interferences
std::map<BasicBlock *, LatticeFact> newRes
= analyzeFunc(man, env, curInterfMap, rErrors, reachableStores
, reachThreadCreate, assertSlice, impacted, mayImpact, v2n, entryFact, f, false);
DEBUG_MSG("merging AI results\n");
// Merge the new results for this combination with the old
res = mergeFactMaps(res, newRes);
return true;
}
// Return true if the load instructions reading from the passed store
// instructions violates the program order.
//
// This uses the baseConstrs and issues a solver call to muZ.
//
// rfs are extra (i1, i2) pairs where reads-from(i1, i2) will be added but
// not checked if its feasible
bool violatesProgOrder(const std::map<Instruction *, Instruction *> interfs
, const std::map<Instruction *, Instruction *> rfs
, z3::context &ctx, Z3_fixedpoint &zfp) const {
DEBUG_MSG("Checking prog order\n");
if (interfs.size() == 0) {
// Interferences can be of size zero when the thread is reading from its
// own memory environment. This will never violate the program order
DEBUG_MSG("\tinterf.size() is zero, skipping prog. order check\n");
return false;
}
// If a loads and stores is in this map then we already have the results
// (the associated value). The solver does not need to be called
std::map<std::set<Instruction*>, bool> readFromCache;
std::set<Instruction*> curInsts;
// The reads-from constraints are only valid for the current interation;
// so, save a backtracking location in the solver.
Z3_fixedpoint_push(ctx, zfp);
bool violates = false;
// Add the read-from constraints from the passed map
for (auto i = interfs.begin(), ie = interfs.end(); i != ie; ++i) {
Instruction *l = i->first;
Instruction *s = i->second;
curInsts.insert(l);
curInsts.insert(s);
addReadsFromFact(ctx, zfp, l ,s);
}
for (auto i = rfs.begin(), ie = rfs.end(); i != ie; ++i) {
Instruction *l = i->first;
Instruction *s = i->second;
addReadsFromFact(ctx, zfp, l ,s);
}
// Check for any infeasible reads-from
// Note: this needs to be run after the previous for-loop runs to
// completion so that all the reads-from constraints are added
for (auto i = interfs.begin(), ie = interfs.end(); i != ie; ++i) {
Instruction *l = i->first;
Instruction *s = i->second;
Z3_bool res = queryNotReads(ctx, zfp, l, s);
if (res == Z3_L_TRUE) {
violates = true;
// Finding one which violates is sufficient to stop
break;
}
else if (res == Z3_L_FALSE) {
violates = false;
DEBUG_MSG("No program order violation, moving to next reads-from\n");
}
else if (res == Z3_L_UNDEF) {
// Assume that it does not violate if it is unknown
errs() << "[WARNING] undef result from muZ\n";
violates = false;
}
else {
assert(0 && "unreachable");
}
}
// Restore the previous state of the solver. This removes all the
// reads-from constraints added
Z3_fixedpoint_pop(ctx, zfp);
// Update the cache
readFromCache[curInsts] = violates;
DEBUG_MSG("Program order violation? " << violates << '\n');
return violates;
}
// Return the results of a query on (not-rf l st)
Z3_bool queryNotReads(z3::context &ctx, Z3_fixedpoint &zfp, Instruction *l
, Instruction *st) const {
assert(Utils::isSomeLoad(l) && "reading from non-load");
z3::expr args[2] = {getValueBVID(ctx, l), getValueBVID(ctx, st)};
z3::expr nrfApp= getNotReadsFromFuncDecl(ctx)(2, args);
Z3_bool ret = Z3_fixedpoint_query(ctx, zfp, nrfApp);
#if 0
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
z3::sort boolSort = ctx.bool_sort();
//Z3_fixedpoint_register_relation(ctx, zfp
//, Z3_get_app_decl(ctx
//, Z3_to_app(ctx, qAst)));
//Z3_ast ldID = getValueBVID(ctx, l);
//Z3_ast stID = getValueBVID(ctx, st);
z3::expr args[2] = {getValueBVID(ctx, l), getValueBVID(ctx, st)};
z3::expr nrfApp = getNotReadsFromFuncDecl(ctx)(2, args);
// Create a relation which is true if the query is true.
// The truth of the query is based off a rule
z3::expr qAst = z3::expr(ctx, Z3_mk_fresh_const(ctx, "query", boolSort));
Z3_fixedpoint_add_rule(ctx, zfp
, Z3_mk_implies(ctx, nrfApp, qAst), NULL);
Z3_bool ret = Z3_fixedpoint_query(ctx, zfp, qAst);
#endif
#ifdef MK_DEBUG
DEBUG_MSG("NRF Query Stats\n");
z3::stats sts = z3::stats(ctx, Z3_fixedpoint_get_statistics(ctx, zfp));
std::cerr << sts << '\n';
std::string rules = Z3_fixedpoint_to_string(ctx, zfp, 0, NULL);
DEBUG_MSG("Rules: " << rules << '\n';);
DEBUG_MSG("Query: " << Z3_ast_to_string(ctx, nrfApp) << '\n');
#endif
return ret;
}
// Return the results of a query on (linehigh l st)
// Result of query: 1:true, -1:false, 0:undefined
bool queryPri(z3::context &ctx, Z3_fixedpoint &zfp, Instruction *l
, Instruction *st) const {
// check nonLastSt first
z3::expr args[1] = {getValueBVID(ctx, st)};
z3::expr nonLastStApp = getNonLastStFuncDecl(ctx)(1, args);
Z3_bool nonLastRet = Z3_fixedpoint_query(ctx, zfp, nonLastStApp);
errs() << "======================================\n";
errs() << "ID of Load: " << getId(l, Z3_BV_SIZE) << "\n";
errs() << *l << "\n";
errs() << "ID of Store: " << getId(st, Z3_BV_SIZE) << "\n";
errs() << *st << "\n";
if (nonLastRet == 1) {
errs() << "St is nonLast\n";
} else {
errs() << "St is NOT nonLast\n";
}
// check complete ld
z3::expr args3[1] = {getValueBVID(ctx, l)};
z3::expr compLdApp = getCompLdFuncDecl(ctx)(1, args3);
Z3_bool compLdRet = Z3_fixedpoint_query(ctx, zfp, compLdApp);
if (compLdRet == 1) {
errs() << "Load is completeLoad\n";
} else {
errs() << "Load is not completeLoad\n";
}
if (compLdRet == 1 && nonLastRet == 1) {
errs() << "======================================\n";
return false;
}
if (compLdRet != 1 && nonLastRet != 1) {
errs() << "======================================\n";
return true;
}
// check ld-st higher
z3::expr args1[2] = {getValueBVID(ctx, l), getValueBVID(ctx, st)};
z3::expr lineHighApp = getLineHighFuncDecl(ctx)(2, args1);
Z3_bool ldStRet = Z3_fixedpoint_query(ctx, zfp, lineHighApp);
// check st-ld higher
z3::expr args2[2] = {getValueBVID(ctx, st), getValueBVID(ctx, l)};
z3::expr lineHighApp2 = getLineHighFuncDecl(ctx)(2, args2);
Z3_bool stLdRet = Z3_fixedpoint_query(ctx, zfp, lineHighApp2);
if (compLdRet != 1 && nonLastRet == 1 && ldStRet == 1) {
errs() << "ld is higher than st\n";
errs() << "======================================\n";
return true;
} else if (compLdRet !=1 && nonLastRet == 1 && ldStRet != 1) {
errs() << "ld is not higher than st\n";
errs() << "======================================\n";
return false;
} else if (compLdRet == 1 && nonLastRet != 1 && stLdRet == 1) {
errs() << "st is higher than ld\n";
errs() << "======================================\n";
return true;
} else if (compLdRet == 1 && nonLastRet != 1 && stLdRet != 1) {
errs() << "st is not higher than ld\n";
errs() << "======================================\n";
return false;
} else {
assert(0 && "There is no case for here");
}
/*
std::cout << "Priority Query Stats";
z3::stats sts = z3::stats(ctx, Z3_fixedpoint_get_statistics(ctx, zfp));
std::cerr << sts << "\n";
*/
//#ifdef MK_DEBUG
//DEBUG_MSG("Priority Query Stats\n");
//z3::stats sts = z3::stats(ctx, Z3_fixedpoint_get_statistics(ctx, zfp));
//std::cerr << sts << '\n';
//#endif
}
// Return the results of a query on (MHB l st)
Z3_bool queryMHB(z3::context &ctx, Z3_fixedpoint &zfp, Instruction *l
, Instruction *st) const {
z3::expr args[2] = {getValueBVID(ctx, l), getValueBVID(ctx, st)};
z3::expr mhbApp = getMHBFuncDecl(ctx)(2, args);
Z3_bool ret = Z3_fixedpoint_query(ctx, zfp, mhbApp);
#ifdef MK_DEBUG
DEBUG_MSG("MHB Query Stats\n");
z3::stats sts = z3::stats(ctx, Z3_fixedpoint_get_statistics(ctx, zfp));
std::cerr << sts << '\n';
#endif
return ret;
}
// Given an instruction and Value found the closest preceding store within
// the same function as the instruction to the passed Value.
//
// If there are none, returns an empty vector.
static std::vector<Instruction *> getPreviousStores(Instruction *i, Value *v) {
assert(i != NULL && "getPreviousStores(i,v): NULL instruction");
assert(v != NULL && "getPreviousStores(i,v): NULL value");
DEBUG_MSG("[DEBUG] getPreviousStores(): " << *i << ", v: " << *v << '\n');
Function *f = i->getParent()->getParent();
BasicBlock *b = i->getParent();
// Check if there is simply a store in this basicblock
Instruction *prevStore = NULL;
for (Instruction &bbi : *b) {
if (&bbi == i) {
break;
}
Value *strPtr = Utils::getStorePtr(&bbi);
if (strPtr == v) {
prevStore = &bbi;
}
}
if (prevStore != NULL) {
std::vector<Instruction *> ret;
ret.push_back(prevStore);
return ret;
}
// We know there is no store before `i` to `v` in the BasicBlock. If there
// is one it must come from some other BasicBlock.
std::map<BasicBlock *, std::set<Instruction*>> reach = getReachingStores(f);
std::set<Instruction*> bReachIn = Utils::mapAtUnsafe(reach, b);
DEBUG_MSG(" numReachingStores:" << bReachIn.size() << '\n');
// Find all the incoming stores to `v`
std::vector<Instruction*> storesToV;
for (auto it = bReachIn.begin(), et = bReachIn.end(); it != et; ++it) {
Instruction *st = *it;
assert(st != NULL && "getPreviousStores: NULL in reachable map");
Value *stPtr = Utils::getStorePtr(st);
assert(stPtr != NULL
&& "getPreviousStores: reachable store with NULL ptr operand");
if (stPtr == v) {
storesToV.push_back(st);
}
}
// storesToV contains zero or more preceeding stores
return storesToV;
//if (storesToV.size() == 0) {
// // There are no stores before `i` to `v` in the BasicBlock and there are no
// return storesToV;
//}
//else if (storesToV.size() == 1) {
// Instruction *storeIn = storesToV[0];
// assert(storeIn != NULL && "getPreviousStore: NULL reachable store");
// assert(Utils::getStorePtr(storeIn) != NULL
// && "getPreviousStore: storeIn with NULL ptr operand");
// return storeIn;
//}
//else {
// DEBUG_MSG("num reaching stores:" << storesToV.size() << '\n');
// for (size_t i = 0; i < storesToV.size(); ++i) {
// DEBUG_MSG(" " << *(storesToV[i]) << '\n');
// }
// assert(0 && "getPreviousStore: more than one reaching store");
//}
}
// CallInst is the thread_create function of `i`. Attempt to look backwards
// from i to find a previous store including looking before the thread
// creation site.
static std::vector<Instruction *> getPreviousStoresWithCreate(Instruction *i
, CallInst *cre) {
if (LoadInst *l = dyn_cast<LoadInst>(i)) {
Value *v = l->getPointerOperand();
std::vector<Instruction *> ret = getPreviousStores(i, v);
if (ret.size() > 0) {
// Found some previous store
return ret;
}
else {
// Try to look back from the creation site.
// TODO: this could continue up the thread creation chain but it doesn't
DEBUG_MSG("[DEBUG] Search searching back from creation stite for store\n");
if (cre == NULL) {
DEBUG_MSG(" NULL creation site, not searching\n");
return ret; // ret.size <= 0
}
ret = getPreviousStores(cre, v);
return ret;
}
}
else {
errs() << "[ERROR] getPreviousStoreWithCreate: unimplemented instruction type: "
<< * i << '\n';
assert(0 && "unreachable");
}
}
// Given an instruction performing a load find the closest precding store
// within the same Function. If no store is found, return NULL.
static std::vector<Instruction *> getPreviousStore(Instruction *i) {
if (LoadInst *l = dyn_cast<LoadInst>(i)) {
Value *v = l->getPointerOperand();
return getPreviousStores(i, v);
}
else {
errs() << "[ERROR] getPreviousStores: unimplemented instruction type: "
<< * i << '\n';
assert(0 && "unreachable");
}
//DEBUG_MSG("[DEBUG] getPreviousStore(): " << *l << '\n');
//Function *f = l->getParent()->getParent();
//BasicBlock *b = l->getParent();
//std::map<BasicBlock *, std::set<Instruction*>> reach = getReachingStores(f);
//std::set<Instruction*> bReachIn = Utils::mapAtUnsafe(reach, b);
//DEBUG_MSG(" numReachingStores:" << bReachIn.size() << '\n');
//if (bReachIn.size() == 0) {
// return NULL;
//}
//else if (bReachIn.size() == 1) {
// Instruction *storeIn = *(bReachIn.begin());
// assert(storeIn != NULL && "getPreviousStore: NULL reachable store");
// assert(Utils::getStorePtr(storeIn) != NULL
// && "getPreviousStore: storeIn with NULL ptr operand");
// // Check for any killing stores before l
// for (Instruction &bbi : *(l->getParent())) {
// if (&bbi == l) {
// // Reached the target instruction
// break;
// }
// Value *strPtr = Utils::getStorePtr(&bbi);
// if (strPtr != NULL && strPtr == Utils::getStorePtr(storeIn)) {
// // strPtr kills in incoming store
// storeIn = &bbi;
// }
// }
// return storeIn;
//}
//else {
// assert(0 && "getPreviousStore: more than one reaching store");
//}
}
// Return all the store instructions which reach the entry of each basicblock
// in F.
//
// Memoizes the results based on the functon address. So, this assumes the
// function is never modified.
static std::map<BasicBlock *, std::set<Instruction *>> getReachingStores(Function *f) {
static std::map<Function *, std::map<BasicBlock *, std::set<Instruction *>>> memoizer;
DEBUG_MSG("Get reaching stores:" << f->getName() << '\n');
auto memIt = memoizer.find(f);
if (memIt != memoizer.end()) {
return memIt->second;
}
// Defininitions reaching the end of a BB
std::map <BasicBlock *, std::set<Instruction *>> reachOut;
std::map <BasicBlock *, std::set<Instruction *>> reachIn;
// Definitions generated by a basicblock
std::map <BasicBlock *, std::set<Instruction *>> bb2gen;
// Variables overwritten by a basicblock
std::map <BasicBlock *, std::set<Value *>> bb2rem;
// Initialze all the maps
for (BasicBlock &B : *f) {
bb2gen[&B] = getGen(&B);
bb2rem[&B] = getRemVars(&B);
reachOut[&B] = std::set<Instruction*>();
}
bool updated = true;
while (updated) {
updated = false;
for (BasicBlock &B : *f) {
std::set<Instruction *> curGen = Utils::mapAtUnsafe(bb2gen, &B);
std::set<Value *> curRem = Utils::mapAtUnsafe(bb2rem, &B);
// The definitions reaching the input to this block is the union of the
// output of the predecessors. Iterate over all the preds and find this
// union.
std::set<Instruction*> curReach;
for (auto it = pred_begin(&B), et = pred_end(&B); it != et; ++it) {
BasicBlock *pred = *it;
std::set<Instruction *> predReachOut = Utils::mapAtUnsafe(reachOut, pred);
curReach.insert(predReachOut.begin(), predReachOut.end());
}
reachIn[&B] = curReach;
// Remove all those things which were killed
for (Value *v : curRem) {
for (auto it = curReach.begin(), et = curReach.end(); it != et; ++it) {
Instruction *curSt = *it;
Value *stPtr = Utils::getStorePtr(curSt);
assert(stPtr != NULL && "reaching store with NULL pointer arg");
if (v == stPtr) {
curReach.erase(it);
}
}
}
// Add all those things generated
curReach.insert(curGen.begin(), curGen.end());
std::set<Instruction*> oldReach = Utils::mapAtUnsafe(reachOut, &B);
if (curReach.size() > oldReach.size()) {
updated = true;
reachOut[&B] = curReach;
}
}
} // while (updated)
memoizer[f] = reachIn;
return reachIn;
}
// Get those stores created in the B
static std::set<Instruction *> getGen(BasicBlock *B) {
// A map keeping track of which values already have stores associated with
// them.
std::map<Value *, Instruction *> valToSt;
// Assumption: the for loop below goes in order
for (Instruction &i : *B) {
Value *stPtr = Utils::getStorePtr(&i);
if (stPtr != NULL) {
// Only maintain the most recent store to each value
valToSt[stPtr] = &i;
}
}
// Flatten the map to a set
std::set<Instruction*> ret;
for (auto it = valToSt.begin(), et = valToSt.end(); it != et; ++it) {
ret.insert(it->second);
}
return ret;
}
static std::set<Value *> getRemVars(BasicBlock *B) {
std::set<Value *> ret;
for (Instruction &i : *B) {
if (Utils::isSomeStore(&i)) {
Value *p = Utils::getStorePtr(&i);
assert(p != NULL && "getKilledVars: store w/o ptr operand");
ret.insert(p);
}
}
return ret;
}
// Return a read-from rule using the two passed strings. Also returns a query
// if the read is satisfiable (check if not-rf is SAT)
static std::string getReadFromRuleAndQuery(const std::string loader
, const std::string storer) {
std::string ret = "";
ret += "(rule (rf " + loader + " " + storer + "))\n";
ret += "(query (not-rf " + loader + " " + storer + "))";
return ret;
}
// Merge the contents of m1 with m2. If they both have Facts for the same
// LatticeFact, the facts will be joined ("unioned") together
std::map<BasicBlock *, LatticeFact> mergeFactMaps(
const std::map<BasicBlock *, LatticeFact> m1
, const std::map<BasicBlock *, LatticeFact> m2) const {
// First, make return contain everything in m1
std::map<BasicBlock *, LatticeFact> ret = m1;
// Then, merge everything in m2 with the return
for (auto i = m2.begin(), ie = m2.end(); i != ie; ++i) {
BasicBlock *b = i->first;
LatticeFact f = i->second;
auto it = ret.find(b);
if (it == ret.end()) {
// Not found in ret , no need to join
ret.emplace(b, f);
}
else {
// Join the two facts
LatticeFact otherF = it->second;
LatticeFact joinedF = LatticeFact::factJoin(f, otherF);
ret.erase(b);
ret.emplace(b, joinedF);
}
}
return ret;
}
// Helper function for analyzeThreadInterf().
// Collapses the map from functions to maps of storeinsts to facts to a map
// from storeinsts to lattice facts. Then calls the function performing the
// analysis.
// This merge can be done because each store instruction is unique.
std::map<BasicBlock *, LatticeFact> analyzeThreadInterf(
ap_manager_t *man
, ap_environment_t *env
, Function *f
, CallInst *createSite
, const std::map<Instruction *, std::vector<Instruction *>> interfs
, const std::map<Function *, std::map<Instruction *, LatticeFact>> fInterfs
//, std::vector<std::pair<Instruction *, LatticeFact>> &rErrors
, std::set<Instruction *> &rErrors
, std::map<Instruction *, LatticeFact> &reachableStores
, std::map<CallInst *, LatticeFact> &reachThreadCreate
, LatticeFact entryFact
, const std::set<Instruction *> assertSlice
, const std::set<Instruction *> impacted
, const std::set<Instruction *> mayImpact
, const std::map<Value *, std::string> v2n
, z3::context &ctx
, Z3_fixedpoint &zfp
) {
DEBUG_MSG("[DEBUG] Printing interference map\n");
DEBUG(printFuncInterfMap(fInterfs););
std::map<Instruction *, LatticeFact> storeToInterf = flattenReachStores(fInterfs);
return analyzeThreadInterf(man, env, f, createSite, interfs, storeToInterf, rErrors
, reachableStores, reachThreadCreate, entryFact, assertSlice, impacted, mayImpact
, v2n, ctx, zfp);
}
// Given a set of interferences from all threads, i.e., that generated on the
// current iteration of the analysis, return a map from each load instruction
// in the passed function to a vector of StoreInsts it could read from
//
// In other words, map each load instruction within the passed function
// (thread) to every store instruction to the same variable from other
// threads
//
// Note: The LatticeFacts in the inner map of interfs is not actually used
// (i.e., interfs could be a map from functions to lists of storeinsts).
//
// TODO: This cannot handle the same function interfering with itself (i.e.,
// multiple threads executing the same function)
std::map<Instruction *, std::vector<Instruction*>> getInterferingStores(
Function *f
, const std::map<Function *, std::map<Instruction *, LatticeFact>> rStores
, const std::map<Value *, std::string> v2n
) const {
DEBUG_MSG("[DEBUG] Getting interfering stores for function: "
<< f->getName() << '\n');
std::map<Instruction *, std::vector<Instruction*>> ret;
for (auto i = rStores.begin(), ie = rStores.end(); i != ie; ++i) {
Function *otherF = i->first;
if (otherF == f) {
// A function cannot interfere with itself (the only case where this
// can happen is for unbounded thread instances)
continue;
}
std::map<Instruction *, LatticeFact> currStores = i->second;
std::vector<Instruction *> fLoads = getLoads(f);
for (Instruction *l : fLoads) {
// For each load, find all the stores in the current thread and get
// the interfering fact
for (auto j = currStores.begin(), je = currStores.end()
; j != je; ++j) {
Instruction *s = j->first;
if (loadStoreSameVal(s, l)) {
DEBUG_MSG("Found intefering store: " << *s << "\nt" << *l << '\n');
Utils::mapInsertToVector(ret, l, s);
//LatticeFact sFact = j->second;
//mapInsertToVector(ret, l, sFact);
}
}
}
} // for (auto ii = rStores.begin() ... )
return ret;
}
// Given a map of loads to their corresponding interfering stores, remove
// those stores which have lower priority than loads
std::map<Instruction*, std::vector<Instruction *>> filterPriInterfs(
z3::context &ctx
, Z3_fixedpoint &zfp
, std::map<Instruction *, std::vector<Instruction *>> interfs) const {
static std::map<std::pair<Instruction*, Instruction*>, Z3_bool> cache;
DEBUG_MSG("Filtering Priority Interferences\n");
// Map from a Load to the vector of interfering stores
std::map<Instruction *, std::vector<Instruction *>> ret;
#ifdef MK_DEBUG
if (interfs.size() == 0) {
DEBUG_MSG("No interferences to filter\n");
}
#endif
for (auto it = interfs.begin(); it != interfs.end(); ++it) {
Instruction *curL = it->first;
std::vector<Instruction *> stores = it->second;
// Pass only stores which have higher priority
std::vector<Instruction *> lInterfs;
// Issue a query for every load--store pair
for (Instruction *st : stores) {
// Use cached query result if possible
bool queryResult;
auto cacheIt = cache.find(std::make_pair(curL, st));
if (cacheIt == cache.end()) {
DEBUG_MSG("Priority filter cache miss\n");
//errs() << "Priority filter cache miss\n";
// never seen this pair before
queryResult = queryPri(ctx, zfp, curL, st);
cache[std::make_pair(curL, st)] = queryResult;
} else {
DEBUG_MSG("Priority filter cache hit\n");
//errs() << "Priority filter cache hit\n";
queryResult = cacheIt->second;
}
totalPairs ++;
if (queryResult) {
// if query is true than it is valid pair
lInterfs.push_back(st);
} else {
filteredPairs ++;
/*
errs() << "Infeasible load--store from MHB\n";
errs() << "Load: " << *curL << '\n';
errs() << "Load Function: " << curL->getParent()->getParent()->getName() << '\n';
errs() << "Store: " << *st << '\n';
errs() << "Store Function: " << st->getParent()->getParent()->getName() << '\n';
*/
DEBUG_MSG("Infeasible load--store from Prioirity\n");
DEBUG_MSG("Load: " << *curL << '\n');
DEBUG_MSG("Load Function: " << curL->getParent()->getParent()->getName() << '\n');
DEBUG_MSG("Store: " << *st << '\n');
DEBUG_MSG("Store Function: " << st->getParent()->getParent()->getName() << '\n');
}
}
assert(lInterfs.size() <= stores.size());
#ifdef MK_DEBUG
if (lInterfs.size() < stores.size()) {
DEBUG_MSG("Pruned interferences via priority: "
<< stores.size() - lInterfs.size() << '\n');
} else {
DEBUG_MSG("No interferences pruned via priority\n");
}
#endif
ret[curL] = lInterfs;
}
return ret;
}
// Given a map of loads to their corresponding interfering stores, remove
// those stores which must-happen-after the load. These can be removed since
// the effect of the store cannot travel backwards in time. These removals
// are valid over all interference permutations
std::map<Instruction *, std::vector<Instruction *>> filterMHBInterfs(
z3::context &ctx
, Z3_fixedpoint &zfp
, std::map<Instruction *, std::vector<Instruction *>> interfs) const {
// Only need to ever check MHB once per load-store pair
static std::map<std::pair<Instruction*, Instruction*>, Z3_bool> cache;
DEBUG_MSG("Filtering MHB Interferences\n");
// Map from a Load to the vector of interfering stores
std::map<Instruction *, std::vector<Instruction *>> ret;
#ifdef MK_DEBUG
if (interfs.size() == 0) {
DEBUG_MSG("No interferences to filter\n");
}
#endif
for (auto it = interfs.begin(); it != interfs.end(); ++it) {
Instruction *curL = it->first;
std::vector<Instruction *> stores = it->second;
// Interfering stores which do not violate MHB. Will be populated in the
// for-loop below
std::vector<Instruction *> lInterfs;
// Issue a query for every load--store pair
for (Instruction *st : stores) {
// Use cached query result if possible
Z3_bool queryResult;
auto cacheIt = cache.find(std::make_pair(curL, st));
if (cacheIt == cache.end()) {
DEBUG_MSG("MHB filter cache miss\n");
// never seen this pair before
queryResult = queryMHB(ctx, zfp, curL, st);
cache[std::make_pair(curL, st)] = queryResult;
}
else {
DEBUG_MSG("MHB filter cache hit\n");
queryResult = cacheIt->second;
}
if (queryResult == Z3_L_FALSE || queryResult == Z3_L_UNDEF) {
// either l may-not-happen before st, or unknown. In both cases,
// conservatively assume that the load can read from the store
lInterfs.push_back(st);
}
else {
DEBUG_MSG("Infeasible load--store from MHB\n");
DEBUG_MSG("Load: " << *curL << '\n');
DEBUG_MSG("Load Function: " << curL->getParent()->getParent()->getName() << '\n');
DEBUG_MSG("Store: " << *st << '\n');
DEBUG_MSG("Store Function: " << st->getParent()->getParent()->getName() << '\n');
}
}
assert(lInterfs.size() <= stores.size());
#ifdef MK_DEBUG
if (lInterfs.size() < stores.size()) {
DEBUG_MSG("Pruned interferences via MHB: "
<< stores.size() - lInterfs.size() << '\n');
}
else {
DEBUG_MSG("No interferences pruned via MHB\n");
}
#endif
ret[curL] = lInterfs;
}
return ret;
}
// Combine the inner map of the passed across all functions.
std::map<Instruction *, LatticeFact> flattenReachStores(
const std::map<Function *, std::map<Instruction *, LatticeFact>> reachStrs
) {
std::map<Instruction *, LatticeFact> facts;
for (auto i = reachStrs.begin(), ie = reachStrs.end(); i != ie; ++i) {
std::map<Instruction *, LatticeFact> cur = i->second;
for (auto j = cur.begin(), je = cur.end(); j != je; ++j) {
Instruction *s = j->first;
// Assumption: Store instructions are unique
assert(facts.find(s) == facts.end() && "duplicate store");
facts.emplace(s, j->second);
}
}
return facts;
}
// Return true if every fact for every storeinst in new is contained in old
bool stableStores(
const std::map<Function *, std::map<Instruction *, LatticeFact>> oldI
, std::map<Function *, std::map<Instruction *, LatticeFact>> newI) {
// Since the store instructions are unique (not shared across threads).
// we can flatten the results and just work on the combined inner maps
std::map<Instruction *, LatticeFact> flatOld = flattenReachStores(oldI);
std::map<Instruction *, LatticeFact> flatNew = flattenReachStores(newI);
// Check if every fact in new is in old
for (auto ni = flatNew.begin(), ne = flatNew.end(); ni != ne; ++ni) {
Instruction *s = ni->first;
LatticeFact newF = ni->second;
auto oi = flatOld.find(s);
if (oi == flatOld.end()) {
// This means the store was not even reachable in the prior execution
// (but, it was reachable in this execution). So, we can stop now since
// we have a completely new fact created in new
assert(!newF.isBottom() && "reachable bottom fact");
DEBUG_MSG("stableStores(): new fact not in old, returning false\n");
return false;
}
// Compare the old and new facts
else {
LatticeFact oldF = oi->second;
// If the new fact is definitely larger (strictly greater than) than
// the old one, we can stop
if (!LatticeFact::areValsEq(newF, oldF)
&& LatticeFact::areValsGEq(newF, oldF)) {
return false;
}
}
}
// At this point, we know none of the new facts are *definitively* larger
// than the old facts. areValsGEq will return false either in the case of
// "no" or "don't know"
// TODO: What to do in this case? return true?
return true;
}
// Convience wrapper to analyze a function in the presense of no inteferences
std::map<BasicBlock *, LatticeFact> analyzeFuncNoInterf(ap_manager_t *man
, ap_environment_t *env
//, std::vector<std::pair<Instruction *, LatticeFact>> &rErrors
, std::set<Instruction *> &rErrors
, std::map<Instruction *, LatticeFact> &reachableStores
, std::map<CallInst *, LatticeFact> &reachThreadCreate
, LatticeFact entryFact
, const std::set<Instruction *> assertSlice
, const std::set<Instruction *> impacted
, const std::set<Instruction *> mayImpact
, const std::map<Value *, std::string> &valToName
, Function *f) const {
std::map<Instruction *, LatticeFact> empty;
return analyzeFunc(man, env, empty, rErrors, reachableStores
, reachThreadCreate, assertSlice, impacted, mayImpact
, valToName, entryFact, f, false);
}
// Analyze the passed function. Returns a map from each basicblock in the
// function to the stabalized facts at the begining of the block.
//
// The passed manager and environment are assumed to be initialized. The
// environment should at least include every variable in the passed map from
// LLVM Values to Apron names.
//
// The passed vector, rErrors, will be updated with any reachable errors
// states and the fact reaching the statement.
//
// If mergeInterfs is true, then the analysis will simultaneously consider
// both any interfering memory state and the state within the thread. This
// means, on any load of `x` both the value within the thread for `x` and the
// value of `x` in the interference are loaded.
std::map<BasicBlock *, LatticeFact> analyzeFunc(ap_manager_t *man
, ap_environment_t *env
, const std::map<Instruction *, LatticeFact> interf
//, std::vector<std::pair<Instruction*, LatticeFact>> &rErrors
, std::set<Instruction*> &rErrors
, std::map<Instruction *, LatticeFact> &reachableStores
, std::map<CallInst *, LatticeFact> &reachThreadCreate
, const std::set<Instruction *> assertSlice
, const std::set<Instruction *> impacted
, const std::set<Instruction *> mayImpact
, const std::map<Value *, std::string> &valToName
, LatticeFact entryFact
, Function *f
, bool mergeInterfs) const {
assert(f && "analyzeFunc: null passed");
if (f->begin() == f->end()) {
errs() << "[ERROR] function has no body\n";
exit(EXIT_FAILURE);
}
// The worklist. It is a map from a basicblock to the new facts reaching
// the block. A map is used so that if multiple predecessors of a
// basicblock add items to the worklist they can be met. In this way, the
// predecessors of a BasicBlock do not need to be explicitly found.
std::map<BasicBlock *, LatticeFact> worklist;
// Bottom and top facts used in initialization
ap_abstract1_t factBot = ap_abstract1_bottom(man, env);
ap_abstract1_t factTop = ap_abstract1_top(man, env);
LatticeFact latBot = LatticeFact(&factBot);
LatticeFact latTop = LatticeFact(&factTop);
// The current state of the analysis.
// This is the facts at the begining of each basicblock.
// If a key is not in the map it is assumed to be an error.
// The initial state is passed by the user
std::map<BasicBlock *, LatticeFact> analState = initBBs(latBot, f);
//Module *M = f->getParent();
//LatticeFact initFact = getInitState(M, latTop, valToName);
// get the first basic block
BasicBlock &firstBb = *(f->begin());
worklist.emplace(&firstBb, entryFact);
while (worklist.size()) {
try {
DEBUG_MSG("New worklist iteration, size: "
<< worklist.size() << '\n');
// Iterator to first item in the list
auto it = worklist.begin();
auto cur = *it;
worklist.erase(it);
BasicBlock *curBb = cur.first;
LatticeFact newFact = cur.second;
DEBUG_MSG("[DEBUG] analyzing block: " << *curBb << '\n');
LatticeFact oldFact = analState.at(curBb);
DEBUG_MSG(" Incomming Fact: ");
DEBUG(newFact.fprint(stderr););
DEBUG_MSG(" Old Fact: ");
DEBUG(oldFact.fprint(stderr););
DEBUG_MSG(" new leq old? " << newFact.leq(oldFact) << '\n');
// If the new fact is the same size or smaller than the old one
// then we can stop.
// It should never really be smaller (assuming the transfer
// functions are monotonicly increasing).
if (newFact.leq(oldFact)) {
continue;
}
// If the new fact is bigger, save it in the analysis state
// Note: the end fact of each block is not saved
// (but, it can be recovered by just running the
// transfer function over the input fact)
analState.erase(curBb);
analState.emplace(curBb, newFact);
std::vector<std::pair<BasicBlock*, LatticeFact> > outFacts
= BBOps::run_transfer_funcs(curBb, newFact, interf, rErrors
, reachableStores, reachThreadCreate, assertSlice
, impacted, mayImpact, valToName, noCombinsG);
// Combine the outfacts of the just analyzed block with any in the
// worklist
//worklist = merge_worklist(worklist, outFacts);
merge_worklist(&worklist, outFacts);
}
catch (const std::out_of_range &oor) {
errs() << "[ERROR] item not found in analysis state\n";
assert(0 && "see above");
exit(EXIT_FAILURE);
}
}
// Cleanup the initial abstract value
ap_abstract1_clear(man, &factBot);
ap_abstract1_clear(man, &factTop);
return analState;
}
// Add the "dom" relation and it's transitive property.
void addDomRel(z3::context &ctx, Z3_fixedpoint &zfp) {
// Create dominance relation
z3::func_decl domDecl = getDomFuncDecl(ctx);
Z3_fixedpoint_register_relation(ctx, zfp, domDecl);
// Create post-dominance relation
z3::func_decl postDomDecl = getPostDomFuncDecl(ctx);
Z3_fixedpoint_register_relation(ctx, zfp, postDomDecl);
addTransRuleBVBV(ctx, zfp, domDecl, Z3_BV_SIZE);
addTransRuleBVBV(ctx, zfp, postDomDecl, Z3_BV_SIZE);
}
// And relations indicating a certain instruction is either a load or store
void addLoadStoreRels(z3::context &ctx, Z3_fixedpoint &zfp) {
// Store relation: (st s v): store s loads value v
z3::func_decl stDecl = getStFuncDecl(ctx);
Z3_fixedpoint_register_relation(ctx, zfp, stDecl);
// Load relation
z3::func_decl ldDecl = getLdFuncDecl(ctx);
Z3_fixedpoint_register_relation(ctx, zfp, ldDecl);
}
// Add MHB relation
void addMHBRel(z3::context &ctx, Z3_fixedpoint &zfp) {
z3::func_decl mhbDecl = getMHBFuncDecl(ctx);
Z3_fixedpoint_register_relation(ctx, zfp, mhbDecl);
}
// Add fence relation
void addFenceRel(z3::context &ctx, Z3_fixedpoint &zfp) {
z3::func_decl fenceDecl = getFenceFuncDecl(ctx);
Z3_fixedpoint_register_relation(ctx, zfp, fenceDecl);
}
void addLwSyncRel(z3::context &ctx, Z3_fixedpoint &zfp) {
z3::func_decl fenceDecl = getFenceFuncDecl(ctx);
Z3_fixedpoint_register_relation(ctx, zfp, fenceDecl);
}
// Add not-reach relation
void addNotReachRel(z3::context &ctx, Z3_fixedpoint &zfp) {
z3::func_decl nreachRel = getNotReachFuncDecl(ctx);
Z3_fixedpoint_register_relation(ctx, zfp, nreachRel);
}
void addReadsFromRel(z3::context &ctx, Z3_fixedpoint &zfp) {
z3::func_decl rf = getReadsFromFuncDecl(ctx);
Z3_fixedpoint_register_relation(ctx, zfp, rf);
}
void addNoReorderRel(z3::context &ctx, Z3_fixedpoint &zfp) {
z3::func_decl no = getNoReorderFuncDecl(ctx);
Z3_fixedpoint_register_relation(ctx, zfp, no);
}
void addNotReadsFromRel(z3::context &ctx, Z3_fixedpoint &zfp) {
z3::func_decl nrf = getNotReadsFromFuncDecl(ctx);
Z3_fixedpoint_register_relation(ctx, zfp, nrf);
}
// Add MHB edges from creation site to child
//
// Currently, this requires that all the pthread_create sites have explicit
// function arguments.
void addCreateFacts(Module &M, z3::context &ctx, Z3_fixedpoint &zfp) {
for (Function &F : M) {
for (BasicBlock &B : F) {
for (Instruction &I : B) {
CallInst *ci = dyn_cast<CallInst>(&I);
if (ci == NULL) {
continue;
}
Function *called = ci->getCalledFunction();
if (called->getName() != "pthread_create") {
continue;
}
// Found pthread_create. The 2nd argument (zero indexed) is the
// function being called
Value *v = ci->getArgOperand(2);
if (Function *tFunc = dyn_cast<Function>(v)) {
// Make sure the function has a body
if (tFunc->empty()) {
errs() << "[WARNING] thread function without body\n";
continue;
}
// The pthread_create site must happen before the first instruction
// in the function
//addMHBFact(ctx, zfp, ci, &tFunc->front().front());
addMHBFact(ctx, zfp, ci
, getFirstLoadStoreCallTerm(&tFunc->front()));
addCreateStoreLoadFacts(ctx, zfp, ci, tFunc);
addThreadLocalNotRead(ctx, zfp, ci, tFunc);
}
else {
errs() << "[ERROR] pthread_create with non function 2nd arg\n";
errs() << *v << '\n';
exit(EXIT_FAILURE);
}
} // for (Instruction &I : B)
} // for (BasicBlock &B : F)
} // for (Function &F : M)
}
// Any store instruction which must ocurr before a thread's creation cannot
// be read by this thread.
//
// If the store before the thread's creation can propagate to the thread,
// then its value will be in the initial environment of the thread
//
// ci is assumed to be the pthread_create call creating tFunc
void addCreateStoreLoadFacts(z3::context &ctx, Z3_fixedpoint &zfp
, CallInst *ci, Function *tFunc) {
std::vector<Instruction*> lds = getLoads(tFunc);
for (Instruction *l : lds) {
addStoreCreateLoadFact(ctx, zfp, ci, l);
}
}
// Add: (=> (and (is-store s _) (mhb s ci)) (nrf s l))
void addStoreCreateLoadFact(z3::context &ctx, Z3_fixedpoint &zfp
, CallInst *ci, Instruction *l) {
assert(Utils::isSomeLoad(l));
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
z3::expr s = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort));
z3::expr v = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort));
z3::expr ciExp = getValueBVID(ctx, ci);
z3::expr lExp = getValueBVID(ctx, l);
z3::expr args[2] = {s, v};
z3::expr isStoreS = getStFuncDecl(ctx)(2, args);
args[0] = s;
args[1] = ciExp;
z3::expr mhbSCi = getMHBFuncDecl(ctx)(2, args);
args[0] = s;
args[1] = lExp;
z3::expr nrfSL = getNotReadsFromFuncDecl(ctx)(2, args);
// (and (is-store s v) (mhb s ci))
z3::expr andSMHB = isStoreS && mhbSCi;
Z3_fixedpoint_add_rule(ctx, zfp, z3::implies(andSMHB, nrfSL), NULL);
}
// Add the "pri" and "higher" relation and it's transitive property
void addPriHighRel(z3::context &ctx, Z3_fixedpoint &zfp) {
// Create (function-decl pri (number))
z3::func_decl priDecl = getPriFuncDecl(ctx);
Z3_fixedpoint_register_relation(ctx, zfp, priDecl);
// add priority related rules
addPriRule(ctx, zfp, priDecl, Z3_BV_SIZE);
// Create (function-decl higher (number number))
z3::func_decl highDecl = getHighFuncDecl(ctx);
Z3_fixedpoint_register_relation(ctx, zfp, highDecl);
// add higher related rules
addHighRule(ctx, zfp, priDecl, highDecl, Z3_BV_SIZE);
// add higher transitive rules
addTransRuleBVBV(ctx, zfp, highDecl, Z3_BV_SIZE);
// Create (function-decl lineHigh (lineNum lineNum))
z3::func_decl lineHighDecl = getLineHighFuncDecl(ctx);
Z3_fixedpoint_register_relation(ctx, zfp, lineHighDecl);
// Create (function-decl linePri (lineNum Priority))
z3::func_decl linePriDecl = getLinePriFuncDecl(ctx);
Z3_fixedpoint_register_relation(ctx, zfp, linePriDecl);
// Build rules for linehigh inference
z3::func_decl ldDecl = getLdFuncDecl(ctx);
z3::func_decl stDecl = getStFuncDecl(ctx);
addLineHighRule(ctx, zfp, ldDecl, stDecl, highDecl, linePriDecl, lineHighDecl, Z3_BV_SIZE);
// Create (function-decl compLd (lineNum))
z3::func_decl compLdDecl = getCompLdFuncDecl(ctx);
Z3_fixedpoint_register_relation(ctx, zfp, compLdDecl);
// Create (function-decl nonLastSt (lineNum))
z3::func_decl nonLastStDecl = getNonLastStFuncDecl(ctx);
Z3_fixedpoint_register_relation(ctx, zfp, nonLastStDecl);
// Build rules for compLd and nonLastSt inferences
z3::func_decl domDecl = getDomFuncDecl(ctx);
z3::func_decl postDomDecl = getPostDomFuncDecl(ctx);
addCombRule(ctx
, zfp
, ldDecl
, stDecl
, domDecl
, postDomDecl
, compLdDecl
, nonLastStDecl
, Z3_BV_SIZE);
}
// Update the context and fixedpoint to contain dominance relation, rules,
// and facts, and also relations and facts about instructions being
// loads/stores
void addDomLoadStoreFacts(std::set<Function*> threadFuncs
, z3::context &ctx
, Z3_fixedpoint &zfp) {
addDomRel(ctx, zfp);
addLoadStoreRels(ctx, zfp);
if (usePriG) {
addPriHighRel(ctx, zfp);
}
// read priority info file and save priority information
std::map<std::string, std::string> priorityInfo;
if (usePriG) {
std::ifstream file("priority.info");
std::string line;
while(std::getline(file, line)) {
std::stringstream linestream(line);
std::string data;
std::string val1;
// read up-to the first tab (discard tab).
std::getline(linestream, data, ':');
// Read the integers using the operator >>
linestream >> val1;
//errs() << data << ":::" << val1 << "\n";
priorityInfo.insert(
std::pair<std::string, std::string> (data, val1));
}
}
for (Function *f : threadFuncs) {
unsigned priority;
if (usePriG) {
// get priority information
std::string name = f->getName();
//errs() << "function: " << name << "\n";
if (name.compare("main") == 0) {
// for the main function priority is just 1
priority = 1;
} else {
priority =
std::stoi(priorityInfo.find(f->getName().str())->second);
}
}
//DominatorTree &dt = getAnalysis<DominatorTreeWrapperPass>(*f).getDomTree();
DominatorTree dt = DominatorTree(*f);
PostDominatorTree pdt;
pdt.runOnFunction(*f);
// The first instruction of the thread may have a happens-before edge
// from the parent-thread. So, connect this first instruction (which may
// not be a load/store) to a load/store/terminator so that transitive
// orderings can be calculated
/*
Instruction *first = &f->front().front();
Instruction *lst = getFirstLoadStoreCallTerm(&f->front());
if (first != lst) {
addDomFact(ctx, zfp, first, lst);
addPostDomFact(ctx, zfp, lst, first);
}
*/
for (BasicBlock &b : *f) {
// add internal dom facts of read/write/call
// inside of each basic block
addInternalDomAndPostDomFacts(&b, ctx, zfp);
if (usePriG) {
addLoadStoreFacts(&b, ctx, zfp, priority);
} else {
addLoadStoreFacts(&b, ctx, zfp);
}
// for dominator tree
DomTreeNodeBase<BasicBlock> *bbNode = dt.getNode(&b);
if (bbNode != NULL) {
// For the dom children of `b`,
// connect the terminator of `b` to the
// first relevant (load, store, terminator) instruction
// in the child
Instruction *from = b.getTerminator();
const std::vector<DomTreeNodeBase<BasicBlock> *> &children
= bbNode->getChildren();
for (size_t i = 0; i < children.size(); ++i) {
BasicBlock *c = children[i]->getBlock();
// check assertion
Instruction *t = &(c->front());
if (CallInst *ci = dyn_cast<CallInst>(t)) {
// Chungha: This is a modification to support
// post-dominance relation for assert.
// Since assert makes branches so that the instruction
// after the branch can't post-dominate the instruction
// before the branch. Therefore, I forcely insert it.
if (ci->getCalledFunction()->getName()
== "__assert_fail") {
BasicBlock *c2 = children[i+1]->getBlock();
Instruction *postFrom
= getFirstLoadStoreCallTerm(c2);
/*
errs() << "PostFrom!!!\n";
errs() << *postFrom;
errs() << "PostTo!!!\n";
errs() << *from;
errs() << "\n";
*/
addPostDomFact(ctx, zfp, postFrom, from);
}
}
Instruction *to = getFirstLoadStoreCallTerm(c);
addDomFact(ctx, zfp, from, to);
}
}
// for post dominator tree
DomTreeNodeBase<BasicBlock> *btNode = pdt.getNode(&b);
if (btNode != NULL) {
// For the post dom children of `b`
// connect the first call/read/write of `b` to the
// last instruction in the child
Instruction *from = getFirstLoadStoreCallTerm(&b);
const std::vector<DomTreeNodeBase<BasicBlock> *> &children
= btNode->getChildren();
for (size_t i = 0; i < children.size(); ++i) {
BasicBlock *c = children[i]->getBlock();
//Instruction *to = getFirstLoadStoreCallTerm(c);
Instruction *to = c->getTerminator();
addPostDomFact(ctx, zfp, from, to);
}
}
} // for (BasicBlock &b : *f)
} // for (Function f : threadFuncs)
}
// Validate the set parameters. This will crash the program on errors
void validateParams(z3::context &ctx, Z3_fixedpoint &zfp, z3::params ¶ms) {
DEBUG_MSG("checking parameters\n");
Z3_param_descrs p_desc = Z3_fixedpoint_get_param_descrs(ctx, zfp);
Z3_param_descrs_inc_ref(ctx, p_desc);
Z3_params_validate(ctx, params, p_desc);
try {
ctx.check_error();
}
catch (z3::exception ex) {
errs() << "[ERROR] Parameter error: " << ex.msg() << '\n';
Z3_param_descrs_dec_ref(ctx, p_desc);
exit(EXIT_FAILURE);
}
Z3_param_descrs_dec_ref(ctx, p_desc);
}
// Add facts about fence instructions in the program. This also will add a
// definition of the fence relation (see addFenceRel()).
void addFenceFacts(std::set<Function*> threadFuncs
, z3::context &ctx
, Z3_fixedpoint &zfp) {
addFenceRel(ctx, zfp);
addLwSyncRel(ctx, zfp);
for (Function *f : threadFuncs) {
for (BasicBlock &b : *f) {
for (Instruction &i : b) {
if (isFence(&i)) {
addFenceFact(ctx, zfp, &i);
}
if (isLwSync(&i)) {
// TODO: how to handle lwsync
//addLwSyncFact(ctx, zfp, &i);
addFenceFact(ctx, zfp, &i);
}
}
}
}
}
// Return true if the passed instruction is a POWER lwsync
//
// An lwsync preserves everything but write--read order
bool isLwSync(Instruction *i) {
if (CallInst *ci = dyn_cast<CallInst>(i)) {
// TSO/PSO fence
if (ci->getCalledFunction()->getName() == "MLWSYNC") {
return true;
}
}
return false;
}
// Return true if the passed instruction operates as a fence or is an
// explicit fence. The programmer can add in explicit fences via a call to a
// function named MFENCE.
bool isFence(Instruction *i) {
if (CallInst *ci = dyn_cast<CallInst>(i)) {
// TSO/PSO fence
if (ci->getCalledFunction()->getName() == "MFENCE") {
return true;
}
// PPC/ARM full fence
if (ci->getCalledFunction()->getName() == "MSYNC") {
return true;
}
else {
// No other call instructions are treated as fences
return false;
}
}
else if (isa<AtomicRMWInst>(i)) {
return true;
}
else if (isa<AtomicCmpXchgInst>(i)) {
return true;
}
else {
// TODO: probably some other instructions to handle as fences
return false;
}
}
bool runOnModule(Module &M) {
manG = Utils::getManager();
ap_manager_set_abort_if_exception(manG, AP_EXC_TIMEOUT, true);
ap_manager_set_abort_if_exception(manG, AP_EXC_OUT_OF_SPACE, true);
ap_manager_set_abort_if_exception(manG, AP_EXC_OVERFLOW, true);
ap_manager_set_abort_if_exception(manG, AP_EXC_INVALID_ARGUMENT, true);
ap_manager_set_abort_if_exception(manG, AP_EXC_NOT_IMPLEMENTED, true);
ap_manager_set_abort_if_exception(manG, AP_EXC_SIZE, true);
// Maps from a Value to a name and vice-versa.
//
// These are used since Apron requires variables to have names
std::map<Value *, std::string> valToName;
std::map<std::string, Value *> nameToVal;
DEBUG_MSG("[DEBUG] Starting WorklistAI\n");
checkCommandLineArgs();
// Initialize fixpoint solver
z3::config cfg;
//Z3_set_param_value(cfg, "DL_DEFAULT_RELATION", "smt_relation2");
z3::context ctx(cfg);
Z3_fixedpoint zfp = Z3_mk_fixedpoint(ctx);
Z3_fixedpoint_inc_ref(ctx, zfp);
z3::params params(ctx);
params.set("engine", ctx.str_symbol("datalog"));
params.set("datalog.default_table", ctx.str_symbol("hashtable"));
params.set("datalog.magic_sets_for_queries", true);
DEBUG_MSG("params:\n" << Z3_fixedpoint_get_help(ctx, zfp));
DEBUG_MSG("Set Parameters:\n");
DEBUG_MSG(Z3_params_to_string(ctx, params) << '\n');
validateParams(ctx, zfp, params);
ap_manager_t* man = Utils::getManager();
ap_environment_t *env = createEnvironment(valToName, nameToVal, M);
DEBUG(printValToNameStderr(valToName););
// Try to find the main function
Function *main = getMainFuncOrNULL(M);
if (main == NULL) {
// TODO: the user should be able to specify the entry of the analysis
errs() << "[ERROR] main function not found\n";
exit(EXIT_FAILURE);
}
// try to find any threads
std::set<Function *> threadFuncs = getThreads(M);
std::vector<CallInst *> threadSites = getThreadCreate(M);
// If there are no threads, then this is a single threaded analysis
bool noThreads = threadSites.size() == 0;
//threadFuncs.insert(main);
// This also addes priority and higher information
addDomLoadStoreFacts(threadFuncs, ctx, zfp);
addMHBRel(ctx, zfp);
if (useConstraintsG || filterMHB) {
DEBUG_MSG("adding constraints: number of threads: "
<< threadFuncs.size() << '\n');
if (tsoConstrG || psoConstrG || rmoConstrG) {
addFenceFacts(threadFuncs, ctx, zfp);
}
addCreateFacts(M, ctx, zfp);
addJoinFacts(M, ctx, zfp);
addNotReachableFacts(M, ctx, zfp);
if (tsoConstrG) {
//addTSOPruningRules(ctx, zfp);
addNoReorderRules(ctx, zfp);
addTSOReorderRules(ctx, zfp);
// TODO: is reads-from MHB?
addReadsFromIsMHB(ctx, zfp);
}
else if (psoConstrG) {
//addPSOPruningRules(ctx, zfp);
addNoReorderRules(ctx, zfp);
addPSOReorderRules(ctx, zfp);
// TODO: is reads-from MHB?
addReadsFromIsMHB(ctx, zfp);
}
else if (rmoConstrG) {
addNoReorderRules(ctx, zfp);
addRMOReorderRules(ctx, zfp);
// TODO: is reads-from MHB?
addReadsFromIsMHB(ctx, zfp);
}
else {
addPruningRules(ctx, zfp);
// TODO: is reads-from MHB?
addReadsFromIsMHB(ctx, zfp);
//addNoReorderRules(ctx, zfp);
//addSCReorderRules(ctx, zfp);
}
}
std::string rules = Z3_fixedpoint_to_string(ctx, zfp, 0, NULL);
errs() << "Rules: " << rules << '\n';
DEBUG_MSG("Rules: " << rules << '\n';);
// This is kind of a hack: NULL in threadSites indicates main (there is not
// CallSite for main)
threadSites.push_back(NULL);
// When using constraints, we start the analysis of the main thread and
// check the reachability of any thread creation sites. If any are
// reachable, then they are subsequently analyzed.
// This is a little bit roundabout since we are clearing the vectors.
if (dynInitG) {
threadFuncs.clear();
threadSites.clear();
threadFuncs.insert(main);
threadSites.push_back(NULL);
}
std::set<Instruction *> assertSlice = getAssertSliceInvIfEnabled(M);
std::set<Instruction *> impacted = getImpactedIfEnabled(M);
std::set<Instruction *> mayImpact = getMayImpactIfEnabled(M);
// Vector containing reachable error states
//std::vector<std::pair<Instruction *, LatticeFact>> rErrors;
std::set<Instruction *> rErrors;
// Repeatedly analyze the main function and any threads until the
// interferences (facts at stores in threads) stabalize
std::map<Function *, std::map<Instruction *, LatticeFact>> allReachStores;
// Map from a Function (thread) to a map from each of its Loads to the
// vector of all interfering store instructions from other threads.
std::map<Function *, std::map<Instruction *, std::vector<Instruction *>>> interfs;
std::map<Function *, std::map<BasicBlock *, LatticeFact>> threadRes;
// The inital state of the thread being analyzed
ap_abstract1_t factTop = ap_abstract1_top(man, env);
LatticeFact latTop = LatticeFact(&factTop);
LatticeFact progInitState = getInitState(&M, latTop, valToName);
ap_abstract1_clear(man, &factTop);
// A map saving the entry fact for a thread. This is only used when
// dynamic thread initialization in enabled
std::map<CallInst *, LatticeFact> threadEntryFacts;
bool stable;
size_t iter = 1;
do {
errs() << "Interference Iteration: " << iter << '\n';
// The reachable stores for this round of the analysis.
// We save this in a new map so we can compare it with
// the results of the previous analysis (allReachStores).
// If the facts stabalize, then we can stop.
std::map<Function *, std::map<Instruction *, LatticeFact>> newReachStores = allReachStores;
// This deque contains the thread functions which still need to be
// processed for this interference iteration. A deque is used because
// when constraints are used the threads are processed as they are
// reached. In other words, the threads to processed is increasing if a
// new thread creation site is reached
std::deque<CallInst *> threadsToProcess;
// Note: when dynInitG is enabled then threadSites only contains main.
// This means that each iteration starts analyzing main
// and then analyzes the children of main recursively.
threadsToProcess.insert(threadsToProcess.end(), threadSites.begin()
, threadSites.end());
assert(threadsToProcess.size() == threadSites.size());
size_t tCount = 0; // only here for output
while (threadsToProcess.size()) {
errs() << "Analyzing thread: " << tCount++ << '\n';
// ci is the CallInst of the pthread_create() creating the thread.
CallInst *ci = threadsToProcess.front();
threadsToProcess.pop_front();
Function *f = NULL;
if (ci == NULL) {
// NULL is a special callsite indicating main
f = main;
} else {
f = getPThreadThreadFunc(ci);
}
LatticeFact entryFact = progInitState;
#if 0
if (dynInitG) {
// If we are dynamically calculating the entry state of
// each thread, then we retrieve the entry fact here.
// Otherwise, the entry fact is simply initialized to be
// the initial state of the program
if (ci != NULL) {
entryFact = Utils::mapAtUnsafe(threadEntryFacts, ci);
}
}
#endif
// Subset of all interferences.
// Only those which could affect this thread.
std::map<Instruction *, std::vector<Instruction *>> curFInterf = interfs[f];
curFInterf = filterMHBInterfs(ctx, zfp, curFInterf);
if (usePriG) {
curFInterf = filterPriInterfs(ctx, zfp, curFInterf);
}
// A map of reachable thread creations in `f`.
// This is used to determine other threads which should be analyzed
std::map<CallInst *, LatticeFact> reachThreadCreate;
// Analyze function in the presense of interferences
std::map<Instruction *, LatticeFact> newStores;
std::map<BasicBlock *, LatticeFact> res = analyzeThreadInterf(man
, env
, f
, ci
, curFInterf
, newReachStores
, rErrors
, newStores
, reachThreadCreate
, entryFact
, assertSlice
, impacted
, mayImpact
, valToName
, ctx
, zfp);
threadRes[f] = res;
// Save the reachable stores for this iteration. We can erase all the
// old ones since the reachable stores are monotonic (on iteration i+1
// we at least reach all the stores of iteration i)
auto fit = newReachStores.find(f);
if (fit != newReachStores.end()) {
newReachStores.erase(fit);
}
newReachStores.emplace(f, newStores);
#if 0
if (dynInitG) {
// When calculating the initial state dynamically, we are calculating
// the threads to explore on-the-fly. Any reachable pthread_create
// call at this point needs to be analyzed during this iteration.
// Note: the facts at each callinstruction are "forgotten" on each
// iteration. However, the facts at the callsites are increasing
// (potentially) since the interferences on the stores are
// increasing.
for (auto rci = reachThreadCreate.begin()
, rce = reachThreadCreate.end(); rci != rce; ++ rci) {
// Get the entry fact for the thread
CallInst *curCall = rci->first;
LatticeFact callFact = rci->second;
Function *thrdFunc = getPThreadThreadFunc(curCall);
DEBUG_MSG("[DEBUG] Found new thread: " << thrdFunc->getName()
<< '\n');
// This function is now saved as being one of the threads we are
// analyzing
threadFuncs.insert(thrdFunc);
// Add the most recent fact to the entry point. Note: we do not
// support threads executing the same function
auto old = threadEntryFacts.find(curCall);
if (old != threadEntryFacts.end()) {
threadEntryFacts.erase(old);
}
threadEntryFacts.emplace(curCall, callFact);
// Add the thread to be processed
threadsToProcess.push_back(curCall);
}
}
#endif
}
// If there are no threads, even if the main() thread has interferences
// they will not do anything since main does not interfer with itself
// (the analysis will finish after a useless 2nd iteration)
if (noThreads) {
break;
}
stable = stableStores(allReachStores, newReachStores);
DEBUG_MSG("Iteration " << iter << ":\n");
DEBUG_MSG("Previous reachable stores:\n");
DEBUG(printStoreFacts(allReachStores););
DEBUG_MSG("\nNew reachable stores:\n");
DEBUG(printStoreFacts(newReachStores););
// Setup the data for the next iteration. This only needs to be done if
// the results have not yet stabalized.
// We calculate the new interferences and save the reachable facts at
// store instructions
if (!stable) {
// Calculate the interferences to be used for each thread
// to be used in the next round of the analysis.
// This uses the reachable stores caluclated for each thread
// in the previous for-loop.
for (Function *f : threadFuncs) {
std::map<Instruction *, std::vector<Instruction *>> interfStores;
interfStores = getInterferingStores(f, newReachStores, valToName);
// Remove those loads which are not the slice, those can read
// arbitrary values without affecting property reachability
if (assertSliceG || impactG) {
for (auto it = interfStores.begin(), ie = interfStores.end()
; it != ie; ++it) {
// assertSlice contains those statements *not*
// on the slice.
// So, if it is found in the assertSlice structure
// then the statement must not be on the slice.
// So, its interference can be removed.
// TODO: for some reason performing this removal
// causes some false alarms??
// These should be mutually exclusive so as
// not to double erase
if (assertSliceG && assertSlice.count(it->first)) {
interfStores.erase(it);
}
else if (impactG && !mayImpact.count(it->first) && !impacted.count(it->first)) {
interfStores.erase(it);
}
//else if (impactG && !impacted.count(it->first)) {
// interfStores.erase(it);
//}
}
}
interfs[f] = interfStores;
}
allReachStores = newReachStores;
}
iter++;
} while (!stable);
//std::map<BasicBlock *, LatticeFact> mainRes = threadRes[main];
//errs() << "==== Main Results ====\n";
//printFactMapStderr(mainRes);
//errs() << "======================\n";
// Print out the map from values to apron names so the results can be
// interpreted
printValToNameStderr(valToName);
for (auto i = threadRes.begin(), ie = threadRes.end(); i != ie; ++i) {
Function *f = i->first;
std::string fname = f->getName();
errs() << "==== " << fname << "() Results ====\n";
std::map<BasicBlock *, LatticeFact> res = i->second;
printFactMapStderr(res);
errs() << "======================\n";
}
z3_fp_helpers::valueCacheToMetadata(M, Z3_BV_SIZE);
// The errors are counted by the number of unique reachable error
// statements. If the statement is reachable multiple times (i.e., on
// multiple iterations) it is only counted once.
//std::set<Instruction *> errInsts;
//for (auto i : rErrors) {
// errInsts.insert(i.first);
//}
//errs() << "Errors found: " << errInsts.size() << '\n';
errs() << "Errors found: " << rErrors.size() << '\n';
errs() << "Max Permutations: " << maxCombPermsG << '\n';
errs() << "Total pairs: " << totalPairs << '\n';
errs() << "Filtered pairs: " << filteredPairs << '\n';
// cleanup the environment (Going Green (tm))
ap_environment_free(env);
// Cleanup Z3 stuff
Z3_fixedpoint_dec_ref(ctx, zfp);
// The IR was modified with metadata only, but still modified
return true;
}
// Join all the facts at the vector of stores for each load into a single
// fact
std::map<Instruction *, LatticeFact> joinInterfs(
const std::map<Instruction *, std::vector<Instruction *>> l2Ss
, const std::map<Instruction *, LatticeFact> sToF
) const {
std::map<Instruction *, LatticeFact> joined;
for (auto i = l2Ss.begin(), ie = l2Ss.end(); i != ie; ++i) {
Instruction *l = i->first;
std::vector<Instruction *> ss = i->second;
if (!ss.size()) {
continue;
}
assert(ss.size() && "load with zero interfering stores");
LatticeFact lfact = Utils::mapAtUnsafe(sToF, ss[0]);
for (size_t j = 1; j < ss.size(); ++j) {
Instruction *s = ss[j];
LatticeFact nextF = Utils::mapAtUnsafe(sToF, s);
lfact = LatticeFact::factJoin(lfact, nextF);
}
assert(joined.find(l) == joined.end() && "duplicate load");
joined.emplace(l, lfact);
}
return joined;
}
// Print the contents of the passed interference map
void printStoreFacts(
std::map<Function *, std::map<Instruction *, LatticeFact>> ints) const {
for (auto ii = ints.begin(), ie = ints.end(); ii != ie; ++ii) {
Function *f = ii->first;
errs() << "Interferences for Function: " << f->getName() << '\n';
std::map<Instruction *, LatticeFact> fInts = ii->second;
for (auto fi = fInts.begin(), fe = fInts.end(); fi != fe; ++fi) {
const Instruction *si = fi->first;
LatticeFact f = fi->second;
errs() << "\tStoreInst: " << *si << "\n\tFact: ";
f.fprint(stderr);
}
}
}
void addLoadStoreFacts(BasicBlock *b, z3::context &ctx, Z3_fixedpoint &zfp) {
for (auto i = b->begin(), ie = b->end(); i != ie; ++i) {
Instruction *cur = &*i;
if (LoadInst *l = dyn_cast<LoadInst>(cur)) {
Value *ptrOp = l->getPointerOperand();
addLoadFact(ctx, zfp, l, ptrOp);
}
else if (StoreInst *s = dyn_cast<StoreInst>(cur)) {
Value *ptrOp = s->getPointerOperand();
addStoreFact(ctx, zfp, s, ptrOp);
}
}
}
void addLoadStoreFacts(BasicBlock *b, z3::context &ctx, Z3_fixedpoint &zfp, unsigned priority) {
z3::func_decl linePriDecl = getLinePriFuncDecl(ctx);
for (auto i = b->begin(), ie = b->end(); i != ie; ++i) {
Instruction *cur = &*i;
if (LoadInst *l = dyn_cast<LoadInst>(cur)) {
Value *ptrOp = l->getPointerOperand();
addLoadFact(ctx, zfp, l, ptrOp);
// add linepri fact for each load
addLinePriFact(ctx, zfp, linePriDecl, l, priority);
} else if (StoreInst *s = dyn_cast<StoreInst>(cur)) {
Value *ptrOp = s->getPointerOperand();
addStoreFact(ctx, zfp, s, ptrOp);
// add linepri fact for each store
addLinePriFact(ctx, zfp, linePriDecl, s, priority);
}
}
}
// Search for any pthread_join calls and add must-happen-before constraints;
// see the overloaded version of this function
void addJoinFacts(Module &M, z3::context &ctx, Z3_fixedpoint &zfp) {
for (Function &F : M) {
for (BasicBlock &BB : F) {
for (Instruction &I : BB) {
CallInst *ci = dyn_cast<CallInst>(&I);
if (ci != NULL) {
if (ci->getCalledFunction()->getName() == "pthread_join") {
addJoinFacts(ci, ctx, zfp);
}
}
} // for (Instruciton ...)
} // for (BasicBlock ...)
} // for (Function ...)
}
// Search for pthread_join() calls and add the happens-before fact that the
// thread must terminate before the join.
//
// This performs the following:
// 1. Check if the instruction is a pthread_join call
// 2. Attempt to find the pthread_create call where the thread ID is used
// 3. If found, return a happens-before fact
// Otherwise, return an emptry string
//
// Note: this makes a few assumptions
// 1. The pthread_t associated with the pthread_join() was only used to
// create a thread in a single function
// 2. The pthread_create() call associated with the passed join is in the
// same function
//
// Point 1 is not explicitly enforced
void addJoinFacts(CallInst *i, z3::context &ctx, Z3_fixedpoint &zfp) {
// Find the associated thread function
assert(i->getNumOperands() >= 1 && "join without operand");
Function *thrdFunc = findCreateFromJoin(i->getOperand(0));
if (thrdFunc == NULL) {
errs() << "[WARNING] no create matching join: " << *i << '\n';
return;
}
if (thrdFunc->empty()) {
errs() << "[WARNING] empty thread function: " << thrdFunc->getName()
<< '\n';
return;
}
// Add happens-before edges from all the return sites of the function to
// the join site
std::vector<ReturnInst*> rets = getRets(thrdFunc);
assert(rets.size() && "function without returns");
for (ReturnInst *r : rets) {
// The return must happen before the join
addMHBFact(ctx, zfp, r, i);
}
}
// Given a pthread_t argument used in a join call, search the def-use chain
// to find where it is used in pthread_create. Return the thread function
// create by the pthread_create call.
//
// Returns NULL if no function was found.
//
// Note: a program actually could use the same pthread_t in multiple
// pthread_create() calls. This function returns the first one found
Function* findCreateFromJoin(Value *pt) {
assert(pt != NULL);
Instruction *i = dyn_cast<Instruction>(pt);
// This iteratively follows the defs of pt backwards until a
// pthread_create() is found
// This assumes the only things on the use-def chain are instructions
if (i != NULL) {
DEBUG_MSG("[DEBUG] Found pthread_t from instruction\n");
}
else {
errs() << "[WARNING] Unhandled pthread_t def: " << *pt << '\n';
return NULL;
}
// A vector of Values is used since, in general, the use-def chains can
// contain any value and not just instructions
std::vector<Value *> toVisit;
toVisit.push_back(i);
while (toVisit.size()) {
Instruction *i = dyn_cast<Instruction>(toVisit.back());
toVisit.pop_back();
if (i == NULL) {
errs() << "[ERROR] non instruction value on use-def chain: "
<< *toVisit.back() << '\n';
exit(EXIT_FAILURE);
}
// Check if the visited instruciton is a call to pthread_create. If it
// is, assume that we are done.
// Note: is there ever a case where the join argument is data dependent
if (CallInst *ci = dyn_cast<CallInst>(i)) {
if (ci->getCalledFunction()->getName() == "pthread_create") {
DEBUG_MSG("paired join with create: " << *ci);
return getPThreadThreadFunc(ci);
}
}
else if (AllocaInst *ai = dyn_cast<AllocaInst>(i)) {
// If we find an alloca, then we've found the site where the pthread_t
// was allocated. Search forward from the alloca for the pthread_create
// site.
return forwardSearchCreate(ai);
}
else if (LoadInst *li = dyn_cast<LoadInst>(i)) {
// Get the defs of the load instruction
for (Use &U : li->operands()) {
Value *useV = U.get();
toVisit.push_back(useV);
}
}
// TODO: Handle additional types here. Might be able to just blindly
// search backwards on all the operands of the instruction
else {
errs() << "[ERROR] Unahandled instruction type while searching for "
<< "pthread_create: " << *i << '\n';
DEBUG_MSG("checking isa loadinst\n");
DEBUG_MSG("isa loadinst? " << isa<LoadInst>(i) << '\n');
exit(EXIT_FAILURE);
}
}
// Reach here means we didn't find the create site
return NULL;
}
// Given an alloca instruction allocating a pthread_t, search forward for the
// site where the pthread_t is being used. Return the function created by the
// pthread_create call
//
// This returns the first site found
Function *forwardSearchCreate(AllocaInst *ai) {
std::vector<Instruction *> toVisit;
toVisit.push_back(ai);
while (toVisit.size()) {
Instruction *cur = toVisit.back();
toVisit.pop_back();
for (User *u : cur->users()) {
// Check if we've found pthread_create
if (CallInst *ci = dyn_cast<CallInst>(u)) {
if (ci->getCalledFunction()->getName() == "pthread_create") {
DEBUG_MSG("found pthread_create on forward search: "
<< *ci << '\n');
return getPThreadThreadFunc(ci);
}
}
if (Instruction *i = dyn_cast<Instruction>(u)) {
toVisit.push_back(i);
}
else {
errs() << "[ERROR] unhandled User searching forward for "
<< "pthread_create: " << *u << '\n';
exit(EXIT_FAILURE);
}
}
} // while (toVisit.size())
// Reach here means we did not find pthread_create
return NULL;
}
// Given a Function, return all of its return instructions
std::vector<ReturnInst*> getRets(Function *f) {
std::vector<ReturnInst*> ret;
for (BasicBlock &BB : *f) {
for (Instruction &I : BB) {
if (ReturnInst *r = dyn_cast<ReturnInst>(&I)) {
ret.push_back(r);
}
}
}
return ret;
}
// Starting from `main`, find all the children threads. Using the
// happen-before relation caused by thread creation, get those stores which a
// thread function must not be able to read from
void getNotReadFrom(std::map<Function *, Function*> &child2parent
, std::map<Function *, std::vector<Function*>> &parent2child
, std::map<Function *, std::vector<StoreInst *>> ¬ReadFrom
, std::map<Function *, CallInst *> &createLocs
, Function *main) {
// List containing function to be processed. The order the functions are
// processed does matter! The parent of a thread must be processed before
// the child. This is required because the parent's information needs to be
// availible (the things the parent cannot read from) in order to evaluate
// the child.
std::deque<Function *> worklist;
worklist.push_back(main);
while (worklist.size()) {
// Get and delete the first item
Function *curParent = worklist.front();
DEBUG_MSG("[DEBUG] getNotReadFrom: analyzing function: "
<< curParent->getName() << '\n');
worklist.pop_front();
// Get all the threads created by `f`. These are all the children of `f`
std::vector<CallInst *> creats = getThreadCreate(curParent);
DEBUG_MSG("\t" << creats.size() << " thread creations\n");
std::vector<Function *> curParentChildren;
for (CallInst *ci : creats) {
Function *thrdFunc = getPThreadThreadFunc(ci);
curParentChildren.push_back(thrdFunc);
// This error could be fixed: see the comment above the assertion below
assert(createLocs.find(thrdFunc) == createLocs.end()
&& "thread function created twice");
createLocs.emplace(thrdFunc, ci);
// The child of curParent also needs to be processed (we need to find
// if it has any children)
worklist.push_back(thrdFunc);
// In general, we should allow the same function to be created twice.
// We could handle this by instead making the child2parent map a map
// from a pair of Function * and CallInst:
// std::map<std::pair<Function *, CallInst *>, Function*>
// In this way, we only require each CallSite to be unique
assert(child2parent.find(thrdFunc) == child2parent.end()
&& "function being created twice");
child2parent.emplace(thrdFunc, curParent);
// Get those store's within the thread that cannot be read by this call
// instruction
std::vector<StoreInst *> mnrl = getThreadLocalNotRead(ci);
DEBUG_MSG("\t" << mnrl.size() << " local not-read from\n");
// Get the stores which cannot be read by any ancestors of the parent
std::vector<StoreInst *> mnrp
= getParentNotRead(ci->getParent()->getParent(), child2parent
, notReadFrom);
DEBUG_MSG("\t" << mnrp.size() << " parent not-read from\n");
// Merge the results
std::vector<StoreInst *> merge;
merge.reserve(mnrl.size() + mnrp.size());
merge.insert(merge.end(), mnrl.begin(), mnrl.end());
merge.insert(merge.end(), mnrp.begin(), mnrp.end());
// Update must-not read-from results
assert(notReadFrom.find(thrdFunc) == notReadFrom.end()
&& "function being created twice");
notReadFrom.emplace(thrdFunc, merge);
} // for (CallInst *ci : creats)
// save the parents children
assert(parent2child.find(curParent) == parent2child.end()
&& "parent visited twice");
parent2child.emplace(curParent, curParentChildren);
}
}
// Given a call instruction `ci`, find those stores within the Function
// calling `ci` which must happen-before `ci`. Any store which must happen
// before `ci` is not visible to the child thread created by `ci`
std::vector<StoreInst *> getThreadLocalNotRead(CallInst *ci) {
BasicBlock *ciBB = ci->getParent();
Function *ciF = ci->getParent()->getParent();
// First, get the stores within the basicblock which happen before the
// CallInst. These trivially must happen before the callinst
std::vector<StoreInst *> ret = getStoresInBBBefore(ci);
DEBUG_MSG("[DEBUG] getThreadLocalNotRead(): "
"intra-BB happens-before stores: " << ret.size() << '\n');
// Next, get all those stores in basicblock which post dominate `ci`. Since
// we just got the stores within the same basicblock as `ci`, we can ignore
// the block containing `ci` (any basicblock post-dominates itself).
PostDominatorTree &PDT = getAnalysis<PostDominatorTree>(*ciF);
SmallVector<BasicBlock *, 10> pdoms;
PDT.getDescendants(ciBB, pdoms);
for (BasicBlock *b : pdoms) {
if (b == ciBB) {
// Do not analyze the BasicBlock containing `ci`
continue;
}
std::vector<StoreInst *> bStores = getStores(b);
// Add bStores to the end of ret
Utils::addVector(ret, bStores);
}
return ret;
}
// Given a pthread_create call, find all the stores within the calling thread
// much must ocurr before the call. These are not visible to the child thread
// unless the value is not overwritten. In that case, the value will be
// present in the initial environment of the thread
void addThreadLocalNotRead(z3::context &ctx, Z3_fixedpoint &zfp, CallInst *ci
, Function *tfunc) {
std::vector<StoreInst*> sts = getThreadLocalNotRead(ci);
std::vector<Instruction*> ls = getLoads(tfunc);
for (StoreInst *s : sts) {
for (Instruction *l : ls) {
addNotReadFact(ctx, zfp, l, s);
}
}
}
// Return the StoreInsts which ocurr before `i` within the same basicblock as
// `i`.
std::vector<StoreInst *> getStoresInBBBefore(Instruction *i) {
BasicBlock *b = i->getParent();
std::vector<StoreInst *> ret;
for (auto bi = b->begin(), be = b->end(); bi != be; ++bi) {
Instruction *cur = &*bi;
if (cur == i) {
return ret;
}
if (StoreInst *si = dyn_cast<StoreInst>(cur)) {
ret.push_back(si);
}
}
// Reaching this point means `i` was not found in its own basicblock. This
// should never happen!
assert(0 && "passed instruction not found");
}
// Given a function `f`, get all the stores which the parents of `f` cannot
// read from. Transitively, `f` can also not read from these stores
std::vector<StoreInst *> getParentNotRead(Function *f
, std::map<Function*, Function*> child2parent
, std::map<Function *, std::vector<StoreInst *>> notReadFrom) {
std::vector<StoreInst *> ret;
std::vector<Function *> parents = getParents(f, child2parent);
for (Function *par : parents) {
auto nri = notReadFrom.find(par);
if (nri != notReadFrom.end()) {
std::vector<StoreInst *> nr = nri->second;
ret.insert(ret.end(), nr.begin(), nr.end());
}
}
return ret;
}
// Given a child thread, follow the child2parent map and return all the
// parents of `child` (i.e., its creater, its creater's creater, and so on)
std::vector<Function *> getParents(Function *child
, const std::map<Function *, Function*> child2parent) const {
std::vector<Function *> ret;
auto iter = child2parent.find(child);
while (iter != child2parent.end()) {
Function *parent = iter->second;
ret.push_back(parent);
// Find the parent of `parent`
iter = child2parent.find(parent);
}
return ret;
}
// Return the first instruction in the passed function. If the function is
// external (i.e., we do not have the source code, return NULL.
Instruction *getFirstInst(Function *f) {
if (f->begin() == f->end()) {
// No basicblocks
return NULL;
}
auto ii = f->begin()->begin();
Instruction *ret = &*ii;
return ret;
}
// Return the function being created in a thread by the passed call
// instruction. It is assumed the call instruction is a pthread_create call.
//
// Otherwise, this will crash.
Function *getPThreadThreadFunc(CallInst *ci) {
Value *v = ci->getArgOperand(2);
if (Function *tFunc = dyn_cast<Function>(v)) {
return tFunc;
}
else {
errs() << "[ERROR] pthread_create with non function 2nd arg\n";
errs() << *v << '\n';
exit(EXIT_FAILURE);
}
}
std::set<BasicBlock *> getAllBBs(Function *F) {
std::set<BasicBlock *> ret;
for (BasicBlock &B : *F) {
ret.insert(&B);
}
return ret;
}
// Update fixedpoint and context to contain not-reachable information
void addNotReachableFacts(Module &M, z3::context &ctx, Z3_fixedpoint &zfp) {
addNotReachRel(ctx, zfp);
for (Function &F : M) {
std::set<BasicBlock*> allBBs = getAllBBs(&F);
std::map<BasicBlock *, std::set<BasicBlock*>> reachMap;
reachMap = getReachability(&F);
for (BasicBlock &B : F) {
auto it = reachMap.find(&B);
assert(it != reachMap.end());
std::set<BasicBlock *> reach = it->second;
if (reach.find(&B) != reach.end()) {
DEBUG_MSG("Self reachable basicblock\n");
}
// At most there will be allBBs.size() items in the result
std::vector<BasicBlock*> notReach(allBBs.size());
// allBbs - reach
// i.e., the not reachable BBs
auto nrIt = set_difference(allBBs.begin()
, allBBs.end()
, reach.begin()
, reach.end()
, notReach.begin());
// Resize notReach to remove any of the non-used slots
notReach.resize(nrIt - notReach.begin());
for (BasicBlock *notReachB : notReach) {
// Every instruyction in B cannot reach notReachB
for (Instruction &BI : B) {
if (!isaStoreLoadCallOrTerm(&BI)) {
continue;
}
for (Instruction &nrBI : *notReachB) {
if (!isaStoreLoadCallOrTerm(&nrBI)) {
continue;
}
addNotReachFact(ctx, zfp, &BI, &nrBI);
}
}
}
}
}
}
// Return true if the passed instruction is a StoreInst, LoadInst, or
// TerminatorInst
bool isaStoreLoadCallOrTerm(Instruction *I) const {
if (isa<StoreInst>(I)) {
return true;
}
else if (isa<LoadInst>(I)) {
return true;
}
else if (isa<TerminatorInst>(I)) {
return true;
}
else if (isa<CallInst>(I)) {
return true;
}
else {
return false;
}
}
std::map<BasicBlock *, std::set<BasicBlock*>> getReachability(Function *F) {
std::map<BasicBlock *, std::set<BasicBlock*>> ret;
for (BasicBlock &B : *F) {
ret.emplace(&B, forwardDfs(&B));
}
return ret;
}
// Return all the basicblocks forwardly reachable from `b`
//
// This only includes `b`in the return if there exists a path from `b` to
// `b`.
std::set<BasicBlock *> forwardDfs(BasicBlock *b) {
std::set<BasicBlock*> ret;
std::set<BasicBlock*> visited;
std::vector<BasicBlock*> s;
// Do not add `b` to ret unless there is a path from `b` to `b`.
// To do this, initialize the stack with the successors
std::vector<BasicBlock*> bSuccs = getSuccsFromBB(b);
s.insert(s.end(), bSuccs.begin(), bSuccs.end());
while (!s.empty()) {
BasicBlock *cur = s.back();
s.pop_back();
if (visited.find(cur) == visited.end()) {
visited.insert(cur);
if (cur == b) {
DEBUG_MSG("self-reachable basicblock: " << b->front() << '\n');
}
ret.insert(cur);
std::vector<BasicBlock*> curSuccs = getSuccsFromBB(cur);
s.insert(s.end(), curSuccs.begin(), curSuccs.end());
}
}
if (ret.find(b) != ret.end()) {
DEBUG_MSG("basicblock can reach itself\n");
}
return ret;
}
std::vector<BasicBlock*> getSuccsFromBB(BasicBlock *B) {
std::vector<BasicBlock *> ret;
TerminatorInst *ti = B->getTerminator();
assert(ti && "malformed basic block");
for (size_t i = 0; i < ti->getNumSuccessors(); ++i) {
ret.push_back(ti->getSuccessor(i));
}
return ret;
}
// Return a const bitvector ID for the passed instruction.
//
// This uses the address of the instruction; LLVM guarantees this is unique.
//
// The size of the bitvector is the size of the pointer-type (e.g.,
// sizeof(uintptr_t))
z3::expr getValueBVID(z3::context &ctx, Value *v) const {
return getValueBVIDSz(ctx, v, Z3_BV_SIZE);
}
// get function declaration of ld relation
z3::func_decl getLdFuncDecl(z3::context &ctx) const {
return getBVBVFuncDecl(ctx, "ld");
}
// get function declarion of st relation
z3::func_decl getStFuncDecl(z3::context &ctx) {
return getBVBVFuncDecl(ctx, "st");
}
z3::func_decl getMHBFuncDecl(z3::context &ctx) const {
return getBVBVFuncDecl(ctx, "mhb");
}
z3::func_decl getNoReorderFuncDecl(z3::context &ctx) const {
return getBVBVFuncDecl(ctx, "noreorder");
}
z3::func_decl getFenceFuncDecl(z3::context &ctx) const {
return getBVFuncDecl(ctx, "fence");
}
z3::func_decl getLwSyncFuncDecl(z3::context &ctx) const {
return getBVFuncDecl(ctx, "lwsync");
}
// Return func_decl of dominance relation
z3::func_decl getDomFuncDecl(z3::context &ctx) const {
return getBVBVFuncDecl(ctx, "dom");
}
// Return func_decl of post dominance relation
z3::func_decl getPostDomFuncDecl(z3::context &ctx) const {
return getBVBVFuncDecl(ctx, "postDom");
}
// Return func_decl of priority
z3::func_decl getPriFuncDecl(z3::context &ctx) const {
return getBVFuncDecl(ctx, "pri");
}
// Return func_decl of higher
z3::func_decl getHighFuncDecl(z3::context &ctx) const {
return getBVBVFuncDecl(ctx, "higher");
}
// Return func_decl of lineHigh
z3::func_decl getLineHighFuncDecl(z3::context &ctx) const {
return getBVBVFuncDecl(ctx, "linehigh");
}
// return func_decl of compLoad
z3::func_decl getCompLdFuncDecl(z3::context &ctx) const {
return getBVFuncDecl(ctx, "compLd");
}
// return func_decl of nonLastStore
z3::func_decl getNonLastStFuncDecl(z3::context &ctx) const {
return getBVFuncDecl(ctx, "nonLastSt");
}
// Return func_decl of linePri
z3::func_decl getLinePriFuncDecl(z3::context &ctx) const {
return getBVBVFuncDecl(ctx, "linepri");
}
z3::func_decl getNotReachFuncDecl(z3::context &ctx) const {
return getBVBVFuncDecl(ctx, "not-reach");
}
z3::func_decl getNotReadsFromFuncDecl(z3::context &ctx) const {
return getBVBVFuncDecl(ctx, "not-rf");
}
z3::func_decl getReadsFromFuncDecl(z3::context &ctx) const {
return getBVBVFuncDecl(ctx, "rf");
}
// Given the name of a relation with arguments (bitvector, bitvector) return
// its function declaration.
z3::func_decl getBVBVFuncDecl(z3::context &ctx, const char *name) const {
return z3_fp_helpers::getBVBVFuncDecl(ctx, name, Z3_BV_SIZE);
}
// Given the name of a relation with arguments (bitvector) return
// its function declaration.
z3::func_decl getBVFuncDecl(z3::context &ctx, const char *name) const {
return z3_fp_helpers::getBVFuncDecl(ctx, name, Z3_BV_SIZE);
}
void addLinePriFact(z3::context &ctx
, Z3_fixedpoint &zfp
, z3::func_decl fd
, llvm::Instruction *l
, unsigned priority) const {
addLinePriFactSz(ctx, zfp, fd, l, priority, Z3_BV_SIZE);
}
void addFact2(z3::context &ctx
, Z3_fixedpoint &zfp
, z3::func_decl fd
, llvm::Value *v1
, llvm::Value *v2) const {
addFact2Sz(ctx, zfp, fd, v1, v2, Z3_BV_SIZE);
}
void addFact1(z3::context &ctx
, Z3_fixedpoint &zfp
, z3::func_decl fd
, llvm::Value *v) const {
addFact1Sz(ctx, zfp, fd, v, Z3_BV_SIZE);
}
// Add a fact that `l` loads `v`
void addLoadFact(z3::context &ctx
, Z3_fixedpoint &zfp
, Instruction *l
, Value *v) {
addFact2(ctx, zfp, getLdFuncDecl(ctx), l, v);
}
// Add a fact that `f` is a fence
void addFenceFact(z3::context &ctx
, Z3_fixedpoint &zfp
, Instruction *f) {
addFact1(ctx, zfp, getFenceFuncDecl(ctx), f);
}
void addLwSyncFact(z3::context &ctx
, Z3_fixedpoint &zfp
, Instruction *f) {
addFact1(ctx, zfp, getLwSyncFuncDecl(ctx), f);
}
// Add (rf l v)
void addReadsFromFact(z3::context &ctx
, Z3_fixedpoint &zfp
, Instruction *l
, Value *v) const {
assert(Utils::isSomeLoad(l) && "non load reading");
addFact2(ctx, zfp, getReadsFromFuncDecl(ctx), l, v);
}
// Add a fact that `l` stores `v`
void addStoreFact(z3::context &ctx
, Z3_fixedpoint &zfp
, Instruction *s
, Value *v) {
addFact2(ctx, zfp, getStFuncDecl(ctx), s, v);
}
// Add (mhb to from)
void addMHBFact(z3::context &ctx, Z3_fixedpoint &zfp, Instruction *from
, Instruction *to) {
//Z3_ast fromId = getValueBVID(ctx, from);
//Z3_ast toId = getValueBVID(ctx, to);
//addMHBFact(ctx, zfp, fromId, toId);
addFact2(ctx, zfp, getMHBFuncDecl(ctx), from, to);
}
// Add fact: (dom a b)
// Converts to instructions to bitvector ids
void addDomFact(z3::context &ctx
, Z3_fixedpoint &zfp
, Instruction *a
, Instruction *b) {
addFact2(ctx, zfp, getDomFuncDecl(ctx), a, b);
}
// Add fact: (dom a b)
// Converts to instructions to bitvector ids
void addPostDomFact(z3::context &ctx
, Z3_fixedpoint &zfp
, Instruction *a
, Instruction *b) {
addFact2(ctx, zfp, getPostDomFuncDecl(ctx), a, b);
}
// Add fact: (not-read s l)
void addNotReadFact(z3::context &ctx
, Z3_fixedpoint &zfp
, Instruction *s
, Instruction *l) {
addFact2(ctx, zfp, getNotReadsFromFuncDecl(ctx), s, l);
}
// Add: (not-reach a b): a cannot reach b
void addNotReachFact(z3::context &ctx
, Z3_fixedpoint &zfp
, Instruction *a
, Instruction *b) {
addFact2(ctx, zfp, getNotReachFuncDecl(ctx), a, b);
}
// Return the dominance and post dominance facts
// within the basicblock (i.e., the order of instructions in the block).
// Since we are only interested in loads and stores, this will ignore all
// other instruction types except the basicblock terminator and calls.
void addInternalDomAndPostDomFacts(BasicBlock *b, z3::context &ctx, Z3_fixedpoint &zfp) {
std::vector<Instruction *> loadsNStores = getLoadStoreCallOrdered(b);
loadsNStores.push_back(b->getTerminator());
assert(loadsNStores.size() > 0 && "basicblock with no terminator");
if (loadsNStores.size() == 1) {
// With only one instruction (the terminator) there is no internal
// dominance facts
return;
}
assert(loadsNStores.size() > 1);
Instruction *prev = loadsNStores[0];
for (size_t i = 1; i < loadsNStores.size(); ++i) {
Instruction *cur = loadsNStores[i];
// prev dominates cur
addDomFact(ctx, zfp, prev, cur);
addPostDomFact(ctx, zfp, cur, prev);
// Update prev for the next iteration
prev = cur;
}
}
// (=> (and (dom a b) (not-reach b a)) (mhb a b))
void addDomNotReachRule(z3::context &ctx, Z3_fixedpoint &zfp) {
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
//Z3_ast a = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "aDom"), bvSort);
//Z3_ast b = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "bDom"), bvSort);
z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort));
z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort));
z3::func_decl domDecl = getDomFuncDecl(ctx);
z3::func_decl nrDecl = getNotReachFuncDecl(ctx);
z3::func_decl mhbDecl = getMHBFuncDecl(ctx);
// (dom a b)
// (mhb a b)
z3::expr args[2] = {a, b};
z3::expr domAB = domDecl(2, args);
z3::expr mhbAB = mhbDecl(2, args);
// (not-reach b a)
args[0] = b;
args[1] = a;
z3::expr nrBA = nrDecl(2, args);
// (and (dom a b) (not-reach b a))
//args[0] = domAB;
//args[1] = nrBA;
z3::expr domNrAnd = domAB && nrBA;
z3::expr imp = z3::implies(domNrAnd, mhbAB);
Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL);
}
// (=> (and (dom a b) (not-reach b a)) (mhb a b))
void addDomNotReachReorderRule(z3::context &ctx, Z3_fixedpoint &zfp) {
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
//Z3_ast a = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "aDom"), bvSort);
//Z3_ast b = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "bDom"), bvSort);
z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort));
z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort));
z3::func_decl domDecl = getDomFuncDecl(ctx);
z3::func_decl nrDecl = getNotReachFuncDecl(ctx);
z3::func_decl mhbDecl = getMHBFuncDecl(ctx);
z3::func_decl noReoDecl = getNoReorderFuncDecl(ctx);
// (dom a b)
// (mhb a b)
// (noreorder a b)
z3::expr args[2] = {a, b};
z3::expr domAB = domDecl(2, args);
z3::expr mhbAB = mhbDecl(2, args);
z3::expr noReoAB = noReoDecl(2, args);
// (not-reach b a)
args[0] = b;
args[1] = a;
z3::expr nrBA = nrDecl(2, args);
// (and (dom a b) (not-reach b a) (noreorder a b))
//args[0] = domAB;
//args[1] = nrBA;
z3::expr domNrAnd = domAB && nrBA && noReoAB;
z3::expr imp = z3::implies(domNrAnd, mhbAB);
Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL);
}
// (=> (and (reads-from l s1)
// (mhb s1 s2)
// (is-load l v)
// (is-store s1 v)
// (is-store s2 v))
// (mhb l s2))
void addReadsFromMHB(z3::context &ctx, Z3_fixedpoint &zfp) {
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
//Z3_ast s1 = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "s1"), bvSort);
//Z3_ast s2 = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "s2"), bvSort);
//Z3_ast l = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "l"), bvSort);
//Z3_ast v = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "v"), bvSort);
z3::expr s1 = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort));
z3::expr s2 = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort));
z3::expr l = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort));
z3::expr v = z3::expr(ctx, Z3_mk_bound(ctx, 3, bvSort));
z3::func_decl mhbDecl = getMHBFuncDecl(ctx);
z3::func_decl rfDecl = getReadsFromFuncDecl(ctx);
z3::func_decl ldDecl = getLdFuncDecl(ctx);
z3::func_decl stDecl = getStFuncDecl(ctx);
z3::expr args[2] = {l, s1};
z3::expr rf_l_s1 = rfDecl(2, args);
args[0] = s1;
args[1] = s2;
z3::expr mhb_s1_s2 = mhbDecl(2, args);
args[0] = l;
args[1] = v;
z3::expr ld_l_v = ldDecl(2, args);
args[0] = s1;
args[1] = v;
z3::expr st_s1_v = stDecl(2, args);
args[0] = s2;
args[1] = v;
z3::expr st_s2_v = stDecl(2, args);
args[0] = l;
args[1] = s2;
z3::expr mhb_l_s2 = mhbDecl(2, args);
//z3::expr andArgs[5] = {rf_l_s1, mhb_s1_s2, ld_l_v, st_s1_v, st_s2_v};
//z3::expr bigAnd = z3::expr(ctx, Z3_mk_and(ctx, 5, andArgs));
z3::expr bigAnd = rf_l_s1 && mhb_s1_s2 && ld_l_v && st_s1_v && st_s2_v;
z3::expr imp = z3::implies(bigAnd, mhb_l_s2);
Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL);
}
// (=> (and (mhb a b) (mhb b c))
// (mhb a c))
void addMHBTrans(z3::context &ctx, Z3_fixedpoint &zfp) {
addTransRuleBVBV(ctx, zfp, getMHBFuncDecl(ctx), Z3_BV_SIZE);
}
// (=> (and (reads-from l1 s1)
// (mhb l1 s2)
// (mhb s2 l2)
// (is-load l1 v)
// (is-load l2 v)
// (is-store s2 v))
// (not-rf l2 s1))
void addOverwriteNotReads(z3::context &ctx, Z3_fixedpoint &zfp) {
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
//Z3_ast l1 = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "l1"), bvSort);
//Z3_ast l2 = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "l2"), bvSort);
//Z3_ast s1 = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "s1"), bvSort);
//Z3_ast s2 = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "s2"), bvSort);
z3::expr l1 = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort));
z3::expr l2 = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort));
z3::expr s1 = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort));
z3::expr s2 = z3::expr(ctx, Z3_mk_bound(ctx, 3, bvSort));
z3::expr v = z3::expr(ctx, Z3_mk_bound(ctx, 4, bvSort));
z3::func_decl rfDecl = getReadsFromFuncDecl(ctx);
z3::func_decl ldDecl = getLdFuncDecl(ctx);
z3::func_decl stDecl = getStFuncDecl(ctx);
z3::func_decl mhbDecl = getMHBFuncDecl(ctx);
z3::func_decl nrfDecl = getNotReadsFromFuncDecl(ctx);
z3::expr args[2] = {l1, s1};
z3::expr rf_l1_s1 = rfDecl(2, args);
args[0] = l1;
args[1] = s2;
z3::expr mhb_l1_s2 = mhbDecl(2, args);
args[0] = s2;
args[1] = l2;
z3::expr mhb_s2_l2 = mhbDecl(2, args);
args[0] = l1;
args[1] = v;
z3::expr ld_l1_v = ldDecl(2, args);
args[0] = l2;
args[1] = v;
z3::expr ld_l2_v = ldDecl(2, args);
args[0] = s2;
args[1] = v;
z3::expr st_s2_v = stDecl(2, args);
args[0] = l2;
args[1] = s1;
z3::expr nrf_l2_s1 = nrfDecl(2, args);
//z3::expr andArgs[6] = {rf_l1_s1, mhb_l1_s2, mhb_s2_l2, ld_l1_v, ld_l2_v
// , st_s2_v};
//z3::expr bigAnd = z3::expr(ctx, Z3_mk_and(ctx, 6, andArgs));
z3::expr bigAnd = rf_l1_s1 && mhb_l1_s2 && mhb_s2_l2 && ld_l1_v
&& ld_l2_v && st_s2_v;
z3::expr imp = z3::implies(bigAnd, nrf_l2_s1);
Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL);
}
// (=> (mhb a b) (not-rf a b))
void addMHBNotReads(z3::context &ctx, Z3_fixedpoint &zfp) {
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
//Z3_ast a = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "a"), bvSort);
//Z3_ast b = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "b"), bvSort);
z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort));
z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort));
z3::expr args[2] = {a, b};
z3::expr mhbAB = getMHBFuncDecl(ctx)(2, args);
z3::expr nrfAB = getNotReadsFromFuncDecl(ctx)(2, args);
Z3_fixedpoint_add_rule(ctx, zfp, Z3_mk_implies(ctx, mhbAB, nrfAB), NULL);
}
//// Add a rule sating that reads-from(a, b) ==> MHB(b, a). A write must ocurr
//// before a read for it to be witnessed
void addMHBNRFRule(z3::context &ctx, Z3_fixedpoint &zfp) const {
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort));
z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort));
z3::expr args[2] = {a, b};
z3::expr rfAB = getReadsFromFuncDecl(ctx)(2, args);
args[0] = b;
args[1] = a;
z3::expr mhbBA = getMHBFuncDecl(ctx)(2, args);
Z3_fixedpoint_add_rule(ctx, zfp, Z3_mk_implies(ctx, rfAB, mhbBA), NULL);
}
// Add rules which can prune interferences:
void addPruningRules(z3::context &ctx, Z3_fixedpoint &zfp) {
addReadsFromRel(ctx, zfp);
addNotReadsFromRel(ctx, zfp);
addMHBNRFRule(ctx, zfp);
addDomNotReachRule(ctx, zfp);
addReadsFromMHB(ctx, zfp);
addMHBTrans(ctx, zfp);
addMHBNotReads(ctx, zfp);
addOverwriteNotReads(ctx, zfp);
}
void addSCReorderRules(z3::context &ctx, Z3_fixedpoint &zfp) {
addNoReorderRel(ctx, zfp);
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
z3::expr v1 = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort));
z3::expr v2 = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort));
z3::func_decl ldDecl = getLdFuncDecl(ctx);
z3::func_decl stDecl = getStFuncDecl(ctx);
z3::func_decl fenceDecl = getFenceFuncDecl(ctx);
/* Single Variable Rules */
// R(v) -> R(v)
addNoReoFunc2Func2(ctx, zfp, ldDecl, ldDecl, v1, v1);
// R(v) -> W(v)
addNoReoFunc2Func2(ctx, zfp, ldDecl, stDecl, v1, v1);
// W(v) -> R(v)
addNoReoFunc2Func2(ctx, zfp, stDecl, ldDecl, v1, v1);
// W(v) -> W(v)
addNoReoFunc2Func2(ctx, zfp, stDecl, stDecl, v1, v1);
/* End Single Variable Rules */
/* Double Variables Rules */
// R(v) -> R(v)
addNoReoFunc2Func2(ctx, zfp, ldDecl, ldDecl, v1, v2);
//// R(v) -> W(v)
addNoReoFunc2Func2(ctx, zfp, ldDecl, stDecl, v1, v2);
//// W(v) -> R(v)
addNoReoFunc2Func2(ctx, zfp, stDecl, ldDecl, v1, v2);
//// W(v) -> W(v)
addNoReoFunc2Func2(ctx, zfp, stDecl, stDecl, v1, v2);
/* End Double Variables Rules */
// Fences dont exist on SC
// Fences and all loads/stores are not reordered
//addNoReoFunc1Func2(ctx, zfp, fenceDecl, stDecl);
//addNoReoFunc1Func2(ctx, zfp, fenceDecl, ldDecl);
//addNoReoFunc2Func1(ctx, zfp, stDecl, fenceDecl);
//addNoReoFunc2Func1(ctx, zfp, ldDecl, fenceDecl);
}
void addTSOReorderRules(z3::context &ctx, Z3_fixedpoint &zfp) {
addNoReorderRel(ctx, zfp);
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
z3::expr v1 = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort));
z3::expr v2 = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort));
z3::func_decl ldDecl = getLdFuncDecl(ctx);
z3::func_decl stDecl = getStFuncDecl(ctx);
z3::func_decl fenceDecl = getFenceFuncDecl(ctx);
/////// OLD DEFINITIONS
//// Loads can never be reordered with anything subsequent
//addNoReoFunc2Func2(ctx, zfp, ldDecl, stDecl, v1, v2);
//addNoReoFunc2Func2(ctx, zfp, ldDecl, ldDecl, v1, v2);
////// Nothing can ever drift past a store
//addNoReoFunc2Func2(ctx, zfp, ldDecl, stDecl, v1, v2);
////addNoReoFunc2Func2(ctx, zfp, stDecl, stDecl, v1, v2);
////// Store--Load to the same variable cannot be re-ordered
//addNoReoFunc2Func2(ctx, zfp, stDecl, ldDecl, v1, v1);
////// Store--Store to any variable cannot be reordered
//////////////addNoReoFunc2Func2(ctx, zfp, stDecl, stDecl, v1, v2);
//// Fences and all loads/stores are not reordered
//addNoReoFunc1Func2(ctx, zfp, fenceDecl, stDecl);
//addNoReoFunc1Func2(ctx, zfp, fenceDecl, ldDecl);
//addNoReoFunc2Func1(ctx, zfp, stDecl, fenceDecl);
//addNoReoFunc2Func1(ctx, zfp, ldDecl, fenceDecl);
/////// END OLD DEFINITIONS
/* Single Variable Rules */
// R(v) -> R(v)
addNoReoFunc2Func2(ctx, zfp, ldDecl, ldDecl, v1, v1);
// R(v) -> W(v)
addNoReoFunc2Func2(ctx, zfp, ldDecl, stDecl, v1, v1);
// W(v) -> R(v)
// This rule is not enforced because if it is it prevents store buffer
// forwarding
//addNoReoFunc2Func2(ctx, zfp, stDecl, ldDecl, v1, v1);
// W(v) -> W(v)
addNoReoFunc2Func2(ctx, zfp, stDecl, stDecl, v1, v1);
/* End Single Variable Rules */
/* Double Variables Rules */
// RMO/PowerPC allow all of these
// R(v) -> R(v)
addNoReoFunc2Func2(ctx, zfp, ldDecl, ldDecl, v1, v2);
//// R(v) -> W(v)
addNoReoFunc2Func2(ctx, zfp, ldDecl, stDecl, v1, v2);
//// W(v) -> R(v)
//addNoReoFunc2Func2(ctx, zfp, stDecl, ldDecl, v1, v2);
//// W(v) -> W(v)
addNoReoFunc2Func2(ctx, zfp, stDecl, stDecl, v1, v2);
/* End Double Variables Rules */
addFenceReorderRules(ctx, zfp);
// Fences and all loads/stores are not reordered
//addNoReoFunc1Func2(ctx, zfp, fenceDecl, stDecl);
//addNoReoFunc1Func2(ctx, zfp, fenceDecl, ldDecl);
//addNoReoFunc2Func1(ctx, zfp, stDecl, fenceDecl);
//addNoReoFunc2Func1(ctx, zfp, ldDecl, fenceDecl);
}
void addRMOReorderRules(z3::context &ctx, Z3_fixedpoint &zfp) {
addNoReorderRel(ctx, zfp);
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
z3::expr v1 = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort));
z3::expr v2 = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort));
z3::func_decl ldDecl = getLdFuncDecl(ctx);
z3::func_decl stDecl = getStFuncDecl(ctx);
/* Single Variable Rules */
// R(v) -> R(v)
addNoReoFunc2Func2(ctx, zfp, ldDecl, ldDecl, v1, v1);
// R(v) -> W(v)
addNoReoFunc2Func2(ctx, zfp, ldDecl, stDecl, v1, v1);
// W(v) -> R(v)
//addNoReoFunc2Func2(ctx, zfp, stDecl, ldDecl, v1, v1);
// W(v) -> W(v)
addNoReoFunc2Func2(ctx, zfp, stDecl, stDecl, v1, v1);
/* End Single Variable Rules */
/* Double Variables Rules */
// RMO/PowerPC allow all of these
// R(v) -> R(v)
//addNoReoFunc2Func2(ctx, zfp, ldDecl, ldDecl, v1, v2);
//// R(v) -> W(v)
//addNoReoFunc2Func2(ctx, zfp, ldDecl, stDecl, v1, v2);
//// W(v) -> R(v)
//addNoReoFunc2Func2(ctx, zfp, stDecl, ldDecl, v1, v2);
//// W(v) -> W(v)
//addNoReoFunc2Func2(ctx, zfp, stDecl, stDecl, v1, v2);
/* End Double Variables Rules */
addFenceReorderRules(ctx, zfp);
//z3::func_decl lwDecl = getLwSyncFuncDecl(ctx);
//addNoReoFunc1Func2(ctx, zfp, lwDecl, stDecl);
//addNoReoFunc1Func2(ctx, zfp, lwDecl, ldDecl);
//addNoReoFunc2Func1(ctx, zfp, stDecl, lwDecl);
//addNoReoFunc2Func1(ctx, zfp, ldDecl, lwDecl);
// Fences and all loads/stores are not reordered
//addNoReoFunc1Func2(ctx, zfp, fenceDecl, stDecl);
//addNoReoFunc1Func2(ctx, zfp, fenceDecl, ldDecl);
//addNoReoFunc2Func1(ctx, zfp, stDecl, fenceDecl);
//addNoReoFunc2Func1(ctx, zfp, ldDecl, fenceDecl);
}
// Common reordering rules involving fences.
void addFenceReorderRules(z3::context &ctx, Z3_fixedpoint &zfp) {
z3::func_decl ldDecl = getLdFuncDecl(ctx);
z3::func_decl stDecl = getStFuncDecl(ctx);
z3::func_decl fenceDecl = getFenceFuncDecl(ctx);
//z3::func_decl lwDecl = getLwSyncFuncDecl(ctx);
addNoReoFunc1Func2(ctx, zfp, fenceDecl, stDecl);
addNoReoFunc1Func2(ctx, zfp, fenceDecl, ldDecl);
addNoReoFunc2Func1(ctx, zfp, stDecl, fenceDecl);
addNoReoFunc2Func1(ctx, zfp, ldDecl, fenceDecl);
// lwsync preserves everything but write-lwsync--read order
//addNoReoFunc1Func2(ctx, zfp, lwDecl, stDecl);
//addNoReoFunc1Func2(ctx, zfp, lwDecl, ldDecl);
//addNoReoFunc2Func1(ctx, zfp, stDecl, lwDecl);
//addNoReoFunc2Func1(ctx, zfp, ldDecl, lwDecl);
}
void addNoReorderRules(z3::context &ctx, Z3_fixedpoint &zfp) {
addReadsFromRel(ctx, zfp);
addNotReadsFromRel(ctx, zfp);
addDomNotReachReorderRule(ctx, zfp);
addMHBNRFRule(ctx, zfp);
addReadsFromMHB(ctx, zfp);
addMHBTrans(ctx, zfp);
addMHBNotReads(ctx, zfp);
addOverwriteNotReads(ctx, zfp);
}
void addPSOReorderRules(z3::context &ctx, Z3_fixedpoint &zfp) {
addNoReorderRel(ctx, zfp);
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
z3::expr v1 = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort));
z3::expr v2 = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort));
z3::func_decl ldDecl = getLdFuncDecl(ctx);
z3::func_decl stDecl = getStFuncDecl(ctx);
//z3::func_decl fenceDecl = getFenceFuncDecl(ctx);
/////// OLD DEFINITIONS
//
//// Loads can never be reordered with anything subsequent
//addNoReoFunc2Func2(ctx, zfp, ldDecl, stDecl, v1, v2);
//addNoReoFunc2Func2(ctx, zfp, ldDecl, ldDecl, v1, v2);
//// Store--Load to the same variable cannot be re-ordered
//addNoReoFunc2Func2(ctx, zfp, stDecl, ldDecl, v1, v1);
//// Store--Store to the same variable cannot be reordered
////addNoReoFunc2Func2(ctx, zfp, stDecl, stDecl, v1, v1);
//// Fences and all loads/stores are not reordered
//addNoReoFunc1Func2(ctx, zfp, fenceDecl, stDecl);
//addNoReoFunc1Func2(ctx, zfp, fenceDecl, ldDecl);
//addNoReoFunc2Func1(ctx, zfp, stDecl, fenceDecl);
//addNoReoFunc2Func1(ctx, zfp, ldDecl, fenceDecl);
/* Single Variable Rules */
// R(v) -> R(v)
addNoReoFunc2Func2(ctx, zfp, ldDecl, ldDecl, v1, v1);
// R(v) -> W(v)
addNoReoFunc2Func2(ctx, zfp, ldDecl, stDecl, v1, v1);
// W(v) -> R(v)
// This rule is not enforced because if it is it prevents store buffer
// forwarding
//addNoReoFunc2Func2(ctx, zfp, stDecl, ldDecl, v1, v1);
// W(v) -> W(v)
addNoReoFunc2Func2(ctx, zfp, stDecl, stDecl, v1, v1);
/* End Single Variable Rules */
/* Double Variables Rules */
// RMO/PowerPC allow all of these
// R(v) -> R(v)
addNoReoFunc2Func2(ctx, zfp, ldDecl, ldDecl, v1, v2);
//// R(v) -> W(v)
addNoReoFunc2Func2(ctx, zfp, ldDecl, stDecl, v1, v2);
//// W(v) -> R(v)
//addNoReoFunc2Func2(ctx, zfp, stDecl, ldDecl, v1, v2);
//// W(v) -> W(v)
//addNoReoFunc2Func2(ctx, zfp, stDecl, stDecl, v1, v2);
/* End Double Variables Rules */
addFenceReorderRules(ctx, zfp);
// Fences and all loads/stores are not reordered
//addNoReoFunc1Func2(ctx, zfp, fenceDecl, stDecl);
//addNoReoFunc1Func2(ctx, zfp, fenceDecl, ldDecl);
//addNoReoFunc2Func1(ctx, zfp, stDecl, fenceDecl);
//addNoReoFunc2Func1(ctx, zfp, ldDecl, fenceDecl);
}
void addTSOPruningRules(z3::context &ctx, Z3_fixedpoint &zfp) {
addReadsFromRel(ctx, zfp);
addNotReadsFromRel(ctx, zfp);
// General Rules
addMHBNRFRule(ctx, zfp);
addReadsFromMHB(ctx, zfp);
addMHBTrans(ctx, zfp);
addMHBNotReads(ctx, zfp);
addOverwriteNotReads(ctx, zfp);
// MHB Rules
addDomStoreStoreTSO(ctx, zfp);
addLoadStoreMHB(ctx, zfp);
addStoreLoadMHB(ctx, zfp);
addLoadLoadMHB(ctx, zfp);
// Fence Rules
addPOLoadStoreFence(ctx, zfp);
}
void addPSOPruningRules(z3::context &ctx, Z3_fixedpoint &zfp) {
addReadsFromRel(ctx, zfp);
addNotReadsFromRel(ctx, zfp);
// General Rules
addMHBNRFRule(ctx, zfp);
addReadsFromMHB(ctx, zfp);
addMHBTrans(ctx, zfp);
addMHBNotReads(ctx, zfp);
addOverwriteNotReads(ctx, zfp);
// MHB Rules
addDomStoreStorePSO(ctx, zfp);
addLoadStoreMHB(ctx, zfp);
addStoreLoadMHB(ctx, zfp);
addLoadLoadMHB(ctx, zfp);
// Fence Rules
addPOLoadStoreFence(ctx, zfp);
}
// Add ordering of loads/stores before/after a fence
void addPOLoadStoreFence(z3::context &ctx, Z3_fixedpoint &zfp) {
addDomFenceFunc2(ctx, zfp, getLdFuncDecl(ctx));
addDomFenceFunc2(ctx, zfp, getStFuncDecl(ctx));
addDomFunc2Fence(ctx, zfp, getLdFuncDecl(ctx));
addDomFunc2Fence(ctx, zfp, getStFuncDecl(ctx));
}
// Add:
// (=> (and (dom a b)
// (not-reach b a)
// (is-fence a)
// (fd b v) )
// (mhb a b))
//
// where fd is the passed func_decl
void addDomFenceFunc2(z3::context &ctx, Z3_fixedpoint &zfp
, const z3::func_decl fd) {
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort));
z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort));
z3::expr v = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort));
z3::func_decl domDecl = getDomFuncDecl(ctx);
z3::func_decl nrDecl = getNotReachFuncDecl(ctx);
z3::func_decl mhbDecl = getMHBFuncDecl(ctx);
z3::func_decl fenceDecl = getFenceFuncDecl(ctx);
// (dom a b)
// (mhb a b)
z3::expr args[2] = {a, b};
z3::expr domAB = domDecl(2, args);
z3::expr mhbAB = mhbDecl(2, args);
// (not-reach b a)
args[0] = b;
args[1] = a;
z3::expr nrBA = nrDecl(2, args);
// (is-fence a)
args[0] = a;
z3::expr fenceA = fenceDecl(1, args);
// (fd b v)
args[0] = b;
args[1] = v;
z3::expr fdBV = fd(2, args);
z3::expr bigAnd = domAB && nrBA && fenceA && fdBV;
z3::expr imp = z3::implies(bigAnd, mhbAB);
Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL);
}
// Add:
// (=> (and (dom a b)
// (not-reach b a)
// (fd a v)
// (is-fence b))
// (mhb a b))
//
// where fd is the passed func_decl
void addDomFunc2Fence(z3::context &ctx, Z3_fixedpoint &zfp
, const z3::func_decl fd) {
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort));
z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort));
z3::expr v = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort));
z3::func_decl domDecl = getDomFuncDecl(ctx);
z3::func_decl nrDecl = getNotReachFuncDecl(ctx);
z3::func_decl mhbDecl = getMHBFuncDecl(ctx);
z3::func_decl fenceDecl = getFenceFuncDecl(ctx);
// (dom a b)
// (mhb a b)
z3::expr args[2] = {a, b};
z3::expr domAB = domDecl(2, args);
z3::expr mhbAB = mhbDecl(2, args);
// (not-reach b a)
args[0] = b;
args[1] = a;
z3::expr nrBA = nrDecl(2, args);
// (is-fence b)
args[0] = b;
z3::expr fenceB = fenceDecl(1, args);
// (fd a v)
args[0] = a;
args[1] = v;
z3::expr fdAV = fd(2, args);
z3::expr bigAnd = domAB && nrBA && fenceB && fdAV;
z3::expr imp = z3::implies(bigAnd, mhbAB);
Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL);
}
// (=> (reads-from b a) (mhb a b))
void addReadsFromIsMHB(z3::context &ctx, Z3_fixedpoint &zfp) {
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort));
z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 3, bvSort));
z3::func_decl rfDecl = getReadsFromFuncDecl(ctx);
z3::func_decl mhbDecl = getMHBFuncDecl(ctx);
z3::expr argsAB[2] = {a, b};
z3::expr argsBA[2] = {b, a};
z3::expr rf_b_a = rfDecl(2, argsBA);
z3::expr mhb_a_b = mhbDecl(2, argsAB);
z3::expr imp = z3::implies(rf_b_a, mhb_a_b);
Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL);
}
// (=> (and (dom a b)
// (not-reach b a)
// (is-store a _)
// (is-store b _) )
// (mhb a b))
//
// i.e., stores to any variable are ordered on TSO
void addDomStoreStoreTSO(z3::context &ctx, Z3_fixedpoint &zfp) {
addStoreStoreMHB(ctx, zfp, false);
//z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
//z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort));
//z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort));
//z3::expr v1 = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort));
//z3::expr v2 = z3::expr(ctx, Z3_mk_bound(ctx, 3, bvSort));
//z3::func_decl domDecl = getDomFuncDecl(ctx);
//z3::func_decl nrDecl = getNotReachFuncDecl(ctx);
//z3::func_decl stDecl = getStFuncDecl(ctx);
//z3::func_decl mhbDecl = getMHBFuncDecl(ctx);
//// (dom a b)
//// (mhb a b)
//z3::expr args[2] = {a, b};
//z3::expr domAB = domDecl(2, args);
//z3::expr mhbAB = mhbDecl(2, args);
//// (not-reach b a)
//args[0] = b;
//args[1] = a;
//z3::expr nrBA = nrDecl(2, args);
//// (is-store a v1)
//// (is-store b v2)
//// v1 may or may not equal v2 to satisfy the deduction
//args[0] = a;
//args[1] = v1;
//z3::expr isStAV1 = stDecl(2, args);
//args[0] = b;
//args[1] = v2;
//z3::expr isStBV2 = stDecl(2, args);
//// (and (dom a b)
//// (not-reach b a)
//// (is-store a _)
//// (is-store b _))
//z3::expr bigAnd = domAB && nrBA && isStAV1 && isStBV2;
//z3::expr imp = z3::implies(bigAnd, mhbAB);
//Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL);
}
// (=> (and (dom a b)
// (not-reach b a)
// (is-store a v)
// (is-store b v) )
// (mhb a b))
//
// i.e., stores to the same variable are ordered on TSO
void addDomStoreStorePSO(z3::context &ctx, Z3_fixedpoint &zfp) {
addStoreStoreMHB(ctx, zfp, true);
}
// (=> (and (dom a f)
// (dom f b)
// (fd1 a v1)
// (fd2 b v2)
// (fd3 f)
// ))
void addNoReoDomFunc2Func2Func1(z3::context, Z3_fixedpoint &zfp
, const z3::func_decl fd1, const z3::func_decl fd2
, const z3::func_decl fd3, const z3::expr v1
, const z3::expr v2, const z3::expr f) {
}
// (=> (and (fd1 a v1)
// (fd2 b v2))
// (noreorder a b)
void addNoReoFunc2Func2(z3::context &ctx, Z3_fixedpoint &zfp
, const z3::func_decl fd1, const z3::func_decl fd2
, const z3::expr v1, const z3::expr v2) {
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort));
z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort));
z3::func_decl noReoDecl = getNoReorderFuncDecl(ctx);
z3::expr args[2] = {a, v1};
z3::expr fd1AV1 = fd1(2, args);
args[0] = a;
args[1] = b;
z3::expr noReo = noReoDecl(2, args);
args[0] = b;
args[1] = v2;
z3::expr fd2BV2 = fd2(2, args);
z3::expr bigAnd = fd1AV1 && fd2BV2;
z3::expr imp = z3::implies(bigAnd, noReo);
Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL);
}
// (=> (and (fd1 a)
// (fd2 b v))
// (noreorder a b)
void addNoReoFunc1Func2(z3::context &ctx, Z3_fixedpoint &zfp
, const z3::func_decl fd1, const z3::func_decl fd2) {
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort));
z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort));
z3::expr v = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort));
z3::func_decl noReoDecl = getNoReorderFuncDecl(ctx);
z3::expr args[2] = {a, v};
z3::expr fd1A = fd1(1, args); // v is not used in args here
args[0] = a;
args[1] = b;
z3::expr noReo = noReoDecl(2, args);
args[0] = b;
args[1] = v;
z3::expr fd2BV = fd2(2, args);
z3::expr bigAnd = fd1A && fd2BV;
z3::expr imp = z3::implies(bigAnd, noReo);
Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL);
}
// (=> (and (fd1 a v)
// (fd2 b))
// (noreorder a b)
void addNoReoFunc2Func1(z3::context &ctx, Z3_fixedpoint &zfp
, const z3::func_decl fd1, const z3::func_decl fd2) {
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort));
z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort));
z3::expr v = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort));
z3::func_decl noReoDecl = getNoReorderFuncDecl(ctx);
z3::expr args[2] = {a, v};
z3::expr fd1AV = fd1(2, args);
args[0] = a;
args[1] = b;
z3::expr noReo = noReoDecl(2, args);
args[0] = b;
z3::expr fd2B = fd2(1, args);
z3::expr bigAnd = fd1AV && fd2B;
z3::expr imp = z3::implies(bigAnd, noReo);
Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL);
}
// Order two statements based on program order and restricted based on two
// binary predicates with the passed variables as their second item.
// (=> (and (dom a b)
// (not-reach b a)
// (fd1 a v1)
// (fd2 b v2) )
// (mhb a b))
void addPOFunc2Func2MHB(z3::context &ctx, Z3_fixedpoint &zfp
, const z3::func_decl fd1, const z3::func_decl fd2
, const z3::expr v1, const z3::expr v2) {
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort));
z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort));
z3::func_decl domDecl = getDomFuncDecl(ctx);
z3::func_decl nrDecl = getNotReachFuncDecl(ctx);
z3::func_decl mhbDecl = getMHBFuncDecl(ctx);
// (dom a b)
// (mhb a b)
z3::expr args[2] = {a, b};
z3::expr domAB = domDecl(2, args);
z3::expr mhbAB = mhbDecl(2, args);
// (not-reach b a)
args[0] = b;
args[1] = a;
z3::expr nrBA = nrDecl(2, args);
// (fd1 a v1)
args[0] = a;
args[1] = v1;
z3::expr fd1AV1 = fd1(2, args);
// (fd2 b v2)
args[0] = b;
args[1] = v2;
z3::expr fd2BV2 = fd2(2, args);
// (and (dom a b)
// (not-reach b a)
// (fd1 a v1)
// (fs2 b v2))
z3::expr bigAnd = domAB && nrBA && fd1AV1 && fd2BV2;
z3::expr imp = z3::implies(bigAnd, mhbAB);
Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL);
}
// Order a store and load based on program-order and if they are to the same
// variable
// (=> (and (dom a b)
// (not-reach b a)
// (is-store a v)
// (is-load b v))
// (mhb a b))
void addStoreLoadMHB(z3::context &ctx, Z3_fixedpoint &zfp) {
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
z3::expr v = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort));
addPOFunc2Func2MHB(ctx, zfp, getStFuncDecl(ctx), getLdFuncDecl(ctx), v, v);
}
// Order a load and store based on program-order and if they are to the same
// variable
// (=> (and (dom a b)
// (not-reach b a)
// (is-load a v))
// (is-store b v)
// (mhb a b))
void addLoadStoreMHB(z3::context &ctx, Z3_fixedpoint &zfp) {
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
z3::expr v = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort));
addPOFunc2Func2MHB(ctx, zfp, getLdFuncDecl(ctx), getStFuncDecl(ctx), v, v);
}
void addLoadLoadMHB(z3::context &ctx, Z3_fixedpoint &zfp) {
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
z3::expr v = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort));
addPOFunc2Func2MHB(ctx, zfp, getLdFuncDecl(ctx), getLdFuncDecl(ctx), v, v);
}
// Add an ordering rule between two stores. If sameVar is true then the two
// stores are ordered based on the program-order and if they access the same
// variable (as on PSO). Otherwise, the stores may access any variable (as on
// TSO).
//
// That is:
//
// (=> (and (dom a b)
// (not-reach b a)
// (is-store a v1)
// (is-store b v2) )
// (mhb a b))
//
// Where v1 = v2 is sameVar is true
void addStoreStoreMHB(z3::context &ctx, Z3_fixedpoint &zfp, bool sameVar) {
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
z3::expr v1 = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort));
z3::expr v2 = v1;
if (!sameVar) {
v2 = z3::expr(ctx, Z3_mk_bound(ctx, 3, bvSort));
}
addPOFunc2Func2MHB(ctx, zfp, getStFuncDecl(ctx), getStFuncDecl(ctx), v1
, v2);
//z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
//z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort));
//z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort));
//z3::expr v1 = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort));
//
//z3::expr v2 = v1;
//if (!sameVar) {
// v2 = z3::expr(ctx, Z3_mk_bound(ctx, 3, bvSort));
//}
//z3::func_decl domDecl = getDomFuncDecl(ctx);
//z3::func_decl nrDecl = getNotReachFuncDecl(ctx);
//z3::func_decl stDecl = getStFuncDecl(ctx);
//z3::func_decl mhbDecl = getMHBFuncDecl(ctx);
//// (dom a b)
//// (mhb a b)
//z3::expr args[2] = {a, b};
//z3::expr domAB = domDecl(2, args);
//z3::expr mhbAB = mhbDecl(2, args);
//// (not-reach b a)
//args[0] = b;
//args[1] = a;
//z3::expr nrBA = nrDecl(2, args);
//// (is-store a v1)
//// (is-store b v2)
//args[0] = a;
//args[1] = v1;
//z3::expr isStAV1 = stDecl(2, args);
//args[0] = b;
//args[1] = v2;
//z3::expr isStBV2 = stDecl(2, args);
//// (and (dom a b)
//// (not-reach b a)
//// (is-store a _)
//// (is-store b _))
//z3::expr bigAnd = domAB && nrBA && isStAV1 && isStBV2;
//z3::expr imp = z3::implies(bigAnd, mhbAB);
//Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL);
}
// Return the first load, store, or terminator instruction in the basic
// block.
static Instruction *getFirstLoadStoreTerm(BasicBlock *b) {
assert(b && "NULL passed");
for (auto i = b->begin(), ie = b->end(); i != ie; ++i) {
Instruction *cur = &*i;
if (isa<LoadInst>(cur)) {
return cur;
}
else if (isa<StoreInst>(cur)) {
return cur;
}
}
// Reaching this point means the basicblock does not have any load or store
// instructions. So, just return the terminator
return b->getTerminator();
}
static Instruction *getFirstLoadStoreCallTerm(BasicBlock *b) {
assert(b && "NULL passed");
for (auto i = b->begin(), ie = b->end(); i != ie; ++i) {
Instruction *cur = &*i;
if (isa<LoadInst>(cur)) {
return cur;
}
else if (isa<StoreInst>(cur)) {
return cur;
}
else if (isa<CallInst>(cur)) {
return cur;
}
}
// Reaching this point means the basicblock does not have
// any load or store instructions. So, just return the terminator
return b->getTerminator();
}
static Instruction *getLastLoadStoreCallTerm(BasicBlock *b) {
assert(b && "NULL passed");
bool find = false;
Instruction *cur;
for (auto i = b->begin(), ie = b->end(); i != ie; ++i) {
cur = &*i;
if (isa<LoadInst>(cur)) {
find = true;
}
else if (isa<StoreInst>(cur)) {
find = true;
}
else if (isa<CallInst>(cur)) {
find = true;
}
}
if (find) {
return cur;
} else {
// Reaching this point means the basicblock does not have
// any load or store instructions. So, just return the front one
return &(b->front());
}
}
#if 0
// Given the passed basicblock, return, starting from the first, the loads
// and stores in the basicblock
static std::vector<Instruction *> getLoadStoreOrdered(BasicBlock *b) {
std::vector<Instruction *> ret;
for (auto i = b->begin(), ie = b->end(); i != ie; ++i) {
Instruction *cur = &*i;
if (isa<LoadInst>(cur)) {
DEBUG_MSG("[DEBUG] Found Load: " << cur << ": " << *cur << '\n');
ret.push_back(cur);
}
else if (isa<StoreInst>(cur)) {
DEBUG_MSG("[DEBUG] Found Store: " << cur << ": " << *cur << '\n');
ret.push_back(cur);
}
}
return ret;
}
#endif
static std::vector<Instruction *> getLoadStoreCallOrdered(BasicBlock *b) {
std::vector<Instruction *> ret;
for (auto i = b->begin(), ie = b->end(); i != ie; ++i) {
Instruction *cur = &*i;
if (isa<LoadInst>(cur)) {
DEBUG_MSG("[DEBUG] Found Load: " << cur << ": " << *cur << '\n');
ret.push_back(cur);
}
else if (isa<StoreInst>(cur)) {
DEBUG_MSG("[DEBUG] Found Store: " << cur << ": " << *cur << '\n');
ret.push_back(cur);
}
else if (isa<CallInst>(cur)) {
DEBUG_MSG("[DEBUG] Found Call" << cur << ": " << *cur << '\n');
ret.push_back(cur);
//DEBUG_MSG("[DEBUG] Found Store: " << cur << ": " << *cur << '\n');
//ret.push_back(cur);
}
}
return ret;
}
// Ensure the global command line flags are valid.
// This will crash with an error message if they are not
void checkCommandLineArgs() const {
// Atleast one abstract domain must be true
if (!useBoxG && !useOctG && !usePolyG && !useLinEqG) {
errs() << "[ERROR] Select an abstract domain (-box, -oct, -pkpoly "
<< "-pklineq)\n";
exit(EXIT_FAILURE);
}
// TSO and PSO cannot both be enabled at the same time
if (tsoConstrG && psoConstrG) {
errs() << "[ERROR] both -pso and -tso cannot be used\n";
exit(EXIT_FAILURE);
}
// Only one abstract domain should be selected
if ((useBoxG && (useOctG || usePolyG || useLinEqG))
|| (useOctG && (useBoxG || usePolyG || useLinEqG))
|| (usePolyG && (useBoxG || useOctG || useLinEqG))
|| (useLinEqG && (useBoxG || useOctG || usePolyG))) {
errs() << "[ERROR] More than one abstract domain selected\n";
exit(EXIT_FAILURE);
}
// The program-order constraint solver is only relevant in combinational
// exploration mode
if (useConstraintsG && noCombinsG) {
errs() << "[ERROR] Constraint solver mode (-constraints) must not use "
"-nocombs\n";
exit(EXIT_FAILURE);
}
// If we are using constraints, we need to know where Z3 lives
if (useConstraintsG && (z3BinLocG.size() == 0)) {
errs() << "[ERROR] -constraints without specify location of Z3 "
"(-z3 <loc>)\n";
exit(EXIT_FAILURE);
}
// Using constraints also uses dynamic thread init. Note: this is not
// strictly necessary.
if (useConstraintsG) {
dynInitG = true;
}
}
void printFuncInterfMap(
const std::map<Function *, std::map<Instruction *, LatticeFact>> fim) const {
for (auto i = fim.begin(), ie = fim.end(); i != ie; ++i) {
std::map<Instruction *, LatticeFact> stm = i->second;
for (auto j = stm.begin(), je = stm.end(); j != je; ++j) {
errs() << "Store: " << *(j->first) << '\n';
}
}
}
std::map<StoreInst *, LatticeFact> joinStFacts(
const std::map<StoreInst *, LatticeFact> m1
, const std::map<StoreInst *, LatticeFact> m2) const {
std::map<StoreInst *, LatticeFact> ret(m1);
for (auto i = m2.begin(), ie = m2.end(); i != ie; ++i) {
StoreInst *cur = i->first;
auto f = ret.find(cur);
if (f != ret.end()) {
LatticeFact newF = LatticeFact::factJoin(i->second, f->second);
ret.erase(cur);
ret.emplace(cur, newF);
}
else {
ret.emplace(cur, f->second);
}
}
return ret;
}
// Return the number of instructions in M
unsigned numInstructions(Module &M) {
unsigned n = 0;
for (auto mit = M.begin(), me = M.end(); mit != me; ++mit) {
Function &f = *mit;
for (inst_iterator ii = inst_begin(f), ie = inst_end(f); ii != ie
; ++ii) {
n++;
}
}
return n;
}
std::set<Instruction *> instsWithoutMetadata(Module &M, std::string md) {
assert(md.length() && "instsWithoutMetadata: length zero metadata");
std::set<Instruction *> ret;
return ret;
for (auto mit = M.begin(), me = M.end(); mit != me; ++mit) {
Function &f = *mit;
for (inst_iterator ii = inst_begin(f), ie = inst_end(f); ii != ie
; ++ii) {
Instruction *i = &*ii;
if (!i->getMetadata(md)) {
ret.insert(i);
}
}
}
return ret;
}
std::set<Instruction *> instsWithMetadata(Module &M, std::string md) {
assert(md.length() && "instsWithoutMetadata: length zero metadata");
std::set<Instruction *> ret;
for (auto mit = M.begin(), me = M.end(); mit != me; ++mit) {
Function &f = *mit;
for (inst_iterator ii = inst_begin(f), ie = inst_end(f); ii != ie
; ++ii) {
Instruction *i = &*ii;
if (i->getMetadata(md)) {
ret.insert(i);
}
}
}
return ret;
}
// If -impact is used then return the set of all statements in M which may
// impact a change.
//
// Otherwise, return an empty set
std::set<Instruction *> getMayImpactIfEnabled(Module &M) {
std::set<Instruction *> ret;
if (!impactG) {
return ret;
}
ret = instsWithMetadata(M, "MayImpact");
//if (ret.size() == 0) {
// errs() << "[ERROR] No may-impact statements found, did you run the change-impact pass?\n";
// exit(EXIT_FAILURE);
//}
return ret;
}
// If -impact is used then return the set of all statements in M which are
// impacted by a change.
//
// Otherwise, return an empty set
std::set<Instruction *> getImpactedIfEnabled(Module &M) {
std::set<Instruction *> ret;
if (!impactG) {
return ret;
}
ret = instsWithMetadata(M, "Impacted");
if (ret.size() == 0) {
errs() << "[ERROR] No impacted statements found, did you run the change-impact pass?\n";
exit(EXIT_FAILURE);
}
return ret;
}
// Return the inversion of the assertion slice if assertSliceG is true.
//
// The "slice inversion" is all the statements *not* on the slice.
//
// If assertSliceG is false then return an empty set.
std::set<Instruction *> getAssertSliceInvIfEnabled(Module &M) {
std::set<Instruction *> ret;
unsigned numInsts = numInstructions(M);
if (!assertSliceG) {
return ret; // size zero
}
ret = instsWithoutMetadata(M, "AssertSlice");
//for (auto mit = M.begin(), me = M.end(); mit != me; ++mit) {
// Function &f = *mit;
// for (inst_iterator ii = inst_begin(f), ie = inst_end(f); ii != ie
// ; ++ii) {
// numInsts++;
// Instruction *i = &*ii;
// if (!i->getMetadata("AssertSlice")) {
// ret.insert(i);
// }
// }
//}
//if (!ret.size()) {
if (numInsts == ret.size()) {
//errs() << "[ERROR] no statements found on slice of an assertion\n"
// "Are you sure the PDG pass has been run?\n";
errs() << "[ERROR] no statements not found on slice of an assertion\n"
"Are you sure the PDG pass has been run?\n";
exit(EXIT_FAILURE);
}
return ret;
}
};
char WorklistAI::ID = 0;
static RegisterPass<WorklistAI> X("worklist-ai"
, "worklist based abstract interpretation"
, false // unmodified CFG
, true); // analysis pass
| 170,444 | 59,236 |
#include <KYEngine/Core.h>
#include <KYEngine/SceneTimelineInfo.h>
#include <KYEngine/Utility/TiXmlHelper.h>
#include <KYEngine/Private/AnimSceneActions/UpdateEntitiesAction.h>
#include <cmath>
#include <iostream>
#include <stdexcept>
const std::string UpdateEntitiesAction::XML_NODE = "update-entities";
UpdateEntitiesAction::UpdateEntitiesAction()
{
}
UpdateEntitiesAction::~UpdateEntitiesAction()
{
}
UpdateEntitiesAction* UpdateEntitiesAction::readFromXml(TiXmlElement* node)
{
UpdateEntitiesAction* action = new UpdateEntitiesAction();
const std::string name = TiXmlHelper::readString(node, "name", false, "<<undefined>>");
action->setName(name);
TiXmlElement* curr = node->FirstChildElement();
while (curr) {
const std::string& value = curr->Value();
if (value == "add-entity") {
const std::string entityRef = TiXmlHelper::readString(node, "entity-ref", true);
action->addAddEntityRef(entityRef);
} else if (value == "remove-entity") {
const std::string entityRef = TiXmlHelper::readString(node, "entity-ref", true);
action->addRemoveEntityRef(entityRef);
} else
throw std::runtime_error("UpdateEntitiesAction: (" + name + ") tag error: " + value);
curr = curr->NextSiblingElement();
}
return action;
}
void UpdateEntitiesAction::start(SceneTimelineInfo* info)
{
std::list<Entity*> toAddEntities;
std::list<Entity*> toRemoveEntities;
for(std::list<std::string>::const_iterator it = m_toAddEntityRef.begin(); it != m_toAddEntityRef.end(); it++)
toAddEntities.push_back(Core::resourceManager().entity(*it));
for(std::list<std::string>::const_iterator it = m_toRemoveEntityRef.begin(); it != m_toRemoveEntityRef.end(); it++)
toRemoveEntities.push_back(Core::resourceManager().entity(*it));
info->layer()->updateEntities(toAddEntities, toRemoveEntities);
}
bool UpdateEntitiesAction::isBlocking()
{
return false;
}
bool UpdateEntitiesAction::isFinished()
{
return true;
}
void UpdateEntitiesAction::update(const double elapsedTime, SceneTimelineInfo* info)
{
}
| 2,122 | 679 |
/**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file profileTimer.cxx
*/
#include "profileTimer.h"
#include "pmap.h"
using namespace std;
// See ProfileTimer.h for documentation.
EXPCL_PANDAEXPRESS ProfileTimer Skyler_timer_global=ProfileTimer("startup");
ProfileTimer* ProfileTimer::_head;
ProfileTimer::
ProfileTimer(const char* name, int maxEntries) :
_entries(0),
_autoTimerCount(0) {
// Keep a list of the ProfileTimers, so we can print them:
_next=_head;
_head=this;
if (name) {
init(name, maxEntries);
}
}
ProfileTimer::
ProfileTimer(const ProfileTimer& other) {
// Add to list:
_next=_head;
_head=this;
// init it:
_name=other._name;
_maxEntries=other._maxEntries;
if (_name) {
init(_name, _maxEntries);
}
// Copy other entries:
_on=other._on;
_elapsedTime=other._elapsedTime;
_autoTimerCount=other._autoTimerCount;
_entryCount=other._entryCount;
if (other._entries) {
memcpy(_entries, other._entries, _entryCount * sizeof(TimerEntry));
}
}
ProfileTimer::
~ProfileTimer() {
PANDA_FREE_ARRAY(_entries);
// Remove this from the list:
if (_head==this) {
_head=_next;
} else {
ProfileTimer* p=_head;
ProfileTimer* prior=p;
while (p) {
if (p==this) {
prior->_next=_next;
break;
}
prior=p;
p=p->_next;
}
}
}
void ProfileTimer::
init(const char* name, int maxEntries) {
_name=name;
_maxEntries=maxEntries;
_entries = (TimerEntry *)PANDA_MALLOC_ARRAY(_maxEntries * sizeof(TimerEntry));
_entryCount=0;
_elapsedTime=0.0;
_on=0.0;
}
double ProfileTimer::
getTotalTime() const {
double total=0;
int i;
for (i=0; i<_entryCount; ++i) {
TimerEntry& te=_entries[i];
total+=te._time;
}
return total;
}
void ProfileTimer::
consolidateAllTo(ostream &out) {
ProfileTimer* p=_head;
while (p) {
p->consolidateTo(out);
p=p->_next;
}
}
void ProfileTimer::
consolidateTo(ostream &out) const {
pmap<string, double> entries;
int i;
for (i=0; i<_entryCount; ++i) {
TimerEntry& te=_entries[i];
entries[te._tag]+=te._time;
}
out << "-------------------------------------------------------------------\n"
<< "Profile Timing of " << _name
<< "\n\n"; // ...should print data and time too.
double total=0;
{
pmap<string, double>::const_iterator i=entries.begin();
for (;i!=entries.end(); ++i) {
out << " " << setw(50) << i->first << ": "
<< setiosflags(ios::fixed) << setprecision(6) << setw(10) << i->second << "\n";
total+=i->second;
}
}
out << "\n [Total Time: "
<< setiosflags(ios::fixed) << setprecision(6) << total
<< " seconds]\n"
<< "-------------------------------------------------------------------\n";
out << endl;
}
void ProfileTimer::
printAllTo(ostream &out) {
ProfileTimer* p=_head;
while (p) {
p->printTo(out);
p=p->_next;
}
}
void ProfileTimer::
printTo(ostream &out) const {
out << "-------------------------------------------------------------------\n"
<< "Profile Timing of " << _name
<< "\n\n"; // ...should print data and time too.
double total=0;
int i;
for (i=0; i<_entryCount; ++i) {
TimerEntry& te=_entries[i];
out << " " << setw(50) << te._tag << ": "
<< setiosflags(ios::fixed) << setprecision(6) << setw(10) << te._time << "\n";
total+=te._time;
}
out << "\n [Total Time: "
<< setiosflags(ios::fixed) << setprecision(6) << total
<< " seconds]\n"
<< "-------------------------------------------------------------------\n";
out << endl;
}
ProfileTimer::AutoTimer::AutoTimer(ProfileTimer& profile, const char* tag) :
_profile(profile) {
_tag=tag;
if (_profile._autoTimerCount) {
// ...this is a nested call to another AutoTimer. Assign the time to the
// prior AutoTimer:
_profile.mark(_profile._entries[_profile._entryCount-1]._tag);
} else {
// ...this is not a nested call.
_profile.mark("other");
}
// Tell the profile that it's in an AutoTimer:
++_profile._autoTimerCount;
_profile.mark(_tag);
}
| 4,349 | 1,537 |
#include "stdafx.h"
#include "HapticAssetTools.h"
#include "AssetToolsLibrary.h"
#define AS_TYPE(Type, Obj) reinterpret_cast<Type *>(Obj)
#define AS_CTYPE(Type, Obj) reinterpret_cast<const Type *>(Obj)
unsigned int NS_ASSETTOOLS_API NSAT_GetVersion(void)
{
return NS_ASSETTOOLS_VERSION;
}
int NSAT_IsCompatibleDLL(void)
{
unsigned int major = NSAT_GetVersion() >> 16;
return major == NS_ASSETTOOLS_VERSION_MAJOR;
}
NS_ASSETTOOLS_API NSAT_Context_t * __stdcall NSAT_Create()
{
return AS_TYPE(NSAT_Context_t, new AssetToolsLibrary());
}
NS_ASSETTOOLS_API int __stdcall NSAT_InitializeFromDirectory(NSAT_Context_t* context, const char * dir)
{
return AS_TYPE(AssetToolsLibrary, context)->InitializeFromDirectory(dir);
}
NS_ASSETTOOLS_API void __stdcall NSAT_Delete(NSAT_Context_t * context)
{
if (!context) {
return;
}
delete AS_TYPE(AssetToolsLibrary, context);
}
NS_ASSETTOOLS_API int __stdcall NSAT_RescanFilesystem(NSAT_Context_t * context)
{
return AS_TYPE(AssetToolsLibrary, context)->Rescan();
}
NS_ASSETTOOLS_API int __stdcall NSAT_CheckIfPackage(NSAT_Context_t* context, const char* dir, PackageInfo& info, bool& isPackage)
{
return AS_TYPE(AssetToolsLibrary, context)->CheckIfPackage(dir, info, isPackage);
}
NS_ASSETTOOLS_API char * __stdcall NSAT_GetError(NSAT_Context_t * context)
{
return AS_TYPE(AssetToolsLibrary, context)->GetError();
}
NS_ASSETTOOLS_API void __stdcall NSAT_FreeError(char * stringPointer)
{
delete[] stringPointer;
stringPointer = nullptr;
}
| 1,506 | 574 |
#include<stdio.h>
long long f[1000000];
int main()
{
int n;
long long sum=1,i=0;
while(sum<=1000000000)
{
f[i]=sum;
i++;
sum+=i;
}
scanf("%d",&n);
for(int i=0;i<n;i++)
{
int temp;
scanf("%d",&temp);
for(int j=0;j<=44721;j++)
{
if(f[j]==temp)
{
printf("1\n");
break;
}
if(f[j]>temp)
{
printf("0\n");
break;
}
}
}
return 0;
}
| 578 | 229 |
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <chrono>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <numbers>
#include "Solvers.h"
using vec2 = mth::vec2<double>;
namespace
{
static constexpr double TO = 4;
static constexpr double STEP = 1;
void error_callback(int error, char const* description)
{
std::cerr << "Error : " << description << std::endl;
}
vec2 Map(vec2 a)
{
/*
* 0, 1 -> -1, -1
* 4, e(4) -> 1, 1
*/
a.Y = (a.Y - 1) / (std::exp(TO) - 1) * 2 - 1;
a.X = a.X / TO * 2 - 1;
return a;
}
template<typename F>
void Draw(F const& f, double d, double U)
{
{
auto f0 = f(0);
auto v2 = Map(f(0));
glVertex2f(v2.X, v2.Y);
}
for (double i = 0; i <= U; i += d)
{
auto v2 = Map(f(d));
glVertex2f(v2.X, v2.Y);
}
}
double EDelta(double v, double h)
{
return v;
}
}
int main()
{
glfwSetErrorCallback(error_callback);
if (!glfwInit())
return 1;
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
GLFWwindow* window = glfwCreateWindow(640, 480, "spring pendulum", NULL, NULL);
if (!window)
{
glfwTerminate();
return 1;
}
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
if (auto err = glewInit(); err != GLEW_OK)
{
std::cerr << "glew init error " << glewGetErrorString(err) << std::endl;
return 1;
}
glClearColor(0, 0, 0, 0);
glEnable(GL_LINE_WIDTH);
while (!glfwWindowShouldClose(window))
{
int width, height;
glfwGetFramebufferSize(window, &width, &height);
glViewport(0, 0, width, height);
glClear(GL_COLOR_BUFFER_BIT);
glLineWidth(5);
glBegin(GL_LINE_STRIP);
{
glColor3f(1, 1, 1);
double cur = 0;
Draw([&](double d)
{
auto r = vec2(cur, std::exp(cur));
cur += d;
return r;
},
STEP,
TO);
}
glEnd();
glLineWidth(3);
glBegin(GL_LINE_STRIP);
{
glColor3f(0, 1, 0);
double cur = 0;
double prev = 1;
Draw([&](double d)
{
prev += Euler(EDelta, prev, d);
cur += d;
auto r = vec2(cur, prev);
return r;
},
STEP,
TO);
}
glEnd();
glBegin(GL_LINE_STRIP);
{
glColor3f(1, 0, 0);
double cur = 0;
double prev = 1;
Draw([&](double d)
{
prev += RungeKutta(EDelta, prev, d);
cur += d;
auto r = vec2(cur, prev);
return r;
},
STEP,
TO);
}
glEnd();
glBegin(GL_LINE_STRIP);
{
glColor3f(0.2, 0.2, 1);
double cur = 0;
double prev = 1;
Draw([&](double d)
{
prev += Midpoint(EDelta, prev, d);
cur += d;
auto r = vec2(cur, prev);
return r;
},
STEP,
TO);
}
glEnd();
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwDestroyWindow(window);
glfwTerminate();
}
| 2,771 | 1,466 |
#include "TechnicPage.h"
#include "ui_TechnicPage.h"
#include "PolycraftLauncher.h"
#include "dialogs/NewInstanceDialog.h"
TechnicPage::TechnicPage(NewInstanceDialog* dialog, QWidget *parent)
: QWidget(parent), ui(new Ui::TechnicPage), dialog(dialog)
{
ui->setupUi(this);
}
TechnicPage::~TechnicPage()
{
delete ui;
}
bool TechnicPage::shouldDisplay() const
{
return true;
}
void TechnicPage::openedImpl()
{
dialog->setSuggestedPack();
}
| 462 | 178 |
#include "rocksdb/rate_limiter.h"
#include "rocks/ctypes.hpp"
using namespace ROCKSDB_NAMESPACE;
using std::shared_ptr;
extern "C" {
// FIXME: leaks a ointer size
rocks_ratelimiter_t* rocks_ratelimiter_create(int64_t rate_bytes_per_sec, int64_t refill_period_us, int32_t fairness) {
rocks_ratelimiter_t* rate_limiter = new rocks_ratelimiter_t;
rate_limiter->rep.reset(NewGenericRateLimiter(rate_bytes_per_sec, refill_period_us, fairness));
return rate_limiter;
}
void rocks_ratelimiter_destroy(rocks_ratelimiter_t* limiter) { delete limiter; }
}
| 559 | 226 |
// Copyright (c) 2010 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 <errno.h>
#include <fcntl.h>
#include <sys/file.h>
#include "chrome/browser/process_singleton.h"
#include "base/eintr_wrapper.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/base/testing_profile.h"
#include "testing/platform_test.h"
namespace {
class ProcessSingletonMacTest : public PlatformTest {
public:
virtual void SetUp() {
PlatformTest::SetUp();
// Put the lock in a temporary directory. Doesn't need to be a
// full profile to test this code.
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
lock_path_ = temp_dir_.path().Append(chrome::kSingletonLockFilename);
}
virtual void TearDown() {
PlatformTest::TearDown();
// Verify that the lock was released.
EXPECT_FALSE(IsLocked());
}
// Return |true| if the file exists and is locked. Forces a failure
// in the containing test in case of error condition.
bool IsLocked() {
int fd = HANDLE_EINTR(open(lock_path_.value().c_str(), O_RDONLY));
if (fd == -1) {
EXPECT_EQ(ENOENT, errno) << "Unexpected error opening lockfile.";
return false;
}
file_util::ScopedFD auto_close(&fd);
int rc = HANDLE_EINTR(flock(fd, LOCK_EX|LOCK_NB));
// Got the lock, so it wasn't already locked. Close releases.
if (rc != -1)
return false;
// Someone else has the lock.
if (errno == EWOULDBLOCK)
return true;
EXPECT_EQ(EWOULDBLOCK, errno) << "Unexpected error acquiring lock.";
return false;
}
ScopedTempDir temp_dir_;
FilePath lock_path_;
};
// Test that the base case doesn't blow up.
TEST_F(ProcessSingletonMacTest, Basic) {
ProcessSingleton ps(temp_dir_.path());
EXPECT_FALSE(IsLocked());
EXPECT_TRUE(ps.Create());
EXPECT_TRUE(IsLocked());
ps.Cleanup();
EXPECT_FALSE(IsLocked());
}
// The destructor should release the lock.
TEST_F(ProcessSingletonMacTest, DestructorReleases) {
EXPECT_FALSE(IsLocked());
{
ProcessSingleton ps(temp_dir_.path());
EXPECT_TRUE(ps.Create());
EXPECT_TRUE(IsLocked());
}
EXPECT_FALSE(IsLocked());
}
// Multiple singletons should interlock appropriately.
TEST_F(ProcessSingletonMacTest, Interlock) {
ProcessSingleton ps1(temp_dir_.path());
ProcessSingleton ps2(temp_dir_.path());
// Windows and Linux use a command-line flag to suppress this, but
// it is on a sub-process so the scope is contained. Rather than
// add additional API to process_singleton.h in an #ifdef, just tell
// the reader what to expect and move on.
LOG(ERROR) << "Expect two failures to obtain the lock.";
// When |ps1| has the lock, |ps2| cannot get it.
EXPECT_FALSE(IsLocked());
EXPECT_TRUE(ps1.Create());
EXPECT_TRUE(IsLocked());
EXPECT_FALSE(ps2.Create());
ps1.Cleanup();
// And when |ps2| has the lock, |ps1| cannot get it.
EXPECT_FALSE(IsLocked());
EXPECT_TRUE(ps2.Create());
EXPECT_TRUE(IsLocked());
EXPECT_FALSE(ps1.Create());
ps2.Cleanup();
EXPECT_FALSE(IsLocked());
}
// Like |Interlock| test, but via |NotifyOtherProcessOrCreate()|.
TEST_F(ProcessSingletonMacTest, NotifyOtherProcessOrCreate) {
ProcessSingleton ps1(temp_dir_.path());
ProcessSingleton ps2(temp_dir_.path());
// Windows and Linux use a command-line flag to suppress this, but
// it is on a sub-process so the scope is contained. Rather than
// add additional API to process_singleton.h in an #ifdef, just tell
// the reader what to expect and move on.
LOG(ERROR) << "Expect two failures to obtain the lock.";
// When |ps1| has the lock, |ps2| cannot get it.
EXPECT_FALSE(IsLocked());
EXPECT_EQ(ProcessSingleton::PROCESS_NONE, ps1.NotifyOtherProcessOrCreate());
EXPECT_TRUE(IsLocked());
EXPECT_EQ(ProcessSingleton::PROFILE_IN_USE, ps2.NotifyOtherProcessOrCreate());
ps1.Cleanup();
// And when |ps2| has the lock, |ps1| cannot get it.
EXPECT_FALSE(IsLocked());
EXPECT_EQ(ProcessSingleton::PROCESS_NONE, ps2.NotifyOtherProcessOrCreate());
EXPECT_TRUE(IsLocked());
EXPECT_EQ(ProcessSingleton::PROFILE_IN_USE, ps1.NotifyOtherProcessOrCreate());
ps2.Cleanup();
EXPECT_FALSE(IsLocked());
}
// TODO(shess): Test that the lock is released when the process dies.
// DEATH_TEST? I don't know. If the code to communicate between
// browser processes is ever written, this all would need to be tested
// more like the other platforms, in which case it would be easy.
} // namespace
| 4,647 | 1,631 |
/* PureBasic Engine3D licence
* --------------------------
*
* MIT License
*
* Copyright (c) 2017 Jerome Ortali
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "Event.hpp"
///////////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////////
PB_EventHandler::PB_EventHandler(Urho3D::Context* context) : Urho3D::Object(context) {
SubscribeToEvent(Urho3D::E_KEYDOWN, URHO3D_HANDLER(PB_EventHandler, ev_KeyDown));
SubscribeToEvent(Urho3D::E_KEYUP, URHO3D_HANDLER(PB_EventHandler, ev_KeyUp));
SubscribeToEvent(Urho3D::E_MOUSEBUTTONDOWN, URHO3D_HANDLER(PB_EventHandler, ev_MouseButtonDown));
SubscribeToEvent(Urho3D::E_MOUSEBUTTONUP, URHO3D_HANDLER(PB_EventHandler, ev_MouseButtonUp));
SubscribeToEvent(Urho3D::E_MOUSEMOVE, URHO3D_HANDLER(PB_EventHandler, ev_MouseMove));
SubscribeToEvent(Urho3D::E_MOUSEWHEEL, URHO3D_HANDLER(PB_EventHandler, ev_MouseWheel));
SubscribeToEvent(Urho3D::E_RESOURCEBACKGROUNDLOADED, URHO3D_HANDLER(PB_EventHandler, ev_BackgroundLoadResource));
SubscribeToEvent(Urho3D::E_FILECHANGED, URHO3D_HANDLER(PB_EventHandler, ev_ResourceFileChange));
attachObserver(this);
}
///////////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////////
void PB_EventHandler::ev_KeyDown(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData) {
Event event;
event.type = keyDown;
event.key.key = eventData[Urho3D::KeyDown::P_KEY].GetInt();
event.key.scancode = eventData[Urho3D::KeyDown::P_SCANCODE].GetInt();
event.key.buttons = eventData[Urho3D::KeyDown::P_BUTTONS].GetInt();
event.key.qualifiers = eventData[Urho3D::KeyDown::P_QUALIFIERS].GetInt();
event.key.repeat = eventData[Urho3D::KeyDown::P_REPEAT].GetInt();
notifyObservers((int)event.type, &event, sizeof(Event));
PB_EVENT->push(event);
}
///////////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////////
void PB_EventHandler::ev_KeyUp(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData) {
Event event;
event.type = keyUp;
event.key.key = eventData[Urho3D::KeyUp::P_KEY].GetInt();
event.key.scancode = eventData[Urho3D::KeyUp::P_SCANCODE].GetInt();
event.key.buttons = eventData[Urho3D::KeyUp::P_BUTTONS].GetInt();
event.key.qualifiers = eventData[Urho3D::KeyUp::P_QUALIFIERS].GetInt();
event.key.repeat = 0;
notifyObservers((int)event.type, &event, sizeof(Event));
PB_EVENT->push(event);
}
///////////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////////
void PB_EventHandler::ev_MouseButtonDown(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData) {
Event event;
event.type = mouseButtonDown;
event.mousebutton.button = eventData[Urho3D::MouseButtonDown::P_BUTTON].GetInt();
event.mousebutton.buttons = eventData[Urho3D::MouseButtonDown::P_BUTTONS].GetInt();
event.mousebutton.qualifiers = eventData[Urho3D::MouseButtonDown::P_QUALIFIERS].GetInt();
notifyObservers((int)event.type, &event, sizeof(Event));
PB_EVENT->push(event);
}
///////////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////////
void PB_EventHandler::ev_MouseButtonUp(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData) {
Event event;
event.type = mouseButtonUp;
event.mousebutton.button = eventData[Urho3D::MouseButtonUp::P_BUTTON].GetInt();
event.mousebutton.buttons = eventData[Urho3D::MouseButtonUp::P_BUTTONS].GetInt();
event.mousebutton.qualifiers = eventData[Urho3D::MouseButtonUp::P_QUALIFIERS].GetInt();
notifyObservers((int)event.type, &event, sizeof(Event));
PB_EVENT->push(event);
}
///////////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////////
void PB_EventHandler::ev_MouseMove(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData) {
Event event;
event.type = mouseMove;
event.mousemove.x = eventData[Urho3D::MouseMove::P_X].GetInt();
event.mousemove.y = eventData[Urho3D::MouseMove::P_Y].GetInt();
event.mousemove.dx = eventData[Urho3D::MouseMove::P_DX].GetInt();
event.mousemove.dy = eventData[Urho3D::MouseMove::P_DY].GetInt();
event.mousemove.buttons = eventData[Urho3D::MouseMove::P_BUTTONS].GetInt();
event.mousemove.qualifiers = eventData[Urho3D::MouseMove::P_QUALIFIERS].GetInt();
notifyObservers((int)event.type, &event, sizeof(Event));
PB_EVENT->push(event);
}
///////////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////////
void PB_EventHandler::ev_MouseWheel(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData) {
Event event;
event.type = mouseWheel;
event.mousewheel.wheel = eventData[Urho3D::MouseWheel::P_WHEEL].GetInt();
event.mousewheel.buttons = eventData[Urho3D::MouseWheel::P_BUTTONS].GetInt();
event.mousewheel.qualifiers = eventData[Urho3D::MouseWheel::P_QUALIFIERS].GetInt();
notifyObservers((int)event.type, &event, sizeof(Event));
PB_EVENT->push(event);
}
///////////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////////
void PB_EventHandler::ev_BackgroundLoadResource(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData) {
Event event;
event.type = backgroundResourceLoaded;
event.resourceLoaded.name = (wchar_t*)Urho3D::WString( eventData[Urho3D::ResourceBackgroundLoaded::P_RESOURCENAME].GetString() ).CString();
event.resourceLoaded.success = (int) eventData[Urho3D::ResourceBackgroundLoaded::P_SUCCESS].GetBool();
event.resourceLoaded.resource = (void*) eventData[Urho3D::ResourceBackgroundLoaded::P_RESOURCE].GetPtr();
notifyObservers((int)event.type, &event, sizeof(Event));
PB_EVENT->push(event);
}
///////////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////////
void PB_EventHandler::ev_ResourceFileChange(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData) {
Event event;
event.type = resourceFileChange;
event.resourceFileChange.resourceName = (wchar_t*)Urho3D::WString(eventData[Urho3D::FileChanged::P_RESOURCENAME].GetString()).CString();
event.resourceFileChange.fileName = (wchar_t*)Urho3D::WString(eventData[Urho3D::FileChanged::P_FILENAME].GetString()).CString();
notifyObservers((int)event.type, &event, sizeof(Event));
PB_EVENT->push(event);
}
///////////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////////
void PB_EventHandler::notify(int what, void* data, int size) {
for (auto & m : m_bindfunction) {
if (what == m.first) {
Event &event = *(Event*)data;
(*m.second)(&event);
}
}
}
///////////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////////
void PB_EventHandler::bindFunction(EventType type, fn_callback callback) {
auto found = m_bindfunction.find(type);
if (found == m_bindfunction.end()) {
m_bindfunction.emplace(type, callback);
}
}
///////////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////////
void PB_EventHandler::unBindFunction(EventType type, fn_callback) {
auto found = m_bindfunction.find(type);
if (found != m_bindfunction.end()) {
m_bindfunction.erase(found);
}
}
///////////////////////////////////////////////////////////////////////////////
// EXPORTED FUNCTIONS
///////////////////////////////////////////////////////////////////////////////
PB_FUNCTION(int) uh3_PoolEvent(Event* ev) {
if (PB_EVENT->size()) {
*ev = PB_EVENT->front();
PB_EVENT->pop();
return 1;
}
return 0;
}
///////////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////////
PB_FUNCTION(void) uh3_BindEvent(int type, void* callback) {
PB_URHOEVENT->bindFunction((EventType)type, (PB_EventHandler::fn_callback)callback);
}
///////////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////////
PB_FUNCTION(void) uh3_UnBindEvent(int type, void* callback) {
PB_URHOEVENT->unBindFunction((EventType)type, (PB_EventHandler::fn_callback)callback);
} | 10,117 | 3,386 |
#include <gtest/gtest.h>
#include "uuid.hpp"
namespace {
TEST(global, round_trip) {
std::string res = get_uuid();
const std::string hex_chars("0123456789ABCDEF");
for (uint cntr = 0; cntr < 36; cntr++) {
if ((cntr == 8) || (cntr == 13) || (cntr == 18) || (cntr == 23)) {
EXPECT_EQ('-', res[cntr]);
} else {
EXPECT_NE(hex_chars.find(res[cntr]), std::string::npos);
}
}
}
}
| 428 | 195 |
// jhcExpVSrc.cpp : iterator for shoveling images to analysis programs
//
// Written by Jonathan H. Connell, jconnell@alum.mit.edu
//
///////////////////////////////////////////////////////////////////////////
//
// Copyright 1998-2014 IBM Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////////
#include "Interface/jhcString.h"
#include "Interface/jhcPickStep.h"
#include "Interface/jhcPickVals.h"
#include "Interface/jhcPickString.h"
#include "Video/jhcVidReg.h"
#include "Video/jhcExpVSrc.h"
//////////////////////////////////////////////////////////////////////////////
// Basic creation and deletion //
//////////////////////////////////////////////////////////////////////////////
//= Constructor makes up a stream of the requested class.
jhcExpVSrc::jhcExpVSrc ()
{
noisy = 1;
index = 1;
Defaults();
}
//= Constructor that takes file name at creation time.
jhcExpVSrc::jhcExpVSrc (const char *name) : jhcGenVSrc(name)
{
noisy = 1;
index = 1;
Defaults();
SetSize(0, 0, 0);
}
//= Need to size internal array properly when source is changed.
int jhcExpVSrc::SetSource (const char *name)
{
if (jhcGenVSrc::SetSource(name) != 1)
return 0;
SetSize(xlim, ylim, Mono);
return 1;
}
//////////////////////////////////////////////////////////////////////////////
// Configuration Parameters //
//////////////////////////////////////////////////////////////////////////////
//= Pop dialog box asking for playback parameters.
// force stream to new values if not already there
// returns 1 if some alteration might have been made
int jhcExpVSrc::AskStep ()
{
jhcPickStep dlg;
double new_fps;
// run dialog box
if (dlg.EditStep(play, freq) < 1)
return 0;
// ask for new framerate directly from source
new_fps = freq / DispRate;
SetRate(new_fps);
DispRate = freq / new_fps;
// adjust frame stepping parameters
SetStep(Increment, ByKey);
if ((nextread < 1) ||
((nframes > 0) && (nextread > nframes)) ||
((FirstFrame > 0) && (nextread < FirstFrame)) ||
((LastFrame > 0) && (nextread > LastFrame)))
Rewind();
return 1;
}
//= Pop dialog box asking for image resizing parameters.
// returns 1 if some alteration might have been made
int jhcExpVSrc::AskSize ()
{
jhcPickVals dlg;
if (dlg.EditParams(squash) < 1)
return 0;
SetSize(xlim, ylim, Mono);
return 1;
}
//= Ask user to given a textual specification of the stream he wants.
// returns 1 if some alteration might have been made
int jhcExpVSrc::AskSource ()
{
jhcPickString dlg;
char fname[250];
strcpy0(fname, FileName, 250);
if (dlg.EditString(fname, 0, "Video source file:", 250) < 1)
return 0;
SetSource(fname);
return 1;
}
//= Ask user to choose new file for stream.
// will copy choice into string if one is provided
// returns 1 if a was file selected, 0 if user cancelled
int jhcExpVSrc::SelectFile (char *choice, int ssz)
{
CFileDialog dlg(TRUE);
OPENFILENAME *vals = &(dlg.m_ofn);
const char *filter;
jhcString kinds, sel, idir(JustDir);
int len;
if (_stricmp(Flavor, "vfw") != 0)
vals->lpstrInitialDir = idir.Txt();
filter = jvreg.FilterTxt(0, &len);
kinds.Set(filter, len);
vals->lpstrFilter = kinds.Txt();
if (dlg.DoModal() == IDOK)
{
sel.Set(vals->lpstrFile);
SetSource(sel.ch);
if (choice != NULL)
strcpy_s(choice, ssz, sel.ch);
return 1;
}
return 0;
}
//= Configure pointers and default values pairings.
// load new defaults from a file (if any)
void jhcExpVSrc::Defaults (char *fname)
{
squash.SetTag("vid_size");
squash.ClearAll();
squash.NextSpec4( &xlim, 0, "Max width");
squash.NextSpec4( &ylim, 0, "Max height");
squash.NextSpec4( &Avg, 0, "Averaging style");
squash.NextSpec4( &Mono, 0, "Monochrome style");
squash.NextSpec4( &Quad, 0, "Extracted quadrant");
squash.NextSpec4( &Shift, 0, "Downshift pixels"); // only for Kinect
squash.NextSpec4( &w, 0, "Current width");
squash.NextSpec4( &h, 0, "Current height");
// some things are for display purposes only
play.LockMatch( &w, 1);
play.LockMatch( &h, 1);
// get values from file (if any)
squash.LoadDefs(fname);
squash.RevertAll();
play.LoadDefs(fname);
play.RevertAll();
}
//= Save current values out as a defaults in specified file.
void jhcExpVSrc::SaveVals (char *fname)
{
squash.SaveVals(fname);
play.SaveVals(fname);
}
//////////////////////////////////////////////////////////////////////////////
// Core Functions //
//////////////////////////////////////////////////////////////////////////////
//= Force width, height, and base image to be consistent with these values.
// sometimes underlying stream or desired size is changed asynchronously
// can optionally request that frames be converted to monochrome (bw nonzero)
// should call this when quadrant processing is selected or deselected
// a positive quadrant picks that number, negative picks left or right side
// @see Processing.jhcGray#ForceMono
void jhcExpVSrc::SetSize (int xmax, int ymax, int bw)
{
int xreq = xmax, yreq = ymax;
double f = 1.0, f2 = 1.0;
// adjust total image size if request is for one panel
if (Quad > 0)
{
xreq *= 2;
yreq *= 2;
}
else if (Quad < 0)
xreq *= 2;
// see if source can shrink images directly via partial decoding
jhcGenVSrc::SetSize(xreq, yreq, bw);
base.SetSize(w, h, d);
base2.SetSize(w2, h2, d2);
// figure out additional shrink factor needed using new w and h
if (xreq > 0)
f = w / (double) xreq;
if (yreq > 0)
f2 = h / (double) yreq;
if ((f > 1.0) || (f2 > 1.0))
f = __max(f, f2);
else
f = __min(f, f2);
// determine size of one quadrant (or possibly whole image)
if (Quad > 0)
{
w /= 2;
h /= 2;
w2 /= 2;
h2 /= 2;
}
else if (Quad < 0)
{
w /= 2;
w2 /= 2;
}
qbase.SetSize(w, h, d);
qbase.SetSize(w2, h2, d2);
// mark whether monochrome conversion needed
// special negative Mono mode makes RGB with all equal
mc = 1;
if (Mono < 0)
{
d = 3;
if (d2 == 3)
d2 = 3;
}
else if ((Mono > 0) && (d == 3))
{
d = 1;
if (d2 == 3)
d2 = 1;
}
else
mc = 0;
mbase.SetSize(w, h, d);
mbase2.SetSize(w2, h2, d2);
// always promise to finally generate size that user asked for
w = ROUND(w / f);
h = ROUND(h / f);
w2 = ROUND(w2 / f);
h2 = ROUND(h2 / f);
}
//= Pass through to underlying video stream, reset pause counter.
int jhcExpVSrc::iSeek (int number)
{
int ans;
if (gvid == NULL)
return 0;
ans = gvid->Seek(number);
ok = gvid->Valid();
return ans;
}
//= Try retrieving next image and possibly resizing it.
// tell actual number of frames advanced
// captures into base, gets quad into qbase, gets mono into mbase
int jhcExpVSrc::iGet (jhcImg& dest, int *advance, int src)
{
int ans;
jhcImg *b = ((src > 0) ? &base2 : &base);
jhcImg *q = ((src > 0) ? &qbase2 : &qbase);
jhcImg *m = ((src > 0) ? &mbase2 : &mbase);
jhcImg *s = b;
// communicate possible auto-looping
if (gvid == NULL)
return 0;
gvid->LastFrame = LastFrame;
// get basic frame into base image or directly into output
// if (dest.SameFormat(base) && (mc <= 0))
if ((xlim <= 0) && (ylim <= 0) && (Mono == 0))
{
s = &dest;
ans = gvid->Get(*s, src);
b->SetSize(*s); // for jhcListVSrc where frames change size
dest.SetSize(*b);
}
else
ans = gvid->Get(*s, src);
// determine amount actually advanced
ok = gvid->Valid();
if (ok > 0)
*advance = gvid->Advance(); // extract "n"
else
*advance = 0;
ParseName(gvid->File());
// possibly abort if frame fetch failed or no alterations needed
if ((ans <= 0) || (s == &dest))
return ans;
// see if should get only a quadrant or one side of the image
if (Quad > 0)
{
if (dest.SameFormat(*q) && (mc <= 0))
return jr.GetQuad(dest, *s, Quad);
jr.GetQuad(*q, *s, Quad);
s = q;
}
else if (Quad < 0)
{
if (dest.SameFormat(*q) && (mc <= 0))
return jr.GetHalf(dest, *s, -Quad);
jr.GetHalf(*q, *s, -Quad);
s = q;
}
// see if color to monochrome conversion needed
if (mc > 0)
{
if (dest.SameFormat(*m))
return jg.ForceMono(dest, *s, abs(Mono));
jg.ForceMono(*m, *s, abs(Mono));
s = m;
}
// do further down-sizing as required
return jr.ForceSize(dest, *s, Avg);
}
//= Get next pair of images from source.
// NOTE: ignores any resizing
int jhcExpVSrc::iDual (jhcImg& dest, jhcImg& dest2)
{
int ans;
// communicate possible auto-looping
if (gvid == NULL)
return 0;
gvid->LastFrame = LastFrame;
// get basic frames directly
ans = gvid->DualGet(dest, dest2);
ParseName(gvid->File());
if (ans <= 0)
return ans;
return 1;
}
| 9,585 | 3,555 |
#include "imodule.hh"
#include <cassert>
#include <utils/cli/err.hh>
namespace {
bool is_branch(const Ins &ins) {
const auto &opname = ins.args[0];
return opname == "b" || opname == "beq" || opname == "ret";
}
} // namespace
void BasicBlock::check() const {
for (std::size_t i = 0; i < _ins.size(); ++i) {
const auto &ins = _ins[i];
PANIC_IF(is_branch(ins) && i + 1 < _ins.size(),
"branch instruction forbidden in the middle of a basicblock");
PANIC_IF(!is_branch(ins) && i + 1 == _ins.size(),
"last instruction must must be a branch");
// @TODO Check if branch to a basicblock
const auto &op = ins.args[0];
if (op == "b")
PANIC_IF(!_mod.get_bb(ins.args[1].substr(1)), "b: invalid label name");
else if (op == "beq") {
PANIC_IF(!_mod.get_bb(ins.args[3].substr(1)) ||
!_mod.get_bb(ins.args[4].substr(1)),
"beq: invalid label name");
}
}
}
IModule::IModule() : _bb_entry(nullptr), _bb_next_id(0) {}
void IModule::check() const {
PANIC_IF(_bb_entry == nullptr, "Entry BB not set");
for (const auto &bb : _bbs_list)
bb->check();
}
std::vector<BasicBlock *> IModule::bb_list() {
std::vector<BasicBlock *> res;
for (auto &bb : _bbs_list)
res.push_back(bb.get());
return res;
}
std::vector<const BasicBlock *> IModule::bb_list() const {
std::vector<const BasicBlock *> res;
for (const auto &bb : _bbs_list)
res.push_back(bb.get());
return res;
}
BasicBlock *IModule::get_bb(bb_id_t id) {
auto it = _bbs_idsm.find(id);
return it == _bbs_idsm.end() ? nullptr : it->second;
}
BasicBlock *IModule::get_bb(const std::string &label) {
auto it = _bbs_labelsm.find(label);
return it == _bbs_labelsm.end() ? nullptr : it->second;
}
const BasicBlock *IModule::get_bb(bb_id_t id) const {
auto it = _bbs_idsm.find(id);
return it == _bbs_idsm.end() ? nullptr : it->second;
}
const BasicBlock *IModule::get_bb(const std::string &label) const {
auto it = _bbs_labelsm.find(label);
return it == _bbs_labelsm.end() ? nullptr : it->second;
}
BasicBlock &IModule::add_bb(const std::string &label) {
auto id = _bb_next_id++;
std::string cpy_label = label.empty() ? ".L" + std::to_string(id) : label;
_bbs_list.emplace_back(
new BasicBlock(*this, id, cpy_label, std::vector<Ins>{}));
BasicBlock *bb = _bbs_list.back().get();
_bbs_idsm.emplace(id, bb);
_bbs_labelsm.emplace(cpy_label, bb);
return *bb;
}
std::unique_ptr<IModule> mod2imod(const Module &mod) {
auto res = std::make_unique<IModule>();
assert(mod.code.size() > 0);
// Add special basic block jumping to code beginning
auto mod_entry = mod.code[0];
if (mod_entry.label_defs.empty())
mod_entry.label_defs.push_back("_start");
auto &entry_bb = res->add_bb("_entry");
entry_bb.ins().push_back(Ins::parse("b @" + mod_entry.label_defs[0]));
res->set_entry_bb(entry_bb);
BasicBlock *next_bb = nullptr;
// Make list of all bbs (divide by branch instructions)
for (const auto &ins : mod.code) {
if (next_bb == nullptr) {
auto label = ins.label_defs.size() > 0 ? ins.label_defs[0] : "";
next_bb = &res->add_bb(label);
}
next_bb->ins().push_back(ins);
if (is_branch(ins)) // end of basic block
next_bb = nullptr;
}
// Check module is well formed
PANIC_IF(next_bb != nullptr, "Last instruction in module isn't a branch");
res->check();
return res;
}
Module imod2mod(const IModule &mod) {
Module res;
for (const auto &bb : mod.bb_list()) {
auto first =
res.code.insert(res.code.end(), bb->ins().begin(), bb->ins().end());
first->label_defs = {bb->label()};
std::size_t first_idx = &*first - &res.code[0];
res.labels.emplace(bb->label(), first_idx);
}
return res;
}
| 3,793 | 1,482 |
#include <iostream>
using namespace std;
int main () {
int f,c;
cin >> f >> c;
char num;
int total=0;
for (int i=0;i<f;i++) {
for (int j=0;j<c;j++) {
char num;
cin >> num;
total+=num-'0';
}
}
cout << total << endl;
} | 241 | 124 |
/*******************************************************************\
Module: abstract events
Author: Vincent Nimal
Date: 2012
\*******************************************************************/
/// \file
/// abstract events
#include "abstract_event.h"
bool abstract_eventt::unsafe_pair_lwfence_param(const abstract_eventt &next,
memory_modelt model,
bool lwsync_met) const
{
/* pairs with fences are not properly pairs */
if(operation==operationt::Fence || next.operation==operationt::Fence
|| operation==operationt::Lwfence || next.operation==operationt::Lwfence
|| operation==operationt::ASMfence || next.operation==operationt::ASMfence)
return false;
/* pairs of shared variables */
if(local || next.local)
return false;
switch(model)
{
case TSO:
return (thread==next.thread &&
operation==operationt::Write &&
next.operation==operationt::Read);
case PSO:
return (thread==next.thread && operation==operationt::Write
/* lwsyncWW -> mfenceWW */
&& !(operation==operationt::Write &&
next.operation==operationt::Write &&
lwsync_met));
case RMO:
return
thread==next.thread &&
/* lwsyncWW -> mfenceWW */
!(operation==operationt::Write &&
next.operation==operationt::Write &&
lwsync_met) &&
/* lwsyncRW -> mfenceRW */
!(operation==operationt::Read &&
next.operation==operationt::Write &&
lwsync_met) &&
/* lwsyncRR -> mfenceRR */
!(operation==operationt::Read &&
next.operation==operationt::Read &&
lwsync_met) &&
/* if posWW, wsi maintained by the processor */
!(variable==next.variable &&
operation==operationt::Write &&
next.operation==operationt::Write) &&
/* if posRW, fri maintained by the processor */
!(variable==next.variable &&
operation==operationt::Read &&
next.operation==operationt::Write);
case Power:
return ((thread==next.thread
/* lwsyncWW -> mfenceWW */
&& !(operation==operationt::Write &&
next.operation==operationt::Write &&
lwsync_met)
/* lwsyncRW -> mfenceRW */
&& !(operation==operationt::Read &&
next.operation==operationt::Write &&
lwsync_met)
/* lwsyncRR -> mfenceRR */
&& !(operation==operationt::Read &&
next.operation==operationt::Read &&
lwsync_met)
/* if posWW, wsi maintained by the processor */
&& (variable!=next.variable ||
operation!=operationt::Write ||
next.operation!=operationt::Write))
/* rfe */
|| (thread!=next.thread &&
operation==operationt::Write &&
next.operation==operationt::Read &&
variable==next.variable));
case Unknown:
{
}
}
assert(false);
/* unknown memory model */
return true;
}
bool abstract_eventt::unsafe_pair_asm(const abstract_eventt &next,
memory_modelt model,
unsigned char met) const
{
/* pairs with fences are not properly pairs */
if(operation==operationt::Fence ||
next.operation==operationt::Fence ||
operation==operationt::Lwfence ||
next.operation==operationt::Lwfence ||
operation==operationt::ASMfence ||
next.operation==operationt::ASMfence)
return false;
/* pairs of shared variables */
if(local || next.local)
return false;
switch(model)
{
case TSO:
return (thread==next.thread &&
operation==operationt::Write &&
next.operation==operationt::Read &&
(met&1)==0);
case PSO:
return (thread==next.thread &&
operation==operationt::Write &&
(met&3)==0);
case RMO:
return
thread==next.thread &&
(met&15)==0 &&
/* if posWW, wsi maintained by the processor */
!(variable==next.variable &&
operation==operationt::Write &&
next.operation==operationt::Write) &&
/* if posRW, fri maintained by the processor */
!(variable==next.variable &&
operation==operationt::Read &&
next.operation==operationt::Write);
case Power:
return
(thread==next.thread &&
(met&15)==0 &&
/* if posWW, wsi maintained by the processor */
(variable!=next.variable ||
operation!=operationt::Write ||
next.operation!=operationt::Write)) ||
/* rfe */
(thread!=next.thread &&
operation==operationt::Write &&
next.operation==operationt::Read &&
variable==next.variable);
case Unknown:
{
}
}
assert(false);
/* unknown memory model */
return true;
}
| 4,648 | 1,376 |
//====================================================================================
//Plane.cpp : plane geometry implementation
//
//This code is part of Anubis Engine.
//
//Anubis Engine is a free game engine created as a fan project to be
//awesome platform for developing games!
//
//All sources can be found here:
// https://github.com/Dgek/Anubis-Engine
//
//Demos based on Anubis Engine can be found here:
// https://github.com/Dgek/Demos
//
//Copyright (c) 2013, Muralev Evgeny
//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 Minotower Games 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 MURALEV EVGENY "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 MURALEV EVGENY 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 "Math_pch.h"
#include "Plane.h"
using namespace Anubis;
bool Plane::Inside(const Vec & point) const
{
AREAL dist = Dot(Normal(), point) + D();
return (dist >= 0.0f);
}
bool Plane::Inside(const Vec & point, const AREAL radius) const
{
float dist = Dot(Normal(), point) + D();
// if this distance is < -radius, we are outside
return (dist >= -radius);
}
Vec Plane::Normal() const { return Vector(getx(&m_coeff), gety(&m_coeff), getz(&m_coeff), 0); }
AREAL32 Plane::D() const { return getw(&m_coeff); } | 2,551 | 857 |
#include <configure/bind.hpp>
#include <configure/bind/path_utils.hpp>
#include <configure/Filesystem.hpp>
#include <configure/lua/State.hpp>
#include <configure/lua/Type.hpp>
#include <configure/Node.hpp>
#include <configure/bind/path_utils.hpp>
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
namespace configure {
static int fs_glob(lua_State* state)
{
Filesystem& self = lua::Converter<std::reference_wrapper<Filesystem>>::extract(state, 1);
std::vector<NodePtr> res;
if (lua_gettop(state) == 3)
{
res = self.glob(
utils::extract_path(state, 2),
lua::Converter<std::string>::extract(state, 3)
);
}
else if (char const* arg = lua_tostring(state, 2))
{
res = self.glob(arg);
}
else
CONFIGURE_THROW(
error::InvalidArgument("Expected a glob pattern")
);
lua_createtable(state, res.size(), 0);
for (int i = 0, len = res.size(); i < len; ++i)
{
lua::Converter<NodePtr>::push(state, res[i]);
lua_rawseti(state, -2, i + 1);
}
return 1;
}
static int fs_rglob(lua_State* state)
{
Filesystem& self = lua::Converter<std::reference_wrapper<Filesystem>>::extract(state, 1);
std::vector<NodePtr> res;
fs::path dir;
if (char const* arg = lua_tostring(state, 2))
dir = arg;
else
dir = lua::Converter<fs::path>::extract(state, 2);
if (char const* arg = lua_tostring(state, 3))
{
res = self.rglob(dir, arg);
}
lua_createtable(state, res.size(), 0);
for (int i = 0, len = res.size(); i < len; ++i)
{
lua::Converter<NodePtr>::push(state, res[i]);
lua_rawseti(state, -2, i + 1);
}
return 1;
}
static int fs_list_directory(lua_State* state)
{
Filesystem& self = lua::Converter<std::reference_wrapper<Filesystem>>::extract(state, 1);
std::vector<NodePtr> res;
if (char const* arg = lua_tostring(state, 2))
res = self.list_directory(arg);
else
res = self.list_directory(
lua::Converter<fs::path>::extract(state, 2)
);
lua_createtable(state, res.size(), 0);
for (int i = 0, len = res.size(); i < len; ++i)
{
lua::Converter<NodePtr>::push(state, res[i]);
lua_rawseti(state, -2, i + 1);
}
return 1;
}
static int fs_find_file(lua_State* state)
{
Filesystem& self = lua::Converter<std::reference_wrapper<Filesystem>>::extract(state, 1);
if (!lua_istable(state, 2))
CONFIGURE_THROW(
error::LuaError(
"Expected a table, got '" + std::string(luaL_tolstring(state, 2, nullptr)) + "'"
)
);
std::vector<fs::path> directories;
for (int i = 1, len = lua_rawlen(state, 2); i <= len; ++i)
{
lua_rawgeti(state, 2, i);
directories.push_back(utils::extract_path(state, -1));
}
lua::Converter<NodePtr>::push(
state,
self.find_file(directories, utils::extract_path(state, 3))
);
return 1;
}
static int fs_which(lua_State* state)
{
Filesystem& self = lua::Converter<std::reference_wrapper<Filesystem>>::extract(state, 1);
std::string arg;
if (fs::path* ptr = lua::Converter<fs::path>::extract_ptr(state, 2))
arg = ptr->string();
else if (char const* ptr = lua_tostring(state, 2))
arg = ptr;
if (!arg.empty())
{
auto res = self.which(arg);
if (res)
lua::Converter<fs::path>::push(state, *res);
else
lua_pushnil(state);
}
else
{
throw std::runtime_error(
"Filesystem.which(): Expected program name, got '" + std::string(luaL_tolstring(state, 2, 0)) + "'");
}
return 1;
}
static int fs_cwd(lua_State* state)
{
lua::Converter<fs::path>::push(state, fs::current_path());
return 1;
}
static int fs_current_script(lua_State* state)
{
lua_Debug ar;
if (lua_getstack(state, 1, &ar) != 1)
CONFIGURE_THROW(error::LuaError("Couldn't get the stack"));
if (lua_getinfo(state, "S", &ar) == 0)
CONFIGURE_THROW(error::LuaError("Couldn't get stack info"));
if (ar.source == nullptr)
CONFIGURE_THROW(error::LuaError("Invalid source file"));
fs::path src(ar.source[0] == '@' ? &ar.source[1] : ar.source);
if (!src.is_absolute())
src = fs::current_path() / src;
if (!fs::exists(src))
CONFIGURE_THROW(error::LuaError("Couldn't find the script path")
<< error::path(src));
lua::Converter<fs::path>::push(state, src);
return 1;
}
static int fs_copy(lua_State* state)
{
Filesystem& self = lua::Converter<std::reference_wrapper<Filesystem>>::extract(state, 1);
NodePtr res;
fs::path dst;
if (char const* arg = lua_tostring(state, 3))
dst = arg;
else if (fs::path* arg = lua::Converter<fs::path>::extract_ptr(state, 3))
dst = *arg;
else
CONFIGURE_THROW(
error::LuaError("Expected string or path for dest argument")
<< error::lua_function("Filesystem::copy")
);
if (char const* arg = lua_tostring(state, 2))
res = self.copy(arg, dst);
else if (fs::path* arg = lua::Converter<fs::path>::extract_ptr(state, 2))
res = self.copy(*arg, dst);
else if (NodePtr* arg = lua::Converter<NodePtr>::extract_ptr(state, 2))
res = self.copy(*arg, dst);
else
CONFIGURE_THROW(
error::LuaError("Expected string, path or Node for src argument")
<< error::lua_function("Filesystem::copy")
);
lua::Converter<NodePtr>::push(state, std::move(res));
return 1;
}
static int fs_create_directories(lua_State* state)
{
lua::Converter<std::reference_wrapper<Filesystem>>::extract(state, 1);
bool res = fs::create_directories(utils::extract_path(state, 2));
lua::Converter<bool>::push(state, res);
return 1;
}
void bind_filesystem(lua::State& state)
{
/// Filesystem operations.
// @classmod Filesystem
lua::Type<Filesystem, std::reference_wrapper<Filesystem>>(state, "Filesystem")
/// Find files according to a glob pattern
// @function Filesystem:glob
// @string pattern A glob pattern
// @return A list of @{Node}s
.def("glob", &fs_glob)
/// Find files recursively according to a glob pattern
// @function Filesystem:rglob
// @tparam string|Path dir The base directory
// @string pattern A glob pattern
// @return A list of @{Node}s
.def("rglob", &fs_rglob)
/// List a directory
// @function Filesystem:list_directory
// @tparam string|Path dir Directory to list
// @return A list of @{Node}s
.def("list_directory", &fs_list_directory)
/// Find a file
// @function Filesystem:find_file
// @tparam table directories A list of directories to inspect
// @tparam string|Path file The file to search for
// @return A @{Node}
.def("find_file", &fs_find_file)
/// Find an executable path
// @function Filesystem:which
// @tparam string|Path name An executable name
// @treturn Path|nil Absolute path to the executable found or nil
.def("which", &fs_which)
/// Generate rule that copy a file.
// @function Filesystem:copy
// @treturn Node the target node
.def("copy", &fs_copy)
/// Return the current working directory
// @function Filesystem:cwd
// @treturn Path current directory
.def("cwd", &fs_cwd)
/// Return the current script path
// @function Filesystem.current_script
.def("current_script", &fs_current_script)
/// Create directories
// @function Filesystem:create_directories
// @treturn bool True on success, false if the directories already exist
.def("create_directories", &fs_create_directories)
;
}
}
| 7,308 | 2,966 |
#ifndef ARRAYDIFF_CONTEXT_HH
#define ARRAYDIFF_CONTEXT_HH
#include <cuda_runtime.h>
#include <cublas.h>
#include <cudnn.h>
#include <nccl.h>
#include <cassert>
#include <experimental/optional>
#include <memory>
#include <vector>
namespace arraydiff {
using std::experimental::optional;
using std::shared_ptr;
using std::vector;
template <typename T>
class GPUMemory;
class Context {
public:
virtual ~Context() {}
virtual void sync() = 0;
};
class GPUConn {
public:
GPUConn(int device, cudaStream_t stream, cublasHandle_t cublas_h, cudnnHandle_t cudnn);
~GPUConn();
int device() const {
return this->device_;
}
cudaStream_t stream() {
return this->stream_;
}
cublasHandle_t cublas() {
return this->cublas_h_;
}
cudnnHandle_t cudnn() {
return this->cudnn_h_;
}
void sync();
private:
int device_;
cudaStream_t stream_;
cublasHandle_t cublas_h_;
cudnnHandle_t cudnn_h_;
};
class GPUContext : public virtual Context {
public:
static shared_ptr<GPUContext> Make(int device);
explicit GPUContext(int device);
virtual ~GPUContext() {}
virtual void sync();
GPUConn conn();
shared_ptr<GPUMemory<uint8_t>> get_scratch();
void reserve_scratch(size_t min_scratch_size);
private:
int device_;
cudaStream_t stream_;
cublasHandle_t cublas_h_;
cudnnHandle_t cudnn_h_;
size_t scratch_size_;
optional<shared_ptr<GPUMemory<uint8_t>>> scratch_;
};
class Spatial2DComm;
class MultiGPUContext : public virtual Context {
public:
static shared_ptr<MultiGPUContext> Make();
MultiGPUContext();
virtual ~MultiGPUContext() {}
virtual void sync();
void sync_rank(size_t rank);
size_t num_ranks() const { return this->dev_ctxs_.size(); }
shared_ptr<GPUContext> device_context(size_t rank);
ncclComm_t nccl_comm(size_t rank);
Spatial2DComm* spatial_comm(size_t rank);
private:
size_t num_ranks_;
vector<shared_ptr<GPUContext>> dev_ctxs_;
int* nccl_devs_;
ncclComm_t* nccl_comms_;
Spatial2DComm* spatial_comms_;
};
} // namespace arraydiff
#endif
| 2,044 | 784 |
/*
* Map.hpp
*
* Created on: 18 giu 2016
* Author: adileobarone
*
* La mappa è composta solo da stanze, non si deve occupare degli oggetti che ci sono sopra,
* poichè sono altre entità gestite da altre classi, l'unico link che c'è è quello che ogni oggetto
* punta a una posizione della mappa in cui si trova.
*
*/
#ifndef MAP_HPP_
#define MAP_HPP_
#include <iostream>
#include <list>
#include "Room.hpp"
#include "lib/easylogging++.hpp"
//Faccio una forward declaration per evitare le dipendenze circolari
class GameManager;
struct RoomNode{
Room* value;
RoomNode* next;
};
class RoomList{
private:
int size;
RoomNode* head;
RoomNode* tail;
public:
RoomList();
void push(Room* rm);
RoomNode* getHead();
RoomNode* getBack();
int length();
void destroy();
};
class Map{
private:
//std::list<Room> roomList;
RoomList rmlist;
GameManager* gm;
public:
Map(GameManager* g);
~Map();
Room* getRoom(Coord coord);
Room* getRoomOrCreate(Coord coord);
//std::list<Room>* getRooms();
RoomList* getRooms();
};
#endif /* MAP_HPP_ */
| 1,107 | 419 |
//<Snippet2>
// Example of the Buffer::SetByte method.
using namespace System;
// Display the array contents in hexadecimal.
void DisplayArray( Array^ arr, String^ name )
{
// Get the array element width; format the formatting string.
int elemWidth = Buffer::ByteLength( arr ) / arr->Length;
String^ format = String::Format( " {{0:X{0}}}", 2 * elemWidth );
// Display the array elements from right to left.
Console::Write( "{0,7}:", name );
for ( int loopX = arr->Length - 1; loopX >= 0; loopX-- )
Console::Write( format, arr->GetValue( loopX ) );
Console::WriteLine();
}
int main()
{
// These are the arrays to be modified with SetByte.
array<Int16>^shorts = gcnew array<Int16>(10);
array<Int64>^longs = gcnew array<Int64>(3);
Console::WriteLine( "This example of the "
"Buffer::SetByte( Array*, int, unsigned char ) \n"
"method generates the following output.\n"
"Note: The arrays are displayed from right to left.\n" );
Console::WriteLine( " Initial values of arrays:\n" );
// Display the initial values of the arrays.
DisplayArray( shorts, "shorts" );
DisplayArray( longs, "longs" );
// Copy two regions of source array to destination array,
// and two overlapped copies from source to source.
Console::WriteLine( "\n Array values after setting byte 3 = 25, \n"
" byte 6 = 64, byte 12 = 121, and byte 17 = 196:\n" );
Buffer::SetByte( shorts, 3, 25 );
Buffer::SetByte( shorts, 6, 64 );
Buffer::SetByte( shorts, 12, 121 );
Buffer::SetByte( shorts, 17, 196 );
Buffer::SetByte( longs, 3, 25 );
Buffer::SetByte( longs, 6, 64 );
Buffer::SetByte( longs, 12, 121 );
Buffer::SetByte( longs, 17, 196 );
// Display the arrays again.
DisplayArray( shorts, "shorts" );
DisplayArray( longs, "longs" );
}
/*
This example of the Buffer::SetByte( Array*, int, unsigned char )
method generates the following output.
Note: The arrays are displayed from right to left.
Initial values of arrays:
shorts: 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000
longs: 0000000000000000 0000000000000000 0000000000000000
Array values after setting byte 3 = 25,
byte 6 = 64, byte 12 = 121, and byte 17 = 196:
shorts: 0000 C400 0000 0079 0000 0000 0040 0000 1900 0000
longs: 000000000000C400 0000007900000000 0040000019000000
*/
//</Snippet2>
| 2,438 | 1,013 |
// Fill out your copyright notice in the Description page of Project Settings.
#include "BlurFilter.h"
// NaÏve gaussian blur impl
bool UBlurFilter::ModifyHeightMap(TArray<uint16>* RawHeightMapData, FBounds Bounds, FRandomStream* RandomStream)
{
for (int32 j = Bounds.MinY; j <= Bounds.MaxY; j++)
{
for (int32 i = Bounds.MinX; i <= Bounds.MaxX; i++)
{
double CountPoints = 0;
double SumPointHeight = 0;
int32 RealDistanceOfInfluence = DistanceOfInfluence;
for (int32 OffsetX = -RealDistanceOfInfluence; OffsetX <= RealDistanceOfInfluence; OffsetX++)
{
int32 NeededOffsetY = RealDistanceOfInfluence - FMath::Abs(OffsetX);
for (int32 OffsetY = -NeededOffsetY; OffsetY <= NeededOffsetY; OffsetY++)
{
FIntPoint CurrentPoint(i + OffsetX, j + OffsetY);
int32 CurrentIndex = (CurrentPoint.Y - Bounds.MinY) * (Bounds.MaxX - Bounds.MinX + 1) + (CurrentPoint.X - Bounds.MinX);
if (CurrentPoint.X >= Bounds.MinX && CurrentPoint.X <= Bounds.MaxX && CurrentPoint.Y >= Bounds.MinY && CurrentPoint.Y <= Bounds.MaxY)
{
double Weight = FMath::Pow(InfluenceDecayPerDistanceUnit, FMath::Abs(OffsetX) + FMath::Abs(OffsetY));
CountPoints += Weight;
SumPointHeight += Weight * (*RawHeightMapData)[CurrentIndex];
}
}
}
int32 CurrentIndex = (j - Bounds.MinY) * (Bounds.MaxX - Bounds.MinX + 1) + (i - Bounds.MinX);
(*RawHeightMapData)[CurrentIndex] = FMath::Clamp(FMath::RoundToInt(SumPointHeight / CountPoints), 0, (int32)UINT16_MAX);
}
}
return true;
}
| 1,528 | 637 |
#include "examples/hello/hello_world_lib.h"
#include "glog/logging.h"
namespace hello {
bool print (proto::Hello hello_pb) {
LOG(INFO) << "Hello world!";
if (!hello_pb.extra_message().empty()) {
LOG(INFO) << hello_pb.extra_message();
}
usleep(1000000);
return !hello_pb.extra_message().empty();
}
}
| 333 | 126 |
#include <interrupts/panic.h>
#include <scheduling/scheduler/scheduler.h>
#include <renderer/renderer2D.h>
#include <renderer/point.h>
#include <driver/serial.h>
#include <config.h>
#include <stdio.h>
#include <disassembler.h>
using namespace interrupts;
Panic::Panic(int intr) {
this->intr = intr;
this->panic = NULL;
}
Panic::Panic(char* panic) {
this->panic = panic;
}
char* Panic::get_panic_message() {
switch(this->intr){
case 0x0:
return((char*) "Divide by Zero");
break;
case 0x1:
return((char*) "Debug");
break;
case 0x2:
return((char*) "Non Maskable Interrupt");
break;
case 0x3:
return((char*) "Breakpoint");
break;
case 0x4:
return((char*) "Overflow");
break;
case 0x5:
return((char*) "Bound Range");
break;
case 0x6:
return((char*) "Invalid Opcode");
break;
case 0x7:
return((char*) "Device Not Available");
break;
case 0x8:
return((char*) "Double Fault");
break;
case 0x9:
return((char*) "Coprocessor Segment Overrun");
break;
case 0xa:
return((char*) "Invalid TSS");
break;
case 0xb:
return((char*) "Segment not Present");
break;
case 0xc:
return((char*) "Stack Fault");
break;
case 0xd:
return((char*) "General Protection");
break;
case 0xe:
return((char*) "Page Fault");
break;
case 0x10:
return((char*) "x87 Floating Point");
break;
case 0x11:
return((char*) "Alignment Check");
break;
case 0x12:
return((char*) "Machine Check");
break;
case 0x13:
return((char*) "SIMD Floating Point");
break;
case 0x1e:
return((char*) "Security-sensitive event in Host");
break;
default:
return((char*) "Reserved");
break;
}
}
void Panic::dump_regs(s_registers* regs) {
renderer::global_font_renderer->printf("cr0: %d; cr2: %d; cr3: %d; cr4: %d\n", regs->cr0, regs->cr2, regs->cr3, regs->cr4);
renderer::global_font_renderer->printf("r8: %d; r9: %d; r10: %d; r11: %d\n", regs->r8, regs->r9, regs->r10, regs->r11);
renderer::global_font_renderer->printf("r12: %d; r13: %d; r14: %d; r15: %d\n", regs->r12, regs->r13, regs->r14, regs->r15);
renderer::global_font_renderer->printf("rdi: %d; rsi: %d; rbp: %d\n", regs->rdi, regs->rsi, regs->rbp);
renderer::global_font_renderer->printf("rax: %d; rbx: %d; rcx: %d; rdx: %d\n", regs->rax, regs->rbx, regs->rcx, regs->rdx);
renderer::global_font_renderer->printf("rip: %d; cs: %d; rflags: %d; rsp: %d\n\n", regs->rip, regs->cs, regs->rflags, regs->rsp);
}
extern uint8_t screen_of_death[];
void Panic::do_it(s_registers* regs) {
renderer::point_t bmp_info = renderer::global_renderer2D->get_bitmap_info(screen_of_death);
renderer::global_font_renderer->color = 0xffe36d2d;
renderer::global_font_renderer->clear();
renderer::global_font_renderer->cursor_position = {0, 8};
renderer::global_font_renderer->color = 0xffffffff;
renderer::global_font_renderer->printf("(/ o_o)/ Oh no! Something terrible has happened and your system has been halted...\n");
renderer::global_font_renderer->printf("There isn't much you can do apart from restart the computer. More information below.\n\n");
if (!this->panic) {
renderer::global_font_renderer->printf("Kernel PANIC -> %s (0x%x)\n", this->get_panic_message(), this->intr);
} else {
renderer::global_font_renderer->printf("Kernel PANIC -> %s\n", this->panic);
}
renderer::global_font_renderer->printf("Kernel version: %d\n", VERSION);
renderer::global_font_renderer->printf("Release type: %s\n\n", RELEASE_T);
renderer::global_font_renderer->printf("Please report this issue at %fhttps://github.com/TheUltimateFoxOS/FoxOS%r by creating an issue.\n", 0xff0000ff);
renderer::global_font_renderer->printf("Feel free to fix this and submit a pull request!\n\n");
if (regs) {
renderer::global_font_renderer->printf("Register dump:\n");
dump_regs(regs);
char disassembled[0xFF];
memset(disassembled, 0, 0xFF);
unsigned char* code_location = (unsigned char*) regs->rip;
int disassembled_size = disassemble(code_location, 10, 0, disassembled);
renderer::global_font_renderer->printf("Faulting instruction: %s\n", disassembled);
renderer::global_font_renderer->printf("\nStarting stack trace:\n");
if(resolve_symbol(resolve_symbol(regs->rip)) != 0) {
char str[512];
sprintf(str, "%s + %d", resolve_symbol(regs->rip), regs->rip - resolve_symbol(resolve_symbol(regs->rip)));
renderer::global_font_renderer->printf("%s\n", str);
} else {
renderer::global_font_renderer->printf("<unknown function at 0x%x>\n", regs->rip);
}
int max_lines = (renderer::global_renderer2D->target_frame_buffer->height - renderer::global_font_renderer->cursor_position.y) / 16;
max_lines -= 4;
driver::global_serial_driver->printf("Starting stack trace using %d as max lines!\n", max_lines);
unwind(max_lines, regs->rbp, [](int frame_num, uint64_t rip) {
if(resolve_symbol(resolve_symbol(rip)) != 0) {
char str[512];
sprintf(str, "%s + %d", resolve_symbol(rip), rip - resolve_symbol(resolve_symbol(rip)));
renderer::global_font_renderer->printf("%s\n", str);
} else {
renderer::global_font_renderer->printf("<unknown function at 0x%x>\n", rip);
}
});
}
renderer::global_renderer2D->load_bitmap(screen_of_death, 0, renderer::global_renderer2D->target_frame_buffer->height - bmp_info.x);
while(true) {
halt_cpu = true;
asm volatile("cli; hlt");
}
} | 5,401 | 2,331 |