hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5110e7dcb11d6a211544dbca488947c8c99a01c1 | 1,565 | cpp | C++ | Algorithms/Easy/155.min-stack.cpp | jtcheng/leetcode | db58973894757789d060301b589735b5985fe102 | [
"MIT"
] | null | null | null | Algorithms/Easy/155.min-stack.cpp | jtcheng/leetcode | db58973894757789d060301b589735b5985fe102 | [
"MIT"
] | null | null | null | Algorithms/Easy/155.min-stack.cpp | jtcheng/leetcode | db58973894757789d060301b589735b5985fe102 | [
"MIT"
] | null | null | null | /*
* @lc app=leetcode id=155 lang=cpp
*
* [155] Min Stack
*
* https://leetcode.com/problems/min-stack/description/
*
* algorithms
* Easy (35.38%)
* Total Accepted: 269.9K
* Total Submissions: 756.8K
* Testcase Example: '["MinStack","push","push","push","getMin","pop","top","getMin"]\n[[],[-2],[0],[-3],[],[],[],[]]'
*
*
* Design a stack that supports push, pop, top, and retrieving the minimum
* element in constant time.
*
*
* push(x) -- Push element x onto stack.
*
*
* pop() -- Removes the element on top of the stack.
*
*
* top() -- Get the top element.
*
*
* getMin() -- Retrieve the minimum element in the stack.
*
*
*
*
* Example:
*
* MinStack minStack = new MinStack();
* minStack.push(-2);
* minStack.push(0);
* minStack.push(-3);
* minStack.getMin(); --> Returns -3.
* minStack.pop();
* minStack.top(); --> Returns 0.
* minStack.getMin(); --> Returns -2.
*
*
*/
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
if (x <= min_) {
s_.push(min_);
min_ = x;
}
s_.push(x);
}
void pop() {
if (s_.top() == min_) {
s_.pop();
min_ = s_.top();
s_.pop();
}
else {
s_.pop();
}
}
int top() {
return s_.top();
}
int getMin() {
return min_;
}
private:
stack<int> s_;
int min_ = INT_MAX;
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
| 16.648936 | 119 | 0.557827 | jtcheng |
5114d062bfce4d6dea07ef750a0be0c1db15feeb | 27,066 | cpp | C++ | Engine/Plugins/Experimental/ControlRig/Source/ControlRig/Private/Rigs/HierarchicalRig.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Plugins/Experimental/ControlRig/Source/ControlRig/Private/Rigs/HierarchicalRig.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Plugins/Experimental/ControlRig/Source/ControlRig/Private/Rigs/HierarchicalRig.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "HierarchicalRig.h"
#include "Engine/SkeletalMesh.h"
#include "AnimationRuntime.h"
#include "AnimationCoreLibrary.h"
#include "Components/StaticMeshComponent.h"
#include "Components/SkeletalMeshComponent.h"
#define LOCTEXT_NAMESPACE "HierarchicalRig"
UHierarchicalRig::UHierarchicalRig()
{
}
#if WITH_EDITOR
void UHierarchicalRig::SetConstraints(const TArray<FTransformConstraint>& InConstraints)
{
Constraints = InConstraints;
}
void UHierarchicalRig::BuildHierarchyFromSkeletalMesh(USkeletalMesh* SkeletalMesh)
{
const TArray<FMeshBoneInfo>& MeshBoneInfos = SkeletalMesh->RefSkeleton.GetRawRefBoneInfo();
const TArray<FTransform>& LocalTransforms = SkeletalMesh->RefSkeleton.GetRefBonePose();
check(MeshBoneInfos.Num() == LocalTransforms.Num());
// clear hierarchy - is this necessary? Maybe not, but it makes it simpler for not handling duplicated names and so on
Hierarchy.Empty();
TArray<FTransform> GlobalTransforms;
FAnimationRuntime::FillUpComponentSpaceTransforms(SkeletalMesh->RefSkeleton, LocalTransforms, GlobalTransforms);
const int32 BoneCount = MeshBoneInfos.Num();
for (int32 BoneIndex = 0; BoneIndex < BoneCount; ++BoneIndex)
{
const FMeshBoneInfo& MeshBoneInfo = MeshBoneInfos[BoneIndex];
const FTransform& LocalTransform = LocalTransforms[BoneIndex];
const FTransform& GlobalTransform = GlobalTransforms[BoneIndex];
FName ParentName;
FConstraintNodeData NodeData;
if (MeshBoneInfo.ParentIndex != INDEX_NONE)
{
ParentName = MeshBoneInfos[MeshBoneInfo.ParentIndex].Name;
const FTransform& GlobalParentTransform = GlobalTransforms[MeshBoneInfo.ParentIndex];
NodeData.RelativeParent = GlobalTransform.GetRelativeTransform(GlobalParentTransform);
}
else
{
NodeData.RelativeParent = GlobalTransform;
}
Hierarchy.Add(MeshBoneInfo.Name, ParentName, GlobalTransform, NodeData);
}
}
#endif // WITH_EDITOR
FTransform UHierarchicalRig::GetLocalTransform(FName NodeName) const
{
return Hierarchy.GetLocalTransformByName(NodeName);
}
FVector UHierarchicalRig::GetLocalLocation(FName NodeName) const
{
return Hierarchy.GetLocalTransformByName(NodeName).GetLocation();
}
FRotator UHierarchicalRig::GetLocalRotation(FName NodeName) const
{
return Hierarchy.GetLocalTransformByName(NodeName).GetRotation().Rotator();
}
FVector UHierarchicalRig::GetLocalScale(FName NodeName) const
{
return Hierarchy.GetLocalTransformByName(NodeName).GetScale3D();
}
FTransform UHierarchicalRig::GetGlobalTransform(FName NodeName) const
{
return Hierarchy.GetGlobalTransformByName(NodeName);
}
FTransform UHierarchicalRig::GetMappedGlobalTransform(FName NodeName) const
{
FTransform GlobalTransform = GetGlobalTransform(NodeName);
ApplyMappingTransform(NodeName, GlobalTransform);
return GlobalTransform;
}
FTransform UHierarchicalRig::GetMappedLocalTransform(FName NodeName) const
{
// should recalculate since mapping is happening in component space
const FAnimationHierarchy& CacheHiearchy = GetHierarchy();
int32 NodeIndex = CacheHiearchy.GetNodeIndex(NodeName);
if (CacheHiearchy.IsValidIndex(NodeIndex))
{
FTransform GlobalTransform = CacheHiearchy.GetGlobalTransform(NodeIndex);
ApplyMappingTransform(NodeName, GlobalTransform);
int32 ParentIndex = CacheHiearchy.GetParentIndex(NodeIndex);
if (CacheHiearchy.IsValidIndex(ParentIndex))
{
FTransform ParentGlobalTransform = CacheHiearchy.GetGlobalTransform(ParentIndex);
ApplyMappingTransform(CacheHiearchy.GetNodeName(ParentIndex), ParentGlobalTransform);
GlobalTransform = GlobalTransform.GetRelativeTransform(ParentGlobalTransform);
}
GlobalTransform.NormalizeRotation();
return GlobalTransform;
}
return FTransform::Identity;
}
FVector UHierarchicalRig::GetGlobalLocation(FName NodeName) const
{
return Hierarchy.GetGlobalTransformByName(NodeName).GetLocation();
}
FRotator UHierarchicalRig::GetGlobalRotation(FName NodeName) const
{
return Hierarchy.GetGlobalTransformByName(NodeName).GetRotation().Rotator();
}
FVector UHierarchicalRig::GetGlobalScale(FName NodeName) const
{
return Hierarchy.GetGlobalTransformByName(NodeName).GetScale3D();
}
void UHierarchicalRig::SetLocalTransform(FName NodeName, const FTransform& Transform)
{
Hierarchy.SetLocalTransformByName(NodeName, Transform);
}
void UHierarchicalRig::SetGlobalTransform(FName NodeName, const FTransform& Transform)
{
int32 NodeIndex = Hierarchy.GetNodeIndex(NodeName);
if (Hierarchy.IsValidIndex(NodeIndex))
{
const FTransform& OldTransform = Hierarchy.GetGlobalTransform(NodeIndex);
if (!OldTransform.Equals(Transform))
{
Hierarchy.SetGlobalTransform(NodeIndex, Transform);
}
// we still have to call evaluate node to update all dependency even if this node didn't change
// because constraints might have to update
EvaluateNode(NodeName);
}
}
void UHierarchicalRig::SetMappedGlobalTransform(FName NodeName, const FTransform& Transform)
{
FTransform NewTransform = Transform;
NewTransform.NormalizeRotation();
ApplyInverseMappingTransform(NodeName, NewTransform);
SetGlobalTransform(NodeName, NewTransform);
}
void UHierarchicalRig::SetMappedLocalTransform(FName NodeName, const FTransform& Transform)
{
// should recalculate since mapping is happening in component space
const FAnimationHierarchy& CacheHiearchy = GetHierarchy();
int32 NodeIndex = CacheHiearchy.GetNodeIndex(NodeName);
if (CacheHiearchy.IsValidIndex(NodeIndex))
{
FTransform GlobalTransform;
int32 ParentIndex = CacheHiearchy.GetParentIndex(NodeIndex);
if (CacheHiearchy.IsValidIndex(ParentIndex))
{
FTransform ParentGlobalTransform = CacheHiearchy.GetGlobalTransform(ParentIndex);
ApplyMappingTransform(CacheHiearchy.GetNodeName(ParentIndex), ParentGlobalTransform);
// have to apply to mapped transform
GlobalTransform = Transform * ParentGlobalTransform;
}
else
{
GlobalTransform = Transform;
}
// inverse mapping transform
ApplyInverseMappingTransform(NodeName, GlobalTransform);
SetGlobalTransform(NodeName, GlobalTransform);
}
}
void UHierarchicalRig::ApplyMappingTransform(FName NodeName, FTransform& InOutTransform) const
{
if (NodeMappingContainer)
{
const FNodeMap* NodeMapping = NodeMappingContainer->GetNodeMapping(NodeName);
if (NodeMapping)
{
InOutTransform = NodeMapping->SourceToTargetTransform * InOutTransform;
}
else
{
// get node data
// @todo: do it here or create mapping for manually. Creating mapping will be more efficient
const int32 Index = Hierarchy.GetNodeIndex(NodeName);
if (Index != INDEX_NONE)
{
const FConstraintNodeData* UserData = static_cast<const FConstraintNodeData*> (Hierarchy.GetUserDataImpl(Index));
if (UserData->LinkedNode != NAME_None)
{
NodeMapping = NodeMappingContainer->GetNodeMapping(UserData->LinkedNode);
if (NodeMapping)
{
InOutTransform = NodeMapping->SourceToTargetTransform * InOutTransform;
}
}
}
}
}
}
void UHierarchicalRig::ApplyInverseMappingTransform(FName NodeName, FTransform& InOutTransform) const
{
if (NodeMappingContainer)
{
const FNodeMap* NodeMapping = NodeMappingContainer->GetNodeMapping(NodeName);
if (NodeMapping)
{
InOutTransform = NodeMapping->SourceToTargetTransform.GetRelativeTransformReverse(InOutTransform);
}
else
{
// get node data
// @todo: do it here or create mapping for manually. Creating mapping will be more efficient
const int32 Index = Hierarchy.GetNodeIndex(NodeName);
if (Index != INDEX_NONE)
{
const FConstraintNodeData* UserData = static_cast<const FConstraintNodeData*> (Hierarchy.GetUserDataImpl(Index));
if (UserData->LinkedNode != NAME_None)
{
NodeMapping = NodeMappingContainer->GetNodeMapping(UserData->LinkedNode);
if (NodeMapping)
{
InOutTransform = NodeMapping->SourceToTargetTransform.GetRelativeTransformReverse(InOutTransform);
}
}
}
}
}
}
#if WITH_EDITOR
FText UHierarchicalRig::GetCategory() const
{
return LOCTEXT("HierarchicalRigCategory", "Animation|ControlRigs");
}
FText UHierarchicalRig::GetTooltipText() const
{
return LOCTEXT("HierarchicalRigTooltip", "Handles hierarchical (node based) data, constraints etc.");
}
#endif
void UHierarchicalRig::GetTickDependencies(TArray<FTickPrerequisite, TInlineAllocator<1>>& OutTickPrerequisites)
{
if (SkeletalMeshComponent.IsValid())
{
OutTickPrerequisites.Add(FTickPrerequisite(SkeletalMeshComponent.Get(), SkeletalMeshComponent->PrimaryComponentTick));
}
}
void UHierarchicalRig::Initialize()
{
Super::Initialize();
// Initialize any manipulators we have
for (UControlManipulator* Manipulator : Manipulators)
{
if (Manipulator)
{
#if WITH_EDITOR
TGuardValue<bool> ScopeGuard(Manipulator->bNotifyListeners, false);
#endif
Manipulator->Initialize(this);
if (Hierarchy.Contains(Manipulator->Name))
{
if (Manipulator->bInLocalSpace)
{
// do not add node in initialize, that is only for editor purpose and to serialize
Manipulator->SetTransform(GetMappedLocalTransform(Manipulator->Name), this);
}
else
{
// do not add node in initialize, that is only for editor purpose and to serialize
Manipulator->SetTransform(GetMappedGlobalTransform(Manipulator->Name), this);
}
}
}
}
Sort();
}
AActor* UHierarchicalRig::GetHostingActor() const
{
if (SkeletalMeshComponent.Get())
{
return SkeletalMeshComponent->GetOwner();
}
return Super::GetHostingActor();
}
void UHierarchicalRig::BindToObject(UObject* InObject)
{
// If we are binding to an actor, find the first skeletal mesh component
if (AActor* Actor = Cast<AActor>(InObject))
{
if (USkeletalMeshComponent* Component = Actor->FindComponentByClass<USkeletalMeshComponent>())
{
SkeletalMeshComponent = Component;
}
}
else if (USkeletalMeshComponent* Component = Cast<USkeletalMeshComponent>(InObject))
{
SkeletalMeshComponent = Component;
}
}
void UHierarchicalRig::UnbindFromObject()
{
SkeletalMeshComponent = nullptr;
}
bool UHierarchicalRig::IsBoundToObject(UObject* InObject) const
{
if (AActor* Actor = Cast<AActor>(InObject))
{
if (USkeletalMeshComponent* Component = Actor->FindComponentByClass<USkeletalMeshComponent>())
{
return SkeletalMeshComponent.Get() == Component;
}
}
else if (USkeletalMeshComponent* Component = Cast<USkeletalMeshComponent>(InObject))
{
return SkeletalMeshComponent.Get() == Component;
}
return false;
}
UObject* UHierarchicalRig::GetBoundObject() const
{
return SkeletalMeshComponent.Get();
}
void UHierarchicalRig::PreEvaluate()
{
Super::PreEvaluate();
// @todo: sequencer will need this -
// Propagate manipulators to nodes
for (UControlManipulator* Manipulator : Manipulators)
{
if (Manipulator)
{
if (Manipulator->bInLocalSpace)
{
SetMappedLocalTransform(Manipulator->Name, Manipulator->GetTransform(this));
}
else
{
SetMappedGlobalTransform(Manipulator->Name, Manipulator->GetTransform(this));
}
}
}
}
void UHierarchicalRig::Evaluate()
{
Super::Evaluate();
}
// we don't really have to update nodes as they're updated by manipulator anyway if input
// but I'm leaving here as a function just in case in the future this came up again
void UHierarchicalRig::UpdateNodes()
{
// Calculate each node
for (const FName& NodeName : SortedNodes)
{
const FTransform& GlobalTransfrom = GetGlobalTransform(NodeName);
SetGlobalTransform(NodeName, GlobalTransfrom);
}
}
void UHierarchicalRig::PostEvaluate()
{
Super::PostEvaluate();
UpdateManipulatorToNode(false);
}
void UHierarchicalRig::UpdateManipulatorToNode(bool bNotifyListeners)
{
// Propagate back to manipulators after evaluation
for (UControlManipulator* Manipulator : Manipulators)
{
if (Manipulator)
{
#if WITH_EDITOR
TGuardValue<bool> ScopeGuard(Manipulator->bNotifyListeners, bNotifyListeners);
#endif
if (Manipulator->bInLocalSpace)
{
// do not add node in initialize, that is only for editor purpose and to serialize
Manipulator->SetTransform(GetMappedLocalTransform(Manipulator->Name), this);
}
else
{
// do not add node in initialize, that is only for editor purpose and to serialize
Manipulator->SetTransform(GetMappedGlobalTransform(Manipulator->Name), this);
}
}
}
}
#if WITH_EDITOR
void UHierarchicalRig::AddNode(FName NodeName, FName ParentName, const FTransform& GlobalTransform, FName LinkedNode /*= NAME_None*/)
{
FConstraintNodeData NewNodeData;
NewNodeData.LinkedNode = LinkedNode;
if (ParentName != NAME_None)
{
FTransform ParentTransform = Hierarchy.GetGlobalTransformByName(ParentName);
NewNodeData.RelativeParent = GlobalTransform.GetRelativeTransform(ParentTransform);
}
else
{
NewNodeData.RelativeParent = GlobalTransform;
}
Hierarchy.Add(NodeName, ParentName, GlobalTransform, NewNodeData);
}
void UHierarchicalRig::SetParent(FName NodeName, FName NewParentName)
{
if (Hierarchy.Contains(NodeName) && (NewParentName == NAME_None || Hierarchy.Contains(NewParentName)))
{
const int32 NodeIndex = Hierarchy.GetNodeIndex(NodeName);
check(NodeIndex != INDEX_NONE);
const FTransform NodeTransform = Hierarchy.GetGlobalTransform(NodeIndex);
Hierarchy.SetParentName(NodeIndex, NewParentName);
FConstraintNodeData& MyNodeData = Hierarchy.GetNodeData<FConstraintNodeData>(NodeIndex);
if (NewParentName != NAME_None)
{
FTransform ParentTransform = Hierarchy.GetGlobalTransformByName(NewParentName);
MyNodeData.RelativeParent = NodeTransform.GetRelativeTransform(ParentTransform);
}
else
{
MyNodeData.RelativeParent = NodeTransform;
}
}
}
void UHierarchicalRig::DeleteConstraint(FName NodeName, FName TargetNode)
{
int32 NodeIndex = Hierarchy.GetNodeIndex(NodeName);
if (Hierarchy.IsValidIndex(NodeIndex))
{
FConstraintNodeData& NodeData = Hierarchy.GetNodeData<FConstraintNodeData>(NodeIndex);
NodeData.DeleteConstraint(TargetNode);
}
}
void UHierarchicalRig::DeleteNode(FName NodeName)
{
int32 NodeIndex = Hierarchy.GetNodeIndex(NodeName);
if (Hierarchy.IsValidIndex(NodeIndex))
{
TArray<FName> Children = Hierarchy.GetChildren(NodeIndex);
FName ParentName = Hierarchy.GetParentName(NodeIndex);
int32 ParentIndex = Hierarchy.GetNodeIndex(ParentName);
FTransform ParentTransform = (ParentIndex != INDEX_NONE)? Hierarchy.GetGlobalTransform(ParentIndex) : FTransform::Identity;
// now reparent the children
for (int32 ChildIndex = 0; ChildIndex < Children.Num(); ++ChildIndex)
{
int32 ChildNodeIndex = Hierarchy.GetNodeIndex(Children[ChildIndex]);
Hierarchy.SetParentName(ChildNodeIndex, ParentName);
// when delete, we have to re-adjust relative transform
FTransform ChildTransform = Hierarchy.GetGlobalTransform(ChildNodeIndex);
FConstraintNodeData& ChildNodeData = Hierarchy.GetNodeData<FConstraintNodeData>(ChildNodeIndex);
ChildNodeData.RelativeParent = ChildTransform.GetRelativeTransform(ParentTransform);
}
Hierarchy.Remove(NodeName);
}
}
FNodeChain UHierarchicalRig::MakeNodeChain(FName RootNode, FName EndNode)
{
FNodeChain NodeChain;
// walk up hierarchy towards root from end to start
FName BoneName = EndNode;
while (BoneName != RootNode)
{
// we hit the root, so clear the bone chain - we have an invalid chain
if (BoneName == NAME_None)
{
NodeChain.Nodes.Reset();
break;
}
NodeChain.Nodes.EmplaceAt(0, BoneName);
int32 NodeIndex = Hierarchy.GetNodeIndex(BoneName);
if (NodeIndex == INDEX_NONE)
{
NodeChain.Nodes.Reset();
break;
}
BoneName = Hierarchy.GetParentName(NodeIndex);
}
return NodeChain;
}
UControlManipulator* UHierarchicalRig::AddManipulator(TSubclassOf<UControlManipulator> ManipulatorClass, FText DisplayName, FName NodeName, FName PropertyToManipulate, EIKSpaceMode KinematicSpace, bool bUsesTranslation, bool bUsesRotation, bool bUsesScale, bool bInLocalSpace)
{
// make sure manipulator doesn't exists already
for (int32 ManipulatorIndex = 0; ManipulatorIndex < Manipulators.Num(); ++ManipulatorIndex)
{
if (UControlManipulator* Manipulator = Manipulators[ManipulatorIndex])
{
if (Manipulator->Name == NodeName)
{
// same name exists, failed, return
return Manipulator;
}
}
}
UControlManipulator* NewManipulator = NewObject<UControlManipulator>(this, ManipulatorClass.Get(), NAME_None, RF_Public | RF_Transactional | RF_ArchetypeObject);
NewManipulator->DisplayName = DisplayName;
NewManipulator->Name = NodeName;
NewManipulator->PropertyToManipulate = PropertyToManipulate;
NewManipulator->KinematicSpace = KinematicSpace;
NewManipulator->bUsesTranslation = bUsesTranslation;
NewManipulator->bUsesRotation = bUsesRotation;
NewManipulator->bUsesScale = bUsesScale;
NewManipulator->bInLocalSpace = bInLocalSpace;
Manipulators.Add(NewManipulator);
return NewManipulator;
}
void UHierarchicalRig::UpdateConstraints()
{
if (Constraints.Num() > 0)
{
for (const FTransformConstraint& Constraint : Constraints)
{
AddConstraint(Constraint);
}
}
}
#endif // WITH_EDITOR
void UHierarchicalRig::AddConstraint(const FTransformConstraint& TransformConstraint)
{
int32 NodeIndex = Hierarchy.GetNodeIndex(TransformConstraint.SourceNode);
int32 ConstraintNodeIndex = Hierarchy.GetNodeIndex(TransformConstraint.TargetNode);
if (NodeIndex != INDEX_NONE && ConstraintNodeIndex != INDEX_NONE)
{
FConstraintNodeData& NodeData = Hierarchy.GetNodeData<FConstraintNodeData>(NodeIndex);
NodeData.AddConstraint(TransformConstraint);
// recalculate main offset for all constraint
if (TransformConstraint.bMaintainOffset)
{
int32 ParentIndex = Hierarchy.GetParentIndex(NodeIndex);
FTransform ParentTransform = (ParentIndex != INDEX_NONE) ? Hierarchy.GetGlobalTransform(ParentIndex) : FTransform::Identity;
FTransform LocalTransform = Hierarchy.GetLocalTransform(NodeIndex);
FTransform TargetTransform = ResolveConstraints(LocalTransform, ParentTransform, NodeData);
NodeData.ConstraintOffset.SaveInverseOffset(LocalTransform, TargetTransform, TransformConstraint.Operator);
}
else
{
NodeData.ConstraintOffset.Reset();
}
}
}
static int32& EnsureNodeExists(TMap<FName, int32>& InGraph, FName Name)
{
int32* Value = InGraph.Find(Name);
if (!Value)
{
Value = &InGraph.Add(Name);
*Value = 0;
}
return *Value;
}
static void IncreaseEdgeCount(TMap<FName, int32>& InGraph, FName Name)
{
int32& EdgeCount = EnsureNodeExists(InGraph, Name);
++EdgeCount;
}
void UHierarchicalRig::AddDependenciesRecursive(int32 OriginalNodeIndex, int32 NodeIndex)
{
const FName& NodeName = Hierarchy.GetNodeName(NodeIndex);
TArray<FName> Neighbors;
GetDependentArray(NodeName, Neighbors);
for (const FName& Neighbor : Neighbors)
{
int32 NeighborNodeIndex = Hierarchy.GetNodeIndex(Neighbor);
if (NeighborNodeIndex != INDEX_NONE)
{
TArray<int32>& NodeDependencies = DependencyGraph[NeighborNodeIndex];
NodeDependencies.AddUnique(OriginalNodeIndex);
AddDependenciesRecursive(OriginalNodeIndex, NeighborNodeIndex);
}
}
}
void UHierarchicalRig::CreateSortedNodes()
{
// Comparison Operator for Sorting.
struct FSortDependencyGraph
{
private:
TArray<int32>* SortedNodeIndices;
public:
FSortDependencyGraph(TArray<int32>* InSortedNodeIndices)
: SortedNodeIndices(InSortedNodeIndices)
{
}
FORCEINLINE bool operator()(const int32& A, const int32& B) const
{
return SortedNodeIndices->Find(A) > SortedNodeIndices->Find(B);
}
};
SortedNodes.Reset();
// name to incoming edge
TMap<FName, int32> Graph;
// calculate incoming edges
for (int32 NodeIndex = 0; NodeIndex < Hierarchy.GetNum(); ++NodeIndex)
{
const FName& NodeName = Hierarchy.GetNodeName(NodeIndex);
EnsureNodeExists(Graph, NodeName);
TArray<FName> Neighbors;
GetDependentArray(NodeName, Neighbors);
// @todo: can include itself?
for (int32 NeighborsIndex = 0; NeighborsIndex < Neighbors.Num(); ++NeighborsIndex)
{
IncreaseEdgeCount(Graph, Neighbors[NeighborsIndex]);
}
}
// do run Kahn
TArray<FName> SortingQueue;
TArray<int32> SortedNodeIndices;
// first remove 0 in-degree vertices
for (const TPair<FName, int32>& GraphPair : Graph)
{
if (GraphPair.Value == 0)
{
SortingQueue.Add(GraphPair.Key);
}
}
// if sorting queue is same as node count, that means nothing is dependent
if (SortingQueue.Num() == Hierarchy.GetNum())
{
SortedNodes = SortingQueue;
}
else
{
while (SortingQueue.Num() != 0)
{
FName Name = SortingQueue[0];
// move the element
SortingQueue.Remove(Name);
SortedNodes.Add(Name);
SortedNodeIndices.Add(Hierarchy.GetNodeIndex(Name));
TArray<FName> Neighbors;
GetDependentArray(Name, Neighbors);
for (int32 NeighborsIndex = 0; NeighborsIndex < Neighbors.Num(); ++NeighborsIndex)
{
int32* EdgeCount = Graph.Find(Neighbors[NeighborsIndex]);
--(*EdgeCount);
if (*EdgeCount == 0)
{
SortingQueue.Add(Neighbors[NeighborsIndex]);
}
}
}
DependencyGraph.Reset();
if (SortedNodes.Num() == Hierarchy.GetNum())
{
// If the sorted node count is different to the hierarchy we have a cycle, so we dont regenerate the graph in that case
// Now generate a path through the DAG for each node to evaluate
DependencyGraph.SetNum(Hierarchy.GetNum());
for (int32 NodeIndex = 0; NodeIndex < Hierarchy.GetNum(); ++NodeIndex)
{
AddDependenciesRecursive(NodeIndex, NodeIndex);
}
// after this, we should sort using SortedNodes.
for (int32 NodeIndex = 0; NodeIndex < Hierarchy.GetNum(); ++NodeIndex)
{
DependencyGraph[NodeIndex].Sort(FSortDependencyGraph(&SortedNodeIndices));
}
}
}
}
void UHierarchicalRig::ApplyConstraint(const FName& NodeName)
{
int32 NodeIndex = Hierarchy.GetNodeIndex(NodeName);
if (NodeIndex != INDEX_NONE)
{
FConstraintNodeData& NodeData = Hierarchy.GetNodeData<FConstraintNodeData>(NodeIndex);
if (NodeData.DoesHaveConstraint())
{
FTransform LocalTransform = Hierarchy.GetLocalTransform(NodeIndex);
int32 ParentIndex = Hierarchy.GetParentIndex(NodeIndex);
FTransform ParentTransform = (ParentIndex != INDEX_NONE)? Hierarchy.GetGlobalTransform(ParentIndex) : FTransform::Identity;
FTransform ConstraintTransform = ResolveConstraints(LocalTransform, ParentTransform, NodeData);
NodeData.ConstraintOffset.ApplyInverseOffset(ConstraintTransform, LocalTransform);
Hierarchy.SetGlobalTransform(NodeIndex, LocalTransform * ParentTransform);
}
}
}
void UHierarchicalRig::EvaluateNode(const FName& NodeName)
{
// constraints have to update when current transform changes - I think that should happen before here
ApplyConstraint(NodeName);
int32 NodeIndex = Hierarchy.GetNodeIndex(NodeName);
if (NodeIndex != INDEX_NONE && NodeIndex < DependencyGraph.Num())
{
for(int32 ChildNodeIndex : DependencyGraph[NodeIndex])
{
FName ChildNodeName = Hierarchy.GetNodeName(ChildNodeIndex);
int32 ParentIndex = Hierarchy.GetParentIndex(ChildNodeIndex);
if (ParentIndex != INDEX_NONE)
{
FTransform ParentTransform = Hierarchy.GetGlobalTransform(ParentIndex);
// Note we don't call SetGlobalTransform here as the local transform has not changed,
// so we dont want to introduce error
Hierarchy.GetTransforms()[ChildNodeIndex] = Hierarchy.GetLocalTransform(ChildNodeIndex) * ParentTransform;
}
ApplyConstraint(ChildNodeName);
}
}
}
void UHierarchicalRig::GetDependentArray(const FName& Name, TArray<FName>& OutList) const
{
int32 NodeIndex = Hierarchy.GetNodeIndex(Name);
OutList.Reset();
if (NodeIndex != INDEX_NONE)
{
FName ParentName = Hierarchy.GetParentName(NodeIndex);
if (ParentName != NAME_None)
{
OutList.AddUnique(ParentName);
}
const FConstraintNodeData& NodeData = Hierarchy.GetNodeData<FConstraintNodeData>(NodeIndex);
const TArray<FTransformConstraint>& NodeConstraints = NodeData.GetConstraints();
for (int32 ConstraintsIndex = 0; ConstraintsIndex < NodeConstraints.Num(); ++ConstraintsIndex)
{
if (NodeConstraints[ConstraintsIndex].TargetNode != NAME_None)
{
OutList.AddUnique(NodeConstraints[ConstraintsIndex].TargetNode);
}
}
}
}
FTransform UHierarchicalRig::ResolveConstraints(const FTransform& LocalTransform, const FTransform& ParentTransform, const FConstraintNodeData& NodeData)
{
FTransform CurrentLocalTransform = LocalTransform;
FGetGlobalTransform OnGetGlobalTransform;
OnGetGlobalTransform.BindUObject(this, &UHierarchicalRig::GetGlobalTransform);
return AnimationCore::SolveConstraints(CurrentLocalTransform, ParentTransform, NodeData.GetConstraints(), OnGetGlobalTransform);
}
void UHierarchicalRig::Sort()
{
CreateSortedNodes();
}
UControlManipulator* UHierarchicalRig::FindManipulator(const FName& Name)
{
for (UControlManipulator* Manipulator : Manipulators)
{
if (Manipulator && Manipulator->Name == Name)
{
return Manipulator;
}
}
return nullptr;
}
void UHierarchicalRig::GetMappableNodeData(TArray<FName>& OutNames, TArray<FTransform>& OutTransforms) const
{
OutNames.Reset();
OutTransforms.Reset();
// now add all nodes
TArray<FNodeObject> Nodes = Hierarchy.GetNodes();
const TArray<FTransform>& Transforms = Hierarchy.GetTransforms();
for (int32 Index = 0; Index < Nodes.Num(); ++Index)
{
const FConstraintNodeData* UserData = static_cast<const FConstraintNodeData*> (Hierarchy.GetUserDataImpl(Index));
// if no node is linked, we only allow them to map, so add them
if (UserData->LinkedNode == NAME_None)
{
OutNames.Add(Nodes[Index].Name);
OutTransforms.Add(Transforms[Index]);
}
}
}
bool UHierarchicalRig::RenameNode(const FName& CurrentNodeName, const FName& NewNodeName)
{
if (Hierarchy.Contains(NewNodeName))
{
// the name is already used
return false;
}
if (Hierarchy.Contains(CurrentNodeName))
{
const int32 NodeIndex = Hierarchy.GetNodeIndex(CurrentNodeName);
Hierarchy.SetNodeName(NodeIndex, NewNodeName);
// now updates Constraints as well as data Constraints
for (int32 Index = 0; Index < Hierarchy.UserData.Num(); ++Index)
{
FConstraintNodeData& ConstraintNodeData = Hierarchy.UserData[Index];
if (ConstraintNodeData.LinkedNode == CurrentNodeName)
{
ConstraintNodeData.LinkedNode = NewNodeName;
}
FTransformConstraint* Constraint = ConstraintNodeData.FindConstraint(CurrentNodeName);
if (Constraint)
{
Constraint->TargetNode = NewNodeName;
}
}
for (int32 Index = 0; Index < Constraints.Num(); ++Index)
{
FTransformConstraint& Constraint = Constraints[Index];
if (Constraint.SourceNode == CurrentNodeName)
{
Constraint.SourceNode = NewNodeName;
}
if (Constraint.TargetNode == CurrentNodeName)
{
Constraint.TargetNode = NewNodeName;
}
}
for (int32 Index = 0; Index < Manipulators.Num(); ++Index)
{
UControlManipulator* Manipulator = Manipulators[Index];
if (Manipulator)
{
if (Manipulator->Name == CurrentNodeName)
{
Manipulator->Name = NewNodeName;
}
}
}
return true;
}
return false;
}
void UHierarchicalRig::Setup()
{
//Initialize();
}
#undef LOCTEXT_NAMESPACE | 29.292208 | 276 | 0.764649 | windystrife |
51150480081cae85b33c08a4b31f2dc9e9fcc218 | 25,801 | cpp | C++ | lib/vdf/LayeredGrid.cpp | yyr/vapor | cdebac81212ffa3f811064bbd7625ffa9089782e | [
"BSD-3-Clause"
] | null | null | null | lib/vdf/LayeredGrid.cpp | yyr/vapor | cdebac81212ffa3f811064bbd7625ffa9089782e | [
"BSD-3-Clause"
] | null | null | null | lib/vdf/LayeredGrid.cpp | yyr/vapor | cdebac81212ffa3f811064bbd7625ffa9089782e | [
"BSD-3-Clause"
] | null | null | null | #include <iostream>
#include <cassert>
#include <cmath>
#include <cfloat>
#include "vapor/LayeredGrid.h"
using namespace std;
using namespace VAPoR;
LayeredGrid::LayeredGrid(
const size_t bs[3],
const size_t min[3],
const size_t max[3],
const double extents[6],
const bool periodic[3],
float ** blks,
float ** coords,
int varying_dim
) : RegularGrid(bs,min,max,extents,periodic,blks) {
//
// Shallow copy blocks
//
size_t nblocks = RegularGrid::GetNumBlks();
_coords = new float*[nblocks];
for (int i=0; i<nblocks; i++) {
_coords[i] = coords[i];
}
_varying_dim = varying_dim;
if (_varying_dim < 0 || _varying_dim > 2) _varying_dim = 2;
//
// Periodic, varying dimensions are not supported
//
if (periodic[_varying_dim]) SetPeriodic(periodic);
_GetUserExtents(_extents);
RegularGrid::_SetExtents(_extents);
}
LayeredGrid::LayeredGrid(
const size_t bs[3],
const size_t min[3],
const size_t max[3],
const double extents[6],
const bool periodic[3],
float ** blks,
float ** coords,
int varying_dim,
float missing_value
) : RegularGrid(bs,min,max,extents,periodic,blks, missing_value) {
//
// Shallow copy blocks
//
size_t nblocks = RegularGrid::GetNumBlks();
_coords = new float*[nblocks];
for (int i=0; i<nblocks; i++) {
_coords[i] = coords[i];
}
_varying_dim = varying_dim;
if (_varying_dim < 0 || _varying_dim > 2) _varying_dim = 2;
assert(periodic[_varying_dim] == false);
_GetUserExtents(_extents);
RegularGrid::_SetExtents(_extents);
}
LayeredGrid::~LayeredGrid() {
if (_coords) delete [] _coords;
}
void LayeredGrid::GetBoundingBox(
const size_t min[3],
const size_t max[3],
double extents[6]
) const {
size_t mymin[] = {min[0],min[1],min[2]};
size_t mymax[] = {max[0],max[1],max[2]};
//
// Don't stop until we find valid extents. When missing values
// are present it's possible that the missing value dimension has
// an entire plane of missing values
//
bool done = false;
while (! done) {
done = true;
_GetBoundingBox(mymin, mymax, extents);
if (_varying_dim == 0) {
if (extents[0] == FLT_MAX && mymin[0]<mymax[0]) {
mymin[0] = mymin[0]+1;
done = false;
}
if (extents[5] == -FLT_MAX && mymax[0]>mymin[0]) {
mymax[0] = mymax[0]-1;
done = false;
}
}
else if (_varying_dim == 1) {
if (extents[1] == FLT_MAX && mymin[1]<mymax[1]) {
mymin[1] = mymin[1]+1;
done = false;
}
if (extents[5] == -FLT_MAX && mymax[1]>mymin[1]) {
mymax[1] = mymax[1]-1;
done = false;
}
}
else if (_varying_dim == 2) {
if (extents[2] == FLT_MAX && mymin[2]<mymax[2]) {
mymin[2] = mymin[2]+1;
done = false;
}
if (extents[5] == -FLT_MAX && mymax[2]>mymin[2]) {
mymax[2] = mymax[2]-1;
done = false;
}
}
}
}
void LayeredGrid::_GetBoundingBox(
const size_t min[3],
const size_t max[3],
double extents[6]
) const {
// Get extents of non-varying dimension. Values returned for
// varying dimension are coordinates for first and last grid
// point, respectively, which in general are not the extents
// of the bounding box.
//
RegularGrid::GetUserCoordinates(
min[0], min[1], min[2], &(extents[0]), &(extents[1]), &(extents[2])
);
RegularGrid::GetUserCoordinates(
max[0], max[1], max[2], &(extents[3]), &(extents[4]), &(extents[5])
);
// Initialize min and max coordinates of varying dimension with
// coordinates of "first" and "last" grid point. Coordinates of
// varying dimension are stored as values of a scalar function
// sampling the coordinate space.
//
float mincoord = FLT_MAX;
float maxcoord = -FLT_MAX;
float mv = GetMissingValue();
assert(_varying_dim >= 0 && _varying_dim <= 2);
bool flip = (
_AccessIJK(_coords, 0, 0, min[_varying_dim]) >
_AccessIJK(_coords, 0, 0, max[_varying_dim])
);
// Now find the extreme values of the varying dimension's coordinates
//
if (_varying_dim == 0) { // I plane
// Find min coordinate in first plane
//
for (int k = min[2]; k<=max[2]; k++) {
for (int j = min[1]; j<=max[1]; j++) {
float v = _AccessIJK(_coords, min[0],j,k);
if (v == mv) continue;
if (! flip) {
if (v<mincoord) mincoord = v;
} else {
if (v>mincoord) mincoord = v;
}
}
}
// Find max coordinate in last plane
//
for (int k = min[2]; k<=max[2]; k++) {
for (int j = min[1]; j<=max[1]; j++) {
float v = _AccessIJK(_coords, max[0],j,k);
if (v == mv) continue;
if (! flip) {
if (v>maxcoord) maxcoord = v;
} else {
if (v<maxcoord) maxcoord = v;
}
}
}
}
else if (_varying_dim == 1) { // J plane
for (int k = min[2]; k<=max[2]; k++) {
for (int i = min[0]; i<=max[0]; i++) {
float v = _AccessIJK(_coords, i,min[1],k);
if (v == mv) continue;
if (! flip) {
if (v<mincoord) mincoord = v;
} else {
if (v>mincoord) mincoord = v;
}
}
}
for (int k = min[2]; k<=max[2]; k++) {
for (int i = min[0]; i<=max[0]; i++) {
float v = _AccessIJK(_coords, i,max[1],k);
if (v == mv) continue;
if (! flip) {
if (v>maxcoord) maxcoord = v;
} else {
if (v<maxcoord) maxcoord = v;
}
}
}
}
else { // _varying_dim == 2 (K plane)
for (int j = min[1]; j<=max[1]; j++) {
for (int i = min[0]; i<=max[0]; i++) {
float v = _AccessIJK(_coords, i,j,min[2]);
if (v == mv) continue;
if (! flip) {
if (v<mincoord) mincoord = v;
} else {
if (v>mincoord) mincoord = v;
}
}
}
for (int j = min[1]; j<=max[1]; j++) {
for (int i = min[0]; i<=max[0]; i++) {
float v = _AccessIJK(_coords, i,j,max[2]);
if (v == mv) continue;
if (! flip) {
if (v>maxcoord) maxcoord = v;
} else {
if (v<maxcoord) maxcoord = v;
}
}
}
}
extents[_varying_dim] = mincoord;
extents[_varying_dim+3] = maxcoord;
}
void LayeredGrid::GetEnclosingRegion(
const double minu[3], const double maxu[3],
size_t min[3], size_t max[3]
) const {
assert (_varying_dim == 2); // Only z varying dim currently supported
//
// Get coords for non-varying dimension
//
RegularGrid::GetEnclosingRegion(minu, maxu, min, max);
// we have the correct results
// for X and Y dimensions, but the Z levels may not be completely
// contained in the box. We need to verify and possibly expand
// the min and max Z values.
//
size_t dims[3];
GetDimensions(dims);
bool done;
double z;
if (maxu[2] >= minu[2]) {
//
// first do max, then min
//
done = false;
for (int k=0; k<dims[2] && ! done; k++) {
done = true;
max[2] = k;
for (int j = min[1]; j<=max[1] && done; j++) {
for (int i = min[0]; i<=max[0] && done; i++) {
z = _AccessIJK(_coords, i, j, k); // get Z coordinate
if (z < maxu[2]) {
done = false;
}
}
}
}
done = false;
for (int k = dims[2]-1; k>=0 && ! done; k--) {
done = true;
min[2] = k;
for (int j = min[1]; j<=max[1] && done; j++) {
for (int i = min[0]; i<=max[0] && done; i++) {
z = _AccessIJK(_coords, i, j, k); // get Z coordinate
if (z > minu[2]) {
done = false;
}
}
}
}
}
else {
//
// first do max, then min
//
done = false;
for (int k=0; k<dims[2] && ! done; k++) {
done = true;
max[2] = k;
for (int j = min[1]; j<=max[1] && done; j++) {
for (int i = min[0]; i<=max[0] && done; i++) {
z = _AccessIJK(_coords, i, j, k); // get Z coordinate
if (z > maxu[2]) {
done = false;
}
}
}
}
done = false;
for (int k = dims[2]-1; k>=0 && ! done; k--) {
done = true;
min[2] = k;
for (int j = min[1]; j<=max[1] && done; j++) {
for (int i = min[0]; i<=max[0] && done; i++) {
z = _AccessIJK(_coords, i, j, k); // get Z coordinate
if (z < maxu[2]) {
done = false;
}
}
}
}
}
}
float LayeredGrid::GetValue(double x, double y, double z) const {
_ClampCoord(x,y,z);
if (! InsideGrid(x,y,z)) return(GetMissingValue());
size_t dims[3];
GetDimensions(dims);
// Get the indecies of the cell containing the point
//
size_t i0, j0, k0;
size_t i1, j1, k1;
GetIJKIndexFloor(x,y,z, &i0,&j0,&k0);
if (i0 == dims[0]-1) i1 = i0;
else i1 = i0+1;
if (j0 == dims[1]-1) j1 = j0;
else j1 = j0+1;
if (k0 == dims[2]-1) k1 = k0;
else k1 = k0+1;
// Get user coordinates of cell containing point
//
double x0, y0, z0, x1, y1, z1;
RegularGrid::GetUserCoordinates(i0,j0,k0, &x0, &y0, &z0);
RegularGrid::GetUserCoordinates(i1,j1,k1, &x1, &y1, &z1);
//
// Calculate interpolation weights. We always interpolate along
// the varying dimension last (the kwgt)
//
double iwgt, jwgt, kwgt;
if (_varying_dim == 0) {
// We have to interpolate coordinate of varying dimension
//
x0 = _interpolateVaryingCoord(i0,j0,k0,x,y,z);
x1 = _interpolateVaryingCoord(i1,j0,k0,x,y,z);
if (y1!=y0) iwgt = fabs((y-y0) / (y1-y0));
else iwgt = 0.0;
if (z1!=z0) jwgt = fabs((z-z0) / (z1-z0));
else jwgt = 0.0;
if (x1!=x0) kwgt = fabs((x-x0) / (x1-x0));
else kwgt = 0.0;
}
else if (_varying_dim == 1) {
y0 = _interpolateVaryingCoord(i0,j0,k0,x,y,z);
y1 = _interpolateVaryingCoord(i0,j1,k0,x,y,z);
if (x1!=x0) iwgt = fabs((x-x0) / (x1-x0));
else iwgt = 0.0;
if (z1!=z0) jwgt = fabs((z-z0) / (z1-z0));
else jwgt = 0.0;
if (y1!=y0) kwgt = fabs((y-y0) / (y1-y0));
else kwgt = 0.0;
}
else {
z0 = _interpolateVaryingCoord(i0,j0,k0,x,y,z);
z1 = _interpolateVaryingCoord(i0,j0,k1,x,y,z);
if (x1!=x0) iwgt = fabs((x-x0) / (x1-x0));
else iwgt = 0.0;
if (y1!=y0) jwgt = fabs((y-y0) / (y1-y0));
else jwgt = 0.0;
if (z1!=z0) kwgt = fabs((z-z0) / (z1-z0));
else kwgt = 0.0;
}
if (GetInterpolationOrder() == 0) {
if (iwgt>0.5) i0++;
if (jwgt>0.5) j0++;
if (kwgt>0.5) k0++;
return(AccessIJK(i0,j0,k0));
}
//
// perform tri-linear interpolation
//
double p0,p1,p2,p3,p4,p5,p6,p7;
p0 = AccessIJK(i0,j0,k0);
if (p0 == GetMissingValue()) return (GetMissingValue());
if (iwgt!=0.0) {
p1 = AccessIJK(i1,j0,k0);
if (p1 == GetMissingValue()) return (GetMissingValue());
}
else p1 = 0.0;
if (jwgt!=0.0) {
p2 = AccessIJK(i0,j1,k0);
if (p2 == GetMissingValue()) return (GetMissingValue());
}
else p2 = 0.0;
if (iwgt!=0.0 && jwgt!=0.0) {
p3 = AccessIJK(i1,j1,k0);
if (p3 == GetMissingValue()) return (GetMissingValue());
}
else p3 = 0.0;
if (kwgt!=0.0) {
p4 = AccessIJK(i0,j0,k1);
if (p4 == GetMissingValue()) return (GetMissingValue());
}
else p4 = 0.0;
if (kwgt!=0.0 && iwgt!=0.0) {
p5 = AccessIJK(i1,j0,k1);
if (p5 == GetMissingValue()) return (GetMissingValue());
}
else p5 = 0.0;
if (kwgt!=0.0 && jwgt!=0.0) {
p6 = AccessIJK(i0,j1,k1);
if (p6 == GetMissingValue()) return (GetMissingValue());
}
else p6 = 0.0;
if (kwgt!=0.0 && iwgt!=0.0 && jwgt!=0.0) {
p7 = AccessIJK(i1,j1,k1);
if (p7 == GetMissingValue()) return (GetMissingValue());
}
else p7 = 0.0;
double c0 = p0+iwgt*(p1-p0) + jwgt*((p2+iwgt*(p3-p2))-(p0+iwgt*(p1-p0)));
double c1 = p4+iwgt*(p5-p4) + jwgt*((p6+iwgt*(p7-p6))-(p4+iwgt*(p5-p4)));
return(c0+kwgt*(c1-c0));
}
void LayeredGrid::_GetUserExtents(double extents[6]) const {
size_t dims[3];
GetDimensions(dims);
size_t min[3] = {0,0,0};
size_t max[3] = {dims[0]-1, dims[1]-1, dims[2]-1};
LayeredGrid::GetBoundingBox(min, max, extents);
}
int LayeredGrid::GetUserCoordinates(
size_t i, size_t j, size_t k,
double *x, double *y, double *z
) const {
// First get coordinates of non-varying dimensions
// The varying dimension coordinate returned is ignored
//
int rc = RegularGrid::GetUserCoordinates(i,j,k,x,y,z);
if (rc<0) return(rc);
// Now get coordinates of varying dimension
//
if (_varying_dim == 0) {
*x = _GetVaryingCoord(i,j,k);
}
else if (_varying_dim == 1) {
*y = _GetVaryingCoord(i,j,k);
}
else {
*z = _GetVaryingCoord(i,j,k);
}
return(0);
}
void LayeredGrid::GetIJKIndex(
double x, double y, double z,
size_t *i, size_t *j, size_t *k
) const {
// First get ijk index of non-varying dimensions
// N.B. index returned for varying dimension is bogus
//
RegularGrid::GetIJKIndex(x,y,z, i,j,k);
size_t dims[3];
GetDimensions(dims);
// At this point the ijk indecies are correct for the non-varying
// dimensions. We only need to find the index for the varying dimension
//
if (_varying_dim == 0) {
size_t i0, j0, k0;
LayeredGrid::GetIJKIndexFloor(x,y,z,&i0, &j0, &k0);
if (i0 == dims[0]-1) { // on boundary
*i = i0;
return;
}
double x0 = _interpolateVaryingCoord(i0,j0,k0,x,y,z);
double x1 = _interpolateVaryingCoord(i0+1,j0,k0,x,y,z);
if (fabs(x-x0) < fabs(x-x1)) {
*i = i0;
}
else {
*i = i0+1;
}
}
else if (_varying_dim == 1) {
size_t i0, j0, k0;
LayeredGrid::GetIJKIndexFloor(x,y,z,&i0, &j0, &k0);
if (j0 == dims[1]-1) { // on boundary
*j = j0;
return;
}
double y0 = _interpolateVaryingCoord(i0,j0,k0,x,y,z);
double y1 = _interpolateVaryingCoord(i0,j0+1,k0,x,y,z);
if (fabs(y-y0) < fabs(y-y1)) {
*j = j0;
}
else {
*j = j0+1;
}
}
else if (_varying_dim == 2) {
size_t i0, j0, k0;
LayeredGrid::GetIJKIndexFloor(x,y,z,&i0, &j0, &k0);
if (k0 == dims[2]-1) { // on boundary
*k = k0;
return;
}
double z0 = _interpolateVaryingCoord(i0,j0,k0,x,y,z);
double z1 = _interpolateVaryingCoord(i0,j0,k0+1,x,y,z);
if (fabs(z-z0) < fabs(z-z1)) {
*k = k0;
}
else {
*k = k0+1;
}
}
}
void LayeredGrid::GetIJKIndexFloor(
double x, double y, double z,
size_t *i, size_t *j, size_t *k
) const {
// First get ijk index of non-varying dimensions
// N.B. index returned for varying dimension is bogus
//
size_t i0, j0, k0;
RegularGrid::GetIJKIndexFloor(x,y,z, &i0,&j0,&k0);
size_t dims[3];
GetDimensions(dims);
size_t i1, j1, k1;
if (i0 == dims[0]-1) i1 = i0;
else i1 = i0+1;
if (j0 == dims[1]-1) j1 = j0;
else j1 = j0+1;
if (k0 == dims[2]-1) k1 = k0;
else k1 = k0+1;
// At this point the ijk indecies are correct for the non-varying
// dimensions. We only need to find the index for the varying dimension
//
if (_varying_dim == 0) {
*j = j0; *k = k0;
i0 = 0;
i1 = dims[0]-1;
double x0 = _interpolateVaryingCoord(i0,j0,k0,x,y,z);
double x1 = _interpolateVaryingCoord(i1,j0,k0,x,y,z);
// see if point is outside grid or on boundary
//
if ((x-x0) * (x-x1) >= 0.0) {
if (x0<=x1) {
if (x<=x0) *i = 0;
else if (x>=x1) *i = dims[0]-1;
}
else {
if (x>=x0) *i = 0;
else if (x<=x1) *i = dims[0]-1;
}
return;
}
//
// X-coord of point must be between x0 and x1
//
while (i1-i0 > 1) {
x1 = _interpolateVaryingCoord((i0+i1)>>1,j0,k0,x,y,z);
if (x1 == x) { // pathological case
//*i = (i0+i1)>>1;
i0 = (i0+i1)>>1;
break;
}
// if the signs of differences change then the coordinate
// is between x0 and x1
//
if ((x-x0) * (x-x1) <= 0.0) {
i1 = (i0+i1)>>1;
}
else {
i0 = (i0+i1)>>1;
x0 = x1;
}
}
*i = i0;
}
else if (_varying_dim == 1) {
*i = i0; *k = k0;
// Now search for the closest point
//
j0 = 0;
j1 = dims[1]-1;
double y0 = _interpolateVaryingCoord(i0,j0,k0,x,y,z);
double y1 = _interpolateVaryingCoord(i0,j1,k0,x,y,z);
// see if point is outside grid or on boundary
//
if ((y-y0) * (y-y1) >= 0.0) {
if (y0<=y1) {
if (y<=y0) *j = 0;
else if (y>=y1) *j = dims[1]-1;
}
else {
if (y>=y0) *j = 0;
else if (y<=y1) *j = dims[1]-1;
}
return;
}
//
// Y-coord of point must be between y0 and y1
//
while (j1-j0 > 1) {
y1 = _interpolateVaryingCoord(i0,(j0+j1)>>1,k0,x,y,z);
if (y1 == y) { // pathological case
//*j = (j0+j1)>>1;
j0 = (j0+j1)>>1;
break;
}
// if the signs of differences change then the coordinate
// is between y0 and y1
//
if ((y-y0) * (y-y1) <= 0.0) {
j1 = (j0+j1)>>1;
}
else {
j0 = (j0+j1)>>1;
y0 = y1;
}
}
*j = j0;
}
else { // _varying_dim == 2
*i = i0; *j = j0;
// Now search for the closest point
//
k0 = 0;
k1 = dims[2]-1;
double z0 = _interpolateVaryingCoord(i0,j0,k0,x,y,z);
double z1 = _interpolateVaryingCoord(i0,j0,k1,x,y,z);
// see if point is outside grid or on boundary
//
if ((z-z0) * (z-z1) >= 0.0) {
if (z0<=z1) {
if (z<=z0) *k = 0;
else if (z>=z1) *k = dims[2]-1;
}
else {
if (z>=z0) *k = 0;
else if (z<=z1) *k = dims[2]-1;
}
return;
}
//
// Z-coord of point must be between z0 and z1
//
while (k1-k0 > 1) {
z1 = _interpolateVaryingCoord(i0,j0,(k0+k1)>>1,x,y,z);
if (z1 == z) { // pathological case
//*k = (k0+k1)>>1;
k0 = (k0+k1)>>1;
break;
}
// if the signs of differences change then the coordinate
// is between z0 and z1
//
if ((z-z0) * (z-z1) <= 0.0) {
k1 = (k0+k1)>>1;
}
else {
k0 = (k0+k1)>>1;
z0 = z1;
}
}
*k = k0;
}
}
int LayeredGrid::Reshape(
const size_t min[3],
const size_t max[3],
const bool periodic[3]
) {
int rc = RegularGrid::Reshape(min,max,periodic);
if (rc<0) return(-1);
_GetUserExtents(_extents);
return(0);
}
void LayeredGrid::SetPeriodic(const bool periodic[3]) {
bool pvec[3];
for (int i=0; i<3; i++) pvec[i] = periodic[i];
pvec[_varying_dim] = false;
RegularGrid::SetPeriodic(pvec);
}
bool LayeredGrid::InsideGrid(double x, double y, double z) const {
// Clamp coordinates on periodic boundaries to reside within the
// grid extents (vary-dimensions can not have periodic boundaries)
//
_ClampCoord(x,y,z);
// Do a quick check to see if the point is completely outside of
// the grid bounds.
//
double extents[6];
GetUserExtents(extents);
if (extents[0] < extents[3]) {
if (x<extents[0] || x>extents[3]) return (false);
}
else {
if (x>extents[0] || x<extents[3]) return (false);
}
if (extents[1] < extents[4]) {
if (y<extents[1] || y>extents[4]) return (false);
}
else {
if (y>extents[1] || y<extents[4]) return (false);
}
if (extents[2] < extents[5]) {
if (z<extents[2] || z>extents[5]) return (false);
}
else {
if (z>extents[2] || z<extents[5]) return (false);
}
// If we get to here the point's non-varying dimension coordinates
// must be inside the grid. It is only the varying dimension
// coordinates that we need to check
//
// Get the indecies of the cell containing the point
// Only the indecies for the non-varying dimensions are correctly
// returned by GetIJKIndexFloor()
//
size_t dims[3];
GetDimensions(dims);
size_t i0, j0, k0;
size_t i1, j1, k1;
RegularGrid::GetIJKIndexFloor(x,y,z, &i0,&j0,&k0);
if (i0 == dims[0]-1) i1 = i0;
else i1 = i0+1;
if (j0 == dims[1]-1) j1 = j0;
else j1 = j0+1;
if (k0 == dims[2]-1) k1 = k0;
else k1 = k0+1;
//
// See if the varying dimension coordinate of the point is
// completely above or below all of the corner points in the first (last)
// cell in the column of cells containing the point
//
double t00, t01, t10, t11; // varying dimension coord of "top" cell
double b00, b01, b10, b11; // varying dimension coord of "bottom" cell
double vc; // varying coordinate value
if (_varying_dim == 0) {
t00 = _GetVaryingCoord( dims[0]-1, j0, k0);
t01 = _GetVaryingCoord( dims[0]-1, j1, k0);
t10 = _GetVaryingCoord( dims[0]-1, j0, k1);
t11 = _GetVaryingCoord( dims[0]-1, j1, k1);
b00 = _GetVaryingCoord( 0, j0, k0);
b01 = _GetVaryingCoord( 0, j1, k0);
b10 = _GetVaryingCoord( 0, j0, k1);
b11 = _GetVaryingCoord( 0, j1, k1);
vc = x;
}
else if (_varying_dim == 1) {
t00 = _GetVaryingCoord( i0, dims[1]-1, k0);
t01 = _GetVaryingCoord( i1, dims[1]-1, k0);
t10 = _GetVaryingCoord( i0, dims[1]-1, k1);
t11 = _GetVaryingCoord( i1, dims[1]-1, k1);
b00 = _GetVaryingCoord( i0, 0, k0);
b01 = _GetVaryingCoord( i1, 0, k0);
b10 = _GetVaryingCoord( i0, 0, k1);
b11 = _GetVaryingCoord( i1, 0, k1);
vc = y;
}
else { // _varying_dim == 2
t00 = _GetVaryingCoord( i0, j0, dims[2]-1);
t01 = _GetVaryingCoord( i1, j0, dims[2]-1);
t10 = _GetVaryingCoord( i0, j1, dims[2]-1);
t11 = _GetVaryingCoord( i1, j1, dims[2]-1);
b00 = _GetVaryingCoord( i0, j0, 0);
b01 = _GetVaryingCoord( i1, j0, 0);
b10 = _GetVaryingCoord( i0, j1, 0);
b11 = _GetVaryingCoord( i1, j1, 0);
vc = z;
}
if (b00<t00) {
// If coordinate is between all of the cell's top and bottom
// coordinates the point must be in the grid
//
if (b00<vc && b01<vc && b10<vc && b11<vc &&
t00>vc && t01>vc && t10>vc && t11>vc) {
return(true);
}
//
// if coordinate is above or below all corner points
// the input point must be outside the grid
//
if (b00>vc && b01>vc && b10>vc && b11>vc) return(false);
if (t00<vc && t01<vc && t10<vc && t11<vc) return(false);
}
else {
if (b00>vc && b01>vc && b10>vc && b11>vc &&
t00<vc && t01<vc && t10<vc && t11<vc) {
return(true);
}
if (b00<vc && b01<vc && b10<vc && b11<vc) return(false);
if (t00>vc && t01>vc && t10>vc && t11>vc) return(false);
}
// If we get this far the point is either inside or outside of a
// boundary cell on the varying dimension. Need to interpolate
// the varying coordinate of the cell
// Varying dimesion coordinate value returned by GetUserCoordinates
// is not valid
//
double x0, y0, z0, x1, y1, z1;
RegularGrid::GetUserCoordinates(i0,j0,k0, &x0, &y0, &z0);
RegularGrid::GetUserCoordinates(i1,j1,k1, &x1, &y1, &z1);
double iwgt, jwgt;
if (_varying_dim == 0) {
if (y1!=y0) iwgt = fabs((y-y0) / (y1-y0));
else iwgt = 0.0;
if (z1!=z0) jwgt = fabs((z-z0) / (z1-z0));
else jwgt = 0.0;
}
else if (_varying_dim == 1) {
if (x1!=x0) iwgt = fabs((x-x0) / (x1-x0));
else iwgt = 0.0;
if (z1!=z0) jwgt = fabs((z-z0) / (z1-z0));
else jwgt = 0.0;
}
else {
if (x1!=x0) iwgt = fabs((x-x0) / (x1-x0));
else iwgt = 0.0;
if (y1!=y0) jwgt = fabs((y-y0) / (y1-y0));
else jwgt = 0.0;
}
double t = t00+iwgt*(t01-t00) + jwgt*((t10+iwgt*(t11-t10))-(t00+iwgt*(t01-t00)));
double b = b00+iwgt*(b01-b00) + jwgt*((b10+iwgt*(b11-b10))-(b00+iwgt*(b01-b00)));
if (b<t) {
if (vc<b || vc>t) return(false);
}
else {
if (vc>b || vc<t) return(false);
}
return(true);
}
void LayeredGrid::GetMinCellExtents(double *x, double *y, double *z) const {
//
// Get X and Y dimension minimums
//
RegularGrid::GetMinCellExtents(x,y,z);
size_t dims[3];
GetDimensions(dims);
if (dims[2] < 2) return;
double tmp;
*z = fabs(_extents[5] - _extents[3]);
for (int k=0; k<dims[2]-1; k++) {
for (int j=0; j<dims[1]; j++) {
for (int i=0; i<dims[0]; i++) {
float z0 = _GetVaryingCoord(i,j,k);
float z1 = _GetVaryingCoord(i,j,k+1);
tmp = fabs(z1-z0);
if (tmp<*z) *z = tmp;
}
}
}
}
double LayeredGrid::_GetVaryingCoord(size_t i, size_t j, size_t k) const {
double mv = GetMissingValue();
double c = _AccessIJK(_coords, i, j, k);
if (c != mv) return (c);
assert (c != mv);
size_t dims[3];
GetDimensions(dims);
//
// Varying coordinate for i,j,k is missing. Look along varying dimension
// axis for first grid point with non-missing value. First search
// below, then above. If no valid coordinate is found, use the
// grid minimum extent
//
if (_varying_dim == 0) {
size_t ii = i;
while (ii>0 && (c=_AccessIJK(_coords,ii-1,j,k)) == mv) ii--;
if (c!=mv) return (c);
ii = i;
while (ii<dims[0]-1 && (c=_AccessIJK(_coords,ii+1,j,k)) == mv) ii++;
if (c!=mv) return (c);
return(_extents[0]);
} else if (_varying_dim == 1) {
size_t jj = j;
while (jj>0 && (c=_AccessIJK(_coords,i,jj-1,k)) == mv) jj--;
if (c!=mv) return (c);
jj = j;
while (jj<dims[1]-1 && (c=_AccessIJK(_coords,i, jj+1,k)) == mv) jj++;
if (c!=mv) return (c);
return(_extents[1]);
} else if (_varying_dim == 2) {
size_t kk = k;
while (kk>0 && (c=_AccessIJK(_coords,i,j,kk-1)) == mv) kk--;
if (c!=mv) return (c);
kk = k;
while (kk<dims[2]-1 && (c=_AccessIJK(_coords,i,j,kk+1)) == mv) kk++;
if (c!=mv) return (c);
return(_extents[2]);
}
return(0.0);
}
double LayeredGrid::_interpolateVaryingCoord(
size_t i0, size_t j0, size_t k0,
double x, double y, double z) const {
// varying dimension coord at corner grid points of cell face
//
double c00, c01, c10, c11;
size_t dims[3];
GetDimensions(dims);
size_t i1, j1, k1;
if (i0 == dims[0]-1) i1 = i0;
else i1 = i0+1;
if (j0 == dims[1]-1) j1 = j0;
else j1 = j0+1;
if (k0 == dims[2]-1) k1 = k0;
else k1 = k0+1;
// Coordinates of grid points for non-varying dimensions
double x0, y0, z0, x1, y1, z1;
RegularGrid::GetUserCoordinates(i0,j0,k0, &x0, &y0, &z0);
RegularGrid::GetUserCoordinates(i1,j1,k1, &x1, &y1, &z1);
double iwgt, jwgt;
if (_varying_dim == 0) {
// Now get user coordinates of vary-dimension grid point
// N.B. Could just call LayeredGrid:GetUserCoordinates() for
// each of the four points but this is more efficient
//
c00 = _AccessIJK(_coords, i0, j0, k0);
c01 = _AccessIJK(_coords, i0, j1, k0);
c10 = _AccessIJK(_coords, i0, j0, k1);
c11 = _AccessIJK(_coords, i0, j1, k1);
if (y1!=y0) iwgt = fabs((y-y0) / (y1-y0));
else iwgt = 0.0;
if (z1!=z0) jwgt = fabs((z-z0) / (z1-z0));
else jwgt = 0.0;
}
else if (_varying_dim == 1) {
c00 = _AccessIJK(_coords, i0, j0, k0);
c01 = _AccessIJK(_coords, i1, j0, k0);
c10 = _AccessIJK(_coords, i0, j0, k1);
c11 = _AccessIJK(_coords, i1, j0, k1);
if (x1!=x0) iwgt = fabs((x-x0) / (x1-x0));
else iwgt = 0.0;
if (z1!=z0) jwgt = fabs((z-z0) / (z1-z0));
else jwgt = 0.0;
}
else { // _varying_dim == 2
c00 = _AccessIJK(_coords, i0, j0, k0);
c01 = _AccessIJK(_coords, i1, j0, k0);
c10 = _AccessIJK(_coords, i0, j1, k0);
c11 = _AccessIJK(_coords, i1, j1, k0);
if (x1!=x0) iwgt = fabs((x-x0) / (x1-x0));
else iwgt = 0.0;
if (y1!=y0) jwgt = fabs((y-y0) / (y1-y0));
else jwgt = 0.0;
}
double c = c00+iwgt*(c01-c00) + jwgt*((c10+iwgt*(c11-c10))-(c00+iwgt*(c01-c00)));
return(c);
}
| 23.476797 | 82 | 0.586218 | yyr |
5119450791c9c70e8f3501fa1f5c6ae74244ed2a | 738 | hpp | C++ | src/gui/hud/gui_ability.hpp | louiz/batajelo | 4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e | [
"BSL-1.0",
"BSD-2-Clause",
"Zlib",
"MIT"
] | 7 | 2015-01-28T09:17:08.000Z | 2020-04-21T13:51:16.000Z | src/gui/hud/gui_ability.hpp | louiz/batajelo | 4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e | [
"BSL-1.0",
"BSD-2-Clause",
"Zlib",
"MIT"
] | null | null | null | src/gui/hud/gui_ability.hpp | louiz/batajelo | 4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e | [
"BSL-1.0",
"BSD-2-Clause",
"Zlib",
"MIT"
] | 1 | 2020-07-11T09:20:25.000Z | 2020-07-11T09:20:25.000Z | #ifndef GUI_ABILITY_HPP_INCLUDED
#define GUI_ABILITY_HPP_INCLUDED
/**
* Contains all the information about an ability, for the GUI part. For
* example the icone to use, the activate callback (it can execute the
* ability directly, or change the LeftClick structure, which only involves
* the GUI)
*/
#include <gui/screen/left_click.hpp>
#include <functional>
class GuiAbility
{
public:
GuiAbility() = default;
~GuiAbility() = default;
LeftClick left_click;
std::function<void()> callback;
private:
GuiAbility(const GuiAbility&) = delete;
GuiAbility(GuiAbility&&) = delete;
GuiAbility& operator=(const GuiAbility&) = delete;
GuiAbility& operator=(GuiAbility&&) = delete;
};
#endif /* GUI_ABILITY_HPP_INCLUDED */
| 23.806452 | 75 | 0.738482 | louiz |
511c4044a743e00aa56c998735284dfc1fd86f47 | 243 | hpp | C++ | include/mutex.hpp | oskarirauta/podman-ubus | fb12bea03ce172d517fd1543249c45bba17b2a45 | [
"MIT"
] | null | null | null | include/mutex.hpp | oskarirauta/podman-ubus | fb12bea03ce172d517fd1543249c45bba17b2a45 | [
"MIT"
] | null | null | null | include/mutex.hpp | oskarirauta/podman-ubus | fb12bea03ce172d517fd1543249c45bba17b2a45 | [
"MIT"
] | 1 | 2022-01-08T07:03:58.000Z | 2022-01-08T07:03:58.000Z | #pragma once
#include <mutex>
#include <thread>
typedef void (*die_handler_func)(int);
struct MutexStore {
public:
std::mutex podman, podman_sched, podman_sock;
MutexStore(die_handler_func die_handler);
};
extern MutexStore mutex;
| 13.5 | 47 | 0.748971 | oskarirauta |
511d7daa914d64fcc4ae8455aad714116a838029 | 246 | cpp | C++ | src/010 - Summation of primes.cpp | montyanderson/euler | ba07a13c8afaa61edf35987f2a4db34c89b5ad39 | [
"MIT"
] | 1 | 2016-03-16T17:08:54.000Z | 2016-03-16T17:08:54.000Z | src/010 - Summation of primes.cpp | montyanderson/euler | ba07a13c8afaa61edf35987f2a4db34c89b5ad39 | [
"MIT"
] | null | null | null | src/010 - Summation of primes.cpp | montyanderson/euler | ba07a13c8afaa61edf35987f2a4db34c89b5ad39 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cmath>
#include "isPrime.hpp"
using namespace std;
int main() {
long int sum = 0;
for(int i = 2; i < 2000000; i++) {
if(isPrime(i) == true)
sum += i;
}
cout << sum << endl;
}
| 13.666667 | 38 | 0.50813 | montyanderson |
511f0d72292001e39395584e8374e6362a1995f3 | 3,520 | cpp | C++ | orca/gporca/libnaucrates/src/operators/CDXLScalarBitmapIndexProbe.cpp | vitessedata/gpdb.4.3.99.x | 9462aad5df1bf120a2a87456b1f9574712227da4 | [
"PostgreSQL",
"Apache-2.0"
] | 3 | 2017-12-10T16:41:21.000Z | 2020-07-08T12:59:12.000Z | orca/gporca/libnaucrates/src/operators/CDXLScalarBitmapIndexProbe.cpp | vitessedata/gpdb.4.3.99.x | 9462aad5df1bf120a2a87456b1f9574712227da4 | [
"PostgreSQL",
"Apache-2.0"
] | null | null | null | orca/gporca/libnaucrates/src/operators/CDXLScalarBitmapIndexProbe.cpp | vitessedata/gpdb.4.3.99.x | 9462aad5df1bf120a2a87456b1f9574712227da4 | [
"PostgreSQL",
"Apache-2.0"
] | 4 | 2017-12-10T16:41:35.000Z | 2020-11-28T12:20:30.000Z | //---------------------------------------------------------------------------
// Greenplum Database
// Copyright (C) 2014 Pivotal, Inc.
//
// @filename:
// CDXLScalarBitmapIndexProbe.cpp
//
// @doc:
// Class for representing DXL bitmap index probe operators
//
// @owner:
//
//
// @test:
//
//
//---------------------------------------------------------------------------
#include "naucrates/dxl/operators/CDXLIndexDescr.h"
#include "naucrates/dxl/operators/CDXLNode.h"
#include "naucrates/dxl/operators/CDXLScalarBitmapIndexProbe.h"
#include "naucrates/dxl/operators/CDXLTableDescr.h"
#include "naucrates/dxl/xml/CXMLSerializer.h"
#include "naucrates/dxl/xml/dxltokens.h"
using namespace gpdxl;
//---------------------------------------------------------------------------
// @function:
// CDXLScalarBitmapIndexProbe::CDXLScalarBitmapIndexProbe
//
// @doc:
// Ctor
//
//---------------------------------------------------------------------------
CDXLScalarBitmapIndexProbe::CDXLScalarBitmapIndexProbe
(
IMemoryPool *pmp,
CDXLIndexDescr *pdxlid
)
:
CDXLScalar(pmp),
m_pdxlid(pdxlid)
{
GPOS_ASSERT(NULL != m_pdxlid);
}
//---------------------------------------------------------------------------
// @function:
// CDXLScalarBitmapIndexProbe::~CDXLScalarBitmapIndexProbe
//
// @doc:
// Dtor
//
//---------------------------------------------------------------------------
CDXLScalarBitmapIndexProbe::~CDXLScalarBitmapIndexProbe()
{
m_pdxlid->Release();
}
//---------------------------------------------------------------------------
// @function:
// CDXLScalarBitmapIndexProbe::PstrOpName
//
// @doc:
// Operator name
//
//---------------------------------------------------------------------------
const CWStringConst *
CDXLScalarBitmapIndexProbe::PstrOpName() const
{
return CDXLTokens::PstrToken(EdxltokenScalarBitmapIndexProbe);
}
//---------------------------------------------------------------------------
// @function:
// CDXLScalarBitmapIndexProbe::SerializeToDXL
//
// @doc:
// Serialize operator in DXL format
//
//---------------------------------------------------------------------------
void
CDXLScalarBitmapIndexProbe::SerializeToDXL
(
CXMLSerializer *pxmlser,
const CDXLNode *pdxln
)
const
{
const CWStringConst *pstrElemName = PstrOpName();
pxmlser->OpenElement(CDXLTokens::PstrToken(EdxltokenNamespacePrefix), pstrElemName);
// serialize children
pdxln->SerializeChildrenToDXL(pxmlser);
// serialize index descriptor
m_pdxlid->SerializeToDXL(pxmlser);
pxmlser->CloseElement(CDXLTokens::PstrToken(EdxltokenNamespacePrefix), pstrElemName);
}
#ifdef GPOS_DEBUG
//---------------------------------------------------------------------------
// @function:
// CDXLScalarBitmapIndexProbe::AssertValid
//
// @doc:
// Checks whether operator node is well-structured
//
//---------------------------------------------------------------------------
void
CDXLScalarBitmapIndexProbe::AssertValid
(
const CDXLNode *pdxln,
BOOL fValidateChildren
)
const
{
// bitmap index probe has 1 child: the index condition list
GPOS_ASSERT(1 == pdxln->UlArity());
if (fValidateChildren)
{
CDXLNode *pdxlnIndexCondList = (*pdxln)[0];
GPOS_ASSERT(EdxlopScalarIndexCondList == pdxlnIndexCondList->Pdxlop()->Edxlop());
pdxlnIndexCondList->Pdxlop()->AssertValid(pdxlnIndexCondList, fValidateChildren);
}
// assert validity of index descriptor
GPOS_ASSERT(NULL != m_pdxlid->Pmdname());
GPOS_ASSERT(m_pdxlid->Pmdname()->Pstr()->FValid());
}
#endif // GPOS_DEBUG
// EOF
| 25.507246 | 86 | 0.549432 | vitessedata |
511f68ab4c70fb1c6b2d997d70d5029a71166217 | 1,651 | cpp | C++ | native/libs/ui/HdrCapabilities.cpp | Keneral/aframeworks | af1d0010bfb88751837fb1afc355705bd8a9ad8b | [
"Unlicense"
] | null | null | null | native/libs/ui/HdrCapabilities.cpp | Keneral/aframeworks | af1d0010bfb88751837fb1afc355705bd8a9ad8b | [
"Unlicense"
] | null | null | null | native/libs/ui/HdrCapabilities.cpp | Keneral/aframeworks | af1d0010bfb88751837fb1afc355705bd8a9ad8b | [
"Unlicense"
] | null | null | null | /*
* Copyright 2016 The Android Open Source Project
*
* 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 <ui/HdrCapabilities.h>
#include <binder/Parcel.h>
namespace android {
status_t HdrCapabilities::writeToParcel(Parcel* parcel) const
{
status_t result = parcel->writeInt32Vector(mSupportedHdrTypes);
if (result != OK) {
return result;
}
result = parcel->writeFloat(mMaxLuminance);
if (result != OK) {
return result;
}
result = parcel->writeFloat(mMaxAverageLuminance);
if (result != OK) {
return result;
}
result = parcel->writeFloat(mMinLuminance);
return result;
}
status_t HdrCapabilities::readFromParcel(const Parcel* parcel)
{
status_t result = parcel->readInt32Vector(&mSupportedHdrTypes);
if (result != OK) {
return result;
}
result = parcel->readFloat(&mMaxLuminance);
if (result != OK) {
return result;
}
result = parcel->readFloat(&mMaxAverageLuminance);
if (result != OK) {
return result;
}
result = parcel->readFloat(&mMinLuminance);
return result;
}
} // namespace android
| 27.516667 | 75 | 0.6808 | Keneral |
512308bd3bfb58307a904a5d872518cf11ac8f01 | 578 | cpp | C++ | codeforces/contests/round/655-div2/c.cpp | tysm/cpsols | 262212646203e516d1706edf962290de93762611 | [
"MIT"
] | 4 | 2020-10-05T19:24:10.000Z | 2021-07-15T00:45:43.000Z | codeforces/contests/round/655-div2/c.cpp | tysm/cpsols | 262212646203e516d1706edf962290de93762611 | [
"MIT"
] | null | null | null | codeforces/contests/round/655-div2/c.cpp | tysm/cpsols | 262212646203e516d1706edf962290de93762611 | [
"MIT"
] | null | null | null | #include <cpplib/stdinc.hpp>
int32_t main(){
desync();
int t;
cin >> t;
while(t--){
int n;
cin >> n;
vi arr(n);
int acc = 0, flag = 0;
for(int i=1; i<=n; ++i){
cin >> arr[i-1];
if(arr[i-1] == i)
flag = 0;
else if(!flag){
flag = 1;
acc++;
}
}
if(acc == 0)
cout << 0 << endl;
else if(acc == 1)
cout << 1 << endl;
else
cout << 2 << endl;
}
return 0;
}
| 19.266667 | 32 | 0.316609 | tysm |
5124d128b166defd1236b752cab620cdaef99725 | 2,969 | cpp | C++ | source/core/owt_base/internal/InternalClient.cpp | yfdandy/owt-server | 93b1721865907c6af94be4fdef8f191e59f345d2 | [
"Apache-2.0"
] | 890 | 2019-03-08T08:04:10.000Z | 2022-03-30T03:07:44.000Z | source/core/owt_base/internal/InternalClient.cpp | yfdandy/owt-server | 93b1721865907c6af94be4fdef8f191e59f345d2 | [
"Apache-2.0"
] | 583 | 2019-03-11T10:27:42.000Z | 2022-03-29T01:41:28.000Z | source/core/owt_base/internal/InternalClient.cpp | yfdandy/owt-server | 93b1721865907c6af94be4fdef8f191e59f345d2 | [
"Apache-2.0"
] | 385 | 2019-03-08T07:50:13.000Z | 2022-03-29T06:36:28.000Z | // Copyright (C) <2021> Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
#include "InternalClient.h"
#include "RawTransport.h"
namespace owt_base {
DEFINE_LOGGER(InternalClient, "owt.InternalClient");
InternalClient::InternalClient(
const std::string& streamId,
const std::string& protocol,
Listener* listener)
: m_client(new TransportClient(this))
, m_streamId(streamId)
, m_ready(false)
, m_listener(listener)
{
}
InternalClient::InternalClient(
const std::string& streamId,
const std::string& protocol,
const std::string& ip,
unsigned int port,
Listener* listener)
: InternalClient(streamId, protocol, listener)
{
if (!TransportSecret::getPassphrase().empty()) {
m_client->enableSecure();
}
m_client->createConnection(ip, port);
}
InternalClient::~InternalClient()
{
m_client->close();
m_client.reset();
}
void InternalClient::connect(const std::string& ip, unsigned int port)
{
m_client->createConnection(ip, port);
}
void InternalClient::onFeedback(const FeedbackMsg& msg)
{
if (!m_ready && msg.cmd != INIT_STREAM_ID) {
return;
}
ELOG_DEBUG("onFeedback ");
uint8_t sendBuffer[512];
sendBuffer[0] = TDT_FEEDBACK_MSG;
memcpy(&sendBuffer[1],
reinterpret_cast<uint8_t*>(const_cast<FeedbackMsg*>(&msg)),
sizeof(FeedbackMsg));
m_client->sendData((uint8_t*)sendBuffer, sizeof(FeedbackMsg) + 1);
}
void InternalClient::onConnected()
{
ELOG_DEBUG("On Connected %s", m_streamId.c_str());
if (m_listener) {
m_listener->onConnected();
}
if (!m_streamId.empty()) {
FeedbackMsg msg(VIDEO_FEEDBACK, INIT_STREAM_ID);
if (m_streamId.length() > 128) {
ELOG_WARN("Too long streamId:%s, will be resized",
m_streamId.c_str());
m_streamId.resize(128);
}
memcpy(&msg.buffer.data[0], m_streamId.c_str(), m_streamId.length());
msg.buffer.len = m_streamId.length();
onFeedback(msg);
}
m_ready = true;
}
void InternalClient::onData(uint8_t* buf, uint32_t len)
{
Frame* frame = nullptr;
MetaData* metadata = nullptr;
if (len <= 1) {
ELOG_DEBUG("Skip onData len: %u", (unsigned int)len);
return;
}
switch ((char) buf[0]) {
case TDT_MEDIA_FRAME:
frame = reinterpret_cast<Frame*>(buf + 1);
frame->payload = reinterpret_cast<uint8_t*>(buf + 1 + sizeof(Frame));
deliverFrame(*frame);
break;
case TDT_MEDIA_METADATA:
metadata = reinterpret_cast<MetaData*>(buf + 1);
metadata->payload = reinterpret_cast<uint8_t*>(buf + 1 + sizeof(MetaData));
deliverMetaData(*metadata);
break;
default:
break;
}
}
void InternalClient::onDisconnected()
{
if (m_listener) {
m_listener->onDisconnected();
}
}
} /* namespace owt_base */
| 25.376068 | 87 | 0.624453 | yfdandy |
5124fde61ab0ba9fb3cfaae95f0314ebb8feedfb | 10,699 | cpp | C++ | src/jet/volume_particle_emitter2.cpp | PavelBlend/fluid-engine-dev | 45b4bdbdb4c6d8c0beebc682180469198203b0ef | [
"MIT"
] | 1,355 | 2016-05-08T07:29:22.000Z | 2022-03-30T13:59:35.000Z | src/jet/volume_particle_emitter2.cpp | Taiyuan-Zhang/fluid-engine-dev | 45b4bdbdb4c6d8c0beebc682180469198203b0ef | [
"MIT"
] | 208 | 2016-05-25T19:47:27.000Z | 2022-01-17T04:18:29.000Z | src/jet/volume_particle_emitter2.cpp | Taiyuan-Zhang/fluid-engine-dev | 45b4bdbdb4c6d8c0beebc682180469198203b0ef | [
"MIT"
] | 218 | 2016-08-23T16:51:10.000Z | 2022-03-31T03:55:48.000Z | // Copyright (c) 2019 Doyub Kim
//
// I am making my contributions/submissions to this project solely in my
// personal capacity and am not conveying any rights to any intellectual
// property of any third parties.
#include <pch.h>
#include <jet/matrix2x2.h>
#include <jet/point_hash_grid_searcher2.h>
#include <jet/samplers.h>
#include <jet/surface_to_implicit2.h>
#include <jet/triangle_point_generator.h>
#include <jet/volume_particle_emitter2.h>
using namespace jet;
static const size_t kDefaultHashGridResolution = 64;
VolumeParticleEmitter2::VolumeParticleEmitter2(
const ImplicitSurface2Ptr& implicitSurface, const BoundingBox2D& maxRegion,
double spacing, const Vector2D& initialVel, const Vector2D& linearVel,
double angularVel, size_t maxNumberOfParticles, double jitter,
bool isOneShot, bool allowOverlapping, uint32_t seed)
: _rng(seed),
_implicitSurface(implicitSurface),
_bounds(maxRegion),
_spacing(spacing),
_initialVel(initialVel),
_linearVel(linearVel),
_angularVel(angularVel),
_maxNumberOfParticles(maxNumberOfParticles),
_jitter(jitter),
_isOneShot(isOneShot),
_allowOverlapping(allowOverlapping) {
_pointsGen = std::make_shared<TrianglePointGenerator>();
}
void VolumeParticleEmitter2::onUpdate(double currentTimeInSeconds,
double timeIntervalInSeconds) {
UNUSED_VARIABLE(currentTimeInSeconds);
UNUSED_VARIABLE(timeIntervalInSeconds);
auto particles = target();
if (particles == nullptr) {
return;
}
if (!isEnabled()) {
return;
}
Array1<Vector2D> newPositions;
Array1<Vector2D> newVelocities;
emit(particles, &newPositions, &newVelocities);
particles->addParticles(newPositions, newVelocities);
if (_isOneShot) {
setIsEnabled(false);
}
}
void VolumeParticleEmitter2::emit(const ParticleSystemData2Ptr& particles,
Array1<Vector2D>* newPositions,
Array1<Vector2D>* newVelocities) {
if (!_implicitSurface) {
return;
}
_implicitSurface->updateQueryEngine();
BoundingBox2D region = _bounds;
if (_implicitSurface->isBounded()) {
BoundingBox2D surfaceBBox = _implicitSurface->boundingBox();
region.lowerCorner = max(region.lowerCorner, surfaceBBox.lowerCorner);
region.upperCorner = min(region.upperCorner, surfaceBBox.upperCorner);
}
// Reserving more space for jittering
const double j = jitter();
const double maxJitterDist = 0.5 * j * _spacing;
size_t numNewParticles = 0;
if (_allowOverlapping || _isOneShot) {
_pointsGen->forEachPoint(region, _spacing, [&](const Vector2D& point) {
double newAngleInRadian = (random() - 0.5) * kTwoPiD;
Matrix2x2D rotationMatrix =
Matrix2x2D::makeRotationMatrix(newAngleInRadian);
Vector2D randomDir = rotationMatrix * Vector2D();
Vector2D offset = maxJitterDist * randomDir;
Vector2D candidate = point + offset;
if (_implicitSurface->signedDistance(candidate) <= 0.0) {
if (_numberOfEmittedParticles < _maxNumberOfParticles) {
newPositions->append(candidate);
++_numberOfEmittedParticles;
++numNewParticles;
} else {
return false;
}
}
return true;
});
} else {
// Use serial hash grid searcher for continuous update.
PointHashGridSearcher2 neighborSearcher(
Size2(kDefaultHashGridResolution, kDefaultHashGridResolution),
2.0 * _spacing);
if (!_allowOverlapping) {
neighborSearcher.build(particles->positions());
}
_pointsGen->forEachPoint(region, _spacing, [&](const Vector2D& point) {
double newAngleInRadian = (random() - 0.5) * kTwoPiD;
Matrix2x2D rotationMatrix =
Matrix2x2D::makeRotationMatrix(newAngleInRadian);
Vector2D randomDir = rotationMatrix * Vector2D();
Vector2D offset = maxJitterDist * randomDir;
Vector2D candidate = point + offset;
if (_implicitSurface->isInside(candidate) &&
(!_allowOverlapping &&
!neighborSearcher.hasNearbyPoint(candidate, _spacing))) {
if (_numberOfEmittedParticles < _maxNumberOfParticles) {
newPositions->append(candidate);
neighborSearcher.add(candidate);
++_numberOfEmittedParticles;
++numNewParticles;
} else {
return false;
}
}
return true;
});
}
JET_INFO << "Number of newly generated particles: " << numNewParticles;
JET_INFO << "Number of total generated particles: "
<< _numberOfEmittedParticles;
newVelocities->resize(newPositions->size());
newVelocities->parallelForEachIndex([&](size_t i) {
(*newVelocities)[i] = velocityAt((*newPositions)[i]);
});
}
void VolumeParticleEmitter2::setPointGenerator(
const PointGenerator2Ptr& newPointsGen) {
_pointsGen = newPointsGen;
}
const ImplicitSurface2Ptr& VolumeParticleEmitter2::surface() const {
return _implicitSurface;
}
void VolumeParticleEmitter2::setSurface(const ImplicitSurface2Ptr& newSurface) {
_implicitSurface = newSurface;
}
const BoundingBox2D& VolumeParticleEmitter2::maxRegion() const {
return _bounds;
}
void VolumeParticleEmitter2::setMaxRegion(const BoundingBox2D& newMaxRegion) {
_bounds = newMaxRegion;
}
double VolumeParticleEmitter2::jitter() const { return _jitter; }
void VolumeParticleEmitter2::setJitter(double newJitter) {
_jitter = clamp(newJitter, 0.0, 1.0);
}
bool VolumeParticleEmitter2::isOneShot() const { return _isOneShot; }
void VolumeParticleEmitter2::setIsOneShot(bool newValue) {
_isOneShot = newValue;
}
bool VolumeParticleEmitter2::allowOverlapping() const {
return _allowOverlapping;
}
void VolumeParticleEmitter2::setAllowOverlapping(bool newValue) {
_allowOverlapping = newValue;
}
size_t VolumeParticleEmitter2::maxNumberOfParticles() const {
return _maxNumberOfParticles;
}
void VolumeParticleEmitter2::setMaxNumberOfParticles(
size_t newMaxNumberOfParticles) {
_maxNumberOfParticles = newMaxNumberOfParticles;
}
double VolumeParticleEmitter2::spacing() const { return _spacing; }
void VolumeParticleEmitter2::setSpacing(double newSpacing) {
_spacing = newSpacing;
}
Vector2D VolumeParticleEmitter2::initialVelocity() const { return _initialVel; }
void VolumeParticleEmitter2::setInitialVelocity(const Vector2D& newInitialVel) {
_initialVel = newInitialVel;
}
Vector2D VolumeParticleEmitter2::linearVelocity() const { return _linearVel; }
void VolumeParticleEmitter2::setLinearVelocity(const Vector2D& newLinearVel) {
_linearVel = newLinearVel;
}
double VolumeParticleEmitter2::angularVelocity() const { return _angularVel; }
void VolumeParticleEmitter2::setAngularVelocity(double newAngularVel) {
_angularVel = newAngularVel;
}
double VolumeParticleEmitter2::random() {
std::uniform_real_distribution<> d(0.0, 1.0);
return d(_rng);
}
Vector2D VolumeParticleEmitter2::velocityAt(const Vector2D& point) const {
Vector2D r = point - _implicitSurface->transform.translation();
return _linearVel + _angularVel * Vector2D(-r.y, r.x) + _initialVel;
}
VolumeParticleEmitter2::Builder VolumeParticleEmitter2::builder() {
return Builder();
}
VolumeParticleEmitter2::Builder&
VolumeParticleEmitter2::Builder::withImplicitSurface(
const ImplicitSurface2Ptr& implicitSurface) {
_implicitSurface = implicitSurface;
if (!_isBoundSet) {
_bounds = _implicitSurface->boundingBox();
}
return *this;
}
VolumeParticleEmitter2::Builder& VolumeParticleEmitter2::Builder::withSurface(
const Surface2Ptr& surface) {
_implicitSurface = std::make_shared<SurfaceToImplicit2>(surface);
if (!_isBoundSet) {
_bounds = surface->boundingBox();
}
return *this;
}
VolumeParticleEmitter2::Builder& VolumeParticleEmitter2::Builder::withMaxRegion(
const BoundingBox2D& bounds) {
_bounds = bounds;
_isBoundSet = true;
return *this;
}
VolumeParticleEmitter2::Builder& VolumeParticleEmitter2::Builder::withSpacing(
double spacing) {
_spacing = spacing;
return *this;
}
VolumeParticleEmitter2::Builder&
VolumeParticleEmitter2::Builder::withInitialVelocity(
const Vector2D& initialVel) {
_initialVel = initialVel;
return *this;
}
VolumeParticleEmitter2::Builder&
VolumeParticleEmitter2::Builder::withLinearVelocity(const Vector2D& linearVel) {
_linearVel = linearVel;
return *this;
}
VolumeParticleEmitter2::Builder&
VolumeParticleEmitter2::Builder::withAngularVelocity(double angularVel) {
_angularVel = angularVel;
return *this;
}
VolumeParticleEmitter2::Builder&
VolumeParticleEmitter2::Builder::withMaxNumberOfParticles(
size_t maxNumberOfParticles) {
_maxNumberOfParticles = maxNumberOfParticles;
return *this;
}
VolumeParticleEmitter2::Builder& VolumeParticleEmitter2::Builder::withJitter(
double jitter) {
_jitter = jitter;
return *this;
}
VolumeParticleEmitter2::Builder& VolumeParticleEmitter2::Builder::withIsOneShot(
bool isOneShot) {
_isOneShot = isOneShot;
return *this;
}
VolumeParticleEmitter2::Builder&
VolumeParticleEmitter2::Builder::withAllowOverlapping(bool allowOverlapping) {
_allowOverlapping = allowOverlapping;
return *this;
}
VolumeParticleEmitter2::Builder&
VolumeParticleEmitter2::Builder::withRandomSeed(uint32_t seed) {
_seed = seed;
return *this;
}
VolumeParticleEmitter2 VolumeParticleEmitter2::Builder::build() const {
return VolumeParticleEmitter2(_implicitSurface, _bounds, _spacing,
_initialVel, _linearVel, _angularVel,
_maxNumberOfParticles, _jitter, _isOneShot,
_allowOverlapping, _seed);
}
VolumeParticleEmitter2Ptr VolumeParticleEmitter2::Builder::makeShared() const {
return std::shared_ptr<VolumeParticleEmitter2>(
new VolumeParticleEmitter2(_implicitSurface, _bounds, _spacing,
_initialVel, _linearVel, _angularVel,
_maxNumberOfParticles, _jitter, _isOneShot,
_allowOverlapping),
[](VolumeParticleEmitter2* obj) { delete obj; });
}
| 31.937313 | 80 | 0.689036 | PavelBlend |
51271f737361182dec58f957ae2fe45c22770f4f | 188 | cpp | C++ | depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/tests/manual/qtabbar/tabbarform.cpp | GrinCash/Grinc-core | 1377979453ba84082f70f9c128be38e57b65a909 | [
"MIT"
] | null | null | null | depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/tests/manual/qtabbar/tabbarform.cpp | GrinCash/Grinc-core | 1377979453ba84082f70f9c128be38e57b65a909 | [
"MIT"
] | null | null | null | depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/tests/manual/qtabbar/tabbarform.cpp | GrinCash/Grinc-core | 1377979453ba84082f70f9c128be38e57b65a909 | [
"MIT"
] | null | null | null | #include "tabbarform.h"
TabBarForm::TabBarForm(QWidget *parent) :
QWidget(parent),
ui(new Ui::TabBarForm)
{
ui->setupUi(this);
}
TabBarForm::~TabBarForm()
{
delete ui;
}
| 13.428571 | 41 | 0.648936 | GrinCash |
5127aea9d1bba2efd60678830c1013b6cfbe718f | 8,199 | hpp | C++ | include/GlobalNamespace/ShowHideAnimationController.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/ShowHideAnimationController.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/ShowHideAnimationController.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: UnityEngine.MonoBehaviour
#include "UnityEngine/MonoBehaviour.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
}
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: Animator
class Animator;
}
// Forward declaring namespace: System::Collections
namespace System::Collections {
// Forward declaring type: IEnumerator
class IEnumerator;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Forward declaring type: ShowHideAnimationController
class ShowHideAnimationController;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::GlobalNamespace::ShowHideAnimationController);
DEFINE_IL2CPP_ARG_TYPE(::GlobalNamespace::ShowHideAnimationController*, "", "ShowHideAnimationController");
// Type namespace:
namespace GlobalNamespace {
// Size: 0x30
#pragma pack(push, 1)
// Autogenerated type: ShowHideAnimationController
// [TokenAttribute] Offset: FFFFFFFF
class ShowHideAnimationController : public ::UnityEngine::MonoBehaviour {
public:
// Nested type: ::GlobalNamespace::ShowHideAnimationController::$DeactivateSelfAfterDelayCoroutine$d__9
class $DeactivateSelfAfterDelayCoroutine$d__9;
#ifdef USE_CODEGEN_FIELDS
public:
#else
#ifdef CODEGEN_FIELD_ACCESSIBILITY
CODEGEN_FIELD_ACCESSIBILITY:
#else
protected:
#endif
#endif
// public UnityEngine.Animator _animator
// Size: 0x8
// Offset: 0x18
::UnityEngine::Animator* animator;
// Field size check
static_assert(sizeof(::UnityEngine::Animator*) == 0x8);
// public System.Boolean _deactivateSelfAfterDelay
// Size: 0x1
// Offset: 0x20
bool deactivateSelfAfterDelay;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: deactivateSelfAfterDelay and: deactivationDelay
char __padding1[0x3] = {};
// public System.Single _deactivationDelay
// Size: 0x4
// Offset: 0x24
float deactivationDelay;
// Field size check
static_assert(sizeof(float) == 0x4);
// private System.Boolean _show
// Size: 0x1
// Offset: 0x28
bool show;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: show and: showAnimatorParam
char __padding3[0x3] = {};
// private System.Int32 _showAnimatorParam
// Size: 0x4
// Offset: 0x2C
int showAnimatorParam;
// Field size check
static_assert(sizeof(int) == 0x4);
public:
// Deleting conversion operator: operator ::System::IntPtr
constexpr operator ::System::IntPtr() const noexcept = delete;
// Get instance field reference: public UnityEngine.Animator _animator
::UnityEngine::Animator*& dyn__animator();
// Get instance field reference: public System.Boolean _deactivateSelfAfterDelay
bool& dyn__deactivateSelfAfterDelay();
// Get instance field reference: public System.Single _deactivationDelay
float& dyn__deactivationDelay();
// Get instance field reference: private System.Boolean _show
bool& dyn__show();
// Get instance field reference: private System.Int32 _showAnimatorParam
int& dyn__showAnimatorParam();
// public System.Boolean get_Show()
// Offset: 0x29D63D4
bool get_Show();
// public System.Void set_Show(System.Boolean value)
// Offset: 0x29D6274
void set_Show(bool value);
// protected System.Void Awake()
// Offset: 0x29D63DC
void Awake();
// private System.Collections.IEnumerator DeactivateSelfAfterDelayCoroutine(System.Single delay)
// Offset: 0x29D6458
::System::Collections::IEnumerator* DeactivateSelfAfterDelayCoroutine(float delay);
// public System.Void .ctor()
// Offset: 0x29D6504
// Implemented from: UnityEngine.MonoBehaviour
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static ShowHideAnimationController* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::GlobalNamespace::ShowHideAnimationController::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<ShowHideAnimationController*, creationType>()));
}
}; // ShowHideAnimationController
#pragma pack(pop)
static check_size<sizeof(ShowHideAnimationController), 44 + sizeof(int)> __GlobalNamespace_ShowHideAnimationControllerSizeCheck;
static_assert(sizeof(ShowHideAnimationController) == 0x30);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: GlobalNamespace::ShowHideAnimationController::get_Show
// Il2CppName: get_Show
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::ShowHideAnimationController::*)()>(&GlobalNamespace::ShowHideAnimationController::get_Show)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ShowHideAnimationController*), "get_Show", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::ShowHideAnimationController::set_Show
// Il2CppName: set_Show
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ShowHideAnimationController::*)(bool)>(&GlobalNamespace::ShowHideAnimationController::set_Show)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ShowHideAnimationController*), "set_Show", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::ShowHideAnimationController::Awake
// Il2CppName: Awake
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ShowHideAnimationController::*)()>(&GlobalNamespace::ShowHideAnimationController::Awake)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ShowHideAnimationController*), "Awake", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::ShowHideAnimationController::DeactivateSelfAfterDelayCoroutine
// Il2CppName: DeactivateSelfAfterDelayCoroutine
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Collections::IEnumerator* (GlobalNamespace::ShowHideAnimationController::*)(float)>(&GlobalNamespace::ShowHideAnimationController::DeactivateSelfAfterDelayCoroutine)> {
static const MethodInfo* get() {
static auto* delay = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ShowHideAnimationController*), "DeactivateSelfAfterDelayCoroutine", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{delay});
}
};
// Writing MetadataGetter for method: GlobalNamespace::ShowHideAnimationController::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 47.393064 | 248 | 0.731919 | RedBrumbler |
512eb0cb8c6ad7662d5123ae67ecd2e42d58b987 | 1,525 | cpp | C++ | src/cpp/MagmaWndTest/main.cpp | bhrnjica/MagmaSharp | 60d3ae4baa03a9db7cc9683f4a44ce864d742f26 | [
"MIT"
] | 2 | 2020-08-02T02:11:27.000Z | 2020-08-30T16:15:50.000Z | src/cpp/MagmaWndTest/main.cpp | bhrnjica/MagmaSharp | 60d3ae4baa03a9db7cc9683f4a44ce864d742f26 | [
"MIT"
] | null | null | null | src/cpp/MagmaWndTest/main.cpp | bhrnjica/MagmaSharp | 60d3ae4baa03a9db7cc9683f4a44ce864d742f26 | [
"MIT"
] | null | null | null | #include <iostream>
// includes, system
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "HelperTest.h"
#include "MagmaDevice.h"
#include "mbmagma.h"
using namespace MagmaBinding;
#include "GSVTests.h"
#include "SVDTests.h"
#include "LSSTests.h"
#include "EIGENTests.h"
#include "MatrixTest.h"
int main(int argc, char** argv)
{
mv2sgemm_test_magma_col_01();
mv2sgemm_test_magma_row_01();
mv2sgemm_test_magma_row();
mv2sgemm_test_magma_col();
mv2sgemm_test_lapack_col_01();
mv2sgemm_test_lapack_row_01();
mv2sgemm_test_lapack_row();
mv2sgemm_test_lapack_col();
mv2dgemm_test_magma_col_01();
mv2dgemm_test_magma_row_01();
mv2dgemm_test_magma_row();
mv2dgemm_test_magma_col();
mv2dgemm_test_lapack_col_01();
mv2dgemm_test_lapack_row_01();
mv2dgemm_test_lapack_row();
mv2dgemm_test_lapack_col();
mbv2getdevice_arch();
//EIGEN
mv2sgeevs_cpu_test();
mv2sgeevs_test();
mv2sgeev_cpu_test();
mv2sgeev_test();
mv2dgeevs_cpu_test();
mv2dgeevs_test();
mv2dgeev_cpu_test();
mv2dgeev_test();
//LSS
mv2sgels_cpu_test();
mv2sgels_test();
mv2sgels_gpu_test();
mv2dgels_cpu_test();
mv2dgels_test();
mv2dgels_gpu_test();
//GSV tests
mv2dgesv_cpu_test();
mv2dgesv_test();
mv2dgesv_gpu_test();
mv2sgesv_cpu_test();
mv2sgesv_test();
mv2sgesv_gpu_test();
//SVD
mv2sgesvd_cpu_test();
mv2sgesvds_cpu_test();
mv2sgesvds_test();
mv2sgesvd_test();
mv2dgesvd_cpu_test();
mv2dgesvds_cpu_test();
mv2dgesvds_test();
mv2dgesvd_test();
return 0;
}
| 17.329545 | 31 | 0.756721 | bhrnjica |
512eea02b2150f4c75cdc9bc70f54ea5376c2147 | 5,252 | cpp | C++ | src/TicTacToeGame.cpp | That-Cool-Coder/sfml-tictactoe | af43fd32b70acd8e73b54a2feb074df93c36bc6d | [
"MIT"
] | null | null | null | src/TicTacToeGame.cpp | That-Cool-Coder/sfml-tictactoe | af43fd32b70acd8e73b54a2feb074df93c36bc6d | [
"MIT"
] | null | null | null | src/TicTacToeGame.cpp | That-Cool-Coder/sfml-tictactoe | af43fd32b70acd8e73b54a2feb074df93c36bc6d | [
"MIT"
] | null | null | null | #include "TicTacToeGame.hpp"
void TicTacToeGame::setup()
{
createBoard();
createText();
m_board.clear();
m_crntPlayer = CellValue::Cross; // todo: set this randomly
}
void TicTacToeGame::createText()
{
m_textEntities.clear();
m_headingText = std::make_shared<sf::Text>();
m_headingText->setFont(shared::font);
m_headingText->setCharacterSize(m_topBarHeight - 15);
m_headingText->setFillColor(m_textColor);
// m_drawables.push_back(m_headingText);
}
void TicTacToeGame::createBoard()
{
m_board = TicTacToeBoard();
}
void TicTacToeGame::update()
{
calcBoardSize();
switch (m_gamePhase)
{
case Playing:
drawCellBorders();
drawCells();
updateText();
break;
case ShowingWinner:
drawCellBorders();
drawCells();
updateText();
if (! m_showWinnerTimer.running) m_showWinnerTimer.start();
if (m_showWinnerTimer.isFinished()) gameManager->queueLoadScene("TitleScreen");
break;
}
}
void TicTacToeGame::handleEvent(sf::Event& event)
{
if (event.type == sf::Event::MouseButtonPressed)
{
switch (m_gamePhase)
{
case Playing:
setCellContents(event);
break;
}
}
}
void TicTacToeGame::updateText()
{
// Yes this is a big and convoluted nested switch-case
// But I couldn't find a way to put this into a table lookup because of the differing
// data types
std::string headingTextContent = "Error: no text supplied for this heading";
switch (m_gamePhase)
{
case Playing:
switch (m_crntPlayer)
{
case CellValue::Nought:
headingTextContent = "Noughts turn";
break;
case CellValue::Cross:
headingTextContent = "Crosses turn";
break;
}
break;
case ShowingWinner:
switch (m_winner)
{
case Winner::Nought:
headingTextContent = "Noughts wins";
break;
case Winner::Cross:
headingTextContent = "Crosses wins";
break;
case Winner::Draw:
headingTextContent = "Draw";
break;
}
break;
}
m_headingText->setString(headingTextContent);
miniengine::utils::centerAlignText(*m_headingText);
m_headingText->setPosition(gameManager->width / 2, m_topBarHeight / 2);
}
void TicTacToeGame::calcBoardSize()
{
int availableHeight = gameManager->height - m_topBarHeight - m_bottomBarHeight;
m_boardSize = std::min(availableHeight, gameManager->width) - m_windowPadding * 2;
m_cellSize = m_boardSize / 3;
m_boardLeft = std::max(gameManager->width - m_boardSize, 1) / 2;
m_boardTop = std::max(gameManager->height - m_boardSize, 1) / 2;
}
void TicTacToeGame::drawCellBorders()
{
sf::RectangleShape rectangle;
rectangle.setFillColor(m_cellBorderColor);
int cellBorderWidth = m_cellBorderWidthProportion * m_boardSize;
rectangle.setSize(sf::Vector2f(m_boardSize, cellBorderWidth));
rectangle.setOrigin(m_boardSize / 2, cellBorderWidth / 2);
// Do the horizontal borders
for (int y = 1; y < BOARD_SIZE; y ++)
{
rectangle.setPosition(m_boardLeft + m_boardSize / 2,
m_boardTop + y * m_cellSize);
gameManager->window.draw(rectangle);
}
// Do the vertical borders
rectangle.setRotation(90);
for (int x = 1; x < BOARD_SIZE; x ++)
{
rectangle.setPosition(m_boardLeft + x * m_cellSize,
m_boardTop + m_boardSize / 2);
gameManager->window.draw(rectangle);
}
}
void TicTacToeGame::drawCells()
{
int cellPadding = m_cellPaddingProportion * m_cellSize;
NoughtGraphic nought((m_cellSize - cellPadding) / 2);
CrossGraphic cross((m_cellSize - cellPadding) / 2);
for (int x = 0; x < BOARD_SIZE; x ++)
{
for (int y = 0; y < BOARD_SIZE; y ++)
{
int xPos = x * m_cellSize + m_cellSize / 2 + m_boardLeft;
int yPos = y * m_cellSize + m_cellSize / 2 + m_boardTop;
if (m_board.getCell(x, y) == CellValue::Nought)
nought.draw(xPos, yPos, gameManager->window, m_backgroundColor);
else if (m_board.getCell(x, y) == CellValue::Cross)
cross.draw(xPos, yPos, gameManager->window);
}
}
}
void TicTacToeGame::setCellContents(sf::Event event)
{
// First calculate board pos of click
int xCoord = (event.mouseButton.x - m_boardLeft) / m_cellSize;
int yCoord = (event.mouseButton.y - m_boardTop) / m_cellSize;
// If click is on board, do game logic
if (xCoord >= 0 && xCoord < BOARD_SIZE &&
yCoord >= 0 && yCoord < BOARD_SIZE)
{
if (m_board.getCell(xCoord, yCoord) == CellValue::Empty)
{
m_board.setCell(xCoord, yCoord, m_crntPlayer);
m_winner = m_board.findWinner();
if (m_winner == Winner::GameNotFinished)
{
if (m_crntPlayer == CellValue::Nought) m_crntPlayer = CellValue::Cross;
else m_crntPlayer = CellValue::Nought;
}
else
{
m_gamePhase = ShowingWinner;
}
}
}
}
| 29.177778 | 89 | 0.609863 | That-Cool-Coder |
51318153f254555c64f9201de6ecb0142f915259 | 7,122 | cpp | C++ | DearPyGui/src/core/AppItems/mvAppItemState.cpp | htnminh/DearPyGui | bfbcb297f287295fae9766b21a53a99fbb0fe756 | [
"MIT"
] | null | null | null | DearPyGui/src/core/AppItems/mvAppItemState.cpp | htnminh/DearPyGui | bfbcb297f287295fae9766b21a53a99fbb0fe756 | [
"MIT"
] | 1 | 2021-08-16T02:39:32.000Z | 2021-08-16T02:39:32.000Z | DearPyGui/src/core/AppItems/mvAppItemState.cpp | Jah-On/DearPyGui | 0e4f5d05555f950670e01bb2a647fb8b0b9a106f | [
"MIT"
] | null | null | null | #include "mvAppItemState.h"
#include <imgui.h>
#include "mvAppItem.h"
#include "mvApp.h"
#include "mvPyObject.h"
namespace Marvel {
void mvAppItemState::reset()
{
_hovered = false;
_active = false;
_focused = false;
_leftclicked = false;
_rightclicked = false;
_middleclicked = false;
_visible = false;
_edited = false;
_activated = false;
_deactivated = false;
_deactivatedAfterEdit = false;
_toggledOpen = false;
}
void mvAppItemState::update()
{
_lastFrameUpdate = mvApp::s_frame;
_hovered = ImGui::IsItemHovered();
_active = ImGui::IsItemActive();
_focused = ImGui::IsItemFocused();
_leftclicked = ImGui::IsItemClicked();
_rightclicked = ImGui::IsItemClicked(1);
_middleclicked = ImGui::IsItemClicked(2);
_visible = ImGui::IsItemVisible();
_edited = ImGui::IsItemEdited();
_activated = ImGui::IsItemActivated();
_deactivated = ImGui::IsItemDeactivated();
_deactivatedAfterEdit = ImGui::IsItemDeactivatedAfterEdit();
_toggledOpen = ImGui::IsItemToggledOpen();
_rectMin = { ImGui::GetItemRectMin().x, ImGui::GetItemRectMin().y };
_rectMax = { ImGui::GetItemRectMax().x, ImGui::GetItemRectMax().y };
_rectSize = { ImGui::GetItemRectSize().x, ImGui::GetItemRectSize().y };
_contextRegionAvail = { ImGui::GetContentRegionAvail().x, ImGui::GetContentRegionAvail().y };
}
void mvAppItemState::getState(PyObject* dict)
{
if (dict == nullptr)
return;
bool valid = _lastFrameUpdate == mvApp::s_frame;
PyDict_SetItemString(dict, "ok", mvPyObject(ToPyBool(_ok)));
PyDict_SetItemString(dict, "pos", mvPyObject(ToPyPairII(_pos.x, _pos.y)));
if(_applicableState & MV_STATE_HOVER) PyDict_SetItemString(dict, "hovered", mvPyObject(ToPyBool(valid ? _hovered : false)));
if(_applicableState & MV_STATE_ACTIVE) PyDict_SetItemString(dict, "active", mvPyObject(ToPyBool(valid ? _active : false)));
if(_applicableState & MV_STATE_FOCUSED) PyDict_SetItemString(dict, "focused", mvPyObject(ToPyBool(valid ? _focused : false)));
if (_applicableState & MV_STATE_CLICKED)
{
PyDict_SetItemString(dict, "clicked", mvPyObject(ToPyBool(valid ? _leftclicked || _rightclicked || _middleclicked : false)));
PyDict_SetItemString(dict, "left_clicked", mvPyObject(ToPyBool(valid ? _leftclicked : false)));
PyDict_SetItemString(dict, "right_clicked", mvPyObject(ToPyBool(valid ? _rightclicked : false)));
PyDict_SetItemString(dict, "middle_clicked", mvPyObject(ToPyBool(valid ? _middleclicked : false)));
}
if(_applicableState & MV_STATE_VISIBLE) PyDict_SetItemString(dict, "visible", mvPyObject(ToPyBool(valid ? _visible : false)));
if(_applicableState & MV_STATE_EDITED) PyDict_SetItemString(dict, "edited", mvPyObject(ToPyBool(valid ? _edited : false)));
if(_applicableState & MV_STATE_ACTIVATED) PyDict_SetItemString(dict, "activated", mvPyObject(ToPyBool(valid ? _activated : false)));
if(_applicableState & MV_STATE_DEACTIVATED) PyDict_SetItemString(dict, "deactivated", mvPyObject(ToPyBool(valid ? _deactivated : false)));
if(_applicableState & MV_STATE_DEACTIVATEDAE) PyDict_SetItemString(dict, "deactivated_after_edit", mvPyObject(ToPyBool(valid ? _deactivatedAfterEdit : false)));
if(_applicableState & MV_STATE_TOGGLED_OPEN) PyDict_SetItemString(dict, "toggled_open", mvPyObject(ToPyBool(valid ? _toggledOpen : false)));
if(_applicableState & MV_STATE_RECT_MIN) PyDict_SetItemString(dict, "rect_min", mvPyObject(ToPyPairII(_rectMin.x, _rectMin.y)));
if(_applicableState & MV_STATE_RECT_MAX) PyDict_SetItemString(dict, "rect_max", mvPyObject(ToPyPairII(_rectMax.x, _rectMax.y)));
if(_applicableState & MV_STATE_RECT_SIZE) PyDict_SetItemString(dict, "rect_size", mvPyObject(ToPyPairII(_rectSize.x, _rectSize.y)));
if(_applicableState & MV_STATE_CONT_AVAIL) PyDict_SetItemString(dict, "content_region_avail", mvPyObject(ToPyPairII(_contextRegionAvail.x, _contextRegionAvail.y)));
}
bool mvAppItemState::isItemHovered(int frameDelay) const
{
if (_lastFrameUpdate + frameDelay != mvApp::s_frame)
return false;
return _hovered;
}
bool mvAppItemState::isItemActive(int frameDelay) const
{
if (_lastFrameUpdate + frameDelay != mvApp::s_frame)
return false;
return _active;
}
bool mvAppItemState::isItemFocused(int frameDelay) const
{
if (_lastFrameUpdate + frameDelay != mvApp::s_frame)
return false;
return _focused;
}
bool mvAppItemState::isItemLeftClicked(int frameDelay) const
{
if (_lastFrameUpdate + frameDelay != mvApp::s_frame)
return false;
return _leftclicked;
}
bool mvAppItemState::isItemRightClicked(int frameDelay) const
{
if (_lastFrameUpdate + frameDelay != mvApp::s_frame)
return false;
return _rightclicked;
}
bool mvAppItemState::isItemMiddleClicked(int frameDelay) const
{
if (_lastFrameUpdate + frameDelay != mvApp::s_frame)
return false;
return _middleclicked;
}
bool mvAppItemState::isItemVisible(int frameDelay) const
{
if (_lastFrameUpdate + frameDelay != mvApp::s_frame)
return false;
return _visible;
}
bool mvAppItemState::isItemEdited(int frameDelay) const
{
if (_lastFrameUpdate + frameDelay != mvApp::s_frame)
return false;
return _edited;
}
bool mvAppItemState::isItemActivated(int frameDelay) const
{
if (_lastFrameUpdate + frameDelay != mvApp::s_frame)
return false;
return _activated;
}
bool mvAppItemState::isItemDeactivated(int frameDelay) const
{
if (_lastFrameUpdate + frameDelay != mvApp::s_frame)
return false;
return _deactivated;
}
bool mvAppItemState::isItemDeactivatedAfterEdit(int frameDelay) const
{
if (_lastFrameUpdate + frameDelay != mvApp::s_frame)
return false;
return _deactivatedAfterEdit;
}
bool mvAppItemState::isItemToogledOpen(int frameDelay) const
{
if (_lastFrameUpdate + frameDelay != mvApp::s_frame)
return false;
return _toggledOpen;
}
bool mvAppItemState::isOk() const
{
return _ok;
}
mvVec2 mvAppItemState::getItemRectMin() const
{
return _rectMin;
}
mvVec2 mvAppItemState::getItemRectMax() const
{
return _rectMax;
}
mvVec2 mvAppItemState::getItemRectSize() const
{
return _rectSize;
}
mvVec2 mvAppItemState::getItemPos() const
{
return _pos;
}
mvVec2 mvAppItemState::getContextRegionAvail() const
{
return _contextRegionAvail;
}
} | 36.901554 | 172 | 0.659927 | htnminh |
5133bba43106ad19491cc409206c5b9064cfd136 | 5,366 | cpp | C++ | src/pi-src/util.cpp | 31337H4X0R/crab-tracker | c822a40010d172ba797b5de8c340931d0feea6e4 | [
"MIT"
] | 1 | 2019-07-31T01:32:17.000Z | 2019-07-31T01:32:17.000Z | src/pi-src/util.cpp | 31337H4X0R/crab-tracker | c822a40010d172ba797b5de8c340931d0feea6e4 | [
"MIT"
] | 47 | 2017-11-04T02:04:42.000Z | 2018-06-16T01:00:48.000Z | src/pi-src/util.cpp | 31337H4X0R/crab-tracker | c822a40010d172ba797b5de8c340931d0feea6e4 | [
"MIT"
] | 2 | 2018-06-10T21:58:49.000Z | 2019-06-18T17:21:03.000Z | /******************************************************************************
Helper methods, including configuration management.
Author: Noah Strong
Project: Crab Tracker
Created: 2018-02-19
******************************************************************************/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "config.h"
/******************************************************************************
CONFIGURATION FUNCTIONS AND VARIABLES
Configuration works as follows: on program startup, the initalize() function
should be called. This will look for and load the `.conf` file whose location
is specificed in CONFIG.H (generally `/etc/crab-tracker.conf`). The .conf file
will be parsed and any key/value pairs whose keys we expect to see will be
read in and saved. The keys we "expect to see" are those that are listed in the
entries[] array below. Initially, entries[] contains the default values for all
parameters we expect to come across; unless new values for those parameters are
found in the .conf file, those values will be used.
******************************************************************************/
/* Basically a key/value store for configuration options */
struct config_entry{
const char* param;
int value;
int isset;
};
/* An exhaustive set of all configuration options. Default values given here */
config_entry entries[] = { {"DISPLAY_PINGS", 1, 0},
{"DISPLAY_RAW_SPI", 0, 0},
{"R_USER", 1, 0},
{"HPHONE_DIST_CM", 300, 0}};
int num_entries = sizeof(entries) / sizeof(config_entry);
/**
* "Public" way for getting a configuration. Looks through entries and returns
* (via an out param) the value of that config option.
* @param param The name of the parameter to look for
* @param result The value of the parameter, if found [OUT PARAM]
* @return 1 if param was found, else 0
*/
int get_param(char* param, int* result){
for(int i=0; i<num_entries; i++){
if(!strcmp(param, entries[i].param)){
*result = entries[i].value;
return 1;
}
}
return 0;
}
/* Rather than include math.h, here's a quick integer min() */
int min(int a, int b){ return a > b ? b : a; }
/**
* Loads the .conf file on the machine and then stores the values of any known
* configuration parameters.
* @return 0 if config loaded successfully, else 1.
*/
int initialize_util(){
printf("Loading configuration... ");
FILE* fp;
char* line = NULL;
char buf[120];
size_t linecap = 0;
ssize_t len;
int n, m, n_found = 0, int_param = 0;
/* Load the `.conf` file, if it exists */
fp = fopen(CONFIG_FILE_PATH, "r");
if (fp == NULL){
perror("fopen");
fprintf(stderr, "Unable to load configuration file\n");
return 1;
}
/* Now we go through every line in the config file */
while ((len = getline(&line, &linecap, fp)) != -1) {
for(int i=0; i<len; i++){
/* Strip out comments (denoted by a hash (#)) */
if(line[i] == '#'){ line[i] = '\0'; i=len; };
}
/* See if any of our parameters are found in this line */
for(int j=0; j<num_entries; j++){
/* Set `buf = entries[j].param + " %d";` */
m = min(strlen(entries[j].param), 115);
strncpy(buf, entries[j].param, m);
strcpy(&buf[m], " %d\0");
n = sscanf(line, buf, &int_param);
if(n > 0){
/* Found the parameter! Store it */
n_found++;
entries[j].value = int_param;
entries[j].isset = 1;
j = num_entries; /* Break out of loop early */
}
}
}
/* Clean up! */
fclose(fp);
if (line) free(line);
printf("successfully read %d configuration parameters\n", n_found);
return 0;
}
/******************************************************************************
DISPLAY AND OTHER HELPER FUNCTIONS
These are mostly simple helper functions, such as binary print functions.
******************************************************************************/
/**
* Print a 32-bit number as binary.
* Written by Zach McGrew (WWU Comptuer Science Graduate Student)
* @param number The number to print
*/
void print_bin(int32_t number) {
uint32_t bit_set = (uint32_t) 1 << 31;
int32_t bit_pos;
for (bit_pos = 31; bit_pos >= 0; --bit_pos, bit_set >>= 1) {
printf("%c", ((uint32_t)number & bit_set ? '1' : '0'));
}
}
/**
* Print an 8-bit unsigned integer in binary to stdout.
* @param number The number (UNSIGNED) to print
*/
void print_bin_8(uint8_t number){
uint8_t bit_set = (uint8_t) 1 << 7;
int bit_pos;
for(bit_pos = 7; bit_pos >= 0; --bit_pos){
printf("%c", ((uint8_t)number & bit_set ? '1' : '0'));
bit_set >>= 1;
}
}
/**
* Print a long unsigned integer in binary to stdout.
* @param number The number (UNSIGNED) to print
*/
void print_bin_ulong(unsigned long number){
unsigned long bit_set = (unsigned long) 1 << 31;
int bit_pos;
for(bit_pos = 31; bit_pos >= 0; --bit_pos){
printf("%c", (number & bit_set ? '1' : '0'));
bit_set >>= 1;
}
}
| 32.131737 | 80 | 0.549758 | 31337H4X0R |
51350ef7d52628847601f5a0ec6fa701d333df3a | 324 | hpp | C++ | include/log.hpp | langenhagen/barn-bookmark-manager | e7db7dba34e92c74ad445d088b57559dbba26f63 | [
"MIT"
] | null | null | null | include/log.hpp | langenhagen/barn-bookmark-manager | e7db7dba34e92c74ad445d088b57559dbba26f63 | [
"MIT"
] | null | null | null | include/log.hpp | langenhagen/barn-bookmark-manager | e7db7dba34e92c74ad445d088b57559dbba26f63 | [
"MIT"
] | null | null | null | /* Common logging functionality.
author: andreasl
*/
#pragma once
#include <ostream>
namespace barn {
namespace bbm {
/* Severity levels for logging.*/
enum Severity {
INFO,
WARN,
ERROR
};
/* Write a log message to console.*/
std::ostream& log(const Severity level);
} // namespace bbm
} // namespace barn
| 13.5 | 40 | 0.675926 | langenhagen |
5135b5e0813ed68e19a88286b59accf0a2449e62 | 45,832 | cpp | C++ | NFIQ2/NFIQ2/NFIQ2Algorithm/src/wsq/util.cpp | mahizhvannan/PYNFIQ2 | 56eac2d780c9b5becd0ca600ffa6198d3a0115a7 | [
"MIT"
] | null | null | null | NFIQ2/NFIQ2/NFIQ2Algorithm/src/wsq/util.cpp | mahizhvannan/PYNFIQ2 | 56eac2d780c9b5becd0ca600ffa6198d3a0115a7 | [
"MIT"
] | null | null | null | NFIQ2/NFIQ2/NFIQ2Algorithm/src/wsq/util.cpp | mahizhvannan/PYNFIQ2 | 56eac2d780c9b5becd0ca600ffa6198d3a0115a7 | [
"MIT"
] | 1 | 2022-02-14T03:16:05.000Z | 2022-02-14T03:16:05.000Z | /*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/***********************************************************************
LIBRARY: WSQ - Grayscale Image Compression
FILE: UTIL.C
AUTHORS: Craig Watson
Michael Garris
DATE: 11/24/1999
UPDATED: 02/24/2005 by MDG
Contains gernal routines responsible for supporting WSQ
image compression.
ROUTINES:
#cat: conv_img_2_flt_ret - Converts an image's unsigned character pixels
#cat: to floating point values in the range +/- 128.0.
#cat: Returns on error.
#cat: conv_img_2_flt - Converts an image's unsigned character pixels
#cat: to floating point values in the range +/- 128.0.
#cat: conv_img_2_uchar - Converts an image's floating point pixels
#cat: unsigned character pixels.
#cat: variance - Calculates the variances within image subbands.
#cat:
#cat: quantize - Quantizes the image's wavelet subbands.
#cat:
#cat: quant_block_sizes - Quantizes an image's subband block.
#cat:
#cat: unquantize - Unquantizes an image's wavelet subbands.
#cat:
#cat: wsq_decompose - Computes the wavelet decomposition of an input image.
#cat:
#cat: get_lets - Compute the wavelet subband decomposition for the image.
#cat:
#cat: wsq_reconstruct - Reconstructs a lossy floating point pixmap from
#cat: a WSQ compressed datastream.
#cat: join_lets - Reconstruct the image from the wavelet subbands.
#cat:
#cat: int_sign - Get the sign of the sythesis filter coefficients.
#cat:
#cat: image_size - Computes the size in bytes of a WSQ compressed image
#cat: file, including headers, tables, and parameters.
#cat: init_wsq_decoder_resources - Initializes memory resources used by the
#cat: WSQ decoder
#cat: free_wsq_decoder_resources - Deallocates memory resources used by the
#cat: WSQ decoder
***********************************************************************/
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <wsq.h>
#include <defs.h>
#include <dataio.h>
/******************************************************************/
/* The routines in this file do numerous things */
/* related to the WSQ algorithm such as: */
/* converting the image data from unsigned char */
/* to float and integer to unsigned char, */
/* splitting the image into the subbands as well */
/* the rejoining process, subband variance */
/* calculations, and quantization. */
/******************************************************************/
/******************************************************************/
/* This routine converts the unsigned char data to float. In the */
/* process it shifts and scales the data so the values range from */
/* +/- 128.0 This function returns on error. */
/******************************************************************/
int conv_img_2_flt_ret(
float *fip, /* output float image data */
float *m_shift, /* shifting parameter */
float *r_scale, /* scaling parameter */
unsigned char *data, /* input unsigned char data */
const int num_pix) /* num pixels in image */
{
int cnt; /* pixel cnt */
unsigned int sum, overflow; /* sum of pixel values */
float mean; /* mean pixel value */
int low, high; /* low/high pixel values */
float low_diff, high_diff; /* new low/high pixels values shifting */
sum = 0;
overflow = 0;
low = 255;
high = 0;
for(cnt = 0; cnt < num_pix; cnt++) {
if(data[cnt] > high)
high = data[cnt];
if(data[cnt] < low)
low = data[cnt];
sum += data[cnt];
if(sum < overflow) {
fprintf(stderr, "ERROR: conv_img_2_flt: overflow at %d\n", cnt);
return(-91);
}
overflow = sum;
}
mean = (float) sum / (float)num_pix;
*m_shift = mean;
low_diff = *m_shift - low;
high_diff = high - *m_shift;
if(low_diff >= high_diff)
*r_scale = low_diff;
else
*r_scale = high_diff;
*r_scale /= (float)128.0;
for(cnt = 0; cnt < num_pix; cnt++) {
fip[cnt] = ((float)data[cnt] - *m_shift) / *r_scale;
}
return(0);
}
/******************************************************************/
/* This routine converts the unsigned char data to float. In the */
/* process it shifts and scales the data so the values range from */
/* +/- 128.0 */
/******************************************************************/
void conv_img_2_flt(
float *fip, /* output float image data */
float *m_shift, /* shifting parameter */
float *r_scale, /* scaling parameter */
unsigned char *data, /* input unsigned char data */
const int num_pix) /* num pixels in image */
{
int cnt; /* pixel cnt */
unsigned int sum, overflow; /* sum of pixel values */
float mean; /* mean pixel value */
int low, high; /* low/high pixel values */
float low_diff, high_diff; /* new low/high pixels values shifting */
sum = 0;
overflow = 0;
low = 255;
high = 0;
for(cnt = 0; cnt < num_pix; cnt++) {
if(data[cnt] > high)
high = data[cnt];
if(data[cnt] < low)
low = data[cnt];
sum += data[cnt];
if(sum < overflow) {
fprintf(stderr, "ERROR: conv_img_2_flt: overflow at pixel %d\n", cnt);
exit(-1);
}
overflow = sum;
}
mean = (float) sum / (float)num_pix;
*m_shift = mean;
low_diff = *m_shift - low;
high_diff = high - *m_shift;
if(low_diff >= high_diff)
*r_scale = low_diff;
else
*r_scale = high_diff;
*r_scale /= (float)128.0;
for(cnt = 0; cnt < num_pix; cnt++) {
fip[cnt] = ((float)data[cnt] - *m_shift) / *r_scale;
}
}
/*********************************************************/
/* Routine to convert image from float to unsigned char. */
/*********************************************************/
void conv_img_2_uchar(
unsigned char *data, /* uchar image pointer */
float *img, /* image pointer */
const int width, /* image width */
const int height, /* image height */
const float m_shift, /* shifting parameter */
const float r_scale) /* scaling parameter */
{
int r, c; /* row/column counters */
float img_tmp; /* temp image data store */
for (r = 0; r < height; r++) {
for (c = 0; c < width; c++) {
img_tmp = (*img * r_scale) + m_shift;
img_tmp += 0.5;
if (img_tmp < 0.0)
*data = 0; /* neg pix poss after quantization */
else if (img_tmp > 255.0)
*data = 255;
else
*data = (unsigned char)img_tmp;
++img;
++data;
}
}
}
/**********************************************************/
/* This routine calculates the variances of the subbands. */
/**********************************************************/
void variance(
QUANT_VALS *quant_vals, /* quantization parameters */
Q_TREE q_tree[], /* quantization "tree" */
const int q_treelen, /* length of q_tree */
float *fip, /* image pointer */
const int width, /* image width */
const int height) /* image height */
{
float *fp; /* temp image pointer */
int cvr; /* subband counter */
int lenx = 0, leny = 0; /* dimensions of area to calculate variance */
int skipx, skipy; /* pixels to skip to get to area for
variance calculation */
int row, col; /* dimension counters */
float ssq; /* sum of squares */
float sum2; /* variance calculation parameter */
float sum_pix; /* sum of pixels */
float vsum; /* variance sum for subbands 0-3 */
vsum = 0.0;
for(cvr = 0; cvr < 4; cvr++) {
fp = fip + (q_tree[cvr].y * width) + q_tree[cvr].x;
ssq = 0.0;
sum_pix = 0.0;
skipx = q_tree[cvr].lenx / 8;
skipy = (9 * q_tree[cvr].leny)/32;
lenx = (3 * q_tree[cvr].lenx)/4;
leny = (7 * q_tree[cvr].leny)/16;
fp += (skipy * width) + skipx;
for(row = 0; row < leny; row++, fp += (width - lenx)) {
for(col = 0; col < lenx; col++) {
sum_pix += *fp;
ssq += *fp * *fp;
fp++;
}
}
sum2 = (sum_pix * sum_pix)/(lenx * leny);
quant_vals->var[cvr] = (float)((ssq - sum2)/((lenx * leny)-1.0));
vsum += quant_vals->var[cvr];
}
if(vsum < 20000.0) {
for(cvr = 0; cvr < NUM_SUBBANDS; cvr++) {
fp = fip + (q_tree[cvr].y * width) + q_tree[cvr].x;
ssq = 0.0;
sum_pix = 0.0;
lenx = q_tree[cvr].lenx;
leny = q_tree[cvr].leny;
for(row = 0; row < leny; row++, fp += (width - lenx)) {
for(col = 0; col < lenx; col++) {
sum_pix += *fp;
ssq += *fp * *fp;
fp++;
}
}
sum2 = (sum_pix * sum_pix)/(lenx * leny);
quant_vals->var[cvr] = (float)((ssq - sum2)/((lenx * leny)-1.0));
}
}
else {
for(cvr = 4; cvr < NUM_SUBBANDS; cvr++) {
fp = fip + (q_tree[cvr].y * width) + q_tree[cvr].x;
ssq = 0.0;
sum_pix = 0.0;
skipx = q_tree[cvr].lenx / 8;
skipy = (9 * q_tree[cvr].leny)/32;
lenx = (3 * q_tree[cvr].lenx)/4;
leny = (7 * q_tree[cvr].leny)/16;
fp += (skipy * width) + skipx;
for(row = 0; row < leny; row++, fp += (width - lenx)) {
for(col = 0; col < lenx; col++) {
sum_pix += *fp;
ssq += *fp * *fp;
fp++;
}
}
sum2 = (sum_pix * sum_pix)/(lenx * leny);
quant_vals->var[cvr] = (float)((ssq - sum2)/((lenx * leny)-1.0));
}
}
}
/************************************************/
/* This routine quantizes the wavelet subbands. */
/************************************************/
int quantize(
short **osip, /* quantized output */
int *ocmp_siz, /* size of quantized output */
QUANT_VALS *quant_vals, /* quantization parameters */
Q_TREE q_tree[], /* quantization "tree" */
const int q_treelen, /* size of q_tree */
float *fip, /* floating point image pointer */
const int width, /* image width */
const int height) /* image height */
{
int i; /* temp counter */
int j; /* interation index */
float *fptr; /* temp image pointer */
short *sip, *sptr; /* pointers to quantized image */
int row, col; /* temp image characteristic parameters */
int cnt; /* subband counter */
float zbin; /* zero bin size */
float A[NUM_SUBBANDS]; /* subband "weights" for quantization */
float m[NUM_SUBBANDS]; /* subband size to image size ratios */
/* (reciprocal of FBI spec for 'm') */
float m1, m2, m3; /* reciprocal constants for 'm' */
float sigma[NUM_SUBBANDS]; /* square root of subband variances */
int K0[NUM_SUBBANDS]; /* initial list of subbands w/variance >= thresh */
int K1[NUM_SUBBANDS]; /* working list of subbands */
int *K, *nK; /* pointers to sets of subbands */
int NP[NUM_SUBBANDS]; /* current subbounds with nonpositive bit rates. */
int K0len; /* number of subbands in K0 */
int Klen, nKlen; /* number of subbands in other subband lists */
int NPlen; /* number of subbands flagged in NP */
float S; /* current frac of subbands w/positive bit rate */
float q; /* current proportionality constant */
float P; /* product of 'q/Q' ratios */
/* Set up 'A' table. */
for(cnt = 0; cnt < STRT_SUBBAND_3; cnt++)
A[cnt] = 1.0;
A[cnt++ /*52*/] = 1.32;
A[cnt++ /*53*/] = 1.08;
A[cnt++ /*54*/] = 1.42;
A[cnt++ /*55*/] = 1.08;
A[cnt++ /*56*/] = 1.32;
A[cnt++ /*57*/] = 1.42;
A[cnt++ /*58*/] = 1.08;
A[cnt++ /*59*/] = 1.08;
for(cnt = 0; cnt < MAX_SUBBANDS; cnt++) {
quant_vals->qbss[cnt] = 0.0;
quant_vals->qzbs[cnt] = 0.0;
}
/* Set up 'Q1' (prime) table. */
for(cnt = 0; cnt < NUM_SUBBANDS; cnt++) {
if(quant_vals->var[cnt] < VARIANCE_THRESH)
quant_vals->qbss[cnt] = 0.0;
else
/* NOTE: q has been taken out of the denominator in the next */
/* 2 formulas from the original code. */
if(cnt < STRT_SIZE_REGION_2 /*4*/)
quant_vals->qbss[cnt] = 1.0;
else
quant_vals->qbss[cnt] = 10.0 / (A[cnt] *
(float)log(quant_vals->var[cnt]));
}
/* Set up output buffer. */
if((sip = (short *) calloc(width*height, sizeof(short))) == NULL) {
fprintf(stderr,"ERROR : quantize : calloc : sip\n");
return(-90);
}
sptr = sip;
/* Set up 'm' table (these values are the reciprocal of 'm' in */
/* the FBI spec). */
m1 = 1.0/1024.0;
m2 = 1.0/256.0;
m3 = 1.0/16.0;
for(cnt = 0; cnt < STRT_SIZE_REGION_2; cnt++)
m[cnt] = m1;
for(cnt = STRT_SIZE_REGION_2; cnt < STRT_SIZE_REGION_3; cnt++)
m[cnt] = m2;
for(cnt = STRT_SIZE_REGION_3; cnt < NUM_SUBBANDS; cnt++)
m[cnt] = m3;
j = 0;
/* Initialize 'K0' and 'K1' lists. */
K0len = 0;
for(cnt = 0; cnt < NUM_SUBBANDS; cnt++){
if(quant_vals->var[cnt] >= VARIANCE_THRESH){
K0[K0len] = cnt;
K1[K0len++] = cnt;
/* Compute square root of subband variance. */
sigma[cnt] = sqrt(quant_vals->var[cnt]);
}
}
K = K1;
Klen = K0len;
while(1){
/* Compute new 'S' */
S = 0.0;
for(i = 0; i < Klen; i++){
/* Remeber 'm' is the reciprocal of spec. */
S += m[K[i]];
}
/* Compute product 'P' */
P = 1.0;
for(i = 0; i < Klen; i++){
/* Remeber 'm' is the reciprocal of spec. */
P *= pow((sigma[K[i]] / quant_vals->qbss[K[i]]), m[K[i]]);
}
/* Compute new 'q' */
q = (pow(2.0f,(float)((quant_vals->r/S)-1.0))/2.5) / pow(P, (float)(1.0/S));
/* Flag subbands with non-positive bitrate. */
memset(NP, 0, NUM_SUBBANDS * sizeof(int));
NPlen = 0;
for(i = 0; i < Klen; i++){
if((quant_vals->qbss[K[i]] / q) >= (5.0*sigma[K[i]])){
NP[K[i]] = TRUE;
NPlen++;
}
}
/* If list of subbands with non-positive bitrate is empty ... */
if(NPlen == 0){
/* Then we are done, so break from while loop. */
break;
}
/* Assign new subband set to previous set K minus subbands in set NP. */
nK = K1;
nKlen = 0;
for(i = 0; i < Klen; i++){
if(!NP[K[i]])
nK[nKlen++] = K[i];
}
/* Assign new set as K. */
K = nK;
Klen = nKlen;
/* Bump iteration counter. */
j++;
}
/* Flag subbands that are in set 'K0' (the very first set). */
nK = K1;
memset(nK, 0, NUM_SUBBANDS * sizeof(int));
for(i = 0; i < K0len; i++){
nK[K0[i]] = TRUE;
}
/* Set 'Q' values. */
for(cnt = 0; cnt < NUM_SUBBANDS; cnt++) {
if(nK[cnt])
quant_vals->qbss[cnt] /= q;
else
quant_vals->qbss[cnt] = 0.0;
quant_vals->qzbs[cnt] = 1.2 * quant_vals->qbss[cnt];
}
/* Now ready to compute and store bin widths for subbands. */
for(cnt = 0; cnt < NUM_SUBBANDS; cnt++) {
fptr = fip + (q_tree[cnt].y * width) + q_tree[cnt].x;
if(quant_vals->qbss[cnt] != 0.0) {
zbin = quant_vals->qzbs[cnt] / 2.0;
for(row = 0;
row < q_tree[cnt].leny;
row++, fptr += width - q_tree[cnt].lenx){
for(col = 0; col < q_tree[cnt].lenx; col++) {
if(-zbin <= *fptr && *fptr <= zbin)
*sptr = 0;
else if(*fptr > 0.0)
*sptr = (short)(((*fptr-zbin)/quant_vals->qbss[cnt]) + 1.0);
else
*sptr = (short)(((*fptr+zbin)/quant_vals->qbss[cnt]) - 1.0);
sptr++;
fptr++;
}
}
}
else if(debug > 0)
fprintf(stderr, "%d -> %3.6f\n", cnt, quant_vals->qbss[cnt]);
}
*osip = sip;
*ocmp_siz = sptr - sip;
return(0);
}
/************************************************************************/
/* Compute quantized WSQ subband block sizes. */
/************************************************************************/
void quant_block_sizes(int *oqsize1, int *oqsize2, int *oqsize3,
QUANT_VALS *quant_vals,
W_TREE w_tree[], const int w_treelen,
Q_TREE q_tree[], const int q_treelen)
{
int qsize1, qsize2, qsize3;
int node;
/* Compute temporary sizes of 3 WSQ subband blocks. */
qsize1 = w_tree[14].lenx * w_tree[14].leny;
qsize2 = (w_tree[5].leny * w_tree[1].lenx) +
(w_tree[4].lenx * w_tree[4].leny);
qsize3 = (w_tree[2].lenx * w_tree[2].leny) +
(w_tree[3].lenx * w_tree[3].leny);
/* Adjust size of quantized WSQ subband blocks. */
for (node = 0; node < STRT_SUBBAND_2; node++)
if(quant_vals->qbss[node] == 0.0)
qsize1 -= (q_tree[node].lenx * q_tree[node].leny);
for (node = STRT_SUBBAND_2; node < STRT_SUBBAND_3; node++)
if(quant_vals->qbss[node] == 0.0)
qsize2 -= (q_tree[node].lenx * q_tree[node].leny);
for (node = STRT_SUBBAND_3; node < STRT_SUBBAND_DEL; node++)
if(quant_vals->qbss[node] == 0.0)
qsize3 -= (q_tree[node].lenx * q_tree[node].leny);
*oqsize1 = qsize1;
*oqsize2 = qsize2;
*oqsize3 = qsize3;
}
/*************************************/
/* Routine to unquantize image data. */
/*************************************/
int unquantize(
float **ofip, /* floating point image pointer */
const DQT_TABLE *dqt_table, /* quantization table structure */
Q_TREE q_tree[], /* quantization table structure */
const int q_treelen, /* size of q_tree */
short *sip, /* quantized image pointer */
const int width, /* image width */
const int height) /* image height */
{
float *fip; /* floating point image */
int row, col; /* cover counter and row/column counters */
float C; /* quantizer bin center */
float *fptr; /* image pointers */
short *sptr;
int cnt; /* subband counter */
if((fip = (float *) calloc(width*height, sizeof(float))) == NULL) {
fprintf(stderr,"ERROR : unquantize : calloc : fip\n");
return(-91);
}
if(dqt_table->dqt_def != 1) {
fprintf(stderr,
"ERROR: unquantize : quantization table parameters not defined!\n");
return(-92);
}
sptr = sip;
C = dqt_table->bin_center;
for(cnt = 0; cnt < NUM_SUBBANDS; cnt++) {
if(dqt_table->q_bin[cnt] == 0.0)
continue;
fptr = fip + (q_tree[cnt].y * width) + q_tree[cnt].x;
for(row = 0;
row < q_tree[cnt].leny;
row++, fptr += width - q_tree[cnt].lenx){
for(col = 0; col < q_tree[cnt].lenx; col++) {
if(*sptr == 0)
*fptr = 0.0;
else if(*sptr > 0)
*fptr = (dqt_table->q_bin[cnt] * ((float)*sptr - C))
+ (dqt_table->z_bin[cnt] / 2.0);
else if(*sptr < 0)
*fptr = (dqt_table->q_bin[cnt] * ((float)*sptr + C))
- (dqt_table->z_bin[cnt] / 2.0);
else {
fprintf(stderr,
"ERROR : unquantize : invalid quantization pixel value\n");
return(-93);
}
fptr++;
sptr++;
}
}
}
*ofip = fip;
return(0);
}
/************************************************************************/
/* WSQ decompose the image. NOTE: this routine modifies and returns */
/* the results in "fdata". */
/************************************************************************/
int wsq_decompose(float *fdata, const int width, const int height,
W_TREE w_tree[], const int w_treelen,
float *hifilt, const int hisz,
float *lofilt, const int losz)
{
int num_pix, node;
float *fdata1, *fdata_bse;
num_pix = width * height;
/* Allocate temporary floating point pixmap. */
if((fdata1 = (float *) malloc(num_pix*sizeof(float))) == NULL) {
fprintf(stderr,"ERROR : wsq_decompose : malloc : fdata1\n");
return(-94);
}
/* Compute the Wavelet image decomposition. */
for(node = 0; node < w_treelen; node++) {
fdata_bse = fdata + (w_tree[node].y * width) + w_tree[node].x;
get_lets(fdata1, fdata_bse, w_tree[node].leny, w_tree[node].lenx,
width, 1, hifilt, hisz, lofilt, losz, w_tree[node].inv_rw);
get_lets(fdata_bse, fdata1, w_tree[node].lenx, w_tree[node].leny,
1, width, hifilt, hisz, lofilt, losz, w_tree[node].inv_cl);
}
free(fdata1);
return(0);
}
/************************************************************/
/************************************************************/
void get_lets(
float *ne, /* image pointers for creating subband splits */
float *old,
const int len1, /* temporary length parameters */
const int len2,
const int pitch, /* pitch gives next row_col to filter */
const int stride, /* stride gives next pixel to filter */
float *hi,
const int hsz, /* NEW */
float *lo, /* filter coefficients */
const int lsz, /* NEW */
const int inv) /* spectral inversion? */
{
float *lopass, *hipass; /* pointers of where to put lopass
and hipass filter outputs */
float *p0,*p1; /* pointers to image pixels used */
int pix, rw_cl; /* pixel counter and row/column counter */
int i, da_ev; /* even or odd row/column of pixels */
int fi_ev;
int loc, hoc, nstr, pstr;
int llen, hlen;
int lpxstr, lspxstr;
float *lpx, *lspx;
int hpxstr, hspxstr;
float *hpx, *hspx;
int olle, ohle;
int olre, ohre;
int lle, lle2;
int lre, lre2;
int hle, hle2;
int hre, hre2;
da_ev = len2 % 2;
fi_ev = lsz % 2;
if(fi_ev) {
loc = (lsz-1)/2;
hoc = (hsz-1)/2 - 1;
olle = 0;
ohle = 0;
olre = 0;
ohre = 0;
}
else {
loc = lsz/2 - 2;
hoc = hsz/2 - 2;
olle = 1;
ohle = 1;
olre = 1;
ohre = 1;
if(loc == -1) {
loc = 0;
olle = 0;
}
if(hoc == -1) {
hoc = 0;
ohle = 0;
}
for(i = 0; i < hsz; i++)
hi[i] *= -1.0;
}
pstr = stride;
nstr = -pstr;
if(da_ev) {
llen = (len2+1)/2;
hlen = llen - 1;
}
else {
llen = len2/2;
hlen = llen;
}
for(rw_cl = 0; rw_cl < len1; rw_cl++) {
if(inv) {
hipass = ne + rw_cl * pitch;
lopass = hipass + hlen * stride;
}
else {
lopass = ne + rw_cl * pitch;
hipass = lopass + llen * stride;
}
p0 = old + rw_cl * pitch;
p1 = p0 + (len2-1) * stride;
lspx = p0 + (loc * stride);
lspxstr = nstr;
lle2 = olle;
lre2 = olre;
hspx = p0 + (hoc * stride);
hspxstr = nstr;
hle2 = ohle;
hre2 = ohre;
for(pix = 0; pix < hlen; pix++) {
lpxstr = lspxstr;
lpx = lspx;
lle = lle2;
lre = lre2;
*lopass = *lpx * lo[0];
for(i = 1; i < lsz; i++) {
if(lpx == p0){
if(lle) {
lpxstr = 0;
lle = 0;
}
else
lpxstr = pstr;
}
if(lpx == p1){
if(lre) {
lpxstr = 0;
lre = 0;
}
else
lpxstr = nstr;
}
lpx += lpxstr;
*lopass += *lpx * lo[i];
}
lopass += stride;
hpxstr = hspxstr;
hpx = hspx;
hle = hle2;
hre = hre2;
*hipass = *hpx * hi[0];
for(i = 1; i < hsz; i++) {
if(hpx == p0){
if(hle) {
hpxstr = 0;
hle = 0;
}
else
hpxstr = pstr;
}
if(hpx == p1){
if(hre) {
hpxstr = 0;
hre = 0;
}
else
hpxstr = nstr;
}
hpx += hpxstr;
*hipass += *hpx * hi[i];
}
hipass += stride;
for(i = 0; i < 2; i++) {
if(lspx == p0){
if(lle2) {
lspxstr = 0;
lle2 = 0;
}
else
lspxstr = pstr;
}
lspx += lspxstr;
if(hspx == p0){
if(hle2) {
hspxstr = 0;
hle2 = 0;
}
else
hspxstr = pstr;
}
hspx += hspxstr;
}
}
if(da_ev) {
lpxstr = lspxstr;
lpx = lspx;
lle = lle2;
lre = lre2;
*lopass = *lpx * lo[0];
for(i = 1; i < lsz; i++) {
if(lpx == p0){
if(lle) {
lpxstr = 0;
lle = 0;
}
else
lpxstr = pstr;
}
if(lpx == p1){
if(lre) {
lpxstr = 0;
lre = 0;
}
else
lpxstr = nstr;
}
lpx += lpxstr;
*lopass += *lpx * lo[i];
}
lopass += stride;
}
}
if(!fi_ev) {
for(i = 0; i < hsz; i++)
hi[i] *= -1.0;
}
}
/************************************************************************/
/* WSQ reconstructs the image. NOTE: this routine modifies and returns */
/* the results in "fdata". */
/************************************************************************/
int wsq_reconstruct(float *fdata, const int width, const int height,
W_TREE w_tree[], const int w_treelen,
const DTT_TABLE *dtt_table)
{
int num_pix, node;
float *fdata1, *fdata_bse;
if(dtt_table->lodef != 1) {
fprintf(stderr,
"ERROR: wsq_reconstruct : Lopass filter coefficients not defined\n");
return(-95);
}
if(dtt_table->hidef != 1) {
fprintf(stderr,
"ERROR: wsq_reconstruct : Hipass filter coefficients not defined\n");
return(-96);
}
num_pix = width * height;
/* Allocate temporary floating point pixmap. */
if((fdata1 = (float *) malloc(num_pix*sizeof(float))) == NULL) {
fprintf(stderr,"ERROR : wsq_reconstruct : malloc : fdata1\n");
return(-97);
}
/* Reconstruct floating point pixmap from wavelet subband data. */
for (node = w_treelen - 1; node >= 0; node--) {
fdata_bse = fdata + (w_tree[node].y * width) + w_tree[node].x;
join_lets(fdata1, fdata_bse, w_tree[node].lenx, w_tree[node].leny,
1, width,
dtt_table->hifilt, dtt_table->hisz,
dtt_table->lofilt, dtt_table->losz,
w_tree[node].inv_cl);
join_lets(fdata_bse, fdata1, w_tree[node].leny, w_tree[node].lenx,
width, 1,
dtt_table->hifilt, dtt_table->hisz,
dtt_table->lofilt, dtt_table->losz,
w_tree[node].inv_rw);
}
free(fdata1);
return(0);
}
/****************************************************************/
void join_lets(
float *ne, /* image pointers for creating subband splits */
float *old,
const int len1, /* temporary length parameters */
const int len2,
const int pitch, /* pitch gives next row_col to filter */
const int stride, /* stride gives next pixel to filter */
float *hi,
const int hsz, /* NEW */
float *lo, /* filter coefficients */
const int lsz, /* NEW */
const int inv) /* spectral inversion? */
{
float *lp0, *lp1;
float *hp0, *hp1;
float *lopass, *hipass; /* lo/hi pass image pointers */
float *limg, *himg;
int pix, cl_rw; /* pixel counter and column/row counter */
int i, da_ev; /* if "scanline" is even or odd and */
int loc, hoc;
int hlen, llen;
int nstr, pstr;
int tap;
int fi_ev;
int olle, ohle, olre, ohre;
int lle, lle2, lre, lre2;
int hle, hle2, hre, hre2;
float *lpx, *lspx;
int lpxstr, lspxstr;
int lstap, lotap;
float *hpx, *hspx;
int hpxstr, hspxstr;
int hstap, hotap;
int asym, fhre = 0, ofhre;
float ssfac, osfac, sfac;
da_ev = len2 % 2;
fi_ev = lsz % 2;
pstr = stride;
nstr = -pstr;
if(da_ev) {
llen = (len2+1)/2;
hlen = llen - 1;
}
else {
llen = len2/2;
hlen = llen;
}
if(fi_ev) {
asym = 0;
ssfac = 1.0;
ofhre = 0;
loc = (lsz-1)/4;
hoc = (hsz+1)/4 - 1;
lotap = ((lsz-1)/2) % 2;
hotap = ((hsz+1)/2) % 2;
if(da_ev) {
olle = 0;
olre = 0;
ohle = 1;
ohre = 1;
}
else {
olle = 0;
olre = 1;
ohle = 1;
ohre = 0;
}
}
else {
asym = 1;
ssfac = -1.0;
ofhre = 2;
loc = lsz/4 - 1;
hoc = hsz/4 - 1;
lotap = (lsz/2) % 2;
hotap = (hsz/2) % 2;
if(da_ev) {
olle = 1;
olre = 0;
ohle = 1;
ohre = 1;
}
else {
olle = 1;
olre = 1;
ohle = 1;
ohre = 1;
}
if(loc == -1) {
loc = 0;
olle = 0;
}
if(hoc == -1) {
hoc = 0;
ohle = 0;
}
for(i = 0; i < hsz; i++)
hi[i] *= -1.0;
}
for (cl_rw = 0; cl_rw < len1; cl_rw++) {
limg = ne + cl_rw * pitch;
himg = limg;
*himg = 0.0;
*(himg + stride) = 0.0;
if(inv) {
hipass = old + cl_rw * pitch;
lopass = hipass + stride * hlen;
}
else {
lopass = old + cl_rw * pitch;
hipass = lopass + stride * llen;
}
lp0 = lopass;
lp1 = lp0 + (llen-1) * stride;
lspx = lp0 + (loc * stride);
lspxstr = nstr;
lstap = lotap;
lle2 = olle;
lre2 = olre;
hp0 = hipass;
hp1 = hp0 + (hlen-1) * stride;
hspx = hp0 + (hoc * stride);
hspxstr = nstr;
hstap = hotap;
hle2 = ohle;
hre2 = ohre;
osfac = ssfac;
for(pix = 0; pix < hlen; pix++) {
for(tap = lstap; tap >=0; tap--) {
lle = lle2;
lre = lre2;
lpx = lspx;
lpxstr = lspxstr;
*limg = *lpx * lo[tap];
for(i = tap+2; i < lsz; i += 2) {
if(lpx == lp0){
if(lle) {
lpxstr = 0;
lle = 0;
}
else
lpxstr = pstr;
}
if(lpx == lp1) {
if(lre) {
lpxstr = 0;
lre = 0;
}
else
lpxstr = nstr;
}
lpx += lpxstr;
*limg += *lpx * lo[i];
}
limg += stride;
}
if(lspx == lp0){
if(lle2) {
lspxstr = 0;
lle2 = 0;
}
else
lspxstr = pstr;
}
lspx += lspxstr;
lstap = 1;
for(tap = hstap; tap >=0; tap--) {
hle = hle2;
hre = hre2;
hpx = hspx;
hpxstr = hspxstr;
fhre = ofhre;
sfac = osfac;
for(i = tap; i < hsz; i += 2) {
if(hpx == hp0) {
if(hle) {
hpxstr = 0;
hle = 0;
}
else {
hpxstr = pstr;
sfac = 1.0;
}
}
if(hpx == hp1) {
if(hre) {
hpxstr = 0;
hre = 0;
if(asym && da_ev) {
hre = 1;
fhre--;
sfac = (float)fhre;
if(sfac == 0.0)
hre = 0;
}
}
else {
hpxstr = nstr;
if(asym)
sfac = -1.0;
}
}
*himg += *hpx * hi[i] * sfac;
hpx += hpxstr;
}
himg += stride;
}
if(hspx == hp0) {
if(hle2) {
hspxstr = 0;
hle2 = 0;
}
else {
hspxstr = pstr;
osfac = 1.0;
}
}
hspx += hspxstr;
hstap = 1;
}
if(da_ev)
if(lotap)
lstap = 1;
else
lstap = 0;
else
if(lotap)
lstap = 2;
else
lstap = 1;
for(tap = 1; tap >= lstap; tap--) {
lle = lle2;
lre = lre2;
lpx = lspx;
lpxstr = lspxstr;
*limg = *lpx * lo[tap];
for(i = tap+2; i < lsz; i += 2) {
if(lpx == lp0){
if(lle) {
lpxstr = 0;
lle = 0;
}
else
lpxstr = pstr;
}
if(lpx == lp1) {
if(lre) {
lpxstr = 0;
lre = 0;
}
else
lpxstr = nstr;
}
lpx += lpxstr;
*limg += *lpx * lo[i];
}
limg += stride;
}
if(da_ev) {
if(hotap)
hstap = 1;
else
hstap = 0;
if(hsz == 2) {
hspx -= hspxstr;
fhre = 1;
}
}
else
if(hotap)
hstap = 2;
else
hstap = 1;
for(tap = 1; tap >= hstap; tap--) {
hle = hle2;
hre = hre2;
hpx = hspx;
hpxstr = hspxstr;
sfac = osfac;
if(hsz != 2)
fhre = ofhre;
for(i = tap; i < hsz; i += 2) {
if(hpx == hp0) {
if(hle) {
hpxstr = 0;
hle = 0;
}
else {
hpxstr = pstr;
sfac = 1.0;
}
}
if(hpx == hp1) {
if(hre) {
hpxstr = 0;
hre = 0;
if(asym && da_ev) {
hre = 1;
fhre--;
sfac = (float)fhre;
if(sfac == 0.0)
hre = 0;
}
}
else {
hpxstr = nstr;
if(asym)
sfac = -1.0;
}
}
*himg += *hpx * hi[i] * sfac;
hpx += hpxstr;
}
himg += stride;
}
}
if(!fi_ev)
for(i = 0; i < hsz; i++)
hi[i] *= -1.0;
}
/*****************************************************/
/* Routine to execute an integer sign determination */
/*****************************************************/
int int_sign(
const int power) /* "sign" power */
{
int cnt, num = -1; /* counter and sign return value */
if(power == 0)
return 1;
for(cnt = 1; cnt < power; cnt++)
num *= -1;
return num;
}
/*************************************************************/
/* Computes size of compressed image file including headers, */
/* tables, and parameters. */
/*************************************************************/
int image_size(
const int blocklen, /* length of the compressed blocks */
short *huffbits1, /* huffman table parameters */
short *huffbits2)
{
int tot_size, cnt;
tot_size = blocklen; /* size of three compressed blocks */
tot_size += 58; /* size of transform table */
tot_size += 389; /* size of quantization table */
tot_size += 17; /* size of frame header */
tot_size += 3; /* size of block 1 */
tot_size += 3; /* size of block 2 */
tot_size += 3; /* size of block 3 */
tot_size += 3; /* size hufftable variable and hufftable number */
tot_size += 16; /* size of huffbits1 */
for(cnt = 1; cnt < 16; cnt ++)
tot_size += huffbits1[cnt]; /* size of huffvalues1 */
tot_size += 3; /* size hufftable variable and hufftable number */
tot_size += 16; /* size of huffbits1 */
for(cnt = 1; cnt < 16; cnt ++)
tot_size += huffbits2[cnt]; /* size of huffvalues2 */
tot_size += 20; /* SOI,SOF,SOB(3),DTT,DQT,DHT(2),EOI */
return tot_size;
}
/*************************************************************/
/* Added by MDG on 02-24-05 */
/* Initializes memory used by the WSQ decoder. */
/*************************************************************/
void init_wsq_decoder_resources()
{
/* Added 02-24-05 by MDG */
/* Init dymanically allocated members to NULL */
/* for proper memory management in: */
/* read_transform_table() */
/* getc_transform_table() */
/* free_wsq_resources() */
dtt_table.lofilt = (float *)NULL;
dtt_table.hifilt = (float *)NULL;
}
/*************************************************************/
/* Added by MDG on 02-24-05 */
/* Deallocates memory used by the WSQ decoder. */
/*************************************************************/
void free_wsq_decoder_resources()
{
if(dtt_table.lofilt != (float *)NULL){
free(dtt_table.lofilt);
dtt_table.lofilt = (float *)NULL;
}
if(dtt_table.hifilt != (float *)NULL){
free(dtt_table.hifilt);
dtt_table.hifilt = (float *)NULL;
}
}
/************************************************************************
#cat: delete_comments_wsq - Deletes all comments in a WSQ compressed file.
*************************************************************************/
/*****************************************************************/
int delete_comments_wsq(unsigned char **ocdata, int *oclen,
unsigned char *idata, const int ilen)
{
int ret, nlen, nalloc, stp;
unsigned short marker, length;
unsigned char m1, m2, *ndata, *cbufptr, *ebufptr;
nalloc = ilen;
/* Initialize current filled length to 0. */
nlen = 0;
/* Allocate new compressed byte stream. */
if((ndata = (unsigned char *)malloc(nalloc * sizeof(unsigned char)))
== (unsigned char *)NULL){
fprintf(stderr, "ERROR : delete_comments_wsq : malloc : ndata\n");
return(-2);
}
cbufptr = idata;
ebufptr = idata + ilen;
/* Parse SOI */
if((ret = getc_marker_wsq(&marker, SOI_WSQ, &cbufptr, ebufptr))){
free(ndata);
return(ret);
}
/* Copy SOI */
if((ret = putc_ushort(marker, ndata, nalloc, &nlen))){
free(ndata);
return(ret);
}
/* Read Next Marker */
if((ret = getc_marker_wsq(&marker, ANY_WSQ, &cbufptr, ebufptr))){
free(ndata);
return(ret);
}
while(marker != EOI_WSQ) {
if(marker != COM_WSQ) {
/* Copy Marker and Data */
if((ret = putc_ushort(marker, ndata, nalloc, &nlen))){
free(ndata);
return(ret);
}
if((ret = getc_ushort(&length, &cbufptr, ebufptr))){
free(ndata);
return(ret);
}
/*
printf("Copying Marker %04X and Data (Length = %d)\n", marker, length);
*/
if((ret = putc_ushort(length, ndata, nalloc, &nlen))){
free(ndata);
return(ret);
}
if((ret = putc_bytes(cbufptr, length-2, ndata, nalloc, &nlen))){
free(ndata);
return(ret);
}
cbufptr += (length-2);
if(marker == SOB_WSQ) {
stp = 0;
while(!stp) {
if((ret = getc_byte(&m1, &cbufptr, ebufptr))) {
free(ndata);
return(ret);
}
if(m1 == 0xFF) {
if((ret = getc_byte(&m2, &cbufptr, ebufptr))){
free(ndata);
return(ret);
}
if(m2 == 0x00) {
if((ret = putc_byte(m1, ndata, nalloc, &nlen))){
free(ndata);
return(ret);
}
if((ret = putc_byte(m2, ndata, nalloc, &nlen))){
free(ndata);
return(ret);
}
}
else {
cbufptr -= 2;
stp = 1;
}
}
else {
if((ret = putc_byte(m1, ndata, nalloc, &nlen))){
free(ndata);
return(ret);
}
}
}
}
}
else {
/* Don't Copy Comments. Print to stdout. */
if((ret = getc_ushort(&length, &cbufptr, ebufptr))){
free(ndata);
return(ret);
}
/*
printf("COMMENT (Length %d):\n", length-2);
for(i = 0; i < length-2; i++)
printf("%c", *(cbufptr+i));
printf("\n");
*/
cbufptr += length-2;
}
if((ret = getc_marker_wsq(&marker, ANY_WSQ, &cbufptr, ebufptr))){
free(ndata);
return(ret);
}
}
/* Copy EOI Marker */
if((ret = putc_ushort(marker, ndata, nalloc, &nlen))){
free(ndata);
return(ret);
}
*ocdata = ndata;
*oclen = nlen;
return(0);
}
| 30.595461 | 82 | 0.448202 | mahizhvannan |
51388507df9298375b670a75a0448f730e9b882a | 1,291 | hh | C++ | skysim/onnc-cimHW/lib/hardware/WordLineDriver.hh | ONNC/ONNC-CIM | dd15eae6b22b39dcd2bff179e14ad0eda40e4338 | [
"BSD-3-Clause"
] | 2 | 2021-07-05T02:26:11.000Z | 2022-01-11T10:37:20.000Z | skysim/onnc-cimHW/lib/hardware/WordLineDriver.hh | ONNC/ONNC-CIM | dd15eae6b22b39dcd2bff179e14ad0eda40e4338 | [
"BSD-3-Clause"
] | null | null | null | skysim/onnc-cimHW/lib/hardware/WordLineDriver.hh | ONNC/ONNC-CIM | dd15eae6b22b39dcd2bff179e14ad0eda40e4338 | [
"BSD-3-Clause"
] | 1 | 2022-01-11T10:39:01.000Z | 2022-01-11T10:39:01.000Z | //===- WordLineDriver.hh --------------------------------------------------===//
//
// The CIM Hardware Simulator Project
//
// See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#pragma once
#include "types.hh"
#include "CrossBarArray.hh"
namespace cimHW {
class WordLineDriver {
public:
WordLineDriver(const unsigned maxWordlines, const unsigned integerLen, const unsigned fractionLen) noexcept;
void setInput(const VectorXnum &inputVector, const unsigned OUSize);
CrossBarArray::WordLineVector getNextWordLine();
virtual RowVectorXui quantize2TwoComplement(const numType x) const;
void reset();
private:
// basic property of a wordline driver
const unsigned m_maxWordlines;
const unsigned m_integerLen;
const unsigned m_fractionLen;
const unsigned m_nBits;
// internal cursor
unsigned m_wordlines;
unsigned m_bitsIndex;
unsigned m_OUSize;
unsigned m_OUIndex;
MatrixXuiRowMajor m_buffer;
};
} // namespace cimHW
| 33.102564 | 110 | 0.522076 | ONNC |
513a337994e1ff22130cb373421048bb31ed1ac5 | 7,518 | cpp | C++ | code_reading/oceanbase-master/src/sql/engine/px/exchange/ob_px_repart_transmit.cpp | wangcy6/weekly_read | 3a8837ee9cd957787ee1785e4066dd623e02e13a | [
"Apache-2.0"
] | null | null | null | code_reading/oceanbase-master/src/sql/engine/px/exchange/ob_px_repart_transmit.cpp | wangcy6/weekly_read | 3a8837ee9cd957787ee1785e4066dd623e02e13a | [
"Apache-2.0"
] | null | null | null | code_reading/oceanbase-master/src/sql/engine/px/exchange/ob_px_repart_transmit.cpp | wangcy6/weekly_read | 3a8837ee9cd957787ee1785e4066dd623e02e13a | [
"Apache-2.0"
] | 1 | 2020-10-18T12:59:31.000Z | 2020-10-18T12:59:31.000Z | /**
* 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.
*/
#define USING_LOG_PREFIX SQL_ENG
#include "sql/engine/px/exchange/ob_px_repart_transmit.h"
#include "sql/dtl/ob_dtl_channel_group.h"
#include "sql/dtl/ob_dtl_rpc_channel.h"
#include "sql/executor/ob_range_hash_key_getter.h"
#include "sql/executor/ob_slice_calc.h"
using namespace oceanbase::common;
using namespace oceanbase::sql;
using namespace oceanbase::share::schema;
OB_SERIALIZE_MEMBER((ObPxRepartTransmitInput, ObPxTransmitInput));
//////////////////////////////////////////
ObPxRepartTransmit::ObPxRepartTransmitCtx::ObPxRepartTransmitCtx(ObExecContext& ctx)
: ObPxTransmit::ObPxTransmitCtx(ctx)
{}
ObPxRepartTransmit::ObPxRepartTransmitCtx::~ObPxRepartTransmitCtx()
{}
//////////////////////////////////////////
ObPxRepartTransmit::ObPxRepartTransmit(common::ObIAllocator& alloc) : ObPxTransmit(alloc)
{}
ObPxRepartTransmit::~ObPxRepartTransmit()
{}
int ObPxRepartTransmit::inner_open(ObExecContext& exec_ctx) const
{
int ret = OB_SUCCESS;
LOG_TRACE("Inner open px fifo transmit", "op_id", get_id());
if (OB_FAIL(ObPxTransmit::inner_open(exec_ctx))) {
LOG_WARN("initialize operator context failed", K(ret));
}
return ret;
}
int ObPxRepartTransmit::do_transmit(ObExecContext& exec_ctx) const
{
int ret = OB_SUCCESS;
ObPhysicalPlanCtx* phy_plan_ctx = NULL;
ObPxRepartTransmitInput* trans_input = NULL;
ObPxRepartTransmitCtx* transmit_ctx = NULL;
if (OB_ISNULL(phy_plan_ctx = GET_PHY_PLAN_CTX(exec_ctx)) ||
OB_ISNULL(trans_input = GET_PHY_OP_INPUT(ObPxRepartTransmitInput, exec_ctx, get_id())) ||
OB_ISNULL(transmit_ctx = GET_PHY_OPERATOR_CTX(ObPxRepartTransmitCtx, exec_ctx, get_id()))) {
LOG_ERROR("fail to op ctx", "op_id", get_id(), "op_type", get_type(), KP(trans_input), KP(transmit_ctx), K(ret));
} else if (!is_repart_exchange()) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("expect repart repartition", K(ret));
} else if (OB_INVALID_ID == repartition_table_id_) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("repartition table id should be set for repart transmit op", K(ret));
} else {
ObSchemaGetterGuard schema_guard;
const ObTableSchema* table_schema = NULL;
if (OB_FAIL(GCTX.schema_service_->get_tenant_schema_guard(
exec_ctx.get_my_session()->get_effective_tenant_id(), schema_guard))) {
LOG_WARN("faile to get schema guard", K(ret));
} else if (OB_FAIL(schema_guard.get_table_schema(repartition_table_id_, table_schema))) {
LOG_WARN("faile to get table schema", K(ret), K_(repartition_table_id));
} else if (OB_ISNULL(table_schema)) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("table schema is null. repart sharding requires a table in dfo", K_(repartition_table_id), K(ret));
} else if (OB_FAIL(
trans_input->get_part_ch_map(transmit_ctx->part_ch_info_, phy_plan_ctx->get_timeout_timestamp()))) {
LOG_WARN("fail to get channel affinity map", K(ret));
} else {
if (get_dist_method() == ObPQDistributeMethod::PARTITION_RANDOM) {
// pkey random
ObRepartRandomSliceIdxCalc repart_slice_calc(exec_ctx,
*table_schema,
&repart_func_,
&repart_sub_func_,
&repart_columns_,
&repart_sub_columns_,
unmatch_row_dist_method_,
transmit_ctx->part_ch_info_,
repartition_type_);
if (OB_FAIL(do_repart_transmit(exec_ctx, repart_slice_calc))) {
LOG_WARN("failed to do repart transmit for pkey random", K(ret));
}
} else if (ObPQDistributeMethod::PARTITION_HASH == get_dist_method()) {
// pkey hash
ObSlaveMapPkeyHashIdxCalc repart_slice_calc(exec_ctx,
*table_schema,
&repart_func_,
&repart_sub_func_,
&repart_columns_,
&repart_sub_columns_,
unmatch_row_dist_method_,
transmit_ctx->task_channels_.count(),
transmit_ctx->part_ch_info_,
transmit_ctx->expr_ctx_,
hash_dist_columns_,
dist_exprs_,
repartition_type_);
if (OB_FAIL(do_repart_transmit(exec_ctx, repart_slice_calc))) {
LOG_WARN("failed to do repart transmit for pkey random", K(ret));
}
} else {
// pkey
ObAffinitizedRepartSliceIdxCalc repart_slice_calc(exec_ctx,
*table_schema,
&repart_func_,
&repart_sub_func_,
&repart_columns_,
&repart_sub_columns_,
unmatch_row_dist_method_,
transmit_ctx->task_channels_.count(),
transmit_ctx->part_ch_info_,
repartition_type_);
if (OB_FAIL(do_repart_transmit(exec_ctx, repart_slice_calc))) {
LOG_WARN("failed to do repart transmit for pkey", K(ret));
}
}
}
}
return ret;
}
int ObPxRepartTransmit::do_repart_transmit(ObExecContext& exec_ctx, ObRepartSliceIdxCalc& repart_slice_calc) const
{
int ret = OB_SUCCESS;
ObPxRepartTransmitCtx* transmit_ctx = NULL;
if (OB_ISNULL(transmit_ctx = GET_PHY_OPERATOR_CTX(ObPxRepartTransmitCtx, exec_ctx, get_id()))) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("transmit_ctx is null", K(ret));
}
if (OB_SUCC(ret)) {
// init the ObRepartSliceIdxCalc cache map
if (OB_FAIL(repart_slice_calc.init_partition_cache_map())) {
LOG_WARN("failed to repart_slice_calc init partiiton cache map", K(ret));
} else if (OB_FAIL(repart_slice_calc.init())) {
LOG_WARN("failed to init repart slice calc", K(ret));
} else if (OB_FAIL(send_rows(exec_ctx, *transmit_ctx, repart_slice_calc))) {
LOG_WARN("failed to send rows", K(ret));
}
}
int tmp_ret = OB_SUCCESS;
if (OB_SUCCESS != (tmp_ret = repart_slice_calc.destroy())) {
LOG_WARN("failed to destroy", K(tmp_ret));
if (OB_SUCC(ret)) {
ret = tmp_ret;
}
}
return ret;
}
int ObPxRepartTransmit::inner_close(ObExecContext& exec_ctx) const
{
return ObPxTransmit::inner_close(exec_ctx);
}
int ObPxRepartTransmit::init_op_ctx(ObExecContext& ctx) const
{
int ret = OB_SUCCESS;
ObPhyOperatorCtx* op_ctx = NULL;
if (OB_FAIL(CREATE_PHY_OPERATOR_CTX(ObPxRepartTransmitCtx, ctx, get_id(), get_type(), op_ctx))) {
LOG_WARN("fail to create phy op ctx", K(ret), K(get_id()), K(get_type()));
} else if (OB_ISNULL(op_ctx)) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("op ctx is NULL", K(ret));
} else if (OB_FAIL(init_cur_row(*op_ctx, has_partition_id_column_idx()))) {
LOG_WARN("fail to int cur row", K(ret));
}
return ret;
}
int ObPxRepartTransmit::create_operator_input(ObExecContext& ctx) const
{
int ret = OB_SUCCESS;
ObIPhyOperatorInput* input = NULL;
if (OB_FAIL(CREATE_PHY_OP_INPUT(ObPxRepartTransmitInput, ctx, get_id(), get_type(), input))) {
LOG_WARN("fail to create phy op input", K(ret), K(get_id()), K(get_type()));
}
UNUSED(input);
return ret;
}
int ObPxRepartTransmit::add_compute(ObColumnExpression* expr)
{
return ObPhyOperator::add_compute(expr);
}
| 37.402985 | 119 | 0.686885 | wangcy6 |
513cc6e6a1fe14e275e9e87c97c261a4e2b9c562 | 15,216 | cpp | C++ | code/3rdParty/ogdf/src/ogdf/cluster/MaximumCPlanarSubgraph.cpp | turbanoff/qvge | 53508adadb4ca566c011b2b41d432030a5fa5fac | [
"MIT"
] | 3 | 2021-09-14T08:11:37.000Z | 2022-03-04T15:42:07.000Z | code/3rdParty/ogdf/src/ogdf/cluster/MaximumCPlanarSubgraph.cpp | turbanoff/qvge | 53508adadb4ca566c011b2b41d432030a5fa5fac | [
"MIT"
] | 2 | 2021-12-04T17:09:53.000Z | 2021-12-16T08:57:25.000Z | code/3rdParty/ogdf/src/ogdf/cluster/MaximumCPlanarSubgraph.cpp | turbanoff/qvge | 53508adadb4ca566c011b2b41d432030a5fa5fac | [
"MIT"
] | 2 | 2021-06-22T08:21:54.000Z | 2021-07-07T06:57:22.000Z | /** \file
* \brief Implementation of class MaximumCPlanarSubgraph
*
* \author Karsten Klein
*
* \par License:
* This file is part of the Open Graph Drawing Framework (OGDF).
*
* \par
* Copyright (C)<br>
* See README.md in the OGDF root directory for details.
*
* \par
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* Version 2 or 3 as published by the Free Software Foundation;
* see the file LICENSE.txt included in the packaging of this file
* for details.
*
* \par
* 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.
*
* \par
* You should have received a copy of the GNU General Public
* License along with this program; if not, see
* http://www.gnu.org/copyleft/gpl.html
*/
#include <ogdf/basic/basic.h>
#include <ogdf/cluster/MaximumCPlanarSubgraph.h>
#include <ogdf/cluster/CconnectClusterPlanar.h>
#include <ogdf/basic/simple_graph_alg.h>
#ifdef OGDF_CPLANAR_DEBUG_OUTPUT
#include <ogdf/fileformats/GraphIO.h>
#endif
using namespace abacus;
namespace ogdf {
using namespace cluster_planarity;
Module::ReturnType MaximumCPlanarSubgraph::doCall(const ClusterGraph &G,
const EdgeArray<int> *pCost,
List<edge> &delEdges,
List<NodePair> &addedEdges)
{
#ifdef OGDF_DEBUG
std::cout << "Creating new Masterproblem for clustergraph with " << G.constGraph().numberOfNodes() << " nodes\n";
#endif
MaxCPlanarMaster* cplanMaster = new MaxCPlanarMaster(G, pCost,
m_heuristicLevel,
m_heuristicRuns,
m_heuristicOEdgeBound,
m_heuristicNPermLists,
m_kuratowskiIterations,
m_subdivisions,
m_kSupportGraphs,
m_kuratowskiHigh,
m_kuratowskiLow,
m_perturbation,
m_branchingGap,
m_time.c_str(),
m_pricing,
m_checkCPlanar,
m_numAddVariables,
m_strongConstraintViolation,
m_strongVariableViolation);
cplanMaster->setPortaFile(m_portaOutput);
cplanMaster->useDefaultCutPool() = m_defaultCutPool;
#ifdef OGDF_DEBUG
std::cout << "Starting Optimization\n";
#endif
Master::STATUS status;
try {
status = cplanMaster->optimize();
}
catch (...)
{
#ifdef OGDF_DEBUG
std::cout << "ABACUS Optimization failed...\n";
#endif
}
m_totalTime = getDoubleTime(*cplanMaster->totalTime());
m_heurTime = getDoubleTime(*cplanMaster->improveTime());
m_sepTime = getDoubleTime(*cplanMaster->separationTime());
m_lpTime = getDoubleTime(*cplanMaster->lpTime());
m_lpSolverTime = getDoubleTime(*cplanMaster->lpSolverTime());
m_totalWTime = getDoubleTime(*cplanMaster->totalCowTime());
m_numKCons = cplanMaster->addedKConstraints();
m_numCCons = cplanMaster->addedCConstraints();
m_numLPs = cplanMaster->nLp();
m_numBCs = cplanMaster->nSub();
m_numSubSelected = cplanMaster->nSubSelected();
m_numVars = cplanMaster->nMaxVars()-cplanMaster->getNumInactiveVars();
#ifdef OGDF_DEBUG
m_solByHeuristic = cplanMaster->m_solByHeuristic;
#endif
#ifdef OGDF_DEBUG
if(cplanMaster->pricing())
Logger::slout() << "Pricing was ON\n";
Logger::slout() << "ABACUS returned with status '" << Master::STATUS_[status] << "'" << std::endl;
#endif
NodePairs allEdges;
cplanMaster->getDeletedEdges(delEdges);
cplanMaster->getConnectionOptimalSolutionEdges(addedEdges);
cplanMaster->getAllOptimalSolutionEdges(allEdges);
#ifdef OGDF_DEBUG
int delE = delEdges.size();
int addE = addedEdges.size();
std::cout << delE << " Number of deleted edges, " << addE << " Number of added edges " << allEdges.size() << " gesamt" << std::endl;
#endif
if (m_portaOutput)
{
writeFeasible(getPortaFileName(), *cplanMaster, status);
}
delete cplanMaster;
switch (status) {
case Master::Optimal: return Module::ReturnType::Optimal; break;
case Master::Error: return Module::ReturnType::Error; break;
default: break;
}
return Module::ReturnType::Error;
}
//returns list of all clusters in subtree at c in bottom up order
void MaximumCPlanarSubgraph::getBottomUpClusterList(const cluster c, List< cluster > & theList)
{
for(cluster cc : c->children) {
getBottomUpClusterList(cc, theList);
}
theList.pushBack(c);
}
//outputs the set of feasible solutions
void MaximumCPlanarSubgraph::writeFeasible(const char *filename,
MaxCPlanarMaster &master,
MaxCPlanarMaster::STATUS &status)
{
const ClusterGraph& CG = *(master.getClusterGraph());
const Graph& G = CG.constGraph();
//first compute the nodepairs that are potential candidates to connect
//chunks in a cluster
//potential connection edges
NodeArray< NodeArray<bool> > potConn(G);
for(node v : G.nodes)
{
potConn[v].init(G, false);
}
//we perform a bottom up cluster tree traversal
List< cluster > clist;
getBottomUpClusterList(CG.rootCluster(), clist);
//could use postordertraversal instead
NodePairs connPairs; //holds all connection node pairs
//counts the number of potential connectivity edges
//int potCount = 0; //equal to number of true values in potConn
//we run through the clusters and check connected components
//we consider all possible edges connecting CCs in a cluster,
//even if they may be connected by edges in a child cluster
//(to get the set of all feasible solutions)
for (cluster c : clist)
{
//we compute the subgraph induced by vertices in c
GraphCopy gcopy;
gcopy.createEmpty(G);
List<node> clusterNodes;
//would be more efficient if we would just merge the childrens' vertices
//and add c's
c->getClusterNodes(clusterNodes);
NodeArray<bool> activeNodes(G, false); //true for all cluster nodes
EdgeArray<edge> copyEdge(G); //holds the edge copy
for (node v : clusterNodes) {
activeNodes[v] = true;
}
gcopy.initByActiveNodes(clusterNodes, activeNodes, copyEdge);
//gcopy now represents the cluster induced subgraph
//we compute the connected components and store all nodepairs
//that connect two of them
NodeArray<int> component(gcopy);
connectedComponents(gcopy, component);
//now we run over all vertices and compare the component
//number of adjacent vertices. If they differ, we found a
//potential connection edge. We do not care if we find them twice.
for(node v : gcopy.nodes)
{
for(node w : gcopy.nodes)
{
if (component[v] != component[w])
{
std::cout << "Indizes: " << v->index() << ":" << w->index() << "\n";
node vg = gcopy.original(v);
node wg = gcopy.original(w);
bool newConn = !((vg->index() < wg->index()) ? potConn[vg][wg] : potConn[wg][vg]);
if (newConn)
{
NodePair np;
np.source = vg;
np.target = wg;
connPairs.pushBack(np);
if (vg->index() < wg->index())
potConn[vg][wg] = true;
else
potConn[wg][vg] = true;
}
}
}
}
}
std::cout << "Potentielle Verbindungskanten: "<< connPairs.size()<<"\n";
//we run through our candidates and save them in an array
//that can be used for dynamic graph updates
int i = 0;
struct connStruct {
bool connected;
node v1, v2;
edge e;
};
connStruct *cons = new connStruct[connPairs.size()];
for(const NodePair &np : connPairs)
{
connStruct cs;
cs.connected = false;
cs.v1 = np.source;
cs.v2 = np.target;
cs.e = nullptr;
cons[i] = cs;
i++;
}
// WARNING: this is extremely slow for graphs with a large number of cluster
// chunks now we test all possible connection edge combinations for c-planarity
Graph G2;
NodeArray<node> origNodes(CG.constGraph());
ClusterArray<cluster> origCluster(CG);
EdgeArray<edge> origEdges(CG.constGraph());
ClusterGraph testCopy(CG, G2, origCluster, origNodes, origEdges);
std::ofstream os(filename);
// Output dimension of the LP (number of variables)
os << "DIM = " << connPairs.size() << "\n";
os << "COMMENT\n";
switch (status) {
case Master::Optimal:
os << "Optimal \n\n"; break;
case Master::Error:
os << "Error \n\n"; break;
default:
os << "unknown \n\n";
}
for (i = 0; i < connPairs.size(); i++)
{
os << "Var " << i << ": " << origNodes[cons[i].v1]->index() << "->" << origNodes[cons[i].v2] << "\n";
}
os << "CONV_SECTION\n";
#ifdef OGDF_CPLANAR_DEBUG_OUTPUT
int writeCount = 0; //debug
#endif
if (connPairs.size() > 0)
while (true)
{
//we create the next test configuration by incrementing the edge selection array
//we create the corresponding graph dynamically on the fly
i = 0;
while (i < connPairs.size() && cons[i].connected)
{
cons[i].connected = false;
OGDF_ASSERT(cons[i].e != nullptr);
G2.delEdge(cons[i].e);
i++;
}
if (i >= connPairs.size()) break;
#if 0
std::cout<<"v1graph: "<<&(*(cons[i].v1->graphOf()))<<"\n";
std::cout<<"origNodesgraph: "<<&(*(origNodes.graphOf()))<<"\n";
#endif
cons[i].connected = true; //i.e., (false) will never be a feasible solution
cons[i].e = G2.newEdge(origNodes[cons[i].v1], origNodes[cons[i].v2]);
//and test it for c-planarity
CconnectClusterPlanar CCCP;
bool cplanar = CCCP.call(testCopy);
//c-planar graphs define a feasible solution
if (cplanar)
{
std::cout << "Feasible solution found\n";
for (int j = 0; j < connPairs.size(); j++)
{
char ch = (cons[j].connected ? '1' : '0');
std::cout << ch;
os << ch << " ";
}
std::cout << "\n";
os << "\n";
#ifdef OGDF_CPLANAR_DEBUG_OUTPUT
string fn = "cGraph";
fn += to_string(writeCount++) + ".gml";
GraphIO::writeGML(testCopy, fn);
#endif
}
}
delete[] cons;
os << "\nEND" <<"\n";
os.close();
#if 0
return;
#endif
os.open(getIeqFileName());
os << "DIM = " << m_numVars << "\n";
// Output the status as a comment
os << "COMMENT\n";
switch (status) {
case Master::Optimal:
os << "Optimal \n\n"; break;
case Master::Error:
os << "Error \n\n"; break;
default:
os << "unknown \n\n";
}
// In case 0 is not a valid solution, some PORTA functions need
//a valid solution in the ieq file
os << "VALID\n";
os << "\nLOWER_BOUNDS\n";
for (i = 0; i < m_numVars; i++) os << "0 ";
os << "\n";
os << "\nHIGHER_BOUNDS\n";
for (i = 0; i < m_numVars; i++) os << "1 ";
os << "\n";
os << "\nINEQUALITIES_SECTION\n";
//we first read the standard constraint that are written
//into a text file by the optimization master
std::ifstream isf(master.getStdConstraintsFileName());
if (!isf)
{
std::cerr << "Could not open optimization master's standard constraint file\n";
os << "#No standard constraints read\n";
}
else
{
char* fileLine = new char[maxConLength()];
while (isf.getline(fileLine, maxConLength()))
{
//skip commment lines
if (fileLine[0] == '#') continue;
int count = 1;
std::istringstream iss(fileLine);
char d;
bool rhs = false;
while (iss >> d)
{
if ( rhs || ( (d == '<') || (d == '>') || (d == '=') ) )
{
os << d;
rhs = true;
}
else
{
if (d != '0')
{
os <<"+"<< d <<"x"<<count;
}
count++;
}
}
os <<"\n";
}
delete[] fileLine;
}
//now we read the cut pools from the master
if (master.useDefaultCutPool())
{
os << "#No cut constraints read from master\n";
#if 0
StandardPool<Constraint, Variable> *connCon = master.cutPool();
#endif
}
else
{
StandardPool<Constraint, Variable> *connCon = master.getCutConnPool();
StandardPool<Constraint, Variable> *kuraCon = master.getCutKuraPool();
StandardPool<Variable, Constraint> *stdVar = master.varPool();
OGDF_ASSERT(connCon != nullptr);
OGDF_ASSERT(kuraCon != nullptr);
std::cout << connCon->number() << " Constraints im MasterConnpool \n";
std::cout << kuraCon->number() << " Constraints im MasterKurapool \n";
std::cout << connCon->size() << " Größe ConnPool"<<"\n";
outputCons(os, connCon, stdVar);
outputCons(os, kuraCon, stdVar);
}
os << "\nEND" <<"\n";
os.close();
std::cout << "Cutting is set: "<<master.cutting()<<"\n";
#if 0
std::cout <<"Bounds for the variables:\n";
Sub &theSub = *(master.firstSub());
for ( i = 0; i < theSub.nVar(); i++)
{
std::cout << i << ": " << theSub.lBound(i) << " - " << theSub.uBound(i) << "\n";
}
#endif
#if 0
// OLD CRAP
std::cout << "Constraints: \n";
StandardPool< Constraint, Variable > *spool = master.conPool();
StandardPool< Constraint, Variable > *cpool = master.cutPool();
std::cout << spool->size() << " Constraints im Masterpool \n";
std::cout << cpool->size() << " Constraints im Mastercutpool \n";
std::cout << "ConPool Constraints \n";
for ( i = 0; i < spool->size(); i++)
{
PoolSlot< Constraint, Variable > * sloty = spool->slot(i);
Constraint *mycon = sloty->conVar();
switch (mycon->sense()->sense())
{
case CSense::Less: std::cout << "<" << "\n"; break;
case CSense::Greater: std::cout << ">" << "\n"; break;
case CSense::Equal: std::cout << "=" << "\n"; break;
default: std::cout << "Inequality sense doesn't make any sense \n"; break;
}
}
std::cout << "CutPool Constraints \n";
for ( i = 0; i < cpool->size(); i++)
{
PoolSlot< Constraint, Variable > * sloty = cpool->slot(i);
Constraint *mycon = sloty->conVar();
switch (mycon->sense()->sense())
{
case CSense::Less: std::cout << "<" << "\n"; break;
case CSense::Greater: std::cout << ">" << "\n"; break;
case CSense::Equal: std::cout << "=" << "\n"; break;
default: std::cout << "Inequality sense doesn't make any sense \n"; break;
}
}
for ( i = 0; i < theSub.nCon(); i++)
{
Constraint &theCon = *(theSub.constraint(i));
for ( i = 0; i < theSub.nVar(); i++)
{
double c = theCon.coeff(theSub.variable(i));
if (c != 0)
std::cout << c;
else std::cout << " ";
}
switch (theCon.sense()->sense())
{
case CSense::Less: std::cout << "<" << "\n"; break;
case CSense::Greater: std::cout << ">" << "\n"; break;
case CSense::Equal: std::cout << "=" << "\n"; break;
default: std::cout << "doesn't make any sense \n"; break;
}
float fl;
while(!(std::cin >> fl))
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
}
}
#endif
}
void MaximumCPlanarSubgraph::outputCons(std::ofstream &os,
StandardPool<Constraint, Variable> *connCon,
StandardPool<Variable, Constraint> *stdVar)
{
int i;
for ( i = 0; i < connCon->number(); i++)
{
PoolSlot< Constraint, Variable > * sloty = connCon->slot(i);
Constraint *mycon = sloty->conVar();
OGDF_ASSERT(mycon != nullptr);
int count;
for (count = 0; count < stdVar->size(); count++)
{
PoolSlot< Variable, Constraint > * slotv = stdVar->slot(count);
Variable *myvar = slotv->conVar();
double d = mycon->coeff(myvar);
if (d != 0.0) //precision!
{
os <<"+"<< d <<"x"<<count+1;
}
}
switch (mycon->sense()->sense())
{
case CSense::Less: os << " <= "; break;
case CSense::Greater: os << " >= "; break;
case CSense::Equal: os << " = "; break;
default:
os << "Inequality sense doesn't make any sense \n";
std::cerr << "Inequality sense unknown \n";
break;
}
os << mycon->rhs();
os << "\n";
}
}
}
| 28.282528 | 133 | 0.642547 | turbanoff |
513da54bf06620d5fd47c5a679cbfdfeab902860 | 47,571 | cc | C++ | gui/schedule_list.cc | chris-nada/simutrans-extended | 71c0c4f78cb3170b1fa1c68d8baafa9a7269ef6f | [
"Artistic-1.0"
] | 38 | 2017-07-26T14:48:12.000Z | 2022-03-24T23:48:55.000Z | gui/schedule_list.cc | chris-nada/simutrans-extended | 71c0c4f78cb3170b1fa1c68d8baafa9a7269ef6f | [
"Artistic-1.0"
] | 74 | 2017-03-15T21:07:34.000Z | 2022-03-18T07:53:11.000Z | gui/schedule_list.cc | chris-nada/simutrans-extended | 71c0c4f78cb3170b1fa1c68d8baafa9a7269ef6f | [
"Artistic-1.0"
] | 43 | 2017-03-10T15:27:28.000Z | 2022-03-05T10:55:38.000Z | /*
* This file is part of the Simutrans-Extended project under the Artistic License.
* (see LICENSE.txt)
*/
#include <stdio.h>
#include <algorithm>
#include "messagebox.h"
#include "schedule_list.h"
#include "line_management_gui.h"
#include "components/gui_convoiinfo.h"
#include "components/gui_divider.h"
#include "line_item.h"
#include "simwin.h"
#include "../simcolor.h"
#include "../simdepot.h"
#include "../simhalt.h"
#include "../simworld.h"
#include "../simevent.h"
#include "../display/simgraph.h"
#include "../simskin.h"
#include "../simconvoi.h"
#include "../vehicle/vehicle.h"
#include "../simlinemgmt.h"
#include "../simmenu.h"
#include "../utils/simstring.h"
#include "../player/simplay.h"
#include "../gui/line_class_manager.h"
#include "../bauer/vehikelbauer.h"
#include "../dataobj/schedule.h"
#include "../dataobj/translator.h"
#include "../dataobj/livery_scheme.h"
#include "../dataobj/environment.h"
#include "../boden/wege/kanal.h"
#include "../boden/wege/maglev.h"
#include "../boden/wege/monorail.h"
#include "../boden/wege/narrowgauge.h"
#include "../boden/wege/runway.h"
#include "../boden/wege/schiene.h"
#include "../boden/wege/strasse.h"
#include "../unicode.h"
#include "minimap.h"
#include "halt_info.h"
uint16 schedule_list_gui_t::livery_scheme_index = 0;
static const char *cost_type[MAX_LINE_COST] =
{
"Free Capacity",
"Transported",
"Distance",
"Average speed",
// "Maxspeed",
"Comfort",
"Revenue",
"Operation",
"Refunds",
"Road toll",
"Profit",
"Convoys",
"Departures",
"Scheduled"
};
const uint8 cost_type_color[MAX_LINE_COST] =
{
COL_FREE_CAPACITY,
COL_TRANSPORTED,
COL_DISTANCE,
COL_AVERAGE_SPEED,
COL_COMFORT,
COL_REVENUE,
COL_OPERATION,
COL_CAR_OWNERSHIP,
COL_TOLL,
COL_PROFIT,
COL_VEHICLE_ASSETS,
//COL_COUNVOI_COUNT,
COL_MAXSPEED,
COL_LILAC
};
static uint32 bFilterStates = 0;
static uint8 tabs_to_lineindex[8];
static uint8 max_idx=0;
static uint8 statistic[MAX_LINE_COST]={
LINE_CAPACITY, LINE_TRANSPORTED_GOODS, LINE_DISTANCE, LINE_AVERAGE_SPEED, LINE_COMFORT, LINE_REVENUE, LINE_OPERATIONS, LINE_REFUNDS, LINE_WAYTOLL, LINE_PROFIT, LINE_CONVOIS, LINE_DEPARTURES, LINE_DEPARTURES_SCHEDULED
//std LINE_CAPACITY, LINE_TRANSPORTED_GOODS, LINE_REVENUE, LINE_OPERATIONS, LINE_PROFIT, LINE_CONVOIS, LINE_DISTANCE, LINE_MAXSPEED, LINE_WAYTOLL
};
static uint8 statistic_type[MAX_LINE_COST]={
STANDARD, STANDARD, STANDARD, STANDARD, STANDARD, MONEY, MONEY, MONEY, MONEY, MONEY, STANDARD, STANDARD, STANDARD
//std STANDARD, STANDARD, MONEY, MONEY, MONEY, STANDARD, STANDARD, STANDARD, MONEY
};
static const char * line_alert_helptexts[5] =
{
"line_nothing_moved",
"line_missing_scheduled_slots",
"line_has_obsolete_vehicles",
"line_overcrowded",
"line_has_upgradeable_vehicles"
};
enum sort_modes_t { SORT_BY_NAME=0, SORT_BY_ID, SORT_BY_PROFIT, SORT_BY_TRANSPORTED, SORT_BY_CONVOIS, SORT_BY_DISTANCE, MAX_SORT_MODES };
static uint8 current_sort_mode = 0;
#define LINE_NAME_COLUMN_WIDTH ((D_BUTTON_WIDTH*3)+11+4)
#define SCL_HEIGHT (min(L_DEFAULT_WINDOW_HEIGHT/2+D_TAB_HEADER_HEIGHT,(15*LINESPACE)))
#define L_DEFAULT_WINDOW_HEIGHT max(305, 24*LINESPACE)
/// selected convoy tab
static uint8 selected_convoy_tab = 0;
/// selected line tab per player
static uint8 selected_tab[MAX_PLAYER_COUNT] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
/// selected line per tab (static)
linehandle_t schedule_list_gui_t::selected_line[MAX_PLAYER_COUNT][simline_t::MAX_LINE_TYPE];
// selected convoy list display mode
static uint8 selected_cnvlist_mode[MAX_PLAYER_COUNT] = {0};
// sort stuff
schedule_list_gui_t::sort_mode_t schedule_list_gui_t::sortby = by_name;
static uint8 default_sortmode = 0;
bool schedule_list_gui_t::sortreverse = false;
const char *schedule_list_gui_t::sort_text[SORT_MODES] = {
"cl_btn_sort_name",
"cl_btn_sort_schedule",
"cl_btn_sort_income",
"cl_btn_sort_loading_lvl",
"cl_btn_sort_max_speed",
"cl_btn_sort_power",
"cl_btn_sort_value",
"cl_btn_sort_age",
"cl_btn_sort_range"
};
gui_line_waiting_status_t::gui_line_waiting_status_t(linehandle_t line_)
{
line = line_;
set_table_layout(1, 0);
set_spacing(scr_size(1, 0));
init();
}
void gui_line_waiting_status_t::init()
{
remove_all();
if (line.is_bound()) {
schedule = line->get_schedule();
if( !schedule->get_count() ) return; // nothing to show
uint8 cols; // table cols
cols = line->get_goods_catg_index().get_count()+show_name+1;
add_table(cols, 0);
{
// header
new_component<gui_empty_t>();
if (show_name) {
new_component<gui_label_t>("stations");
}
for (uint8 catg_index = 0; catg_index < goods_manager_t::get_max_catg_index(); catg_index++) {
if (line->get_goods_catg_index().is_contained(catg_index) ) {
add_table(2,1);
{
new_component<gui_image_t>(goods_manager_t::get_info_catg_index(catg_index)->get_catg_symbol(), 0, ALIGN_NONE, true);
new_component<gui_label_t>(goods_manager_t::get_info_catg_index(catg_index)->get_catg_name());
}
end_table();
}
}
// border
new_component<gui_empty_t>();
for (uint8 i = 1; i < cols; ++i) {
new_component<gui_border_t>();
}
uint8 entry_idx = 0;
FORX(minivec_tpl<schedule_entry_t>, const& i, schedule->entries, ++entry_idx) {
halthandle_t const halt = haltestelle_t::get_halt(i.pos, line->get_owner());
if( !halt.is_bound() ) { continue; }
const bool is_interchange = (halt->registered_lines.get_count() + halt->registered_convoys.get_count()) > 1;
new_component<gui_schedule_entry_number_t>(entry_idx, halt->get_owner()->get_player_color1(),
is_interchange ? gui_schedule_entry_number_t::number_style::interchange : gui_schedule_entry_number_t::number_style::halt,
scr_size(D_ENTRY_NO_WIDTH, max(D_POS_BUTTON_HEIGHT, D_ENTRY_NO_HEIGHT)),
halt->get_basis_pos3d()
);
if (show_name) {
gui_label_buf_t *lb = new_component<gui_label_buf_t>();
lb->buf().append(halt->get_name());
lb->update();
}
for (uint8 catg_index = 0; catg_index < goods_manager_t::get_max_catg_index(); catg_index++) {
if (line->get_goods_catg_index().is_contained(catg_index)) {
new_component<gui_halt_waiting_catg_t>(halt, catg_index);
}
}
}
}
end_table();
}
}
void gui_line_waiting_status_t::draw(scr_coord offset)
{
if (line.is_bound()) {
if (!line->get_schedule()->matches(world(), schedule)) {
init();
}
}
set_size(get_size());
gui_aligned_container_t::draw(offset);
}
schedule_list_gui_t::schedule_list_gui_t(player_t *player_) :
gui_frame_t(translator::translate("Line Management"), player_),
player(player_),
scrolly_convois(&cont),
cont_haltlist(linehandle_t()),
scrolly_haltestellen(&cont_tab_haltlist, true, true),
scroll_times_history(&cont_times_history, true, true),
scrolly_line_info(&cont_line_info, true, true),
scl(gui_scrolled_list_t::listskin, line_scrollitem_t::compare),
lbl_filter("Line Filter"),
cont_line_capacity_by_catg(linehandle_t(), convoihandle_t()),
convoy_infos(),
halt_entry_origin(-1), halt_entry_dest(-1),
routebar_middle(player_->get_player_color1(), gui_colored_route_bar_t::downward)
{
selection = -1;
schedule_filter[0] = 0;
old_schedule_filter[0] = 0;
last_schedule = NULL;
old_player = NULL;
line_goods_catg_count = 0;
origin_halt = halthandle_t();
destination_halt = halthandle_t();
// init scrolled list
scl.set_pos(scr_coord(0,1));
scl.set_size(scr_size(LINE_NAME_COLUMN_WIDTH-11-4, SCL_HEIGHT-18));
scl.set_highlight_color(color_idx_to_rgb(player->get_player_color1()+1));
scl.add_listener(this);
// tab panel
tabs.set_pos(scr_coord(11,5));
tabs.set_size(scr_size(LINE_NAME_COLUMN_WIDTH-11-4, SCL_HEIGHT));
tabs.add_tab(&scl, translator::translate("All"));
max_idx = 0;
tabs_to_lineindex[max_idx++] = simline_t::line;
// now add all specific tabs
if(maglev_t::default_maglev) {
tabs.add_tab(&scl, translator::translate("Maglev"), skinverwaltung_t::maglevhaltsymbol, translator::translate("Maglev"));
tabs_to_lineindex[max_idx++] = simline_t::maglevline;
}
if(monorail_t::default_monorail) {
tabs.add_tab(&scl, translator::translate("Monorail"), skinverwaltung_t::monorailhaltsymbol, translator::translate("Monorail"));
tabs_to_lineindex[max_idx++] = simline_t::monorailline;
}
if(schiene_t::default_schiene) {
tabs.add_tab(&scl, translator::translate("Train"), skinverwaltung_t::zughaltsymbol, translator::translate("Train"));
tabs_to_lineindex[max_idx++] = simline_t::trainline;
}
if(narrowgauge_t::default_narrowgauge) {
tabs.add_tab(&scl, translator::translate("Narrowgauge"), skinverwaltung_t::narrowgaugehaltsymbol, translator::translate("Narrowgauge"));
tabs_to_lineindex[max_idx++] = simline_t::narrowgaugeline;
}
if (!vehicle_builder_t::get_info(tram_wt).empty()) {
tabs.add_tab(&scl, translator::translate("Tram"), skinverwaltung_t::tramhaltsymbol, translator::translate("Tram"));
tabs_to_lineindex[max_idx++] = simline_t::tramline;
}
if(strasse_t::default_strasse) {
tabs.add_tab(&scl, translator::translate("Truck"), skinverwaltung_t::autohaltsymbol, translator::translate("Truck"));
tabs_to_lineindex[max_idx++] = simline_t::truckline;
}
if (!vehicle_builder_t::get_info(water_wt).empty()) {
tabs.add_tab(&scl, translator::translate("Ship"), skinverwaltung_t::schiffshaltsymbol, translator::translate("Ship"));
tabs_to_lineindex[max_idx++] = simline_t::shipline;
}
if(runway_t::default_runway) {
tabs.add_tab(&scl, translator::translate("Air"), skinverwaltung_t::airhaltsymbol, translator::translate("Air"));
tabs_to_lineindex[max_idx++] = simline_t::airline;
}
tabs.add_listener(this);
add_component(&tabs);
// editable line name
inp_name.add_listener(this);
inp_name.set_pos(scr_coord(LINE_NAME_COLUMN_WIDTH+23, D_MARGIN_TOP));
inp_name.set_visible(false);
add_component(&inp_name);
// sort button on convoy list, define this first to prevent overlapping
sortedby.set_pos(scr_coord(BUTTON1_X, 2));
sortedby.set_size(scr_size(D_BUTTON_WIDTH*1.5, D_BUTTON_HEIGHT));
sortedby.set_max_size(scr_size(D_BUTTON_WIDTH * 1.5, LINESPACE * 8));
for (int i = 0; i < SORT_MODES; i++) {
sortedby.new_component<gui_scrolled_list_t::const_text_scrollitem_t>(translator::translate(sort_text[i]), SYSCOL_TEXT);
}
sortedby.set_selection(default_sortmode);
sortedby.add_listener(this);
cont_convoys.add_component(&sortedby);
// convoi list
cont.set_size(scr_size(200, 80));
cont.set_pos(scr_coord(D_H_SPACE, D_V_SPACE));
scrolly_convois.set_pos(scr_coord(0, D_BUTTON_HEIGHT+D_H_SPACE));
scrolly_convois.set_show_scroll_y(true);
scrolly_convois.set_scroll_amount_y(40);
scrolly_convois.set_visible(false);
cont_convoys.add_component(&scrolly_convois);
scrolly_line_info.set_visible(false);
cont_line_info.set_table_layout(1,0);
cont_line_info.add_table(2,0)->set_spacing(scr_size(D_H_SPACE, 0));
{
cont_line_info.add_component(&halt_entry_origin);
cont_line_info.add_component(&lb_line_origin);
cont_line_info.add_component(&routebar_middle);
cont_line_info.new_component<gui_empty_t>();
cont_line_info.add_component(&halt_entry_dest);
cont_line_info.add_component(&lb_line_destination);
}
cont_line_info.end_table();
cont_line_info.add_table(3,1);
{
cont_line_info.add_component(&lb_travel_distance);
if (skinverwaltung_t::service_frequency) {
cont_line_info.new_component<gui_image_t>(skinverwaltung_t::service_frequency->get_image_id(0), 0, ALIGN_NONE, true)->set_tooltip(translator::translate("Service frequency"));
}
else {
cont_line_info.new_component<gui_label_t>("Service frequency");
}
cont_line_info.add_component(&lb_service_frequency);
}
cont_line_info.end_table();
cont_line_info.add_table(2,1);
{
cont_line_info.add_component(&lb_convoy_count);
bt_withdraw_line.init(button_t::box_state, "Withdraw All", scr_coord(0, 0), scr_size(D_BUTTON_WIDTH+18,D_BUTTON_HEIGHT));
bt_withdraw_line.set_tooltip("Convoi is sold when all wagons are empty.");
if (skinverwaltung_t::alerts) {
bt_withdraw_line.set_image(skinverwaltung_t::alerts->get_image_id(2));
}
bt_withdraw_line.add_listener(this);
cont_line_info.add_component(&bt_withdraw_line);
}
cont_line_info.end_table();
cont_line_info.new_component<gui_divider_t>();
cont_line_info.add_component(&cont_line_capacity_by_catg);
scrolly_line_info.set_pos(scr_coord(0, 8 + SCL_HEIGHT + D_BUTTON_HEIGHT + D_BUTTON_HEIGHT + 2));
add_component(&scrolly_line_info);
// filter lines by
lbl_filter.set_pos( scr_coord( 11, 7+SCL_HEIGHT+2 ) );
add_component(&lbl_filter);
inp_filter.set_pos( scr_coord( 11+D_BUTTON_WIDTH, 7+SCL_HEIGHT ) );
inp_filter.set_size( scr_size( D_BUTTON_WIDTH*2- D_BUTTON_HEIGHT *3, D_EDIT_HEIGHT ) );
inp_filter.set_text( schedule_filter, lengthof(schedule_filter) );
// inp_filter.set_tooltip("Only show lines containing");
inp_filter.add_listener(this);
add_component(&inp_filter);
filter_btn_all_pas.init(button_t::roundbox_state, NULL, scr_coord(inp_filter.get_pos() + scr_coord(inp_filter.get_size().w, 0)), scr_size(D_BUTTON_HEIGHT, D_BUTTON_HEIGHT));
filter_btn_all_pas.set_image(skinverwaltung_t::passengers->get_image_id(0));
filter_btn_all_pas.set_tooltip("filter_pas_line");
filter_btn_all_pas.pressed = line_type_flags & (1 << simline_t::all_pas);
add_component(&filter_btn_all_pas);
filter_btn_all_pas.add_listener(this);
filter_btn_all_mails.init(button_t::roundbox_state, NULL, scr_coord(filter_btn_all_pas.get_pos() + scr_coord(D_BUTTON_HEIGHT, 0)), scr_size(D_BUTTON_HEIGHT, D_BUTTON_HEIGHT));
filter_btn_all_mails.set_image(skinverwaltung_t::mail->get_image_id(0));
filter_btn_all_mails.set_tooltip("filter_mail_line");
filter_btn_all_mails.pressed = line_type_flags & (1 << simline_t::all_mail);
filter_btn_all_mails.add_listener(this);
add_component(&filter_btn_all_mails);
filter_btn_all_freights.init(button_t::roundbox_state, NULL, scr_coord(filter_btn_all_mails.get_pos() + scr_coord(D_BUTTON_HEIGHT, 0)), scr_size(D_BUTTON_HEIGHT, D_BUTTON_HEIGHT));
filter_btn_all_freights.set_image(skinverwaltung_t::goods->get_image_id(0));
filter_btn_all_freights.set_tooltip("filter_freight_line");
filter_btn_all_freights.pressed = line_type_flags & (1 << simline_t::all_freight);
filter_btn_all_freights.add_listener(this);
add_component(&filter_btn_all_freights);
// normal buttons edit new remove
bt_new_line.init(button_t::roundbox, "New Line", scr_coord(11, 8+SCL_HEIGHT+D_BUTTON_HEIGHT ), D_BUTTON_SIZE);
bt_new_line.add_listener(this);
add_component(&bt_new_line);
bt_edit_line.init(button_t::roundbox, "Update Line", scr_coord(11+D_BUTTON_WIDTH, 8+SCL_HEIGHT+D_BUTTON_HEIGHT ), D_BUTTON_SIZE);
bt_edit_line.set_tooltip("Modify the selected line");
bt_edit_line.add_listener(this);
bt_edit_line.disable();
add_component(&bt_edit_line);
bt_delete_line.init(button_t::roundbox, "Delete Line", scr_coord(11+2*D_BUTTON_WIDTH, 8+SCL_HEIGHT+D_BUTTON_HEIGHT ), D_BUTTON_SIZE);
bt_delete_line.set_tooltip("Delete the selected line (if without associated convois).");
bt_delete_line.add_listener(this);
bt_delete_line.disable();
add_component(&bt_delete_line);
int offset_y = D_MARGIN_TOP + D_BUTTON_HEIGHT*2;
bt_line_class_manager.init(button_t::roundbox_state, "line_class_manager", scr_coord(LINE_NAME_COLUMN_WIDTH, offset_y), D_BUTTON_SIZE);
bt_line_class_manager.set_tooltip("change_the_classes_for_the_entire_line");
bt_line_class_manager.set_visible(false);
bt_line_class_manager.add_listener(this);
add_component(&bt_line_class_manager);
offset_y += D_BUTTON_HEIGHT;
// Select livery
livery_selector.set_pos(scr_coord(LINE_NAME_COLUMN_WIDTH, offset_y));
livery_selector.set_focusable(false);
livery_selector.set_size(scr_size(D_BUTTON_WIDTH*1.5, D_BUTTON_HEIGHT));
livery_selector.set_max_size(scr_size(D_BUTTON_WIDTH - 8, LINESPACE * 8 + 2 + 16));
livery_selector.set_highlight_color(1);
livery_selector.clear_elements();
livery_selector.add_listener(this);
add_component(&livery_selector);
// sort asc/desc switching button
sort_order.set_typ(button_t::sortarrow_state); // NOTE: This dialog is not yet auto-aligned, so we need to pre-set the typ to calculate the size
sort_order.init(button_t::sortarrow_state, "", scr_coord(BUTTON1_X + D_BUTTON_WIDTH * 1.5 + D_H_SPACE, 2), sort_order.get_min_size());
sort_order.set_tooltip(translator::translate("cl_btn_sort_order"));
sort_order.add_listener(this);
sort_order.pressed = sortreverse;
cont_convoys.add_component(&sort_order);
bt_mode_convois.init(button_t::roundbox, gui_convoy_formation_t::cnvlist_mode_button_texts[selected_cnvlist_mode[player->get_player_nr()]], scr_coord(BUTTON3_X, 2), scr_size(D_BUTTON_WIDTH+15, D_BUTTON_HEIGHT));
bt_mode_convois.add_listener(this);
cont_convoys.add_component(&bt_mode_convois);
info_tabs.add_tab(&cont_convoys, translator::translate("Convoys"));
offset_y += D_BUTTON_HEIGHT;
// right tabs
info_tabs.set_pos(scr_coord(LINE_NAME_COLUMN_WIDTH-4, offset_y));
info_tabs.add_listener(this);
info_tabs.set_size(scr_size(get_windowsize().w- LINE_NAME_COLUMN_WIDTH+4+D_MARGIN_RIGHT, get_windowsize().h-offset_y));
add_component(&info_tabs);
//CHART
chart.set_dimension(12, 1000);
chart.set_pos( scr_coord(68, LINESPACE) );
chart.set_seed(0);
chart.set_background(SYSCOL_CHART_BACKGROUND);
chart.set_ltr(env_t::left_to_right_graphs);
cont_charts.add_component(&chart);
// add filter buttons
for (int i=0; i<MAX_LINE_COST; i++) {
filterButtons[i].init(button_t::box_state,cost_type[i],scr_coord(0,0), D_BUTTON_SIZE);
filterButtons[i].add_listener(this);
filterButtons[i].background_color = color_idx_to_rgb(cost_type_color[i]);
cont_charts.add_component(filterButtons + i);
}
info_tabs.add_tab(&cont_charts, translator::translate("Chart"));
info_tabs.set_active_tab_index(selected_convoy_tab);
cont_times_history.set_table_layout(1,0);
info_tabs.add_tab(&scroll_times_history, translator::translate("times_history"));
cont_tab_haltlist.set_table_layout(1,0);
bt_show_halt_name.init(button_t::square_state, "show station names");
bt_show_halt_name.set_tooltip("helptxt_show_station_name");
bt_show_halt_name.pressed=true;
bt_show_halt_name.add_listener(this);
cont_tab_haltlist.add_component(&bt_show_halt_name);
cont_tab_haltlist.add_component(&cont_haltlist);
info_tabs.add_tab(&scrolly_haltestellen, translator::translate("waiting_status"));
// recover last selected line
int index = 0;
for( uint i=0; i<max_idx; i++ ) {
if( tabs_to_lineindex[i] == selected_tab[player->get_player_nr()] ) {
line = selected_line[player->get_player_nr()][selected_tab[player->get_player_nr()]];
// check owner here: selected_line[][] is not reset between games, so line could have another player as owner
if (line.is_bound() && line->get_owner() != player) {
line = linehandle_t();
}
index = i;
break;
}
}
selected_tab[player->get_player_nr()] = tabs_to_lineindex[index]; // reset if previous selected tab is not there anymore
tabs.set_active_tab_index(index);
if(index>0) {
bt_new_line.enable();
}
else {
bt_new_line.disable();
}
update_lineinfo( line );
// resize button
set_min_windowsize(scr_size(LINE_NAME_COLUMN_WIDTH + D_BUTTON_WIDTH*3 + D_MARGIN_LEFT*2, L_DEFAULT_WINDOW_HEIGHT));
set_resizemode(diagonal_resize);
resize(scr_coord(0,0));
resize(scr_coord(D_BUTTON_WIDTH, LINESPACE*3+D_V_SPACE)); // suitable for 4 buttons horizontally and 5 convoys vertically
build_line_list(index);
}
schedule_list_gui_t::~schedule_list_gui_t()
{
delete last_schedule;
// change line name if necessary
rename_line();
}
/**
* Mouse clicks are hereby reported to the GUI-Components
*/
bool schedule_list_gui_t::infowin_event(const event_t *ev)
{
if(ev->ev_class == INFOWIN) {
if(ev->ev_code == WIN_CLOSE) {
// hide schedule on minimap (may not current, but for safe)
minimap_t::get_instance()->set_selected_cnv( convoihandle_t() );
}
else if( (ev->ev_code==WIN_OPEN || ev->ev_code==WIN_TOP) && line.is_bound() ) {
if( line->count_convoys()>0 ) {
// set this schedule as current to show on minimap if possible
minimap_t::get_instance()->set_selected_cnv( line->get_convoy(0) );
}
else {
// set this schedule as current to show on minimap if possible
minimap_t::get_instance()->set_selected_cnv( convoihandle_t() );
}
}
}
return gui_frame_t::infowin_event(ev);
}
bool schedule_list_gui_t::action_triggered( gui_action_creator_t *comp, value_t v )
{
if(comp == &bt_edit_line) {
if(line.is_bound()) {
create_win( new line_management_gui_t(line, player), w_info, (ptrdiff_t)line.get_rep() );
}
}
else if(comp == &bt_new_line) {
// create typed line
assert( tabs.get_active_tab_index() > 0 && tabs.get_active_tab_index()<max_idx );
// update line schedule via tool!
tool_t *tmp_tool = create_tool( TOOL_CHANGE_LINE | SIMPLE_TOOL );
cbuffer_t buf;
int type = tabs_to_lineindex[tabs.get_active_tab_index()];
buf.printf( "c,0,%i,0,0|%i|", type, type );
tmp_tool->set_default_param(buf);
welt->set_tool( tmp_tool, player );
// since init always returns false, it is safe to delete immediately
delete tmp_tool;
depot_t::update_all_win();
}
else if(comp == &bt_delete_line) {
if(line.is_bound()) {
tool_t *tmp_tool = create_tool( TOOL_CHANGE_LINE | SIMPLE_TOOL );
cbuffer_t buf;
buf.printf( "d,%i", line.get_id() );
tmp_tool->set_default_param(buf);
welt->set_tool( tmp_tool, player );
// since init always returns false, it is safe to delete immediately
delete tmp_tool;
depot_t::update_all_win();
}
}
else if(comp == &bt_withdraw_line) {
bt_withdraw_line.pressed ^= 1;
if (line.is_bound()) {
tool_t *tmp_tool = create_tool( TOOL_CHANGE_LINE | SIMPLE_TOOL );
cbuffer_t buf;
buf.printf( "w,%i,%i", line.get_id(), bt_withdraw_line.pressed );
tmp_tool->set_default_param(buf);
welt->set_tool( tmp_tool, player );
// since init always returns false, it is safe to delete immediately
delete tmp_tool;
}
}
else if (comp == &bt_line_class_manager)
{
create_win(20, 20, new line_class_manager_t(line), w_info, magic_line_class_manager + line.get_id());
return true;
}
else if (comp == &sortedby) {
int tmp = sortedby.get_selection();
if (tmp >= 0 && tmp < sortedby.count_elements())
{
sortedby.set_selection(tmp);
set_sortierung((sort_mode_t)tmp);
}
else {
sortedby.set_selection(0);
set_sortierung(by_name);
}
default_sortmode = (uint8)tmp;
update_lineinfo(line);
}
else if (comp == &sort_order) {
set_reverse(!get_reverse());
update_lineinfo(line);
sort_order.pressed = sortreverse;
}
else if (comp == &bt_mode_convois) {
selected_cnvlist_mode[player->get_player_nr()] = (selected_cnvlist_mode[player->get_player_nr()] + 1) % gui_convoy_formation_t::CONVOY_OVERVIEW_MODES;
bt_mode_convois.set_text(gui_convoy_formation_t::cnvlist_mode_button_texts[selected_cnvlist_mode[player->get_player_nr()]]);
update_lineinfo(line);
}
else if(comp == &livery_selector)
{
sint32 livery_selection = livery_selector.get_selection();
if(livery_selection < 0)
{
livery_selector.set_selection(0);
livery_selection = 0;
}
livery_scheme_index = livery_scheme_indices.empty()? 0 : livery_scheme_indices[livery_selection];
if (line.is_bound())
{
tool_t *tmp_tool = create_tool( TOOL_CHANGE_LINE | SIMPLE_TOOL );
cbuffer_t buf;
buf.printf( "V,%i,%i", line.get_id(), livery_scheme_index );
tmp_tool->set_default_param(buf);
welt->set_tool( tmp_tool, player );
// since init always returns false, it is safe to delete immediately
delete tmp_tool;
}
}
else if (comp == &tabs) {
int const tab = tabs.get_active_tab_index();
uint8 old_selected_tab = selected_tab[player->get_player_nr()];
selected_tab[player->get_player_nr()] = tabs_to_lineindex[tab];
if( old_selected_tab == simline_t::line && selected_line[player->get_player_nr()][0].is_bound() && selected_line[player->get_player_nr()][0]->get_linetype() == selected_tab[player->get_player_nr()] ) {
// switching from general to same waytype tab while line is seletced => use current line instead
selected_line[player->get_player_nr()][selected_tab[player->get_player_nr()]] = selected_line[player->get_player_nr()][0];
}
update_lineinfo( selected_line[player->get_player_nr()][selected_tab[player->get_player_nr()]] );
build_line_list(tab);
if (tab>0) {
bt_new_line.enable( (welt->get_active_player() == player || player == welt->get_player(1)) && !welt->get_active_player()->is_locked() );
}
else {
bt_new_line.disable();
}
}
else if(comp == &info_tabs){
selected_convoy_tab = (uint8)info_tabs.get_active_tab_index();
if (selected_convoy_tab == 3) {
cont_haltlist.init();
}
}
else if (comp == &scl) {
if( line_scrollitem_t *li=(line_scrollitem_t *)scl.get_element(v.i) ) {
update_lineinfo( li->get_line() );
}
else {
// no valid line
update_lineinfo(linehandle_t());
}
selected_line[player->get_player_nr()][selected_tab[player->get_player_nr()]] = line;
selected_line[player->get_player_nr()][0] = line; // keep these the same in overview
}
else if (comp == &inp_filter) {
if( strcmp(old_schedule_filter,schedule_filter) ) {
build_line_list(tabs.get_active_tab_index());
strcpy(old_schedule_filter,schedule_filter);
}
}
else if (comp == &inp_name) {
rename_line();
}
else if (comp == &filter_btn_all_pas) {
line_type_flags ^= (1 << simline_t::all_pas);
filter_btn_all_pas.pressed = line_type_flags & (1 << simline_t::all_pas);
build_line_list(tabs.get_active_tab_index());
}
else if (comp == &filter_btn_all_mails) {
line_type_flags ^= (1 << simline_t::all_mail);
filter_btn_all_mails.pressed = line_type_flags & (1 << simline_t::all_mail);
build_line_list(tabs.get_active_tab_index());
}
else if (comp == &filter_btn_all_freights) {
line_type_flags ^= (1 << simline_t::all_freight);
filter_btn_all_freights.pressed = line_type_flags & (1 << simline_t::all_freight);
build_line_list(tabs.get_active_tab_index());
}
else if (comp == &bt_show_halt_name) {
bt_show_halt_name.pressed = !bt_show_halt_name.pressed;
cont_haltlist.set_show_name( bt_show_halt_name.pressed );
}
else {
if (line.is_bound()) {
for ( int i = 0; i<MAX_LINE_COST; i++) {
if (comp == &filterButtons[i]) {
bFilterStates ^= (1 << i);
if(bFilterStates & (1 << i)) {
chart.show_curve(i);
}
else {
chart.hide_curve(i);
}
break;
}
}
}
}
return true;
}
void schedule_list_gui_t::reset_line_name()
{
// change text input of selected line
if (line.is_bound()) {
tstrncpy(old_line_name, line->get_name(), sizeof(old_line_name));
tstrncpy(line_name, line->get_name(), sizeof(line_name));
inp_name.set_text(line_name, sizeof(line_name));
}
}
void schedule_list_gui_t::rename_line()
{
if (line.is_bound()
&& ((player == welt->get_active_player() && !welt->get_active_player()->is_locked()) || welt->get_active_player() == welt->get_public_player())) {
const char *t = inp_name.get_text();
// only change if old name and current name are the same
// otherwise some unintended undo if renaming would occur
if( t && t[0] && strcmp(t, line->get_name()) && strcmp(old_line_name, line->get_name())==0) {
// text changed => call tool
cbuffer_t buf;
buf.printf( "l%u,%s", line.get_id(), t );
tool_t *tmp_tool = create_tool( TOOL_RENAME | SIMPLE_TOOL );
tmp_tool->set_default_param( buf );
welt->set_tool( tmp_tool, line->get_owner() );
// since init always returns false, it is safe to delete immediately
delete tmp_tool;
// do not trigger this command again
tstrncpy(old_line_name, t, sizeof(old_line_name));
}
}
}
void schedule_list_gui_t::draw(scr_coord pos, scr_size size)
{
if( old_line_count != player->simlinemgmt.get_line_count() ) {
show_lineinfo( line );
}
if( old_player != welt->get_active_player() ) {
// deativate buttons, if not curretn player
old_player = welt->get_active_player();
const bool activate = (old_player == player || old_player == welt->get_player( 1 )) && !welt->get_active_player()->is_locked();
bt_delete_line.enable( activate );
bt_edit_line.enable( activate );
bt_new_line.enable( activate && tabs.get_active_tab_index() > 0);
bt_withdraw_line.set_visible( activate );
livery_selector.enable( activate );
}
// if search string changed, update line selection
if( strcmp( old_schedule_filter, schedule_filter ) ) {
build_line_list(tabs.get_active_tab_index());
strcpy( old_schedule_filter, schedule_filter );
}
gui_frame_t::draw(pos, size);
if( line.is_bound() ) {
if( (!line->get_schedule()->empty() && !line->get_schedule()->matches( welt, last_schedule )) || last_vehicle_count != line->count_convoys() || line->get_goods_catg_index().get_count() != line_goods_catg_count ) {
update_lineinfo( line );
}
// line type symbol
display_color_img(line->get_linetype_symbol(), pos.x + LINE_NAME_COLUMN_WIDTH -23, pos.y + D_TITLEBAR_HEIGHT + D_MARGIN_TOP - 42 + FIXED_SYMBOL_YOFF, 0, false, false);
PUSH_CLIP( pos.x + 1, pos.y + D_TITLEBAR_HEIGHT, size.w - 2, size.h - D_TITLEBAR_HEIGHT);
display(pos);
POP_CLIP();
}
for (int i = 0; i < MAX_LINE_COST; i++) {
filterButtons[i].pressed = ((bFilterStates & (1 << i)) != 0);
}
}
#define GOODS_SYMBOL_CELL_WIDTH 14 // TODO: This will be used in common with halt detail in the future
void schedule_list_gui_t::display(scr_coord pos)
{
uint32 icnv = line->count_convoys();
cbuffer_t buf;
char ctmp[128];
int top = D_TITLEBAR_HEIGHT + D_MARGIN_TOP + D_EDIT_HEIGHT + D_V_SPACE;
int left = LINE_NAME_COLUMN_WIDTH;
sint64 profit = line->get_finance_history(0,LINE_PROFIT);
uint32 line_total_vehicle_count=0;
for (uint32 i = 0; i<icnv; i++) {
convoihandle_t const cnv = line->get_convoy(i);
// we do not want to count the capacity of depot convois
if (!cnv->in_depot()) {
line_total_vehicle_count += cnv->get_vehicle_count();
}
}
if (last_schedule != line->get_schedule() && origin_halt.is_bound()) {
uint8 halt_symbol_style = gui_schedule_entry_number_t::halt;
lb_line_origin.buf().append(origin_halt->get_name());
if ((origin_halt->registered_lines.get_count() + origin_halt->registered_convoys.get_count()) > 1) {
halt_symbol_style = gui_schedule_entry_number_t::interchange;
}
halt_entry_origin.init(halt_entry_idx[0], origin_halt->get_owner()->get_player_color1(), halt_symbol_style, origin_halt->get_basis_pos3d());
if (destination_halt.is_bound()) {
halt_symbol_style = gui_schedule_entry_number_t::halt;
if ((destination_halt->registered_lines.get_count() + destination_halt->registered_convoys.get_count()) > 1) {
halt_symbol_style = gui_schedule_entry_number_t::interchange;
}
halt_entry_dest.init(halt_entry_idx[1], destination_halt->get_owner()->get_player_color1(), halt_symbol_style, destination_halt->get_basis_pos3d());
if (line->get_schedule()->is_mirrored()) {
routebar_middle.set_line_style(gui_colored_route_bar_t::doubled);
}
else {
routebar_middle.set_line_style(gui_colored_route_bar_t::downward);
}
lb_line_destination.buf().append(destination_halt->get_name());
lb_travel_distance.buf().printf("%s: %.1fkm ", translator::translate("travel_distance"), (float)(line->get_travel_distance()*world()->get_settings().get_meters_per_tile()/1000.0));
lb_travel_distance.update();
}
}
lb_line_origin.update();
lb_line_destination.update();
// convoy count
if (line->get_convoys().get_count()>1) {
lb_convoy_count.buf().printf(translator::translate("%d convois"), icnv);
}
else {
lb_convoy_count.buf().append(line->get_convoys().get_count() == 1 ? translator::translate("1 convoi") : translator::translate("no convois"));
}
if (icnv && line_total_vehicle_count>1) {
lb_convoy_count.buf().printf(translator::translate(", %d vehicles"), line_total_vehicle_count);
}
lb_convoy_count.update();
// Display service frequency
const sint64 service_frequency = line->get_service_frequency();
if(service_frequency)
{
char as_clock[32];
welt->sprintf_ticks(as_clock, sizeof(as_clock), service_frequency);
lb_service_frequency.buf().printf(" %s", as_clock);
lb_service_frequency.set_color(line->get_state() & simline_t::line_missing_scheduled_slots ? color_idx_to_rgb(COL_DARK_TURQUOISE) : SYSCOL_TEXT);
lb_service_frequency.set_tooltip(line->get_state() & simline_t::line_missing_scheduled_slots ? translator::translate(line_alert_helptexts[1]) : "");
}
else {
lb_service_frequency.buf().append("--:--");
}
lb_service_frequency.update();
int len2 = display_proportional_clip_rgb(pos.x+LINE_NAME_COLUMN_WIDTH, pos.y+top, translator::translate("Gewinn"), ALIGN_LEFT, SYSCOL_TEXT, true );
money_to_string(ctmp, profit/100.0);
len2 += display_proportional_clip_rgb(pos.x+LINE_NAME_COLUMN_WIDTH+len2+5, pos.y+top, ctmp, ALIGN_LEFT, profit>=0?MONEY_PLUS:MONEY_MINUS, true );
bt_line_class_manager.disable();
for (unsigned convoy = 0; convoy < line->count_convoys(); convoy++)
{
convoihandle_t cnv = line->get_convoy(convoy);
for (unsigned veh = 0; veh < cnv->get_vehicle_count(); veh++)
{
vehicle_t* v = cnv->get_vehicle(veh);
if (v->get_cargo_type()->get_catg_index() == goods_manager_t::INDEX_PAS || v->get_cargo_type()->get_catg_index() == goods_manager_t::INDEX_MAIL)
{
bt_line_class_manager.enable( (welt->get_active_player() == player || player == welt->get_player(1)) && !welt->get_active_player()->is_locked() );
}
}
}
top += D_BUTTON_HEIGHT + LINESPACE + 1;
left = LINE_NAME_COLUMN_WIDTH + D_BUTTON_WIDTH*1.5 + D_V_SPACE;
buf.clear();
// show the state of the line, if interresting
if (line->get_state() & simline_t::line_nothing_moved) {
if (skinverwaltung_t::alerts) {
display_color_img_with_tooltip(skinverwaltung_t::alerts->get_image_id(2), pos.x + left, pos.y + top + FIXED_SYMBOL_YOFF, 0, false, false, translator::translate(line_alert_helptexts[0]));
left += GOODS_SYMBOL_CELL_WIDTH;
}
else {
buf.append(translator::translate(line_alert_helptexts[0]));
}
}
if (line->count_convoys() && line->get_state() & simline_t::line_has_upgradeable_vehicles) {
if (skinverwaltung_t::upgradable) {
display_color_img_with_tooltip(skinverwaltung_t::upgradable->get_image_id(1), pos.x + left, pos.y + top + FIXED_SYMBOL_YOFF, 0, false, false, translator::translate(line_alert_helptexts[4]));
left += GOODS_SYMBOL_CELL_WIDTH;
}
else if (!buf.len() && line->get_state_color() == COL_PURPLE) {
buf.append(translator::translate(line_alert_helptexts[4]));
}
}
if (line->count_convoys() && line->get_state() & simline_t::line_has_obsolete_vehicles) {
if (skinverwaltung_t::alerts) {
display_color_img_with_tooltip(skinverwaltung_t::alerts->get_image_id(1), pos.x + left, pos.y + top + FIXED_SYMBOL_YOFF, 0, false, false, translator::translate(line_alert_helptexts[2]));
left += GOODS_SYMBOL_CELL_WIDTH;
}
else if (!buf.len()) {
buf.append(translator::translate(line_alert_helptexts[2]));
}
}
if (line->count_convoys() && line->get_state() & simline_t::line_overcrowded) {
if (skinverwaltung_t::pax_evaluation_icons) {
display_color_img_with_tooltip(skinverwaltung_t::pax_evaluation_icons->get_image_id(1), pos.x + left, pos.y + top + FIXED_SYMBOL_YOFF, 0, false, false, translator::translate(line_alert_helptexts[3]));
left += GOODS_SYMBOL_CELL_WIDTH;
}
else if (!buf.len() && line->get_state_color() == COL_DARK_PURPLE) {
buf.append(translator::translate(line_alert_helptexts[3]));
}
}
if (buf.len() > 0) {
display_proportional_clip_rgb(pos.x + left, pos.y + top, buf, ALIGN_LEFT, line->get_state_color(), true);
}
cont_line_info.set_size(cont_line_info.get_size());
}
void schedule_list_gui_t::set_windowsize(scr_size size)
{
gui_frame_t::set_windowsize(size);
int rest_width = get_windowsize().w-LINE_NAME_COLUMN_WIDTH;
int button_per_row=max(1,rest_width/(D_BUTTON_WIDTH+D_H_SPACE));
int button_rows= MAX_LINE_COST/button_per_row + ((MAX_LINE_COST%button_per_row)!=0);
scrolly_line_info.set_size( scr_size(LINE_NAME_COLUMN_WIDTH-4, get_client_windowsize().h - scrolly_line_info.get_pos().y-1) );
info_tabs.set_size( scr_size(rest_width+2, get_windowsize().h-info_tabs.get_pos().y-D_TITLEBAR_HEIGHT-1) );
scrolly_convois.set_size( scr_size(info_tabs.get_size().w+1, info_tabs.get_size().h - scrolly_convois.get_pos().y - D_H_SPACE-1) );
chart.set_size(scr_size(rest_width-68-D_MARGIN_RIGHT, SCL_HEIGHT-14-(button_rows*(D_BUTTON_HEIGHT+D_H_SPACE))));
inp_name.set_size(scr_size(rest_width - 31, D_EDIT_HEIGHT));
int y=SCL_HEIGHT-(button_rows*(D_BUTTON_HEIGHT+D_H_SPACE))+18;
for (int i=0; i<MAX_LINE_COST; i++) {
filterButtons[i].set_pos( scr_coord((i%button_per_row)*(D_BUTTON_WIDTH+D_H_SPACE)+D_H_SPACE, y+(i/button_per_row)*(D_BUTTON_HEIGHT+D_H_SPACE)) );
}
}
void schedule_list_gui_t::build_line_list(int selected_tab)
{
sint32 sel = -1;
scl.clear_elements();
player->simlinemgmt.get_lines(tabs_to_lineindex[selected_tab], &lines, get_filter_type_bits(), true);
FOR(vector_tpl<linehandle_t>, const l, lines) {
// search name
if( utf8caseutf8(l->get_name(), schedule_filter) ) {
scl.new_component<line_scrollitem_t>(l);
if ( line == l ) {
sel = scl.get_count() - 1;
}
}
}
scl.set_selection( sel );
line_scrollitem_t::sort_mode = (line_scrollitem_t::sort_modes_t)current_sort_mode;
scl.sort( 0 );
scl.set_size(scl.get_size());
old_line_count = player->simlinemgmt.get_line_count();
}
/* hides show components */
void schedule_list_gui_t::update_lineinfo(linehandle_t new_line)
{
// change line name if necessary
if (line.is_bound()) {
rename_line();
}
if(new_line.is_bound()) {
const bool activate = (old_player == player || old_player == welt->get_player(1)) && !welt->get_active_player()->is_locked();
// ok, this line is visible
scrolly_convois.set_visible(true);
scrolly_haltestellen.set_visible(true);
scrolly_line_info.set_visible(new_line->get_schedule()->get_count()>0);
inp_name.set_visible(true);
livery_selector.set_visible(true);
cont_line_capacity_by_catg.set_line(new_line);
cont_times_history.set_visible(true);
cont_times_history.remove_all();
cont_times_history.new_component<gui_times_history_t>(new_line, convoihandle_t(), false);
if (!new_line->get_schedule()->is_mirrored()) {
cont_times_history.new_component<gui_times_history_t>(new_line, convoihandle_t(), true);
}
cont_haltlist.set_visible(true);
cont_haltlist.set_line(new_line);
resize(scr_size(0,0));
livery_selector.set_visible(true);
// fill container with info of line's convoys
// we do it here, since this list needs only to be
// refreshed when the user selects a new line
line_convoys.clear();
line_convoys = new_line->get_convoys();
sort_list();
uint32 i, icnv = 0;
line_goods_catg_count = new_line->get_goods_catg_index().get_count();
icnv = new_line->count_convoys();
// display convoys of line
cont.remove_all();
while (!convoy_infos.empty()) {
delete convoy_infos.pop_back();
}
convoy_infos.resize(icnv);
scr_coord_val ypos = 0;
for(i = 0; i<icnv; i++ ) {
gui_convoiinfo_t* const cinfo = new gui_convoiinfo_t(line_convoys.get_element(i), false);
cinfo->set_pos(scr_coord(0, ypos-D_MARGIN_TOP));
scr_size csize = cinfo->get_min_size();
cinfo->set_size(scr_size(400, csize.h-D_MARGINS_Y));
cinfo->set_mode(selected_cnvlist_mode[player->get_player_nr()]);
cinfo->set_switchable_label(sortby);
convoy_infos.append(cinfo);
cont.add_component(cinfo);
ypos += csize.h - D_MARGIN_TOP-D_V_SPACE*2;
}
cont.set_size(scr_size(600, ypos));
bt_delete_line.disable();
bt_withdraw_line.set_visible(false);
if( icnv>0 ) {
bt_withdraw_line.set_visible(true);
}
else {
bt_delete_line.enable( activate );
}
bt_edit_line.enable( activate );
bt_withdraw_line.pressed = new_line->get_withdraw();
bt_withdraw_line.background_color = color_idx_to_rgb( bt_withdraw_line.pressed ? COL_DARK_YELLOW-1 : COL_YELLOW );
bt_withdraw_line.text_color = color_idx_to_rgb(bt_withdraw_line.pressed ? COL_WHITE : COL_BLACK);
livery_selector.set_focusable(true);
livery_selector.clear_elements();
livery_scheme_indices.clear();
if( icnv>0 ) {
// build available livery schemes list for this line
if (new_line->count_convoys()) {
const uint16 month_now = welt->get_timeline_year_month();
vector_tpl<livery_scheme_t*>* schemes = welt->get_settings().get_livery_schemes();
ITERATE_PTR(schemes, i)
{
bool found = false;
livery_scheme_t* scheme = schemes->get_element(i);
if (scheme->is_available(month_now))
{
for (uint32 j = 0; j < new_line->count_convoys(); j++)
{
convoihandle_t const cnv_in_line = new_line->get_convoy(j);
for (int k = 0; k < cnv_in_line->get_vehicle_count(); k++) {
const vehicle_desc_t *desc = cnv_in_line->get_vehicle(k)->get_desc();
if (desc->get_livery_count()) {
const char* test_livery = scheme->get_latest_available_livery(month_now, desc);
if (test_livery) {
if (scheme->is_contained(test_livery, month_now)) {
livery_selector.new_component<gui_scrolled_list_t::const_text_scrollitem_t>(translator::translate(scheme->get_name()), SYSCOL_TEXT);
livery_scheme_indices.append(i);
found = true;
break;
}
}
}
}
if (found) {
livery_selector.set_selection(livery_scheme_indices.index_of(i));
break;
}
}
}
}
}
}
if(livery_scheme_indices.empty()) {
livery_selector.new_component<gui_scrolled_list_t::const_text_scrollitem_t>(translator::translate("No livery"), SYSCOL_TEXT);
livery_selector.set_selection(0);
}
uint8 entry_idx = 0;
halt_entry_idx[0] = 255;
halt_entry_idx[1] = 255;
origin_halt = halthandle_t();
destination_halt = halthandle_t();
FORX(minivec_tpl<schedule_entry_t>, const& i, new_line->get_schedule()->entries, ++entry_idx) {
halthandle_t const halt = haltestelle_t::get_halt(i.pos, player);
if (halt.is_bound()) {
if (halt_entry_idx[0] == 255) {
halt_entry_idx[0] = entry_idx;
origin_halt = halt;
}
else {
halt_entry_idx[1] = entry_idx;
destination_halt = halt;
}
}
}
// chart
chart.remove_curves();
for(i=0; i<MAX_LINE_COST; i++) {
chart.add_curve(color_idx_to_rgb(cost_type_color[i]), new_line->get_finance_history(), MAX_LINE_COST, statistic[i], MAX_MONTHS, statistic_type[i], filterButtons[i].pressed, true, statistic_type[i]*2 );
if (bFilterStates & (1 << i)) {
chart.show_curve(i);
}
}
chart.set_visible(true);
// has this line a single running convoi?
if( new_line.is_bound() && new_line->count_convoys() > 0 ) {
// set this schedule as current to show on minimap if possible
minimap_t::get_instance()->set_selected_cnv( new_line->get_convoy(0) );
}
else {
minimap_t::get_instance()->set_selected_cnv( convoihandle_t() );
}
delete last_schedule;
last_schedule = new_line->get_schedule()->copy();
last_vehicle_count = new_line->count_convoys();
}
else if( inp_name.is_visible() ) {
// previously a line was visible
// thus the need to hide everything
line_convoys.clear();
cont.remove_all();
cont_times_history.remove_all();
cont_line_capacity_by_catg.set_line(linehandle_t());
scrolly_convois.set_visible(false);
scrolly_haltestellen.set_visible(false);
livery_selector.set_visible(false);
scrolly_line_info.set_visible(false);
inp_name.set_visible(false);
cont_times_history.set_visible(false);
cont_haltlist.set_visible(false);
scl.set_selection(-1);
bt_delete_line.disable();
bt_edit_line.disable();
for(int i=0; i<MAX_LINE_COST; i++) {
chart.hide_curve(i);
}
chart.set_visible(true);
// hide schedule on minimap (may not current, but for safe)
minimap_t::get_instance()->set_selected_cnv( convoihandle_t() );
delete last_schedule;
last_schedule = NULL;
last_vehicle_count = 0;
}
line = new_line;
bt_line_class_manager.set_visible(line.is_bound());
reset_line_name();
}
void schedule_list_gui_t::show_lineinfo(linehandle_t line)
{
update_lineinfo(line);
if( line.is_bound() ) {
// rebuilding line list will also show selection
for( uint8 i=0; i<max_idx; i++ ) {
if( tabs_to_lineindex[i]==line->get_linetype() ) {
tabs.set_active_tab_index( i );
build_line_list( i );
break;
}
}
}
}
bool schedule_list_gui_t::compare_convois(convoihandle_t const cnv1, convoihandle_t const cnv2)
{
sint32 cmp = 0;
switch (sortby) {
default:
case by_name:
cmp = strcmp(cnv1->get_internal_name(), cnv2->get_internal_name());
break;
case by_schedule:
cmp = cnv1->get_schedule()->get_current_stop() - cnv2->get_schedule()->get_current_stop();
break;
case by_profit:
cmp = sgn(cnv1->get_jahresgewinn() - cnv2->get_jahresgewinn());
break;
case by_loading_lvl:
cmp = cnv1->get_loading_level() - cnv2->get_loading_level();
break;
case by_max_speed:
cmp = cnv1->get_min_top_speed() - cnv2->get_min_top_speed();
break;
case by_power:
cmp = cnv1->get_sum_power() - cnv2->get_sum_power();
break;
case by_age:
cmp = cnv1->get_average_age() - cnv2->get_average_age();
break;
case by_value:
cmp = sgn(cnv1->get_purchase_cost() - cnv2->get_purchase_cost());
break;
}
return sortreverse ? cmp > 0 : cmp < 0;
}
// sort the line convoy list
void schedule_list_gui_t::sort_list()
{
if (!line_convoys.get_count()) {
return;
}
std::sort(line_convoys.begin(), line_convoys.end(), compare_convois);
}
void schedule_list_gui_t::update_data(linehandle_t changed_line)
{
if (changed_line.is_bound()) {
const uint16 i = tabs.get_active_tab_index();
if (tabs_to_lineindex[i] == simline_t::line || tabs_to_lineindex[i] == changed_line->get_linetype()) {
// rebuilds the line list, but does not change selection
build_line_list(i);
}
// change text input of selected line
if (changed_line.get_id() == line.get_id()) {
reset_line_name();
}
}
}
uint32 schedule_list_gui_t::get_rdwr_id()
{
return magic_line_management_t+player->get_player_nr();
}
void schedule_list_gui_t::rdwr( loadsave_t *file )
{
scr_size size;
sint32 cont_xoff, cont_yoff, halt_xoff, halt_yoff;
if( file->is_saving() ) {
size = get_windowsize();
cont_xoff = scrolly_convois.get_scroll_x();
cont_yoff = scrolly_convois.get_scroll_y();
halt_xoff = scrolly_haltestellen.get_scroll_x();
halt_yoff = scrolly_haltestellen.get_scroll_y();
}
size.rdwr( file );
simline_t::rdwr_linehandle_t(file, line);
int chart_records = line_cost_t::MAX_LINE_COST;
if( file->is_version_less(112, 8) ) {
chart_records = 8;
}
else if (file->get_extended_version() < 14 || (file->get_extended_version() == 14 && file->get_extended_revision() < 25)) {
chart_records = 12;
}
for (int i=0; i<chart_records; i++) {
bool b = filterButtons[i].pressed;
file->rdwr_bool( b );
filterButtons[i].pressed = b;
}
file->rdwr_long( cont_xoff );
file->rdwr_long( cont_yoff );
file->rdwr_long( halt_xoff );
file->rdwr_long( halt_yoff );
// open dialogue
if( file->is_loading() ) {
show_lineinfo( line );
set_windowsize( size );
resize( scr_coord(0,0) );
scrolly_convois.set_scroll_position( cont_xoff, cont_yoff );
scrolly_haltestellen.set_scroll_position( halt_xoff, halt_yoff );
}
}
| 35.580404 | 223 | 0.734817 | chris-nada |
514096aea2ce9eddf1faef3485127c8c1036afd6 | 10,698 | cc | C++ | chrome/browser/android/explore_sites/explore_sites_fetcher.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | chrome/browser/android/explore_sites/explore_sites_fetcher.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | chrome/browser/android/explore_sites/explore_sites_fetcher.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/android/explore_sites/explore_sites_fetcher.h"
#include <string>
#include <utility>
#include "base/bind.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/metrics/field_trial_params.h"
#include "base/metrics/histogram_functions.h"
#include "base/strings/stringprintf.h"
#include "base/values.h"
#include "base/version.h"
#include "chrome/browser/android/explore_sites/catalog.pb.h"
#include "chrome/browser/android/explore_sites/explore_sites_bridge.h"
#include "chrome/browser/android/explore_sites/explore_sites_feature.h"
#include "chrome/browser/android/explore_sites/explore_sites_types.h"
#include "chrome/browser/android/explore_sites/url_util.h"
#include "chrome/browser/flags/android/chrome_feature_list.h"
#include "chrome/common/channel_info.h"
#include "components/version_info/version_info.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/storage_partition.h"
#include "google_apis/google_api_keys.h"
#include "net/base/load_flags.h"
#include "net/base/url_util.h"
#include "net/http/http_request_headers.h"
#include "net/http/http_status_code.h"
#include "net/traffic_annotation/network_traffic_annotation.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/cpp/simple_url_loader.h"
#include "services/network/public/mojom/url_response_head.mojom.h"
#include "url/gurl.h"
namespace explore_sites {
namespace {
// Content type needed in order to communicate with the server in binary
// proto format.
const char kRequestContentType[] = "application/x-protobuf";
const char kRequestMethod[] = "GET";
constexpr net::NetworkTrafficAnnotationTag traffic_annotation =
net::DefineNetworkTrafficAnnotation("explore_sites", R"(
semantics {
sender: "Explore Sites"
description:
"Downloads a catalog of categories and sites for the purposes of "
"exploring the Web."
trigger:
"Periodically scheduled for update in the background and also "
"triggered by New Tab Page UI."
data:
"Proto data comprising interesting site and category information."
" No user information is sent."
destination: GOOGLE_OWNED_SERVICE
}
policy {
cookies_allowed: NO
policy_exception_justification:
"TODO(crbug.com/1231780): Add this field."
})");
} // namespace
const net::BackoffEntry::Policy
ExploreSitesFetcher::kImmediateFetchBackoffPolicy = {
0, // Number of initial errors to ignore without backoff.
1 * 1000, // Initial delay for backoff in ms: 1 second.
2, // Factor to multiply for exponential backoff.
0, // Fuzzing percentage.
4 * 1000, // Maximum time to delay requests in ms: 4 seconds.
-1, // Don't discard entry even if unused.
false // Don't use initial delay unless the last was an error.
};
const int ExploreSitesFetcher::kMaxFailureCountForImmediateFetch = 3;
const net::BackoffEntry::Policy
ExploreSitesFetcher::kBackgroundFetchBackoffPolicy = {
0, // Number of initial errors to ignore without backoff.
5 * 1000, // Initial delay for backoff in ms: 5 seconds.
2, // Factor to multiply for exponential backoff.
0, // Fuzzing percentage.
320 * 1000, // Maximum time to delay requests in ms: 320 seconds.
-1, // Don't discard entry even if unused.
false // Don't use initial delay unless the last was an error.
};
const int ExploreSitesFetcher::kMaxFailureCountForBackgroundFetch = 2;
// static
std::unique_ptr<ExploreSitesFetcher> ExploreSitesFetcher::CreateForGetCatalog(
bool is_immediate_fetch,
const std::string& catalog_version,
const std::string& accept_languages,
const std::string& country_code,
scoped_refptr<network::SharedURLLoaderFactory> loader_factory,
Callback callback) {
GURL url = GetCatalogURL();
return base::WrapUnique(new ExploreSitesFetcher(
is_immediate_fetch, url, catalog_version, accept_languages, country_code,
loader_factory, std::move(callback)));
}
ExploreSitesFetcher::ExploreSitesFetcher(
bool is_immediate_fetch,
const GURL& url,
const std::string& catalog_version,
const std::string& accept_languages,
const std::string& country_code,
scoped_refptr<network::SharedURLLoaderFactory> loader_factory,
Callback callback)
: is_immediate_fetch_(is_immediate_fetch),
accept_languages_(accept_languages),
country_code_(country_code),
catalog_version_(catalog_version),
url_(url),
device_delegate_(std::make_unique<DeviceDelegate>()),
callback_(std::move(callback)),
url_loader_factory_(loader_factory) {
base::Version version = version_info::GetVersion();
std::string channel_name =
chrome::GetChannelName(chrome::WithExtendedStable(true));
client_version_ = base::StringPrintf("%d.%d.%d.%s.chrome",
version.components()[0], // Major
version.components()[2], // Build
version.components()[3], // Patch
channel_name.c_str());
UpdateBackoffEntry();
}
ExploreSitesFetcher::~ExploreSitesFetcher() {}
void ExploreSitesFetcher::Start() {
auto resource_request = std::make_unique<network::ResourceRequest>();
GURL request_url =
net::AppendOrReplaceQueryParameter(url_, "country_code", country_code_);
request_url = net::AppendOrReplaceQueryParameter(request_url, "version_token",
catalog_version_);
resource_request->url = request_url;
resource_request->method = kRequestMethod;
bool is_stable_channel =
chrome::GetChannel() == version_info::Channel::STABLE;
std::string api_key = is_stable_channel ? google_apis::GetAPIKey()
: google_apis::GetNonStableAPIKey();
resource_request->headers.SetHeader("x-goog-api-key", api_key);
resource_request->headers.SetHeader("X-Client-Version", client_version_);
resource_request->headers.SetHeader(net::HttpRequestHeaders::kContentType,
kRequestContentType);
std::string scale_factor =
std::to_string(device_delegate_->GetScaleFactorFromDevice());
resource_request->headers.SetHeader("X-Device-Scale-Factor", scale_factor);
if (!accept_languages_.empty()) {
resource_request->headers.SetHeader(
net::HttpRequestHeaders::kAcceptLanguage, accept_languages_);
}
// Get field trial value, if any.
std::string tag = base::GetFieldTrialParamValueByFeature(
chrome::android::kExploreSites,
chrome::android::explore_sites::
kExploreSitesHeadersExperimentParameterName);
if (!tag.empty()) {
resource_request->headers.SetHeader("X-Goog-Chrome-Experiment-Tag", tag);
}
url_loader_ = network::SimpleURLLoader::Create(std::move(resource_request),
traffic_annotation);
url_loader_->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
url_loader_factory_.get(),
base::BindOnce(&ExploreSitesFetcher::OnSimpleLoaderComplete,
weak_factory_.GetWeakPtr()));
}
float ExploreSitesFetcher::DeviceDelegate::GetScaleFactorFromDevice() {
return ExploreSitesBridge::GetScaleFactorFromDevice();
}
void ExploreSitesFetcher::SetDeviceDelegateForTest(
std::unique_ptr<ExploreSitesFetcher::DeviceDelegate> device_delegate) {
device_delegate_ = std::move(device_delegate);
}
void ExploreSitesFetcher::RestartAsImmediateFetchIfNotYet() {
if (is_immediate_fetch_)
return;
is_immediate_fetch_ = true;
UpdateBackoffEntry();
url_loader_.reset();
Start();
}
void ExploreSitesFetcher::OnSimpleLoaderComplete(
std::unique_ptr<std::string> response_body) {
ExploreSitesRequestStatus status = HandleResponseCode();
if (response_body && response_body->empty()) {
DVLOG(1) << "Failed to get response or empty response";
status = ExploreSitesRequestStatus::kFailure;
}
if (status == ExploreSitesRequestStatus::kFailure &&
!disable_retry_for_testing_) {
RetryWithBackoff();
return;
}
std::move(callback_).Run(status, std::move(response_body));
}
ExploreSitesRequestStatus ExploreSitesFetcher::HandleResponseCode() {
int response_code = -1;
int net_error = url_loader_->NetError();
base::UmaHistogramSparse("ExploreSites.FetcherNetErrorCode", -net_error);
if (url_loader_->ResponseInfo() && url_loader_->ResponseInfo()->headers)
response_code = url_loader_->ResponseInfo()->headers->response_code();
if (response_code == -1) {
DVLOG(1) << "Net error: " << net_error;
return (net_error == net::ERR_BLOCKED_BY_ADMINISTRATOR)
? ExploreSitesRequestStatus::kShouldSuspendBlockedByAdministrator
: ExploreSitesRequestStatus::kFailure;
}
base::UmaHistogramSparse("ExploreSites.FetcherHttpResponseCode",
response_code);
if (response_code < 200 || response_code > 299) {
DVLOG(1) << "HTTP status: " << response_code;
switch (response_code) {
case net::HTTP_BAD_REQUEST:
return ExploreSitesRequestStatus::kShouldSuspendBadRequest;
default:
return ExploreSitesRequestStatus::kFailure;
}
}
return ExploreSitesRequestStatus::kSuccess;
}
void ExploreSitesFetcher::RetryWithBackoff() {
backoff_entry_->InformOfRequest(false);
if (backoff_entry_->failure_count() >= max_failure_count_) {
std::move(callback_).Run(ExploreSitesRequestStatus::kFailure,
std::unique_ptr<std::string>());
return;
}
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::BindOnce(&ExploreSitesFetcher::Start, weak_factory_.GetWeakPtr()),
backoff_entry_->GetTimeUntilRelease());
}
void ExploreSitesFetcher::UpdateBackoffEntry() {
backoff_entry_ = std::make_unique<net::BackoffEntry>(
is_immediate_fetch_ ? &kImmediateFetchBackoffPolicy
: &kBackgroundFetchBackoffPolicy);
max_failure_count_ = is_immediate_fetch_ ? kMaxFailureCountForImmediateFetch
: kMaxFailureCountForBackgroundFetch;
}
} // namespace explore_sites
| 39.043796 | 80 | 0.697046 | zealoussnow |
51416c8e10df51850d6fb404a2ba6e0e0dff40c8 | 395 | cpp | C++ | engine/generators/settlements/sector/source/SectorFeature.cpp | sidav/shadow-of-the-wyrm | 747afdeebed885b1a4f7ab42f04f9f756afd3e52 | [
"MIT"
] | 60 | 2019-08-21T04:08:41.000Z | 2022-03-10T13:48:04.000Z | engine/generators/settlements/sector/source/SectorFeature.cpp | cleancoindev/shadow-of-the-wyrm | 51b23e98285ecb8336324bfd41ebf00f67b30389 | [
"MIT"
] | 3 | 2021-03-18T15:11:14.000Z | 2021-10-20T12:13:07.000Z | engine/generators/settlements/sector/source/SectorFeature.cpp | cleancoindev/shadow-of-the-wyrm | 51b23e98285ecb8336324bfd41ebf00f67b30389 | [
"MIT"
] | 8 | 2019-11-16T06:29:05.000Z | 2022-01-23T17:33:43.000Z | #include "SectorFeature.hpp"
#include "CoordUtils.hpp"
using namespace std;
bool SectorFeature::generate(MapPtr map, const Coordinate& start_coord, const Coordinate& end_coord)
{
bool generated = false;
if (map && CoordUtils::is_in_range(map->size(), start_coord, end_coord))
{
generated = generate_feature(map, start_coord, end_coord);
}
return generated;
}
| 21.944444 | 101 | 0.703797 | sidav |
5143ffaee250fada2155680e07a710901a7e2add | 9,281 | cpp | C++ | interpreter/lexer.cpp | kmc-jp/icfpc-2020 | 5bff55fe16bc2fc79e74601c6cb18ee1466beaf8 | [
"MIT"
] | null | null | null | interpreter/lexer.cpp | kmc-jp/icfpc-2020 | 5bff55fe16bc2fc79e74601c6cb18ee1466beaf8 | [
"MIT"
] | null | null | null | interpreter/lexer.cpp | kmc-jp/icfpc-2020 | 5bff55fe16bc2fc79e74601c6cb18ee1466beaf8 | [
"MIT"
] | null | null | null | #include "lexer.hpp"
void skip_spaces(std::string const& in, int& pos) {
while(pos < (int)in.size() && in[pos] == ' ') ++pos;
}
void skip_spaces(std::vector<std::string> const& in, int& x) {
while(x < (int)in[0].size()) {
bool all_space = true;
for(int y = 0; y < (int)in.size(); ++y) {
all_space &= in[y][x] == '0';
}
if(!all_space) break;
++x;
}
}
auto trim_input(std::vector<std::string> const& in) {
int x = 0;
std::vector<std::vector<std::string>> res;
while(true) {
skip_spaces(in, x);
if(x == (int)in[0].size()) break;
std::vector<std::string> tmp(in.size());
// scanning
while(x < (int)in[0].size()) {
bool exists_one = false;
for(int y = 0; y < (int)in.size(); ++y) {
exists_one |= in[y][x] == '1';
}
if(!exists_one) break;
for(int y = 0; y < (int)in.size(); ++y) {
tmp[y].push_back(in[y][x]);
}
++x;
}
// trim top/bottom
tmp.erase(std::remove_if(tmp.begin(), tmp.end(),
[] (auto const& s) { return s.find_first_of('1') == std::string::npos; }),
tmp.end());
res.push_back(std::move(tmp));
}
return res;
}
Token dict_operator(const ll id) {
if(id == 0) return app;
if(id == 1) return {TokenType::I, 0};
if(id == 2) return {TokenType::True, 0};
if(id == 5) return comb_b;
if(id == 6) return comb_c;
if(id == 7) return {TokenType::S, 0};
if(id == 8) return {TokenType::False, 0};
if(id == 10) return {TokenType::Negate, 0};
if(id == 12) return {TokenType::Equality, 0};
if(id == 14) return nil;
if(id == 15) return {TokenType::IsNil, 0};
if(id == 40) return {TokenType::Division, 0};
if(id == 146) return {TokenType::Product, 0};
if(id == 170) return {TokenType::Modulate, 0};
if(id == 174) return {TokenType::Send, 0};
if(id == 341) return {TokenType::Demod, 0};
if(id == 365) return sum;
if(id == 401) return {TokenType::Pred, 0};
if(id == 416) return {TokenType::Lt, 0};
if(id == 417) return {TokenType::Succ, 0};
if(id == 448) return {TokenType::Eq, 0};
if(id == 64170) return cons;
if(id == 64171) return {TokenType::Cdr, 0};
if(id == 64174) return {TokenType::Car, 0};
if(id == 17043521) return cons;
throw std::runtime_error("dict_operator: not supported " + std::to_string(id));
}
ll calc_number_part(std::vector<std::string> const& symbol) {
const int n = std::min(symbol.size(), symbol[0].size()) - 1;
ll res = 0;
for(int y = 0; y < n; ++y) {
for(int x = 0; x < n; ++x) {
if(symbol[y + 1][x + 1] == '1') {
res += 1LL << (y * n + x);
}
}
}
return res;
}
ll calc_var_number_part(std::vector<std::string> const& symbol) {
assert(symbol.size() == symbol[0].size());
const int n = symbol.size();
ll res = 0;
for(int y = 0; y < n - 3; ++y) {
for(int x = 0; x < n - 3; ++x) {
if(symbol[y + 2][x + 2] == '0') {
res += 1LL << (y * (n - 3) + x);
}
}
}
return res;
}
bool is_lparen(std::vector<std::string> const& symbol) {
if(symbol.size() != 5u || symbol[0].size() != 3u) return false;
bool res = true;
for(int x = 0; x < 3; ++x) {
for(int y = 2 - x; y <= 2 + x; ++y) {
res &= symbol[y][x] == '1';
}
}
return res;
}
bool is_rparen(std::vector<std::string> const& symbol) {
if(symbol.size() != 5u || symbol[0].size() != 3u) return false;
bool res = true;
for(int x = 0; x < 3; ++x) {
for(int y = x; y <= 4 - x; ++y) {
res &= symbol[y][x] == '1';
}
}
return res;
}
bool is_list_sep(std::vector<std::string> const& symbol) {
if(symbol.size() != 5u || symbol[0].size() != 2u) return false;
bool res = true;
for(auto const& s : symbol) {
for(auto const c : s) {
res &= c == '1';
}
}
return res;
}
bool is_variable(std::vector<std::string> const& symbol) {
if(symbol.size() != symbol[0].size()) return false;
if(symbol.size() < 4u) return false;
if(symbol[1][1] == '0') return false;
const int n = symbol.size();
for(int i = 2; i < n - 1; ++i) {
if(symbol[1][i] == '1' || symbol[i][1] == '1') return false;
}
bool res = true;
for(int i = 0; i < n; ++i) {
res &= symbol[0][i] == '1' && symbol[i][0] == '1' && symbol[n - 1][i] == '1' && symbol[i][n - 1] == '1';
}
return res;
}
Token tokenize_one(std::vector<std::string> const& symbol) {
if(is_lparen(symbol)) {
throw std::runtime_error("tokenize_one: not implemented lparen");
} else if(is_rparen(symbol)) {
throw std::runtime_error("tokenize_one: not implemented rparen");
} else if(is_list_sep(symbol)) {
throw std::runtime_error("tokenize_one: not implemented list_sep");
} else if(is_variable(symbol)) {
const ll id = calc_var_number_part(symbol);
std::cout << ("x" + std::to_string(id)) << std::endl;
//throw std::runtime_error("not supported");
} else if(symbol[0][0] == '0') { // number
const ll num = calc_number_part(symbol);
if(symbol.size() == symbol[0].size()) { // positive
return number(num);
} else {
return number(-num);
}
} else if(symbol[0][0] == '1') { // operator
return dict_operator(calc_number_part(symbol));
}
throw std::runtime_error("tokenize_one: not implmented");
}
std::vector<Token> tokenize(std::vector<std::string> const& input) {
std::vector<Token> res;
for(auto&& v : trim_input(input)) {
res.push_back(tokenize_one(std::move(v)));
}
return res;
}
bool is_number(std::string const& s) {
bool res = true;
for(int i = s[0] == '-'; i < (int)s.size(); ++i) {
res &= (bool)isdigit(s[i]);
}
return res;
}
// require: all tokens are separated by spaces
std::vector<Token> tokenize(std::string const& input) {
std::vector<Token> res;
std::string cur;
int pos = 0;
while(true) {
skip_spaces(input, pos);
if(pos >= (int)input.size()) return res;
while(pos < (int)input.size() && input[pos] != ' ') cur += input[pos++];
if(cur == "ap") res.push_back(app);
else if(cur[0] == ':') res.push_back({TokenType::Variable, std::stoll(cur.substr(1))}); // todo
else if(is_number(cur)) res.push_back(number(std::stoll(cur)));
else if(cur == "inc") res.push_back({TokenType::Succ, 0});
else if(cur == "dec") res.push_back({TokenType::Pred, 0});
else if(cur == "add") res.push_back(sum);
else if(cur == "=") res.push_back({TokenType::Equality, 0});
else if(cur[0] == 'x') res.push_back({TokenType::Variable, std::stoll(cur.substr(1))});
else if(cur == "mul") res.push_back({TokenType::Product, 0});
else if(cur == "div") res.push_back({TokenType::Division, 0});
else if(cur == "eq") res.push_back({TokenType::Eq, 0});
else if(cur == "lt") res.push_back({TokenType::Lt, 0});
else if(cur == "mod") res.push_back({TokenType::Modulate, 0});
else if(cur == "dem") res.push_back({TokenType::Demod, 0});
else if(cur == "send") res.push_back({TokenType::Send, 0});
else if(cur == "neg") res.push_back({TokenType::Negate, 0});
else if(cur == "s") res.push_back({TokenType::S, 0});
else if(cur == "c") res.push_back({TokenType::C, 0});
else if(cur == "b") res.push_back({TokenType::B, 0});
else if(cur == "t") res.push_back({TokenType::True, 0});
else if(cur == "f") res.push_back({TokenType::False, 0});
else if(cur == "i") res.push_back({TokenType::I, 0});
else if(cur == "pwr2") res.push_back({TokenType::Pwr2, 0}); // ???
else if(cur == "cons") res.push_back(cons);
else if(cur == "car") res.push_back({TokenType::Car, 0});
else if(cur == "cdr") res.push_back({TokenType::Cdr, 0});
else if(cur == "nil") res.push_back(nil);
else if(cur == "isnil") res.push_back({TokenType::IsNil, 0});
else if(cur == "(") throw std::runtime_error("not implemented");
else if(cur == ",") throw std::runtime_error("not implemented");
else if(cur == ")") throw std::runtime_error("not implemented");
else if(cur == "vec") res.push_back(cons);
else if(cur == "draw") throw std::runtime_error("not implemented draw");
else if(cur == "interact") throw std::runtime_error("not implemented: interact");
else throw std::runtime_error("error lexing: " + cur);
cur.clear();
}
}
| 38.35124 | 113 | 0.504579 | kmc-jp |
51462164b90de054864b36b9771f835aacfdc382 | 196 | hpp | C++ | src/fwd/sln.hpp | PiotrOstrow/eoserv | 73253dcc711368a94942b0cfab86f3d42b88b999 | [
"Zlib"
] | 21 | 2020-01-22T10:42:26.000Z | 2022-02-15T19:45:43.000Z | src/fwd/sln.hpp | eoserv/mainclone-eoserv | e18e87f169140b6c0da80b9d866f672e8f6dced5 | [
"Zlib"
] | 12 | 2019-12-10T21:47:57.000Z | 2020-11-06T06:01:52.000Z | src/fwd/sln.hpp | eoserv/mainclone-eoserv | e18e87f169140b6c0da80b9d866f672e8f6dced5 | [
"Zlib"
] | 11 | 2020-04-01T21:46:07.000Z | 2022-03-07T10:50:43.000Z |
/* $Id$
* EOSERV is released under the zlib license.
* See LICENSE.txt for more info.
*/
#ifndef FWD_SLN_HPP_INCLUDED
#define FWD_SLN_HPP_INCLUDED
class SLN;
#endif // FWD_SLN_HPP_INCLUDED
| 15.076923 | 45 | 0.744898 | PiotrOstrow |
5146f18a203e00e16d60dc73391b8ce36cadcdd8 | 3,606 | cpp | C++ | Project/zoolib/ValPred/Expr_Bool_ValPred.cpp | ElectricMagic/zoolib_cxx | cb3ccfde931b3989cd420fa093153204a7899805 | [
"MIT"
] | 13 | 2015-01-28T21:05:09.000Z | 2021-11-03T22:21:11.000Z | Project/zoolib/ValPred/Expr_Bool_ValPred.cpp | ElectricMagic/zoolib_cxx | cb3ccfde931b3989cd420fa093153204a7899805 | [
"MIT"
] | null | null | null | Project/zoolib/ValPred/Expr_Bool_ValPred.cpp | ElectricMagic/zoolib_cxx | cb3ccfde931b3989cd420fa093153204a7899805 | [
"MIT"
] | 4 | 2018-11-16T08:33:33.000Z | 2021-12-11T19:40:46.000Z | // Copyright (c) 2011 Andrew Green. MIT License. http://www.zoolib.org
#include "zoolib/ValPred/Expr_Bool_ValPred.h"
namespace ZooLib {
// =================================================================================================
#pragma mark - Expr_Bool_ValPred
Expr_Bool_ValPred::Expr_Bool_ValPred(const ValPred& iValPred)
: fValPred(iValPred)
{}
Expr_Bool_ValPred::~Expr_Bool_ValPred()
{}
void Expr_Bool_ValPred::Accept(const Visitor& iVisitor)
{
if (Visitor_Expr_Bool_ValPred* theVisitor = sDynNonConst<Visitor_Expr_Bool_ValPred>(&iVisitor))
this->Accept_Expr_Bool_ValPred(*theVisitor);
else
inherited::Accept(iVisitor);
}
void Expr_Bool_ValPred::Accept_Expr_Op0(Visitor_Expr_Op0_T<Expr_Bool>& iVisitor)
{
if (Visitor_Expr_Bool_ValPred* theVisitor = sDynNonConst<Visitor_Expr_Bool_ValPred>(&iVisitor))
this->Accept_Expr_Bool_ValPred(*theVisitor);
else
inherited::Accept_Expr_Op0(iVisitor);
}
int Expr_Bool_ValPred::Compare(const ZP<Expr>& iOther)
{
if (ZP<Expr_Bool_ValPred> other = iOther.DynamicCast<Expr_Bool_ValPred>())
return sCompare_T(this->GetValPred(), other->GetValPred());
return Expr::Compare(iOther);
}
ZP<Expr_Bool> Expr_Bool_ValPred::Self()
{ return this; }
ZP<Expr_Bool> Expr_Bool_ValPred::Clone()
{ return this; }
void Expr_Bool_ValPred::Accept_Expr_Bool_ValPred(Visitor_Expr_Bool_ValPred& iVisitor)
{ iVisitor.Visit_Expr_Bool_ValPred(this); }
const ValPred& Expr_Bool_ValPred::GetValPred() const
{ return fValPred; }
// =================================================================================================
#pragma mark - Visitor_Expr_Bool_ValPred
void Visitor_Expr_Bool_ValPred::Visit_Expr_Bool_ValPred(const ZP<Expr_Bool_ValPred >& iExpr)
{ this->Visit_Expr_Op0(iExpr); }
// =================================================================================================
#pragma mark - Operators
ZP<Expr_Bool> sExpr_Bool(const ValPred& iValPred)
{ return new Expr_Bool_ValPred(iValPred); }
ZP<Expr_Bool> operator~(const ValPred& iValPred)
{ return new Expr_Bool_Not(sExpr_Bool(iValPred)); }
ZP<Expr_Bool> operator&(bool iBool, const ValPred& iValPred)
{
if (iBool)
return sExpr_Bool(iValPred);
return sFalse();
}
ZP<Expr_Bool> operator&(const ValPred& iValPred, bool iBool)
{
if (iBool)
return sExpr_Bool(iValPred);
return sFalse();
}
ZP<Expr_Bool> operator|(bool iBool, const ValPred& iValPred)
{
if (iBool)
return sTrue();
return sExpr_Bool(iValPred);
}
ZP<Expr_Bool> operator|(const ValPred& iValPred, bool iBool)
{
if (iBool)
return sTrue();
return sExpr_Bool(iValPred);
}
ZP<Expr_Bool> operator&(const ValPred& iLHS, const ValPred& iRHS)
{ return new Expr_Bool_And(sExpr_Bool(iLHS), sExpr_Bool(iRHS)); }
ZP<Expr_Bool> operator&(const ValPred& iLHS, const ZP<Expr_Bool>& iRHS)
{ return new Expr_Bool_And(sExpr_Bool(iLHS), iRHS); }
ZP<Expr_Bool> operator&(const ZP<Expr_Bool>& iLHS, const ValPred& iRHS)
{ return new Expr_Bool_And(iLHS, sExpr_Bool(iRHS)); }
ZP<Expr_Bool>& operator&=(ZP<Expr_Bool>& ioLHS, const ValPred& iRHS)
{ return ioLHS = ioLHS & iRHS; }
ZP<Expr_Bool> operator|(const ValPred& iLHS, const ValPred& iRHS)
{ return new Expr_Bool_Or(sExpr_Bool(iLHS), sExpr_Bool(iRHS)); }
ZP<Expr_Bool> operator|(const ValPred& iLHS, const ZP<Expr_Bool>& iRHS)
{ return new Expr_Bool_Or(sExpr_Bool(iLHS), iRHS); }
ZP<Expr_Bool> operator|(const ZP<Expr_Bool>& iLHS, const ValPred& iRHS)
{ return new Expr_Bool_Or(iLHS, sExpr_Bool(iRHS)); }
ZP<Expr_Bool>& operator|=(ZP<Expr_Bool>& ioLHS, const ValPred& iRHS)
{ return ioLHS = ioLHS | iRHS; }
} // namespace ZooLib
| 29.801653 | 100 | 0.691625 | ElectricMagic |
514786e45bfa78af864d4f97ff08ceae21f9fbcd | 2,542 | cpp | C++ | lightOJ/loj1123.cpp | partho222/programming | 98a87b6a04f39c343125cf5f0dd85e0f1c37d56c | [
"BSD-2-Clause"
] | null | null | null | lightOJ/loj1123.cpp | partho222/programming | 98a87b6a04f39c343125cf5f0dd85e0f1c37d56c | [
"BSD-2-Clause"
] | null | null | null | lightOJ/loj1123.cpp | partho222/programming | 98a87b6a04f39c343125cf5f0dd85e0f1c37d56c | [
"BSD-2-Clause"
] | null | null | null | /* Tariq ahmed khan - Daffodil */
#include <bits/stdc++.h>
#define _ ios_base::sync_with_stdio(0);cin.tie(0); // I/O optimization
#define pi 2*acos(0.0)
#define scan(x) scanf("%d",&x)
#define sf scanf
#define pf printf
#define pb push_back
#define memoclr(n,x) memset(n,x,sizeof(n) )
#define INF 1 << 30
typedef long long LLI;
typedef unsigned long long LLU;
template<class T> T gcd(T x, T y){if (y==0) return x; return gcd(y,x%y);}
template<class T> T lcm(T x, T y){return ((x/gcd(x,y))*y);}
template<class T> T maxt(T x, T y){if (x > y) return x; else return y;}
template<class T> T mint(T x, T y){if (x < y) return x; else return y;}
template<class T> T power(T x, T y){T res=1,a = x; while(y){if(y&1){res*=a;}a*=a;y>>=1;}return res;}
template<class T> T bigmod(T x,T y,T mod){T res=1,a=x; while(y){if(y&1){res=(res*a)%mod;}a=(a*a)%mod;y>>=1;}return res;}
int dir[8][2]={{-1,0}
,{1,0}
,{0,-1}
,{0,1}
,{-1,-1}
,{-1,1}
,{1,-1}
,{1,1}};
using namespace std;
struct node{
int st,ed,len;
};
node edge[300];
bool comp(const node &a , const node &b){
if(a.len < b.len)
return true;
return false;
}
int up[300],dow[300];
int main() {
#ifdef partho222
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
#endif
int test,kase=0;
scan(test);
while(test--)
{
int n,wk,x,y;
scan(n); scan(wk);
pf("Case %d:\n",++kase);
for(int i=0 ; i<wk ; i++)
{
scanf("%d %d %d",&edge[i].st,&edge[i].ed,&edge[i].len);
if(i < n-1)
{
pf("-1\n");
continue;
}
memoclr(up,-1);
memoclr(dow,-1);
sort(edge+0,edge+(i+1),comp);
int res = 0,all=0;
for(int j=0 ; j<= i && all != n-1 ; j++)
{
if( dow[ edge[j].ed ] == -1 || up[ edge[j].st ] == -1 )
{
//cout << edge[j].st << " -> " << edge[j].ed << " = " << edge[j].len << endl;
up[ edge[j].st ] = 0 ; dow[ edge[j].ed ] = 0;
//up[ edge[j].ed ] = 0 ; dow[ edge[j].st ] = 0;
res += edge[j].len;
all++;
}
}
//cout << res << endl;
if( all == n-1)
pf("%d\n",res);
else
pf("-1\n");
}
}
return 0;
}
| 23.537037 | 120 | 0.434304 | partho222 |
5147b6b5966663e3288f8cec47347c937a866519 | 954 | cpp | C++ | The_Eye/src/Biquad_Filter.cpp | michprev/drone | 51c659cdd4e1d50446a563bb11e800defda9a298 | [
"MIT"
] | 2 | 2017-06-03T01:07:16.000Z | 2017-07-14T17:49:16.000Z | The_Eye/src/Biquad_Filter.cpp | michprev/drone | 51c659cdd4e1d50446a563bb11e800defda9a298 | [
"MIT"
] | 5 | 2017-04-24T20:29:04.000Z | 2017-06-26T17:40:53.000Z | The_Eye/src/Biquad_Filter.cpp | michprev/drone | 51c659cdd4e1d50446a563bb11e800defda9a298 | [
"MIT"
] | null | null | null | /*
* Biquad_Filter.cpp
*
* Created on: 24. 6. 2017
* Author: michp
*/
#include <Biquad_Filter.h>
namespace flyhero {
Biquad_Filter::Biquad_Filter(Filter_Type type, float sample_frequency, float cut_frequency) {
double K = std::tan(this->PI * cut_frequency / sample_frequency);
double Q = 1.0 / std::sqrt(2); // let Q be 1 / sqrt(2) for Butterworth
double norm;
switch (type) {
case FILTER_LOW_PASS:
norm = 1.0 / (1 + K / Q + K * K);
this->a0 = K * K * norm;
this->a1 = 2 * this->a0;
this->a2 = this->a0;
this->b1 = 2 * (K * K - 1) * norm;
this->b2 = (1 - K / Q + K * K) * norm;
break;
case FILTER_NOTCH:
norm = 1.0 / (1 + K / Q + K * K);
this->a0 = (1 + K * K) * norm;
this->a1 = 2 * (K * K - 1) * norm;
this->a2 = this->a0;
this->b1 = this->a1;
this->b2 = (1 - K / Q + K * K) * norm;
break;
}
this->z1 = 0;
this->z2 = 0;
}
} /* namespace flyhero */
| 20.73913 | 94 | 0.524109 | michprev |
514ca2cb3acec8c2b0b53fb1c22ade80fbb6b6f6 | 17,331 | hpp | C++ | GetOrientation/Vector2.hpp | LiangJy123/GetOrientation | b7ced089676847b986b5c16718ec847bbb3fd223 | [
"MIT"
] | 71 | 2020-05-28T07:19:39.000Z | 2022-02-14T02:48:01.000Z | GetOrientation/Vector2.hpp | LiangJy123/GetOrientation | b7ced089676847b986b5c16718ec847bbb3fd223 | [
"MIT"
] | 4 | 2021-02-20T13:49:53.000Z | 2022-03-24T16:39:08.000Z | GetOrientation/Vector2.hpp | LiangJy123/GetOrientation | b7ced089676847b986b5c16718ec847bbb3fd223 | [
"MIT"
] | 9 | 2017-11-22T01:25:32.000Z | 2021-12-25T11:28:34.000Z | /**
* ============================================================================
* MIT License
*
* Copyright (c) 2016 Eric Phillips
*
* 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.
* ============================================================================
*
*
* This file implements a series of math functions for manipulating a
* 2D vector.
*
* Created by Eric Phillips on October 15, 2016.
*/
#pragma once
#define _USE_MATH_DEFINES
#include <math.h>
struct Vector2
{
union
{
struct
{
double X;
double Y;
};
double data[2];
};
/**
* Constructors.
*/
inline Vector2();
inline Vector2(double data[]);
inline Vector2(double value);
inline Vector2(double x, double y);
/**
* Constants for common vectors.
*/
static inline Vector2 Zero();
static inline Vector2 One();
static inline Vector2 Right();
static inline Vector2 Left();
static inline Vector2 Up();
static inline Vector2 Down();
/**
* Returns the angle between two vectors in radians.
* @param a: The first vector.
* @param b: The second vector.
* @return: A scalar value.
*/
static inline double Angle(Vector2 a, Vector2 b);
/**
* Returns a vector with its magnitude clamped to maxLength.
* @param vector: The target vector.
* @param maxLength: The maximum length of the return vector.
* @return: A new vector.
*/
static inline Vector2 ClampMagnitude(Vector2 vector, double maxLength);
/**
* Returns the component of a in the direction of b (scalar projection).
* @param a: The target vector.
* @param b: The vector being compared against.
* @return: A scalar value.
*/
static inline double Component(Vector2 a, Vector2 b);
/**
* Returns the distance between a and b.
* @param a: The first point.
* @param b: The second point.
* @return: A scalar value.
*/
static inline double Distance(Vector2 a, Vector2 b);
/**
* Returns the dot product of two vectors.
* @param lhs: The left side of the multiplication.
* @param rhs: The right side of the multiplication.
* @return: A scalar value.
*/
static inline double Dot(Vector2 lhs, Vector2 rhs);
/**
* Converts a polar representation of a vector into cartesian
* coordinates.
* @param rad: The magnitude of the vector.
* @param theta: The angle from the X axis.
* @return: A new vector.
*/
static inline Vector2 FromPolar(double rad, double theta);
/**
* Returns a vector linearly interpolated between a and b, moving along
* a straight line. The vector is clamped to never go beyond the end points.
* @param a: The starting point.
* @param b: The ending point.
* @param t: The interpolation value [0-1].
* @return: A new vector.
*/
static inline Vector2 Lerp(Vector2 a, Vector2 b, double t);
/**
* Returns a vector linearly interpolated between a and b, moving along
* a straight line.
* @param a: The starting point.
* @param b: The ending point.
* @param t: The interpolation value [0-1] (no actual bounds).
* @return: A new vector.
*/
static inline Vector2 LerpUnclamped(Vector2 a, Vector2 b, double t);
/**
* Returns the magnitude of a vector.
* @param v: The vector in question.
* @return: A scalar value.
*/
static inline double Magnitude(Vector2 v);
/**
* Returns a vector made from the largest components of two other vectors.
* @param a: The first vector.
* @param b: The second vector.
* @return: A new vector.
*/
static inline Vector2 Max(Vector2 a, Vector2 b);
/**
* Returns a vector made from the smallest components of two other vectors.
* @param a: The first vector.
* @param b: The second vector.
* @return: A new vector.
*/
static inline Vector2 Min(Vector2 a, Vector2 b);
/**
* Returns a vector "maxDistanceDelta" units closer to the target. This
* interpolation is in a straight line, and will not overshoot.
* @param current: The current position.
* @param target: The destination position.
* @param maxDistanceDelta: The maximum distance to move.
* @return: A new vector.
*/
static inline Vector2 MoveTowards(Vector2 current, Vector2 target,
double maxDistanceDelta);
/**
* Returns a new vector with magnitude of one.
* @param v: The vector in question.
* @return: A new vector.
*/
static inline Vector2 Normalized(Vector2 v);
/**
* Creates a new coordinate system out of the two vectors.
* Normalizes "normal" and normalizes "tangent" and makes it orthogonal to
* "normal"..
* @param normal: A reference to the first axis vector.
* @param tangent: A reference to the second axis vector.
*/
static inline void OrthoNormalize(Vector2 &normal, Vector2 &tangent);
/**
* Returns the vector projection of a onto b.
* @param a: The target vector.
* @param b: The vector being projected onto.
* @return: A new vector.
*/
static inline Vector2 Project(Vector2 a, Vector2 b);
/**
* Returns a vector reflected about the provided line.
* This behaves as if there is a plane with the line as its normal, and the
* vector comes in and bounces off this plane.
* @param vector: The vector traveling inward at the imaginary plane.
* @param line: The line about which to reflect.
* @return: A new vector pointing outward from the imaginary plane.
*/
static inline Vector2 Reflect(Vector2 vector, Vector2 line);
/**
* Returns the vector rejection of a on b.
* @param a: The target vector.
* @param b: The vector being projected onto.
* @return: A new vector.
*/
static inline Vector2 Reject(Vector2 a, Vector2 b);
/**
* Rotates vector "current" towards vector "target" by "maxRadiansDelta".
* This treats the vectors as directions and will linearly interpolate
* between their magnitudes by "maxMagnitudeDelta". This function does not
* overshoot. If a negative delta is supplied, it will rotate away from
* "target" until it is pointing the opposite direction, but will not
* overshoot that either.
* @param current: The starting direction.
* @param target: The destination direction.
* @param maxRadiansDelta: The maximum number of radians to rotate.
* @param maxMagnitudeDelta: The maximum delta for magnitude interpolation.
* @return: A new vector.
*/
static inline Vector2 RotateTowards(Vector2 current, Vector2 target,
double maxRadiansDelta,
double maxMagnitudeDelta);
/**
* Multiplies two vectors component-wise.
* @param a: The lhs of the multiplication.
* @param b: The rhs of the multiplication.
* @return: A new vector.
*/
static inline Vector2 Scale(Vector2 a, Vector2 b);
/**
* Returns a vector rotated towards b from a by the percent t.
* Since interpolation is done spherically, the vector moves at a constant
* angular velocity. This rotation is clamped to 0 <= t <= 1.
* @param a: The starting direction.
* @param b: The ending direction.
* @param t: The interpolation value [0-1].
*/
static inline Vector2 Slerp(Vector2 a, Vector2 b, double t);
/**
* Returns a vector rotated towards b from a by the percent t.
* Since interpolation is done spherically, the vector moves at a constant
* angular velocity. This rotation is unclamped.
* @param a: The starting direction.
* @param b: The ending direction.
* @param t: The interpolation value [0-1].
*/
static inline Vector2 SlerpUnclamped(Vector2 a, Vector2 b, double t);
/**
* Returns the squared magnitude of a vector.
* This is useful when comparing relative lengths, where the exact length
* is not important, and much time can be saved by not calculating the
* square root.
* @param v: The vector in question.
* @return: A scalar value.
*/
static inline double SqrMagnitude(Vector2 v);
/**
* Calculates the polar coordinate space representation of a vector.
* @param vector: The vector to convert.
* @param rad: The magnitude of the vector.
* @param theta: The angle from the X axis.
*/
static inline void ToPolar(Vector2 vector, double &rad, double &theta);
/**
* Operator overloading.
*/
inline struct Vector2& operator+=(const double rhs);
inline struct Vector2& operator-=(const double rhs);
inline struct Vector2& operator*=(const double rhs);
inline struct Vector2& operator/=(const double rhs);
inline struct Vector2& operator+=(const Vector2 rhs);
inline struct Vector2& operator-=(const Vector2 rhs);
};
inline Vector2 operator-(Vector2 rhs);
inline Vector2 operator+(Vector2 lhs, const double rhs);
inline Vector2 operator-(Vector2 lhs, const double rhs);
inline Vector2 operator*(Vector2 lhs, const double rhs);
inline Vector2 operator/(Vector2 lhs, const double rhs);
inline Vector2 operator+(const double lhs, Vector2 rhs);
inline Vector2 operator-(const double lhs, Vector2 rhs);
inline Vector2 operator*(const double lhs, Vector2 rhs);
inline Vector2 operator/(const double lhs, Vector2 rhs);
inline Vector2 operator+(Vector2 lhs, const Vector2 rhs);
inline Vector2 operator-(Vector2 lhs, const Vector2 rhs);
inline bool operator==(const Vector2 lhs, const Vector2 rhs);
inline bool operator!=(const Vector2 lhs, const Vector2 rhs);
/*******************************************************************************
* Implementation
*/
Vector2::Vector2() : X(0), Y(0) {}
Vector2::Vector2(double data[]) : X(data[0]), Y(data[1]) {}
Vector2::Vector2(double value) : X(value), Y(value) {}
Vector2::Vector2(double x, double y) : X(x), Y(y) {}
Vector2 Vector2::Zero() { return Vector2(0, 0); }
Vector2 Vector2::One() { return Vector2(1, 1); }
Vector2 Vector2::Right() { return Vector2(1, 0); }
Vector2 Vector2::Left() { return Vector2(-1, 0); }
Vector2 Vector2::Up() { return Vector2(0, 1); }
Vector2 Vector2::Down() { return Vector2(0, -1); }
double Vector2::Angle(Vector2 a, Vector2 b)
{
double v = Dot(a, b) / (Magnitude(a) * Magnitude(b));
v = fmax(v, -1.0);
v = fmin(v, 1.0);
return acos(v);
}
Vector2 Vector2::ClampMagnitude(Vector2 vector, double maxLength)
{
double length = Magnitude(vector);
if (length > maxLength)
vector *= maxLength / length;
return vector;
}
double Vector2::Component(Vector2 a, Vector2 b)
{
return Dot(a, b) / Magnitude(b);
}
double Vector2::Distance(Vector2 a, Vector2 b)
{
return Vector2::Magnitude(a - b);
}
double Vector2::Dot(Vector2 lhs, Vector2 rhs)
{
return lhs.X * rhs.X + lhs.Y * rhs.Y;
}
Vector2 Vector2::FromPolar(double rad, double theta)
{
Vector2 v;
v.X = rad * cos(theta);
v.Y = rad * sin(theta);
return v;
}
Vector2 Vector2::Lerp(Vector2 a, Vector2 b, double t)
{
if (t < 0) return a;
else if (t > 1) return b;
return LerpUnclamped(a, b, t);
}
Vector2 Vector2::LerpUnclamped(Vector2 a, Vector2 b, double t)
{
return (b - a) * t + a;
}
double Vector2::Magnitude(Vector2 v)
{
return sqrt(SqrMagnitude(v));
}
Vector2 Vector2::Max(Vector2 a, Vector2 b)
{
double x = a.X > b.X ? a.X : b.X;
double y = a.Y > b.Y ? a.Y : b.Y;
return Vector2(x, y);
}
Vector2 Vector2::Min(Vector2 a, Vector2 b)
{
double x = a.X > b.X ? b.X : a.X;
double y = a.Y > b.Y ? b.Y : a.Y;
return Vector2(x, y);
}
Vector2 Vector2::MoveTowards(Vector2 current, Vector2 target,
double maxDistanceDelta)
{
Vector2 d = target - current;
double m = Magnitude(d);
if (m < maxDistanceDelta || m == 0)
return target;
return current + (d * maxDistanceDelta / m);
}
Vector2 Vector2::Normalized(Vector2 v)
{
double mag = Magnitude(v);
if (mag == 0)
return Vector2::Zero();
return v / mag;
}
void Vector2::OrthoNormalize(Vector2 &normal, Vector2 &tangent)
{
normal = Normalized(normal);
tangent = Reject(tangent, normal);
tangent = Normalized(tangent);
}
Vector2 Vector2::Project(Vector2 a, Vector2 b)
{
double m = Magnitude(b);
return Dot(a, b) / (m * m) * b;
}
Vector2 Vector2::Reflect(Vector2 vector, Vector2 planeNormal)
{
return vector - 2 * Project(vector, planeNormal);
}
Vector2 Vector2::Reject(Vector2 a, Vector2 b)
{
return a - Project(a, b);
}
Vector2 Vector2::RotateTowards(Vector2 current, Vector2 target,
double maxRadiansDelta,
double maxMagnitudeDelta)
{
double magCur = Magnitude(current);
double magTar = Magnitude(target);
double newMag = magCur + maxMagnitudeDelta *
((magTar > magCur) - (magCur > magTar));
newMag = fmin(newMag, fmax(magCur, magTar));
newMag = fmax(newMag, fmin(magCur, magTar));
double totalAngle = Angle(current, target) - maxRadiansDelta;
if (totalAngle <= 0)
return Normalized(target) * newMag;
else if (totalAngle >= M_PI)
return Normalized(-target) * newMag;
double axis = current.X * target.Y - current.Y * target.X;
axis = axis / fabs(axis);
if (!(1 - fabs(axis) < 0.00001))
axis = 1;
current = Normalized(current);
Vector2 newVector = current * cos(maxRadiansDelta) +
Vector2(-current.Y, current.X) * sin(maxRadiansDelta) * axis;
return newVector * newMag;
}
Vector2 Vector2::Scale(Vector2 a, Vector2 b)
{
return Vector2(a.X * b.X, a.Y * b.Y);
}
Vector2 Vector2::Slerp(Vector2 a, Vector2 b, double t)
{
if (t < 0) return a;
else if (t > 1) return b;
return SlerpUnclamped(a, b, t);
}
Vector2 Vector2::SlerpUnclamped(Vector2 a, Vector2 b, double t)
{
double magA = Magnitude(a);
double magB = Magnitude(b);
a /= magA;
b /= magB;
double dot = Dot(a, b);
dot = fmax(dot, -1.0);
dot = fmin(dot, 1.0);
double theta = acos(dot) * t;
Vector2 relativeVec = Normalized(b - a * dot);
Vector2 newVec = a * cos(theta) + relativeVec * sin(theta);
return newVec * (magA + (magB - magA) * t);
}
double Vector2::SqrMagnitude(Vector2 v)
{
return v.X * v.X + v.Y * v.Y;
}
void Vector2::ToPolar(Vector2 vector, double &rad, double &theta)
{
rad = Magnitude(vector);
theta = atan2(vector.Y, vector.X);
}
struct Vector2& Vector2::operator+=(const double rhs)
{
X += rhs;
Y += rhs;
return *this;
}
struct Vector2& Vector2::operator-=(const double rhs)
{
X -= rhs;
Y -= rhs;
return *this;
}
struct Vector2& Vector2::operator*=(const double rhs)
{
X *= rhs;
Y *= rhs;
return *this;
}
struct Vector2& Vector2::operator/=(const double rhs)
{
X /= rhs;
Y /= rhs;
return *this;
}
struct Vector2& Vector2::operator+=(const Vector2 rhs)
{
X += rhs.X;
Y += rhs.Y;
return *this;
}
struct Vector2& Vector2::operator-=(const Vector2 rhs)
{
X -= rhs.X;
Y -= rhs.Y;
return *this;
}
Vector2 operator-(Vector2 rhs) { return rhs * -1; }
Vector2 operator+(Vector2 lhs, const double rhs) { return lhs += rhs; }
Vector2 operator-(Vector2 lhs, const double rhs) { return lhs -= rhs; }
Vector2 operator*(Vector2 lhs, const double rhs) { return lhs *= rhs; }
Vector2 operator/(Vector2 lhs, const double rhs) { return lhs /= rhs; }
Vector2 operator+(const double lhs, Vector2 rhs) { return rhs += lhs; }
Vector2 operator-(const double lhs, Vector2 rhs) { return rhs -= lhs; }
Vector2 operator*(const double lhs, Vector2 rhs) { return rhs *= lhs; }
Vector2 operator/(const double lhs, Vector2 rhs) { return rhs /= lhs; }
Vector2 operator+(Vector2 lhs, const Vector2 rhs) { return lhs += rhs; }
Vector2 operator-(Vector2 lhs, const Vector2 rhs) { return lhs -= rhs; }
bool operator==(const Vector2 lhs, const Vector2 rhs)
{
return lhs.X == rhs.X && lhs.Y == rhs.Y;
}
bool operator!=(const Vector2 lhs, const Vector2 rhs)
{
return !(lhs == rhs);
}
| 30.620141 | 80 | 0.63724 | LiangJy123 |
514e28037e08f2ff0ce001d3ef6a78cef42b8e14 | 6,419 | cpp | C++ | glasscore/tests/picklist_unittest.cpp | jpatton-USGS/neic-glass3 | 52ab2eabd5d5d97c9d74f44c462aec7e88e51899 | [
"CC0-1.0"
] | 9 | 2019-02-18T09:08:43.000Z | 2021-08-25T13:59:15.000Z | glasscore/tests/picklist_unittest.cpp | jpatton-USGS/neic-glass3 | 52ab2eabd5d5d97c9d74f44c462aec7e88e51899 | [
"CC0-1.0"
] | 65 | 2017-12-06T16:01:11.000Z | 2021-06-10T15:24:23.000Z | glasscore/tests/picklist_unittest.cpp | jpatton-USGS/neic-glass3 | 52ab2eabd5d5d97c9d74f44c462aec7e88e51899 | [
"CC0-1.0"
] | 7 | 2017-12-04T20:21:28.000Z | 2021-12-01T15:59:40.000Z | #include <gtest/gtest.h>
#include <memory>
#include <string>
#include <logger.h>
#include "Pick.h"
#include "PickList.h"
#include "Site.h"
#include "SiteList.h"
#define SITEJSON "{\"Type\":\"StationInfo\",\"Elevation\":2326.000000,\"Latitude\":45.822170,\"Longitude\":-112.451000,\"Site\":{\"Station\":\"LRM\",\"Channel\":\"EHZ\",\"Network\":\"MB\",\"Location\":\"\"},\"Enable\":true,\"Quality\":1.0,\"UseForTeleseismic\":true}" // NOLINT
#define SITE2JSON "{\"Type\":\"StationInfo\",\"Elevation\":1342.000000,\"Latitude\":46.711330,\"Longitude\":-111.831200,\"Site\":{\"Station\":\"HRY\",\"Channel\":\"EHZ\",\"Network\":\"MB\",\"Location\":\"\"},\"Enable\":true,\"Quality\":1.0,\"UseForTeleseismic\":true}" // NOLINT
#define SITE3JSON "{\"Type\":\"StationInfo\",\"Elevation\":1589.000000,\"Latitude\":45.596970,\"Longitude\":-111.629670,\"Site\":{\"Station\":\"BOZ\",\"Channel\":\"BHZ\",\"Network\":\"US\",\"Location\":\"00\"},\"Enable\":true,\"Quality\":1.0,\"UseForTeleseismic\":true}" // NOLINT
#define PICKJSON "{\"ID\":\"20682831\",\"Phase\":\"P\",\"Polarity\":\"up\",\"Site\":{\"Channel\":\"EHZ\",\"Location\":\"\",\"Network\":\"MB\",\"Station\":\"LRM\"},\"Source\":{\"AgencyID\":\"228041013\",\"Author\":\"228041013\"},\"Time\":\"2014-12-23T00:01:43.599Z\",\"Type\":\"Pick\"}" // NOLINT
#define PICK2JSON "{\"ID\":\"20682832\",\"Phase\":\"P\",\"Polarity\":\"up\",\"Site\":{\"Channel\":\"EHZ\",\"Location\":\"\",\"Network\":\"MB\",\"Station\":\"HRY\"},\"Source\":{\"AgencyID\":\"228041013\",\"Author\":\"228041013\"},\"Time\":\"2014-12-23T00:02:43.599Z\",\"Type\":\"Pick\"}" // NOLINT
#define PICK3JSON "{\"ID\":\"20682833\",\"Phase\":\"P\",\"Polarity\":\"up\",\"Site\":{\"Channel\":\"BHZ\",\"Location\":\"00\",\"Network\":\"US\",\"Station\":\"BOZ\"},\"Source\":{\"AgencyID\":\"228041013\",\"Author\":\"228041013\"},\"Time\":\"2014-12-23T00:03:43.599Z\",\"Type\":\"Pick\"}" // NOLINT
#define PICK4JSON "{\"ID\":\"20682834\",\"Phase\":\"P\",\"Polarity\":\"up\",\"Site\":{\"Channel\":\"EHZ\",\"Location\":\"\",\"Network\":\"MB\",\"Station\":\"LRM\"},\"Source\":{\"AgencyID\":\"228041013\",\"Author\":\"228041013\"},\"Time\":\"2014-12-23T00:04:43.599Z\",\"Type\":\"Pick\"}" // NOLINT
#define PICK5JSON "{\"ID\":\"20682835\",\"Phase\":\"P\",\"Polarity\":\"up\",\"Site\":{\"Channel\":\"EHZ\",\"Location\":\"\",\"Network\":\"MB\",\"Station\":\"HRY\"},\"Source\":{\"AgencyID\":\"228041013\",\"Author\":\"228041013\"},\"Time\":\"2014-12-23T00:05:43.599Z\",\"Type\":\"Pick\"}" // NOLINT
#define PICK6JSON "{\"ID\":\"20682836\",\"Phase\":\"P\",\"Polarity\":\"up\",\"Site\":{\"Channel\":\"BHZ\",\"Location\":\"00\",\"Network\":\"US\",\"Station\":\"BOZ\"},\"Source\":{\"AgencyID\":\"228041013\",\"Author\":\"228041013\"},\"Time\":\"2014-12-23T00:00:43.599Z\",\"Type\":\"Pick\"}" // NOLINT
#define SCNL "LRM.EHZ.MB"
#define SCNL2 "BOZ.BHZ.US.00"
#define TPICK 3628281643.59000
#define TPICK2 3628281943.590000
#define TPICK3 3628281763.590000
#define MAXNPICK 5
// NOTE: Need to consider testing scavenge, and rouges functions,
// but that would need a much more involved set of real nodes and data,
// not this simple setup.
// Maybe consider performing this test at a higher level?
// test to see if the picklist can be constructed
TEST(PickListTest, Construction) {
glass3::util::Logger::disable();
// construct a picklist
glasscore::CPickList * testPickList = new glasscore::CPickList();
// assert default values
ASSERT_EQ(0, testPickList->getCountOfTotalPicksProcessed())<< "nPickTotal is 0";
// lists
ASSERT_EQ(0, testPickList->length())<< "getVPickSize() is 0";
// pointers
ASSERT_EQ(NULL, testPickList->getSiteList())<< "pSiteList null";
}
// test various pick operations
TEST(PickListTest, PickOperations) {
glass3::util::Logger::disable();
// create json objects from the strings
std::shared_ptr<json::Object> siteJSON = std::make_shared<json::Object>(
json::Object(json::Deserialize(std::string(SITEJSON))));
std::shared_ptr<json::Object> site2JSON = std::make_shared<json::Object>(
json::Object(json::Deserialize(std::string(SITE2JSON))));
std::shared_ptr<json::Object> site3JSON = std::make_shared<json::Object>(
json::Object(json::Deserialize(std::string(SITE3JSON))));
std::shared_ptr<json::Object> pickJSON = std::make_shared<json::Object>(
json::Object(json::Deserialize(std::string(PICKJSON))));
std::shared_ptr<json::Object> pick2JSON = std::make_shared<json::Object>(
json::Object(json::Deserialize(std::string(PICK2JSON))));
std::shared_ptr<json::Object> pick3JSON = std::make_shared<json::Object>(
json::Object(json::Deserialize(std::string(PICK3JSON))));
std::shared_ptr<json::Object> pick4JSON = std::make_shared<json::Object>(
json::Object(json::Deserialize(std::string(PICK4JSON))));
std::shared_ptr<json::Object> pick5JSON = std::make_shared<json::Object>(
json::Object(json::Deserialize(std::string(PICK5JSON))));
std::shared_ptr<json::Object> pick6JSON = std::make_shared<json::Object>(
json::Object(json::Deserialize(std::string(PICK6JSON))));
// construct a sitelist
glasscore::CSiteList * testSiteList = new glasscore::CSiteList();
// add sites to site list
testSiteList->addSiteFromJSON(siteJSON);
testSiteList->addSiteFromJSON(site2JSON);
testSiteList->addSiteFromJSON(site3JSON);
// construct a picklist
glasscore::CPickList * testPickList = new glasscore::CPickList();
testPickList->setSiteList(testSiteList);
glasscore::CGlass::setMaxNumPicks(-1);
testPickList->setMaxAllowablePickCount(MAXNPICK);
// test adding picks by addPick and dispatch
testPickList->addPick(pickJSON);
testPickList->receiveExternalMessage(pick3JSON);
// give time for work
std::this_thread::sleep_for(std::chrono::seconds(1));
int expectedSize = 2;
ASSERT_EQ(expectedSize, testPickList->getCountOfTotalPicksProcessed())<<
"Added Picks";
// add more picks
testPickList->addPick(pick2JSON);
testPickList->addPick(pick4JSON);
testPickList->addPick(pick5JSON);
testPickList->addPick(pick6JSON);
// give time for work
std::this_thread::sleep_for(std::chrono::seconds(1));
// check to make sure the size isn't any larger than our max
expectedSize = MAXNPICK;
ASSERT_EQ(expectedSize, testPickList->length())<<
"testPickList not larger than max";
// test clearing picks
testPickList->clear();
expectedSize = 0;
ASSERT_EQ(expectedSize, testPickList->getCountOfTotalPicksProcessed())<< "Cleared Picks";
}
| 51.766129 | 299 | 0.664901 | jpatton-USGS |
515051bf441f183564bcfd34c6049dff2b78431e | 17,177 | cpp | C++ | Development/External/wxWindows_2.4.0/contrib/samples/ogl/studio/doc.cpp | addstone/unrealengine3 | 4579d360dfd52b12493292120b27bb430f978fc8 | [
"FSFAP"
] | 37 | 2020-05-22T18:18:47.000Z | 2022-03-19T06:51:54.000Z | Development/External/wxWindows_2.4.0/contrib/samples/ogl/studio/doc.cpp | AdanosGotoman/unrealengine3 | 4579d360dfd52b12493292120b27bb430f978fc8 | [
"FSFAP"
] | null | null | null | Development/External/wxWindows_2.4.0/contrib/samples/ogl/studio/doc.cpp | AdanosGotoman/unrealengine3 | 4579d360dfd52b12493292120b27bb430f978fc8 | [
"FSFAP"
] | 27 | 2020-05-17T01:03:30.000Z | 2022-03-06T19:10:14.000Z | /////////////////////////////////////////////////////////////////////////////
// Name: doc.cpp
// Purpose: Implements document functionality
// Author: Julian Smart
// Modified by:
// Created: 12/07/98
// RCS-ID: $Id: doc.cpp,v 1.2 2001/10/30 13:28:45 GT Exp $
// Copyright: (c) Julian Smart
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#ifdef __GNUG__
// #pragma implementation
#endif
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/wxexpr.h>
#include "studio.h"
#include "doc.h"
#include "view.h"
#include <wx/ogl/basicp.h>
IMPLEMENT_DYNAMIC_CLASS(csDiagramDocument, wxDocument)
#ifdef _MSC_VER
#pragma warning(disable:4355)
#endif
csDiagramDocument::csDiagramDocument():m_diagram(this)
{
}
#ifdef _MSC_VER
#pragma warning(default:4355)
#endif
csDiagramDocument::~csDiagramDocument()
{
}
bool csDiagramDocument::OnCloseDocument()
{
m_diagram.DeleteAllShapes();
return TRUE;
}
bool csDiagramDocument::OnSaveDocument(const wxString& file)
{
if (file == "")
return FALSE;
if (!m_diagram.SaveFile(file))
{
wxString msgTitle;
if (wxTheApp->GetAppName() != "")
msgTitle = wxTheApp->GetAppName();
else
msgTitle = wxString("File error");
(void)wxMessageBox("Sorry, could not open this file for saving.", msgTitle, wxOK | wxICON_EXCLAMATION,
GetDocumentWindow());
return FALSE;
}
Modify(FALSE);
SetFilename(file);
return TRUE;
}
bool csDiagramDocument::OnOpenDocument(const wxString& file)
{
if (!OnSaveModified())
return FALSE;
wxString msgTitle;
if (wxTheApp->GetAppName() != "")
msgTitle = wxTheApp->GetAppName();
else
msgTitle = wxString("File error");
m_diagram.DeleteAllShapes();
if (!m_diagram.LoadFile(file))
{
(void)wxMessageBox("Sorry, could not open this file.", msgTitle, wxOK|wxICON_EXCLAMATION,
GetDocumentWindow());
return FALSE;
}
SetFilename(file, TRUE);
Modify(FALSE);
UpdateAllViews();
return TRUE;
}
/*
* Implementation of drawing command
*/
csDiagramCommand::csDiagramCommand(const wxString& name, csDiagramDocument *doc,
csCommandState* onlyState):
wxCommand(TRUE, name)
{
m_doc = doc;
if (onlyState)
{
AddState(onlyState);
}
}
csDiagramCommand::~csDiagramCommand()
{
wxNode* node = m_states.First();
while (node)
{
csCommandState* state = (csCommandState*) node->Data();
delete state;
node = node->Next();
}
}
void csDiagramCommand::AddState(csCommandState* state)
{
state->m_doc = m_doc;
// state->m_cmd = m_cmd;
m_states.Append(state);
}
// Insert a state at the beginning of the list
void csDiagramCommand::InsertState(csCommandState* state)
{
state->m_doc = m_doc;
// state->m_cmd = m_cmd;
m_states.Insert(state);
}
// Schedule all lines connected to the states to be cut.
void csDiagramCommand::RemoveLines()
{
wxNode* node = m_states.First();
while (node)
{
csCommandState* state = (csCommandState*) node->Data();
wxShape* shape = state->GetShapeOnCanvas();
wxASSERT( (shape != NULL) );
wxNode *node1 = shape->GetLines().First();
while (node1)
{
wxLineShape *line = (wxLineShape *)node1->Data();
if (!FindStateByShape(line))
{
csCommandState* newState = new csCommandState(ID_CS_CUT, NULL, line);
InsertState(newState);
}
node1 = node1->Next();
}
node = node->Next();
}
}
csCommandState* csDiagramCommand::FindStateByShape(wxShape* shape)
{
wxNode* node = m_states.First();
while (node)
{
csCommandState* state = (csCommandState*) node->Data();
if (shape == state->GetShapeOnCanvas() || shape == state->GetSavedState())
return state;
node = node->Next();
}
return NULL;
}
bool csDiagramCommand::Do()
{
wxNode* node = m_states.First();
while (node)
{
csCommandState* state = (csCommandState*) node->Data();
if (!state->Do())
return FALSE;
node = node->Next();
}
return TRUE;
}
bool csDiagramCommand::Undo()
{
// Undo in reverse order, so e.g. shapes get added
// back before the lines do.
wxNode* node = m_states.Last();
while (node)
{
csCommandState* state = (csCommandState*) node->Data();
if (!state->Undo())
return FALSE;
node = node->Previous();
}
return TRUE;
}
csCommandState::csCommandState(int cmd, wxShape* savedState, wxShape* shapeOnCanvas)
{
m_cmd = cmd;
m_doc = NULL;
m_savedState = savedState;
m_shapeOnCanvas = shapeOnCanvas;
m_linePositionFrom = 0;
m_linePositionTo = 0;
}
csCommandState::~csCommandState()
{
if (m_savedState)
{
m_savedState->SetCanvas(NULL);
delete m_savedState;
}
}
bool csCommandState::Do()
{
switch (m_cmd)
{
case ID_CS_CUT:
{
// New state is 'nothing' - maybe pass shape ID to state so we know what
// we're talking about.
// Then save old shape in m_savedState (actually swap pointers)
wxASSERT( (m_shapeOnCanvas != NULL) );
wxASSERT( (m_savedState == NULL) ); // new state will be 'nothing'
wxASSERT( (m_doc != NULL) );
wxShapeCanvas* canvas = m_shapeOnCanvas->GetCanvas();
// In case this is a line
wxShape* lineFrom = NULL;
wxShape* lineTo = NULL;
int attachmentFrom = 0, attachmentTo = 0;
if (m_shapeOnCanvas->IsKindOf(CLASSINFO(wxLineShape)))
{
// Store the from/to info to save in the line shape
wxLineShape* lineShape = (wxLineShape*) m_shapeOnCanvas;
lineFrom = lineShape->GetFrom();
lineTo = lineShape->GetTo();
attachmentFrom = lineShape->GetAttachmentFrom();
attachmentTo = lineShape->GetAttachmentTo();
m_linePositionFrom = lineFrom->GetLinePosition(lineShape);
m_linePositionTo = lineTo->GetLinePosition(lineShape);
}
m_shapeOnCanvas->Select(FALSE);
((csDiagramView*) m_doc->GetFirstView())->SelectShape(m_shapeOnCanvas, FALSE);
m_shapeOnCanvas->Unlink();
m_doc->GetDiagram()->RemoveShape(m_shapeOnCanvas);
m_savedState = m_shapeOnCanvas;
if (m_savedState->IsKindOf(CLASSINFO(wxLineShape)))
{
// Restore the from/to info for future reference
wxLineShape* lineShape = (wxLineShape*) m_savedState;
lineShape->SetFrom(lineFrom);
lineShape->SetTo(lineTo);
lineShape->SetAttachments(attachmentFrom, attachmentTo);
wxClientDC dc(canvas);
canvas->PrepareDC(dc);
lineFrom->MoveLinks(dc);
lineTo->MoveLinks(dc);
}
m_doc->Modify(TRUE);
m_doc->UpdateAllViews();
break;
}
case ID_CS_ADD_SHAPE:
case ID_CS_ADD_SHAPE_SELECT:
{
// The app has given the command state a new m_savedState
// shape, which is the new shape to add to the canvas (but
// not actually added until this point).
// The new 'saved state' is therefore 'nothing' since there
// was nothing there before.
wxASSERT( (m_shapeOnCanvas == NULL) );
wxASSERT( (m_savedState != NULL) );
wxASSERT( (m_doc != NULL) );
m_shapeOnCanvas = m_savedState;
m_savedState = NULL;
m_doc->GetDiagram()->AddShape(m_shapeOnCanvas);
m_shapeOnCanvas->Show(TRUE);
wxClientDC dc(m_shapeOnCanvas->GetCanvas());
m_shapeOnCanvas->GetCanvas()->PrepareDC(dc);
csEvtHandler *handler = (csEvtHandler *)m_shapeOnCanvas->GetEventHandler();
m_shapeOnCanvas->FormatText(dc, handler->m_label);
m_shapeOnCanvas->Move(dc, m_shapeOnCanvas->GetX(), m_shapeOnCanvas->GetY());
if (m_cmd == ID_CS_ADD_SHAPE_SELECT)
{
m_shapeOnCanvas->Select(TRUE, &dc);
((csDiagramView*) m_doc->GetFirstView())->SelectShape(m_shapeOnCanvas, TRUE);
}
m_doc->Modify(TRUE);
m_doc->UpdateAllViews();
break;
}
case ID_CS_ADD_LINE:
case ID_CS_ADD_LINE_SELECT:
{
wxASSERT( (m_shapeOnCanvas == NULL) );
wxASSERT( (m_savedState != NULL) );
wxASSERT( (m_doc != NULL) );
wxLineShape *lineShape = (wxLineShape *)m_savedState;
wxASSERT( (lineShape->GetFrom() != NULL) );
wxASSERT( (lineShape->GetTo() != NULL) );
m_shapeOnCanvas = m_savedState;
m_savedState = NULL;
m_doc->GetDiagram()->AddShape(lineShape);
lineShape->GetFrom()->AddLine(lineShape, lineShape->GetTo(),
lineShape->GetAttachmentFrom(), lineShape->GetAttachmentTo());
lineShape->Show(TRUE);
wxClientDC dc(lineShape->GetCanvas());
lineShape->GetCanvas()->PrepareDC(dc);
// It won't get drawn properly unless you move both
// connected images
lineShape->GetFrom()->Move(dc, lineShape->GetFrom()->GetX(), lineShape->GetFrom()->GetY());
lineShape->GetTo()->Move(dc, lineShape->GetTo()->GetX(), lineShape->GetTo()->GetY());
if (m_cmd == ID_CS_ADD_LINE_SELECT)
{
lineShape->Select(TRUE, &dc);
((csDiagramView*) m_doc->GetFirstView())->SelectShape(m_shapeOnCanvas, TRUE);
}
m_doc->Modify(TRUE);
m_doc->UpdateAllViews();
break;
}
case ID_CS_CHANGE_BACKGROUND_COLOUR:
case ID_CS_MOVE:
case ID_CS_SIZE:
case ID_CS_EDIT_PROPERTIES:
case ID_CS_FONT_CHANGE:
case ID_CS_ARROW_CHANGE:
case ID_CS_ROTATE_CLOCKWISE:
case ID_CS_ROTATE_ANTICLOCKWISE:
case ID_CS_CHANGE_LINE_ORDERING:
case ID_CS_CHANGE_LINE_ATTACHMENT:
case ID_CS_ALIGN:
case ID_CS_NEW_POINT:
case ID_CS_CUT_POINT:
case ID_CS_MOVE_LINE_POINT:
case ID_CS_STRAIGHTEN:
case ID_CS_MOVE_LABEL:
{
// At this point we have been given a new shape
// just like the old one but with a changed colour.
// It's now time to apply that change to the
// shape on the canvas, saving the old state.
// NOTE: this is general enough to work with MOST attribute
// changes!
wxASSERT( (m_shapeOnCanvas != NULL) );
wxASSERT( (m_savedState != NULL) ); // This is the new shape with changed colour
wxASSERT( (m_doc != NULL) );
wxClientDC dc(m_shapeOnCanvas->GetCanvas());
m_shapeOnCanvas->GetCanvas()->PrepareDC(dc);
bool isSelected = m_shapeOnCanvas->Selected();
if (isSelected)
m_shapeOnCanvas->Select(FALSE, & dc);
if (m_cmd == ID_CS_SIZE || m_cmd == ID_CS_ROTATE_CLOCKWISE || m_cmd == ID_CS_ROTATE_ANTICLOCKWISE ||
m_cmd == ID_CS_CHANGE_LINE_ORDERING || m_cmd == ID_CS_CHANGE_LINE_ATTACHMENT)
{
m_shapeOnCanvas->Erase(dc);
}
// TODO: make sure the ID is the same. Or, when applying the new state,
// don't change the original ID.
wxShape* tempShape = m_shapeOnCanvas->CreateNewCopy();
// Apply the saved state to the shape on the canvas, by copying.
m_savedState->CopyWithHandler(*m_shapeOnCanvas);
// Delete this state now it's been used (m_shapeOnCanvas currently holds this state)
delete m_savedState;
// Remember the previous state
m_savedState = tempShape;
// Redraw the shape
if (m_cmd == ID_CS_MOVE || m_cmd == ID_CS_ROTATE_CLOCKWISE || m_cmd == ID_CS_ROTATE_ANTICLOCKWISE ||
m_cmd == ID_CS_ALIGN)
{
m_shapeOnCanvas->Move(dc, m_shapeOnCanvas->GetX(), m_shapeOnCanvas->GetY());
csEvtHandler *handler = (csEvtHandler *)m_shapeOnCanvas->GetEventHandler();
m_shapeOnCanvas->FormatText(dc, handler->m_label);
m_shapeOnCanvas->Draw(dc);
}
else if (m_cmd == ID_CS_CHANGE_LINE_ORDERING)
{
m_shapeOnCanvas->MoveLinks(dc);
}
else if (m_cmd == ID_CS_CHANGE_LINE_ATTACHMENT)
{
wxLineShape *lineShape = (wxLineShape *)m_shapeOnCanvas;
// Have to move both sets of links since we don't know which links
// have been affected (unless we compared before and after states).
lineShape->GetFrom()->MoveLinks(dc);
lineShape->GetTo()->MoveLinks(dc);
}
else if (m_cmd == ID_CS_SIZE)
{
double width, height;
m_shapeOnCanvas->GetBoundingBoxMax(&width, &height);
m_shapeOnCanvas->SetSize(width, height);
m_shapeOnCanvas->Move(dc, m_shapeOnCanvas->GetX(), m_shapeOnCanvas->GetY());
m_shapeOnCanvas->Show(TRUE);
// Recursively redraw links if we have a composite.
if (m_shapeOnCanvas->GetChildren().Number() > 0)
m_shapeOnCanvas->DrawLinks(dc, -1, TRUE);
m_shapeOnCanvas->GetEventHandler()->OnEndSize(width, height);
}
else if (m_cmd == ID_CS_EDIT_PROPERTIES || m_cmd == ID_CS_FONT_CHANGE)
{
csEvtHandler *handler = (csEvtHandler *)m_shapeOnCanvas->GetEventHandler();
m_shapeOnCanvas->FormatText(dc, handler->m_label);
m_shapeOnCanvas->Draw(dc);
}
else
{
m_shapeOnCanvas->Draw(dc);
}
if (isSelected)
m_shapeOnCanvas->Select(TRUE, & dc);
m_doc->Modify(TRUE);
m_doc->UpdateAllViews();
break;
}
}
return TRUE;
}
bool csCommandState::Undo()
{
switch (m_cmd)
{
case ID_CS_CUT:
{
wxASSERT( (m_savedState != NULL) );
wxASSERT( (m_doc != NULL) );
m_doc->GetDiagram()->AddShape(m_savedState);
m_shapeOnCanvas = m_savedState;
m_savedState = NULL;
if (m_shapeOnCanvas->IsKindOf(CLASSINFO(wxLineShape)))
{
wxLineShape* lineShape = (wxLineShape*) m_shapeOnCanvas;
lineShape->GetFrom()->AddLine(lineShape, lineShape->GetTo(),
lineShape->GetAttachmentFrom(), lineShape->GetAttachmentTo(),
m_linePositionFrom, m_linePositionTo);
wxShapeCanvas* canvas = lineShape->GetFrom()->GetCanvas();
wxClientDC dc(canvas);
canvas->PrepareDC(dc);
lineShape->GetFrom()->MoveLinks(dc);
lineShape->GetTo()->MoveLinks(dc);
}
m_shapeOnCanvas->Show(TRUE);
m_doc->Modify(TRUE);
m_doc->UpdateAllViews();
break;
}
case ID_CS_ADD_SHAPE:
case ID_CS_ADD_LINE:
case ID_CS_ADD_SHAPE_SELECT:
case ID_CS_ADD_LINE_SELECT:
{
wxASSERT( (m_shapeOnCanvas != NULL) );
wxASSERT( (m_savedState == NULL) );
wxASSERT( (m_doc != NULL) );
// In case this is a line
wxShape* lineFrom = NULL;
wxShape* lineTo = NULL;
int attachmentFrom = 0, attachmentTo = 0;
if (m_shapeOnCanvas->IsKindOf(CLASSINFO(wxLineShape)))
{
// Store the from/to info to save in the line shape
wxLineShape* lineShape = (wxLineShape*) m_shapeOnCanvas;
lineFrom = lineShape->GetFrom();
lineTo = lineShape->GetTo();
attachmentFrom = lineShape->GetAttachmentFrom();
attachmentTo = lineShape->GetAttachmentTo();
}
wxClientDC dc(m_shapeOnCanvas->GetCanvas());
m_shapeOnCanvas->GetCanvas()->PrepareDC(dc);
m_shapeOnCanvas->Select(FALSE, &dc);
((csDiagramView*) m_doc->GetFirstView())->SelectShape(m_shapeOnCanvas, FALSE);
m_doc->GetDiagram()->RemoveShape(m_shapeOnCanvas);
m_shapeOnCanvas->Unlink(); // Unlinks the line, if it is a line
if (m_shapeOnCanvas->IsKindOf(CLASSINFO(wxLineShape)))
{
// Restore the from/to info for future reference
wxLineShape* lineShape = (wxLineShape*) m_shapeOnCanvas;
lineShape->SetFrom(lineFrom);
lineShape->SetTo(lineTo);
lineShape->SetAttachments(attachmentFrom, attachmentTo);
}
m_savedState = m_shapeOnCanvas;
m_shapeOnCanvas = NULL;
m_doc->Modify(TRUE);
m_doc->UpdateAllViews();
break;
}
case ID_CS_CHANGE_BACKGROUND_COLOUR:
case ID_CS_MOVE:
case ID_CS_SIZE:
case ID_CS_EDIT_PROPERTIES:
case ID_CS_FONT_CHANGE:
case ID_CS_ARROW_CHANGE:
case ID_CS_ROTATE_CLOCKWISE:
case ID_CS_ROTATE_ANTICLOCKWISE:
case ID_CS_CHANGE_LINE_ORDERING:
case ID_CS_CHANGE_LINE_ATTACHMENT:
case ID_CS_ALIGN:
case ID_CS_NEW_POINT:
case ID_CS_CUT_POINT:
case ID_CS_MOVE_LINE_POINT:
case ID_CS_STRAIGHTEN:
case ID_CS_MOVE_LABEL:
{
// Exactly like the Do case; we're just swapping states.
Do();
break;
}
}
return TRUE;
}
| 28.676127 | 108 | 0.611224 | addstone |
51525ce67259d341ba2805b5e45f1d6092f43b46 | 35,486 | cpp | C++ | source/bundles/index/IndexTaskService.cpp | izenecloud/sf1r-lite | 8de9aa83c38c9cd05a80b216579552e89609f136 | [
"Apache-2.0"
] | 77 | 2015-02-12T20:59:20.000Z | 2022-03-05T18:40:49.000Z | source/bundles/index/IndexTaskService.cpp | fytzzh/sf1r-lite | 8de9aa83c38c9cd05a80b216579552e89609f136 | [
"Apache-2.0"
] | 1 | 2017-04-28T08:55:47.000Z | 2017-07-10T10:10:53.000Z | source/bundles/index/IndexTaskService.cpp | fytzzh/sf1r-lite | 8de9aa83c38c9cd05a80b216579552e89609f136 | [
"Apache-2.0"
] | 33 | 2015-01-05T03:03:05.000Z | 2022-02-06T04:22:46.000Z | #include "IndexTaskService.h"
#include <common/JobScheduler.h>
#include <aggregator-manager/IndexWorker.h>
#include <node-manager/NodeManagerBase.h>
#include <node-manager/MasterManagerBase.h>
#include <node-manager/sharding/ScdSharder.h>
#include <node-manager/sharding/ScdDispatcher.h>
#include <node-manager/DistributeRequestHooker.h>
#include <node-manager/DistributeFileSyncMgr.h>
#include <node-manager/DistributeFileSys.h>
#include <util/driver/Request.h>
#include <common/Utilities.h>
#include <glog/logging.h>
#include <boost/filesystem.hpp>
namespace bfs = boost::filesystem;
using namespace izenelib::driver;
namespace sf1r
{
static const char* SCD_BACKUP_DIR = "backup";
const static std::string DISPATCH_TEMP_DIR = "dispatch-temp-dir/";
IndexTaskService::IndexTaskService(IndexBundleConfiguration* bundleConfig)
: bundleConfig_(bundleConfig)
{
service_ = Sf1rTopology::getServiceName(Sf1rTopology::SearchService);
//ShardingConfig::RangeListT ranges;
//ranges.push_back(100);
//ranges.push_back(1000);
//shard_cfg_.addRangeShardKey("UnchangableRangeProperty", ranges);
//ShardingConfig::AttrListT strranges;
//strranges.push_back("abc");
//shard_cfg_.addAttributeShardKey("UnchangableAttributeProperty", strranges);
if (DistributeFileSys::get()->isEnabled() && !bundleConfig_->indexShardKeys_.empty())
{
const std::string& coll = bundleConfig_->collectionName_;
sharding_map_dir_ = DistributeFileSys::get()->getFixedCopyPath("/sharding_map/");
sharding_map_dir_ = DistributeFileSys::get()->getDFSPathForLocal(sharding_map_dir_);
if (!bfs::exists(sharding_map_dir_))
{
bfs::create_directories(sharding_map_dir_);
}
sharding_strategy_.reset(new MapShardingStrategy(sharding_map_dir_ + coll));
sharding_strategy_->shard_cfg_.shardidList_ = bundleConfig_->col_shard_info_.shardList_;
if (sharding_strategy_->shard_cfg_.shardidList_.empty())
throw "sharding config is error!";
sharding_strategy_->shard_cfg_.setUniqueShardKey(bundleConfig_->indexShardKeys_[0]);
sharding_strategy_->init();
}
}
IndexTaskService::~IndexTaskService()
{
}
std::string IndexTaskService::getShardingMapDir()
{
return sharding_map_dir_;
}
bool IndexTaskService::SendRequestToSharding(uint32_t shardid)
{
Request::kCallType hooktype = (Request::kCallType)DistributeRequestHooker::get()->getHookType();
if (hooktype == Request::FromAPI)
{
return true;
}
const std::string& reqdata = DistributeRequestHooker::get()->getAdditionData();
bool ret = false;
if (hooktype == Request::FromDistribute)
{
indexAggregator_->singleRequest(bundleConfig_->collectionName_, 0,
"HookDistributeRequestForIndex", (int)hooktype, reqdata, ret, shardid);
}
else
{
ret = true;
}
if (!ret)
{
LOG(WARNING) << "Send Request to shard node failed.";
}
return ret;
}
bool IndexTaskService::HookDistributeRequestForIndex()
{
Request::kCallType hooktype = (Request::kCallType)DistributeRequestHooker::get()->getHookType();
if (hooktype == Request::FromAPI)
{
// from api do not need hook, just process as usually.
return true;
}
const std::string& reqdata = DistributeRequestHooker::get()->getAdditionData();
bool ret = false;
if (hooktype == Request::FromDistribute)
{
indexAggregator_->distributeRequestWithoutLocal(bundleConfig_->collectionName_, 0, "HookDistributeRequestForIndex", (int)hooktype, reqdata, ret);
}
else
{
// local hook has been moved to the request controller.
ret = true;
}
if (!ret)
{
LOG(WARNING) << "Request failed, HookDistributeRequestForIndex failed.";
}
return ret;
}
bool IndexTaskService::index(unsigned int numdoc, std::string scd_path, int disable_sharding_type)
{
bool result = true;
// disable_sharding_type , 0 no disable, 1 disable sending request to sharding node,
// 2 disable sending to sharding node and disable sharding SCD on local. (This means
// local node will index all of the docs in the given SCD files.)
bool disable_sharding = (disable_sharding_type != (int)DefaultShard);
indexWorker_->disableSharding(disable_sharding_type == (int)LocalOnly);
if (DistributeFileSys::get()->isEnabled())
{
if (scd_path.empty())
{
LOG(ERROR) << "scd path should be specified while dfs is enabled.";
return false;
}
scd_path = DistributeFileSys::get()->getDFSPathForLocal(scd_path);
}
else
{
scd_path = bundleConfig_->indexSCDPath();
}
if (bundleConfig_->isMasterAggregator() && indexAggregator_->isNeedDistribute() &&
DistributeRequestHooker::get()->isRunningPrimary())
{
if (DistributeRequestHooker::get()->isHooked())
{
if (DistributeRequestHooker::get()->getHookType() == Request::FromDistribute &&
!disable_sharding)
{
result = distributedIndex_(numdoc, scd_path);
}
else
{
if (disable_sharding)
LOG(INFO) << "==== The sharding is disabled! =====";
//if (DistributeFileSys::get()->isEnabled())
//{
// // while dfs enabled, the master will shard the scd file under the main scd_path
// // to sub-directory directly on dfs.
// // and the shard worker only index the sub-directory belong to it.
// //
// std::string myshard;
// myshard = boost::lexical_cast<std::string>(MasterManagerBase::get()->getMyShardId());
// scd_path = (bfs::path(scd_path)/bfs::path(DISPATCH_TEMP_DIR + myshard)).string();
//}
if (!isNeedDoLocal())
return false;
indexWorker_->index(scd_path, numdoc, result);
}
}
else
{
task_type task = boost::bind(&IndexTaskService::distributedIndex_, this, numdoc, scd_path);
JobScheduler::get()->addTask(task, bundleConfig_->collectionName_);
}
}
else
{
if (bundleConfig_->isMasterAggregator() &&
DistributeRequestHooker::get()->isRunningPrimary() && !DistributeFileSys::get()->isEnabled())
{
LOG(INFO) << "only local worker available, copy master scd files and indexing local.";
// search the directory for files
static const bfs::directory_iterator kItrEnd;
std::string masterScdPath = bundleConfig_->masterIndexSCDPath();
ScdParser parser(bundleConfig_->encoding_);
bfs::path bkDir = bfs::path(masterScdPath) / SCD_BACKUP_DIR;
LOG(INFO) << "creating directory : " << bkDir;
bfs::create_directories(bkDir);
for (bfs::directory_iterator itr(masterScdPath); itr != kItrEnd; ++itr)
{
if (bfs::is_regular_file(itr->status()))
{
std::string fileName = itr->path().filename().string();
if (parser.checkSCDFormat(fileName))
{
try {
bfs::copy_file(itr->path().string(), bundleConfig_->indexSCDPath() + "/" + fileName);
LOG(INFO) << "SCD File copy to local index path:" << fileName;
LOG(INFO) << "moving SCD files to directory " << bkDir;
bfs::rename(itr->path().string(), bkDir / itr->path().filename());
}
catch(const std::exception& e) {
LOG(WARNING) << "failed to move file: " << std::endl << fileName << std::endl << e.what();
}
}
else
{
LOG(WARNING) << "SCD File not valid " << fileName;
}
}
}
}
if (!isNeedDoLocal())
return false;
indexWorker_->index(scd_path, numdoc, result);
}
return result;
}
bool IndexTaskService::isNeedSharding()
{
if (bundleConfig_->isMasterAggregator() && indexAggregator_->isNeedDistribute() &&
DistributeRequestHooker::get()->isRunningPrimary())
{
return DistributeRequestHooker::get()->getHookType() == Request::FromDistribute;
}
return false;
}
bool IndexTaskService::isNeedDoLocal()
{
if (NodeManagerBase::get()->isDistributed() && !bundleConfig_->isWorkerNode())
{
LOG(INFO) << "local worker is disabled, no need do local work.";
return false;
}
return true;
}
bool IndexTaskService::reindex_from_scd(const std::vector<std::string>& scd_list, int64_t timestamp)
{
if (!isNeedDoLocal())
return false;
indexWorker_->disableSharding(false);
return indexWorker_->buildCollection(0, scd_list, timestamp);
}
bool IndexTaskService::index(boost::shared_ptr<DocumentManager>& documentManager, int64_t timestamp)
{
if (!isNeedDoLocal())
return false;
return indexWorker_->reindex(documentManager, timestamp);
}
bool IndexTaskService::optimizeIndex()
{
if (!isNeedDoLocal())
return false;
return indexWorker_->optimizeIndex();
}
bool IndexTaskService::createDocument(const Value& documentValue)
{
if (isNeedSharding())
{
if (!scdSharder_)
createScdSharder(scdSharder_);
SCDDoc scddoc;
IndexWorker::value2SCDDoc(documentValue, scddoc);
shardid_t shardid = scdSharder_->sharding(scddoc);
if (shardid != MasterManagerBase::get()->getMyShardId())
{
// need send to the shard.
return SendRequestToSharding(shardid);
}
}
return indexWorker_->createDocument(documentValue);
}
bool IndexTaskService::updateDocument(const Value& documentValue)
{
if (isNeedSharding())
{
if (!scdSharder_)
createScdSharder(scdSharder_);
SCDDoc scddoc;
IndexWorker::value2SCDDoc(documentValue, scddoc);
shardid_t shardid = scdSharder_->sharding(scddoc);
if (shardid != MasterManagerBase::get()->getMyShardId())
{
// need send to the shard.
return SendRequestToSharding(shardid);
}
}
return indexWorker_->updateDocument(documentValue);
}
bool IndexTaskService::updateDocumentInplace(const Value& request)
{
if (isNeedSharding())
{
if (!scdSharder_)
createScdSharder(scdSharder_);
SCDDoc scddoc;
IndexWorker::value2SCDDoc(request, scddoc);
shardid_t shardid = scdSharder_->sharding(scddoc);
if (shardid != MasterManagerBase::get()->getMyShardId())
{
// need send to the shard.
return SendRequestToSharding(shardid);
}
}
return indexWorker_->updateDocumentInplace(request);
}
bool IndexTaskService::destroyDocument(const Value& documentValue)
{
if (isNeedSharding())
{
if (!scdSharder_)
createScdSharder(scdSharder_);
SCDDoc scddoc;
IndexWorker::value2SCDDoc(documentValue, scddoc);
shardid_t shardid = scdSharder_->sharding(scddoc);
if (shardid != MasterManagerBase::get()->getMyShardId())
{
// need send to the shard.
return SendRequestToSharding(shardid);
}
}
return indexWorker_->destroyDocument(documentValue);
}
void IndexTaskService::flush()
{
indexWorker_->flush(true);
}
bool IndexTaskService::getIndexStatus(Status& status)
{
return indexWorker_->getIndexStatus(status);
}
bool IndexTaskService::isAutoRebuild()
{
return bundleConfig_->isAutoRebuild_;
}
std::string IndexTaskService::getScdDir(bool rebuild) const
{
if (rebuild)
return bundleConfig_->rebuildIndexSCDPath();
if( bundleConfig_->isMasterAggregator() )
return bundleConfig_->masterIndexSCDPath();
return bundleConfig_->indexSCDPath();
}
CollectionPath& IndexTaskService::getCollectionPath() const
{
return bundleConfig_->collPath_;
}
boost::shared_ptr<DocumentManager> IndexTaskService::getDocumentManager() const
{
return indexWorker_->getDocumentManager();
}
bool IndexTaskService::distributedIndex_(unsigned int numdoc, std::string scd_dir)
{
// notify that current master is indexing for the specified collection,
// we may need to check that whether other Master it's indexing this collection in some cases,
// or it's depends on Nginx router strategy.
MasterManagerBase::get()->registerIndexStatus(bundleConfig_->collectionName_, true);
if (!DistributeFileSys::get()->isEnabled())
{
scd_dir = bundleConfig_->masterIndexSCDPath();
}
bool ret = distributedIndexImpl_(
numdoc,
bundleConfig_->collectionName_,
scd_dir);
MasterManagerBase::get()->registerIndexStatus(bundleConfig_->collectionName_, false);
return ret;
}
bool IndexTaskService::distributedIndexImpl_(
unsigned int numdoc,
const std::string& collectionName,
const std::string& masterScdPath)
{
if (!scdSharder_)
{
if (!createScdSharder(scdSharder_))
{
LOG(ERROR) << "create scd sharder failed.";
return false;
}
if (!scdSharder_)
{
LOG(INFO) << "no scd sharder!";
return false;
}
}
if (!MasterManagerBase::get()->isAllShardNodeOK(bundleConfig_->col_shard_info_.shardList_))
{
LOG(ERROR) << "some of sharding node is not ready for index.";
return false;
}
std::string scd_dir = masterScdPath;
std::vector<std::string> outScdFileList;
//
// 1. dispatching scd to multiple nodes
if (!DistributeFileSys::get()->isEnabled())
{
boost::shared_ptr<ScdDispatcher> scdDispatcher(new BatchScdDispatcher(scdSharder_,
collectionName, DistributeFileSys::get()->isEnabled()));
if(!scdDispatcher->dispatch(outScdFileList, masterScdPath, bundleConfig_->indexSCDPath(), numdoc))
return false;
}
// 2. send index request to multiple nodes
LOG(INFO) << "start distributed indexing";
HookDistributeRequestForIndex();
if (!DistributeFileSys::get()->isEnabled())
scd_dir = bundleConfig_->indexSCDPath();
bool ret = true;
if (isNeedDoLocal())
{
// starting local index.
indexWorker_->index(scd_dir, numdoc, ret);
}
if (ret && !DistributeFileSys::get()->isEnabled())
{
bfs::path bkDir = bfs::path(masterScdPath) / SCD_BACKUP_DIR;
bfs::create_directories(bkDir);
LOG(INFO) << "moving " << outScdFileList.size() << " SCD files to directory " << bkDir;
for (size_t i = 0; i < outScdFileList.size(); i++)
{
try {
bfs::rename(outScdFileList[i], bkDir / bfs::path(outScdFileList[i]).filename());
}
catch(const std::exception& e) {
LOG(WARNING) << "failed to move file: " << std::endl << outScdFileList[i] << std::endl << e.what();
}
}
}
if (!isNeedDoLocal())
return false;
return ret;
}
bool IndexTaskService::createScdSharder(
boost::shared_ptr<ScdSharder>& scdSharder)
{
return indexWorker_->createScdSharder(scdSharder);
}
izenelib::util::UString::EncodingType IndexTaskService::getEncode() const
{
return bundleConfig_->encoding_;
}
const std::vector<shardid_t>& IndexTaskService::getShardidListForSearch()
{
return bundleConfig_->col_shard_info_.shardList_;
}
typedef std::map<shardid_t, std::vector<vnodeid_t> > ShardingTopologyT;
static void printSharding(const ShardingTopologyT& sharding_topology)
{
for(ShardingTopologyT::const_iterator cit = sharding_topology.begin();
cit != sharding_topology.end(); ++cit)
{
std::cout << "sharding : " << (uint32_t)cit->first << " is holding : ";
for (size_t i = 0; i < cit->second.size(); ++i)
{
std::cout << cit->second[i] << ", ";
}
std::cout << std::endl;
}
}
static bool removeSharding(const std::vector<shardid_t>& remove_sharding_nodes,
std::vector<shardid_t>& left_sharding_nodes,
size_t new_vnode_for_sharding,
ShardingTopologyT& current_sharding_topology,
std::map<vnodeid_t, std::pair<shardid_t, shardid_t> >& migrate_data_list,
std::vector<shardid_t>& sharding_map)
{
ShardingTopologyT remove_sharding_topo;
for (size_t i = 0; i < remove_sharding_nodes.size(); ++i)
{
remove_sharding_topo[remove_sharding_nodes[i]] = current_sharding_topology[remove_sharding_nodes[i]];
current_sharding_topology.erase(remove_sharding_nodes[i]);
}
if (current_sharding_topology.empty() || remove_sharding_topo.size() != remove_sharding_nodes.size())
{
return false;
}
ShardingTopologyT::iterator migrate_to_it = current_sharding_topology.begin();
for(ShardingTopologyT::iterator remove_it = remove_sharding_topo.begin();
remove_it != remove_sharding_topo.end(); ++remove_it)
{
size_t vnode_index = 0;
for (; vnode_index < remove_it->second.size();
++vnode_index)
{
vnodeid_t vid = remove_it->second[vnode_index];
migrate_data_list[vid] = std::pair<shardid_t, shardid_t>(remove_it->first, migrate_to_it->first);
LOG(INFO) << "vnode : " << vid << " will be moved from "
<< (uint32_t)remove_it->first << " to " << (uint32_t)migrate_to_it->first;
sharding_map[vid] = migrate_to_it->first;
migrate_to_it->second.push_back(vid);
if (migrate_to_it->second.size() > new_vnode_for_sharding)
{
// the new sharding node got enough data. move to next.
left_sharding_nodes.push_back(migrate_to_it->first);
++migrate_to_it;
if (migrate_to_it == current_sharding_topology.end())
{
ShardingTopologyT::iterator tmpit = remove_it;
if (vnode_index != (remove_it->second.size() - 1) ||
++tmpit != remove_sharding_topo.end() )
{
LOG(INFO) << "the remove sharding vnode can not totally migrate to others.";
return false;
}
break;
}
}
}
remove_it->second.clear();
}
while(migrate_to_it != current_sharding_topology.end())
{
left_sharding_nodes.push_back(migrate_to_it->first);
++migrate_to_it;
}
return true;
}
static void migrateSharding(const std::vector<shardid_t>& new_sharding_nodes,
size_t new_vnode_for_sharding,
ShardingTopologyT& current_sharding_topology,
ShardingTopologyT& new_sharding_topology,
std::map<vnodeid_t, std::pair<shardid_t, shardid_t> >& migrate_data_list,
std::vector<shardid_t>& sharding_map)
{
// move the vnode from src sharding node to dest sharding node.
size_t migrate_to = 0;
for(ShardingTopologyT::iterator it = current_sharding_topology.begin();
it != current_sharding_topology.end(); ++it)
{
size_t migrate_start = it->second.size() - 1;
while (migrate_to < new_sharding_nodes.size())
{
// this old sharding has not enough data so do not migrate from this node.
if (it->second.size() <= new_vnode_for_sharding)
break;
size_t old_start = migrate_start;
for (size_t vnode_index = old_start;
vnode_index > new_vnode_for_sharding;
--vnode_index)
{
vnodeid_t vid = it->second[vnode_index];
migrate_data_list[vid] = std::pair<shardid_t, shardid_t>(it->first, new_sharding_nodes[migrate_to]);
LOG(INFO) << "vnode : " << vid << " will be moved from " << (uint32_t)it->first << " to " << (uint32_t)new_sharding_nodes[migrate_to];
sharding_map[vid] = new_sharding_nodes[migrate_to];
new_sharding_topology[new_sharding_nodes[migrate_to]].push_back(vid);
--migrate_start;
if (new_sharding_topology[new_sharding_nodes[migrate_to]].size() >= new_vnode_for_sharding)
{
// the new sharding node got enough data. move to next.
++migrate_to;
if (migrate_to >= new_sharding_nodes.size())
break;
}
}
it->second.erase(it->second.begin() + migrate_start, it->second.end());
}
if (migrate_to >= new_sharding_nodes.size())
break;
}
}
bool IndexTaskService::doMigrateWork(bool removing,
const std::map<vnodeid_t, std::pair<shardid_t, shardid_t> >& migrate_data_list,
const std::vector<shardid_t>& migrate_nodes,
const std::string& map_file,
const std::vector<shardid_t>& current_sharding_map)
{
std::map<std::string, std::map<shardid_t, std::vector<vnodeid_t> > > migrate_from_to_list;
for(std::map<vnodeid_t, std::pair<shardid_t, shardid_t> >::const_iterator cit = migrate_data_list.begin();
cit != migrate_data_list.end(); ++cit)
{
std::string shardip = MasterManagerBase::get()->getShardNodeIP(cit->second.first);
if (shardip.empty())
{
LOG(ERROR) << "get source shard node ip error. " << cit->second.first;
return false;
}
migrate_from_to_list[shardip][cit->second.second].push_back(cit->first);
}
std::map<shardid_t, std::vector<std::string> > generated_insert_scds;
// the scds used for remove on the src node.
std::map<shardid_t, std::vector<std::string> > generated_del_scds;
bool ret = true;
ret = DistributeFileSyncMgr::get()->generateMigrateScds(bundleConfig_->collectionName_,
migrate_from_to_list,
generated_insert_scds,
generated_del_scds);
if (!ret)
{
LOG(ERROR) << "generate the migrate SCD files failed.";
return false;
}
// wait for all sharding nodes to finish their write queue.
if(!MasterManagerBase::get()->waitForMigrateReady(getShardidListForSearch()))
{
LOG(INFO) << " wait for migrate get ready failed.";
return false;
}
if (!removing)
{
// wait new sharding nodes to started.
if (!MasterManagerBase::get()->waitForNewShardingNodes(migrate_nodes))
{
LOG(INFO) << "wait for new sharding nodes to startup failed.";
return false;
}
}
if (!indexShardingNodes(generated_insert_scds))
{
return false;
}
if (!removing)
{
// wait for the new sharding nodes to finish indexing.
MasterManagerBase::get()->waitForMigrateIndexing(migrate_nodes);
}
indexShardingNodes(generated_del_scds);
MasterManagerBase::get()->waitForMigrateIndexing(getShardidListForSearch());
MapShardingStrategy::saveShardingMapToFile(map_file, current_sharding_map);
// update config will cause the collection to restart, so
// the IndexTaskService will be destructed.
updateShardingConfig(migrate_nodes, removing);
return true;
}
bool IndexTaskService::addNewShardingNodes(const std::vector<shardid_t>& new_sharding_nodes)
{
if (!bundleConfig_->isMasterAggregator())
{
LOG(INFO) << "change sharding node must be send to the master node.";
return false;
}
if (!sharding_strategy_ || sharding_strategy_->shard_cfg_.shardidList_.size() == 0)
{
LOG(ERROR) << "no sharding config.";
return false;
}
if (new_sharding_nodes.empty())
{
LOG(INFO) << "empty new sharding nodes.";
return false;
}
for (size_t i = 0; i < new_sharding_nodes.size(); ++i)
{
if (std::find(bundleConfig_->col_shard_info_.shardList_.begin(),
bundleConfig_->col_shard_info_.shardList_.end(),
new_sharding_nodes[i]) != bundleConfig_->col_shard_info_.shardList_.end())
{
LOG(ERROR) << "new sharding nodes exists in the old sharding config.";
return false;
}
}
size_t current_sharding_num = sharding_strategy_->shard_cfg_.shardidList_.size();
// reading current sharding config(include the load on these nodes),
// and determine which nodes need
// migrate which part of their data.
std::vector<shardid_t> current_sharding_map;
std::string map_file = sharding_map_dir_ + bundleConfig_->collectionName_;
MapShardingStrategy::readShardingMapFile(map_file, current_sharding_map);
if (bundleConfig_->col_shard_info_.shardList_.size() == 1)
{
if (current_sharding_map.empty())
{
current_sharding_map.resize(MapShardingStrategy::MAX_MAP_SIZE, bundleConfig_->col_shard_info_.shardList_[0]);
}
}
if (current_sharding_map.empty())
{
LOG(ERROR) << "sharding map is empty!";
return false;
}
if (current_sharding_map.size() < current_sharding_num + new_sharding_nodes.size())
{
LOG(ERROR) << "the actual sharding num is larger than virtual nodes." << current_sharding_map.size();
return false;
}
size_t current_vnode_for_sharding = current_sharding_map.size()/current_sharding_num;
size_t new_vnode_for_sharding = current_sharding_map.size()/(current_sharding_num + new_sharding_nodes.size());
ShardingTopologyT current_sharding_topology;
for (size_t i = 0; i < current_sharding_map.size(); ++i)
{
current_sharding_topology[current_sharding_map[i]].push_back(i);
}
LOG(INFO) << "Before migrate, the average vnodes for each sharding is: " << current_vnode_for_sharding
<< " and sharding topology is : ";
printSharding(current_sharding_topology);
// move the vnode from src sharding node to dest sharding node.
std::map<vnodeid_t, std::pair<shardid_t, shardid_t> > migrate_data_list;
ShardingTopologyT new_sharding_topology;
migrateSharding(new_sharding_nodes, new_vnode_for_sharding,
current_sharding_topology,
new_sharding_topology, migrate_data_list,
current_sharding_map);
LOG(INFO) << "After migrate, the average vnodes for each sharding will be: " << new_vnode_for_sharding
<< " and sharding topology will be : ";
printSharding(current_sharding_topology);
printSharding(new_sharding_topology);
// this will disallow any new write. This may fail if other migrate
// running or not all sharding nodes alive.
if(!MasterManagerBase::get()->notifyAllShardingBeginMigrate(getShardidListForSearch()))
{
return false;
}
bool ret = doMigrateWork(false, migrate_data_list, new_sharding_nodes,
map_file, current_sharding_map);
// allow new write running.
MasterManagerBase::get()->notifyAllShardingEndMigrate();
return ret;
}
bool IndexTaskService::indexShardingNodes(const std::map<shardid_t, std::vector<std::string> >& generated_migrate_scds)
{
std::string tmp_migrate_scd_dir = DistributeFileSys::get()->getFixedCopyPath("/migrate_scds/"
+ bundleConfig_->collectionName_ + "/" + boost::lexical_cast<std::string>(Utilities::createTimeStamp()));
bfs::create_directories(DistributeFileSys::get()->getDFSPathForLocal(tmp_migrate_scd_dir));
std::map<shardid_t, std::vector<std::string> >::const_iterator cit = generated_migrate_scds.begin();
for (; cit != generated_migrate_scds.end(); ++cit)
{
LOG(INFO) << "prepare scd files for sharding node : " << (uint32_t)cit->first;
std::string shard_scd_dir = tmp_migrate_scd_dir + "/shard" + getShardidStr(cit->first) + "/";
bfs::create_directories(DistributeFileSys::get()->getDFSPathForLocal(shard_scd_dir));
for (size_t i = 0; i < cit->second.size(); ++i)
{
LOG(INFO) << "add migrate scd : " << cit->second[i];
bfs::rename(DistributeFileSys::get()->getDFSPathForLocal(cit->second[i]),
bfs::path(DistributeFileSys::get()->getDFSPathForLocal(shard_scd_dir))/(bfs::path(cit->second[i]).filename()));
}
// send index command.
std::string json_req = "{\"collection\":\"" + bundleConfig_->collectionName_
+ "\",\"index_scd_path\":\"" + shard_scd_dir
+ "\",\"disable_sharding\":2"
+ ",\"header\":{\"action\":\"index\",\"controller\":\"commands\"},\"uri\":\"commands/index\"}";
LOG(INFO) << "send request : " << json_req;
std::vector<shardid_t> shardid;
shardid.push_back(cit->first);
if (!MasterManagerBase::get()->pushWriteReqToShard(json_req, shardid, true, true))
{
LOG(WARNING) << "push write failed.";
return false;
}
}
return true;
}
void IndexTaskService::updateShardingConfig(const std::vector<shardid_t>& new_sharding_nodes, bool removing)
{
std::string sharding_cfg;
std::vector<shardid_t> curr_shard_nodes = getShardidListForSearch();
if (!removing)
{
for (size_t i = 0; i < curr_shard_nodes.size(); ++i)
{
if (sharding_cfg.empty())
sharding_cfg = getShardidStr(curr_shard_nodes[i]);
else
sharding_cfg += "," + getShardidStr(curr_shard_nodes[i]);
}
}
for (size_t i = 0; i < new_sharding_nodes.size(); ++i)
{
if (sharding_cfg.empty())
sharding_cfg = getShardidStr(new_sharding_nodes[i]);
else
sharding_cfg += "," + getShardidStr(new_sharding_nodes[i]);
}
LOG(INFO) << "new sharding cfg is : " << sharding_cfg;
//
// send index command.
std::string json_req = "{\"collection\":\"" + bundleConfig_->collectionName_
+ "\",\"new_sharding_cfg\":\"" + sharding_cfg
+ "\",\"header\":{\"action\":\"update_sharding_conf\",\"controller\":\"collection\"},\"uri\":\"collection/update_sharding_conf\"}";
LOG(INFO) << "send request : " << json_req;
if (!removing)
MasterManagerBase::get()->pushWriteReqToShard(json_req, new_sharding_nodes, true, true);
if (bundleConfig_->isMasterAggregator() && !bundleConfig_->isWorkerNode())
{
curr_shard_nodes.push_back(MasterManagerBase::get()->getMyShardId());
}
MasterManagerBase::get()->pushWriteReqToShard(json_req, curr_shard_nodes, true, true);
}
bool IndexTaskService::generateMigrateSCD(const std::map<shardid_t, std::vector<vnodeid_t> >& vnode_list,
std::map<shardid_t, std::string>& generated_insert_scds,
std::map<shardid_t, std::string>& generated_del_scds)
{
return indexWorker_->generateMigrateSCD(vnode_list, generated_insert_scds, generated_del_scds);
}
bool IndexTaskService::removeShardingNodes(const std::vector<shardid_t>& remove_sharding_nodes)
{
if (!bundleConfig_->isMasterAggregator())
{
LOG(INFO) << "change sharding node must be send to the master node.";
return false;
}
if (!sharding_strategy_ || sharding_strategy_->shard_cfg_.shardidList_.size() == 0)
{
LOG(ERROR) << "no sharding config.";
return false;
}
if (remove_sharding_nodes.empty())
{
LOG(INFO) << "empty sharding nodes.";
return false;
}
size_t current_sharding_num = sharding_strategy_->shard_cfg_.shardidList_.size();
if (current_sharding_num == 1)
{
LOG(INFO) << "The last one sharding node can not be removed.";
return false;
}
if (remove_sharding_nodes.size() >= current_sharding_num)
{
LOG(INFO) << "You can not remove all sharding nodes.";
return false;
}
for (size_t i = 0; i < remove_sharding_nodes.size(); ++i)
{
if (std::find(bundleConfig_->col_shard_info_.shardList_.begin(),
bundleConfig_->col_shard_info_.shardList_.end(),
remove_sharding_nodes[i]) == bundleConfig_->col_shard_info_.shardList_.end())
{
LOG(ERROR) << "removing sharding node does not exist in the old sharding config.";
return false;
}
}
std::vector<shardid_t> current_sharding_map;
std::string map_file = sharding_map_dir_ + bundleConfig_->collectionName_;
MapShardingStrategy::readShardingMapFile(map_file, current_sharding_map);
if (current_sharding_map.empty())
{
LOG(ERROR) << "sharding map is empty!";
return false;
}
size_t current_vnode_for_sharding = current_sharding_map.size()/current_sharding_num;
size_t new_vnode_for_sharding = current_sharding_map.size()/(current_sharding_num - remove_sharding_nodes.size());
ShardingTopologyT current_sharding_topology;
for (size_t i = 0; i < current_sharding_map.size(); ++i)
{
current_sharding_topology[current_sharding_map[i]].push_back(i);
}
LOG(INFO) << "Before migrate, the average vnodes for each sharding is: " << current_vnode_for_sharding
<< " and sharding topology is : ";
printSharding(current_sharding_topology);
std::map<vnodeid_t, std::pair<shardid_t, shardid_t> > migrate_data_list;
ShardingTopologyT new_sharding_topology;
std::vector<shardid_t> left_sharding_nodes;
bool ret = removeSharding(remove_sharding_nodes, left_sharding_nodes,
new_vnode_for_sharding,
current_sharding_topology,
migrate_data_list,
current_sharding_map);
if (!ret || left_sharding_nodes.empty())
{
LOG(INFO) << "removing nodes are wrong.";
return false;
}
LOG(INFO) << "After migrate, the average vnodes for each sharding will be: " << new_vnode_for_sharding
<< " and sharding topology will be : ";
printSharding(current_sharding_topology);
if(!MasterManagerBase::get()->notifyAllShardingBeginMigrate(getShardidListForSearch()))
{
return false;
}
ret = doMigrateWork(true, migrate_data_list, left_sharding_nodes,
map_file, current_sharding_map);
// allow new write running.
MasterManagerBase::get()->notifyAllShardingEndMigrate();
return ret;
}
}
| 37.158115 | 154 | 0.620526 | izenecloud |
515437bc433e9c841957d5e61e63a18afde2dd41 | 2,903 | cc | C++ | framework/memory/memory_manager.cc | ans-hub/gdm_framework | 4218bb658d542df2c0568c4d3aac813cd1f18e1b | [
"MIT"
] | 1 | 2020-12-30T23:50:01.000Z | 2020-12-30T23:50:01.000Z | framework/memory/memory_manager.cc | ans-hub/gdm_framework | 4218bb658d542df2c0568c4d3aac813cd1f18e1b | [
"MIT"
] | null | null | null | framework/memory/memory_manager.cc | ans-hub/gdm_framework | 4218bb658d542df2c0568c4d3aac813cd1f18e1b | [
"MIT"
] | null | null | null | // *************************************************************
// File: memory_manager.cc
// Author: Novoselov Anton @ 2018
// URL: https://github.com/ans-hub/gdm_framework
// *************************************************************
#include "memory_manager.h"
#include <memory/memory_tracker.h>
#include <memory/defines.h>
#include <math/general.h>
#include <system/assert_utils.h>
#if defined (_WIN32)
#include <malloc.h>
#else
#include <cstdlib>
#endif
// --public
void* gdm::MemoryManager::Allocate(size_t bytes, MemoryTagValue tag)
{
return AllocateAligned(bytes, GetDefaultAlignment(), tag);
}
void* gdm::MemoryManager::AllocateAligned(size_t bytes, size_t align, MemoryTagValue tag)
{
align = math::Max(align, GetDefaultAlignment());
ASSERTF(math::IsPowerOfTwo(align), "Alignment %zu is not power of 2", align);
#if defined (_WIN32)
void* ptr = _aligned_malloc(bytes, align);
#else
void* ptr = std::aligned_alloc(size, align);
#endif
MemoryTracker::GetInstance().AddUsage(tag, GetPointerSize(ptr, align));
return ptr;
}
void* gdm::MemoryManager::Reallocate(void* ptr, size_t new_bytes, MemoryTagValue tag)
{
return ReallocateAligned(ptr, new_bytes, GetDefaultAlignment(), tag);
}
void* gdm::MemoryManager::ReallocateAligned(void* ptr, size_t new_bytes, size_t align, MemoryTagValue tag)
{
align = math::Max(align, GetDefaultAlignment());
ASSERTF(math::IsPowerOfTwo(align), "Alignment %zu is not power of 2", align);
#if defined (_WIN32)
MemoryTracker::GetInstance().SubUsage(tag, GetPointerSize(ptr, align));
void* new_ptr = _aligned_realloc(ptr, new_bytes, align);
MemoryTracker::GetInstance().AddUsage(tag, GetPointerSize(new_ptr, align));
#else
void* new_ptr = Allocate(new_bytes, align);
memcpy(new_mem, ptr, GetPointerSize(ptr, align));
Deallocate(ptr, align);
#endif
MemoryTracker::GetInstance().AddUsage(tag, GetPointerSize(new_ptr, align));
return new_ptr;
}
void gdm::MemoryManager::Deallocate(void* ptr, MemoryTagValue tag)
{
DeallocateAligned(ptr, GetDefaultAlignment(), tag);
}
void gdm::MemoryManager::DeallocateAligned(void* ptr, size_t align, MemoryTagValue tag)
{
MemoryTracker::GetInstance().SubUsage(tag, GetPointerSize(ptr, align));
#if defined (_WIN32)
_aligned_free(ptr);
#else
std::free(mem);
#endif
}
size_t gdm::MemoryManager::GetPointerSize(void* ptr, size_t align)
{
if (!ptr)
return 0;
align = math::Max(align, GetDefaultAlignment());
ASSERTF(math::IsPowerOfTwo(align), "Alignment %zu is not power of 2", align);
#if defined(_WIN32)
return _aligned_msize(ptr, align, 0);
#else
return malloc_usabe_size(ptr);
#endif
}
auto gdm::MemoryManager::GetTagUsage(MemoryTagValue tag) -> size_t
{
return MemoryTracker::GetInstance().GetTagUsage(tag);
}
auto gdm::MemoryManager::GetTagName(MemoryTagValue tag) -> const char*
{
return MemoryTracker::GetInstance().GetTagName(tag);
}
| 27.647619 | 106 | 0.704099 | ans-hub |
5154c545d113704b907231f66fae21a48063d0ce | 6,134 | cpp | C++ | benchmarks/src/cuda/parboil/benchmarks/mri-gridding/src/opencl_base/sort.cpp | abca3210/gpgpu-sim_simulations | bf7eaf6e49bf357e0cc2ecfe7e0ff446d88e2691 | [
"BSD-2-Clause"
] | 28 | 2017-09-06T21:12:53.000Z | 2022-02-16T01:01:55.000Z | benchmarks/src/cuda/parboil/benchmarks/mri-gridding/src/opencl_base/sort.cpp | abca3210/gpgpu-sim_simulations | bf7eaf6e49bf357e0cc2ecfe7e0ff446d88e2691 | [
"BSD-2-Clause"
] | 1 | 2019-10-02T13:56:24.000Z | 2019-10-02T13:56:24.000Z | benchmarks/src/cuda/parboil/benchmarks/mri-gridding/src/opencl_base/sort.cpp | abca3210/gpgpu-sim_simulations | bf7eaf6e49bf357e0cc2ecfe7e0ff446d88e2691 | [
"BSD-2-Clause"
] | 34 | 2017-12-14T01:06:58.000Z | 2022-02-14T09:40:35.000Z | /***************************************************************************
*
* (C) Copyright 2010 The Board of Trustees of the
* University of Illinois
* All Rights Reserved
*
***************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include "scanLargeArray.h"
#include "OpenCL_common.h"
#define UINT32_MAX 4294967295
#define BITS 4
#define LNB 4
#define SORT_BS 256
void sort (int numElems, unsigned int max_value, cl_mem* &dkeysPtr, cl_mem* &dvaluesPtr, cl_mem* &dkeys_oPtr, cl_mem* &dvalues_oPtr, cl_context *clContextPtr, cl_command_queue clCommandQueue, const cl_device_id clDevice, size_t *workItemSizes){
size_t block[1] = { SORT_BS };
size_t grid[1] = { ((numElems+4*SORT_BS-1)/(4*SORT_BS)) * block[0] };
unsigned int iterations = 0;
while(max_value > 0){
max_value >>= BITS;
iterations++;
}
cl_int ciErrNum;
cl_context clContext = *clContextPtr;
cl_program sort_program;
cl_kernel splitSort;
cl_kernel splitRearrange;
cl_mem dhisto;
cl_mem* original = dkeysPtr;
unsigned int *zeroData;
zeroData = (unsigned int *) calloc( (1<<BITS)*grid[0], sizeof(unsigned int) );
if (zeroData == NULL) { fprintf(stderr, "Could not allocate host memory! (%s: %d)\n", __FILE__, __LINE__); exit(1); }
dhisto = clCreateBuffer(clContext, CL_MEM_COPY_HOST_PTR, (1<<BITS)*((numElems+4*SORT_BS-1)/(4*SORT_BS))*sizeof(unsigned int), zeroData, &ciErrNum); OCL_ERRCK_VAR(ciErrNum);
free(zeroData);
//char compileOptions[256];
// -cl-nv-verbose // Provides register info for NVIDIA devices
// Set all Macros referenced by kernels
/* sprintf(compileOptions, "\
-D CUTOFF2_VAL=%f -D CUTOFF_VAL=%f\
-D GRIDSIZE_VAL1=%d -D GRIDSIZE_VAL2=%d -D GRIDSIZE_VAL3=%d\
-D SIZE_XY_VAL=%d -D ONE_OVER_CUTOFF2_VAL=%f",
cutoff2, cutoff,
params.gridSize[0], params.gridSize[1], params.gridSize[2],
size_xy, _1overCutoff2
);*/
size_t program_length;
const char *source_path = "src/opencl_base/sort.cl";
char *source;
// Dynamically allocate buffer for source
source = oclLoadProgSource(source_path, "", &program_length);
if(!source) {
fprintf(stderr, "Could not load program source (%s)\n", __FILE__); exit(1);
}
sort_program = clCreateProgramWithSource(clContext, 1, (const char **)&source, &program_length, &ciErrNum);
OCL_ERRCK_VAR(ciErrNum);
free(source);
OCL_ERRCK_RETVAL ( clBuildProgram(sort_program, 1, &clDevice, NULL /*compileOptions*/, NULL, NULL) );
// Uncomment to get build log from compiler for debugging
char *build_log;
size_t ret_val_size;
ciErrNum = clGetProgramBuildInfo(sort_program, clDevice, CL_PROGRAM_BUILD_LOG, 0, NULL, &ret_val_size); OCL_ERRCK_VAR(ciErrNum);
build_log = (char *)malloc(ret_val_size+1);
ciErrNum = clGetProgramBuildInfo(sort_program, clDevice, CL_PROGRAM_BUILD_LOG, ret_val_size, build_log, NULL);
OCL_ERRCK_VAR(ciErrNum);
// to be carefully, terminate with \0
// there's no information in the reference whether the string is 0 terminated or not
build_log[ret_val_size] = '\0';
fprintf(stderr, "%s\n", build_log );
splitSort = clCreateKernel(sort_program, "splitSort", &ciErrNum);
OCL_ERRCK_VAR(ciErrNum);
splitRearrange = clCreateKernel(sort_program, "splitRearrange", &ciErrNum);
OCL_ERRCK_VAR(ciErrNum);
OCL_ERRCK_RETVAL( clSetKernelArg(splitSort, 0, sizeof(int), &numElems) );
OCL_ERRCK_RETVAL( clSetKernelArg(splitSort, 2, sizeof(cl_mem), (void *)dkeysPtr) );
OCL_ERRCK_RETVAL( clSetKernelArg(splitSort, 3, sizeof(cl_mem), (void *)dvaluesPtr) );
OCL_ERRCK_RETVAL( clSetKernelArg(splitSort, 4, sizeof(cl_mem), (void *)&dhisto) );
OCL_ERRCK_RETVAL( clSetKernelArg(splitRearrange, 0, sizeof(int), &numElems) );
OCL_ERRCK_RETVAL( clSetKernelArg(splitRearrange, 2, sizeof(cl_mem), (void *)dkeysPtr) );
OCL_ERRCK_RETVAL( clSetKernelArg(splitRearrange, 3, sizeof(cl_mem), (void *)dkeys_oPtr) );
OCL_ERRCK_RETVAL( clSetKernelArg(splitRearrange, 4, sizeof(cl_mem), (void *)dvaluesPtr) );
OCL_ERRCK_RETVAL( clSetKernelArg(splitRearrange, 5, sizeof(cl_mem), (void *)dvalues_oPtr) );
OCL_ERRCK_RETVAL( clSetKernelArg(splitRearrange, 6, sizeof(cl_mem), (void *)&dhisto) );
for (int i=0; i<iterations; i++){
OCL_ERRCK_RETVAL( clSetKernelArg(splitSort, 1, sizeof(int), &i) );
OCL_ERRCK_RETVAL( clSetKernelArg(splitSort, 2, sizeof(cl_mem), (void *)dkeysPtr) );
OCL_ERRCK_RETVAL( clSetKernelArg(splitSort, 3, sizeof(cl_mem), (void *)dvaluesPtr) );
OCL_ERRCK_RETVAL ( clEnqueueNDRangeKernel(clCommandQueue, splitSort, 1, 0,
grid, block, 0, 0, 0) );
scanLargeArray(((numElems+4*SORT_BS-1)/(4*SORT_BS))*(1<<BITS), dhisto, clContext, clCommandQueue, clDevice, workItemSizes);
OCL_ERRCK_RETVAL( clSetKernelArg(splitRearrange, 1, sizeof(int), &i ) );
OCL_ERRCK_RETVAL( clSetKernelArg(splitRearrange, 2, sizeof(cl_mem), (void *)dkeysPtr) );
OCL_ERRCK_RETVAL( clSetKernelArg(splitRearrange, 3, sizeof(cl_mem), (void *)dkeys_oPtr) );
OCL_ERRCK_RETVAL( clSetKernelArg(splitRearrange, 4, sizeof(cl_mem), (void *)dvaluesPtr) );
OCL_ERRCK_RETVAL( clSetKernelArg(splitRearrange, 5, sizeof(cl_mem), (void *)dvalues_oPtr) );
OCL_ERRCK_RETVAL ( clEnqueueNDRangeKernel(clCommandQueue, splitRearrange, 1, 0,
grid, block, 0, 0, 0) );
cl_mem* temp = dkeysPtr;
dkeysPtr = dkeys_oPtr;
dkeys_oPtr = temp;
temp = dvaluesPtr;
dvaluesPtr = dvalues_oPtr;
dvalues_oPtr = temp;
}
OCL_ERRCK_RETVAL ( clReleaseKernel(splitSort) );
OCL_ERRCK_RETVAL ( clReleaseKernel(splitRearrange) );
OCL_ERRCK_RETVAL ( clReleaseMemObject(*dkeys_oPtr) );
OCL_ERRCK_RETVAL ( clReleaseMemObject(*dvalues_oPtr) );
OCL_ERRCK_RETVAL ( clReleaseMemObject(dhisto) );
OCL_ERRCK_RETVAL ( clReleaseProgram(sort_program) );
}
| 40.622517 | 244 | 0.66971 | abca3210 |
51557d33621fe7cfed967ce3a7394e8251002639 | 3,118 | hpp | C++ | KFPlugin/KFDeployServer/KFDeployServerModule.hpp | 282951387/KFrame | 5d6e953f7cc312321c36632715259394ca67144c | [
"Apache-2.0"
] | 1 | 2021-04-26T09:31:32.000Z | 2021-04-26T09:31:32.000Z | KFPlugin/KFDeployServer/KFDeployServerModule.hpp | 282951387/KFrame | 5d6e953f7cc312321c36632715259394ca67144c | [
"Apache-2.0"
] | null | null | null | KFPlugin/KFDeployServer/KFDeployServerModule.hpp | 282951387/KFrame | 5d6e953f7cc312321c36632715259394ca67144c | [
"Apache-2.0"
] | null | null | null | #ifndef __KF_DEPLOY_SERVER_MODULE_H__
#define __KF_DEPLOY_SERVER_MODULE_H__
/************************************************************************
// @Module : 部署Server
// @Author : __凌_痕__
// @QQ : 7969936
// @Mail : lori227@qq.com
// @Date : 2018-7-2
************************************************************************/
#include "KFProtocol/KFProtocol.h"
#include "KFDeployServerInterface.h"
#include "KFMySQL/KFMySQLInterface.h"
#include "KFMessage/KFMessageInterface.h"
#include "KFDelayed/KFDelayedInterface.h"
#include "KFTcpServer/KFTcpServerInterface.h"
#include "KFHttpServer/KFHttpServerInterface.h"
#include "KFHttpClient/KFHttpClientInterface.h"
namespace KFrame
{
class KFAgentData
{
public:
KFAgentData()
{
_port = 0;
status = 0;
}
public:
// 服务器id
std::string _agent_id;
// 局域网地址
std::string _local_ip;
// 名字
std::string _name;
// 类型
std::string _type;
// 服务
std::string _service;
// 端口
uint32 _port;
// 状态
uint32 status;
};
class KFDeployServerModule : public KFDeployServerInterface
{
public:
KFDeployServerModule() = default;
~KFDeployServerModule() = default;
// 逻辑
virtual void BeforeRun();
virtual void PrepareRun();
// 关闭
virtual void ShutDown();
protected:
// 连接丢失
__KF_NET_EVENT_FUNCTION__( OnServerLostClient );
// 启动服务器
__KF_HTTP_FUNCTION__( HandleDeployCommand );
// 部署命令
__KF_DELAYED_FUNCTION__( OnHttpDeployCommandToAgent );
__KF_DELAYED_FUNCTION__( OnTcpDeployCommandToAgent );
protected:
// 注册Agent
__KF_MESSAGE_FUNCTION__( HandleRegisterAgentToServerReq );
// 执行sql语句
__KF_MESSAGE_FUNCTION__( HandleExecuteMySQLReq );
// 查询sql语句
__KF_MESSAGE_FUNCTION__( HandleQueryMySQLReq );
// 查询sql语句
__KF_MESSAGE_FUNCTION__( HandleDeleteMySQLReq );
// 部署命令
__KF_MESSAGE_FUNCTION__( HandleDeployToolCommandReq );
// 日志
__KF_MESSAGE_FUNCTION__( HandleDeployLogToServerReq );
// 查询toolid
__KF_MESSAGE_FUNCTION__( HandleDeployQueryToolIdReq );
protected:
// 更新Agnet状态
void UpdateAgentToDatabase( KFAgentData* kfagent, uint32 status );
// 回发日志消息
template<typename... P>
void LogDeploy( uint64 agentid, const char* myfmt, P&& ... args )
{
auto msg = __FORMAT__( myfmt, std::forward<P>( args )... );
return SendLogMessage( agentid, msg );
}
void SendLogMessage( uint64 agentid, const std::string& msg );
private:
KFMySQLDriver* _mysql_driver{ nullptr };
// Agent列表
KFHashMap< std::string, const std::string&, KFAgentData > _agent_list;
// 定时任务id
uint64 _delayed_id = 0u;
// web列表
std::string _web_deploy_url;
};
}
#endif | 23.801527 | 78 | 0.570558 | 282951387 |
5156bd17cb03baca910c1161afe5ffce9114d280 | 17,113 | cpp | C++ | src/ply_io.cpp | janzill/displaz | c23b2e8202ffb6831fe6fb63b91a590b01a541aa | [
"BSD-3-Clause"
] | null | null | null | src/ply_io.cpp | janzill/displaz | c23b2e8202ffb6831fe6fb63b91a590b01a541aa | [
"BSD-3-Clause"
] | null | null | null | src/ply_io.cpp | janzill/displaz | c23b2e8202ffb6831fe6fb63b91a590b01a541aa | [
"BSD-3-Clause"
] | 1 | 2021-03-05T09:33:21.000Z | 2021-03-05T09:33:21.000Z | // Copyright 2015, Christopher J. Foster and the other displaz contributors.
// Use of this code is governed by the BSD-style license found in LICENSE.txt
#include "ply_io.h"
#include <cstdint>
#include "QtLogger.h"
//------------------------------------------------------------------------------
// Utilities for interfacing with rply
/// Callback handler for reading ply data into a point field using rply
class PlyFieldLoader
{
public:
PlyFieldLoader(GeomField& field)
: m_field(&field),
m_pointIndex(0),
m_componentReadCount(0),
m_isPositionField(field.name == "position")
{ }
/// rply callback to accept a single element of a point field
static int rplyCallback(p_ply_argument argument)
{
void* pinfo = 0;
long idata = 0;
ply_get_argument_user_data(argument, &pinfo, &idata);
double value = ply_get_argument_value(argument);
return pinfo ? ((PlyFieldLoader*)pinfo)->writeValue(idata, value) : 0;
}
/// Accept a single element of a point field from the ply file
int writeValue(int componentIndex, double value)
{
if (m_isPositionField)
{
// Remove fixed offset using first value read.
if (m_pointIndex == 0)
m_offset[componentIndex] = value;
value -= m_offset[componentIndex];
}
// Set data value depending on type
size_t idx = m_pointIndex*m_field->spec.count + componentIndex;
switch(m_field->spec.type)
{
case TypeSpec::Int:
switch(m_field->spec.elsize)
{
case 1: m_field->as<int8_t>()[idx] = (int8_t)value; break;
case 2: m_field->as<int16_t>()[idx] = (int16_t)value; break;
case 4: m_field->as<int32_t>()[idx] = (int32_t)value; break;
}
break;
case TypeSpec::Uint:
switch(m_field->spec.elsize)
{
case 1: m_field->as<uint8_t>()[idx] = (uint8_t)value; break;
case 2: m_field->as<uint16_t>()[idx] = (uint16_t)value; break;
case 4: m_field->as<uint32_t>()[idx] = (uint32_t)value; break;
}
break;
case TypeSpec::Float:
switch(m_field->spec.elsize)
{
case 4: m_field->as<float>()[idx] = (float)value; break;
case 8: m_field->as<double>()[idx] = (double)value; break;
}
break;
default:
assert(0 && "Unknown type encountered");
}
// Keep track of which point we're on
++m_componentReadCount;
if (m_componentReadCount == m_field->spec.count)
{
++m_pointIndex;
m_componentReadCount = 0;
}
return 1;
}
V3d offset() const { return V3d(m_offset[0], m_offset[1], m_offset[2]); }
private:
GeomField* m_field;
size_t m_pointIndex;
int m_componentReadCount;
bool m_isPositionField;
double m_offset[3];
};
/// Get TypeSpec type info from associated rply type
void plyTypeToPointFieldType(e_ply_type& plyType, TypeSpec::Type& type, int& elsize)
{
switch(plyType)
{
case PLY_INT8: case PLY_CHAR: type = TypeSpec::Int; elsize = 1; break;
case PLY_INT16: case PLY_SHORT: type = TypeSpec::Int; elsize = 2; break;
case PLY_INT32: case PLY_INT: type = TypeSpec::Int; elsize = 4; break;
case PLY_UINT8: case PLY_UCHAR: type = TypeSpec::Uint; elsize = 1; break;
case PLY_UINT16: case PLY_USHORT: type = TypeSpec::Uint; elsize = 2; break;
case PLY_UIN32: case PLY_UINT: type = TypeSpec::Uint; elsize = 4; break;
case PLY_FLOAT32: case PLY_FLOAT: type = TypeSpec::Float; elsize = 4; break;
case PLY_FLOAT64: case PLY_DOUBLE: type = TypeSpec::Float; elsize = 8; break;
default: assert(0 && "Unknown ply type");
}
}
//------------------------------------------------------------------------------
// Utilities for loading point fields from the "vertex" element
/// Find "vertex" element in ply file
p_ply_element findVertexElement(p_ply ply, size_t& npoints)
{
for (p_ply_element elem = ply_get_next_element(ply, NULL);
elem != NULL; elem = ply_get_next_element(ply, elem))
{
const char* name = 0;
long ninstances = 0;
if (!ply_get_element_info(elem, &name, &ninstances))
continue;
//tfm::printf("element %s, ninstances = %d\n", name, ninstances);
if (strcmp(name, "vertex") == 0)
{
npoints = ninstances;
return elem;
}
}
return NULL;
}
/// Mapping from ply field names to internal (name,index)
struct PlyPointField
{
std::string displazName;
int componentIndex;
TypeSpec::Semantics semantics;
std::string plyName;
e_ply_type plyType;
};
/// Parse ply point properties, and recognize standard names
static std::vector<PlyPointField> parsePlyPointFields(p_ply_element vertexElement)
{
// List of some fields which might be found in a .ply file and mappings to
// displaz field groups. Note that there's no standard!
PlyPointField standardFields[] = {
{"position", 0, TypeSpec::Vector, "x", PLY_FLOAT},
{"position", 1, TypeSpec::Vector, "y", PLY_FLOAT},
{"position", 2, TypeSpec::Vector, "z", PLY_FLOAT},
{"color", 0, TypeSpec::Color , "red", PLY_UINT8},
{"color", 1, TypeSpec::Color , "green", PLY_UINT8},
{"color", 2, TypeSpec::Color , "blue", PLY_UINT8},
{"color", 0, TypeSpec::Color , "r", PLY_UINT8},
{"color", 1, TypeSpec::Color , "g", PLY_UINT8},
{"color", 2, TypeSpec::Color , "b", PLY_UINT8},
{"normal", 0, TypeSpec::Vector, "nx", PLY_FLOAT},
{"normal", 1, TypeSpec::Vector, "ny", PLY_FLOAT},
{"normal", 2, TypeSpec::Vector, "nz", PLY_FLOAT},
};
QRegExp vec3ComponentPattern("(.*)_?([xyz])");
QRegExp arrayComponentPattern("(.*)\\[([0-9]+)\\]");
size_t numStandardFields = sizeof(standardFields)/sizeof(standardFields[0]);
std::vector<PlyPointField> fieldInfo;
for (p_ply_property prop = ply_get_next_property(vertexElement, NULL);
prop != NULL; prop = ply_get_next_property(vertexElement, prop))
{
const char* propName = 0;
e_ply_type propType;
if (!ply_get_property_info(prop, &propName, &propType, NULL, NULL))
continue;
if (propType == PLY_LIST)
{
g_logger.warning("Ignoring list property %s in ply file", propName);
continue;
}
bool isStandardField = false;
for (size_t i = 0; i < numStandardFields; ++i)
{
if (iequals(standardFields[i].plyName, propName))
{
fieldInfo.push_back(standardFields[i]);
fieldInfo.back().plyType = propType;
fieldInfo.back().plyName = propName; // ensure correct string case
isStandardField = true;
break;
}
}
if (!isStandardField)
{
// Try to guess whether this is one of several components - if so,
// it will be turned into an array type (such as a vector)
std::string displazName = propName;
int index = 0;
TypeSpec::Semantics semantics = TypeSpec::Array;
if (vec3ComponentPattern.exactMatch(propName))
{
displazName = vec3ComponentPattern.cap(1).toStdString();
index = vec3ComponentPattern.cap(2)[0].toLatin1() - 'x';
semantics = TypeSpec::Vector;
}
else if(arrayComponentPattern.exactMatch(propName))
{
displazName = arrayComponentPattern.cap(1).toStdString();
index = arrayComponentPattern.cap(2).toInt();
}
PlyPointField field = {displazName, index, semantics, propName, propType};
fieldInfo.push_back(field);
}
}
return fieldInfo;
}
/// Order PlyPointField by displaz field name and component index
bool displazFieldComparison(const PlyPointField& a, const PlyPointField& b)
{
if (a.displazName != b.displazName)
return a.displazName < b.displazName;
if (a.componentIndex != b.componentIndex)
return a.componentIndex < b.componentIndex;
return a.semantics < b.semantics;
}
bool loadPlyVertexProperties(QString fileName, p_ply ply, p_ply_element vertexElement,
std::vector<GeomField>& fields, V3d& offset,
size_t npoints)
{
// Create displaz GeomField for each property of the "vertex" element
std::vector<PlyPointField> fieldInfo = parsePlyPointFields(vertexElement);
std::sort(fieldInfo.begin(), fieldInfo.end(), &displazFieldComparison);
std::vector<PlyFieldLoader> fieldLoaders;
// Hack: use reserve to avoid iterator invalidation in push_back()
fields.reserve(fieldInfo.size());
fieldLoaders.reserve(fieldInfo.size());
// Always add position field
fields.push_back(GeomField(TypeSpec::vec3float32(), "position", npoints));
fieldLoaders.push_back(PlyFieldLoader(fields[0]));
bool hasPosition = false;
// Add all other fields, and connect fields to rply callbacks
for (size_t i = 0; i < fieldInfo.size(); )
{
const std::string& fieldName = fieldInfo[i].displazName;
TypeSpec::Semantics semantics = fieldInfo[i].semantics;
TypeSpec::Type baseType = TypeSpec::Unknown;
int elsize = 0;
plyTypeToPointFieldType(fieldInfo[i].plyType, baseType, elsize);
size_t eltBegin = i;
int maxComponentIndex = 0;
while (i < fieldInfo.size() && fieldInfo[i].displazName == fieldName &&
fieldInfo[i].semantics == semantics)
{
maxComponentIndex = std::max(maxComponentIndex,
fieldInfo[i].componentIndex);
++i;
}
size_t eltEnd = i;
PlyFieldLoader* loader = 0;
if (fieldName == "position")
{
hasPosition = true;
loader = &fieldLoaders[0];
}
else
{
TypeSpec type(baseType, elsize, maxComponentIndex+1, semantics);
//tfm::printf("%s: type %s\n", fieldName, type);
fields.push_back(GeomField(type, fieldName, npoints));
fieldLoaders.push_back(PlyFieldLoader(fields.back()));
loader = &fieldLoaders.back();
}
for (size_t j = eltBegin; j < eltEnd; ++j)
{
ply_set_read_cb(ply, "vertex", fieldInfo[j].plyName.c_str(),
&PlyFieldLoader::rplyCallback,
loader, fieldInfo[j].componentIndex);
}
}
if (!hasPosition)
{
g_logger.error("No position property found in file %s", fileName);
return false;
}
// All setup is done; read ply file using the callbacks
if (!ply_read(ply))
return false;
offset = fieldLoaders[0].offset();
return true;
}
//------------------------------------------------------------------------------
// Utilities for loading ply in "displaz-native" format
/// Find all elements with name "vertex_*"
///
/// The position element will always be in vertexElements[0] if present.
bool findVertexElements(std::vector<p_ply_element>& vertexElements,
p_ply ply, size_t& npoints)
{
int64_t np = -1;
int positionIndex = -1;
for (p_ply_element elem = ply_get_next_element(ply, NULL);
elem != NULL; elem = ply_get_next_element(ply, elem))
{
const char* name = 0;
long ninstances = 0;
if (!ply_get_element_info(elem, &name, &ninstances))
continue;
if (strncmp(name, "vertex_", 7) == 0)
{
if (np == -1)
np = ninstances;
if (np != ninstances)
{
g_logger.error("Inconsistent number of points in \"vertex_*\" fields");
return false;
}
vertexElements.push_back(elem);
if (strcmp(name, "vertex_position") == 0)
positionIndex = (int)vertexElements.size()-1;
}
else
{
g_logger.warning("Ignoring unrecogized ply element: %s", name);
}
}
if (positionIndex == -1)
{
g_logger.error("%s", "No vertex position found in ply file");
return false;
}
if (positionIndex != 0)
std::swap(vertexElements[0], vertexElements[positionIndex]);
npoints = np;
return true;
}
bool loadDisplazNativePly(QString fileName, p_ply ply,
std::vector<GeomField>& fields, V3d& offset,
size_t& npoints)
{
std::vector<p_ply_element> vertexElements;
if (!findVertexElements(vertexElements, ply, npoints))
return false;
// Map each vertex element to the associated displaz type
std::vector<PlyFieldLoader> fieldLoaders;
// Reserve to avoid reallocs which invalidate pointers to elements.
fields.reserve(vertexElements.size());
fieldLoaders.reserve(vertexElements.size());
for (auto elem = vertexElements.begin(); elem != vertexElements.end(); ++elem)
{
const char* elemName = 0;
ply_get_element_info(*elem, &elemName, 0);
assert(elemName);
// Figure out type of current element. All properties of the element
// should have the same type.
TypeSpec::Type baseType = TypeSpec::Unknown;
int elsize = 0;
p_ply_property firstProp = ply_get_next_property(*elem, NULL);
e_ply_type firstPropType = PLY_LIST;
const char* firstPropName = 0;
ply_get_property_info(firstProp, &firstPropName, &firstPropType, NULL, NULL);
plyTypeToPointFieldType(firstPropType, baseType, elsize);
// Determine semantics from first property. Displaz-native storage
// doesn't care about the rest of the property names (or perhaps it
// should be super strict?)
TypeSpec::Semantics semantics;
if (strcmp(firstPropName, "x") == 0)
semantics = TypeSpec::Vector;
else if (strcmp(firstPropName, "r") == 0)
semantics = TypeSpec::Color;
else if (strcmp(firstPropName, "0") == 0)
semantics = TypeSpec::Array;
else
{
g_logger.error("Could not determine vector semantics for property %s.%s: expected property name x, r or 0", elemName, firstPropName);
return false;
}
// Count properties
int numProps = 0;
for (p_ply_property prop = ply_get_next_property(*elem, NULL);
prop != NULL; prop = ply_get_next_property(*elem, prop))
{
numProps += 1;
}
std::string fieldName = elemName + 7; // Strip off "vertex_" prefix
if (fieldName == "position")
{
if (numProps != 3)
{
g_logger.error("position field must have three elements, found %d", numProps);
return false;
}
// Force "vector float[3]" for position
semantics = TypeSpec::Vector;
elsize = 4;
baseType = TypeSpec::Float;
}
// Create loader callback object
TypeSpec type(baseType, elsize, numProps, semantics);
fields.push_back(GeomField(type, fieldName, npoints));
fieldLoaders.push_back(PlyFieldLoader(fields.back()));
// Connect callbacks for each property
int propIdx = 0;
for (p_ply_property prop = ply_get_next_property(*elem, NULL);
prop != NULL; prop = ply_get_next_property(*elem, prop))
{
e_ply_type propType;
const char* propName = 0;
ply_get_property_info(prop, &propName, &propType, NULL, NULL);
ply_set_read_cb(ply, elemName, propName, &PlyFieldLoader::rplyCallback,
&fieldLoaders.back(), propIdx);
propIdx += 1;
}
g_logger.info("%s: %s %s", fileName, type, fieldName);
}
// All setup is done; read ply file using the callbacks
if (!ply_read(ply))
{
g_logger.error("Error in ply_read()");
return false;
}
offset = fieldLoaders[0].offset();
return true;
}
void logRplyError(p_ply ply, const char* message)
{
g_logger.error("rply: %s", message);
}
| 38.028889 | 145 | 0.566412 | janzill |
51583b19e10bf60abece9d5844384f0ea560fc86 | 21,230 | cxx | C++ | PWGLF/NUCLEX/Exotica/LambdaNN/AliAnalysisTaskLNNntuple.cxx | maroozm/AliPhysics | 22ec256928cfdf8f800e05bfc1a6e124d90b6eaf | [
"BSD-3-Clause"
] | 114 | 2017-03-03T09:12:23.000Z | 2022-03-03T20:29:42.000Z | PWGLF/NUCLEX/Exotica/LambdaNN/AliAnalysisTaskLNNntuple.cxx | maroozm/AliPhysics | 22ec256928cfdf8f800e05bfc1a6e124d90b6eaf | [
"BSD-3-Clause"
] | 19,637 | 2017-01-16T12:34:41.000Z | 2022-03-31T22:02:40.000Z | PWGLF/NUCLEX/Exotica/LambdaNN/AliAnalysisTaskLNNntuple.cxx | maroozm/AliPhysics | 22ec256928cfdf8f800e05bfc1a6e124d90b6eaf | [
"BSD-3-Clause"
] | 1,021 | 2016-07-14T22:41:16.000Z | 2022-03-31T05:15:51.000Z | /**************************************************************************
* Contributors are not mentioned at all. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//
//-----------------------------------------------------------------
// AliAnalysisTaskLNNntuple class
//-----------------------------------------------------------------
class TTree;
class TParticle;
class TVector3;
#include "AliAnalysisManager.h"
#include <AliMCEventHandler.h>
#include <AliMCEvent.h>
#include <AliStack.h>
class AliESDVertex;
class AliESDv0;
#include <iostream>
#include "AliAnalysisTaskSE.h"
#include "TList.h"
#include "TH1.h"
#include "TH2.h"
#include "TH3.h"
#include "TNtuple.h"
#include "TNtupleD.h"
#include "TCutG.h"
#include "TF1.h"
#include "TVector3.h"
#include "TCanvas.h"
#include "TMath.h"
#include "TChain.h"
#include "Riostream.h"
#include "AliLog.h"
#include "AliESDEvent.h"
#include "AliESDtrack.h"
#include "AliExternalTrackParam.h"
#include "AliInputEventHandler.h"
#include "AliAnalysisTaskLNNntuple.h"
#include "AliCentrality.h"
#include "AliTRDPIDResponse.h"
#include "TString.h"
#include <TDatime.h>
#include <TRandom3.h>
#include <TLorentzVector.h>
//#include <AliVTrack.h>
ClassImp (AliAnalysisTaskLNNntuple)
//________________________________________________________________________
AliAnalysisTaskLNNntuple::AliAnalysisTaskLNNntuple ():
AliAnalysisTaskSE (),
fMaxPtPion(0.55),
fMinPtTriton(0.75),
fYear(2015),
fMC(kTRUE),
fEventCuts(),
fListHist (0),
fHistEventMultiplicity (0),
fHistTrackMultiplicity (0),
fhBB (0),
fhTOF (0),
fhMassTOF (0),
fhBBPions (0),
fhBBH3 (0),
fhBBH3TofSel (0), fhTestNsigma (0), fTPCclusPID(0), fhTestQ(0), fNt (0), fPIDResponse(0)
{
// Dummy Constructor
//Printf(" ****************** Default ctor \n");
}
//________________________________________________________________________
AliAnalysisTaskLNNntuple::AliAnalysisTaskLNNntuple (const char *name, Bool_t mc):
AliAnalysisTaskSE (name),
fMaxPtPion(0.55),
fMinPtTriton(0.75),
fYear(2015),
fMC(mc),
fEventCuts(),
fListHist (0),
fHistEventMultiplicity (0),
fHistTrackMultiplicity (0),
fhBB (0),
fhTOF (0),
fhMassTOF (0),
fhBBPions (0),
fhBBH3 (0),
fhBBH3TofSel (0),
fhTestNsigma (0),
fTPCclusPID(0),
fhTestQ(0),
fNt (0), fPIDResponse(0)
{
// Define input and output slots here
// Input slot #0 works with a TChain
//DefineInput(0, TChain::Class());
// Output slot #0 writes into a TList container ()
DefineInput (0, TChain::Class ());
DefineOutput (1, TList::Class ());
//DefineOutput(2, TTree::Class());
//DefineOutput(3, TTree::Class());
//Printf(" ****************** Right ctor \n");
}
//_______________________________________________________
AliAnalysisTaskLNNntuple::~AliAnalysisTaskLNNntuple ()
{
// Destructor
if (fListHist)
{
delete fListHist;
fListHist = 0;
}
}
//==================DEFINITION OF OUTPUT OBJECTS==============================
void AliAnalysisTaskLNNntuple::UserCreateOutputObjects ()
{
fListHist = new TList ();
fListHist->SetOwner (); // IMPORTANT!
if(fYear==2015) fEventCuts.SetupLHC15o();
if(fYear==2011) fEventCuts.SetupRun1PbPb();
if (!fHistEventMultiplicity)
{
fHistEventMultiplicity =
new TH1F ("fHistEventMultiplicity", "Nb of Events", 13, -0.5, 12.5);
fHistEventMultiplicity->GetXaxis ()->SetBinLabel (1, "All Events");
fHistEventMultiplicity->GetXaxis ()->SetBinLabel (2, "Events w/PV");
fHistEventMultiplicity->GetXaxis ()->SetBinLabel (3, "Events w/|Vz|<10cm");
fHistEventMultiplicity->GetXaxis ()->SetBinLabel (4, "Central Events");
fHistEventMultiplicity->GetXaxis ()->SetBinLabel (5, "SemiCentral Events");
fHistEventMultiplicity->GetXaxis ()->SetBinLabel (6, "MB Events");
fHistEventMultiplicity->GetXaxis ()->SetBinLabel (7, "Central Events w/|Vz|<10cm");
fHistEventMultiplicity->GetXaxis ()->SetBinLabel (8, "SemiCentral Events w/|Vz|<10cm");
fHistEventMultiplicity->GetXaxis ()->SetBinLabel (9, "MB Events w/|Vz|<10cm");
fHistEventMultiplicity->GetXaxis ()->SetBinLabel (10,"Any Events");
fHistEventMultiplicity->GetXaxis ()->SetBinLabel (11,"Any Events w/|Vz|<10cm");
fHistEventMultiplicity->GetXaxis ()->SetBinLabel (12,"other");
fListHist->Add (fHistEventMultiplicity);
}
if (!fHistTrackMultiplicity)
{
fHistTrackMultiplicity =
new TH2F ("fHistTrackMultiplicity", "Nb of Tracks", 2500, 0, 25000,
210, -1, 104);
fHistTrackMultiplicity->GetXaxis ()->SetTitle ("Number of tracks");
fHistTrackMultiplicity->GetYaxis ()->SetTitle ("Percentile");
fListHist->Add (fHistTrackMultiplicity);
}
Double_t pMax = 8;
Double_t binWidth = 0.1;
Int_t nBinBB = (Int_t) (2 * pMax / binWidth);
if (!fhBB)
{
fhBB = new TH2F ("fhBB", "BetheBlochTPC", nBinBB, -pMax, pMax, 400, 0, 800);
fhBB->GetXaxis ()->SetTitle ("p/z (GeV/#it{c})");
fhBB->GetYaxis ()->SetTitle ("TPC Signal");
fListHist->Add (fhBB);
}
if (!fhTOF)
{
fhTOF = new TH2F ("fhTOF", "Scatter Plot TOF", nBinBB, -pMax, pMax, 100, 0,1.2);
fhTOF->GetXaxis ()->SetTitle ("p/z (GeV/#it{c})");
fhTOF->GetYaxis ()->SetTitle ("#beta");
fListHist->Add (fhTOF);
}
if (!fhMassTOF)
{
fhMassTOF =
new TH2F ("fhMassTOF", "Particle Mass - TOF", nBinBB, 0, pMax, 400, 0,5);
fhMassTOF->GetYaxis ()->SetTitle ("Mass (GeV/#it{c}^{2})");
fhMassTOF->GetXaxis ()->SetTitle ("P (GeV/#it{c})");
fListHist->Add (fhMassTOF);
}
if (!fhBBPions)
{
fhBBPions = new TH2F ("fhBBPions", "Bethe-Bloch TPC Pions", nBinBB, -pMax, pMax, 400, 0, 800);
fhBBPions->GetXaxis ()->SetTitle ("p/z (GeV/#it{c})");
fhBBPions->GetYaxis ()->SetTitle ("TPC Signal");
fListHist->Add (fhBBPions);
}
if (!fhBBH3)
{
fhBBH3 = new TH2F ("fhBBH3", "Bethe-Bloch TPC ^3H", nBinBB, -pMax, pMax, 400, 0, 800);
fhBBH3->GetXaxis ()->SetTitle ("p/z (GeV/#it{c})");
fhBBH3->GetYaxis ()->SetTitle ("TPC Signal");
fListHist->Add (fhBBH3);
}
if (!fhBBH3TofSel)
{
fhBBH3TofSel =
new TH2F ("fhBBH3TofSel","Bethe-Bloch TPC #^{3}H after TOF 3#sigma cut", nBinBB,-pMax, pMax, 400, 0, 800);
fhBBH3TofSel->GetXaxis ()->SetTitle ("p/z (GeV/#it{c})");
fhBBH3TofSel->GetYaxis ()->SetTitle ("TPC Signal");
fListHist->Add (fhBBH3TofSel);
}
if (!fhTestNsigma)
{
fhTestNsigma = new TH2F ("hNsigmaTri", "n #sigma distribution", 300, 0, 15, 100, -10, 10);
fListHist->Add (fhTestNsigma);
}
if(!fTPCclusPID){
fTPCclusPID = new TH2F("fTPCclusPID","triton track : clusters vs PID clusters",200,0,200,200,0,200);
fListHist->Add (fTPCclusPID);
}
if(!fhTestQ){
fhTestQ = new TH2F("htestQ","candidate charge as from TPC",16,-2,2,16,-2,2);
fhTestQ->SetXTitle("#pi Id charge");
fhTestQ->SetYTitle("3H Id charge");
fListHist->Add(fhTestQ);
}
if (!fNt)
{
if(!fMC){
fNt = new TNtupleD ("nt", "V0 ntuple","piPx:piPy:piPz:triPx:triPy:triPz:nSpi:nStri:triTOFmass:piTPCsig:triTPCsig:v0P:ptArm:alphaArm:triDcaXY:triDcaZ:v0DcaD:decayL:decayLxy:v0Dca:CosP:v0VtxErrSum:sign:dcaPi:is3Hele:nSPiFromPiTof:nSPrTof:nSPiTof:nITSclus:triTRDsig");
fListHist->Add (fNt);
} else {
fNt = new TNtupleD ("nt", "V0 ntuple","piPx:piPy:piPz:triPx:triPy:triPz:nSpi:nStri:triTOFmass:piTPCsig:triTPCsig:v0P:ptArm:alphaArm:triDcaXY:triDCAZ:v0DcaD:decayL:decayLxy:v0Dca:CosP:v0VtxErrSum:sign:dcaPi:is3Hele:nSPiFromPiTof:nSPrTof:nSPiTof:nITSclus:piPdgCode:triPdgCode:piMumPdgCode:triMumPdgCode:triTRDsig");
fListHist->Add (fNt);
}
}
PostData (1, fListHist);
} // end UserCreateOutputObjects
//====================== USER EXEC ========================
void
AliAnalysisTaskLNNntuple::UserExec (Option_t *)
{
//------------------------------------------
// Main loop
AliVEvent *event = InputEvent ();
if (!event)
{
Printf ("ERROR: Could not retrieve event");
return;
}
if(fMC) Info ("AliAnalysisTaskLNNntuple for MC", "Starting UserExec");
else Info ("AliAnalysisTaskLNNntuple for Data", "Starting UserExec");
// Load MC if required
AliStack *stack = 0;
Int_t nbMcTracks=0;
if(fMC){
AliMCEvent *mcEvent = MCEvent();
if (!mcEvent) {
Printf("ERROR: Could not retrieve MC event");
return;
}
stack = mcEvent->Stack();
nbMcTracks = stack->GetNtrack();;
if(!stack) {
Printf( "Stack not available, Exiting... \n");
return;
}
}
// Load ESD event
AliESDEvent *lESDevent = dynamic_cast < AliESDEvent * >(event);
if (!lESDevent)
{
AliError ("Cannot get the ESD event");
return;
}
fHistEventMultiplicity->Fill (0);
Double_t lMagneticField = lESDevent->GetMagneticField ();
Int_t TrackNumber = -1;
AliAnalysisManager *man = AliAnalysisManager::GetAnalysisManager ();
AliInputEventHandler *inputHandler = (AliInputEventHandler *) (man->GetInputEventHandler ());
TrackNumber = lESDevent->GetNumberOfTracks ();
if (TrackNumber < 3) return;
if(!fEventCuts.AcceptEvent(lESDevent)) return;
Float_t centrality=fEventCuts.GetCentrality(0); // 0 = V0M
fHistTrackMultiplicity->Fill(TrackNumber,centrality);
Int_t selCentrality = SelectCentrality(centrality);
fHistEventMultiplicity->Fill (selCentrality);
//*******//
// PID //
//*******//
fPIDResponse = inputHandler->GetPIDResponse ();
if(!fPIDResponse) {
AliError("!!! Please check the PID task, it is not loaded!!\n");
return;
}
fPIDResponse->SetCachePID (kTRUE);
//===========================================
// Primary vertex cut
const AliESDVertex *vtx = lESDevent->GetPrimaryVertexTracks ();
if (vtx->GetNContributors () < 1)
{
// SPD vertex cut
vtx = lESDevent->GetPrimaryVertexSPD ();
if (vtx->GetNContributors () < 1)
{
Info ("AliAnalysisTaskLNNntuple","No good vertex, skip event");
return; // NO GOOD VERTEX, SKIP EVENT
}
}
fHistEventMultiplicity->Fill (1); // analyzed events with PV
if (TMath::Abs (vtx->GetX()) > 10) return;
selCentrality = SelectCentrality(centrality,kTRUE);
fHistEventMultiplicity->Fill (selCentrality);
fHistEventMultiplicity->Fill (2);
// track quality monitor plots
for (Int_t j=0; j<TrackNumber; j++) { //loop on tracks
AliESDtrack *esdtrack=lESDevent->GetTrack(j);
if(!esdtrack) {
AliError(Form("ERROR: Could not retrieve esdtrack %d",j));
continue;
}
// ************** Track cuts ****************
if (!PassTrackCuts(esdtrack)) continue;
fhBB->Fill(esdtrack->P()/esdtrack->GetSign(),esdtrack->GetTPCsignal());
fhTestNsigma->Fill(esdtrack->P(),fPIDResponse->NumberOfSigmasTPC(esdtrack,(AliPID::EParticleType)6));
Double_t tofmass = -1;
tofmass = GetTOFmass(esdtrack);
if(tofmass>0) {
fhMassTOF->Fill(esdtrack->P(),tofmass);
}
}
// *************** Loop over V0s ***************
for(Int_t iv=0; iv<lESDevent->GetNumberOfV0s(); iv++){
AliESDv0 * v0s = lESDevent->GetV0(iv);
if(!v0s) continue;
TVector3 globVtx(vtx->GetX(),vtx->GetY(),vtx->GetZ());
TVector3 v0Vtx(v0s->Xv(),v0s->Yv(),v0s->Zv());
TVector3 decayL = globVtx-v0Vtx;
Double_t path = decayL.Mag();
if(!Passv0Cuts(v0s,path)) continue;
AliESDtrack* trackPos = lESDevent->GetTrack(v0s->GetPindex());
AliESDtrack* trackNeg = lESDevent->GetTrack(v0s->GetNindex());
if(!PassTrackCuts(trackPos)) continue;
if(!PassTrackCuts(trackNeg)) continue;
AliESDtrack *pion =0x0;
AliESDtrack *triton=0x0;
Double_t momPi[3], momTri[3];
if(IsPionCandidate(trackPos) && IsTritonCandidate(trackNeg)) {
pion = trackPos;
triton = trackNeg;
v0s->GetPPxPyPz(momPi[0],momPi[1],momPi[2]);
v0s->GetNPxPyPz(momTri[0],momTri[1],momTri[2]);
} else if(IsPionCandidate(trackNeg)&&IsTritonCandidate(trackPos)){
pion = trackNeg; triton = trackPos;
v0s->GetNPxPyPz(momPi[0],momPi[1],momPi[2]);
v0s->GetPPxPyPz(momTri[0],momTri[1],momTri[2]);
}
else continue;
// monitor dE/dx of tracks in selected V0s
fhBBPions->Fill(pion->P()*pion->GetSign(),pion->GetTPCsignal());
fhBBH3->Fill(triton->P()*triton->GetSign(),triton->GetTPCsignal());
Double_t tofMass = GetTOFmass(triton);
if(tofMass>2.5 && tofMass <3.5) fhBBH3TofSel->Fill(triton->P()*triton->GetSign(),triton->GetTPCsignal());
Double_t nSPi = fPIDResponse->NumberOfSigmasTPC (pion,(AliPID::EParticleType) 2);
Double_t nSTri = fPIDResponse->NumberOfSigmasTPC (triton,(AliPID::EParticleType) 6);
Double_t decayLXY = TMath::Sqrt(decayL.Mag2 () - decayL.Z () * decayL.Z ());
Double_t ptArm = v0s->PtArmV0 ();
Double_t alphaArm = v0s->AlphaV0 ();
Float_t dcaTri[2] = { -100, -100 };
Double_t Vtxpos[3] ={ globVtx.X (), globVtx.Y (), globVtx.Z () };
triton->GetDZ (Vtxpos[0], Vtxpos[1], Vtxpos[2], lESDevent->GetMagneticField (), dcaTri);
//dca to primary vertex
Float_t dcaPi= pion->GetD(Vtxpos[0],Vtxpos[1],lESDevent->GetMagneticField());
//Float_t dcaTriTot = triton->GetD(Vtxpos[0],Vtxpos[1],lESDevent->GetMagneticField()); -> same as dcaTri[1]
Double_t nSPiFromPiTof = fPIDResponse->NumberOfSigmasTOF (pion,(AliPID::EParticleType) 2);
Double_t nSPrTof = fPIDResponse->NumberOfSigmasTOF (triton,(AliPID::EParticleType) 4); //check if 3H is identified as proton in TOF PID
Double_t nSPiTof = fPIDResponse->NumberOfSigmasTOF (triton,(AliPID::EParticleType) 2); // check if 3H is identified as pion TOF PID
AliESDVertex vtxV0 = v0s->GetVertex ();
Double_t sigmaVtxV0[2] = { pion->GetD(vtxV0.GetX (), vtxV0.GetY (),lMagneticField), triton->GetD (vtxV0.GetX (), vtxV0.GetY (), lMagneticField) };
Double_t err = TMath::Sqrt (sigmaVtxV0[0] * sigmaVtxV0[0] + sigmaVtxV0[1] * sigmaVtxV0[1]);
fhTestQ->Fill(pion->Charge(),triton->Charge());
Float_t isHele=0;
Int_t nTrackletsPID=0;
Float_t eleEff[3] = {0.85,0.9,0.95};
AliPIDResponse::EDetPidStatus pidStatus = fPIDResponse->CheckPIDStatus(AliPIDResponse::kTRD,triton);
if(pidStatus!=AliPIDResponse::kDetPidOk) isHele = -1;
else {
for(Int_t iEff=0; iEff<3; iEff++) {
Bool_t isEle = fPIDResponse->IdentifiedAsElectronTRD(triton,nTrackletsPID,eleEff[iEff],centrality,AliTRDPIDResponse::kLQ2D);
if(isEle && nTrackletsPID>3) isHele += (iEff+1)*TMath::Power(10,iEff);
}
}
if(fMC){
Double_t pdgPion=-1, pdgTriton=-1, pdgPionMum=-1, pdgTritonMum=-1;
if(TMath::Abs(pion->GetLabel()<nbMcTracks)) {
TParticle *piMC = stack->Particle(TMath::Abs(pion->GetLabel()));
pdgPion = piMC->GetPdgCode();
Int_t mum = piMC->GetFirstMother();
if(mum>0 && mum<nbMcTracks){
pdgPionMum = stack->Particle(mum)->GetPdgCode();
}
}
if(TMath::Abs(triton->GetLabel()<nbMcTracks)) {
TParticle *tritonMC = stack->Particle(TMath::Abs(triton->GetLabel()));
pdgTriton = tritonMC->GetPdgCode();
Int_t mum = tritonMC->GetFirstMother();
if(mum>0 && mum<nbMcTracks){
pdgTritonMum = stack->Particle(mum)->GetPdgCode();
}
}
Double_t ntuple[34] =
{ momPi[0], momPi[1], momPi[2], momTri[0], momTri[1],momTri[2], nSPi, nSTri,
tofMass,pion->GetTPCsignal (), triton->GetTPCsignal (),
v0s->P(), ptArm, alphaArm, dcaTri[0], dcaTri[1],v0s->GetDcaV0Daughters (), decayL.Mag(), decayLXY,
v0s->GetD (vtx->GetX (), vtx->GetY (), vtx->GetZ ()),v0s->GetV0CosineOfPointingAngle (), err, pion->GetSign () + triton->GetSign ()*10,
dcaPi,isHele,nSPiFromPiTof,nSPrTof,nSPiTof,pion->GetNumberOfITSClusters()+100.*triton->GetNumberOfITSClusters(),
pdgPion,pdgTriton,pdgPionMum,pdgTritonMum,triton->GetTRDsignal()};
fNt->Fill (ntuple);
} else {
Double_t ntuple[30] =
{ momPi[0], momPi[1], momPi[2], momTri[0], momTri[1],momTri[2], nSPi, nSTri,
tofMass,pion->GetTPCsignal (), triton->GetTPCsignal (),
v0s->P(), ptArm, alphaArm, dcaTri[0], dcaTri[1], v0s->GetDcaV0Daughters (), decayL.Mag(), decayLXY,
v0s->GetD (vtx->GetX (), vtx->GetY (), vtx->GetZ ()),v0s->GetV0CosineOfPointingAngle (), err, pion->GetSign () + triton->GetSign ()*10,
dcaPi,isHele,nSPiFromPiTof,nSPrTof,nSPiTof,pion->GetNumberOfITSClusters()+100.*triton->GetNumberOfITSClusters(),triton->GetTRDsignal()};
fNt->Fill (ntuple);
}
} // loop over V0s
PostData (1, fListHist);
} //end userexec
//________________________________________________________________________
void
AliAnalysisTaskLNNntuple::Terminate (Option_t *)
{
// Draw result to the screen
// Called once at the end of the query
}
//________________________________________________________________________
Bool_t AliAnalysisTaskLNNntuple::PassTrackCuts (AliESDtrack * tr)
{
if(tr->GetTPCNcls() < 60 ) return kFALSE;
if (!(tr->GetStatus () & AliESDtrack::kTPCrefit)) return kFALSE;
if (Chi2perNDF (tr) > 5) return kFALSE;
if (tr->GetKinkIndex (0) != 0) return kFALSE;
if (TMath::Abs (tr->Eta ()) > 0.9) return kFALSE;
if (tr->P () < 0.15) return kFALSE;
if (tr->P () > 10) return kFALSE;
return true;
}
//________________________________________________________________________
Bool_t AliAnalysisTaskLNNntuple::Passv0Cuts (AliESDv0 * v0, Double_t decayLength)
{
if(v0->GetOnFlyStatus()==kTRUE) return false;
if (v0->P () < 0.7) return kFALSE;
if (v0->P () > 10) return kFALSE;
if (v0->GetDcaV0Daughters () > 0.8) return kFALSE;
if (v0->GetV0CosineOfPointingAngle () < 0.9995) return kFALSE;
if (decayLength < 0.5) return false; // loose cut to reduce bkg of V0s coming from primary vertex( weak decay and the coice of 1 cm comes from MC study )
return true;
}
//________________________________________________________________
Bool_t AliAnalysisTaskLNNntuple::IsPionCandidate (AliESDtrack * tr)
{
if(tr->Pt()> fMaxPtPion) return kFALSE;
AliPIDResponse::EDetPidStatus statusTPC;
Double_t nSigmaTPC = -999;
statusTPC = fPIDResponse->NumberOfSigmas (AliPIDResponse::kTPC, tr, AliPID::kPion,nSigmaTPC);
Bool_t z = kFALSE;
if (statusTPC == AliPIDResponse::kDetPidOk && TMath::Abs (nSigmaTPC) <= 3.5) z = kTRUE;
return z;
}
//________________________________________________________________________
Bool_t AliAnalysisTaskLNNntuple::IsTritonCandidate(AliESDtrack * tr)
{
if(tr->Pt()<fMinPtTriton) return kFALSE;
AliPIDResponse::EDetPidStatus statusTPC;
Double_t nSigmaTPC = -999;
statusTPC = fPIDResponse->NumberOfSigmas (AliPIDResponse::kTPC, tr, AliPID::kTriton, nSigmaTPC);
Bool_t z = kFALSE;
if (statusTPC == AliPIDResponse::kDetPidOk && TMath::Abs (nSigmaTPC) <= 3.5) z = kTRUE;
if(z) {
fTPCclusPID->Fill(tr->GetTPCNcls(),tr->GetTPCsignalN());
if(tr->GetTPCsignalN()<40) z = kFALSE;
}
return z;
}
//________________________________________________________________________
Double_t AliAnalysisTaskLNNntuple::GetTOFmass(AliESDtrack * tr)
{
// get TOF mass
Double_t m = -999; //mass
Double_t b = -999; //beta
Double_t trackLeng = 0;
if ((tr->GetStatus () & AliESDtrack::kTOFout) == AliESDtrack::kTOFout)
{
trackLeng = tr->GetIntegratedLength ();
//Double_t p = tr->P ();
Double_t p = tr->GetTPCmomentum();
Double_t speedOfLight = TMath::C () * 1E2 * 1E-12; // cm/ps
Double_t timeTOF = tr->GetTOFsignal () - fPIDResponse->GetTOFResponse ().GetStartTime (p); // ps
b = trackLeng / (timeTOF * speedOfLight);
if (b >= 1 || b == 0) return m;
m = p * TMath::Sqrt (1 / (b * b) - 1);
}
return m;
}
//________________________________________________________________________
Double_t AliAnalysisTaskLNNntuple::Chi2perNDF (AliESDtrack * track)
{
// Calculate chi2 per ndf for track
Int_t nClustersTPC = track->GetTPCNcls ();
if (nClustersTPC > 5) return (track->GetTPCchi2 () / Float_t (nClustersTPC - 5));
else return (-1.);
}
//________________________________________________________________________
Int_t AliAnalysisTaskLNNntuple::SelectCentrality(Float_t perc, Bool_t isPrimVtx){
// enum {kCentral=3, kSemiCentral=4, kPeripheral=5, kOther=9, kCentralPV=6,kSemiCentralPV=7, kPeripheralPV=8, kOtherPV=10 };
Int_t result=-1;
if(!isPrimVtx){
if(perc<=10) result=3;
else if(perc>10 && perc <=40) result=4;
else if(perc>40 && perc <=90) result=5;
else result=9;
} else {
if(perc<=10) result=6;
else if(perc>10 && perc <=40) result=7;
else if(perc>40 && perc <=90) result=8;
else result=10;
}
return result;
}
| 34.746318 | 314 | 0.652803 | maroozm |
51584e7bcb46e295884dd77708cf1067703d0f21 | 1,081 | cpp | C++ | A2OJ/B/025.Vasya and Wrestling.cpp | XitizVerma/Data-Structures-and-Algorithms-Advanced | 610225eeb7e0b4ade229ec86355901ad1ca38784 | [
"MIT"
] | null | null | null | A2OJ/B/025.Vasya and Wrestling.cpp | XitizVerma/Data-Structures-and-Algorithms-Advanced | 610225eeb7e0b4ade229ec86355901ad1ca38784 | [
"MIT"
] | null | null | null | A2OJ/B/025.Vasya and Wrestling.cpp | XitizVerma/Data-Structures-and-Algorithms-Advanced | 610225eeb7e0b4ade229ec86355901ad1ca38784 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define ll long long
#define fast ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)
using namespace std;
set<ll> usinversal;
ll ans = 0;
ll aa = 0;
int main()
{
fast;
ll n;
cin >> n;
ll sum1 = 0, sum2= 0;
vector<ll> a1, a2;
bool l;
while (n--)
{
ll x;
cin >>x;
if (x >= 0)
{
sum1 += x;
a1.push_back(x);
l = true;
}
else
{
sum2 += -1 *x;
a2.push_back(-1 * x);
l = false;
}
}
if (sum1 >sum2)
{
cout << "first" << "\n";
}
else if (sum2 > sum1)
{
cout << "second" << "\n";
}
else
{
if (a1 > a2)
{
cout << "first" << "\n";
}
else if (a1 < a2)
{
cout <<"second" << "\n";
}
else if (l)
{
cout << "first" << "\n";
}
else
{
cout << "second" << "\n";
}
}
return 0;
} | 16.630769 | 76 | 0.345976 | XitizVerma |
5158ad2fd453e38221b065d2a78afeee2118edde | 8,081 | cpp | C++ | tests/ktx/src/KtxTests.cpp | Darlingnotin/Antisocial_VR | f1debafb784ed5a63a40fe9b80790fbaccfedfce | [
"Apache-2.0"
] | 272 | 2021-01-07T03:06:08.000Z | 2022-03-25T03:54:07.000Z | tests/ktx/src/KtxTests.cpp | Darlingnotin/Antisocial_VR | f1debafb784ed5a63a40fe9b80790fbaccfedfce | [
"Apache-2.0"
] | 1,021 | 2020-12-12T02:33:32.000Z | 2022-03-31T23:36:37.000Z | tests/ktx/src/KtxTests.cpp | Darlingnotin/Antisocial_VR | f1debafb784ed5a63a40fe9b80790fbaccfedfce | [
"Apache-2.0"
] | 77 | 2020-12-15T06:59:34.000Z | 2022-03-23T22:18:04.000Z | //
// Created by Bradley Austin Davis on 2016/07/01
// Copyright 2014 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#include "KtxTests.h"
#include <mutex>
#include <QtTest/QtTest>
#include <ktx/KTX.h>
#include <gpu/Texture.h>
#include <image/Image.h>
QTEST_GUILESS_MAIN(KtxTests)
QString getRootPath() {
static std::once_flag once;
static QString result;
std::call_once(once, [&] {
QFileInfo file(__FILE__);
QDir parent = file.absolutePath();
result = QDir::cleanPath(parent.currentPath() + "/../../..");
});
return result;
}
void KtxTests::initTestCase() {
}
void KtxTests::cleanupTestCase() {
}
void KtxTests::testKhronosCompressionFunctions() {
using namespace khronos::gl::texture;
QCOMPARE(evalAlignedCompressedBlockCount<4>(0), (uint32_t)0x0);
QCOMPARE(evalAlignedCompressedBlockCount<4>(1), (uint32_t)0x1);
QCOMPARE(evalAlignedCompressedBlockCount<4>(4), (uint32_t)0x1);
QCOMPARE(evalAlignedCompressedBlockCount<4>(5), (uint32_t)0x2);
QCOMPARE(evalCompressedBlockCount(InternalFormat::COMPRESSED_SRGB_S3TC_DXT1_EXT, 0x00), (uint32_t)0x00);
QCOMPARE(evalCompressedBlockCount(InternalFormat::COMPRESSED_SRGB_S3TC_DXT1_EXT, 0x01), (uint32_t)0x01);
QCOMPARE(evalCompressedBlockCount(InternalFormat::COMPRESSED_SRGB_S3TC_DXT1_EXT, 0x04), (uint32_t)0x01);
QCOMPARE(evalCompressedBlockCount(InternalFormat::COMPRESSED_SRGB_S3TC_DXT1_EXT, 0x05), (uint32_t)0x02);
QCOMPARE(evalCompressedBlockCount(InternalFormat::COMPRESSED_SRGB_S3TC_DXT1_EXT, 0x1000), (uint32_t)0x400);
QVERIFY_EXCEPTION_THROWN(evalCompressedBlockCount(InternalFormat::RGBA8, 0x00), std::runtime_error);
}
void KtxTests::testKtxEvalFunctions() {
QCOMPARE(sizeof(ktx::Header), (size_t)64);
QCOMPARE(ktx::evalPadding(0x0), (uint8_t)0);
QCOMPARE(ktx::evalPadding(0x1), (uint8_t)3);
QCOMPARE(ktx::evalPadding(0x2), (uint8_t)2);
QCOMPARE(ktx::evalPadding(0x3), (uint8_t)1);
QCOMPARE(ktx::evalPadding(0x4), (uint8_t)0);
QCOMPARE(ktx::evalPadding(0x400), (uint8_t)0);
QCOMPARE(ktx::evalPadding(0x401), (uint8_t)3);
QCOMPARE(ktx::evalPaddedSize(0x0), 0x0);
QCOMPARE(ktx::evalPaddedSize(0x1), 0x4);
QCOMPARE(ktx::evalPaddedSize(0x2), 0x4);
QCOMPARE(ktx::evalPaddedSize(0x3), 0x4);
QCOMPARE(ktx::evalPaddedSize(0x4), 0x4);
QCOMPARE(ktx::evalPaddedSize(0x400), 0x400);
QCOMPARE(ktx::evalPaddedSize(0x401), 0x404);
QCOMPARE(ktx::evalAlignedCount((uint32_t)0x0), (uint32_t)0x0);
QCOMPARE(ktx::evalAlignedCount((uint32_t)0x1), (uint32_t)0x1);
QCOMPARE(ktx::evalAlignedCount((uint32_t)0x4), (uint32_t)0x1);
QCOMPARE(ktx::evalAlignedCount((uint32_t)0x5), (uint32_t)0x2);
}
void KtxTests::testKtxSerialization() {
const QString TEST_IMAGE = getRootPath() + "/scripts/developer/tests/cube_texture.png";
QImage image(TEST_IMAGE);
std::atomic<bool> abortSignal;
gpu::TexturePointer testTexture =
image::TextureUsage::process2DTextureColorFromImage(std::move(image), TEST_IMAGE.toStdString(), true, abortSignal);
auto ktxMemory = gpu::Texture::serialize(*testTexture);
QVERIFY(ktxMemory.get());
// Serialize the image to a file
QTemporaryFile TEST_IMAGE_KTX;
{
const auto& ktxStorage = ktxMemory->getStorage();
QVERIFY(ktx::KTX::validate(ktxStorage));
QVERIFY(ktxMemory->isValid());
auto& outFile = TEST_IMAGE_KTX;
if (!outFile.open()) {
QFAIL("Unable to open file");
}
auto ktxSize = ktxStorage->size();
outFile.resize(ktxSize);
auto dest = outFile.map(0, ktxSize);
memcpy(dest, ktxStorage->data(), ktxSize);
outFile.unmap(dest);
outFile.close();
}
{
auto ktxStorage = std::make_shared<storage::FileStorage>(TEST_IMAGE_KTX.fileName());
QVERIFY(ktx::KTX::validate(ktxStorage));
auto ktxFile = ktx::KTX::create(ktxStorage);
QVERIFY(ktxFile.get());
QVERIFY(ktxFile->isValid());
{
const auto& memStorage = ktxMemory->getStorage();
const auto& fileStorage = ktxFile->getStorage();
QVERIFY(memStorage->size() == fileStorage->size());
QVERIFY(memStorage->data() != fileStorage->data());
QVERIFY(0 == memcmp(memStorage->data(), fileStorage->data(), memStorage->size()));
QVERIFY(ktxFile->_images.size() == ktxMemory->_images.size());
auto imageCount = ktxFile->_images.size();
auto startMemory = ktxMemory->_storage->data();
auto startFile = ktxFile->_storage->data();
for (size_t i = 0; i < imageCount; ++i) {
auto memImages = ktxMemory->_images[i];
auto fileImages = ktxFile->_images[i];
QVERIFY(memImages._padding == fileImages._padding);
QVERIFY(memImages._numFaces == fileImages._numFaces);
QVERIFY(memImages._imageSize == fileImages._imageSize);
QVERIFY(memImages._faceSize == fileImages._faceSize);
QVERIFY(memImages._faceBytes.size() == memImages._numFaces);
QVERIFY(fileImages._faceBytes.size() == fileImages._numFaces);
auto faceCount = fileImages._numFaces;
for (uint32_t face = 0; face < faceCount; ++face) {
auto memFace = memImages._faceBytes[face];
auto memOffset = memFace - startMemory;
auto fileFace = fileImages._faceBytes[face];
auto fileOffset = fileFace - startFile;
QVERIFY(memOffset % 4 == 0);
QVERIFY(memOffset == fileOffset);
}
}
}
}
testTexture->setKtxBacking(TEST_IMAGE_KTX.fileName().toStdString());
}
#if 0
static const QString TEST_FOLDER { "H:/ktx_cacheold" };
//static const QString TEST_FOLDER { "C:/Users/bdavis/Git/KTX/testimages" };
//static const QString EXTENSIONS { "4bbdf8f786470e4ab3e672d44b8e8df2.ktx" };
static const QString EXTENSIONS { "*.ktx" };
int mainTemp(int, char**) {
setupHifiApplication("KTX Tests");
auto fileInfoList = QDir { TEST_FOLDER }.entryInfoList(QStringList { EXTENSIONS });
for (auto fileInfo : fileInfoList) {
qDebug() << fileInfo.filePath();
std::shared_ptr<storage::Storage> storage { new storage::FileStorage { fileInfo.filePath() } };
if (!ktx::KTX::validate(storage)) {
qDebug() << "KTX invalid";
}
auto ktxFile = ktx::KTX::create(storage);
ktx::KTXDescriptor ktxDescriptor = ktxFile->toDescriptor();
qDebug() << "Contains " << ktxDescriptor.keyValues.size() << " key value pairs";
for (const auto& kv : ktxDescriptor.keyValues) {
qDebug() << "\t" << kv._key.c_str();
}
auto offsetToMinMipKV = ktxDescriptor.getValueOffsetForKey(ktx::HIFI_MIN_POPULATED_MIP_KEY);
if (offsetToMinMipKV) {
auto data = storage->data() + ktx::KTX_HEADER_SIZE + offsetToMinMipKV;
auto minMipLevelAvailable = *data;
qDebug() << "\tMin mip available " << minMipLevelAvailable;
assert(minMipLevelAvailable < ktxDescriptor.header.numberOfMipmapLevels);
}
auto storageSize = storage->size();
for (const auto& faceImageDesc : ktxDescriptor.images) {
//assert(0 == (faceImageDesc._faceSize % 4));
for (const auto& faceOffset : faceImageDesc._faceOffsets) {
assert(0 == (faceOffset % 4));
auto faceEndOffset = faceOffset + faceImageDesc._faceSize;
assert(faceEndOffset <= storageSize);
}
}
for (const auto& faceImage : ktxFile->_images) {
for (const ktx::Byte* faceBytes : faceImage._faceBytes) {
assert(0 == (reinterpret_cast<size_t>(faceBytes) % 4));
}
}
}
return 0;
}
#endif
| 40.60804 | 123 | 0.64497 | Darlingnotin |
5158e6cfeebf75aa4a17e480bfc14a894b96f420 | 118 | cpp | C++ | project567/src/component468/cpp/lib8.cpp | gradle/perf-native-large | af00fd258fbe9c7d274f386e46847fe12062cc71 | [
"Apache-2.0"
] | 2 | 2016-11-23T17:25:24.000Z | 2016-11-23T17:25:27.000Z | project567/src/component468/cpp/lib8.cpp | gradle/perf-native-large | af00fd258fbe9c7d274f386e46847fe12062cc71 | [
"Apache-2.0"
] | 15 | 2016-09-15T03:19:32.000Z | 2016-09-17T09:15:32.000Z | project567/src/component468/cpp/lib8.cpp | gradle/perf-native-large | af00fd258fbe9c7d274f386e46847fe12062cc71 | [
"Apache-2.0"
] | 2 | 2019-11-09T16:26:55.000Z | 2021-01-13T10:51:09.000Z | #include <stdio.h>
#include <component468/lib1.h>
int component468_8 () {
printf("Hello world!\n");
return 0;
}
| 13.111111 | 30 | 0.661017 | gradle |
515af9a070aa948b0cf524f3d3db3453891690c6 | 2,795 | cpp | C++ | libraries/networking/src/HMACAuth.cpp | Darlingnotin/Antisocial_VR | f1debafb784ed5a63a40fe9b80790fbaccfedfce | [
"Apache-2.0"
] | 272 | 2021-01-07T03:06:08.000Z | 2022-03-25T03:54:07.000Z | libraries/networking/src/HMACAuth.cpp | Darlingnotin/Antisocial_VR | f1debafb784ed5a63a40fe9b80790fbaccfedfce | [
"Apache-2.0"
] | 1,021 | 2020-12-12T02:33:32.000Z | 2022-03-31T23:36:37.000Z | libraries/networking/src/HMACAuth.cpp | Darlingnotin/Antisocial_VR | f1debafb784ed5a63a40fe9b80790fbaccfedfce | [
"Apache-2.0"
] | 77 | 2020-12-15T06:59:34.000Z | 2022-03-23T22:18:04.000Z | //
// HMACAuth.cpp
// libraries/networking/src
//
// Created by Simon Walton on 3/19/2018.
// Copyright 2018 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#include "HMACAuth.h"
#include <openssl/opensslv.h>
#include <openssl/hmac.h>
#include <QUuid>
#include "NetworkLogging.h"
#include <cassert>
#if OPENSSL_VERSION_NUMBER >= 0x10100000
HMACAuth::HMACAuth(AuthMethod authMethod)
: _hmacContext(HMAC_CTX_new())
, _authMethod(authMethod) { }
HMACAuth::~HMACAuth()
{
HMAC_CTX_free(_hmacContext);
}
#else
HMACAuth::HMACAuth(AuthMethod authMethod)
: _hmacContext(new HMAC_CTX())
, _authMethod(authMethod) {
HMAC_CTX_init(_hmacContext);
}
HMACAuth::~HMACAuth() {
HMAC_CTX_cleanup(_hmacContext);
delete _hmacContext;
}
#endif
bool HMACAuth::setKey(const char* keyValue, int keyLen) {
const EVP_MD* sslStruct = nullptr;
switch (_authMethod) {
case MD5:
sslStruct = EVP_md5();
break;
case SHA1:
sslStruct = EVP_sha1();
break;
case SHA224:
sslStruct = EVP_sha224();
break;
case SHA256:
sslStruct = EVP_sha256();
break;
case RIPEMD160:
sslStruct = EVP_ripemd160();
break;
default:
return false;
}
QMutexLocker lock(&_lock);
return (bool) HMAC_Init_ex(_hmacContext, keyValue, keyLen, sslStruct, nullptr);
}
bool HMACAuth::setKey(const QUuid& uidKey) {
const QByteArray rfcBytes(uidKey.toRfc4122());
return setKey(rfcBytes.constData(), rfcBytes.length());
}
bool HMACAuth::addData(const char* data, int dataLen) {
QMutexLocker lock(&_lock);
return (bool) HMAC_Update(_hmacContext, reinterpret_cast<const unsigned char*>(data), dataLen);
}
HMACAuth::HMACHash HMACAuth::result() {
HMACHash hashValue(EVP_MAX_MD_SIZE);
unsigned int hashLen;
QMutexLocker lock(&_lock);
auto hmacResult = HMAC_Final(_hmacContext, &hashValue[0], &hashLen);
if (hmacResult) {
hashValue.resize((size_t)hashLen);
} else {
// the HMAC_FINAL call failed - should not be possible to get into this state
qCWarning(networking) << "Error occured calling HMAC_Final";
assert(hmacResult);
}
// Clear state for possible reuse.
HMAC_Init_ex(_hmacContext, nullptr, 0, nullptr, nullptr);
return hashValue;
}
bool HMACAuth::calculateHash(HMACHash& hashResult, const char* data, int dataLen) {
QMutexLocker lock(&_lock);
if (!addData(data, dataLen)) {
qCWarning(networking) << "Error occured calling HMACAuth::addData()";
assert(false);
return false;
}
hashResult = result();
return true;
}
| 23.686441 | 99 | 0.667621 | Darlingnotin |
515bdedef961afeb3573601aa52e151ec83104d1 | 706 | cpp | C++ | server/Common/Packets/GCStallError.cpp | viticm/web-pap | 7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca | [
"BSD-3-Clause"
] | 3 | 2018-06-19T21:37:38.000Z | 2021-07-31T21:51:40.000Z | server/Common/Packets/GCStallError.cpp | viticm/web-pap | 7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca | [
"BSD-3-Clause"
] | null | null | null | server/Common/Packets/GCStallError.cpp | viticm/web-pap | 7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca | [
"BSD-3-Clause"
] | 13 | 2015-01-30T17:45:06.000Z | 2022-01-06T02:29:34.000Z | #include "stdafx.h"
// GCStallError.cpp
//
/////////////////////////////////////////////////////
#include "GCStallError.h"
BOOL GCStallError::Read( SocketInputStream& iStream )
{
__ENTER_FUNCTION
iStream.Read( (CHAR*)(&m_ID), sizeof(BYTE));
return TRUE ;
__LEAVE_FUNCTION
return FALSE ;
}
BOOL GCStallError::Write( SocketOutputStream& oStream )const
{
__ENTER_FUNCTION
oStream.Write( (CHAR*)(&m_ID), sizeof(BYTE));
return TRUE ;
__LEAVE_FUNCTION
return FALSE ;
}
UINT GCStallError::Execute( Player* pPlayer )
{
__ENTER_FUNCTION
return GCStallErrorHandler::Execute( this, pPlayer ) ;
__LEAVE_FUNCTION
return FALSE ;
}
| 16.045455 | 62 | 0.610482 | viticm |
515c0f991d826f7014190d628854a375aba1a70d | 1,624 | cpp | C++ | audio_editor_core/audio_editor_core/paste_board/ae_pasteboard_types.cpp | objective-audio/audio_editor | 649f74cdca3d7db3d618922a345ea158a0c03a1d | [
"MIT"
] | null | null | null | audio_editor_core/audio_editor_core/paste_board/ae_pasteboard_types.cpp | objective-audio/audio_editor | 649f74cdca3d7db3d618922a345ea158a0c03a1d | [
"MIT"
] | null | null | null | audio_editor_core/audio_editor_core/paste_board/ae_pasteboard_types.cpp | objective-audio/audio_editor | 649f74cdca3d7db3d618922a345ea158a0c03a1d | [
"MIT"
] | null | null | null | //
// ae_pasteboard_types.cpp
//
#include "ae_pasteboard_types.h"
#include <audio_editor_core/ae_pasteboard_constants.h>
#include <audio_editor_core/ae_pasteboard_utils.h>
using namespace yas;
using namespace yas::ae;
using namespace yas::ae::pasteboard_constants;
std::string pasting_file_module::data() const {
std::map<std::string, std::string> map{{file_module_key::kind, file_module_kind::value},
{file_module_key::file_frame, std::to_string(this->file_frame)},
{file_module_key::length, std::to_string(this->length)}};
return pasteboard_utils::to_data_string(map);
}
std::optional<pasting_file_module> pasting_file_module::make_value(std::string const &data) {
auto const map = pasteboard_utils::to_data_map(data);
if (map.contains(file_module_key::kind) && map.at(file_module_key::kind) == file_module_kind::value &&
map.contains(file_module_key::file_frame) && map.contains(file_module_key::length)) {
auto const file_frame_string = map.at(file_module_key::file_frame);
auto const length_string = map.at(file_module_key::length);
return pasting_file_module{.file_frame = std::stoll(file_frame_string), .length = std::stoul(length_string)};
}
return std::nullopt;
}
std::string yas::to_string(ae::pasting_file_module const &module) {
return "{" + std::to_string(module.file_frame) + "," + std::to_string(module.length) + "}";
}
std::ostream &operator<<(std::ostream &os, yas::ae::pasting_file_module const &value) {
os << to_string(value);
return os;
}
| 38.666667 | 117 | 0.692118 | objective-audio |
515fdcb124524d54694735ebf2de3286716ca302 | 920 | cpp | C++ | Actor/Characters/Enemy/E4/State/StateRoot_EnemyE4.cpp | Bornsoul/Revenger_JoyContinue | 599716970ca87a493bf3a959b36de0b330b318f1 | [
"MIT"
] | null | null | null | Actor/Characters/Enemy/E4/State/StateRoot_EnemyE4.cpp | Bornsoul/Revenger_JoyContinue | 599716970ca87a493bf3a959b36de0b330b318f1 | [
"MIT"
] | null | null | null | Actor/Characters/Enemy/E4/State/StateRoot_EnemyE4.cpp | Bornsoul/Revenger_JoyContinue | 599716970ca87a493bf3a959b36de0b330b318f1 | [
"MIT"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "StateRoot_EnemyE4.h"
#include "StateMng_EnemyE4.h"
UStateRoot_EnemyE4::UStateRoot_EnemyE4()
{
}
UStateRoot_EnemyE4::~UStateRoot_EnemyE4()
{
}
void UStateRoot_EnemyE4::Init(class UStateMng_GC* pMng)
{
Super::Init(pMng);
m_pStateMng_Override = Cast<UStateMng_EnemyE4>(pMng);
if (m_pStateMng_Override == nullptr)
{
ULOG(TEXT("m_pStateMng_Override is nullptr"));
}
}
void UStateRoot_EnemyE4::Enter()
{
Super::Enter();
}
void UStateRoot_EnemyE4::Exit()
{
Super::Exit();
}
void UStateRoot_EnemyE4::Update(float fDeltaTime)
{
Super::Update(fDeltaTime);
}
void UStateRoot_EnemyE4::StateMessage(FString sMessage)
{
Super::StateMessage(sMessage);
}
AEnemyE4* UStateRoot_EnemyE4::GetRootChar()
{
if (m_pStateMng_Override == nullptr)
{
return nullptr;
}
return m_pStateMng_Override->GetRootCharacter_Override();
}
| 16.727273 | 78 | 0.755435 | Bornsoul |
51637f2c62188dae57e1f0a21870117260bcf1c9 | 813 | hpp | C++ | WorldLoader/Include/WorldDataTags.hpp | jordanlittlefair/Foundation | ab737b933ea5bbe2be76133ed78c8e882f072fd0 | [
"BSL-1.0"
] | null | null | null | WorldLoader/Include/WorldDataTags.hpp | jordanlittlefair/Foundation | ab737b933ea5bbe2be76133ed78c8e882f072fd0 | [
"BSL-1.0"
] | null | null | null | WorldLoader/Include/WorldDataTags.hpp | jordanlittlefair/Foundation | ab737b933ea5bbe2be76133ed78c8e882f072fd0 | [
"BSL-1.0"
] | null | null | null | #pragma once
#ifndef _WORLDLOADER_WORLDDATATAGS_HPP_
#define _WORLDLOADER_WORLDDATATAGS_HPP_
/*
Define the tags which make up the entities in an xml world file.
*/
#define WORLD_TAG "World"
#define ASSETS_TAG "Assets"
#define ENTITIES_TAG "Entities"
#define ENTITY_TAG "Entity"
#define NAME_TAG "Name"
#define COMPONENTS_TAG "Components"
#define NODES_TAG "Nodes"
/*
<!-- An example of the structure of an xml world file -->
<World>
<Entity>
<Name>
"The entity's name"
<Name/>
<Components>
<!--
A list of
components
stored in
the entity.
-->
<Components/>
<Nodes>
<!--
A list of
nodes stored
in the entity.
-->
<Nodes/>
<Entity/>
<!--
More entities
....
-->
<World/>
*/
#endif | 15.339623 | 66 | 0.597786 | jordanlittlefair |
5164f4efc116badb10d2b6ddc9de96185a4dd22c | 966 | cpp | C++ | lab5ex6.cpp | nuriyevanar0/cpp-first-sem-labs | 6811b4339b9781f01d21ab0224a3ddf4ecf6a7a7 | [
"MIT"
] | null | null | null | lab5ex6.cpp | nuriyevanar0/cpp-first-sem-labs | 6811b4339b9781f01d21ab0224a3ddf4ecf6a7a7 | [
"MIT"
] | null | null | null | lab5ex6.cpp | nuriyevanar0/cpp-first-sem-labs | 6811b4339b9781f01d21ab0224a3ddf4ecf6a7a7 | [
"MIT"
] | null | null | null | #include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
/*
Laboratory 5 Ex 6
Write a program to generate two-dimentional array with random numbers and find maximum element in the whole array.
Print array and maximum element.
*/
int main() {
srand (time(NULL));
int array1[3][3];
int row = 3, column = 3;
// Generating Random two-dimensional array
for (int i = 0; i < column; i++)
{
for(int j = 0; j < row; j++)
{
array1[i][j] = rand() % 10;
}
}
//Printing Array
for (int i = 0; i < column; i++)
{
for(int j = 0; j < row; j++)
{
cout << array1[i][j] << " ";
}
cout << "\n";
}
//Finding maximum element in the Array
int maxElement;
for (int i = 0; i < column; i++)
{
for (int j = 0; j < row; j++)
{
if (array1[i][j] > maxElement)
{
maxElement = array1[i][j];
}
}
}
cout << "Maximum element is "<< maxElement << endl;
return 0;
}
| 19.714286 | 116 | 0.546584 | nuriyevanar0 |
51654a8f49d8be92abdbac129a1f8b07f8e8422a | 22,383 | cpp | C++ | external/modeling/tri_integrator.cpp | raphaelsulzer/mesh-tools | 73150bec58813e2b9b750205807002a1c3f18884 | [
"MIT"
] | 1 | 2022-02-24T03:39:05.000Z | 2022-02-24T03:39:05.000Z | external/modeling/tri_integrator.cpp | raphaelsulzer/mesh-tools | 73150bec58813e2b9b750205807002a1c3f18884 | [
"MIT"
] | 1 | 2022-02-24T06:59:59.000Z | 2022-03-04T01:25:09.000Z | external/modeling/tri_integrator.cpp | raphaelsulzer/mesh-tools | 73150bec58813e2b9b750205807002a1c3f18884 | [
"MIT"
] | null | null | null | /*
Copyright (c) 2010, Matt Berger
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 University of Utah nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "tri_integrator.h"
TriIntegrator::TriIntegrator(Vector3RB _point, Vector3RB _v1, Vector3RB _v2, Vector3RB _v3, double _eps, double _lambda) {
v1 = _v1;
v2 = _v2;
v3 = _v3;
point = _point;
eps = _eps;
normal = (v2-v1).cross(v3-v1);
area = 0.5*normal.length();
normal.normalize();
verify = false;
// setup integration, determine if approximation is ok
this->tri_integrals();
double approx_lambda = _lambda;
double shortest_length = point.length(closest_point);
double d1 = v1.length(point), d2 = v2.length(point), d3 = v3.length(point);
double inv_shortest_length = 1.0 / shortest_length;
use_approximation = (inv_shortest_length*d1) < approx_lambda && (inv_shortest_length*d2) < approx_lambda &&
(inv_shortest_length*d3) < approx_lambda;
}
TriIntegrator::TriIntegrator(Vector3RB _point, Vector3RB _v1, Vector3RB _v2, Vector3RB _v3, double _eps) {
v1 = _v1;
v2 = _v2;
v3 = _v3;
point = _point;
eps = _eps;
normal = (v2-v1).cross(v3-v1);
area = 0.5*normal.length();
normal.normalize();
verify = false;
use_approximation = false;
this->tri_integrals();
}
// assumption: ONLY LINE INTEGRALS!
TriIntegrator::TriIntegrator(Vector3RB _pt, double _eps) {
point = _pt;
eps = _eps;
}
TriIntegrator::~TriIntegrator() {
}
double TriIntegrator::weight_eval(Vector3RB _p1, Vector3RB _p2) {
return 1.0 / (_p1.sqdDist(_p2) + (eps*eps));
}
double TriIntegrator::weight_eval_sqd(Vector3RB _p1, Vector3RB _p2) {
double main_weight = _p1.sqdDist(_p2) + (eps*eps);
return 1.0 / (main_weight*main_weight);
}
double TriIntegrator::weight_eval_cbd(Vector3RB _p1, Vector3RB _p2) {
double main_weight = _p1.sqdDist(_p2) + (eps*eps);
return 1.0 / (main_weight*main_weight*main_weight);
}
double TriIntegrator::constant_integration() {
if(use_approximation) {
Vector3RB bary = (v1+v2+v3)*(1.0/3.0);
double w = this->weight_eval_sqd(bary, point);
return area*w;
}
// else
return this->numerical_constant_integration();
}
double TriIntegrator::numerical_constant_integration() {
double full_integral = 0, full_area = 0;
double* inner_integration = new double[num_steps];
for(int t = 0; t < num_subtris; t++) {
SubTri sub_tri = subdivided_tris[t];
Vector3RB weighty_pt, lesser_pt;
if(this->weight_eval(sub_tri.v2, point) > this->weight_eval(sub_tri.v3, point)) {
weighty_pt = sub_tri.v2;
lesser_pt = sub_tri.v3;
}
else {
weighty_pt = sub_tri.v3;
lesser_pt = sub_tri.v2;
}
Vector3RB edge_perp = (lesser_pt-weighty_pt).cross(normal);
edge_perp.normalize();
Vector3RB edge_dir = weighty_pt-sub_tri.o;
edge_dir.normalize();
Vector3RB integral_dir = edge_dir.cross(normal);
// inner analytical integration: solve at each step point
for(unsigned i = 0; i < num_steps; i++) {
double alpha = nonuniform_steps[i];
Vector3RB e1 = sub_tri.o*(1.0-alpha) + lesser_pt*alpha;
Vector3RB e2 = ray_plane_intersection(weighty_pt, edge_perp, e1, edge_dir);
if(e1 == e2)
cout << "positions equal?? " << alpha << endl;
double analytical_integral = this->constant_line_integration(e1, e2);
//double analytical_integral = this->weight_eval_sqd((e1+e2)*0.5, point);
inner_integration[i] = analytical_integral;
}
// outer numerical integration: trapezoidal rule
double sub_integral = 0;
for(unsigned i = 1; i < num_steps; i++) {
double alpha_0 = nonuniform_steps[i-1];
Vector3RB e1_0 = sub_tri.o*(1.0-alpha_0) + lesser_pt*alpha_0;
double alpha_1 = nonuniform_steps[i];
Vector3RB e1_1 = sub_tri.o*(1.0-alpha_1) + lesser_pt*alpha_1;
Vector3RB proj_pt = orthogonal_projection(e1_0, e1_1, integral_dir);
double step_size = e1_0.length(proj_pt);
sub_integral += 0.5*(inner_integration[i-1]+inner_integration[i])*step_size;
}
full_integral += sub_integral;
}
delete [] inner_integration;
// VERIFICATION: monte-carlo integration
if(verify) {
int num_samples = 900000;
double mc_integral = 0;
for(int i = 0; i < num_samples; i++) {
double u = (double)rand() / (double)RAND_MAX;
double v = (double)rand() / (double)RAND_MAX;
double tmp = sqrt(u);
double b1 = 1.0-tmp;
double b2 = v*tmp;
double b3 = (1.0-b1-b2);
Vector3RB rand_pt = v1*b1 + v2*b2 + v3*b3;
mc_integral += this->weight_eval_sqd(rand_pt, point);
}
mc_integral *= (area / (double)num_samples);
cout << "constant quadrature integral: " << full_integral << " ; mc integral: " << mc_integral << endl;
}
return full_integral;
}
double TriIntegrator::linear_integration(TriFunction _f) {
if(use_approximation) {
Vector3RB bary = (v1+v2+v3)*(1.0/3.0);
double w = this->weight_eval_sqd(bary, point);
double bary_f = (_f.f1+_f.f2+_f.f3)/3.0;
return bary_f*area*w;
}
// else
return this->numerical_linear_integration(_f);
}
double TriIntegrator::numerical_linear_integration(TriFunction _f) {
double full_integral = 0, full_area = 0;
double* inner_integration = new double[num_steps];
for(int t = 0; t < num_subtris; t++) {
SubTri sub_tri = subdivided_tris[t];
Vector3RB weighty_pt, lesser_pt;
if(this->weight_eval(sub_tri.v2, point) > this->weight_eval(sub_tri.v3, point)) {
weighty_pt = sub_tri.v2;
lesser_pt = sub_tri.v3;
}
else {
weighty_pt = sub_tri.v3;
lesser_pt = sub_tri.v2;
}
Vector3RB edge_perp = (lesser_pt-weighty_pt).cross(normal);
edge_perp.normalize();
Vector3RB edge_dir = weighty_pt-sub_tri.o;
edge_dir.normalize();
Vector3RB integral_dir = edge_dir.cross(normal);
double b0_1, b1_1, b2_1;
double b0_2, b1_2, b2_2;
// inner analytical integration: solve at each step point
for(unsigned i = 0; i < num_steps; i++) {
double alpha = nonuniform_steps[i];
Vector3RB e1 = sub_tri.o*(1.0-alpha) + lesser_pt*alpha;
this->barycentric_coordinate(e1, b0_1, b1_1, b2_1);
Vector3RB e2 = ray_plane_intersection(weighty_pt, edge_perp, e1, edge_dir);
this->barycentric_coordinate(e2, b0_2, b1_2, b2_2);
double f1 = _f.f1*b0_1 + _f.f2*b1_1 + _f.f3*b2_1;
double f2 = _f.f1*b0_2 + _f.f2*b1_2 + _f.f3*b2_2;
double analytical_integral = this->linear_line_integration(e1, e2, f1, f2);
inner_integration[i] = analytical_integral;
}
// outer numerical integration: trapezoidal rule
double sub_integral = 0;
for(unsigned i = 1; i < num_steps; i++) {
double alpha_0 = nonuniform_steps[i-1];
Vector3RB e1_0 = sub_tri.o*(1.0-alpha_0) + lesser_pt*alpha_0;
double alpha_1 = nonuniform_steps[i];
Vector3RB e1_1 = sub_tri.o*(1.0-alpha_1) + lesser_pt*alpha_1;
Vector3RB proj_pt = orthogonal_projection(e1_0, e1_1, integral_dir);
double step_size = e1_0.length(proj_pt);
sub_integral += 0.5*(inner_integration[i-1]+inner_integration[i])*step_size;
}
full_integral += sub_integral;
}
delete [] inner_integration;
// VERIFICATION: monte-carlo integration
if(verify) {
int num_samples = 900000;
double mc_integral = 0;
for(int i = 0; i < num_samples; i++) {
double u = (double)rand() / (double)RAND_MAX;
double v = (double)rand() / (double)RAND_MAX;
double tmp = sqrt(u);
double b1 = 1.0-tmp;
double b2 = v*tmp;
double b3 = (1.0-b1-b2);
Vector3RB rand_pt = v1*b1 + v2*b2 + v3*b3;
double rand_f = _f.f1*b1 + _f.f2*b2 + _f.f3*b3;
mc_integral += rand_f*this->weight_eval_sqd(rand_pt, point);
}
mc_integral *= (area / (double)num_samples);
cout << "linear quadrature integral["<<num_subtris<<"] : " << full_integral << " ; mc integral: " << mc_integral << endl;
}
return full_integral;
}
double TriIntegrator::product_integration(TriFunction _f, TriFunction _g) {
if(use_approximation) {
Vector3RB bary = (v1+v2+v3)*(1.0/3.0);
double w = this->weight_eval_sqd(bary, point);
double bary_f = (_f.f1+_f.f2+_f.f3)/3.0;
double bary_g = (_g.f1+_g.f2+_g.f3)/3.0;
return bary_f*bary_g*area*w;
}
// else
return this->numerical_product_integration(_f, _g);
}
double TriIntegrator::numerical_product_integration(TriFunction _f, TriFunction _g) {
double full_integral = 0, full_area = 0;
for(int t = 0; t < num_subtris; t++) {
SubTri sub_tri = subdivided_tris[t];
Vector3RB weighty_pt, lesser_pt;
if(this->weight_eval(sub_tri.v2, point) > this->weight_eval(sub_tri.v3, point)) {
weighty_pt = sub_tri.v2;
lesser_pt = sub_tri.v3;
}
else {
weighty_pt = sub_tri.v3;
lesser_pt = sub_tri.v2;
}
Vector3RB edge_perp = (lesser_pt-weighty_pt).cross(normal);
edge_perp.normalize();
Vector3RB edge_dir = weighty_pt-sub_tri.o;
edge_dir.normalize();
Vector3RB integral_dir = edge_dir.cross(normal);
double b0_1, b1_1, b2_1;
double b0_2, b1_2, b2_2;
// inner analytical integration: solve at each step point
vector<double> inner_integration;
for(unsigned i = 0; i < num_steps; i++) {
double alpha = nonuniform_steps[i];
Vector3RB e1 = sub_tri.o*(1.0-alpha) + lesser_pt*alpha;
this->barycentric_coordinate(e1, b0_1, b1_1, b2_1);
Vector3RB e2 = ray_plane_intersection(weighty_pt, edge_perp, e1, edge_dir);
this->barycentric_coordinate(e2, b0_2, b1_2, b2_2);
double f1 = _f.f1*b0_1 + _f.f2*b1_1 + _f.f3*b2_1;
double g1 = _g.f1*b0_1 + _g.f2*b1_1 + _g.f3*b2_1;
double f2 = _f.f1*b0_2 + _f.f2*b1_2 + _f.f3*b2_2;
double g2 = _g.f1*b0_2 + _g.f2*b1_2 + _g.f3*b2_2;
double analytical_integral = this->quadratic_line_integration(e1, e2, f1, f2, g1, g2);
inner_integration.push_back(analytical_integral);
}
// outer numerical integration: trapezoidal rule
double sub_integral = 0;
for(unsigned i = 1; i < num_steps; i++) {
double alpha_0 = nonuniform_steps[i-1];
Vector3RB e1_0 = sub_tri.o*(1.0-alpha_0) + lesser_pt*alpha_0;
double alpha_1 = nonuniform_steps[i];
Vector3RB e1_1 = sub_tri.o*(1.0-alpha_1) + lesser_pt*alpha_1;
Vector3RB proj_pt = orthogonal_projection(e1_0, e1_1, integral_dir);
double step_size = e1_0.length(proj_pt);
sub_integral += 0.5*(inner_integration[i-1]+inner_integration[i])*step_size;
}
full_integral += sub_integral;
}
// VERIFICATION: monte-carlo integration
if(verify) {
int num_samples = 900000;
double mc_integral = 0;
for(int i = 0; i < num_samples; i++) {
double u = (double)rand() / (double)RAND_MAX;
double v = (double)rand() / (double)RAND_MAX;
double tmp = sqrt(u);
double b1 = 1.0-tmp;
double b2 = v*tmp;
double b3 = (1.0-b1-b2);
Vector3RB rand_pt = v1*b1 + v2*b2 + v3*b3;
double rand_f = _f.f1*b1 + _f.f2*b2 + _f.f3*b3;
double rand_g = _g.f1*b1 + _g.f2*b2 + _g.f3*b3;
mc_integral += rand_f*rand_g*this->weight_eval_sqd(rand_pt, point);
}
mc_integral *= (area / (double)num_samples);
cout << "quadratic quadrature integral: " << full_integral << " ; mc integral: " << mc_integral << endl;
}
return full_integral;
}
Vector3RB TriIntegrator::gradient_integration() {
if(use_approximation) {
Vector3RB bary = (v1+v2+v3)*(1.0/3.0);
double w = this->weight_eval_cbd(bary, point);
return (bary-point)*4.0*area*w;
}
// else
return this->numerical_gradient_integration();
}
Vector3RB TriIntegrator::numerical_gradient_integration() {
Vector3RB full_integral(0,0,0);
Vector3RB* inner_integration = new Vector3RB[num_steps];
for(int t = 0; t < num_subtris; t++) {
SubTri sub_tri = subdivided_tris[t];
Vector3RB weighty_pt, lesser_pt;
if(this->weight_eval(sub_tri.v2, point) > this->weight_eval(sub_tri.v3, point)) {
weighty_pt = sub_tri.v2;
lesser_pt = sub_tri.v3;
}
else {
weighty_pt = sub_tri.v3;
lesser_pt = sub_tri.v2;
}
Vector3RB edge_perp = (lesser_pt-weighty_pt).cross(normal);
edge_perp.normalize();
Vector3RB edge_dir = weighty_pt-sub_tri.o;
edge_dir.normalize();
Vector3RB integral_dir = edge_dir.cross(normal);
// inner analytical integration: solve at each step point
for(unsigned i = 0; i < num_steps; i++) {
double alpha = nonuniform_steps[i];
Vector3RB e1 = sub_tri.o*(1.0-alpha) + lesser_pt*alpha;
Vector3RB e2 = ray_plane_intersection(weighty_pt, edge_perp, e1, edge_dir);
inner_integration[i] = this->gradient_line_integration(e1, e2);
}
// outer numerical integration: trapezoidal rule
Vector3RB sub_integral(0,0,0);
for(unsigned i = 1; i < num_steps; i++) {
double alpha_0 = nonuniform_steps[i-1];
Vector3RB e1_0 = sub_tri.o*(1.0-alpha_0) + lesser_pt*alpha_0;
double alpha_1 = nonuniform_steps[i];
Vector3RB e1_1 = sub_tri.o*(1.0-alpha_1) + lesser_pt*alpha_1;
Vector3RB proj_pt = orthogonal_projection(e1_0, e1_1, integral_dir);
double step_size = e1_0.length(proj_pt);
sub_integral = sub_integral + (inner_integration[i-1]+inner_integration[i])*0.5*step_size;
}
full_integral = full_integral + sub_integral;
}
delete [] inner_integration;
// VERIFICATION: monte-carlo integration
if(verify) {
int num_samples = 900000;
Vector3RB mc_integral(0,0,0);
for(int i = 0; i < num_samples; i++) {
double u = (double)rand() / (double)RAND_MAX;
double v = (double)rand() / (double)RAND_MAX;
double tmp = sqrt(u);
double b1 = 1.0-tmp;
double b2 = v*tmp;
double b3 = (1.0-b1-b2);
Vector3RB rand_pt = v1*b1 + v2*b2 + v3*b3;
mc_integral = mc_integral + (rand_pt-point)*4.0*this->weight_eval_cbd(rand_pt,point);
}
mc_integral = mc_integral*(area / (double)num_samples);
cout << "gradient quadrature integral: " << full_integral << " ; mc integral: " << mc_integral << endl;
}
return full_integral;
}
double TriIntegrator::inv_quadratic_integral(double _a, double _b, double _c) {
double c1 = sqrt(4.0*_a*_c-_b*_b);
return (2.0/c1)*(atan( (2.0*_a+_b)/(c1) ) - atan( (_b)/(c1) ));
//return 2.0/c1;
}
double TriIntegrator::inv_sqd_quadratic_integral(double _a, double _b, double _c) {
double c1_sqd = 4.0*_a*_c-_b*_b;
double factor1 = ( ((2.0*_a+_b) / (_a+_b+_c)) - (_b/_c) ) / c1_sqd;
double factor2 = (2.0*_a) / c1_sqd;
return factor1 + factor2*this->inv_quadratic_integral(_a,_b,_c);
}
double TriIntegrator::inv_cubic_integral(double _a, double _b, double _c) {
double descr = 4.0*_a*_c-_b*_b;
double sqd_sum = (_a+_b+_c)*(_a+_b+_c);
double factor1 = ( ((2.0*_a+_b)/sqd_sum) - (_b/(_c*_c)) ) / (2.0*descr);
double factor2 = (3.0*_a) / descr;
return factor1 + factor2*this->inv_sqd_quadratic_integral(_a,_b,_c);
}
double TriIntegrator::inv_linear_sqd_quadratic_integral(double _a, double _b, double _c) {
double c1_sqd = 4.0*_a*_c-_b*_b;
double factor1 = -( ((_b+2.0*_c) / (_a+_b+_c)) - 2.0 ) / c1_sqd;
double factor2 = -_b / c1_sqd;
return factor1 + factor2*this->inv_quadratic_integral(_a,_b,_c);
}
double TriIntegrator::inv_linear_cubic_integral(double _a, double _b, double _c) {
double descr = 4.0*_a*_c-_b*_b;
double sqd_sum = (_a+_b+_c)*(_a+_b+_c);
double factor1 = -( ((_b+2.0*_c)/sqd_sum) - (2.0/_c) ) / (2.0*descr);
double factor2 = -(3.0*_b)/(2.0*descr);
return factor1 + factor2*this->inv_sqd_quadratic_integral(_a,_b,_c);
}
double TriIntegrator::constant_line_integration(Vector3RB _p1, Vector3RB _p2) {
Vector3RB v1 = point-_p1, v2 = _p1-_p2;
double a = v2.dotProduct(v2), b = 2.0*v1.dotProduct(v2), c = v1.dotProduct(v1) + eps*eps;
double descr = 4.0*a*c-b*b;
if(descr == 0) {
cout << "line " << _p1 << " " << _p2 << " : " << point << endl;
}
double line_length = _p1.length(_p2);
double full_integral = line_length*this->inv_sqd_quadratic_integral(a,b,c);
return full_integral;
}
double TriIntegrator::linear_line_integration(Vector3RB _p1, Vector3RB _p2, double _f1, double _f2) {
Vector3RB v1 = point-_p1, v2 = _p1-_p2;
double a = v2.dotProduct(v2), b = 2.0*v1.dotProduct(v2), c = v1.dotProduct(v1) + eps*eps;
double line_length = _p1.length(_p2);
double full_integral = line_length*(_f1*this->inv_sqd_quadratic_integral(a,b,c) + (_f2-_f1)*this->inv_linear_sqd_quadratic_integral(a,b,c));
return full_integral;
}
double TriIntegrator::quadratic_line_integration(Vector3RB _p1, Vector3RB _p2, double _f1, double _f2, double _g1, double _g2) {
Vector3RB v1 = point-_p1, v2 = _p1-_p2;
double a = v2.dotProduct(v2), b = 2.0*v1.dotProduct(v2), c = v1.dotProduct(v1) + eps*eps;
double line_length = _p1.length(_p2);
double alpha_1 = (_f2-_f1)*(_g2-_g1);
double alpha_2 = (_f2-_f1)*_g1 + (_g2-_g1)*_f1;
double alpha_3 = _f1*_g1;
double simple_factor = (alpha_1/a)*this->inv_quadratic_integral(a,b,c);
double const_factor = (alpha_3 - (alpha_1*c)/a)*this->inv_sqd_quadratic_integral(a,b,c);
double linear_factor = (alpha_2 - (alpha_1*b)/a)*this->inv_linear_sqd_quadratic_integral(a,b,c);
double full_integral = line_length*(simple_factor+const_factor+linear_factor);
return full_integral;
}
Vector3RB TriIntegrator::gradient_line_integration(Vector3RB _p1, Vector3RB _p2) {
Vector3RB v1 = point-_p1, v2 = _p1-_p2;
double a = v2.dotProduct(v2), b = 2.0*v1.dotProduct(v2), c = v1.dotProduct(v1) + eps*eps;
double line_length = _p1.length(_p2);
Vector3RB factor1 = point;
Vector3RB factor2_1 = _p1, factor2_2 = _p2-_p1;
double integral1 = line_length*this->inv_cubic_integral(a,b,c);
double integral2 = line_length*this->inv_linear_cubic_integral(a,b,c);
return ((factor2_1*integral1 + factor2_2*integral2) - factor1*integral1)*4.0;
}
void TriIntegrator::tri_integrals() {
if(point == v1) {
num_subtris = 1;
subdivided_tris[0] = SubTri(v1, v2, v3);
closest_point = v1;
return;
}
else if(point == v2) {
num_subtris = 1;
subdivided_tris[0] = SubTri(v2, v3, v1);
closest_point = v2;
return;
}
else if(point == v3) {
num_subtris = 1;
subdivided_tris[0] = SubTri(v3, v1, v2);
closest_point = v3;
return;
}
// --- first step: project point onto plane, and subdivide triangle based on projected point --- //
Vector3RB orthog_pt = point + normal*(v1-point).dotProduct(normal);
Vector3RB area_normal1 = (v2-orthog_pt).cross(v3-orthog_pt);
Vector3RB area_normal2 = (v3-orthog_pt).cross(v1-orthog_pt);
Vector3RB area_normal3 = (v1-orthog_pt).cross(v2-orthog_pt);
bool is_area1_positive = area_normal1.dotProduct(normal) > 0;
bool is_area2_positive = area_normal2.dotProduct(normal) > 0;
bool is_area3_positive = area_normal3.dotProduct(normal) > 0;
// is our projection in the triangle?
if(is_area1_positive && is_area2_positive && is_area3_positive) {
num_subtris = 3;
subdivided_tris[0] = SubTri(orthog_pt, v1, v2);
subdivided_tris[1] = SubTri(orthog_pt, v2, v3);
subdivided_tris[2] = SubTri(orthog_pt, v3, v1);
closest_point = orthog_pt;
return;
}
// otherwise, find the point on the border of the triangle closest to orthog_pt
Vector3RB tri_verts[3];
tri_verts[0] = v1; tri_verts[1] = v2; tri_verts[2] = v3;
// first try the edges ...
bool is_contained = false;
for(int i = 0; i < 3; i++) {
Vector3RB q1 = tri_verts[i], q2 = tri_verts[(i+1)%3], q3 = tri_verts[(i+2)%3];
Vector3RB e1 = q2-q1, e2 = q1-q2;
Vector3RB edge_perp = e2.cross(normal);
is_contained = signed_dist(orthog_pt, q1, edge_perp) > 0 && signed_dist(orthog_pt, q1, e1) > 0 && signed_dist(orthog_pt, q2, e2) > 0;
if(is_contained) {
Vector3RB edge_point = this->edge_projection(q1, q2, normal, orthog_pt);
num_subtris = 2;
subdivided_tris[0] = SubTri(edge_point, q2, q3);
subdivided_tris[1] = SubTri(edge_point, q3, q1);
closest_point = edge_point;
return;
}
}
// ... and last, find closest vertex
int min_ind = 2;
double sqd_dist1 = v1.sqdDist(orthog_pt), sqd_dist2 = v2.sqdDist(orthog_pt), sqd_dist3 = v3.sqdDist(orthog_pt);
if(sqd_dist1 < sqd_dist2 && sqd_dist1 < sqd_dist3)
min_ind = 0;
else if(sqd_dist2 < sqd_dist3)
min_ind = 1;
Vector3RB q1 = tri_verts[min_ind], q2 = tri_verts[(min_ind+1)%3], q3 = tri_verts[(min_ind+2)%3];
num_subtris = 1;
subdivided_tris[0] = SubTri(q1,q2,q3);
closest_point = q1;
}
Vector3RB TriIntegrator::ray_plane_intersection(Vector3RB _p, Vector3RB _n, Vector3RB _m, Vector3RB _d) {
double t = (_p-_m).dotProduct(_n) / _d.dotProduct(_n);
return _m + _d*t;
}
Vector3RB TriIntegrator::orthogonal_projection(Vector3RB _p, Vector3RB _x, Vector3RB _normal) {
return _p + _normal*((_p-_x).dotProduct(_normal)/_normal.dotProduct(_normal));
}
double TriIntegrator::signed_dist(Vector3RB _p, Vector3RB _x, Vector3RB _normal) {
return ((_p-_x).dotProduct(_normal)) / _normal.dotProduct(_normal);
}
Vector3RB TriIntegrator::edge_projection(Vector3RB _v1, Vector3RB _v2, Vector3RB _normal, Vector3RB _point) {
// get normal of edge -> just cross of edge with normal
Vector3RB edge_normal = (_v2-_v1).cross(_normal);
edge_normal.normalize();
// projection of _point onto plane spanned by edge normal
return _point + edge_normal*(_v1-_point).dotProduct(edge_normal);
}
void TriIntegrator::barycentric_coordinate(Vector3RB _point, double& b1, double& b2, double& b3) {
double area1 = 0.5*((_point-v2).cross(_point-v3)).length();
double area2 = 0.5*((_point-v3).cross(_point-v1)).length();
double area3 = 0.5*((_point-v1).cross(_point-v2)).length();
double inv_area = 1.0 / area;
b1 = area1*inv_area;
b2 = area2*inv_area;
b3 = area3*inv_area;
}
| 35.698565 | 141 | 0.705669 | raphaelsulzer |
5165566847d1911f4bc07185ae61e0d32f02d691 | 5,813 | cc | C++ | vm/message_loop_epoll.cc | Outcue/primordialsoup | 056dd858b011c2f3bc71b9f15240061d1d0760ad | [
"Apache-2.0"
] | 35 | 2016-05-20T03:59:10.000Z | 2022-02-21T09:59:14.000Z | vm/message_loop_epoll.cc | Outcue/primordialsoup | 056dd858b011c2f3bc71b9f15240061d1d0760ad | [
"Apache-2.0"
] | 7 | 2020-11-22T04:53:24.000Z | 2021-04-18T02:14:09.000Z | vm/message_loop_epoll.cc | Outcue/primordialsoup | 056dd858b011c2f3bc71b9f15240061d1d0760ad | [
"Apache-2.0"
] | 4 | 2017-02-15T04:26:37.000Z | 2020-11-21T02:29:23.000Z | // Copyright (c) 2018, the Newspeak project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "vm/globals.h" // NOLINT
#if defined(OS_ANDROID) || defined(OS_LINUX)
#include "vm/message_loop.h"
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/epoll.h>
#include <sys/timerfd.h>
#include <unistd.h>
#include "vm/lockers.h"
#include "vm/os.h"
namespace psoup {
static bool SetBlockingHelper(intptr_t fd, bool blocking) {
intptr_t status;
status = fcntl(fd, F_GETFL);
if (status < 0) {
perror("fcntl(F_GETFL) failed");
return false;
}
status = blocking ? (status & ~O_NONBLOCK) : (status | O_NONBLOCK);
if (fcntl(fd, F_SETFL, status) < 0) {
perror("fcntl(F_SETFL, O_NONBLOCK) failed");
return false;
}
return true;
}
EPollMessageLoop::EPollMessageLoop(Isolate* isolate)
: MessageLoop(isolate),
mutex_(),
head_(NULL),
tail_(NULL),
wakeup_(0) {
int result = pipe(interrupt_fds_);
if (result != 0) {
FATAL("Failed to create pipe");
}
if (!SetBlockingHelper(interrupt_fds_[0], false)) {
FATAL("Failed to set pipe fd non-blocking\n");
}
timer_fd_ = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC);
if (timer_fd_ == -1) {
FATAL("Failed to creater timer_fd");
}
epoll_fd_ = epoll_create(64);
if (epoll_fd_ == -1) {
FATAL("Failed to create epoll");
}
struct epoll_event event;
event.events = EPOLLIN;
event.data.fd = interrupt_fds_[0];
int status = epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, interrupt_fds_[0], &event);
if (status == -1) {
FATAL("Failed to add pipe to epoll");
}
event.events = EPOLLIN;
event.data.fd = timer_fd_;
status = epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, timer_fd_, &event);
if (status == -1) {
FATAL("Failed to add timer_fd to epoll");
}
}
EPollMessageLoop::~EPollMessageLoop() {
close(epoll_fd_);
close(timer_fd_);
close(interrupt_fds_[0]);
close(interrupt_fds_[1]);
}
intptr_t EPollMessageLoop::AwaitSignal(intptr_t fd, intptr_t signals) {
struct epoll_event event;
event.events = EPOLLRDHUP | EPOLLET;
if (signals & (1 << kReadEvent)) {
event.events |= EPOLLIN;
}
if (signals & (1 << kWriteEvent)) {
event.events |= EPOLLOUT;
}
event.data.fd = fd;
int status = epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, fd, &event);
if (status == -1) {
FATAL("Failed to add to epoll");
}
return fd;
}
void EPollMessageLoop::CancelSignalWait(intptr_t wait_id) {
UNIMPLEMENTED();
}
void EPollMessageLoop::MessageEpilogue(int64_t new_wakeup) {
wakeup_ = new_wakeup;
struct itimerspec it;
memset(&it, 0, sizeof(it));
if (new_wakeup != 0) {
it.it_value.tv_sec = new_wakeup / kNanosecondsPerSecond;
it.it_value.tv_nsec = new_wakeup % kNanosecondsPerSecond;
}
timerfd_settime(timer_fd_, TFD_TIMER_ABSTIME, &it, NULL);
if ((open_ports_ == 0) && (wakeup_ == 0)) {
Exit(0);
}
}
void EPollMessageLoop::Exit(intptr_t exit_code) {
exit_code_ = exit_code;
isolate_ = NULL;
}
void EPollMessageLoop::PostMessage(IsolateMessage* message) {
MutexLocker locker(&mutex_);
if (head_ == NULL) {
head_ = tail_ = message;
Notify();
} else {
tail_->next_ = message;
tail_ = message;
}
}
void EPollMessageLoop::Notify() {
uword message = 0;
ssize_t written = write(interrupt_fds_[1], &message, sizeof(message));
if (written != sizeof(message)) {
FATAL("Failed to atomically write notify message");
}
}
IsolateMessage* EPollMessageLoop::TakeMessages() {
MutexLocker locker(&mutex_);
IsolateMessage* message = head_;
head_ = tail_ = NULL;
return message;
}
intptr_t EPollMessageLoop::Run() {
while (isolate_ != NULL) {
static const intptr_t kMaxEvents = 16;
struct epoll_event events[kMaxEvents];
int result = epoll_wait(epoll_fd_, events, kMaxEvents, -1);
if (result <= 0) {
if ((errno != EWOULDBLOCK) && (errno != EINTR)) {
FATAL("epoll_wait failed");
}
} else {
for (int i = 0; i < result; i++) {
if (events[i].data.fd == interrupt_fds_[0]) {
// Interrupt fd.
uword message = 0;
ssize_t red = read(interrupt_fds_[0], &message, sizeof(message));
if (red != sizeof(message)) {
FATAL("Failed to atomically write notify message");
}
} else if (events[i].data.fd == timer_fd_) {
int64_t value;
ssize_t ignore = read(timer_fd_, &value, sizeof(value));
(void)ignore;
DispatchWakeup();
} else {
intptr_t fd = events[i].data.fd;
intptr_t pending = 0;
if (events[i].events & EPOLLERR) {
pending |= 1 << kErrorEvent;
}
if (events[i].events & EPOLLIN) {
pending |= 1 << kReadEvent;
}
if (events[i].events & EPOLLOUT) {
pending |= 1 << kWriteEvent;
}
if (events[i].events & EPOLLHUP) {
pending |= 1 << kCloseEvent;
}
if (events[i].events & EPOLLRDHUP) {
pending |= 1 << kCloseEvent;
}
DispatchSignal(fd, 0, pending, 0);
}
}
}
IsolateMessage* message = TakeMessages();
while (message != NULL) {
IsolateMessage* next = message->next_;
DispatchMessage(message);
message = next;
}
}
if (open_ports_ > 0) {
PortMap::CloseAllPorts(this);
}
while (head_ != NULL) {
IsolateMessage* message = head_;
head_ = message->next_;
delete message;
}
return exit_code_;
}
void EPollMessageLoop::Interrupt() {
Exit(SIGINT);
Notify();
}
} // namespace psoup
#endif // defined(OS_ANDROID) || defined(OS_LINUX)
| 25.384279 | 80 | 0.62429 | Outcue |
5169c78622a0ad2debdf3bee0f2f1700c8106601 | 1,232 | cpp | C++ | Round-Robin/Frame.cpp | MichelDequick/mbed-round-robin | dbdcf88ac30be2e64c2de286b99f3bebe8f3a2e1 | [
"Apache-2.0"
] | null | null | null | Round-Robin/Frame.cpp | MichelDequick/mbed-round-robin | dbdcf88ac30be2e64c2de286b99f3bebe8f3a2e1 | [
"Apache-2.0"
] | null | null | null | Round-Robin/Frame.cpp | MichelDequick/mbed-round-robin | dbdcf88ac30be2e64c2de286b99f3bebe8f3a2e1 | [
"Apache-2.0"
] | null | null | null | #include "Frame.h"
#include "mbed.h"
Frame::Frame(char * data)
{
this->data = data;
memset(id, 0x00, 32);
}
Frame::~Frame(void)
{
}
void Frame::decode(void)
{
len = data[2];
idd = data[3];
tmp = (data[4] << 8) + data[5];;
pwm = data[6];
tun = data[7];
for(int i = 8; i < (strlen(data) - 3); i++) {
id[i-8] = data[i];
}
crc = data[strlen(data)-4];
}
void Frame::checkCRC(void)
{
}
void Frame::calculateCRC(void)
{
}
void Frame::generate(char * data)
{
memset(data, 0x00, 256);
data[0] = FRAME_SOF_1;
data[1] = FRAME_SOF_2;
data[2] = len;
data[3] = idd;
data[4] = 1;
data[5] = 203;
// data[4] = tmp >> 8;
// data[5] = tmp & 0xFF;
data[6] = pwm;
data[7] = tun;
// for(int i = 0; i < (strlen(id)); i++) {
// data[7 + i] = id[i];
// }
data[8] = 108;
data[9] = crc;
data[10] = FRAME_EOF_1;
data[11] = FRAME_EOF_2;
// data[6 + strlen(id) + 1] = 109;
// data[6 + strlen(id) + 2] = crc;
// data[6 + strlen(id) + 3] = FRAME_EOF_1;
// data[6 + strlen(id) + 4] = FRAME_EOF_2;
for(int i = 0; i < (strlen(data)); i++) {
printf("Data[%i]: %i\n\r", i, data[i]);
}
}
| 16.648649 | 49 | 0.474026 | MichelDequick |
51722affefe3e10e1e4ff6656bfad18534cffa69 | 18,567 | cxx | C++ | Modules/Registration/Common/test/itkLandmarkBasedTransformInitializerTest.cxx | lassoan/ITK | 4634cb0490934f055065230e3db64df8f546b72a | [
"Apache-2.0"
] | 2 | 2019-09-15T10:17:06.000Z | 2019-09-15T10:19:06.000Z | Modules/Registration/Common/test/itkLandmarkBasedTransformInitializerTest.cxx | lassoan/ITK | 4634cb0490934f055065230e3db64df8f546b72a | [
"Apache-2.0"
] | null | null | null | Modules/Registration/Common/test/itkLandmarkBasedTransformInitializerTest.cxx | lassoan/ITK | 4634cb0490934f055065230e3db64df8f546b72a | [
"Apache-2.0"
] | 1 | 2021-09-23T08:33:37.000Z | 2021-09-23T08:33:37.000Z | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 "itkLandmarkBasedTransformInitializer.h"
#include "itkImage.h"
#include "itkObject.h"
#include "itkTestingMacros.h"
#include <iostream>
template <unsigned int Dimension>
typename itk::Image<unsigned char, Dimension>::Pointer
CreateTestImage()
{
using FixedImageType = itk::Image<unsigned char, Dimension>;
typename FixedImageType::Pointer image = FixedImageType::New();
typename FixedImageType::RegionType fRegion;
typename FixedImageType::SizeType fSize;
typename FixedImageType::IndexType fIndex;
fSize.Fill(30); // size 30 x 30 x 30
fIndex.Fill(0);
fRegion.SetSize(fSize);
fRegion.SetIndex(fIndex);
image->SetLargestPossibleRegion(fRegion);
image->SetBufferedRegion(fRegion);
image->SetRequestedRegion(fRegion);
image->Allocate();
return image;
}
// Moving Landmarks = Fixed Landmarks rotated by 'angle' degrees and then
// translated by the 'translation'. Offset can be used to move the fixed
// landmarks around.
template <typename TTransformInitializer>
void
Init3DPoints(typename TTransformInitializer::LandmarkPointContainer & fixedLandmarks,
typename TTransformInitializer::LandmarkPointContainer & movingLandmarks)
{
const double nPI = 4.0 * std::atan(1.0);
typename TTransformInitializer::LandmarkPointType point;
typename TTransformInitializer::LandmarkPointType tmp;
double angle = 10 * nPI / 180.0;
typename TTransformInitializer::LandmarkPointType translation;
translation[0] = 6;
translation[1] = 10;
translation[2] = 7;
typename TTransformInitializer::LandmarkPointType offset;
offset[0] = 10;
offset[1] = 1;
offset[2] = 5;
point[0] = 2 + offset[0];
point[1] = 2 + offset[1];
point[2] = 0 + offset[2];
fixedLandmarks.push_back(point);
tmp = point;
point[0] = std::cos(angle) * point[0] - std::sin(angle) * point[1] + translation[0];
point[1] = std::sin(angle) * tmp[0] + std::cos(angle) * point[1] + translation[1];
point[2] = point[2] + translation[2];
movingLandmarks.push_back(point);
point[0] = 2 + offset[0];
point[1] = -2 + offset[1];
point[2] = 0 + offset[2];
fixedLandmarks.push_back(point);
tmp = point;
point[0] = std::cos(angle) * point[0] - std::sin(angle) * point[1] + translation[0];
point[1] = std::sin(angle) * tmp[0] + std::cos(angle) * point[1] + translation[1];
point[2] = point[2] + translation[2];
movingLandmarks.push_back(point);
point[0] = -2 + offset[0];
point[1] = 2 + offset[1];
point[2] = 0 + offset[2];
fixedLandmarks.push_back(point);
tmp = point;
point[0] = std::cos(angle) * point[0] - std::sin(angle) * point[1] + translation[0];
point[1] = std::sin(angle) * tmp[0] + std::cos(angle) * point[1] + translation[1];
point[2] = point[2] + translation[2];
movingLandmarks.push_back(point);
point[0] = -2 + offset[0];
point[1] = -2 + offset[1];
point[2] = 0 + offset[2];
fixedLandmarks.push_back(point);
tmp = point;
point[0] = std::cos(angle) * point[0] - std::sin(angle) * point[1] + translation[0];
point[1] = std::sin(angle) * tmp[0] + std::cos(angle) * point[1] + translation[1];
point[2] = point[2] + translation[2];
movingLandmarks.push_back(point);
}
template <typename TransformInitializerType>
bool
ExecuteAndExamine(typename TransformInitializerType::Pointer initializer,
typename TransformInitializerType::LandmarkPointContainer fixedLandmarks,
typename TransformInitializerType::LandmarkPointContainer movingLandmarks,
unsigned failLimit = 0)
{
typename TransformInitializerType::TransformType::Pointer transform = TransformInitializerType::TransformType::New();
initializer->SetTransform(transform);
initializer->InitializeTransform();
// Transform the landmarks now. For the given set of landmarks, since we computed the
// moving landmarks explicitly from the rotation and translation specified, we should
// get a transform that does not give any mismatch. In other words, if the fixed
// landmarks are transformed by the transform computed by the
// LandmarkBasedTransformInitializer, they should coincide exactly with the moving
// landmarks. Note that we specified 4 landmarks, although three non-collinear
// landmarks is sufficient to guarantee a solution.
typename TransformInitializerType::PointsContainerConstIterator fitr = fixedLandmarks.begin();
typename TransformInitializerType::PointsContainerConstIterator mitr = movingLandmarks.begin();
using OutputVectorType = typename TransformInitializerType::OutputVectorType;
OutputVectorType error;
typename OutputVectorType::RealValueType tolerance = 0.1;
unsigned int failed = 0;
while (mitr != movingLandmarks.end())
{
typename TransformInitializerType::LandmarkPointType transformedPoint = transform->TransformPoint(*fitr);
std::cout << " Fixed Landmark: " << *fitr << " Moving landmark " << *mitr
<< " Transformed fixed Landmark : " << transformedPoint;
error = *mitr - transformedPoint;
std::cout << " error = " << error.GetNorm() << std::endl;
if (error.GetNorm() > tolerance)
{
failed++;
}
++mitr;
++fitr;
}
if (failed > failLimit)
{
std::cout << " Fixed landmarks transformed by the transform did not match closely "
<< "enough with the moving landmarks. The transform computed was: ";
transform->Print(std::cout);
std::cout << "[FAILED]" << std::endl;
return false;
}
else
{
std::cout << " Landmark alignment using " << transform->GetNameOfClass() << " [PASSED]" << std::endl;
}
return true;
}
// Test LandmarkBasedTransformInitializer for given transform type
// Returns false if test failed, true if it succeeded
template <typename TransformType>
bool
test1()
{
typename TransformType::Pointer transform = TransformType::New();
std::cout << "Testing Landmark alignment with " << transform->GetNameOfClass() << std::endl;
using PixelType = unsigned char;
constexpr unsigned int Dimension = 3;
using FixedImageType = itk::Image<PixelType, Dimension>;
using MovingImageType = itk::Image<PixelType, Dimension>;
using TransformInitializerType =
itk::LandmarkBasedTransformInitializer<TransformType, FixedImageType, MovingImageType>;
typename TransformInitializerType::Pointer initializer = TransformInitializerType::New();
typename TransformInitializerType::LandmarkPointContainer fixedLandmarks;
typename TransformInitializerType::LandmarkPointContainer movingLandmarks;
Init3DPoints<TransformInitializerType>(fixedLandmarks, movingLandmarks);
// No landmarks are set, it should throw
ITK_TRY_EXPECT_EXCEPTION(initializer->InitializeTransform());
initializer->SetMovingLandmarks(movingLandmarks);
ITK_TRY_EXPECT_EXCEPTION(initializer->InitializeTransform()); // Fixed landmarks missing
initializer->SetFixedLandmarks(fixedLandmarks);
return ExecuteAndExamine<TransformInitializerType>(initializer, fixedLandmarks, movingLandmarks);
}
// The test specifies a bunch of fixed and moving landmarks and tests if the
// fixed landmarks after transform by the computed transform coincides
// with the moving landmarks.
int
itkLandmarkBasedTransformInitializerTest(int, char *[])
{
bool success = true;
success &= test1<itk::VersorRigid3DTransform<double>>();
// Rigid3DTransform isn't supported by the landmark based initializer
// success &= test1<itk::Rigid3DTransform< double > >();
using PixelType = unsigned char;
{
// Test landmark alignment using Rigid 2D transform in 2 dimensions
std::cout << "Testing Landmark alignment with Rigid2DTransform" << std::endl;
constexpr unsigned int Dimension = 2;
using FixedImageType = itk::Image<PixelType, Dimension>;
using MovingImageType = itk::Image<PixelType, Dimension>;
FixedImageType::Pointer fixedImage = CreateTestImage<Dimension>();
MovingImageType::Pointer movingImage = CreateTestImage<Dimension>();
// Set the transform type
using TransformType = itk::Rigid2DTransform<double>;
using TransformInitializerType =
itk::LandmarkBasedTransformInitializer<TransformType, FixedImageType, MovingImageType>;
TransformInitializerType::Pointer initializer = TransformInitializerType::New();
ITK_EXERCISE_BASIC_OBJECT_METHODS(initializer, LandmarkBasedTransformInitializer, Object);
initializer->DebugOn();
// Set fixed and moving landmarks
TransformInitializerType::LandmarkPointContainer fixedLandmarks;
TransformInitializerType::LandmarkPointContainer movingLandmarks;
TransformInitializerType::LandmarkPointType point;
TransformInitializerType::LandmarkPointType tmp;
// Moving Landmarks = Fixed Landmarks rotated by 'angle' degrees and then
// translated by the 'translation'. Offset can be used to move the fixed
// landmarks around.
const double nPI = 4.0 * std::atan(1.0);
double angle = 10 * nPI / 180.0;
TransformInitializerType::LandmarkPointType translation;
translation[0] = 6;
translation[1] = 10;
TransformInitializerType::LandmarkPointType offset;
offset[0] = 10;
offset[1] = 1;
point[0] = 2 + offset[0];
point[1] = 2 + offset[1];
fixedLandmarks.push_back(point);
tmp = point;
point[0] = std::cos(angle) * point[0] - std::sin(angle) * point[1] + translation[0];
point[1] = std::sin(angle) * tmp[0] + std::cos(angle) * point[1] + translation[1];
movingLandmarks.push_back(point);
point[0] = 2 + offset[0];
point[1] = -2 + offset[1];
fixedLandmarks.push_back(point);
tmp = point;
point[0] = std::cos(angle) * point[0] - std::sin(angle) * point[1] + translation[0];
point[1] = std::sin(angle) * tmp[0] + std::cos(angle) * point[1] + translation[1];
movingLandmarks.push_back(point);
point[0] = -2 + offset[0];
point[1] = 2 + offset[1];
fixedLandmarks.push_back(point);
tmp = point;
point[0] = std::cos(angle) * point[0] - std::sin(angle) * point[1] + translation[0];
point[1] = std::sin(angle) * tmp[0] + std::cos(angle) * point[1] + translation[1];
movingLandmarks.push_back(point);
point[0] = -2 + offset[0];
point[1] = -2 + offset[1];
fixedLandmarks.push_back(point);
tmp = point;
point[0] = std::cos(angle) * point[0] - std::sin(angle) * point[1] + translation[0];
point[1] = std::sin(angle) * tmp[0] + std::cos(angle) * point[1] + translation[1];
movingLandmarks.push_back(point);
// No landmarks are set, it should throw
ITK_TRY_EXPECT_EXCEPTION(initializer->InitializeTransform());
initializer->SetFixedLandmarks(fixedLandmarks);
ITK_TRY_EXPECT_EXCEPTION(initializer->InitializeTransform()); // Moving landmarks missing
initializer->SetMovingLandmarks(movingLandmarks);
success &= ExecuteAndExamine<TransformInitializerType>(initializer, fixedLandmarks, movingLandmarks);
}
{
constexpr unsigned int Dimension = 3;
using ImageType = itk::Image<PixelType, Dimension>;
ImageType::Pointer fixedImage = CreateTestImage<Dimension>();
ImageType::Pointer movingImage = CreateTestImage<Dimension>();
using TransformType = itk::AffineTransform<double, Dimension>;
TransformType::Pointer transform = TransformType::New();
using TransformInitializerType = itk::LandmarkBasedTransformInitializer<TransformType, ImageType, ImageType>;
TransformInitializerType::Pointer initializer = TransformInitializerType::New();
ITK_EXERCISE_BASIC_OBJECT_METHODS(initializer, LandmarkBasedTransformInitializer, Object);
initializer->SetTransform(transform);
// Test that an exception is thrown if there aren't enough points
ITK_TRY_EXPECT_EXCEPTION(initializer->InitializeTransform());
const unsigned int numLandmarks(8);
double fixedLandMarkInit[numLandmarks][3] = {
{ -1.33671, -279.739, 176.001 },
{ 28.0989, -346.692, 183.367 },
{ -1.36713, -257.43, 155.36 },
{ -33.0851, -347.026, 180.865 },
{ -0.16083, -268.529, 148.96 },
{ -0.103873, -251.31, 122.973 },
{ 200, 200, 200 }, // dummy
{ -300, 100, 1000 } // dummy
};
double movingLandmarkInit[numLandmarks][3] = {
{ -1.65605 + 0.011, -30.0661, 20.1656 },
{ 28.1409, -93.1172 + 0.015, -5.34366 },
{ -1.55885, -0.499696 - 0.04, 12.7584 },
{ -33.0151 + 0.001, -92.0973, -8.66965 },
{ -0.189769, -7.3485, 1.74263 + 0.008 },
{ 0.1021, 20.2155, -12.8526 - 0.006 },
{ 200, 200, 200 }, // dummy
{ -300, 100, 1000 } // dummy
};
double weights[numLandmarks] = { 10, 1, 10, 1, 1, 1, 0.001, 0.001 };
{ // First Test with working Landmarks
// These landmark should match properly
constexpr unsigned int numWorkingLandmark = 6;
TransformInitializerType::LandmarkPointContainer fixedLandmarks;
TransformInitializerType::LandmarkPointContainer movingLandmarks;
TransformInitializerType::LandmarkWeightType landmarkWeights;
for (unsigned i = 0; i < numWorkingLandmark; ++i)
{
TransformInitializerType::LandmarkPointType fixedPoint, movingPoint;
for (unsigned j = 0; j < 3; ++j)
{
fixedPoint[j] = fixedLandMarkInit[i][j];
movingPoint[j] = movingLandmarkInit[i][j];
}
fixedLandmarks.push_back(fixedPoint);
movingLandmarks.push_back(movingPoint);
landmarkWeights.push_back(weights[i]);
}
initializer->SetFixedLandmarks(fixedLandmarks);
initializer->SetMovingLandmarks(movingLandmarks);
initializer->SetLandmarkWeight(landmarkWeights);
std::cerr << "Transform " << transform << std::endl;
success &= ExecuteAndExamine<TransformInitializerType>(initializer, fixedLandmarks, movingLandmarks);
}
{ // Test with dummy points
// dummy points should not matched based on given weights
constexpr unsigned int numDummyLandmark = 8;
TransformInitializerType::LandmarkPointContainer fixedLandmarks;
TransformInitializerType::LandmarkPointContainer movingLandmarks;
TransformInitializerType::LandmarkWeightType landmarkWeights;
for (unsigned i = 0; i < numDummyLandmark; ++i)
{
TransformInitializerType::LandmarkPointType fixedPoint, movingPoint;
for (unsigned j = 0; j < 3; ++j)
{
fixedPoint[j] = fixedLandMarkInit[i][j];
movingPoint[j] = movingLandmarkInit[i][j];
}
fixedLandmarks.push_back(fixedPoint);
movingLandmarks.push_back(movingPoint);
landmarkWeights.push_back(weights[i]);
}
initializer->SetFixedLandmarks(fixedLandmarks);
initializer->SetMovingLandmarks(movingLandmarks);
initializer->SetLandmarkWeight(landmarkWeights);
std::cerr << "Transform " << transform << std::endl;
success &= ExecuteAndExamine<TransformInitializerType>(initializer, fixedLandmarks, movingLandmarks, 2);
} // Second test with dummy
}
{
std::cout << "\nTesting Landmark alignment with BSplineTransform..." << std::endl;
constexpr unsigned int Dimension = 3;
using FixedImageType = itk::Image<PixelType, Dimension>;
using MovingImageType = itk::Image<PixelType, Dimension>;
FixedImageType::Pointer fixedImage = CreateTestImage<Dimension>();
MovingImageType::Pointer movingImage = CreateTestImage<Dimension>();
FixedImageType::PointType origin;
origin[0] = -5;
origin[1] = -5;
origin[2] = -5;
fixedImage->SetOrigin(origin);
// Set the transform type
constexpr unsigned int SplineOrder = 3;
using TransformType = itk::BSplineTransform<double, FixedImageType::ImageDimension, SplineOrder>;
TransformType::Pointer transform = TransformType::New();
using TransformInitializerType =
itk::LandmarkBasedTransformInitializer<TransformType, FixedImageType, MovingImageType>;
TransformInitializerType::Pointer initializer = TransformInitializerType::New();
ITK_EXERCISE_BASIC_OBJECT_METHODS(initializer, LandmarkBasedTransformInitializer, Object);
TransformInitializerType::LandmarkPointContainer fixedLandmarks;
TransformInitializerType::LandmarkPointContainer movingLandmarks;
Init3DPoints<TransformInitializerType>(fixedLandmarks, movingLandmarks);
constexpr unsigned int numLandmarks = 4;
double weights[numLandmarks] = { 1, 3, 0.01, 0.5 };
TransformInitializerType::LandmarkWeightType landmarkWeights;
for (double weight : weights)
{
landmarkWeights.push_back(weight);
}
initializer->SetFixedLandmarks(fixedLandmarks);
initializer->SetMovingLandmarks(movingLandmarks);
initializer->SetLandmarkWeight(landmarkWeights);
initializer->SetTransform(transform);
initializer->SetBSplineNumberOfControlPoints(8);
// Test that an exception is thrown if the reference image isn't set
ITK_TRY_EXPECT_EXCEPTION(initializer->InitializeTransform());
// Now set the reference image and initialization should work
initializer->SetReferenceImage(fixedImage);
success &= ExecuteAndExamine<TransformInitializerType>(initializer, fixedLandmarks, movingLandmarks);
}
{
using TransformType = itk::Transform<float, 3, 3>;
using TransformInitializerType = itk::LandmarkBasedTransformInitializer<TransformType>;
TransformInitializerType::Pointer initializer = TransformInitializerType::New();
ITK_EXERCISE_BASIC_OBJECT_METHODS(initializer, LandmarkBasedTransformInitializer, Object);
}
if (!success)
{
return EXIT_FAILURE;
}
std::cout << "Test PASSED!" << std::endl;
return EXIT_SUCCESS;
}
| 38.440994 | 119 | 0.694458 | lassoan |
5174d524b9373318061ff23bb5bc8dc555f6ea5e | 217 | cpp | C++ | chapter-4/4.8.cpp | zero4drift/Cpp-Primer-5th-Exercises | d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f | [
"MIT"
] | null | null | null | chapter-4/4.8.cpp | zero4drift/Cpp-Primer-5th-Exercises | d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f | [
"MIT"
] | null | null | null | chapter-4/4.8.cpp | zero4drift/Cpp-Primer-5th-Exercises | d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f | [
"MIT"
] | null | null | null | // && operator: if the left operand is flase, there is no need to compute the right operand
// || operator: if the left operand is true, there is no need to compute the right operand
// == operator: there is no order
| 54.25 | 91 | 0.723502 | zero4drift |
5176f73ee52bf7a3246e4672abf3bd45bbd3d757 | 1,560 | cpp | C++ | cpp/beginner_contest_147/d.cpp | kitoko552/atcoder | a1e18b6d855baefb90ae6df010bcf1ffa8ff5562 | [
"MIT"
] | 1 | 2020-03-31T05:53:38.000Z | 2020-03-31T05:53:38.000Z | cpp/beginner_contest_147/d.cpp | kitoko552/atcoder | a1e18b6d855baefb90ae6df010bcf1ffa8ff5562 | [
"MIT"
] | null | null | null | cpp/beginner_contest_147/d.cpp | kitoko552/atcoder | a1e18b6d855baefb90ae6df010bcf1ffa8ff5562 | [
"MIT"
] | null | null | null | #include<iostream>
#include<algorithm>
#include<cmath>
#include<vector>
#include<map>
#include<queue>
#define rep(i, n) for (int i = 0; i < (n); ++i)
#define rep1(i, n) for (int i = 1; i < (n); ++i)
using namespace std;
using ll = long long;
using P = pair<int, int>;
const int INF = 1001001001;
const int mod = 1000000007;
struct mint {
ll x;
mint(ll x=0):x((x%mod+mod)%mod){}
mint operator-() const { return mint(-x);}
mint& operator+=(const mint a) {
if ((x += a.x) >= mod) x -= mod;
return *this;
}
mint& operator-=(const mint a) {
if ((x += mod-a.x) >= mod) x -= mod;
return *this;
}
mint& operator*=(const mint a) {
(x *= a.x) %= mod;
return *this;
}
mint operator+(const mint a) const {
mint res(*this);
return res+=a;
}
mint operator-(const mint a) const {
mint res(*this);
return res-=a;
}
mint operator*(const mint a) const {
mint res(*this);
return res*=a;
}
mint pow(ll t) const {
if (!t) return 1;
mint a = pow(t>>1);
a *= a;
if (t&1) a *= *this;
return a;
}
// for prime mod
mint inv() const {
return pow(mod-2);
}
mint& operator/=(const mint a) {
return (*this) *= a.inv();
}
mint operator/(const mint a) const {
mint res(*this);
return res/=a;
}
};
int main() {
int N;
cin >> N;
ll A[N];
rep(i,N) cin >> A[i];
mint ans = 0;
rep(k,60) {
mint n1 = 0;
rep(i,N) {
if((A[i] >> k) & 1) n1+=1;
}
ans += n1*(mint(N)-n1)*mint(2).pow(k);
}
cout << ans.x << endl;
return 0;
}
| 18.795181 | 48 | 0.527564 | kitoko552 |
517854476b5e9fdff130edbcaef0775d56a1532c | 232 | cpp | C++ | project/CrafterraTest/CrafterraTest/Source.cpp | AsPJT/CrafterraProterozoic | d0531d2052b1bb5c10b6763f74034e6e3c678d1f | [
"CC0-1.0"
] | null | null | null | project/CrafterraTest/CrafterraTest/Source.cpp | AsPJT/CrafterraProterozoic | d0531d2052b1bb5c10b6763f74034e6e3c678d1f | [
"CC0-1.0"
] | null | null | null | project/CrafterraTest/CrafterraTest/Source.cpp | AsPJT/CrafterraProterozoic | d0531d2052b1bb5c10b6763f74034e6e3c678d1f | [
"CC0-1.0"
] | null | null | null | #ifdef _OPENMP
#include <omp.h>
#endif
#ifdef _WIN32
#include <DxLib.h>
#ifndef __DXLIB
#define __DXLIB
#endif
#ifndef __WINDOWS__
#define __WINDOWS__
#endif
#else
#include <Siv3D.hpp>
#endif
#include <Sample/UseAsLib2/Sample1.hpp>
| 14.5 | 39 | 0.767241 | AsPJT |
5178b2e86f3dbef7adc5c9095dc278415c475dac | 5,554 | cpp | C++ | unittest/util.cpp | Jamaika1/charls | 2abc1561925031b10f68666421315b2f3c63bbab | [
"BSD-3-Clause"
] | null | null | null | unittest/util.cpp | Jamaika1/charls | 2abc1561925031b10f68666421315b2f3c63bbab | [
"BSD-3-Clause"
] | null | null | null | unittest/util.cpp | Jamaika1/charls | 2abc1561925031b10f68666421315b2f3c63bbab | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) Team CharLS.
// SPDX-License-Identifier: BSD-3-Clause
#include "pch.h"
#include "util.h"
#include <charls/charls.h>
#include "../src/jpeg_stream_writer.h"
#include "../test/portable_anymap_file.h"
using Microsoft::VisualStudio::CppUnitTestFramework::Assert;
using std::ifstream;
using std::vector;
using namespace charls;
using namespace charls_test;
namespace {
void triplet_to_planar(vector<uint8_t>& buffer, uint32_t width, uint32_t height)
{
vector<uint8_t> workBuffer(buffer.size());
const size_t byteCount = static_cast<size_t>(width) * height;
for (size_t index = 0; index < byteCount; index++)
{
workBuffer[index] = buffer[index * 3 + 0];
workBuffer[index + 1 * byteCount] = buffer[index * 3 + 1];
workBuffer[index + 2 * byteCount] = buffer[index * 3 + 2];
}
swap(buffer, workBuffer);
}
} // namespace
vector<uint8_t> read_file(const char* filename)
{
ifstream input;
input.exceptions(input.eofbit | input.failbit | input.badbit);
input.open(filename, input.in | input.binary);
input.seekg(0, input.end);
const auto byteCountFile = static_cast<int>(input.tellg());
input.seekg(0, input.beg);
vector<uint8_t> buffer(byteCountFile);
input.read(reinterpret_cast<char*>(buffer.data()), buffer.size());
return buffer;
}
portable_anymap_file read_anymap_reference_file(const char* filename, const interleave_mode interleave_mode, const frame_info& frame_info)
{
portable_anymap_file reference_file(filename);
if (interleave_mode == interleave_mode::none && frame_info.component_count == 3)
{
triplet_to_planar(reference_file.image_data(), frame_info.width, frame_info.height);
}
return reference_file;
}
portable_anymap_file read_anymap_reference_file(const char* filename, const interleave_mode interleave_mode)
{
portable_anymap_file reference_file(filename);
if (interleave_mode == interleave_mode::none && reference_file.component_count() == 3)
{
triplet_to_planar(reference_file.image_data(), reference_file.width(), reference_file.height());
}
return reference_file;
}
vector<uint8_t> create_test_spiff_header(const uint8_t high_version, const uint8_t low_version, const bool end_of_directory)
{
vector<uint8_t> buffer;
buffer.push_back(0xFF);
buffer.push_back(0xD8); // SOI.
buffer.push_back(0xFF);
buffer.push_back(0xE8); // ApplicationData8
buffer.push_back(0);
buffer.push_back(32);
// SPIFF identifier string.
buffer.push_back('S');
buffer.push_back('P');
buffer.push_back('I');
buffer.push_back('F');
buffer.push_back('F');
buffer.push_back(0);
// Version
buffer.push_back(high_version);
buffer.push_back(low_version);
buffer.push_back(0); // profile id
buffer.push_back(3); // component count
// Height
buffer.push_back(0);
buffer.push_back(0);
buffer.push_back(0x3);
buffer.push_back(0x20);
// Width
buffer.push_back(0);
buffer.push_back(0);
buffer.push_back(0x2);
buffer.push_back(0x58);
buffer.push_back(10); // color space
buffer.push_back(8); // bits per sample
buffer.push_back(6); // compression type, 6 = JPEG-LS
buffer.push_back(1); // resolution units
// vertical_resolution
buffer.push_back(0);
buffer.push_back(0);
buffer.push_back(0);
buffer.push_back(96);
// header.horizontal_resolution = 1024;
buffer.push_back(0);
buffer.push_back(0);
buffer.push_back(4);
buffer.push_back(0);
const size_t spiff_header_size = buffer.size();
buffer.resize(buffer.size() + 100);
const ByteStreamInfo info = FromByteArray(buffer.data() + spiff_header_size, buffer.size() - spiff_header_size);
JpegStreamWriter writer(info);
if (end_of_directory)
{
writer.WriteSpiffEndOfDirectoryEntry();
}
writer.WriteStartOfFrameSegment(100, 100, 8, 1);
writer.WriteStartOfScanSegment(1, 0, interleave_mode::none);
return buffer;
}
vector<uint8_t> create_noise_image_16bit(const size_t pixel_count, const int bit_count, const uint32_t seed)
{
srand(seed);
vector<uint8_t> buffer(pixel_count * 2);
const auto mask = static_cast<uint16_t>((1 << bit_count) - 1);
for (size_t i = 0; i < pixel_count; i = i + 2)
{
const uint16_t value = static_cast<uint16_t>(rand()) & mask;
buffer[i] = static_cast<uint8_t>(value);
buffer[i] = static_cast<uint8_t>(value >> 8);
}
return buffer;
}
void test_round_trip_legacy(const vector<uint8_t>& source, const JlsParameters& params)
{
vector<uint8_t> encodedBuffer(params.height * params.width * params.components * params.bitsPerSample / 4);
vector<uint8_t> decodedBuffer(static_cast<size_t>(params.height) * params.width * ((params.bitsPerSample + 7) / 8) * params.components);
size_t compressedLength = 0;
auto error = JpegLsEncode(encodedBuffer.data(), encodedBuffer.size(), &compressedLength,
source.data(), source.size(), ¶ms, nullptr);
Assert::AreEqual(jpegls_errc::success, error);
error = JpegLsDecode(decodedBuffer.data(), decodedBuffer.size(), encodedBuffer.data(), compressedLength, nullptr, nullptr);
Assert::AreEqual(jpegls_errc::success, error);
const uint8_t* byteOut = decodedBuffer.data();
for (size_t i = 0; i < decodedBuffer.size(); ++i)
{
if (source[i] != byteOut[i])
{
Assert::IsTrue(false);
break;
}
}
}
| 29.700535 | 140 | 0.684732 | Jamaika1 |
5178f25f4875cdbef934fb4fc3337045663a5abb | 26,635 | cpp | C++ | OgreMain/src/OgreProfiler.cpp | FreeNightKnight/ogre-next | f2d1a31887a87c492b4225e063325c48693fec19 | [
"MIT"
] | null | null | null | OgreMain/src/OgreProfiler.cpp | FreeNightKnight/ogre-next | f2d1a31887a87c492b4225e063325c48693fec19 | [
"MIT"
] | null | null | null | OgreMain/src/OgreProfiler.cpp | FreeNightKnight/ogre-next | f2d1a31887a87c492b4225e063325c48693fec19 | [
"MIT"
] | null | null | null | /*
-----------------------------------------------------------------------------
This source file is part of OGRE-Next
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
/*
Although the code is original, many of the ideas for the profiler were borrowed from
"Real-Time In-Game Profiling" by Steve Rabin which can be found in Game Programming
Gems 1.
This code can easily be adapted to your own non-Ogre project. The only code that is
Ogre-dependent is in the visualization/logging routines and the use of the Timer class.
Enjoy!
*/
#include "OgreProfiler.h"
#include "OgreLogManager.h"
#include "OgreRenderSystem.h"
#include "OgreRoot.h"
#include "OgreTimer.h"
namespace Ogre
{
//-----------------------------------------------------------------------
// PROFILE DEFINITIONS
//-----------------------------------------------------------------------
template <>
Profiler *Singleton<Profiler>::msSingleton = 0;
Profiler *Profiler::getSingletonPtr() { return msSingleton; }
Profiler &Profiler::getSingleton()
{
assert( msSingleton );
return ( *msSingleton );
}
//-----------------------------------------------------------------------
Profile::Profile( const String &profileName, ProfileSampleFlags::ProfileSampleFlags flags,
uint32 groupID ) :
mName( profileName ),
mGroupID( groupID )
{
Ogre::Profiler::getSingleton().beginProfile( profileName, groupID, flags );
}
//-----------------------------------------------------------------------
Profile::~Profile() { Ogre::Profiler::getSingleton().endProfile( mName, mGroupID ); }
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// PROFILER DEFINITIONS
//-----------------------------------------------------------------------
Profiler::Profiler() :
mCurrent( &mRoot ),
mLast( NULL ),
mRoot(),
mInitialized( false ),
mUpdateDisplayFrequency( 10 ),
mCurrentFrame( 0 ),
mTimer( 0 ),
mTotalFrameTime( 0 ),
mEnabled( OGRE_PROFILING == OGRE_PROFILING_INTERNAL_OFFLINE ),
mUseStableMarkers( false ),
mNewEnableState( false ),
mProfileMask( 0xFFFFFFFF ),
mMaxTotalFrameTime( 0 ),
mAverageFrameTime( 0 ),
mResetExtents( false )
#if OGRE_PROFILING == OGRE_PROFILING_REMOTERY
,
mRemotery( 0 )
#endif
{
mRoot.hierarchicalLvl = std::numeric_limits<uint>::max();
}
//-----------------------------------------------------------------------
ProfileInstance::ProfileInstance() :
parent( NULL ),
frameNumber( 0 ),
accum( 0 ),
hierarchicalLvl( 0 )
{
history.numCallsThisFrame = 0;
history.totalTimePercent = 0;
history.totalTimeMillisecs = 0;
history.totalCalls = 0;
history.maxTimePercent = 0;
history.maxTimeMillisecs = 0;
history.minTimePercent = 1;
history.minTimeMillisecs = 100000;
history.currentTimePercent = 0;
history.currentTimeMillisecs = 0;
frame.frameTime = 0;
frame.calls = 0;
}
ProfileInstance::~ProfileInstance() { destroyAllChildren(); }
//-----------------------------------------------------------------------
Profiler::~Profiler()
{
if( !mRoot.children.empty() )
{
// log the results of our profiling before we quit
logResults();
}
// clear all our lists
mDisabledProfiles.clear();
#if OGRE_PROFILING == OGRE_PROFILING_REMOTERY
if( mRemotery )
{
Root::getSingleton().getRenderSystem()->deinitGPUProfiling();
rmt_DestroyGlobalInstance( mRemotery );
mRemotery = 0;
}
#endif
}
//-----------------------------------------------------------------------
void Profiler::setTimer( Timer *t ) { mTimer = t; }
//-----------------------------------------------------------------------
Timer *Profiler::getTimer()
{
assert( mTimer && "Timer not set!" );
return mTimer;
}
//-----------------------------------------------------------------------
void Profiler::setEnabled( bool enabled )
{
#if OGRE_PROFILING != OGRE_PROFILING_INTERNAL_OFFLINE
if( !mInitialized && enabled )
{
for( TProfileSessionListener::iterator i = mListeners.begin(); i != mListeners.end(); ++i )
( *i )->initializeSession();
# if OGRE_PROFILING == OGRE_PROFILING_REMOTERY
rmtSettings *settings = rmt_Settings();
settings->messageQueueSizeInBytes *= 10;
settings->maxNbMessagesPerUpdate *= 10;
rmt_CreateGlobalInstance( &mRemotery );
rmt_SetCurrentThreadName( "Main Ogre Thread" );
Root::getSingleton().getRenderSystem()->initGPUProfiling();
# endif
mInitialized = true;
}
else if( mInitialized )
{
for( TProfileSessionListener::iterator i = mListeners.begin(); i != mListeners.end(); ++i )
( *i )->finializeSession();
mInitialized = false;
mEnabled = false;
# if OGRE_PROFILING == OGRE_PROFILING_REMOTERY
Root::getSingleton().getRenderSystem()->deinitGPUProfiling();
if( mRemotery )
{
rmt_DestroyGlobalInstance( mRemotery );
mRemotery = 0;
}
# endif
}
#else
mEnabled = enabled;
mOfflineProfiler.setPaused( !enabled );
#endif
// We store this enable/disable request until the frame ends
// (don't want to screw up any open profiles!)
mNewEnableState = enabled;
}
//-----------------------------------------------------------------------
bool Profiler::getEnabled() const { return mEnabled; }
//-----------------------------------------------------------------------
void Profiler::setUseStableMarkers( bool useStableMarkers ) { mUseStableMarkers = useStableMarkers; }
//-----------------------------------------------------------------------
bool Profiler::getUseStableMarkers() const { return mUseStableMarkers; }
//-----------------------------------------------------------------------
void Profiler::changeEnableState()
{
for( TProfileSessionListener::iterator i = mListeners.begin(); i != mListeners.end(); ++i )
( *i )->changeEnableState( mNewEnableState );
mEnabled = mNewEnableState;
}
//-----------------------------------------------------------------------
void Profiler::disableProfile( const String &profileName )
{
// even if we are in the middle of this profile, endProfile() will still end it.
mDisabledProfiles.insert( profileName );
}
//-----------------------------------------------------------------------
void Profiler::enableProfile( const String &profileName ) { mDisabledProfiles.erase( profileName ); }
//-----------------------------------------------------------------------
void Profiler::beginProfile( const String &profileName, uint32 groupID,
ProfileSampleFlags::ProfileSampleFlags flags )
{
#if OGRE_PROFILING == OGRE_PROFILING_INTERNAL_OFFLINE
mOfflineProfiler.profileBegin( profileName.c_str(), flags );
#else
// regardless of whether or not we are enabled, we need the application's root profile (ie the
// first profile started each frame) we need this so bogus profiles don't show up when users
// enable profiling mid frame so we check
// if the profiler is enabled
if( !mEnabled )
return;
// mask groups
if( ( groupID & mProfileMask ) == 0 )
return;
// we only process this profile if isn't disabled
if( mDisabledProfiles.find( profileName ) != mDisabledProfiles.end() )
return;
// empty string is reserved for the root
// not really fatal anymore, however one shouldn't name one's profile as an empty string anyway.
assert( ( profileName != "" ) && ( "Profile name can't be an empty string" ) );
// this would be an internal error.
assert( mCurrent );
// need a timer to profile!
assert( mTimer && "Timer not set!" );
ProfileInstance *&instance = mCurrent->childrenMap[profileName];
if( instance )
{ // found existing child.
// Sanity check.
assert( instance->name == profileName );
if( instance->frameNumber != mCurrentFrame )
{ // new frame, reset stats
instance->frame.calls = 0;
instance->frame.frameTime = 0;
instance->frameNumber = mCurrentFrame;
}
}
else
{ // new child!
instance = OGRE_NEW ProfileInstance();
instance->name = profileName;
instance->parent = mCurrent;
instance->hierarchicalLvl = mCurrent->hierarchicalLvl + 1;
mCurrent->children.push_back( instance );
}
instance->frameNumber = mCurrentFrame;
mCurrent = instance;
// we do this at the very end of the function to get the most
// accurate timing results
mCurrent->currTime = mTimer->getMicroseconds();
#endif
}
//-----------------------------------------------------------------------
void Profiler::endProfile( const String &profileName, uint32 groupID )
{
#if OGRE_PROFILING == OGRE_PROFILING_INTERNAL_OFFLINE
mOfflineProfiler.profileEnd();
#else
if( !mEnabled )
{
// if the profiler received a request to be enabled or disabled
if( mNewEnableState != mEnabled )
{ // note mNewEnableState == true to reach this.
changeEnableState();
// NOTE we will be in an 'error' state until the next begin. ie endProfile will likely
// get invoked using a profileName that was never started. even then, we can't be sure
// that the next beginProfile will be the true start of a new frame
}
return;
}
else
{
if( mNewEnableState != mEnabled )
{ // note mNewEnableState == false to reach this.
changeEnableState();
// unwind the hierarchy, should be easy enough
mCurrent = &mRoot;
mLast = NULL;
}
if( &mRoot == mCurrent && mLast )
{ // profiler was enabled this frame, but the first subsequent beginProfile was NOT the
// beinging of a new frame as we had hoped.
// we have a bogus ProfileInstance in our hierarchy, we will need to remove it, then
// update the overlays so as not to confuse ze user
// we could use mRoot.children.find() instead of this, except we'd be compairing strings
// instead of a pointer. the string way could be faster, but i don't believe it would.
ProfileChildrenVec::iterator it = mRoot.children.begin(), endit = mRoot.children.end();
for( ; it != endit; ++it )
{
if( mLast == *it )
{
mRoot.childrenMap.erase( ( *it )->name );
mRoot.children.erase( it );
break;
}
}
// with mLast == NULL we won't reach this code, in case this isn't the end of the top
// level profile
ProfileInstance *last = mLast;
mLast = NULL;
OGRE_DELETE last;
processFrameStats();
displayResults();
}
}
if( &mRoot == mCurrent )
return;
// mask groups
if( ( groupID & mProfileMask ) == 0 )
return;
// need a timer to profile!
assert( mTimer && "Timer not set!" );
// get the end time of this profile
// we do this as close the beginning of this function as possible
// to get more accurate timing results
const uint64 endTime = mTimer->getMicroseconds();
// empty string is reserved for designating an empty parent
assert( ( profileName != "" ) && ( "Profile name can't be an empty string" ) );
// we only process this profile if isn't disabled
// we check the current instance name against the provided profileName as a guard against
// disabling a profile name /after/ said profile began
if( mCurrent->name != profileName &&
mDisabledProfiles.find( profileName ) != mDisabledProfiles.end() )
return;
// calculate the elapsed time of this profile
const uint64 timeElapsed = endTime - mCurrent->currTime;
// update parent's accumulator if it isn't the root
if( &mRoot != mCurrent->parent )
{
// add this profile's time to the parent's accumlator
mCurrent->parent->accum += timeElapsed;
}
mCurrent->frame.frameTime += timeElapsed;
++mCurrent->frame.calls;
mLast = mCurrent;
mCurrent = mCurrent->parent;
if( &mRoot == mCurrent )
{
// the stack is empty and all the profiles have been completed
// we have reached the end of the frame so process the frame statistics
// we know that the time elapsed of the main loop is the total time the frame took
mTotalFrameTime = timeElapsed;
if( timeElapsed > mMaxTotalFrameTime )
mMaxTotalFrameTime = timeElapsed;
// we got all the information we need, so process the profiles
// for this frame
processFrameStats();
// we display everything to the screen
displayResults();
}
#endif
}
//-----------------------------------------------------------------------
void Profiler::beginGPUEvent( const String &event )
{
Root::getSingleton().getRenderSystem()->beginProfileEvent( event );
}
//-----------------------------------------------------------------------
void Profiler::endGPUEvent( const String &event )
{
Root::getSingleton().getRenderSystem()->endProfileEvent();
}
//-----------------------------------------------------------------------
void Profiler::markGPUEvent( const String &event )
{
Root::getSingleton().getRenderSystem()->markProfileEvent( event );
}
//-----------------------------------------------------------------------
void Profiler::beginGPUSample( const String &name, uint32 *hashCache )
{
Root::getSingleton().getRenderSystem()->beginGPUSampleProfile( name, hashCache );
}
//-----------------------------------------------------------------------
void Profiler::endGPUSample( const String &name )
{
Root::getSingleton().getRenderSystem()->endGPUSampleProfile( name );
}
//-----------------------------------------------------------------------
void Profiler::processFrameStats( ProfileInstance *instance, Real &maxFrameTime )
{
// calculate what percentage of frame time this profile took
const Real framePercentage = (Real)instance->frame.frameTime / (Real)mTotalFrameTime;
const Real frameTimeMillisecs = (Real)instance->frame.frameTime / 1000.0f;
// update the profile stats
instance->history.currentTimePercent = framePercentage;
instance->history.currentTimeMillisecs = frameTimeMillisecs;
if( mResetExtents )
{
instance->history.totalTimePercent = framePercentage;
instance->history.totalTimeMillisecs = frameTimeMillisecs;
instance->history.totalCalls = 1;
}
else
{
instance->history.totalTimePercent += framePercentage;
instance->history.totalTimeMillisecs += frameTimeMillisecs;
instance->history.totalCalls++;
}
instance->history.numCallsThisFrame = instance->frame.calls;
// if we find a new minimum for this profile, update it
if( frameTimeMillisecs < instance->history.minTimeMillisecs || mResetExtents )
{
instance->history.minTimePercent = framePercentage;
instance->history.minTimeMillisecs = frameTimeMillisecs;
}
// if we find a new maximum for this profile, update it
if( frameTimeMillisecs > instance->history.maxTimeMillisecs || mResetExtents )
{
instance->history.maxTimePercent = framePercentage;
instance->history.maxTimeMillisecs = frameTimeMillisecs;
}
if( instance->frame.frameTime > maxFrameTime )
maxFrameTime = (Real)instance->frame.frameTime;
ProfileChildrenVec::iterator it = instance->children.begin(), endit = instance->children.end();
for( ; it != endit; ++it )
{
ProfileInstance *child = *it;
// we set the number of times each profile was called per frame to 0
// because not all profiles are called every frame
child->history.numCallsThisFrame = 0;
if( child->frame.calls > 0 )
{
processFrameStats( child, maxFrameTime );
}
}
}
//-----------------------------------------------------------------------
void Profiler::processFrameStats()
{
Real maxFrameTime = 0;
ProfileChildrenVec::iterator it = mRoot.children.begin(), endit = mRoot.children.end();
for( ; it != endit; ++it )
{
ProfileInstance *child = *it;
// we set the number of times each profile was called per frame to 0
// because not all profiles are called every frame
child->history.numCallsThisFrame = 0;
if( child->frame.calls > 0 )
{
processFrameStats( child, maxFrameTime );
}
}
// Calculate whether the extents are now so out of date they need regenerating
if( mCurrentFrame == 0 )
mAverageFrameTime = maxFrameTime;
else
mAverageFrameTime = ( mAverageFrameTime + maxFrameTime ) * 0.5f;
if( (Real)mMaxTotalFrameTime > mAverageFrameTime * 4 )
{
mResetExtents = true;
mMaxTotalFrameTime = (ulong)mAverageFrameTime;
}
else
mResetExtents = false;
}
//-----------------------------------------------------------------------
void Profiler::displayResults()
{
// if its time to update the display
if( !( mCurrentFrame % mUpdateDisplayFrequency ) )
{
// ensure the root won't be culled
mRoot.frame.calls = 1;
for( TProfileSessionListener::iterator i = mListeners.begin(); i != mListeners.end(); ++i )
( *i )->displayResults( mRoot, mMaxTotalFrameTime );
}
++mCurrentFrame;
}
//-----------------------------------------------------------------------
bool Profiler::watchForMax( const String &profileName )
{
assert( ( profileName != "" ) && ( "Profile name can't be an empty string" ) );
return mRoot.watchForMax( profileName );
}
//-----------------------------------------------------------------------
bool ProfileInstance::watchForMax( const String &profileName )
{
ProfileChildrenVec::iterator it = children.begin(), endit = children.end();
for( ; it != endit; ++it )
{
ProfileInstance *child = *it;
if( ( child->name == profileName && child->watchForMax() ) ||
child->watchForMax( profileName ) )
return true;
}
return false;
}
//-----------------------------------------------------------------------
bool Profiler::watchForMin( const String &profileName )
{
assert( ( profileName != "" ) && ( "Profile name can't be an empty string" ) );
return mRoot.watchForMin( profileName );
}
//-----------------------------------------------------------------------
bool ProfileInstance::watchForMin( const String &profileName )
{
ProfileChildrenVec::iterator it = children.begin(), endit = children.end();
for( ; it != endit; ++it )
{
ProfileInstance *child = *it;
if( ( child->name == profileName && child->watchForMin() ) ||
child->watchForMin( profileName ) )
return true;
}
return false;
}
//-----------------------------------------------------------------------
bool Profiler::watchForLimit( const String &profileName, Real limit, bool greaterThan )
{
assert( ( profileName != "" ) && ( "Profile name can't be an empty string" ) );
return mRoot.watchForLimit( profileName, limit, greaterThan );
}
//-----------------------------------------------------------------------
bool ProfileInstance::watchForLimit( const String &profileName, Real limit, bool greaterThan )
{
ProfileChildrenVec::iterator it = children.begin(), endit = children.end();
for( ; it != endit; ++it )
{
ProfileInstance *child = *it;
if( ( child->name == profileName && child->watchForLimit( limit, greaterThan ) ) ||
child->watchForLimit( profileName, limit, greaterThan ) )
return true;
}
return false;
}
//-----------------------------------------------------------------------
void Profiler::logResults()
{
LogManager::getSingleton().logMessage(
"----------------------Profiler Results----------------------" );
for( ProfileChildrenVec::iterator it = mRoot.children.begin(); it != mRoot.children.end(); ++it )
{
( *it )->logResults();
}
LogManager::getSingleton().logMessage(
"------------------------------------------------------------" );
}
//-----------------------------------------------------------------------
void ProfileInstance::logResults()
{
// create an indent that represents the hierarchical order of the profile
String indent = "";
for( uint i = 0; i < hierarchicalLvl; ++i )
{
indent = indent + "\t";
}
LogManager::getSingleton().logMessage(
indent + "Name " + name + " | Min " + StringConverter::toString( history.minTimePercent ) +
" | Max " + StringConverter::toString( history.maxTimePercent ) + " | Avg " +
StringConverter::toString( history.totalTimePercent / history.totalCalls ) );
for( ProfileChildrenVec::iterator it = children.begin(); it != children.end(); ++it )
{
( *it )->logResults();
}
}
//-----------------------------------------------------------------------
void Profiler::reset( bool deleteAll )
{
mRoot.reset();
mMaxTotalFrameTime = 0;
if( deleteAll )
mRoot.destroyAllChildren();
}
//-----------------------------------------------------------------------
void ProfileInstance::destroyAllChildren()
{
for( ProfileChildrenVec::iterator it = children.begin(); it != children.end(); ++it )
{
ProfileInstance *instance = *it;
OGRE_DELETE instance;
}
children.clear();
childrenMap.clear();
}
//-----------------------------------------------------------------------
void ProfileInstance::reset()
{
history.currentTimePercent = history.maxTimePercent = history.totalTimePercent = 0;
history.currentTimeMillisecs = history.maxTimeMillisecs = history.totalTimeMillisecs = 0;
history.numCallsThisFrame = history.totalCalls = 0;
history.minTimePercent = 1;
history.minTimeMillisecs = 100000;
for( ProfileChildrenVec::iterator it = children.begin(); it != children.end(); ++it )
{
( *it )->reset();
}
}
//-----------------------------------------------------------------------
void Profiler::setUpdateDisplayFrequency( uint freq ) { mUpdateDisplayFrequency = freq; }
//-----------------------------------------------------------------------
uint Profiler::getUpdateDisplayFrequency() const { return mUpdateDisplayFrequency; }
//-----------------------------------------------------------------------
void Profiler::addListener( ProfileSessionListener *listener ) { mListeners.push_back( listener ); }
//-----------------------------------------------------------------------
void Profiler::removeListener( ProfileSessionListener *listener )
{
mListeners.erase( std::find( mListeners.begin(), mListeners.end(), listener ) );
}
//-----------------------------------------------------------------------
} // namespace Ogre
| 39.635417 | 105 | 0.516689 | FreeNightKnight |
517cc35908300e49e7a1922fd1f8cb5a1ea1188e | 10,792 | cpp | C++ | Code/trunk/cpp/Research/ArnoldiResearch.cpp | jlconlin/PhDThesis | 8e704613721a800ce1c59576e94f40fa6f7cd986 | [
"MIT"
] | null | null | null | Code/trunk/cpp/Research/ArnoldiResearch.cpp | jlconlin/PhDThesis | 8e704613721a800ce1c59576e94f40fa6f7cd986 | [
"MIT"
] | null | null | null | Code/trunk/cpp/Research/ArnoldiResearch.cpp | jlconlin/PhDThesis | 8e704613721a800ce1c59576e94f40fa6f7cd986 | [
"MIT"
] | null | null | null | /*ArnoldiResearch.cpp
This code is used to run Arnoldi's method.
*/
#include <iostream>
#include <string>
#include <complex>
#include "LinearSpaceSource.h"
#include "ArnoldiMC.h"
#include "ArnoldiArgs.hpp"
#include "RandomLib/Random.hpp"
#include "gnuFile.h"
#include "gnuplot_i.hpp"
#include "CartesianMesh1D.hh"
#include "Field.hh"
#include "Material.h"
#include "HistSource.h"
#include "Utilities.h"
#include "boost/numeric/ublas/vector.hpp"
#include "boost/numeric/ublas/vector_expression.hpp"
#include "boost/numeric/bindings/traits/ublas_vector.hpp"
#include "boost/numeric/ublas/io.hpp"
using std::cout;
using std::endl;
using std::string;
using std::complex;
namespace ublas = boost::numeric::ublas;
template<class S>
Gnuplot& PlotVectors(ArnoldiArgs&, ArnoldiMC<S>&, S&, Gnuplot&,
CartesianMesh<OneD>&, gnuFile&);
template<>
Gnuplot& PlotVectors(ArnoldiArgs& Args, ArnoldiMC<HistSource>& AMC,
HistSource& InitialSource, Gnuplot& G, CartesianMesh<OneD>& M,
gnuFile& Data){
G.set_style("histeps");
HistSource::ublas_vec_t Centers = InitialSource.Centers();
ArnoldiMC<HistSource>::c_vec_t Mean, SD;
ublas::vector<double> mReal, mImag, sReal, sImag;
for( int i = 0; i < Args.nEigs.getValue(); ++i ){
std::ostringstream title; title << "RAM l-" << i;
AMC.MeanVector(i, Mean, SD);
#ifndef NOPLOT
G.plot_xy(Centers, real(Mean), title.str());
#endif
// Append data to file
title.str(""); title << "RAM eigenvector-" << i;
Data.append(title.str(), Centers, Mean, SD );
}
}
Gnuplot& PlotVectors(ArnoldiArgs& Args, ArnoldiMC<LinearSpaceSource>& AMC,
LinearSpaceSource& InitialSource, Gnuplot& G, CartesianMesh<OneD>& M,
gnuFile& Data){
G.set_style("lines");
ArnoldiMC<HistSource>::c_vec_t Mean, SD;
std::vector<double> Slopes, Intercepts;
std::vector<double>::iterator sIter;
std::vector<double>::iterator iIter;
std::vector<double>::iterator mIter;
std::vector<double> x,y;
for( int i = 0; i < Args.nEigs.getValue(); ++i ){
std::ostringstream title; title << "RAM l-" << i;
AMC.MeanVector(i, Mean, SD);
// Make LinearSpaceSource from Arnoldi vector
LinearSpaceSource LSS(AMC.Seed(), M, real(Mean));
LSS.PlotPoints(x,y);
#ifndef NOPLOT
G.plot_xy(x,y, title.str() );
#endif
// Append data to file
title.str(""); title << "RAM eigenvector-" << i;
Data.append(title.str(), x,y);
}
}
template<class S>
void RunArnoldi(ArnoldiMC<S>& AMC, S& InitialSource, RestartMethod& RM,
std::vector<unsigned long>& seed, CartesianMesh<OneD>& SourceMesh,
ArnoldiArgs& Args){
AMC.RAM( InitialSource, Args.nEigs.getValue(), Args.Iterations.getValue(),
Args.active.getValue(), Args.inactive.getValue(),
Args.tracks.getValue(), RM);
// Post Processing---------------------------------------------------------
std::ostringstream ChartTitle;
ChartTitle << Args.cmdLine() << ", seed = " << seed[0];
std::string Title = ChartTitle.str();
// Make sure Title isn't too long and flow off of chart
if( Title.size() > 120 ){
int j = Title.size()/120.0;
for( int i = 0; i < j; ++i ){
// Find space after 120-th character
int pos = Title.find(" ", (i+1)*120);
if( pos > 0 ) Title.insert(pos, "\\n");
}
}
// Store date in Data
gnuFile Data( Args.filename.getValue() );
Data.appendH( Title );
Data.appendH( Args.Args() );
#ifndef NOPLOT
// Gnuplot plotting
Gnuplot GValues("linespoints");
Gnuplot GVectors("histeps");
Gnuplot GEntropy("lines");
cout << "set terminal " + Args.terminal.getValue() << endl;
GValues.cmd("set terminal " + Args.terminal.getValue() );
GVectors.cmd("set terminal " + Args.terminal.getValue() );
GVectors.cmd("set xzeroaxis");
GEntropy.cmd("set terminal " + Args.terminal.getValue() );
// Plot Eigenvalues
GValues.set_title("Eigenvalues\\n" + Title );
GValues.set_xlabel("Histories Tracked");
GValues.set_ylabel("Mean Eigenvalues");
#endif
std::vector<double> Tracks(AMC.Tracks(true));
std::vector<complex<double> > Mean, SD, Values;
std::vector<double> mReal, mImag, sReal, sImag;
for( int n = 0; n < Args.nEigs.getValue(); ++n ){
std::ostringstream title; title << "RAM l-" << n;
AMC.MeanValues(Mean, SD, n, true);
SplitComplexVector(Mean, mReal, mImag);
SplitComplexVector(SD, sReal, sImag);
#ifndef NOPLOT
GValues.plot_xy_err( Tracks, mReal, sReal, title.str());
#endif
title.str(""); title << "RAM eigenvalue-" << n;
Data.append( title.str(), Tracks, Mean, SD);
title.str(""); title << "raw value-0" << n;
Values = AMC.Values(n, true);
Data.append( title.str(), Tracks, Values );
}
#ifndef NOPLOT
// Plot Eigenvectors
GVectors.set_title("Eigenvectors\\n" + Title );
PlotVectors(Args, AMC, InitialSource, GVectors, SourceMesh, Data);
#endif
// Get time and store it in Data file
std::vector<double> time = AMC.Time();
Data.append("Arnoldi-Time", Tracks, time);
// Get FOM and store it in Data file
std::vector<double> FOM = AMC.FOM();
std::vector<double> ActiveTracks = AMC.Tracks(false);
Data.append("FOM-Arnoldi", ActiveTracks, FOM);
// Plot and store Entropy
GEntropy.set_title("Entropy\\n" + Title );
std::vector<double> Entropy = AMC.Entropy(true);
std::vector<double> IterationsTracks = AMC.TracksbyIteration(true);
GEntropy.plot_xy( IterationsTracks, Entropy, "Entropy-Iterations");
Data.append("Entropy-Iterations", IterationsTracks, Entropy );
Entropy = AMC.EntropyRestart(true);
GEntropy.plot_xy( Tracks, Entropy, "Entropy-Restarts");
Data.append("Entropy-Restarts", Tracks, Entropy );
}
int main(int argc, char** argv){
cout << "Running ArnoldiResearch." << endl;
try{
ArnoldiArgs Args("Arnoldi will run Arnoldi's method.");
// Problem specific arguments
// What Arnoldi methods are allowed
// std::vector<string> AllowedMethods;
// AllowedMethods.push_back("implicit"); AllowedMethods.push_back("explicit");
// TCLAP::ValuesConstraint<string> MethodAllow(AllowedMethods);
// TCLAP::ValueArg<string> method("m", "method", "Restart Method", false,
// "explicit","m");
// method.Constrain(&MethodAllow);
// Args.cmd.add(method);
// What Source types are allowed
std::vector<string> AllowedSources;
AllowedSources.push_back("Histogram"); AllowedSources.push_back("Linear");
TCLAP::ValuesConstraint<string> SourceAllow(AllowedSources);
TCLAP::ValueArg<string> source("c", "source", "Fission Source Type", false,
"Histogram", "c");
source.Constrain(&SourceAllow);
Args.cmd.add(source);
// Parse command line arguments
Args.Parse(argc,argv);
cout << "\n" << Args << endl;
if( Args.run.getValue() ){
cout << "Running Arnoldi's Method" << endl;
//
// Set random seed
std::vector<unsigned long> seed(2, 1);
if( not Args.seed.getValue() ) seed[0] = RandomLib::Random::SeedWord();
else seed[0] = Args.seed.getValue();
cout << "Master seed: " << seed[0] << endl;
// Material from Rathkopf and Martin (1986)
// Material Absorber(0.5,0.5,0.0,1.0); // Absorbing
// Material from Modak et al. (1995)
Material Absorber(0.8,0.2,0.0,5.0); // Absorbing
// Set up materials
std::vector<double> ZoneWidths;
ublas::vector<Material> Media;
if( Args.MultiMedia.getValue() ){ // 5 slab problem from Ueki and Brown (2005)
ZoneWidths.push_back(1.0);
ZoneWidths.push_back(1.0);
ZoneWidths.push_back(5.0);
ZoneWidths.push_back(1.0);
ZoneWidths.push_back(1.0);
Material Scatter( 0.8, 0.0, 0.2, 0.0 );
Material Fuel( 0.8, 0.1, 0.1, 3.0 );
Material Absorber( 0.1, 0.0, 0.9, 0.0 );
Media.resize(5);
Media[0] = Fuel;
Media[1] = Scatter;
Media[2] = Absorber;
Media[3] = Scatter;
Media[4] = Fuel;
}
else{ // One zone
ZoneWidths.push_back( Args.width.getValue() );
Media.resize(1);
Media[0] = Absorber;
}
// Geometry
CartesianMesh<OneD> GeometryMesh( ZoneWidths );
Field<Zone<OneD>, Material, ublas::vector<Material> >
GeometryField(GeometryMesh, Media);
cout << "Materials:\n";
for( int i = 0; i < Media.size(); ++i ){
cout << Media[i] << endl;
}
// Restart Method
RestartMethod RM = EXPLICIT;
// Initial Uniform Source
double totalWidth;
totalWidth = std::accumulate(ZoneWidths.begin(), ZoneWidths.end(), 0.0);
CartesianMesh<OneD> SourceMesh(totalWidth, 1.0, Args.bins.getValue());
if( source.getValue() == "Histogram" ){
ublas::vector<double, std::vector<double> >
Probabilities(Args.bins.getValue(), 0.0);
Probabilities[0] = 1.0;
// Make initial source point source if two-media problem
if( Args.MultiMedia.getValue() ){ // Multi-media problem
Probabilities *= 0.0;
Probabilities[0] = 1.0;
}
HistSource InitialSource(seed, SourceMesh, Probabilities);
ArnoldiMC<HistSource> AMC(seed, GeometryField, SourceMesh,
Args.relaxed.getValue(), Args.verbose.getValue(),
Args.tolerance.getValue() );
RunArnoldi(AMC, InitialSource, RM, seed, SourceMesh, Args);
}
else if( source.getValue() == "Linear" ){
ublas::vector<double> S(SourceMesh.numZones(), 0.0);
ublas::vector<double> I(SourceMesh.numZones(), 0.0);
I[0] = 1.0;
// Make initial source point source if two-media problem
if( Args.MultiMedia.getValue() ){ // Multi-media problem
I *= 0.0;
I[0] = 1.0;
}
LinearSpaceSource InitialSource(S, I, SourceMesh, seed);
ArnoldiMC<LinearSpaceSource> AMC(seed, GeometryField, SourceMesh,
Args.relaxed.getValue(), Args.verbose.getValue(),
Args.tolerance.getValue() );
RunArnoldi(AMC, InitialSource, RM, seed, SourceMesh, Args);
}
}
}
catch (TCLAP::ArgException &e){
std::cerr << "error: " << e.error() << " for arg " << e.argId() << endl;
return 1;
}
return 0;
}
| 33.725 | 88 | 0.599796 | jlconlin |
51829af04373ec22127a695a60160a8edfa14157 | 1,099 | cpp | C++ | 1-CLRS-Solution/C15-Dynamic-Programming/Problem/code/15.4.cpp | ftxj/2th-SummerHO | 422e04478d5904eb3bb75417793a4981ba108e19 | [
"MIT"
] | null | null | null | 1-CLRS-Solution/C15-Dynamic-Programming/Problem/code/15.4.cpp | ftxj/2th-SummerHO | 422e04478d5904eb3bb75417793a4981ba108e19 | [
"MIT"
] | null | null | null | 1-CLRS-Solution/C15-Dynamic-Programming/Problem/code/15.4.cpp | ftxj/2th-SummerHO | 422e04478d5904eb3bb75417793a4981ba108e19 | [
"MIT"
] | 1 | 2018-03-29T12:00:15.000Z | 2018-03-29T12:00:15.000Z | #include <iostream>
#include <climits>
#include <cmath>
using namespace std;
int main(){
const int N = 7;
int dp[N];
int M = 30;
int cost[N][N];
int G[N];
for(int i = 0; i < N; ++i){
cin >> G[i];
}
int temp;
for(int i = 0; i < N; ++i){
for(int j = i; j < N; ++j){
if(i == j)
cost[i][j] = G[j];
else
cost[i][j] = cost[i][j - 1] + G[j] + 1;
}
}
int last;
for(int i = 0; i < N; ++i){
dp[i] = INT_MAX;
for(int j = 0; j <= i; ++j){
if(cost[j][i] > M){
temp = INT_MAX;
continue;
}
else if(i == N - 1){
temp = j == 0? 0 : dp[j - 1];
}
else if(j == 0){
temp = M - cost[j][i];
}
else{
temp = dp[j - 1] + M - cost[j][i];
}
if(temp < dp[i]){
dp[i] = temp;
last = j;
}
}
}
cout << dp[N - 1] << endl;
return 0;
} | 22.895833 | 55 | 0.312102 | ftxj |
51832e86e703cbf77a4dd68e0f0cac291664c7e7 | 743 | cc | C++ | third_party/blink/renderer/core/events/visual_viewport_scroll_event.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | third_party/blink/renderer/core/events/visual_viewport_scroll_event.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | third_party/blink/renderer/core/events/visual_viewport_scroll_event.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/events/visual_viewport_scroll_event.h"
#include "third_party/blink/renderer/core/frame/use_counter.h"
namespace blink {
VisualViewportScrollEvent::~VisualViewportScrollEvent() = default;
VisualViewportScrollEvent::VisualViewportScrollEvent()
: Event(EventTypeNames::scroll, Bubbles::kNo, Cancelable::kNo) {}
void VisualViewportScrollEvent::DoneDispatchingEventAtCurrentTarget() {
UseCounter::Count(currentTarget()->GetExecutionContext(),
WebFeature::kVisualViewportScrollFired);
}
} // namespace blink
| 33.772727 | 80 | 0.776581 | zipated |
51835c5df2de4879756205d30600687a501c29c4 | 3,573 | cpp | C++ | src/couchdb/couchview.cpp | jpnurmi/qtcouchdb | 44fdb67d04b86ea715f8ede66b510488d5232493 | [
"MIT"
] | 2 | 2020-12-12T03:15:03.000Z | 2022-01-03T11:11:58.000Z | src/couchdb/couchview.cpp | CELLINKAB/qtcouchdb | 44fdb67d04b86ea715f8ede66b510488d5232493 | [
"MIT"
] | 3 | 2020-11-28T10:53:10.000Z | 2020-11-28T14:00:29.000Z | src/couchdb/couchview.cpp | jpnurmi/qtcouchdb | 44fdb67d04b86ea715f8ede66b510488d5232493 | [
"MIT"
] | 2 | 2021-02-13T14:38:58.000Z | 2022-02-21T15:42:26.000Z | #include "couchview.h"
#include "couchclient.h"
#include "couchdatabase.h"
#include "couchdesigndocument.h"
#include "couchrequest.h"
#include "couchresponse.h"
class CouchViewPrivate
{
Q_DECLARE_PUBLIC(CouchView)
public:
CouchResponse *response(CouchResponse *response)
{
Q_Q(CouchView);
QObject::connect(response, &CouchResponse::errorOccurred, [=](const CouchError &error) {
emit q->errorOccurred(error);
});
return response;
}
CouchView *q_ptr = nullptr;
QString name;
CouchDesignDocument *designDocument = nullptr;
};
CouchView::CouchView(QObject *parent)
: CouchView(QString(), nullptr, parent)
{
}
CouchView::CouchView(const QString &name, CouchDesignDocument *designDocument, QObject *parent)
: QObject(parent),
d_ptr(new CouchViewPrivate)
{
Q_D(CouchView);
d->q_ptr = this;
d->name = name;
setDesignDocument(designDocument);
}
CouchView::~CouchView()
{
}
QUrl CouchView::url() const
{
Q_D(const CouchView);
if (!d->designDocument || d->name.isEmpty())
return QUrl();
return Couch::viewUrl(d->designDocument->url(), d->name);
}
QString CouchView::name() const
{
Q_D(const CouchView);
return d->name;
}
void CouchView::setName(const QString &name)
{
Q_D(CouchView);
if (d->name == name)
return;
d->name = name;
emit urlChanged(url());
emit nameChanged(name);
}
CouchClient *CouchView::client() const
{
Q_D(const CouchView);
if (!d->designDocument)
return nullptr;
return d->designDocument->client();
}
CouchDatabase *CouchView::database() const
{
Q_D(const CouchView);
if (!d->designDocument)
return nullptr;
return d->designDocument->database();
}
CouchDesignDocument *CouchView::designDocument() const
{
Q_D(const CouchView);
return d->designDocument;
}
void CouchView::setDesignDocument(CouchDesignDocument *designDocument)
{
Q_D(CouchView);
if (d->designDocument == designDocument)
return;
QUrl oldUrl = url();
CouchClient *oldClient = client();
CouchDatabase *oldDatabase = database();
if (d->designDocument)
d->designDocument->disconnect(this);
if (designDocument) {
connect(designDocument, &CouchDesignDocument::urlChanged, this, &CouchView::urlChanged);
connect(designDocument, &CouchDesignDocument::clientChanged, this, &CouchView::clientChanged);
connect(designDocument, &CouchDesignDocument::databaseChanged, this, &CouchView::databaseChanged);
}
d->designDocument = designDocument;
if (oldUrl != url())
emit urlChanged(url());
if (oldClient != client())
emit clientChanged(client());
if (oldDatabase != database())
emit databaseChanged(database());
emit designDocumentChanged(designDocument);
}
CouchResponse *CouchView::listRowIds()
{
return queryRows(CouchQuery());
}
CouchResponse *CouchView::listFullRows()
{
return queryRows(CouchQuery::full());
}
CouchResponse *CouchView::queryRows(const CouchQuery &query)
{
Q_D(CouchView);
CouchClient *client = d->designDocument ? d->designDocument->client() : nullptr;
if (!client)
return nullptr;
CouchRequest request = Couch::queryRows(url(), query);
CouchResponse *response = client->sendRequest(request);
if (!response)
return nullptr;
connect(response, &CouchResponse::received, [=](const QByteArray &data) {
emit rowsListed(Couch::toDocumentList(data));
});
return d->response(response);
}
| 23.662252 | 106 | 0.671425 | jpnurmi |
3d601d61551912a675c10715d1120966d560daf2 | 506 | cpp | C++ | Falling-into-deeps/src/graphics/VertexBuffer.cpp | RustyGuard/Falling_into_deeps | 81021f7ebeba65a6c367850462636309365e7e4a | [
"Apache-2.0"
] | null | null | null | Falling-into-deeps/src/graphics/VertexBuffer.cpp | RustyGuard/Falling_into_deeps | 81021f7ebeba65a6c367850462636309365e7e4a | [
"Apache-2.0"
] | null | null | null | Falling-into-deeps/src/graphics/VertexBuffer.cpp | RustyGuard/Falling_into_deeps | 81021f7ebeba65a6c367850462636309365e7e4a | [
"Apache-2.0"
] | null | null | null | #include "gearpch.h"
#include "VertexBuffer.h"
#include <glad/glad.h>
VertexBuffer::VertexBuffer(const void* data, unsigned int size) {
glGenBuffers(1, &m_RendererId);
glBindBuffer(GL_ARRAY_BUFFER, m_RendererId);
glBufferData(GL_ARRAY_BUFFER, size, data, GL_STATIC_DRAW);
}
VertexBuffer::~VertexBuffer() {
glDeleteBuffers(1, &m_RendererId);
}
void VertexBuffer::bind() const {
glBindBuffer(GL_ARRAY_BUFFER, m_RendererId);
}
void VertexBuffer::unbind() const {
glBindBuffer(GL_ARRAY_BUFFER, 0);
} | 23 | 65 | 0.764822 | RustyGuard |
3d6281a5138f78af7693962c66fcbb42f37071d5 | 297 | cpp | C++ | hello1.cpp | ash1247/CodeBlocksLinux | 30c974e7abd580b2c524bea6de9da94033e8cd9e | [
"MIT"
] | null | null | null | hello1.cpp | ash1247/CodeBlocksLinux | 30c974e7abd580b2c524bea6de9da94033e8cd9e | [
"MIT"
] | null | null | null | hello1.cpp | ash1247/CodeBlocksLinux | 30c974e7abd580b2c524bea6de9da94033e8cd9e | [
"MIT"
] | null | null | null | /*Copyright of Ashikul Hosen */
#include <iostream>
#include <vector>
int main(int argc, char *argv[]) {
std::cout << "abada\n";
std::vector<int> vi;
vi.push_back(10);
vi.push_back();
for (auto it = vi.begin(); it != vi.end(); ++it) {
std::cout << *it << "\n";
}
return 0;
}
| 17.470588 | 52 | 0.558923 | ash1247 |
3d63920e8ebec4d927f266bca5edd25f5959259d | 4,517 | cpp | C++ | Engine/Source/Developer/DirectoryWatcher/Private/Windows/DirectoryWatcherWindows.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | Engine/Source/Developer/DirectoryWatcher/Private/Windows/DirectoryWatcherWindows.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | 2 | 2015-06-21T17:38:11.000Z | 2015-06-22T20:54:42.000Z | Engine/Source/Developer/DirectoryWatcher/Private/Windows/DirectoryWatcherWindows.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#include "DirectoryWatcherPrivatePCH.h"
FDirectoryWatcherWindows::FDirectoryWatcherWindows()
{
NumRequests = 0;
}
FDirectoryWatcherWindows::~FDirectoryWatcherWindows()
{
if ( RequestMap.Num() != 0 )
{
// Delete any remaining requests here. These requests are likely from modules which are still loaded at the time that this module unloads.
for (TMap<FString, FDirectoryWatchRequestWindows*>::TConstIterator RequestIt(RequestMap); RequestIt; ++RequestIt)
{
if ( ensure(RequestIt.Value()) )
{
// make sure we end the watch request, as we may get a callback if a request is in flight
RequestIt.Value()->EndWatchRequest();
delete RequestIt.Value();
NumRequests--;
}
}
RequestMap.Empty();
}
if ( RequestsPendingDelete.Num() != 0 )
{
for ( int32 RequestIdx = 0; RequestIdx < RequestsPendingDelete.Num(); ++RequestIdx )
{
delete RequestsPendingDelete[RequestIdx];
NumRequests--;
}
}
// Make sure every request that was created is destroyed
ensure(NumRequests == 0);
}
bool FDirectoryWatcherWindows::RegisterDirectoryChangedCallback_Handle( const FString& Directory, const FDirectoryChanged& InDelegate, FDelegateHandle& Handle, uint32 Flags )
{
FDirectoryWatchRequestWindows** RequestPtr = RequestMap.Find(Directory);
FDirectoryWatchRequestWindows* Request = NULL;
if ( RequestPtr )
{
// There should be no NULL entries in the map
check (*RequestPtr);
Request = *RequestPtr;
}
else
{
Request = new FDirectoryWatchRequestWindows(Flags);
NumRequests++;
// Begin reading directory changes
if ( !Request->Init(Directory) )
{
uint32 Error = GetLastError();
UE_LOG(LogDirectoryWatcher, Warning, TEXT("Failed to begin reading directory changes for %s. Error: %d"), *Directory, Error);
delete Request;
NumRequests--;
return false;
}
RequestMap.Add(Directory, Request);
}
Handle = Request->AddDelegate(InDelegate);
return true;
}
bool FDirectoryWatcherWindows::UnregisterDirectoryChangedCallback_Handle( const FString& Directory, FDelegateHandle InHandle )
{
FDirectoryWatchRequestWindows** RequestPtr = RequestMap.Find(Directory);
if ( RequestPtr )
{
// There should be no NULL entries in the map
check (*RequestPtr);
FDirectoryWatchRequestWindows* Request = *RequestPtr;
if ( Request->RemoveDelegate(InHandle) )
{
if ( !Request->HasDelegates() )
{
// Remove from the active map and add to the pending delete list
RequestMap.Remove(Directory);
RequestsPendingDelete.AddUnique(Request);
// Signal to end the watch which will mark this request for deletion
Request->EndWatchRequest();
}
return true;
}
}
return false;
}
void FDirectoryWatcherWindows::Tick( float DeltaSeconds )
{
TArray<HANDLE> DirectoryHandles;
TMap<FString, FDirectoryWatchRequestWindows*> InvalidRequestsToDelete;
// Find all handles to listen to and invalid requests to delete
for (TMap<FString, FDirectoryWatchRequestWindows*>::TConstIterator RequestIt(RequestMap); RequestIt; ++RequestIt)
{
if ( RequestIt.Value()->IsPendingDelete() )
{
InvalidRequestsToDelete.Add(RequestIt.Key(), RequestIt.Value());
}
else
{
DirectoryHandles.Add(RequestIt.Value()->GetDirectoryHandle());
}
}
// Remove all invalid requests from the request map and add them to the pending delete list so they will be deleted below
for (TMap<FString, FDirectoryWatchRequestWindows*>::TConstIterator RequestIt(InvalidRequestsToDelete); RequestIt; ++RequestIt)
{
RequestMap.Remove(RequestIt.Key());
RequestsPendingDelete.AddUnique(RequestIt.Value());
}
// Trigger any file changed delegates that are queued up
if ( DirectoryHandles.Num() > 0 )
{
MsgWaitForMultipleObjectsEx(DirectoryHandles.Num(), DirectoryHandles.GetData(), 0, QS_ALLEVENTS, MWMO_ALERTABLE);
}
// Delete any stale or invalid requests
for ( int32 RequestIdx = RequestsPendingDelete.Num() - 1; RequestIdx >= 0; --RequestIdx )
{
FDirectoryWatchRequestWindows* Request = RequestsPendingDelete[RequestIdx];
if ( Request->IsPendingDelete() )
{
// This request is safe to delete. Delete and remove it from the list
delete Request;
NumRequests--;
RequestsPendingDelete.RemoveAt(RequestIdx);
}
}
// Finally, trigger any file change notification delegates
for (TMap<FString, FDirectoryWatchRequestWindows*>::TConstIterator RequestIt(RequestMap); RequestIt; ++RequestIt)
{
RequestIt.Value()->ProcessPendingNotifications();
}
}
| 28.408805 | 174 | 0.737658 | PopCap |
3d64d90533ab2e164f2812e961ffb9692921214e | 38,971 | cpp | C++ | enduser/speech/sapi/sapi/a_recoei.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | enduser/speech/sapi/sapi/a_recoei.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | enduser/speech/sapi/sapi/a_recoei.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*******************************************************************************
* a_recoei.cpp *
*-------------*
* Description:
* This module is the main implementation file for the CSpeechRecoEventInterests
* automation methods.
*-------------------------------------------------------------------------------
* Created By: Leonro Date: 11/20/00
* Copyright (C) 2000 Microsoft Corporation
* All Rights Reserved
*
*******************************************************************************/
//--- Additional includes
#include "stdafx.h"
#include "a_recoei.h"
#ifdef SAPI_AUTOMATION
/*****************************************************************************
* CSpeechRecoEventInterests::FinalRelease *
*------------------------*
* Description:
* destructor
********************************************************************* Leonro ***/
void CSpeechRecoEventInterests::FinalRelease()
{
SPDBG_FUNC( "CSpeechRecoEventInterests::FinalRelease" );
if( m_pCRecoCtxt )
{
m_pCRecoCtxt->Release();
m_pCRecoCtxt = NULL;
}
} /* CSpeechRecoEventInterests::FinalRelease */
//
//=== ICSpeechRecoEventInterests interface ==================================================
//
/*****************************************************************************
* CSpeechRecoEventInterests::put_StreamEnd *
*----------------------------------*
*
* This method enables and disables the interest in the SPEI_END_SR_STREAM event on
* the Reco Context.
*
********************************************************************* Leonro ***/
STDMETHODIMP CSpeechRecoEventInterests::put_StreamEnd( VARIANT_BOOL Enabled )
{
SPDBG_FUNC( "CSpeechRecoEventInterests::put_StreamEnd" );
ULONGLONG ullInterest = 0;
HRESULT hr = S_OK;
hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL );
ULONGLONG test = SPFEI_ALL_SR_EVENTS;
if( SUCCEEDED( hr ) )
{
if( Enabled )
{
ullInterest |= (1ui64 << SPEI_END_SR_STREAM);
}
else
{
ullInterest &= ~(1ui64 << SPEI_END_SR_STREAM);
}
hr = m_pCRecoCtxt->SetInterest( ullInterest, ullInterest );
}
return hr;
} /* CSpeechRecoEventInterests::put_StreamEnd */
/*****************************************************************************
* CSpeechRecoEventInterests::get_StreamEnd *
*----------------------------------*
*
* This method determines whether or not the SPEI_END_SR_STREAM interest is
* enabled on the Reco Context object.
*
********************************************************************* Leonro ***/
STDMETHODIMP CSpeechRecoEventInterests::get_StreamEnd( VARIANT_BOOL* Enabled )
{
SPDBG_FUNC( "CSpeechRecoEventInterests::get_StreamEnd" );
ULONGLONG ullInterest = 0;
HRESULT hr = S_OK;
if( SP_IS_BAD_WRITE_PTR( Enabled ) )
{
hr = E_POINTER;
}
else
{
hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL );
if( SUCCEEDED( hr ) )
{
if( ullInterest & (1ui64 << SPEI_END_SR_STREAM) )
{
*Enabled = VARIANT_TRUE;
}
else
{
*Enabled = VARIANT_FALSE;
}
}
}
return hr;
} /* CSpeechRecoEventInterests::get_StreamEnd */
/*****************************************************************************
* CSpeechRecoEventInterests::put_SoundStart *
*----------------------------------*
*
* This method enables and disables the interest in the SPEI_SOUND_START event on
* the Reco Context.
*
********************************************************************* Leonro ***/
STDMETHODIMP CSpeechRecoEventInterests::put_SoundStart( VARIANT_BOOL Enabled )
{
SPDBG_FUNC( "CSpeechRecoEventInterests::put_SoundStart" );
ULONGLONG ullInterest = 0;
HRESULT hr = S_OK;
hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL );
if( SUCCEEDED( hr ) )
{
if( Enabled )
{
ullInterest |= (1ui64 << SPEI_SOUND_START);
}
else
{
ullInterest &= ~(1ui64 << SPEI_SOUND_START);
}
hr = m_pCRecoCtxt->SetInterest( ullInterest, ullInterest );
}
return hr;
} /* CSpeechRecoEventInterests::put_SoundStart */
/*****************************************************************************
* CSpeechRecoEventInterests::get_SoundStart *
*----------------------------------*
*
* This method determines whether or not the SPEI_SOUND_START interest is
* enabled on the Reco Context object.
*
********************************************************************* Leonro ***/
STDMETHODIMP CSpeechRecoEventInterests::get_SoundStart( VARIANT_BOOL* Enabled )
{
SPDBG_FUNC( "CSpeechRecoEventInterests::get_SoundStart" );
ULONGLONG ullInterest = 0;
HRESULT hr = S_OK;
if( SP_IS_BAD_WRITE_PTR( Enabled ) )
{
hr = E_POINTER;
}
else
{
hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL );
if( SUCCEEDED( hr ) )
{
if( ullInterest & (1ui64 << SPEI_SOUND_START) )
{
*Enabled = VARIANT_TRUE;
}
else
{
*Enabled = VARIANT_FALSE;
}
}
}
return hr;
} /* CSpeechRecoEventInterests::get_SoundStart */
/*****************************************************************************
* CSpeechRecoEventInterests::put_SoundEnd *
*----------------------------------*
*
* This method enables and disables the interest in the SPEI_SOUND_END event on
* the Reco Context.
*
********************************************************************* Leonro ***/
STDMETHODIMP CSpeechRecoEventInterests::put_SoundEnd( VARIANT_BOOL Enabled )
{
SPDBG_FUNC( "CSpeechRecoEventInterests::put_SoundEnd" );
ULONGLONG ullInterest = 0;
HRESULT hr = S_OK;
hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL );
if( SUCCEEDED( hr ) )
{
if( Enabled )
{
ullInterest |= (1ui64 << SPEI_SOUND_END);
}
else
{
ullInterest &= ~(1ui64 << SPEI_SOUND_END);
}
hr = m_pCRecoCtxt->SetInterest( ullInterest, ullInterest );
}
return hr;
} /* CSpeechRecoEventInterests::put_SoundEnd */
/*****************************************************************************
* CSpeechRecoEventInterests::get_SoundEnd *
*----------------------------------*
*
* This method determines whether or not the SPEI_SOUND_END interest is
* enabled on the Reco Context object.
*
********************************************************************* Leonro ***/
STDMETHODIMP CSpeechRecoEventInterests::get_SoundEnd( VARIANT_BOOL* Enabled )
{
SPDBG_FUNC( "CSpeechRecoEventInterests::get_SoundEnd" );
ULONGLONG ullInterest = 0;
HRESULT hr = S_OK;
if( SP_IS_BAD_WRITE_PTR( Enabled ) )
{
hr = E_POINTER;
}
else
{
hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL );
if( SUCCEEDED( hr ) )
{
if( ullInterest & (1ui64 << SPEI_SOUND_END) )
{
*Enabled = VARIANT_TRUE;
}
else
{
*Enabled = VARIANT_FALSE;
}
}
}
return hr;
} /* CSpeechRecoEventInterests::get_SoundEnd */
/*****************************************************************************
* CSpeechRecoEventInterests::put_PhraseStart *
*----------------------------------*
*
* This method enables and disables the interest in the SPEI_PHRASE_START event on
* the Reco Context.
*
********************************************************************* Leonro ***/
STDMETHODIMP CSpeechRecoEventInterests::put_PhraseStart( VARIANT_BOOL Enabled )
{
SPDBG_FUNC( "CSpeechRecoEventInterests::put_PhraseStart" );
ULONGLONG ullInterest = 0;
HRESULT hr = S_OK;
hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL );
if( SUCCEEDED( hr ) )
{
if( Enabled )
{
ullInterest |= (1ui64 << SPEI_PHRASE_START);
}
else
{
ullInterest &= ~(1ui64 << SPEI_PHRASE_START);
}
hr = m_pCRecoCtxt->SetInterest( ullInterest, ullInterest );
}
return hr;
} /* CSpeechRecoEventInterests::put_PhraseStart */
/*****************************************************************************
* CSpeechRecoEventInterests::get_PhraseStart *
*----------------------------------*
*
* This method determines whether or not the SPEI_PHRASE_START interest is
* enabled on the Reco Context object.
*
********************************************************************* Leonro ***/
STDMETHODIMP CSpeechRecoEventInterests::get_PhraseStart( VARIANT_BOOL* Enabled )
{
SPDBG_FUNC( "CSpeechRecoEventInterests::get_PhraseStart" );
ULONGLONG ullInterest = 0;
HRESULT hr = S_OK;
if( SP_IS_BAD_WRITE_PTR( Enabled ) )
{
hr = E_POINTER;
}
else
{
hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL );
if( SUCCEEDED( hr ) )
{
if( ullInterest & (1ui64 << SPEI_PHRASE_START) )
{
*Enabled = VARIANT_TRUE;
}
else
{
*Enabled = VARIANT_FALSE;
}
}
}
return hr;
} /* CSpeechRecoEventInterests::get_PhraseStart */
/*****************************************************************************
* CSpeechRecoEventInterests::put_Recognition *
*----------------------------------*
*
* This method enables and disables the interest in the SPEI_RECOGNITION event on
* the Reco Context.
*
********************************************************************* Leonro ***/
STDMETHODIMP CSpeechRecoEventInterests::put_Recognition( VARIANT_BOOL Enabled )
{
SPDBG_FUNC( "CSpeechRecoEventInterests::put_Recognition" );
ULONGLONG ullInterest = 0;
HRESULT hr = S_OK;
hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL );
if( SUCCEEDED( hr ) )
{
if( Enabled )
{
ullInterest |= (1ui64 << SPEI_RECOGNITION);
}
else
{
ullInterest &= ~(1ui64 << SPEI_RECOGNITION);
}
hr = m_pCRecoCtxt->SetInterest( ullInterest, ullInterest );
}
return hr;
} /* CSpeechRecoEventInterests::put_Recognition */
/*****************************************************************************
* CSpeechRecoEventInterests::get_Recognition *
*----------------------------------*
*
* This method determines whether or not the SPEI_RECOGNITION interest is
* enabled on the Reco Context object.
*
********************************************************************* Leonro ***/
STDMETHODIMP CSpeechRecoEventInterests::get_Recognition( VARIANT_BOOL* Enabled )
{
SPDBG_FUNC( "CSpeechRecoEventInterests::get_Recognition" );
ULONGLONG ullInterest = 0;
HRESULT hr = S_OK;
if( SP_IS_BAD_WRITE_PTR( Enabled ) )
{
hr = E_POINTER;
}
else
{
hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL );
if( SUCCEEDED( hr ) )
{
if( ullInterest & (1ui64 << SPEI_RECOGNITION) )
{
*Enabled = VARIANT_TRUE;
}
else
{
*Enabled = VARIANT_FALSE;
}
}
}
return hr;
} /* CSpeechRecoEventInterests::get_Recognition */
/*****************************************************************************
* CSpeechRecoEventInterests::put_Hypothesis *
*----------------------------------*
*
* This method enables and disables the interest in the SPEI_HYPOTHESIS event on
* the Reco Context.
*
********************************************************************* Leonro ***/
STDMETHODIMP CSpeechRecoEventInterests::put_Hypothesis( VARIANT_BOOL Enabled )
{
SPDBG_FUNC( "CSpeechRecoEventInterests::put_Hypothesis" );
ULONGLONG ullInterest = 0;
HRESULT hr = S_OK;
hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL );
if( SUCCEEDED( hr ) )
{
if( Enabled )
{
ullInterest |= (1ui64 << SPEI_HYPOTHESIS);
}
else
{
ullInterest &= ~(1ui64 << SPEI_HYPOTHESIS);
}
hr = m_pCRecoCtxt->SetInterest( ullInterest, ullInterest );
}
return hr;
} /* CSpeechRecoEventInterests::put_Hypothesis */
/*****************************************************************************
* CSpeechRecoEventInterests::get_Hypothesis *
*----------------------------------*
*
* This method determines whether or not the SPEI_HYPOTHESIS interest is
* enabled on the Reco Context object.
*
********************************************************************* Leonro ***/
STDMETHODIMP CSpeechRecoEventInterests::get_Hypothesis( VARIANT_BOOL* Enabled )
{
SPDBG_FUNC( "CSpeechRecoEventInterests::get_Hypothesis" );
ULONGLONG ullInterest = 0;
HRESULT hr = S_OK;
if( SP_IS_BAD_WRITE_PTR( Enabled ) )
{
hr = E_POINTER;
}
else
{
hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL );
if( SUCCEEDED( hr ) )
{
if( ullInterest & (1ui64 << SPEI_HYPOTHESIS) )
{
*Enabled = VARIANT_TRUE;
}
else
{
*Enabled = VARIANT_FALSE;
}
}
}
return hr;
} /* CSpeechRecoEventInterests::get_Hypothesis */
/*****************************************************************************
* CSpeechRecoEventInterests::put_Bookmark *
*----------------------------------*
*
* This method enables and disables the interest in the SPEI_SR_BOOKMARK event on
* the Reco Context.
*
********************************************************************* Leonro ***/
STDMETHODIMP CSpeechRecoEventInterests::put_Bookmark( VARIANT_BOOL Enabled )
{
SPDBG_FUNC( "CSpeechRecoEventInterests::put_Bookmark" );
ULONGLONG ullInterest = 0;
HRESULT hr = S_OK;
hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL );
if( SUCCEEDED( hr ) )
{
if( Enabled )
{
ullInterest |= (1ui64 << SPEI_SR_BOOKMARK);
}
else
{
ullInterest &= ~(1ui64 << SPEI_SR_BOOKMARK);
}
hr = m_pCRecoCtxt->SetInterest( ullInterest, ullInterest );
}
return hr;
} /* CSpeechRecoEventInterests::put_Bookmark */
/*****************************************************************************
* CSpeechRecoEventInterests::get_Bookmark *
*----------------------------------*
*
* This method determines whether or not the SPEI_SR_BOOKMARK interest is
* enabled on the Reco Context object.
*
********************************************************************* Leonro ***/
STDMETHODIMP CSpeechRecoEventInterests::get_Bookmark( VARIANT_BOOL* Enabled )
{
SPDBG_FUNC( "CSpeechRecoEventInterests::get_Bookmark" );
ULONGLONG ullInterest = 0;
HRESULT hr = S_OK;
if( SP_IS_BAD_WRITE_PTR( Enabled ) )
{
hr = E_POINTER;
}
else
{
hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL );
if( SUCCEEDED( hr ) )
{
if( ullInterest & (1ui64 << SPEI_SR_BOOKMARK) )
{
*Enabled = VARIANT_TRUE;
}
else
{
*Enabled = VARIANT_FALSE;
}
}
}
return hr;
} /* CSpeechRecoEventInterests::get_Bookmark */
/*****************************************************************************
* CSpeechRecoEventInterests::put_PropertyNumChange *
*----------------------------------*
*
* This method enables and disables the interest in the SPEI_PROPERTY_NUM_CHANGE event on
* the Reco Context.
*
********************************************************************* Leonro ***/
STDMETHODIMP CSpeechRecoEventInterests::put_PropertyNumChange( VARIANT_BOOL Enabled )
{
SPDBG_FUNC( "CSpeechRecoEventInterests::put_PropertyNumChange" );
ULONGLONG ullInterest = 0;
HRESULT hr = S_OK;
hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL );
if( SUCCEEDED( hr ) )
{
if( Enabled )
{
ullInterest |= (1ui64 << SPEI_PROPERTY_NUM_CHANGE);
}
else
{
ullInterest &= ~(1ui64 << SPEI_PROPERTY_NUM_CHANGE);
}
hr = m_pCRecoCtxt->SetInterest( ullInterest, ullInterest );
}
return hr;
} /* CSpeechRecoEventInterests::put_PropertyNumChange */
/*****************************************************************************
* CSpeechRecoEventInterests::get_PropertyNumChange *
*----------------------------------*
*
* This method determines whether or not the SPEI_PROPERTY_NUM_CHANGE interest is
* enabled on the Reco Context object.
*
********************************************************************* Leonro ***/
STDMETHODIMP CSpeechRecoEventInterests::get_PropertyNumChange( VARIANT_BOOL* Enabled )
{
SPDBG_FUNC( "CSpeechRecoEventInterests::get_PropertyNumChange" );
ULONGLONG ullInterest = 0;
HRESULT hr = S_OK;
if( SP_IS_BAD_WRITE_PTR( Enabled ) )
{
hr = E_POINTER;
}
else
{
hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL );
if( SUCCEEDED( hr ) )
{
if( ullInterest & (1ui64 << SPEI_PROPERTY_NUM_CHANGE) )
{
*Enabled = VARIANT_TRUE;
}
else
{
*Enabled = VARIANT_FALSE;
}
}
}
return hr;
} /* CSpeechRecoEventInterests::get_PropertyNumChange */
/*****************************************************************************
* CSpeechRecoEventInterests::put_PropertyStringChange *
*----------------------------------*
*
* This method enables and disables the interest in the SPEI_PROPERTY_STRING_CHANGE event on
* the Reco Context.
*
********************************************************************* Leonro ***/
STDMETHODIMP CSpeechRecoEventInterests::put_PropertyStringChange( VARIANT_BOOL Enabled )
{
SPDBG_FUNC( "CSpeechRecoEventInterests::put_PropertyStringChange" );
ULONGLONG ullInterest = 0;
HRESULT hr = S_OK;
hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL );
if( SUCCEEDED( hr ) )
{
if( Enabled )
{
ullInterest |= (1ui64 << SPEI_PROPERTY_STRING_CHANGE);
}
else
{
ullInterest &= ~(1ui64 << SPEI_PROPERTY_STRING_CHANGE);
}
hr = m_pCRecoCtxt->SetInterest( ullInterest, ullInterest );
}
return hr;
} /* CSpeechRecoEventInterests::put_PropertyStringChange */
/*****************************************************************************
* CSpeechRecoEventInterests::get_PropertyStringChange *
*----------------------------------*
*
* This method determines whether or not the SPEI_PROPERTY_STRING_CHANGE interest is
* enabled on the Reco Context object.
*
********************************************************************* Leonro ***/
STDMETHODIMP CSpeechRecoEventInterests::get_PropertyStringChange( VARIANT_BOOL* Enabled )
{
SPDBG_FUNC( "CSpeechRecoEventInterests::get_PropertyStringChange" );
ULONGLONG ullInterest = 0;
HRESULT hr = S_OK;
if( SP_IS_BAD_WRITE_PTR( Enabled ) )
{
hr = E_POINTER;
}
else
{
hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL );
if( SUCCEEDED( hr ) )
{
if( ullInterest & (1ui64 << SPEI_PROPERTY_STRING_CHANGE) )
{
*Enabled = VARIANT_TRUE;
}
else
{
*Enabled = VARIANT_FALSE;
}
}
}
return hr;
} /* CSpeechRecoEventInterests::get_PropertyStringChange */
/*****************************************************************************
* CSpeechRecoEventInterests::put_FalseRecognition *
*----------------------------------*
*
* This method enables and disables the interest in the SPEI_FALSE_RECOGNITION event on
* the Reco Context.
*
********************************************************************* Leonro ***/
STDMETHODIMP CSpeechRecoEventInterests::put_FalseRecognition( VARIANT_BOOL Enabled )
{
SPDBG_FUNC( "CSpeechRecoEventInterests::put_FalseRecognition" );
ULONGLONG ullInterest = 0;
HRESULT hr = S_OK;
hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL );
if( SUCCEEDED( hr ) )
{
if( Enabled )
{
ullInterest |= (1ui64 << SPEI_FALSE_RECOGNITION);
}
else
{
ullInterest &= ~(1ui64 << SPEI_FALSE_RECOGNITION);
}
hr = m_pCRecoCtxt->SetInterest( ullInterest, ullInterest );
}
return hr;
} /* CSpeechRecoEventInterests::put_FalseRecognition */
/*****************************************************************************
* CSpeechRecoEventInterests::get_FalseRecognition *
*----------------------------------*
*
* This method determines whether or not the SPEI_FALSE_RECOGNITION interest is
* enabled on the Reco Context object.
*
********************************************************************* Leonro ***/
STDMETHODIMP CSpeechRecoEventInterests::get_FalseRecognition( VARIANT_BOOL* Enabled )
{
SPDBG_FUNC( "CSpeechRecoEventInterests::get_FalseRecognition" );
ULONGLONG ullInterest = 0;
HRESULT hr = S_OK;
if( SP_IS_BAD_WRITE_PTR( Enabled ) )
{
hr = E_POINTER;
}
else
{
hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL );
if( SUCCEEDED( hr ) )
{
if( ullInterest & (1ui64 << SPEI_FALSE_RECOGNITION) )
{
*Enabled = VARIANT_TRUE;
}
else
{
*Enabled = VARIANT_FALSE;
}
}
}
return hr;
} /* CSpeechRecoEventInterests::get_FalseRecognition */
/*****************************************************************************
* CSpeechRecoEventInterests::put_Interference *
*----------------------------------*
*
* This method enables and disables the interest in the SPEI_INTERFERENCE event on
* the Reco Context.
*
********************************************************************* Leonro ***/
STDMETHODIMP CSpeechRecoEventInterests::put_Interference( VARIANT_BOOL Enabled )
{
SPDBG_FUNC( "CSpeechRecoEventInterests::put_Interference" );
ULONGLONG ullInterest = 0;
HRESULT hr = S_OK;
hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL );
if( SUCCEEDED( hr ) )
{
if( Enabled )
{
ullInterest |= (1ui64 << SPEI_INTERFERENCE);
}
else
{
ullInterest &= ~(1ui64 << SPEI_INTERFERENCE);
}
hr = m_pCRecoCtxt->SetInterest( ullInterest, ullInterest );
}
return hr;
} /* CSpeechRecoEventInterests::put_Interference */
/*****************************************************************************
* CSpeechRecoEventInterests::get_Interference *
*----------------------------------*
*
* This method determines whether or not the SPEI_INTERFERENCE interest is
* enabled on the Reco Context object.
*
********************************************************************* Leonro ***/
STDMETHODIMP CSpeechRecoEventInterests::get_Interference( VARIANT_BOOL* Enabled )
{
SPDBG_FUNC( "CSpeechRecoEventInterests::get_Interference" );
ULONGLONG ullInterest = 0;
HRESULT hr = S_OK;
if( SP_IS_BAD_WRITE_PTR( Enabled ) )
{
hr = E_POINTER;
}
else
{
hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL );
if( SUCCEEDED( hr ) )
{
if( ullInterest & (1ui64 << SPEI_INTERFERENCE) )
{
*Enabled = VARIANT_TRUE;
}
else
{
*Enabled = VARIANT_FALSE;
}
}
}
return hr;
} /* CSpeechRecoEventInterests::get_Interference */
/*****************************************************************************
* CSpeechRecoEventInterests::put_RequestUI *
*----------------------------------*
*
* This method enables and disables the interest in the SPEI_REQUEST_UI event on
* the Reco Context.
*
********************************************************************* Leonro ***/
STDMETHODIMP CSpeechRecoEventInterests::put_RequestUI( VARIANT_BOOL Enabled )
{
SPDBG_FUNC( "CSpeechRecoEventInterests::put_RequestUI" );
ULONGLONG ullInterest = 0;
HRESULT hr = S_OK;
hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL );
if( SUCCEEDED( hr ) )
{
if( Enabled )
{
ullInterest |= (1ui64 << SPEI_REQUEST_UI);
}
else
{
ullInterest &= ~(1ui64 << SPEI_REQUEST_UI);
}
hr = m_pCRecoCtxt->SetInterest( ullInterest, ullInterest );
}
return hr;
} /* CSpeechRecoEventInterests::put_RequestUI */
/*****************************************************************************
* CSpeechRecoEventInterests::get_RequestUI *
*----------------------------------*
*
* This method determines whether or not the SPEI_REQUEST_UI interest is
* enabled on the Reco Context object.
*
********************************************************************* Leonro ***/
STDMETHODIMP CSpeechRecoEventInterests::get_RequestUI( VARIANT_BOOL* Enabled )
{
SPDBG_FUNC( "CSpeechRecoEventInterests::get_RequestUI" );
ULONGLONG ullInterest = 0;
HRESULT hr = S_OK;
if( SP_IS_BAD_WRITE_PTR( Enabled ) )
{
hr = E_POINTER;
}
else
{
hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL );
if( SUCCEEDED( hr ) )
{
if( ullInterest & (1ui64 << SPEI_REQUEST_UI) )
{
*Enabled = VARIANT_TRUE;
}
else
{
*Enabled = VARIANT_FALSE;
}
}
}
return hr;
} /* CSpeechRecoEventInterests::get_RequestUI */
/*****************************************************************************
* CSpeechRecoEventInterests::put_StateChange *
*----------------------------------*
*
* This method enables and disables the interest in the SPEI_RECO_STATE_CHANGE event on
* the Reco Context.
*
********************************************************************* Leonro ***/
STDMETHODIMP CSpeechRecoEventInterests::put_StateChange( VARIANT_BOOL Enabled )
{
SPDBG_FUNC( "CSpeechRecoEventInterests::put_StateChange" );
ULONGLONG ullInterest = 0;
HRESULT hr = S_OK;
hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL );
if( SUCCEEDED( hr ) )
{
if( Enabled )
{
ullInterest |= (1ui64 << SPEI_RECO_STATE_CHANGE);
}
else
{
ullInterest &= ~(1ui64 << SPEI_RECO_STATE_CHANGE);
}
hr = m_pCRecoCtxt->SetInterest( ullInterest, ullInterest );
}
return hr;
} /* CSpeechRecoEventInterests::put_StateChange */
/*****************************************************************************
* CSpeechRecoEventInterests::get_StateChange *
*----------------------------------*
*
* This method determines whether or not the SPEI_RECO_STATE_CHANGE interest is
* enabled on the Reco Context object.
*
********************************************************************* Leonro ***/
STDMETHODIMP CSpeechRecoEventInterests::get_StateChange( VARIANT_BOOL* Enabled )
{
SPDBG_FUNC( "CSpeechRecoEventInterests::get_StateChange" );
ULONGLONG ullInterest = 0;
HRESULT hr = S_OK;
if( SP_IS_BAD_WRITE_PTR( Enabled ) )
{
hr = E_POINTER;
}
else
{
hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL );
if( SUCCEEDED( hr ) )
{
if( ullInterest & (1ui64 << SPEI_RECO_STATE_CHANGE) )
{
*Enabled = VARIANT_TRUE;
}
else
{
*Enabled = VARIANT_FALSE;
}
}
}
return hr;
} /* CSpeechRecoEventInterests::get_StateChange */
/*****************************************************************************
* CSpeechRecoEventInterests::put_Adaptation *
*----------------------------------*
*
* This method enables and disables the interest in the SPEI_ADAPTATION event on
* the Reco Context.
*
********************************************************************* Leonro ***/
STDMETHODIMP CSpeechRecoEventInterests::put_Adaptation( VARIANT_BOOL Enabled )
{
SPDBG_FUNC( "CSpeechRecoEventInterests::put_Adaptation" );
ULONGLONG ullInterest = 0;
HRESULT hr = S_OK;
hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL );
if( SUCCEEDED( hr ) )
{
if( Enabled )
{
ullInterest |= (1ui64 << SPEI_ADAPTATION);
}
else
{
ullInterest &= ~(1ui64 << SPEI_ADAPTATION);
}
hr = m_pCRecoCtxt->SetInterest( ullInterest, ullInterest );
}
return hr;
} /* CSpeechRecoEventInterests::put_Adaptation */
/*****************************************************************************
* CSpeechRecoEventInterests::get_Adaptation *
*----------------------------------*
*
* This method determines whether or not the SPEI_ADAPTATION interest is
* enabled on the Reco Context object.
*
********************************************************************* Leonro ***/
STDMETHODIMP CSpeechRecoEventInterests::get_Adaptation( VARIANT_BOOL* Enabled )
{
SPDBG_FUNC( "CSpeechRecoEventInterests::get_Adaptation" );
ULONGLONG ullInterest = 0;
HRESULT hr = S_OK;
if( SP_IS_BAD_WRITE_PTR( Enabled ) )
{
hr = E_POINTER;
}
else
{
hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL );
if( SUCCEEDED( hr ) )
{
if( ullInterest & (1ui64 << SPEI_ADAPTATION) )
{
*Enabled = VARIANT_TRUE;
}
else
{
*Enabled = VARIANT_FALSE;
}
}
}
return hr;
} /* CSpeechRecoEventInterests::get_Adaptation */
/*****************************************************************************
* CSpeechRecoEventInterests::put_StreamStart *
*----------------------------------*
*
* This method enables and disables the interest in the SPEI_START_SR_STREAM event on
* the Reco Context.
*
********************************************************************* Leonro ***/
STDMETHODIMP CSpeechRecoEventInterests::put_StreamStart( VARIANT_BOOL Enabled )
{
SPDBG_FUNC( "CSpeechRecoEventInterests::put_StreamStart" );
ULONGLONG ullInterest = 0;
HRESULT hr = S_OK;
hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL );
if( SUCCEEDED( hr ) )
{
if( Enabled )
{
ullInterest |= (1ui64 << SPEI_START_SR_STREAM);
}
else
{
ullInterest &= ~(1ui64 << SPEI_START_SR_STREAM);
}
hr = m_pCRecoCtxt->SetInterest( ullInterest, ullInterest );
}
return hr;
} /* CSpeechRecoEventInterests::put_StreamStart */
/*****************************************************************************
* CSpeechRecoEventInterests::get_StreamStart *
*----------------------------------*
*
* This method determines whether or not the SPEI_START_SR_STREAM interest is
* enabled on the Reco Context object.
*
********************************************************************* Leonro ***/
STDMETHODIMP CSpeechRecoEventInterests::get_StreamStart( VARIANT_BOOL* Enabled )
{
SPDBG_FUNC( "CSpeechRecoEventInterests::get_StreamStart" );
ULONGLONG ullInterest = 0;
HRESULT hr = S_OK;
if( SP_IS_BAD_WRITE_PTR( Enabled ) )
{
hr = E_POINTER;
}
else
{
hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL );
if( SUCCEEDED( hr ) )
{
if( ullInterest & (1ui64 << SPEI_START_SR_STREAM) )
{
*Enabled = VARIANT_TRUE;
}
else
{
*Enabled = VARIANT_FALSE;
}
}
}
return hr;
} /* CSpeechRecoEventInterests::get_StreamStart */
/*****************************************************************************
* CSpeechRecoEventInterests::put_OtherContext *
*----------------------------------*
*
* This method enables and disables the interest in the SPEI_RECO_OTHER_CONTEXT event on
* the Reco Context.
*
********************************************************************* Leonro ***/
STDMETHODIMP CSpeechRecoEventInterests::put_OtherContext( VARIANT_BOOL Enabled )
{
SPDBG_FUNC( "CSpeechRecoEventInterests::put_OtherContext" );
ULONGLONG ullInterest = 0;
HRESULT hr = S_OK;
hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL );
if( SUCCEEDED( hr ) )
{
if( Enabled )
{
ullInterest |= (1ui64 << SPEI_RECO_OTHER_CONTEXT);
}
else
{
ullInterest &= ~(1ui64 << SPEI_RECO_OTHER_CONTEXT);
}
hr = m_pCRecoCtxt->SetInterest( ullInterest, ullInterest );
}
return hr;
} /* CSpeechRecoEventInterests::put_OtherContext */
/*****************************************************************************
* CSpeechRecoEventInterests::get_OtherContext *
*----------------------------------*
*
* This method determines whether or not the SPEI_RECO_OTHER_CONTEXT interest is
* enabled on the Reco Context object.
*
********************************************************************* Leonro ***/
STDMETHODIMP CSpeechRecoEventInterests::get_OtherContext( VARIANT_BOOL* Enabled )
{
SPDBG_FUNC( "CSpeechRecoEventInterests::get_OtherContext" );
ULONGLONG ullInterest = 0;
HRESULT hr = S_OK;
if( SP_IS_BAD_WRITE_PTR( Enabled ) )
{
hr = E_POINTER;
}
else
{
hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL );
if( SUCCEEDED( hr ) )
{
if( ullInterest & (1ui64 << SPEI_RECO_OTHER_CONTEXT) )
{
*Enabled = VARIANT_TRUE;
}
else
{
*Enabled = VARIANT_FALSE;
}
}
}
return hr;
} /* CSpeechRecoEventInterests::get_OtherContext */
/*****************************************************************************
* CSpeechRecoEventInterests::put_AudioLevel *
*----------------------------------*
*
* This method enables and disables the interest in the SPEI_SR_AUDIO_LEVEL event on
* the Reco Context.
*
********************************************************************* Leonro ***/
STDMETHODIMP CSpeechRecoEventInterests::put_AudioLevel( VARIANT_BOOL Enabled )
{
SPDBG_FUNC( "CSpeechRecoEventInterests::put_AudioLevel" );
ULONGLONG ullInterest = 0;
HRESULT hr = S_OK;
hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL );
if( SUCCEEDED( hr ) )
{
if( Enabled )
{
ullInterest |= (1ui64 << SPEI_SR_AUDIO_LEVEL);
}
else
{
ullInterest &= ~(1ui64 << SPEI_SR_AUDIO_LEVEL);
}
hr = m_pCRecoCtxt->SetInterest( ullInterest, ullInterest );
}
return hr;
} /* CSpeechRecoEventInterests::put_AudioLevel */
/*****************************************************************************
* CSpeechRecoEventInterests::get_AudioLevel *
*----------------------------------*
*
* This method determines whether or not the SPFEI(SPEI_SR_AUDIO_LEVEL interest is
* enabled on the Reco Context object.
*
********************************************************************* Leonro ***/
STDMETHODIMP CSpeechRecoEventInterests::get_AudioLevel( VARIANT_BOOL* Enabled )
{
SPDBG_FUNC( "CSpeechRecoEventInterests::get_AudioLevel" );
ULONGLONG ullInterest = 0;
HRESULT hr = S_OK;
if( SP_IS_BAD_WRITE_PTR( Enabled ) )
{
hr = E_POINTER;
}
else
{
hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL );
if( SUCCEEDED( hr ) )
{
if( ullInterest & (1ui64 << SPEI_SR_AUDIO_LEVEL) )
{
*Enabled = VARIANT_TRUE;
}
else
{
*Enabled = VARIANT_FALSE;
}
}
}
return hr;
} /* CSpeechRecoEventInterests::get_AudioLevel */
/*****************************************************************************
* CSpeechRecoEventInterests::SetAll *
*----------------------------------*
*
* This method sets all the interests on the Reco Context.
*
********************************************************************* Leonro ***/
STDMETHODIMP CSpeechRecoEventInterests::SetAll()
{
SPDBG_FUNC( "CSpeechRecoEventInterests::SetAll" );
HRESULT hr = S_OK;
hr = m_pCRecoCtxt->SetInterest( SPFEI_ALL_SR_EVENTS, SPFEI_ALL_SR_EVENTS );
return hr;
} /* CSpeechRecoEventInterests::SetAll */
/*****************************************************************************
* CSpeechRecoEventInterests::ClearAll *
*----------------------------------*
*
* This method clears all the interests on the Reco Context.
*
********************************************************************* Leonro ***/
STDMETHODIMP CSpeechRecoEventInterests::ClearAll()
{
SPDBG_FUNC( "CSpeechRecoEventInterests::ClearAll" );
HRESULT hr = S_OK;
hr = m_pCRecoCtxt->SetInterest( 0, 0 );
return hr;
} /* CSpeechRecoEventInterests::ClearAll */
#endif // SAPI_AUTOMATION
| 30.710008 | 95 | 0.481332 | npocmaka |
3d66f3f41199ebd53bd7f3919cfb09d249fc20b6 | 11,096 | cc | C++ | ui/ozone/platform/scenic/scenic_surface_factory.cc | blueboxd/chromium-legacy | 07223bc94bd97499909c9ed3c3f5769d718fe2e0 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 76 | 2020-09-02T03:05:41.000Z | 2022-03-30T04:40:55.000Z | ui/ozone/platform/scenic/scenic_surface_factory.cc | blueboxd/chromium-legacy | 07223bc94bd97499909c9ed3c3f5769d718fe2e0 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 45 | 2020-09-02T03:21:37.000Z | 2022-03-31T22:19:45.000Z | ui/ozone/platform/scenic/scenic_surface_factory.cc | blueboxd/chromium-legacy | 07223bc94bd97499909c9ed3c3f5769d718fe2e0 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 8 | 2020-07-22T18:49:18.000Z | 2022-02-08T10:27:16.000Z | // Copyright 2018 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 "ui/ozone/platform/scenic/scenic_surface_factory.h"
#include <lib/sys/cpp/component_context.h>
#include <lib/zx/event.h>
#include <memory>
#include "base/bind.h"
#include "base/containers/contains.h"
#include "base/fuchsia/fuchsia_logging.h"
#include "base/fuchsia/process_context.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "third_party/angle/src/common/fuchsia_egl/fuchsia_egl.h"
#include "ui/gfx/geometry/skia_conversions.h"
#include "ui/gfx/native_pixmap.h"
#include "ui/gfx/vsync_provider.h"
#include "ui/gl/gl_surface_egl.h"
#include "ui/ozone/common/egl_util.h"
#include "ui/ozone/common/gl_ozone_egl.h"
#include "ui/ozone/platform/scenic/scenic_gpu_service.h"
#include "ui/ozone/platform/scenic/scenic_surface.h"
#include "ui/ozone/platform/scenic/scenic_window.h"
#include "ui/ozone/platform/scenic/scenic_window_canvas.h"
#include "ui/ozone/platform/scenic/scenic_window_manager.h"
#include "ui/ozone/platform/scenic/sysmem_buffer_collection.h"
#if BUILDFLAG(ENABLE_VULKAN)
#include "ui/ozone/platform/scenic/vulkan_implementation_scenic.h"
#endif
namespace ui {
namespace {
struct FuchsiaEGLWindowDeleter {
void operator()(fuchsia_egl_window* egl_window) {
fuchsia_egl_window_destroy(egl_window);
}
};
fuchsia::ui::scenic::ScenicPtr ConnectToScenic() {
fuchsia::ui::scenic::ScenicPtr scenic =
base::ComponentContextForProcess()
->svc()
->Connect<fuchsia::ui::scenic::Scenic>();
scenic.set_error_handler(
base::LogFidlErrorAndExitProcess(FROM_HERE, "fuchsia.ui.scenic.Scenic"));
return scenic;
}
class GLSurfaceFuchsiaImagePipe : public gl::NativeViewGLSurfaceEGL {
public:
explicit GLSurfaceFuchsiaImagePipe(
ScenicSurfaceFactory* scenic_surface_factory,
gfx::AcceleratedWidget widget)
: NativeViewGLSurfaceEGL(0, nullptr),
scenic_surface_factory_(scenic_surface_factory),
widget_(widget) {}
GLSurfaceFuchsiaImagePipe(const GLSurfaceFuchsiaImagePipe&) = delete;
GLSurfaceFuchsiaImagePipe& operator=(const GLSurfaceFuchsiaImagePipe&) =
delete;
// gl::NativeViewGLSurfaceEGL:
bool InitializeNativeWindow() override {
fuchsia::images::ImagePipe2Ptr image_pipe;
ScenicSurface* scenic_surface =
scenic_surface_factory_->GetSurface(widget_);
scenic_surface->SetTextureToNewImagePipe(image_pipe.NewRequest());
egl_window_.reset(
fuchsia_egl_window_create(image_pipe.Unbind().TakeChannel().release(),
size_.width(), size_.height()));
window_ = reinterpret_cast<EGLNativeWindowType>(egl_window_.get());
return true;
}
bool Resize(const gfx::Size& size,
float scale_factor,
const gfx::ColorSpace& color_space,
bool has_alpha) override {
fuchsia_egl_window_resize(egl_window_.get(), size.width(), size.height());
return gl::NativeViewGLSurfaceEGL::Resize(size, scale_factor, color_space,
has_alpha);
}
private:
~GLSurfaceFuchsiaImagePipe() override {}
ScenicSurfaceFactory* const scenic_surface_factory_;
gfx::AcceleratedWidget widget_ = gfx::kNullAcceleratedWidget;
std::unique_ptr<fuchsia_egl_window, FuchsiaEGLWindowDeleter> egl_window_;
};
class GLOzoneEGLScenic : public GLOzoneEGL {
public:
explicit GLOzoneEGLScenic(ScenicSurfaceFactory* scenic_surface_factory)
: scenic_surface_factory_(scenic_surface_factory) {}
GLOzoneEGLScenic(const GLOzoneEGLScenic&) = delete;
GLOzoneEGLScenic& operator=(const GLOzoneEGLScenic&) = delete;
~GLOzoneEGLScenic() override = default;
// GLOzone:
scoped_refptr<gl::GLSurface> CreateViewGLSurface(
gfx::AcceleratedWidget window) override {
return gl::InitializeGLSurface(
base::MakeRefCounted<GLSurfaceFuchsiaImagePipe>(scenic_surface_factory_,
window));
}
scoped_refptr<gl::GLSurface> CreateOffscreenGLSurface(
const gfx::Size& size) override {
return gl::InitializeGLSurface(
base::MakeRefCounted<gl::SurfacelessEGL>(size));
}
gl::EGLDisplayPlatform GetNativeDisplay() override {
return gl::EGLDisplayPlatform(EGL_DEFAULT_DISPLAY);
}
protected:
bool LoadGLES2Bindings(
const gl::GLImplementationParts& implementation) override {
return LoadDefaultEGLGLES2Bindings(implementation);
}
private:
ScenicSurfaceFactory* const scenic_surface_factory_;
};
fuchsia::sysmem::AllocatorHandle ConnectSysmemAllocator() {
fuchsia::sysmem::AllocatorHandle allocator;
base::ComponentContextForProcess()->svc()->Connect(allocator.NewRequest());
return allocator;
}
} // namespace
ScenicSurfaceFactory::ScenicSurfaceFactory()
: egl_implementation_(std::make_unique<GLOzoneEGLScenic>(this)),
sysmem_buffer_manager_(this),
weak_ptr_factory_(this) {}
ScenicSurfaceFactory::~ScenicSurfaceFactory() {
Shutdown();
}
void ScenicSurfaceFactory::Initialize(
mojo::PendingRemote<mojom::ScenicGpuHost> gpu_host) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
base::AutoLock lock(surface_lock_);
DCHECK(surface_map_.empty());
main_thread_task_runner_ = base::ThreadTaskRunnerHandle::Get();
DCHECK(main_thread_task_runner_);
DCHECK(!gpu_host_);
gpu_host_.Bind(std::move(gpu_host));
sysmem_buffer_manager_.Initialize(ConnectSysmemAllocator());
// Scenic is lazily connected to avoid a dependency in headless mode.
DCHECK(!scenic_);
}
void ScenicSurfaceFactory::Shutdown() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
base::AutoLock lock(surface_lock_);
DCHECK(surface_map_.empty());
main_thread_task_runner_ = nullptr;
gpu_host_.reset();
sysmem_buffer_manager_.Shutdown();
scenic_ = nullptr;
}
std::vector<gl::GLImplementationParts>
ScenicSurfaceFactory::GetAllowedGLImplementations() {
return std::vector<gl::GLImplementationParts>{
gl::GLImplementationParts(gl::kGLImplementationEGLANGLE),
gl::GLImplementationParts(gl::kGLImplementationSwiftShaderGL),
gl::GLImplementationParts(gl::kGLImplementationEGLGLES2),
gl::GLImplementationParts(gl::kGLImplementationStubGL),
};
}
GLOzone* ScenicSurfaceFactory::GetGLOzone(
const gl::GLImplementationParts& implementation) {
switch (implementation.gl) {
case gl::kGLImplementationSwiftShaderGL:
case gl::kGLImplementationEGLGLES2:
case gl::kGLImplementationEGLANGLE:
return egl_implementation_.get();
default:
return nullptr;
}
}
std::unique_ptr<PlatformWindowSurface>
ScenicSurfaceFactory::CreatePlatformWindowSurface(
gfx::AcceleratedWidget window) {
DCHECK_NE(window, gfx::kNullAcceleratedWidget);
auto surface = std::make_unique<ScenicSurface>(this, &sysmem_buffer_manager_,
window, CreateScenicSession());
main_thread_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&ScenicSurfaceFactory::AttachSurfaceToWindow,
weak_ptr_factory_.GetWeakPtr(), window,
surface->CreateView()));
return surface;
}
std::unique_ptr<SurfaceOzoneCanvas> ScenicSurfaceFactory::CreateCanvasForWidget(
gfx::AcceleratedWidget widget) {
ScenicSurface* surface = GetSurface(widget);
return std::make_unique<ScenicWindowCanvas>(surface);
}
scoped_refptr<gfx::NativePixmap> ScenicSurfaceFactory::CreateNativePixmap(
gfx::AcceleratedWidget widget,
VkDevice vk_device,
gfx::Size size,
gfx::BufferFormat format,
gfx::BufferUsage usage,
absl::optional<gfx::Size> framebuffer_size) {
DCHECK(!framebuffer_size || framebuffer_size == size);
if (widget != gfx::kNullAcceleratedWidget &&
usage == gfx::BufferUsage::SCANOUT) {
// The usage SCANOUT is for a primary plane buffer.
auto* surface = GetSurface(widget);
CHECK(surface);
return surface->AllocatePrimaryPlanePixmap(vk_device, size, format);
}
auto collection = sysmem_buffer_manager_.CreateCollection(vk_device, size,
format, usage, 1);
if (!collection)
return nullptr;
return collection->CreateNativePixmap(0);
}
void ScenicSurfaceFactory::CreateNativePixmapAsync(
gfx::AcceleratedWidget widget,
VkDevice vk_device,
gfx::Size size,
gfx::BufferFormat format,
gfx::BufferUsage usage,
NativePixmapCallback callback) {
std::move(callback).Run(
CreateNativePixmap(widget, vk_device, size, format, usage));
}
#if BUILDFLAG(ENABLE_VULKAN)
std::unique_ptr<gpu::VulkanImplementation>
ScenicSurfaceFactory::CreateVulkanImplementation(bool use_swiftshader,
bool allow_protected_memory) {
return std::make_unique<ui::VulkanImplementationScenic>(
this, &sysmem_buffer_manager_, allow_protected_memory);
}
#endif
void ScenicSurfaceFactory::AddSurface(gfx::AcceleratedWidget widget,
ScenicSurface* surface) {
base::AutoLock lock(surface_lock_);
DCHECK(!base::Contains(surface_map_, widget));
surface->AssertBelongsToCurrentThread();
surface_map_.emplace(widget, surface);
}
void ScenicSurfaceFactory::RemoveSurface(gfx::AcceleratedWidget widget) {
base::AutoLock lock(surface_lock_);
auto it = surface_map_.find(widget);
DCHECK(it != surface_map_.end());
ScenicSurface* surface = it->second;
surface->AssertBelongsToCurrentThread();
surface_map_.erase(it);
}
ScenicSurface* ScenicSurfaceFactory::GetSurface(gfx::AcceleratedWidget widget) {
base::AutoLock lock(surface_lock_);
auto it = surface_map_.find(widget);
if (it == surface_map_.end())
return nullptr;
ScenicSurface* surface = it->second;
surface->AssertBelongsToCurrentThread();
return surface;
}
scenic::SessionPtrAndListenerRequest
ScenicSurfaceFactory::CreateScenicSession() {
fuchsia::ui::scenic::SessionPtr session;
fidl::InterfaceHandle<fuchsia::ui::scenic::SessionListener> listener_handle;
auto listener_request = listener_handle.NewRequest();
{
// Cache Scenic connection for main thread. For other treads create
// one-shot connection.
fuchsia::ui::scenic::ScenicPtr local_scenic;
fuchsia::ui::scenic::ScenicPtr* scenic =
main_thread_task_runner_->BelongsToCurrentThread() ? &scenic_
: &local_scenic;
if (!*scenic)
*scenic = ConnectToScenic();
(*scenic)->CreateSession(session.NewRequest(), std::move(listener_handle));
}
return {std::move(session), std::move(listener_request)};
}
void ScenicSurfaceFactory::AttachSurfaceToWindow(
gfx::AcceleratedWidget window,
mojo::PlatformHandle surface_view_holder_token_mojo) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
gpu_host_->AttachSurfaceToWindow(window,
std::move(surface_view_holder_token_mojo));
}
} // namespace ui
| 34.246914 | 80 | 0.727379 | blueboxd |
3d693dac6cbf4bafac99f7da2535618067b5fb6a | 1,553 | cc | C++ | src/libraptor/Utility.cc | RabbitNick/rfc5053 | e7a8e94be467a1e5d9fa18f55d6bf4dd84757dec | [
"MIT"
] | 28 | 2015-04-11T10:20:25.000Z | 2021-04-28T15:48:36.000Z | src/libraptor/Utility.cc | RabbitNick/rfc5053 | e7a8e94be467a1e5d9fa18f55d6bf4dd84757dec | [
"MIT"
] | 1 | 2016-11-25T06:10:13.000Z | 2016-11-25T06:10:13.000Z | src/libraptor/Utility.cc | RabbitNick/rfc5053 | e7a8e94be467a1e5d9fa18f55d6bf4dd84757dec | [
"MIT"
] | 18 | 2015-04-10T08:25:48.000Z | 2022-01-25T11:22:31.000Z |
#include "Utility.h"
Utility::Utility(void)
{
}
Utility::~Utility(void)
{
}
bool Utility::checking_prime_integer(uint32_t v)
{
for (int i = 2; i < v; i++)
{
if (v % i == 0)
{
return 0;
}
}
return 1;
}
uint32_t Utility::find_smallest_prime_integer(uint32_t v)
{
bool r = 0;
uint32_t prime = v;
r = checking_prime_integer(prime);
while(r == 0)
{
prime++;
r = checking_prime_integer(prime);
}
//prime--;
return prime;
}
ublas::vector<uint8_t> Utility::matrix_row_XOR(ublas::vector<uint8_t> row_1, ublas::vector<uint8_t> row_2)
{
if (row_1.size() != row_2.size())
{
std::cout << "The columns are not the same in two rows!" << std::endl;
exit(-1);
}
ublas::vector<uint8_t> r(row_1.size());
for (int i = 0; i < row_1.size(); ++i)
{
r(i) = row_1(i) ^ row_2(i);
}
return r;
}
// template<class T>
// bool Utility::InvertMatrix (const boost::numeric::ublas::matrix<T>& input, boost::numeric::ublas::matrix<T>& inverse)
// {
// using namespace boost::numeric::ublas;
// typedef permutation_matrix<std::size_t> pmatrix;
// // create a working copy of the input
// matrix<T> A(input);
// // create a permutation matrix for the LU-factorization
// pmatrix pm(A.size1());
// // perform LU-factorization
// int res = lu_factorize(A,pm);
// if( res != 0 ) return false;
// // create identity matrix of "inverse"
// inverse.assign(boost::numeric::ublas::identity_matrix<T>(A.size1()));
// // backsubstitute to get the inverse
// lu_substitute(A, pm, inverse);
// return true;
// } | 16.521277 | 120 | 0.631037 | RabbitNick |
3d6c20b45a546f37ae10e83a2456432c8c3ded8d | 7,016 | cpp | C++ | src/chatroomwindow.cpp | Alpha-Incorporated/Chatter-Box | 96937353a75c2dcb8e89e99fb3d317211ff7e85c | [
"MIT"
] | 2 | 2019-02-27T12:02:16.000Z | 2019-02-27T15:29:49.000Z | src/chatroomwindow.cpp | Alien-Inc/Chatter-Box | 96937353a75c2dcb8e89e99fb3d317211ff7e85c | [
"MIT"
] | 2 | 2020-11-19T08:39:52.000Z | 2020-11-19T08:50:19.000Z | src/chatroomwindow.cpp | Alpha-Incorporated/Chatter-Box | 96937353a75c2dcb8e89e99fb3d317211ff7e85c | [
"MIT"
] | 1 | 2020-02-21T04:26:13.000Z | 2020-02-21T04:26:13.000Z | #include "chatroomwindow.h"
using namespace chat_room;
ChatRoomWindow::ChatRoomWindow() : QMainWindow(nullptr), initialized(false)
{
// Set up Window
this->setGeometry(150, 150, 640, 480);
setWindowTitle(tr("Chat"));
setMinimumSize(640, 480);
// Menu Bar
exit_chat_action = new QAction(QString("Exit"), this);
chat_menu = menuBar()->addMenu(tr("Chat"));
chat_menu->addAction(exit_chat_action);
connect(exit_chat_action, &QAction::triggered, this, &ChatRoomWindow::exitCurrentChat);
menuBar()->hide();
// Conversation List
conversation_model = new ConversationModel(this);
conversation_list = new QListView(this);
conversation_list->setModel(conversation_model);
conversation_list->setGeometry(0, 0, 640, 480);
connect(conversation_list, &QListView::clicked, this, &ChatRoomWindow::onConversationListClicked);
// Additional set-up
app_data_directory = QString(getenv("LOCALAPPDATA")) + QString("/ChatApp/");
connect(client_socket, &QWebSocket::textMessageReceived, this, &ChatRoomWindow::onTextMessageReceived);
connect(client_socket, &QWebSocket::binaryMessageReceived, this, &ChatRoomWindow::onBinaryMessageReceived);
std::clog << "Chat : ChatRoomWindow set up!" << std::endl;
}
ChatRoomWindow::~ChatRoomWindow()
{
if (message_list) {
delete message_list;
}
if (conversation_list) {
delete conversation_list;
}
if (message_model) {
delete message_model;
}
if (conversation_model) {
delete conversation_model;
}
if (send_text_button) {
delete send_text_button;
}
if (message_input_box) {
delete message_input_box;
}
if (chat_menu_bar) {
delete chat_menu_bar;
}
if (chat_menu) {
delete chat_menu;
}
if (exit_chat_action) {
delete exit_chat_action;
}
}
void ChatRoomWindow::onConversationListClicked(const QModelIndex& model_index)
{
std::clog << "Chat : ChatRoomWindow - Chat list item clicked" << std::endl;
unsigned int index = model_index.row();
User clicked_user = user_list[index];
current_receiver = clicked_user;
// Open the particular conversation
this->setUpChatRoom();
// Add pending messages
std::stringstream file_name_stream;
file_name_stream << current_receiver << current_user;
std::string file_name;
std::getline(file_name_stream, file_name);
std::ifstream pending_message_file(file_name);
if (pending_message_file.is_open())
{
Message message;
while (!(pending_message_file >> message).eof()) {
message_model->addMessage(message);
}
pending_message_file.close();
std::remove(file_name.c_str());
}
initialized = true;
}
void ChatRoomWindow::onSendTextButtonClicked()
{
std::clog << "Chat : ChatRoomWindow - Send text button clicked" << std::endl;
QString text = message_input_box->text();
message_input_box->setText(QString(""));
if (!text.isEmpty()) {
Message message(current_user, current_receiver, text.toStdString());
message_model->addMessage(message);
std::stringstream message_stream;
message_stream << message;
std::string data;
std::getline(message_stream, data);
client_socket->sendTextMessage(QString(data.c_str()));
}
}
void ChatRoomWindow::onReturnKeyPressed()
{
std::clog << "Chat : ChatRoom - Return key pressed" << std::endl;
QString text = message_input_box->text();
message_input_box->setText(QString(""));
if (!text.isEmpty()) {
Message message(current_user, current_receiver, text.toStdString());
message_model->addMessage(message);
std::stringstream message_stream;
message_stream << message;
std::string data;
std::getline(message_stream, data);
client_socket->sendTextMessage(QString(data.c_str()));
}
}
void ChatRoomWindow::onTextMessageReceived(const QString &data)
{
std::clog << "Chat : ChatRoomWindow - New message received" << std::endl;
std::stringstream data_stream(data.toStdString());
User from, to;
std::string text;
std::getline(data_stream >> from >> to, text);
Message message(from, to, text);
if (!text.empty()) {
if (from == current_receiver) {
message_model->addMessage(message);
}
else {
std::stringstream file_name_stream;
file_name_stream >> from >> to;
std::string file_name;
std::getline(file_name_stream, file_name);
std::ofstream pending_messages_file(file_name, std::ios::app);
pending_messages_file << message << std::endl;
}
}
}
void ChatRoomWindow::onBinaryMessageReceived(const QByteArray &byte_stream)
{
std::clog << "Chat : ChatRoomWindow - Binary data received from server" << std::endl;
std::stringstream data_stream(byte_stream.toStdString());
std::string type;
data_stream >> type;
if (type == "userlist")
{
User user;
user_list.erase(user_list.begin(), user_list.end());
while (!(data_stream >> user).eof())
{
user_list.push_back(user);
}
conversation_model->updateUserList(user_list);
}
else if (type == "userdata") {
data_stream >> current_user;
std::clog << "Chat : ChatRoomWindow - Current user data populated" << std::endl;
}
}
void ChatRoomWindow::setUpChatRoom()
{
conversation_list->hide();
send_text_button = new QPushButton(SEND_TEXT_BUTTON_TEXT, this);
message_input_box = new QLineEdit(this);
message_list = new QListView(this);
send_text_button->setGeometry(540, 460, 80, 40);
message_input_box->setGeometry(0, 440, 560, 40);
message_input_box->setFont(QFont("Default", 15));
message_model = new MessageModel(this);
message_list->setModel(message_model);
message_list->setGeometry(0, 25, 640, 415);
message_list->setFont(QFont("Default", 15));
menuBar()->show();
send_text_button->show();
message_input_box->show();
message_list->show();
connect(send_text_button, &QPushButton::clicked, this, &ChatRoomWindow::onSendTextButtonClicked);
connect(message_input_box, &QLineEdit::returnPressed, this, &ChatRoomWindow::onReturnKeyPressed);
}
void ChatRoomWindow::exitCurrentChat()
{
std::clog << "Chat : ChatRoom - Current chat exited" << std::endl;
send_text_button->disconnect();
message_input_box->disconnect();
message_list->disconnect();
delete send_text_button;
delete message_input_box;
delete message_list;
menuBar()->hide();
conversation_list->show();
}
| 28.064 | 112 | 0.638683 | Alpha-Incorporated |
3d70329e7cbc40ded3bdfda45592de5854d0ae37 | 677 | cpp | C++ | Camp_0-2563/1007-AwitCat34.cpp | MasterIceZ/POSN_BUU | 56e176fb843d7ddcee0cf4acf2bb141576c260cf | [
"MIT"
] | null | null | null | Camp_0-2563/1007-AwitCat34.cpp | MasterIceZ/POSN_BUU | 56e176fb843d7ddcee0cf4acf2bb141576c260cf | [
"MIT"
] | null | null | null | Camp_0-2563/1007-AwitCat34.cpp | MasterIceZ/POSN_BUU | 56e176fb843d7ddcee0cf4acf2bb141576c260cf | [
"MIT"
] | null | null | null | /*
* TASK : AwitCat34
* AUTHOR : Hydrolyzed~
* LANG : C
* SCHOOL : RYW
* */
#include<stdio.h>
#include<string.h>
char a[510];
char *ptr;
int main (){
int i,q,ch,ch2,len;
gets(a);
sscanf(a,"%d",&q);
while(q--)
{
gets(a);
if(a[strlen(a)-1]=='\r')
a[strlen(a)-1]='\0';
ptr = strtok(a," ");
ch = 1;
while(ptr!= NULL)
{
len = strlen(ptr);
if(len%4==0){
for(i=0,ch2=1;i<len;i+=4){
if(strncmp("meow",&ptr[i],4)){
ch2=0;
break;
}
}
if(ch2){
printf("YES\n"); ch= 0; break;
}
}
ptr = strtok(NULL," ");
}
if(ch){
printf("NO\n");
}
}
}
| 14.104167 | 36 | 0.423929 | MasterIceZ |
3d708f463d383f4177d06c7c5839f517b028fc96 | 23,280 | cc | C++ | third_party/blink/renderer/core/html/html_iframe_element.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/blink/renderer/core/html/html_iframe_element.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/blink/renderer/core/html/html_iframe_element.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-01-05T23:43:46.000Z | 2021-01-07T23:36:34.000Z | /*
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 1999 Antti Koivisto (koivisto@kde.org)
* (C) 2000 Simon Hausmann (hausmann@kde.org)
* (C) 2001 Dirk Mueller (mueller@kde.org)
* Copyright (C) 2004, 2006, 2008, 2009 Apple Inc. All rights reserved.
* Copyright (C) 2009 Ericsson AB. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "third_party/blink/renderer/core/html/html_iframe_element.h"
#include "base/metrics/histogram_macros.h"
#include "services/network/public/cpp/features.h"
#include "services/network/public/cpp/web_sandbox_flags.h"
#include "services/network/public/mojom/trust_tokens.mojom-blink.h"
#include "services/network/public/mojom/web_sandbox_flags.mojom-blink.h"
#include "third_party/blink/public/mojom/feature_policy/feature_policy.mojom-blink.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_html_iframe_element.h"
#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/style_change_reason.h"
#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/core/feature_policy/document_policy_parser.h"
#include "third_party/blink/renderer/core/feature_policy/feature_policy_parser.h"
#include "third_party/blink/renderer/core/feature_policy/iframe_policy.h"
#include "third_party/blink/renderer/core/fetch/trust_token_issuance_authorization.h"
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
#include "third_party/blink/renderer/core/frame/sandbox_flags.h"
#include "third_party/blink/renderer/core/html/html_document.h"
#include "third_party/blink/renderer/core/html/trust_token_attribute_parsing.h"
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/core/layout/layout_iframe.h"
#include "third_party/blink/renderer/core/loader/document_loader.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/json/json_parser.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
namespace blink {
HTMLIFrameElement::HTMLIFrameElement(Document& document)
: HTMLFrameElementBase(html_names::kIFrameTag, document),
collapsed_by_client_(false),
sandbox_(MakeGarbageCollected<HTMLIFrameElementSandbox>(this)),
referrer_policy_(network::mojom::ReferrerPolicy::kDefault) {}
void HTMLIFrameElement::Trace(Visitor* visitor) const {
visitor->Trace(sandbox_);
visitor->Trace(policy_);
HTMLFrameElementBase::Trace(visitor);
Supplementable<HTMLIFrameElement>::Trace(visitor);
}
HTMLIFrameElement::~HTMLIFrameElement() = default;
const AttrNameToTrustedType& HTMLIFrameElement::GetCheckedAttributeTypes()
const {
DEFINE_STATIC_LOCAL(AttrNameToTrustedType, attribute_map,
({{"srcdoc", SpecificTrustedType::kHTML}}));
return attribute_map;
}
void HTMLIFrameElement::SetCollapsed(bool collapse) {
if (collapsed_by_client_ == collapse)
return;
collapsed_by_client_ = collapse;
// This is always called in response to an IPC, so should not happen in the
// middle of a style recalc.
DCHECK(!GetDocument().InStyleRecalc());
// Trigger style recalc to trigger layout tree re-attachment.
SetNeedsStyleRecalc(kLocalStyleChange, StyleChangeReasonForTracing::Create(
style_change_reason::kFrame));
}
DOMTokenList* HTMLIFrameElement::sandbox() const {
return sandbox_.Get();
}
DOMFeaturePolicy* HTMLIFrameElement::featurePolicy() {
if (!policy_ && GetExecutionContext()) {
policy_ = MakeGarbageCollected<IFramePolicy>(
GetExecutionContext(), GetFramePolicy().container_policy,
GetOriginForFeaturePolicy());
}
return policy_.Get();
}
bool HTMLIFrameElement::IsPresentationAttribute(
const QualifiedName& name) const {
if (name == html_names::kWidthAttr || name == html_names::kHeightAttr ||
name == html_names::kAlignAttr || name == html_names::kFrameborderAttr)
return true;
return HTMLFrameElementBase::IsPresentationAttribute(name);
}
void HTMLIFrameElement::CollectStyleForPresentationAttribute(
const QualifiedName& name,
const AtomicString& value,
MutableCSSPropertyValueSet* style) {
if (name == html_names::kWidthAttr) {
AddHTMLLengthToStyle(style, CSSPropertyID::kWidth, value);
} else if (name == html_names::kHeightAttr) {
AddHTMLLengthToStyle(style, CSSPropertyID::kHeight, value);
} else if (name == html_names::kAlignAttr) {
ApplyAlignmentAttributeToStyle(value, style);
} else if (name == html_names::kFrameborderAttr) {
// LocalFrame border doesn't really match the HTML4 spec definition for
// iframes. It simply adds a presentational hint that the border should be
// off if set to zero.
if (!value.ToInt()) {
// Add a rule that nulls out our border width.
AddPropertyToPresentationAttributeStyle(
style, CSSPropertyID::kBorderWidth, 0,
CSSPrimitiveValue::UnitType::kPixels);
}
} else {
HTMLFrameElementBase::CollectStyleForPresentationAttribute(name, value,
style);
}
}
void HTMLIFrameElement::ParseAttribute(
const AttributeModificationParams& params) {
const QualifiedName& name = params.name;
const AtomicString& value = params.new_value;
if (name == html_names::kNameAttr) {
auto* document = DynamicTo<HTMLDocument>(GetDocument());
if (document && IsInDocumentTree()) {
document->RemoveNamedItem(name_);
document->AddNamedItem(value);
}
AtomicString old_name = name_;
name_ = value;
if (name_ != old_name)
FrameOwnerPropertiesChanged();
} else if (name == html_names::kSandboxAttr) {
sandbox_->DidUpdateAttributeValue(params.old_value, value);
bool feature_policy_for_sandbox =
RuntimeEnabledFeatures::FeaturePolicyForSandboxEnabled();
network::mojom::blink::WebSandboxFlags current_flags =
network::mojom::blink::WebSandboxFlags::kNone;
if (!value.IsNull()) {
using network::mojom::blink::WebSandboxFlags;
WebSandboxFlags ignored_flags =
!RuntimeEnabledFeatures::StorageAccessAPIEnabled()
? WebSandboxFlags::kStorageAccessByUserActivation
: WebSandboxFlags::kNone;
auto parsed = network::ParseWebSandboxPolicy(sandbox_->value().Utf8(),
ignored_flags);
current_flags = parsed.flags;
if (!parsed.error_message.empty()) {
GetDocument().AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>(
mojom::blink::ConsoleMessageSource::kOther,
mojom::blink::ConsoleMessageLevel::kError,
WebString::FromUTF8(
"Error while parsing the 'sandbox' attribute: " +
parsed.error_message)));
}
}
SetAllowedToDownload(
(current_flags & network::mojom::blink::WebSandboxFlags::kDownloads) ==
network::mojom::blink::WebSandboxFlags::kNone);
// With FeaturePolicyForSandbox, sandbox flags are represented as part of
// the container policies. However, not all sandbox flags are yet converted
// and for now the residue will stay around in the stored flags.
// (see https://crbug.com/812381).
network::mojom::blink::WebSandboxFlags sandbox_to_set = current_flags;
sandbox_flags_converted_to_feature_policies_ =
network::mojom::blink::WebSandboxFlags::kNone;
if (feature_policy_for_sandbox &&
current_flags != network::mojom::blink::WebSandboxFlags::kNone) {
// Residue sandbox which will not be mapped to feature policies.
sandbox_to_set =
GetSandboxFlagsNotImplementedAsFeaturePolicy(current_flags);
// The part of sandbox which will be mapped to feature policies.
sandbox_flags_converted_to_feature_policies_ =
current_flags & ~sandbox_to_set;
}
SetSandboxFlags(sandbox_to_set);
if (RuntimeEnabledFeatures::FeaturePolicyForSandboxEnabled())
UpdateContainerPolicy();
UseCounter::Count(GetDocument(), WebFeature::kSandboxViaIFrame);
} else if (name == html_names::kReferrerpolicyAttr) {
referrer_policy_ = network::mojom::ReferrerPolicy::kDefault;
if (!value.IsNull()) {
SecurityPolicy::ReferrerPolicyFromString(
value, kSupportReferrerPolicyLegacyKeywords, &referrer_policy_);
UseCounter::Count(GetDocument(),
WebFeature::kHTMLIFrameElementReferrerPolicyAttribute);
}
} else if (name == html_names::kAllowfullscreenAttr) {
bool old_allow_fullscreen = allow_fullscreen_;
allow_fullscreen_ = !value.IsNull();
if (allow_fullscreen_ != old_allow_fullscreen) {
// TODO(iclelland): Remove this use counter when the allowfullscreen
// attribute state is snapshotted on document creation. crbug.com/682282
if (allow_fullscreen_ && ContentFrame()) {
UseCounter::Count(
GetDocument(),
WebFeature::
kHTMLIFrameElementAllowfullscreenAttributeSetAfterContentLoad);
}
FrameOwnerPropertiesChanged();
UpdateContainerPolicy();
}
} else if (name == html_names::kAllowpaymentrequestAttr) {
bool old_allow_payment_request = allow_payment_request_;
allow_payment_request_ = !value.IsNull();
if (allow_payment_request_ != old_allow_payment_request) {
FrameOwnerPropertiesChanged();
UpdateContainerPolicy();
}
} else if (name == html_names::kCspAttr) {
if (base::FeatureList::IsEnabled(network::features::kOutOfBlinkCSPEE)) {
if (value.Contains('\n') || value.Contains('\r') || value.Contains(',')) {
required_csp_ = g_null_atom;
GetDocument().AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>(
mojom::blink::ConsoleMessageSource::kOther,
mojom::blink::ConsoleMessageLevel::kError,
"'csp' attribute is invalid: " + value));
return;
}
if (required_csp_ != value) {
required_csp_ = value;
CSPAttributeChanged();
UseCounter::Count(GetDocument(), WebFeature::kIFrameCSPAttribute);
}
} else {
if (!ContentSecurityPolicy::IsValidCSPAttr(
value.GetString(), GetDocument().RequiredCSP().GetString())) {
required_csp_ = g_null_atom;
GetDocument().AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>(
mojom::blink::ConsoleMessageSource::kOther,
mojom::blink::ConsoleMessageLevel::kError,
"'csp' attribute is not a valid policy: " + value));
return;
}
if (required_csp_ != value) {
required_csp_ = value;
FrameOwnerPropertiesChanged();
UseCounter::Count(GetDocument(), WebFeature::kIFrameCSPAttribute);
}
}
} else if (name == html_names::kAllowAttr) {
if (allow_ != value) {
allow_ = value;
UpdateContainerPolicy();
if (!value.IsEmpty()) {
UseCounter::Count(GetDocument(),
WebFeature::kFeaturePolicyAllowAttribute);
}
if (value.Contains(',')) {
UseCounter::Count(GetDocument(),
WebFeature::kCommaSeparatorInAllowAttribute);
}
}
} else if (name == html_names::kDisallowdocumentaccessAttr &&
RuntimeEnabledFeatures::DisallowDocumentAccessEnabled()) {
UseCounter::Count(GetDocument(), WebFeature::kDisallowDocumentAccess);
SetDisallowDocumentAccesss(!value.IsNull());
// We don't need to call tell the client frame properties
// changed since this attribute only stays inside the renderer.
} else if (name == html_names::kPolicyAttr) {
if (required_policy_ != value) {
required_policy_ = value;
UpdateRequiredPolicy();
}
} else if (name == html_names::kTrusttokenAttr) {
trust_token_ = value;
} else {
// Websites picked up a Chromium article that used this non-specified
// attribute which ended up changing shape after the specification process.
// This error message and use count will help developers to move to the
// proper solution.
// To avoid polluting the console, this is being recorded only once per
// page.
if (name == "gesture" && value == "media" && GetDocument().Loader() &&
!GetDocument().Loader()->GetUseCounterHelper().HasRecordedMeasurement(
WebFeature::kHTMLIFrameElementGestureMedia)) {
UseCounter::Count(GetDocument(),
WebFeature::kHTMLIFrameElementGestureMedia);
GetDocument().AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>(
mojom::ConsoleMessageSource::kOther,
mojom::ConsoleMessageLevel::kWarning,
"<iframe gesture=\"media\"> is not supported. "
"Use <iframe allow=\"autoplay\">, "
"https://goo.gl/ximf56"));
}
if (name == html_names::kSrcAttr)
LogUpdateAttributeIfIsolatedWorldAndInDocument("iframe", params);
HTMLFrameElementBase::ParseAttribute(params);
}
}
DocumentPolicyFeatureState HTMLIFrameElement::ConstructRequiredPolicy() const {
if (!RuntimeEnabledFeatures::DocumentPolicyNegotiationEnabled(
GetExecutionContext()))
return {};
if (!required_policy_.IsEmpty()) {
UseCounter::Count(
GetDocument(),
mojom::blink::WebFeature::kDocumentPolicyIframePolicyAttribute);
}
PolicyParserMessageBuffer logger;
DocumentPolicy::ParsedDocumentPolicy new_required_policy =
DocumentPolicyParser::Parse(required_policy_, logger)
.value_or(DocumentPolicy::ParsedDocumentPolicy{});
for (const auto& message : logger.GetMessages()) {
GetDocument().AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>(
mojom::blink::ConsoleMessageSource::kOther, message.level,
message.content));
}
if (!new_required_policy.endpoint_map.empty()) {
GetDocument().AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>(
mojom::blink::ConsoleMessageSource::kOther,
mojom::blink::ConsoleMessageLevel::kWarning,
"Iframe policy attribute cannot specify reporting endpoint."));
}
for (const auto& policy_entry : new_required_policy.feature_state) {
mojom::blink::DocumentPolicyFeature feature = policy_entry.first;
if (!GetDocument().DocumentPolicyFeatureObserved(feature)) {
UMA_HISTOGRAM_ENUMERATION(
"Blink.UseCounter.DocumentPolicy.PolicyAttribute", feature);
}
}
return new_required_policy.feature_state;
}
ParsedFeaturePolicy HTMLIFrameElement::ConstructContainerPolicy() const {
if (!GetExecutionContext())
return ParsedFeaturePolicy();
scoped_refptr<const SecurityOrigin> src_origin = GetOriginForFeaturePolicy();
scoped_refptr<const SecurityOrigin> self_origin =
GetExecutionContext()->GetSecurityOrigin();
PolicyParserMessageBuffer logger;
// Start with the allow attribute
ParsedFeaturePolicy container_policy = FeaturePolicyParser::ParseAttribute(
allow_, self_origin, src_origin, logger, GetExecutionContext());
// Next, process sandbox flags. These all only take effect if a corresponding
// policy does *not* exist in the allow attribute's value.
if (RuntimeEnabledFeatures::FeaturePolicyForSandboxEnabled()) {
// If the frame is sandboxed at all, then warn if feature policy attributes
// will override the sandbox attributes.
if ((sandbox_flags_converted_to_feature_policies_ &
network::mojom::blink::WebSandboxFlags::kNavigation) !=
network::mojom::blink::WebSandboxFlags::kNone) {
for (const auto& pair : SandboxFlagsWithFeaturePolicies()) {
if ((sandbox_flags_converted_to_feature_policies_ & pair.first) !=
network::mojom::blink::WebSandboxFlags::kNone &&
IsFeatureDeclared(pair.second, container_policy)) {
logger.Warn(String::Format(
"Allow and Sandbox attributes both mention '%s'. Allow will take "
"precedence.",
GetNameForFeature(pair.second).Utf8().c_str()));
}
}
}
ApplySandboxFlagsToParsedFeaturePolicy(
sandbox_flags_converted_to_feature_policies_, container_policy);
}
// Finally, process the allow* attribuets. Like sandbox attributes, they only
// take effect if the corresponding feature is not present in the allow
// attribute's value.
// If allowfullscreen attribute is present and no fullscreen policy is set,
// enable the feature for all origins.
if (AllowFullscreen()) {
bool policy_changed = AllowFeatureEverywhereIfNotPresent(
mojom::blink::FeaturePolicyFeature::kFullscreen, container_policy);
if (!policy_changed) {
logger.Warn(
"Allow attribute will take precedence over 'allowfullscreen'.");
}
}
// If the allowpaymentrequest attribute is present and no 'payment' policy is
// set, enable the feature for all origins.
if (AllowPaymentRequest()) {
bool policy_changed = AllowFeatureEverywhereIfNotPresent(
mojom::blink::FeaturePolicyFeature::kPayment, container_policy);
if (!policy_changed) {
logger.Warn(
"Allow attribute will take precedence over 'allowpaymentrequest'.");
}
}
// Update the JavaScript policy object associated with this iframe, if it
// exists.
if (policy_)
policy_->UpdateContainerPolicy(container_policy, src_origin);
for (const auto& message : logger.GetMessages()) {
GetDocument().AddConsoleMessage(
MakeGarbageCollected<ConsoleMessage>(
mojom::blink::ConsoleMessageSource::kOther, message.level,
message.content),
/* discard_duplicates */ true);
}
return container_policy;
}
bool HTMLIFrameElement::LayoutObjectIsNeeded(const ComputedStyle& style) const {
return ContentFrame() && !collapsed_by_client_ &&
HTMLElement::LayoutObjectIsNeeded(style);
}
LayoutObject* HTMLIFrameElement::CreateLayoutObject(const ComputedStyle&,
LegacyLayout) {
return new LayoutIFrame(this);
}
Node::InsertionNotificationRequest HTMLIFrameElement::InsertedInto(
ContainerNode& insertion_point) {
InsertionNotificationRequest result =
HTMLFrameElementBase::InsertedInto(insertion_point);
auto* html_doc = DynamicTo<HTMLDocument>(GetDocument());
if (html_doc && insertion_point.IsInDocumentTree()) {
html_doc->AddNamedItem(name_);
if (!base::FeatureList::IsEnabled(network::features::kOutOfBlinkCSPEE) &&
!ContentSecurityPolicy::IsValidCSPAttr(
required_csp_, GetDocument().RequiredCSP().GetString())) {
if (!required_csp_.IsEmpty()) {
GetDocument().AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>(
mojom::ConsoleMessageSource::kOther,
mojom::ConsoleMessageLevel::kError,
"'csp' attribute is not a valid policy: " + required_csp_));
}
if (required_csp_ != GetDocument().RequiredCSP()) {
required_csp_ = GetDocument().RequiredCSP();
FrameOwnerPropertiesChanged();
UseCounter::Count(GetDocument(), WebFeature::kIFrameCSPAttribute);
}
}
}
LogAddElementIfIsolatedWorldAndInDocument("iframe", html_names::kSrcAttr);
return result;
}
void HTMLIFrameElement::RemovedFrom(ContainerNode& insertion_point) {
HTMLFrameElementBase::RemovedFrom(insertion_point);
auto* html_doc = DynamicTo<HTMLDocument>(GetDocument());
if (html_doc && insertion_point.IsInDocumentTree())
html_doc->RemoveNamedItem(name_);
}
bool HTMLIFrameElement::IsInteractiveContent() const {
return true;
}
network::mojom::ReferrerPolicy HTMLIFrameElement::ReferrerPolicyAttribute() {
return referrer_policy_;
}
network::mojom::blink::TrustTokenParamsPtr
HTMLIFrameElement::ConstructTrustTokenParams() const {
if (!trust_token_)
return nullptr;
JSONParseError parse_error;
std::unique_ptr<JSONValue> parsed_attribute =
ParseJSON(trust_token_, &parse_error);
if (!parsed_attribute) {
GetDocument().AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>(
mojom::blink::ConsoleMessageSource::kOther,
mojom::blink::ConsoleMessageLevel::kError,
"iframe trusttoken attribute was invalid JSON: " + parse_error.message +
String::Format(" (line %d, col %d)", parse_error.line,
parse_error.column)));
return nullptr;
}
network::mojom::blink::TrustTokenParamsPtr parsed_params =
internal::TrustTokenParamsFromJson(std::move(parsed_attribute));
if (!parsed_params) {
GetDocument().AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>(
mojom::blink::ConsoleMessageSource::kOther,
mojom::blink::ConsoleMessageLevel::kError,
"Couldn't parse iframe trusttoken attribute (was it missing a "
"field?)"));
return nullptr;
}
// Trust token redemption and signing (but not issuance) require that the
// trust-token-redemption feature policy be present.
bool operation_requires_feature_policy =
parsed_params->type ==
network::mojom::blink::TrustTokenOperationType::kRedemption ||
parsed_params->type ==
network::mojom::blink::TrustTokenOperationType::kSigning;
if (operation_requires_feature_policy &&
(!GetExecutionContext()->IsFeatureEnabled(
mojom::blink::FeaturePolicyFeature::kTrustTokenRedemption))) {
GetExecutionContext()->AddConsoleMessage(
MakeGarbageCollected<ConsoleMessage>(
mojom::blink::ConsoleMessageSource::kOther,
mojom::blink::ConsoleMessageLevel::kError,
"Trust Tokens: Attempted redemption or signing without the "
"trust-token-redemption Feature Policy feature present."));
return nullptr;
}
if (parsed_params->type ==
network::mojom::blink::TrustTokenOperationType::kIssuance &&
!IsTrustTokenIssuanceAvailableInExecutionContext(
*GetExecutionContext())) {
GetDocument().AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>(
mojom::blink::ConsoleMessageSource::kOther,
mojom::blink::ConsoleMessageLevel::kError,
"Trust Tokens issuance is disabled except in "
"contexts with the TrustTokens Origin Trial enabled."));
return nullptr;
}
return parsed_params;
}
} // namespace blink
| 42.173913 | 85 | 0.708591 | mghgroup |
3d723a663ce7d5148bc1a2e3f308422cc832ea65 | 286 | cpp | C++ | src/cliente/modelos/PuntuacionJugadores.cpp | humbertodias/Final-Fight | f5f8983dce599cc68548797d6d992cb34b44c3b2 | [
"MIT"
] | null | null | null | src/cliente/modelos/PuntuacionJugadores.cpp | humbertodias/Final-Fight | f5f8983dce599cc68548797d6d992cb34b44c3b2 | [
"MIT"
] | null | null | null | src/cliente/modelos/PuntuacionJugadores.cpp | humbertodias/Final-Fight | f5f8983dce599cc68548797d6d992cb34b44c3b2 | [
"MIT"
] | null | null | null | //
// Created by sebas on 7/11/19.
//
#include "PuntuacionJugadores.h"
void
PuntuacionJugadores::setPuntuacion (string jugador, int puntuacion)
{
puntuaciones[jugador] = puntuacion;
}
unordered_map < string, int >
PuntuacionJugadores::getPuntuaciones ()
{
return puntuaciones;
}
| 15.888889 | 67 | 0.744755 | humbertodias |
3d7273bdb42f812dbdfd16ed655854dffcbbc0f0 | 2,768 | cpp | C++ | Interface/mainwindow.cpp | EduFreit4s/MEOWN | cd4c6e56a66c251ff485103a10308c5a2e34347c | [
"MIT"
] | null | null | null | Interface/mainwindow.cpp | EduFreit4s/MEOWN | cd4c6e56a66c251ff485103a10308c5a2e34347c | [
"MIT"
] | null | null | null | Interface/mainwindow.cpp | EduFreit4s/MEOWN | cd4c6e56a66c251ff485103a10308c5a2e34347c | [
"MIT"
] | 2 | 2020-01-25T12:19:57.000Z | 2020-09-29T23:54:19.000Z | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
for(auto& item : QSerialPortInfo::availablePorts()){
ui->box_serial->addItem(item.portName());
}
for(auto& item : QSerialPortInfo::standardBaudRates()){
ui->box_velocidade->addItem(QString::number(item));
}
connect(&serial,
SIGNAL(readyRead()),
this,
SLOT(dadosRecebidos()));
}
MainWindow::~MainWindow()
{
serial.close();
delete ui;
}
void MainWindow::dadosRecebidos()
{
auto data = serial.readAll();
auto dados = QJsonDocument::fromJson(data).object().toVariantMap();
if(dados.contains("POWER")){
power = dados["POWER"].toString();
ui->tabelaStats->setItem(1,1, new QTableWidgetItem(power));
}
if(dados.contains("VOLT")){
volt = dados["VOLT"].toString();
ui->tabelaStats->setItem(2,1, new QTableWidgetItem(volt));
}
if(dados.contains("AMPER")){
amper = dados["AMPER"].toString();
ui->tabelaStats->setItem(3,1, new QTableWidgetItem(amper));
}
}
void MainWindow::on_btnPlug_clicked()
{
plugStatus = !plugStatus;
if(plugStatus){
serial.setPortName(ui->box_serial->currentText());
serial.setBaudRate(ui->box_velocidade->currentText().toInt());
if(serial.open(QIODevice::ReadWrite)){
ui->status_conexao->setText("Status: Conectado");
ui -> btnPlug ->setText("Desconectar");
}
}else{
serial.close();
ui->status_conexao->setText("Status: Desconectado");
ui -> btnPlug ->setText("Conectar");
}
}
void MainWindow::on_btnAction_clicked()
{
action = !action;
qDebug() << action;
if(action){
ui->btnAction->setText("Desativar alimentação manual");
serial.write("{\"ACAO\": 1}");
}else{
ui->btnAction->setText("Ativar alimentação manual");
serial.write("{\"ACAO\": 0}");
}
}
void MainWindow::on_btnEmailEdu_clicked()
{
QUrl email = QUrl("mailto:freitas.eduardo@academico.ifpb.edu.br");
QDesktopServices::openUrl(email);
}
void MainWindow::on_btnEmailNeto_clicked()
{
QUrl email = QUrl("mailto:neto.batista@academico.ifpb.edu.br");
QDesktopServices::openUrl(email);
}
void MainWindow::on_btnGithub_clicked()
{
QUrl github = QUrl("https://github.com/EduFreit4s/Meown");
QDesktopServices::openUrl(github);
}
void MainWindow::on_btnSite_clicked()
{
QUrl github = QUrl("https://meown-engine.herokuapp.com/");
QDesktopServices::openUrl(github);
}
| 24.714286 | 71 | 0.61091 | EduFreit4s |
3d73ddf3050c562588f8e6fa6b3e018b6ae3d663 | 494 | hpp | C++ | DesignPattern/Creator/Factory/FactoryBuilder.hpp | ludaye123/DesignPatterns | aec36ca2c7475640f6e34153a9a6678a953124a7 | [
"MIT"
] | null | null | null | DesignPattern/Creator/Factory/FactoryBuilder.hpp | ludaye123/DesignPatterns | aec36ca2c7475640f6e34153a9a6678a953124a7 | [
"MIT"
] | null | null | null | DesignPattern/Creator/Factory/FactoryBuilder.hpp | ludaye123/DesignPatterns | aec36ca2c7475640f6e34153a9a6678a953124a7 | [
"MIT"
] | null | null | null | //
// FactoryBuilder.hpp
// DesignPatterns
//
// Created by Shen Lu on 2018/8/18.
// Copyright © 2018 Shen Lu. All rights reserved.
//
#ifndef FactoryBuilder_hpp
#define FactoryBuilder_hpp
#include <memory>
namespace ls {
typedef enum FactoryType {
Factory1 = 0,
Factory2 = 1
}FactoryType;
class Factory;
class FactoryBuilder {
public:
static std::shared_ptr<Factory> createFactory(FactoryType type);
};
}
#endif /* FactoryBuilder_hpp */
| 18.296296 | 72 | 0.663968 | ludaye123 |
3d74c2e8973c303968c154b02ea4a55a0df334c6 | 160 | cpp | C++ | network_viruses/randomFactory.cpp | uncerso/code-graveyard | df875fd070022faf84374e260bd77663760b1e4c | [
"Apache-2.0"
] | 1 | 2017-10-24T21:43:43.000Z | 2017-10-24T21:43:43.000Z | network_viruses/randomFactory.cpp | uncerso/code-graveyard | df875fd070022faf84374e260bd77663760b1e4c | [
"Apache-2.0"
] | 3 | 2017-12-02T08:15:29.000Z | 2018-06-05T19:35:56.000Z | network_viruses/randomFactory.cpp | uncerso/code-graveyard | df875fd070022faf84374e260bd77663760b1e4c | [
"Apache-2.0"
] | null | null | null | #include "randomFactory.hpp"
RandomFactory::RandomFactory()
: gen_((std::random_device())())
{}
unsigned int RandomFactory::operator()() {
return gen_();
}
| 16 | 42 | 0.69375 | uncerso |
3d74fd41ee998d04b737d0e3cc6ccb61e8cdff43 | 4,051 | cpp | C++ | CSL/Sources/Window.cpp | eriser/CSL | 6f4646369f0c90ea90e2c113374044818ab37ded | [
"BSD-4-Clause-UC"
] | 32 | 2020-04-17T22:48:53.000Z | 2021-06-15T13:13:28.000Z | CSL/Sources/Window.cpp | eriser/CSL | 6f4646369f0c90ea90e2c113374044818ab37ded | [
"BSD-4-Clause-UC"
] | null | null | null | CSL/Sources/Window.cpp | eriser/CSL | 6f4646369f0c90ea90e2c113374044818ab37ded | [
"BSD-4-Clause-UC"
] | 2 | 2020-06-05T15:51:31.000Z | 2021-08-31T15:09:26.000Z | //
// Window.cpp -- implementation of the various function window classes
// See the copyright notice and acknowledgment of authors in the file COPYRIGHT
//
#include "Window.h"
#include <math.h>
using namespace csl;
Window::Window() : UnitGenerator(), mGain(1) {
this->setSize(CGestalt::blockSize());
}
// Gain is optional and defaults to 1 when not specified.
Window::Window(unsigned windowSize, float gain) : UnitGenerator(), mGain(gain) {
this->setSize(windowSize);
}
Window::~Window() {
mWindowBuffer.freeBuffers();
}
void Window::setGain(float gain) {
mGain = gain;
fillWindow(); // Re-caluclate window using new gain value.
}
void Window::setSize(unsigned windowSize) {
mWindowBufferPos = 0;
mWindowSize = windowSize;
// If previously allocated, free me first.
mWindowBuffer.freeBuffers();
mWindowBuffer.setSize(1, mWindowSize); // Allocate memory to store the window.
mWindowBuffer.allocateBuffers();
fillWindow(); // Fill the buffer with the window data.
}
void Window::nextBuffer(Buffer &outputBuffer, unsigned outBufNum) throw (CException) {
/// get everything into registers
unsigned numFrames = outputBuffer.mNumFrames;
sample* outputBufferPtr = outputBuffer.buffer(outBufNum);
sample* windowBufferPtr = mWindowBuffer.buffer(0);
unsigned windowBufferPos = mWindowBufferPos;
unsigned windowBufferSize = mWindowSize;
#ifdef CSL_DEBUG
logMsg("Window::nextBuffer");
#endif
for (unsigned i = 0; i < numFrames; i++) {
if (windowBufferPos > windowBufferSize)
windowBufferPos = 0;
*outputBufferPtr++ = windowBufferPtr[windowBufferPos++];
}
mWindowBufferPos = windowBufferPos;
}
void Window::fillWindow() {
sample* windowBufferPtr = mWindowBuffer.buffer(0);
// create the window -- I make a Hamming window, subclasses may override
for (unsigned i = 0; i < mWindowSize; i++ )
*windowBufferPtr++ = (0.54 - 0.46*cos(CSL_TWOPI*i/(mWindowSize - 1) ));
}
void RectangularWindow::fillWindow() {
sample* windowBufferPtr = mWindowBuffer.buffer(0);
for (unsigned i = 0; i < mWindowSize; i++ ) // create the window
*windowBufferPtr++ = mGain;
}
void TriangularWindow::fillWindow() {
sample* windowBufferPtr = mWindowBuffer.buffer(0);
float accum = 0.0f;
unsigned winHalf = mWindowSize / 2;
float step = 1.0f / ((float) winHalf);
for (unsigned i = 0; i < winHalf; i++ ) { // create the rising half
*windowBufferPtr++ = accum;
accum += step;
}
for (unsigned i = winHalf; i < mWindowSize; i++ ) { // create the falling half
*windowBufferPtr++ = accum;
accum -= step;
}
}
void HammingWindow::fillWindow() {
sample* windowBufferPtr = mWindowBuffer.buffer(0);
sample increment = CSL_TWOPI/(mWindowSize - 1);
for (unsigned i = 0; i < mWindowSize; i++ )
*windowBufferPtr++ = (0.54 - 0.46*cos(i * increment));
}
void HannWindow::fillWindow() {
sample* windowBufferPtr = mWindowBuffer.buffer(0);
sample increment = CSL_TWOPI/(mWindowSize - 1);
for (unsigned i = 0; i < mWindowSize; i++ )
*windowBufferPtr++ = 0.5 * (1 - cos(i * increment)) * mGain;
}
void BlackmanWindow::fillWindow() {
sample* windowBufferPtr = mWindowBuffer.buffer(0);
sample increment = CSL_TWOPI/(mWindowSize - 1);
for (unsigned i = 0; i < mWindowSize; i++ )
*windowBufferPtr++ = (0.42 - 0.5 * cos(i * increment) + 0.08 * cos(2 * i * increment)) * mGain;
}
void BlackmanHarrisWindow::fillWindow() {
sample* windowBufferPtr = mWindowBuffer.buffer(0);
sample increment = CSL_TWOPI/(mWindowSize - 1);
for (unsigned i = 0; i < mWindowSize; i++ )
*windowBufferPtr++ = (0.35875 - 0.48829 * cos(i * increment)
+ 0.14128 * cos(2 * i * increment)
- 0.01168 * cos(3 * i * increment)) * mGain;
}
void WelchWindow::fillWindow() {
sample* windowBufferPtr = mWindowBuffer.buffer(0);
sample increment = 2.f/(mWindowSize - 1);
sample phase = -1.f;
for (unsigned i = 0; i < mWindowSize; i++ ) { // create the window
*windowBufferPtr++ = (1.f - phase * phase) * mGain;
phase += increment;
}
}
void Window::dump() {
logMsg("Window of size: %d samples", mWindowSize);
}
| 30.458647 | 97 | 0.690941 | eriser |
3d75245a1fb3653d48c6e36de37d8fb2b6c951b8 | 14,691 | cpp | C++ | mlir/lib/Dialect/LLVMIR/IR/LLVMTypes.cpp | glyons-intel/llvm | 780bdd6047d53acceb5cc8e419314026fbe007ba | [
"Apache-2.0"
] | null | null | null | mlir/lib/Dialect/LLVMIR/IR/LLVMTypes.cpp | glyons-intel/llvm | 780bdd6047d53acceb5cc8e419314026fbe007ba | [
"Apache-2.0"
] | null | null | null | mlir/lib/Dialect/LLVMIR/IR/LLVMTypes.cpp | glyons-intel/llvm | 780bdd6047d53acceb5cc8e419314026fbe007ba | [
"Apache-2.0"
] | null | null | null | //===- LLVMTypes.cpp - MLIR LLVM Dialect types ----------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements the types for the LLVM dialect in MLIR. These MLIR types
// correspond to the LLVM IR type system.
//
//===----------------------------------------------------------------------===//
#include "TypeDetail.h"
#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
#include "mlir/Dialect/LLVMIR/LLVMTypes.h"
#include "mlir/IR/DialectImplementation.h"
#include "mlir/IR/TypeSupport.h"
#include "llvm/ADT/TypeSwitch.h"
#include "llvm/Support/TypeSize.h"
using namespace mlir;
using namespace mlir::LLVM;
//===----------------------------------------------------------------------===//
// LLVMType.
//===----------------------------------------------------------------------===//
bool LLVMType::classof(Type type) {
return llvm::isa<LLVMDialect>(type.getDialect());
}
LLVMDialect &LLVMType::getDialect() {
return static_cast<LLVMDialect &>(Type::getDialect());
}
//===----------------------------------------------------------------------===//
// Array type.
//===----------------------------------------------------------------------===//
bool LLVMArrayType::isValidElementType(LLVMType type) {
return !type.isa<LLVMVoidType, LLVMLabelType, LLVMMetadataType,
LLVMFunctionType, LLVMTokenType, LLVMScalableVectorType>();
}
LLVMArrayType LLVMArrayType::get(LLVMType elementType, unsigned numElements) {
assert(elementType && "expected non-null subtype");
return Base::get(elementType.getContext(), elementType, numElements);
}
LLVMArrayType LLVMArrayType::getChecked(Location loc, LLVMType elementType,
unsigned numElements) {
assert(elementType && "expected non-null subtype");
return Base::getChecked(loc, elementType, numElements);
}
LLVMType LLVMArrayType::getElementType() { return getImpl()->elementType; }
unsigned LLVMArrayType::getNumElements() { return getImpl()->numElements; }
LogicalResult
LLVMArrayType::verifyConstructionInvariants(Location loc, LLVMType elementType,
unsigned numElements) {
if (!isValidElementType(elementType))
return emitError(loc, "invalid array element type: ") << elementType;
return success();
}
//===----------------------------------------------------------------------===//
// Function type.
//===----------------------------------------------------------------------===//
bool LLVMFunctionType::isValidArgumentType(LLVMType type) {
return !type.isa<LLVMVoidType, LLVMFunctionType>();
}
bool LLVMFunctionType::isValidResultType(LLVMType type) {
return !type.isa<LLVMFunctionType, LLVMMetadataType, LLVMLabelType>();
}
LLVMFunctionType LLVMFunctionType::get(LLVMType result,
ArrayRef<LLVMType> arguments,
bool isVarArg) {
assert(result && "expected non-null result");
return Base::get(result.getContext(), result, arguments, isVarArg);
}
LLVMFunctionType LLVMFunctionType::getChecked(Location loc, LLVMType result,
ArrayRef<LLVMType> arguments,
bool isVarArg) {
assert(result && "expected non-null result");
return Base::getChecked(loc, result, arguments, isVarArg);
}
LLVMType LLVMFunctionType::getReturnType() {
return getImpl()->getReturnType();
}
unsigned LLVMFunctionType::getNumParams() {
return getImpl()->getArgumentTypes().size();
}
LLVMType LLVMFunctionType::getParamType(unsigned i) {
return getImpl()->getArgumentTypes()[i];
}
bool LLVMFunctionType::isVarArg() { return getImpl()->isVariadic(); }
ArrayRef<LLVMType> LLVMFunctionType::getParams() {
return getImpl()->getArgumentTypes();
}
LogicalResult LLVMFunctionType::verifyConstructionInvariants(
Location loc, LLVMType result, ArrayRef<LLVMType> arguments, bool) {
if (!isValidResultType(result))
return emitError(loc, "invalid function result type: ") << result;
for (LLVMType arg : arguments)
if (!isValidArgumentType(arg))
return emitError(loc, "invalid function argument type: ") << arg;
return success();
}
//===----------------------------------------------------------------------===//
// Integer type.
//===----------------------------------------------------------------------===//
LLVMIntegerType LLVMIntegerType::get(MLIRContext *ctx, unsigned bitwidth) {
return Base::get(ctx, bitwidth);
}
LLVMIntegerType LLVMIntegerType::getChecked(Location loc, unsigned bitwidth) {
return Base::getChecked(loc, bitwidth);
}
unsigned LLVMIntegerType::getBitWidth() { return getImpl()->bitwidth; }
LogicalResult LLVMIntegerType::verifyConstructionInvariants(Location loc,
unsigned bitwidth) {
constexpr int maxSupportedBitwidth = (1 << 24);
if (bitwidth >= maxSupportedBitwidth)
return emitError(loc, "integer type too wide");
return success();
}
//===----------------------------------------------------------------------===//
// Pointer type.
//===----------------------------------------------------------------------===//
bool LLVMPointerType::isValidElementType(LLVMType type) {
return !type.isa<LLVMVoidType, LLVMTokenType, LLVMMetadataType,
LLVMLabelType>();
}
LLVMPointerType LLVMPointerType::get(LLVMType pointee, unsigned addressSpace) {
assert(pointee && "expected non-null subtype");
return Base::get(pointee.getContext(), pointee, addressSpace);
}
LLVMPointerType LLVMPointerType::getChecked(Location loc, LLVMType pointee,
unsigned addressSpace) {
return Base::getChecked(loc, pointee, addressSpace);
}
LLVMType LLVMPointerType::getElementType() { return getImpl()->pointeeType; }
unsigned LLVMPointerType::getAddressSpace() { return getImpl()->addressSpace; }
LogicalResult LLVMPointerType::verifyConstructionInvariants(Location loc,
LLVMType pointee,
unsigned) {
if (!isValidElementType(pointee))
return emitError(loc, "invalid pointer element type: ") << pointee;
return success();
}
//===----------------------------------------------------------------------===//
// Struct type.
//===----------------------------------------------------------------------===//
bool LLVMStructType::isValidElementType(LLVMType type) {
return !type.isa<LLVMVoidType, LLVMLabelType, LLVMMetadataType,
LLVMFunctionType, LLVMTokenType, LLVMScalableVectorType>();
}
LLVMStructType LLVMStructType::getIdentified(MLIRContext *context,
StringRef name) {
return Base::get(context, name, /*opaque=*/false);
}
LLVMStructType LLVMStructType::getIdentifiedChecked(Location loc,
StringRef name) {
return Base::getChecked(loc, name, /*opaque=*/false);
}
LLVMStructType LLVMStructType::getNewIdentified(MLIRContext *context,
StringRef name,
ArrayRef<LLVMType> elements,
bool isPacked) {
std::string stringName = name.str();
unsigned counter = 0;
do {
auto type = LLVMStructType::getIdentified(context, stringName);
if (type.isInitialized() || failed(type.setBody(elements, isPacked))) {
counter += 1;
stringName = (Twine(name) + "." + std::to_string(counter)).str();
continue;
}
return type;
} while (true);
}
LLVMStructType LLVMStructType::getLiteral(MLIRContext *context,
ArrayRef<LLVMType> types,
bool isPacked) {
return Base::get(context, types, isPacked);
}
LLVMStructType LLVMStructType::getLiteralChecked(Location loc,
ArrayRef<LLVMType> types,
bool isPacked) {
return Base::getChecked(loc, types, isPacked);
}
LLVMStructType LLVMStructType::getOpaque(StringRef name, MLIRContext *context) {
return Base::get(context, name, /*opaque=*/true);
}
LLVMStructType LLVMStructType::getOpaqueChecked(Location loc, StringRef name) {
return Base::getChecked(loc, name, /*opaque=*/true);
}
LogicalResult LLVMStructType::setBody(ArrayRef<LLVMType> types, bool isPacked) {
assert(isIdentified() && "can only set bodies of identified structs");
assert(llvm::all_of(types, LLVMStructType::isValidElementType) &&
"expected valid body types");
return Base::mutate(types, isPacked);
}
bool LLVMStructType::isPacked() { return getImpl()->isPacked(); }
bool LLVMStructType::isIdentified() { return getImpl()->isIdentified(); }
bool LLVMStructType::isOpaque() {
return getImpl()->isIdentified() &&
(getImpl()->isOpaque() || !getImpl()->isInitialized());
}
bool LLVMStructType::isInitialized() { return getImpl()->isInitialized(); }
StringRef LLVMStructType::getName() { return getImpl()->getIdentifier(); }
ArrayRef<LLVMType> LLVMStructType::getBody() {
return isIdentified() ? getImpl()->getIdentifiedStructBody()
: getImpl()->getTypeList();
}
LogicalResult LLVMStructType::verifyConstructionInvariants(Location, StringRef,
bool) {
return success();
}
LogicalResult
LLVMStructType::verifyConstructionInvariants(Location loc,
ArrayRef<LLVMType> types, bool) {
for (LLVMType t : types)
if (!isValidElementType(t))
return emitError(loc, "invalid LLVM structure element type: ") << t;
return success();
}
//===----------------------------------------------------------------------===//
// Vector types.
//===----------------------------------------------------------------------===//
bool LLVMVectorType::isValidElementType(LLVMType type) {
return type.isa<LLVMIntegerType, LLVMPointerType>() ||
mlir::LLVM::isCompatibleFloatingPointType(type);
}
/// Support type casting functionality.
bool LLVMVectorType::classof(Type type) {
return type.isa<LLVMFixedVectorType, LLVMScalableVectorType>();
}
LLVMType LLVMVectorType::getElementType() {
// Both derived classes share the implementation type.
return static_cast<detail::LLVMTypeAndSizeStorage *>(impl)->elementType;
}
llvm::ElementCount LLVMVectorType::getElementCount() {
// Both derived classes share the implementation type.
return llvm::ElementCount::get(
static_cast<detail::LLVMTypeAndSizeStorage *>(impl)->numElements,
isa<LLVMScalableVectorType>());
}
/// Verifies that the type about to be constructed is well-formed.
LogicalResult
LLVMVectorType::verifyConstructionInvariants(Location loc, LLVMType elementType,
unsigned numElements) {
if (numElements == 0)
return emitError(loc, "the number of vector elements must be positive");
if (!isValidElementType(elementType))
return emitError(loc, "invalid vector element type");
return success();
}
LLVMFixedVectorType LLVMFixedVectorType::get(LLVMType elementType,
unsigned numElements) {
assert(elementType && "expected non-null subtype");
return Base::get(elementType.getContext(), elementType, numElements);
}
LLVMFixedVectorType LLVMFixedVectorType::getChecked(Location loc,
LLVMType elementType,
unsigned numElements) {
assert(elementType && "expected non-null subtype");
return Base::getChecked(loc, elementType, numElements);
}
unsigned LLVMFixedVectorType::getNumElements() {
return getImpl()->numElements;
}
LLVMScalableVectorType LLVMScalableVectorType::get(LLVMType elementType,
unsigned minNumElements) {
assert(elementType && "expected non-null subtype");
return Base::get(elementType.getContext(), elementType, minNumElements);
}
LLVMScalableVectorType
LLVMScalableVectorType::getChecked(Location loc, LLVMType elementType,
unsigned minNumElements) {
assert(elementType && "expected non-null subtype");
return Base::getChecked(loc, elementType, minNumElements);
}
unsigned LLVMScalableVectorType::getMinNumElements() {
return getImpl()->numElements;
}
//===----------------------------------------------------------------------===//
// Utility functions.
//===----------------------------------------------------------------------===//
llvm::TypeSize mlir::LLVM::getPrimitiveTypeSizeInBits(Type type) {
assert(isCompatibleType(type) &&
"expected a type compatible with the LLVM dialect");
return llvm::TypeSwitch<Type, llvm::TypeSize>(type)
.Case<LLVMHalfType, LLVMBFloatType>(
[](LLVMType) { return llvm::TypeSize::Fixed(16); })
.Case<LLVMFloatType>([](LLVMType) { return llvm::TypeSize::Fixed(32); })
.Case<LLVMDoubleType, LLVMX86MMXType>(
[](LLVMType) { return llvm::TypeSize::Fixed(64); })
.Case<LLVMIntegerType>([](LLVMIntegerType intTy) {
return llvm::TypeSize::Fixed(intTy.getBitWidth());
})
.Case<LLVMX86FP80Type>([](LLVMType) { return llvm::TypeSize::Fixed(80); })
.Case<LLVMPPCFP128Type, LLVMFP128Type>(
[](LLVMType) { return llvm::TypeSize::Fixed(128); })
.Case<LLVMVectorType>([](LLVMVectorType t) {
llvm::TypeSize elementSize =
getPrimitiveTypeSizeInBits(t.getElementType());
llvm::ElementCount elementCount = t.getElementCount();
assert(!elementSize.isScalable() &&
"vector type should have fixed-width elements");
return llvm::TypeSize(elementSize.getFixedSize() *
elementCount.getKnownMinValue(),
elementCount.isScalable());
})
.Default([](Type ty) {
assert((ty.isa<LLVMVoidType, LLVMLabelType, LLVMMetadataType,
LLVMTokenType, LLVMStructType, LLVMArrayType,
LLVMPointerType, LLVMFunctionType>()) &&
"unexpected missing support for primitive type");
return llvm::TypeSize::Fixed(0);
});
}
| 38.458115 | 80 | 0.593629 | glyons-intel |
3d7781676043ed75de57252e1516f6e469f00aba | 30,115 | cpp | C++ | android/android_9/hardware/google/av/codec2/vndk/util/C2InterfaceHelper.cpp | yakuizhao/intel-vaapi-driver | b2bb0383352694941826543a171b557efac2219b | [
"MIT"
] | null | null | null | android/android_9/hardware/google/av/codec2/vndk/util/C2InterfaceHelper.cpp | yakuizhao/intel-vaapi-driver | b2bb0383352694941826543a171b557efac2219b | [
"MIT"
] | null | null | null | android/android_9/hardware/google/av/codec2/vndk/util/C2InterfaceHelper.cpp | yakuizhao/intel-vaapi-driver | b2bb0383352694941826543a171b557efac2219b | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2018 The Android Open Source Project
*
* 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 <C2Debug.h>
#include <C2ParamInternal.h>
#include <util/C2InterfaceHelper.h>
#include <android-base/stringprintf.h>
using ::android::base::StringPrintf;
/* --------------------------------- ReflectorHelper --------------------------------- */
void C2ReflectorHelper::addStructDescriptors(
std::vector<C2StructDescriptor> &structs, _Tuple<> *) {
std::lock_guard<std::mutex> lock(_mMutex);
for (C2StructDescriptor &strukt : structs) {
// TODO: check if structure descriptions conflict with existing ones
addStructDescriptor(std::move(strukt));
}
}
std::unique_ptr<C2StructDescriptor>
C2ReflectorHelper::describe(C2Param::CoreIndex paramIndex) const {
std::lock_guard<std::mutex> lock(_mMutex);
auto it = _mStructs.find(paramIndex);
if (it == _mStructs.end()) {
return nullptr;
} else {
return std::make_unique<C2StructDescriptor>(it->second);
}
};
void C2ReflectorHelper::addStructDescriptor(C2StructDescriptor &&strukt) {
if (_mStructs.find(strukt.coreIndex()) != _mStructs.end()) {
// already added
// TODO: validate that descriptor matches stored descriptor
}
// validate that all struct fields are known to this reflector
for (const C2FieldDescriptor &fd : strukt) {
if (fd.type() & C2FieldDescriptor::STRUCT_FLAG) {
C2Param::CoreIndex coreIndex = fd.type() &~ C2FieldDescriptor::STRUCT_FLAG;
if (_mStructs.find(coreIndex) == _mStructs.end()) {
C2_LOG(INFO) << "missing struct descriptor #" << coreIndex << " for field "
<< fd.name() << " of struct #" << strukt.coreIndex();
}
}
}
_mStructs.emplace(strukt.coreIndex(), strukt);
}
/* ---------------------------- ParamHelper ---------------------------- */
class C2InterfaceHelper::ParamHelper::Impl {
public:
Impl(ParamRef param, C2StringLiteral name, C2StructDescriptor &&strukt)
: mParam(param), mName(name), _mStruct(strukt) { }
Impl(Impl&&) = default;
void addDownDependency(C2Param::Index index) {
mDownDependencies.push_back(index);
}
C2InterfaceHelper::ParamHelper::attrib_t& attrib() {
return mAttrib;
}
void build() {
// move dependencies into descriptor
mDescriptor = std::make_shared<C2ParamDescriptor>(
index(), (C2ParamDescriptor::attrib_t)mAttrib,
std::move(mName), std::move(mDependencies));
}
void createFieldsAndSupportedValues(const std::shared_ptr<C2ParamReflector> &reflector) {
for (const C2FieldUtils::Info &f :
C2FieldUtils::enumerateFields(*mDefaultValue, reflector)) {
if (!f.isArithmetic()) {
continue;
}
std::unique_ptr<C2FieldSupportedValues> fsvPointer;
// create a breakable structure
do {
C2FieldSupportedValues fsv;
switch (f.type()) {
case C2FieldDescriptor::INT32: fsv = C2SupportedRange<int32_t>::Any(); break;
case C2FieldDescriptor::UINT32: fsv = C2SupportedRange<uint32_t>::Any(); break;
case C2FieldDescriptor::INT64: fsv = C2SupportedRange<int64_t>::Any(); break;
case C2FieldDescriptor::UINT64: fsv = C2SupportedRange<uint64_t>::Any(); break;
case C2FieldDescriptor::FLOAT: fsv = C2SupportedRange<float>::Any(); break;
case C2FieldDescriptor::BLOB: fsv = C2SupportedRange<uint8_t>::Any(); break;
case C2FieldDescriptor::STRING: fsv = C2SupportedRange<char>::Any(); break;
default:
continue; // break out of do {} while
}
fsvPointer = std::make_unique<C2FieldSupportedValues>(fsv);
} while (false);
mFields.emplace_hint(
mFields.end(),
_C2FieldId(f.offset(), f.size()),
std::make_shared<FieldHelper>(
mParam, _C2FieldId(f.offset(), f.size()), std::move(fsvPointer)));
}
}
/**
* Finds a field descriptor.
*/
std::shared_ptr<FieldHelper> findField(size_t baseOffs, size_t baseSize) const {
auto it = mFields.find(_C2FieldId(baseOffs, baseSize));
if (it == mFields.end()) {
return nullptr;
}
return it->second;
}
const std::vector<ParamRef> getDependenciesAsRefs() const {
return mDependenciesAsRefs;
}
std::shared_ptr<const C2ParamDescriptor> getDescriptor() const {
return mDescriptor;
}
const std::vector<C2Param::Index> getDownDependencies() const {
return mDownDependencies;
}
C2Param::Index index() const {
if (!mDefaultValue) {
fprintf(stderr, "%s missing default value\n", mName.c_str());
}
return mDefaultValue->index();
}
C2String name() const {
return mName;
}
const ParamRef ref() const {
return mParam;
}
C2StructDescriptor retrieveStructDescriptor() {
return std::move(_mStruct);
}
void setDefaultValue(std::shared_ptr<C2Param> default_) {
mDefaultValue = default_;
}
void setDependencies(std::vector<C2Param::Index> indices, std::vector<ParamRef> refs) {
mDependencies = indices;
mDependenciesAsRefs = refs;
}
void setFields(std::vector<C2ParamFieldValues> &&fields) {
// do not allow adding fields multiple times, or to const values
if (!mFields.empty()) {
C2_LOG(FATAL) << "Trying to add fields to param " << mName << " multiple times";
} else if (mAttrib & attrib_t::IS_CONST) {
C2_LOG(FATAL) << "Trying to add fields to const param " << mName;
}
for (C2ParamFieldValues &pfv : fields) {
mFields.emplace_hint(
mFields.end(),
// _C2FieldId constructor
_C2ParamInspector::GetField(pfv.paramOrField),
// Field constructor
std::make_shared<FieldHelper>(mParam,
_C2ParamInspector::GetField(pfv.paramOrField),
std::move(pfv.values)));
}
}
void setGetter(std::function<std::shared_ptr<C2Param>(bool)> getter) {
mGetter = getter;
}
void setSetter(std::function<C2R(const C2Param *, bool, bool *, Factory &)> setter) {
mSetter = setter;
}
c2_status_t trySet(
const C2Param *value, bool mayBlock, bool *changed, Factory &f,
std::vector<std::unique_ptr<C2SettingResult>>* const failures) {
C2R result = mSetter(value, mayBlock, changed, f);
return result.retrieveFailures(failures);
}
c2_status_t validate(const std::shared_ptr<C2ParamReflector> &reflector) {
if (!mSetter && mFields.empty()) {
C2_LOG(WARNING) << "Param " << mName << " has no setter, making it const";
// dependencies are empty in this case
mAttrib |= attrib_t::IS_CONST;
} else if (!mSetter) {
C2_LOG(FATAL) << "Param " << mName << " has no setter";
}
if (mAttrib & attrib_t::IS_CONST) {
createFieldsAndSupportedValues(reflector);
} else {
// TODO: update default based on setter and verify that FSV covers the values
}
if (mFields.empty()) {
C2_LOG(FATAL) << "Param " << mName << " has no fields";
}
return C2_OK;
}
std::shared_ptr<C2Param> value() {
return mParam.get();
}
std::shared_ptr<const C2Param> value() const {
return mParam.get();
}
private:
typedef _C2ParamInspector::attrib_t attrib_t;
ParamRef mParam;
C2String mName;
C2StructDescriptor _mStruct;
std::shared_ptr<C2Param> mDefaultValue;
attrib_t mAttrib;
std::function<C2R(const C2Param *, bool, bool *, Factory &)> mSetter;
std::function<std::shared_ptr<C2Param>(bool)> mGetter;
std::vector<C2Param::Index> mDependencies;
std::vector<ParamRef> mDependenciesAsRefs;
std::vector<C2Param::Index> mDownDependencies; // TODO: this does not work for stream dependencies
std::map<_C2FieldId, std::shared_ptr<FieldHelper>> mFields;
std::shared_ptr<C2ParamDescriptor> mDescriptor;
};
C2InterfaceHelper::ParamHelper::ParamHelper(
ParamRef param, C2StringLiteral name, C2StructDescriptor &&strukt)
: mImpl(std::make_unique<C2InterfaceHelper::ParamHelper::Impl>(
param, name, std::move(strukt))) { }
C2InterfaceHelper::ParamHelper::ParamHelper(C2InterfaceHelper::ParamHelper &&) = default;
C2InterfaceHelper::ParamHelper::~ParamHelper() = default;
void C2InterfaceHelper::ParamHelper::addDownDependency(C2Param::Index index) {
return mImpl->addDownDependency(index);
}
C2InterfaceHelper::ParamHelper::attrib_t& C2InterfaceHelper::ParamHelper::attrib() {
return mImpl->attrib();
}
std::shared_ptr<C2InterfaceHelper::ParamHelper> C2InterfaceHelper::ParamHelper::build() {
mImpl->build();
return std::make_shared<C2InterfaceHelper::ParamHelper>(std::move(*this));
}
std::shared_ptr<C2InterfaceHelper::FieldHelper>
C2InterfaceHelper::ParamHelper::findField(size_t baseOffs, size_t baseSize) const {
return mImpl->findField(baseOffs, baseSize);
}
const std::vector<C2InterfaceHelper::ParamRef>
C2InterfaceHelper::ParamHelper::getDependenciesAsRefs() const {
return mImpl->getDependenciesAsRefs();
}
std::shared_ptr<const C2ParamDescriptor>
C2InterfaceHelper::ParamHelper::getDescriptor() const {
return mImpl->getDescriptor();
}
const std::vector<C2Param::Index> C2InterfaceHelper::ParamHelper::getDownDependencies() const {
return mImpl->getDownDependencies();
}
C2Param::Index C2InterfaceHelper::ParamHelper::index() const {
return mImpl->index();
}
C2String C2InterfaceHelper::ParamHelper::name() const {
return mImpl->name();
}
const C2InterfaceHelper::ParamRef C2InterfaceHelper::ParamHelper::ref() const {
return mImpl->ref();
}
C2StructDescriptor C2InterfaceHelper::ParamHelper::retrieveStructDescriptor() {
return mImpl->retrieveStructDescriptor();
}
void C2InterfaceHelper::ParamHelper::setDefaultValue(std::shared_ptr<C2Param> default_) {
mImpl->setDefaultValue(default_);
}
void C2InterfaceHelper::ParamHelper::setDependencies(
std::vector<C2Param::Index> indices, std::vector<ParamRef> refs) {
mImpl->setDependencies(indices, refs);
}
void C2InterfaceHelper::ParamHelper::setFields(std::vector<C2ParamFieldValues> &&fields) {
return mImpl->setFields(std::move(fields));
}
void C2InterfaceHelper::ParamHelper::setGetter(
std::function<std::shared_ptr<C2Param>(bool)> getter) {
mImpl->setGetter(getter);
}
void C2InterfaceHelper::ParamHelper::setSetter(
std::function<C2R(const C2Param *, bool, bool *, Factory &)> setter) {
mImpl->setSetter(setter);
}
c2_status_t C2InterfaceHelper::ParamHelper::trySet(
const C2Param *value, bool mayBlock, bool *changed, Factory &f,
std::vector<std::unique_ptr<C2SettingResult>>* const failures) {
return mImpl->trySet(value, mayBlock, changed, f, failures);
}
c2_status_t C2InterfaceHelper::ParamHelper::validate(
const std::shared_ptr<C2ParamReflector> &reflector) {
return mImpl->validate(reflector);
}
std::shared_ptr<C2Param> C2InterfaceHelper::ParamHelper::value() {
return mImpl->value();
}
std::shared_ptr<const C2Param> C2InterfaceHelper::ParamHelper::value() const {
return mImpl->value();
}
/* ---------------------------- FieldHelper ---------------------------- */
C2ParamField C2InterfaceHelper::FieldHelper::makeParamField(C2Param::Index index) const {
return _C2ParamInspector::CreateParamField(index, mFieldId);
}
C2InterfaceHelper::FieldHelper::FieldHelper(const ParamRef ¶m, const _C2FieldId &field,
std::unique_ptr<C2FieldSupportedValues> &&values)
: mParam(param),
mFieldId(field),
mPossible(std::move(values)) {
C2_LOG(VERBOSE) << "Creating field helper " << field << " "
<< C2FieldSupportedValuesHelper<uint32_t>(*mPossible);
}
void C2InterfaceHelper::FieldHelper::setSupportedValues(
std::unique_ptr<C2FieldSupportedValues> &&values) {
mSupported = std::move(values);
}
const C2FieldSupportedValues *C2InterfaceHelper::FieldHelper::getSupportedValues() const {
return (mSupported ? mSupported : mPossible).get();
}
const C2FieldSupportedValues *C2InterfaceHelper::FieldHelper::getPossibleValues() const {
return mPossible.get();
}
/* ---------------------------- Field ---------------------------- */
/**
* Wrapper around field-supported-values builder that gets stored in the
* field helper when the builder goes out of scope.
*/
template<typename T>
struct SupportedValuesBuilder : C2ParamFieldValuesBuilder<T> {
SupportedValuesBuilder(
C2ParamField &field, std::shared_ptr<C2InterfaceHelper::FieldHelper> helper)
: C2ParamFieldValuesBuilder<T>(field), _mHelper(helper), _mField(field) {
}
/**
* Save builder values on destruction.
*/
virtual ~SupportedValuesBuilder() override {
_mHelper->setSupportedValues(std::move(C2ParamFieldValues(*this).values));
}
private:
std::shared_ptr<C2InterfaceHelper::FieldHelper> _mHelper;
C2ParamField _mField;
};
template<typename T>
C2ParamFieldValuesBuilder<T> C2InterfaceHelper::Field<T>::shouldBe() const {
return C2ParamFieldValuesBuilder<T>(_mField);
}
template<typename T>
C2ParamFieldValuesBuilder<T> C2InterfaceHelper::Field<T>::mustBe() {
return SupportedValuesBuilder<T>(_mField, _mHelper);
}
/*
template<typename T> C2SettingResultsBuilder C2InterfaceHelper::Field<T>::validatePossible(T &value)
const {
/// TODO
return C2SettingResultsBuilder::Ok();
}
*/
template<typename T>
C2InterfaceHelper::Field<T>::Field(std::shared_ptr<FieldHelper> helper, C2Param::Index index)
: _mHelper(helper), _mField(helper->makeParamField(index)) { }
template struct C2InterfaceHelper::Field<uint8_t>;
template struct C2InterfaceHelper::Field<char>;
template struct C2InterfaceHelper::Field<int32_t>;
template struct C2InterfaceHelper::Field<uint32_t>;
//template struct C2InterfaceHelper::Field<c2_cntr32_t>;
template struct C2InterfaceHelper::Field<int64_t>;
template struct C2InterfaceHelper::Field<uint64_t>;
//template struct C2InterfaceHelper::Field<c2_cntr64_t>;
template struct C2InterfaceHelper::Field<float>;
/* --------------------------------- Factory --------------------------------- */
struct C2InterfaceHelper::FactoryImpl : public C2InterfaceHelper::Factory {
virtual std::shared_ptr<C2ParamReflector> getReflector() const override {
return _mReflector;
}
virtual std::shared_ptr<ParamHelper>
getParamHelper(const ParamRef ¶m) const override {
return _mParams.find(param)->second;
}
public:
FactoryImpl(std::shared_ptr<C2ParamReflector> reflector)
: _mReflector(reflector) { }
virtual ~FactoryImpl() = default;
void addParam(std::shared_ptr<ParamHelper> param) {
_mParams.insert({ param->ref(), param });
_mIndexToHelper.insert({param->index(), param});
// add down-dependencies (and validate dependencies as a result)
size_t ix = 0;
for (const ParamRef &ref : param->getDependenciesAsRefs()) {
// dependencies must already be defined
if (!_mParams.count(ref)) {
C2_LOG(FATAL) << "Parameter " << param->name() << " has a dependency at index "
<< ix << " that is not yet defined";
}
_mParams.find(ref)->second->addDownDependency(param->index());
++ix;
}
_mDependencyIndex.emplace(param->index(), _mDependencyIndex.size());
}
std::shared_ptr<ParamHelper> getParam(C2Param::Index ix) const {
// TODO: handle streams separately
const auto it = _mIndexToHelper.find(ix);
if (it == _mIndexToHelper.end()) {
return nullptr;
}
return it->second;
}
/**
* TODO: this could return a copy using proper pointer cast.
*/
std::shared_ptr<C2Param> getParamValue(C2Param::Index ix) const {
std::shared_ptr<ParamHelper> helper = getParam(ix);
return helper ? helper->value() : nullptr;
}
c2_status_t querySupportedParams(
std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const {
for (const auto &it : _mParams) {
// TODO: change querySupportedParams signature?
params->push_back(
std::const_pointer_cast<C2ParamDescriptor>(it.second->getDescriptor()));
}
// TODO: handle errors
return C2_OK;
}
size_t getDependencyIndex(C2Param::Index ix) {
// in this version of the helper there is only a single stream so
// we can look up directly by index
auto it = _mDependencyIndex.find(ix);
return it == _mDependencyIndex.end() ? SIZE_MAX : it->second;
}
private:
std::map<ParamRef, std::shared_ptr<ParamHelper>> _mParams;
std::map<C2Param::Index, std::shared_ptr<ParamHelper>> _mIndexToHelper;
std::shared_ptr<C2ParamReflector> _mReflector;
std::map<C2Param::Index, size_t> _mDependencyIndex;
};
/* --------------------------------- Helper --------------------------------- */
namespace {
static std::string asString(C2Param *p) {
char addr[20];
sprintf(addr, "%p:[", p);
std::string v = addr;
for (size_t i = 0; i < p->size(); ++i) {
char d[4];
sprintf(d, " %02x", *(((uint8_t *)p) + i));
v += d + (i == 0);
}
return v + "]";
}
}
C2InterfaceHelper::C2InterfaceHelper(std::shared_ptr<C2ReflectorHelper> reflector)
: mReflector(reflector),
_mFactory(std::make_shared<FactoryImpl>(reflector)) { }
size_t C2InterfaceHelper::GetBaseOffset(const std::shared_ptr<C2ParamReflector> &reflector,
C2Param::CoreIndex index, size_t offset) {
std::unique_ptr<C2StructDescriptor> param = reflector->describe(index);
if (param == nullptr) {
return ~(size_t)0; // param structure not described
}
for (const C2FieldDescriptor &field : *param) {
size_t fieldOffset = _C2ParamInspector::GetOffset(field);
size_t fieldSize = _C2ParamInspector::GetSize(field);
size_t fieldExtent = field.extent();
if (offset < fieldOffset) {
return ~(size_t)0; // not found
}
if (offset == fieldOffset) {
// exact match
return offset;
}
if (field.extent() == 0 || offset < fieldOffset + fieldSize * fieldExtent) {
// reduce to first element in case of array
offset = fieldOffset + (offset - fieldOffset) % fieldSize;
if (field.type() >= C2FieldDescriptor::STRUCT_FLAG) {
// this offset is within a field
offset = GetBaseOffset(
reflector, field.type() & ~C2FieldDescriptor::STRUCT_FLAG,
offset - fieldOffset);
return ~offset ? fieldOffset + offset : offset;
}
}
}
return ~(size_t)0; // not found
}
void C2InterfaceHelper::addParameter(std::shared_ptr<ParamHelper> param) {
mReflector->addStructDescriptor(param->retrieveStructDescriptor());
c2_status_t err = param->validate(mReflector);
if (err != C2_CORRUPTED) {
_mFactory->addParam(param);
}
}
c2_status_t C2InterfaceHelper::config(
const std::vector<C2Param*> ¶ms, c2_blocking_t mayBlock,
std::vector<std::unique_ptr<C2SettingResult>>* const failures, bool updateParams,
std::vector<std::shared_ptr<C2Param>> *changes __unused /* TODO */) {
bool paramWasInvalid = false; // TODO is this the same as bad value?
bool paramNotFound = false;
bool paramBadValue = false;
bool paramNoMemory = false;
bool paramBlocking = false;
bool paramTimedOut = false;
bool paramCorrupted = false;
// dependencies
// down dependencies are marked dirty, but params set are not immediately
// marked dirty (unless they become down dependency) so that we can
// avoid setting them if they did not change
// TODO: there could be multiple indices for the same dependency index
// { depIx, paramIx } may be a suitable key
std::map<size_t, std::pair<C2Param::Index, bool>> dependencies;
// we cannot determine the last valid parameter, so add an extra
// loop iteration after the last parameter
for (size_t p_ix = 0; p_ix <= params.size(); ++p_ix) {
C2Param *p = nullptr;
C2Param::Index paramIx = 0u;
size_t paramDepIx = SIZE_MAX;
bool last = p_ix == params.size();
if (!last) {
p = params[p_ix];
if (!*p) {
paramWasInvalid = true;
p->invalidate();
continue;
}
paramIx = p->index();
paramDepIx = getDependencyIndex(paramIx);
if (paramDepIx == SIZE_MAX) {
// unsupported parameter
paramNotFound = true;
continue;
}
//
// first insert - mark not dirty
// it may have been marked dirty by a dependency update
// this does not overrwrite(!)
(void)dependencies.insert({ paramDepIx, { paramIx, false /* dirty */ }});
auto it = dependencies.find(paramDepIx);
C2_LOG(VERBOSE) << "marking dependency for setting at #" << paramDepIx << ": "
<< it->second.first << ", update "
<< (it->second.second ? "always (dirty)" : "only if changed");
} else {
// process any remaining dependencies
if (dependencies.empty()) {
continue;
}
C2_LOG(VERBOSE) << "handling dirty down dependencies after last setting";
}
// process any dirtied down-dependencies until the next param
while (dependencies.size() && dependencies.begin()->first <= paramDepIx) {
auto min = dependencies.begin();
C2Param::Index ix = min->second.first;
bool dirty = min->second.second;
dependencies.erase(min);
std::shared_ptr<ParamHelper> param = _mFactory->getParam(ix);
C2_LOG(VERBOSE) << "old value " << asString(param->value().get());
if (!last) {
C2_LOG(VERBOSE) << "new value " << asString(p);
}
if (!last && !dirty && ix == paramIx && *param->value() == *p) {
// no change in value - and dependencies were not updated
// no need to update
C2_LOG(VERBOSE) << "ignoring setting unchanged param " << ix;
continue;
}
// apply setting
bool changed = false;
C2_LOG(VERBOSE) << "setting param " << ix;
std::shared_ptr<C2Param> oldValue = param->value();
c2_status_t res = param->trySet(
(!last && paramIx == ix) ? p : param->value().get(), mayBlock,
&changed, *_mFactory, failures);
std::shared_ptr<C2Param> newValue = param->value();
C2_CHECK_EQ(oldValue == newValue, *oldValue == *newValue);
switch (res) {
case C2_OK: break;
case C2_BAD_VALUE: paramBadValue = true; break;
case C2_NO_MEMORY: paramNoMemory = true; break;
case C2_TIMED_OUT: paramTimedOut = true; break;
case C2_BLOCKING: paramBlocking = true; break;
case C2_CORRUPTED: paramCorrupted = true; break;
default: ;// TODO fatal
}
// copy back result for configured values (or invalidate if it does not fit or match)
if (updateParams && !last && paramIx == ix) {
if (!p->updateFrom(*param->value())) {
p->invalidate();
}
}
// compare ptrs as params are copy on write
if (changed) {
C2_LOG(VERBOSE) << "param " << ix << " value changed";
// value changed update down-dependencies and mark them dirty
for (const C2Param::Index ix : param->getDownDependencies()) {
C2_LOG(VERBOSE) << 1;
auto insert_res = dependencies.insert(
{ getDependencyIndex(ix), { ix, true /* dirty */ }});
if (!insert_res.second) {
(*insert_res.first).second.second = true; // mark dirty
}
auto it = dependencies.find(getDependencyIndex(ix));
C2_CHECK(it->second.second);
C2_LOG(VERBOSE) << "marking down dependencies to update at #"
<< getDependencyIndex(ix) << ": " << it->second.first;
}
}
}
}
return (paramCorrupted ? C2_CORRUPTED :
paramBlocking ? C2_BLOCKING :
paramTimedOut ? C2_TIMED_OUT :
paramNoMemory ? C2_NO_MEMORY :
(paramBadValue || paramWasInvalid) ? C2_BAD_VALUE :
paramNotFound ? C2_BAD_INDEX : C2_OK);
}
size_t C2InterfaceHelper::getDependencyIndex(C2Param::Index ix) const {
return _mFactory->getDependencyIndex(ix);
}
c2_status_t C2InterfaceHelper::query(
const std::vector<C2Param*> &stackParams,
const std::vector<C2Param::Index> &heapParamIndices,
c2_blocking_t mayBlock __unused /* TODO */,
std::vector<std::unique_ptr<C2Param>>* const heapParams) const {
bool paramWasInvalid = false;
bool paramNotFound = false;
bool paramDidNotFit = false;
bool paramNoMemory = false;
for (C2Param* const p : stackParams) {
if (!*p) {
paramWasInvalid = true;
p->invalidate();
} else {
std::shared_ptr<C2Param> value = _mFactory->getParamValue(p->index());
if (!value) {
paramNotFound = true;
p->invalidate();
} else if (!p->updateFrom(*value)) {
paramDidNotFit = true;
p->invalidate();
}
}
}
for (const C2Param::Index ix : heapParamIndices) {
std::shared_ptr<C2Param> value = _mFactory->getParamValue(ix);
if (value) {
std::unique_ptr<C2Param> p = C2Param::Copy(*value);
if (p != nullptr) {
heapParams->push_back(std::move(p));
} else {
paramNoMemory = true;
}
} else {
paramNotFound = true;
}
}
return paramNoMemory ? C2_NO_MEMORY :
paramNotFound ? C2_BAD_INDEX :
// the following errors are not marked in the return value
paramDidNotFit ? C2_OK :
paramWasInvalid ? C2_OK : C2_OK;
}
c2_status_t C2InterfaceHelper::querySupportedParams(
std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const {
return _mFactory->querySupportedParams(params);
}
c2_status_t C2InterfaceHelper::querySupportedValues(
std::vector<C2FieldSupportedValuesQuery> &fields, c2_blocking_t mayBlock __unused) const {
for (C2FieldSupportedValuesQuery &query : fields) {
C2_LOG(VERBOSE) << "querying field " << query.field();
C2Param::Index ix = _C2ParamInspector::GetIndex(query.field());
std::shared_ptr<ParamHelper> param = _mFactory->getParam(ix);
if (!param) {
C2_LOG(VERBOSE) << "bad param";
query.status = C2_BAD_INDEX;
continue;
}
size_t offs = GetBaseOffset(
mReflector, ix,
_C2ParamInspector::GetOffset(query.field()) - sizeof(C2Param));
if (~offs == 0) {
C2_LOG(VERBOSE) << "field could not be found";
query.status = C2_NOT_FOUND;
continue;
}
offs += sizeof(C2Param);
C2_LOG(VERBOSE) << "field resolved to "
<< StringPrintf("@%02zx+%02x", offs, _C2ParamInspector::GetSize(query.field()));
std::shared_ptr<FieldHelper> field =
param->findField(offs, _C2ParamInspector::GetSize(query.field()));
if (!field) {
C2_LOG(VERBOSE) << "bad field";
query.status = C2_NOT_FOUND;
continue;
}
const C2FieldSupportedValues *values = nullptr;
switch (query.type()) {
case C2FieldSupportedValuesQuery::CURRENT:
values = field->getSupportedValues();
break;
case C2FieldSupportedValuesQuery::POSSIBLE:
values = field->getPossibleValues();
break;
default:
C2_LOG(VERBOSE) << "bad query type: " << query.type();
query.status = C2_BAD_VALUE;
}
if (values) {
query.values = *values;
query.status = C2_OK;
} else {
C2_LOG(DEBUG) << "no values published by component";
query.status = C2_CORRUPTED;
}
}
return C2_OK;
}
| 36.370773 | 102 | 0.609397 | yakuizhao |
3d7b5860f741021f8c568dc4c3ff16817ddff922 | 349 | cpp | C++ | TAO/orbsvcs/tests/Bug_2287_Regression/Hello.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 36 | 2015-01-10T07:27:33.000Z | 2022-03-07T03:32:08.000Z | TAO/orbsvcs/tests/Bug_2287_Regression/Hello.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 2 | 2018-08-13T07:30:51.000Z | 2019-02-25T03:04:31.000Z | TAO/orbsvcs/tests/Bug_2287_Regression/Hello.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 38 | 2015-01-08T14:12:06.000Z | 2022-01-19T08:33:00.000Z | //
// $Id: Hello.cpp 91672 2010-09-08 18:44:58Z johnnyw $
//
#include "Hello.h"
Hello::Hello (CORBA::ORB_ptr orb, Test::Hello_ptr, CORBA::ULong)
: orb_ (CORBA::ORB::_duplicate (orb))
{
}
void
Hello::shutdown (void)
{
this->orb_->shutdown (0);
}
void
Hello::ping (void)
{
return;
}
void
Hello::throw_location_forward (void)
{
return;
}
| 11.633333 | 64 | 0.644699 | cflowe |
3d7c3af74d836e566f95a05cb69cb62848074c79 | 5,123 | hpp | C++ | include/strf/detail/printers_tuple.hpp | eyalroz/strf | 94cd5aef40530269da0727178017cb4a8992c5dc | [
"BSL-1.0"
] | null | null | null | include/strf/detail/printers_tuple.hpp | eyalroz/strf | 94cd5aef40530269da0727178017cb4a8992c5dc | [
"BSL-1.0"
] | 18 | 2019-12-13T15:52:26.000Z | 2020-01-17T14:51:33.000Z | include/strf/detail/printers_tuple.hpp | eyalroz/strf | 94cd5aef40530269da0727178017cb4a8992c5dc | [
"BSL-1.0"
] | 1 | 2021-12-23T05:53:22.000Z | 2021-12-23T05:53:22.000Z | #ifndef STRF_DETAIL_PRINTERS_TUPLE_HPP
#define STRF_DETAIL_PRINTERS_TUPLE_HPP
// 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)
#include <strf/detail/facets/encoding.hpp>
namespace strf {
namespace detail {
template <typename Arg>
using opt_val_or_cref = std::conditional_t
< std::is_array<Arg>::value, const Arg&, Arg > ;
template <std::size_t I, typename T>
struct indexed_obj
{
constexpr STRF_HD indexed_obj(const T& cp)
: obj(cp)
{
}
T obj;
};
struct simple_tuple_from_args {};
template <typename ISeq, typename ... T>
class simple_tuple_impl;
template <std::size_t ... I, typename ... T>
class simple_tuple_impl<std::index_sequence<I...>, T...>
: private indexed_obj<I, T> ...
{
template <std::size_t J, typename U>
static constexpr STRF_HD const indexed_obj<J, U>& _get(const indexed_obj<J, U>& r)
{
return r;
}
public:
static constexpr std::size_t size = sizeof...(T);
template <typename ... Args>
constexpr STRF_HD explicit simple_tuple_impl(simple_tuple_from_args, Args&& ... args)
: indexed_obj<I, T>(args)...
{
}
template <std::size_t J>
constexpr STRF_HD const auto& get() const
{
return _get<J>(*this).obj;
}
};
template <typename ... T>
class simple_tuple
: public strf::detail::simple_tuple_impl
< std::make_index_sequence<sizeof...(T)>, T...>
{
using strf::detail::simple_tuple_impl
< std::make_index_sequence<sizeof...(T)>, T...>
::simple_tuple_impl;
};
template <typename ... Args>
constexpr STRF_HD strf::detail::simple_tuple
< strf::detail::opt_val_or_cref<Args>... >
make_simple_tuple(const Args& ... args)
{
return strf::detail::simple_tuple
< strf::detail::opt_val_or_cref<Args>... >
{ strf::detail::simple_tuple_from_args{}, args... };
}
template <std::size_t J, typename ... T>
constexpr STRF_HD const auto& get(const simple_tuple<T...>& tp)
{
return tp.template get<J>();
}
template <std::size_t I, typename Printer>
struct indexed_printer
{
using char_type = typename Printer::char_type;
template <typename FPack, typename Preview, typename Arg>
STRF_HD indexed_printer( const FPack& fp
, Preview& preview
, const Arg& arg )
: printer(make_printer<char_type>(strf::rank<5>(), fp, preview, arg))
{
}
STRF_HD indexed_printer(const indexed_printer& other)
: printer(other.printer)
{
}
STRF_HD indexed_printer(indexed_printer&& other)
: printer(other.printer)
{
}
Printer printer;
};
template < typename CharT
, typename ISeq
, typename ... Printers >
class printers_tuple_impl;
template < typename CharT
, std::size_t ... I
, typename ... Printers >
class printers_tuple_impl<CharT, std::index_sequence<I...>, Printers...>
: private detail::indexed_printer<I, Printers> ...
{
template <std::size_t J, typename T>
static STRF_HD const indexed_printer<J, T>& _get(const indexed_printer<J, T>& r)
{
return r;
}
public:
using char_type = CharT;
static constexpr std::size_t size = sizeof...(Printers);
template < typename FPack, typename Preview, typename ... Args >
STRF_HD printers_tuple_impl
( const FPack& fp
, Preview& preview
, const strf::detail::simple_tuple<Args...>& args )
: indexed_printer<I, Printers>(fp, preview, args.template get<I>()) ...
{
}
template <std::size_t J>
STRF_HD const auto& get() const
{
return _get<J>(*this).printer;
}
};
template< typename CharT, std::size_t ... I, typename ... Printers >
STRF_HD void write( strf::basic_outbuf<CharT>& ob
, const strf::detail::printers_tuple_impl
< CharT, std::index_sequence<I...>, Printers... >& printers )
{
strf::detail::write_args<CharT>(ob, printers.template get<I>()...);
}
template < typename CharT, typename ... Printers >
using printers_tuple = printers_tuple_impl
< CharT
, std::make_index_sequence<sizeof...(Printers)>
, Printers... >;
template < typename CharT
, typename FPack
, typename Preview
, typename ISeq
, typename ... Args >
class printers_tuple_alias
{
template <typename Arg>
using _printer
= decltype(make_printer<CharT>( strf::rank<5>()
, std::declval<const FPack&>()
, std::declval<Preview&>()
, std::declval<const Arg&>()));
public:
using type = printers_tuple_impl<CharT, ISeq, _printer<Args>...>;
};
template < typename CharT, typename FPack, typename Preview, typename ... Args >
using printers_tuple_from_args
= typename printers_tuple_alias
< CharT, FPack, Preview, std::make_index_sequence<sizeof...(Args)>, Args... >
:: type;
} // namespace detail
} // namespace strf
#endif // STRF_DETAIL_PRINTERS_TUPLE_HPP
| 26.407216 | 89 | 0.632637 | eyalroz |
3d7e6be2b25dd13c2ccffb7ca01d3f4fe17584d1 | 13,225 | cc | C++ | DeepestScatter_Train/CppProtocols/DisneyDescriptor.pb.cc | marsermd/DeepestScatter | eeb490b5e6afd7f05049c8aca90a5c2e6f253726 | [
"MIT"
] | 13 | 2018-09-02T05:39:28.000Z | 2021-08-17T13:15:14.000Z | DeepestScatter_Train/CppProtocols/DisneyDescriptor.pb.cc | marsermd/DeepestScatter | eeb490b5e6afd7f05049c8aca90a5c2e6f253726 | [
"MIT"
] | 18 | 2020-01-28T22:39:23.000Z | 2022-03-11T23:33:13.000Z | DeepestScatter_Train/CppProtocols/DisneyDescriptor.pb.cc | marsermd/DeepestScatter | eeb490b5e6afd7f05049c8aca90a5c2e6f253726 | [
"MIT"
] | 3 | 2019-12-07T01:20:07.000Z | 2021-03-17T02:10:36.000Z | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: DisneyDescriptor.proto
#include "DisneyDescriptor.pb.h"
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// This is a temporary google only hack
#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
#include "third_party/protobuf/version.h"
#endif
// @@protoc_insertion_point(includes)
namespace Persistance {
class DisneyDescriptorDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<DisneyDescriptor>
_instance;
} _DisneyDescriptor_default_instance_;
} // namespace Persistance
namespace protobuf_DisneyDescriptor_2eproto {
static void InitDefaultsDisneyDescriptor() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::Persistance::_DisneyDescriptor_default_instance_;
new (ptr) ::Persistance::DisneyDescriptor();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::Persistance::DisneyDescriptor::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<0> scc_info_DisneyDescriptor =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsDisneyDescriptor}, {}};
void InitDefaults() {
::google::protobuf::internal::InitSCC(&scc_info_DisneyDescriptor.base);
}
::google::protobuf::Metadata file_level_metadata[1];
const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
~0u, // no _has_bits_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Persistance::DisneyDescriptor, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Persistance::DisneyDescriptor, grid_),
};
static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
{ 0, -1, sizeof(::Persistance::DisneyDescriptor)},
};
static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::Persistance::_DisneyDescriptor_default_instance_),
};
void protobuf_AssignDescriptors() {
AddDescriptors();
AssignDescriptors(
"DisneyDescriptor.proto", schemas, file_default_instances, TableStruct::offsets,
file_level_metadata, NULL, NULL);
}
void protobuf_AssignDescriptorsOnce() {
static ::google::protobuf::internal::once_flag once;
::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);
}
void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 1);
}
void AddDescriptorsImpl() {
InitDefaults();
static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n\026DisneyDescriptor.proto\022\013Persistance\032\014V"
"ector.proto\" \n\020DisneyDescriptor\022\014\n\004grid\030"
"\001 \001(\014b\006proto3"
};
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
descriptor, 93);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"DisneyDescriptor.proto", &protobuf_RegisterTypes);
::protobuf_Vector_2eproto::AddDescriptors();
}
void AddDescriptors() {
static ::google::protobuf::internal::once_flag once;
::google::protobuf::internal::call_once(once, AddDescriptorsImpl);
}
// Force AddDescriptors() to be called at dynamic initialization time.
struct StaticDescriptorInitializer {
StaticDescriptorInitializer() {
AddDescriptors();
}
} static_descriptor_initializer;
} // namespace protobuf_DisneyDescriptor_2eproto
namespace Persistance {
// ===================================================================
void DisneyDescriptor::InitAsDefaultInstance() {
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int DisneyDescriptor::kGridFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
DisneyDescriptor::DisneyDescriptor()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
::google::protobuf::internal::InitSCC(
&protobuf_DisneyDescriptor_2eproto::scc_info_DisneyDescriptor.base);
SharedCtor();
// @@protoc_insertion_point(constructor:Persistance.DisneyDescriptor)
}
DisneyDescriptor::DisneyDescriptor(const DisneyDescriptor& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
grid_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.grid().size() > 0) {
grid_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.grid_);
}
// @@protoc_insertion_point(copy_constructor:Persistance.DisneyDescriptor)
}
void DisneyDescriptor::SharedCtor() {
grid_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
DisneyDescriptor::~DisneyDescriptor() {
// @@protoc_insertion_point(destructor:Persistance.DisneyDescriptor)
SharedDtor();
}
void DisneyDescriptor::SharedDtor() {
grid_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void DisneyDescriptor::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* DisneyDescriptor::descriptor() {
::protobuf_DisneyDescriptor_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_DisneyDescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const DisneyDescriptor& DisneyDescriptor::default_instance() {
::google::protobuf::internal::InitSCC(&protobuf_DisneyDescriptor_2eproto::scc_info_DisneyDescriptor.base);
return *internal_default_instance();
}
void DisneyDescriptor::Clear() {
// @@protoc_insertion_point(message_clear_start:Persistance.DisneyDescriptor)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
grid_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
_internal_metadata_.Clear();
}
bool DisneyDescriptor::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:Persistance.DisneyDescriptor)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// bytes grid = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadBytes(
input, this->mutable_grid()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:Persistance.DisneyDescriptor)
return true;
failure:
// @@protoc_insertion_point(parse_failure:Persistance.DisneyDescriptor)
return false;
#undef DO_
}
void DisneyDescriptor::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:Persistance.DisneyDescriptor)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// bytes grid = 1;
if (this->grid().size() > 0) {
::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased(
1, this->grid(), output);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
}
// @@protoc_insertion_point(serialize_end:Persistance.DisneyDescriptor)
}
::google::protobuf::uint8* DisneyDescriptor::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:Persistance.DisneyDescriptor)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// bytes grid = 1;
if (this->grid().size() > 0) {
target =
::google::protobuf::internal::WireFormatLite::WriteBytesToArray(
1, this->grid(), target);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
}
// @@protoc_insertion_point(serialize_to_array_end:Persistance.DisneyDescriptor)
return target;
}
size_t DisneyDescriptor::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:Persistance.DisneyDescriptor)
size_t total_size = 0;
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
}
// bytes grid = 1;
if (this->grid().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::BytesSize(
this->grid());
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void DisneyDescriptor::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:Persistance.DisneyDescriptor)
GOOGLE_DCHECK_NE(&from, this);
const DisneyDescriptor* source =
::google::protobuf::internal::DynamicCastToGenerated<const DisneyDescriptor>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:Persistance.DisneyDescriptor)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:Persistance.DisneyDescriptor)
MergeFrom(*source);
}
}
void DisneyDescriptor::MergeFrom(const DisneyDescriptor& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:Persistance.DisneyDescriptor)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.grid().size() > 0) {
grid_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.grid_);
}
}
void DisneyDescriptor::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:Persistance.DisneyDescriptor)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void DisneyDescriptor::CopyFrom(const DisneyDescriptor& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:Persistance.DisneyDescriptor)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool DisneyDescriptor::IsInitialized() const {
return true;
}
void DisneyDescriptor::Swap(DisneyDescriptor* other) {
if (other == this) return;
InternalSwap(other);
}
void DisneyDescriptor::InternalSwap(DisneyDescriptor* other) {
using std::swap;
grid_.Swap(&other->grid_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
_internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata DisneyDescriptor::GetMetadata() const {
protobuf_DisneyDescriptor_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_DisneyDescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
}
// @@protoc_insertion_point(namespace_scope)
} // namespace Persistance
namespace google {
namespace protobuf {
template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::Persistance::DisneyDescriptor* Arena::CreateMaybeMessage< ::Persistance::DisneyDescriptor >(Arena* arena) {
return Arena::CreateInternal< ::Persistance::DisneyDescriptor >(arena);
}
} // namespace protobuf
} // namespace google
// @@protoc_insertion_point(global_scope)
| 37.571023 | 168 | 0.74828 | marsermd |
3d806e9c34580c43acc589461acae24f252ae99b | 1,175 | cpp | C++ | MonoNative.Tests/mscorlib/System/Reflection/mscorlib_System_Reflection_AssemblyVersionAttribute_Fixture.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | 7 | 2015-03-10T03:36:16.000Z | 2021-11-05T01:16:58.000Z | MonoNative.Tests/mscorlib/System/Reflection/mscorlib_System_Reflection_AssemblyVersionAttribute_Fixture.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | 1 | 2020-06-23T10:02:33.000Z | 2020-06-24T02:05:47.000Z | MonoNative.Tests/mscorlib/System/Reflection/mscorlib_System_Reflection_AssemblyVersionAttribute_Fixture.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | null | null | null | // Mono Native Fixture
// Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// Namespace: System.Reflection
// Name: AssemblyVersionAttribute
// C++ Typed Name: mscorlib::System::Reflection::AssemblyVersionAttribute
#include <gtest/gtest.h>
#include <mscorlib/System/Reflection/mscorlib_System_Reflection_AssemblyVersionAttribute.h>
#include <mscorlib/System/mscorlib_System_Type.h>
namespace mscorlib
{
namespace System
{
namespace Reflection
{
//Constructors Tests
//AssemblyVersionAttribute(mscorlib::System::String version)
TEST(mscorlib_System_Reflection_AssemblyVersionAttribute_Fixture,Constructor_1)
{
}
//Public Methods Tests
//Public Properties Tests
// Property Version
// Return Type: mscorlib::System::String
// Property Get Method
TEST(mscorlib_System_Reflection_AssemblyVersionAttribute_Fixture,get_Version_Test)
{
}
// Property TypeId
// Return Type: mscorlib::System::Object
// Property Get Method
TEST(mscorlib_System_Reflection_AssemblyVersionAttribute_Fixture,get_TypeId_Test)
{
}
}
}
}
| 20.614035 | 91 | 0.728511 | brunolauze |
3d8472edd22f2fd255f7b698bea9a011461a382b | 31,155 | cpp | C++ | src/aadcBase/src/jury/AADC_JuryModule_ConnectionLib/cJuryModule.cpp | AppliedAutonomyOffenburg/AADC_2015_A2O | 19a2ac67d743ad23e5a259ca70aed6b3d1f2e3ac | [
"BSD-4-Clause"
] | 1 | 2018-09-09T21:39:29.000Z | 2018-09-09T21:39:29.000Z | src/aadcBase/src/jury/AADC_JuryModule_ConnectionLib/cJuryModule.cpp | TeamAutonomousCarOffenburg/A2O_2015 | 19a2ac67d743ad23e5a259ca70aed6b3d1f2e3ac | [
"BSD-4-Clause"
] | null | null | null | src/aadcBase/src/jury/AADC_JuryModule_ConnectionLib/cJuryModule.cpp | TeamAutonomousCarOffenburg/A2O_2015 | 19a2ac67d743ad23e5a259ca70aed6b3d1f2e3ac | [
"BSD-4-Clause"
] | 1 | 2016-04-05T06:34:08.000Z | 2016-04-05T06:34:08.000Z | /**
Copyright (c)
Audi Autonomous Driving Cup. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. All advertising materials mentioning features or use of this software must display the following acknowledgement: This product includes software developed by the Audi AG and its contributors for Audi Autonomous Driving Cup.
4. Neither the name of Audi 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 AUDI AG AND CONTRIBUTORS AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL AUDI AG OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**********************************************************************
* $Author:: spiesra $ $Date:: 2015-05-13 08:29:07#$ $Rev:: 35003 $
**********************************************************************/
#include "stdafx.h"
#include "coder_description.h"
#include "cJuryModule.h"
#include "QFileDialog"
#include "QMessageBox"
#include "QDomDocument"
#include "QTimer"
cJuryConnectionThread::cJuryConnectionThread() : m_pJuryModule(NULL)
{
}
void cJuryConnectionThread::run()
{
if (m_pJuryModule)
{
// if jury module is set, call the connect/disconnect method
m_pJuryModule->ConnectDisconnectNetworkClients();
}
}
tResult cJuryConnectionThread::RegisterJuryModule(cJuryModule* pJuryModule)
{
m_pJuryModule = pJuryModule;
RETURN_NOERROR;
}
cJuryModule::cJuryModule(QWidget *parent) :
QWidget(parent),
m_i16LastDriverEntryId(-1),
m_pDataRemoteSystemData(NULL),
m_pDataSystemDataSender(NULL),
m_pLocalSystemSender(NULL),
m_pRemoteSystem(NULL),
m_pNetwork(NULL),
m_bConnected(false),
m_oLastReceiveTimestamp(QTime()),
m_pWidget(new Ui::cDisplayWidget),
m_strManeuverList("")
{
// setup the widget
m_pWidget->setupUi(this);
// initialize the Qt connections
Init();
// set the jury module pointer
m_oConnectionThread.RegisterJuryModule(this);
}
void cJuryModule::OnCloseWindows()
{
close();
}
cJuryModule::~cJuryModule()
{
// delete the widget
if (m_pWidget != NULL)
{
delete m_pWidget;
m_pWidget = NULL;
}
// cleanup any network conection
CleanUpNetwork();
}
tResult cJuryModule::Init()
{
// connect the widgets and methods
connect(m_pWidget->m_btnFileSelection, SIGNAL(released()), this, SLOT(OnManeuverListButton()));
connect(m_pWidget->m_btnFileSelectionDescr, SIGNAL(released()), this, SLOT(OnDescriptionFileButton()));
connect(m_pWidget->m_edtManeuverFile, SIGNAL(returnPressed()), this, SLOT(OnManeuverListSelected()));
connect(m_pWidget->m_edtManeuverFile, SIGNAL(editingFinished()), this, SLOT(OnManeuverListSelected()));
connect(m_pWidget->m_btnEmergencyStop, SIGNAL(released()), this, SLOT(OnEmergencyStop()));
connect(m_pWidget->m_btnStart, SIGNAL(released()), this, SLOT(OnStart()));
connect(m_pWidget->m_btnStop, SIGNAL(released()), this, SLOT(OnStop()));
connect(m_pWidget->m_btnRequest, SIGNAL(released()), this, SLOT(OnRequestReady()));
connect(m_pWidget->m_btnConnectDisconnect, SIGNAL(released()), this, SLOT(OnConnectDisconnect()));
connect(m_pWidget->m_btnManeuverlist, SIGNAL(released()), this, SLOT(SendManeuverList()));
connect(this, SIGNAL(SetDriverState(int, int)), this, SLOT(OnDriverState(int, int)));
connect(this, SIGNAL(SetLogText(QString)), this, SLOT(OnAppendText(QString)));
connect(this, SIGNAL(SetConnectionState()), this, SLOT(OnConnectionStateChange()));
connect(this, SIGNAL(SetControlState()), this, SLOT(OnControlState()));
connect(m_pWidget->m_comboSector, SIGNAL(currentIndexChanged(int)), this, SLOT(OnComboSectionBoxChanged(int)));
connect(m_pWidget->m_comboManeuver, SIGNAL(currentIndexChanged(int)), this, SLOT(OnComboActionBoxChanged(int)));
connect(m_pWidget->m_cbxLocalHost, SIGNAL(stateChanged(int)), this, SLOT(OnLocalhostCheckChanged(int)));
connect(m_pWidget->m_btnOpenTerminal, SIGNAL(released()), this, SLOT(OnOpenTerminalProcess()));
connect(&m_oTerminalProcess, SIGNAL(started()), this, SLOT(OnProcessStarted()));
connect(&m_oTerminalProcess, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(OnProcessFinished(int,QProcess::ExitStatus)));
connect(&m_oTerminalProcess, SIGNAL(error(QProcess::ProcessError)), this, SLOT(OnProcessError(QProcess::ProcessError)));
// set the connection and control state
SetConnectionState();
SetControlState();
RETURN_NOERROR;
}
void cJuryModule::OnConnectionStateChange()
{
if(m_pWidget)
{
// control the button text and background
if (m_bConnected)
{
m_pWidget->m_btnConnectDisconnect->setText("disconnect");
m_pWidget->m_btnConnectDisconnect->setStyleSheet("background:green");
}
else
{
m_pWidget->m_btnConnectDisconnect->setText("connect");
m_pWidget->m_btnConnectDisconnect->setStyleSheet("");
}
SetControlState();
}
}
void cJuryModule::OnControlState()
{
// control the emergency button and the maneuver control group
tBool bEnabled = false;
if (m_bConnected && !m_strManeuverList.empty())
{
bEnabled = true;
}
m_pWidget->grpManeuverCtrl->setEnabled(bEnabled);
m_pWidget->m_btnEmergencyStop->setEnabled(m_bConnected);
}
tResult cJuryModule::CleanUpNetwork()
{
// delete the network
m_pLocalSystemSender = NULL;
m_pRemoteSystem = NULL;
m_pDataSystemDataSender = NULL;
m_pDataRemoteSystemData = NULL;
if (m_pNetwork)
{
delete m_pNetwork;
m_pNetwork = NULL;
}
RETURN_NOERROR;
}
tResult cJuryModule::ConnectDisconnectNetworkClients()
{
if (m_pNetwork)
{
// network is present, so we have to disconnect
QString strText = QString("Disconnecting...");
SetLogText(strText);
m_bConnected = false;
SetConnectionState();
m_pNetwork->DestroySystem(m_pLocalSystemSender);
m_pNetwork->DestroySystem(m_pRemoteSystem);
CleanUpNetwork();
strText = QString("Disconnected");
SetLogText(strText);
RETURN_NOERROR;
}
// network is not present, connect
QString strText = QString("Trying to connect to ") + QString(GetIpAdress().c_str()) + QString(" ...");
SetLogText(strText);
// create new network
m_pNetwork = new cNetwork("");
cNetwork::SetLogLevel(cNetwork::eLOG_LVL_ERROR);
//Initialize the network
tResult nRes = m_pNetwork->Init();
if (ERR_NOERROR != nRes) //Never forget the error check
{
CleanUpNetwork();
return nRes;
}
const tInt nFlags = 0;
tString strIp = GetIpAdress();
//Create one local system which is part of the network
//this is to send data to the world !!
const tString strDataSendUrl("tcp://" + strIp + ":5000");
m_pLocalSystemSender = NULL; //Gets assigned while created
const tString strLocalSystemNameData("JuryModuleData"); //Name of the first system
nRes = m_pNetwork->CreateLocalSystem(&m_pLocalSystemSender,
strLocalSystemNameData,
strDataSendUrl,
nFlags);//if not given, default = 0
if (ERR_NOERROR != nRes)
{
CleanUpNetwork();
return nRes;
}
//the system can also have some data available
nRes = m_pLocalSystemSender->GetDataServer(&m_pDataSystemDataSender);
if (ERR_NOERROR != nRes)
{
CleanUpNetwork();
return nRes;
}
// check if there is a description file set, otherwise use the coded description
QString strDescriptionFile = m_pWidget->m_edtDescriptionFile->text();
tString strMyDDLDefinitionAsString;
if (!QFile::exists(strDescriptionFile))
{
SetLogText("No valid media description file set. Will use the internal description.");
strMyDDLDefinitionAsString = CONNLIB_JURY_MODULE_DDL_AS_STRING;
}
else
{
SetLogText(QString("Using media description file ") + strDescriptionFile);
strMyDDLDefinitionAsString = strDescriptionFile.toStdString();
}
nRes = m_pDataSystemDataSender->AddDDL(strMyDDLDefinitionAsString);
if (ERR_NOERROR != nRes)
{
SetLogText("Media description not valid. Please set a valid file.");
CleanUpNetwork();
return nRes;
}
// define the description of outgoing data
tDataDesc sDescEmergencyStopRaw;
sDescEmergencyStopRaw.strName = CONLIB_OUT_PORT_NAME_EMERGENCY_STOP;
sDescEmergencyStopRaw.strDescriptionComment = "The emergency stop struct in raw mode";
sDescEmergencyStopRaw.strType = "plainraw";
nRes = m_pDataSystemDataSender->PublishPlainData(CONLIB_STREAM_NAME_EMERGENCY_STOP, sDescEmergencyStopRaw);
if (ERR_NOERROR != nRes)
{
CleanUpNetwork();
return nRes;
}
tDataDesc sDescJuryStruct;
sDescJuryStruct.strName = CONLIB_OUT_PORT_NAME_JURY_STRUCT;
sDescJuryStruct.strDescriptionComment = "the jury data as struct";
sDescJuryStruct.strType = "plainraw";
nRes = m_pDataSystemDataSender->PublishPlainData(CONLIB_STREAM_NAME_JURY_STRUCT, sDescJuryStruct);
if (ERR_NOERROR != nRes)
{
CleanUpNetwork();
return nRes;
}
tDataDesc sDescManeuverList;
sDescManeuverList.strName = CONLIB_OUT_PORT_NAME_MANEUVER_LIST;
sDescManeuverList.strDescriptionComment = "the Manuverlist as string";
sDescManeuverList.strType = "plainraw";
nRes = m_pDataSystemDataSender->PublishPlainData(CONLIB_STREAM_NAME_MANEUVER_LIST, sDescManeuverList);
if (ERR_NOERROR != nRes)
{
CleanUpNetwork();
return nRes;
}
//this is to receive data from a specific sender!!
//Create one local system which is part of the network
const tString strDataUrl("tcp://" + strIp + ":5000");
m_pRemoteSystem = NULL; //Gets assigned while created
const tString strSystemNameData("ADTFData"); //Name of the first system
nRes = m_pNetwork->CreateRemoteSystem(&m_pRemoteSystem,
strSystemNameData,
strDataUrl,
nFlags);//if not given, default = 0
if (ERR_NOERROR != nRes)
{
CleanUpNetwork();
return nRes;
}
nRes = m_pRemoteSystem->GetDataServer(&m_pDataRemoteSystemData);
if (ERR_NOERROR != nRes)
{
CleanUpNetwork();
return nRes;
}
//this is only required if you subscribe to raw data, otherwise the DDL will be transmitted by the sender.
m_pDataRemoteSystemData->AddDDL(strMyDDLDefinitionAsString);
m_pDataRemoteSystemData->SubscribeForPlainDataRaw(CONLIB_IN_PORT_NAME_DRIVER_STRUCT, CONLIB_STREAM_NAME_DRIVER_STRUCT, this);
m_pDataRemoteSystemData->SubscribeForPlainDataRaw(CONLIB_IN_PORT_NAME_JURY_STRUCT_LOOPBACK, CONLIB_STREAM_NAME_JURY_STRUCT, this);
m_pDataRemoteSystemData->SubscribeForPlainDataRaw(CONLIB_IN_PORT_NAME_EMERGENCY_STOP_LOOPBACK, CONLIB_STREAM_NAME_EMERGENCY_STOP, this);
m_pDataRemoteSystemData->SubscribeForPlainDataRaw(CONLIB_IN_PORT_NAME_MANEUVER_LIST, CONLIB_STREAM_NAME_MANEUVER_LIST, this);
// set the connection state in ui
strText = QString("Connected to ") + QString(GetIpAdress().c_str());
SetLogText(strText);
m_bConnected = true;
SetConnectionState();
RETURN_NOERROR;
}
void cJuryModule::OnManeuverListButton()
{
// open file dialog to get the maneuver list file
QString strManeuverFile = QFileDialog::getOpenFileName(this, tr("Open Maneuver List"), m_strManeuverFile, tr("AADC Maneuver List (*.xml)"));
if(!strManeuverFile.isEmpty())
{
m_pWidget->m_edtManeuverFile->setText(strManeuverFile);
emit OnManeuverListSelected();
}
}
void cJuryModule::OnDescriptionFileButton()
{
// open a file dialog to get the description file
QString strDescriptionFile = QFileDialog::getOpenFileName(this, tr("Open media description file"), "", tr("ADTF media description file (*.description)"));
if(!strDescriptionFile.isEmpty())
{
m_pWidget->m_edtDescriptionFile->setText(strDescriptionFile);
}
}
tResult cJuryModule::OnOpenTerminalProcess()
{
// start the given terminal process (detached because otherwise no terminal window will be opened
if(m_oTerminalProcess.startDetached(m_pWidget->m_edtTerminalProgram->text() ))
{
OnProcessStarted();
}
else
{
OnProcessError(m_oTerminalProcess.error());
}
RETURN_NOERROR;
}
void cJuryModule::OnProcessStarted()
{
// set text in log
SetLogText("Terminal program started");
}
void cJuryModule::OnProcessFinished(int exitCode, QProcess::ExitStatus exitStatus)
{
// set text in log
SetLogText(QString("Process finished with ") + QString::number(exitCode) + QString("and state ") + QString(exitStatus));
}
void cJuryModule::OnProcessError(QProcess::ProcessError error)
{
// set text in log
SetLogText(QString("Process failed with error code ") + QString::number(error) + QString(": ") + m_oTerminalProcess.errorString());
}
void cJuryModule::OnManeuverListSelected()
{
// get the maneuver file from edit field
QString strManeuverFile = m_pWidget->m_edtManeuverFile->text();
if (!strManeuverFile.isEmpty())
{
// check if file exists
if (QFile::exists(strManeuverFile) && strManeuverFile.contains(".xml"))
{
// load the file
m_strManeuverFile = strManeuverFile;
LoadManeuverList();
}
else
{
// file not found, show message box
QMessageBox::critical(this, tr("File not found or valid"), tr("The given Maneuver List can not be found or is not valid."));
m_pWidget->m_edtManeuverFile->setFocus();
}
}
else
{
// do nothing
}
}
tResult cJuryModule::OnDataUpdate(const tString& strName, const tVoid* pData, const tSize& szSize)
{
// called from the connection lib on new data
// check data size
RETURN_IF_POINTER_NULL(pData);
if (szSize <= 0)
{
RETURN_ERROR(ERR_INVALID_ARG);
}
// check the name of the data
if (strName == CONLIB_IN_PORT_NAME_DRIVER_STRUCT)
{
// data from driver
const tDriverStruct* sDriverData = (const tDriverStruct*) pData;
//update the gui
emit SetDriverState(sDriverData->i8StateID, sDriverData->i16ManeuverEntry);
//update the timeline
if (m_i16LastDriverEntryId < sDriverData->i16ManeuverEntry || m_i16LastDriverEntryId == -1 || sDriverData->i8StateID == -1 || sDriverData->i8StateID == 2)
{
// set the first time manually
if (m_oLastReceiveTimestamp.isNull())
{
m_oLastReceiveTimestamp = QTime::currentTime();
m_i16LastDriverEntryId = sDriverData->i16ManeuverEntry;
}
// calc the time diff
tTimeStamp timeDiff = (m_oLastReceiveTimestamp.msecsTo(QTime::currentTime())); //time in milliseconds
QString Message;
switch (stateCar(sDriverData->i8StateID))
{
case stateCar_READY:
Message = "from " + QString::number(m_i16LastDriverEntryId) + " to " + QString::number(sDriverData->i16ManeuverEntry) + ": " + QString::number(timeDiff) + " msec: Ready";
break;
case stateCar_RUNNING:
Message = "from " + QString::number(m_i16LastDriverEntryId) + " to " + QString::number(sDriverData->i16ManeuverEntry) + ": " + QString::number(timeDiff) + " msec: OK";
break;
case stateCar_COMPLETE:
Message = "from " + QString::number(m_i16LastDriverEntryId) + " to " + QString::number(sDriverData->i16ManeuverEntry) + ": " + QString::number(timeDiff) + " msec: Complete";
break;
case stateCar_ERROR:
Message = "from " + QString::number(m_i16LastDriverEntryId) + " to " + QString::number(sDriverData->i16ManeuverEntry) + ": " + QString::number(timeDiff) + " msec: Error";
break;
case stateCar_STARTUP:
break;
}
// set the last time
m_oLastReceiveTimestamp = QTime::currentTime();
m_i16LastDriverEntryId = sDriverData->i16ManeuverEntry;
//update the ui
SetLogText(Message);
}
}
else if (strName == CONLIB_IN_PORT_NAME_JURY_STRUCT_LOOPBACK)
{
// data from jury loopback
const tJuryStruct* sJuryLoopbackData = (const tJuryStruct*) pData;
QString strText = QString("Loopback Jury: Received jury struct loopback with action ");
switch(juryActions(sJuryLoopbackData->i8ActionID))
{
case action_GETREADY:
strText += "GETREADY ";
break;
case action_START:
strText += "START ";
break;
case action_STOP:
strText += "STOP ";
break;
default:
strText += "UNKNOWN ";
break;
}
strText += QString(" and maneuver ") + QString::number(sJuryLoopbackData->i16ManeuverEntry);
// write text to log (just for checking the connection)
SetLogText(strText);
//QMetaObject::invokeMethod(this, "OnAppendText", Qt::AutoConnection, Q_ARG(QString, strText));
}
else if (strName == CONLIB_IN_PORT_NAME_EMERGENCY_STOP_LOOPBACK)
{
// data from emergency loopback
const tJuryEmergencyStop* sJuryLoopbackData = (const tJuryEmergencyStop*) pData;
QString strText = QString("Loopback Emergency: Received emergency loopback with ");
strText += (sJuryLoopbackData->bEmergencyStop == true) ? QString("true") : QString("false");
// write text to log (just for checking the connection)
SetLogText(strText);
//QMetaObject::invokeMethod(this, "OnAppendText", Qt::AutoConnection, Q_ARG(QString, strText));
}
else if (strName == CONLIB_IN_PORT_NAME_MANEUVER_LIST)
{
// data from maneuverlist loopback
const tInt32* i32DataSize = (const tInt32*) pData;
const tChar* pcString = (const tChar*) ((tChar*)pData + sizeof(tInt32));
tString strManeuver(pcString);
QString strText = QString("Loopback ManeuverList received");
// check the data content
if(*i32DataSize != (m_strManeuverList.size() + sizeof(char)))
{
strText += QString(" size does not match");
}
if(strManeuver != m_strManeuverList)
{
strText += QString(" content does not match");
}
strText += "!!!";
// write text to log (just for checking the connection)
SetLogText(strText);
//QMetaObject::invokeMethod(this, "OnAppendText", Qt::AutoConnection, Q_ARG(QString, strText));
}
RETURN_NOERROR;
}
tResult cJuryModule::OnPlainDataDescriptionUpdate(const tChar* strDataName, const tChar* strStructName, const tChar* strDDL)
{
// will be called, if we are using NON-RAW-Mode
// write text to log (just for checking the connection)
SetLogText(QString("Received description update for ") + QString(strDataName));
RETURN_NOERROR;
}
tResult cJuryModule::OnEmergencyStop()
{
// emergency stop button pressed
// send emergency stop 3 times
m_nEmergencyCounter = 3;
QTimer::singleShot(0, this, SLOT(SendEmergencyStop()));
RETURN_NOERROR;
}
tResult cJuryModule::OnRequestReady()
{
// request button pressed
// setup jury struct and send 3 times
m_i16ManeuverEntry = m_pWidget->m_comboManeuver->currentIndex();
m_actionID = action_GETREADY;
m_iJuryStructCounter = 3;
QTimer::singleShot(0, this, SLOT(SendJuryStruct()));
RETURN_NOERROR;
}
tResult cJuryModule::OnStop()
{
// stop button pressed
// setup jury struct and send 3 times
m_i16ManeuverEntry = m_pWidget->m_comboManeuver->currentIndex();
m_actionID = action_STOP;
m_iJuryStructCounter = 3;
QTimer::singleShot(0, this, SLOT(SendJuryStruct()));
RETURN_NOERROR;
}
tResult cJuryModule::OnStart()
{
// start button pressed
// setup jury struct and send 3 times
m_i16ManeuverEntry = m_pWidget->m_comboManeuver->currentIndex();
m_actionID = action_START;
m_iJuryStructCounter = 3;
QTimer::singleShot(0, this, SLOT(SendJuryStruct()));
RETURN_NOERROR;
}
tResult cJuryModule::OnLocalhostCheckChanged(int nState)
{
// localhost checkbox state changed
bool bEnable = false;
if (nState == 0)
{
bEnable = true;
}
// enable/disable ip settings
m_pWidget->m_spinBoxIP1->setEnabled(bEnable);
m_pWidget->m_spinBoxIP2->setEnabled(bEnable);
m_pWidget->m_spinBoxIP3->setEnabled(bEnable);
m_pWidget->m_spinBoxIP4->setEnabled(bEnable);
RETURN_NOERROR;
}
tResult cJuryModule::LoadManeuverList()
{
// load the maneuver list
// clear old list
m_strManeuverList.clear();
// use QDom for parsing
QDomDocument oDoc("maneuver_list");
QFile oFile(m_strManeuverFile);
// open file
if(!oFile.open(QIODevice::ReadOnly))
{
RETURN_ERROR(ERR_FILE_NOT_FOUND);
}
if (!oDoc.setContent(&oFile))
{
oFile.close();
RETURN_ERROR(ERR_INVALID_FILE);
}
// get the root element
QDomElement oRoot = oDoc.documentElement();
// get all sectors from DOM
QDomNodeList lstSectors = oRoot.elementsByTagName("AADC-Sector");
// iterate over all sectors
for (int nIdxSectors = 0; nIdxSectors < lstSectors.size(); ++nIdxSectors)
{
// get the ids and maneuver from sector
QDomNode oNodeSector = lstSectors.item(nIdxSectors);
QDomElement oElementSector = oNodeSector.toElement();
QString strIdSector = oElementSector.attribute("id");
tSector sSector;
sSector.id = strIdSector.toInt();
QDomNodeList lstManeuver = oElementSector.elementsByTagName("AADC-Maneuver");
// iterate over all maneuver
for (int nIdxManeuver = 0; nIdxManeuver < lstManeuver.size(); ++nIdxManeuver)
{
// get the id and the action
QDomNode oNodeManeuver = lstManeuver.item(nIdxManeuver);
QDomElement oElementManeuver = oNodeManeuver.toElement();
QString strIdManeuver = oElementManeuver.attribute("id");
tAADC_Maneuver sManeuver;
sManeuver.nId = strIdManeuver.toInt();
sManeuver.action = oElementManeuver.attribute("action").toStdString();
// fill the internal maneuver list
sSector.lstManeuvers.push_back(sManeuver);
}
// fill the internal sector list
m_lstSections.push_back(sSector);
}
// check sector list
if (m_lstSections.size() > 0)
{
SetLogText("Jury Module: Loaded Maneuver file successfully.");
}
else
{
SetLogText("Jury Module: no valid Maneuver Data found!");
}
// fill the combo boxes
FillComboBoxes();
// get the xml string for transmission
m_strManeuverList = oDoc.toString().toStdString();
// set the controls (enable/disable)
SetControlState();
RETURN_NOERROR;
}
tResult cJuryModule::SendEmergencyStop()
{
// the signal was transmitted as long as emergency counter is set
if(m_nEmergencyCounter > 0)
{
tJuryEmergencyStop sEmergencyStop;
sEmergencyStop.bEmergencyStop = true;
m_pDataSystemDataSender->UpdateData(CONLIB_OUT_PORT_NAME_EMERGENCY_STOP, &sEmergencyStop, sizeof(sEmergencyStop));
--m_nEmergencyCounter;
QTimer::singleShot(1000, this, SLOT(SendEmergencyStop()));
}
RETURN_NOERROR;
}
tResult cJuryModule::SendJuryStruct()
{
// the signal was transmitted as long as jury struct counter is set
if (m_iJuryStructCounter > 0)
{
tJuryStruct sJury;
sJury.i8ActionID = m_actionID;
sJury.i16ManeuverEntry = m_i16ManeuverEntry;
m_pDataSystemDataSender->UpdateData(CONLIB_OUT_PORT_NAME_JURY_STRUCT, &sJury, sizeof(sJury));
--m_iJuryStructCounter;
QTimer::singleShot(1000, this, SLOT(SendJuryStruct()));
}
RETURN_NOERROR;
}
tResult cJuryModule::SendManeuverList()
{
// only if maneuver file is set it will be transmitted
if (!m_strManeuverList.empty())
{
// hack to transmit data with dynamic size
tInt32 i32StringSize = (tInt32) (m_strManeuverList.size() + sizeof(tChar)); // plus one more char for terminating /0
tSize szBufferSize = i32StringSize * sizeof(char) + sizeof(i32StringSize); // buffer size is string size plus also transmitted size-value
// create a buffer
tUInt8 *pui8Buffer = new tUInt8[szBufferSize];
tInt32* pi32SizeInBuffer = (tInt32*) pui8Buffer;
// set the string size (needed for serialization/deserialization)
*pi32SizeInBuffer = i32StringSize;
// copy the maneuverlist string into the buffer
memcpy(pui8Buffer + sizeof(i32StringSize), m_strManeuverList.c_str(), i32StringSize * sizeof(char));
// transmit the data buffer
m_pDataSystemDataSender->UpdateData(CONLIB_OUT_PORT_NAME_MANEUVER_LIST, pui8Buffer, szBufferSize);
// cleanup
delete [] pui8Buffer;
//QTimer::singleShot(1000, this, SLOT(SendManeuverList()));
}
RETURN_NOERROR;
}
void cJuryModule::OnDriverState(int state, int entryId)
{
// set the driver state
SetDriverManeuverID(entryId);
switch (stateCar(state))
{
case stateCar_ERROR:
SetDriverStateError();
break;
case stateCar_READY:
SetDriverStateReady();
break;
case stateCar_RUNNING:
SetDriverStateRun();
break;
case stateCar_COMPLETE:
SetDriverStateComplete();
break;
case stateCar_STARTUP:
break;
}
}
void cJuryModule::OnAppendText(QString text)
{
// append the given text to the log field
if(m_pWidget)
{
m_pWidget->m_edtLogField->append(text);
}
}
void cJuryModule::OnComboActionBoxChanged(int index)
{
// search for the right section entry
for(unsigned int nIdxSection = 0; nIdxSection < m_lstSections.size(); nIdxSection++)
{
for(unsigned int nIdxManeuver = 0; nIdxManeuver < m_lstSections[nIdxSection].lstManeuvers.size(); nIdxManeuver++)
{
if(index == m_lstSections[nIdxSection].lstManeuvers[nIdxManeuver].nId)
{
m_pWidget->m_comboSector->setCurrentIndex(nIdxSection);
break;
}
}
}
}
void cJuryModule::OnComboSectionBoxChanged(int index)
{
//get the action id from selected section and write it to action combo box
m_pWidget->m_comboManeuver->setCurrentIndex(m_lstSections[index].lstManeuvers[0].nId);
}
void cJuryModule::SetDriverStateError()
{
// set the background and text
m_pWidget->m_lblState->setStyleSheet("background-color: rgb(255,0,0);");
m_pWidget->m_lblState->setText("Error");
}
void cJuryModule::SetDriverStateRun()
{
// set the background and text
m_pWidget->m_lblState->setStyleSheet("background-color: rgb(0,255,0);");
m_pWidget->m_lblState->setText("Running");
}
void cJuryModule::SetDriverStateReady()
{
// set the background and text
m_pWidget->m_lblState->setStyleSheet("background-color: rgb(255,255,0);");
m_pWidget->m_lblState->setText("Ready");
}
void cJuryModule::SetDriverStateComplete()
{
// set the background and text
m_pWidget->m_lblState->setStyleSheet("background-color: rgb(0,0,255);");
m_pWidget->m_lblState->setText("Complete");
}
tString cJuryModule::GetIpAdress()
{
// get the ip adress from the spinners or if localhost checkbox is checked use "localhost"
if (m_pWidget->m_cbxLocalHost->isChecked())
{
m_strIPAdress = "localhost";
}
else
{
QString strIp1 = m_pWidget->m_spinBoxIP1->text();
QString strIp2 = m_pWidget->m_spinBoxIP2->text();
QString strIp3 = m_pWidget->m_spinBoxIP3->text();
QString strIp4 = m_pWidget->m_spinBoxIP4->text();
m_strIPAdress = strIp1.toStdString() + "." + strIp2.toStdString() + "." + strIp3.toStdString() + "." + strIp4.toStdString();
}
return m_strIPAdress;
}
void cJuryModule::OnConnectDisconnect()
{
// connect / disconnect button pressed
// check for already running connection thread
if (!m_oConnectionThread.isRunning())
{
m_oConnectionThread.start();
}
// the timer will use the main thread which freezes the UI while connecting
//QTimer::singleShot(0, this, SLOT(ConnectDisconnectNetworkClients()));
}
void cJuryModule::SetDriverManeuverID(tInt16 id)
{
// set the id from received driver struct
m_pWidget->m_lblDriverManeuverID->setText(QString::number(id));
}
void cJuryModule::FillComboBoxes()
{
int nLastManeuverId = 0;
int nLastSectionId = 0;
// vector of maneuver names to fill the combobox also with names
std::vector<std::string> lstManeuverNames;
// find the last maneuver and section id
for(unsigned int i = 0; i < m_lstSections.size(); i++)
{
nLastSectionId++;
for(unsigned int j = 0; j < m_lstSections[i].lstManeuvers.size(); j++)
{
nLastManeuverId++;
lstManeuverNames.push_back(m_lstSections[i].lstManeuvers[j].action);
}
}
// clear the old entries
m_pWidget->m_comboManeuver->clear();
m_pWidget->m_comboSector->clear();
// fill the combo boxes
for(int i = 0; i < nLastManeuverId; i++)
{
m_pWidget->m_comboManeuver->addItem(QString::number(i) + QString(" - ") + QString(lstManeuverNames[i].c_str()));
}
for(int i = 0; i < nLastSectionId; i++)
{
m_pWidget->m_comboSector->addItem(QString::number(i));
}
}
| 33.717532 | 728 | 0.670647 | AppliedAutonomyOffenburg |
3d8599d2291dacb9bfa9e9c275ac75234d2e7408 | 1,118 | cpp | C++ | Laboratorio/PL- Aeropuerto/GamonalSanchezVictor/Box.cpp | lauram15a/Estructuras_de_datos | 5e31dd097c3fe3cfa36a49d6d0282687cc8e8d08 | [
"MIT"
] | null | null | null | Laboratorio/PL- Aeropuerto/GamonalSanchezVictor/Box.cpp | lauram15a/Estructuras_de_datos | 5e31dd097c3fe3cfa36a49d6d0282687cc8e8d08 | [
"MIT"
] | null | null | null | Laboratorio/PL- Aeropuerto/GamonalSanchezVictor/Box.cpp | lauram15a/Estructuras_de_datos | 5e31dd097c3fe3cfa36a49d6d0282687cc8e8d08 | [
"MIT"
] | null | null | null | #include "Box.hpp"
Box::Box()
{
lleno = false;
}
Box::~Box()
{
}
void Box::meter(Pasajero p, int tiempo)
{
pasajero_box = p;
lleno = true;
pasajero_box.setTiempo_espera(tiempo - pasajero_box.getHora_llegada() + 1); // una vez el pasajero entra al Box, defino el tiempo que ha estado esperando (en la lista)
pasajero_box.setTiempo_box(tiempo);
}
void Box::sacar()
{
lleno = false;
}
void Box::imprimir(int tiempo)
{
if (lleno)
{
cout << " " << endl;
cout << "*************** BOX ***************" << endl;
cout << " " << endl;
cout << "En el BOX esta el pasajero con ID = " << pasajero_box.getId_pasajero() << " con tiempo: " << tiempo << endl;
cout << "Con tiempo de espera = " << pasajero_box.getTiempo_espera() << endl;
}
else
{
cout << "BOX VACIO --> no se puede imprimir" << endl;
}
cout << " " << endl;
}
//GETTERS Y SETTERS
bool Box::isVacio()
{
return !lleno;
}
Pasajero Box::getPasajero()
{
return pasajero_box;
}
void Box::setPasajero(Pasajero pasajeroBox)
{
pasajero_box = pasajeroBox;
} | 19.614035 | 171 | 0.57424 | lauram15a |
3d88f8c3a6d012d27b7d6e9b89c371ffe73f546c | 400 | cpp | C++ | udacity-program_c_plusplus_programming_v1.0/demo/format.cpp | linksdl/futuretec-project-self_driving_cars_projects | 38e8f14543132ec86a8bada8d708eefaef23fee8 | [
"MIT"
] | null | null | null | udacity-program_c_plusplus_programming_v1.0/demo/format.cpp | linksdl/futuretec-project-self_driving_cars_projects | 38e8f14543132ec86a8bada8d708eefaef23fee8 | [
"MIT"
] | null | null | null | udacity-program_c_plusplus_programming_v1.0/demo/format.cpp | linksdl/futuretec-project-self_driving_cars_projects | 38e8f14543132ec86a8bada8d708eefaef23fee8 | [
"MIT"
] | null | null | null |
#include <iostream>
#include <iomanip>
int main()
{
std::cout<<"\n\nThe text without any formating\n";
std::cout<<"Ints"<<"Floats"<<"Doubles"<< "\n";
std::cout<<"\nThe text with setw(15)\n";
std::cout<<"Ints"<<std::setw(15)<<"Floats"<<std::setw(15)<<"Doubles"<< "\n";
std::cout<<"\n\nThe text with tabs\n";
std::cout<<"Ints\t"<<"Floats\t"<<"Doubles"<< "\n";
return 0;
} | 26.666667 | 80 | 0.5625 | linksdl |
3d8fcdaa9c8b2037dc2f6b6786a2fbd513e3ca83 | 1,498 | cpp | C++ | Plugins/org.blueberry.ui.qt/src/berrySaveablesLifecycleEvent.cpp | liu3xing3long/MITK-2016.11 | 385c506f9792414f40337e106e13d5fd61aa3ccc | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Plugins/org.blueberry.ui.qt/src/berrySaveablesLifecycleEvent.cpp | liu3xing3long/MITK-2016.11 | 385c506f9792414f40337e106e13d5fd61aa3ccc | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Plugins/org.blueberry.ui.qt/src/berrySaveablesLifecycleEvent.cpp | liu3xing3long/MITK-2016.11 | 385c506f9792414f40337e106e13d5fd61aa3ccc | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | /*===================================================================
BlueBerry Platform
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "berrySaveablesLifecycleEvent.h"
namespace berry
{
const int SaveablesLifecycleEvent::POST_OPEN = 1;
const int SaveablesLifecycleEvent::PRE_CLOSE = 2;
const int SaveablesLifecycleEvent::POST_CLOSE = 3;
const int SaveablesLifecycleEvent::DIRTY_CHANGED = 4;
SaveablesLifecycleEvent::SaveablesLifecycleEvent(Object::Pointer source_,
int eventType_, const QList<Saveable::Pointer>& saveables_,
bool force_) :
eventType(eventType_), saveables(saveables_), force(force_), veto(false),
source(source_)
{
}
int SaveablesLifecycleEvent::GetEventType()
{
return eventType;
}
Object::Pointer SaveablesLifecycleEvent::GetSource()
{
return source;
}
QList<Saveable::Pointer> SaveablesLifecycleEvent::GetSaveables()
{
return saveables;
}
bool SaveablesLifecycleEvent::IsVeto()
{
return veto;
}
void SaveablesLifecycleEvent::SetVeto(bool veto)
{
this->veto = veto;
}
bool SaveablesLifecycleEvent::IsForce()
{
return force;
}
}
| 22.358209 | 76 | 0.670895 | liu3xing3long |
3d90af6b88da4f912f82181ea2dfc9b2beae930e | 2,570 | cc | C++ | companyreg/src/model/GetInitFlowResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | companyreg/src/model/GetInitFlowResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | companyreg/src/model/GetInitFlowResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* 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/companyreg/model/GetInitFlowResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Companyreg;
using namespace AlibabaCloud::Companyreg::Model;
GetInitFlowResult::GetInitFlowResult() :
ServiceResult()
{}
GetInitFlowResult::GetInitFlowResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
GetInitFlowResult::~GetInitFlowResult()
{}
void GetInitFlowResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto allNodeListNode = value["NodeList"]["NodeListItem"];
for (auto valueNodeListNodeListItem : allNodeListNode)
{
NodeListItem nodeListObject;
if(!valueNodeListNodeListItem["Index"].isNull())
nodeListObject.index = std::stoi(valueNodeListNodeListItem["Index"].asString());
if(!valueNodeListNodeListItem["Status"].isNull())
nodeListObject.status = valueNodeListNodeListItem["Status"].asString();
if(!valueNodeListNodeListItem["Description"].isNull())
nodeListObject.description = valueNodeListNodeListItem["Description"].asString();
if(!valueNodeListNodeListItem["Code"].isNull())
nodeListObject.code = valueNodeListNodeListItem["Code"].asString();
if(!valueNodeListNodeListItem["Name"].isNull())
nodeListObject.name = valueNodeListNodeListItem["Name"].asString();
if(!valueNodeListNodeListItem["FailReason"].isNull())
nodeListObject.failReason = valueNodeListNodeListItem["FailReason"].asString();
if(!valueNodeListNodeListItem["Id"].isNull())
nodeListObject.id = std::stoi(valueNodeListNodeListItem["Id"].asString());
nodeList_.push_back(nodeListObject);
}
if(!value["FlowStatus"].isNull())
flowStatus_ = value["FlowStatus"].asString();
}
std::vector<GetInitFlowResult::NodeListItem> GetInitFlowResult::getNodeList()const
{
return nodeList_;
}
std::string GetInitFlowResult::getFlowStatus()const
{
return flowStatus_;
}
| 33.376623 | 84 | 0.7607 | aliyun |
3d90fe884817d34fa8aa0135cae4ff27dcc57bbf | 1,336 | cpp | C++ | Lezioni/07/35_4.cpp | FoxySeta/unibo-00819-programmazione | e8b54bf38c9f7885b05eabff9bced7c212aeb97e | [
"MIT"
] | 3 | 2021-11-02T16:06:46.000Z | 2022-02-15T11:24:15.000Z | Lezioni/07/35_4.cpp | FoxySeta/unibo-00819-programmazione | e8b54bf38c9f7885b05eabff9bced7c212aeb97e | [
"MIT"
] | 1 | 2020-09-25T17:54:52.000Z | 2020-09-25T22:15:42.000Z | Lezioni/07/35_4.cpp | FoxySeta/unibo-00819-programmazione | e8b54bf38c9f7885b05eabff9bced7c212aeb97e | [
"MIT"
] | null | null | null | /*
Università di Bologna
Corso di laurea in Informatica
00819 - Programmazione
Stefano Volpe #969766
20/10/2020
35_4.cpp
"Array", d. 35, es. 4
*/
#include <iostream>
using namespace std;
void parola(const char str[], int n, char dest[]);
int main()
{
const char s[]{ "Alma Mater Studiorum" };
constexpr size_t dim{ 100 };
char d[dim];
parola(s, 2, d);
cout << '"' << d << "\"\n";
}
void parola(const char str[], const int n, char dest[])
{
constexpr char space{ ' ' }, end{ '\0' };
size_t i{ 0 };
// Spazi iniziali
while (str[i] == space)
++i;
if (str[i] == end) {
// Nessuna parola trovata
dest[0] = end;
return;
}
int k;
for (k = 1; k < n && str[i] != end; ++k) {
// Parola non interessante
do
++i;
while (str[i] != space && str[i] != end);
if (str[i] == end) {
// Non abbastanza parole
dest[0] = end;
return;
}
// Spazi fra parole
do
++i;
while (str[i] == space);
}
if (k < n) {
// Nessuna parola trovata
dest[0] = end;
return;
}
size_t j{ 0 };
while (str[i] != space && str[i] != end) {
dest[j++] = str[i++];
}
dest[j] = end;
} | 19.647059 | 55 | 0.459581 | FoxySeta |
3d92232cf2b40986147c65925e92d61538179f86 | 391 | cpp | C++ | components/source/Sphere.cpp | matheusvxf/Lighting-and-Shaders | c555cbae2a4c882a0d13d1b5e4daa5c39c020c32 | [
"MIT"
] | 1 | 2016-07-21T08:52:49.000Z | 2016-07-21T08:52:49.000Z | components/source/Sphere.cpp | matheusvxf/Lighting-and-Shaders | c555cbae2a4c882a0d13d1b5e4daa5c39c020c32 | [
"MIT"
] | null | null | null | components/source/Sphere.cpp | matheusvxf/Lighting-and-Shaders | c555cbae2a4c882a0d13d1b5e4daa5c39c020c32 | [
"MIT"
] | null | null | null | #include "Sphere.h"
#include "GLee.h"
Sphere::Sphere() : Sphere(1.0) {}
Sphere::Sphere(double radius)
{
this->radius = radius;
this->slices = 64;
this->stacks = 64;
this->set_bouding_box(Vector3(radius, 0, 0), Vector3(0, radius, 0), Vector3(0, 0, radius));
}
Sphere::~Sphere()
{
}
void Sphere::render()
{
glutSolidSphere(this->radius, this->slices, this->stacks);
}
| 17 | 95 | 0.631714 | matheusvxf |
3d96664ff2e87811b18d09ff4e6afb64e84d651e | 1,671 | hh | C++ | src/bugengine/scheduler/api/bugengine/scheduler/task/kerneltask.hh | bugengine/BugEngine | 1b3831d494ee06b0bd74a8227c939dd774b91226 | [
"BSD-3-Clause"
] | 4 | 2015-05-13T16:28:36.000Z | 2017-05-24T15:34:14.000Z | src/bugengine/scheduler/api/bugengine/scheduler/task/kerneltask.hh | bugengine/BugEngine | 1b3831d494ee06b0bd74a8227c939dd774b91226 | [
"BSD-3-Clause"
] | null | null | null | src/bugengine/scheduler/api/bugengine/scheduler/task/kerneltask.hh | bugengine/BugEngine | 1b3831d494ee06b0bd74a8227c939dd774b91226 | [
"BSD-3-Clause"
] | 1 | 2017-03-21T08:28:07.000Z | 2017-03-21T08:28:07.000Z | /* BugEngine <bugengine.devel@gmail.com>
see LICENSE for detail */
#ifndef BE_SCHEDULER_TASK_KERNELTASK_HH_
#define BE_SCHEDULER_TASK_KERNELTASK_HH_
/**************************************************************************************************/
#include <bugengine/scheduler/stdafx.h>
#include <bugengine/scheduler/kernel/kernel.script.hh>
#include <bugengine/scheduler/kernel/parameters/iparameter.script.hh>
#include <bugengine/scheduler/task/itask.hh>
namespace BugEngine { namespace KernelScheduler {
class Kernel;
class IScheduler;
}} // namespace BugEngine::KernelScheduler
namespace BugEngine {
class Scheduler;
}
namespace BugEngine { namespace Task {
class be_api(SCHEDULER) KernelTask : public ITask
{
friend class ::BugEngine::Scheduler;
BE_NOCOPY(KernelTask);
private:
weak< const KernelScheduler::Kernel > const m_kernel;
weak< KernelScheduler::IScheduler > m_targetScheduler;
minitl::array< weak< KernelScheduler::IParameter > > const m_parameters;
u32 m_subTaskCount;
public:
KernelTask(istring name, KernelScheduler::SchedulerType type, color32 color,
Scheduler::Priority priority,
weak< const BugEngine::KernelScheduler::Kernel > kernel,
minitl::array< weak< KernelScheduler::IParameter > > parameters);
~KernelTask();
virtual void schedule(weak< Scheduler > scheduler) override;
};
}} // namespace BugEngine::Task
/**************************************************************************************************/
#endif
| 34.8125 | 100 | 0.597247 | bugengine |
3d967d74a56a02f98bf1629c747b63e56e076687 | 25,002 | cpp | C++ | src/io.cpp | ericgjackson/slumbot2017 | f0ddb6af63e9f7e25ffa7ef01337d47299a6520d | [
"MIT"
] | 15 | 2017-11-01T16:11:46.000Z | 2020-08-18T14:20:12.000Z | src/io.cpp | ericgjackson/slumbot2017 | f0ddb6af63e9f7e25ffa7ef01337d47299a6520d | [
"MIT"
] | 11 | 2020-02-16T12:45:33.000Z | 2022-02-10T07:20:47.000Z | src/io.cpp | ericgjackson/slumbot2017 | f0ddb6af63e9f7e25ffa7ef01337d47299a6520d | [
"MIT"
] | 7 | 2017-11-01T18:32:31.000Z | 2021-01-11T17:55:59.000Z | #include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <string>
#include <vector>
#include "io.h"
// Note that stat() is very slow. We've replaced the call to stat() with
// a call to open().
bool FileExists(const char *filename) {
int fd = open(filename, O_RDONLY, 0);
if (fd == -1) {
if (errno == ENOENT) {
// I believe this is what happens when there is no such file
return false;
}
fprintf(stderr, "Failed to open \"%s\", errno %i\n", filename, errno);
if (errno == 24) {
fprintf(stderr, "errno 24 may indicate too many open files\n");
}
exit(-1);
} else {
close(fd);
return true;
}
#if 0
struct stat stbuf;
int ret = stat(filename, &stbuf);
if (ret == -1) {
return false;
} else {
return true;
}
#endif
}
long long int FileSize(const char *filename) {
struct stat stbuf;
if (stat(filename, &stbuf) == -1) {
fprintf(stderr, "FileSize: Couldn't access: %s\n", filename);
exit(-1);
}
return stbuf.st_size;
}
void Reader::OpenFile(const char *filename) {
filename_ = filename;
struct stat stbuf;
if (stat(filename, &stbuf) == -1) {
fprintf(stderr, "Reader::OpenFile: Couldn't access: %s\n", filename);
exit(-1);
}
file_size_ = stbuf.st_size;
remaining_ = file_size_;
fd_ = open(filename, O_RDONLY, 0);
if (fd_ == -1) {
fprintf(stderr, "Failed to open \"%s\", errno %i\n", filename, errno);
if (errno == 24) {
fprintf(stderr, "errno 24 may indicate too many open files\n");
}
exit(-1);
}
overflow_size_ = 0;
byte_pos_ = 0;
}
Reader::Reader(const char *filename) {
OpenFile(filename);
buf_size_ = kBufSize;
if (remaining_ < buf_size_) buf_size_ = remaining_;
buf_.reset(new unsigned char[buf_size_]);
buf_ptr_ = buf_.get();
end_read_ = buf_.get();
if (! Refresh()) {
fprintf(stderr, "Warning: empty file: %s\n", filename);
}
}
// This constructor for use by NewReaderMaybe(). Doesn't call stat().
// I should clean up this code to avoid redundancy.
Reader::Reader(const char *filename, long long int file_size) {
filename_ = filename;
file_size_ = file_size;
remaining_ = file_size;
fd_ = open(filename, O_RDONLY, 0);
if (fd_ == -1) {
fprintf(stderr, "Failed to open \"%s\", errno %i\n", filename, errno);
if (errno == 24) {
fprintf(stderr, "errno 24 may indicate too many open files\n");
}
exit(-1);
}
overflow_size_ = 0;
byte_pos_ = 0;
buf_size_ = kBufSize;
if (remaining_ < buf_size_) buf_size_ = remaining_;
buf_.reset(new unsigned char[buf_size_]);
buf_ptr_ = buf_.get();
end_read_ = buf_.get();
if (! Refresh()) {
fprintf(stderr, "Warning: empty file: %s\n", filename);
}
}
// Returns NULL if no file by this name exists
Reader *NewReaderMaybe(const char *filename) {
struct stat stbuf;
if (stat(filename, &stbuf) == -1) {
return NULL;
}
long long int file_size = stbuf.st_size;
return new Reader(filename, file_size);
}
Reader::~Reader(void) {
close(fd_);
}
bool Reader::AtEnd(void) const {
// This doesn't work for CompressedReader
// return byte_pos_ == file_size_;
return (buf_ptr_ == end_read_ && remaining_ == 0 && overflow_size_ == 0);
}
void Reader::SeekTo(long long int offset) {
long long int ret = lseek(fd_, offset, SEEK_SET);
if (ret == -1) {
fprintf(stderr, "lseek failed, offset %lli, ret %lli, errno %i, fd %i\n",
offset, ret, errno, fd_);
fprintf(stderr, "File: %s\n", filename_.c_str());
exit(-1);
}
remaining_ = file_size_ - offset;
overflow_size_ = 0;
byte_pos_ = offset;
Refresh();
}
bool Reader::Refresh(void) {
if (remaining_ == 0 && overflow_size_ == 0) return false;
if (overflow_size_ > 0) {
memcpy(buf_.get(), overflow_, overflow_size_);
}
buf_ptr_ = buf_.get();
unsigned char *read_into = buf_.get() + overflow_size_;
int to_read = buf_size_ - overflow_size_;
if (to_read > remaining_) to_read = remaining_;
int ret;
if ((ret = read(fd_, read_into, to_read)) != to_read) {
fprintf(stderr, "Read returned %i not %i\n", ret, to_read);
fprintf(stderr, "File: %s\n", filename_.c_str());
fprintf(stderr, "remaining_ %lli\n", remaining_);
exit(-1);
}
remaining_ -= to_read;
end_read_ = read_into + to_read;
overflow_size_ = 0;
return true;
}
bool Reader::GetLine(string *s) {
s->clear();
while (true) {
if (buf_ptr_ == end_read_) {
if (! Refresh()) {
return false;
}
}
if (*buf_ptr_ == '\r') {
++buf_ptr_;
++byte_pos_;
continue;
}
if (*buf_ptr_ == '\n') {
++buf_ptr_;
++byte_pos_;
break;
}
s->push_back(*buf_ptr_);
++buf_ptr_;
++byte_pos_;
}
return true;
}
bool Reader::ReadInt(int *i) {
if (buf_ptr_ + sizeof(int) > end_read_) {
if (buf_ptr_ < end_read_) {
overflow_size_ = (int)(end_read_ - buf_ptr_);
memcpy(overflow_, buf_ptr_, overflow_size_);
}
if (! Refresh()) {
return false;
}
}
char my_buf[4];
my_buf[0] = *buf_ptr_++;
my_buf[1] = *buf_ptr_++;
my_buf[2] = *buf_ptr_++;
my_buf[3] = *buf_ptr_++;
byte_pos_ += 4;
int *int_ptr = reinterpret_cast<int *>(my_buf);
*i = *int_ptr;
return true;
}
int Reader::ReadIntOrDie(void) {
int i;
if (! ReadInt(&i)) {
fprintf(stderr, "Couldn't read int; file %s byte pos %lli\n",
filename_.c_str(), byte_pos_);
exit(-1);
}
return i;
}
bool Reader::ReadUnsignedInt(unsigned int *u) {
if (buf_ptr_ + sizeof(int) > end_read_) {
if (buf_ptr_ < end_read_) {
overflow_size_ = (int)(end_read_ - buf_ptr_);
memcpy(overflow_, buf_ptr_, overflow_size_);
}
if (! Refresh()) {
return false;
}
}
char my_buf[4];
my_buf[0] = *buf_ptr_++;
my_buf[1] = *buf_ptr_++;
my_buf[2] = *buf_ptr_++;
my_buf[3] = *buf_ptr_++;
byte_pos_ += 4;
unsigned int *u_int_ptr = reinterpret_cast<unsigned int *>(my_buf);
*u = *u_int_ptr;
return true;
}
unsigned int Reader::ReadUnsignedIntOrDie(void) {
unsigned int u;
if (! ReadUnsignedInt(&u)) {
fprintf(stderr, "Couldn't read unsigned int\n");
fprintf(stderr, "File: %s\n", filename_.c_str());
fprintf(stderr, "Byte pos: %lli\n", byte_pos_);
exit(-1);
}
return u;
}
bool Reader::ReadLong(long long int *l) {
if (buf_ptr_ + sizeof(long long int) > end_read_) {
if (buf_ptr_ < end_read_) {
overflow_size_ = (int)(end_read_ - buf_ptr_);
memcpy(overflow_, buf_ptr_, overflow_size_);
}
if (! Refresh()) {
return false;
}
}
*l = *(long long int *)buf_ptr_;
buf_ptr_ += sizeof(long long int);
byte_pos_ += sizeof(long long int);
return true;
}
long long int Reader::ReadLongOrDie(void) {
long long int l;
if (! ReadLong(&l)) {
fprintf(stderr, "Couldn't read long\n");
exit(-1);
}
return l;
}
bool Reader::ReadUnsignedLong(unsigned long long int *u) {
if (buf_ptr_ + sizeof(unsigned long long int) > end_read_) {
if (buf_ptr_ < end_read_) {
overflow_size_ = (int)(end_read_ - buf_ptr_);
memcpy(overflow_, buf_ptr_, overflow_size_);
}
if (! Refresh()) {
return false;
}
}
*u = *(unsigned long long int *)buf_ptr_;
buf_ptr_ += sizeof(unsigned long long int);
byte_pos_ += sizeof(unsigned long long int);
return true;
}
unsigned long long int Reader::ReadUnsignedLongOrDie(void) {
unsigned long long int u;
if (! ReadUnsignedLong(&u)) {
fprintf(stderr, "Couldn't read unsigned long\n");
exit(-1);
}
return u;
}
bool Reader::ReadShort(short *s) {
if (buf_ptr_ + sizeof(short) > end_read_) {
if (buf_ptr_ < end_read_) {
overflow_size_ = (int)(end_read_ - buf_ptr_);
memcpy(overflow_, buf_ptr_, overflow_size_);
}
if (! Refresh()) {
return false;
}
}
// Possible alignment issue?
*s = *(short *)buf_ptr_;
buf_ptr_ += sizeof(short);
byte_pos_ += sizeof(short);
return true;
}
short Reader::ReadShortOrDie(void) {
short s;
if (! ReadShort(&s)) {
fprintf(stderr, "Couldn't read short\n");
exit(-1);
}
return s;
}
bool Reader::ReadUnsignedShort(unsigned short *u) {
if (buf_ptr_ + sizeof(unsigned short) > end_read_) {
if (buf_ptr_ < end_read_) {
overflow_size_ = (int)(end_read_ - buf_ptr_);
memcpy(overflow_, buf_ptr_, overflow_size_);
}
if (! Refresh()) {
return false;
}
}
*u = *(unsigned short *)buf_ptr_;
buf_ptr_ += sizeof(unsigned short);
byte_pos_ += sizeof(unsigned short);
return true;
}
unsigned short Reader::ReadUnsignedShortOrDie(void) {
unsigned short s;
if (! ReadUnsignedShort(&s)) {
fprintf(stderr, "Couldn't read unsigned short; file %s byte pos %lli "
"file_size %lli\n", filename_.c_str(), byte_pos_, file_size_);
exit(-1);
}
return s;
}
bool Reader::ReadChar(char *c) {
if (buf_ptr_ + sizeof(char) > end_read_) {
if (buf_ptr_ < end_read_) {
overflow_size_ = (int)(end_read_ - buf_ptr_);
memcpy(overflow_, buf_ptr_, overflow_size_);
}
if (! Refresh()) {
return false;
}
}
*c = *(char *)buf_ptr_;
buf_ptr_ += sizeof(char);
byte_pos_ += sizeof(char);
return true;
}
char Reader::ReadCharOrDie(void) {
char c;
if (! ReadChar(&c)) {
fprintf(stderr, "Couldn't read char\n");
exit(-1);
}
return c;
}
bool Reader::ReadUnsignedChar(unsigned char *u) {
if (buf_ptr_ + sizeof(unsigned char) > end_read_) {
if (buf_ptr_ < end_read_) {
overflow_size_ = (int)(end_read_ - buf_ptr_);
memcpy(overflow_, buf_ptr_, overflow_size_);
}
if (! Refresh()) {
return false;
}
}
*u = *(unsigned char *)buf_ptr_;
buf_ptr_ += sizeof(unsigned char);
byte_pos_ += sizeof(unsigned char);
return true;
}
unsigned char Reader::ReadUnsignedCharOrDie(void) {
unsigned char u;
if (! ReadUnsignedChar(&u)) {
fprintf(stderr, "Couldn't read unsigned char\n");
fprintf(stderr, "File: %s\n", filename_.c_str());
fprintf(stderr, "Byte pos: %lli\n", byte_pos_);
exit(-1);
}
return u;
}
void Reader::ReadOrDie(unsigned char *c) {
*c = ReadUnsignedCharOrDie();
}
void Reader::ReadOrDie(unsigned short *s) {
*s = ReadUnsignedShortOrDie();
}
void Reader::ReadOrDie(unsigned int *u) {
*u = ReadUnsignedIntOrDie();
}
void Reader::ReadOrDie(int *i) {
*i = ReadIntOrDie();
}
void Reader::ReadOrDie(double *d) {
*d = ReadDoubleOrDie();
}
void Reader::ReadNBytesOrDie(unsigned int num_bytes, unsigned char *buf) {
for (unsigned int i = 0; i < num_bytes; ++i) {
if (buf_ptr_ + 1 > end_read_) {
if (! Refresh()) {
fprintf(stderr, "Couldn't read %i bytes\n", num_bytes);
fprintf(stderr, "Filename: %s\n", filename_.c_str());
fprintf(stderr, "File size: %lli\n", file_size_);
fprintf(stderr, "Before read byte pos: %lli\n", byte_pos_);
fprintf(stderr, "Overflow size: %i\n", overflow_size_);
fprintf(stderr, "i %i\n", i);
exit(-1);
}
}
buf[i] = *buf_ptr_++;
++byte_pos_;
}
}
void Reader::ReadEverythingLeft(unsigned char *data) {
unsigned long long int data_pos = 0ULL;
unsigned long long int left = file_size_ - byte_pos_;
while (left > 0) {
unsigned long long int num_bytes = end_read_ - buf_ptr_;
memcpy(data + data_pos, buf_ptr_, num_bytes);
buf_ptr_ = end_read_;
data_pos += num_bytes;
if (data_pos > left) {
fprintf(stderr, "ReadEverythingLeft: read too much?!?\n");
exit(-1);
} else if (data_pos == left) {
break;
}
if (! Refresh()) {
fprintf(stderr, "ReadEverythingLeft: premature EOF?!?\n");
exit(-1);
}
}
}
bool Reader::ReadCString(string *s) {
*s = "";
while (true) {
if (buf_ptr_ + 1 > end_read_) {
if (! Refresh()) {
return false;
}
}
char c = *buf_ptr_++;
++byte_pos_;
if (c == 0) return true;
*s += c;
}
}
string Reader::ReadCStringOrDie(void) {
string s;
if (! ReadCString(&s)) {
fprintf(stderr, "Couldn't read string\n");
exit(-1);
}
return s;
}
bool Reader::ReadDouble(double *d) {
if (buf_ptr_ + sizeof(double) > end_read_) {
if (buf_ptr_ < end_read_) {
overflow_size_ = (int)(end_read_ - buf_ptr_);
memcpy(overflow_, buf_ptr_, overflow_size_);
}
if (! Refresh()) {
return false;
}
}
*d = *(double *)buf_ptr_;
buf_ptr_ += sizeof(double);
byte_pos_ += sizeof(double);
return true;
}
double Reader::ReadDoubleOrDie(void) {
double d;
if (! ReadDouble(&d)) {
fprintf(stderr, "Couldn't read double: file %s byte pos %lli\n",
filename_.c_str(), byte_pos_);
exit(-1);
}
return d;
}
bool Reader::ReadFloat(float *f) {
if (buf_ptr_ + sizeof(float) > end_read_) {
if (buf_ptr_ < end_read_) {
overflow_size_ = (int)(end_read_ - buf_ptr_);
memcpy(overflow_, buf_ptr_, overflow_size_);
}
if (! Refresh()) {
return false;
}
}
*f = *(float *)buf_ptr_;
buf_ptr_ += sizeof(float);
byte_pos_ += sizeof(float);
return true;
}
float Reader::ReadFloatOrDie(void) {
float f;
if (! ReadFloat(&f)) {
fprintf(stderr, "Couldn't read float: file %s\n", filename_.c_str());
exit(-1);
}
return f;
}
// Identical to ReadDouble()
bool Reader::ReadReal(double *d) {
if (buf_ptr_ + sizeof(double) > end_read_) {
if (buf_ptr_ < end_read_) {
overflow_size_ = (int)(end_read_ - buf_ptr_);
memcpy(overflow_, buf_ptr_, overflow_size_);
}
if (! Refresh()) {
return false;
}
}
*d = *(double *)buf_ptr_;
buf_ptr_ += sizeof(double);
byte_pos_ += sizeof(double);
return true;
}
// Identical to ReadFloat()
bool Reader::ReadReal(float *f) {
if (buf_ptr_ + sizeof(float) > end_read_) {
if (buf_ptr_ < end_read_) {
overflow_size_ = (int)(end_read_ - buf_ptr_);
memcpy(overflow_, buf_ptr_, overflow_size_);
}
if (! Refresh()) {
return false;
}
}
*f = *(float *)buf_ptr_;
buf_ptr_ += sizeof(float);
byte_pos_ += sizeof(float);
return true;
}
void Writer::Init(const char *filename, bool modify, int buf_size) {
filename_ = filename;
if (modify) {
fd_ = open(filename, O_WRONLY, 0666);
if (fd_ < 0 && errno == ENOENT) {
// If file doesn't exist, open it with creat()
fd_ = creat(filename, 0666);
}
} else {
// creat() is supposedly equivalent to passing
// O_WRONLY|O_CREAT|O_TRUNC to open().
fd_ = creat(filename, 0666);
}
if (fd_ < 0) {
// Is this how errors are indicated?
fprintf(stderr, "Couldn't open %s for writing (errno %i)\n", filename,
errno);
exit(-1);
}
buf_size_ = buf_size;
buf_.reset(new unsigned char[buf_size_]);
end_buf_ = buf_.get() + buf_size_;
buf_ptr_ = buf_.get();
}
Writer::Writer(const char *filename, int buf_size) {
Init(filename, false, buf_size);
}
Writer::Writer(const char *filename, bool modify) {
Init(filename, modify, kBufSize);
}
Writer::Writer(const char *filename) {
Init(filename, false, kBufSize);
}
Writer::~Writer(void) {
Flush();
close(fd_);
}
// Generally write() writes everything in one call. Haven't seen any cases
// that justify the loop I do below. Could take it out.
void Writer::Flush(void) {
if (buf_ptr_ > buf_.get()) {
int left_to_write = (int)(buf_ptr_ - buf_.get());
while (left_to_write > 0) {
int written = write(fd_, buf_.get(), left_to_write);
if (written < 0) {
fprintf(stderr,
"Error in flush: tried to write %i, return of %i; errno %i; "
"fd %i\n", left_to_write, written, errno, fd_);
exit(-1);
} else if (written == 0) {
// Stall for a bit to avoid busy loop
sleep(1);
}
left_to_write -= written;
}
}
buf_ptr_ = buf_.get();
}
// Only makes sense to call if we created the Writer with modify=true
void Writer::SeekTo(long long int offset) {
Flush();
long long int ret = lseek(fd_, offset, SEEK_SET);
if (ret == -1) {
fprintf(stderr, "lseek failed, offset %lli, ret %lli, errno %i, fd %i\n",
offset, ret, errno, fd_);
fprintf(stderr, "File: %s\n", filename_.c_str());
exit(-1);
}
}
long long int Writer::Tell(void) {
Flush();
return lseek(fd_, 0LL, SEEK_CUR);
}
void Writer::WriteInt(int i) {
if (buf_ptr_ + sizeof(int) > end_buf_) {
Flush();
}
// Couldn't we have an alignment issue if we write a char and then an int,
// for example?
// *(int *)buf_ptr_ = i;
memcpy(buf_ptr_, (void *)&i, sizeof(int));
buf_ptr_ += sizeof(int);
}
void Writer::WriteUnsignedInt(unsigned int u) {
if (buf_ptr_ + sizeof(unsigned int) > end_buf_) {
Flush();
}
*(unsigned int *)buf_ptr_ = u;
buf_ptr_ += sizeof(unsigned int);
}
void Writer::WriteLong(long long int l) {
if (buf_ptr_ + sizeof(long long int) > end_buf_) {
Flush();
}
*(long long int *)buf_ptr_ = l;
buf_ptr_ += sizeof(long long int);
}
void Writer::WriteUnsignedLong(unsigned long long int u) {
if (buf_ptr_ + sizeof(unsigned long long int) > end_buf_) {
Flush();
}
*(unsigned long long int *)buf_ptr_ = u;
buf_ptr_ += sizeof(unsigned long long int);
}
void Writer::WriteShort(short s) {
if (buf_ptr_ + sizeof(short) > end_buf_) {
Flush();
}
*(short *)buf_ptr_ = s;
buf_ptr_ += sizeof(short);
}
void Writer::WriteChar(char c) {
if (buf_ptr_ + sizeof(char) > end_buf_) {
Flush();
}
*(char *)buf_ptr_ = c;
buf_ptr_ += sizeof(char);
}
void Writer::WriteUnsignedChar(unsigned char c) {
if (buf_ptr_ + sizeof(unsigned char) > end_buf_) {
Flush();
}
*(unsigned char *)buf_ptr_ = c;
buf_ptr_ += sizeof(unsigned char);
}
void Writer::WriteUnsignedShort(unsigned short s) {
if (buf_ptr_ + sizeof(unsigned short) > end_buf_) {
Flush();
}
*(unsigned short *)buf_ptr_ = s;
buf_ptr_ += sizeof(unsigned short);
}
void Writer::WriteFloat(float f) {
if (buf_ptr_ + sizeof(float) > end_buf_) {
Flush();
}
*(float *)buf_ptr_ = f;
buf_ptr_ += sizeof(float);
}
void Writer::WriteDouble(double d) {
if (buf_ptr_ + sizeof(double) > end_buf_) {
Flush();
}
*(double *)buf_ptr_ = d;
buf_ptr_ += sizeof(double);
}
// Identical to WriteFloat()
void Writer::WriteReal(float f) {
if (buf_ptr_ + sizeof(float) > end_buf_) {
Flush();
}
*(float *)buf_ptr_ = f;
buf_ptr_ += sizeof(float);
}
// Identical to WriteDouble()
void Writer::WriteReal(double d) {
if (buf_ptr_ + sizeof(double) > end_buf_) {
Flush();
}
*(double *)buf_ptr_ = d;
buf_ptr_ += sizeof(double);
}
void Writer::Write(unsigned char c) {
WriteUnsignedChar(c);
}
void Writer::Write(unsigned short s) {
WriteUnsignedShort(s);
}
void Writer::Write(int i) {
WriteInt(i);
}
void Writer::Write(unsigned int u) {
WriteUnsignedInt(u);
}
void Writer::Write(double d) {
WriteDouble(d);
}
void Writer::WriteCString(const char *s) {
int len = strlen(s);
if (buf_ptr_ + len + 1 > end_buf_) {
Flush();
}
memcpy(buf_ptr_, s, len);
buf_ptr_[len] = 0;
buf_ptr_ += len + 1;
}
// Does not write num_bytes into file
void Writer::WriteNBytes(unsigned char *bytes, unsigned int num_bytes) {
if ((int)num_bytes > buf_size_) {
Flush();
while ((int)num_bytes > buf_size_) {
buf_size_ *= 2;
buf_.reset(new unsigned char[buf_size_]);
buf_ptr_ = buf_.get();
end_buf_ = buf_.get() + buf_size_;
}
}
if (buf_ptr_ + num_bytes > end_buf_) {
Flush();
}
memcpy(buf_ptr_, bytes, num_bytes);
buf_ptr_ += num_bytes;
}
void Writer::WriteBytes(unsigned char *bytes, int num_bytes) {
WriteInt(num_bytes);
if (num_bytes > buf_size_) {
Flush();
while (num_bytes > buf_size_) {
buf_size_ *= 2;
buf_.reset(new unsigned char[buf_size_]);
buf_ptr_ = buf_.get();
end_buf_ = buf_.get() + buf_size_;
}
}
if (buf_ptr_ + num_bytes > end_buf_) {
Flush();
}
memcpy(buf_ptr_, bytes, num_bytes);
buf_ptr_ += num_bytes;
}
void Writer::WriteText(const char *s) {
int len = strlen(s);
if (buf_ptr_ + len + 1 > end_buf_) {
Flush();
}
memcpy(buf_ptr_, s, len);
buf_ptr_ += len;
}
unsigned int Writer::BufPos(void) {
return (unsigned int)(buf_ptr_ - buf_.get());
}
ReadWriter::ReadWriter(const char *filename) {
filename_ = filename;
fd_ = open(filename, O_RDWR, 0666);
if (fd_ < 0 && errno == ENOENT) {
fprintf(stderr, "Can only create a ReadWriter on an existing file\n");
fprintf(stderr, "Filename: %s\n", filename);
exit(-1);
}
}
ReadWriter::~ReadWriter(void) {
close(fd_);
}
void ReadWriter::SeekTo(long long int offset) {
long long int ret = lseek(fd_, offset, SEEK_SET);
if (ret == -1) {
fprintf(stderr, "lseek failed, offset %lli, ret %lli, errno %i, fd %i\n",
offset, ret, errno, fd_);
fprintf(stderr, "File: %s\n", filename_.c_str());
exit(-1);
}
}
int ReadWriter::ReadIntOrDie(void) {
int i, ret;
if ((ret = read(fd_, &i, 4)) != 4) {
fprintf(stderr, "ReadWriter::ReadInt returned %i not 4\n", ret);
fprintf(stderr, "File: %s\n", filename_.c_str());
exit(-1);
}
return i;
}
void ReadWriter::WriteInt(int i) {
int written = write(fd_, &i, 4);
if (written != 4) {
fprintf(stderr, "Error: tried to write 4 bytes, return of %i; fd %i\n",
written, fd_);
exit(-1);
}
}
bool IsADirectory(const char *path) {
struct stat statbuf;
if (stat(path, &statbuf) != 0) return 0;
return S_ISDIR(statbuf.st_mode);
}
// Filenames in listing returned are full paths
void GetDirectoryListing(const char *dir, vector<string> *listing) {
int dirlen = strlen(dir);
bool ends_in_slash = (dir[dirlen - 1] == '/');
listing->clear();
DIR *dfd = opendir(dir);
if (dfd == NULL) {
fprintf(stderr, "GetDirectoryListing: could not open directory %s\n", dir);
exit(-1);
}
dirent *dp;
while ((dp = readdir(dfd))) {
if (strcmp(dp->d_name, ".") && strcmp(dp->d_name, "..")) {
string full_path = dir;
if (! ends_in_slash) {
full_path += "/";
}
full_path += dp->d_name;
listing->push_back(full_path);
}
}
closedir(dfd);
}
static void RecursivelyDelete(const string &path) {
if (! IsADirectory(path.c_str())) {
// fprintf(stderr, "Removing file %s\n", path.c_str());
RemoveFile(path.c_str());
return;
}
vector<string> listing;
GetDirectoryListing(path.c_str(), &listing);
unsigned int num = listing.size();
for (unsigned int i = 0; i < num; ++i) {
RecursivelyDelete(listing[i]);
}
// fprintf(stderr, "Removing dir %s\n", path.c_str());
RemoveFile(path.c_str());
}
void RecursivelyDeleteDirectory(const char *dir) {
if (! IsADirectory(dir)) {
fprintf(stderr, "Path supplied is not a directory: %s\n", dir);
return;
}
vector<string> listing;
GetDirectoryListing(dir, &listing);
unsigned int num = listing.size();
for (unsigned int i = 0; i < num; ++i) {
RecursivelyDelete(listing[i]);
}
// fprintf(stderr, "Removing dir %s\n", dir);
RemoveFile(dir);
}
// Gives read/write/execute permissions to everyone
void Mkdir(const char *dir) {
int ret = mkdir(dir, S_IRWXU | S_IRWXG | S_IRWXO);
if (ret != 0) {
if (errno == 17) {
// File or directory by this name already exists. We'll just assume
// it's a directory and return successfully.
return;
}
fprintf(stderr, "mkdir returned %i; errno %i\n", ret, errno);
fprintf(stderr, "Directory: %s\n", dir);
exit(-1);
}
}
// FileExists() calls stat() which is very expensive. Try calling
// remove() without a preceding FileExists() check.
void RemoveFile(const char *filename) {
int ret = remove(filename);
if (ret) {
// ENOENT just signifies that there is no file by the given name
if (errno != ENOENT) {
fprintf(stderr, "Error removing file: %i; errno %i\n", ret, errno);
exit(-1);
}
}
}
// How is this different from RemoveFile()?
void UnlinkFile(const char *filename) {
int ret = unlink(filename);
if (ret) {
// ENOENT just signifies that there is no file by the given name
if (errno != ENOENT) {
fprintf(stderr, "Error unlinking file: %i; errno %i\n", ret, errno);
exit(-1);
}
}
}
void MoveFile(const char *old_location, const char *new_location) {
if (! FileExists(old_location)) {
fprintf(stderr, "MoveFile: old location \"%s\" does not exist\n",
old_location);
exit(-1);
}
if (FileExists(new_location)) {
fprintf(stderr, "MoveFile: new location \"%s\" already exists\n",
new_location);
exit(-1);
}
int ret = rename(old_location, new_location);
if (ret != 0) {
fprintf(stderr, "MoveFile: rename() returned %i\n", ret);
fprintf(stderr, "Old location: %s\n", old_location);
fprintf(stderr, "New location: %s\n", new_location);
exit(-1);
}
}
void CopyFile(const char *old_location, const char *new_location) {
Reader reader(old_location);
Writer writer(new_location);
unsigned char uc;
while (reader.ReadUnsignedChar(&uc)) {
writer.WriteUnsignedChar(uc);
}
}
| 24.297376 | 79 | 0.62191 | ericgjackson |
3d999d5f0d448760b952954f732fe32a95e06901 | 3,021 | hpp | C++ | Nacro/SDK/FN_Results_PlayerScoreRow_parameters.hpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 11 | 2021-08-08T23:25:10.000Z | 2022-02-19T23:07:22.000Z | Nacro/SDK/FN_Results_PlayerScoreRow_parameters.hpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 1 | 2022-01-01T22:51:59.000Z | 2022-01-08T16:14:15.000Z | Nacro/SDK/FN_Results_PlayerScoreRow_parameters.hpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 8 | 2021-08-09T13:51:54.000Z | 2022-01-26T20:33:37.000Z | #pragma once
// Fortnite (1.8) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "../SDK.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function Results_PlayerScoreRow.Results_PlayerScoreRow_C.InitializeHomeBasePower
struct UResults_PlayerScoreRow_C_InitializeHomeBasePower_Params
{
struct FUniqueNetIdRepl PlayerID; // (Parm)
};
// Function Results_PlayerScoreRow.Results_PlayerScoreRow_C.InitializePlayerName
struct UResults_PlayerScoreRow_C_InitializePlayerName_Params
{
class UFortUIScoreReport* ScoreReport; // (Parm, ZeroConstructor, IsPlainOldData)
int ScoreReportReferece; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function Results_PlayerScoreRow.Results_PlayerScoreRow_C.InitializeScores
struct UResults_PlayerScoreRow_C_InitializeScores_Params
{
class UFortUIScoreReport* InScoreReport; // (Parm, ZeroConstructor, IsPlainOldData)
int InScoreReportIndex; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function Results_PlayerScoreRow.Results_PlayerScoreRow_C.InitializeBackground
struct UResults_PlayerScoreRow_C_InitializeBackground_Params
{
};
// Function Results_PlayerScoreRow.Results_PlayerScoreRow_C.Initialize
struct UResults_PlayerScoreRow_C_Initialize_Params
{
class UFortUIScoreReport* ScoreReport; // (Parm, ZeroConstructor, IsPlainOldData)
int ScoreReportIndex; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function Results_PlayerScoreRow.Results_PlayerScoreRow_C.Manual Pre Construct
struct UResults_PlayerScoreRow_C_Manual_Pre_Construct_Params
{
bool bIsDesignTime; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function Results_PlayerScoreRow.Results_PlayerScoreRow_C.PreConstruct
struct UResults_PlayerScoreRow_C_PreConstruct_Params
{
bool* IsDesignTime; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function Results_PlayerScoreRow.Results_PlayerScoreRow_C.ExecuteUbergraph_Results_PlayerScoreRow
struct UResults_PlayerScoreRow_C_ExecuteUbergraph_Results_PlayerScoreRow_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 41.958333 | 152 | 0.572327 | Milxnor |
3d9a34a2b9f721db162195c2eea5ade04f3d56c0 | 36,728 | hpp | C++ | Motorola/MCore IDA IDP/5.0/IDA/Inc/loader.hpp | erithion/old_junk | b2dcaa23320824f8b2c17571f27826869ccd0d4b | [
"MIT"
] | 1 | 2021-06-26T17:08:24.000Z | 2021-06-26T17:08:24.000Z | Motorola/MCore IDA IDP/5.0/IDA/Inc/loader.hpp | erithion/old_junk | b2dcaa23320824f8b2c17571f27826869ccd0d4b | [
"MIT"
] | null | null | null | Motorola/MCore IDA IDP/5.0/IDA/Inc/loader.hpp | erithion/old_junk | b2dcaa23320824f8b2c17571f27826869ccd0d4b | [
"MIT"
] | null | null | null | /*
* Interactive disassembler (IDA).
* Copyright (c) 1990-97 by Ilfak Guilfanov.
* ALL RIGHTS RESERVED.
* E-mail: ig@estar.msk.su
* FIDO: 2:5020/209
*
*/
#ifndef _LOADER_HPP
#define _LOADER_HPP
#pragma pack(push, 1) // IDA uses 1 byte alignments!
//
// This file contains:
// - definitions of IDP, LDR, PLUGIN module interfaces.
// - functions to load files into the database
// - functions to generate output files
// - high level functions to work with the database (open, save, close)
//
// The LDR interface consists of one structure loader_t
// The IDP interface consists of one structure processor_t (see idp.hpp)
// The PLUGIN interface consists of one structure plugin_t
//
// Modules can't use standard FILE* functions.
// They must use functions from <fpro.h>
//
// Modules can't use standard memory allocation functions.
// They must use functions from <pro.h>
//
// The exported entry #1 in the module should point to the
// the appropriate structure. (loader_t for LDR module, for example)
//
//----------------------------------------------------------------------
// DEFINITION OF LDR MODULES
//----------------------------------------------------------------------
class linput_t; // loader input source. see diskio.hpp for the functions
// Loader description block - must be exported from the loader module
#define MAX_FILE_FORMAT_NAME 64
struct loader_t
{
ulong version; // api version, should be IDP_INTERFACE_VERSION
ulong flags; // loader flags
#define LDRF_RELOAD 0x0001 // loader recognizes NEF_RELOAD flag
//
// check input file format. if recognized, then return 1
// and fill 'fileformatname'.
// otherwise return 0
// This function will be called many times till it returns !=0.
// 'n' parameter will be incremented after each call.
// Initially, n==0 for each loader.
// This function may return a unique file format number instead of 1.
// To get this unique number, please contact the author.
//
// If the return value is ORed with ACCEPT_FIRST, then this format
// should be placed first in the "load file" dialog box
//
#define ACCEPT_FIRST 0x8000
int (idaapi* accept_file)(linput_t *li,
char fileformatname[MAX_FILE_FORMAT_NAME],
int n);
//
// load file into the database.
// fp - pointer to file positioned at the start of the file
// fileformatname - name of type of the file (it was returned
// by the accept_file)
// neflags - user-supplied flags. They determine how to
// load the file.
// in the case of failure loader_failure() should be called
//
void (idaapi* load_file)(linput_t *li,
ushort neflags,
const char *fileformatname);
#define NEF_SEGS 0x0001 // Create segments
#define NEF_RSCS 0x0002 // Load resources
#define NEF_NAME 0x0004 // Rename entries
#define NEF_MAN 0x0008 // Manual load
#define NEF_FILL 0x0010 // Fill segment gaps
#define NEF_IMPS 0x0020 // Create imports section
#define NEF_TIGHT 0x0040 // Don't align segments (OMF)
#define NEF_FIRST 0x0080 // This is the first file loaded
// into the database.
#define NEF_CODE 0x0100 // for load_binary_file:
// load as a code segment
#define NEF_RELOAD 0x0200 // reload the file at the same place:
// don't create segments
// don't create fixup info
// don't import segments
// etc
// load only the bytes into the base.
// a loader should have LDRF_RELOAD
// bit set
#define NEF_FLAT 0x0400 // Autocreate FLAT group (PE)
#define NEF_MINI 0x0800 // Create mini database (do not copy
#define NEF_LOPT 0x1000 // Display additional loader options dialog
//
// create output file from the database.
// this function may be absent.
// if fp == NULL, then this function returns:
// 0 - can't create file of this type
// 1 - ok, can create file of this type
// if fp != NULL, then this function should create the output file
//
int (idaapi* save_file)(FILE *fp, const char *fileformatname);
// take care of a moved segment (fix up relocations, for example)
// this function may be absent.
// from - previous linear address of the segment
// to - current linear address of the segment
// size - size of the moved segment
// fileformatname - the file format
// a special calling method move_segm(BADADDR, delta, 0, formatname)
// means that the whole program has been moved in the memory (rebased) by delta bytes
// returns: 1-ok, 0-failure
int (idaapi* move_segm)(ea_t from,
ea_t to,
asize_t size,
const char *fileformatname);
// initialize user configurable options based on the input file.
// this function may be absent.
// fp - pointer to file positioned at the start of the file
// This function is called as soon as a loader is selected, and allow the loader
// to populate XML variables, select a default processor, ...
// returns: true-ok, false-cancel
bool (idaapi* init_loader_options)(linput_t *li);
};
#ifdef __BORLANDC__
#if sizeof(loader_t) % 4
#error "Size of loader_t is incorrect"
#endif
#endif
extern "C" loader_t LDSC; // (declaration for loaders)
// Display a message about a loader failure and stop the loading process
// The kernel will destroy the database
// If format == NULL, no message will be displayed
// This function does not return (it longjumps)!
// It may be called only from loader_t.load_file()
idaman void ida_export vloader_failure(const char *format, va_list va);
inline void loader_failure(const char *format=NULL, ...)
{
va_list va;
va_start(va, format);
vloader_failure(format, va);
va_end(va);
}
//----------------------------------------------------------------------
// LDR module file name extensions:
#ifdef __NT__
#ifdef __EA64__
#ifdef __AMD64__
#define LOADER_EXT "x64"
#else
#define LOADER_EXT "l64"
#endif
#else
#define LOADER_EXT "ldw"
#endif
#endif
#ifdef __LINUX__
#ifdef __EA64__
#define LOADER_EXT "llx64"
#else
#define LOADER_EXT "llx"
#endif
#endif
#ifdef __EA64__
#define LOADER_DLL "*64." LOADER_EXT
#else
#define LOADER_DLL "*." LOADER_EXT
#endif
//----------------------------------------------------------------------
// Functions for the UI to load files
//----------------------------------------------------------------------
struct load_info_t // List of loaders
{
load_info_t *next;
char dllname[QMAXPATH];
char ftypename[MAX_FILE_FORMAT_NAME];
filetype_t ftype;
int pri; // 1-place first, 0-normal priority
};
// Build list of potential loaders
idaman load_info_t *ida_export build_loaders_list(linput_t *li);
// Free the list of loaders
idaman void ida_export free_loaders_list(load_info_t *list);
// Get name of loader from its DLL file.
// (for example, for PE files we will get "PE")
idaman char *ida_export get_loader_name_from_dll(char *dllname);
// Get name of loader used to load the input file into the database
// If no external loader was used, returns -1
// Otherwise copies the loader file name without the extension in the buf
// and returns its length
// (for example, for PE files we will get "PE")
idaman ssize_t ida_export get_loader_name(char *buf, size_t bufsize);
// Initialize user configurable options from the given loader
// based on the input file.
idaman bool ida_export init_loader_options(linput_t *li, load_info_t *loader);
// Load a binary file into the database.
// This function usually is called from ui.
// filename - the name of input file as is
// (if the input file is from library, then
// this is the name from the library)
// li - loader input source
// _neflags - see NEF_.. constants. For the first file
// the flag NEF_FIRST must be set.
// fileoff - Offset in the input file
// basepara - Load address in paragraphs
// binoff - Load offset (load_address=(basepara<<4)+binoff)
// nbytes - Number of bytes to load from the file
// 0 - up to the end of the file
// If nbytes is bigger than the number of
// bytes rest, the kernel will load as much
// as possible
// Returns: 1-ok, 0-failed (couldn't open the file)
idaman bool ida_export load_binary_file(
const char *filename,
linput_t *li,
ushort _neflags,
long fileoff,
ea_t basepara,
ea_t binoff,
ulong nbytes);
// Load a non-binary file into the database.
// This function usually is called from ui.
// filename - the name of input file as is
// (if the input file is from library, then
// this is the name from the library)
// li - loader input source
// sysdlldir - a directory with system dlls. Pass "." if unknown.
// _neflags - see NEF_.. constants. For the first file
// the flag NEF_FIRST must be set.
// loader - pointer to load_info_t structure.
// If the current IDP module has ph.loader != NULL
// then this argument is ignored.
// Returns: 1-ok, 0-failed
idaman bool ida_export load_nonbinary_file(
const char *filename,
linput_t *li,
const char *sysdlldir,
ushort _neflags,
load_info_t *loader);
//--------------------------------------------------------------------------
// Output file types:
typedef int ofile_type_t;
const ofile_type_t
OFILE_MAP = 0, // MAP file
OFILE_EXE = 1, // Executable file
OFILE_IDC = 2, // IDC file
OFILE_LST = 3, // Disassembly listing
OFILE_ASM = 4, // Assembly
OFILE_DIF = 5; // Difference
// Callback functions to output lines:
typedef int idaapi html_header_cb_t(FILE *fp);
typedef int idaapi html_footer_cb_t(FILE *fp);
typedef int idaapi html_line_cb_t(FILE *fp,
const char *line,
bgcolor_t prefix_color,
bgcolor_t bg_color);
#define gen_outline_t html_line_cb_t
//------------------------------------------------------------------
// Generate an output file
// otype - type of output file.
// fp - the output file handle
// ea1 - start address. For some file types this argument is ignored
// ea2 - end address. For some file types this argument is ignored
// as usual in ida, the end address of the range is not included
// flags - bit combination of GENFLG_...
// returns: number of the generated lines.
// -1 if an error occured
// ofile_exe: 0-can't generate exe file, 1-ok
idaman int ida_export gen_file(ofile_type_t otype, FILE *fp, ea_t ea1, ea_t ea2, int flags);
// 'flag' is a combination of the following:
#define GENFLG_MAPSEG 0x0001 // map: generate map of segments
#define GENFLG_MAPNAME 0x0002 // map: include dummy names
#define GENFLG_MAPDMNG 0x0004 // map: demangle names
#define GENFLG_MAPLOC 0x0008 // map: include local names
#define GENFLG_IDCTYPE 0x0008 // idc: gen only information about types
#define GENFLG_ASMTYPE 0x0010 // asm&lst: gen information about types too
#define GENFLG_GENHTML 0x0020 // asm&lst: generate html (ui_genfile_callback will be used)
#define GENFLG_ASMINC 0x0040 // asm&lst: gen information only about types
//----------------------------------------------------------------------
// Helper functions for the loaders & ui
//----------------------------------------------------------------------
// Load portion of file into the database
// This function will include (ea1..ea2) into the addressing space of the
// program (make it enabled)
// li - pointer ot input source
// pos - position in the file
// (ea1..ea2) - range of destination linear addresses
// patchable - should the kernel remember correspondance of
// file offsets to linear addresses.
// returns: 1-ok,0-read error, a warning is displayed
idaman int ida_export file2base(linput_t *li,
long pos,
ea_t ea1,
ea_t ea2,
int patchable);
#define FILEREG_PATCHABLE 1 // means that the input file may be
// patched (i.e. no compression,
// no iterated data, etc)
#define FILEREG_NOTPATCHABLE 0 // the data is kept in some encoded
// form in the file.
// Load database from the memory.
// memptr - pointer to buffer with bytes
// (ea1..ea2) - range of destination linear addresses
// fpos - position in the input file the data is taken from.
// if == -1, then no file position correspond to the data.
// This function works for wide byte processors too.
// returns: always 1
idaman int ida_export mem2base(const void *memptr,ea_t ea1,ea_t ea2,long fpos);
// Unload database to a binary file.
// fp - pointer to file
// pos - position in the file
// (ea1..ea2) - range of source linear addresses
// This function works for wide byte processors too.
// returns: 1-ok(always), write error leads to immediate exit
idaman int ida_export base2file(FILE *fp,long pos,ea_t ea1,ea_t ea2);
// Load information from DBG file into the database
// li - handler to opened input. If NULL, then fname is checked
// lname - name of loader module without extension and path
// fname - name of file to load (only if fp == NULL)
// is_remote - is the file located on a remote computer with
// the debugger server?
// Returns: 1-ok, 0-error (message is displayed)
idaman int ida_export load_loader_module(linput_t *li,
const char *lname,
const char *fname,
bool is_remote);
// Add long comment at inf.minEA:
// Input file: ....
// File format: ....
// This function should be called only from the loader to describe the input file.
idaman void ida_export create_filename_cmt(void);
// Get the input file type
// This function can recognize libraries and zip files.
idaman filetype_t ida_export get_basic_file_type(linput_t *li);
// Get name of the current file type
// The current file type is kept in inf.filetype.
// buf - buffer for the file type name
// bufsize - its size
// Returns: size of answer, this function always succeeds
idaman size_t ida_export get_file_type_name(char *buf, size_t bufsize);
//----------------------------------------------------------------------
// Work with IDS files: read and use information from them
//
// This structure is used in import_module():
struct impinfo_t
{
const char *dllname;
void (idaapi*func)(uval_t num, const char *name, uval_t node);
uval_t node;
};
// Find and import DLL module.
// This function adds information to the database (renames functions, etc)
// module - name of DLL
// windir - system directory with dlls
// modnode - node with information about imported entries
// imports by ordinals:
// altval(ord) contains linear address
// imports by name:
// supval(ea) contains the imported name
// Either altval or supval arrays may be absent.
// The node should never be deleted.
// importer- callback function (may be NULL):
// check dll module
// call 'func' for all exported entries in the file
// fp - pointer to file opened in binary mode.
// file position is 0.
// ud - pointer to impinfo_t structure
// this function checks that 'dllname' match the name of module
// if not, it returns 0
// otherwise it calls 'func' for each exported entry
// if dllname==NULL then 'func' will be called with num==0 and name==dllname
// and returns:
// 0 - dllname doesn't match, should continue
// 1 - ok
// ostype - type of operating system (subdir name)
// NULL means the IDS directory itself (not recommended)
idaman void ida_export import_module(const char *module,
const char *windir,
uval_t modnode,
int (idaapi*importer)(linput_t *li,impinfo_t *ii),
const char *ostype);
// Load and apply IDS file
// fname - name of file to apply
// This function loads the specified IDS file and applies it to the database
// If the program imports functions from a module with the same name
// as the name of the ids file being loaded, then only functions from this
// module will be affected. Otherwise (i.e. when the program does not import
// a module with this name) any function in the program may be affected.
// Returns:
// 1 - ok
// 0 - some error (a message is displayed)
// if the ids file does not exist, no message is displayed
idaman int ida_export load_ids_module(char *fname);
//----------------------------------------------------------------------
// DEFINITION OF PLUGIN MODULES
//----------------------------------------------------------------------
// A plugin is a module in plugins subdirectory which can be called by
// pressing a hotkey. It usually performs an action asked by the user.
class plugin_t
{
public:
int version; // Should be equal to IDP_INTERFACE_VERSION
int flags; // Features of the plugin:
#define PLUGIN_MOD 0x0001 // Plugin changes the database.
// IDA won't call the plugin if
// the processor prohibited any changes
// by setting PR_NOCHANGES in processor_t.
#define PLUGIN_DRAW 0x0002 // IDA should redraw everything after calling
// the plugin
#define PLUGIN_SEG 0x0004 // Plugin may be applied only if the
// current address belongs to a segment
#define PLUGIN_UNL 0x0008 // Unload the plugin immediately after
// calling 'run'.
// This flag may be set anytime.
// The kernel checks it after each call to 'run'
// The main purpose of this flag is to ease
// the debugging of new plugins.
#define PLUGIN_HIDE 0x0010 // Plugin should not appear in the Edit, Plugins menu
// This flag is checked at the start
#define PLUGIN_DBG 0x0020 // A debugger plugin. init() should put
// the address of debugger_t to dbg
// See idd.hpp for details
#define PLUGIN_PROC 0x0040 // Load plugin when a processor module is loaded and keep it
// until the processor module is unloaded
#define PLUGIN_FIX 0x0080 // Load plugin when IDA starts and keep it in the
// memory until IDA stops
int (idaapi* init)(void); // Initialize plugin
#define PLUGIN_SKIP 0 // Plugin doesn't want to be loaded
#define PLUGIN_OK 1 // Plugin agrees to work with the current database
// It will be loaded as soon as the user presses the hotkey
#define PLUGIN_KEEP 2 // Plugin agrees to work with the current database
// and wants to stay in the memory
void (idaapi* term)(void); // Terminate plugin. This function will be called
// when the plugin is unloaded. May be NULL.
void (idaapi* run)(int arg); // Invoke plugin
char *comment; // Long comment about the plugin
// it could appear in the status line
// or as a hint
char *help; // Multiline help about the plugin
char *wanted_name; // The preferred short name of the plugin
char *wanted_hotkey; // The preferred hotkey to run the plugin
};
extern "C" plugin_t PLUGIN; // (declaration for plugins)
//--------------------------------------------------------------------------
// A plugin can hook to the notification point and receive notifications
// of all major events in IDA. The callback function will be called
// for each event. The parameters of the callback:
// user_data - data supplied in call to hook_to_notification_point()
// notification_code - idp_notify or ui_notification_t code, depending on
// the hoot type
// va - additional parameters supplied with the notification
// see the event descriptions for information
// The callback should return:
// 0 - ok, the event should be processed further
// !=0 - the event is blocked and should be discarded
// in the case of processor modules, the returned value is used
// as the return value of notify()
typedef int idaapi hook_cb_t(void *user_data, int notification_code, va_list va);
enum hook_type_t
{
HT_IDP, // Hook to the processor module.
// The callback will receive all idp_notify events.
// See file idp.hpp for the list of events.
HT_UI, // Hook to the user interface.
// The callback will receive all ui_notification_t events.
// See file kernwin.hpp for the list of events.
HT_DBG, // Hook to the debugger.
// The callback will receive all dbg_notification_t events.
// See file dbg.hpp for the list of events.
HT_GRAPH, // Hook to the graph events
// The callback will receive all graph_notification_t events.
// See file graph.hpp for the list of events.
HT_LAST
};
idaman bool ida_export hook_to_notification_point(hook_type_t hook_type,
hook_cb_t *cb,
void *user_data);
// The plugin should unhook before being unloaded:
// (preferably in its termination function)
// Returns number of unhooked functions.
// If different callbacks have the same callback function pointer
// and user_data is not NULL, only the callback whose associated
// user defined data matchs will be removed.
idaman int ida_export unhook_from_notification_point(hook_type_t hook_type,
hook_cb_t *cb,
void *user_data = NULL);
// A well behaved processor module should call this function
// in his notify() function. If this function returns 0, then
// the processor module should process the notification itself
// Otherwise the code should be returned to the caller, like this:
//
// int code = invoke_callbacks(HT_IDP, what, va);
// if ( code ) return code;
// ...
//
idaman int ida_export invoke_callbacks(hook_type_t hook_type, int notification_code, va_list va);
// Method to generate graph notifications:
inline int idaapi grcall(int code, ...)
{
va_list va;
va_start(va, code);
int result = invoke_callbacks(HT_GRAPH, code, va);
va_end(va);
return result;
}
// Get plugin options from the command line
// If the user has specified the options in the -Oplugin_name:options
// format, them this function will return the 'options' part of it
// The 'plugin' parameter should denote the plugin name
// Returns NULL if there we no options specified
idaman const char *ida_export get_plugin_options(const char *plugin);
//--------------------------------------------------------------------------
// PLUGIN module file name extensions:
#ifdef __NT__
#ifdef __EA64__
#ifdef __AMD64__
#define PLUGIN_EXT "x64"
#else
#define PLUGIN_EXT "p64"
#endif
#else
#define PLUGIN_EXT "plw"
#endif
#endif
#ifdef __LINUX__
#ifdef __EA64__
#define PLUGIN_EXT "plx64"
#else
#define PLUGIN_EXT "plx"
#endif
#endif
#define PLUGIN_DLL "*." PLUGIN_EXT
//----------------------------------------------------------------------
// LOW LEVEL DLL LOADING FUNCTIONS
// Only the kernel should use these functions!
#define LNE_MAXSEG 10 // Max number of segments
#if 0
extern char dlldata[4096]; // Reserved place for DLL data
#define DLLDATASTART 0xA0 // Absolute offset of dlldata
extern char ldrdata[64]; // Reserved place for LOADER data
#define LDRDATASTART (DLLDATASTART+sizeof(dlldata)) // Absolute offset of ldrdata
#endif
struct idadll_t
{
void *dllinfo[LNE_MAXSEG];
void *entry; // first entry point of DLL
bool is_loaded(void) const { return dllinfo[0] != NULL; }
};
int load_dll(const char *file, idadll_t *dllmem);
// dllmem - allocated segments
// dos: segment 1 (data) isn't allocated
// Returns 0 - ok, else:
#define RE_NOFILE 1 /* No such file */
#define RE_NOTIDP 2 /* Not IDP file */
#define RE_NOPAGE 3 /* Can't load: bad segments */
#define RE_NOLINK 4 /* No linkage info */
#define RE_BADRTP 5 /* Bad relocation type */
#define RE_BADORD 6 /* Bad imported ordinal */
#define RE_BADATP 7 /* Bad relocation atype */
#define RE_BADMAP 8 /* DLLDATA offset is invalid */
void load_dll_or_die(const char *file, idadll_t *dllmem);
idaman int ida_export load_dll_or_say(const char *file, idadll_t *dllmem);
idaman void ida_export free_dll(idadll_t *dllmem);
// The processor description string should be at the offset 0x80 of the IDP file
// (the string consists of the processor types separated by colons)
#define IDP_DESC_START 0x80
#define IDP_DESC_END 0x200
idaman char *ida_export get_idp_desc(const char *file, char *buf, size_t bufsize); // Get IDP module name
//--------------------------------------------------------------------------
// IDP module file name extensions:
#ifdef __NT__
#ifdef __EA64__
#ifdef __AMD64__
#define IDP_EXT "x64"
#else
#define IDP_EXT "w64"
#endif
#else
#define IDP_EXT "w32"
#endif
#endif
#ifdef __LINUX__
#ifdef __EA64__
#define IDP_EXT "ilx64"
#else
#define IDP_EXT "ilx"
#endif
#endif
#ifdef __EA64__
#define IDP_DLL "*64." IDP_EXT
#else
#define IDP_DLL "*." IDP_EXT
#endif
//--------------------------------------------------------------------------
// Plugin information in IDA is stored in the following structure:
struct plugin_info_t
{
plugin_info_t *next; // next plugin information
char *path; // full path to the plugin
char *org_name; // original short name of the plugin
char *name; // short name of the plugin
// it will appear in the menu
ushort org_hotkey; // original hotkey to run the plugin
ushort hotkey; // current hotkey to run the plugin
int arg; // argument used to call the plugin
plugin_t *entry; // pointer to the plugin if it is already loaded
idadll_t dllmem;
int flags; // a copy of plugin_t.flags
};
// Get pointer to the list of plugins (some plugins might be listed several times
// in the list - once for each configured argument)
idaman plugin_info_t *ida_export get_plugins(void);
// Load a user-defined plugin
// name - short plugin name without path and extension
// or absolute path to the file name
// Returns: pointer to plugin description block
idaman plugin_t *ida_export load_plugin(const char *name);
// Run a loaded plugin with the specified argument
// ptr - pointer to plugin description block
// arg - argument to run with
idaman bool ida_export run_plugin(plugin_t *ptr, int arg);
// Load & run a plugin
inline bool idaapi load_and_run_plugin(const char *name, int arg)
{
return run_plugin(load_plugin(name), arg);
}
// Run a plugin as configured
// ptr - pointer to plugin information block
idaman bool ida_export invoke_plugin(plugin_info_t *ptr);
// Information for the user interface about available debuggers
struct dbg_info_t
{
plugin_info_t *pi;
struct debugger_t *dbg;
dbg_info_t(plugin_info_t *_pi, struct debugger_t *_dbg) : pi(_pi), dbg(_dbg) {}
};
idaman size_t ida_export get_debugger_plugins(const dbg_info_t **array);
// Initialize plugins with the specified flag
idaman void ida_export init_plugins(int flag);
// Terminate plugins with the specified flag
idaman void ida_export term_plugins(int flag);
//------------------------------------------------------------------------
//
// work with file regions (for patching)
//
void init_fileregions(void); // called by the kernel
void term_fileregions(void); // called by the kernel
inline void save_fileregions(void) {} // called by the kernel
void add_fileregion(ea_t ea1,ea_t ea2,long fpos); // called by the kernel
void move_fileregions(ea_t from, ea_t to, asize_t size);// called by the kernel
// Get offset in the input file which corresponds to the given ea
// If the specified ea can't be mapped into the input file offset,
// return -1.
idaman long ida_export get_fileregion_offset(ea_t ea);
// Get linear address which corresponds to the specified input file offset.
// If can't be found, then return BADADDR
idaman ea_t ida_export get_fileregion_ea(long offset);
//------------------------------------------------------------------------
// Generate an exe file (unload the database in binary form)
// fp - the output file handle
// if fp == NULL then returns:
// 1 - can generate an executable file
// 0 - can't generate an executable file
// returns: 1-ok, 0-failed
idaman int ida_export gen_exe_file(FILE *fp);
//------------------------------------------------------------------------
// Reload the input file
// This function reloads the byte values from the input file
// It doesn't modify the segmentation, names, comments, etc.
// file - name of the input file
// if file == NULL then returns:
// 1 - can reload the input file
// 0 - can't reload the input file
// is_remote - is the file located on a remote computer with
// the debugger server?
// returns: 1-ok, 0-failed
idaman int ida_export reload_file(const char *file, bool is_remote);
//------------------------------------------------------------------------
// Generate an IDC file (unload the database in text form)
// fp - the output file handle
// onlytypes - if true then generate idc about enums, structs and
// other type definitions used in the program
// returns: 1-ok, 0-failed
int local_gen_idc_file(FILE *fp, ea_t ea1, ea_t ea2, bool onlytypes);
//------------------------------------------------------------------------
// Output to a file all lines controlled by place 'pl'
// These functions are for the kernel only.
class place_t;
long print_all_places(FILE *fp,place_t *pl, html_line_cb_t *line_cb = NULL);
extern html_line_cb_t save_text_line;
long idaapi print_all_structs(FILE *fp, html_line_cb_t *line_cb = NULL);
long idaapi print_all_enums(FILE *fp, html_line_cb_t *line_cb = NULL);
//--------------------------------------------------------------------------
//
// KERNEL ONLY functions & data
//
idaman ida_export_data char command_line_file[QMAXPATH]; // full path to the file specified in the command line
idaman ida_export_data char database_idb[QMAXPATH]; // full path of IDB file
extern char database_id0[QMAXPATH]; // full path of original ID0 file (not exported)
idaman bool ida_export is_database_ext(const char *ext); // check the file extension
extern ulong ida_database_memory; // Database buffer size in bytes.
idaman ulong ida_export_data database_flags; // close_database() will:
#define DBFL_KILL 0x01 // delete unpacked database
#define DBFL_COMP 0x02 // compress database
#define DBFL_BAK 0x04 // create backup file
// (only if idb file is created)
#define DBFL_TEMP 0x08 // temporary database
inline bool is_temp_database(void) { return (database_flags & DBFL_TEMP) != 0; }
extern bool pe_create_idata;
extern bool pe_load_resources;
extern bool pe_create_flat_group;
// database check codes
typedef int dbcheck_t;
const dbcheck_t
DBCHK_NONE = 0, // database doesn't exist
DBCHK_OK = 1, // database exists
DBCHK_BAD = 2, // database exists but we can't use it
DBCHK_NEW = 3; // database exists but we the user asked to destroy it
dbcheck_t check_database(const char *file);
int open_database(bool isnew, const char *file, ulong input_size, bool is_temp_database);
// returns 'waspacked'
idaman int ida_export flush_buffers(void); // Flush buffers to disk
idaman void ida_export save_database(const char *outfile, bool delete_unpacked);
// Flush buffers and make
// a copy of database
void close_database(void); // see database_flags
bool compress_btree(const char *btree_file); // (internal) compress .ID0
bool get_input_file_from_archive(char *filename, size_t namesize, bool is_remote, char **temp_file_ptr);
bool loader_move_segm(ea_t from, ea_t to, asize_t size, bool keep);
int generate_ida_copyright(FILE *fp, const char *cmt, html_line_cb_t *line_cb);
bool is_in_loader(void);
void get_ids_filename(char *buf,
size_t bufsize,
const char *idsname,
const char *ostype,
bool *use_ordinals,
char **autotils,
int maxtils);
#pragma pack(pop)
#endif
| 40.183807 | 113 | 0.577135 | erithion |
3da1c05933f3c5acf281a50e6a045e021950367e | 6,523 | cpp | C++ | source/Neuron.cpp | It4innovations/PESOM | e6e82b9eb65d89a1a4c8fc624da3f125cc3ecb1e | [
"BSD-3-Clause"
] | null | null | null | source/Neuron.cpp | It4innovations/PESOM | e6e82b9eb65d89a1a4c8fc624da3f125cc3ecb1e | [
"BSD-3-Clause"
] | null | null | null | source/Neuron.cpp | It4innovations/PESOM | e6e82b9eb65d89a1a4c8fc624da3f125cc3ecb1e | [
"BSD-3-Clause"
] | null | null | null | #include "Neuron.h"
#include <stdlib.h>
#include <time.h>
#include <math.h>
Neuron::Neuron(int x, int y, int pocetVstupu, int seedNeuron,int poziceVNeuronovesiti, double Mink)
{
srand(seedNeuron);
LIMITITERACE = 50;
ZERO= 0.0000000001;
vahy=new double[pocetVstupu];
nonZeroVahy = new int[pocetVstupu];
seznamNenulAll = new bool[pocetVstupu];
//0=x, 1=y
souradnice[0]=x;
souradnice[1]=y;
poziceVRikosti=poziceVNeuronovesiti;
MinkowskehoNumber=Mink;
numberOfdimension=pocetVstupu;
numberOfseznamNenul=0;
VahyX = 0;
nonZeroCount = 0;
VstupY = 0.0;
for (int i = 0; i < pocetVstupu; i++)
{
vahy[i]=r2();
VahyX += vahy[i] * vahy[i];
nonZeroVahy[i] = i;
seznamNenulAll[i]=false;
}
nonZeroCount = pocetVstupu;
}
Neuron::Neuron(int x, int y)
{
LIMITITERACE = 50;
ZERO= 0.0000000001;
souradnice[0]=x;
souradnice[1]=y;
numberOfseznamNenul=0;
VahyX = 0;
nonZeroCount = 0;
VstupY = 0.0;
}
Neuron::~Neuron(void)
{
delete vahy;
delete nonZeroVahy;
delete seznamNenulAll;
}
double Neuron::Minkowskeho(void)
{
double suma = 0;
double pom = 0;
int coutner = 0;
for (int i = 0; i < numberOfdimension; i++)
{
if (i == seznamNenul[coutner])
{
pom = vstupy[coutner] - vahy[i];
suma += pow(abs(pom),MinkowskehoNumber);
coutner++;
if (coutner == numberOfseznamNenul)
coutner = 0;
}
else
{
suma += pow(vahy[i],MinkowskehoNumber);
}
}
return pow(suma,1/MinkowskehoNumber);// sqrt(suma);
}
double Neuron::Euklid2(void)
{
if(cosin)
return Cosin2();
else
{
double suma = 0;
int pocet = numberOfseznamNenul;
for (int i = 0; i < pocet; i++)
{
suma -= 2 * vstupy[i] * vahy[seznamNenul[i]];
}
suma += VahyX;
suma += VstupY;
return sqrt(suma);
}
}
double Neuron::Cosin2()
{
double suma = 0;
int pocet = numberOfseznamNenul;
for (int i = 0; i < pocet; i++)
{
suma += vstupy[i] * vahy[seznamNenul[i]];
}
return 1-(suma/(sqrt(VahyX)*sqrt(VstupY)));
}
bool Neuron::UpdateWeigh(int coordinatesOfWinnerX,int coordinatesOfWinnerY, double fiNa2, double learningRatio)
{
bool jeVetsiVahaNez0 = false;
//Potrebuji vzdalenost mezi prvky
int rozdilX = souradnice[0] - coordinatesOfWinnerX;
int rozdilY = souradnice[1] - coordinatesOfWinnerY;
//Nedelam odmocninu protoze pro dalsi vypocty potrebuji mit euklida ^2
float euklid = rozdilX * rozdilX + rozdilY * rozdilY;
if (euklid < fiNa2)
{
int counter = 0;
int maxCounte = numberOfseznamNenul;
double omega = exp(-(double)euklid / (2 * fiNa2));
omega *= learningRatio; //zmena
int pocet = numberOfdimension;
// double pomocnaNasob = 0;
counter = Compute(counter, maxCounte, omega, pocet);
}
return jeVetsiVahaNez0;
}
int Neuron::Compute(int counter, int maxCounte, double omega, int count)
{
VahyX = 0;
for (int i = 0; i < numberOfseznamNenul; i++)
{
seznamNenulAll[seznamNenul[i]] = true;
}
int tmpNonZero = 0;
for (int i = 0; i < nonZeroCount; i++)
{
int index = nonZeroVahy[i];
if (seznamNenulAll[index]) continue;
double vahyI = vahy[index];
vahyI -= omega * vahyI;
if (vahyI < ZERO)
{
vahy[index] = 0;
}
else
{
VahyX += vahyI * vahyI;
nonZeroVahy[tmpNonZero] = index;
tmpNonZero++;
vahy[index] = vahyI;
}
}
for (int i = 0; i < numberOfseznamNenul; i++)
{
int index = seznamNenul[i];
double vahyI = vahy[index];
vahyI += omega * (vstupy[i] - vahyI);
VahyX += vahyI * vahyI;
vahy[index] = vahyI;
seznamNenulAll[index] = false;
nonZeroVahy[tmpNonZero] = index;
tmpNonZero++;
}
nonZeroCount = tmpNonZero;
return counter;
}
void Neuron::RecalculateWeight(void)
{
VahyX = 0;
for (int i = 0; i < numberOfdimension; i++)
{
VahyX += vahy[i] * vahy[i];
}
}
int Neuron::GetNumberOfZero(void)
{
int result = 0;
for (int i = 0; i < numberOfdimension; i++)
{
if (vahy[i] < ZERO)
result++;
}
return result;
}
double Neuron::r2(void)
{
return (double)0.6+(((double)rand() / (double)RAND_MAX)/100) ;
}
double Neuron::RidkostVypocet(int x)
{
return ((double)pocetNulvEpochach[x]) / numberOfdimension;
}
double Neuron::EuklidMikowsky(void)
{
if (gngCosin)
return Cosin();
double suma = 0;
double pom = 0;
for (int i = 0; i < numberOfdimension; i++)
{
pom = vstupy[i] - vahy[i];
suma += pow(abs(pom), gngMinkowskehoNumber);
}
return pow(suma, 1 / gngMinkowskehoNumber);// sqrt(suma);
}
double Neuron::Euklid(void)
{
double suma = 0;
double pom = 0;
for (int i = 0; i < numberOfdimension; i++)
{
pom = vstupy[i] - vahy[i];
suma +=pom*pom;
}
return sqrt(suma);
}
double Neuron::Cosin()
{
double suma = 0;
// int pocet = numberOfseznamNenul;
double vs=0;
double va=0;
for (int i = 0; i < numberOfdimension; i++)
{
suma += vstupy[i] * vahy[i];
va+=vahy[i]*vahy[i];
vs+=vstupy[i] *vstupy[i];
}
return 1-(suma/(sqrt(va)*sqrt(vs)));
} | 24.430712 | 112 | 0.479074 | It4innovations |
3da1ed6ca101bd811623e8f9480527f1509ef6c6 | 3,777 | cpp | C++ | src/Library/Geometry/TriangleMeshLoaderBezier.cpp | aravindkrishnaswamy/rise | 297d0339a7f7acd1418e322a30a21f44c7dbbb1d | [
"BSD-2-Clause"
] | 1 | 2018-12-20T19:31:02.000Z | 2018-12-20T19:31:02.000Z | src/Library/Geometry/TriangleMeshLoaderBezier.cpp | aravindkrishnaswamy/rise | 297d0339a7f7acd1418e322a30a21f44c7dbbb1d | [
"BSD-2-Clause"
] | null | null | null | src/Library/Geometry/TriangleMeshLoaderBezier.cpp | aravindkrishnaswamy/rise | 297d0339a7f7acd1418e322a30a21f44c7dbbb1d | [
"BSD-2-Clause"
] | null | null | null | //////////////////////////////////////////////////////////////////////
//
// TriangleMeshLoaderBezier.cpp - Implementation of the bezier mesh
// loader
//
// Author: Aravind Krishnaswamy
// Date of Birth: August 7, 2002
// Tabs: 4
// Comments:
//
// License Information: Please see the attached LICENSE.TXT file
//
//////////////////////////////////////////////////////////////////////
#include "pch.h"
#include "TriangleMeshLoaderBezier.h"
#include "BezierTesselation.h"
#include "GeometryUtilities.h"
#include "../Interfaces/ILog.h"
#include "../Utilities/MediaPathLocator.h"
#include <stdio.h>
using namespace RISE;
using namespace RISE::Implementation;
TriangleMeshLoaderBezier::TriangleMeshLoaderBezier(
const char * szFile,
const unsigned int detail,
const bool bCombineSharedVertices_,
const bool bCenterObject_,
const IFunction2D* displacement_,
Scalar disp_scale_
) :
nDetail( detail ),
bCombineSharedVertices( bCombineSharedVertices_ ),
bCenterObject( bCenterObject_ ),
displacement( displacement_ ),
disp_scale( disp_scale_ )
{
strncpy( szFilename, GlobalMediaPathLocator().Find(szFile).c_str(), 256 );
}
TriangleMeshLoaderBezier::~TriangleMeshLoaderBezier( )
{
}
bool TriangleMeshLoaderBezier::LoadTriangleMesh( ITriangleMeshGeometryIndexed* pGeom )
{
FILE* inputFile = fopen( szFilename, "r" );
if( !inputFile || !pGeom ) {
GlobalLog()->Print( eLog_Error, "TriangleMeshLoaderBezier:: Failed to open file or bad geometry object" );
return false;
}
pGeom->BeginIndexedTriangles();
char line[4096];
if( fgets( (char*)&line, 4096, inputFile ) != NULL )
{
// Read that first line, it tells us how many
// patches are dealing with here
unsigned int numPatches = 0;
sscanf( line, "%u", &numPatches );
BezierPatchesListType patches;
for( unsigned int i=0; i<numPatches; i++ )
{
// We assume every 16 lines gives us a patch
BezierPatch patch;
for( int j=0; j<4; j++ ) {
for( int k=0; k<4; k++ ) {
double x, y, z;
if( fscanf( inputFile, "%lf %lf %lf", &x, &y, &z ) == EOF ) {
GlobalLog()->PrintSourceError( "TriangleMeshLoaderBezier:: Fatal error while reading file. Nothing will be loaded", __FILE__, __LINE__ );
return false;
}
patch.c[j].pts[k] = Point3( x, y, z );
}
}
patches.push_back( patch );
}
GlobalLog()->PrintEx( eLog_Event, "TriangleMeshLoaderBezier:: Tesselating %u bezier patches...", numPatches );
// Now tesselate all the patches together and then add them to
// the geometry object
IndexTriangleListType indtris;
VerticesListType vertices;
NormalsListType normals;
TexCoordsListType coords;
GeneratePolygonsFromBezierPatches( indtris, vertices, normals, coords, patches, nDetail );
if( bCombineSharedVertices ) {
GlobalLog()->PrintEx( eLog_Event, "TriangleMeshLoaderBezier:: Attempting to combine shared vertices..." );
CombineSharedVerticesFromGrids( indtris, vertices, numPatches, nDetail, nDetail );
}
CalculateVertexNormals( indtris, normals, vertices );
if( bCenterObject ) {
CenterObject( vertices );
}
if( displacement ) {
RemapTextureCoords( coords );
ApplyDisplacementMapToObject( indtris, vertices, normals, coords, *displacement, disp_scale );
// After applying displacement, recalculate the vertex normals
normals.clear();
CalculateVertexNormals( indtris, normals, vertices );
}
pGeom->AddVertices( vertices );
pGeom->AddNormals( normals );
pGeom->AddTexCoords( coords );
pGeom->AddIndexedTriangles( indtris );
GlobalLog()->PrintEx( eLog_Event, "TriangleMeshGeometryIndexed:: Constructing acceleration structures for %u triangles", indtris.size() );
}
pGeom->DoneIndexedTriangles();
fclose( inputFile );
return true;
}
| 27.977778 | 144 | 0.684141 | aravindkrishnaswamy |
3da66e690e2ea299c2e5817726855ce0f508c9de | 5,011 | cpp | C++ | tests/src/core/testqgssettings.cpp | dyna-mis/Hilabeling | cb7d5d4be29624a20c8a367162dbc6fd779b2b52 | [
"MIT"
] | null | null | null | tests/src/core/testqgssettings.cpp | dyna-mis/Hilabeling | cb7d5d4be29624a20c8a367162dbc6fd779b2b52 | [
"MIT"
] | null | null | null | tests/src/core/testqgssettings.cpp | dyna-mis/Hilabeling | cb7d5d4be29624a20c8a367162dbc6fd779b2b52 | [
"MIT"
] | 1 | 2021-12-25T08:40:30.000Z | 2021-12-25T08:40:30.000Z | /***************************************************************************
testqgssettings.cpp
--------------------------------------
Date : 17.02.2018
Copyright : (C) 2018 by Denis Rouzaud
Email : denis.rouzaud@gmail.com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include <QObject>
#include "qgssettings.h"
#include "qgsunittypes.h"
#include "qgsmaplayerproxymodel.h"
#include "qgstest.h"
/**
* \ingroup UnitTests
* This is a unit test for the operations on curve geometries
*/
class TestQgsSettings : public QObject
{
Q_OBJECT
private slots:
void enumValue();
void flagValue();
};
void TestQgsSettings::enumValue()
{
QgsSettings settings;
// assign to inexisting value
settings.setValue( QStringLiteral( "qgis/testing/my_value_for_units" ), -1 );
settings.setValue( QStringLiteral( "qgis/testing/my_value_for_units_as_string" ), QStringLiteral( "myString" ) );
// just to be sure it really doesn't exist
QVERIFY( static_cast<int>( QgsUnitTypes::LayoutMeters ) != -1 );
// standard method returns invalid value
int v1 = settings.value( QStringLiteral( "qgis/testing/my_value_for_units" ), QgsUnitTypes::LayoutMeters ).toInt();
QCOMPARE( v1, -1 );
// enum method returns default value if current setting is incorrect
QgsUnitTypes::LayoutUnit v2 = settings.enumValue( QStringLiteral( "qgis/testing/my_value_for_units" ), QgsUnitTypes::LayoutMeters );
QCOMPARE( v2, QgsUnitTypes::LayoutMeters );
QgsUnitTypes::LayoutUnit v2s = settings.enumValue( QStringLiteral( "qgis/testing/my_value_for_units_as_string" ), QgsUnitTypes::LayoutMeters );
QCOMPARE( v2s, QgsUnitTypes::LayoutMeters );
// test a different value than default
settings.setValue( QStringLiteral( "qgis/testing/my_value_for_units" ), QgsUnitTypes::LayoutCentimeters );
QgsUnitTypes::LayoutUnit v3 = settings.enumValue( QStringLiteral( "qgis/testing/my_value_for_units" ), QgsUnitTypes::LayoutMeters );
QCOMPARE( v3, QgsUnitTypes::LayoutCentimeters );
settings.setEnumValue( QStringLiteral( "qgis/testing/my_value_for_units" ), QgsUnitTypes::LayoutCentimeters );
// auto conversion of old settings (int to str)
QCOMPARE( settings.value( "qgis/testing/my_value_for_units" ).toString(), QStringLiteral( "LayoutCentimeters" ) );
QgsUnitTypes::LayoutUnit v3s = settings.enumValue( QStringLiteral( "qgis/testing/my_value_for_units" ), QgsUnitTypes::LayoutMeters );
QCOMPARE( v3s, QgsUnitTypes::LayoutCentimeters );
QString v3ss = settings.value( QStringLiteral( "qgis/testing/my_value_for_units" ), QStringLiteral( "myDummyValue" ) ).toString();
QCOMPARE( v3ss, QStringLiteral( "LayoutCentimeters" ) );
}
void TestQgsSettings::flagValue()
{
QgsSettings settings;
QgsMapLayerProxyModel::Filters pointAndLine = QgsMapLayerProxyModel::Filters( QgsMapLayerProxyModel::PointLayer | QgsMapLayerProxyModel::LineLayer );
QgsMapLayerProxyModel::Filters pointAndPolygon = QgsMapLayerProxyModel::Filters( QgsMapLayerProxyModel::PointLayer | QgsMapLayerProxyModel::PolygonLayer );
settings.setValue( QStringLiteral( "qgis/testing/my_value_for_a_flag" ), 1e8 ); // invalid
QgsMapLayerProxyModel::Filters v4 = settings.enumValue( QStringLiteral( "qgis/testing/my_value_for_a_flag" ), pointAndLine );
QCOMPARE( v4, pointAndLine );
settings.setValue( QStringLiteral( "qgis/testing/my_value_for_a_flag" ), static_cast<int>( pointAndPolygon ) );
QgsMapLayerProxyModel::Filters v5 = settings.flagValue( QStringLiteral( "qgis/testing/my_value_for_a_flag" ), pointAndLine, QgsSettings::NoSection );
QCOMPARE( v5, pointAndPolygon );
// auto conversion of old settings (int to str)
QCOMPARE( settings.value( "qgis/testing/my_value_for_a_flag" ).toString(), QStringLiteral( "PointLayer|PolygonLayer" ) );
settings.setFlagValue( QStringLiteral( "qgis/testing/my_value_for_a_flag_as_string" ), pointAndPolygon, QgsSettings::NoSection );
QgsMapLayerProxyModel::Filters v5s = settings.flagValue( QStringLiteral( "qgis/testing/my_value_for_a_flag_as_string" ), pointAndLine, QgsSettings::NoSection );
QCOMPARE( v5s, pointAndPolygon );
QString v5ss = settings.value( QStringLiteral( "qgis/testing/my_value_for_a_flag_as_string" ), QStringLiteral( "myDummyString" ), QgsSettings::NoSection ).toString();
QCOMPARE( v5ss, QStringLiteral( "PointLayer|PolygonLayer" ) );
}
QGSTEST_MAIN( TestQgsSettings )
#include "testqgssettings.moc"
| 52.197917 | 168 | 0.688086 | dyna-mis |
3daa5b67d974d6136ba7b6af85504733dc91a5f2 | 7,166 | cpp | C++ | applications/mne_scan/plugins/natus/natusproducer.cpp | Andrey1994/mne-cpp | 6264b1107b9447b7db64309f73f09e848fd198c4 | [
"BSD-3-Clause"
] | 2 | 2021-11-16T19:38:12.000Z | 2021-11-18T20:52:08.000Z | applications/mne_scan/plugins/natus/natusproducer.cpp | Andrey1994/mne-cpp | 6264b1107b9447b7db64309f73f09e848fd198c4 | [
"BSD-3-Clause"
] | null | null | null | applications/mne_scan/plugins/natus/natusproducer.cpp | Andrey1994/mne-cpp | 6264b1107b9447b7db64309f73f09e848fd198c4 | [
"BSD-3-Clause"
] | 1 | 2021-11-16T19:39:01.000Z | 2021-11-16T19:39:01.000Z | //=============================================================================================================
/**
* @file natusproducer.cpp
* @author Gabriel B Motta <gabrielbenmotta@gmail.com>;
* Lorenz Esch <lesch@mgh.harvard.edu>
* @version dev
* @date June, 2018
*
* @section LICENSE
*
* Copyright (C) 2018, Gabriel B Motta, Lorenz Esch. 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 MNE-CPP authors nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
* @brief Contains the definition of the NatusProducer class.
*
*/
//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include "natusproducer.h"
#include <iostream>
//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
#include <QDebug>
#include <QDataStream>
#include <QScopedArrayPointer>
//*************************************************************************************************************
//=============================================================================================================
// EIGEN INCLUDES
//=============================================================================================================
//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace NATUSPLUGIN;
using namespace Eigen;
//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================
NatusProducer::NatusProducer(int iBlockSize, int iChannelSize, QObject *parent)
: QObject(parent)
, m_iMatDataSampleIterator(1)
{
//qRegisterMetaType<Eigen::MatrixXd>();
//Init socket
m_pUdpSocket = QSharedPointer<QUdpSocket>(new QUdpSocket(this));
m_pUdpSocket->bind(QHostAddress::AnyIPv4, 50000);
connect(m_pUdpSocket.data(), &QUdpSocket::readyRead,
this, &NatusProducer::readPendingDatagrams);
m_matData.resize(iChannelSize, iBlockSize);
m_fSampleFreq = 0;
m_fChannelSize = 0;
}
//*************************************************************************************************************
void NatusProducer::readPendingDatagrams()
{
while (m_pUdpSocket->hasPendingDatagrams()) {
QNetworkDatagram datagram = m_pUdpSocket->receiveDatagram();
//qDebug() << "Datagram on port 50000 from IP "<<datagram.senderAddress();
processDatagram(datagram);
}
}
//*************************************************************************************************************
void NatusProducer::processDatagram(const QNetworkDatagram &datagram)
{
QByteArray data = datagram.data();
QDataStream stream(data);
// Read info
float fPackageNumber, fNumberSamples, fNumberChannels;
char cInfo[3*sizeof(float)];
stream.readRawData(cInfo, sizeof(cInfo));
float* fInfo = reinterpret_cast<float*>(cInfo);
fPackageNumber = fInfo[0];
fNumberSamples = fInfo[1];
fNumberChannels = fInfo[2];
// // Print info about received data
// qDebug()<<"fPackageNumber "<<fPackageNumber;
// qDebug()<<"fNumberSamples "<<fNumberSamples;
// qDebug()<<"fNumberChannels "<<fNumberChannels;
// qDebug()<<"data.size() "<<data.size();
// qDebug()<<"data.size() "<<data.size();
// qDebug()<<"data.size() "<<data.size();
// Read actual data
int iDataSize = int(fNumberSamples * fNumberChannels);
QScopedArrayPointer<char> cData(new char[iDataSize*sizeof(float)]);
//char *cData = new char[iDataSize*sizeof(float)];
stream.readRawData(cData.data(), iDataSize*sizeof(float));
float* fData = reinterpret_cast<float*>(cData.data());
//Get data
Eigen::MatrixXf matData;
matData.resize(fNumberChannels, fNumberSamples);
int itr = 0;
for(int j = 0; j < fNumberSamples; ++j) {
for(int i = 0; i < fNumberChannels; ++i) {
matData(i,j) = fData[itr++]/10e06;
}
}
if(m_iMatDataSampleIterator+matData.cols() <= m_matData.cols()) {
m_matData.block(0, m_iMatDataSampleIterator, matData.rows(), matData.cols()) = matData.cast<double>();
m_iMatDataSampleIterator += matData.cols();
} else {
m_matData.block(0, m_iMatDataSampleIterator, matData.rows(), m_matData.cols()-m_iMatDataSampleIterator) = matData.block(0, 0, matData.rows(), m_matData.cols()-m_iMatDataSampleIterator).cast<double>();
m_iMatDataSampleIterator = 0;
}
//qDebug() << "m_iMatDataSampleIterator" << m_iMatDataSampleIterator;
if(m_iMatDataSampleIterator == m_matData.cols()) {
m_iMatDataSampleIterator = 0;
//qDebug()<<"Emit data";
MatrixXd matEmit = m_matData.cast<double>();
emit newDataAvailable(matEmit);
}
}
| 42.152941 | 208 | 0.503768 | Andrey1994 |
3dac70154b3cf3642d5b6cde7005fdae00c73bbc | 24,055 | cpp | C++ | glib-adv/aest.cpp | ksemer/snap | 0084126c30ad49a4437bc8ea30be78484f8c58d7 | [
"BSD-3-Clause"
] | 1,805 | 2015-01-06T20:01:35.000Z | 2022-03-29T16:12:51.000Z | glib-adv/aest.cpp | lizhaoqing/snap | 907c34aac6bcddc7c2f8efb64be76e87dd7e4ea5 | [
"BSD-3-Clause"
] | 168 | 2015-01-07T22:57:29.000Z | 2022-03-15T01:20:24.000Z | glib-adv/aest.cpp | lizhaoqing/snap | 907c34aac6bcddc7c2f8efb64be76e87dd7e4ea5 | [
"BSD-3-Clause"
] | 768 | 2015-01-09T02:28:45.000Z | 2022-03-30T00:53:46.000Z | /////////////////////////////////////////////////
// Attribute-Estimator
PAttrEst TAttrEst::Load(TSIn& SIn){
TStr TypeNm(SIn);
if (TypeNm==TTypeNm<TAttrEstRnd>()){return new TAttrEstRnd(SIn);}
else if (TypeNm==TTypeNm<TAttrEstIGain>()){return new TAttrEstIGain(SIn);}
else if (TypeNm==TTypeNm<TAttrEstIGainNorm>()){return new TAttrEstIGainNorm(SIn);}
else if (TypeNm==TTypeNm<TAttrEstIGainRatio>()){return new TAttrEstIGainRatio(SIn);}
else if (TypeNm==TTypeNm<TAttrEstMantarasDist>()){return new TAttrEstMantarasDist(SIn);}
else if (TypeNm==TTypeNm<TAttrEstMdl>()){return new TAttrEstMdl(SIn);}
else if (TypeNm==TTypeNm<TAttrEstGStat>()){return new TAttrEstGStat(SIn);}
else if (TypeNm==TTypeNm<TAttrEstChiSquare>()){return new TAttrEstChiSquare(SIn);}
else if (TypeNm==TTypeNm<TAttrEstOrt>()){return new TAttrEstOrt(SIn);}
else if (TypeNm==TTypeNm<TAttrEstGini>()){return new TAttrEstGini(SIn);}
else if (TypeNm==TTypeNm<TAttrEstWgtEvd>()){return new TAttrEstWgtEvd(SIn);}
else if (TypeNm==TTypeNm<TAttrEstTextWgtEvd>()){return new TAttrEstTextWgtEvd(SIn);}
else if (TypeNm==TTypeNm<TAttrEstOddsRatio>()){return new TAttrEstOddsRatio(SIn);}
else if (TypeNm==TTypeNm<TAttrEstWgtOddsRatio>()){return new TAttrEstWgtOddsRatio(SIn);}
else if (TypeNm==TTypeNm<TAttrEstCondOddsRatio>()){return new TAttrEstCondOddsRatio(SIn);}
else if (TypeNm==TTypeNm<TAttrEstLogPRatio>()){return new TAttrEstLogPRatio(SIn);}
else if (TypeNm==TTypeNm<TAttrEstExpPDiff>()){return new TAttrEstExpPDiff(SIn);}
else if (TypeNm==TTypeNm<TAttrEstMutInf>()){return new TAttrEstMutInf(SIn);}
else if (TypeNm==TTypeNm<TAttrEstCrossEnt>()){return new TAttrEstCrossEnt(SIn);}
else if (TypeNm==TTypeNm<TAttrEstTermFq>()){return new TAttrEstTermFq(SIn);}
else {Fail; return NULL;}
}
PTbValDs TAttrEst::GetCSValDs(const int& AttrN, const int& SplitN,
const PTbValSplit& ValSplit, const PDmDs& DmDs){
PTbValDs CSValDs=new TTbValDs(DmDs->GetCDs()->GetDscs());
for (int ValN=0; ValN<ValSplit->GetSplitVals(SplitN); ValN++){
TTbVal Val=ValSplit->GetSplitVal(SplitN, ValN);
for (int CDsc=0; CDsc<DmDs->GetCDs()->GetDscs(); CDsc++){
double ValW=DmDs->GetCAVDs(CDsc, AttrN)->GetValW(Val);
CSValDs->AddVal(CDsc, ValW);
}
}
CSValDs->Def();
return CSValDs;
}
PTbValDs TAttrEst::GetSValDs(const int& AttrN,
const PTbValSplit& ValSplit, const PDmDs& DmDs){
PTbValDs SValDs=new TTbValDs(ValSplit->GetSplits());
for (int SplitN=0; SplitN<ValSplit->GetSplits(); SplitN++){
for (int ValN=0; ValN<ValSplit->GetSplitVals(SplitN); ValN++){
TTbVal Val=ValSplit->GetSplitVal(SplitN, ValN);
double ValW=DmDs->GetAVDs(AttrN)->GetValW(Val);
SValDs->AddVal(SplitN, ValW);
}
}
SValDs->Def();
return SValDs;
}
PTbValDs TAttrEst::GetSCValDs(const int& CDsc, const int& AttrN,
const PTbValSplit& ValSplit, const PDmDs& DmDs){
PTbValDs SCValDs=new TTbValDs(ValSplit->GetSplits());
for (int SplitN=0; SplitN<ValSplit->GetSplits(); SplitN++){
for (int ValN=0; ValN<ValSplit->GetSplitVals(SplitN); ValN++){
TTbVal Val=ValSplit->GetSplitVal(SplitN, ValN);
double ValW=DmDs->GetCAVDs(CDsc, AttrN)->GetValW(Val);
SCValDs->AddVal(SplitN, ValW);
}
}
SCValDs->Def();
return SCValDs;
}
double TAttrEst::GetCEntropy(
const PDmDs& DmDs, const PDmDs& PriorDmDs, const PPrbEst& PrbEst){
double CEntropy=0;
for (int CDsc=0; CDsc<DmDs->GetCDs()->GetDscs(); CDsc++){
double CPrb=PrbEst->GetCPrb(CDsc, DmDs, PriorDmDs);
if (CPrb>0){CEntropy-=CPrb*TMath::Log2(CPrb);}
}
return CEntropy;
}
double TAttrEst::GetAEntropy(const int& AttrN, const PTbValSplit& ValSplit,
const PDmDs& DmDs, const PDmDs& PriorDmDs, const PPrbEst& PrbEst){
PTbValDs SValDs=GetSValDs(AttrN, ValSplit, DmDs);
PTbValDs PriorSValDs=GetSValDs(AttrN, ValSplit, PriorDmDs);
double AEntropy=0;
for (int SplitN=0; SplitN<ValSplit->GetSplits(); SplitN++){
double SPrb=PrbEst->GetVPrb(SplitN, SValDs, PriorSValDs);
if (SPrb>0){AEntropy-=SPrb*TMath::Log2(SPrb);}
}
return AEntropy;
}
double TAttrEst::GetCAEntropy(const int& AttrN, const PTbValSplit& ValSplit,
const PDmDs& DmDs, const PDmDs& PriorDmDs, const PPrbEst& PrbEst){
double CAEntropy=0;
for (int SplitN=0; SplitN<ValSplit->GetSplits(); SplitN++){
PTbValDs CSValDs=GetCSValDs(AttrN, SplitN, ValSplit, DmDs);
double SPrb=CSValDs->GetSumPrb(DmDs->GetSumW());
double SEntropy=0;
for (int CDsc=0; CDsc<DmDs->GetCDs()->GetDscs(); CDsc++){
double CAPrb=SPrb*PrbEst->GetVPrb(CDsc, CSValDs, PriorDmDs->GetCDs());
if (CAPrb>0){SEntropy-=CAPrb*TMath::Log2(CAPrb);}
}
CAEntropy+=SEntropy;
}
return CAEntropy;
}
PPrbEst TAttrEst::GetPrbEst(const PPrbEst& PrbEst){
if (!PrbEst.Empty()){return PrbEst;}
else {return PPrbEst(new TPrbEstRelFq());}
}
PPp TAttrEst::GetPrbEstPp(const TStr& Nm, const TStr& DNm){
PPp Pp=new TPp(Nm, DNm, ptSet);
Pp->AddPp(TPrbEst::GetPp(TTypeNm<TPrbEst>(), TPrbEst::DNm));
return Pp;
}
const TStr TAttrEst::DNm("Attribute Estimate");
PPp TAttrEst::GetPp(const TStr& Nm, const TStr& DNm){
PPp Pp=new TPp(Nm, DNm, ptSel);
Pp->AddPp(TAttrEstRnd::GetPp(TTypeNm<TAttrEstRnd>(), TAttrEstRnd::DNm));
Pp->AddPp(TAttrEstIGain::GetPp(TTypeNm<TAttrEstIGain>(), TAttrEstIGain::DNm));
Pp->AddPp(TAttrEstIGainNorm::GetPp(TTypeNm<TAttrEstIGainNorm>(), TAttrEstIGainNorm::DNm));
Pp->AddPp(TAttrEstIGainRatio::GetPp(TTypeNm<TAttrEstIGainRatio>(), TAttrEstIGainRatio::DNm));
Pp->AddPp(TAttrEstMantarasDist::GetPp(TTypeNm<TAttrEstMantarasDist>(), TAttrEstMantarasDist::DNm));
Pp->AddPp(TAttrEstMdl::GetPp(TTypeNm<TAttrEstMdl>(), TAttrEstMdl::DNm));
Pp->AddPp(TAttrEstGStat::GetPp(TTypeNm<TAttrEstGStat>(), TAttrEstGStat::DNm));
Pp->AddPp(TAttrEstChiSquare::GetPp(TTypeNm<TAttrEstChiSquare>(), TAttrEstChiSquare::DNm));
Pp->AddPp(TAttrEstOrt::GetPp(TTypeNm<TAttrEstOrt>(), TAttrEstOrt::DNm));
Pp->AddPp(TAttrEstGini::GetPp(TTypeNm<TAttrEstGini>(), TAttrEstGini::DNm));
Pp->AddPp(TAttrEstWgtEvd::GetPp(TTypeNm<TAttrEstWgtEvd>(), TAttrEstWgtEvd::DNm));
Pp->AddPp(TAttrEstTextWgtEvd::GetPp(TTypeNm<TAttrEstTextWgtEvd>(), TAttrEstTextWgtEvd::DNm));
Pp->AddPp(TAttrEstOddsRatio::GetPp(TTypeNm<TAttrEstOddsRatio>(), TAttrEstOddsRatio::DNm));
Pp->AddPp(TAttrEstWgtOddsRatio::GetPp(TTypeNm<TAttrEstWgtOddsRatio>(), TAttrEstWgtOddsRatio::DNm));
Pp->AddPp(TAttrEstCondOddsRatio::GetPp(TTypeNm<TAttrEstCondOddsRatio>(), TAttrEstCondOddsRatio::DNm));
Pp->AddPp(TAttrEstLogPRatio::GetPp(TTypeNm<TAttrEstLogPRatio>(), TAttrEstLogPRatio::DNm));
Pp->AddPp(TAttrEstExpPDiff::GetPp(TTypeNm<TAttrEstExpPDiff>(), TAttrEstExpPDiff::DNm));
Pp->AddPp(TAttrEstMutInf::GetPp(TTypeNm<TAttrEstMutInf>(), TAttrEstMutInf::DNm));
Pp->AddPp(TAttrEstCrossEnt::GetPp(TTypeNm<TAttrEstCrossEnt>(), TAttrEstCrossEnt::DNm));
Pp->AddPp(TAttrEstTermFq::GetPp(TTypeNm<TAttrEstTermFq>(), TAttrEstTermFq::DNm));
Pp->PutDfVal(TTypeNm<TAttrEstIGain>());
return Pp;
}
PAttrEst TAttrEst::New(const PPp& Pp){
if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstRnd>())){
return new TAttrEstRnd(Pp->GetSelPp());}
else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstIGain>())){
return new TAttrEstIGain(Pp->GetSelPp());}
else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstIGainNorm>())){
return new TAttrEstIGainNorm(Pp->GetSelPp());}
else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstIGainRatio>())){
return new TAttrEstIGainRatio(Pp->GetSelPp());}
else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstMantarasDist>())){
return new TAttrEstMantarasDist(Pp->GetSelPp());}
else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstMdl>())){
return new TAttrEstMdl(Pp->GetSelPp());}
else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstGStat>())){
return new TAttrEstGStat(Pp->GetSelPp());}
else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstChiSquare>())){
return new TAttrEstChiSquare(Pp->GetSelPp());}
else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstOrt>())){
return new TAttrEstOrt(Pp->GetSelPp());}
else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstGini>())){
return new TAttrEstGini(Pp->GetSelPp());}
else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstWgtEvd>())){
return new TAttrEstWgtEvd(Pp->GetSelPp());}
else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstTextWgtEvd>())){
return new TAttrEstTextWgtEvd(Pp->GetSelPp());}
else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstOddsRatio>())){
return new TAttrEstOddsRatio(Pp->GetSelPp());}
else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstWgtOddsRatio>())){
return new TAttrEstWgtOddsRatio(Pp->GetSelPp());}
else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstCondOddsRatio>())){
return new TAttrEstCondOddsRatio(Pp->GetSelPp());}
else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstLogPRatio>())){
return new TAttrEstLogPRatio(Pp->GetSelPp());}
else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstExpPDiff>())){
return new TAttrEstExpPDiff(Pp->GetSelPp());}
else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstMutInf>())){
return new TAttrEstMutInf(Pp->GetSelPp());}
else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstCrossEnt>())){
return new TAttrEstCrossEnt(Pp->GetSelPp());}
else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstTermFq>())){
return new TAttrEstTermFq(Pp->GetSelPp());}
else {Fail; return NULL;}
}
/////////////////////////////////////////////////
// Attribute-Estimator-Random
const TStr TAttrEstRnd::DNm("Random");
PPp TAttrEstRnd::GetPp(const TStr& Nm, const TStr& DNm){
PPp Pp=new TPp(Nm, DNm, ptSet);
Pp->AddPp(TPrbEst::GetPp(TTypeNm<TPrbEst>(), TPrbEst::DNm));
Pp->AddPpInt("Seed", "Random-Seed", 0, TInt::Mx, 1);
return Pp;
}
/////////////////////////////////////////////////
// Attribute-Estimator-Information-Gain
const TStr TAttrEstIGain::DNm("Inf-Gain");
/////////////////////////////////////////////////
// Attribute-Estimator-Information-Gain-Normalized
const TStr TAttrEstIGainNorm::DNm("Inf-Gain-Normalized");
/////////////////////////////////////////////////
// Attribute-Estimator-Information-Gain-Ratio
const TStr TAttrEstIGainRatio::DNm("Inf-Gain-Ratio");
/////////////////////////////////////////////////
// Attribute-Estimator-Mantaras-Distance
const TStr TAttrEstMantarasDist::DNm("Mantaras-Distance");
/////////////////////////////////////////////////
// Attribute-Estimator-MDL
double TAttrEstMdl::GetAttrQ(
const int& AttrN, const PTbValSplit& ValSplit,
const PDmDs& DmDs, const PDmDs& PriorDmDs){
double SumW=DmDs->GetSumW();
int CDscs=DmDs->GetCDs()->GetDscs();
double IGainAttrQ=IGain.GetAttrQ(AttrN, ValSplit, DmDs, PriorDmDs);
double LnPart=TSpecFunc::LnComb(TFlt::Round(SumW)+CDscs-1, CDscs-1);
for (int SplitN=0; SplitN<ValSplit->GetSplits(); SplitN++){
double SSumW=0;
for (int ValN=0; ValN<ValSplit->GetSplitVals(SplitN); ValN++){
TTbVal Val=ValSplit->GetSplitVal(SplitN, ValN);
double ValW=DmDs->GetAVDs(AttrN)->GetValW(Val);
SSumW+=ValW;
}
LnPart-=TSpecFunc::LnComb(TFlt::Round(SSumW+CDscs-1), CDscs-1);
}
return IGainAttrQ+LnPart/SumW;
}
const TStr TAttrEstMdl::DNm("MDL");
/////////////////////////////////////////////////
// Attribute-Estimator-G-Statistics
const TStr TAttrEstGStat::DNm("G-Statistics");
/////////////////////////////////////////////////
// Attribute-Estimator-Chi-Square
double TAttrEstChiSquare::GetAttrQ(
const int& AttrN, const PTbValSplit& ValSplit,
const PDmDs& DmDs, const PDmDs&){
double ChiSquare=0;
for (int SplitN=0; SplitN<ValSplit->GetSplits(); SplitN++){
PTbValDs CSValDs=GetCSValDs(AttrN, SplitN, ValSplit, DmDs);
double SPrb=CSValDs->GetSumPrb(DmDs->GetSumW());
for (int CDsc=0; CDsc<DmDs->GetCDs()->GetDscs(); CDsc++){
double Frac=SPrb*DmDs->GetCDs()->GetValW(CDsc);
if (Frac>0){ChiSquare+=TMath::Sqr(Frac-CSValDs->GetValW(CDsc))/Frac;}
}
}
return ChiSquare;
}
const TStr TAttrEstChiSquare::DNm("Chi-Square");
/////////////////////////////////////////////////
// Attribute-Estimator-ORT
double TAttrEstOrt::GetAttrQ(
const int& AttrN, const PTbValSplit& ValSplit,
const PDmDs& DmDs, const PDmDs& PriorDmDs){
IAssert(ValSplit->GetSplits()==2); // **make exception
PTbValDs CSValDs1=GetCSValDs(AttrN, 0, ValSplit, DmDs);
PTbValDs CSValDs2=GetCSValDs(AttrN, 1, ValSplit, DmDs);
double Cos=0; double Norm1=0; double Norm2=0;
for (int CDsc=0; CDsc<DmDs->GetCDs()->GetDscs(); CDsc++){
double CSPrb1=PrbEst->GetVPrb(CDsc, CSValDs1, PriorDmDs->GetCDs());
double CSPrb2=PrbEst->GetVPrb(CDsc, CSValDs2, PriorDmDs->GetCDs());
Cos+=CSPrb1*CSPrb2; Norm1+=TMath::Sqr(CSPrb1); Norm2+=TMath::Sqr(CSPrb2);
}
if ((Norm1==0)||(Norm2==0)){Cos=1;}
else {Cos=Cos/(sqrt(Norm1)*sqrt(Norm2));}
return 1-Cos;
}
const TStr TAttrEstOrt::DNm("ORT");
/////////////////////////////////////////////////
// Attribute-Estimator-Gini
double TAttrEstGini::GetAttrQ(
const int& AttrN, const PTbValSplit& ValSplit,
const PDmDs& DmDs, const PDmDs& PriorDmDs){
double Gini=0;
for (int SplitN=0; SplitN<ValSplit->GetSplits(); SplitN++){
PTbValDs CSValDs=GetCSValDs(AttrN, SplitN, ValSplit, DmDs);
double SPrb=CSValDs->GetSumPrb(DmDs->GetSumW());
double Sum=0;
for (int CDsc=0; CDsc<DmDs->GetCDs()->GetDscs(); CDsc++){
Sum+=TMath::Sqr(PrbEst->GetVPrb(CDsc, CSValDs, PriorDmDs->GetCDs()));}
Gini+=SPrb*Sum;
}
for (int CDsc=0; CDsc<DmDs->GetCDs()->GetDscs(); CDsc++){
double CPrb=PrbEst->GetCPrb(CDsc, DmDs, PriorDmDs);
Gini-=TMath::Sqr(CPrb);
}
return Gini;
}
const TStr TAttrEstGini::DNm("Gini-Index");
/////////////////////////////////////////////////
// Attribute-Estimator-Weight-Of-Evidence
double TAttrEstWgtEvd::GetAttrQ(
const int& AttrN, const PTbValSplit& ValSplit,
const PDmDs& DmDs, const PDmDs& PriorDmDs){
double PriorSumW=PriorDmDs->GetSumW();
if (PriorSumW==0){return 0;}
double WgtEvd=0;
for (int SplitN=0; SplitN<ValSplit->GetSplits(); SplitN++){
PTbValDs CSValDs=GetCSValDs(AttrN, SplitN, ValSplit, DmDs);
double SPrb=CSValDs->GetSumPrb(DmDs->GetSumW());
for (int CDsc=0; CDsc<DmDs->GetCDs()->GetDscs(); CDsc++){
double OrigCPrb=PrbEst->GetCPrb(CDsc, DmDs, PriorDmDs);
double CPrb=OrigCPrb;
if (CPrb==0){CPrb=1/TMath::Sqr(PriorSumW);}
if (CPrb==1){CPrb=1-(1/TMath::Sqr(PriorSumW));}
double OddsC=CPrb/(1-CPrb);
double CSPrb=PrbEst->GetVPrb(CDsc, CSValDs, PriorDmDs->GetCDs());
if (CSPrb==0){CSPrb=1/TMath::Sqr(PriorSumW);}
if (CSPrb==1){CSPrb=1-(1/TMath::Sqr(PriorSumW));}
double OddsCS=CSPrb/(1-CSPrb);
WgtEvd+=OrigCPrb*SPrb*fabs(log(OddsCS/OddsC));
}
}
return WgtEvd;
}
const TStr TAttrEstWgtEvd::DNm("Weight-Of-Evidence");
/////////////////////////////////////////////////
// Attribute-Estimator-Text-Weight-Of-Evidence
double TAttrEstTextWgtEvd::GetAttrQ(
const int& AttrN, const PTbValSplit& ValSplit,
const PDmDs& DmDs, const PDmDs& PriorDmDs){
double PriorSumW=PriorDmDs->GetSumW();
if (PriorSumW==0){return 0;}
double WgtEvd=0;
PTbValDs CS1ValDs=GetCSValDs(AttrN, 1, ValSplit, DmDs);
double S1Prb=CS1ValDs->GetSumPrb(DmDs->GetSumW());
for (int CDsc=0; CDsc<DmDs->GetCDs()->GetDscs(); CDsc++){
double OrigCPrb=PrbEst->GetCPrb(CDsc, DmDs, PriorDmDs);
double CPrb=OrigCPrb;
if (CPrb==0){CPrb=1/TMath::Sqr(PriorSumW);}
if (CPrb==1){CPrb=1-(1/TMath::Sqr(PriorSumW));}
double OddsC=CPrb/(1-CPrb);
double CS1Prb=PrbEst->GetVPrb(CDsc, CS1ValDs, PriorDmDs->GetCDs());
if (CS1Prb==0){CS1Prb=1/TMath::Sqr(PriorSumW);}
if (CS1Prb==1){CS1Prb=1-(1/TMath::Sqr(PriorSumW));}
double OddsCS1=CS1Prb/(1-CS1Prb);
WgtEvd+=OrigCPrb*S1Prb*fabs(log(OddsCS1/OddsC));
}
return WgtEvd;
}
const TStr TAttrEstTextWgtEvd::DNm("Text-Weight-Of-Evidence");
/////////////////////////////////////////////////
// Attribute-Estimator-Odds-Ratio
double TAttrEstOddsRatio::GetAttrQ(
const int& AttrN, const PTbValSplit& ValSplit,
const PDmDs& DmDs, const PDmDs& PriorDmDs){
IAssert(DmDs->GetCDs()->GetDscs()==2); // **make exception
IAssert(ValSplit->GetSplits()==2); // **make exception
double PriorSumW=PriorDmDs->GetSumW();
if (PriorSumW==0){return TFlt::Mn;}
// split-number-0: false; split-number-1: true
PTbValDs SC0ValDs=GetSCValDs(0, AttrN, ValSplit, DmDs);
PTbValDs SC1ValDs=GetSCValDs(1, AttrN, ValSplit, DmDs);
PTbValDs PriorSValDs=GetSValDs(AttrN, ValSplit, PriorDmDs);
double S1C0Prb=PrbEst->GetVPrb(TTbVal::PosVal, SC0ValDs, PriorSValDs);
double S1C1Prb=PrbEst->GetVPrb(TTbVal::PosVal, SC1ValDs, PriorSValDs);
if (S1C0Prb==0){S1C0Prb=1/TMath::Sqr(PriorSumW);}
if (S1C0Prb==1){S1C0Prb=1-(1/TMath::Sqr(PriorSumW));}
double OddsS1C0=S1C0Prb/(1-S1C0Prb);
if (S1C1Prb==0){S1C1Prb=1/TMath::Sqr(PriorSumW);}
if (S1C1Prb==1){S1C1Prb=1-(1/TMath::Sqr(PriorSumW));}
double OddsS1C1=S1C1Prb/(1-S1C1Prb);
double OddsRatio=log(OddsS1C1/OddsS1C0);
return OddsRatio;
}
const TStr TAttrEstOddsRatio::DNm("Odds-Ratio");
/////////////////////////////////////////////////
// Attribute-Estimator-Weighted-Odds-Ratio
double TAttrEstWgtOddsRatio::GetAttrQ(
const int& AttrN, const PTbValSplit& ValSplit,
const PDmDs& DmDs, const PDmDs& PriorDmDs){
IAssert(DmDs->GetCDs()->GetDscs()==2); // **make exception
IAssert(ValSplit->GetSplits()==2); // **make exception
PTbValDs CSValDs=GetCSValDs(AttrN, 1, ValSplit, DmDs);
double SPrb=CSValDs->GetSumPrb(DmDs->GetSumW());
double WgtOddsRatio=SPrb*OddsRatio.GetAttrQ(AttrN, ValSplit, DmDs, PriorDmDs);
return WgtOddsRatio;
}
const TStr TAttrEstWgtOddsRatio::DNm("Weighted-Odds-Ratio");
/////////////////////////////////////////////////
// Attribute-Estimator-Conditional-Odds-Ratio
double TAttrEstCondOddsRatio::GetAttrQ(
const int& AttrN, const PTbValSplit& ValSplit,
const PDmDs& DmDs, const PDmDs& PriorDmDs){
IAssert(DmDs->GetCDs()->GetDscs()==2); // **make exception
IAssert(ValSplit->GetSplits()==2); // **make exception
double PriorSumW=PriorDmDs->GetSumW();
if (PriorSumW==0){return TFlt::Mn;}
// split-number-0: false; split-number-1: true
PTbValDs SC0ValDs=GetSCValDs(0, AttrN, ValSplit, DmDs);
PTbValDs SC1ValDs=GetSCValDs(1, AttrN, ValSplit, DmDs);
PTbValDs PriorSValDs=GetSValDs(AttrN, ValSplit, PriorDmDs);
double S1C0Prb=PrbEst->GetVPrb(TTbVal::PosVal, SC0ValDs, PriorSValDs);
double S1C1Prb=PrbEst->GetVPrb(TTbVal::PosVal, SC1ValDs, PriorSValDs);
if (S1C0Prb==0){S1C0Prb=1/TMath::Sqr(PriorSumW);}
if (S1C0Prb==1){S1C0Prb=1-(1/TMath::Sqr(PriorSumW));}
double OddsS1C0=S1C0Prb/(1-S1C0Prb);
if (S1C1Prb==0){S1C1Prb=1/TMath::Sqr(PriorSumW);}
if (S1C1Prb==1){S1C1Prb=1-(1/TMath::Sqr(PriorSumW));}
double OddsS1C1=S1C1Prb/(1-S1C1Prb);
double CondOddsRatio;
if (S1C0Prb-S1C1Prb>InvTsh){
CondOddsRatio=InvWgt*log(OddsS1C0/OddsS1C1);
} else {
CondOddsRatio=log(OddsS1C1/OddsS1C0);
}
return CondOddsRatio;
}
const TStr TAttrEstCondOddsRatio::DNm("Conditional-Odds-Ratio");
PPp TAttrEstCondOddsRatio::GetPp(const TStr& Nm, const TStr& DNm){
PPp Pp=new TPp(Nm, DNm, ptSet);
Pp->AddPp(TPrbEst::GetPp(TTypeNm<TPrbEst>(), TPrbEst::DNm));
Pp->AddPpFlt("InvTsh", "Inversion-Treshold", 0, 1, 0.9);
Pp->AddPpFlt("InvWgt", "Inversion-Weight", 0, 1, 0.1);
return Pp;
}
/////////////////////////////////////////////////
// Attribute-Estimator-Log-Probability-Ratio
double TAttrEstLogPRatio::GetAttrQ(
const int& AttrN, const PTbValSplit& ValSplit,
const PDmDs& DmDs, const PDmDs& PriorDmDs){
IAssert(DmDs->GetCDs()->GetDscs()==2); // **make exception
IAssert(ValSplit->GetSplits()==2); // **make exception
double PriorSumW=PriorDmDs->GetSumW();
if (PriorSumW==0){return TFlt::Mn;}
// split-number-0: false; split-number-1: true
PTbValDs SC0ValDs=GetSCValDs(0, AttrN, ValSplit, DmDs);
PTbValDs SC1ValDs=GetSCValDs(1, AttrN, ValSplit, DmDs);
PTbValDs PriorSValDs=GetSValDs(AttrN, ValSplit, PriorDmDs);
double S1C0Prb=PrbEst->GetVPrb(TTbVal::PosVal, SC0ValDs, PriorSValDs);
double S1C1Prb=PrbEst->GetVPrb(TTbVal::PosVal, SC1ValDs, PriorSValDs);
if (S1C0Prb==0){S1C0Prb=1/TMath::Sqr(PriorSumW);}
if (S1C1Prb==0){S1C1Prb=1/TMath::Sqr(PriorSumW);}
double LogPRatio=log(S1C1Prb/S1C0Prb);
return LogPRatio;
}
const TStr TAttrEstLogPRatio::DNm("Log-Probability-Ratio");
/////////////////////////////////////////////////
// Attribute-Estimator-Exp-Probability-Difference
double TAttrEstExpPDiff::GetAttrQ(
const int& AttrN, const PTbValSplit& ValSplit,
const PDmDs& DmDs, const PDmDs& PriorDmDs){
IAssert(DmDs->GetCDs()->GetDscs()==2); // **make exception
IAssert(ValSplit->GetSplits()==2); // **make exception
double SumW=DmDs->GetSumW();
if (SumW==0){return TFlt::Mn;}
// split-number-0: false; split-number-1: true
PTbValDs SC0ValDs=GetSCValDs(0, AttrN, ValSplit, DmDs);
PTbValDs SC1ValDs=GetSCValDs(1, AttrN, ValSplit, DmDs);
PTbValDs PriorSValDs=GetSValDs(AttrN, ValSplit, PriorDmDs);
double S1C0Prb=PrbEst->GetVPrb(TTbVal::PosVal, SC0ValDs, PriorSValDs);
double S1C1Prb=PrbEst->GetVPrb(TTbVal::PosVal, SC1ValDs, PriorSValDs);
double ExpPDiff=exp(S1C1Prb-S1C0Prb);
return ExpPDiff;
}
const TStr TAttrEstExpPDiff::DNm("Exp-Probability-Difference");
/////////////////////////////////////////////////
// Attribute-Estimator-Mutual-Information
double TAttrEstMutInf::GetAttrQ(
const int& AttrN, const PTbValSplit& ValSplit,
const PDmDs& DmDs, const PDmDs& PriorDmDs){
IAssert(ValSplit->GetSplits()==2); // **make exception
// split-number-0: false; split-number-1: true
PTbValDs SValDs=GetSValDs(AttrN, ValSplit, DmDs);
PTbValDs PriorSValDs=GetSValDs(AttrN, ValSplit, PriorDmDs);
double S1Prb=PrbEst->GetVPrb(TTbVal::PosVal, SValDs, PriorSValDs);
if (S1Prb==0){return TFlt::Mn;}
double MutInf=0;
for (int CDsc=0; CDsc<DmDs->GetCDs()->GetDscs(); CDsc++){
double CPrb=PrbEst->GetCPrb(CDsc, DmDs, PriorDmDs);
PTbValDs SCValDs=GetSCValDs(CDsc, AttrN, ValSplit, DmDs);
double S1CPrb=PrbEst->GetVPrb(TTbVal::PosVal, SCValDs, PriorSValDs);
if (S1CPrb==0){S1CPrb=1/TMath::Sqr(DmDs->GetSumW());}
MutInf+=CPrb*log(S1CPrb/S1Prb);
}
return MutInf;
}
const TStr TAttrEstMutInf::DNm("Mutual-Information");
/////////////////////////////////////////////////
// Attribute-Estimator-Cross-Entropy
double TAttrEstCrossEnt::GetAttrQ(
const int& AttrN, const PTbValSplit& ValSplit,
const PDmDs& DmDs, const PDmDs& PriorDmDs){
IAssert(ValSplit->GetSplits()==2); // **make exception
// split-number-0: false; split-number-1: true
PTbValDs CS1ValDs=GetCSValDs(AttrN, 1, ValSplit, DmDs);
PTbValDs SValDs=GetSValDs(AttrN, ValSplit, DmDs);
PTbValDs PriorSValDs=GetSValDs(AttrN, ValSplit, PriorDmDs);
double S1Prb=PrbEst->GetVPrb(TTbVal::PosVal, SValDs, PriorSValDs);
if (S1Prb==0){return TFlt::Mn;}
double CrossEnt=0;
for (int CDsc=0; CDsc<DmDs->GetCDs()->GetDscs(); CDsc++){
double CPrb=PrbEst->GetCPrb(CDsc, DmDs, PriorDmDs);
double CS1Prb=PrbEst->GetVPrb(CDsc, CS1ValDs, PriorDmDs->GetCDs());
if (CS1Prb>0){Assert(CPrb>0);
CrossEnt+=CS1Prb*log(CS1Prb/CPrb);}
}
CrossEnt*=S1Prb;
return CrossEnt;
}
const TStr TAttrEstCrossEnt::DNm("Cross-Entropy");
/////////////////////////////////////////////////
// Attribute-Estimator-Term-Frequency
double TAttrEstTermFq::GetAttrQ(
const int& AttrN, const PTbValSplit& ValSplit,
const PDmDs& DmDs, const PDmDs&){
IAssert(ValSplit->GetSplits()==2); // **make exception
PTbValDs CSValDs=GetCSValDs(AttrN, 1, ValSplit, DmDs);
return CSValDs->GetSumW();
}
const TStr TAttrEstTermFq::DNm("Term-Frequency");
| 41.331615 | 105 | 0.665849 | ksemer |
3dac85c8bafbc7d9a7802659675a8a65a627d769 | 743 | hh | C++ | gem5/src/mem/ruby/network/booksim2/rptrafficmanager.hh | jyhuang91/flyover | 952a0fffee952c9f88b93017b6bba65a84d562cb | [
"MIT"
] | 3 | 2020-11-01T08:23:10.000Z | 2021-12-21T02:53:36.000Z | gem5/src/mem/ruby/network/booksim2/rptrafficmanager.hh | jyhuang91/flyover | 952a0fffee952c9f88b93017b6bba65a84d562cb | [
"MIT"
] | null | null | null | gem5/src/mem/ruby/network/booksim2/rptrafficmanager.hh | jyhuang91/flyover | 952a0fffee952c9f88b93017b6bba65a84d562cb | [
"MIT"
] | 1 | 2020-12-07T00:57:30.000Z | 2020-12-07T00:57:30.000Z | /*
* rptrafficmanager.hh
* - A traffic manager for Router Parking
*
* Author: Jiayi Huang
*/
#ifndef _RPTRAFFICMANAGER_HPP_
#define _RPTRAFFICMANAGER_HPP_
#include <cassert>
#include "mem/ruby/network/booksim2/trafficmanager.hh"
class RPTrafficManager : public TrafficManager {
private:
vector<vector<int> > _packet_size;
vector<vector<int> > _packet_size_rate;
vector<int> _packet_size_max_val;
// ============ Internal methods ============
protected:
virtual void _Inject();
virtual void _Step( );
virtual void _GeneratePacket( int source, int size, int cl, uint64_t time );
public:
RPTrafficManager( const Configuration &config, const vector<BSNetwork *> & net );
virtual ~RPTrafficManager( );
};
#endif
| 19.051282 | 83 | 0.713324 | jyhuang91 |
3dadd9169507170884588ae2e6e56af05806cd41 | 3,213 | cpp | C++ | problems/kickstart/2021/E/palindromic-crossword/code.cpp | brunodccarvalho/competitive | 4177c439174fbe749293b9da3445ce7303bd23c2 | [
"MIT"
] | 7 | 2020-10-15T22:37:10.000Z | 2022-02-26T17:23:49.000Z | problems/kickstart/2021/E/palindromic-crossword/code.cpp | brunodccarvalho/competitive | 4177c439174fbe749293b9da3445ce7303bd23c2 | [
"MIT"
] | null | null | null | problems/kickstart/2021/E/palindromic-crossword/code.cpp | brunodccarvalho/competitive | 4177c439174fbe749293b9da3445ce7303bd23c2 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#ifdef LOCAL
#include "code/formatting.hpp"
#else
#define debug(...) (void)0
#endif
using namespace std;
static_assert(sizeof(int) == 4 && sizeof(long) == 8);
struct disjoint_set {
int N, S;
vector<int> next, size;
explicit disjoint_set(int N = 0) : N(N), S(N), next(N), size(N, 1) {
iota(begin(next), end(next), 0);
}
void assign(int N) { *this = disjoint_set(N); }
bool same(int i, int j) { return find(i) == find(j); }
bool unit(int i) { return i == next[i] && size[i] == 1; }
bool root(int i) { return find(i) == i; }
void reroot(int u) {
if (u != find(u)) {
size[u] = size[find(u)];
next[u] = next[find(u)] = u;
}
}
int find(int i) {
while (i != next[i]) {
i = next[i] = next[next[i]];
}
return i;
}
bool join(int i, int j) {
i = find(i);
j = find(j);
if (i != j) {
if (size[i] < size[j]) {
swap(i, j);
}
next[j] = i;
size[i] += size[j];
S--;
return true;
}
return false;
}
};
auto solve() {
int N, M;
cin >> N >> M;
vector<string> grid(N);
for (int i = 0; i < N; i++) {
cin >> grid[i];
}
disjoint_set dsu(N * M);
auto id = [&](int i, int j) { return i * M + j; };
// columns
for (int i = 0; i < N; i++) {
int j = 0;
do {
while (j < M && grid[i][j] == '#')
j++;
int a = j;
while (j < M && grid[i][j] != '#')
j++;
int b = j;
for (int c = a, d = b - 1; c < d; c++, d--) {
dsu.join(id(i, c), id(i, d));
}
} while (j < M);
}
// rows
for (int j = 0; j < M; j++) {
int i = 0;
do {
while (i < N && grid[i][j] == '#')
i++;
int a = i;
while (i < N && grid[i][j] != '#')
i++;
int b = i;
for (int c = a, d = b - 1; c < d; c++, d--) {
dsu.join(id(c, j), id(d, j));
}
} while (i < N);
}
vector<string> ans = grid;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (grid[i][j] != '.' && grid[i][j] != '#') {
int x = dsu.find(id(i, j));
int r = x / M, c = x - r * M;
ans[r][c] = grid[i][j];
}
}
}
int filled = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (ans[i][j] != '#') {
int x = dsu.find(id(i, j));
int r = x / M, c = x - r * M;
ans[i][j] = ans[r][c];
filled += ans[i][j] != '.' && grid[i][j] == '.';
}
}
}
cout << filled << '\n';
for (int i = 0; i < N; i++) {
cout << ans[i] << '\n';
}
}
int main() {
ios::sync_with_stdio(false), cin.tie(nullptr);
int T;
cin >> T;
for (int t = 1; t <= T; t++) {
cout << "Case #" << t << ": ";
solve();
}
return 0;
}
| 23.452555 | 72 | 0.347028 | brunodccarvalho |
3dafc103374acfba34a3fafd4afc8355c902b015 | 24 | cpp | C++ | src/StockOrder.cpp | JanEbbing/StockAnalyzer | 81e76bb71c7958d969533b8a730eb77792836730 | [
"MIT"
] | null | null | null | src/StockOrder.cpp | JanEbbing/StockAnalyzer | 81e76bb71c7958d969533b8a730eb77792836730 | [
"MIT"
] | null | null | null | src/StockOrder.cpp | JanEbbing/StockAnalyzer | 81e76bb71c7958d969533b8a730eb77792836730 | [
"MIT"
] | null | null | null | #include "StockOrder.h"
| 12 | 23 | 0.75 | JanEbbing |