hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
โŒ€
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
โŒ€
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
โŒ€
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
โŒ€
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
โŒ€
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
โŒ€
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
โŒ€
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
โŒ€
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
โŒ€
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
90ffbbb13d7fdc5c2ca060e950b9a327df18f015
8,853
cxx
C++
Source/Common/itkManagedProcessObject.cxx
amirsalah/manageditk
1ca3a8ea7db221a3b6a578d3c75e3ed941ef8761
[ "MIT" ]
null
null
null
Source/Common/itkManagedProcessObject.cxx
amirsalah/manageditk
1ca3a8ea7db221a3b6a578d3c75e3ed941ef8761
[ "MIT" ]
null
null
null
Source/Common/itkManagedProcessObject.cxx
amirsalah/manageditk
1ca3a8ea7db221a3b6a578d3c75e3ed941ef8761
[ "MIT" ]
null
null
null
/*============================================================================= NOTE: THIS FILE IS A HANDMADE WRAPPER FOR THE ManagedITK PROJECT. Project: ManagedITK Program: Insight Segmentation & Registration Toolkit Module: itkManagedProcessObject.cxx Language: C++/CLI Author: Dan Mueller Date: $Date: 2008-06-15 19:37:32 +0200 (Sun, 15 Jun 2008) $ Revision: $Revision: 15 $ Portions of this code are covered under the ITK and VTK copyright. See http://www.itk.org/HTML/Copyright.htm for details. See http://www.vtk.org/copyright.php for details. Copyright (c) 2007-2008 Daniel Mueller Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. =============================================================================*/ #pragma once #pragma warning( disable : 4635 ) // Disable warnings about XML doc comments #ifndef __itkManagedProcessObject_cxx #define __itkManagedProcessObject_cxx // Include some useful ManagedITK files #include "itkManagedObject.cxx" // Use some managed namespaces #using <mscorlib.dll> #using <System.dll> using namespace System; using namespace System::IO; using namespace System::Reflection; using namespace System::Diagnostics; using namespace System::Collections::Generic; namespace itk { /** Forward reference to itkProcessObject */ ref class itkProcessObject; ///<summary> ///EventArgs subclass holding the current progress of a process object. ///Provides a convient method which converts the fractional progress to an integer percentage. ///</summary> public ref class itkProgressEventArgs : itkEventArgs { private: float m_Progress; public: ///<summary>Default constructor.</summary> ///<param name="progress">The fractional progress of the process object (ie. 0.03 = 3%)</param> itkProgressEventArgs( float progress ) : itkEventArgs( ) { this->m_Progress = progress; } ///<summary>Get the current progress as a fraction (ie. 0.03 = 3 %).</summary> property float Progress { virtual float get() { return this->m_Progress; } } ///<summary>Get the current progress as a percentage, rounded to the nearest integer value.</summary> property int ProgressAsPercentage { virtual int get() { return static_cast<int>( System::Math::Round(this->m_Progress*100.0) ); } } }; ///<summary>A delegate for events sent from an itkProcessObject, with a progress value between 0.0 and 1.0.</summary> public delegate void itkProgressHandler(itkProcessObject^ sender, itkProgressEventArgs^ e); ///<summary> ///This abstract class is a managed replacement for itk::ProcessObject. ///</summary> ///<remarks> ///ProcessObject is an abstract object that specifies behavior and ///interface of network process objects (sources, filters, mappers). ///Source objects are creators of visualization data; filters input, ///process, and output image data; and mappers transform data into ///another form (like transforming coordinates or writing data to a file). /// ///A major role of ProcessObject is to define the inputs and outputs of ///a filter. More than one input and/or output may exist for a given filter. ///Some classes (e.g., source objects or mapper objects) will not use inputs ///(the source) or outputs (mappers). In this case, the inputs or outputs is ///just ignored. ///</remarks> public ref class itkProcessObject abstract : itkObject { private: String^ m_Name; itkProgressHandler^ m_EventStorage_Progress; protected: ///<summary>Protected constructor.</summary> ///<param name="name">A string representing the name of the ProcessObject.</param> itkProcessObject( String^ name ) : itkObject( ) { this->m_Name = name; } public: ///<summary>Get/set a string describing the process object.</summary> property String^ Name { virtual String^ get() { return this->m_Name; } } ///<summary> ///Get the size of the input array. This is merely the size of the input array, ///not the number of inputs that have valid DataObject's assigned. ///</summary> ///<remarks>Use NumberOfValidRequiredInputs to determine how many inputs are non-null.</remarks> property unsigned int NumberOfInputs { virtual unsigned int get()=0; } ///<summary> ///Get the number of valid inputs. This is the number of non-null entries in the ///input array in the first NumberOfRequiredInputs slots. This method is used ///to determine whether the necessary required inputs have been set. ///</summary> property unsigned int NumberOfValidRequiredInputs { virtual unsigned int get()=0; } ///<summary>Return the length of the output array.</summary> property unsigned int NumberOfOutputs { virtual unsigned int get()=0; } ///<summary>Get/set the number of threads to create when executing.</summary> property unsigned int NumberOfThreads { virtual unsigned int get()=0; virtual void set(unsigned int threads)=0; } ///<summary>An event which is raised when the progress of the process is updated.</summary> event itkProgressHandler^ Progress { public: void add (itkProgressHandler^ handler) { m_EventStorage_Progress += handler; } void remove (itkProgressHandler^ handler) { m_EventStorage_Progress -= handler; } internal: void raise( itkProcessObject^ obj, itkProgressEventArgs^ e ) { if (this->m_EventStorage_Progress != nullptr) this->m_EventStorage_Progress(obj, e); } } ///<summary> ///Bring this filter up-to-date. ///</summary> ///<remarks> ///Update() checks modified times against last execution times, and ///re-executes objects if necessary. A side effect of this method ///ss that the whole pipeline may execute in order to bring this filter ///up-to-date. This method updates the currently prescribed requested region. ///If no requested region has been set on the output, then the requested ///region will be set to the largest possible region. Once the requested ///region is set, Update() will make sure the specified requested region ///is up-to-date. To have a filter always to produce its largest possible ///region, users should call UpdateLargestPossibleRegion() instead. ///</remarks> virtual void Update ( ) = 0; ///<summary> ///Bring the largest possible region of this filter up-to-date. ///</summary> ///<remarks> ///Like Update(), but sets the output requested region to the ///largest possible region for the output. This is the method users ///should call if they want the entire dataset to be processed. If ///a user wants to update the same output region as a previous call ///to Update() or a previous call to UpdateLargestPossibleRegion(), ///then they should call the method Update(). ///</remarks> virtual void UpdateLargestPossibleRegion ( ) = 0; ///<summary> ///Set the AbortGenerateData flag to true, and try to prematurely terminate the process. ///</summary> ///<remarks> ///Process objects may handle premature termination of execution in different ways. ///Eg. many filters totally ignore this flag. ///</remarks> virtual void AbortGenerateData ( ) = 0; ///<summary>Invoke the Progress event.</summary> virtual void InvokeProgressEvent ( itkProgressEventArgs^ e ) { this->Progress(this, e); } }; // end ref class } // end namespace #endif
38.324675
120
0.672427
[ "object", "transform" ]
2900c59a65d58885697faeee8eb24329f1bf477b
126,420
cpp
C++
llvm/unittests/CodeGen/InstrRefLDVTest.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
6
2022-01-20T02:15:30.000Z
2022-02-23T13:55:31.000Z
llvm/unittests/CodeGen/InstrRefLDVTest.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
null
null
null
llvm/unittests/CodeGen/InstrRefLDVTest.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
null
null
null
//===------------- llvm/unittest/CodeGen/InstrRefLDVTest.cpp --------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/MIRParser/MIRParser.h" #include "llvm/CodeGen/MachineModuleInfo.h" #include "llvm/CodeGen/TargetLowering.h" #include "llvm/CodeGen/TargetSubtargetInfo.h" #include "llvm/IR/DIBuilder.h" #include "llvm/IR/DebugInfoMetadata.h" #include "llvm/IR/IRBuilder.h" #include "llvm/MC/TargetRegistry.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" #include "../lib/CodeGen/LiveDebugValues/InstrRefBasedImpl.h" #include "gtest/gtest.h" using namespace llvm; using namespace LiveDebugValues; // Include helper functions to ease the manipulation of MachineFunctions #include "MFCommon.inc" class InstrRefLDVTest : public testing::Test { public: friend class InstrRefBasedLDV; using MLocTransferMap = InstrRefBasedLDV::MLocTransferMap; LLVMContext Ctx; std::unique_ptr<Module> Mod; std::unique_ptr<TargetMachine> Machine; std::unique_ptr<MachineFunction> MF; std::unique_ptr<MachineDominatorTree> DomTree; std::unique_ptr<MachineModuleInfo> MMI; DICompileUnit *OurCU; DIFile *OurFile; DISubprogram *OurFunc; DILexicalBlock *OurBlock, *AnotherBlock; DISubprogram *ToInlineFunc; DILexicalBlock *ToInlineBlock; DILocalVariable *FuncVariable; DIBasicType *LongInt; DIExpression *EmptyExpr; DebugLoc OutermostLoc, InBlockLoc, NotNestedBlockLoc, InlinedLoc; MachineBasicBlock *MBB0, *MBB1, *MBB2, *MBB3, *MBB4; std::unique_ptr<InstrRefBasedLDV> LDV; std::unique_ptr<MLocTracker> MTracker; std::unique_ptr<VLocTracker> VTracker; SmallString<256> MIRStr; InstrRefLDVTest() : Ctx(), Mod(std::make_unique<Module>("beehives", Ctx)) {} void SetUp() { // Boilerplate that creates a MachineFunction and associated blocks. Mod->setDataLayout("e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-" "n8:16:32:64-S128"); Triple TargetTriple("x86_64--"); std::string Error; const Target *T = TargetRegistry::lookupTarget("", TargetTriple, Error); if (!T) GTEST_SKIP(); TargetOptions Options; Machine = std::unique_ptr<TargetMachine>( T->createTargetMachine(Triple::normalize("x86_64--"), "", "", Options, None, None, CodeGenOpt::Aggressive)); auto Type = FunctionType::get(Type::getVoidTy(Ctx), false); auto F = Function::Create(Type, GlobalValue::ExternalLinkage, "Test", &*Mod); unsigned FunctionNum = 42; MMI = std::make_unique<MachineModuleInfo>((LLVMTargetMachine *)&*Machine); const TargetSubtargetInfo &STI = *Machine->getSubtargetImpl(*F); MF = std::make_unique<MachineFunction>(*F, (LLVMTargetMachine &)*Machine, STI, FunctionNum, *MMI); // Create metadata: CU, subprogram, some blocks and an inline function // scope. DIBuilder DIB(*Mod); OurFile = DIB.createFile("xyzzy.c", "/cave"); OurCU = DIB.createCompileUnit(dwarf::DW_LANG_C99, OurFile, "nou", false, "", 0); auto OurSubT = DIB.createSubroutineType(DIB.getOrCreateTypeArray(None)); OurFunc = DIB.createFunction(OurCU, "bees", "", OurFile, 1, OurSubT, 1, DINode::FlagZero, DISubprogram::SPFlagDefinition); F->setSubprogram(OurFunc); OurBlock = DIB.createLexicalBlock(OurFunc, OurFile, 2, 3); AnotherBlock = DIB.createLexicalBlock(OurFunc, OurFile, 2, 6); ToInlineFunc = DIB.createFunction(OurFile, "shoes", "", OurFile, 10, OurSubT, 10, DINode::FlagZero, DISubprogram::SPFlagDefinition); // Make some nested scopes. OutermostLoc = DILocation::get(Ctx, 3, 1, OurFunc); InBlockLoc = DILocation::get(Ctx, 4, 1, OurBlock); InlinedLoc = DILocation::get(Ctx, 10, 1, ToInlineFunc, InBlockLoc.get()); // Make a scope that isn't nested within the others. NotNestedBlockLoc = DILocation::get(Ctx, 4, 1, AnotherBlock); LongInt = DIB.createBasicType("long", 64, llvm::dwarf::DW_ATE_unsigned); FuncVariable = DIB.createAutoVariable(OurFunc, "lala", OurFile, 1, LongInt); EmptyExpr = DIExpression::get(Ctx, {}); DIB.finalize(); } Register getRegByName(const char *WantedName) { auto *TRI = MF->getRegInfo().getTargetRegisterInfo(); // Slow, but works. for (unsigned int I = 1; I < TRI->getNumRegs(); ++I) { const char *Name = TRI->getName(I); if (strcmp(WantedName, Name) == 0) return I; } // If this ever fails, something is very wrong with this unit test. llvm_unreachable("Can't find register by name"); } InstrRefBasedLDV *setupLDVObj(MachineFunction *MF) { // Create a new LDV object, and plug some relevant object ptrs into it. LDV = std::make_unique<InstrRefBasedLDV>(); const TargetSubtargetInfo &STI = MF->getSubtarget(); LDV->TII = STI.getInstrInfo(); LDV->TRI = STI.getRegisterInfo(); LDV->TFI = STI.getFrameLowering(); LDV->MFI = &MF->getFrameInfo(); LDV->MRI = &MF->getRegInfo(); DomTree = std::make_unique<MachineDominatorTree>(*MF); LDV->DomTree = &*DomTree; // Future work: unit tests for mtracker / vtracker / ttracker. // Setup things like the artifical block map, and BlockNo <=> RPO Order // mappings. LDV->initialSetup(*MF); LDV->LS.initialize(*MF); addMTracker(MF); return &*LDV; } void addMTracker(MachineFunction *MF) { ASSERT_TRUE(LDV); // Add a machine-location-tracking object to LDV. Don't initialize any // register locations within it though. const TargetSubtargetInfo &STI = MF->getSubtarget(); MTracker = std::make_unique<MLocTracker>( *MF, *LDV->TII, *LDV->TRI, *STI.getTargetLowering()); LDV->MTracker = &*MTracker; } void addVTracker() { ASSERT_TRUE(LDV); VTracker = std::make_unique<VLocTracker>(); LDV->VTracker = &*VTracker; } // Some routines for bouncing into LDV, void buildMLocValueMap(ValueIDNum **MInLocs, ValueIDNum **MOutLocs, SmallVectorImpl<MLocTransferMap> &MLocTransfer) { LDV->buildMLocValueMap(*MF, MInLocs, MOutLocs, MLocTransfer); } void placeMLocPHIs(MachineFunction &MF, SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks, ValueIDNum **MInLocs, SmallVectorImpl<MLocTransferMap> &MLocTransfer) { LDV->placeMLocPHIs(MF, AllBlocks, MInLocs, MLocTransfer); } Optional<ValueIDNum> pickVPHILoc(const MachineBasicBlock &MBB, const DebugVariable &Var, const InstrRefBasedLDV::LiveIdxT &LiveOuts, ValueIDNum **MOutLocs, const SmallVectorImpl<const MachineBasicBlock *> &BlockOrders) { return LDV->pickVPHILoc(MBB, Var, LiveOuts, MOutLocs, BlockOrders); } bool vlocJoin(MachineBasicBlock &MBB, InstrRefBasedLDV::LiveIdxT &VLOCOutLocs, SmallPtrSet<const MachineBasicBlock *, 8> &InScopeBlocks, SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore, DbgValue &InLoc) { return LDV->vlocJoin(MBB, VLOCOutLocs, InScopeBlocks, BlocksToExplore, InLoc); } void buildVLocValueMap(const DILocation *DILoc, const SmallSet<DebugVariable, 4> &VarsWeCareAbout, SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks, InstrRefBasedLDV::LiveInsT &Output, ValueIDNum **MOutLocs, ValueIDNum **MInLocs, SmallVectorImpl<VLocTracker> &AllTheVLocs) { LDV->buildVLocValueMap(DILoc, VarsWeCareAbout, AssignBlocks, Output, MOutLocs, MInLocs, AllTheVLocs); } void initValueArray(ValueIDNum **Nums, unsigned Blks, unsigned Locs) { for (unsigned int I = 0; I < Blks; ++I) for (unsigned int J = 0; J < Locs; ++J) Nums[I][J] = ValueIDNum::EmptyValue; } void setupSingleBlock() { // Add an entry block with nothing but 'ret void' in it. Function &F = const_cast<llvm::Function &>(MF->getFunction()); auto *BB0 = BasicBlock::Create(Ctx, "entry", &F); IRBuilder<> IRB(BB0); IRB.CreateRetVoid(); MBB0 = MF->CreateMachineBasicBlock(BB0); MF->insert(MF->end(), MBB0); MF->RenumberBlocks(); setupLDVObj(&*MF); } void setupDiamondBlocks() { // entry // / \ // br1 br2 // \ / // ret llvm::Function &F = const_cast<llvm::Function &>(MF->getFunction()); auto *BB0 = BasicBlock::Create(Ctx, "a", &F); auto *BB1 = BasicBlock::Create(Ctx, "b", &F); auto *BB2 = BasicBlock::Create(Ctx, "c", &F); auto *BB3 = BasicBlock::Create(Ctx, "d", &F); IRBuilder<> IRB0(BB0), IRB1(BB1), IRB2(BB2), IRB3(BB3); IRB0.CreateBr(BB1); IRB1.CreateBr(BB2); IRB2.CreateBr(BB3); IRB3.CreateRetVoid(); MBB0 = MF->CreateMachineBasicBlock(BB0); MF->insert(MF->end(), MBB0); MBB1 = MF->CreateMachineBasicBlock(BB1); MF->insert(MF->end(), MBB1); MBB2 = MF->CreateMachineBasicBlock(BB2); MF->insert(MF->end(), MBB2); MBB3 = MF->CreateMachineBasicBlock(BB3); MF->insert(MF->end(), MBB3); MBB0->addSuccessor(MBB1); MBB0->addSuccessor(MBB2); MBB1->addSuccessor(MBB3); MBB2->addSuccessor(MBB3); MF->RenumberBlocks(); setupLDVObj(&*MF); } void setupSimpleLoop() { // entry // | // |/-----\ // loopblk | // |\-----/ // | // ret llvm::Function &F = const_cast<llvm::Function &>(MF->getFunction()); auto *BB0 = BasicBlock::Create(Ctx, "entry", &F); auto *BB1 = BasicBlock::Create(Ctx, "loop", &F); auto *BB2 = BasicBlock::Create(Ctx, "ret", &F); IRBuilder<> IRB0(BB0), IRB1(BB1), IRB2(BB2); IRB0.CreateBr(BB1); IRB1.CreateBr(BB2); IRB2.CreateRetVoid(); MBB0 = MF->CreateMachineBasicBlock(BB0); MF->insert(MF->end(), MBB0); MBB1 = MF->CreateMachineBasicBlock(BB1); MF->insert(MF->end(), MBB1); MBB2 = MF->CreateMachineBasicBlock(BB2); MF->insert(MF->end(), MBB2); MBB0->addSuccessor(MBB1); MBB1->addSuccessor(MBB2); MBB1->addSuccessor(MBB1); MF->RenumberBlocks(); setupLDVObj(&*MF); } void setupNestedLoops() { // entry // | // loop1 // ^\ // | \ /-\ // | loop2 | // | / \-/ // ^ / // join // | // ret llvm::Function &F = const_cast<llvm::Function &>(MF->getFunction()); auto *BB0 = BasicBlock::Create(Ctx, "entry", &F); auto *BB1 = BasicBlock::Create(Ctx, "loop1", &F); auto *BB2 = BasicBlock::Create(Ctx, "loop2", &F); auto *BB3 = BasicBlock::Create(Ctx, "join", &F); auto *BB4 = BasicBlock::Create(Ctx, "ret", &F); IRBuilder<> IRB0(BB0), IRB1(BB1), IRB2(BB2), IRB3(BB3), IRB4(BB4); IRB0.CreateBr(BB1); IRB1.CreateBr(BB2); IRB2.CreateBr(BB3); IRB3.CreateBr(BB4); IRB4.CreateRetVoid(); MBB0 = MF->CreateMachineBasicBlock(BB0); MF->insert(MF->end(), MBB0); MBB1 = MF->CreateMachineBasicBlock(BB1); MF->insert(MF->end(), MBB1); MBB2 = MF->CreateMachineBasicBlock(BB2); MF->insert(MF->end(), MBB2); MBB3 = MF->CreateMachineBasicBlock(BB3); MF->insert(MF->end(), MBB3); MBB4 = MF->CreateMachineBasicBlock(BB4); MF->insert(MF->end(), MBB4); MBB0->addSuccessor(MBB1); MBB1->addSuccessor(MBB2); MBB2->addSuccessor(MBB2); MBB2->addSuccessor(MBB3); MBB3->addSuccessor(MBB1); MBB3->addSuccessor(MBB4); MF->RenumberBlocks(); setupLDVObj(&*MF); } void setupNoDominatingLoop() { // entry // / \ // / \ // / \ // head1 head2 // ^ \ / ^ // ^ \ / ^ // \-joinblk -/ // | // ret llvm::Function &F = const_cast<llvm::Function &>(MF->getFunction()); auto *BB0 = BasicBlock::Create(Ctx, "entry", &F); auto *BB1 = BasicBlock::Create(Ctx, "head1", &F); auto *BB2 = BasicBlock::Create(Ctx, "head2", &F); auto *BB3 = BasicBlock::Create(Ctx, "joinblk", &F); auto *BB4 = BasicBlock::Create(Ctx, "ret", &F); IRBuilder<> IRB0(BB0), IRB1(BB1), IRB2(BB2), IRB3(BB3), IRB4(BB4); IRB0.CreateBr(BB1); IRB1.CreateBr(BB2); IRB2.CreateBr(BB3); IRB3.CreateBr(BB4); IRB4.CreateRetVoid(); MBB0 = MF->CreateMachineBasicBlock(BB0); MF->insert(MF->end(), MBB0); MBB1 = MF->CreateMachineBasicBlock(BB1); MF->insert(MF->end(), MBB1); MBB2 = MF->CreateMachineBasicBlock(BB2); MF->insert(MF->end(), MBB2); MBB3 = MF->CreateMachineBasicBlock(BB3); MF->insert(MF->end(), MBB3); MBB4 = MF->CreateMachineBasicBlock(BB4); MF->insert(MF->end(), MBB4); MBB0->addSuccessor(MBB1); MBB0->addSuccessor(MBB2); MBB1->addSuccessor(MBB3); MBB2->addSuccessor(MBB3); MBB3->addSuccessor(MBB1); MBB3->addSuccessor(MBB2); MBB3->addSuccessor(MBB4); MF->RenumberBlocks(); setupLDVObj(&*MF); } void setupBadlyNestedLoops() { // entry // | // loop1 -o // | ^ // | ^ // loop2 -o // | ^ // | ^ // loop3 -o // | // ret // // NB: the loop blocks self-loop, which is a bit too fiddly to draw on // accurately. llvm::Function &F = const_cast<llvm::Function &>(MF->getFunction()); auto *BB0 = BasicBlock::Create(Ctx, "entry", &F); auto *BB1 = BasicBlock::Create(Ctx, "loop1", &F); auto *BB2 = BasicBlock::Create(Ctx, "loop2", &F); auto *BB3 = BasicBlock::Create(Ctx, "loop3", &F); auto *BB4 = BasicBlock::Create(Ctx, "ret", &F); IRBuilder<> IRB0(BB0), IRB1(BB1), IRB2(BB2), IRB3(BB3), IRB4(BB4); IRB0.CreateBr(BB1); IRB1.CreateBr(BB2); IRB2.CreateBr(BB3); IRB3.CreateBr(BB4); IRB4.CreateRetVoid(); MBB0 = MF->CreateMachineBasicBlock(BB0); MF->insert(MF->end(), MBB0); MBB1 = MF->CreateMachineBasicBlock(BB1); MF->insert(MF->end(), MBB1); MBB2 = MF->CreateMachineBasicBlock(BB2); MF->insert(MF->end(), MBB2); MBB3 = MF->CreateMachineBasicBlock(BB3); MF->insert(MF->end(), MBB3); MBB4 = MF->CreateMachineBasicBlock(BB4); MF->insert(MF->end(), MBB4); MBB0->addSuccessor(MBB1); MBB1->addSuccessor(MBB1); MBB1->addSuccessor(MBB2); MBB2->addSuccessor(MBB1); MBB2->addSuccessor(MBB2); MBB2->addSuccessor(MBB3); MBB3->addSuccessor(MBB2); MBB3->addSuccessor(MBB3); MBB3->addSuccessor(MBB4); MF->RenumberBlocks(); setupLDVObj(&*MF); } MachineFunction *readMIRBlock(const char *Input) { MIRStr.clear(); StringRef S = Twine(Twine(R"MIR( --- | target triple = "x86_64-unknown-linux-gnu" define void @test() { ret void } ... --- name: test tracksRegLiveness: true stack: - { id: 0, name: '', type: spill-slot, offset: -16, size: 8, alignment: 8, stack-id: default, callee-saved-register: '', callee-saved-restored: true, debug-info-variable: '', debug-info-expression: '', debug-info-location: '' } body: | bb.0: liveins: $rdi, $rsi )MIR") + Twine(Input) + Twine("...\n")) .toNullTerminatedStringRef(MIRStr); ; // Clear the "test" function from MMI if it's still present. if (Function *Fn = Mod->getFunction("test")) MMI->deleteMachineFunctionFor(*Fn); auto MemBuf = MemoryBuffer::getMemBuffer(S, "<input>"); auto MIRParse = createMIRParser(std::move(MemBuf), Ctx); Mod = MIRParse->parseIRModule(); assert(Mod); Mod->setDataLayout("e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-" "n8:16:32:64-S128"); bool Result = MIRParse->parseMachineFunctions(*Mod, *MMI); assert(!Result && "Failed to parse unit test machine function?"); (void)Result; Function *Fn = Mod->getFunction("test"); assert(Fn && "Failed to parse a unit test module string?"); Fn->setSubprogram(OurFunc); return MMI->getMachineFunction(*Fn); } void produceMLocTransferFunction(MachineFunction &MF, SmallVectorImpl<MLocTransferMap> &MLocTransfer, unsigned MaxNumBlocks) { LDV->produceMLocTransferFunction(MF, MLocTransfer, MaxNumBlocks); } }; TEST_F(InstrRefLDVTest, MTransferDefs) { MachineFunction *MF = readMIRBlock( " $rax = MOV64ri 0\n" " RETQ $rax\n"); setupLDVObj(MF); // We should start with only SP tracked. EXPECT_TRUE(MTracker->getNumLocs() == 1); SmallVector<MLocTransferMap, 1> TransferMap; TransferMap.resize(1); produceMLocTransferFunction(*MF, TransferMap, 1); // Code contains only one register write: that should assign to each of the // aliasing registers. Test that all of them get locations, and have a // corresponding def at the first instr in the function. const char *RegNames[] = {"RAX", "HAX", "EAX", "AX", "AH", "AL"}; EXPECT_TRUE(MTracker->getNumLocs() == 7); for (const char *RegName : RegNames) { Register R = getRegByName(RegName); ASSERT_TRUE(MTracker->isRegisterTracked(R)); LocIdx L = MTracker->getRegMLoc(R); ValueIDNum V = MTracker->readReg(R); // Value of this register should be: block zero, instruction 1, and the // location it's defined in is itself. ValueIDNum ToCmp(0, 1, L); EXPECT_EQ(V, ToCmp); } // Do the same again, but with an aliasing write. This should write to all // the same registers again, except $ah and $hax (the upper 8 bits of $ax // and 32 bits of $rax resp.). MF = readMIRBlock( " $rax = MOV64ri 0\n" " $al = MOV8ri 0\n" " RETQ $rax\n"); setupLDVObj(MF); TransferMap.clear(); TransferMap.resize(1); produceMLocTransferFunction(*MF, TransferMap, 1); auto TestRegSetSite = [&](const char *Name, unsigned InstrNum) { Register R = getRegByName(Name); ASSERT_TRUE(MTracker->isRegisterTracked(R)); LocIdx L = MTracker->getRegMLoc(R); ValueIDNum V = MTracker->readMLoc(L); ValueIDNum ToCmp(0, InstrNum, L); EXPECT_EQ(V, ToCmp); }; TestRegSetSite("AL", 2); TestRegSetSite("AH", 1); TestRegSetSite("AX", 2); TestRegSetSite("EAX", 2); TestRegSetSite("HAX", 1); TestRegSetSite("RAX", 2); // This call should: // * Def rax via the implicit-def, // * Clobber rsi/rdi and all their subregs, via the register mask // * Same for rcx, despite it not being a use in the instr, it's in the mask // * NOT clobber $rsp / $esp $ sp, LiveDebugValues deliberately ignores // these. // * NOT clobber $rbx, because it's non-volatile // * Not track every other register in the machine, only those needed. MF = readMIRBlock( " $rax = MOV64ri 0\n" // instr 1 " $rbx = MOV64ri 0\n" // instr 2 " $rcx = MOV64ri 0\n" // instr 3 " $rdi = MOV64ri 0\n" // instr 4 " $rsi = MOV64ri 0\n" // instr 5 " CALL64r $rax, csr_64, implicit $rsp, implicit $ssp, implicit $rdi, implicit $rsi, implicit-def $rsp, implicit-def $ssp, implicit-def $rax, implicit-def $esp, implicit-def $sp\n\n\n\n" // instr 6 " RETQ $rax\n"); // instr 7 setupLDVObj(MF); TransferMap.clear(); TransferMap.resize(1); produceMLocTransferFunction(*MF, TransferMap, 1); const char *RegsSetInCall[] = {"AL", "AH", "AX", "EAX", "HAX", "RAX", "DIL", "DIH", "DI", "EDI", "HDI", "RDI", "SIL", "SIH", "SI", "ESI", "HSI", "RSI", "CL", "CH", "CX", "ECX", "HCX", "RCX"}; for (const char *RegSetInCall : RegsSetInCall) TestRegSetSite(RegSetInCall, 6); const char *RegsLeftAlone[] = {"BL", "BH", "BX", "EBX", "HBX", "RBX"}; for (const char *RegLeftAlone : RegsLeftAlone) TestRegSetSite(RegLeftAlone, 2); // Stack pointer should be the live-in to the function, instruction zero. TestRegSetSite("RSP", 0); // These stack regs should not be tracked either. Nor the (fake) subregs. EXPECT_FALSE(MTracker->isRegisterTracked(getRegByName("ESP"))); EXPECT_FALSE(MTracker->isRegisterTracked(getRegByName("SP"))); EXPECT_FALSE(MTracker->isRegisterTracked(getRegByName("SPL"))); EXPECT_FALSE(MTracker->isRegisterTracked(getRegByName("SPH"))); EXPECT_FALSE(MTracker->isRegisterTracked(getRegByName("HSP"))); // Should only be tracking: 6 x {A, B, C, DI, SI} registers = 30, // Plus RSP, SSP = 32. EXPECT_EQ(32u, MTracker->getNumLocs()); // When we DBG_PHI something, we should track all its subregs. MF = readMIRBlock( " DBG_PHI $rdi, 0\n" " RETQ\n"); setupLDVObj(MF); TransferMap.clear(); TransferMap.resize(1); produceMLocTransferFunction(*MF, TransferMap, 1); // All DI regs and RSP tracked. EXPECT_EQ(7u, MTracker->getNumLocs()); // All the DI registers should have block live-in values, i.e. the argument // to the function. const char *DIRegs[] = {"DIL", "DIH", "DI", "EDI", "HDI", "RDI"}; for (const char *DIReg : DIRegs) TestRegSetSite(DIReg, 0); } TEST_F(InstrRefLDVTest, MTransferMeta) { // Meta instructions should not have any effect on register values. SmallVector<MLocTransferMap, 1> TransferMap; MachineFunction *MF = readMIRBlock( " $rax = MOV64ri 0\n" " $rax = IMPLICIT_DEF\n" " $rax = KILL killed $rax\n" " RETQ $rax\n"); setupLDVObj(MF); TransferMap.clear(); TransferMap.resize(1); produceMLocTransferFunction(*MF, TransferMap, 1); LocIdx RaxLoc = MTracker->getRegMLoc(getRegByName("RAX")); ValueIDNum V = MTracker->readMLoc(RaxLoc); // Def of rax should be from instruction 1, i.e., unmodified. ValueIDNum Cmp(0, 1, RaxLoc); EXPECT_EQ(Cmp, V); } TEST_F(InstrRefLDVTest, MTransferCopies) { SmallVector<MLocTransferMap, 1> TransferMap; // This memory spill should be recognised, and a spill slot created. MachineFunction *MF = readMIRBlock( " $rax = MOV64ri 0\n" " MOV64mr $rsp, 1, $noreg, 16, $noreg, $rax :: (store 8 into %stack.0)\n" " RETQ $rax\n"); setupLDVObj(MF); TransferMap.clear(); TransferMap.resize(1); produceMLocTransferFunction(*MF, TransferMap, 1); // Check that the spill location contains the value defined in rax by // instruction 1. The MIR header says -16 offset, but it's stored as -8; // it's not completely clear why, but here we only care about correctly // identifying the slot, not that all the surrounding data is correct. SpillLoc L = {getRegByName("RSP"), StackOffset::getFixed(-8)}; SpillLocationNo SpillNo = MTracker->getOrTrackSpillLoc(L); unsigned SpillLocID = MTracker->getLocID(SpillNo, {64, 0}); LocIdx SpillLoc = MTracker->getSpillMLoc(SpillLocID); ValueIDNum V = MTracker->readMLoc(SpillLoc); Register RAX = getRegByName("RAX"); LocIdx RaxLoc = MTracker->getRegMLoc(RAX); ValueIDNum Cmp(0, 1, RaxLoc); EXPECT_EQ(V, Cmp); // A spill and restore should be recognised. MF = readMIRBlock( " $rax = MOV64ri 0\n" " MOV64mr $rsp, 1, $noreg, 16, $noreg, $rax :: (store 8 into %stack.0)\n" " $rbx = MOV64rm $rsp, 1, $noreg, 0, $noreg :: (load 8 from %stack.0)\n" " RETQ\n"); setupLDVObj(MF); TransferMap.clear(); TransferMap.resize(1); produceMLocTransferFunction(*MF, TransferMap, 1); // Test that rbx contains rax from instruction 1. RAX = getRegByName("RAX"); RaxLoc = MTracker->getRegMLoc(RAX); Register RBX = getRegByName("RBX"); LocIdx RbxLoc = MTracker->getRegMLoc(RBX); Cmp = ValueIDNum(0, 1, RaxLoc); ValueIDNum RbxVal = MTracker->readMLoc(RbxLoc); EXPECT_EQ(RbxVal, Cmp); // Testing that all the subregisters are transferred happens in // MTransferSubregSpills. // Copies and x86 movs should be recognised and honoured. In addition, all // of the subregisters should be copied across too. MF = readMIRBlock( " $rax = MOV64ri 0\n" " $rcx = COPY $rax\n" " $rbx = MOV64rr $rcx\n" " RETQ\n"); setupLDVObj(MF); TransferMap.clear(); TransferMap.resize(1); produceMLocTransferFunction(*MF, TransferMap, 1); const char *ARegs[] = {"AL", "AH", "AX", "EAX", "HAX", "RAX"}; const char *BRegs[] = {"BL", "BH", "BX", "EBX", "HBX", "RBX"}; const char *CRegs[] = {"CL", "CH", "CX", "ECX", "HCX", "RCX"}; auto CheckReg = [&](unsigned int I) { LocIdx A = MTracker->getRegMLoc(getRegByName(ARegs[I])); LocIdx B = MTracker->getRegMLoc(getRegByName(BRegs[I])); LocIdx C = MTracker->getRegMLoc(getRegByName(CRegs[I])); ValueIDNum ARefVal(0, 1, A); ValueIDNum AVal = MTracker->readMLoc(A); ValueIDNum BVal = MTracker->readMLoc(B); ValueIDNum CVal = MTracker->readMLoc(C); EXPECT_EQ(ARefVal, AVal); EXPECT_EQ(ARefVal, BVal); EXPECT_EQ(ARefVal, CVal); }; for (unsigned int I = 0; I < 6; ++I) CheckReg(I); // When we copy to a subregister, the super-register should be def'd too: it's // value will have changed. MF = readMIRBlock( " $rax = MOV64ri 0\n" " $ecx = COPY $eax\n" " RETQ\n"); setupLDVObj(MF); TransferMap.clear(); TransferMap.resize(1); produceMLocTransferFunction(*MF, TransferMap, 1); // First four regs [al, ah, ax, eax] should be copied to *cx. for (unsigned int I = 0; I < 4; ++I) { LocIdx A = MTracker->getRegMLoc(getRegByName(ARegs[I])); LocIdx C = MTracker->getRegMLoc(getRegByName(CRegs[I])); ValueIDNum ARefVal(0, 1, A); ValueIDNum AVal = MTracker->readMLoc(A); ValueIDNum CVal = MTracker->readMLoc(C); EXPECT_EQ(ARefVal, AVal); EXPECT_EQ(ARefVal, CVal); } // But rcx should contain a value defined by the COPY. LocIdx RcxLoc = MTracker->getRegMLoc(getRegByName("RCX")); ValueIDNum RcxVal = MTracker->readMLoc(RcxLoc); ValueIDNum RcxDefVal(0, 2, RcxLoc); // instr 2 -> the copy EXPECT_EQ(RcxVal, RcxDefVal); } TEST_F(InstrRefLDVTest, MTransferSubregSpills) { SmallVector<MLocTransferMap, 1> TransferMap; MachineFunction *MF = readMIRBlock( " $rax = MOV64ri 0\n" " MOV64mr $rsp, 1, $noreg, 16, $noreg, $rax :: (store 8 into %stack.0)\n" " $rbx = MOV64rm $rsp, 1, $noreg, 0, $noreg :: (load 8 from %stack.0)\n" " RETQ\n"); setupLDVObj(MF); TransferMap.clear(); TransferMap.resize(1); produceMLocTransferFunction(*MF, TransferMap, 1); // Check that all the subregs of rax and rbx contain the same values. One // should completely transfer to the other. const char *ARegs[] = {"AL", "AH", "AX", "EAX", "HAX", "RAX"}; const char *BRegs[] = {"BL", "BH", "BX", "EBX", "HBX", "RBX"}; for (unsigned int I = 0; I < 6; ++I) { LocIdx A = MTracker->getRegMLoc(getRegByName(ARegs[I])); LocIdx B = MTracker->getRegMLoc(getRegByName(BRegs[I])); EXPECT_EQ(MTracker->readMLoc(A), MTracker->readMLoc(B)); } // Explicitly check what's in the different subreg slots, on the stack. // Pair up subreg idx fields with the corresponding subregister in $rax. MLocTracker::StackSlotPos SubRegIdxes[] = {{8, 0}, {8, 8}, {16, 0}, {32, 0}, {64, 0}}; const char *SubRegNames[] = {"AL", "AH", "AX", "EAX", "RAX"}; for (unsigned int I = 0; I < 5; ++I) { // Value number where it's defined, LocIdx RegLoc = MTracker->getRegMLoc(getRegByName(SubRegNames[I])); ValueIDNum DefNum(0, 1, RegLoc); // Read the corresponding subreg field from the stack. SpillLoc L = {getRegByName("RSP"), StackOffset::getFixed(-8)}; SpillLocationNo SpillNo = MTracker->getOrTrackSpillLoc(L); unsigned SpillID = MTracker->getLocID(SpillNo, SubRegIdxes[I]); LocIdx SpillLoc = MTracker->getSpillMLoc(SpillID); ValueIDNum SpillValue = MTracker->readMLoc(SpillLoc); EXPECT_EQ(DefNum, SpillValue); } // If we have exactly the same code, but we write $eax to the stack slot after // $rax, then we should still have exactly the same output in the lower five // subregisters. Storing $eax to the start of the slot will overwrite with the // same values. $rax, as an aliasing register, should be reset to something // else by that write. // In theory, we could try and recognise that we're writing the _same_ values // to the stack again, and so $rax doesn't need to be reset to something else. // It seems vanishingly unlikely that LLVM would generate such code though, // so the benefits would be small. MF = readMIRBlock( " $rax = MOV64ri 0\n" " MOV64mr $rsp, 1, $noreg, 16, $noreg, $rax :: (store 8 into %stack.0)\n" " MOV32mr $rsp, 1, $noreg, 16, $noreg, $eax :: (store 4 into %stack.0)\n" " $rbx = MOV64rm $rsp, 1, $noreg, 0, $noreg :: (load 8 from %stack.0)\n" " RETQ\n"); setupLDVObj(MF); TransferMap.clear(); TransferMap.resize(1); produceMLocTransferFunction(*MF, TransferMap, 1); // Check lower five registers up to and include $eax == $ebx, for (unsigned int I = 0; I < 5; ++I) { LocIdx A = MTracker->getRegMLoc(getRegByName(ARegs[I])); LocIdx B = MTracker->getRegMLoc(getRegByName(BRegs[I])); EXPECT_EQ(MTracker->readMLoc(A), MTracker->readMLoc(B)); } // $rbx should contain something else; today it's a def at the spill point // of the 4 byte value. SpillLoc L = {getRegByName("RSP"), StackOffset::getFixed(-8)}; SpillLocationNo SpillNo = MTracker->getOrTrackSpillLoc(L); unsigned SpillID = MTracker->getLocID(SpillNo, {64, 0}); LocIdx Spill64Loc = MTracker->getSpillMLoc(SpillID); ValueIDNum DefAtSpill64(0, 3, Spill64Loc); LocIdx RbxLoc = MTracker->getRegMLoc(getRegByName("RBX")); EXPECT_EQ(MTracker->readMLoc(RbxLoc), DefAtSpill64); // Same again, test that the lower four subreg slots on the stack are the // value defined by $rax in instruction 1. for (unsigned int I = 0; I < 4; ++I) { // Value number where it's defined, LocIdx RegLoc = MTracker->getRegMLoc(getRegByName(SubRegNames[I])); ValueIDNum DefNum(0, 1, RegLoc); // Read the corresponding subreg field from the stack. SpillNo = MTracker->getOrTrackSpillLoc(L); SpillID = MTracker->getLocID(SpillNo, SubRegIdxes[I]); LocIdx SpillLoc = MTracker->getSpillMLoc(SpillID); ValueIDNum SpillValue = MTracker->readMLoc(SpillLoc); EXPECT_EQ(DefNum, SpillValue); } // Stack slot for $rax should be a different value, today it's EmptyValue. ValueIDNum SpillValue = MTracker->readMLoc(Spill64Loc); EXPECT_EQ(SpillValue, DefAtSpill64); // If we write something to the stack, then over-write with some register // from a completely different hierarchy, none of the "old" values should be // readable. // NB: slight hack, store 16 in to a 8 byte stack slot. MF = readMIRBlock( " $rax = MOV64ri 0\n" " MOV64mr $rsp, 1, $noreg, 16, $noreg, $rax :: (store 8 into %stack.0)\n" " $xmm0 = IMPLICIT_DEF\n" " MOVUPDmr $rsp, 1, $noreg, 16, $noreg, killed $xmm0 :: (store (s128) into %stack.0)\n" " $rbx = MOV64rm $rsp, 1, $noreg, 0, $noreg :: (load 8 from %stack.0)\n" " RETQ\n"); setupLDVObj(MF); TransferMap.clear(); TransferMap.resize(1); produceMLocTransferFunction(*MF, TransferMap, 1); for (unsigned int I = 0; I < 5; ++I) { // Read subreg fields from the stack. SpillLocationNo SpillNo = MTracker->getOrTrackSpillLoc(L); unsigned SpillID = MTracker->getLocID(SpillNo, SubRegIdxes[I]); LocIdx SpillLoc = MTracker->getSpillMLoc(SpillID); ValueIDNum SpillValue = MTracker->readMLoc(SpillLoc); // Value should be defined by the spill-to-xmm0 instr, get value of a def // at the point of the spill. ValueIDNum SpillDef(0, 4, SpillLoc); EXPECT_EQ(SpillValue, SpillDef); } // Read xmm0's position and ensure it has a value. Should be the live-in // value to the block, as IMPLICIT_DEF isn't a real def. SpillNo = MTracker->getOrTrackSpillLoc(L); SpillID = MTracker->getLocID(SpillNo, {128, 0}); LocIdx Spill128Loc = MTracker->getSpillMLoc(SpillID); SpillValue = MTracker->readMLoc(Spill128Loc); Register XMM0 = getRegByName("XMM0"); LocIdx Xmm0Loc = MTracker->getRegMLoc(XMM0); EXPECT_EQ(ValueIDNum(0, 0, Xmm0Loc), SpillValue); // What happens if we spill ah to the stack, then load al? It should find // the same value. MF = readMIRBlock( " $rax = MOV64ri 0\n" " MOV8mr $rsp, 1, $noreg, 16, $noreg, $ah :: (store 1 into %stack.0)\n" " $al = MOV8rm $rsp, 1, $noreg, 0, $noreg :: (load 1 from %stack.0)\n" " RETQ\n"); setupLDVObj(MF); TransferMap.clear(); TransferMap.resize(1); produceMLocTransferFunction(*MF, TransferMap, 1); Register AL = getRegByName("AL"); Register AH = getRegByName("AH"); LocIdx AlLoc = MTracker->getRegMLoc(AL); LocIdx AhLoc = MTracker->getRegMLoc(AH); ValueIDNum AHDef(0, 1, AhLoc); ValueIDNum ALValue = MTracker->readMLoc(AlLoc); EXPECT_EQ(ALValue, AHDef); } TEST_F(InstrRefLDVTest, MLocSingleBlock) { // Test some very simple properties about interpreting the transfer function. setupSingleBlock(); // We should start with a single location, the stack pointer. ASSERT_TRUE(MTracker->getNumLocs() == 1); LocIdx RspLoc(0); // Set up live-in and live-out tables for this function: two locations (we // add one later) in a single block. ValueIDNum InLocs[2], OutLocs[2]; ValueIDNum *InLocsPtr[1] = {&InLocs[0]}; ValueIDNum *OutLocsPtr[1] = {&OutLocs[0]}; // Transfer function: nothing. SmallVector<MLocTransferMap, 1> TransferFunc; TransferFunc.resize(1); // Try and build value maps... buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc); // The result should be that RSP is marked as a live-in-PHI -- this represents // an argument. And as there's no transfer function, the block live-out should // be the same. EXPECT_EQ(InLocs[0], ValueIDNum(0, 0, RspLoc)); EXPECT_EQ(OutLocs[0], ValueIDNum(0, 0, RspLoc)); // Try again, this time initialising the in-locs to be defined by an // instruction. The entry block should always be re-assigned to be the // arguments. initValueArray(InLocsPtr, 1, 2); initValueArray(OutLocsPtr, 1, 2); InLocs[0] = ValueIDNum(0, 1, RspLoc); buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc); EXPECT_EQ(InLocs[0], ValueIDNum(0, 0, RspLoc)); EXPECT_EQ(OutLocs[0], ValueIDNum(0, 0, RspLoc)); // Now insert something into the transfer function to assign to the single // machine location. TransferFunc[0].insert({RspLoc, ValueIDNum(0, 1, RspLoc)}); initValueArray(InLocsPtr, 1, 2); initValueArray(OutLocsPtr, 1, 2); buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc); EXPECT_EQ(InLocs[0], ValueIDNum(0, 0, RspLoc)); EXPECT_EQ(OutLocs[0], ValueIDNum(0, 1, RspLoc)); TransferFunc[0].clear(); // Add a new register to be tracked, and insert it into the transfer function // as a copy. The output of $rax should be the live-in value of $rsp. Register RAX = getRegByName("RAX"); LocIdx RaxLoc = MTracker->lookupOrTrackRegister(RAX); TransferFunc[0].insert({RspLoc, ValueIDNum(0, 1, RspLoc)}); TransferFunc[0].insert({RaxLoc, ValueIDNum(0, 0, RspLoc)}); initValueArray(InLocsPtr, 1, 2); initValueArray(OutLocsPtr, 1, 2); buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc); EXPECT_EQ(InLocs[0], ValueIDNum(0, 0, RspLoc)); EXPECT_EQ(InLocs[1], ValueIDNum(0, 0, RaxLoc)); EXPECT_EQ(OutLocs[0], ValueIDNum(0, 1, RspLoc)); EXPECT_EQ(OutLocs[1], ValueIDNum(0, 0, RspLoc)); // Rax contains RspLoc. TransferFunc[0].clear(); } TEST_F(InstrRefLDVTest, MLocDiamondBlocks) { // Test that information flows from the entry block to two successors. // entry // / \ // br1 br2 // \ / // ret setupDiamondBlocks(); ASSERT_TRUE(MTracker->getNumLocs() == 1); LocIdx RspLoc(0); Register RAX = getRegByName("RAX"); LocIdx RaxLoc = MTracker->lookupOrTrackRegister(RAX); ValueIDNum InLocs[4][2], OutLocs[4][2]; ValueIDNum *InLocsPtr[4] = {InLocs[0], InLocs[1], InLocs[2], InLocs[3]}; ValueIDNum *OutLocsPtr[4] = {OutLocs[0], OutLocs[1], OutLocs[2], OutLocs[3]}; // Transfer function: start with nothing. SmallVector<MLocTransferMap, 1> TransferFunc; TransferFunc.resize(4); // Name some values. unsigned EntryBlk = 0, BrBlk1 = 1, BrBlk2 = 2, RetBlk = 3; ValueIDNum LiveInRsp(EntryBlk, 0, RspLoc); ValueIDNum RspDefInBlk0(EntryBlk, 1, RspLoc); ValueIDNum RspDefInBlk1(BrBlk1, 1, RspLoc); ValueIDNum RspDefInBlk2(BrBlk2, 1, RspLoc); ValueIDNum RspPHIInBlk3(RetBlk, 0, RspLoc); ValueIDNum RaxLiveInBlk1(BrBlk1, 0, RaxLoc); ValueIDNum RaxLiveInBlk2(BrBlk2, 0, RaxLoc); // With no transfer function, the live-in values to the entry block should // propagate to all live-outs and the live-ins to the two successor blocks. // IN ADDITION: this checks that the exit block doesn't get a PHI put in it. initValueArray(InLocsPtr, 4, 2); initValueArray(OutLocsPtr, 4, 2); buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc); EXPECT_EQ(InLocs[0][0], LiveInRsp); EXPECT_EQ(InLocs[1][0], LiveInRsp); EXPECT_EQ(InLocs[2][0], LiveInRsp); EXPECT_EQ(InLocs[3][0], LiveInRsp); EXPECT_EQ(OutLocs[0][0], LiveInRsp); EXPECT_EQ(OutLocs[1][0], LiveInRsp); EXPECT_EQ(OutLocs[2][0], LiveInRsp); EXPECT_EQ(OutLocs[3][0], LiveInRsp); // (Skipped writing out locations for $rax). // Check that a def of $rsp in the entry block will likewise reach all the // successors. TransferFunc[0].insert({RspLoc, RspDefInBlk0}); initValueArray(InLocsPtr, 4, 2); initValueArray(OutLocsPtr, 4, 2); buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc); EXPECT_EQ(InLocs[0][0], LiveInRsp); EXPECT_EQ(InLocs[1][0], RspDefInBlk0); EXPECT_EQ(InLocs[2][0], RspDefInBlk0); EXPECT_EQ(InLocs[3][0], RspDefInBlk0); EXPECT_EQ(OutLocs[0][0], RspDefInBlk0); EXPECT_EQ(OutLocs[1][0], RspDefInBlk0); EXPECT_EQ(OutLocs[2][0], RspDefInBlk0); EXPECT_EQ(OutLocs[3][0], RspDefInBlk0); TransferFunc[0].clear(); // Def in one branch of the diamond means that we need a PHI in the ret block TransferFunc[0].insert({RspLoc, RspDefInBlk0}); TransferFunc[1].insert({RspLoc, RspDefInBlk1}); initValueArray(InLocsPtr, 4, 2); initValueArray(OutLocsPtr, 4, 2); buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc); // This value map: like above, where RspDefInBlk0 is propagated through one // branch of the diamond, but is def'ed in the live-outs of the other. The // ret / merging block should have a PHI in its live-ins. EXPECT_EQ(InLocs[0][0], LiveInRsp); EXPECT_EQ(InLocs[1][0], RspDefInBlk0); EXPECT_EQ(InLocs[2][0], RspDefInBlk0); EXPECT_EQ(InLocs[3][0], RspPHIInBlk3); EXPECT_EQ(OutLocs[0][0], RspDefInBlk0); EXPECT_EQ(OutLocs[1][0], RspDefInBlk1); EXPECT_EQ(OutLocs[2][0], RspDefInBlk0); EXPECT_EQ(OutLocs[3][0], RspPHIInBlk3); TransferFunc[0].clear(); TransferFunc[1].clear(); // If we have differeing defs in either side of the diamond, we should // continue to produce a PHI, TransferFunc[0].insert({RspLoc, RspDefInBlk0}); TransferFunc[1].insert({RspLoc, RspDefInBlk1}); TransferFunc[2].insert({RspLoc, RspDefInBlk2}); initValueArray(InLocsPtr, 4, 2); initValueArray(OutLocsPtr, 4, 2); buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc); EXPECT_EQ(InLocs[0][0], LiveInRsp); EXPECT_EQ(InLocs[1][0], RspDefInBlk0); EXPECT_EQ(InLocs[2][0], RspDefInBlk0); EXPECT_EQ(InLocs[3][0], RspPHIInBlk3); EXPECT_EQ(OutLocs[0][0], RspDefInBlk0); EXPECT_EQ(OutLocs[1][0], RspDefInBlk1); EXPECT_EQ(OutLocs[2][0], RspDefInBlk2); EXPECT_EQ(OutLocs[3][0], RspPHIInBlk3); TransferFunc[0].clear(); TransferFunc[1].clear(); TransferFunc[2].clear(); // If we have defs of the same value on either side of the branch, a PHI will // initially be created, however value propagation should then eliminate it. // Encode this by copying the live-in value to $rax, and copying it to $rsp // from $rax in each branch of the diamond. We don't allow the definition of // arbitary values in transfer functions. TransferFunc[0].insert({RspLoc, RspDefInBlk0}); TransferFunc[0].insert({RaxLoc, LiveInRsp}); TransferFunc[1].insert({RspLoc, RaxLiveInBlk1}); TransferFunc[2].insert({RspLoc, RaxLiveInBlk2}); initValueArray(InLocsPtr, 4, 2); initValueArray(OutLocsPtr, 4, 2); buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc); EXPECT_EQ(InLocs[0][0], LiveInRsp); EXPECT_EQ(InLocs[1][0], RspDefInBlk0); EXPECT_EQ(InLocs[2][0], RspDefInBlk0); EXPECT_EQ(InLocs[3][0], LiveInRsp); EXPECT_EQ(OutLocs[0][0], RspDefInBlk0); EXPECT_EQ(OutLocs[1][0], LiveInRsp); EXPECT_EQ(OutLocs[2][0], LiveInRsp); EXPECT_EQ(OutLocs[3][0], LiveInRsp); TransferFunc[0].clear(); TransferFunc[1].clear(); TransferFunc[2].clear(); } TEST_F(InstrRefLDVTest, MLocDiamondSpills) { // Test that defs in stack locations that require PHIs, cause PHIs to be // installed in aliasing locations. i.e., if there's a PHI in the lower // 8 bits of the stack, there should be PHIs for 16/32/64 bit locations // on the stack too. // Technically this isn't needed for accuracy: we should calculate PHIs // independently for each location. However, because there's an optimisation // that only places PHIs for the lower "interfering" parts of stack slots, // test for this behaviour. setupDiamondBlocks(); ASSERT_TRUE(MTracker->getNumLocs() == 1); LocIdx RspLoc(0); // Create a stack location and ensure it's tracked. SpillLoc SL = {getRegByName("RSP"), StackOffset::getFixed(-8)}; SpillLocationNo SpillNo = MTracker->getOrTrackSpillLoc(SL); ASSERT_EQ(MTracker->getNumLocs(), 10u); // Tracks all possible stack locs. // Locations are: RSP, stack slots from 2^3 bits wide up to 2^9 for zmm regs, // then slots for sub_8bit_hi and sub_16bit_hi ({8, 8} and {16, 16}). // Pick out the locations on the stack that various x86 regs would be written // to. HAX is the upper 16 bits of EAX. unsigned ALID = MTracker->getLocID(SpillNo, {8, 0}); unsigned AHID = MTracker->getLocID(SpillNo, {8, 8}); unsigned AXID = MTracker->getLocID(SpillNo, {16, 0}); unsigned EAXID = MTracker->getLocID(SpillNo, {32, 0}); unsigned HAXID = MTracker->getLocID(SpillNo, {16, 16}); unsigned RAXID = MTracker->getLocID(SpillNo, {64, 0}); LocIdx ALStackLoc = MTracker->getSpillMLoc(ALID); LocIdx AHStackLoc = MTracker->getSpillMLoc(AHID); LocIdx AXStackLoc = MTracker->getSpillMLoc(AXID); LocIdx EAXStackLoc = MTracker->getSpillMLoc(EAXID); LocIdx HAXStackLoc = MTracker->getSpillMLoc(HAXID); LocIdx RAXStackLoc = MTracker->getSpillMLoc(RAXID); // There are other locations, for things like xmm0, which we're going to // ignore here. ValueIDNum InLocs[4][10]; ValueIDNum *InLocsPtr[4] = {InLocs[0], InLocs[1], InLocs[2], InLocs[3]}; // Transfer function: start with nothing. SmallVector<MLocTransferMap, 1> TransferFunc; TransferFunc.resize(4); // Name some values. unsigned EntryBlk = 0, Blk1 = 1, RetBlk = 3; ValueIDNum LiveInRsp(EntryBlk, 0, RspLoc); ValueIDNum ALLiveIn(EntryBlk, 0, ALStackLoc); ValueIDNum AHLiveIn(EntryBlk, 0, AHStackLoc); ValueIDNum HAXLiveIn(EntryBlk, 0, HAXStackLoc); ValueIDNum ALPHI(RetBlk, 0, ALStackLoc); ValueIDNum AXPHI(RetBlk, 0, AXStackLoc); ValueIDNum EAXPHI(RetBlk, 0, EAXStackLoc); ValueIDNum HAXPHI(RetBlk, 0, HAXStackLoc); ValueIDNum RAXPHI(RetBlk, 0, RAXStackLoc); ValueIDNum ALDefInBlk1(Blk1, 1, ALStackLoc); ValueIDNum HAXDefInBlk1(Blk1, 1, HAXStackLoc); SmallPtrSet<MachineBasicBlock *, 4> AllBlocks{MBB0, MBB1, MBB2, MBB3}; // If we put defs into one side of the diamond, for AL and HAX, then we should // find all aliasing positions have PHIs placed. This isn't technically what // the transfer function says to do: but we're testing that the optimisation // to reduce IDF calculation does the right thing. // AH should not be def'd: it don't alias AL or HAX. // // NB: we don't call buildMLocValueMap, because it will try to eliminate the // upper-slot PHIs, and succeed because of our slightly cooked transfer // function. TransferFunc[1].insert({ALStackLoc, ALDefInBlk1}); TransferFunc[1].insert({HAXStackLoc, HAXDefInBlk1}); initValueArray(InLocsPtr, 4, 10); placeMLocPHIs(*MF, AllBlocks, InLocsPtr, TransferFunc); EXPECT_EQ(InLocs[3][ALStackLoc.asU64()], ALPHI); EXPECT_EQ(InLocs[3][AXStackLoc.asU64()], AXPHI); EXPECT_EQ(InLocs[3][EAXStackLoc.asU64()], EAXPHI); EXPECT_EQ(InLocs[3][HAXStackLoc.asU64()], HAXPHI); EXPECT_EQ(InLocs[3][RAXStackLoc.asU64()], RAXPHI); // AH should be left untouched, EXPECT_EQ(InLocs[3][AHStackLoc.asU64()], ValueIDNum::EmptyValue); } TEST_F(InstrRefLDVTest, MLocSimpleLoop) { // entry // | // |/-----\ // loopblk | // |\-----/ // | // ret setupSimpleLoop(); ASSERT_TRUE(MTracker->getNumLocs() == 1); LocIdx RspLoc(0); Register RAX = getRegByName("RAX"); LocIdx RaxLoc = MTracker->lookupOrTrackRegister(RAX); ValueIDNum InLocs[3][2], OutLocs[3][2]; ValueIDNum *InLocsPtr[3] = {InLocs[0], InLocs[1], InLocs[2]}; ValueIDNum *OutLocsPtr[3] = {OutLocs[0], OutLocs[1], OutLocs[2]}; SmallVector<MLocTransferMap, 1> TransferFunc; TransferFunc.resize(3); // Name some values. unsigned EntryBlk = 0, LoopBlk = 1, RetBlk = 2; ValueIDNum LiveInRsp(EntryBlk, 0, RspLoc); ValueIDNum RspPHIInBlk1(LoopBlk, 0, RspLoc); ValueIDNum RspDefInBlk1(LoopBlk, 1, RspLoc); ValueIDNum LiveInRax(EntryBlk, 0, RaxLoc); ValueIDNum RaxPHIInBlk1(LoopBlk, 0, RaxLoc); ValueIDNum RaxPHIInBlk2(RetBlk, 0, RaxLoc); // Begin test with all locations being live-through. initValueArray(InLocsPtr, 3, 2); initValueArray(OutLocsPtr, 3, 2); buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc); EXPECT_EQ(InLocs[0][0], LiveInRsp); EXPECT_EQ(InLocs[1][0], LiveInRsp); EXPECT_EQ(InLocs[2][0], LiveInRsp); EXPECT_EQ(OutLocs[0][0], LiveInRsp); EXPECT_EQ(OutLocs[1][0], LiveInRsp); EXPECT_EQ(OutLocs[2][0], LiveInRsp); // Add a def of $rsp to the loop block: it should be in the live-outs, but // should cause a PHI to be placed in the live-ins. Test the transfer function // by copying that PHI into $rax in the loop, then back to $rsp in the ret // block. TransferFunc[1].insert({RspLoc, RspDefInBlk1}); TransferFunc[1].insert({RaxLoc, RspPHIInBlk1}); TransferFunc[2].insert({RspLoc, RaxPHIInBlk2}); initValueArray(InLocsPtr, 3, 2); initValueArray(OutLocsPtr, 3, 2); buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc); EXPECT_EQ(InLocs[0][0], LiveInRsp); EXPECT_EQ(InLocs[1][0], RspPHIInBlk1); EXPECT_EQ(InLocs[2][0], RspDefInBlk1); EXPECT_EQ(OutLocs[0][0], LiveInRsp); EXPECT_EQ(OutLocs[1][0], RspDefInBlk1); EXPECT_EQ(OutLocs[2][0], RspPHIInBlk1); // Check rax as well, EXPECT_EQ(InLocs[0][1], LiveInRax); EXPECT_EQ(InLocs[1][1], RaxPHIInBlk1); EXPECT_EQ(InLocs[2][1], RspPHIInBlk1); EXPECT_EQ(OutLocs[0][1], LiveInRax); EXPECT_EQ(OutLocs[1][1], RspPHIInBlk1); EXPECT_EQ(OutLocs[2][1], RspPHIInBlk1); TransferFunc[1].clear(); TransferFunc[2].clear(); // As with the diamond case, a PHI will be created if there's a (implicit) // def in the entry block and loop block; but should be value propagated away // if it copies in the same value. Copy live-in $rsp to $rax, then copy it // into $rsp in the loop. Encoded as copying the live-in $rax value in block 1 // to $rsp. TransferFunc[0].insert({RaxLoc, LiveInRsp}); TransferFunc[1].insert({RspLoc, RaxPHIInBlk1}); initValueArray(InLocsPtr, 3, 2); initValueArray(OutLocsPtr, 3, 2); buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc); EXPECT_EQ(InLocs[0][0], LiveInRsp); EXPECT_EQ(InLocs[1][0], LiveInRsp); EXPECT_EQ(InLocs[2][0], LiveInRsp); EXPECT_EQ(OutLocs[0][0], LiveInRsp); EXPECT_EQ(OutLocs[1][0], LiveInRsp); EXPECT_EQ(OutLocs[2][0], LiveInRsp); // Check $rax's values. EXPECT_EQ(InLocs[0][1], LiveInRax); EXPECT_EQ(InLocs[1][1], LiveInRsp); EXPECT_EQ(InLocs[2][1], LiveInRsp); EXPECT_EQ(OutLocs[0][1], LiveInRsp); EXPECT_EQ(OutLocs[1][1], LiveInRsp); EXPECT_EQ(OutLocs[2][1], LiveInRsp); TransferFunc[0].clear(); TransferFunc[1].clear(); } TEST_F(InstrRefLDVTest, MLocNestedLoop) { // entry // | // loop1 // ^\ // | \ /-\ // | loop2 | // | / \-/ // ^ / // join // | // ret setupNestedLoops(); ASSERT_TRUE(MTracker->getNumLocs() == 1); LocIdx RspLoc(0); Register RAX = getRegByName("RAX"); LocIdx RaxLoc = MTracker->lookupOrTrackRegister(RAX); ValueIDNum InLocs[5][2], OutLocs[5][2]; ValueIDNum *InLocsPtr[5] = {InLocs[0], InLocs[1], InLocs[2], InLocs[3], InLocs[4]}; ValueIDNum *OutLocsPtr[5] = {OutLocs[0], OutLocs[1], OutLocs[2], OutLocs[3], OutLocs[4]}; SmallVector<MLocTransferMap, 1> TransferFunc; TransferFunc.resize(5); unsigned EntryBlk = 0, Loop1Blk = 1, Loop2Blk = 2, JoinBlk = 3; ValueIDNum LiveInRsp(EntryBlk, 0, RspLoc); ValueIDNum RspPHIInBlk1(Loop1Blk, 0, RspLoc); ValueIDNum RspDefInBlk1(Loop1Blk, 1, RspLoc); ValueIDNum RspPHIInBlk2(Loop2Blk, 0, RspLoc); ValueIDNum RspDefInBlk2(Loop2Blk, 1, RspLoc); ValueIDNum RspDefInBlk3(JoinBlk, 1, RspLoc); ValueIDNum LiveInRax(EntryBlk, 0, RaxLoc); ValueIDNum RaxPHIInBlk1(Loop1Blk, 0, RaxLoc); ValueIDNum RaxPHIInBlk2(Loop2Blk, 0, RaxLoc); // Like the other tests: first ensure that if there's nothing in the transfer // function, then everything is live-through (check $rsp). initValueArray(InLocsPtr, 5, 2); initValueArray(OutLocsPtr, 5, 2); buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc); EXPECT_EQ(InLocs[0][0], LiveInRsp); EXPECT_EQ(InLocs[1][0], LiveInRsp); EXPECT_EQ(InLocs[2][0], LiveInRsp); EXPECT_EQ(InLocs[3][0], LiveInRsp); EXPECT_EQ(InLocs[4][0], LiveInRsp); EXPECT_EQ(OutLocs[0][0], LiveInRsp); EXPECT_EQ(OutLocs[1][0], LiveInRsp); EXPECT_EQ(OutLocs[2][0], LiveInRsp); EXPECT_EQ(OutLocs[3][0], LiveInRsp); EXPECT_EQ(OutLocs[4][0], LiveInRsp); // A def in the inner loop means we should get PHIs at the heads of both // loops. Live-outs of the last three blocks will be the def, as it dominates // those. TransferFunc[2].insert({RspLoc, RspDefInBlk2}); initValueArray(InLocsPtr, 5, 2); initValueArray(OutLocsPtr, 5, 2); buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc); EXPECT_EQ(InLocs[0][0], LiveInRsp); EXPECT_EQ(InLocs[1][0], RspPHIInBlk1); EXPECT_EQ(InLocs[2][0], RspPHIInBlk2); EXPECT_EQ(InLocs[3][0], RspDefInBlk2); EXPECT_EQ(InLocs[4][0], RspDefInBlk2); EXPECT_EQ(OutLocs[0][0], LiveInRsp); EXPECT_EQ(OutLocs[1][0], RspPHIInBlk1); EXPECT_EQ(OutLocs[2][0], RspDefInBlk2); EXPECT_EQ(OutLocs[3][0], RspDefInBlk2); EXPECT_EQ(OutLocs[4][0], RspDefInBlk2); TransferFunc[2].clear(); // Adding a def to the outer loop header shouldn't affect this much -- the // live-out of block 1 changes. TransferFunc[1].insert({RspLoc, RspDefInBlk1}); TransferFunc[2].insert({RspLoc, RspDefInBlk2}); initValueArray(InLocsPtr, 5, 2); initValueArray(OutLocsPtr, 5, 2); buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc); EXPECT_EQ(InLocs[0][0], LiveInRsp); EXPECT_EQ(InLocs[1][0], RspPHIInBlk1); EXPECT_EQ(InLocs[2][0], RspPHIInBlk2); EXPECT_EQ(InLocs[3][0], RspDefInBlk2); EXPECT_EQ(InLocs[4][0], RspDefInBlk2); EXPECT_EQ(OutLocs[0][0], LiveInRsp); EXPECT_EQ(OutLocs[1][0], RspDefInBlk1); EXPECT_EQ(OutLocs[2][0], RspDefInBlk2); EXPECT_EQ(OutLocs[3][0], RspDefInBlk2); EXPECT_EQ(OutLocs[4][0], RspDefInBlk2); TransferFunc[1].clear(); TransferFunc[2].clear(); // Likewise, putting a def in the outer loop tail shouldn't affect where // the PHIs go, and should propagate into the ret block. TransferFunc[1].insert({RspLoc, RspDefInBlk1}); TransferFunc[2].insert({RspLoc, RspDefInBlk2}); TransferFunc[3].insert({RspLoc, RspDefInBlk3}); initValueArray(InLocsPtr, 5, 2); initValueArray(OutLocsPtr, 5, 2); buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc); EXPECT_EQ(InLocs[0][0], LiveInRsp); EXPECT_EQ(InLocs[1][0], RspPHIInBlk1); EXPECT_EQ(InLocs[2][0], RspPHIInBlk2); EXPECT_EQ(InLocs[3][0], RspDefInBlk2); EXPECT_EQ(InLocs[4][0], RspDefInBlk3); EXPECT_EQ(OutLocs[0][0], LiveInRsp); EXPECT_EQ(OutLocs[1][0], RspDefInBlk1); EXPECT_EQ(OutLocs[2][0], RspDefInBlk2); EXPECT_EQ(OutLocs[3][0], RspDefInBlk3); EXPECT_EQ(OutLocs[4][0], RspDefInBlk3); TransferFunc[1].clear(); TransferFunc[2].clear(); TransferFunc[3].clear(); // However: if we don't def in the inner-loop, then we just have defs in the // head and tail of the outer loop. The inner loop should be live-through. TransferFunc[1].insert({RspLoc, RspDefInBlk1}); TransferFunc[3].insert({RspLoc, RspDefInBlk3}); initValueArray(InLocsPtr, 5, 2); initValueArray(OutLocsPtr, 5, 2); buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc); EXPECT_EQ(InLocs[0][0], LiveInRsp); EXPECT_EQ(InLocs[1][0], RspPHIInBlk1); EXPECT_EQ(InLocs[2][0], RspDefInBlk1); EXPECT_EQ(InLocs[3][0], RspDefInBlk1); EXPECT_EQ(InLocs[4][0], RspDefInBlk3); EXPECT_EQ(OutLocs[0][0], LiveInRsp); EXPECT_EQ(OutLocs[1][0], RspDefInBlk1); EXPECT_EQ(OutLocs[2][0], RspDefInBlk1); EXPECT_EQ(OutLocs[3][0], RspDefInBlk3); EXPECT_EQ(OutLocs[4][0], RspDefInBlk3); TransferFunc[1].clear(); TransferFunc[3].clear(); // Check that this still works if we copy RspDefInBlk1 to $rax and then // copy it back into $rsp in the inner loop. TransferFunc[1].insert({RspLoc, RspDefInBlk1}); TransferFunc[1].insert({RaxLoc, RspDefInBlk1}); TransferFunc[2].insert({RspLoc, RaxPHIInBlk2}); TransferFunc[3].insert({RspLoc, RspDefInBlk3}); initValueArray(InLocsPtr, 5, 2); initValueArray(OutLocsPtr, 5, 2); buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc); EXPECT_EQ(InLocs[0][0], LiveInRsp); EXPECT_EQ(InLocs[1][0], RspPHIInBlk1); EXPECT_EQ(InLocs[2][0], RspDefInBlk1); EXPECT_EQ(InLocs[3][0], RspDefInBlk1); EXPECT_EQ(InLocs[4][0], RspDefInBlk3); EXPECT_EQ(OutLocs[0][0], LiveInRsp); EXPECT_EQ(OutLocs[1][0], RspDefInBlk1); EXPECT_EQ(OutLocs[2][0], RspDefInBlk1); EXPECT_EQ(OutLocs[3][0], RspDefInBlk3); EXPECT_EQ(OutLocs[4][0], RspDefInBlk3); // Look at raxes value in the relevant blocks, EXPECT_EQ(InLocs[2][1], RspDefInBlk1); EXPECT_EQ(OutLocs[1][1], RspDefInBlk1); TransferFunc[1].clear(); TransferFunc[2].clear(); TransferFunc[3].clear(); // If we have a single def in the tail of the outer loop, that should produce // a PHI at the loop head, and be live-through the inner loop. TransferFunc[3].insert({RspLoc, RspDefInBlk3}); initValueArray(InLocsPtr, 5, 2); initValueArray(OutLocsPtr, 5, 2); buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc); EXPECT_EQ(InLocs[0][0], LiveInRsp); EXPECT_EQ(InLocs[1][0], RspPHIInBlk1); EXPECT_EQ(InLocs[2][0], RspPHIInBlk1); EXPECT_EQ(InLocs[3][0], RspPHIInBlk1); EXPECT_EQ(InLocs[4][0], RspDefInBlk3); EXPECT_EQ(OutLocs[0][0], LiveInRsp); EXPECT_EQ(OutLocs[1][0], RspPHIInBlk1); EXPECT_EQ(OutLocs[2][0], RspPHIInBlk1); EXPECT_EQ(OutLocs[3][0], RspDefInBlk3); EXPECT_EQ(OutLocs[4][0], RspDefInBlk3); TransferFunc[3].clear(); // And if we copy from $rsp to $rax in block 2, it should resolve to the PHI // in block 1, and we should keep that value in rax until the ret block. // There'll be a PHI in block 1 and 2, because we're putting a def in the // inner loop. TransferFunc[2].insert({RaxLoc, RspPHIInBlk2}); TransferFunc[3].insert({RspLoc, RspDefInBlk3}); initValueArray(InLocsPtr, 5, 2); initValueArray(OutLocsPtr, 5, 2); buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc); // Examining the values of rax, EXPECT_EQ(InLocs[0][1], LiveInRax); EXPECT_EQ(InLocs[1][1], RaxPHIInBlk1); EXPECT_EQ(InLocs[2][1], RaxPHIInBlk2); EXPECT_EQ(InLocs[3][1], RspPHIInBlk1); EXPECT_EQ(InLocs[4][1], RspPHIInBlk1); EXPECT_EQ(OutLocs[0][1], LiveInRax); EXPECT_EQ(OutLocs[1][1], RaxPHIInBlk1); EXPECT_EQ(OutLocs[2][1], RspPHIInBlk1); EXPECT_EQ(OutLocs[3][1], RspPHIInBlk1); EXPECT_EQ(OutLocs[4][1], RspPHIInBlk1); TransferFunc[2].clear(); TransferFunc[3].clear(); } TEST_F(InstrRefLDVTest, MLocNoDominatingLoop) { // entry // / \ // / \ // / \ // head1 head2 // ^ \ / ^ // ^ \ / ^ // \-joinblk -/ // | // ret setupNoDominatingLoop(); ASSERT_TRUE(MTracker->getNumLocs() == 1); LocIdx RspLoc(0); Register RAX = getRegByName("RAX"); LocIdx RaxLoc = MTracker->lookupOrTrackRegister(RAX); ValueIDNum InLocs[5][2], OutLocs[5][2]; ValueIDNum *InLocsPtr[5] = {InLocs[0], InLocs[1], InLocs[2], InLocs[3], InLocs[4]}; ValueIDNum *OutLocsPtr[5] = {OutLocs[0], OutLocs[1], OutLocs[2], OutLocs[3], OutLocs[4]}; SmallVector<MLocTransferMap, 1> TransferFunc; TransferFunc.resize(5); unsigned EntryBlk = 0, Head1Blk = 1, Head2Blk = 2, JoinBlk = 3; ValueIDNum LiveInRsp(EntryBlk, 0, RspLoc); ValueIDNum RspPHIInBlk1(Head1Blk, 0, RspLoc); ValueIDNum RspDefInBlk1(Head1Blk, 1, RspLoc); ValueIDNum RspPHIInBlk2(Head2Blk, 0, RspLoc); ValueIDNum RspDefInBlk2(Head2Blk, 1, RspLoc); ValueIDNum RspPHIInBlk3(JoinBlk, 0, RspLoc); ValueIDNum RspDefInBlk3(JoinBlk, 1, RspLoc); ValueIDNum RaxPHIInBlk1(Head1Blk, 0, RaxLoc); ValueIDNum RaxPHIInBlk2(Head2Blk, 0, RaxLoc); // As ever, test that everything is live-through if there are no defs. initValueArray(InLocsPtr, 5, 2); initValueArray(OutLocsPtr, 5, 2); buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc); EXPECT_EQ(InLocs[0][0], LiveInRsp); EXPECT_EQ(InLocs[1][0], LiveInRsp); EXPECT_EQ(InLocs[2][0], LiveInRsp); EXPECT_EQ(InLocs[3][0], LiveInRsp); EXPECT_EQ(InLocs[4][0], LiveInRsp); EXPECT_EQ(OutLocs[0][0], LiveInRsp); EXPECT_EQ(OutLocs[1][0], LiveInRsp); EXPECT_EQ(OutLocs[2][0], LiveInRsp); EXPECT_EQ(OutLocs[3][0], LiveInRsp); EXPECT_EQ(OutLocs[4][0], LiveInRsp); // Putting a def in the 'join' block will cause us to have two distinct // PHIs in each loop head, then on entry to the join block. TransferFunc[3].insert({RspLoc, RspDefInBlk3}); initValueArray(InLocsPtr, 5, 2); initValueArray(OutLocsPtr, 5, 2); buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc); EXPECT_EQ(InLocs[0][0], LiveInRsp); EXPECT_EQ(InLocs[1][0], RspPHIInBlk1); EXPECT_EQ(InLocs[2][0], RspPHIInBlk2); EXPECT_EQ(InLocs[3][0], RspPHIInBlk3); EXPECT_EQ(InLocs[4][0], RspDefInBlk3); EXPECT_EQ(OutLocs[0][0], LiveInRsp); EXPECT_EQ(OutLocs[1][0], RspPHIInBlk1); EXPECT_EQ(OutLocs[2][0], RspPHIInBlk2); EXPECT_EQ(OutLocs[3][0], RspDefInBlk3); EXPECT_EQ(OutLocs[4][0], RspDefInBlk3); TransferFunc[3].clear(); // We should get the same behaviour if we put the def in either of the // loop heads -- it should force the other head to be a PHI. TransferFunc[1].insert({RspLoc, RspDefInBlk1}); initValueArray(InLocsPtr, 5, 2); initValueArray(OutLocsPtr, 5, 2); buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc); EXPECT_EQ(InLocs[0][0], LiveInRsp); EXPECT_EQ(InLocs[1][0], RspPHIInBlk1); EXPECT_EQ(InLocs[2][0], RspPHIInBlk2); EXPECT_EQ(InLocs[3][0], RspPHIInBlk3); EXPECT_EQ(InLocs[4][0], RspPHIInBlk3); EXPECT_EQ(OutLocs[0][0], LiveInRsp); EXPECT_EQ(OutLocs[1][0], RspDefInBlk1); EXPECT_EQ(OutLocs[2][0], RspPHIInBlk2); EXPECT_EQ(OutLocs[3][0], RspPHIInBlk3); EXPECT_EQ(OutLocs[4][0], RspPHIInBlk3); TransferFunc[1].clear(); // Check symmetry, TransferFunc[2].insert({RspLoc, RspDefInBlk2}); initValueArray(InLocsPtr, 5, 2); initValueArray(OutLocsPtr, 5, 2); buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc); EXPECT_EQ(InLocs[0][0], LiveInRsp); EXPECT_EQ(InLocs[1][0], RspPHIInBlk1); EXPECT_EQ(InLocs[2][0], RspPHIInBlk2); EXPECT_EQ(InLocs[3][0], RspPHIInBlk3); EXPECT_EQ(InLocs[4][0], RspPHIInBlk3); EXPECT_EQ(OutLocs[0][0], LiveInRsp); EXPECT_EQ(OutLocs[1][0], RspPHIInBlk1); EXPECT_EQ(OutLocs[2][0], RspDefInBlk2); EXPECT_EQ(OutLocs[3][0], RspPHIInBlk3); EXPECT_EQ(OutLocs[4][0], RspPHIInBlk3); TransferFunc[2].clear(); // Test some scenarios where there _shouldn't_ be any PHIs created at heads. // These are those PHIs are created, but value propagation eliminates them. // For example, lets copy rsp-livein to $rsp inside each loop head, so that // there's no need for a PHI in the join block. Put a def of $rsp in block 3 // to force PHIs elsewhere. TransferFunc[0].insert({RaxLoc, LiveInRsp}); TransferFunc[1].insert({RspLoc, RaxPHIInBlk1}); TransferFunc[2].insert({RspLoc, RaxPHIInBlk2}); TransferFunc[3].insert({RspLoc, RspDefInBlk3}); initValueArray(InLocsPtr, 5, 2); initValueArray(OutLocsPtr, 5, 2); buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc); EXPECT_EQ(InLocs[0][0], LiveInRsp); EXPECT_EQ(InLocs[1][0], RspPHIInBlk1); EXPECT_EQ(InLocs[2][0], RspPHIInBlk2); EXPECT_EQ(InLocs[3][0], LiveInRsp); EXPECT_EQ(InLocs[4][0], RspDefInBlk3); EXPECT_EQ(OutLocs[0][0], LiveInRsp); EXPECT_EQ(OutLocs[1][0], LiveInRsp); EXPECT_EQ(OutLocs[2][0], LiveInRsp); EXPECT_EQ(OutLocs[3][0], RspDefInBlk3); EXPECT_EQ(OutLocs[4][0], RspDefInBlk3); TransferFunc[0].clear(); TransferFunc[1].clear(); TransferFunc[2].clear(); TransferFunc[3].clear(); // In fact, if we eliminate the def in block 3, none of those PHIs are // necessary, as we're just repeatedly copying LiveInRsp into $rsp. They // should all be value propagated out. TransferFunc[0].insert({RaxLoc, LiveInRsp}); TransferFunc[1].insert({RspLoc, RaxPHIInBlk1}); TransferFunc[2].insert({RspLoc, RaxPHIInBlk2}); initValueArray(InLocsPtr, 5, 2); initValueArray(OutLocsPtr, 5, 2); buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc); EXPECT_EQ(InLocs[0][0], LiveInRsp); EXPECT_EQ(InLocs[1][0], LiveInRsp); EXPECT_EQ(InLocs[2][0], LiveInRsp); EXPECT_EQ(InLocs[3][0], LiveInRsp); EXPECT_EQ(InLocs[4][0], LiveInRsp); EXPECT_EQ(OutLocs[0][0], LiveInRsp); EXPECT_EQ(OutLocs[1][0], LiveInRsp); EXPECT_EQ(OutLocs[2][0], LiveInRsp); EXPECT_EQ(OutLocs[3][0], LiveInRsp); EXPECT_EQ(OutLocs[4][0], LiveInRsp); TransferFunc[0].clear(); TransferFunc[1].clear(); TransferFunc[2].clear(); } TEST_F(InstrRefLDVTest, MLocBadlyNestedLoops) { // entry // | // loop1 -o // | ^ // | ^ // loop2 -o // | ^ // | ^ // loop3 -o // | // ret setupBadlyNestedLoops(); ASSERT_TRUE(MTracker->getNumLocs() == 1); LocIdx RspLoc(0); Register RAX = getRegByName("RAX"); LocIdx RaxLoc = MTracker->lookupOrTrackRegister(RAX); ValueIDNum InLocs[5][2], OutLocs[5][2]; ValueIDNum *InLocsPtr[5] = {InLocs[0], InLocs[1], InLocs[2], InLocs[3], InLocs[4]}; ValueIDNum *OutLocsPtr[5] = {OutLocs[0], OutLocs[1], OutLocs[2], OutLocs[3], OutLocs[4]}; SmallVector<MLocTransferMap, 1> TransferFunc; TransferFunc.resize(5); unsigned EntryBlk = 0, Loop1Blk = 1, Loop2Blk = 2, Loop3Blk = 3; ValueIDNum LiveInRsp(EntryBlk, 0, RspLoc); ValueIDNum RspPHIInBlk1(Loop1Blk, 0, RspLoc); ValueIDNum RspDefInBlk1(Loop1Blk, 1, RspLoc); ValueIDNum RspPHIInBlk2(Loop2Blk, 0, RspLoc); ValueIDNum RspPHIInBlk3(Loop3Blk, 0, RspLoc); ValueIDNum RspDefInBlk3(Loop3Blk, 1, RspLoc); ValueIDNum LiveInRax(EntryBlk, 0, RaxLoc); ValueIDNum RaxPHIInBlk3(Loop3Blk, 0, RaxLoc); // As ever, test that everything is live-through if there are no defs. initValueArray(InLocsPtr, 5, 2); initValueArray(OutLocsPtr, 5, 2); buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc); EXPECT_EQ(InLocs[0][0], LiveInRsp); EXPECT_EQ(InLocs[1][0], LiveInRsp); EXPECT_EQ(InLocs[2][0], LiveInRsp); EXPECT_EQ(InLocs[3][0], LiveInRsp); EXPECT_EQ(InLocs[4][0], LiveInRsp); EXPECT_EQ(OutLocs[0][0], LiveInRsp); EXPECT_EQ(OutLocs[1][0], LiveInRsp); EXPECT_EQ(OutLocs[2][0], LiveInRsp); EXPECT_EQ(OutLocs[3][0], LiveInRsp); EXPECT_EQ(OutLocs[4][0], LiveInRsp); // A def in loop3 should cause PHIs in every loop block: they're all // reachable from each other. TransferFunc[3].insert({RspLoc, RspDefInBlk3}); initValueArray(InLocsPtr, 5, 2); initValueArray(OutLocsPtr, 5, 2); buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc); EXPECT_EQ(InLocs[0][0], LiveInRsp); EXPECT_EQ(InLocs[1][0], RspPHIInBlk1); EXPECT_EQ(InLocs[2][0], RspPHIInBlk2); EXPECT_EQ(InLocs[3][0], RspPHIInBlk3); EXPECT_EQ(InLocs[4][0], RspDefInBlk3); EXPECT_EQ(OutLocs[0][0], LiveInRsp); EXPECT_EQ(OutLocs[1][0], RspPHIInBlk1); EXPECT_EQ(OutLocs[2][0], RspPHIInBlk2); EXPECT_EQ(OutLocs[3][0], RspDefInBlk3); EXPECT_EQ(OutLocs[4][0], RspDefInBlk3); TransferFunc[3].clear(); // A def in loop1 should cause a PHI in loop1, but not the other blocks. // loop2 and loop3 are dominated by the def in loop1, so they should have // that value live-through. TransferFunc[1].insert({RspLoc, RspDefInBlk1}); initValueArray(InLocsPtr, 5, 2); initValueArray(OutLocsPtr, 5, 2); buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc); EXPECT_EQ(InLocs[0][0], LiveInRsp); EXPECT_EQ(InLocs[1][0], RspPHIInBlk1); EXPECT_EQ(InLocs[2][0], RspDefInBlk1); EXPECT_EQ(InLocs[3][0], RspDefInBlk1); EXPECT_EQ(InLocs[4][0], RspDefInBlk1); EXPECT_EQ(OutLocs[0][0], LiveInRsp); EXPECT_EQ(OutLocs[1][0], RspDefInBlk1); EXPECT_EQ(OutLocs[2][0], RspDefInBlk1); EXPECT_EQ(OutLocs[3][0], RspDefInBlk1); EXPECT_EQ(OutLocs[4][0], RspDefInBlk1); TransferFunc[1].clear(); // As with earlier tricks: copy $rsp to $rax in the entry block, then $rax // to $rsp in block 3. The only def of $rsp is simply copying the same value // back into itself, and the value of $rsp is LiveInRsp all the way through. // PHIs should be created, then value-propagated away... however this // doesn't work in practice. // Consider the entry to loop3: we can determine that there's an incoming // PHI value from loop2, and LiveInRsp from the self-loop. This would still // justify having a PHI on entry to loop3. The only way to completely // value-propagate these PHIs away would be to speculatively explore what // PHIs could be eliminated and what that would lead to; which is // combinatorially complex. // Happily: // a) In this scenario, we always have a tracked location for LiveInRsp // anyway, so there's no loss in availability, // b) Only DBG_PHIs of a register would be vunlerable to this scenario, and // even then only if a true PHI became a DBG_PHI and was then optimised // through branch folding to no longer be at a CFG join, // c) The register allocator can spot this kind of redundant COPY easily, // and eliminate it. // // This unit test left in as a reference for the limitations of this // approach. PHIs will be left in $rsp on entry to each block. TransferFunc[0].insert({RaxLoc, LiveInRsp}); TransferFunc[3].insert({RspLoc, RaxPHIInBlk3}); initValueArray(InLocsPtr, 5, 2); initValueArray(OutLocsPtr, 5, 2); buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc); EXPECT_EQ(InLocs[0][0], LiveInRsp); EXPECT_EQ(InLocs[1][0], RspPHIInBlk1); EXPECT_EQ(InLocs[2][0], RspPHIInBlk2); EXPECT_EQ(InLocs[3][0], RspPHIInBlk3); EXPECT_EQ(InLocs[4][0], LiveInRsp); EXPECT_EQ(OutLocs[0][0], LiveInRsp); EXPECT_EQ(OutLocs[1][0], RspPHIInBlk1); EXPECT_EQ(OutLocs[2][0], RspPHIInBlk2); EXPECT_EQ(OutLocs[3][0], LiveInRsp); EXPECT_EQ(OutLocs[4][0], LiveInRsp); // Check $rax's value. It should have $rsps value from the entry block // onwards. EXPECT_EQ(InLocs[0][1], LiveInRax); EXPECT_EQ(InLocs[1][1], LiveInRsp); EXPECT_EQ(InLocs[2][1], LiveInRsp); EXPECT_EQ(InLocs[3][1], LiveInRsp); EXPECT_EQ(InLocs[4][1], LiveInRsp); EXPECT_EQ(OutLocs[0][1], LiveInRsp); EXPECT_EQ(OutLocs[1][1], LiveInRsp); EXPECT_EQ(OutLocs[2][1], LiveInRsp); EXPECT_EQ(OutLocs[3][1], LiveInRsp); EXPECT_EQ(OutLocs[4][1], LiveInRsp); } TEST_F(InstrRefLDVTest, pickVPHILocDiamond) { // entry // / \ // br1 br2 // \ / // ret setupDiamondBlocks(); ASSERT_TRUE(MTracker->getNumLocs() == 1); LocIdx RspLoc(0); Register RAX = getRegByName("RAX"); LocIdx RaxLoc = MTracker->lookupOrTrackRegister(RAX); ValueIDNum OutLocs[4][2]; ValueIDNum *OutLocsPtr[4] = {OutLocs[0], OutLocs[1], OutLocs[2], OutLocs[3]}; initValueArray(OutLocsPtr, 4, 2); unsigned EntryBlk = 0, Br2Blk = 2, RetBlk = 3; ValueIDNum LiveInRsp(EntryBlk, 0, RspLoc); ValueIDNum LiveInRax(EntryBlk, 0, RaxLoc); ValueIDNum RspPHIInBlk2(Br2Blk, 0, RspLoc); ValueIDNum RspPHIInBlk3(RetBlk, 0, RspLoc); DebugVariable Var(FuncVariable, None, nullptr); DbgValueProperties EmptyProps(EmptyExpr, false); SmallVector<DbgValue, 32> VLiveOuts; VLiveOuts.resize(4, DbgValue(EmptyProps, DbgValue::Undef)); InstrRefBasedLDV::LiveIdxT VLiveOutIdx; VLiveOutIdx[MBB0] = &VLiveOuts[0]; VLiveOutIdx[MBB1] = &VLiveOuts[1]; VLiveOutIdx[MBB2] = &VLiveOuts[2]; VLiveOutIdx[MBB3] = &VLiveOuts[3]; SmallVector<const MachineBasicBlock *, 2> Preds; for (const auto *Pred : MBB3->predecessors()) Preds.push_back(Pred); // Specify the live-outs around the joining block. OutLocs[1][0] = LiveInRsp; OutLocs[2][0] = LiveInRax; Optional<ValueIDNum> Result; // Simple case: join two distinct values on entry to the block. VLiveOuts[1] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def); VLiveOuts[2] = DbgValue(LiveInRax, EmptyProps, DbgValue::Def); Result = pickVPHILoc(*MBB3, Var, VLiveOutIdx, OutLocsPtr, Preds); // Should have picked a PHI in $rsp in block 3. EXPECT_TRUE(Result); if (Result) { EXPECT_EQ(*Result, RspPHIInBlk3); } // If the incoming values are swapped between blocks, we should not // successfully join. The CFG merge would select the right values, but in // the wrong conditions. std::swap(VLiveOuts[1], VLiveOuts[2]); Result = pickVPHILoc(*MBB3, Var, VLiveOutIdx, OutLocsPtr, Preds); EXPECT_FALSE(Result); // Swap back, std::swap(VLiveOuts[1], VLiveOuts[2]); // Setting one of these to being a constant should prohibit merging. VLiveOuts[1].Kind = DbgValue::Const; VLiveOuts[1].MO = MachineOperand::CreateImm(0); Result = pickVPHILoc(*MBB3, Var, VLiveOutIdx, OutLocsPtr, Preds); EXPECT_FALSE(Result); // Seeing both to being a constant -> still prohibit, it shouldn't become // a value in the register file anywhere. VLiveOuts[2] = VLiveOuts[1]; Result = pickVPHILoc(*MBB3, Var, VLiveOutIdx, OutLocsPtr, Preds); EXPECT_FALSE(Result); // NoVals shouldn't join with anything else. VLiveOuts[1] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def); VLiveOuts[2] = DbgValue(2, EmptyProps, DbgValue::NoVal); Result = pickVPHILoc(*MBB3, Var, VLiveOutIdx, OutLocsPtr, Preds); EXPECT_FALSE(Result); // We might merge in another VPHI in such a join. Present pickVPHILoc with // such a scenario: first, where one incoming edge has a VPHI with no known // value. This represents an edge where there was a PHI value that can't be // found in the register file -- we can't subsequently find a PHI here. VLiveOuts[1] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def); VLiveOuts[2] = DbgValue(2, EmptyProps, DbgValue::VPHI); EXPECT_EQ(VLiveOuts[2].ID, ValueIDNum::EmptyValue); Result = pickVPHILoc(*MBB3, Var, VLiveOutIdx, OutLocsPtr, Preds); EXPECT_FALSE(Result); // However, if we know the value of the incoming VPHI, we can search for its // location. Use a PHI machine-value for doing this, as VPHIs should always // have PHI values, or they should have been eliminated. OutLocs[2][0] = RspPHIInBlk2; VLiveOuts[1] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def); VLiveOuts[2] = DbgValue(2, EmptyProps, DbgValue::VPHI); VLiveOuts[2].ID = RspPHIInBlk2; // Set location where PHI happens. Result = pickVPHILoc(*MBB3, Var, VLiveOutIdx, OutLocsPtr, Preds); EXPECT_TRUE(Result); if (Result) { EXPECT_EQ(*Result, RspPHIInBlk3); } // If that value isn't available from that block, don't join. OutLocs[2][0] = LiveInRsp; Result = pickVPHILoc(*MBB3, Var, VLiveOutIdx, OutLocsPtr, Preds); EXPECT_FALSE(Result); // Check that we don't pick values when the properties disagree, for example // different indirectness or DIExpression. DIExpression *NewExpr = DIExpression::prepend(EmptyExpr, DIExpression::ApplyOffset, 4); DbgValueProperties PropsWithExpr(NewExpr, false); VLiveOuts[1] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def); VLiveOuts[2] = DbgValue(LiveInRsp, PropsWithExpr, DbgValue::Def); Result = pickVPHILoc(*MBB3, Var, VLiveOutIdx, OutLocsPtr, Preds); EXPECT_FALSE(Result); DbgValueProperties PropsWithIndirect(EmptyExpr, true); VLiveOuts[1] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def); VLiveOuts[2] = DbgValue(LiveInRsp, PropsWithIndirect, DbgValue::Def); Result = pickVPHILoc(*MBB3, Var, VLiveOutIdx, OutLocsPtr, Preds); EXPECT_FALSE(Result); } TEST_F(InstrRefLDVTest, pickVPHILocLoops) { setupSimpleLoop(); // entry // | // |/-----\ // loopblk | // |\-----/ // | // ret ASSERT_TRUE(MTracker->getNumLocs() == 1); LocIdx RspLoc(0); Register RAX = getRegByName("RAX"); LocIdx RaxLoc = MTracker->lookupOrTrackRegister(RAX); ValueIDNum OutLocs[3][2]; ValueIDNum *OutLocsPtr[4] = {OutLocs[0], OutLocs[1], OutLocs[2]}; initValueArray(OutLocsPtr, 3, 2); unsigned EntryBlk = 0, LoopBlk = 1; ValueIDNum LiveInRsp(EntryBlk, 0, RspLoc); ValueIDNum LiveInRax(EntryBlk, 0, RaxLoc); ValueIDNum RspPHIInBlk1(LoopBlk, 0, RspLoc); ValueIDNum RaxPHIInBlk1(LoopBlk, 0, RaxLoc); DebugVariable Var(FuncVariable, None, nullptr); DbgValueProperties EmptyProps(EmptyExpr, false); SmallVector<DbgValue, 32> VLiveOuts; VLiveOuts.resize(3, DbgValue(EmptyProps, DbgValue::Undef)); InstrRefBasedLDV::LiveIdxT VLiveOutIdx; VLiveOutIdx[MBB0] = &VLiveOuts[0]; VLiveOutIdx[MBB1] = &VLiveOuts[1]; VLiveOutIdx[MBB2] = &VLiveOuts[2]; SmallVector<const MachineBasicBlock *, 2> Preds; for (const auto *Pred : MBB1->predecessors()) Preds.push_back(Pred); // Specify the live-outs around the joining block. OutLocs[0][0] = LiveInRsp; OutLocs[1][0] = LiveInRax; Optional<ValueIDNum> Result; // See that we can merge as normal on a backedge. VLiveOuts[0] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def); VLiveOuts[1] = DbgValue(LiveInRax, EmptyProps, DbgValue::Def); Result = pickVPHILoc(*MBB1, Var, VLiveOutIdx, OutLocsPtr, Preds); // Should have picked a PHI in $rsp in block 1. EXPECT_TRUE(Result); if (Result) { EXPECT_EQ(*Result, RspPHIInBlk1); } // And that, if the desired values aren't available, we don't merge. OutLocs[1][0] = LiveInRsp; Result = pickVPHILoc(*MBB1, Var, VLiveOutIdx, OutLocsPtr, Preds); EXPECT_FALSE(Result); // Test the backedge behaviour: PHIs that feed back into themselves can // carry this variables value. Feed in LiveInRsp in both $rsp and $rax // from the entry block, but only put an appropriate backedge PHI in $rax. // Only the $rax location can form the correct PHI. OutLocs[0][0] = LiveInRsp; OutLocs[0][1] = LiveInRsp; OutLocs[1][0] = RaxPHIInBlk1; OutLocs[1][1] = RaxPHIInBlk1; VLiveOuts[0] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def); // Crucially, a VPHI originating in this block: VLiveOuts[1] = DbgValue(1, EmptyProps, DbgValue::VPHI); Result = pickVPHILoc(*MBB1, Var, VLiveOutIdx, OutLocsPtr, Preds); EXPECT_TRUE(Result); if (Result) { EXPECT_EQ(*Result, RaxPHIInBlk1); } // Merging should not be permitted if there's a usable PHI on the backedge, // but it's in the wrong place. (Overwrite $rax). OutLocs[1][1] = LiveInRax; Result = pickVPHILoc(*MBB1, Var, VLiveOutIdx, OutLocsPtr, Preds); EXPECT_FALSE(Result); // Additionally, if the VPHI coming back on the loop backedge isn't from // this block (block 1), we can't merge it. OutLocs[1][1] = RaxPHIInBlk1; VLiveOuts[0] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def); VLiveOuts[1] = DbgValue(0, EmptyProps, DbgValue::VPHI); Result = pickVPHILoc(*MBB1, Var, VLiveOutIdx, OutLocsPtr, Preds); EXPECT_FALSE(Result); } TEST_F(InstrRefLDVTest, pickVPHILocBadlyNestedLoops) { // Run some tests similar to pickVPHILocLoops, with more than one backedge, // and check that we merge correctly over many candidate locations. setupBadlyNestedLoops(); // entry // | // loop1 -o // | ^ // | ^ // loop2 -o // | ^ // | ^ // loop3 -o // | // ret ASSERT_TRUE(MTracker->getNumLocs() == 1); LocIdx RspLoc(0); Register RAX = getRegByName("RAX"); LocIdx RaxLoc = MTracker->lookupOrTrackRegister(RAX); Register RBX = getRegByName("RBX"); LocIdx RbxLoc = MTracker->lookupOrTrackRegister(RBX); ValueIDNum OutLocs[5][3]; ValueIDNum *OutLocsPtr[5] = {OutLocs[0], OutLocs[1], OutLocs[2], OutLocs[3], OutLocs[4]}; initValueArray(OutLocsPtr, 5, 3); unsigned EntryBlk = 0, Loop1Blk = 1; ValueIDNum LiveInRsp(EntryBlk, 0, RspLoc); ValueIDNum LiveInRax(EntryBlk, 0, RaxLoc); ValueIDNum LiveInRbx(EntryBlk, 0, RbxLoc); ValueIDNum RspPHIInBlk1(Loop1Blk, 0, RspLoc); ValueIDNum RaxPHIInBlk1(Loop1Blk, 0, RaxLoc); ValueIDNum RbxPHIInBlk1(Loop1Blk, 0, RbxLoc); DebugVariable Var(FuncVariable, None, nullptr); DbgValueProperties EmptyProps(EmptyExpr, false); SmallVector<DbgValue, 32> VLiveOuts; VLiveOuts.resize(5, DbgValue(EmptyProps, DbgValue::Undef)); InstrRefBasedLDV::LiveIdxT VLiveOutIdx; VLiveOutIdx[MBB0] = &VLiveOuts[0]; VLiveOutIdx[MBB1] = &VLiveOuts[1]; VLiveOutIdx[MBB2] = &VLiveOuts[2]; VLiveOutIdx[MBB3] = &VLiveOuts[3]; VLiveOutIdx[MBB4] = &VLiveOuts[4]; // We're going to focus on block 1. SmallVector<const MachineBasicBlock *, 2> Preds; for (const auto *Pred : MBB1->predecessors()) Preds.push_back(Pred); // Specify the live-outs around the joining block. Incoming edges from the // entry block, self, and loop2. OutLocs[0][0] = LiveInRsp; OutLocs[1][0] = LiveInRax; OutLocs[2][0] = LiveInRbx; Optional<ValueIDNum> Result; // See that we can merge as normal on a backedge. VLiveOuts[0] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def); VLiveOuts[1] = DbgValue(LiveInRax, EmptyProps, DbgValue::Def); VLiveOuts[2] = DbgValue(LiveInRbx, EmptyProps, DbgValue::Def); Result = pickVPHILoc(*MBB1, Var, VLiveOutIdx, OutLocsPtr, Preds); // Should have picked a PHI in $rsp in block 1. EXPECT_TRUE(Result); if (Result) { EXPECT_EQ(*Result, RspPHIInBlk1); } // Check too that permuting the live-out locations prevents merging OutLocs[0][0] = LiveInRax; OutLocs[1][0] = LiveInRbx; OutLocs[2][0] = LiveInRsp; Result = pickVPHILoc(*MBB1, Var, VLiveOutIdx, OutLocsPtr, Preds); EXPECT_FALSE(Result); OutLocs[0][0] = LiveInRsp; OutLocs[1][0] = LiveInRax; OutLocs[2][0] = LiveInRbx; // Feeding a PHI back on one backedge shouldn't merge (block 1 self backedge // wants LiveInRax). OutLocs[1][0] = RspPHIInBlk1; Result = pickVPHILoc(*MBB1, Var, VLiveOutIdx, OutLocsPtr, Preds); EXPECT_FALSE(Result); // If the variables value on that edge is a VPHI feeding into itself, that's // fine. VLiveOuts[0] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def); VLiveOuts[1] = DbgValue(1, EmptyProps, DbgValue::VPHI); VLiveOuts[2] = DbgValue(LiveInRbx, EmptyProps, DbgValue::Def); Result = pickVPHILoc(*MBB1, Var, VLiveOutIdx, OutLocsPtr, Preds); EXPECT_TRUE(Result); if (Result) { EXPECT_EQ(*Result, RspPHIInBlk1); } // Likewise: the other backedge being a VPHI from block 1 should be accepted. OutLocs[2][0] = RspPHIInBlk1; VLiveOuts[0] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def); VLiveOuts[1] = DbgValue(1, EmptyProps, DbgValue::VPHI); VLiveOuts[2] = DbgValue(1, EmptyProps, DbgValue::VPHI); Result = pickVPHILoc(*MBB1, Var, VLiveOutIdx, OutLocsPtr, Preds); EXPECT_TRUE(Result); if (Result) { EXPECT_EQ(*Result, RspPHIInBlk1); } // Here's where it becomes tricky: we should not merge if there are two // _distinct_ backedge PHIs. We can't have a PHI that happens in both rsp // and rax for example. We can only pick one location as the live-in. OutLocs[2][0] = RaxPHIInBlk1; Result = pickVPHILoc(*MBB1, Var, VLiveOutIdx, OutLocsPtr, Preds); EXPECT_FALSE(Result); // The above test sources correct machine-PHI-value from two places. Now // try with one machine-PHI-value, but placed in two different locations // on the backedge. Again, we can't merge a location here, there's no // location that works on all paths. OutLocs[0][0] = LiveInRsp; OutLocs[1][0] = RspPHIInBlk1; OutLocs[2][0] = LiveInRsp; OutLocs[2][1] = RspPHIInBlk1; Result = pickVPHILoc(*MBB1, Var, VLiveOutIdx, OutLocsPtr, Preds); EXPECT_FALSE(Result); // Scatter various PHI values across the available locations. Only rbx (loc 2) // has the right value in both backedges -- that's the loc that should be // picked. OutLocs[0][2] = LiveInRsp; OutLocs[1][0] = RspPHIInBlk1; OutLocs[1][1] = RaxPHIInBlk1; OutLocs[1][2] = RbxPHIInBlk1; OutLocs[2][0] = LiveInRsp; OutLocs[2][1] = RspPHIInBlk1; OutLocs[2][2] = RbxPHIInBlk1; Result = pickVPHILoc(*MBB1, Var, VLiveOutIdx, OutLocsPtr, Preds); EXPECT_TRUE(Result); if (Result) { EXPECT_EQ(*Result, RbxPHIInBlk1); } } TEST_F(InstrRefLDVTest, vlocJoinDiamond) { // entry // / \ // br1 br2 // \ / // ret setupDiamondBlocks(); ASSERT_TRUE(MTracker->getNumLocs() == 1); LocIdx RspLoc(0); Register RAX = getRegByName("RAX"); LocIdx RaxLoc = MTracker->lookupOrTrackRegister(RAX); unsigned EntryBlk = 0, Br2Blk = 2, RetBlk = 3; ValueIDNum LiveInRsp(EntryBlk, 0, RspLoc); ValueIDNum LiveInRax(EntryBlk, 0, RaxLoc); ValueIDNum RspPHIInBlkBr2Blk(Br2Blk, 0, RspLoc); ValueIDNum RspPHIInBlkRetBlk(RetBlk, 0, RspLoc); DebugVariable Var(FuncVariable, None, nullptr); DbgValueProperties EmptyProps(EmptyExpr, false); SmallVector<DbgValue, 32> VLiveOuts; VLiveOuts.resize(4, DbgValue(EmptyProps, DbgValue::Undef)); InstrRefBasedLDV::LiveIdxT VLiveOutIdx; VLiveOutIdx[MBB0] = &VLiveOuts[0]; VLiveOutIdx[MBB1] = &VLiveOuts[1]; VLiveOutIdx[MBB2] = &VLiveOuts[2]; VLiveOutIdx[MBB3] = &VLiveOuts[3]; SmallPtrSet<const MachineBasicBlock *, 8> AllBlocks; AllBlocks.insert(MBB0); AllBlocks.insert(MBB1); AllBlocks.insert(MBB2); AllBlocks.insert(MBB3); SmallVector<const MachineBasicBlock *, 2> Preds; for (const auto *Pred : MBB3->predecessors()) Preds.push_back(Pred); SmallSet<DebugVariable, 4> AllVars; AllVars.insert(Var); // vlocJoin is here to propagate incoming values, and eliminate PHIs. Start // off by propagating a value into the merging block, number 3. DbgValue JoinedLoc = DbgValue(3, EmptyProps, DbgValue::NoVal); VLiveOuts[1] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def); VLiveOuts[2] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def); bool Result = vlocJoin(*MBB3, VLiveOutIdx, AllBlocks, AllBlocks, JoinedLoc); EXPECT_TRUE(Result); // Output locs should have changed. EXPECT_EQ(JoinedLoc.Kind, DbgValue::Def); EXPECT_EQ(JoinedLoc.ID, LiveInRsp); // And if we did it a second time, leaving the live-ins as it was, then // we should report no change. Result = vlocJoin(*MBB3, VLiveOutIdx, AllBlocks, AllBlocks, JoinedLoc); EXPECT_FALSE(Result); // If the live-in variable values are different, but there's no PHI placed // in this block, then just pick a location. It should be the first (in RPO) // predecessor to avoid being a backedge. VLiveOuts[1] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def); VLiveOuts[2] = DbgValue(LiveInRax, EmptyProps, DbgValue::Def); JoinedLoc = DbgValue(3, EmptyProps, DbgValue::NoVal); Result = vlocJoin(*MBB3, VLiveOutIdx, AllBlocks, AllBlocks, JoinedLoc); EXPECT_TRUE(Result); EXPECT_EQ(JoinedLoc.Kind, DbgValue::Def); // RPO is blocks 0 2 1 3, so LiveInRax is picked as the first predecessor // of this join. EXPECT_EQ(JoinedLoc.ID, LiveInRax); // No tests for whether vlocJoin will pass-through a variable with differing // expressions / properties. Those can only come about due to assignments; and // for any assignment at all, a PHI should have been placed at the dominance // frontier. We rely on the IDF calculator being accurate (which is OK, // because so does the rest of LLVM). // Try placing a PHI. With differing input values (LiveInRsp, LiveInRax), // this PHI should not be eliminated. JoinedLoc = DbgValue(3, EmptyProps, DbgValue::VPHI); Result = vlocJoin(*MBB3, VLiveOutIdx, AllBlocks, AllBlocks, JoinedLoc); // Expect no change. EXPECT_FALSE(Result); EXPECT_EQ(JoinedLoc.Kind, DbgValue::VPHI); // This should not have been assigned a fixed value. EXPECT_EQ(JoinedLoc.ID, ValueIDNum::EmptyValue); EXPECT_EQ(JoinedLoc.BlockNo, 3); // Try a simple PHI elimination. Put a PHI in block 3, but LiveInRsp on both // incoming edges. Re-load in and out-locs with unrelated values; they're // irrelevant. VLiveOuts[1] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def); VLiveOuts[2] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def); JoinedLoc = DbgValue(3, EmptyProps, DbgValue::VPHI); Result = vlocJoin(*MBB3, VLiveOutIdx, AllBlocks, AllBlocks, JoinedLoc); EXPECT_TRUE(Result); EXPECT_EQ(JoinedLoc.Kind, DbgValue::Def); EXPECT_EQ(JoinedLoc.ID, LiveInRsp); // If the "current" live-in is a VPHI, but not a VPHI generated in the current // block, then it's the remains of an earlier value propagation. We should // value propagate through this merge. Even if the current incoming values // disagree, because we've previously determined any VPHI here is redundant. VLiveOuts[1] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def); VLiveOuts[2] = DbgValue(LiveInRax, EmptyProps, DbgValue::Def); JoinedLoc = DbgValue(2, EmptyProps, DbgValue::VPHI); Result = vlocJoin(*MBB3, VLiveOutIdx, AllBlocks, AllBlocks, JoinedLoc); EXPECT_TRUE(Result); EXPECT_EQ(JoinedLoc.Kind, DbgValue::Def); EXPECT_EQ(JoinedLoc.ID, LiveInRax); // from block 2 // The above test, but test that we will install one value-propagated VPHI // over another. VLiveOuts[1] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def); VLiveOuts[2] = DbgValue(0, EmptyProps, DbgValue::VPHI); JoinedLoc = DbgValue(2, EmptyProps, DbgValue::VPHI); Result = vlocJoin(*MBB3, VLiveOutIdx, AllBlocks, AllBlocks, JoinedLoc); EXPECT_TRUE(Result); EXPECT_EQ(JoinedLoc.Kind, DbgValue::VPHI); EXPECT_EQ(JoinedLoc.BlockNo, 0); // We shouldn't eliminate PHIs when properties disagree. DbgValueProperties PropsWithIndirect(EmptyExpr, true); VLiveOuts[1] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def); VLiveOuts[2] = DbgValue(LiveInRsp, PropsWithIndirect, DbgValue::Def); JoinedLoc = DbgValue(3, EmptyProps, DbgValue::VPHI); Result = vlocJoin(*MBB3, VLiveOutIdx, AllBlocks, AllBlocks, JoinedLoc); EXPECT_FALSE(Result); EXPECT_EQ(JoinedLoc.Kind, DbgValue::VPHI); EXPECT_EQ(JoinedLoc.BlockNo, 3); // Even if properties disagree, we should still value-propagate if there's no // PHI to be eliminated. The disagreeing values should work themselves out, // seeing how we've determined no PHI is necessary. VLiveOuts[1] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def); VLiveOuts[2] = DbgValue(LiveInRsp, PropsWithIndirect, DbgValue::Def); JoinedLoc = DbgValue(2, EmptyProps, DbgValue::VPHI); Result = vlocJoin(*MBB3, VLiveOutIdx, AllBlocks, AllBlocks, JoinedLoc); EXPECT_TRUE(Result); EXPECT_EQ(JoinedLoc.Kind, DbgValue::Def); EXPECT_EQ(JoinedLoc.ID, LiveInRsp); // Also check properties come from block 2, the first RPO predecessor to block // three. EXPECT_EQ(JoinedLoc.Properties, PropsWithIndirect); // Again, disagreeing properties, this time the expr, should cause a PHI to // not be eliminated. DIExpression *NewExpr = DIExpression::prepend(EmptyExpr, DIExpression::ApplyOffset, 4); DbgValueProperties PropsWithExpr(NewExpr, false); VLiveOuts[1] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def); VLiveOuts[2] = DbgValue(LiveInRsp, PropsWithExpr, DbgValue::Def); JoinedLoc = DbgValue(3, EmptyProps, DbgValue::VPHI); Result = vlocJoin(*MBB3, VLiveOutIdx, AllBlocks, AllBlocks, JoinedLoc); EXPECT_FALSE(Result); } TEST_F(InstrRefLDVTest, vlocJoinLoops) { setupSimpleLoop(); // entry // | // |/-----\ // loopblk | // |\-----/ // | // ret ASSERT_TRUE(MTracker->getNumLocs() == 1); LocIdx RspLoc(0); Register RAX = getRegByName("RAX"); LocIdx RaxLoc = MTracker->lookupOrTrackRegister(RAX); unsigned EntryBlk = 0, LoopBlk = 1; ValueIDNum LiveInRsp(EntryBlk, 0, RspLoc); ValueIDNum LiveInRax(EntryBlk, 0, RaxLoc); ValueIDNum RspPHIInBlk1(LoopBlk, 0, RspLoc); DebugVariable Var(FuncVariable, None, nullptr); DbgValueProperties EmptyProps(EmptyExpr, false); SmallVector<DbgValue, 32> VLiveOuts; VLiveOuts.resize(3, DbgValue(EmptyProps, DbgValue::Undef)); InstrRefBasedLDV::LiveIdxT VLiveOutIdx; VLiveOutIdx[MBB0] = &VLiveOuts[0]; VLiveOutIdx[MBB1] = &VLiveOuts[1]; VLiveOutIdx[MBB2] = &VLiveOuts[2]; SmallPtrSet<const MachineBasicBlock *, 8> AllBlocks; AllBlocks.insert(MBB0); AllBlocks.insert(MBB1); AllBlocks.insert(MBB2); SmallVector<const MachineBasicBlock *, 2> Preds; for (const auto *Pred : MBB1->predecessors()) Preds.push_back(Pred); SmallSet<DebugVariable, 4> AllVars; AllVars.insert(Var); // Test some back-edge-specific behaviours of vloc join. Mostly: the fact that // VPHIs that arrive on backedges can be eliminated, despite having different // values to the predecessor. // First: when there's no VPHI placed already, propagate the live-in value of // the first RPO predecessor. VLiveOuts[0] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def); VLiveOuts[1] = DbgValue(LiveInRax, EmptyProps, DbgValue::Def); DbgValue JoinedLoc = DbgValue(LiveInRax, EmptyProps, DbgValue::Def); bool Result = vlocJoin(*MBB1, VLiveOutIdx, AllBlocks, AllBlocks, JoinedLoc); EXPECT_TRUE(Result); EXPECT_EQ(JoinedLoc.Kind, DbgValue::Def); EXPECT_EQ(JoinedLoc.ID, LiveInRsp); // If there is a VPHI: don't elimiante it if there are disagreeing values. VLiveOuts[0] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def); VLiveOuts[1] = DbgValue(LiveInRax, EmptyProps, DbgValue::Def); JoinedLoc = DbgValue(1, EmptyProps, DbgValue::VPHI); Result = vlocJoin(*MBB1, VLiveOutIdx, AllBlocks, AllBlocks, JoinedLoc); EXPECT_FALSE(Result); EXPECT_EQ(JoinedLoc.Kind, DbgValue::VPHI); EXPECT_EQ(JoinedLoc.BlockNo, 1); // If we feed this VPHI back into itself though, we can eliminate it. VLiveOuts[0] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def); VLiveOuts[1] = DbgValue(1, EmptyProps, DbgValue::VPHI); JoinedLoc = DbgValue(1, EmptyProps, DbgValue::VPHI); Result = vlocJoin(*MBB1, VLiveOutIdx, AllBlocks, AllBlocks, JoinedLoc); EXPECT_TRUE(Result); EXPECT_EQ(JoinedLoc.Kind, DbgValue::Def); EXPECT_EQ(JoinedLoc.ID, LiveInRsp); // Don't eliminate backedge VPHIs if the predecessors have different // properties. DIExpression *NewExpr = DIExpression::prepend(EmptyExpr, DIExpression::ApplyOffset, 4); DbgValueProperties PropsWithExpr(NewExpr, false); VLiveOuts[0] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def); VLiveOuts[1] = DbgValue(1, PropsWithExpr, DbgValue::VPHI); JoinedLoc = DbgValue(1, EmptyProps, DbgValue::VPHI); Result = vlocJoin(*MBB1, VLiveOutIdx, AllBlocks, AllBlocks, JoinedLoc); EXPECT_FALSE(Result); EXPECT_EQ(JoinedLoc.Kind, DbgValue::VPHI); EXPECT_EQ(JoinedLoc.BlockNo, 1); // Backedges with VPHIs, but from the wrong block, shouldn't be eliminated. VLiveOuts[0] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def); VLiveOuts[1] = DbgValue(0, EmptyProps, DbgValue::VPHI); JoinedLoc = DbgValue(1, EmptyProps, DbgValue::VPHI); Result = vlocJoin(*MBB1, VLiveOutIdx, AllBlocks, AllBlocks, JoinedLoc); EXPECT_FALSE(Result); EXPECT_EQ(JoinedLoc.Kind, DbgValue::VPHI); EXPECT_EQ(JoinedLoc.BlockNo, 1); } TEST_F(InstrRefLDVTest, vlocJoinBadlyNestedLoops) { // Test PHI elimination in the presence of multiple backedges. setupBadlyNestedLoops(); // entry // | // loop1 -o // | ^ // | ^ // loop2 -o // | ^ // | ^ // loop3 -o // | // ret ASSERT_TRUE(MTracker->getNumLocs() == 1); LocIdx RspLoc(0); Register RAX = getRegByName("RAX"); LocIdx RaxLoc = MTracker->lookupOrTrackRegister(RAX); Register RBX = getRegByName("RBX"); LocIdx RbxLoc = MTracker->lookupOrTrackRegister(RBX); unsigned EntryBlk = 0; ValueIDNum LiveInRsp(EntryBlk, 0, RspLoc); ValueIDNum LiveInRax(EntryBlk, 0, RaxLoc); ValueIDNum LiveInRbx(EntryBlk, 0, RbxLoc); DebugVariable Var(FuncVariable, None, nullptr); DbgValueProperties EmptyProps(EmptyExpr, false); SmallVector<DbgValue, 32> VLiveOuts; VLiveOuts.resize(5, DbgValue(EmptyProps, DbgValue::Undef)); InstrRefBasedLDV::LiveIdxT VLiveOutIdx; VLiveOutIdx[MBB0] = &VLiveOuts[0]; VLiveOutIdx[MBB1] = &VLiveOuts[1]; VLiveOutIdx[MBB2] = &VLiveOuts[2]; VLiveOutIdx[MBB3] = &VLiveOuts[3]; VLiveOutIdx[MBB4] = &VLiveOuts[4]; SmallPtrSet<const MachineBasicBlock *, 8> AllBlocks; AllBlocks.insert(MBB0); AllBlocks.insert(MBB1); AllBlocks.insert(MBB2); AllBlocks.insert(MBB3); AllBlocks.insert(MBB4); // We're going to focus on block 1. SmallVector<const MachineBasicBlock *, 3> Preds; for (const auto *Pred : MBB1->predecessors()) Preds.push_back(Pred); SmallSet<DebugVariable, 4> AllVars; AllVars.insert(Var); // Test a normal VPHI isn't eliminated. VLiveOuts[0] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def); VLiveOuts[1] = DbgValue(LiveInRax, EmptyProps, DbgValue::Def); VLiveOuts[2] = DbgValue(LiveInRbx, EmptyProps, DbgValue::Def); DbgValue JoinedLoc = DbgValue(1, EmptyProps, DbgValue::VPHI); bool Result = vlocJoin(*MBB1, VLiveOutIdx, AllBlocks, AllBlocks, JoinedLoc); EXPECT_FALSE(Result); EXPECT_EQ(JoinedLoc.Kind, DbgValue::VPHI); EXPECT_EQ(JoinedLoc.BlockNo, 1); // Common VPHIs on backedges should merge. VLiveOuts[0] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def); VLiveOuts[1] = DbgValue(1, EmptyProps, DbgValue::VPHI); VLiveOuts[2] = DbgValue(1, EmptyProps, DbgValue::VPHI); JoinedLoc = DbgValue(1, EmptyProps, DbgValue::VPHI); Result = vlocJoin(*MBB1, VLiveOutIdx, AllBlocks, AllBlocks, JoinedLoc); EXPECT_TRUE(Result); EXPECT_EQ(JoinedLoc.Kind, DbgValue::Def); EXPECT_EQ(JoinedLoc.ID, LiveInRsp); // They shouldn't merge if one of their properties is different. DbgValueProperties PropsWithIndirect(EmptyExpr, true); VLiveOuts[0] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def); VLiveOuts[1] = DbgValue(1, EmptyProps, DbgValue::VPHI); VLiveOuts[2] = DbgValue(1, PropsWithIndirect, DbgValue::VPHI); JoinedLoc = DbgValue(1, EmptyProps, DbgValue::VPHI); Result = vlocJoin(*MBB1, VLiveOutIdx, AllBlocks, AllBlocks, JoinedLoc); EXPECT_FALSE(Result); EXPECT_EQ(JoinedLoc.Kind, DbgValue::VPHI); EXPECT_EQ(JoinedLoc.BlockNo, 1); // VPHIs from different blocks should not merge. VLiveOuts[0] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def); VLiveOuts[1] = DbgValue(1, EmptyProps, DbgValue::VPHI); VLiveOuts[2] = DbgValue(2, EmptyProps, DbgValue::VPHI); JoinedLoc = DbgValue(1, EmptyProps, DbgValue::VPHI); Result = vlocJoin(*MBB1, VLiveOutIdx, AllBlocks, AllBlocks, JoinedLoc); EXPECT_FALSE(Result); EXPECT_EQ(JoinedLoc.Kind, DbgValue::VPHI); EXPECT_EQ(JoinedLoc.BlockNo, 1); } // Above are tests for picking VPHI locations, and eliminating VPHIs. No // unit-tests are written for evaluating the transfer function as that's // pretty straight forwards, or applying VPHI-location-picking to live-ins. // Instead, pre-set some machine locations and apply buildVLocValueMap to the // existing CFG patterns. TEST_F(InstrRefLDVTest, VLocSingleBlock) { setupSingleBlock(); ASSERT_TRUE(MTracker->getNumLocs() == 1); LocIdx RspLoc(0); ValueIDNum InLocs[2], OutLocs[2]; ValueIDNum *InLocsPtr[1] = {&InLocs[0]}; ValueIDNum *OutLocsPtr[1] = {&OutLocs[0]}; ValueIDNum LiveInRsp = ValueIDNum(0, 0, RspLoc); InLocs[0] = OutLocs[0] = LiveInRsp; DebugVariable Var(FuncVariable, None, nullptr); DbgValueProperties EmptyProps(EmptyExpr, false); SmallSet<DebugVariable, 4> AllVars; AllVars.insert(Var); // Mild hack: rather than constructing machine instructions in each block // and creating lexical scopes across them, instead just tell // buildVLocValueMap that there's an assignment in every block. That makes // every block in scope. SmallPtrSet<MachineBasicBlock *, 4> AssignBlocks; AssignBlocks.insert(MBB0); SmallVector<VLocTracker, 1> VLocs; VLocs.resize(1); InstrRefBasedLDV::LiveInsT Output; // Test that, with no assignments at all, no mappings are created for the // variable in this function. buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output, OutLocsPtr, InLocsPtr, VLocs); EXPECT_EQ(Output.size(), 0ul); // If we put an assignment in the transfer function, that should... well, // do nothing, because we don't store the live-outs. VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)}); buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output, OutLocsPtr, InLocsPtr, VLocs); EXPECT_EQ(Output.size(), 0ul); // There is pretty much nothing else of interest to test with a single block. // It's not relevant to the SSA-construction parts of variable values. } TEST_F(InstrRefLDVTest, VLocDiamondBlocks) { setupDiamondBlocks(); // entry // / \ // br1 br2 // \ / // ret ASSERT_TRUE(MTracker->getNumLocs() == 1); LocIdx RspLoc(0); Register RAX = getRegByName("RAX"); LocIdx RaxLoc = MTracker->lookupOrTrackRegister(RAX); unsigned EntryBlk = 0, RetBlk = 3; ValueIDNum LiveInRsp = ValueIDNum(EntryBlk, 0, RspLoc); ValueIDNum LiveInRax = ValueIDNum(EntryBlk, 0, RaxLoc); ValueIDNum RspPHIInBlk3 = ValueIDNum(RetBlk, 0, RspLoc); ValueIDNum InLocs[4][2], OutLocs[4][2]; ValueIDNum *InLocsPtr[4] = {InLocs[0], InLocs[1], InLocs[2], InLocs[3]}; ValueIDNum *OutLocsPtr[4] = {OutLocs[0], OutLocs[1], OutLocs[2], OutLocs[3]}; initValueArray(InLocsPtr, 4, 2); initValueArray(OutLocsPtr, 4, 2); DebugVariable Var(FuncVariable, None, nullptr); DbgValueProperties EmptyProps(EmptyExpr, false); SmallSet<DebugVariable, 4> AllVars; AllVars.insert(Var); // Mild hack: rather than constructing machine instructions in each block // and creating lexical scopes across them, instead just tell // buildVLocValueMap that there's an assignment in every block. That makes // every block in scope. SmallPtrSet<MachineBasicBlock *, 4> AssignBlocks; AssignBlocks.insert(MBB0); AssignBlocks.insert(MBB1); AssignBlocks.insert(MBB2); AssignBlocks.insert(MBB3); SmallVector<VLocTracker, 1> VLocs; VLocs.resize(4); InstrRefBasedLDV::LiveInsT Output; // Start off with LiveInRsp in every location. for (unsigned int I = 0; I < 4; ++I) { InLocs[I][0] = InLocs[I][1] = LiveInRsp; OutLocs[I][0] = OutLocs[I][1] = LiveInRsp; } auto ClearOutputs = [&]() { for (auto &Elem : Output) Elem.clear(); }; Output.resize(4); // No assignments -> no values. buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output, OutLocsPtr, InLocsPtr, VLocs); EXPECT_EQ(Output[0].size(), 0ul); EXPECT_EQ(Output[1].size(), 0ul); EXPECT_EQ(Output[2].size(), 0ul); EXPECT_EQ(Output[3].size(), 0ul); // An assignment in the end block should also not affect other blocks; or // produce any live-ins. VLocs[3].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)}); buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output, OutLocsPtr, InLocsPtr, VLocs); EXPECT_EQ(Output[0].size(), 0ul); EXPECT_EQ(Output[1].size(), 0ul); EXPECT_EQ(Output[2].size(), 0ul); EXPECT_EQ(Output[3].size(), 0ul); ClearOutputs(); // Assignments in either of the side-of-diamond blocks should also not be // propagated anywhere. VLocs[3].Vars.clear(); VLocs[2].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)}); buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output, OutLocsPtr, InLocsPtr, VLocs); EXPECT_EQ(Output[0].size(), 0ul); EXPECT_EQ(Output[1].size(), 0ul); EXPECT_EQ(Output[2].size(), 0ul); EXPECT_EQ(Output[3].size(), 0ul); VLocs[2].Vars.clear(); ClearOutputs(); VLocs[1].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)}); buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output, OutLocsPtr, InLocsPtr, VLocs); EXPECT_EQ(Output[0].size(), 0ul); EXPECT_EQ(Output[1].size(), 0ul); EXPECT_EQ(Output[2].size(), 0ul); EXPECT_EQ(Output[3].size(), 0ul); VLocs[1].Vars.clear(); ClearOutputs(); // However: putting an assignment in the first block should propagate variable // values through to all other blocks, as it dominates. VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)}); buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output, OutLocsPtr, InLocsPtr, VLocs); EXPECT_EQ(Output[0].size(), 0ul); ASSERT_EQ(Output[1].size(), 1ul); ASSERT_EQ(Output[2].size(), 1ul); ASSERT_EQ(Output[3].size(), 1ul); EXPECT_EQ(Output[1][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[1][0].second.ID, LiveInRsp); EXPECT_EQ(Output[2][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[2][0].second.ID, LiveInRsp); EXPECT_EQ(Output[3][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[3][0].second.ID, LiveInRsp); ClearOutputs(); VLocs[0].Vars.clear(); // Additionally, even if that value isn't available in the register file, it // should still be propagated, as buildVLocValueMap shouldn't care about // what's in the registers (except for PHIs). // values through to all other blocks, as it dominates. VLocs[0].Vars.insert({Var, DbgValue(LiveInRax, EmptyProps, DbgValue::Def)}); buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output, OutLocsPtr, InLocsPtr, VLocs); EXPECT_EQ(Output[0].size(), 0ul); ASSERT_EQ(Output[1].size(), 1ul); ASSERT_EQ(Output[2].size(), 1ul); ASSERT_EQ(Output[3].size(), 1ul); EXPECT_EQ(Output[1][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[1][0].second.ID, LiveInRax); EXPECT_EQ(Output[2][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[2][0].second.ID, LiveInRax); EXPECT_EQ(Output[3][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[3][0].second.ID, LiveInRax); ClearOutputs(); VLocs[0].Vars.clear(); // We should get a live-in to the merging block, if there are two assigns of // the same value in either side of the diamond. VLocs[1].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)}); VLocs[2].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)}); buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output, OutLocsPtr, InLocsPtr, VLocs); EXPECT_EQ(Output[0].size(), 0ul); EXPECT_EQ(Output[1].size(), 0ul); EXPECT_EQ(Output[2].size(), 0ul); ASSERT_EQ(Output[3].size(), 1ul); EXPECT_EQ(Output[3][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[3][0].second.ID, LiveInRsp); ClearOutputs(); VLocs[1].Vars.clear(); VLocs[2].Vars.clear(); // If we assign a value in the entry block, then 'undef' on a branch, we // shouldn't have a live-in in the merge block. VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)}); VLocs[1].Vars.insert({Var, DbgValue(EmptyProps, DbgValue::Undef)}); buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output, OutLocsPtr, InLocsPtr, VLocs); EXPECT_EQ(Output[0].size(), 0ul); ASSERT_EQ(Output[1].size(), 1ul); ASSERT_EQ(Output[2].size(), 1ul); EXPECT_EQ(Output[3].size(), 0ul); EXPECT_EQ(Output[1][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[1][0].second.ID, LiveInRsp); EXPECT_EQ(Output[2][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[2][0].second.ID, LiveInRsp); ClearOutputs(); VLocs[0].Vars.clear(); VLocs[1].Vars.clear(); // Having different values joining into the merge block should mean we have // no live-in in that block. Block ones LiveInRax value doesn't appear as a // live-in anywhere, it's block internal. VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)}); VLocs[1].Vars.insert({Var, DbgValue(LiveInRax, EmptyProps, DbgValue::Def)}); buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output, OutLocsPtr, InLocsPtr, VLocs); EXPECT_EQ(Output[0].size(), 0ul); ASSERT_EQ(Output[1].size(), 1ul); ASSERT_EQ(Output[2].size(), 1ul); EXPECT_EQ(Output[3].size(), 0ul); EXPECT_EQ(Output[1][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[1][0].second.ID, LiveInRsp); EXPECT_EQ(Output[2][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[2][0].second.ID, LiveInRsp); ClearOutputs(); VLocs[0].Vars.clear(); VLocs[1].Vars.clear(); // But on the other hand, if there's a location in the register file where // those two values can be joined, do so. OutLocs[1][0] = LiveInRax; VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)}); VLocs[1].Vars.insert({Var, DbgValue(LiveInRax, EmptyProps, DbgValue::Def)}); buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output, OutLocsPtr, InLocsPtr, VLocs); EXPECT_EQ(Output[0].size(), 0ul); ASSERT_EQ(Output[1].size(), 1ul); ASSERT_EQ(Output[2].size(), 1ul); ASSERT_EQ(Output[3].size(), 1ul); EXPECT_EQ(Output[1][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[1][0].second.ID, LiveInRsp); EXPECT_EQ(Output[2][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[2][0].second.ID, LiveInRsp); EXPECT_EQ(Output[3][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[3][0].second.ID, RspPHIInBlk3); ClearOutputs(); VLocs[0].Vars.clear(); VLocs[1].Vars.clear(); } TEST_F(InstrRefLDVTest, VLocSimpleLoop) { setupSimpleLoop(); // entry // | // |/-----\ // loopblk | // |\-----/ // | // ret ASSERT_TRUE(MTracker->getNumLocs() == 1); LocIdx RspLoc(0); Register RAX = getRegByName("RAX"); LocIdx RaxLoc = MTracker->lookupOrTrackRegister(RAX); unsigned EntryBlk = 0, LoopBlk = 1; ValueIDNum LiveInRsp = ValueIDNum(EntryBlk, 0, RspLoc); ValueIDNum LiveInRax = ValueIDNum(EntryBlk, 0, RaxLoc); ValueIDNum RspPHIInBlk1 = ValueIDNum(LoopBlk, 0, RspLoc); ValueIDNum RspDefInBlk1 = ValueIDNum(LoopBlk, 1, RspLoc); ValueIDNum RaxPHIInBlk1 = ValueIDNum(LoopBlk, 0, RaxLoc); ValueIDNum InLocs[3][2], OutLocs[3][2]; ValueIDNum *InLocsPtr[3] = {InLocs[0], InLocs[1], InLocs[2]}; ValueIDNum *OutLocsPtr[3] = {OutLocs[0], OutLocs[1], OutLocs[2]}; initValueArray(InLocsPtr, 3, 2); initValueArray(OutLocsPtr, 3, 2); DebugVariable Var(FuncVariable, None, nullptr); DbgValueProperties EmptyProps(EmptyExpr, false); SmallSet<DebugVariable, 4> AllVars; AllVars.insert(Var); SmallPtrSet<MachineBasicBlock *, 4> AssignBlocks; AssignBlocks.insert(MBB0); AssignBlocks.insert(MBB1); AssignBlocks.insert(MBB2); SmallVector<VLocTracker, 3> VLocs; VLocs.resize(3); InstrRefBasedLDV::LiveInsT Output; // Start off with LiveInRsp in every location. for (unsigned int I = 0; I < 3; ++I) { InLocs[I][0] = InLocs[I][1] = LiveInRsp; OutLocs[I][0] = OutLocs[I][1] = LiveInRsp; } auto ClearOutputs = [&]() { for (auto &Elem : Output) Elem.clear(); }; Output.resize(3); // Easy starter: a dominating assign should propagate to all blocks. VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)}); buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output, OutLocsPtr, InLocsPtr, VLocs); EXPECT_EQ(Output[0].size(), 0ul); ASSERT_EQ(Output[1].size(), 1ul); ASSERT_EQ(Output[2].size(), 1ul); EXPECT_EQ(Output[1][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[1][0].second.ID, LiveInRsp); EXPECT_EQ(Output[2][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[2][0].second.ID, LiveInRsp); ClearOutputs(); VLocs[0].Vars.clear(); VLocs[1].Vars.clear(); // Put an undef assignment in the loop. Should get no live-in value. VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)}); VLocs[1].Vars.insert({Var, DbgValue(EmptyProps, DbgValue::Undef)}); buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output, OutLocsPtr, InLocsPtr, VLocs); EXPECT_EQ(Output[0].size(), 0ul); EXPECT_EQ(Output[1].size(), 0ul); EXPECT_EQ(Output[2].size(), 0ul); ClearOutputs(); VLocs[0].Vars.clear(); VLocs[1].Vars.clear(); // Assignment of the same value should naturally join. VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)}); VLocs[1].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)}); buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output, OutLocsPtr, InLocsPtr, VLocs); EXPECT_EQ(Output[0].size(), 0ul); ASSERT_EQ(Output[1].size(), 1ul); ASSERT_EQ(Output[2].size(), 1ul); EXPECT_EQ(Output[1][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[1][0].second.ID, LiveInRsp); EXPECT_EQ(Output[2][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[2][0].second.ID, LiveInRsp); ClearOutputs(); VLocs[0].Vars.clear(); VLocs[1].Vars.clear(); // Assignment of different values shouldn't join with no machine PHI vals. // Will be live-in to exit block as it's dominated. VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)}); VLocs[1].Vars.insert({Var, DbgValue(LiveInRax, EmptyProps, DbgValue::Def)}); buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output, OutLocsPtr, InLocsPtr, VLocs); EXPECT_EQ(Output[0].size(), 0ul); EXPECT_EQ(Output[1].size(), 0ul); ASSERT_EQ(Output[2].size(), 1ul); EXPECT_EQ(Output[2][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[2][0].second.ID, LiveInRax); ClearOutputs(); VLocs[0].Vars.clear(); VLocs[1].Vars.clear(); // Install a completely unrelated PHI value, that we should not join on. Try // with unrelated assign in loop block again. InLocs[1][0] = RspPHIInBlk1; OutLocs[1][0] = RspDefInBlk1; VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)}); VLocs[1].Vars.insert({Var, DbgValue(LiveInRax, EmptyProps, DbgValue::Def)}); buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output, OutLocsPtr, InLocsPtr, VLocs); EXPECT_EQ(Output[0].size(), 0ul); EXPECT_EQ(Output[1].size(), 0ul); ASSERT_EQ(Output[2].size(), 1ul); EXPECT_EQ(Output[2][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[2][0].second.ID, LiveInRax); ClearOutputs(); VLocs[0].Vars.clear(); VLocs[1].Vars.clear(); // Now, if we assign RspDefInBlk1 in the loop block, we should be able to // find the appropriate PHI. InLocs[1][0] = RspPHIInBlk1; OutLocs[1][0] = RspDefInBlk1; VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)}); VLocs[1].Vars.insert({Var, DbgValue(RspDefInBlk1, EmptyProps, DbgValue::Def)}); buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output, OutLocsPtr, InLocsPtr, VLocs); EXPECT_EQ(Output[0].size(), 0ul); ASSERT_EQ(Output[1].size(), 1ul); ASSERT_EQ(Output[2].size(), 1ul); EXPECT_EQ(Output[1][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[1][0].second.ID, RspPHIInBlk1); EXPECT_EQ(Output[2][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[2][0].second.ID, RspDefInBlk1); ClearOutputs(); VLocs[0].Vars.clear(); VLocs[1].Vars.clear(); // If the PHI happens in a different location, the live-in should happen // there. InLocs[1][0] = LiveInRsp; OutLocs[1][0] = LiveInRsp; InLocs[1][1] = RaxPHIInBlk1; OutLocs[1][1] = RspDefInBlk1; VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)}); VLocs[1].Vars.insert({Var, DbgValue(RspDefInBlk1, EmptyProps, DbgValue::Def)}); buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output, OutLocsPtr, InLocsPtr, VLocs); EXPECT_EQ(Output[0].size(), 0ul); ASSERT_EQ(Output[1].size(), 1ul); ASSERT_EQ(Output[2].size(), 1ul); EXPECT_EQ(Output[1][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[1][0].second.ID, RaxPHIInBlk1); EXPECT_EQ(Output[2][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[2][0].second.ID, RspDefInBlk1); ClearOutputs(); VLocs[0].Vars.clear(); VLocs[1].Vars.clear(); // The PHI happening in both places should be handled too. Exactly where // isn't important, but if the location picked changes, this test will let // you know. InLocs[1][0] = RaxPHIInBlk1; OutLocs[1][0] = RspDefInBlk1; InLocs[1][1] = RaxPHIInBlk1; OutLocs[1][1] = RspDefInBlk1; VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)}); VLocs[1].Vars.insert({Var, DbgValue(RspDefInBlk1, EmptyProps, DbgValue::Def)}); buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output, OutLocsPtr, InLocsPtr, VLocs); EXPECT_EQ(Output[0].size(), 0ul); ASSERT_EQ(Output[1].size(), 1ul); ASSERT_EQ(Output[2].size(), 1ul); EXPECT_EQ(Output[1][0].second.Kind, DbgValue::Def); // Today, the first register is picked. EXPECT_EQ(Output[1][0].second.ID, RspPHIInBlk1); EXPECT_EQ(Output[2][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[2][0].second.ID, RspDefInBlk1); ClearOutputs(); VLocs[0].Vars.clear(); VLocs[1].Vars.clear(); // If the loop block looked a bit like this: // %0 = PHI %1, %2 // [...] // DBG_VALUE %0 // Then with instr-ref it becomes: // DBG_PHI %0 // [...] // DBG_INSTR_REF // And we would be feeding a machine PHI-value back around the loop. However: // this does not mean we can eliminate the variable value PHI and use the // variable value from the entry block: they are distinct values that must be // joined at some location by the control flow. // [This test input would never occur naturally, the machine-PHI would be // eliminated] InLocs[1][0] = RspPHIInBlk1; OutLocs[1][0] = RspPHIInBlk1; InLocs[1][1] = LiveInRax; OutLocs[1][1] = LiveInRax; VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)}); VLocs[1].Vars.insert({Var, DbgValue(RspPHIInBlk1, EmptyProps, DbgValue::Def)}); buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output, OutLocsPtr, InLocsPtr, VLocs); EXPECT_EQ(Output[0].size(), 0ul); ASSERT_EQ(Output[1].size(), 1ul); ASSERT_EQ(Output[2].size(), 1ul); EXPECT_EQ(Output[1][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[1][0].second.ID, RspPHIInBlk1); EXPECT_EQ(Output[2][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[2][0].second.ID, RspPHIInBlk1); ClearOutputs(); VLocs[0].Vars.clear(); VLocs[1].Vars.clear(); // Test that we can eliminate PHIs. A PHI will be placed at the loop head // because there's a def in in. InLocs[1][0] = LiveInRsp; OutLocs[1][0] = LiveInRsp; VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)}); VLocs[1].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)}); buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output, OutLocsPtr, InLocsPtr, VLocs); EXPECT_EQ(Output[0].size(), 0ul); ASSERT_EQ(Output[1].size(), 1ul); ASSERT_EQ(Output[2].size(), 1ul); EXPECT_EQ(Output[1][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[1][0].second.ID, LiveInRsp); EXPECT_EQ(Output[2][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[2][0].second.ID, LiveInRsp); ClearOutputs(); VLocs[0].Vars.clear(); VLocs[1].Vars.clear(); } // test phi elimination with the nested situation TEST_F(InstrRefLDVTest, VLocNestedLoop) { // entry // | // loop1 // ^\ // | \ /-\ // | loop2 | // | / \-/ // ^ / // join // | // ret setupNestedLoops(); ASSERT_TRUE(MTracker->getNumLocs() == 1); LocIdx RspLoc(0); Register RAX = getRegByName("RAX"); LocIdx RaxLoc = MTracker->lookupOrTrackRegister(RAX); unsigned EntryBlk = 0, Loop1Blk = 1, Loop2Blk = 2; ValueIDNum LiveInRsp = ValueIDNum(EntryBlk, 0, RspLoc); ValueIDNum LiveInRax = ValueIDNum(EntryBlk, 0, RaxLoc); ValueIDNum RspPHIInBlk1 = ValueIDNum(Loop1Blk, 0, RspLoc); ValueIDNum RspPHIInBlk2 = ValueIDNum(Loop2Blk, 0, RspLoc); ValueIDNum RspDefInBlk2 = ValueIDNum(Loop2Blk, 1, RspLoc); ValueIDNum InLocs[5][2], OutLocs[5][2]; ValueIDNum *InLocsPtr[5] = {InLocs[0], InLocs[1], InLocs[2], InLocs[3], InLocs[4]}; ValueIDNum *OutLocsPtr[5] = {OutLocs[0], OutLocs[1], OutLocs[2], OutLocs[3], OutLocs[4]}; initValueArray(InLocsPtr, 5, 2); initValueArray(OutLocsPtr, 5, 2); DebugVariable Var(FuncVariable, None, nullptr); DbgValueProperties EmptyProps(EmptyExpr, false); SmallSet<DebugVariable, 4> AllVars; AllVars.insert(Var); SmallPtrSet<MachineBasicBlock *, 5> AssignBlocks; AssignBlocks.insert(MBB0); AssignBlocks.insert(MBB1); AssignBlocks.insert(MBB2); AssignBlocks.insert(MBB3); AssignBlocks.insert(MBB4); SmallVector<VLocTracker, 5> VLocs; VLocs.resize(5); InstrRefBasedLDV::LiveInsT Output; // Start off with LiveInRsp in every location. for (unsigned int I = 0; I < 5; ++I) { InLocs[I][0] = InLocs[I][1] = LiveInRsp; OutLocs[I][0] = OutLocs[I][1] = LiveInRsp; } auto ClearOutputs = [&]() { for (auto &Elem : Output) Elem.clear(); }; Output.resize(5); // A dominating assign should propagate to all blocks. VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)}); buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output, OutLocsPtr, InLocsPtr, VLocs); EXPECT_EQ(Output[0].size(), 0ul); ASSERT_EQ(Output[1].size(), 1ul); ASSERT_EQ(Output[2].size(), 1ul); ASSERT_EQ(Output[3].size(), 1ul); ASSERT_EQ(Output[4].size(), 1ul); EXPECT_EQ(Output[1][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[1][0].second.ID, LiveInRsp); EXPECT_EQ(Output[2][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[2][0].second.ID, LiveInRsp); EXPECT_EQ(Output[3][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[3][0].second.ID, LiveInRsp); EXPECT_EQ(Output[4][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[4][0].second.ID, LiveInRsp); ClearOutputs(); VLocs[0].Vars.clear(); // Test that an assign in the inner loop causes unresolved PHIs at the heads // of both loops, and no output location. Dominated blocks do get values. VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)}); VLocs[2].Vars.insert({Var, DbgValue(LiveInRax, EmptyProps, DbgValue::Def)}); buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output, OutLocsPtr, InLocsPtr, VLocs); EXPECT_EQ(Output[0].size(), 0ul); EXPECT_EQ(Output[1].size(), 0ul); EXPECT_EQ(Output[2].size(), 0ul); ASSERT_EQ(Output[3].size(), 1ul); ASSERT_EQ(Output[4].size(), 1ul); EXPECT_EQ(Output[3][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[3][0].second.ID, LiveInRax); EXPECT_EQ(Output[4][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[4][0].second.ID, LiveInRax); ClearOutputs(); VLocs[0].Vars.clear(); VLocs[2].Vars.clear(); // Same test, but with no assignment in block 0. We should still get values // in dominated blocks. VLocs[2].Vars.insert({Var, DbgValue(LiveInRax, EmptyProps, DbgValue::Def)}); buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output, OutLocsPtr, InLocsPtr, VLocs); EXPECT_EQ(Output[0].size(), 0ul); EXPECT_EQ(Output[1].size(), 0ul); EXPECT_EQ(Output[2].size(), 0ul); ASSERT_EQ(Output[3].size(), 1ul); ASSERT_EQ(Output[4].size(), 1ul); EXPECT_EQ(Output[3][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[3][0].second.ID, LiveInRax); EXPECT_EQ(Output[4][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[4][0].second.ID, LiveInRax); ClearOutputs(); VLocs[2].Vars.clear(); // Similarly, assignments in the outer loop gives location to dominated // blocks, but no PHI locations are found at the outer loop head. VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)}); VLocs[3].Vars.insert({Var, DbgValue(LiveInRax, EmptyProps, DbgValue::Def)}); buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output, OutLocsPtr, InLocsPtr, VLocs); EXPECT_EQ(Output[0].size(), 0ul); EXPECT_EQ(Output[1].size(), 0ul); EXPECT_EQ(Output[2].size(), 0ul); EXPECT_EQ(Output[3].size(), 0ul); ASSERT_EQ(Output[4].size(), 1ul); EXPECT_EQ(Output[4][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[4][0].second.ID, LiveInRax); ClearOutputs(); VLocs[0].Vars.clear(); VLocs[3].Vars.clear(); VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)}); VLocs[1].Vars.insert({Var, DbgValue(LiveInRax, EmptyProps, DbgValue::Def)}); buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output, OutLocsPtr, InLocsPtr, VLocs); EXPECT_EQ(Output[0].size(), 0ul); EXPECT_EQ(Output[1].size(), 0ul); ASSERT_EQ(Output[2].size(), 1ul); ASSERT_EQ(Output[3].size(), 1ul); ASSERT_EQ(Output[4].size(), 1ul); EXPECT_EQ(Output[2][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[2][0].second.ID, LiveInRax); EXPECT_EQ(Output[3][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[3][0].second.ID, LiveInRax); EXPECT_EQ(Output[4][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[4][0].second.ID, LiveInRax); ClearOutputs(); VLocs[0].Vars.clear(); VLocs[1].Vars.clear(); // With an assignment of the same value in the inner loop, we should work out // that all PHIs can be eliminated and the same value is live-through the // whole function. VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)}); VLocs[2].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)}); buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output, OutLocsPtr, InLocsPtr, VLocs); EXPECT_EQ(Output[0].size(), 0ul); EXPECT_EQ(Output[1].size(), 1ul); EXPECT_EQ(Output[2].size(), 1ul); ASSERT_EQ(Output[3].size(), 1ul); ASSERT_EQ(Output[4].size(), 1ul); EXPECT_EQ(Output[1][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[1][0].second.ID, LiveInRsp); EXPECT_EQ(Output[2][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[2][0].second.ID, LiveInRsp); EXPECT_EQ(Output[3][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[3][0].second.ID, LiveInRsp); EXPECT_EQ(Output[4][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[4][0].second.ID, LiveInRsp); ClearOutputs(); VLocs[0].Vars.clear(); VLocs[2].Vars.clear(); // If we have an assignment in the inner loop, and a PHI for it at the inner // loop head, we could find a live-in location for the inner loop. But because // the outer loop has no PHI, we can't find a variable value for outer loop // head, so can't have a live-in value for the inner loop head. InLocs[2][0] = RspPHIInBlk2; OutLocs[2][0] = LiveInRax; // NB: all other machine locations are LiveInRsp, disallowing a PHI in block // one. Even though RspPHIInBlk2 isn't available later in the function, we // should still produce a live-in value. The fact it's unavailable is a // different concern. VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)}); VLocs[2].Vars.insert({Var, DbgValue(LiveInRax, EmptyProps, DbgValue::Def)}); buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output, OutLocsPtr, InLocsPtr, VLocs); EXPECT_EQ(Output[0].size(), 0ul); EXPECT_EQ(Output[1].size(), 0ul); EXPECT_EQ(Output[2].size(), 0ul); ASSERT_EQ(Output[3].size(), 1ul); ASSERT_EQ(Output[4].size(), 1ul); EXPECT_EQ(Output[3][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[3][0].second.ID, LiveInRax); EXPECT_EQ(Output[4][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[4][0].second.ID, LiveInRax); ClearOutputs(); VLocs[0].Vars.clear(); VLocs[2].Vars.clear(); // Have an assignment in inner loop that can have a PHI resolved; and add a // machine value PHI to the outer loop head, so that we can find a location // all the way through the function. InLocs[1][0] = RspPHIInBlk1; OutLocs[1][0] = RspPHIInBlk1; InLocs[2][0] = RspPHIInBlk2; OutLocs[2][0] = RspDefInBlk2; InLocs[3][0] = RspDefInBlk2; OutLocs[3][0] = RspDefInBlk2; VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)}); VLocs[2].Vars.insert({Var, DbgValue(RspDefInBlk2, EmptyProps, DbgValue::Def)}); buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output, OutLocsPtr, InLocsPtr, VLocs); EXPECT_EQ(Output[0].size(), 0ul); ASSERT_EQ(Output[1].size(), 1ul); ASSERT_EQ(Output[2].size(), 1ul); ASSERT_EQ(Output[3].size(), 1ul); ASSERT_EQ(Output[4].size(), 1ul); EXPECT_EQ(Output[1][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[1][0].second.ID, RspPHIInBlk1); EXPECT_EQ(Output[2][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[2][0].second.ID, RspPHIInBlk2); EXPECT_EQ(Output[3][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[3][0].second.ID, RspDefInBlk2); EXPECT_EQ(Output[4][0].second.Kind, DbgValue::Def); EXPECT_EQ(Output[4][0].second.ID, RspDefInBlk2); ClearOutputs(); VLocs[0].Vars.clear(); VLocs[2].Vars.clear(); }
39.006479
202
0.681704
[ "object" ]
2902d2750054fa81b49153707ef3c98393638ff3
2,210
cpp
C++
src/CountTriangles.cpp
liu2z2/codility
c73c40ada9a7cb13c6f415e70fef3e89f0fa85d5
[ "Unlicense" ]
37
2019-06-18T08:26:40.000Z
2022-03-29T19:51:48.000Z
src/CountTriangles.cpp
liu2z2/codility
c73c40ada9a7cb13c6f415e70fef3e89f0fa85d5
[ "Unlicense" ]
6
2019-06-27T06:26:37.000Z
2022-02-09T04:54:18.000Z
src/CountTriangles.cpp
liu2z2/codility
c73c40ada9a7cb13c6f415e70fef3e89f0fa85d5
[ "Unlicense" ]
30
2019-05-24T02:11:32.000Z
2021-10-16T00:12:27.000Z
// https://app.codility.com/programmers/lessons/15-caterpillar_method/count_triangles/ // // Task Score: 100% // Correctness: 100% // Performance: 100% // Detected time complexity: O(N^2) // #include <algorithm> #include <vector> #include <map> using namespace std; // This is the simple brute force method, but it O(N^3) // Solution passes 100%, performance tests fail int bruteForce(vector<int> &A) { const int N = A.size(); if ( N<3 ) { return 0; } long long int triangles = 0; for (int i=0; i<(N-2); i++) { for (int j=(i+1); j<(N-1); j++) { for (int k=(j+1); k<N; k++) { if ( ( (A[i] + A[j]) > A[k]) && ( (A[j] + A[k]) > A[i]) && ( (A[k] + A[i]) > A[j]) ) { triangles++; } } } } return triangles; } // // This is the optimized solution // int solution(vector<int> &A) { const int N = A.size(); // If we sort the array, we only need to find A[P] + A[Q] > A[R] // Given // 0 <= P < Q < R < N // 0 < A[P] <= A[Q] <= A[R] // Then // A[Q] + A[R] > A[P] because A[n] > 0 and A[Q] and A[R] both >= A[P] // A[P] + A[R] > A[Q] Because A[n] > 0 and A[R] >= A[Q] // int triangles = 0; // Sort the algorithm, this is O(N*log(N)) complexity std::sort(A.begin(), A.end()); // Iterate through all numbers and find where A[P] + A[Q] > A[R] // or more specifically, where A[P] > A[R] - A[Q] for (int p=0; p<(N-2); p++) { // {P}, {Q = P+1}, {R = Q+1 = P+2} int r = p+2; // To make this O(N^2) we need to only loop through Q and R once, // knowing that when R > Q+1, then all of the A[Q] .. A[R-1] are // also solutions and we can just add them to the next iteration for (int q=(p+1); q<(N-1); q++) { // Stop if R reaches the end or if A[P] <= A[R]-A[Q] while ( (r<N) && (A[p] > (A[r]-A[q])) ) { // Increment the triangles and keep pushing R out to the right r++; } triangles += (r-q-1); } } return triangles; }
27.974684
86
0.464253
[ "vector" ]
2902eb284401751093cdaa81f5d352edd59f761b
2,192
cpp
C++
algorithms/sorting_and_searching/non_comparison_sorting/example.cpp
kruztev/FMI-DSA
f509dba6cd95792ec9c4c9ad55620a3dc06c6602
[ "MIT" ]
24
2017-12-21T13:57:34.000Z
2021-12-08T01:12:32.000Z
algorithms/sorting_and_searching/non_comparison_sorting/example.cpp
kruztev/FMI-DSA
f509dba6cd95792ec9c4c9ad55620a3dc06c6602
[ "MIT" ]
28
2018-11-01T23:34:08.000Z
2019-10-07T17:42:54.000Z
algorithms/sorting_and_searching/non_comparison_sorting/example.cpp
kruztev/FMI-DSA
f509dba6cd95792ec9c4c9ad55620a3dc06c6602
[ "MIT" ]
4
2018-04-24T19:28:51.000Z
2020-07-19T14:06:23.000Z
/******************************************************************************* * This file is part of the "Data structures and algorithms" course. FMI 2018/19 *******************************************************************************/ /** * @file example.cpp * @author Ivan Filipov * @author Nikolay Babulkov * @date 12.2019 * @brief An example usage of our non-comparison sorting implementations. */ #include <cstdio> // std::printf(), std::putchar() #include "non_comparison_sorting.h" using std::printf; using std::putchar; /// printing array with contain which can be casted to integer template <typename T> void print_array(const std::vector<T>& arr) { for(int i : arr) printf("%d ", i); putchar('\n'); } /// test counting sort on fixed array void test_counting_sort() { std::vector<unsigned char> arr = { 124 ,5 , 11, 2, 6, 7 , 42 , 13 , 88 , 21 ,9 , 8 }; printf("\n--------------\n"); printf("\ngiven array : \n"); print_array(arr); counting_sort(arr); printf("\nresult of counting sort : \n"); print_array(arr); } /// test MSD radix sort on fixed array of strings void test_msd_radix() { std::vector<std::string> given_names = { "pesho", "gosho", "katrin", "jean", "claude", "van", "damme" }; printf("\n--------------\n"); printf("\ngiven names : \n"); for (const std::string& name : given_names) printf("\"%s\" ", name.c_str()); msd_strings_radix_sort(given_names, 0, given_names.size(), 0); printf("\n\nafter MSD radix sorting : \n"); for (const std::string& name : given_names) printf("\"%s\" ", name.c_str()); putchar('\n'); } /// test LSD radix sort on fixed array void test_lsd_radix() { std::vector<int> vec = { 22211, 555, 444, 1223, 1000, 322, 245, 231, 3, 23 }; printf("\n--------------\n"); printf("\ngiven array:\n"); print_array(vec); lsd_radix_sort(vec); printf("\nsorted output from LSD radix sorting: \n"); print_array(vec); } int main() { /* run counting sort algorithm */ test_counting_sort(); /* run MSD strings radix sort algorithm */ test_msd_radix(); /* run LSD integers radix sort algorithm */ test_lsd_radix(); return 0; }
25.488372
86
0.577099
[ "vector" ]
291061150d61230d9efe595bfd0de4447dc6b160
9,885
cpp
C++
CirculationModel.cpp
alexkaiser/heart_valves
53f30ec3680503542890a84949b7fb51d1734272
[ "BSD-3-Clause" ]
null
null
null
CirculationModel.cpp
alexkaiser/heart_valves
53f30ec3680503542890a84949b7fb51d1734272
[ "BSD-3-Clause" ]
null
null
null
CirculationModel.cpp
alexkaiser/heart_valves
53f30ec3680503542890a84949b7fb51d1734272
[ "BSD-3-Clause" ]
null
null
null
// Filename: CirculationModel.cpp // Created on 20 Aug 2007 by Boyce Griffith // Modified by Alex Kaiser, 7/2016 #include "CirculationModel.h" /////////////////////////////// INCLUDES ///////////////////////////////////// #ifndef included_IBAMR_config #include <IBAMR_config.h> #define included_IBAMR_config #endif #ifndef included_SAMRAI_config #include <SAMRAI_config.h> #define included_SAMRAI_config #endif // SAMRAI INCLUDES #include <CartesianGridGeometry.h> #include <CartesianPatchGeometry.h> #include <PatchLevel.h> #include <SideData.h> #include <tbox/RestartManager.h> #include <tbox/SAMRAI_MPI.h> #include <tbox/Utilities.h> // C++ STDLIB INCLUDES #include <cassert> /////////////////////////////// NAMESPACE //////////////////////////////////// /////////////////////////////// STATIC /////////////////////////////////////// #define MMHG_TO_CGS 1333.22368 namespace { // Name of output file. static const string DATA_FILE_NAME = "bc_data.m"; } /////////////////////////////// PUBLIC /////////////////////////////////////// CirculationModel::CirculationModel(const string& object_name, Pointer<Database> input_db, bool register_for_restart, double P_initial) : d_object_name(object_name), d_registered_for_restart(register_for_restart), d_time(0.0), d_nsrc(1), // number of sets of variables d_qsrc(d_nsrc, 0.0), // flux d_psrc(d_nsrc, P_initial), // pressure d_p_opposite(0.0), // pressure opposite face d_srcname(d_nsrc), d_P_Wk(P_initial), d_bdry_interface_level_number(numeric_limits<int>::max()) { #if !defined(NDEBUG) assert(!object_name.empty()); #endif if (d_registered_for_restart) { RestartManager::getManager()->registerRestartItem(d_object_name, this); } if (input_db) { d_R_proximal = input_db->getDouble("R_proximal"); d_R_distal = input_db->getDouble("R_distal"); d_C = input_db->getDouble("C"); std::cout << "input db got values R_proximal = " << d_R_proximal << "\tR_distal = " << d_R_distal << "\tC = " << d_C << "\n"; } else { TBOX_ERROR("Must provide valid input_db"); } // Initialize object with data read from the input and restart databases. const bool from_restart = RestartManager::getManager()->isFromRestart(); if (from_restart) { getFromRestart(); } else { // nsrcs = the number of sources in the valve tester: // (1) windkessel d_srcname[0] = "windkessel "; } return; } // CirculationModel CirculationModel::~CirculationModel() { return; } // ~CirculationModel void CirculationModel::windkessel_be_update(double& P_Wk, double& P_boundary, const double& Q_l_atrium, const double& dt) { // Backward Euler update for windkessel model. P_Wk = ((d_C / dt) * P_Wk + Q_l_atrium) / (d_C / dt + 1.0 / d_R_distal); P_boundary = P_Wk + d_R_proximal * Q_l_atrium; return; } // windkessel_be_update void CirculationModel::advanceTimeDependentData(const double dt, const double Q_input) { d_qsrc[0] = Q_input; // The downstream pressure is determined by a three-element Windkessel model. double P_boundary; const double Q_source = d_qsrc[0]; double& P_Wk = d_P_Wk; windkessel_be_update(P_Wk, P_boundary, Q_source, dt); d_psrc[0] = P_boundary; // Update the current time. d_time += dt; // Output the updated values. const long precision = plog.precision(); plog.unsetf(ios_base::showpos); plog.unsetf(ios_base::scientific); plog << "============================================================================\n" << "Circulation model variables at time " << d_time << ":\n"; plog.setf(ios_base::showpos); plog.setf(ios_base::scientific); plog.precision(5); plog << "Q = " << d_qsrc[0] << " ml/s\n"; plog << "P_boundary = " << d_psrc[0]/MMHG_TO_CGS << " mmHg\t" << d_psrc[0] << " dynes/cm^2\n"; plog << "P_Wk = " << d_psrc[0]/MMHG_TO_CGS << " mmHg\t" << P_Wk << " dynes/cm^2\n" ; plog << "============================================================================\n"; plog.unsetf(ios_base::showpos); plog.unsetf(ios_base::scientific); plog.precision(precision); // Write the current state to disk. writeDataFile(); return; } // advanceTimeDependentData void CirculationModel::putToDatabase(Pointer<Database> db) { db->putDouble("d_time", d_time); db->putInteger("d_nsrc", d_nsrc); db->putDoubleArray("d_qsrc", &d_qsrc[0], d_nsrc); db->putDoubleArray("d_psrc", &d_psrc[0], d_nsrc); db->putStringArray("d_srcname", &d_srcname[0], d_nsrc); db->putDouble("d_P_Wk", d_P_Wk); db->putDouble("d_p_opposite", d_p_opposite); db->putInteger("d_bdry_interface_level_number", d_bdry_interface_level_number); return; } // putToDatabase void CirculationModel::write_plot_code() { static const int mpi_root = 0; if (SAMRAI_MPI::getRank() == mpi_root) { ofstream fout(DATA_FILE_NAME.c_str(), ios::app); fout.setf(ios_base::scientific); fout.setf(ios_base::showpos); fout.precision(10); fout << "];\n"; fout << "MMHG_TO_CGS = 1333.22368;\n"; fout << "fig = figure;\n"; fout << "times = bc_vals(:,1);\n"; fout << "p_aorta = bc_vals(:,2)/MMHG_TO_CGS;\n"; fout << "q_aorta = bc_vals(:,3);\n"; fout << "p_wk = bc_vals(:,4)/MMHG_TO_CGS;\n"; fout << "p_lv = bc_vals(:,5)/MMHG_TO_CGS;\n"; fout << "subplot(2,1,1)\n"; fout << "plot(times, p_aorta, 'k')\n"; fout << "hold on\n"; fout << "plot(times, p_wk, ':k')\n"; fout << "plot(times, p_lv, '--k')\n"; fout << "legend('P_{Ao}', 'P_{Wk}', 'P_{LV}', 'Location','NorthEastOutside');\n"; fout << "xlabel('t (s)');\n"; fout << "ylabel('P (mmHg)');\n"; fout << "subplot(2,1,2)\n"; fout << "plot(times, q_aorta, 'k')\n"; fout << "hold on\n"; fout << "dt = times(2,1) - times(1);\n"; fout << "net_flux = dt*cumsum(q_aorta);\n"; fout << "plot(bc_vals(:,1), net_flux, '--k')\n"; fout << "plot(bc_vals(:,1), 0*net_flux, ':k')\n"; fout << "legend('Q', 'net Q', 'Location','NorthEastOutside')\n"; fout << "xlabel('t (s)')\n"; fout << "ylabel('Flow (ml/s), Net Flow (ml)')\n"; fout << "set(fig, 'Position', [100, 100, 1000, 750])\n"; fout << "set(fig,'PaperPositionMode','auto')\n"; fout << "printfig(fig, 'bc_model_variables')\n"; fout << "min_p_aorta_after_first_beat = min(p_aorta(floor(end/3):end))\n"; fout << "max_p_aorta_after_first_beat = max(p_aorta(floor(end/3):end))\n"; fout << "mean_p_aorta = mean(p_aorta)\n"; fout << "mean_p_wk = mean(p_wk)\n"; fout << "mean_p_lv = mean(p_lv)\n"; } return; } /////////////////////////////// PROTECTED //////////////////////////////////// /////////////////////////////// PRIVATE ////////////////////////////////////// void CirculationModel::writeDataFile() const { static const int mpi_root = 0; if (SAMRAI_MPI::getRank() == mpi_root) { static bool file_initialized = false; const bool from_restart = RestartManager::getManager()->isFromRestart(); if (!from_restart && !file_initialized) { ofstream fout(DATA_FILE_NAME.c_str(), ios::out); fout << "% time " << " P_outlet (dynes/cm^2)" << " Q (ml/s)" << " P_Wk (dynes/cm^2)" << " P_opposite (dynes/cm^2)" << "\n" << "bc_vals = ["; file_initialized = true; } ofstream fout(DATA_FILE_NAME.c_str(), ios::app); for (int n = 0; n < d_nsrc; ++n) { fout << d_time; fout.setf(ios_base::scientific); fout.setf(ios_base::showpos); fout.precision(10); fout << " " << d_psrc[n]; fout.setf(ios_base::scientific); fout.setf(ios_base::showpos); fout.precision(10); fout << " " << d_qsrc[n]; fout.setf(ios_base::scientific); fout.setf(ios_base::showpos); fout.precision(10); fout << " " << d_P_Wk; fout.setf(ios_base::scientific); fout.setf(ios_base::showpos); fout.precision(10); fout << " " << d_p_opposite; fout << "; \n"; } } return; } // writeDataFile void CirculationModel::getFromRestart() { Pointer<Database> restart_db = RestartManager::getManager()->getRootDatabase(); Pointer<Database> db; if (restart_db->isDatabase(d_object_name)) { db = restart_db->getDatabase(d_object_name); } else { TBOX_ERROR("Restart database corresponding to " << d_object_name << " not found in restart file."); } d_time = db->getDouble("d_time"); d_nsrc = db->getInteger("d_nsrc"); d_qsrc.resize(d_nsrc); d_psrc.resize(d_nsrc); d_srcname.resize(d_nsrc); db->getDoubleArray("d_qsrc", &d_qsrc[0], d_nsrc); db->getDoubleArray("d_psrc", &d_psrc[0], d_nsrc); db->getStringArray("d_srcname", &d_srcname[0], d_nsrc); d_P_Wk = db->getDouble("d_P_Wk"); d_p_opposite = db->getDouble("d_p_opposite"); d_bdry_interface_level_number = db->getInteger("d_bdry_interface_level_number"); return; } // getFromRestart /////////////////////////////// NAMESPACE //////////////////////////////////// /////////////////////////////// TEMPLATE INSTANTIATION /////////////////////// //////////////////////////////////////////////////////////////////////////////
33.060201
136
0.546788
[ "object", "model" ]
291364b73d800881aae7f82b8a00115918b12950
1,394
hpp
C++
demo/Vitis-AI-Library/samples/ultrafast/process_result.hpp
hito0512/Vitis-AI
996459fb96cb077ed2f7e789d515893b1cccbc95
[ "Apache-2.0" ]
1
2022-02-17T22:13:23.000Z
2022-02-17T22:13:23.000Z
demo/Vitis-AI-Library/samples/ultrafast/process_result.hpp
hito0512/Vitis-AI
996459fb96cb077ed2f7e789d515893b1cccbc95
[ "Apache-2.0" ]
null
null
null
demo/Vitis-AI-Library/samples/ultrafast/process_result.hpp
hito0512/Vitis-AI
996459fb96cb077ed2f7e789d515893b1cccbc95
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019 Xilinx Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <sys/stat.h> #include <iostream> #include <opencv2/core.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <vector> #include "vitis/ai/ultrafast.hpp" using namespace cv; using namespace std; Scalar colors[] = { Scalar(255, 0, 0), Scalar(0, 255, 0), Scalar(255, 255, 0), Scalar(0, 0, 255) }; static cv::Mat process_result( cv::Mat &img, const vitis::ai::UltraFastResult &result, bool is_jpeg) { int iloop = 0; for(auto &lane: result.lanes) { std::cout <<"lane: " << iloop << "\n"; for(auto &v: lane) { if(v.first >0) { cv::circle(img, cv::Point(v.first, v.second), 5, colors[iloop], -1); } std::cout << " ( " << v.first << ", " << v.second << " )\n"; } iloop++; } return img; }
27.88
99
0.647059
[ "vector" ]
29159f0185f5df1f53d045be9ea622b4c13bc756
962
cc
C++
RAVL2/Math/Geometry/Projective/2D/PPerspective2d.cc
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/Math/Geometry/Projective/2D/PPerspective2d.cc
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/Math/Geometry/Projective/2D/PPerspective2d.cc
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
// This file is part of RAVL, Recognition And Vision Library // Copyright (C) 2003, University of Surrey // This code may be redistributed under the terms of the GNU Lesser // General Public License (LGPL). See the lgpl.licence file for details or // see http://www.gnu.org/copyleft/lesser.html // file-header-ends-here //////////////////////////////////////////////////////////////////////// //! rcsid="$Id: PPerspective2d.cc 3521 2003-10-08 20:38:22Z craftit $" //! lib=RavlMath //! file="Ravl/Math/Geometry/Projective/2D/PPerspective2d.cc" #include "Ravl/PPerspective2d.hh" namespace RavlN { ostream & operator<<(ostream & outS, const PPerspective2dC & p) { for (UIntT i = 0; i < 3; ++i) for (UIntT j = 0; j < 3; ++j) outS << p[i][j] << ' '; return outS; } istream & operator>>(istream & inS, PPerspective2dC & p) { for (UIntT i = 0; i < 3; ++i) for (UIntT j = 0; j < 3; ++j) inS >> p[i][j]; return inS; } }
30.0625
74
0.5842
[ "geometry" ]
2915beda367fa56aa2ef58fbe3fa63608ebf333d
6,994
cpp
C++
source/test.cpp
ict-project/libict-utf8
88460cff256b7d85c93aedad15158d53230b228c
[ "BSD-3-Clause" ]
null
null
null
source/test.cpp
ict-project/libict-utf8
88460cff256b7d85c93aedad15158d53230b228c
[ "BSD-3-Clause" ]
null
null
null
source/test.cpp
ict-project/libict-utf8
88460cff256b7d85c93aedad15158d53230b228c
[ "BSD-3-Clause" ]
1
2022-03-28T20:22:59.000Z
2022-03-28T20:22:59.000Z
//! @file //! @brief Test module - Source file. //! @author Mariusz Ornowski (mariusz.ornowski@ict-project.pl) //! @version 1.0 //! @date 2016-2017 //! @copyright ICT-Project Mariusz Ornowski (ict-project.pl) /* ************************************************************** Copyright (c) 2016-2017, ICT-Project Mariusz Ornowski (ict-project.pl) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the ICT-Project Mariusz Ornowski 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 "test.hpp" #include "all.hpp" #include <algorithm> //============================================ namespace ict { namespace test { //=========================================== std::vector<TC*> & TC::getList(){ static std::vector<TC*> list; return(list); } TC::TC(const tag_list_t & tags_in,test_fun_t fun_in,const char * file_in,int line_in):tags(tags_in),fun(fun_in),file(file_in),line(line_in){ getList().push_back(this); } bool TC::testTags(const tag_list_t & tags_in) const{ for (const std::string & in : tags_in) { auto it=std::find(tags.begin(),tags.end(),in); if (it==tags.end()) return(false); } return(true); } std::string TC::printTags(const tag_list_t & tags_in,char separator) const{ std::string out; bool first=true; for (const std::string & in : tags_in) { if (first){ first=false; } else { out+=separator; } out+=in; } return(out); } std::string TC::printTags(char separator) const{ return(printTags(tags,separator)); } int TC::runThis(const tag_list_t & tags_in) const{ if (testTags(tags_in)){ int out=0; if (fun) { std::cout<<"## TC: "<<printTags()<<std::endl; out=fun(); std::cout<<"RESULT: "<<(out?"ERROR":"OK")<<std::endl; if (out){ std::cout<<" FILE="<<file<<", LINE="<<line<<", OUT="<<out<<std::endl; } std::cout<<std::endl; } return(out); } return(0); } int TC::run(const tag_list_t & tags_in){ if (tags_in.size()) if (tags_in.at(0)=="-"){ for (const TC * tc : getList()) { std::cout<<"add_test(NAME "<<tc->printTags('-')<<" COMMAND ${PROJECT_NAME}-test "<<tc->printTags(' ')<<")"<<std::endl; } return(0); } for (const TC * tc : getList()) { int out=tc->runThis(tags_in); if (out) return(out); } return(0); } //============================================ // Source: https://pl.wikipedia.org/wiki/Pangram#j.C4.99zyk_polski const test_string_t test_string({ "Pchnฤ…ฤ‡ w tฤ™ ล‚รณdลบ jeลผa lub oล›m skrzyล„ fig.", "Pรณjdลบลผe, kiล„ tฤ™ chmurnoล›ฤ‡ w gล‚ฤ…b flaszy!", "Myล›lฤ™: Fruล„ z pล‚acht gฤ…sko, jedลบ wbiฤ‡ nรณลผ.", "Doล›ฤ‡ bล‚azeล„stw, ลผrฤ… mรณj pฤ™k luลบnych fig.", "W niลผach mรณgล‚ zjeล›ฤ‡ truflฤ™ koล„ bฤ…dลบ psy.", "Doล›ฤ‡ grรณลบb fuzjฤ…, klnฤ™, pych i maล‚ลผeล„stw!", "Pรณjdลบ w loch zbiฤ‡ maล‚ลผeล„skฤ… gฤ™ล› futryn!", "Filmuj rzeลบ ลผฤ…daล„, poล›ฤ‡, gnฤ™b chล‚ystkรณw!.", "O, mรณgล‚ลผe sฤ™p chlaล„ wyjล›ฤ‡ furtkฤ… bลบdzin.", "Mฤ™ลผny bฤ…dลบ, chroล„ puล‚k twรณj i szeล›ฤ‡ flag.", "Chwyฤ‡ maล‚ลผonkฤ™, strรณj bฤ…dลบ pleล›ล„ z fugi.", "Jeลผ wlรณkล‚ gฤ™ล›. Uf! Bฤ…dลบ choฤ‡ przy nim, staล„!", "Wรณjt dลบgnฤ…ล‚ boลผy puch, szeล›ฤ‡ fraล„, milkฤ™.", "Mknฤ…ล‚ boลผy puch. Jeล›ฤ‡ stรณg z lฤ™dลบwi Fraล„?", "Puล›ฤ‡ mฤ… dล‚oล„! Gnij schab, frytkฤ™! Zwรณลบ ลผel!", "Tknฤ™ ล‚รณj, wapล„. Doล›ฤ‡! Uf! Gryลบ chleb, miฤ…ลผsz!", "Znajdลบ pchล‚y, wrรณลผko! Film \"Teล›ฤ‡\" gฤ™bฤ… suล„!", "Sklnฤ… chรณw ลผab? Jim, puล›ฤ‡ dล‚oล„! Zgryลบ fetฤ™!", "Aj, pech! Struล› dลบgnฤ…ล‚ ฤ‡mฤ™ FBI! Koล„ lลผy wรณz.", "Tchรณrz w KGB. Sฤ…dลบ pล‚oฤ‡! Fajny mฤ™ลผuล› i leล„.", "Bฤ…dลบ waล›ฤ‡ gej, chroล„ kumpli! Zล‚รณลผ syf, tnฤ™!", "Struล› czknฤ…ล‚. Pฤ™dลบ, bij ฤ‡my! ลปe รณw golf Haล„?", "Czyล›ฤ‡ sejf glinom! W ล‚รณลผku Haล„ ...pฤ™dลบ, trฤ…b!", "Strzฤ…ล›ฤ‡ puch nimfy w ล‚รณj kaล„? Boลผe, glฤ™dลบ!", "W Miล„sku lลผฤ… naftฤ™ Jรณลบ. Goล›ฤ‡ brzydล‚. Pech!", "Sznur ล›liw. Chล‚รณd gฤ…b. Pot mฤ™k. Jaลบล„ ลผyฤ‡. Fe!", "ใ‚ฏใ‚คใƒƒใ‚ฏใƒ–ใƒฉใ‚ฆใƒณใ‚ญใƒ„ใƒใฏๆ€ ๆƒฐใช็ŠฌใฎไธŠใ‚’้ฃ›ใณใพใ™ใ€‚", }); const test_wstring_t test_wstring({ L"Pchnฤ…ฤ‡ w tฤ™ ล‚รณdลบ jeลผa lub oล›m skrzyล„ fig.", L"Pรณjdลบลผe, kiล„ tฤ™ chmurnoล›ฤ‡ w gล‚ฤ…b flaszy!", L"Myล›lฤ™: Fruล„ z pล‚acht gฤ…sko, jedลบ wbiฤ‡ nรณลผ.", L"Doล›ฤ‡ bล‚azeล„stw, ลผrฤ… mรณj pฤ™k luลบnych fig.", L"W niลผach mรณgล‚ zjeล›ฤ‡ truflฤ™ koล„ bฤ…dลบ psy.", L"Doล›ฤ‡ grรณลบb fuzjฤ…, klnฤ™, pych i maล‚ลผeล„stw!", L"Pรณjdลบ w loch zbiฤ‡ maล‚ลผeล„skฤ… gฤ™ล› futryn!", L"Filmuj rzeลบ ลผฤ…daล„, poล›ฤ‡, gnฤ™b chล‚ystkรณw!.", L"O, mรณgล‚ลผe sฤ™p chlaล„ wyjล›ฤ‡ furtkฤ… bลบdzin.", L"Mฤ™ลผny bฤ…dลบ, chroล„ puล‚k twรณj i szeล›ฤ‡ flag.", L"Chwyฤ‡ maล‚ลผonkฤ™, strรณj bฤ…dลบ pleล›ล„ z fugi.", L"Jeลผ wlรณkล‚ gฤ™ล›. Uf! Bฤ…dลบ choฤ‡ przy nim, staล„!", L"Wรณjt dลบgnฤ…ล‚ boลผy puch, szeล›ฤ‡ fraล„, milkฤ™.", L"Mknฤ…ล‚ boลผy puch. Jeล›ฤ‡ stรณg z lฤ™dลบwi Fraล„?", L"Puล›ฤ‡ mฤ… dล‚oล„! Gnij schab, frytkฤ™! Zwรณลบ ลผel!", L"Tknฤ™ ล‚รณj, wapล„. Doล›ฤ‡! Uf! Gryลบ chleb, miฤ…ลผsz!", L"Znajdลบ pchล‚y, wrรณลผko! Film \"Teล›ฤ‡\" gฤ™bฤ… suล„!", L"Sklnฤ… chรณw ลผab? Jim, puล›ฤ‡ dล‚oล„! Zgryลบ fetฤ™!", L"Aj, pech! Struล› dลบgnฤ…ล‚ ฤ‡mฤ™ FBI! Koล„ lลผy wรณz.", L"Tchรณrz w KGB. Sฤ…dลบ pล‚oฤ‡! Fajny mฤ™ลผuล› i leล„.", L"Bฤ…dลบ waล›ฤ‡ gej, chroล„ kumpli! Zล‚รณลผ syf, tnฤ™!", L"Struล› czknฤ…ล‚. Pฤ™dลบ, bij ฤ‡my! ลปe รณw golf Haล„?", L"Czyล›ฤ‡ sejf glinom! W ล‚รณลผku Haล„ ...pฤ™dลบ, trฤ…b!", L"Strzฤ…ล›ฤ‡ puch nimfy w ล‚รณj kaล„? Boลผe, glฤ™dลบ!", L"W Miล„sku lลผฤ… naftฤ™ Jรณลบ. Goล›ฤ‡ brzydล‚. Pech!", L"Sznur ล›liw. Chล‚รณd gฤ…b. Pot mฤ™k. Jaลบล„ ลผyฤ‡. Fe!", L"ใ‚ฏใ‚คใƒƒใ‚ฏใƒ–ใƒฉใ‚ฆใƒณใ‚ญใƒ„ใƒใฏๆ€ ๆƒฐใช็ŠฌใฎไธŠใ‚’้ฃ›ใณใพใ™ใ€‚", }); //============================================ }} //============================================ ict::test::tag_list_t tag_list; //================================================= int main(int argc,const char **argv){ //std::string locale(setlocale(LC_ALL,std::getenv("LANG"))); std::string locale(setlocale(LC_ALL,"C")); for (std::size_t i=1;i<argc;i++) { tag_list.emplace_back(argv[i]); } return(ict::test::TC::run(tag_list)); } //===========================================
39.738636
140
0.637403
[ "vector" ]
2919ed98e2a36c18bb1987522064a58f271ea316
9,090
cc
C++
chrome/test/chromedriver/server/http_server.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-10-18T02:33:40.000Z
2020-10-18T02:33:40.000Z
chrome/test/chromedriver/server/http_server.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2021-05-17T16:28:52.000Z
2021-05-21T22:42:22.000Z
chrome/test/chromedriver/server/http_server.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/test/chromedriver/server/http_server.h" #include "net/base/network_interfaces.h" namespace { // Maximum message size between app and ChromeDriver. Data larger than 150 MB // or so can cause crashes in Chrome (https://crbug.com/890854), so there is no // need to support messages that are too large. const int kBufferSize = 256 * 1024 * 1024; // 256 MB int ListenOnIPv4(net::ServerSocket* socket, uint16_t port, bool allow_remote) { std::string binding_ip = net::IPAddress::IPv4Localhost().ToString(); if (allow_remote) binding_ip = net::IPAddress::IPv4AllZeros().ToString(); return socket->ListenWithAddressAndPort(binding_ip, port, 5); } int ListenOnIPv6(net::ServerSocket* socket, uint16_t port, bool allow_remote) { std::string binding_ip = net::IPAddress::IPv6Localhost().ToString(); if (allow_remote) binding_ip = net::IPAddress::IPv6AllZeros().ToString(); return socket->ListenWithAddressAndPort(binding_ip, port, 5); } // Heuristic to check if hostname is fully qualified bool IsSimple(const std::string& hostname) { return hostname.find('.') == std::string::npos; } bool IsMatch(const std::string& system_host, const std::string& hostname) { return hostname == system_host || (base::StartsWith(system_host, hostname) && IsSimple(hostname) && system_host[hostname.size()] == '.'); } void GetCanonicalHostName(std::vector<std::string>* canonical_host_names) { struct addrinfo hints, *info = nullptr, *p; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_CANONNAME; auto hostname = net::GetHostName(); int gai_result; if ((gai_result = getaddrinfo(hostname.c_str(), "http", &hints, &info)) != 0) { LOG(ERROR) << "GetCanonicalHostName Error hostname: " << hostname; } for (p = info; p != nullptr; p = p->ai_next) { if (p->ai_canonname != hostname) canonical_host_names->emplace_back(p->ai_canonname); } if (canonical_host_names->empty()) canonical_host_names->emplace_back(hostname); freeaddrinfo(info); return; } bool RequestIsSafeToServe(const net::HttpServerRequestInfo& info, bool allow_remote, const std::vector<net::IPAddress>& whitelisted_ips) { std::string origin_header_value = info.GetHeaderValue("origin"); std::string host_header_value = info.GetHeaderValue("host"); bool is_origin_set = !origin_header_value.empty(); GURL origin_url(origin_header_value); bool is_origin_local = is_origin_set && net::IsLocalhost(origin_url); bool is_host_set = !host_header_value.empty(); GURL host_url("http://" + host_header_value); bool is_host_local = is_host_set && net::IsLocalhost(host_url); // If origin is localhost, then host needs to be localhost as well. if (is_origin_local && !is_host_local) { LOG(ERROR) << "Rejecting request with localhost origin but host: " << host_header_value; return false; } if (!allow_remote) { // If remote is not allowed, both origin and host header need to be // localhost or not specified. if (is_origin_set && !is_origin_local) { LOG(ERROR) << "Rejecting request with non-local origin: " << origin_header_value; return false; } if (is_host_set && !is_host_local) { LOG(ERROR) << "Rejecting request with non-local host: " << host_header_value; return false; } } else { if (is_origin_set && !is_origin_local) { // Check against allowed list where empty allowed list is special case to // allow all. Disallow any other non-local origin. bool allow_all = whitelisted_ips.empty(); if (!allow_all) { LOG(ERROR) << "Rejecting request with origin set: " << origin_header_value; return false; } } if (is_host_set && !is_host_local) { net::IPAddress host_address = net::IPAddress(); auto host = host_url.host(); bool host_match = false; if (ParseURLHostnameToAddress(host, &host_address)) { net::NetworkInterfaceList list; if (net::GetNetworkList(&list, net::INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES)) { for (const auto& networkInterface : list) { if (networkInterface.address == host_address) { host_match = true; break; } } if (!host_match) { LOG(ERROR) << "Rejecting request with host: " << host_header_value << " address: " << host_address.ToString(); return false; } } } else { static bool cached = false; static std::vector<std::string> canonical_host_names; if (!cached) { GetCanonicalHostName(&canonical_host_names); cached = true; } for (const auto& system_host : canonical_host_names) { if (IsMatch(system_host, host)) { host_match = true; break; } } if (!host_match) { LOG(ERROR) << "Unable find match for host: " << host_header_value; return false; } } } } return true; } } // namespace HttpServer::HttpServer(const std::string& url_base, const std::vector<net::IPAddress>& whitelisted_ips, const HttpRequestHandlerFunc& handle_request_func, base::WeakPtr<HttpHandler> handler, scoped_refptr<base::SingleThreadTaskRunner> cmd_runner) : url_base_(url_base), handle_request_func_(handle_request_func), allow_remote_(false), whitelisted_ips_(whitelisted_ips), handler_(handler), cmd_runner_(cmd_runner) {} int HttpServer::Start(uint16_t port, bool allow_remote, bool use_ipv4) { allow_remote_ = allow_remote; std::unique_ptr<net::ServerSocket> server_socket( new net::TCPServerSocket(nullptr, net::NetLogSource())); int status = use_ipv4 ? ListenOnIPv4(server_socket.get(), port, allow_remote) : ListenOnIPv6(server_socket.get(), port, allow_remote); if (status != net::OK) { VLOG(0) << "listen on " << (use_ipv4 ? "IPv4" : "IPv6") << " failed with error " << net::ErrorToShortString(status); return status; } server_ = std::make_unique<net::HttpServer>(std::move(server_socket), this); net::IPEndPoint address; return server_->GetLocalAddress(&address); } void HttpServer::OnConnect(int connection_id) { server_->SetSendBufferSize(connection_id, kBufferSize); server_->SetReceiveBufferSize(connection_id, kBufferSize); } void HttpServer::OnHttpRequest(int connection_id, const net::HttpServerRequestInfo& info) { if (!RequestIsSafeToServe(info, allow_remote_, whitelisted_ips_)) { server_->Send500(connection_id, "Host header or origin header is specified and is not " "whitelisted or localhost.", TRAFFIC_ANNOTATION_FOR_TESTS); return; } handle_request_func_.Run( info, base::BindRepeating(&HttpServer::OnResponse, weak_factory_.GetWeakPtr(), connection_id, !info.HasHeaderValue("connection", "close"))); } HttpServer::~HttpServer() = default; void HttpServer::OnWebSocketRequest(int connection_id, const net::HttpServerRequestInfo& info) { cmd_runner_->PostTask( FROM_HERE, base::BindOnce(&HttpHandler::OnWebSocketRequest, handler_, this, connection_id, info)); } void HttpServer::OnWebSocketMessage(int connection_id, std::string data) { // TODO: Make use of WebSocket data VLOG(0) << "HttpServer::OnWebSocketMessage received: " << data; } void HttpServer::OnClose(int connection_id) { cmd_runner_->PostTask( FROM_HERE, base::BindOnce(&HttpHandler::OnClose, handler_, this, connection_id)); } void HttpServer::AcceptWebSocket(int connection_id, const net::HttpServerRequestInfo& request) { server_->AcceptWebSocket(connection_id, request, TRAFFIC_ANNOTATION_FOR_TESTS); } void HttpServer::SendResponse( int connection_id, const net::HttpServerResponseInfo& response, const net::NetworkTrafficAnnotationTag& traffic_annotation) { server_->SendResponse(connection_id, response, traffic_annotation); } void HttpServer::OnResponse( int connection_id, bool keep_alive, std::unique_ptr<net::HttpServerResponseInfo> response) { if (!keep_alive) response->AddHeader("Connection", "close"); server_->SendResponse(connection_id, *response, TRAFFIC_ANNOTATION_FOR_TESTS); // Don't need to call server_->Close(), since SendResponse() will handle // this for us. }
36.653226
80
0.652035
[ "vector" ]
291e4e801747014cb0b3adce53b9fe14b4cdfcd9
15,172
cpp
C++
Server/Modules/SearchModule/src/SearchProcessor.cpp
wayfinder/Wayfinder-Server
a688546589f246ee12a8a167a568a9c4c4ef8151
[ "BSD-3-Clause" ]
4
2015-08-17T20:12:22.000Z
2020-05-30T19:53:26.000Z
Server/Modules/SearchModule/src/SearchProcessor.cpp
wayfinder/Wayfinder-Server
a688546589f246ee12a8a167a568a9c4c4ef8151
[ "BSD-3-Clause" ]
null
null
null
Server/Modules/SearchModule/src/SearchProcessor.cpp
wayfinder/Wayfinder-Server
a688546589f246ee12a8a167a568a9c4c4ef8151
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd 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 Vodafone Group Services Ltd 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 "config.h" #include "Packet.h" #include "Processor.h" #include "ServerProximityPackets.h" #include "SystemPackets.h" #include "SearchProcessor.h" #include "LoadMapPacket.h" #include "DeleteMapPacket.h" #include "StringTable.h" #include "SearchParameters.h" #include "SearchPacket.h" #include "SearchExpandItemPacket.h" #include "SearchableSearchUnit.h" #include "SearchMatch.h" #include "SearchResult.h" #include "DeleteHelpers.h" #include <map> #include <vector> #include <signal.h> // time to wait in seconds before exiting. // 10*60 s = 10 minutes const uint32 defaultAlarmLimit = 1*60; // one minute const uint32 loadMapAlarmLimit = 10*60; // ten minutes uint32 SearchProcessor::alarmLimit = defaultAlarmLimit; SearchProcessor::SearchProcessor(MapSafeVector* loadedMaps) : MapHandlingProcessor(loadedMaps) { m_nbrPackets = 0; m_nbrFailedPackets = 0; } SearchProcessor::~SearchProcessor() { STLUtility::deleteAllSecond( m_searchUnits ); m_searchUnits.clear(); } StringTable::stringCode SearchProcessor::loadMap( uint32 mapID, uint32& mapSize ) { setAlarm(loadMapAlarmLimit); mapSize = 1; // Change this to something better. // Check if it is already loaded... if ( m_searchUnits.find(mapID) != m_searchUnits.end() ) { mc2dbg << "[SProc]: Map " << mapID << " is already loaded" << endl; return StringTable::ERROR_MAP_LOADED; } // Check for MAX_UINT32. if ( mapID == MAX_UINT32 ) { mc2log << warn << "[SProc]: Loading of map MAX_UINT32 is not legal. " << "Request ignored." << endl; return StringTable::MAPNOTFOUND; } // Load SearchableSearchUnit* newUnit = new SearchableSearchUnit; if ( newUnit->loadFromMapModule(mapID) ) { m_searchUnits.insert(make_pair(mapID, newUnit)); // The size in the databuffer should pretty much correspond // to the real size in memory since the stuff is stored rather // compactly. mapSize = newUnit->getSizeInDataBuffer(); return StringTable::OK; } else { mc2log << error << "[SProc]: Load map not ok, deleting failed attempt " << "for map " << mapID << "." << endl; delete newUnit; return StringTable::ERROR_LOADING_MAP; } } StringTable::stringCode SearchProcessor::deleteMap( uint32 mapID ) { mc2dbg2 << "unloadMap " << mapID << endl; StringTable::stringCode result; if ( m_searchUnits.find(mapID) == m_searchUnits.end() ) { mc2dbg << "Non fatal error: \n" << "unloadMapRequest received with mapID that " << "was not loaded.\n" << "Request Ignored." << endl; result = StringTable::MAPNOTFOUND; } else { delete m_searchUnits[mapID]; m_searchUnits.erase(mapID); result = StringTable::OK; } return result; } const SearchableSearchUnit* SearchProcessor::getSearchUnitByMapID(uint32 mapID) const { map<uint32, SearchableSearchUnit*>::const_iterator it = m_searchUnits.find(mapID); if ( it == m_searchUnits.end() ) { return NULL; } else { return it->second; } } void SearchProcessor::handleAlarm(int iMsg) { ::mc2log << warn << "SearchProcessor: Received an alarm! iMsg is " << iMsg << endl; ::mc2log << error << "Query was not finished within " << SearchProcessor::alarmLimit << " seconds." << endl; abort(); } void SearchProcessor::setAlarm(uint32 seconds) { # ifndef profiling struct itimerval it; it.it_interval.tv_sec = 0; // no second alarm it.it_interval.tv_usec = 0; it.it_value.tv_sec = seconds; it.it_value.tv_usec = 0; alarmLimit = seconds; signal(SIGVTALRM, SearchProcessor::handleAlarm); if (setitimer(ITIMER_VIRTUAL, &it, NULL) != 0) { MC2WARNING2("Could not set alarm timer", PERROR;); } # endif } static inline void writePacketInfo(int nbrHits, char* packetInfo, int nbrMasks, char** maskNames, const uint32* masks, const char* searchString, uint32 categoryType, int maxPackInfo, LangTypes::language_t lang, SearchTypes::StringMatching matching = SearchTypes::MaxDefinedMatching, SearchTypes::StringPart part = SearchTypes::MaxDefinedStringPart, SearchTypes::SearchSorting sorting = SearchTypes::MaxDefinedSort) { int maxPackInfoLeft = maxPackInfo - 1; if ( packetInfo != NULL ) { int res = 0; for(int i=0; i < (int)nbrMasks && res >= 0 && maxPackInfoLeft > 0; ++i ){ if ( maskNames && maskNames[i] != NULL && maskNames[i][0] != '\0' ) { res = snprintf(packetInfo, maxPackInfoLeft, "%x:\"%s\", ", masks[i], maskNames[i]); packetInfo += res; maxPackInfoLeft -= res; } else { res = snprintf(packetInfo, maxPackInfoLeft, "0x%x, ", masks[i]); packetInfo += res; maxPackInfoLeft -= res; } if ( i > 20 ) { res = snprintf(packetInfo, maxPackInfoLeft, "... "); packetInfo += res; maxPackInfoLeft -= res; break; } } if ( res >=0 && maxPackInfoLeft > 0 ) { packetInfo -= 2; // Overwrite the , *packetInfo++ = ':'; *packetInfo = '\0'; maxPackInfoLeft--; } if ( res >= 0 && maxPackInfoLeft > 0 && searchString != NULL ) { res = snprintf(packetInfo, maxPackInfoLeft, "\"%s\"", searchString); maxPackInfoLeft -= res; packetInfo += res; } if ( res >= 0 && maxPackInfoLeft >= 12 ) { res = snprintf(packetInfo, maxPackInfoLeft, ",%#010x", categoryType); maxPackInfoLeft -= res; packetInfo += res; } if ( res >= 0 && maxPackInfoLeft >= 20 && matching != SearchTypes::MaxDefinedMatching) { const char* matchingString = SearchTypes::getMatchingString( matching ); const char* partString = SearchTypes::getPartString( part ); const char* sortingString = SearchTypes::getSortingString( sorting ); const char* langString = LangTypes::getLanguageAsString(lang, false); res = snprintf(packetInfo, maxPackInfoLeft, ",%s,%s,%s [%s]", partString, matchingString, sortingString, langString); maxPackInfoLeft -= res; packetInfo += res; } if ( maxPackInfoLeft >= 10 ) { char hits[30]; sprintf(hits, ", n=%d", nbrHits); strcat(packetInfo, hits); packetInfo += strlen(hits); } } } static inline void writePacketInfo(char* packetInfo, int maxPacketInfo, const UserSearchParameters& params, int nbrHits) { writePacketInfo(nbrHits, packetInfo, params.getNbrMasks(), NULL, params.getMaskItemIDs(), params.getSearchString(), params.getRequestedTypes(), maxPacketInfo, params.getRequestedLanguage(), params.getMatching(), params.getStringPart(), params.getSorting()); } SearchExpandItemReplyPacket* SearchProcessor:: handleSearchExpandItem(const SearchExpandItemRequestPacket* req) { vector<pair<uint32, IDPair_t> > reqIDs; STLUtility::AutoContainerMap< vector<pair<uint32, OverviewMatch*> > > expandedIDs; req->getItems(reqIDs); const SearchableSearchUnit* ssunit = getSearchUnitByMapID(req->getMapID()); ssunit->expandIDs( expandedIDs, reqIDs, req->getExpand() ); return new SearchExpandItemReplyPacket( req, expandedIDs ); } ReplyPacket* SearchProcessor::handleSearchRequestPacket(const SearchRequestPacket* req, char* packetInfo) { // Do not return early from this function since we want to // write JT-info. const uint32 mapID = req->getMapID(); const SearchableSearchUnit* unit = getSearchUnitByMapID(mapID); // Create the params. They know what to do. UserSearchParameters params(req); ReplyPacket* result = NULL; int nbrHits = -1; // What to do? switch ( req->getSearchType() ) { case SearchRequestPacket::USER_SEARCH: case SearchRequestPacket::PROXIMITY_SEARCH: { // These searches use VanillaReply. VanillaSearchReplyPacket* vanillaReply = new VanillaSearchReplyPacket(req); vanillaReply->setStatus(StringTable::OK); result = vanillaReply; SearchUnitSearchResult searchResult; switch ( req->getSearchType() ) { case SearchRequestPacket::USER_SEARCH: // Normal searching unit->search(searchResult, params); break; case SearchRequestPacket::PROXIMITY_SEARCH: // Convert the id:s to matches. unit->proximitySearch(searchResult, params, params.getProximityItems()); break; case SearchRequestPacket::OVERVIEW_SEARCH: // NOP, just to make the compiler stop complaning // should never be here. break; } // End inner switch. // And then add the results to the packet. for(SearchUnitSearchResult::iterator it = searchResult.begin(); it != searchResult.end(); ++it ) { (*it)->addToPacket(vanillaReply); } // For log nbrHits = searchResult.size(); } break; case SearchRequestPacket::OVERVIEW_SEARCH: { // Create the result vector and search. vector<OverviewMatch*> overviewResult; unit->overviewSearch( overviewResult, params ); // For log nbrHits = overviewResult.size(); result = new OverviewSearchReplyPacket(req, overviewResult); result->setStatus(StringTable::OK); // Clean up STLUtility::deleteValues( overviewResult ); } break; default: { // Not implemented result = new VanillaSearchReplyPacket(req); result->setStatus(StringTable::NOT); } break; } writePacketInfo(packetInfo, c_maxPackInfo, params, nbrHits); return result; } Packet* SearchProcessor::handleRequestPacket( const RequestPacket& p, char* packetInfo ) { setAlarm(defaultAlarmLimit); DEBUG2(uint32 startTime = TimeUtility::getCurrentMicroTime();); DEBUG2({ mc2log << info << "SearchProcessor received packet" << endl << "IP " << p.getOriginIP() << endl << "Port " << p.getOriginPort() << endl << "PacketID " << p.getPacketID() << endl << "RequestID " << p.getRequestID() << endl << "Subtype as string: " << p.getSubTypeAsString() << endl; }); Packet* result = NULL; StringTable::stringCode resultStatus = StringTable::NOTOK; // by default m_nbrPackets++; int subType = p.getSubType(); DEBUG2( mc2dbg2 << "Packet subType : " << subType << "\n" ); switch (subType) { case Packet::PACKETTYPE_SEARCHEXPANDITEMREQUEST: { const SearchExpandItemRequestPacket* seirp = static_cast<const SearchExpandItemRequestPacket*>( &p ); result = handleSearchExpandItem(seirp); resultStatus = StringTable::stringCode(( static_cast<ReplyPacket*>(result))->getStatus()); break; } case Packet::PACKETTYPE_SEARCHREQUEST: { const SearchRequestPacket* srpack = static_cast<const SearchRequestPacket*>( &p ); result = handleSearchRequestPacket(srpack, packetInfo); resultStatus = StringTable::stringCode(( static_cast<ReplyPacket*>(result))->getStatus()); break; } default: { mc2log << error << "[SProc]: Unhandled packet of type " << subType << endl; resultStatus = StringTable::UNKNOWN; } } // switch if((dynamic_cast<ReplyPacket*>(result) != NULL) && (static_cast<ReplyPacket*>(result)->getStatus() == StringTable::MAPNOTFOUND)) { delete result; result = new AcknowledgeRequestReplyPacket( &p, StringTable::OK, ACKTIME_NOMAP ); } if (result == NULL) { mc2dbg2 << "Unknown subtype (or unhandled request) " << (int) p.getSubType() << endl; mc2dbg4 << "IP " << p.getOriginIP() << endl << "Port " << p.getOriginPort() << endl << "PacketID " << p.getPacketID() << endl << "RequestID " << p.getRequestID() << endl; } else { mc2dbg2 << "Returning packet to IP=" << result->getOriginIP() << ", port=" << result->getOriginPort() << endl ; } setAlarm(0); return result; } int SearchProcessor::getCurrentStatus() { return 0; }
33.054466
755
0.595439
[ "vector" ]
2920f1143fe070e2cfc2f4c0951adf728c658c48
2,621
cpp
C++
sw4534.cpp
sjnov11/SW-expert-academy
b7040017f2f8ff037aee40a5024284aaad1e50f9
[ "MIT" ]
1
2022-02-21T09:11:15.000Z
2022-02-21T09:11:15.000Z
sw4534.cpp
sjnov11/SW-expert-academy
b7040017f2f8ff037aee40a5024284aaad1e50f9
[ "MIT" ]
null
null
null
sw4534.cpp
sjnov11/SW-expert-academy
b7040017f2f8ff037aee40a5024284aaad1e50f9
[ "MIT" ]
1
2019-07-03T10:12:55.000Z
2019-07-03T10:12:55.000Z
#include <iostream> #include <vector> #include <stdlib.h> using namespace std; #define MOD 1000000007 long long cache[100000][2]; bool visited[100000] = {false, }; class Node { public: int val; int root; vector<Node*> children; Node(int v) { val = v; root = 1; } }; // white 0 black 1 long long totalCaseNum(Node* node, int color) { visited[node->val] = true; if (cache[node->val][color] > 0) return cache[node->val][color]; else { vector<Node*>::iterator child_it; long long ret = 1; if (color == 0) { long long val = 1; for (child_it = node->children.begin(); child_it != node->children.end(); ++child_it) { if (visited[(*child_it)->val]) { continue; } val = (val * ((totalCaseNum(*child_it, 0) + totalCaseNum(*child_it, 1)) % MOD)) % MOD; } cache[node->val][color] = val; } else if (color == 1) { long long val = 1; for (child_it = node->children.begin(); child_it != node->children.end(); ++child_it) { if (visited[(*child_it)->val]) { continue; } val = (val * (totalCaseNum(*child_it, 0) % MOD)) % MOD; } cache[node->val][color] = val; } visited[node->val] = false; return cache[node->val][color]; } } int main() { ios_base::sync_with_stdio(false); int T; cin >> T; for (int test_case = 1; test_case <= T; test_case++) { Node* node_list[100000]; int N; cin >> N; for (int i = 0; i < N; i++) { node_list[i] = new Node(i); } for (int i = 0; i < N - 1; i++) { int first, second; cin >> first >> second; Node* parent; Node* child; parent = node_list[first- 1]; child = node_list[second - 1]; parent->children.push_back(child); child->children.push_back(parent); } Node* root = node_list[0]; long long result = (totalCaseNum(root, 0) % MOD + totalCaseNum(root, 1) % MOD) %MOD; cout << "#" << test_case << " " << result << endl; for (int i = 0; i < N; i++) { free(node_list[i]); cache[i][0] = 0; cache[i][1] = 0; visited[i] = false; } } return 0; }
27.302083
120
0.446776
[ "vector" ]
2923bbc3e23d4b3f6b8e0323fc12e0f89e422ef8
19,985
cpp
C++
src/rest.cpp
moorecoin/MooreCoinMiningAlgorithm
fe6a153e1392f6e18110b1e69481aa5c3c8b4a1d
[ "MIT" ]
null
null
null
src/rest.cpp
moorecoin/MooreCoinMiningAlgorithm
fe6a153e1392f6e18110b1e69481aa5c3c8b4a1d
[ "MIT" ]
null
null
null
src/rest.cpp
moorecoin/MooreCoinMiningAlgorithm
fe6a153e1392f6e18110b1e69481aa5c3c8b4a1d
[ "MIT" ]
null
null
null
// copyright (c) 2009-2010 satoshi nakamoto // copyright (c) 2009-2014 the moorecoin core developers // distributed under the mit software license, see the accompanying // file copying or http://www.opensource.org/licenses/mit-license.php. #include "primitives/block.h" #include "primitives/transaction.h" #include "main.h" #include "rpcserver.h" #include "streams.h" #include "sync.h" #include "txmempool.h" #include "utilstrencodings.h" #include "version.h" #include <boost/algorithm/string.hpp> #include <boost/dynamic_bitset.hpp> #include "univalue/univalue.h" using namespace std; static const int max_getutxos_outpoints = 15; //allow a max of 15 outpoints to be queried at once enum retformat { rf_undef, rf_binary, rf_hex, rf_json, }; static const struct { enum retformat rf; const char* name; } rf_names[] = { {rf_undef, ""}, {rf_binary, "bin"}, {rf_hex, "hex"}, {rf_json, "json"}, }; struct ccoin { uint32_t ntxver; // don't call this nversion, that name has a special meaning inside implement_serialize uint32_t nheight; ctxout out; add_serialize_methods; template <typename stream, typename operation> inline void serializationop(stream& s, operation ser_action, int ntype, int nversion) { readwrite(ntxver); readwrite(nheight); readwrite(out); } }; class resterr { public: enum httpstatuscode status; string message; }; extern void txtojson(const ctransaction& tx, const uint256 hashblock, univalue& entry); extern univalue blocktojson(const cblock& block, const cblockindex* blockindex, bool txdetails = false); extern void scriptpubkeytojson(const cscript& scriptpubkey, univalue& out, bool fincludehex); static resterr resterr(enum httpstatuscode status, string message) { resterr re; re.status = status; re.message = message; return re; } static enum retformat parsedataformat(vector<string>& params, const string strreq) { boost::split(params, strreq, boost::is_any_of(".")); if (params.size() > 1) { for (unsigned int i = 0; i < arraylen(rf_names); i++) if (params[1] == rf_names[i].name) return rf_names[i].rf; } return rf_names[0].rf; } static string availabledataformatsstring() { string formats = ""; for (unsigned int i = 0; i < arraylen(rf_names); i++) if (strlen(rf_names[i].name) > 0) { formats.append("."); formats.append(rf_names[i].name); formats.append(", "); } if (formats.length() > 0) return formats.substr(0, formats.length() - 2); return formats; } static bool parsehashstr(const string& strreq, uint256& v) { if (!ishex(strreq) || (strreq.size() != 64)) return false; v.sethex(strreq); return true; } static bool rest_headers(acceptedconnection* conn, const std::string& struripart, const std::string& strrequest, const std::map<std::string, std::string>& mapheaders, bool frun) { vector<string> params; const retformat rf = parsedataformat(params, struripart); vector<string> path; boost::split(path, params[0], boost::is_any_of("/")); if (path.size() != 2) throw resterr(http_bad_request, "no header count specified. use /rest/headers/<count>/<hash>.<ext>."); long count = strtol(path[0].c_str(), null, 10); if (count < 1 || count > 2000) throw resterr(http_bad_request, "header count out of range: " + path[0]); string hashstr = path[1]; uint256 hash; if (!parsehashstr(hashstr, hash)) throw resterr(http_bad_request, "invalid hash: " + hashstr); std::vector<cblockheader> headers; headers.reserve(count); { lock(cs_main); blockmap::const_iterator it = mapblockindex.find(hash); const cblockindex *pindex = (it != mapblockindex.end()) ? it->second : null; while (pindex != null && chainactive.contains(pindex)) { headers.push_back(pindex->getblockheader()); if (headers.size() == (unsigned long)count) break; pindex = chainactive.next(pindex); } } cdatastream ssheader(ser_network, protocol_version); boost_foreach(const cblockheader &header, headers) { ssheader << header; } switch (rf) { case rf_binary: { string binaryheader = ssheader.str(); conn->stream() << httpreplyheader(http_ok, frun, binaryheader.size(), "application/octet-stream") << binaryheader << std::flush; return true; } case rf_hex: { string strhex = hexstr(ssheader.begin(), ssheader.end()) + "\n"; conn->stream() << httpreply(http_ok, strhex, frun, false, "text/plain") << std::flush; return true; } default: { throw resterr(http_not_found, "output format not found (available: .bin, .hex)"); } } // not reached return true; // continue to process further http reqs on this cxn } static bool rest_block(acceptedconnection* conn, const std::string& struripart, const std::string& strrequest, const std::map<std::string, std::string>& mapheaders, bool frun, bool showtxdetails) { vector<string> params; const retformat rf = parsedataformat(params, struripart); string hashstr = params[0]; uint256 hash; if (!parsehashstr(hashstr, hash)) throw resterr(http_bad_request, "invalid hash: " + hashstr); cblock block; cblockindex* pblockindex = null; { lock(cs_main); if (mapblockindex.count(hash) == 0) throw resterr(http_not_found, hashstr + " not found"); pblockindex = mapblockindex[hash]; if (fhavepruned && !(pblockindex->nstatus & block_have_data) && pblockindex->ntx > 0) throw resterr(http_not_found, hashstr + " not available (pruned data)"); if (!readblockfromdisk(block, pblockindex)) throw resterr(http_not_found, hashstr + " not found"); } cdatastream ssblock(ser_network, protocol_version); ssblock << block; switch (rf) { case rf_binary: { string binaryblock = ssblock.str(); conn->stream() << httpreplyheader(http_ok, frun, binaryblock.size(), "application/octet-stream") << binaryblock << std::flush; return true; } case rf_hex: { string strhex = hexstr(ssblock.begin(), ssblock.end()) + "\n"; conn->stream() << httpreply(http_ok, strhex, frun, false, "text/plain") << std::flush; return true; } case rf_json: { univalue objblock = blocktojson(block, pblockindex, showtxdetails); string strjson = objblock.write() + "\n"; conn->stream() << httpreply(http_ok, strjson, frun) << std::flush; return true; } default: { throw resterr(http_not_found, "output format not found (available: " + availabledataformatsstring() + ")"); } } // not reached return true; // continue to process further http reqs on this cxn } static bool rest_block_extended(acceptedconnection* conn, const std::string& struripart, const std::string& strrequest, const std::map<std::string, std::string>& mapheaders, bool frun) { return rest_block(conn, struripart, strrequest, mapheaders, frun, true); } static bool rest_block_notxdetails(acceptedconnection* conn, const std::string& struripart, const std::string& strrequest, const std::map<std::string, std::string>& mapheaders, bool frun) { return rest_block(conn, struripart, strrequest, mapheaders, frun, false); } static bool rest_chaininfo(acceptedconnection* conn, const std::string& struripart, const std::string& strrequest, const std::map<std::string, std::string>& mapheaders, bool frun) { vector<string> params; const retformat rf = parsedataformat(params, struripart); switch (rf) { case rf_json: { univalue rpcparams(univalue::varr); univalue chaininfoobject = getblockchaininfo(rpcparams, false); string strjson = chaininfoobject.write() + "\n"; conn->stream() << httpreply(http_ok, strjson, frun) << std::flush; return true; } default: { throw resterr(http_not_found, "output format not found (available: json)"); } } // not reached return true; // continue to process further http reqs on this cxn } static bool rest_tx(acceptedconnection* conn, const std::string& struripart, const std::string& strrequest, const std::map<std::string, std::string>& mapheaders, bool frun) { vector<string> params; const retformat rf = parsedataformat(params, struripart); string hashstr = params[0]; uint256 hash; if (!parsehashstr(hashstr, hash)) throw resterr(http_bad_request, "invalid hash: " + hashstr); ctransaction tx; uint256 hashblock = uint256(); if (!gettransaction(hash, tx, hashblock, true)) throw resterr(http_not_found, hashstr + " not found"); cdatastream sstx(ser_network, protocol_version); sstx << tx; switch (rf) { case rf_binary: { string binarytx = sstx.str(); conn->stream() << httpreplyheader(http_ok, frun, binarytx.size(), "application/octet-stream") << binarytx << std::flush; return true; } case rf_hex: { string strhex = hexstr(sstx.begin(), sstx.end()) + "\n"; conn->stream() << httpreply(http_ok, strhex, frun, false, "text/plain") << std::flush; return true; } case rf_json: { univalue objtx(univalue::vobj); txtojson(tx, hashblock, objtx); string strjson = objtx.write() + "\n"; conn->stream() << httpreply(http_ok, strjson, frun) << std::flush; return true; } default: { throw resterr(http_not_found, "output format not found (available: " + availabledataformatsstring() + ")"); } } // not reached return true; // continue to process further http reqs on this cxn } static bool rest_getutxos(acceptedconnection* conn, const std::string& struripart, const std::string& strrequest, const std::map<std::string, std::string>& mapheaders, bool frun) { vector<string> params; enum retformat rf = parsedataformat(params, struripart); vector<string> uriparts; if (params.size() > 0 && params[0].length() > 1) { std::string struriparams = params[0].substr(1); boost::split(uriparts, struriparams, boost::is_any_of("/")); } // throw exception in case of a empty request if (strrequest.length() == 0 && uriparts.size() == 0) throw resterr(http_internal_server_error, "error: empty request"); bool finputparsed = false; bool fcheckmempool = false; vector<coutpoint> voutpoints; // parse/deserialize input // input-format = output-format, rest/getutxos/bin requires binary input, gives binary output, ... if (uriparts.size() > 0) { //inputs is sent over uri scheme (/rest/getutxos/checkmempool/txid1-n/txid2-n/...) if (uriparts.size() > 0 && uriparts[0] == "checkmempool") fcheckmempool = true; for (size_t i = (fcheckmempool) ? 1 : 0; i < uriparts.size(); i++) { uint256 txid; int32_t noutput; std::string strtxid = uriparts[i].substr(0, uriparts[i].find("-")); std::string stroutput = uriparts[i].substr(uriparts[i].find("-")+1); if (!parseint32(stroutput, &noutput) || !ishex(strtxid)) throw resterr(http_internal_server_error, "parse error"); txid.sethex(strtxid); voutpoints.push_back(coutpoint(txid, (uint32_t)noutput)); } if (voutpoints.size() > 0) finputparsed = true; else throw resterr(http_internal_server_error, "error: empty request"); } string strrequestmutable = strrequest; //convert const string to string for allowing hex to bin converting switch (rf) { case rf_hex: { // convert hex to bin, continue then with bin part std::vector<unsigned char> strrequestv = parsehex(strrequest); strrequestmutable.assign(strrequestv.begin(), strrequestv.end()); } case rf_binary: { try { //deserialize only if user sent a request if (strrequestmutable.size() > 0) { if (finputparsed) //don't allow sending input over uri and http raw data throw resterr(http_internal_server_error, "combination of uri scheme inputs and raw post data is not allowed"); cdatastream oss(ser_network, protocol_version); oss << strrequestmutable; oss >> fcheckmempool; oss >> voutpoints; } } catch (const std::ios_base::failure& e) { // abort in case of unreadable binary data throw resterr(http_internal_server_error, "parse error"); } break; } case rf_json: { if (!finputparsed) throw resterr(http_internal_server_error, "error: empty request"); break; } default: { throw resterr(http_not_found, "output format not found (available: " + availabledataformatsstring() + ")"); } } // limit max outpoints if (voutpoints.size() > max_getutxos_outpoints) throw resterr(http_internal_server_error, strprintf("error: max outpoints exceeded (max: %d, tried: %d)", max_getutxos_outpoints, voutpoints.size())); // check spentness and form a bitmap (as well as a json capable human-readble string representation) vector<unsigned char> bitmap; vector<ccoin> outs; std::string bitmapstringrepresentation; boost::dynamic_bitset<unsigned char> hits(voutpoints.size()); { lock2(cs_main, mempool.cs); ccoinsview viewdummy; ccoinsviewcache view(&viewdummy); ccoinsviewcache& viewchain = *pcoinstip; ccoinsviewmempool viewmempool(&viewchain, mempool); if (fcheckmempool) view.setbackend(viewmempool); // switch cache backend to db+mempool in case user likes to query mempool for (size_t i = 0; i < voutpoints.size(); i++) { ccoins coins; uint256 hash = voutpoints[i].hash; if (view.getcoins(hash, coins)) { mempool.prunespent(hash, coins); if (coins.isavailable(voutpoints[i].n)) { hits[i] = true; // safe to index into vout here because isavailable checked if it's off the end of the array, or if // n is valid but points to an already spent output (isnull). ccoin coin; coin.ntxver = coins.nversion; coin.nheight = coins.nheight; coin.out = coins.vout.at(voutpoints[i].n); assert(!coin.out.isnull()); outs.push_back(coin); } } bitmapstringrepresentation.append(hits[i] ? "1" : "0"); // form a binary string representation (human-readable for json output) } } boost::to_block_range(hits, std::back_inserter(bitmap)); switch (rf) { case rf_binary: { // serialize data // use exact same output as mentioned in bip64 cdatastream ssgetutxoresponse(ser_network, protocol_version); ssgetutxoresponse << chainactive.height() << chainactive.tip()->getblockhash() << bitmap << outs; string ssgetutxoresponsestring = ssgetutxoresponse.str(); conn->stream() << httpreplyheader(http_ok, frun, ssgetutxoresponsestring.size(), "application/octet-stream") << ssgetutxoresponsestring << std::flush; return true; } case rf_hex: { cdatastream ssgetutxoresponse(ser_network, protocol_version); ssgetutxoresponse << chainactive.height() << chainactive.tip()->getblockhash() << bitmap << outs; string strhex = hexstr(ssgetutxoresponse.begin(), ssgetutxoresponse.end()) + "\n"; conn->stream() << httpreply(http_ok, strhex, frun, false, "text/plain") << std::flush; return true; } case rf_json: { univalue objgetutxoresponse(univalue::vobj); // pack in some essentials // use more or less the same output as mentioned in bip64 objgetutxoresponse.push_back(pair("chainheight", chainactive.height())); objgetutxoresponse.push_back(pair("chaintiphash", chainactive.tip()->getblockhash().gethex())); objgetutxoresponse.push_back(pair("bitmap", bitmapstringrepresentation)); univalue utxos(univalue::varr); boost_foreach (const ccoin& coin, outs) { univalue utxo(univalue::vobj); utxo.push_back(pair("txvers", (int32_t)coin.ntxver)); utxo.push_back(pair("height", (int32_t)coin.nheight)); utxo.push_back(pair("value", valuefromamount(coin.out.nvalue))); // include the script in a json output univalue o(univalue::vobj); scriptpubkeytojson(coin.out.scriptpubkey, o, true); utxo.push_back(pair("scriptpubkey", o)); utxos.push_back(utxo); } objgetutxoresponse.push_back(pair("utxos", utxos)); // return json string string strjson = objgetutxoresponse.write() + "\n"; conn->stream() << httpreply(http_ok, strjson, frun) << std::flush; return true; } default: { throw resterr(http_not_found, "output format not found (available: " + availabledataformatsstring() + ")"); } } // not reached return true; // continue to process further http reqs on this cxn } static const struct { const char* prefix; bool (*handler)(acceptedconnection* conn, const std::string& struripart, const std::string& strrequest, const std::map<std::string, std::string>& mapheaders, bool frun); } uri_prefixes[] = { {"/rest/tx/", rest_tx}, {"/rest/block/notxdetails/", rest_block_notxdetails}, {"/rest/block/", rest_block_extended}, {"/rest/chaininfo", rest_chaininfo}, {"/rest/headers/", rest_headers}, {"/rest/getutxos", rest_getutxos}, }; bool httpreq_rest(acceptedconnection* conn, const std::string& struri, const string& strrequest, const std::map<std::string, std::string>& mapheaders, bool frun) { try { std::string statusmessage; if (rpcisinwarmup(&statusmessage)) throw resterr(http_service_unavailable, "service temporarily unavailable: " + statusmessage); for (unsigned int i = 0; i < arraylen(uri_prefixes); i++) { unsigned int plen = strlen(uri_prefixes[i].prefix); if (struri.substr(0, plen) == uri_prefixes[i].prefix) { string struripart = struri.substr(plen); return uri_prefixes[i].handler(conn, struripart, strrequest, mapheaders, frun); } } } catch (const resterr& re) { conn->stream() << httpreply(re.status, re.message + "\r\n", false, false, "text/plain") << std::flush; return false; } conn->stream() << httperror(http_not_found, false) << std::flush; return false; }
34.817073
158
0.607105
[ "vector" ]
29243147f7c6032cc8b76e80f29975791f2ec4f7
4,835
cpp
C++
src/visualization/rviz_frame.cpp
mfkiwl/FLVIS
7472fef6fbc6cfc1e2c0de5dd1d0a7ae5462f689
[ "BSD-2-Clause" ]
113
2020-10-18T12:35:16.000Z
2022-03-29T06:08:49.000Z
src/visualization/rviz_frame.cpp
JazzyFeng/FLVIS-gpu
74dd8a136d1923592d2ca74d2408cc2c3bbb8c7b
[ "BSD-2-Clause" ]
9
2020-07-04T07:54:57.000Z
2022-02-17T06:37:33.000Z
src/visualization/rviz_frame.cpp
JazzyFeng/FLVIS-gpu
74dd8a136d1923592d2ca74d2408cc2c3bbb8c7b
[ "BSD-2-Clause" ]
29
2021-01-11T13:04:53.000Z
2022-03-29T06:08:50.000Z
#include "include/rviz_frame.h" RVIZFrame::RVIZFrame(ros::NodeHandle& nh, string poseTopicName, string frameIDPose, string ptsTopicName, string frameIDPts, int bufferPose, int bufferPts) { pose_pub = nh.advertise<geometry_msgs::PoseStamped>(poseTopicName, bufferPose); marker_pub = nh.advertise<visualization_msgs::Marker>(ptsTopicName, bufferPts); this->frame_id_pose = frameIDPose; this->frame_id_pts = frameIDPts; } RVIZFrame::~RVIZFrame(){} //Trsnformation world to camera [R|t] void RVIZFrame::pubFramePoseT_c_w(const SE3 T_c_w, const ros::Time stamp) { pubFramePoseT_w_c(T_c_w.inverse(),stamp); } //Trsnformation camera to world void RVIZFrame::pubFramePoseT_w_c(const SE3 T_w_c, const ros::Time stamp) { geometry_msgs::PoseStamped poseStamped; poseStamped.header.frame_id = frame_id_pose; poseStamped.header.stamp = stamp; Quaterniond q = T_w_c.so3().unit_quaternion(); Vec3 t = T_w_c.translation(); poseStamped.pose.orientation.w = q.w(); poseStamped.pose.orientation.x = q.x(); poseStamped.pose.orientation.y = q.y(); poseStamped.pose.orientation.z = q.z(); poseStamped.pose.position.x = t[0]; poseStamped.pose.position.y = t[1]; poseStamped.pose.position.z = t[2]; pose_pub.publish(poseStamped); } void RVIZFrame::pubFramePtsPoseT_c_w(const vector<Vec3> &pts3d, const SE3 T_c_w, const ros::Time stamp) { pubFramePtsPoseT_w_c(pts3d,T_c_w.inverse(),stamp); } void RVIZFrame::pubFramePtsPoseT_w_c(const vector<Vec3>& pts3d, const SE3 T_w_c, const ros::Time stamp) { pubFramePoseT_w_c(T_w_c); visualization_msgs::Marker points, line_list,camera_pyramid; points.header.frame_id = line_list.header.frame_id = camera_pyramid.header.frame_id = frame_id_pts; points.header.stamp = line_list.header.stamp = camera_pyramid.header.stamp = stamp; points.ns = line_list.ns = camera_pyramid.ns = "points_and_lines"; points.action = line_list.action = camera_pyramid.action = visualization_msgs::Marker::ADD; points.pose.orientation.w = line_list.pose.orientation.w = camera_pyramid.pose.orientation.w = 1.0; points.id = 0; line_list.id = 1; camera_pyramid.id=2; points.type = visualization_msgs::Marker::POINTS; line_list.type = visualization_msgs::Marker::LINE_LIST; camera_pyramid.type = visualization_msgs::Marker::LINE_LIST; // POINTS markers use x and y scale for width/height respectively // Points are blue points.scale.x = 0.05; points.scale.y = 0.05; points.color.b = 0.7f; points.color.a = 1.0; // LINE_LIST markers use only the x component of scale, for the line width // Line list is greed line_list.color.g = 0.8f; line_list.color.a = 1.0; line_list.scale.x = 0.005; // LINE_LIST markers use only the x component of scale, for the line width // Line list is greed camera_pyramid.color.r = 0.3f; camera_pyramid.color.b = 0.5f; camera_pyramid.color.a = 1.0; camera_pyramid.scale.x = 0.02; Vec3 t = T_w_c.translation(); geometry_msgs::Point camera_pos; camera_pos.x=t[0]; camera_pos.y=t[1]; camera_pos.z=t[2]; Vec3 pyramidPoint_c[4];//camera frame pyramidPoint_c[0] = Vec3(0.1,0.07,0.07); pyramidPoint_c[1] = Vec3(0.1,-0.07,0.07); pyramidPoint_c[2] = Vec3(-0.1,-0.07,0.07); pyramidPoint_c[3] = Vec3(-0.1,0.07,0.07); Vec3 pyramidPoint_w; geometry_msgs::Point pyramidPointDraw[4]; for(int i=0; i<4; i++) { pyramidPoint_w = T_w_c * pyramidPoint_c[i]; pyramidPointDraw[i].x=pyramidPoint_w[0]; pyramidPointDraw[i].y=pyramidPoint_w[1]; pyramidPointDraw[i].z=pyramidPoint_w[2]; camera_pyramid.points.push_back(camera_pos); camera_pyramid.points.push_back(pyramidPointDraw[i]); } camera_pyramid.points.push_back(pyramidPointDraw[0]); camera_pyramid.points.push_back(pyramidPointDraw[1]); camera_pyramid.points.push_back(pyramidPointDraw[1]); camera_pyramid.points.push_back(pyramidPointDraw[2]); camera_pyramid.points.push_back(pyramidPointDraw[2]); camera_pyramid.points.push_back(pyramidPointDraw[3]); camera_pyramid.points.push_back(pyramidPointDraw[3]); camera_pyramid.points.push_back(pyramidPointDraw[0]); // Create the vertices for the points and lines for (size_t i = 0; i <pts3d.size(); i++) { geometry_msgs::Point p; p.x = pts3d.at(i)[0]; p.y = pts3d.at(i)[1]; p.z = pts3d.at(i)[2]; points.points.push_back(p); line_list.points.push_back(camera_pos); line_list.points.push_back(p); } marker_pub.publish(points); marker_pub.publish(line_list); marker_pub.publish(camera_pyramid); }
33.344828
102
0.685832
[ "vector" ]
292af3f51b0d1f5472134a46e69314ee638038f9
12,948
cc
C++
kernel/cellaigs.cc
gudeh/yosys
9711e96c595224a0c0b539e09baf11a801ba20b2
[ "ISC" ]
1,718
2018-01-06T15:16:30.000Z
2022-03-30T17:44:22.000Z
kernel/cellaigs.cc
gudeh/yosys
9711e96c595224a0c0b539e09baf11a801ba20b2
[ "ISC" ]
1,669
2018-01-06T22:57:24.000Z
2022-03-31T06:51:49.000Z
kernel/cellaigs.cc
gudeh/yosys
9711e96c595224a0c0b539e09baf11a801ba20b2
[ "ISC" ]
569
2018-01-19T01:51:14.000Z
2022-03-31T23:03:09.000Z
/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/cellaigs.h" YOSYS_NAMESPACE_BEGIN AigNode::AigNode() { portbit = -1; inverter = false; left_parent = -1; right_parent = -1; } bool AigNode::operator==(const AigNode &other) const { if (portname != other.portname) return false; if (portbit != other.portbit) return false; if (inverter != other.inverter) return false; if (left_parent != other.left_parent) return false; if (right_parent != other.right_parent) return false; return true; } unsigned int AigNode::hash() const { unsigned int h = mkhash_init; h = mkhash(portname.hash(), portbit); h = mkhash(h, inverter); h = mkhash(h, left_parent); h = mkhash(h, right_parent); return h; } bool Aig::operator==(const Aig &other) const { return name == other.name; } unsigned int Aig::hash() const { return hash_ops<std::string>::hash(name); } struct AigMaker { Aig *aig; Cell *cell; idict<AigNode> aig_indices; int the_true_node; int the_false_node; AigMaker(Aig *aig, Cell *cell) : aig(aig), cell(cell) { the_true_node = -1; the_false_node = -1; } int node2index(const AigNode &node) { if (node.left_parent > node.right_parent) { AigNode n(node); std::swap(n.left_parent, n.right_parent); return node2index(n); } if (!aig_indices.count(node)) { aig_indices.expect(node, GetSize(aig->nodes)); aig->nodes.push_back(node); } return aig_indices.at(node); } int bool_node(bool value) { AigNode node; node.inverter = value; return node2index(node); } int inport(IdString portname, int portbit = 0, bool inverter = false) { if (portbit >= GetSize(cell->getPort(portname))) { if (cell->parameters.count(portname.str() + "_SIGNED") && cell->getParam(portname.str() + "_SIGNED").as_bool()) return inport(portname, GetSize(cell->getPort(portname))-1, inverter); return bool_node(inverter); } AigNode node; node.portname = portname; node.portbit = portbit; node.inverter = inverter; return node2index(node); } vector<int> inport_vec(IdString portname, int width) { vector<int> vec; for (int i = 0; i < width; i++) vec.push_back(inport(portname, i)); return vec; } int not_inport(IdString portname, int portbit = 0) { return inport(portname, portbit, true); } int not_gate(int A) { AigNode node(aig_indices[A]); node.outports.clear(); node.inverter = !node.inverter; return node2index(node); } int and_gate(int A, int B, bool inverter = false) { if (A == B) return inverter ? not_gate(A) : A; const AigNode &nA = aig_indices[A]; const AigNode &nB = aig_indices[B]; AigNode nB_inv(nB); nB_inv.inverter = !nB_inv.inverter; if (nA == nB_inv) return bool_node(inverter); bool nA_bool = nA.portbit < 0 && nA.left_parent < 0 && nA.right_parent < 0; bool nB_bool = nB.portbit < 0 && nB.left_parent < 0 && nB.right_parent < 0; if (nA_bool && nB_bool) { bool bA = nA.inverter; bool bB = nB.inverter; return bool_node(inverter != (bA && bB)); } if (nA_bool) { bool bA = nA.inverter; if (inverter) return bA ? not_gate(B) : bool_node(true); return bA ? B : bool_node(false); } if (nB_bool) { bool bB = nB.inverter; if (inverter) return bB ? not_gate(A) : bool_node(true); return bB ? A : bool_node(false); } AigNode node; node.inverter = inverter; node.left_parent = A; node.right_parent = B; return node2index(node); } int nand_gate(int A, int B) { return and_gate(A, B, true); } int or_gate(int A, int B) { return nand_gate(not_gate(A), not_gate(B)); } int nor_gate(int A, int B) { return and_gate(not_gate(A), not_gate(B)); } int xor_gate(int A, int B) { return nor_gate(and_gate(A, B), nor_gate(A, B)); } int xnor_gate(int A, int B) { return or_gate(and_gate(A, B), nor_gate(A, B)); } int andnot_gate(int A, int B) { return and_gate(A, not_gate(B)); } int ornot_gate(int A, int B) { return or_gate(A, not_gate(B)); } int mux_gate(int A, int B, int S) { return or_gate(and_gate(A, not_gate(S)), and_gate(B, S)); } vector<int> adder(const vector<int> &A, const vector<int> &B, int carry, vector<int> *X = nullptr, vector<int> *CO = nullptr) { vector<int> Y(GetSize(A)); log_assert(GetSize(A) == GetSize(B)); for (int i = 0; i < GetSize(A); i++) { Y[i] = xor_gate(xor_gate(A[i], B[i]), carry); carry = or_gate(and_gate(A[i], B[i]), and_gate(or_gate(A[i], B[i]), carry)); if (X != nullptr) X->at(i) = xor_gate(A[i], B[i]); if (CO != nullptr) CO->at(i) = carry; } return Y; } void outport(int node, IdString portname, int portbit = 0) { if (portbit < GetSize(cell->getPort(portname))) aig->nodes.at(node).outports.push_back(pair<IdString, int>(portname, portbit)); } void outport_bool(int node, IdString portname) { outport(node, portname); for (int i = 1; i < GetSize(cell->getPort(portname)); i++) outport(bool_node(false), portname, i); } void outport_vec(const vector<int> &vec, IdString portname) { for (int i = 0; i < GetSize(vec); i++) outport(vec.at(i), portname, i); } }; Aig::Aig(Cell *cell) { if (cell->type[0] != '$') return; AigMaker mk(this, cell); name = cell->type.str(); string mkname_last; bool mkname_a_signed = false; bool mkname_b_signed = false; bool mkname_is_signed = false; cell->parameters.sort(); for (auto p : cell->parameters) { if (p.first == ID::A_WIDTH && mkname_a_signed) { name = mkname_last + stringf(":%d%c", p.second.as_int(), mkname_is_signed ? 'S' : 'U'); } else if (p.first == ID::B_WIDTH && mkname_b_signed) { name = mkname_last + stringf(":%d%c", p.second.as_int(), mkname_is_signed ? 'S' : 'U'); } else { mkname_last = name; name += stringf(":%d", p.second.as_int()); } mkname_a_signed = false; mkname_b_signed = false; mkname_is_signed = false; if (p.first == ID::A_SIGNED) { mkname_a_signed = true; mkname_is_signed = p.second.as_bool(); } if (p.first == ID::B_SIGNED) { mkname_b_signed = true; mkname_is_signed = p.second.as_bool(); } } if (cell->type.in(ID($not), ID($_NOT_), ID($pos), ID($_BUF_))) { for (int i = 0; i < GetSize(cell->getPort(ID::Y)); i++) { int A = mk.inport(ID::A, i); int Y = cell->type.in(ID($not), ID($_NOT_)) ? mk.not_gate(A) : A; mk.outport(Y, ID::Y, i); } goto optimize; } if (cell->type.in(ID($and), ID($_AND_), ID($_NAND_), ID($or), ID($_OR_), ID($_NOR_), ID($xor), ID($xnor), ID($_XOR_), ID($_XNOR_), ID($_ANDNOT_), ID($_ORNOT_))) { for (int i = 0; i < GetSize(cell->getPort(ID::Y)); i++) { int A = mk.inport(ID::A, i); int B = mk.inport(ID::B, i); int Y = cell->type.in(ID($and), ID($_AND_)) ? mk.and_gate(A, B) : cell->type.in(ID($_NAND_)) ? mk.nand_gate(A, B) : cell->type.in(ID($or), ID($_OR_)) ? mk.or_gate(A, B) : cell->type.in(ID($_NOR_)) ? mk.nor_gate(A, B) : cell->type.in(ID($xor), ID($_XOR_)) ? mk.xor_gate(A, B) : cell->type.in(ID($xnor), ID($_XNOR_)) ? mk.xnor_gate(A, B) : cell->type.in(ID($_ANDNOT_)) ? mk.andnot_gate(A, B) : cell->type.in(ID($_ORNOT_)) ? mk.ornot_gate(A, B) : -1; mk.outport(Y, ID::Y, i); } goto optimize; } if (cell->type.in(ID($mux), ID($_MUX_))) { int S = mk.inport(ID::S); for (int i = 0; i < GetSize(cell->getPort(ID::Y)); i++) { int A = mk.inport(ID::A, i); int B = mk.inport(ID::B, i); int Y = mk.mux_gate(A, B, S); if (cell->type == ID($_NMUX_)) Y = mk.not_gate(Y); mk.outport(Y, ID::Y, i); } goto optimize; } if (cell->type.in(ID($reduce_and), ID($reduce_or), ID($reduce_xor), ID($reduce_xnor), ID($reduce_bool))) { int Y = mk.inport(ID::A, 0); for (int i = 1; i < GetSize(cell->getPort(ID::A)); i++) { int A = mk.inport(ID::A, i); if (cell->type == ID($reduce_and)) Y = mk.and_gate(A, Y); if (cell->type == ID($reduce_or)) Y = mk.or_gate(A, Y); if (cell->type == ID($reduce_bool)) Y = mk.or_gate(A, Y); if (cell->type == ID($reduce_xor)) Y = mk.xor_gate(A, Y); if (cell->type == ID($reduce_xnor)) Y = mk.xor_gate(A, Y); } if (cell->type == ID($reduce_xnor)) Y = mk.not_gate(Y); mk.outport(Y, ID::Y, 0); for (int i = 1; i < GetSize(cell->getPort(ID::Y)); i++) mk.outport(mk.bool_node(false), ID::Y, i); goto optimize; } if (cell->type.in(ID($logic_not), ID($logic_and), ID($logic_or))) { int A = mk.inport(ID::A, 0), Y = -1; for (int i = 1; i < GetSize(cell->getPort(ID::A)); i++) A = mk.or_gate(mk.inport(ID::A, i), A); if (cell->type.in(ID($logic_and), ID($logic_or))) { int B = mk.inport(ID::B, 0); for (int i = 1; i < GetSize(cell->getPort(ID::B)); i++) B = mk.or_gate(mk.inport(ID::B, i), B); if (cell->type == ID($logic_and)) Y = mk.and_gate(A, B); if (cell->type == ID($logic_or)) Y = mk.or_gate(A, B); } else { if (cell->type == ID($logic_not)) Y = mk.not_gate(A); } mk.outport_bool(Y, ID::Y); goto optimize; } if (cell->type.in(ID($add), ID($sub))) { int width = GetSize(cell->getPort(ID::Y)); vector<int> A = mk.inport_vec(ID::A, width); vector<int> B = mk.inport_vec(ID::B, width); int carry = mk.bool_node(false); if (cell->type == ID($sub)) { for (auto &n : B) n = mk.not_gate(n); carry = mk.not_gate(carry); } vector<int> Y = mk.adder(A, B, carry); mk.outport_vec(Y, ID::Y); goto optimize; } if (cell->type == ID($alu)) { int width = GetSize(cell->getPort(ID::Y)); vector<int> A = mk.inport_vec(ID::A, width); vector<int> B = mk.inport_vec(ID::B, width); int carry = mk.inport(ID::CI); int binv = mk.inport(ID::BI); for (auto &n : B) n = mk.xor_gate(n, binv); vector<int> X(width), CO(width); vector<int> Y = mk.adder(A, B, carry, &X, &CO); for (int i = 0; i < width; i++) X[i] = mk.xor_gate(A[i], B[i]); mk.outport_vec(Y, ID::Y); mk.outport_vec(X, ID::X); mk.outport_vec(CO, ID::CO); goto optimize; } if (cell->type.in(ID($eq), ID($ne))) { int width = max(GetSize(cell->getPort(ID::A)), GetSize(cell->getPort(ID::B))); vector<int> A = mk.inport_vec(ID::A, width); vector<int> B = mk.inport_vec(ID::B, width); int Y = mk.bool_node(false); for (int i = 0; i < width; i++) Y = mk.or_gate(Y, mk.xor_gate(A[i], B[i])); if (cell->type == ID($eq)) Y = mk.not_gate(Y); mk.outport_bool(Y, ID::Y); goto optimize; } if (cell->type == ID($_AOI3_)) { int A = mk.inport(ID::A); int B = mk.inport(ID::B); int C = mk.inport(ID::C); int Y = mk.nor_gate(mk.and_gate(A, B), C); mk.outport(Y, ID::Y); goto optimize; } if (cell->type == ID($_OAI3_)) { int A = mk.inport(ID::A); int B = mk.inport(ID::B); int C = mk.inport(ID::C); int Y = mk.nand_gate(mk.or_gate(A, B), C); mk.outport(Y, ID::Y); goto optimize; } if (cell->type == ID($_AOI4_)) { int A = mk.inport(ID::A); int B = mk.inport(ID::B); int C = mk.inport(ID::C); int D = mk.inport(ID::D); int Y = mk.nor_gate(mk.and_gate(A, B), mk.and_gate(C, D)); mk.outport(Y, ID::Y); goto optimize; } if (cell->type == ID($_OAI4_)) { int A = mk.inport(ID::A); int B = mk.inport(ID::B); int C = mk.inport(ID::C); int D = mk.inport(ID::D); int Y = mk.nand_gate(mk.or_gate(A, B), mk.or_gate(C, D)); mk.outport(Y, ID::Y); goto optimize; } name.clear(); return; optimize:; pool<int> used_old_ids; vector<AigNode> new_nodes; dict<int, int> old_to_new_ids; old_to_new_ids[-1] = -1; for (int i = GetSize(nodes)-1; i >= 0; i--) { if (!nodes[i].outports.empty()) used_old_ids.insert(i); if (!used_old_ids.count(i)) continue; if (nodes[i].left_parent >= 0) used_old_ids.insert(nodes[i].left_parent); if (nodes[i].right_parent >= 0) used_old_ids.insert(nodes[i].right_parent); } for (int i = 0; i < GetSize(nodes); i++) { if (!used_old_ids.count(i)) continue; nodes[i].left_parent = old_to_new_ids.at(nodes[i].left_parent); nodes[i].right_parent = old_to_new_ids.at(nodes[i].right_parent); old_to_new_ids[i] = GetSize(new_nodes); new_nodes.push_back(nodes[i]); } new_nodes.swap(nodes); } YOSYS_NAMESPACE_END
26.104839
161
0.615462
[ "vector" ]
292d48755f59e0b2b432a6b3d29e32db63914ff7
5,209
cc
C++
test/timetable/departure_table.cc
mapbox/nepomuk
8771482edb9b16bb0f5a152c15681c57eb3bb6b6
[ "MIT" ]
22
2017-05-12T11:52:26.000Z
2021-12-06T06:05:08.000Z
test/timetable/departure_table.cc
mapbox/nepomuk
8771482edb9b16bb0f5a152c15681c57eb3bb6b6
[ "MIT" ]
49
2017-05-11T16:13:58.000Z
2017-12-13T11:19:17.000Z
test/timetable/departure_table.cc
mapbox/nepomuk
8771482edb9b16bb0f5a152c15681c57eb3bb6b6
[ "MIT" ]
7
2017-11-19T12:04:26.000Z
2021-12-06T06:14:25.000Z
#include "timetable/departure_table.hpp" #include "timetable/departure_table_factory.hpp" #include "timetable/exceptions.hpp" #include "date/time.hpp" #include "gtfs/frequency.hpp" #include "gtfs/stop.hpp" #include "id/sequence.hpp" #include "id/stop.hpp" #include "id/trip.hpp" #include <algorithm> #include <boost/optional.hpp> using namespace nepomuk::timetable; using namespace nepomuk; using namespace nepomuk::gtfs; using namespace nepomuk::date; // make sure we get a new main function here #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_CASE(check_input_validity_and_parsing) { // cannot use empty vectors std::vector<Frequency> data; BOOST_CHECK_THROW(DepartureTableFactory::produce(data.begin(), data.end()), InvalidInputError); // hourly trips between 0:00 and 6:00 data.push_back({TripID{0}, Time{"00:00:00"}, Time{"06:00:00"}, 3600, boost::none}); // every 5 minutes until 10:00 data.push_back({TripID{0}, Time{"06:00:00"}, Time{"10:00:00"}, 300, boost::none}); // every 10 minutes between 10:00 and 16:00 data.push_back({TripID{0}, Time{"10:00:00"}, Time{"16:00:00"}, 600, boost::none}); // every 30 minutes from 16:00 to 24:00 data.push_back({TripID{0}, Time{"16:00:00"}, Time{"24:00:00"}, 1800, boost::none}); data.push_back({TripID{1}, Time{"00:00:00"}, Time{"06:00:00"}, 1800, boost::none}); // every 10 minutes for most of the day data.push_back({TripID{1}, Time{"06:00:00"}, Time{"16:00:00"}, 600, boost::none}); // every 30 minutes from 16:00 to 24:00 data.push_back({TripID{1}, Time{"16:00:00"}, Time{"24:00:00"}, 1800, boost::none}); BOOST_CHECK_THROW(DepartureTableFactory::produce(data.begin(), data.end()), InvalidInputError); const auto first_table = DepartureTableFactory::produce(data.begin(), data.begin() + 4); const auto second_table = DepartureTableFactory::produce(data.begin() + 4, data.end()); { auto reachable_departures = first_table.list(Time("06:00:00")); BOOST_CHECK_EQUAL(std::distance(reachable_departures.begin(), reachable_departures.end()), 3ll); } { auto reachable_departures = first_table.list(Time("05:00:00")); BOOST_CHECK_EQUAL(std::distance(reachable_departures.begin(), reachable_departures.end()), 4ll); } { // missing the "5:00:00" train by a second auto reachable_departures = first_table.list(Time("05:00:01")); BOOST_CHECK_EQUAL(std::distance(reachable_departures.begin(), reachable_departures.end()), 3ll); } } BOOST_AUTO_TEST_CASE(test_departure) { Departure frequency_departure = {Time{"10:00:00"}, Time{"16:00:00"}, 600, 0ull}; BOOST_CHECK_EQUAL(frequency_departure.get_next_departure(Time("00:01:23")), Time("10:00:00")); BOOST_CHECK_EQUAL(frequency_departure.get_next_departure(Time("10:00:00")), Time("10:00:00")); BOOST_CHECK_EQUAL(frequency_departure.get_next_departure(Time("10:00:01")), Time("10:10:00")); BOOST_CHECK_EQUAL(frequency_departure.get_next_departure(Time("10:10:01")), Time("10:20:00")); BOOST_CHECK_EQUAL(frequency_departure.get_next_departure(Time("10:10:00")), Time("10:10:00")); } BOOST_AUTO_TEST_CASE(construct_from_stops) { std::vector<StopTime> data; BOOST_CHECK_THROW(DepartureTableFactory::produce(data.begin(), data.end()), InvalidInputError); StopTime first = {TripID{0}, Time("00:10:00"), Time("00:10:00"), StopID{0}, SequenceID{0}, boost::none, boost::none, boost::none, boost::none, boost::none}; StopTime second = {TripID{0}, Time("00:15:00"), Time("00:15:00"), StopID{1}, SequenceID{1}, boost::none, boost::none, boost::none, boost::none, boost::none}; StopTime second_invalid_trip = {TripID{1}, Time("00:15:00"), Time("00:15:00"), StopID{1}, SequenceID{1}, boost::none, boost::none, boost::none, boost::none, boost::none}; data.push_back(first); data.push_back(second); data.push_back(second_invalid_trip); BOOST_CHECK_THROW(DepartureTableFactory::produce(data.begin(), data.end()), InvalidInputError); data.pop_back(); const auto table = DepartureTableFactory::produce(data.begin(), data.end()); Time time("00:02:23"); const auto departure = table.list(time); BOOST_CHECK(std::distance(departure.begin(), departure.end()) == 1); BOOST_CHECK_EQUAL(departure.begin()->get_next_departure(time), Time("00:10:00")); }
39.763359
99
0.588405
[ "vector" ]
292e3600fe1c52d13055a196660282a62449712a
7,684
hpp
C++
library/include/rocwmma/internal/mapping_util.hpp
dlangbe/rocWMMA
8dd5c1cd4de202e556e338223e17071daac65987
[ "MIT" ]
null
null
null
library/include/rocwmma/internal/mapping_util.hpp
dlangbe/rocWMMA
8dd5c1cd4de202e556e338223e17071daac65987
[ "MIT" ]
null
null
null
library/include/rocwmma/internal/mapping_util.hpp
dlangbe/rocWMMA
8dd5c1cd4de202e556e338223e17071daac65987
[ "MIT" ]
null
null
null
/******************************************************************************* * * MIT License * * Copyright 2021-2022 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * *******************************************************************************/ #ifndef ROCWMMA_MAPPING_UTIL_HPP #define ROCWMMA_MAPPING_UTIL_HPP #include <utility> namespace rocwmma { // 2D Coordinate using Coord2d = std::pair<uint32_t, uint32_t>; // Fwd declaration struct row_major; struct col_major; namespace detail { struct WaveSpace { using WaveCoordT = Coord2d; using WorkgroupCoordT = Coord2d; using WorkgroupDimT = Coord2d; // Current lane normalized to [0, 63]. __device__ static inline uint32_t localLaneId(); // Local wave coordinate relative to current workgroup. __device__ constexpr static inline WaveCoordT localWaveCoord(); // Global wave grid coordinate relative to all workgroups. __device__ static inline WaveCoordT globalWaveCoord(); // Global workgroup Id __device__ constexpr static inline WorkgroupCoordT workgroupCoord(); // Size of workgroup, normalized to wave count. __device__ constexpr static inline WorkgroupDimT workgroupDim(); }; /* Matrix coordinate space is analogous to global block space scaled by BlockM and BlockN. */ template <uint32_t BlockHeight, uint32_t BlockWidth> struct MatrixSpace { using MatrixCoordT = Coord2d; using BlockCoordT = Coord2d; // Global matrix coordinate space (row, col) transform for a given block grid coordinate. __device__ static inline MatrixCoordT fromBlockCoord(BlockCoordT const& blockCoord); }; /* Calculate the memory offsets and addresses for a given matrix coordinate or block coordinate. */ template <typename DataOrientation> struct DataSpace { using MatrixCoordT = Coord2d; using MatrixSizeT = Coord2d; enum : uint32_t { MajorIndex = std::is_same<DataOrientation, row_major>::value ? 0 : 1, MinorIndex = std::is_same<DataOrientation, row_major>::value ? 1 : 0 }; // Determine the leading dimension of a matrix. __device__ constexpr static inline auto leadingDim(MatrixSizeT const& matrixSize); // Global data coordinate space (1d element) transform for a matrix coordinate. __device__ constexpr static inline auto fromMatrixCoord(MatrixCoordT const& matrixCoord, uint32_t leadingDim); }; template <> struct DataSpace<void>; } // namespace detail; /* This mapping utility is intended to map from workgroup configuration into functional wave units. Depending on how the workgroup threads are grouped, threads are mapped to their work differently, so it is best to assume a particular configuration. ***Important assumption: *** This particular mapping assumes that the major dimension for threadcount is in the blockDim.x element. This means that blockSize.x threadcounts are multiples of 64, and blockSize.y threadcounts are in multiples of 1. blockDim = (waveRows * 64, waveCols). Wave rows and cols map directly to scaled matrix rows and cols for processing. *** E.g. BlockDim of (64, 1) will give a grid of (1, 1) waves, or 1 total wave in the workgroup. localWaveId of (1, 1) is the wave corresponding to threads ([0 - 63], 1) in the workgroup. E.g. BlockDim of (256, 4) will give a grid of (4, 4) waves, or 16 total waves in the workgroup. localWaveId of (2, 3) is the wave corresponding to threads ([128 - 191], 3) in the workgroup. */ template <uint32_t BlockHeight, uint32_t BlockWidth, typename DataT, typename DataLayout> struct MappingUtil { using WaveSpace = detail::WaveSpace; using MatrixSpace = detail::MatrixSpace<BlockHeight, BlockWidth>; using DataSpace = detail::DataSpace<DataLayout>; using WaveCoordT = typename WaveSpace::WaveCoordT; using BlockCoordT = typename MatrixSpace::BlockCoordT; using MatrixCoordT = typename MatrixSpace::MatrixCoordT; using WorkgroupDimT = typename WaveSpace::WorkgroupDimT; /// Current wave perspective // Current lane of current wave __device__ static inline uint32_t laneId(); // Local wave coordinate relative to workgroup __device__ static inline WaveCoordT waveCoord(); // Global block (grid) coordinate of current wave __device__ static inline BlockCoordT blockCoord(); // Matrix coordinate of current wave __device__ static inline MatrixCoordT matrixCoord(); // Data address of current wave __device__ static inline DataT const* dataCoord(DataT const* baseAddr, uint32_t ldm); __device__ static inline DataT* dataCoord(DataT* baseAddr, uint32_t ldm); /// Current workgroup perspective __device__ static inline WorkgroupDimT workgroupDim(); /// Coordinate override helpers // Current global wave coordinate with row override __device__ static inline BlockCoordT blockCoordM(uint32_t m); // Current global wave coordinate with col override __device__ static inline BlockCoordT blockCoordN(uint32_t n); // Matrix coordinate of current wave with row override __device__ static inline MatrixCoordT matrixCoordM(uint32_t m); // Matrix coordinate of current wave with col override __device__ static inline MatrixCoordT matrixCoordN(uint32_t n); /// Conversion helpers // Convert from any block coord to matrix coord __device__ static inline MatrixCoordT matrixCoord(BlockCoordT const& blockCoord); // Convert from any matrix coord to data offset __device__ static inline uint32_t dataOffset(MatrixCoordT const& matrixCoord, uint32_t ldm); // Convert from any matrix coord to data address __device__ static inline DataT const* dataCoord(DataT const* baseAddr, MatrixCoordT const& matrixCoord, uint32_t ldm); __device__ static inline DataT* dataCoord(DataT* baseAddr, MatrixCoordT const& matrixCoord, uint32_t ldm); }; } // namespace rocwmma #include "mapping_util_impl.hpp" #endif // ROCWMMA_MAPPING_UTIL_HPP
37.666667
101
0.671265
[ "transform" ]
292f079e3314ed9de9226f0a3bb72d685ba6f6ab
993
cpp
C++
permutation_in_a_string.cpp
shafitek/ArXives
67170d6bde2093703d9cd3e8efa55b61e7b5ea75
[ "MIT" ]
null
null
null
permutation_in_a_string.cpp
shafitek/ArXives
67170d6bde2093703d9cd3e8efa55b61e7b5ea75
[ "MIT" ]
null
null
null
permutation_in_a_string.cpp
shafitek/ArXives
67170d6bde2093703d9cd3e8efa55b61e7b5ea75
[ "MIT" ]
null
null
null
// https://leetcode.com/problems/permutation-in-string/ class Solution { public: bool checkInclusion(string s1, string s2) { size_t len1 = s1.length(); size_t len2 = s2.length(); if (len1 > len2) return false; int window_size = len1; int total_stride = len2 - len1 + 1; vector<int> h_map(26,0); for(int i = 0; i < len1; i++) h_map[s1[i]-'a']++; int k = 0; unsigned int permNum; vector<int> tmp_arr(26,0); while(k < total_stride){ fill(tmp_arr.begin(), tmp_arr.end(), 0); permNum = 0; for(int i = 0; i < len1; i++) tmp_arr[s2[k+i]-'a']++; k++; for (int i = 0; i < 26; i++) { if(h_map[i] != tmp_arr[i]) break; permNum++; } if (permNum == tmp_arr.size()) return true; } return false; } };
27.583333
65
0.441088
[ "vector" ]
2934a33c786bae3ea78b0af617e830b49015079a
2,300
cc
C++
poj/1/1472.cc
eagletmt/procon
adbe503eb3c1bbcc1538b2ee8988aa353937e8d4
[ "MIT" ]
1
2015-04-17T09:54:23.000Z
2015-04-17T09:54:23.000Z
poj/1/1472.cc
eagletmt/procon
adbe503eb3c1bbcc1538b2ee8988aa353937e8d4
[ "MIT" ]
null
null
null
poj/1/1472.cc
eagletmt/procon
adbe503eb3c1bbcc1538b2ee8988aa353937e8d4
[ "MIT" ]
null
null
null
#include <iostream> #include <sstream> #include <vector> #include <algorithm> using namespace std; struct poly { int cs[15]; poly() { fill_n(cs, 15, 0); } poly& operator+=(const poly& p) { for (int i = 0; i <= 10; i++) { cs[i] += p.cs[i]; } return *this; } poly operator*(const poly& p) const { poly ans; for (int i = 0; i <= 10; i++) { for (int j = 0; i+j <= 10; j++) { ans.cs[i+j] += cs[i] * p.cs[j]; } } return ans; } }; ostream& operator<<(ostream& os, const poly& p) { bool first = true; for (int i = 10; i >= 0; i--) { if (p.cs[i] != 0) { if (!first) { os << '+'; } if (p.cs[i] == 1 && i != 0) { } else { os << p.cs[i]; if (i != 0) { os << "*"; } } if (i != 0) { os << "n"; if (i != 1) { os << "^" << i; } } first = false; } } if (first) { os << 0; } return os; } typedef vector<string>::const_iterator Iterator; int read(const string& s) { istringstream iss(s); int n; iss >> n; return n; } poly statements(Iterator& it); poly statement(Iterator& it) { if (*it == "OP") { ++it; poly p; p.cs[0] = read(*it); ++it; return p; } else if (*it == "LOOP") { ++it; const string s = *it; ++it; poly p; if (s == "n") { p.cs[1] = 1; } else { p.cs[0] = read(s); } const poly q = statements(it); if (*it != "END") { throw "statement-loop"; } ++it; const poly ans = p * q; return ans; } else { throw "statement"; } } poly statements(Iterator& it) { poly p; p.cs[0] = 0; while (*it == "LOOP" || *it == "OP") { p += statement(it); } return p; } poly program(Iterator& it) { if (*it != "BEGIN") { throw "program-begin"; } ++it; const poly p = statements(it); if (*it != "END") { throw "program-end"; } ++it; return p; } int main() { int T; cin >> T; vector<string> tokens; for (string tok; cin >> tok;) { tokens.push_back(tok); } Iterator it = tokens.begin(); for (int Ti = 1; Ti <= T; Ti++) { cout << "Program #" << Ti << endl; const poly p = program(it); cout << "Runtime = " << p << endl; cout << endl; } return 0; }
16.911765
49
0.452609
[ "vector" ]
a097baa00aab91e7993dc1183945bd4fd4857d50
1,317
hpp
C++
fawnds/cindex/twolevel_absoff_bucketing.hpp
ByteHamster/silt
9970432b27db7b9ef3f23f56cdd0609183e9fd83
[ "Apache-2.0" ]
134
2015-02-02T21:32:16.000Z
2022-01-27T06:03:22.000Z
fawnds/cindex/twolevel_absoff_bucketing.hpp
theopengroup/silt
9970432b27db7b9ef3f23f56cdd0609183e9fd83
[ "Apache-2.0" ]
null
null
null
fawnds/cindex/twolevel_absoff_bucketing.hpp
theopengroup/silt
9970432b27db7b9ef3f23f56cdd0609183e9fd83
[ "Apache-2.0" ]
43
2015-01-02T03:12:34.000Z
2021-12-17T09:19:28.000Z
#pragma once #include "common.hpp" #include <vector> #include <boost/array.hpp> namespace cindex { template<typename ValueType = uint16_t, typename UpperValueType = uint32_t> class twolevel_absoff_bucketing { public: typedef ValueType value_type; typedef UpperValueType upper_value_type; public: twolevel_absoff_bucketing(std::size_t size = 0, std::size_t keys_per_bucket = 1, std::size_t keys_per_block = 1); void resize(std::size_t size, std::size_t keys_per_bucket, std::size_t keys_per_block); void insert(const std::size_t& index_offset, const std::size_t& dest_offset); void finalize() {} std::size_t index_offset(std::size_t i) const CINDEX_WARN_UNUSED_RESULT; std::size_t dest_offset(std::size_t i) const CINDEX_WARN_UNUSED_RESULT; std::size_t size() const CINDEX_WARN_UNUSED_RESULT; std::size_t bit_size() const CINDEX_WARN_UNUSED_RESULT; protected: std::size_t upper_index_offset(std::size_t i) const CINDEX_WARN_UNUSED_RESULT; std::size_t upper_dest_offset(std::size_t i) const CINDEX_WARN_UNUSED_RESULT; private: std::size_t size_; std::size_t keys_per_bucket_; std::size_t upper_bucket_size_; std::vector<boost::array<value_type, 2> > bucket_info_; std::vector<boost::array<upper_value_type, 2> > upper_bucket_info_; std::size_t current_i_; }; }
27.4375
115
0.769932
[ "vector" ]
a09a22521a67603d5d893b93a649a7a18ca35820
5,418
cpp
C++
logdevice/server/RecordCachePersistence.cpp
majra20/LogDevice
dea0df7991120d567354d7a29d832b0e10be7477
[ "BSD-3-Clause" ]
1,831
2018-09-12T15:41:52.000Z
2022-01-05T02:38:03.000Z
logdevice/server/RecordCachePersistence.cpp
majra20/LogDevice
dea0df7991120d567354d7a29d832b0e10be7477
[ "BSD-3-Clause" ]
183
2018-09-12T16:14:59.000Z
2021-12-07T15:49:43.000Z
logdevice/server/RecordCachePersistence.cpp
majra20/LogDevice
dea0df7991120d567354d7a29d832b0e10be7477
[ "BSD-3-Clause" ]
228
2018-09-12T15:41:51.000Z
2022-01-05T08:12:09.000Z
/** * Copyright (c) 2017-present, Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include "logdevice/server/RecordCachePersistence.h" #include "logdevice/common/Worker.h" #include "logdevice/server/RecordCache.h" #include "logdevice/server/ServerProcessor.h" #include "logdevice/server/read_path/LogStorageStateMap.h" #include "logdevice/server/storage_tasks/ExecStorageThread.h" #include "logdevice/server/storage_tasks/ShardedStorageThreadPool.h" #include "logdevice/server/storage_tasks/StorageThreadPool.h" namespace facebook { namespace logdevice { namespace RecordCachePersistence { // Write in batches of 10Mib static const size_t SNAPSHOT_BATCH_SIZE_LIMIT = 10 * 1024 * 1024; void persistRecordCaches(shard_index_t shard_idx, StorageThreadPool* storage_thread_pool) { LocalLogStore& shard = storage_thread_pool->getLocalLogStore(); LogStorageStateMap& log_storage_state_map = storage_thread_pool->getProcessor().getLogStorageStateMap(); ShardedStorageThreadPool* sharded_store = storage_thread_pool->getProcessor().sharded_storage_thread_pool_; Status accepting = shard.acceptingWrites(); if (accepting != Status::OK && accepting != Status::LOW_ON_SPC) { ld_info("Shard %d not accepting writes, skipping RecordCache persistence", shard_idx); return; } ld_check(shard.getShardIdx() == shard_idx); ld_check(sharded_store->numShards() > 0); const size_t bytes_limit_per_shard = storage_thread_pool->getProcessor().settings()->record_cache_max_size / sharded_store->numShards(); // Keep owners of RecordCache blobs in memory so contents aren't freed std::vector<std::unique_ptr<uint8_t[]>> record_cache_snapshot_owners; std::vector<std::pair<logid_t, Slice>> record_cache_snapshot_batch; size_t logs_in_current_batch = 0; size_t total_persisted_logs = 0; size_t bytes_in_current_batch = 0; size_t total_bytes = 0; auto commit_batch = [&]() -> int { int rv = shard.writeLogSnapshotBlobs( LocalLogStore::LogSnapshotBlobType::RECORD_CACHE, record_cache_snapshot_batch); if (rv != 0) { ld_error("Failed to write a batch of log snapshot blobs to shard " "%d: %s. Written in previous batches: %ju logs, totaling %ju " "bytes", shard_idx, error_name(err), total_persisted_logs, total_bytes); } else { total_bytes += bytes_in_current_batch; total_persisted_logs += logs_in_current_batch; } bytes_in_current_batch = logs_in_current_batch = 0; record_cache_snapshot_batch.clear(); record_cache_snapshot_owners.clear(); return rv; }; // A callback function called for each log, which will write batches of // serialized representations of record caches to disk. auto callback = [&](logid_t log_id, const LogStorageState& state) { // Serialize the record cache RecordCache* record_cache = state.record_cache_.get(); if (!record_cache) { return 0; } ssize_t size = record_cache->sizeInLinearBuffer(); if (size == -1) { ld_error("Failed to calculate size of RecordCache in linear buffer on " "shard %d", shard_idx); return -1; } if (bytes_limit_per_shard > 0 && total_bytes + bytes_in_current_batch + size >= bytes_limit_per_shard) { // the snapshot is about to exceed the byte limit, commit the current // batch and abort the operation commit_batch(); ld_error("Snapshot of record cache on shard %d reached the byte limit of " "%lu bytes per-shard. Already persisted %lu, current batch %lu. " "Stop persisting record caches on this shard.", shard_idx, bytes_limit_per_shard, total_bytes, bytes_in_current_batch); return -1; } auto buffer = std::make_unique<uint8_t[]>(size); ssize_t linear_size = record_cache->toLinearBuffer( reinterpret_cast<char*>(buffer.get()), size); if (linear_size == -1) { ld_error("Failed to linearize RecordCache on shard %d", shard_idx); return -1; } ld_check(size == linear_size); // Add serialized representation to batch. If the batch's size now exceeds // the batch limit, write it and start a new one. // TODO 12730327: make code cleaner without sharing states between two // lambdas bytes_in_current_batch += linear_size; logs_in_current_batch++; record_cache_snapshot_batch.emplace_back( log_id, Slice(buffer.get(), linear_size)); record_cache_snapshot_owners.push_back(std::move(buffer)); if (bytes_in_current_batch >= SNAPSHOT_BATCH_SIZE_LIMIT) { return commit_batch(); } return 0; }; // Run above lambda for each log int rv = log_storage_state_map.forEachLogOnShard(shard_idx, callback); // Write the last batch, unless we've previously encountered an error if (rv == 0) { commit_batch(); } ld_info("Persisted record caches for %ju logs on shard %d, totaling %ju " "bytes.", total_persisted_logs, shard_idx, total_bytes); } }}} // namespace facebook::logdevice::RecordCachePersistence
37.109589
80
0.689553
[ "vector" ]
a0a09c9a50aa8e0e79b28a34db66950ec4e10c66
17,400
cpp
C++
toonz/sources/common/trop/traylit.cpp
wofogen/tahoma2d
ce5a89a7b1027b2c1769accb91184a2ee6442b4d
[ "BSD-3-Clause" ]
3,710
2016-03-26T00:40:48.000Z
2022-03-31T21:35:12.000Z
toonz/sources/common/trop/traylit.cpp
wofogen/tahoma2d
ce5a89a7b1027b2c1769accb91184a2ee6442b4d
[ "BSD-3-Clause" ]
4,246
2016-03-26T01:21:45.000Z
2022-03-31T23:10:47.000Z
toonz/sources/common/trop/traylit.cpp
wofogen/tahoma2d
ce5a89a7b1027b2c1769accb91184a2ee6442b4d
[ "BSD-3-Clause" ]
633
2016-03-26T00:42:25.000Z
2022-03-17T02:55:13.000Z
#include "traster.h" #include "tpixelutils.h" #include "trop.h" //*********************************************************************************************** // Local namespace stuff //*********************************************************************************************** namespace { template <typename T> struct RaylitFuncTraits { typedef void (*function_type)(T *, T *, int, int, int, int, const TRect &, const TRect &, const TRop::RaylitParams &); }; //-------------------------------------------------------------------------------------------- template <typename T> void performStandardRaylit(T *bufIn, T *bufOut, int dxIn, int dyIn, int dxOut, int dyOut, const TRect &srcRect, const TRect &dstRect, const TRop::RaylitParams &params) { /* NOTATION: Diagram assuming octant 1 / | / | / - ray_final_y | octLy / 1 | +---- | _____ octLx So, octLx and octLy are the octant's lx and ly; ray_final_y is the final height of the ray we're tracing */ // Build colors-related variables int max = T::maxChannelValue; /*-- ้€ๆ˜Ž้ƒจๅˆ†ใฎ่‰ฒ --*/ int transp_val = (params.m_invert) ? max : 0, opaque_val = max - transp_val; int value, val_r, val_g, val_b, val_m; double lightness, r_fac, g_fac, b_fac, m_fac; /*-- 8bit/16bitใฎ้•ใ„ใ‚’ๅธๅŽใ™ใ‚‹ไฟ‚ๆ•ฐ --*/ double factor = max / 255.0; // NOTE: These variable initializations are, well, // heuristic at least. They were probably tested // to be good, but didn't quite make any REAL sense. // They could be done MUCH better, but changing them // would alter the way raylit has been applied until now. // Should be changed at some point, though... double scale = params.m_scale; double decay = log(params.m_decay / 100.0 + 1.0) + 1.0; double intensity = 1e8 * log(params.m_intensity / 100.0 + 1.0) / scale; double smoothness = log(params.m_smoothness * 5.0 / 100.0 + 1.0); double radius = params.m_radius; /*-- 1ใ‚นใƒ†ใƒƒใƒ—้€ฒใ‚“ใ ๆ™‚ใ€ๆฌกใฎใƒ”ใ‚ฏใ‚ปใƒซใงๅ…‰ๆบใŒ็„กใ‹ใฃใŸใจใใฎๅ…‰ใฎๅผฑใพใ‚‹ๅ‰ฒๅˆ --*/ double neg_delta_p = smoothness * intensity; /*-- 1ใ‚นใƒ†ใƒƒใƒ—้€ฒใ‚“ใ ๆ™‚ใ€ๆฌกใฎใƒ”ใ‚ฏใ‚ปใƒซใงๅ…‰ๆบใŒๆœ‰ใฃใŸใจใใฎๅ…‰ใฎๅผทใพใ‚‹ๅ‰ฒๅˆ --*/ double quot_delta_p = intensity / max; // /*-- * m_colorใฏRaylitFxใฎColorๅ€คใ€‚r_facใ€g_facใ€b_facใฏๅ„ใƒใƒฃใƒณใƒใƒซใ‚’Premultiplyใ—ใŸๅ€ค * --*/ m_fac = (params.m_color.m / 255.0); r_fac = m_fac * (params.m_color.r / 255.0); g_fac = m_fac * (params.m_color.g / 255.0); b_fac = m_fac * (params.m_color.b / 255.0); // Geometry-related variables int x, y, ray_final_y; int octLx = dstRect.x1 - dstRect.x0; double rayPosIncrementX = 1.0 / scale; double sq_z = sq(params.m_lightOriginSrc.z); // We'll be making square // distances from p, so square // it once now // Perform raylit T *pixIn, *pixOut; for (ray_final_y = 0; ray_final_y < octLx; ++ray_final_y) { // Initialize increment variables lightness = 0.0; double rayPosIncrementY = rayPosIncrementX * (ray_final_y / (double)octLx); // Use an integer counter to know when y must increase. Will add ray_final_y // as long as // a multiple of octLx-1 is reached, then increase int yIncrementCounter = 0, yIncrementThreshold = octLx - 1; // Trace a single ray of light TPointD rayPos(rayPosIncrementX, rayPosIncrementY); for (x = dstRect.x0, y = dstRect.y0, pixIn = bufIn, pixOut = bufOut; (x < dstRect.x1) && (y < dstRect.y1); ++x) { bool insideSrc = (x >= srcRect.x0) && (x < srcRect.x1) && (y >= srcRect.y0) && (y < srcRect.y1); if (insideSrc) { // Add a light component depending on source's matte if (pixIn->m == opaque_val) lightness = std::max( 0.0, lightness - neg_delta_p); // No light source - ray fading else { if (pixIn->m == transp_val) lightness += intensity; // Full light source - ray enforcing else lightness = std::max( 0.0, lightness + // Half light source (params.m_invert ? pixIn->m : (max - pixIn->m)) * quot_delta_p); // matte-linear enforcing } if (params.m_includeInput) { val_r = pixIn->r; val_g = pixIn->g; val_b = pixIn->b; val_m = pixIn->m; } else val_r = val_g = val_b = val_m = 0; } else { if (!params.m_invert) lightness += intensity; else lightness = std::max(0.0, lightness - neg_delta_p); val_r = val_g = val_b = val_m = 0; } bool insideDst = (x >= 0) && (y >= 0); if (insideDst) { // Write the corresponding destination pixel if (lightness > 0.0) { if (radius == 0.0) { value = (int)(factor * lightness / (rayPos.x * pow((double)(sq(rayPos.x) + sq(rayPos.y) + sq_z), decay)) + 0.5); // * ^-d... 0.5 rounds } else { double ratio = std::max(0.001, 1.0 - radius / norm(rayPos)); value = (int)(factor * lightness / (rayPos.x * ratio * pow((double)(sq(rayPos.x * ratio) + sq(rayPos.y * ratio) + sq_z), decay)) + 0.5); // * ^-d... 0.5 rounds } } else value = 0; // NOTE: pow() could be slow. If that is the case, it could be cached // for the whole octant along the longest ray at integer positions, // and then linearly interpolated between those... Have to profile this // before resorting to that... val_r += value * r_fac; val_g += value * g_fac; val_b += value * b_fac; val_m += value * m_fac; pixOut->r = (val_r > max) ? max : val_r; pixOut->g = (val_g > max) ? max : val_g; pixOut->b = (val_b > max) ? max : val_b; pixOut->m = (val_m > max) ? max : val_m; } // Increment variables along the x-axis pixIn += dxIn, pixOut += dxOut; rayPos.x += rayPosIncrementX, rayPos.y += rayPosIncrementY; // Increment variables along the y-axis if ((yIncrementCounter += ray_final_y) >= yIncrementThreshold) { ++y, pixIn += dyIn, pixOut += dyOut; yIncrementCounter -= yIncrementThreshold; } } } } //-------------------------------------------------------------------------------------------- template <typename T> void performColorRaylit(T *bufIn, T *bufOut, int dxIn, int dyIn, int dxOut, int dyOut, const TRect &srcRect, const TRect &dstRect, const TRop::RaylitParams &params) { // Build colors-related variables int max = T::maxChannelValue; int val_r, val_g, val_b, val_m; double lightness_r, lightness_g, lightness_b; double factor = max / 255.0; // NOTE: These variable initializations are, well, // heuristic at least. They were probably tested // to be good, but didn't quite make any REAL sense. // They could be done MUCH better, but changing them // would alter the way raylit has been applied until now. // Should be changed at some point, though... double scale = params.m_scale; double decay = log(params.m_decay / 100.0 + 1.0) + 1.0; double intensity = 1e8 * log(params.m_intensity / 100.0 + 1.0) / scale; double smoothness = log(params.m_smoothness * 5.0 / 100.0 + 1.0); double radius = params.m_radius; double neg_delta_p = smoothness * intensity; // would alter the way raylit has been applied until now. double quot_delta_p = intensity / max; // // Should be changed at some point, though... // Geometry-related variables int x, y, ray_final_y; int octLx = dstRect.x1 - dstRect.x0; double rayPosIncrementX = 1.0 / scale; double fac, sq_z = sq(params.m_lightOriginSrc.z); // We'll be making square // distances from p, so // square it once now // Perform raylit T *pixIn, *pixOut; for (ray_final_y = 0; ray_final_y < octLx; ++ray_final_y) { // Initialize increment variables lightness_r = lightness_g = lightness_b = 0.0; int l, l_max; double rayPosIncrementY = rayPosIncrementX * (ray_final_y / (double)octLx); // Use an integer counter to know when y must increase. Will add ray_final_y // as long as // a multiple of octLx-1 is reached, then increase int yIncrementCounter = 0, yIncrementThreshold = octLx - 1; // Trace a single ray of light TPointD rayPos(rayPosIncrementX, rayPosIncrementY); for (x = dstRect.x0, y = dstRect.y0, pixIn = bufIn, pixOut = bufOut; (x < dstRect.x1) && (y < dstRect.y1); ++x) { bool insideSrc = (x >= srcRect.x0) && (x < srcRect.x1) && (y >= srcRect.y0) && (y < srcRect.y1); if (insideSrc) { val_r = pixIn->r; val_g = pixIn->g; val_b = pixIn->b; val_m = pixIn->m; lightness_r = std::max(0.0, val_r ? lightness_r + val_r * quot_delta_p : lightness_r - neg_delta_p); lightness_g = std::max(0.0, val_g ? lightness_g + val_g * quot_delta_p : lightness_g - neg_delta_p); lightness_b = std::max(0.0, val_b ? lightness_b + val_b * quot_delta_p : lightness_b - neg_delta_p); if (!params.m_includeInput) val_r = val_g = val_b = val_m = 0; } else { lightness_r = std::max(0.0, lightness_r - neg_delta_p); lightness_g = std::max(0.0, lightness_g - neg_delta_p); lightness_b = std::max(0.0, lightness_b - neg_delta_p); val_r = val_g = val_b = val_m = 0; } bool insideDst = (x >= 0) && (y >= 0); if (insideDst) { // Write the corresponding destination pixel if (radius == 0.0) { fac = factor / (rayPos.x * pow((double)(sq(rayPos.x) + sq(rayPos.y) + sq_z), decay)); } else { double ratio = std::max(0.001, 1.0 - radius / norm(rayPos)); fac = factor / (rayPos.x * ratio * pow((double)(sq(rayPos.x * ratio) + sq(rayPos.y * ratio) + sq_z), decay)); } // NOTE: pow() could be slow. If that is the case, it could be cached // for the whole octant along the longest ray at integer positions, // and then linearly interpolated between those... Have to profile this // before resorting to that... val_r += l = (int)(fac * lightness_r + 0.5); l_max = l; val_g += l = (int)(fac * lightness_g + 0.5); l_max = std::max(l, l_max); val_b += l = (int)(fac * lightness_b + 0.5); l_max = std::max(l, l_max); val_m += l_max; pixOut->r = (val_r > max) ? max : val_r; pixOut->g = (val_g > max) ? max : val_g; pixOut->b = (val_b > max) ? max : val_b; pixOut->m = (val_m > max) ? max : val_m; } // Increment variables along the x-axis pixIn += dxIn, pixOut += dxOut; rayPos.x += rayPosIncrementX, rayPos.y += rayPosIncrementY; // Increment variables along the y-axis if ((yIncrementCounter += ray_final_y) >= yIncrementThreshold) { ++y, pixIn += dyIn, pixOut += dyOut; yIncrementCounter -= yIncrementThreshold; } } } } //-------------------------------------------------------------------------------------------- /*-- ใƒ”ใ‚ถ็Šถใซ8ๅˆ†ๅ‰ฒใ•ใ‚ŒใŸ้ ˜ๅŸŸใฎ1ใคใ‚’่จˆ็ฎ—ใ™ใ‚‹ --*/ template <typename T> void computeOctant(const TRasterPT<T> &src, const TRasterPT<T> &dst, int octant, const TRop::RaylitParams &params, typename RaylitFuncTraits<T>::function_type raylitFunc) { // Build octant geometry variables int x0, x1, lxIn, lxOut, dxIn, dxOut; int y0, y1, lyIn, lyOut, dyIn, dyOut; const T3DPoint &pIn = params.m_lightOriginSrc, &pOut = params.m_lightOriginDst; int srcWrap = src->getWrap(), dstWrap = dst->getWrap(); T *bufIn = (T *)src->getRawData() + tfloor(pIn.y) * srcWrap + tfloor(pIn.x); T *bufOut = (T *)dst->getRawData() + tfloor(pOut.y) * dstWrap + tfloor(pOut.x); TRect srcRect(src->getBounds() + TPoint(tround(pOut.x - pIn.x), tround(pOut.y - pIn.y))); lxIn = src->getLx(), lxOut = dst->getLx(); lyIn = src->getLy(), lyOut = dst->getLy(); /*-- 1ใƒ”ใ‚ฏใ‚ปใƒซใšใค้€ฒใ‚€ใจใใฎ็งปๅ‹•ๅ€ค --*/ // Vertical octant pairs if (octant == 1 || octant == 8) dxIn = 1, dxOut = 1, x0 = tfloor(pOut.x), x1 = lxOut; if (octant == 2 || octant == 7) dyIn = 1, dyOut = 1, y0 = tfloor(pOut.x), y1 = lxOut; if (octant == 3 || octant == 6) dyIn = -1, dyOut = -1, y0 = lxOut - tfloor(pOut.x) - 1, y1 = lxOut, std::swap(srcRect.x0, srcRect.x1), srcRect.x0 = lxOut - srcRect.x0, srcRect.x1 = lxOut - srcRect.x1; if (octant == 4 || octant == 5) dxIn = -1, dxOut = -1, x0 = lxOut - tfloor(pOut.x) - 1, x1 = lxOut, std::swap(srcRect.x0, srcRect.x1), srcRect.x0 = lxOut - srcRect.x0, srcRect.x1 = lxOut - srcRect.x1; // Horizontal octant pairs if (octant == 2 || octant == 3) dxIn = srcWrap, dxOut = dstWrap, x0 = tfloor(pOut.y), x1 = lyOut; if (octant == 1 || octant == 4) dyIn = srcWrap, dyOut = dstWrap, y0 = tfloor(pOut.y), y1 = lyOut; if (octant == 5 || octant == 8) dyIn = -srcWrap, dyOut = -dstWrap, y0 = lyOut - tfloor(pOut.y) - 1, y1 = lyOut, std::swap(srcRect.y0, srcRect.y1), srcRect.y0 = lyOut - srcRect.y0, srcRect.y1 = lyOut - srcRect.y1; if (octant == 6 || octant == 7) dxIn = -srcWrap, dxOut = -dstWrap, x0 = lyOut - tfloor(pOut.y) - 1, x1 = lyOut, std::swap(srcRect.y0, srcRect.y1), srcRect.y0 = lyOut - srcRect.y0, srcRect.y1 = lyOut - srcRect.y1; /*-- ็ธฆๅ‘ใใฎใƒ”ใ‚ถ้ ˜ๅŸŸใ‚’่จˆ็ฎ—ใ™ใ‚‹ๅ ดๅˆใฏใ€90ๅบฆๅ›ž่ปขใ—ใฆใ‹ใ‚‰ --*/ // Swap x and y axis where necessary if (octant == 2 || octant == 3 || octant == 6 || octant == 7) { std::swap(lxIn, lyIn), std::swap(lxOut, lyOut); std::swap(srcRect.x0, srcRect.y0), std::swap(srcRect.x1, srcRect.y1); } int octLx = (x1 - x0), octLy = (y1 - y0); assert(octLx > 0 && octLy > 0); if (octLx <= 0 && octLy <= 0) return; raylitFunc(bufIn, bufOut, dxIn, dyIn, dxOut, dyOut, srcRect, TRect(x0, y0, x1, y1), params); } //-------------------------------------------------------------------------------------------- /* OCTANTS: \ 3 | 2 / \ | / \ | / 4 \|/ 1 ----+---- 5 /|\ 8 / | \ / | \ / 6 | 7 \ */ template <typename T> void doRaylit(const TRasterPT<T> &src, const TRasterPT<T> &dst, const TRop::RaylitParams &params, typename RaylitFuncTraits<T>::function_type raylitFunc) { int lxOut = dst->getLx(), lyOut = dst->getLy(); const T3DPoint &p = params.m_lightOriginDst; src->lock(); dst->lock(); // Depending on the position of p, only some of the quadrants need to be built if (p.y < lyOut) { if (p.x < lxOut) { // Compute the raylit fx on each octant independently computeOctant(src, dst, 1, params, raylitFunc); computeOctant(src, dst, 2, params, raylitFunc); } if (p.x >= 0) { computeOctant(src, dst, 3, params, raylitFunc); computeOctant(src, dst, 4, params, raylitFunc); } } if (p.y >= 0) { if (p.x >= 0) { computeOctant(src, dst, 5, params, raylitFunc); computeOctant(src, dst, 6, params, raylitFunc); } if (p.x < lxOut) { computeOctant(src, dst, 7, params, raylitFunc); computeOctant(src, dst, 8, params, raylitFunc); } } dst->unlock(); src->unlock(); } } // namespace //*********************************************************************************************** // TRop::raylit implementation //*********************************************************************************************** void TRop::raylit(const TRasterP &dstRas, const TRasterP &srcRas, const RaylitParams &params) { if ((TRaster32P)dstRas && (TRaster32P)srcRas) doRaylit<TPixel32>(srcRas, dstRas, params, &performStandardRaylit<TPixel32>); else if ((TRaster64P)dstRas && (TRaster64P)srcRas) doRaylit<TPixel64>(srcRas, dstRas, params, &performStandardRaylit<TPixel64>); else throw TException("TRop::raylit unsupported pixel type"); } //-------------------------------------------------------------------------------------------- void TRop::glassRaylit(const TRasterP &dstRas, const TRasterP &srcRas, const RaylitParams &params) { if ((TRaster32P)dstRas && (TRaster32P)srcRas) doRaylit<TPixel32>(srcRas, dstRas, params, &performColorRaylit<TPixel32>); else if ((TRaster64P)dstRas && (TRaster64P)srcRas) doRaylit<TPixel64>(srcRas, dstRas, params, &performColorRaylit<TPixel64>); else throw TException("TRop::raylit unsupported pixel type"); }
36.325678
97
0.535402
[ "geometry" ]
a0a5e8099e3aad416c0bf12a0869b127349bfcf6
7,733
cpp
C++
servant/libservant/AuthLogic.cpp
SuckShit/TarsCpp
3f42f4e7a7bf43026a782c5d4b033155c27ed0c4
[ "BSD-3-Clause" ]
null
null
null
servant/libservant/AuthLogic.cpp
SuckShit/TarsCpp
3f42f4e7a7bf43026a782c5d4b033155c27ed0c4
[ "BSD-3-Clause" ]
null
null
null
servant/libservant/AuthLogic.cpp
SuckShit/TarsCpp
3f42f4e7a7bf43026a782c5d4b033155c27ed0c4
[ "BSD-3-Clause" ]
1
2021-05-21T09:59:06.000Z
2021-05-21T09:59:06.000Z
๏ปฟ/** * Tencent is pleased to support the open source community by making Tars available. * * Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * https://opensource.org/licenses/BSD-3-Clause * * 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 "util/tc_epoll_server.h" #include "util/tc_des.h" #include "util/tc_sha.h" #include "util/tc_md5.h" #include "servant/Application.h" #include "servant/AuthLogic.h" #include <iostream> #include <cassert> namespace tars { bool processAuth(TC_EpollServer::Connection *conn, const shared_ptr<TC_EpollServer::RecvContext> &data) { conn->tryInitAuthState(AUTH_INIT); if (conn->_authState == AUTH_SUCC) return false; // data to be processed TC_EpollServer::BindAdapterPtr adapter = data->adapter(); int type = adapter->getEndpoint().getAuthType(); if (type == AUTH_TYPENONE) { adapter->getEpollServer()->info("processAuth no need auth func, auth succ"); conn->_authState = AUTH_SUCC; return false; } // got auth request RequestPacket request; if (adapter->isTarsProtocol()) { TarsInputStream<BufferReader> is; is.setBuffer(data->buffer().data(), data->buffer().size()); try { request.readFrom(is); } catch(...) { adapter->getEpollServer()->error("processAuth tars protocol decode error, close connection."); conn->setClose(); return true; } } else { request.sBuffer = data->buffer(); } int currentState = conn->_authState; int newstate = tars::defaultProcessAuthReq(request.sBuffer.data(), request.sBuffer.size(), adapter->getName()); std::string out = tars::etos((tars::AUTH_STATE)newstate); if (newstate < 0) { // ้ชŒ่ฏ้”™่ฏฏ,ๆ–ญๅผ€่ฟžๆŽฅ adapter->getEpollServer()->error("authProcess failed with new state [" + out + "]"); conn->setClose(); return true; } adapter->getEpollServer()->info(TC_Common::tostr(conn->getId()) + "'s auth response[" + out + "], change state from " + tars::etos((tars::AUTH_STATE)currentState) + " to " + out); conn->_authState = newstate; shared_ptr<TC_EpollServer::SendContext> sData = data->createSendContext(); if (adapter->isTarsProtocol()) { TarsOutputStream<BufferWriterVector> os; ResponsePacket response; response.iVersion = TARSVERSION; response.iRequestId = request.iRequestId; response.iMessageType = request.iMessageType; response.cPacketType = request.cPacketType; response.iRet = 0; response.sBuffer.assign(out.begin(), out.end()); int iHeaderLen = 0; // ๅ…ˆ้ข„็•™4ไธชๅญ—่Š‚้•ฟๅบฆ os.writeBuf((const char *)&iHeaderLen, sizeof(iHeaderLen)); response.writeTo(os); vector<char> buff; buff.swap(os.getByteBuffer()); assert(buff.size() >= 4); iHeaderLen = htonl((int)(buff.size())); memcpy((void*)buff.data(), (const char *)&iHeaderLen, sizeof(iHeaderLen)); sData->buffer()->swap(buff); } else { sData->buffer()->assign(out.c_str(), out.size()); } adapter->getEpollServer()->send(sData); return true; // processed } int processAuthReqHelper(const BasicAuthPackage& pkg, const BasicAuthInfo& info) { // ๆ˜Žๆ–‡:objName, accessKey, time, hashMethod // ๅฏ†ๆ–‡:use TmpKey to enc secret1; // and tmpKey = sha1(secret2 | timestamp); if (pkg.sObjName != info.sObjName) return AUTH_WRONG_OBJ; if (pkg.sAccessKey != info.sAccessKey) return AUTH_WRONG_AK; time_t now = TNOW; const int range = 60 * 60; if (!(pkg.iTime > (now - range) && pkg.iTime < (now + range))) return AUTH_WRONG_TIME; if (pkg.sHashMethod != "sha1") return AUTH_NOT_SUPPORT_ENC; // ็”จsecret1 = sha1(password); secret2 = sha1(secret1); // 1.client create TmpKey use timestamp and secret2; // 2.client use TmpKey to enc secret1; // 3.server use TmpKey same as client, to dec secret1; // 4.server got secret1, then sha1(secret1), to compare secret2; // ไธ‹้ข่ฟ™ไธชๆ˜ฏ123456็š„ไธคๆฌกsha1ๅ€ผ //assert (info.sHashSecretKey2 == "69c5fcebaa65b560eaf06c3fbeb481ae44b8d618"); string tmpKey; string hash2; { string hash1 = TC_SHA::sha1str(info.sHashSecretKey2.data(), info.sHashSecretKey2.size()); hash2 = TC_SHA::sha1str(hash1.data(), hash1.size()); string tmp = hash2; const char* pt = (const char* )&pkg.iTime; for (size_t i = 0; i < sizeof pkg.iTime; ++ i) { tmp[i] |= pt[i]; } tmpKey = TC_MD5::md5str(tmp); } string secret1; { try { secret1 = TC_Des::decrypt3(tmpKey.data(), pkg.sSignature.data(), pkg.sSignature.size()); } catch (const TC_DES_Exception& ) { return AUTH_DEC_FAIL; } } // 4.server got secret1, then sha1(secret1), to compare secret2; string clientSecret2 = TC_SHA::sha1str(secret1.data(), secret1.size()); if (clientSecret2.size() != hash2.size() || !std::equal(clientSecret2.begin(), clientSecret2.end(), hash2.begin())) { return AUTH_ERROR; } return AUTH_SUCC; } // ๅช้œ€่ฆไผ ๅ…ฅ expect ็š„objname๏ผ› // ๅ†…้ƒจๆ นๆฎobjๆŸฅๆ‰พaccess่ดฆๅท้›† int defaultProcessAuthReq(const char* request, size_t len, const string& expectObj) { if (len <= 20) return AUTH_PROTO_ERR; BasicAuthPackage pkg; TarsInputStream<BufferReader> is; is.setBuffer(request, len); try { pkg.readFrom(is); } catch(...) { return AUTH_PROTO_ERR; } TC_EpollServer::BindAdapterPtr bap = Application::getEpollServer()->getBindAdapter(expectObj); if (!bap) return AUTH_WRONG_OBJ; BasicAuthInfo info; string expectServantName = ServantHelperManager::getInstance()->getAdapterServant(expectObj); info.sObjName = expectServantName; info.sAccessKey = pkg.sAccessKey; info.sHashSecretKey2 = bap->getSk(info.sAccessKey); if (info.sHashSecretKey2.empty()) return AUTH_WRONG_AK; return processAuthReqHelper(pkg, info); } int defaultProcessAuthReq(const string& request, const string& expectObj) { return defaultProcessAuthReq(request.data(), request.size(), expectObj); } string defaultCreateAuthReq(const BasicAuthInfo& info /*, const string& hashMethod*/ ) { // ๆ˜Žๆ–‡:objName, accessKey, time, hashMethod // ๅฏ†ๆ–‡:use TmpKey to enc secret1; TarsOutputStream<BufferWriterString> os; BasicAuthPackage pkg; pkg.sObjName = info.sObjName; pkg.sAccessKey = info.sAccessKey; pkg.iTime = TNOW; string secret1 = TC_SHA::sha1str(info.sSecretKey.data(), info.sSecretKey.size()); string secret2 = TC_SHA::sha1str(secret1.data(), secret1.size()); // create tmpKey string tmpKey; { string tmp = secret2; const char* pt = (const char* )&pkg.iTime; for (size_t i = 0; i < sizeof pkg.iTime; ++ i) { tmp[i] |= pt[i]; } // ๅช็”จไบ†ๅ‰้ข24ๅญ—่Š‚ tmpKey = TC_MD5::md5str(tmp); } pkg.sSignature = TC_Des::encrypt3(tmpKey.data(), secret1.data(), secret1.size()); pkg.writeTo(os); return os.getByteBuffer(); } } // end namespace tars
28.640741
123
0.639597
[ "vector" ]
a0a70440a291bccff511a60ec89a6f11ef4a525e
419
cpp
C++
examples/polar_plots/polarscatter/polarscatter_3.cpp
kurogane1031/matplotplusplus
44d21156edba8effe1e764a8642b0b70590d597b
[ "MIT" ]
2
2020-09-02T14:02:26.000Z
2020-10-28T07:00:44.000Z
examples/polar_plots/polarscatter/polarscatter_3.cpp
kurogane1031/matplotplusplus
44d21156edba8effe1e764a8642b0b70590d597b
[ "MIT" ]
null
null
null
examples/polar_plots/polarscatter/polarscatter_3.cpp
kurogane1031/matplotplusplus
44d21156edba8effe1e764a8642b0b70590d597b
[ "MIT" ]
2
2020-09-01T16:22:07.000Z
2020-09-02T14:02:27.000Z
#include <cmath> #include <matplot/matplot.h> int main() { using namespace matplot; std::vector<double> theta = iota(pi/4, pi/4, 2*pi); std::vector<double> rho = {19,6,12,18,16,11,15,15}; std::vector<double> sizes = {6*2,15*2,20*2,3*2,15*2,3*2,6*2,40*2,}; std::vector<double> colors = {1,2,2,2,1,1,2,1,}; auto s = polarscatter(theta, rho, sizes, colors, "filled"); wait(); return 0; }
27.933333
71
0.596659
[ "vector" ]
a0a8a5710a017e6be50a0e8e482dc2d0c12bfcf6
1,529
cpp
C++
src/_leetcode/leet_26.cpp
turesnake/leetPractice
a87b9b90eb8016038d7e5d3ad8e50e4ceb54d69b
[ "MIT" ]
null
null
null
src/_leetcode/leet_26.cpp
turesnake/leetPractice
a87b9b90eb8016038d7e5d3ad8e50e4ceb54d69b
[ "MIT" ]
null
null
null
src/_leetcode/leet_26.cpp
turesnake/leetPractice
a87b9b90eb8016038d7e5d3ad8e50e4ceb54d69b
[ "MIT" ]
null
null
null
/* * ====================== leet_26.cpp ========================== * -- tpr -- * CREATE -- 2020.04.14 * MODIFY -- * ---------------------------------------------------------- * 26. ๅˆ ้™คๆŽ’ๅบๆ•ฐ็ป„ไธญ็š„้‡ๅค้กน */ #include "innLeet.h" namespace leet_26 {//~ int removeDuplicates( std::vector<int>& nums) { if( nums.size() < 2 ){ return nums.size(); } auto tail = nums.begin(); auto head = tail; while( tail != nums.end() ){ head = tail + 1; while( true ){ if(head==nums.end()){ // ๆœ€ๅŽไธ€็ป„ๆ•ฐไบ† nums.erase( tail+1, head ); return nums.size(); } if( *head != *tail ){ break; } head++; } // ็Žฐๅœจ๏ผŒhead ๆŒ‡ๅ‘ๆ–ฐๅ€ผ tail = nums.erase( tail+1, head ); } return 0; } int removeDuplicates_2( std::vector<int>& nums) { auto last = std::unique( nums.begin(), nums.end() ); nums.erase( last, nums.end() ); return nums.size(); } //=========================================================// void main_(){ //std::vector<int> v { 0,0,1,1,1,2,2,3,3,4 }; std::vector<int> v { 0, 0, 0, 1, 2,2 }; int ret = removeDuplicates_2( v ); cout << "ret = " << ret << endl; for( const auto &i : v ){ cout << i << ", "; } cout << endl; debug::log( "\n~~~~ leet: 26 :end ~~~~\n" ); } }//~
18.646341
64
0.359058
[ "vector" ]
a0a8c8945e7f77b31a43871edd41cf3d8b0d6b32
11,436
cpp
C++
plugins/ipmidirect/ipmi_mc_vendor_intel.cpp
openhpi2/openhpi_apr25
720d4043124ac44d17715db4ffb735c623c08e38
[ "BSD-3-Clause" ]
5
2018-12-18T01:32:53.000Z
2021-11-15T10:41:48.000Z
plugins/ipmidirect/ipmi_mc_vendor_intel.cpp
openhpi2/openhpi_apr25
720d4043124ac44d17715db4ffb735c623c08e38
[ "BSD-3-Clause" ]
34
2018-05-11T21:31:33.000Z
2021-01-12T07:13:46.000Z
plugins/ipmidirect/ipmi_mc_vendor_intel.cpp
openhpi2/openhpi_apr25
720d4043124ac44d17715db4ffb735c623c08e38
[ "BSD-3-Clause" ]
8
2018-08-27T22:48:44.000Z
2022-03-15T03:49:55.000Z
/* * Intel specific code * * Copyright (c) 2004-2006 by Intel Corp. * * 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. This * file and program are licensed under a BSD style license. See * the Copying file included with the OpenHPI distribution for * full licensing terms. * * Authors: * Andy Cress <arcress@users.sourceforge.net> */ #include "ipmi_mc_vendor_intel.h" #include "ipmi_utils.h" #include "ipmi_log.h" #include "ipmi_mc.h" #include "ipmi_domain.h" // #include <errno.h> #define HSC_SA 0xc0 /*slave address of HSC mc*/ int g_enableHSC = 0; /* flag to detect whether an HSC is present */ /*--------------------------------------- * cIpmiMcVendorIntelBmc object *---------------------------------------*/ cIpmiMcVendorIntelBmc::cIpmiMcVendorIntelBmc( unsigned int product_id ) : cIpmiMcVendor( 0x000157, product_id, "Intel BMC" ) { /* instantiate the cIpmiMcVendorIntelBmc */ } cIpmiMcVendorIntelBmc::~cIpmiMcVendorIntelBmc() { } bool cIpmiMcVendorIntelBmc::InitMc( cIpmiMc *mc, const cIpmiMsg &devid ) { stdlog << "Intel InitMc[" << mc->ManufacturerId() << "," << mc->ProductId() << "]: addr = " << mc->GetAddress() << "\n"; /* Set the m_busid for Leds */ switch(mc->ProductId()) { case 0x0022: m_busid = PRIVATE_BUS_ID5; break; /*TIGI2U*/ case 0x001B: m_busid = PRIVATE_BUS_ID; break; /*TIGPR2U*/ case 0x4311: m_busid = PERIPHERAL_BUS_ID; break; /*TIGPT1U mBMC*/ case 0x0026: case 0x0028: /*S5000PAL*/ case 0x0029: case 0x0811: m_busid = PRIVATE_BUS_ID7; break; /*TIGW1U*/ case 0x003E: /*S5520UR*/ case 0x0048: /*S1200BT*/ case 0x0049: /*S2600GL*/ case 0x004A: /*S2600CP*/ case 0x004D: /*S2600JF*/ case 0x004F: /*S2400SC*/ case 0x0051: /*S2400EP*/ case 0x0055: /*S2600IP*/ case 0x0056: /*W2600CR*/ case 0x005C: /*S4600LH*/ case 0x005D: /*S2600CO*/ case 0x0900: /*TIGPR2U HSC*/ case 0x0911: /*TIGI2U HSC*/ case 0x0A0C: /*TIGW1U HSC*/ default: m_busid = PRIVATE_BUS_ID; break; } if (mc->IsTcaMc()) return true; /* * If here, the MC has (manuf_id == 0x000157) Intel, and * product_id == one of these: { 0x000C, 0x001B, 0x0022, 0x4311, * 0x0100, 0x0026, 0x0028, 0x0811 }; * These return GetDeviceID with ProvidesDeviceSdrs() == true, and * use the SDR Repository. */ mc->SetProvidesDeviceSdrs(false); mc->IsRmsBoard() = true; /* * The FRUSDR should be set at the factory, so don't change it here. * Don't clear the SEL here either. */ return true; } bool cIpmiMcVendorIntelBmc::CreateControls(cIpmiDomain *dom, cIpmiMc * mc, cIpmiSdrs * sdrs ) { const char *name; char dstr[80]; int i; if (mc->IsTcaMc()) return true; for ( int j = 0; j < mc->NumResources(); j++ ) { cIpmiResource *res = mc->GetResource( j ); if ( res == 0 ) continue; /* Note that the RPT has not been Populated yet */ if (res->FruId() == 0) { /* Create the alarm LED RDRs for the baseboard */ for (i = 0; i <= LED_IDENT; i++) { cIpmiControlIntelRmsLed *led = new cIpmiControlIntelRmsLed( mc, i); led->EntityPath() = res->EntityPath(); switch (i) { case LED_POWER: name = "Power Alarm LED"; break; case LED_CRIT: name = "Critical Alarm LED"; break; case LED_MAJOR: name = "Major Alarm LED"; break; case LED_MINOR: name = "Minor Alarm LED"; break; case LED_IDENT: name = "Chassis Identify LED"; break; default: snprintf(dstr,sizeof(dstr),"Control LED %d",i); name = dstr; break; } led->IdString().SetAscii(name, SAHPI_TL_TYPE_TEXT, SAHPI_LANG_ENGLISH); res->AddRdr( led ); led->m_busid = m_busid; } break; } } return true; } bool cIpmiMcVendorIntelBmc::ProcessSdr( cIpmiDomain *domain, cIpmiMc *mc, cIpmiSdrs *sdrs ) { if ( mc->GetAddress() != 0x20 ) { stdlog << "Intel MC " << mc->GetAddress() << " skipped\n"; return true; } stdlog << "Intel MC " << mc->GetAddress() << ", ProcessSdr\n"; /* Cannot enable Watchdog here because RPT is not built yet. */ /* * Sort through the SDR DeviceLocatorRecords and handle them. * e.g.: slave address 0xc0 (HSC) or 0x28 (IPMB Bridge), */ for( unsigned int i = 0; i < sdrs->NumSdrs(); i++ ) { cIpmiSdr *sdr = sdrs->Sdr( i ); switch( sdr->m_type ) { case eSdrTypeMcDeviceLocatorRecord: stdlog << "Intel SDR[" << i << "] Locator " << sdr->m_data[5] << "\n"; if (sdr->m_data[5] == HSC_SA) g_enableHSC = 1; break; default: break; } } return true; } bool cIpmiMcVendorIntelBmc::ProcessFru( cIpmiInventory *inv, cIpmiMc *mc, unsigned int sa, SaHpiEntityTypeT type ) { stdlog << "ProcessFru: Intel MC " << sa << " enableHSC " << g_enableHSC << "\n"; if (mc->IsTcaMc()) return true; if (type == SAHPI_ENT_SYSTEM_BOARD) { cIpmiResource *res = inv->Resource(); stdlog << "ProcessFru: found " << inv->IdString() << " id " << res->m_resource_id << "\n"; /* RPTs are not built yet, so we can't enable RESET here */ /* see ipmi_resource.cpp for that. */ } else if ((sa != mc->GetAddress()) && (type != SAHPI_ENT_SYSTEM_BOARD)) { /* g_enableHSC == 1 */ stdlog << "ProcessFru: " << inv->IdString() << " setting addr " << mc->GetAddress() << " to " << sa << " type " << type << "\n"; cIpmiAddr addr(eIpmiAddrTypeIpmb,mc->GetChannel(),0,sa); inv->SetAddr(addr); } return true; } /*--------------------------------------- * cIpmiControlIntelRmsLed object *---------------------------------------*/ cIpmiControlIntelRmsLed::cIpmiControlIntelRmsLed( cIpmiMc *mc, unsigned int num) : cIpmiControl( mc, num, SAHPI_CTRL_LED, SAHPI_CTRL_TYPE_DIGITAL ) { } cIpmiControlIntelRmsLed::~cIpmiControlIntelRmsLed() { } bool cIpmiControlIntelRmsLed::CreateRdr( SaHpiRptEntryT &resource, SaHpiRdrT &rdr ) { int n; if ( cIpmiControl::CreateRdr( resource, rdr ) == false ) return false; n = rdr.RdrTypeUnion.CtrlRec.Num; // rdr->RdrTypeUnion.CtrlRec.Num = n; rdr.RdrTypeUnion.CtrlRec.Oem = OEM_ALARM_BASE + n; rdr.RdrTypeUnion.CtrlRec.Type = SAHPI_CTRL_TYPE_DIGITAL; rdr.RdrTypeUnion.CtrlRec.OutputType = SAHPI_CTRL_LED; if (n == LED_IDENT) /* Identify LED */ rdr.RdrTypeUnion.CtrlRec.WriteOnly = SAHPI_TRUE; else rdr.RdrTypeUnion.CtrlRec.WriteOnly = SAHPI_FALSE; stdlog << "Intel:CreateRdr(Led): num = " << n << " oem_num = " << rdr.RdrTypeUnion.CtrlRec.Oem << "\n"; return true; } SaErrorT cIpmiControlIntelRmsLed::GetState( SaHpiCtrlModeT &mode, SaHpiCtrlStateT &state ) { unsigned char mask = 0x01; int i; SaErrorT rv = SA_OK; /*TODO: add GetAlarmsPicmg() if ATCA */ int idx = m_num; // m_oem - OEM_ALARM_BASE; if (idx == LED_IDENT) { /* Identify LED */ mode = SAHPI_CTRL_MODE_MANUAL; state.Type = SAHPI_CTRL_TYPE_DIGITAL; state.StateUnion.Digital = SAHPI_CTRL_STATE_OFF; return rv; } unsigned char val = GetAlarms(); mode = SAHPI_CTRL_MODE_MANUAL; /* or SAHPI_CTRL_MODE_AUTO */ state.Type = SAHPI_CTRL_TYPE_DIGITAL; for (i = 0; i < idx; i++) mask = mask << 1; if ((val & mask) == 0) state.StateUnion.Digital = SAHPI_CTRL_STATE_ON; else state.StateUnion.Digital = SAHPI_CTRL_STATE_OFF; stdlog << "Led:GetState(" << idx << "): mode = " << mode << " state = " << state.StateUnion.Digital << "\n"; return rv; } SaErrorT cIpmiControlIntelRmsLed::SetState( const SaHpiCtrlModeT &mode, const SaHpiCtrlStateT &state ) { static unsigned char id_time = 20; /*id_time = 20 seconds*/ unsigned char mask = 0x01; unsigned char val, newval; int i; SaErrorT rv = SA_OK; /*TODO: add SetAlarmsPicmg() if ATCA */ int idx = m_num; // m_oem - OEM_ALARM_BASE; if (idx == LED_IDENT) { /* Identify LED */ rv = SetIdentify(id_time); /* turn ID on for id_time seconds */ return rv; } val = GetAlarms(); for (i = 0; i < idx; i++) mask = mask << 1; if (state.StateUnion.Digital == SAHPI_CTRL_STATE_ON) { mask = ~mask; /*NOT*/ newval = val & mask; } else { newval = val | mask; } rv = SetAlarms(newval); stdlog << "Led:SetAlarms(" << idx << ") " << "state = " << state.StateUnion.Digital << " rv = " << rv << "\n"; return rv; } void cIpmiControlIntelRmsLed::Dump( cIpmiLog &dump, const char *name ) const { dump.Begin( "LedControl", name ); dump.End(); } unsigned char cIpmiControlIntelRmsLed::GetAlarms( void ) { cIpmiMsg msg( eIpmiNetfnApp, eIpmiCmdMasterReadWrite ); msg.m_data[0] = m_busid; msg.m_data[1] = ALARMS_PANEL_READ; msg.m_data[2] = 0x01; msg.m_data_len = 3; cIpmiMsg rsp; SaErrorT rv = Resource()->SendCommandReadLock( this, msg, rsp ); if (rv != SA_OK) return(0); // uchar cc = rsp.m_data[0]; return(rsp.m_data[1]); } unsigned char cIpmiControlIntelRmsLed::GetAlarmsPicmg( unsigned char picmg_id, unsigned char fruid) { cIpmiMsg msg( eIpmiNetfnPicmg, eIpmiCmdGetFruLedState ); cIpmiMsg rsp; msg.m_data[0] = picmg_id; msg.m_data[1] = fruid; msg.m_data[2] = 0; /* blue LED */ msg.m_data_len = 3; SaErrorT rv = Resource()->SendCommandReadLock( this, msg, rsp ); if (rv == 0 && rsp.m_data[0] != 0) rv = rsp.m_data[0]; /*comp code*/ if (rv != 0) { stdlog << "GetAlarmsPicmg error rv = " << rv << "\n"; return(0); } return(rsp.m_data[6]); /*status byte*/ } int cIpmiControlIntelRmsLed::SetAlarmsPicmg( unsigned char picmg_id, unsigned char fruid, unsigned char val) { cIpmiMsg msg( eIpmiNetfnPicmg, eIpmiCmdSetFruLedState ); cIpmiMsg rsp; msg.m_data[0] = picmg_id; msg.m_data[1] = fruid; msg.m_data[2] = 0; /* blue LED */ msg.m_data[3] = val; msg.m_data[4] = 0; msg.m_data[5] = 1; /* color blue */ msg.m_data_len = 6; SaErrorT rv = Resource()->SendCommandReadLock( this, msg, rsp ); if (rv != 0) return(rv); if (rsp.m_data[0] != 0) rv = rsp.m_data[0]; /*comp code*/ return(rv); } int cIpmiControlIntelRmsLed::SetAlarms( unsigned char value) { cIpmiMsg msg( eIpmiNetfnApp, eIpmiCmdMasterReadWrite ); msg.m_data[0] = m_busid; msg.m_data[1] = ALARMS_PANEL_WRITE; msg.m_data[2] = 0x01; msg.m_data[3] = value; msg.m_data_len = 4; cIpmiMsg rsp; SaErrorT rv = Resource()->SendCommandReadLock( this, msg, rsp ); if (rv != 0) return(rv); if (rsp.m_data[0] != 0) rv = rsp.m_data[0]; /*comp code*/ return(rv); } int cIpmiControlIntelRmsLed::SetIdentify( unsigned char tval) { cIpmiMsg msg( eIpmiNetfnChassis, eIpmiCmdChassisIdentify ); msg.m_data[0] = tval; /*num seconds*/ msg.m_data_len = 1; cIpmiMsg rsp; SaErrorT rv = Resource()->SendCommandReadLock( this, msg, rsp ); if (rv != 0) return(rv); if (rsp.m_data[0] != 0) rv = rsp.m_data[0]; /*comp code*/ return(rv); } /*end of ipmi_mc_vendor_intel.cpp */
29.859008
109
0.605981
[ "object" ]
a0aaca9f13a91d6f753cf69c52120a5b63addb77
675
cpp
C++
snippets/cpp/VS_Snippets_WebNet/ControlAdapter_Browser/CPP/controladapter_browser.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
2
2020-03-12T19:26:36.000Z
2022-01-10T21:45:33.000Z
snippets/cpp/VS_Snippets_WebNet/ControlAdapter_Browser/CPP/controladapter_browser.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
555
2019-09-23T22:22:58.000Z
2021-07-15T18:51:12.000Z
snippets/cpp/VS_Snippets_WebNet/ControlAdapter_Browser/CPP/controladapter_browser.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
3
2020-01-29T16:31:15.000Z
2021-08-24T07:00:15.000Z
// <snippet1> #using <System.Web.dll> #using <System.dll> using namespace System; using namespace System::Web::UI; using namespace System::Web::UI::Adapters; public ref class CustomControlAdapter: public ControlAdapter { protected: virtual void Render( HtmlTextWriter^ writer ) override { // Access Browser details through the Browser property. Version^ jScriptVersion = Browser->JScriptVersion; // Test if the browser supports Javascript. if ( jScriptVersion != nullptr ) { // Render JavaScript-aware markup. } else { // Render scriptless markup. } } }; // </snippet1> void main(){}
21.774194
61
0.648889
[ "render" ]
a0ab1f63666ac32bd6801f7f7b58fcbd31ae39f5
5,612
hpp
C++
rank.hpp
herumi/opti
65b84ef788faef5511e9943542804ea3508b7ac0
[ "BSD-3-Clause" ]
15
2015-02-24T12:37:56.000Z
2021-03-23T11:49:57.000Z
rank.hpp
herumi/opti
65b84ef788faef5511e9943542804ea3508b7ac0
[ "BSD-3-Clause" ]
null
null
null
rank.hpp
herumi/opti
65b84ef788faef5511e9943542804ea3508b7ac0
[ "BSD-3-Clause" ]
6
2015-02-15T16:26:46.000Z
2020-11-18T12:54:42.000Z
#pragma once #include <vector> #include <assert.h> #include <stddef.h> #include "v128.h" #define XBYAK_NO_OP_NAMES #include <xbyak/xbyak.h> namespace mie { class BitVector { size_t bitSize_; std::vector<uint64_t> v_; public: BitVector() : bitSize_(0) { } void resize(size_t bitSize) { bitSize_ = bitSize; v_.resize((bitSize + 63) / 64); } bool get(size_t idx) const { size_t q = idx / 64; size_t r = idx % 64; return (v_[q] & (1ULL << r)) != 0; } void set(size_t idx, bool b) { size_t q = idx / 64; size_t r = idx % 64; uint64_t v = v_[q]; v &= ~(1ULL << r); if (b) v |= (1ULL << r); v_[q] = v; } size_t size() const { return bitSize_; } const uint64_t *getBlock() const { return &v_[0]; } uint64_t *getBlock() { return &v_[0]; } size_t getBlockSize() const { return v_.size(); } void put() const { printf(">%016llx:%016llx:%016llx:%016llx\n", (long long)v_[3], (long long)v_[2], (long long)v_[1], (long long)v_[0]); } }; namespace succ_impl { struct Block { uint32_t rank; union { uint8_t s8[4]; uint32_t s; } ci; uint64_t data[8]; }; struct Code : Xbyak::CodeGenerator { Code(char *buf, size_t size) try : Xbyak::CodeGenerator(size, buf) { Xbyak::CodeArray::protect(buf, size, true); gen_rank1(); } catch (std::exception& e) { printf("ERR:%s\n", e.what()); ::exit(1); } private: /* rank1(const Block *blk, size_t idx); */ void gen_rank1() { using namespace Xbyak; #ifdef XBYAK32 #error "not implemented for 32-bit version" #endif #ifdef XBYAK64_WIN const Reg64& blk = r8; const Reg32& idx = edx; mov(r8, rcx); #else const Reg64& blk = rdi; const Reg32& idx = esi; #endif const Reg64& mask = r9; const Reg64& m0 = r11; const Xmm& zero = xm0; const Xmm& v = xm1; mov(ecx, idx); and_(ecx, 63); xor_(eax, eax); inc(eax); shl(rax, cl); sub(rax, 1); mov(mask, rax); mov(eax, idx); shr(eax, 9); imul(eax, eax, sizeof(succ_impl::Block)); add(blk, rax); mov(rcx, idx); shr(ecx, 7); and_(ecx, 3); // q shl(ecx, 3); // q * 8 or_(m0, uint32_t(-1)); and_(idx, 64); cmovz(m0, mask); // m0 = !(idx & 64) ? mask : -1 cmovz(mask, idx); // mask = (idx & 64) ? 0(=idx) : mask // idx is free, so use edx and_(m0, ptr [blk + offsetof(succ_impl::Block, data) + rcx * 2 + 0]); and_(mask, ptr [blk + offsetof(succ_impl::Block, data) + rcx * 2 + 8]); popcnt(m0, m0); popcnt(rax, mask); add(rax, m0); mov(edx, 1); add(eax, ptr [blk + offsetof(succ_impl::Block, rank)]); shl(edx, cl); sub(edx, 1); and_(edx, ptr [blk + offsetof(succ_impl::Block, ci.s)]); movd(v, edx); pxor(zero, zero); psadbw(v, zero); movd(edx, v); add(eax, edx); ret(); } }; template<int dummy = 0> struct InstanceIsHere { static MIE_ALIGN(4096) char buf[4096]; static Code code; }; template<int dummy> Code InstanceIsHere<dummy>::code(buf, sizeof(buf)); template<int dummy> char InstanceIsHere<dummy>::buf[4096]; struct DummyCall { DummyCall() { InstanceIsHere<>::code.getCode(); } }; } // mie::succ_impl /* extra memory (32 + 8 * 4) / 256 = 1/4 */ struct SBV1 { struct B { uint64_t org[4]; uint32_t a; uint8_t b[4]; }; std::vector<B> blk_; uint64_t popCount64(uint64_t x) const { return _mm_popcnt_u64(x); } public: SBV1() { } SBV1(const uint64_t *blk, size_t blkNum) { init(blk, blkNum); } void init(const uint64_t *blk, size_t blkNum) { size_t tblNum = (blkNum + 3) / 4; blk_.resize(tblNum); uint32_t av = 0; size_t pos = 0; for (size_t i = 0; i < tblNum; i++) { B& b = blk_[i]; b.a = av; uint32_t bv = 0; for (size_t j = 0; j < 4; j++) { uint64_t v = pos < blkNum ? blk[pos++] : 0; b.org[j] = v; int c = (int)popCount64(v); av += c; b.b[j] = (uint8_t)bv; bv += c; } } } uint32_t rank1(size_t i) const { if (i == 0) return 0; size_t q = i / 256; size_t r = (i / 64) & 3; const B& b = blk_[q]; return uint32_t(b.a + b.b[r] + popCount64(b.org[r] & ((1ULL << (i & 63)) - 1))); } }; /* extra memory (32 + 8 * 4) / 512 = 1/8 */ class SBV2 { AlignedArray<succ_impl::Block> blk_; public: SBV2() { } SBV2(const uint64_t *blk, size_t blkNum) { init(blk, blkNum); } uint64_t rank1(size_t idx) const { return rank1m(idx); } uint64_t rank1m(size_t idx) const { #if 1 return ((uint64_t (*)(const succ_impl::Block*, size_t))((char*)succ_impl::InstanceIsHere<>::buf))(&blk_[0], idx); #else const uint64_t mask = (uint64_t(1) << (idx & 63)) - 1; const succ_impl::Block& blk = blk_[idx / 512]; uint64_t ret = blk.rank; uint64_t q = (idx / 128) % 4; uint64_t b0 = blk.data[q * 2 + 0]; uint64_t b1 = blk.data[q * 2 + 1]; uint64_t m0 = (idx & 64) ? -1 : mask; uint64_t m1 = (idx & 64) ? mask : 0; ret += popCount64(b0 & m0); ret += popCount64(b1 & m1); uint32_t x = blk.ci.s & ((1U << (q * 8)) - 1); V128 v(x); v = psadbw(v, Zero()); ret += movd(v); return ret; #endif } uint64_t select1(uint64_t) const { return 0; } uint64_t popCount64(uint64_t x) const { return _mm_popcnt_u64(x); } void init(const uint64_t *blk, size_t blkNum) { size_t tblNum = (blkNum + 7) / 8; blk_.resize(tblNum); uint32_t r = 0; size_t pos = 0; for (size_t i = 0; i < tblNum; i++) { succ_impl::Block& b = blk_[i]; b.rank = r; uint8_t s8 = 0; for (size_t j = 0; j < 4; j++) { uint64_t vL = pos < blkNum ? blk[pos++] : 0; uint64_t vH = pos < blkNum ? blk[pos++] : 0; b.data[j * 2 + 0] = vL; b.data[j * 2 + 1] = vH; s8 = uint8_t(popCount64(vL) + popCount64(vH)); b.ci.s8[j] = s8; r += s8; } } } }; } // mie
20.114695
119
0.583393
[ "vector" ]
a0abe0b70c039cb994a04fc6f20b4862c5cb780d
23,953
cpp
C++
test/src/tc/ca/gtest/src/btc/CATest.cpp
jonghenhan/iotivity
7dfc2bc6a5c0506cf88bc23e88e38fe1b795da31
[ "Apache-2.0" ]
301
2015-01-20T16:11:32.000Z
2021-11-25T04:29:36.000Z
test/src/tc/ca/gtest/src/btc/CATest.cpp
jonghenhan/iotivity
7dfc2bc6a5c0506cf88bc23e88e38fe1b795da31
[ "Apache-2.0" ]
13
2015-06-04T09:55:15.000Z
2020-09-23T00:38:07.000Z
test/src/tc/ca/gtest/src/btc/CATest.cpp
jonghenhan/iotivity
7dfc2bc6a5c0506cf88bc23e88e38fe1b795da31
[ "Apache-2.0" ]
233
2015-01-26T03:41:59.000Z
2022-03-18T23:54:04.000Z
/****************************************************************** * * Copyright 2016 Samsung Electronics 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 "CAHelper.h" class CATest_btc: public ::testing::Test { protected: CAHelper m_caHelper; virtual void SetUp() { CommonTestUtil::runCommonTCSetUpPart(); } virtual void TearDown() { CommonTestUtil::runCommonTCTearDownPart(); } }; /** * @since 2014-11-28 * @see void CATerminate() * @objective Test 'CAInitialize' positively to initialize CA module * @target CAResult_t CAInitialize() * @test_data none * @pre_condition none * @procedure call CAInitialize() API * @post_condition Terminate CA using CATerminate() API * @expected Initialization will succeed and return CA_STATUS_OK */ #if defined(__LINUX__) || defined(__TIZEN__) || defined(__ANDROID__) || defined(__WINDOWS__) TEST_F(CATest_btc , CAInitialize_P) { if (!m_caHelper.initialize()) { SET_FAILURE(m_caHelper.getFailureMessage()); return; } CATerminate(); } #endif /** * @since 2014-12-01 * @see CAResult_t CAInitialize() * @see void CATerminate() * @objective Test 'CARegisterHandler' positively to register request & response handlers * @target void CARegisterHandler(CARequestCallback ReqHandler, CAResponseCallback RespHandler, CAErrorCallback ErrorHandler) * @test_data 1. A request handler * 2. A response handler * 2. A error handler * @pre_condition Initialize CA using CAInitialize() * @procedure call Call CARegisterHandler() API with request,response and error handlers as arguments * @post_condition Terminate CA using CATerminate() API * @expected CARegisterHandler() will register the handlers */ #if defined(__LINUX__) || defined(__TIZEN__) || defined(__ANDROID__) || defined(__WINDOWS__) TEST_F(CATest_btc , CARegisterHandler_P) { if (!m_caHelper.initialize()) { SET_FAILURE(m_caHelper.getFailureMessage()); return; } CARegisterHandler(CAHelper::requestHandler, CAHelper::responseHandler, CAHelper::errorHandler); CATerminate(); } #endif /** * @since 2014-11-28 * @see void CADestroyToken(CAToken_t token) * @objective Test 'CAGenerateToken' positively to generate a token * @target CAResult_t CAGenerateToken(CAToken_t *token, uint8_t tokenLength) * @test_data a pointer of the type CAToken_t and token length * @pre_condition none * @procedure call the CAGenerateToken() API with passing a reference to the token and uint8_t length to tokenLength as argument * @post_condition Destroy token using CADestroyToken. * @expected 1. It will generate a token and return CA_STATUS_OK * 2. Token variable is not NULL */ #if defined(__LINUX__) || defined(__TIZEN__) || defined(__ANDROID__) || defined(__WINDOWS__) TEST_F(CATest_btc , CAGenerateToken_P) { if (!m_caHelper.generateToken()) { SET_FAILURE(m_caHelper.getFailureMessage()); CATerminate(); return; } m_caHelper.destroyToken(); } #endif /** * @since 2016-02-18 * @see void CADestroyToken(CAToken_t token) * @objective Test 'CAGenerateToken' positively with lower boundary value in Token Length parameter [LBV] * @target CAResult_t CAGenerateToken(CAToken_t *token, uint8_t tokenLength) * @test_data Lower boundary value (1) as token length argument * @pre_condition none * @procedure Call CAGenerateToken with lower boundary value (1) as token length argument * @post_condition Destroy token using CADestroyToken. * @expected 1. It will generate a token and return CA_STATUS_OK * 2. Token variable is not NULL */ #if defined(__LINUX__) || defined(__TIZEN__) || defined(__ANDROID__) || defined(__WINDOWS__) TEST_F(CATest_btc , CAGenerateToken_LBV_P) { CAToken_t token = NULL; CAResult_t m_result = CAGenerateToken(&token, TOKEN_MIN_LENGTH ); if (token == NULL) { m_caHelper.m_failureMessage = "Failed to generate token."; SET_FAILURE(m_caHelper.getFailureMessage()); } if (m_result != CA_STATUS_OK) { SET_FAILURE(m_caHelper.getFailureMessage("CAGenerateToken", m_result, CA_STATUS_OK )); return; } CADestroyToken(token); } #endif /** * @since 2015-02-17 * @see none * @objective Test 'CAGenerateToken' negatively with out of lower bundary value in Token Length parameter [LOBV] * @target CAResult_t CAGenerateToken(CAToken_t *token, uint8_t tokenLength) * @test_data out of lower bundary value as token length argument * @pre_condition none * @procedure Call CAGenerateToken with out of lower boundary value in token length parameter * @post_condition none * @expected It will return CA_STATUS_INVALID_PARAM */ #if defined(__LINUX__) || defined(__TIZEN__) || defined(__ANDROID__) || defined(__WINDOWS__) TEST_F(CATest_btc , CAGenerateToken_LOBV_N) { CAToken_t token = NULL; CAResult_t result = CAGenerateToken(&token, TOKEN_LOBV_LENGTH); if (result != CA_STATUS_INVALID_PARAM) { SET_FAILURE(m_caHelper.getFailureMessage()); IOTIVITYTEST_LOG(ERROR, "CAGenerateToken, Returned: %s, Expected: %s", m_caHelper.getResultName(result), m_caHelper.getResultName(CA_STATUS_INVALID_PARAM)); } } #endif /** * @since 2015-02-17 * @see none * @objective Test 'CAGenerateToken' negatively with out of upper boundary value in Token Length parameter [UOBV] * @target CAResult_t CAGenerateToken(CAToken_t *token, uint8_t tokenLength) * @test_data out of upper boundary value as token length argument * @pre_condition none * @procedure Call CAGenerateToken with out of upper boundary value in token length parameter * @post_condition none * @expected It will return CA_STATUS_INVALID_PARAM */ #if defined(__LINUX__) || defined(__TIZEN__) || defined(__ANDROID__) || defined(__WINDOWS__) TEST_F(CATest_btc , CAGenerateToken_UOBV_N) { CAToken_t m_token = NULL; CAResult_t m_result = CAGenerateToken(&m_token, TOKEN_UOBV_LENGTH); if (m_result != CA_STATUS_INVALID_PARAM) { SET_FAILURE(m_caHelper.getFailureMessage()); IOTIVITYTEST_LOG(ERROR, "CAGenerateToken, Returned: %s, Expected: %s", m_caHelper.getResultName(m_result), m_caHelper.getResultName(CA_STATUS_INVALID_PARAM)); } } #endif /** * @since 2016-02-18 * @see none * @objective Test 'CAGenerateToken' negatively with passing invalid refrerence in token parameter [UFRV] * @target CAResult_t CAGenerateToken(CAToken_t *token, uint8_t tokenLength) * @test_data Invalid reference as token argument * @pre_condition none * @procedure Call CAGenerateToken with unformatted reference value in token type parameter * @post_condition none * @expected It will not generate token & will return CA_STATUS_INVALID_PARAM */ #if defined(__LINUX__) || defined(__TIZEN__) || defined(__ANDROID__) || defined(__WINDOWS__) TEST_F(CATest_btc , CAGenerateToken_UFRV_N) { CAToken_t *m_token = NULL; CAResult_t m_result = CAGenerateToken(m_token, TOKEN_MAX_LENGTH); if (m_result != CA_STATUS_INVALID_PARAM) { SET_FAILURE(m_caHelper.getFailureMessage("CAGenerateToken", m_result, CA_STATUS_INVALID_PARAM)); } } #endif /** * @since 2014-12-02 * @see none * @objective Test 'CAGenerateToken' negatively with passing NULL value as token argument * @target CAResult_t CAGenerateToken(CAToken_t *token, uint8_t tokenLength) * @test_data NULL as token argument * @pre_condition none * @procedure Call CAGenerateToken with NULL value as token argument * @post_condition none * @expected It will return CA_STATUS_INVALID_PARAM */ #if defined(__LINUX__) || defined(__TIZEN__) || defined(__ANDROID__) || defined(__WINDOWS__) TEST_F(CATest_btc , CAGenerateToken_N) { if (!m_caHelper.generateToken(CA_STATUS_INVALID_PARAM)) { SET_FAILURE(m_caHelper.getFailureMessage()); } } #endif /** * @since 2016-02-22 * @see CAResult_t CAInitialize() * @see void CATerminate() * @objective Test 'CASelectNetwork' positively with lower boundary value of selected network [LBV] * @target CAResult_t CASelectNetwork(CATransportAdapter_t interestedNetwork) * @test_data lower boundary value as network argument * @pre_condition Initialize CA using CAInitialize * @procedure 1. Call CASelectNetwork using lower boundary value as network argument * 2. Check it's return value * @post_condition Terminate CA using CATerminate function * @expected It will return CA_NOT_SUPPORTED */ #if defined(__LINUX__) || defined(__TIZEN__) || defined(__ANDROID__) || defined(__WINDOWS__) TEST_F(CATest_btc, CASelectNetwork_LBV_P) { if (!m_caHelper.initialize()) { SET_FAILURE(m_caHelper.getFailureMessage()); return; } if (!m_caHelper.selectNetwork(CA_DEFAULT_ADAPTER, CA_NOT_SUPPORTED)) { SET_FAILURE(m_caHelper.getFailureMessage()); } CATerminate(); } #endif /** * @since 2016-02-22 * @see CAResult_t CAInitialize() * @see void CATerminate() * @objective Test 'CASelectNetwork' positively with upper boundary value of selected network [UBV] * @target CAResult_t CASelectNetwork(CATransportAdapter_t interestedNetwork) * @test_data upper boundary value as network argument * @pre_condition Initialize CA using CAInitialize * @procedure 1. Call CASelectNetwork using upper boundary value as network argument * 2. Check it's return value * @post_condition Terminate CA using CATerminate function * @expected It will return CA_STATUS_OK */ #if defined(__LINUX__) || defined(__TIZEN__) || defined(__ANDROID__) || defined(__WINDOWS__) TEST_F(CATest_btc, CASelectNetwork_UBV_P) { if (!m_caHelper.initialize()) { SET_FAILURE(m_caHelper.getFailureMessage()); return; } if (!m_caHelper.selectNetwork(CA_ALL_ADAPTERS, CA_STATUS_OK)) { SET_FAILURE(m_caHelper.getFailureMessage()); } CATerminate(); } #endif /** * @since 2016-02-23 * @see CAResult_t CAInitialize() * @see void CATerminate() * @objective Test 'CASelectNetwork' negatively with out of lower boundary value of selected network [LOBV] * @target CAResult_t CASelectNetwork(CATransportAdapter_t interestedNetwork) * @test_data out of lower boundary value as Network argument * @pre_condition Initialize CA using CAInitialize * @procedure 1. Call CASelectNetwork using out of lower boundary value as network argument * 2. Check it's return value * @post_condition Terminate CA using CATerminate function * @expected It will return CA_NOT_SUPPORTED */ #if defined(__LINUX__) || defined(__TIZEN__) || defined(__ANDROID__) || defined(__WINDOWS__) TEST_F(CATest_btc, CASelectNetwork_LOBV_N) { if (!m_caHelper.initialize()) { SET_FAILURE(m_caHelper.getFailureMessage()); return; } IOTIVITYTEST_LOG(DEBUG, "[CASelectNetwork] IN "); m_caHelper.m_result = CASelectNetwork(CA_INVALID_ADAPTER); if (m_caHelper.m_result != CA_NOT_SUPPORTED) { SET_FAILURE(m_caHelper.getFailureMessage("CASelectNetwork", m_caHelper.m_result, CA_NOT_SUPPORTED)); } IOTIVITYTEST_LOG(DEBUG, "[CASelectNetwork] OUT "); CATerminate(); } #endif /** * @since 2016-02-23 * @see CAResult_t CAInitialize() * @see void CATerminate() * @objective Test 'CASelectNetwork' negatively with out of upper boundary value of selected network [UOBV] * @target CAResult_t CASelectNetwork(CATransportAdapter_t interestedNetwork) * @test_data upper boundary value as network argument * @pre_condition Initialize CA using CAInitialize * @procedure 1. Call CASelectNetwork using out of upper boundary value as network argument * 2. Check it's return value * @post_condition Terminate CA using CATerminate function * @expected It will return CA_NOT_SUPPORTED */ #if defined(__LINUX__) || defined(__TIZEN__) || defined(__ANDROID__) || defined(__WINDOWS__) TEST_F(CATest_btc, CASelectNetwork_UOBV_N) { if (!m_caHelper.initialize()) { SET_FAILURE(m_caHelper.getFailureMessage()); return; } if (!m_caHelper.selectNetwork(CA_INVALID_UOBV_ADAPTER, CA_NOT_SUPPORTED)) { SET_FAILURE(m_caHelper.getFailureMessage()); } CATerminate(); } #endif /** * @since 2014-12-04 * @see CAResult_t CAInitialize() * @see void CATerminate() * @objective Test 'CASelectNetwork' negatively to select invalid network * @target CAResult_t CASelectNetwork(CATransportAdapter_t interestedNetwork) * @test_data invalid value for which network interface is not defined * @pre_condition Initialize CA using CAInitialize * @procedure 1. Call CASelectNetwork using invalid network value * 2. Check it's return value * @post_condition Terminate CA using CATerminate function * @expected It will fail to select a network and will return CA_NOT_SUPPORTED */ #if defined(__LINUX__) || defined(__TIZEN__) || defined(__ANDROID__) || defined(__WINDOWS__) TEST_F(CATest_btc, CASelectNetwork_N) { if (!m_caHelper.initialize()) { SET_FAILURE(m_caHelper.getFailureMessage()); return; } if (!m_caHelper.selectNetwork(NETWORK_OUT_OF_BOUNDARY_VALUE, CA_NOT_SUPPORTED)) { SET_FAILURE(m_caHelper.getFailureMessage()); } CATerminate(); } #endif /** * @since 2016-02-23 * @see CAResult_t CAInitialize() * @see CAResult_t CASelectNetwork(const uint32_t interestedNetwork) * @see void CATerminate() * @objective Test 'CAUnSelectNetwork' positively with upper boundary value of selected network [UBV] * @target CAResult_t CAUnSelectNetwork(CATransportAdapter_t nonInterestedNetwork) * @test_data upper boundary value as Network argument * @pre_condition Initialize CA using CAInitialize * @procedure 1. Call CASelectNetwork using upper boundary value as network argument * 2. Check it's return value * 3. Call CAUnselectNetwork using upper boundary value value as network argument * 4. Check it's return value * @post_condition Terminate CA using CATerminate function * @expected It will unselect the network and will return CA_STATUS_OK */ #if defined(__LINUX__) || defined(__TIZEN__) || defined(__ANDROID__) || defined(__WINDOWS__) TEST_F(CATest_btc, CAUnSelectNetwork_UBV_P) { if (!m_caHelper.initialize()) { SET_FAILURE(m_caHelper.getFailureMessage()); return; } if (!m_caHelper.selectNetwork(CA_ALL_ADAPTERS, CA_STATUS_OK)) { SET_FAILURE(m_caHelper.getFailureMessage()); CATerminate(); return; } if (!m_caHelper.unselectNetwork(CA_ALL_ADAPTERS, CA_STATUS_OK)) { SET_FAILURE(m_caHelper.getFailureMessage()); } CATerminate(); } #endif /** * @since 2014-11-28 * @see CAResult_t CAInitialize() * @see void CATerminate() * @objective Test 'CAUnSelectNetwork' negatively to un-select invalid network * @target CAResult_t CAUnSelectNetwork(CATransportAdapter_t nonInterestedNetwork) * @test_data invalid value for which adapter is not defined * @pre_condition Initialize CA using CAInitialize * @procedure 1. Call CAUnSelectNetwork with invalid adapter * 2. Check it's return value * @post_condition Terminate CA using CATerminate * @expected It will fail to un-select the network and will return CA_STATUS_FAILED */ #if defined(__LINUX__) || defined(__TIZEN__) || defined(__ANDROID__) || defined(__WINDOWS__) TEST_F(CATest_btc, CAUnSelectNetwork_N) { if (!m_caHelper.initialize()) { SET_FAILURE(m_caHelper.getFailureMessage()); return; } if (!m_caHelper.unselectNetwork(NETWORK_OUT_OF_BOUNDARY_VALUE, CA_STATUS_FAILED)) { SET_FAILURE(m_caHelper.getFailureMessage()); } CATerminate(); } #endif /** * @since 2014-12-02 * @see CAResult_t CAInitialize() * @see void CATerminate() * @objective Test CAHandleRequestResponse() API positively * @target CAResult_t CAHandleRequestResponse() * @test_data none * @pre_condition Initialize CA using CAInitialize() * @procedure 1. Call CAHandleRequestResponse() API * 2. Check it's return value * @post_condition Terminate CA using CATerminate() * @expected CAHandleRequestResponse() will return CA_STATUS_OK */ #if defined(__LINUX__) || defined(__TIZEN__) || defined(__ANDROID__) || defined(__WINDOWS__) TEST_F(CATest_btc , CAHandleRequestResponse_P) { if (!m_caHelper.initialize()) { SET_FAILURE(m_caHelper.getFailureMessage()); return; } CAResult_t result = CAHandleRequestResponse(); if (result != CA_STATUS_OK) { SET_FAILURE(m_caHelper.getFailureMessage("CAHandleRequestResponse", result, CA_STATUS_OK)); } CATerminate(); } #endif /** * @since 2016-02-23 * @see CAResult_t CAInitialize() * @see void CATerminate() * @objective Test 'CAStartListeningServer' without selecting a network [ECRC] * @target CAResult_t CAStartListeningServer() * @test_data none * @pre_condition 1. Initialize CA using CAInitialize * 2. Do not select network * @procedure 1. Call CAStartListeningServer API * 2. Check it's return value * @post_condition Terminate CA using CATerminate * @expected It will return CA_STATUS_FAILED */ #if defined(__LINUX__) || defined(__TIZEN__) || defined(__ANDROID__) || defined(__WINDOWS__) TEST_F(CATest_btc, CAStartListeningServerWithoutSelectingNetwork_ECRC_N) { if (!m_caHelper.initialize()) { SET_FAILURE(m_caHelper.getFailureMessage()); return; } if (!m_caHelper.startListeningServer(CA_STATUS_FAILED)) { SET_FAILURE(m_caHelper.getFailureMessage()); } CATerminate(); } #endif /** * @since 2015-02-16 * @see CAResult_t CAInitialize() * @see void CATerminate() * @objective Test 'CAStopListeningServer' negatively without SelectingNetwork [ECRC] * @target CAResult_t CAStopListeningServer() * @test_data none * @pre_condition Initialize CA using CAInitialize * @procedure 1. Call the CAStopListeningServer API * 2. Check it's return value * @post_condition Terminate CA using CATerminate * @expected It will return CA_STATUS_FAILED */ #if defined(__LINUX__) || defined(__TIZEN__) || defined(__ANDROID__) || defined(__WINDOWS__) TEST_F(CATest_btc, CAStopListeningServerWithoutSelectingNetwork_ECRC_N) { if (!m_caHelper.initialize()) { SET_FAILURE(m_caHelper.getFailureMessage()); return; } if (!m_caHelper.stopListeningServer(CA_STATUS_FAILED)) { SET_FAILURE(m_caHelper.getFailureMessage()); } CATerminate(); } #endif /** * @since 2016-02-24 * @see CAResult_t CAInitialize() * @see void CATerminate() * @objective Test 'CAStartDiscoveryServer' without selecting a network [ECRC] * @target CAResult_t CAStartDiscoveryServer() * @test_data none * @pre_condition 1. Initialize CA using CAInitialize * 2. Do not select network * @procedure 1. Call the CAStartDiscoveryServer API * 2. Check it's return value * @post_condition Terminate CA using CATerminate * @expected It will return CA_STATUS_FAILED */ #if defined(__LINUX__) || defined(__TIZEN__) || defined(__ANDROID__) || defined(__WINDOWS__) TEST_F(CATest_btc, CAStartDiscoveryServerWithoutSelectingNetwork_ECRC_N) { if (!m_caHelper.initialize()) { SET_FAILURE(m_caHelper.getFailureMessage()); return; } if (!m_caHelper.startDiscoveryServer(CA_STATUS_FAILED)) { SET_FAILURE(m_caHelper.getFailureMessage()); } CATerminate(); } #endif /** * @since 2016-02-24 * @see none * @objective Test 'CACreateEndpoint' to check against negative value in Adapter [adapter-ECRC] * @target CAResult_t CACreateEndpoint(CATransportFlags_t flags, CATransportAdapter_t adapter, const char *addr, * uint16_t port, CAEndpoint_t **object) * @test_data Invalid adapter * @pre_condition none * @procedure 1. call the CACreateEndpoint API and pass the invalid value as adapter arguments * 2. Check it's return value * @post_condition none * @expected It will fail to create end point and return CA_STATUS_OK */ #if defined(__LINUX__) || defined(__TIZEN__) || defined(__ANDROID__) || defined(__WINDOWS__) TEST_F(CATest_btc, CACreateEndpoint_Adapter_ECRC_N) { CAEndpoint_t* m_endpoint = NULL; CAResult_t m_result = CACreateEndpoint(CA_DEFAULT_FLAGS, CA_INVALID_ADAPTER, ENDPOINT_IP, ENDPOINT_PORT, &m_endpoint); if (m_result != CA_STATUS_OK) { SET_FAILURE(m_caHelper.getFailureMessage("CACreateEndpoint", m_result, CA_STATUS_OK)); } } #endif /** * @since 2016-02-25 * @see none * @objective Test 'CADestroyEndpoint' negatively to check with NULL value [NV] * @target void CADestroyEndpoint(CAEndpoint_t *object) * @test_data NULL value in endpoint * @pre_condition none * @procedure 1. call the CADestroyEndpoint API and pass the NULL value * 2. Check it's return value * @post_condition none * @expected It will invoke the API without any error/exception */ #if defined(__LINUX__) || defined(__TIZEN__) || defined(__ANDROID__) || defined(__WINDOWS__) TEST_F(CATest_btc, CADestroyEndpoint_NV_N) { CADestroyEndpoint(NULL); } #endif #ifdef __WITH_DTLS__ /** * @since 2015-02-02 * @see CAResult_t CAInitialize() * @see void CATerminate() * @objective Test CAregisterPskCredentialsHandler return value when a valid handler is registered * @target CAResult_t CAregisterPskCredentialsHandler(CAGetDTLSPskCredentialsHandler GetDTLSCredentials) * @test_data OCDtlsPskCredsBlob object * @pre_condition Initialize CA using CAInitialize * @procedure call 1. Call CAregisterPskCredentialsHandler * 2. Check it's return value * @post_condition Terminate CA using CATerminate * @expected CAregisterPskCredentialsHandler return value will be CA_STATUS_OK */ #if defined(__LINUX__) || defined(__TIZEN__) || defined(__ANDROID__) || defined(__WINDOWS__) TEST_F(CATest_btc, RegisterDtls_P) { if (!m_caHelper.initialize()) { SET_FAILURE(m_caHelper.getFailureMessage()); return; } if(!m_caHelper.setDtls()) { SET_FAILURE(m_caHelper.getFailureMessage()); } CATerminate(); } #endif /** * @since 2015-02-04 * @see CAResult_t CAInitialize() * @see void CATerminate() * @objective Test CAregisterPskCredentialsHandler return value when a invalid handler is registered * @target CAResult_t CAregisterPskCredentialsHandler(CAGetDTLSPskCredentialsHandler GetDTLSCredentials) * @test_data NULL as GetDTLSCredentials * @pre_condition Initialize CA using CAInitialize * @procedure call 1. Call CAregisterPskCredentialsHandler with NULL handler * 2. Check it's return value * @post_condition Terminate CA using CATerminate * @expected CAregisterPskCredentialsHandler return value won't be CA_STATUS_OK */ #if defined(__LINUX__) || defined(__TIZEN__) || defined(__ANDROID__) || defined(__WINDOWS__) TEST_F(CATest_btc, RegisterDtlsCredentialsWithNullHandler_N) { if (!m_caHelper.initialize()) { SET_FAILURE(m_caHelper.getFailureMessage()); return; } CAResult_t result = CAregisterPskCredentialsHandler(NULL); if (result != CA_STATUS_OK) { SET_FAILURE("CAregisterPskCredentialsHandler not returned CA_STATUS_OK with NULL handler"); } CATerminate(); } #endif #endif
33.268056
167
0.725963
[ "object" ]
a0aee7fabe4c2bb92ff760b43612bd688e1bb86a
4,026
hpp
C++
hecl/include/hecl/Console.hpp
BoofOof32/metaforce
b4b0083aedb90cc5ad2b40ca06bd204235684b73
[ "MIT" ]
267
2016-03-10T21:59:16.000Z
2021-03-28T18:21:03.000Z
hecl/include/hecl/Console.hpp
cobalt2727/metaforce
3bb05c0ee5dd9b1b8eaa861fc49713aef62c844a
[ "MIT" ]
129
2016-03-12T10:17:32.000Z
2021-04-05T20:45:19.000Z
hecl/include/hecl/Console.hpp
cobalt2727/metaforce
3bb05c0ee5dd9b1b8eaa861fc49713aef62c844a
[ "MIT" ]
31
2016-03-20T00:20:11.000Z
2021-03-10T21:14:11.000Z
#pragma once #include <functional> #include <string> #include <unordered_map> #include <vector> #include <boo/System.hpp> #include <logvisor/logvisor.hpp> namespace boo { class IWindow; enum class EModifierKey; enum class ESpecialKey; struct IGraphicsCommandQueue; } // namespace boo namespace hecl { class CVarManager; class CVar; struct SConsoleCommand { enum class ECommandFlags { Normal = 0, Cheat = (1 << 0), Developer = (1 << 1) }; std::string m_displayName; std::string m_helpString; std::string m_usage; std::function<void(class Console*, const std::vector<std::string>&)> m_func; ECommandFlags m_flags; }; ENABLE_BITWISE_ENUM(SConsoleCommand::ECommandFlags) class Console { friend class LogVisorAdapter; struct LogVisorAdapter : logvisor::ILogger { Console* m_con; LogVisorAdapter(Console* con) : logvisor::ILogger(log_typeid(LogVisorAdapter)), m_con(con) {} ~LogVisorAdapter() override = default; void report(const char* modName, logvisor::Level severity, fmt::string_view format, fmt::format_args args) override; void report(const char* modName, logvisor::Level severity, fmt::wstring_view format, fmt::wformat_args args) override; void reportSource(const char* modName, logvisor::Level severity, const char* file, unsigned linenum, fmt::string_view format, fmt::format_args args) override; void reportSource(const char* modName, logvisor::Level severity, const char* file, unsigned linenum, fmt::wstring_view format, fmt::wformat_args args) override; }; public: static Console* m_instance; enum class Level { Info, /**< Non-error informative message */ Warning, /**< Non-error warning message */ Error, /**< Recoverable error message */ Fatal /**< Non-recoverable error message (Kept for compatibility with logvisor) */ }; enum class State { Closed, Closing, Opened, Opening }; private: CVarManager* m_cvarMgr = nullptr; boo::IWindow* m_window = nullptr; std::unordered_map<std::string, SConsoleCommand> m_commands; std::vector<std::pair<std::string, Level>> m_log; int m_logOffset = 0; std::string m_commandString; std::vector<std::string> m_commandHistory; int m_cursorPosition = -1; int m_currentCommand = -1; size_t m_maxLines = 0; bool m_overwrite : 1; bool m_cursorAtEnd : 1; State m_state = State::Closed; CVar* m_conSpeed; CVar* m_conHeight; bool m_showCursor = true; float m_cursorTime = 0.f; public: Console(CVarManager*); void registerCommand(std::string_view name, std::string_view helpText, std::string_view usage, std::function<void(Console*, const std::vector<std::string>&)>&& func, SConsoleCommand::ECommandFlags cmdFlags = SConsoleCommand::ECommandFlags::Normal); void unregisterCommand(std::string_view name); void executeString(const std::string& strToExec); void help(Console* con, const std::vector<std::string>& args); void listCommands(Console* con, const std::vector<std::string>& args); bool commandExists(std::string_view cmd) const; void vreport(Level level, fmt::string_view format, fmt::format_args args); template <typename S, typename... Args, typename Char = fmt::char_t<S>> void report(Level level, const S& format, Args&&... args) { vreport(level, fmt::to_string_view<Char>(format), fmt::basic_format_args<fmt::buffer_context<Char>>( fmt::make_args_checked<Args...>(format, args...))); } void init(boo::IWindow* ctx); void proc(); void draw(boo::IGraphicsCommandQueue* gfxQ); void handleCharCode(unsigned long chr, boo::EModifierKey mod, bool repeat); void handleSpecialKeyDown(boo::ESpecialKey sp, boo::EModifierKey mod, bool repeat); void handleSpecialKeyUp(boo::ESpecialKey sp, boo::EModifierKey mod); void dumpLog(); static Console* instance(); static void RegisterLogger(Console* con); bool isOpen() const { return m_state == State::Opened; } }; } // namespace hecl
35.946429
120
0.706408
[ "vector" ]
a0af0af278d1a3c65f649e791f59fd71d39ea58d
9,374
cpp
C++
drishti/clipgrabber.cpp
shouhengli/drishti
46558d12adcc1d365b7e2125d28190e3be2181c3
[ "MIT" ]
null
null
null
drishti/clipgrabber.cpp
shouhengli/drishti
46558d12adcc1d365b7e2125d28190e3be2181c3
[ "MIT" ]
null
null
null
drishti/clipgrabber.cpp
shouhengli/drishti
46558d12adcc1d365b7e2125d28190e3be2181c3
[ "MIT" ]
null
null
null
#include "global.h" #include "clipgrabber.h" #include "staticfunctions.h" #include "matrix.h" ClipGrabber::ClipGrabber() { m_lastX = m_lastY = -1; m_pressed = false; m_pointPressed = -1; } ClipGrabber::~ClipGrabber() { removeFromMouseGrabberPool(); } int ClipGrabber::pointPressed() { return m_pointPressed; } void ClipGrabber::mousePosition(int& x, int& y) { x = m_lastX; y = m_lastY; } bool ClipGrabber::xActive(const Camera* const camera, Vec pos, Vec pp, bool &flag) { Vec tang = m_tang; Vec xaxis = m_xaxis; Vec yaxis = m_yaxis; tang = Matrix::rotateVec(m_xform, tang); xaxis = Matrix::rotateVec(m_xform, xaxis); yaxis = Matrix::rotateVec(m_xform, yaxis); float s1 = tscale1(); float s2 = tscale2(); Vec c0, ca, cb, c1; c0 = pos + s1*xaxis; c0 = camera->projectedCoordinatesOf(c0); c0 = Vec(c0.x, c0.y, 0); c1 = pos - s1*xaxis; c1 = camera->projectedCoordinatesOf(c1); c1 = Vec(c1.x, c1.y, 0); ca = pos - 0.2*s2*yaxis; ca = camera->projectedCoordinatesOf(ca); ca = Vec(ca.x, ca.y, 0); cb = pos + 0.2*s2*yaxis; cb = camera->projectedCoordinatesOf(cb); cb = Vec(cb.x, cb.y, 0); flag = StaticFunctions::inTriangle(ca, cb, c0, pp); return (flag || StaticFunctions::inTriangle(ca, cb, c1, pp)); } bool ClipGrabber::yActive(const Camera* const camera, Vec pos, Vec pp, bool &flag) { Vec tang = m_tang; Vec xaxis = m_xaxis; Vec yaxis = m_yaxis; tang = Matrix::rotateVec(m_xform, tang); xaxis = Matrix::rotateVec(m_xform, xaxis); yaxis = Matrix::rotateVec(m_xform, yaxis); float s1 = tscale1(); float s2 = tscale2(); Vec c0, ca, cb, c1; c0 = pos + s2*yaxis; c0 = camera->projectedCoordinatesOf(c0); c0 = Vec(c0.x, c0.y, 0); c1 = pos - s2*yaxis; c1 = camera->projectedCoordinatesOf(c1); c1 = Vec(c1.x, c1.y, 0); ca = pos - 0.2*s1*xaxis; ca = camera->projectedCoordinatesOf(ca); ca = Vec(ca.x, ca.y, 0); cb = pos + 0.2*s1*xaxis; cb = camera->projectedCoordinatesOf(cb); cb = Vec(cb.x, cb.y, 0); flag = StaticFunctions::inTriangle(ca, cb, c0, pp); return (flag || StaticFunctions::inTriangle(ca, cb, c1, pp)); } bool ClipGrabber::zActive(const Camera* const camera, Vec pos, Vec pp) { Vec tang = m_tang; Vec xaxis = m_xaxis; Vec yaxis = m_yaxis; tang = Matrix::rotateVec(m_xform, tang); xaxis = Matrix::rotateVec(m_xform, xaxis); yaxis = Matrix::rotateVec(m_xform, yaxis); float s1 = tscale1(); float s2 = tscale2(); float r = size(); Vec c0, cax, cbx, cay, cby; c0 = pos + r*tang; c0 = camera->projectedCoordinatesOf(c0); c0 = Vec(c0.x, c0.y, 0); cax = pos - 0.2*s1*xaxis; cax = camera->projectedCoordinatesOf(cax); cax = Vec(cax.x, cax.y, 0); cbx = pos + 0.2*s1*xaxis; cbx = camera->projectedCoordinatesOf(cbx); cbx = Vec(cbx.x, cbx.y, 0); cay = pos - 0.2*s2*yaxis; cay = camera->projectedCoordinatesOf(cay); cay = Vec(cay.x, cay.y, 0); cby = pos + 0.2*s2*yaxis; cby = camera->projectedCoordinatesOf(cby); cby = Vec(cby.x, cby.y, 0); return (StaticFunctions::inTriangle(cax, cbx, c0, pp) || StaticFunctions::inTriangle(cay, cby, c0, pp)); } void ClipGrabber::checkIfGrabsMouse(int x, int y, const Camera* const camera) { if (m_pressed) { // mouse button pressed so keep grabbing setActive(true); setGrabsMouse(true); return; } int sz = 20; m_lastX = x; m_lastY = y; Vec voxelScaling = Global::voxelScaling(); Vec pos = VECPRODUCT(position(), voxelScaling); pos = Matrix::xformVec(m_xform, pos); Vec pp = Vec(x, y, 0); bool flag; if (xActive(camera, pos, pp, flag) || yActive(camera, pos, pp, flag) || zActive(camera, pos, pp)) { setActive(true); setGrabsMouse(true); return; } setActive(false); setGrabsMouse(false); } void ClipGrabber::mousePressEvent(QMouseEvent* const event, Camera* const camera) { m_pointPressed = -1; m_pressed = true; m_prevPos = event->pos(); Vec voxelScaling = Global::voxelScaling(); Vec pp = Vec(m_prevPos.x(), m_prevPos.y(), 0); Vec pos = VECPRODUCT(position(), voxelScaling); pos = Matrix::xformVec(m_xform, pos); bool flag; if (xActive(camera, pos, pp, flag)) { if (flag) setMoveAxis(MoveX0); else setMoveAxis(MoveX1); emit selectForEditing(); return; } else if (yActive(camera, pos, pp, flag)) { if (flag) setMoveAxis(MoveY0); else setMoveAxis(MoveY1); emit selectForEditing(); return; } else if (zActive(camera, pos, pp)) { setMoveAxis(MoveZ); emit selectForEditing(); return; } } void ClipGrabber::mouseMoveEvent(QMouseEvent* const event, Camera* const camera) { if (!m_pressed) return; QPoint delta = event->pos() - m_prevPos; Vec voxelScaling = Global::voxelScaling(); Vec tang = m_tang; Vec xaxis = m_xaxis; Vec yaxis = m_yaxis; tang = Matrix::rotateVec(m_xform, tang); xaxis = Matrix::rotateVec(m_xform, xaxis); yaxis = Matrix::rotateVec(m_xform, yaxis); if (event->buttons() != Qt::LeftButton) { tang = VECDIVIDE(tang, voxelScaling); xaxis = VECDIVIDE(xaxis, voxelScaling); yaxis = VECDIVIDE(yaxis, voxelScaling); Vec trans(delta.x(), -delta.y(), 0.0f); // Scale to fit the screen mouse displacement trans *= 2.0 * tan(camera->fieldOfView()/2.0) * fabs((camera->frame()->coordinatesOf(Vec(0,0,0))).z) / camera->screenHeight(); // Transform to world coordinate system. trans = camera->frame()->orientation().rotate(trans); Vec voxelScaling = Global::voxelScaling(); trans = VECDIVIDE(trans, voxelScaling); if (event->modifiers() & Qt::ControlModifier || event->modifiers() & Qt::MetaModifier) { if (moveAxis() < MoveY0) { float vx = trans*m_xaxis; if (moveAxis() == MoveX0) setScale1(scale1() + 0.05*vx); else setScale1(scale1() - 0.05*vx); } else if (moveAxis() < MoveZ) { float vy = trans*m_yaxis; if (moveAxis() == MoveY0) setScale2(scale2() + 0.05*vy); else setScale2(scale2() - 0.05*vy); } } else { if (moveAxis() < MoveY0) { float vx = trans*xaxis; trans = vx*xaxis; } else if (moveAxis() < MoveZ) { float vy = trans*yaxis; trans = vy*yaxis; } else if (moveAxis() == MoveZ) { float vz = trans*tang; if (qAbs(vz) < 0.1) { vz = trans.norm(); if (qAbs(delta.x()) > qAbs(delta.y())) vz = (delta.x() >= 0 ? 1 : -1); else vz = (delta.y() >= 0 ? 1 : -1); } trans = vz*tang; } translate(trans); } } else { bool ctrlOn = (event->modifiers() & Qt::ControlModifier || event->modifiers() & Qt::MetaModifier); if (moveAxis() == MoveZ && !ctrlOn) { Vec axis; axis = (delta.y()*camera->rightVector() + delta.x()*camera->upVector()); rotate(axis, qMax(qAbs(delta.x()), qAbs(delta.y()))); //rotate(camera->rightVector(), delta.y()); //rotate(camera->upVector(), delta.x()); } else { Vec axis; if (moveAxis() < MoveY0) axis = xaxis; else if (moveAxis() < MoveZ) axis = yaxis; else axis = tang; Vec voxelScaling = Global::voxelScaling(); Vec pos = VECPRODUCT(position(), voxelScaling); pos = Matrix::xformVec(m_xform, pos); float r = size(); Vec trans(delta.x(), delta.y(), 0.0f); Vec p0 = camera->projectedCoordinatesOf(pos); p0 = Vec(p0.x, p0.y, 0); Vec c0 = pos + r*axis; c0 = camera->projectedCoordinatesOf(c0); c0 = Vec(c0.x, c0.y, 0); Vec perp = c0-p0; perp = Vec(-perp.y, perp.x, 0); perp.normalize(); float angle = perp * trans; rotate(axis, angle); } // if (moveAxis() == MoveZ) // { // float ag; // if (qAbs(delta.x()) > qAbs(delta.y())) // ag = delta.x(); // else // ag = delta.y(); // rotate(camera->viewDirection(), ag); // } // else // Vec axis; // if (moveAxis() < MoveY0) axis = xaxis; // else if (moveAxis() < MoveZ) axis = yaxis; // else if (moveAxis() == MoveZ) axis = tang; // // Vec voxelScaling = Global::voxelScaling(); // Vec pos = VECPRODUCT(position(), voxelScaling); // pos = Matrix::xformVec(m_xform, pos); // // float r = size(); // Vec trans(delta.x(), -delta.y(), 0.0f); // // Vec p0 = camera->projectedCoordinatesOf(pos); p0 = Vec(p0.x, p0.y, 0); // Vec c0 = pos + r*axis; // c0 = camera->projectedCoordinatesOf(c0); c0 = Vec(c0.x, c0.y, 0); // Vec perp = c0-p0; // perp = Vec(-perp.y, perp.x, 0); // perp.normalize(); // // float angle = perp * trans; // rotate(axis, angle); } m_prevPos = event->pos(); } void ClipGrabber::mouseReleaseEvent(QMouseEvent* const event, Camera* const camera) { m_pressed = false; m_pointPressed = -1; setActive(false); emit deselectForEditing(); } void ClipGrabber::wheelEvent(QWheelEvent* const event, Camera* const camera) { int mag = event->delta()/8.0f/15.0f; if (event->modifiers() & Qt::ShiftModifier) { int tk = thickness(); tk = qBound(0, tk+mag, 100); setThickness(tk); } else { Vec tang = m_tang; tang = Matrix::rotateVec(m_xform, tang); translate(mag*tang); } }
23.852417
78
0.594197
[ "transform" ]
a0b7a24f120358f276de191bf63b78a40b00e13a
307
cpp
C++
noncopyable.cpp
ishansheth/ModernCpp-Exercises
c33d63ea9e6fe3115fbac51304a75292f32998cd
[ "MIT" ]
null
null
null
noncopyable.cpp
ishansheth/ModernCpp-Exercises
c33d63ea9e6fe3115fbac51304a75292f32998cd
[ "MIT" ]
null
null
null
noncopyable.cpp
ishansheth/ModernCpp-Exercises
c33d63ea9e6fe3115fbac51304a75292f32998cd
[ "MIT" ]
null
null
null
#include <iostream> class Noncopy{ protected: Noncopy(){} private: Noncopy(const Noncopy&); Noncopy& operator=(const Noncopy&); }; class File: public Noncopy{ public: File(){ std::cout<<"Creating file object"<<std::endl; } }; int main(){ File f; // not allowed File f2(f); }
9.59375
49
0.615635
[ "object" ]
a0b87237a167018a3774457bc664a38ae788fa7c
1,262
hpp
C++
src/points/Bezier/BezierPath.hpp
KasumiL5x/hadan
6d0a9f2243bfa1120988487343463f8163f0b149
[ "MIT" ]
1
2017-06-28T13:57:33.000Z
2017-06-28T13:57:33.000Z
src/points/Bezier/BezierPath.hpp
KasumiL5x/hadan
6d0a9f2243bfa1120988487343463f8163f0b149
[ "MIT" ]
null
null
null
src/points/Bezier/BezierPath.hpp
KasumiL5x/hadan
6d0a9f2243bfa1120988487343463f8163f0b149
[ "MIT" ]
null
null
null
// http://devmag.org.za/2011/04/05/bzier-curves-a-tutorial/ #ifndef __bezier_path__ #define __bezier_path__ #include <vector> #include <cc/Vec3.hpp> class BezierPath { public: BezierPath(); ~BezierPath(); void setControlPoints( const std::vector<cc::Vec3f>& newControlPoints ); const std::vector<cc::Vec3f> getControlPoints() const; void interpolate( const std::vector<cc::Vec3f>& segmentPoints, float scale ); void samplePoints( const std::vector<cc::Vec3f>& sourcePoints, float minSqrDist, float maxSqrDist, float scale ); cc::Vec3f calculateBezierPoint( int curveIndex, float t ); std::vector<cc::Vec3f> getDrawingPoints( unsigned int samples ); std::vector<cc::Vec3f> getDrawingPointsAlternate( unsigned int samples ); std::vector<cc::Vec3f> getDrawingPointsRecursive( unsigned int samples ); private: cc::Vec3f calculateBezierPoint( float t, const cc::Vec3f& p0, const cc::Vec3f& p1, const cc::Vec3f& p2, const cc::Vec3f& p3 ); std::vector<cc::Vec3f> findDrawingPoints( unsigned int curveIndex ); int findDrawingPoints( unsigned int curveIndex, float t0, float t1, std::vector<cc::Vec3f>& pointList, unsigned int insertionIndex ); private: std::vector<cc::Vec3f> _controlPoints; unsigned int _curveCount; }; #endif /* __bezier_path__ */
39.4375
134
0.752773
[ "vector" ]
a0bcc78295a0c55336c04e12eaad42d678049447
1,360
cpp
C++
foundation/cpp/3_dynamic_programming/1_time_and_space_complexity/8.cpp
vikaskbm/pepcoding
fb39b6dd62f4e5b76f75e12f2b222e2adb4854c1
[ "MIT" ]
2
2021-03-16T08:56:46.000Z
2021-03-17T05:37:21.000Z
foundation/cpp/3_dynamic_programming/1_time_and_space_complexity/8.cpp
vikaskbm/pepcoding
fb39b6dd62f4e5b76f75e12f2b222e2adb4854c1
[ "MIT" ]
null
null
null
foundation/cpp/3_dynamic_programming/1_time_and_space_complexity/8.cpp
vikaskbm/pepcoding
fb39b6dd62f4e5b76f75e12f2b222e2adb4854c1
[ "MIT" ]
null
null
null
// Quick Select // 1. You are given an array(arr) of integers. // 2. You have to find the k-th smallest element in the given array using the quick-select algorithm. // n=5 // 7 // -2 // 4 // 1 // 3 // k=3 // pivot -> 3 // Swapping -2 and 7 // Swapping 1 and 7 // Swapping 3 and 4 // pivot index -> 2 // 3 #include<iostream> #include<vector> using namespace std; void swap(vector <int> &arr, int i, int j){ cout << "Swapping " + to_string(arr[i]) + " and " + to_string(arr[j]) << endl; int t = arr[i]; arr[i] = arr[j]; arr[j] = t; } int partition(vector<int> &arr, int l, int r){ int idx = l; int p = arr[r]; cout << "pivot -> " + to_string(p) << endl; for(int i=l; i<=r; i++){ if(arr[i] <= p){ swap(arr, i, idx); idx++; } } cout << "pivot index -> " + to_string(idx-1) << endl; return idx-1; } void quick_select(vector<int> &arr, int k, int l, int r){ int p = partition(arr, l, r); while(p!=k-1){ if(p>k-1){ l=l; r=p-1; } else { l=p+1; r=r; } p=partition(arr, l, r); } cout << arr[p] << endl; } int main() { int n, k; cin >> n; vector <int> arr(n); for(int i=0; i<n; i++) cin >> arr[i]; cin >> k; quick_select(arr, k, 0, n-1); }
18.888889
101
0.478676
[ "vector" ]
a0c0e576491cb119e61c92e92e7b67f4007bd2eb
5,020
cpp
C++
FSMEngineProject/FSMAudioTest.cpp
millerf1234/FSMRenderEngine
44291023c2df01d04c9fc05bb45240e9145b4b37
[ "MIT" ]
null
null
null
FSMEngineProject/FSMAudioTest.cpp
millerf1234/FSMRenderEngine
44291023c2df01d04c9fc05bb45240e9145b4b37
[ "MIT" ]
null
null
null
FSMEngineProject/FSMAudioTest.cpp
millerf1234/FSMRenderEngine
44291023c2df01d04c9fc05bb45240e9145b4b37
[ "MIT" ]
null
null
null
#include "FSMAudioTest.h" #if 0 #include <vector> namespace FSMEngineInternal { namespace FSMAudio { static constexpr const size_t ENUMERATED_AUDIO_DEVICE_NAME_LENGTH_LIMIT = 2048u; typedef struct EnumeratedAudioDevice { ALchar nameBuffer[ENUMERATED_AUDIO_DEVICE_NAME_LENGTH_LIMIT]; EnumeratedAudioDevice() { LOG(TRACE) << __FUNCTION__; for (size_t i = 0u; i < ENUMERATED_AUDIO_DEVICE_NAME_LENGTH_LIMIT; i++) nameBuffer[i] = '\0'; } } EnumeratedAudioDevice; bool FSMAudioTest::initialized = false; bool checkForAudioDeviceEnumerationExtension() noexcept; std::vector<EnumeratedAudioDevice> enumerateAudioDevices() noexcept; void logEnumeratedDevices(const std::vector<EnumeratedAudioDevice>&) noexcept; bool FSMAudioTest::initializeAudio(AudioConfiguration config) noexcept { LOG(TRACE) << __FUNCTION__; if (checkForAudioDeviceEnumerationExtension()) { //Enumerate Devices auto devices = enumerateAudioDevices(); logEnumeratedDevices(devices); } else { //We are forced to use the implementation's designated default device } return false; } bool checkForAudioDeviceEnumerationExtension() noexcept { LOG(TRACE) << __FUNCTION__; ALboolean enumerationAvailable = AL_FALSE; //First parameter as NULL means we want to retrieve information //from all available devices enumerationAvailable = alcIsExtensionPresent(NULL, "ALC_ENUMERATION_EXT"); if (checkOpenALErrorStack()) return false; if (AL_TRUE == enumerationAvailable) return true; else return false; } std::vector<EnumeratedAudioDevice> enumerateAudioDevices() noexcept { LOG(TRACE) << __FUNCTION__; std::vector<EnumeratedAudioDevice> devices; const ALchar* deviceNameList = alcGetString(NULL, ALC_DEVICE_SPECIFIER); if (checkOpenALErrorStack()) { return devices; } //still more todo return devices; } void logEnumeratedDevices(const std::vector<EnumeratedAudioDevice>& audioDeviceNames) noexcept { LOG(TRACE) << __FUNCTION__; LOG(INFO) << "Detected the following Audio Devices: "; for (auto device : audioDeviceNames) LOG(INFO) << " " << device.nameBuffer; LOG(INFO) << "\n\n"; } } //namespace FSMAudio } //namespace FSMEngineInternal /* void AudioRenderer::parseDevicesIntoVector(std::vector<const ALchar*>& devices) { const ALchar * deviceNames = alcGetString(NULL, ALC_DEVICE_SPECIFIER); //Get device list if (checkForError()) { return; } bool reachedEndOfList = false; size_t nameLength = 0; std::ostringstream deviceName; const ALchar * nameIterator, *nextAfterNameIterator; nameIterator = deviceNames; nextAfterNameIterator = (deviceNames + 1); do { if ( (*nameIterator) == '\0') { nameLength = 0; static std::vector<std::string> names; names.push_back(deviceName.str()); std::vector<std::string>::iterator mostRecentName = names.end(); mostRecentName--; //Move iterator to be at the last item in the vector devices.push_back(static_cast<const ALchar *>((*mostRecentName).c_str())); if (devices.size() > MAX_DEVICE_NAMES_TO_RECORD) { std::cout << "\n\nWarning! Excessive number of Audio Devices detected!\n"; std::cout << "Only the first " << MAX_DEVICE_NAMES_TO_RECORD; std::cout << " devices will be recorded!" << std::endl; return; } //clear the stringstream std::ostringstream().swap(deviceName); //Check to see if we reached the end of the list if ( (*nextAfterNameIterator) == '\0' ) { reachedEndOfList = true; continue; } } else { deviceName << (*nameIterator); if (deviceName.str().size() > MAX_DEVICE_NAME_LENGTH) { std::cout << "\nWARNING! One of the detected audio devices "; std::cout << "has a name that exceeds the maximum name limit\n"; deviceName << '\0'; //Give the device name a terminating character std::cout << "\nThe device name that is causing the issue is: \n"; std::cout << deviceName.str() << std::endl; return; } nameIterator = nextAfterNameIterator++; } } while (!reachedEndOfList); } */ #endif //#if 0
34.62069
104
0.578088
[ "vector" ]
a0c66aa0b26a93f9cd18d4ab066cc8d0d2bd5322
6,479
cc
C++
chrome/browser/media_gallery/media_device_notifications_window_win_unittest.cc
Crystalnix/BitPop
1fae4ecfb965e163f6ce154b3988b3181678742a
[ "BSD-3-Clause" ]
7
2015-05-20T22:41:35.000Z
2021-11-18T19:07:59.000Z
chrome/browser/media_gallery/media_device_notifications_window_win_unittest.cc
Crystalnix/BitPop
1fae4ecfb965e163f6ce154b3988b3181678742a
[ "BSD-3-Clause" ]
1
2015-02-02T06:55:08.000Z
2016-01-20T06:11:59.000Z
chrome/browser/media_gallery/media_device_notifications_window_win_unittest.cc
Crystalnix/BitPop
1fae4ecfb965e163f6ce154b3988b3181678742a
[ "BSD-3-Clause" ]
2
2015-12-08T00:37:41.000Z
2017-04-06T05:34:05.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/media_gallery/media_device_notifications_window_win.h" #include <dbt.h> #include <string> #include <vector> #include "base/file_util.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop.h" #include "base/scoped_temp_dir.h" #include "base/string_number_conversions.h" #include "base/system_monitor/system_monitor.h" #include "base/test/mock_devices_changed_observer.h" #include "content/public/test/test_browser_thread.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace { using content::BrowserThread; LRESULT GetVolumeName(LPCWSTR drive, LPWSTR volume_name, unsigned int volume_name_length) { DCHECK(volume_name_length > wcslen(drive) + 2); *volume_name = 'V'; wcscpy(volume_name + 1, drive); return TRUE; } } // namespace using chrome::MediaDeviceNotificationsWindowWin; using testing::_; class MediaDeviceNotificationsWindowWinTest : public testing::Test { public: MediaDeviceNotificationsWindowWinTest() : ui_thread_(BrowserThread::UI, &message_loop_), file_thread_(BrowserThread::FILE) { } virtual ~MediaDeviceNotificationsWindowWinTest() { } protected: virtual void SetUp() OVERRIDE { ASSERT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::UI)); file_thread_.Start(); window_ = new MediaDeviceNotificationsWindowWin(&GetVolumeName); system_monitor_.AddDevicesChangedObserver(&observer_); } virtual void TearDown() { system_monitor_.RemoveDevicesChangedObserver(&observer_); WaitForFileThread(); } static void PostQuitToUIThread() { BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, MessageLoop::QuitClosure()); } static void WaitForFileThread() { BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, base::Bind(&PostQuitToUIThread)); MessageLoop::current()->Run(); } void DoDevicesAttachedTest(const std::vector<int>& device_indices); void DoDevicesDetachedTest(const std::vector<int>& device_indices); MessageLoop message_loop_; content::TestBrowserThread ui_thread_; content::TestBrowserThread file_thread_; base::SystemMonitor system_monitor_; base::MockDevicesChangedObserver observer_; scoped_refptr<MediaDeviceNotificationsWindowWin> window_; }; void MediaDeviceNotificationsWindowWinTest::DoDevicesAttachedTest( const std::vector<int>& device_indices) { DEV_BROADCAST_VOLUME volume_broadcast; volume_broadcast.dbcv_size = sizeof(volume_broadcast); volume_broadcast.dbcv_devicetype = DBT_DEVTYP_VOLUME; volume_broadcast.dbcv_unitmask = 0x0; volume_broadcast.dbcv_flags = 0x0; { testing::InSequence sequence; for (std::vector<int>::const_iterator it = device_indices.begin(); it != device_indices.end(); ++it) { volume_broadcast.dbcv_unitmask |= 0x1 << *it; std::wstring drive(L"_:\\"); drive[0] = 'A' + *it; FilePath::StringType name = L"V" + drive; EXPECT_CALL(observer_, OnMediaDeviceAttached(base::IntToString(*it), name, base::SystemMonitor::TYPE_PATH, drive)) .Times(0); } } window_->OnDeviceChange(DBT_DEVICEARRIVAL, reinterpret_cast<DWORD>(&volume_broadcast)); message_loop_.RunAllPending(); } void MediaDeviceNotificationsWindowWinTest::DoDevicesDetachedTest( const std::vector<int>& device_indices) { DEV_BROADCAST_VOLUME volume_broadcast; volume_broadcast.dbcv_size = sizeof(volume_broadcast); volume_broadcast.dbcv_devicetype = DBT_DEVTYP_VOLUME; volume_broadcast.dbcv_unitmask = 0x0; volume_broadcast.dbcv_flags = 0x0; { testing::InSequence sequence; for (std::vector<int>::const_iterator it = device_indices.begin(); it != device_indices.end(); ++it) { volume_broadcast.dbcv_unitmask |= 0x1 << *it; EXPECT_CALL(observer_, OnMediaDeviceDetached(base::IntToString(*it))) .Times(0); } } window_->OnDeviceChange(DBT_DEVICEREMOVECOMPLETE, reinterpret_cast<DWORD>(&volume_broadcast)); message_loop_.RunAllPending(); } TEST_F(MediaDeviceNotificationsWindowWinTest, RandomMessage) { window_->OnDeviceChange(DBT_DEVICEQUERYREMOVE, NULL); message_loop_.RunAllPending(); } TEST_F(MediaDeviceNotificationsWindowWinTest, DevicesAttached) { std::vector<int> device_indices; device_indices.push_back(1); device_indices.push_back(5); device_indices.push_back(7); DoDevicesAttachedTest(device_indices); } TEST_F(MediaDeviceNotificationsWindowWinTest, DevicesAttachedHighBoundary) { std::vector<int> device_indices; device_indices.push_back(25); DoDevicesAttachedTest(device_indices); } TEST_F(MediaDeviceNotificationsWindowWinTest, DevicesAttachedLowBoundary) { std::vector<int> device_indices; device_indices.push_back(0); DoDevicesAttachedTest(device_indices); } TEST_F(MediaDeviceNotificationsWindowWinTest, DevicesAttachedAdjacentBits) { std::vector<int> device_indices; device_indices.push_back(0); device_indices.push_back(1); device_indices.push_back(2); device_indices.push_back(3); DoDevicesAttachedTest(device_indices); } TEST_F(MediaDeviceNotificationsWindowWinTest, DevicesDetached) { std::vector<int> device_indices; device_indices.push_back(1); device_indices.push_back(5); device_indices.push_back(7); DoDevicesDetachedTest(device_indices); } TEST_F(MediaDeviceNotificationsWindowWinTest, DevicesDetachedHighBoundary) { std::vector<int> device_indices; device_indices.push_back(25); DoDevicesDetachedTest(device_indices); } TEST_F(MediaDeviceNotificationsWindowWinTest, DevicesDetachedLowBoundary) { std::vector<int> device_indices; device_indices.push_back(0); DoDevicesDetachedTest(device_indices); } TEST_F(MediaDeviceNotificationsWindowWinTest, DevicesDetachedAdjacentBits) { std::vector<int> device_indices; device_indices.push_back(0); device_indices.push_back(1); device_indices.push_back(2); device_indices.push_back(3); DoDevicesDetachedTest(device_indices); }
31.299517
79
0.729434
[ "vector" ]
a0c7948e99ad4f0082151f405865057c3bc70a79
1,961
cpp
C++
Math/matrix.cpp
rsk0315/codefolio
1de990978489f466e1fd47884d4a19de9cc30e02
[ "MIT" ]
1
2020-03-20T13:24:30.000Z
2020-03-20T13:24:30.000Z
Math/matrix.cpp
rsk0315/codefolio
1de990978489f466e1fd47884d4a19de9cc30e02
[ "MIT" ]
null
null
null
Math/matrix.cpp
rsk0315/codefolio
1de990978489f466e1fd47884d4a19de9cc30e02
[ "MIT" ]
null
null
null
template <typename Tp> class matrix { public: using value_type = Tp; private: class M_container: private std::vector<Tp> { friend matrix<Tp>; public: M_container() = default; M_container(size_t n, Tp const& x = Tp{}): std::vector<Tp>(n, x) {} M_container(const std::initializer_list<Tp>& init): std::vector<Tp>(init) {} Tp& operator [](size_t i) { return std::vector<Tp>::operator [](i); } Tp const& operator [](size_t i) const { return std::vector<Tp>::operator [](i); } }; size_t M_rows = 0; size_t M_columns = 0; std::vector<M_container> M_c; matrix M_modmul(matrix const& rhs, Tp mod) const { if (M_columns != rhs.M_rows) throw std::logic_error("size mismatch"); matrix res(M_rows, rhs.M_columns); for (size_t i = 0; i < M_rows; ++i) for (size_t j = 0; j < M_columns; ++j) for (size_t k = 0; k < rhs.M_columns; ++k) (res[i][k] += (*this)[i][j] * rhs[j][k]) %= mod; return res; } public: matrix(size_t n, size_t m, Tp const& x = Tp{}): M_rows(n), M_columns(m), M_c(n, M_container(m, x)) {} matrix(std::initializer_list<std::initializer_list<Tp>> const& init) { for (auto const& ii: init) { M_c.emplace_back(ii); ++M_rows; M_columns = std::max(M_columns, ii.size()); } for (auto& ci: M_c) { if (ci.size() < M_columns) ci.resize(M_columns, Tp()); } } M_container& operator [](size_t i) { return M_c[i]; } M_container const& operator [](size_t i) const { return M_c[i]; } matrix modpow(intmax_t iexp, Tp mod) { if (M_rows != M_columns) throw std::logic_error("non-square matrix"); size_t n = M_rows; matrix eye(n, n); for (size_t i = 0; i < n; ++i) eye[i][i] = Tp{1}; matrix res = eye; for (matrix dbl = *this; iexp; iexp >>= 1) { if (iexp & 1) res = res.M_modmul(dbl, mod); dbl = dbl.M_modmul(dbl, mod); } return res; } void clear() { M_c.clear(); } };
28.42029
85
0.585416
[ "vector" ]
a0d00c0cdeebca28e9dd264e29d5106b0b31c05d
60,072
cpp
C++
casadi/casadi-windows-matlabR2016a-v3/include/casadi/core/mx_function.cpp
pymBRT/TROPIC
77ec31d34dbd8d038674e966d13915f8032cf4ab
[ "BSD-3-Clause" ]
29
2020-05-11T16:59:10.000Z
2022-02-24T11:30:16.000Z
casadi/casadi-windows-matlabR2016a-v3/include/casadi/core/mx_function.cpp
pymBRT/TROPIC
77ec31d34dbd8d038674e966d13915f8032cf4ab
[ "BSD-3-Clause" ]
1
2021-02-04T04:20:55.000Z
2021-02-28T20:47:02.000Z
casadi/casadi-windows-matlabR2016a-v3/include/casadi/core/mx_function.cpp
pymBRT/TROPIC
77ec31d34dbd8d038674e966d13915f8032cf4ab
[ "BSD-3-Clause" ]
10
2020-06-22T22:41:32.000Z
2021-12-15T12:26:13.000Z
/* * This file is part of CasADi. * * CasADi -- A symbolic framework for dynamic optimization. * Copyright (C) 2010-2014 Joel Andersson, Joris Gillis, Moritz Diehl, * K.U. Leuven. All rights reserved. * Copyright (C) 2011-2014 Greg Horn * * CasADi is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * CasADi is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with CasADi; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #include "mx_function.hpp" #include "casadi_misc.hpp" #include "casadi_common.hpp" #include "global_options.hpp" #include "casadi_interrupt.hpp" #include "io_instruction.hpp" #include "serializing_stream.hpp" #include <stack> #include <typeinfo> // Throw informative error message #define CASADI_THROW_ERROR(FNAME, WHAT) \ throw CasadiException("Error in MXFunction::" FNAME " at " + CASADI_WHERE + ":\n"\ + std::string(WHAT)); using namespace std; namespace casadi { MXFunction::MXFunction(const std::string& name, const std::vector<MX>& inputv, const std::vector<MX>& outputv, const std::vector<std::string>& name_in, const std::vector<std::string>& name_out) : XFunction<MXFunction, MX, MXNode>(name, inputv, outputv, name_in, name_out) { } MXFunction::~MXFunction() { clear_mem(); } const Options MXFunction::options_ = {{&FunctionInternal::options_}, {{"default_in", {OT_DOUBLEVECTOR, "Default input values"}}, {"live_variables", {OT_BOOL, "Reuse variables in the work vector"}} } }; Dict MXFunction::generate_options(bool is_temp) const { Dict opts = FunctionInternal::generate_options(is_temp); //opts["default_in"] = default_in_; opts["live_variables"] = live_variables_; return opts; } MX MXFunction::instruction_MX(casadi_int k) const { return algorithm_.at(k).data; } std::vector<casadi_int> MXFunction::instruction_input(casadi_int k) const { auto e = algorithm_.at(k); if (e.op==OP_INPUT) { const IOInstruction* io = static_cast<const IOInstruction*>(e.data.get()); return { io->ind() }; } else { return e.arg; } } std::vector<casadi_int> MXFunction::instruction_output(casadi_int k) const { auto e = algorithm_.at(k); if (e.op==OP_OUTPUT) { const IOInstruction* io = static_cast<const IOInstruction*>(e.data.get()); return { io->ind() }; } else { return e.res; } } void MXFunction::init(const Dict& opts) { // Call the init function of the base class XFunction<MXFunction, MX, MXNode>::init(opts); if (verbose_) casadi_message(name_ + "::init"); // Default (temporary) options live_variables_ = true; // Read options for (auto&& op : opts) { if (op.first=="default_in") { default_in_ = op.second; } else if (op.first=="live_variables") { live_variables_ = op.second; } } // Check/set default inputs if (default_in_.empty()) { default_in_.resize(n_in_, 0); } else { casadi_assert(default_in_.size()==n_in_, "Option 'default_in' has incorrect length"); } // Stack used to sort the computational graph stack<MXNode*> s; // All nodes vector<MXNode*> nodes; // Add the list of nodes for (casadi_int ind=0; ind<out_.size(); ++ind) { // Loop over primitives of each output vector<MX> prim = out_[ind].primitives(); casadi_int nz_offset=0; for (casadi_int p=0; p<prim.size(); ++p) { // Get the nodes using a depth first search s.push(prim[p].get()); sort_depth_first(s, nodes); // Add an output instruction ("data" below will take ownership) nodes.push_back(new Output(prim[p], ind, p, nz_offset)); // Update offset nz_offset += prim[p].nnz(); } } // Set the temporary variables to be the corresponding place in the sorted graph for (casadi_int i=0; i<nodes.size(); ++i) { nodes[i]->temp = i; } // Place in the algorithm for each node vector<casadi_int> place_in_alg; place_in_alg.reserve(nodes.size()); // Input instructions vector<pair<casadi_int, MXNode*> > symb_loc; // Count the number of times each node is used vector<casadi_int> refcount(nodes.size(), 0); // Get the sequence of instructions for the virtual machine algorithm_.resize(0); algorithm_.reserve(nodes.size()); for (MXNode* n : nodes) { // Get the operation casadi_int op = n->op(); // Store location if parameter (or input) if (op==OP_PARAMETER) { symb_loc.push_back(make_pair(algorithm_.size(), n)); } // If a new element in the algorithm needs to be added if (op>=0) { AlgEl ae; ae.op = op; ae.data.own(n); ae.arg.resize(n->n_dep()); for (casadi_int i=0; i<n->n_dep(); ++i) { ae.arg[i] = n->dep(i)->temp; } ae.res.resize(n->nout()); if (n->has_output()) { fill(ae.res.begin(), ae.res.end(), -1); } else if (!ae.res.empty()) { ae.res[0] = n->temp; } // Increase the reference count of the dependencies for (casadi_int c=0; c<ae.arg.size(); ++c) { if (ae.arg[c]>=0) { refcount[ae.arg[c]]++; } } // Save to algorithm place_in_alg.push_back(algorithm_.size()); algorithm_.push_back(ae); } else { // Function output node // Get the output index casadi_int oind = n->which_output(); // Get the index of the parent node casadi_int pind = place_in_alg[n->dep(0)->temp]; // Save location in the algorithm element corresponding to the parent node casadi_int& otmp = algorithm_[pind].res.at(oind); if (otmp<0) { otmp = n->temp; // First time this function output is encountered, save to algorithm } else { n->temp = otmp; // Function output is a duplicate, use the node encountered first } // Not in the algorithm place_in_alg.push_back(-1); } } // Place in the work vector for each of the nodes in the tree (overwrites the reference counter) vector<casadi_int>& place = place_in_alg; // Reuse memory as it is no longer needed place.resize(nodes.size()); // Stack with unused elements in the work vector, sorted by sparsity pattern SPARSITY_MAP<casadi_int, stack<casadi_int> > unused_all; // Work vector size casadi_int worksize = 0; // Find a place in the work vector for the operation for (auto&& e : algorithm_) { // There are two tasks, allocate memory of the result and free the // memory off the arguments, order depends on whether inplace is possible casadi_int first_to_free = 0; casadi_int last_to_free = e.data->n_inplace(); for (casadi_int task=0; task<2; ++task) { // Dereference or free the memory of the arguments for (casadi_int c=last_to_free-1; c>=first_to_free; --c) { // reverse order so that the // first argument will end up // at the top of the stack // Index of the argument casadi_int& ch_ind = e.arg[c]; if (ch_ind>=0) { // Decrease reference count and add to the stack of // unused variables if the count hits zero casadi_int remaining = --refcount[ch_ind]; // Free variable for reuse if (live_variables_ && remaining==0) { // Get a pointer to the sparsity pattern of the argument that can be freed casadi_int nnz = nodes[ch_ind]->sparsity().nnz(); // Add to the stack of unused work vector elements for the current sparsity unused_all[nnz].push(place[ch_ind]); } // Point to the place in the work vector instead of to the place in the list of nodes ch_ind = place[ch_ind]; } } // Nothing more to allocate if (task==1) break; // Free the rest in the next iteration first_to_free = last_to_free; last_to_free = e.arg.size(); // Allocate/reuse memory for the results of the operation for (casadi_int c=0; c<e.res.size(); ++c) { if (e.res[c]>=0) { // Are reuse of variables (live variables) enabled? if (live_variables_) { // Get a pointer to the sparsity pattern node casadi_int nnz = e.data->sparsity(c).nnz(); // Get a reference to the stack for the current sparsity stack<casadi_int>& unused = unused_all[nnz]; // Try to reuse a variable from the stack if possible (last in, first out) if (!unused.empty()) { e.res[c] = place[e.res[c]] = unused.top(); unused.pop(); continue; // Success, no new element needed in the work vector } } // Allocate a new element in the work vector e.res[c] = place[e.res[c]] = worksize++; } } } } if (verbose_) { if (live_variables_) { casadi_message("Using live variables: work array is " + str(worksize) + " instead of " + str(nodes.size())); } else { casadi_message("Live variables disabled."); } } // Allocate work vectors (numeric) workloc_.resize(worksize+1); fill(workloc_.begin(), workloc_.end(), -1); size_t wind=0, sz_w=0; for (auto&& e : algorithm_) { if (e.op!=OP_OUTPUT) { for (casadi_int c=0; c<e.res.size(); ++c) { if (e.res[c]>=0) { alloc_arg(e.data->sz_arg()); alloc_res(e.data->sz_res()); alloc_iw(e.data->sz_iw()); sz_w = max(sz_w, e.data->sz_w()); if (workloc_[e.res[c]] < 0) { workloc_[e.res[c]] = wind; wind += e.data->sparsity(c).nnz(); } } } } } workloc_.back()=wind; for (casadi_int i=0; i<workloc_.size(); ++i) { if (workloc_[i]<0) workloc_[i] = i==0 ? 0 : workloc_[i-1]; workloc_[i] += sz_w; } sz_w += wind; alloc_w(sz_w); // Reset the temporary variables for (casadi_int i=0; i<nodes.size(); ++i) { if (nodes[i]) { nodes[i]->temp = 0; } } // Now mark each input's place in the algorithm for (auto it=symb_loc.begin(); it!=symb_loc.end(); ++it) { it->second->temp = it->first+1; } // Add input instructions, loop over inputs for (casadi_int ind=0; ind<in_.size(); ++ind) { // Loop over symbolic primitives of each input vector<MX> prim = in_[ind].primitives(); casadi_int nz_offset=0; for (casadi_int p=0; p<prim.size(); ++p) { casadi_int i = prim[p].get_temp()-1; if (i>=0) { // Mark read prim[p].set_temp(0); // Replace parameter with input instruction algorithm_[i].data.own(new Input(prim[p].sparsity(), ind, p, nz_offset)); algorithm_[i].op = OP_INPUT; } nz_offset += prim[p]->nnz(); } } // Locate free variables free_vars_.clear(); for (auto it=symb_loc.begin(); it!=symb_loc.end(); ++it) { casadi_int i = it->second->temp-1; if (i>=0) { // Save to list of free parameters free_vars_.push_back(MX::create(it->second)); // Remove marker it->second->temp=0; } } // Does any embedded function have reference counting for codegen? for (auto&& a : algorithm_) { if (a.data->has_refcount()) { has_refcount_ = true; break; } } } int MXFunction::eval(const double** arg, double** res, casadi_int* iw, double* w, void* mem) const { if (verbose_) casadi_message(name_ + "::eval"); // Work vector and temporaries to hold pointers to operation input and outputs const double** arg1 = arg+n_in_; double** res1 = res+n_out_; // Make sure that there are no free variables if (!free_vars_.empty()) { std::stringstream ss; disp(ss, false); casadi_error("Cannot evaluate \"" + ss.str() + "\" since variables " + str(free_vars_) + " are free."); } // Evaluate all of the nodes of the algorithm: // should only evaluate nodes that have not yet been calculated! for (auto&& e : algorithm_) { if (e.op==OP_INPUT) { // Pass an input double *w1 = w+workloc_[e.res.front()]; casadi_int nnz=e.data.nnz(); casadi_int i=e.data->ind(); casadi_int nz_offset=e.data->offset(); if (arg[i]==nullptr) { fill(w1, w1+nnz, 0); } else { copy(arg[i]+nz_offset, arg[i]+nz_offset+nnz, w1); } } else if (e.op==OP_OUTPUT) { // Get an output double *w1 = w+workloc_[e.arg.front()]; casadi_int nnz=e.data->dep().nnz(); casadi_int i=e.data->ind(); casadi_int nz_offset=e.data->offset(); if (res[i]) copy(w1, w1+nnz, res[i]+nz_offset); } else { // Point pointers to the data corresponding to the element for (casadi_int i=0; i<e.arg.size(); ++i) arg1[i] = e.arg[i]>=0 ? w+workloc_[e.arg[i]] : nullptr; for (casadi_int i=0; i<e.res.size(); ++i) res1[i] = e.res[i]>=0 ? w+workloc_[e.res[i]] : nullptr; // Evaluate if (e.data->eval(arg1, res1, iw, w)) return 1; } } return 0; } string MXFunction::print(const AlgEl& el) const { stringstream s; if (el.op==OP_OUTPUT) { s << "output[" << el.data->ind() << "][" << el.data->segment() << "]" << " = @" << el.arg.at(0); } else if (el.op==OP_SETNONZEROS || el.op==OP_ADDNONZEROS) { if (el.res.front()!=el.arg.at(0)) { s << "@" << el.res.front() << " = @" << el.arg.at(0) << "; "; } vector<string> arg(2); arg[0] = "@" + str(el.res.front()); arg[1] = "@" + str(el.arg.at(1)); s << el.data->disp(arg); } else { if (el.res.size()==1) { s << "@" << el.res.front() << " = "; } else { s << "{"; for (casadi_int i=0; i<el.res.size(); ++i) { if (i!=0) s << ", "; if (el.res[i]>=0) { s << "@" << el.res[i]; } else { s << "NULL"; } } s << "} = "; } vector<string> arg; if (el.op!=OP_INPUT) { arg.resize(el.arg.size()); for (casadi_int i=0; i<el.arg.size(); ++i) { if (el.arg[i]>=0) { arg[i] = "@" + str(el.arg[i]); } else { arg[i] = "NULL"; } } } s << el.data->disp(arg); } return s.str(); } void MXFunction::disp_more(ostream &stream) const { stream << "Algorithm:"; for (auto&& e : algorithm_) { InterruptHandler::check(); stream << endl << print(e); } } int MXFunction:: sp_forward(const bvec_t** arg, bvec_t** res, casadi_int* iw, bvec_t* w, void* mem) const { // Fall back when forward mode not allowed if (sp_weight()==1) return FunctionInternal::sp_forward(arg, res, iw, w, mem); // Temporaries to hold pointers to operation input and outputs const bvec_t** arg1=arg+n_in_; bvec_t** res1=res+n_out_; // Propagate sparsity forward for (auto&& e : algorithm_) { if (e.op==OP_INPUT) { // Pass input seeds casadi_int nnz=e.data.nnz(); casadi_int i=e.data->ind(); casadi_int nz_offset=e.data->offset(); const bvec_t* argi = arg[i]; bvec_t* w1 = w + workloc_[e.res.front()]; if (argi!=nullptr) { copy(argi+nz_offset, argi+nz_offset+nnz, w1); } else { fill_n(w1, nnz, 0); } } else if (e.op==OP_OUTPUT) { // Get the output sensitivities casadi_int nnz=e.data.dep().nnz(); casadi_int i=e.data->ind(); casadi_int nz_offset=e.data->offset(); bvec_t* resi = res[i]; bvec_t* w1 = w + workloc_[e.arg.front()]; if (resi!=nullptr) copy(w1, w1+nnz, resi+nz_offset); } else { // Point pointers to the data corresponding to the element for (casadi_int i=0; i<e.arg.size(); ++i) arg1[i] = e.arg[i]>=0 ? w+workloc_[e.arg[i]] : nullptr; for (casadi_int i=0; i<e.res.size(); ++i) res1[i] = e.res[i]>=0 ? w+workloc_[e.res[i]] : nullptr; // Propagate sparsity forwards if (e.data->sp_forward(arg1, res1, iw, w)) return 1; } } return 0; } int MXFunction::sp_reverse(bvec_t** arg, bvec_t** res, casadi_int* iw, bvec_t* w, void* mem) const { // Fall back when reverse mode not allowed if (sp_weight()==0) return FunctionInternal::sp_reverse(arg, res, iw, w, mem); // Temporaries to hold pointers to operation input and outputs bvec_t** arg1=arg+n_in_; bvec_t** res1=res+n_out_; fill_n(w, sz_w(), 0); // Propagate sparsity backwards for (auto it=algorithm_.rbegin(); it!=algorithm_.rend(); it++) { if (it->op==OP_INPUT) { // Get the input sensitivities and clear it from the work vector casadi_int nnz=it->data.nnz(); casadi_int i=it->data->ind(); casadi_int nz_offset=it->data->offset(); bvec_t* argi = arg[i]; bvec_t* w1 = w + workloc_[it->res.front()]; if (argi!=nullptr) for (casadi_int k=0; k<nnz; ++k) argi[nz_offset+k] |= w1[k]; fill_n(w1, nnz, 0); } else if (it->op==OP_OUTPUT) { // Pass output seeds casadi_int nnz=it->data.dep().nnz(); casadi_int i=it->data->ind(); casadi_int nz_offset=it->data->offset(); bvec_t* resi = res[i] ? res[i] + nz_offset : nullptr; bvec_t* w1 = w + workloc_[it->arg.front()]; if (resi!=nullptr) { for (casadi_int k=0; k<nnz; ++k) w1[k] |= resi[k]; fill_n(resi, nnz, 0); } } else { // Point pointers to the data corresponding to the element for (casadi_int i=0; i<it->arg.size(); ++i) arg1[i] = it->arg[i]>=0 ? w+workloc_[it->arg[i]] : nullptr; for (casadi_int i=0; i<it->res.size(); ++i) res1[i] = it->res[i]>=0 ? w+workloc_[it->res[i]] : nullptr; // Propagate sparsity backwards if (it->data->sp_reverse(arg1, res1, iw, w)) return 1; } } return 0; } std::vector<MX> MXFunction::symbolic_output(const std::vector<MX>& arg) const { // Check if input is given const casadi_int checking_depth = 2; bool input_given = true; for (casadi_int i=0; i<arg.size() && input_given; ++i) { if (!is_equal(arg[i], in_[i], checking_depth)) { input_given = false; } } // Return output if possible, else fall back to base class if (input_given) { return out_; } else { return FunctionInternal::symbolic_output(arg); } } void MXFunction::eval_mx(const MXVector& arg, MXVector& res, bool always_inline, bool never_inline) const { always_inline = always_inline || always_inline_; never_inline = never_inline || never_inline_; if (verbose_) casadi_message(name_ + "::eval_mx"); try { // Resize the number of outputs casadi_assert(arg.size()==n_in_, "Wrong number of input arguments"); res.resize(out_.size()); // Trivial inline by default if output known if (!never_inline && isInput(arg)) { copy(out_.begin(), out_.end(), res.begin()); return; } // non-inlining call is implemented in the base-class if (!should_inline(always_inline, never_inline)) { return FunctionInternal::eval_mx(arg, res, false, true); } // Symbolic work, non-differentiated vector<MX> swork(workloc_.size()-1); if (verbose_) casadi_message("Allocated work vector"); // Split up inputs analogous to symbolic primitives vector<vector<MX> > arg_split(in_.size()); for (casadi_int i=0; i<in_.size(); ++i) arg_split[i] = in_[i].split_primitives(arg[i]); // Allocate storage for split outputs vector<vector<MX> > res_split(out_.size()); for (casadi_int i=0; i<out_.size(); ++i) res_split[i].resize(out_[i].n_primitives()); vector<MX> arg1, res1; // Loop over computational nodes in forward order casadi_int alg_counter = 0; for (auto it=algorithm_.begin(); it!=algorithm_.end(); ++it, ++alg_counter) { if (it->op == OP_INPUT) { swork[it->res.front()] = project(arg_split.at(it->data->ind()).at(it->data->segment()), it->data.sparsity(), true); } else if (it->op==OP_OUTPUT) { // Collect the results res_split.at(it->data->ind()).at(it->data->segment()) = swork[it->arg.front()]; } else if (it->op==OP_PARAMETER) { // Fetch parameter swork[it->res.front()] = it->data; } else { // Arguments of the operation arg1.resize(it->arg.size()); for (casadi_int i=0; i<arg1.size(); ++i) { casadi_int el = it->arg[i]; // index of the argument arg1[i] = el<0 ? MX(it->data->dep(i).size()) : swork[el]; } // Perform the operation res1.resize(it->res.size()); it->data->eval_mx(arg1, res1); // Get the result for (casadi_int i=0; i<res1.size(); ++i) { casadi_int el = it->res[i]; // index of the output if (el>=0) swork[el] = res1[i]; } } } // Join split outputs for (casadi_int i=0; i<res.size(); ++i) res[i] = out_[i].join_primitives(res_split[i]); } catch (std::exception& e) { CASADI_THROW_ERROR("eval_mx", e.what()); } } void MXFunction::ad_forward(const std::vector<std::vector<MX> >& fseed, std::vector<std::vector<MX> >& fsens) const { if (verbose_) casadi_message(name_ + "::ad_forward(" + str(fseed.size())+ ")"); try { // Allocate results casadi_int nfwd = fseed.size(); fsens.resize(nfwd); for (casadi_int d=0; d<nfwd; ++d) { fsens[d].resize(n_out_); } // Quick return if no directions if (nfwd==0) return; // Check if seeds need to have dimensions corrected casadi_int npar = 1; for (auto&& r : fseed) { if (!matching_arg(r, npar)) { casadi_assert_dev(npar==1); return ad_forward(replace_fseed(fseed, npar), fsens); } } // Check if there are any zero seeds for (auto&& r : fseed) { if (purgable(r)) { // New argument without all-zero directions std::vector<std::vector<MX> > fseed_purged, fsens_purged; fseed_purged.reserve(nfwd); vector<casadi_int> index_purged; for (casadi_int d=0; d<nfwd; ++d) { if (purgable(fseed[d])) { for (casadi_int i=0; i<fsens[d].size(); ++i) { fsens[d][i] = MX(size_out(i)); } } else { fseed_purged.push_back(fsens[d]); index_purged.push_back(d); } } // Call recursively ad_forward(fseed_purged, fsens_purged); // Fetch result for (casadi_int d=0; d<fseed_purged.size(); ++d) { fsens[index_purged[d]] = fsens_purged[d]; } return; } } if (!enable_forward_) { // Do the non-inlining call from FunctionInternal // NOLINTNEXTLINE(bugprone-parent-virtual-call) FunctionInternal::call_forward(in_, out_, fseed, fsens, false, false); return; } // Work vector, forward derivatives std::vector<std::vector<MX> > dwork(workloc_.size()-1); fill(dwork.begin(), dwork.end(), std::vector<MX>(nfwd)); if (verbose_) casadi_message("Allocated derivative work vector (forward mode)"); // Split up fseed analogous to symbolic primitives vector<vector<vector<MX> > > fseed_split(nfwd); for (casadi_int d=0; d<nfwd; ++d) { fseed_split[d].resize(fseed[d].size()); for (casadi_int i=0; i<fseed[d].size(); ++i) { fseed_split[d][i] = in_[i].split_primitives(fseed[d][i]); } } // Allocate splited forward sensitivities vector<vector<vector<MX> > > fsens_split(nfwd); for (casadi_int d=0; d<nfwd; ++d) { fsens_split[d].resize(out_.size()); for (casadi_int i=0; i<out_.size(); ++i) { fsens_split[d][i].resize(out_[i].n_primitives()); } } // Pointers to the arguments of the current operation vector<vector<MX> > oseed, osens; oseed.reserve(nfwd); osens.reserve(nfwd); vector<bool> skip(nfwd, false); // Loop over computational nodes in forward order for (auto&& e : algorithm_) { if (e.op == OP_INPUT) { // Fetch forward seed for (casadi_int d=0; d<nfwd; ++d) { dwork[e.res.front()][d] = project(fseed_split[d].at(e.data->ind()).at(e.data->segment()), e.data.sparsity(), true); } } else if (e.op==OP_OUTPUT) { // Collect forward sensitivity for (casadi_int d=0; d<nfwd; ++d) { fsens_split[d][e.data->ind()][e.data->segment()] = dwork[e.arg.front()][d]; } } else if (e.op==OP_PARAMETER) { // Fetch parameter for (casadi_int d=0; d<nfwd; ++d) { dwork[e.res.front()][d] = MX(); } } else { // Get seeds, ignoring all-zero directions oseed.clear(); for (casadi_int d=0; d<nfwd; ++d) { // Collect seeds, skipping directions with only zeros vector<MX> seed(e.arg.size()); skip[d] = true; // All seeds are zero? for (casadi_int i=0; i<e.arg.size(); ++i) { casadi_int el = e.arg[i]; if (el<0 || dwork[el][d].is_empty(true)) { seed[i] = MX(e.data->dep(i).size()); } else { seed[i] = dwork[el][d]; } if (skip[d] && !seed[i].is_zero()) skip[d] = false; } if (!skip[d]) oseed.push_back(seed); } // Perform the operation osens.resize(oseed.size()); if (!osens.empty()) { fill(osens.begin(), osens.end(), vector<MX>(e.res.size())); e.data.ad_forward(oseed, osens); } // Store sensitivities casadi_int d1=0; for (casadi_int d=0; d<nfwd; ++d) { for (casadi_int i=0; i<e.res.size(); ++i) { casadi_int el = e.res[i]; if (el>=0) { dwork[el][d] = skip[d] ? MX(e.data->sparsity(i).size()) : osens[d1][i]; } } if (!skip[d]) d1++; } } } // Get forward sensitivities for (casadi_int d=0; d<nfwd; ++d) { for (casadi_int i=0; i<out_.size(); ++i) { fsens[d][i] = out_[i].join_primitives(fsens_split[d][i]); } } } catch (std::exception& e) { CASADI_THROW_ERROR("ad_forward", e.what()); } } void MXFunction::ad_reverse(const std::vector<std::vector<MX> >& aseed, std::vector<std::vector<MX> >& asens) const { if (verbose_) casadi_message(name_ + "::ad_reverse(" + str(aseed.size())+ ")"); try { // Allocate results casadi_int nadj = aseed.size(); asens.resize(nadj); for (casadi_int d=0; d<nadj; ++d) { asens[d].resize(n_in_); } // Quick return if no directions if (nadj==0) return; // Check if seeds need to have dimensions corrected casadi_int npar = 1; for (auto&& r : aseed) { if (!matching_res(r, npar)) { casadi_assert_dev(npar==1); return ad_reverse(replace_aseed(aseed, npar), asens); } } // Check if there are any zero seeds for (auto&& r : aseed) { // If any direction can be skipped if (purgable(r)) { // New argument without all-zero directions std::vector<std::vector<MX> > aseed_purged, asens_purged; aseed_purged.reserve(nadj); vector<casadi_int> index_purged; for (casadi_int d=0; d<nadj; ++d) { if (purgable(aseed[d])) { for (casadi_int i=0; i<asens[d].size(); ++i) { asens[d][i] = MX(size_in(i)); } } else { aseed_purged.push_back(asens[d]); index_purged.push_back(d); } } // Call recursively ad_reverse(aseed_purged, asens_purged); // Fetch result for (casadi_int d=0; d<aseed_purged.size(); ++d) { asens[index_purged[d]] = asens_purged[d]; } return; } } if (!enable_reverse_) { vector<vector<MX> > v; // Do the non-inlining call from FunctionInternal // NOLINTNEXTLINE(bugprone-parent-virtual-call) FunctionInternal::call_reverse(in_, out_, aseed, v, false, false); for (casadi_int i=0; i<v.size(); ++i) { for (casadi_int j=0; j<v[i].size(); ++j) { if (!v[i][j].is_empty()) { // TODO(@jaeandersson): Hack if (asens[i][j].is_empty()) { asens[i][j] = v[i][j]; } else { asens[i][j] += v[i][j]; } } } } return; } // Split up aseed analogous to symbolic primitives vector<vector<vector<MX> > > aseed_split(nadj); for (casadi_int d=0; d<nadj; ++d) { aseed_split[d].resize(out_.size()); for (casadi_int i=0; i<out_.size(); ++i) { aseed_split[d][i] = out_[i].split_primitives(aseed[d][i]); } } // Allocate splited adjoint sensitivities vector<vector<vector<MX> > > asens_split(nadj); for (casadi_int d=0; d<nadj; ++d) { asens_split[d].resize(in_.size()); for (casadi_int i=0; i<in_.size(); ++i) { asens_split[d][i].resize(in_[i].n_primitives()); } } // Pointers to the arguments of the current operation vector<vector<MX> > oseed, osens; oseed.reserve(nadj); osens.reserve(nadj); vector<bool> skip(nadj, false); // Work vector, adjoint derivatives std::vector<std::vector<MX> > dwork(workloc_.size()-1); fill(dwork.begin(), dwork.end(), std::vector<MX>(nadj)); // Loop over computational nodes in reverse order for (auto it=algorithm_.rbegin(); it!=algorithm_.rend(); ++it) { if (it->op == OP_INPUT) { // Get the adjoint sensitivities for (casadi_int d=0; d<nadj; ++d) { asens_split[d].at(it->data->ind()).at(it->data->segment()) = dwork[it->res.front()][d]; dwork[it->res.front()][d] = MX(); } } else if (it->op==OP_OUTPUT) { // Pass the adjoint seeds for (casadi_int d=0; d<nadj; ++d) { MX a = project(aseed_split[d].at(it->data->ind()).at(it->data->segment()), it->data.dep().sparsity(), true); if (dwork[it->arg.front()][d].is_empty(true)) { dwork[it->arg.front()][d] = a; } else { dwork[it->arg.front()][d] += a; } } } else if (it->op==OP_PARAMETER) { // Clear adjoint seeds for (casadi_int d=0; d<nadj; ++d) { dwork[it->res.front()][d] = MX(); } } else { // Collect and reset seeds oseed.clear(); for (casadi_int d=0; d<nadj; ++d) { // Can the direction be skipped completely? skip[d] = true; // Seeds for direction d vector<MX> seed(it->res.size()); for (casadi_int i=0; i<it->res.size(); ++i) { // Get and clear seed casadi_int el = it->res[i]; if (el>=0) { seed[i] = dwork[el][d]; dwork[el][d] = MX(); } else { seed[i] = MX(); } // If first time encountered, reset to zero of right dimension if (seed[i].is_empty(true)) seed[i] = MX(it->data->sparsity(i).size()); // If nonzero seeds, keep direction if (skip[d] && !seed[i].is_zero()) skip[d] = false; } // Add to list of derivatives if (!skip[d]) oseed.push_back(seed); } // Get values of sensitivities before addition osens.resize(oseed.size()); casadi_int d1=0; for (casadi_int d=0; d<nadj; ++d) { if (skip[d]) continue; osens[d1].resize(it->arg.size()); for (casadi_int i=0; i<it->arg.size(); ++i) { // Pass seed and reset to avoid counting twice casadi_int el = it->arg[i]; if (el>=0) { osens[d1][i] = dwork[el][d]; dwork[el][d] = MX(); } else { osens[d1][i] = MX(); } // If first time encountered, reset to zero of right dimension if (osens[d1][i].is_empty(true)) osens[d1][i] = MX(it->data->dep(i).size()); } d1++; } // Perform the operation if (!osens.empty()) { it->data.ad_reverse(oseed, osens); } // Store sensitivities d1=0; for (casadi_int d=0; d<nadj; ++d) { if (skip[d]) continue; for (casadi_int i=0; i<it->arg.size(); ++i) { casadi_int el = it->arg[i]; if (el>=0) { if (dwork[el][d].is_empty(true)) { dwork[el][d] = osens[d1][i]; } else { dwork[el][d] += osens[d1][i]; } } } d1++; } } } // Get adjoint sensitivities for (casadi_int d=0; d<nadj; ++d) { for (casadi_int i=0; i<in_.size(); ++i) { asens[d][i] = in_[i].join_primitives(asens_split[d][i]); } } } catch (std::exception& e) { CASADI_THROW_ERROR("ad_reverse", e.what()); } } int MXFunction::eval_sx(const SXElem** arg, SXElem** res, casadi_int* iw, SXElem* w, void* mem) const { // Work vector and temporaries to hold pointers to operation input and outputs vector<const SXElem*> argp(sz_arg()); vector<SXElem*> resp(sz_res()); // Evaluate all of the nodes of the algorithm: // should only evaluate nodes that have not yet been calculated! for (auto&& a : algorithm_) { if (a.op==OP_INPUT) { // Pass an input SXElem *w1 = w+workloc_[a.res.front()]; casadi_int nnz=a.data.nnz(); casadi_int i=a.data->ind(); casadi_int nz_offset=a.data->offset(); if (arg[i]==nullptr) { std::fill(w1, w1+nnz, 0); } else { std::copy(arg[i]+nz_offset, arg[i]+nz_offset+nnz, w1); } } else if (a.op==OP_OUTPUT) { // Get the outputs SXElem *w1 = w+workloc_[a.arg.front()]; casadi_int nnz=a.data.dep().nnz(); casadi_int i=a.data->ind(); casadi_int nz_offset=a.data->offset(); if (res[i]) std::copy(w1, w1+nnz, res[i]+nz_offset); } else if (a.op==OP_PARAMETER) { continue; // FIXME } else { // Point pointers to the data corresponding to the element for (casadi_int i=0; i<a.arg.size(); ++i) argp[i] = a.arg[i]>=0 ? w+workloc_[a.arg[i]] : nullptr; for (casadi_int i=0; i<a.res.size(); ++i) resp[i] = a.res[i]>=0 ? w+workloc_[a.res[i]] : nullptr; // Evaluate if (a.data->eval_sx(get_ptr(argp), get_ptr(resp), iw, w)) return 1; } } return 0; } void MXFunction::codegen_declarations(CodeGenerator& g) const { // Make sure that there are no free variables if (!free_vars_.empty()) { casadi_error("Code generation of '" + name_ + "' is not possible since variables " + str(free_vars_) + " are free."); } // Generate code for the embedded functions for (auto&& a : algorithm_) { a.data->add_dependency(g); } } void MXFunction::codegen_incref(CodeGenerator& g) const { set<void*> added; for (auto&& a : algorithm_) { a.data->codegen_incref(g, added); } } void MXFunction::codegen_decref(CodeGenerator& g) const { set<void*> added; for (auto&& a : algorithm_) { a.data->codegen_decref(g, added); } } void MXFunction::codegen_body(CodeGenerator& g) const { // Temporary variables and vectors g.init_local("arg1", "arg+" + str(n_in_)); g.init_local("res1", "res+" + str(n_out_)); // Declare scalar work vector elements as local variables bool first = true; for (casadi_int i=0; i<workloc_.size()-1; ++i) { casadi_int n=workloc_[i+1]-workloc_[i]; if (n==0) continue; if (first) { g << "casadi_real "; first = false; } else { g << ", "; } /* Could use local variables for small work vector elements here, e.g.: ... } else if (n<10) { g << "w" << i << "[" << n << "]"; } else { ... */ if (!g.codegen_scalars && n==1) { g << "w" << i; } else { g << "*w" << i << "=w+" << workloc_[i]; } } if (!first) g << ";\n"; // Operation number (for printing) casadi_int k=0; // Names of operation argument and results vector<casadi_int> arg, res; // Codegen the algorithm for (auto&& e : algorithm_) { // Generate comment if (g.verbose) { g << "/* #" << k++ << ": " << print(e) << " */\n"; } // Get the names of the operation arguments arg.resize(e.arg.size()); for (casadi_int i=0; i<e.arg.size(); ++i) { casadi_int j=e.arg.at(i); if (j>=0 && workloc_.at(j)!=workloc_.at(j+1)) { arg.at(i) = j; } else { arg.at(i) = -1; } } // Get the names of the operation results res.resize(e.res.size()); for (casadi_int i=0; i<e.res.size(); ++i) { casadi_int j=e.res.at(i); if (j>=0 && workloc_.at(j)!=workloc_.at(j+1)) { res.at(i) = j; } else { res.at(i) = -1; } } // Generate operation e.data->generate(g, arg, res); } } void MXFunction::generate_lifted(Function& vdef_fcn, Function& vinit_fcn) const { vector<MX> swork(workloc_.size()-1); vector<MX> arg1, res1; // Get input primitives vector<vector<MX> > in_split(in_.size()); for (casadi_int i=0; i<in_.size(); ++i) in_split[i] = in_[i].primitives(); // Definition of intermediate variables vector<MX> y; vector<MX> g; vector<vector<MX> > f_G(out_.size()); for (casadi_int i=0; i<out_.size(); ++i) f_G[i].resize(out_[i].n_primitives()); // Initial guess for intermediate variables vector<MX> x_init; // Temporary stringstream stringstream ss; for (casadi_int algNo=0; algNo<2; ++algNo) { for (auto&& e : algorithm_) { switch (e.op) { case OP_LIFT: { MX& arg = swork[e.arg.at(0)]; MX& arg_init = swork[e.arg.at(1)]; MX& res = swork[e.res.front()]; switch (algNo) { case 0: ss.str(string()); ss << "y" << y.size(); y.push_back(MX::sym(ss.str(), arg.sparsity())); g.push_back(arg); res = y.back(); break; case 1: x_init.push_back(arg_init); res = arg_init; break; } break; } case OP_INPUT: swork[e.res.front()] = in_split.at(e.data->ind()).at(e.data->segment()); break; case OP_PARAMETER: swork[e.res.front()] = e.data; break; case OP_OUTPUT: if (algNo==0) { f_G.at(e.data->ind()).at(e.data->segment()) = swork[e.arg.front()]; } break; default: { // Arguments of the operation arg1.resize(e.arg.size()); for (casadi_int i=0; i<arg1.size(); ++i) { casadi_int el = e.arg[i]; // index of the argument arg1[i] = el<0 ? MX(e.data->dep(i).size()) : swork[el]; } // Perform the operation res1.resize(e.res.size()); e.data.eval_mx(arg1, res1); // Get the result for (casadi_int i=0; i<res1.size(); ++i) { casadi_int el = e.res[i]; // index of the output if (el>=0) swork[el] = res1[i]; } } } } } // Definition of intermediate variables vector<MX> f_in = in_; f_in.insert(f_in.end(), y.begin(), y.end()); vector<MX> f_out; for (casadi_int i=0; i<out_.size(); ++i) f_out.push_back(out_[i].join_primitives(f_G[i])); f_out.insert(f_out.end(), g.begin(), g.end()); vdef_fcn = Function("lifting_variable_definition", f_in, f_out); // Initial guess of intermediate variables f_in = in_; f_out = x_init; vinit_fcn = Function("lifting_variable_guess", f_in, f_out); } const MX MXFunction::mx_in(casadi_int ind) const { return in_.at(ind); } const std::vector<MX> MXFunction::mx_in() const { return in_; } bool MXFunction::is_a(const std::string& type, bool recursive) const { return type=="MXFunction" || (recursive && XFunction<MXFunction, MX, MXNode>::is_a(type, recursive)); } void MXFunction::substitute_inplace(std::vector<MX>& vdef, std::vector<MX>& ex) const { vector<MX> work(workloc_.size()-1); vector<MX> oarg, ores; for (auto it=algorithm_.begin(); it!=algorithm_.end(); ++it) { switch (it->op) { case OP_INPUT: casadi_assert(it->data->segment()==0, "Not implemented"); work.at(it->res.front()) = vdef.at(it->data->ind()); break; case OP_PARAMETER: case OP_CONST: work.at(it->res.front()) = it->data; break; case OP_OUTPUT: casadi_assert(it->data->segment()==0, "Not implemented"); if (it->data->ind()<vdef.size()) { vdef.at(it->data->ind()) = work.at(it->arg.front()); } else { ex.at(it->data->ind()-vdef.size()) = work.at(it->arg.front()); } break; default: { // Arguments of the operation oarg.resize(it->arg.size()); for (casadi_int i=0; i<oarg.size(); ++i) { casadi_int el = it->arg[i]; oarg[i] = el<0 ? MX(it->data->dep(i).size()) : work.at(el); } // Perform the operation ores.resize(it->res.size()); it->data->eval_mx(oarg, ores); // Get the result for (casadi_int i=0; i<ores.size(); ++i) { casadi_int el = it->res[i]; if (el>=0) work.at(el) = ores[i]; } } } } } bool MXFunction::should_inline(bool always_inline, bool never_inline) const { // If inlining has been specified casadi_assert(!(always_inline && never_inline), "Inconsistent options for " + definition()); casadi_assert(!(never_inline && has_free()), "Must inline " + definition()); if (always_inline) return true; if (never_inline) return false; // Functions with free variables must be inlined if (has_free()) return true; // No inlining by default return false; } void MXFunction::export_code_body(const std::string& lang, std::ostream &ss, const Dict& options) const { // Default values for options casadi_int indent_level = 0; // Read options for (auto&& op : options) { if (op.first=="indent_level") { indent_level = op.second; } else { casadi_error("Unknown option '" + op.first + "'."); } } // Construct indent string std::string indent; for (casadi_int i=0;i<indent_level;++i) { indent += " "; } Function f = shared_from_this<Function>(); // Loop over algorithm for (casadi_int k=0;k<f.n_instructions();++k) { // Get operation casadi_int op = static_cast<casadi_int>(f.instruction_id(k)); // Get MX node MX x = f.instruction_MX(k); // Get input positions into workvector std::vector<casadi_int> o = f.instruction_output(k); // Get output positions into workvector std::vector<casadi_int> i = f.instruction_input(k); switch (op) { case OP_INPUT: ss << indent << "w" << o[0] << " = varargin{" << i[0]+1 << "};" << std::endl; break; case OP_OUTPUT: { Dict info = x.info(); casadi_int segment = info["segment"]; x.dep(0).sparsity().export_code("matlab", ss, {{"name", "sp_in"}, {"indent_level", indent_level}, {"as_matrix", true}}); ss << indent << "argout_" << o[0] << "{" << (1+segment) << "} = "; ss << "w" << i[0] << "(sp_in==1);" << std::endl; } break; case OP_CONST: { DM v = static_cast<DM>(x); Dict opts; opts["name"] = "m"; opts["indent_level"] = indent_level; v.export_code("matlab", ss, opts); ss << indent << "w" << o[0] << " = m;" << std::endl; } break; case OP_SQ: ss << indent << "w" << o[0] << " = " << "w" << i[0] << ".^2;" << std::endl; break; case OP_MTIMES: ss << indent << "w" << o[0] << " = "; ss << "w" << i[1] << "*w" << i[2] << "+w" << i[0] << ";" << std::endl; break; case OP_MUL: { std::string prefix = (x.dep(0).is_scalar() || x.dep(1).is_scalar()) ? "" : "."; ss << indent << "w" << o[0] << " = " << "w" << i[0] << prefix << "*w" << i[1] << ";"; ss << std::endl; } break; case OP_TWICE: ss << indent << "w" << o[0] << " = 2*w" << i[0] << ";" << std::endl; break; case OP_INV: ss << indent << "w" << o[0] << " = 1./w" << i[0] << ";" << std::endl; break; case OP_DOT: ss << indent << "w" << o[0] << " = dot(w" << i[0] << ",w" << i[1]<< ");" << std::endl; break; case OP_BILIN: ss << indent << "w" << o[0] << " = w" << i[1] << ".'*w" << i[0]<< "*w" << i[2] << ";"; ss << std::endl; break; case OP_RANK1: ss << indent << "w" << o[0] << " = w" << i[0] << "+"; ss << "w" << i[1] << "*w" << i[2] << "*w" << i[3] << ".';"; ss << std::endl; break; case OP_FABS: ss << indent << "w" << o[0] << " = abs(w" << i[0] << ");" << std::endl; break; case OP_DETERMINANT: ss << indent << "w" << o[0] << " = det(w" << i[0] << ");" << std::endl; break; case OP_INVERSE: ss << indent << "w" << o[0] << " = inv(w" << i[0] << ");"; ss << "w" << o[0] << "(w" << o[0] << "==0) = 1e-200;" << std::endl; break; case OP_SOLVE: { bool tr = x.info()["tr"]; if (tr) { ss << indent << "w" << o[0] << " = ((w" << i[1] << ".')\\w" << i[0] << ").';"; ss << std::endl; } else { ss << indent << "w" << o[0] << " = w" << i[1] << "\\w" << i[0] << ";" << std::endl; } ss << "w" << o[0] << "(w" << o[0] << "==0) = 1e-200;" << std::endl; } break; case OP_DIV: { std::string prefix = (x.dep(0).is_scalar() || x.dep(1).is_scalar()) ? "" : "."; ss << indent << "w" << o[0] << " = " << "w" << i[0] << prefix << "/w" << i[1] << ";"; ss << std::endl; } break; case OP_POW: case OP_CONSTPOW: ss << indent << "w" << o[0] << " = " << "w" << i[0] << ".^w" << i[1] << ";" << std::endl; break; case OP_TRANSPOSE: ss << indent << "w" << o[0] << " = " << "w" << i[0] << ".';" << std::endl; break; case OP_HORZCAT: case OP_VERTCAT: { ss << indent << "w" << o[0] << " = ["; for (casadi_int e : i) { ss << "w" << e << (op==OP_HORZCAT ? " " : ";"); } ss << "];" << std::endl; } break; case OP_DIAGCAT: { for (casadi_int k=0;k<i.size();++k) { x.dep(k).sparsity().export_code("matlab", ss, {{"name", "sp_in" + str(k)}, {"indent_level", indent_level}, {"as_matrix", true}}); } ss << indent << "w" << o[0] << " = ["; for (casadi_int k=0;k<i.size();++k) { ss << "w" << i[k] << "(sp_in" << k << "==1);"; } ss << "];" << std::endl; Dict opts; opts["name"] = "sp"; opts["indent_level"] = indent_level; opts["as_matrix"] = false; x.sparsity().export_code("matlab", ss, opts); ss << indent << "w" << o[0] << " = "; ss << "sparse(sp_i, sp_j, w" << o[0] << ", sp_m, sp_n);" << std::endl; } break; case OP_HORZSPLIT: case OP_VERTSPLIT: { Dict info = x.info(); std::vector<casadi_int> offset = info["offset"]; casadi::Function output = info["output"]; std::vector<Sparsity> sp; for (casadi_int i=0;i<output.n_out();i++) sp.push_back(output.sparsity_out(i)); for (casadi_int k=0;k<o.size();++k) { if (o[k]==-1) continue; x.dep(0).sparsity().export_code("matlab", ss, {{"name", "sp_in"}, {"indent_level", indent_level}, {"as_matrix", true}}); ss << indent << "tmp = w" << i[0]<< "(sp_in==1);" << std::endl; Dict opts; opts["name"] = "sp"; opts["indent_level"] = indent_level; opts["as_matrix"] = false; sp[k].export_code("matlab", ss, opts); ss << indent << "w" << o[k] << " = sparse(sp_i, sp_j, "; ss << "tmp(" << offset[k]+1 << ":" << offset[k+1] << "), sp_m, sp_n);" << std::endl; } } break; case OP_GETNONZEROS: case OP_SETNONZEROS: { Dict info = x.info(); std::string nonzeros; if (info.find("nz")!=info.end()) { nonzeros = "1+" + str(info["nz"]); } else if (info.find("slice")!=info.end()) { Dict s = info["slice"]; casadi_int start = s["start"]; casadi_int step = s["step"]; casadi_int stop = s["stop"]; nonzeros = str(start+1) + ":" + str(step) + ":" + str(stop); nonzeros = "nonzeros(" + nonzeros + ")"; } else { Dict inner = info["inner"]; Dict outer = info["outer"]; casadi_int inner_start = inner["start"]; casadi_int inner_step = inner["step"]; casadi_int inner_stop = inner["stop"]; casadi_int outer_start = outer["start"]; casadi_int outer_step = outer["step"]; casadi_int outer_stop = outer["stop"]; std::string inner_slice = "(" + str(inner_start) + ":" + str(inner_step) + ":" + str(inner_stop-1)+")"; std::string outer_slice = "(" + str(outer_start+1) + ":" + str(outer_step) + ":" + str(outer_stop)+")"; casadi_int N = range(outer_start, outer_stop, outer_step).size(); casadi_int M = range(inner_start, inner_stop, inner_step).size(); nonzeros = "repmat("+ inner_slice +"', 1, " + str(N) + ")+" + "repmat("+ outer_slice +", " + str(M) + ", 1)"; nonzeros = "nonzeros(" + nonzeros + ")"; } Dict opts; opts["name"] = "sp"; opts["indent_level"] = indent_level; opts["as_matrix"] = false; x.sparsity().export_code("matlab", ss, opts); if (op==OP_GETNONZEROS) { x.dep(0).sparsity().export_code("matlab", ss, {{"name", "sp_in"}, {"indent_level", indent_level}, {"as_matrix", true}}); //ss << indent << "w" << i[0] << "" << std::endl; //ss << indent << "size(w" << i[0] << ")" << std::endl; ss << indent << "in_flat = w" << i[0] << "(sp_in==1);" << std::endl; //ss << indent << "in_flat" << std::endl; //ss << indent << "size(in_flat)" << std::endl; ss << indent << "w" << o[0] << " = in_flat(" << nonzeros << ");" << std::endl; } else { x.dep(0).sparsity().export_code("matlab", ss, {{"name", "sp_in0"}, {"indent_level", indent_level}, {"as_matrix", true}}); x.dep(1).sparsity().export_code("matlab", ss, {{"name", "sp_in1"}, {"indent_level", indent_level}, {"as_matrix", true}}); ss << indent << "in_flat = w" << i[1] << "(sp_in1==1);" << std::endl; ss << indent << "w" << o[0] << " = w" << i[0] << "(sp_in0==1);" << std::endl; ss << indent << "w" << o[0] << "(" << nonzeros << ") = "; if (info["add"]) ss << "w" << o[0] << "(" << nonzeros << ") + "; ss << "in_flat;"; } ss << indent << "w" << o[0] << " = "; ss << "sparse(sp_i, sp_j, w" << o[0] << ", sp_m, sp_n);" << std::endl; } break; case OP_PROJECT: { Dict opts; opts["name"] = "sp"; opts["indent_level"] = indent_level; x.sparsity().export_code("matlab", ss, opts); ss << indent << "w" << o[0] << " = "; ss << "sparse(sp_i, sp_j, w" << i[0] << "(sp==1), sp_m, sp_n);" << std::endl; } break; case OP_NORM1: ss << indent << "w" << o[0] << " = norm(w" << i[0] << ", 1);" << std::endl; break; case OP_NORM2: ss << indent << "w" << o[0] << " = norm(w" << i[0] << ", 2);" << std::endl; break; case OP_NORMF: ss << indent << "w" << o[0] << " = norm(w" << i[0] << ", 'fro');" << std::endl; break; case OP_NORMINF: ss << indent << "w" << o[0] << " = norm(w" << i[0] << ", inf);" << std::endl; break; case OP_MMIN: ss << indent << "w" << o[0] << " = min(w" << i[0] << ");" << std::endl; break; case OP_MMAX: ss << indent << "w" << o[0] << " = max(w" << i[0] << ");" << std::endl; break; case OP_NOT: ss << indent << "w" << o[0] << " = ~" << "w" << i[0] << ";" << std::endl; break; case OP_OR: ss << indent << "w" << o[0] << " = w" << i[0] << " | w" << i[1] << ";" << std::endl; break; case OP_AND: ss << indent << "w" << o[0] << " = w" << i[0] << " & w" << i[1] << ";" << std::endl; break; case OP_NE: ss << indent << "w" << o[0] << " = w" << i[0] << " ~= w" << i[1] << ";" << std::endl; break; case OP_IF_ELSE_ZERO: ss << indent << "w" << o[0] << " = "; ss << "if_else_zero_gen(w" << i[0] << ", w" << i[1] << ");" << std::endl; break; case OP_RESHAPE: { x.dep(0).sparsity().export_code("matlab", ss, {{"name", "sp_in"}, {"indent_level", indent_level}, {"as_matrix", true}}); x.sparsity().export_code("matlab", ss, {{"name", "sp_out"}, {"indent_level", indent_level}, {"as_matrix", false}}); ss << indent << "w" << o[0] << " = sparse(sp_out_i, sp_out_j, "; ss << "w" << i[0] << "(sp_in==1), sp_out_m, sp_out_n);" << std::endl; } break; default: if (x.is_binary()) { ss << indent << "w" << o[0] << " = " << casadi::casadi_math<double>::print(op, "w"+std::to_string(i[0]), "w"+std::to_string(i[1])) << ";" << std::endl; } else if (x.is_unary()) { ss << indent << "w" << o[0] << " = " << casadi::casadi_math<double>::print(op, "w"+std::to_string(i[0])) << ";" << std::endl; } else { ss << "unknown" + x.class_name() << std::endl; } } } } Dict MXFunction::get_stats(void* mem) const { Dict stats = XFunction::get_stats(mem); Function dep; for (auto&& e : algorithm_) { if (e.op==OP_CALL) { Function d = e.data.which_function(); if (d.is_a("conic", true)) { if (!dep.is_null()) return stats; dep = d; } } } if (dep.is_null()) return stats; return dep.stats(1); } void MXFunction::serialize_body(SerializingStream &s) const { XFunction<MXFunction, MX, MXNode>::serialize_body(s); s.version("MXFunction", 1); s.pack("MXFunction::n_instr", algorithm_.size()); // Loop over algorithm for (const auto& e : algorithm_) { s.pack("MXFunction::alg::data", e.data); s.pack("MXFunction::alg::arg", e.arg); s.pack("MXFunction::alg::res", e.res); } s.pack("MXFunction::workloc", workloc_); s.pack("MXFunction::free_vars", free_vars_); s.pack("MXFunction::default_in", default_in_); s.pack("MXFunction::live_variables", live_variables_); XFunction<MXFunction, MX, MXNode>::delayed_serialize_members(s); } MXFunction::MXFunction(DeserializingStream& s) : XFunction<MXFunction, MX, MXNode>(s) { s.version("MXFunction", 1); size_t n_instructions; s.unpack("MXFunction::n_instr", n_instructions); algorithm_.resize(n_instructions); for (casadi_int k=0;k<n_instructions;++k) { AlgEl& e = algorithm_[k]; s.unpack("MXFunction::alg::data", e.data); e.op = e.data.op(); s.unpack("MXFunction::alg::arg", e.arg); s.unpack("MXFunction::alg::res", e.res); } s.unpack("MXFunction::workloc", workloc_); s.unpack("MXFunction::free_vars", free_vars_); s.unpack("MXFunction::default_in", default_in_); s.unpack("MXFunction::live_variables", live_variables_); XFunction<MXFunction, MX, MXNode>::delayed_deserialize_members(s); } ProtoFunction* MXFunction::deserialize(DeserializingStream& s) { return new MXFunction(s); } } // namespace casadi
34.70364
100
0.507275
[ "vector" ]
a0d1b5ae67a0789d9fe0d14e5db7b1e9cfb063fa
24,933
cpp
C++
src/tiddlerstore_qt/tiddlerstore_handler_qt.cpp
edersasch/cpp_experiments
adf57eed97e9095de673489a5cff9b56263cef29
[ "MIT" ]
null
null
null
src/tiddlerstore_qt/tiddlerstore_handler_qt.cpp
edersasch/cpp_experiments
adf57eed97e9095de673489a5cff9b56263cef29
[ "MIT" ]
null
null
null
src/tiddlerstore_qt/tiddlerstore_handler_qt.cpp
edersasch/cpp_experiments
adf57eed97e9095de673489a5cff9b56263cef29
[ "MIT" ]
null
null
null
#include "tiddlerstore_handler_qt.h" #include "tiddlerstore/tiddlerstore.h" #include <QMenu> #include <QLineEdit> #include <QStyle> #include <QToolButton> #include <QListView> #include <QStandardPaths> #include <QFileDialog> #include <QHBoxLayout> #include <QVBoxLayout> #include <QFormLayout> #include <QGroupBox> #include <QComboBox> #include <QCompleter> #include <QLabel> #include <QMouseEvent> #include <utility> Flow_List_View::Flow_List_View(QWidget* parent) : QListView(parent) { setFlow(QListView::LeftToRight); setWrapping(true); setResizeMode(QListView::Adjust); setSpacing(2); } void Flow_List_View::doItemsLayout() { QListView::doItemsLayout(); setMaximumSize(QWIDGETSIZE_MAX, contentsSize().height() + 2); } void Flow_List_View::mouseMoveEvent(QMouseEvent* event) { QModelIndex index = indexAt(event->pos()); if (index.row() != hoverRow || state() != QAbstractItemView::NoState) { delete_del_button(); if (index.row() != -1 && state() == QAbstractItemView::NoState) { hoverRow = index.row(); del_button = new QToolButton(this); del_button->setStyleSheet("background-color: rgba(255, 255, 255, 0); border: none;"); auto rect = visualRect(index); rect.setWidth(rect.height()); del_button->setGeometry(rect); del_button->show(); connect(del_button, &QToolButton::clicked, del_button, [this, index] { delete_del_button(); model()->removeRow(index.row()); }); } } QListView::mouseMoveEvent(event); } void Flow_List_View::leaveEvent(QEvent* event) { delete_del_button(); QListView::leaveEvent(event); } // private void Flow_List_View::delete_del_button() { if (del_button) { del_button->deleteLater(); } del_button = nullptr; hoverRow = -1; } Move_Only_StandardItemModel::Move_Only_StandardItemModel(QObject* parent) : QStandardItemModel(parent) { } Qt::ItemFlags Move_Only_StandardItemModel::flags(const QModelIndex& index) const { return index.isValid() ? QStandardItemModel::flags(index) & ~Qt::ItemIsDropEnabled : QStandardItemModel::flags(index); } Qt::DropActions Move_Only_StandardItemModel::supportedDropActions() const { return Qt::MoveAction; } bool Move_Only_StandardItemModel::dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent) { if (parent.isValid()) { return false; } return QStandardItemModel::dropMimeData(data, action, row, column, parent); } namespace { void clear_layout(QLayout* l) { QLayoutItem* child; while ((child = l->takeAt(0) ) != nullptr) { if (child->widget()) { child->widget()->deleteLater(); } auto cl = child->layout(); if (cl) { clear_layout(cl); } delete child; } } } Tiddlerstore_Handler::Tiddlerstore_Handler(const QStringList& tiddlerstore_list, QWidget* parent) : QWidget(parent) , tiddlerstore_history(tiddlerstore_list) , tiddler_list_view(new QListView(this)) , load_button(new QToolButton(this)) , load_history_menu(new QMenu(tr("Attention! Unsaved Changes"), this)) , filter_layout(new QVBoxLayout) { auto main_layout(new QVBoxLayout(this)); main_layout->addLayout(setup_toolbar()); setup_filter(); main_layout->addLayout(filter_layout); setup_tiddler_list_view(); main_layout->addWidget(tiddler_list_view); connect(&store_model, &Tiddlerstore_Model::model_created, this, &Tiddlerstore_Handler::connect_model); connect(&store_model, &Tiddlerstore_Model::removed, this, &Tiddlerstore_Handler::set_dirty); auto elems = tiddlerstore_history.get_elements(); if (!elems.isEmpty()) { open_store(elems.first()); } } Tiddlerstore_Handler::~Tiddlerstore_Handler() = default; // private QHBoxLayout* Tiddlerstore_Handler::setup_toolbar() { auto layout = new QHBoxLayout; setup_load_button(); layout->addWidget(load_button); layout->addWidget(setup_save_button()); layout->addStretch(); return layout; } void Tiddlerstore_Handler::setup_load_button() { connect(load_history_menu, &QMenu::aboutToShow, load_history_menu, [this] { auto elems = tiddlerstore_history.get_elements(); auto default_location = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation); load_history_menu->clear(); for (auto it = elems.begin(); it != elems.end(); it += 1) { auto path = *it; auto load = load_history_menu->addAction(path); connect(load, &QAction::triggered, this, [this, path] { open_store(path); }); } auto load_other = load_history_menu->addAction("..."); connect(load_other, &QAction::triggered, this, [this, default_location] { auto path = QFileDialog::getOpenFileName(nullptr, tr("Select Tiddlerstore"), default_location); if (!path.isEmpty()) { open_store(path); } }); }); load_button->setIcon(style()->standardIcon(QStyle::SP_DialogOpenButton)); load_button->setPopupMode(QToolButton::InstantPopup); load_button->setMenu(load_history_menu); } QToolButton* Tiddlerstore_Handler::setup_save_button() { auto save_menu(new QMenu(this)); connect(save_menu, &QMenu::aboutToShow, save_menu, [this, save_menu] { auto elems = tiddlerstore_history.get_elements(); auto default_location = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation); save_menu->clear(); if (!elems.isEmpty()) { auto save_current = save_menu->addAction(elems.first()); connect(save_current, &QAction::triggered, this, [this, save_current]{ save_store(save_current->text()); }); QFileInfo fi(elems.first()); default_location = fi.path(); } auto save_other = save_menu->addAction("..."); connect(save_other, &QAction::triggered, save_other, [this, default_location] { auto other_name = QFileDialog::getSaveFileName(nullptr, tr("Where do you want to save?"), default_location); if (!other_name.isEmpty()) { save_store(other_name); } }); }); auto save_button(new QToolButton(this)); save_button->setIcon(style()->standardIcon(QStyle::SP_DialogSaveButton)); save_button->setPopupMode(QToolButton::InstantPopup); save_button->setMenu(save_menu); return save_button; } void Tiddlerstore_Handler::setup_tiddler_list_view() { title_sort_model.setSourceModel(&title_model); title_sort_model.sort(0); tiddler_list_view->setModel(&title_sort_model); tiddler_list_view->setEditTriggers(QAbstractItemView::NoEditTriggers); connect(tiddler_list_view, &QListView::clicked, tiddler_list_view, [this](const QModelIndex& index) { prepare_open(*store[static_cast<std::size_t>(source_row(index.row()))]); }); } void Tiddlerstore_Handler::setup_main_title_filter() { if (!main_title_filter_edit) { main_title_filter_edit = new QLineEdit(this); main_title_filter_edit->setClearButtonEnabled(true); main_title_filter_open_action = main_title_filter_edit->addAction(style()->standardIcon(QStyle::SP_DirOpenIcon), QLineEdit::LeadingPosition); main_title_filter_open_action->setVisible(false); connect(main_title_filter_open_action, &QAction::triggered, main_title_filter_open_action, [this] { for (int i = 0; i < title_sort_model.rowCount(); i += 1) { if (!tiddler_list_view->isRowHidden(i)) { prepare_open(*store[static_cast<std::size_t>(source_row(i))]); return; } } }); main_title_filter_add_action = main_title_filter_edit->addAction(style()->standardIcon(QStyle::SP_FileDialogNewFolder), QLineEdit::LeadingPosition); main_title_filter_add_action->setVisible(false); connect(main_title_filter_add_action, &QAction::triggered, main_title_filter_add_action, [this] { auto& t = *store.emplace_back(new Tiddlerstore::Tiddler); adjust_dirty(true); t.set_title(main_title_filter_edit->text().toStdString()); if (t.title().empty()) { t.set_title(tr("New Entry ...").toStdString()); } main_title_filter_edit->clear(); prepare_open(t); set_dirty(); }); main_title_filter_placeholder_action = main_title_filter_edit->addAction(style()->standardIcon(QStyle::SP_FileIcon), QLineEdit::LeadingPosition); connect(main_title_filter_edit, &QLineEdit::returnPressed, main_title_filter_edit, [this] { if (main_title_filter_open_action->isVisible()) { main_title_filter_open_action->trigger(); } else { if (main_title_filter_add_action->isVisible()) { main_title_filter_add_action->trigger(); } } }); } } void Tiddlerstore_Handler::setup_filter() { if (filter_groups.empty()) { auto single_group = filter_groups.emplace_back(new Tiddlerstore::Single_Group).get(); single_group->emplace_back(new Tiddlerstore::Filter_Data); setup_main_title_filter(); connect(main_title_filter_edit, &QLineEdit::textChanged, main_title_filter_edit, [this, single_group] (const QString& text) { single_group->front()->key = text.toStdString(); apply_filter(); }); } else { main_title_filter_edit->parentWidget()->layout()->removeWidget(main_title_filter_edit); main_title_filter_edit->setParent(this); clear_layout(filter_layout); } filter_groups.erase(std::remove_if(filter_groups.begin(), filter_groups.end(), [this](auto& single_group) { if (single_group->empty()) { return true; } add_single_group(*single_group); return false; }), filter_groups.end()); auto empty_group = filter_groups.emplace_back(new Tiddlerstore::Single_Group).get(); add_single_group(*empty_group); } void Tiddlerstore_Handler::add_single_group(Tiddlerstore::Single_Group& single_group) { auto group_box = new QGroupBox(this); group_box->setContentsMargins(0, 0, 0, 0); group_box->setFlat(true); auto group_layout = new QVBoxLayout(group_box); auto filter_form_layout = new QFormLayout; QStringList title_opt {"title"}; QStringList text_opt {"text"}; QStringList tag_opts; QStringList field_opts; QStringList list_opts; for (const auto& t : present_tags) { tag_opts.append(t.c_str()); } for (const auto& t : present_fields) { field_opts.append(t.c_str()); } for (const auto& t : present_lists) { list_opts.append(t.c_str()); } if (filter_layout->count() == 0) { group_layout->addWidget(main_title_filter_edit); } group_layout->addLayout(filter_form_layout); for (auto& filter_data : single_group) { QToolButton* del = nullptr; switch (filter_data->filter_type) { case Tiddlerstore::Filter_Type::Title: if (filter_layout->count() > 0 || filter_data != single_group.front()) { del = add_title_filter(*filter_data, filter_form_layout); } break; case Tiddlerstore::Filter_Type::Text: del = add_text_filter(*filter_data, filter_form_layout); break; case Tiddlerstore::Filter_Type::Tag: del = add_tag_filter(*filter_data, filter_form_layout); tag_opts.removeAll(filter_data->key.c_str()); break; case Tiddlerstore::Filter_Type::Field: del = add_field_filter(*filter_data, filter_form_layout); break; case Tiddlerstore::Filter_Type::List: del = add_list_filter(*filter_data, filter_form_layout); break; } if (del) { const auto fd_ptr = filter_data.get(); connect(del, &QToolButton::clicked, del, [this, &single_group, fd_ptr] { auto it = std::find_if(single_group.begin(), single_group.end(), [fd_ptr](const auto& f_data) { return f_data.get() == fd_ptr; }); if(it != single_group.end()) { single_group.erase(it); } setup_filter(); apply_filter(); }); } } QStringList remaining_opts; remaining_opts << title_opt; remaining_opts << text_opt; for (const auto& o : tag_opts) { remaining_opts.append(QString("tag: ") + o); } for (const auto& o : field_opts) { remaining_opts.append(QString("field: ") + o); } for (const auto& o : list_opts) { remaining_opts.append(QString("list: ") + o); } auto box = new QComboBox(this); box->insertItems(0, remaining_opts); box->setEditable(true); box->setInsertPolicy(QComboBox::NoInsert); box->setEditText(QString()); box->setCurrentIndex(-1); box->completer()->setFilterMode(Qt::MatchContains); box->completer()->setCaseSensitivity(Qt::CaseInsensitive); box->completer()->setCompletionMode(QCompleter::PopupCompletion); connect(box, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), box, [this, title_opt, text_opt, tag_opts, field_opts, list_opts, &single_group](int index) { auto add_to_group = [this, &index, &single_group](const QStringList& opts, Tiddlerstore::Filter_Data filter_data) { if (index < opts.size()) { single_group.emplace_back(new Tiddlerstore::Filter_Data(std::move(filter_data))); setup_filter(); apply_filter(); return true; } index -= opts.size(); return false; }; add_to_group(title_opt, {Tiddlerstore::Filter_Type::Title}) || add_to_group(text_opt, {Tiddlerstore::Filter_Type::Text}) || add_to_group(tag_opts, {Tiddlerstore::Filter_Type::Tag, false, index < tag_opts.size() ? tag_opts[index].toStdString() : std::string()}) || add_to_group(field_opts, {Tiddlerstore::Filter_Type::Field, false, index < field_opts.size() ? field_opts[index].toStdString() : std::string()}) || add_to_group(list_opts, {Tiddlerstore::Filter_Type::List, false, index < list_opts.size() ? list_opts[index].toStdString() : std::string()}); }); group_layout->addWidget(box); filter_layout->addWidget(group_box); } void Tiddlerstore_Handler::add_negate_button(Tiddlerstore::Filter_Data& filter_data, QLayout* layout) { auto negate_button = new QToolButton(this); negate_button->setCheckable(true); negate_button->setChecked(filter_data.negate); connect(negate_button, &QToolButton::toggled, negate_button, [this, &filter_data](bool checked) { filter_data.negate = checked; apply_filter(); }); layout->addWidget(negate_button); } QToolButton* Tiddlerstore_Handler::add_label_del_row(const QString& text, QLayout* single_filter_functions, QFormLayout* filter_form_layout) { auto label = new QLabel(text, this); auto delete_button = new QToolButton(this); delete_button->setIcon(style()->standardIcon(QStyle::SP_TrashIcon)); single_filter_functions->addWidget(delete_button); filter_form_layout->addRow(label, single_filter_functions); return delete_button; } QToolButton* Tiddlerstore_Handler::add_title_filter(Tiddlerstore::Filter_Data& filter_data, QFormLayout* filter_form_layout) { auto single_filter_functions = new QHBoxLayout; add_negate_button(filter_data, single_filter_functions); auto line_edit = new QLineEdit(this); line_edit->setText(filter_data.key.c_str()); connect(line_edit, &QLineEdit::textChanged, line_edit, [this, &filter_data](const QString& text) { filter_data.key = text.toStdString(); apply_filter(); }); single_filter_functions->addWidget(line_edit); return add_label_del_row(tr("Title"), single_filter_functions, filter_form_layout); } QToolButton* Tiddlerstore_Handler::add_text_filter(Tiddlerstore::Filter_Data& filter_data, QFormLayout* filter_form_layout) { auto single_filter_functions = new QHBoxLayout; add_negate_button(filter_data, single_filter_functions); auto line_edit = new QLineEdit(this); line_edit->setText(filter_data.key.c_str()); connect(line_edit, &QLineEdit::textChanged, line_edit, [this, &filter_data](const QString& text) { filter_data.key = text.toStdString(); apply_filter(); }); single_filter_functions->addWidget(line_edit); return add_label_del_row(tr("Text"), single_filter_functions, filter_form_layout); } QToolButton* Tiddlerstore_Handler::add_tag_filter(Tiddlerstore::Filter_Data& filter_data, QFormLayout* filter_form_layout) { auto single_filter_functions = new QHBoxLayout; add_negate_button(filter_data, single_filter_functions); auto tag_value = new QLabel(filter_data.key.c_str(), this); single_filter_functions->addWidget(tag_value); return add_label_del_row(tr("Tag"), single_filter_functions, filter_form_layout); } QToolButton* Tiddlerstore_Handler::add_field_filter(Tiddlerstore::Filter_Data& filter_data, QFormLayout* filter_form_layout) { auto single_filter_functions = new QHBoxLayout; add_negate_button(filter_data, single_filter_functions); auto line_edit = new QLineEdit(this); line_edit->setText(filter_data.field_value.c_str()); connect(line_edit, &QLineEdit::textChanged, line_edit, [this, &filter_data](const QString& text) { filter_data.field_value = text.toStdString(); apply_filter(); }); single_filter_functions->addWidget(line_edit); return add_label_del_row(tr("Field: ") + filter_data.key.c_str(), single_filter_functions, filter_form_layout); } QToolButton* Tiddlerstore_Handler::add_list_filter(Tiddlerstore::Filter_Data& filter_data, QFormLayout* filter_form_layout) { auto single_filter_functions = new QHBoxLayout; add_negate_button(filter_data, single_filter_functions); auto list_view = new Flow_List_View(this); list_view->setDropIndicatorShown(true); list_view->setDragDropMode(QAbstractItemView::InternalMove); list_view->setMouseTracking(true); auto list_model = new Move_Only_StandardItemModel; list_view->setModel(list_model); auto list_handler = new QWidget(this); auto list_handler_layout = new QVBoxLayout(list_handler); list_handler_layout->addWidget(list_view); auto entry_enter_edit = new QLineEdit(this); entry_enter_edit->setClearButtonEnabled(true); entry_enter_edit->addAction(style()->standardIcon(QStyle::SP_DialogApplyButton), QLineEdit::LeadingPosition); auto add_to_list_model = [this, list_model, list_view](const std::string& text) { auto item = new QStandardItem(text.c_str()); list_model->appendRow(item); auto rect = list_view->visualRect(item->index()); if (list_view->iconSize().height() > rect.height()) { list_view->setIconSize(QSize(rect.height(), rect.height())); } item->setIcon(style()->standardIcon(QStyle::SP_TitleBarCloseButton)); }; for (const auto& text : filter_data.list_value) { add_to_list_model(text); } connect(entry_enter_edit, &QLineEdit::returnPressed, entry_enter_edit, [add_to_list_model, entry_enter_edit]() { auto text = entry_enter_edit->text().toStdString(); if (!text.empty()) { add_to_list_model(text); entry_enter_edit->clear(); } }); list_handler_layout->addWidget(entry_enter_edit); // try to make the empty list view as high as a single line list_view->setMinimumSize(QSize(1, entry_enter_edit->height() - entry_enter_edit->contentsMargins().top() - entry_enter_edit->contentsMargins().bottom())); single_filter_functions->addWidget(list_handler); connect(list_model, &QStandardItemModel::dataChanged, list_model, [&filter_data, list_model](const QModelIndex& topLeft, const QModelIndex& bottomRight) { int i = topLeft.row(); int j = bottomRight.row(); while (i <= j) { auto text = list_model->item(i)->text(); if (text.isEmpty()) { list_model->removeRow(i); j -= 1; } else { if (static_cast<std::size_t>(i) < filter_data.list_value.size()) { filter_data.list_value[static_cast<std::size_t>(i)] = text.toStdString(); } i += 1; } } }); connect(list_model, &QStandardItemModel::rowsRemoved, list_model, [&filter_data](const QModelIndex&, int first, int last) { for (int i = first; i <= last && i < static_cast<int>(filter_data.list_value.size()); i += 1) { filter_data.list_value.erase(filter_data.list_value.begin() + i); } }); connect(list_model, &QStandardItemModel::rowsInserted, list_model, [&filter_data, list_model](const QModelIndex&, int first, int last) { for (int i = first; i <= last; i += 1) { auto item = list_model->item(i); filter_data.list_value.insert(filter_data.list_value.begin() + i, item ? list_model->item(i)->text().toStdString() : std::string()); } }); return add_label_del_row(tr("List: ") + filter_data.key.c_str(), single_filter_functions, filter_form_layout); } void Tiddlerstore_Handler::connect_model(Tiddler_Model* model) { connect(model, &Tiddler_Model::title_changed, this, &Tiddlerstore_Handler::set_dirty); connect(model, &Tiddler_Model::text_changed, this, &Tiddlerstore_Handler::set_dirty); connect(model, &Tiddler_Model::history_size_changed, this, &Tiddlerstore_Handler::set_dirty); connect(model, &Tiddler_Model::tags_changed, this, &Tiddlerstore_Handler::set_dirty); connect(model, &Tiddler_Model::field_changed, this, &Tiddlerstore_Handler::set_dirty); connect(model, &Tiddler_Model::field_added, this, &Tiddlerstore_Handler::set_dirty); connect(model, &Tiddler_Model::field_removed, this, &Tiddlerstore_Handler::set_dirty); connect(model, &Tiddler_Model::list_changed, this, &Tiddlerstore_Handler::set_dirty); connect(model, &Tiddler_Model::list_added, this, &Tiddlerstore_Handler::set_dirty); connect(model, &Tiddler_Model::list_removed, this, &Tiddlerstore_Handler::set_dirty); set_dirty(); } void Tiddlerstore_Handler::apply_filter() { auto idx = Tiddlerstore::apply_filter(store, filter_groups).filtered_idx(); for (int i = 0; i < title_sort_model.rowCount(); i += 1) { tiddler_list_view->setRowHidden(i, std::find(idx.begin(), idx.end(), source_row(i)) == idx.end()); } bool show_open = idx.size() == 1; bool show_add = idx.empty(); main_title_filter_open_action->setVisible(show_open); main_title_filter_add_action->setVisible(show_add); main_title_filter_placeholder_action->setVisible(!(show_open || show_add)); } void Tiddlerstore_Handler::adjust_dirty(bool dirty_value) { if (dirty_value != is_dirty) { is_dirty = dirty_value; if (is_dirty) { if (!load_safety_menu) { load_safety_menu = new QMenu; } load_button->setMenu(load_safety_menu); load_safety_menu->addMenu(load_history_menu); } else { load_button->setMenu(load_history_menu); } } present_tags = Tiddlerstore::store_tags(store); present_fields = Tiddlerstore::store_fields(store); present_lists = Tiddlerstore::store_lists(store); QStringList titles; for (const auto& t : store) { titles << t->title().c_str(); } title_model.setStringList(titles); setup_filter(); apply_filter(); } void Tiddlerstore_Handler::open_store(const QString& path) { store = Tiddlerstore::open_store_from_file(path.toStdString()); adjust_dirty(false); } void Tiddlerstore_Handler::save_store(const QString& path) { if (Tiddlerstore::save_store_to_file(store, path.toStdString())) { tiddlerstore_history.set_current_element(path); adjust_dirty(false); } } void Tiddlerstore_Handler::prepare_open(Tiddlerstore::Tiddler& t) { auto model = store_model.model_for_tiddler(t); if (model) { emit open_tiddler_model(model); } } int Tiddlerstore_Handler::source_row(int filter_row) { return title_sort_model.mapToSource(title_sort_model.index(filter_row, 0)).row(); }
40.410049
182
0.670838
[ "model" ]
a0d2da391fcd03c53b6072f8626c87f37c1c8cc4
6,072
cpp
C++
tests/unittests/testctiglcurvestosurface.cpp
cfsengineering/tigl
abfbb57b82dc6beac7cde212a4cd5e0aed866db8
[ "Apache-2.0" ]
171
2015-04-13T11:24:34.000Z
2022-03-26T00:56:38.000Z
tests/unittests/testctiglcurvestosurface.cpp
cfsengineering/tigl
abfbb57b82dc6beac7cde212a4cd5e0aed866db8
[ "Apache-2.0" ]
620
2015-01-20T08:34:36.000Z
2022-03-30T11:05:33.000Z
tests/unittests/testctiglcurvestosurface.cpp
cfsengineering/tigl
abfbb57b82dc6beac7cde212a4cd5e0aed866db8
[ "Apache-2.0" ]
56
2015-02-09T13:33:56.000Z
2022-03-19T04:52:51.000Z
#include "test.h" #include "CTiglCurvesToSurface.h" #include <TColgp_Array1OfPnt.hxx> #include <TColStd_Array1OfReal.hxx> #include <TColStd_Array1OfInteger.hxx> #include <Geom_BSplineCurve.hxx> #include <Geom_BSplineSurface.hxx> #include <TopoDS.hxx> #include <TopoDS_Edge.hxx> #include <BRep_Builder.hxx> #include <BRepTools.hxx> #include <BRep_Builder.hxx> #include <TopExp_Explorer.hxx> #include <GeomConvert.hxx> #include <Precision.hxx> #include <BRepBuilderAPI_MakeFace.hxx> #include <sstream> #include <tiglcommonfunctions.h> #include <Geom_BSplineCurve.hxx> namespace tigl { TEST(CTiglCurvesToSurface, testSkinnedBSplineSurface) { /* * Tests the method skinning_bspline_surface(spline_list, degree_v_direction, parameters) by creating a skinned * surface by two B-splines (argument u), Skinning direction is v, so: * surface(u, v) = curve1(u) * (1 - v) + curve2(u) * v */ // degree of both B-splines unsigned int degree_u = 2; // create first B-spline that represents the parabola f(x) = (x - 0.5)^2 in order to being able to test it afterwards TColgp_Array1OfPnt controlPoints1(1, 3); controlPoints1(1) = gp_Pnt(0., 6., 0.25); controlPoints1(2) = gp_Pnt(0.5, 6., - 0.25); controlPoints1(3) = gp_Pnt(1., 6., 0.25); TColStd_Array1OfReal knots(1, 2); knots(1) = 0.; knots(2) = 1.; TColStd_Array1OfInteger mults(1, 2); mults(1) = 3; mults(2) = 3; Handle(Geom_BSplineCurve) curve1 = new Geom_BSplineCurve(controlPoints1, knots, mults, degree_u); // create second B-spline that represents the parabola g(x) = - (x - 0.5)^2 in order to being able to test it afterwards TColgp_Array1OfPnt controlPoints2(1, 3); controlPoints2(1) = gp_Pnt(0., 0., - 0.25); controlPoints2(2) = gp_Pnt(0.5, 0., 0.25); controlPoints2(3) = gp_Pnt(1., 0., - 0.25); Handle(Geom_BSplineCurve) curve2 = new Geom_BSplineCurve(controlPoints2, knots, mults, degree_u); std::vector<Handle(Geom_Curve) > splines_vector; splines_vector.push_back(curve1); splines_vector.push_back(curve2); CTiglCurvesToSurface skinner(splines_vector); Handle(Geom_BSplineSurface) skinnedSurface = skinner.Surface(); // now test the skinned surface for (int u_idx = 0; u_idx < 100; ++u_idx) { for (int v_idx = 0; v_idx < 100; ++v_idx) { double u_value = u_idx / 100.; double v_value = v_idx / 100.; gp_Pnt surface_point = skinnedSurface->Value(u_value, v_value); gp_Pnt point_curve1 = curve1->Value(u_value); gp_Pnt point_curve2 = curve2->Value(u_value); gp_Pnt right_point(point_curve1.X() * (1 - v_value) + point_curve2.X() * v_value, point_curve1.Y() * (1 - v_value) + point_curve2.Y() * v_value, point_curve1.Z() * (1 - v_value) + point_curve2.Z() * v_value); ASSERT_NEAR(surface_point.X(), right_point.X(), 1e-15); ASSERT_NEAR(surface_point.Y(), right_point.Y(), 1e-15); ASSERT_NEAR(surface_point.Z(), right_point.Z(), 1e-15); } } } TEST(TiglBSplineAlgorithms, curvesToSurfaceContinous) { // Read in nacelle data from BRep TopoDS_Shape shape_u; BRep_Builder builder_u; BRepTools::Read(shape_u, "TestData/CurveNetworks/fuselage1/guides.brep", builder_u); // get the splines in u-direction from the Edges std::vector<Handle(Geom_Curve)> curves; for (TopExp_Explorer exp(shape_u, TopAbs_EDGE); exp.More(); exp.Next()) { TopoDS_Edge curve_edge = TopoDS::Edge(exp.Current()); double beginning = 0; double end = 1; Handle(Geom_Curve) curve = BRep_Tool::Curve(curve_edge, beginning, end); Handle(Geom_BSplineCurve) spline = GeomConvert::CurveToBSplineCurve(curve); curves.push_back(spline); } CTiglCurvesToSurface skinner(curves, true); Handle(Geom_BSplineSurface) surface = skinner.Surface(); double umin, umax, vmin, vmax; surface->Bounds(umin, umax, vmin, vmax); EXPECT_TRUE(surface->DN(umin, vmin, 0, 0).IsEqual(surface->DN(umin, vmax, 0, 0), 1e-10, 1e-6)); EXPECT_TRUE(surface->DN(umin, vmin, 0, 1).IsEqual(surface->DN(umin, vmax, 0, 1), 1e-10, 1e-6)); double umean = 0.5 * (umin + umax); EXPECT_TRUE(surface->DN(umean, vmin, 0, 0).IsEqual(surface->DN(umean, vmax, 0, 0), 1e-10, 1e-6)); EXPECT_TRUE(surface->DN(umean, vmin, 0, 1).IsEqual(surface->DN(umean, vmax, 0, 1), 1e-10, 1e-6)); EXPECT_TRUE(surface->DN(umax, vmin, 0, 0).IsEqual(surface->DN(umax, vmax, 0, 0), 1e-10, 1e-6)); EXPECT_TRUE(surface->DN(umax, vmin, 0, 1).IsEqual(surface->DN(umax, vmax, 0, 1), 1e-10, 1e-6)); // Write surface BRepTools::Write(BRepBuilderAPI_MakeFace(surface, Precision::Confusion()).Face(), "TestData/curvesToSurfaceContinous.brep"); } TEST(TiglBSplineAlgorithms, curvesToSurfaceBug) { std::vector<Handle(Geom_Curve)> profileCurves; double xmin=1e6; double xmax=-1e6; for (int i = 5; i<9; ++i) { std::stringstream ss; ss << "TestData/bugs/501/edge_1_profile_" << i << ".brep"; TopoDS_Edge edge; BRep_Builder builder; BRepTools::Read(edge, ss.str().c_str(), builder); Standard_Real umin, umax; Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, umin, umax); gp_Vec p = curve->DN(umin, 0); xmin = p.X() < xmin ? p.X() : xmin; xmax = p.X() > xmax ? p.X() : xmax; profileCurves.push_back(GetBSplineCurve(edge)); } tigl::CTiglCurvesToSurface surfaceSkinner(profileCurves); surfaceSkinner.SetMaxDegree(1); Handle(Geom_BSplineSurface) surface = surfaceSkinner.Surface(); double umin, umax, vmin, vmax; surface->Bounds(umin, umax, vmin, vmax); double u = umin + 0.999*(umax-umin); gp_Vec p = surface->DN(u, vmin + 0.95*(vmax-vmin), 0, 0); EXPECT_TRUE(p.X() <= xmax); EXPECT_TRUE(p.X() >= xmin); BRepBuilderAPI_MakeFace faceMaker(surface, 1e-10); TopoDS_Face result = faceMaker.Face(); BRepTools::Write(result, "TestData/bugs/501/resultShape.brep"); } }
35.302326
220
0.662879
[ "vector" ]
a0d5e6e488c7ad29687cd4d563fc5aeb1d98d0d9
887
hpp
C++
expert/abstract_expert.hpp
BowenforGit/Grasper
268468d6eb0a56e9a4815c0c1d7660b06bf8a1f7
[ "Apache-2.0" ]
29
2019-11-18T14:25:05.000Z
2022-02-10T07:21:48.000Z
expert/abstract_expert.hpp
BowenforGit/Grasper
268468d6eb0a56e9a4815c0c1d7660b06bf8a1f7
[ "Apache-2.0" ]
2
2021-03-17T03:17:38.000Z
2021-04-11T04:06:23.000Z
expert/abstract_expert.hpp
BowenforGit/Grasper
268468d6eb0a56e9a4815c0c1d7660b06bf8a1f7
[ "Apache-2.0" ]
6
2019-11-21T18:04:15.000Z
2022-03-01T02:48:50.000Z
/* Copyright 2019 Husky Data Lab, CUHK Authors: Hongzhi Chen (hzchen@cse.cuhk.edu.hk) */ #ifndef ABSTRACT_EXPERT_HPP_ #define ABSTRACT_EXPERT_HPP_ #include <string> #include <vector> #include <thread> #include <chrono> #include "base/core_affinity.hpp" #include "core/message.hpp" #include "storage/data_store.hpp" #include "utils/tid_mapper.hpp" class AbstractExpert { public: AbstractExpert(int id, DataStore* data_store, CoreAffinity* core_affinity):id_(id), data_store_(data_store), core_affinity_(core_affinity) {} virtual ~AbstractExpert() {} const int GetExpertId() {return id_;} virtual void process(const vector<Expert_Object> & experts, Message & msg) = 0; protected: // Data Store DataStore* data_store_; // Core affinity CoreAffinity* core_affinity_; private: // Expert ID int id_; }; #endif /* ABSTRACT_EXPERT_HPP_ */
20.627907
145
0.722661
[ "vector" ]
a0d846c96f214f3762cd4472f8eb44520c48b77a
1,349
hpp
C++
include/VROSC/IEnablable.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
include/VROSC/IEnablable.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
include/VROSC/IEnablable.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
1
2022-03-30T21:07:35.000Z
2022-03-30T21:07:35.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/byref.hpp" // Completed includes // Type namespace: VROSC namespace VROSC { // Forward declaring type: IEnablable class IEnablable; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::VROSC::IEnablable); DEFINE_IL2CPP_ARG_TYPE(::VROSC::IEnablable*, "VROSC", "IEnablable"); // Type namespace: VROSC namespace VROSC { // Size: 0x10 #pragma pack(push, 1) // Autogenerated type: VROSC.IEnablable // [TokenAttribute] Offset: FFFFFFFF class IEnablable { public: // public System.Boolean get_Enabled() // Offset: 0xFFFFFFFFFFFFFFFF bool get_Enabled(); }; // VROSC.IEnablable #pragma pack(pop) } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: VROSC::IEnablable::get_Enabled // Il2CppName: get_Enabled template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (VROSC::IEnablable::*)()>(&VROSC::IEnablable::get_Enabled)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(VROSC::IEnablable*), "get_Enabled", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } };
34.589744
147
0.692365
[ "vector" ]
a0d9dc33a824761c962800ba20d5e4b5e0a5c677
2,559
cpp
C++
scripts/training/MGIZA/src/Dictionary.cpp
noisychannel/joshua
cabf0a30b717ade61a3b8e2d2d65b0cb61f7cf36
[ "BSD-2-Clause" ]
null
null
null
scripts/training/MGIZA/src/Dictionary.cpp
noisychannel/joshua
cabf0a30b717ade61a3b8e2d2d65b0cb61f7cf36
[ "BSD-2-Clause" ]
null
null
null
scripts/training/MGIZA/src/Dictionary.cpp
noisychannel/joshua
cabf0a30b717ade61a3b8e2d2d65b0cb61f7cf36
[ "BSD-2-Clause" ]
null
null
null
/* EGYPT Toolkit for Statistical Machine Translation Written by Yaser Al-Onaizan, Jan Curin, Michael Jahr, Kevin Knight, John Lafferty, Dan Melamed, David Purdy, Franz Och, Noah Smith, and David Yarowsky. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* Noah A. Smith Dictionary object for dictionary filter in Model 1 training Dictionary file must be in order (sorted) by Foreign vocab id, but English vocab ids may be in any order. 9 August 1999 */ #include "Dictionary.h" #include <string.h> Dictionary::Dictionary(const char *filename){ if(!strcmp(filename, "")){ dead = true; return; } dead = false; cout << "Reading dictionary from: " << filename << '\n'; ifstream dFile(filename); if(!dFile){ cerr << "ERROR: Can't open dictionary: " << filename << '\n'; exit(1); } currindexmin = 0; currindexmax = 0; currval = 0; int p, q; while((dFile >> p >> q)){ pairs[0].push_back(p); pairs[1].push_back(q); } cout << "Dictionary read; " << pairs[0].size() << " pairs loaded." << '\n'; dFile.close(); } bool Dictionary::indict(int p, int q){ if(dead) return false; if(p == 0 && q == 0) return false; if(currval == p){ for(int i = currindexmin; i <= currindexmax; i++) if(pairs[1][i] == q) return true; return false; } else{ int begin = 0, end = pairs[0].size() - 1, middle = 0; unsigned int t; bool ret = false; while(begin <= end){ middle = begin + ((end - begin) >> 1); if(p < pairs[0][middle]) end = middle - 1; else if(p > pairs[0][middle]) begin = middle + 1; else{ break; } } t = middle; while(pairs[0][t] == p ) if(pairs[1][t--] == q) ret = true; currindexmin = t + 1; t = middle + 1; while(pairs[0][t] == p && t < pairs[0].size()) if(pairs[1][t++] == q) ret = true; currindexmax = t - 1; currval = p; return ret; } }
27.223404
151
0.633451
[ "object", "model" ]
a0dcde9486518adf36d8e8adf3c4a2d96d078b81
2,433
cc
C++
cinn/frontend/decomposer/conv2d_grad.cc
winter-wang/CINN
55cbed5a051bf3d0695de775dbe7492d4926f9be
[ "Apache-2.0" ]
null
null
null
cinn/frontend/decomposer/conv2d_grad.cc
winter-wang/CINN
55cbed5a051bf3d0695de775dbe7492d4926f9be
[ "Apache-2.0" ]
null
null
null
cinn/frontend/decomposer/conv2d_grad.cc
winter-wang/CINN
55cbed5a051bf3d0695de775dbe7492d4926f9be
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2021 CINN Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "cinn/frontend/decomposer_registry.h" namespace cinn { namespace frontend { namespace decomposer { // conv2d backward data/filter void conv2d_grad(const Instruction& instr, const DecomposerContext& context) { auto& dy = instr->inputs[0]; auto& x = instr->inputs[1]; auto& w = instr->inputs[2]; CinnBuilder* builder = context.builder(); // create backward data auto dx = builder->Conv(w, dy, instr.GetAttrs<std::vector<int>>("strides"), instr.GetAttrs<std::vector<int>>("paddings"), instr.GetAttrs<std::vector<int>>("dilations"), instr.GetAttrs<int>("groups"), "backward_data", instr.GetAttrs<std::string>("data_format"), instr.GetAttrs<std::string>("padding_algorithm")); context.MapOutToOrigin(dx, instr->outputs[0]); // create backward filter auto dw = builder->Conv(x, dy, instr.GetAttrs<std::vector<int>>("strides"), instr.GetAttrs<std::vector<int>>("paddings"), instr.GetAttrs<std::vector<int>>("dilations"), instr.GetAttrs<int>("groups"), "backward_filter", instr.GetAttrs<std::string>("data_format"), instr.GetAttrs<std::string>("padding_algorithm"), w->shape); context.MapOutToOrigin(dw, instr->outputs[1]); } } // namespace decomposer } // namespace frontend } // namespace cinn CINN_REGISTER_HELPER(conv2d_grad_decomposer) { CINN_DECOMPOSER_REGISTER(conv2d_grad, cinn::frontend::decomposer::conv2d_grad); return true; }
38.619048
81
0.59926
[ "shape", "vector" ]
a0ed19d2bb4d0fca8536eef22e548037a941cffd
14,424
cc
C++
caffe2/utils/math_test.cc
Hacky-DH/pytorch
80dc4be615854570aa39a7e36495897d8a040ecc
[ "Intel" ]
60,067
2017-01-18T17:21:31.000Z
2022-03-31T21:37:45.000Z
caffe2/utils/math_test.cc
Hacky-DH/pytorch
80dc4be615854570aa39a7e36495897d8a040ecc
[ "Intel" ]
66,955
2017-01-18T17:21:38.000Z
2022-03-31T23:56:11.000Z
caffe2/utils/math_test.cc
Hacky-DH/pytorch
80dc4be615854570aa39a7e36495897d8a040ecc
[ "Intel" ]
19,210
2017-01-18T17:45:04.000Z
2022-03-31T23:51:56.000Z
#include <array> #include <memory> #include <vector> #include <gtest/gtest.h> #include "caffe2/core/blob.h" #include "caffe2/core/context.h" #include "caffe2/core/tensor.h" #include "caffe2/proto/caffe2_pb.h" #include "caffe2/utils/conversions.h" #include "caffe2/utils/math.h" #include <c10/util/irange.h> namespace caffe2 { TEST(MathTest, GemmNoTransNoTrans) { DeviceOption option; CPUContext cpu_context(option); Tensor X(std::vector<int>{5, 10}, CPU); Tensor W(std::vector<int>{10, 6}, CPU); Tensor Y(std::vector<int>{5, 6}, CPU); EXPECT_EQ(X.numel(), 50); EXPECT_EQ(W.numel(), 60); math::Set<float, CPUContext>( X.numel(), 1, X.mutable_data<float>(), &cpu_context); math::Set<float, CPUContext>( W.numel(), 1, W.mutable_data<float>(), &cpu_context); EXPECT_EQ(Y.numel(), 30); for (int i = 0; i < X.numel(); ++i) { CHECK_EQ(X.data<float>()[i], 1); } for (int i = 0; i < W.numel(); ++i) { CHECK_EQ(W.data<float>()[i], 1); } const float kOne = 1.0; const float kPointFive = 0.5; const float kZero = 0.0; math::Gemm<float, CPUContext>( CblasNoTrans, CblasNoTrans, 5, 6, 10, kOne, X.data<float>(), W.data<float>(), kZero, Y.mutable_data<float>(), &cpu_context); EXPECT_EQ(Y.numel(), 30); for (int i = 0; i < Y.numel(); ++i) { CHECK_EQ(Y.data<float>()[i], 10) << i; } // Test Accumulate math::Gemm<float, CPUContext>( CblasNoTrans, CblasNoTrans, 5, 6, 10, kOne, X.data<float>(), W.data<float>(), kPointFive, Y.mutable_data<float>(), &cpu_context); EXPECT_EQ(Y.numel(), 30); for (int i = 0; i < Y.numel(); ++i) { CHECK_EQ(Y.data<float>()[i], 15) << i; } // Test Accumulate math::Gemm<float, CPUContext>( CblasNoTrans, CblasNoTrans, 5, 6, 10, kPointFive, X.data<float>(), W.data<float>(), kOne, Y.mutable_data<float>(), &cpu_context); EXPECT_EQ(Y.numel(), 30); for (int i = 0; i < Y.numel(); ++i) { CHECK_EQ(Y.data<float>()[i], 20) << i; } } TEST(MathTest, GemmNoTransTrans) { DeviceOption option; CPUContext cpu_context(option); Tensor X(std::vector<int>{5, 10}, CPU); Tensor W(std::vector<int>{6, 10}, CPU); Tensor Y(std::vector<int>{5, 6}, CPU); EXPECT_EQ(X.numel(), 50); EXPECT_EQ(W.numel(), 60); math::Set<float, CPUContext>( X.numel(), 1, X.mutable_data<float>(), &cpu_context); math::Set<float, CPUContext>( W.numel(), 1, W.mutable_data<float>(), &cpu_context); EXPECT_EQ(Y.numel(), 30); for (int i = 0; i < X.numel(); ++i) { CHECK_EQ(X.data<float>()[i], 1); } for (int i = 0; i < W.numel(); ++i) { CHECK_EQ(W.data<float>()[i], 1); } const float kOne = 1.0; const float kPointFive = 0.5; const float kZero = 0.0; math::Gemm<float, CPUContext>( CblasNoTrans, CblasTrans, 5, 6, 10, kOne, X.data<float>(), W.data<float>(), kZero, Y.mutable_data<float>(), &cpu_context); EXPECT_EQ(Y.numel(), 30); for (int i = 0; i < Y.numel(); ++i) { CHECK_EQ(Y.data<float>()[i], 10) << i; } // Test Accumulate math::Gemm<float, CPUContext>( CblasNoTrans, CblasTrans, 5, 6, 10, kOne, X.data<float>(), W.data<float>(), kPointFive, Y.mutable_data<float>(), &cpu_context); EXPECT_EQ(Y.numel(), 30); for (int i = 0; i < Y.numel(); ++i) { CHECK_EQ(Y.data<float>()[i], 15) << i; } math::Gemm<float, CPUContext>( CblasNoTrans, CblasTrans, 5, 6, 10, kPointFive, X.data<float>(), W.data<float>(), kOne, Y.mutable_data<float>(), &cpu_context); EXPECT_EQ(Y.numel(), 30); for (int i = 0; i < Y.numel(); ++i) { CHECK_EQ(Y.data<float>()[i], 20) << i; } } namespace { constexpr float kEps = 1e-5; // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) class GemmBatchedTest : public testing::TestWithParam<testing::tuple<bool, bool>> { protected: void SetUp() override { cpu_context_ = make_unique<CPUContext>(option_); ReinitializeTensor( &X_, std::vector<int64_t>{3, 5, 10}, at::dtype<float>().device(CPU)); ReinitializeTensor( &W_, std::vector<int64_t>{3, 6, 10}, at::dtype<float>().device(CPU)); ReinitializeTensor( &Y_, std::vector<int64_t>{3, 5, 6}, at::dtype<float>().device(CPU)); math::Set<float, CPUContext>( X_.numel(), 1, X_.mutable_data<float>(), cpu_context_.get()); math::Set<float, CPUContext>( W_.numel(), 1, W_.mutable_data<float>(), cpu_context_.get()); trans_X_ = std::get<0>(GetParam()); trans_W_ = std::get<1>(GetParam()); } void RunGemmBatched(const float alpha, const float beta) { const float* X_data = X_.template data<float>(); const float* W_data = W_.template data<float>(); float* Y_data = Y_.template mutable_data<float>(); const int X_stride = 5 * 10; const int W_stride = 6 * 10; const int Y_stride = 5 * 6; std::array<const float*, 3> X_array = { X_data, X_data + X_stride, X_data + 2 * X_stride}; std::array<const float*, 3> W_array = { W_data, W_data + W_stride, W_data + 2 * W_stride}; std::array<float*, 3> Y_array = { Y_data, Y_data + Y_stride, Y_data + 2 * Y_stride}; math::GemmBatched( trans_X_ ? CblasTrans : CblasNoTrans, trans_W_ ? CblasTrans : CblasNoTrans, 3, 5, 6, 10, alpha, X_array.data(), W_array.data(), beta, Y_array.data(), cpu_context_.get()); } void RunGemmStridedBatched(const float alpha, const float beta) { const float* X_data = X_.template data<float>(); const float* W_data = W_.template data<float>(); float* Y_data = Y_.template mutable_data<float>(); const int X_stride = 5 * 10; const int W_stride = 6 * 10; const int Y_stride = 5 * 6; math::GemmStridedBatched<float, CPUContext>( trans_X_ ? CblasTrans : CblasNoTrans, trans_W_ ? CblasTrans : CblasNoTrans, 3, 5, 6, 10, alpha, X_data, X_stride, W_data, W_stride, beta, Y_data, Y_stride, cpu_context_.get()); } void VerifyOutput(const float value) const { for (int i = 0; i < Y_.numel(); ++i) { EXPECT_FLOAT_EQ(value, Y_.template data<float>()[i]); } } // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) DeviceOption option_; // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) std::unique_ptr<CPUContext> cpu_context_; // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) Tensor X_; // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) Tensor W_; // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) Tensor Y_; // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) bool trans_X_; // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) bool trans_W_; }; TEST_P(GemmBatchedTest, GemmBatchedFloatTest) { RunGemmBatched(1.0f, 0.0f); VerifyOutput(10.0f); RunGemmBatched(1.0f, 0.5f); VerifyOutput(15.0f); RunGemmBatched(0.5f, 1.0f); VerifyOutput(20.0f); } TEST_P(GemmBatchedTest, GemmStridedBatchedFloatTest) { RunGemmStridedBatched(1.0f, 0.0f); VerifyOutput(10.0f); RunGemmStridedBatched(1.0f, 0.5f); VerifyOutput(15.0f); RunGemmStridedBatched(0.5f, 1.0f); VerifyOutput(20.0f); } INSTANTIATE_TEST_CASE_P( GemmBatchedTrans, GemmBatchedTest, testing::Combine(testing::Bool(), testing::Bool())); } // namespace TEST(MathTest, GemvNoTrans) { DeviceOption option; CPUContext cpu_context(option); Tensor A(std::vector<int>{5, 10}, CPU); Tensor X(std::vector<int>{10}, CPU); Tensor Y(std::vector<int>{5}, CPU); EXPECT_EQ(A.numel(), 50); EXPECT_EQ(X.numel(), 10); math::Set<float, CPUContext>( A.numel(), 1, A.mutable_data<float>(), &cpu_context); math::Set<float, CPUContext>( X.numel(), 1, X.mutable_data<float>(), &cpu_context); EXPECT_EQ(Y.numel(), 5); for (int i = 0; i < A.numel(); ++i) { CHECK_EQ(A.data<float>()[i], 1); } for (int i = 0; i < X.numel(); ++i) { CHECK_EQ(X.data<float>()[i], 1); } const float kOne = 1.0; const float kPointFive = 0.5; const float kZero = 0.0; math::Gemv<float, CPUContext>( CblasNoTrans, 5, 10, kOne, A.data<float>(), X.data<float>(), kZero, Y.mutable_data<float>(), &cpu_context); for (int i = 0; i < Y.numel(); ++i) { CHECK_EQ(Y.data<float>()[i], 10) << i; } // Test Accumulate math::Gemv<float, CPUContext>( CblasNoTrans, 5, 10, kOne, A.data<float>(), X.data<float>(), kPointFive, Y.mutable_data<float>(), &cpu_context); for (int i = 0; i < Y.numel(); ++i) { CHECK_EQ(Y.data<float>()[i], 15) << i; } // Test Accumulate math::Gemv<float, CPUContext>( CblasNoTrans, 5, 10, kPointFive, A.data<float>(), X.data<float>(), kOne, Y.mutable_data<float>(), &cpu_context); for (int i = 0; i < Y.numel(); ++i) { CHECK_EQ(Y.data<float>()[i], 20) << i; } } TEST(MathTest, GemvTrans) { DeviceOption option; CPUContext cpu_context(option); Tensor A(std::vector<int>{6, 10}, CPU); Tensor X(std::vector<int>{6}, CPU); Tensor Y(std::vector<int>{10}, CPU); EXPECT_EQ(A.numel(), 60); EXPECT_EQ(X.numel(), 6); math::Set<float, CPUContext>( A.numel(), 1, A.mutable_data<float>(), &cpu_context); math::Set<float, CPUContext>( X.numel(), 1, X.mutable_data<float>(), &cpu_context); EXPECT_EQ(Y.numel(), 10); for (int i = 0; i < A.numel(); ++i) { CHECK_EQ(A.data<float>()[i], 1); } for (int i = 0; i < X.numel(); ++i) { CHECK_EQ(X.data<float>()[i], 1); } const float kOne = 1.0; const float kPointFive = 0.5; const float kZero = 0.0; math::Gemv<float, CPUContext>( CblasTrans, 6, 10, kOne, A.data<float>(), X.data<float>(), kZero, Y.mutable_data<float>(), &cpu_context); for (int i = 0; i < Y.numel(); ++i) { CHECK_EQ(Y.data<float>()[i], 6) << i; } // Test Accumulate math::Gemv<float, CPUContext>( CblasTrans, 6, 10, kOne, A.data<float>(), X.data<float>(), kPointFive, Y.mutable_data<float>(), &cpu_context); for (int i = 0; i < Y.numel(); ++i) { CHECK_EQ(Y.data<float>()[i], 9) << i; } // Test Accumulate math::Gemv<float, CPUContext>( CblasTrans, 6, 10, kPointFive, A.data<float>(), X.data<float>(), kOne, Y.mutable_data<float>(), &cpu_context); for (int i = 0; i < Y.numel(); ++i) { CHECK_EQ(Y.data<float>()[i], 12) << i; } } TEST(MathTest, FloatToHalfConversion) { float a = 1.0f; float b = 1.75f; float c = 128.125f; float converted_a = static_cast<float>(at::Half(a)); float converted_b = static_cast<float>(at::Half(b)); float converted_c = static_cast<float>(at::Half(c)); CHECK_EQ(a, converted_a); CHECK_EQ(b, converted_b); CHECK_EQ(c, converted_c); } namespace { class BroadcastTest : public testing::Test { protected: void SetUp() override { cpu_context_ = make_unique<CPUContext>(option_); } void RunBroadcastTest( const std::vector<int>& X_dims, const std::vector<int>& Y_dims, const std::vector<float>& X_data, const std::vector<float>& Y_data) { std::vector<int64_t> X_dims_64; std::vector<int64_t> Y_dims_64; std::copy(X_dims.cbegin(), X_dims.cend(), std::back_inserter(X_dims_64)); std::copy(Y_dims.cbegin(), Y_dims.cend(), std::back_inserter(Y_dims_64)); ReinitializeTensor(&X_, X_dims_64, at::dtype<float>().device(CPU)); ReinitializeTensor(&Y_, Y_dims_64, at::dtype<float>().device(CPU)); ASSERT_EQ(X_data.size(), X_.numel()); cpu_context_->CopyFromCPU<float>( X_data.size(), X_data.data(), X_.mutable_data<float>()); for (bool allow_broadcast_fastpath : {false, true}) { math::Broadcast<float, CPUContext>( X_dims.size(), X_dims.data(), Y_dims.size(), Y_dims.data(), 1.0f, X_.data<float>(), Y_.mutable_data<float>(), cpu_context_.get(), allow_broadcast_fastpath); ASSERT_EQ(Y_data.size(), Y_.numel()); for (const auto i : c10::irange(Y_data.size())) { EXPECT_FLOAT_EQ(Y_data[i], Y_.data<float>()[i]); } } } // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) DeviceOption option_; // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) std::unique_ptr<CPUContext> cpu_context_; // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) Tensor X_; // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) Tensor Y_; }; TEST_F(BroadcastTest, BroadcastFloatTest) { RunBroadcastTest({2}, {2}, {1.0f, 2.0f}, {1.0f, 2.0f}); RunBroadcastTest({1}, {2}, {1.0f}, {1.0f, 1.0f}); RunBroadcastTest({1}, {2, 2}, {1.0f}, {1.0f, 1.0f, 1.0f, 1.0f}); RunBroadcastTest({2, 1}, {2, 2}, {1.0f, 2.0f}, {1.0f, 1.0f, 2.0f, 2.0f}); RunBroadcastTest({1, 2}, {2, 2}, {1.0f, 2.0f}, {1.0f, 2.0f, 1.0f, 2.0f}); RunBroadcastTest( {2, 1}, {2, 2, 2}, {1.0f, 2.0f}, {1.0f, 1.0f, 2.0f, 2.0f, 1.0f, 1.0f, 2.0f, 2.0f}); RunBroadcastTest( {1, 2}, {2, 2, 2}, {1.0f, 2.0f}, {1.0f, 2.0f, 1.0f, 2.0f, 1.0f, 2.0f, 1.0f, 2.0f}); } class RandFixedSumTest : public testing::Test { protected: void SetUp() override { cpu_context_ = make_unique<CPUContext>(option_); } // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) DeviceOption option_; // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) std::unique_ptr<CPUContext> cpu_context_; }; TEST_F(RandFixedSumTest, UpperBound) { std::vector<int> l(20); math::RandFixedSum<int, CPUContext>( 20, 1, 1000, 1000, l.data(), cpu_context_.get()); } } // namespace } // namespace caffe2
27.422053
78
0.596436
[ "vector" ]
a0f0e2aa688301020e58f201550fe765bd80cff5
8,118
cpp
C++
tools/intel_multisample.cpp
AIS-Bonn/stillleben
f3673d1ef48c50debe52cf9c634ae000556259c8
[ "MIT" ]
46
2020-05-16T08:21:05.000Z
2022-02-14T03:02:42.000Z
tools/intel_multisample.cpp
AIS-Bonn/stillleben
f3673d1ef48c50debe52cf9c634ae000556259c8
[ "MIT" ]
4
2020-06-26T07:40:30.000Z
2020-10-23T08:43:13.000Z
tools/intel_multisample.cpp
AIS-Bonn/stillleben
f3673d1ef48c50debe52cf9c634ae000556259c8
[ "MIT" ]
2
2021-02-19T03:10:34.000Z
2022-02-17T10:42:53.000Z
// This is a two-stage test: First, we render to a multisample texture // of the specified format. The contents are then read in a second shader run // using texelFetch() and written into an GL_R8UI texture. // Compilation: // g++ -std=c++11 -o intel_multisample intel_multisample.cpp -lglfw -lGL -lGLEW #include <GL/glew.h> #define GLEW_STATIC #include <GLFW/glfw3.h> #include <cstdio> #include <vector> #include <string> #include <map> const char* VERTEX_SHADER = R"EOS( #version 330 layout (location = 0) in vec2 position; void main() { gl_Position.xywz = vec4(position, 1.0, 0.0); } )EOS"; const char* FRAGMENT_SHADER_1 = R"EOS( #version 330 layout (location = 0) out uint my_output; void main() { my_output = 5u; } )EOS"; const char* FRAGMENT_SHADER_2 = R"EOS( #version 330 uniform usampler2DMS sampler; out uint my_output; void main() { my_output = texelFetch(sampler, ivec2(0,0), 0).r; } )EOS"; GLuint compileShader(const std::string& shader, GLenum type, const char* source) { GLuint shader_obj = glCreateShader(type); glShaderSource(shader_obj, 1, &source, NULL); glCompileShader(shader_obj); GLint success = 0; glGetShaderiv(shader_obj, GL_COMPILE_STATUS, &success); if(success == GL_FALSE) { fprintf(stderr, "Could not compile %s\n", shader.c_str()); GLint maxLength = 0; glGetShaderiv(shader_obj, GL_INFO_LOG_LENGTH, &maxLength); // The maxLength includes the NULL character std::vector<GLchar> infoLog(maxLength); glGetShaderInfoLog(shader_obj, maxLength, &maxLength, &infoLog[0]); fprintf(stderr, "Output:\n%s\n", infoLog.data()); std::abort(); } return shader_obj; } void errorCallback( GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam) { fprintf( stderr, "GL DEBUG message: %s type = 0x%x, severity = 0x%x, message = %s\n", ( type == GL_DEBUG_TYPE_ERROR ? "** GL ERROR **" : "" ), type, severity, message ); } const std::map<std::string, GLenum> KNOWN_FORMATS{ {"GL_R32F", GL_R32F}, {"GL_R32UI", GL_R32UI}, {"GL_R16UI", GL_R16UI}, {"GL_R8UI", GL_R8UI} }; int main(int argc, char** argv) { if(argc < 2 || std::string(argv[1]) == "--help") { fprintf(stderr, "Usage: %s <format>\n", argv[0]); fprintf(stderr, "Where format is one of:"); for(auto& fmt : KNOWN_FORMATS) fprintf(stderr, " %s", fmt.first.c_str()); fprintf(stderr, "\n"); return 1; } auto it = KNOWN_FORMATS.find(argv[1]); if(it == KNOWN_FORMATS.end()) { fprintf(stderr, "Unknown format '%s'\n", argv[1]); return 1; } printf("Testing format %s\n", argv[1]); GLenum format = it->second; if(!glfwInit()) { fprintf(stderr, "glfwInit failed\n"); return 1; } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); GLFWwindow* window = glfwCreateWindow(640, 480, "My Title", NULL, NULL); if(!window) { fprintf(stderr, "Could not create GLFW window\n"); return 1; } glfwMakeContextCurrent(window); glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { printf("Failed to initialize GLEW.\n"); glfwTerminate(); return 1; } int width, height; glfwGetFramebufferSize(window, &width, &height); glViewport(0, 0, width, height); glEnable(GL_DEBUG_OUTPUT); glDebugMessageCallback(errorCallback, 0); { GLint samples; glGetIntegerv(GL_MAX_INTEGER_SAMPLES, &samples); printf("GL_MAX_INTEGER_SAMPLES: %d\n", samples); glGetIntegerv(GL_MAX_SAMPLES, &samples); printf("GL_MAX_SAMPLES: %d\n", samples); printf("Supported sample counts per internal format:\n"); for(const auto& fmt : KNOWN_FORMATS) { GLint length = 0; glGetInternalformativ(GL_TEXTURE_2D_MULTISAMPLE, fmt.second, GL_NUM_SAMPLE_COUNTS, 1, &length); std::vector<GLint> buf(length); glGetInternalformativ(GL_TEXTURE_2D_MULTISAMPLE, fmt.second, GL_SAMPLES, buf.size(), buf.data()); printf(" - %10s:", fmt.first.c_str()); for(auto& v : buf) printf(" %d", v); printf("\n"); } } // Compile shaders GLuint vertex_shader_1; GLuint vertex_shader_2; GLuint fragment_shader_1; GLuint fragment_shader_2; GLuint program1; GLuint program2; { vertex_shader_1 = compileShader("vertex shader", GL_VERTEX_SHADER, VERTEX_SHADER); vertex_shader_2 = compileShader("vertex shader", GL_VERTEX_SHADER, VERTEX_SHADER); fragment_shader_1 = compileShader("fragment shader 1", GL_FRAGMENT_SHADER, FRAGMENT_SHADER_1); fragment_shader_2 = compileShader("fragment shader 2", GL_FRAGMENT_SHADER, FRAGMENT_SHADER_2); program1 = glCreateProgram(); glAttachShader(program1, vertex_shader_1); glAttachShader(program1, fragment_shader_1); glLinkProgram(program1); program2 = glCreateProgram(); glAttachShader(program2, vertex_shader_2); glAttachShader(program2, fragment_shader_2); glLinkProgram(program2); } const float quadPoints[]{ 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, -1.0f, 1.0f }; GLuint vao; glGenVertexArrays(1, &vao); glBindVertexArray(vao); GLuint vbo; glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, 8*sizeof(float), quadPoints, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0); // First render: fill multisample texture with value "5" GLuint texture; { GLuint fbo; glCreateFramebuffers(1, &fbo); glBindFramebuffer(GL_FRAMEBUFFER, fbo); // Create multisample texture glCreateTextures(GL_TEXTURE_2D_MULTISAMPLE, 1, &texture); glTextureStorage2DMultisample(texture, 4, format, 640, 480, GL_FALSE); glNamedFramebufferTexture(fbo, GL_COLOR_ATTACHMENT0, texture, 0); const GLenum buffers[]{GL_COLOR_ATTACHMENT0}; glNamedFramebufferDrawBuffers(fbo, 1, buffers); GLenum status = glCheckNamedFramebufferStatus(fbo, GL_DRAW_FRAMEBUFFER); if(status != GL_FRAMEBUFFER_COMPLETE) { fprintf(stderr, "Invalid framebuffer status\n"); return 1; } glUseProgram(program1); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); } // Second render: read texel from multisample texture GLuint outputTexture; { GLuint fbo; glCreateFramebuffers(1, &fbo); glBindFramebuffer(GL_FRAMEBUFFER, fbo); // Create output texture glCreateTextures(GL_TEXTURE_RECTANGLE, 1, &outputTexture); glTextureStorage2D(outputTexture, 1, GL_R8UI, 640, 480); glNamedFramebufferTexture(fbo, GL_COLOR_ATTACHMENT0, outputTexture, 0); const GLenum buffers[]{GL_COLOR_ATTACHMENT0}; glNamedFramebufferDrawBuffers(fbo, 1, buffers); // bind input texture glBindTextureUnit(0, texture); glUseProgram(program2); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); } // Read out outputTexture { std::vector<uint8_t> data(640*480); glGetTextureImage(outputTexture, 0, GL_RED_INTEGER, GL_UNSIGNED_BYTE, data.size(), data.data()); printf("First pixels (these should have value 5):\n"); for(std::size_t i = 0; i < 100; ++i) { printf("%02X ", data[i]); } printf("\n"); bool correct = true; for(auto val : data) { if(val != 5) { correct = false; break; } } if(correct) printf("PASS\n"); else printf("FAIL\n"); } glfwTerminate(); return 0; }
27.333333
109
0.623553
[ "render", "vector" ]
a0f110b24ebcf99b5d8272ff31f1658710de75b8
2,483
cxx
C++
Filters/ParallelFlowPaths/vtkPStreaklineFilter.cxx
forestGzh/VTK
bc98327275bd5cfa95c5825f80a2755a458b6da8
[ "BSD-3-Clause" ]
3
2015-07-28T18:07:50.000Z
2018-02-28T20:59:58.000Z
Filters/ParallelFlowPaths/vtkPStreaklineFilter.cxx
forestGzh/VTK
bc98327275bd5cfa95c5825f80a2755a458b6da8
[ "BSD-3-Clause" ]
14
2015-04-25T17:54:13.000Z
2017-01-13T15:30:39.000Z
Filters/ParallelFlowPaths/vtkPStreaklineFilter.cxx
forestGzh/VTK
bc98327275bd5cfa95c5825f80a2755a458b6da8
[ "BSD-3-Clause" ]
4
2016-09-08T02:11:00.000Z
2019-08-15T02:38:39.000Z
/*========================================================================= Program: Visualization Toolkit Module: vtkPStreaklineFilter.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkPStreaklineFilter.h" #include "vtkObjectFactory.h" #include "vtkSetGet.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkCell.h" #include "vtkCellArray.h" #include "vtkCellData.h" #include "vtkPointData.h" #include "vtkIntArray.h" #include "vtkSmartPointer.h" #include "vtkFloatArray.h" #include "vtkMultiProcessController.h" #include "vtkAppendPolyData.h" #include "vtkNew.h" #include <vector> #include <cassert> vtkStandardNewMacro(vtkPStreaklineFilter) vtkPStreaklineFilter::vtkPStreaklineFilter() { this->It.Initialize(this); } int vtkPStreaklineFilter::OutputParticles(vtkPolyData* particles) { return this->It.OutputParticles(particles); } void vtkPStreaklineFilter::Finalize() { int leader = 0; int tag = 129; if(this->Controller->GetLocalProcessId()==leader) //process 0 do the actual work { vtkNew<vtkAppendPolyData> append; int totalNumPts(0); for(int i=0; i<this->Controller->GetNumberOfProcesses(); i++) { if(i!=this->Controller->GetLocalProcessId()) { vtkSmartPointer<vtkPolyData> output_i = vtkSmartPointer<vtkPolyData>::New(); this->Controller->Receive(output_i, i, tag); append->AddInputData(output_i); totalNumPts+= output_i->GetNumberOfPoints(); } else { append->AddInputData(this->Output); totalNumPts+= this->Output->GetNumberOfPoints(); } } append->Update(); vtkPolyData* appoutput = append->GetOutput(); this->Output->Initialize(); this->Output->ShallowCopy(appoutput); assert(this->Output->GetNumberOfPoints()==totalNumPts); this->It.Finalize(); } else { //send everything to rank 0 this->Controller->Send(this->Output,leader, tag); this->Output->Initialize(); } return; } void vtkPStreaklineFilter::PrintSelf(ostream& os, vtkIndent indent) { Superclass::PrintSelf(os,indent); }
27.285714
84
0.674184
[ "vector" ]
9d0ba690198ba84e2be351f9a7db142a29ee4185
1,071
cpp
C++
src/main/algorithms/cpp/array/find_the_duplicate_number_287/solution.cpp
algorithmlover2016/leet_code
2eecc7971194c8a755e67719d8f66c636694e7e9
[ "Apache-2.0" ]
null
null
null
src/main/algorithms/cpp/array/find_the_duplicate_number_287/solution.cpp
algorithmlover2016/leet_code
2eecc7971194c8a755e67719d8f66c636694e7e9
[ "Apache-2.0" ]
null
null
null
src/main/algorithms/cpp/array/find_the_duplicate_number_287/solution.cpp
algorithmlover2016/leet_code
2eecc7971194c8a755e67719d8f66c636694e7e9
[ "Apache-2.0" ]
null
null
null
#include "../../head.h" // the solution, n + 1 elements, and except the duplicate one, the other(1-n) must exist class Solution { public: int findDuplicate(std::vector<int> const & nums) { if (nums.empty()) { return -1; } int res = 0; for (int index = 1; index < nums.size(); index++) { res ^= index ^ nums[index]; } return res ^ nums[0]; } }; class Solution { public: int findDuplicate(std::vector<int> const & nums) { if (nums.empty()) { return -1; } // already go forward one step int slow = nums[0], fast = nums[slow]; while (slow != fast) { // std::cout << "\nfast, slow: " << fast << "\t" << slow << "\t"; fast = nums[nums[fast]]; slow = nums[slow]; } fast = 0; while (fast != slow) { // std::cout << "\nfast, slow: " << fast << "\t" << slow << "\t"; fast = nums[fast]; slow = nums[slow]; } return fast; } };
25.5
88
0.451914
[ "vector" ]
9d0e312254d5c00939154826b5265d1ad0574780
1,193
cpp
C++
rules/constrictor_ruleset.cpp
TheApX/battlesnake-engine-cpp
05053f06ecc631f037417bd0d897b28f48dfe07d
[ "MIT" ]
3
2021-07-05T22:42:26.000Z
2021-07-29T12:14:43.000Z
rules/constrictor_ruleset.cpp
TheApX/battlesnake-engine-cpp
05053f06ecc631f037417bd0d897b28f48dfe07d
[ "MIT" ]
2
2021-07-12T00:11:57.000Z
2021-09-04T19:11:38.000Z
rules/constrictor_ruleset.cpp
TheApX/battlesnake-engine-cpp
05053f06ecc631f037417bd0d897b28f48dfe07d
[ "MIT" ]
null
null
null
#include "battlesnake/rules/constrictor_ruleset.h" namespace battlesnake { namespace rules { BoardState ConstrictorRuleset::CreateInitialBoardState( Coordinate width, Coordinate height, std::vector<SnakeId> snake_ids) { BoardState next_state = StandardRuleset::CreateInitialBoardState(width, height, snake_ids); applyConstrictorRules(next_state); return next_state; } void ConstrictorRuleset::CreateNextBoardState(const BoardState& prev_state, const SnakeMovesVector& moves, int turn, BoardState& next_state) { StandardRuleset::CreateNextBoardState(prev_state, moves, turn, next_state); applyConstrictorRules(next_state); } void ConstrictorRuleset::applyConstrictorRules(BoardState& state) const { state.food.clear(); for (Snake& snake : state.snakes) { snake.health = snake_max_health_; if (snake.Length() < 2) { growSnake(snake); continue; } if (snake.body.moves_length == snake.body.total_length - 1) { growSnake(snake); } } } } // namespace rules } // namespace battlesnake
27.113636
77
0.65549
[ "vector" ]
9d0e3a3494e87f0f6f2554c7c160cfe91f159a27
2,996
hpp
C++
wbc/ahl_robot_controller/include/ahl_robot_controller/robot_controller.hpp
daichi-yoshikawa/ahl_wbc
ea241562e521c7509d3b0405393996998f7cdc6e
[ "BSD-3-Clause" ]
33
2015-12-16T15:32:22.000Z
2022-03-21T05:09:40.000Z
wbc/ahl_robot_controller/include/ahl_robot_controller/robot_controller.hpp
daichi-yoshikawa/ahl_wbc
ea241562e521c7509d3b0405393996998f7cdc6e
[ "BSD-3-Clause" ]
3
2016-06-08T09:53:44.000Z
2020-10-26T11:27:23.000Z
wbc/ahl_robot_controller/include/ahl_robot_controller/robot_controller.hpp
daichi-yoshikawa/ahl_wbc
ea241562e521c7509d3b0405393996998f7cdc6e
[ "BSD-3-Clause" ]
10
2016-01-27T10:30:01.000Z
2022-03-21T05:08:27.000Z
/********************************************************************* * * Software License Agreement (BSD License) * * Copyright (c) 2015, Daichi Yoshikawa * 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 Daichi Yoshikawa 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. * * Author: Daichi Yoshikawa * *********************************************************************/ #ifndef __AHL_ROBOT_CONTROLLER_ROBOT_CONTROLLER_HPP #define __AHL_ROBOT_CONTROLLER_ROBOT_CONTROLLER_HPP #include <map> #include <list> #include <memory> #include <ahl_robot/ahl_robot.hpp> #include "ahl_robot_controller/param_base.hpp" #include "ahl_robot_controller/task/task.hpp" #include "ahl_robot_controller/task/multi_task.hpp" namespace ahl_ctrl { class RobotController { public: explicit RobotController(); void init(const ahl_robot::RobotPtr& robot); void init(const ahl_robot::RobotPtr& robot, const ParamBasePtr& param); void addTask(const TaskPtr& task, int32_t priority); void clearTask(); void updateModel(); void simulate(double period, const Eigen::VectorXd& tau, Eigen::VectorXd& qd, Eigen::VectorXd& dqd, Eigen::VectorXd& ddqd); void computeGeneralizedForce(Eigen::VectorXd& tau); private: ParamBasePtr param_; MultiTaskPtr multi_task_; ahl_robot::RobotPtr robot_; std::vector<ahl_robot::ManipulatorPtr> mnp_; uint32_t dof_; }; using RobotControllerPtr = std::shared_ptr<RobotController>; } // namespace ahl_ctrl #endif // __AHL_ROBOT_CONTROLLER_ROBOT_CONTROLLER_HPP
37.924051
127
0.716956
[ "vector" ]
9d116425c9fa1cdff1dbf265396827c0f918c5d4
4,362
cpp
C++
Scheduler.cpp
FlySkyPie/arduino-software-pwm
1822a1b01c4edaf45a3ddbe96b4e53c2e2f6fbc3
[ "MIT" ]
null
null
null
Scheduler.cpp
FlySkyPie/arduino-software-pwm
1822a1b01c4edaf45a3ddbe96b4e53c2e2f6fbc3
[ "MIT" ]
null
null
null
Scheduler.cpp
FlySkyPie/arduino-software-pwm
1822a1b01c4edaf45a3ddbe96b4e53c2e2f6fbc3
[ "MIT" ]
null
null
null
/* * This class is used for software PWM. */ #include "Scheduler.h" Scheduler::Scheduler(uint8_t size) { this->initialize(size); } Scheduler::~Scheduler() { delete [] this->exception; delete [] this->power; delete [] this->pinSchedule; delete [] this->powerSchedule; } /* * Set new mission. */ void Scheduler::setMission(uint8_t id, uint8_t power) { if (id>this->size) { return; } if (power == 0 || power == 0xff) { this->exception[id] = true; } else { this->exception[id] = false; } this->power[id] = power; this->changed = true; } void Scheduler::updateSchedule() { if (!this->changed) { return; } this->createSchedule(); this->loadSchedule(); this->sortSchedule(); this->reloadFullPins(); this->reloadOffPins(); this->changed = false; } /* * Get schedule table. */ void Scheduler::getSchedule(uint8_t **pins, uint8_t **powers, uint8_t &size) { *pins = this->pinSchedule; *powers = this->powerSchedule; size = this->scheduledCount; } /* * Get tablle of pins which turn full on. */ void Scheduler::getFullPins(uint8_t **pins, uint8_t &size) { *pins = this->fullPins; size = this->fullPinsCount; } /* * Get tablle of pins which turn full off. */ void Scheduler::getOffPins(uint8_t **pins, uint8_t &size) { *pins = this->offPins; size = this->offPinsCount; } /* * reload pins which turn full on. */ void Scheduler::reloadFullPins() { delete [] this->fullPins; this->fullPins = new uint8_t[this->getFullPinsCount()]; uint8_t i = 0, j = 0; while (i < this->size) { if (this->power[i] == 255) { this->fullPins[j] = i; j++; } i++; } } /* * reload pins which turn off. */ void Scheduler::reloadOffPins() { delete [] this->offPins; this->offPins = new uint8_t[this->getOffPinsCount()]; uint8_t i = 0, j = 0; while (i < this->size) { if (this->power[i] == 0) { this->offPins[j] = i; j++; } i++; } } /* * Recount number of full pins and return it. */ uint8_t Scheduler::getFullPinsCount() { this->fullPinsCount = 0; for (uint8_t i = 0; i<this->size; i++) { if (this->power[i] == 255) { this->fullPinsCount += 1; } } return this->fullPinsCount; } /* * Recount number of off pins and return it. */ uint8_t Scheduler::getOffPinsCount() { this->offPinsCount = 0; for (uint8_t i = 0; i<this->size; i++) { if (this->power[i] == 0) { this->offPinsCount += 1; } } return this->offPinsCount; } /* * Initialize object, create dynamic array, * fill the status array. */ void Scheduler::initialize(uint8_t size) { this->changed = true; this->size = size; this->exception = new bool[size]; this->power = new uint8_t[size]; //fill array for (uint8_t i = 0; i<this->size; i++) { this->exception[i] = true; this->power[i] = 0; } this->pinSchedule = new uint8_t[0]; this->powerSchedule = new uint8_t[0]; this->offPins = new uint8_t[0]; this->fullPins = new uint8_t[0]; } /* * Release old schedule table, and create new dynamic array as schedule table. */ void Scheduler::createSchedule() { delete [] this->pinSchedule; delete [] this->powerSchedule; this->scheduledCount = 0; for (uint8_t i = 0; i<this->size; i++) { if (!this->exception[i]) { this->scheduledCount += 1; } } this->pinSchedule = new uint8_t[this->scheduledCount]; this->powerSchedule = new uint8_t[this->scheduledCount ]; } /* * Load pin id and power to schedule table from status table. * Ignore exception pin. */ void Scheduler::loadSchedule() { uint8_t i = 0, j = 0; while (i < this->size) { if (!this->exception[i]) { this->pinSchedule[j] = i; this->powerSchedule[j] = this->power[i]; j++; } i++; } } /* * Sort schedule by power value. */ void Scheduler::sortSchedule() { for (uint8_t i = 0; i < this->scheduledCount - 1; i++) { for (uint8_t j = 0; j < this->scheduledCount - i - 1; j++) { if (this->powerSchedule[j] <= this->powerSchedule[j + 1]) { continue; } uint8_t tempId = pinSchedule[j + 1]; uint8_t tempPower = powerSchedule[j + 1]; this->pinSchedule[j + 1] = this->pinSchedule[j]; this->powerSchedule[j + 1] = this->powerSchedule[j]; this->pinSchedule[j] = tempId; this->powerSchedule[j] = tempPower; } } }
20.478873
78
0.605456
[ "object" ]
1dd92f13669ae86a959cb2694a65828f41e2d8eb
7,310
cpp
C++
src/GafferSceneUI/CameraVisualiser.cpp
danieldresser-ie/gaffer
78c22487156a5800fcca49a24f52451a8ac0c559
[ "BSD-3-Clause" ]
1
2016-07-31T09:55:09.000Z
2016-07-31T09:55:09.000Z
src/GafferSceneUI/CameraVisualiser.cpp
Kthulhu/gaffer
8995d579d07231988abc92c3ac2788c15c8bc75c
[ "BSD-3-Clause" ]
null
null
null
src/GafferSceneUI/CameraVisualiser.cpp
Kthulhu/gaffer
8995d579d07231988abc92c3ac2788c15c8bc75c
[ "BSD-3-Clause" ]
1
2020-02-15T16:15:54.000Z
2020-02-15T16:15:54.000Z
////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015, John Haddon. 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 John Haddon nor the names of // any other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "IECore/Camera.h" #include "IECore/SimpleTypedData.h" #include "IECore/AngleConversion.h" #include "IECoreGL/CurvesPrimitive.h" #include "IECoreGL/Group.h" #include "GafferSceneUI/ObjectVisualiser.h" using namespace std; using namespace Imath; using namespace GafferSceneUI; namespace { class CameraVisualiser : public ObjectVisualiser { public : typedef IECore::Camera ObjectType; CameraVisualiser() { } virtual ~CameraVisualiser() { } virtual IECoreGL::ConstRenderablePtr visualise( const IECore::Object *object ) const { const IECore::Camera *camera = IECore::runTimeCast<const IECore::Camera>( object ); if( !camera ) { return NULL; } IECore::CameraPtr fullCamera = camera->copy(); fullCamera->addStandardParameters(); IECoreGL::GroupPtr group = new IECoreGL::Group(); group->getState()->add( new IECoreGL::Primitive::DrawWireframe( true ) ); group->getState()->add( new IECoreGL::Primitive::DrawSolid( false ) ); group->getState()->add( new IECoreGL::CurvesPrimitive::UseGLLines( true ) ); group->getState()->add( new IECoreGL::WireframeColorStateComponent( Color4f( 0, 0.25, 0, 1 ) ) ); IECore::V3fVectorDataPtr pData = new IECore::V3fVectorData; IECore::IntVectorDataPtr vertsPerCurveData = new IECore::IntVectorData; vector<V3f> &p = pData->writable(); vector<int> &vertsPerCurve = vertsPerCurveData->writable(); // box for the camera body const Box3f b( V3f( -0.5, -0.5, 0 ), V3f( 0.5, 0.5, 2.0 ) ); vertsPerCurve.push_back( 5 ); p.push_back( b.min ); p.push_back( V3f( b.max.x, b.min.y, b.min.z ) ); p.push_back( V3f( b.max.x, b.min.y, b.max.z ) ); p.push_back( V3f( b.min.x, b.min.y, b.max.z ) ); p.push_back( b.min ); vertsPerCurve.push_back( 5 ); p.push_back( V3f( b.min.x, b.max.y, b.min.z ) ); p.push_back( V3f( b.max.x, b.max.y, b.min.z ) ); p.push_back( V3f( b.max.x, b.max.y, b.max.z ) ); p.push_back( V3f( b.min.x, b.max.y, b.max.z ) ); p.push_back( V3f( b.min.x, b.max.y, b.min.z ) ); vertsPerCurve.push_back( 2 ); p.push_back( b.min ); p.push_back( V3f( b.min.x, b.max.y, b.min.z ) ); vertsPerCurve.push_back( 2 ); p.push_back( V3f( b.max.x, b.min.y, b.min.z ) ); p.push_back( V3f( b.max.x, b.max.y, b.min.z ) ); vertsPerCurve.push_back( 2 ); p.push_back( V3f( b.max.x, b.min.y, b.max.z ) ); p.push_back( V3f( b.max.x, b.max.y, b.max.z ) ); vertsPerCurve.push_back( 2 ); p.push_back( V3f( b.min.x, b.min.y, b.max.z ) ); p.push_back( V3f( b.min.x, b.max.y, b.max.z ) ); // frustum const std::string &projection = fullCamera->parametersData()->member<IECore::StringData>( "projection" )->readable(); const Box2f &screenWindow = fullCamera->parametersData()->member<IECore::Box2fData>( "screenWindow" )->readable(); /// \todo When we're drawing the camera by some means other than creating a primitive for it, /// use the actual clippings planes. Right now that's not a good idea as it results in /huge/ /// framing bounds when the viewer frames a selected camera. V2f clippingPlanes( 0, 5 ); Box2f near( screenWindow ); Box2f far( screenWindow ); if( projection == "perspective" ) { float fov = fullCamera->parametersData()->member<IECore::FloatData>( "projection:fov" )->readable(); float d = tan( IECore::degreesToRadians( fov / 2.0f ) ); near.min *= d * clippingPlanes[0]; near.max *= d * clippingPlanes[0]; far.min *= d * clippingPlanes[1]; far.max *= d * clippingPlanes[1]; } vertsPerCurve.push_back( 5 ); p.push_back( V3f( near.min.x, near.min.y, -clippingPlanes[0] ) ); p.push_back( V3f( near.max.x, near.min.y, -clippingPlanes[0] ) ); p.push_back( V3f( near.max.x, near.max.y, -clippingPlanes[0] ) ); p.push_back( V3f( near.min.x, near.max.y, -clippingPlanes[0] ) ); p.push_back( V3f( near.min.x, near.min.y, -clippingPlanes[0] ) ); vertsPerCurve.push_back( 5 ); p.push_back( V3f( far.min.x, far.min.y, -clippingPlanes[1] ) ); p.push_back( V3f( far.max.x, far.min.y, -clippingPlanes[1] ) ); p.push_back( V3f( far.max.x, far.max.y, -clippingPlanes[1] ) ); p.push_back( V3f( far.min.x, far.max.y, -clippingPlanes[1] ) ); p.push_back( V3f( far.min.x, far.min.y, -clippingPlanes[1] ) ); vertsPerCurve.push_back( 2 ); p.push_back( V3f( near.min.x, near.min.y, -clippingPlanes[0] ) ); p.push_back( V3f( far.min.x, far.min.y, -clippingPlanes[1] ) ); vertsPerCurve.push_back( 2 ); p.push_back( V3f( near.max.x, near.min.y, -clippingPlanes[0] ) ); p.push_back( V3f( far.max.x, far.min.y, -clippingPlanes[1] ) ); vertsPerCurve.push_back( 2 ); p.push_back( V3f( near.max.x, near.max.y, -clippingPlanes[0] ) ); p.push_back( V3f( far.max.x, far.max.y, -clippingPlanes[1] ) ); vertsPerCurve.push_back( 2 ); p.push_back( V3f( near.min.x, near.max.y, -clippingPlanes[0] ) ); p.push_back( V3f( far.min.x, far.max.y, -clippingPlanes[1] ) ); IECoreGL::CurvesPrimitivePtr curves = new IECoreGL::CurvesPrimitive( IECore::CubicBasisf::linear(), false, vertsPerCurveData ); curves->addPrimitiveVariable( "P", IECore::PrimitiveVariable( IECore::PrimitiveVariable::Vertex, pData ) ); group->addChild( curves ); return group; } protected : static ObjectVisualiserDescription<CameraVisualiser> g_visualiserDescription; }; ObjectVisualiser::ObjectVisualiserDescription<CameraVisualiser> CameraVisualiser::g_visualiserDescription; } // namespace
38.072917
130
0.663748
[ "object", "vector" ]
1ddd0ca870d9558d3e5e9ad9748904f71f8d7ff4
10,249
cpp
C++
src/qt/qtbase/tests/auto/other/macgui/guitest.cpp
zwollerob/PhantomJS_AMR6VL
71c126e98a8c32950158d04d0bd75823cd008b99
[ "BSD-3-Clause" ]
null
null
null
src/qt/qtbase/tests/auto/other/macgui/guitest.cpp
zwollerob/PhantomJS_AMR6VL
71c126e98a8c32950158d04d0bd75823cd008b99
[ "BSD-3-Clause" ]
null
null
null
src/qt/qtbase/tests/auto/other/macgui/guitest.cpp
zwollerob/PhantomJS_AMR6VL
71c126e98a8c32950158d04d0bd75823cd008b99
[ "BSD-3-Clause" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "guitest.h" #include <QDebug> #include <QWidget> #include <QStack> #include <QTimer> #include <QtTest/QtTest> #ifdef Q_OS_MAC # include <ApplicationServices/ApplicationServices.h> #endif /* Not really a test, just prints interface info. */ class PrintTest : public TestBase { public: bool operator()(QAccessibleInterface *candidate) { qDebug() << ""; qDebug() << "Name" << candidate->text(QAccessible::Name); qDebug() << "Pos" << candidate->rect(); qDebug() << "Number of children" << candidate->childCount(); return false; } }; class NameTest : public TestBase { public: NameTest(const QString &text, QAccessible::Text textType) : text(text), textType(textType) {} QString text; QAccessible::Text textType; bool operator()(QAccessibleInterface *candidate) { return (candidate->text(textType) == text); } }; void WidgetNavigator::printAll(QWidget *widget) { QAccessibleInterface * const iface = QAccessible::queryAccessibleInterface(widget); printAll(iface); } void WidgetNavigator::printAll(QAccessibleInterface *interface) { PrintTest printTest; recursiveSearch(&printTest, interface); } QAccessibleInterface *WidgetNavigator::find(QAccessible::Text textType, const QString &text, QWidget *start) { QAccessibleInterface *const iface = QAccessible::queryAccessibleInterface(start); return find(textType, text, iface); } QAccessibleInterface *WidgetNavigator::find(QAccessible::Text textType, const QString &text, QAccessibleInterface *start) { NameTest nameTest(text, textType); return recursiveSearch(&nameTest, start); } /* Recursiveley navigates the accessible hiearchy looking for an interface that passsed the Test (meaning it returns true). */ QAccessibleInterface *WidgetNavigator::recursiveSearch(TestBase *test, QAccessibleInterface *iface) { QStack<QAccessibleInterface *> todoInterfaces; todoInterfaces.push(iface); while (todoInterfaces.isEmpty() == false) { QAccessibleInterface *testInterface = todoInterfaces.pop(); if ((*test)(testInterface)) return testInterface; const int numChildren = testInterface->childCount(); for (int i = 0; i < numChildren; ++i) { QAccessibleInterface *childInterface = testInterface->child(i); if (childInterface) { todoInterfaces.push(childInterface); } } } return 0; } QWidget *WidgetNavigator::getWidget(QAccessibleInterface *interface) { return qobject_cast<QWidget *>(interface->object()); } WidgetNavigator::~WidgetNavigator() { } /////////////////////////////////////////////////////////////////////////////// namespace NativeEvents { #ifdef Q_OS_MAC void mouseClick(const QPoint &globalPos, Qt::MouseButtons buttons) { CGPoint position; position.x = globalPos.x(); position.y = globalPos.y(); CGEventType mouseDownType = (buttons & Qt::LeftButton) ? kCGEventLeftMouseDown : (buttons & Qt::RightButton) ? kCGEventRightMouseDown : kCGEventOtherMouseDown; CGMouseButton mouseButton = mouseDownType == kCGEventOtherMouseDown ? kCGMouseButtonCenter : kCGEventLeftMouseDown; CGEventRef mouseEvent = CGEventCreateMouseEvent(NULL, mouseDownType, position, mouseButton); CGEventPost(kCGHIDEventTap, mouseEvent); CGEventType mouseUpType = (buttons & Qt::LeftButton) ? kCGEventLeftMouseUp : (buttons & Qt::RightButton) ? kCGEventRightMouseUp : kCGEventOtherMouseUp; CGEventSetType(mouseEvent, mouseUpType); CGEventPost(kCGHIDEventTap, mouseEvent); CFRelease(mouseEvent); } #else # error Oops, NativeEvents::mouseClick() is not implemented on this platform. #endif }; /////////////////////////////////////////////////////////////////////////////// GuiTester::GuiTester() { clearSequence(); } GuiTester::~GuiTester() { foreach(DelayedAction *action, actions) delete action; } bool checkPixel(QColor pixel, QColor expected) { const int allowedDiff = 20; return !(qAbs(pixel.red() - expected.red()) > allowedDiff || qAbs(pixel.green() - expected.green()) > allowedDiff || qAbs(pixel.blue() - expected.blue()) > allowedDiff); } /* Tests that the pixels inside rect in image all have the given color. */ bool GuiTester::isFilled(const QImage image, const QRect &rect, const QColor &color) { for (int y = rect.top(); y <= rect.bottom(); ++y) for (int x = rect.left(); x <= rect.right(); ++x) { const QColor pixel = image.pixel(x, y); if (checkPixel(pixel, color) == false) { // qDebug()<< "Wrong pixel value at" << x << y << pixel.red() << pixel.green() << pixel.blue(); return false; } } return true; } /* Tests that stuff is painted to the pixels inside rect. This test fails if any lines in the given direction have pixels of only one color. */ bool GuiTester::isContent(const QImage image, const QRect &rect, Directions directions) { if (directions & Horizontal) { for (int y = rect.top(); y <= rect.bottom(); ++y) { QColor currentColor = image.pixel(rect.left(), y); bool fullRun = true; for (int x = rect.left() + 1; x <= rect.right(); ++x) { if (checkPixel(image.pixel(x, y), currentColor) == false) { fullRun = false; break; } } if (fullRun) { // qDebug() << "Single-color line at horizontal line " << y << currentColor; return false; } } return true; } if (directions & Vertical) { for (int x = rect.left(); x <= rect.right(); ++x) { QRgb currentColor = image.pixel(x, rect.top()); bool fullRun = true; for (int y = rect.top() + 1; y <= rect.bottom(); ++y) { if (checkPixel(image.pixel(x, y), currentColor) == false) { fullRun = false; break; } } if (fullRun) { // qDebug() << "Single-color line at vertical line" << x << currentColor; return false; } } return true; } return false; // shut the compiler up. } void DelayedAction::run() { if (next) QTimer::singleShot(next->delay, next, SLOT(run())); }; /* Schedules a mouse click at an interface using a singleShot timer. Only one click can be scheduled at a time. */ ClickLaterAction::ClickLaterAction(QAccessibleInterface *interface, Qt::MouseButtons buttons) { this->useInterface = true; this->interface = interface; this->buttons = buttons; } /* Schedules a mouse click at a widget using a singleShot timer. Only one click can be scheduled at a time. */ ClickLaterAction::ClickLaterAction(QWidget *widget, Qt::MouseButtons buttons) { this->useInterface = false; this->widget = widget; this->buttons = buttons; } void ClickLaterAction::run() { if (useInterface) { const QPoint globalCenter = interface->rect().center(); NativeEvents::mouseClick(globalCenter, buttons); } else { // use widget const QSize halfSize = widget->size() / 2; const QPoint globalCenter = widget->mapToGlobal(QPoint(halfSize.width(), halfSize.height())); NativeEvents::mouseClick(globalCenter, buttons); } DelayedAction::run(); } void GuiTester::clickLater(QAccessibleInterface *interface, Qt::MouseButtons buttons, int delay) { clearSequence(); addToSequence(new ClickLaterAction(interface, buttons), delay); runSequence(); } void GuiTester::clickLater(QWidget *widget, Qt::MouseButtons buttons, int delay) { clearSequence(); addToSequence(new ClickLaterAction(widget, buttons), delay); runSequence(); } void GuiTester::clearSequence() { startAction = new DelayedAction(); actions.insert(startAction); lastAction = startAction; } void GuiTester::addToSequence(DelayedAction *action, int delay) { actions.insert(action); action->delay = delay; lastAction->next = action; lastAction = action; } void GuiTester::runSequence() { QTimer::singleShot(0, startAction, SLOT(run())); } void GuiTester::exitLoopSlot() { QTestEventLoop::instance().exitLoop(); }
31.246951
123
0.625524
[ "object" ]
1dde435d0b29db386e90bc83a150cd911117dffc
27,394
cc
C++
server/engine/test/rocksdb_test.cc
ibyte2011/LaserDB
326fa477c4cbee36f46706ecb3b4a48d3bdab057
[ "Apache-2.0" ]
null
null
null
server/engine/test/rocksdb_test.cc
ibyte2011/LaserDB
326fa477c4cbee36f46706ecb3b4a48d3bdab057
[ "Apache-2.0" ]
null
null
null
server/engine/test/rocksdb_test.cc
ibyte2011/LaserDB
326fa477c4cbee36f46706ecb3b4a48d3bdab057
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2020-present, Weibo, Inc. 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. * * @author ZhongXiu Hao <nmred.hao@gmail.com> */ #include "laser/server/engine/rocksdb.h" #include "boost/filesystem.hpp" #include "folly/Singleton.h" #include "folly/portability/GTest.h" #include "folly/Random.h" namespace laser { DECLARE_bool(batch_ingest_format_is_sst); namespace test { class RocksdbTest : public ::testing::Test { public: RocksdbTest() { folly::SingletonVault::singleton()->registrationComplete(); path_ = folly::to<std::string>("/tmp/rocksdb_unit_test_", folly::Random::secureRand32()); std::vector<std::string> primary_keys({"uid", "xx"}); std::vector<std::string> column_names({"age"}); LaserKeyFormat test_key(primary_keys, column_names); key_ = test_key; options_.create_if_missing = true; // ้ป˜่ฎคไป…ๆต‹่ฏ•ๅŠ ่ฝฝ sst ๆ ผๅผๆ–‡ไปถ laser::FLAGS_batch_ingest_format_is_sst = true; } virtual ~RocksdbTest() { boost::filesystem::path bpath(path_); if (boost::filesystem::exists(bpath)) { boost::filesystem::remove_all(bpath); } } bool opendb() { auto db = std::make_shared<laser::ReplicationDB>(path_, options_); db_ = std::make_shared<laser::RocksDbEngine>(db); return db_->open(); } virtual void TearDown() { boost::filesystem::path bpath(path_); if (boost::filesystem::exists(bpath)) { boost::filesystem::remove_all(bpath); } } virtual void SetUp() {} protected: rocksdb::Options options_; std::string path_; std::shared_ptr<laser::RocksDbEngine> db_; LaserKeyFormat key_; void testIngestDeltaStringData(uint32_t size) { EXPECT_TRUE(opendb()); std::string sst_file_temp_db = folly::to<std::string>(path_, "/", folly::Random::secureRand32()); auto replication_db = std::make_shared<laser::ReplicationDB>(sst_file_temp_db, options_); auto dump_db = std::make_shared<laser::RocksDbEngine>(replication_db); EXPECT_TRUE(dump_db->open()); std::string value_prefix = "xxxx"; for (uint32_t i = 0; i < size; i++) { std::string data = folly::to<std::string>(value_prefix, i); std::vector<std::string> primary_keys({"uid", "xx"}); std::vector<std::string> column_names({data}); LaserKeyFormat test_key(primary_keys, column_names); laser::Status status = dump_db->set(test_key, data); EXPECT_EQ(laser::Status::OK, status); } std::string sst_file_path = folly::to<std::string>(path_, "/", folly::Random::secureRand32()); laser::Status status = dump_db->dumpSst(sst_file_path); EXPECT_EQ(laser::Status::OK, status); std::string tempdb_path = folly::to<std::string>(path_, "/", folly::Random::secureRand32()); status = db_->ingestDeltaSst(sst_file_path, tempdb_path); EXPECT_EQ(laser::Status::OK, status); for (uint32_t i = 0; i < size; i++) { std::string data = folly::to<std::string>(value_prefix, i); std::vector<std::string> primary_keys({"uid", "xx"}); std::vector<std::string> column_names({data}); LaserKeyFormat test_key(primary_keys, column_names); laser::LaserValueRawString value; laser::Status status = db_->get(&value, test_key); EXPECT_EQ(laser::Status::OK, status); EXPECT_EQ(data, value.getValue()); } } }; TEST_F(RocksdbTest, opendb) { EXPECT_TRUE(opendb()); } TEST_F(RocksdbTest, append) { EXPECT_TRUE(opendb()); uint32_t length = 0; laser::Status s = db_->append(&length, key_, "data"); EXPECT_EQ(laser::Status::OK, s); EXPECT_EQ(4, length); laser::LaserValueRawString value; s = db_->get(&value, key_); EXPECT_EQ(laser::Status::OK, s); EXPECT_EQ("data", value.getValue()); length = 0; s = db_->append(&length, key_, "111"); EXPECT_EQ(laser::Status::OK, s); EXPECT_EQ(7, length); value.reset(); s = db_->get(&value, key_); EXPECT_EQ(laser::Status::OK, s); EXPECT_EQ("data111", value.getValue()); } TEST_F(RocksdbTest, exist) { EXPECT_TRUE(opendb()); uint32_t length = 0; laser::Status s = db_->append(&length, key_, "data"); EXPECT_EQ(laser::Status::OK, s); EXPECT_EQ(4, length); laser::LaserValueRawString value; s = db_->get(&value, key_); EXPECT_EQ(laser::Status::OK, s); EXPECT_EQ("data", value.getValue()); bool has_key = false; s = db_->exist(&has_key, key_); EXPECT_EQ(laser::Status::OK, s); EXPECT_EQ(true, has_key); s = db_->delkey(key_); EXPECT_EQ(laser::Status::OK, s); s = db_->exist(&has_key, key_); EXPECT_EQ(laser::Status::OK, s); EXPECT_EQ(false, has_key); } TEST_F(RocksdbTest, setx) { EXPECT_TRUE(opendb()); RocksDbEngineSetOptions options; options.not_exists = true; laser::Status s = db_->setx(key_, "data", options); EXPECT_EQ(laser::Status::OK, s); laser::LaserValueRawString value; s = db_->get(&value, key_); EXPECT_EQ(laser::Status::OK, s); EXPECT_EQ("data", value.getValue()); s = db_->setx(key_, "data", options); EXPECT_EQ(laser::Status::RS_KEY_EXISTS, s); s = db_->delkey(key_); EXPECT_EQ(laser::Status::OK, s); options.ttl = 5; options.not_exists = true; s = db_->setx(key_, "data", options); EXPECT_EQ(laser::Status::OK, s); s = db_->setx(key_, "data", options); EXPECT_EQ(laser::Status::RS_KEY_EXISTS, s); std::this_thread::sleep_for(std::chrono::milliseconds(10)); s = db_->setx(key_, "data", options); EXPECT_EQ(laser::Status::OK, s); } TEST_F(RocksdbTest, set) { EXPECT_TRUE(opendb()); laser::Status s = db_->set(key_, "data"); EXPECT_EQ(laser::Status::OK, s); laser::LaserValueRawString value; s = db_->get(&value, key_); EXPECT_EQ(laser::Status::OK, s); EXPECT_EQ("data", value.getValue()); s = db_->set(key_, "111"); EXPECT_EQ(laser::Status::OK, s); value.reset(); s = db_->get(&value, key_); EXPECT_EQ(laser::Status::OK, s); EXPECT_EQ("111", value.getValue()); } TEST_F(RocksdbTest, incrAndDecr) { EXPECT_TRUE(opendb()); std::vector<std::string> primary_keys({"uid", "xx"}); std::vector<std::string> column_names({"age"}); int64_t value; laser::Status s = db_->incr(&value, key_); EXPECT_EQ(laser::Status::OK, s); EXPECT_EQ(1, value); s = db_->incr(&value, key_, 1000); EXPECT_EQ(laser::Status::OK, s); EXPECT_EQ(1001, value); s = db_->decr(&value, key_); EXPECT_EQ(laser::Status::OK, s); EXPECT_EQ(1000, value); s = db_->decr(&value, key_, 3000); EXPECT_EQ(laser::Status::OK, s); EXPECT_EQ(-2000, value); } TEST_F(RocksdbTest, hset) { EXPECT_TRUE(opendb()); std::string field = "test1"; std::string field_value = "xxxx"; laser::Status s = db_->hset(key_, field, field_value); EXPECT_EQ(laser::Status::OK, s); LaserValueMapMeta map_meta; s = db_->hlen(&map_meta, key_); EXPECT_EQ(laser::Status::OK, s); EXPECT_EQ(1, map_meta.getSize()); LaserValueRawString value; s = db_->hget(&value, key_, field); EXPECT_EQ(laser::Status::OK, s); EXPECT_EQ(field_value, value.getValue()); // set ไธ€ไธช ๅญ˜ๅœจ็š„ key s = db_->hset(key_, field, field_value); EXPECT_EQ(laser::Status::OK, s); map_meta.reset(); s = db_->hlen(&map_meta, key_); EXPECT_EQ(laser::Status::OK, s); EXPECT_EQ(1, map_meta.getSize()); } TEST_F(RocksdbTest, hmset) { EXPECT_TRUE(opendb()); std::string field_prefix = "test"; std::string field_value = "xxxx"; std::string field0 = "test0"; laser::Status s = db_->hset(key_, field0, field_value); EXPECT_EQ(laser::Status::OK, s); LaserValueMapMeta map_meta; s = db_->hlen(&map_meta, key_); EXPECT_EQ(laser::Status::OK, s); EXPECT_EQ(1, map_meta.getSize()); LaserValueRawString value; s = db_->hget(&value, key_, field0); EXPECT_EQ(laser::Status::OK, s); EXPECT_EQ(field_value, value.getValue()); std::map<std::string, std::string> data; for (int i = 0; i < 10; i++) { data[folly::to<std::string>(field_prefix, i)] = folly::to<std::string>(field_value, i); } // set ไธ€ไธช ๅญ˜ๅœจ็š„ key s = db_->hmset(key_, data); EXPECT_EQ(laser::Status::OK, s); map_meta.reset(); s = db_->hlen(&map_meta, key_); EXPECT_EQ(laser::Status::OK, s); EXPECT_EQ(10, map_meta.getSize()); std::vector<laser::LaserKeyFormatMapData> keys; s = db_->hkeys(&keys, key_); EXPECT_EQ(laser::Status::OK, s); for (int i = 0; i < 10; i++) { EXPECT_EQ(folly::to<std::string>(field_prefix, i), keys[i].getField()); } for (int i = 0; i < 10; i++) { std::string field = folly::to<std::string>(field_prefix, i); std::string value = folly::to<std::string>(field_value, i); LaserValueRawString raw_value; s = db_->hget(&raw_value, key_, field); EXPECT_EQ(laser::Status::OK, s); EXPECT_EQ(value, raw_value.getValue()); } } TEST_F(RocksdbTest, hdel) { EXPECT_TRUE(opendb()); std::string field = "test1"; std::string field_value = "xxxx"; laser::Status s = db_->hset(key_, field, field_value); EXPECT_EQ(laser::Status::OK, s); LaserValueMapMeta map_meta; s = db_->hlen(&map_meta, key_); EXPECT_EQ(laser::Status::OK, s); EXPECT_EQ(1, map_meta.getSize()); s = db_->hdel(key_, field); EXPECT_EQ(laser::Status::OK, s); map_meta.reset(); s = db_->hlen(&map_meta, key_); EXPECT_EQ(laser::Status::OK, s); EXPECT_EQ(0, map_meta.getSize()); s = db_->hdel(key_, field); EXPECT_EQ(laser::Status::RS_NOT_FOUND, s); } TEST_F(RocksdbTest, hget) { EXPECT_TRUE(opendb()); std::string field = "test"; std::string field1 = "test1"; std::string field_value = "xxxx"; laser::Status s = db_->hset(key_, field, field_value); EXPECT_EQ(laser::Status::OK, s); LaserValueMapMeta map_meta; s = db_->hlen(&map_meta, key_); EXPECT_EQ(laser::Status::OK, s); EXPECT_EQ(1, map_meta.getSize()); LaserValueRawString value; s = db_->hget(&value, key_, field); EXPECT_EQ(laser::Status::OK, s); EXPECT_EQ(field_value, value.getValue()); s = db_->hget(&value, key_, field1); EXPECT_EQ(laser::Status::RS_NOT_FOUND, s); } TEST_F(RocksdbTest, hkeys) { EXPECT_TRUE(opendb()); std::string field_prefix = "test1"; std::string field_value = "xxxx"; for (int i = 0; i < 100; i++) { laser::Status s = db_->hset(key_, folly::to<std::string>(field_prefix, i), field_value); EXPECT_EQ(laser::Status::OK, s); } std::vector<laser::LaserKeyFormatMapData> keys; laser::Status s = db_->hkeys(&keys, key_); EXPECT_EQ(laser::Status::OK, s); for (int i = 0; i < 100; i++) { EXPECT_EQ(folly::to<std::string>(field_prefix, i), keys[i].getField()); } } TEST_F(RocksdbTest, hgetall) { EXPECT_TRUE(opendb()); std::string field_prefix = "test1"; std::string field_value = "xxxx"; for (int i = 0; i < 100; i++) { laser::Status s = db_->hset(key_, folly::to<std::string>(field_prefix, i), field_value); EXPECT_EQ(laser::Status::OK, s); } std::unordered_map<std::string, LaserValueRawString> values; laser::Status s = db_->hgetall(&values, key_); EXPECT_EQ(laser::Status::OK, s); for (int i = 0; i < 100; i++) { EXPECT_EQ(field_value, values[folly::to<std::string>(field_prefix, i)].getValue()); } } TEST_F(RocksdbTest, pushFront) { EXPECT_TRUE(opendb()); std::string value_prefix = "xxxx"; for (int i = 0; i < 100; i++) { laser::Status status = db_->pushFront(key_, folly::to<std::string>(value_prefix, i)); EXPECT_EQ(laser::Status::OK, status); } laser::LaserValueListMeta list_meta; laser::Status status = db_->get(&list_meta, key_); EXPECT_EQ(laser::Status::OK, status); EXPECT_EQ(100, list_meta.getSize()); LaserValueRawString value; status = db_->lindex(&value, key_, 98); EXPECT_EQ(laser::Status::OK, status); // 99 98 .......0 EXPECT_EQ(folly::to<std::string>(value_prefix, 1), value.getValue()); value.reset(); status = db_->lindex(&value, key_, -2); EXPECT_EQ(laser::Status::OK, status); EXPECT_EQ(folly::to<std::string>(value_prefix, 1), value.getValue()); value.reset(); status = db_->lindex(&value, key_, 0); EXPECT_EQ(laser::Status::OK, status); EXPECT_EQ(folly::to<std::string>(value_prefix, 99), value.getValue()); value.reset(); status = db_->lindex(&value, key_, 100); EXPECT_EQ(laser::Status::RS_NOT_FOUND, status); } TEST_F(RocksdbTest, pushBack) { EXPECT_TRUE(opendb()); std::string value_prefix = "xxxx"; for (int i = 0; i < 100; i++) { laser::Status status = db_->pushBack(key_, folly::to<std::string>(value_prefix, i)); EXPECT_EQ(laser::Status::OK, status); } laser::LaserValueListMeta list_meta; laser::Status status = db_->get(&list_meta, key_); EXPECT_EQ(laser::Status::OK, status); EXPECT_EQ(100, list_meta.getSize()); LaserValueRawString value; status = db_->lindex(&value, key_, 98); EXPECT_EQ(laser::Status::OK, status); // 0 1 2 ..... 98 99 EXPECT_EQ(folly::to<std::string>(value_prefix, 98), value.getValue()); } TEST_F(RocksdbTest, popFront) { EXPECT_TRUE(opendb()); std::string value_prefix = "xxxx"; for (int i = 0; i < 100; i++) { laser::Status status = db_->pushBack(key_, folly::to<std::string>(value_prefix, i)); EXPECT_EQ(laser::Status::OK, status); } laser::LaserValueListMeta list_meta; laser::Status status = db_->get(&list_meta, key_); EXPECT_EQ(laser::Status::OK, status); EXPECT_EQ(100, list_meta.getSize()); LaserValueRawString value; for (int i = 0; i < 100; i++) { value.reset(); status = db_->popFront(&value, key_); EXPECT_EQ(laser::Status::OK, status); EXPECT_EQ(folly::to<std::string>(value_prefix, i), value.getValue()); } list_meta.reset(); status = db_->get(&list_meta, key_); EXPECT_EQ(laser::Status::OK, status); EXPECT_EQ(0, list_meta.getSize()); } TEST_F(RocksdbTest, popBack) { EXPECT_TRUE(opendb()); std::string value_prefix = "xxxx"; for (int i = 0; i < 100; i++) { laser::Status status = db_->pushFront(key_, folly::to<std::string>(value_prefix, i)); EXPECT_EQ(laser::Status::OK, status); } laser::LaserValueListMeta list_meta; laser::Status status = db_->get(&list_meta, key_); EXPECT_EQ(laser::Status::OK, status); EXPECT_EQ(100, list_meta.getSize()); LaserValueRawString value; for (int i = 0; i < 100; i++) { value.reset(); status = db_->popBack(&value, key_); EXPECT_EQ(laser::Status::OK, status); EXPECT_EQ(folly::to<std::string>(value_prefix, i), value.getValue()); } list_meta.reset(); status = db_->get(&list_meta, key_); EXPECT_EQ(laser::Status::OK, status); EXPECT_EQ(0, list_meta.getSize()); } TEST_F(RocksdbTest, popEmpty) { EXPECT_TRUE(opendb()); laser::LaserValueListMeta list_meta; laser::Status status = db_->get(&list_meta, key_); EXPECT_EQ(laser::Status::OK, status); EXPECT_EQ(0, list_meta.getSize()); LaserValueRawString value; status = db_->popBack(&value, key_); EXPECT_EQ(laser::Status::RS_NOT_FOUND, status); status = db_->pushFront(key_, "test"); EXPECT_EQ(laser::Status::OK, status); value.reset(); status = db_->popBack(&value, key_); EXPECT_EQ(laser::Status::OK, status); EXPECT_EQ("test", value.getValue()); value.reset(); status = db_->popBack(&value, key_); EXPECT_EQ(laser::Status::RS_EMPTY, status); } TEST_F(RocksdbTest, lrange) { EXPECT_TRUE(opendb()); std::vector<LaserValueRawString> values; laser::Status status = db_->lrange(&values, key_); EXPECT_EQ(laser::Status::RS_NOT_FOUND, status); std::string value_prefix = "xxxx"; for (int i = 0; i < 100; i++) { laser::Status status = db_->pushBack(key_, folly::to<std::string>(value_prefix, i)); EXPECT_EQ(laser::Status::OK, status); } values.clear(); status = db_->lrange(&values, key_); EXPECT_EQ(laser::Status::OK, status); EXPECT_EQ(100, values.size()); values.clear(); status = db_->lrange(&values, key_, 4); EXPECT_EQ(laser::Status::OK, status); EXPECT_EQ(96, values.size()); for (int i = 4; i < 100; i++) { EXPECT_EQ(folly::to<std::string>(value_prefix, i), values[i - 4].getValue()); } values.clear(); status = db_->lrange(&values, key_, 4, 10); EXPECT_EQ(laser::Status::OK, status); EXPECT_EQ(6, values.size()); for (int i = 4; i < 10; i++) { EXPECT_EQ(folly::to<std::string>(value_prefix, i), values[i - 4].getValue()); } values.clear(); status = db_->lrange(&values, key_, 4, 3); EXPECT_EQ(laser::Status::RS_INVALID_ARGUMENT, status); values.clear(); status = db_->lrange(&values, key_, 100, 200); EXPECT_EQ(laser::Status::RS_INVALID_ARGUMENT, status); } TEST_F(RocksdbTest, sadd) { EXPECT_TRUE(opendb()); std::string value_prefix = "xxxx"; for (int i = 0; i < 100; i++) { laser::Status status = db_->sadd(key_, folly::to<std::string>(value_prefix, i)); EXPECT_EQ(laser::Status::OK, status); } LaserValueSetMeta set_meta; laser::Status status = db_->get(&set_meta, key_); EXPECT_EQ(laser::Status::OK, status); EXPECT_EQ(100, set_meta.getSize()); for (int i = 0; i < 100; i++) { laser::Status status = db_->sadd(key_, folly::to<std::string>(value_prefix, i)); EXPECT_EQ(laser::Status::OK, status); } set_meta.reset(); status = db_->get(&set_meta, key_); EXPECT_EQ(laser::Status::OK, status); EXPECT_EQ(100, set_meta.getSize()); std::vector<LaserKeyFormatSetData> members; status = db_->members(&members, key_); EXPECT_EQ(laser::Status::OK, status); for (int i = 0; i < 100; i++) { EXPECT_EQ(folly::to<std::string>(value_prefix, i), members[i].getData()); } status = db_->hasMember(key_, folly::to<std::string>(value_prefix, 50)); EXPECT_EQ(laser::Status::OK, status); status = db_->hasMember(key_, folly::to<std::string>(value_prefix, 500)); EXPECT_EQ(laser::Status::RS_NOT_FOUND, status); status = db_->sdel(key_, folly::to<std::string>(value_prefix, 50)); EXPECT_EQ(laser::Status::OK, status); status = db_->hasMember(key_, folly::to<std::string>(value_prefix, 50)); EXPECT_EQ(laser::Status::RS_NOT_FOUND, status); set_meta.reset(); status = db_->get(&set_meta, key_); EXPECT_EQ(laser::Status::OK, status); EXPECT_EQ(99, set_meta.getSize()); } TEST_F(RocksdbTest, zset) { EXPECT_TRUE(opendb()); std::map<std::string, int64_t> member_scores; member_scores.insert({"negative_one_million", -1000000}); member_scores.insert({"negative_two_million", -2000000}); member_scores.insert({"three", 3}); member_scores.insert({"four", 4}); laser::Status s = db_->zadd(key_, member_scores); EXPECT_EQ(laser::Status::OK, s); // the same score and member should not add s = db_->zadd(key_, member_scores); EXPECT_EQ(laser::Status::OK, s); std::vector<LaserScoreMember> members; s = db_->zrangeByScore(&members, key_, -2000000, 0); EXPECT_EQ(laser::Status::OK, s); EXPECT_EQ(2, members.size()); EXPECT_EQ("negative_two_million", members[0].get_member()); EXPECT_EQ(-2000000, members[0].get_score()); EXPECT_EQ("negative_one_million", members[1].get_member()); EXPECT_EQ(-1000000, members[1].get_score()); members.clear(); s = db_->zrangeByScore(&members, key_, -3000000, 4); EXPECT_EQ(laser::Status::OK, s); EXPECT_EQ(4, members.size()); EXPECT_EQ("negative_two_million", members[0].get_member()); EXPECT_EQ(-2000000, members[0].get_score()); EXPECT_EQ("negative_one_million", members[1].get_member()); EXPECT_EQ(-1000000, members[1].get_score()); EXPECT_EQ("three", members[2].get_member()); EXPECT_EQ(3, members[2].get_score()); EXPECT_EQ("four", members[3].get_member()); EXPECT_EQ(4, members[3].get_score()); members.clear(); s = db_->zrangeByScore(&members, key_, 0, 4); EXPECT_EQ(laser::Status::OK, s); EXPECT_EQ(2, members.size()); EXPECT_EQ("three", members[0].get_member()); EXPECT_EQ(3, members[0].get_score()); EXPECT_EQ("four", members[1].get_member()); EXPECT_EQ(4, members[1].get_score()); std::map<std::string, int64_t> member_scores2; member_scores2.insert({"negative_one_million_second", -1000000}); member_scores2.insert({"negative_two_million_second", -2000000}); s = db_->zadd(key_, member_scores2); EXPECT_EQ(laser::Status::OK, s); int64_t number = 0; s = db_->zremRangeByScore(&number, key_, -1000000, -1000000); EXPECT_EQ(laser::Status::OK, s); EXPECT_EQ(1, number); members.clear(); s = db_->zrangeByScore(&members, key_, -2000000, -1000000); EXPECT_EQ(laser::Status::OK, s); EXPECT_EQ(2, members.size()); EXPECT_EQ("negative_two_million", members[0].get_member()); EXPECT_EQ(-2000000, members[0].get_score()); EXPECT_EQ("negative_two_million_second", members[1].get_member()); EXPECT_EQ(-2000000, members[1].get_score()); uint64_t expire_time = 5 + static_cast<uint64_t>(common::currentTimeInMs()); s = db_->expireAt(key_, expire_time); EXPECT_EQ(laser::Status::OK, s); std::this_thread::sleep_for(std::chrono::milliseconds(10)); s = db_->zrangeByScore(&members, key_, -2000000, -1000000); EXPECT_EQ(laser::Status::RS_KEY_EXPIRE, s); } TEST_F(RocksdbTest, type_error) { EXPECT_TRUE(opendb()); std::vector<std::string> primary_keys({"uid", "xx"}); std::vector<std::string> column_names({"age"}); uint32_t length = 0; laser::Status s = db_->append(&length, key_, "data"); EXPECT_EQ(laser::Status::OK, s); // ็ฑปๅž‹ไธๅฏน int64_t value; s = db_->incr(&value, key_); EXPECT_EQ(laser::Status::RS_INVALID_ARGUMENT, s); } TEST_F(RocksdbTest, delkey) { EXPECT_TRUE(opendb()); std::string value_prefix = "xxxx"; std::vector<std::string> set_pk({"uid", "set"}); std::vector<std::string> column_names({"age"}); LaserKeyFormat set_key(set_pk, column_names); for (int i = 0; i < 100; i++) { laser::Status status = db_->sadd(set_key, folly::to<std::string>(value_prefix, i)); EXPECT_EQ(laser::Status::OK, status); } LaserValueSetMeta set_meta; laser::Status status = db_->get(&set_meta, set_key); EXPECT_EQ(laser::Status::OK, status); EXPECT_EQ(100, set_meta.getSize()); status = db_->delkey(set_key); EXPECT_EQ(laser::Status::OK, status); status = db_->get(&set_meta, set_key); EXPECT_EQ(laser::Status::RS_NOT_FOUND, status); } TEST_F(RocksdbTest, ingestDeltaData) { EXPECT_TRUE(opendb()); std::string sst_file_temp_db = folly::to<std::string>(path_, "/", folly::Random::secureRand32()); auto replication_db = std::make_shared<laser::ReplicationDB>(sst_file_temp_db, options_); auto dump_db = std::make_shared<laser::RocksDbEngine>(replication_db); EXPECT_TRUE(dump_db->open()); std::string value_prefix = "xxxx"; std::vector<std::string> set_pk({"uid", "set"}); std::vector<std::string> column_names({"age"}); for (uint32_t key_index = 0; key_index < 100; key_index++) { set_pk[1] = folly::to<std::string>("set", key_index); LaserKeyFormat set_key(set_pk, column_names); for (int i = 0; i < 100; i++) { laser::Status status = dump_db->sadd(set_key, folly::to<std::string>(value_prefix, i)); EXPECT_EQ(laser::Status::OK, status); } } std::string sst_file_path = folly::to<std::string>(path_, "/", folly::Random::secureRand32()); laser::Status status = dump_db->dumpSst(sst_file_path); EXPECT_EQ(laser::Status::OK, status); std::string tempdb_path = folly::to<std::string>(path_, "/", folly::Random::secureRand32()); status = db_->ingestDeltaSst(sst_file_path, tempdb_path); EXPECT_EQ(laser::Status::OK, status); // check for (uint32_t key_index = 0; key_index < 100; key_index++) { set_pk[1] = folly::to<std::string>("set", key_index); LaserKeyFormat set_key(set_pk, column_names); LaserValueSetMeta set_meta; laser::Status status = db_->get(&set_meta, set_key); EXPECT_EQ(laser::Status::OK, status); EXPECT_EQ(100, set_meta.getSize()); std::vector<LaserKeyFormatSetData> members; status = db_->members(&members, set_key); EXPECT_EQ(laser::Status::OK, status); for (int i = 0; i < 100; i++) { EXPECT_EQ(folly::to<std::string>(value_prefix, i), members[i].getData()); } } } TEST_F(RocksdbTest, ingestDeltaDataString) { testIngestDeltaStringData(100); testIngestDeltaStringData(1000); testIngestDeltaStringData(1001); testIngestDeltaStringData(10000); } TEST_F(RocksdbTest, expire) { EXPECT_TRUE(opendb()); std::string sst_file_temp_db = folly::to<std::string>(path_, "/", folly::Random::secureRand32()); auto replication_db = std::make_shared<laser::ReplicationDB>(sst_file_temp_db, options_); auto dump_db = std::make_shared<laser::RocksDbEngine>(replication_db); EXPECT_TRUE(dump_db->open()); std::string value_prefix = "xxxx"; std::string key_prefix = "string"; std::vector<std::string> pk({"uid", "0"}); std::vector<std::string> column_names({"age"}); uint64_t expire_time = 30000 + static_cast<uint64_t>(common::currentTimeInMs()); for (uint32_t key_index = 0; key_index < 100; key_index++) { pk[1] = folly::to<std::string>(key_prefix, key_index); LaserKeyFormat set_key(pk, column_names); laser::Status status = dump_db->set(set_key, folly::to<std::string>(value_prefix, key_index)); EXPECT_EQ(laser::Status::OK, status); status = dump_db->expireAt(set_key, expire_time + key_index); EXPECT_EQ(laser::Status::OK, status); LaserValueRawString data; status = dump_db->get(&data, set_key); EXPECT_EQ(laser::Status::OK, status); EXPECT_EQ(folly::to<std::string>(value_prefix, key_index), data.getValue()); } } TEST_F(RocksdbTest, deleteExpireKeysAndAutoExpire) { std::string test_path = folly::to<std::string>(path_, "/", folly::Random::secureRand32()); auto replication_db = std::make_shared<laser::ReplicationDB>(test_path, options_); auto rocks_options = std::make_shared<RocksDbEngineOptions>(); rocks_options->ttl = 5; auto db = std::make_shared<laser::RocksDbEngine>(replication_db, rocks_options); EXPECT_TRUE(db->open()); std::string value_prefix = "xxxx"; std::string key_prefix = "string"; std::vector<std::string> pk({"uid", "0"}); std::vector<std::string> column_names({"age"}); for (uint32_t key_index = 0; key_index < 100; key_index++) { pk[1] = folly::to<std::string>(key_prefix, key_index); LaserKeyFormat set_key(pk, column_names); laser::Status status = db->set(set_key, folly::to<std::string>(value_prefix, key_index)); EXPECT_EQ(laser::Status::OK, status); } std::this_thread::sleep_for(std::chrono::milliseconds(10)); for (uint32_t key_index = 0; key_index < 100; key_index++) { pk[1] = folly::to<std::string>(key_prefix, key_index); LaserKeyFormat set_key(pk, column_names); LaserValueRawString data; Status status = db->get(&data, set_key); EXPECT_EQ(laser::Status::RS_KEY_EXPIRE, status); } replication_db->compactRange(); for (uint32_t key_index = 0; key_index < 100; key_index++) { pk[1] = folly::to<std::string>(key_prefix, key_index); LaserKeyFormat set_key(pk, column_names); LaserValueRawString data; Status status = db->get(&data, set_key); EXPECT_EQ(laser::Status::RS_NOT_FOUND, status); } } } // namespace test } // namespace laser
31.200456
101
0.670439
[ "vector" ]
1de079882feaba92aecb2d96aa22fb93ba90a4fa
4,445
cpp
C++
Chapter_4_Graph/SSSP/kattis_fire2.cpp
BrandonTang89/CP4_Code
5114471f439978dd11f6f2cbf6af20ca654593da
[ "MIT" ]
2
2021-12-29T04:12:59.000Z
2022-03-30T09:32:19.000Z
Chapter_4_Graph/SSSP/kattis_fire2.cpp
BrandonTang89/CP4_Code
5114471f439978dd11f6f2cbf6af20ca654593da
[ "MIT" ]
null
null
null
Chapter_4_Graph/SSSP/kattis_fire2.cpp
BrandonTang89/CP4_Code
5114471f439978dd11f6f2cbf6af20ca654593da
[ "MIT" ]
1
2022-03-01T06:12:46.000Z
2022-03-01T06:12:46.000Z
/* kattis - fire2 This a non-standard floodfill / BFS question. Observation 1: We can model the situation as a simulation where fire and the "person's possible position" are both spreading. Fire can spread into the person's position but not the other way around. Both fire and person's position cannot spread onto walls. Since the person can always jump away from a cell catching on fire but cannot jump onto a cell that is about to catch fire, we should always simulate the fire first. This means that at clock cycle, we propate each propagatable fire cell first before doing the same for the person cells. This can be implemented with the use of a deque to store the upcoming propagatable cells. The same BFS frontier idea is kept, updating this deque with new frontier cells. Fire cells are put at the front of the deque while person cells are put at the back. However, we notice that one deque will not be a good idea because we don't know what calls are from what time. This could be solved by adding a 4th parameter of "clock" time but we choose instead to use 2 separate deques. We clear all the propagatable cells from the primary deque and put their children into the secondary deque. When the primary deque is empty, we increment the clock and swap the secondary and primary deque. Amortized Analysis: Even though there could be up to O(hw) cells in the propagation queue at any time, we note that after a person cell propagates once, that cell will only need to propagate again if it is covered by fire. This means that at most, each cell propagates twice, once when the person spreads onto the cell, and a second time when the fire spreads onto the tile. This means at most each cell is processed twice in the entire algorithm. Time: O(hw), Mem: O(hw) */ #pragma GCC optimize("Ofast") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,fma") #pragma GCC optimize("unroll-loops") #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef vector<int> vi; #define fast_cin() ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int ttc, w, h; vector<vector<char>> grid; deque<tuple<int, int, int>> q1, q2; // type (0 for fire, 1 for person), r, c int dr[] = {0, 0, 1, -1}; int dc[] = {1, -1, 0, 0}; int main(){ fast_cin(); cin >> ttc; for (int tc=0;tc<ttc;tc++){ cin >> w >> h; grid.assign(h, vector<char>(w, '.')); q1.clear(); q2.clear(); for (int r=0;r<h; r++){ for (int c=0;c<w;c++){ cin >> grid[r][c]; if (grid[r][c] == '@'){ q1.emplace_back(1, r, c); } else if (grid[r][c] == '*'){ q1.emplace_back(0, r, c); } } } int clock = 1; bool escaped = false; while (!(q1.empty() && q2.empty())){ // while not both empty auto &pq = ((clock&1) ? q1 : q2); // odd clock -> (pq == q1, sq == q2) auto &sq = ((clock&1) ? q2 : q1); while(!pq.empty()){ // while primary queue not empty auto [type, r, c] = pq.front(); //printf("type: %d, r: %d, c: %d\n", type, r, c); pq.pop_front(); for (int i=0;i<4;i++){ int nr = r + dr[i]; int nc = c + dc[i]; if (nc < 0 || nr < 0 || nc >= w || nr >= h){ if (type == 1){ escaped = true; break; } continue; } if (grid[nr][nc] == '#' || grid[nr][nc] == '*')continue; if (type == 1 && grid[nr][nc] == '@') continue; // person has no reason to go backwards grid[nr][nc] = ((type == 1) ? '@' : '*'); if (type == 1) sq.emplace_back(type, nr, nc); else sq.emplace_front(type, nr, nc); } if(escaped)break; } if(escaped)break; clock++; } if (escaped){ cout << clock << endl; } else{ cout << "IMPOSSIBLE" << endl; } } return 0; }
37.669492
107
0.538133
[ "vector", "model" ]
1de9597f7a60d3e0a1f05ad9ac3e866ae1822734
3,051
cc
C++
src/graph/op/kernel/where_op.cc
ishine/deepx_core
a71fa4b5fec5cf5d83da04cbb9ee437d0c8b6e05
[ "BSD-2-Clause" ]
309
2021-03-24T03:00:19.000Z
2022-03-31T16:17:46.000Z
src/graph/op/kernel/where_op.cc
kiminh/deepx_core
928d248ef26c9a5b48e34ff6a66761f94cd4be72
[ "BSD-2-Clause" ]
4
2021-03-30T01:46:32.000Z
2021-04-06T12:22:18.000Z
src/graph/op/kernel/where_op.cc
kiminh/deepx_core
928d248ef26c9a5b48e34ff6a66761f94cd4be72
[ "BSD-2-Clause" ]
45
2021-03-29T06:12:17.000Z
2022-03-04T05:19:46.000Z
// Copyright 2019 the deepx authors. // Author: Yafei Zhang (kimmyzhang@tencent.com) // #include <deepx_core/graph/op_impl.h> namespace deepx_core { namespace { bool WhereInferShape(const Shape& C, const Shape& X, const Shape& Y, Shape* Z) noexcept { if (C != X) { DXERROR("Invalid C and X: inconsistent shape %s vs %s.", to_string(C).c_str(), to_string(X).c_str()); } if (C != Y) { DXERROR("Invalid C and Y: inconsistent shape %s vs %s.", to_string(C).c_str(), to_string(Y).c_str()); } *Z = C; return true; } template <typename T> void Where(const Tensor<T>& C, const Tensor<T>& X, const Tensor<T>& Y, Tensor<T>* Z) noexcept { for (int i = 0; i < C.total_dim(); ++i) { if (C.data(i) != 0) { Z->data(i) = X.data(i); } else { Z->data(i) = Y.data(i); } } } template <typename T> void WhereBackward(const Tensor<T>& C, const Tensor<T>& /*X*/, const Tensor<T>& /*Y*/, const Tensor<T>& /*Z*/, const Tensor<T>& gZ, Tensor<T>* gX, Tensor<T>* gY) noexcept { for (int i = 0; i < gZ.total_dim(); ++i) { if (C.data(i) != 0) { if (gX) { gX->data(i) += gZ.data(i); } } else { if (gY) { gY->data(i) += gZ.data(i); } } } } } // namespace WhereNode::WhereNode(std::string name, GraphNode* C, GraphNode* X, GraphNode* Y) : GraphNode(std::move(name)) { DXCHECK_THROW(C->tensor_type() == TENSOR_TYPE_TSR); DXCHECK_THROW(X->tensor_type() == TENSOR_TYPE_TSR); DXCHECK_THROW(Y->tensor_type() == TENSOR_TYPE_TSR); input_ = {C, X, Y}; node_type_ = GRAPH_NODE_TYPE_HIDDEN; tensor_type_ = TENSOR_TYPE_TSR; if (!C->shape().empty() && !X->shape().empty() && !Y->shape().empty()) { (void)WhereInferShape(C->shape(), X->shape(), Y->shape(), &shape_); } } class WhereOp : public OpImpl { private: const GraphNode* Cnode_ = nullptr; const GraphNode* Xnode_ = nullptr; const GraphNode* Ynode_ = nullptr; const tsr_t* C_ = nullptr; const tsr_t* X_ = nullptr; const tsr_t* Y_ = nullptr; Shape Zshape_; tsr_t* Z_ = nullptr; tsr_t* gZ_ = nullptr; tsr_t* gC_ = nullptr; tsr_t* gX_ = nullptr; tsr_t* gY_ = nullptr; public: DEFINE_OP_LIKE(WhereOp); void InitForward() override { Cnode_ = node_->input(0); Xnode_ = node_->input(1); Ynode_ = node_->input(2); C_ = GetPtrTSR(Cnode_); X_ = GetPtrTSR(Xnode_); Y_ = GetPtrTSR(Ynode_); DXCHECK_THROW( WhereInferShape(C_->shape(), X_->shape(), Y_->shape(), &Zshape_)); Z_ = InitHiddenTSR(node_, Zshape_); } void InitBackward() override { gZ_ = GetGradPtrTSR(node_); gC_ = InitGradTSR(Cnode_, C_->shape()); gX_ = InitGradTSR(Xnode_, X_->shape()); gY_ = InitGradTSR(Ynode_, Y_->shape()); } void Forward() override { Where(*C_, *X_, *Y_, Z_); } void Backward() override { if (gZ_) { WhereBackward(*C_, *X_, *Y_, *Z_, *gZ_, gX_, gY_); } } }; GRAPH_NODE_OP_REGISTER(Where); } // namespace deepx_core
25.425
80
0.58571
[ "shape" ]
1deb3cbf89444666a7f3a8b63a61ea783f9406f3
5,164
cpp
C++
src/utils.cpp
cisco-open-source/oic
a6795f31fc639b181a10a5da753ecb97c011ca3d
[ "Apache-2.0" ]
1
2017-05-06T14:26:37.000Z
2017-05-06T14:26:37.000Z
src/utils.cpp
cisco-open-source/oic
a6795f31fc639b181a10a5da753ecb97c011ca3d
[ "Apache-2.0" ]
null
null
null
src/utils.cpp
cisco-open-source/oic
a6795f31fc639b181a10a5da753ecb97c011ca3d
[ "Apache-2.0" ]
2
2018-03-10T02:43:19.000Z
2020-10-02T18:50:20.000Z
#include "utils.h" #include <sstream> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> std::string getUserHome() { char *p = getenv("HOME"); std::string ret; if (p == NULL) ret = ""; else ret = std::string(p); return ret; } bool file_exist(const char *filename) { struct stat buffer; return (stat(filename, &buffer) == 0); } char* duplicateStr(const std::string sourceString) { return strdup(sourceString.c_str()); } void printOCResource(const OC::OCResource& oCResource) { printf( "PrintfOcResource\n"); printf( "\tRes[sId] = %s\n", oCResource.sid().c_str()); printf( "\tRes[Uri] = %s\n", oCResource.uri().c_str()); printf( "\tRes[Host] = %s\n", oCResource.host().c_str()); printf( "\tRes[Resource types]:\n"); for (const auto& resourceTypes : oCResource.getResourceTypes()) { printf( "\t\t%s\n", resourceTypes.c_str()); } printf( "Res[Resource interfaces] \n"); for (const auto& resourceInterfaces : oCResource.getResourceInterfaces()) { printf( "\t\t%s\n", resourceInterfaces.c_str()); } } void printOCRep(const OCRepresentation &oCRepr) { printf(">>printOCRep:\n"); std::string uri = oCRepr.getUri(); printf("\turi=%s\n", uri.c_str()); printf("\thost=%s\n", oCRepr.getHost().c_str()); printf("\ttypes\n"); for (const auto& resourceTypes : oCRepr.getResourceTypes()) { printf("\t\t%s\n", resourceTypes.c_str()); } printf("\tinterfaces\n"); for (const auto& resourceInterfaces : oCRepr.getResourceInterfaces()) { printf("\t\t%s\n", resourceInterfaces.c_str()); } for (const auto& cur : oCRepr) { std::string attrname = cur.attrname(); printf("\tattr key=%s\n", attrname.c_str()); if (AttributeType::String == cur.type()) { std::string curStr = cur.getValue<std::string>(); printf("\tRep[String]: key=%s, value=%s\n", attrname.c_str(), curStr.c_str()); } else if (AttributeType::Integer == cur.type()) { printf("\tRep[Integer]: key=%s, value=%d\n", attrname.c_str(), cur.getValue<int>()); } else if (AttributeType::Double == cur.type()) { printf("\tRep[Double]: key=%s, value=%f\n", attrname.c_str(), cur.getValue<double>()); } else if (AttributeType::Boolean == cur.type()) { printf("\tRep[Boolean]: key=%s, value=%d\n", attrname.c_str(), cur.getValue<bool>()); } else if (AttributeType::OCRepresentation == cur.type()) { printf("\tRep[OCRepresentation]: key=%s, value=%s\n", attrname.c_str(), "OCRep"); printOCRep(cur.getValue<OCRepresentation>()); } else if (AttributeType::Vector == cur.type()) { printf("\tRep[OCRepresentation]: key=%s, value=%s\n", attrname.c_str(), "Vector"); if (cur.base_type() == AttributeType::OCRepresentation) { printf("\tVector of OCRepresentation\n"); std::vector<OCRepresentation> v = cur.getValue<std::vector<OCRepresentation>>(); for (const auto& curv : v) { printf("\t>>Print sub OCRepresentation\n"); printOCRep(curv); printf("\t<<Print sub OCRepresentation\n"); } } } } printf("<<printOCRep:\n"); } bool checkType(const OCRepresentation &rep, const std::string requiredType) { /* std::vector<std::string> v = rep.getResourceTypes(); if (std::find(v.begin(), v.end(), requiredType) == v.end()) { std::cout << rep.getUri() << " invalid because missing type " << requiredType << std::endl; return false; }*/ return true; } bool checkInterface(const OCRepresentation &rep, const std::string requiredInt) { /* std::vector<std::string> v = rep.getResourceInterfaces(); if (std::find(v.begin(), v.end(), requiredInt) == v.end()) { std::cout << rep.getUri() << " invalid because missing interface " << requiredInt << std::endl; return false; }*/ return true; } bool checkAttr(const OCRepresentation &rep, const std::string requiredName, const AttributeType requiredType) { return checkAttr(rep, requiredName, requiredType, true); } bool checkAttr(const OCRepresentation &rep, const std::string requiredName, const AttributeType requiredType, bool mandatory) { if (!rep.hasAttribute(requiredName)) { if (mandatory) { std::cout << rep.getUri() << " invalid because missing attribute " << requiredName << std::endl; return false; } return true; } for (const auto& cur : rep) { std::string attrname = cur.attrname(); if (attrname == requiredName && requiredType != cur.type()) { std::cout << rep.getUri() << " invalid because " << attrname << " has wrong type:" << cur.type() << " instead of " << requiredType << std::endl; return false; } } return true; }
32.275
156
0.572812
[ "vector" ]
1df2fb808a434bcf0481d4984a16332e5cc4bdd7
489
cpp
C++
CondFormats/Luminosity/test/testSerializationLuminosity.cpp
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
CondFormats/Luminosity/test/testSerializationLuminosity.cpp
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
CondFormats/Luminosity/test/testSerializationLuminosity.cpp
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
#include "CondFormats/Serialization/interface/Test.h" #include "CondFormats/Luminosity/src/headers.h" int main() { testSerialization<lumi::BunchCrossingInfo>(); testSerialization<lumi::HLTInfo>(); testSerialization<lumi::LumiSectionData>(); testSerialization<lumi::TriggerInfo>(); testSerialization<std::vector<lumi::BunchCrossingInfo>>(); testSerialization<std::vector<lumi::HLTInfo>>(); testSerialization<std::vector<lumi::TriggerInfo>>(); return 0; }
28.764706
62
0.730061
[ "vector" ]
38071d83a1452b9eb89bd0fbc6435d892f23c49e
23,112
cpp
C++
admin/src/manage-entries.cpp
protein-bioinformatics/STAMPS
af5a4943d67ae3ce1cee51ab0d23f98d6269dd81
[ "MIT" ]
1
2022-03-24T15:26:58.000Z
2022-03-24T15:26:58.000Z
admin/src/manage-entries.cpp
protein-bioinformatics/STAMPS
af5a4943d67ae3ce1cee51ab0d23f98d6269dd81
[ "MIT" ]
null
null
null
admin/src/manage-entries.cpp
protein-bioinformatics/STAMPS
af5a4943d67ae3ce1cee51ab0d23f98d6269dd81
[ "MIT" ]
null
null
null
#include "bio-classes.h" char data_sepatator = '~'; void print_out(string response, bool compress){ replaceAll(response, "\n", ""); replaceAll(response, "\t", ""); if (compress){ cout << compress_string(response); } else { cout << response; } } static int sqlite_select_protein_loci(void *data, int argc, char **argv, char **azColName){ string* response = (string*)data; if (response[0].length() > 1) response[0] += ","; response[0] += "\"" + string(argv[0]) + "\":[" + argv[0]; for (int i = 1; i < argc; ++i){ string content = argv[i]; replaceAll(content, "\n", "\\n"); replaceAll(content, "\\", "\\\\"); response[0] += ",\"" + content + "\""; } response[0] += "]"; return SQLITE_OK; } static int sqlite_select_remaining(void *data, int argc, char **argv, char **azColName){ string* response = (string*)data; if (response[0].length() > 1) response[0] += ","; response[0] += "[" + string(argv[0]); for (int i = 1; i < argc; ++i){ string content = argv[i]; replaceAll(content, "\n", "\\n"); replaceAll(content, "\\", "\\\\"); response[0] += ",\"" + content + "\""; } response[0] += "]"; return SQLITE_OK; } static int sqlite_table_meta(void *data, int argc, char **argv, char **azColName){ string* response = (string*)data; if (response[0].length() > 1) response[0] += ","; response[0] += "\"" + string(argv[1]) + "\""; return SQLITE_OK; } int main(int argc, char** argv) { bool compress = true; string response = ""; if (compress){ cout << "Content-Type: text/html" << endl; cout << "Content-Encoding: deflate" << endl << endl; } else { cout << "Content-Type: text/html" << endl << endl; } // load get values char* get_string_chr = getenv("QUERY_STRING"); if (!get_string_chr){ response += "-1"; print_out(response, compress); return -1; } string get_string = get_string_chr; if (!get_string.length()){ response += "-2"; print_out(response, compress); return -2; } vector<string> get_entries = split(get_string, '&'); map< string, string > form; for (uint i = 0; i < get_entries.size(); ++i){ vector<string> get_value = split(get_entries.at(i), '='); string value = (get_value.size() > 1) ? urlDecode(get_value.at(1)) : ""; form.insert(pair< string, string >(get_value.at(0), value)); } // load parameters from config file map< string, string > parameters; read_config_file("../qsdb.conf", parameters); string action = (form.find("action") != form.end()) ? form["action"] : ""; if (!action.length()){ response += "-4"; print_out(response, compress); return -4; } if (action.compare("get") != 0 && action.compare("set") != 0 && action.compare("insert") != 0){ response += "-5"; print_out(response, compress); return -5; } // retrieve id and peptide sequence from spectral library sqlite3 *db; char *zErrMsg = 0; int rc, chr; string database = parameters["root_path"] + "/data/database.sqlite"; rc = sqlite3_open((char*)database.c_str(), &db); if( rc ){ print_out("[]", compress); exit(-3); } if (!action.compare("set")){ string set_table = (form.find("table") != form.end()) ? form["table"] : ""; string set_id = (form.find("id") != form.end()) ? form["id"] : ""; string set_col = (form.find("column") != form.end()) ? form["column"] : ""; string set_value = (form.find("value") != form.end()) ? form["value"] : ""; if (!is_integer_number(set_id) || !set_table.length() || !set_id.length() || !set_col.length()){ response += "-6"; print_out(response, compress); sqlite3_close(db); return -6; } replaceAll(set_table, "\"", ""); replaceAll(set_table, "'", ""); replaceAll(set_col, "\"", ""); replaceAll(set_col, "'", ""); replaceAll(set_value, "\"", ""); replaceAll(set_value, "'", ""); if (!set_table.compare("nodeproteincorrelations")){ string sql_query = "DELETE npc FROM " + set_table + " npc INNER JOIN proteins p ON p.id = npc.protein_id WHERE npc.node_id = " + set_id + " AND p.species = " + set_col + ";"; rc = sqlite3_exec(db, sql_query.c_str(), NULL, NULL, &zErrMsg); for(string protein_id : split(set_value, ':')){ sql_query = "INSERT INTO " + set_table + "(node_id, protein_id) VALUES(" + set_id + ", " + protein_id + ");"; rc = sqlite3_exec(db, sql_query.c_str(), NULL, NULL, &zErrMsg); } } else if (!set_table.compare("protein_loci")){ string sql_query = "DELETE FROM " + set_table + " WHERE locus_id = " + set_id + ";"; rc = sqlite3_exec(db, sql_query.c_str(), NULL, NULL, &zErrMsg); for(string protein_id : split(set_value, ':')){ sql_query = "INSERT INTO " + set_table + "(locus_id, protein_id) VALUES(" + set_id + ", " + protein_id + ");"; rc = sqlite3_exec(db, sql_query.c_str(), NULL, NULL, &zErrMsg); } } else if (!set_table.compare("images")){ string sql_query = "UPDATE " + set_table + " SET " + set_col + " = '" + set_value + "' WHERE node_id = " + set_id + ";"; rc = sqlite3_exec(db, sql_query.c_str(), NULL, NULL, &zErrMsg); } else { if (!set_table.compare("metabolites") && !set_col.compare("smiles")){ string filepath = parameters["root_path"] + "/admin/scripts"; string command = "java -cp " + filepath + "/cdk-2.0.jar:" + filepath + "/sqlite-jdbc-3.27.2.1.jar:. DrawChem " + set_id + " '" + set_value + "'"; int result = system(command.c_str()); replaceAll(set_value, "\\", "\\\\"); } string sql_query = "UPDATE " + set_table + " SET " + set_col + " = '" + set_value + "' WHERE id = " + set_id + ";"; //cout << sql_query << endl; rc = sqlite3_exec(db, sql_query.c_str(), NULL, NULL, &zErrMsg); } response += "0"; print_out(response, compress); } else if (!action.compare("get")){ string action_type = (form.find("type") != form.end()) ? form["type"] : ""; if (!action_type.length()){ response += "-9"; print_out(response, compress); sqlite3_close(db); return -9; } if (!action_type.compare("pathway_groups") || !action_type.compare("pathways") || !action_type.compare("proteins") || !action_type.compare("tissues") || !action_type.compare("loci_names") || !action_type.compare("function_names") || !action_type.compare("protein_loci") || !action_type.compare("loci_names") || !action_type.compare("species") || !action_type.compare("metabolites")){ string order_col = (form.find("column") != form.end()) ? form["column"] : ""; string limit = (form.find("limit") != form.end()) ? form["limit"] : ""; string filters = (form.find("filters") != form.end()) ? form["filters"] : ""; string checked = (form.find("checked") != form.end()) ? form["checked"] : ""; string sql_query = "SELECT * FROM " + action_type; if (checked.length()){ replaceAll(checked, "\"", ""); replaceAll(checked, "'", ""); sql_query += " INNER JOIN nodeproteincorrelations ON id = protein_id WHERE node_id = " + checked; } if (!action_type.compare("protein_loci")){ sql_query += " INNER JOIN proteins ON id = protein_id "; } if (filters.length()){ replaceAll(filters, "\"", ""); replaceAll(filters, "'", ""); vector<string> tokens = split(filters, 6); for (int i = 0; i < tokens.size(); ++i){ string token = tokens[i]; sql_query += (i == 0 && checked.length() == 0) ? " WHERE" : " AND"; vector<string> tt = split(token, ':'); sql_query += " LOWER(" + tt[0] + ") LIKE '%" + ((tt.size() > 1) ? tt[1] : "") + "%'"; } } if (order_col.length()){ replaceAll(order_col, "\"", ""); replaceAll(order_col, "'", ""); vector<string> tokens = split(order_col, ':'); sql_query += " ORDER BY " + tokens[0]; if (tokens.size() > 1) sql_query += " " + tokens[1]; } if (limit.length()){ replaceAll(limit, "\"", ""); replaceAll(limit, "'", ""); replaceAll(limit, ":", ","); sql_query += " LIMIT " + limit; } sql_query += ";"; string data[] = {""}; if (action_type.compare("protein_loci")){ data[0] = "{"; rc = sqlite3_exec(db, sql_query.c_str(), sqlite_select_protein_loci, (void*)data, &zErrMsg); data[0] += "}"; } else { data[0] = "["; rc = sqlite3_exec(db, sql_query.c_str(), sqlite_select_remaining, (void*)data, &zErrMsg); data[0] += "]"; } response += data[0]; print_out(response, compress); } else if (!action_type.compare("pathway_groups_num") || !action_type.compare("proteins_num") || !action_type.compare("metabolites_num") || !action_type.compare("species_num") || !action_type.compare("tissues_num") || !action_type.compare("loci_names_num") || !action_type.compare("pathways_num")){ replaceAll(action_type, "_num", ""); string sql_query = "SELECT count(*) from " + action_type + ";"; sqlite3_stmt *stmt; sqlite3_prepare_v2(db, sql_query.c_str(), -1, &stmt, 0); int rc = sqlite3_step(stmt); response += (char*)sqlite3_column_text(stmt, 0); sqlite3_reset(stmt); print_out(response, compress); } else if (!action_type.compare("pathway_groups_col") || !action_type.compare("proteins_col") || !action_type.compare("metabolites_col") || !action_type.compare("species_col") || !action_type.compare("tissues_col") || !action_type.compare("loci_names_col") || !action_type.compare("pathways_col")){ replaceAll(action_type, "_col", ""); string sql_query = "PRAGMA table_info('" + action_type + "');"; string data[] = {"["}; rc = sqlite3_exec(db, sql_query.c_str(), sqlite_table_meta, (void*)data, &zErrMsg); data[0] += "]"; response += data[0]; print_out(response, compress); } } else if (!action.compare("insert")){ string species_id = ""; string action_type = (form.find("type") != form.end()) ? form["type"] : ""; if (!action_type.length()){ response += "-4"; print_out(response, compress); sqlite3_close(db); return -4; } if (action_type.compare("pathway_groups") != 0 && action_type.compare("pathways") != 0 && action_type.compare("proteins") != 0 && action_type.compare("metabolites") != 0 && action_type.compare("species") != 0 && action_type.compare("tissues") != 0 && action_type.compare("loci_names") != 0 ){ response += "-5"; print_out(response, compress); sqlite3_close(db); return -5; } string data = (form.find("data") != form.end()) ? form["data"] : ""; if (!data.length()){ response += "-13"; print_out(response, compress); sqlite3_close(db); return -13; } vector<string> data_token = split(data, data_sepatator); string smiles_data = ""; vector< vector<string> > insert_data; for (int i = 0; i < data_token.size(); ++i){ vector<string> row = split(data_token[i], ':'); replaceAll(row[0], "\"", ""); replaceAll(row[0], "'", ""); if (row.size() >= 2){ replaceAll(row[1], "\"", ""); replaceAll(row[1], "'", ""); for (int j = 2; j < row.size(); ++j){ replaceAll(row[j], "\"", ""); replaceAll(row[j], "'", ""); row[1] += ":" + row[j]; } } else row.push_back(""); insert_data.push_back(row); if (!action_type.compare("metabolites") && !row[0].compare("smiles") && row[1].length()) smiles_data = row[1]; } string sql_query = "INSERT INTO " + action_type + " ("; for (int i = 0; i < insert_data.size(); ++i){ if (i) sql_query += ", "; sql_query += insert_data[i][0]; } sql_query += ") VALUES ('"; for (int i = 0; i < insert_data.size(); ++i){ if (i) sql_query += "', '"; if (insert_data[i][0].compare("icon") == 0 && action_type.compare("tissues") == 0){ string icon_img = insert_data[i][1]; while (icon_img.length() & 3) icon_img += "="; replaceAll(icon_img, "_", "/"); replaceAll(icon_img, "-", "+"); sql_query += icon_img; } else if (insert_data[i][0].compare("color") == 0 && action_type.compare("tissues") == 0){ sql_query += "#" + insert_data[i][1]; } else if (insert_data[i][0].compare("ncbi") == 0 && action_type.compare("species") == 0){ species_id = insert_data[i][1]; sql_query += insert_data[i][1]; } else { sql_query += insert_data[i][1]; } } sql_query += "');"; rc = sqlite3_exec(db, sql_query.c_str(), NULL, NULL, &zErrMsg); // create new spectral library if not present if (!action_type.compare("species")){ string filepath = parameters["root_path"] + "/data/spectral_library_" + species_id + ".blib"; ifstream f(filepath.c_str()); if (!f.good()){ f.close(); sqlite3 *db_lib; char *zErrMsg = 0; int rc; rc = sqlite3_open(filepath.c_str(), &db_lib); if( rc ){ print_out("-10", compress); exit(-10); } sqlite3_exec(db_lib, "CREATE TABLE SpectrumSourceFiles(id INTEGER primary key autoincrement not null, fileName TEXT);", NULL, NULL, &zErrMsg); sqlite3_exec(db_lib, "CREATE TABLE ScoreTypes (id INTEGER PRIMARY KEY, scoreType VARCHAR(128), probabilityType VARCHAR(128));", NULL, NULL, &zErrMsg); sqlite3_exec(db_lib, "INSERT INTO `ScoreTypes` (id,scoreType,probabilityType) VALUES (0,'UNKNOWN','NOT_A_PROBABILITY_VALUE'), \ (1,'PERCOLATOR QVALUE','PROBABILITY_THAT_IDENTIFICATION_IS_INCORRECT'), \ (2,'PEPTIDE PROPHET SOMETHING','PROBABILITY_THAT_IDENTIFICATION_IS_CORRECT'), \ (3,'SPECTRUM MILL','NOT_A_PROBABILITY_VALUE'), \ (4,'IDPICKER FDR','PROBABILITY_THAT_IDENTIFICATION_IS_INCORRECT'), \ (5,'MASCOT IONS SCORE','PROBABILITY_THAT_IDENTIFICATION_IS_INCORRECT'), \ (6,'TANDEM EXPECTATION VALUE','PROBABILITY_THAT_IDENTIFICATION_IS_INCORRECT'), \ (7,'PROTEIN PILOT CONFIDENCE','PROBABILITY_THAT_IDENTIFICATION_IS_CORRECT'), \ (8,'SCAFFOLD SOMETHING','PROBABILITY_THAT_IDENTIFICATION_IS_CORRECT'), \ (9,'WATERS MSE PEPTIDE SCORE','NOT_A_PROBABILITY_VALUE'), \ (10,'OMSSA EXPECTATION SCORE','PROBABILITY_THAT_IDENTIFICATION_IS_INCORRECT'), \ (11,'PROTEIN PROSPECTOR EXPECTATION SCORE','PROBABILITY_THAT_IDENTIFICATION_IS_INCORRECT'), \ (12,'SEQUEST XCORR','PROBABILITY_THAT_IDENTIFICATION_IS_INCORRECT'), \ (13,'MAXQUANT SCORE','PROBABILITY_THAT_IDENTIFICATION_IS_INCORRECT'), \ (14,'MORPHEUS SCORE','PROBABILITY_THAT_IDENTIFICATION_IS_INCORRECT'), \ (15,'MSGF+ SCORE','PROBABILITY_THAT_IDENTIFICATION_IS_INCORRECT'), \ (16,'PEAKS CONFIDENCE SCORE','PROBABILITY_THAT_IDENTIFICATION_IS_INCORRECT'), \ (17,'BYONIC SCORE','PROBABILITY_THAT_IDENTIFICATION_IS_INCORRECT'), \ (18,'PEPTIDE SHAKER CONFIDENCE','PROBABILITY_THAT_IDENTIFICATION_IS_CORRECT'), \ (19,'GENERIC Q-VALUE','PROBABILITY_THAT_IDENTIFICATION_IS_INCORRECT');", NULL, NULL, &zErrMsg); sqlite3_exec(db_lib, "CREATE TABLE Tissues(RefSpectraID INTEGER, tissue INTEGER, number INTEGER, PRIMARY KEY (RefSpectraID, tissue))", NULL, NULL, &zErrMsg); sqlite3_exec(db_lib, "CREATE TABLE RetentionTimes(RefSpectraID INTEGER, RedundantRefSpectraID INTEGER, SpectrumSourceID INTEGER, driftTimeMsec REAL, collisionalCrossSectionSqA REAL, driftTimeHighEnergyOffsetMsec REAL, retentionTime REAL, bestSpectrum INTEGER, FOREIGN KEY(RefSpectraID) REFERENCES RefSpectra(id));", NULL, NULL, &zErrMsg); sqlite3_exec(db_lib, "CREATE TABLE RefSpectraPeaks(RefSpectraID INTEGER, peakMZ BLOB, peakIntensity BLOB);", NULL, NULL, &zErrMsg); sqlite3_exec(db_lib, "CREATE TABLE RefSpectraPeakAnnotations (id INTEGER primary key autoincrement not null, RefSpectraID INTEGER not null, peakIndex INTEGER not null, name VARCHAR(256), formula VARCHAR(256),inchiKey VARCHAR(256), otherKeys VARCHAR(256), charge INTEGER, adduct VARCHAR(256), comment VARCHAR(256), mzTheoretical REAL not null,mzObserved REAL not null);", NULL, NULL, &zErrMsg); sqlite3_exec(db_lib, "CREATE TABLE RefSpectra(id INTEGER primary key autoincrement not null, peptideSeq VARCHAR(150), precursorMZ REAL, precursorCharge INTEGER, peptideModSeq VARCHAR(200), prevAA CHAR(1), nextAA CHAR(1), copies INTEGER, numPeaks INTEGER, driftTimeMsec REAL, collisionalCrossSectionSqA REAL, driftTimeHighEnergyOffsetMsec REAL, retentionTime REAL, fileID INTEGER, SpecIDinFile VARCHAR(256), score REAL, scoreType TINYINT, confidence INT);", NULL, NULL, &zErrMsg); sqlite3_exec(db_lib, "CREATE TABLE Modifications (id INTEGER primary key autoincrement not null, RefSpectraID INTEGER, position INTEGER, mass REAL);", NULL, NULL, &zErrMsg); sqlite3_exec(db_lib, "CREATE TABLE LibInfo(libLSID TEXT, createTime TEXT, numSpecs INTEGER, majorVersion INTEGER, minorVersion INTEGER);", NULL, NULL, &zErrMsg); sqlite3_exec(db_lib, "INSERT INTO `LibInfo` (libLSID,createTime,numSpecs,majorVersion,minorVersion) VALUES ('urn:lsid:stamps.isas.de:spectral_library:stamps:nr:spectra','Tue Jul 03 10:43:40 2018',4248,1,7);", NULL, NULL, &zErrMsg); sqlite3_exec(db_lib, "CREATE TABLE IonMobilityTypes (id INTEGER PRIMARY KEY, ionMobilityType VARCHAR(128) );", NULL, NULL, &zErrMsg); sqlite3_exec(db_lib, "INSERT INTO `IonMobilityTypes` (id,ionMobilityType) VALUES (0,'none'), \ (1,'driftTime(msec)'), \ (2,'inverseK0(Vsec/cm^2)');", NULL, NULL, &zErrMsg); sqlite3_exec(db_lib, "CREATE INDEX idxRefIdPeaks ON RefSpectraPeaks (RefSpectraID);", NULL, NULL, &zErrMsg); sqlite3_exec(db_lib, "CREATE INDEX idxRefIdPeakAnnotations ON RefSpectraPeakAnnotations (RefSpectraID);", NULL, NULL, &zErrMsg); sqlite3_exec(db_lib, "CREATE INDEX idxPeptideMod ON RefSpectra (peptideModSeq, precursorCharge);", NULL, NULL, &zErrMsg); sqlite3_exec(db_lib, "CREATE INDEX idxPeptide ON RefSpectra (peptideSeq, precursorCharge);", NULL, NULL, &zErrMsg); sqlite3_mutex_enter(sqlite3_db_mutex(db_lib)); sqlite3_exec(db_lib, "PRAGMA synchronous=OFF", NULL, NULL, &zErrMsg); sqlite3_exec(db_lib, "PRAGMA count_changes=OFF", NULL, NULL, &zErrMsg); sqlite3_exec(db_lib, "PRAGMA journal_mode=MEMORY", NULL, NULL, &zErrMsg); sqlite3_exec(db_lib, "PRAGMA temp_store=MEMORY", NULL, NULL, &zErrMsg); sqlite3_mutex_leave(sqlite3_db_mutex(db_lib)); sqlite3_close(db_lib); } else { f.close(); } } else if (!action_type.compare("metabolites")){ sql_query = "SELECT max(id) max_id FROM metabolites;"; sqlite3_stmt *stmt; sqlite3_prepare_v2(db, sql_query.c_str(), -1, &stmt, 0); int rc = sqlite3_step(stmt); string metabolite_id = (char*)sqlite3_column_text(stmt, 0); sqlite3_reset(stmt); string filepath = parameters["root_path"] + "/admin/scripts"; string command = "java -cp " + filepath + "/cdk-2.0.jar:" + filepath + "/sqlite-jdbc-3.27.2.1.jar:. DrawChem " + metabolite_id + " '" + smiles_data + "'"; int result = system(command.c_str()); } if (!action_type.compare("pathways")){ string sql_query = "SELECT max(id) from " + action_type + ";"; sqlite3_stmt *stmt; sqlite3_prepare_v2(db, sql_query.c_str(), -1, &stmt, 0); int rc = sqlite3_step(stmt); response += (char*)sqlite3_column_text(stmt, 0); sqlite3_reset(stmt); } else { response += "0"; } print_out(response, compress); } sqlite3_close(db); return 0; }
43.443609
495
0.529552
[ "vector" ]
3815ca5af4794e2c5efd1d6a9f7b413903dfd479
11,142
hpp
C++
__drivers/gv_renderer_bgfx/gv_bgfx_app.hpp
dragonsn/gv_game_engine
dca6c1fb1f8d96e9a244f157a63f8a69da084b0f
[ "MIT" ]
2
2018-12-03T13:17:31.000Z
2020-04-08T07:00:02.000Z
__drivers/gv_renderer_bgfx/gv_bgfx_app.hpp
dragonsn/gv_game_engine
dca6c1fb1f8d96e9a244f157a63f8a69da084b0f
[ "MIT" ]
null
null
null
__drivers/gv_renderer_bgfx/gv_bgfx_app.hpp
dragonsn/gv_game_engine
dca6c1fb1f8d96e9a244f157a63f8a69da084b0f
[ "MIT" ]
null
null
null
//#include <bx/uint32_t.h> //this is a fork from bgfx sample ; #define BGFX_MAX_GPU_SKIN_BONE_NUMBER 64 namespace bgfx_debug_cube { struct PosColorVertex { float m_x; float m_y; float m_z; uint32_t m_abgr; static void init() { ms_decl .begin() .add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float) .add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true) .end(); }; static bgfx::VertexDecl ms_decl; }; bgfx::VertexDecl PosColorVertex::ms_decl; static PosColorVertex s_cubeVertices[] = { {-1.0f, 1.0f, 1.0f, 0xff000000 }, { 1.0f, 1.0f, 1.0f, 0xff0000ff }, {-1.0f, -1.0f, 1.0f, 0xff00ff00 }, { 1.0f, -1.0f, 1.0f, 0xff00ffff }, {-1.0f, 1.0f, -1.0f, 0xffff0000 }, { 1.0f, 1.0f, -1.0f, 0xffff00ff }, {-1.0f, -1.0f, -1.0f, 0xffffff00 }, { 1.0f, -1.0f, -1.0f, 0xffffffff }, }; static const uint16_t s_cubeTriList[] = { 0, 1, 2, // 0 1, 3, 2, 4, 6, 5, // 2 5, 6, 7, 0, 2, 4, // 4 4, 2, 6, 1, 5, 3, // 6 5, 7, 3, 0, 4, 1, // 8 4, 5, 1, 2, 3, 6, // 10 6, 3, 7, }; bgfx::VertexBufferHandle m_vbh; bgfx::IndexBufferHandle m_ibh; bgfx::ProgramHandle m_program; void init() { // Create vertex stream declaration. PosColorVertex::init(); // Create static vertex buffer. m_vbh = bgfx::createVertexBuffer( // Static data can be passed with bgfx::makeRef bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices)) , PosColorVertex::ms_decl ); m_ibh = bgfx::createIndexBuffer( // Static data can be passed with bgfx::makeRef bgfx::makeRef(s_cubeTriList, sizeof(s_cubeTriList)) ); // Create program from shaders. m_program = loadProgram("vs_default", "fs_default"); } void destroy() { } void paint() { bgfx::IndexBufferHandle ibh = m_ibh; uint64_t state = 0 | BGFX_STATE_WRITE_R | BGFX_STATE_WRITE_G | BGFX_STATE_WRITE_B | BGFX_STATE_WRITE_A | BGFX_STATE_WRITE_Z | BGFX_STATE_DEPTH_TEST_LESS | BGFX_STATE_CULL_CW | BGFX_STATE_MSAA ; // Submit 11x11 cubes. for (uint32_t yy = 0; yy < 11; ++yy) { for (uint32_t xx = 0; xx < 11; ++xx) { float mtx[16]; bx::mtxRotateXY(mtx, xx * 0.21f, yy * 0.37f); mtx[12] = -15.0f + float(xx)*3.0f; mtx[13] = -15.0f + float(yy)*3.0f; mtx[14] = 0.0f; // Set model matrix for rendering. bgfx::setTransform(mtx); // Set vertex and index buffer. bgfx::setVertexBuffer(0, m_vbh); bgfx::setIndexBuffer(ibh); // Set render states. bgfx::setState(state); // Submit primitive for rendering to view 0. bgfx::submit(0, m_program); } } } } gv_bgfx_app::gv_bgfx_app(const char* _name, const char* _description) : entry::AppI(_name, _description) { } void gv_bgfx_app::init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) { Args args(_argc, _argv); m_width = _width; m_height = _height; m_debug = BGFX_DEBUG_TEXT; m_reset = BGFX_RESET_VSYNC; bgfx::Init init; init.type = args.m_type; init.vendorId = args.m_pciId; init.resolution.width = m_width; init.resolution.height = m_height; init.resolution.reset = m_reset; bgfx::init(init); // Enable debug text. bgfx::setDebug(m_debug); // Set view 0 clear state. bgfx::setViewClear(0 , BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH , 0x303030ff , 1.0f , 0 ); imguiCreate(); m_inited = 1;; entry::setCurrentDir(gv_global::framework_config.data_path_root+"/bgfx/"); bgfx_debug_cube::init(); } int gv_bgfx_app::shutdown() { m_inited = 0; imguiDestroy(); // Shutdown bgfx. bgfx::shutdown(); return 0; } void gv_bgfx_app::pre_tick() { m_start_tick_event.wait(); }; void gv_bgfx_app::set_camera() { float at[3] = { 0.0f, 0.0f, 0.0f }; float eye[3] = { 0.0f, 0.0f, -35.0f }; // Set view and projection matrix for view 0. { float view[16]; bx::mtxLookAt(view, eye, at); float proj[16]; bx::mtxProj(proj, 60.0f, float(m_width) / float(m_height), 0.1f, 1000.0f, bgfx::getCaps()->homogeneousDepth); bgfx::setViewTransform(0, view, proj); // Set view 0 default viewport. bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height)); } // This dummy draw call is here to make sure that view 0 is cleared // if no other draw calls are submitted to view 0. bgfx::touch(0); } void gv_bgfx_app::tick() { imguiBeginFrame(m_mouseState.m_mx , m_mouseState.m_my , (m_mouseState.m_buttons[entry::MouseButton::Left] ? IMGUI_MBUT_LEFT : 0) | (m_mouseState.m_buttons[entry::MouseButton::Right] ? IMGUI_MBUT_RIGHT : 0) | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0) , m_mouseState.m_mz , uint16_t(m_width) , uint16_t(m_height) ); showExampleDialog(this); imguiEndFrame(); // Set view 0 default viewport. bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height)); // This dummy draw call is here to make sure that view 0 is cleared // if no other draw calls are submitted to view 0. bgfx::touch(0); // Use debug font to print information about this example. bgfx::dbgTextClear(); bgfx::dbgTextImage( bx::max<uint16_t>(uint16_t(m_width / 2 / 8), 20) - 20 , bx::max<uint16_t>(uint16_t(m_height / 2 / 16), 6) - 6 , 40 , 12 , s_logo , 160 ); bgfx::dbgTextPrintf(0, 1, 0x0f, "Color can be changed with ANSI \x1b[9;me\x1b[10;ms\x1b[11;mc\x1b[12;ma\x1b[13;mp\x1b[14;me\x1b[0m code too."); bgfx::dbgTextPrintf(80, 1, 0x0f, "\x1b[;0m \x1b[;1m \x1b[; 2m \x1b[; 3m \x1b[; 4m \x1b[; 5m \x1b[; 6m \x1b[; 7m \x1b[0m"); bgfx::dbgTextPrintf(80, 2, 0x0f, "\x1b[;8m \x1b[;9m \x1b[;10m \x1b[;11m \x1b[;12m \x1b[;13m \x1b[;14m \x1b[;15m \x1b[0m"); const bgfx::Stats* stats = bgfx::getStats(); bgfx::dbgTextPrintf(0, 2, 0x0f, "Backbuffer %dW x %dH in pixels, debug text %dW x %dH in characters." , stats->width , stats->height , stats->textWidth , stats->textHeight ); set_camera(); for (int i = 0; i < this->m_renderables.size(); i++) { this->render_renderable(m_renderables[i]); } bgfx_debug_cube::paint(); bgfx::frame(); }; void gv_bgfx_app::post_tick() { m_end_tick_event.set(); }; bool gv_bgfx_app::update() { bool ret = false; pre_tick(); if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState)) { //notify gv signal end // Advance to next frame. Rendering thread will be kicked to // process submitted rendering primitives. tick(); ret=true; } post_tick(); return ret; } gv::gv_int gv_bgfx_app::on_event(gv::gv_object_event* pevent) { switch (pevent->m_id) { case gv_object_event_id_render_init: { gv_object_event_render_init* pe =gvt_cast<gv_object_event_render_init>(pevent); GV_ASSERT(pe); //m_window_handle = (void*)pe->window_handle; } break; case gv_object_event_id_render_uninit: { //this->destroy_gameplay3d(); } break; case gv_object_event_id_add_component: { gv_object_event_add_component* pe =gvt_cast<gv_object_event_add_component>(pevent); GV_ASSERT(pe); this->add_renderable(gvt_cast<gv_component>(pe->component)); } break; case gv_object_event_id_remove_component: { gv_object_event_remove_component* pe =gvt_cast<gv_object_event_remove_component>(pevent); GV_ASSERT(pe); this->remove_renderable(pe->component); } break; case gv_object_event_id_render_enable_pass: { gv_object_event_render_enable_pass* pe =gvt_cast<gv_object_event_render_enable_pass>(pevent); GV_ASSERT(pe); // todo this->enable_render_pass( pe->pass); } break; case gv_object_event_id_render_disable_pass: { gv_object_event_render_disable_pass* pe = gvt_cast<gv_object_event_render_disable_pass>(pevent); GV_ASSERT(pe); // todo this->enable_render_pass( pe->pass,false); } break; case gv_object_event_id_render_set_camera: { gv_object_event_render_set_camera* pe = gvt_cast<gv_object_event_render_set_camera>(pevent); GV_ASSERT(pe); this->m_main_camera = gvt_cast<gv_com_camera>(pe->camera); GV_ASSERT(this->m_main_camera); } break; case gv_object_event_id_render_set_ui_manager: { gv_object_event_render_set_ui_manager* pe = gvt_cast<gv_object_event_render_set_ui_manager>(pevent); GV_ASSERT(pe); // todo this->m_ui_mgr=pe->ui_mgr; } break; case gv_object_event_id_render_reload_shader_cache: { //this->m_hook->reloadShaderCache(); } break; } return 1; }; void gv_bgfx_app::add_renderable(gv_component* in_com){ //don't cache if not add to any world if (!in_com || !in_com->get_entity()->get_world() || m_renderables.find(in_com)) { return; } m_renderables.add(in_com); gv_com_graphic* com = gvt_cast<gv_com_graphic>(in_com); if (!com) { return; } //if error in material ,failed. //if (!precache(com->get_material())) return; //if (precache(gvt_cast<gv_com_terrain_roam>(in_com))) return; gv_renderer_bgfx::static_get()->precache_material(com->get_material()); if (precache(gvt_cast<gv_com_static_mesh>(in_com))) return; if (precache(gvt_cast<gv_com_skeletal_mesh>(in_com))) return; } void gv_bgfx_app::remove_renderable(gv_component* pcomponent){ this->m_renderables.remove(pcomponent); } bool gv_bgfx_app::render_renderable(gv_component * pcomponent) { gv_com_static_mesh * pmesh = gvt_cast<gv_com_static_mesh>(pcomponent); if (pmesh) { {//update transform //SN_TEMP TEST; float mtx[16]; bx::mtxRotateXY(mtx, (float)gv_global::time->get_sec_from_start() , 0); mtx[12] = 0; mtx[13] = 0; mtx[14] = 150.0f; // Set model matrix for rendering. bgfx::setTransform(mtx); } gv_material * mat=pmesh->get_material(); gv_static_mesh* mesh_gv = pmesh->get_resource<gv_static_mesh>(); if (!mesh_gv) return false; mesh_gv->get_vb()->get_hardware_cache<gv_vertex_buffer_bgfx> ()->set(); mesh_gv->get_ib()->get_hardware_cache<gv_index_buffer_bgfx>()->set(); //for bgfx ,not support mesh segment,create submeshes!! ..... //if (pmesh->get_material() ) { set_material(pmesh, mat); // bgfx::submit(0, mat->get_effect()->get_hardware_cache<gv_effect_bgfx>()->m_bgfx_program); bgfx::submit(0, bgfx_debug_cube:: m_program); } } return true; }; bool gv_bgfx_app::precache(gv_com_static_mesh* mesh) { gv_renderer_bgfx::static_get()->precache_static_mesh(mesh->m_static_mesh); return true; }; bool gv_bgfx_app::precache(gv_com_skeletal_mesh* mesh) { gv_renderer_bgfx::static_get()->precache_skeletal_mesh(mesh->get_skeletal_mesh()); return true; }; bool gv_bgfx_app::set_material(gv_com_graphic* com, gv_material * mat){ if (mat) { uint64_t state = 0 | BGFX_STATE_WRITE_R | BGFX_STATE_WRITE_G | BGFX_STATE_WRITE_B | BGFX_STATE_WRITE_A | BGFX_STATE_WRITE_Z | BGFX_STATE_DEPTH_TEST_LESS | BGFX_STATE_CULL_CW | BGFX_STATE_MSAA //| BGFX_STATE_PT_TRISTRIP ; //set shader parameter here .. } return true; }; //dummy function , should never be called from entry int32_t _main_(int32_t _argc, char** _argv) { GV_ASSERT(0); return 1; }; ENTRY_IMPLEMENT_MAIN(gv_bgfx_app, "gv_bgfx", "Initialization and debug text.");
24.926174
148
0.678244
[ "mesh", "render", "model", "transform" ]
381aec5007763d3f86ae4a8d8ec345c700517214
4,966
hpp
C++
libs/mockturtle/io/pla_reader.hpp
wjyoumans/staq
d5227bd4651ce64ba277aab5061e3a132be853bb
[ "MIT" ]
96
2019-12-11T10:18:10.000Z
2022-03-27T20:16:33.000Z
libs/mockturtle/io/pla_reader.hpp
wjyoumans/staq
d5227bd4651ce64ba277aab5061e3a132be853bb
[ "MIT" ]
43
2020-01-08T00:59:07.000Z
2022-03-28T21:35:59.000Z
libs/mockturtle/io/pla_reader.hpp
wjyoumans/staq
d5227bd4651ce64ba277aab5061e3a132be853bb
[ "MIT" ]
21
2019-12-15T01:40:48.000Z
2021-12-31T05:27:34.000Z
/* mockturtle: C++ logic network library * Copyright (C) 2018-2019 EPFL * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ /*! \file pla_reader.hpp \brief Lorina reader for PLA files \author Mathias Soeken */ #pragma once #include "../traits.hpp" #include <lorina/pla.hpp> namespace mockturtle { /*! \brief Lorina reader callback for PLA files. * * **Required network functions:** * - `create_pi` * - `create_po` * - `create_not` * - `create_nary_and` * - `create_nary_or` * - `create_nary_xor` * \verbatim embed:rst Example .. code-block:: c++ aig_network aig; lorina::read_pla( "file.pla", pla_reader( aig ) ); mig_network mig; lorina::read_pla( "file.pla", pla_reader( mig ) ); \endverbatim */ template <typename Ntk> class pla_reader : public lorina::pla_reader { public: explicit pla_reader(Ntk& ntk) : _ntk(ntk) { static_assert(is_network_type_v<Ntk>, "Ntk is not a network type"); static_assert(has_create_pi_v<Ntk>, "Ntk does not implement the create_pi function"); static_assert(has_create_po_v<Ntk>, "Ntk does not implement the create_po function"); static_assert(has_create_not_v<Ntk>, "Ntk does not implement the create_not function"); static_assert(has_create_nary_and_v<Ntk>, "Ntk does not implement the create_nary_and function"); static_assert(has_create_nary_or_v<Ntk>, "Ntk does not implement the create_nary_or function"); static_assert(has_create_nary_xor_v<Ntk>, "Ntk does not implement the create_nary_xor function"); } void on_number_of_inputs(std::size_t number_of_inputs) const override { _pis.resize(number_of_inputs); std::generate(_pis.begin(), _pis.end(), [this]() { return _ntk.create_pi(); }); } void on_number_of_outputs(std::size_t number_of_outputs) const override { _products.resize(number_of_outputs); } bool on_keyword(const std::string& keyword, const std::string& value) const override { if (keyword == "type" && value == "esop") { _is_xor = true; return true; } return false; } void on_end() const override { for (auto const& v : _products) { _ntk.create_po(_is_xor ? _ntk.create_nary_xor(v) : _ntk.create_nary_or(v)); } } void on_term(const std::string& term, const std::string& out) const override { std::vector<signal<Ntk>> literals; for (auto i = 0u; i < term.size(); ++i) { switch (term[i]) { default: std::cerr << "[w] unknown character '" << term[i] << "' in PLA input term, treat as don't care\n"; case '-': break; case '0': literals.push_back(_ntk.create_not(_pis[i])); break; case '1': literals.push_back(_pis[i]); break; } } const auto product = _ntk.create_nary_and(literals); for (auto i = 0u; i < out.size(); ++i) { switch (out[i]) { default: std::cerr << "[w] unknown character '" << out[i] << "' in PLA output term, treat is 0\n"; case '0': break; case '1': _products[i].push_back(product); break; } } } private: Ntk& _ntk; mutable std::vector<signal<Ntk>> _pis; mutable std::vector<std::vector<signal<Ntk>>> _products; mutable bool _is_xor{false}; }; } /* namespace mockturtle */
32.671053
78
0.586186
[ "vector" ]
3823c0b75836838d64bdc89743c48b0a0c92dfa5
2,483
cpp
C++
code/components/citizen-scripting-core/src/NativeResourceLogging.cpp
thorium-cfx/fivem
587eb7c12066a2ebf8631bde7bb39ee2df1b5a0c
[ "MIT" ]
5,411
2017-04-14T08:57:56.000Z
2022-03-30T19:35:15.000Z
code/components/citizen-scripting-core/src/NativeResourceLogging.cpp
thorium-cfx/fivem
587eb7c12066a2ebf8631bde7bb39ee2df1b5a0c
[ "MIT" ]
802
2017-04-21T14:18:36.000Z
2022-03-31T21:20:48.000Z
code/components/citizen-scripting-core/src/NativeResourceLogging.cpp
thorium-cfx/fivem
587eb7c12066a2ebf8631bde7bb39ee2df1b5a0c
[ "MIT" ]
2,011
2017-04-14T09:44:15.000Z
2022-03-31T15:40:39.000Z
#include <StdInc.h> #if __has_include("NativeHandlerLogging.h") && defined(ENABLE_NATIVE_HANDLER_LOGGING) #include <HttpClient.h> #include <NativeHandlerLogging.h> #include <Resource.h> #include <ResourceManager.h> #include <unordered_map> #include <unordered_set> #include <json.hpp> static std::unordered_map<std::string, std::unordered_set<uint64_t>> g_nativeLogs; using json = nlohmann::json; static void AsyncUploadNativeLog() { FILE* f = _wfopen(MakeRelativeCitPath(L"cache/native_stats.json").c_str(), L"rb"); if (f) { fseek(f, 0, SEEK_END); size_t size = ftell(f); fseek(f, 0, SEEK_SET); std::vector<char> data(size); fread(data.data(), 1, data.size(), f); fclose(f); _wunlink(MakeRelativeCitPath(L"cache/native_stats.json").c_str()); HttpRequestOptions options; options.headers["content-type"] = "application/json; charset=utf-8"; Instance<HttpClient>::Get()->DoPostRequest("http://native-collector-live.fivem.net/upload", std::string(data.data(), data.size()), options, [](bool success, const char*, size_t) { }); } } static void SerializeNativeLog() { auto jsonMap = json::object(); for (const auto& dataPair : g_nativeLogs) { const auto& [resourceName, set] = dataPair; auto arr = json::array(); for (const auto& native : set) { arr.push_back(json(fmt::sprintf("%016llx", native))); } jsonMap[resourceName] = arr; } FILE* f = _wfopen(MakeRelativeCitPath(L"cache/native_stats.json").c_str(), L"wb"); if (f) { auto str = jsonMap.dump(); fwrite(str.c_str(), 1, str.size(), f); fclose(f); } } static InitFunction initFunction([]() { fx::Resource::OnInitializeInstance.Connect([](fx::Resource* resource) { resource->OnActivate.Connect([resource]() { NativeHandlerLogging::PushLog(std::make_shared<concurrency::concurrent_unordered_set<uint64_t>>()); }, -99999999); resource->OnDeactivate.Connect([resource]() { auto nativeLog = NativeHandlerLogging::PopLog(); if (nativeLog) { auto& outLog = g_nativeLogs[resource->GetName()]; for (const auto& entry : *nativeLog) { outLog.insert(entry); } } }, 99999999); }); fx::ResourceManager::OnInitializeInstance.Connect([](fx::ResourceManager* resourceManager) { AsyncUploadNativeLog(); resourceManager->OnTick.Connect([]() { static uint32_t lastTick; if ((GetTickCount() - lastTick) > 30000) { SerializeNativeLog(); lastTick = GetTickCount(); } }); }); }); #endif
20.691667
179
0.678212
[ "object", "vector" ]
3824dcb3e02e44a7b16b585984fa9818cd7ebdae
20,407
hpp
C++
src/fields/tuple_fwd.hpp
lanl/shoccs
6fd72a612e872df62749eec6b010bd1f1e5ee1e7
[ "BSD-3-Clause" ]
null
null
null
src/fields/tuple_fwd.hpp
lanl/shoccs
6fd72a612e872df62749eec6b010bd1f1e5ee1e7
[ "BSD-3-Clause" ]
2
2022-02-18T22:43:06.000Z
2022-02-18T22:43:19.000Z
src/fields/tuple_fwd.hpp
lanl/shoccs
6fd72a612e872df62749eec6b010bd1f1e5ee1e7
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include "types.hpp" #include <range/v3/range/concepts.hpp> #include <range/v3/view/common.hpp> #include <range/v3/view/view.hpp> #include <boost/mp11.hpp> #include <boost/type_traits/copy_cv_ref.hpp> namespace ccs //::field::tuple { using std::get; using namespace boost::mp11; // Concept for being able to apply vs::all. Need to exclude int3 as // an "Allable" range to trigger proper tuple construction calls template <typename T> concept All = rs::range<T&> && rs::viewable_range<T> && (!std::same_as<int3, std::remove_cvref_t<T>>); // Forward decls for main types template <typename...> struct tuple; // forward decls for component types template <typename...> struct container_tuple; template <typename...> struct view_tuple_base; template <typename...> struct view_tuple; // // container_tuple concepts // template <typename> struct is_container_tuple : std::false_type { }; template <typename... Args> struct is_container_tuple<container_tuple<Args...>> : std::true_type { }; template <typename T> concept ContainerTuple = is_container_tuple<std::remove_cvref_t<T>>::value; // // ViewBase/View Tuples // template <typename> struct is_view_tuple_base : std::false_type { }; template <typename... Args> struct is_view_tuple_base<view_tuple_base<Args...>> : std::true_type { }; template <typename T> concept ViewTupleBase = is_view_tuple_base<std::remove_cvref_t<T>>::value; template <typename> struct is_view_tuple : std::false_type { }; template <typename... Args> struct is_view_tuple<view_tuple<Args...>> : std::true_type { }; template <typename T> concept ViewTuple = is_view_tuple<std::remove_cvref_t<T>>::value; // // Tuple concepts // template <typename> struct is_tuple : std::false_type { }; template <typename... Args> struct is_tuple<tuple<Args...>> : std::true_type { }; template <typename T> concept Tuple = is_tuple<std::remove_cvref_t<T>>::value; // // "Owning" Tuples are those that have the datastructure associated with the view // In the current implementation, Owning Tuples always inherit from container_tuple // namespace detail { template <typename> struct has_container_tuple : std::false_type { }; template <template <typename...> typename T, typename... Args> struct has_container_tuple<T<Args...>> : std::is_base_of<container_tuple<Args...>, T<Args...>> { }; } // namespace detail template <typename T> using is_owning_tuple = detail::has_container_tuple<std::remove_cvref_t<T>>::type; template <typename T> concept OwningTuple = detail::has_container_tuple<std::remove_cvref_t<T>>::value; // // The concepts are supposed to work with all manner of the tuples in the code (i.e. // ViewTuples, ContainerTuples, Tuples, std::tuple, ...). Some of the range-v3 ranges // result in custom range tuples so we have to be strict about what we call tuple_like // namespace detail { template <typename T> struct is_tuple_like_impl : std::false_type { }; template <typename... Args> struct is_tuple_like_impl<std::tuple<Args...>> : std::true_type { }; template <typename... Args> struct is_tuple_like_impl<rs::common_tuple<Args...>> : std::true_type { }; template <template <typename...> typename T, typename... Args> struct is_tuple_like_impl<T<Args...>> : mp_or<std::is_base_of<container_tuple<Args...>, T<Args...>>, std::is_base_of<view_tuple_base<Args...>, T<Args...>>> { }; } // namespace detail template <typename T> using is_tuple_like = detail::is_tuple_like_impl<std::remove_cvref_t<T>>::type; template <typename T> concept TupleLike = is_tuple_like<T>::value; namespace detail { template <typename> struct is_stdarray_impl : std::false_type { }; template <typename T, auto N> struct is_stdarray_impl<std::array<T, N>> : std::true_type { }; } // namespace detail template <typename T> using is_stdarray = detail::is_stdarray_impl<std::remove_cvref_t<T>>::type; template <typename T> concept NumericTuple = is_stdarray<T>::value || (TupleLike<T>&& mp_apply<mp_all, mp_transform_q<mp_compose<std::remove_cvref_t, std::is_arithmetic>, mp_rename<std::remove_reference_t<T>, mp_list>>>::value); template <typename T> concept Non_Owning_Tuple = TupleLike<T> &&(!OwningTuple<T>); template <typename T> concept NonTupleRange = rs::input_range<T> &&(!TupleLike<T>); // // Determine the nesting level of the tuples. Will be needed for smart selections // namespace detail { template <typename T, typename V> struct tuple_levels_impl; } template <typename T, typename V = mp_size_t<0>> using tuple_levels = detail::tuple_levels_impl<T, V>::type; namespace detail { template <typename T, typename V> struct tuple_levels_impl { using type = V; }; template <TupleLike T, auto I> struct tuple_levels_impl<T, mp_size_t<I>> { using type = tuple_levels<mp_first<std::remove_cvref_t<T>>, mp_size_t<I + 1>>; }; } // namespace detail template <typename T> constexpr auto tuple_levels_v = tuple_levels<T>::value; // // Will need index_sequences for the tuple indices // template <typename T> using tuple_seq = std::make_index_sequence<mp_size<std::remove_cvref_t<T>>::value>; // // The Tuples template arguments are non-req qualified versions of the types that // result from using `get` to extract different pieces. This maps the Tuple to an // mp_list of the types produced by applying `get` to access every element // namespace detail { template <typename T, typename I> struct tuple_get_types_impl; template <typename T, auto... Is> struct tuple_get_types_impl<T, std::index_sequence<Is...>> { using type = mp_list<decltype(get<Is>(std::declval<T>()))...>; }; } // namespace detail template <TupleLike T> using tuple_get_types = detail::tuple_get_types_impl<T, tuple_seq<T>>::type; // // concept for nested tuples. Will allow for more intuitive mapping and for_each // template <typename T> concept NestedTuple = TupleLike<T> && mp_apply<mp_all, mp_transform<is_tuple_like, tuple_get_types<T>>>::value; // // need to determine the shape of tuples to make sure we only appy the mp11 function // on similarly shaped tuples to prevent disasters // namespace detail { template <typename> struct tuple_shape_impl; } template <TupleLike T> using tuple_shape = typename detail::tuple_shape_impl<std::remove_cvref_t<T>>::type; namespace detail { template <typename T> struct tuple_shape_impl { using type = mp_list<mp_size<T>>; }; template <NestedTuple T> struct tuple_shape_impl<T> { using type = mp_transform<tuple_shape, mp_apply<mp_list, T>>; }; } // namespace detail template <typename T, typename U> concept SimilarTuples = TupleLike<T> && TupleLike<U> && std::same_as<tuple_shape<T>, tuple_shape<U>>; // // Range concepts // template <typename T> concept Range = rs::input_range<T> &&(!std::same_as<int3, std::remove_cvref_t<T>>); // template <typename T> // concept AnyOutputRange = rs::range<T>&& rs::output_range<T, rs::range_value_t<T>>; // // Trait for OutputRange. Used to constrain self-modify math operations. // These need to be based on type traits so they can be mapped over nested tuples // namespace detail { template <typename Rout, typename Rin> struct is_output_range_impl : std::false_type { }; template <typename Rout, typename Rin> requires rs::range<Rout> && ((rs::range<Rin> && rs::output_range<Rout, rs::range_value_t<Rin>>) || (rs::output_range<Rout, Rin>)) struct is_output_range_impl<Rout, Rin> : std::true_type { }; } // namespace detail template <typename Rout, typename Rin = Rout> using is_output_range = detail::is_output_range_impl<Rout, Rin>::type; template <typename Rout, typename Rin = Rout> concept OutputRange = is_output_range<Rout, Rin>::value; namespace detail { template <typename, typename> struct is_output_tuple_impl; } template <typename Out, typename In> using is_output_tuple = detail::is_output_tuple_impl<Out, In>::type; namespace detail { template <typename Out, typename In> struct is_output_tuple_impl { using type = is_output_range<Out, In>; }; template <TupleLike Out, typename In> struct is_output_tuple_impl<Out, In> { using type = mp_flatten< mp_transform_q<mp_bind_back<is_output_tuple, In>, tuple_get_types<Out>>>; }; template <TupleLike Out, SimilarTuples<Out> In> struct is_output_tuple_impl<Out, In> { using type = mp_flatten< mp_transform<is_output_tuple, tuple_get_types<Out>, tuple_get_types<In>>>; }; } // namespace detail template <typename Out, typename In> concept OutputTuple = TupleLike<Out> && mp_apply<mp_all, is_output_tuple<Out, In>>::value; // // Check that we canconstruct something from a range needed for output ranges and // container // namespace detail { template <typename, typename> struct constructible_from_range_impl { using type = std::false_type; }; template <typename T, NonTupleRange Arg> struct constructible_from_range_impl<T, Arg> { using C = decltype(vs::common(std::declval<Arg>())); using type = std::is_constructible<T, rs::iterator_t<C>, rs::sentinel_t<C>>; }; template <typename T, NonTupleRange Arg> requires rs::common_range<Arg> struct constructible_from_range_impl<T, Arg> { using type = std::is_constructible<T, rs::iterator_t<Arg>, rs::sentinel_t<Arg>>; }; } // namespace detail template <typename T, typename Arg> using is_constructible_from_range = detail::constructible_from_range_impl<T, Arg>::type; template <typename T, typename Arg> concept ConstructibleFromRange = is_constructible_from_range<T, Arg>::value; // // Combine all supported construction methods into a single trait // template <typename T, typename Arg> using is_constructible_from = mp_or<is_constructible_from_range<T, Arg>, std::is_constructible<T, Arg>>; // // Traits for nested construction // namespace detail { template <typename, typename> struct is_tuple_constructible_from_impl; } template <typename T, typename Arg> using is_tuple_constructible_from = detail::is_tuple_constructible_from_impl<T, Arg>::type; namespace detail { template <typename T, typename Arg> struct is_tuple_constructible_from_impl { using type = is_constructible_from<T, Arg>; }; // Note that we can't use tuple_get_types here for T since that adds references via get // which change the constructibility of the components of T template <TupleLike T, TupleLike Arg> requires(mp_size<std::remove_cvref_t<T>>::value == mp_size<std::remove_cvref_t<Arg>>::value) struct is_tuple_constructible_from_impl<T, Arg> { using type = mp_flatten<mp_transform<is_tuple_constructible_from, // tuple_get_types<T>, mp_rename<std::remove_reference_t<T>, mp_list>, tuple_get_types<Arg>>>; }; } // namespace detail template <typename T, typename Arg> concept TupleFromTuple = SimilarTuples<T, Arg> && mp_apply<mp_all, is_tuple_constructible_from<T, Arg>>::value; template <typename Arg, typename T> concept TupleToTuple = TupleFromTuple<T, Arg>; template <typename T, typename Arg> concept ArrayFromTuple = is_stdarray<T>::value && TupleLike<Arg> && mp_apply<mp_all, mp_transform_q<mp_bind_front<std::is_constructible, typename T::value_type>, tuple_get_types<Arg>>>::value; // // traits for invoking functions over tuples // namespace detail { template <typename, typename...> struct is_nested_invocable_impl; } template <typename F, typename... T> using is_nested_invocable = detail::is_nested_invocable_impl<F, T...>::type; namespace detail { template <typename F, typename... Args> struct is_nested_invocable_impl { using type = std::is_invocable<F, Args...>; }; template <typename F, TupleLike... Args> struct is_nested_invocable_impl<F, Args...> { using type = mp_flatten< mp_transform_q<mp_bind_front<is_nested_invocable, F>, tuple_get_types<Args>...>>; }; } // namespace detail // // NestedInvocableOver tests to see if we can recursively drill down to the non-tuple // elements of a nested tuple and apply a given function // template <typename F, typename... T> concept NestedInvocableOver = (NestedTuple<T> && ...) && mp_apply<mp_all, is_nested_invocable<F, T...>>::value; // // Invokable Over tries to apply the Function to each element of the Tuples. // preference is given to NestedInvokable // template <typename F, typename... T> concept InvocableOver = (!NestedInvocableOver<F, T...>)&&(!TupleLike<F>)&&(TupleLike<T>&&...) && mp_same<tuple_seq<T>...>::value&& mp_apply< mp_all, mp_transform_q<mp_bind_front<std::is_invocable, F>, tuple_get_types<T>...>>::value; // // It can be convenient to invoke a Function whose first argument is an mp_size_t<I> // Currently we don't have a use for a nested version // template <typename F, typename... T> concept IndexedInvocableOver = (!TupleLike<F>)&&(!InvocableOver<F, T...>)&&(TupleLike<T>&&...) && mp_same<tuple_seq<T>...>::value&& mp_apply< mp_all, mp_transform_q<mp_bind_front<std::is_invocable, F>, mp_iota<mp_size<mp_front<mp_list<std::remove_cvref_t<T>...>>>>, tuple_get_types<T>...>>::value; // // Invoke a Tuple-of-functions over a tuple // template <typename F, typename... T> concept TupleInvocableOver = TupleLike<F> &&(TupleLike<T>&&...) && mp_same<tuple_seq<F>, tuple_seq<T>...>::value&& mp_apply< mp_all, mp_transform_q<mp_bind_front<std::is_invocable>, tuple_get_types<F>, tuple_get_types<T>...>>::value; namespace detail { template <typename, typename> struct is_pipeable_impl : std::false_type { }; template <typename F, typename T> requires requires(F f, T t) { t | f; } struct is_pipeable_impl<F, T> : std::true_type { }; } // namespace detail template <typename F, typename T> using is_pipeable = detail::is_pipeable_impl<F, T>::type; // // traits for nested pipeables // namespace detail { template <typename, typename> struct is_nested_pipeable_impl; } template <typename F, typename T> using is_nested_pipeable = detail::is_nested_pipeable_impl<F, T>::type; namespace detail { template <typename F, typename T> struct is_nested_pipeable_impl { using type = is_pipeable<F, T>; }; template <typename F, TupleLike T> struct is_nested_pipeable_impl<F, T> { using type = mp_flatten< mp_transform_q<mp_bind_front<is_nested_pipeable, F>, tuple_get_types<T>>>; }; } // namespace detail // // PipeableOver tests for applying operator| to each element of a potentially nested // Tuple. Since the constrained algorithms simply call transform there is no need to make // a distinction here // template <typename F, typename T> concept PipeableOver = TupleLike<T> && mp_apply<mp_all, is_nested_pipeable<F, T>>::value; template <typename F, typename T> concept TuplePipeableOver = TupleLike<T> && TupleLike<F> && mp_same<tuple_seq<F>, tuple_seq<T>>::value && mp_apply<mp_all, mp_transform_q<mp_bind_front<is_pipeable>, tuple_get_types<F>, tuple_get_types<T>>>::value; // // Traits for view_closures and Tuples of view_closures // namespace detail { template <typename T> struct is_view_closure_impl : std::false_type { }; template <typename Fn> struct is_view_closure_impl<vs::view_closure<Fn>> : std::true_type { }; } // namespace detail template <typename T> using is_view_closure = detail::is_view_closure_impl<std::remove_cvref_t<T>>::type; namespace detail { template <typename> struct is_nested_view_closure_impl; } template <typename T> using is_nested_view_closure = detail::is_nested_view_closure_impl<std::remove_cvref_t<T>>::type; namespace detail { template <typename T> struct is_nested_view_closure_impl { using type = mp_list<is_view_closure<T>>; }; template <TupleLike T> struct is_nested_view_closure_impl<T> { using type = mp_flatten<mp_transform<is_nested_view_closure, mp_rename<std::remove_reference_t<T>, mp_list>>>; }; } // namespace detail template <typename T> concept ViewClosure = is_view_closure<T>::value; template <typename T> concept ViewClosures = mp_apply<mp_all, is_nested_view_closure<T>>::value; // // Traits for ref_views - needed to implement intuitive assignment for ViewTuples // namespace detail { template <typename> struct is_ref_view_impl : std::false_type { }; template <typename Rng> struct is_ref_view_impl<rs::ref_view<Rng>> : std::true_type { }; } // namespace detail template <typename R> using is_ref_view = detail::is_ref_view_impl<std::remove_cvref_t<R>>::type; template <typename R> concept RefView = is_ref_view<R>::value; // // traits for being able to assign the components of a tuple // template <typename T, typename U> concept AssignableRefView = TupleLike<T> && mp_apply<mp_all, mp_transform<is_ref_view, tuple_get_types<T>>>::value && (!TupleLike<U>)&&mp_apply< mp_all, mp_transform_q<mp_bind_back<std::is_assignable, U>, mp_rename<std::remove_reference_t<T>, mp_list>>>::value; template <typename T, typename U> concept AssignableDirect = TupleLike<T> &&(!TupleLike<U>)&&mp_apply< mp_all, mp_transform_q<mp_bind_back<std::is_assignable, U>, tuple_get_types<T>>>::value; template <typename T, typename U> concept AssignableDirectTuple = TupleLike<T> && SimilarTuples<T, U> && mp_apply< mp_all, mp_transform<std::is_assignable, tuple_get_types<T>, tuple_get_types<U>>>::value; // // type functions for construct list of types for get based access. Facilitates // selection logic // template <auto... Is> using list_index = mp_list<mp_size_t<Is>...>; namespace detail { template <typename> struct is_list_index_impl : std::false_type { }; template <auto... Is> struct is_list_index_impl<list_index<Is...>> : std::true_type { }; } // namespace detail template <typename T> using is_list_index = detail::is_list_index_impl<T>::type; template <typename T> concept ListIndex = is_list_index<T>::value; namespace detail { template <typename> struct is_list_indices : std::false_type { }; template <typename... T> struct is_list_indices<mp_list<T...>> { using type = mp_apply<mp_all, mp_transform<is_list_index, mp_list<T...>>>; }; } // namespace detail template <typename T> using is_list_indices = detail::is_list_indices<T>::type; template <typename T> concept ListIndices = is_list_indices<T>::value; template <ListIndex L, std::size_t I> constexpr auto index_v = mp_at_c<L, I>::value; namespace detail { template <typename T> struct viewable_range_by_value_impl { using type = T; }; template <All T> struct viewable_range_by_value_impl<T&> { using type = T; }; } // namespace detail template <typename T> using viewable_range_by_value = detail::viewable_range_by_value_impl<T>::type; namespace detail { template <typename> struct underlying_range_impl; } template <typename T> using underlying_range_t = detail::underlying_range_impl<T>::type; namespace detail { template <typename> struct underlying_range_impl { static_assert("No underlying range type for tuple"); }; template <Range R> struct underlying_range_impl<R> { using type = std::remove_cvref_t<R>; }; template <TupleLike T> requires(!Range<T>) struct underlying_range_impl<T> { using type = underlying_range_t<std::remove_cvref_t<mp_first<tuple_get_types<T>>>>; }; } // namespace detail } // namespace ccs // need to specialize this bool inorder for r_tuples to have the correct behavior. // This is somewhat tricky and is hopefully tested by all the "concepts" tests in // r_tuple.t.cpp namespace ranges { template <typename... Args> inline constexpr bool enable_view<ccs::tuple<Args...>> = false; template <ccs::All T> inline constexpr bool enable_view<ccs::tuple<T>> = true; template <ccs::All T> inline constexpr bool enable_view<ccs::view_tuple<T>> = true; } // namespace ranges
28.22545
90
0.705444
[ "shape", "transform" ]
382d9bd9b2f66fa5949d105f5c60c2968efa4717
682
cpp
C++
001_two_sum.cpp
koallen/leetcode-cpp
a2b6dbb9d543f1402773ff259224a1d4e316ce01
[ "MIT" ]
null
null
null
001_two_sum.cpp
koallen/leetcode-cpp
a2b6dbb9d543f1402773ff259224a1d4e316ce01
[ "MIT" ]
null
null
null
001_two_sum.cpp
koallen/leetcode-cpp
a2b6dbb9d543f1402773ff259224a1d4e316ce01
[ "MIT" ]
null
null
null
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> returnVal(2, 0); unordered_map<int, int> numToIndex(nums.size()); for (int i = 0; i < nums.size(); ++i) { numToIndex[nums[i]] = i; } int numNeeded; for (int i = 0; i < nums.size(); ++i) { numNeeded = target - nums[i]; auto it = numToIndex.find(numNeeded); if (it != numToIndex.end() && it->second != i) { returnVal[0] = i; returnVal[1] = it->second; return returnVal; } } return returnVal; } };
28.416667
60
0.456012
[ "vector" ]
3832bb6cc66e2521aea61960e9b25907abd00105
21,409
cpp
C++
10-algorithmic-analysis/readerEx.10.04/main.cpp
heavy3/programming-abstractions
e10eab5fe7d9ca7d7d4cc96551524707214e43a8
[ "MIT" ]
81
2018-11-15T21:23:19.000Z
2022-03-06T09:46:36.000Z
10-algorithmic-analysis/readerEx.10.04/main.cpp
heavy3/programming-abstractions
e10eab5fe7d9ca7d7d4cc96551524707214e43a8
[ "MIT" ]
null
null
null
10-algorithmic-analysis/readerEx.10.04/main.cpp
heavy3/programming-abstractions
e10eab5fe7d9ca7d7d4cc96551524707214e43a8
[ "MIT" ]
41
2018-11-15T21:23:24.000Z
2022-02-24T03:02:26.000Z
// // main.cpp // // This program implements an O(N) algorithm for sorting an integer array // where all the values fall within the range 0 to 9999. // // Suppose you know that all the values in an integer array fall into the // range 0 to 9999. Show that it is possible to write a O(N) algorithm to sort // arrays with this restriction. Implement your algorithm and evaluate its // performance by taking empirical measurements using the strategy outlined in // exercise 3. Explain why the performance of the algorithm is so bad for // small values of N. // // Notes // // My first attempt at mutating the input data to create a sort index // resulted in a mess. Then I backed up and created a linear-ish // sort using the map abstract data type, solving the more general // case of dynamic data range on the input though missing the linear // performance requirement for large N. I then realized the constraint of // a fixed data range in the problem statement implied I should use a fixed // length frequency vector in lieu of the (less performant) map. So // now I'm getting the desired linear behavior for large N. // // For fun, I added a '#define COMPARE_SORTS' to trigger a comparison of // runtimes across my two new sorts (linearSort and mapSort) and my insertion // sort from an earlier problem. // // -------------------------------------------------------------------------- // Attribution: "Programming Abstractions in C++" by Eric Roberts // Chapter 10, Exercise 4 // Stanford University, Autumn Quarter 2012 // http://web.stanford.edu/class/archive/cs/cs106b/cs106b.1136/materials/CS106BX-Reader.pdf // -------------------------------------------------------------------------- // // Created by Glenn Streiff on 5/3/16. // Copyright ยฉ 2016 Glenn Streiff. All rights reserved. // #include <iostream> #include <iomanip> #include <ostream> #include <ctime> #include <cmath> #include "vector.h" #include "random.h" #include "map.h" #include "error.h" using namespace std; //#define DEBUGGING // Uncomment this for more diagnostic info. #define ENABLE_TRIALS // Improve accuracy of runtime calc for small data sets. #define COMPARE_SORTS // Integrate results from multiple sort functions. #ifdef DEBUGGING // Instrument debug output on console. #define SHOW_UNSORTED // Sanity check the data going into the sort fn. #define SHOW_SORTED // Sanity check the data coming from the sort fn. #undef ENABLE_TRIALS // Disable repeated trials when debugging. #endif // Constants const std::string HEADER = "CS106B Programming Abstractions in C++: Ex 10.04\n"; #ifdef COMPARE_SORTS const std::string DETAIL = "Multi-sort runtime comparison for fixed range input: 0 - 9999"; #else const std::string DETAIL = "O(N-ish) sort of integers of known range: 0 - 9999"; #endif const std::string BANNER = HEADER + DETAIL; const int MIN_DATA_VAL = 0; // Limits the minimum value in input data. const int MAX_DATA_VAL = 9999; // Limits the maximum value input data. #if defined(SHOW_UNSORTED) || defined(SHOW_SORTED) const int SMALLISH_DATASET = 25; // In debug mode, these dump to the console. #endif #ifdef ENABLE_TRIALS const int MAX_REPS = 10000; // Number of trials for data set with N = 1. #endif const int MSEC_PER_SEC = 1000; // Convert from seconds to milliseconds. const double PERCENT_SORTED = 0.94; // Percentage of data in sorted order when // creating mostly-sorted input data sets. const double PERCENT_DELTA = 0.03; // Variability relative to MAX_DATA_VAL for // unsorted values in mostly-sorted data. const int MAX_NUM_UNIQUE = MAX_DATA_VAL - MIN_DATA_VAL + 1; // Types enum SimulationT { GET_OVERHEAD, // Don't run the sort. Just calculate simulation overhead. PERFORM_SORT // Perform the sort (includes simulation overhead). }; enum ConditionT { ASCENDING, // Input data already sorted. ASCENDISH, // Input data mostly sorted in ascending order. RANDOMIZE, // Input data randomized. DESCENDING, // Input data reverse sorted. LAST_CONDITION, // Terminate post increment iterator. SKIPPING, // Unable generate data under current constraints. }; typedef void(*pSortFn)(Vector<int>&); struct ResultT { int N; // Size of input data. double timeMsec; // Elasped time to sort input data (factors out overhead). ConditionT cond; // Degree of randomness in generated input data. pSortFn fn; // Function used to sort data. }; typedef Vector<ResultT> Report; // Aggregates results for various sizes of input // Prototypes void insertionSort(Vector<int> & data); void mapSort(Vector<int> & data); void linearSort(Vector<int> & data); ostream & operator<<(ostream & os, const Report & report); ConditionT operator++(ConditionT & cond, int); int getNumTrials(int N); void getInputData(Vector<int> & items, const int N, const ConditionT condition = RANDOMIZE); void runSort(const int N, ResultT & result, const ConditionT cond, void (sortfn)(Vector<int> & data)); double getSortTime(Vector<int> & data, void (sortfn)(Vector<int> & data), SimulationT simType = PERFORM_SORT); ostream & operator<<(ostream & os, const ConditionT cond); ostream & operator<<(ostream & os, pSortFn fn); // Main program int main() { cout << BANNER << endl << endl; Vector<int> N; // Predefined input data sizes. N += 10, 50, 100, 500, 1000, 5000, 10000; Vector<pSortFn> sortFunctions; #ifdef COMPARE_SORTS sortFunctions += linearSort, mapSort, insertionSort; #else sortFunctions += linearSort; #endif for (ConditionT cond = ASCENDING; cond <= DESCENDING; cond++) { Report report; for (int n: N) { ResultT result; // Run sorting function against n-length vector of generated data. // // For small data sets00, this may entail repeating the sort // and computing average elapsed time and correcting for overhead. for (pSortFn sortFunction : sortFunctions) { runSort(n, result, cond, sortFunction); report.add(result); } } cout << report << endl; } return 0; } // // Function: runSort // Usage: runSort(N, &result, RANDOMIZE); // ------------------------------------ // Runs a sorting simulation for an input data set of size N items. // The input data are generated as a side-effect of the simulation. // // Results are reported through a pass-by-reference result record. // // The degree of randomness seen in the input data may be specified // by an optional condition variable. // void runSort(const int N, ResultT & result, const ConditionT cond, void (sortfn)(Vector<int> &)) { if (N > MAX_NUM_UNIQUE && cond != RANDOMIZE) { // Punt if constraints on min and max data value prevent us // from populating the input vector with the desired number // of N values. This run will be marked as 'skipped' in the ouput // report. For example, can't fill a vector of 10,000 numbers // in ascending order if allowable range is 0 - 999. result.cond = SKIPPING; result.N = N; result.timeMsec = 0.0; result.fn = sortfn; return; } Vector<int> data; getInputData(data, N, cond); #ifdef SHOW_UNSORTED if (data.size() <= SMALLISH_DATASET) { cout << "unsorted: " << data << endl; } #endif // Perform the sort and return elapsed time. double totalSecs = getSortTime(data, sortfn, PERFORM_SORT); #ifdef SHOW_SORTED if (data.size() <= SMALLISH_DATASET) { cout << "sorted: " << data << endl; } #endif // Correct for overhead incurred. double overheadSecs = getSortTime(data, sortfn, GET_OVERHEAD); result.timeMsec = (totalSecs - overheadSecs) * double(MSEC_PER_SEC); result.N = data.size(); result.cond = cond; result.fn = sortfn; } // // Function: getSortTime // Usage: elapsedSeconds = getSortTime(&inputData); // elapsedSeconds = getSortTime(&inputData, GET_OVERHEAD); // -------------------------------------------------------------- // Returns the elapsed time in seconds for sorting an input vector. // // Can be configured to return the overhead associated with with // running the simulation over multiple repetitions. // double getSortTime(Vector<int> & data, void (sortfn)(Vector<int> &), SimulationT simType) { int repeat = getNumTrials(data.size()); int repeatSave = repeat; clock_t t0, tN; Vector<int> mutatedData; switch (simType) { case GET_OVERHEAD: { t0 = clock(); // cpu cycles since process started. while (repeat > 0) { --repeat; mutatedData.clear(); mutatedData += data; } tN = clock(); // cpu cycles since process started. } break; case PERFORM_SORT: default: { t0 = clock(); while (repeat > 0) { --repeat; mutatedData.clear(); mutatedData += data; sortfn(mutatedData); } tN = clock(); data.clear(); data += mutatedData; } break; } if (tN < t0) { // Debugging stack corruption makes you do crazy things. error("getSortTime: clock() error. Negative elapsed time. :-/"); } double elapsedCpuClocks = double(tN - t0) / repeatSave; return elapsedCpuClocks / double(CLOCKS_PER_SEC); } // // Function: getNumTrials // Usage: int numRepetitions = getNumTrials(inputdata.size()); // ---------------------------------------------------------------- // Returns a repetition count for looping through multiple runs of identical // but short-lived processing steps. // // Handy for benchmarking under small input data conditions. // // When the constant MAX_REPS = 10000, this routine returns the following // repetitions for the following values of N: // // N = 10 reps = 1000 // N = 50 reps = 200 // N = 100 reps = 100 // N = 500 reps = 20 // N = 1000 reps = 10 // N = 5000 reps = 2 // N = 10000 reps = 1 // N = 50000 reps = 1 // N = 100000 reps = 1 // // For large data sets, we don't need multiple simulation runs, so the // repetition value steps down accordingly. // int getNumTrials(int N) { int numTrials = 1; #ifdef ENABLE_TRIALS if ((N > 0) && (N < MAX_REPS)) numTrials = MAX_REPS / N; #endif return numTrials; } // // Function: getInputData // Usage: getInputData(&data, N); // getInputData(&data, N, DESCENDING); // ------------------------------------------ // Populates a pass-by-reference vector with N integers generated // under client-specified conditions. // // By default, a vector of random integers ranging in value // from MIN_DATA_VAL to MAX_DATA_VAL is returned. // // Under ASCENDING conditions, a sorted-ascending order vector is returned. // Under ASCENDISH conditions, a mostly sorted vector is returned. // Under DESCENDING conditions, a sorted-descending order vector is returned. // void getInputData(Vector<int> & items, const int N, const ConditionT condition){ items.clear(); switch (condition) { case ASCENDING: // pre-sorted for (int n = MIN_DATA_VAL; n <= min(N-1, MAX_DATA_VAL); n++) items.add(n); break; case ASCENDISH: // mostly sorted for (int n = MIN_DATA_VAL; n <= min(N-1, MAX_DATA_VAL); n++) { if (randomChance(PERCENT_SORTED)) { items.add(n); } else { int n_maxrand = n + (PERCENT_DELTA) * (MAX_DATA_VAL); int n_max = (n_maxrand <= MAX_DATA_VAL) ? n_maxrand : MAX_DATA_VAL; items.add(randomInteger(n, n_max)); } } break; case DESCENDING: // reverse sorted for (int n = min(N-1, MAX_DATA_VAL); n >= max(0, MIN_DATA_VAL); n--){ items.add(n); } break; case RANDOMIZE: // random data in random positions within a range default: for (int n = 0; n < N; n++) items.add(randomInteger(MIN_DATA_VAL, MAX_DATA_VAL)); break; } #ifdef DEBUGGING cout << "getInputData() size = " << items.size() << endl; #endif } // Function: linearSort // Usage: linearSort(&data); // ------------------------- // Returns a sorted collection of integers in a pass-by-reference vector. // // Iterate over the input data, using the values as indices into a // (potentially sparse) frequency-of-occurrence vector. // This sorts the data while accounting for duplicate values on the input. // // Repopulate the input vector with sorted data by rediscovering that data // in order within the frequency vector, using an inner loop to // output the correct number of duplicates of a given value. // // Complexity Analysis // ------------------- // Running time is ~ t(2N), or O(N) // Populating the frequency-of-occurrence vector takes runtime of t(N). // Iterating over the intrinsically sorted frequency vector and // overwriting the input vector with sorted data also takes t(N). // // Memory usage is O(C), where C is expected range in value across the input. // // Performance is generally linear for various N-sized data sets. // However, per-item overhead increases for relatively small N since // the frequency vector becomes correspondingly sparse but still requires // full traversal at any N-sized input. // // The capacity of the frequency vector is a function of the expected range in // values on the input (as opposed to the the number of items in the input). void linearSort(Vector<int> & items) { Vector<int> freq(MAX_NUM_UNIQUE, 0); for (int item: items) { // Guard against indexing beyond the bounds of the frequency // vector if some out-of-range input data shows up. // This should probably be an exception once I learn about those. :P if (item >= MAX_NUM_UNIQUE) { ostringstream oss; oss << "(" << item << " >= " << MAX_NUM_UNIQUE << ")"; error("linearSort(): item >= MAX_NUM_UNIQUE " + oss.str()); } freq[item] = freq[item] + 1; }; int si = 0; for (int i = 0; i < MAX_NUM_UNIQUE; i++) { for (int f = 0; f < freq[i]; f++) { // Overwrite input vector with sorted data. items[si++] = i; } } } // // Function: mapSort // Usage: mapSort(&data); // ---------------------- // My stab at an O(n) sort which returns a collection of sorted integers in a // pass-by-reference vector. // // (I'm probably cheating by using the map data type. :P // My earlier attempt to use the input data itself to directly calculate a // proximate sorted index devolved to a freakish mess.) // // The current algorithm iterates over the unsorted input, building a map // of unique data values and their frequency of occurance. // // A subsequent iteration of the map overwrites the unsorted input vector // with sorted items (including any duplicates items). // // Complexity Analysis // ------------------- // If map populating a map is O(N), then building up the frequency // map is also O(N). // // The map traversal is implemented as a double for-loop which, upon // cursory analysis, might suggest O(N^2) operations. However // the inner loop merely iterates over the constant number of duplicates // of a given input value. The total number of operations across // the two loops is still O(N) (um, assuming map traversal is O(N)). // // This yields ~ 2N operations which would still be O(N). // void mapSort(Vector<int> & items) { Map<int, int> freq; // Map item value to item frequency in the input data. for (int item : items) { freq[item] += 1; } // Rely upon map iterator to return items in sorted order. // Use frequency count to drive inner loop. int si = 0; for (int sortedItem : freq) { for (int i = 0; i < freq[sortedItem]; ++i) { items[si++] = sortedItem; } } } // // Function: insertionSort // Usage: insertionSort(&data); // ---------------------------- // Sorts a pass-by-reference vector of integers using Insertion Sort. // // The algorithm partitions the input vector into sorted and unsorted // regions. // // Initially, only the 0th element is considered sorted. // // As the algorithm proceeds, the sorted region at the head of the vector grows // while the unsorted tail becomes vanishingly small. // // An outter loop passes the nearest unsorted item to an inner loop // which flip-flops that item into position within the sorted // region. // // With each iteration of the outter loop, the sorted region grows by one // while the unsorted region deminishes by one. // // Graphically, the agorithm looks like this: // // [ 56 | 25 37 58 95 19 73 30 ] Initial conditions. // \_ sorted // // [ 25 56 | 37 58 95 19 73 30 ] 1st pass // // [ 25 37 56 | 58 95 19 73 30 ] 2nd pass // // Complexity: O(N^2) worst case // ----------------------------- // The outter loop is linearly sensitive to the size of the input vector. // The inner loop is similarly sensitive in the worst case of reverse ordered // input data since unsorted values at the end of the vector are repositioned // to the head of the vector with O(n) operations. This yields and overall // worst case complexity bounded by O(N^2). // // TODO: Optimization // // As the sorted region becomes large, one could employ binary search to // to find the insertion point therein, yielding O(logN) behavior for that // portion of the algorithm over the O(n) flip-flop positioning strategy. // void insertionSort(Vector<int> & items) { for (int u = 1; u < items.size(); u++) { int k = items[u]; int s = u - 1; while (s >= 0 && items[s] > k) { items[s+1] = items[s]; items[s--] = k; } } } // // Operator: << // Usage: cout << report << endl; // ------------------------------ // Displays formatted results from multiple runs of a sort function under // conditions of increasing scale. Input data condition is also reflected. // ostream & operator<<(ostream & os, const Report & report) { int prevN = report[0].N; #ifdef COMPARE_SORTS os << " N | Time (msec) | Input Data | Sort Function" << endl; os << "---------+---------------+--------------------+-------------------" << endl; #else os << " N | Time (msec) | Input Data " << endl; os << "---------+---------------+--------------------" << endl; #endif for (ResultT rec : report) { #ifdef COMPARE_SORTS if (prevN != rec.N) { prevN = rec.N; os << "---------+---------------+--------------------+-------------------" << endl; } #endif os << right; os << setw(7) << rec.N << " |"; os << setw(14) << fixed << setprecision(5) << rec.timeMsec; os << " | " << setw(18) << left << rec.cond; #ifdef COMPARE_SORTS os << " | " << setw(14) << left << rec.fn; #endif os << endl; } return os; } // // Operator: << // Usage: cout << inputConditions << endl; // --------------------------------------- // Displays the string equivalents for the enumerated ConditionT type // which characterizes the input data. // ostream & operator<<(ostream & os, const ConditionT cond) { switch (cond) { case ASCENDING: os << "ascending"; break; case ASCENDISH: os << "mostly ascending"; break; case DESCENDING: os << "descending"; break; case SKIPPING: os << "skipping"; break; case RANDOMIZE: default: os << "random"; break; } return os; } // // Operator: << // Usage: cout << sortfn << endl; // ------------------------------ // Displays the string equivalents for the specified sort function. // ostream & operator<<(ostream & os, pSortFn fn) { if (fn == linearSort) { os << "linearSort"; } else if (fn == mapSort) { os << "mapSort"; } else if (fn == insertionSort) { os << "insertionSort"; } else { os << "unknown"; } return os; } // // Operator: ++ (ConditionT post-increment) // Usage: for (ConditionT cond = ASCENDING; cond <= DESCENDING; cond++) {...} // -------------------------------------------------------------------------- // Defines a post-increment operator for the input data conditioning type, // ConditionT. // ConditionT operator++(ConditionT & cond, int) { ConditionT old = cond; if (cond < LAST_CONDITION) cond = ConditionT(cond + 1); return old; }
34.036566
95
0.599608
[ "vector" ]
3833e728aef3f7058715c909c352e99f62aa976a
10,745
hh
C++
gazebo/physics/Population.hh
hyunoklee/Gazebo
619218c0bb3dc8878b6c4dc2fddf3f7ec1d85497
[ "ECL-2.0", "Apache-2.0" ]
45
2015-07-17T10:14:22.000Z
2022-03-30T19:25:36.000Z
gazebo/physics/Population.hh
hyunoklee/Gazebo
619218c0bb3dc8878b6c4dc2fddf3f7ec1d85497
[ "ECL-2.0", "Apache-2.0" ]
1
2021-04-15T07:14:26.000Z
2021-04-15T07:14:26.000Z
gazebo/physics/Population.hh
hyunoklee/Gazebo
619218c0bb3dc8878b6c4dc2fddf3f7ec1d85497
[ "ECL-2.0", "Apache-2.0" ]
64
2015-04-18T07:10:14.000Z
2022-02-21T13:15:41.000Z
/* * Copyright (C) 2014 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef _GAZEBO_POPULATION_HH_ #define _GAZEBO_POPULATION_HH_ #include <string> #include <vector> #include <boost/shared_ptr.hpp> #include <boost/scoped_ptr.hpp> #include <sdf/sdf.hh> #include "gazebo/common/Console.hh" #include "gazebo/math/Pose.hh" #include "gazebo/math/Vector3.hh" #include "gazebo/physics/World.hh" #include "gazebo/util/system.hh" namespace gazebo { namespace physics { /// \addtogroup gazebo_physics /// \{ /// \brief Forward declaration of the private data class. class PopulationPrivate; /// \brief Stores all the posible parameters that define a population. class GAZEBO_VISIBLE PopulationParams { /// \brief The three side lengths of the box. public: math::Vector3 size; /// \brief Number of rows used when models are distributed as a grid. public: int rows; /// \brief Number of columns used when models are distributed as a grid. public: int cols; /// \brief Distance between models when they are distributed as a grid. public: math::Vector3 step; /// The reference frame of the population's region. public: math::Pose pose; /// \brief Radius of the cylinder's base containing the models. public: double radius; /// \brief Length of the cylinder containing the models. public: double length; /// \brief Name of the model. public: std::string modelName; /// \brief Contains the sdf representation of the model. public: std::string modelSdf; /// \brief Number of models to spawn. public: int modelCount; /// \brief Object distribution. E.g.: random, grid. public: std::string distribution; /// \brief Type region in which the objects will be spawned. E.g.: box. public: std::string region; }; /// \class Population Population.hh physics/physics.hh /// \brief Class that automatically populates an environment with multiple /// objects based on several parameters to define the number of objects, /// shape of the object distribution or type of distribution. class GAZEBO_VISIBLE Population { /// \brief Constructor. Load an sdf file containing a population element. /// \param[in] _sdf SDF parameters. /// \param[in] _world Pointer to the world. public: Population(sdf::ElementPtr _sdf, boost::shared_ptr<World> _world); /// \brief Destructor. public: virtual ~Population(); /// \brief Generate and spawn multiple populations into the world. /// \return True when the populations were successfully spawned or false /// otherwise. public: bool PopulateAll(); /// \brief Generate and spawn one model population into the world. /// \param[in] _population SDF parameter containing the population details /// \return True when the population was successfully spawned or false /// otherwise. private: bool PopulateOne(const sdf::ElementPtr _population); /// \brief Read a value from an SDF element. Before reading the value, it /// checks if the element exists and print an error message if not found. /// \param[in] _sdfElement SDF element containing the value to read. /// \param[in] _element SDF label to read. Ex: "model_count", "min". /// \param[out] _value Requested value. /// \return True if the element was found or false otherwise. private: template<typename T> bool ValueFromSdf( const sdf::ElementPtr &_sdfElement, const std::string &_element, T &_value) { if (_sdfElement->HasElement(_element)) { _value = _sdfElement->Get<T>(_element); return true; } gzerr << "Unable to find <" << _element << "> inside the population tag" << std::endl; return false; } /// \brief Get a requested SDF element from a SDF. Before returning, it /// checks if the element exists and print an error message if not found. /// \param[in] _sdfElement SDF element containing the requested SDF. /// \param[in] _element SDF label to read. Ex: "model", "box". /// \param[out] _value Requested SDF element. /// \return True if the element was found or false otherwise. private: bool ElementFromSdf(const sdf::ElementPtr &_sdfElement, const std::string &_element, sdf::ElementPtr &_value); /// \brief Parse the sdf file. Some of the output parameters should be /// ignored depending on the region's population. For example, if the /// region is a box, the parameters '_center', 'radius', and 'height' /// should not be used. /// \param[in] _population SDF element containing the Population /// description. /// \param[out] _params Population parameters parsed from the SDF. /// \return True when the function succeed or false otherwise. private: bool ParseSdf(sdf::ElementPtr _population, PopulationParams &_params); /// \brief Populate a vector of poses with '_modelCount' elements, /// randomly distributed within a box. /// \param[in] _modelCount Number of poses. /// \param[in] _min Minimum corner of the box containing the models. /// \param[in] _max Maximum corner of the box containing the models. /// \param[out] _poses Vector containing the poses that will be used to /// populate models. private: void CreatePosesBoxRandom(const PopulationParams &_populParams, std::vector<math::Vector3> &_poses); /// \brief Populate a vector of poses with '_modelCount' elements, /// uniformly distributed within a box. We use k-means to split the /// box in similar subregions. /// \param[in] _modelCount Number of poses. /// \param[in] _min Minimum corner of the box containing the models. /// \param[in] _max Maximum corner of the box containing the models. /// \param[out] _poses Vector containing the poses that will be used to /// populate models. private: void CreatePosesBoxUniform(const PopulationParams &_populParams, std::vector<math::Vector3> &_poses); /// \brief Populate a vector of poses evenly placed in a 2D grid pattern. /// \param[in] _min Minimum corner of the box containing the models. /// \param[in] _rows Number of rows used when the models are /// distributed as a 2D grid. /// \param[in] _cols Number of columns used when the models are /// distributed as a 2D grid. /// \param[in] _step Distance between the models when the objects are /// distributed as a 2D grid. /// \param[out] _poses Vector containing the poses that will be used to /// populate models. private: void CreatePosesBoxGrid(const PopulationParams &_populParams, std::vector<math::Vector3> &_poses); /// \brief Populate a vector of poses with '_modelCount' elements, /// evenly placed in a row along the global x-axis. /// \param[in] _modelCount Number of poses. /// \param[in] _min Minimum corner of the box containing the models. /// \param[in] _max Maximum corner of the box containing the models. /// \param[out] _poses Vector containing the poses that will be used to /// populate models. private: void CreatePosesBoxLinearX(const PopulationParams &_populParams, std::vector<math::Vector3> &_poses); /// \brief Populate a vector of poses with '_modelCount' elements, /// evenly placed in a row along the global y-axis. /// \param[in] _modelCount Number of poses. /// \param[in] _min Minimum corner of the box containing the models. /// \param[in] _max Maximum corner of the box containing the models. /// \param[out] _poses Vector containing the poses that will be used to /// populate models. private: void CreatePosesBoxLinearY(const PopulationParams &_populParams, std::vector<math::Vector3> &_poses); /// \brief Populate a vector of poses with '_modelCount' elements, /// evenly placed in a row along the global z-axis. /// \param[in] _modelCount Number of poses. /// \param[in] _min Minimum corner of the box containing the models. /// \param[in] _max Maximum corner of the box containing the models. /// \param[out] _poses Vector containing the poses that will be used to /// populate models. private: void CreatePosesBoxLinearZ(const PopulationParams &_populParams, std::vector<math::Vector3> &_poses); /// \brief Populate a vector of poses with '_modelCount' elements, /// randomly distributed within a cylinder. /// \param[in] _modelCount Number of poses. /// \param[in] _center Center of the cylinder's base containing /// the models. /// \param[in] _radius Radius of the cylinder's base containing /// the models /// \param[in] _height Height of the cylinder containing the models. /// \param[out] _poses Vector containing the poses that will be used to /// populate models. private: void CreatePosesCylinderRandom( const PopulationParams &_populParams, std::vector<math::Vector3> &_poses); /// \brief Populate a vector of poses with '_modelCount' elements, /// uniformly distributed within a cylinder. We use k-means to split the /// cylinder in similar subregions. /// \param[in] _modelCount Number of poses. /// \param[in] _center Center of the cylinder's base containing /// the models. /// \param[in] _radius Radius of the cylinder's base containing /// the models /// \param[in] _height Height of the cylinder containing the models. /// \param[out] _poses Vector containing the poses that will be used to /// populate models. private: void CreatePosesCylinderUniform( const PopulationParams &_populParams, std::vector<math::Vector3> &_poses); /// \internal /// \brief Pointer to private data. private: boost::scoped_ptr<PopulationPrivate> dataPtr; }; /// \} } } #endif
43.502024
80
0.668683
[ "object", "shape", "vector", "model" ]
383869be586762977926680f8801d3e28c1f07f7
7,033
cc
C++
src/theia/image/image_canvas.cc
nuernber/Theia
4bac771b09458a46c44619afa89498a13cd39999
[ "BSD-3-Clause" ]
1
2021-02-02T13:30:52.000Z
2021-02-02T13:30:52.000Z
src/theia/image/image_canvas.cc
nuernber/Theia
4bac771b09458a46c44619afa89498a13cd39999
[ "BSD-3-Clause" ]
null
null
null
src/theia/image/image_canvas.cc
nuernber/Theia
4bac771b09458a46c44619afa89498a13cd39999
[ "BSD-3-Clause" ]
1
2020-09-28T08:43:13.000Z
2020-09-28T08:43:13.000Z
// Copyright (C) 2013 The Regents of the University of California (Regents). // 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 Regents or University of California nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Please contact the author of this library if you have any questions. // Author: Chris Sweeney (cmsweeney@cs.ucsb.edu) #include "theia/image/image_canvas.h" #include <cvd/draw.h> #include <glog/logging.h> #include <cmath> #include <string> #include <vector> #include "theia/image/image.h" #include "theia/image/keypoint_detector/keypoint.h" #define _USE_MATH_DEFINES namespace theia { // Add an image to the canvas such that all the images that have been added // are now side-by-side on the canvas. This is useful for feature matching. int ImageCanvas::AddImage(const GrayImage& image) { RGBImage rgb_img(image.ConvertTo<RGBPixel>()); return AddImage(rgb_img); } int ImageCanvas::AddImage(const RGBImage& image) { if (pixel_offsets_.size() == 0) { image_ = image.GetCVDImage().copy_from_me(); pixel_offsets_.push_back(0); } else { pixel_offsets_.push_back(image_.size().x); CVD::Image<RGBPixel> image_copy = image_.copy_from_me(); CVD::joinImages(image_copy, image.GetCVDImage(), image_); } return pixel_offsets_.size() - 1; } // Draw a circle in the image at image_index. void ImageCanvas::DrawCircle(int image_index, int x, int y, int radius, const RGBPixel& color) { CHECK_GT(pixel_offsets_.size(), image_index) << "Trying to draw in an image index that does not exist!"; DrawCircle(pixel_offsets_[image_index] + x, y, radius, color); } // Draw a circle onto the canvas. void ImageCanvas::DrawCircle(int x, int y, int radius, const RGBPixel& color) { std::vector<CVD::ImageRef> circle_pixels = CVD::getCircle(radius); CVD::drawShape(image_, CVD::ImageRef(x, y), circle_pixels, color); } // Draw a line in the image at image_index. void ImageCanvas::DrawLine(int image_index, int x1, int y1, int x2, int y2, const RGBPixel& color) { CHECK_GT(pixel_offsets_.size(), image_index) << "Trying to draw in an image index that does not exist!"; DrawLine(pixel_offsets_[image_index] + x1, y1, pixel_offsets_[image_index] + x2, y2, color); } void ImageCanvas::DrawLine(int image_index1, int x1, int y1, int image_index2, int x2, int y2, const RGBPixel& color) { DrawLine(pixel_offsets_[image_index1] + x1, y1, pixel_offsets_[image_index2] + x2, y2, color); } // Draw a line onto the image canvas. void ImageCanvas::DrawLine(int x1, int y1, int x2, int y2, const RGBPixel& color) { CVD::drawLine(image_, x1, y1, x2, y2, color); } // Draw a cross in the image at image_index. void ImageCanvas::DrawCross(int image_index, int x, int y, int length, const RGBPixel& color) { CHECK_GT(pixel_offsets_.size(), image_index) << "Trying to draw in an image index that does not exist!"; DrawCross(pixel_offsets_[image_index] + x, y, length, color); } // Draw a cross onto the image canvas. void ImageCanvas::DrawCross(int x, int y, int length, const RGBPixel& color) { CVD::drawCross(image_, CVD::ImageRef(x, y), length, color); } // Draw a box in the image at image_index. void ImageCanvas::DrawBox(int image_index, int x, int y, int x_length, int y_length, const RGBPixel& color) { CHECK_GT(pixel_offsets_.size(), image_index) << "Trying to draw in an image index that does not exist!"; DrawBox(pixel_offsets_[image_index] + x, y, x_length, y_length, color); } // Draw a box onto the image canvas. void ImageCanvas::DrawBox(int x, int y, int x_length, int y_length, const RGBPixel& color) { CVD::drawBox(image_, CVD::ImageRef(x, y), CVD::ImageRef(x + x_length, y + y_length), color); } void ImageCanvas::DrawFeature(int image_index, int x, int y, int radius, double orientation, const RGBPixel& color) { CHECK_GT(pixel_offsets_.size(), image_index) << "Trying to draw in an image index that does not exist!"; // Draw circle at keypoint with size scale*strength. DrawCircle(image_index, x, y, radius, color); // Draw line in direction of the orientation if applicable. DrawLine(image_index, x, y, x + radius*cos(orientation), y + radius*sin(orientation), color); } // Write the image canvas to a file. void ImageCanvas::Write(const std::string& output_name) { CVD::img_save(image_, output_name); } template <> void ImageCanvas::DrawFeature(int image_index, const Keypoint& feature, const RGBPixel& color, double scale) { double radius = feature.has_strength() ? feature.strength() * scale : scale; double angle = feature.has_orientation() ? feature.orientation() : 0.0; DrawFeature(image_index, feature.x(), feature.y(), radius, angle, color); } template <> void ImageCanvas::DrawFeature<Eigen::Vector2d>(int image_index, const Eigen::Vector2d& feature, const RGBPixel& color, double scale) { double radius = scale; double angle = 0.0; DrawFeature(image_index, feature.x(), feature.y(), radius, angle, color); } } // namespace theia
40.653179
79
0.66842
[ "vector" ]
383b08124c768f72bc8ccf760180c1e337de5941
14,333
cpp
C++
build/moc/moc_ESP8266ComponentController.cpp
UNIST-ESCL/UNIST_GCS
f61f0c12bbb028869e4494f507ea8ab52c8c79c2
[ "Apache-2.0" ]
1
2018-11-07T06:10:53.000Z
2018-11-07T06:10:53.000Z
build/moc/moc_ESP8266ComponentController.cpp
UNIST-ESCL/UNIST_GCS
f61f0c12bbb028869e4494f507ea8ab52c8c79c2
[ "Apache-2.0" ]
null
null
null
build/moc/moc_ESP8266ComponentController.cpp
UNIST-ESCL/UNIST_GCS
f61f0c12bbb028869e4494f507ea8ab52c8c79c2
[ "Apache-2.0" ]
1
2018-11-07T06:10:47.000Z
2018-11-07T06:10:47.000Z
/**************************************************************************** ** Meta object code from reading C++ file 'ESP8266ComponentController.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.9.3) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../src/AutoPilotPlugins/Common/ESP8266ComponentController.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'ESP8266ComponentController.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.9.3. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_ESP8266ComponentController_t { QByteArrayData data[35]; char stringdata0[451]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_ESP8266ComponentController_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_ESP8266ComponentController_t qt_meta_stringdata_ESP8266ComponentController = { { QT_MOC_LITERAL(0, 0, 26), // "ESP8266ComponentController" QT_MOC_LITERAL(1, 27, 14), // "versionChanged" QT_MOC_LITERAL(2, 42, 0), // "" QT_MOC_LITERAL(3, 43, 15), // "wifiSSIDChanged" QT_MOC_LITERAL(4, 59, 19), // "wifiPasswordChanged" QT_MOC_LITERAL(5, 79, 18), // "wifiSSIDStaChanged" QT_MOC_LITERAL(6, 98, 22), // "wifiPasswordStaChanged" QT_MOC_LITERAL(7, 121, 16), // "baudIndexChanged" QT_MOC_LITERAL(8, 138, 11), // "busyChanged" QT_MOC_LITERAL(9, 150, 17), // "_mavCommandResult" QT_MOC_LITERAL(10, 168, 9), // "vehicleId" QT_MOC_LITERAL(11, 178, 9), // "component" QT_MOC_LITERAL(12, 188, 7), // "command" QT_MOC_LITERAL(13, 196, 6), // "result" QT_MOC_LITERAL(14, 203, 20), // "noReponseFromVehicle" QT_MOC_LITERAL(15, 224, 12), // "_ssidChanged" QT_MOC_LITERAL(16, 237, 5), // "value" QT_MOC_LITERAL(17, 243, 16), // "_passwordChanged" QT_MOC_LITERAL(18, 260, 12), // "_baudChanged" QT_MOC_LITERAL(19, 273, 15), // "_versionChanged" QT_MOC_LITERAL(20, 289, 15), // "restoreDefaults" QT_MOC_LITERAL(21, 305, 6), // "reboot" QT_MOC_LITERAL(22, 312, 11), // "componentID" QT_MOC_LITERAL(23, 324, 7), // "version" QT_MOC_LITERAL(24, 332, 13), // "wifiIPAddress" QT_MOC_LITERAL(25, 346, 8), // "wifiSSID" QT_MOC_LITERAL(26, 355, 12), // "wifiPassword" QT_MOC_LITERAL(27, 368, 11), // "wifiSSIDSta" QT_MOC_LITERAL(28, 380, 15), // "wifiPasswordSta" QT_MOC_LITERAL(29, 396, 12), // "wifiChannels" QT_MOC_LITERAL(30, 409, 9), // "baudRates" QT_MOC_LITERAL(31, 419, 9), // "baudIndex" QT_MOC_LITERAL(32, 429, 4), // "busy" QT_MOC_LITERAL(33, 434, 7), // "vehicle" QT_MOC_LITERAL(34, 442, 8) // "Vehicle*" }, "ESP8266ComponentController\0versionChanged\0" "\0wifiSSIDChanged\0wifiPasswordChanged\0" "wifiSSIDStaChanged\0wifiPasswordStaChanged\0" "baudIndexChanged\0busyChanged\0" "_mavCommandResult\0vehicleId\0component\0" "command\0result\0noReponseFromVehicle\0" "_ssidChanged\0value\0_passwordChanged\0" "_baudChanged\0_versionChanged\0" "restoreDefaults\0reboot\0componentID\0" "version\0wifiIPAddress\0wifiSSID\0" "wifiPassword\0wifiSSIDSta\0wifiPasswordSta\0" "wifiChannels\0baudRates\0baudIndex\0busy\0" "vehicle\0Vehicle*" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_ESP8266ComponentController[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 14, 14, // methods 12, 116, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 7, // signalCount // signals: name, argc, parameters, tag, flags 1, 0, 84, 2, 0x06 /* Public */, 3, 0, 85, 2, 0x06 /* Public */, 4, 0, 86, 2, 0x06 /* Public */, 5, 0, 87, 2, 0x06 /* Public */, 6, 0, 88, 2, 0x06 /* Public */, 7, 0, 89, 2, 0x06 /* Public */, 8, 0, 90, 2, 0x06 /* Public */, // slots: name, argc, parameters, tag, flags 9, 5, 91, 2, 0x08 /* Private */, 15, 1, 102, 2, 0x08 /* Private */, 17, 1, 105, 2, 0x08 /* Private */, 18, 1, 108, 2, 0x08 /* Private */, 19, 1, 111, 2, 0x08 /* Private */, // methods: name, argc, parameters, tag, flags 20, 0, 114, 2, 0x02 /* Public */, 21, 0, 115, 2, 0x02 /* Public */, // signals: parameters QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, // slots: parameters QMetaType::Void, QMetaType::Int, QMetaType::Int, QMetaType::Int, QMetaType::Int, QMetaType::Bool, 10, 11, 12, 13, 14, QMetaType::Void, QMetaType::QVariant, 16, QMetaType::Void, QMetaType::QVariant, 16, QMetaType::Void, QMetaType::QVariant, 16, QMetaType::Void, QMetaType::QVariant, 16, // methods: parameters QMetaType::Void, QMetaType::Void, // properties: name, type, flags 22, QMetaType::Int, 0x00095401, 23, QMetaType::QString, 0x00495001, 24, QMetaType::QString, 0x00095401, 25, QMetaType::QString, 0x00495103, 26, QMetaType::QString, 0x00495103, 27, QMetaType::QString, 0x00495103, 28, QMetaType::QString, 0x00495103, 29, QMetaType::QStringList, 0x00095401, 30, QMetaType::QStringList, 0x00095401, 31, QMetaType::Int, 0x00495103, 32, QMetaType::Bool, 0x00495001, 33, 0x80000000 | 34, 0x00095409, // properties: notify_signal_id 0, 0, 0, 1, 2, 3, 4, 0, 0, 5, 6, 0, 0 // eod }; void ESP8266ComponentController::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { ESP8266ComponentController *_t = static_cast<ESP8266ComponentController *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->versionChanged(); break; case 1: _t->wifiSSIDChanged(); break; case 2: _t->wifiPasswordChanged(); break; case 3: _t->wifiSSIDStaChanged(); break; case 4: _t->wifiPasswordStaChanged(); break; case 5: _t->baudIndexChanged(); break; case 6: _t->busyChanged(); break; case 7: _t->_mavCommandResult((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< int(*)>(_a[3])),(*reinterpret_cast< int(*)>(_a[4])),(*reinterpret_cast< bool(*)>(_a[5]))); break; case 8: _t->_ssidChanged((*reinterpret_cast< QVariant(*)>(_a[1]))); break; case 9: _t->_passwordChanged((*reinterpret_cast< QVariant(*)>(_a[1]))); break; case 10: _t->_baudChanged((*reinterpret_cast< QVariant(*)>(_a[1]))); break; case 11: _t->_versionChanged((*reinterpret_cast< QVariant(*)>(_a[1]))); break; case 12: _t->restoreDefaults(); break; case 13: _t->reboot(); break; default: ; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast<int *>(_a[0]); { typedef void (ESP8266ComponentController::*_t)(); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ESP8266ComponentController::versionChanged)) { *result = 0; return; } } { typedef void (ESP8266ComponentController::*_t)(); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ESP8266ComponentController::wifiSSIDChanged)) { *result = 1; return; } } { typedef void (ESP8266ComponentController::*_t)(); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ESP8266ComponentController::wifiPasswordChanged)) { *result = 2; return; } } { typedef void (ESP8266ComponentController::*_t)(); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ESP8266ComponentController::wifiSSIDStaChanged)) { *result = 3; return; } } { typedef void (ESP8266ComponentController::*_t)(); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ESP8266ComponentController::wifiPasswordStaChanged)) { *result = 4; return; } } { typedef void (ESP8266ComponentController::*_t)(); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ESP8266ComponentController::baudIndexChanged)) { *result = 5; return; } } { typedef void (ESP8266ComponentController::*_t)(); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ESP8266ComponentController::busyChanged)) { *result = 6; return; } } } else if (_c == QMetaObject::RegisterPropertyMetaType) { switch (_id) { default: *reinterpret_cast<int*>(_a[0]) = -1; break; case 11: *reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< Vehicle* >(); break; } } #ifndef QT_NO_PROPERTIES else if (_c == QMetaObject::ReadProperty) { ESP8266ComponentController *_t = static_cast<ESP8266ComponentController *>(_o); Q_UNUSED(_t) void *_v = _a[0]; switch (_id) { case 0: *reinterpret_cast< int*>(_v) = _t->componentID(); break; case 1: *reinterpret_cast< QString*>(_v) = _t->version(); break; case 2: *reinterpret_cast< QString*>(_v) = _t->wifiIPAddress(); break; case 3: *reinterpret_cast< QString*>(_v) = _t->wifiSSID(); break; case 4: *reinterpret_cast< QString*>(_v) = _t->wifiPassword(); break; case 5: *reinterpret_cast< QString*>(_v) = _t->wifiSSIDSta(); break; case 6: *reinterpret_cast< QString*>(_v) = _t->wifiPasswordSta(); break; case 7: *reinterpret_cast< QStringList*>(_v) = _t->wifiChannels(); break; case 8: *reinterpret_cast< QStringList*>(_v) = _t->baudRates(); break; case 9: *reinterpret_cast< int*>(_v) = _t->baudIndex(); break; case 10: *reinterpret_cast< bool*>(_v) = _t->busy(); break; case 11: *reinterpret_cast< Vehicle**>(_v) = _t->vehicle(); break; default: break; } } else if (_c == QMetaObject::WriteProperty) { ESP8266ComponentController *_t = static_cast<ESP8266ComponentController *>(_o); Q_UNUSED(_t) void *_v = _a[0]; switch (_id) { case 3: _t->setWifiSSID(*reinterpret_cast< QString*>(_v)); break; case 4: _t->setWifiPassword(*reinterpret_cast< QString*>(_v)); break; case 5: _t->setWifiSSIDSta(*reinterpret_cast< QString*>(_v)); break; case 6: _t->setWifiPasswordSta(*reinterpret_cast< QString*>(_v)); break; case 9: _t->setBaudIndex(*reinterpret_cast< int*>(_v)); break; default: break; } } else if (_c == QMetaObject::ResetProperty) { } #endif // QT_NO_PROPERTIES } const QMetaObject ESP8266ComponentController::staticMetaObject = { { &FactPanelController::staticMetaObject, qt_meta_stringdata_ESP8266ComponentController.data, qt_meta_data_ESP8266ComponentController, qt_static_metacall, nullptr, nullptr} }; const QMetaObject *ESP8266ComponentController::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *ESP8266ComponentController::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_ESP8266ComponentController.stringdata0)) return static_cast<void*>(this); return FactPanelController::qt_metacast(_clname); } int ESP8266ComponentController::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = FactPanelController::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 14) qt_static_metacall(this, _c, _id, _a); _id -= 14; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 14) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 14; } #ifndef QT_NO_PROPERTIES else if (_c == QMetaObject::ReadProperty || _c == QMetaObject::WriteProperty || _c == QMetaObject::ResetProperty || _c == QMetaObject::RegisterPropertyMetaType) { qt_static_metacall(this, _c, _id, _a); _id -= 12; } else if (_c == QMetaObject::QueryPropertyDesignable) { _id -= 12; } else if (_c == QMetaObject::QueryPropertyScriptable) { _id -= 12; } else if (_c == QMetaObject::QueryPropertyStored) { _id -= 12; } else if (_c == QMetaObject::QueryPropertyEditable) { _id -= 12; } else if (_c == QMetaObject::QueryPropertyUser) { _id -= 12; } #endif // QT_NO_PROPERTIES return _id; } // SIGNAL 0 void ESP8266ComponentController::versionChanged() { QMetaObject::activate(this, &staticMetaObject, 0, nullptr); } // SIGNAL 1 void ESP8266ComponentController::wifiSSIDChanged() { QMetaObject::activate(this, &staticMetaObject, 1, nullptr); } // SIGNAL 2 void ESP8266ComponentController::wifiPasswordChanged() { QMetaObject::activate(this, &staticMetaObject, 2, nullptr); } // SIGNAL 3 void ESP8266ComponentController::wifiSSIDStaChanged() { QMetaObject::activate(this, &staticMetaObject, 3, nullptr); } // SIGNAL 4 void ESP8266ComponentController::wifiPasswordStaChanged() { QMetaObject::activate(this, &staticMetaObject, 4, nullptr); } // SIGNAL 5 void ESP8266ComponentController::baudIndexChanged() { QMetaObject::activate(this, &staticMetaObject, 5, nullptr); } // SIGNAL 6 void ESP8266ComponentController::busyChanged() { QMetaObject::activate(this, &staticMetaObject, 6, nullptr); } QT_WARNING_POP QT_END_MOC_NAMESPACE
37.228571
227
0.620526
[ "object" ]
383b36ee61b8a3eba31b19984183b724d190ee81
22,295
cpp
C++
src/mickey/mickey.cpp
jung1981/linux-track
92db912deb9dafe40aa30b00223ed065c9e334aa
[ "MIT" ]
null
null
null
src/mickey/mickey.cpp
jung1981/linux-track
92db912deb9dafe40aa30b00223ed065c9e334aa
[ "MIT" ]
1
2019-09-03T23:51:31.000Z
2019-09-03T23:51:31.000Z
src/mickey/mickey.cpp
jung1981/linux-track
92db912deb9dafe40aa30b00223ed065c9e334aa
[ "MIT" ]
null
null
null
#define NEWS_SERIAL 1 #ifdef HAVE_CONFIG_H #include "../../config.h" #endif #include <QMessageBox> #include <QTimer> #include <QMutex> #include <QMessageBox> #include <QApplication> #include <QDesktopWidget> #include <QCursor> #include "mickey.h" #include "mouse.h" #include "linuxtrack.h" #include "piper.h" #include "math_utils.h" #include "transform.h" #include <iostream> #include "hotkey.h" //Time to wait after the tracking commences to perform a recentering [ms] const int settleTime = 2000; //2 seconds void RestrainWidgetToScreen(QWidget * w) { QRect screenRect = QApplication::desktop()->availableGeometry(w); QRect wRect = w->frameGeometry(); /* std::cout<<"fg left: "<<w->frameGeometry().left(); std::cout<<" fg right: "<<w->frameGeometry().right(); std::cout<<" fg top: "<<w->frameGeometry().top(); std::cout<<" fg bottom: "<<w->frameGeometry().bottom()<<std::endl; std::cout<<"scr left: "<<screenRect.left(); std::cout<<" scr right: "<<screenRect.right(); std::cout<<" scr top: "<<screenRect.top(); std::cout<<" scr bottom: "<<screenRect.bottom()<<std::endl; */ //make sure the window fits the screen if(screenRect.width() < wRect.width()){ wRect.setWidth(screenRect.width()); } if(screenRect.height() < wRect.height()){ wRect.setHeight(screenRect.height()); } //shuffle the window so it is fully visible if(screenRect.left() > wRect.left()){ wRect.moveLeft(screenRect.left()); } if(screenRect.right() < wRect.right()){ wRect.moveRight(screenRect.right()); } if(screenRect.bottom() < wRect.bottom()){ wRect.moveBottom(screenRect.bottom()); } if(screenRect.top() > wRect.top()){ wRect.moveTop(screenRect.top()); } w->resize(wRect.size()); w->move(wRect.topLeft()); /* std::cout<<"fg left: "<<w->frameGeometry().left(); std::cout<<" fg right: "<<w->frameGeometry().right(); std::cout<<" fg top: "<<w->frameGeometry().top(); std::cout<<" fg bottom: "<<w->frameGeometry().bottom()<<std::endl; */ } MickeyApplyDialog::MickeyApplyDialog() { ui.setupUi(this); timer.setSingleShot(false); QObject::connect(&timer, SIGNAL(timeout()), this, SLOT(timeout())); setModal(true); } void MickeyApplyDialog::closeEvent(QCloseEvent *event) { timer.stop(); emit keep(); QDialog::closeEvent(event); } void MickeyApplyDialog::trySettings() { timer.start(1000); cntr = 15; ui.FBString->setText(QString::fromUtf8("Will automatically revert back in %1 seconds...").arg(cntr)); show(); raise(); activateWindow(); //std::cout<<"trying settings!"<<std::endl; } void MickeyApplyDialog::timeout() { //std::cout<<"Apl timeout!"<<std::endl; --cntr; if(cntr == 0){ timer.stop(); emit revert(); hide(); }else{ ui.FBString->setText(QString::fromUtf8("Will automatically revert back in %1 seconds...").arg(cntr)); } } void MickeyApplyDialog::on_RevertButton_pressed() { timer.stop(); //std::cout<<"Reverting..."<<std::endl; emit revert(); hide(); } void MickeyApplyDialog::on_KeepButton_pressed() { timer.stop(); //std::cout<<"Keeping..."<<std::endl; emit keep(); hide(); } MickeyCalibration::MickeyCalibration() { ui.setupUi(this); timer.setSingleShot(false); QObject::connect(ui.CancelButton, SIGNAL(pressed()), this, SLOT(cancelPressed())); QObject::connect(&timer, SIGNAL(timeout()), this, SLOT(timeout())); setModal(true); } void MickeyCalibration::closeEvent(QCloseEvent *event) { cancelPressed(); QDialog::closeEvent(event); } /* void MickeyCalibration::hide() { std::cout<<"Hide called!"<<std::endl; timer.stop(); if(calState == CALIBRATE){ emit cancelCalibration(); } QWidget::hide(); } */ void MickeyCalibration::calibrate() { timer.start(1000); calState = CENTER; cntr = GUI.getCntrDelay() + 1; timeout(); window()->show(); window()->raise(); window()->activateWindow(); } void MickeyCalibration::recenter() { timer.start(1000); calState = CENTER_ONLY; cntr = GUI.getCntrDelay() + 1;// +1 - compensation for first increment in timeout() timeout(); window()->show(); window()->raise(); window()->activateWindow(); } void MickeyCalibration::cancelPressed() { timer.stop(); if(calState == CALIBRATE){ emit cancelCalibration(true); }else{ emit cancelCalibration(false); } hide(); } void MickeyCalibration::timeout() { //std::cout<<"timer!"<<std::endl; --cntr; if(cntr == 0){ switch(calState){ case CENTER_ONLY: timer.stop(); emit recenterNow(true); window()->hide(); break; case CENTER: emit recenterNow(false); emit startCalibration(); calState = CALIBRATE; cntr = GUI.getCalDelay(); break; case CALIBRATE: timer.stop(); emit finishCalibration(); window()->hide(); break; } } switch(calState){ case CENTER: case CENTER_ONLY: ui.CalibrationText->setText(QString::fromUtf8("Please center your head and sight.")); ui.FBString->setText(QString::fromUtf8("Center position will be recorded in %1 seconds...").arg(cntr)); break; case CALIBRATE: ui.CalibrationText->setText(QString::fromUtf8("Please move your head to left/right and up/down extremes.")); ui.FBString->setText(QString::fromUtf8("Calibration will end in %1 seconds...").arg(cntr)); break; } } mouseClass mouse = mouseClass(); MickeyThread::MickeyThread(Mickey *p) : QThread(p), fifo(-1), finish(false), parent(*p), fakeBtn(0) { } void MickeyThread::processClick(sn4_btn_event_t ev) { //std::cout<<"Processing click! ("<<(int)ev.btns<<")"<<std::endl; int btns = ev.btns; mouse.click((buttons_t)btns, ev.timestamp); } //emulate mouse button press using keyboard void MickeyThread::on_mouseHotKey_activated(int button, bool pressed) { //std::cout<<(pressed ? "Button pressed!!!" : "Button released!!!")<<std::endl; sn4_btn_event_t ev; ev.btns = pressed ? button : 0; gettimeofday(&(ev.timestamp), NULL); processClick(ev); } void MickeyThread::run() { sn4_btn_event_t ev; ssize_t read; finish = false; while(1){ while(fifo <= 1){ if(finish){ return; } fifo = prepareBtnChanel(); if(fifo <= 0){ QThread::sleep(1); } } while(fetch_data(fifo, (void*)&ev, sizeof(ev), &read)){ //std::cout<<"Thread alive!"<<std::endl; if(finish){ return; } if(read == sizeof(ev)){ ev.btns ^= 3; processClick(ev); } } } } Mickey::Mickey() : updateTimer(this), btnThread(this), state(STANDBY), calDlg(), aplDlg(), recenterFlag(true), dw(NULL) { trans = new MickeyTransform(); //QObject::connect(onOffSwitch, SIGNAL(activated()), this, SLOT(onOffSwitch_activated())); //QObject::connect(&lbtnSwitch, SIGNAL(activated()), &btnThread, SLOT(on_key_pressed())); QObject::connect(this, SIGNAL(mouseHotKey_activated(int, bool)), &btnThread, SLOT(on_mouseHotKey_activated(int, bool))); QObject::connect(&updateTimer, SIGNAL(timeout()), this, SLOT(updateTimer_activated())); QObject::connect(&aplDlg, SIGNAL(keep()), this, SLOT(keepSettings())); QObject::connect(&aplDlg, SIGNAL(revert()), this, SLOT(revertSettings())); QObject::connect(&calDlg, SIGNAL(recenterNow(bool)), this, SLOT(recenterNow(bool))); QObject::connect(&calDlg, SIGNAL(startCalibration()), this, SLOT(startCalibration())); QObject::connect(&calDlg, SIGNAL(finishCalibration()), this, SLOT(finishCalibration())); QObject::connect(&calDlg, SIGNAL(cancelCalibration(bool)), this, SLOT(cancelCalibration(bool))); if(!mouse.init()){ exit(1); } dw = QApplication::desktop(); // screenBBox = dw->screenGeometry(); screenBBox = QRect(0, 0, dw->width(), dw->height()); screenCenter = screenBBox.center(); updateTimer.setSingleShot(false); updateTimer.setInterval(8); btnThread.start(); linuxtrack_init((char *)"Mickey"); changeState(TRACKING); } Mickey::~Mickey() { if(linuxtrack_get_tracking_state() == RUNNING){ linuxtrack_suspend(); } updateTimer.stop(); delete trans; trans = NULL; btnThread.setFinish(); btnThread.wait(); } void Mickey::screenResized(int screen) { (void)screen; // screenBBox = dw->screenGeometry(screen); screenBBox = QRect(0, 0, dw->width(), dw->height()); screenCenter = screenBBox.center(); } void Mickey::applySettings() { aplDlg.trySettings(); trans->applySettings(); } void Mickey::revertSettings() { trans->revertSettings(); } void Mickey::keepSettings() { trans->keepSettings(); } void Mickey::pause() { //std::cout<<"Pausing!"<<std::endl; //btnThread.setFinish(); //btnThread.wait(); updateTimer.stop(); linuxtrack_suspend(); } void Mickey::wakeup() { //std::cout<<"Waking up!"<<std::endl; updateTimer.start(); //btnThread.start(); linuxtrack_wakeup(); //ltr_recenter(); } void Mickey::calibrate() { changeState(CALIBRATING); calDlg.calibrate(); } void Mickey::recenter() { changeState(CALIBRATING); calDlg.recenter(); } void Mickey::changeState(state_t newState) { switch(state){ case TRACKING: switch(newState){ case TRACKING: //nothing to do break; case STANDBY: pause(); break; case CALIBRATING: break; } break; case STANDBY: switch(newState){ case TRACKING: wakeup(); break; case STANDBY: //nothing to do break; case CALIBRATING: wakeup(); break; } break; case CALIBRATING: switch(newState){ case TRACKING: //calDlg.hide(); //just continue... break; case STANDBY: //don't let this happen newState = CALIBRATING; break; case CALIBRATING: //nothing to do break; } break; } state = newState; switch(newState){ case TRACKING: GUI.setStatusLabel(QString::fromUtf8("Tracking")); break; case CALIBRATING: GUI.setStatusLabel(QString::fromUtf8("Calibrating")); break; case STANDBY: GUI.setStatusLabel(QString::fromUtf8("Paused")); break; } } void Mickey::hotKey_activated(int id, bool pressed) { switch(id){ case 0: // toggle if(!pressed){ return; } //std::cout<<"On/off switch activated!"<<std::endl; switch(state){ case TRACKING: changeState(STANDBY); break; case STANDBY: changeState(TRACKING); initTimer.start(); break; default: break; } break; case 1: //LMB emit mouseHotKey_activated(LEFT_BUTTON, pressed); break; case 2: //MMB emit mouseHotKey_activated(MIDDLE_BUTTON, pressed); break; case 3: // quick recenter linuxtrack_recenter(); break; } } void Mickey::updateTimer_activated() { static float heading_p = 0.0; static float pitch_p = 0.0; linuxtrack_pose_t full_pose; float blobs[3*3]; int blobs_read; //float heading, pitch, roll, tx, ty, tz; //unsigned int counter; static int lastTrackingState = -1; int trackingState = linuxtrack_get_tracking_state(); if(lastTrackingState != trackingState){ lastTrackingState = trackingState; if(trackingState == RUNNING){ switch(state){ case TRACKING: GUI.setStatusLabel(QString::fromUtf8("Tracking")); break; case CALIBRATING: GUI.setStatusLabel(QString::fromUtf8("Calibrating")); break; case STANDBY: GUI.setStatusLabel(QString::fromUtf8("Paused")); break; } }else{ switch(trackingState){ case INITIALIZING: GUI.setStatusLabel(QString::fromUtf8("Initializing")); break; case err_NOT_INITIALIZED: case err_SYMBOL_LOOKUP: case err_NO_CONFIG: case err_NOT_FOUND: case err_PROCESSING_FRAME: GUI.setStatusLabel(QString::fromUtf8("Error")); break; default: GUI.setStatusLabel(QString::fromUtf8("Inactive")); break; } } } if(trackingState != RUNNING){ return; } if(recenterFlag){ if(initTimer.elapsed() < settleTime){ return; }else{ linuxtrack_recenter(); recenterFlag = false; } } // if(linuxtrack_get_pose(&heading, &pitch, &roll, &tx, &ty, &tz, &counter) > 0){ if(linuxtrack_get_pose_full(&full_pose, blobs, 3, &blobs_read) > 0){ //new frame has arrived /*heading = full_pose.yaw; pitch = full_pose.pitch; roll = full_pose.roll; tx = full_pose.tx; ty = full_pose.ty; tz = full_pose.tz; counter = full_pose.counter; */ heading_p = full_pose.raw_yaw; pitch_p = full_pose.raw_pitch; //ui.XLabel->setText(QString("X: %1").arg(heading)); //ui.YLabel->setText(QString("Y: %1").arg(pitch)); } int elapsed = updateElapsed.elapsed(); updateElapsed.restart(); //reversing signs to get the cursor move according to the head movement float dx, dy; trans->update(heading_p, pitch_p, relative, elapsed, dx, dy); if(state == TRACKING){ if(relative){ int idx = (int)dx; int idy = (int)dy; if((idx != 0) || (idy != 0)){ mouse.move((int)dx, (int)dy); //QPoint pos = QCursor::pos(); //pos += QPoint(dx,dy); //QCursor::setPos(pos); } }else{ QPoint c = screenCenter + QPoint(screenCenter.x() * dx, screenCenter.y() * dy); QCursor::setPos(c); } } } void Mickey::startCalibration() { trans->startCalibration(); } void Mickey::finishCalibration() { trans->finishCalibration(); changeState(TRACKING); applySettings(); } void Mickey::cancelCalibration(bool calStarted) { if(calStarted){ trans->cancelCalibration(); } changeState(TRACKING); } /* bool Mickey::setShortcut(QKeySequence seq) { bool res = onOffSwitch->setShortcut(seq); //If the shortcut doesn't work, pause the tracking to avoid problems if(res){ changeState(TRACKING); }else{ changeState(STANDBY); } return res; } */ MickeyGUI *MickeyGUI::instance = NULL; MickeyGUI &MickeyGUI::getInstance() { if(instance == NULL){ instance = new MickeyGUI(); instance->init(); } return *instance; } void MickeyGUI::deleteInstance() { if(instance != NULL){ MickeyGUI *tmp = instance; instance = NULL; delete tmp; } } static HotKey* addHotKey(const QString &label, const QString &prefId, int id, QWidget *owner, QObject *target, QGridLayout *dest, QSettings *pref, int row, int column) { HotKey *hk = new HotKey(label, prefId, id, owner); QString hkString = pref->value(prefId, QString::fromUtf8("None")).toString(); if(hk->setHotKey(hkString)){ //std::cout<<"hk: "<<hk<<std::endl; dest->addWidget(hk, row, column); QObject::connect(hk, SIGNAL(activated(int, bool)), target, SLOT(hotKey_activated(int, bool))); QObject::connect(hk, SIGNAL(newHotKey(const QString &, const QString &)), owner, SLOT(updateHotKey(const QString &, const QString &))); return hk; }else{ delete hk; return NULL; } } MickeyGUI::MickeyGUI(QWidget *parent) : QWidget(parent), mickey(NULL), settings(QString::fromUtf8("linuxtrack"), QString::fromUtf8("mickey")), changed(false), hotkeySet(false) { ui.setupUi(this); readPrefs(); //mickey = new Mickey(); } void MickeyGUI::updateHotKey(const QString &prefId, const QString &hk) { //std::cout<<"Updating Id: "<<prefId.toUtf8().constData()<<" "<<hk.toUtf8().constData()<<std::endl; settings.beginGroup(QString::fromUtf8("HotKeys")); settings.setValue(prefId, hk); settings.endGroup(); } MickeyGUI::~MickeyGUI() { ui.HotkeyStack->removeWidget(toggleHotKey); ui.HotkeyStack->removeWidget(lmbHotKey); ui.HotkeyStack->removeWidget(mmbHotKey); delete toggleHotKey; delete lmbHotKey; delete mmbHotKey; delete mickey; } void MickeyGUI::readPrefs() { //Axes setup bool relative; settings.beginGroup(QString::fromUtf8("Axes")); deadzone = settings.value(QString::fromUtf8("DeadZone"), 20).toInt(); sensitivity = settings.value(QString::fromUtf8("Sensitivity"), 50).toInt(); curvature = settings.value(QString::fromUtf8("Curvature"), 50).toInt(); smoothing = settings.value(QString::fromUtf8("Smoothing"), 33).toInt(); stepOnly = settings.value(QString::fromUtf8("StepOnly"), false).toBool(); relative = settings.value(QString::fromUtf8("Relative"), true).toBool(); ui.SensSlider->setValue(sensitivity); ui.DZSlider->setValue(deadzone); ui.CurveSlider->setValue(curvature); ui.SmoothingSlider->setValue(smoothing); ui.StepOnly->setCheckState(stepOnly ? Qt::Checked : Qt::Unchecked); if(stepOnly){ ui.CurveSlider->setDisabled(true); }else{ ui.CurveSlider->setEnabled(true); } if(relative){ ui.RelativeCB->setChecked(true); }else{ ui.AbsoluteCB->setChecked(true); ui.SensSlider->setDisabled(true); ui.DZSlider->setDisabled(true); ui.CurveSlider->setDisabled(true); ui.StepOnly->setDisabled(true); } settings.endGroup(); //trans setup settings.beginGroup(QString::fromUtf8("Transform")); maxValX = settings.value(QString::fromUtf8("RangeX"), 130).toFloat(); maxValY = settings.value(QString::fromUtf8("RangeY"), 130).toFloat(); settings.endGroup(); //calibration setup settings.beginGroup(QString::fromUtf8("Calibration")); calDelay = settings.value(QString::fromUtf8("CalibrationDelay"), 10).toInt(); cntrDelay = settings.value(QString::fromUtf8("CenteringDelay"), 10).toInt(); settings.endGroup(); ui.CalibrationTimeout->setValue(calDelay); ui.CenterTimeout->setValue(cntrDelay); HelpViewer::LoadPrefs(settings); settings.beginGroup(QString::fromUtf8("Misc")); welcome = settings.value(QString::fromUtf8("welcome"), true).toBool(); newsSerial = settings.value(QString::fromUtf8("news"), -1).toInt(); resize(settings.value(QString::fromUtf8("size"), QSize(-1, -1)).toSize()); move(settings.value(QString::fromUtf8("pos"), QPoint(0, 0)).toPoint()); settings.endGroup(); } void MickeyGUI::storePrefs() { HelpViewer::StorePrefs(settings); settings.beginGroup(QString::fromUtf8("Misc")); settings.setValue(QString::fromUtf8("welcome"), false); settings.setValue(QString::fromUtf8("news"), NEWS_SERIAL); settings.setValue(QString::fromUtf8("size"), size()); settings.setValue(QString::fromUtf8("pos"), pos()); settings.endGroup(); if(!changed){ return; } if(QMessageBox::question(this, QString::fromUtf8("Save prefs?"), QString::fromUtf8("Preferences have changed, do you want to save them?"), QMessageBox::Save | QMessageBox::Discard, QMessageBox::Save) == QMessageBox::Discard){ return; } //Axes setup settings.beginGroup(QString::fromUtf8("Axes")); settings.setValue(QString::fromUtf8("DeadZone"), deadzone); settings.setValue(QString::fromUtf8("Sensitivity"), sensitivity); settings.setValue(QString::fromUtf8("Curvature"), curvature); settings.setValue(QString::fromUtf8("Smoothing"), smoothing); settings.setValue(QString::fromUtf8("StepOnly"), stepOnly); settings.setValue(QString::fromUtf8("Relative"), mickey->getRelative()); settings.endGroup(); //trans setup settings.beginGroup(QString::fromUtf8("Transform")); settings.setValue(QString::fromUtf8("RangeX"), maxValX); settings.setValue(QString::fromUtf8("RangeY"), maxValY); settings.endGroup(); //calibration setup settings.beginGroup(QString::fromUtf8("Calibration")); settings.setValue(QString::fromUtf8("CalibrationDelay"), calDelay); settings.setValue(QString::fromUtf8("CenteringDelay"), cntrDelay); settings.endGroup(); } void MickeyGUI::setStepOnly(bool value) { changed = true; stepOnly = value; ui.StepOnly->setCheckState(stepOnly ? Qt::Checked : Qt::Unchecked); if(stepOnly){ ui.CurveSlider->setDisabled(true); }else{ ui.CurveSlider->setEnabled(true); } } void MickeyGUI::on_StepOnly_stateChanged(int state) { stepOnly = (state == Qt::Checked); if(stepOnly){ ui.CurveSlider->setDisabled(true); }else{ ui.CurveSlider->setEnabled(true); } emit axisChanged(); ui.ApplyButton->setEnabled(true); } void MickeyGUI::closeEvent(QCloseEvent *event) { storePrefs(); HelpViewer::CloseWindow(); QWidget::closeEvent(event); } void MickeyGUI::on_MickeyTabs_currentChanged(int index) { switch(index){ case 0: HelpViewer::ChangePage(QString::fromUtf8("tracking.htm")); break; case 1: HelpViewer::ChangePage(QString::fromUtf8("misc.htm")); break; } } void MickeyGUI::show() { QWidget::show(); setWindowTitle(QString::fromUtf8("Mickey v")+QString::fromUtf8(PACKAGE_VERSION)); RestrainWidgetToScreen(this); if(welcome){ HelpViewer::ChangePage(QString::fromUtf8("welcome.htm")); HelpViewer::ShowWindow(); }else if(newsSerial < NEWS_SERIAL){ HelpViewer::ChangePage(QString::fromUtf8("news.htm")); HelpViewer::ShowWindow(); }else{ HelpViewer::ChangePage(QString::fromUtf8("tracking.htm")); } } //To avoid recursion as Mickey's constructor uses GUI too void MickeyGUI::init() { mickey = new Mickey(); settings.beginGroup(QString::fromUtf8("HotKeys")); ui.HotkeyStack->addWidget(new QLabel(QString::fromUtf8("Hotkey setup")), 1, 1); toggleHotKey = addHotKey(QString::fromUtf8("Start/Stop tracking:"), QString::fromUtf8("tracking_toggle"), 0, this, mickey, ui.HotkeyStack, &settings, 2, 1); recenterHotKey = addHotKey(QString::fromUtf8("Quick recenter:"), QString::fromUtf8("quick_recenter"), 3, this, mickey, ui.HotkeyStack, &settings, 2, 2); ui.HotkeyStack->addWidget(new QLabel(QString::fromUtf8("Mouse button emulation")), 3, 1); lmbHotKey = addHotKey(QString::fromUtf8("Left:"), QString::fromUtf8("l_mouse"), 1, this, mickey, ui.HotkeyStack, &settings, 4, 1); mmbHotKey = addHotKey(QString::fromUtf8("Middle:"), QString::fromUtf8("m_mouse"), 2, this, mickey, ui.HotkeyStack, &settings, 4, 2); settings.endGroup(); ui.ApplyButton->setEnabled(false); mickey->setRelative(ui.RelativeCB->isChecked()); changed = false; }
26.19859
116
0.653151
[ "transform" ]
383bc2f12317c7038e05545d0617d886d075dd08
2,047
cpp
C++
Samples/Printing/cpp/Scenario1Basic.xaml.cpp
dujianxin/Windows-universal-samples
d4e95ff0ac408c5d4d980bb18d53fb2c6556a273
[ "MIT" ]
2,504
2019-05-07T06:56:42.000Z
2022-03-31T19:37:59.000Z
Samples/Printing/cpp/Scenario1Basic.xaml.cpp
dujianxin/Windows-universal-samples
d4e95ff0ac408c5d4d980bb18d53fb2c6556a273
[ "MIT" ]
314
2019-05-08T16:56:30.000Z
2022-03-21T07:13:45.000Z
Samples/Printing/cpp/Scenario1Basic.xaml.cpp
dujianxin/Windows-universal-samples
d4e95ff0ac408c5d4d980bb18d53fb2c6556a273
[ "MIT" ]
2,219
2019-05-07T00:47:26.000Z
2022-03-30T21:12:31.000Z
// Copyright (c) Microsoft. All rights reserved. #include "pch.h" #include "Scenario1Basic.xaml.h" #include "PageToPrint.xaml.h" using namespace SDKTemplate; using namespace Platform; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::Graphics::Printing; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Controls::Primitives; using namespace Windows::UI::Xaml::Data; using namespace Windows::UI::Xaml::Input; using namespace Windows::UI::Xaml::Media; using namespace Windows::UI::Xaml::Navigation; Scenario1Basic::Scenario1Basic() { InitializeComponent(); } void Scenario1Basic::OnPrintButtonClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { printHelper->ShowPrintUIAsync(); } void Scenario1Basic::OnNavigatedTo(NavigationEventArgs^ e) { if (PrintManager::IsSupported()) { // Tell the user how to print MainPage::Current->NotifyUser("Print contract registered with customization, use the Print button to print.", NotifyType::StatusMessage); } else { // Remove the print button InvokePrintingButton->Visibility = Windows::UI::Xaml::Visibility::Collapsed; // Inform user that Printing is not supported MainPage::Current->NotifyUser("Printing is not supported.", NotifyType::ErrorMessage); // Printing-related event handlers will never be called if printing // is not supported, but it's okay to register for them anyway. } // Initalize common helper class and register for printing printHelper = ref new PrintHelper(this); printHelper->RegisterForPrinting(); // Initialize print content for this scenario printHelper->PreparePrintContent(ref new PageToPrint()); } void Scenario1Basic::OnNavigatedFrom(NavigationEventArgs^ e) { if (printHelper) { printHelper->UnregisterForPrinting(); } }
31.492308
146
0.705911
[ "object" ]
383d80b042de66247e6a02a4132ebdcf2c1348f3
33,115
hpp
C++
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_crypto_macsec_mka_oper.hpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
17
2016-12-02T05:45:49.000Z
2022-02-10T19:32:54.000Z
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_crypto_macsec_mka_oper.hpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
2
2017-03-27T15:22:38.000Z
2019-11-05T08:30:16.000Z
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_crypto_macsec_mka_oper.hpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
11
2016-12-02T05:45:52.000Z
2019-11-07T08:28:17.000Z
#ifndef _CISCO_IOS_XR_CRYPTO_MACSEC_MKA_OPER_ #define _CISCO_IOS_XR_CRYPTO_MACSEC_MKA_OPER_ #include <memory> #include <vector> #include <string> #include <ydk/types.hpp> #include <ydk/errors.hpp> namespace cisco_ios_xr { namespace Cisco_IOS_XR_crypto_macsec_mka_oper { class Macsec : public ydk::Entity { public: Macsec(); ~Macsec(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::shared_ptr<ydk::Entity> clone_ptr() const override; ydk::augment_capabilities_function get_augment_capabilities_function() const override; std::string get_bundle_yang_models_location() const override; std::string get_bundle_name() const override; std::map<std::pair<std::string, std::string>, std::string> get_namespace_identity_lookup() const override; class Mka; //type: Macsec::Mka std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_crypto_macsec_mka_oper::Macsec::Mka> mka; }; // Macsec class Macsec::Mka : public ydk::Entity { public: Mka(); ~Mka(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class Interfaces; //type: Macsec::Mka::Interfaces std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_crypto_macsec_mka_oper::Macsec::Mka::Interfaces> interfaces; }; // Macsec::Mka class Macsec::Mka::Interfaces : public ydk::Entity { public: Interfaces(); ~Interfaces(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class Interface; //type: Macsec::Mka::Interfaces::Interface ydk::YList interface; }; // Macsec::Mka::Interfaces class Macsec::Mka::Interfaces::Interface : public ydk::Entity { public: Interface(); ~Interface(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf name; //type: string class Session; //type: Macsec::Mka::Interfaces::Interface::Session class Info; //type: Macsec::Mka::Interfaces::Interface::Info std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_crypto_macsec_mka_oper::Macsec::Mka::Interfaces::Interface::Session> session; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_crypto_macsec_mka_oper::Macsec::Mka::Interfaces::Interface::Info> info; }; // Macsec::Mka::Interfaces::Interface class Macsec::Mka::Interfaces::Interface::Session : public ydk::Entity { public: Session(); ~Session(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class SessionSummary; //type: Macsec::Mka::Interfaces::Interface::Session::SessionSummary class Vp; //type: Macsec::Mka::Interfaces::Interface::Session::Vp class Ca; //type: Macsec::Mka::Interfaces::Interface::Session::Ca std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_crypto_macsec_mka_oper::Macsec::Mka::Interfaces::Interface::Session::SessionSummary> session_summary; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_crypto_macsec_mka_oper::Macsec::Mka::Interfaces::Interface::Session::Vp> vp; ydk::YList ca; }; // Macsec::Mka::Interfaces::Interface::Session class Macsec::Mka::Interfaces::Interface::Session::SessionSummary : public ydk::Entity { public: SessionSummary(); ~SessionSummary(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf interface_name; //type: string ydk::YLeaf inherited_policy; //type: boolean ydk::YLeaf policy; //type: string ydk::YLeaf priority; //type: uint32 ydk::YLeaf my_mac; //type: string ydk::YLeaf delay_protection; //type: boolean ydk::YLeaf replay_protect; //type: boolean ydk::YLeaf window_size; //type: uint32 ydk::YLeaf include_icv_indicator; //type: boolean ydk::YLeaf confidentiality_offset; //type: uint32 ydk::YLeaf algo_agility; //type: uint32 ydk::YLeaf capability; //type: uint32 ydk::YLeaf mka_cipher_suite; //type: string ydk::YLeaf configured_mac_sec_cipher_suite; //type: string ydk::YLeaf mac_sec_desired; //type: boolean class OuterTag; //type: Macsec::Mka::Interfaces::Interface::Session::SessionSummary::OuterTag class InnerTag; //type: Macsec::Mka::Interfaces::Interface::Session::SessionSummary::InnerTag std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_crypto_macsec_mka_oper::Macsec::Mka::Interfaces::Interface::Session::SessionSummary::OuterTag> outer_tag; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_crypto_macsec_mka_oper::Macsec::Mka::Interfaces::Interface::Session::SessionSummary::InnerTag> inner_tag; }; // Macsec::Mka::Interfaces::Interface::Session::SessionSummary class Macsec::Mka::Interfaces::Interface::Session::SessionSummary::OuterTag : public ydk::Entity { public: OuterTag(); ~OuterTag(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf ether_type; //type: uint16 ydk::YLeaf priority; //type: uint8 ydk::YLeaf cfi; //type: uint8 ydk::YLeaf vlan_id; //type: uint16 }; // Macsec::Mka::Interfaces::Interface::Session::SessionSummary::OuterTag class Macsec::Mka::Interfaces::Interface::Session::SessionSummary::InnerTag : public ydk::Entity { public: InnerTag(); ~InnerTag(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf ether_type; //type: uint16 ydk::YLeaf priority; //type: uint8 ydk::YLeaf cfi; //type: uint8 ydk::YLeaf vlan_id; //type: uint16 }; // Macsec::Mka::Interfaces::Interface::Session::SessionSummary::InnerTag class Macsec::Mka::Interfaces::Interface::Session::Vp : public ydk::Entity { public: Vp(); ~Vp(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf my_sci; //type: string ydk::YLeaf virtual_port_id; //type: uint32 ydk::YLeaf latest_rx; //type: boolean ydk::YLeaf latest_tx; //type: boolean ydk::YLeaf latest_an; //type: uint32 ydk::YLeaf latest_ki; //type: string ydk::YLeaf latest_kn; //type: uint32 ydk::YLeaf old_rx; //type: boolean ydk::YLeaf old_tx; //type: boolean ydk::YLeaf old_an; //type: uint32 ydk::YLeaf old_ki; //type: string ydk::YLeaf old_kn; //type: uint32 ydk::YLeaf wait_time; //type: uint32 ydk::YLeaf retire_time; //type: uint32 ydk::YLeaf macsec_cipher_suite; //type: MacsecCipherSuite ydk::YLeaf ssci; //type: uint32 ydk::YLeaf time_to_sak_rekey; //type: string class FallbackKeepalive; //type: Macsec::Mka::Interfaces::Interface::Session::Vp::FallbackKeepalive ydk::YList fallback_keepalive; }; // Macsec::Mka::Interfaces::Interface::Session::Vp class Macsec::Mka::Interfaces::Interface::Session::Vp::FallbackKeepalive : public ydk::Entity { public: FallbackKeepalive(); ~FallbackKeepalive(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf ckn; //type: string ydk::YLeaf mi; //type: string ydk::YLeaf mn; //type: uint32 class PeersStatus; //type: Macsec::Mka::Interfaces::Interface::Session::Vp::FallbackKeepalive::PeersStatus std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_crypto_macsec_mka_oper::Macsec::Mka::Interfaces::Interface::Session::Vp::FallbackKeepalive::PeersStatus> peers_status; }; // Macsec::Mka::Interfaces::Interface::Session::Vp::FallbackKeepalive class Macsec::Mka::Interfaces::Interface::Session::Vp::FallbackKeepalive::PeersStatus : public ydk::Entity { public: PeersStatus(); ~PeersStatus(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tx_mkpdu_timestamp; //type: string ydk::YLeaf peer_count; //type: uint32 class Peer; //type: Macsec::Mka::Interfaces::Interface::Session::Vp::FallbackKeepalive::PeersStatus::Peer ydk::YList peer; }; // Macsec::Mka::Interfaces::Interface::Session::Vp::FallbackKeepalive::PeersStatus class Macsec::Mka::Interfaces::Interface::Session::Vp::FallbackKeepalive::PeersStatus::Peer : public ydk::Entity { public: Peer(); ~Peer(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf sci; //type: string class PeerData; //type: Macsec::Mka::Interfaces::Interface::Session::Vp::FallbackKeepalive::PeersStatus::Peer::PeerData std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_crypto_macsec_mka_oper::Macsec::Mka::Interfaces::Interface::Session::Vp::FallbackKeepalive::PeersStatus::Peer::PeerData> peer_data; }; // Macsec::Mka::Interfaces::Interface::Session::Vp::FallbackKeepalive::PeersStatus::Peer class Macsec::Mka::Interfaces::Interface::Session::Vp::FallbackKeepalive::PeersStatus::Peer::PeerData : public ydk::Entity { public: PeerData(); ~PeerData(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf mi; //type: string ydk::YLeaf icv_status; //type: string ydk::YLeaf icv_check_timestamp; //type: string }; // Macsec::Mka::Interfaces::Interface::Session::Vp::FallbackKeepalive::PeersStatus::Peer::PeerData class Macsec::Mka::Interfaces::Interface::Session::Ca : public ydk::Entity { public: Ca(); ~Ca(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf is_key_server; //type: boolean ydk::YLeaf status; //type: uint32 ydk::YLeaf num_live_peers; //type: uint32 ydk::YLeaf first_ca; //type: boolean ydk::YLeaf peer_sci; //type: string ydk::YLeaf num_live_peers_responded; //type: uint32 ydk::YLeaf ckn; //type: string ydk::YLeaf my_mi; //type: string ydk::YLeaf my_mn; //type: uint32 ydk::YLeaf authenticator; //type: boolean ydk::YLeaf status_description; //type: string ydk::YLeaf authentication_mode; //type: string ydk::YLeaf key_chain; //type: string class PeersStatus; //type: Macsec::Mka::Interfaces::Interface::Session::Ca::PeersStatus class LivePeer; //type: Macsec::Mka::Interfaces::Interface::Session::Ca::LivePeer class PotentialPeer; //type: Macsec::Mka::Interfaces::Interface::Session::Ca::PotentialPeer class DormantPeer; //type: Macsec::Mka::Interfaces::Interface::Session::Ca::DormantPeer std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_crypto_macsec_mka_oper::Macsec::Mka::Interfaces::Interface::Session::Ca::PeersStatus> peers_status; ydk::YList live_peer; ydk::YList potential_peer; ydk::YList dormant_peer; }; // Macsec::Mka::Interfaces::Interface::Session::Ca class Macsec::Mka::Interfaces::Interface::Session::Ca::PeersStatus : public ydk::Entity { public: PeersStatus(); ~PeersStatus(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tx_mkpdu_timestamp; //type: string ydk::YLeaf peer_count; //type: uint32 class Peer; //type: Macsec::Mka::Interfaces::Interface::Session::Ca::PeersStatus::Peer ydk::YList peer; }; // Macsec::Mka::Interfaces::Interface::Session::Ca::PeersStatus class Macsec::Mka::Interfaces::Interface::Session::Ca::PeersStatus::Peer : public ydk::Entity { public: Peer(); ~Peer(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf sci; //type: string class PeerData; //type: Macsec::Mka::Interfaces::Interface::Session::Ca::PeersStatus::Peer::PeerData std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_crypto_macsec_mka_oper::Macsec::Mka::Interfaces::Interface::Session::Ca::PeersStatus::Peer::PeerData> peer_data; }; // Macsec::Mka::Interfaces::Interface::Session::Ca::PeersStatus::Peer class Macsec::Mka::Interfaces::Interface::Session::Ca::PeersStatus::Peer::PeerData : public ydk::Entity { public: PeerData(); ~PeerData(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf mi; //type: string ydk::YLeaf icv_status; //type: string ydk::YLeaf icv_check_timestamp; //type: string }; // Macsec::Mka::Interfaces::Interface::Session::Ca::PeersStatus::Peer::PeerData class Macsec::Mka::Interfaces::Interface::Session::Ca::LivePeer : public ydk::Entity { public: LivePeer(); ~LivePeer(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf mi; //type: string ydk::YLeaf sci; //type: string ydk::YLeaf mn; //type: uint32 ydk::YLeaf priority; //type: uint32 ydk::YLeaf ssci; //type: uint32 }; // Macsec::Mka::Interfaces::Interface::Session::Ca::LivePeer class Macsec::Mka::Interfaces::Interface::Session::Ca::PotentialPeer : public ydk::Entity { public: PotentialPeer(); ~PotentialPeer(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf mi; //type: string ydk::YLeaf sci; //type: string ydk::YLeaf mn; //type: uint32 ydk::YLeaf priority; //type: uint32 ydk::YLeaf ssci; //type: uint32 }; // Macsec::Mka::Interfaces::Interface::Session::Ca::PotentialPeer class Macsec::Mka::Interfaces::Interface::Session::Ca::DormantPeer : public ydk::Entity { public: DormantPeer(); ~DormantPeer(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf mi; //type: string ydk::YLeaf sci; //type: string ydk::YLeaf mn; //type: uint32 ydk::YLeaf priority; //type: uint32 ydk::YLeaf ssci; //type: uint32 }; // Macsec::Mka::Interfaces::Interface::Session::Ca::DormantPeer class Macsec::Mka::Interfaces::Interface::Info : public ydk::Entity { public: Info(); ~Info(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class InterfaceSummary; //type: Macsec::Mka::Interfaces::Interface::Info::InterfaceSummary std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_crypto_macsec_mka_oper::Macsec::Mka::Interfaces::Interface::Info::InterfaceSummary> interface_summary; }; // Macsec::Mka::Interfaces::Interface::Info class Macsec::Mka::Interfaces::Interface::Info::InterfaceSummary : public ydk::Entity { public: InterfaceSummary(); ~InterfaceSummary(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf interface_name; //type: string ydk::YLeaf short_name; //type: string ydk::YLeaf key_chain; //type: string ydk::YLeaf policy; //type: string ydk::YLeaf macsec_svc_port; //type: boolean ydk::YLeaf macsec_svc_port_type; //type: MacsecServicePort ydk::YLeaf svcport_short_name; //type: string ydk::YLeaf mka_mode; //type: MkaAuthenticationMode ydk::YLeaf fallback_keychain; //type: string ydk::YLeaf macsec_shutdown; //type: boolean }; // Macsec::Mka::Interfaces::Interface::Info::InterfaceSummary class MacsecCipherSuite : public ydk::Enum { public: static const ydk::Enum::YLeaf cipher_suite_none; static const ydk::Enum::YLeaf cipher_suite_gcm_aes_128; static const ydk::Enum::YLeaf cipher_suite_gcm_aes_256; static const ydk::Enum::YLeaf cipher_suite_gcm_aes_128_xpn; static const ydk::Enum::YLeaf cipher_suite_gcm_aes_256_xpn; static int get_enum_value(const std::string & name) { if (name == "cipher-suite-none") return 0; if (name == "cipher-suite-gcm-aes-128") return 1; if (name == "cipher-suite-gcm-aes-256") return 2; if (name == "cipher-suite-gcm-aes-128-xpn") return 3; if (name == "cipher-suite-gcm-aes-256-xpn") return 4; return -1; } }; class MkaAuthenticationMode : public ydk::Enum { public: static const ydk::Enum::YLeaf auth_mode_invalid; static const ydk::Enum::YLeaf auth_mode_psk; static const ydk::Enum::YLeaf auth_mode_eap; static int get_enum_value(const std::string & name) { if (name == "auth-mode-invalid") return 0; if (name == "auth-mode-psk") return 1; if (name == "auth-mode-eap") return 2; return -1; } }; class MacsecServicePort : public ydk::Enum { public: static const ydk::Enum::YLeaf macsec_service_port_none; static const ydk::Enum::YLeaf macsec_service_port_encryption; static const ydk::Enum::YLeaf macsec_service_port_decryption; static int get_enum_value(const std::string & name) { if (name == "macsec-service-port-none") return 0; if (name == "macsec-service-port-encryption") return 1; if (name == "macsec-service-port-decryption") return 2; return -1; } }; } } #endif /* _CISCO_IOS_XR_CRYPTO_MACSEC_MKA_OPER_ */
49.796992
182
0.683678
[ "vector" ]
3840e67bcff4db1a8c6fb19ccc81df78408be185
7,998
cpp
C++
testApp/misc/testByteBuffer.cpp
hir12111/pvDataCPP
d12571b4cdaaf8010b2e11e04905fde85b287299
[ "MIT" ]
null
null
null
testApp/misc/testByteBuffer.cpp
hir12111/pvDataCPP
d12571b4cdaaf8010b2e11e04905fde85b287299
[ "MIT" ]
null
null
null
testApp/misc/testByteBuffer.cpp
hir12111/pvDataCPP
d12571b4cdaaf8010b2e11e04905fde85b287299
[ "MIT" ]
null
null
null
/* * Copyright information and license terms for this software can be * found in the file LICENSE that is included with the distribution */ /* * testByteBuffer.cpp * * Created on: Oct 20, 2010 * Author: Miha Vitorovic */ #include <iostream> #include <fstream> #include <cstring> #include <memory> #include <testMain.h> #include <pv/pvUnitTest.h> #include <pv/byteBuffer.h> #include <pv/pvIntrospect.h> using namespace epics::pvData; static void testBasicOperations() { epics::auto_ptr<ByteBuffer> buff(new ByteBuffer(32)); testOk1(buff->getSize()==32); testOk1(buff->getPosition()==0); testOk1(buff->getLimit()==32); testOk1(buff->getRemaining()==32); buff->putBoolean(true); testOk1(buff->getPosition()==1); testOk1(buff->getRemaining()==31); buff->putByte(-12); testOk1(buff->getPosition()==2); testOk1(buff->getRemaining()==30); buff->putShort(10516); testOk1(buff->getPosition()==4); testOk1(buff->getRemaining()==28); buff->putInt(0x1937628B); testOk1(buff->getPosition()==8); testOk1(buff->getRemaining()==24); buff->putLong(2345678123LL); testOk1(buff->getPosition()==16); testOk1(buff->getRemaining()==16); float testFloat = 34.67f; buff->putFloat(testFloat); testOk1(buff->getPosition()==20); testOk1(buff->getRemaining()==12); double testDouble = -512.23974; buff->putDouble(testDouble); testOk1(buff->getPosition()==28); testOk1(buff->getRemaining()==4); // testing direct reads testOk1(buff->getBoolean(0)==true); testOk1(buff->getByte(1)==-12); testOk1(buff->getShort(2)==10516); testOk1(buff->getInt(4)==0x1937628B); testOk1(buff->getLong(8)==2345678123LL); testOk1(buff->getFloat(16)==testFloat); testOk1(buff->getDouble(20)==testDouble); buff->flip(); testOk1(buff->getLimit()==28); testOk1(buff->getPosition()==0); testOk1(buff->getRemaining()==28); testOk1(buff->getBoolean()==true); testOk1(buff->getPosition()==1); testOk1(buff->getByte()==-12); testOk1(buff->getPosition()==2); testOk1(buff->getShort()==10516); testOk1(buff->getPosition()==4); testOk1(buff->getInt()==0x1937628B); testOk1(buff->getPosition()==8); testOk1(buff->getLong()==2345678123LL); testOk1(buff->getPosition()==16); testOk1(buff->getFloat()==testFloat); testOk1(buff->getPosition()==20); testOk1(buff->getDouble()==testDouble); testOk1(buff->getPosition()==28); buff->clear(); testOk1(buff->getPosition()==0); testOk1(buff->getLimit()==32); testOk1(buff->getRemaining()==32); buff->setPosition(4); testOk1(buff->getPosition()==4); testOk1(buff->getLimit()==32); testOk1(buff->getRemaining()==(32-4)); buff->setPosition(13); testOk1(buff->getPosition()==13); testOk1(buff->getLimit()==32); testOk1(buff->getRemaining()==(32-13)); // testing absolute puts buff->clear(); buff->setPosition(28); buff->putBoolean(0, true); buff->putByte(1, -12); buff->putShort(2, 10516); buff->putInt(4, 0x1937628B); buff->putLong(8, 2345678123LL); buff->putFloat(16, testFloat); buff->putDouble(20, testDouble); buff->flip(); testOk1(buff->getLimit()==28); testOk1(buff->getPosition()==0); testOk1(buff->getRemaining()==28); testOk1(buff->getBoolean()==true); testOk1(buff->getPosition()==1); testOk1(buff->getByte()==-12); testOk1(buff->getPosition()==2); testOk1(buff->getShort()==10516); testOk1(buff->getPosition()==4); testOk1(buff->getInt()==0x1937628B); testOk1(buff->getPosition()==8); testOk1(buff->getLong()==2345678123LL); testOk1(buff->getPosition()==16); testOk1(buff->getFloat()==testFloat); testOk1(buff->getPosition()==20); testOk1(buff->getDouble()==testDouble); testOk1(buff->getPosition()==28); buff->clear(); testOk1(buff->getPosition()==0); testOk1(buff->getLimit()==32); testOk1(buff->getRemaining()==32); char src[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm' }; char dst[] = { ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' }; buff->put(src, 2, 6); testOk1(buff->getPosition()==6); testOk1(strncmp(buff->getArray(),&src[2],6)==0); buff->flip(); testOk1(buff->getLimit()==6); testOk1(buff->getPosition()==0); testOk1(buff->getRemaining()==6); buff->get(dst, 2, 6); testOk1(buff->getLimit()==6); testOk1(buff->getPosition()==6); testOk1(strncmp(&src[2],&dst[2],6)==0); testShow()<<"First 10 characters of destination: >>"<<std::string(dst, 10)<<"<<\n"; } static const char expect_be[] = "abcdef"; static const char expect_le[] = "bafedc"; static void testInverseEndianness(int order, const char *expect) { testDiag("check byte swapping features order=%d", order); epics::auto_ptr<ByteBuffer> buf(new ByteBuffer(32,order)); buf->putShort(0x6162); buf->putInt(0x63646566); testOk1(strncmp(buf->getArray(),expect,6)==0); buf->flip(); testOk1(buf->getShort()==0x6162); testOk1(buf->getInt()==0x63646566); } static void testSwap() { testDiag("Check epics::pvData::swap<T>(v)"); testOk1(swap<uint8>(0x80)==0x80); testOk1(swap<uint16>(0x7080)==0x8070); testOk1(swap<uint32>(0x10203040)==0x40302010); uint64 a = 0x10203040, b = 0x80706050; a <<= 32; b <<= 32; a |= 0x50607080; b |= 0x40302010; testOk1(swap<uint64>(a)==b); } static void testUnaligned() { testDiag("test correctness of unaligned access"); ByteBuffer buf(32, EPICS_ENDIAN_BIG); // malloc() should give us a buffer aligned to at least native integer size buf.align(sizeof(int)); testOk1(buf.getPosition()==0); buf.clear(); buf.put<uint8>(0x42); buf.put<uint16>(0x1020); buf.align(2, '\x41'); testOk1(buf.getPosition()==4); testOk1(memcmp(buf.getBuffer(), "\x42\x10\x20\x41", 4)==0); buf.clear(); buf.put<uint8>(0x42); buf.put<uint32>(0x12345678); buf.align(4, '\x41'); testOk1(buf.getPosition()==8); testOk1(memcmp(buf.getBuffer(), "\x42\x12\x34\x56\x78\x41\x41\x41", 8)==0); buf.clear(); buf.put<uint8>(0x42); uint64 val = 0x12345678; val<<=32; val |= 0x90abcdef; buf.put<uint64>(val); buf.align(8, '\x41'); testOk1(buf.getPosition()==16); testOk1(memcmp(buf.getBuffer(), "\x42\x12\x34\x56\x78\x90\xab\xcd\xef\x41\x41\x41", 8)==0); } static void testArrayLE() { testDiag("testArray() LE"); ByteBuffer buf(8, EPICS_ENDIAN_LITTLE); std::vector<uint32> vals; vals.push_back(0x12345678); vals.push_back(0x01020304); buf.putArray(&vals[0], vals.size()); testEqual(buf.getPosition(), 8u); testOk1(memcmp(buf.getBuffer(), "\x78\x56\x34\x12\x04\x03\x02\x01", 8)==0); buf.clear(); buf.put("\x40\x30\x20\x10\xa4\xa3\xa2\xa1", 0, 8); buf.flip(); buf.getArray(&vals[0], 2); testEqual(vals[0], 0x10203040u); testEqual(vals[1], 0xa1a2a3a4u); } static void testArrayBE() { testDiag("testArray() BE"); ByteBuffer buf(8, EPICS_ENDIAN_BIG); std::vector<uint32> vals; vals.push_back(0x12345678u); vals.push_back(0x01020304u); buf.putArray(&vals[0], vals.size()); testEqual(buf.getPosition(), 8u); testOk1(memcmp(buf.getBuffer(), "\x12\x34\x56\x78\x01\x02\x03\x04", 8)==0); buf.clear(); buf.put("\x10\x20\x30\x40\xa1\xa2\xa3\xa4", 0, 8); buf.flip(); buf.getArray(&vals[0], 2); testEqual(vals[0], 0x10203040u); testEqual(vals[1], 0xa1a2a3a4u); } MAIN(testByteBuffer) { testPlan(104); testDiag("Tests byteBuffer"); testBasicOperations(); testInverseEndianness(EPICS_ENDIAN_BIG, expect_be); testInverseEndianness(EPICS_ENDIAN_LITTLE, expect_le); testSwap(); testUnaligned(); testArrayLE(); testArrayBE(); return testDone(); }
25.0721
95
0.61978
[ "vector" ]
3840f01e227265284caf1f408b44de754248a2cd
3,692
hpp
C++
tests/benchdnn/parser.hpp
heagoo/mkl-dnn
c7d30404d31d8873310dd4de45f16edbf5deb228
[ "Apache-2.0" ]
null
null
null
tests/benchdnn/parser.hpp
heagoo/mkl-dnn
c7d30404d31d8873310dd4de45f16edbf5deb228
[ "Apache-2.0" ]
null
null
null
tests/benchdnn/parser.hpp
heagoo/mkl-dnn
c7d30404d31d8873310dd4de45f16edbf5deb228
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #ifndef _PARSER_HPP #define _PARSER_HPP #include <stdlib.h> #include <stdio.h> #include <string> #include "mkldnn.h" #include "mkldnn_memory.hpp" namespace parser { static const auto eol = std::string::npos; template <typename T, typename F> static bool parse_vector_str(T &vec, F process_func, const char *str) { const std::string s = str; vec.clear(); for (size_t start = 0, comma = 0; comma != eol; start = comma + 1) { comma = s.find_first_of(',', start); size_t val_len = (comma == eol ? s.size() : comma) - start; assert(val_len < 32); char value[32] = ""; s.copy(value, val_len, start); vec.push_back(process_func(value)); } return true; } template <typename T, typename F> static bool parse_vector_option(T &vec, F process_func, const char *str, const std::string &option_name) { const std::string pattern = "--" + option_name + "="; if (pattern.find(str, 0, pattern.size()) != eol) return parse_vector_str(vec, process_func, str + pattern.size()); return false; } template <typename T, typename F> static bool parse_single_value_option(T &val, F process_func, const char *str, const std::string &option_name) { const std::string pattern = "--" + option_name + "="; if (pattern.find(str, 0, pattern.size()) != eol) return val = process_func(str + pattern.size()), true; return false; } bool parse_dir(std::vector<dir_t> &dir, const char *str, const std::string &option_name = "dir"); bool parse_dt(std::vector<mkldnn_data_type_t> &dt, const char *str, const std::string &option_name = "dt"); bool parse_tag(std::vector<mkldnn_format_tag_t> &tag, const char *str, const std::string &option_name = "tag"); bool parse_mb(std::vector<int64_t> &mb, const char *str, const std::string &option_name = "mb"); bool parse_attr(attr_t &attr, const char *str, const std::string &option_name = "attr"); bool parse_axis(std::vector<int> &axis, const char *str, const std::string &option_name = "axis"); bool parse_test_pattern_match(const char *&match, const char *str, const std::string &option_name = "match"); bool parse_skip_impl(const char *&skip_impl, const char *str, const std::string &option_name = "skip-impl"); bool parse_allow_unimpl(bool &allow_unimpl, const char *str, const std::string &option_name = "allow-unimpl"); bool parse_perf_template(const char *&pt, const char *pt_def, const char *pt_csv, const char *str, const std::string &option_name = "perf-template"); bool parse_reset(void (*reset_func)(), const char *str, const std::string &option_name = "reset"); bool parse_batch(const bench_f bench, const char *str, const std::string &option_name = "batch"); bool parse_bench_settings(const char *str); void catch_unknown_options(const char *str, const char *driver_name); } #endif
34.185185
80
0.651408
[ "vector" ]
384243ce01fba1d878828109f6af5c4917e23a0f
4,947
hpp
C++
src/app.hpp
icetingyu/invokeEscreen
d5d215f6e8d5ab47f70556d0bf7c133d76c708cc
[ "Apache-2.0" ]
1
2021-04-05T19:11:13.000Z
2021-04-05T19:11:13.000Z
src/app.hpp
icetingyu/invokeEscreen
d5d215f6e8d5ab47f70556d0bf7c133d76c708cc
[ "Apache-2.0" ]
null
null
null
src/app.hpp
icetingyu/invokeEscreen
d5d215f6e8d5ab47f70556d0bf7c133d76c708cc
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2012, 2013 BlackBerry Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef APP_HPP #define APP_HPP #include <bb/cascades/GroupDataModel> #include <bb/system/CardDoneMessage> #include <bb/system/InvokeManager> #include <bb/system/SystemDialog.hpp> #include <bb/cascades/Invocation> #include <bb/cascades/InvokeQuery> #include <QObject> /*! * @brief Application GUI object */ //! [0] class App: public QObject { Q_OBJECT // The properties to configure an invocation request Q_PROPERTY(int targetType READ targetType WRITE setTargetType NOTIFY targetTypeChanged) Q_PROPERTY(QString action READ action WRITE setAction NOTIFY actionChanged) Q_PROPERTY(QString mimeType READ mimeType WRITE setMimeType NOTIFY mimeTypeChanged) Q_PROPERTY(QString uri READ uri WRITE setUri NOTIFY uriChanged) Q_PROPERTY(QString data READ data WRITE setData NOTIFY dataChanged) Q_PROPERTY(QString target READ target WRITE setTarget NOTIFY targetChanged) // The model property that lists the invocation targets query results Q_PROPERTY(bb::cascades::GroupDataModel* model READ model CONSTANT) // The current error message Q_PROPERTY(QString errorMessage READ errorMessage NOTIFY errorMessageChanged) // The current status message Q_PROPERTY(QString statusMessage READ statusMessage NOTIFY statusMessageChanged) public: App(QObject *parent = 0); public Q_SLOTS: // This method is called to invoke another application with the current configuration void invoke(); // This method is called to query for all applications that can be invoked with the current configuration void query(); // This method invokes the menu service with the Invoke Request. Only works with platform actions such as SET, SHARE, OPEN etc. void platformInvoke(); // This method is called to invoke a specific application with the given @p target id void invokeTarget(const QString &target); // This method clears the current error message void clearError(); // This method shows an error dialog with he current error message void showErrorDialog(); Q_SIGNALS: // The change notification signals of the properties void targetTypeChanged(); void actionChanged(); void mimeTypeChanged(); void uriChanged(); void dataChanged(); void targetChanged(); void errorMessageChanged(); void statusMessageChanged(); // This signal is emitted if the query() call was successful void queryFinished(); // This signal is emitted to trigger a close of the query result sheet void closeQueryResults(); private Q_SLOTS: // This slot handles the result of an invocation void processInvokeReply(); // This slot handles the result of a target query void processQueryReply(); // This slot updates the status message if the user has started to peek an invoked card void peekStarted(bb::system::CardPeek::Type); // This slot updates the status message if the user has finished to peek an invoked card void peekEnded(); // This slot updates the status message when the invocation of a card is done void childCardDone(const bb::system::CardDoneMessage&); // This slot triggers the platform invocation via m_invocation void onArmed(); private: // The accessor methods of the properties int targetType() const; void setTargetType(int targetType); QString action() const; void setAction(const QString &action); QString mimeType() const; void setMimeType(const QString &mimeType); QString uri() const; void setUri(const QString &uri); QString data() const; void setData(const QString &data); QString target() const; void setTarget(const QString &target); bb::cascades::GroupDataModel* model() const; QString errorMessage() const; QString statusMessage() const; // The property values int m_targetType; QString m_action; QString m_mimeType; QString m_uri; QString m_data; QString m_target; bb::cascades::GroupDataModel* m_model; QString m_errorMessage; QString m_statusMessage; // The error dialog bb::system::SystemDialog* m_dialog; // The central object to manage invocations bb::system::InvokeManager* m_invokeManager; // The Invocation object for platform ivnocations bb::cascades::Invocation* m_invocation; }; //! [0] #endif
32.98
131
0.732161
[ "object", "model" ]
3845d64aa31a595fe54b8f64b69077d5854144f7
5,444
cpp
C++
Modules/ThirdParty/OssimPlugins/src/ossim/AlosPalsar/AlosPalsarData.cpp
xcorail/OTB
092a93654c3b5d009e420f450fe9b675f737cdca
[ "Apache-2.0" ]
2
2018-03-30T18:05:55.000Z
2020-08-28T01:03:49.000Z
Modules/ThirdParty/OssimPlugins/src/ossim/AlosPalsar/AlosPalsarData.cpp
xcorail/OTB
092a93654c3b5d009e420f450fe9b675f737cdca
[ "Apache-2.0" ]
3
2015-10-14T10:11:38.000Z
2015-10-15T08:26:23.000Z
Modules/ThirdParty/OssimPlugins/src/ossim/AlosPalsar/AlosPalsarData.cpp
xcorail/OTB
092a93654c3b5d009e420f450fe9b675f737cdca
[ "Apache-2.0" ]
2
2015-10-08T12:04:06.000Z
2018-06-19T08:00:47.000Z
/* * Copyright (C) 2005-2017 by Centre National d'Etudes Spatiales (CNES) * Copyright (C) 2008-2010 by Centre for Remote Imaging, Sensing and Processing (CRISP) * * This file is licensed under MIT license: * * 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 <AlosPalsar/AlosPalsarData.h> #include <AlosPalsar/AlosPalsarRecordHeader.h> #include <AlosPalsar/AlosPalsarDataFileDescriptor.h> #include <AlosPalsar/AlosPalsarSignalData.h> #include <ossim/base/ossimTrace.h> #include <ossim/base/ossimKeywordlist.h> #include <ossim/base/ossimKeywordNames.h> // Static trace for debugging static ossimTrace traceDebug("ossimAlosPalsarData:debug"); namespace ossimplugins { const int AlosPalsarData::AlosPalsarDataFileDescriptorID = 1; const int AlosPalsarData::AlosPalsarSignalDataID = 2; AlosPalsarData::AlosPalsarData() { } AlosPalsarData::~AlosPalsarData() { ClearRecords(); } std::ostream& operator<<(std::ostream& os, const AlosPalsarData& data) { std::map<int, AlosPalsarRecord*>::const_iterator it = data._records.begin(); while (it != data._records.end()) { (*it).second->Write(os); ++it; } return os; } std::istream& operator>>(std::istream& is, AlosPalsarData& data) { data.ClearRecords(); AlosPalsarRecordHeader header; is >> header; AlosPalsarRecord* record = new AlosPalsarDataFileDescriptor; if (record != NULL) { record->Read(is); data._records[header.get_rec_seq()] = record; } else { char* buff = new char[header.get_length()-12]; is.read(buff, header.get_length() - 12); delete buff; } std::streampos filePosition; filePosition = is.tellg(); is >> header; record = new AlosPalsarSignalData; if (record != NULL) { record->Read(is); data._records[header.get_rec_seq()] = record; // std::cout << "Record sequence number = " << header.get_rec_seq() << std::endl; } is.seekg(filePosition); // Rewind file pointer to start of record // Then, advance pointer to next record is.seekg(static_cast<std::streamoff>(header.get_length()), std::ios::cur); return is; } AlosPalsarData::AlosPalsarData(const AlosPalsarData& rhs) { std::map<int, AlosPalsarRecord*>::const_iterator it = rhs._records.begin(); while (it != rhs._records.end()) { _records[(*it).first] = (*it).second->Clone(); ++it; } } AlosPalsarData& AlosPalsarData::operator=(const AlosPalsarData& rhs) { ClearRecords(); std::map<int, AlosPalsarRecord*>::const_iterator it = rhs._records.begin(); while (it != rhs._records.end()) { _records[(*it).first] = (*it).second->Clone(); ++it; } return *this; } void AlosPalsarData::ClearRecords() { std::map<int, AlosPalsarRecord*>::const_iterator it = _records.begin(); while (it != _records.end()) { delete(*it).second; ++it; } _records.clear(); } bool AlosPalsarData::saveState(ossimKeywordlist& kwl, const char* prefix) const { static const char MODULE[] = "AlosPalsarData::saveState"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } bool result = true; /* * Adding metadata necessary to the sensor model in the keywordlist */ const AlosPalsarDataFileDescriptor *datafiledesc = get_AlosPalsarDataFileDescriptor(); if (datafiledesc != NULL) { kwl.add(prefix, "num_lines", datafiledesc->get_num_lines(), true); kwl.add(prefix, "num_pix_in_line", datafiledesc->get_num_pix_in_line(), true); } else { result = false; } const AlosPalsarSignalData *signalData = get_AlosPalsarSignalData(); if (datafiledesc != NULL) { kwl.add(prefix, "pulse_repetition_frequency", signalData->get_pulse_repetition_frequency(), true); // slant range to 1st data sample in meters kwl.add(prefix, "slant_range_to_1st_data_sample", signalData->get_slant_range_to_1st_data_sample(), true); } else { result = false; } return result; } const AlosPalsarDataFileDescriptor * AlosPalsarData::get_AlosPalsarDataFileDescriptor() const { return dynamic_cast<const AlosPalsarDataFileDescriptor*>(_records.find(AlosPalsarDataFileDescriptorID)->second); } const AlosPalsarSignalData * AlosPalsarData::get_AlosPalsarSignalData() const { // TODO: Check if _records[AlosPalsarSignalDataID] works return dynamic_cast<const AlosPalsarSignalData*>(_records.find(AlosPalsarSignalDataID)->second); } }
27.084577
114
0.715467
[ "model" ]
38466fb950db304deb66c599b7b16e396496f883
8,836
hpp
C++
include/System/IO/UnexceptionalStreamReader.hpp
sc2ad/BeatSaber-Quest-Codegen
ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab
[ "Unlicense" ]
23
2020-08-07T04:09:00.000Z
2022-03-31T22:10:29.000Z
include/System/IO/UnexceptionalStreamReader.hpp
sc2ad/BeatSaber-Quest-Codegen
ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab
[ "Unlicense" ]
6
2021-09-29T23:47:31.000Z
2022-03-30T20:49:23.000Z
include/System/IO/UnexceptionalStreamReader.hpp
sc2ad/BeatSaber-Quest-Codegen
ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab
[ "Unlicense" ]
17
2020-08-20T19:36:52.000Z
2022-03-30T18:28:24.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: System.IO.StreamReader #include "System/IO/StreamReader.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" #include "extern/beatsaber-hook/shared/utils/typedefs-array.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::IO namespace System::IO { // Forward declaring type: Stream class Stream; } // Forward declaring namespace: System::Text namespace System::Text { // Forward declaring type: Encoding class Encoding; } // Completed forward declares // Type namespace: System.IO namespace System::IO { // Forward declaring type: UnexceptionalStreamReader class UnexceptionalStreamReader; } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(System::IO::UnexceptionalStreamReader); DEFINE_IL2CPP_ARG_TYPE(System::IO::UnexceptionalStreamReader*, "System.IO", "UnexceptionalStreamReader"); // Type namespace: System.IO namespace System::IO { // Size: 0x68 #pragma pack(push, 1) // Autogenerated type: System.IO.UnexceptionalStreamReader // [TokenAttribute] Offset: FFFFFFFF class UnexceptionalStreamReader : public System::IO::StreamReader { public: // Get static field: static private System.Boolean[] newline static ::ArrayW<bool> _get_newline(); // Set static field: static private System.Boolean[] newline static void _set_newline(::ArrayW<bool> value); // Get static field: static private System.Char newlineChar static ::Il2CppChar _get_newlineChar(); // Set static field: static private System.Char newlineChar static void _set_newlineChar(::Il2CppChar value); // private System.Boolean CheckEOL(System.Char current) // Offset: 0x19ED8B8 bool CheckEOL(::Il2CppChar current); // static private System.Void .cctor() // Offset: 0x19ED398 // Implemented from: System.IO.StreamReader // Base method: System.Void StreamReader::.cctor() // Base method: System.Void TextReader::.cctor() static void _cctor(); // public System.Void .ctor(System.IO.Stream stream, System.Text.Encoding encoding) // Offset: 0x19ED43C // Implemented from: System.IO.StreamReader // Base method: System.Void StreamReader::.ctor(System.IO.Stream stream, System.Text.Encoding encoding) template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static UnexceptionalStreamReader* New_ctor(System::IO::Stream* stream, System::Text::Encoding* encoding) { static auto ___internal__logger = ::Logger::get().WithContext("System::IO::UnexceptionalStreamReader::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<UnexceptionalStreamReader*, creationType>(stream, encoding))); } // public override System.Int32 Peek() // Offset: 0x19ED4BC // Implemented from: System.IO.StreamReader // Base method: System.Int32 StreamReader::Peek() int Peek(); // public override System.Int32 Read() // Offset: 0x19ED57C // Implemented from: System.IO.StreamReader // Base method: System.Int32 StreamReader::Read() int Read(); // public override System.Int32 Read(in System.Char[] dest_buffer, System.Int32 index, System.Int32 count) // Offset: 0x19ED63C // Implemented from: System.IO.StreamReader // Base method: System.Int32 StreamReader::Read(in System.Char[] dest_buffer, System.Int32 index, System.Int32 count) int Read(ByRef<::ArrayW<::Il2CppChar>> dest_buffer, int index, int count); // public override System.String ReadLine() // Offset: 0x19EDAA8 // Implemented from: System.IO.StreamReader // Base method: System.String StreamReader::ReadLine() ::Il2CppString* ReadLine(); // public override System.String ReadToEnd() // Offset: 0x19EDB68 // Implemented from: System.IO.StreamReader // Base method: System.String StreamReader::ReadToEnd() ::Il2CppString* ReadToEnd(); }; // System.IO.UnexceptionalStreamReader #pragma pack(pop) } #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: System::IO::UnexceptionalStreamReader::CheckEOL // Il2CppName: CheckEOL template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::IO::UnexceptionalStreamReader::*)(::Il2CppChar)>(&System::IO::UnexceptionalStreamReader::CheckEOL)> { static const MethodInfo* get() { static auto* current = &::il2cpp_utils::GetClassFromName("System", "Char")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::IO::UnexceptionalStreamReader*), "CheckEOL", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{current}); } }; // Writing MetadataGetter for method: System::IO::UnexceptionalStreamReader::_cctor // Il2CppName: .cctor template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)()>(&System::IO::UnexceptionalStreamReader::_cctor)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::IO::UnexceptionalStreamReader*), ".cctor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::IO::UnexceptionalStreamReader::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: System::IO::UnexceptionalStreamReader::Peek // Il2CppName: Peek template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::IO::UnexceptionalStreamReader::*)()>(&System::IO::UnexceptionalStreamReader::Peek)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::IO::UnexceptionalStreamReader*), "Peek", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::IO::UnexceptionalStreamReader::Read // Il2CppName: Read template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::IO::UnexceptionalStreamReader::*)()>(&System::IO::UnexceptionalStreamReader::Read)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::IO::UnexceptionalStreamReader*), "Read", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::IO::UnexceptionalStreamReader::Read // Il2CppName: Read template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::IO::UnexceptionalStreamReader::*)(ByRef<::ArrayW<::Il2CppChar>>, int, int)>(&System::IO::UnexceptionalStreamReader::Read)> { static const MethodInfo* get() { static auto* dest_buffer = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Char"), 1)->this_arg; static auto* index = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* count = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::IO::UnexceptionalStreamReader*), "Read", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{dest_buffer, index, count}); } }; // Writing MetadataGetter for method: System::IO::UnexceptionalStreamReader::ReadLine // Il2CppName: ReadLine template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppString* (System::IO::UnexceptionalStreamReader::*)()>(&System::IO::UnexceptionalStreamReader::ReadLine)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::IO::UnexceptionalStreamReader*), "ReadLine", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::IO::UnexceptionalStreamReader::ReadToEnd // Il2CppName: ReadToEnd template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppString* (System::IO::UnexceptionalStreamReader::*)()>(&System::IO::UnexceptionalStreamReader::ReadToEnd)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::IO::UnexceptionalStreamReader*), "ReadToEnd", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } };
54.208589
207
0.723857
[ "vector" ]
384678b15d26bf5f59e1c29682ac8de43fcf3237
4,063
cpp
C++
tests/vocabulary_map_test.cpp
Bungarch/meta
c0c4fc7fe78e8e910cecd31bf85f7f9da829cce5
[ "MIT" ]
null
null
null
tests/vocabulary_map_test.cpp
Bungarch/meta
c0c4fc7fe78e8e910cecd31bf85f7f9da829cce5
[ "MIT" ]
null
null
null
tests/vocabulary_map_test.cpp
Bungarch/meta
c0c4fc7fe78e8e910cecd31bf85f7f9da829cce5
[ "MIT" ]
null
null
null
/** * @file vocabulary_map_test.cpp * @author Sean Massung * @author Chase Geigle */ #include <iostream> #include "bandit/bandit.h" #include "meta/io/binary.h" #include "meta/io/filesystem.h" #include "meta/index/vocabulary_map_writer.h" #include "meta/index/vocabulary_map.h" #include "meta/util/disk_vector.h" #include "meta/util/optional.h" using namespace bandit; using namespace snowhouse; using namespace meta; namespace { void write_file(uint16_t size) { index::vocabulary_map_writer writer{"meta-tmp-test.bin", size}; auto str = std::string{"abcdefghijklmn"}; for (const auto& c : str) writer.insert(std::string(1, c)); } void assert_correctness(uint16_t size) { std::vector<std::pair<std::string, uint64_t>> expected = {{"a", 0}, {"b", 1}, {"c", 2}, {"d", 3}, {"e", 4}, {"f", 5}, {"g", 6}, {"h", 7}, {"i", 8}, {"j", 9}, {"k", 10}, {"l", 11}, {"m", 12}, {"n", 13}}; // second level expected.push_back({"a", size * 0}); expected.push_back({"c", size * 1}); expected.push_back({"e", size * 2}); expected.push_back({"g", size * 3}); expected.push_back({"i", size * 4}); expected.push_back({"k", size * 5}); expected.push_back({"m", size * 6}); // third level expected.push_back({"a", size * 7}); expected.push_back({"e", size * 8}); expected.push_back({"i", size * 9}); expected.push_back({"m", size * 10}); // root expected.push_back({"a", size * 11}); expected.push_back({"i", size * 12}); { std::ifstream file{"meta-tmp-test.bin", std::ios::binary}; util::disk_vector<uint64_t> inverse{"meta-tmp-test.bin.inverse", 14}; std::size_t idx = 0; while (file) { // skip over padding if (file.tellg() % size != 0 && file.peek() == '\0') file.seekg(size - (file.tellg() % size), file.cur); // checks that the inverse map contains the correct position of // the terms in the lowest level if (idx < 14) AssertThat(inverse[idx], Equals(static_cast<uint64_t>(file.tellg()))); std::string term; uint64_t num; io::read_binary(file, term); if (!file) break; io::read_binary(file, num); if (!file) break; AssertThat(term, Equals(expected[idx].first)); AssertThat(num, Equals(expected[idx].second)); ++idx; } AssertThat(file.fail(), IsTrue()); AssertThat(idx, Equals(expected.size())); } filesystem::delete_file("meta-tmp-test.bin"); filesystem::delete_file("meta-tmp-test.bin.inverse"); } void read_file(uint16_t size) { std::vector<std::pair<std::string, uint64_t>> expected = {{"a", 0}, {"b", 1}, {"c", 2}, {"d", 3}, {"e", 4}, {"f", 5}, {"g", 6}, {"h", 7}, {"i", 8}, {"j", 9}, {"k", 10}, {"l", 11}, {"m", 12}, {"n", 13}}; index::vocabulary_map map{"meta-tmp-test.bin", size}; for (const auto& p : expected) { auto elem = map.find(p.first); AssertThat(static_cast<bool>(elem), IsTrue()); AssertThat(*elem, Equals(p.second)); AssertThat(map.find_term(term_id{p.second}), Equals(p.first)); } AssertThat(static_cast<bool>(map.find("0")), IsFalse()); AssertThat(static_cast<bool>(map.find("zabawe")), IsFalse()); AssertThat(map.size(), Equals(14ul)); } } go_bandit([]() { describe("[vocabulary-map]", []() { it("should write full blocks", []() { write_file(20); assert_correctness(20); }); it("should write partial blocks", []() { write_file(23); assert_correctness(23); }); it("should read full blocks", []() { write_file(20); read_file(20); }); it("should read partial blocks", []() { write_file(23); read_file(23); }); }); });
30.320896
77
0.532857
[ "vector" ]
38470b9c42d962ed8c9c0e92126b139a9473a539
4,549
cpp
C++
amr-wind/utilities/sampling/KineticEnergy.cpp
jrood-nrel/amr-wind
c1531ecc7ccccef0956cb72e3461535375dbe4f6
[ "BSD-3-Clause" ]
null
null
null
amr-wind/utilities/sampling/KineticEnergy.cpp
jrood-nrel/amr-wind
c1531ecc7ccccef0956cb72e3461535375dbe4f6
[ "BSD-3-Clause" ]
null
null
null
amr-wind/utilities/sampling/KineticEnergy.cpp
jrood-nrel/amr-wind
c1531ecc7ccccef0956cb72e3461535375dbe4f6
[ "BSD-3-Clause" ]
1
2022-02-16T04:14:50.000Z
2022-02-16T04:14:50.000Z
#include "amr-wind/utilities/sampling/KineticEnergy.H" #include "amr-wind/utilities/io_utils.H" #include "amr-wind/utilities/ncutils/nc_interface.H" #include <AMReX_MultiFabUtil.H> #include <utility> #include "AMReX_ParmParse.H" #include "amr-wind/utilities/IOManager.H" namespace amr_wind { namespace kinetic_energy { KineticEnergy::KineticEnergy(CFDSim& sim, std::string label) : m_sim(sim) , m_label(std::move(label)) , m_velocity(sim.repo().get_field("velocity")) , m_density(sim.repo().get_field("density")) {} KineticEnergy::~KineticEnergy() = default; void KineticEnergy::initialize() { BL_PROFILE("amr-wind::KineticEnergy::initialize"); amrex::ParmParse pp(m_label); pp.query("output_frequency", m_out_freq); prepare_ascii_file(); } amrex::Real KineticEnergy::calculate_kinetic_energy() { BL_PROFILE("amr-wind::KineticEnergy::calculate_kinetic_energy"); // integrated total Kinetic Energy amrex::Real Kinetic_energy = 0.0; const int finest_level = m_velocity.repo().num_active_levels() - 1; const auto& geom = m_velocity.repo().mesh().Geom(); for (int lev = 0; lev <= finest_level; lev++) { amrex::iMultiFab level_mask; if (lev < finest_level) { level_mask = makeFineMask( m_sim.mesh().boxArray(lev), m_sim.mesh().DistributionMap(lev), m_sim.mesh().boxArray(lev + 1), amrex::IntVect(2), 1, 0); } else { level_mask.define( m_sim.mesh().boxArray(lev), m_sim.mesh().DistributionMap(lev), 1, 0, amrex::MFInfo()); level_mask.setVal(1); } const amrex::Real cell_vol = geom[lev].CellSize()[0] * geom[lev].CellSize()[1] * geom[lev].CellSize()[2]; Kinetic_energy += amrex::ReduceSum( m_density(lev), m_velocity(lev), level_mask, 0, [=] AMREX_GPU_HOST_DEVICE( amrex::Box const& bx, amrex::Array4<amrex::Real const> const& den_arr, amrex::Array4<amrex::Real const> const& vel_arr, amrex::Array4<int const> const& mask_arr) -> amrex::Real { amrex::Real Kinetic_Energy_Fab = 0.0; amrex::Loop( bx, [=, &Kinetic_Energy_Fab](int i, int j, int k) noexcept { Kinetic_Energy_Fab += cell_vol * mask_arr(i, j, k) * den_arr(i, j, k) * (vel_arr(i, j, k, 0) * vel_arr(i, j, k, 0) + vel_arr(i, j, k, 1) * vel_arr(i, j, k, 1) + vel_arr(i, j, k, 2) * vel_arr(i, j, k, 2)); }); return Kinetic_Energy_Fab; }); } // total volume of grid on level 0 const amrex::Real total_vol = geom[0].ProbDomain().volume(); Kinetic_energy *= 0.5 / total_vol; amrex::ParallelDescriptor::ReduceRealSum(Kinetic_energy); return Kinetic_energy; } void KineticEnergy::post_advance_work() { BL_PROFILE("amr-wind::KineticEnergy::post_advance_work"); const auto& time = m_sim.time(); const int tidx = time.time_index(); // Skip processing if it is not an output timestep if (!(tidx % m_out_freq == 0)) return; m_total_kinetic_energy = calculate_kinetic_energy(); write_ascii(); } void KineticEnergy::prepare_ascii_file() { BL_PROFILE("amr-wind::KineticEnergy::prepare_ascii_file"); const std::string post_dir = "post_processing"; const std::string sname = amrex::Concatenate(m_label, m_sim.time().time_index()); if (!amrex::UtilCreateDirectory(post_dir, 0755)) { amrex::CreateDirectoryFailed(post_dir); } m_out_fname = post_dir + "/" + sname + ".txt"; if (amrex::ParallelDescriptor::IOProcessor()) { std::ofstream f(m_out_fname.c_str()); f << "time_step time kinetic_energy" << std::endl; f.close(); } } void KineticEnergy::write_ascii() { BL_PROFILE("amr-wind::KineticEnergy::write_ascii"); if (amrex::ParallelDescriptor::IOProcessor()) { std::ofstream f(m_out_fname.c_str(), std::ios_base::app); f << m_sim.time().time_index() << std::scientific << std::setprecision(m_precision) << std::setw(m_width) << m_sim.time().new_time(); f << std::setw(m_width) << m_total_kinetic_energy; f << std::endl; f.close(); } } } // namespace kinetic_energy } // namespace amr_wind
32.726619
80
0.595296
[ "mesh" ]
384a93a69d5eaca9445a821d3c55baba11c35767
1,587
cpp
C++
C++/706.cpp
TianChenjiang/LeetCode
a680c90bc968eba5aa76c3674af1f2d927986ec7
[ "MIT" ]
1
2021-08-31T08:53:47.000Z
2021-08-31T08:53:47.000Z
C++/706.cpp
TianChenjiang/LeetCode
a680c90bc968eba5aa76c3674af1f2d927986ec7
[ "MIT" ]
null
null
null
C++/706.cpp
TianChenjiang/LeetCode
a680c90bc968eba5aa76c3674af1f2d927986ec7
[ "MIT" ]
null
null
null
class MyHashMap { public: /** Initialize your data structure here. */ const static int base = 769; vector<list<pair<int,int>>> data; static int hash (int key) { return key % base; } MyHashMap() : data(base) { } /** value will always be non-negative. */ void put(int key, int value) { int hashKey = hash(key); for (auto it = data[hashKey].begin(); it != data[hashKey].end(); it++) { if ((*it).first == key) { (*it).second = value; return; } } data[hashKey].push_back(make_pair(key,value)); } /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */ int get(int key) { int hashKey = hash(key); for (auto it = data[hashKey].begin(); it != data[hashKey].end(); it++) { if ((*it).first == key) { return (*it).second; } } return -1; } /** Removes the mapping of the specified value key if this map contains a mapping for the key */ void remove(int key) { int hashKey = hash(key); for (auto it = data[hashKey].begin(); it != data[hashKey].end(); it++) { if ((*it).first == key) { data[hashKey].erase(it); return; } } } }; /** * Your MyHashMap object will be instantiated and called as such: * MyHashMap* obj = new MyHashMap(); * obj->put(key,value); * int param_2 = obj->get(key); * obj->remove(key); */
29.388889
116
0.514178
[ "object", "vector" ]
384d1c9f64624680f5dd5dede6635912ec311a5d
30,901
cpp
C++
explorer/adapter.cpp
anatolse/beam
43c4ce0011598641d9cdeffbfdee66fde0a49730
[ "Apache-2.0" ]
null
null
null
explorer/adapter.cpp
anatolse/beam
43c4ce0011598641d9cdeffbfdee66fde0a49730
[ "Apache-2.0" ]
null
null
null
explorer/adapter.cpp
anatolse/beam
43c4ce0011598641d9cdeffbfdee66fde0a49730
[ "Apache-2.0" ]
null
null
null
// Copyright 2018 The Beam Team // // 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 "adapter.h" #include "node/node.h" #include "core/serialization_adapters.h" #include "bvm/bvm2.h" #include "http/http_msg_creator.h" #include "http/http_json_serializer.h" #include "nlohmann/json.hpp" #include "utility/helpers.h" #include "utility/logger.h" #include "wallet/core/common.h" #include "wallet/core/common_utils.h" #include "wallet/core/wallet.h" #include "wallet/core/wallet_db.h" #include "wallet/client/wallet_client.h" #include "wallet/client/extensions/broadcast_gateway/broadcast_router.h" #include "wallet/core/wallet_network.h" #ifdef BEAM_ATOMIC_SWAP_SUPPORT #include "wallet/client/extensions/offers_board/offers_protocol_handler.h" #include "wallet/client/extensions/offers_board/swap_offers_board.h" #endif // BEAM_ATOMIC_SWAP_SUPPORT namespace beam { namespace explorer { namespace { static const size_t PACKER_FRAGMENTS_SIZE = 4096; static const size_t CACHE_DEPTH = 100000; #ifdef BEAM_ATOMIC_SWAP_SUPPORT const unsigned int FAKE_SEED = 10283UL; const char WALLET_DB_PATH[] = "explorer-wallet.db"; const char WALLET_DB_PASS[] = "1"; #endif // BEAM_ATOMIC_SWAP_SUPPORT const char* hash_to_hex(char* buf, const Merkle::Hash& hash) { return to_hex(buf, hash.m_pData, hash.nBytes); } const char* uint256_to_hex(char* buf, const ECC::uintBig& n) { char* p = to_hex(buf + 2, n.m_pData, n.nBytes); while (p && *p == '0') ++p; if (*p == '\0') --p; *--p = 'x'; *--p = '0'; return p; } const char* difficulty_to_hex(char* buf, const Difficulty& d) { ECC::uintBig raw; d.Unpack(raw); return uint256_to_hex(buf, raw); } struct ResponseCache { io::SharedBuffer status; std::map<Height, io::SharedBuffer> blocks; Height currentHeight=0; explicit ResponseCache(size_t depth) : _depth(depth) {} void compact() { if (blocks.empty() || currentHeight <= _depth) return; Height horizon = currentHeight - _depth; if (blocks.rbegin()->first < horizon) { blocks.clear(); return; } auto b = blocks.begin(); auto it = b; while (it != blocks.end()) { if (it->first >= horizon) break; ++it; } blocks.erase(b, it); } bool get_block(io::SerializedMsg& out, Height h) { const auto& it = blocks.find(h); if (it == blocks.end()) return false; out.push_back(it->second); return true; } void put_block(Height h, const io::SharedBuffer& body) { if (currentHeight - h > _depth) return; compact(); blocks[h] = body; } private: size_t _depth; }; using nlohmann::json; } //namespace class ExchangeRateProvider : public IBroadcastListener { public: ExchangeRateProvider(IBroadcastMsgGateway& broadcastGateway, const wallet::IWalletDB::Ptr& walletDB) : _broadcastGateway(broadcastGateway), _walletDB(walletDB) { PeerID key; if (wallet::BroadcastMsgValidator::stringToPublicKey(wallet::kBroadcastValidatorPublicKey, key)) { _validator.setPublisherKeys( { key } ); } _broadcastGateway.registerListener(BroadcastContentType::ExchangeRates, this); } virtual ~ExchangeRateProvider() = default; std::string getRate(wallet::ExchangeRate::Currency unit, uint64_t height) { if (height >= _preloadStartHeight && height <= _preloadEndHeight) { auto it = std::find_if( _ratesCache.begin(), _ratesCache.end(), [unit, height] (const wallet::ExchangeRateHistoryEntity& rate) { return rate.m_currency == wallet::ExchangeRate::Currency::Beam && rate.m_unit == unit && rate.m_height <= height; }); return it != _ratesCache.end() ? std::to_string(wallet::PrintableAmount(it->m_rate, true)) : "-"; } else { const auto rate = _walletDB->getExchangeRateHistoryEntity( wallet::ExchangeRate::Currency::Beam, unit, height); return rate.m_height ? std::to_string(wallet::PrintableAmount(rate.m_rate, true)) : "-"; } } void preloadRates(uint64_t startHeight, uint64_t endHeight) { _preloadStartHeight = startHeight; _preloadEndHeight = endHeight; const auto btcFirstRate = _walletDB->getExchangeRateHistoryEntity( wallet::ExchangeRate::Currency::Beam, wallet::ExchangeRate::Currency::Bitcoin, startHeight); const auto usdFirstRate = _walletDB->getExchangeRateHistoryEntity( wallet::ExchangeRate::Currency::Beam, wallet::ExchangeRate::Currency::Usd, startHeight); auto minHeight = std::min(btcFirstRate.m_height, usdFirstRate.m_height); _ratesCache = _walletDB->getExchangeRatesHistory(minHeight, endHeight); } // IBroadcastListener implementation bool onMessage(uint64_t unused, BroadcastMsg&& msg) override { Block::SystemState::Full blockState; _walletDB->get_History().get_Tip(blockState); if (!blockState.m_Height) return false; if (_validator.isSignatureValid(msg)) { try { std::vector<wallet::ExchangeRate> rates; if (wallet::fromByteBuffer(msg.m_content, rates)) { for (auto& rate : rates) { wallet::ExchangeRateHistoryEntity rateHistory = rate; rateHistory.m_height = blockState.m_Height; _walletDB->saveExchangeRateHistoryEntity(rateHistory); } } } catch(...) { LOG_WARNING() << "broadcast message processing exception"; return false; } } return true; } private: IBroadcastMsgGateway& _broadcastGateway; wallet::IWalletDB::Ptr _walletDB; wallet::BroadcastMsgValidator _validator; uint64_t _preloadStartHeight = 0; uint64_t _preloadEndHeight = 0; std::vector<wallet::ExchangeRateHistoryEntity> _ratesCache; }; /// Explorer server backend, gets callback on status update and returns json messages for server class Adapter : public Node::IObserver, public IAdapter { public: Adapter(Node& node) : _packer(PACKER_FRAGMENTS_SIZE), _node(node), _nodeBackend(node.get_Processor()), _statusDirty(true), _nodeIsSyncing(true), _cache(CACHE_DEPTH) { init_helper_fragments(); _hook = &node.m_Cfg.m_Observer; _nextHook = *_hook; *_hook = this; if (!wallet::WalletDB::isInitialized(WALLET_DB_PATH)) { ECC::NoLeak<ECC::uintBig> seed; seed.V = FAKE_SEED; _walletDB = wallet::WalletDB::init(WALLET_DB_PATH, SecString(WALLET_DB_PASS), seed, false); } else { _walletDB = wallet::WalletDB::open(WALLET_DB_PATH, SecString(WALLET_DB_PASS)); } _wallet = std::make_shared<wallet::Wallet>(_walletDB); auto nnet = std::make_shared<proto::FlyClient::NetworkStd>(*_wallet); nnet->m_Cfg.m_vNodes.push_back(node.m_Cfg.m_Listen); nnet->Connect(); auto wnet = std::make_shared<wallet::WalletNetworkViaBbs>(*_wallet, nnet, _walletDB); _wallet->AddMessageEndpoint(wnet); _wallet->SetNodeEndpoint(nnet); _broadcastRouter = std::make_shared<BroadcastRouter>(*nnet, *wnet); _exchangeRateProvider = std::make_shared<ExchangeRateProvider>(*_broadcastRouter, _walletDB); #ifdef BEAM_ATOMIC_SWAP_SUPPORT _offerBoardProtocolHandler = std::make_shared<wallet::OfferBoardProtocolHandler>(_walletDB->get_SbbsKdf()); _offersBulletinBoard = std::make_shared<wallet::SwapOffersBoard>( *_broadcastRouter, *_offerBoardProtocolHandler, _walletDB); #endif // BEAM_ATOMIC_SWAP_SUPPORT } virtual ~Adapter() { if (_nextHook) *_hook = _nextHook; } private: void init_helper_fragments() { static const char* s = "[,]\""; io::SharedBuffer buf(s, 4); _leftBrace = buf; _leftBrace.size = 1; _comma = buf; _comma.size = 1; _comma.data ++; _rightBrace = buf; _rightBrace.size = 1; _rightBrace.data += 2; _quote = buf; _quote.size = 1; _quote.data += 3; } /// Returns body for /status request void OnSyncProgress() override { const Node::SyncStatus& s = _node.m_SyncStatus; bool isSyncing = (s.m_Done != s.m_Total); if (isSyncing != _nodeIsSyncing) { _statusDirty = true; _nodeIsSyncing = isSyncing; } if (_nextHook) _nextHook->OnSyncProgress(); } void OnStateChanged() override { const auto& cursor = _nodeBackend.m_Cursor; _cache.currentHeight = cursor.m_Sid.m_Height; _statusDirty = true; if (_nextHook) _nextHook->OnStateChanged(); } void OnRolledBack(const Block::SystemState::ID& id) override { auto& blocks = _cache.blocks; blocks.erase(blocks.lower_bound(id.m_Height), blocks.end()); if (_nextHook) _nextHook->OnRolledBack(id); } bool get_status(io::SerializedMsg& out) override { if (_statusDirty) { const auto& cursor = _nodeBackend.m_Cursor; _cache.currentHeight = cursor.m_Sid.m_Height; NodeDB& db = _nodeBackend.get_DB(); auto shieldedOuts24hAgo = db.GetShieldedCount(cursor.m_Sid.m_Height >= 1440 ? cursor.m_Sid.m_Height - 1440 : 0); auto shieldedPer24h = _nodeBackend.m_Extra.m_ShieldedOutputs - shieldedOuts24hAgo; auto possibleShieldedReadyHours = Rules::get().Shielded.MaxWindowBacklog / 2 / shieldedPer24h * 24; char buf[80]; _sm.clear(); if (!serialize_json_msg( _sm, _packer, json{ { "timestamp", cursor.m_Full.m_TimeStamp }, { "height", _cache.currentHeight }, { "low_horizon", _nodeBackend.m_Extra.m_TxoHi }, { "hash", hash_to_hex(buf, cursor.m_ID.m_Hash) }, { "chainwork", uint256_to_hex(buf, cursor.m_Full.m_ChainWork) }, { "peers_count", _node.get_AcessiblePeerCount() }, { "shielded_outputs_total", _nodeBackend.m_Extra.m_ShieldedOutputs }, { "shielded_outputs_per_24h", shieldedPer24h }, { "shielded_possible_ready_in_hours", possibleShieldedReadyHours } } )) { return false; } _cache.status = io::normalize(_sm, false); _statusDirty = false; _sm.clear(); } out.push_back(_cache.status); return true; } bool extract_row(Height height, uint64_t& row, uint64_t* prevRow) { NodeDB& db = _nodeBackend.get_DB(); NodeDB::WalkerState ws; db.EnumStatesAt(ws, height); while (true) { if (!ws.MoveNext()) { return false; } if (NodeDB::StateFlags::Active & db.GetStateFlags(ws.m_Sid.m_Row)) { row = ws.m_Sid.m_Row; break; } } if (prevRow) { *prevRow = row; if (!db.get_Prev(*prevRow)) { *prevRow = 0; } } return true; } struct ExtraInfo { struct Writer { std::ostringstream m_os; bool m_Empty = true; void Next() { if (m_Empty) m_Empty = false; else m_os << ", "; } void OnAsset(const Asset::Proof* pProof) { if (pProof) { Next(); auto t0 = pProof->m_Begin; m_os << "Asset [" << t0 << "-" << t0 + Rules::get().CA.m_ProofCfg.get_N() - 1 << "]"; } } void OnContract(const bvm2::ContractID&, uint32_t iMethod, const TxKernelContractControl& krn) { m_os << "Contract."; switch (iMethod) { case 0: m_os << "Create"; break; case 1: m_os << "Destroy"; break; default: m_os << "Method_" << iMethod; } m_os << ", Args=" << krn.m_Args.size(); } }; static std::string get(const Asset::Metadata& md) { std::string sMetadata; const ByteBuffer& bb = md.m_Value; // alias sMetadata.reserve(bb.size()); for (size_t i = 0; i < bb.size(); i++) { char ch = bb[i]; if ((ch < 32) || (ch > 126)) ch = '?'; sMetadata.push_back(ch); } return sMetadata; } static std::string get(const Output& outp, Height h, Height hMaturity) { Writer w; if (outp.m_Coinbase) { w.Next(); w.m_os << "Coinbase"; } if (outp.m_pPublic) { w.Next(); w.m_os << "Value=" << outp.m_pPublic->m_Value; } if (outp.m_Incubation) { w.Next(); w.m_os << "Incubation +" << outp.m_Incubation; } if (hMaturity != h) { w.Next(); w.m_os << "Maturity=" << hMaturity; } w.OnAsset(outp.m_pAsset.get()); return w.m_os.str(); } static std::string get(const TxKernel& krn, Amount& fee) { struct MyWalker :public TxKernel::IWalker { Writer m_Wr; Amount m_Fee = 0; virtual bool OnKrn(const TxKernel& krn) override { m_Fee += krn.m_Fee; switch (krn.get_Subtype()) { #define THE_MACRO(id, name) case id: OnKrnEx(Cast::Up<TxKernel##name>(krn)); break; BeamKernelsAll(THE_MACRO) #undef THE_MACRO } return true; } void OnKrnEx(const TxKernelStd& krn) { if (krn.m_pRelativeLock) { m_Wr.Next(); m_Wr.m_os << "Rel.Lock ID=" << krn.m_pRelativeLock->m_ID << " H=" << krn.m_pRelativeLock->m_LockHeight; } if (krn.m_pHashLock) { m_Wr.Next(); m_Wr.m_os << "Hash.Lock Preimage=" << krn.m_pHashLock->m_Value; } } void OnKrnEx(const TxKernelAssetCreate& krn) { m_Wr.Next(); m_Wr.m_os << "Asset.Create MD.Hash=" << krn.m_MetaData.m_Hash; } void OnKrnEx(const TxKernelAssetDestroy& krn) { m_Wr.Next(); m_Wr.m_os << "Asset.Destroy ID=" << krn.m_AssetID; } void OnKrnEx(const TxKernelAssetEmit& krn) { m_Wr.Next(); m_Wr.m_os << "Asset.Emit ID=" << krn.m_AssetID << " Value=" << krn.m_Value; } void OnKrnEx(const TxKernelShieldedOutput& krn) { m_Wr.Next(); m_Wr.m_os << "Shielded.Out"; m_Wr.OnAsset(krn.m_Txo.m_pAsset.get()); } void OnKrnEx(const TxKernelShieldedInput& krn) { uint32_t n = krn.m_SpendProof.m_Cfg.get_N(); TxoID id0 = krn.m_WindowEnd; if (id0 > n) id0 -= n; else id0 = 0; m_Wr.Next(); m_Wr.m_os << "Shielded.In Set=[" << id0 << "-" << krn.m_WindowEnd - 1 << "]"; m_Wr.OnAsset(krn.m_pAsset.get()); } void OnKrnEx(const TxKernelContractCreate& krn) { bvm2::ContractID cid; bvm2::get_Cid(cid, krn.m_Data, krn.m_Args); m_Wr.Next(); m_Wr.OnContract(cid, 0, krn); } void OnKrnEx(const TxKernelContractInvoke& krn) { m_Wr.Next(); m_Wr.OnContract(krn.m_Cid, krn.m_iMethod, krn); } } wlk; if (!krn.m_vNested.empty()) { wlk.m_Wr.Next(); wlk.m_Wr.m_os << "Composite"; } wlk.Process(krn); fee = wlk.m_Fee; return wlk.m_Wr.m_os.str(); } }; bool extract_block_from_row(json& out, uint64_t row, Height height) { NodeDB& db = _nodeBackend.get_DB(); Block::SystemState::Full blockState; Block::SystemState::ID id; Block::Body block; bool ok = true; std::vector<Output::Ptr> vOutsIn; try { db.get_State(row, blockState); blockState.get_ID(id); NodeDB::StateID sid; sid.m_Row = row; sid.m_Height = id.m_Height; _nodeBackend.ExtractBlockWithExtra(block, vOutsIn, sid); } catch (...) { ok = false; } if (ok) { char buf[80]; assert(block.m_vInputs.size() == vOutsIn.size()); json inputs = json::array(); for (size_t i = 0; i < block.m_vInputs.size(); i++) { const Input& inp = *block.m_vInputs[i]; const Output& outp = *vOutsIn[i]; assert(inp.m_Commitment == outp.m_Commitment); Height hCreate = inp.m_Internal.m_Maturity - outp.get_MinMaturity(0); inputs.push_back( json{ {"commitment", uint256_to_hex(buf, outp.m_Commitment.m_X)}, {"height", hCreate}, {"extra", ExtraInfo::get(outp, hCreate, inp.m_Internal.m_Maturity)} } ); } json outputs = json::array(); for (const auto &v : block.m_vOutputs) { outputs.push_back( json{ {"commitment", uint256_to_hex(buf, v->m_Commitment.m_X)}, {"extra", ExtraInfo::get(*v, height, v->get_MinMaturity(height))} } ); } json kernels = json::array(); for (const auto &v : block.m_vKernels) { Amount fee = 0; std::string sExtra = ExtraInfo::get(*v, fee); kernels.push_back( json{ {"id", hash_to_hex(buf, v->m_Internal.m_ID)}, {"minHeight", v->m_Height.m_Min}, {"maxHeight", v->m_Height.m_Max}, {"fee", fee}, {"extra", sExtra} } ); } json assets = json::array(); Asset::Full ai; for (ai.m_ID = 1; ; ai.m_ID++) { int ret = _nodeBackend.get_AssetAt(ai, height); if (!ret) break; if (ret > 0) { assets.push_back( json{ {"id", ai.m_ID}, {"metadata", ExtraInfo::get(ai.m_Metadata)}, {"metahash", hash_to_hex(buf, ai.m_Metadata.m_Hash)}, {"owner", hash_to_hex(buf, ai.m_Owner)}, {"value_lo", AmountBig::get_Lo(ai.m_Value)}, {"value_hi", AmountBig::get_Hi(ai.m_Value)}, {"lock_height", ai.m_LockHeight} } ); } } auto btcRate = _exchangeRateProvider->getRate(wallet::ExchangeRate::Currency::Bitcoin, blockState.m_Height); auto usdRate = _exchangeRateProvider->getRate(wallet::ExchangeRate::Currency::Usd, blockState.m_Height); out = json{ {"found", true}, {"timestamp", blockState.m_TimeStamp}, {"height", blockState.m_Height}, {"hash", hash_to_hex(buf, id.m_Hash)}, {"prev", hash_to_hex(buf, blockState.m_Prev)}, {"difficulty", blockState.m_PoW.m_Difficulty.ToFloat()}, {"chainwork", uint256_to_hex(buf, blockState.m_ChainWork)}, {"subsidy", Rules::get_Emission(blockState.m_Height)}, {"assets", assets}, {"inputs", inputs}, {"outputs", outputs}, {"kernels", kernels}, {"rate_btc", btcRate}, {"rate_usd", usdRate} }; LOG_DEBUG() << out; } return ok; } bool extract_block(json& out, Height height, uint64_t& row, uint64_t* prevRow) { bool ok = true; if (row == 0) { ok = extract_row(height, row, prevRow); } else if (prevRow != 0) { *prevRow = row; if (!_nodeBackend.get_DB().get_Prev(*prevRow)) { *prevRow = 0; } } return ok && extract_block_from_row(out, row, height); } bool get_block_impl(io::SerializedMsg& out, uint64_t height, uint64_t& row, uint64_t* prevRow) { if (_cache.get_block(out, height)) { if (prevRow && row > 0) { extract_row(height, row, prevRow); } return true; } if (_statusDirty) { const auto &cursor = _nodeBackend.m_Cursor; _cache.currentHeight = cursor.m_Sid.m_Height; } io::SharedBuffer body; bool blockAvailable = (height <= _cache.currentHeight); if (blockAvailable) { json j; if (!extract_block(j, height, row, prevRow)) { blockAvailable = false; } else { _sm.clear(); if (serialize_json_msg(_sm, _packer, j)) { body = io::normalize(_sm, false); _cache.put_block(height, body); } else { return false; } _sm.clear(); } } if (blockAvailable) { out.push_back(body); return true; } return serialize_json_msg(out, _packer, json{ { "found", false}, {"height", height } }); } bool json2Msg(const json& obj, io::SerializedMsg& out) { LOG_DEBUG() << obj; _sm.clear(); io::SharedBuffer body; if (serialize_json_msg(_sm, _packer, obj)) { body = io::normalize(_sm, false); } else { return false; } _sm.clear(); out.push_back(body); return true; } bool get_block(io::SerializedMsg& out, uint64_t height) override { uint64_t row=0; return get_block_impl(out, height, row, 0); } bool get_block_by_hash(io::SerializedMsg& out, const ByteBuffer& hash) override { NodeDB& db = _nodeBackend.get_DB(); Height height = db.FindBlock(hash); uint64_t row = 0; return get_block_impl(out, height, row, 0); } bool get_block_by_kernel(io::SerializedMsg& out, const ByteBuffer& key) override { NodeDB& db = _nodeBackend.get_DB(); Height height = db.FindKernel(key); uint64_t row = 0; return get_block_impl(out, height, row, 0); } bool get_blocks(io::SerializedMsg& out, uint64_t startHeight, uint64_t n) override { Height endHeight = startHeight + n - 1; _exchangeRateProvider->preloadRates(startHeight, endHeight); static const uint64_t maxElements = 1500; if (n > maxElements) n = maxElements; else if (n==0) n=1; out.push_back(_leftBrace); uint64_t row = 0; uint64_t prevRow = 0; for (;;) { bool ok = get_block_impl(out, endHeight, row, &prevRow); if (!ok) return false; if (endHeight == startHeight) { break; } out.push_back(_comma); row = prevRow; --endHeight; } out.push_back(_rightBrace); return true; } bool get_peers(io::SerializedMsg& out) override { auto& peers = _node.get_AcessiblePeerAddrs(); out.push_back(_leftBrace); for (auto& peer : peers) { auto addr = peer.get_ParentObj().m_Addr.m_Value.str(); { out.push_back(_quote); out.push_back({ addr.data(), addr.size() }); out.push_back(_quote); } out.push_back(_comma); } // remove last comma if (!peers.empty()) out.pop_back(); out.push_back(_rightBrace); return true; } #ifdef BEAM_ATOMIC_SWAP_SUPPORT bool get_swap_offers(io::SerializedMsg& out) override { auto offers = _offersBulletinBoard->getOffersList(); json result = json::array(); for(auto& offer : offers) { result.push_back( json { {"status", offer.m_status}, {"status_string", swapOfferStatusToString(offer.m_status)}, {"txId", wallet::TxIDToString(offer.m_txId)}, {"beam_amount", std::to_string(wallet::PrintableAmount(offer.amountBeam(), true))}, {"swap_amount", std::to_string(wallet::PrintableAmount(offer.amountSwapCoin(), true))}, {"swap_currency", std::to_string(offer.swapCoinType())}, {"time_created", format_timestamp(wallet::kTimeStampFormat3x3, offer.timeCreated() * 1000, false)}, {"min_height", offer.minHeight()}, {"height_expired", offer.minHeight() + offer.peerResponseHeight()}, }); } return json2Msg(result, out); } bool get_swap_totals(io::SerializedMsg& out) override { auto offers = _offersBulletinBoard->getOffersList(); Amount beamAmount = 0, bitcoinAmount = 0, litecoinAmount = 0, qtumAmount = 0, bitcoinCashAmount = 0, dogecoinAmount = 0, dashAmount = 0; for(auto& offer : offers) { beamAmount += offer.amountBeam(); switch (offer.swapCoinType()) { case wallet::AtomicSwapCoin::Bitcoin : bitcoinAmount += offer.amountSwapCoin(); break; case wallet::AtomicSwapCoin::Litecoin : litecoinAmount += offer.amountSwapCoin(); break; case wallet::AtomicSwapCoin::Qtum : qtumAmount += offer.amountSwapCoin(); break; case wallet::AtomicSwapCoin::Bitcoin_Cash : bitcoinCashAmount += offer.amountSwapCoin(); break; case wallet::AtomicSwapCoin::Dogecoin : dogecoinAmount += offer.amountSwapCoin(); break; case wallet::AtomicSwapCoin::Dash : dashAmount += offer.amountSwapCoin(); break; default : LOG_ERROR() << "Unknown swap coin type"; return false; } } json obj = json{ { "total_swaps_count", offers.size()}, { "beams_offered", std::to_string(wallet::PrintableAmount(beamAmount, true)) }, { "bitcoin_offered", std::to_string(wallet::PrintableAmount(bitcoinAmount, true))}, { "litecoin_offered", std::to_string(wallet::PrintableAmount(litecoinAmount, true))}, { "qtum_offered", std::to_string(wallet::PrintableAmount(qtumAmount, true))}, { "bicoin_cash_offered", std::to_string(wallet::PrintableAmount(bitcoinCashAmount, true))}, { "dogecoin_offered", std::to_string(wallet::PrintableAmount(dogecoinAmount, true))}, { "dash_offered", std::to_string(wallet::PrintableAmount(dashAmount, true))} }; return json2Msg(obj, out); } #endif // BEAM_ATOMIC_SWAP_SUPPORT HttpMsgCreator _packer; // node db interface Node& _node; NodeProcessor& _nodeBackend; // helper fragments io::SharedBuffer _leftBrace, _comma, _rightBrace, _quote; // If true then status boby needs to be refreshed bool _statusDirty; // True if node is syncing at the moment bool _nodeIsSyncing; // node observers chain Node::IObserver** _hook; Node::IObserver* _nextHook; ResponseCache _cache; io::SerializedMsg _sm; wallet::IWalletDB::Ptr _walletDB; wallet::Wallet::Ptr _wallet; std::shared_ptr<wallet::BroadcastRouter> _broadcastRouter; std::shared_ptr<ExchangeRateProvider> _exchangeRateProvider; #ifdef BEAM_ATOMIC_SWAP_SUPPORT std::shared_ptr<wallet::OfferBoardProtocolHandler> _offerBoardProtocolHandler; wallet::SwapOffersBoard::Ptr _offersBulletinBoard; #endif // BEAM_ATOMIC_SWAP_SUPPORT }; IAdapter::Ptr create_adapter(Node& node) { return IAdapter::Ptr(new Adapter(node)); } }} //namespaces
32.323222
127
0.528462
[ "vector" ]
384de19755a4ed14c65c882f92603d0bb6b043cc
10,716
cpp
C++
src/omexmeta/OmexMetaXmlAssistant.cpp
nickerso/libOmexMeta
5088f04726c474e5be49166778aee84af4d08ea5
[ "Apache-2.0" ]
null
null
null
src/omexmeta/OmexMetaXmlAssistant.cpp
nickerso/libOmexMeta
5088f04726c474e5be49166778aee84af4d08ea5
[ "Apache-2.0" ]
null
null
null
src/omexmeta/OmexMetaXmlAssistant.cpp
nickerso/libOmexMeta
5088f04726c474e5be49166778aee84af4d08ea5
[ "Apache-2.0" ]
null
null
null
// // Created by Ciaran on 4/14/2020. // #include "omexmeta/OmexMetaXmlAssistant.h" namespace omexmeta { OmexMetaXmlAssistant::OmexMetaXmlAssistant(std::string xml, std::string metaid_base, int metaid_num_digits, bool generate_new_metaids) : xml_(std::move(xml)), metaid_base_(std::move(metaid_base)), metaid_num_digits_(metaid_num_digits), generate_new_metaids_(generate_new_metaids) { } std::vector<std::string> OmexMetaXmlAssistant::getValidElements() const { return std::vector<std::string>({"Any"}); } void OmexMetaXmlAssistant::generateMetaId(std::vector<std::string> &seen_metaids, long count, const MetaID &metaid_gen, std::string &id) { id = metaid_gen.generate(count); if (std::find(seen_metaids.begin(), seen_metaids.end(), id) != seen_metaids.end()) { count += 1; generateMetaId(seen_metaids, count, metaid_gen, id); // recursion } } void OmexMetaXmlAssistant::addMetaIdsRecursion(xmlDocPtr doc, xmlNode *a_node, std::vector<std::string> &seen_metaids) { xmlNode *cur_node; cur_node = a_node; long count = 0; for (cur_node = a_node; cur_node; cur_node = cur_node->next) { // isolate element nodes if (cur_node->type == XML_ELEMENT_NODE) { const std::vector<std::string> &valid_elements = getValidElements(); // if the node name is in our list of valid elements or if valid_elements_ = ["All"] if (std::find(valid_elements.begin(), valid_elements.end(), std::string((const char *) cur_node->name)) != valid_elements.end() || (valid_elements.size() == 1 && valid_elements[0] == "Any")) { /* * Test to see whether the element has the metaid attribute. * In SBML there is a metaid attribute associated with sbml elements which are used * for the metaid. In cellml however a "cmeta" namespace is used instead. We need * to account for both so we can collect the ids from models that use both strategies. */ const std::string& metaid_name = metaIdTagName(); const std::string metaid_namespace = metaIdNamespace(); // creates an indicator to check whether we need a namespace or not for the metaid that we generate bool needs_namespace = true; if (metaid_namespace.empty()) needs_namespace = false; bool has_metaid = false; if (needs_namespace){ // use namespace strategy (cellml) has_metaid = xmlHasNsProp(cur_node, (const xmlChar *) metaIdTagName().c_str(), (const xmlChar *) metaIdNamespace().c_str()); } else { // use attribute/property strategy (sbml) has_metaid = xmlHasProp(cur_node, (const xmlChar *) metaIdTagName().c_str()); } if (!has_metaid) { // next we check to see whether the user wants us to add a metaid for them to this element. // Otherwise we just collect the metaids for later inspection. if (generateNewMetaids()) { // If we don't already have metaid and user wants us to add one, we generate a unique id MetaID metaId((const char*)cur_node->name, 0, getMetaidNumDigits()); std::string id; OmexMetaXmlAssistant::generateMetaId(seen_metaids, count, metaId, id); if (!needs_namespace) { xmlNewProp(cur_node, (const xmlChar *) metaIdTagName().c_str(), (const xmlChar *) id.c_str()); } else { // look through the existing list of xml namespaces. // if its there we grab a pointer to it. if not we create it. std::string cellml_metaid_namespace = "http://www.cellml.org/metadata/1.0#"; xmlNsPtr* ns_list_ptr = xmlGetNsList(doc, cur_node); xmlNsPtr ns = ns_list_ptr[0]; while(ns){ // make copy std::string candidate = (const char*)ns->href; if (cellml_metaid_namespace == candidate) break; // ns will point to the namespace we want ns = ns->next; // xmlFree(ns); } // if ns is nullptr it means we traversed the previous // while loop and reached the end. Therefore the ns we want // doesn't exist and we want to create it if (ns == nullptr){ ns = xmlNewGlobalNs(doc, (const xmlChar*) cellml_metaid_namespace.c_str(), (const xmlChar*) "cmeta"); } // now create the NsProperty xmlNewNsProp(cur_node, ns, (const xmlChar*)metaIdTagName().c_str(), (const xmlChar *) id.c_str()); // clear up //todo does this work? xmlFree(ns_list_ptr); } seen_metaids.push_back(id); count += 1; } } else { // if namespace already exists, we take note by adding it to seen_metaids. xmlChar *id = nullptr; if (needs_namespace){ id = xmlGetNsProp(cur_node, (const xmlChar *) metaIdTagName().c_str(), (const xmlChar *) metaIdNamespace().c_str()); } else{ id = xmlGetProp(cur_node, (const xmlChar *) metaIdTagName().c_str()); } if (id == nullptr){ throw NullPointerException("OmexMetaXmlAssistant::addMetaIdsRecursion::id is null"); } seen_metaids.emplace_back((const char *) id); xmlFree(id); } } } // recursion, we do this for every node addMetaIdsRecursion(doc, cur_node->children, seen_metaids); } } std::pair<std::string, std::vector<std::string>> OmexMetaXmlAssistant::addMetaIds() { LIBXML_TEST_VERSION; xmlDocPtr doc; /* the resulting document tree */ doc = xmlParseDoc((const xmlChar *) xml_.c_str()); if (doc == nullptr) { throw NullPointerException("NullPointerException: OmexMetaXmlAssistant::addMetaIds(): doc"); } xmlNodePtr root_element = xmlDocGetRootElement(doc); std::vector<std::string> seen_metaids = {}; addMetaIdsRecursion(doc, root_element, seen_metaids); xmlChar *s; int size; xmlDocDumpMemory(doc, &s, &size); if (s == nullptr) throw std::bad_alloc(); std::string x = std::string((const char *) s); xmlFree(s); xmlFreeDoc(doc); xmlCleanupParser(); std::pair<std::string, std::vector<std::string>> sbml_with_metaid(x, seen_metaids); return sbml_with_metaid; } std::string OmexMetaXmlAssistant::metaIdTagName() const { return std::string(); } std::string OmexMetaXmlAssistant::metaIdNamespace() const { return std::string(); } bool OmexMetaXmlAssistant::generateNewMetaids() const { return generate_new_metaids_; } const std::string &OmexMetaXmlAssistant::getMetaidBase() const { return metaid_base_; } int OmexMetaXmlAssistant::getMetaidNumDigits() const { return metaid_num_digits_; } std::vector<std::string> SBMLAssistant::getValidElements() const { std::vector<std::string> valid_elements_ = { "model", "unit", "compartment", "species", "reaction", "kineticLaw", "parameter", }; return valid_elements_; } std::string SBMLAssistant::metaIdTagName() const { return "metaid"; } std::string SBMLAssistant::metaIdNamespace() const { return std::string(); } std::vector<std::string> CellMLAssistant::getValidElements() const { std::vector<std::string> valid_elements_ = { "model", "component", "variable"}; return valid_elements_; } std::string CellMLAssistant::metaIdTagName() const { return "id"; } std::string CellMLAssistant::metaIdNamespace() const { return "http://www.cellml.org/metadata/1.0#"; } XmlAssistantPtr OmexMetaXmlAssistantFactory::generate(const std::string &xml, OmexMetaXmlType type, bool generate_new_metaids, std::string metaid_base, int metaid_num_digits) { switch (type) { case OMEXMETA_TYPE_SBML: { SBMLAssistant sbmlAssistant(xml, metaid_base, metaid_num_digits, generate_new_metaids); return std::make_unique<SBMLAssistant>(sbmlAssistant); } case OMEXMETA_TYPE_CELLML: { CellMLAssistant cellMlAssistant(xml, metaid_base, metaid_num_digits, generate_new_metaids); return std::make_unique<CellMLAssistant>(cellMlAssistant); } case OMEXMETA_TYPE_UNKNOWN: { OmexMetaXmlAssistant xmlAssistant(xml, metaid_base, metaid_num_digits, generate_new_metaids); return std::make_unique<OmexMetaXmlAssistant>(xmlAssistant); } default: throw std::invalid_argument("Not a correct type"); } } }
48.488688
150
0.515864
[ "vector", "model" ]
384ef36c68e2a70b25cd46894362e54068a8954f
25,391
cpp
C++
s2e/qemu/s2e/S2E.cpp
wyz7155/SymDrive
055f3ab1601d6350b397eddc9f3982271d9186d2
[ "MIT" ]
null
null
null
s2e/qemu/s2e/S2E.cpp
wyz7155/SymDrive
055f3ab1601d6350b397eddc9f3982271d9186d2
[ "MIT" ]
null
null
null
s2e/qemu/s2e/S2E.cpp
wyz7155/SymDrive
055f3ab1601d6350b397eddc9f3982271d9186d2
[ "MIT" ]
null
null
null
/* * S2E Selective Symbolic Execution Framework * * Copyright (c) 2010, Dependable Systems Laboratory, EPFL * 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 Dependable Systems Laboratory, EPFL 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 DEPENDABLE SYSTEMS LABORATORY, EPFL 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. * * Currently maintained by: * Volodymyr Kuznetsov <vova.kuznetsov@epfl.ch> * Vitaly Chipounov <vitaly.chipounov@epfl.ch> * * All contributors are listed in S2E-AUTHORS file. * */ // XXX: qemu stuff should be included before anything from KLEE or LLVM ! extern "C" { #include <qemu-common.h> #include <cpus.h> #include <main-loop.h> #include <sysemu.h> extern CPUX86State *env; } #include <tcg-llvm.h> #include "S2E.h" #include <s2e/Plugin.h> #include <s2e/Plugins/CorePlugin.h> #include <s2e/ConfigFile.h> #include <s2e/Utils.h> #include <s2e/S2EExecutor.h> #include <s2e/S2EExecutionState.h> #include <s2e/s2e_qemu.h> #include <llvm/Support/FileSystem.h> #include <llvm/Support/Path.h> #include <llvm/Support/CommandLine.h> #include <llvm/Support/raw_os_ostream.h> #include <llvm/Support/raw_ostream.h> #include <llvm/Module.h> #include <llvm/ExecutionEngine/ExecutionEngine.h> #include <llvm/Bitcode/ReaderWriter.h> #include <klee/Interpreter.h> #include <klee/Common.h> #include <iostream> #include <sstream> #include <deque> #include <stdlib.h> #include <assert.h> #include <errno.h> #include <stdarg.h> #include <stdio.h> #include <sys/stat.h> #ifndef _WIN32 #include <sys/types.h> #include <unistd.h> #endif // stacktrace.h (c) 2008, Timo Bingmann from http://idlebox.net/ // published under the WTFPL v2.0 #if defined(CONFIG_WIN32) void print_stacktrace(void) { std::ostream &os = g_s2e->getDebugStream(); os << "Stack trace printing unsupported on Windows" << '\n'; } #else #include <stdio.h> #include <stdlib.h> #include <execinfo.h> #include <cxxabi.h> /** Print a demangled stack backtrace of the caller function to FILE* out. */ void print_stacktrace(void) { unsigned int max_frames = 63; llvm::raw_ostream &os = g_s2e->getDebugStream(); os << "Stack trace" << '\n'; // storage array for stack trace address data void* addrlist[max_frames+1]; // retrieve current stack addresses int addrlen = backtrace(addrlist, sizeof(addrlist) / sizeof(void*)); if (addrlen == 0) { s2e_debug_print(" <empty, possibly corrupt>\n"); return; } // resolve addresses into strings containing "filename(function+address)", // this array must be free()-ed char** symbollist = backtrace_symbols(addrlist, addrlen); // allocate string which will be filled with the demangled function name size_t funcnamesize = 256; char* funcname = (char*)malloc(funcnamesize); // iterate over the returned symbol lines. skip the first, it is the // address of this function. for (int i = 1; i < addrlen; i++) { char *begin_name = 0, *begin_offset = 0, *end_offset = 0; // find parentheses and +address offset surrounding the mangled name: // ./module(function+0x15c) [0x8048a6d] for (char *p = symbollist[i]; *p; ++p) { if (*p == '(') begin_name = p; else if (*p == '+') begin_offset = p; else if (*p == ')' && begin_offset) { end_offset = p; break; } } if (begin_name && begin_offset && end_offset && begin_name < begin_offset) { *begin_name++ = '\0'; *begin_offset++ = '\0'; *end_offset = '\0'; // mangled name is now in [begin_name, begin_offset) and caller // offset in [begin_offset, end_offset). now apply // __cxa_demangle(): int status; char* ret = abi::__cxa_demangle(begin_name, funcname, &funcnamesize, &status); if (status == 0) { funcname = ret; // use possibly realloc()-ed string s2e_debug_print(" %s : %s+%s\n", symbollist[i], funcname, begin_offset); } else { // demangling failed. Output function name as a C function with // no arguments. s2e_debug_print(" %s : %s()+%s\n", symbollist[i], begin_name, begin_offset); } } else { // couldn't parse the line? print the whole line. s2e_debug_print(" %s\n", symbollist[i]); } } free(funcname); free(symbollist); } #endif //CONFIG_WIN32 namespace s2e { using namespace std; S2E::S2E(int argc, char** argv, TCGLLVMContext *tcgLLVMContext, const std::string &configFileName, const std::string &outputDirectory, int verbose, unsigned s2e_max_processes) : m_tcgLLVMContext(tcgLLVMContext) { if (s2e_max_processes < 1) { std::cerr << "You must at least allow one process for S2E." << '\n'; exit(1); } if (s2e_max_processes > S2E_MAX_PROCESSES) { std::cerr << "S2E can handle at most " << S2E_MAX_PROCESSES << " processes." << '\n'; std::cerr << "Please increase the S2E_MAX_PROCESSES constant." << '\n'; exit(1); } #ifdef CONFIG_WIN32 if (s2e_max_processes > 1) { std::cerr << "S2E for Windows does not support more than one process" << '\n'; exit(1); } #endif m_startTimeSeconds = llvm::sys::TimeValue::now().seconds(); m_forking = false; m_maxProcesses = s2e_max_processes; m_currentProcessIndex = 0; m_currentProcessId = 0; S2EShared *shared = m_sync.acquire(); shared->currentProcessCount = 1; shared->lastStateId = 0; shared->lastFileId = 1; shared->processIds[m_currentProcessId] = m_currentProcessIndex; shared->processPids[m_currentProcessId] = getpid(); m_sync.release(); /* Open output directory. Do it at the very begining so that other init* functions can use it. */ initOutputDirectory(outputDirectory, verbose, false); /* Copy the config file into the output directory */ { llvm::raw_ostream *out = openOutputFile("s2e.config.lua"); ifstream in(configFileName.c_str()); char c; while (in.get(c)) { (*out) << c; } delete out; } /* Save command line arguments */ { llvm::raw_ostream *out = openOutputFile("s2e.cmdline"); for(int i = 0; i < argc; ++i) { if(i != 0) (*out) << " "; (*out) << "'" << argv[i] << "'"; } delete out; } /* Parse configuration file */ m_configFile = new s2e::ConfigFile(configFileName); /* Initialize KLEE command line options */ initKleeOptions(); /* Initialize S2EExecutor */ initExecutor(); /* Load and initialize plugins */ initPlugins(); /* Init the custom memory allocator */ //void slab_init(); //slab_init(); } void S2E::writeBitCodeToFile() { std::string error; std::string fileName = getOutputFilename("module.bc"); llvm::raw_fd_ostream o(fileName.c_str(), error, llvm::raw_fd_ostream::F_Binary); llvm::Module *module = m_tcgLLVMContext->getModule(); // Output the bitcode file to stdout llvm::WriteBitcodeToFile(module, o); } S2E::~S2E() { //Delete all the stuff used by the instance foreach(Plugin* p, m_activePluginsList) delete p; //Tell other instances we are dead so they can fork more S2EShared *shared = m_sync.acquire(); assert(shared->processIds[m_currentProcessId] == m_currentProcessIndex); shared->processIds[m_currentProcessId] = (unsigned) -1; shared->processPids[m_currentProcessId] = (unsigned) -1; --shared->currentProcessCount; m_sync.release(); delete m_pluginsFactory; writeBitCodeToFile(); // KModule wants to delete the llvm::Module in destroyer. // llvm::ModuleProvider wants to delete it too. We have to arbitrate. //XXX: llvm 3.0. How doe it work? //m_tcgLLVMContext->getModuleProvider()->releaseModule(); //Make sure everything is clean m_s2eExecutor->flushTb(); //This is necessary, as the execution engine uses the module. m_tcgLLVMContext->deleteExecutionEngine(); delete m_s2eExecutor; delete m_s2eHandler; //The execution engine deletion will also delete the module. m_tcgLLVMContext->deleteExecutionEngine(); delete m_configFile; delete m_warningStream; delete m_messageStream; delete m_infoFileRaw; delete m_warningsFileRaw; delete m_messagesFileRaw; delete m_debugFileRaw; } Plugin* S2E::getPlugin(const std::string& name) const { ActivePluginsMap::const_iterator it = m_activePluginsMap.find(name); if(it != m_activePluginsMap.end()) return const_cast<Plugin*>(it->second); else return NULL; } std::string S2E::getOutputFilename(const std::string &fileName) { llvm::sys::Path filePath(m_outputDirectory); filePath.appendComponent(fileName); return filePath.str(); } llvm::raw_ostream* S2E::openOutputFile(const std::string &fileName) { std::string path = getOutputFilename(fileName); std::string error; llvm::raw_fd_ostream *f = new llvm::raw_fd_ostream(path.c_str(), error, llvm::raw_fd_ostream::F_Binary); if (!f || error.size()>0) { llvm::errs() << "Error opening " << path << ": " << error << "\n"; exit(-1); } return f; } void S2E::initOutputDirectory(const string& outputDirectory, int verbose, bool forked) { if (!forked) { //In case we create the first S2E process if (outputDirectory.empty()) { llvm::sys::Path cwd = llvm::sys::Path::GetCurrentDirectory(); for (int i = 0; ; i++) { ostringstream dirName; dirName << "s2e-out-" << i; llvm::sys::Path dirPath(cwd); dirPath.appendComponent(dirName.str()); bool exists = false; llvm::sys::fs::exists(dirPath.str(), exists); if(!exists) { m_outputDirectory = dirPath.str(); break; } } } else { m_outputDirectory = outputDirectory; } m_outputDirectoryBase = m_outputDirectory; }else { m_outputDirectory = m_outputDirectoryBase; } #ifndef _WIN32 if (m_maxProcesses > 1) { //Create one output directory per child process //This prevents child processes to clobber each other's output llvm::sys::Path dirPath(m_outputDirectory); ostringstream oss; oss << m_currentProcessIndex; dirPath.appendComponent(oss.str()); bool exists = false; llvm::sys::fs::exists(dirPath.str(), exists); assert(!exists); m_outputDirectory = dirPath.str(); } #endif std::cout << "S2E: output directory = \"" << m_outputDirectory << "\"\n"; llvm::sys::Path outDir(m_outputDirectory); std::string mkdirError; #ifdef _WIN32 //XXX: If set to true on Windows, it fails when parent directories exist //For now, we assume that only the last component needs to be created if (outDir.createDirectoryOnDisk(false, &mkdirError)) { #else if (outDir.createDirectoryOnDisk(true, &mkdirError)) { #endif std::cerr << "Could not create output directory " << outDir.str() << " error: " << mkdirError << '\n'; exit(-1); } #ifndef _WIN32 if (!forked) { llvm::sys::Path s2eLast("."); s2eLast.appendComponent("s2e-last"); if ((unlink(s2eLast.c_str()) < 0) && (errno != ENOENT)) { perror("ERROR: Cannot unlink s2e-last"); exit(1); } if (symlink(m_outputDirectoryBase.c_str(), s2eLast.c_str()) < 0) { perror("ERROR: Cannot make symlink s2e-last"); exit(1); } } #endif ios_base::sync_with_stdio(true); cout.setf(ios_base::unitbuf); cerr.setf(ios_base::unitbuf); m_infoFileRaw = openOutputFile("info.txt"); m_debugFileRaw = openOutputFile("debug.txt"); m_messagesFileRaw = openOutputFile("messages.txt"); m_warningsFileRaw = openOutputFile("warnings.txt"); // Messages appear in messages.txt, debug.txt and on stdout raw_tee_ostream *messageStream = new raw_tee_ostream(m_messagesFileRaw); messageStream->addParentBuf(m_debugFileRaw); if (verbose) { messageStream->addParentBuf(&llvm::outs()); } m_messageStream = messageStream; // Warnings appear in warnings.txt, messages.txt, debug.txt // and on stderr in red color raw_tee_ostream *warningsStream = new raw_tee_ostream(m_warningsFileRaw); warningsStream->addParentBuf(m_debugFileRaw); warningsStream->addParentBuf(m_messagesFileRaw); warningsStream->addParentBuf(new raw_highlight_ostream(&llvm::errs())); m_warningStream = warningsStream; #if 0 // Messages appear in messages.txt, debug.txt and on stdout m_messagesStreamBuf = new TeeStreamBuf(messagesFileBuf); static_cast<TeeStreamBuf*>(m_messagesStreamBuf)->addParentBuf(debugFileBuf); if(verbose) static_cast<TeeStreamBuf*>(m_messagesStreamBuf)->addParentBuf(cerr.rdbuf()); m_messagesFile->rdbuf(m_messagesStreamBuf); m_messagesFile->setf(ios_base::unitbuf); // Warnings appear in warnings.txt, messages.txt, debug.txt // and on stderr in red color m_warningsStreamBuf = new TeeStreamBuf(warningsFileBuf); static_cast<TeeStreamBuf*>(m_warningsStreamBuf)->addParentBuf(messagesFileBuf); static_cast<TeeStreamBuf*>(m_warningsStreamBuf)->addParentBuf(debugFileBuf); if(verbose) static_cast<TeeStreamBuf*>(m_warningsStreamBuf)->addParentBuf( new HighlightStreamBuf(cerr.rdbuf())); else static_cast<TeeStreamBuf*>(m_warningsStreamBuf)->addParentBuf(cerr.rdbuf()); m_warningsFile->rdbuf(m_warningsStreamBuf); m_warningsFile->setf(ios_base::unitbuf); #endif klee::klee_message_stream = m_messageStream; klee::klee_warning_stream = m_warningStream; } void S2E::initKleeOptions() { std::vector<std::string> kleeOptions = getConfig()->getStringList("s2e.kleeArgs"); if(!kleeOptions.empty()) { int numArgs = kleeOptions.size() + 1; const char **kleeArgv = new const char*[numArgs + 1]; kleeArgv[0] = "s2e.kleeArgs"; kleeArgv[numArgs] = 0; for(unsigned int i = 0; i < kleeOptions.size(); ++i) kleeArgv[i+1] = kleeOptions[i].c_str(); llvm::cl::ParseCommandLineOptions(numArgs, (char**) kleeArgv); delete[] kleeArgv; } } void S2E::initPlugins() { m_pluginsFactory = new PluginsFactory(); m_corePlugin = dynamic_cast<CorePlugin*>( m_pluginsFactory->createPlugin(this, "CorePlugin")); assert(m_corePlugin); m_activePluginsList.push_back(m_corePlugin); m_activePluginsMap.insert( make_pair(m_corePlugin->getPluginInfo()->name, m_corePlugin)); if(!m_corePlugin->getPluginInfo()->functionName.empty()) m_activePluginsMap.insert( make_pair(m_corePlugin->getPluginInfo()->functionName, m_corePlugin)); vector<string> pluginNames = getConfig()->getStringList("plugins"); /* Check and load plugins */ foreach(const string& pluginName, pluginNames) { const PluginInfo* pluginInfo = m_pluginsFactory->getPluginInfo(pluginName); if(!pluginInfo) { std::cerr << "ERROR: plugin '" << pluginName << "' does not exists in this S2E installation" << '\n'; exit(1); } else if(getPlugin(pluginInfo->name)) { std::cerr << "ERROR: plugin '" << pluginInfo->name << "' was already loaded " << "(is it enabled multiple times ?)" << '\n'; exit(1); } else if(!pluginInfo->functionName.empty() && getPlugin(pluginInfo->functionName)) { std::cerr << "ERROR: plugin '" << pluginInfo->name << "' with function '" << pluginInfo->functionName << "' can not be loaded because" << '\n' << " this function is already provided by '" << getPlugin(pluginInfo->functionName)->getPluginInfo()->name << "' plugin" << '\n'; exit(1); } else { Plugin* plugin = m_pluginsFactory->createPlugin(this, pluginName); assert(plugin); m_activePluginsList.push_back(plugin); m_activePluginsMap.insert( make_pair(plugin->getPluginInfo()->name, plugin)); if(!plugin->getPluginInfo()->functionName.empty()) m_activePluginsMap.insert( make_pair(plugin->getPluginInfo()->functionName, plugin)); } } /* Check dependencies */ foreach(Plugin* p, m_activePluginsList) { foreach(const string& name, p->getPluginInfo()->dependencies) { if(!getPlugin(name)) { std::cerr << "ERROR: plugin '" << p->getPluginInfo()->name << "' depends on plugin '" << name << "' which is not enabled in config" << '\n'; exit(1); } } } /* Initialize plugins */ foreach(Plugin* p, m_activePluginsList) { p->initialize(); } } void S2E::initExecutor() { m_s2eHandler = new S2EHandler(this); S2EExecutor::InterpreterOptions IOpts; m_s2eExecutor = new S2EExecutor(this, m_tcgLLVMContext, IOpts, m_s2eHandler); } llvm::raw_ostream& S2E::getStream(llvm::raw_ostream &stream, const S2EExecutionState* state) const { fflush(stdout); fflush(stderr); stream.flush(); if(state) { llvm::sys::TimeValue curTime = llvm::sys::TimeValue::now(); stream << (curTime.seconds() - m_startTimeSeconds) << ' '; if (m_maxProcesses > 1) { stream << "[Node " << m_currentProcessIndex << "/" << m_currentProcessId << " - State " << state->getID() << "] "; }else { stream << "[" << state->getID() << "/" // MJR << m_s2eExecutor->getStatesCount() << "] "; // stream << "[State " << state->getID() << "] "; // MJR } } return stream; } void S2E::printf(llvm::raw_ostream &os, const char *fmt, ...) { va_list vl; va_start(vl,fmt); char str[512]; vsnprintf(str, sizeof(str), fmt, vl); os << str; } void S2E::refreshPlugins() { foreach2(it, m_activePluginsList.begin(), m_activePluginsList.end()) { (*it)->refresh(); } } int S2E::fork() { #ifdef CONFIG_WIN32 return -1; #else S2EShared *shared = m_sync.acquire(); if (shared->currentProcessCount == m_maxProcesses) { m_sync.release(); return -1; } unsigned newProcessIndex = shared->lastFileId; ++shared->lastFileId; ++shared->currentProcessCount; m_sync.release(); pid_t pid = ::fork(); if (pid < 0) { //Fork failed shared = m_sync.acquire(); //Do not decrement lastFileId, as other fork may have //succeeded while we were handling the failure. --shared->currentProcessCount; m_sync.release(); return -1; } if (pid == 0) { //Allocate a free slot in the instance map shared = m_sync.acquire(); unsigned i=0; for (i=0; i<m_maxProcesses; ++i) { if (shared->processIds[i] == (unsigned)-1) { shared->processIds[i] = newProcessIndex; shared->processPids[i] = getpid(); m_currentProcessId = i; break; } } assert (i < m_maxProcesses); m_sync.release(); m_currentProcessIndex = newProcessIndex; //We are the child process, setup the log files again initOutputDirectory(m_outputDirectoryBase, 0, true); //Also recreate new statistics files m_s2eExecutor->initializeStatistics(); //And the solver output m_s2eExecutor->initializeSolver(); m_forking = true; qemu_init_cpu_loop(); if (main_loop_init()) { fprintf(stderr, "qemu_init_main_loop failed\n"); exit(1); } if (init_timer_alarm(0)<0) { getDebugStream() << "Could not initialize timers" << '\n'; exit(-1); } qemu_init_vcpu(env); cpu_synchronize_all_post_init(); os_setup_signal_handling(); vm_start(); os_setup_post(); resume_all_vcpus(); vm_stop(RUN_STATE_SAVE_VM); m_forking = false; } return pid == 0 ? 1 : 0; #endif } unsigned S2E::fetchAndIncrementStateId() { S2EShared *shared = m_sync.acquire(); unsigned ret = shared->lastStateId; ++shared->lastStateId; m_sync.release(); return ret; } unsigned S2E::fetchNextStateId() { S2EShared *shared = m_sync.acquire(); unsigned ret = shared->lastStateId; m_sync.release(); return ret; } unsigned S2E::getCurrentProcessCount() { S2EShared *shared = m_sync.acquire(); unsigned ret = shared->currentProcessCount; m_sync.release(); return ret; } unsigned S2E::getProcessIndexForId(unsigned id) { assert(id < m_maxProcesses); S2EShared *shared = m_sync.acquire(); unsigned ret = shared->processIds[id]; m_sync.release(); return ret; } bool S2E::checkDeadProcesses() { S2EShared *shared = m_sync.acquire(); bool ret = false; for (unsigned i=0; i<m_maxProcesses; ++i) { if (shared->processPids[i] == (unsigned)-1) { continue; } //Check if pid is alive char buffer[64]; snprintf(buffer, sizeof(buffer), "kill -0 %d", shared->processPids[i]); int ret = system(buffer); if (ret != 0) { //Process is dead, we have to decrement everyting shared->processIds[i] = (unsigned) -1; shared->processPids[i] = (unsigned) -1; --shared->currentProcessCount; ret = true; } } m_sync.release(); return ret; } } // namespace s2e /******************************/ /* Functions called from QEMU */ extern "C" { S2E* g_s2e = NULL; S2E* s2e_initialize(int argc, char** argv, TCGLLVMContext* tcgLLVMContext, const char* s2e_config_file, const char* s2e_output_dir, int verbose, unsigned s2e_max_processes) { return new S2E(argc, argv, tcgLLVMContext, s2e_config_file ? s2e_config_file : "", s2e_output_dir ? s2e_output_dir : "", verbose, s2e_max_processes); } void s2e_close(S2E *s2e) { print_stacktrace(); delete s2e; tcg_llvm_close(tcg_llvm_ctx); tcg_llvm_ctx = NULL; } int s2e_is_forking() { return g_s2e->isForking(); } void s2e_debug_print(const char *fmtstr, ...) { if (!g_s2e) { return; } va_list vl; va_start(vl,fmtstr); char str[512]; vsnprintf(str, sizeof(str), fmtstr, vl); g_s2e->getDebugStream() << str; va_end(vl); } //Print a klee expression. //Useful for invocations from GDB void s2e_print_expr(void *expr); void s2e_print_expr(void *expr) { klee::ref<klee::Expr> e = *(klee::ref<klee::Expr>*)expr; std::stringstream ss; ss << e; g_s2e->getDebugStream() << ss.str() << '\n'; } void s2e_print_value(void *value); void s2e_print_value(void *value) { llvm::Value *v = (llvm::Value*)value; g_s2e->getDebugStream() << *v << '\n'; } extern "C" { void s2e_execute_cmd(const char *cmd) { g_s2e->getConfig()->invokeLuaCommand(cmd); } } } // extern "C"
29.801643
108
0.614785
[ "vector" ]
ee2d5084cce71d145f0114090dd62e386b206b85
1,328
cc
C++
Question/ๅญ—็ฌฆไธฒไธญๆ‰พๅ‡บ่ฟž็ปญๆœ€้•ฟ็š„ๆ•ฐๅญ—ไธฒ.cc
lkimprove/Study_C
ee1153536f28e160d5daad4ddebaa547c3941ee7
[ "MIT" ]
null
null
null
Question/ๅญ—็ฌฆไธฒไธญๆ‰พๅ‡บ่ฟž็ปญๆœ€้•ฟ็š„ๆ•ฐๅญ—ไธฒ.cc
lkimprove/Study_C
ee1153536f28e160d5daad4ddebaa547c3941ee7
[ "MIT" ]
null
null
null
Question/ๅญ—็ฌฆไธฒไธญๆ‰พๅ‡บ่ฟž็ปญๆœ€้•ฟ็š„ๆ•ฐๅญ—ไธฒ.cc
lkimprove/Study_C
ee1153536f28e160d5daad4ddebaa547c3941ee7
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <algorithm> using namespace std; int main(){ string s; //่พ“ๅ…ฅ while(getline(cin, s)){ string ret; //้ๅކๅญ—็ฌฆไธฒ for(int i = 0; i < s.size(); i++){ string tmp; //่Žทๅ–่ฟž็ปญ็š„ๆ•ฐๅญ—ๅญ—็ฌฆไธฒ while(s[i] >= '0' && s[i] <= '9' && i < s.size()){ tmp += s[i]; i++; } //ๅˆคๆ–ญๅฝ“ๅ‰ๅญ—็ฌฆไธฒๆ˜ฏๅฆๆœ€้•ฟ if(ret.size() < tmp.size()){ swap(ret, tmp); } } cout << ret << endl; } return 0; } //ๅŠจๆ€่ง„ๅˆ’ #include <iostream> #include <string> #include <vector> using namespace std; int main(){ string str; while(getline(cin, str)){ int flag = 0, size = 0; vector<int> dp(str.size() + 1, 0); for(int i = 1; i <= str.size(); i++){ if(str[i - 1] >= '0' && str[i - 1] <= '9'){ dp[i] = dp[i - 1] + 1; if(dp[i] > size){ size = dp[i]; flag = i - size; } } } string ret; for(int i = 0; i < size; i++){ ret.push_back(str[flag++]); } cout << ret << endl; } return 0; }
19.246377
62
0.355422
[ "vector" ]
ee2f3179a7e5301ba97bdcb8baa66d3c6a163368
9,096
cc
C++
src/gcpuinfo.cc
ioan2/gpuinfo
520b734f6d64d45cff5dec8b860c5f17635f3887
[ "BSD-3-Clause" ]
null
null
null
src/gcpuinfo.cc
ioan2/gpuinfo
520b734f6d64d45cff5dec8b860c5f17635f3887
[ "BSD-3-Clause" ]
null
null
null
src/gcpuinfo.cc
ioan2/gpuinfo
520b734f6d64d45cff5dec8b860c5f17635f3887
[ "BSD-3-Clause" ]
null
null
null
/** This library is under the 3-Clause BSD License Copyright (c) 2017, Johannes Heinecke Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Author: Johannes Heinecke Version: 1.1 as of 27th December 2017 */ #include <iostream> #include <map> #include <vector> #include <cstring> #include <cstdlib> #include <gtk/gtk.h> #include "cpuinfo.h" #include "utils.h" #include "widgets.h" #define APPNAME "cgpuinfo" using namespace std; /** structure to give information to callback */ //struct cb_data { // CpuInfo *ci; // vector<FieldsGroup *>fgs; //vector<const char *>infos; //map<const char *, vector<GtkWidget *> > labels; //}; /* TODO: process cpu - core correctly (which cpu on which core) */ /** used to update labels */ gboolean time_handler(CallBackDataCPU *cbdata) { unsigned int u[MAX_CPU], s[MAX_CPU], n[MAX_CPU], i[MAX_CPU], t[MAX_CPU]; cbdata->ci->getCPUtime(u, s, n, i); cbdata->ci->getCoreTemp(t); unsigned int x = 0; for (vector<FieldsGroup *>::iterator it = cbdata->cpu_fgs.begin(); it != cbdata->cpu_fgs.end(); ++it, ++x) { // pour tous les FieldsGroup des CPU (*it)->setValue('u', u[x]/10.0); (*it)->setValue('n', n[x]/10.0); (*it)->setValue('s', s[x]/10.0); } x = 1; for (vector<FieldsGroup *>::iterator it = cbdata->core_fgs.begin(); it != cbdata->core_fgs.end(); ++it, ++x) { (*it)->setValue('t', t[x]/1000.0); } return TRUE; } int main(int argc, char *argv[]) { if (argc <= 1) { cerr << argv[0] << " [options]" << endl << "options:" << endl << " -d update delay (default 500ms)" << endl << " -T textual output" << endl << "\n without -T" <<endl << " --nn do not show niced" << endl << " -v vertical layout" << endl << " -c compact view (no labels)" << endl << " -p progressbar view" << endl << "\n with -T" <<endl << " -t add time stamp" << endl << " -l log mode" << endl << endl; ; } unsigned int delay = 1000; bool textonly = false; bool logmode = false; bool timest = false; bool showniced = true; bool vertical = false; bool progressbar = false; bool compact = false; for (int i = 1; i<argc; ++i) { if (strcmp(argv[i], "-d") == 0 && i < argc-1) { unsigned int d = atoi(argv[i+1]); if (d < 1) { cerr << "invalid option: " << argv[i] << " " << argv[i+1] << endl; } else { ++i; delay = d; } } else if (strcmp(argv[i], "-T") == 0) { textonly = true; } else if (strcmp(argv[i], "-c") == 0) { compact = true; } else if (strcmp(argv[i], "-p") == 0) { progressbar = true; } else if (strcmp(argv[i], "-v") == 0) { vertical = true; } else if (strcmp(argv[i], "--nn") == 0) { showniced = false; } else if (strcmp(argv[i], "-l") == 0) { logmode = true; } else if (strcmp(argv[i], "-t") == 0) { timest = true; } else { cerr << "invalid option: " << argv[i] << endl; break; } } CpuInfo ci; unsigned int cpus = ci.getCpus(); // cpu number + 1 (total) unsigned int cores = ci.getCores(); // core number + 1 unsigned int cpus_par_core = (cpus-1)/(cores-1); if (!textonly) { // initialise cbdata CallBackDataCPU cbdata; cbdata.ci = &ci; gtk_init(&argc, &argv); //printf("GTK+ version: %d.%d.%d\n", gtk_major_version, gtk_minor_version, gtk_micro_version); //printf("Glib version: %d.%d.%d\n", glib_major_version, glib_minor_version, glib_micro_version); //PangoFontDescription *pfd = pango_font_description_from_string("Serif 12"); // main window GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL); //gtk_window_set_default_size(GTK_WINDOW(window), 300, 100); gtk_window_set_title(GTK_WINDOW(window), APPNAME); //gtk_window_set_resizable(GTK_WINDOW(window), FALSE); gtk_container_set_border_width(GTK_CONTAINER(window), 1); // create main table (a column per core) GtkWidget *maintable; if (vertical) maintable = gtk_table_new(cpus, 2, FALSE); // rows, columns, homogenuous else { // first column for headers maintable = gtk_table_new(2, cpus+1, FALSE); // rows, columns, homogenuous } gtk_table_set_row_spacings(GTK_TABLE(maintable), 2); gtk_table_set_col_spacings(GTK_TABLE(maintable), 2); gtk_container_add(GTK_CONTAINER(window), maintable); char tmp[70]; // // create headers // if (!compact) { // GtkWidget *label = gtk_label_new("temperature"); // gtk_label_set_angle(GTK_LABEL(label), 90); // // left, right, top, bottom // gtk_table_attach_defaults(GTK_TABLE(maintable), label, // 0, 1, // 0, 1); // } // create core infos int offset = 2; // headers, total column for (unsigned int i = 0; i < cores-1; ++i) { sprintf(tmp, "core %d:", i); FieldsGroup *fg = new FieldsGroup(tmp, vertical); cbdata.core_fgs.push_back(fg); const char *name = 0; if (!compact && i == 0) name = "temperature"; fg->add('t', new InfoField(name, "%.fC", vertical, progressbar)); fg->setValue('t', 40); if (vertical) { // left, right, top, bottom gtk_table_attach_defaults(GTK_TABLE(maintable), fg->getWidget(), 0, 1, offset + i*cpus_par_core, offset + (i+1)*cpus_par_core); } else { // left, right, top, bottom gtk_table_attach_defaults(GTK_TABLE(maintable), fg->getWidget(), offset + i*cpus_par_core, offset + (i+1)*cpus_par_core, 0, 1); } } //cerr << "cpc " << cpus_par_core << endl; // create cpu infos for (unsigned int i = 0; i < cpus; ++i) { if (i == 0) sprintf(tmp, "total:"); else { sprintf(tmp, "cpu %d:", i-1); //cerr << i << " core: " << ci.getCore(i-1) << endl; } int currentcore = ci.getCore(i-1); int offset = 1; int column = offset; // with headers if (i != 0) column = offset + 1 + currentcore*cpus_par_core + (i-1)/(cores-1); //cerr << i << " " << (i-1) % 2<< " xxx: " << " " << currentcore << " " << column << endl; FieldsGroup *fg = new FieldsGroup(tmp, vertical); cbdata.cpu_fgs.push_back(fg); if (vertical) { // left, right, top, bottom gtk_table_attach_defaults(GTK_TABLE(maintable), fg->getWidget(), 1, 2, column, column+1); } else { // left, right, top, bottom gtk_table_attach_defaults(GTK_TABLE(maintable), fg->getWidget(), column, column+1, 1, 2); } const char *name = 0; if (!compact && i == 0) name = "user"; fg->add('u', new InfoField(name, "%.1f%%", vertical, progressbar)); //fg->setValue('u', 20.0); if (showniced) { if (!compact && i == 0) name = "niced"; fg->add('n', new InfoField(name, "%.1f%%", vertical, progressbar)); fg->setValue('n', 40); } if (!compact && i == 0) name = "system"; fg->add('s', new InfoField(name, "%.1f%%", vertical, progressbar)); fg->setValue('s', 30); } //pango_font_description_free(pfd); // destroy applicatation when window is closed g_signal_connect(G_OBJECT(window), "destroy", G_CALLBACK(gtk_main_quit), G_OBJECT(window)); //g_signal_connect(window, "expose-event", G_CALLBACK(on_expose_event), NULL); // set first values time_handler(&cbdata); // update values every <delay> milliseconds g_timeout_add(delay, (GSourceFunc) time_handler, &cbdata); // draw window gtk_widget_show_all(window); // loop gtk_main(); } else { while(true) { if (timest) { timestamp(cerr); } if (!logmode) { cerr << '\r'; for (unsigned int i = 0; i < cpus; ++i) { cerr << " \t"; } cerr << '\r'; } ci.out(cerr); if (logmode) cerr <<endl; usleep(delay*1000); } } }
30.019802
114
0.623021
[ "vector" ]
ee2fdc5d865aa34aeb6689bf0b28e48e11b48334
7,704
cpp
C++
io/MonitoringStagedFRROTreeGeneratorLogger.cpp
Rodrigo-Schmidt/VItA
38d36843d299e59dee82913ab629c2873cbc57a6
[ "Apache-2.0" ]
null
null
null
io/MonitoringStagedFRROTreeGeneratorLogger.cpp
Rodrigo-Schmidt/VItA
38d36843d299e59dee82913ab629c2873cbc57a6
[ "Apache-2.0" ]
null
null
null
io/MonitoringStagedFRROTreeGeneratorLogger.cpp
Rodrigo-Schmidt/VItA
38d36843d299e59dee82913ab629c2873cbc57a6
[ "Apache-2.0" ]
null
null
null
// Standard library dependencies #include<cstdio> #include<typeinfo> // This class interface #include"MonitoringStagedFRROTreeGeneratorLogger.h" void MonitoringStagedFRROTreeGeneratorLogger::logDomainFiles(FILE *fp, AbstractDomain *domain) { domain->logDomainFiles(fp); } void MonitoringStagedFRROTreeGeneratorLogger::logCostEstimator(FILE *fp, AbstractCostEstimator *costEstimator) { costEstimator->logCostEstimator(fp); } void MonitoringStagedFRROTreeGeneratorLogger::logGenData(FILE *fp, GeneratorData *data) { logCostEstimator(fp, data->costEstimator); fprintf(fp, "n_level_test = %d.\n", data->nLevelTest); fprintf(fp, "n_terminal_trial = %d.\n", data->nTerminalTrial); fprintf(fp, "d_lim_reduction_factor = %f.\n", data->dLimReductionFactor); fprintf(fp, "perfusion_area_factor = %f.\n", data->perfusionAreaFactor); fprintf(fp, "close_neighborhood factor = %f.\n", data->closeNeighborhoodFactor); fprintf(fp, "mid_point_d_lim_factor = %f.\n", data->midPointDlimFactor); fprintf(fp, "n_bifurcation_test = %d.\n", data->nBifurcationTest); fprintf(fp, "vessel_function = %d.\n", data->vesselFunction); fprintf(fp, "reset_d_lim = %d.\n", (int) data->resetsDLim); } void MonitoringStagedFRROTreeGeneratorLogger::logConstraint(FILE *fp, AbstractConstraintFunction<double, int> *constraint) { const type_info& type_constant = typeid(ConstantConstraintFunction<double, int>); const type_info& constraint_type = typeid(*constraint); // Is ConstantConstraintFunction if (type_constant.hash_code() == constraint_type.hash_code()) { fprintf(fp, "ConstantConstraintFunction = %lf\n", constraint->getValue(0)); } // Is ConstantPiecewiseConstraintFunction else { ConstantPiecewiseConstraintFunction<double, int> *pieceConstraint = static_cast<ConstantPiecewiseConstraintFunction<double, int> *>(constraint); fprintf(fp, "ConstantPiecewiseConstraintFunction\n"); vector<double> values = pieceConstraint->getValues(); vector<int> conditions = pieceConstraint->getConditions(); size_t size = values.size(); fprintf(fp, "Values = "); for (size_t i = 0; i < size; ++i) { fprintf(fp, "%lf ", values[i]); } fprintf(fp, "\n"); fprintf(fp, "Conditions = "); for (size_t i = 0; i < size; ++i) { fprintf(fp, "%d ", conditions[i]); } fprintf(fp, "\n"); } } void MonitoringStagedFRROTreeGeneratorLogger::logConstraint(FILE *fp, AbstractConstraintFunction<double, double> *constraint) { const type_info& type_constant = typeid(ConstantConstraintFunction<double, double>); const type_info& constraint_type = typeid(*constraint); // Is ConstantConstraintFunction if (type_constant.hash_code() == constraint_type.hash_code()) { fprintf(fp, "ConstantConstraintFunction = %lf\n", constraint->getValue(0)); } // Is ConstantPiecewiseConstraintFunction else { ConstantPiecewiseConstraintFunction<double, double> *pieceConstraint = static_cast<ConstantPiecewiseConstraintFunction<double, double> *>(constraint); fprintf(fp, "ConstantPiecewiseConstraintFunction\n"); vector<double> values = pieceConstraint->getValues(); vector<double> conditions = pieceConstraint->getConditions(); size_t size = values.size(); fprintf(fp, "Values = "); for (size_t i = 0; i < size; ++i) { fprintf(fp, "%lf ", values[i]); } fprintf(fp, "\n"); fprintf(fp, "Conditions = "); for (size_t i = 0; i < size; ++i) { fprintf(fp, "%lf ", conditions[i]); } fprintf(fp, "\n"); } } void MonitoringStagedFRROTreeGeneratorLogger::logDomain(FILE *fp, AbstractDomain *domain, long long int n_term, AbstractConstraintFunction<double, int> *gam, AbstractConstraintFunction<double, int> *epsLim, AbstractConstraintFunction<double, int> *nu) { fprintf(fp, "n_term = %lld.\n", n_term); fprintf(fp, "gamma\n"); logConstraint(fp, gam); fprintf(fp, "eps_lim\n"); logConstraint(fp, epsLim); fprintf(fp, "nu\n"); logConstraint(fp, nu); fprintf(fp, "n_draw = %d.\n", domain->getDraw()); fprintf(fp, "random seed = %d.\n", domain->getSeed()); fprintf(fp, "characteristic_lenght = %f.\n", domain->getCharacteristicLength()); fprintf(fp, "is_convex_domain = %d.\n", domain->isIsConvexDomain()); fprintf(fp, "min_bif_angle = %f.\n", domain->getMinBifurcationAngle()); fprintf(fp, "is_bif_plane_constrained = %d.\n", (int) domain->isIsBifPlaneContrained()); fprintf(fp, "min_plane_angle = %f.\n", domain->getMinPlaneAngle()); logGenData(fp, domain->getInstanceData()); } MonitoringStagedFRROTreeGeneratorLogger::MonitoringStagedFRROTreeGeneratorLogger(FILE *fp, MonitoringStagedFRROTreeGenerator *treeGen) { this->file = fp; this->treeGenerator = treeGen; }; MonitoringStagedFRROTreeGeneratorLogger::~MonitoringStagedFRROTreeGeneratorLogger() { }; void MonitoringStagedFRROTreeGeneratorLogger::write() { FILE *fp = this->file; MonitoringStagedFRROTreeGenerator *generator = this->treeGenerator; SingleVesselCCOOTree *tree = (SingleVesselCCOOTree *) generator->getTree(); double q0 = tree->getQProx(); StagedDomain* stagedDomain = this->treeGenerator->getDomain(); vector<AbstractDomain *> *domains = stagedDomain->getDomains(); vector<long long int> *nTerms = stagedDomain->getNTerminals(); vector<AbstractConstraintFunction<double, int> *> *gams = generator->getGams(); vector<AbstractConstraintFunction<double, int> *> *epsLims = generator->getEpsLims(); vector<AbstractConstraintFunction<double, int> *> *nus = generator->getNus(); int size = domains->size(); string filenameCCO = tree->getFilenameCCO(); if(filenameCCO.empty()) { point x0 = tree->getXProx(); double r0 = tree->getRootRadius(); fprintf(fp, "Root position = (%f, %f, %f).\n", x0.p[0], x0.p[1], x0.p[2]); fprintf(fp, "Root radius = %f.\n", r0); fprintf(fp, "Root influx = %f.\n", q0); } else { fprintf(fp, "Input CCO filename = %s\n", filenameCCO.c_str()); fprintf(fp, "Root influx = %f.\n", q0); } fprintf(fp, "isInCm = %d\n", (int) tree->getIsInCm()); fprintf(fp, "isFL = %d\n", (int) tree->getIsFL()); fprintf(fp, "isGammaStage = %d\n", (int) tree->getIsGammaStage()); if (tree->getGamRadius()) { fprintf(fp, "Gamma radius:\n"); logConstraint(fp, tree->getGamRadius()); } if (tree->getGamFlow()) { fprintf(fp, "Gamma flow:\n"); logConstraint(fp, tree->getGamFlow()); } for (int i = 0; i < size; ++i) { fprintf(fp, "\n"); fprintf(fp, "Stage[%d]\n", i); logDomainFiles(fp, (*domains)[i]); logDomain(fp, (*domains)[i], (*nTerms)[i], (*gams)[i], (*epsLims)[i], (*nus)[i]); } fprintf(fp, "\n"); fprintf(fp, "Initial dLim = %f.\n", generator->getDLimInitial()); fprintf(fp, "Last dLim = %f.\n", generator->getDLimLast()); time_t begin_time = generator->getBeginTime(); time_t end_time = generator->getEndTime(); struct tm initial_tm = *localtime(&begin_time); struct tm last_tm = *localtime(&end_time); char time_initial_c_string[21]; char time_last_c_string[21]; strftime(time_initial_c_string, 20, "%d_%m_%Y_%H_%M_%S", &initial_tm); strftime(time_last_c_string, 20, "%d_%m_%Y_%H_%M_%S", &last_tm); fprintf(fp, "\n"); fprintf(fp, "Beginning of generation time = %s\n", time_initial_c_string); fprintf(fp, "End of generation time = %s\n", time_last_c_string); }
44.022857
158
0.664071
[ "vector" ]
ee3e831e240a31e7543c6371a600160a97b01de4
2,082
cc
C++
examples/save_load.cc
Knase23/Starcraft2AiTesting
bdbf4c7103352c78b41942271c413de9cc8ad5b6
[ "MIT" ]
1,734
2017-08-09T17:12:26.000Z
2022-03-30T22:20:30.000Z
examples/save_load.cc
Knase23/Starcraft2AiTesting
bdbf4c7103352c78b41942271c413de9cc8ad5b6
[ "MIT" ]
231
2017-08-09T18:36:40.000Z
2022-02-07T04:41:49.000Z
examples/save_load.cc
Knase23/Starcraft2AiTesting
bdbf4c7103352c78b41942271c413de9cc8ad5b6
[ "MIT" ]
383
2017-08-09T18:07:40.000Z
2022-03-11T15:09:40.000Z
#include "sc2api/sc2_api.h" #include "sc2lib/sc2_lib.h" #include "sc2utils/sc2_manage_process.h" #include <iostream> using namespace sc2; class WorkerRushBot : public Agent { public: void CenterCamera(std::vector<const Unit*> units) { if (units.size() == 0) return; Point2D center; for (auto unit : units) { center += unit->pos; } center /= (float)units.size(); Debug()->DebugMoveCamera(center); Debug()->SendDebug(); } virtual void OnStep() final { const ObservationInterface* obs = Observation(); // Worker rush the enemy! // auto enemy_base = obs->GetGameInfo().enemy_start_locations[0]; const auto& workers = obs->GetUnits(Unit::Alliance::Self, IsUnit(UNIT_TYPEID::TERRAN_SCV)); for (auto unit : workers) { Actions()->UnitCommand(unit, ABILITY_ID::ATTACK, enemy_base); } CenterCamera(workers); // Create a savepoint as we arrive at the enemy base // if (!has_save) { const auto& enemies = obs->GetUnits(Unit::Alliance::Enemy, IsVisible()); if (enemies.size() > 0) { Control()->Save(); has_save = true; } } // All our workers died... Load the savepoint and try again. // if (has_save && workers.size() == 0) { Control()->Load(); } }; private: bool has_save = false; }; //************************************************************************************************* int main(int argc, char* argv[]) { sc2::Coordinator coordinator; if (!coordinator.LoadSettings(argc, argv)) { return 1; } WorkerRushBot bot; coordinator.SetParticipants({ CreateParticipant(sc2::Race::Terran, &bot), CreateComputer(sc2::Race::Protoss) }); coordinator.LaunchStarcraft(); coordinator.StartGame(sc2::kMapBelShirVestigeLE); while (coordinator.Update()); while (!sc2::PollKeyPress()); return 0; }
26.35443
99
0.545149
[ "vector" ]
ee4838c8d3de6b2f1bf8c8a0d1592eb718cb5b0b
1,123
cpp
C++
examples/angourimath/angourimath.cpp
Cooble/monobind
ef015b7c65a6b1ecbea0dcf72d2b0952abc80034
[ "MIT" ]
12
2020-09-20T14:09:25.000Z
2022-02-07T21:58:04.000Z
examples/angourimath/angourimath.cpp
Cooble/monobind
ef015b7c65a6b1ecbea0dcf72d2b0952abc80034
[ "MIT" ]
3
2020-10-31T14:05:33.000Z
2021-11-21T00:50:49.000Z
examples/angourimath/angourimath.cpp
Cooble/monobind
ef015b7c65a6b1ecbea0dcf72d2b0952abc80034
[ "MIT" ]
3
2020-10-28T15:24:40.000Z
2021-11-14T16:04:58.000Z
#include <monobind/monobind.h> #include <iostream> #include <string> #include <vector> int main() { monobind::mono mono(MONOBIND_MONO_ROOT); mono.init_jit("AngouriMathExample"); // load AngouriMath assembly monobind::assembly assembly(mono.get_domain(), "AngouriMath.dll"); monobind::class_type real_number_class(assembly.get_image(), "AngouriMath", "Entity/Number/Real"); std::cout << real_number_class << ".PositiveInfinity = " << real_number_class["PositiveInfinity"] << std::endl; auto from_string = assembly.get_method("Entity::op_Implicit(string)").as_function<monobind::object(std::string)>(); auto expr = from_string("x2 - 3x + 2"); auto solve = assembly.get_method("MathS::SolveEquation(Entity,Entity/Variable)").as_function<monobind::object(monobind::object, monobind::object)>(); auto to_variable = assembly.get_method("Entity/Variable::op_Implicit(string)").as_function<monobind::object(std::string)>(); auto var = to_variable("x"); auto result = solve(expr, var); std::cout << "solutions of (" << expr << "): " << result << std::endl; return 0; }
41.592593
153
0.69724
[ "object", "vector" ]
ee48dd5655a9160c05e3e3aff4678c210f18315b
3,141
hpp
C++
externals/numeric_bindings/boost/numeric/bindings/detail/array.hpp
fperignon/sandbox
649f09d6db7bbd84c2418de74eb9453c0131f070
[ "Apache-2.0" ]
137
2015-06-16T15:55:28.000Z
2022-03-26T06:01:59.000Z
externals/numeric_bindings/boost/numeric/bindings/detail/array.hpp
fperignon/sandbox
649f09d6db7bbd84c2418de74eb9453c0131f070
[ "Apache-2.0" ]
381
2015-09-22T15:31:08.000Z
2022-02-14T09:05:23.000Z
externals/numeric_bindings/boost/numeric/bindings/detail/array.hpp
fperignon/sandbox
649f09d6db7bbd84c2418de74eb9453c0131f070
[ "Apache-2.0" ]
30
2015-08-06T22:57:51.000Z
2022-03-02T20:30:20.000Z
// // Copyright (c) 2003 Kresimir Fresl // Copyright (c) 2009 Rutger ter Borg // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #ifndef BOOST_NUMERIC_BINDINGS_DETAIL_ARRAY_HPP #define BOOST_NUMERIC_BINDINGS_DETAIL_ARRAY_HPP #include <new> #include <boost/noncopyable.hpp> #include <boost/numeric/bindings/detail/adaptor.hpp> /* very simple dynamic array class which is used in `higher level' bindings functions for pivot and work arrays Namely, there are (at least) two versions of all bindings functions where called LAPACK function expects work and/or pivot array, e.g. `lower' level (user should provide work and pivot arrays): int sysv (SymmA& a, IVec& i, MatrB& b, Work& w); `higher' level (with `internal' work and pivot arrays): int sysv (SymmA& a, MatrB& b); Probably you ask why I didn't use std::vector. There are two reasons. First is efficiency -- std::vector's constructor initialises vector elements. Second is consistency. LAPACK functions use `info' parameter as an error indicator. On the other hand, std::vector's allocator can throw an exception if memory allocation fails. detail::array's constructor uses `new (nothrow)' which returns 0 if allocation fails. So I can check whether array::storage == 0 and return appropriate error in `info'.*/ namespace boost { namespace numeric { namespace bindings { namespace detail { template <typename T> class array : private noncopyable { public: typedef std::ptrdiff_t size_type ; array (size_type n) { stg = new (std::nothrow) T[n]; sz = (stg != nullptr) ? n : 0; } ~array() { delete[] stg; } size_type size() const { return sz; } bool valid() const { return stg != 0; } void resize (int n) { delete[] stg; stg = new (std::nothrow) T[n]; sz = (stg != 0) ? n : 0; } T* storage() { return stg; } T const* storage() const { return stg; } T& operator[] (int i) { return stg[i]; } T const& operator[] (int i) const { return stg[i]; } private: size_type sz; T* stg; }; template< typename T, typename Id, typename Enable > struct adaptor< array< T >, Id, Enable > { typedef typename copy_const< Id, T >::type value_type; typedef mpl::map< mpl::pair< tag::value_type, value_type >, mpl::pair< tag::entity, tag::vector >, mpl::pair< tag::size_type<1>, std::ptrdiff_t >, mpl::pair< tag::data_structure, tag::linear_array >, mpl::pair< tag::stride_type<1>, tag::contiguous > > property_map; static std::ptrdiff_t size1( const Id& t ) { return t.size(); } static value_type* begin_value( Id& t ) { return t.storage(); } static value_type* end_value( Id& t ) { return t.storage() + t.size(); } }; } // namespace detail } // namespace bindings } // namespace numeric } // namespace boost #endif
24.539063
73
0.629736
[ "vector" ]
ee4ba1d0ecc8f1f313cf2db1d9d3aa6f7618694f
16,639
cpp
C++
src/HF/hfphfdevicestatus.cpp
webosose/com.webos.service.hfp
bf4e38643ffe55a8b66557b2a8b6a536c098c9c2
[ "Apache-2.0" ]
null
null
null
src/HF/hfphfdevicestatus.cpp
webosose/com.webos.service.hfp
bf4e38643ffe55a8b66557b2a8b6a536c098c9c2
[ "Apache-2.0" ]
null
null
null
src/HF/hfphfdevicestatus.cpp
webosose/com.webos.service.hfp
bf4e38643ffe55a8b66557b2a8b6a536c098c9c2
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2020 LG Electronics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 #include <bitset> #include <algorithm> #include <boost/algorithm/string.hpp> #include "logging.h" #include "utils.h" #include "hfphfdevicestatus.h" #include "hfphfrole.h" #include "hfpdeviceinfo.h" HfpHFDeviceStatus::HfpHFDeviceStatus(HfpHFRole* roleObj) : mHFRole(roleObj), mDisconnectedHeldCall(false), mReceivedWaitingCall(false), mActiveNumber(""), mHasCallStatus(0), mEnabledBVRA(false), mTempDeviceInfo(nullptr) { } HfpHFDeviceStatus::~HfpHFDeviceStatus() { flushDeviceInfo(); if (mTempDeviceInfo != nullptr) delete mTempDeviceInfo; } void HfpHFDeviceStatus::flushDeviceInfo() { for (auto& i : mHfpDeviceInfo) { for(auto devitr : i.second) { if (devitr.second != nullptr) delete devitr.second; } } mHfpDeviceInfo.clear(); } void HfpHFDeviceStatus::updateStatus(const std::string &remoteAddr, std::string &resultCode) { transform(resultCode.begin(), resultCode.end(), resultCode.begin(), ::toupper); BT_DEBUG("resultCode = %s", resultCode.c_str()); if (resultCode.find("CMEE") != std::string::npos) { mHFRole->sendResponseToClient(remoteAddr, false); } else if (resultCode.find(":") != std::string::npos) { std::string atCmd = resultCode.substr(resultCode.find_first_of("+") + 1); int iSub = atCmd.find_first_of(":"); atCmd.erase(atCmd.begin() + iSub, atCmd.end()); std::string arguments = resultCode.substr(resultCode.find_last_of(":") + 1); BT_DEBUG("address = %s, AT command = %s, arguments = %s", remoteAddr.c_str(), atCmd.c_str(), arguments.c_str()); if (atCmd.compare("VGS") == 0) { updateAudioVolume(remoteAddr, std::stoi(arguments), false); mHFRole->setVolumeToAudio(remoteAddr); } else if (atCmd.compare("BVRA") == 0) { bool enabled = false; if (arguments.compare("1") == 0) enabled = true; updateBVRAStatus(enabled); mReceivedATCmd.push(receiveATCMD::ATCMD::BVRA); } else updateCallStatus(remoteAddr, atCmd, arguments); if (mReceivedATCmd.front() != receiveATCMD::ATCMD::CLCC) { if (mReceivedATCmd.front() == receiveATCMD::ATCMD::BRSF || mReceivedATCmd.front() == receiveATCMD::ATCMD::BVRA) mReceivedATCmd.pop(); else mHFRole->notifySubscribersStatusChanged(true); } } else { if (resultCode.compare("RING") == 0) updateRingStatus(remoteAddr, true); else if (resultCode.find("OK") == 0) { int receivedATCmd = -1; if (!mReceivedATCmd.empty()) { receivedATCmd = mReceivedATCmd.front(); mReceivedATCmd.pop(); BT_DEBUG("front = %d", receivedATCmd); } switch (receivedATCmd) { case receiveATCMD::ATCMD::CLCC: if (mDisconnectedHeldCall || (mReceivedWaitingCall && mHasCallStatus == 1)) eraseCallStatus(remoteAddr); mHFRole->notifySubscribersStatusChanged(true); mHasCallStatus = 0; break; case receiveATCMD::ATCMD::VGS: mHFRole->notifySubscribersStatusChanged(true); mHFRole->setVolumeToAudio(remoteAddr); // fall-through default: mHFRole->sendResponseToClient(remoteAddr, true); break; } } else if (resultCode.find("ERROR") == 0) mHFRole->sendResponseToClient(remoteAddr, false); else BT_DEBUG("Unknown result code : %s", resultCode.c_str()); } } void HfpHFDeviceStatus::updateCallStatus(const std::string &remoteAddr, const std::string &atCmd, std::string &arguments) { if (atCmd.compare("CIND") == 0) { if (arguments.find("CALL") != std::string::npos) { setCINDType(arguments); } else { removeSpace(arguments); setCINDValue(remoteAddr, arguments); } } else if (atCmd.compare("BRSF") == 0) { removeSpace(arguments); setBRSFValue(remoteAddr, arguments); mReceivedATCmd.push(receiveATCMD::ATCMD::BRSF); } else if (atCmd.compare("CIEV") == 0) { removeSpace(arguments); if (setCIEVValue(remoteAddr, arguments)) { updateRingStatus(remoteAddr, false); if (!isCallActive(remoteAddr)) clearCLCC(remoteAddr); mHFRole->sendCLCC(remoteAddr); mReceivedATCmd.push(receiveATCMD::ATCMD::CLCC); } } else if (atCmd.compare("CLCC") == 0) { updateCLCC(remoteAddr, arguments); mHasCallStatus++; } else if (atCmd.compare("CCWA") == 0) mReceivedWaitingCall = true; } void HfpHFDeviceStatus::updateRingStatus(const std::string &remoteAddr, bool receive) { HfpDeviceInfo* localDevice = findDeviceInfo(remoteAddr); if (localDevice == nullptr) { BT_DEBUG("Can't find the deviceinfo : %s", remoteAddr.c_str()); return; } localDevice->setRING(receive); } void HfpHFDeviceStatus::updateAudioVolume(const std::string &remoteAddr, const std::string &adapterAddress, int volume, bool isUpdated) { HfpDeviceInfo* localDevice = findDeviceInfo(remoteAddr, adapterAddress); if (localDevice == nullptr) { BT_DEBUG("Can't find the deviceinfo : %s", remoteAddr.c_str()); return; } localDevice->setAudioStatus(SCO::DeviceStatus::VOLUME, volume); if (isUpdated) mReceivedATCmd.push(receiveATCMD::ATCMD::VGS); } void HfpHFDeviceStatus::updateAudioVolume(const std::string &remoteAddr, int volume, bool isUpdated) { HfpDeviceInfo* localDevice = findDeviceInfo(remoteAddr); if (localDevice == nullptr) { BT_DEBUG("Can't find the deviceinfo : %s", remoteAddr.c_str()); return; } localDevice->setAudioStatus(SCO::DeviceStatus::VOLUME, volume); if (isUpdated) mReceivedATCmd.push(receiveATCMD::ATCMD::VGS); } void HfpHFDeviceStatus::clearCLCC(const std::string &remoteAddr) { HfpDeviceInfo* localDevice = findDeviceInfo(remoteAddr); if (localDevice == nullptr) { BT_DEBUG("Can't find the deviceinfo : %s", remoteAddr.c_str()); return; } mActiveNumber = ""; localDevice->clearCLCC(); } void HfpHFDeviceStatus::updateCLCC(const std::string &remoteAddr, const std::string &arguments) { HfpDeviceInfo* localDevice = findDeviceInfo(remoteAddr); if (localDevice == nullptr) { BT_DEBUG("Can't find the deviceinfo : %s", remoteAddr.c_str()); return; } auto convertStatus = [] (int status, int type)->std::string{ if (type == CLCC::DeviceStatus::DIRECTION) { switch (status) { case HFGeneral::Status::STATUSFALSE: return "outgoing"; case HFGeneral::Status::STATUSTRUE: return "incoming"; default: return "inactive"; } } else { switch (status) { case CLCC::CallStatus::ACTIVE: return "active"; case CLCC::CallStatus::HELD: return "held"; case CLCC::CallStatus::DIALING: return "dialing"; case CLCC::CallStatus::ALERTING: return "alerting"; case CLCC::CallStatus::INCOMING: return "incoming"; case CLCC::CallStatus::WAITING: return "waiting"; case CLCC::CallStatus::CALLHELDBYRESPONSE: return "callheldbyresponse"; default: return "inactive"; } } }; std::vector<std::string> argArrays; boost::split(argArrays, arguments, boost::is_any_of(",")); if (argArrays.size() < 7) return; std::string number = argArrays[CLCC::DeviceStatus::NUMBER].substr(1, argArrays[CLCC::DeviceStatus::NUMBER].size() - 2); for (int i = 0; i < CLCC::DeviceStatus::MAXSTATUS; i++) { if (i != CLCC::DeviceStatus::NUMBER) { if (i == CLCC::DeviceStatus::STATUS || i == CLCC::DeviceStatus::DIRECTION) localDevice->setCallStatus(number, i, convertStatus(std::stoi(argArrays[i]), i)); else localDevice->setCallStatus(number, i, argArrays[i]); } } mActiveNumber = number; } bool HfpHFDeviceStatus::isCallActive(const std::string &remoteAddr) { HfpDeviceInfo* localDevice = findDeviceInfo(remoteAddr); if (!localDevice) return false; if (localDevice->getDeviceStatus(CIND::DeviceStatus::CALL) == CIND::Call::INACTIVE) return false; return true; } HfpDeviceInfo* HfpHFDeviceStatus::findDeviceInfo(const std::string &remoteAddr) const { auto localDevice = mHfpDeviceInfo.find(remoteAddr); if (localDevice != mHfpDeviceInfo.end()) return nullptr; return nullptr; } HfpDeviceInfo* HfpHFDeviceStatus::findDeviceInfo(const std::string &remoteAddr, const std::string &adapterAddr) const { auto adapterInfo = mHfpDeviceInfo.find(adapterAddr); if (adapterInfo != mHfpDeviceInfo.end()) { auto deviceInfo = adapterInfo->second.find(remoteAddr); if(deviceInfo != adapterInfo->second.end()) return deviceInfo->second; } return nullptr; } bool HfpHFDeviceStatus::createDeviceInfo(const std::string &remoteAddr , const std::string &adapterAddr) { if (isDeviceAvailable(remoteAddr,adapterAddr)) { BT_DEBUG("Local device already has %s's DeviceInfo", remoteAddr.c_str()); return false; } HfpDeviceInfo* deviceInfo; if (mTempDeviceInfo == nullptr) { deviceInfo = new HfpDeviceInfo; } else { deviceInfo = mTempDeviceInfo; mTempDeviceInfo = nullptr; } auto adapterInfo = mHfpDeviceInfo.find(adapterAddr); if(adapterInfo != mHfpDeviceInfo.end()) { adapterInfo->second.insert(std::make_pair(remoteAddr, deviceInfo)); } else { std::unordered_map<std::string, HfpDeviceInfo*> temp ; temp.insert(std::make_pair(remoteAddr,deviceInfo)); mHfpDeviceInfo.insert(std::make_pair(adapterAddr,temp)); } deviceInfo->setAudioStatus(SCO::DeviceStatus::VOLUME, 9); BT_DEBUG("Create the %s's DeviceInfo", remoteAddr.c_str()); /*if (isCallActive(remoteAddr)) { mHFRole->sendCLCC(remoteAddr); mReceivedATCmd.push(receiveATCMD::ATCMD::CLCC); }*/ return true; } bool HfpHFDeviceStatus::removeDeviceInfo(const std::string &remoteAddr , const std::string &adapterAddr) { auto adapterItr = mHfpDeviceInfo.find(adapterAddr); if(adapterItr != mHfpDeviceInfo.end()) { auto device = adapterItr->second.find(remoteAddr); if(device != adapterItr->second.end()) { BT_DEBUG("Remove adapter %s's device %s", adapterAddr.c_str(), remoteAddr.c_str()); delete device->second; adapterItr->second.erase(device); if(adapterItr->second.size() == 0) { BT_DEBUG("Remove adapter %s's Info", adapterAddr.c_str()); mHfpDeviceInfo.erase(adapterAddr); } return true; } } return false; } bool HfpHFDeviceStatus::removeAllDevicebyAdapterAddress(const std::string &adapterAddr) { auto adapterItr = mHfpDeviceInfo.find(adapterAddr); if(adapterItr != mHfpDeviceInfo.end()) { for (auto devitr : adapterItr->second) { if(devitr.second) delete devitr.second; } mHfpDeviceInfo.erase(adapterAddr); return true; } return false; } void HfpHFDeviceStatus::setBRSFValue(const std::string &remoteAddr, const std::string &arguments) { HfpDeviceInfo* localDevice = findDeviceInfo(remoteAddr); if (localDevice == nullptr) { BT_DEBUG("Can't find the device info : %s", remoteAddr.c_str()); return; } int iValue = std::stoi(arguments); #if HFP_V_1_7 == TRUE std::bitset<12> bValue(iValue); #else std::bitset<10> bValue(iValue); #endif for (int i = 0; i < bValue.size(); i ++) { localDevice->setAGFeature(i, bValue.test(i)); } if (bValue.test(BRSF::DeviceStatus::NREC)) { mHFRole->sendNREC(remoteAddr); BT_DEBUG("%s is supporting the NREC", remoteAddr.c_str()); } } void HfpHFDeviceStatus::setCINDType(const std::string &arguments) { int firstIndex = 0; int secondIndex = 0; for(int i = 0; i < CIND::DeviceStatus::MAXSTATUS; i++) { firstIndex = arguments.find_first_of("\"", secondIndex); secondIndex = arguments.find_first_of("\"", firstIndex + 2); std::string sIndex = arguments.substr(firstIndex + 1, secondIndex - firstIndex - 1); storeCINDIndex(sIndex, i); secondIndex += 2; } } void HfpHFDeviceStatus::storeCINDIndex(const std::string &type, int index) { if (mTempDeviceInfo == nullptr) mTempDeviceInfo = new HfpDeviceInfo; if (type.compare("CALL") == 0) mTempDeviceInfo->setCINDIndex(index, CIND::DeviceStatus::CALL); else if (type.compare("CALLSETUP") == 0) mTempDeviceInfo->setCINDIndex(index, CIND::DeviceStatus::CALLSETUP); else if (type.compare("SERVICE") == 0) mTempDeviceInfo->setCINDIndex(index, CIND::DeviceStatus::SERVICE); else if (type.compare("SIGNAL") == 0) mTempDeviceInfo->setCINDIndex(index, CIND::DeviceStatus::SIGNAL); else if (type.compare("ROAM") == 0) mTempDeviceInfo->setCINDIndex(index, CIND::DeviceStatus::ROAMING); else if (type.compare("BATTCHG") == 0) mTempDeviceInfo->setCINDIndex(index, CIND::DeviceStatus::BATTCHG); else if (type.compare("CALLHELD") == 0) mTempDeviceInfo->setCINDIndex(index, CIND::DeviceStatus::CALLHELD); } void HfpHFDeviceStatus::setCINDValue(const std::string &remoteAddr, const std::string &arguments) { if (mTempDeviceInfo != nullptr) { int firstIndex = 0; for (int i = CIND::DeviceStatus::SERVICE; i < CIND::DeviceStatus::MAXSTATUS; i++) { std::string sValue = arguments.substr(firstIndex, 1); int iValue = std::stoi(sValue); mTempDeviceInfo->setDeviceStatus(i, iValue); firstIndex += 2; } } else BT_DEBUG("mTempDeviceInfo is NULL"); } bool HfpHFDeviceStatus::setCIEVValue(const std::string &remoteAddr, const std::string &arguments) { HfpDeviceInfo* localDevice = findDeviceInfo(remoteAddr); if (localDevice == nullptr) { BT_DEBUG("Can't find the deviceinfo : %s", remoteAddr.c_str()); return false; } std::string sIndex = arguments.substr(0, 1); int iIndex = std::stoi(sIndex) - 1; std::string sValue = arguments.substr(2, 3); int iValue = std::stoi(sValue); if (localDevice->setDeviceStatus(iIndex, iValue)) { if (localDevice->getCINDIndex(iIndex) == (CIND::DeviceStatus::CALLHELD) && iValue == CIND::CallHeld::NOHELD) mDisconnectedHeldCall = true; if (localDevice->getCINDIndex(iIndex) == (CIND::DeviceStatus::CALLHELD)) mReceivedWaitingCall = false; return true; } return false; } bool HfpHFDeviceStatus::isDeviceAvailable(const std::string &remoteAddr , const std::string &adapterAddr) const { auto adapterInfo = mHfpDeviceInfo.find(adapterAddr); if (adapterInfo == mHfpDeviceInfo.end()) return false; else { auto deviceInfo = adapterInfo->second.find(remoteAddr); if(deviceInfo == adapterInfo->second.end()) return false; } return true; } bool HfpHFDeviceStatus::isAdapterAvailable(const std::string &adapterAddr) const { auto adapterInfo = mHfpDeviceInfo.find(adapterAddr); if (adapterInfo == mHfpDeviceInfo.end()) return false; return true; } BluetoothErrorCode HfpHFDeviceStatus::checkAddress(const std::string &remoteAddr) const { if (remoteAddr.size() != 17) return BT_ERR_ADDRESS_INVALID; //if (isDeviceAvailable(remoteAddr)) Commented adapter change required //return BT_ERR_NO_ERROR; return BT_ERR_DEVICE_NOT_CONNECTED; } BluetoothErrorCode HfpHFDeviceStatus::checkAddress(const std::string &remoteAddr, const std::string &adapterAddress) const { if (remoteAddr.size() != 17) return BT_ERR_ADDRESS_INVALID; if (isDeviceAvailable(remoteAddr, adapterAddress)) return BT_ERR_NO_ERROR; return BT_ERR_DEVICE_NOT_CONNECTED; } bool HfpHFDeviceStatus::isDeviceConnecting() const { if (mHfpDeviceInfo.empty() && mTempDeviceInfo != nullptr) { BT_DEBUG("Device is connecting..."); return true; } return false; } void HfpHFDeviceStatus::eraseCallStatus(const std::string &remoteAddr) { HfpDeviceInfo* localDevice = findDeviceInfo(remoteAddr); if (localDevice == nullptr) { BT_DEBUG("Can't find the deviceinfo : %s", remoteAddr.c_str()); return; } BT_DEBUG("activeNumber = %s", mActiveNumber.c_str()); for (auto& iterCallStatus : localDevice->getCallStatusList()) { if (iterCallStatus.first.compare(mActiveNumber) != 0) localDevice->eraseCallStatus(iterCallStatus.first); } mActiveNumber = ""; mDisconnectedHeldCall = false; } bool HfpHFDeviceStatus::updateSCOStatus(const std::string &remoteAddr, const std::string &adapterAddr, bool status) { HfpDeviceInfo* localDevice = findDeviceInfo(remoteAddr,adapterAddr); if (localDevice == nullptr) { BT_DEBUG("Can't find the deviceinfo : %s for adapter %s ", remoteAddr.c_str(),adapterAddr.c_str()); return false; } int SCOStatus = status ? HFGeneral::Status::STATUSTRUE : HFGeneral::Status::STATUSFALSE; if (SCOStatus == localDevice->getAudioStatus(SCO::DeviceStatus::CONNECTED)) return false; localDevice->setAudioStatus(SCO::DeviceStatus::CONNECTED, SCOStatus); return true; }
27.548013
135
0.715187
[ "vector", "transform" ]
ee4babd2a0c8672fcb45218371f3f2fabe6d7d04
2,178
cpp
C++
src/raft/snapshot.cpp
CheranMahalingam/Distributed-Video-Processor
2940b1d92f6f6d940304de24d79680f01c888c47
[ "MIT" ]
null
null
null
src/raft/snapshot.cpp
CheranMahalingam/Distributed-Video-Processor
2940b1d92f6f6d940304de24d79680f01c888c47
[ "MIT" ]
null
null
null
src/raft/snapshot.cpp
CheranMahalingam/Distributed-Video-Processor
2940b1d92f6f6d940304de24d79680f01c888c47
[ "MIT" ]
1
2022-01-09T22:43:46.000Z
2022-01-09T22:43:46.000Z
#include "snapshot.h" namespace raft { Snapshot::Snapshot(const std::string dir) { std::filesystem::create_directories(dir); log_file_ = dir + "log"; state_file_ = dir + "state"; } void Snapshot::PersistState(const int term, const std::string vote_id) { std::fstream out(state_file_, std::ios::out | std::ios::trunc | std::ios::binary); rpc::State state; state.set_term(term); state.set_voteid(vote_id); SerializeDelimitedToOstream(state, &out); logger(LogLevel::Debug) << "Persisted state to disk"; out.close(); } void Snapshot::PersistLog(const std::vector<rpc::LogEntry>& entries, const bool append) { auto flags = std::ios::out | std::ios::binary; if (append) { flags |= std::ios::app; } else { flags |= std::ios::trunc; } std::fstream out(log_file_, flags); for (auto &entry:entries) { SerializeDelimitedToOstream(entry, &out); } logger(LogLevel::Debug) << "Persisted log to disk"; } std::tuple<int, std::string> Snapshot::RestoreState() { std::fstream in(state_file_, std::ios::in | std::ios::binary); IstreamInputStream state_stream(&in); rpc::State state; ParseDelimitedFromZeroCopyStream(&state, &state_stream, nullptr); logger(LogLevel::Debug) << "Restoring state from disk, term =" << state.term() << "voteId =" << state.voteid(); in.close(); return std::make_tuple(state.term(), state.voteid()); } std::vector<rpc::LogEntry> Snapshot::RestoreLog() { std::fstream in(log_file_, std::ios::in | std::ios::binary); IstreamInputStream log_stream(&in); std::vector<rpc::LogEntry> entries; rpc::LogEntry entry; while (ParseDelimitedFromZeroCopyStream(&entry, &log_stream, nullptr)) { entries.push_back(entry); } logger(LogLevel::Debug) << "Restoring log from disk, size =" << entries.size(); in.close(); return entries; } bool Snapshot::Empty() const { std::ifstream state(state_file_, std::ios::binary); std::ifstream log(log_file_, std::ios::binary); return state.peek() == std::ifstream::traits_type::eof() && log.peek() == std::ifstream::traits_type::eof(); } }
28.657895
115
0.647842
[ "vector" ]
ee4efdab93b4aae42d06dfa38a0b166fb7108712
55,868
cpp
C++
src/hotspot/share/jvmci/jvmciCodeInstaller.cpp
desiyonan/OpenJDK8
74d4f56b6312c303642e053e5d428b44cc8326c5
[ "MIT" ]
2
2018-06-19T05:43:32.000Z
2018-06-23T10:04:56.000Z
src/hotspot/share/jvmci/jvmciCodeInstaller.cpp
desiyonan/OpenJDK8
74d4f56b6312c303642e053e5d428b44cc8326c5
[ "MIT" ]
null
null
null
src/hotspot/share/jvmci/jvmciCodeInstaller.cpp
desiyonan/OpenJDK8
74d4f56b6312c303642e053e5d428b44cc8326c5
[ "MIT" ]
null
null
null
/* * Copyright (c) 2011, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ #include "precompiled.hpp" #include "asm/register.hpp" #include "classfile/vmSymbols.hpp" #include "code/compiledIC.hpp" #include "code/vmreg.inline.hpp" #include "compiler/compileBroker.hpp" #include "compiler/disassembler.hpp" #include "jvmci/jvmciEnv.hpp" #include "jvmci/jvmciCompiler.hpp" #include "jvmci/jvmciCodeInstaller.hpp" #include "jvmci/jvmciJavaClasses.hpp" #include "jvmci/jvmciCompilerToVM.hpp" #include "jvmci/jvmciRuntime.hpp" #include "memory/allocation.inline.hpp" #include "oops/arrayOop.inline.hpp" #include "oops/oop.inline.hpp" #include "oops/objArrayOop.inline.hpp" #include "oops/typeArrayOop.inline.hpp" #include "runtime/interfaceSupport.inline.hpp" #include "runtime/javaCalls.hpp" #include "runtime/jniHandles.inline.hpp" #include "runtime/safepointMechanism.inline.hpp" #include "runtime/sharedRuntime.hpp" #include "utilities/align.hpp" // frequently used constants // Allocate them with new so they are never destroyed (otherwise, a // forced exit could destroy these objects while they are still in // use). ConstantOopWriteValue* CodeInstaller::_oop_null_scope_value = new (ResourceObj::C_HEAP, mtCompiler) ConstantOopWriteValue(NULL); ConstantIntValue* CodeInstaller::_int_m1_scope_value = new (ResourceObj::C_HEAP, mtCompiler) ConstantIntValue(-1); ConstantIntValue* CodeInstaller::_int_0_scope_value = new (ResourceObj::C_HEAP, mtCompiler) ConstantIntValue((jint)0); ConstantIntValue* CodeInstaller::_int_1_scope_value = new (ResourceObj::C_HEAP, mtCompiler) ConstantIntValue(1); ConstantIntValue* CodeInstaller::_int_2_scope_value = new (ResourceObj::C_HEAP, mtCompiler) ConstantIntValue(2); LocationValue* CodeInstaller::_illegal_value = new (ResourceObj::C_HEAP, mtCompiler) LocationValue(Location()); Method* getMethodFromHotSpotMethod(oop hotspot_method) { assert(hotspot_method != NULL && hotspot_method->is_a(HotSpotResolvedJavaMethodImpl::klass()), "sanity"); return CompilerToVM::asMethod(hotspot_method); } VMReg getVMRegFromLocation(Handle location, int total_frame_size, TRAPS) { if (location.is_null()) { THROW_NULL(vmSymbols::java_lang_NullPointerException()); } Handle reg(THREAD, code_Location::reg(location)); jint offset = code_Location::offset(location); if (reg.not_null()) { // register jint number = code_Register::number(reg); VMReg vmReg = CodeInstaller::get_hotspot_reg(number, CHECK_NULL); if (offset % 4 == 0) { return vmReg->next(offset / 4); } else { JVMCI_ERROR_NULL("unaligned subregister offset %d in oop map", offset); } } else { // stack slot if (offset % 4 == 0) { VMReg vmReg = VMRegImpl::stack2reg(offset / 4); if (!OopMapValue::legal_vm_reg_name(vmReg)) { // This restriction only applies to VMRegs that are used in OopMap but // since that's the only use of VMRegs it's simplest to put this test // here. This test should also be equivalent legal_vm_reg_name but JVMCI // clients can use max_oop_map_stack_stack_offset to detect this problem // directly. The asserts just ensure that the tests are in agreement. assert(offset > CompilerToVM::Data::max_oop_map_stack_offset(), "illegal VMReg"); JVMCI_ERROR_NULL("stack offset %d is too large to be encoded in OopMap (max %d)", offset, CompilerToVM::Data::max_oop_map_stack_offset()); } assert(OopMapValue::legal_vm_reg_name(vmReg), "illegal VMReg"); return vmReg; } else { JVMCI_ERROR_NULL("unaligned stack offset %d in oop map", offset); } } } objArrayOop CodeInstaller::sites() { return (objArrayOop) JNIHandles::resolve(_sites_handle); } arrayOop CodeInstaller::code() { return (arrayOop) JNIHandles::resolve(_code_handle); } arrayOop CodeInstaller::data_section() { return (arrayOop) JNIHandles::resolve(_data_section_handle); } objArrayOop CodeInstaller::data_section_patches() { return (objArrayOop) JNIHandles::resolve(_data_section_patches_handle); } #ifndef PRODUCT objArrayOop CodeInstaller::comments() { return (objArrayOop) JNIHandles::resolve(_comments_handle); } #endif oop CodeInstaller::word_kind() { return JNIHandles::resolve(_word_kind_handle); } // creates a HotSpot oop map out of the byte arrays provided by DebugInfo OopMap* CodeInstaller::create_oop_map(Handle debug_info, TRAPS) { Handle reference_map(THREAD, DebugInfo::referenceMap(debug_info)); if (reference_map.is_null()) { THROW_NULL(vmSymbols::java_lang_NullPointerException()); } if (!reference_map->is_a(HotSpotReferenceMap::klass())) { JVMCI_ERROR_NULL("unknown reference map: %s", reference_map->klass()->signature_name()); } if (!_has_wide_vector && SharedRuntime::is_wide_vector(HotSpotReferenceMap::maxRegisterSize(reference_map))) { if (SharedRuntime::polling_page_vectors_safepoint_handler_blob() == NULL) { JVMCI_ERROR_NULL("JVMCI is producing code using vectors larger than the runtime supports"); } _has_wide_vector = true; } OopMap* map = new OopMap(_total_frame_size, _parameter_count); objArrayHandle objects(THREAD, HotSpotReferenceMap::objects(reference_map)); objArrayHandle derivedBase(THREAD, HotSpotReferenceMap::derivedBase(reference_map)); typeArrayHandle sizeInBytes(THREAD, HotSpotReferenceMap::sizeInBytes(reference_map)); if (objects.is_null() || derivedBase.is_null() || sizeInBytes.is_null()) { THROW_NULL(vmSymbols::java_lang_NullPointerException()); } if (objects->length() != derivedBase->length() || objects->length() != sizeInBytes->length()) { JVMCI_ERROR_NULL("arrays in reference map have different sizes: %d %d %d", objects->length(), derivedBase->length(), sizeInBytes->length()); } for (int i = 0; i < objects->length(); i++) { Handle location(THREAD, objects->obj_at(i)); Handle baseLocation(THREAD, derivedBase->obj_at(i)); int bytes = sizeInBytes->int_at(i); VMReg vmReg = getVMRegFromLocation(location, _total_frame_size, CHECK_NULL); if (baseLocation.not_null()) { // derived oop #ifdef _LP64 if (bytes == 8) { #else if (bytes == 4) { #endif VMReg baseReg = getVMRegFromLocation(baseLocation, _total_frame_size, CHECK_NULL); map->set_derived_oop(vmReg, baseReg); } else { JVMCI_ERROR_NULL("invalid derived oop size in ReferenceMap: %d", bytes); } #ifdef _LP64 } else if (bytes == 8) { // wide oop map->set_oop(vmReg); } else if (bytes == 4) { // narrow oop map->set_narrowoop(vmReg); #else } else if (bytes == 4) { map->set_oop(vmReg); #endif } else { JVMCI_ERROR_NULL("invalid oop size in ReferenceMap: %d", bytes); } } Handle callee_save_info(THREAD, (oop) DebugInfo::calleeSaveInfo(debug_info)); if (callee_save_info.not_null()) { objArrayHandle registers(THREAD, RegisterSaveLayout::registers(callee_save_info)); typeArrayHandle slots(THREAD, RegisterSaveLayout::slots(callee_save_info)); for (jint i = 0; i < slots->length(); i++) { Handle jvmci_reg (THREAD, registers->obj_at(i)); jint jvmci_reg_number = code_Register::number(jvmci_reg); VMReg hotspot_reg = CodeInstaller::get_hotspot_reg(jvmci_reg_number, CHECK_NULL); // HotSpot stack slots are 4 bytes jint jvmci_slot = slots->int_at(i); jint hotspot_slot = jvmci_slot * VMRegImpl::slots_per_word; VMReg hotspot_slot_as_reg = VMRegImpl::stack2reg(hotspot_slot); map->set_callee_saved(hotspot_slot_as_reg, hotspot_reg); #ifdef _LP64 // (copied from generate_oop_map() in c1_Runtime1_x86.cpp) VMReg hotspot_slot_hi_as_reg = VMRegImpl::stack2reg(hotspot_slot + 1); map->set_callee_saved(hotspot_slot_hi_as_reg, hotspot_reg->next()); #endif } } return map; } AOTOopRecorder::AOTOopRecorder(Arena* arena, bool deduplicate) : OopRecorder(arena, deduplicate) { _meta_refs = new GrowableArray<jobject>(); } int AOTOopRecorder::nr_meta_refs() const { return _meta_refs->length(); } jobject AOTOopRecorder::meta_element(int pos) const { return _meta_refs->at(pos); } int AOTOopRecorder::find_index(Metadata* h) { JavaThread* THREAD = JavaThread::current(); int oldCount = metadata_count(); int index = this->OopRecorder::find_index(h); int newCount = metadata_count(); if (oldCount == newCount) { // found a match return index; } vmassert(index + 1 == newCount, "must be last"); Klass* klass = NULL; oop result = NULL; if (h->is_klass()) { klass = (Klass*) h; result = CompilerToVM::get_jvmci_type(klass, CATCH); } else if (h->is_method()) { Method* method = (Method*) h; methodHandle mh(method); result = CompilerToVM::get_jvmci_method(method, CATCH); } jobject ref = JNIHandles::make_local(THREAD, result); record_meta_ref(ref, index); return index; } int AOTOopRecorder::find_index(jobject h) { if (h == NULL) { return 0; } oop javaMirror = JNIHandles::resolve(h); Klass* klass = java_lang_Class::as_Klass(javaMirror); return find_index(klass); } void AOTOopRecorder::record_meta_ref(jobject o, int index) { assert(index > 0, "must be 1..n"); index -= 1; // reduce by one to convert to array index assert(index == _meta_refs->length(), "must be last"); _meta_refs->append(o); } void* CodeInstaller::record_metadata_reference(CodeSection* section, address dest, Handle constant, TRAPS) { /* * This method needs to return a raw (untyped) pointer, since the value of a pointer to the base * class is in general not equal to the pointer of the subclass. When patching metaspace pointers, * the compiler expects a direct pointer to the subclass (Klass* or Method*), not a pointer to the * base class (Metadata* or MetaspaceObj*). */ oop obj = HotSpotMetaspaceConstantImpl::metaspaceObject(constant); if (obj->is_a(HotSpotResolvedObjectTypeImpl::klass())) { Klass* klass = java_lang_Class::as_Klass(HotSpotResolvedObjectTypeImpl::javaClass(obj)); assert(!HotSpotMetaspaceConstantImpl::compressed(constant), "unexpected compressed klass pointer %s @ " INTPTR_FORMAT, klass->name()->as_C_string(), p2i(klass)); int index = _oop_recorder->find_index(klass); section->relocate(dest, metadata_Relocation::spec(index)); TRACE_jvmci_3("metadata[%d of %d] = %s", index, _oop_recorder->metadata_count(), klass->name()->as_C_string()); return klass; } else if (obj->is_a(HotSpotResolvedJavaMethodImpl::klass())) { Method* method = (Method*) (address) HotSpotResolvedJavaMethodImpl::metaspaceMethod(obj); assert(!HotSpotMetaspaceConstantImpl::compressed(constant), "unexpected compressed method pointer %s @ " INTPTR_FORMAT, method->name()->as_C_string(), p2i(method)); int index = _oop_recorder->find_index(method); section->relocate(dest, metadata_Relocation::spec(index)); TRACE_jvmci_3("metadata[%d of %d] = %s", index, _oop_recorder->metadata_count(), method->name()->as_C_string()); return method; } else { JVMCI_ERROR_NULL("unexpected metadata reference for constant of type %s", obj->klass()->signature_name()); } } #ifdef _LP64 narrowKlass CodeInstaller::record_narrow_metadata_reference(CodeSection* section, address dest, Handle constant, TRAPS) { oop obj = HotSpotMetaspaceConstantImpl::metaspaceObject(constant); assert(HotSpotMetaspaceConstantImpl::compressed(constant), "unexpected uncompressed pointer"); if (!obj->is_a(HotSpotResolvedObjectTypeImpl::klass())) { JVMCI_ERROR_0("unexpected compressed pointer of type %s", obj->klass()->signature_name()); } Klass* klass = java_lang_Class::as_Klass(HotSpotResolvedObjectTypeImpl::javaClass(obj)); int index = _oop_recorder->find_index(klass); section->relocate(dest, metadata_Relocation::spec(index)); TRACE_jvmci_3("narrowKlass[%d of %d] = %s", index, _oop_recorder->metadata_count(), klass->name()->as_C_string()); return Klass::encode_klass(klass); } #endif Location::Type CodeInstaller::get_oop_type(Thread* thread, Handle value) { Handle valueKind(thread, Value::valueKind(value)); Handle platformKind(thread, ValueKind::platformKind(valueKind)); if (platformKind == word_kind()) { return Location::oop; } else { return Location::narrowoop; } } ScopeValue* CodeInstaller::get_scope_value(Handle value, BasicType type, GrowableArray<ScopeValue*>* objects, ScopeValue* &second, TRAPS) { second = NULL; if (value.is_null()) { THROW_NULL(vmSymbols::java_lang_NullPointerException()); } else if (value == Value::ILLEGAL()) { if (type != T_ILLEGAL) { JVMCI_ERROR_NULL("unexpected illegal value, expected %s", basictype_to_str(type)); } return _illegal_value; } else if (value->is_a(RegisterValue::klass())) { Handle reg(THREAD, RegisterValue::reg(value)); jint number = code_Register::number(reg); VMReg hotspotRegister = get_hotspot_reg(number, CHECK_NULL); if (is_general_purpose_reg(hotspotRegister)) { Location::Type locationType; if (type == T_OBJECT) { locationType = get_oop_type(THREAD, value); } else if (type == T_LONG) { locationType = Location::lng; } else if (type == T_INT || type == T_FLOAT || type == T_SHORT || type == T_CHAR || type == T_BYTE || type == T_BOOLEAN) { locationType = Location::int_in_long; } else { JVMCI_ERROR_NULL("unexpected type %s in cpu register", basictype_to_str(type)); } ScopeValue* value = new LocationValue(Location::new_reg_loc(locationType, hotspotRegister)); if (type == T_LONG) { second = value; } return value; } else { Location::Type locationType; if (type == T_FLOAT) { // this seems weird, but the same value is used in c1_LinearScan locationType = Location::normal; } else if (type == T_DOUBLE) { locationType = Location::dbl; } else { JVMCI_ERROR_NULL("unexpected type %s in floating point register", basictype_to_str(type)); } ScopeValue* value = new LocationValue(Location::new_reg_loc(locationType, hotspotRegister)); if (type == T_DOUBLE) { second = value; } return value; } } else if (value->is_a(StackSlot::klass())) { jint offset = StackSlot::offset(value); if (StackSlot::addFrameSize(value)) { offset += _total_frame_size; } Location::Type locationType; if (type == T_OBJECT) { locationType = get_oop_type(THREAD, value); } else if (type == T_LONG) { locationType = Location::lng; } else if (type == T_DOUBLE) { locationType = Location::dbl; } else if (type == T_INT || type == T_FLOAT || type == T_SHORT || type == T_CHAR || type == T_BYTE || type == T_BOOLEAN) { locationType = Location::normal; } else { JVMCI_ERROR_NULL("unexpected type %s in stack slot", basictype_to_str(type)); } ScopeValue* value = new LocationValue(Location::new_stk_loc(locationType, offset)); if (type == T_DOUBLE || type == T_LONG) { second = value; } return value; } else if (value->is_a(JavaConstant::klass())) { if (value->is_a(PrimitiveConstant::klass())) { if (value->is_a(RawConstant::klass())) { jlong prim = PrimitiveConstant::primitive(value); return new ConstantLongValue(prim); } else { Handle primitive_constant_kind(THREAD, PrimitiveConstant::kind(value)); BasicType constantType = JVMCIRuntime::kindToBasicType(primitive_constant_kind, CHECK_NULL); if (type != constantType) { JVMCI_ERROR_NULL("primitive constant type doesn't match, expected %s but got %s", basictype_to_str(type), basictype_to_str(constantType)); } if (type == T_INT || type == T_FLOAT) { jint prim = (jint)PrimitiveConstant::primitive(value); switch (prim) { case -1: return _int_m1_scope_value; case 0: return _int_0_scope_value; case 1: return _int_1_scope_value; case 2: return _int_2_scope_value; default: return new ConstantIntValue(prim); } } else if (type == T_LONG || type == T_DOUBLE) { jlong prim = PrimitiveConstant::primitive(value); second = _int_1_scope_value; return new ConstantLongValue(prim); } else { JVMCI_ERROR_NULL("unexpected primitive constant type %s", basictype_to_str(type)); } } } else if (value->is_a(NullConstant::klass()) || value->is_a(HotSpotCompressedNullConstant::klass())) { if (type == T_OBJECT) { return _oop_null_scope_value; } else { JVMCI_ERROR_NULL("unexpected null constant, expected %s", basictype_to_str(type)); } } else if (value->is_a(HotSpotObjectConstantImpl::klass())) { if (type == T_OBJECT) { oop obj = HotSpotObjectConstantImpl::object(value); if (obj == NULL) { JVMCI_ERROR_NULL("null value must be in NullConstant"); } return new ConstantOopWriteValue(JNIHandles::make_local(obj)); } else { JVMCI_ERROR_NULL("unexpected object constant, expected %s", basictype_to_str(type)); } } } else if (value->is_a(VirtualObject::klass())) { if (type == T_OBJECT) { int id = VirtualObject::id(value); if (0 <= id && id < objects->length()) { ScopeValue* object = objects->at(id); if (object != NULL) { return object; } } JVMCI_ERROR_NULL("unknown virtual object id %d", id); } else { JVMCI_ERROR_NULL("unexpected virtual object, expected %s", basictype_to_str(type)); } } JVMCI_ERROR_NULL("unexpected value in scope: %s", value->klass()->signature_name()) } void CodeInstaller::record_object_value(ObjectValue* sv, Handle value, GrowableArray<ScopeValue*>* objects, TRAPS) { // Might want a HandleMark here. Handle type(THREAD, VirtualObject::type(value)); int id = VirtualObject::id(value); oop javaMirror = HotSpotResolvedObjectTypeImpl::javaClass(type); Klass* klass = java_lang_Class::as_Klass(javaMirror); bool isLongArray = klass == Universe::longArrayKlassObj(); objArrayHandle values(THREAD, VirtualObject::values(value)); objArrayHandle slotKinds(THREAD, VirtualObject::slotKinds(value)); for (jint i = 0; i < values->length(); i++) { HandleMark hm(THREAD); ScopeValue* cur_second = NULL; Handle object(THREAD, values->obj_at(i)); Handle slot_kind (THREAD, slotKinds->obj_at(i)); BasicType type = JVMCIRuntime::kindToBasicType(slot_kind, CHECK); ScopeValue* value = get_scope_value(object, type, objects, cur_second, CHECK); if (isLongArray && cur_second == NULL) { // we're trying to put ints into a long array... this isn't really valid, but it's used for some optimizations. // add an int 0 constant cur_second = _int_0_scope_value; } if (cur_second != NULL) { sv->field_values()->append(cur_second); } assert(value != NULL, "missing value"); sv->field_values()->append(value); } } MonitorValue* CodeInstaller::get_monitor_value(Handle value, GrowableArray<ScopeValue*>* objects, TRAPS) { if (value.is_null()) { THROW_NULL(vmSymbols::java_lang_NullPointerException()); } if (!value->is_a(StackLockValue::klass())) { JVMCI_ERROR_NULL("Monitors must be of type StackLockValue, got %s", value->klass()->signature_name()); } ScopeValue* second = NULL; Handle stack_lock_owner(THREAD, StackLockValue::owner(value)); ScopeValue* owner_value = get_scope_value(stack_lock_owner, T_OBJECT, objects, second, CHECK_NULL); assert(second == NULL, "monitor cannot occupy two stack slots"); Handle stack_lock_slot(THREAD, StackLockValue::slot(value)); ScopeValue* lock_data_value = get_scope_value(stack_lock_slot, T_LONG, objects, second, CHECK_NULL); assert(second == lock_data_value, "monitor is LONG value that occupies two stack slots"); assert(lock_data_value->is_location(), "invalid monitor location"); Location lock_data_loc = ((LocationValue*)lock_data_value)->location(); bool eliminated = false; if (StackLockValue::eliminated(value)) { eliminated = true; } return new MonitorValue(owner_value, lock_data_loc, eliminated); } void CodeInstaller::initialize_dependencies(oop compiled_code, OopRecorder* recorder, TRAPS) { JavaThread* thread = JavaThread::current(); assert(THREAD == thread, ""); CompilerThread* compilerThread = thread->is_Compiler_thread() ? thread->as_CompilerThread() : NULL; _oop_recorder = recorder; _dependencies = new Dependencies(&_arena, _oop_recorder, compilerThread != NULL ? compilerThread->log() : NULL); objArrayHandle assumptions(THREAD, HotSpotCompiledCode::assumptions(compiled_code)); if (!assumptions.is_null()) { int length = assumptions->length(); for (int i = 0; i < length; ++i) { Handle assumption(THREAD, assumptions->obj_at(i)); if (!assumption.is_null()) { if (assumption->klass() == Assumptions_NoFinalizableSubclass::klass()) { assumption_NoFinalizableSubclass(THREAD, assumption); } else if (assumption->klass() == Assumptions_ConcreteSubtype::klass()) { assumption_ConcreteSubtype(THREAD, assumption); } else if (assumption->klass() == Assumptions_LeafType::klass()) { assumption_LeafType(THREAD, assumption); } else if (assumption->klass() == Assumptions_ConcreteMethod::klass()) { assumption_ConcreteMethod(THREAD, assumption); } else if (assumption->klass() == Assumptions_CallSiteTargetValue::klass()) { assumption_CallSiteTargetValue(THREAD, assumption); } else { JVMCI_ERROR("unexpected Assumption subclass %s", assumption->klass()->signature_name()); } } } } if (JvmtiExport::can_hotswap_or_post_breakpoint()) { objArrayHandle methods(THREAD, HotSpotCompiledCode::methods(compiled_code)); if (!methods.is_null()) { int length = methods->length(); for (int i = 0; i < length; ++i) { Handle method_handle(THREAD, methods->obj_at(i)); methodHandle method = getMethodFromHotSpotMethod(method_handle()); _dependencies->assert_evol_method(method()); } } } } RelocBuffer::~RelocBuffer() { if (_buffer != NULL) { FREE_C_HEAP_ARRAY(char, _buffer); } } address RelocBuffer::begin() const { if (_buffer != NULL) { return (address) _buffer; } return (address) _static_buffer; } void RelocBuffer::set_size(size_t bytes) { assert(bytes <= _size, "can't grow in size!"); _size = bytes; } void RelocBuffer::ensure_size(size_t bytes) { assert(_buffer == NULL, "can only be used once"); assert(_size == 0, "can only be used once"); if (bytes >= RelocBuffer::stack_size) { _buffer = NEW_C_HEAP_ARRAY(char, bytes, mtInternal); } _size = bytes; } JVMCIEnv::CodeInstallResult CodeInstaller::gather_metadata(Handle target, Handle compiled_code, CodeMetadata& metadata, TRAPS) { CodeBuffer buffer("JVMCI Compiler CodeBuffer for Metadata"); jobject compiled_code_obj = JNIHandles::make_local(compiled_code()); AOTOopRecorder* recorder = new AOTOopRecorder(&_arena, true); initialize_dependencies(JNIHandles::resolve(compiled_code_obj), recorder, CHECK_OK); metadata.set_oop_recorder(recorder); // Get instructions and constants CodeSections early because we need it. _instructions = buffer.insts(); _constants = buffer.consts(); #if INCLUDE_AOT buffer.set_immutable_PIC(_immutable_pic_compilation); #endif initialize_fields(target(), JNIHandles::resolve(compiled_code_obj), CHECK_OK); JVMCIEnv::CodeInstallResult result = initialize_buffer(buffer, false, CHECK_OK); if (result != JVMCIEnv::ok) { return result; } _debug_recorder->pcs_size(); // create the sentinel record assert(_debug_recorder->pcs_length() >= 2, "must be at least 2"); metadata.set_pc_desc(_debug_recorder->pcs(), _debug_recorder->pcs_length()); metadata.set_scopes(_debug_recorder->stream()->buffer(), _debug_recorder->data_size()); metadata.set_exception_table(&_exception_handler_table); RelocBuffer* reloc_buffer = metadata.get_reloc_buffer(); reloc_buffer->ensure_size(buffer.total_relocation_size()); size_t size = (size_t) buffer.copy_relocations_to(reloc_buffer->begin(), (CodeBuffer::csize_t) reloc_buffer->size(), true); reloc_buffer->set_size(size); return JVMCIEnv::ok; } // constructor used to create a method JVMCIEnv::CodeInstallResult CodeInstaller::install(JVMCICompiler* compiler, Handle target, Handle compiled_code, CodeBlob*& cb, Handle installed_code, Handle speculation_log, TRAPS) { CodeBuffer buffer("JVMCI Compiler CodeBuffer"); jobject compiled_code_obj = JNIHandles::make_local(compiled_code()); OopRecorder* recorder = new OopRecorder(&_arena, true); initialize_dependencies(JNIHandles::resolve(compiled_code_obj), recorder, CHECK_OK); // Get instructions and constants CodeSections early because we need it. _instructions = buffer.insts(); _constants = buffer.consts(); #if INCLUDE_AOT buffer.set_immutable_PIC(_immutable_pic_compilation); #endif initialize_fields(target(), JNIHandles::resolve(compiled_code_obj), CHECK_OK); JVMCIEnv::CodeInstallResult result = initialize_buffer(buffer, true, CHECK_OK); if (result != JVMCIEnv::ok) { return result; } int stack_slots = _total_frame_size / HeapWordSize; // conversion to words if (!compiled_code->is_a(HotSpotCompiledNmethod::klass())) { oop stubName = HotSpotCompiledCode::name(compiled_code_obj); if (stubName == NULL) { JVMCI_ERROR_OK("stub should have a name"); } char* name = strdup(java_lang_String::as_utf8_string(stubName)); cb = RuntimeStub::new_runtime_stub(name, &buffer, CodeOffsets::frame_never_safe, stack_slots, _debug_recorder->_oopmaps, false); result = JVMCIEnv::ok; } else { nmethod* nm = NULL; methodHandle method = getMethodFromHotSpotMethod(HotSpotCompiledNmethod::method(compiled_code)); jint entry_bci = HotSpotCompiledNmethod::entryBCI(compiled_code); jint id = HotSpotCompiledNmethod::id(compiled_code); bool has_unsafe_access = HotSpotCompiledNmethod::hasUnsafeAccess(compiled_code) == JNI_TRUE; JVMCIEnv* env = (JVMCIEnv*) (address) HotSpotCompiledNmethod::jvmciEnv(compiled_code); if (id == -1) { // Make sure a valid compile_id is associated with every compile id = CompileBroker::assign_compile_id_unlocked(Thread::current(), method, entry_bci); } result = JVMCIEnv::register_method(method, nm, entry_bci, &_offsets, _orig_pc_offset, &buffer, stack_slots, _debug_recorder->_oopmaps, &_exception_handler_table, compiler, _debug_recorder, _dependencies, env, id, has_unsafe_access, _has_wide_vector, installed_code, compiled_code, speculation_log); cb = nm->as_codeblob_or_null(); if (nm != NULL && env == NULL) { DirectiveSet* directive = DirectivesStack::getMatchingDirective(method, compiler); bool printnmethods = directive->PrintAssemblyOption || directive->PrintNMethodsOption; if (!printnmethods && (PrintDebugInfo || PrintRelocations || PrintDependencies || PrintExceptionHandlers)) { nm->print_nmethod(printnmethods); } DirectivesStack::release(directive); } } if (cb != NULL) { // Make sure the pre-calculated constants section size was correct. guarantee((cb->code_begin() - cb->content_begin()) >= _constants_size, "%d < %d", (int)(cb->code_begin() - cb->content_begin()), _constants_size); } return result; } void CodeInstaller::initialize_fields(oop target, oop compiled_code, TRAPS) { if (compiled_code->is_a(HotSpotCompiledNmethod::klass())) { Handle hotspotJavaMethod(THREAD, HotSpotCompiledNmethod::method(compiled_code)); methodHandle method = getMethodFromHotSpotMethod(hotspotJavaMethod()); _parameter_count = method->size_of_parameters(); TRACE_jvmci_2("installing code for %s", method->name_and_sig_as_C_string()); } else { // Must be a HotSpotCompiledRuntimeStub. // Only used in OopMap constructor for non-product builds _parameter_count = 0; } _sites_handle = JNIHandles::make_local(HotSpotCompiledCode::sites(compiled_code)); _code_handle = JNIHandles::make_local(HotSpotCompiledCode::targetCode(compiled_code)); _code_size = HotSpotCompiledCode::targetCodeSize(compiled_code); _total_frame_size = HotSpotCompiledCode::totalFrameSize(compiled_code); oop deoptRescueSlot = HotSpotCompiledCode::deoptRescueSlot(compiled_code); if (deoptRescueSlot == NULL) { _orig_pc_offset = -1; } else { _orig_pc_offset = StackSlot::offset(deoptRescueSlot); if (StackSlot::addFrameSize(deoptRescueSlot)) { _orig_pc_offset += _total_frame_size; } if (_orig_pc_offset < 0) { JVMCI_ERROR("invalid deopt rescue slot: %d", _orig_pc_offset); } } // Pre-calculate the constants section size. This is required for PC-relative addressing. _data_section_handle = JNIHandles::make_local(HotSpotCompiledCode::dataSection(compiled_code)); if ((_constants->alignment() % HotSpotCompiledCode::dataSectionAlignment(compiled_code)) != 0) { JVMCI_ERROR("invalid data section alignment: %d", HotSpotCompiledCode::dataSectionAlignment(compiled_code)); } _constants_size = data_section()->length(); _data_section_patches_handle = JNIHandles::make_local(HotSpotCompiledCode::dataSectionPatches(compiled_code)); #ifndef PRODUCT _comments_handle = JNIHandles::make_local(HotSpotCompiledCode::comments(compiled_code)); #endif _next_call_type = INVOKE_INVALID; _has_wide_vector = false; oop arch = TargetDescription::arch(target); _word_kind_handle = JNIHandles::make_local(Architecture::wordKind(arch)); } int CodeInstaller::estimate_stubs_size(TRAPS) { // Estimate the number of static and aot call stubs that might be emitted. int static_call_stubs = 0; int aot_call_stubs = 0; int trampoline_stubs = 0; objArrayOop sites = this->sites(); for (int i = 0; i < sites->length(); i++) { oop site = sites->obj_at(i); if (site != NULL) { if (site->is_a(site_Mark::klass())) { oop id_obj = site_Mark::id(site); if (id_obj != NULL) { if (!java_lang_boxing_object::is_instance(id_obj, T_INT)) { JVMCI_ERROR_0("expected Integer id, got %s", id_obj->klass()->signature_name()); } jint id = id_obj->int_field(java_lang_boxing_object::value_offset_in_bytes(T_INT)); switch (id) { case INVOKEINTERFACE: case INVOKEVIRTUAL: trampoline_stubs++; break; case INVOKESTATIC: case INVOKESPECIAL: static_call_stubs++; trampoline_stubs++; break; default: break; } } } if (UseAOT && site->is_a(site_Call::klass())) { oop target = site_Call::target(site); InstanceKlass* target_klass = InstanceKlass::cast(target->klass()); if (!target_klass->is_subclass_of(SystemDictionary::HotSpotForeignCallTarget_klass())) { // Add far aot trampolines. aot_call_stubs++; } } } } int size = static_call_stubs * CompiledStaticCall::to_interp_stub_size(); size += trampoline_stubs * CompiledStaticCall::to_trampoline_stub_size(); #if INCLUDE_AOT size += aot_call_stubs * CompiledStaticCall::to_aot_stub_size(); #endif return size; } // perform data and call relocation on the CodeBuffer JVMCIEnv::CodeInstallResult CodeInstaller::initialize_buffer(CodeBuffer& buffer, bool check_size, TRAPS) { HandleMark hm; objArrayHandle sites(THREAD, this->sites()); int locs_buffer_size = sites->length() * (relocInfo::length_limit + sizeof(relocInfo)); // Allocate enough space in the stub section for the static call // stubs. Stubs have extra relocs but they are managed by the stub // section itself so they don't need to be accounted for in the // locs_buffer above. int stubs_size = estimate_stubs_size(CHECK_OK); int total_size = align_up(_code_size, buffer.insts()->alignment()) + align_up(_constants_size, buffer.consts()->alignment()) + align_up(stubs_size, buffer.stubs()->alignment()); if (check_size && total_size > JVMCINMethodSizeLimit) { return JVMCIEnv::code_too_large; } buffer.initialize(total_size, locs_buffer_size); if (buffer.blob() == NULL) { return JVMCIEnv::cache_full; } buffer.initialize_stubs_size(stubs_size); buffer.initialize_consts_size(_constants_size); _debug_recorder = new DebugInformationRecorder(_oop_recorder); _debug_recorder->set_oopmaps(new OopMapSet()); buffer.initialize_oop_recorder(_oop_recorder); // copy the constant data into the newly created CodeBuffer address end_data = _constants->start() + _constants_size; memcpy(_constants->start(), data_section()->base(T_BYTE), _constants_size); _constants->set_end(end_data); // copy the code into the newly created CodeBuffer address end_pc = _instructions->start() + _code_size; guarantee(_instructions->allocates2(end_pc), "initialize should have reserved enough space for all the code"); memcpy(_instructions->start(), code()->base(T_BYTE), _code_size); _instructions->set_end(end_pc); for (int i = 0; i < data_section_patches()->length(); i++) { HandleMark hm(THREAD); Handle patch(THREAD, data_section_patches()->obj_at(i)); if (patch.is_null()) { THROW_(vmSymbols::java_lang_NullPointerException(), JVMCIEnv::ok); } Handle reference(THREAD, site_DataPatch::reference(patch)); if (reference.is_null()) { THROW_(vmSymbols::java_lang_NullPointerException(), JVMCIEnv::ok); } if (!reference->is_a(site_ConstantReference::klass())) { JVMCI_ERROR_OK("invalid patch in data section: %s", reference->klass()->signature_name()); } Handle constant(THREAD, site_ConstantReference::constant(reference)); if (constant.is_null()) { THROW_(vmSymbols::java_lang_NullPointerException(), JVMCIEnv::ok); } address dest = _constants->start() + site_Site::pcOffset(patch); if (constant->is_a(HotSpotMetaspaceConstantImpl::klass())) { if (HotSpotMetaspaceConstantImpl::compressed(constant)) { #ifdef _LP64 *((narrowKlass*) dest) = record_narrow_metadata_reference(_constants, dest, constant, CHECK_OK); #else JVMCI_ERROR_OK("unexpected compressed Klass* in 32-bit mode"); #endif } else { *((void**) dest) = record_metadata_reference(_constants, dest, constant, CHECK_OK); } } else if (constant->is_a(HotSpotObjectConstantImpl::klass())) { Handle obj(THREAD, HotSpotObjectConstantImpl::object(constant)); jobject value = JNIHandles::make_local(obj()); int oop_index = _oop_recorder->find_index(value); if (HotSpotObjectConstantImpl::compressed(constant)) { #ifdef _LP64 _constants->relocate(dest, oop_Relocation::spec(oop_index), relocInfo::narrow_oop_in_const); #else JVMCI_ERROR_OK("unexpected compressed oop in 32-bit mode"); #endif } else { _constants->relocate(dest, oop_Relocation::spec(oop_index)); } } else { JVMCI_ERROR_OK("invalid constant in data section: %s", constant->klass()->signature_name()); } } jint last_pc_offset = -1; for (int i = 0; i < sites->length(); i++) { HandleMark hm(THREAD); Handle site(THREAD, sites->obj_at(i)); if (site.is_null()) { THROW_(vmSymbols::java_lang_NullPointerException(), JVMCIEnv::ok); } jint pc_offset = site_Site::pcOffset(site); if (site->is_a(site_Call::klass())) { TRACE_jvmci_4("call at %i", pc_offset); site_Call(buffer, pc_offset, site, CHECK_OK); } else if (site->is_a(site_Infopoint::klass())) { // three reasons for infopoints denote actual safepoints oop reason = site_Infopoint::reason(site); if (site_InfopointReason::SAFEPOINT() == reason || site_InfopointReason::CALL() == reason || site_InfopointReason::IMPLICIT_EXCEPTION() == reason) { TRACE_jvmci_4("safepoint at %i", pc_offset); site_Safepoint(buffer, pc_offset, site, CHECK_OK); if (_orig_pc_offset < 0) { JVMCI_ERROR_OK("method contains safepoint, but has no deopt rescue slot"); } } else { TRACE_jvmci_4("infopoint at %i", pc_offset); site_Infopoint(buffer, pc_offset, site, CHECK_OK); } } else if (site->is_a(site_DataPatch::klass())) { TRACE_jvmci_4("datapatch at %i", pc_offset); site_DataPatch(buffer, pc_offset, site, CHECK_OK); } else if (site->is_a(site_Mark::klass())) { TRACE_jvmci_4("mark at %i", pc_offset); site_Mark(buffer, pc_offset, site, CHECK_OK); } else if (site->is_a(site_ExceptionHandler::klass())) { TRACE_jvmci_4("exceptionhandler at %i", pc_offset); site_ExceptionHandler(pc_offset, site); } else { JVMCI_ERROR_OK("unexpected site subclass: %s", site->klass()->signature_name()); } last_pc_offset = pc_offset; JavaThread* thread = JavaThread::current(); if (SafepointMechanism::poll(thread)) { // this is a hacky way to force a safepoint check but nothing else was jumping out at me. ThreadToNativeFromVM ttnfv(thread); } } #ifndef PRODUCT if (comments() != NULL) { for (int i = 0; i < comments()->length(); i++) { oop comment = comments()->obj_at(i); assert(comment->is_a(HotSpotCompiledCode_Comment::klass()), "cce"); jint offset = HotSpotCompiledCode_Comment::pcOffset(comment); char* text = java_lang_String::as_utf8_string(HotSpotCompiledCode_Comment::text(comment)); buffer.block_comment(offset, text); } } #endif return JVMCIEnv::ok; } void CodeInstaller::assumption_NoFinalizableSubclass(Thread* thread, Handle assumption) { Handle receiverType_handle (thread, Assumptions_NoFinalizableSubclass::receiverType(assumption())); Klass* receiverType = java_lang_Class::as_Klass(HotSpotResolvedObjectTypeImpl::javaClass(receiverType_handle)); _dependencies->assert_has_no_finalizable_subclasses(receiverType); } void CodeInstaller::assumption_ConcreteSubtype(Thread* thread, Handle assumption) { Handle context_handle (thread, Assumptions_ConcreteSubtype::context(assumption())); Handle subtype_handle (thread, Assumptions_ConcreteSubtype::subtype(assumption())); Klass* context = java_lang_Class::as_Klass(HotSpotResolvedObjectTypeImpl::javaClass(context_handle)); Klass* subtype = java_lang_Class::as_Klass(HotSpotResolvedObjectTypeImpl::javaClass(subtype_handle)); assert(context->is_abstract(), ""); _dependencies->assert_abstract_with_unique_concrete_subtype(context, subtype); } void CodeInstaller::assumption_LeafType(Thread* thread, Handle assumption) { Handle context_handle (thread, Assumptions_LeafType::context(assumption())); Klass* context = java_lang_Class::as_Klass(HotSpotResolvedObjectTypeImpl::javaClass(context_handle)); _dependencies->assert_leaf_type(context); } void CodeInstaller::assumption_ConcreteMethod(Thread* thread, Handle assumption) { Handle impl_handle (thread, Assumptions_ConcreteMethod::impl(assumption())); Handle context_handle (thread, Assumptions_ConcreteMethod::context(assumption())); methodHandle impl = getMethodFromHotSpotMethod(impl_handle()); Klass* context = java_lang_Class::as_Klass(HotSpotResolvedObjectTypeImpl::javaClass(context_handle)); _dependencies->assert_unique_concrete_method(context, impl()); } void CodeInstaller::assumption_CallSiteTargetValue(Thread* thread, Handle assumption) { Handle callSite(thread, Assumptions_CallSiteTargetValue::callSite(assumption())); Handle methodHandle(thread, Assumptions_CallSiteTargetValue::methodHandle(assumption())); _dependencies->assert_call_site_target_value(callSite(), methodHandle()); } void CodeInstaller::site_ExceptionHandler(jint pc_offset, Handle exc) { jint handler_offset = site_ExceptionHandler::handlerPos(exc); // Subtable header _exception_handler_table.add_entry(HandlerTableEntry(1, pc_offset, 0)); // Subtable entry _exception_handler_table.add_entry(HandlerTableEntry(-1, handler_offset, 0)); } // If deoptimization happens, the interpreter should reexecute these bytecodes. // This function mainly helps the compilers to set up the reexecute bit. static bool bytecode_should_reexecute(Bytecodes::Code code) { switch (code) { case Bytecodes::_invokedynamic: case Bytecodes::_invokevirtual: case Bytecodes::_invokeinterface: case Bytecodes::_invokespecial: case Bytecodes::_invokestatic: return false; default: return true; } return true; } GrowableArray<ScopeValue*>* CodeInstaller::record_virtual_objects(Handle debug_info, TRAPS) { objArrayHandle virtualObjects(THREAD, DebugInfo::virtualObjectMapping(debug_info)); if (virtualObjects.is_null()) { return NULL; } GrowableArray<ScopeValue*>* objects = new GrowableArray<ScopeValue*>(virtualObjects->length(), virtualObjects->length(), NULL); // Create the unique ObjectValues for (int i = 0; i < virtualObjects->length(); i++) { HandleMark hm(THREAD); Handle value(THREAD, virtualObjects->obj_at(i)); int id = VirtualObject::id(value); Handle type(THREAD, VirtualObject::type(value)); oop javaMirror = HotSpotResolvedObjectTypeImpl::javaClass(type); ObjectValue* sv = new ObjectValue(id, new ConstantOopWriteValue(JNIHandles::make_local(Thread::current(), javaMirror))); if (id < 0 || id >= objects->length()) { JVMCI_ERROR_NULL("virtual object id %d out of bounds", id); } if (objects->at(id) != NULL) { JVMCI_ERROR_NULL("duplicate virtual object id %d", id); } objects->at_put(id, sv); } // All the values which could be referenced by the VirtualObjects // exist, so now describe all the VirtualObjects themselves. for (int i = 0; i < virtualObjects->length(); i++) { HandleMark hm(THREAD); Handle value(THREAD, virtualObjects->obj_at(i)); int id = VirtualObject::id(value); record_object_value(objects->at(id)->as_ObjectValue(), value, objects, CHECK_NULL); } _debug_recorder->dump_object_pool(objects); return objects; } void CodeInstaller::record_scope(jint pc_offset, Handle debug_info, ScopeMode scope_mode, bool return_oop, TRAPS) { Handle position(THREAD, DebugInfo::bytecodePosition(debug_info)); if (position.is_null()) { // Stubs do not record scope info, just oop maps return; } GrowableArray<ScopeValue*>* objectMapping; if (scope_mode == CodeInstaller::FullFrame) { objectMapping = record_virtual_objects(debug_info, CHECK); } else { objectMapping = NULL; } record_scope(pc_offset, position, scope_mode, objectMapping, return_oop, CHECK); } void CodeInstaller::record_scope(jint pc_offset, Handle position, ScopeMode scope_mode, GrowableArray<ScopeValue*>* objects, bool return_oop, TRAPS) { Handle frame; if (scope_mode == CodeInstaller::FullFrame) { if (!position->is_a(BytecodeFrame::klass())) { JVMCI_ERROR("Full frame expected for debug info at %i", pc_offset); } frame = position; } Handle caller_frame (THREAD, BytecodePosition::caller(position)); if (caller_frame.not_null()) { record_scope(pc_offset, caller_frame, scope_mode, objects, return_oop, CHECK); } Handle hotspot_method (THREAD, BytecodePosition::method(position)); Method* method = getMethodFromHotSpotMethod(hotspot_method()); jint bci = BytecodePosition::bci(position); if (bci == BytecodeFrame::BEFORE_BCI()) { bci = SynchronizationEntryBCI; } TRACE_jvmci_2("Recording scope pc_offset=%d bci=%d method=%s", pc_offset, bci, method->name_and_sig_as_C_string()); bool reexecute = false; if (frame.not_null()) { if (bci == SynchronizationEntryBCI){ reexecute = false; } else { Bytecodes::Code code = Bytecodes::java_code_at(method, method->bcp_from(bci)); reexecute = bytecode_should_reexecute(code); if (frame.not_null()) { reexecute = (BytecodeFrame::duringCall(frame) == JNI_FALSE); } } } DebugToken* locals_token = NULL; DebugToken* expressions_token = NULL; DebugToken* monitors_token = NULL; bool throw_exception = false; if (frame.not_null()) { jint local_count = BytecodeFrame::numLocals(frame); jint expression_count = BytecodeFrame::numStack(frame); jint monitor_count = BytecodeFrame::numLocks(frame); objArrayHandle values(THREAD, BytecodeFrame::values(frame)); objArrayHandle slotKinds(THREAD, BytecodeFrame::slotKinds(frame)); if (values.is_null() || slotKinds.is_null()) { THROW(vmSymbols::java_lang_NullPointerException()); } if (local_count + expression_count + monitor_count != values->length()) { JVMCI_ERROR("unexpected values length %d in scope (%d locals, %d expressions, %d monitors)", values->length(), local_count, expression_count, monitor_count); } if (local_count + expression_count != slotKinds->length()) { JVMCI_ERROR("unexpected slotKinds length %d in scope (%d locals, %d expressions)", slotKinds->length(), local_count, expression_count); } GrowableArray<ScopeValue*>* locals = local_count > 0 ? new GrowableArray<ScopeValue*> (local_count) : NULL; GrowableArray<ScopeValue*>* expressions = expression_count > 0 ? new GrowableArray<ScopeValue*> (expression_count) : NULL; GrowableArray<MonitorValue*>* monitors = monitor_count > 0 ? new GrowableArray<MonitorValue*> (monitor_count) : NULL; TRACE_jvmci_2("Scope at bci %d with %d values", bci, values->length()); TRACE_jvmci_2("%d locals %d expressions, %d monitors", local_count, expression_count, monitor_count); for (jint i = 0; i < values->length(); i++) { HandleMark hm(THREAD); ScopeValue* second = NULL; Handle value(THREAD, values->obj_at(i)); if (i < local_count) { BasicType type = JVMCIRuntime::kindToBasicType(Handle(THREAD, slotKinds->obj_at(i)), CHECK); ScopeValue* first = get_scope_value(value, type, objects, second, CHECK); if (second != NULL) { locals->append(second); } locals->append(first); } else if (i < local_count + expression_count) { BasicType type = JVMCIRuntime::kindToBasicType(Handle(THREAD, slotKinds->obj_at(i)), CHECK); ScopeValue* first = get_scope_value(value, type, objects, second, CHECK); if (second != NULL) { expressions->append(second); } expressions->append(first); } else { MonitorValue *monitor = get_monitor_value(value, objects, CHECK); monitors->append(monitor); } if (second != NULL) { i++; if (i >= values->length() || values->obj_at(i) != Value::ILLEGAL()) { JVMCI_ERROR("double-slot value not followed by Value.ILLEGAL"); } } } locals_token = _debug_recorder->create_scope_values(locals); expressions_token = _debug_recorder->create_scope_values(expressions); monitors_token = _debug_recorder->create_monitor_values(monitors); throw_exception = BytecodeFrame::rethrowException(frame) == JNI_TRUE; } _debug_recorder->describe_scope(pc_offset, method, NULL, bci, reexecute, throw_exception, false, return_oop, locals_token, expressions_token, monitors_token); } void CodeInstaller::site_Safepoint(CodeBuffer& buffer, jint pc_offset, Handle site, TRAPS) { Handle debug_info (THREAD, site_Infopoint::debugInfo(site)); if (debug_info.is_null()) { JVMCI_ERROR("debug info expected at safepoint at %i", pc_offset); } // address instruction = _instructions->start() + pc_offset; // jint next_pc_offset = Assembler::locate_next_instruction(instruction) - _instructions->start(); OopMap *map = create_oop_map(debug_info, CHECK); _debug_recorder->add_safepoint(pc_offset, map); record_scope(pc_offset, debug_info, CodeInstaller::FullFrame, CHECK); _debug_recorder->end_safepoint(pc_offset); } void CodeInstaller::site_Infopoint(CodeBuffer& buffer, jint pc_offset, Handle site, TRAPS) { Handle debug_info (THREAD, site_Infopoint::debugInfo(site)); if (debug_info.is_null()) { JVMCI_ERROR("debug info expected at infopoint at %i", pc_offset); } // We'd like to check that pc_offset is greater than the // last pc recorded with _debug_recorder (raising an exception if not) // but DebugInformationRecorder doesn't have sufficient public API. _debug_recorder->add_non_safepoint(pc_offset); record_scope(pc_offset, debug_info, CodeInstaller::BytecodePosition, CHECK); _debug_recorder->end_non_safepoint(pc_offset); } void CodeInstaller::site_Call(CodeBuffer& buffer, jint pc_offset, Handle site, TRAPS) { Handle target(THREAD, site_Call::target(site)); InstanceKlass* target_klass = InstanceKlass::cast(target->klass()); Handle hotspot_method; // JavaMethod Handle foreign_call; if (target_klass->is_subclass_of(SystemDictionary::HotSpotForeignCallTarget_klass())) { foreign_call = target; } else { hotspot_method = target; } Handle debug_info (THREAD, site_Call::debugInfo(site)); assert(hotspot_method.not_null() ^ foreign_call.not_null(), "Call site needs exactly one type"); NativeInstruction* inst = nativeInstruction_at(_instructions->start() + pc_offset); jint next_pc_offset = CodeInstaller::pd_next_offset(inst, pc_offset, hotspot_method, CHECK); if (debug_info.not_null()) { OopMap *map = create_oop_map(debug_info, CHECK); _debug_recorder->add_safepoint(next_pc_offset, map); bool return_oop = hotspot_method.not_null() && getMethodFromHotSpotMethod(hotspot_method())->is_returning_oop(); record_scope(next_pc_offset, debug_info, CodeInstaller::FullFrame, return_oop, CHECK); } if (foreign_call.not_null()) { jlong foreign_call_destination = HotSpotForeignCallTarget::address(foreign_call); if (_immutable_pic_compilation) { // Use fake short distance during PIC compilation. foreign_call_destination = (jlong)(_instructions->start() + pc_offset); } CodeInstaller::pd_relocate_ForeignCall(inst, foreign_call_destination, CHECK); } else { // method != NULL if (debug_info.is_null()) { JVMCI_ERROR("debug info expected at call at %i", pc_offset); } TRACE_jvmci_3("method call"); CodeInstaller::pd_relocate_JavaMethod(buffer, hotspot_method, pc_offset, CHECK); if (_next_call_type == INVOKESTATIC || _next_call_type == INVOKESPECIAL) { // Need a static call stub for transitions from compiled to interpreted. CompiledStaticCall::emit_to_interp_stub(buffer, _instructions->start() + pc_offset); } #if INCLUDE_AOT // Trampoline to far aot code. CompiledStaticCall::emit_to_aot_stub(buffer, _instructions->start() + pc_offset); #endif } _next_call_type = INVOKE_INVALID; if (debug_info.not_null()) { _debug_recorder->end_safepoint(next_pc_offset); } } void CodeInstaller::site_DataPatch(CodeBuffer& buffer, jint pc_offset, Handle site, TRAPS) { Handle reference(THREAD, site_DataPatch::reference(site)); if (reference.is_null()) { THROW(vmSymbols::java_lang_NullPointerException()); } else if (reference->is_a(site_ConstantReference::klass())) { Handle constant(THREAD, site_ConstantReference::constant(reference)); if (constant.is_null()) { THROW(vmSymbols::java_lang_NullPointerException()); } else if (constant->is_a(HotSpotObjectConstantImpl::klass())) { if (!_immutable_pic_compilation) { // Do not patch during PIC compilation. pd_patch_OopConstant(pc_offset, constant, CHECK); } } else if (constant->is_a(HotSpotMetaspaceConstantImpl::klass())) { if (!_immutable_pic_compilation) { pd_patch_MetaspaceConstant(pc_offset, constant, CHECK); } } else if (constant->is_a(HotSpotSentinelConstant::klass())) { if (!_immutable_pic_compilation) { JVMCI_ERROR("sentinel constant not supported for normal compiles: %s", constant->klass()->signature_name()); } } else { JVMCI_ERROR("unknown constant type in data patch: %s", constant->klass()->signature_name()); } } else if (reference->is_a(site_DataSectionReference::klass())) { int data_offset = site_DataSectionReference::offset(reference); if (0 <= data_offset && data_offset < _constants_size) { pd_patch_DataSectionReference(pc_offset, data_offset, CHECK); } else { JVMCI_ERROR("data offset 0x%X points outside data section (size 0x%X)", data_offset, _constants_size); } } else { JVMCI_ERROR("unknown data patch type: %s", reference->klass()->signature_name()); } } void CodeInstaller::site_Mark(CodeBuffer& buffer, jint pc_offset, Handle site, TRAPS) { Handle id_obj (THREAD, site_Mark::id(site)); if (id_obj.not_null()) { if (!java_lang_boxing_object::is_instance(id_obj(), T_INT)) { JVMCI_ERROR("expected Integer id, got %s", id_obj->klass()->signature_name()); } jint id = id_obj->int_field(java_lang_boxing_object::value_offset_in_bytes(T_INT)); address pc = _instructions->start() + pc_offset; switch (id) { case UNVERIFIED_ENTRY: _offsets.set_value(CodeOffsets::Entry, pc_offset); break; case VERIFIED_ENTRY: _offsets.set_value(CodeOffsets::Verified_Entry, pc_offset); break; case OSR_ENTRY: _offsets.set_value(CodeOffsets::OSR_Entry, pc_offset); break; case EXCEPTION_HANDLER_ENTRY: _offsets.set_value(CodeOffsets::Exceptions, pc_offset); break; case DEOPT_HANDLER_ENTRY: _offsets.set_value(CodeOffsets::Deopt, pc_offset); break; case INVOKEVIRTUAL: case INVOKEINTERFACE: case INLINE_INVOKE: case INVOKESTATIC: case INVOKESPECIAL: _next_call_type = (MarkId) id; _invoke_mark_pc = pc; break; case POLL_NEAR: case POLL_FAR: case POLL_RETURN_NEAR: case POLL_RETURN_FAR: pd_relocate_poll(pc, id, CHECK); break; case CARD_TABLE_SHIFT: case CARD_TABLE_ADDRESS: case HEAP_TOP_ADDRESS: case HEAP_END_ADDRESS: case NARROW_KLASS_BASE_ADDRESS: case NARROW_OOP_BASE_ADDRESS: case CRC_TABLE_ADDRESS: case LOG_OF_HEAP_REGION_GRAIN_BYTES: case INLINE_CONTIGUOUS_ALLOCATION_SUPPORTED: break; default: JVMCI_ERROR("invalid mark id: %d", id); break; } } }
41.754858
183
0.70484
[ "object" ]
ee56be18cd11c4a6e2a3e4b4b39d85bda06f481a
1,179
cpp
C++
REDSI_1160929_1161573/boost_1_67_0/libs/geometry/doc/src/examples/algorithms/is_empty.cpp
Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo
eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8
[ "MIT" ]
32
2019-02-27T06:57:07.000Z
2021-08-29T10:56:19.000Z
REDSI_1160929_1161573/boost_1_67_0/libs/geometry/doc/src/examples/algorithms/is_empty.cpp
Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo
eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8
[ "MIT" ]
1
2019-04-04T18:00:00.000Z
2019-04-04T18:00:00.000Z
REDSI_1160929_1161573/boost_1_67_0/libs/geometry/doc/src/examples/algorithms/is_empty.cpp
Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo
eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8
[ "MIT" ]
5
2019-08-20T13:45:04.000Z
2022-03-01T18:23:49.000Z
// Boost.Geometry (aka GGL, Generic Geometry Library) // QuickBook Example // Copyright (c) 2015, Oracle and/or its affiliates // Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle // Licensed under the Boost Software License version 1.0. // http://www.boost.org/users/license.html //[is_empty //` Check if a geometry is the empty set #include <iostream> #include <boost/geometry.hpp> #include <boost/geometry/geometries/point_xy.hpp> int main() { boost::geometry::model::multi_linestring < boost::geometry::model::linestring < boost::geometry::model::d2::point_xy<double> > > mls; boost::geometry::read_wkt("MULTILINESTRING((0 0,0 10,10 0),(1 1,8 1,1 8))", mls); std::cout << "Is empty? " << (boost::geometry::is_empty(mls) ? "yes" : "no") << std::endl; boost::geometry::clear(mls); std::cout << "Is empty (after clearing)? " << (boost::geometry::is_empty(mls) ? "yes" : "no") << std::endl; return 0; } //] //[is_empty_output /*` Output: [pre Is empty? no Is empty (after clearing)? yes ] */ //]
24.5625
112
0.59542
[ "geometry", "model" ]
ee59637a012ceeae7d925014eec8b7a68e656f89
3,142
cpp
C++
src/ms/spec/baseline_util.cpp
toppic-suite/toppic-suite
b5f0851f437dde053ddc646f45f9f592c16503ec
[ "Apache-2.0" ]
8
2018-05-23T14:37:31.000Z
2022-02-04T23:48:38.000Z
src/ms/spec/baseline_util.cpp
toppic-suite/toppic-suite
b5f0851f437dde053ddc646f45f9f592c16503ec
[ "Apache-2.0" ]
9
2019-08-31T08:17:45.000Z
2022-02-11T20:58:06.000Z
src/ms/spec/baseline_util.cpp
toppic-suite/toppic-suite
b5f0851f437dde053ddc646f45f9f592c16503ec
[ "Apache-2.0" ]
4
2018-04-25T01:39:38.000Z
2020-05-20T19:25:07.000Z
//Copyright (c) 2014 - 2020, The Trustees of Indiana University. // //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 <memory> #include <cmath> #include "common/util/logger.hpp" #include "ms/spec/baseline_util.hpp" namespace toppic { namespace baseline_util { class IntvDens { public: IntvDens(double bgn, double end, int num, double perc): bgn_(bgn), end_(end), num_(num), perc_(perc) { } double getBgn() {return bgn_;} double getEnd() {return end_;} double getMiddle() {return (bgn_ + end_) / 2;} int getNum() {return num_;} double getPerc() {return perc_;} private: double bgn_, end_; int num_; double perc_; }; typedef std::shared_ptr<IntvDens> IntvDensPtr; typedef std::vector<IntvDensPtr> IntvDensPtrVec; IntvDensPtrVec getDensity(const std::vector<double> &inte, double max_inte) { double intv_width = 10; if (max_inte > 10000) { intv_width = max_inte / 1000; } else if (max_inte < 100) { intv_width = max_inte / 100; } int total_num = static_cast<int>(inte.size()); int intv_num = static_cast<int>(std::round(max_inte / intv_width)) + 1; IntvDensPtrVec dens(intv_num); for (int i = 0; i < intv_num; i++) { double bgn = i * intv_width; double end = (i + 1) * intv_width; int num = 0; for (int j = 0; j < total_num; j++) { if (inte[j] > bgn && inte[j] <= end) { num++; } } IntvDensPtr cur_den = std::make_shared<IntvDens>(bgn, end, num, num / total_num); dens[i] = cur_den; } return dens; } void outputDens(const IntvDensPtrVec &dens) { for (size_t i = 0; i < dens.size(); i++) { std::cout << dens[i]->getBgn() << " " << dens[i]->getEnd() << " " << dens[i]->getNum() << " " << dens[i]->getPerc() << std::endl; } } int getMaxPos(const IntvDensPtrVec &dens) { int max_pos = -1; int max_num = -1; for (size_t i = 0; i < dens.size(); i++) { if (dens[i]->getNum() > max_num) { max_num = dens[i]->getNum(); max_pos = i; } } return max_pos; } double getMaxInte(const std::vector<double> &inte) { double max_inte = -1; for (size_t i = 0; i < inte.size(); i++) { if (inte[i] > max_inte) { max_inte = inte[i]; } } return max_inte; } double getBaseLine(const std::vector<double> &inte) { double max_inte = getMaxInte(inte); int max_pos; IntvDensPtrVec dens; do { dens = getDensity(inte, max_inte); max_pos = getMaxPos(dens); if (max_pos == 0) { max_inte = dens[max_pos]->getEnd(); } } while (max_pos == 0); return dens[max_pos]->getBgn(); } } // namespace deconv_util } // namespace toppic
25.544715
85
0.6324
[ "vector" ]
ee5a0141fc64e96f9f9fc56809686837538c69fe
7,167
cpp
C++
src-2007/game/client/facesdk/face_api.cpp
KyleGospo/City-17-Episode-One-Source
2bc0bb56a2e0a63d963755e2831c15f2970c38e7
[ "Unlicense" ]
30
2016-04-23T04:55:52.000Z
2021-05-19T10:26:27.000Z
src/game/client/facesdk/face_api.cpp
KyleGospo/City-17-Episode-One-Source-2013
0cc2bb3c19dd411f0eb3e86665cec2eec8952d5e
[ "Unlicense" ]
2
2017-01-10T11:45:03.000Z
2018-05-23T16:42:56.000Z
src-2007/game/client/facesdk/face_api.cpp
KyleGospo/City-17-Episode-One-Source
2bc0bb56a2e0a63d963755e2831c15f2970c38e7
[ "Unlicense" ]
15
2016-04-26T13:16:38.000Z
2022-03-08T06:13:14.000Z
#include "cbase.h" #include "face_api.h" using namespace std; FaceAPI::FaceAPI() { m_bFaceAPIHasCamera = true; m_bFaceAPIInitialized = false; } void FaceAPI::init() //smCoord3f *head_pos, smCoord3f *head_rot) { //this.head_pos = head_pos; //this.head_rot = head_rot; /*try { // Initialize the API THROW_ON_ERROR(smAPIInit()); //run(); } catch (std::exception &e) { cerr << e.what() << endl; }*/ //Don't use check result here, we have something special for the API. result = smAPIInit(); if( result < 0 ) { Warning("FaceAPI failed to initialize! Please ensure that you have followed City 17's installation instructions correctly!\n"); m_bFaceAPIHasCamera = false; m_bFaceAPIInitialized = false; } else { m_bFaceAPIInitialized = true; } } /* // Handles head-tracker head-pose callbacks void STDCALL receiveHeadPose(void *, smHTHeadPose head_pose) { // Make output readable fixed(cout); showpos(cout); cout.precision(2); //cout << "Head Pose: "; //cout << "pos("; //cout << head_pose.head_pos.x << ","; //cout << head_pose.head_pos.y << ","; //cout << head_pose.head_pos.z << ") "; //cout << "rot("; //cout << rad2deg(head_pose.head_rot.x_rads) << ","; //cout << rad2deg(head_pose.head_rot.y_rads) << ","; //cout << rad2deg(head_pose.head_rot.z_rads) << ") "; //cout << "conf " << head_pose.confidence; //cout << endl; //*head_pos = head_pose.head_pos; //*head_rot = head_pose.head_rot; } */ // Create the first available camera detected on the system void FaceAPI::createFirstCamera() { /* // Register the WDM category of cameras THROW_ON_ERROR(smCameraRegisterCategory(SM_API_CAMERA_CATEGORY_WDM)); // Detect cameras smCameraInfoList info_list; THROW_ON_ERROR(smCameraCreateInfoList(&info_list)); if (info_list.num_cameras == 0) { throw std::runtime_error("No cameras were detected"); } else { cout << "The followings cameras were detected: " << endl; for (int i=0; i<info_list.num_cameras; ++i) { char buf[1024]; THROW_ON_ERROR(smStringWriteBuffer(info_list.info[i].category,buf,1024)); cout << " " << i << ". Category: " << std::string(buf); THROW_ON_ERROR(smStringWriteBuffer(info_list.info[i].model,buf,1024)); cout << " Model: " << std::string(buf); cout << " Instance: " << info_list.info[i].instance_index << endl; } } // Create the first camera detected on the system //smCamera camera; THROW_ON_ERROR(smCameraCreate(info_list.info[0], 0, &camera)); // Destroy the info list smCameraDestroyInfoList(&info_list); //return camera; */ // Register the WDM category of cameras result = smCameraRegisterType(SM_API_CAMERA_TYPE_WDM); CheckResult( "Register Camera Type" ); // Detect cameras smCameraInfoList info_list; result = smCameraCreateInfoList(&info_list); CheckResult( "Camera Create Info List" ); if (info_list.num_cameras == 0) { //throw std::runtime_error("No cameras were detected"); Msg( "No free cameras detected for FaceAPI!\n" ); } else { //cout << "The followings cameras were detected: " << endl; Msg( "The following cameras were detected:\n" ); for (int i=0; i<info_list.num_cameras; ++i) { char buf[1024]; //cout << " " << i << ". Type: " << info_list.info[i].type; result = smStringWriteBuffer(info_list.info[i].model,buf,1024); CheckResult( "String Write Buffer" ); //cout << " Model: " << std::string(buf); //cout << " Instance: " << info_list.info[i].instance_index << endl; Msg( "Model: %s\n", buf ); Msg( "Instance: %i\n", info_list.info[i].instance_index ); // Print all the possible formats for the camera for (int j=0; j<info_list.info[i].num_formats; j++) { smCameraVideoFormat video_format = info_list.info[i].formats[j]; //cout << " - Format: "; //cout << " res (" << video_format.res.w << "," << video_format.res.h << ")"; //cout << " image code " << video_format.format; //cout << " framerate " << video_format.framerate << "(hz)"; //cout << " upside-down? " << (video_format.is_upside_down ? "y":"n") << endl; Msg( " - Camera Format:\n" ); Msg( " res ( %i, %i )\n", video_format.res.w, video_format.res.h ); Msg( " framerate: %.2f", video_format.framerate ); } } } // Create the first camera detected on the system //smCameraHandle camera_handle = 0; result = smCameraCreate(&info_list.info[0], 0 /* Don't override any settings */, &camera); CheckResult( "Camera Creation" ); // Destroy the info list smCameraDestroyInfoList(&info_list); //return camera_handle; } void FaceAPI::start(headPoseCallback callback) { // Get the version int major, minor, maint; result = smAPIVersion(&major, &minor, &maint); CheckResult( "Retrieve API Version" ); //cout << endl << "API VERSION: " << major << "." << minor << "." << maint << "." << endl << endl; //smAPIInit(); // Register the WDM category of cameras result = smCameraRegisterType(SM_API_CAMERA_TYPE_WDM); CheckResult( "Camera Type Registration" ); const bool non_commercial_license = smAPINonCommercialLicense() == SM_API_TRUE; if (non_commercial_license) { //cout << "Non-Commercial License restrictions apply, see doco for details." << endl; // Create a new Head-Tracker engine that uses the camera result = smEngineCreate(SM_API_ENGINE_LATEST_HEAD_TRACKER,&engine); CheckResult( "Engine Creation" ); } else { // Print out a list of connected cameras, and choose the first camera on the system createFirstCamera(); // Create a new Head-Tracker engine that uses the camera result = smEngineCreateWithCamera(SM_API_ENGINE_LATEST_HEAD_TRACKER,camera,&engine); CheckResult( "Set Engine to Camera" ); } // Check license for particular engine version (always ok for non-commercial license) const bool engine_licensed = smEngineIsLicensed(engine) == SM_API_OK; // Hook up callbacks to receive output data from engine. // This function will return an error if the engine is not licensed. if (engine_licensed) { result = smHTRegisterHeadPoseCallback(engine,0,(smHTHeadPoseCallback)callback); CheckResult( "Register Head Pose Callback" ); } /*else { cout << "Engine is not licensed, cannot obtain any output data." << endl; }*/ // Start tracking result = smEngineStart(engine); CheckResult( "Start Engine" ); } void FaceAPI::reset() { result = smEngineStop(engine); CheckResult( "Engine Stop (Reset)" ); result = smEngineStart(engine); CheckResult( "Engine Start (Reset)" ); } void FaceAPI::end() { // Destroy engine result = smEngineDestroy(&engine); CheckResult( "Engine Shutdown" ); } void FaceAPI::CheckResult( const char* failedSystem ) { if( result < 0 ) { DevMsg("FaceAPI - Failed at step: '%s'\n", failedSystem); m_bFaceAPIHasCamera = false; } }
29.372951
129
0.638342
[ "model" ]
ee5af4f9f3edc69973acec5a76c9d62f3a1bc008
2,642
cpp
C++
system_metrics_collector/test/system_metrics_collector/test_composition.cpp
ahcorde/system_metrics_collector
9f942f08d411c702ab4fd816cc1a8bbb1700baa1
[ "Apache-2.0" ]
null
null
null
system_metrics_collector/test/system_metrics_collector/test_composition.cpp
ahcorde/system_metrics_collector
9f942f08d411c702ab4fd816cc1a8bbb1700baa1
[ "Apache-2.0" ]
null
null
null
system_metrics_collector/test/system_metrics_collector/test_composition.cpp
ahcorde/system_metrics_collector
9f942f08d411c702ab4fd816cc1a8bbb1700baa1
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // 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 <gtest/gtest.h> #include <memory> #include <string> #include <vector> #include "class_loader/class_loader.hpp" #include "rclcpp/rclcpp.hpp" #include "rclcpp_components/node_factory.hpp" #include "test_constants.hpp" namespace { constexpr const char kSystemMetricsCollectorLibName[] = "libsystem_metrics_collector.so"; constexpr const std::array<const char *, 2> kExpectedClassNames = { "system_metrics_collector::LinuxProcessCpuMeasurementNode", "system_metrics_collector::LinuxProcessMemoryMeasurementNode" }; } bool IsExpectedClassName(const std::string & class_name) { auto result = std::find_if(kExpectedClassNames.cbegin(), kExpectedClassNames.cend(), [&class_name](const char * expected_class_name) { return class_name.find(expected_class_name) != std::string::npos; }); return result != kExpectedClassNames.cend(); } TEST(TestComposeableNodes, DlopenTest) { rclcpp::init(0, nullptr); rclcpp::executors::SingleThreadedExecutor exec; rclcpp::NodeOptions options; const auto loader = std::make_unique<class_loader::ClassLoader>(kSystemMetricsCollectorLibName); const auto class_names = loader->getAvailableClasses<rclcpp_components::NodeFactory>(); ASSERT_EQ(kExpectedClassNames.size(), class_names.size()); std::vector<rclcpp_components::NodeInstanceWrapper> node_wrappers; for (const auto & class_name : class_names) { ASSERT_TRUE(IsExpectedClassName(class_name)); const auto node_factory = loader->createInstance<rclcpp_components::NodeFactory>(class_name); auto wrapper = node_factory->create_node_instance(options); exec.add_node(wrapper.get_node_base_interface()); node_wrappers.push_back(wrapper); } std::promise<bool> empty_promise; std::shared_future<bool> dummy_future = empty_promise.get_future(); exec.spin_until_future_complete(dummy_future, test_constants::kTestDuration); for (auto & wrapper : node_wrappers) { exec.remove_node(wrapper.get_node_base_interface()); } rclcpp::shutdown(); }
36.191781
98
0.766086
[ "vector" ]
ee65932dbe213ddc34150feebbd61336a7dc4551
1,096
cpp
C++
problemsets/UVA/10505.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
problemsets/UVA/10505.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
problemsets/UVA/10505.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
/** * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * */ #include <cstdio> #include <algorithm> #include <vector> #include <set> using namespace std; int N; vector<int> adj[210]; char vis[210]; int A, B; bool dfs(int u, int c) { vis[u] = c; c ? A++ : B++; bool ok = 1; for (int i = 0; i < adj[u].size(); i++) { int v = adj[u][i]; if (vis[v]== c) ok = 0; if (vis[v]==-1) ok &= dfs(v,1-c); } return ok; } int main() { int T; scanf("%d", &T); while (T--) { scanf("%d", &N); for (int i = 1; i <= N; i++) adj[i].clear(), vis[i] = -1; for (int i = 1; i <= N; i++) { int m, x; scanf("%d", &m); for (int j = 0; j < m; j++) { scanf("%d", &x); adj[i].push_back(x); adj[x].push_back(i); } } int ret = 0; for (int i = 1; i <= N; i++) if (vis[i]==-1) { A = B = 0; if (dfs(i,0)) ret += max(A,B); } printf("%d\n", ret); } return 0; }
19.571429
65
0.395985
[ "vector" ]
ee6a03aab21d4770477b5fd775c555e4feb13434
2,972
cpp
C++
Ko-Fi Engine/Source/PanelResources.cpp
Chamfer-Studios/Ko-Fi-Engine
cdc7fd9fd8c30803ac2e3fe0ecaf1923bbd7532e
[ "MIT" ]
2
2022-02-26T23:35:53.000Z
2022-03-04T16:25:18.000Z
Ko-Fi Engine/Source/PanelResources.cpp
Chamfer-Studios/Ko-Fi-Engine
cdc7fd9fd8c30803ac2e3fe0ecaf1923bbd7532e
[ "MIT" ]
2
2022-02-23T09:41:09.000Z
2022-03-08T08:46:21.000Z
Ko-Fi Engine/Source/PanelResources.cpp
Chamfer-Studios/Ko-Fi-Engine
cdc7fd9fd8c30803ac2e3fe0ecaf1923bbd7532e
[ "MIT" ]
1
2022-03-03T18:41:32.000Z
2022-03-03T18:41:32.000Z
#include "PanelResources.h" #include "M_Editor.h" #include "M_ResourceManager.h" #include "Resource.h" #include "M_ResourceManager.h" #include "optick.h" PanelResources::PanelResources(M_Editor* editor) { panelName = "Resources"; this->editor = editor; this->resourceManager = nullptr; } PanelResources::~PanelResources() { } bool PanelResources::Awake() { return true; } bool PanelResources::Update() { OPTICK_EVENT(); if (editor->toggleResourcesPanel) ShowResourcesWindow(&editor->toggleResourcesPanel); return true; } void PanelResources::ShowResourcesWindow(bool* toggleResourcesPanel) { if (!ImGui::Begin("References", toggleResourcesPanel, ImGuiWindowFlags_AlwaysAutoResize)) { ImGui::End(); return; } if (resourceManager == nullptr) { ImGui::End(); return; } ImVec4 blue(0.0f, 1.0f, 1.0f, 0.8f); ImVec4 yellow(1.0f, 1.0f, 0.0f, 1.0f); uint models = 0; uint meshes = 0; uint textures = 0; uint animations = 0; uint shaders = 0; const std::map<UID, Resource*>* resourcesMap = resourceManager->GetResourcesMap(); std::multimap<uint, Resource*> sorted; for (std::map<UID, Resource*>::const_iterator item = resourcesMap->cbegin(); item != resourcesMap->cend(); ++item) { if (item->second == nullptr) continue; switch (item->second->GetType()) { case ResourceType::MODEL: ++models; break; case ResourceType::MESH: ++meshes; break; case ResourceType::MATERIAL: ++shaders; break; case ResourceType::TEXTURE: ++textures; break; case ResourceType::ANIMATION: ++animations; break; } sorted.emplace((uint)item->second->GetType(), item->second); } for (const auto& rIt : sorted) { ImGui::TextColored(blue, "%s", rIt.second->GetAssetFile()); ImGui::Text("UID:"); ImGui::SameLine(); ImGui::TextColored(yellow, "%lu", rIt.second->GetUID()); std::string type; switch (rIt.second->GetType()) { case ResourceType::MODEL: type = "Model"; break; case ResourceType::MESH: type = "Mesh"; break; case ResourceType::MATERIAL: type = "Shader"; break; case ResourceType::TEXTURE: type = "Texture"; break; case ResourceType::ANIMATION: type = "Animation"; break; } ImGui::Text("Type:"); ImGui::SameLine(); ImGui::TextColored(yellow, "%s", type.c_str()); ImGui::Text("References:"); ImGui::SameLine(); ImGui::TextColored(yellow, "%u", rIt.second->GetReferenceCount()); ImGui::Separator(); } sorted.clear(); ImGui::Text("Total Models:"); ImGui::SameLine(); ImGui::TextColored(yellow, "%u", models); ImGui::Text("Total Meshes:"); ImGui::SameLine(); ImGui::TextColored(yellow, "%u", meshes); ImGui::Text("Total Shaders:"); ImGui::SameLine(); ImGui::TextColored(yellow, "%u", shaders); ImGui::Text("Total Textures:"); ImGui::SameLine(); ImGui::TextColored(yellow, "%u", textures); ImGui::Text("Total Animations:"); ImGui::SameLine(); ImGui::TextColored(yellow, "%u", animations); ImGui::End(); }
20.081081
115
0.6679
[ "mesh", "model" ]
ee79dd09f4222f35add19d047f23eb5eee23a591
6,803
cpp
C++
src/axom/inlet/examples/documentation_generation.cpp
raineyeh/axom
57a6ef7ab50e113e4cf4b639657eb84ff10789c0
[ "BSD-3-Clause" ]
null
null
null
src/axom/inlet/examples/documentation_generation.cpp
raineyeh/axom
57a6ef7ab50e113e4cf4b639657eb84ff10789c0
[ "BSD-3-Clause" ]
null
null
null
src/axom/inlet/examples/documentation_generation.cpp
raineyeh/axom
57a6ef7ab50e113e4cf4b639657eb84ff10789c0
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2017-2021, Lawrence Livermore National Security, LLC and // other Axom Project Developers. See the top-level LICENSE file for details. // // SPDX-License-Identifier: (BSD-3-Clause) // usage : ./inlet_documentation_generation_example --enableDocs --fil lua_file.lua #include "axom/inlet.hpp" #include "axom/slic/core/SimpleLogger.hpp" #include "CLI11/CLI11.hpp" #include <iostream> #include <limits> using axom::inlet::Inlet; using axom::inlet::LuaReader; using axom::inlet::SphinxWriter; using axom::sidre::DataStore; void findStr(std::string path, const Inlet& inlet) { auto proxy = inlet[path]; if(proxy.type() == axom::inlet::InletType::String) { std::cout << "found " << proxy.get<std::string>(); } else { std::cout << "not found "; } std::cout << std::endl; } void findInt(std::string path, const Inlet& inlet) { auto proxy = inlet[path]; if(proxy.type() == axom::inlet::InletType::Integer) { std::cout << "found " << proxy.get<int>(); } else { std::cout << "not found "; } std::cout << std::endl; } void findDouble(std::string path, const Inlet& inlet) { auto proxy = inlet[path]; if(proxy.type() == axom::inlet::InletType::Double) { std::cout << "found " << proxy.get<double>(); } else { std::cout << "not found "; } std::cout << std::endl; } void defineSchema(Inlet& inlet) { // Add the description to the thermal_solver/mesh/filename Field auto& filename_field = inlet.addString("thermal_solver/mesh/filename", "mesh filename"); // Set the field's required property to true filename_field.required(); inlet.addInt("thermal_solver/mesh/serial", "number of serial refinements") .range(0, std::numeric_limits<int>::max()) .defaultValue(1); // The description for thermal_solver/mesh/parallel is left unspecified inlet.addInt("thermal_solver/mesh/parallel") .range(1, std::numeric_limits<int>::max()) .defaultValue(1); inlet.addInt("thermal_solver/order", "polynomial order") .required() .range(1, std::numeric_limits<int>::max()); auto& timestep_field = inlet.addString("thermal_solver/timestepper", "thermal solver timestepper"); timestep_field.defaultValue("quasistatic") .validValues({"quasistatic", "forwardeuler", "backwardeuler"}); auto& coef_type_field = inlet.addString("thermal_solver/u0/type", "description for u0 type"); coef_type_field.defaultValue("constant").validValues({"constant", "function"}); inlet.addString("thermal_solver/u0/func", "description for u0 func").required(); inlet.addString("thermal_solver/kappa/type", "description for kappa type") .required() .validValues({"constant", "function"}); inlet .addDouble("thermal_solver/kappa/constant", "thermal conductivity constant") .required(); // Add description to solver container by using the addStruct function auto& solver_schema = inlet.addStruct("thermal_solver/solver", "linear equation solver options"); // You can also add fields through a container auto& rel_tol_field = solver_schema.addDouble("rel_tol", "solver relative tolerance"); rel_tol_field.required(false); rel_tol_field.defaultValue(1.e-6); rel_tol_field.range(0.0, std::numeric_limits<double>::max()); auto& abs_tol_field = solver_schema.addDouble("abs_tol", "solver absolute tolerance"); abs_tol_field.required(true); abs_tol_field.defaultValue(1.e-12); abs_tol_field.range(0.0, std::numeric_limits<double>::max()); auto& print_level_field = solver_schema.addInt("print_level", "solver print/debug level"); print_level_field.required(true); print_level_field.defaultValue(0); print_level_field.range(0, 3); auto& max_iter_field = solver_schema.addInt("max_iter", "maximum iteration limit"); max_iter_field.required(false); max_iter_field.defaultValue(100); max_iter_field.range(1, std::numeric_limits<int>::max()); auto& dt_field = solver_schema.addDouble("dt", "time step"); dt_field.required(true); dt_field.defaultValue(1); dt_field.range(0.0, std::numeric_limits<double>::max()); auto& steps_field = solver_schema.addInt("steps", "number of steps/cycles to take"); steps_field.required(true); steps_field.defaultValue(1); steps_field.range(1, std::numeric_limits<int>::max()); } // Checking the contents of the passed inlet void checkValues(const Inlet& inlet) { findStr("thermal_solver/mesh/filename", inlet); findStr("thermal_solver/timestepper", inlet); findStr("thermal_solver/u0/type", inlet); findStr("thermal_solver/u0/func", inlet); findStr("thermal_solver/kappa/type", inlet); findInt("thermal_solver/mesh/serial", inlet); findInt("thermal_solver/mesh/parallel", inlet); findInt("thermal_solver/order", inlet); findInt("thermal_solver/solver/print_level", inlet); findInt("thermal_solver/solver/max_iter", inlet); findInt("thermal_solver/solver/steps", inlet); findDouble("thermal_solver/solver/dt", inlet); findDouble("thermal_solver/solver/abs_tol", inlet); findDouble("thermal_solver/solver/rel_tol", inlet); findDouble("thermal_solver/kappa/constant", inlet); // Verify that contents of Inlet meet the requirements of the specified schema if(inlet.verify()) { SLIC_INFO("Inlet verify successful."); } else { SLIC_INFO("Inlet verify failed."); } } int main(int argc, char** argv) { // Inlet requires a SLIC logger to be initialized to output runtime information // This is a generic basic SLIC logger axom::slic::SimpleLogger logger; // Handle command line arguments CLI::App app {"Basic example of Axom's Inlet component"}; bool docsEnabled {false}; app.add_flag("--enableDocs", docsEnabled, "Enables documentation generation"); std::string inputFileName; auto opt = app.add_option("--file", inputFileName, "Path to input file"); opt->check(CLI::ExistingFile); CLI11_PARSE(app, argc, argv); // Create inlet and parse input file data into the inlet DataStore ds; auto lr = std::make_unique<LuaReader>(); lr->parseFile(inputFileName); Inlet inlet(std::move(lr), ds.getRoot(), docsEnabled); defineSchema(inlet); checkValues(inlet); // Generate the documentation // _inlet_documentation_generation_start inlet.write(SphinxWriter("example_doc.rst")); // _inlet_documentation_generation_end inlet.write(axom::inlet::JSONSchemaWriter("example_doc.json")); if(docsEnabled) { SLIC_INFO("Sphinx documentation was written to example_doc.rst\n"); SLIC_INFO("A JSON schema was written to example_doc.json\n"); } return 0; }
31.206422
84
0.689843
[ "mesh" ]
ee7d6059ee031924d426f724f6f12d2c9f4a6e26
1,441
cc
C++
3rdparty/pytorch/caffe2/operators/quantized/int8_fc_op.cc
WoodoLee/TorchCraft
999f68aab9e7d50ed3ae138297226dc95fefc458
[ "MIT" ]
null
null
null
3rdparty/pytorch/caffe2/operators/quantized/int8_fc_op.cc
WoodoLee/TorchCraft
999f68aab9e7d50ed3ae138297226dc95fefc458
[ "MIT" ]
null
null
null
3rdparty/pytorch/caffe2/operators/quantized/int8_fc_op.cc
WoodoLee/TorchCraft
999f68aab9e7d50ed3ae138297226dc95fefc458
[ "MIT" ]
null
null
null
#include "caffe2/operators/quantized/int8_fc_op.h" namespace caffe2 { REGISTER_CPU_OPERATOR(Int8FC, int8::Int8FCOp); OPERATOR_SCHEMA(Int8FC) .NumInputs(3) .NumOutputs(1) .SetDoc(R"DOC( Computes the result of passing an input vector X into a fully connected layer with 2D weight matrix W and 1D bias vector b. That is, the layer computes Y = X * W^T + b, where X has size (M x K), W has size (N x K), b has size (N), and Y has size (M x N), where M is often the batch size. NOTE: X does not need to explicitly be a 2D vector; rather, it will be coerced into one. For an arbitrary n-dimensional tensor X \in [a_0, a_1 * ... * a_{n-1}]. Only this case is supported! Lastly, even though b is a 1D vector of size N, it is copied/resized to be size (M x N) implicitly and added to each vector in the batch. Each of these dimensions must be matched correctly, or else the operator will throw errors. )DOC") .Arg("Y_scale", "Output tensor quantization scale") .Arg("Y_zero_point", "Output tensor quantization offset") .Input( 0, "X", "input tensor that's coerced into a 2D matrix of size (MxK) " "as described above") .Input( 1, "W", "A tensor that is coerced into a 2D blob of size (KxN) " "containing fully connected weight matrix") .Input(2, "b", "1D blob containing bias vector") .Output(0, "Y", "2D output tensor"); } // namespace caffe2
34.309524
72
0.673144
[ "vector" ]
ee807b2842fd4ffa01d529c671742e93b791d9ef
3,199
cpp
C++
resources/Solution Code/Ch6/e6-6.cpp
viniciusjavs/Programming
ef1eed5c0a2782dd3ef1c0453460c93384dab41b
[ "MIT" ]
2
2021-08-19T18:27:58.000Z
2021-12-17T17:53:08.000Z
resources/Solution Code/Ch6/e6-6.cpp
vjavs/Programming
ef1eed5c0a2782dd3ef1c0453460c93384dab41b
[ "MIT" ]
null
null
null
resources/Solution Code/Ch6/e6-6.cpp
vjavs/Programming
ef1eed5c0a2782dd3ef1c0453460c93384dab41b
[ "MIT" ]
null
null
null
// Bjarne Stroustrup 4/11/2009 // Chapter 6 Exercise 6 /* English grammar */ #include "std_lib_facilities.h" // note that different compilers/SDEs keep header files in different places // so that you may have to use "../std_lib_facilities.h" or "../../std_lib_facilities.h" // the ../ notation means "look one directly/folder up from the current directory/folder" /* I started writing the sentence() function and then invented the classification functions is_noun(), etc., then I introduced the vectors of words to represent the classifications. Those word classification vectors makes it trivial to enlarge the vocabulary. The exercise didn't ask us to handle multiple statements, but why not? */ // vectors of words, appropriately classified: vector<string> nouns; vector<string> verbs; vector<string> conjunctions; void init() // initialize word classes { nouns.push_back("birds"); nouns.push_back("fish"); nouns.push_back("C++"); // I didn't suggest addin "C+" to this exercise // but it seems some people like that verbs.push_back("rules"); verbs.push_back("fly"); verbs.push_back("swim"); conjunctions.push_back("and"); conjunctions.push_back("or"); conjunctions.push_back("but"); } bool is_noun(string w) { for(int i = 0; i<nouns.size(); ++i) if (w==nouns[i]) return true; return false; } bool is_verb(string w) { for(int i = 0; i<verbs.size(); ++i) if (w==verbs[i]) return true; return false; } bool is_conjunction(string w) { for(int i = 0; i<conjunctions.size(); ++i) if (w==conjunctions[i]) return true; return false; } bool sentence() { string w; cin >> w; if (!is_noun(w)) return false; string w2; cin >> w2; if (!is_verb(w2)) return false; string w3; cin >> w3; if (w3 == ".") return true; // end of sentence if (!is_conjunction(w3)) return false; // not end of sentence and not conjunction return sentence(); // look for another sentence } int main() try { cout << "enter a sentence of the simplified grammar (terminated by a dot):\n"; init(); // initialize word tables while (cin) { bool b = sentence(); if (b) cout << "OK\n"; else cout << "not OK\n"; cout << "Try again: "; } keep_window_open("~"); // For some Windows(tm) setups } catch (runtime_error e) { // this code is to produceerror messages; it will be described in Chapter 5 cout << e.what() << '\n'; keep_window_open("~"); // For some Windows(tm) setups } /* This is fairly simple, but not very polished. For example, how do you exit gracefully? I suggest adding a way ofgetting out, e.g. if a sentence ends with a '!' rather than with a '.', exit. Or maybe the work "quit" as the start of a sentence should cause an exit. Also, just saying "OK" or "not OK" is not very informative; maybe we could tell the user something about the sentence structure. On simple way of doing that would be for each sentence() call to push a string containing w+w2 onto a sentences vector and w3 onto a conjs vector, so that we could output "( birds fly ) but (fish swim)" for the input "birds fly but fish swim ." */
28.061404
108
0.665833
[ "vector" ]
ee863fd5354869b614b27ae9ea54550ff00165c3
2,869
cpp
C++
Algorithm/Sources/Algorithms/SJTAlgorithm.cpp
Minusi/AlgorithmArchive
f579f91024a582cdf7e36591308123f8c920e204
[ "Unlicense" ]
null
null
null
Algorithm/Sources/Algorithms/SJTAlgorithm.cpp
Minusi/AlgorithmArchive
f579f91024a582cdf7e36591308123f8c920e204
[ "Unlicense" ]
null
null
null
Algorithm/Sources/Algorithms/SJTAlgorithm.cpp
Minusi/AlgorithmArchive
f579f91024a582cdf7e36591308123f8c920e204
[ "Unlicense" ]
null
null
null
๏ปฟ//#include <iostream> //#include <vector> //#include <algorithm> // //using namespace std; // // // //bool IsMobile(int, vector<int>&, const vector<int>&); // //// ๊ฐ ์š”์†Œ๋“ค์ด ์›€์ง์ผ ์ˆ˜ ์žˆ๋Š” ์ง€ ๊ฒ€์‚ฌํ•ฉ๋‹ˆ๋‹ค. //bool CheckMobiles(vector<int>& Array, const vector<int>& Directions) //{ // for (int i = 0; i < Array.size(); ++i) // { // if (IsMobile(i, Array, Directions)) // { // return true; // } // } // return false; //} // //// ํ•ด๋‹น ์š”์†Œ๊ฐ€ ์›€์ง์ผ ์ˆ˜ ์žˆ๋Š”์ง€ ๊ฒ€์‚ฌํ•ฉ๋‹ˆ๋‹ค. //bool IsMobile(int p, vector<int>& Array, const vector<int>& Directions) //{ // // ์ฒซ ๋ฒˆ์งธ ์š”์†Œ๊ฐ€ ์™ผ์ชฝ์œผ๋กœ ์ด๋™ํ•  ์ˆ˜ ์žˆ๋‹ค๋ฉด false์ž…๋‹ˆ๋‹ค. // if (p == 0 && Directions[p] == 0) // { // return false; // } // // ๋งˆ์ง€๋ง‰ ์š”์†Œ๊ฐ€ ์˜ค๋ฅธ์ชฝ์œผ๋กœ ์ด๋™ํ•  ์ˆ˜ ์žˆ๋‹ค๋ฉด false์ž…๋‹ˆ๋‹ค. // else if (p == Array.size() - 1 && Directions[p] == 1) // { // return false; // } // else // { // // ์™ผ์ชฝ์œผ๋กœ ์›€์ง์ผ ์ˆ˜ ์žˆ๊ณ , ์™ผ์ชฝ ์š”์†Œ๋ณด๋‹ค ๊ฐ’์ด ํฌ๋ฉด true์ž…๋‹ˆ๋‹ค. // if (Directions[p] == 0) // { // if (Array[p] > Array[p - 1]) // { // return true; // } // } // // ์˜ค๋ฅธ์ชฝ์œผ๋กœ ์›€์ง์ผ ์ˆ˜ ์žˆ๊ณ , ์˜ค๋ฅธ์ชฝ ์š”์†Œ๋ณด๋‹ค ๊ฐ’์ด ํฌ๋ฉด true์ž…๋‹ˆ๋‹ค. // else // { // if (Array[p] > Array[p + 1]) // { // return true; // } // } // } // // // ๊ทธ ์™ธ์˜ ๊ฒฝ์šฐ, ์ „๋ถ€ false์ž…๋‹ˆ๋‹ค. // return false; //} // // // //// ์›€์ง์ผ ์ˆ˜ ์žˆ๋Š” ์ˆ˜ ์ค‘ ๊ฐ€์žฅ ํฐ ์ˆ˜์˜ ์ธ๋ฑ์Šค๋ฅผ ์ฐพ์Šต๋‹ˆ๋‹ค. //int FindLargest(vector<int>& Array, const vector<int>& Directions) //{ // vector<int> MobileNumbers; // // // ์›€์ง์ผ ์ˆ˜ ์žˆ๋Š” ๋ชจ๋“  ์ˆ˜์— ๋Œ€ํ•œ ์ธ๋ฑ์Šค๋ฅผ ์ฐพ์Šต๋‹ˆ๋‹ค. // for (int i = 0; i < Array.size(); ++i) // { // if (IsMobile(i, Array, Directions)) // { // // ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜๋ฉด ์ธ๋ฑ์Šค๋ฅผ ์‚ฝ์ž…ํ•ฉ๋‹ˆ๋‹ค. // MobileNumbers.push_back(i); // } // } // // int Largest = MobileNumbers[0]; // // // ๋น„๊ต ์—ฐ์‚ฐ์„ ํ†ตํ•ด ์›€์ง์ผ ์ˆ˜ ์žˆ๋Š” ๊ฐ€์žฅ ํฐ ์ˆ˜์˜ ์ธ๋ฑ์Šค๋ฅผ ์ฐพ์Šต๋‹ˆ๋‹ค. // for (int p = 1; p < MobileNumbers.size(); ++p) // { // if (Array[MobileNumbers[p]] > Array[Largest]) // { // Largest = MobileNumbers[p]; // } // } // // // ์ธ๋ฑ์Šค๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. // return Largest; //} // // // //// ๋ฉ”์ธ ํ•จ์ˆ˜ //void SJTAlgorithm(vector<int>& Array) //{ // int k; // vector<int> Directions; // // for (const auto it : Array) // { // Directions.push_back(0); // } // // for (const auto it : Array) // { // cout << it << " "; // } // cout << endl; // // // ๋ฐฐ์—ด์—์„œ ์›€์ง์ผ ์ˆ˜ ์žˆ๋Š” ์š”์†Œ๊ฐ€ ์—†์„ ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณตํ•ฉ๋‹ˆ๋‹ค. // while (CheckMobiles(Array, Directions)) // { // // ๊ฐ€์žฅ ํฐ ์ˆ˜์˜ ์ธ๋ฑ์Šค๋ฅผ ์ฐพ์•„์„œ ์™ผ์ชฝ์œผ๋กœ ์›€์ง์ผ ์ˆ˜ ์žˆ๋‹ค๋ฉด ์Šค์™‘ํ•ฉ๋‹ˆ๋‹ค. // k = FindLargest(Array, Directions); // if (Directions[k] == 0) // { // swap(Array[k], Array[k - 1]); // swap(Directions[k], Directions[k - 1]); // k = k - 1; // } // // ๊ทธ ์™ธ์˜ ๊ฒฝ์šฐ, ์˜ค๋ฅธ์ชฝ์œผ๋กœ ์Šค์™‘ํ•ฉ๋‹ˆ๋‹ค. // else // { // swap(Array[k], Array[k + 1]); // swap(Directions[k], Directions[k + 1]); // k += 1; // } // // for (int i = 0; i < Array.size(); ++i) // { // if (Array[i] > Array[k]) // { // if (Directions[i] == 0) // { // Directions[i] = 1; // } // else // { // Directions[i] = 0; // } // } // } // // for (const auto it : Array) // { // cout << it << " "; // } // cout << endl; // } //} // // // //void main() //{ // vector<int> Array = { 1,2,3,4 }; // SJTAlgorithm(Array); //}
17.93125
73
0.504357
[ "vector" ]