commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
a84983ea72ca5569585a4f321e2bb89cf78d6d9c
lib/ExecutionEngine/JIT/JIT.cpp
lib/ExecutionEngine/JIT/JIT.cpp
//===-- JIT.cpp - LLVM Just in Time Compiler ------------------------------===// // // This file implements the top-level support for creating a Just-In-Time // compiler for the current architecture. // //===----------------------------------------------------------------------===// #include "VM.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetMachineImpls.h" #include "llvm/Module.h" #include "Support/CommandLine.h" // FIXME: REMOVE THIS #include "llvm/PassManager.h" #if !defined(ENABLE_X86_JIT) && !defined(ENABLE_SPARC_JIT) #define NO_JITS_ENABLED #endif namespace { enum ArchName { x86, Sparc }; #ifndef NO_JITS_ENABLED cl::opt<ArchName> Arch("march", cl::desc("Architecture to JIT to:"), cl::Prefix, cl::values( #ifdef ENABLE_X86_JIT clEnumVal(x86, " IA-32 (Pentium and above)"), #endif #ifdef ENABLE_SPARC_JIT clEnumValN(Sparc, "sparc", " Sparc-V9"), #endif 0), #if defined(ENABLE_X86_JIT) cl::init(x86) #elif defined(ENABLE_SPARC_JIT) cl::init(Sparc) #endif ); #endif /* NO_JITS_ENABLED */ } /// createJIT - Create an return a new JIT compiler if there is one available /// for the current target. Otherwise it returns null. /// ExecutionEngine *ExecutionEngine::createJIT(Module *M, unsigned Config) { TargetMachine* (*TargetMachineAllocator)(unsigned) = 0; // Allow a command-line switch to override what *should* be the default target // machine for this platform. This allows for debugging a Sparc JIT on X86 -- // our X86 machines are much faster at recompiling LLVM and linking LLI. #ifdef NO_JITS_ENABLED return 0; #endif switch (Arch) { #ifdef ENABLE_X86_JIT case x86: TargetMachineAllocator = allocateX86TargetMachine; break; #endif #ifdef ENABLE_SPARC_JIT case Sparc: TargetMachineAllocator = allocateSparcTargetMachine; break; #endif default: assert(0 && "-march flag not supported on this host!"); } // Allocate a target... TargetMachine *Target = (*TargetMachineAllocator)(Config); assert(Target && "Could not allocate target machine!"); // Create the virtual machine object... return new VM(M, Target); } VM::VM(Module *M, TargetMachine *tm) : ExecutionEngine(M), TM(*tm) { setTargetData(TM.getTargetData()); // Initialize MCE MCE = createEmitter(*this); setupPassManager(); #ifdef ENABLE_SPARC_JIT // THIS GOES BEYOND UGLY HACKS if (TM.getName() == "UltraSparc-Native") { extern Pass *createPreSelectionPass(TargetMachine &TM); PassManager PM; // Specialize LLVM code for this target machine and then // run basic dataflow optimizations on LLVM code. PM.add(createPreSelectionPass(TM)); PM.run(*M); } #endif emitGlobals(); } int VM::run(const std::string &FnName, const std::vector<std::string> &Args) { Function *F = getModule().getNamedFunction(FnName); if (F == 0) { std::cerr << "Could not find function '" << FnName <<"' in module!\n"; return 1; } int(*PF)(int, char**) = (int(*)(int, char**))getPointerToFunction(F); assert(PF != 0 && "Null pointer to function?"); // Build an argv vector... char **Argv = (char**)CreateArgv(Args); // Call the main function... int Result = PF(Args.size(), Argv); // Run any atexit handlers now! runAtExitHandlers(); return Result; }
//===-- JIT.cpp - LLVM Just in Time Compiler ------------------------------===// // // This file implements the top-level support for creating a Just-In-Time // compiler for the current architecture. // //===----------------------------------------------------------------------===// #include "VM.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetMachineImpls.h" #include "llvm/Module.h" #include "Support/CommandLine.h" // FIXME: REMOVE THIS #include "llvm/PassManager.h" #if !defined(ENABLE_X86_JIT) && !defined(ENABLE_SPARC_JIT) #define NO_JITS_ENABLED #endif namespace { enum ArchName { x86, Sparc }; #ifndef NO_JITS_ENABLED cl::opt<ArchName> Arch("march", cl::desc("Architecture to JIT to:"), cl::Prefix, cl::values( #ifdef ENABLE_X86_JIT clEnumVal(x86, " IA-32 (Pentium and above)"), #endif #ifdef ENABLE_SPARC_JIT clEnumValN(Sparc, "sparc", " Sparc-V9"), #endif 0), #if defined(ENABLE_X86_JIT) cl::init(x86) #elif defined(ENABLE_SPARC_JIT) cl::init(Sparc) #endif ); #endif /* NO_JITS_ENABLED */ } /// createJIT - Create an return a new JIT compiler if there is one available /// for the current target. Otherwise it returns null. /// ExecutionEngine *ExecutionEngine::createJIT(Module *M, unsigned Config) { TargetMachine* (*TargetMachineAllocator)(unsigned) = 0; // Allow a command-line switch to override what *should* be the default target // machine for this platform. This allows for debugging a Sparc JIT on X86 -- // our X86 machines are much faster at recompiling LLVM and linking LLI. #ifdef NO_JITS_ENABLED return 0; #endif switch (Arch) { #ifdef ENABLE_X86_JIT case x86: TargetMachineAllocator = allocateX86TargetMachine; break; #endif #ifdef ENABLE_SPARC_JIT case Sparc: TargetMachineAllocator = allocateSparcTargetMachine; break; #endif default: assert(0 && "-march flag not supported on this host!"); } // Allocate a target... TargetMachine *Target = (*TargetMachineAllocator)(Config); assert(Target && "Could not allocate target machine!"); // Create the virtual machine object... return new VM(M, Target); } VM::VM(Module *M, TargetMachine *tm) : ExecutionEngine(M), TM(*tm) { setTargetData(TM.getTargetData()); // Initialize MCE MCE = createEmitter(*this); setupPassManager(); #ifdef ENABLE_SPARC_JIT // THIS GOES BEYOND UGLY HACKS if (TM.getName() == "UltraSparc-Native") { extern Pass *createPreSelectionPass(TargetMachine &TM); PassManager PM; // Specialize LLVM code for this target machine and then // run basic dataflow optimizations on LLVM code. PM.add(createPreSelectionPass(TM)); PM.run(*M); } #endif emitGlobals(); } int VM::run(const std::string &FnName, const std::vector<std::string> &Args) { Function *F = getModule().getNamedFunction(FnName); if (F == 0) { std::cerr << "Could not find function '" << FnName << "' in module!\n"; return 1; } int(*PF)(int, char**) = (int(*)(int, char**))getPointerToFunction(F); assert(PF != 0 && "Null pointer to function?"); // Build an argv vector... char **Argv = (char**)CreateArgv(Args); // Call the main function... int Result = PF(Args.size(), Argv); // Run any atexit handlers now! runAtExitHandlers(); return Result; }
Fix space
Fix space git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@7273 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
apple/swift-llvm,chubbymaggie/asap,chubbymaggie/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,dslab-epfl/asap,chubbymaggie/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,chubbymaggie/asap,apple/swift-llvm,dslab-epfl/asap,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,dslab-epfl/asap,dslab-epfl/asap,apple/swift-llvm,chubbymaggie/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,dslab-epfl/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,dslab-epfl/asap,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm
5e491e31d6fe9ec924ef565c833ba25db714b00a
lib/Option/SanitizerOptions.cpp
lib/Option/SanitizerOptions.cpp
//===--- SanitizerOptions.cpp - Swift Sanitizer options ------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // \file // This file implements the parsing of sanitizer arguments. // //===----------------------------------------------------------------------===// #include "swift/Option/SanitizerOptions.h" #include "swift/AST/DiagnosticEngine.h" #include "swift/AST/DiagnosticsFrontend.h" using namespace swift; static StringRef toStringRef(const SanitizerKind kind) { switch (kind) { case SanitizerKind::Address: return "address"; case SanitizerKind::None: llvm_unreachable("Getting a name for SanitizerKind::None"); } llvm_unreachable("Unsupported sanitizer"); } SanitizerKind swift::parseSanitizerArgValues(const llvm::opt::Arg *A, const llvm::Triple &Triple, DiagnosticEngine &Diags) { SanitizerKind kind = SanitizerKind::None; // Find the sanitizer kind. // TODO: Add support for dealing with multiple sanitizers. for (int i = 0, n = A->getNumValues(); i != n; ++i) { const char *Value = A->getValue(i); if (StringRef(Value).equals("address")) { kind = SanitizerKind::Address; } else { Diags.diagnose(SourceLoc(), diag::error_unsupported_option_argument, A->getOption().getName(), A->getValue(i)); return kind; } } // Check if the traget is supported for this sanitizer. if (!Triple.isOSDarwin() && kind != SanitizerKind::None) { SmallVector<char, 128> buffer; Diags.diagnose(SourceLoc(), diag::error_unsupported_opt_for_target, (A->getOption().getName() + toStringRef(kind)).toStringRef(buffer), Triple.getTriple()); } return kind; }
//===--- SanitizerOptions.cpp - Swift Sanitizer options ------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // \file // This file implements the parsing of sanitizer arguments. // //===----------------------------------------------------------------------===// #include "swift/Option/SanitizerOptions.h" #include "swift/AST/DiagnosticEngine.h" #include "swift/AST/DiagnosticsFrontend.h" using namespace swift; static StringRef toStringRef(const SanitizerKind kind) { switch (kind) { case SanitizerKind::Address: return "address"; case SanitizerKind::None: llvm_unreachable("Getting a name for SanitizerKind::None"); } llvm_unreachable("Unsupported sanitizer"); } SanitizerKind swift::parseSanitizerArgValues(const llvm::opt::Arg *A, const llvm::Triple &Triple, DiagnosticEngine &Diags) { SanitizerKind kind = SanitizerKind::None; // Find the sanitizer kind. // TODO: Add support for dealing with multiple sanitizers. for (int i = 0, n = A->getNumValues(); i != n; ++i) { const char *Value = A->getValue(i); if (StringRef(Value).equals("address")) { kind = SanitizerKind::Address; } else { Diags.diagnose(SourceLoc(), diag::error_unsupported_option_argument, A->getOption().getName(), A->getValue(i)); return kind; } } // Check if the target is supported for this sanitizer. if (!Triple.isOSDarwin() && kind != SanitizerKind::None) { SmallVector<char, 128> buffer; Diags.diagnose(SourceLoc(), diag::error_unsupported_opt_for_target, (A->getOption().getName() + toStringRef(kind)).toStringRef(buffer), Triple.getTriple()); } return kind; }
Fix recently introduced typo: "traget" → "target"
[gardening] Fix recently introduced typo: "traget" → "target"
C++
apache-2.0
jtbandes/swift,ahoppen/swift,atrick/swift,atrick/swift,swiftix/swift,jopamer/swift,return/swift,lorentey/swift,tinysun212/swift-windows,therealbnut/swift,jckarter/swift,arvedviehweger/swift,johnno1962d/swift,jckarter/swift,JGiola/swift,harlanhaskins/swift,aschwaighofer/swift,devincoughlin/swift,rudkx/swift,modocache/swift,benlangmuir/swift,shajrawi/swift,karwa/swift,huonw/swift,amraboelela/swift,sschiau/swift,jckarter/swift,djwbrown/swift,apple/swift,harlanhaskins/swift,KrishMunot/swift,stephentyrone/swift,codestergit/swift,milseman/swift,alblue/swift,ken0nek/swift,danielmartin/swift,manavgabhawala/swift,sschiau/swift,therealbnut/swift,tjw/swift,glessard/swift,zisko/swift,sschiau/swift,kstaring/swift,arvedviehweger/swift,ahoppen/swift,stephentyrone/swift,devincoughlin/swift,atrick/swift,devincoughlin/swift,deyton/swift,SwiftAndroid/swift,sschiau/swift,xedin/swift,hughbe/swift,calebd/swift,hooman/swift,shahmishal/swift,kperryua/swift,SwiftAndroid/swift,nathawes/swift,devincoughlin/swift,karwa/swift,jmgc/swift,shajrawi/swift,therealbnut/swift,uasys/swift,JaSpa/swift,xwu/swift,rudkx/swift,arvedviehweger/swift,bitjammer/swift,OscarSwanros/swift,tkremenek/swift,airspeedswift/swift,gribozavr/swift,austinzheng/swift,tinysun212/swift-windows,CodaFi/swift,calebd/swift,modocache/swift,russbishop/swift,airspeedswift/swift,gribozavr/swift,codestergit/swift,milseman/swift,glessard/swift,dduan/swift,practicalswift/swift,frootloops/swift,gmilos/swift,danielmartin/swift,russbishop/swift,allevato/swift,swiftix/swift,deyton/swift,apple/swift,KrishMunot/swift,rudkx/swift,parkera/swift,IngmarStein/swift,kstaring/swift,russbishop/swift,felix91gr/swift,jmgc/swift,allevato/swift,gottesmm/swift,parkera/swift,danielmartin/swift,shahmishal/swift,stephentyrone/swift,danielmartin/swift,bitjammer/swift,roambotics/swift,jtbandes/swift,arvedviehweger/swift,SwiftAndroid/swift,harlanhaskins/swift,austinzheng/swift,bitjammer/swift,airspeedswift/swift,benlangmuir/swift,ahoppen/swift,bitjammer/swift,zisko/swift,Jnosh/swift,ken0nek/swift,johnno1962d/swift,ken0nek/swift,OscarSwanros/swift,huonw/swift,gottesmm/swift,kperryua/swift,danielmartin/swift,jopamer/swift,frootloops/swift,JaSpa/swift,benlangmuir/swift,gottesmm/swift,KrishMunot/swift,tinysun212/swift-windows,stephentyrone/swift,hughbe/swift,JGiola/swift,austinzheng/swift,roambotics/swift,SwiftAndroid/swift,Jnosh/swift,natecook1000/swift,dreamsxin/swift,Jnosh/swift,return/swift,zisko/swift,stephentyrone/swift,shahmishal/swift,xedin/swift,hughbe/swift,apple/swift,tkremenek/swift,deyton/swift,shahmishal/swift,xwu/swift,tinysun212/swift-windows,glessard/swift,SwiftAndroid/swift,jckarter/swift,gregomni/swift,rudkx/swift,calebd/swift,parkera/swift,roambotics/swift,djwbrown/swift,jmgc/swift,JGiola/swift,aschwaighofer/swift,CodaFi/swift,gribozavr/swift,tjw/swift,johnno1962d/swift,devincoughlin/swift,lorentey/swift,devincoughlin/swift,milseman/swift,kstaring/swift,rudkx/swift,natecook1000/swift,huonw/swift,IngmarStein/swift,shajrawi/swift,gmilos/swift,hooman/swift,alblue/swift,swiftix/swift,xwu/swift,alblue/swift,parkera/swift,ben-ng/swift,alblue/swift,CodaFi/swift,apple/swift,airspeedswift/swift,CodaFi/swift,deyton/swift,hughbe/swift,jopamer/swift,OscarSwanros/swift,aschwaighofer/swift,hooman/swift,xwu/swift,arvedviehweger/swift,uasys/swift,djwbrown/swift,return/swift,practicalswift/swift,jckarter/swift,xedin/swift,dduan/swift,shajrawi/swift,russbishop/swift,OscarSwanros/swift,gmilos/swift,jmgc/swift,allevato/swift,lorentey/swift,milseman/swift,KrishMunot/swift,gottesmm/swift,therealbnut/swift,benlangmuir/swift,harlanhaskins/swift,karwa/swift,milseman/swift,JaSpa/swift,amraboelela/swift,uasys/swift,IngmarStein/swift,milseman/swift,djwbrown/swift,gregomni/swift,austinzheng/swift,IngmarStein/swift,gregomni/swift,amraboelela/swift,practicalswift/swift,therealbnut/swift,shahmishal/swift,manavgabhawala/swift,gmilos/swift,manavgabhawala/swift,frootloops/swift,karwa/swift,uasys/swift,KrishMunot/swift,tkremenek/swift,amraboelela/swift,deyton/swift,johnno1962d/swift,felix91gr/swift,harlanhaskins/swift,therealbnut/swift,ben-ng/swift,arvedviehweger/swift,alblue/swift,practicalswift/swift,nathawes/swift,hughbe/swift,codestergit/swift,frootloops/swift,xedin/swift,shahmishal/swift,airspeedswift/swift,ben-ng/swift,KrishMunot/swift,parkera/swift,jtbandes/swift,Jnosh/swift,dduan/swift,ahoppen/swift,ken0nek/swift,tkremenek/swift,atrick/swift,jopamer/swift,allevato/swift,parkera/swift,manavgabhawala/swift,natecook1000/swift,xwu/swift,brentdax/swift,brentdax/swift,lorentey/swift,tardieu/swift,sschiau/swift,apple/swift,stephentyrone/swift,brentdax/swift,stephentyrone/swift,zisko/swift,xedin/swift,kperryua/swift,calebd/swift,gribozavr/swift,IngmarStein/swift,harlanhaskins/swift,gmilos/swift,JaSpa/swift,modocache/swift,gribozavr/swift,airspeedswift/swift,jtbandes/swift,tardieu/swift,manavgabhawala/swift,glessard/swift,roambotics/swift,nathawes/swift,karwa/swift,practicalswift/swift,tjw/swift,shajrawi/swift,Jnosh/swift,modocache/swift,gregomni/swift,amraboelela/swift,lorentey/swift,rudkx/swift,tjw/swift,brentdax/swift,return/swift,ken0nek/swift,airspeedswift/swift,nathawes/swift,dduan/swift,russbishop/swift,JaSpa/swift,frootloops/swift,jopamer/swift,tkremenek/swift,felix91gr/swift,ken0nek/swift,austinzheng/swift,kstaring/swift,lorentey/swift,allevato/swift,jtbandes/swift,ahoppen/swift,jopamer/swift,jckarter/swift,xwu/swift,aschwaighofer/swift,ahoppen/swift,JGiola/swift,nathawes/swift,kperryua/swift,atrick/swift,return/swift,felix91gr/swift,modocache/swift,kperryua/swift,ben-ng/swift,parkera/swift,lorentey/swift,tkremenek/swift,practicalswift/swift,practicalswift/swift,natecook1000/swift,uasys/swift,JaSpa/swift,atrick/swift,dduan/swift,danielmartin/swift,codestergit/swift,return/swift,nathawes/swift,johnno1962d/swift,felix91gr/swift,JGiola/swift,calebd/swift,shajrawi/swift,nathawes/swift,gmilos/swift,djwbrown/swift,shahmishal/swift,jmgc/swift,karwa/swift,swiftix/swift,modocache/swift,modocache/swift,jmgc/swift,parkera/swift,natecook1000/swift,tardieu/swift,Jnosh/swift,hooman/swift,tjw/swift,shajrawi/swift,alblue/swift,devincoughlin/swift,uasys/swift,zisko/swift,jckarter/swift,dreamsxin/swift,xedin/swift,OscarSwanros/swift,allevato/swift,swiftix/swift,hooman/swift,deyton/swift,lorentey/swift,kstaring/swift,sschiau/swift,KrishMunot/swift,JaSpa/swift,felix91gr/swift,jopamer/swift,aschwaighofer/swift,swiftix/swift,kstaring/swift,gmilos/swift,deyton/swift,dduan/swift,glessard/swift,IngmarStein/swift,uasys/swift,djwbrown/swift,Jnosh/swift,xwu/swift,kperryua/swift,jmgc/swift,kperryua/swift,arvedviehweger/swift,ben-ng/swift,russbishop/swift,roambotics/swift,apple/swift,austinzheng/swift,benlangmuir/swift,dduan/swift,djwbrown/swift,huonw/swift,tardieu/swift,karwa/swift,gribozavr/swift,xedin/swift,brentdax/swift,brentdax/swift,karwa/swift,manavgabhawala/swift,practicalswift/swift,tardieu/swift,hughbe/swift,gribozavr/swift,IngmarStein/swift,amraboelela/swift,SwiftAndroid/swift,therealbnut/swift,tjw/swift,brentdax/swift,shahmishal/swift,glessard/swift,JGiola/swift,zisko/swift,austinzheng/swift,huonw/swift,huonw/swift,return/swift,tinysun212/swift-windows,tardieu/swift,russbishop/swift,CodaFi/swift,ben-ng/swift,SwiftAndroid/swift,gribozavr/swift,tardieu/swift,frootloops/swift,calebd/swift,jtbandes/swift,roambotics/swift,tkremenek/swift,codestergit/swift,calebd/swift,natecook1000/swift,xedin/swift,tinysun212/swift-windows,benlangmuir/swift,shajrawi/swift,devincoughlin/swift,hooman/swift,sschiau/swift,OscarSwanros/swift,huonw/swift,bitjammer/swift,manavgabhawala/swift,OscarSwanros/swift,johnno1962d/swift,aschwaighofer/swift,codestergit/swift,gottesmm/swift,CodaFi/swift,gottesmm/swift,sschiau/swift,gregomni/swift,swiftix/swift,natecook1000/swift,aschwaighofer/swift,gottesmm/swift,hughbe/swift,codestergit/swift,harlanhaskins/swift,frootloops/swift,bitjammer/swift,hooman/swift,danielmartin/swift,allevato/swift,amraboelela/swift,kstaring/swift,ken0nek/swift,zisko/swift,johnno1962d/swift,milseman/swift,alblue/swift,felix91gr/swift,bitjammer/swift,CodaFi/swift,gregomni/swift,ben-ng/swift,tinysun212/swift-windows,tjw/swift,jtbandes/swift
f91726d1fc2beb45d228725d0031ada2d3ad43d3
src/ircprotocol.cpp
src/ircprotocol.cpp
/* * Copyright (C) 2008-2013 The Communi Project * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. */ #include "ircprotocol.h" #include "ircsession_p.h" #include "ircsessioninfo.h" #include "ircmessagebuilder_p.h" #include "ircsession.h" #include "ircmessage.h" #include "irccommand.h" #include "irc.h" #include <QDebug> class IrcProtocolPrivate { Q_DECLARE_PUBLIC(IrcProtocol) public: IrcProtocolPrivate(IrcProtocol* protocol); void readLines(const QByteArray& delimiter); void processLine(const QByteArray& line); void handleNumericMessage(IrcNumericMessage* msg); void handlePrivateMessage(IrcPrivateMessage* msg); void handleCapabilityMessage(IrcCapabilityMessage* msg); IrcProtocol* q_ptr; IrcSession* session; IrcMessageBuilder* builder; QByteArray buffer; QSet<QString> activeCaps; QSet<QString> availableCaps; }; IrcProtocolPrivate::IrcProtocolPrivate(IrcProtocol* protocol) : q_ptr(protocol) { } void IrcProtocolPrivate::readLines(const QByteArray& delimiter) { int i = -1; while ((i = buffer.indexOf(delimiter)) != -1) { QByteArray line = buffer.left(i).trimmed(); buffer = buffer.mid(i + delimiter.length()); if (!line.isEmpty()) processLine(line); } } void IrcProtocolPrivate::processLine(const QByteArray& line) { Q_Q(IrcProtocol); static bool dbg = qgetenv("COMMUNI_DEBUG").toInt(); if (dbg) qDebug() << line; if (line.startsWith("AUTHENTICATE")) { const QList<QByteArray> args = line.split(' '); const bool auth = args.count() == 2 && args.at(1) == "+"; q->authenticate(auth && session->isSecure()); if (!session->isConnected()) session->sendData("CAP END"); return; } IrcMessage* msg = IrcMessage::fromData(line, session); if (msg) { msg->setEncoding(session->encoding()); switch (msg->type()) { case IrcMessage::Capability: handleCapabilityMessage(static_cast<IrcCapabilityMessage*>(msg)); break; case IrcMessage::Nick: if (msg->flags() & IrcMessage::Own) q->setNick(static_cast<IrcNickMessage*>(msg)->nick()); break; case IrcMessage::Numeric: handleNumericMessage(static_cast<IrcNumericMessage*>(msg)); break; case IrcMessage::Ping: session->sendRaw("PONG " + static_cast<IrcPingMessage*>(msg)->argument()); break; case IrcMessage::Private: handlePrivateMessage(static_cast<IrcPrivateMessage*>(msg)); break; default: break; } q->receiveMessage(msg); if (msg->type() == IrcMessage::Numeric) builder->processMessage(static_cast<IrcNumericMessage*>(msg)); } } void IrcProtocolPrivate::handleNumericMessage(IrcNumericMessage* msg) { Q_Q(IrcProtocol); switch (msg->code()) { case Irc::RPL_WELCOME: q->setNick(msg->parameters().value(0)); q->setConnected(true); break; case Irc::RPL_ISUPPORT: { QHash<QString, QString> info; foreach (const QString& param, msg->parameters().mid(1)) { QStringList keyValue = param.split("=", QString::SkipEmptyParts); info.insert(keyValue.value(0), keyValue.value(1)); } q->setInfo(info); break; } case Irc::ERR_NICKNAMEINUSE: case Irc::ERR_NICKCOLLISION: { QString alternate; emit session->nickNameReserved(&alternate); if (!alternate.isEmpty()) session->setNickName(alternate); break; } default: break; } } void IrcProtocolPrivate::handlePrivateMessage(IrcPrivateMessage* msg) { if (msg->isRequest()) { IrcCommand* reply = session->createCtcpReply(msg); if (reply) session->sendCommand(reply); } } static void handleCapability(QSet<QString>* caps, const QString& cap) { Q_ASSERT(caps); if (cap.startsWith(QLatin1Char('-')) || cap.startsWith(QLatin1Char('='))) caps->remove(cap.mid(1)); else if (cap.startsWith(QLatin1Char('~'))) caps->insert(cap.mid(1)); else caps->insert(cap); } void IrcProtocolPrivate::handleCapabilityMessage(IrcCapabilityMessage* msg) { Q_Q(IrcProtocol); const bool connected = session->isConnected(); const QString subCommand = msg->subCommand(); if (subCommand == "LS") { foreach (const QString& cap, msg->capabilities()) handleCapability(&availableCaps, cap); if (!connected) { const QStringList params = msg->parameters(); if (params.value(params.count() - 1) != QLatin1String("*")) { QStringList request; emit session->capabilities(availableCaps.toList(), &request); if (!request.isEmpty()) { session->sendCommand(IrcCommand::createCapability("REQ", request)); } else { // TODO: #14: SASL over non-SSL connection if (session->isSecure()) q->authenticate(false); session->sendData("CAP END"); } } } } else if (subCommand == "ACK" || subCommand == "NAK") { bool auth = false; if (subCommand == "ACK") { foreach (const QString& cap, msg->capabilities()) { handleCapability(&activeCaps, cap); if (cap == "sasl") auth = session->sendData("AUTHENTICATE PLAIN"); // TODO: methods } } if (!connected && !auth) { // TODO: #14: SASL over non-SSL connection if (session->isSecure()) q->authenticate(false); session->sendData("CAP END"); } } } IrcProtocol::IrcProtocol(IrcSession* session) : QObject(session), d_ptr(new IrcProtocolPrivate(this)) { Q_D(IrcProtocol); d->session = session; d->builder = new IrcMessageBuilder(session); connect(d->builder, SIGNAL(messageReceived(IrcMessage*)), this, SLOT(receiveMessage(IrcMessage*))); } IrcProtocol::~IrcProtocol() { Q_D(IrcProtocol); delete d->builder; } IrcSession* IrcProtocol::session() const { Q_D(const IrcProtocol); return d->session; } QAbstractSocket* IrcProtocol::socket() const { Q_D(const IrcProtocol); return d->session->socket(); } void IrcProtocol::open() { Q_D(IrcProtocol); const bool secure = d->session->isSecure(); if (secure) QMetaObject::invokeMethod(socket(), "startClientEncryption"); d->activeCaps.clear(); d->availableCaps.clear(); // Send CAP LS first; if the server understands it this will // temporarily pause the handshake until CAP END is sent, so we // know whether the server supports the CAP extension. d->session->sendData("CAP LS"); if (!d->session->isSecure()) authenticate(false); d->session->sendCommand(IrcCommand::createNick(d->session->nickName())); d->session->sendRaw(QString("USER %1 hostname servername :%2").arg(d->session->userName(), d->session->realName())); } void IrcProtocol::authenticate(bool secure) { Q_D(IrcProtocol); QString passwd; emit d->session->password(&passwd); if (!passwd.isEmpty()) { if (secure) { const QByteArray userName = d->session->userName().toUtf8(); const QByteArray data = userName + '\0' + userName + '\0' + passwd.toUtf8(); d->session->sendData("AUTHENTICATE " + data.toBase64()); } else { d->session->sendRaw(QString("PASS %1").arg(passwd)); } } } void IrcProtocol::read() { Q_D(IrcProtocol); d->buffer += socket()->readAll(); // try reading RFC compliant message lines first d->readLines("\r\n"); // fall back to RFC incompliant lines... d->readLines("\n"); } bool IrcProtocol::write(const QByteArray& data) { return socket()->write(data + QByteArray("\r\n")) != -1; } QStringList IrcProtocol::availableCapabilities() const { Q_D(const IrcProtocol); return d->availableCaps.toList(); } QStringList IrcProtocol::activeCapabilities() const { Q_D(const IrcProtocol); return d->activeCaps.toList(); } void IrcProtocol::setActive(bool active) { Q_D(IrcProtocol); IrcSessionPrivate* priv = IrcSessionPrivate::get(d->session); priv->setActive(active); } void IrcProtocol::setConnected(bool connected) { Q_D(IrcProtocol); IrcSessionPrivate* priv = IrcSessionPrivate::get(d->session); priv->setConnected(connected); } void IrcProtocol::setNick(const QString& nick) { Q_D(IrcProtocol); IrcSessionPrivate* priv = IrcSessionPrivate::get(d->session); priv->setNick(nick); } void IrcProtocol::setInfo(const QHash<QString, QString>& info) { Q_D(IrcProtocol); IrcSessionPrivate* priv = IrcSessionPrivate::get(d->session); priv->setInfo(info); } void IrcProtocol::receiveMessage(IrcMessage* message) { Q_D(IrcProtocol); IrcSessionPrivate* priv = IrcSessionPrivate::get(d->session); priv->receiveMessage(message); }
/* * Copyright (C) 2008-2013 The Communi Project * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. */ #include "ircprotocol.h" #include "ircsession_p.h" #include "ircsessioninfo.h" #include "ircmessagebuilder_p.h" #include "ircsession.h" #include "ircmessage.h" #include "irccommand.h" #include "irc.h" #include <QDebug> class IrcProtocolPrivate { Q_DECLARE_PUBLIC(IrcProtocol) public: IrcProtocolPrivate(IrcProtocol* protocol); void readLines(const QByteArray& delimiter); void processLine(const QByteArray& line); void handleNumericMessage(IrcNumericMessage* msg); void handlePrivateMessage(IrcPrivateMessage* msg); void handleCapabilityMessage(IrcCapabilityMessage* msg); IrcProtocol* q_ptr; IrcSession* session; IrcMessageBuilder* builder; QByteArray buffer; QSet<QString> activeCaps; QSet<QString> availableCaps; }; IrcProtocolPrivate::IrcProtocolPrivate(IrcProtocol* protocol) : q_ptr(protocol) { } void IrcProtocolPrivate::readLines(const QByteArray& delimiter) { int i = -1; while ((i = buffer.indexOf(delimiter)) != -1) { QByteArray line = buffer.left(i).trimmed(); buffer = buffer.mid(i + delimiter.length()); if (!line.isEmpty()) processLine(line); } } void IrcProtocolPrivate::processLine(const QByteArray& line) { Q_Q(IrcProtocol); static bool dbg = qgetenv("COMMUNI_DEBUG").toInt(); if (dbg) qDebug() << line; if (line.startsWith("AUTHENTICATE")) { const QList<QByteArray> args = line.split(' '); const bool auth = args.count() == 2 && args.at(1) == "+"; if (auth) q->authenticate(true); if (!session->isConnected()) session->sendData("CAP END"); return; } IrcMessage* msg = IrcMessage::fromData(line, session); if (msg) { msg->setEncoding(session->encoding()); switch (msg->type()) { case IrcMessage::Capability: handleCapabilityMessage(static_cast<IrcCapabilityMessage*>(msg)); break; case IrcMessage::Nick: if (msg->flags() & IrcMessage::Own) q->setNick(static_cast<IrcNickMessage*>(msg)->nick()); break; case IrcMessage::Numeric: handleNumericMessage(static_cast<IrcNumericMessage*>(msg)); break; case IrcMessage::Ping: session->sendRaw("PONG " + static_cast<IrcPingMessage*>(msg)->argument()); break; case IrcMessage::Private: handlePrivateMessage(static_cast<IrcPrivateMessage*>(msg)); break; default: break; } q->receiveMessage(msg); if (msg->type() == IrcMessage::Numeric) builder->processMessage(static_cast<IrcNumericMessage*>(msg)); } } void IrcProtocolPrivate::handleNumericMessage(IrcNumericMessage* msg) { Q_Q(IrcProtocol); switch (msg->code()) { case Irc::RPL_WELCOME: q->setNick(msg->parameters().value(0)); q->setConnected(true); break; case Irc::RPL_ISUPPORT: { QHash<QString, QString> info; foreach (const QString& param, msg->parameters().mid(1)) { QStringList keyValue = param.split("=", QString::SkipEmptyParts); info.insert(keyValue.value(0), keyValue.value(1)); } q->setInfo(info); break; } case Irc::ERR_NICKNAMEINUSE: case Irc::ERR_NICKCOLLISION: { QString alternate; emit session->nickNameReserved(&alternate); if (!alternate.isEmpty()) session->setNickName(alternate); break; } default: break; } } void IrcProtocolPrivate::handlePrivateMessage(IrcPrivateMessage* msg) { if (msg->isRequest()) { IrcCommand* reply = session->createCtcpReply(msg); if (reply) session->sendCommand(reply); } } static void handleCapability(QSet<QString>* caps, const QString& cap) { Q_ASSERT(caps); if (cap.startsWith(QLatin1Char('-')) || cap.startsWith(QLatin1Char('='))) caps->remove(cap.mid(1)); else if (cap.startsWith(QLatin1Char('~'))) caps->insert(cap.mid(1)); else caps->insert(cap); } void IrcProtocolPrivate::handleCapabilityMessage(IrcCapabilityMessage* msg) { Q_Q(IrcProtocol); const bool connected = session->isConnected(); const QString subCommand = msg->subCommand(); if (subCommand == "LS") { foreach (const QString& cap, msg->capabilities()) handleCapability(&availableCaps, cap); if (!connected) { const QStringList params = msg->parameters(); if (params.value(params.count() - 1) != QLatin1String("*")) { QStringList request; emit session->capabilities(availableCaps.toList(), &request); if (!request.isEmpty()) { session->sendCommand(IrcCommand::createCapability("REQ", request)); } else { q->authenticate(false); session->sendData("CAP END"); } } } } else if (subCommand == "ACK" || subCommand == "NAK") { bool auth = false; if (subCommand == "ACK") { foreach (const QString& cap, msg->capabilities()) { handleCapability(&activeCaps, cap); if (cap == "sasl") auth = session->sendData("AUTHENTICATE PLAIN"); // TODO: methods } } if (!connected && !auth) { q->authenticate(false); session->sendData("CAP END"); } } } IrcProtocol::IrcProtocol(IrcSession* session) : QObject(session), d_ptr(new IrcProtocolPrivate(this)) { Q_D(IrcProtocol); d->session = session; d->builder = new IrcMessageBuilder(session); connect(d->builder, SIGNAL(messageReceived(IrcMessage*)), this, SLOT(receiveMessage(IrcMessage*))); } IrcProtocol::~IrcProtocol() { Q_D(IrcProtocol); delete d->builder; } IrcSession* IrcProtocol::session() const { Q_D(const IrcProtocol); return d->session; } QAbstractSocket* IrcProtocol::socket() const { Q_D(const IrcProtocol); return d->session->socket(); } void IrcProtocol::open() { Q_D(IrcProtocol); const bool secure = d->session->isSecure(); if (secure) QMetaObject::invokeMethod(socket(), "startClientEncryption"); d->activeCaps.clear(); d->availableCaps.clear(); // Send CAP LS first; if the server understands it this will // temporarily pause the handshake until CAP END is sent, so we // know whether the server supports the CAP extension. d->session->sendData("CAP LS"); d->session->sendCommand(IrcCommand::createNick(d->session->nickName())); d->session->sendRaw(QString("USER %1 hostname servername :%2").arg(d->session->userName(), d->session->realName())); } void IrcProtocol::authenticate(bool secure) { Q_D(IrcProtocol); QString passwd; emit d->session->password(&passwd); if (!passwd.isEmpty()) { if (secure) { const QByteArray userName = d->session->userName().toUtf8(); const QByteArray data = userName + '\0' + userName + '\0' + passwd.toUtf8(); d->session->sendData("AUTHENTICATE " + data.toBase64()); } else { d->session->sendRaw(QString("PASS %1").arg(passwd)); } } } void IrcProtocol::read() { Q_D(IrcProtocol); d->buffer += socket()->readAll(); // try reading RFC compliant message lines first d->readLines("\r\n"); // fall back to RFC incompliant lines... d->readLines("\n"); } bool IrcProtocol::write(const QByteArray& data) { return socket()->write(data + QByteArray("\r\n")) != -1; } QStringList IrcProtocol::availableCapabilities() const { Q_D(const IrcProtocol); return d->availableCaps.toList(); } QStringList IrcProtocol::activeCapabilities() const { Q_D(const IrcProtocol); return d->activeCaps.toList(); } void IrcProtocol::setActive(bool active) { Q_D(IrcProtocol); IrcSessionPrivate* priv = IrcSessionPrivate::get(d->session); priv->setActive(active); } void IrcProtocol::setConnected(bool connected) { Q_D(IrcProtocol); IrcSessionPrivate* priv = IrcSessionPrivate::get(d->session); priv->setConnected(connected); } void IrcProtocol::setNick(const QString& nick) { Q_D(IrcProtocol); IrcSessionPrivate* priv = IrcSessionPrivate::get(d->session); priv->setNick(nick); } void IrcProtocol::setInfo(const QHash<QString, QString>& info) { Q_D(IrcProtocol); IrcSessionPrivate* priv = IrcSessionPrivate::get(d->session); priv->setInfo(info); } void IrcProtocol::receiveMessage(IrcMessage* message) { Q_D(IrcProtocol); IrcSessionPrivate* priv = IrcSessionPrivate::get(d->session); priv->receiveMessage(message); }
Fix #14: SASL over non-SSL connection
Fix #14: SASL over non-SSL connection
C++
bsd-3-clause
jpnurmi/libcommuni,jpnurmi/libcommuni,communi/libcommuni,communi/libcommuni
5974d8300e322b821212711eb83e9afa3816de7a
common/phys_trans/mpitransport.cc
common/phys_trans/mpitransport.cc
#include "mpitransport.h" #include "lock.h" #include "log.h" #include "mpi.h" #include "config.h" #define LOG_DEFAULT_RANK m_core_id #define LOG_DEFAULT_MODULE TRANSPORT #include <iostream> using namespace std; #ifdef PHYS_TRANS_USE_LOCKS Lock* Transport::pt_lock; #define PT_LOCK() \ assert(Transport::pt_lock); \ ScopedLock __scopedLock(*Transport::pt_lock); #else #define PT_LOCK() { } #endif void Transport::ptFinish() { LOG_PRINT_EXPLICIT(-1, TRANSPORT, "Entering finish"); int err_code; err_code = MPI_Finalize(); LOG_ASSERT_ERROR_EXPLICIT(err_code == MPI_SUCCESS, -1, TRANSPORT, "ptFinish : MPI_Finalize fail."); LOG_PRINT_EXPLICIT(-1, TRANSPORT, "Exiting finish"); } void Transport::ptBarrier() { // FIXME: This is potentially dangerous, but I don't see a way // around it using MPI_Barrier. If other threads are waiting on // this process (say, for shared memory response) in order to reach // this barrier, we will deadlock. // Correct implementation should probably manually implement a // barrier via broadcast messages and counters. // - NZB PT_LOCK(); LOG_PRINT_EXPLICIT(-1, TRANSPORT, "Entering barrier"); int err_code; err_code = MPI_Barrier(MPI_COMM_WORLD); LOG_ASSERT_ERROR_EXPLICIT(err_code == MPI_SUCCESS, -1, TRANSPORT, "ptBarrier : MPI_Barrier fail."); LOG_PRINT_EXPLICIT(-1, TRANSPORT, "Exiting barrier"); } // This routine should be executed once in each process void Transport::ptGlobalInit() { int err_code; SInt32 rank; #ifdef PHYS_TRANS_USE_LOCKS // initialize global phys trans lock pt_lock = Lock::create(); #endif //***** Initialize MPI *****// // NOTE: MPI barfs if I call MPI_Init_thread with MPI_THREAD_MULTIPLE // in a non-threaded process. I think this is a bug but I'll work // around it for now. SInt32 required, provided; if (g_config->getProcessCount() > 1) { required = MPI_THREAD_MULTIPLE; } else { required = MPI_THREAD_SINGLE; } err_code = MPI_Init_thread(NULL, NULL, required, &provided); LOG_ASSERT_ERROR_EXPLICIT(err_code == MPI_SUCCESS, -1, TRANSPORT, "ptRecv : MPI_Get_count fail."); assert(provided >= required); //***** Fill in g_config with values that we are responsible for *****// err_code = MPI_Comm_rank(MPI_COMM_WORLD, &rank); LOG_ASSERT_ERROR_EXPLICIT(err_code == MPI_SUCCESS, -1, TRANSPORT, "ptProcessNum : MPI_Comm_rank fail."); g_config->setProcessNum(rank); LOG_PRINT_EXPLICIT(-1, TRANSPORT, "Process number set to %i", g_config->getCurrentProcessNum()); } // This routine should be executed once in each thread Transport::Transport(SInt32 core_id) : m_core_id(core_id) { } SInt32 Transport::ptSend(SInt32 receiver, void *buffer, SInt32 size) { int err_code; // Notes: // - The data is sent using MPI_BYTE so that MPI won't do any conversions. // - We use the receiver ID as the tag so that messages can be // demultiplexed automatically by MPI in the receiving process. // UInt32 dest_proc = g_config->getProcessNumForCore(receiver); LOG_PRINT("sending msg -- from comm id: %i, size: %i, dest recvr: %d dest proc: %i", m_core_id, size, receiver, dest_proc); PT_LOCK(); err_code = MPI_Send(buffer, size, MPI_BYTE, dest_proc, receiver, MPI_COMM_WORLD); LOG_ASSERT_ERROR(err_code == MPI_SUCCESS, "ptSend : MPI_Send fail."); LOG_PRINT("message sent"); // FIXME: Why do we need to return the size? return size; } void* Transport::ptRecv() { MPI_Status status; SInt32 pkt_size, source; Byte* buffer; int err_code; LOG_PRINT("attempting receive -- m_core_id: %i", m_core_id); // Probe for a message from any source but with our ID tag. #ifdef PHYS_TRANS_USE_LOCKS // When using phys_trans locks, we spin. while (true) { SInt32 flag; pt_lock->acquire(); // this is essentially ptQuery without the locks err_code = MPI_Iprobe(MPI_ANY_SOURCE, m_core_id, MPI_COMM_WORLD, &flag, &status); LOG_ASSERT_ERROR(err_code == MPI_SUCCESS, "ptRecv : MPI_Iprobe fail."); // if a message is ready, leave the loop _without_ releasing the lock if (flag != 0) break; // otherwise, release and yield pt_lock->release(); sched_yield(); } #else // Otherwise, blocking MPI call. err_code = MPI_Probe(MPI_ANY_SOURCE, m_core_id, MPI_COMM_WORLD, &status); LOG_ASSERT_ERROR(err_code == MPI_SUCCESS, "ptRecv : MPI_Probe fail."); #endif // Now we know that there is a message ready, check status to see how // big it is and who the source is. err_code = MPI_Get_count(&status, MPI_BYTE, &pkt_size); LOG_ASSERT_ERROR(err_code == MPI_SUCCESS, "ptRecv : MPI_Get_count fail."); assert(status.MPI_SOURCE != MPI_UNDEFINED); source = status.MPI_SOURCE; // Allocate a buffer for the incoming message buffer = new Byte[pkt_size]; LOG_PRINT("msg found -- m_core_id: %i, size: %i, source: %i", m_core_id, pkt_size, source); // We need to make sure the source here is the same as the one returned // by the call to Probe above. Otherwise, we might get a message from // a different sender that could have a different size. err_code = MPI_Recv(buffer, pkt_size, MPI_BYTE, source, m_core_id, MPI_COMM_WORLD, &status); LOG_ASSERT_ERROR(err_code == MPI_SUCCESS, "ptRecv : MPI_Recv fail."); LOG_PRINT("msg received"); #ifdef PHYS_TRANS_USE_LOCKS pt_lock->release(); #endif return buffer; // NOTE: the caller should free the buffer when it's finished with it } Boolean Transport::ptQuery() { SInt32 flag; MPI_Status status; int err_code; PT_LOCK(); // Probe for a message from any source but with our ID tag err_code = MPI_Iprobe(MPI_ANY_SOURCE, m_core_id, MPI_COMM_WORLD, &flag, &status); LOG_ASSERT_ERROR(err_code == MPI_SUCCESS, "ptQuery : MPI_Iprobe fail."); // flag == 0 indicates that no message is waiting return (flag != 0); }
#include "mpitransport.h" #include "lock.h" #include "log.h" #include "mpi.h" #include "config.h" #define LOG_DEFAULT_RANK m_core_id #define LOG_DEFAULT_MODULE TRANSPORT #include <iostream> using namespace std; #ifdef PHYS_TRANS_USE_LOCKS Lock* Transport::pt_lock; #define PT_LOCK() \ assert(Transport::pt_lock); \ ScopedLock __scopedLock(*Transport::pt_lock); #else #define PT_LOCK() { } #endif void Transport::ptFinish() { LOG_PRINT_EXPLICIT(-1, TRANSPORT, "Entering finish"); int err_code; err_code = MPI_Finalize(); LOG_ASSERT_ERROR_EXPLICIT(err_code == MPI_SUCCESS, -1, TRANSPORT, "ptFinish : MPI_Finalize fail."); LOG_PRINT_EXPLICIT(-1, TRANSPORT, "Exiting finish"); } void Transport::ptBarrier() { // FIXME: This is potentially dangerous, but I don't see a way // around it using MPI_Barrier. If other threads are waiting on // this process (say, for shared memory response) in order to reach // this barrier, we will deadlock. // Correct implementation should probably manually implement a // barrier via broadcast messages and counters. // - NZB PT_LOCK(); LOG_PRINT_EXPLICIT(-1, TRANSPORT, "Entering barrier"); int err_code; err_code = MPI_Barrier(MPI_COMM_WORLD); LOG_ASSERT_ERROR_EXPLICIT(err_code == MPI_SUCCESS, -1, TRANSPORT, "ptBarrier : MPI_Barrier fail."); LOG_PRINT_EXPLICIT(-1, TRANSPORT, "Exiting barrier"); } // This routine should be executed once in each process void Transport::ptGlobalInit() { int err_code; SInt32 rank; #ifdef PHYS_TRANS_USE_LOCKS // initialize global phys trans lock pt_lock = Lock::create(); #endif //***** Initialize MPI *****// // NOTE: MPI barfs if I call MPI_Init_thread with MPI_THREAD_MULTIPLE // in a non-threaded process. I think this is a bug but I'll work // around it for now. SInt32 required, provided; if (g_config->getProcessCount() > 1) { required = MPI_THREAD_MULTIPLE; } else { required = MPI_THREAD_SINGLE; } err_code = MPI_Init_thread(NULL, NULL, required, &provided); LOG_ASSERT_ERROR_EXPLICIT(err_code == MPI_SUCCESS, -1, TRANSPORT, "ptRecv : MPI_Get_count fail."); assert(provided >= required); //***** Fill in g_config with values that we are responsible for *****// err_code = MPI_Comm_rank(MPI_COMM_WORLD, &rank); LOG_ASSERT_ERROR_EXPLICIT(err_code == MPI_SUCCESS, -1, TRANSPORT, "ptProcessNum : MPI_Comm_rank fail."); g_config->setProcessNum(rank); LOG_PRINT_EXPLICIT(-1, TRANSPORT, "Process number set to %i", g_config->getCurrentProcessNum()); } // This routine should be executed once in each thread Transport::Transport(SInt32 core_id) : m_core_id(core_id) { } SInt32 Transport::ptSend(SInt32 dest_id, void *buffer, SInt32 size) { int err_code; // Notes: // - The data is sent using MPI_BYTE so that MPI won't do any conversions. // - We use the receiver ID as the tag so that messages can be // demultiplexed automatically by MPI in the receiving process. // UInt32 dest_proc = g_config->getProcessNumForCore(dest_id); LOG_PRINT("sending msg -- from core_id: %i, size: %i, dest core_id: %d, dest proc: %i", m_core_id, size, dest_id, dest_proc); PT_LOCK(); err_code = MPI_Send(buffer, size, MPI_BYTE, dest_proc, dest_id, MPI_COMM_WORLD); LOG_ASSERT_ERROR(err_code == MPI_SUCCESS, "ptSend : MPI_Send fail."); LOG_PRINT("message sent"); // FIXME: Why do we need to return the size? return size; } void* Transport::ptRecv() { MPI_Status status; SInt32 pkt_size, source; Byte* buffer; int err_code; LOG_PRINT("attempting receive -- core_id: %i", m_core_id); // Probe for a message from any source but with our ID tag. #ifdef PHYS_TRANS_USE_LOCKS // When using phys_trans locks, we spin. while (true) { SInt32 flag; pt_lock->acquire(); // this is essentially ptQuery without the locks err_code = MPI_Iprobe(MPI_ANY_SOURCE, m_core_id, MPI_COMM_WORLD, &flag, &status); LOG_ASSERT_ERROR(err_code == MPI_SUCCESS, "ptRecv : MPI_Iprobe fail."); // if a message is ready, leave the loop _without_ releasing the lock if (flag != 0) break; // otherwise, release and yield pt_lock->release(); sched_yield(); } #else // Otherwise, blocking MPI call. err_code = MPI_Probe(MPI_ANY_SOURCE, m_core_id, MPI_COMM_WORLD, &status); LOG_ASSERT_ERROR(err_code == MPI_SUCCESS, "ptRecv : MPI_Probe fail."); #endif // Now we know that there is a message ready, check status to see how // big it is and who the source is. err_code = MPI_Get_count(&status, MPI_BYTE, &pkt_size); LOG_ASSERT_ERROR(err_code == MPI_SUCCESS, "ptRecv : MPI_Get_count fail."); assert(status.MPI_SOURCE != MPI_UNDEFINED); source = status.MPI_SOURCE; // Allocate a buffer for the incoming message buffer = new Byte[pkt_size]; LOG_PRINT("msg found -- core_id: %i, size: %i, source: %i", m_core_id, pkt_size, source); // We need to make sure the source here is the same as the one returned // by the call to Probe above. Otherwise, we might get a message from // a different sender that could have a different size. err_code = MPI_Recv(buffer, pkt_size, MPI_BYTE, source, m_core_id, MPI_COMM_WORLD, &status); LOG_ASSERT_ERROR(err_code == MPI_SUCCESS, "ptRecv : MPI_Recv fail."); LOG_PRINT("msg received"); #ifdef PHYS_TRANS_USE_LOCKS pt_lock->release(); #endif return buffer; // NOTE: the caller should free the buffer when it's finished with it } Boolean Transport::ptQuery() { SInt32 flag; MPI_Status status; int err_code; PT_LOCK(); // Probe for a message from any source but with our ID tag err_code = MPI_Iprobe(MPI_ANY_SOURCE, m_core_id, MPI_COMM_WORLD, &flag, &status); LOG_ASSERT_ERROR(err_code == MPI_SUCCESS, "ptQuery : MPI_Iprobe fail."); // flag == 0 indicates that no message is waiting return (flag != 0); }
Clean up log messages, change var name in ptSend.
[trans] Clean up log messages, change var name in ptSend.
C++
mit
8l/Graphite,mit-carbon/Graphite,mit-carbon/Graphite,victorisildur/Graphite,victorisildur/Graphite,victorisildur/Graphite,nkawahara/Graphite,fhijaz/Graphite,nkawahara/Graphite,mit-carbon/Graphite-Cycle-Level,8l/Graphite,fhijaz/Graphite,fhijaz/Graphite,nkawahara/Graphite,mit-carbon/Graphite,victorisildur/Graphite,fhijaz/Graphite,mit-carbon/Graphite-Cycle-Level,nkawahara/Graphite,8l/Graphite,mit-carbon/Graphite-Cycle-Level,8l/Graphite,mit-carbon/Graphite-Cycle-Level,mit-carbon/Graphite
9b97ca197de6ad8ddcd0bade66f1f2fc5dab7361
common/vp9_header_parser_tests.cc
common/vp9_header_parser_tests.cc
// Copyright (c) 2016 The WebM project authors. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. #include "common/vp9_header_parser.h" #include <string> #include "gtest/gtest.h" #include "common/hdr_util.h" #include "mkvparser/mkvparser.h" #include "mkvparser/mkvreader.h" #include "testing/test_util.h" namespace { class Vp9HeaderParserTests : public ::testing::Test { public: Vp9HeaderParserTests() : is_reader_open_(false), segment_(NULL) {} ~Vp9HeaderParserTests() override { CloseReader(); if (segment_ != NULL) { delete segment_; segment_ = NULL; } } void CloseReader() { if (is_reader_open_) { reader_.Close(); } is_reader_open_ = false; } void CreateAndLoadSegment(const std::string& filename, int expected_doc_type_ver) { filename_ = test::GetTestFilePath(filename); ASSERT_EQ(0, reader_.Open(filename_.c_str())); is_reader_open_ = true; pos_ = 0; mkvparser::EBMLHeader ebml_header; ebml_header.Parse(&reader_, pos_); ASSERT_EQ(1, ebml_header.m_version); ASSERT_EQ(1, ebml_header.m_readVersion); ASSERT_STREQ("webm", ebml_header.m_docType); ASSERT_EQ(expected_doc_type_ver, ebml_header.m_docTypeVersion); ASSERT_EQ(2, ebml_header.m_docTypeReadVersion); ASSERT_EQ(0, mkvparser::Segment::CreateInstance(&reader_, pos_, segment_)); ASSERT_FALSE(HasFailure()); ASSERT_GE(0, segment_->Load()); } void CreateAndLoadSegment(const std::string& filename) { CreateAndLoadSegment(filename, 4); } void ProcessTheFrames() { unsigned char* data = NULL; size_t data_len = 0; const mkvparser::Tracks* const parser_tracks = segment_->GetTracks(); ASSERT_TRUE(parser_tracks != NULL); const mkvparser::Cluster* cluster = segment_->GetFirst(); ASSERT_TRUE(cluster != NULL); while ((cluster != NULL) && !cluster->EOS()) { const mkvparser::BlockEntry* block_entry; long status = cluster->GetFirst(block_entry); // NOLINT ASSERT_EQ(0, status); while ((block_entry != NULL) && !block_entry->EOS()) { const mkvparser::Block* const block = block_entry->GetBlock(); ASSERT_TRUE(block != NULL); const long long trackNum = block->GetTrackNumber(); // NOLINT const mkvparser::Track* const parser_track = parser_tracks->GetTrackByNumber( static_cast<unsigned long>(trackNum)); // NOLINT ASSERT_TRUE(parser_track != NULL); const long long track_type = parser_track->GetType(); // NOLINT if (track_type == mkvparser::Track::kVideo) { const int frame_count = block->GetFrameCount(); for (int i = 0; i < frame_count; ++i) { const mkvparser::Block::Frame& frame = block->GetFrame(i); if (static_cast<size_t>(frame.len) > data_len) { delete[] data; data = new unsigned char[frame.len]; ASSERT_TRUE(data != NULL); data_len = static_cast<size_t>(frame.len); } ASSERT_FALSE(frame.Read(&reader_, data)); parser_.SetFrame(data, data_len); parser_.ParseUncompressedHeader(); } } status = cluster->GetNext(block_entry, block_entry); ASSERT_EQ(0, status); } cluster = segment_->GetNext(cluster); } delete[] data; } protected: mkvparser::MkvReader reader_; bool is_reader_open_; mkvparser::Segment* segment_; std::string filename_; long long pos_; // NOLINT vp9_parser::Vp9HeaderParser parser_; }; TEST_F(Vp9HeaderParserTests, VideoOnlyFile) { CreateAndLoadSegment("test_stereo_left_right.webm"); ProcessTheFrames(); EXPECT_EQ(256, parser_.width()); EXPECT_EQ(144, parser_.height()); EXPECT_EQ(1, parser_.column_tiles()); EXPECT_EQ(0, parser_.frame_parallel_mode()); } TEST_F(Vp9HeaderParserTests, Muxed) { CreateAndLoadSegment("bbb_480p_vp9_opus_1second.webm", 4); ProcessTheFrames(); EXPECT_EQ(854, parser_.width()); EXPECT_EQ(480, parser_.height()); EXPECT_EQ(2, parser_.column_tiles()); EXPECT_EQ(1, parser_.frame_parallel_mode()); } } // namespace int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
// Copyright (c) 2016 The WebM project authors. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. #include "common/vp9_header_parser.h" #include <string> #include "gtest/gtest.h" #include "common/hdr_util.h" #include "mkvparser/mkvparser.h" #include "mkvparser/mkvreader.h" #include "testing/test_util.h" namespace { class Vp9HeaderParserTests : public ::testing::Test { public: Vp9HeaderParserTests() : is_reader_open_(false), segment_(NULL) {} ~Vp9HeaderParserTests() override { CloseReader(); if (segment_ != NULL) { delete segment_; segment_ = NULL; } } void CloseReader() { if (is_reader_open_) { reader_.Close(); } is_reader_open_ = false; } void CreateAndLoadSegment(const std::string& filename, int expected_doc_type_ver) { filename_ = test::GetTestFilePath(filename); ASSERT_EQ(0, reader_.Open(filename_.c_str())); is_reader_open_ = true; pos_ = 0; mkvparser::EBMLHeader ebml_header; ebml_header.Parse(&reader_, pos_); ASSERT_EQ(1, ebml_header.m_version); ASSERT_EQ(1, ebml_header.m_readVersion); ASSERT_STREQ("webm", ebml_header.m_docType); ASSERT_EQ(expected_doc_type_ver, ebml_header.m_docTypeVersion); ASSERT_EQ(2, ebml_header.m_docTypeReadVersion); ASSERT_EQ(0, mkvparser::Segment::CreateInstance(&reader_, pos_, segment_)); ASSERT_FALSE(HasFailure()); ASSERT_GE(0, segment_->Load()); } void CreateAndLoadSegment(const std::string& filename) { CreateAndLoadSegment(filename, 4); } void ProcessTheFrames(bool invalid_bitstream) { unsigned char* data = NULL; size_t data_len = 0; const mkvparser::Tracks* const parser_tracks = segment_->GetTracks(); ASSERT_TRUE(parser_tracks != NULL); const mkvparser::Cluster* cluster = segment_->GetFirst(); ASSERT_TRUE(cluster != NULL); while ((cluster != NULL) && !cluster->EOS()) { const mkvparser::BlockEntry* block_entry; long status = cluster->GetFirst(block_entry); // NOLINT ASSERT_EQ(0, status); while ((block_entry != NULL) && !block_entry->EOS()) { const mkvparser::Block* const block = block_entry->GetBlock(); ASSERT_TRUE(block != NULL); const long long trackNum = block->GetTrackNumber(); // NOLINT const mkvparser::Track* const parser_track = parser_tracks->GetTrackByNumber( static_cast<unsigned long>(trackNum)); // NOLINT ASSERT_TRUE(parser_track != NULL); const long long track_type = parser_track->GetType(); // NOLINT if (track_type == mkvparser::Track::kVideo) { const int frame_count = block->GetFrameCount(); for (int i = 0; i < frame_count; ++i) { const mkvparser::Block::Frame& frame = block->GetFrame(i); if (static_cast<size_t>(frame.len) > data_len) { delete[] data; data = new unsigned char[frame.len]; ASSERT_TRUE(data != NULL); data_len = static_cast<size_t>(frame.len); } ASSERT_FALSE(frame.Read(&reader_, data)); parser_.SetFrame(data, data_len); ASSERT_EQ(parser_.ParseUncompressedHeader(), !invalid_bitstream); } } status = cluster->GetNext(block_entry, block_entry); ASSERT_EQ(0, status); } cluster = segment_->GetNext(cluster); } delete[] data; } protected: mkvparser::MkvReader reader_; bool is_reader_open_; mkvparser::Segment* segment_; std::string filename_; long long pos_; // NOLINT vp9_parser::Vp9HeaderParser parser_; }; TEST_F(Vp9HeaderParserTests, VideoOnlyFile) { ASSERT_NO_FATAL_FAILURE(CreateAndLoadSegment("test_stereo_left_right.webm")); ProcessTheFrames(false); EXPECT_EQ(256, parser_.width()); EXPECT_EQ(144, parser_.height()); EXPECT_EQ(1, parser_.column_tiles()); EXPECT_EQ(0, parser_.frame_parallel_mode()); } TEST_F(Vp9HeaderParserTests, Muxed) { ASSERT_NO_FATAL_FAILURE( CreateAndLoadSegment("bbb_480p_vp9_opus_1second.webm", 4)); ProcessTheFrames(false); EXPECT_EQ(854, parser_.width()); EXPECT_EQ(480, parser_.height()); EXPECT_EQ(2, parser_.column_tiles()); EXPECT_EQ(1, parser_.frame_parallel_mode()); } } // namespace int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
check parser return
vp9_header_parser_tests: check parser return ensure ParseUncompressedHeader() succeeds with valid bitstreams Change-Id: I1e3900fc08f3b6b2e86bc2f59fd8fd96bc26ad0f
C++
bsd-3-clause
webmproject/libwebm,webmproject/libwebm,webmproject/libwebm
4a1cd3dab6ae3234700efe161eb881d3bf69f2bf
grit_core/src/linux/KeyboardX11.c++
grit_core/src/linux/KeyboardX11.c++
/* Copyright (c) David Cunningham and the Grit Game Engine project 2010 * * 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 <iostream> #include <sstream> #include "KeyboardX11.h" #include "../CentralisedLog.h" #include "../unicode_util.h" KeyboardX11::KeyboardX11 (size_t window) : focussed(true) { #define MAP_KEY(xk,k) myKeyMap.insert(std::make_pair(xk,k)) // all the keys for which XLookupString followed by XKeySymToString would not return // what we want // these guys return the ascii control code MAP_KEY(XK_space, "Space"); MAP_KEY(XK_BackSpace, "BackSpace"); MAP_KEY(XK_Delete, "Delete"); MAP_KEY(XK_Tab, "Tab"); MAP_KEY(XK_Return, "Return"); MAP_KEY(XK_Escape, "Escape"); MAP_KEY(XK_Caps_Lock, "CapsLock"); MAP_KEY(XK_Page_Up, "PageUp"); MAP_KEY(XK_Page_Down, "PageDown"); MAP_KEY(XK_Num_Lock, "NumLock"); MAP_KEY(XK_Print, "SysRq"); MAP_KEY(XK_Scroll_Lock, "Scroll"); MAP_KEY(XK_Control_L, "Ctrl"); MAP_KEY(XK_Control_R, "Ctrl"); MAP_KEY(XK_Shift_R, "Shift"); MAP_KEY(XK_Shift_L, "Shift"); MAP_KEY(XK_Alt_R, "Alt"); MAP_KEY(XK_Alt_L, "Alt"); MAP_KEY(XK_Super_L, "LWin"); MAP_KEY(XK_Super_R, "RWin"); //Keypad MAP_KEY(XK_KP_0, "NUMPAD0"); MAP_KEY(XK_KP_1, "NUMPAD1"); MAP_KEY(XK_KP_2, "NUMPAD2"); MAP_KEY(XK_KP_3, "NUMPAD3"); MAP_KEY(XK_KP_4, "NUMPAD4"); MAP_KEY(XK_KP_5, "NUMPAD5"); MAP_KEY(XK_KP_6, "NUMPAD6"); MAP_KEY(XK_KP_7, "NUMPAD7"); MAP_KEY(XK_KP_8, "NUMPAD8"); MAP_KEY(XK_KP_9, "NUMPAD9"); MAP_KEY(XK_KP_Add, "NUMPAD+"); MAP_KEY(XK_KP_Subtract, "NUMPAD-"); MAP_KEY(XK_KP_Decimal, "NUMPAD."); MAP_KEY(XK_KP_Equal, "NUMPAD="); MAP_KEY(XK_KP_Divide, "NUMPAD/"); MAP_KEY(XK_KP_Multiply, "NUMPAD*"); MAP_KEY(XK_KP_Enter, "NUMPADReturn"); //Keypad with numlock off MAP_KEY(XK_KP_Home, "NUMPAD7"); MAP_KEY(XK_KP_Up, "NUMPAD8"); MAP_KEY(XK_KP_Page_Up, "NUMPAD9"); MAP_KEY(XK_KP_Left, "NUMPAD4"); MAP_KEY(XK_KP_Begin, "NUMPAD5"); MAP_KEY(XK_KP_Right, "NUMPAD6"); MAP_KEY(XK_KP_End, "NUMPAD1"); MAP_KEY(XK_KP_Down, "NUMPAD2"); MAP_KEY(XK_KP_Page_Down, "NUMPAD3"); MAP_KEY(XK_KP_Insert, "NUMPAD0"); MAP_KEY(XK_KP_Delete, "NUMPAD."); //These guys give full names instead of the symbols //but we want to behave the same on windows and linux, so... MAP_KEY(XK_comma, ","); MAP_KEY(XK_period, "."); MAP_KEY(XK_semicolon, ";"); MAP_KEY(XK_slash, "/"); MAP_KEY(XK_backslash, "\\"); MAP_KEY(XK_apostrophe, "'"); MAP_KEY(XK_bracketleft, "["); MAP_KEY(XK_bracketright, "]"); MAP_KEY(XK_minus, "-"); MAP_KEY(XK_equal, "="); MAP_KEY(XK_grave, "`"); win = window; display = XOpenDisplay(0); APP_ASSERT(display); /* im = XOpenIM(display, NULL, NULL, NULL); APP_ASSERT(im); ic = XCreateIC(im); APP_ASSERT(im); */ long event_mask = KeyPressMask | KeyReleaseMask; event_mask |= FocusChangeMask; if (XSelectInput(display, win, event_mask) == BadWindow) { CERR << "calling XSelectInput: BadWindow" << std::endl; app_fatal(); } } KeyboardX11::~KeyboardX11 (void) { if(display) { getPresses(); //if (ic) XDestroyIC(ic); //if (im) XCloseIM(im); XCloseDisplay(display); } } void KeyboardX11::add_key (Keyboard::Presses &keys, XEvent ev, int kind) { const char *prefix[] = { "-", "=", "+" }; std::string str = prefix[kind+1]; std::string keystr; // There is a list of specific keysyms that I want to map to strings myself KeySym key = XLookupKeysym(&ev.xkey, 0); if (myKeyMap.find(key) != myKeyMap.end()) { keystr = myKeyMap[key]; } else { keystr = XKeysymToString(key); } str += keystr; bool contains = currentlyPressed.find(keystr)!=currentlyPressed.end(); switch (kind) { case -1: // release if (!contains) return; currentlyPressed.erase(keystr); break; case 0: // repeat if (!contains) { add_key(keys, ev, 1); return; } break; case 1: // press if (contains) return; currentlyPressed.insert(keystr); break; } if (verbose) { CLOG << "X key: " << str << std::endl; } keys.push_back(str); // TODO: advanced input method / context for non-european languages // use Xutf8LookupString // or use an existing system like gtk char buf[1024]; int r = XLookupString(&ev.xkey, buf, sizeof buf, NULL, NULL); // don't want text events unless the key is being pressed or repeated if (r && kind >= 0) { APP_ASSERT(r==1); // returns latin1 which is a subset of unicode unsigned long codepoint = (unsigned char)buf[0]; // do not want non-printable text coming from keyboard, we have the // above system for those keys if ((codepoint>=0x20 && codepoint<0x7f) || codepoint>=0xa0) { str = ":"; // just encode into utf8 and we're done encode_utf8(codepoint, str); if (verbose) { CLOG << "X key text: \"" << str << "\"" << std::endl; } keys.push_back(str); } } } bool KeyboardX11::hasFocus (void) { return focussed; } Keyboard::Presses KeyboardX11::getPresses (void) { Keyboard::Presses r; // collect presses here XEvent event; //Poll x11 for events bool last_was_release = false; KeySym last_key = 0; XEvent last_event; while(XPending(display) > 0) { XNextEvent(display, &event); switch (event.type) { case FocusIn: { focussed = true; last_was_release = false; } break; case FocusOut: { focussed = false; last_was_release = false; } break; case KeyRelease: { if (last_was_release) { add_key(r, last_event, -1); } KeySym key = XLookupKeysym(&event.xkey, 0); last_key = key; last_event = event; last_was_release = true; } break; case KeyPress: { KeySym key = XLookupKeysym(&event.xkey, 0); if (last_was_release) { if (last_key!=key) { // different key, add both add_key(r, last_event, -1); add_key(r, event, 1); } else { add_key(r, event, 0); } } else { add_key(r, event, 1); } last_was_release = false; } break; } } if (last_was_release) { add_key(r, last_event, -1); } for (Presses::iterator i=keysToFlush.begin(), i_=keysToFlush.end() ; i!=i_ ; ++i) { if (currentlyPressed.find(*i)!=currentlyPressed.end()) { r.push_back("-"+*i); currentlyPressed.erase(*i); if (verbose) { CLOG << "X keyboard: flushed: " << *i << std::endl; } } } keysToFlush.clear(); if (fullFlushRequested) { // Any key we currently recognise as being held // down is "released" (note a repeating key // will still repeat upon refocus) typedef std::set<Press>::iterator I; for (I i=currentlyPressed.begin(),i_=currentlyPressed.end() ; i!=i_ ; ++i) { r.push_back("-"+*i); } currentlyPressed.clear(); fullFlushRequested = false; if (verbose) { CLOG << "X keyboard: all flushed" << std::endl; } } return r; } // vim: shiftwidth=8:tabstop=8:expandtab
/* Copyright (c) David Cunningham and the Grit Game Engine project 2010 * * 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 <iostream> #include <sstream> #include "KeyboardX11.h" #include "../CentralisedLog.h" #include "../unicode_util.h" KeyboardX11::KeyboardX11 (size_t window) : focussed(true) { #define MAP_KEY(xk,k) myKeyMap.insert(std::make_pair(xk,k)) // all the keys for which XLookupString followed by XKeySymToString would not return // what we want // these guys return the ascii control code MAP_KEY(XK_space, "Space"); MAP_KEY(XK_BackSpace, "BackSpace"); MAP_KEY(XK_Delete, "Delete"); MAP_KEY(XK_Tab, "Tab"); MAP_KEY(XK_Return, "Return"); MAP_KEY(XK_Escape, "Escape"); MAP_KEY(XK_Caps_Lock, "CapsLock"); MAP_KEY(XK_Page_Up, "PageUp"); MAP_KEY(XK_Page_Down, "PageDown"); MAP_KEY(XK_Num_Lock, "NumLock"); MAP_KEY(XK_Print, "SysRq"); MAP_KEY(XK_Scroll_Lock, "Scroll"); MAP_KEY(XK_Control_L, "Ctrl"); MAP_KEY(XK_Control_R, "Ctrl"); MAP_KEY(XK_Shift_R, "Shift"); MAP_KEY(XK_Shift_L, "Shift"); MAP_KEY(XK_Alt_R, "Alt"); MAP_KEY(XK_Alt_L, "Alt"); MAP_KEY(XK_Super_L, "LWin"); MAP_KEY(XK_Super_R, "RWin"); //Keypad MAP_KEY(XK_KP_0, "NUMPAD0"); MAP_KEY(XK_KP_1, "NUMPAD1"); MAP_KEY(XK_KP_2, "NUMPAD2"); MAP_KEY(XK_KP_3, "NUMPAD3"); MAP_KEY(XK_KP_4, "NUMPAD4"); MAP_KEY(XK_KP_5, "NUMPAD5"); MAP_KEY(XK_KP_6, "NUMPAD6"); MAP_KEY(XK_KP_7, "NUMPAD7"); MAP_KEY(XK_KP_8, "NUMPAD8"); MAP_KEY(XK_KP_9, "NUMPAD9"); MAP_KEY(XK_KP_Add, "NUMPAD+"); MAP_KEY(XK_KP_Subtract, "NUMPAD-"); MAP_KEY(XK_KP_Decimal, "NUMPAD."); MAP_KEY(XK_KP_Equal, "NUMPAD="); MAP_KEY(XK_KP_Divide, "NUMPAD/"); MAP_KEY(XK_KP_Multiply, "NUMPAD*"); MAP_KEY(XK_KP_Enter, "NUMPADReturn"); //Keypad with numlock off MAP_KEY(XK_KP_Home, "NUMPAD7"); MAP_KEY(XK_KP_Up, "NUMPAD8"); MAP_KEY(XK_KP_Page_Up, "NUMPAD9"); MAP_KEY(XK_KP_Left, "NUMPAD4"); MAP_KEY(XK_KP_Begin, "NUMPAD5"); MAP_KEY(XK_KP_Right, "NUMPAD6"); MAP_KEY(XK_KP_End, "NUMPAD1"); MAP_KEY(XK_KP_Down, "NUMPAD2"); MAP_KEY(XK_KP_Page_Down, "NUMPAD3"); MAP_KEY(XK_KP_Insert, "NUMPAD0"); MAP_KEY(XK_KP_Delete, "NUMPAD."); //These guys give full names instead of the symbols //but we want to behave the same on windows and linux, so... MAP_KEY(XK_comma, ","); MAP_KEY(XK_period, "."); MAP_KEY(XK_semicolon, ";"); MAP_KEY(XK_slash, "/"); MAP_KEY(XK_backslash, "\\"); MAP_KEY(XK_apostrophe, "'"); MAP_KEY(XK_bracketleft, "["); MAP_KEY(XK_bracketright, "]"); MAP_KEY(XK_minus, "-"); MAP_KEY(XK_equal, "="); MAP_KEY(XK_grave, "`"); win = window; display = XOpenDisplay(0); APP_ASSERT(display); /* im = XOpenIM(display, NULL, NULL, NULL); APP_ASSERT(im); ic = XCreateIC(im); APP_ASSERT(im); */ long event_mask = KeyPressMask | KeyReleaseMask; event_mask |= FocusChangeMask; if (XSelectInput(display, win, event_mask) == BadWindow) { CERR << "calling XSelectInput: BadWindow" << std::endl; app_fatal(); } } KeyboardX11::~KeyboardX11 (void) { if(display) { getPresses(); //if (ic) XDestroyIC(ic); //if (im) XCloseIM(im); XCloseDisplay(display); } } void KeyboardX11::add_key (Keyboard::Presses &keys, XEvent ev, int kind) { const char *prefix[] = { "-", "=", "+" }; std::string str = prefix[kind+1]; std::string keystr; // There is a list of specific keysyms that I want to map to strings myself KeySym key = XLookupKeysym(&ev.xkey, 0); if (key == NoSymbol) return; // key is not bound in X if (myKeyMap.find(key) != myKeyMap.end()) { keystr = myKeyMap[key]; } else { keystr = XKeysymToString(key); } str += keystr; bool contains = currentlyPressed.find(keystr)!=currentlyPressed.end(); switch (kind) { case -1: // release if (!contains) return; currentlyPressed.erase(keystr); break; case 0: // repeat if (!contains) { add_key(keys, ev, 1); return; } break; case 1: // press if (contains) return; currentlyPressed.insert(keystr); break; } if (verbose) { CLOG << "X key: " << str << std::endl; } keys.push_back(str); // TODO: advanced input method / context for non-european languages // use Xutf8LookupString // or use an existing system like gtk char buf[1024]; int r = XLookupString(&ev.xkey, buf, sizeof buf, NULL, NULL); // don't want text events unless the key is being pressed or repeated if (r && kind >= 0) { APP_ASSERT(r==1); // returns latin1 which is a subset of unicode unsigned long codepoint = (unsigned char)buf[0]; // do not want non-printable text coming from keyboard, we have the // above system for those keys if ((codepoint>=0x20 && codepoint<0x7f) || codepoint>=0xa0) { str = ":"; // just encode into utf8 and we're done encode_utf8(codepoint, str); if (verbose) { CLOG << "X key text: \"" << str << "\"" << std::endl; } keys.push_back(str); } } } bool KeyboardX11::hasFocus (void) { return focussed; } Keyboard::Presses KeyboardX11::getPresses (void) { Keyboard::Presses r; // collect presses here XEvent event; //Poll x11 for events bool last_was_release = false; KeySym last_key = 0; XEvent last_event; while(XPending(display) > 0) { XNextEvent(display, &event); switch (event.type) { case FocusIn: { focussed = true; last_was_release = false; } break; case FocusOut: { focussed = false; last_was_release = false; } break; case KeyRelease: { if (last_was_release) { add_key(r, last_event, -1); } KeySym key = XLookupKeysym(&event.xkey, 0); last_key = key; last_event = event; last_was_release = true; } break; case KeyPress: { KeySym key = XLookupKeysym(&event.xkey, 0); if (last_was_release) { if (last_key!=key) { // different key, add both add_key(r, last_event, -1); add_key(r, event, 1); } else { add_key(r, event, 0); } } else { add_key(r, event, 1); } last_was_release = false; } break; } } if (last_was_release) { add_key(r, last_event, -1); } for (Presses::iterator i=keysToFlush.begin(), i_=keysToFlush.end() ; i!=i_ ; ++i) { if (currentlyPressed.find(*i)!=currentlyPressed.end()) { r.push_back("-"+*i); currentlyPressed.erase(*i); if (verbose) { CLOG << "X keyboard: flushed: " << *i << std::endl; } } } keysToFlush.clear(); if (fullFlushRequested) { // Any key we currently recognise as being held // down is "released" (note a repeating key // will still repeat upon refocus) typedef std::set<Press>::iterator I; for (I i=currentlyPressed.begin(),i_=currentlyPressed.end() ; i!=i_ ; ++i) { r.push_back("-"+*i); } currentlyPressed.clear(); fullFlushRequested = false; if (verbose) { CLOG << "X keyboard: all flushed" << std::endl; } } return r; } // vim: shiftwidth=8:tabstop=8:expandtab
Fix bug where an unbound (in the OS) key would crash the game
Fix bug where an unbound (in the OS) key would crash the game
C++
mit
grit-engine/grit-engine,sparkprime/grit-engine,sparkprime/grit-engine,grit-engine/grit-engine,sparkprime/grit-engine,grit-engine/grit-engine,grit-engine/grit-engine,sparkprime/grit-engine
11212eb0d1a1587155b424bb56435bab58545029
src/plugins/cpptools/cppfindreferences.cpp
src/plugins/cpptools/cppfindreferences.cpp
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** 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 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://www.qtsoftware.com/contact. ** **************************************************************************/ #include "cppfindreferences.h" #include "cppmodelmanager.h" #include "cpptoolsconstants.h" #include <texteditor/basetexteditor.h> #include <find/searchresultwindow.h> #include <extensionsystem/pluginmanager.h> #include <utils/filesearch.h> #include <coreplugin/progressmanager/progressmanager.h> #include <coreplugin/icore.h> #include <ASTVisitor.h> #include <AST.h> #include <Control.h> #include <Literals.h> #include <TranslationUnit.h> #include <Symbols.h> #include <Names.h> #include <Scope.h> #include <cplusplus/CppDocument.h> #include <cplusplus/ExpressionUnderCursor.h> #include <cplusplus/ResolveExpression.h> #include <cplusplus/Overview.h> #include <cplusplus/TypeOfExpression.h> #include <QtCore/QTime> #include <QtCore/QtConcurrentRun> #include <QtCore/QDir> #include <qtconcurrent/runextensions.h> using namespace CppTools::Internal; using namespace CPlusPlus; namespace { struct Process: protected ASTVisitor { public: Process(QFutureInterface<Core::Utils::FileSearchResult> &future, Document::Ptr doc, const Snapshot &snapshot) : ASTVisitor(doc->control()), _future(future), _doc(doc), _snapshot(snapshot), _source(_doc->source()), _sem(doc->control()) { _snapshot.insert(_doc); } void operator()(Symbol *symbol, Identifier *id, AST *ast) { _declSymbol = symbol; _id = id; _exprDoc = Document::create("<references>"); accept(ast); } protected: using ASTVisitor::visit; QString matchingLine(const Token &tk) const { const char *beg = _source.constData(); const char *cp = beg + tk.offset; for (; cp != beg - 1; --cp) { if (*cp == '\n') break; } ++cp; const char *lineEnd = cp + 1; for (; *lineEnd; ++lineEnd) { if (*lineEnd == '\n') break; } const QString matchingLine = QString::fromUtf8(cp, lineEnd - cp); return matchingLine; } void reportResult(unsigned tokenIndex) { const Token &tk = tokenAt(tokenIndex); const QString lineText = matchingLine(tk); unsigned line, col; getTokenStartPosition(tokenIndex, &line, &col); if (col) --col; // adjust the column position. int len = tk.f.length; _future.reportResult(Core::Utils::FileSearchResult(QDir::toNativeSeparators(_doc->fileName()), line, lineText, col, len)); } bool checkCandidates(const QList<Symbol *> &candidates) const { if (Symbol *canonicalSymbol = LookupContext::canonicalSymbol(candidates)) { #if 0 qDebug() << "*** canonical symbol:" << canonicalSymbol->fileName() << canonicalSymbol->line() << canonicalSymbol->column() << "candidates:" << candidates.size(); #endif return isDeclSymbol(canonicalSymbol); } return false; } bool isDeclSymbol(Symbol *symbol) const { if (! symbol) return false; else if (symbol == _declSymbol) return true; else if (symbol->line() == _declSymbol->line() && symbol->column() == _declSymbol->column()) { if (! qstrcmp(symbol->fileName(), _declSymbol->fileName())) return true; } return false; } LookupContext currentContext(AST *ast) const { unsigned line, column; getTokenStartPosition(ast->firstToken(), &line, &column); Symbol *lastVisibleSymbol = _doc->findSymbolAt(line, column); return LookupContext(lastVisibleSymbol, _exprDoc, _doc, _snapshot); } void ensureNameIsValid(NameAST *ast) { if (ast && ! ast->name) ast->name = _sem.check(ast, /*scope = */ 0); } virtual bool visit(MemInitializerAST *ast) { if (ast->name && ast->name->asSimpleName() != 0) { ensureNameIsValid(ast->name); SimpleNameAST *simple = ast->name->asSimpleName(); if (identifier(simple->identifier_token) == _id) { LookupContext context = currentContext(ast); const QList<Symbol *> candidates = context.resolve(simple->name); if (checkCandidates(candidates)) reportResult(simple->identifier_token); } } accept(ast->expression); return false; } virtual bool visit(PostfixExpressionAST *ast) { _postfixExpressionStack.append(ast); return true; } virtual void endVisit(PostfixExpressionAST *) { _postfixExpressionStack.removeLast(); } virtual bool visit(MemberAccessAST *ast) { if (! ast->member_name) return false; SimpleNameAST *simple = ast->member_name->asSimpleName(); if (! simple) return true; // ### TODO handle pseudo-destructors and qualified names. Q_ASSERT(! _postfixExpressionStack.isEmpty()); if (identifier(simple->identifier_token) == _id) { unsigned startOfPostfixExpression = _postfixExpressionStack.last()->firstToken(); unsigned begin = tokenAt(startOfPostfixExpression).begin(); unsigned end = tokenAt(ast->member_name->lastToken() - 1).end(); const QString expression = _source.mid(begin, end - begin); // qDebug() << "*** expression:" << expression; TypeOfExpression typeofExpression; typeofExpression.setSnapshot(_snapshot); unsigned line, column; getTokenStartPosition(startOfPostfixExpression, &line, &column); Symbol *lastVisibleSymbol = _doc->findSymbolAt(line, column); const QList<TypeOfExpression::Result> results = typeofExpression(expression, _doc, lastVisibleSymbol, TypeOfExpression::NoPreprocess); QList<Symbol *> candidates; foreach (TypeOfExpression::Result r, results) { FullySpecifiedType ty = r.first; Symbol *lastVisibleSymbol = r.second; candidates.append(lastVisibleSymbol); } if (checkCandidates(candidates)) reportResult(simple->identifier_token); } return false; } virtual bool visit(QualifiedNameAST *ast) { if (! ast->name) { //qWarning() << "invalid AST at" << _doc->fileName() << line << column; ast->name = _sem.check(ast, /*scope */ static_cast<Scope *>(0)); } Q_ASSERT(ast->name != 0); Identifier *id = ast->name->identifier(); if (id == _id && ast->unqualified_name) { LookupContext context = currentContext(ast); const QList<Symbol *> candidates = context.resolve(ast->name); if (checkCandidates(candidates)) reportResult(ast->unqualified_name->firstToken()); } return false; } virtual bool visit(SimpleNameAST *ast) { Identifier *id = identifier(ast->identifier_token); if (id == _id) { LookupContext context = currentContext(ast); const QList<Symbol *> candidates = context.resolve(ast->name); if (checkCandidates(candidates)) reportResult(ast->identifier_token); } return false; } virtual bool visit(TemplateIdAST *ast) { Identifier *id = identifier(ast->identifier_token); if (id == _id) { LookupContext context = currentContext(ast); const QList<Symbol *> candidates = context.resolve(ast->name); if (checkCandidates(candidates)) reportResult(ast->identifier_token); } return false; } private: QFutureInterface<Core::Utils::FileSearchResult> &_future; Identifier *_id; // ### remove me Symbol *_declSymbol; Document::Ptr _doc; Snapshot _snapshot; QByteArray _source; Document::Ptr _exprDoc; Semantic _sem; QList<PostfixExpressionAST *> _postfixExpressionStack; }; } // end of anonymous namespace CppFindReferences::CppFindReferences(CppModelManager *modelManager) : _modelManager(modelManager), _resultWindow(ExtensionSystem::PluginManager::instance()->getObject<Find::SearchResultWindow>()) { m_watcher.setPendingResultsLimit(1); connect(&m_watcher, SIGNAL(resultReadyAt(int)), this, SLOT(displayResult(int))); connect(&m_watcher, SIGNAL(finished()), this, SLOT(searchFinished())); } CppFindReferences::~CppFindReferences() { } static void find_helper(QFutureInterface<Core::Utils::FileSearchResult> &future, const QMap<QString, QString> wl, Snapshot snapshot, Symbol *symbol) { QTime tm; tm.start(); Identifier *symbolId = symbol->identifier(); Q_ASSERT(symbolId != 0); const QString sourceFile = QString::fromUtf8(symbol->fileName(), symbol->fileNameLength()); QStringList files(sourceFile); files += snapshot.dependsOn(sourceFile); qDebug() << "done in:" << tm.elapsed() << "number of files to parse:" << files.size(); future.setProgressRange(0, files.size()); for (int i = 0; i < files.size(); ++i) { const QString &fileName = files.at(i); future.setProgressValueAndText(i, QFileInfo(fileName).fileName()); Document::Ptr previousDoc = snapshot.value(fileName); if (previousDoc) { Control *control = previousDoc->control(); Identifier *id = control->findIdentifier(symbolId->chars(), symbolId->size()); if (! id) continue; // skip this document, it's not using symbolId. } QByteArray source; if (wl.contains(fileName)) source = snapshot.preprocessedCode(wl.value(fileName), fileName); else { QFile file(fileName); if (! file.open(QFile::ReadOnly)) continue; const QString contents = QTextStream(&file).readAll(); // ### FIXME source = snapshot.preprocessedCode(contents, fileName); } Document::Ptr doc = snapshot.documentFromSource(source, fileName); doc->tokenize(); Control *control = doc->control(); if (Identifier *id = control->findIdentifier(symbolId->chars(), symbolId->size())) { doc->check(); TranslationUnit *unit = doc->translationUnit(); Process process(future, doc, snapshot); process(symbol, id, unit->ast()); } } future.setProgressValue(files.size()); } void CppFindReferences::findAll(Symbol *symbol) { _resultWindow->clearContents(); _resultWindow->popup(true); const Snapshot snapshot = _modelManager->snapshot(); const QMap<QString, QString> wl = _modelManager->buildWorkingCopyList(); Core::ProgressManager *progressManager = Core::ICore::instance()->progressManager(); QFuture<Core::Utils::FileSearchResult> result = QtConcurrent::run(&find_helper, wl, snapshot, symbol); m_watcher.setFuture(result); Core::FutureProgress *progress = progressManager->addTask(result, tr("Searching..."), CppTools::Constants::TASK_SEARCH, Core::ProgressManager::CloseOnSuccess); connect(progress, SIGNAL(clicked()), _resultWindow, SLOT(popup())); } void CppFindReferences::displayResult(int index) { Core::Utils::FileSearchResult result = m_watcher.future().resultAt(index); Find::ResultWindowItem *item = _resultWindow->addResult(result.fileName, result.lineNumber, result.matchingLine, result.matchStart, result.matchLength); if (item) connect(item, SIGNAL(activated(const QString&,int,int)), this, SLOT(openEditor(const QString&,int,int))); } void CppFindReferences::searchFinished() { emit changed(); } void CppFindReferences::openEditor(const QString &fileName, int line, int column) { TextEditor::BaseTextEditor::openEditorAt(fileName, line, column); }
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** 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 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://www.qtsoftware.com/contact. ** **************************************************************************/ #include "cppfindreferences.h" #include "cppmodelmanager.h" #include "cpptoolsconstants.h" #include <texteditor/basetexteditor.h> #include <find/searchresultwindow.h> #include <extensionsystem/pluginmanager.h> #include <utils/filesearch.h> #include <coreplugin/progressmanager/progressmanager.h> #include <coreplugin/icore.h> #include <ASTVisitor.h> #include <AST.h> #include <Control.h> #include <Literals.h> #include <TranslationUnit.h> #include <Symbols.h> #include <Names.h> #include <Scope.h> #include <cplusplus/CppDocument.h> #include <cplusplus/ExpressionUnderCursor.h> #include <cplusplus/ResolveExpression.h> #include <cplusplus/Overview.h> #include <cplusplus/TypeOfExpression.h> #include <QtCore/QTime> #include <QtCore/QtConcurrentRun> #include <QtCore/QDir> #include <qtconcurrent/runextensions.h> using namespace CppTools::Internal; using namespace CPlusPlus; namespace { struct Process: protected ASTVisitor { public: Process(QFutureInterface<Core::Utils::FileSearchResult> &future, Document::Ptr doc, const Snapshot &snapshot) : ASTVisitor(doc->control()), _future(future), _doc(doc), _snapshot(snapshot), _source(_doc->source()), _sem(doc->control()) { _snapshot.insert(_doc); } void operator()(Symbol *symbol, Identifier *id, AST *ast) { _declSymbol = symbol; _id = id; _exprDoc = Document::create("<references>"); accept(ast); } protected: using ASTVisitor::visit; QString matchingLine(const Token &tk) const { const char *beg = _source.constData(); const char *cp = beg + tk.offset; for (; cp != beg - 1; --cp) { if (*cp == '\n') break; } ++cp; const char *lineEnd = cp + 1; for (; *lineEnd; ++lineEnd) { if (*lineEnd == '\n') break; } const QString matchingLine = QString::fromUtf8(cp, lineEnd - cp); return matchingLine; } void reportResult(unsigned tokenIndex) { const Token &tk = tokenAt(tokenIndex); const QString lineText = matchingLine(tk); unsigned line, col; getTokenStartPosition(tokenIndex, &line, &col); if (col) --col; // adjust the column position. int len = tk.f.length; _future.reportResult(Core::Utils::FileSearchResult(QDir::toNativeSeparators(_doc->fileName()), line, lineText, col, len)); } bool checkCandidates(const QList<Symbol *> &candidates) const { if (Symbol *canonicalSymbol = LookupContext::canonicalSymbol(candidates)) { #if 0 qDebug() << "*** canonical symbol:" << canonicalSymbol->fileName() << canonicalSymbol->line() << canonicalSymbol->column() << "candidates:" << candidates.size(); #endif return isDeclSymbol(canonicalSymbol); } return false; } bool isDeclSymbol(Symbol *symbol) const { if (! symbol) return false; else if (symbol == _declSymbol) return true; else if (symbol->line() == _declSymbol->line() && symbol->column() == _declSymbol->column()) { if (! qstrcmp(symbol->fileName(), _declSymbol->fileName())) return true; } return false; } LookupContext currentContext(AST *ast) const { unsigned line, column; getTokenStartPosition(ast->firstToken(), &line, &column); Symbol *lastVisibleSymbol = _doc->findSymbolAt(line, column); return LookupContext(lastVisibleSymbol, _exprDoc, _doc, _snapshot); } void ensureNameIsValid(NameAST *ast) { if (ast && ! ast->name) ast->name = _sem.check(ast, /*scope = */ 0); } virtual bool visit(MemInitializerAST *ast) { if (ast->name && ast->name->asSimpleName() != 0) { ensureNameIsValid(ast->name); SimpleNameAST *simple = ast->name->asSimpleName(); if (identifier(simple->identifier_token) == _id) { LookupContext context = currentContext(ast); const QList<Symbol *> candidates = context.resolve(simple->name); if (checkCandidates(candidates)) reportResult(simple->identifier_token); } } accept(ast->expression); return false; } virtual bool visit(PostfixExpressionAST *ast) { _postfixExpressionStack.append(ast); return true; } virtual void endVisit(PostfixExpressionAST *) { _postfixExpressionStack.removeLast(); } virtual bool visit(MemberAccessAST *ast) { if (ast->member_name) { if (SimpleNameAST *simple = ast->member_name->asSimpleName()) { if (identifier(simple->identifier_token) == _id) { Q_ASSERT(! _postfixExpressionStack.isEmpty()); checkExpression(_postfixExpressionStack.last()->firstToken(), simple->identifier_token); return false; } } } return true; } void checkExpression(unsigned startToken, unsigned endToken) { const unsigned begin = tokenAt(startToken).begin(); const unsigned end = tokenAt(endToken).end(); const QString expression = _source.mid(begin, end - begin); // qDebug() << "*** expression:" << expression; TypeOfExpression typeofExpression; typeofExpression.setSnapshot(_snapshot); unsigned line, column; getTokenStartPosition(startToken, &line, &column); Symbol *lastVisibleSymbol = _doc->findSymbolAt(line, column); const QList<TypeOfExpression::Result> results = typeofExpression(expression, _doc, lastVisibleSymbol, TypeOfExpression::NoPreprocess); QList<Symbol *> candidates; foreach (TypeOfExpression::Result r, results) { FullySpecifiedType ty = r.first; Symbol *lastVisibleSymbol = r.second; candidates.append(lastVisibleSymbol); } if (checkCandidates(candidates)) reportResult(endToken); } virtual bool visit(QualifiedNameAST *ast) { for (NestedNameSpecifierAST *nested_name_specifier = ast->nested_name_specifier; nested_name_specifier; nested_name_specifier = nested_name_specifier->next) { if (NameAST *class_or_namespace_name = nested_name_specifier->class_or_namespace_name) { SimpleNameAST *simple_name = class_or_namespace_name->asSimpleName(); TemplateIdAST *template_id = 0; if (! simple_name) { template_id = class_or_namespace_name->asTemplateId(); if (template_id) { for (TemplateArgumentListAST *template_arguments = template_id->template_arguments; template_arguments; template_arguments = template_arguments->next) { accept(template_arguments->template_argument); } } } if (simple_name || template_id) { const unsigned identifier_token = simple_name ? simple_name->identifier_token : template_id->identifier_token; if (identifier(identifier_token) == _id) checkExpression(ast->firstToken(), identifier_token); } } } if (ast->unqualified_name) { SimpleNameAST *simple_name = ast->unqualified_name->asSimpleName(); TemplateIdAST *template_id = 0; if (! simple_name) { template_id = ast->unqualified_name->asTemplateId(); if (template_id) { for (TemplateArgumentListAST *template_arguments = template_id->template_arguments; template_arguments; template_arguments = template_arguments->next) { accept(template_arguments->template_argument); } } } if (simple_name || template_id) { const unsigned identifier_token = simple_name ? simple_name->identifier_token : template_id->identifier_token; if (identifier(identifier_token) == _id) checkExpression(ast->firstToken(), identifier_token); } } return false; } virtual bool visit(SimpleNameAST *ast) { Identifier *id = identifier(ast->identifier_token); if (id == _id) { LookupContext context = currentContext(ast); const QList<Symbol *> candidates = context.resolve(ast->name); if (checkCandidates(candidates)) reportResult(ast->identifier_token); } return false; } virtual bool visit(DestructorNameAST *ast) { Identifier *id = identifier(ast->identifier_token); if (id == _id) { LookupContext context = currentContext(ast); const QList<Symbol *> candidates = context.resolve(ast->name); if (checkCandidates(candidates)) reportResult(ast->identifier_token); } return false; } virtual bool visit(TemplateIdAST *ast) { Identifier *id = identifier(ast->identifier_token); if (id == _id) { LookupContext context = currentContext(ast); const QList<Symbol *> candidates = context.resolve(ast->name); if (checkCandidates(candidates)) reportResult(ast->identifier_token); } return false; } private: QFutureInterface<Core::Utils::FileSearchResult> &_future; Identifier *_id; // ### remove me Symbol *_declSymbol; Document::Ptr _doc; Snapshot _snapshot; QByteArray _source; Document::Ptr _exprDoc; Semantic _sem; QList<PostfixExpressionAST *> _postfixExpressionStack; QList<QualifiedNameAST *> _qualifiedNameStack; }; } // end of anonymous namespace CppFindReferences::CppFindReferences(CppModelManager *modelManager) : _modelManager(modelManager), _resultWindow(ExtensionSystem::PluginManager::instance()->getObject<Find::SearchResultWindow>()) { m_watcher.setPendingResultsLimit(1); connect(&m_watcher, SIGNAL(resultReadyAt(int)), this, SLOT(displayResult(int))); connect(&m_watcher, SIGNAL(finished()), this, SLOT(searchFinished())); } CppFindReferences::~CppFindReferences() { } static void find_helper(QFutureInterface<Core::Utils::FileSearchResult> &future, const QMap<QString, QString> wl, Snapshot snapshot, Symbol *symbol) { QTime tm; tm.start(); Identifier *symbolId = symbol->identifier(); Q_ASSERT(symbolId != 0); const QString sourceFile = QString::fromUtf8(symbol->fileName(), symbol->fileNameLength()); QStringList files(sourceFile); files += snapshot.dependsOn(sourceFile); qDebug() << "done in:" << tm.elapsed() << "number of files to parse:" << files.size(); future.setProgressRange(0, files.size()); for (int i = 0; i < files.size(); ++i) { const QString &fileName = files.at(i); future.setProgressValueAndText(i, QFileInfo(fileName).fileName()); Document::Ptr previousDoc = snapshot.value(fileName); if (previousDoc) { Control *control = previousDoc->control(); Identifier *id = control->findIdentifier(symbolId->chars(), symbolId->size()); if (! id) continue; // skip this document, it's not using symbolId. } QByteArray source; if (wl.contains(fileName)) source = snapshot.preprocessedCode(wl.value(fileName), fileName); else { QFile file(fileName); if (! file.open(QFile::ReadOnly)) continue; const QString contents = QTextStream(&file).readAll(); // ### FIXME source = snapshot.preprocessedCode(contents, fileName); } Document::Ptr doc = snapshot.documentFromSource(source, fileName); doc->tokenize(); Control *control = doc->control(); if (Identifier *id = control->findIdentifier(symbolId->chars(), symbolId->size())) { doc->check(); TranslationUnit *unit = doc->translationUnit(); Process process(future, doc, snapshot); process(symbol, id, unit->ast()); } } future.setProgressValue(files.size()); } void CppFindReferences::findAll(Symbol *symbol) { _resultWindow->clearContents(); _resultWindow->popup(true); const Snapshot snapshot = _modelManager->snapshot(); const QMap<QString, QString> wl = _modelManager->buildWorkingCopyList(); Core::ProgressManager *progressManager = Core::ICore::instance()->progressManager(); QFuture<Core::Utils::FileSearchResult> result = QtConcurrent::run(&find_helper, wl, snapshot, symbol); m_watcher.setFuture(result); Core::FutureProgress *progress = progressManager->addTask(result, tr("Searching..."), CppTools::Constants::TASK_SEARCH, Core::ProgressManager::CloseOnSuccess); connect(progress, SIGNAL(clicked()), _resultWindow, SLOT(popup())); } void CppFindReferences::displayResult(int index) { Core::Utils::FileSearchResult result = m_watcher.future().resultAt(index); Find::ResultWindowItem *item = _resultWindow->addResult(result.fileName, result.lineNumber, result.matchingLine, result.matchStart, result.matchLength); if (item) connect(item, SIGNAL(activated(const QString&,int,int)), this, SLOT(openEditor(const QString&,int,int))); } void CppFindReferences::searchFinished() { emit changed(); } void CppFindReferences::openEditor(const QString &fileName, int line, int column) { TextEditor::BaseTextEditor::openEditorAt(fileName, line, column); }
Handle qualified name ids.
Handle qualified name ids.
C++
lgpl-2.1
AltarBeastiful/qt-creator,colede/qtcreator,kuba1/qtcreator,xianian/qt-creator,amyvmiwei/qt-creator,omniacreator/qtcreator,syntheticpp/qt-creator,danimo/qt-creator,renatofilho/QtCreator,xianian/qt-creator,martyone/sailfish-qtcreator,hdweiss/qt-creator-visualizer,kuba1/qtcreator,richardmg/qtcreator,xianian/qt-creator,Distrotech/qtcreator,amyvmiwei/qt-creator,AltarBeastiful/qt-creator,jonnor/qt-creator,KDE/android-qt-creator,pcacjr/qt-creator,martyone/sailfish-qtcreator,AltarBeastiful/qt-creator,ostash/qt-creator-i18n-uk,martyone/sailfish-qtcreator,xianian/qt-creator,KDAB/KDAB-Creator,richardmg/qtcreator,hdweiss/qt-creator-visualizer,KDE/android-qt-creator,enricoros/k-qt-creator-inspector,farseerri/git_code,maui-packages/qt-creator,pcacjr/qt-creator,ostash/qt-creator-i18n-uk,syntheticpp/qt-creator,maui-packages/qt-creator,martyone/sailfish-qtcreator,bakaiadam/collaborative_qt_creator,Distrotech/qtcreator,amyvmiwei/qt-creator,dmik/qt-creator-os2,renatofilho/QtCreator,Distrotech/qtcreator,dmik/qt-creator-os2,richardmg/qtcreator,yinyunqiao/qtcreator,kuba1/qtcreator,bakaiadam/collaborative_qt_creator,dmik/qt-creator-os2,malikcjm/qtcreator,KDAB/KDAB-Creator,amyvmiwei/qt-creator,darksylinc/qt-creator,danimo/qt-creator,malikcjm/qtcreator,enricoros/k-qt-creator-inspector,bakaiadam/collaborative_qt_creator,yinyunqiao/qtcreator,pcacjr/qt-creator,azat/qtcreator,malikcjm/qtcreator,Distrotech/qtcreator,KDAB/KDAB-Creator,azat/qtcreator,dmik/qt-creator-os2,farseerri/git_code,dmik/qt-creator-os2,hdweiss/qt-creator-visualizer,danimo/qt-creator,Distrotech/qtcreator,farseerri/git_code,omniacreator/qtcreator,danimo/qt-creator,renatofilho/QtCreator,danimo/qt-creator,KDAB/KDAB-Creator,maui-packages/qt-creator,richardmg/qtcreator,amyvmiwei/qt-creator,xianian/qt-creator,enricoros/k-qt-creator-inspector,AltarBeastiful/qt-creator,xianian/qt-creator,yinyunqiao/qtcreator,colede/qtcreator,xianian/qt-creator,pcacjr/qt-creator,darksylinc/qt-creator,omniacreator/qtcreator,bakaiadam/collaborative_qt_creator,farseerri/git_code,KDE/android-qt-creator,duythanhphan/qt-creator,sandsmark/qtcreator-minimap,enricoros/k-qt-creator-inspector,syntheticpp/qt-creator,maui-packages/qt-creator,colede/qtcreator,martyone/sailfish-qtcreator,richardmg/qtcreator,martyone/sailfish-qtcreator,sandsmark/qtcreator-minimap,colede/qtcreator,duythanhphan/qt-creator,ostash/qt-creator-i18n-uk,duythanhphan/qt-creator,jonnor/qt-creator,kuba1/qtcreator,syntheticpp/qt-creator,duythanhphan/qt-creator,yinyunqiao/qtcreator,pcacjr/qt-creator,farseerri/git_code,yinyunqiao/qtcreator,danimo/qt-creator,azat/qtcreator,dmik/qt-creator-os2,darksylinc/qt-creator,kuba1/qtcreator,renatofilho/QtCreator,colede/qtcreator,hdweiss/qt-creator-visualizer,sandsmark/qtcreator-minimap,KDAB/KDAB-Creator,pcacjr/qt-creator,hdweiss/qt-creator-visualizer,jonnor/qt-creator,azat/qtcreator,darksylinc/qt-creator,farseerri/git_code,amyvmiwei/qt-creator,KDE/android-qt-creator,duythanhphan/qt-creator,xianian/qt-creator,sandsmark/qtcreator-minimap,maui-packages/qt-creator,ostash/qt-creator-i18n-uk,dmik/qt-creator-os2,darksylinc/qt-creator,enricoros/k-qt-creator-inspector,martyone/sailfish-qtcreator,malikcjm/qtcreator,omniacreator/qtcreator,darksylinc/qt-creator,darksylinc/qt-creator,kuba1/qtcreator,syntheticpp/qt-creator,malikcjm/qtcreator,hdweiss/qt-creator-visualizer,ostash/qt-creator-i18n-uk,richardmg/qtcreator,yinyunqiao/qtcreator,jonnor/qt-creator,amyvmiwei/qt-creator,bakaiadam/collaborative_qt_creator,martyone/sailfish-qtcreator,pcacjr/qt-creator,KDE/android-qt-creator,sandsmark/qtcreator-minimap,ostash/qt-creator-i18n-uk,sandsmark/qtcreator-minimap,enricoros/k-qt-creator-inspector,danimo/qt-creator,jonnor/qt-creator,darksylinc/qt-creator,syntheticpp/qt-creator,AltarBeastiful/qt-creator,malikcjm/qtcreator,bakaiadam/collaborative_qt_creator,renatofilho/QtCreator,omniacreator/qtcreator,AltarBeastiful/qt-creator,omniacreator/qtcreator,ostash/qt-creator-i18n-uk,richardmg/qtcreator,azat/qtcreator,AltarBeastiful/qt-creator,azat/qtcreator,KDE/android-qt-creator,kuba1/qtcreator,kuba1/qtcreator,farseerri/git_code,jonnor/qt-creator,maui-packages/qt-creator,syntheticpp/qt-creator,duythanhphan/qt-creator,amyvmiwei/qt-creator,colede/qtcreator,kuba1/qtcreator,Distrotech/qtcreator,maui-packages/qt-creator,bakaiadam/collaborative_qt_creator,renatofilho/QtCreator,danimo/qt-creator,AltarBeastiful/qt-creator,martyone/sailfish-qtcreator,duythanhphan/qt-creator,malikcjm/qtcreator,danimo/qt-creator,xianian/qt-creator,KDE/android-qt-creator,KDE/android-qt-creator,yinyunqiao/qtcreator,KDAB/KDAB-Creator,farseerri/git_code,colede/qtcreator,omniacreator/qtcreator,Distrotech/qtcreator,enricoros/k-qt-creator-inspector
48a7c150fca9997999c3c10527e2d11da6d5c4b1
lib/Target/X86/X86Subtarget.cpp
lib/Target/X86/X86Subtarget.cpp
//===-- X86Subtarget.cpp - X86 Subtarget Information ----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the X86 specific subclass of TargetSubtargetInfo. // //===----------------------------------------------------------------------===// #include "X86Subtarget.h" #include "X86InstrInfo.h" #include "llvm/IR/Attributes.h" #include "llvm/IR/Function.h" #include "llvm/IR/GlobalValue.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/Host.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" #if defined(_MSC_VER) #include <intrin.h> #endif using namespace llvm; #define DEBUG_TYPE "subtarget" #define GET_SUBTARGETINFO_TARGET_DESC #define GET_SUBTARGETINFO_CTOR #include "X86GenSubtargetInfo.inc" // Temporary option to control early if-conversion for x86 while adding machine // models. static cl::opt<bool> X86EarlyIfConv("x86-early-ifcvt", cl::Hidden, cl::desc("Enable early if-conversion on X86")); /// ClassifyBlockAddressReference - Classify a blockaddress reference for the /// current subtarget according to how we should reference it in a non-pcrel /// context. unsigned char X86Subtarget::ClassifyBlockAddressReference() const { if (isPICStyleGOT()) // 32-bit ELF targets. return X86II::MO_GOTOFF; if (isPICStyleStubPIC()) // Darwin/32 in PIC mode. return X86II::MO_PIC_BASE_OFFSET; // Direct static reference to label. return X86II::MO_NO_FLAG; } /// ClassifyGlobalReference - Classify a global variable reference for the /// current subtarget according to how we should reference it in a non-pcrel /// context. unsigned char X86Subtarget:: ClassifyGlobalReference(const GlobalValue *GV, const TargetMachine &TM) const { // DLLImport only exists on windows, it is implemented as a load from a // DLLIMPORT stub. if (GV->hasDLLImportStorageClass()) return X86II::MO_DLLIMPORT; // Determine whether this is a reference to a definition or a declaration. // Materializable GVs (in JIT lazy compilation mode) do not require an extra // load from stub. bool isDecl = GV->hasAvailableExternallyLinkage(); if (GV->isDeclaration() && !GV->isMaterializable()) isDecl = true; // X86-64 in PIC mode. if (isPICStyleRIPRel()) { // Large model never uses stubs. if (TM.getCodeModel() == CodeModel::Large) return X86II::MO_NO_FLAG; if (isTargetDarwin()) { // If symbol visibility is hidden, the extra load is not needed if // target is x86-64 or the symbol is definitely defined in the current // translation unit. if (GV->hasDefaultVisibility() && (isDecl || GV->isWeakForLinker())) return X86II::MO_GOTPCREL; } else if (!isTargetWin64()) { assert(isTargetELF() && "Unknown rip-relative target"); // Extra load is needed for all externally visible. if (!GV->hasLocalLinkage() && GV->hasDefaultVisibility()) return X86II::MO_GOTPCREL; } return X86II::MO_NO_FLAG; } if (isPICStyleGOT()) { // 32-bit ELF targets. // Extra load is needed for all externally visible. if (GV->hasLocalLinkage() || GV->hasHiddenVisibility()) return X86II::MO_GOTOFF; return X86II::MO_GOT; } if (isPICStyleStubPIC()) { // Darwin/32 in PIC mode. // Determine whether we have a stub reference and/or whether the reference // is relative to the PIC base or not. // If this is a strong reference to a definition, it is definitely not // through a stub. if (!isDecl && !GV->isWeakForLinker()) return X86II::MO_PIC_BASE_OFFSET; // Unless we have a symbol with hidden visibility, we have to go through a // normal $non_lazy_ptr stub because this symbol might be resolved late. if (!GV->hasHiddenVisibility()) // Non-hidden $non_lazy_ptr reference. return X86II::MO_DARWIN_NONLAZY_PIC_BASE; // If symbol visibility is hidden, we have a stub for common symbol // references and external declarations. if (isDecl || GV->hasCommonLinkage()) { // Hidden $non_lazy_ptr reference. return X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE; } // Otherwise, no stub. return X86II::MO_PIC_BASE_OFFSET; } if (isPICStyleStubNoDynamic()) { // Darwin/32 in -mdynamic-no-pic mode. // Determine whether we have a stub reference. // If this is a strong reference to a definition, it is definitely not // through a stub. if (!isDecl && !GV->isWeakForLinker()) return X86II::MO_NO_FLAG; // Unless we have a symbol with hidden visibility, we have to go through a // normal $non_lazy_ptr stub because this symbol might be resolved late. if (!GV->hasHiddenVisibility()) // Non-hidden $non_lazy_ptr reference. return X86II::MO_DARWIN_NONLAZY; // Otherwise, no stub. return X86II::MO_NO_FLAG; } // Direct static reference to global. return X86II::MO_NO_FLAG; } /// getBZeroEntry - This function returns the name of a function which has an /// interface like the non-standard bzero function, if such a function exists on /// the current subtarget and it is considered prefereable over memset with zero /// passed as the second argument. Otherwise it returns null. const char *X86Subtarget::getBZeroEntry() const { // Darwin 10 has a __bzero entry point for this purpose. if (getTargetTriple().isMacOSX() && !getTargetTriple().isMacOSXVersionLT(10, 6)) return "__bzero"; return nullptr; } bool X86Subtarget::hasSinCos() const { return getTargetTriple().isMacOSX() && !getTargetTriple().isMacOSXVersionLT(10, 9) && is64Bit(); } /// IsLegalToCallImmediateAddr - Return true if the subtarget allows calls /// to immediate address. bool X86Subtarget::IsLegalToCallImmediateAddr(const TargetMachine &TM) const { // FIXME: I386 PE/COFF supports PC relative calls using IMAGE_REL_I386_REL32 // but WinCOFFObjectWriter::RecordRelocation cannot emit them. Once it does, // the following check for Win32 should be removed. if (In64BitMode || isTargetWin32()) return false; return isTargetELF() || TM.getRelocationModel() == Reloc::Static; } void X86Subtarget::resetSubtargetFeatures(const MachineFunction *MF) { AttributeSet FnAttrs = MF->getFunction()->getAttributes(); Attribute CPUAttr = FnAttrs.getAttribute(AttributeSet::FunctionIndex, "target-cpu"); Attribute FSAttr = FnAttrs.getAttribute(AttributeSet::FunctionIndex, "target-features"); std::string CPU = !CPUAttr.hasAttribute(Attribute::None) ? CPUAttr.getValueAsString() : ""; std::string FS = !FSAttr.hasAttribute(Attribute::None) ? FSAttr.getValueAsString() : ""; if (!FS.empty()) { initializeEnvironment(); resetSubtargetFeatures(CPU, FS); } } void X86Subtarget::resetSubtargetFeatures(StringRef CPU, StringRef FS) { std::string CPUName = CPU; if (CPUName.empty()) CPUName = "generic"; // Make sure 64-bit features are available in 64-bit mode. (But make sure // SSE2 can be turned off explicitly.) std::string FullFS = FS; if (In64BitMode) { if (!FullFS.empty()) FullFS = "+64bit,+sse2," + FullFS; else FullFS = "+64bit,+sse2"; } // If feature string is not empty, parse features string. ParseSubtargetFeatures(CPUName, FullFS); // Make sure the right MCSchedModel is used. InitCPUSchedModel(CPUName); if (X86ProcFamily == IntelAtom || X86ProcFamily == IntelSLM) PostRAScheduler = true; InstrItins = getInstrItineraryForCPU(CPUName); // It's important to keep the MCSubtargetInfo feature bits in sync with // target data structure which is shared with MC code emitter, etc. if (In64BitMode) ToggleFeature(X86::Mode64Bit); else if (In32BitMode) ToggleFeature(X86::Mode32Bit); else if (In16BitMode) ToggleFeature(X86::Mode16Bit); else llvm_unreachable("Not 16-bit, 32-bit or 64-bit mode!"); DEBUG(dbgs() << "Subtarget features: SSELevel " << X86SSELevel << ", 3DNowLevel " << X863DNowLevel << ", 64bit " << HasX86_64 << "\n"); assert((!In64BitMode || HasX86_64) && "64-bit code requested on a subtarget that doesn't support it!"); // Stack alignment is 16 bytes on Darwin, Linux and Solaris (both // 32 and 64 bit) and for all 64-bit targets. if (StackAlignOverride) stackAlignment = StackAlignOverride; else if (isTargetDarwin() || isTargetLinux() || isTargetSolaris() || In64BitMode) stackAlignment = 16; } void X86Subtarget::initializeEnvironment() { X86SSELevel = NoMMXSSE; X863DNowLevel = NoThreeDNow; HasCMov = false; HasX86_64 = false; HasPOPCNT = false; HasSSE4A = false; HasAES = false; HasPCLMUL = false; HasFMA = false; HasFMA4 = false; HasXOP = false; HasTBM = false; HasMOVBE = false; HasRDRAND = false; HasF16C = false; HasFSGSBase = false; HasLZCNT = false; HasBMI = false; HasBMI2 = false; HasRTM = false; HasHLE = false; HasERI = false; HasCDI = false; HasPFI = false; HasADX = false; HasSHA = false; HasPRFCHW = false; HasRDSEED = false; IsBTMemSlow = false; IsSHLDSlow = false; IsUAMemFast = false; HasVectorUAMem = false; HasCmpxchg16b = false; UseLeaForSP = false; HasSlowDivide = false; PostRAScheduler = false; PadShortFunctions = false; CallRegIndirect = false; LEAUsesAG = false; SlowLEA = false; SlowIncDec = false; stackAlignment = 4; // FIXME: this is a known good value for Yonah. How about others? MaxInlineSizeThreshold = 128; } static std::string computeDataLayout(const X86Subtarget &ST) { // X86 is little endian std::string Ret = "e"; Ret += DataLayout::getManglingComponent(ST.getTargetTriple()); // X86 and x32 have 32 bit pointers. if (ST.isTarget64BitILP32() || !ST.is64Bit()) Ret += "-p:32:32"; // Some ABIs align 64 bit integers and doubles to 64 bits, others to 32. if (ST.is64Bit() || ST.isOSWindows() || ST.isTargetNaCl()) Ret += "-i64:64"; else Ret += "-f64:32:64"; // Some ABIs align long double to 128 bits, others to 32. if (ST.isTargetNaCl()) ; // No f80 else if (ST.is64Bit() || ST.isTargetDarwin()) Ret += "-f80:128"; else Ret += "-f80:32"; // The registers can hold 8, 16, 32 or, in x86-64, 64 bits. if (ST.is64Bit()) Ret += "-n8:16:32:64"; else Ret += "-n8:16:32"; // The stack is aligned to 32 bits on some ABIs and 128 bits on others. if (!ST.is64Bit() && ST.isOSWindows()) Ret += "-S32"; else Ret += "-S128"; return Ret; } X86Subtarget::X86Subtarget(const std::string &TT, const std::string &CPU, const std::string &FS, X86TargetMachine &TM, unsigned StackAlignOverride) : X86GenSubtargetInfo(TT, CPU, FS), X86ProcFamily(Others), PICStyle(PICStyles::None), TargetTriple(TT), StackAlignOverride(StackAlignOverride), In64BitMode(TargetTriple.getArch() == Triple::x86_64), In32BitMode(TargetTriple.getArch() == Triple::x86 && TargetTriple.getEnvironment() != Triple::CODE16), In16BitMode(TargetTriple.getArch() == Triple::x86 && TargetTriple.getEnvironment() == Triple::CODE16), DL(computeDataLayout(*this)), TSInfo(DL) { initializeEnvironment(); resetSubtargetFeatures(CPU, FS); // Ordering here is important. X86InstrInfo initializes X86RegisterInfo which // X86TargetLowering needs. InstrInfo = new X86InstrInfo(TM); TLInfo = new X86TargetLowering(TM); FrameLowering = new X86FrameLowering(TargetFrameLowering::StackGrowsDown, getStackAlignment(), is64Bit() ? -8 : -4); JITInfo = new X86JITInfo(hasSSE1()); } X86Subtarget::~X86Subtarget() { delete TLInfo; delete InstrInfo; delete FrameLowering; } bool X86Subtarget::enablePostRAScheduler(CodeGenOpt::Level OptLevel, TargetSubtargetInfo::AntiDepBreakMode &Mode, RegClassVector &CriticalPathRCs) const { Mode = TargetSubtargetInfo::ANTIDEP_CRITICAL; CriticalPathRCs.clear(); return PostRAScheduler && OptLevel >= CodeGenOpt::Default; } bool X86Subtarget::enableEarlyIfConversion() const { return hasCMov() && X86EarlyIfConv; }
//===-- X86Subtarget.cpp - X86 Subtarget Information ----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the X86 specific subclass of TargetSubtargetInfo. // //===----------------------------------------------------------------------===// #include "X86Subtarget.h" #include "X86InstrInfo.h" #include "llvm/IR/Attributes.h" #include "llvm/IR/Function.h" #include "llvm/IR/GlobalValue.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/Host.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" #if defined(_MSC_VER) #include <intrin.h> #endif using namespace llvm; #define DEBUG_TYPE "subtarget" #define GET_SUBTARGETINFO_TARGET_DESC #define GET_SUBTARGETINFO_CTOR #include "X86GenSubtargetInfo.inc" // Temporary option to control early if-conversion for x86 while adding machine // models. static cl::opt<bool> X86EarlyIfConv("x86-early-ifcvt", cl::Hidden, cl::desc("Enable early if-conversion on X86")); /// ClassifyBlockAddressReference - Classify a blockaddress reference for the /// current subtarget according to how we should reference it in a non-pcrel /// context. unsigned char X86Subtarget::ClassifyBlockAddressReference() const { if (isPICStyleGOT()) // 32-bit ELF targets. return X86II::MO_GOTOFF; if (isPICStyleStubPIC()) // Darwin/32 in PIC mode. return X86II::MO_PIC_BASE_OFFSET; // Direct static reference to label. return X86II::MO_NO_FLAG; } /// ClassifyGlobalReference - Classify a global variable reference for the /// current subtarget according to how we should reference it in a non-pcrel /// context. unsigned char X86Subtarget:: ClassifyGlobalReference(const GlobalValue *GV, const TargetMachine &TM) const { // DLLImport only exists on windows, it is implemented as a load from a // DLLIMPORT stub. if (GV->hasDLLImportStorageClass()) return X86II::MO_DLLIMPORT; // Determine whether this is a reference to a definition or a declaration. // Materializable GVs (in JIT lazy compilation mode) do not require an extra // load from stub. bool isDecl = GV->hasAvailableExternallyLinkage(); if (GV->isDeclaration() && !GV->isMaterializable()) isDecl = true; // X86-64 in PIC mode. if (isPICStyleRIPRel()) { // Large model never uses stubs. if (TM.getCodeModel() == CodeModel::Large) return X86II::MO_NO_FLAG; if (isTargetDarwin()) { // If symbol visibility is hidden, the extra load is not needed if // target is x86-64 or the symbol is definitely defined in the current // translation unit. if (GV->hasDefaultVisibility() && (isDecl || GV->isWeakForLinker())) return X86II::MO_GOTPCREL; } else if (!isTargetWin64()) { assert(isTargetELF() && "Unknown rip-relative target"); // Extra load is needed for all externally visible. if (!GV->hasLocalLinkage() && GV->hasDefaultVisibility()) return X86II::MO_GOTPCREL; } return X86II::MO_NO_FLAG; } if (isPICStyleGOT()) { // 32-bit ELF targets. // Extra load is needed for all externally visible. if (GV->hasLocalLinkage() || GV->hasHiddenVisibility()) return X86II::MO_GOTOFF; return X86II::MO_GOT; } if (isPICStyleStubPIC()) { // Darwin/32 in PIC mode. // Determine whether we have a stub reference and/or whether the reference // is relative to the PIC base or not. // If this is a strong reference to a definition, it is definitely not // through a stub. if (!isDecl && !GV->isWeakForLinker()) return X86II::MO_PIC_BASE_OFFSET; // Unless we have a symbol with hidden visibility, we have to go through a // normal $non_lazy_ptr stub because this symbol might be resolved late. if (!GV->hasHiddenVisibility()) // Non-hidden $non_lazy_ptr reference. return X86II::MO_DARWIN_NONLAZY_PIC_BASE; // If symbol visibility is hidden, we have a stub for common symbol // references and external declarations. if (isDecl || GV->hasCommonLinkage()) { // Hidden $non_lazy_ptr reference. return X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE; } // Otherwise, no stub. return X86II::MO_PIC_BASE_OFFSET; } if (isPICStyleStubNoDynamic()) { // Darwin/32 in -mdynamic-no-pic mode. // Determine whether we have a stub reference. // If this is a strong reference to a definition, it is definitely not // through a stub. if (!isDecl && !GV->isWeakForLinker()) return X86II::MO_NO_FLAG; // Unless we have a symbol with hidden visibility, we have to go through a // normal $non_lazy_ptr stub because this symbol might be resolved late. if (!GV->hasHiddenVisibility()) // Non-hidden $non_lazy_ptr reference. return X86II::MO_DARWIN_NONLAZY; // Otherwise, no stub. return X86II::MO_NO_FLAG; } // Direct static reference to global. return X86II::MO_NO_FLAG; } /// getBZeroEntry - This function returns the name of a function which has an /// interface like the non-standard bzero function, if such a function exists on /// the current subtarget and it is considered prefereable over memset with zero /// passed as the second argument. Otherwise it returns null. const char *X86Subtarget::getBZeroEntry() const { // Darwin 10 has a __bzero entry point for this purpose. if (getTargetTriple().isMacOSX() && !getTargetTriple().isMacOSXVersionLT(10, 6)) return "__bzero"; return nullptr; } bool X86Subtarget::hasSinCos() const { return getTargetTriple().isMacOSX() && !getTargetTriple().isMacOSXVersionLT(10, 9) && is64Bit(); } /// IsLegalToCallImmediateAddr - Return true if the subtarget allows calls /// to immediate address. bool X86Subtarget::IsLegalToCallImmediateAddr(const TargetMachine &TM) const { // FIXME: I386 PE/COFF supports PC relative calls using IMAGE_REL_I386_REL32 // but WinCOFFObjectWriter::RecordRelocation cannot emit them. Once it does, // the following check for Win32 should be removed. if (In64BitMode || isTargetWin32()) return false; return isTargetELF() || TM.getRelocationModel() == Reloc::Static; } void X86Subtarget::resetSubtargetFeatures(const MachineFunction *MF) { AttributeSet FnAttrs = MF->getFunction()->getAttributes(); Attribute CPUAttr = FnAttrs.getAttribute(AttributeSet::FunctionIndex, "target-cpu"); Attribute FSAttr = FnAttrs.getAttribute(AttributeSet::FunctionIndex, "target-features"); std::string CPU = !CPUAttr.hasAttribute(Attribute::None) ? CPUAttr.getValueAsString() : ""; std::string FS = !FSAttr.hasAttribute(Attribute::None) ? FSAttr.getValueAsString() : ""; if (!FS.empty()) { initializeEnvironment(); resetSubtargetFeatures(CPU, FS); } } void X86Subtarget::resetSubtargetFeatures(StringRef CPU, StringRef FS) { std::string CPUName = CPU; if (CPUName.empty()) CPUName = "generic"; // Make sure 64-bit features are available in 64-bit mode. (But make sure // SSE2 can be turned off explicitly.) std::string FullFS = FS; if (In64BitMode) { if (!FullFS.empty()) FullFS = "+64bit,+sse2," + FullFS; else FullFS = "+64bit,+sse2"; } // If feature string is not empty, parse features string. ParseSubtargetFeatures(CPUName, FullFS); // Make sure the right MCSchedModel is used. InitCPUSchedModel(CPUName); if (X86ProcFamily == IntelAtom || X86ProcFamily == IntelSLM) PostRAScheduler = true; InstrItins = getInstrItineraryForCPU(CPUName); // It's important to keep the MCSubtargetInfo feature bits in sync with // target data structure which is shared with MC code emitter, etc. if (In64BitMode) ToggleFeature(X86::Mode64Bit); else if (In32BitMode) ToggleFeature(X86::Mode32Bit); else if (In16BitMode) ToggleFeature(X86::Mode16Bit); else llvm_unreachable("Not 16-bit, 32-bit or 64-bit mode!"); DEBUG(dbgs() << "Subtarget features: SSELevel " << X86SSELevel << ", 3DNowLevel " << X863DNowLevel << ", 64bit " << HasX86_64 << "\n"); assert((!In64BitMode || HasX86_64) && "64-bit code requested on a subtarget that doesn't support it!"); // Stack alignment is 16 bytes on Darwin, Linux and Solaris (both // 32 and 64 bit) and for all 64-bit targets. if (StackAlignOverride) stackAlignment = StackAlignOverride; else if (isTargetDarwin() || isTargetLinux() || isTargetSolaris() || In64BitMode) stackAlignment = 16; } void X86Subtarget::initializeEnvironment() { X86SSELevel = NoMMXSSE; X863DNowLevel = NoThreeDNow; HasCMov = false; HasX86_64 = false; HasPOPCNT = false; HasSSE4A = false; HasAES = false; HasPCLMUL = false; HasFMA = false; HasFMA4 = false; HasXOP = false; HasTBM = false; HasMOVBE = false; HasRDRAND = false; HasF16C = false; HasFSGSBase = false; HasLZCNT = false; HasBMI = false; HasBMI2 = false; HasRTM = false; HasHLE = false; HasERI = false; HasCDI = false; HasPFI = false; HasADX = false; HasSHA = false; HasPRFCHW = false; HasRDSEED = false; IsBTMemSlow = false; IsSHLDSlow = false; IsUAMemFast = false; HasVectorUAMem = false; HasCmpxchg16b = false; UseLeaForSP = false; HasSlowDivide = false; PostRAScheduler = false; PadShortFunctions = false; CallRegIndirect = false; LEAUsesAG = false; SlowLEA = false; SlowIncDec = false; stackAlignment = 4; // FIXME: this is a known good value for Yonah. How about others? MaxInlineSizeThreshold = 128; } static std::string computeDataLayout(const X86Subtarget &ST) { // X86 is little endian std::string Ret = "e"; Ret += DataLayout::getManglingComponent(ST.getTargetTriple()); // X86 and x32 have 32 bit pointers. if (ST.isTarget64BitILP32() || !ST.is64Bit()) Ret += "-p:32:32"; // Some ABIs align 64 bit integers and doubles to 64 bits, others to 32. if (ST.is64Bit() || ST.isOSWindows() || ST.isTargetNaCl()) Ret += "-i64:64"; else Ret += "-f64:32:64"; // Some ABIs align long double to 128 bits, others to 32. if (ST.isTargetNaCl()) ; // No f80 else if (ST.is64Bit() || ST.isTargetDarwin()) Ret += "-f80:128"; else Ret += "-f80:32"; // The registers can hold 8, 16, 32 or, in x86-64, 64 bits. if (ST.is64Bit()) Ret += "-n8:16:32:64"; else Ret += "-n8:16:32"; // The stack is aligned to 32 bits on some ABIs and 128 bits on others. if (!ST.is64Bit() && ST.isOSWindows()) Ret += "-S32"; else Ret += "-S128"; return Ret; } X86Subtarget::X86Subtarget(const std::string &TT, const std::string &CPU, const std::string &FS, X86TargetMachine &TM, unsigned StackAlignOverride) : X86GenSubtargetInfo(TT, CPU, FS), X86ProcFamily(Others), PICStyle(PICStyles::None), TargetTriple(TT), StackAlignOverride(StackAlignOverride), In64BitMode(TargetTriple.getArch() == Triple::x86_64), In32BitMode(TargetTriple.getArch() == Triple::x86 && TargetTriple.getEnvironment() != Triple::CODE16), In16BitMode(TargetTriple.getArch() == Triple::x86 && TargetTriple.getEnvironment() == Triple::CODE16), DL(computeDataLayout(*this)), TSInfo(DL) { initializeEnvironment(); resetSubtargetFeatures(CPU, FS); // Ordering here is important. X86InstrInfo initializes X86RegisterInfo which // X86TargetLowering needs. InstrInfo = new X86InstrInfo(TM); TLInfo = new X86TargetLowering(TM); FrameLowering = new X86FrameLowering(TargetFrameLowering::StackGrowsDown, getStackAlignment(), is64Bit() ? -8 : -4); JITInfo = new X86JITInfo(hasSSE1()); } X86Subtarget::~X86Subtarget() { delete TLInfo; delete InstrInfo; delete FrameLowering; delete JITInfo; } bool X86Subtarget::enablePostRAScheduler(CodeGenOpt::Level OptLevel, TargetSubtargetInfo::AntiDepBreakMode &Mode, RegClassVector &CriticalPathRCs) const { Mode = TargetSubtargetInfo::ANTIDEP_CRITICAL; CriticalPathRCs.clear(); return PostRAScheduler && OptLevel >= CodeGenOpt::Default; } bool X86Subtarget::enableEarlyIfConversion() const { return hasCMov() && X86EarlyIfConv; }
Delete X86JITInfo in the subtarget destructor.
Delete X86JITInfo in the subtarget destructor. git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@210516 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
apple/swift-llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,chubbymaggie/asap,dslab-epfl/asap,chubbymaggie/asap,chubbymaggie/asap,llvm-mirror/llvm,dslab-epfl/asap,dslab-epfl/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,dslab-epfl/asap,chubbymaggie/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,chubbymaggie/asap,dslab-epfl/asap,llvm-mirror/llvm,apple/swift-llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm
d1f76866fec725cbeccc28ab83ae871a53954346
src/media/plugins/video/videoparser.cpp
src/media/plugins/video/videoparser.cpp
/**************************************************************************** This file is part of the QtMediaHub project on http://www.qtmediahub.com Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).* All rights reserved. Contact: Girish Ramakrishnan [email protected] Contact: Nokia Corporation [email protected] Contact: Nokia Corporation [email protected] You may use this file under the terms of the BSD license as follows: Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ****************************************************************************/ #include "videoparser.h" #include "qmh-config.h" #include "libraryinfo.h" #include <QtGui> #include <QtSql> #include "scopedtransaction.h" #define DEBUG if (0) qDebug() << __PRETTY_FUNCTION__ bool VideoParser::canRead(const QFileInfo &info) const { static QStringList supportedTypes = QStringList() << "avi" << "ogg" << "mp4" << "mpeg" << "mpg" << "mov" << "ogv" << "wmv" << "mkv"; return supportedTypes.contains(info.suffix()); } #ifdef THUMBNAIL_GSTREAMER #include <gst/gst.h> #define CAPS "video/x-raw-rgb,pixel-aspect-ratio=1/1,bpp=(int)24,depth=(int)24,endianness=(int)4321,red_mask=(int)0xff0000, green_mask=(int)0x00ff00, blue_mask=(int)0x0000ff" static QImage generateThumbnailGstreamer(const QFileInfo &fileInfo) { GstElement *pipeline, *sink; gint width, height; GstBuffer *buffer; GError *error = NULL; gint64 duration, position; GstFormat format; GstStateChangeReturn ret; gboolean res; gst_init (NULL, NULL); QString descr = "uridecodebin uri=\"file://" + fileInfo.absoluteFilePath() + "\" ! ffmpegcolorspace ! videoscale ! appsink name=sink caps=\"" CAPS "\""; pipeline = gst_parse_launch (descr.toAscii(), &error); if (error != NULL) { qDebug() << "could not construct pipeline: " << error->message; g_error_free (error); return QImage(); } sink = gst_bin_get_by_name (GST_BIN (pipeline), "sink"); ret = gst_element_set_state (pipeline, GST_STATE_PAUSED); switch (ret) { case GST_STATE_CHANGE_FAILURE: qDebug() << "failed to play the file"; return QImage(); case GST_STATE_CHANGE_NO_PREROLL: qDebug() << "live sources not supported yet"; return QImage(); default: break; } ret = gst_element_get_state (pipeline, NULL, NULL, 5 * GST_SECOND); if (ret == GST_STATE_CHANGE_FAILURE) { qDebug() << "failed to play the file"; return QImage(); } /* get the duration */ format = GST_FORMAT_TIME; gst_element_query_duration (pipeline, &format, &duration); if (duration != -1) position = duration * 0.5; else position = 1 * GST_SECOND; gst_element_seek_simple (pipeline, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH, position); g_signal_emit_by_name (sink, "pull-preroll", &buffer, NULL); if (buffer) { GstCaps *caps; GstStructure *s; caps = GST_BUFFER_CAPS (buffer); if (!caps) { qDebug() << "could not get snapshot format"; return QImage(); } s = gst_caps_get_structure (caps, 0); res = gst_structure_get_int (s, "width", &width); res |= gst_structure_get_int (s, "height", &height); if (!res) { qDebug() << "could not get snapshot dimension"; return QImage(); } QImage image(GST_BUFFER_DATA (buffer), width, height, GST_ROUND_UP_4 (width * 3), QImage::Format_RGB888); gst_element_set_state (pipeline, GST_STATE_NULL); gst_object_unref (pipeline); const int previewWidth = Config::value("thumbnail-size", "256").toInt(); return image.width() <= previewWidth ? image: image.scaledToWidth(previewWidth, Qt::SmoothTransformation); } else { qDebug() << "could not make snapshot"; return QImage(); } } #endif static QByteArray generateThumbnail(const QFileInfo &fileInfo) { if (!Config::isEnabled("video-thumbnails", true)) return QByteArray(); QByteArray md5 = QCryptographicHash::hash("file://" + QFile::encodeName(fileInfo.absoluteFilePath()), QCryptographicHash::Md5).toHex(); QFileInfo thumbnailInfo(LibraryInfo::thumbnailPath() + md5 + ".png"); if (thumbnailInfo.exists()) return QUrl::fromLocalFile(thumbnailInfo.absoluteFilePath()).toEncoded(); #ifdef THUMBNAIL_GSTREAMER QImage image = generateThumbnailGstreamer(fileInfo); if (image.isNull()) return QByteArray(); image.save(thumbnailInfo.absoluteFilePath()); return QUrl::fromLocalFile(thumbnailInfo.absoluteFilePath()).toEncoded();; #else return QByteArray(); #endif } // clearly needs more advanced recognizer static QString determineTitle(const QFileInfo &info) { QString title = info.fileName(); title.remove(title.lastIndexOf('.'), title.length()); title.replace(QRegExp("[\\._\\-]"), " "); title.replace(QRegExp("xvid|rip|hdtv", Qt::CaseInsensitive), "" ); title.simplified(); title[0] = title[0].toUpper(); return title; } // ## See if DELETE+INSERT is the best approach. Sqlite3 supports INSERT OR IGNORE which could aslo be used // ## Also check other upsert methods QList<QSqlRecord> VideoParser::updateMediaInfos(const QList<QFileInfo> &fis, QSqlDatabase db) { QList<QSqlRecord> records; QSqlQuery query(db); ScopedTransaction transaction(db); foreach(const QFileInfo &fi, fis) { DEBUG << "Updating " << fi.absoluteFilePath(); query.prepare("DELETE FROM video WHERE filepath=:filepath"); query.bindValue(":filepath", fi.absoluteFilePath()); if (!query.exec()) qWarning() << query.lastError().text(); if (!query.prepare("INSERT INTO video (filepath, title, thumbnail, uri, directory, mtime, ctime, filesize) " " VALUES (:filepath, :title, :thumbnail, :uri, :directory, :mtime, :ctime, :filesize)")) { qWarning() << query.lastError().text(); return records; } query.bindValue(":filepath", fi.absoluteFilePath()); query.bindValue(":title", determineTitle(fi)); query.bindValue(":thumbnail", generateThumbnail(fi)); query.bindValue(":uri", QUrl::fromLocalFile(fi.absoluteFilePath()).toEncoded()); query.bindValue(":directory", fi.absolutePath() + '/'); query.bindValue(":mtime", fi.lastModified().toTime_t()); query.bindValue(":ctime", fi.created().toTime_t()); query.bindValue(":filesize", fi.size()); if (!query.exec()) qWarning() << query.lastError().text(); QSqlRecord record; record.append(QSqlField("id", QVariant::Int)); record.setValue(0, query.lastInsertId()); QMap<QString, QVariant> boundValues = query.boundValues(); for (QMap<QString, QVariant>::const_iterator it = boundValues.constBegin(); it != boundValues.constEnd(); ++it) { QString key = it.key().mid(1); // remove the ':' record.append(QSqlField(key, (QVariant::Type) it.value().type())); record.setValue(key, it.value()); } records.append(record); } emit databaseUpdated(records); return records; }
/**************************************************************************** This file is part of the QtMediaHub project on http://www.qtmediahub.com Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).* All rights reserved. Contact: Girish Ramakrishnan [email protected] Contact: Nokia Corporation [email protected] Contact: Nokia Corporation [email protected] You may use this file under the terms of the BSD license as follows: Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ****************************************************************************/ #include "videoparser.h" #include "qmh-config.h" #include "libraryinfo.h" #include <QtGui> #include <QtSql> #include "scopedtransaction.h" #define DEBUG if (0) qDebug() << __PRETTY_FUNCTION__ bool VideoParser::canRead(const QFileInfo &info) const { static QStringList supportedTypes = QStringList() << "avi" << "ogg" << "mp4" << "mpeg" << "mpg" << "mov" << "ogv" << "wmv" << "mkv" << Config::value("additional-video-extensions", QString()).split(","); return supportedTypes.contains(info.suffix()); } #ifdef THUMBNAIL_GSTREAMER #include <gst/gst.h> #define CAPS "video/x-raw-rgb,pixel-aspect-ratio=1/1,bpp=(int)24,depth=(int)24,endianness=(int)4321,red_mask=(int)0xff0000, green_mask=(int)0x00ff00, blue_mask=(int)0x0000ff" static QImage generateThumbnailGstreamer(const QFileInfo &fileInfo) { GstElement *pipeline, *sink; gint width, height; GstBuffer *buffer; GError *error = NULL; gint64 duration, position; GstFormat format; GstStateChangeReturn ret; gboolean res; gst_init (NULL, NULL); QString descr = "uridecodebin uri=\"file://" + fileInfo.absoluteFilePath() + "\" ! ffmpegcolorspace ! videoscale ! appsink name=sink caps=\"" CAPS "\""; pipeline = gst_parse_launch (descr.toAscii(), &error); if (error != NULL) { qDebug() << "could not construct pipeline: " << error->message; g_error_free (error); return QImage(); } sink = gst_bin_get_by_name (GST_BIN (pipeline), "sink"); ret = gst_element_set_state (pipeline, GST_STATE_PAUSED); switch (ret) { case GST_STATE_CHANGE_FAILURE: qDebug() << "failed to play the file"; return QImage(); case GST_STATE_CHANGE_NO_PREROLL: qDebug() << "live sources not supported yet"; return QImage(); default: break; } ret = gst_element_get_state (pipeline, NULL, NULL, 5 * GST_SECOND); if (ret == GST_STATE_CHANGE_FAILURE) { qDebug() << "failed to play the file"; return QImage(); } /* get the duration */ format = GST_FORMAT_TIME; gst_element_query_duration (pipeline, &format, &duration); if (duration != -1) position = duration * 0.5; else position = 1 * GST_SECOND; gst_element_seek_simple (pipeline, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH, position); g_signal_emit_by_name (sink, "pull-preroll", &buffer, NULL); if (buffer) { GstCaps *caps; GstStructure *s; caps = GST_BUFFER_CAPS (buffer); if (!caps) { qDebug() << "could not get snapshot format"; return QImage(); } s = gst_caps_get_structure (caps, 0); res = gst_structure_get_int (s, "width", &width); res |= gst_structure_get_int (s, "height", &height); if (!res) { qDebug() << "could not get snapshot dimension"; return QImage(); } QImage image(GST_BUFFER_DATA (buffer), width, height, GST_ROUND_UP_4 (width * 3), QImage::Format_RGB888); gst_element_set_state (pipeline, GST_STATE_NULL); gst_object_unref (pipeline); const int previewWidth = Config::value("thumbnail-size", "256").toInt(); return image.width() <= previewWidth ? image: image.scaledToWidth(previewWidth, Qt::SmoothTransformation); } else { qDebug() << "could not make snapshot"; return QImage(); } } #endif static QByteArray generateThumbnail(const QFileInfo &fileInfo) { if (!Config::isEnabled("video-thumbnails", true)) return QByteArray(); QByteArray md5 = QCryptographicHash::hash("file://" + QFile::encodeName(fileInfo.absoluteFilePath()), QCryptographicHash::Md5).toHex(); QFileInfo thumbnailInfo(LibraryInfo::thumbnailPath() + md5 + ".png"); if (thumbnailInfo.exists()) return QUrl::fromLocalFile(thumbnailInfo.absoluteFilePath()).toEncoded(); #ifdef THUMBNAIL_GSTREAMER QImage image = generateThumbnailGstreamer(fileInfo); if (image.isNull()) return QByteArray(); image.save(thumbnailInfo.absoluteFilePath()); return QUrl::fromLocalFile(thumbnailInfo.absoluteFilePath()).toEncoded();; #else return QByteArray(); #endif } // clearly needs more advanced recognizer static QString determineTitle(const QFileInfo &info) { QString title = info.fileName(); title.remove(title.lastIndexOf('.'), title.length()); title.replace(QRegExp("[\\._\\-]"), " "); title.replace(QRegExp("xvid|rip|hdtv", Qt::CaseInsensitive), "" ); title.simplified(); title[0] = title[0].toUpper(); return title; } // ## See if DELETE+INSERT is the best approach. Sqlite3 supports INSERT OR IGNORE which could aslo be used // ## Also check other upsert methods QList<QSqlRecord> VideoParser::updateMediaInfos(const QList<QFileInfo> &fis, QSqlDatabase db) { QList<QSqlRecord> records; QSqlQuery query(db); ScopedTransaction transaction(db); foreach(const QFileInfo &fi, fis) { DEBUG << "Updating " << fi.absoluteFilePath(); query.prepare("DELETE FROM video WHERE filepath=:filepath"); query.bindValue(":filepath", fi.absoluteFilePath()); if (!query.exec()) qWarning() << query.lastError().text(); if (!query.prepare("INSERT INTO video (filepath, title, thumbnail, uri, directory, mtime, ctime, filesize) " " VALUES (:filepath, :title, :thumbnail, :uri, :directory, :mtime, :ctime, :filesize)")) { qWarning() << query.lastError().text(); return records; } query.bindValue(":filepath", fi.absoluteFilePath()); query.bindValue(":title", determineTitle(fi)); query.bindValue(":thumbnail", generateThumbnail(fi)); query.bindValue(":uri", QUrl::fromLocalFile(fi.absoluteFilePath()).toEncoded()); query.bindValue(":directory", fi.absolutePath() + '/'); query.bindValue(":mtime", fi.lastModified().toTime_t()); query.bindValue(":ctime", fi.created().toTime_t()); query.bindValue(":filesize", fi.size()); if (!query.exec()) qWarning() << query.lastError().text(); QSqlRecord record; record.append(QSqlField("id", QVariant::Int)); record.setValue(0, query.lastInsertId()); QMap<QString, QVariant> boundValues = query.boundValues(); for (QMap<QString, QVariant>::const_iterator it = boundValues.constBegin(); it != boundValues.constEnd(); ++it) { QString key = it.key().mid(1); // remove the ':' record.append(QSqlField(key, (QVariant::Type) it.value().type())); record.setValue(key, it.value()); } records.append(record); } emit databaseUpdated(records); return records; }
Add support for specifying additional video formats on the command line
Add support for specifying additional video formats on the command line
C++
bsd-3-clause
qtmediahub/sasquatch,qtmediahub/sasquatch,qtmediahub/sasquatch
ab653fb1d2176a6202114ae6798cc9cb335843f5
src/driver.cpp
src/driver.cpp
//======================================================================= // Copyright (c) 2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <iostream> #include <cstdlib> #include <cstdio> #include <cstring> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> #include "RCSwitch.h" namespace { const std::size_t UNIX_PATH_MAX = 108; const std::size_t gpio_pin = 2; bool revoke_root(){ if (getuid() == 0) { if (setgid(1000) != 0){ std::cout << "asgard:dht11: setgid: Unable to drop group privileges: " << strerror(errno) << std::endl; return false; } if (setuid(1000) != 0){ std::cout << "asgard:dht11: setgid: Unable to drop user privileges: " << strerror(errno) << std::endl; return false; } } if (setuid(0) != -1){ std::cout << "asgard:dht11: managed to regain root privileges, exiting..." << std::endl; return false; } return true; } } //end of anonymous namespace int main(){ RCSwitch rc_switch; //Run the wiringPi setup (as root) wiringPiSetup(); rc_switch = RCSwitch(); rc_switch.enableReceive(gpio_pin); //Drop root privileges and run as pi:pi again if(!revoke_root()){ std::cout << "asgard:dht11: unable to revoke root privileges, exiting..." << std::endl; return 1; } //Open the socket auto socket_fd = socket(PF_UNIX, SOCK_STREAM, 0); if(socket_fd < 0){ std::cout << "asgard:rf: socket() failed" << std::endl; return 1; } //Init the address struct sockaddr_un address; memset(&address, 0, sizeof(struct sockaddr_un)); address.sun_family = AF_UNIX; snprintf(address.sun_path, UNIX_PATH_MAX, "/tmp/asgard_socket"); //Connect to the server if(connect(socket_fd, (struct sockaddr *) &address, sizeof(struct sockaddr_un)) != 0){ std::cout << "asgard:rf: connect() failed" << std::endl; return 1; } while(true) { if (rc_switch.available()) { int value = rc_switch.getReceivedValue(); if (value == 0) { printf("Wrong encoding\n"); } else { printf("Received value : %i\n", rc_switch.getReceivedValue() ); } rc_switch.resetAvailable(); } delay(100); //TODO Perhaps this is not a good idea } //Close the socket close(socket_fd); return 0; }
//======================================================================= // Copyright (c) 2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <iostream> #include <cstdlib> #include <cstdio> #include <cstring> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> #include "RCSwitch.h" namespace { const std::size_t UNIX_PATH_MAX = 108; const std::size_t gpio_pin = 2; //Buffers char write_buffer[4096]; char receive_buffer[4096]; bool revoke_root(){ if (getuid() == 0) { if (setgid(1000) != 0){ std::cout << "asgard:dht11: setgid: Unable to drop group privileges: " << strerror(errno) << std::endl; return false; } if (setuid(1000) != 0){ std::cout << "asgard:dht11: setgid: Unable to drop user privileges: " << strerror(errno) << std::endl; return false; } } if (setuid(0) != -1){ std::cout << "asgard:dht11: managed to regain root privileges, exiting..." << std::endl; return false; } return true; } void read_data(RCSwitch& rc_switch, int socket_fd, int rf_button_1){ if (rc_switch.available()) { int value = rc_switch.getReceivedValue(); if (value) { if(rc_switch.getReceivedvalue() == 1135920){ //Send the event to the server auto nbytes = snprintf(write_buffer, 4096, "EVENT %d 1", rf_button_1); write(socket_fd, write_buffer, nbytes); } else { printf("asgard:rf:received unknown value: %i\n", rc_switch.getReceivedValue()); } } else { printf("asgard:rf:received unknown encoding\n"); } rc_switch.resetAvailable(); } } } //end of anonymous namespace int main(){ RCSwitch rc_switch; //Run the wiringPi setup (as root) wiringPiSetup(); rc_switch = RCSwitch(); rc_switch.enableReceive(gpio_pin); //Drop root privileges and run as pi:pi again if(!revoke_root()){ std::cout << "asgard:dht11: unable to revoke root privileges, exiting..." << std::endl; return 1; } //Open the socket auto socket_fd = socket(PF_UNIX, SOCK_STREAM, 0); if(socket_fd < 0){ std::cout << "asgard:rf: socket() failed" << std::endl; return 1; } //Init the address struct sockaddr_un address; memset(&address, 0, sizeof(struct sockaddr_un)); address.sun_family = AF_UNIX; snprintf(address.sun_path, UNIX_PATH_MAX, "/tmp/asgard_socket"); //Connect to the server if(connect(socket_fd, (struct sockaddr *) &address, sizeof(struct sockaddr_un)) != 0){ std::cout << "asgard:rf: connect() failed" << std::endl; return 1; } //Register the actuator auto nbytes = snprintf(write_buffer, 4096, "REG_ACTUATOR rf_button_1"); write(socket_fd, write_buffer, nbytes); //Get the response from the server nbytes = read(socket_fd, receive_buffer, 4096); if(!nbytes){ std::cout << "asgard:ir: failed to register actuator" << std::endl; return 1; } receive_buffer[nbytes] = 0; //Parse the actuator id int rf_button_1 = atoi(receive_buffer); std::cout << "remote actuator: " << rf_button_1 << std::endl; while(true) { read_data(rc_switch, socket_fd, rf_button_1); delay(100); //TODO Perhaps this is not a good idea } //Close the socket close(socket_fd); return 0; }
Integrate into asgard system
Integrate into asgard system
C++
mit
stephane-ly/asgard-rf-driver,wichtounet/asgard-rf-driver
b05ac741e2e944e03ce68155fff931991eb21cde
BB10-Cordova/Template/plugin/src/blackberry10/native/src/template_js.cpp
BB10-Cordova/Template/plugin/src/blackberry10/native/src/template_js.cpp
/* * Copyright (c) 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. */ #include <string> #include "../public/tokenizer.h" #include "ExtractZIPFile_js.hpp" #include "ExtractZIPFile_ndk.hpp" using namespace std; /** * Default constructor. */ TemplateJS::TemplateJS(const std::string& id) : m_id(id) { m_pLogger = new webworks::Logger("TemplateJS", this); m_pTemplateController = new webworks::TemplateNDK(this); } /** * TemplateJS destructor. */ TemplateJS::~TemplateJS() { if (m_pTemplateController) delete m_pTemplateController; if (m_pLogger) delete m_pLogger; } webworks::Logger* TemplateJS::getLog() { return m_pLogger; } /** * This method returns the list of objects implemented by this native * extension. */ char* onGetObjList() { static char name[] = "TemplateJS"; return name; } /** * This method is used by JNext to instantiate the TemplateJS object when * an object is created on the JavaScript server side. */ JSExt* onCreateObject(const string& className, const string& id) { if (className == "TemplateJS") { return new TemplateJS(id); } return NULL; } /** * Method used by JNext to determine if the object can be deleted. */ bool TemplateJS::CanDelete() { return true; } /** * It will be called from JNext JavaScript side with passed string. * This method implements the interface for the JavaScript to native binding * for invoking native code. This method is triggered when JNext.invoke is * called on the JavaScript side with this native objects id. */ string TemplateJS::InvokeMethod(const string& command) { // format must be: "command callbackId params" size_t commandIndex = command.find_first_of(" "); std::string strCommand = command.substr(0, commandIndex); size_t callbackIndex = command.find_first_of(" ", commandIndex + 1); std::string callbackId = command.substr(commandIndex + 1, callbackIndex - commandIndex - 1); std::string arg = command.substr(callbackIndex + 1, command.length()); // based on the command given, run the appropriate method in template_ndk.cpp if (strCommand == "testString") { return m_pTemplateController->templateTestString(); } else if (strCommand == "testStringInput") { return m_pTemplateController->templateTestString(arg); } else if (strCommand == "templateProperty") { // if arg exists we are setting property if (arg != strCommand) { m_pTemplateController->setTemplateProperty(arg); } else { return m_pTemplateController->getTemplateProperty(); } } else if (strCommand == "testAsync") { m_pTemplateController->templateTestAsync(callbackId, arg); } else if (strCommand == "templateStartThread") { return m_pTemplateController->templateStartThread(callbackId); } else if (strCommand == "templateStopThread") { return m_pTemplateController->templateStopThread(); } strCommand.append(";"); strCommand.append(command); return strCommand; } // Notifies JavaScript of an event void TemplateJS::NotifyEvent(const std::string& event) { std::string eventString = m_id + " "; eventString.append(event); SendPluginEvent(eventString.c_str(), m_pContext); }
/* * Copyright (c) 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. */ #include <string> #include "../public/tokenizer.h" #include "template_js.hpp" #include "template_ndk.hpp" using namespace std; /** * Default constructor. */ TemplateJS::TemplateJS(const std::string& id) : m_id(id) { m_pLogger = new webworks::Logger("TemplateJS", this); m_pTemplateController = new webworks::TemplateNDK(this); } /** * TemplateJS destructor. */ TemplateJS::~TemplateJS() { if (m_pTemplateController) delete m_pTemplateController; if (m_pLogger) delete m_pLogger; } webworks::Logger* TemplateJS::getLog() { return m_pLogger; } /** * This method returns the list of objects implemented by this native * extension. */ char* onGetObjList() { static char name[] = "TemplateJS"; return name; } /** * This method is used by JNext to instantiate the TemplateJS object when * an object is created on the JavaScript server side. */ JSExt* onCreateObject(const string& className, const string& id) { if (className == "TemplateJS") { return new TemplateJS(id); } return NULL; } /** * Method used by JNext to determine if the object can be deleted. */ bool TemplateJS::CanDelete() { return true; } /** * It will be called from JNext JavaScript side with passed string. * This method implements the interface for the JavaScript to native binding * for invoking native code. This method is triggered when JNext.invoke is * called on the JavaScript side with this native objects id. */ string TemplateJS::InvokeMethod(const string& command) { // format must be: "command callbackId params" size_t commandIndex = command.find_first_of(" "); std::string strCommand = command.substr(0, commandIndex); size_t callbackIndex = command.find_first_of(" ", commandIndex + 1); std::string callbackId = command.substr(commandIndex + 1, callbackIndex - commandIndex - 1); std::string arg = command.substr(callbackIndex + 1, command.length()); // based on the command given, run the appropriate method in template_ndk.cpp if (strCommand == "testString") { return m_pTemplateController->templateTestString(); } else if (strCommand == "testStringInput") { return m_pTemplateController->templateTestString(arg); } else if (strCommand == "templateProperty") { // if arg exists we are setting property if (arg != strCommand) { m_pTemplateController->setTemplateProperty(arg); } else { return m_pTemplateController->getTemplateProperty(); } } else if (strCommand == "testAsync") { m_pTemplateController->templateTestAsync(callbackId, arg); } else if (strCommand == "templateStartThread") { return m_pTemplateController->templateStartThread(callbackId); } else if (strCommand == "templateStopThread") { return m_pTemplateController->templateStopThread(); } strCommand.append(";"); strCommand.append(command); return strCommand; } // Notifies JavaScript of an event void TemplateJS::NotifyEvent(const std::string& event) { std::string eventString = m_id + " "; eventString.append(event); SendPluginEvent(eventString.c_str(), m_pContext); }
Revert includes that were accidentally changed with another pull request
Revert includes that were accidentally changed with another pull request
C++
apache-2.0
jcmurray/WebWorks-Community-APIs,Jayapraju/WebWorks-Community-APIs,timwindsor/WebWorks-Community-APIs,T-M-C/WebWorks-Community-APIs,T-M-C/WebWorks-Community-APIs,gamerDecathlete/WebWorks-Community-APIs,blackberry/WebWorks-Community-APIs,blackberry/WebWorks-Community-APIs,Makoz/WebWorks-Community-APIs,gamerDecathlete/WebWorks-Community-APIs,T-M-C/WebWorks-Community-APIs,Jayapraju/WebWorks-Community-APIs,blackberry/WebWorks-Community-APIs,jcmurray/WebWorks-Community-APIs,gamerDecathlete/WebWorks-Community-APIs,parker-mar/WebWorks-Community-APIs,Jayapraju/WebWorks-Community-APIs,Makoz/WebWorks-Community-APIs,timwindsor/WebWorks-Community-APIs,Makoz/WebWorks-Community-APIs,timwindsor/WebWorks-Community-APIs,blackberry/WebWorks-Community-APIs,jcmurray/WebWorks-Community-APIs,parker-mar/WebWorks-Community-APIs,parker-mar/WebWorks-Community-APIs,Jayapraju/WebWorks-Community-APIs,Makoz/WebWorks-Community-APIs,timwindsor/WebWorks-Community-APIs,jcmurray/WebWorks-Community-APIs,T-M-C/WebWorks-Community-APIs,Jayapraju/WebWorks-Community-APIs,jcmurray/WebWorks-Community-APIs,gamerDecathlete/WebWorks-Community-APIs,blackberry/WebWorks-Community-APIs,Makoz/WebWorks-Community-APIs,timwindsor/WebWorks-Community-APIs,timwindsor/WebWorks-Community-APIs,gamerDecathlete/WebWorks-Community-APIs,jcmurray/WebWorks-Community-APIs,Jayapraju/WebWorks-Community-APIs,gamerDecathlete/WebWorks-Community-APIs,parker-mar/WebWorks-Community-APIs,parker-mar/WebWorks-Community-APIs,blackberry/WebWorks-Community-APIs,parker-mar/WebWorks-Community-APIs,T-M-C/WebWorks-Community-APIs,Makoz/WebWorks-Community-APIs,T-M-C/WebWorks-Community-APIs
720f723cc33abc3d827a11f0ed0c02ecc04e1070
plugins/testplugin/testmain.cpp
plugins/testplugin/testmain.cpp
#include "testplugin.h" int main() { sgraph::sgmanager man; std::vector<std::string> ac1streamsin; std::vector<std::string> ac1streamsout; ac1streamsout.push_back("stream1"); std::vector<std::string> ac2streamsin; std::vector<std::string> ac2streamsout; ac2streamsin.push_back("stream1"); ac2streamsout.push_back("stream2"); std::vector<std::string> ac3streamsin; std::vector<std::string> ac3streamsout; ac3streamsin.push_back("stream2"); man.addActor("provider",new testprovider(1,1,1), ac1streamsin, ac1streamsout); man.addActor("transformer",new testtransformer(1,-1,7), ac2streamsin, ac2streamsout); man.addActor("consumer",new testconsumer(1,sgraph::sgtimeunit_second*3,1), ac3streamsin, ac3streamsout); std::vector<std::string> actorsretrieve; actorsretrieve.push_back("provider"); actorsretrieve.push_back("transformer"); actorsretrieve.push_back("consumer"); for (sgraph::sgactor* actor : man.getActors(actorsretrieve)) { std::cout << "Actorname: " << actor->getName() << std::endl; } man.start(); std::cout << "simplegraph test started, press any key to exit" << std::endl; getchar(); return 0; }
#include "testplugin.h" int main() { sgraph::sgmanager man; std::vector<std::string> ac1streamsin; std::vector<std::string> ac1streamsout; ac1streamsout.push_back("stream1"); std::vector<std::string> ac2streamsin; std::vector<std::string> ac2streamsout; ac2streamsin.push_back("stream1"); ac2streamsout.push_back("stream2"); std::vector<std::string> ac3streamsin; std::vector<std::string> ac3streamsout; ac3streamsin.push_back("stream2"); man.addActor("provider",new testprovider(1,1,1), ac1streamsin, ac1streamsout); man.addActor("transformer",new testtransformer(1,-1,8), ac2streamsin, ac2streamsout); man.addActor("consumer",new testconsumer(10,sgraph::sgtimeunit_second*3,1), ac3streamsin, ac3streamsout); std::vector<std::string> actorsretrieve; actorsretrieve.push_back("provider"); actorsretrieve.push_back("transformer"); actorsretrieve.push_back("consumer"); for (sgraph::sgactor* actor : man.getActors(actorsretrieve)) { std::cout << "Actorname: " << actor->getName() << std::endl; } man.start(); std::cout << "simplegraph test started, press any key to exit" << std::endl; getchar(); return 0; }
update testmain with parallelized example
update testmain with parallelized example
C++
bsd-3-clause
devkral/simplegraph
41b56f20b853c12a944da87ee0dddce77247f561
src/modules/mavlink/streams/RAW_RPM.hpp
src/modules/mavlink/streams/RAW_RPM.hpp
/**************************************************************************** * * Copyright (c) 2020 PX4 Development Team. 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 PX4 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. * ****************************************************************************/ #ifndef RAW_RPM_HPP #define RAW_RPM_HPP #include <uORB/topics/rpm.h> class MavlinkStreamRawRpm : public MavlinkStream { public: static MavlinkStream *new_instance(Mavlink *mavlink) { return new MavlinkStreamRawRpm(mavlink); } static constexpr const char *get_name_static() { return "RAW_RPM"; } static constexpr uint16_t get_id_static() { return MAVLINK_MSG_ID_RAW_RPM; } const char *get_name() const override { return get_name_static(); } uint16_t get_id() override { return get_id_static(); } unsigned get_size() override { return _rpm_sub.advertised() ? MAVLINK_MSG_ID_RAW_RPM + MAVLINK_NUM_NON_PAYLOAD_BYTES : 0; } private: explicit MavlinkStreamRawRpm(Mavlink *mavlink) : MavlinkStream(mavlink) {} uORB::Subscription _rpm_sub{ORB_ID(rpm)}; bool send() override { rpm_s rpm; if (_rpm_sub.update(&rpm)) { mavlink_raw_rpm_t msg{}; msg.frequency = rpm.indicated_frequency_rpm; mavlink_msg_raw_rpm_send_struct(_mavlink->get_channel(), &msg); return true; } return false; } }; #endif // RAW_RPM_HPP
/**************************************************************************** * * Copyright (c) 2020 PX4 Development Team. 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 PX4 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. * ****************************************************************************/ #ifndef RAW_RPM_HPP #define RAW_RPM_HPP #include <uORB/topics/rpm.h> class MavlinkStreamRawRpm : public MavlinkStream { public: static MavlinkStream *new_instance(Mavlink *mavlink) { return new MavlinkStreamRawRpm(mavlink); } static constexpr const char *get_name_static() { return "RAW_RPM"; } static constexpr uint16_t get_id_static() { return MAVLINK_MSG_ID_RAW_RPM; } const char *get_name() const override { return get_name_static(); } uint16_t get_id() override { return get_id_static(); } unsigned get_size() override { return _rpm_sub.advertised() ? (MAVLINK_MSG_ID_RAW_RPM_LEN + MAVLINK_NUM_NON_PAYLOAD_BYTES) : 0; } private: explicit MavlinkStreamRawRpm(Mavlink *mavlink) : MavlinkStream(mavlink) {} uORB::Subscription _rpm_sub{ORB_ID(rpm)}; bool send() override { rpm_s rpm; if (_rpm_sub.update(&rpm)) { mavlink_raw_rpm_t msg{}; msg.frequency = rpm.indicated_frequency_rpm; mavlink_msg_raw_rpm_send_struct(_mavlink->get_channel(), &msg); return true; } return false; } }; #endif // RAW_RPM_HPP
fix raw rpm message size
mavlink_messages: fix raw rpm message size
C++
bsd-3-clause
krbeverx/Firmware,acfloria/Firmware,krbeverx/Firmware,acfloria/Firmware,acfloria/Firmware,acfloria/Firmware,krbeverx/Firmware,acfloria/Firmware,krbeverx/Firmware,krbeverx/Firmware,krbeverx/Firmware,acfloria/Firmware,krbeverx/Firmware,acfloria/Firmware
a96501a26ac01a69ec901631227ed32f32af69fc
src/engine.cpp
src/engine.cpp
/* * Copyright 2018 Andrei Pangin * * 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 "engine.h" #include "stackFrame.h" Error Engine::check(Arguments& args) { return Error::OK; } CStack Engine::cstack() { return CSTACK_FP; } int Engine::getNativeTrace(void* ucontext, int tid, const void** callchain, int max_depth, CodeCache* java_methods, CodeCache* runtime_stubs) { if (ucontext == NULL) { return 0; } StackFrame frame(ucontext); const void* pc = (const void*)frame.pc(); uintptr_t fp = frame.fp(); uintptr_t prev_fp = (uintptr_t)&fp; uintptr_t bottom = prev_fp + 0x100000; int depth = 0; const void* const valid_pc = (const void*)0x1000; // Walk until the bottom of the stack or until the first Java frame while (depth < max_depth && pc >= valid_pc) { if (java_methods->contains(pc) || runtime_stubs->contains(pc)) { break; } callchain[depth++] = pc; // Check if the next frame is below on the current stack if (fp <= prev_fp || fp >= prev_fp + 0x40000 || fp >= bottom) { break; } // Frame pointer must be word aligned if ((fp & (sizeof(uintptr_t) - 1)) != 0) { break; } prev_fp = fp; pc = ((const void**)fp)[1]; fp = ((uintptr_t*)fp)[0]; } return depth; }
/* * Copyright 2018 Andrei Pangin * * 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 "engine.h" #include "stackFrame.h" Error Engine::check(Arguments& args) { return Error::OK; } CStack Engine::cstack() { return CSTACK_FP; } int Engine::getNativeTrace(void* ucontext, int tid, const void** callchain, int max_depth, CodeCache* java_methods, CodeCache* runtime_stubs) { const void* pc; uintptr_t fp; uintptr_t prev_fp = (uintptr_t)&fp; uintptr_t bottom = prev_fp + 0x100000; if (ucontext == NULL) { pc = __builtin_return_address(0); fp = (uintptr_t)__builtin_frame_address(1); } else { StackFrame frame(ucontext); pc = (const void*)frame.pc(); fp = frame.fp(); } int depth = 0; const void* const valid_pc = (const void*)0x1000; // Walk until the bottom of the stack or until the first Java frame while (depth < max_depth && pc >= valid_pc) { if (java_methods->contains(pc) || runtime_stubs->contains(pc)) { break; } callchain[depth++] = pc; // Check if the next frame is below on the current stack if (fp <= prev_fp || fp >= prev_fp + 0x40000 || fp >= bottom) { break; } // Frame pointer must be word aligned if ((fp & (sizeof(uintptr_t) - 1)) != 0) { break; } prev_fp = fp; pc = ((const void**)fp)[1]; fp = ((uintptr_t*)fp)[0]; } return depth; }
Enable native stacks for non-signal events, e.g. lock profiling
Enable native stacks for non-signal events, e.g. lock profiling
C++
apache-2.0
apangin/async-profiler,apangin/async-profiler,jvm-profiling-tools/async-profiler,apangin/async-profiler,jvm-profiling-tools/async-profiler,jvm-profiling-tools/async-profiler,jvm-profiling-tools/async-profiler,jvm-profiling-tools/async-profiler,apangin/async-profiler
782ae6cbaf5f70b6d8332a0fe81849c294387c7d
Modules/Applications/AppClassification/app/otbPolygonClassStatistics.cxx
Modules/Applications/AppClassification/app/otbPolygonClassStatistics.cxx
/* * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "otbOGRDataToClassStatisticsFilter.h" #include "otbStatisticsXMLFileWriter.h" #include "otbGeometriesProjectionFilter.h" #include "otbGeometriesSet.h" #include "otbWrapperElevationParametersHandler.h" namespace otb { namespace Wrapper { /** Utility function to negate std::isalnum */ bool IsNotAlphaNum(char c) { return !std::isalnum(c); } class PolygonClassStatistics : public Application { public: /** Standard class typedefs. */ typedef PolygonClassStatistics Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(PolygonClassStatistics, otb::Application); /** Filters typedef */ typedef otb::OGRDataToClassStatisticsFilter<FloatVectorImageType,UInt8ImageType> FilterType; typedef otb::StatisticsXMLFileWriter<FloatVectorImageType::PixelType> StatWriterType; typedef otb::GeometriesSet GeometriesType; typedef otb::GeometriesProjectionFilter ProjectionFilterType; private: PolygonClassStatistics() { } void DoInit() ITK_OVERRIDE { SetName("PolygonClassStatistics"); SetDescription("Computes statistics on a training polygon set."); // Documentation SetDocName("Polygon Class Statistics"); SetDocLongDescription("The application processes a set of geometries " "intended for training (they should have a field giving the associated " "class). The geometries are analysed against a support image to compute " "statistics : \n" " - number of samples per class\n" " - number of samples per geometry\n" "An optional raster mask can be used to discard samples. Different types" " of geometry are supported : polygons, lines, points. The behaviour is " "different for each type of geometry :\n" " - polygon: select pixels whose center is inside the polygon\n" " - lines : select pixels intersecting the line\n" " - points : select closest pixel to the point"); SetDocLimitations("None"); SetDocAuthors("OTB-Team"); SetDocSeeAlso(" "); AddDocTag(Tags::Learning); AddParameter(ParameterType_InputImage, "in", "InputImage"); SetParameterDescription("in", "Support image that will be classified"); AddParameter(ParameterType_InputImage, "mask", "InputMask"); SetParameterDescription("mask", "Validity mask (only pixels corresponding to a mask value greater than 0 will be used for statistics)"); MandatoryOff("mask"); AddParameter(ParameterType_InputFilename, "vec", "Input vectors"); SetParameterDescription("vec","Input geometries to analyse"); AddParameter(ParameterType_OutputFilename, "out", "Output Statistics"); SetParameterDescription("out","Output file to store statistics (XML format)"); AddParameter(ParameterType_ListView, "field", "Field Name"); SetParameterDescription("field","Name of the field carrying the class name in the input vectors."); SetListViewSingleSelectionMode("field",true); AddParameter(ParameterType_Int, "layer", "Layer Index"); SetParameterDescription("layer", "Layer index to read in the input vector file."); MandatoryOff("layer"); SetDefaultParameterInt("layer",0); ElevationParametersHandler::AddElevationParameters(this, "elev"); AddRAMParameter(); // Doc example parameter settings SetDocExampleParameterValue("in", "support_image.tif"); SetDocExampleParameterValue("vec", "variousVectors.sqlite"); SetDocExampleParameterValue("field", "label"); SetDocExampleParameterValue("out","polygonStat.xml"); SetOfficialDocLink(); } void DoUpdateParameters() ITK_OVERRIDE { if ( HasValue("vec") ) { std::string vectorFile = GetParameterString("vec"); ogr::DataSource::Pointer ogrDS = ogr::DataSource::New(vectorFile, ogr::DataSource::Modes::Read); ogr::Layer layer = ogrDS->GetLayer(this->GetParameterInt("layer")); ogr::Feature feature = layer.ogr().GetNextFeature(); ClearChoices("field"); for(int iField=0; iField<feature.ogr().GetFieldCount(); iField++) { std::string key, item = feature.ogr().GetFieldDefnRef(iField)->GetNameRef(); key = item; std::string::iterator end = std::remove_if(key.begin(),key.end(),IsNotAlphaNum); std::transform(key.begin(), end, key.begin(), tolower); OGRFieldType fieldType = feature.ogr().GetFieldDefnRef(iField)->GetType(); if(fieldType == OFTString || fieldType == OFTInteger || ogr::version_proxy::IsOFTInteger64(fieldType)) { std::string tmpKey="field."+key.substr(0, end - key.begin()); AddChoice(tmpKey,item); } } } } void DoExecute() ITK_OVERRIDE { otb::ogr::DataSource::Pointer vectors = otb::ogr::DataSource::New(this->GetParameterString("vec")); // Retrieve the field name std::vector<int> selectedCFieldIdx = GetSelectedItems("field"); if(selectedCFieldIdx.empty()) { otbAppLogFATAL(<<"No field has been selected for data labelling!"); } std::vector<std::string> cFieldNames = GetChoiceNames("field"); std::string fieldName = cFieldNames[selectedCFieldIdx.front()]; otb::Wrapper::ElevationParametersHandler::SetupDEMHandlerFromElevationParameters(this,"elev"); // Reproject geometries FloatVectorImageType::Pointer inputImg = this->GetParameterImage("in"); std::string imageProjectionRef = inputImg->GetProjectionRef(); FloatVectorImageType::ImageKeywordlistType imageKwl = inputImg->GetImageKeywordlist(); std::string vectorProjectionRef = vectors->GetLayer(GetParameterInt("layer")).GetProjectionRef(); otb::ogr::DataSource::Pointer reprojVector = vectors; GeometriesType::Pointer inputGeomSet; ProjectionFilterType::Pointer geometriesProjFilter; GeometriesType::Pointer outputGeomSet; bool doReproj = true; // don't reproject for these cases if (vectorProjectionRef.empty() || (imageProjectionRef == vectorProjectionRef) || (imageProjectionRef.empty() && imageKwl.GetSize() == 0)) doReproj = false; if (doReproj) { inputGeomSet = GeometriesType::New(vectors); reprojVector = otb::ogr::DataSource::New(); outputGeomSet = GeometriesType::New(reprojVector); // Filter instantiation geometriesProjFilter = ProjectionFilterType::New(); geometriesProjFilter->SetInput(inputGeomSet); if (imageProjectionRef.empty()) { geometriesProjFilter->SetOutputKeywordList(inputImg->GetImageKeywordlist()); // nec qd capteur } geometriesProjFilter->SetOutputProjectionRef(imageProjectionRef); geometriesProjFilter->SetOutput(outputGeomSet); otbAppLogINFO("Reprojecting input vectors..."); geometriesProjFilter->Update(); } FilterType::Pointer filter = FilterType::New(); filter->SetInput(this->GetParameterImage("in")); if (IsParameterEnabled("mask") && HasValue("mask")) { filter->SetMask(this->GetParameterImage<UInt8ImageType>("mask")); } filter->SetOGRData(reprojVector); filter->SetFieldName(fieldName); filter->SetLayerIndex(this->GetParameterInt("layer")); filter->GetStreamer()->SetAutomaticAdaptativeStreaming(GetParameterInt("ram")); AddProcess(filter->GetStreamer(),"Analyse polygons..."); filter->Update(); FilterType::ClassCountMapType &classCount = filter->GetClassCountOutput()->Get(); FilterType::PolygonSizeMapType &polySize = filter->GetPolygonSizeOutput()->Get(); StatWriterType::Pointer statWriter = StatWriterType::New(); statWriter->SetFileName(this->GetParameterString("out")); statWriter->AddInputMap<FilterType::ClassCountMapType>("samplesPerClass",classCount); statWriter->AddInputMap<FilterType::PolygonSizeMapType>("samplesPerVector",polySize); statWriter->Update(); } }; } // end of namespace Wrapper } // end of namespace otb OTB_APPLICATION_EXPORT(otb::Wrapper::PolygonClassStatistics)
/* * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "otbOGRDataToClassStatisticsFilter.h" #include "otbStatisticsXMLFileWriter.h" #include "otbGeometriesProjectionFilter.h" #include "otbGeometriesSet.h" #include "otbWrapperElevationParametersHandler.h" namespace otb { namespace Wrapper { /** Utility function to negate std::isalnum */ bool IsNotAlphaNum(char c) { return !std::isalnum(c); } class PolygonClassStatistics : public Application { public: /** Standard class typedefs. */ typedef PolygonClassStatistics Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(PolygonClassStatistics, otb::Application); /** Filters typedef */ typedef otb::OGRDataToClassStatisticsFilter<FloatVectorImageType,UInt8ImageType> FilterType; typedef otb::StatisticsXMLFileWriter<FloatVectorImageType::PixelType> StatWriterType; typedef otb::GeometriesSet GeometriesType; typedef otb::GeometriesProjectionFilter ProjectionFilterType; private: PolygonClassStatistics() { } void DoInit() ITK_OVERRIDE { SetName("PolygonClassStatistics"); SetDescription("Computes statistics on a training polygon set."); // Documentation SetDocName("Polygon Class Statistics"); SetDocLongDescription("The application processes a set of geometries " "intended for training (they should have a field giving the associated " "class). The geometries are analyzed against a support image to compute " "statistics : \n" " - number of samples per class\n" " - number of samples per geometry\n" "An optional raster mask can be used to discard samples. Different types" " of geometry are supported : polygons, lines, points. The behaviour is " "different for each type of geometry :\n" " - polygon: select pixels whose center is inside the polygon\n" " - lines : select pixels intersecting the line\n" " - points : select closest pixel to the point"); SetDocLimitations("None"); SetDocAuthors("OTB-Team"); SetDocSeeAlso(" "); AddDocTag(Tags::Learning); AddParameter(ParameterType_InputImage, "in", "InputImage"); SetParameterDescription("in", "Support image that will be classified"); AddParameter(ParameterType_InputImage, "mask", "InputMask"); SetParameterDescription("mask", "Validity mask (only pixels corresponding to a mask value greater than 0 will be used for statistics)"); MandatoryOff("mask"); AddParameter(ParameterType_InputFilename, "vec", "Input vectors"); SetParameterDescription("vec","Input geometries to analyze"); AddParameter(ParameterType_OutputFilename, "out", "Output Statistics"); SetParameterDescription("out","Output file to store statistics (XML format)"); AddParameter(ParameterType_ListView, "field", "Field Name"); SetParameterDescription("field","Name of the field carrying the class name in the input vectors."); SetListViewSingleSelectionMode("field",true); AddParameter(ParameterType_Int, "layer", "Layer Index"); SetParameterDescription("layer", "Layer index to read in the input vector file."); MandatoryOff("layer"); SetDefaultParameterInt("layer",0); ElevationParametersHandler::AddElevationParameters(this, "elev"); AddRAMParameter(); // Doc example parameter settings SetDocExampleParameterValue("in", "support_image.tif"); SetDocExampleParameterValue("vec", "variousVectors.sqlite"); SetDocExampleParameterValue("field", "label"); SetDocExampleParameterValue("out","polygonStat.xml"); SetOfficialDocLink(); } void DoUpdateParameters() ITK_OVERRIDE { if ( HasValue("vec") ) { std::string vectorFile = GetParameterString("vec"); ogr::DataSource::Pointer ogrDS = ogr::DataSource::New(vectorFile, ogr::DataSource::Modes::Read); ogr::Layer layer = ogrDS->GetLayer(this->GetParameterInt("layer")); ogr::Feature feature = layer.ogr().GetNextFeature(); ClearChoices("field"); for(int iField=0; iField<feature.ogr().GetFieldCount(); iField++) { std::string key, item = feature.ogr().GetFieldDefnRef(iField)->GetNameRef(); key = item; std::string::iterator end = std::remove_if(key.begin(),key.end(),IsNotAlphaNum); std::transform(key.begin(), end, key.begin(), tolower); OGRFieldType fieldType = feature.ogr().GetFieldDefnRef(iField)->GetType(); if(fieldType == OFTString || fieldType == OFTInteger || ogr::version_proxy::IsOFTInteger64(fieldType)) { std::string tmpKey="field."+key.substr(0, end - key.begin()); AddChoice(tmpKey,item); } } } } void DoExecute() ITK_OVERRIDE { otb::ogr::DataSource::Pointer vectors = otb::ogr::DataSource::New(this->GetParameterString("vec")); // Retrieve the field name std::vector<int> selectedCFieldIdx = GetSelectedItems("field"); if(selectedCFieldIdx.empty()) { otbAppLogFATAL(<<"No field has been selected for data labelling!"); } std::vector<std::string> cFieldNames = GetChoiceNames("field"); std::string fieldName = cFieldNames[selectedCFieldIdx.front()]; otb::Wrapper::ElevationParametersHandler::SetupDEMHandlerFromElevationParameters(this,"elev"); // Reproject geometries FloatVectorImageType::Pointer inputImg = this->GetParameterImage("in"); std::string imageProjectionRef = inputImg->GetProjectionRef(); FloatVectorImageType::ImageKeywordlistType imageKwl = inputImg->GetImageKeywordlist(); std::string vectorProjectionRef = vectors->GetLayer(GetParameterInt("layer")).GetProjectionRef(); otb::ogr::DataSource::Pointer reprojVector = vectors; GeometriesType::Pointer inputGeomSet; ProjectionFilterType::Pointer geometriesProjFilter; GeometriesType::Pointer outputGeomSet; bool doReproj = true; // don't reproject for these cases if (vectorProjectionRef.empty() || (imageProjectionRef == vectorProjectionRef) || (imageProjectionRef.empty() && imageKwl.GetSize() == 0)) doReproj = false; if (doReproj) { inputGeomSet = GeometriesType::New(vectors); reprojVector = otb::ogr::DataSource::New(); outputGeomSet = GeometriesType::New(reprojVector); // Filter instantiation geometriesProjFilter = ProjectionFilterType::New(); geometriesProjFilter->SetInput(inputGeomSet); if (imageProjectionRef.empty()) { geometriesProjFilter->SetOutputKeywordList(inputImg->GetImageKeywordlist()); // nec qd capteur } geometriesProjFilter->SetOutputProjectionRef(imageProjectionRef); geometriesProjFilter->SetOutput(outputGeomSet); otbAppLogINFO("Reprojecting input vectors..."); geometriesProjFilter->Update(); } FilterType::Pointer filter = FilterType::New(); filter->SetInput(this->GetParameterImage("in")); if (IsParameterEnabled("mask") && HasValue("mask")) { filter->SetMask(this->GetParameterImage<UInt8ImageType>("mask")); } filter->SetOGRData(reprojVector); filter->SetFieldName(fieldName); filter->SetLayerIndex(this->GetParameterInt("layer")); filter->GetStreamer()->SetAutomaticAdaptativeStreaming(GetParameterInt("ram")); AddProcess(filter->GetStreamer(),"Analyze polygons..."); filter->Update(); FilterType::ClassCountMapType &classCount = filter->GetClassCountOutput()->Get(); FilterType::PolygonSizeMapType &polySize = filter->GetPolygonSizeOutput()->Get(); StatWriterType::Pointer statWriter = StatWriterType::New(); statWriter->SetFileName(this->GetParameterString("out")); statWriter->AddInputMap<FilterType::ClassCountMapType>("samplesPerClass",classCount); statWriter->AddInputMap<FilterType::PolygonSizeMapType>("samplesPerVector",polySize); statWriter->Update(); } }; } // end of namespace Wrapper } // end of namespace otb OTB_APPLICATION_EXPORT(otb::Wrapper::PolygonClassStatistics)
use analyze instead of analyse (more coherent with itk/otb code)
DOC: use analyze instead of analyse (more coherent with itk/otb code)
C++
apache-2.0
orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB
1dc9c485373ecdc9311eb3a5a915fa659b72ee76
firmware/weather.cpp
firmware/weather.cpp
# include "weather.h" # include <application.h> WeatherData weather; // creates weather object void WeatherData :: message(int data) // this is just for testing, can be removed later { Serial.print("Timestamp: "); Serial.println(_weatherTime); Serial.print("Temp (F): "); Serial.println(_greenhouseTemp); Serial.print("Humidity (%): "); Serial.println(_greenhouseHumidity); } void WeatherData :: weatherData() { _weatherTime = 0; _greenhouseTemp = 0; _greenhouseHumidity = 0; _backupGreenhouseTemp = 0; _backupGreenhouseHumidity = 0; _outsideTemp = 0; _outsideHumidity = 0; _solar = 0; _high = 0; _low = 0; } void WeatherData :: weatherData(unsigned int weatherTime, int greenhouseTemp,int greenhouseHumidity, int backupGreenhouseTemp, int backupGreenhouseHumidity,int outsideTemp, int outsideHumidity, int solar, int high, int low) { _weatherTime = weatherTime; _greenhouseTemp = greenhouseTemp; _greenhouseHumidity = greenhouseHumidity; _backupGreenhouseTemp = backupGreenhouseTemp; _backupGreenhouseHumidity = backupGreenhouseHumidity; _outsideTemp = outsideTemp; _outsideHumidity = outsideHumidity; _solar = solar; _high = high; _low = low; } unsigned int WeatherData :: weatherTime() { return _weatherTime; } int WeatherData :: greenhouseTemp() { return _greenhouseTemp; } int WeatherData :: greenhouseHumidity() { return _greenhouseHumidity; } int WeatherData :: backupGreenhouseTemp() { return _backupGreenhouseTemp; } int WeatherData :: backupGreenhouseHumidity() { return _backupGreenhouseHumidity; } int WeatherData :: outsideTemp() { return _outsideTemp; } int WeatherData :: outsideHumidity() { return _outsideHumidity; } int WeatherData :: solar() { return _solar; } int WeatherData :: high() { return _high; } int WeatherData :: low() { return _low; }
# include "weather.h" # include <application.h> WeatherData weatherstation; // creates weather object void WeatherData :: message(int data) // this is just for testing, can be removed later { Serial.print("Timestamp: "); Serial.println(_weatherTime); Serial.print("Temp (F): "); Serial.println(_greenhouseTemp); Serial.print("Humidity (%): "); Serial.println(_greenhouseHumidity); } void WeatherData :: weatherData() { _weatherTime = 0; _weatherTransmitTime = 0; _greenhouseTemp = 0; _greenhouseHumidity = 0; _backupGreenhouseTemp = 0; _backupGreenhouseHumidity = 0; _outsideTemp = 0; _outsideHumidity = 0; _solar = 0; _high = 0; _low = 0; } void WeatherData :: weatherData(unsigned int weatherTime, unsigned int weatherTransmitTime, int greenhouseTemp,int greenhouseHumidity, int backupGreenhouseTemp, int backupGreenhouseHumidity,int outsideTemp, int outsideHumidity, int solar, int high, int low) { _weatherTime = weatherTime; _weatherTransmitTime = weatherTransmitTime; _greenhouseTemp = greenhouseTemp; _greenhouseHumidity = greenhouseHumidity; _backupGreenhouseTemp = backupGreenhouseTemp; _backupGreenhouseHumidity = backupGreenhouseHumidity; _outsideTemp = outsideTemp; _outsideHumidity = outsideHumidity; _solar = solar; _high = high; _low = low; } unsigned int WeatherData :: weatherTime() { return _weatherTime; } unsigned int WeatherData :: weatherTransmitTime() { return _weatherTransmitTime; } int WeatherData :: greenhouseTemp() { return _greenhouseTemp; } int WeatherData :: greenhouseHumidity() { return _greenhouseHumidity; } int WeatherData :: backupGreenhouseTemp() { return _backupGreenhouseTemp; } int WeatherData :: backupGreenhouseHumidity() { return _backupGreenhouseHumidity; } int WeatherData :: outsideTemp() { return _outsideTemp; } int WeatherData :: outsideHumidity() { return _outsideHumidity; } int WeatherData :: solar() { return _solar; } int WeatherData :: high() { return _high; } int WeatherData :: low() { return _low; }
Update weather.cpp
Update weather.cpp
C++
mit
geoffsharris/weather
7d1805889dfd5585c318c9ad6e0fae3d493eb43f
src/fslock.cpp
src/fslock.cpp
#include "fslock.h" #include <cerrno> #include <fcntl.h> #include <string.h> #include <sys/stat.h> #include <unistd.h> #include "logger.h" namespace newsboat { void remove_lock(const std::string& lock_filepath) { ::unlink(lock_filepath.c_str()); LOG(Level::DEBUG, "FsLock: removed lockfile %s", lock_filepath); } FsLock::~FsLock() { if (locked) { remove_lock(lock_filepath); ::close(fd); } } bool FsLock::try_lock(const std::string& new_lock_filepath, pid_t& pid) { if (locked && lock_filepath == new_lock_filepath) { return true; } // pid == 0 indicates that something went majorly wrong during locking pid = 0; LOG(Level::DEBUG, "FsLock: trying to lock `%s'", new_lock_filepath); // first, we open (and possibly create) the lock file fd = ::open(new_lock_filepath.c_str(), O_RDWR | O_CREAT, 0600); if (fd < 0) { return false; } // then we lock it (returns immediately if locking is not possible) if (lockf(fd, F_TLOCK, 0) == 0) { LOG(Level::DEBUG, "FsLock: locked `%s', writing PID...", new_lock_filepath); std::string pidtext = std::to_string(getpid()); // locking successful -> truncate file and write own PID into it ssize_t written = 0; if (ftruncate(fd, 0) == 0) { written = write(fd, pidtext.c_str(), pidtext.length()); } bool success = (written != -1) && (static_cast<unsigned int>(written) == pidtext.length()); LOG(Level::DEBUG, "FsLock: PID written successfully: %i", success); if (success) { if (locked) { remove_lock(lock_filepath); } locked = success; lock_filepath = new_lock_filepath; } else { ::close(fd); } return success; } else { LOG(Level::ERROR, "FsLock: something went wrong during locking: %s", strerror(errno)); } // locking was not successful -> read PID of locking process from the // file if (fd >= 0) { char buf[32]; int len = read(fd, buf, sizeof(buf) - 1); if (len > 0) { buf[len] = '\0'; unsigned int upid = 0; sscanf(buf, "%u", &upid); pid = upid; } close(fd); } LOG(Level::DEBUG, "FsLock: locking failed, already locked by %u", pid); return false; } } // namespace newsboat
#include "fslock.h" #include <cerrno> #include <fcntl.h> #include <string.h> #include <sys/stat.h> #include <unistd.h> #include "logger.h" namespace newsboat { void remove_lock(const std::string& lock_filepath) { ::unlink(lock_filepath.c_str()); LOG(Level::DEBUG, "FsLock: removed lockfile %s", lock_filepath); } FsLock::~FsLock() { if (locked) { remove_lock(lock_filepath); ::close(fd); } } bool FsLock::try_lock(const std::string& new_lock_filepath, pid_t& pid) { if (locked && lock_filepath == new_lock_filepath) { return true; } // pid == 0 indicates that something went majorly wrong during locking pid = 0; LOG(Level::DEBUG, "FsLock: trying to lock `%s'", new_lock_filepath); // first, we open (and possibly create) the lock file fd = ::open(new_lock_filepath.c_str(), O_RDWR | O_CREAT, 0600); if (fd < 0) { return false; } // then we lock it (returns immediately if locking is not possible) if (lockf(fd, F_TLOCK, 0) == 0) { LOG(Level::DEBUG, "FsLock: locked `%s', writing PID...", new_lock_filepath); std::string pidtext = std::to_string(getpid()); // locking successful -> truncate file and write own PID into it ssize_t written = 0; if (ftruncate(fd, 0) == 0) { written = write(fd, pidtext.c_str(), pidtext.length()); } bool success = (written != -1) && (static_cast<unsigned int>(written) == pidtext.length()); LOG(Level::DEBUG, "FsLock: PID written successfully: %i", success); if (success) { if (locked) { remove_lock(lock_filepath); } locked = true; lock_filepath = new_lock_filepath; } else { ::close(fd); } return success; } else { LOG(Level::ERROR, "FsLock: something went wrong during locking: %s", strerror(errno)); } // locking was not successful -> read PID of locking process from the // file if (fd >= 0) { char buf[32]; int len = read(fd, buf, sizeof(buf) - 1); if (len > 0) { buf[len] = '\0'; unsigned int upid = 0; sscanf(buf, "%u", &upid); pid = upid; } close(fd); } LOG(Level::DEBUG, "FsLock: locking failed, already locked by %u", pid); return false; } } // namespace newsboat
Make the code more obvious
Make the code more obvious Problem spotted by PVS Studio.
C++
mit
newsboat/newsboat,newsboat/newsboat,newsboat/newsboat,newsboat/newsboat,der-lyse/newsboat,newsboat/newsboat,der-lyse/newsboat,der-lyse/newsboat,der-lyse/newsboat,der-lyse/newsboat,der-lyse/newsboat,newsboat/newsboat,newsboat/newsboat,newsboat/newsboat,der-lyse/newsboat,der-lyse/newsboat
49f49fa7835fcc87a62dc783e049746829abb519
loom-bit/loom.cpp
loom-bit/loom.cpp
#define _REENTRANT #include <cassert> #include <signal.h> #include <sys/prctl.h> #include <pthread.h> #include <sys/time.h> #include <ctime> #include "sync.h" #include "loom.h" #include "daemon.h" #include "fixes.h" using namespace std; spin_rwlock_t updating_nthreads; volatile int in_atomic_region; atomic_t executing_basic_func[MAX_N_CHECKS]; atomic_t in_check[MAX_N_CHECKS]; volatile int is_func_patched[MAX_N_FUNCS]; volatile int enabled[MAX_N_CHECKS]; // TODO: multiple callback functions volatile inject_func_t callback[MAX_N_INSTS]; argument_t arguments[MAX_N_INSTS]; int daemon_pid = -1; void stop_daemon() { #if 0 char file_name[1024]; sprintf(file_name, "/tmp/log.%d", getpid()); flog = fopen(file_name, "a"); fprintf(flog, "stop_daemon %d\n", daemon_pid); fclose(flog); #endif if (daemon_pid != -1) kill(daemon_pid, 9); } int start_daemon() { const static int CHILD_STACK_SIZE = 1024 * 1024; void *child_stack = (char *)malloc(CHILD_STACK_SIZE) + CHILD_STACK_SIZE; if (!child_stack) { perror("malloc"); return -1; } daemon_pid = clone(handle_client_requests, child_stack, CLONE_VM, NULL); fprintf(stderr, "daemon_pid = %d\n", daemon_pid); return 0; } // #define MEASURE_TIME /* * Returns -1 on error. But still need to activate. */ int deactivate(const vector<int> &checks, int &n_tries) { #if 0 fprintf(stderr, "checks:"); for (size_t i = 0; i < checks.size(); ++i) fprintf(stderr, " %d", checks[i]); fprintf(stderr, "\n"); #endif int tmp[MAX_N_CHECKS]; #ifdef MEASURE_TIME struct timeval start, t1, t2, t3, diff; gettimeofday(&start, NULL); #endif for (int i = 0; i < MAX_N_CHECKS; ++i) tmp[i] = 1; for (size_t i = 0; i < checks.size(); ++i) { int check_id = checks[i]; tmp[check_id] = 0; } for (int i = 0; i < MAX_N_CHECKS; ++i) { if (tmp[i] == 1) enabled[i] = 1; } #ifdef MEASURE_TIME gettimeofday(&t1, NULL); timersub(&t1, &start, &diff); FILE *flog = fopen("/tmp/log", "a"); fprintf(flog, "setting flag = %ld\n", diff.tv_sec * 1000000 + diff.tv_usec); fclose(flog); #endif fprintf(stderr, "Deactivating...\n"); n_tries = 0; #if 1 while (true) { n_tries++; spin_write_lock(&updating_nthreads); #ifdef MEASURE_TIME if (n_tries == 1) { gettimeofday(&t2, NULL); timersub(&t2, &t1, &diff); flog = fopen("/tmp/log", "a"); fprintf(flog, "grabbing lock = %ld\n", diff.tv_sec * 1000000 + diff.tv_usec); fclose(flog); } #endif // fprintf(stderr, "Grabbed the global lock\n"); bool ok = true; for (int i = 0; i < MAX_N_CHECKS; ++i) { if (enabled[i] == 0 && (executing_basic_func[i] > 0 || in_check[i] > 0)) { // fprintf(stderr, "check %d does not satisfy\n", i); ok = false; break; } } if (ok) break; spin_write_unlock(&updating_nthreads); usleep(10 * 1000); } #else n_tries++; spin_write_lock(&updating_nthreads); for (int i = 0; i < MAX_N_CHECKS; ++i) { if (enabled[i] == 0 && (executing_basic_func[i] > 0 || in_check[i] > 0)) { // fprintf(stderr, "check %d does not satisfy\n", i); return -1; } } #endif #ifdef MEASURE_TIME gettimeofday(&t3, NULL); timersub(&t3, &t2, &diff); flog = fopen("/tmp/log", "a"); fprintf(flog, "waiting = %ld\n", diff.tv_sec * 1000000 + diff.tv_usec); fclose(flog); #endif return 0; } int activate() { int i; int ok_to_activate; spin_write_unlock(&updating_nthreads); for (i = 0; i < MAX_N_CHECKS; ++i) enabled[i] = 0; do { ok_to_activate = 1; for (i = 0; i < MAX_N_CHECKS; ++i) { if (in_check[i] > 0) { ok_to_activate = 0; break; } } } while (ok_to_activate == 0); return 0; } // #define SAMPLING_ENABLED #ifdef SAMPLING_ENABLED static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; #endif int __enter_atomic_region() { for (int i = 0; i < MAX_N_CHECKS; ++i) enabled[i] = 1; #ifdef SAMPLING_ENABLED pthread_mutex_lock(&m); /* FILE *fout = fopen("/tmp/log", "a"); fprintf(fout, "Entering the atomic region...\n"); fclose(fout); */ fprintf(stderr, "Entering the atomic region...\n"); pthread_mutex_unlock(&m); #endif spin_read_unlock(&updating_nthreads); spin_write_lock(&updating_nthreads); // fprintf(stderr, "Grabbed the global lock\n"); in_atomic_region = 1; for (int i = 0; i < MAX_N_CHECKS; ++i) enabled[i] = 0; return 0; } int __exit_atomic_region() { int i, ok_to_activate; #ifdef SAMPLING_ENABLED pthread_mutex_lock(&m); /* FILE *fout = fopen("/tmp/log", "a"); fprintf(fout, "Exiting the atomic region...\n"); fclose(fout); */ fprintf(stderr, "Exiting the atomic region...\n"); pthread_mutex_unlock(&m); #endif in_atomic_region = 0; spin_write_unlock(&updating_nthreads); do { ok_to_activate = 1; for (i = 0; i < MAX_N_CHECKS; ++i) { if (in_check[i] > 0) { ok_to_activate = 0; break; } } } while (ok_to_activate == 0); spin_read_lock(&updating_nthreads); return 0; } #ifndef OPT3 extern "C" int loom_before_call(int check_id) { #ifdef SAMPLING_ENABLED static int counter = 0; counter++; if (counter >= 1000) { pthread_mutex_lock(&m); FILE *fout = fopen("/tmp/log", "a"); fprintf(fout, "before_call: %d\n", check_id); fclose(fout); pthread_mutex_unlock(&m); counter = 0; } #endif #ifdef EXTERN_FUNC_ENABLED if (in_atomic_region) return 1; atomic_inc(&executing_basic_func[check_id]); spin_read_unlock(&updating_nthreads); #endif return 0; } extern "C" void loom_after_call(int check_id) { #ifdef SAMPLING_ENABLED static int counter = 0; counter++; if (counter >= 1000) { pthread_mutex_lock(&m); FILE *fout = fopen("/tmp/log", "a"); fprintf(fout, "before_call: %d\n", check_id); fclose(fout); pthread_mutex_unlock(&m); counter = 0; } #endif #ifdef EXTERN_FUNC_ENABLED #ifdef WAIT_CHECK while (unlikely(enabled[check_id])); #endif spin_read_lock(&updating_nthreads); atomic_dec(&executing_basic_func[check_id]); #endif } #endif // OPT3 #ifndef INLINE_DISPATCHER extern "C" void loom_dispatcher(int ins_id) { if (likely(callback[ins_id] == NULL)) return; inject_func_t func = callback[ins_id]; func(arguments[ins_id]); } #endif
#define _REENTRANT #include <cassert> #include <signal.h> #include <sys/prctl.h> #include <pthread.h> #include <sys/time.h> #include <ctime> #include "sync.h" #include "loom.h" #include "daemon.h" #include "fixes.h" using namespace std; spin_rwlock_t updating_nthreads; volatile int in_atomic_region; atomic_t executing_basic_func[MAX_N_CHECKS]; atomic_t in_check[MAX_N_CHECKS]; volatile int is_func_patched[MAX_N_FUNCS]; volatile int enabled[MAX_N_CHECKS]; // TODO: multiple callback functions volatile inject_func_t callback[MAX_N_INSTS]; argument_t arguments[MAX_N_INSTS]; int daemon_pid = -1; void stop_daemon() { #if 0 char file_name[1024]; sprintf(file_name, "/tmp/log.%d", getpid()); flog = fopen(file_name, "a"); fprintf(flog, "stop_daemon %d\n", daemon_pid); fclose(flog); #endif if (daemon_pid != -1) kill(daemon_pid, 9); } int start_daemon() { const static int CHILD_STACK_SIZE = 1024 * 1024; void *child_stack = (char *)malloc(CHILD_STACK_SIZE) + CHILD_STACK_SIZE; if (!child_stack) { perror("malloc"); return -1; } daemon_pid = clone(handle_client_requests, child_stack, CLONE_VM, NULL); fprintf(stderr, "daemon_pid = %d\n", daemon_pid); return 0; } // #define MEASURE_TIME /* * Returns -1 on error. But still need to activate. */ int deactivate(const vector<int> &checks, int &n_tries) { #if 0 fprintf(stderr, "checks:"); for (size_t i = 0; i < checks.size(); ++i) fprintf(stderr, " %d", checks[i]); fprintf(stderr, "\n"); #endif int tmp[MAX_N_CHECKS]; #ifdef MEASURE_TIME struct timeval start, t1, t2, t3, diff; gettimeofday(&start, NULL); #endif for (int i = 0; i < MAX_N_CHECKS; ++i) tmp[i] = 1; for (size_t i = 0; i < checks.size(); ++i) { int check_id = checks[i]; tmp[check_id] = 0; } for (int i = 0; i < MAX_N_CHECKS; ++i) { if (tmp[i] == 1) enabled[i] = 1; } #ifdef MEASURE_TIME gettimeofday(&t1, NULL); timersub(&t1, &start, &diff); FILE *flog = fopen("/tmp/log", "a"); fprintf(flog, "setting flag = %ld\n", diff.tv_sec * 1000000 + diff.tv_usec); fclose(flog); #endif fprintf(stderr, "Deactivating...\n"); n_tries = 0; #if 1 while (true) { n_tries++; spin_write_lock(&updating_nthreads); #ifdef MEASURE_TIME if (n_tries == 1) { gettimeofday(&t2, NULL); timersub(&t2, &t1, &diff); flog = fopen("/tmp/log", "a"); fprintf(flog, "grabbing lock = %ld\n", diff.tv_sec * 1000000 + diff.tv_usec); fclose(flog); } #endif // fprintf(stderr, "Grabbed the global lock\n"); bool ok = true; for (int i = 0; i < MAX_N_CHECKS; ++i) { if (enabled[i] == 0 && (executing_basic_func[i] > 0 || in_check[i] > 0)) { // fprintf(stderr, "check %d does not satisfy\n", i); ok = false; break; } } if (ok) break; spin_write_unlock(&updating_nthreads); usleep(10 * 1000); } #else n_tries++; spin_write_lock(&updating_nthreads); for (int i = 0; i < MAX_N_CHECKS; ++i) { if (enabled[i] == 0 && (executing_basic_func[i] > 0 || in_check[i] > 0)) { // fprintf(stderr, "check %d does not satisfy\n", i); return -1; } } #endif #ifdef MEASURE_TIME gettimeofday(&t3, NULL); timersub(&t3, &t2, &diff); flog = fopen("/tmp/log", "a"); fprintf(flog, "waiting = %ld\n", diff.tv_sec * 1000000 + diff.tv_usec); fclose(flog); #endif return 0; } int activate() { int i; int ok_to_activate; spin_write_unlock(&updating_nthreads); for (i = 0; i < MAX_N_CHECKS; ++i) enabled[i] = 0; do { ok_to_activate = 1; for (i = 0; i < MAX_N_CHECKS; ++i) { if (in_check[i] > 0) { ok_to_activate = 0; break; } } } while (ok_to_activate == 0); return 0; } // #define SAMPLING_ENABLED #ifdef SAMPLING_ENABLED static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; #endif int __enter_atomic_region() { for (int i = 0; i < MAX_N_CHECKS; ++i) enabled[i] = 1; #ifdef SAMPLING_ENABLED pthread_mutex_lock(&m); /* FILE *fout = fopen("/tmp/log", "a"); fprintf(fout, "Entering the atomic region...\n"); fclose(fout); */ fprintf(stderr, "Entering the atomic region...\n"); pthread_mutex_unlock(&m); #endif spin_read_unlock(&updating_nthreads); spin_write_lock(&updating_nthreads); // fprintf(stderr, "Grabbed the global lock\n"); in_atomic_region = 1; for (int i = 0; i < MAX_N_CHECKS; ++i) enabled[i] = 0; return 0; } int __exit_atomic_region() { int i, ok_to_activate; #ifdef SAMPLING_ENABLED pthread_mutex_lock(&m); /* FILE *fout = fopen("/tmp/log", "a"); fprintf(fout, "Exiting the atomic region...\n"); fclose(fout); */ fprintf(stderr, "Exiting the atomic region...\n"); pthread_mutex_unlock(&m); #endif in_atomic_region = 0; spin_write_unlock(&updating_nthreads); do { ok_to_activate = 1; for (i = 0; i < MAX_N_CHECKS; ++i) { if (in_check[i] > 0) { ok_to_activate = 0; break; } } } while (ok_to_activate == 0); spin_read_lock(&updating_nthreads); return 0; } #ifndef OPT3 extern "C" int loom_before_call(int check_id) { #ifdef SAMPLING_ENABLED static int counter = 0; counter++; if (counter >= 1000) { pthread_mutex_lock(&m); FILE *fout = fopen("/tmp/log", "a"); fprintf(fout, "before_call: %d\n", check_id); fclose(fout); pthread_mutex_unlock(&m); counter = 0; } #endif #ifdef EXTERN_FUNC_ENABLED if (in_atomic_region) return 1; atomic_inc(&executing_basic_func[check_id]); spin_read_unlock(&updating_nthreads); #endif return 0; } extern "C" void loom_after_call(int check_id) { #ifdef SAMPLING_ENABLED static int counter = 0; counter++; if (counter >= 1000) { pthread_mutex_lock(&m); FILE *fout = fopen("/tmp/log", "a"); fprintf(fout, "before_call: %d\n", check_id); fclose(fout); pthread_mutex_unlock(&m); counter = 0; } #endif #ifdef EXTERN_FUNC_ENABLED #ifdef WAIT_CHECK while (unlikely(enabled[check_id])); #endif spin_read_lock(&updating_nthreads); atomic_dec(&executing_basic_func[check_id]); #endif } #endif // OPT3 #ifndef INLINE_DISPATCHER extern "C" void loom_dispatcher(int ins_id) { if (likely(callback[ins_id] == NULL)) return; inject_func_t func = callback[ins_id]; func(arguments[ins_id]); } #endif
remove redundant blank lines
remove redundant blank lines
C++
bsd-3-clause
wujingyue/loom,wujingyue/loom,wujingyue/loom
f88fd3b9bec33a60acce0ec507f0ff3addb9a861
lib/primesieve/src/iterator.cpp
lib/primesieve/src/iterator.cpp
/// /// @file iterator.cpp /// /// Copyright (C) 2022 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primesieve/iterator.hpp> #include <primesieve/IteratorHelper.hpp> #include <primesieve/PrimeGenerator.hpp> #include <stdint.h> #include <vector> #include <memory> namespace { template <typename T> void clear(std::unique_ptr<T>& ptr) { ptr.reset(nullptr); } } // namespace namespace primesieve { iterator::~iterator() = default; iterator::iterator(iterator&&) noexcept = default; iterator& iterator::operator=(iterator&&) noexcept = default; iterator::iterator(uint64_t start, uint64_t stop_hint) { skipto(start, stop_hint); } void iterator::skipto(uint64_t start, uint64_t stop_hint) { start_ = start; stop_ = start; stop_hint_ = stop_hint; i_ = 0; last_idx_ = 0; dist_ = 0; clear(primeGenerator_); } void iterator::generate_next_primes() { std::size_t size = 0; while (!size) { if (!primeGenerator_) { IteratorHelper::next(&start_, &stop_, stop_hint_, &dist_); auto p = new PrimeGenerator(start_, stop_); primeGenerator_.reset(p); } primeGenerator_->fillNextPrimes(primes_, &size); // There are 3 different cases here: // 1) The primes array contains a few primes (<= 512). // In this case we return the primes to the user. // 2) The primes array is empty because the next // prime > stop. In this case we reset the // primeGenerator object, increase the start & stop // numbers and sieve the next segment. // 3) The next prime > 2^64. In this case the primes // array contains an error code (UINT64_MAX) which // is returned to the user. if (size == 0) clear(primeGenerator_); } i_ = 0; last_idx_ = size - 1; } void iterator::generate_prev_primes() { // Special case if generate_next_primes() has // been used before generate_prev_primes(). if (primeGenerator_) { assert(!primes_.empty()); start_ = primes_.front(); clear(primeGenerator_); } std::size_t size = 0; while (!size) { IteratorHelper::prev(&start_, &stop_, stop_hint_, &dist_); PrimeGenerator primeGenerator(start_, stop_); primeGenerator.fillPrevPrimes(primes_, &size); } last_idx_ = size - 1; i_ = last_idx_; } } // namespace
/// /// @file iterator.cpp /// /// Copyright (C) 2022 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primesieve/iterator.hpp> #include <primesieve/IteratorHelper.hpp> #include <primesieve/PrimeGenerator.hpp> #include <stdint.h> #include <vector> #include <memory> namespace { template <typename T> void clear(std::unique_ptr<T>& ptr) { ptr.reset(nullptr); } } // namespace namespace primesieve { iterator::~iterator() = default; iterator::iterator(iterator&&) noexcept = default; iterator& iterator::operator=(iterator&&) noexcept = default; iterator::iterator(uint64_t start, uint64_t stop_hint) { start_ = start; stop_ = start; stop_hint_ = stop_hint; i_ = 0; last_idx_ = 0; dist_ = 0; } void iterator::skipto(uint64_t start, uint64_t stop_hint) { start_ = start; stop_ = start; stop_hint_ = stop_hint; i_ = 0; last_idx_ = 0; dist_ = 0; clear(primeGenerator_); } void iterator::generate_next_primes() { std::size_t size = 0; while (!size) { if (!primeGenerator_) { IteratorHelper::next(&start_, &stop_, stop_hint_, &dist_); auto p = new PrimeGenerator(start_, stop_); primeGenerator_.reset(p); } primeGenerator_->fillNextPrimes(primes_, &size); // There are 3 different cases here: // 1) The primes array contains a few primes (<= 512). // In this case we return the primes to the user. // 2) The primes array is empty because the next // prime > stop. In this case we reset the // primeGenerator object, increase the start & stop // numbers and sieve the next segment. // 3) The next prime > 2^64. In this case the primes // array contains an error code (UINT64_MAX) which // is returned to the user. if (size == 0) clear(primeGenerator_); } i_ = 0; last_idx_ = size - 1; } void iterator::generate_prev_primes() { // Special case if generate_next_primes() has // been used before generate_prev_primes(). if (primeGenerator_) { assert(!primes_.empty()); start_ = primes_.front(); clear(primeGenerator_); } std::size_t size = 0; while (!size) { IteratorHelper::prev(&start_, &stop_, stop_hint_, &dist_); PrimeGenerator primeGenerator(start_, stop_); primeGenerator.fillPrevPrimes(primes_, &size); } last_idx_ = size - 1; i_ = last_idx_; } } // namespace
Improve constructor
Improve constructor
C++
bsd-2-clause
kimwalisch/primecount,kimwalisch/primecount,kimwalisch/primecount
34eab6738cea227245355544bcc542a7bfd06f7c
src/systeminfo/linux/qscreensaver_mir.cpp
src/systeminfo/linux/qscreensaver_mir.cpp
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtSystems module 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 "qscreensaver_mir_p.h" #include <QDBusConnection> #include <QDBusInterface> #include <QDBusPendingCall> QT_BEGIN_NAMESPACE QScreenSaverPrivate::QScreenSaverPrivate(QScreenSaver *parent) : q_ptr(parent) , m_keepDisplayOnRequestId(-1) , m_iface("com.canonical.Unity.Screen", "/com/canonical/Unity/Screen", "com.canonical.Unity.Screen", QDBusConnection::systemBus()) { } bool QScreenSaverPrivate::screenSaverEnabled() { return m_keepDisplayOnRequestId == -1; } void QScreenSaverPrivate::setScreenSaverEnabled(bool enabled) { if (!m_iface.isValid()) return; if (m_keepDisplayOnRequestId == -1 && !enabled) { // set request QDBusMessage reply = m_iface.call("keepDisplayOn"); if (reply.arguments().count() > 0) m_keepDisplayOnRequestId = reply.arguments().first().toInt(); } else if (m_keepDisplayOnRequestId != -1 && enabled) { // clear request m_iface.asyncCall("removeDisplayOnRequest", m_keepDisplayOnRequestId); m_keepDisplayOnRequestId = -1; } } QT_END_NAMESPACE
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtSystems module 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 "qscreensaver_mir_p.h" #include <QDBusConnection> #include <QDBusInterface> #include <QDBusPendingCall> QT_BEGIN_NAMESPACE QScreenSaverPrivate::QScreenSaverPrivate(QScreenSaver *parent) : q_ptr(parent) , m_keepDisplayOnRequestId(-1) , m_iface(QLatin1String("com.canonical.Unity.Screen"), QLatin1String("/com/canonical/Unity/Screen"), QLatin1String("com.canonical.Unity.Screen"), QDBusConnection::systemBus()) { } bool QScreenSaverPrivate::screenSaverEnabled() { return m_keepDisplayOnRequestId == -1; } void QScreenSaverPrivate::setScreenSaverEnabled(bool enabled) { if (!m_iface.isValid()) return; if (m_keepDisplayOnRequestId == -1 && !enabled) { // set request QDBusMessage reply = m_iface.call(QLatin1String("keepDisplayOn")); if (reply.arguments().count() > 0) m_keepDisplayOnRequestId = reply.arguments().first().toInt(); } else if (m_keepDisplayOnRequestId != -1 && enabled) { // clear request m_iface.asyncCall(QLatin1String("removeDisplayOnRequest"), m_keepDisplayOnRequestId); m_keepDisplayOnRequestId = -1; } } QT_END_NAMESPACE
Fix warnings from use of the deprecated c string to QString conversion.
Fix warnings from use of the deprecated c string to QString conversion. Change-Id: I5bea2701cf964648ba7a65b881c8f01ad499aeb6 Reviewed-by: Eskil Abrahamsen Blomfeldt <[email protected]>
C++
lgpl-2.1
qtproject/qtsystems,qtproject/qtsystems
05a5a8ad752c5256c72c05a5f24282bfd71e2efa
apps/HelloSocket/hello_socket.cc
apps/HelloSocket/hello_socket.cc
#include "third_party/freertos_kernel/include/FreeRTOS.h" #include "third_party/freertos_kernel/include/task.h" #include "third_party/nxp/rt1176-sdk/middleware/lwip/src/include/lwip/sockets.h" #include <cstdio> extern "C" void app_main(void *param) { printf("Hello socket.\r\n"); int listening_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 0; setsockopt(listening_socket, 0, SO_RCVTIMEO, &tv, sizeof(tv)); struct sockaddr_in bind_address; bind_address.sin_family = AF_INET; bind_address.sin_port = PP_HTONS(31337); bind_address.sin_addr.s_addr = PP_HTONL(INADDR_ANY); bind(listening_socket, reinterpret_cast<struct sockaddr*>(&bind_address), sizeof(bind_address)); listen(listening_socket, 1); const char *fixed_str = "Hello socket.\r\n"; while (true) { int accepted_socket = accept(listening_socket, nullptr, nullptr); send(accepted_socket, fixed_str, strlen(fixed_str), 0); closesocket(accepted_socket); } vTaskSuspend(NULL); }
#include <cstdio> #include "third_party/freertos_kernel/include/FreeRTOS.h" #include "third_party/freertos_kernel/include/task.h" #include "third_party/nxp/rt1176-sdk/middleware/lwip/src/include/lwip/sockets.h" extern "C" void app_main(void* param) { printf("Hello socket.\r\n"); int listening_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 0; setsockopt(listening_socket, 0, SO_RCVTIMEO, &tv, sizeof(tv)); struct sockaddr_in bind_address; bind_address.sin_family = AF_INET; bind_address.sin_port = PP_HTONS(31337); bind_address.sin_addr.s_addr = PP_HTONL(INADDR_ANY); bind(listening_socket, reinterpret_cast<struct sockaddr*>(&bind_address), sizeof(bind_address)); listen(listening_socket, 1); const char* fixed_str = "Hello socket.\r\n"; while (true) { int accepted_socket = accept(listening_socket, nullptr, nullptr); send(accepted_socket, fixed_str, strlen(fixed_str), 0); closesocket(accepted_socket); } vTaskSuspend(NULL); }
Format HelloSocket app
Format HelloSocket app Change-Id: I542e7d96b2424899d9eb3b24996fd73dde0189e8 GitOrigin-RevId: a8872b6fbcd9787b6deaf8b509b28fd96968507d
C++
apache-2.0
google-coral/coralmicro,google-coral/coralmicro,google-coral/coralmicro,google-coral/coralmicro,google-coral/coralmicro
fa39c371bb97119065632a14daadd13f74ce20ac
src/test/fuzz/script.cpp
src/test/fuzz/script.cpp
// Copyright (c) 2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chainparams.h> #include <compressor.h> #include <core_io.h> #include <core_memusage.h> #include <policy/policy.h> #include <pubkey.h> #include <script/descriptor.h> #include <script/script.h> #include <script/sign.h> #include <script/signingprovider.h> #include <script/standard.h> #include <streams.h> #include <test/fuzz/fuzz.h> #include <univalue.h> #include <util/memory.h> void initialize() { // Fuzzers using pubkey must hold an ECCVerifyHandle. static const auto verify_handle = MakeUnique<ECCVerifyHandle>(); SelectParams(CBaseChainParams::REGTEST); } void test_one_input(const std::vector<uint8_t>& buffer) { const CScript script(buffer.begin(), buffer.end()); std::vector<unsigned char> compressed; if (CompressScript(script, compressed)) { const unsigned int size = compressed[0]; compressed.erase(compressed.begin()); assert(size >= 0 && size <= 5); CScript decompressed_script; const bool ok = DecompressScript(decompressed_script, size, compressed); assert(ok); assert(script == decompressed_script); } for (unsigned int size = 0; size < 6; ++size) { std::vector<unsigned char> vch(GetSpecialScriptSize(size), 0x00); vch.insert(vch.end(), buffer.begin(), buffer.end()); CScript decompressed_script; (void)DecompressScript(decompressed_script, size, vch); } CTxDestination address; (void)ExtractDestination(script, address); txnouttype type_ret; std::vector<CTxDestination> addresses; int required_ret; (void)ExtractDestinations(script, type_ret, addresses, required_ret); (void)GetScriptForWitness(script); const FlatSigningProvider signing_provider; (void)InferDescriptor(script, signing_provider); (void)IsSegWitOutput(signing_provider, script); (void)IsSolvable(signing_provider, script); txnouttype which_type; (void)IsStandard(script, which_type); (void)RecursiveDynamicUsage(script); std::vector<std::vector<unsigned char>> solutions; (void)Solver(script, solutions); (void)script.HasValidOps(); (void)script.IsPayToScriptHash(); (void)script.IsPayToWitnessScriptHash(); (void)script.IsPushOnly(); (void)script.IsUnspendable(); (void)script.GetSigOpCount(/* fAccurate= */ false); (void)FormatScript(script); (void)ScriptToAsmStr(script, false); (void)ScriptToAsmStr(script, true); UniValue o1(UniValue::VOBJ); ScriptPubKeyToUniv(script, o1, true); UniValue o2(UniValue::VOBJ); ScriptPubKeyToUniv(script, o2, false); UniValue o3(UniValue::VOBJ); ScriptToUniv(script, o3, true); UniValue o4(UniValue::VOBJ); ScriptToUniv(script, o4, false); }
// Copyright (c) 2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chainparams.h> #include <compressor.h> #include <core_io.h> #include <core_memusage.h> #include <policy/policy.h> #include <pubkey.h> #include <script/descriptor.h> #include <script/script.h> #include <script/sign.h> #include <script/signingprovider.h> #include <script/standard.h> #include <streams.h> #include <test/fuzz/fuzz.h> #include <univalue.h> #include <util/memory.h> void initialize() { // Fuzzers using pubkey must hold an ECCVerifyHandle. static const auto verify_handle = MakeUnique<ECCVerifyHandle>(); SelectParams(CBaseChainParams::REGTEST); } void test_one_input(const std::vector<uint8_t>& buffer) { const CScript script(buffer.begin(), buffer.end()); std::vector<unsigned char> compressed; if (CompressScript(script, compressed)) { const unsigned int size = compressed[0]; compressed.erase(compressed.begin()); assert(size >= 0 && size <= 5); CScript decompressed_script; const bool ok = DecompressScript(decompressed_script, size, compressed); assert(ok); assert(script == decompressed_script); } CTxDestination address; (void)ExtractDestination(script, address); txnouttype type_ret; std::vector<CTxDestination> addresses; int required_ret; (void)ExtractDestinations(script, type_ret, addresses, required_ret); (void)GetScriptForWitness(script); const FlatSigningProvider signing_provider; (void)InferDescriptor(script, signing_provider); (void)IsSegWitOutput(signing_provider, script); (void)IsSolvable(signing_provider, script); txnouttype which_type; (void)IsStandard(script, which_type); (void)RecursiveDynamicUsage(script); std::vector<std::vector<unsigned char>> solutions; (void)Solver(script, solutions); (void)script.HasValidOps(); (void)script.IsPayToScriptHash(); (void)script.IsPayToWitnessScriptHash(); (void)script.IsPushOnly(); (void)script.IsUnspendable(); (void)script.GetSigOpCount(/* fAccurate= */ false); (void)FormatScript(script); (void)ScriptToAsmStr(script, false); (void)ScriptToAsmStr(script, true); UniValue o1(UniValue::VOBJ); ScriptPubKeyToUniv(script, o1, true); UniValue o2(UniValue::VOBJ); ScriptPubKeyToUniv(script, o2, false); UniValue o3(UniValue::VOBJ); ScriptToUniv(script, o3, true); UniValue o4(UniValue::VOBJ); ScriptToUniv(script, o4, false); }
Remove unit test from fuzzing harness
tests: Remove unit test from fuzzing harness Former-commit-id: ec73b9449a750fb06e31dd25601810e42d62eb09
C++
mit
syscoin/syscoin2,syscoin/syscoin,syscoin/syscoin,syscoin/syscoin2,syscoin/syscoin2,syscoin/syscoin2,syscoin/syscoin,syscoin/syscoin,syscoin/syscoin,syscoin/syscoin,syscoin/syscoin2,syscoin/syscoin,syscoin/syscoin2,syscoin/syscoin
fbe8851ba2f654190069e511c2a061b36c268cdd
arangod/Utils/AqlTransaction.cpp
arangod/Utils/AqlTransaction.cpp
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Jan Steemann //////////////////////////////////////////////////////////////////////////////// #include "AqlTransaction.h" #include "CollectionNameResolver.h" #include "Logger/Logger.h" #include "VocBase/LogicalCollection.h" using namespace arangodb; /// @brief add a collection to the transaction int AqlTransaction::processCollection(aql::Collection* collection) { int state = setupState(); if (state != TRI_ERROR_NO_ERROR) { return state; } if (ServerState::instance()->isCoordinator()) { return processCollectionCoordinator(collection); } return processCollectionNormal(collection); } /// @brief add a coordinator collection to the transaction int AqlTransaction::processCollectionCoordinator(aql::Collection* collection) { TRI_voc_cid_t cid = this->resolver()->getCollectionId(collection->getName()); return this->addCollection(cid, collection->getName().c_str(), collection->accessType); } /// @brief add a regular collection to the transaction int AqlTransaction::processCollectionNormal(aql::Collection* collection) { TRI_voc_cid_t cid = 0; arangodb::LogicalCollection const* col = this->resolver()->getCollectionStruct(collection->getName()); if (col == nullptr) { auto startTime = TRI_microtime(); auto endTime = startTime + 60.0; do { usleep(10000); if (TRI_microtime() > endTime) { break; } col = this->resolver()->getCollectionStruct(collection->getName()); } while (col == nullptr); } if (col != nullptr) { cid = col->cid(); } int res = this->addCollection(cid, collection->getName(), collection->accessType); if (res == TRI_ERROR_NO_ERROR && col != nullptr) { collection->setCollection(const_cast<arangodb::LogicalCollection*>(col)); } return res; } LogicalCollection* AqlTransaction::documentCollection(TRI_voc_cid_t cid) { TRI_transaction_collection_t* trxColl = this->trxCollection(cid); TRI_ASSERT(trxColl != nullptr); return trxColl->_collection; } /// @brief lockCollections, this is needed in a corner case in AQL: we need /// to lock all shards in a controlled way when we set up a distributed /// execution engine. To this end, we prevent the standard mechanism to /// lock collections on the DBservers when we instantiate the query. Then, /// in a second round, we need to lock the shards in exactly the right /// order via an HTTP call. This method is used to implement that HTTP action. int AqlTransaction::lockCollections() { auto trx = getInternals(); for (auto& trxCollection : trx->_collections) { int res = TRI_LockCollectionTransaction(trxCollection, trxCollection->_accessType, 0); if (res != TRI_ERROR_NO_ERROR) { return res; } } return TRI_ERROR_NO_ERROR; }
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Jan Steemann //////////////////////////////////////////////////////////////////////////////// #include "AqlTransaction.h" #include "CollectionNameResolver.h" #include "Logger/Logger.h" #include "VocBase/LogicalCollection.h" using namespace arangodb; /// @brief add a collection to the transaction int AqlTransaction::processCollection(aql::Collection* collection) { int state = setupState(); if (state != TRI_ERROR_NO_ERROR) { return state; } if (ServerState::instance()->isCoordinator()) { return processCollectionCoordinator(collection); } return processCollectionNormal(collection); } /// @brief add a coordinator collection to the transaction int AqlTransaction::processCollectionCoordinator(aql::Collection* collection) { TRI_voc_cid_t cid = this->resolver()->getCollectionId(collection->getName()); return this->addCollection(cid, collection->getName().c_str(), collection->accessType); } /// @brief add a regular collection to the transaction int AqlTransaction::processCollectionNormal(aql::Collection* collection) { TRI_voc_cid_t cid = 0; arangodb::LogicalCollection const* col = this->resolver()->getCollectionStruct(collection->getName()); /*if (col == nullptr) { auto startTime = TRI_microtime(); auto endTime = startTime + 60.0; do { usleep(10000); if (TRI_microtime() > endTime) { break; } col = this->resolver()->getCollectionStruct(collection->getName()); } while (col == nullptr); } */ if (col != nullptr) { cid = col->cid(); } int res = this->addCollection(cid, collection->getName(), collection->accessType); if (res == TRI_ERROR_NO_ERROR && col != nullptr) { collection->setCollection(const_cast<arangodb::LogicalCollection*>(col)); } return res; } LogicalCollection* AqlTransaction::documentCollection(TRI_voc_cid_t cid) { TRI_transaction_collection_t* trxColl = this->trxCollection(cid); TRI_ASSERT(trxColl != nullptr); return trxColl->_collection; } /// @brief lockCollections, this is needed in a corner case in AQL: we need /// to lock all shards in a controlled way when we set up a distributed /// execution engine. To this end, we prevent the standard mechanism to /// lock collections on the DBservers when we instantiate the query. Then, /// in a second round, we need to lock the shards in exactly the right /// order via an HTTP call. This method is used to implement that HTTP action. int AqlTransaction::lockCollections() { auto trx = getInternals(); for (auto& trxCollection : trx->_collections) { int res = TRI_LockCollectionTransaction(trxCollection, trxCollection->_accessType, 0); if (res != TRI_ERROR_NO_ERROR) { return res; } } return TRI_ERROR_NO_ERROR; }
comment out waiting for now
comment out waiting for now
C++
apache-2.0
joerg84/arangodb,graetzer/arangodb,arangodb/arangodb,arangodb/arangodb,baslr/ArangoDB,graetzer/arangodb,hkernbach/arangodb,arangodb/arangodb,fceller/arangodb,hkernbach/arangodb,wiltonlazary/arangodb,Simran-B/arangodb,fceller/arangodb,hkernbach/arangodb,baslr/ArangoDB,joerg84/arangodb,wiltonlazary/arangodb,fceller/arangodb,graetzer/arangodb,baslr/ArangoDB,joerg84/arangodb,fceller/arangodb,graetzer/arangodb,hkernbach/arangodb,hkernbach/arangodb,hkernbach/arangodb,graetzer/arangodb,graetzer/arangodb,joerg84/arangodb,Simran-B/arangodb,joerg84/arangodb,Simran-B/arangodb,graetzer/arangodb,fceller/arangodb,graetzer/arangodb,baslr/ArangoDB,arangodb/arangodb,Simran-B/arangodb,arangodb/arangodb,hkernbach/arangodb,arangodb/arangodb,baslr/ArangoDB,baslr/ArangoDB,hkernbach/arangodb,wiltonlazary/arangodb,joerg84/arangodb,fceller/arangodb,joerg84/arangodb,baslr/ArangoDB,hkernbach/arangodb,baslr/ArangoDB,baslr/ArangoDB,joerg84/arangodb,arangodb/arangodb,graetzer/arangodb,Simran-B/arangodb,baslr/ArangoDB,fceller/arangodb,fceller/arangodb,joerg84/arangodb,baslr/ArangoDB,joerg84/arangodb,Simran-B/arangodb,arangodb/arangodb,hkernbach/arangodb,fceller/arangodb,Simran-B/arangodb,joerg84/arangodb,wiltonlazary/arangodb,wiltonlazary/arangodb,wiltonlazary/arangodb,graetzer/arangodb,baslr/ArangoDB,hkernbach/arangodb,wiltonlazary/arangodb,fceller/arangodb,graetzer/arangodb,baslr/ArangoDB,baslr/ArangoDB,graetzer/arangodb,Simran-B/arangodb,Simran-B/arangodb,Simran-B/arangodb,graetzer/arangodb,joerg84/arangodb,hkernbach/arangodb,wiltonlazary/arangodb,hkernbach/arangodb,joerg84/arangodb,graetzer/arangodb,joerg84/arangodb,hkernbach/arangodb
94eb44901dd0e6a727021d27fd47267a57781fa7
arangod/V8Server/V8Traverser.cpp
arangod/V8Server/V8Traverser.cpp
//////////////////////////////////////////////////////////////////////////////// /// @brief V8 Traverser /// /// @file /// /// DISCLAIMER /// /// Copyright 2014-2015 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Michael Hackstein /// @author Copyright 2014-2015, ArangoDB GmbH, Cologne, Germany /// @author Copyright 2012-2013, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include "v8.h" #include "V8/v8-conv.h" #include "V8/v8-utils.h" #include "V8Server/v8-vocbaseprivate.h" #include "V8Server/v8-wrapshapedjson.h" #include "V8Server/v8-vocindex.h" #include "V8Server/v8-collection.h" #include "Utils/transactions.h" #include "Utils/V8ResolverGuard.h" #include "Utils/CollectionNameResolver.h" #include "VocBase/document-collection.h" #include "Traverser.h" #include "VocBase/key-generator.h" using namespace std; using namespace triagens::basics; using namespace triagens::arango; class SimpleEdgeExpander { TRI_edge_direction_e direction; TRI_document_collection_t* edgeCollection; string edgeIdPrefix; CollectionNameResolver* resolver; bool usesDist; string id; public: SimpleEdgeExpander( TRI_edge_direction_e direction, TRI_document_collection_t* edgeCollection, string edgeCollectionName, CollectionNameResolver* resolver, string id ) : direction(direction), edgeCollection(edgeCollection), resolver(resolver), usesDist(false), id(id) { // cout << id << direction << endl; edgeIdPrefix = edgeCollectionName + "/"; }; Traverser::VertexId extractFromId(TRI_doc_mptr_copy_t& ptr) { char const* key = TRI_EXTRACT_MARKER_FROM_KEY(&ptr); TRI_voc_cid_t cid = TRI_EXTRACT_MARKER_FROM_CID(&ptr); string col = resolver->getCollectionName(cid); col.append("/"); col.append(key); return col; }; Traverser::VertexId extractToId(TRI_doc_mptr_copy_t& ptr) { char const* key = TRI_EXTRACT_MARKER_TO_KEY(&ptr); TRI_voc_cid_t cid = TRI_EXTRACT_MARKER_TO_CID(&ptr); string col = resolver->getCollectionName(cid); col.append("/"); col.append(key); return col; }; Traverser::EdgeId extractEdgeId(TRI_doc_mptr_copy_t& ptr) { char const* key = TRI_EXTRACT_MARKER_KEY(&ptr); return edgeIdPrefix + key; }; void operator() (Traverser::VertexId source, vector<Traverser::Step>& result) { std::vector<TRI_doc_mptr_copy_t> edges; TransactionBase fake(true); // Fake a transaction to please checks. Due to multi-threading // Process Vertex Id! size_t split; char const* str = source.c_str(); if (!TRI_ValidateDocumentIdKeyGenerator(str, &split)) { // TODO Error Handling return; } string collectionName = string(str, split); auto const length = strlen(str) - split - 1; auto buffer = new char[length + 1]; memcpy(buffer, str + split + 1, length); buffer[length] = '\0'; auto col = resolver->getCollectionStruct(collectionName); if (col == nullptr) { // collection not found throw TRI_ERROR_ARANGO_COLLECTION_NOT_FOUND; } auto collectionCId = col->_cid; edges = TRI_LookupEdgesDocumentCollection(edgeCollection, direction, collectionCId, buffer); if (direction == 1) { // cout << edges.size() << endl; } std::unordered_map<Traverser::VertexId, Traverser::Step> candidates; Traverser::VertexId from; Traverser::VertexId to; std::unordered_map<Traverser::VertexId, Traverser::Step>::const_iterator cand; if (usesDist) { for (size_t j = 0; j < edges.size(); ++j) { from = extractFromId(edges[j]); to = extractToId(edges[j]); if (from != source) { candidates.find(from); if (cand == candidates.end()) { // Add weight candidates.emplace(from, Traverser::Step(to, from, 1, extractEdgeId(edges[j]))); } else { // Compare weight } } else if (to != source) { candidates.find(to); if (cand == candidates.end()) { // Add weight candidates.emplace(to, Traverser::Step(from, to, 1, extractEdgeId(edges[j]))); } else { // Compare weight } } } } else { for (size_t j = 0; j < edges.size(); ++j) { from = extractFromId(edges[j]); to = extractToId(edges[j]); if (from != source) { candidates.find(from); if (cand == candidates.end()) { candidates.emplace(from, Traverser::Step(to, from, 1, extractEdgeId(edges[j]))); } } else if (to != source) { candidates.find(to); if (cand == candidates.end()) { candidates.emplace(to, Traverser::Step(from, to, 1, extractEdgeId(edges[j]))); } } } } for (auto it = candidates.begin(); it != candidates.end(); ++it) { result.push_back(it->second); } } }; static v8::Handle<v8::Value> pathIdsToV8(v8::Isolate* isolate, Traverser::Path& p) { v8::EscapableHandleScope scope(isolate); TRI_GET_GLOBALS(); v8::Handle<v8::Object> result = v8::Object::New(isolate); uint32_t const vn = static_cast<uint32_t>(p.vertices.size()); v8::Handle<v8::Array> vertices = v8::Array::New(isolate, static_cast<int>(vn)); for (size_t j = 0; j < vn; ++j) { vertices->Set(static_cast<uint32_t>(j), TRI_V8_STRING(p.vertices[j].c_str())); } result->Set(TRI_V8_STRING("vertices"), vertices); uint32_t const en = static_cast<uint32_t>(p.edges.size()); v8::Handle<v8::Array> edges = v8::Array::New(isolate, static_cast<int>(en)); for (size_t j = 0; j < en; ++j) { edges->Set(static_cast<uint32_t>(j), TRI_V8_STRING(p.edges[j].c_str())); } result->Set(TRI_V8_STRING("edges"), edges); result->Set(TRI_V8_STRING("distance"), v8::Number::New(isolate, p.weight)); return scope.Escape<v8::Value>(result); }; struct LocalCollectionGuard { LocalCollectionGuard (TRI_vocbase_col_t* collection) : _collection(collection) { } ~LocalCollectionGuard () { if (_collection != nullptr && ! _collection->_isLocal) { FreeCoordinatorCollection(_collection); } } TRI_vocbase_col_t* _collection; }; void TRI_RunDijkstraSearch (const v8::FunctionCallbackInfo<v8::Value>& args) { v8::Isolate* isolate = args.GetIsolate(); v8::HandleScope scope(isolate); if (args.Length() < 4 || args.Length() > 5) { TRI_V8_THROW_EXCEPTION_USAGE("AQL_SHORTEST_PATH(<vertexcollection>, <edgecollection>, <start>, <end>, <options>)"); } std::unique_ptr<char[]> key; TRI_vocbase_t* vocbase; TRI_vocbase_col_t const* col = nullptr; vocbase = GetContextVocBase(isolate); vector<string> readCollections; vector<string> writeCollections; double lockTimeout = (double) (TRI_TRANSACTION_DEFAULT_LOCK_TIMEOUT / 1000000ULL); bool embed = false; bool waitForSync = false; // get the vertex collection if (! args[0]->IsString()) { TRI_V8_THROW_TYPE_ERROR("expecting string for <vertexcollection>"); } string vertexCollectionName = TRI_ObjectToString(args[0]); // get the edge collection if (! args[1]->IsString()) { TRI_V8_THROW_TYPE_ERROR("expecting string for <edgecollection>"); } string const edgeCollectionName = TRI_ObjectToString(args[1]); vocbase = GetContextVocBase(isolate); if (vocbase == nullptr) { TRI_V8_THROW_EXCEPTION(TRI_ERROR_ARANGO_DATABASE_NOT_FOUND); } V8ResolverGuard resolver(vocbase); readCollections.push_back(vertexCollectionName); readCollections.push_back(edgeCollectionName); if (! args[2]->IsString()) { TRI_V8_THROW_TYPE_ERROR("expecting string for <startVertex>"); } string const startVertex = TRI_ObjectToString(args[2]); if (! args[3]->IsString()) { TRI_V8_THROW_TYPE_ERROR("expecting string for <targetVertex>"); } string const targetVertex = TRI_ObjectToString(args[3]); /* std::string vertexColName; if (! ExtractDocumentHandle(isolate, args[2], vertexColName, key, rid)) { TRI_V8_THROW_EXCEPTION(TRI_ERROR_ARANGO_DOCUMENT_HANDLE_BAD); } if (key.get() == nullptr) { TRI_V8_THROW_EXCEPTION(TRI_ERROR_ARANGO_DOCUMENT_HANDLE_BAD); } TRI_ASSERT(key.get() != nullptr); */ // IHHF isCoordinator // Start Transaction to collect all parts of the path ExplicitTransaction trx( vocbase, readCollections, writeCollections, lockTimeout, waitForSync, embed ); int res = trx.begin(); if (res != TRI_ERROR_NO_ERROR) { TRI_V8_THROW_EXCEPTION(res); } col = resolver.getResolver()->getCollectionStruct(vertexCollectionName); if (col == nullptr) { // collection not found TRI_V8_THROW_EXCEPTION(TRI_ERROR_ARANGO_COLLECTION_NOT_FOUND); } if (trx.orderBarrier(trx.trxCollection(col->_cid)) == nullptr) { TRI_V8_THROW_EXCEPTION_MEMORY(); } col = resolver.getResolver()->getCollectionStruct(edgeCollectionName); if (col == nullptr) { // collection not found TRI_V8_THROW_EXCEPTION(TRI_ERROR_ARANGO_COLLECTION_NOT_FOUND); } if (trx.orderBarrier(trx.trxCollection(col->_cid)) == nullptr) { TRI_V8_THROW_EXCEPTION_MEMORY(); } TRI_document_collection_t* ecol = trx.trxCollection(col->_cid)->_collection->_collection; CollectionNameResolver resolver1(vocbase); CollectionNameResolver resolver2(vocbase); SimpleEdgeExpander forwardExpander(TRI_EDGE_OUT, ecol, edgeCollectionName, &resolver1, "A"); SimpleEdgeExpander backwardExpander(TRI_EDGE_IN, ecol, edgeCollectionName, &resolver2, "B"); Traverser traverser(forwardExpander, backwardExpander); unique_ptr<Traverser::Path> path(traverser.shortestPath(startVertex, targetVertex)); if (path.get() == nullptr) { res = trx.finish(res); v8::EscapableHandleScope scope(isolate); TRI_V8_RETURN(scope.Escape<v8::Value>(v8::Object::New(isolate))); } auto result = pathIdsToV8(isolate, *path); res = trx.finish(res); TRI_V8_RETURN(result); /* // This is how to get the data out of the collections! // Vertices TRI_doc_mptr_copy_t document; res = trx.readSingle(trx.trxCollection(vertexCollectionCId), &document, key.get()); // Edges TRI_EDGE_OUT is hardcoded std::vector<TRI_doc_mptr_copy_t>&& edges = TRI_LookupEdgesDocumentCollection(ecol, TRI_EDGE_OUT, vertexCollectionCId, key.get()); */ // Add Dijkstra here /* // Now build up the result use Subtransactions for each used collection if (res == TRI_ERROR_NO_ERROR) { { // Collect all vertices SingleCollectionReadOnlyTransaction subtrx(new V8TransactionContext(true), vocbase, vertexCollectionCId); res = subtrx.begin(); if (res != TRI_ERROR_NO_ERROR) { TRI_V8_THROW_EXCEPTION(res); } result = TRI_WrapShapedJson(isolate, subtrx, vertexCollectionCId, document.getDataPtr()); if (document.getDataPtr() == nullptr) { res = TRI_ERROR_ARANGO_DOCUMENT_NOT_FOUND; TRI_V8_THROW_EXCEPTION(res); } res = subtrx.finish(res); } { // Collect all edges SingleCollectionReadOnlyTransaction subtrx2(new V8TransactionContext(true), vocbase, edgeCollectionCId); res = subtrx2.begin(); if (res != TRI_ERROR_NO_ERROR) { TRI_V8_THROW_EXCEPTION(res); } bool error = false; uint32_t const n = static_cast<uint32_t>(edges.size()); documents = v8::Array::New(isolate, static_cast<int>(n)); for (size_t j = 0; j < n; ++j) { v8::Handle<v8::Value> doc = TRI_WrapShapedJson(isolate, subtrx2, edgeCollectionCId, edges[j].getDataPtr()); if (doc.IsEmpty()) { error = true; break; } else { documents->Set(static_cast<uint32_t>(j), doc); } } if (error) { TRI_V8_THROW_EXCEPTION_MEMORY(); } res = subtrx2.finish(res); } } */ }
//////////////////////////////////////////////////////////////////////////////// /// @brief V8 Traverser /// /// @file /// /// DISCLAIMER /// /// Copyright 2014-2015 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Michael Hackstein /// @author Copyright 2014-2015, ArangoDB GmbH, Cologne, Germany /// @author Copyright 2012-2013, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include "v8.h" #include "V8/v8-conv.h" #include "V8/v8-utils.h" #include "V8Server/v8-vocbaseprivate.h" #include "V8Server/v8-wrapshapedjson.h" #include "V8Server/v8-vocindex.h" #include "V8Server/v8-collection.h" #include "Utils/transactions.h" #include "Utils/V8ResolverGuard.h" #include "Utils/CollectionNameResolver.h" #include "VocBase/document-collection.h" #include "Traverser.h" #include "VocBase/key-generator.h" using namespace std; using namespace triagens::basics; using namespace triagens::arango; class SimpleEdgeExpander { //////////////////////////////////////////////////////////////////////////////// /// @brief direction of expansion //////////////////////////////////////////////////////////////////////////////// TRI_edge_direction_e direction; //////////////////////////////////////////////////////////////////////////////// /// @brief edge collection //////////////////////////////////////////////////////////////////////////////// TRI_document_collection_t* edgeCollection; //////////////////////////////////////////////////////////////////////////////// /// @brief collection name and / //////////////////////////////////////////////////////////////////////////////// string edgeIdPrefix; //////////////////////////////////////////////////////////////////////////////// /// @brief the collection name resolver //////////////////////////////////////////////////////////////////////////////// CollectionNameResolver* resolver; //////////////////////////////////////////////////////////////////////////////// /// @brief this indicates whether or not a distance attribute is used or /// whether all edges are considered to have weight 1 //////////////////////////////////////////////////////////////////////////////// bool usesDist; //////////////////////////////////////////////////////////////////////////////// /// @brief an ID for the expander, just for debuggin //////////////////////////////////////////////////////////////////////////////// string id; public: SimpleEdgeExpander(TRI_edge_direction_e direction, TRI_document_collection_t* edgeCollection, string edgeCollectionName, CollectionNameResolver* resolver, string id) : direction(direction), edgeCollection(edgeCollection), resolver(resolver), usesDist(false), id(id) { edgeIdPrefix = edgeCollectionName + "/"; }; Traverser::VertexId extractFromId(TRI_doc_mptr_copy_t& ptr) { char const* key = TRI_EXTRACT_MARKER_FROM_KEY(&ptr); TRI_voc_cid_t cid = TRI_EXTRACT_MARKER_FROM_CID(&ptr); string col = resolver->getCollectionName(cid); col.append("/"); col.append(key); return col; }; Traverser::VertexId extractToId(TRI_doc_mptr_copy_t& ptr) { char const* key = TRI_EXTRACT_MARKER_TO_KEY(&ptr); TRI_voc_cid_t cid = TRI_EXTRACT_MARKER_TO_CID(&ptr); string col = resolver->getCollectionName(cid); col.append("/"); col.append(key); return col; }; Traverser::EdgeId extractEdgeId(TRI_doc_mptr_copy_t& ptr) { char const* key = TRI_EXTRACT_MARKER_KEY(&ptr); return edgeIdPrefix + key; }; void operator() (Traverser::VertexId source, vector<Traverser::Step>& result) { std::vector<TRI_doc_mptr_copy_t> edges; TransactionBase fake(true); // Fake a transaction to please checks. // This is due to multi-threading // Process Vertex Id! size_t split; char const* str = source.c_str(); if (!TRI_ValidateDocumentIdKeyGenerator(str, &split)) { // TODO Error Handling return; } string collectionName = source.substr(0, split); auto col = resolver->getCollectionStruct(collectionName); if (col == nullptr) { // collection not found throw TRI_ERROR_ARANGO_COLLECTION_NOT_FOUND; } auto collectionCId = col->_cid; edges = TRI_LookupEdgesDocumentCollection(edgeCollection, direction, collectionCId, const_cast<char*>(str + split + 1)); unordered_map<Traverser::VertexId, size_t> candidates; Traverser::VertexId from; Traverser::VertexId to; if (usesDist) { for (size_t j = 0; j < edges.size(); ++j) { from = extractFromId(edges[j]); to = extractToId(edges[j]); if (from != source) { auto cand = candidates.find(from); if (cand == candidates.end()) { // Add weight result.emplace_back(to, from, 1, extractEdgeId(edges[j])); candidates.emplace(from, result.size()-1); } else { // Compare weight // use result[cand->seconde].weight() and .setWeight() } } else if (to != source) { auto cand = candidates.find(to); if (cand == candidates.end()) { // Add weight result.emplace_back(to, from, 1, extractEdgeId(edges[j])); candidates.emplace(to, result.size()-1); } else { // Compare weight // use result[cand->seconde].weight() and .setWeight() } } } } else { for (size_t j = 0; j < edges.size(); ++j) { from = extractFromId(edges[j]); to = extractToId(edges[j]); if (from != source) { auto cand = candidates.find(from); if (cand == candidates.end()) { result.emplace_back(from, to, 1, extractEdgeId(edges[j])); candidates.emplace(from, result.size()-1); } } else if (to != source) { auto cand = candidates.find(to); if (cand == candidates.end()) { result.emplace_back(to, from, 1, extractEdgeId(edges[j])); candidates.emplace(to, result.size()-1); } } } } } }; static v8::Handle<v8::Value> pathIdsToV8(v8::Isolate* isolate, Traverser::Path& p) { v8::EscapableHandleScope scope(isolate); TRI_GET_GLOBALS(); v8::Handle<v8::Object> result = v8::Object::New(isolate); uint32_t const vn = static_cast<uint32_t>(p.vertices.size()); v8::Handle<v8::Array> vertices = v8::Array::New(isolate, static_cast<int>(vn)); for (size_t j = 0; j < vn; ++j) { vertices->Set(static_cast<uint32_t>(j), TRI_V8_STRING(p.vertices[j].c_str())); } result->Set(TRI_V8_STRING("vertices"), vertices); uint32_t const en = static_cast<uint32_t>(p.edges.size()); v8::Handle<v8::Array> edges = v8::Array::New(isolate, static_cast<int>(en)); for (size_t j = 0; j < en; ++j) { edges->Set(static_cast<uint32_t>(j), TRI_V8_STRING(p.edges[j].c_str())); } result->Set(TRI_V8_STRING("edges"), edges); result->Set(TRI_V8_STRING("distance"), v8::Number::New(isolate, p.weight)); return scope.Escape<v8::Value>(result); }; struct LocalCollectionGuard { LocalCollectionGuard (TRI_vocbase_col_t* collection) : _collection(collection) { } ~LocalCollectionGuard () { if (_collection != nullptr && ! _collection->_isLocal) { FreeCoordinatorCollection(_collection); } } TRI_vocbase_col_t* _collection; }; void TRI_RunDijkstraSearch (const v8::FunctionCallbackInfo<v8::Value>& args) { v8::Isolate* isolate = args.GetIsolate(); v8::HandleScope scope(isolate); if (args.Length() < 4 || args.Length() > 5) { TRI_V8_THROW_EXCEPTION_USAGE("AQL_SHORTEST_PATH(<vertexcollection>, <edgecollection>, <start>, <end>, <options>)"); } std::unique_ptr<char[]> key; TRI_vocbase_t* vocbase; TRI_vocbase_col_t const* col = nullptr; vocbase = GetContextVocBase(isolate); vector<string> readCollections; vector<string> writeCollections; double lockTimeout = (double) (TRI_TRANSACTION_DEFAULT_LOCK_TIMEOUT / 1000000ULL); bool embed = false; bool waitForSync = false; // get the vertex collection if (! args[0]->IsString()) { TRI_V8_THROW_TYPE_ERROR("expecting string for <vertexcollection>"); } string vertexCollectionName = TRI_ObjectToString(args[0]); // get the edge collection if (! args[1]->IsString()) { TRI_V8_THROW_TYPE_ERROR("expecting string for <edgecollection>"); } string const edgeCollectionName = TRI_ObjectToString(args[1]); vocbase = GetContextVocBase(isolate); if (vocbase == nullptr) { TRI_V8_THROW_EXCEPTION(TRI_ERROR_ARANGO_DATABASE_NOT_FOUND); } V8ResolverGuard resolver(vocbase); readCollections.push_back(vertexCollectionName); readCollections.push_back(edgeCollectionName); if (! args[2]->IsString()) { TRI_V8_THROW_TYPE_ERROR("expecting string for <startVertex>"); } string const startVertex = TRI_ObjectToString(args[2]); if (! args[3]->IsString()) { TRI_V8_THROW_TYPE_ERROR("expecting string for <targetVertex>"); } string const targetVertex = TRI_ObjectToString(args[3]); /* std::string vertexColName; if (! ExtractDocumentHandle(isolate, args[2], vertexColName, key, rid)) { TRI_V8_THROW_EXCEPTION(TRI_ERROR_ARANGO_DOCUMENT_HANDLE_BAD); } if (key.get() == nullptr) { TRI_V8_THROW_EXCEPTION(TRI_ERROR_ARANGO_DOCUMENT_HANDLE_BAD); } TRI_ASSERT(key.get() != nullptr); */ // IHHF isCoordinator // Start Transaction to collect all parts of the path ExplicitTransaction trx( vocbase, readCollections, writeCollections, lockTimeout, waitForSync, embed ); int res = trx.begin(); if (res != TRI_ERROR_NO_ERROR) { TRI_V8_THROW_EXCEPTION(res); } col = resolver.getResolver()->getCollectionStruct(vertexCollectionName); if (col == nullptr) { // collection not found TRI_V8_THROW_EXCEPTION(TRI_ERROR_ARANGO_COLLECTION_NOT_FOUND); } if (trx.orderBarrier(trx.trxCollection(col->_cid)) == nullptr) { TRI_V8_THROW_EXCEPTION_MEMORY(); } col = resolver.getResolver()->getCollectionStruct(edgeCollectionName); if (col == nullptr) { // collection not found TRI_V8_THROW_EXCEPTION(TRI_ERROR_ARANGO_COLLECTION_NOT_FOUND); } if (trx.orderBarrier(trx.trxCollection(col->_cid)) == nullptr) { TRI_V8_THROW_EXCEPTION_MEMORY(); } TRI_document_collection_t* ecol = trx.trxCollection(col->_cid)->_collection->_collection; CollectionNameResolver resolver1(vocbase); CollectionNameResolver resolver2(vocbase); SimpleEdgeExpander forwardExpander(TRI_EDGE_OUT, ecol, edgeCollectionName, &resolver1, "A"); SimpleEdgeExpander backwardExpander(TRI_EDGE_IN, ecol, edgeCollectionName, &resolver2, "B"); Traverser traverser(forwardExpander, backwardExpander); unique_ptr<Traverser::Path> path(traverser.shortestPath(startVertex, targetVertex)); if (path.get() == nullptr) { res = trx.finish(res); v8::EscapableHandleScope scope(isolate); TRI_V8_RETURN(scope.Escape<v8::Value>(v8::Object::New(isolate))); } auto result = pathIdsToV8(isolate, *path); res = trx.finish(res); TRI_V8_RETURN(result); /* // This is how to get the data out of the collections! // Vertices TRI_doc_mptr_copy_t document; res = trx.readSingle(trx.trxCollection(vertexCollectionCId), &document, key.get()); // Edges TRI_EDGE_OUT is hardcoded std::vector<TRI_doc_mptr_copy_t>&& edges = TRI_LookupEdgesDocumentCollection(ecol, TRI_EDGE_OUT, vertexCollectionCId, key.get()); */ // Add Dijkstra here /* // Now build up the result use Subtransactions for each used collection if (res == TRI_ERROR_NO_ERROR) { { // Collect all vertices SingleCollectionReadOnlyTransaction subtrx(new V8TransactionContext(true), vocbase, vertexCollectionCId); res = subtrx.begin(); if (res != TRI_ERROR_NO_ERROR) { TRI_V8_THROW_EXCEPTION(res); } result = TRI_WrapShapedJson(isolate, subtrx, vertexCollectionCId, document.getDataPtr()); if (document.getDataPtr() == nullptr) { res = TRI_ERROR_ARANGO_DOCUMENT_NOT_FOUND; TRI_V8_THROW_EXCEPTION(res); } res = subtrx.finish(res); } { // Collect all edges SingleCollectionReadOnlyTransaction subtrx2(new V8TransactionContext(true), vocbase, edgeCollectionCId); res = subtrx2.begin(); if (res != TRI_ERROR_NO_ERROR) { TRI_V8_THROW_EXCEPTION(res); } bool error = false; uint32_t const n = static_cast<uint32_t>(edges.size()); documents = v8::Array::New(isolate, static_cast<int>(n)); for (size_t j = 0; j < n; ++j) { v8::Handle<v8::Value> doc = TRI_WrapShapedJson(isolate, subtrx2, edgeCollectionCId, edges[j].getDataPtr()); if (doc.IsEmpty()) { error = true; break; } else { documents->Set(static_cast<uint32_t>(j), doc); } } if (error) { TRI_V8_THROW_EXCEPTION_MEMORY(); } res = subtrx2.finish(res); } } */ }
Correct edge expander.
Correct edge expander.
C++
apache-2.0
abaditsegay/arangodb,pekeler/arangodb,nvoron23/arangodb,mujiansu/arangodb,razvanphp/arangodb,nekulin/arangodb,mujiansu/arangodb,razvanphp/arangodb,aurelijusb/arangodb,pekeler/arangodb,aurelijusb/arangodb,nekulin/arangodb,aurelijusb/arangodb,abaditsegay/arangodb,aurelijusb/arangodb,razvanphp/arangodb,razvanphp/arangodb,pekeler/arangodb,mujiansu/arangodb,pekeler/arangodb,mujiansu/arangodb,abaditsegay/arangodb,aurelijusb/arangodb,aurelijusb/arangodb,kkdd/arangodb,aurelijusb/arangodb,aurelijusb/arangodb,nekulin/arangodb,kkdd/arangodb,razvanphp/arangodb,kkdd/arangodb,abaditsegay/arangodb,razvanphp/arangodb,kkdd/arangodb,mujiansu/arangodb,nvoron23/arangodb,kkdd/arangodb,nvoron23/arangodb,abaditsegay/arangodb,abaditsegay/arangodb,kkdd/arangodb,nekulin/arangodb,pekeler/arangodb,nekulin/arangodb,razvanphp/arangodb,nvoron23/arangodb,razvanphp/arangodb,nekulin/arangodb,razvanphp/arangodb,nekulin/arangodb,nekulin/arangodb,nvoron23/arangodb,mujiansu/arangodb,nvoron23/arangodb,pekeler/arangodb,kkdd/arangodb,kkdd/arangodb,aurelijusb/arangodb,aurelijusb/arangodb,pekeler/arangodb,kkdd/arangodb,nvoron23/arangodb,pekeler/arangodb,nvoron23/arangodb,abaditsegay/arangodb,nekulin/arangodb,pekeler/arangodb,nvoron23/arangodb,mujiansu/arangodb,kkdd/arangodb,mujiansu/arangodb,mujiansu/arangodb,abaditsegay/arangodb,abaditsegay/arangodb,pekeler/arangodb,abaditsegay/arangodb,nekulin/arangodb,nvoron23/arangodb,razvanphp/arangodb,mujiansu/arangodb
bfd407e14bba593ae88121c9a8bec57f1f4ad928
src/tests/type_tests.cpp
src/tests/type_tests.cpp
// Copyright 2008 Paul Hodge #include "common_headers.h" #include "builtin_types.h" #include "branch.h" #include "builtins.h" #include "runtime.h" #include "testing.h" #include "type.h" namespace circa { namespace type_tests { void compound_types() { Branch branch; Term* MyType = branch.eval("type MyType { int myint, string astr }"); test_assert(MyType != NULL); test_assert(is_type(MyType)); test_assert(as_type(MyType).fields.size() == 2); test_assert(as_type(MyType).fields[0].name == "myint"); test_assert(as_type(MyType).fields[0].type == INT_TYPE); test_assert(as_type(MyType).findFieldIndex("myint") == 0); test_assert(as_type(MyType).fields[1].name == "astr"); test_assert(as_type(MyType).fields[1].type == STRING_TYPE); test_assert(as_type(MyType).findFieldIndex("astr") == 1); // instanciation Term* inst = branch.eval("inst = MyType()"); test_assert(inst != NULL); test_assert(inst->type = MyType); test_assert(inst->value != NULL); test_assert(as_branch(inst)[0]->asInt() == 0); test_assert(as_branch(inst)[1]->asString() == ""); // field access on a brand new type Term* astr = branch.eval("inst.astr"); test_assert(is_string(astr)); test_equals(as_string(astr), ""); // field assignment Term *inst2 = branch.eval("inst.astr = 'hello'"); test_assert(as_branch(inst2)[1]->asString() == "hello"); test_assert(inst2->type == MyType); // type specialization // field access of recently assigned value // TODO /*Term* inst1_myint = branch.eval("inst.myint"); test_assert(inst1_myint != NULL); test_assert(!inst1_myint->hasError()); Term* inst1_astr = branch.eval("inst.astr"); test_assert(inst1_astr != NULL); test_assert(!inst1_astr->hasError());*/ } void type_declaration() { Branch branch; Term* myType = branch.eval("type MyType { string a, int b } "); test_assert(as_type(myType).numFields() == 2); test_assert(as_type(myType).fields[0].name == "a"); test_assert(as_type(myType).fields[0].type == STRING_TYPE); test_assert(as_type(myType).fields[1].name == "b"); test_assert(as_type(myType).fields[1].type == INT_TYPE); test_assert(as_type(myType).alloc != NULL); test_assert(as_type(myType).copy != NULL); Term* instance = branch.eval("mt = MyType()"); test_assert(is_value_alloced(instance)); } void type_iterator() { Branch branch; Term *t = branch.eval("t = Type()"); Type &type = as_type(t); ReferenceIterator *it; it = start_reference_iterator(t); test_assert(it->finished()); delete it; type.addField(INT_TYPE, "int1"); type.addField(STRING_TYPE, "int1"); it = start_reference_iterator(t); test_assert(it->current() == INT_TYPE); it->advance(); test_assert(it->current() == STRING_TYPE); it->advance(); test_assert(it->finished()); delete it; } void register_tests() { REGISTER_TEST_CASE(type_tests::compound_types); REGISTER_TEST_CASE(type_tests::type_declaration); REGISTER_TEST_CASE(type_tests::type_iterator); } } // namespace type_tests } // namespace circa
// Copyright 2008 Paul Hodge #include "common_headers.h" #include "builtin_types.h" #include "branch.h" #include "builtins.h" #include "runtime.h" #include "testing.h" #include "type.h" namespace circa { namespace type_tests { void compound_types() { Branch branch; Term* MyType = branch.eval("type MyType { int myint, string astr }"); test_assert(MyType != NULL); test_assert(is_type(MyType)); test_assert(as_type(MyType).fields.size() == 2); test_assert(as_type(MyType).fields[0].name == "myint"); test_assert(as_type(MyType).fields[0].type == INT_TYPE); test_assert(as_type(MyType).findFieldIndex("myint") == 0); test_assert(as_type(MyType).fields[1].name == "astr"); test_assert(as_type(MyType).fields[1].type == STRING_TYPE); test_assert(as_type(MyType).findFieldIndex("astr") == 1); // instanciation Term* inst = branch.eval("inst = MyType()"); test_assert(inst != NULL); test_assert(inst->type = MyType); test_assert(inst->value != NULL); test_assert(as_branch(inst)[0]->asInt() == 0); test_assert(as_branch(inst)[1]->asString() == ""); // field access on a brand new type Term* astr = branch.eval("inst.astr"); test_assert(is_string(astr)); test_equals(as_string(astr), ""); // field assignment Term *inst2 = branch.eval("inst.astr = 'hello'"); test_assert(as_branch(inst2)[1]->asString() == "hello"); test_assert(inst2->type == MyType); // type specialization // field access of recently assigned value Term* astr2 = branch.eval("inst.astr"); test_assert(is_string(astr2)); test_equals(as_string(astr2), "hello"); } void type_declaration() { Branch branch; Term* myType = branch.eval("type MyType { string a, int b } "); test_assert(as_type(myType).numFields() == 2); test_assert(as_type(myType).fields[0].name == "a"); test_assert(as_type(myType).fields[0].type == STRING_TYPE); test_assert(as_type(myType).fields[1].name == "b"); test_assert(as_type(myType).fields[1].type == INT_TYPE); test_assert(as_type(myType).alloc != NULL); test_assert(as_type(myType).copy != NULL); Term* instance = branch.eval("mt = MyType()"); test_assert(is_value_alloced(instance)); } void type_iterator() { Branch branch; Term *t = branch.eval("t = Type()"); Type &type = as_type(t); ReferenceIterator *it; it = start_reference_iterator(t); test_assert(it->finished()); delete it; type.addField(INT_TYPE, "int1"); type.addField(STRING_TYPE, "int1"); it = start_reference_iterator(t); test_assert(it->current() == INT_TYPE); it->advance(); test_assert(it->current() == STRING_TYPE); it->advance(); test_assert(it->finished()); delete it; } void register_tests() { REGISTER_TEST_CASE(type_tests::compound_types); REGISTER_TEST_CASE(type_tests::type_declaration); REGISTER_TEST_CASE(type_tests::type_iterator); } } // namespace type_tests } // namespace circa
Add a little to type tests
Add a little to type tests
C++
mit
andyfischer/circa,andyfischer/circa,andyfischer/circa,andyfischer/circa
e194168cefebbb2c666093c92c594fd804bd19b1
chrome/browser/chromeos/notifications/balloon_collection_impl.cc
chrome/browser/chromeos/notifications/balloon_collection_impl.cc
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/notifications/balloon_collection_impl.h" #include <algorithm> #include "base/logging.h" #include "chrome/browser/chromeos/notifications/balloon_view.h" #include "chrome/browser/chromeos/notifications/notification_panel.h" #include "chrome/browser/notifications/balloon.h" #include "chrome/browser/notifications/notification.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/window_sizer.h" #include "content/common/notification_service.h" #include "ui/gfx/rect.h" #include "ui/gfx/size.h" namespace { // Margin from the edge of the work area const int kVerticalEdgeMargin = 5; const int kHorizontalEdgeMargin = 5; } // namespace namespace chromeos { BalloonCollectionImpl::BalloonCollectionImpl() : notification_ui_(new NotificationPanel()) { registrar_.Add(this, NotificationType::BROWSER_CLOSED, NotificationService::AllSources()); } BalloonCollectionImpl::~BalloonCollectionImpl() { Shutdown(); } void BalloonCollectionImpl::Add(const Notification& notification, Profile* profile) { Balloon* new_balloon = MakeBalloon(notification, profile); base_.Add(new_balloon); new_balloon->Show(); notification_ui_->Add(new_balloon); // There may be no listener in a unit test. if (space_change_listener_) space_change_listener_->OnBalloonSpaceChanged(); } bool BalloonCollectionImpl::AddWebUIMessageCallback( const Notification& notification, const std::string& message, MessageCallback* callback) { Balloon* balloon = FindBalloon(notification); if (!balloon) { delete callback; return false; } BalloonViewHost* host = static_cast<BalloonViewHost*>(balloon->view()->GetHost()); return host->AddWebUIMessageCallback(message, callback); } void BalloonCollectionImpl::AddSystemNotification( const Notification& notification, Profile* profile, bool sticky, bool control) { Balloon* new_balloon = new Balloon(notification, profile, this); new_balloon->set_view( new chromeos::BalloonViewImpl(sticky, control, true)); base_.Add(new_balloon); new_balloon->Show(); notification_ui_->Add(new_balloon); // There may be no listener in a unit test. if (space_change_listener_) space_change_listener_->OnBalloonSpaceChanged(); } bool BalloonCollectionImpl::UpdateNotification( const Notification& notification) { Balloon* balloon = FindBalloon(notification); if (!balloon) return false; balloon->Update(notification); notification_ui_->Update(balloon); return true; } bool BalloonCollectionImpl::UpdateAndShowNotification( const Notification& notification) { Balloon* balloon = FindBalloon(notification); if (!balloon) return false; balloon->Update(notification); bool updated = notification_ui_->Update(balloon); DCHECK(updated); notification_ui_->Show(balloon); return true; } bool BalloonCollectionImpl::RemoveById(const std::string& id) { return base_.CloseById(id); } bool BalloonCollectionImpl::RemoveBySourceOrigin(const GURL& origin) { return base_.CloseAllBySourceOrigin(origin); } void BalloonCollectionImpl::RemoveAll() { base_.CloseAll(); } bool BalloonCollectionImpl::HasSpace() const { return true; } void BalloonCollectionImpl::ResizeBalloon(Balloon* balloon, const gfx::Size& size) { notification_ui_->ResizeNotification(balloon, size); } void BalloonCollectionImpl::OnBalloonClosed(Balloon* source) { notification_ui_->Remove(source); base_.Remove(source); // There may be no listener in a unit test. if (space_change_listener_) space_change_listener_->OnBalloonSpaceChanged(); } const BalloonCollectionImpl::Balloons& BalloonCollectionImpl::GetActiveBalloons() { return base_.balloons(); } void BalloonCollectionImpl::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { DCHECK(type == NotificationType::BROWSER_CLOSED); bool app_closing = *Details<bool>(details).ptr(); // When exiting, we need to shutdown all renderers in // BalloonViewImpl before IO thread gets deleted in the // BrowserProcessImpl's destructor. See http://crbug.com/40810 // for details. if (app_closing) RemoveAll(); } void BalloonCollectionImpl::Shutdown() { // We need to remove the panel first because deleting // views that are not owned by parent will not remove // themselves from the parent. DVLOG(1) << "Shutting down notification UI"; notification_ui_.reset(); } Balloon* BalloonCollectionImpl::MakeBalloon(const Notification& notification, Profile* profile) { Balloon* new_balloon = new Balloon(notification, profile, this); new_balloon->set_view(new chromeos::BalloonViewImpl(false, true, false)); return new_balloon; } } // namespace chromeos // static BalloonCollection* BalloonCollection::Create() { return new chromeos::BalloonCollectionImpl(); }
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/notifications/balloon_collection_impl.h" #include <algorithm> #include "base/logging.h" #include "chrome/browser/chromeos/notifications/balloon_view.h" #include "chrome/browser/chromeos/notifications/notification_panel.h" #include "chrome/browser/notifications/balloon.h" #include "chrome/browser/notifications/notification.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/window_sizer.h" #include "content/common/notification_service.h" #include "ui/gfx/rect.h" #include "ui/gfx/size.h" namespace { // Margin from the edge of the work area const int kVerticalEdgeMargin = 5; const int kHorizontalEdgeMargin = 5; } // namespace namespace chromeos { BalloonCollectionImpl::BalloonCollectionImpl() : notification_ui_(new NotificationPanel()) { registrar_.Add(this, NotificationType::BROWSER_CLOSED, NotificationService::AllSources()); } BalloonCollectionImpl::~BalloonCollectionImpl() { Shutdown(); } void BalloonCollectionImpl::Add(const Notification& notification, Profile* profile) { Balloon* new_balloon = MakeBalloon(notification, profile); base_.Add(new_balloon); new_balloon->Show(); notification_ui_->Add(new_balloon); // There may be no listener in a unit test. if (space_change_listener_) space_change_listener_->OnBalloonSpaceChanged(); // This is used only for testing. if (on_collection_changed_callback_.get()) on_collection_changed_callback_->Run(); } bool BalloonCollectionImpl::AddWebUIMessageCallback( const Notification& notification, const std::string& message, MessageCallback* callback) { Balloon* balloon = FindBalloon(notification); if (!balloon) { delete callback; return false; } BalloonViewHost* host = static_cast<BalloonViewHost*>(balloon->view()->GetHost()); return host->AddWebUIMessageCallback(message, callback); } void BalloonCollectionImpl::AddSystemNotification( const Notification& notification, Profile* profile, bool sticky, bool control) { Balloon* new_balloon = new Balloon(notification, profile, this); new_balloon->set_view( new chromeos::BalloonViewImpl(sticky, control, true)); base_.Add(new_balloon); new_balloon->Show(); notification_ui_->Add(new_balloon); // There may be no listener in a unit test. if (space_change_listener_) space_change_listener_->OnBalloonSpaceChanged(); } bool BalloonCollectionImpl::UpdateNotification( const Notification& notification) { Balloon* balloon = FindBalloon(notification); if (!balloon) return false; balloon->Update(notification); notification_ui_->Update(balloon); return true; } bool BalloonCollectionImpl::UpdateAndShowNotification( const Notification& notification) { Balloon* balloon = FindBalloon(notification); if (!balloon) return false; balloon->Update(notification); bool updated = notification_ui_->Update(balloon); DCHECK(updated); notification_ui_->Show(balloon); return true; } bool BalloonCollectionImpl::RemoveById(const std::string& id) { return base_.CloseById(id); } bool BalloonCollectionImpl::RemoveBySourceOrigin(const GURL& origin) { return base_.CloseAllBySourceOrigin(origin); } void BalloonCollectionImpl::RemoveAll() { base_.CloseAll(); } bool BalloonCollectionImpl::HasSpace() const { return true; } void BalloonCollectionImpl::ResizeBalloon(Balloon* balloon, const gfx::Size& size) { notification_ui_->ResizeNotification(balloon, size); } void BalloonCollectionImpl::OnBalloonClosed(Balloon* source) { notification_ui_->Remove(source); base_.Remove(source); // There may be no listener in a unit test. if (space_change_listener_) space_change_listener_->OnBalloonSpaceChanged(); // This is used only for testing. if (on_collection_changed_callback_.get()) on_collection_changed_callback_->Run(); } const BalloonCollectionImpl::Balloons& BalloonCollectionImpl::GetActiveBalloons() { return base_.balloons(); } void BalloonCollectionImpl::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { DCHECK(type == NotificationType::BROWSER_CLOSED); bool app_closing = *Details<bool>(details).ptr(); // When exiting, we need to shutdown all renderers in // BalloonViewImpl before IO thread gets deleted in the // BrowserProcessImpl's destructor. See http://crbug.com/40810 // for details. if (app_closing) RemoveAll(); } void BalloonCollectionImpl::Shutdown() { // We need to remove the panel first because deleting // views that are not owned by parent will not remove // themselves from the parent. DVLOG(1) << "Shutting down notification UI"; notification_ui_.reset(); } Balloon* BalloonCollectionImpl::MakeBalloon(const Notification& notification, Profile* profile) { Balloon* new_balloon = new Balloon(notification, profile, this); new_balloon->set_view(new chromeos::BalloonViewImpl(false, true, false)); return new_balloon; } } // namespace chromeos // static BalloonCollection* BalloonCollection::Create() { return new chromeos::BalloonCollectionImpl(); }
Call on_collection_changed_callback_ on chromeos
Call on_collection_changed_callback_ on chromeos BUG=81624,chromium-os:15176 TEST=pyauto notification will pass Review URL: http://codereview.chromium.org/7146027 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@89368 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
adobe/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,ropik/chromium,adobe/chromium,adobe/chromium,adobe/chromium,yitian134/chromium,yitian134/chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,ropik/chromium,ropik/chromium,ropik/chromium,gavinp/chromium,yitian134/chromium,gavinp/chromium,ropik/chromium,gavinp/chromium,yitian134/chromium,yitian134/chromium,adobe/chromium,ropik/chromium,gavinp/chromium,ropik/chromium,gavinp/chromium,ropik/chromium,gavinp/chromium,gavinp/chromium,ropik/chromium,yitian134/chromium,adobe/chromium,adobe/chromium,gavinp/chromium,gavinp/chromium,gavinp/chromium,adobe/chromium
eae7f109065e0a7b67dc7a8696a79974bea22621
map_difference.hh
map_difference.hh
/* * Copyright (C) 2015 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <map> #include <set> template<typename Key> struct map_difference { // Entries in left map whose keys don't exist in the right map. std::set<Key> entries_only_on_left; // Entries in right map whose keys don't exist in the left map. std::set<Key> entries_only_on_right; // Entries that appear in both maps with the same value. std::set<Key> entries_in_common; // Entries that appear in both maps but have different values. std::set<Key> entries_differing; map_difference() : entries_only_on_left{} , entries_only_on_right{} , entries_in_common{} , entries_differing{} { } }; template<template<typename...> class Map, typename Key, typename Tp, typename Compare = std::less<Key>, typename Eq = std::equal_to<Tp>, typename Alloc> inline map_difference<Key> difference(const Map<Key, Tp, Compare, Alloc>& left, const Map<Key, Tp, Compare, Alloc>& right, Compare key_comp = Compare(), Eq equals = Eq(), Alloc alloc = Alloc()) { map_difference<Key> diff{}; for (auto&& kv : right) { diff.entries_only_on_right.emplace(kv.first); } for (auto&& kv : left) { auto&& left_key = kv.first; auto&& it = right.find(left_key); if (it != right.end()) { diff.entries_only_on_right.erase(left_key); const Tp& left_value = kv.second; const Tp& right_value = it->second; if (equals(left_value, right_value)) { diff.entries_in_common.emplace(left_key); } else { diff.entries_differing.emplace(left_key); } } else { diff.entries_only_on_left.emplace(left_key); } } return diff; } template<typename Key, typename Tp, typename Compare, typename Eq, typename Alloc> inline map_difference<Key> difference(const std::map<Key, Tp, Compare, Alloc>& left, const std::map<Key, Tp, Compare, Alloc>& right, Eq equals) { return difference(left, right, left.key_comp(), equals); }
/* * Copyright (C) 2015 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <map> #include <set> template<typename Key> struct map_difference { // Entries in left map whose keys don't exist in the right map. std::set<Key> entries_only_on_left; // Entries in right map whose keys don't exist in the left map. std::set<Key> entries_only_on_right; // Entries that appear in both maps with the same value. std::set<Key> entries_in_common; // Entries that appear in both maps but have different values. std::set<Key> entries_differing; map_difference() : entries_only_on_left{} , entries_only_on_right{} , entries_in_common{} , entries_differing{} { } }; /** * Produces a map_difference between the two specified maps, with Key keys and * Tp values, using the provided equality function. In order to work with any * map type, such as std::map and std::unordered_map, Args holds the remaining * type parameters of the particular map type. */ template<template<typename...> class Map, typename Key, typename Tp, typename Eq = std::equal_to<Tp>, typename... Args> inline map_difference<Key> difference(const Map<Key, Tp, Args...>& left, const Map<Key, Tp, Args...>& right, Eq equals = Eq()) { map_difference<Key> diff{}; for (auto&& kv : right) { diff.entries_only_on_right.emplace(kv.first); } for (auto&& kv : left) { auto&& left_key = kv.first; auto&& it = right.find(left_key); if (it != right.end()) { diff.entries_only_on_right.erase(left_key); const Tp& left_value = kv.second; const Tp& right_value = it->second; if (equals(left_value, right_value)) { diff.entries_in_common.emplace(left_key); } else { diff.entries_differing.emplace(left_key); } } else { diff.entries_only_on_left.emplace(left_key); } } return diff; }
Allow on unordered_map
map_difference: Allow on unordered_map This patch changes the map_difference interface so difference() can be called on on unordered_maps. Signed-off-by: Duarte Nunes <[email protected]>
C++
agpl-3.0
kjniemi/scylla,avikivity/scylla,scylladb/scylla,kjniemi/scylla,raphaelsc/scylla,duarten/scylla,raphaelsc/scylla,scylladb/scylla,avikivity/scylla,duarten/scylla,scylladb/scylla,kjniemi/scylla,scylladb/scylla,avikivity/scylla,duarten/scylla,raphaelsc/scylla
d57e789c662eb771d0e1f52361f0c3e5e41dd511
akonadi_next/amazingcompleter.cpp
akonadi_next/amazingcompleter.cpp
/* Copyright (c) 2009 Stephen Kelly <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "amazingcompleter.h" #include <kselectionproxymodel.h> #include <qlistview.h> #include <kdebug.h> using namespace Akonadi; class Akonadi::AmazingCompleterPrivate { public: AmazingCompleterPrivate(AmazingCompleter *completer) //, QAbstractItemModel *model) : m_matchingRole(Qt::DisplayRole), m_completionRole(Qt::DisplayRole), m_minumumLength(3), q_ptr(completer) { } QAbstractItemModel *m_model; KSelectionProxyModel *m_selectionProxyModel; QItemSelectionModel *m_itemSelectionModel; QAbstractItemView *m_view; QWidget *m_widget; int m_matchingRole; int m_completionRole; AmazingCompleter::ViewHandler m_viewHandler; QVariant m_matchData; int m_minumumLength; Q_DECLARE_PUBLIC(AmazingCompleter) AmazingCompleter *q_ptr; }; AmazingCompleter::AmazingCompleter( /* QAbstractItemModel* model, */ QObject* parent) : QObject(parent), d_ptr(new AmazingCompleterPrivate(this) /* ,model) */) { } AmazingCompleter::~AmazingCompleter() { delete d_ptr; } void AmazingCompleter::setCompletionPrefixString(const QString& matchData) { if (matchData.isEmpty()) setCompletionPrefix(QVariant()); else setCompletionPrefix(matchData); } void AmazingCompleter::setCompletionPrefix(const QVariant& matchData) { Q_D(AmazingCompleter); d->m_matchData = matchData; d->m_itemSelectionModel->clearSelection(); if (!matchData.isValid()) { d->m_view->hide(); return; } QString matchString = matchData.toString(); if (matchString.size() < d->m_minumumLength) { d->m_view->hide(); return; } QModelIndex idx = d->m_model->index(0, 0); if (!idx.isValid()) return; QModelIndexList matchingIndexes = d->m_model->match(idx, d->m_matchingRole, matchData, -1); // StartsWith kDebug() << matchingIndexes.size(); if (matchingIndexes.size() > 0) d->m_view->show(); else d->m_view->hide(); foreach(const QModelIndex &matchingIndex, matchingIndexes) d->m_itemSelectionModel->select(matchingIndex, QItemSelectionModel::Select); // Put this in a queued connection? } void AmazingCompleter::sourceRowsInserted(const QModelIndex &parent, int start, int end) { Q_D(AmazingCompleter); if (d->m_matchData.isValid()) setCompletionPrefix(d->m_matchData); } void AmazingCompleter::setModel(QAbstractItemModel* model) { Q_D(AmazingCompleter); d->m_model = model; d->m_itemSelectionModel = new QItemSelectionModel(model, this); d->m_selectionProxyModel = new KSelectionProxyModel(d->m_itemSelectionModel, this); d->m_selectionProxyModel->setSourceModel(d->m_model); connect(d->m_model, SIGNAL(rowsInserted(const QModelIndex &, int, int)), SLOT(sourceRowsInserted(const QModelIndex &, int, int))); } void AmazingCompleter::setView(QAbstractItemView* view, ViewHandler handler) { Q_D(AmazingCompleter); d->m_view = view; QSize size = d->m_widget->size(); size.setHeight(size.height()*10); size.setWidth(size.width() * 2.5); view->move(50, 50); view->resize(size); view->hide(); connectModelToView(d->m_selectionProxyModel, view); } void AmazingCompleter::connectModelToView(QAbstractItemModel *model, QAbstractItemView *view) { view->setModel(model); } void AmazingCompleter::setWidget(QWidget* widget) { Q_D(AmazingCompleter); d->m_widget = widget; } void AmazingCompleter::setCompletionRole(int role) { Q_D(AmazingCompleter); d->m_completionRole = role; } void AmazingCompleter::setMatchingRole(int role) { Q_D(AmazingCompleter); d->m_matchingRole = role; }
/* Copyright (c) 2009 Stephen Kelly <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "amazingcompleter.h" #include <kselectionproxymodel.h> #include <qlistview.h> #include <kdebug.h> using namespace Akonadi; class Akonadi::AmazingCompleterPrivate { public: AmazingCompleterPrivate(AmazingCompleter *completer) //, QAbstractItemModel *model) : m_matchingRole(Qt::DisplayRole), m_completionRole(Qt::DisplayRole), m_minumumLength(3), q_ptr(completer) { } QAbstractItemModel *m_model; KSelectionProxyModel *m_selectionProxyModel; QItemSelectionModel *m_itemSelectionModel; QAbstractItemView *m_view; QWidget *m_widget; int m_matchingRole; int m_completionRole; AmazingCompleter::ViewHandler m_viewHandler; QVariant m_matchData; int m_minumumLength; Q_DECLARE_PUBLIC(AmazingCompleter) AmazingCompleter *q_ptr; }; AmazingCompleter::AmazingCompleter( /* QAbstractItemModel* model, */ QObject* parent) : QObject(parent), d_ptr(new AmazingCompleterPrivate(this) /* ,model) */) { } AmazingCompleter::~AmazingCompleter() { delete d_ptr; } void AmazingCompleter::setCompletionPrefixString(const QString& matchData) { if (matchData.isEmpty()) setCompletionPrefix(QVariant()); else setCompletionPrefix(matchData); } void AmazingCompleter::setCompletionPrefix(const QVariant& matchData) { Q_D(AmazingCompleter); d->m_matchData = matchData; d->m_itemSelectionModel->clearSelection(); if (!matchData.isValid()) { d->m_view->hide(); return; } QString matchString = matchData.toString(); if (matchString.size() < d->m_minumumLength) { d->m_view->hide(); return; } QModelIndex idx = d->m_model->index(0, 0); if (!idx.isValid()) return; QModelIndexList matchingIndexes = d->m_model->match(idx, d->m_matchingRole, matchData, -1); // StartsWith kDebug() << matchingIndexes.size(); if (matchingIndexes.size() > 0) d->m_view->show(); else d->m_view->hide(); foreach(const QModelIndex &matchingIndex, matchingIndexes) d->m_itemSelectionModel->select(matchingIndex, QItemSelectionModel::Select); // Put this in a queued connection? } void AmazingCompleter::sourceRowsInserted(const QModelIndex &parent, int start, int end) { Q_UNUSED( parent ); Q_UNUSED( start ); Q_UNUSED( end ); Q_D(AmazingCompleter); if (d->m_matchData.isValid()) setCompletionPrefix(d->m_matchData); } void AmazingCompleter::setModel(QAbstractItemModel* model) { Q_D(AmazingCompleter); d->m_model = model; d->m_itemSelectionModel = new QItemSelectionModel(model, this); d->m_selectionProxyModel = new KSelectionProxyModel(d->m_itemSelectionModel, this); d->m_selectionProxyModel->setSourceModel(d->m_model); connect(d->m_model, SIGNAL(rowsInserted(const QModelIndex &, int, int)), SLOT(sourceRowsInserted(const QModelIndex &, int, int))); } void AmazingCompleter::setView(QAbstractItemView* view, ViewHandler handler) { Q_D(AmazingCompleter); d->m_view = view; QSize size = d->m_widget->size(); size.setHeight(size.height()*10); size.setWidth(size.width() * 2.5); view->move(50, 50); view->resize(size); view->hide(); connectModelToView(d->m_selectionProxyModel, view); } void AmazingCompleter::connectModelToView(QAbstractItemModel *model, QAbstractItemView *view) { view->setModel(model); } void AmazingCompleter::setWidget(QWidget* widget) { Q_D(AmazingCompleter); d->m_widget = widget; } void AmazingCompleter::setCompletionRole(int role) { Q_D(AmazingCompleter); d->m_completionRole = role; } void AmazingCompleter::setMatchingRole(int role) { Q_D(AmazingCompleter); d->m_matchingRole = role; }
add some Q_UNUSED( )
add some Q_UNUSED( ) svn path=/trunk/KDE/kdepim/akonadi/akonadi_next/; revision=1054802
C++
lgpl-2.1
lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi
8387b8af3ce72d707a182b41211243a4aa493360
backends/jitrt/lib/custom_call.cc
backends/jitrt/lib/custom_call.cc
/* * Copyright 2022 The TensorFlow Runtime Authors * * 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. */ //===- custom_call.cc - ---------------------------------------------------===// // JitRt custom calls library. //===----------------------------------------------------------------------===// #include "tfrt/jitrt/custom_call.h" #include <memory> #include <string> #include <utility> #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringMap.h" #include "mlir/ExecutionEngine/CRunnerUtils.h" namespace tfrt { namespace jitrt { using mlir::failure; using mlir::TypeID; raw_ostream& operator<<(raw_ostream& os, const MemrefView& view) { auto print_arr = [&](string_view name, ArrayRef<int64_t> arr) { os << " " << name << ": ["; if (!arr.empty()) { os << arr[0]; for (int i = 1; i < arr.size(); ++i) os << ", " << arr[i]; } os << "]"; }; os << "MemrefView: dtype: " << view.dtype << " offset: " << view.offset; print_arr("sizes", view.sizes); print_arr("strides", view.strides); return os; } raw_ostream& operator<<(raw_ostream& os, const FlatMemrefView& view) { return os << "FlatMemrefView: dtype: " << view.dtype << " size_in_bytes: " << view.size_in_bytes; } struct CustomCallRegistry::Impl { llvm::StringMap<std::unique_ptr<CustomCall>> custom_calls; }; CustomCallRegistry::CustomCallRegistry() : impl_(std::make_unique<Impl>()) {} void CustomCallRegistry::Register(std::unique_ptr<CustomCall> custom_call) { llvm::StringRef key = custom_call->name(); auto inserted = impl_->custom_calls.insert({key, std::move(custom_call)}); assert(inserted.second && "duplicate custom call registration"); (void)inserted; } CustomCall* CustomCallRegistry::Find(llvm::StringRef callee) const { auto it = impl_->custom_calls.find(callee); if (it == impl_->custom_calls.end()) return nullptr; return it->second.get(); } static std::vector<CustomCallRegistry::RegistrationFunction>* GetCustomCallRegistrations() { static auto* ret = new std::vector<CustomCallRegistry::RegistrationFunction>; return ret; } void RegisterStaticCustomCalls(CustomCallRegistry* custom_call_registry) { for (auto func : *GetCustomCallRegistrations()) func(custom_call_registry); } void AddStaticCustomCallRegistration( CustomCallRegistry::RegistrationFunction registration) { GetCustomCallRegistrations()->push_back(registration); } static mlir::FailureOr<DType> ScalarTypeIdToDType(TypeID type_id) { if (TypeID::get<uint8_t>() == type_id) return DType::UI8; if (TypeID::get<uint32_t>() == type_id) return DType::UI32; if (TypeID::get<uint64_t>() == type_id) return DType::UI64; if (TypeID::get<int32_t>() == type_id) return DType::I32; if (TypeID::get<int64_t>() == type_id) return DType::I64; if (TypeID::get<float>() == type_id) return DType::F32; if (TypeID::get<double>() == type_id) return DType::F64; assert(false && "unsupported data type"); return failure(); } template <typename T, int rank> static ArrayRef<int64_t> Sizes(StridedMemRefType<T, rank>* memref) { return llvm::makeArrayRef(memref->sizes); } template <typename T> static ArrayRef<int64_t> Sizes(StridedMemRefType<T, 0>* memref) { return {}; } template <typename T, int rank> static ArrayRef<int64_t> Strides(StridedMemRefType<T, rank>* memref) { return llvm::makeArrayRef(memref->strides); } template <typename T> static ArrayRef<int64_t> Strides(StridedMemRefType<T, 0>* memref) { return {}; } mlir::FailureOr<MemrefView> CustomCallArgDecoding<MemrefView>::Decode( TypeID type_id, void* value) { // Check that encoded value hold the correct type id. if (type_id != TypeID::get<MemrefView>()) return failure(); // Cast opaque memory to exected encoding. auto* encoded = reinterpret_cast<internal::EncodedMemref*>(value); // Get the memref element data type. void* opaque = reinterpret_cast<void*>(encoded->element_type_id); TypeID element_type_id = TypeID::getFromOpaquePointer(opaque); auto dtype = ScalarTypeIdToDType(element_type_id); if (mlir::failed(dtype)) return failure(); // Unpack the StridedMemRefType into the MemrefView. auto unpack_strided_memref = [&](auto rank_tag) -> MemrefView { constexpr int rank = decltype(rank_tag)::value; using Descriptor = StridedMemRefType<float, rank>; auto* descriptor = reinterpret_cast<Descriptor*>(encoded->descriptor); return MemrefView{*dtype, descriptor->data, descriptor->offset, Sizes(descriptor), Strides(descriptor)}; }; // Dispatch based on the memref rank. switch (encoded->rank) { case 0: return unpack_strided_memref(std::integral_constant<int, 0>{}); case 1: return unpack_strided_memref(std::integral_constant<int, 1>{}); case 2: return unpack_strided_memref(std::integral_constant<int, 2>{}); case 3: return unpack_strided_memref(std::integral_constant<int, 3>{}); case 4: return unpack_strided_memref(std::integral_constant<int, 4>{}); case 5: return unpack_strided_memref(std::integral_constant<int, 5>{}); default: assert(false && "unsupported memref rank"); return failure(); } } mlir::FailureOr<FlatMemrefView> CustomCallArgDecoding<FlatMemrefView>::Decode( mlir::TypeID type_id, void* value) { FlatMemrefView memref; // Check that the encoded value holds the correct type id. if (type_id != TypeID::get<MemrefView>()) return failure(); // Cast opaque memory to the encoded memref. auto* encoded = reinterpret_cast<internal::EncodedMemref*>(value); // Get the memref element data type. void* opaque = reinterpret_cast<void*>(encoded->element_type_id); TypeID element_type_id = TypeID::getFromOpaquePointer(opaque); auto dtype = ScalarTypeIdToDType(element_type_id); if (mlir::failed(dtype)) return failure(); memref.dtype = *dtype; // Unpack the StridedMemRefType into the FlatMemrefView. auto unpack_strided_memref = [&](auto rank_tag) { constexpr int rank = decltype(rank_tag)::value; using Descriptor = StridedMemRefType<float, rank>; auto* descriptor = reinterpret_cast<Descriptor*>(encoded->descriptor); memref.data = descriptor->data; memref.size_in_bytes = std::accumulate(Sizes(descriptor).begin(), Sizes(descriptor).end(), GetHostSize(memref.dtype), std::multiplies<int64_t>()); }; // Dispatch based on the memref rank. switch (encoded->rank) { case 0: unpack_strided_memref(std::integral_constant<int, 0>{}); break; case 1: unpack_strided_memref(std::integral_constant<int, 1>{}); break; case 2: unpack_strided_memref(std::integral_constant<int, 2>{}); break; case 3: unpack_strided_memref(std::integral_constant<int, 3>{}); break; case 4: unpack_strided_memref(std::integral_constant<int, 4>{}); break; case 5: unpack_strided_memref(std::integral_constant<int, 5>{}); break; default: assert(false && "unsupported memref rank"); return failure(); } return memref; } } // namespace jitrt } // namespace tfrt
/* * Copyright 2022 The TensorFlow Runtime Authors * * 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. */ //===- custom_call.cc - ---------------------------------------------------===// // JitRt custom calls library. //===----------------------------------------------------------------------===// #include "tfrt/jitrt/custom_call.h" #include <memory> #include <string> #include <utility> #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringMap.h" #include "mlir/ExecutionEngine/CRunnerUtils.h" namespace tfrt { namespace jitrt { using mlir::failure; using mlir::TypeID; raw_ostream& operator<<(raw_ostream& os, const MemrefView& view) { auto print_arr = [&](string_view name, ArrayRef<int64_t> arr) { os << " " << name << ": ["; if (!arr.empty()) { os << arr[0]; for (int i = 1; i < arr.size(); ++i) os << ", " << arr[i]; } os << "]"; }; os << "MemrefView: dtype: " << view.dtype << " offset: " << view.offset; print_arr("sizes", view.sizes); print_arr("strides", view.strides); return os; } raw_ostream& operator<<(raw_ostream& os, const FlatMemrefView& view) { return os << "FlatMemrefView: dtype: " << view.dtype << " size_in_bytes: " << view.size_in_bytes; } struct CustomCallRegistry::Impl { llvm::StringMap<std::unique_ptr<CustomCall>> custom_calls; }; CustomCallRegistry::CustomCallRegistry() : impl_(std::make_unique<Impl>()) {} void CustomCallRegistry::Register(std::unique_ptr<CustomCall> custom_call) { llvm::StringRef key = custom_call->name(); auto inserted = impl_->custom_calls.insert({key, std::move(custom_call)}); assert(inserted.second && "duplicate custom call registration"); (void)inserted; } CustomCall* CustomCallRegistry::Find(llvm::StringRef callee) const { auto it = impl_->custom_calls.find(callee); if (it == impl_->custom_calls.end()) return nullptr; return it->second.get(); } static std::vector<CustomCallRegistry::RegistrationFunction>* GetCustomCallRegistrations() { static auto* ret = new std::vector<CustomCallRegistry::RegistrationFunction>; return ret; } void RegisterStaticCustomCalls(CustomCallRegistry* custom_call_registry) { for (auto func : *GetCustomCallRegistrations()) func(custom_call_registry); } void AddStaticCustomCallRegistration( CustomCallRegistry::RegistrationFunction registration) { GetCustomCallRegistrations()->push_back(registration); } static mlir::FailureOr<DType> ScalarTypeIdToDType(TypeID type_id) { // f32 is by far the most popular data type in ML models, check it first! if (LLVM_LIKELY(TypeID::get<float>() == type_id)) return DType::F32; if (TypeID::get<uint8_t>() == type_id) return DType::UI8; if (TypeID::get<uint32_t>() == type_id) return DType::UI32; if (TypeID::get<uint64_t>() == type_id) return DType::UI64; if (TypeID::get<int32_t>() == type_id) return DType::I32; if (TypeID::get<int64_t>() == type_id) return DType::I64; if (TypeID::get<double>() == type_id) return DType::F64; assert(false && "unsupported data type"); return failure(); } template <typename T, int rank> static ArrayRef<int64_t> Sizes(StridedMemRefType<T, rank>* memref) { return llvm::makeArrayRef(memref->sizes); } template <typename T> static ArrayRef<int64_t> Sizes(StridedMemRefType<T, 0>* memref) { return {}; } template <typename T, int rank> static ArrayRef<int64_t> Strides(StridedMemRefType<T, rank>* memref) { return llvm::makeArrayRef(memref->strides); } template <typename T> static ArrayRef<int64_t> Strides(StridedMemRefType<T, 0>* memref) { return {}; } template <typename T, int rank> static int64_t NumElements(StridedMemRefType<T, rank>* memref) { int64_t num_elements = 1; for (int d = 0; d < rank; ++d) num_elements *= memref->sizes[d]; return num_elements; } template <typename T> static int64_t NumElements(StridedMemRefType<T, 0>* memref) { return 0; } mlir::FailureOr<MemrefView> CustomCallArgDecoding<MemrefView>::Decode( TypeID type_id, void* value) { // Check that encoded value hold the correct type id. if (type_id != TypeID::get<MemrefView>()) return failure(); // Cast opaque memory to exected encoding. auto* encoded = reinterpret_cast<internal::EncodedMemref*>(value); // Get the memref element data type. void* opaque = reinterpret_cast<void*>(encoded->element_type_id); TypeID element_type_id = TypeID::getFromOpaquePointer(opaque); auto dtype = ScalarTypeIdToDType(element_type_id); if (mlir::failed(dtype)) return failure(); // Unpack the StridedMemRefType into the MemrefView. auto unpack_strided_memref = [&](auto rank_tag) -> MemrefView { constexpr int rank = decltype(rank_tag)::value; using Descriptor = StridedMemRefType<float, rank>; auto* descriptor = reinterpret_cast<Descriptor*>(encoded->descriptor); return MemrefView{*dtype, descriptor->data, descriptor->offset, Sizes(descriptor), Strides(descriptor)}; }; // Dispatch based on the memref rank. switch (encoded->rank) { case 0: return unpack_strided_memref(std::integral_constant<int, 0>{}); case 1: return unpack_strided_memref(std::integral_constant<int, 1>{}); case 2: return unpack_strided_memref(std::integral_constant<int, 2>{}); case 3: return unpack_strided_memref(std::integral_constant<int, 3>{}); case 4: return unpack_strided_memref(std::integral_constant<int, 4>{}); case 5: return unpack_strided_memref(std::integral_constant<int, 5>{}); default: assert(false && "unsupported memref rank"); return failure(); } } mlir::FailureOr<FlatMemrefView> CustomCallArgDecoding<FlatMemrefView>::Decode( mlir::TypeID type_id, void* value) { // Check that the encoded value holds the correct type id. if (type_id != TypeID::get<MemrefView>()) return failure(); // Cast opaque memory to the encoded memref. auto* encoded = reinterpret_cast<internal::EncodedMemref*>(value); // Get the memref element data type. void* opaque = reinterpret_cast<void*>(encoded->element_type_id); TypeID element_type_id = TypeID::getFromOpaquePointer(opaque); auto dtype = ScalarTypeIdToDType(element_type_id); if (mlir::failed(dtype)) return failure(); // Unpack the StridedMemRefType into the FlatMemrefView. auto unpack_strided_memref = [&](auto rank_tag) -> FlatMemrefView { constexpr int rank = decltype(rank_tag)::value; using Descriptor = StridedMemRefType<float, rank>; auto* descriptor = reinterpret_cast<Descriptor*>(encoded->descriptor); FlatMemrefView memref; memref.dtype = *dtype; memref.data = descriptor->data; memref.size_in_bytes = GetHostSize(memref.dtype) * NumElements(descriptor); return memref; }; // Dispatch based on the memref rank. switch (encoded->rank) { case 0: return unpack_strided_memref(std::integral_constant<int, 0>{}); case 1: return unpack_strided_memref(std::integral_constant<int, 1>{}); case 2: return unpack_strided_memref(std::integral_constant<int, 2>{}); case 3: return unpack_strided_memref(std::integral_constant<int, 3>{}); case 4: return unpack_strided_memref(std::integral_constant<int, 4>{}); case 5: return unpack_strided_memref(std::integral_constant<int, 5>{}); default: assert(false && "unsupported memref rank"); return failure(); } } } // namespace jitrt } // namespace tfrt
Optimize FlatMemrefView decoding
[tfrt:jitrt] Optimize FlatMemrefView decoding PiperOrigin-RevId: 447078534
C++
apache-2.0
tensorflow/runtime,tensorflow/runtime,tensorflow/runtime,tensorflow/runtime
5b08728dbb18938fd250ea4f082c99ca18f76d0d
libcaf_core/test/cow_string.cpp
libcaf_core/test/cow_string.cpp
// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in // the main distribution directory for license terms and copyright or visit // https://github.com/actor-framework/actor-framework/blob/master/LICENSE. #define CAF_SUITE cow_string #include "caf/cow_string.hpp" #include "core-test.hpp" using std::make_tuple; using std::string; using std::tuple; using namespace caf; using namespace std::literals; SCENARIO("default constructed COW strings are empty") { WHEN("default-constructing a COW tuple") { cow_string str; THEN("the string is empty") { CHECK(str.empty()); CHECK_EQ(str.size(), 0u); CHECK_EQ(str.length(), 0u); CHECK_EQ(str.begin(), str.end()); CHECK_EQ(str.rbegin(), str.rend()); } AND("the reference count is exactly 1") { CHECK(str.unique()); } } } SCENARIO("COW string are constructible from STD strings") { WHEN("copy-constructing a COW string from an STD string") { auto std_str = "hello world"s; auto str = cow_string{std_str}; THEN("the COW string contains a copy of the original string content") { CHECK(!str.empty()); CHECK_EQ(str.size(), std_str.size()); CHECK_EQ(str.length(), std_str.length()); CHECK_NE(str.begin(), str.end()); CHECK_NE(str.rbegin(), str.rend()); CHECK_EQ(str, std_str); } AND("the reference count is exactly 1") { CHECK(str.unique()); } } WHEN("move-constructing a COW string from an STD string") { auto std_str = "hello world"s; auto str = cow_string{std::move(std_str)}; THEN("the COW string contains the original string content") { CHECK(!str.empty()); CHECK_NE(str.begin(), str.end()); CHECK_NE(str.rbegin(), str.rend()); CHECK_NE(str, std_str); CHECK_EQ(str, "hello world"); } AND("the reference count is exactly 1") { CHECK(str.unique()); } } } SCENARIO("copying COW strings makes shallow copies") { WHEN("copy-constructing a COW string from an another COW string") { auto str1 = cow_string{"hello world"s}; auto str2 = str1; THEN("both COW strings point to the same data") { CHECK_EQ(str1.data(), str2.data()); } AND("the reference count is at least 2") { CHECK(!str1.unique()); CHECK(!str2.unique()); } } } SCENARIO("COW strings detach their content when becoming unshared") { WHEN("copy-constructing a COW string from an another COW string") { auto str1 = cow_string{"hello world"s}; auto str2 = str1; THEN("writing to the original does not change the copy") { str1.unshared() = "foobar"; CHECK_EQ(str1, "foobar"); CHECK_EQ(str2, "hello world"); CHECK(str1.unique()); CHECK(str2.unique()); } } }
// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in // the main distribution directory for license terms and copyright or visit // https://github.com/actor-framework/actor-framework/blob/master/LICENSE. #define CAF_SUITE cow_string #include "caf/cow_string.hpp" #include "core-test.hpp" using std::make_tuple; using std::string; using std::tuple; using namespace caf; using namespace std::literals; SCENARIO("default constructed COW strings are empty") { WHEN("default-constructing a COW tuple") { cow_string str; THEN("the string is empty") { CHECK(str.empty()); CHECK_EQ(str.size(), 0u); CHECK_EQ(str.length(), 0u); CHECK_EQ(str.begin(), str.end()); CHECK_EQ(str.rbegin(), str.rend()); } AND("the reference count is exactly 1") { CHECK(str.unique()); } } } SCENARIO("COW string are constructible from STD strings") { WHEN("copy-constructing a COW string from an STD string") { auto std_str = "hello world"s; auto str = cow_string{std_str}; THEN("the COW string contains a copy of the original string content") { CHECK(!str.empty()); CHECK_EQ(str.size(), std_str.size()); CHECK_EQ(str.length(), std_str.length()); CHECK_NE(str.begin(), str.end()); CHECK_NE(str.rbegin(), str.rend()); CHECK_EQ(str, std_str); } AND("the reference count is exactly 1") { CHECK(str.unique()); } } WHEN("move-constructing a COW string from an STD string") { auto std_str = "hello world"s; auto str = cow_string{std::move(std_str)}; THEN("the COW string contains the original string content") { CHECK(!str.empty()); CHECK_NE(str.begin(), str.end()); CHECK_NE(str.rbegin(), str.rend()); CHECK_NE(str, std_str); CHECK_EQ(str, "hello world"); } AND("the reference count is exactly 1") { CHECK(str.unique()); } } } SCENARIO("copying COW strings makes shallow copies") { WHEN("copy-constructing a COW string from an another COW string") { auto str1 = cow_string{"hello world"s}; auto str2 = str1; THEN("both COW strings point to the same data") { CHECK_EQ(str1.data(), str2.data()); } AND("the reference count is at least 2") { CHECK(!str1.unique()); CHECK(!str2.unique()); } } } SCENARIO("COW strings detach their content when becoming unshared") { WHEN("copy-constructing a COW string from an another COW string") { auto str1 = cow_string{"hello world"s}; auto str2 = str1; THEN("writing to the original does not change the copy") { str1.unshared() = "foobar"; CHECK_EQ(str1, "foobar"); CHECK_EQ(str2, "hello world"); CHECK(str1.unique()); CHECK(str2.unique()); } } }
Fix formatting
Fix formatting
C++
bsd-3-clause
DavadDi/actor-framework,actor-framework/actor-framework,actor-framework/actor-framework,DavadDi/actor-framework,DavadDi/actor-framework,actor-framework/actor-framework,actor-framework/actor-framework,DavadDi/actor-framework
f5bdd93f9ca3fe7cd212f56f805ca2e80c250616
test/asan/TestCases/Linux/odr-violation.cc
test/asan/TestCases/Linux/odr-violation.cc
// FIXME: https://code.google.com/p/address-sanitizer/issues/detail?id=316 // XFAIL: android // // We use fast_unwind_on_malloc=0 to have full unwinding even w/o frame // pointers. This setting is not on by default because it's too expensive. // // Different size: detect a bug if detect_odr_violation>=1 // RUN: %clangxx_asan -DBUILD_SO=1 -fPIC -shared %s -o %t-ODR-SO.so // RUN: %clangxx_asan %s %t-ODR-SO.so -Wl,-R. -o %t-ODR-EXE // RUN: %env_asan_opts=fast_unwind_on_malloc=0:detect_odr_violation=1 not %run %t-ODR-EXE 2>&1 | FileCheck %s // RUN: %env_asan_opts=fast_unwind_on_malloc=0:detect_odr_violation=2 not %run %t-ODR-EXE 2>&1 | FileCheck %s // RUN: %env_asan_opts=fast_unwind_on_malloc=0:detect_odr_violation=0 %run %t-ODR-EXE 2>&1 | FileCheck %s --check-prefix=DISABLED // RUN: %env_asan_opts=fast_unwind_on_malloc=0 not %run %t-ODR-EXE 2>&1 | FileCheck %s // // Same size: report a bug only if detect_odr_violation>=2. // RUN: %clangxx_asan -DBUILD_SO=1 -fPIC -shared %s -o %t-ODR-SO.so -DSZ=100 // RUN: %env_asan_opts=fast_unwind_on_malloc=0:detect_odr_violation=1 %run %t-ODR-EXE 2>&1 | FileCheck %s --check-prefix=DISABLED // RUN: %env_asan_opts=fast_unwind_on_malloc=0:detect_odr_violation=2 not %run %t-ODR-EXE 2>&1 | FileCheck %s // RUN: %env_asan_opts=fast_unwind_on_malloc=0 not %run %t-ODR-EXE 2>&1 | FileCheck %s // RUN: echo "odr_violation:foo::ZZZ" > %t.supp // RUN: %env_asan_opts=fast_unwind_on_malloc=0:detect_odr_violation=2:suppressions=%t.supp not %run %t-ODR-EXE 2>&1 | FileCheck %s // RUN: echo "odr_violation:foo::G" > %t.supp // RUN: %env_asan_opts=fast_unwind_on_malloc=0:detect_odr_violation=2:suppressions=%t.supp %run %t-ODR-EXE 2>&1 | FileCheck %s --check-prefix=DISABLED // RUN: rm -f %t.supp // // Use private aliases for global variables: use indicator symbol to detect ODR violation. // RUN: %clangxx_asan -DBUILD_SO=1 -fPIC -shared -mllvm -asan-use-private-alias %s -o %t-ODR-SO.so -DSZ=100 // RUN: %clangxx_asan -mllvm -asan-use-private-alias %s %t-ODR-SO.so -Wl,-R. -o %t-ODR-EXE // RUN: %env_asan_opts=fast_unwind_on_malloc=0 not %run %t-ODR-EXE 2>&1 | FileCheck %s // GNU driver doesn't handle .so files properly. // REQUIRES: Clang #ifndef SZ # define SZ 4 #endif #if BUILD_SO namespace foo { char G[SZ]; } #else #include <stdio.h> namespace foo { char G[100]; } // CHECK: ERROR: AddressSanitizer: odr-violation // CHECK: size=100 'foo::G' {{.*}}odr-violation.cc:[[@LINE-2]]:22 // CHECK: size={{4|100}} 'foo::G' int main(int argc, char **argv) { printf("PASS: %p\n", &foo::G); } #endif // CHECK: These globals were registered at these points: // CHECK: ODR-EXE // CHECK: ODR-SO // CHECK: SUMMARY: AddressSanitizer: odr-violation: global 'foo::G' at {{.*}}odr-violation.cc // DISABLED: PASS
// FIXME: https://code.google.com/p/address-sanitizer/issues/detail?id=316 // XFAIL: android // // We use fast_unwind_on_malloc=0 to have full unwinding even w/o frame // pointers. This setting is not on by default because it's too expensive. // // Different size: detect a bug if detect_odr_violation>=1 // RUN: %clangxx_asan -DBUILD_SO=1 -fPIC -shared %s -o %t-ODR-SO.so // RUN: %clangxx_asan %s %t-ODR-SO.so -Wl,-R. -o %t-ODR-EXE // RUN: %env_asan_opts=fast_unwind_on_malloc=0:detect_odr_violation=1 not %run %t-ODR-EXE 2>&1 | FileCheck %s // RUN: %env_asan_opts=fast_unwind_on_malloc=0:detect_odr_violation=2 not %run %t-ODR-EXE 2>&1 | FileCheck %s // RUN: %env_asan_opts=fast_unwind_on_malloc=0:detect_odr_violation=0 %run %t-ODR-EXE 2>&1 | FileCheck %s --check-prefix=DISABLED // RUN: %env_asan_opts=fast_unwind_on_malloc=0 not %run %t-ODR-EXE 2>&1 | FileCheck %s // // Same size: report a bug only if detect_odr_violation>=2. // RUN: %clangxx_asan -DBUILD_SO=1 -fPIC -shared %s -o %t-ODR-SO.so -DSZ=100 // RUN: %env_asan_opts=fast_unwind_on_malloc=0:detect_odr_violation=1 %run %t-ODR-EXE 2>&1 | FileCheck %s --check-prefix=DISABLED // RUN: %env_asan_opts=fast_unwind_on_malloc=0:detect_odr_violation=2 not %run %t-ODR-EXE 2>&1 | FileCheck %s // RUN: %env_asan_opts=fast_unwind_on_malloc=0 not %run %t-ODR-EXE 2>&1 | FileCheck %s // RUN: echo "odr_violation:foo::ZZZ" > %t.supp // RUN: %env_asan_opts=fast_unwind_on_malloc=0:detect_odr_violation=2:suppressions=%t.supp not %run %t-ODR-EXE 2>&1 | FileCheck %s // RUN: echo "odr_violation:foo::G" > %t.supp // RUN: %env_asan_opts=fast_unwind_on_malloc=0:detect_odr_violation=2:suppressions=%t.supp %run %t-ODR-EXE 2>&1 | FileCheck %s --check-prefix=DISABLED // RUN: rm -f %t.supp // // Use private aliases for global variables without indicator symbol. // RUN: %clangxx_asan -DBUILD_SO=1 -fPIC -shared -mllvm -asan-use-private-alias %s -o %t-ODR-SO.so -DSZ=100 // RUN: %clangxx_asan -mllvm -asan-use-private-alias %s %t-ODR-SO.so -Wl,-R. -o %t-ODR-EXE // RUN: %env_asan_opts=fast_unwind_on_malloc=0 %run %t-ODR-EXE 2>&1 | FileCheck %s --check-prefix=DISABLED // Use private aliases for global variables: use indicator symbol to detect ODR violation. // RUN: %clangxx_asan -DBUILD_SO=1 -fPIC -shared -mllvm -asan-use-private-alias -mllvm -asan-use-odr-indicator %s -o %t-ODR-SO.so -DSZ=100 // RUN: %clangxx_asan -mllvm -asan-use-private-alias -mllvm -asan-use-odr-indicator %s %t-ODR-SO.so -Wl,-R. -o %t-ODR-EXE // RUN: %env_asan_opts=fast_unwind_on_malloc=0 not %run %t-ODR-EXE 2>&1 | FileCheck %s // GNU driver doesn't handle .so files properly. // REQUIRES: Clang #ifndef SZ # define SZ 4 #endif #if BUILD_SO namespace foo { char G[SZ]; } #else #include <stdio.h> namespace foo { char G[100]; } // CHECK: ERROR: AddressSanitizer: odr-violation // CHECK: size=100 'foo::G' {{.*}}odr-violation.cc:[[@LINE-2]]:22 // CHECK: size={{4|100}} 'foo::G' int main(int argc, char **argv) { printf("PASS: %p\n", &foo::G); } #endif // CHECK: These globals were registered at these points: // CHECK: ODR-EXE // CHECK: ODR-SO // CHECK: SUMMARY: AddressSanitizer: odr-violation: global 'foo::G' at {{.*}}odr-violation.cc // DISABLED: PASS
Split -asan-use-private-alias to -asan-use-odr-indicator
[asan] Split -asan-use-private-alias to -asan-use-odr-indicator Reviewers: eugenis, m.ostapenko, ygribov Subscribers: mehdi_amini, kubamracek, hiraditya, steven_wu, dexonsmith, llvm-commits Differential Revision: https://reviews.llvm.org/D55156 git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@348316 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt
e1d290331e638a4bcefe7a0e7edd54556a97f6c7
ch15/ex15.1.2.3/quote.cpp
ch15/ex15.1.2.3/quote.cpp
#include "quote.h"
#include "Quote.h"
Update quote.cpp
Update quote.cpp
C++
cc0-1.0
zhangzhizhongz3/CppPrimer,zhangzhizhongz3/CppPrimer
90c1f40171baf169e51c28faf625efbe9da86f5e
src/xalanc/Include/XalanMemMgrAutoPtr.hpp
src/xalanc/Include/XalanMemMgrAutoPtr.hpp
/* * Copyright 1999-2004 The Apache Software 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. */ #if !defined(XALANMEMMGRAUTOPTR_HEADER_GUARD_1357924680) #define XALANMEMMGRAUTOPTR_HEADER_GUARD_1357924680 // Base include file. Must be first. #include <xalanc/PlatformSupport/PlatformSupportDefinitions.hpp> #include <xalanc/Include/XalanMemoryManagement.hpp> #include <cstddef> #include <cassert> #include <utility> XALAN_CPP_NAMESPACE_BEGIN XALAN_USING_XERCES(MemoryManager) // An auto_ptr-like class that supports the MemoryManager class. template< class Type, bool toCallDestructor = true> class XalanMemMgrAutoPtr { public: typedef XALAN_STD_QUALIFIER pair<MemoryManager*, Type*> AutoPtrPairType; class MemMgrAutoPtrData : public AutoPtrPairType { public: MemMgrAutoPtrData(): AutoPtrPairType(0,0) { } MemMgrAutoPtrData( MemoryManager* memoryManager, Type* dataPointer): AutoPtrPairType(memoryManager, dataPointer) { invariants(); } bool isInitilized()const { return this->first != 0 && this->second != 0; } void deallocate() { invariants(); if ( isInitilized() ) { if ( toCallDestructor ) { this->second->~Type(); } this->first->deallocate(this->second); } } void reset( MemoryManager* memoryManager , Type* dataPointer) { invariants(); this->first = memoryManager; this->second = dataPointer; invariants(); } private: void invariants() const { assert( isInitilized() || (this->first == 0 && this->second == 0)); } }; XalanMemMgrAutoPtr( MemoryManager& theManager, Type* ptr) : m_pointerInfo(&theManager, ptr) { } XalanMemMgrAutoPtr() : m_pointerInfo() { } XalanMemMgrAutoPtr(const XalanMemMgrAutoPtr<Type, toCallDestructor>& theSource) : m_pointerInfo(((XalanMemMgrAutoPtr<Type>&)theSource).release()) { } XalanMemMgrAutoPtr<Type,toCallDestructor>& operator=(XalanMemMgrAutoPtr<Type,toCallDestructor>& theRHS) { if (this != &theRHS) { m_pointerInfo.deallocate(); m_pointerInfo = theRHS.release(); } return *this; } ~XalanMemMgrAutoPtr() { m_pointerInfo.deallocate(); } Type& operator*() const { return *m_pointerInfo.second; } Type* operator->() const { return m_pointerInfo.second; } Type* get() const { return m_pointerInfo.second; } MemoryManager* getMemoryManager() { return m_pointerInfo.first; } const MemoryManager* getMemoryManager() const { return m_pointerInfo.first; } MemMgrAutoPtrData release() { MemMgrAutoPtrData tmp = m_pointerInfo; m_pointerInfo.reset(0, 0); return MemMgrAutoPtrData(tmp); } Type* releasePtr() { MemMgrAutoPtrData tmp = release(); return tmp.second; } void reset( MemoryManager* theManager = 0, Type* thePointer = 0) { m_pointerInfo.deallocate(); m_pointerInfo.reset(theManager, thePointer); } private: // data member MemMgrAutoPtrData m_pointerInfo; }; template<class Type> class XalanMemMgrAutoPtrArray { public: typedef unsigned int size_type; class MemMgrAutoPtrArrayData { public: MemMgrAutoPtrArrayData(): m_memoryManager(0), m_dataArray(0), m_size(0) { } MemMgrAutoPtrArrayData( MemoryManager* memoryManager, Type* dataPointer, size_type size): m_memoryManager(memoryManager), m_dataArray(dataPointer), m_size(size) { invariants(); } bool isInitilized()const { return m_memoryManager != 0 && m_dataArray != 0 && m_size != 0; } void deallocate() { invariants(); if ( isInitilized() ) { assert ( m_dataArray != 0 ); for ( size_type i = 0; i < m_size ; ++i ) { m_dataArray[i].~Type(); } m_memoryManager->deallocate(m_dataArray); } } void reset( MemoryManager* theMemoryManager, Type* thePointer, size_type size) { invariants(); m_memoryManager = theMemoryManager; m_dataArray = thePointer; m_size = size; invariants(); } MemoryManager* m_memoryManager; Type* m_dataArray; size_type m_size; private: void invariants()const { assert( isInitilized() || (m_memoryManager == 0 && m_dataArray == 0 && m_size == 0)); } }; XalanMemMgrAutoPtrArray( MemoryManager& theManager, Type* ptr, size_type size) : m_pointerInfo( &theManager, ptr, size) { } XalanMemMgrAutoPtrArray() : m_pointerInfo() { } XalanMemMgrAutoPtrArray(const XalanMemMgrAutoPtrArray<Type>& theSource) : m_pointerInfo(((XalanMemMgrAutoPtr<Type>&)theSource).release()) { } XalanMemMgrAutoPtrArray<Type>& operator=(XalanMemMgrAutoPtrArray<Type>& theRHS) { if (this != &theRHS) { m_pointerInfo.deallocate(); m_pointerInfo = theRHS.release(); } return *this; } ~XalanMemMgrAutoPtrArray() { m_pointerInfo.deallocate(); } Type& operator*() const { return *m_pointerInfo.m_dataArray; } Type* operator->() const { return m_pointerInfo.m_dataArray; } Type* get() const { return m_pointerInfo.m_dataArray; } size_type getSize()const { return m_pointerInfo.m_size; } MemoryManager* getMemoryManager() { return m_pointerInfo.m_memoryManager; } const MemoryManager* getMemoryManager() const { return m_pointerInfo.m_memoryManager; } XalanMemMgrAutoPtrArray<Type>& operator++ () { ++m_pointerInfo.m_size; return *this; } /* Since this class is not reference-counted, I don't see how this could work, since the destruction of the temporary will free the controlled pointer. XalanMemMgrAutoPtrArray<Type> operator++ (int) { XalanMemMgrAutoPtrArray<Type> temp = *this; ++*this; return temp; } */ MemMgrAutoPtrArrayData release() { MemMgrAutoPtrArrayData tmp = m_pointerInfo; m_pointerInfo.reset( 0 , 0 , 0); return MemMgrAutoPtrArrayData(tmp); } Type* releasePtr() { MemMgrAutoPtrArrayData tmp = release(); return tmp.m_dataPointer; } void reset( MemoryManager* theManager = 0, Type* thePointer = 0 , size_type size = 0) { m_pointerInfo.deallocate(); m_pointerInfo.reset(theManager, thePointer, size); } Type& operator[](size_type index) const { return m_pointerInfo.m_dataArray[index]; } private: // data member MemMgrAutoPtrArrayData m_pointerInfo; }; XALAN_CPP_NAMESPACE_END #endif // if !defined(XALANMEMMGRAUTOPTR_HEADER_GUARD_1357924680)
/* * Copyright 1999-2004 The Apache Software 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. */ #if !defined(XALANMEMMGRAUTOPTR_HEADER_GUARD_1357924680) #define XALANMEMMGRAUTOPTR_HEADER_GUARD_1357924680 // Base include file. Must be first. #include <xalanc/PlatformSupport/PlatformSupportDefinitions.hpp> #include <xalanc/Include/XalanMemoryManagement.hpp> #include <cstddef> #include <cassert> #include <utility> XALAN_CPP_NAMESPACE_BEGIN XALAN_USING_XERCES(MemoryManager) // An auto_ptr-like class that supports the MemoryManager class. template< class Type, bool toCallDestructor = true> class XalanMemMgrAutoPtr { public: typedef XALAN_STD_QUALIFIER pair<MemoryManager*, Type*> AutoPtrPairType; class MemMgrAutoPtrData : public AutoPtrPairType { public: MemMgrAutoPtrData(): AutoPtrPairType(0,0) { } MemMgrAutoPtrData( MemoryManager* memoryManager, Type* dataPointer): AutoPtrPairType(memoryManager, dataPointer) { invariants(); } bool isInitilized()const { return this->first != 0 && this->second != 0; } void deallocate() { invariants(); if ( isInitilized() ) { if ( toCallDestructor ) { this->second->~Type(); } this->first->deallocate(this->second); } } void reset( MemoryManager* memoryManager , Type* dataPointer) { invariants(); this->first = memoryManager; this->second = dataPointer; invariants(); } private: void invariants() const { assert( isInitilized() || (this->first == 0 && this->second == 0)); } }; XalanMemMgrAutoPtr( MemoryManager& theManager, Type* ptr) : m_pointerInfo(&theManager, ptr) { } XalanMemMgrAutoPtr() : m_pointerInfo() { } XalanMemMgrAutoPtr(const XalanMemMgrAutoPtr<Type, toCallDestructor>& theSource) : m_pointerInfo(((XalanMemMgrAutoPtr<Type>&)theSource).release()) { } XalanMemMgrAutoPtr<Type,toCallDestructor>& operator=(XalanMemMgrAutoPtr<Type,toCallDestructor>& theRHS) { if (this != &theRHS) { m_pointerInfo.deallocate(); m_pointerInfo = theRHS.release(); } return *this; } ~XalanMemMgrAutoPtr() { m_pointerInfo.deallocate(); } Type& operator*() const { return *m_pointerInfo.second; } Type* operator->() const { return m_pointerInfo.second; } Type* get() const { return m_pointerInfo.second; } MemoryManager* getMemoryManager() { return m_pointerInfo.first; } const MemoryManager* getMemoryManager() const { return m_pointerInfo.first; } MemMgrAutoPtrData release() { MemMgrAutoPtrData tmp = m_pointerInfo; m_pointerInfo.reset(0, 0); return MemMgrAutoPtrData(tmp); } Type* releasePtr() { MemMgrAutoPtrData tmp = release(); return tmp.second; } void reset( MemoryManager* theManager = 0, Type* thePointer = 0) { m_pointerInfo.deallocate(); m_pointerInfo.reset(theManager, thePointer); } private: // data member MemMgrAutoPtrData m_pointerInfo; }; template<class Type> class XalanMemMgrAutoPtrArray { public: #if defined(XALAN_STRICT_ANSI_HEADERS) typedef std::size_t size_type; #else typedef size_t size_type; #endif class MemMgrAutoPtrArrayData { public: MemMgrAutoPtrArrayData(): m_memoryManager(0), m_dataArray(0), m_size(0) { } MemMgrAutoPtrArrayData( MemoryManager* memoryManager, Type* dataPointer, size_type size): m_memoryManager(memoryManager), m_dataArray(dataPointer), m_size(size) { invariants(); } bool isInitilized()const { return m_memoryManager != 0 && m_dataArray != 0 && m_size != 0; } void deallocate() { invariants(); if ( isInitilized() ) { assert ( m_dataArray != 0 ); for ( size_type i = 0; i < m_size ; ++i ) { m_dataArray[i].~Type(); } m_memoryManager->deallocate(m_dataArray); } } void reset( MemoryManager* theMemoryManager, Type* thePointer, size_type size) { invariants(); m_memoryManager = theMemoryManager; m_dataArray = thePointer; m_size = size; invariants(); } MemoryManager* m_memoryManager; Type* m_dataArray; size_type m_size; private: void invariants()const { assert( isInitilized() || (m_memoryManager == 0 && m_dataArray == 0 && m_size == 0)); } }; XalanMemMgrAutoPtrArray( MemoryManager& theManager, Type* ptr, size_type size) : m_pointerInfo( &theManager, ptr, size) { } XalanMemMgrAutoPtrArray() : m_pointerInfo() { } XalanMemMgrAutoPtrArray(const XalanMemMgrAutoPtrArray<Type>& theSource) : m_pointerInfo(((XalanMemMgrAutoPtr<Type>&)theSource).release()) { } XalanMemMgrAutoPtrArray<Type>& operator=(XalanMemMgrAutoPtrArray<Type>& theRHS) { if (this != &theRHS) { m_pointerInfo.deallocate(); m_pointerInfo = theRHS.release(); } return *this; } ~XalanMemMgrAutoPtrArray() { m_pointerInfo.deallocate(); } Type& operator*() const { return *m_pointerInfo.m_dataArray; } Type* operator->() const { return m_pointerInfo.m_dataArray; } Type* get() const { return m_pointerInfo.m_dataArray; } size_type getSize()const { return m_pointerInfo.m_size; } MemoryManager* getMemoryManager() { return m_pointerInfo.m_memoryManager; } const MemoryManager* getMemoryManager() const { return m_pointerInfo.m_memoryManager; } XalanMemMgrAutoPtrArray<Type>& operator++ () { ++m_pointerInfo.m_size; return *this; } /* Since this class is not reference-counted, I don't see how this could work, since the destruction of the temporary will free the controlled pointer. XalanMemMgrAutoPtrArray<Type> operator++ (int) { XalanMemMgrAutoPtrArray<Type> temp = *this; ++*this; return temp; } */ MemMgrAutoPtrArrayData release() { MemMgrAutoPtrArrayData tmp = m_pointerInfo; m_pointerInfo.reset(0, 0, 0); return MemMgrAutoPtrArrayData(tmp); } Type* releasePtr() { MemMgrAutoPtrArrayData tmp = release(); return tmp.m_dataArray; } void reset( MemoryManager* theManager = 0, Type* thePointer = 0 , size_type size = 0) { m_pointerInfo.deallocate(); m_pointerInfo.reset(theManager, thePointer, size); } Type& operator[](size_type index) const { return m_pointerInfo.m_dataArray[index]; } private: // data member MemMgrAutoPtrArrayData m_pointerInfo; }; XALAN_CPP_NAMESPACE_END #endif // if !defined(XALANMEMMGRAUTOPTR_HEADER_GUARD_1357924680)
Fix for Jira issue XALANC-466.
Fix for Jira issue XALANC-466.
C++
apache-2.0
apache/xalan-c,apache/xalan-c,apache/xalan-c,apache/xalan-c
1f4b5efd5790b7f6ef8d931abe1d98a824fc86d9
auditd/tests/auditconfig_test.cc
auditd/tests/auditconfig_test.cc
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2015 Couchbase, 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. */ #include <map> #include <cstdlib> #include <iostream> #include <platform/dirutils.h> #include <platform/platform.h> #include <cerrno> #include <cstring> #include "auditd.h" #include "auditconfig.h" #include <gtest/gtest.h> class AuditConfigTest : public ::testing::Test { protected: static void SetUpTestCase() { testdir = std::string("auditconfig-test-") + std::to_string(cb_getpid()); ASSERT_TRUE(CouchbaseDirectoryUtilities::mkdirp(testdir)); // Create the audit_events.json file needed by the configuration std::string fname = testdir + std::string("/audit_events.json"); FILE* fd = fopen(fname.c_str(), "w"); ASSERT_NE(nullptr, fd) << "Unable to open test file '" << fname << "' error: " << strerror(errno); ASSERT_EQ(0, fclose(fd)) << "Failed to close test file '" << fname << "' error: " << strerror(errno); } static void TearDownTestCase() { CouchbaseDirectoryUtilities::rmrf(testdir); } cJSON *json; AuditConfig config; static std::string testdir; virtual void SetUp() { json = createDefaultConfig(); } virtual void TearDown() { cJSON_Delete(json); } cJSON *createDefaultConfig(void) { cJSON *root = cJSON_CreateObject(); cJSON_AddNumberToObject(root, "version", 1); cJSON_AddNumberToObject(root, "rotate_size", 20*1024*1024); cJSON_AddNumberToObject(root, "rotate_interval", 900); cJSON_AddTrueToObject(root, "auditd_enabled"); cJSON_AddTrueToObject(root, "buffered"); cJSON_AddStringToObject(root, "log_path", testdir.c_str()); cJSON_AddStringToObject(root, "descriptors_path", testdir.c_str()); cJSON *sync = cJSON_CreateArray(); cJSON_AddItemToObject(root, "sync", sync); cJSON *disabled = cJSON_CreateArray(); cJSON_AddItemToObject(root, "disabled", disabled); return root; } }; std::string AuditConfigTest::testdir; TEST_F(AuditConfigTest, UnknownTag) { cJSON_AddNumberToObject(json, "foo", 5); EXPECT_THROW(config.initialize_config(json), std::string); } // version TEST_F(AuditConfigTest, TestNoVersion) { cJSON *obj = cJSON_DetachItemFromObject(json, "version"); cJSON_Delete(obj); EXPECT_THROW(config.initialize_config(json), std::string); } TEST_F(AuditConfigTest, TestIllegalDatatypeVersion) { cJSON_ReplaceItemInObject(json, "version", cJSON_CreateString("foobar")); EXPECT_THROW(config.initialize_config(json), std::string); } TEST_F(AuditConfigTest, TestLegalVersion) { for (int version = -100; version < 100; ++version) { cJSON_ReplaceItemInObject(json, "version", cJSON_CreateNumber(version)); if (version == 1) { EXPECT_NO_THROW(config.initialize_config(json)); } else { EXPECT_THROW(config.initialize_config(json), std::string); } } } // rotate_size TEST_F(AuditConfigTest, TestNoRotateSize) { cJSON *obj = cJSON_DetachItemFromObject(json, "rotate_size"); cJSON_Delete(obj); EXPECT_THROW(config.initialize_config(json), std::string); } TEST_F(AuditConfigTest, TestRotateSizeSetGet) { for (size_t ii = 0; ii < 100; ++ii) { config.set_rotate_size(ii); EXPECT_EQ(ii, config.get_rotate_size()); } } TEST_F(AuditConfigTest, TestRotateSizeIllegalDatatype) { cJSON_ReplaceItemInObject(json, "rotate_size", cJSON_CreateString("foobar")); EXPECT_THROW(config.initialize_config(json), std::string); } TEST_F(AuditConfigTest, TestRotateSizeLegalValue) { cJSON_ReplaceItemInObject(json, "rotate_size", cJSON_CreateNumber(100)); EXPECT_NO_THROW(config.initialize_config(json)); } TEST_F(AuditConfigTest, TestRotateSizeIllegalValue) { cJSON_ReplaceItemInObject(json, "rotate_size", cJSON_CreateNumber(-1)); EXPECT_THROW(config.initialize_config(json), std::string); } // rotate_interval TEST_F(AuditConfigTest, TestNoRotateInterval) { cJSON *obj = cJSON_DetachItemFromObject(json, "rotate_interval"); cJSON_Delete(obj); EXPECT_THROW(config.initialize_config(json), std::string); } TEST_F(AuditConfigTest, TestRotateIntervalSetGet) { for (size_t ii = AuditConfig::min_file_rotation_time; ii < AuditConfig::min_file_rotation_time+10; ++ii) { config.set_rotate_interval(ii); EXPECT_EQ(ii, config.get_rotate_interval()); } } TEST_F(AuditConfigTest, TestRotateIntervalIllegalDatatype) { cJSON_ReplaceItemInObject(json, "rotate_interval", cJSON_CreateString("foobar")); EXPECT_THROW(config.initialize_config(json), std::string); } TEST_F(AuditConfigTest, TestRotateIntervalLegalValue) { for (size_t ii = AuditConfig::min_file_rotation_time; ii < AuditConfig::max_file_rotation_time; ii += 1000) { cJSON_ReplaceItemInObject(json, "rotate_interval", cJSON_CreateNumber(ii)); EXPECT_NO_THROW(config.initialize_config(json)); } } TEST_F(AuditConfigTest, TestRotateIntervalIllegalValue) { cJSON_ReplaceItemInObject(json, "rotate_interval", cJSON_CreateNumber(AuditConfig::min_file_rotation_time-1)); EXPECT_THROW(config.initialize_config(json), std::string); cJSON_ReplaceItemInObject(json, "rotate_interval", cJSON_CreateNumber(AuditConfig::max_file_rotation_time+1)); EXPECT_THROW(config.initialize_config(json), std::string); } // auditd_enabled TEST_F(AuditConfigTest, TestNoAuditdEnabled) { cJSON *obj = cJSON_DetachItemFromObject(json, "auditd_enabled"); cJSON_Delete(obj); EXPECT_THROW(config.initialize_config(json), std::string); } TEST_F(AuditConfigTest, TestGetSetAuditdEnabled) { config.set_auditd_enabled(true); EXPECT_TRUE(config.is_auditd_enabled()); config.set_auditd_enabled(false); EXPECT_FALSE(config.is_auditd_enabled()); } TEST_F(AuditConfigTest, TestIllegalDatatypeAuditdEnabled) { cJSON_ReplaceItemInObject(json, "auditd_enabled", cJSON_CreateString("foobar")); EXPECT_THROW(config.initialize_config(json), std::string); } TEST_F(AuditConfigTest, TestLegalAuditdEnabled) { cJSON_ReplaceItemInObject(json, "auditd_enabled", cJSON_CreateTrue()); EXPECT_NO_THROW(config.initialize_config(json)); cJSON_ReplaceItemInObject(json, "auditd_enabled", cJSON_CreateFalse()); EXPECT_NO_THROW(config.initialize_config(json)); } // buffered TEST_F(AuditConfigTest, TestNoBuffered) { // buffered is optional, and enabled unless explicitly disabled cJSON *obj = cJSON_DetachItemFromObject(json, "buffered"); cJSON_Delete(obj); EXPECT_NO_THROW(config.initialize_config(json)); EXPECT_TRUE(config.is_buffered()); } TEST_F(AuditConfigTest, TestGetSetBuffered) { config.set_buffered(true); EXPECT_TRUE(config.is_buffered()); config.set_buffered(false); EXPECT_FALSE(config.is_buffered()); } TEST_F(AuditConfigTest, TestIllegalDatatypeBuffered) { cJSON_ReplaceItemInObject(json, "buffered", cJSON_CreateString("foobar")); EXPECT_THROW(config.initialize_config(json), std::string); } TEST_F(AuditConfigTest, TestLegalBuffered) { cJSON_ReplaceItemInObject(json, "buffered", cJSON_CreateTrue()); EXPECT_NO_THROW(config.initialize_config(json)); cJSON_ReplaceItemInObject(json, "buffered", cJSON_CreateFalse()); EXPECT_NO_THROW(config.initialize_config(json)); } // log_path TEST_F(AuditConfigTest, TestNoLogPath) { cJSON *obj = cJSON_DetachItemFromObject(json, "log_path"); cJSON_Delete(obj); EXPECT_THROW(config.initialize_config(json), std::string); } TEST_F(AuditConfigTest, TestGetSetLogPath) { EXPECT_NO_THROW(config.set_log_directory(testdir)); EXPECT_EQ(testdir, config.get_log_directory()); } TEST_F(AuditConfigTest, TestGetSetSanitizeLogPath) { // Trim of trailing paths std::string path = testdir + std::string("/"); EXPECT_NO_THROW(config.set_log_directory(path)); EXPECT_EQ(testdir, config.get_log_directory()); } #ifdef WIN32 TEST_F(AuditConfigTest, TestGetSetSanitizeLogPathMixedSeparators) { // Trim of trailing paths std::string path = testdir + std::string("/mydir\\baddir"); EXPECT_NO_THROW(config.set_log_directory(path)); EXPECT_EQ(testdir + "\\mydir\\baddir", config.get_log_directory()); EXPECT_TRUE(CouchbaseDirectoryUtilities::rmrf(config.get_log_directory())) << "Failed to remove: " << config.get_log_directory() << ": " << strerror(errno) << std::endl; } #endif #ifndef WIN32 TEST_F(AuditConfigTest, TestFailToCreateDirLogPath) { cJSON_ReplaceItemInObject(json, "log_path", cJSON_CreateString("/itwouldsuckifthisexists")); EXPECT_THROW(config.initialize_config(json), std::string); } #endif TEST_F(AuditConfigTest, TestCreateDirLogPath) { std::string path = testdir + std::string("/mybar"); cJSON_ReplaceItemInObject(json, "log_path", cJSON_CreateString(path.c_str())); EXPECT_NO_THROW(config.initialize_config(json)); EXPECT_TRUE(CouchbaseDirectoryUtilities::rmrf(config.get_log_directory())) << "Failed to remove: " << config.get_log_directory() << ": " << strerror(errno) << std::endl; } // descriptors_path TEST_F(AuditConfigTest, TestNoDescriptorsPath) { cJSON *obj = cJSON_DetachItemFromObject(json, "descriptors_path"); cJSON_Delete(obj); EXPECT_THROW(config.initialize_config(json), std::string); } TEST_F(AuditConfigTest, TestGetSetDescriptorsPath) { EXPECT_NO_THROW(config.set_descriptors_path(testdir)); EXPECT_EQ(testdir, config.get_descriptors_path()); } TEST_F(AuditConfigTest, TestSetMissingEventDescrFileDescriptorsPath) { std::string path = testdir + std::string("/foo"); CouchbaseDirectoryUtilities::mkdirp(path); EXPECT_THROW(config.set_descriptors_path(path), std::string); EXPECT_TRUE(CouchbaseDirectoryUtilities::rmrf(path)) << "Failed to remove: " << path << ": " << strerror(errno) << std::endl; } // Sync TEST_F(AuditConfigTest, TestNoSync) { cJSON *obj = cJSON_DetachItemFromObject(json, "sync"); cJSON_Delete(obj); EXPECT_THROW(config.initialize_config(json), std::string); } TEST_F(AuditConfigTest, TestSpecifySync) { cJSON *array = cJSON_CreateArray(); for (int ii = 0; ii < 10; ++ii) { cJSON_AddItemToArray(array, cJSON_CreateNumber(ii)); } cJSON_ReplaceItemInObject(json, "sync", array); EXPECT_NO_THROW(config.initialize_config(json)); for (uint32_t ii = 0; ii < 100; ++ii) { if (ii < 10) { EXPECT_TRUE(config.is_event_sync(ii)); } else { EXPECT_FALSE(config.is_event_sync(ii)); } } } // Disabled TEST_F(AuditConfigTest, TestNoDisabled) { cJSON *obj = cJSON_DetachItemFromObject(json, "disabled"); cJSON_Delete(obj); EXPECT_THROW(config.initialize_config(json), std::string); } TEST_F(AuditConfigTest, TestSpecifyDisabled) { cJSON *array = cJSON_CreateArray(); for (int ii = 0; ii < 10; ++ii) { cJSON_AddItemToArray(array, cJSON_CreateNumber(ii)); } cJSON_ReplaceItemInObject(json, "disabled", array); EXPECT_NO_THROW(config.initialize_config(json)); for (uint32_t ii = 0; ii < 100; ++ii) { if (ii < 10) { EXPECT_TRUE(config.is_event_disabled(ii)); } else { EXPECT_FALSE(config.is_event_disabled(ii)); } } }
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2015 Couchbase, 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. */ #include <map> #include <cstdlib> #include <iostream> #include <platform/dirutils.h> #include <platform/platform.h> #include <cerrno> #include <cstring> #include "auditd.h" #include "auditconfig.h" #include <gtest/gtest.h> class AuditConfigTest : public ::testing::Test { protected: static void SetUpTestCase() { testdir = std::string("auditconfig-test-") + std::to_string(cb_getpid()); ASSERT_TRUE(CouchbaseDirectoryUtilities::mkdirp(testdir)); // Create the audit_events.json file needed by the configuration std::string fname = testdir + std::string("/audit_events.json"); FILE* fd = fopen(fname.c_str(), "w"); ASSERT_NE(nullptr, fd) << "Unable to open test file '" << fname << "' error: " << strerror(errno); ASSERT_EQ(0, fclose(fd)) << "Failed to close test file '" << fname << "' error: " << strerror(errno); } static void TearDownTestCase() { CouchbaseDirectoryUtilities::rmrf(testdir); } cJSON *json; AuditConfig config; static std::string testdir; virtual void SetUp() { json = createDefaultConfig(); } virtual void TearDown() { cJSON_Delete(json); } cJSON *createDefaultConfig(void) { cJSON *root = cJSON_CreateObject(); cJSON_AddNumberToObject(root, "version", 1); cJSON_AddNumberToObject(root, "rotate_size", 20*1024*1024); cJSON_AddNumberToObject(root, "rotate_interval", 900); cJSON_AddTrueToObject(root, "auditd_enabled"); cJSON_AddTrueToObject(root, "buffered"); cJSON_AddStringToObject(root, "log_path", testdir.c_str()); cJSON_AddStringToObject(root, "descriptors_path", testdir.c_str()); cJSON *sync = cJSON_CreateArray(); cJSON_AddItemToObject(root, "sync", sync); cJSON *disabled = cJSON_CreateArray(); cJSON_AddItemToObject(root, "disabled", disabled); return root; } }; std::string AuditConfigTest::testdir; TEST_F(AuditConfigTest, UnknownTag) { cJSON_AddNumberToObject(json, "foo", 5); EXPECT_THROW(config.initialize_config(json), std::string); } // version TEST_F(AuditConfigTest, TestNoVersion) { cJSON *obj = cJSON_DetachItemFromObject(json, "version"); cJSON_Delete(obj); EXPECT_THROW(config.initialize_config(json), std::string); } TEST_F(AuditConfigTest, TestIllegalDatatypeVersion) { cJSON_ReplaceItemInObject(json, "version", cJSON_CreateString("foobar")); EXPECT_THROW(config.initialize_config(json), std::string); } TEST_F(AuditConfigTest, TestLegalVersion) { for (int version = -100; version < 100; ++version) { cJSON_ReplaceItemInObject(json, "version", cJSON_CreateNumber(version)); if (version == 1) { EXPECT_NO_THROW(config.initialize_config(json)); } else { EXPECT_THROW(config.initialize_config(json), std::string); } } } // rotate_size TEST_F(AuditConfigTest, TestNoRotateSize) { cJSON *obj = cJSON_DetachItemFromObject(json, "rotate_size"); cJSON_Delete(obj); EXPECT_THROW(config.initialize_config(json), std::string); } TEST_F(AuditConfigTest, TestRotateSizeSetGet) { for (size_t ii = 0; ii < 100; ++ii) { config.set_rotate_size(ii); EXPECT_EQ(ii, config.get_rotate_size()); } } TEST_F(AuditConfigTest, TestRotateSizeIllegalDatatype) { cJSON_ReplaceItemInObject(json, "rotate_size", cJSON_CreateString("foobar")); EXPECT_THROW(config.initialize_config(json), std::string); } TEST_F(AuditConfigTest, TestRotateSizeLegalValue) { cJSON_ReplaceItemInObject(json, "rotate_size", cJSON_CreateNumber(100)); EXPECT_NO_THROW(config.initialize_config(json)); } TEST_F(AuditConfigTest, TestRotateSizeIllegalValue) { cJSON_ReplaceItemInObject(json, "rotate_size", cJSON_CreateNumber(-1)); EXPECT_THROW(config.initialize_config(json), std::string); } // rotate_interval TEST_F(AuditConfigTest, TestNoRotateInterval) { cJSON *obj = cJSON_DetachItemFromObject(json, "rotate_interval"); cJSON_Delete(obj); EXPECT_THROW(config.initialize_config(json), std::string); } TEST_F(AuditConfigTest, TestRotateIntervalSetGet) { for (size_t ii = AuditConfig::min_file_rotation_time; ii < AuditConfig::min_file_rotation_time+10; ++ii) { config.set_rotate_interval(uint32_t(ii)); EXPECT_EQ(ii, config.get_rotate_interval()); } } TEST_F(AuditConfigTest, TestRotateIntervalIllegalDatatype) { cJSON_ReplaceItemInObject(json, "rotate_interval", cJSON_CreateString("foobar")); EXPECT_THROW(config.initialize_config(json), std::string); } TEST_F(AuditConfigTest, TestRotateIntervalLegalValue) { for (size_t ii = AuditConfig::min_file_rotation_time; ii < AuditConfig::max_file_rotation_time; ii += 1000) { cJSON_ReplaceItemInObject(json, "rotate_interval", cJSON_CreateNumber(double(ii))); EXPECT_NO_THROW(config.initialize_config(json)); } } TEST_F(AuditConfigTest, TestRotateIntervalIllegalValue) { cJSON_ReplaceItemInObject(json, "rotate_interval", cJSON_CreateNumber(AuditConfig::min_file_rotation_time-1)); EXPECT_THROW(config.initialize_config(json), std::string); cJSON_ReplaceItemInObject(json, "rotate_interval", cJSON_CreateNumber(AuditConfig::max_file_rotation_time+1)); EXPECT_THROW(config.initialize_config(json), std::string); } // auditd_enabled TEST_F(AuditConfigTest, TestNoAuditdEnabled) { cJSON *obj = cJSON_DetachItemFromObject(json, "auditd_enabled"); cJSON_Delete(obj); EXPECT_THROW(config.initialize_config(json), std::string); } TEST_F(AuditConfigTest, TestGetSetAuditdEnabled) { config.set_auditd_enabled(true); EXPECT_TRUE(config.is_auditd_enabled()); config.set_auditd_enabled(false); EXPECT_FALSE(config.is_auditd_enabled()); } TEST_F(AuditConfigTest, TestIllegalDatatypeAuditdEnabled) { cJSON_ReplaceItemInObject(json, "auditd_enabled", cJSON_CreateString("foobar")); EXPECT_THROW(config.initialize_config(json), std::string); } TEST_F(AuditConfigTest, TestLegalAuditdEnabled) { cJSON_ReplaceItemInObject(json, "auditd_enabled", cJSON_CreateTrue()); EXPECT_NO_THROW(config.initialize_config(json)); cJSON_ReplaceItemInObject(json, "auditd_enabled", cJSON_CreateFalse()); EXPECT_NO_THROW(config.initialize_config(json)); } // buffered TEST_F(AuditConfigTest, TestNoBuffered) { // buffered is optional, and enabled unless explicitly disabled cJSON *obj = cJSON_DetachItemFromObject(json, "buffered"); cJSON_Delete(obj); EXPECT_NO_THROW(config.initialize_config(json)); EXPECT_TRUE(config.is_buffered()); } TEST_F(AuditConfigTest, TestGetSetBuffered) { config.set_buffered(true); EXPECT_TRUE(config.is_buffered()); config.set_buffered(false); EXPECT_FALSE(config.is_buffered()); } TEST_F(AuditConfigTest, TestIllegalDatatypeBuffered) { cJSON_ReplaceItemInObject(json, "buffered", cJSON_CreateString("foobar")); EXPECT_THROW(config.initialize_config(json), std::string); } TEST_F(AuditConfigTest, TestLegalBuffered) { cJSON_ReplaceItemInObject(json, "buffered", cJSON_CreateTrue()); EXPECT_NO_THROW(config.initialize_config(json)); cJSON_ReplaceItemInObject(json, "buffered", cJSON_CreateFalse()); EXPECT_NO_THROW(config.initialize_config(json)); } // log_path TEST_F(AuditConfigTest, TestNoLogPath) { cJSON *obj = cJSON_DetachItemFromObject(json, "log_path"); cJSON_Delete(obj); EXPECT_THROW(config.initialize_config(json), std::string); } TEST_F(AuditConfigTest, TestGetSetLogPath) { EXPECT_NO_THROW(config.set_log_directory(testdir)); EXPECT_EQ(testdir, config.get_log_directory()); } TEST_F(AuditConfigTest, TestGetSetSanitizeLogPath) { // Trim of trailing paths std::string path = testdir + std::string("/"); EXPECT_NO_THROW(config.set_log_directory(path)); EXPECT_EQ(testdir, config.get_log_directory()); } #ifdef WIN32 TEST_F(AuditConfigTest, TestGetSetSanitizeLogPathMixedSeparators) { // Trim of trailing paths std::string path = testdir + std::string("/mydir\\baddir"); EXPECT_NO_THROW(config.set_log_directory(path)); EXPECT_EQ(testdir + "\\mydir\\baddir", config.get_log_directory()); EXPECT_TRUE(CouchbaseDirectoryUtilities::rmrf(config.get_log_directory())) << "Failed to remove: " << config.get_log_directory() << ": " << strerror(errno) << std::endl; } #endif #ifndef WIN32 TEST_F(AuditConfigTest, TestFailToCreateDirLogPath) { cJSON_ReplaceItemInObject(json, "log_path", cJSON_CreateString("/itwouldsuckifthisexists")); EXPECT_THROW(config.initialize_config(json), std::string); } #endif TEST_F(AuditConfigTest, TestCreateDirLogPath) { std::string path = testdir + std::string("/mybar"); cJSON_ReplaceItemInObject(json, "log_path", cJSON_CreateString(path.c_str())); EXPECT_NO_THROW(config.initialize_config(json)); EXPECT_TRUE(CouchbaseDirectoryUtilities::rmrf(config.get_log_directory())) << "Failed to remove: " << config.get_log_directory() << ": " << strerror(errno) << std::endl; } // descriptors_path TEST_F(AuditConfigTest, TestNoDescriptorsPath) { cJSON *obj = cJSON_DetachItemFromObject(json, "descriptors_path"); cJSON_Delete(obj); EXPECT_THROW(config.initialize_config(json), std::string); } TEST_F(AuditConfigTest, TestGetSetDescriptorsPath) { EXPECT_NO_THROW(config.set_descriptors_path(testdir)); EXPECT_EQ(testdir, config.get_descriptors_path()); } TEST_F(AuditConfigTest, TestSetMissingEventDescrFileDescriptorsPath) { std::string path = testdir + std::string("/foo"); CouchbaseDirectoryUtilities::mkdirp(path); EXPECT_THROW(config.set_descriptors_path(path), std::string); EXPECT_TRUE(CouchbaseDirectoryUtilities::rmrf(path)) << "Failed to remove: " << path << ": " << strerror(errno) << std::endl; } // Sync TEST_F(AuditConfigTest, TestNoSync) { cJSON *obj = cJSON_DetachItemFromObject(json, "sync"); cJSON_Delete(obj); EXPECT_THROW(config.initialize_config(json), std::string); } TEST_F(AuditConfigTest, TestSpecifySync) { cJSON *array = cJSON_CreateArray(); for (int ii = 0; ii < 10; ++ii) { cJSON_AddItemToArray(array, cJSON_CreateNumber(ii)); } cJSON_ReplaceItemInObject(json, "sync", array); EXPECT_NO_THROW(config.initialize_config(json)); for (uint32_t ii = 0; ii < 100; ++ii) { if (ii < 10) { EXPECT_TRUE(config.is_event_sync(ii)); } else { EXPECT_FALSE(config.is_event_sync(ii)); } } } // Disabled TEST_F(AuditConfigTest, TestNoDisabled) { cJSON *obj = cJSON_DetachItemFromObject(json, "disabled"); cJSON_Delete(obj); EXPECT_THROW(config.initialize_config(json), std::string); } TEST_F(AuditConfigTest, TestSpecifyDisabled) { cJSON *array = cJSON_CreateArray(); for (int ii = 0; ii < 10; ++ii) { cJSON_AddItemToArray(array, cJSON_CreateNumber(ii)); } cJSON_ReplaceItemInObject(json, "disabled", array); EXPECT_NO_THROW(config.initialize_config(json)); for (uint32_t ii = 0; ii < 100; ++ii) { if (ii < 10) { EXPECT_TRUE(config.is_event_disabled(ii)); } else { EXPECT_FALSE(config.is_event_disabled(ii)); } } }
Remove compile warnings on WIN32
Remove compile warnings on WIN32 Change-Id: I7ff72ec03212f932a6e0da83d37a0b9fb454658a Reviewed-on: http://review.couchbase.org/52906 Reviewed-by: Dave Rigby <[email protected]> Tested-by: buildbot <[email protected]>
C++
bsd-3-clause
daverigby/memcached,couchbase/memcached,couchbase/memcached,cloudrain21/memcached-1,daverigby/kv_engine,couchbase/memcached,daverigby/kv_engine,cloudrain21/memcached-1,owendCB/memcached,owendCB/memcached,cloudrain21/memcached-1,daverigby/memcached,owendCB/memcached,daverigby/memcached,daverigby/kv_engine,couchbase/memcached,daverigby/kv_engine,daverigby/memcached,owendCB/memcached,cloudrain21/memcached-1
7c7338e7266fb3c60f9203518f9bb66b84f82814
chrome/common/net/gaia/oauth2_access_token_fetcher_unittest.cc
chrome/common/net/gaia/oauth2_access_token_fetcher_unittest.cc
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // A complete set of unit tests for OAuth2AccessTokenFetcher. #include <string> #include "base/memory/scoped_ptr.h" #include "base/message_loop.h" #include "chrome/common/net/gaia/gaia_urls.h" #include "chrome/common/net/gaia/google_service_auth_error.h" #include "chrome/common/net/http_return.h" #include "chrome/common/net/gaia/oauth2_access_token_consumer.h" #include "chrome/common/net/gaia/oauth2_access_token_fetcher.h" #include "chrome/test/base/testing_profile.h" #include "content/public/common/url_fetcher.h" #include "content/public/common/url_fetcher_delegate.h" #include "content/public/common/url_fetcher_factory.h" #include "content/test/test_browser_thread.h" #include "content/test/test_url_fetcher_factory.h" #include "googleurl/src/gurl.h" #include "net/url_request/url_request.h" #include "net/url_request/url_request_status.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using content::BrowserThread; using content::URLFetcher; using content::URLFetcherDelegate; using content::URLFetcherFactory; using net::ResponseCookies; using net::URLRequestStatus; using testing::_; using testing::Return; namespace { typedef std::vector<std::string> ScopeList; static const char kValidTokenResponse[] = "{" " \"access_token\": \"at1\"," " \"expires_in\": 3600," " \"token_type\": \"Bearer\"" "}"; static const char kTokenResponseNoAccessToken[] = "{" " \"expires_in\": 3600," " \"token_type\": \"Bearer\"" "}"; } class MockUrlFetcherFactory : public ScopedURLFetcherFactory, public URLFetcherFactory { public: MockUrlFetcherFactory() : ScopedURLFetcherFactory(ALLOW_THIS_IN_INITIALIZER_LIST(this)) { } virtual ~MockUrlFetcherFactory() {} MOCK_METHOD4( CreateURLFetcher, URLFetcher* (int id, const GURL& url, URLFetcher::RequestType request_type, URLFetcherDelegate* d)); }; class MockOAuth2AccessTokenConsumer : public OAuth2AccessTokenConsumer { public: MockOAuth2AccessTokenConsumer() {} ~MockOAuth2AccessTokenConsumer() {} MOCK_METHOD1(OnGetTokenSuccess, void(const std::string& access_token)); MOCK_METHOD1(OnGetTokenFailure, void(const GoogleServiceAuthError& error)); }; class OAuth2AccessTokenFetcherTest : public testing::Test { public: OAuth2AccessTokenFetcherTest() : ui_thread_(BrowserThread::UI, &message_loop_), fetcher_(&consumer_, profile_.GetRequestContext()) { } virtual ~OAuth2AccessTokenFetcherTest() { } virtual TestURLFetcher* SetupGetAccessToken( bool fetch_succeeds, int response_code, const std::string& body) { GURL url(GaiaUrls::GetInstance()->oauth2_token_url()); TestURLFetcher* url_fetcher = new TestURLFetcher(0, url, &fetcher_); URLRequestStatus::Status status = fetch_succeeds ? URLRequestStatus::SUCCESS : URLRequestStatus::FAILED; url_fetcher->set_status(URLRequestStatus(status, 0)); if (response_code != 0) url_fetcher->set_response_code(response_code); if (!body.empty()) url_fetcher->SetResponseString(body); EXPECT_CALL(factory_, CreateURLFetcher(_, url, _, _)) .WillOnce(Return(url_fetcher)); return url_fetcher; } protected: MessageLoop message_loop_; content::TestBrowserThread ui_thread_; MockUrlFetcherFactory factory_; MockOAuth2AccessTokenConsumer consumer_; TestingProfile profile_; OAuth2AccessTokenFetcher fetcher_; }; TEST_F(OAuth2AccessTokenFetcherTest, GetAccessTokenRequestFailure) { TestURLFetcher* url_fetcher = SetupGetAccessToken(false, 0, ""); EXPECT_CALL(consumer_, OnGetTokenFailure(_)).Times(1); fetcher_.Start("client_id", "client_secret", "refresh_token", ScopeList()); fetcher_.OnURLFetchComplete(url_fetcher); } TEST_F(OAuth2AccessTokenFetcherTest, GetAccessTokenResponseCodeFailure) { TestURLFetcher* url_fetcher = SetupGetAccessToken(true, RC_FORBIDDEN, ""); EXPECT_CALL(consumer_, OnGetTokenFailure(_)).Times(1); fetcher_.Start("client_id", "client_secret", "refresh_token", ScopeList()); fetcher_.OnURLFetchComplete(url_fetcher); } TEST_F(OAuth2AccessTokenFetcherTest, Success) { TestURLFetcher* url_fetcher = SetupGetAccessToken( true, RC_REQUEST_OK, kValidTokenResponse); EXPECT_CALL(consumer_, OnGetTokenSuccess("at1")).Times(1); fetcher_.Start("client_id", "client_secret", "refresh_token", ScopeList()); fetcher_.OnURLFetchComplete(url_fetcher); } TEST_F(OAuth2AccessTokenFetcherTest, MakeGetAccessTokenBody) { { // No scope. std::string body = "client_id=cid1&" "client_secret=cs1&" "grant_type=refresh_token&" "refresh_token=rt1"; EXPECT_EQ(body, OAuth2AccessTokenFetcher::MakeGetAccessTokenBody( "cid1", "cs1", "rt1", ScopeList())); } { // One scope. std::string body = "client_id=cid1&" "client_secret=cs1&" "grant_type=refresh_token&" "refresh_token=rt1&" "scope=https://www.googleapis.com/foo"; ScopeList scopes; scopes.push_back("https://www.googleapis.com/foo"); EXPECT_EQ(body, OAuth2AccessTokenFetcher::MakeGetAccessTokenBody( "cid1", "cs1", "rt1", scopes)); } { // Multiple scopes. std::string body = "client_id=cid1&" "client_secret=cs1&" "grant_type=refresh_token&" "refresh_token=rt1&" "scope=https://www.googleapis.com/foo+" "https://www.googleapis.com/bar+" "https://www.googleapis.com/baz"; ScopeList scopes; scopes.push_back("https://www.googleapis.com/foo"); scopes.push_back("https://www.googleapis.com/bar"); scopes.push_back("https://www.googleapis.com/baz"); EXPECT_EQ(body, OAuth2AccessTokenFetcher::MakeGetAccessTokenBody( "cid1", "cs1", "rt1", scopes)); } } TEST_F(OAuth2AccessTokenFetcherTest, ParseGetAccessTokenResponse) { { // No body. TestURLFetcher url_fetcher(0, GURL("www.google.com"), NULL); std::string at; EXPECT_FALSE(OAuth2AccessTokenFetcher::ParseGetAccessTokenResponse( &url_fetcher, &at)); EXPECT_TRUE(at.empty()); } { // Bad json. TestURLFetcher url_fetcher(0, GURL("www.google.com"), NULL); url_fetcher.SetResponseString("foo"); std::string at; EXPECT_FALSE(OAuth2AccessTokenFetcher::ParseGetAccessTokenResponse( &url_fetcher, &at)); EXPECT_TRUE(at.empty()); } { // Valid json: access token missing. TestURLFetcher url_fetcher(0, GURL("www.google.com"), NULL); url_fetcher.SetResponseString(kTokenResponseNoAccessToken); std::string at; EXPECT_FALSE(OAuth2AccessTokenFetcher::ParseGetAccessTokenResponse( &url_fetcher, &at)); EXPECT_TRUE(at.empty()); } { // Valid json: all good. TestURLFetcher url_fetcher(0, GURL("www.google.com"), NULL); url_fetcher.SetResponseString(kValidTokenResponse); std::string at; EXPECT_TRUE(OAuth2AccessTokenFetcher::ParseGetAccessTokenResponse( &url_fetcher, &at)); EXPECT_EQ("at1", at); } }
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // A complete set of unit tests for OAuth2AccessTokenFetcher. #include <string> #include "base/memory/scoped_ptr.h" #include "base/message_loop.h" #include "chrome/common/net/gaia/gaia_urls.h" #include "chrome/common/net/gaia/google_service_auth_error.h" #include "chrome/common/net/http_return.h" #include "chrome/common/net/gaia/oauth2_access_token_consumer.h" #include "chrome/common/net/gaia/oauth2_access_token_fetcher.h" #include "chrome/test/base/testing_profile.h" #include "content/public/common/url_fetcher.h" #include "content/public/common/url_fetcher_delegate.h" #include "content/public/common/url_fetcher_factory.h" #include "content/test/test_browser_thread.h" #include "content/test/test_url_fetcher_factory.h" #include "googleurl/src/gurl.h" #include "net/url_request/url_request.h" #include "net/url_request/url_request_status.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using content::BrowserThread; using content::URLFetcher; using content::URLFetcherDelegate; using content::URLFetcherFactory; using net::ResponseCookies; using net::URLRequestStatus; using testing::_; using testing::Return; namespace { typedef std::vector<std::string> ScopeList; static const char kValidTokenResponse[] = "{" " \"access_token\": \"at1\"," " \"expires_in\": 3600," " \"token_type\": \"Bearer\"" "}"; static const char kTokenResponseNoAccessToken[] = "{" " \"expires_in\": 3600," " \"token_type\": \"Bearer\"" "}"; } class MockUrlFetcherFactory : public ScopedURLFetcherFactory, public URLFetcherFactory { public: MockUrlFetcherFactory() : ScopedURLFetcherFactory(ALLOW_THIS_IN_INITIALIZER_LIST(this)) { } virtual ~MockUrlFetcherFactory() {} MOCK_METHOD4( CreateURLFetcher, URLFetcher* (int id, const GURL& url, URLFetcher::RequestType request_type, URLFetcherDelegate* d)); }; class MockOAuth2AccessTokenConsumer : public OAuth2AccessTokenConsumer { public: MockOAuth2AccessTokenConsumer() {} ~MockOAuth2AccessTokenConsumer() {} MOCK_METHOD1(OnGetTokenSuccess, void(const std::string& access_token)); MOCK_METHOD1(OnGetTokenFailure, void(const GoogleServiceAuthError& error)); }; class OAuth2AccessTokenFetcherTest : public testing::Test { public: OAuth2AccessTokenFetcherTest() : ui_thread_(BrowserThread::UI, &message_loop_), fetcher_(&consumer_, profile_.GetRequestContext()) { } virtual ~OAuth2AccessTokenFetcherTest() { } virtual TestURLFetcher* SetupGetAccessToken( bool fetch_succeeds, int response_code, const std::string& body) { GURL url(GaiaUrls::GetInstance()->oauth2_token_url()); TestURLFetcher* url_fetcher = new TestURLFetcher(0, url, &fetcher_); URLRequestStatus::Status status = fetch_succeeds ? URLRequestStatus::SUCCESS : URLRequestStatus::FAILED; url_fetcher->set_status(URLRequestStatus(status, 0)); if (response_code != 0) url_fetcher->set_response_code(response_code); if (!body.empty()) url_fetcher->SetResponseString(body); EXPECT_CALL(factory_, CreateURLFetcher(_, url, _, _)) .WillOnce(Return(url_fetcher)); return url_fetcher; } protected: MessageLoop message_loop_; content::TestBrowserThread ui_thread_; MockUrlFetcherFactory factory_; MockOAuth2AccessTokenConsumer consumer_; TestingProfile profile_; OAuth2AccessTokenFetcher fetcher_; }; TEST_F(OAuth2AccessTokenFetcherTest, FLAKY_GetAccessTokenRequestFailure) { TestURLFetcher* url_fetcher = SetupGetAccessToken(false, 0, ""); EXPECT_CALL(consumer_, OnGetTokenFailure(_)).Times(1); fetcher_.Start("client_id", "client_secret", "refresh_token", ScopeList()); fetcher_.OnURLFetchComplete(url_fetcher); } TEST_F(OAuth2AccessTokenFetcherTest, GetAccessTokenResponseCodeFailure) { TestURLFetcher* url_fetcher = SetupGetAccessToken(true, RC_FORBIDDEN, ""); EXPECT_CALL(consumer_, OnGetTokenFailure(_)).Times(1); fetcher_.Start("client_id", "client_secret", "refresh_token", ScopeList()); fetcher_.OnURLFetchComplete(url_fetcher); } TEST_F(OAuth2AccessTokenFetcherTest, Success) { TestURLFetcher* url_fetcher = SetupGetAccessToken( true, RC_REQUEST_OK, kValidTokenResponse); EXPECT_CALL(consumer_, OnGetTokenSuccess("at1")).Times(1); fetcher_.Start("client_id", "client_secret", "refresh_token", ScopeList()); fetcher_.OnURLFetchComplete(url_fetcher); } TEST_F(OAuth2AccessTokenFetcherTest, MakeGetAccessTokenBody) { { // No scope. std::string body = "client_id=cid1&" "client_secret=cs1&" "grant_type=refresh_token&" "refresh_token=rt1"; EXPECT_EQ(body, OAuth2AccessTokenFetcher::MakeGetAccessTokenBody( "cid1", "cs1", "rt1", ScopeList())); } { // One scope. std::string body = "client_id=cid1&" "client_secret=cs1&" "grant_type=refresh_token&" "refresh_token=rt1&" "scope=https://www.googleapis.com/foo"; ScopeList scopes; scopes.push_back("https://www.googleapis.com/foo"); EXPECT_EQ(body, OAuth2AccessTokenFetcher::MakeGetAccessTokenBody( "cid1", "cs1", "rt1", scopes)); } { // Multiple scopes. std::string body = "client_id=cid1&" "client_secret=cs1&" "grant_type=refresh_token&" "refresh_token=rt1&" "scope=https://www.googleapis.com/foo+" "https://www.googleapis.com/bar+" "https://www.googleapis.com/baz"; ScopeList scopes; scopes.push_back("https://www.googleapis.com/foo"); scopes.push_back("https://www.googleapis.com/bar"); scopes.push_back("https://www.googleapis.com/baz"); EXPECT_EQ(body, OAuth2AccessTokenFetcher::MakeGetAccessTokenBody( "cid1", "cs1", "rt1", scopes)); } } TEST_F(OAuth2AccessTokenFetcherTest, ParseGetAccessTokenResponse) { { // No body. TestURLFetcher url_fetcher(0, GURL("www.google.com"), NULL); std::string at; EXPECT_FALSE(OAuth2AccessTokenFetcher::ParseGetAccessTokenResponse( &url_fetcher, &at)); EXPECT_TRUE(at.empty()); } { // Bad json. TestURLFetcher url_fetcher(0, GURL("www.google.com"), NULL); url_fetcher.SetResponseString("foo"); std::string at; EXPECT_FALSE(OAuth2AccessTokenFetcher::ParseGetAccessTokenResponse( &url_fetcher, &at)); EXPECT_TRUE(at.empty()); } { // Valid json: access token missing. TestURLFetcher url_fetcher(0, GURL("www.google.com"), NULL); url_fetcher.SetResponseString(kTokenResponseNoAccessToken); std::string at; EXPECT_FALSE(OAuth2AccessTokenFetcher::ParseGetAccessTokenResponse( &url_fetcher, &at)); EXPECT_TRUE(at.empty()); } { // Valid json: all good. TestURLFetcher url_fetcher(0, GURL("www.google.com"), NULL); url_fetcher.SetResponseString(kValidTokenResponse); std::string at; EXPECT_TRUE(OAuth2AccessTokenFetcher::ParseGetAccessTokenResponse( &url_fetcher, &at)); EXPECT_EQ("at1", at); } }
Mark OAuth2AccessTokenFetcherTest.GetAccessTokenRequestFailure as flaky, currently has a failure rate of 14%.
Mark OAuth2AccessTokenFetcherTest.GetAccessTokenRequestFailure as flaky, currently has a failure rate of 14%. TBR=markmentovai BUG=113446 Review URL: https://chromiumcodereview.appspot.com/9369036 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@121260 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
dednal/chromium.src,axinging/chromium-crosswalk,keishi/chromium,keishi/chromium,dushu1203/chromium.src,ChromiumWebApps/chromium,anirudhSK/chromium,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,timopulkkinen/BubbleFish,zcbenz/cefode-chromium,ondra-novak/chromium.src,mogoweb/chromium-crosswalk,hujiajie/pa-chromium,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,littlstar/chromium.src,krieger-od/nwjs_chromium.src,pozdnyakov/chromium-crosswalk,ondra-novak/chromium.src,Just-D/chromium-1,littlstar/chromium.src,mogoweb/chromium-crosswalk,robclark/chromium,timopulkkinen/BubbleFish,pozdnyakov/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,keishi/chromium,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,hujiajie/pa-chromium,ondra-novak/chromium.src,jaruba/chromium.src,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,markYoungH/chromium.src,timopulkkinen/BubbleFish,robclark/chromium,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,junmin-zhu/chromium-rivertrail,zcbenz/cefode-chromium,keishi/chromium,M4sse/chromium.src,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk,dednal/chromium.src,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,robclark/chromium,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,markYoungH/chromium.src,anirudhSK/chromium,anirudhSK/chromium,ondra-novak/chromium.src,M4sse/chromium.src,Fireblend/chromium-crosswalk,junmin-zhu/chromium-rivertrail,M4sse/chromium.src,dushu1203/chromium.src,ChromiumWebApps/chromium,mogoweb/chromium-crosswalk,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,robclark/chromium,axinging/chromium-crosswalk,M4sse/chromium.src,axinging/chromium-crosswalk,timopulkkinen/BubbleFish,ChromiumWebApps/chromium,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk,anirudhSK/chromium,PeterWangIntel/chromium-crosswalk,keishi/chromium,pozdnyakov/chromium-crosswalk,timopulkkinen/BubbleFish,ltilve/chromium,robclark/chromium,pozdnyakov/chromium-crosswalk,dushu1203/chromium.src,fujunwei/chromium-crosswalk,ltilve/chromium,zcbenz/cefode-chromium,patrickm/chromium.src,M4sse/chromium.src,patrickm/chromium.src,patrickm/chromium.src,M4sse/chromium.src,markYoungH/chromium.src,crosswalk-project/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,junmin-zhu/chromium-rivertrail,ChromiumWebApps/chromium,markYoungH/chromium.src,hgl888/chromium-crosswalk,ondra-novak/chromium.src,robclark/chromium,Jonekee/chromium.src,nacl-webkit/chrome_deps,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,dushu1203/chromium.src,Jonekee/chromium.src,rogerwang/chromium,mohamed--abdel-maksoud/chromium.src,keishi/chromium,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,jaruba/chromium.src,patrickm/chromium.src,mogoweb/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,markYoungH/chromium.src,M4sse/chromium.src,fujunwei/chromium-crosswalk,bright-sparks/chromium-spacewalk,jaruba/chromium.src,zcbenz/cefode-chromium,hujiajie/pa-chromium,nacl-webkit/chrome_deps,PeterWangIntel/chromium-crosswalk,hujiajie/pa-chromium,rogerwang/chromium,junmin-zhu/chromium-rivertrail,dednal/chromium.src,anirudhSK/chromium,hgl888/chromium-crosswalk,zcbenz/cefode-chromium,Fireblend/chromium-crosswalk,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,Fireblend/chromium-crosswalk,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,robclark/chromium,Pluto-tv/chromium-crosswalk,keishi/chromium,jaruba/chromium.src,Jonekee/chromium.src,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,zcbenz/cefode-chromium,Jonekee/chromium.src,anirudhSK/chromium,ltilve/chromium,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,Just-D/chromium-1,patrickm/chromium.src,littlstar/chromium.src,nacl-webkit/chrome_deps,markYoungH/chromium.src,junmin-zhu/chromium-rivertrail,hujiajie/pa-chromium,Just-D/chromium-1,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,patrickm/chromium.src,rogerwang/chromium,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,nacl-webkit/chrome_deps,zcbenz/cefode-chromium,M4sse/chromium.src,jaruba/chromium.src,zcbenz/cefode-chromium,nacl-webkit/chrome_deps,dushu1203/chromium.src,dushu1203/chromium.src,axinging/chromium-crosswalk,markYoungH/chromium.src,littlstar/chromium.src,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,dednal/chromium.src,ChromiumWebApps/chromium,ltilve/chromium,Pluto-tv/chromium-crosswalk,ltilve/chromium,Chilledheart/chromium,fujunwei/chromium-crosswalk,Fireblend/chromium-crosswalk,nacl-webkit/chrome_deps,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,fujunwei/chromium-crosswalk,Chilledheart/chromium,mogoweb/chromium-crosswalk,Fireblend/chromium-crosswalk,littlstar/chromium.src,axinging/chromium-crosswalk,Chilledheart/chromium,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,junmin-zhu/chromium-rivertrail,bright-sparks/chromium-spacewalk,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,dednal/chromium.src,chuan9/chromium-crosswalk,hujiajie/pa-chromium,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,anirudhSK/chromium,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,littlstar/chromium.src,zcbenz/cefode-chromium,rogerwang/chromium,Fireblend/chromium-crosswalk,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,TheTypoMaster/chromium-crosswalk,timopulkkinen/BubbleFish,axinging/chromium-crosswalk,Jonekee/chromium.src,Chilledheart/chromium,jaruba/chromium.src,littlstar/chromium.src,keishi/chromium,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ltilve/chromium,pozdnyakov/chromium-crosswalk,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,junmin-zhu/chromium-rivertrail,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,bright-sparks/chromium-spacewalk,dednal/chromium.src,pozdnyakov/chromium-crosswalk,keishi/chromium,fujunwei/chromium-crosswalk,Fireblend/chromium-crosswalk,ondra-novak/chromium.src,dushu1203/chromium.src,rogerwang/chromium,hujiajie/pa-chromium,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,rogerwang/chromium,ChromiumWebApps/chromium,robclark/chromium,axinging/chromium-crosswalk,rogerwang/chromium,PeterWangIntel/chromium-crosswalk,ltilve/chromium,bright-sparks/chromium-spacewalk,hujiajie/pa-chromium,Just-D/chromium-1,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,Just-D/chromium-1,Jonekee/chromium.src,rogerwang/chromium,zcbenz/cefode-chromium,anirudhSK/chromium,jaruba/chromium.src,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,fujunwei/chromium-crosswalk,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,ltilve/chromium,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,mogoweb/chromium-crosswalk,mogoweb/chromium-crosswalk,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,junmin-zhu/chromium-rivertrail,ltilve/chromium,fujunwei/chromium-crosswalk,robclark/chromium,ChromiumWebApps/chromium,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,rogerwang/chromium,littlstar/chromium.src,nacl-webkit/chrome_deps,jaruba/chromium.src,Just-D/chromium-1,pozdnyakov/chromium-crosswalk,dednal/chromium.src,krieger-od/nwjs_chromium.src,anirudhSK/chromium,robclark/chromium,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk,timopulkkinen/BubbleFish,mogoweb/chromium-crosswalk,timopulkkinen/BubbleFish,patrickm/chromium.src,PeterWangIntel/chromium-crosswalk,nacl-webkit/chrome_deps,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,Jonekee/chromium.src,dednal/chromium.src,markYoungH/chromium.src,pozdnyakov/chromium-crosswalk,hujiajie/pa-chromium,keishi/chromium,pozdnyakov/chromium-crosswalk,timopulkkinen/BubbleFish,bright-sparks/chromium-spacewalk,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,timopulkkinen/BubbleFish,patrickm/chromium.src,PeterWangIntel/chromium-crosswalk,hujiajie/pa-chromium,dednal/chromium.src,junmin-zhu/chromium-rivertrail,dushu1203/chromium.src,junmin-zhu/chromium-rivertrail,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,nacl-webkit/chrome_deps,hujiajie/pa-chromium,keishi/chromium,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,patrickm/chromium.src,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,M4sse/chromium.src,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,rogerwang/chromium
9ed287e0398c2582805345c303bffbbb63c236ec
src/util/string_util.cpp
src/util/string_util.cpp
/* * Copyright 2006-2008 The FLWOR 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. */ #include "stdafx.h" #include <cerrno> #include <cstdlib> #include "ascii_util.h" #include "cxx_util.h" #include "string_util.h" #include "zorbatypes/zstring.h" #ifdef WIN32 namespace std { // Windows doesn't have these functions -- add them ourselves. static float strtof( char const *s, char **end ) { double const result = std::strtod( s, end ); if ( !errno ) { if ( result < std::numeric_limits<float>::min() || result > std::numeric_limits<float>::max() ) errno = ERANGE; } return static_cast<float>( result ); } inline long long strtoll( char const *s, char **end, int base ) { return ::_strtoi64( s, end, base ); } inline unsigned long long strtoull( char const *s, char **end, int base ) { return ::_strtoui64( s, end, base ); } } // namespace std #endif /* WIN32 */ using namespace std; namespace zorba { namespace ztd { /////////////////////////////////////////////////////////////////////////////// static void check_parse_number( char const *buf, char const *end, bool check_trailing_chars ) { if ( errno == ERANGE ) { zstring const s( buf, end ); throw std::range_error( BUILD_STRING( '"', s, "\": number too big/small" ) ); } if ( end == buf ) throw std::invalid_argument( BUILD_STRING( '"', buf, "\": no digits" ) ); if ( check_trailing_chars ) for ( ; *end; ++end ) // remaining characters, if any, ... if ( !ascii::is_space( *end ) ) // ... may only be whitespace throw std::invalid_argument( BUILD_STRING( '"', *end, "\": invalid character" ) ); } #define ATON_PREAMBLE() \ bool check_trailing_chars; \ char const *pc; \ if ( end ) { \ check_trailing_chars = false; \ } else { \ end = &pc; \ check_trailing_chars = true; \ } \ errno = 0 /////////////////////////////////////////////////////////////////////////////// double atod( char const *buf, char const **end ) { ATON_PREAMBLE(); double const result = std::strtod( buf, (char**)end ); check_parse_number( buf, *end, check_trailing_chars ); return result; } float atof( char const *buf, char const **end ) { ATON_PREAMBLE(); float const result = std::strtof( buf, (char**)end ); check_parse_number( buf, *end, check_trailing_chars ); return result; } long long atoll( char const *buf, char const **end ) { ATON_PREAMBLE(); long long const result = std::strtoll( buf, (char**)end, 10 ); check_parse_number( buf, *end, check_trailing_chars ); return result; } unsigned long long atoull( char const *buf, char const **end ) { ATON_PREAMBLE(); // // We have to check for '-' ourselves since strtoull(3) allows it (oddly). // buf = ascii::trim_start_whitespace( buf ); bool const minus = *buf == '-'; unsigned long long const result = std::strtoull( buf, (char**)end, 10 ); check_parse_number( buf, *end, check_trailing_chars ); if ( minus && result ) { // // Throw an exception only if there was a '-' and the result is non-zero. // Hence, this allows "-0" and treats it as "0". // throw std::invalid_argument( "'-': invalid character for unsigned integer" ); } return result; } char* itoa( long long n, char *buf ) { // // This implementation is much faster than using sprintf(3). // char *s = buf; long long n_prev; do { n_prev = n; n /= 10; *s++ = "9876543210123456789" [ 9 + n_prev - n * 10 ]; } while ( n ); if ( n_prev < 0 ) *s++ = '-'; *s = '\0'; for ( char *t = buf; t < s; ++t ) { char const c = *--s; *s = *t; *t = c; } return buf; } char* itoa( unsigned long long n, char *buf ) { char *s = buf; unsigned long long n_prev; do { n_prev = n; n /= 10; *s++ = "0123456789" [ n_prev - n * 10 ]; } while ( n ); *s = '\0'; for ( char *t = buf; t < s; ++t ) { char const c = *--s; *s = *t; *t = c; } return buf; } /////////////////////////////////////////////////////////////////////////////// } // namespace ztd } // namespace zorba /* vim:set et sw=2 ts=2: */
/* * Copyright 2006-2008 The FLWOR 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. */ #include "stdafx.h" #include <cerrno> #include <cstdlib> #include "ascii_util.h" #include "cxx_util.h" #include "string_util.h" #include "zorbatypes/zstring.h" #ifdef WIN32 namespace std { // Windows doesn't have these functions -- add them ourselves. static float strtof( char const *s, char **end ) { double const result = std::strtod( s, end ); if ( !errno ) { if ( result < std::numeric_limits<float>::min() || result > std::numeric_limits<float>::max() ) errno = ERANGE; } return static_cast<float>( result ); } inline long long strtoll( char const *s, char **end, int base ) { return ::_strtoi64( s, end, base ); } inline unsigned long long strtoull( char const *s, char **end, int base ) { return ::_strtoui64( s, end, base ); } } // namespace std #endif /* WIN32 */ using namespace std; namespace zorba { namespace ztd { /////////////////////////////////////////////////////////////////////////////// static void check_errno( char const *buf, char const *end ) { if ( errno == ERANGE ) { zstring const s( buf, end ); throw std::range_error( BUILD_STRING( '"', s, "\": number too big/small" ) ); } } static void check_parse_number( char const *buf, char const *end, bool check_trailing_chars ) { if ( end == buf ) throw std::invalid_argument( BUILD_STRING( '"', buf, "\": no digits" ) ); if ( check_trailing_chars ) for ( ; *end; ++end ) // remaining characters, if any, ... if ( !ascii::is_space( *end ) ) // ... may only be whitespace throw std::invalid_argument( BUILD_STRING( '"', *end, "\": invalid character" ) ); } #define ATON_PREAMBLE() \ bool check_trailing_chars; \ char const *pc; \ if ( end ) { \ check_trailing_chars = false; \ } else { \ end = &pc; \ check_trailing_chars = true; \ } \ errno = 0 /////////////////////////////////////////////////////////////////////////////// double atod( char const *buf, char const **end ) { ATON_PREAMBLE(); double const result = std::strtod( buf, (char**)end ); check_parse_number( buf, *end, check_trailing_chars ); return result; } float atof( char const *buf, char const **end ) { ATON_PREAMBLE(); float const result = std::strtof( buf, (char**)end ); check_parse_number( buf, *end, check_trailing_chars ); return result; } long long atoll( char const *buf, char const **end ) { ATON_PREAMBLE(); long long const result = std::strtoll( buf, (char**)end, 10 ); check_errno( buf, *end ); check_parse_number( buf, *end, check_trailing_chars ); return result; } unsigned long long atoull( char const *buf, char const **end ) { ATON_PREAMBLE(); // // We have to check for '-' ourselves since strtoull(3) allows it (oddly). // buf = ascii::trim_start_whitespace( buf ); bool const minus = *buf == '-'; unsigned long long const result = std::strtoull( buf, (char**)end, 10 ); check_errno( buf, *end ); check_parse_number( buf, *end, check_trailing_chars ); if ( minus && result ) { // // Throw an exception only if there was a '-' and the result is non-zero. // Hence, this allows "-0" and treats it as "0". // throw std::invalid_argument( "'-': invalid character for unsigned integer" ); } return result; } char* itoa( long long n, char *buf ) { // // This implementation is much faster than using sprintf(3). // char *s = buf; long long n_prev; do { n_prev = n; n /= 10; *s++ = "9876543210123456789" [ 9 + n_prev - n * 10 ]; } while ( n ); if ( n_prev < 0 ) *s++ = '-'; *s = '\0'; for ( char *t = buf; t < s; ++t ) { char const c = *--s; *s = *t; *t = c; } return buf; } char* itoa( unsigned long long n, char *buf ) { char *s = buf; unsigned long long n_prev; do { n_prev = n; n /= 10; *s++ = "0123456789" [ n_prev - n * 10 ]; } while ( n ); *s = '\0'; for ( char *t = buf; t < s; ++t ) { char const c = *--s; *s = *t; *t = c; } return buf; } /////////////////////////////////////////////////////////////////////////////// } // namespace ztd } // namespace zorba /* vim:set et sw=2 ts=2: */
Put string_util back.
Put string_util back.
C++
apache-2.0
bgarrels/zorba,bgarrels/zorba,28msec/zorba,cezarfx/zorba,28msec/zorba,cezarfx/zorba,bgarrels/zorba,cezarfx/zorba,bgarrels/zorba,cezarfx/zorba,28msec/zorba,cezarfx/zorba,cezarfx/zorba,28msec/zorba,28msec/zorba,bgarrels/zorba,bgarrels/zorba,28msec/zorba,bgarrels/zorba,cezarfx/zorba,cezarfx/zorba,28msec/zorba,bgarrels/zorba,28msec/zorba,28msec/zorba,cezarfx/zorba,cezarfx/zorba
a4cf81ba5a7e6de436db66b985522bf3197f8fc0
test/net/integration/websocket/service.cpp
test/net/integration/websocket/service.cpp
#include <service> #include <net/interfaces> #include <net/ws/connector.hpp> #include <http> #include <deque> #include <kernel/crash_context.hpp> struct alignas(SMP_ALIGN) HTTP_server { http::Server* server = nullptr; net::tcp::buffer_t buffer = nullptr; net::WS_server_connector* ws_serve = nullptr; // websocket clients std::deque<net::WebSocket_ptr> clients; }; static SMP::Array<HTTP_server> httpd; static net::WebSocket_ptr& new_client(net::WebSocket_ptr socket) { auto& sys = PER_CPU(httpd); for (auto& client : sys.clients) if (client->is_alive() == false) { return client = std::move(socket); } sys.clients.push_back(std::move(socket)); return sys.clients.back(); } bool accept_client(net::Socket remote, std::string origin) { /* printf("Verifying origin: \"%s\"\n" "Verifying remote: \"%s\"\n", origin.c_str(), remote.to_string().c_str()); */ (void) origin; return remote.address() == net::ip4::Addr(10,0,0,1); } void websocket_service(net::TCP& tcp, uint16_t port) { PER_CPU(httpd).server = new http::Server(tcp); // buffer used for testing PER_CPU(httpd).buffer = net::tcp::construct_buffer(1024); // Set up server connector PER_CPU(httpd).ws_serve = new net::WS_server_connector( [&tcp] (net::WebSocket_ptr ws) { // sometimes we get failed WS connections if (ws == nullptr) return; SET_CRASH("WebSocket created: %s", ws->to_string().c_str()); auto& socket = new_client(std::move(ws)); // if we are still connected, attempt was verified and the handshake was accepted if (socket->is_alive()) { socket->on_read = [] (auto message) { printf("WebSocket on_read: %.*s\n", (int) message->size(), message->data()); }; //socket->write("THIS IS A TEST CAN YOU HEAR THIS?"); for (int i = 0; i < 1000; i++) socket->write(PER_CPU(httpd).buffer, net::op_code::BINARY); //socket->close(); socket->on_close = [] (uint16_t reason) { if (reason == 1000) printf("SUCCESS\n"); else assert(0 && "FAILURE"); }; } }, accept_client); PER_CPU(httpd).server->on_request(*PER_CPU(httpd).ws_serve); PER_CPU(httpd).server->listen(port); /// server /// } void Service::start() { auto& inet = net::Interfaces::get(0); inet.network_config( { 10, 0, 0, 54 }, // IP { 255,255,255, 0 }, // Netmask { 10, 0, 0, 1 }, // Gateway { 10, 0, 0, 1 }); // DNS // run websocket server locally websocket_service(inet.tcp(), 8000); } void ws_client_test(net::TCP& tcp) { /// client /// static http::Basic_client client(tcp); net::WebSocket::connect(client, "ws://10.0.0.1:8001/", [] (net::WebSocket_ptr socket) { if (!socket) { printf("WS Connection failed!\n"); return; } socket->on_error = [] (std::string reason) { printf("Socket error: %s\n", reason.c_str()); }; socket->write("HOLAS\r\n"); PER_CPU(httpd).clients.push_back(std::move(socket)); }); /// client /// }
#include <service> #include <net/interfaces> #include <net/ws/connector.hpp> #include <http> #include <deque> #include <kernel/crash_context.hpp> struct HTTP_server { http::Server* server = nullptr; net::tcp::buffer_t buffer = nullptr; net::WS_server_connector* ws_serve = nullptr; // websocket clients std::deque<net::WebSocket_ptr> clients; }; static HTTP_server httpd; auto& server() { return httpd; } static net::WebSocket_ptr& new_client(net::WebSocket_ptr socket) { auto& sys = server(); for (auto& client : sys.clients) if (client->is_alive() == false) { return client = std::move(socket); } sys.clients.push_back(std::move(socket)); return sys.clients.back(); } bool accept_client(net::Socket remote, std::string origin) { /* printf("Verifying origin: \"%s\"\n" "Verifying remote: \"%s\"\n", origin.c_str(), remote.to_string().c_str()); */ (void) origin; return remote.address() == net::ip4::Addr(10,0,0,1); } void websocket_service(net::TCP& tcp, uint16_t port) { auto& sys = server(); sys.server = new http::Server(tcp); // buffer used for testing sys.buffer = net::tcp::construct_buffer(1024); // Set up server connector sys.ws_serve = new net::WS_server_connector( [&tcp] (net::WebSocket_ptr ws) { // sometimes we get failed WS connections if (ws == nullptr) return; SET_CRASH("WebSocket created: %s", ws->to_string().c_str()); auto& socket = new_client(std::move(ws)); // if we are still connected, attempt was verified and the handshake was accepted if (socket->is_alive()) { socket->on_read = [] (auto message) { printf("WebSocket on_read: %.*s\n", (int) message->size(), message->data()); }; //socket->write("THIS IS A TEST CAN YOU HEAR THIS?"); for (int i = 0; i < 1000; i++) socket->write(server().buffer, net::op_code::BINARY); //socket->close(); socket->on_close = [] (uint16_t reason) { if (reason == 1000) printf("SUCCESS\n"); else assert(0 && "FAILURE"); }; } }, accept_client); sys.server->on_request(*sys.ws_serve); sys.server->listen(port); /// server /// } void Service::start() { auto& inet = net::Interfaces::get(0); inet.network_config( { 10, 0, 0, 54 }, // IP { 255,255,255, 0 }, // Netmask { 10, 0, 0, 1 }, // Gateway { 10, 0, 0, 1 }); // DNS // run websocket server locally websocket_service(inet.tcp(), 8000); } void ws_client_test(net::TCP& tcp) { /// client /// static http::Basic_client client(tcp); net::WebSocket::connect(client, "ws://10.0.0.1:8001/", [] (net::WebSocket_ptr socket) { if (!socket) { printf("WS Connection failed!\n"); return; } socket->on_error = [] (std::string reason) { printf("Socket error: %s\n", reason.c_str()); }; socket->write("HOLAS\r\n"); server().clients.push_back(std::move(socket)); }); /// client /// }
Fix the WebSockets test
test: Fix the WebSockets test
C++
apache-2.0
hioa-cs/IncludeOS,hioa-cs/IncludeOS,hioa-cs/IncludeOS,hioa-cs/IncludeOS,hioa-cs/IncludeOS
4f81569cbff4d76f3a3d13d30e4bb81d2f97e746
test/net/integration/websocket/service.cpp
test/net/integration/websocket/service.cpp
#include <service> #include <net/inet4> #include <net/ws/connector.hpp> #include <http> #include <crash> #include <deque> struct alignas(SMP_ALIGN) HTTP_server { http::Server* server = nullptr; net::tcp::buffer_t buffer = nullptr; net::WS_server_connector* ws_serve = nullptr; // websocket clients std::deque<net::WebSocket_ptr> clients; }; static SMP_ARRAY<HTTP_server> httpd; static net::WebSocket_ptr& new_client(net::WebSocket_ptr socket) { auto& sys = PER_CPU(httpd); for (auto& client : sys.clients) if (client->is_alive() == false) { return client = std::move(socket); } sys.clients.push_back(std::move(socket)); return sys.clients.back(); } bool accept_client(net::Socket remote, std::string origin) { /* printf("Verifying origin: \"%s\"\n" "Verifying remote: \"%s\"\n", origin.c_str(), remote.to_string().c_str()); */ (void) origin; return remote.address() == net::ip4::Addr(10,0,0,1); } void websocket_service(net::TCP& tcp, uint16_t port) { PER_CPU(httpd).server = new http::Server(tcp); // buffer used for testing PER_CPU(httpd).buffer = net::tcp::construct_buffer(1024); // Set up server connector PER_CPU(httpd).ws_serve = new net::WS_server_connector( [&tcp] (net::WebSocket_ptr ws) { // sometimes we get failed WS connections if (ws == nullptr) return; SET_CRASH("WebSocket created: %s", ws->to_string().c_str()); auto& socket = new_client(std::move(ws)); // if we are still connected, attempt was verified and the handshake was accepted if (socket->is_alive()) { socket->on_read = [] (auto message) { printf("WebSocket on_read: %.*s\n", (int) message->size(), message->data()); }; //socket->write("THIS IS A TEST CAN YOU HEAR THIS?"); for (int i = 0; i < 1000; i++) socket->write(PER_CPU(httpd).buffer, net::op_code::BINARY); //socket->close(); socket->on_close = [] (uint16_t reason) { if (reason == 1000) printf("SUCCESS\n"); else assert(0 && "FAILURE"); }; } }, accept_client); PER_CPU(httpd).server->on_request(*PER_CPU(httpd).ws_serve); PER_CPU(httpd).server->listen(port); /// server /// } void Service::start() { auto& inet = net::Inet4::ifconfig<>(0); inet.network_config( { 10, 0, 0, 54 }, // IP { 255,255,255, 0 }, // Netmask { 10, 0, 0, 1 }, // Gateway { 10, 0, 0, 1 }); // DNS // run websocket server locally websocket_service(inet.tcp(), 8000); } void ws_client_test(net::TCP& tcp) { /// client /// static http::Basic_client client(tcp); net::WebSocket::connect(client, "ws://10.0.0.1:8001/", [] (net::WebSocket_ptr socket) { if (!socket) { printf("WS Connection failed!\n"); return; } socket->on_error = [] (std::string reason) { printf("Socket error: %s\n", reason.c_str()); }; socket->write("HOLAS\r\n"); PER_CPU(httpd).clients.push_back(std::move(socket)); }); /// client /// }
#include <service> #include <net/inet4> #include <net/ws/connector.hpp> #include <http> #include <crash> #include <deque> struct alignas(SMP_ALIGN) HTTP_server { http::Server* server = nullptr; net::tcp::buffer_t buffer = nullptr; net::WS_server_connector* ws_serve = nullptr; // websocket clients std::deque<net::WebSocket_ptr> clients; }; static SMP::Array<HTTP_server> httpd; static net::WebSocket_ptr& new_client(net::WebSocket_ptr socket) { auto& sys = PER_CPU(httpd); for (auto& client : sys.clients) if (client->is_alive() == false) { return client = std::move(socket); } sys.clients.push_back(std::move(socket)); return sys.clients.back(); } bool accept_client(net::Socket remote, std::string origin) { /* printf("Verifying origin: \"%s\"\n" "Verifying remote: \"%s\"\n", origin.c_str(), remote.to_string().c_str()); */ (void) origin; return remote.address() == net::ip4::Addr(10,0,0,1); } void websocket_service(net::TCP& tcp, uint16_t port) { PER_CPU(httpd).server = new http::Server(tcp); // buffer used for testing PER_CPU(httpd).buffer = net::tcp::construct_buffer(1024); // Set up server connector PER_CPU(httpd).ws_serve = new net::WS_server_connector( [&tcp] (net::WebSocket_ptr ws) { // sometimes we get failed WS connections if (ws == nullptr) return; SET_CRASH("WebSocket created: %s", ws->to_string().c_str()); auto& socket = new_client(std::move(ws)); // if we are still connected, attempt was verified and the handshake was accepted if (socket->is_alive()) { socket->on_read = [] (auto message) { printf("WebSocket on_read: %.*s\n", (int) message->size(), message->data()); }; //socket->write("THIS IS A TEST CAN YOU HEAR THIS?"); for (int i = 0; i < 1000; i++) socket->write(PER_CPU(httpd).buffer, net::op_code::BINARY); //socket->close(); socket->on_close = [] (uint16_t reason) { if (reason == 1000) printf("SUCCESS\n"); else assert(0 && "FAILURE"); }; } }, accept_client); PER_CPU(httpd).server->on_request(*PER_CPU(httpd).ws_serve); PER_CPU(httpd).server->listen(port); /// server /// } void Service::start() { auto& inet = net::Inet4::ifconfig<>(0); inet.network_config( { 10, 0, 0, 54 }, // IP { 255,255,255, 0 }, // Netmask { 10, 0, 0, 1 }, // Gateway { 10, 0, 0, 1 }); // DNS // run websocket server locally websocket_service(inet.tcp(), 8000); } void ws_client_test(net::TCP& tcp) { /// client /// static http::Basic_client client(tcp); net::WebSocket::connect(client, "ws://10.0.0.1:8001/", [] (net::WebSocket_ptr socket) { if (!socket) { printf("WS Connection failed!\n"); return; } socket->on_error = [] (std::string reason) { printf("Socket error: %s\n", reason.c_str()); }; socket->write("HOLAS\r\n"); PER_CPU(httpd).clients.push_back(std::move(socket)); }); /// client /// }
Fix websocket test, use SMP::Array
test: Fix websocket test, use SMP::Array
C++
apache-2.0
AndreasAakesson/IncludeOS,hioa-cs/IncludeOS,AndreasAakesson/IncludeOS,hioa-cs/IncludeOS,alfred-bratterud/IncludeOS,alfred-bratterud/IncludeOS,alfred-bratterud/IncludeOS,AnnikaH/IncludeOS,alfred-bratterud/IncludeOS,hioa-cs/IncludeOS,mnordsletten/IncludeOS,AndreasAakesson/IncludeOS,hioa-cs/IncludeOS,AnnikaH/IncludeOS,mnordsletten/IncludeOS,AndreasAakesson/IncludeOS,mnordsletten/IncludeOS,mnordsletten/IncludeOS,AndreasAakesson/IncludeOS,mnordsletten/IncludeOS,AndreasAakesson/IncludeOS,AnnikaH/IncludeOS,alfred-bratterud/IncludeOS,mnordsletten/IncludeOS,hioa-cs/IncludeOS,AnnikaH/IncludeOS,AnnikaH/IncludeOS
db654c5451714fcf3f2b7b2deec259cac26c5b60
src/utils/VoxelUtils.cpp
src/utils/VoxelUtils.cpp
//Copyright (c) 2021 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include "VoxelUtils.h" #include "utils/polygonUtils.h" namespace cura { DilationKernel::DilationKernel(GridPoint3 kernel_size, DilationKernel::Type type) : kernel_size(kernel_size) , type(type) { coord_t mult = kernel_size.x * kernel_size.y * kernel_size.z; // multiplier for division to avoid rounding and to avoid use of floating point numbers relative_cells.reserve(mult); GridPoint3 half_kernel = kernel_size / 2; GridPoint3 start = - half_kernel; GridPoint3 end = kernel_size - half_kernel; for (coord_t x = start.x; x < end.x; x++) { for (coord_t y = start.y; y < end.y; y++) { for (coord_t z = start.z; z < end.z; z++) { GridPoint3 current(x, y, z); if (type != Type::CUBE) { GridPoint3 limit((x < 0)? start.x : end.x - 1, (y < 0)? start.y : end.y - 1, (z < 0)? start.z : end.z - 1); if (limit.x == 0) limit.x = 1; if (limit.y == 0) limit.y = 1; if (limit.z == 0) limit.z = 1; const GridPoint3 rel_dists = mult * current / limit; if ((type == Type::DIAMOND && rel_dists.x + rel_dists.y + rel_dists.z > mult) || (type == Type::PRISM && rel_dists.x + rel_dists.y > mult) ) { continue; // don't consider this cell } } relative_cells.emplace_back(x, y, z); } } } } bool VoxelUtils::walkLine(Point3 start, Point3 end, const std::function<bool (GridPoint3)>& process_cell_func) const { Point3 diff = end - start; const GridPoint3 start_cell = toGridPoint(start); const GridPoint3 end_cell = toGridPoint(end); if (start_cell == end_cell) { return process_cell_func(start_cell); } Point3 current_cell = start_cell; while (true) { bool continue_ = process_cell_func(current_cell); if ( ! continue_) return false; if (current_cell == end_cell) break; int stepping_dim = -1; // dimension in which the line next exits the current cell float percentage_along_line = 1.1; for (int dim = 0; dim < 3; dim++) { if (diff[dim] == 0) continue; coord_t crossing_boundary = toLowerCoord(current_cell[dim], dim) + (diff[dim] > 0) * cell_size[dim]; float percentage_along_line_here = (crossing_boundary - start[dim]) / static_cast<float>(diff[dim]); if (percentage_along_line_here < percentage_along_line) { percentage_along_line = percentage_along_line_here; stepping_dim = dim; } } assert(stepping_dim != -1); current_cell[stepping_dim] += (diff[stepping_dim] > 0) ? 1 : -1; } return true; } bool VoxelUtils::walkPolygons(const Polygons& polys, coord_t z, const std::function<bool (GridPoint3)>& process_cell_func) const { for (ConstPolygonRef poly : polys) { Point last = poly.back(); for (Point p : poly) { bool continue_ = walkLine(Point3(last.X, last.Y, z), Point3(p.X, p.Y, z), process_cell_func); if ( ! continue_) return false; last = p; } } return true; } bool VoxelUtils::walkDilatedPolygons(const Polygons& polys, coord_t z, const DilationKernel& kernel, const std::function<bool (GridPoint3)>& process_cell_func) const { Polygons translated = polys; const Point3 translation = (Point3(1,1,1) - kernel.kernel_size % 2) * cell_size / 2; if (translation.x && translation.y) { translated.translate(Point(translation.x, translation.y)); } return walkPolygons(translated, z + translation.z, [&kernel, &process_cell_func, this](GridPoint3 cell) { return dilate(cell, kernel, process_cell_func); }); } bool VoxelUtils::walkAreas(const Polygons& polys, coord_t z, const std::function<bool (GridPoint3)>& process_cell_func) const { Polygons translated = polys; const Point3 translation = - cell_size / 2; // offset half a cell so that the dots of spreadDotsArea are centered on the middle of the cell isntead of the lower corners. if (translation.x && translation.y) { translated.translate(Point(translation.x, translation.y)); } return _walkAreas(translated, z, process_cell_func); } bool VoxelUtils::_walkAreas(const Polygons& polys, coord_t z, const std::function<bool (GridPoint3)>& process_cell_func) const { std::vector<Point> skin_points = PolygonUtils::spreadDotsArea(polys, cell_size.x); for (Point p : skin_points) { bool continue_ = process_cell_func(toGridPoint(Point3(p.X + cell_size.x / 2, p.Y + cell_size.y / 2, z))); if ( ! continue_) return false; } return true; } bool VoxelUtils::walkDilatedAreas(const Polygons& polys, coord_t z, const DilationKernel& kernel, const std::function<bool (GridPoint3)>& process_cell_func) const { Polygons translated = polys; const Point3 translation = (Point3(1,1,1) - kernel.kernel_size % 2) * cell_size / 2 // offset half a cell when using a n even kernel - cell_size / 2; // offset half a cell so that the dots of spreadDotsArea are centered on the middle of the cell isntead of the lower corners. if (translation.x && translation.y) { translated.translate(Point(translation.x, translation.y)); } return _walkAreas(translated, z + translation.z, [&kernel, &process_cell_func, this](GridPoint3 cell) { return dilate(cell, kernel, process_cell_func); }); } bool VoxelUtils::dilate(GridPoint3 loc, const DilationKernel& kernel, const std::function<bool (GridPoint3)>& process_cell_func) const { for (const GridPoint3& rel : kernel.relative_cells) { bool continue_ = process_cell_func(loc + rel); if ( ! continue_) return false; } return true; } std::function<bool (GridPoint3)> VoxelUtils::dilate(const DilationKernel& kernel, const std::function<bool (GridPoint3)>& process_cell_func) const { return [&process_cell_func, &kernel, this](GridPoint3 p) { return dilate(p, kernel, process_cell_func); }; } } // namespace cura
//Copyright (c) 2021 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include "VoxelUtils.h" #include "utils/polygonUtils.h" namespace cura { DilationKernel::DilationKernel(GridPoint3 kernel_size, DilationKernel::Type type) : kernel_size(kernel_size) , type(type) { coord_t mult = kernel_size.x * kernel_size.y * kernel_size.z; // multiplier for division to avoid rounding and to avoid use of floating point numbers relative_cells.reserve(mult); GridPoint3 half_kernel = kernel_size / 2; GridPoint3 start = - half_kernel; GridPoint3 end = kernel_size - half_kernel; for (coord_t x = start.x; x < end.x; x++) { for (coord_t y = start.y; y < end.y; y++) { for (coord_t z = start.z; z < end.z; z++) { GridPoint3 current(x, y, z); if (type != Type::CUBE) { GridPoint3 limit((x < 0)? start.x : end.x - 1, (y < 0)? start.y : end.y - 1, (z < 0)? start.z : end.z - 1); if (limit.x == 0) limit.x = 1; if (limit.y == 0) limit.y = 1; if (limit.z == 0) limit.z = 1; const GridPoint3 rel_dists = mult * current / limit; if ((type == Type::DIAMOND && rel_dists.x + rel_dists.y + rel_dists.z > mult) || (type == Type::PRISM && rel_dists.x + rel_dists.y > mult) ) { continue; // don't consider this cell } } relative_cells.emplace_back(x, y, z); } } } } bool VoxelUtils::walkLine(Point3 start, Point3 end, const std::function<bool (GridPoint3)>& process_cell_func) const { Point3 diff = end - start; const GridPoint3 start_cell = toGridPoint(start); const GridPoint3 end_cell = toGridPoint(end); if (start_cell == end_cell) { return process_cell_func(start_cell); } Point3 current_cell = start_cell; while (true) { bool continue_ = process_cell_func(current_cell); if ( ! continue_) return false; int stepping_dim = -1; // dimension in which the line next exits the current cell float percentage_along_line = std::numeric_limits<float>::max(); for (int dim = 0; dim < 3; dim++) { if (diff[dim] == 0) continue; coord_t crossing_boundary = toLowerCoord(current_cell[dim], dim) + (diff[dim] > 0) * cell_size[dim]; float percentage_along_line_here = (crossing_boundary - start[dim]) / static_cast<float>(diff[dim]); if (percentage_along_line_here < percentage_along_line) { percentage_along_line = percentage_along_line_here; stepping_dim = dim; } } assert(stepping_dim != -1); if (percentage_along_line > 1.0) return true; // next cell is beyond the end current_cell[stepping_dim] += (diff[stepping_dim] > 0) ? 1 : -1; } return true; } bool VoxelUtils::walkPolygons(const Polygons& polys, coord_t z, const std::function<bool (GridPoint3)>& process_cell_func) const { for (ConstPolygonRef poly : polys) { Point last = poly.back(); for (Point p : poly) { bool continue_ = walkLine(Point3(last.X, last.Y, z), Point3(p.X, p.Y, z), process_cell_func); if ( ! continue_) return false; last = p; } } return true; } bool VoxelUtils::walkDilatedPolygons(const Polygons& polys, coord_t z, const DilationKernel& kernel, const std::function<bool (GridPoint3)>& process_cell_func) const { Polygons translated = polys; const Point3 translation = (Point3(1,1,1) - kernel.kernel_size % 2) * cell_size / 2; if (translation.x && translation.y) { translated.translate(Point(translation.x, translation.y)); } return walkPolygons(translated, z + translation.z, [&kernel, &process_cell_func, this](GridPoint3 cell) { return dilate(cell, kernel, process_cell_func); }); } bool VoxelUtils::walkAreas(const Polygons& polys, coord_t z, const std::function<bool (GridPoint3)>& process_cell_func) const { Polygons translated = polys; const Point3 translation = - cell_size / 2; // offset half a cell so that the dots of spreadDotsArea are centered on the middle of the cell isntead of the lower corners. if (translation.x && translation.y) { translated.translate(Point(translation.x, translation.y)); } return _walkAreas(translated, z, process_cell_func); } bool VoxelUtils::_walkAreas(const Polygons& polys, coord_t z, const std::function<bool (GridPoint3)>& process_cell_func) const { std::vector<Point> skin_points = PolygonUtils::spreadDotsArea(polys, cell_size.x); for (Point p : skin_points) { bool continue_ = process_cell_func(toGridPoint(Point3(p.X + cell_size.x / 2, p.Y + cell_size.y / 2, z))); if ( ! continue_) return false; } return true; } bool VoxelUtils::walkDilatedAreas(const Polygons& polys, coord_t z, const DilationKernel& kernel, const std::function<bool (GridPoint3)>& process_cell_func) const { Polygons translated = polys; const Point3 translation = (Point3(1,1,1) - kernel.kernel_size % 2) * cell_size / 2 // offset half a cell when using a n even kernel - cell_size / 2; // offset half a cell so that the dots of spreadDotsArea are centered on the middle of the cell isntead of the lower corners. if (translation.x && translation.y) { translated.translate(Point(translation.x, translation.y)); } return _walkAreas(translated, z + translation.z, [&kernel, &process_cell_func, this](GridPoint3 cell) { return dilate(cell, kernel, process_cell_func); }); } bool VoxelUtils::dilate(GridPoint3 loc, const DilationKernel& kernel, const std::function<bool (GridPoint3)>& process_cell_func) const { for (const GridPoint3& rel : kernel.relative_cells) { bool continue_ = process_cell_func(loc + rel); if ( ! continue_) return false; } return true; } std::function<bool (GridPoint3)> VoxelUtils::dilate(const DilationKernel& kernel, const std::function<bool (GridPoint3)>& process_cell_func) const { return [&process_cell_func, &kernel, this](GridPoint3 p) { return dilate(p, kernel, process_cell_func); }; } } // namespace cura
fix robustness of walkLine
fix robustness of walkLine In some cases where the line goes exactly through the crosssection of 4/8 cells, the end_cell wasn't reached. The new implementation is more robust.
C++
agpl-3.0
Ultimaker/CuraEngine,Ultimaker/CuraEngine
e4bdec22965e5c6696dc00261385ee9016199dd2
libkdepim/kincidencechooser.cpp
libkdepim/kincidencechooser.cpp
/* This file is part of libkdepim. Copyright (c) 2004 Lutz Rogowski <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "kincidencechooser.h" #include <kcal/incidence.h> #include <kcal/incidenceformatter.h> #include <khbox.h> #include <klocale.h> #include <kglobal.h> #include <QLayout> #include <QLabel> #include <q3buttongroup.h> #include <QRadioButton> #include <QPushButton> #include <q3scrollview.h> #include <QTextBrowser> #include <QApplication> #include <QGridLayout> using namespace KPIM; int KIncidenceChooser::chooseMode = KIncidenceChooser::ask ; KIncidenceChooser::KIncidenceChooser( QWidget *parent ) : KDialog( parent ) { setModal( true ); KDialog *topFrame = this; QGridLayout *topLayout = new QGridLayout( topFrame ); topLayout->setMargin( 5 ); topLayout->setSpacing( 3 ); int iii = 0; setWindowTitle( i18n( "Conflict Detected" ) ); QLabel *lab; lab = new QLabel( i18n( "<qt>A conflict was detected. This probably means someone edited " "the same entry on the server while you changed it locally." "<br/>NOTE: You have to check mail again to apply your changes " "to the server.</qt>" ), topFrame ); topLayout->addWidget( lab, iii, 0, 1, 3 ); ++iii; KHBox *b_box = new KHBox( topFrame ); topLayout->addWidget( b_box, iii, 0, 1, 3 ); ++iii; QPushButton *button = new QPushButton( i18n( "Take Local" ), b_box ); connect ( button, SIGNAL( clicked()), this, SLOT (takeIncidence1() ) ); button = new QPushButton( i18n( "Take New" ), b_box ); connect ( button, SIGNAL( clicked()), this, SLOT (takeIncidence2() ) ); button = new QPushButton( i18n( "Take Both" ), b_box ); connect ( button, SIGNAL( clicked()), this, SLOT (takeBoth() ) ); topLayout->setSpacing( spacingHint() ); topLayout->setMargin( marginHint() ); // text is not translated, because text has to be set later mInc1lab = new QLabel ( i18n( "Local incidence" ), topFrame ); topLayout->addWidget( mInc1lab, iii, 0 ); mInc1Sumlab = new QLabel ( i18n( "Local incidence summary" ), topFrame ); topLayout->addWidget( mInc1Sumlab, iii, 1, 1, 2 ); ++iii; topLayout->addWidget( new QLabel ( i18n( "Last modified:" ), topFrame ), iii, 0 ); mMod1lab = new QLabel ( "Set Last modified", topFrame ); topLayout->addWidget( mMod1lab, iii, 1 ); showDetails1 = new QPushButton( i18n( "Show Details" ), topFrame ); connect ( showDetails1, SIGNAL( clicked()), this, SLOT (showIncidence1() ) ); topLayout->addWidget( showDetails1, iii, 2 ); ++iii; mInc2lab = new QLabel ( "Local incidence", topFrame ); topLayout->addWidget( mInc2lab, iii, 0 ); mInc2Sumlab = new QLabel ( "Local incidence summary", topFrame ); topLayout->addWidget( mInc2Sumlab, iii, 1, 1, 2 ); ++iii; topLayout->addWidget( new QLabel ( i18n( "Last modified:" ), topFrame ), iii, 0 ); mMod2lab = new QLabel ( "Set Last modified", topFrame ); topLayout->addWidget( mMod2lab, iii, 1 ); showDetails2 = new QPushButton( i18n( "Show Details" ), topFrame ); connect ( showDetails2, SIGNAL( clicked()), this, SLOT (showIncidence2() ) ); topLayout->addWidget( showDetails2, iii, 2 ); ++iii; // #if 0 // commented out for now, because the diff code has too many bugs diffBut = new QPushButton( i18n( "Show Differences" ), topFrame ); connect ( diffBut, SIGNAL( clicked()), this, SLOT ( showDiff() ) ); topLayout->addWidget( cdiffBut, iii, 0, 1, 3 ); ++iii; #else diffBut = 0; #endif mBg = new Q3ButtonGroup ( 1, Qt::Horizontal, i18n( "Sync Preferences" ), topFrame ); topLayout->addWidget( mBg, iii, 0, 1, 3 ); ++iii; mBg->insert( new QRadioButton ( i18n( "Take local entry on conflict" ), mBg ), KIncidenceChooser::local ); mBg->insert( new QRadioButton ( i18n( "Take new (remote) entry on conflict" ), mBg ), KIncidenceChooser::remote ); mBg->insert( new QRadioButton ( i18n( "Take newest entry on conflict" ), mBg ), KIncidenceChooser::newest ); mBg->insert( new QRadioButton ( i18n( "Ask for every entry on conflict" ), mBg ), KIncidenceChooser::ask ); mBg->insert( new QRadioButton ( i18n( "Take both on conflict" ), mBg ), KIncidenceChooser::both ); mBg->setButton ( chooseMode ); mTbL = 0; mTbN = 0; mDisplayDiff = 0; choosedIncidence = 0; button = new QPushButton( i18n( "Apply This to All Conflicts of This Sync" ), topFrame ); connect ( button, SIGNAL( clicked()), this, SLOT ( setSyncMode() ) ); topLayout->addWidget( button, iii, 0, 1, 3 ); } KIncidenceChooser::~KIncidenceChooser() { if ( mTbL ) { delete mTbL; } if ( mTbN ) { delete mTbN; } if ( mDisplayDiff ) { delete mDisplayDiff; delete diff; } } void KIncidenceChooser::setIncidence( KCal::Incidence *local, KCal::Incidence *remote ) { mInc1 = local; mInc2 = remote; setLabels(); } KCal::Incidence *KIncidenceChooser::getIncidence( ) { KCal::Incidence *retval = choosedIncidence; if ( chooseMode == KIncidenceChooser::local ) { retval = mInc1; } else if ( chooseMode == KIncidenceChooser::remote ) { retval = mInc2; } else if ( chooseMode == KIncidenceChooser::both ) { retval = 0; } else if ( chooseMode == KIncidenceChooser::newest ) { if ( mInc1->lastModified() == mInc2->lastModified() ) { retval = 0; } if ( mInc1->lastModified() > mInc2->lastModified() ) { retval = mInc1; } else { retval = mInc2; } } return retval; } void KIncidenceChooser::setSyncMode() { chooseMode = mBg->selectedId (); if ( chooseMode != KIncidenceChooser::ask ) { QDialog::accept(); } } void KIncidenceChooser::useGlobalMode() { if ( chooseMode != KIncidenceChooser::ask ) { QDialog::reject(); } } void KIncidenceChooser::setLabels() { KCal::Incidence *inc = mInc1; QLabel *des = mInc1lab; QLabel *sum = mInc1Sumlab; if ( inc->type() == "Event" ) { des->setText( i18n( "Local Event" ) ); sum->setText( inc->summary().left( 30 ) ); if ( diffBut ) { diffBut->setEnabled( true ); } } else if ( inc->type() == "Todo" ) { des->setText( i18n( "Local Todo" ) ); sum->setText( inc->summary().left( 30 ) ); if ( diffBut ) { diffBut->setEnabled( true ); } } else if ( inc->type() == "Journal" ) { des->setText( i18n( "Local Journal" ) ); sum->setText( inc->description().left( 30 ) ); if ( diffBut ) { diffBut->setEnabled( false ); } } mMod1lab->setText( KGlobal::locale()->formatDateTime( inc->lastModified().dateTime() ) ); inc = mInc2; des = mInc2lab; sum = mInc2Sumlab; if ( inc->type() == "Event" ) { des->setText( i18n( "New Event" ) ); sum->setText( inc->summary().left( 30 ) ); } else if ( inc->type() == "Todo" ) { des->setText( i18n( "New Todo" ) ); sum->setText( inc->summary().left( 30 ) ); } else if ( inc->type() == "Journal" ) { des->setText( i18n( "New Journal" ) ); sum->setText( inc->description().left( 30 ) ); } mMod2lab->setText( KGlobal::locale()->formatDateTime( inc->lastModified().dateTime() ) ); } void KIncidenceChooser::showIncidence1() { if ( mTbL ) { if ( mTbL->isVisible() ) { showDetails1->setText( i18n( "Show Details" ) ); mTbL->hide(); } else { showDetails1->setText( i18n( "Hide Details" ) ); mTbL->show(); mTbL->raise(); } return; } mTbL = new KDialog( this ); mTbL->setCaption( mInc1lab->text() ); mTbL->setModal( false ); mTbL->setButtons( Ok ); connect( mTbL, SIGNAL( okClicked() ), this, SLOT( detailsDialogClosed() ) ); QTextBrowser *textBrowser = new QTextBrowser( mTbL ); mTbL->setMainWidget( textBrowser ); textBrowser->setHtml( KCal::IncidenceFormatter::extensiveDisplayString( mInc1 ) ); mTbL->setMinimumSize( 400, 400 ); showDetails1->setText( i18n( "Hide Details" ) ); mTbL->show(); mTbL->raise(); } void KIncidenceChooser::detailsDialogClosed() { KDialog *dialog = static_cast<KDialog *>( const_cast<QObject *>( sender() ) ); if ( dialog == mTbL ) { showDetails1->setText( i18n( "Show details..." ) ); } else { showDetails2->setText( i18n( "Show details..." ) ); } } void KIncidenceChooser::showDiff() { if ( mDisplayDiff ) { mDisplayDiff->show(); mDisplayDiff->raise(); return; } mDisplayDiff = new KPIM::HTMLDiffAlgoDisplay (this); if ( mInc1->summary().left( 20 ) != mInc2->summary().left( 20 ) ) { mDisplayDiff->setWindowTitle( i18n( "Differences of %1 and %2", mInc1->summary().left( 20 ), mInc2->summary().left( 20 ) ) ); } else { mDisplayDiff->setWindowTitle( i18n( "Differences of %1", mInc1->summary().left( 20 ) ) ); } diff = new KPIM::CalendarDiffAlgo( mInc1, mInc2 ); diff->setLeftSourceTitle( i18n( "Local entry" ) ); diff->setRightSourceTitle( i18n( "New (remote) entry" ) ); diff->addDisplay( mDisplayDiff ); diff->run(); mDisplayDiff->show(); mDisplayDiff->raise(); } void KIncidenceChooser::showIncidence2() { if ( mTbN ) { if ( mTbN->isVisible() ) { showDetails2->setText( i18n( "Show Details" ) ); mTbN->hide(); } else { showDetails2->setText( i18n( "Hide Details" ) ); mTbN->show(); mTbN->raise(); } return; } mTbN = new KDialog( this ); mTbN->setCaption( mInc2lab->text() ); mTbN->setModal( false ); mTbN->setButtons( Ok ); connect( mTbN, SIGNAL( okClicked() ), this, SLOT( detailsDialogClosed() ) ); QTextBrowser *textBrowser = new QTextBrowser( mTbN ); mTbN->setMainWidget( textBrowser ); textBrowser->setHtml( KCal::IncidenceFormatter::extensiveDisplayString( mInc2 ) ); mTbN->setMinimumSize( 400, 400 ); showDetails2->setText( i18n( "Hide Details" ) ); mTbN->show(); mTbN->raise(); } void KIncidenceChooser::takeIncidence1() { choosedIncidence = mInc1; QDialog::accept(); } void KIncidenceChooser::takeIncidence2() { choosedIncidence = mInc2; QDialog::accept(); } void KIncidenceChooser::takeBoth() { choosedIncidence = 0; QDialog::accept(); } #include "kincidencechooser.moc"
/* This file is part of libkdepim. Copyright (c) 2004 Lutz Rogowski <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "kincidencechooser.h" #include <kcal/incidence.h> #include <kcal/incidenceformatter.h> #include <khbox.h> #include <klocale.h> #include <kglobal.h> #include <QLayout> #include <QLabel> #include <q3buttongroup.h> #include <QRadioButton> #include <QPushButton> #include <q3scrollview.h> #include <QTextBrowser> #include <QApplication> #include <QGridLayout> using namespace KPIM; int KIncidenceChooser::chooseMode = KIncidenceChooser::ask ; KIncidenceChooser::KIncidenceChooser( QWidget *parent ) : KDialog( parent ) { setModal( true ); QWidget *topFrame = mainWidget(); QGridLayout *topLayout = new QGridLayout( topFrame ); topLayout->setMargin( 5 ); topLayout->setSpacing( 3 ); int iii = 0; setWindowTitle( i18n( "Conflict Detected" ) ); QLabel *lab; lab = new QLabel( i18n( "<qt>A conflict was detected. This probably means someone edited " "the same entry on the server while you changed it locally." "<br/>NOTE: You have to check mail again to apply your changes " "to the server.</qt>" ), topFrame ); lab->setWordWrap( true ); topLayout->addWidget( lab, iii, 0, 1, 3 ); ++iii; KHBox *b_box = new KHBox( topFrame ); topLayout->addWidget( b_box, iii, 0, 1, 3 ); ++iii; QPushButton *button = new QPushButton( i18n( "Take Local" ), b_box ); connect ( button, SIGNAL( clicked()), this, SLOT (takeIncidence1() ) ); button = new QPushButton( i18n( "Take New" ), b_box ); connect ( button, SIGNAL( clicked()), this, SLOT (takeIncidence2() ) ); button = new QPushButton( i18n( "Take Both" ), b_box ); connect ( button, SIGNAL( clicked()), this, SLOT (takeBoth() ) ); topLayout->setSpacing( spacingHint() ); topLayout->setMargin( marginHint() ); // text is not translated, because text has to be set later mInc1lab = new QLabel ( i18n( "Local incidence" ), topFrame ); topLayout->addWidget( mInc1lab, iii, 0 ); mInc1Sumlab = new QLabel ( i18n( "Local incidence summary" ), topFrame ); topLayout->addWidget( mInc1Sumlab, iii, 1, 1, 2 ); ++iii; topLayout->addWidget( new QLabel ( i18n( "Last modified:" ), topFrame ), iii, 0 ); mMod1lab = new QLabel ( "Set Last modified", topFrame ); topLayout->addWidget( mMod1lab, iii, 1 ); showDetails1 = new QPushButton( i18n( "Show Details" ), topFrame ); connect ( showDetails1, SIGNAL( clicked()), this, SLOT (showIncidence1() ) ); topLayout->addWidget( showDetails1, iii, 2 ); ++iii; mInc2lab = new QLabel ( "Local incidence", topFrame ); topLayout->addWidget( mInc2lab, iii, 0 ); mInc2Sumlab = new QLabel ( "Local incidence summary", topFrame ); topLayout->addWidget( mInc2Sumlab, iii, 1, 1, 2 ); ++iii; topLayout->addWidget( new QLabel ( i18n( "Last modified:" ), topFrame ), iii, 0 ); mMod2lab = new QLabel ( "Set Last modified", topFrame ); topLayout->addWidget( mMod2lab, iii, 1 ); showDetails2 = new QPushButton( i18n( "Show Details" ), topFrame ); connect ( showDetails2, SIGNAL( clicked()), this, SLOT (showIncidence2() ) ); topLayout->addWidget( showDetails2, iii, 2 ); ++iii; // #if 0 // commented out for now, because the diff code has too many bugs diffBut = new QPushButton( i18n( "Show Differences" ), topFrame ); connect ( diffBut, SIGNAL( clicked()), this, SLOT ( showDiff() ) ); topLayout->addWidget( cdiffBut, iii, 0, 1, 3 ); ++iii; #else diffBut = 0; #endif mBg = new Q3ButtonGroup ( 1, Qt::Horizontal, i18n( "Sync Preferences" ), topFrame ); topLayout->addWidget( mBg, iii, 0, 1, 3 ); ++iii; mBg->insert( new QRadioButton ( i18n( "Take local entry on conflict" ), mBg ), KIncidenceChooser::local ); mBg->insert( new QRadioButton ( i18n( "Take new (remote) entry on conflict" ), mBg ), KIncidenceChooser::remote ); mBg->insert( new QRadioButton ( i18n( "Take newest entry on conflict" ), mBg ), KIncidenceChooser::newest ); mBg->insert( new QRadioButton ( i18n( "Ask for every entry on conflict" ), mBg ), KIncidenceChooser::ask ); mBg->insert( new QRadioButton ( i18n( "Take both on conflict" ), mBg ), KIncidenceChooser::both ); mBg->setButton ( chooseMode ); mTbL = 0; mTbN = 0; mDisplayDiff = 0; choosedIncidence = 0; button = new QPushButton( i18n( "Apply This to All Conflicts of This Sync" ), topFrame ); connect ( button, SIGNAL( clicked()), this, SLOT ( setSyncMode() ) ); topLayout->addWidget( button, iii, 0, 1, 3 ); } KIncidenceChooser::~KIncidenceChooser() { if ( mTbL ) { delete mTbL; } if ( mTbN ) { delete mTbN; } if ( mDisplayDiff ) { delete mDisplayDiff; delete diff; } } void KIncidenceChooser::setIncidence( KCal::Incidence *local, KCal::Incidence *remote ) { mInc1 = local; mInc2 = remote; setLabels(); } KCal::Incidence *KIncidenceChooser::getIncidence( ) { KCal::Incidence *retval = choosedIncidence; if ( chooseMode == KIncidenceChooser::local ) { retval = mInc1; } else if ( chooseMode == KIncidenceChooser::remote ) { retval = mInc2; } else if ( chooseMode == KIncidenceChooser::both ) { retval = 0; } else if ( chooseMode == KIncidenceChooser::newest ) { if ( mInc1->lastModified() == mInc2->lastModified() ) { retval = 0; } if ( mInc1->lastModified() > mInc2->lastModified() ) { retval = mInc1; } else { retval = mInc2; } } return retval; } void KIncidenceChooser::setSyncMode() { chooseMode = mBg->selectedId (); if ( chooseMode != KIncidenceChooser::ask ) { QDialog::accept(); } } void KIncidenceChooser::useGlobalMode() { if ( chooseMode != KIncidenceChooser::ask ) { QDialog::reject(); } } void KIncidenceChooser::setLabels() { KCal::Incidence *inc = mInc1; QLabel *des = mInc1lab; QLabel *sum = mInc1Sumlab; if ( inc->type() == "Event" ) { des->setText( i18n( "Local Event" ) ); sum->setText( inc->summary().left( 30 ) ); if ( diffBut ) { diffBut->setEnabled( true ); } } else if ( inc->type() == "Todo" ) { des->setText( i18n( "Local Todo" ) ); sum->setText( inc->summary().left( 30 ) ); if ( diffBut ) { diffBut->setEnabled( true ); } } else if ( inc->type() == "Journal" ) { des->setText( i18n( "Local Journal" ) ); sum->setText( inc->description().left( 30 ) ); if ( diffBut ) { diffBut->setEnabled( false ); } } mMod1lab->setText( KGlobal::locale()->formatDateTime( inc->lastModified().dateTime() ) ); inc = mInc2; des = mInc2lab; sum = mInc2Sumlab; if ( inc->type() == "Event" ) { des->setText( i18n( "New Event" ) ); sum->setText( inc->summary().left( 30 ) ); } else if ( inc->type() == "Todo" ) { des->setText( i18n( "New Todo" ) ); sum->setText( inc->summary().left( 30 ) ); } else if ( inc->type() == "Journal" ) { des->setText( i18n( "New Journal" ) ); sum->setText( inc->description().left( 30 ) ); } mMod2lab->setText( KGlobal::locale()->formatDateTime( inc->lastModified().dateTime() ) ); } void KIncidenceChooser::showIncidence1() { if ( mTbL ) { if ( mTbL->isVisible() ) { showDetails1->setText( i18n( "Show Details" ) ); mTbL->hide(); } else { showDetails1->setText( i18n( "Hide Details" ) ); mTbL->show(); mTbL->raise(); } return; } mTbL = new KDialog( this ); mTbL->setCaption( mInc1lab->text() ); mTbL->setModal( false ); mTbL->setButtons( Ok ); connect( mTbL, SIGNAL( okClicked() ), this, SLOT( detailsDialogClosed() ) ); QTextBrowser *textBrowser = new QTextBrowser( mTbL ); mTbL->setMainWidget( textBrowser ); textBrowser->setHtml( KCal::IncidenceFormatter::extensiveDisplayString( mInc1 ) ); mTbL->setMinimumSize( 400, 400 ); showDetails1->setText( i18n( "Hide Details" ) ); mTbL->show(); mTbL->raise(); } void KIncidenceChooser::detailsDialogClosed() { KDialog *dialog = static_cast<KDialog *>( const_cast<QObject *>( sender() ) ); if ( dialog == mTbL ) { showDetails1->setText( i18n( "Show details..." ) ); } else { showDetails2->setText( i18n( "Show details..." ) ); } } void KIncidenceChooser::showDiff() { if ( mDisplayDiff ) { mDisplayDiff->show(); mDisplayDiff->raise(); return; } mDisplayDiff = new KPIM::HTMLDiffAlgoDisplay (this); if ( mInc1->summary().left( 20 ) != mInc2->summary().left( 20 ) ) { mDisplayDiff->setWindowTitle( i18n( "Differences of %1 and %2", mInc1->summary().left( 20 ), mInc2->summary().left( 20 ) ) ); } else { mDisplayDiff->setWindowTitle( i18n( "Differences of %1", mInc1->summary().left( 20 ) ) ); } diff = new KPIM::CalendarDiffAlgo( mInc1, mInc2 ); diff->setLeftSourceTitle( i18n( "Local entry" ) ); diff->setRightSourceTitle( i18n( "New (remote) entry" ) ); diff->addDisplay( mDisplayDiff ); diff->run(); mDisplayDiff->show(); mDisplayDiff->raise(); } void KIncidenceChooser::showIncidence2() { if ( mTbN ) { if ( mTbN->isVisible() ) { showDetails2->setText( i18n( "Show Details" ) ); mTbN->hide(); } else { showDetails2->setText( i18n( "Hide Details" ) ); mTbN->show(); mTbN->raise(); } return; } mTbN = new KDialog( this ); mTbN->setCaption( mInc2lab->text() ); mTbN->setModal( false ); mTbN->setButtons( Ok ); connect( mTbN, SIGNAL( okClicked() ), this, SLOT( detailsDialogClosed() ) ); QTextBrowser *textBrowser = new QTextBrowser( mTbN ); mTbN->setMainWidget( textBrowser ); textBrowser->setHtml( KCal::IncidenceFormatter::extensiveDisplayString( mInc2 ) ); mTbN->setMinimumSize( 400, 400 ); showDetails2->setText( i18n( "Hide Details" ) ); mTbN->show(); mTbN->raise(); } void KIncidenceChooser::takeIncidence1() { choosedIncidence = mInc1; QDialog::accept(); } void KIncidenceChooser::takeIncidence2() { choosedIncidence = mInc2; QDialog::accept(); } void KIncidenceChooser::takeBoth() { choosedIncidence = 0; QDialog::accept(); } #include "kincidencechooser.moc"
Fix layout.
Fix layout. svn path=/trunk/KDE/kdepim/; revision=788090
C++
lgpl-2.1
lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi
c9a76d7a54666ca4e68cd168863fb21ee48f3236
proto/p4info/convert_p4info.cpp
proto/p4info/convert_p4info.cpp
/* Copyright 2013-present Barefoot Networks, 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. */ /* * Antonin Bas ([email protected]) * */ #include <PI/p4info.h> #include <unistd.h> #include <fstream> // std::ifstream, std::ofstream #include <iostream> #include <string> #include "PI/proto/p4info_to_and_from_proto.h" #include "p4/config/v1/p4info.pb.h" namespace { void print_help(const char *prog_name) { std::cerr << "Usage: " << prog_name << " [OPTIONS]...\n" << "Utility to convert P4Info proto from and to other formats\n\n" << "-f format of source (from)\n" << " one of 'bmv2', 'native', 'proto'\n" << "-t desired format of destination dir (to)\n" << " one of 'native', 'proto'\n" << "-i path to input config\n" << "-o path where to write output\n"; } char *from = NULL; char *to = NULL; char *input_path = NULL; char *output_path = NULL; int parse_opts(int argc, char *argv[]) { int c; opterr = 0; while ((c = getopt(argc, argv, "i:o:f:t:h")) != -1) { switch (c) { case 'i': input_path = optarg; break; case 'o': output_path = optarg; break; case 'f': from = optarg; break; case 't': to = optarg; break; case 'h': print_help(argv[0]); exit(0); case '?': if (optopt == 'i' || optopt == 'o' ||optopt == 'f' || optopt == 't') { std::cerr << "Option -" << static_cast<char>(optopt) << " requires an argument.\n\n"; print_help(argv[0]); } else if (isprint(optopt)) { std::cerr << "Unknown option -" << static_cast<char>(optopt) << ".\n\n"; print_help(argv[0]); } else { std::cerr << "Unknown option character.\n\n"; print_help(argv[0]); } return 1; default: abort(); } } if (!input_path || !output_path || !from || !to) { fprintf(stderr, "Options -f, -t, -i and -o are ALL required.\n\n"); print_help(argv[0]); return 1; } return 0; } } // namespace // TODO(antonin) int main(int argc, char *argv[]) { int rc; if ((rc = parse_opts(argc, argv)) != 0) return rc; std::string from_str(from); std::string to_str(to); std::string input_path_str(input_path); std::string output_path_str(output_path); pi_p4info_t *p4info; if (from_str == "bmv2" || from_str == "native") { pi_status_t status; if (from_str == "bmv2") { status = pi_add_config_from_file(input_path, PI_CONFIG_TYPE_BMV2_JSON, &p4info); } else { status = pi_add_config_from_file(input_path, PI_CONFIG_TYPE_NATIVE_JSON, &p4info); } if (status != PI_STATUS_SUCCESS) { std::cerr << "Error when loading input config.\n"; return 1; } } else if (from_str == "proto") { p4::config::v1::P4Info p4info_proto; std::ifstream is(input_path_str, std::ifstream::binary); if (!is) { std::cerr << "Error while opening protobuf input file.\n"; return 1; } auto status = p4info_proto.ParseFromIstream(&is); if (!status) { std::cerr << "Error while importing protobuf message.\n"; return 1; } if (!pi::p4info::p4info_proto_reader(p4info_proto, &p4info)) { std::cerr << "Error while importing protobuf message to p4info.\n"; return 1; } } else { std::cerr << "Invalid value for -f option.\n"; return 1; } std::ofstream os(output_path_str, std::ofstream::binary); if (!os) { std::cerr << "Error while opening output file.\n"; return 1; } if (to_str == "native") { char *native_json = pi_serialize_config(p4info, 1); std::cout << native_json << "\n"; os << native_json << "\n"; free(native_json); } else if (to_str == "proto") { const auto p4info_proto = pi::p4info::p4info_serialize_to_proto(p4info); std::cout << p4info_proto.DebugString(); p4info_proto.SerializeToOstream(&os); } else { std::cerr << "Invalid value for -t option.\n"; return 1; } pi_destroy_config(p4info); }
/* Copyright 2013-present Barefoot Networks, 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. */ /* * Antonin Bas ([email protected]) * */ #include <PI/p4info.h> #include <unistd.h> #include <google/protobuf/io/zero_copy_stream_impl.h> #include <google/protobuf/text_format.h> #include <fstream> // std::ifstream, std::ofstream #include <iostream> #include <string> #include "PI/proto/p4info_to_and_from_proto.h" #include "p4/config/v1/p4info.pb.h" namespace { void print_help(const char *prog_name) { std::cerr << "Usage: " << prog_name << " [OPTIONS]...\n" << "Utility to convert P4Info proto from and to other formats\n\n" << "-f format of source (from)\n" << " one of 'bmv2', 'native', 'proto', 'prototext'\n" << "-t desired format of destination dir (to)\n" << " one of 'native', 'proto', 'prototext'\n" << "-i path to input config\n" << "-o path where to write output\n"; } char *from = NULL; char *to = NULL; char *input_path = NULL; char *output_path = NULL; int parse_opts(int argc, char *argv[]) { int c; opterr = 0; while ((c = getopt(argc, argv, "i:o:f:t:h")) != -1) { switch (c) { case 'i': input_path = optarg; break; case 'o': output_path = optarg; break; case 'f': from = optarg; break; case 't': to = optarg; break; case 'h': print_help(argv[0]); exit(0); case '?': if (optopt == 'i' || optopt == 'o' ||optopt == 'f' || optopt == 't') { std::cerr << "Option -" << static_cast<char>(optopt) << " requires an argument.\n\n"; print_help(argv[0]); } else if (isprint(optopt)) { std::cerr << "Unknown option -" << static_cast<char>(optopt) << ".\n\n"; print_help(argv[0]); } else { std::cerr << "Unknown option character.\n\n"; print_help(argv[0]); } return 1; default: abort(); } } if (!input_path || !output_path || !from || !to) { fprintf(stderr, "Options -f, -t, -i and -o are ALL required.\n\n"); print_help(argv[0]); return 1; } return 0; } } // namespace int main(int argc, char *argv[]) { int rc; if ((rc = parse_opts(argc, argv)) != 0) return rc; std::string from_str(from); std::string to_str(to); std::string input_path_str(input_path); std::string output_path_str(output_path); pi_p4info_t *p4info; if (from_str == "bmv2" || from_str == "native") { pi_status_t status; if (from_str == "bmv2") { status = pi_add_config_from_file(input_path, PI_CONFIG_TYPE_BMV2_JSON, &p4info); } else { status = pi_add_config_from_file(input_path, PI_CONFIG_TYPE_NATIVE_JSON, &p4info); } if (status != PI_STATUS_SUCCESS) { std::cerr << "Error when loading input config.\n"; return 1; } } else if (from_str == "proto") { p4::config::v1::P4Info p4info_proto; std::ifstream is(input_path_str, std::ifstream::binary); if (!is) { std::cerr << "Error while opening protobuf input file.\n"; return 1; } auto status = p4info_proto.ParseFromIstream(&is); if (!status) { std::cerr << "Error while importing protobuf message.\n"; return 1; } if (!pi::p4info::p4info_proto_reader(p4info_proto, &p4info)) { std::cerr << "Error while importing protobuf message to p4info.\n"; return 1; } } else if (from_str == "prototext") { p4::config::v1::P4Info p4info_proto; std::ifstream is(input_path_str); if (!is) { std::cerr << "Error while opening protobuf text input file.\n"; return 1; } google::protobuf::io::IstreamInputStream is_(&is); auto status = google::protobuf::TextFormat::Parse(&is_, &p4info_proto); if (!status) { std::cerr << "Error while importing protobuf text message.\n"; return 1; } if (!pi::p4info::p4info_proto_reader(p4info_proto, &p4info)) { std::cerr << "Error while importing protobuf message to p4info.\n"; return 1; } } else { std::cerr << "Invalid value for -f option.\n"; return 1; } std::ofstream os(output_path_str, std::ofstream::binary); if (!os) { std::cerr << "Error while opening output file.\n"; return 1; } if (to_str == "native") { char *native_json = pi_serialize_config(p4info, 1); std::cout << native_json << "\n"; os << native_json << "\n"; free(native_json); } else if (to_str == "proto") { const auto p4info_proto = pi::p4info::p4info_serialize_to_proto(p4info); std::cout << p4info_proto.DebugString(); p4info_proto.SerializeToOstream(&os); } else if (to_str == "prototext") { const auto p4info_proto = pi::p4info::p4info_serialize_to_proto(p4info); std::cout << p4info_proto.DebugString(); google::protobuf::io::OstreamOutputStream os_(&os); auto status = google::protobuf::TextFormat::Print(p4info_proto, &os_); if (!status) { std::cerr << "Error while writing protobuf text file.\n"; return 1; } } else { std::cerr << "Invalid value for -t option.\n"; return 1; } pi_destroy_config(p4info); }
Support Protobuf text format in P4Info conversion tool
Support Protobuf text format in P4Info conversion tool
C++
apache-2.0
p4lang/PI,p4lang/PI,p4lang/PI,p4lang/PI
d09b6a481012389d971bda2bd41251276a7ab893
test/standalone/font_registration_test.cpp
test/standalone/font_registration_test.cpp
#define CATCH_CONFIG_MAIN #include "catch.hpp" #include <mapnik/font_engine_freetype.hpp> #include <mapnik/util/fs.hpp> #include <mapnik/map.hpp> #include <mapnik/load_map.hpp> #include <mapnik/debug.hpp> #include <iostream> #include <vector> #include <algorithm> TEST_CASE("font") { SECTION("registration") { try { mapnik::logger logger; mapnik::logger::severity_type original_severity = logger.get_severity(); // grab references to global statics of registered/cached fonts auto const& global_mapping = mapnik::freetype_engine::get_mapping(); auto const& global_cache = mapnik::freetype_engine::get_cache(); // mapnik.Map object has parallel structure for localized fonts mapnik::Map m(1,1); auto const& local_mapping = m.get_font_file_mapping(); auto const& local_cache = m.get_font_memory_cache(); // should be empty to start REQUIRE( global_mapping.empty() ); REQUIRE( global_cache.empty() ); REQUIRE( local_mapping.empty() ); REQUIRE( local_cache.empty() ); std::string fontdir("fonts/"); REQUIRE( mapnik::util::exists( fontdir ) ); REQUIRE( mapnik::util::is_directory( fontdir ) ); // test map cached fonts REQUIRE( m.register_fonts(fontdir , false ) ); REQUIRE( m.get_font_memory_cache().size() == 0 ); REQUIRE( m.get_font_file_mapping().size() == 1 ); REQUIRE( m.load_fonts() ); REQUIRE( m.get_font_memory_cache().size() == 1 ); REQUIRE( m.register_fonts(fontdir , true ) ); REQUIRE( m.get_font_file_mapping().size() == 22 ); REQUIRE( m.load_fonts() ); REQUIRE( m.get_font_memory_cache().size() == 22 ); // copy discards memory cache but not file mapping mapnik::Map m2(m); REQUIRE( m2.get_font_memory_cache().size() == 0 ); REQUIRE( m2.get_font_file_mapping().size() == 22 ); REQUIRE( m2.load_fonts() ); REQUIRE( m2.get_font_memory_cache().size() == 22 ); // test font-directory from XML mapnik::Map m3(1,1); mapnik::load_map_string(m3,"<Map font-directory=\"fonts/\"></Map>"); REQUIRE( m3.get_font_memory_cache().size() == 0 ); REQUIRE( m3.load_fonts() ); REQUIRE( m3.get_font_memory_cache().size() == 1 ); std::vector<std::string> face_names; std::string foo("foo"); // fake directories REQUIRE( !mapnik::freetype_engine::register_fonts(foo , true ) ); face_names = mapnik::freetype_engine::face_names(); REQUIRE( face_names.size() == 0 ); REQUIRE( !mapnik::freetype_engine::register_fonts(foo) ); face_names = mapnik::freetype_engine::face_names(); REQUIRE( face_names.size() == 0 ); // directories without fonts // silence warnings here by altering the logging severity logger.set_severity(mapnik::logger::none); std::string src("src"); // an empty directory will not return true // we need to register at least one font and not fail on any // to return true REQUIRE( mapnik::freetype_engine::register_font(src) == false ); REQUIRE( mapnik::freetype_engine::register_fonts(src, true) == false ); REQUIRE( mapnik::freetype_engine::face_names().size() == 0 ); // bogus, emtpy file that looks like font REQUIRE( mapnik::freetype_engine::register_font("test/data/fonts/fake.ttf") == false ); REQUIRE( mapnik::freetype_engine::register_fonts("test/data/fonts/fake.ttf") == false ); REQUIRE( mapnik::freetype_engine::face_names().size() == 0 ); REQUIRE( mapnik::freetype_engine::register_font("test/data/fonts/intentionally-broken.ttf") == false ); REQUIRE( mapnik::freetype_engine::register_fonts("test/data/fonts/intentionally-broken.ttf") == false ); REQUIRE( mapnik::freetype_engine::face_names().size() == 0 ); // now restore the original severity logger.set_severity(original_severity); // register unifont, since we know it sits in the root fonts/ dir REQUIRE( mapnik::freetype_engine::register_fonts(fontdir) ); face_names = mapnik::freetype_engine::face_names(); REQUIRE( face_names.size() > 0 ); REQUIRE( face_names.size() == 1 ); // re-register unifont, should not have any affect REQUIRE( mapnik::freetype_engine::register_fonts(fontdir, false) ); face_names = mapnik::freetype_engine::face_names(); REQUIRE( face_names.size() == 1 ); // single dejavu font in separate location std::string dejavu_bold_oblique("test/data/fonts/DejaVuSansMono-BoldOblique.ttf"); REQUIRE( mapnik::freetype_engine::register_font(dejavu_bold_oblique) ); face_names = mapnik::freetype_engine::face_names(); REQUIRE( face_names.size() == 2 ); // now, inspect font mapping and confirm the correct 'DejaVu Sans Mono Bold Oblique' is registered using font_file_mapping = std::map<std::string, std::pair<int,std::string> >; font_file_mapping const& name2file = mapnik::freetype_engine::get_mapping(); bool found_dejavu = false; for (auto const& item : name2file) { if (item.first == "DejaVu Sans Mono Bold Oblique") { found_dejavu = true; REQUIRE( item.second.first == 0 ); REQUIRE( item.second.second == dejavu_bold_oblique ); } } REQUIRE( found_dejavu ); // recurse to find all dejavu fonts REQUIRE( mapnik::freetype_engine::register_fonts(fontdir, true) ); face_names = mapnik::freetype_engine::face_names(); REQUIRE( face_names.size() == 22 ); // we should have re-registered 'DejaVu Sans Mono Bold Oblique' again, // but now at a new path bool found_dejavu2 = false; for (auto const& item : name2file) { if (item.first == "DejaVu Sans Mono Bold Oblique") { found_dejavu2 = true; REQUIRE( item.second.first == 0 ); // path should be different REQUIRE( item.second.second != dejavu_bold_oblique ); } } REQUIRE( found_dejavu2 ); // now that global registry is populated // now test that a map only loads new fonts mapnik::Map m4(1,1); REQUIRE( m4.register_fonts(fontdir , true ) ); REQUIRE( m4.get_font_memory_cache().size() == 0 ); REQUIRE( m4.get_font_file_mapping().size() == 22 ); REQUIRE( !m4.load_fonts() ); REQUIRE( m4.get_font_memory_cache().size() == 0 ); REQUIRE( m4.register_fonts(dejavu_bold_oblique, false) ); REQUIRE( m4.load_fonts() ); REQUIRE( m4.get_font_memory_cache().size() == 1 ); // check that we can correctly read a .ttc containing // multiple valid faces // https://github.com/mapnik/mapnik/issues/2274 REQUIRE( mapnik::freetype_engine::register_font("test/data/fonts/NotoSans-Regular.ttc") ); face_names = mapnik::freetype_engine::face_names(); REQUIRE( face_names.size() == 24 ); // now blindly register as many system fonts as possible // the goal here to make sure we don't crash // linux mapnik::freetype_engine::register_fonts("/usr/share/fonts/", true); mapnik::freetype_engine::register_fonts("/usr/local/share/fonts/", true); // osx mapnik::freetype_engine::register_fonts("/Library/Fonts/", true); mapnik::freetype_engine::register_fonts("/System/Library/Fonts/", true); // windows mapnik::freetype_engine::register_fonts("C:\\Windows\\Fonts", true); face_names = mapnik::freetype_engine::face_names(); REQUIRE( face_names.size() > 22 ); } catch (std::exception const & ex) { std::clog << ex.what() << "\n"; REQUIRE(false); } } }
#define CATCH_CONFIG_MAIN #include "catch.hpp" #include <mapnik/font_engine_freetype.hpp> #include <mapnik/util/fs.hpp> #include <mapnik/map.hpp> #include <mapnik/load_map.hpp> #include <mapnik/debug.hpp> #include <iostream> #include <vector> #include <algorithm> TEST_CASE("font") { SECTION("registration") { try { mapnik::logger logger; mapnik::logger::severity_type original_severity = logger.get_severity(); // grab references to global statics of registered/cached fonts auto const& global_mapping = mapnik::freetype_engine::get_mapping(); auto const& global_cache = mapnik::freetype_engine::get_cache(); // mapnik.Map object has parallel structure for localized fonts mapnik::Map m(1,1); auto const& local_mapping = m.get_font_file_mapping(); auto const& local_cache = m.get_font_memory_cache(); // should be empty to start REQUIRE( global_mapping.empty() ); REQUIRE( global_cache.empty() ); REQUIRE( local_mapping.empty() ); REQUIRE( local_cache.empty() ); std::string fontdir("fonts/"); REQUIRE( mapnik::util::exists( fontdir ) ); REQUIRE( mapnik::util::is_directory( fontdir ) ); // test map cached fonts REQUIRE( m.register_fonts(fontdir , false ) ); REQUIRE( m.get_font_memory_cache().size() == 0 ); REQUIRE( m.get_font_file_mapping().size() == 1 ); REQUIRE( m.load_fonts() ); REQUIRE( m.get_font_memory_cache().size() == 1 ); REQUIRE( m.register_fonts(fontdir , true ) ); REQUIRE( m.get_font_file_mapping().size() == 23 ); REQUIRE( m.load_fonts() ); REQUIRE( m.get_font_memory_cache().size() == 23 ); // copy discards memory cache but not file mapping mapnik::Map m2(m); REQUIRE( m2.get_font_memory_cache().size() == 0 ); REQUIRE( m2.get_font_file_mapping().size() == 23 ); REQUIRE( m2.load_fonts() ); REQUIRE( m2.get_font_memory_cache().size() == 23 ); // test font-directory from XML mapnik::Map m3(1,1); mapnik::load_map_string(m3,"<Map font-directory=\"fonts/\"></Map>"); REQUIRE( m3.get_font_memory_cache().size() == 0 ); REQUIRE( m3.load_fonts() ); REQUIRE( m3.get_font_memory_cache().size() == 1 ); std::vector<std::string> face_names; std::string foo("foo"); // fake directories REQUIRE( !mapnik::freetype_engine::register_fonts(foo , true ) ); face_names = mapnik::freetype_engine::face_names(); REQUIRE( face_names.size() == 0 ); REQUIRE( !mapnik::freetype_engine::register_fonts(foo) ); face_names = mapnik::freetype_engine::face_names(); REQUIRE( face_names.size() == 0 ); // directories without fonts // silence warnings here by altering the logging severity logger.set_severity(mapnik::logger::none); std::string src("src"); // an empty directory will not return true // we need to register at least one font and not fail on any // to return true REQUIRE( mapnik::freetype_engine::register_font(src) == false ); REQUIRE( mapnik::freetype_engine::register_fonts(src, true) == false ); REQUIRE( mapnik::freetype_engine::face_names().size() == 0 ); // bogus, emtpy file that looks like font REQUIRE( mapnik::freetype_engine::register_font("test/data/fonts/fake.ttf") == false ); REQUIRE( mapnik::freetype_engine::register_fonts("test/data/fonts/fake.ttf") == false ); REQUIRE( mapnik::freetype_engine::face_names().size() == 0 ); REQUIRE( mapnik::freetype_engine::register_font("test/data/fonts/intentionally-broken.ttf") == false ); REQUIRE( mapnik::freetype_engine::register_fonts("test/data/fonts/intentionally-broken.ttf") == false ); REQUIRE( mapnik::freetype_engine::face_names().size() == 0 ); // now restore the original severity logger.set_severity(original_severity); // register unifont, since we know it sits in the root fonts/ dir REQUIRE( mapnik::freetype_engine::register_fonts(fontdir) ); face_names = mapnik::freetype_engine::face_names(); REQUIRE( face_names.size() > 0 ); REQUIRE( face_names.size() == 1 ); // re-register unifont, should not have any affect REQUIRE( mapnik::freetype_engine::register_fonts(fontdir, false) ); face_names = mapnik::freetype_engine::face_names(); REQUIRE( face_names.size() == 1 ); // single dejavu font in separate location std::string dejavu_bold_oblique("test/data/fonts/DejaVuSansMono-BoldOblique.ttf"); REQUIRE( mapnik::freetype_engine::register_font(dejavu_bold_oblique) ); face_names = mapnik::freetype_engine::face_names(); REQUIRE( face_names.size() == 2 ); // now, inspect font mapping and confirm the correct 'DejaVu Sans Mono Bold Oblique' is registered using font_file_mapping = std::map<std::string, std::pair<int,std::string> >; font_file_mapping const& name2file = mapnik::freetype_engine::get_mapping(); bool found_dejavu = false; for (auto const& item : name2file) { if (item.first == "DejaVu Sans Mono Bold Oblique") { found_dejavu = true; REQUIRE( item.second.first == 0 ); REQUIRE( item.second.second == dejavu_bold_oblique ); } } REQUIRE( found_dejavu ); // recurse to find all dejavu fonts REQUIRE( mapnik::freetype_engine::register_fonts(fontdir, true) ); face_names = mapnik::freetype_engine::face_names(); REQUIRE( face_names.size() == 23 ); // we should have re-registered 'DejaVu Sans Mono Bold Oblique' again, // but now at a new path bool found_dejavu2 = false; for (auto const& item : name2file) { if (item.first == "DejaVu Sans Mono Bold Oblique") { found_dejavu2 = true; REQUIRE( item.second.first == 0 ); // path should be different REQUIRE( item.second.second != dejavu_bold_oblique ); } } REQUIRE( found_dejavu2 ); // now that global registry is populated // now test that a map only loads new fonts mapnik::Map m4(1,1); REQUIRE( m4.register_fonts(fontdir , true ) ); REQUIRE( m4.get_font_memory_cache().size() == 0 ); REQUIRE( m4.get_font_file_mapping().size() == 23 ); REQUIRE( !m4.load_fonts() ); REQUIRE( m4.get_font_memory_cache().size() == 0 ); REQUIRE( m4.register_fonts(dejavu_bold_oblique, false) ); REQUIRE( m4.load_fonts() ); REQUIRE( m4.get_font_memory_cache().size() == 1 ); // check that we can correctly read a .ttc containing // multiple valid faces // https://github.com/mapnik/mapnik/issues/2274 REQUIRE( mapnik::freetype_engine::register_font("test/data/fonts/NotoSans-Regular.ttc") ); face_names = mapnik::freetype_engine::face_names(); REQUIRE( face_names.size() == 25 ); // now blindly register as many system fonts as possible // the goal here to make sure we don't crash // linux mapnik::freetype_engine::register_fonts("/usr/share/fonts/", true); mapnik::freetype_engine::register_fonts("/usr/local/share/fonts/", true); // osx mapnik::freetype_engine::register_fonts("/Library/Fonts/", true); mapnik::freetype_engine::register_fonts("/System/Library/Fonts/", true); // windows mapnik::freetype_engine::register_fonts("C:\\Windows\\Fonts", true); face_names = mapnik::freetype_engine::face_names(); REQUIRE( face_names.size() > 23 ); } catch (std::exception const & ex) { std::clog << ex.what() << "\n"; REQUIRE(false); } } }
update font_registration test
update font_registration test
C++
lgpl-2.1
mapycz/mapnik,naturalatlas/mapnik,lightmare/mapnik,naturalatlas/mapnik,mapnik/mapnik,lightmare/mapnik,tomhughes/mapnik,mapnik/mapnik,zerebubuth/mapnik,naturalatlas/mapnik,tomhughes/mapnik,zerebubuth/mapnik,tomhughes/mapnik,mapnik/mapnik,mapycz/mapnik,zerebubuth/mapnik,mapycz/mapnik,naturalatlas/mapnik,CartoDB/mapnik,CartoDB/mapnik,lightmare/mapnik,CartoDB/mapnik,mapnik/mapnik,tomhughes/mapnik,lightmare/mapnik
edf9bd5bcfc035521123484c966512a06f91b79a
apps/hello_ssp/src/hello_ssp.cpp
apps/hello_ssp/src/hello_ssp.cpp
#include <petuum_ps_common/include/petuum_ps.hpp> #include <gflags/gflags.h> #include <glog/logging.h> #include <thread> #include <cstdint> #include <random> #include <chrono> DEFINE_string(hostfile, "", "Path to file containing server ip:port."); DEFINE_int32(num_clients, 1, "# of nodes"); DEFINE_int32(client_id, 0, "Client ID"); DEFINE_int32(num_threads, 1, "# of worker threads."); DEFINE_int32(num_iterations, 10, "# of iterations."); DEFINE_int32(staleness, 0, "Staleness."); DEFINE_int32(max_delay_millisec, 100, ""); // HelloSSP demonstrates the concept of stale synchronous parallel (SSP). It // uses 1 table with 1 row, with num_workers columns (FLAGS_num_clients * // FLAGS_num_threads), each entry is the clock of one worker as viewed by each // worker. SSP ensures that the clock view will be at most 'staleness' clocks // apart, which we verify here. namespace { const int kDenseRowType = 0; const int kTableID = 0; void HelloSSPWorker(int worker_rank) { petuum::PSTableGroup::RegisterThread(); std::random_device rd; std::mt19937 rng; std::uniform_int_distribution<int> dist(0,FLAGS_max_delay_millisec); petuum::Table<double> clock_table = petuum::PSTableGroup::GetTableOrDie<double>(kTableID); int num_workers = FLAGS_num_clients * FLAGS_num_threads; std::vector<double> row_cache; for (int clock = 0; clock < FLAGS_num_iterations; ++clock) { std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng))); petuum::RowAccessor row_acc; clock_table.Get(0, &row_acc); const auto& row = row_acc.Get<petuum::DenseRow<double>>(); // Cache the row to a local vector to avoid acquiring lock when accessing // each entry. row.CopyToVector(&row_cache); for (int w = 0; w < num_workers; ++w) { CHECK_GE(row_cache[w], clock - FLAGS_staleness) << "I'm worker " << worker_rank << " seeing w: " << w; } // Update clock entry associated with this worker. clock_table.Inc(0, worker_rank, 1); petuum::PSTableGroup::Clock(); } // After global barrier, all clock view should be up-to-date. petuum::PSTableGroup::GlobalBarrier(); petuum::RowAccessor row_acc; clock_table.Get(0, &row_acc); const auto& row = row_acc.Get<petuum::DenseRow<double>>(); row.CopyToVector(&row_cache); for (int w = 0; w < num_workers; ++w) { CHECK_EQ(row_cache[w], FLAGS_num_iterations); } LOG(INFO) << "Worker " << worker_rank << " verified all clock reads."; petuum::PSTableGroup::DeregisterThread(); } } // anonymous namespace int main(int argc, char *argv[]) { google::ParseCommandLineFlags(&argc, &argv, true); google::InitGoogleLogging(argv[0]); petuum::TableGroupConfig table_group_config; table_group_config.num_comm_channels_per_client = 1; table_group_config.num_total_clients = FLAGS_num_clients; table_group_config.num_tables = 1; // just the clock table // + 1 for main() thread. table_group_config.num_local_app_threads = FLAGS_num_threads + 1; table_group_config.client_id = FLAGS_client_id; table_group_config.consistency_model = petuum::SSPPush; petuum::GetHostInfos(FLAGS_hostfile, &table_group_config.host_map); petuum::PSTableGroup::RegisterRow<petuum::DenseRow<double>>(kDenseRowType); petuum::PSTableGroup::Init(table_group_config, false); // Creating test table. petuum::ClientTableConfig table_config; table_config.table_info.row_type = kDenseRowType; table_config.table_info.table_staleness = FLAGS_staleness; table_config.table_info.row_capacity = FLAGS_num_clients * FLAGS_num_threads; table_config.process_cache_capacity = 1; // only 1 row. table_config.table_info.row_oplog_type = petuum::RowOpLogType::kDenseRowOpLog; // no need to squeeze out 0's table_config.table_info.oplog_dense_serialized = false; table_config.table_info.dense_row_oplog_capacity = table_config.table_info.row_capacity; table_config.oplog_capacity = table_config.process_cache_capacity; CHECK(petuum::PSTableGroup::CreateTable(kTableID, table_config)); petuum::PSTableGroup::CreateTableDone(); LOG(INFO) << "Starting HelloSSP with " << FLAGS_num_threads << " threads " << "on client " << FLAGS_client_id; std::vector<std::thread> threads(FLAGS_num_threads); int worker_rank = FLAGS_client_id * FLAGS_num_threads; for (auto& thr : threads) { thr = std::thread(HelloSSPWorker, worker_rank++); } for (auto& thr : threads) { thr.join(); } petuum::PSTableGroup::ShutDown(); LOG(INFO) << "HelloSSP Finished!"; return 0; }
#include <petuum_ps_common/include/petuum_ps.hpp> #include <gflags/gflags.h> #include <glog/logging.h> #include <thread> #include <cstdint> #include <random> #include <chrono> DEFINE_string(hostfile, "", "Path to file containing server ip:port."); DEFINE_int32(num_clients, 1, "# of nodes"); DEFINE_int32(client_id, 0, "Client ID"); DEFINE_int32(num_threads, 1, "# of worker threads."); DEFINE_int32(num_iterations, 10, "# of iterations."); DEFINE_int32(staleness, 0, "Staleness."); DEFINE_int32(max_delay_millisec, 100, ""); // HelloSSP demonstrates the concept of stale synchronous parallel (SSP). It // uses 1 table with 1 row, with num_workers columns (FLAGS_num_clients * // FLAGS_num_threads), each entry is the clock of one worker as viewed by each // worker. SSP ensures that the clock view will be at most 'staleness' clocks // apart, which we verify here. namespace { const int kDenseRowType = 0; const int kTableID = 0; void HelloSSPWorker(int worker_rank) { petuum::PSTableGroup::RegisterThread(); std::random_device rd; std::mt19937 rng; std::uniform_int_distribution<int> dist(0,FLAGS_max_delay_millisec); petuum::Table<double> clock_table = petuum::PSTableGroup::GetTableOrDie<double>(kTableID); int num_workers = FLAGS_num_clients * FLAGS_num_threads; std::vector<double> row_cache; // Register callbacks. clock_table.GetAsyncForced(0); clock_table.WaitPendingAsyncGet(); for (int clock = 0; clock < FLAGS_num_iterations; ++clock) { std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng))); petuum::RowAccessor row_acc; clock_table.Get(0, &row_acc); const auto& row = row_acc.Get<petuum::DenseRow<double>>(); // Cache the row to a local vector to avoid acquiring lock when accessing // each entry. row.CopyToVector(&row_cache); for (int w = 0; w < num_workers; ++w) { CHECK_GE(row_cache[w], clock - FLAGS_staleness) << "I'm worker " << worker_rank << " seeing w: " << w; } // Update clock entry associated with this worker. clock_table.Inc(0, worker_rank, 1); petuum::PSTableGroup::Clock(); } // After global barrier, all clock view should be up-to-date. petuum::PSTableGroup::GlobalBarrier(); petuum::RowAccessor row_acc; clock_table.Get(0, &row_acc); const auto& row = row_acc.Get<petuum::DenseRow<double>>(); row.CopyToVector(&row_cache); for (int w = 0; w < num_workers; ++w) { CHECK_EQ(row_cache[w], FLAGS_num_iterations); } LOG(INFO) << "Worker " << worker_rank << " verified all clock reads."; petuum::PSTableGroup::DeregisterThread(); } } // anonymous namespace int main(int argc, char *argv[]) { google::ParseCommandLineFlags(&argc, &argv, true); google::InitGoogleLogging(argv[0]); petuum::TableGroupConfig table_group_config; table_group_config.num_comm_channels_per_client = 1; table_group_config.num_total_clients = FLAGS_num_clients; table_group_config.num_tables = 1; // just the clock table // + 1 for main() thread. table_group_config.num_local_app_threads = FLAGS_num_threads + 1; table_group_config.client_id = FLAGS_client_id; table_group_config.consistency_model = petuum::SSPPush; petuum::GetHostInfos(FLAGS_hostfile, &table_group_config.host_map); petuum::PSTableGroup::RegisterRow<petuum::DenseRow<double>>(kDenseRowType); petuum::PSTableGroup::Init(table_group_config, false); // Creating test table. petuum::ClientTableConfig table_config; table_config.table_info.row_type = kDenseRowType; table_config.table_info.table_staleness = FLAGS_staleness; table_config.table_info.row_capacity = FLAGS_num_clients * FLAGS_num_threads; table_config.process_cache_capacity = 1; // only 1 row. table_config.table_info.row_oplog_type = petuum::RowOpLogType::kDenseRowOpLog; // no need to squeeze out 0's table_config.table_info.oplog_dense_serialized = false; table_config.table_info.dense_row_oplog_capacity = table_config.table_info.row_capacity; table_config.oplog_capacity = table_config.process_cache_capacity; CHECK(petuum::PSTableGroup::CreateTable(kTableID, table_config)); petuum::PSTableGroup::CreateTableDone(); LOG(INFO) << "Starting HelloSSP with " << FLAGS_num_threads << " threads " << "on client " << FLAGS_client_id; std::vector<std::thread> threads(FLAGS_num_threads); int worker_rank = FLAGS_client_id * FLAGS_num_threads; for (auto& thr : threads) { thr = std::thread(HelloSSPWorker, worker_rank++); } for (auto& thr : threads) { thr.join(); } petuum::PSTableGroup::ShutDown(); LOG(INFO) << "HelloSSP Finished!"; return 0; }
add bootstrap
add bootstrap
C++
bsd-3-clause
daiwei89/wdai_petuum_public,daiwei89/wdai_petuum_public,daiwei89/wdai_petuum_public,daiwei89/wdai_petuum_public
c99f0c1adbcd2090d36b353cd3370420292c92fc
libnanocv/optimize/batch_gd.hpp
libnanocv/optimize/batch_gd.hpp
#pragma once #include "batch_params.hpp" #include "ls_armijo.hpp" #include <cassert> namespace ncv { namespace optimize { /// /// \brief gradient descent /// template < typename tproblem ///< optimization problem > struct batch_gd : public batch_params_t<tproblem> { typedef batch_params_t<tproblem> base_t; typedef typename base_t::tscalar tscalar; typedef typename base_t::tsize tsize; typedef typename base_t::tvector tvector; typedef typename base_t::tstate tstate; typedef typename base_t::twlog twlog; typedef typename base_t::telog telog; typedef typename base_t::tulog tulog; /// /// \brief constructor /// batch_gd( tsize max_iterations, tscalar epsilon, const twlog& wlog = twlog(), const telog& elog = telog(), const tulog& ulog = tulog()) : base_t(max_iterations, epsilon, wlog, elog, ulog) { } /// /// \brief minimize starting from the initial guess x0 /// tstate operator()(const tproblem& problem, const tvector& x0) const { assert(problem.size() == static_cast<tsize>(x0.size())); tstate cstate(problem, x0); // current state tscalar prv_fx = 0; // iterate until convergence for (tsize i = 0; i < base_t::m_max_iterations; i ++) { base_t::ulog(cstate); // check convergence if (cstate.converged(base_t::m_epsilon)) { break; } // descent direction cstate.d = -cstate.g; // initial line-search step (Nocedal & Wright (numerical optimization 2nd) @ p.59) const tscalar dg = cstate.d.dot(cstate.g); const tscalar t0 = (i == 0) ? (1.0) : std::min(1.0, 1.01 * 2.0 * (cstate.f - prv_fx) / dg); prv_fx = cstate.f; // update solution const tscalar t = ls_armijo(problem, cstate, base_t::m_wlog, t0); if (t < std::numeric_limits<tscalar>::epsilon()) { base_t::elog("line-search failed for GD!"); break; } cstate.update(problem, t); } return cstate; } }; } }
#pragma once #include "batch_params.hpp" #include "ls_armijo.hpp" #include <cassert> namespace ncv { namespace optimize { /// /// \brief gradient descent /// template < typename tproblem ///< optimization problem > struct batch_gd : public batch_params_t<tproblem> { typedef batch_params_t<tproblem> base_t; typedef typename base_t::tscalar tscalar; typedef typename base_t::tsize tsize; typedef typename base_t::tvector tvector; typedef typename base_t::tstate tstate; typedef typename base_t::twlog twlog; typedef typename base_t::telog telog; typedef typename base_t::tulog tulog; /// /// \brief constructor /// batch_gd( tsize max_iterations, tscalar epsilon, const twlog& wlog = twlog(), const telog& elog = telog(), const tulog& ulog = tulog()) : base_t(max_iterations, epsilon, wlog, elog, ulog) { } /// /// \brief minimize starting from the initial guess x0 /// tstate operator()(const tproblem& problem, const tvector& x0) const { assert(problem.size() == static_cast<tsize>(x0.size())); tstate cstate(problem, x0); // current state tscalar prv_fx = 0; const tscalar alpha = tscalar(0.2); const tscalar beta = tscalar(0.7); // iterate until convergence for (tsize i = 0; i < base_t::m_max_iterations; i ++) { base_t::ulog(cstate); // check convergence if (cstate.converged(base_t::m_epsilon)) { break; } // descent direction cstate.d = -cstate.g; // initial line-search step (Nocedal & Wright (numerical optimization 2nd) @ p.59) const tscalar dg = cstate.d.dot(cstate.g); const tscalar t0 = (i == 0) ? (1.0) : std::min(1.0, 1.01 * 2.0 * (cstate.f - prv_fx) / dg); prv_fx = cstate.f; // update solution const tscalar t = ls_armijo(problem, cstate, base_t::m_wlog, t0, alpha, beta); if (t < std::numeric_limits<tscalar>::epsilon()) { base_t::elog("line-search failed for GD!"); break; } cstate.update(problem, t); } return cstate; } }; } }
make line-search parameters explicit for GD
make line-search parameters explicit for GD
C++
mit
accosmin/nanocv,accosmin/nanocv,accosmin/nanocv,accosmin/nano,accosmin/nano,accosmin/nano
d3b3db011513f2ad391d17fd2088285d31f1aa46
test/test_early_wamp_session_destructor.cc
test/test_early_wamp_session_destructor.cc
/* * Copyright (c) 2017 Darren Smith * * wampcc is free software; you can redistribute it and/or modify * it under the terms of the MIT license. See LICENSE for details. */ #include "test_common.h" #include "mini_test.h" using namespace wampcc; using namespace std; int global_port; int global_loops = 100; void test_WS_destroyed_before_kernel(int port) { TSTART(); callback_status = callback_status_t::not_invoked; { unique_ptr<kernel> the_kernel( new kernel({}, logger::nolog() ) ); unique_ptr<tcp_socket> sock (new tcp_socket(the_kernel.get())); /* attempt to connect the socket */ cout << "attemping socket connection ...\n"; auto fut = sock->connect("127.0.0.1", port); auto connect_status = fut.wait_for(chrono::milliseconds(100)); if (connect_status == future_status::timeout) { cout << " failed to connect\n"; return; } cout << " got socket connection\n"; /* attempt to create a session */ cout << "attemping session creation ...\n"; shared_ptr<wamp_session> session = wamp_session::create<rawsocket_protocol>( the_kernel.get(), std::move(sock), session_cb, {}); cout << " got session\n"; cout << "calling: session->close().wait()\n"; session->close().wait(); cout << "trigger ~wamp_session for " << session->unique_id() << "\n"; session.reset(); cout << "exiting scope (will trigger kernel, io_loop, ev_loop destruction)...\n"; } // ensure callback was invoked assert(callback_status == callback_status_t::close_with_sp); cout << "test success\n"; } TEST_CASE("test_WS_destroyed_before_kernel_shared_server") { // share a common internal_server for (int i = 0; i < 10; i++) { internal_server iserver; int port = iserver.start(global_port++); for (int j=0; j < global_loops; j++) { test_WS_destroyed_before_kernel(port); } } } TEST_CASE("test_WS_destroyed_before_kernel_common_server") { // use one internal_server per test for (int i = 0; i < global_loops; i++) { internal_server iserver; int port = iserver.start(global_port++); test_WS_destroyed_before_kernel(port); } } int main(int argc, char** argv) { try { global_port = 21000; if (argc > 1) global_port = atoi(argv[1]); int result = minitest::run(argc, argv); return (result < 0xFF ? result : 0xFF); } catch (exception& e) { cout << e.what() << endl; return 1; } }
/* * Copyright (c) 2017 Darren Smith * * wampcc is free software; you can redistribute it and/or modify * it under the terms of the MIT license. See LICENSE for details. */ #include "test_common.h" #include "mini_test.h" using namespace wampcc; using namespace std; int global_port; int global_loops = 100; void test_WS_destroyed_before_kernel(int port) { TSTART(); callback_status = callback_status_t::not_invoked; { unique_ptr<kernel> the_kernel( new kernel({}, logger::nolog() ) ); unique_ptr<tcp_socket> sock (new tcp_socket(the_kernel.get())); /* attempt to connect the socket */ cout << "attemping socket connection ...\n"; auto fut = sock->connect("127.0.0.1", port); auto connect_status = fut.wait_for(chrono::milliseconds(100)); if (connect_status == future_status::timeout) { cout << " failed to connect\n"; return; } cout << " got socket connection\n"; /* attempt to create a session */ cout << "attemping session creation ...\n"; shared_ptr<wamp_session> session = wamp_session::create<rawsocket_protocol>( the_kernel.get(), std::move(sock), session_cb, {}); cout << " got session\n"; cout << "calling: session->close().wait()\n"; session->close().wait(); cout << "trigger ~wamp_session for " << session->unique_id() << "\n"; session.reset(); cout << "exiting scope (will trigger kernel, io_loop, ev_loop destruction)...\n"; } // ensure callback was invoked assert(callback_status == callback_status_t::close_with_sp); cout << "test success\n"; } TEST_CASE("test_WS_destroyed_before_kernel_shared_server") { // share a common internal_server for (int i = 0; i < 3; i++) { internal_server iserver; int port = iserver.start(global_port++); for (int j=0; j < global_loops; j++) { test_WS_destroyed_before_kernel(port); } } } TEST_CASE("test_WS_destroyed_before_kernel_common_server") { // use one internal_server per test for (int i = 0; i < global_loops; i++) { internal_server iserver; int port = iserver.start(global_port++); test_WS_destroyed_before_kernel(port); } } int main(int argc, char** argv) { try { global_port = 21000; if (argc > 1) global_port = atoi(argv[1]); int result = minitest::run(argc, argv); return (result < 0xFF ? result : 0xFF); } catch (exception& e) { cout << e.what() << endl; return 1; } }
reduce number of loops
reduce number of loops
C++
mit
darrenjs/wampcc,darrenjs/wampcc,darrenjs/wampcc,darrenjs/wampcc,darrenjs/wampcc
4fd28fff8c873bd4e236cfa4614b43897ad264ec
test/dynalloc.cpp
test/dynalloc.cpp
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008 Gael Guennebaud <[email protected]> // // Eigen 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. // // Alternatively, 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. // // Eigen 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 or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #include "main.h" #if EIGEN_ALIGN #define ALIGNMENT 16 #else #define ALIGNMENT 1 #endif void check_handmade_aligned_malloc() { for(int i = 1; i < 1000; i++) { char *p = (char*)internal::handmade_aligned_malloc(i); VERIFY(size_t(p)%ALIGNMENT==0); // if the buffer is wrongly allocated this will give a bad write --> check with valgrind for(int j = 0; j < i; j++) p[j]=0; internal::handmade_aligned_free(p); } } void check_aligned_malloc() { for(int i = 1; i < 1000; i++) { char *p = (char*)internal::aligned_malloc(i); VERIFY(size_t(p)%ALIGNMENT==0); // if the buffer is wrongly allocated this will give a bad write --> check with valgrind for(int j = 0; j < i; j++) p[j]=0; internal::aligned_free(p); } } void check_aligned_new() { for(int i = 1; i < 1000; i++) { float *p = internal::aligned_new<float>(i); VERIFY(size_t(p)%ALIGNMENT==0); // if the buffer is wrongly allocated this will give a bad write --> check with valgrind for(int j = 0; j < i; j++) p[j]=0; internal::aligned_delete(p,i); } } void check_aligned_stack_alloc() { for(int i = 1; i < 1000; i++) { float *p = ei_aligned_stack_new(float,i); VERIFY(size_t(p)%ALIGNMENT==0); // if the buffer is wrongly allocated this will give a bad write --> check with valgrind for(int j = 0; j < i; j++) p[j]=0; ei_aligned_stack_delete(float,p,i); } } // test compilation with both a struct and a class... struct MyStruct { EIGEN_MAKE_ALIGNED_OPERATOR_NEW char dummychar; Vector4f avec; }; class MyClassA { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW char dummychar; Vector4f avec; }; template<typename T> void check_dynaligned() { T* obj = new T; VERIFY(size_t(obj)%ALIGNMENT==0); delete obj; } void test_dynalloc() { // low level dynamic memory allocation CALL_SUBTEST(check_handmade_aligned_malloc()); CALL_SUBTEST(check_aligned_malloc()); CALL_SUBTEST(check_aligned_new()); CALL_SUBTEST(check_aligned_stack_alloc()); for (int i=0; i<g_repeat*100; ++i) { CALL_SUBTEST(check_dynaligned<Vector4f>() ); CALL_SUBTEST(check_dynaligned<Vector2d>() ); CALL_SUBTEST(check_dynaligned<Matrix4f>() ); CALL_SUBTEST(check_dynaligned<Vector4d>() ); CALL_SUBTEST(check_dynaligned<Vector4i>() ); } // check static allocation, who knows ? { MyStruct foo0; VERIFY(size_t(foo0.avec.data())%ALIGNMENT==0); MyClassA fooA; VERIFY(size_t(fooA.avec.data())%ALIGNMENT==0); } // dynamic allocation, single object for (int i=0; i<g_repeat*100; ++i) { MyStruct *foo0 = new MyStruct(); VERIFY(size_t(foo0->avec.data())%ALIGNMENT==0); MyClassA *fooA = new MyClassA(); VERIFY(size_t(fooA->avec.data())%ALIGNMENT==0); delete foo0; delete fooA; } // dynamic allocation, array const int N = 10; for (int i=0; i<g_repeat*100; ++i) { MyStruct *foo0 = new MyStruct[N]; VERIFY(size_t(foo0->avec.data())%ALIGNMENT==0); MyClassA *fooA = new MyClassA[N]; VERIFY(size_t(fooA->avec.data())%ALIGNMENT==0); delete[] foo0; delete[] fooA; } }
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008 Gael Guennebaud <[email protected]> // // Eigen 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. // // Alternatively, 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. // // Eigen 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 or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #include "main.h" #if EIGEN_ALIGN #define ALIGNMENT 16 #else #define ALIGNMENT 1 #endif void check_handmade_aligned_malloc() { for(int i = 1; i < 1000; i++) { char *p = (char*)internal::handmade_aligned_malloc(i); VERIFY(size_t(p)%ALIGNMENT==0); // if the buffer is wrongly allocated this will give a bad write --> check with valgrind for(int j = 0; j < i; j++) p[j]=0; internal::handmade_aligned_free(p); } } void check_aligned_malloc() { for(int i = 1; i < 1000; i++) { char *p = (char*)internal::aligned_malloc(i); VERIFY(size_t(p)%ALIGNMENT==0); // if the buffer is wrongly allocated this will give a bad write --> check with valgrind for(int j = 0; j < i; j++) p[j]=0; internal::aligned_free(p); } } void check_aligned_new() { for(int i = 1; i < 1000; i++) { float *p = internal::aligned_new<float>(i); VERIFY(size_t(p)%ALIGNMENT==0); // if the buffer is wrongly allocated this will give a bad write --> check with valgrind for(int j = 0; j < i; j++) p[j]=0; internal::aligned_delete(p,i); } } void check_aligned_stack_alloc() { for(int i = 1; i < 1000; i++) { float *p = ei_aligned_stack_new(float,i); VERIFY(size_t(p)%ALIGNMENT==0); // if the buffer is wrongly allocated this will give a bad write --> check with valgrind for(int j = 0; j < i; j++) p[j]=0; ei_aligned_stack_delete(float,p,i); } } // test compilation with both a struct and a class... struct MyStruct { EIGEN_MAKE_ALIGNED_OPERATOR_NEW char dummychar; Vector4f avec; }; class MyClassA { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW char dummychar; Vector4f avec; }; template<typename T> void check_dynaligned() { T* obj = new T; VERIFY(size_t(obj)%ALIGNMENT==0); delete obj; } void test_dynalloc() { // low level dynamic memory allocation CALL_SUBTEST(check_handmade_aligned_malloc()); CALL_SUBTEST(check_aligned_malloc()); CALL_SUBTEST(check_aligned_new()); CALL_SUBTEST(check_aligned_stack_alloc()); for (int i=0; i<g_repeat*100; ++i) { CALL_SUBTEST(check_dynaligned<Vector4f>() ); CALL_SUBTEST(check_dynaligned<Vector2d>() ); CALL_SUBTEST(check_dynaligned<Matrix4f>() ); CALL_SUBTEST(check_dynaligned<Vector4d>() ); CALL_SUBTEST(check_dynaligned<Vector4i>() ); } // check static allocation, who knows ? #if EIGEN_ALIGN_STATICALLY { MyStruct foo0; VERIFY(size_t(foo0.avec.data())%ALIGNMENT==0); MyClassA fooA; VERIFY(size_t(fooA.avec.data())%ALIGNMENT==0); } // dynamic allocation, single object for (int i=0; i<g_repeat*100; ++i) { MyStruct *foo0 = new MyStruct(); VERIFY(size_t(foo0->avec.data())%ALIGNMENT==0); MyClassA *fooA = new MyClassA(); VERIFY(size_t(fooA->avec.data())%ALIGNMENT==0); delete foo0; delete fooA; } // dynamic allocation, array const int N = 10; for (int i=0; i<g_repeat*100; ++i) { MyStruct *foo0 = new MyStruct[N]; VERIFY(size_t(foo0->avec.data())%ALIGNMENT==0); MyClassA *fooA = new MyClassA[N]; VERIFY(size_t(fooA->avec.data())%ALIGNMENT==0); delete[] foo0; delete[] fooA; } #endif }
disable testing of aligned members when aligned static allocation is not enabled (e.g., for gcc 3.4)
disable testing of aligned members when aligned static allocation is not enabled (e.g., for gcc 3.4)
C++
bsd-3-clause
pthulhu/eigen,pthulhu/eigen,pthulhu/eigen,cjntaylor/eigen,pthulhu/eigen,cjntaylor/eigen,cjntaylor/eigen,cjntaylor/eigen,pthulhu/eigen
b2827fcc56f0ddca96a9459a89e67c789d6bf6c2
testat-1/sevensegment/src/sevensegment.cpp
testat-1/sevensegment/src/sevensegment.cpp
#include "sevensegment.h" #include <ostream> #include <vector> #include <string> #include <algorithm> #include <iterator> #include <stdexcept> namespace sevensegment { using digit = std::vector<std::string>; const std::vector<digit> digits { { " - ", "| |", " ", "| |", " - " }, // 0 { " ", " |", " ", " |", " " }, // 1 { " - ", " |", " - ", "| ", " - " }, // 2 { " - ", " |", " - ", " |", " - " }, // 3 { " ", "| |", " - ", " |", " " }, // 4 { " - ", "| ", " - ", " |", " - " }, // 5 { " - ", "| ", " - ", "| |", " - " }, // 6 { " - ", " |", " ", " |", " " }, // 7 { " - ", "| |", " - ", "| |", " - " }, // 8 { " - ", "| |", " - ", " |", " - " } // 9 }; const digit minus_sign { " ", " ", " - ", " ", " " }; // - const std::vector<digit> error { { " - ", "| ", " - ", "| ", " - " }, // E { " ", " ", " - ", "| ", " " }, // r { " ", " ", " - ", "| ", " " }, // r { " ", " ", " - ", "| |" " - " }, // o { " ", " ", " - ", "| ", " " }, // r }; std::string stretchDigitLine(const std::string& line, const unsigned scale_factor) { std::string stretched_line(scale_factor+2, line[1]); stretched_line.front() = line[0]; stretched_line.back() = line[2]; return stretched_line; } std::vector<digit> split_digits(const int i, std::vector<digit>& vector) { if(i >= 10) split_digits(i / 10, vector); vector.push_back(digits.at(i % 10)); return vector; } std::vector<digit> split_digits(int i) { std::vector<digit> vector {}; if (i<0) { vector.push_back(minus_sign); i = -i; } return split_digits(i, vector); } std::string lineOfLargeDigits(const std::vector<digit>& digits_vector, const unsigned line_nr, const unsigned scale_factor){ std::string line {}; unsigned digit_nr { 0 }; const auto number_of_digits = digits_vector.size(); for(digit d : digits_vector){ line.append(stretchDigitLine(d[line_nr], scale_factor)); // between digits (not at the end) if (++digit_nr != number_of_digits) line.append(scale_factor/2, ' '); // letter spacing for readability } return line; } constexpr unsigned display_size { 8 }; void printDigitSequence(const std::vector<digit> digits_vector, std::ostream& out, const unsigned scale_factor){ if (scale_factor<1) throw std::range_error { "invalid scale" }; if (digits_vector.size() > display_size) throw std::overflow_error { "too many digits" }; unsigned line_nr {0}; std::ostream_iterator<std::string> out_it(out, "\n"); // iterate through lines, not digits // OPTIMIZE: transpose vector first for(int line_nr = 0; line_nr < 5; ++line_nr) { if (line_nr == 1 || line_nr == 3) { const auto line = lineOfLargeDigits(digits_vector, line_nr, scale_factor); std::generate_n(out_it, scale_factor, [&](){return line;}); } else { out << lineOfLargeDigits(digits_vector, line_nr, scale_factor) << '\n'; } } } void printLargeDigit(const unsigned i, std::ostream& out, const unsigned scale_factor) { const auto digit = digits.at(i); const std::vector< std::vector<std::string> > single_digit_vector { digit }; printDigitSequence(single_digit_vector, out, scale_factor); } void printLargeNumber(const int i, std::ostream& out, const unsigned scale_factor) { const auto digits_vector = split_digits(i); printDigitSequence(digits_vector, out, scale_factor); } void printLargeError(std::ostream& out, const unsigned scale_factor) { printDigitSequence(error, out, scale_factor); } }
#include "sevensegment.h" #include <ostream> #include <vector> #include <string> #include <algorithm> #include <iterator> #include <stdexcept> namespace sevensegment { using digit = std::vector<std::string>; const std::vector<digit> digits { { " - ", "| |", " ", "| |", " - " }, // 0 { " ", " |", " ", " |", " " }, // 1 { " - ", " |", " - ", "| ", " - " }, // 2 { " - ", " |", " - ", " |", " - " }, // 3 { " ", "| |", " - ", " |", " " }, // 4 { " - ", "| ", " - ", " |", " - " }, // 5 { " - ", "| ", " - ", "| |", " - " }, // 6 { " - ", " |", " ", " |", " " }, // 7 { " - ", "| |", " - ", "| |", " - " }, // 8 { " - ", "| |", " - ", " |", " - " } // 9 }; const digit minus_sign { " ", " ", " - ", " ", " " }; // - const std::vector<digit> error { { " - ", "| ", " - ", "| ", " - " }, // E { " ", " ", " - ", "| ", " " }, // r { " ", " ", " - ", "| ", " " }, // r { " ", " ", " - ", "| |" " - " }, // o { " ", " ", " - ", "| ", " " }, // r }; std::string stretchDigitLine(const std::string& line, const unsigned scale_factor) { std::string stretched_line(scale_factor+2, line[1]); stretched_line.front() = line[0]; stretched_line.back() = line[2]; return stretched_line; } std::vector<digit> split_digits(const int i, std::vector<digit>& vector) { if(i >= 10) split_digits(i / 10, vector); vector.push_back(digits.at(i % 10)); return vector; } std::vector<digit> split_digits(int i) { std::vector<digit> vector {}; if (i<0) { vector.push_back(minus_sign); i = -i; } return split_digits(i, vector); } std::string lineOfLargeDigits(const std::vector<digit>& digits_vector, const unsigned line_nr, const unsigned scale_factor){ std::string line {}; unsigned digit_nr { 0 }; const auto number_of_digits = digits_vector.size(); for(digit d : digits_vector){ line.append(stretchDigitLine(d[line_nr], scale_factor)); // between digits (not at the end) if (++digit_nr != number_of_digits) line.append(scale_factor/2, ' '); // letter spacing for readability } return line; } constexpr unsigned display_size { 8 }; void printDigitSequence(const std::vector<digit> digits_vector, std::ostream& out, const unsigned scale_factor){ if (scale_factor<1) throw std::range_error { "invalid scale" }; if (digits_vector.size() > display_size) throw std::overflow_error { "too many digits" }; unsigned line_nr {0}; std::ostream_iterator<std::string> out_it(out, "\n"); // iterate through lines, not digits // OPTIMIZE: transpose vector first for(int line_nr = 0; line_nr < 5; ++line_nr) { if (line_nr == 1 || line_nr == 3) { const auto line = lineOfLargeDigits(digits_vector, line_nr, scale_factor); std::generate_n(out_it, scale_factor, [&](){return line;}); } else { out << lineOfLargeDigits(digits_vector, line_nr, scale_factor) << '\n'; } } } void printLargeDigit(const unsigned i, std::ostream& out, const unsigned scale_factor) { const auto digit = digits.at(i); const std::vector<digit> single_digit_vector { digit }; printDigitSequence(single_digit_vector, out, scale_factor); } void printLargeNumber(const int i, std::ostream& out, const unsigned scale_factor) { const auto digits_vector = split_digits(i); printDigitSequence(digits_vector, out, scale_factor); } void printLargeError(std::ostream& out, const unsigned scale_factor) { printDigitSequence(error, out, scale_factor); } }
simplify declaration using type alias
simplify declaration using type alias
C++
mit
paddor/cpp-exercises,paddor/prog3,paddor/prog3,paddor/prog3,paddor/cpp-exercises,paddor/cpp-exercises
8270f9299fd8d3dbf658200f7f43bede170bfe71
src/json_ui.cc
src/json_ui.cc
#include "json_ui.hh" #include "containers.hh" #include "display_buffer.hh" #include "keys.hh" #include "file.hh" #include "event_manager.hh" #include "value.hh" #include "unit_tests.hh" #include <utility> #include <unistd.h> namespace Kakoune { template<typename T> String to_json(ArrayView<const T> array) { String res; for (auto& elem : array) { if (not res.empty()) res += ", "; res += to_json(elem); } return "[" + res + "]"; } template<typename T, MemoryDomain D> String to_json(const Vector<T, D>& vec) { return to_json(ArrayView<const T>{vec}); } String to_json(int i) { return to_string(i); } String to_json(bool b) { return b ? "true" : "false"; } String to_json(StringView str) { String res; res.reserve(str.length() + 4); res += '"'; for (auto it = str.begin(), end = str.end(); it != end; ) { auto next = std::find_if(it, end, [](char c) { return c == '\\' or c == '"' or (c >= 0 and c <= 0x1F); }); res += StringView{it, next}; if (next == end) break; char buf[7] = {'\\', *next, 0}; if (*next >= 0 and *next <= 0x1F) sprintf(buf, "\\u%04x", *next); res += buf; it = next+1; } res += '"'; return res; } String to_json(Color color) { if (color.color == Kakoune::Color::RGB) { char buffer[10]; sprintf(buffer, R"("#%02x%02x%02x")", color.r, color.g, color.b); return buffer; } return to_json(color_to_str(color)); } String to_json(Attribute attributes) { struct { Attribute attr; StringView name; } attrs[] { { Attribute::Exclusive, "exclusive" }, { Attribute::Underline, "underline" }, { Attribute::Reverse, "reverse" }, { Attribute::Blink, "blink" }, { Attribute::Bold, "bold" }, { Attribute::Dim, "dim" }, { Attribute::Italic, "italic" }, }; String res; for (auto& attr : attrs) { if (not (attributes & attr.attr)) continue; if (not res.empty()) res += ", "; res += to_json(attr.name); } return "[" + res + "]"; } String to_json(Face face) { return format(R"(\{ "fg": {}, "bg": {}, "attributes": {} })", to_json(face.fg), to_json(face.bg), to_json(face.attributes)); } String to_json(const DisplayAtom& atom) { return format(R"(\{ "face": {}, "contents": {} })", to_json(atom.face), to_json(atom.content())); } String to_json(const DisplayLine& line) { return to_json(line.atoms()); } String to_json(CharCoord coord) { return format(R"(\{ "line": {}, "column": {} })", coord.line, coord.column); } String to_json(MenuStyle style) { switch (style) { case MenuStyle::Prompt: return R"("prompt")"; case MenuStyle::Inline: return R"("inline")"; } return ""; } String to_json(InfoStyle style) { switch (style) { case InfoStyle::Prompt: return R"("prompt")"; case InfoStyle::Inline: return R"("inline")"; case InfoStyle::InlineAbove: return R"("inlineAbove")"; case InfoStyle::InlineBelow: return R"("inlineBelow")"; case InfoStyle::MenuDoc: return R"("menuDoc")"; } return ""; } String concat() { return ""; } template<typename First, typename... Args> String concat(First&& first, Args&&... args) { if (sizeof...(Args) != 0) return to_json(first) + ", " + concat(args...); return to_json(first); } template<typename... Args> void rpc_call(StringView method, Args&&... args) { auto q = format(R"(\{ "jsonrpc": "2.0", "method": "{}", "params": [{}] }{})", method, concat(std::forward<Args>(args)...), "\n"); write_stdout(q); } JsonUI::JsonUI() : m_stdin_watcher{0, [this](FDWatcher&, EventMode mode) { parse_requests(mode); }}, m_dimensions{24, 80} { set_signal_handler(SIGINT, SIG_DFL); } void JsonUI::draw(const DisplayBuffer& display_buffer, const Face& default_face, const Face& padding_face) { rpc_call("draw", display_buffer.lines(), default_face, padding_face); } void JsonUI::draw_status(const DisplayLine& status_line, const DisplayLine& mode_line, const Face& default_face) { rpc_call("draw_status", status_line, mode_line, default_face); } bool JsonUI::is_key_available() { return not m_pending_keys.empty(); } Key JsonUI::get_key() { kak_assert(not m_pending_keys.empty()); Key key = m_pending_keys.front(); m_pending_keys.erase(m_pending_keys.begin()); return key; } void JsonUI::menu_show(ConstArrayView<DisplayLine> items, CharCoord anchor, Face fg, Face bg, MenuStyle style) { rpc_call("menu_show", items, anchor, fg, bg, style); } void JsonUI::menu_select(int selected) { rpc_call("menu_show", selected); } void JsonUI::menu_hide() { rpc_call("menu_hide"); } void JsonUI::info_show(StringView title, StringView content, CharCoord anchor, Face face, InfoStyle style) { rpc_call("info_show", title, content, anchor, face, style); } void JsonUI::info_hide() { rpc_call("info_hide"); } void JsonUI::refresh(bool force) { rpc_call("refresh", force); } void JsonUI::set_input_callback(InputCallback callback) { m_input_callback = std::move(callback); } void JsonUI::set_ui_options(const Options& options) { // rpc_call("set_ui_options", options); } CharCoord JsonUI::dimensions() { return m_dimensions; } using JsonArray = Vector<Value>; using JsonObject = IdMap<Value>; static bool is_digit(char c) { return c >= '0' and c <= '9'; } std::tuple<Value, const char*> parse_json(const char* pos, const char* end) { using Result = std::tuple<Value, const char*>; if (not skip_while(pos, end, is_blank)) return {}; if (is_digit(*pos)) { auto digit_end = pos; skip_while(digit_end, end, is_digit); return Result{ Value{str_to_int({pos, digit_end})}, digit_end }; } if (end - pos > 4 and StringView{pos, pos+4} == "true") return Result{ Value{true}, pos+4 }; if (end - pos > 5 and StringView{pos, pos+5} == "false") return Result{ Value{false}, pos+5 }; if (*pos == '"') { String value; bool escaped = false; ++pos; for (auto string_end = pos; string_end != end; ++string_end) { if (escaped) { escaped = false; value += StringView{pos, string_end}; value.back() = *string_end; pos = string_end+1; continue; } if (*string_end == '\\') escaped = true; if (*string_end == '"') { value += StringView{pos, string_end}; return Result{std::move(value), string_end+1}; } } return {}; } if (*pos == '[') { JsonArray array; if (*++pos == ']') return Result{std::move(array), pos+1}; while (true) { Value element; std::tie(element, pos) = parse_json(pos, end); if (not element) return {}; array.push_back(std::move(element)); if (not skip_while(pos, end, is_blank)) return {}; if (*pos == ',') ++pos; else if (*pos == ']') return Result{std::move(array), pos+1}; else throw runtime_error("unable to parse array, expected ',' or ']'"); } } if (*pos == '{') { JsonObject object; if (*++pos == '}') return Result{std::move(object), pos+1}; while (true) { Value name_value; std::tie(name_value, pos) = parse_json(pos, end); if (not name_value) return {}; String& name = name_value.as<String>(); if (not skip_while(pos, end, is_blank)) return {}; if (*pos++ != ':') throw runtime_error("expected :"); Value element; std::tie(element, pos) = parse_json(pos, end); if (not element) return {}; object.append({ std::move(name), std::move(element) }); if (not skip_while(pos, end, is_blank)) return {}; if (*pos == ',') ++pos; else if (*pos == '}') return Result{std::move(object), pos+1}; else throw runtime_error("unable to parse object, expected ',' or '}'"); } } throw runtime_error("Could not parse json"); } std::tuple<Value, const char*> parse_json(StringView json) { return parse_json(json.begin(), json.end()); } void JsonUI::eval_json(const Value& json) { const JsonObject& object = json.as<JsonObject>(); auto json_it = object.find("jsonrpc"); if (json_it == object.end() or json_it->value.as<String>() != "2.0") throw runtime_error("invalid json rpc request"); auto method_it = object.find("method"); if (method_it == object.end()) throw runtime_error("invalid json rpc request (method missing)"); StringView method = method_it->value.as<String>(); auto params_it = object.find("params"); if (params_it == object.end()) throw runtime_error("invalid json rpc request (params missing)"); const JsonArray& params = params_it->value.as<JsonArray>(); if (method == "keys") { for (auto& key_val : params) { for (auto& key : parse_keys(key_val.as<String>())) m_pending_keys.push_back(key); } } else if (method == "resize") { if (params.size() != 2) throw runtime_error("resize expects 2 parameters"); CharCoord dim{params[0].as<int>(), params[1].as<int>()}; m_dimensions = dim; m_pending_keys.push_back(resize(dim)); } else throw runtime_error("unknown method"); } static bool stdin_ready() { fd_set rfds; FD_ZERO(&rfds); FD_SET(0, &rfds); timeval tv; tv.tv_sec = 0; tv.tv_usec = 0; return select(1, &rfds, nullptr, nullptr, &tv) == 1; } void JsonUI::parse_requests(EventMode mode) { constexpr size_t bufsize = 1024; char buf[bufsize]; while (stdin_ready()) { ssize_t size = ::read(0, buf, bufsize); if (size == -1 or size == 0) break; m_requests += StringView{buf, buf + size}; } if (not m_requests.empty()) { const char* pos = nullptr; try { Value json; std::tie(json, pos) = parse_json(m_requests); if (json) eval_json(json); } catch (runtime_error& error) { write_stderr(format("error while handling requests '{}': '{}'", m_requests, error.what())); // try to salvage request by dropping its first line auto eol = find(m_requests, '\n'); if (eol != m_requests.end()) m_requests = String{eol+1, m_requests.end()}; else m_requests = String{}; } if (pos) m_requests = String{pos, m_requests.end()}; } while (m_input_callback and not m_pending_keys.empty()) m_input_callback(mode); } UnitTest test_json_parser{[]() { { auto value = std::get<0>(parse_json(R"({ "jsonrpc": "2.0", "method": "keys", "params": [ "b", "l", "a", "h" ] })")); kak_assert(value); } { auto value = std::get<0>(parse_json("[10,20]")); kak_assert(value and value.is_a<JsonArray>()); kak_assert(value.as<JsonArray>().at(1).as<int>() == 20); } { auto value = std::get<0>(parse_json("{}")); kak_assert(value and value.is_a<JsonObject>()); kak_assert(value.as<JsonObject>().empty()); } }}; }
#include "json_ui.hh" #include "containers.hh" #include "display_buffer.hh" #include "keys.hh" #include "file.hh" #include "event_manager.hh" #include "value.hh" #include "unit_tests.hh" #include <utility> #include <unistd.h> namespace Kakoune { template<typename T> String to_json(ArrayView<const T> array) { String res; for (auto& elem : array) { if (not res.empty()) res += ", "; res += to_json(elem); } return "[" + res + "]"; } template<typename T, MemoryDomain D> String to_json(const Vector<T, D>& vec) { return to_json(ArrayView<const T>{vec}); } String to_json(int i) { return to_string(i); } String to_json(bool b) { return b ? "true" : "false"; } String to_json(StringView str) { String res; res.reserve(str.length() + 4); res += '"'; for (auto it = str.begin(), end = str.end(); it != end; ) { auto next = std::find_if(it, end, [](char c) { return c == '\\' or c == '"' or (c >= 0 and c <= 0x1F); }); res += StringView{it, next}; if (next == end) break; char buf[7] = {'\\', *next, 0}; if (*next >= 0 and *next <= 0x1F) sprintf(buf, "\\u%04x", *next); res += buf; it = next+1; } res += '"'; return res; } String to_json(Color color) { if (color.color == Kakoune::Color::RGB) { char buffer[10]; sprintf(buffer, R"("#%02x%02x%02x")", color.r, color.g, color.b); return buffer; } return to_json(color_to_str(color)); } String to_json(Attribute attributes) { struct { Attribute attr; StringView name; } attrs[] { { Attribute::Exclusive, "exclusive" }, { Attribute::Underline, "underline" }, { Attribute::Reverse, "reverse" }, { Attribute::Blink, "blink" }, { Attribute::Bold, "bold" }, { Attribute::Dim, "dim" }, { Attribute::Italic, "italic" }, }; String res; for (auto& attr : attrs) { if (not (attributes & attr.attr)) continue; if (not res.empty()) res += ", "; res += to_json(attr.name); } return "[" + res + "]"; } String to_json(Face face) { return format(R"(\{ "fg": {}, "bg": {}, "attributes": {} })", to_json(face.fg), to_json(face.bg), to_json(face.attributes)); } String to_json(const DisplayAtom& atom) { return format(R"(\{ "face": {}, "contents": {} })", to_json(atom.face), to_json(atom.content())); } String to_json(const DisplayLine& line) { return to_json(line.atoms()); } String to_json(CharCoord coord) { return format(R"(\{ "line": {}, "column": {} })", coord.line, coord.column); } String to_json(MenuStyle style) { switch (style) { case MenuStyle::Prompt: return R"("prompt")"; case MenuStyle::Inline: return R"("inline")"; } return ""; } String to_json(InfoStyle style) { switch (style) { case InfoStyle::Prompt: return R"("prompt")"; case InfoStyle::Inline: return R"("inline")"; case InfoStyle::InlineAbove: return R"("inlineAbove")"; case InfoStyle::InlineBelow: return R"("inlineBelow")"; case InfoStyle::MenuDoc: return R"("menuDoc")"; } return ""; } String concat() { return ""; } template<typename First, typename... Args> String concat(First&& first, Args&&... args) { if (sizeof...(Args) != 0) return to_json(first) + ", " + concat(args...); return to_json(first); } template<typename... Args> void rpc_call(StringView method, Args&&... args) { auto q = format(R"(\{ "jsonrpc": "2.0", "method": "{}", "params": [{}] }{})", method, concat(std::forward<Args>(args)...), "\n"); write_stdout(q); } JsonUI::JsonUI() : m_stdin_watcher{0, [this](FDWatcher&, EventMode mode) { parse_requests(mode); }}, m_dimensions{24, 80} { set_signal_handler(SIGINT, SIG_DFL); } void JsonUI::draw(const DisplayBuffer& display_buffer, const Face& default_face, const Face& padding_face) { rpc_call("draw", display_buffer.lines(), default_face, padding_face); } void JsonUI::draw_status(const DisplayLine& status_line, const DisplayLine& mode_line, const Face& default_face) { rpc_call("draw_status", status_line, mode_line, default_face); } bool JsonUI::is_key_available() { return not m_pending_keys.empty(); } Key JsonUI::get_key() { kak_assert(not m_pending_keys.empty()); Key key = m_pending_keys.front(); m_pending_keys.erase(m_pending_keys.begin()); return key; } void JsonUI::menu_show(ConstArrayView<DisplayLine> items, CharCoord anchor, Face fg, Face bg, MenuStyle style) { rpc_call("menu_show", items, anchor, fg, bg, style); } void JsonUI::menu_select(int selected) { rpc_call("menu_show", selected); } void JsonUI::menu_hide() { rpc_call("menu_hide"); } void JsonUI::info_show(StringView title, StringView content, CharCoord anchor, Face face, InfoStyle style) { rpc_call("info_show", title, content, anchor, face, style); } void JsonUI::info_hide() { rpc_call("info_hide"); } void JsonUI::refresh(bool force) { rpc_call("refresh", force); } void JsonUI::set_input_callback(InputCallback callback) { m_input_callback = std::move(callback); } void JsonUI::set_ui_options(const Options& options) { // rpc_call("set_ui_options", options); } CharCoord JsonUI::dimensions() { return m_dimensions; } using JsonArray = Vector<Value>; using JsonObject = IdMap<Value>; static bool is_digit(char c) { return c >= '0' and c <= '9'; } std::tuple<Value, const char*> parse_json(const char* pos, const char* end) { using Result = std::tuple<Value, const char*>; if (not skip_while(pos, end, is_blank)) return {}; if (is_digit(*pos)) { auto digit_end = pos; skip_while(digit_end, end, is_digit); return Result{ Value{str_to_int({pos, digit_end})}, digit_end }; } if (end - pos > 4 and StringView{pos, pos+4} == "true") return Result{ Value{true}, pos+4 }; if (end - pos > 5 and StringView{pos, pos+5} == "false") return Result{ Value{false}, pos+5 }; if (*pos == '"') { String value; bool escaped = false; ++pos; for (auto string_end = pos; string_end != end; ++string_end) { if (escaped) { escaped = false; value += StringView{pos, string_end}; value.back() = *string_end; pos = string_end+1; continue; } if (*string_end == '\\') escaped = true; if (*string_end == '"') { value += StringView{pos, string_end}; return Result{std::move(value), string_end+1}; } } return {}; } if (*pos == '[') { JsonArray array; if (*++pos == ']') return Result{std::move(array), pos+1}; while (true) { Value element; std::tie(element, pos) = parse_json(pos, end); if (not element) return {}; array.push_back(std::move(element)); if (not skip_while(pos, end, is_blank)) return {}; if (*pos == ',') ++pos; else if (*pos == ']') return Result{std::move(array), pos+1}; else throw runtime_error("unable to parse array, expected ',' or ']'"); } } if (*pos == '{') { JsonObject object; if (*++pos == '}') return Result{std::move(object), pos+1}; while (true) { Value name_value; std::tie(name_value, pos) = parse_json(pos, end); if (not name_value) return {}; String& name = name_value.as<String>(); if (not skip_while(pos, end, is_blank)) return {}; if (*pos++ != ':') throw runtime_error("expected :"); Value element; std::tie(element, pos) = parse_json(pos, end); if (not element) return {}; object.append({ std::move(name), std::move(element) }); if (not skip_while(pos, end, is_blank)) return {}; if (*pos == ',') ++pos; else if (*pos == '}') return Result{std::move(object), pos+1}; else throw runtime_error("unable to parse object, expected ',' or '}'"); } } throw runtime_error("Could not parse json"); } std::tuple<Value, const char*> parse_json(StringView json) { return parse_json(json.begin(), json.end()); } void JsonUI::eval_json(const Value& json) { if (not json.is_a<JsonObject>()) throw runtime_error("json request is not an object"); const JsonObject& object = json.as<JsonObject>(); auto json_it = object.find("jsonrpc"); if (json_it == object.end() or json_it->value.as<String>() != "2.0") throw runtime_error("invalid json rpc request"); auto method_it = object.find("method"); if (method_it == object.end()) throw runtime_error("invalid json rpc request (method missing)"); StringView method = method_it->value.as<String>(); auto params_it = object.find("params"); if (params_it == object.end()) throw runtime_error("invalid json rpc request (params missing)"); const JsonArray& params = params_it->value.as<JsonArray>(); if (method == "keys") { for (auto& key_val : params) { for (auto& key : parse_keys(key_val.as<String>())) m_pending_keys.push_back(key); } } else if (method == "resize") { if (params.size() != 2) throw runtime_error("resize expects 2 parameters"); CharCoord dim{params[0].as<int>(), params[1].as<int>()}; m_dimensions = dim; m_pending_keys.push_back(resize(dim)); } else throw runtime_error("unknown method"); } static bool stdin_ready() { fd_set rfds; FD_ZERO(&rfds); FD_SET(0, &rfds); timeval tv; tv.tv_sec = 0; tv.tv_usec = 0; return select(1, &rfds, nullptr, nullptr, &tv) == 1; } void JsonUI::parse_requests(EventMode mode) { constexpr size_t bufsize = 1024; char buf[bufsize]; while (stdin_ready()) { ssize_t size = ::read(0, buf, bufsize); if (size == -1 or size == 0) break; m_requests += StringView{buf, buf + size}; } if (not m_requests.empty()) { const char* pos = nullptr; try { Value json; std::tie(json, pos) = parse_json(m_requests); if (json) eval_json(json); } catch (runtime_error& error) { write_stderr(format("error while handling requests '{}': '{}'", m_requests, error.what())); // try to salvage request by dropping its first line pos = std::min(m_requests.end(), find(m_requests, '\n')+1); } if (pos) m_requests = String{pos, m_requests.end()}; } while (m_input_callback and not m_pending_keys.empty()) m_input_callback(mode); } UnitTest test_json_parser{[]() { { auto value = std::get<0>(parse_json(R"({ "jsonrpc": "2.0", "method": "keys", "params": [ "b", "l", "a", "h" ] })")); kak_assert(value); } { auto value = std::get<0>(parse_json("[10,20]")); kak_assert(value and value.is_a<JsonArray>()); kak_assert(value.as<JsonArray>().at(1).as<int>() == 20); } { auto value = std::get<0>(parse_json("{}")); kak_assert(value and value.is_a<JsonObject>()); kak_assert(value.as<JsonObject>().empty()); } }}; }
Improve robustness of json parsing and execution
Improve robustness of json parsing and execution Fixes #720
C++
unlicense
occivink/kakoune,casimir/kakoune,mawww/kakoune,alexherbo2/kakoune,jjthrash/kakoune,Somasis/kakoune,jkonecny12/kakoune,alexherbo2/kakoune,jjthrash/kakoune,ekie/kakoune,danr/kakoune,mawww/kakoune,Somasis/kakoune,jkonecny12/kakoune,casimir/kakoune,flavius/kakoune,flavius/kakoune,danr/kakoune,danr/kakoune,mawww/kakoune,flavius/kakoune,alexherbo2/kakoune,ekie/kakoune,alexherbo2/kakoune,lenormf/kakoune,jkonecny12/kakoune,lenormf/kakoune,casimir/kakoune,Somasis/kakoune,occivink/kakoune,Somasis/kakoune,jjthrash/kakoune,jkonecny12/kakoune,danr/kakoune,jjthrash/kakoune,ekie/kakoune,lenormf/kakoune,ekie/kakoune,lenormf/kakoune,occivink/kakoune,casimir/kakoune,flavius/kakoune,mawww/kakoune,occivink/kakoune
d264263e414b7ae5be4cc1cbb4080d9048718ee6
libvast/test/system/archive.cpp
libvast/test/system/archive.cpp
/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #include "vast/concept/printable/stream.hpp" #include "vast/concept/printable/vast/event.hpp" #include "vast/system/archive.hpp" #include "vast/ids.hpp" #include "vast/detail/spawn_container_source.hpp" #define SUITE archive #include "test.hpp" #include "fixtures/actor_system_and_events.hpp" using namespace caf; using namespace vast; FIXTURE_SCOPE(archive_tests, fixtures::deterministic_actor_system_and_events) TEST(archiving and querying) { auto a = self->spawn(system::archive, directory, 10, 1024 * 1024); auto push_to_archive = [&](auto xs) { auto cs = vast::detail::spawn_container_source(sys, a, std::move(xs)); run_exhaustively(); }; MESSAGE("import bro conn logs to archive"); push_to_archive(bro_conn_log); MESSAGE("import DNS logs to archive"); push_to_archive(bro_dns_log); MESSAGE("import HTTP logs to archive"); push_to_archive(bro_http_log); MESSAGE("import BCP dump logs to archive"); push_to_archive(bgpdump_txt); MESSAGE("query events"); auto ids = make_ids({{100, 150}, {10150, 10200}}); self->send(a, ids); run_exhaustively(); auto result_opt = fetch_result<std::vector<event>>(); REQUIRE(result_opt); auto& result = *result_opt; REQUIRE_EQUAL(result.size(), 100u); // We sort because the specific compression algorithm used at the archive // determines the order of results. std::sort(result.begin(), result.end()); // We processed the segments in reverse order of arrival (to maximize LRU hit // rate). Therefore, the result set contains first the events with higher // IDs [10150,10200) and then the ones with lower ID [100,150). CHECK_EQUAL(result[0].id(), 100u); CHECK_EQUAL(result[0].type().name(), "bro::conn"); CHECK_EQUAL(result[50].id(), 10150u); CHECK_EQUAL(result[50].type().name(), "bro::dns"); CHECK_EQUAL(result[result.size() - 1].id(), 10199u); self->send_exit(a, exit_reason::user_shutdown); } FIXTURE_SCOPE_END()
/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #include "vast/concept/printable/stream.hpp" #include "vast/concept/printable/vast/event.hpp" #include "vast/system/archive.hpp" #include "vast/ids.hpp" #include "vast/detail/spawn_container_source.hpp" #define SUITE archive #include "test.hpp" #include "fixtures/actor_system_and_events.hpp" using namespace caf; using namespace vast; FIXTURE_SCOPE(archive_tests, fixtures::deterministic_actor_system_and_events) TEST(archiving and querying) { auto a = self->spawn(system::archive, directory, 10, 1024 * 1024); auto push_to_archive = [&](auto xs) { auto cs = vast::detail::spawn_container_source(sys, a, std::move(xs)); run_exhaustively(); }; MESSAGE("import bro conn logs to archive"); push_to_archive(bro_conn_log); MESSAGE("import DNS logs to archive"); push_to_archive(bro_dns_log); MESSAGE("import HTTP logs to archive"); push_to_archive(bro_http_log); MESSAGE("import BCP dump logs to archive"); push_to_archive(bgpdump_txt); MESSAGE("query events"); auto ids = make_ids({{100, 150}, {10150, 10200}}); auto result = request<std::vector<event>>(a, ids); REQUIRE_EQUAL(result.size(), 100u); // We sort because the specific compression algorithm used at the archive // determines the order of results. std::sort(result.begin(), result.end()); // We processed the segments in reverse order of arrival (to maximize LRU hit // rate). Therefore, the result set contains first the events with higher // IDs [10150,10200) and then the ones with lower ID [100,150). CHECK_EQUAL(result[0].id(), 100u); CHECK_EQUAL(result[0].type().name(), "bro::conn"); CHECK_EQUAL(result[50].id(), 10150u); CHECK_EQUAL(result[50].type().name(), "bro::dns"); CHECK_EQUAL(result[result.size() - 1].id(), 10199u); self->send_exit(a, exit_reason::user_shutdown); } FIXTURE_SCOPE_END()
Use new CAF fixture magic for simplification
Use new CAF fixture magic for simplification
C++
bsd-3-clause
mavam/vast,vast-io/vast,vast-io/vast,mavam/vast,vast-io/vast,vast-io/vast,vast-io/vast,mavam/vast,mavam/vast
25530989b0f2f9ca857530830dcab8257d885177
gridpath/scenario.cc
gridpath/scenario.cc
#include "scenario.hpp" #include "../utils/utils.hpp" #include "../search/main.hpp" #include <iostream> #include <cmath> static const float Epsilon = 0.001; Scenario::Scenario(int ac, char *av[]) : argc(ac), argv(av), maproot("./"), lastmap(NULL), entry(-1), nentries(0) { for (int i = 0; i < argc; i++) { if (strcmp(argv[i], "-maproot") == 0 && i < argc - 1) { maproot = argv[i+1]; i++; } else if (strcmp(argv[i], "-entry") == 0 && i < argc - 1) { entry = strtol(argv[i+1], NULL, 10); i++; } } if (maproot[maproot.size()-1] != '/') maproot += '/'; } Scenario::~Scenario(void) { if (lastmap) delete lastmap; } void Scenario::run(std::istream &in) { checkver(in); outputhdr(stdout); Search<GridPath> *srch = getsearch<GridPath>(argc, argv); ScenarioEntry ent(*this); while (in >> ent) { nentries++; if (entry >= 0 && nentries - 1 != entry) continue; Result<GridPath> r = ent.run(srch); ent.outputrow(stdout, nentries-1, r); res.add(r); srch->reset(); } res.output(stdout); dfpair(stdout, "number of entries", "%u", nentries); } void Scenario::checkver(std::istream &in) { float ver; std::string verstr; std::cin >> verstr >> ver; if (verstr != "version") fatal("Expected a version header"); if (ver != 1.0) fatal("Version %g is unsupported. Latest supported version is 1.0", ver); } void Scenario::outputhdr(FILE *out) { dfrowhdr(out, "run", 15, "num", "bucket", "width", "height", "start x", "start y", "finish x", "finish y", "optimal sol", "nodes expanded", "nodes generated", "sol cost", "sol length", "wall time", "cpu time"); } GridMap *Scenario::getmap(std::string mapfile) { std::string path = maproot + mapfile; if (!lastmap || lastmap->filename() != path) { if (lastmap) delete lastmap; lastmap = new GridMap(path); } return lastmap; } ScenarioEntry::ScenarioEntry(Scenario &s) : scen(s) { } Result<GridPath> ScenarioEntry::run(Search<GridPath> *srch) { GridPath d(scen.getmap(mapfile), x0, y0, x1, y1); GridPath::State s0 = d.initialstate(); Result<GridPath> &r = srch->search(d, s0); if (fabsf(r.cost - opt) > Epsilon) fatal("Expected optimal cost of %g, got %g\n", opt, r.cost); return r; } void ScenarioEntry::outputrow(FILE *out, unsigned int n, Result<GridPath> &r) { dfrow(out, "run", "uuuuuuuuguugugg", (unsigned long) n, (unsigned long) bucket, (unsigned long) w, (unsigned long) h, (unsigned long) x0, (unsigned long) y0, (unsigned long) x1, (unsigned long) y1, opt, r.expd, r.gend, r.cost, (unsigned long) r.path.size(), r.wallend - r.wallstrt, r.cpuend - r.cpustrt); } std::istream &operator>>(std::istream &in, ScenarioEntry &s) { in >> s.bucket; in >> s.mapfile; in >> s.w >> s.h; in >> s.x0 >> s.y0; in >> s.x1 >> s.y1; in >> s.opt; return in; }
#include "scenario.hpp" #include "../utils/utils.hpp" #include "../search/main.hpp" #include <iostream> #include <cmath> static const float Epsilon = 0.001; Scenario::Scenario(int ac, char *av[]) : argc(ac), argv(av), maproot("./"), lastmap(NULL), entry(-1), nentries(0) { for (int i = 0; i < argc; i++) { if (strcmp(argv[i], "-maproot") == 0 && i < argc - 1) { maproot = argv[i+1]; i++; } else if (strcmp(argv[i], "-entry") == 0 && i < argc - 1) { entry = strtol(argv[i+1], NULL, 10); i++; } } if (maproot[maproot.size()-1] != '/') maproot += '/'; } Scenario::~Scenario(void) { if (lastmap) delete lastmap; } void Scenario::run(std::istream &in) { checkver(in); outputhdr(stdout); Search<GridPath> *srch = getsearch<GridPath>(argc, argv); ScenarioEntry ent(*this); while (in >> ent) { nentries++; if (entry >= 0 && nentries - 1 != entry) continue; Result<GridPath> r = ent.run(srch); ent.outputrow(stdout, nentries-1, r); res.add(r); srch->reset(); } res.output(stdout); dfpair(stdout, "number of entries", "%u", nentries); } void Scenario::checkver(std::istream &in) { float ver; std::string verstr; std::cin >> verstr >> ver; if (verstr != "version") fatal("Expected a version header"); if (ver != 1.0) fatal("Version %g is unsupported. Latest supported version is 1.0", ver); } void Scenario::outputhdr(FILE *out) { dfrowhdr(out, "run", 15, "num", "bucket", "width", "height", "start x", "start y", "finish x", "finish y", "optimal sol", "nodes expanded", "nodes generated", "sol cost", "sol length", "wall time", "cpu time"); } GridMap *Scenario::getmap(std::string mapfile) { std::string path = maproot + mapfile; if (!lastmap || lastmap->filename() != path) { if (lastmap) delete lastmap; lastmap = new GridMap(path); } return lastmap; } ScenarioEntry::ScenarioEntry(Scenario &s) : scen(s) { } Result<GridPath> ScenarioEntry::run(Search<GridPath> *srch) { GridPath d(scen.getmap(mapfile), x0, y0, x1, y1); GridPath::State s0 = d.initialstate(); Result<GridPath> &r = srch->search(d, s0); // Scenario file has 0-cost for no-path. We use -1. if (fabsf(r.cost - opt) > Epsilon && !(opt == 0 && r.cost == -1)) fatal("Expected optimal cost of %g, got %g\n", opt, r.cost); return r; } void ScenarioEntry::outputrow(FILE *out, unsigned int n, Result<GridPath> &r) { dfrow(out, "run", "uuuuuuuuguugugg", (unsigned long) n, (unsigned long) bucket, (unsigned long) w, (unsigned long) h, (unsigned long) x0, (unsigned long) y0, (unsigned long) x1, (unsigned long) y1, opt, r.expd, r.gend, r.cost, (unsigned long) r.path.size(), r.wallend - r.wallstrt, r.cpuend - r.cpustrt); } std::istream &operator>>(std::istream &in, ScenarioEntry &s) { in >> s.bucket; in >> s.mapfile; in >> s.w >> s.h; in >> s.x0 >> s.y0; in >> s.x1 >> s.y1; in >> s.opt; return in; }
Handle no-solution scenario entries.
Handle no-solution scenario entries.
C++
mit
skiesel/search,skiesel/search,eaburns/search,eaburns/search,skiesel/search,eaburns/search
4081fc39fe99f6867407e04aa1c42400c4c04b74
stan/math/prim/mat/fun/divide_columns.hpp
stan/math/prim/mat/fun/divide_columns.hpp
#ifndef STAN_MATH_PRIM_MAT_FUN_DIVIDE_COLUMNS_HPP #define STAN_MATH_PRIM_MAT_FUN_DIVIDE_COLUMNS_HPP #include <stan/math/prim/mat/fun/Eigen.hpp> #include <stan/math/prim/scal/fun/divide.hpp> #include <stan/math/prim/scal/meta/scalar_type.hpp> namespace stan { namespace math { /** * Takes Stan data type vector[n] x[D] and divides each * dimension by the specified scalar. * * * @tparam T_x type of elements contained in vector x, usually Eigen::Matrix * @tparam T_s type of element of scalar, usually double or var * @tparam R number of rows in the submatrix of x * @tparam C number of columns in the submatrix of x * * @param x std::vector of elements representing a matrix * @param scalar a scalar * */ template <typename T_x, typename T_s, int R, int C> inline typename std::vector<Eigen::Matrix<T_x, R, C>> divide_columns( const std::vector<Eigen::Matrix<T_x, R, C>> &x, const T_s &scalar) { size_t N = x.size(); std::vector<Eigen::Matrix<T_x, R, C>> out(N); for (size_t n = 0; n < N; ++n) { out[n] = divide(x[n], scalar); } return out; } /** * Takes Stan data type vector[n] x[D] and divides each * dimension sequentially by each element of the vector * * @tparam T_x type of elements contained in vector x, usually Eigen::Matrix * @tparam T_v vector of elements * @tparam R number of rows in the submatrix of x * @tparam C number of columns in the submatrix of x * * @param x std::vector of elements representing a matrix * @param vec a vector type of elements * @throw std::invalid argument if D != length of vector * */ template <typename T_x, typename T_v, int R, int C> inline typename std::vector<Eigen::Matrix<T_x, R, C>> divide_columns( const std::vector<Eigen::Matrix<T_x, R, C>> &x, const std::vector<T_v> &vec) { size_t N = x.size(); size_t D = x[0].size(); check_size_match("divide_columns", "x dimension", D, "vector", vec.size()); std::vector<Eigen::Matrix<T_x, R, C>> out(N); for (size_t n = 0; n < N; ++n) { for (size_t d = 0; d < D; ++d) { out[n].resize(D); out[n][d] = divide(x[n][d], vec[d]); } } return out; } } // namespace math } // namespace stan #endif
#ifndef STAN_MATH_PRIM_MAT_FUN_DIVIDE_COLUMNS_HPP #define STAN_MATH_PRIM_MAT_FUN_DIVIDE_COLUMNS_HPP #include <stan/math/prim/mat/fun/Eigen.hpp> #include <stan/math/prim/scal/fun/divide.hpp> #include <stan/math/prim/scal/meta/scalar_type.hpp> #include <vector> namespace stan { namespace math { /** * Takes Stan data type vector[n] x[D] and divides each * dimension by the specified scalar. * * * @tparam T_x type of elements contained in vector x, usually Eigen::Matrix * @tparam T_s type of element of scalar, usually double or var * @tparam R number of rows in the submatrix of x * @tparam C number of columns in the submatrix of x * * @param x std::vector of elements representing a matrix * @param scalar a scalar * */ template <typename T_x, typename T_s, int R, int C> inline typename std::vector<Eigen::Matrix<T_x, R, C>> divide_columns( const std::vector<Eigen::Matrix<T_x, R, C>> &x, const T_s &scalar) { size_t N = x.size(); std::vector<Eigen::Matrix<T_x, R, C>> out(N); for (size_t n = 0; n < N; ++n) { out[n] = divide(x[n], scalar); } return out; } /** * Takes Stan data type vector[n] x[D] and divides each * dimension sequentially by each element of the vector * * @tparam T_x type of elements contained in vector x, usually Eigen::Matrix * @tparam T_v vector of elements * @tparam R number of rows in the submatrix of x * @tparam C number of columns in the submatrix of x * * @param x std::vector of elements representing a matrix * @param vec a vector type of elements * @throw std::invalid argument if D != length of vector * */ template <typename T_x, typename T_v, int R, int C> inline typename std::vector<Eigen::Matrix<T_x, R, C>> divide_columns( const std::vector<Eigen::Matrix<T_x, R, C>> &x, const std::vector<T_v> &vec) { size_t N = x.size(); size_t D = x[0].size(); check_size_match("divide_columns", "x dimension", D, "vector", vec.size()); std::vector<Eigen::Matrix<T_x, R, C>> out(N); for (size_t n = 0; n < N; ++n) { for (size_t d = 0; d < D; ++d) { out[n].resize(D); out[n][d] = divide(x[n][d], vec[d]); } } return out; } } // namespace math } // namespace stan #endif
Update divide_columns.hpp
Update divide_columns.hpp
C++
bsd-3-clause
stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math
4532594afbce5fa9cd29c9fbb663a5b112188fec
stan/math/prim/prob/hmm_marginal_lpdf.hpp
stan/math/prim/prob/hmm_marginal_lpdf.hpp
#ifndef STAN_MATH_REV_FUN_HMM_MARGINAL_LPDF_HPP #define STAN_MATH_REV_FUN_HMM_MARGINAL_LPDF_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/prim/err.hpp> #include <stan/math/prim/fun/row.hpp> #include <stan/math/prim/fun/col.hpp> #include <stan/math/prim/fun/transpose.hpp> #include <stan/math/prim/fun/exp.hpp> #include <stan/math/prim/fun/value_of.hpp> #include <stan/math/prim/core.hpp> #include <vector> namespace stan { namespace math { template <typename T_omega, typename T_Gamma, typename T_rho, typename T_alpha> inline auto hmm_marginal_lpdf_val( const Eigen::Matrix<T_omega, Eigen::Dynamic, Eigen::Dynamic>& omegas, const Eigen::Matrix<T_Gamma, Eigen::Dynamic, Eigen::Dynamic>& Gamma_val, const Eigen::Matrix<T_rho, Eigen::Dynamic, 1>& rho_val, Eigen::Matrix<T_alpha, Eigen::Dynamic, Eigen::Dynamic>& alphas, Eigen::Matrix<T_alpha, Eigen::Dynamic, 1>& alpha_log_norms) { const int n_states = omegas.rows(); const int n_transitions = omegas.cols() - 1; alphas.col(0) = omegas.col(0).cwiseProduct(rho_val); const auto norm = alphas.col(0).maxCoeff(); alphas.col(0) /= norm; alpha_log_norms(0) = log(norm); for (int n = 1; n <= n_transitions; ++n) { alphas.col(n) = omegas.col(n).cwiseProduct(Gamma_val.transpose() * alphas.col(n - 1)); const auto col_norm = alphas.col(n).maxCoeff(); alphas.col(n) /= col_norm; alpha_log_norms(n) = log(col_norm) + alpha_log_norms(n - 1); } return log(alphas.col(n_transitions).sum()) + alpha_log_norms(n_transitions); } /** * For a Hidden Markov Model with observation y, hidden state x, * and parameters theta, return the log marginal density, log * p(y | theta). In this setting, the hidden states are discrete * and take values over the finite space {1, ..., K}. * The marginal lpdf is obtained via a forward pass, and * the derivative is calculated with an adjoint method, * e.g (Betancourt, Margossian, & Leos-Barajas, 2020). * log_omegas is a matrix of observational densities, where * the (i, j)th entry corresponds to the density of the ith observation, y_i, * given x_i = j. * The transition matrix Gamma is such that the (i, j)th entry is the * probability that x_n = j given x_{n - 1} = i. The rows of Gamma are * simplexes. * The Gamma argument is only checked if there is at least one transition. * * @tparam T_omega type of the log likelihood matrix * @tparam T_Gamma type of the transition matrix * @tparam T_rho type of the initial guess vector * @param[in] log_omegas log matrix of observational densities. * @param[in] Gamma transition density between hidden states. * @param[in] rho initial state * @return log marginal density. * @throw `std::invalid_argument` if Gamma is not square, when we have * at least one transition, or if the size of rho is not the * number of rows of log_omegas. * @throw `std::domain_error` if rho is not a simplex and of the rows * of Gamma are not a simplex (when there is at least one transition). */ template <typename T_omega, typename T_Gamma, typename T_rho> inline auto hmm_marginal_lpdf( const Eigen::Matrix<T_omega, Eigen::Dynamic, Eigen::Dynamic>& log_omegas, const Eigen::Matrix<T_Gamma, Eigen::Dynamic, Eigen::Dynamic>& Gamma, const Eigen::Matrix<T_rho, Eigen::Dynamic, 1>& rho) { using T_partial_type = partials_return_t<T_omega, T_Gamma, T_rho>; using eig_matrix_partial = Eigen::Matrix<T_partial_type, Eigen::Dynamic, Eigen::Dynamic>; using eig_vector_partial = Eigen::Matrix<T_partial_type, Eigen::Dynamic, 1>; int n_states = log_omegas.rows(); int n_transitions = log_omegas.cols() - 1; check_consistent_size("hmm_marginal_lpdf", "rho", rho, n_states); check_simplex("hmm_marginal_lpdf", "rho", rho); if (n_transitions != 0) { check_square("hmm_marginal_lpdf", "Gamma", Gamma); check_nonzero_size("hmm_marginal_lpdf", "Gamma", Gamma); check_multiplicable("hmm_marginal_lpdf", "Gamma", Gamma, "log_omegas", log_omegas); for (int i = 0; i < Gamma.rows(); ++i) { check_simplex("hmm_marginal_lpdf", "Gamma[i, ]", row(Gamma, i + 1)); } } operands_and_partials<Eigen::Matrix<T_omega, Eigen::Dynamic, Eigen::Dynamic>, Eigen::Matrix<T_Gamma, Eigen::Dynamic, Eigen::Dynamic>, Eigen::Matrix<T_rho, Eigen::Dynamic, 1> > ops_partials(log_omegas, Gamma, rho); eig_matrix_partial alphas(n_states, n_transitions + 1); eig_vector_partial alpha_log_norms(n_transitions + 1); auto Gamma_val = value_of(Gamma); // compute the density using the forward algorithm. auto rho_val = value_of(rho); eig_matrix_partial omegas = value_of(log_omegas).array().exp(); auto log_marginal_density = hmm_marginal_lpdf_val(omegas, Gamma_val, rho_val, alphas, alpha_log_norms); // Variables required for all three Jacobian-adjoint products. auto norm_norm = alpha_log_norms(n_transitions); auto unnormed_marginal = alphas.col(n_transitions).sum(); std::vector<eig_vector_partial> kappa(n_transitions); eig_vector_partial kappa_log_norms(n_transitions); std::vector<T_partial_type> grad_corr(n_transitions, 0); if (n_transitions > 0) { kappa[n_transitions - 1] = Eigen::VectorXd::Ones(n_states); kappa_log_norms(n_transitions - 1) = 0; grad_corr[n_transitions - 1] = exp(alpha_log_norms(n_transitions - 1) - norm_norm); } for (int n = n_transitions - 1; n-- > 0;) { kappa[n] = Gamma_val * (omegas.col(n + 2).cwiseProduct(kappa[n + 1])); auto norm = kappa[n].maxCoeff(); kappa[n] /= norm; kappa_log_norms[n] = log(norm) + kappa_log_norms[n + 1]; grad_corr[n] = exp(alpha_log_norms[n] + kappa_log_norms[n] - norm_norm); } if (!is_constant_all<T_Gamma>::value) { eig_matrix_partial Gamma_jacad = Eigen::MatrixXd::Zero(n_states, n_states); for (int n = n_transitions - 1; n >= 0; --n) { Gamma_jacad += grad_corr[n] * alphas.col(n) * kappa[n].cwiseProduct(omegas.col(n + 1)).transpose() / unnormed_marginal; } ops_partials.edge2_.partials_ = Gamma_jacad; } if (!is_constant_all<T_omega, T_rho>::value) { eig_matrix_partial log_omega_jacad = Eigen::MatrixXd::Zero(n_states, n_transitions + 1); if (!is_constant_all<T_omega>::value) { // auto Gamma_alpha = Gamma_val.transpose() * alphas; for (int n = n_transitions - 1; n >= 0; --n) log_omega_jacad.col(n + 1) = grad_corr[n] // * kappa[n].cwiseProduct(Gamma_alpha.col(n)).eval(); // * kappa[n].cwiseProduct(Gamma_alpha.col(n)); * kappa[n].cwiseProduct(Gamma_val.transpose() * alphas.col(n)); } // Boundary terms if (n_transitions == 0) { if (!is_constant_all<T_omega>::value) { log_omega_jacad = omegas.cwiseProduct(value_of(rho)) / exp(log_marginal_density); ops_partials.edge1_.partials_ = log_omega_jacad; } if (!is_constant_all<T_rho>::value) { ops_partials.edge3_.partials_ = omegas.col(0) / exp(log_marginal_density); } return ops_partials.build(log_marginal_density); } else { auto grad_corr_boundary = exp(kappa_log_norms(0) - norm_norm); eig_vector_partial C = Gamma_val * omegas.col(1).cwiseProduct(kappa[0]); if (!is_constant_all<T_omega>::value) { log_omega_jacad.col(0) = grad_corr_boundary * C.cwiseProduct(value_of(rho)); ops_partials.edge1_.partials_ = log_omega_jacad.cwiseProduct(omegas / unnormed_marginal); } if (!is_constant_all<T_rho>::value) { ops_partials.edge3_.partials_ = grad_corr_boundary * C.cwiseProduct(omegas.col(0)) / unnormed_marginal; } } } return ops_partials.build(log_marginal_density); } } // namespace math } // namespace stan #endif
#ifndef STAN_MATH_REV_FUN_HMM_MARGINAL_LPDF_HPP #define STAN_MATH_REV_FUN_HMM_MARGINAL_LPDF_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/prim/err.hpp> #include <stan/math/prim/fun/row.hpp> #include <stan/math/prim/fun/col.hpp> #include <stan/math/prim/fun/transpose.hpp> #include <stan/math/prim/fun/exp.hpp> #include <stan/math/prim/fun/value_of.hpp> #include <stan/math/prim/core.hpp> #include <vector> namespace stan { namespace math { template <typename T_omega, typename T_Gamma, typename T_rho, typename T_alpha> inline auto hmm_marginal_lpdf_val( const Eigen::Matrix<T_omega, Eigen::Dynamic, Eigen::Dynamic>& omegas, const Eigen::Matrix<T_Gamma, Eigen::Dynamic, Eigen::Dynamic>& Gamma_val, const Eigen::Matrix<T_rho, Eigen::Dynamic, 1>& rho_val, Eigen::Matrix<T_alpha, Eigen::Dynamic, Eigen::Dynamic>& alphas, Eigen::Matrix<T_alpha, Eigen::Dynamic, 1>& alpha_log_norms, T_alpha& norm_norm) { const int n_states = omegas.rows(); const int n_transitions = omegas.cols() - 1; alphas.col(0) = omegas.col(0).cwiseProduct(rho_val); const auto norm = alphas.col(0).maxCoeff(); alphas.col(0) /= norm; alpha_log_norms(0) = log(norm); auto Gamma_val_transpose = Gamma_val.transpose().eval(); for (int n = 1; n <= n_transitions; ++n) { alphas.col(n) = omegas.col(n).cwiseProduct(Gamma_val_transpose * alphas.col(n - 1)); const auto col_norm = alphas.col(n).maxCoeff(); alphas.col(n) /= col_norm; alpha_log_norms(n) = log(col_norm) + alpha_log_norms(n - 1); } norm_norm = alpha_log_norms(n_transitions); return log(alphas.col(n_transitions).sum()) + norm_norm; } /** * For a Hidden Markov Model with observation y, hidden state x, * and parameters theta, return the log marginal density, log * p(y | theta). In this setting, the hidden states are discrete * and take values over the finite space {1, ..., K}. * The marginal lpdf is obtained via a forward pass, and * the derivative is calculated with an adjoint method, * e.g (Betancourt, Margossian, & Leos-Barajas, 2020). * log_omegas is a matrix of observational densities, where * the (i, j)th entry corresponds to the density of the ith observation, y_i, * given x_i = j. * The transition matrix Gamma is such that the (i, j)th entry is the * probability that x_n = j given x_{n - 1} = i. The rows of Gamma are * simplexes. * The Gamma argument is only checked if there is at least one transition. * * @tparam T_omega type of the log likelihood matrix * @tparam T_Gamma type of the transition matrix * @tparam T_rho type of the initial guess vector * @param[in] log_omegas log matrix of observational densities. * @param[in] Gamma transition density between hidden states. * @param[in] rho initial state * @return log marginal density. * @throw `std::invalid_argument` if Gamma is not square, when we have * at least one transition, or if the size of rho is not the * number of rows of log_omegas. * @throw `std::domain_error` if rho is not a simplex and of the rows * of Gamma are not a simplex (when there is at least one transition). */ template <typename T_omega, typename T_Gamma, typename T_rho> inline auto hmm_marginal_lpdf( const Eigen::Matrix<T_omega, Eigen::Dynamic, Eigen::Dynamic>& log_omegas, const Eigen::Matrix<T_Gamma, Eigen::Dynamic, Eigen::Dynamic>& Gamma, const Eigen::Matrix<T_rho, Eigen::Dynamic, 1>& rho) { using T_partial_type = partials_return_t<T_omega, T_Gamma, T_rho>; using eig_matrix_partial = Eigen::Matrix<T_partial_type, Eigen::Dynamic, Eigen::Dynamic>; using eig_vector_partial = Eigen::Matrix<T_partial_type, Eigen::Dynamic, 1>; int n_states = log_omegas.rows(); int n_transitions = log_omegas.cols() - 1; check_consistent_size("hmm_marginal_lpdf", "rho", rho, n_states); check_simplex("hmm_marginal_lpdf", "rho", rho); if (n_transitions != 0) { check_square("hmm_marginal_lpdf", "Gamma", Gamma); check_nonzero_size("hmm_marginal_lpdf", "Gamma", Gamma); check_multiplicable("hmm_marginal_lpdf", "Gamma", Gamma, "log_omegas", log_omegas); for (int i = 0; i < Gamma.rows(); ++i) { check_simplex("hmm_marginal_lpdf", "Gamma[i, ]", row(Gamma, i + 1)); } } operands_and_partials<Eigen::Matrix<T_omega, Eigen::Dynamic, Eigen::Dynamic>, Eigen::Matrix<T_Gamma, Eigen::Dynamic, Eigen::Dynamic>, Eigen::Matrix<T_rho, Eigen::Dynamic, 1> > ops_partials(log_omegas, Gamma, rho); eig_matrix_partial alphas(n_states, n_transitions + 1); eig_vector_partial alpha_log_norms(n_transitions + 1); auto Gamma_val = value_of(Gamma); // compute the density using the forward algorithm. auto rho_val = value_of(rho); eig_matrix_partial omegas = value_of(log_omegas).array().exp(); T_partial_type norm_norm; auto log_marginal_density = hmm_marginal_lpdf_val(omegas, Gamma_val, rho_val, alphas, alpha_log_norms, norm_norm); // Variables required for all three Jacobian-adjoint products. auto unnormed_marginal = alphas.col(n_transitions).sum(); std::vector<eig_vector_partial> kappa(n_transitions); eig_vector_partial kappa_log_norms(n_transitions); std::vector<T_partial_type> grad_corr(n_transitions, 0); if (n_transitions > 0) { kappa[n_transitions - 1] = Eigen::VectorXd::Ones(n_states); kappa_log_norms(n_transitions - 1) = 0; grad_corr[n_transitions - 1] = exp(alpha_log_norms(n_transitions - 1) - norm_norm); } for (int n = n_transitions - 1; n-- > 0;) { kappa[n] = Gamma_val * (omegas.col(n + 2).cwiseProduct(kappa[n + 1])); auto norm = kappa[n].maxCoeff(); kappa[n] /= norm; kappa_log_norms[n] = log(norm) + kappa_log_norms[n + 1]; grad_corr[n] = exp(alpha_log_norms[n] + kappa_log_norms[n] - norm_norm); } if (!is_constant_all<T_Gamma>::value) { eig_matrix_partial Gamma_jacad = Eigen::MatrixXd::Zero(n_states, n_states); for (int n = n_transitions - 1; n >= 0; --n) { Gamma_jacad += grad_corr[n] * alphas.col(n) * kappa[n].cwiseProduct(omegas.col(n + 1)).transpose() / unnormed_marginal; } ops_partials.edge2_.partials_ = Gamma_jacad; } if (!is_constant_all<T_omega, T_rho>::value) { eig_matrix_partial log_omega_jacad = Eigen::MatrixXd::Zero(n_states, n_transitions + 1); if (!is_constant_all<T_omega>::value) { for (int n = n_transitions - 1; n >= 0; --n) log_omega_jacad.col(n + 1) = grad_corr[n] * kappa[n].cwiseProduct(Gamma_val.transpose() * alphas.col(n)); } // Boundary terms if (n_transitions == 0) { if (!is_constant_all<T_omega>::value) { log_omega_jacad = omegas.cwiseProduct(value_of(rho)) / exp(log_marginal_density); ops_partials.edge1_.partials_ = log_omega_jacad; } if (!is_constant_all<T_rho>::value) { ops_partials.edge3_.partials_ = omegas.col(0) / exp(log_marginal_density); } return ops_partials.build(log_marginal_density); } else { auto grad_corr_boundary = exp(kappa_log_norms(0) - norm_norm); eig_vector_partial C = Gamma_val * omegas.col(1).cwiseProduct(kappa[0]); if (!is_constant_all<T_omega>::value) { log_omega_jacad.col(0) = grad_corr_boundary * C.cwiseProduct(value_of(rho)); ops_partials.edge1_.partials_ = log_omega_jacad.cwiseProduct(omegas / unnormed_marginal); } if (!is_constant_all<T_rho>::value) { ops_partials.edge3_.partials_ = grad_corr_boundary * C.cwiseProduct(omegas.col(0)) / unnormed_marginal; } } } return ops_partials.build(log_marginal_density); } } // namespace math } // namespace stan #endif
move norm_norm
move norm_norm
C++
bsd-3-clause
stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math
6ab326a8f0c95b6427d900ca4a076abcd01eda0c
src/laszip.hpp
src/laszip.hpp
/* =============================================================================== FILE: laszip.hpp CONTENTS: Contains LASitem and LASchunk structs as well as the IDs of the currently supported entropy coding scheme PROGRAMMERS: [email protected] - http://rapidlasso.com COPYRIGHT: (c) 2007-2019, martin isenburg, rapidlasso - fast tools to catch reality This is free software; you can redistribute and/or modify it under the terms of the GNU Lesser General Licence as published by the Free Software Foundation. See the COPYING file for more information. This software is distributed WITHOUT ANY WARRANTY and without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. CHANGE HISTORY: 20 March 2019 -- upped to 3.3 r1 for consistent legacy and extended class check 21 February 2019 -- bug fix when writing 4294967295+ points uncompressed to LAS 28 December 2018 -- fix for v4 decompression of WavePacket part of PRDF 9 and 10 27 December 2018 -- upped to 3.2 r9 for bug fix in multi-channel NIR decompression 7 November 2018 -- upped to 3.2 r8 for identical legacy and extended flags check 20 October 2018 -- upped to 3.2 r7 for rare bug in LASinterval::merge_intervals() 5 October 2018 -- upped to 3.2 r6 for corrected 'is_empty' return value 28 September 2018 -- upped to 3.2 r5 for fix in extended classification writing 9 February 2018 -- minor version increment as it can read v4 compressed items 28 December 2017 -- fix incorrect 'context switch' reported by Wanwannodao 23 August 2017 -- minor version increment for C++ stream-based read/write API 28 May 2017 -- support for "LAS 1.4 selective decompression" added into DLL API 8 April 2017 -- new check for whether point size and total size of items match 30 March 2017 -- support for "native LAS 1.4 extension" added into main branch 7 January 2017 -- set reserved VLR field from 0xAABB to 0x0 in DLL 7 January 2017 -- consistent compatibility mode scan angle quantization in DLL 7 January 2017 -- compatibility mode *decompression* fix for waveforms in DLL 25 February 2016 -- depreciating old libLAS laszipper/lasunzipper binding 29 July 2013 -- reorganized to create an easy-to-use LASzip DLL 5 December 2011 -- learns the chunk table if it is missing (e.g. truncated LAZ) 6 October 2011 -- large file support, ability to read with missing chunk table 23 June 2011 -- turned on LASzip version 2.0 compressor with chunking 8 May 2011 -- added an option for variable chunking via chunk() 23 April 2011 -- changed interface for simplicity and chunking support 20 March 2011 -- incrementing LASZIP_VERSION to 1.2 for improved compression 10 January 2011 -- licensing change for LGPL release and liblas integration 12 December 2010 -- refactored from lasdefinitions after movies with silke =============================================================================== */ #ifndef LASZIP_HPP #define LASZIP_HPP #if defined(_MSC_VER) && (_MSC_VER < 1300) #define LZ_WIN32_VC6 typedef __int64 SIGNED_INT64; #else typedef long long SIGNED_INT64; #endif #if defined(_MSC_VER) && \ (_MSC_FULL_VER >= 150000000) #define LASCopyString _strdup #else #define LASCopyString strdup #endif #define LASZIP_VERSION_MAJOR 3 #define LASZIP_VERSION_MINOR 4 #define LASZIP_VERSION_REVISION 1 #define LASZIP_VERSION_BUILD_DATE 190411 #define LASZIP_COMPRESSOR_NONE 0 #define LASZIP_COMPRESSOR_POINTWISE 1 #define LASZIP_COMPRESSOR_POINTWISE_CHUNKED 2 #define LASZIP_COMPRESSOR_LAYERED_CHUNKED 3 #define LASZIP_COMPRESSOR_TOTAL_NUMBER_OF 4 #define LASZIP_COMPRESSOR_CHUNKED LASZIP_COMPRESSOR_POINTWISE_CHUNKED #define LASZIP_COMPRESSOR_NOT_CHUNKED LASZIP_COMPRESSOR_POINTWISE #define LASZIP_COMPRESSOR_DEFAULT LASZIP_COMPRESSOR_CHUNKED #define LASZIP_CODER_ARITHMETIC 0 #define LASZIP_CODER_TOTAL_NUMBER_OF 1 #define LASZIP_CHUNK_SIZE_DEFAULT 50000 class LASitem { public: enum Type { BYTE = 0, SHORT, INT, LONG, FLOAT, DOUBLE, POINT10, GPSTIME11, RGB12, WAVEPACKET13, POINT14, RGB14, RGBNIR14, WAVEPACKET14, BYTE14 } type; unsigned short size; unsigned short version; bool is_type(LASitem::Type t) const; const char* get_name() const; }; class LASzip { public: // supported version control bool check_compressor(const unsigned short compressor); bool check_coder(const unsigned short coder); bool check_item(const LASitem* item); bool check_items(const unsigned short num_items, const LASitem* items, const unsigned short point_size=0); bool check(const unsigned short point_size=0); // go back and forth between item array and point type & size bool setup(unsigned short* num_items, LASitem** items, const unsigned char point_type, const unsigned short point_size, const unsigned short compressor=LASZIP_COMPRESSOR_NONE); bool is_standard(const unsigned short num_items, const LASitem* items, unsigned char* point_type=0, unsigned short* record_length=0); bool is_standard(unsigned char* point_type=0, unsigned short* record_length=0); // pack to and unpack from VLR unsigned char* bytes; bool unpack(const unsigned char* bytes, const int num); bool pack(unsigned char*& bytes, int& num); // setup bool request_compatibility_mode(const unsigned short requested_compatibility_mode=0); // 0 = none, 1 = LAS 1.4 compatibility mode bool setup(const unsigned char point_type, const unsigned short point_size, const unsigned short compressor=LASZIP_COMPRESSOR_DEFAULT); bool setup(const unsigned short num_items, const LASitem* items, const unsigned short compressor); bool set_chunk_size(const unsigned int chunk_size); /* for compressor only */ bool request_version(const unsigned short requested_version); /* for compressor only */ // in case a function returns false this string describes the problem const char* get_error() const; // stored in LASzip VLR data section unsigned short compressor; unsigned short coder; unsigned char version_major; unsigned char version_minor; unsigned short version_revision; unsigned int options; unsigned int chunk_size; SIGNED_INT64 number_of_special_evlrs; /* must be -1 if unused */ SIGNED_INT64 offset_to_special_evlrs; /* must be -1 if unused */ unsigned short num_items; LASitem* items; LASzip(); ~LASzip(); private: bool return_error(const char* err); char* error_string; }; #endif
/* =============================================================================== FILE: laszip.hpp CONTENTS: Contains LASitem and LASchunk structs as well as the IDs of the currently supported entropy coding scheme PROGRAMMERS: [email protected] - http://rapidlasso.com COPYRIGHT: (c) 2007-2019, martin isenburg, rapidlasso - fast tools to catch reality This is free software; you can redistribute and/or modify it under the terms of the GNU Lesser General Licence as published by the Free Software Foundation. See the COPYING file for more information. This software is distributed WITHOUT ANY WARRANTY and without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. CHANGE HISTORY: 20 March 2019 -- upped to 3.3 r1 for consistent legacy and extended class check 21 February 2019 -- bug fix when writing 4294967295+ points uncompressed to LAS 28 December 2018 -- fix for v4 decompression of WavePacket part of PRDF 9 and 10 27 December 2018 -- upped to 3.2 r9 for bug fix in multi-channel NIR decompression 7 November 2018 -- upped to 3.2 r8 for identical legacy and extended flags check 20 October 2018 -- upped to 3.2 r7 for rare bug in LASinterval::merge_intervals() 5 October 2018 -- upped to 3.2 r6 for corrected 'is_empty' return value 28 September 2018 -- upped to 3.2 r5 for fix in extended classification writing 9 February 2018 -- minor version increment as it can read v4 compressed items 28 December 2017 -- fix incorrect 'context switch' reported by Wanwannodao 23 August 2017 -- minor version increment for C++ stream-based read/write API 28 May 2017 -- support for "LAS 1.4 selective decompression" added into DLL API 8 April 2017 -- new check for whether point size and total size of items match 30 March 2017 -- support for "native LAS 1.4 extension" added into main branch 7 January 2017 -- set reserved VLR field from 0xAABB to 0x0 in DLL 7 January 2017 -- consistent compatibility mode scan angle quantization in DLL 7 January 2017 -- compatibility mode *decompression* fix for waveforms in DLL 25 February 2016 -- depreciating old libLAS laszipper/lasunzipper binding 29 July 2013 -- reorganized to create an easy-to-use LASzip DLL 5 December 2011 -- learns the chunk table if it is missing (e.g. truncated LAZ) 6 October 2011 -- large file support, ability to read with missing chunk table 23 June 2011 -- turned on LASzip version 2.0 compressor with chunking 8 May 2011 -- added an option for variable chunking via chunk() 23 April 2011 -- changed interface for simplicity and chunking support 20 March 2011 -- incrementing LASZIP_VERSION to 1.2 for improved compression 10 January 2011 -- licensing change for LGPL release and liblas integration 12 December 2010 -- refactored from lasdefinitions after movies with silke =============================================================================== */ #ifndef LASZIP_HPP #define LASZIP_HPP #include "mydefs.hpp" #if defined(_MSC_VER) && (_MSC_VER < 1300) #define LZ_WIN32_VC6 typedef __int64 SIGNED_INT64; #else typedef long long SIGNED_INT64; #endif #if defined(_MSC_VER) && (_MSC_FULL_VER >= 150000000) #define LASCopyString _strdup #else #define LASCopyString strdup #endif #if defined(_MSC_VER) #include <windows.h> wchar_t* UTF8toUTF16(const char* utf8); #endif #define LASZIP_VERSION_MAJOR 3 #define LASZIP_VERSION_MINOR 4 #define LASZIP_VERSION_REVISION 2 #define LASZIP_VERSION_BUILD_DATE 191015 #define LASZIP_COMPRESSOR_NONE 0 #define LASZIP_COMPRESSOR_POINTWISE 1 #define LASZIP_COMPRESSOR_POINTWISE_CHUNKED 2 #define LASZIP_COMPRESSOR_LAYERED_CHUNKED 3 #define LASZIP_COMPRESSOR_TOTAL_NUMBER_OF 4 #define LASZIP_COMPRESSOR_CHUNKED LASZIP_COMPRESSOR_POINTWISE_CHUNKED #define LASZIP_COMPRESSOR_NOT_CHUNKED LASZIP_COMPRESSOR_POINTWISE #define LASZIP_COMPRESSOR_DEFAULT LASZIP_COMPRESSOR_CHUNKED #define LASZIP_CODER_ARITHMETIC 0 #define LASZIP_CODER_TOTAL_NUMBER_OF 1 #define LASZIP_CHUNK_SIZE_DEFAULT 50000 class LASLIB_DLL LASitem { public: enum Type { BYTE = 0, SHORT, INT, LONG, FLOAT, DOUBLE, POINT10, GPSTIME11, RGB12, WAVEPACKET13, POINT14, RGB14, RGBNIR14, WAVEPACKET14, BYTE14 } type; unsigned short size; unsigned short version; bool is_type(LASitem::Type t) const; const char* get_name() const; }; class LASLIB_DLL LASzip { public: // supported version control bool check_compressor(const unsigned short compressor); bool check_coder(const unsigned short coder); bool check_item(const LASitem* item); bool check_items(const unsigned short num_items, const LASitem* items, const unsigned short point_size=0); bool check(const unsigned short point_size=0); // go back and forth between item array and point type & size bool setup(unsigned short* num_items, LASitem** items, const unsigned char point_type, const unsigned short point_size, const unsigned short compressor=LASZIP_COMPRESSOR_NONE); bool is_standard(const unsigned short num_items, const LASitem* items, unsigned char* point_type=0, unsigned short* record_length=0); bool is_standard(unsigned char* point_type=0, unsigned short* record_length=0); // pack to and unpack from VLR unsigned char* bytes; bool unpack(const unsigned char* bytes, const int num); bool pack(unsigned char*& bytes, int& num); // setup bool request_compatibility_mode(const unsigned short requested_compatibility_mode=0); // 0 = none, 1 = LAS 1.4 compatibility mode bool setup(const unsigned char point_type, const unsigned short point_size, const unsigned short compressor=LASZIP_COMPRESSOR_DEFAULT); bool setup(const unsigned short num_items, const LASitem* items, const unsigned short compressor); bool set_chunk_size(const unsigned int chunk_size); /* for compressor only */ bool request_version(const unsigned short requested_version); /* for compressor only */ // in case a function returns false this string describes the problem const char* get_error() const; // stored in LASzip VLR data section unsigned short compressor; unsigned short coder; unsigned char version_major; unsigned char version_minor; unsigned short version_revision; unsigned int options; unsigned int chunk_size; SIGNED_INT64 number_of_special_evlrs; /* must be -1 if unused */ SIGNED_INT64 offset_to_special_evlrs; /* must be -1 if unused */ unsigned short num_items; LASitem* items; LASzip(); ~LASzip(); private: bool return_error(const char* err); char* error_string; }; #endif
add unicode support for Windows
add unicode support for Windows
C++
unknown
hobu/LASzip,hobu/LASzip,hobu/LASzip,LASzip/LASzip,LASzip/LASzip,LASzip/LASzip
8ffbeb18cd3bcc61860e557ae7c681a4c67d9808
src/zerotime_manager.cpp
src/zerotime_manager.cpp
/* * Copyright (c) 2013-2015 John Connor (BM-NC49AxAjcqVcF5jNPu85Rb8MJ2d9JqZt) * * This file is part of vanillacoin. * * vanillacoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <coin/globals.hpp> #include <coin/stack_impl.hpp> #include <coin/zerotime.hpp> #include <coin/zerotime_manager.hpp> using namespace coin; zerotime_manager::zerotime_manager( boost::asio::io_service & ios, boost::asio::strand & s, stack_impl & owner ) : io_service_(ios) , strand_(s) , stack_impl_(owner) , timer_(ios) { // ... } void zerotime_manager::start() { /** * Start the timer. */ do_tick(60); } void zerotime_manager::stop() { timer_.cancel(); } void zerotime_manager::probe_for_answers( const sha256 & hash_tx, const std::vector<transaction_in> & transactions_in ) { if (globals::instance().is_zerotime_enabled()) { if (m_questions.count(hash_tx) == 0) { #warning :TODO: // Prepare: // :TODO: m_questions[hash_tx] = zerotime_question(transactions_in); // :TODO: 6 blocks = 20 mins = 1200 seconds // :TODO: m_qa_expire_times[hash_tx] = std::time(0) + (20 * 60); // Probe: // :TODO: auto addrs = stack_impl_.get_address_manager()->get_addr(8); // :TODO: m_questioned_tcp_endpoints[hash_tx].push_back(addrs[0]); // Listen: // :TODO: m_answers_tcp[ztanswer.hash_tx()].push_back(std::make_pair(ep, ztanswer)); } } } void zerotime_manager::do_tick(const std::uint32_t & interval) { auto self(shared_from_this()); timer_.expires_from_now(std::chrono::seconds(interval)); timer_.async_wait(strand_.wrap([this, self, interval] (boost::system::error_code ec) { if (ec) { // ... } else { if (globals::instance().is_zerotime_enabled()) { /** * Clear expired input locks. */ zerotime::instance().clear_expired_input_locks(); } /** * Start the timer. */ do_tick(60); } })); }
/* * Copyright (c) 2013-2015 John Connor (BM-NC49AxAjcqVcF5jNPu85Rb8MJ2d9JqZt) * * This file is part of vanillacoin. * * vanillacoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <coin/globals.hpp> #include <coin/stack_impl.hpp> #include <coin/zerotime.hpp> #include <coin/zerotime_manager.hpp> using namespace coin; zerotime_manager::zerotime_manager( boost::asio::io_service & ios, boost::asio::strand & s, stack_impl & owner ) : io_service_(ios) , strand_(s) , stack_impl_(owner) , timer_(ios) { // ... } void zerotime_manager::start() { /** * Start the timer. */ do_tick(60); } void zerotime_manager::stop() { timer_.cancel(); } void zerotime_manager::probe_for_answers( const sha256 & hash_tx, const std::vector<transaction_in> & transactions_in ) { if (globals::instance().is_zerotime_enabled()) { if (m_questions.count(hash_tx) == 0) { } } } void zerotime_manager::do_tick(const std::uint32_t & interval) { auto self(shared_from_this()); timer_.expires_from_now(std::chrono::seconds(interval)); timer_.async_wait(strand_.wrap([this, self, interval] (boost::system::error_code ec) { if (ec) { // ... } else { if (globals::instance().is_zerotime_enabled()) { /** * Clear expired input locks. */ zerotime::instance().clear_expired_input_locks(); } /** * Start the timer. */ do_tick(60); } })); }
remove warning
remove warning
C++
agpl-3.0
sum01/vcash,xCoreDev/vanillacoin,xCoreDev/vcash,fczuardi/vanillacoin,xCoreDev/vcash,openvcash/vcash,sum01/vcash,openvcash/vcash,xCoreDev/vanillacoin,fczuardi/vanillacoin
5ee9e448fce04de171cb07787887ed41088537bb
thrift/conformance/data/ValueGenerator.cpp
thrift/conformance/data/ValueGenerator.cpp
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <thrift/conformance/data/ValueGenerator.h> #include <cmath> #include <limits> namespace apache::thrift::conformance::data { namespace { template <typename Tag> void addStringValues(NamedValues<Tag>& values) { values.emplace_back("", "empty"); values.emplace_back("a", "lower"); values.emplace_back("A", "upper"); values.emplace_back(" a ", "spaces"); values.emplace_back(" a", "leading_space"); values.emplace_back("a ", "trailing_space"); values.emplace_back("Hello", "utf8"); if constexpr (type::base_type_v<Tag> == type::BaseType::Binary) { values.emplace_back("\x72\x01\xff", "bad_utf8"); } } template <typename Tag, bool key> void addNumberValues(NamedValues<Tag>& values) { using T = type::standard_type<Tag>; using numeric_limits = std::numeric_limits<T>; values.emplace_back(0, "zero"); // Extrema if (numeric_limits::lowest() != numeric_limits::min()) { values.emplace_back(numeric_limits::lowest(), "lowest"); } values.emplace_back(numeric_limits::min(), "min"); values.emplace_back(numeric_limits::max(), "max"); if constexpr (!numeric_limits::is_integer) { values.emplace_back(1UL << numeric_limits::digits, "max_int"); values.emplace_back(-values.back().value, "min_int"); values.emplace_back((1UL << numeric_limits::digits) - 1, "max_digits"); values.emplace_back(-values.back().value, "neg_max_digits"); } if constexpr (numeric_limits::has_infinity) { values.emplace_back(numeric_limits::infinity(), "inf"); values.emplace_back(-numeric_limits::infinity(), "neg_inf"); } // Minutiae values.emplace_back(1, "one"); if constexpr (numeric_limits::is_signed) { values.emplace_back(-1, "neg_one"); } if constexpr (numeric_limits::epsilon() != 0) { values.emplace_back(numeric_limits::epsilon(), "epsilon"); values.emplace_back(-numeric_limits::epsilon(), "neg_epsilon"); } if constexpr (numeric_limits::has_denorm == std::denorm_present) { values.emplace_back(numeric_limits::denorm_min(), "denorm_min"); values.emplace_back(-numeric_limits::denorm_min(), "neg_denorm_min"); } if constexpr (!key) { if constexpr (numeric_limits::has_quiet_NaN) { values.emplace_back(numeric_limits::quiet_NaN(), "NaN"); } if (auto nzero = -static_cast<T>(0); std::signbit(nzero)) { values.emplace_back(nzero, "neg_zero"); } } } template <typename Tag, bool key> NamedValues<Tag> generateValues() { static_assert(type::is_a_v<Tag, type::primitive_c>, ""); using T = type::standard_type<Tag>; NamedValues<Tag> values; if constexpr (type::is_a_v<Tag, type::bool_t>) { values.emplace_back(true, "true"); values.emplace_back(false, "false"); } else if constexpr (type::is_a_v<Tag, type::string_c>) { addStringValues<Tag>(values); } else if constexpr (type::is_a_v<Tag, type::number_c>) { addNumberValues<Tag, key>(values); } else { values.emplace_back(T(), "default"); } return values; } } // namespace template <typename Tag> auto ValueGenerator<Tag>::getInterestingValues() -> const Values& { static auto kValues = generateValues<Tag, false>(); return kValues; } template <typename Tag> auto ValueGenerator<Tag>::getKeyValues() -> const Values& { static auto kValues = generateValues<Tag, true>(); return kValues; } template struct ValueGenerator<type::bool_t>; template struct ValueGenerator<type::byte_t>; template struct ValueGenerator<type::i16_t>; template struct ValueGenerator<type::i32_t>; template struct ValueGenerator<type::i64_t>; template struct ValueGenerator<type::float_t>; template struct ValueGenerator<type::double_t>; template struct ValueGenerator<type::string_t>; template struct ValueGenerator<type::binary_t>; } // namespace apache::thrift::conformance::data
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <thrift/conformance/data/ValueGenerator.h> #include <cmath> #include <limits> namespace apache::thrift::conformance::data { namespace { template <typename Tag> void addStringValues(NamedValues<Tag>& values) { values.emplace_back("", "empty"); values.emplace_back("a", "lower"); values.emplace_back("A", "upper"); values.emplace_back(" a ", "spaces"); values.emplace_back(" a", "leading_space"); values.emplace_back("a ", "trailing_space"); values.emplace_back("Hello", "utf8"); if constexpr (type::base_type_v<Tag> == type::BaseType::Binary) { values.emplace_back("\x72\x01\xff", "bad_utf8"); } } template <typename Tag, bool key> void addNumberValues(NamedValues<Tag>& values) { using T = type::standard_type<Tag>; using numeric_limits = std::numeric_limits<T>; values.emplace_back(0, "zero"); // Extrema if (numeric_limits::lowest() != numeric_limits::min()) { values.emplace_back(numeric_limits::lowest(), "lowest"); } values.emplace_back(numeric_limits::min(), "min"); values.emplace_back(numeric_limits::max(), "max"); if constexpr (!numeric_limits::is_integer) { values.emplace_back(1UL << numeric_limits::digits, "max_int"); values.emplace_back(-values.back().value, "min_int"); values.emplace_back((1UL << numeric_limits::digits) - 1, "max_digits"); values.emplace_back(-values.back().value, "neg_max_digits"); values.emplace_back(0.1, "one_tenth"); values.emplace_back( std::nextafter(numeric_limits::min(), T(1)), "min_plus_ulp"); values.emplace_back( std::nextafter(numeric_limits::max(), T(1)), "max_minus_ulp"); } if constexpr (numeric_limits::has_infinity) { values.emplace_back(numeric_limits::infinity(), "inf"); values.emplace_back(-numeric_limits::infinity(), "neg_inf"); } // Minutiae values.emplace_back(1, "one"); if constexpr (numeric_limits::is_signed) { values.emplace_back(-1, "neg_one"); } if constexpr (numeric_limits::epsilon() != 0) { values.emplace_back(numeric_limits::epsilon(), "epsilon"); values.emplace_back(-numeric_limits::epsilon(), "neg_epsilon"); } if constexpr (numeric_limits::has_denorm == std::denorm_present) { values.emplace_back(numeric_limits::denorm_min(), "denorm_min"); values.emplace_back(-numeric_limits::denorm_min(), "neg_denorm_min"); } if constexpr (std::is_same_v<T, double>) { values.emplace_back(1.9156918820264798e-56, "fmt_case_1"); values.emplace_back(3788512123356.9854, "fmt_case_2"); } if constexpr (!key) { if constexpr (numeric_limits::has_quiet_NaN) { values.emplace_back(numeric_limits::quiet_NaN(), "NaN"); } if (auto nzero = -static_cast<T>(0); std::signbit(nzero)) { values.emplace_back(nzero, "neg_zero"); } } } template <typename Tag, bool key> NamedValues<Tag> generateValues() { static_assert(type::is_a_v<Tag, type::primitive_c>, ""); using T = type::standard_type<Tag>; NamedValues<Tag> values; if constexpr (type::is_a_v<Tag, type::bool_t>) { values.emplace_back(true, "true"); values.emplace_back(false, "false"); } else if constexpr (type::is_a_v<Tag, type::string_c>) { addStringValues<Tag>(values); } else if constexpr (type::is_a_v<Tag, type::number_c>) { addNumberValues<Tag, key>(values); } else { values.emplace_back(T(), "default"); } return values; } } // namespace template <typename Tag> auto ValueGenerator<Tag>::getInterestingValues() -> const Values& { static auto kValues = generateValues<Tag, false>(); return kValues; } template <typename Tag> auto ValueGenerator<Tag>::getKeyValues() -> const Values& { static auto kValues = generateValues<Tag, true>(); return kValues; } template struct ValueGenerator<type::bool_t>; template struct ValueGenerator<type::byte_t>; template struct ValueGenerator<type::i16_t>; template struct ValueGenerator<type::i32_t>; template struct ValueGenerator<type::i64_t>; template struct ValueGenerator<type::float_t>; template struct ValueGenerator<type::double_t>; template struct ValueGenerator<type::string_t>; template struct ValueGenerator<type::binary_t>; } // namespace apache::thrift::conformance::data
Add a few FP test cases
Add a few FP test cases Summary: Add a few "interesting" FP test cases to the conformance test. The fmt_test_* are taken from {fmt} regression tests and may exercise some problematic paths in FP formatting code. Reviewed By: Alfus Differential Revision: D39043191 fbshipit-source-id: 63e3188c0f6d63f2b5e6badc82b5b163238c802b
C++
apache-2.0
facebook/fbthrift,facebook/fbthrift,facebook/fbthrift,facebook/fbthrift,facebook/fbthrift,facebook/fbthrift,facebook/fbthrift,facebook/fbthrift,facebook/fbthrift
d4d1d372972bb418c1f74f771b76f738f4652297
src/logger.cpp
src/logger.cpp
#include <mlopen/logger.hpp> #include <cstdlib> namespace mlopen { bool IsLogging() { char* cs = std::getenv("MIOPEN_ENABLE_LOGGING"); return cs != nullptr && cs != std::string("0"); } }
#include <mlopen/logger.hpp> #include <cstdlib> namespace mlopen { bool IsLogging() { char* cs = std::getenv("MIOPEN_ENABLE_LOGGING"); return cs != nullptr && cs != std::string("0"); } } // namespace mlopen
Fix tidy check
Fix tidy check
C++
mit
ROCmSoftwarePlatform/MIOpen,ROCmSoftwarePlatform/MIOpen,ROCmSoftwarePlatform/MIOpen,ROCmSoftwarePlatform/MIOpen,ROCmSoftwarePlatform/MIOpen
f0866ff2ab237c52dc30ce8ac28204c1b8f8a570
source/Plugins/ExpressionParser/Swift/SwiftSILManipulator.cpp
source/Plugins/ExpressionParser/Swift/SwiftSILManipulator.cpp
//===-- SwiftSILManipulator.cpp ---------------------------------*- C++ -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "SwiftSILManipulator.h" #include "SwiftASTManipulator.h" #include "lldb/Core/Log.h" #include "lldb/Symbol/CompilerType.h" #include "swift/SIL/SILArgument.h" #include "swift/SIL/SILBasicBlock.h" #include "swift/SIL/SILBuilder.h" #include "swift/SIL/SILFunction.h" #include "swift/SIL/SILLocation.h" #include "swift/SIL/SILModule.h" #include "swift/SIL/SILType.h" #include "swift/SIL/SILValue.h" #include "swift/SIL/TypeLowering.h" using namespace lldb_private; SwiftSILManipulator::SwiftSILManipulator (swift::SILBuilder &builder) : m_builder(builder), m_log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)) { } swift::SILValue SwiftSILManipulator::emitLValueForVariable(swift::VarDecl *var, SwiftExpressionParser::SILVariableInfo &info) { swift::SILFunction &function = m_builder.getFunction(); swift::SILBasicBlock &entry_block = *function.getBlocks().begin(); swift::SILArgument *struct_argument = nullptr; for (swift::SILArgument *argument : entry_block.getBBArgs()) { swift::Identifier argument_name = argument->getDecl()->getName(); if (!strcmp(argument_name.get(), SwiftASTManipulator::GetArgumentName())) { struct_argument = argument; break; } } if (!struct_argument) return swift::SILValue(); assert (struct_argument->getType().getAsString().find("UnsafeMutablePointer") != std::string::npos); swift::CanType unsafe_mutable_pointer_can_type = struct_argument->getType().getSwiftType(); swift::BoundGenericStructType *unsafe_mutable_pointer_struct_type = llvm::cast<swift::BoundGenericStructType>(unsafe_mutable_pointer_can_type.getPointer()); swift::StructDecl *unsafe_mutable_pointer_struct_decl = unsafe_mutable_pointer_struct_type->getDecl(); swift::VarDecl *value_member_decl = nullptr; for (swift::Decl *member : unsafe_mutable_pointer_struct_decl->getMembers()) { if (swift::VarDecl *member_var = llvm::dyn_cast<swift::VarDecl>(member)) { if (member_var->getName().str().equals("_rawValue")) { value_member_decl = member_var; break; } } } if (!value_member_decl) return swift::SILValue(); swift::ASTContext &ast_ctx = m_builder.getASTContext(); swift::Lowering::TypeConverter converter(m_builder.getModule()); swift::SILLocation null_loc((swift::Decl*)nullptr); swift::SILType raw_pointer_type = swift::SILType::getRawPointerType(ast_ctx); swift::StructExtractInst *struct_extract = m_builder.createStructExtract(null_loc, struct_argument, value_member_decl, raw_pointer_type); swift::IntegerLiteralInst *integer_literal = m_builder.createIntegerLiteral(null_loc, swift::SILType::getBuiltinIntegerType(64, ast_ctx), (intmax_t)info.offset); swift::IndexRawPointerInst *index_raw_pointer = m_builder.createIndexRawPointer(null_loc, struct_extract, integer_literal); swift::PointerToAddressInst *pointer_to_return_slot = m_builder.createPointerToAddress(null_loc, index_raw_pointer, raw_pointer_type.getAddressType()); swift::LoadInst *pointer_to_variable = m_builder.createLoad(null_loc, pointer_to_return_slot); swift::PointerToAddressInst *address_of_variable = m_builder.createPointerToAddress(null_loc, pointer_to_variable, converter.getLoweredType(var->getType()).getAddressType()); if (info.needs_init) { info.needs_init = false; return swift::SILValue(m_builder.createMarkUninitialized(null_loc, address_of_variable, swift::MarkUninitializedInst::Var)); } else return swift::SILValue(address_of_variable); }
//===-- SwiftSILManipulator.cpp ---------------------------------*- C++ -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "SwiftSILManipulator.h" #include "SwiftASTManipulator.h" #include "lldb/Core/Log.h" #include "lldb/Symbol/CompilerType.h" #include "swift/SIL/SILArgument.h" #include "swift/SIL/SILBasicBlock.h" #include "swift/SIL/SILBuilder.h" #include "swift/SIL/SILFunction.h" #include "swift/SIL/SILLocation.h" #include "swift/SIL/SILModule.h" #include "swift/SIL/SILType.h" #include "swift/SIL/SILValue.h" #include "swift/SIL/TypeLowering.h" using namespace lldb_private; SwiftSILManipulator::SwiftSILManipulator (swift::SILBuilder &builder) : m_builder(builder), m_log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)) { } swift::SILValue SwiftSILManipulator::emitLValueForVariable(swift::VarDecl *var, SwiftExpressionParser::SILVariableInfo &info) { swift::SILFunction &function = m_builder.getFunction(); swift::SILBasicBlock &entry_block = *function.getBlocks().begin(); swift::SILArgument *struct_argument = nullptr; for (swift::SILArgument *argument : entry_block.getBBArgs()) { swift::Identifier argument_name = argument->getDecl()->getName(); if (!strcmp(argument_name.get(), SwiftASTManipulator::GetArgumentName())) { struct_argument = argument; break; } } if (!struct_argument) return swift::SILValue(); assert (struct_argument->getType().getAsString().find("UnsafeMutablePointer") != std::string::npos); swift::CanType unsafe_mutable_pointer_can_type = struct_argument->getType().getSwiftType(); swift::BoundGenericStructType *unsafe_mutable_pointer_struct_type = llvm::cast<swift::BoundGenericStructType>(unsafe_mutable_pointer_can_type.getPointer()); swift::StructDecl *unsafe_mutable_pointer_struct_decl = unsafe_mutable_pointer_struct_type->getDecl(); swift::VarDecl *value_member_decl = nullptr; for (swift::Decl *member : unsafe_mutable_pointer_struct_decl->getMembers()) { if (swift::VarDecl *member_var = llvm::dyn_cast<swift::VarDecl>(member)) { if (member_var->getName().str().equals("_rawValue")) { value_member_decl = member_var; break; } } } if (!value_member_decl) return swift::SILValue(); swift::ASTContext &ast_ctx = m_builder.getASTContext(); swift::Lowering::TypeConverter converter(m_builder.getModule()); swift::SILLocation null_loc((swift::Decl*)nullptr); swift::SILType raw_pointer_type = swift::SILType::getRawPointerType(ast_ctx); swift::StructExtractInst *struct_extract = m_builder.createStructExtract(null_loc, struct_argument, value_member_decl, raw_pointer_type); swift::IntegerLiteralInst *integer_literal = m_builder.createIntegerLiteral(null_loc, swift::SILType::getBuiltinIntegerType(64, ast_ctx), (intmax_t)info.offset); swift::IndexRawPointerInst *index_raw_pointer = m_builder.createIndexRawPointer(null_loc, struct_extract, integer_literal); swift::PointerToAddressInst *pointer_to_return_slot = m_builder.createPointerToAddress(null_loc, index_raw_pointer, raw_pointer_type.getAddressType(), /*isStrict*/ true); swift::LoadInst *pointer_to_variable = m_builder.createLoad(null_loc, pointer_to_return_slot); swift::PointerToAddressInst *address_of_variable = m_builder.createPointerToAddress(null_loc, pointer_to_variable, converter.getLoweredType(var->getType()).getAddressType(), /*isStrict*/ true); if (info.needs_init) { info.needs_init = false; return swift::SILValue(m_builder.createMarkUninitialized(null_loc, address_of_variable, swift::MarkUninitializedInst::Var)); } else return swift::SILValue(address_of_variable); }
Update for Swift SE-0107: UnsafeRawPointer (#33)
Update for Swift SE-0107: UnsafeRawPointer (#33) This is needed for: commit 675cca18d7624297647ccb46193f675656092f99 Author: Andrew Trick <[email protected]> Date: Thu Jul 14 17:26:18 2016 Add an isStrict flag to SIL pointer_to_address. Strict aliasing only applies to memory operations that use strict addresses. The optimizer needs to be aware of this flag. Uses of raw addresses should not have their address substituted with a strict address. Also add Builtin.LoadRaw which will be used by raw pointer loads.
C++
apache-2.0
apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb
c554e86c074e3602ba3999b366c5cf1008a570d7
eval/src/vespa/eval/instruction/generic_concat.cpp
eval/src/vespa/eval/instruction/generic_concat.cpp
// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "generic_concat.h" #include "generic_join.h" #include <vespa/eval/eval/value.h> #include <vespa/eval/eval/wrap_param.h> #include <vespa/vespalib/util/overload.h> #include <vespa/vespalib/util/stash.h> #include <vespa/vespalib/util/typify.h> #include <vespa/vespalib/util/visit_ranges.h> #include <cassert> using namespace vespalib::eval::tensor_function; namespace vespalib::eval::instruction { using State = InterpretedFunction::State; using Instruction = InterpretedFunction::Instruction; namespace { struct ConcatParam { ValueType res_type; SparseJoinPlan sparse_plan; DenseConcatPlan dense_plan; const ValueBuilderFactory &factory; ConcatParam(const ValueType &res_type_in, const ValueType &lhs_type, const ValueType &rhs_type, const vespalib::string &dimension, const ValueBuilderFactory &factory_in) : res_type(res_type_in), sparse_plan(lhs_type, rhs_type), dense_plan(lhs_type, rhs_type, dimension, res_type), factory(factory_in) { assert(!res_type.is_error()); } }; template <typename LCT, typename RCT, typename OCT> std::unique_ptr<Value> generic_concat(const Value &a, const Value &b, const SparseJoinPlan &sparse_plan, const DenseConcatPlan &dense_plan, const ValueType &res_type, const ValueBuilderFactory &factory) { auto a_cells = a.cells().typify<LCT>(); auto b_cells = b.cells().typify<RCT>(); SparseJoinState sparse(sparse_plan, a.index(), b.index()); auto builder = factory.create_transient_value_builder<OCT>(res_type, sparse_plan.sources.size(), dense_plan.output_size, sparse.first_index.size()); auto outer = sparse.first_index.create_view({}); auto inner = sparse.second_index.create_view(sparse.second_view_dims); outer->lookup({}); while (outer->next_result(sparse.first_address, sparse.first_subspace)) { inner->lookup(sparse.address_overlap); while (inner->next_result(sparse.second_only_address, sparse.second_subspace)) { OCT *dst = builder->add_subspace(sparse.full_address).begin(); { size_t left_input_offset = dense_plan.left.input_size * sparse.lhs_subspace; auto copy_left = [&](size_t in_idx, size_t out_idx) { dst[out_idx] = a_cells[in_idx]; }; dense_plan.left.execute(left_input_offset, 0, copy_left); } { size_t right_input_offset = dense_plan.right.input_size * sparse.rhs_subspace; auto copy_right = [&](size_t in_idx, size_t out_idx) { dst[out_idx] = b_cells[in_idx]; }; dense_plan.right.execute(right_input_offset, dense_plan.right_offset, copy_right); } } } return builder->build(std::move(builder)); } template <typename LCT, typename RCT, typename OCT> void my_generic_concat_op(State &state, uint64_t param_in) { const auto &param = unwrap_param<ConcatParam>(param_in); const Value &lhs = state.peek(1); const Value &rhs = state.peek(0); auto res_value = generic_concat<LCT, RCT, OCT>( lhs, rhs, param.sparse_plan, param.dense_plan, param.res_type, param.factory); auto &result = state.stash.create<std::unique_ptr<Value>>(std::move(res_value)); const Value &result_ref = *(result.get()); state.pop_pop_push(result_ref); } template <typename LCT, typename RCT, typename OCT, bool forward_lhs> void my_mixed_dense_concat_op(State &state, uint64_t param_in) { const auto &param = unwrap_param<ConcatParam>(param_in); const DenseConcatPlan &dense_plan = param.dense_plan; auto lhs_cells = state.peek(1).cells().typify<LCT>(); auto rhs_cells = state.peek(0).cells().typify<RCT>(); const auto &index = state.peek(forward_lhs ? 1 : 0).index(); size_t num_subspaces = index.size(); size_t num_out_cells = dense_plan.output_size * num_subspaces; ArrayRef<OCT> out_cells = state.stash.create_uninitialized_array<OCT>(num_out_cells); OCT *dst = out_cells.begin(); const LCT *lhs = lhs_cells.begin(); const RCT *rhs = rhs_cells.begin(); auto copy_left = [&](size_t in_idx, size_t out_idx) { dst[out_idx] = lhs[in_idx]; }; auto copy_right = [&](size_t in_idx, size_t out_idx) { dst[out_idx] = rhs[in_idx]; }; for (size_t i = 0; i < num_subspaces; ++i) { dense_plan.left.execute(0, 0, copy_left); dense_plan.right.execute(0, dense_plan.right_offset, copy_right); if (forward_lhs) { lhs += dense_plan.left.input_size; } else { rhs += dense_plan.right.input_size; } dst += dense_plan.output_size; } if (forward_lhs) { assert(lhs == lhs_cells.end()); } else { assert(rhs == rhs_cells.end()); } assert(dst == out_cells.end()); state.pop_pop_push(state.stash.create<ValueView>(param.res_type, index, TypedCells(out_cells))); } template <typename LCT, typename RCT, typename OCT> void my_dense_simple_concat_op(State &state, uint64_t param_in) { const auto &param = unwrap_param<ConcatParam>(param_in); const Value &lhs = state.peek(1); const Value &rhs = state.peek(0); const auto a = lhs.cells().typify<LCT>(); const auto b = rhs.cells().typify<RCT>(); ArrayRef<OCT> result = state.stash.create_uninitialized_array<OCT>(a.size() + b.size()); auto pos = result.begin(); for (size_t i = 0; i < a.size(); ++i) { *pos++ = a[i]; } for (size_t i = 0; i < b.size(); ++i) { *pos++ = b[i]; } Value &ref = state.stash.create<DenseValueView>(param.res_type, TypedCells(result)); state.pop_pop_push(ref); } struct SelectGenericConcatOp { template <typename LCT, typename RCT, typename OCT> static auto invoke(const ConcatParam &param) { if (param.sparse_plan.sources.empty() && param.res_type.is_dense()) { auto & dp = param.dense_plan; if ((dp.output_size == (dp.left.input_size + dp.right.input_size)) && (dp.right_offset == dp.left.input_size)) { return my_dense_simple_concat_op<LCT, RCT, OCT>; } } if (param.sparse_plan.should_forward_lhs_index()) { return my_mixed_dense_concat_op<LCT, RCT, OCT, true>; } if (param.sparse_plan.should_forward_rhs_index()) { return my_mixed_dense_concat_op<LCT, RCT, OCT, false>; } return my_generic_concat_op<LCT, RCT, OCT>; } }; enum class Case { NONE, OUT, CONCAT, BOTH }; } // namespace <unnamed> std::pair<size_t, size_t> DenseConcatPlan::InOutLoop::fill_from(const ValueType &in_type, std::string concat_dimension, const ValueType &out_type) { SmallVector<size_t> out_loop_cnt; Case prev_case = Case::NONE; auto update_plan = [&](Case my_case, size_t in_size, size_t out_size, size_t in_val, size_t out_val) { if (my_case == prev_case) { assert(!out_loop_cnt.empty()); in_loop_cnt.back() *= in_size; out_loop_cnt.back() *= out_size; } else { in_loop_cnt.push_back(in_size); out_loop_cnt.push_back(out_size); in_stride.push_back(in_val); out_stride.push_back(out_val); prev_case = my_case; } }; auto visitor = overload { [&](visit_ranges_first, const auto &) { abort(); }, [&](visit_ranges_second, const auto &b) { if (b.name == concat_dimension) { update_plan(Case::CONCAT, 1, b.size, 0, 1); } else { update_plan(Case::OUT, b.size, b.size, 0, 1); } }, [&](visit_ranges_both, const auto &a, const auto &b) { if (b.name == concat_dimension) { update_plan(Case::CONCAT, a.size, b.size, 1, 1); } else { update_plan(Case::BOTH, a.size, b.size, 1, 1); } } }; const auto input_dimensions = in_type.nontrivial_indexed_dimensions(); const auto output_dimensions = out_type.nontrivial_indexed_dimensions(); visit_ranges(visitor, input_dimensions.begin(), input_dimensions.end(), output_dimensions.begin(), output_dimensions.end(), [](const auto &a, const auto &b){ return (a.name < b.name); }); input_size = 1; size_t output_size_for_concat = 1; size_t offset_for_concat = 0; for (size_t i = in_loop_cnt.size(); i-- > 0; ) { if (in_stride[i] != 0) { in_stride[i] = input_size; input_size *= in_loop_cnt[i]; } assert(out_stride[i] != 0); assert(out_loop_cnt[i] != 0); out_stride[i] = output_size_for_concat; output_size_for_concat *= out_loop_cnt[i]; // loop counts are different if and only if this is the concat dimension if (in_loop_cnt[i] != out_loop_cnt[i]) { assert(offset_for_concat == 0); offset_for_concat = in_loop_cnt[i] * out_stride[i]; } } assert(offset_for_concat != 0); return std::make_pair(offset_for_concat, output_size_for_concat); } DenseConcatPlan::DenseConcatPlan(const ValueType &lhs_type, const ValueType &rhs_type, std::string concat_dimension, const ValueType &out_type) { std::tie(right_offset, output_size) = left.fill_from(lhs_type, concat_dimension, out_type); auto [ other_offset, other_size ] = right.fill_from(rhs_type, concat_dimension, out_type); assert(other_offset > 0); assert(output_size == other_size); } DenseConcatPlan::~DenseConcatPlan() = default; DenseConcatPlan::InOutLoop::~InOutLoop() = default; InterpretedFunction::Instruction GenericConcat::make_instruction(const ValueType &result_type, const ValueType &lhs_type, const ValueType &rhs_type, const vespalib::string &dimension, const ValueBuilderFactory &factory, Stash &stash) { auto &param = stash.create<ConcatParam>(result_type, lhs_type, rhs_type, dimension, factory); assert(result_type == ValueType::concat(lhs_type, rhs_type, dimension)); auto fun = typify_invoke<3,TypifyCellType,SelectGenericConcatOp>( lhs_type.cell_type(), rhs_type.cell_type(), param.res_type.cell_type(), param); return Instruction(fun, wrap_param<ConcatParam>(param)); } } // namespace
// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "generic_concat.h" #include "generic_join.h" #include <vespa/eval/eval/value.h> #include <vespa/eval/eval/wrap_param.h> #include <vespa/vespalib/util/overload.h> #include <vespa/vespalib/util/stash.h> #include <vespa/vespalib/util/typify.h> #include <vespa/vespalib/util/visit_ranges.h> #include <cassert> using namespace vespalib::eval::tensor_function; namespace vespalib::eval::instruction { using State = InterpretedFunction::State; using Instruction = InterpretedFunction::Instruction; namespace { struct ConcatParam { ValueType res_type; SparseJoinPlan sparse_plan; DenseConcatPlan dense_plan; const ValueBuilderFactory &factory; ConcatParam(const ValueType &res_type_in, const ValueType &lhs_type, const ValueType &rhs_type, const vespalib::string &dimension, const ValueBuilderFactory &factory_in) : res_type(res_type_in), sparse_plan(lhs_type, rhs_type), dense_plan(lhs_type, rhs_type, dimension, res_type), factory(factory_in) { assert(!res_type.is_error()); } }; template <typename LCT, typename RCT, typename OCT> std::unique_ptr<Value> generic_concat(const Value &a, const Value &b, const SparseJoinPlan &sparse_plan, const DenseConcatPlan &dense_plan, const ValueType &res_type, const ValueBuilderFactory &factory) { auto a_cells = a.cells().typify<LCT>(); auto b_cells = b.cells().typify<RCT>(); SparseJoinState sparse(sparse_plan, a.index(), b.index()); auto builder = factory.create_transient_value_builder<OCT>(res_type, sparse_plan.sources.size(), dense_plan.output_size, sparse.first_index.size()); auto outer = sparse.first_index.create_view({}); auto inner = sparse.second_index.create_view(sparse.second_view_dims); outer->lookup({}); while (outer->next_result(sparse.first_address, sparse.first_subspace)) { inner->lookup(sparse.address_overlap); while (inner->next_result(sparse.second_only_address, sparse.second_subspace)) { OCT *dst = builder->add_subspace(sparse.full_address).begin(); { size_t left_input_offset = dense_plan.left.input_size * sparse.lhs_subspace; auto copy_left = [&](size_t in_idx, size_t out_idx) { dst[out_idx] = a_cells[in_idx]; }; dense_plan.left.execute(left_input_offset, 0, copy_left); } { size_t right_input_offset = dense_plan.right.input_size * sparse.rhs_subspace; auto copy_right = [&](size_t in_idx, size_t out_idx) { dst[out_idx] = b_cells[in_idx]; }; dense_plan.right.execute(right_input_offset, dense_plan.right_offset, copy_right); } } } return builder->build(std::move(builder)); } template <typename LCT, typename RCT, typename OCT> void my_generic_concat_op(State &state, uint64_t param_in) { const auto &param = unwrap_param<ConcatParam>(param_in); const Value &lhs = state.peek(1); const Value &rhs = state.peek(0); auto res_value = generic_concat<LCT, RCT, OCT>( lhs, rhs, param.sparse_plan, param.dense_plan, param.res_type, param.factory); auto &result = state.stash.create<std::unique_ptr<Value>>(std::move(res_value)); const Value &result_ref = *(result.get()); state.pop_pop_push(result_ref); } template <typename LCT, typename RCT, typename OCT, bool forward_lhs> void my_mixed_dense_concat_op(State &state, uint64_t param_in) { const auto &param = unwrap_param<ConcatParam>(param_in); const DenseConcatPlan &dense_plan = param.dense_plan; auto lhs_cells = state.peek(1).cells().typify<LCT>(); auto rhs_cells = state.peek(0).cells().typify<RCT>(); const auto &index = state.peek(forward_lhs ? 1 : 0).index(); size_t num_subspaces = index.size(); size_t num_out_cells = dense_plan.output_size * num_subspaces; ArrayRef<OCT> out_cells = state.stash.create_uninitialized_array<OCT>(num_out_cells); OCT *dst = out_cells.begin(); const LCT *lhs = lhs_cells.begin(); const RCT *rhs = rhs_cells.begin(); auto copy_left = [&](size_t in_idx, size_t out_idx) { dst[out_idx] = lhs[in_idx]; }; auto copy_right = [&](size_t in_idx, size_t out_idx) { dst[out_idx] = rhs[in_idx]; }; for (size_t i = 0; i < num_subspaces; ++i) { dense_plan.left.execute(0, 0, copy_left); dense_plan.right.execute(0, dense_plan.right_offset, copy_right); if (forward_lhs) { lhs += dense_plan.left.input_size; } else { rhs += dense_plan.right.input_size; } dst += dense_plan.output_size; } if (forward_lhs) { assert(lhs == lhs_cells.end()); } else { assert(rhs == rhs_cells.end()); } assert(dst == out_cells.end()); state.pop_pop_push(state.stash.create<ValueView>(param.res_type, index, TypedCells(out_cells))); } template <typename LCT, typename RCT, typename OCT> void my_dense_simple_concat_op(State &state, uint64_t param_in) { const auto &param = unwrap_param<ConcatParam>(param_in); const Value &lhs = state.peek(1); const Value &rhs = state.peek(0); const auto a = lhs.cells().typify<LCT>(); const auto b = rhs.cells().typify<RCT>(); ArrayRef<OCT> result = state.stash.create_uninitialized_array<OCT>(a.size() + b.size()); auto pos = result.begin(); for (size_t i = 0; i < a.size(); ++i) { *pos++ = a[i]; } for (size_t i = 0; i < b.size(); ++i) { *pos++ = b[i]; } Value &ref = state.stash.create<DenseValueView>(param.res_type, TypedCells(result)); state.pop_pop_push(ref); } struct SelectGenericConcatOp { template <typename LCM, typename RCM> static auto invoke(const ConcatParam &param) { using LCT = CellValueType<LCM::value.cell_type>; using RCT = CellValueType<RCM::value.cell_type>; constexpr CellMeta ocm = CellMeta::concat(LCM::value, RCM::value); using OCT = CellValueType<ocm.cell_type>; if (param.sparse_plan.sources.empty() && param.res_type.is_dense()) { auto & dp = param.dense_plan; if ((dp.output_size == (dp.left.input_size + dp.right.input_size)) && (dp.right_offset == dp.left.input_size)) { return my_dense_simple_concat_op<LCT, RCT, OCT>; } } if (param.sparse_plan.should_forward_lhs_index()) { return my_mixed_dense_concat_op<LCT, RCT, OCT, true>; } if (param.sparse_plan.should_forward_rhs_index()) { return my_mixed_dense_concat_op<LCT, RCT, OCT, false>; } return my_generic_concat_op<LCT, RCT, OCT>; } }; enum class Case { NONE, OUT, CONCAT, BOTH }; } // namespace <unnamed> std::pair<size_t, size_t> DenseConcatPlan::InOutLoop::fill_from(const ValueType &in_type, std::string concat_dimension, const ValueType &out_type) { SmallVector<size_t> out_loop_cnt; Case prev_case = Case::NONE; auto update_plan = [&](Case my_case, size_t in_size, size_t out_size, size_t in_val, size_t out_val) { if (my_case == prev_case) { assert(!out_loop_cnt.empty()); in_loop_cnt.back() *= in_size; out_loop_cnt.back() *= out_size; } else { in_loop_cnt.push_back(in_size); out_loop_cnt.push_back(out_size); in_stride.push_back(in_val); out_stride.push_back(out_val); prev_case = my_case; } }; auto visitor = overload { [&](visit_ranges_first, const auto &) { abort(); }, [&](visit_ranges_second, const auto &b) { if (b.name == concat_dimension) { update_plan(Case::CONCAT, 1, b.size, 0, 1); } else { update_plan(Case::OUT, b.size, b.size, 0, 1); } }, [&](visit_ranges_both, const auto &a, const auto &b) { if (b.name == concat_dimension) { update_plan(Case::CONCAT, a.size, b.size, 1, 1); } else { update_plan(Case::BOTH, a.size, b.size, 1, 1); } } }; const auto input_dimensions = in_type.nontrivial_indexed_dimensions(); const auto output_dimensions = out_type.nontrivial_indexed_dimensions(); visit_ranges(visitor, input_dimensions.begin(), input_dimensions.end(), output_dimensions.begin(), output_dimensions.end(), [](const auto &a, const auto &b){ return (a.name < b.name); }); input_size = 1; size_t output_size_for_concat = 1; size_t offset_for_concat = 0; for (size_t i = in_loop_cnt.size(); i-- > 0; ) { if (in_stride[i] != 0) { in_stride[i] = input_size; input_size *= in_loop_cnt[i]; } assert(out_stride[i] != 0); assert(out_loop_cnt[i] != 0); out_stride[i] = output_size_for_concat; output_size_for_concat *= out_loop_cnt[i]; // loop counts are different if and only if this is the concat dimension if (in_loop_cnt[i] != out_loop_cnt[i]) { assert(offset_for_concat == 0); offset_for_concat = in_loop_cnt[i] * out_stride[i]; } } assert(offset_for_concat != 0); return std::make_pair(offset_for_concat, output_size_for_concat); } DenseConcatPlan::DenseConcatPlan(const ValueType &lhs_type, const ValueType &rhs_type, std::string concat_dimension, const ValueType &out_type) { std::tie(right_offset, output_size) = left.fill_from(lhs_type, concat_dimension, out_type); auto [ other_offset, other_size ] = right.fill_from(rhs_type, concat_dimension, out_type); assert(other_offset > 0); assert(output_size == other_size); } DenseConcatPlan::~DenseConcatPlan() = default; DenseConcatPlan::InOutLoop::~InOutLoop() = default; InterpretedFunction::Instruction GenericConcat::make_instruction(const ValueType &result_type, const ValueType &lhs_type, const ValueType &rhs_type, const vespalib::string &dimension, const ValueBuilderFactory &factory, Stash &stash) { auto &param = stash.create<ConcatParam>(result_type, lhs_type, rhs_type, dimension, factory); assert(result_type == ValueType::concat(lhs_type, rhs_type, dimension)); auto fun = typify_invoke<2,TypifyCellMeta,SelectGenericConcatOp>( lhs_type.cell_meta(), rhs_type.cell_meta(), param); return Instruction(fun, wrap_param<ConcatParam>(param)); } } // namespace
use TypifyCellMeta in GenericConcat
use TypifyCellMeta in GenericConcat
C++
apache-2.0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
af7d875c27c349a13f457ca6bad6bcec078681b6
helpers/MainLoop.cpp
helpers/MainLoop.cpp
#include <chrono> #include "MainLoop.hpp" #include "EntityManager.hpp" #include "functions/Execute.hpp" #include "Timer.hpp" namespace kengine::MainLoop { void run(EntityManager & em) { auto start = std::chrono::system_clock::now(); auto end = std::chrono::system_clock::now(); while (em.running) { const float deltaTime = std::chrono::duration<float, std::ratio<1>>(end - start).count(); start = std::chrono::system_clock::now(); for (const auto & [e, func] : em.getEntities<functions::Execute>()) func(deltaTime); end = std::chrono::system_clock::now(); } } }
#include <chrono> #include "MainLoop.hpp" #include "EntityManager.hpp" #include "functions/Execute.hpp" namespace kengine::MainLoop { void run(EntityManager & em) { auto start = std::chrono::system_clock::now(); auto end = std::chrono::system_clock::now(); while (em.running) { const float deltaTime = std::chrono::duration<float, std::ratio<1>>(end - start).count(); start = std::chrono::system_clock::now(); for (const auto & [e, func] : em.getEntities<functions::Execute>()) func(deltaTime); end = std::chrono::system_clock::now(); } } }
remove unused include in MainLoop
remove unused include in MainLoop
C++
mit
phiste/kengine,phiste/kengine,phiste/kengine
7418bc861f6a73faaeb0ca0e78638e633aee607f
helpers/d3d7size.hpp
helpers/d3d7size.hpp
/************************************************************************** * * Copyright 2015 VMware, Inc. * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sub license, * 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 (including the next * paragraph) 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 NON-INFRINGEMENT. IN NO EVENT SHALL * AUTHORS, * AND/OR THEIR SUPPLIERS 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. * **************************************************************************/ /* * Auxiliary functions to compute the size of array/blob arguments. */ #pragma once static inline size_t _getVertexSize(DWORD dwFVF) { size_t size = 0; assert((dwFVF & D3DFVF_RESERVED0) == 0); switch (dwFVF & D3DFVF_POSITION_MASK) { case D3DFVF_XYZ: size += 3 * sizeof(FLOAT); break; case D3DFVF_XYZRHW: size += 4 * sizeof(FLOAT); break; case D3DFVF_XYZB1: size += (3 + 1) * sizeof(FLOAT); break; case D3DFVF_XYZB2: size += (3 + 2) * sizeof(FLOAT); break; case D3DFVF_XYZB3: size += (3 + 3) * sizeof(FLOAT); break; case D3DFVF_XYZB4: size += (3 + 4) * sizeof(FLOAT); break; case D3DFVF_XYZB5: size += (3 + 5) * sizeof(FLOAT); break; #if DIRECT3D_VERSION >= 0x0900 case D3DFVF_XYZW: size += 4 * sizeof(FLOAT); break; #endif } if (dwFVF & D3DFVF_NORMAL) { size += 3 * sizeof(FLOAT); } #if DIRECT3D_VERSION >= 0x0800 if (dwFVF & D3DFVF_PSIZE) { size += sizeof(FLOAT); } #else if (dwFVF & D3DFVF_RESERVED1) { // D3DLVERTEX size += sizeof(DWORD); } #endif if (dwFVF & D3DFVF_DIFFUSE) { size += sizeof(D3DCOLOR); } if (dwFVF & D3DFVF_SPECULAR) { size += sizeof(D3DCOLOR); } DWORD dwNumTextures = (dwFVF & D3DFVF_TEXCOUNT_MASK) >> D3DFVF_TEXCOUNT_SHIFT; for (DWORD CoordIndex = 0; CoordIndex < dwNumTextures; ++CoordIndex) { // See D3DFVF_TEXCOORDSIZE* DWORD dwTexCoordSize = (dwFVF >> (CoordIndex*2 + 16)) & 3; size += dwTexCoordSize * sizeof(FLOAT); } assert((dwFVF & D3DFVF_RESERVED2) == 0); return size; }
/************************************************************************** * * Copyright 2015 VMware, Inc. * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sub license, * 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 (including the next * paragraph) 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 NON-INFRINGEMENT. IN NO EVENT SHALL * AUTHORS, * AND/OR THEIR SUPPLIERS 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. * **************************************************************************/ /* * Auxiliary functions to compute the size of array/blob arguments. */ #pragma once static inline size_t _getVertexSize(DWORD dwFVF) { size_t size = 0; assert((dwFVF & D3DFVF_RESERVED0) == 0); switch (dwFVF & D3DFVF_POSITION_MASK) { case D3DFVF_XYZ: size += 3 * sizeof(FLOAT); break; case D3DFVF_XYZRHW: size += 4 * sizeof(FLOAT); break; case D3DFVF_XYZB1: size += (3 + 1) * sizeof(FLOAT); break; case D3DFVF_XYZB2: size += (3 + 2) * sizeof(FLOAT); break; case D3DFVF_XYZB3: size += (3 + 3) * sizeof(FLOAT); break; case D3DFVF_XYZB4: size += (3 + 4) * sizeof(FLOAT); break; case D3DFVF_XYZB5: size += (3 + 5) * sizeof(FLOAT); break; #if DIRECT3D_VERSION >= 0x0900 case D3DFVF_XYZW: size += 4 * sizeof(FLOAT); break; #endif } if (dwFVF & D3DFVF_NORMAL) { size += 3 * sizeof(FLOAT); } #if DIRECT3D_VERSION >= 0x0800 if (dwFVF & D3DFVF_PSIZE) { size += sizeof(FLOAT); } #else if (dwFVF & D3DFVF_RESERVED1) { // D3DLVERTEX size += sizeof(DWORD); } #endif if (dwFVF & D3DFVF_DIFFUSE) { size += sizeof(D3DCOLOR); } if (dwFVF & D3DFVF_SPECULAR) { size += sizeof(D3DCOLOR); } DWORD dwNumTextures = (dwFVF & D3DFVF_TEXCOUNT_MASK) >> D3DFVF_TEXCOUNT_SHIFT; for (DWORD CoordIndex = 0; CoordIndex < dwNumTextures; ++CoordIndex) { // See D3DFVF_TEXCOORDSIZE* DWORD dwTexCoordSize = (dwFVF >> (CoordIndex*2 + 16)) & 3; switch (dwTexCoordSize) { case D3DFVF_TEXTUREFORMAT2: size += 2 * sizeof(FLOAT); break; case D3DFVF_TEXTUREFORMAT1: size += 1 * sizeof(FLOAT); break; case D3DFVF_TEXTUREFORMAT3: size += 3 * sizeof(FLOAT); break; case D3DFVF_TEXTUREFORMAT4: size += 4 * sizeof(FLOAT); break; } } assert((dwFVF & D3DFVF_RESERVED2) == 0); return size; }
Fix calculation of FVF texture coord size.
ddrawtrace: Fix calculation of FVF texture coord size.
C++
mit
schulmar/apitrace,schulmar/apitrace,EoD/apitrace,apitrace/apitrace,apitrace/apitrace,trtt/apitrace,trtt/apitrace,EoD/apitrace,schulmar/apitrace,apitrace/apitrace,EoD/apitrace,EoD/apitrace,trtt/apitrace,trtt/apitrace,schulmar/apitrace,EoD/apitrace,trtt/apitrace,apitrace/apitrace,schulmar/apitrace
9df0e2d1f160980d2ae86ccd95f167e8dcb2ff43
test/scan-test.cc
test/scan-test.cc
// Formatting library for C++ - scanning API proof of concept // // Copyright (c) 2012 - present, Victor Zverovich // All rights reserved. // // For the license information refer to format.h. #include <array> #include <climits> #include "fmt/format.h" #include "gmock.h" #include "gtest-extra.h" FMT_BEGIN_NAMESPACE namespace internal { struct scan_arg { type arg_type; union { int* int_value; unsigned* uint_value; long long* long_long_value; unsigned long long* ulong_long_value; // TODO: more types }; scan_arg() : arg_type(none_type) {} scan_arg(int& value) : arg_type(int_type), int_value(&value) {} scan_arg(unsigned& value) : arg_type(uint_type), uint_value(&value) {} scan_arg(long long& value) : arg_type(long_long_type), long_long_value(&value) {} scan_arg(unsigned long long& value) : arg_type(ulong_long_type), ulong_long_value(&value) {} }; } // namespace internal struct scan_args { int size; const internal::scan_arg* data; template <size_t N> scan_args(const std::array<internal::scan_arg, N>& store) : size(N), data(store.data()) { static_assert(N < INT_MAX, "too many arguments"); } }; namespace internal { struct scan_handler : error_handler { private: const char* begin_; const char* end_; scan_args args_; int next_arg_id_; scan_arg arg_; template <typename T = unsigned> T read_uint() { T value = 0; while (begin_ != end_) { char c = *begin_++; if (c < '0' || c > '9') on_error("invalid input"); // TODO: check overflow value = value * 10 + (c - '0'); } return value; } template <typename T = int> T read_int() { T value = 0; bool negative = begin_ != end_ && *begin_ == '-'; if (negative) ++begin_; value = read_uint<typename std::make_unsigned<T>::type>(); if (negative) value = -value; return value; } public: scan_handler(string_view input, scan_args args) : begin_(input.data()), end_(begin_ + input.size()), args_(args), next_arg_id_(0) {} const char* pos() const { return begin_; } void on_text(const char* begin, const char* end) { auto size = end - begin; if (begin_ + size > end_ || !std::equal(begin, end, begin_)) on_error("invalid input"); begin_ += size; } void on_arg_id() { if (next_arg_id_ >= args_.size) on_error("argument index out of range"); arg_ = args_.data[next_arg_id_++]; } void on_arg_id(unsigned) { on_error("invalid format"); } void on_arg_id(string_view) { on_error("invalid format"); } void on_replacement_field(const char*) { switch (arg_.arg_type) { case int_type: *arg_.int_value = read_int(); break; case uint_type: *arg_.uint_value = read_uint(); break; case long_long_type: *arg_.long_long_value = read_int<long long>(); break; case ulong_long_type: *arg_.ulong_long_value = read_uint<unsigned long long>(); break; default: assert(false); } } const char* on_format_specs(const char* begin, const char*) { return begin; } }; } // namespace internal template <typename... Args> std::array<internal::scan_arg, sizeof...(Args)> make_scan_args(Args&... args) { return std::array<internal::scan_arg, sizeof...(Args)>{args...}; } string_view::iterator vscan(string_view input, string_view format_str, scan_args args) { internal::scan_handler h(input, args); internal::parse_format_string<false>(format_str, h); return input.begin() + (h.pos() - &*input.begin()); } template <typename... Args> string_view::iterator scan(string_view input, string_view format_str, Args&... args) { return vscan(input, format_str, make_scan_args(args...)); } FMT_END_NAMESPACE TEST(ScanTest, ReadText) { fmt::string_view s = "foo"; auto end = fmt::scan(s, "foo"); EXPECT_EQ(end, s.end()); EXPECT_THROW_MSG(fmt::scan("fob", "foo"), fmt::format_error, "invalid input"); } TEST(ScanTest, ReadInt) { int n = 0; fmt::scan("42", "{}", n); EXPECT_EQ(n, 42); fmt::scan("-42", "{}", n); EXPECT_EQ(n, -42); } TEST(ScanTest, ReadLongLong) { long long n = 0; fmt::scan("42", "{}", n); EXPECT_EQ(n, 42); fmt::scan("-42", "{}", n); EXPECT_EQ(n, -42); } TEST(ScanTest, ReadUInt) { unsigned n = 0; fmt::scan("42", "{}", n); EXPECT_EQ(n, 42); EXPECT_THROW_MSG(fmt::scan("-42", "{}", n), fmt::format_error, "invalid input"); } TEST(ScanTest, ReadULongLong) { unsigned long long n = 0; fmt::scan("42", "{}", n); EXPECT_EQ(n, 42); EXPECT_THROW_MSG(fmt::scan("-42", "{}", n), fmt::format_error, "invalid input"); } TEST(ScanTest, InvalidFormat) { EXPECT_THROW_MSG(fmt::scan("", "{}"), fmt::format_error, "argument index out of range"); EXPECT_THROW_MSG(fmt::scan("", "{"), fmt::format_error, "invalid format string"); }
// Formatting library for C++ - scanning API proof of concept // // Copyright (c) 2012 - present, Victor Zverovich // All rights reserved. // // For the license information refer to format.h. #include <array> #include <climits> #include "fmt/format.h" #include "gmock.h" #include "gtest-extra.h" FMT_BEGIN_NAMESPACE namespace internal { struct scan_arg { type arg_type; union { int* int_value; unsigned* uint_value; long long* long_long_value; unsigned long long* ulong_long_value; std::string* string; // TODO: more types }; scan_arg() : arg_type(none_type) {} scan_arg(int& value) : arg_type(int_type), int_value(&value) {} scan_arg(unsigned& value) : arg_type(uint_type), uint_value(&value) {} scan_arg(long long& value) : arg_type(long_long_type), long_long_value(&value) {} scan_arg(unsigned long long& value) : arg_type(ulong_long_type), ulong_long_value(&value) {} scan_arg(std::string& value) : arg_type(string_type), string(&value) {} }; } // namespace internal struct scan_args { int size; const internal::scan_arg* data; template <size_t N> scan_args(const std::array<internal::scan_arg, N>& store) : size(N), data(store.data()) { static_assert(N < INT_MAX, "too many arguments"); } }; namespace internal { struct scan_handler : error_handler { private: const char* begin_; const char* end_; scan_args args_; int next_arg_id_; scan_arg arg_; template <typename T = unsigned> T read_uint() { T value = 0; while (begin_ != end_) { char c = *begin_++; if (c < '0' || c > '9') on_error("invalid input"); // TODO: check overflow value = value * 10 + (c - '0'); } return value; } template <typename T = int> T read_int() { T value = 0; bool negative = begin_ != end_ && *begin_ == '-'; if (negative) ++begin_; value = read_uint<typename std::make_unsigned<T>::type>(); if (negative) value = -value; return value; } public: scan_handler(string_view input, scan_args args) : begin_(input.data()), end_(begin_ + input.size()), args_(args), next_arg_id_(0) {} const char* pos() const { return begin_; } void on_text(const char* begin, const char* end) { auto size = end - begin; if (begin_ + size > end_ || !std::equal(begin, end, begin_)) on_error("invalid input"); begin_ += size; } void on_arg_id() { if (next_arg_id_ >= args_.size) on_error("argument index out of range"); arg_ = args_.data[next_arg_id_++]; } void on_arg_id(unsigned) { on_error("invalid format"); } void on_arg_id(string_view) { on_error("invalid format"); } void on_replacement_field(const char*) { switch (arg_.arg_type) { case int_type: *arg_.int_value = read_int(); break; case uint_type: *arg_.uint_value = read_uint(); break; case long_long_type: *arg_.long_long_value = read_int<long long>(); break; case ulong_long_type: *arg_.ulong_long_value = read_uint<unsigned long long>(); break; case string_type: { while (begin_ != end_ && *begin_ != ' ') arg_.string->push_back(*begin_++); break; } default: assert(false); } } const char* on_format_specs(const char* begin, const char*) { return begin; } }; } // namespace internal template <typename... Args> std::array<internal::scan_arg, sizeof...(Args)> make_scan_args(Args&... args) { return std::array<internal::scan_arg, sizeof...(Args)>{args...}; } string_view::iterator vscan(string_view input, string_view format_str, scan_args args) { internal::scan_handler h(input, args); internal::parse_format_string<false>(format_str, h); return input.begin() + (h.pos() - &*input.begin()); } template <typename... Args> string_view::iterator scan(string_view input, string_view format_str, Args&... args) { return vscan(input, format_str, make_scan_args(args...)); } FMT_END_NAMESPACE TEST(ScanTest, ReadText) { fmt::string_view s = "foo"; auto end = fmt::scan(s, "foo"); EXPECT_EQ(end, s.end()); EXPECT_THROW_MSG(fmt::scan("fob", "foo"), fmt::format_error, "invalid input"); } TEST(ScanTest, ReadInt) { int n = 0; fmt::scan("42", "{}", n); EXPECT_EQ(n, 42); fmt::scan("-42", "{}", n); EXPECT_EQ(n, -42); } TEST(ScanTest, ReadLongLong) { long long n = 0; fmt::scan("42", "{}", n); EXPECT_EQ(n, 42); fmt::scan("-42", "{}", n); EXPECT_EQ(n, -42); } TEST(ScanTest, ReadUInt) { unsigned n = 0; fmt::scan("42", "{}", n); EXPECT_EQ(n, 42); EXPECT_THROW_MSG(fmt::scan("-42", "{}", n), fmt::format_error, "invalid input"); } TEST(ScanTest, ReadULongLong) { unsigned long long n = 0; fmt::scan("42", "{}", n); EXPECT_EQ(n, 42); EXPECT_THROW_MSG(fmt::scan("-42", "{}", n), fmt::format_error, "invalid input"); } TEST(ScanTest, ReadString) { std::string s; fmt::scan("foo", "{}", s); EXPECT_EQ(s, "foo"); } TEST(ScanTest, InvalidFormat) { EXPECT_THROW_MSG(fmt::scan("", "{}"), fmt::format_error, "argument index out of range"); EXPECT_THROW_MSG(fmt::scan("", "{"), fmt::format_error, "invalid format string"); } TEST(ScanTest, Example) { std::string key; int value; fmt::scan("answer = 42", "{} = {}", key, value); EXPECT_EQ(key, "answer"); EXPECT_EQ(value, 42); }
Implement string parsing
Implement string parsing
C++
bsd-2-clause
alabuzhev/fmt,cppformat/cppformat,alabuzhev/fmt,cppformat/cppformat,alabuzhev/fmt,cppformat/cppformat
09ce5c70c41f0a3ff418b7b6cd521b0da881fd36
src/netconf.cc
src/netconf.cc
// Copyright 2015 Toggl Desktop developers. #include "../src/netconf.h" #include <string> #include <sstream> #include "./https_client.h" #include "Poco/Environment.h" #include "Poco/Logger.h" #include "Poco/Net/HTTPCredentials.h" #include "Poco/Net/HTTPSClientSession.h" #include "Poco/URI.h" #include "Poco/UnicodeConverter.h" #ifdef __MACH__ #include <CoreFoundation/CoreFoundation.h> // NOLINT #include <CoreServices/CoreServices.h> // NOLINT #endif #ifdef _WIN32 #include <winhttp.h> #pragma comment(lib, "winhttp") #endif #ifdef __linux__ #include <sys/types.h> #include <sys/wait.h> #include <spawn.h> #endif namespace toggl { error Netconf::autodetectProxy( const std::string encoded_url, std::vector<std::string> *proxy_strings) { poco_assert(proxy_strings); proxy_strings->clear(); if (encoded_url.empty()) { return noError; } #ifdef _WIN32 WINHTTP_CURRENT_USER_IE_PROXY_CONFIG ie_config = { 0 }; if (!WinHttpGetIEProxyConfigForCurrentUser(&ie_config)) { std::stringstream ss; ss << "WinHttpGetIEProxyConfigForCurrentUser error: " << GetLastError(); return ss.str(); } if (ie_config.lpszProxy) { std::wstring proxy_url_wide(ie_config.lpszProxy); std::string s(""); Poco::UnicodeConverter::toUTF8(proxy_url_wide, s); proxy_strings->push_back(s); } #endif // Inspired by VLC source code // https://github.com/videolan/vlc/blob/master/src/darwin/netconf.c #ifdef __MACH__ CFDictionaryRef dicRef = CFNetworkCopySystemProxySettings(); if (NULL != dicRef) { const CFStringRef proxyCFstr = (const CFStringRef)CFDictionaryGetValue( dicRef, (const void*)kCFNetworkProxiesHTTPProxy); const CFNumberRef portCFnum = (const CFNumberRef)CFDictionaryGetValue( dicRef, (const void*)kCFNetworkProxiesHTTPPort); if (NULL != proxyCFstr && NULL != portCFnum) { int port = 0; if (!CFNumberGetValue(portCFnum, kCFNumberIntType, &port)) { CFRelease(dicRef); return noError; } const std::size_t kBufsize(4096); char host_buffer[kBufsize]; memset(host_buffer, 0, sizeof(host_buffer)); if (CFStringGetCString(proxyCFstr, host_buffer, sizeof(host_buffer) - 1, kCFStringEncodingUTF8)) { char buffer[kBufsize]; snprintf(buffer, kBufsize, "%s:%d", host_buffer, port); proxy_strings->push_back(std::string(buffer)); } } CFRelease(dicRef); } #endif // Inspired by VLC source code // https://github.com/videolan/vlc/blob/master/src/posix/netconf.c #ifdef __linux__ posix_spawn_file_actions_t actions; posix_spawn_file_actions_init(&actions); posix_spawn_file_actions_addopen(&actions, STDIN_FILENO, "/dev/null", O_RDONLY, 0644); int fd[2]; posix_spawn_file_actions_adddup2(&actions, fd[1], STDOUT_FILENO); posix_spawnattr_t attr; posix_spawnattr_init(&attr); { sigset_t set; sigemptyset(&set); posix_spawnattr_setsigmask(&attr, &set); sigaddset(&set, SIGPIPE); posix_spawnattr_setsigdefault(&attr, &set); posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK); } pid_t pid; char *argv[3] = { const_cast<char *>("proxy"), const_cast<char *>(encoded_url.c_str()), NULL }; if (posix_spawnp(&pid, "proxy", &actions, &attr, argv, environ)) { pid = -1; } posix_spawnattr_destroy(&attr); posix_spawn_file_actions_destroy(&actions); close(fd[1]); if (-1 == pid) { close(fd[0]); return error("Failed to run proxy command"); } char buf[1024]; size_t len = 0; do { ssize_t val = read(fd[0], buf + len, sizeof (buf) - len); if (val <= 0) { break; } len += val; } while (len < sizeof (buf)); close(fd[0]); while (true) { int status = {0}; if (-1 != waitpid(pid, &status, 0)) { break; } } if (len >= 9 && !strncasecmp(buf, "direct://", 9)) { return noError; } char *end = (char *)memchr(buf, '\n', len); if (end != NULL) { *end = '\0'; proxy_strings->push_back(std::string(buf)); } #endif return noError; } error Netconf::ConfigureProxy( const std::string encoded_url, Poco::Net::HTTPSClientSession *session) { Poco::Logger &logger = Poco::Logger::get("ConfigureProxy"); std::string proxy_url(""); if (HTTPSClient::Config.AutodetectProxy) { if (Poco::Environment::has("HTTPS_PROXY")) { proxy_url = Poco::Environment::get("HTTPS_PROXY"); } if (Poco::Environment::has("https_proxy")) { proxy_url = Poco::Environment::get("https_proxy"); } if (Poco::Environment::has("HTTP_PROXY")) { proxy_url = Poco::Environment::get("HTTP_PROXY"); } if (Poco::Environment::has("http_proxy")) { proxy_url = Poco::Environment::get("http_proxy"); } if (proxy_url.empty()) { std::vector<std::string> proxy_strings; error err = autodetectProxy(encoded_url, &proxy_strings); if (err != noError) { return err; } if (!proxy_strings.empty()) { proxy_url = proxy_strings[0]; } } if (!proxy_url.empty()) { if (proxy_url.find("://") == std::string::npos) { proxy_url = "http://" + proxy_url; } Poco::URI proxy_uri(proxy_url); std::stringstream ss; ss << "Using proxy URI=" + proxy_uri.toString() << " host=" << proxy_uri.getHost() << " port=" << proxy_uri.getPort(); logger.debug(ss.str()); session->setProxy( proxy_uri.getHost(), proxy_uri.getPort()); if (!proxy_uri.getUserInfo().empty()) { Poco::Net::HTTPCredentials credentials; credentials.fromUserInfo(proxy_uri.getUserInfo()); session->setProxyCredentials( credentials.getUsername(), credentials.getPassword()); logger.debug("Proxy credentials detected username=" + credentials.getUsername()); } } } // Try to use user-configured proxy if (proxy_url.empty() && HTTPSClient::Config.UseProxy && HTTPSClient::Config.ProxySettings.IsConfigured()) { session->setProxy( HTTPSClient::Config.ProxySettings.Host(), static_cast<Poco::UInt16>( HTTPSClient::Config.ProxySettings.Port())); std::stringstream ss; ss << "Proxy configured " << " host=" << HTTPSClient::Config.ProxySettings.Host() << " port=" << HTTPSClient::Config.ProxySettings.Port(); logger.debug(ss.str()); if (HTTPSClient::Config.ProxySettings.HasCredentials()) { session->setProxyCredentials( HTTPSClient::Config.ProxySettings.Username(), HTTPSClient::Config.ProxySettings.Password()); logger.debug("Proxy credentials configured username=" + HTTPSClient::Config.ProxySettings.Username()); } } return noError; } } // namespace toggl
// Copyright 2015 Toggl Desktop developers. #include "../src/netconf.h" #include <string> #include <sstream> #include "./https_client.h" #include "Poco/Environment.h" #include "Poco/Logger.h" #include "Poco/Net/HTTPCredentials.h" #include "Poco/Net/HTTPSClientSession.h" #include "Poco/URI.h" #include "Poco/UnicodeConverter.h" #ifdef __MACH__ #include <CoreFoundation/CoreFoundation.h> // NOLINT #include <CoreServices/CoreServices.h> // NOLINT #endif #ifdef _WIN32 #include <winhttp.h> #pragma comment(lib, "winhttp") #endif #ifdef __linux__ #include <sys/types.h> #include <sys/wait.h> #include <spawn.h> #endif namespace toggl { error Netconf::autodetectProxy( const std::string encoded_url, std::vector<std::string> *proxy_strings) { poco_assert(proxy_strings); proxy_strings->clear(); if (encoded_url.empty()) { return noError; } #ifdef _WIN32 WINHTTP_CURRENT_USER_IE_PROXY_CONFIG ie_config = { 0 }; if (!WinHttpGetIEProxyConfigForCurrentUser(&ie_config)) { std::stringstream ss; ss << "WinHttpGetIEProxyConfigForCurrentUser error: " << GetLastError(); return ss.str(); } if (ie_config.lpszProxy) { std::wstring proxy_url_wide(ie_config.lpszProxy); std::string s(""); Poco::UnicodeConverter::toUTF8(proxy_url_wide, s); proxy_strings->push_back(s); } #endif // Inspired by VLC source code // https://github.com/videolan/vlc/blob/master/src/darwin/netconf.c #ifdef __MACH__ CFDictionaryRef dicRef = CFNetworkCopySystemProxySettings(); if (NULL != dicRef) { const CFStringRef proxyCFstr = (const CFStringRef)CFDictionaryGetValue( dicRef, (const void*)kCFNetworkProxiesHTTPProxy); const CFNumberRef portCFnum = (const CFNumberRef)CFDictionaryGetValue( dicRef, (const void*)kCFNetworkProxiesHTTPPort); if (NULL != proxyCFstr && NULL != portCFnum) { int port = 0; if (!CFNumberGetValue(portCFnum, kCFNumberIntType, &port)) { CFRelease(dicRef); return noError; } const std::size_t kBufsize(4096); char host_buffer[kBufsize]; memset(host_buffer, 0, sizeof(host_buffer)); if (CFStringGetCString(proxyCFstr, host_buffer, sizeof(host_buffer) - 1, kCFStringEncodingUTF8)) { char buffer[kBufsize]; snprintf(buffer, kBufsize, "%s:%d", host_buffer, port); proxy_strings->push_back(std::string(buffer)); } } CFRelease(dicRef); } #endif // Inspired by VLC source code // https://github.com/videolan/vlc/blob/master/src/posix/netconf.c #ifdef __linux__ posix_spawn_file_actions_t actions; posix_spawn_file_actions_init(&actions); posix_spawn_file_actions_addopen(&actions, STDIN_FILENO, "/dev/null", O_RDONLY, 0644); int fd[2]; posix_spawn_file_actions_adddup2(&actions, fd[1], STDOUT_FILENO); posix_spawnattr_t attr; posix_spawnattr_init(&attr); { sigset_t set; sigemptyset(&set); posix_spawnattr_setsigmask(&attr, &set); sigaddset(&set, SIGPIPE); posix_spawnattr_setsigdefault(&attr, &set); posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK); } pid_t pid; char *argv[3] = { const_cast<char *>("proxy"), const_cast<char *>(encoded_url.c_str()), NULL }; if (posix_spawnp(&pid, "proxy", &actions, &attr, argv, environ)) { pid = -1; } posix_spawnattr_destroy(&attr); posix_spawn_file_actions_destroy(&actions); close(fd[1]); if (-1 == pid) { close(fd[0]); return error("Failed to run proxy command"); } char buf[1024]; size_t len = 0; do { ssize_t val = read(fd[0], buf + len, sizeof (buf) - len); if (val <= 0) { break; } len += val; } while (len < sizeof (buf)); close(fd[0]); while (true) { int status = {0}; if (-1 != waitpid(pid, &status, 0)) { break; } } if (len >= 9 && !strncasecmp(buf, "direct://", 9)) { return noError; } char *end = <char *>(memchr(buf, '\n', len)); if (end != NULL) { *end = '\0'; proxy_strings->push_back(std::string(buf)); } #endif return noError; } error Netconf::ConfigureProxy( const std::string encoded_url, Poco::Net::HTTPSClientSession *session) { Poco::Logger &logger = Poco::Logger::get("ConfigureProxy"); std::string proxy_url(""); if (HTTPSClient::Config.AutodetectProxy) { if (Poco::Environment::has("HTTPS_PROXY")) { proxy_url = Poco::Environment::get("HTTPS_PROXY"); } if (Poco::Environment::has("https_proxy")) { proxy_url = Poco::Environment::get("https_proxy"); } if (Poco::Environment::has("HTTP_PROXY")) { proxy_url = Poco::Environment::get("HTTP_PROXY"); } if (Poco::Environment::has("http_proxy")) { proxy_url = Poco::Environment::get("http_proxy"); } if (proxy_url.empty()) { std::vector<std::string> proxy_strings; error err = autodetectProxy(encoded_url, &proxy_strings); if (err != noError) { return err; } if (!proxy_strings.empty()) { proxy_url = proxy_strings[0]; } } if (!proxy_url.empty()) { if (proxy_url.find("://") == std::string::npos) { proxy_url = "http://" + proxy_url; } Poco::URI proxy_uri(proxy_url); std::stringstream ss; ss << "Using proxy URI=" + proxy_uri.toString() << " host=" << proxy_uri.getHost() << " port=" << proxy_uri.getPort(); logger.debug(ss.str()); session->setProxy( proxy_uri.getHost(), proxy_uri.getPort()); if (!proxy_uri.getUserInfo().empty()) { Poco::Net::HTTPCredentials credentials; credentials.fromUserInfo(proxy_uri.getUserInfo()); session->setProxyCredentials( credentials.getUsername(), credentials.getPassword()); logger.debug("Proxy credentials detected username=" + credentials.getUsername()); } } } // Try to use user-configured proxy if (proxy_url.empty() && HTTPSClient::Config.UseProxy && HTTPSClient::Config.ProxySettings.IsConfigured()) { session->setProxy( HTTPSClient::Config.ProxySettings.Host(), static_cast<Poco::UInt16>( HTTPSClient::Config.ProxySettings.Port())); std::stringstream ss; ss << "Proxy configured " << " host=" << HTTPSClient::Config.ProxySettings.Host() << " port=" << HTTPSClient::Config.ProxySettings.Port(); logger.debug(ss.str()); if (HTTPSClient::Config.ProxySettings.HasCredentials()) { session->setProxyCredentials( HTTPSClient::Config.ProxySettings.Username(), HTTPSClient::Config.ProxySettings.Password()); logger.debug("Proxy credentials configured username=" + HTTPSClient::Config.ProxySettings.Username()); } } return noError; } } // namespace toggl
fix cast warning (lib)
fix cast warning (lib)
C++
bsd-3-clause
codeman38/toggldesktop,codeman38/toggldesktop,codeman38/toggldesktop,codeman38/toggldesktop,codeman38/toggldesktop,codeman38/toggldesktop
0a1d331483c8eb7b6952f5fb080b00a86dc8835b
telepathy-qml-lib/notificationmanager.cpp
telepathy-qml-lib/notificationmanager.cpp
/* * Copyright 2011 Intel Corporation. * * This program is licensed under the terms and conditions of the * Apache License, version 2.0. The full text of the Apache License is at * http://www.apache.org/licenses/LICENSE-2.0 */ #include "notificationmanager.h" #include "settingshelper.h" #include <QDebug> #include <QApplication> #include <MNotification> NotificationItem::~NotificationItem() { // no need to delete the pointer, QSharedPointer will take care of it } NotificationManager::NotificationManager(QObject *parent) : QObject(parent), mChatActive(0), mApplicationActive(true) { mAppWindow = QApplication::topLevelWidgets()[0]; } QString NotificationManager::currentAccount() const { return mCurrentAccount; } QString NotificationManager::currentContact() const { return mCurrentContact; } bool NotificationManager::chatActive() const { return mChatActive > 0; } bool NotificationManager::applicationActive() const { return mApplicationActive; } void NotificationManager::setCurrentAccount(const QString &account) { mCurrentAccount = account; qDebug() << "NOTIFICATION: current account is" << account; processNotifications(); } void NotificationManager::setCurrentContact(const QString &contact) { mCurrentContact = contact; qDebug() << "NOTIFICATION: current contact is" << contact; processNotifications(); } void NotificationManager::setChatActive(bool active) { if (active) mChatActive++; else mChatActive--; qDebug() << "NOTIFICATION: chat is active:" << (active!=0); processNotifications(); } void NotificationManager::setApplicationActive(bool active) { mApplicationActive = active; qDebug() << "NOTIFICATION: application is active:" << active; processNotifications(); } void NotificationManager::notifyPendingMessage(const QString &accountId, const QString &contactId, const QString &contactAlias, const QDateTime &time, const QString &message) { qDebug() << "Notifying a message from contact" << contactId; placeNotification(NotificationItem::PendingChatMessage, accountId, contactId, contactAlias, time, message); } void NotificationManager::notifyMissedCall(const QString &accountId, const QString &contactId, const QString &contactAlias, const QDateTime &time) { qDebug() << "Notifying a missed call from contact" << contactId; placeNotification(NotificationItem::MissedCall, accountId, contactId, contactAlias, time); } void NotificationManager::notifyMissedVideoCall(const QString &accountId, const QString &contactId, const QString &contactAlias, const QDateTime &time) { qDebug() << "Notifying a missed video call from contact" << contactId; placeNotification(NotificationItem::MissedVideoCall, accountId, contactId, contactAlias, time); } void NotificationManager::notifyIncomingFileTransfer(const QString &accountId, const QString &contactId, const QString &contactAlias, const QDateTime &time, const QString &fileName) { qDebug() << "Notifying an incoming file transfer from contact" << contactId; placeNotification(NotificationItem::IncomingFileTransfer, accountId, contactId, contactAlias, time, tr("%1 is sending you the file %2").arg(contactAlias, fileName)); } void NotificationManager::notifyIncomingCall(const QString &accountId, const QString &contactId, const QString &contactAlias, const QString &image) { NotificationItem notification; notification.type = NotificationItem::IncomingCall; notification.accountId = accountId; notification.contactId = contactId; notification.message = tr("%1 is calling you").arg(contactAlias); notification.item = QSharedPointer<MNotification>(new MNotification(MNotification::ImIncomingVideoChat, contactAlias, notification.message)); QList<QVariant> args; args << accountId << contactId; notification.item->setAction(MRemoteAction("com.meego.app.imapprover", "/com/meego/app/imapprover", "com.meego.app.imapprover", "acceptCall", args)); QString icon("image://themedimage/widgets/apps/chat/"); if (!image.isNull()) { notification.item->setImage(image); } else { notification.item->setImage(icon + "call-fullscreen-default"); } notification.item->publish(); mCallNotifications.append(notification); } void NotificationManager::processNotifications() { // if the application is not active, we should notify everything // so not removing anything from the list if (!mApplicationActive) { return; } // if there is an active chat, we should remove all notifications // of the contact in the chat if (mChatActive) { // Remove all notifications for the contact we are chatting to QList<NotificationItem>::iterator it = mNotifications.begin(); while (it != mNotifications.end()) { if ((*it).accountId == mCurrentAccount && (*it).contactId == mCurrentContact) { (*it).item->remove(); it = mNotifications.erase(it); } else { ++it; } } return; } // if there is no active chat, we should remove notifications from the current account if (!mCurrentAccount.isEmpty()) { QList<NotificationItem>::iterator it = mNotifications.begin(); while (it != mNotifications.end()) { if ((*it).accountId == mCurrentAccount) { (*it).item->remove(); it = mNotifications.erase(it); } else { ++it; } } return; } // that's all folks } void NotificationManager::placeNotification(NotificationItem::NotificationType type, const QString &accountId, const QString &contactId, const QString &contactAlias, const QDateTime &time, const QString &message) { int eventCount = 0; // TODO: check how we are supposed to use the time in the notifications Q_UNUSED(time) // if the user configured the option not to receive notifications, we should respect that if (!SettingsHelper::self()->enableNotifications()) { return; } // remove previous notifications from that contact QList<NotificationItem>::iterator it = mNotifications.begin(); while (it != mNotifications.end()) { if ((*it).accountId == accountId && (*it).contactId == contactId) { eventCount = (*it).item->count(); (*it).item->remove(); it = mNotifications.erase(it); } else { ++it; } } // increate the event counter eventCount++; // if the application is currently active, we have to meet all the conditions // for displaying the notification if (mApplicationActive) { // if there is an active chat, we should not place notifications of that chat if (mChatActive && accountId == mCurrentAccount && contactId == mCurrentContact) { return; } // now if there is no chat active, we should only place // notifications of other accounts if (!mChatActive && accountId == mCurrentAccount) { return; } } // check all the conditions before setting up a notification NotificationItem notification; notification.type = type; notification.accountId = accountId; notification.contactId = contactId; notification.message = message; notification.item = QSharedPointer<MNotification>(new MNotification(MNotification::ImEvent, contactAlias, message)); QList<QVariant> args; args << accountId << contactId; notification.item->setAction(MRemoteAction("com.meego.app.im", "/com/meego/app/im", "com.meego.app.im", "showChat", args)); notification.item->setCount(eventCount); QString icon("image://themedimage/widgets/apps/chat/"); switch (type) { case NotificationItem::IncomingFileTransfer: case NotificationItem::PendingChatMessage: notification.item->setImage(icon + "message-unread"); break; case NotificationItem::MissedCall: notification.item->setImage(icon + "call-audio-missed"); break; case NotificationItem::MissedVideoCall: notification.item->setImage(icon + "call-video-missed"); break; } notification.item->publish(); mNotifications.append(notification); } void NotificationManager::clear() { foreach (NotificationItem notification, mNotifications) { notification.item->remove(); } mNotifications.clear(); }
/* * Copyright 2011 Intel Corporation. * * This program is licensed under the terms and conditions of the * Apache License, version 2.0. The full text of the Apache License is at * http://www.apache.org/licenses/LICENSE-2.0 */ #include "notificationmanager.h" #include "settingshelper.h" #include <QDebug> #include <QApplication> #include <MNotification> NotificationItem::~NotificationItem() { // no need to delete the pointer, QSharedPointer will take care of it } NotificationManager::NotificationManager(QObject *parent) : QObject(parent), mChatActive(0), mApplicationActive(true) { mAppWindow = QApplication::topLevelWidgets()[0]; } QString NotificationManager::currentAccount() const { return mCurrentAccount; } QString NotificationManager::currentContact() const { return mCurrentContact; } bool NotificationManager::chatActive() const { return mChatActive > 0; } bool NotificationManager::applicationActive() const { return mApplicationActive; } void NotificationManager::setCurrentAccount(const QString &account) { mCurrentAccount = account; qDebug() << "NOTIFICATION: current account is" << account; processNotifications(); } void NotificationManager::setCurrentContact(const QString &contact) { mCurrentContact = contact; qDebug() << "NOTIFICATION: current contact is" << contact; processNotifications(); } void NotificationManager::setChatActive(bool active) { if (active) mChatActive++; else mChatActive--; qDebug() << "NOTIFICATION: chat is active:" << (active!=0); processNotifications(); } void NotificationManager::setApplicationActive(bool active) { mApplicationActive = active; qDebug() << "NOTIFICATION: application is active:" << active; processNotifications(); } void NotificationManager::notifyPendingMessage(const QString &accountId, const QString &contactId, const QString &contactAlias, const QDateTime &time, const QString &message) { qDebug() << "Notifying a message from contact" << contactId; placeNotification(NotificationItem::PendingChatMessage, accountId, contactId, contactAlias, time, message); } void NotificationManager::notifyMissedCall(const QString &accountId, const QString &contactId, const QString &contactAlias, const QDateTime &time) { qDebug() << "Notifying a missed call from contact" << contactId; placeNotification(NotificationItem::MissedCall, accountId, contactId, contactAlias, time); } void NotificationManager::notifyMissedVideoCall(const QString &accountId, const QString &contactId, const QString &contactAlias, const QDateTime &time) { qDebug() << "Notifying a missed video call from contact" << contactId; placeNotification(NotificationItem::MissedVideoCall, accountId, contactId, contactAlias, time); } void NotificationManager::notifyIncomingFileTransfer(const QString &accountId, const QString &contactId, const QString &contactAlias, const QDateTime &time, const QString &fileName) { qDebug() << "Notifying an incoming file transfer from contact" << contactId; placeNotification(NotificationItem::IncomingFileTransfer, accountId, contactId, contactAlias, time, tr("%1 is sending you the file %2").arg(contactAlias, fileName)); } void NotificationManager::notifyIncomingCall(const QString &accountId, const QString &contactId, const QString &contactAlias, const QString &image) { NotificationItem notification; notification.type = NotificationItem::IncomingCall; notification.accountId = accountId; notification.contactId = contactId; notification.message = tr("%1 is calling you").arg(contactAlias); notification.item = QSharedPointer<MNotification>(new MNotification(MNotification::ImIncomingVideoChat, contactAlias, notification.message)); QList<QVariant> args; args << accountId << contactId; notification.item->setAction(MRemoteAction("com.meego.app.imapprover", "/com/meego/app/imapprover", "com.meego.app.imapprover", "acceptCall", args)); QString icon("image://themedimage/widgets/apps/chat/"); if (!image.isNull()) { notification.item->setImage(image); } else { notification.item->setImage(icon + "call-fullscreen-default"); } notification.item->publish(); mCallNotifications.append(notification); } void NotificationManager::processNotifications() { // if the application is not active, we should notify everything // so not removing anything from the list if (!mApplicationActive) { return; } // if there is an active chat, we should remove all notifications // of the contact in the chat if (mChatActive) { // Remove all notifications for the contact we are chatting to QList<NotificationItem>::iterator it = mNotifications.begin(); while (it != mNotifications.end()) { if ((*it).accountId == mCurrentAccount && (*it).contactId == mCurrentContact) { (*it).item->remove(); it = mNotifications.erase(it); } else { ++it; } } return; } // if there is no active chat, we should remove notifications from the current account if (!mCurrentAccount.isEmpty()) { QList<NotificationItem>::iterator it = mNotifications.begin(); while (it != mNotifications.end()) { if ((*it).accountId == mCurrentAccount) { (*it).item->remove(); it = mNotifications.erase(it); } else { ++it; } } return; } // that's all folks } void NotificationManager::placeNotification(NotificationItem::NotificationType type, const QString &accountId, const QString &contactId, const QString &contactAlias, const QDateTime &time, const QString &message) { int eventCount = 0; // TODO: check how we are supposed to use the time in the notifications Q_UNUSED(time) // if the user configured the option not to receive notifications, we should respect that if (!SettingsHelper::self()->enableNotifications()) { return; } // remove previous notifications from that contact QList<NotificationItem>::iterator it = mNotifications.begin(); while (it != mNotifications.end()) { if ((*it).accountId == accountId && (*it).contactId == contactId) { eventCount = (*it).item->count(); (*it).item->remove(); it = mNotifications.erase(it); } else { ++it; } } // increate the event counter eventCount++; // if the application is currently active, we have to meet all the conditions // for displaying the notification if (mApplicationActive) { // if there is an active chat, we should not place notifications of that chat if (mChatActive && accountId == mCurrentAccount && contactId == mCurrentContact) { return; } // now if there is no chat active, we should only place // notifications of other accounts if (!mChatActive && accountId == mCurrentAccount) { return; } } // check all the conditions before setting up a notification NotificationItem notification; notification.type = type; notification.accountId = accountId; notification.contactId = contactId; notification.message = message; notification.item = QSharedPointer<MNotification>(new MNotification(MNotification::ImEvent, contactAlias, message)); QList<QVariant> args; args << accountId << contactId; notification.item->setAction(MRemoteAction("com.meego.app.im", "/com/meego/app/im", "com.meego.app.im", "showChat", args)); notification.item->setCount(eventCount); QString icon("image://themedimage/widgets/apps/chat/"); switch (type) { case NotificationItem::IncomingFileTransfer: case NotificationItem::PendingChatMessage: notification.item->setImage(icon + "message-unread"); break; case NotificationItem::MissedCall: notification.item->setImage(icon + "call-audio-missed"); break; case NotificationItem::MissedVideoCall: notification.item->setImage(icon + "call-video-missed"); break; default: break; } notification.item->publish(); mNotifications.append(notification); } void NotificationManager::clear() { foreach (NotificationItem notification, mNotifications) { notification.item->remove(); } mNotifications.clear(); }
Remove warning in switch
Remove warning in switch
C++
apache-2.0
meego-tablet-ux/meego-app-im,meego-tablet-ux/meego-app-im
ed5c768bc2810c43dbd92c727c33aa82e420d588
test/test_info.cc
test/test_info.cc
#define BOOST_TEST_MODULE info #include <boost/test/included/unit_test.hpp> #include <mpl/mpl.hpp> BOOST_AUTO_TEST_CASE(info) { [[maybe_unused]] const mpl::communicator &comm_world{mpl::environment::comm_world()}; mpl::info info_1; BOOST_TEST(info_1.size() == 0); info_1.set("Douglas Adams", "The Hitchhiker's Guide to the Galaxy"); info_1.set("Isaac Asimov", "Nightfall"); BOOST_TEST(info_1.size() == 2); BOOST_TEST(info_1.value("Isaac Asimov").value() == "Nightfall"); mpl::info info_2{info_1}; BOOST_TEST(info_1.size() == 2); BOOST_TEST(info_2.value("Isaac Asimov").value() == "Nightfall"); }
#define BOOST_TEST_MODULE info #include <boost/test/included/unit_test.hpp> #include <mpl/mpl.hpp> BOOST_AUTO_TEST_CASE(info) { [[maybe_unused]] const mpl::communicator &comm_world{mpl::environment::comm_world()}; mpl::info info_1; BOOST_TEST(info_1.size() == 0); info_1.set("Douglas Adams", "The Hitchhiker's Guide to the Galaxy"); info_1.set("Isaac Asimov", "Nightfall"); BOOST_TEST(info_1.size() == 2); BOOST_TEST(info_1.value("Isaac Asimov").value() == "Nightfall"); mpl::info info_2{info_1}; BOOST_TEST(info_1.size() == 2); BOOST_TEST(info_2.value("Isaac Asimov").value() == "Nightfall"); BOOST_TEST(not info_2.value("no such thing")); }
extend test_info.cc
extend test_info.cc
C++
bsd-3-clause
rabauke/mpl
f7c6d9ce6c82fb619a5c5e10a424c55c9bec8ae8
test/test_utp.cpp
test/test_utp.cpp
/* Copyright (c) 2008, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/session.hpp" #include "libtorrent/session_settings.hpp" #include "libtorrent/hasher.hpp" #include "libtorrent/alert_types.hpp" #include "libtorrent/bencode.hpp" #include "libtorrent/thread.hpp" #include "libtorrent/time.hpp" #include "libtorrent/file.hpp" #include <boost/tuple/tuple.hpp> #include <boost/bind.hpp> #include "test.hpp" #include "setup_transfer.hpp" #include <fstream> #include <iostream> using namespace libtorrent; using boost::tuples::ignore; void test_transfer() { // in case the previous run was terminated error_code ec; remove_all("./tmp1_utp", ec); remove_all("./tmp2_utp", ec); session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48885, 49930), "0.0.0.0", 0); session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49885, 50930), "0.0.0.0", 0); session_settings sett; sett.enable_outgoing_tcp = false; sett.min_reconnect_time = 1; sett.announce_to_all_trackers = true; sett.announce_to_all_tiers = true; // make sure we announce to both http and udp trackers sett.prefer_udp_trackers = false; // for performance testing // sett.disable_hash_checks = true; // sett.utp_delayed_ack = 0; // disable this to use regular size packets over loopback // sett.utp_dynamic_sock_buf = false; ses1.set_settings(sett); ses2.set_settings(sett); #ifndef TORRENT_DISABLE_ENCRYPTION pe_settings pes; pes.out_enc_policy = pe_settings::disabled; pes.in_enc_policy = pe_settings::disabled; ses1.set_pe_settings(pes); ses2.set_pe_settings(pes); #endif torrent_handle tor1; torrent_handle tor2; create_directory("./tmp1_utp", ec); std::ofstream file("./tmp1_utp/temporary"); boost::intrusive_ptr<torrent_info> t = ::create_torrent(&file, 512 * 1024, 20, false); file.close(); // for performance testing add_torrent_params atp; // atp.storage = &disabled_storage_constructor; // test using piece sizes smaller than 16kB boost::tie(tor1, tor2, ignore) = setup_transfer(&ses1, &ses2, 0 , true, false, true, "_utp", 0, &t, false, &atp); for (int i = 0; i < 300; ++i) { print_alerts(ses1, "ses1", true, true, true); print_alerts(ses2, "ses2", true, true, true); torrent_status st1 = tor1.status(); torrent_status st2 = tor2.status(); std::cerr << "\033[32m" << int(st1.download_payload_rate / 1000.f) << "kB/s " << "\033[33m" << int(st1.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st1.progress * 100) << "% " << st1.num_peers << ": " << "\033[32m" << int(st2.download_payload_rate / 1000.f) << "kB/s " << "\033[31m" << int(st2.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st2.progress * 100) << "% " << st2.num_peers << " cc: " << st2.connect_candidates << std::endl; if (st2.is_finished) break; test_sleep(500); TEST_CHECK(st1.state == torrent_status::seeding || st1.state == torrent_status::checking_files); TEST_CHECK(st2.state == torrent_status::downloading); } TEST_CHECK(tor1.status().is_finished); TEST_CHECK(tor2.status().is_finished); } int test_main() { using namespace libtorrent; test_transfer(); error_code ec; remove_all("./tmp1_utp", ec); remove_all("./tmp2_utp", ec); return 0; }
/* Copyright (c) 2008, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/session.hpp" #include "libtorrent/session_settings.hpp" #include "libtorrent/hasher.hpp" #include "libtorrent/alert_types.hpp" #include "libtorrent/bencode.hpp" #include "libtorrent/thread.hpp" #include "libtorrent/time.hpp" #include "libtorrent/file.hpp" #include <boost/tuple/tuple.hpp> #include <boost/bind.hpp> #include "test.hpp" #include "setup_transfer.hpp" #include <fstream> #include <iostream> using namespace libtorrent; using boost::tuples::ignore; void test_transfer() { // in case the previous run was terminated error_code ec; remove_all("./tmp1_utp", ec); remove_all("./tmp2_utp", ec); session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48885, 49930), "0.0.0.0", 0); session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49885, 50930), "0.0.0.0", 0); session_settings sett; sett.enable_outgoing_tcp = false; sett.min_reconnect_time = 1; sett.announce_to_all_trackers = true; sett.announce_to_all_tiers = true; // make sure we announce to both http and udp trackers sett.prefer_udp_trackers = false; // for performance testing // sett.disable_hash_checks = true; // sett.utp_delayed_ack = 0; // disable this to use regular size packets over loopback // sett.utp_dynamic_sock_buf = false; ses1.set_settings(sett); ses2.set_settings(sett); #ifndef TORRENT_DISABLE_ENCRYPTION pe_settings pes; pes.out_enc_policy = pe_settings::disabled; pes.in_enc_policy = pe_settings::disabled; ses1.set_pe_settings(pes); ses2.set_pe_settings(pes); #endif torrent_handle tor1; torrent_handle tor2; create_directory("./tmp1_utp", ec); std::ofstream file("./tmp1_utp/temporary"); boost::intrusive_ptr<torrent_info> t = ::create_torrent(&file, 512 * 1024, 20, false); file.close(); // for performance testing add_torrent_params atp; // atp.storage = &disabled_storage_constructor; // test using piece sizes smaller than 16kB boost::tie(tor1, tor2, ignore) = setup_transfer(&ses1, &ses2, 0 , true, false, true, "_utp", 0, &t, false, &atp); for (int i = 0; i < 300; ++i) { print_alerts(ses1, "ses1", true, true, true); print_alerts(ses2, "ses2", true, true, true); test_sleep(500); torrent_status st1 = tor1.status(); torrent_status st2 = tor2.status(); std::cerr << "\033[32m" << int(st1.download_payload_rate / 1000.f) << "kB/s " << "\033[33m" << int(st1.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st1.progress * 100) << "% " << st1.num_peers << ": " << "\033[32m" << int(st2.download_payload_rate / 1000.f) << "kB/s " << "\033[31m" << int(st2.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st2.progress * 100) << "% " << st2.num_peers << " cc: " << st2.connect_candidates << std::endl; if (st2.is_finished) break; TEST_CHECK(st1.state == torrent_status::seeding || st1.state == torrent_status::checking_files); TEST_CHECK(st2.state == torrent_status::downloading); } TEST_CHECK(tor1.status().is_finished); TEST_CHECK(tor2.status().is_finished); } int test_main() { using namespace libtorrent; test_transfer(); error_code ec; remove_all("./tmp1_utp", ec); remove_all("./tmp2_utp", ec); return 0; }
make test_utp more likely to pass
make test_utp more likely to pass
C++
bsd-3-clause
jpetso/libtorrent,jpetso/libtorrent,jpetso/libtorrent,jpetso/libtorrent
2c382f53d4e63646b4ff0e1d83067e594c2ab51f
tensorflow/core/kernels/mkl_softmax_op.cc
tensorflow/core/kernels/mkl_softmax_op.cc
/* Copyright 2015 The TensorFlow 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. ==============================================================================*/ // See docs in ../ops/nn_ops.cc. #ifdef INTEL_MKL #ifndef INTEL_MKL_ML_ONLY #include "tensorflow/core/framework/numeric_op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/util/tensor_format.h" #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" #include "tensorflow/core/util/mkl_util.h" #include "mkldnn.hpp" using mkldnn::prop_kind; using mkldnn::softmax_forward; using mkldnn::stream; namespace tensorflow { typedef Eigen::ThreadPoolDevice CPUDevice; template <typename Device, typename T> class MklSoftmaxOp : public OpKernel { public: ~MklSoftmaxOp() {} explicit MklSoftmaxOp(OpKernelConstruction *context) : OpKernel(context) {} void Compute(OpKernelContext *context) override { try { auto cpu_engine = engine(engine::cpu, 0); // src_tensor now points to the 0-th input of global data struct "context" size_t src_idx = 0; const Tensor &src_tensor = MklGetInput(context, src_idx); // Add: get MklShape MklDnnShape src_mkl_shape; GetMklShape(context, src_idx, &src_mkl_shape); // src_dims is the dimenstion of src_tensor // dim of the dst will also be same as src_dims auto src_tf_shape = src_mkl_shape.IsMklTensor() ? src_mkl_shape.GetTfShape() : src_tensor.shape(); const int input_dims = src_tf_shape.dims(); auto src_dims = TFShapeToMklDnnDims(src_tf_shape); memory::dims output_dims; int axis; if (src_mkl_shape.IsMklTensor()) { axis = 1; output_dims = src_mkl_shape.GetSizesAsMklDnnDims(); } else { axis = input_dims - 1; output_dims = src_dims; } memory::format layout_type; // In MKL, data format passed to mkl softmax op depends on dimension of // the input tensor. // Here "x" data format in MKL is used for 1 dim tensor, "nc" for 2 dim // tensor, // "tnc" for 3 dim tensor, "nchw" for 4 dim tensor, and "ncdhw" for 5 dim // tensor. // Each of the simbols has the following meaning: // n = batch, c = channels, t = sequence lenght, h = height, // w = width, d = depth switch (input_dims) { case 1: layout_type = memory::format::x; break; case 2: layout_type = memory::format::nc; break; case 3: layout_type = memory::format::tnc; break; case 4: if (src_mkl_shape.IsMklTensor()) { layout_type = memory::format::nhwc; } else { layout_type = memory::format::nchw; } break; case 5: if (src_mkl_shape.IsMklTensor()) { layout_type = memory::format::ndhwc; } else { layout_type = memory::format::ncdhw; } break; default: OP_REQUIRES_OK(context, errors::Aborted("Input dims must be <= 5 and >=1")); return; } // Create softmax memory for src, dst: both are defined in mkl_util.h, // they are wrapper MklDnnData<T> src(&cpu_engine); MklDnnData<T> dst(&cpu_engine); // If input is in MKL layout, then simply grab input layout; otherwise, // construct input Tf layout. For TF layout, although input shape // (src_dims) required is in MKL-DNN order, the layout is Tensorflow's // layout auto src_md = src_mkl_shape.IsMklTensor() ? src_mkl_shape.GetMklLayout() : memory::desc(src_dims, MklDnnType<T>(), layout_type); // src: setting memory descriptor // following functions are in mkl_util.h src.SetUsrMem(src_md, &src_tensor); // creating a memory descriptor auto softmax_fwd_desc = softmax_forward::desc(prop_kind::forward_scoring, src.GetUsrMemDesc(), axis); auto softmax_fwd_pd = softmax_forward::primitive_desc(softmax_fwd_desc, cpu_engine); // add: output Tensor *output_tensor = nullptr; MklDnnShape output_mkl_shape; TensorShape output_tf_shape; // shape of output TF tensor. // Softmax MklDnn output layout is same as input layout. auto dst_pd = src.GetUsrMemPrimDesc(); // if input is MKL shape, output is also MKL shape. // if input is TF shape, output is also TF shape if (src_mkl_shape.IsMklTensor()) { output_mkl_shape.SetMklTensor(true); output_mkl_shape.SetMklLayout(&dst_pd); output_mkl_shape.SetElemType(MklDnnType<T>()); output_mkl_shape.SetTfLayout(output_dims.size(), output_dims, layout_type); output_tf_shape.AddDim((dst_pd.get_size() / sizeof(T))); } else { // then output is also TF shape output_mkl_shape.SetMklTensor(false); output_tf_shape = MklDnnDimsToTFShape(output_dims); } // Allocate output shape (MKL or TF based on the above) AllocateOutputSetMklShape(context, 0, &output_tensor, output_tf_shape, output_mkl_shape); // Output_dims and input_dims are same dst.SetUsrMem(src_md, output_tensor); // finally creating the "softmax op" using the primitive descriptor, src // and dst auto softmax_fwd = softmax_forward(softmax_fwd_pd, src.GetOpMem(), dst.GetOpMem()); // execute net (pushing to the stream) // following 3 are common for all mkl dnn ops std::vector<primitive> net; net.push_back(softmax_fwd); stream(stream::kind::eager).submit(net).wait(); } catch (mkldnn::error &e) { string error_msg = "Status: " + std::to_string(e.status) + ", message: " + string(e.message) + ", in file " + string(__FILE__) + ":" + std::to_string(__LINE__); OP_REQUIRES_OK( context, errors::Aborted("Operation received an exception:", error_msg)); } } }; /* Register DNN kernels for supported operations and supported types - right now * it is only Softmax and f32 */ #define REGISTER_SOFTMAX_MKL_SUPPORTED_KERNELS_TYPES(type) \ REGISTER_KERNEL_BUILDER(Name("_MklSoftmax") \ .Device(DEVICE_CPU) \ .TypeConstraint<type>("T") \ .Label(mkl_op_registry::kMklOpLabel), \ MklSoftmaxOp<CPUDevice, type>); TF_CALL_float(REGISTER_SOFTMAX_MKL_SUPPORTED_KERNELS_TYPES); } // namespace tensorflow #endif // INTEL_MKL_ML_ONLY #endif // INTEL_MKL
/* Copyright 2015 The TensorFlow 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. ==============================================================================*/ // See docs in ../ops/nn_ops.cc. #ifdef INTEL_MKL #ifndef INTEL_MKL_ML_ONLY #include "tensorflow/core/framework/numeric_op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/util/tensor_format.h" #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" #include "tensorflow/core/util/mkl_util.h" #include "mkldnn.hpp" using mkldnn::prop_kind; using mkldnn::softmax_forward; using mkldnn::stream; namespace tensorflow { typedef Eigen::ThreadPoolDevice CPUDevice; template <typename Device, typename T> class MklSoftmaxOp : public OpKernel { public: ~MklSoftmaxOp() {} explicit MklSoftmaxOp(OpKernelConstruction* context) : OpKernel(context) {} void Compute(OpKernelContext* context) override { try { auto cpu_engine = engine(engine::cpu, 0); // src_tensor now points to the 0-th input of global data struct "context" size_t src_idx = 0; const Tensor& src_tensor = MklGetInput(context, src_idx); // Add: get MklShape MklDnnShape src_mkl_shape; GetMklShape(context, src_idx, &src_mkl_shape); // src_dims is the dimenstion of src_tensor // dim of the dst will also be same as src_dims auto src_tf_shape = src_mkl_shape.IsMklTensor() ? src_mkl_shape.GetTfShape() : src_tensor.shape(); const int input_dims = src_tf_shape.dims(); auto src_dims = TFShapeToMklDnnDims(src_tf_shape); memory::dims output_dims; int axis; if (src_mkl_shape.IsMklTensor()) { axis = 1; output_dims = src_mkl_shape.GetSizesAsMklDnnDims(); } else { axis = input_dims - 1; output_dims = src_dims; } memory::format layout_type; // In MKL, data format passed to mkl softmax op depends on dimension of // the input tensor. // Here "x" data format in MKL is used for 1 dim tensor, "nc" for 2 dim // tensor, // "tnc" for 3 dim tensor, "nchw" for 4 dim tensor, and "ncdhw" for 5 dim // tensor. // Each of the simbols has the following meaning: // n = batch, c = channels, t = sequence lenght, h = height, // w = width, d = depth switch (input_dims) { case 1: layout_type = memory::format::x; break; case 2: layout_type = memory::format::nc; break; case 3: layout_type = memory::format::tnc; break; case 4: if (src_mkl_shape.IsMklTensor()) { layout_type = memory::format::nhwc; } else { layout_type = memory::format::nchw; } break; case 5: if (src_mkl_shape.IsMklTensor()) { layout_type = memory::format::ndhwc; } else { layout_type = memory::format::ncdhw; } break; default: OP_REQUIRES_OK(context, errors::Aborted("Input dims must be <= 5 and >=1")); return; } // Create softmax memory for src, dst: both are defined in mkl_util.h, // they are wrapper MklDnnData<T> src(&cpu_engine); MklDnnData<T> dst(&cpu_engine); // If input is in MKL layout, then simply grab input layout; otherwise, // construct input Tf layout. For TF layout, although input shape // (src_dims) required is in MKL-DNN order, the layout is Tensorflow's // layout auto src_md = src_mkl_shape.IsMklTensor() ? src_mkl_shape.GetMklLayout() : memory::desc(src_dims, MklDnnType<T>(), layout_type); // src: setting memory descriptor // following functions are in mkl_util.h src.SetUsrMem(src_md, &src_tensor); // creating a memory descriptor auto softmax_fwd_desc = softmax_forward::desc(prop_kind::forward_scoring, src.GetUsrMemDesc(), axis); auto softmax_fwd_pd = softmax_forward::primitive_desc(softmax_fwd_desc, cpu_engine); // add: output Tensor* output_tensor = nullptr; MklDnnShape output_mkl_shape; TensorShape output_tf_shape; // shape of output TF tensor. // Softmax MklDnn output layout is same as input layout. auto dst_pd = src.GetUsrMemPrimDesc(); // if input is MKL shape, output is also MKL shape. // if input is TF shape, output is also TF shape if (src_mkl_shape.IsMklTensor()) { output_mkl_shape.SetMklTensor(true); output_mkl_shape.SetMklLayout(&dst_pd); output_mkl_shape.SetElemType(MklDnnType<T>()); output_mkl_shape.SetTfLayout(output_dims.size(), output_dims, layout_type); output_tf_shape.AddDim((dst_pd.get_size() / sizeof(T))); } else { // then output is also TF shape output_mkl_shape.SetMklTensor(false); output_tf_shape = MklDnnDimsToTFShape(output_dims); } // Allocate output shape (MKL or TF based on the above) AllocateOutputSetMklShape(context, 0, &output_tensor, output_tf_shape, output_mkl_shape); // Output_dims and input_dims are same dst.SetUsrMem(src_md, output_tensor); // finally creating the "softmax op" using the primitive descriptor, src // and dst auto softmax_fwd = softmax_forward(softmax_fwd_pd, src.GetOpMem(), dst.GetOpMem()); // execute net (pushing to the stream) // following 3 are common for all mkl dnn ops std::vector<primitive> net; net.push_back(softmax_fwd); stream(stream::kind::eager).submit(net).wait(); } catch (mkldnn::error& e) { string error_msg = "Status: " + std::to_string(e.status) + ", message: " + string(e.message) + ", in file " + string(__FILE__) + ":" + std::to_string(__LINE__); OP_REQUIRES_OK( context, errors::Aborted("Operation received an exception:", error_msg)); } } }; /* Register DNN kernels for supported operations and supported types - right now * it is only Softmax and f32 */ #define REGISTER_SOFTMAX_MKL_SUPPORTED_KERNELS_TYPES(type) \ REGISTER_KERNEL_BUILDER(Name("_MklSoftmax") \ .Device(DEVICE_CPU) \ .TypeConstraint<type>("T") \ .Label(mkl_op_registry::kMklOpLabel), \ MklSoftmaxOp<CPUDevice, type>); TF_CALL_float(REGISTER_SOFTMAX_MKL_SUPPORTED_KERNELS_TYPES); } // namespace tensorflow #endif // INTEL_MKL_ML_ONLY #endif // INTEL_MKL
fix clang format
fix clang format Change-Id: Iabc5524dc0858611d4a43b2f8992ec2f397d386e
C++
apache-2.0
adit-chandra/tensorflow,ageron/tensorflow,aam-at/tensorflow,hfp/tensorflow-xsmm,tensorflow/tensorflow-pywrap_tf_optimizer,hfp/tensorflow-xsmm,apark263/tensorflow,tensorflow/tensorflow-pywrap_saved_model,yongtang/tensorflow,jbedorf/tensorflow,jhseu/tensorflow,arborh/tensorflow,freedomtan/tensorflow,cxxgtxy/tensorflow,arborh/tensorflow,tensorflow/tensorflow,kevin-coder/tensorflow-fork,petewarden/tensorflow,davidzchen/tensorflow,hfp/tensorflow-xsmm,sarvex/tensorflow,xzturn/tensorflow,theflofly/tensorflow,tensorflow/tensorflow,asimshankar/tensorflow,annarev/tensorflow,chemelnucfin/tensorflow,chemelnucfin/tensorflow,tensorflow/tensorflow,arborh/tensorflow,ageron/tensorflow,theflofly/tensorflow,ghchinoy/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,aldian/tensorflow,kevin-coder/tensorflow-fork,jhseu/tensorflow,kevin-coder/tensorflow-fork,gunan/tensorflow,jbedorf/tensorflow,xzturn/tensorflow,freedomtan/tensorflow,jbedorf/tensorflow,theflofly/tensorflow,kevin-coder/tensorflow-fork,chemelnucfin/tensorflow,Intel-tensorflow/tensorflow,gautam1858/tensorflow,aam-at/tensorflow,jendap/tensorflow,sarvex/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-tensorflow/tensorflow,asimshankar/tensorflow,paolodedios/tensorflow,paolodedios/tensorflow,ghchinoy/tensorflow,xzturn/tensorflow,chemelnucfin/tensorflow,alsrgv/tensorflow,arborh/tensorflow,aam-at/tensorflow,cxxgtxy/tensorflow,tensorflow/tensorflow-pywrap_saved_model,asimshankar/tensorflow,gautam1858/tensorflow,annarev/tensorflow,karllessard/tensorflow,alsrgv/tensorflow,adit-chandra/tensorflow,asimshankar/tensorflow,gautam1858/tensorflow,yongtang/tensorflow,gunan/tensorflow,chemelnucfin/tensorflow,hfp/tensorflow-xsmm,apark263/tensorflow,theflofly/tensorflow,alsrgv/tensorflow,ghchinoy/tensorflow,freedomtan/tensorflow,arborh/tensorflow,petewarden/tensorflow,aam-at/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Bismarrck/tensorflow,tensorflow/tensorflow-pywrap_saved_model,adit-chandra/tensorflow,alsrgv/tensorflow,theflofly/tensorflow,annarev/tensorflow,karllessard/tensorflow,jendap/tensorflow,adit-chandra/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_tf_optimizer,frreiss/tensorflow-fred,jendap/tensorflow,alsrgv/tensorflow,jhseu/tensorflow,petewarden/tensorflow,ageron/tensorflow,xzturn/tensorflow,kevin-coder/tensorflow-fork,karllessard/tensorflow,annarev/tensorflow,alsrgv/tensorflow,jendap/tensorflow,ageron/tensorflow,aam-at/tensorflow,xzturn/tensorflow,paolodedios/tensorflow,aldian/tensorflow,theflofly/tensorflow,jhseu/tensorflow,apark263/tensorflow,jendap/tensorflow,paolodedios/tensorflow,Intel-tensorflow/tensorflow,paolodedios/tensorflow,ghchinoy/tensorflow,paolodedios/tensorflow,chemelnucfin/tensorflow,freedomtan/tensorflow,paolodedios/tensorflow,apark263/tensorflow,renyi533/tensorflow,freedomtan/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,paolodedios/tensorflow,yongtang/tensorflow,yongtang/tensorflow,alsrgv/tensorflow,apark263/tensorflow,renyi533/tensorflow,DavidNorman/tensorflow,frreiss/tensorflow-fred,jendap/tensorflow,karllessard/tensorflow,cxxgtxy/tensorflow,hfp/tensorflow-xsmm,arborh/tensorflow,aam-at/tensorflow,ageron/tensorflow,hfp/tensorflow-xsmm,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-experimental_link_static_libraries_once,jbedorf/tensorflow,Intel-tensorflow/tensorflow,davidzchen/tensorflow,renyi533/tensorflow,Bismarrck/tensorflow,ppwwyyxx/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,DavidNorman/tensorflow,ghchinoy/tensorflow,ppwwyyxx/tensorflow,kevin-coder/tensorflow-fork,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-Corporation/tensorflow,renyi533/tensorflow,gautam1858/tensorflow,yongtang/tensorflow,apark263/tensorflow,frreiss/tensorflow-fred,kevin-coder/tensorflow-fork,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_tf_optimizer,renyi533/tensorflow,chemelnucfin/tensorflow,aam-at/tensorflow,apark263/tensorflow,ageron/tensorflow,frreiss/tensorflow-fred,asimshankar/tensorflow,jbedorf/tensorflow,ageron/tensorflow,freedomtan/tensorflow,jendap/tensorflow,asimshankar/tensorflow,gunan/tensorflow,yongtang/tensorflow,jhseu/tensorflow,ppwwyyxx/tensorflow,asimshankar/tensorflow,sarvex/tensorflow,ppwwyyxx/tensorflow,cxxgtxy/tensorflow,theflofly/tensorflow,theflofly/tensorflow,aam-at/tensorflow,ageron/tensorflow,freedomtan/tensorflow,freedomtan/tensorflow,jbedorf/tensorflow,DavidNorman/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,jendap/tensorflow,xzturn/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,adit-chandra/tensorflow,jhseu/tensorflow,renyi533/tensorflow,annarev/tensorflow,ppwwyyxx/tensorflow,paolodedios/tensorflow,renyi533/tensorflow,alsrgv/tensorflow,alsrgv/tensorflow,yongtang/tensorflow,frreiss/tensorflow-fred,hfp/tensorflow-xsmm,jhseu/tensorflow,aldian/tensorflow,chemelnucfin/tensorflow,davidzchen/tensorflow,annarev/tensorflow,theflofly/tensorflow,jbedorf/tensorflow,adit-chandra/tensorflow,xzturn/tensorflow,jbedorf/tensorflow,arborh/tensorflow,yongtang/tensorflow,Intel-Corporation/tensorflow,ppwwyyxx/tensorflow,arborh/tensorflow,kevin-coder/tensorflow-fork,Bismarrck/tensorflow,ppwwyyxx/tensorflow,Bismarrck/tensorflow,apark263/tensorflow,DavidNorman/tensorflow,kevin-coder/tensorflow-fork,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-experimental_link_static_libraries_once,kevin-coder/tensorflow-fork,tensorflow/tensorflow,jbedorf/tensorflow,ppwwyyxx/tensorflow,Intel-tensorflow/tensorflow,arborh/tensorflow,arborh/tensorflow,gunan/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,cxxgtxy/tensorflow,Intel-Corporation/tensorflow,freedomtan/tensorflow,jhseu/tensorflow,xzturn/tensorflow,Bismarrck/tensorflow,alsrgv/tensorflow,adit-chandra/tensorflow,kevin-coder/tensorflow-fork,Intel-Corporation/tensorflow,petewarden/tensorflow,jhseu/tensorflow,aam-at/tensorflow,tensorflow/tensorflow-pywrap_saved_model,gunan/tensorflow,Bismarrck/tensorflow,hfp/tensorflow-xsmm,davidzchen/tensorflow,chemelnucfin/tensorflow,ppwwyyxx/tensorflow,arborh/tensorflow,chemelnucfin/tensorflow,tensorflow/tensorflow-pywrap_saved_model,gunan/tensorflow,DavidNorman/tensorflow,hfp/tensorflow-xsmm,aldian/tensorflow,apark263/tensorflow,adit-chandra/tensorflow,DavidNorman/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,yongtang/tensorflow,gautam1858/tensorflow,renyi533/tensorflow,petewarden/tensorflow,theflofly/tensorflow,annarev/tensorflow,petewarden/tensorflow,petewarden/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_tf_optimizer,hfp/tensorflow-xsmm,frreiss/tensorflow-fred,yongtang/tensorflow,DavidNorman/tensorflow,renyi533/tensorflow,frreiss/tensorflow-fred,Intel-Corporation/tensorflow,jhseu/tensorflow,davidzchen/tensorflow,davidzchen/tensorflow,ghchinoy/tensorflow,petewarden/tensorflow,annarev/tensorflow,frreiss/tensorflow-fred,gunan/tensorflow,gunan/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-tensorflow/tensorflow,adit-chandra/tensorflow,Intel-tensorflow/tensorflow,gautam1858/tensorflow,aldian/tensorflow,aam-at/tensorflow,Bismarrck/tensorflow,adit-chandra/tensorflow,DavidNorman/tensorflow,jbedorf/tensorflow,ageron/tensorflow,asimshankar/tensorflow,apark263/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-tensorflow/tensorflow,gautam1858/tensorflow,renyi533/tensorflow,aldian/tensorflow,karllessard/tensorflow,jendap/tensorflow,paolodedios/tensorflow,ageron/tensorflow,alsrgv/tensorflow,Intel-tensorflow/tensorflow,gunan/tensorflow,frreiss/tensorflow-fred,annarev/tensorflow,karllessard/tensorflow,frreiss/tensorflow-fred,Bismarrck/tensorflow,annarev/tensorflow,Intel-Corporation/tensorflow,ppwwyyxx/tensorflow,ghchinoy/tensorflow,jhseu/tensorflow,freedomtan/tensorflow,davidzchen/tensorflow,adit-chandra/tensorflow,chemelnucfin/tensorflow,cxxgtxy/tensorflow,cxxgtxy/tensorflow,gautam1858/tensorflow,jbedorf/tensorflow,ghchinoy/tensorflow,apark263/tensorflow,xzturn/tensorflow,renyi533/tensorflow,ghchinoy/tensorflow,aam-at/tensorflow,yongtang/tensorflow,Bismarrck/tensorflow,petewarden/tensorflow,frreiss/tensorflow-fred,aldian/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-tensorflow/tensorflow,gunan/tensorflow,aldian/tensorflow,ghchinoy/tensorflow,renyi533/tensorflow,tensorflow/tensorflow,jbedorf/tensorflow,chemelnucfin/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,jendap/tensorflow,xzturn/tensorflow,ghchinoy/tensorflow,theflofly/tensorflow,sarvex/tensorflow,ageron/tensorflow,Intel-Corporation/tensorflow,asimshankar/tensorflow,xzturn/tensorflow,DavidNorman/tensorflow,DavidNorman/tensorflow,petewarden/tensorflow,adit-chandra/tensorflow,davidzchen/tensorflow,theflofly/tensorflow,jendap/tensorflow,tensorflow/tensorflow,gautam1858/tensorflow,karllessard/tensorflow,paolodedios/tensorflow,sarvex/tensorflow,davidzchen/tensorflow,gunan/tensorflow,DavidNorman/tensorflow,tensorflow/tensorflow-pywrap_saved_model,asimshankar/tensorflow,asimshankar/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow,ppwwyyxx/tensorflow,ppwwyyxx/tensorflow,arborh/tensorflow,gautam1858/tensorflow,Intel-Corporation/tensorflow,alsrgv/tensorflow,Bismarrck/tensorflow,DavidNorman/tensorflow,ghchinoy/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,gautam1858/tensorflow,aam-at/tensorflow,karllessard/tensorflow,annarev/tensorflow,cxxgtxy/tensorflow,sarvex/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow,sarvex/tensorflow,hfp/tensorflow-xsmm,ageron/tensorflow,freedomtan/tensorflow,sarvex/tensorflow,gunan/tensorflow,frreiss/tensorflow-fred,karllessard/tensorflow,Bismarrck/tensorflow,jhseu/tensorflow,xzturn/tensorflow,petewarden/tensorflow,petewarden/tensorflow
f544094d5e1ee627ebd34542aead7bf1241fae19
src/random.cpp
src/random.cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "random.h" #include "crypto/sha512.h" #include "support/cleanse.h" #ifdef WIN32 #include "compat.h" // for Windows API #include <wincrypt.h> #endif #include "util.h" // for LogPrint() #include "utilstrencodings.h" // for GetTime() #include <stdlib.h> #include <limits> #ifndef WIN32 #include <sys/time.h> #endif #ifdef HAVE_SYS_GETRANDOM #include <sys/syscall.h> #include <linux/random.h> #endif #ifdef HAVE_GETENTROPY #include <unistd.h> #endif #ifdef HAVE_SYSCTL_ARND #include <sys/sysctl.h> #endif #include <openssl/err.h> #include <openssl/rand.h> static void RandFailure() { LogPrintf("Failed to read randomness, aborting\n"); abort(); } static inline int64_t GetPerformanceCounter() { int64_t nCounter = 0; #ifdef WIN32 QueryPerformanceCounter((LARGE_INTEGER*)&nCounter); #else timeval t; gettimeofday(&t, NULL); nCounter = (int64_t)(t.tv_sec * 1000000 + t.tv_usec); #endif return nCounter; } void RandAddSeed() { // Seed with CPU performance counter int64_t nCounter = GetPerformanceCounter(); RAND_add(&nCounter, sizeof(nCounter), 1.5); memory_cleanse((void*)&nCounter, sizeof(nCounter)); } static void RandAddSeedPerfmon() { RandAddSeed(); #ifdef WIN32 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom // Seed with the entire set of perfmon data // This can take up to 2 seconds, so only do it every 10 minutes static int64_t nLastPerfmon; if (GetTime() < nLastPerfmon + 10 * 60) return; nLastPerfmon = GetTime(); std::vector<unsigned char> vData(250000, 0); long ret = 0; unsigned long nSize = 0; const size_t nMaxSize = 10000000; // Bail out at more than 10MB of performance data while (true) { nSize = vData.size(); ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, vData.data(), &nSize); if (ret != ERROR_MORE_DATA || vData.size() >= nMaxSize) break; vData.resize(std::max((vData.size() * 3) / 2, nMaxSize)); // Grow size of buffer exponentially } RegCloseKey(HKEY_PERFORMANCE_DATA); if (ret == ERROR_SUCCESS) { RAND_add(vData.data(), nSize, nSize / 100.0); memory_cleanse(vData.data(), nSize); LogPrint(BCLog::RAND, "%s: %lu bytes\n", __func__, nSize); } else { static bool warned = false; // Warn only once if (!warned) { LogPrintf("%s: Warning: RegQueryValueExA(HKEY_PERFORMANCE_DATA) failed with code %i\n", __func__, ret); warned = true; } } #endif } #ifndef WIN32 /** Fallback: get 32 bytes of system entropy from /dev/urandom. The most * compatible way to get cryptographic randomness on UNIX-ish platforms. */ void GetDevURandom(unsigned char *ent32) { int f = open("/dev/urandom", O_RDONLY); if (f == -1) { RandFailure(); } int have = 0; do { ssize_t n = read(f, ent32 + have, NUM_OS_RANDOM_BYTES - have); if (n <= 0 || n + have > NUM_OS_RANDOM_BYTES) { RandFailure(); } have += n; } while (have < NUM_OS_RANDOM_BYTES); close(f); } #endif /** Get 32 bytes of system entropy. */ void GetOSRand(unsigned char *ent32) { #if defined(WIN32) HCRYPTPROV hProvider; int ret = CryptAcquireContextW(&hProvider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT); if (!ret) { RandFailure(); } ret = CryptGenRandom(hProvider, NUM_OS_RANDOM_BYTES, ent32); if (!ret) { RandFailure(); } CryptReleaseContext(hProvider, 0); #elif defined(HAVE_SYS_GETRANDOM) /* Linux. From the getrandom(2) man page: * "If the urandom source has been initialized, reads of up to 256 bytes * will always return as many bytes as requested and will not be * interrupted by signals." */ int rv = syscall(SYS_getrandom, ent32, NUM_OS_RANDOM_BYTES, 0); if (rv != NUM_OS_RANDOM_BYTES) { if (rv < 0 && errno == ENOSYS) { /* Fallback for kernel <3.17: the return value will be -1 and errno * ENOSYS if the syscall is not available, in that case fall back * to /dev/urandom. */ GetDevURandom(ent32); } else { RandFailure(); } } #elif defined(HAVE_GETENTROPY) /* On OpenBSD this can return up to 256 bytes of entropy, will return an * error if more are requested. * The call cannot return less than the requested number of bytes. */ if (getentropy(ent32, NUM_OS_RANDOM_BYTES) != 0) { RandFailure(); } #elif defined(HAVE_SYSCTL_ARND) /* FreeBSD and similar. It is possible for the call to return less * bytes than requested, so need to read in a loop. */ static const int name[2] = {CTL_KERN, KERN_ARND}; int have = 0; do { size_t len = NUM_OS_RANDOM_BYTES - have; if (sysctl(name, ARRAYLEN(name), ent32 + have, &len, NULL, 0) != 0) { RandFailure(); } have += len; } while (have < NUM_OS_RANDOM_BYTES); #else /* Fall back to /dev/urandom if there is no specific method implemented to * get system entropy for this OS. */ GetDevURandom(ent32); #endif } void GetRandBytes(unsigned char* buf, int num) { if (RAND_bytes(buf, num) != 1) { RandFailure(); } } void GetStrongRandBytes(unsigned char* out, int num) { assert(num <= 32); CSHA512 hasher; unsigned char buf[64]; // First source: OpenSSL's RNG RandAddSeedPerfmon(); GetRandBytes(buf, 32); hasher.Write(buf, 32); // Second source: OS RNG GetOSRand(buf); hasher.Write(buf, 32); // Produce output hasher.Finalize(buf); memcpy(out, buf, num); memory_cleanse(buf, 64); } uint64_t GetRand(uint64_t nMax) { if (nMax == 0) return 0; // The range of the random source must be a multiple of the modulus // to give every possible output value an equal possibility uint64_t nRange = (std::numeric_limits<uint64_t>::max() / nMax) * nMax; uint64_t nRand = 0; do { GetRandBytes((unsigned char*)&nRand, sizeof(nRand)); } while (nRand >= nRange); return (nRand % nMax); } int GetRandInt(int nMax) { return GetRand(nMax); } uint256 GetRandHash() { uint256 hash; GetRandBytes((unsigned char*)&hash, sizeof(hash)); return hash; } void FastRandomContext::RandomSeed() { uint256 seed = GetRandHash(); rng.SetKey(seed.begin(), 32); requires_seed = false; } FastRandomContext::FastRandomContext(const uint256& seed) : requires_seed(false), bytebuf_size(0), bitbuf_size(0) { rng.SetKey(seed.begin(), 32); } bool Random_SanityCheck() { /* This does not measure the quality of randomness, but it does test that * OSRandom() overwrites all 32 bytes of the output given a maximum * number of tries. */ static const ssize_t MAX_TRIES = 1024; uint8_t data[NUM_OS_RANDOM_BYTES]; bool overwritten[NUM_OS_RANDOM_BYTES] = {}; /* Tracks which bytes have been overwritten at least once */ int num_overwritten; int tries = 0; /* Loop until all bytes have been overwritten at least once, or max number tries reached */ do { memset(data, 0, NUM_OS_RANDOM_BYTES); GetOSRand(data); for (int x=0; x < NUM_OS_RANDOM_BYTES; ++x) { overwritten[x] |= (data[x] != 0); } num_overwritten = 0; for (int x=0; x < NUM_OS_RANDOM_BYTES; ++x) { if (overwritten[x]) { num_overwritten += 1; } } tries += 1; } while (num_overwritten < NUM_OS_RANDOM_BYTES && tries < MAX_TRIES); return (num_overwritten == NUM_OS_RANDOM_BYTES); /* If this failed, bailed out after too many tries */ } FastRandomContext::FastRandomContext(bool fDeterministic) : requires_seed(!fDeterministic), bytebuf_size(0), bitbuf_size(0) { if (!fDeterministic) { return; } uint256 seed; rng.SetKey(seed.begin(), 32); }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "random.h" #include "crypto/sha512.h" #include "support/cleanse.h" #ifdef WIN32 #include "compat.h" // for Windows API #include <wincrypt.h> #endif #include "util.h" // for LogPrint() #include "utilstrencodings.h" // for GetTime() #include <stdlib.h> #include <limits> #include <chrono> #ifndef WIN32 #include <sys/time.h> #endif #ifdef HAVE_SYS_GETRANDOM #include <sys/syscall.h> #include <linux/random.h> #endif #ifdef HAVE_GETENTROPY #include <unistd.h> #endif #ifdef HAVE_SYSCTL_ARND #include <sys/sysctl.h> #endif #include <openssl/err.h> #include <openssl/rand.h> static void RandFailure() { LogPrintf("Failed to read randomness, aborting\n"); abort(); } static inline int64_t GetPerformanceCounter() { // Read the hardware time stamp counter when available. // See https://en.wikipedia.org/wiki/Time_Stamp_Counter for more information. #if defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64)) return __rdtsc(); #elif !defined(_MSC_VER) && defined(__i386__) uint64_t r = 0; __asm__ volatile ("rdtsc" : "=A"(r)); // Constrain the r variable to the eax:edx pair. return r; #elif !defined(_MSC_VER) && (defined(__x86_64__) || defined(__amd64__)) uint64_t r1 = 0, r2 = 0; __asm__ volatile ("rdtsc" : "=a"(r1), "=d"(r2)); // Constrain r1 to rax and r2 to rdx. return (r2 << 32) | r1; #else // Fall back to using C++11 clock (usually microsecond or nanosecond precision) return std::chrono::high_resolution_clock::now().time_since_epoch().count(); #endif } void RandAddSeed() { // Seed with CPU performance counter int64_t nCounter = GetPerformanceCounter(); RAND_add(&nCounter, sizeof(nCounter), 1.5); memory_cleanse((void*)&nCounter, sizeof(nCounter)); } static void RandAddSeedPerfmon() { RandAddSeed(); #ifdef WIN32 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom // Seed with the entire set of perfmon data // This can take up to 2 seconds, so only do it every 10 minutes static int64_t nLastPerfmon; if (GetTime() < nLastPerfmon + 10 * 60) return; nLastPerfmon = GetTime(); std::vector<unsigned char> vData(250000, 0); long ret = 0; unsigned long nSize = 0; const size_t nMaxSize = 10000000; // Bail out at more than 10MB of performance data while (true) { nSize = vData.size(); ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, vData.data(), &nSize); if (ret != ERROR_MORE_DATA || vData.size() >= nMaxSize) break; vData.resize(std::max((vData.size() * 3) / 2, nMaxSize)); // Grow size of buffer exponentially } RegCloseKey(HKEY_PERFORMANCE_DATA); if (ret == ERROR_SUCCESS) { RAND_add(vData.data(), nSize, nSize / 100.0); memory_cleanse(vData.data(), nSize); LogPrint(BCLog::RAND, "%s: %lu bytes\n", __func__, nSize); } else { static bool warned = false; // Warn only once if (!warned) { LogPrintf("%s: Warning: RegQueryValueExA(HKEY_PERFORMANCE_DATA) failed with code %i\n", __func__, ret); warned = true; } } #endif } #ifndef WIN32 /** Fallback: get 32 bytes of system entropy from /dev/urandom. The most * compatible way to get cryptographic randomness on UNIX-ish platforms. */ void GetDevURandom(unsigned char *ent32) { int f = open("/dev/urandom", O_RDONLY); if (f == -1) { RandFailure(); } int have = 0; do { ssize_t n = read(f, ent32 + have, NUM_OS_RANDOM_BYTES - have); if (n <= 0 || n + have > NUM_OS_RANDOM_BYTES) { RandFailure(); } have += n; } while (have < NUM_OS_RANDOM_BYTES); close(f); } #endif /** Get 32 bytes of system entropy. */ void GetOSRand(unsigned char *ent32) { #if defined(WIN32) HCRYPTPROV hProvider; int ret = CryptAcquireContextW(&hProvider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT); if (!ret) { RandFailure(); } ret = CryptGenRandom(hProvider, NUM_OS_RANDOM_BYTES, ent32); if (!ret) { RandFailure(); } CryptReleaseContext(hProvider, 0); #elif defined(HAVE_SYS_GETRANDOM) /* Linux. From the getrandom(2) man page: * "If the urandom source has been initialized, reads of up to 256 bytes * will always return as many bytes as requested and will not be * interrupted by signals." */ int rv = syscall(SYS_getrandom, ent32, NUM_OS_RANDOM_BYTES, 0); if (rv != NUM_OS_RANDOM_BYTES) { if (rv < 0 && errno == ENOSYS) { /* Fallback for kernel <3.17: the return value will be -1 and errno * ENOSYS if the syscall is not available, in that case fall back * to /dev/urandom. */ GetDevURandom(ent32); } else { RandFailure(); } } #elif defined(HAVE_GETENTROPY) /* On OpenBSD this can return up to 256 bytes of entropy, will return an * error if more are requested. * The call cannot return less than the requested number of bytes. */ if (getentropy(ent32, NUM_OS_RANDOM_BYTES) != 0) { RandFailure(); } #elif defined(HAVE_SYSCTL_ARND) /* FreeBSD and similar. It is possible for the call to return less * bytes than requested, so need to read in a loop. */ static const int name[2] = {CTL_KERN, KERN_ARND}; int have = 0; do { size_t len = NUM_OS_RANDOM_BYTES - have; if (sysctl(name, ARRAYLEN(name), ent32 + have, &len, NULL, 0) != 0) { RandFailure(); } have += len; } while (have < NUM_OS_RANDOM_BYTES); #else /* Fall back to /dev/urandom if there is no specific method implemented to * get system entropy for this OS. */ GetDevURandom(ent32); #endif } void GetRandBytes(unsigned char* buf, int num) { if (RAND_bytes(buf, num) != 1) { RandFailure(); } } void GetStrongRandBytes(unsigned char* out, int num) { assert(num <= 32); CSHA512 hasher; unsigned char buf[64]; // First source: OpenSSL's RNG RandAddSeedPerfmon(); GetRandBytes(buf, 32); hasher.Write(buf, 32); // Second source: OS RNG GetOSRand(buf); hasher.Write(buf, 32); // Produce output hasher.Finalize(buf); memcpy(out, buf, num); memory_cleanse(buf, 64); } uint64_t GetRand(uint64_t nMax) { if (nMax == 0) return 0; // The range of the random source must be a multiple of the modulus // to give every possible output value an equal possibility uint64_t nRange = (std::numeric_limits<uint64_t>::max() / nMax) * nMax; uint64_t nRand = 0; do { GetRandBytes((unsigned char*)&nRand, sizeof(nRand)); } while (nRand >= nRange); return (nRand % nMax); } int GetRandInt(int nMax) { return GetRand(nMax); } uint256 GetRandHash() { uint256 hash; GetRandBytes((unsigned char*)&hash, sizeof(hash)); return hash; } void FastRandomContext::RandomSeed() { uint256 seed = GetRandHash(); rng.SetKey(seed.begin(), 32); requires_seed = false; } FastRandomContext::FastRandomContext(const uint256& seed) : requires_seed(false), bytebuf_size(0), bitbuf_size(0) { rng.SetKey(seed.begin(), 32); } bool Random_SanityCheck() { /* This does not measure the quality of randomness, but it does test that * OSRandom() overwrites all 32 bytes of the output given a maximum * number of tries. */ static const ssize_t MAX_TRIES = 1024; uint8_t data[NUM_OS_RANDOM_BYTES]; bool overwritten[NUM_OS_RANDOM_BYTES] = {}; /* Tracks which bytes have been overwritten at least once */ int num_overwritten; int tries = 0; /* Loop until all bytes have been overwritten at least once, or max number tries reached */ do { memset(data, 0, NUM_OS_RANDOM_BYTES); GetOSRand(data); for (int x=0; x < NUM_OS_RANDOM_BYTES; ++x) { overwritten[x] |= (data[x] != 0); } num_overwritten = 0; for (int x=0; x < NUM_OS_RANDOM_BYTES; ++x) { if (overwritten[x]) { num_overwritten += 1; } } tries += 1; } while (num_overwritten < NUM_OS_RANDOM_BYTES && tries < MAX_TRIES); return (num_overwritten == NUM_OS_RANDOM_BYTES); /* If this failed, bailed out after too many tries */ } FastRandomContext::FastRandomContext(bool fDeterministic) : requires_seed(!fDeterministic), bytebuf_size(0), bitbuf_size(0) { if (!fDeterministic) { return; } uint256 seed; rng.SetKey(seed.begin(), 32); }
Use hardware timestamps in RNG seeding
Use hardware timestamps in RNG seeding
C++
mit
mruddy/bitcoin,sipsorcery/bitcoin,practicalswift/bitcoin,midnightmagic/bitcoin,trippysalmon/bitcoin,EthanHeilman/bitcoin,UFOCoins/ufo,sebrandon1/bitcoin,achow101/bitcoin,litecoin-project/litecoin,ryanofsky/bitcoin,Jcing95/iop-hd,gjhiggins/vcoincore,fanquake/bitcoin,jonasschnelli/bitcoin,r8921039/bitcoin,kallewoof/bitcoin,ajtowns/bitcoin,instagibbs/bitcoin,UFOCoins/ufo,gmaxwell/bitcoin,senadmd/coinmarketwatch,digibyte/digibyte,jambolo/bitcoin,untrustbank/litecoin,dgarage/bc2,Anfauglith/iop-hd,Xekyo/bitcoin,174high/bitcoin,r8921039/bitcoin,anditto/bitcoin,OmniLayer/omnicore,namecoin/namecoin-core,bitbrazilcoin-project/bitbrazilcoin,laudaa/bitcoin,domob1812/namecore,jtimon/bitcoin,174high/bitcoin,sstone/bitcoin,viacoin/viacoin,droark/bitcoin,FeatherCoin/Feathercoin,rawodb/bitcoin,domob1812/namecore,donaloconnor/bitcoin,globaltoken/globaltoken,starwels/starwels,guncoin/guncoin,RHavar/bitcoin,domob1812/huntercore,maaku/bitcoin,wangxinxi/litecoin,domob1812/namecore,1185/starwels,nikkitan/bitcoin,sarielsaz/sarielsaz,globaltoken/globaltoken,BTCGPU/BTCGPU,MazaCoin/maza,mm-s/bitcoin,Exgibichi/statusquo,Gazer022/bitcoin,donaloconnor/bitcoin,sipsorcery/bitcoin,Bushstar/UFO-Project,GroestlCoin/GroestlCoin,fujicoin/fujicoin,dscotese/bitcoin,TheBlueMatt/bitcoin,Flowdalic/bitcoin,particl/particl-core,namecoin/namecoin-core,rnicoll/dogecoin,Theshadow4all/ShadowCoin,jamesob/bitcoin,Flowdalic/bitcoin,globaltoken/globaltoken,jmcorgan/bitcoin,myriadcoin/myriadcoin,ahmedbodi/vertcoin,GlobalBoost/GlobalBoost,mruddy/bitcoin,cryptoprojects/ultimateonlinecash,namecoin/namecoin-core,sstone/bitcoin,domob1812/namecore,tecnovert/particl-core,romanornr/viacoin,cryptoprojects/ultimateonlinecash,Mirobit/bitcoin,1185/starwels,ericshawlinux/bitcoin,instagibbs/bitcoin,gjhiggins/vcoincore,BTCGPU/BTCGPU,Bushstar/UFO-Project,Kogser/bitcoin,gmaxwell/bitcoin,daliwangi/bitcoin,joshrabinowitz/bitcoin,MarcoFalke/bitcoin,lbryio/lbrycrd,mb300sd/bitcoin,kazcw/bitcoin,sebrandon1/bitcoin,tjps/bitcoin,Christewart/bitcoin,aspanta/bitcoin,RHavar/bitcoin,Chancoin-core/CHANCOIN,wangxinxi/litecoin,cdecker/bitcoin,StarbuckBG/BTCGPU,kevcooper/bitcoin,jnewbery/bitcoin,lbryio/lbrycrd,GroestlCoin/GroestlCoin,aspanta/bitcoin,bespike/litecoin,Bushstar/UFO-Project,lateminer/bitcoin,RHavar/bitcoin,x-kalux/bitcoin_WiG-B,Christewart/bitcoin,namecoin/namecore,spiritlinxl/BTCGPU,jmcorgan/bitcoin,litecoin-project/litecoin,Rav3nPL/bitcoin,pataquets/namecoin-core,deeponion/deeponion,gjhiggins/vcoincore,gjhiggins/vcoincore,donaloconnor/bitcoin,MarcoFalke/bitcoin,sipsorcery/bitcoin,DigitalPandacoin/pandacoin,BitzenyCoreDevelopers/bitzeny,apoelstra/bitcoin,droark/bitcoin,StarbuckBG/BTCGPU,TheBlueMatt/bitcoin,bitbrazilcoin-project/bitbrazilcoin,bitbrazilcoin-project/bitbrazilcoin,donaloconnor/bitcoin,randy-waterhouse/bitcoin,brandonrobertz/namecoin-core,instagibbs/bitcoin,21E14/bitcoin,qtumproject/qtum,globaltoken/globaltoken,bitcoin/bitcoin,monacoinproject/monacoin,shelvenzhou/BTCGPU,1185/starwels,jambolo/bitcoin,ajtowns/bitcoin,Rav3nPL/bitcoin,tjps/bitcoin,MeshCollider/bitcoin,monacoinproject/monacoin,CryptArc/bitcoin,simonmulser/bitcoin,destenson/bitcoin--bitcoin,DigitalPandacoin/pandacoin,destenson/bitcoin--bitcoin,wellenreiter01/Feathercoin,dgarage/bc2,Kogser/bitcoin,Anfauglith/iop-hd,mitchellcash/bitcoin,gjhiggins/vcoincore,sstone/bitcoin,kevcooper/bitcoin,stamhe/bitcoin,lbryio/lbrycrd,mm-s/bitcoin,pataquets/namecoin-core,prusnak/bitcoin,joshrabinowitz/bitcoin,namecoin/namecore,GlobalBoost/GlobalBoost,jtimon/bitcoin,prusnak/bitcoin,fujicoin/fujicoin,nlgcoin/guldencoin-official,guncoin/guncoin,prusnak/bitcoin,tjps/bitcoin,Sjors/bitcoin,r8921039/bitcoin,instagibbs/bitcoin,nbenoit/bitcoin,GroestlCoin/bitcoin,sarielsaz/sarielsaz,thrasher-/litecoin,tjps/bitcoin,CryptArc/bitcoin,nbenoit/bitcoin,Jcing95/iop-hd,21E14/bitcoin,21E14/bitcoin,Gazer022/bitcoin,rawodb/bitcoin,viacoin/viacoin,wangxinxi/litecoin,spiritlinxl/BTCGPU,TheBlueMatt/bitcoin,Friedbaumer/litecoin,anditto/bitcoin,kazcw/bitcoin,Flowdalic/bitcoin,litecoin-project/litecoin,rnicoll/bitcoin,MazaCoin/maza,ppcoin/ppcoin,shelvenzhou/BTCGPU,21E14/bitcoin,bitcoin/bitcoin,Chancoin-core/CHANCOIN,BTCGPU/BTCGPU,laudaa/bitcoin,bitbrazilcoin-project/bitbrazilcoin,GlobalBoost/GlobalBoost,sipsorcery/bitcoin,lateminer/bitcoin,rnicoll/bitcoin,Mirobit/bitcoin,jlopp/statoshi,domob1812/huntercore,spiritlinxl/BTCGPU,trippysalmon/bitcoin,bitcoinsSG/bitcoin,Theshadow4all/ShadowCoin,ElementsProject/elements,Anfauglith/iop-hd,monacoinproject/monacoin,randy-waterhouse/bitcoin,CryptArc/bitcoin,afk11/bitcoin,sarielsaz/sarielsaz,simonmulser/bitcoin,senadmd/coinmarketwatch,ericshawlinux/bitcoin,afk11/bitcoin,digibyte/digibyte,Anfauglith/iop-hd,Gazer022/bitcoin,Gazer022/bitcoin,anditto/bitcoin,ajtowns/bitcoin,brandonrobertz/namecoin-core,fujicoin/fujicoin,ryanofsky/bitcoin,mb300sd/bitcoin,destenson/bitcoin--bitcoin,rnicoll/dogecoin,guncoin/guncoin,Theshadow4all/ShadowCoin,sipsorcery/bitcoin,Kogser/bitcoin,vertcoin/vertcoin,ahmedbodi/vertcoin,shelvenzhou/BTCGPU,prusnak/bitcoin,nikkitan/bitcoin,alecalve/bitcoin,litecoin-project/litecoin,sarielsaz/sarielsaz,EthanHeilman/bitcoin,kazcw/bitcoin,ryanofsky/bitcoin,namecoin/namecore,fanquake/bitcoin,randy-waterhouse/bitcoin,trippysalmon/bitcoin,dscotese/bitcoin,namecoin/namecore,Rav3nPL/bitcoin,kallewoof/bitcoin,RHavar/bitcoin,rnicoll/dogecoin,Exgibichi/statusquo,Gazer022/bitcoin,EthanHeilman/bitcoin,starwels/starwels,GroestlCoin/bitcoin,Jcing95/iop-hd,prusnak/bitcoin,r8921039/bitcoin,achow101/bitcoin,AkioNak/bitcoin,bitcoinknots/bitcoin,jonasschnelli/bitcoin,thrasher-/litecoin,tecnovert/particl-core,gmaxwell/bitcoin,wangxinxi/litecoin,joshrabinowitz/bitcoin,tecnovert/particl-core,x-kalux/bitcoin_WiG-B,nlgcoin/guldencoin-official,bitcoinsSG/bitcoin,myriadteam/myriadcoin,sarielsaz/sarielsaz,sebrandon1/bitcoin,starwels/starwels,ElementsProject/elements,21E14/bitcoin,rawodb/bitcoin,Mirobit/bitcoin,domob1812/huntercore,sebrandon1/bitcoin,deeponion/deeponion,EthanHeilman/bitcoin,domob1812/namecore,rnicoll/dogecoin,jmcorgan/bitcoin,Friedbaumer/litecoin,nbenoit/bitcoin,vmp32k/litecoin,nikkitan/bitcoin,DigitalPandacoin/pandacoin,wellenreiter01/Feathercoin,afk11/bitcoin,shelvenzhou/BTCGPU,domob1812/huntercore,daliwangi/bitcoin,Christewart/bitcoin,ElementsProject/elements,Sjors/bitcoin,mm-s/bitcoin,qtumproject/qtum,midnightmagic/bitcoin,JeremyRubin/bitcoin,Jcing95/iop-hd,Exgibichi/statusquo,bitcoinsSG/bitcoin,Friedbaumer/litecoin,randy-waterhouse/bitcoin,kallewoof/bitcoin,sebrandon1/bitcoin,alecalve/bitcoin,gmaxwell/bitcoin,MarcoFalke/bitcoin,Flowdalic/bitcoin,qtumproject/qtum,jlopp/statoshi,senadmd/coinmarketwatch,anditto/bitcoin,earonesty/bitcoin,fanquake/bitcoin,laudaa/bitcoin,jtimon/bitcoin,Sjors/bitcoin,nlgcoin/guldencoin-official,paveljanik/bitcoin,pstratem/bitcoin,Xekyo/bitcoin,afk11/bitcoin,Chancoin-core/CHANCOIN,MeshCollider/bitcoin,x-kalux/bitcoin_WiG-B,kazcw/bitcoin,pstratem/bitcoin,shelvenzhou/BTCGPU,ryanofsky/bitcoin,Mirobit/bitcoin,174high/bitcoin,jnewbery/bitcoin,sstone/bitcoin,Kogser/bitcoin,sarielsaz/sarielsaz,wellenreiter01/Feathercoin,bespike/litecoin,brandonrobertz/namecoin-core,jonasschnelli/bitcoin,r8921039/bitcoin,kevcooper/bitcoin,rnicoll/bitcoin,domob1812/namecore,RHavar/bitcoin,untrustbank/litecoin,peercoin/peercoin,particl/particl-core,jamesob/bitcoin,deeponion/deeponion,aspanta/bitcoin,lateminer/bitcoin,nikkitan/bitcoin,digibyte/digibyte,dscotese/bitcoin,qtumproject/qtum,aspanta/bitcoin,stamhe/bitcoin,namecoin/namecoin-core,dgarage/bc3,achow101/bitcoin,domob1812/bitcoin,Sjors/bitcoin,FeatherCoin/Feathercoin,pataquets/namecoin-core,gmaxwell/bitcoin,maaku/bitcoin,CryptArc/bitcoin,jambolo/bitcoin,litecoin-project/litecoin,thrasher-/litecoin,UFOCoins/ufo,bitbrazilcoin-project/bitbrazilcoin,achow101/bitcoin,Jcing95/iop-hd,practicalswift/bitcoin,Christewart/bitcoin,OmniLayer/omnicore,JeremyRubin/bitcoin,brandonrobertz/namecoin-core,Bushstar/UFO-Project,domob1812/bitcoin,myriadcoin/myriadcoin,Flowdalic/bitcoin,deeponion/deeponion,dgarage/bc2,EthanHeilman/bitcoin,CryptArc/bitcoin,Friedbaumer/litecoin,andreaskern/bitcoin,romanornr/viacoin,destenson/bitcoin--bitcoin,jamesob/bitcoin,MazaCoin/maza,andreaskern/bitcoin,OmniLayer/omnicore,kazcw/bitcoin,jamesob/bitcoin,Exgibichi/statusquo,Kogser/bitcoin,mitchellcash/bitcoin,jlopp/statoshi,daliwangi/bitcoin,droark/bitcoin,BitzenyCoreDevelopers/bitzeny,wellenreiter01/Feathercoin,jambolo/bitcoin,jlopp/statoshi,ericshawlinux/bitcoin,viacoin/viacoin,174high/bitcoin,sebrandon1/bitcoin,jmcorgan/bitcoin,fanquake/bitcoin,n1bor/bitcoin,donaloconnor/bitcoin,tjps/bitcoin,bitcoinknots/bitcoin,h4x3rotab/BTCGPU,174high/bitcoin,lateminer/bitcoin,nikkitan/bitcoin,vertcoin/vertcoin,JeremyRubin/bitcoin,bitbrazilcoin-project/bitbrazilcoin,namecoin/namecore,mb300sd/bitcoin,globaltoken/globaltoken,peercoin/peercoin,Mirobit/bitcoin,dgarage/bc3,monacoinproject/monacoin,simonmulser/bitcoin,EthanHeilman/bitcoin,BTCGPU/BTCGPU,pataquets/namecoin-core,paveljanik/bitcoin,yenliangl/bitcoin,n1bor/bitcoin,h4x3rotab/BTCGPU,droark/bitcoin,domob1812/huntercore,earonesty/bitcoin,fujicoin/fujicoin,174high/bitcoin,JeremyRubin/bitcoin,ahmedbodi/vertcoin,bitcoinknots/bitcoin,myriadcoin/myriadcoin,trippysalmon/bitcoin,sstone/bitcoin,maaku/bitcoin,fujicoin/fujicoin,brandonrobertz/namecoin-core,jnewbery/bitcoin,Xekyo/bitcoin,AkioNak/bitcoin,laudaa/bitcoin,lateminer/bitcoin,andreaskern/bitcoin,paveljanik/bitcoin,h4x3rotab/BTCGPU,lbryio/lbrycrd,trippysalmon/bitcoin,spiritlinxl/BTCGPU,Kogser/bitcoin,MarcoFalke/bitcoin,myriadteam/myriadcoin,ericshawlinux/bitcoin,jmcorgan/bitcoin,Rav3nPL/bitcoin,rawodb/bitcoin,1185/starwels,peercoin/peercoin,nlgcoin/guldencoin-official,gmaxwell/bitcoin,digibyte/digibyte,Friedbaumer/litecoin,mb300sd/bitcoin,MazaCoin/maza,tecnovert/particl-core,lbryio/lbrycrd,digibyte/digibyte,earonesty/bitcoin,MazaCoin/maza,MeshCollider/bitcoin,Kogser/bitcoin,dgarage/bc2,joshrabinowitz/bitcoin,droark/bitcoin,Anfauglith/iop-hd,dscotese/bitcoin,ElementsProject/elements,stamhe/bitcoin,n1bor/bitcoin,Xekyo/bitcoin,rnicoll/bitcoin,n1bor/bitcoin,bespike/litecoin,maaku/bitcoin,GroestlCoin/bitcoin,Rav3nPL/bitcoin,domob1812/huntercore,fanquake/bitcoin,jambolo/bitcoin,cdecker/bitcoin,n1bor/bitcoin,dgarage/bc3,GlobalBoost/GlobalBoost,BitzenyCoreDevelopers/bitzeny,Theshadow4all/ShadowCoin,cryptoprojects/ultimateonlinecash,pataquets/namecoin-core,lateminer/bitcoin,GroestlCoin/GroestlCoin,fanquake/bitcoin,nbenoit/bitcoin,myriadteam/myriadcoin,mruddy/bitcoin,ajtowns/bitcoin,yenliangl/bitcoin,paveljanik/bitcoin,bitcoin/bitcoin,digibyte/digibyte,maaku/bitcoin,OmniLayer/omnicore,bitcoin/bitcoin,ppcoin/ppcoin,cryptoprojects/ultimateonlinecash,cdecker/bitcoin,bitcoinsSG/bitcoin,jlopp/statoshi,TheBlueMatt/bitcoin,GroestlCoin/bitcoin,paveljanik/bitcoin,myriadteam/myriadcoin,aspanta/bitcoin,bespike/litecoin,untrustbank/litecoin,laudaa/bitcoin,thrasher-/litecoin,tecnovert/particl-core,achow101/bitcoin,deeponion/deeponion,senadmd/coinmarketwatch,myriadcoin/myriadcoin,Flowdalic/bitcoin,wellenreiter01/Feathercoin,mm-s/bitcoin,h4x3rotab/BTCGPU,romanornr/viacoin,UFOCoins/ufo,randy-waterhouse/bitcoin,daliwangi/bitcoin,h4x3rotab/BTCGPU,n1bor/bitcoin,AkioNak/bitcoin,wellenreiter01/Feathercoin,BTCGPU/BTCGPU,mitchellcash/bitcoin,stamhe/bitcoin,StarbuckBG/BTCGPU,pstratem/bitcoin,ahmedbodi/vertcoin,DigitalPandacoin/pandacoin,jonasschnelli/bitcoin,sipsorcery/bitcoin,viacoin/viacoin,sstone/bitcoin,joshrabinowitz/bitcoin,Christewart/bitcoin,myriadteam/myriadcoin,Xekyo/bitcoin,spiritlinxl/BTCGPU,GroestlCoin/bitcoin,dscotese/bitcoin,dgarage/bc2,apoelstra/bitcoin,kallewoof/bitcoin,starwels/starwels,bitcoinknots/bitcoin,jonasschnelli/bitcoin,starwels/starwels,guncoin/guncoin,stamhe/bitcoin,pstratem/bitcoin,vertcoin/vertcoin,romanornr/viacoin,maaku/bitcoin,monacoinproject/monacoin,Chancoin-core/CHANCOIN,pataquets/namecoin-core,ElementsProject/elements,vmp32k/litecoin,DigitalPandacoin/pandacoin,ahmedbodi/vertcoin,lbryio/lbrycrd,tjps/bitcoin,JeremyRubin/bitcoin,yenliangl/bitcoin,anditto/bitcoin,Kogser/bitcoin,apoelstra/bitcoin,nbenoit/bitcoin,jlopp/statoshi,ahmedbodi/vertcoin,ajtowns/bitcoin,x-kalux/bitcoin_WiG-B,mruddy/bitcoin,andreaskern/bitcoin,destenson/bitcoin--bitcoin,domob1812/bitcoin,peercoin/peercoin,peercoin/peercoin,jnewbery/bitcoin,kallewoof/bitcoin,Bushstar/UFO-Project,romanornr/viacoin,thrasher-/litecoin,r8921039/bitcoin,anditto/bitcoin,BitzenyCoreDevelopers/bitzeny,guncoin/guncoin,yenliangl/bitcoin,cdecker/bitcoin,StarbuckBG/BTCGPU,jtimon/bitcoin,cryptoprojects/ultimateonlinecash,kevcooper/bitcoin,donaloconnor/bitcoin,JeremyRubin/bitcoin,AkioNak/bitcoin,namecoin/namecoin-core,Rav3nPL/bitcoin,instagibbs/bitcoin,fujicoin/fujicoin,rnicoll/dogecoin,jambolo/bitcoin,nlgcoin/guldencoin-official,paveljanik/bitcoin,MeshCollider/bitcoin,OmniLayer/omnicore,Mirobit/bitcoin,Exgibichi/statusquo,RHavar/bitcoin,kallewoof/bitcoin,cdecker/bitcoin,x-kalux/bitcoin_WiG-B,trippysalmon/bitcoin,bitcoinsSG/bitcoin,vmp32k/litecoin,domob1812/bitcoin,shelvenzhou/BTCGPU,UFOCoins/ufo,apoelstra/bitcoin,midnightmagic/bitcoin,cdecker/bitcoin,afk11/bitcoin,tecnovert/particl-core,bitcoinsSG/bitcoin,senadmd/coinmarketwatch,jamesob/bitcoin,vertcoin/vertcoin,mitchellcash/bitcoin,h4x3rotab/BTCGPU,mitchellcash/bitcoin,ppcoin/ppcoin,qtumproject/qtum,Exgibichi/statusquo,afk11/bitcoin,dgarage/bc3,lbryio/lbrycrd,daliwangi/bitcoin,wangxinxi/litecoin,GroestlCoin/GroestlCoin,GlobalBoost/GlobalBoost,Xekyo/bitcoin,Gazer022/bitcoin,gjhiggins/vcoincore,laudaa/bitcoin,romanornr/viacoin,ericshawlinux/bitcoin,mm-s/bitcoin,rawodb/bitcoin,1185/starwels,Kogser/bitcoin,nikkitan/bitcoin,viacoin/viacoin,simonmulser/bitcoin,myriadcoin/myriadcoin,globaltoken/globaltoken,dscotese/bitcoin,GroestlCoin/bitcoin,rawodb/bitcoin,droark/bitcoin,starwels/starwels,prusnak/bitcoin,earonesty/bitcoin,mb300sd/bitcoin,joshrabinowitz/bitcoin,AkioNak/bitcoin,Kogser/bitcoin,Bushstar/UFO-Project,Jcing95/iop-hd,earonesty/bitcoin,midnightmagic/bitcoin,daliwangi/bitcoin,alecalve/bitcoin,bitcoin/bitcoin,UFOCoins/ufo,MeshCollider/bitcoin,aspanta/bitcoin,kevcooper/bitcoin,mitchellcash/bitcoin,senadmd/coinmarketwatch,jnewbery/bitcoin,mruddy/bitcoin,thrasher-/litecoin,bitcoin/bitcoin,wangxinxi/litecoin,OmniLayer/omnicore,instagibbs/bitcoin,GroestlCoin/GroestlCoin,21E14/bitcoin,practicalswift/bitcoin,untrustbank/litecoin,myriadteam/myriadcoin,jtimon/bitcoin,practicalswift/bitcoin,Kogser/bitcoin,kevcooper/bitcoin,jtimon/bitcoin,TheBlueMatt/bitcoin,domob1812/bitcoin,untrustbank/litecoin,apoelstra/bitcoin,midnightmagic/bitcoin,myriadcoin/myriadcoin,mruddy/bitcoin,guncoin/guncoin,viacoin/viacoin,AkioNak/bitcoin,StarbuckBG/BTCGPU,namecoin/namecoin-core,CryptArc/bitcoin,destenson/bitcoin--bitcoin,particl/particl-core,yenliangl/bitcoin,GlobalBoost/GlobalBoost,randy-waterhouse/bitcoin,andreaskern/bitcoin,apoelstra/bitcoin,jamesob/bitcoin,MarcoFalke/bitcoin,ppcoin/ppcoin,monacoinproject/monacoin,GroestlCoin/GroestlCoin,brandonrobertz/namecoin-core,dgarage/bc3,simonmulser/bitcoin,pstratem/bitcoin,deeponion/deeponion,rnicoll/bitcoin,bitcoinknots/bitcoin,BitzenyCoreDevelopers/bitzeny,practicalswift/bitcoin,MazaCoin/maza,stamhe/bitcoin,peercoin/peercoin,vmp32k/litecoin,ryanofsky/bitcoin,litecoin-project/litecoin,ajtowns/bitcoin,achow101/bitcoin,qtumproject/qtum,MeshCollider/bitcoin,bespike/litecoin,namecoin/namecore,DigitalPandacoin/pandacoin,nlgcoin/guldencoin-official,cryptoprojects/ultimateonlinecash,earonesty/bitcoin,BitzenyCoreDevelopers/bitzeny,ryanofsky/bitcoin,yenliangl/bitcoin,TheBlueMatt/bitcoin,FeatherCoin/Feathercoin,jmcorgan/bitcoin,vmp32k/litecoin,StarbuckBG/BTCGPU,x-kalux/bitcoin_WiG-B,Anfauglith/iop-hd,mm-s/bitcoin,Theshadow4all/ShadowCoin,Chancoin-core/CHANCOIN,kazcw/bitcoin,alecalve/bitcoin,rnicoll/bitcoin,domob1812/bitcoin,BTCGPU/BTCGPU,spiritlinxl/BTCGPU,ElementsProject/elements,ericshawlinux/bitcoin,1185/starwels,vmp32k/litecoin,Kogser/bitcoin,alecalve/bitcoin,particl/particl-core,particl/particl-core,Friedbaumer/litecoin,vertcoin/vertcoin,Christewart/bitcoin,Chancoin-core/CHANCOIN,FeatherCoin/Feathercoin,pstratem/bitcoin,Theshadow4all/ShadowCoin,vertcoin/vertcoin,dgarage/bc3,MarcoFalke/bitcoin,dgarage/bc2,Sjors/bitcoin,bespike/litecoin,particl/particl-core,FeatherCoin/Feathercoin,qtumproject/qtum,nbenoit/bitcoin,untrustbank/litecoin,GlobalBoost/GlobalBoost,midnightmagic/bitcoin,alecalve/bitcoin,FeatherCoin/Feathercoin,simonmulser/bitcoin,andreaskern/bitcoin,practicalswift/bitcoin,mb300sd/bitcoin
9308a5591b21c48cfb6e5ad273c0eaad31c4bb02
tascore/corelib/tasdeviceutils_unix.cpp
tascore/corelib/tasdeviceutils_unix.cpp
/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of Testability Driver Qt Agent ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected] . ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "tasdeviceutils.h" #if defined(TAS_MAEMO) && defined(HAVE_QAPP) #include <MApplication> #include <MWindow> #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/Xatom.h> #endif #ifdef TAS_MAEMO #include <qmsystem2/qmdisplaystate.h> #endif #include <taslogger.h> #include <stdlib.h> #include <sys/resource.h> #include <time.h> #if defined(Q_WS_X11) #include <X11/Xlib.h> #include <X11/extensions/XTest.h> #endif #include <QEvent> #if defined(TAS_MAEMO) && defined(HAVE_QAPP) namespace { int getOrientationForWidget(QWidget* widget) { Display* display = QX11Info::display(); Atom orientationAngleAtom = XInternAtom(display, "_MEEGOTOUCH_ORIENTATION_ANGLE", True); int orientation = -1; Atom actual_type; int actual_format; unsigned long nitems; unsigned long bytes_after; unsigned char *prop = 0; int status; if (widget && orientationAngleAtom != None) { TasLogger::logger()->debug("got widget and orientation angle"); status = XGetWindowProperty(display, widget->effectiveWinId(), orientationAngleAtom, 0, 1024, False, AnyPropertyType, &actual_type, &actual_format, &nitems, &bytes_after, &prop); if (status!=0 || !prop || actual_format == None) { //NOP } else { TasLogger::logger()->debug("setting it!"); orientation = prop[1] * 256; orientation += prop[0]; if (prop) XFree(prop); return orientation; } } if (prop) XFree(prop); return -1; } } #endif TasDeviceUtils::TasDeviceUtils() { gpuDetailsHandler = 0; pwrDetailsHandler = 0; } void TasDeviceUtils::resetInactivity() { #ifdef TAS_MAEMO TasLogger::logger()->debug("TasDeviceUtils:: resetting inactivity"); MeeGo::QmDisplayState state; if (!state.set(MeeGo::QmDisplayState::On)) { TasLogger::logger()->warning("TasDeviceUtils:: setting displaystate failed!"); } if (!state.setBlankingPause()) { TasLogger::logger()->warning("TasDeviceUtils:: setBlankingPause failed!"); } #endif } GpuMemDetails TasDeviceUtils::gpuMemDetails() { GpuMemDetails details; details.isValid = false; return details; } PwrDetails TasDeviceUtils::pwrDetails() { PwrDetails details; details.isValid = false; return details; } void TasDeviceUtils::stopPwrData() {} // TODO remove the duplicate code (maemo version) /*! Returns the heap size of the process. -1 means not supported. */ int TasDeviceUtils::currentProcessHeapSize() { char buf[30]; unsigned size = -1; // total program size // If needed later. // unsigned resident = -1;// resident set size // unsigned share;// shared pages // unsigned text;// text (code) // unsigned lib;// library // unsigned data;// data/stack // unsigned dt;// dirty pages (unused in Linux 2.6) snprintf(buf, 30, "/proc/%u/statm", (unsigned)getpid()); FILE* pf = fopen(buf, "r"); if (pf) { fscanf(pf, "%u "/* %u %u %u %u %u " */, &size /*,&resident, &share, &text, &lib, &data */); } fclose(pf); return size; } /*! * /proc/cpuinfo data */ void TasDeviceUtils::addSystemInformation(TasObject& object) { QFile file("/proc/cpuinfo"); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { return; } TasObject& child = object.addObject(); child.setName("/proc/cpuinfo"); QTextStream in(&file); QString line = in.readLine(); while (!line.isNull()) { QStringList list = line.split(":"); if (list.size() == 2) { child.addAttribute(list[0].trimmed(),list[1].trimmed()); } line = in.readLine(); } } qreal TasDeviceUtils::currentProcessCpuTime() { struct timespec now; if(clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &now) == 0) { return (double)now.tv_sec + (double)now.tv_nsec / 1000000000.0; } else { return -1.0; } } /*! Not supported */ void TasDeviceUtils::addSystemMemoryStatus(TasObject& object) { FILE *meminfo = fopen("/proc/meminfo", "r"); int ram = -1; int ramFree = -1; int cached = -1; if(meminfo == NULL) { } else { char line[256]; while(fgets(line, sizeof(line), meminfo)) { if (ram == -1) { sscanf(line, "MemTotal: %d kB", &ram); } else if (ramFree == -1) { sscanf(line, "MemFree: %d kB", &ramFree); } else if (cached == -1) { sscanf(line, "Cached: %d kB", &cached); break; } } object.addAttribute("total",QString::number(ram)); object.addAttribute("available",QString::number(ramFree)); object.addAttribute("cached",QString::number(ramFree)); // If we got here, then we couldn't find the proper line in the meminfo file: // do something appropriate like return an error code, throw an exception, etc. fclose(meminfo); } } // void TasDeviceUtils::tapScreen(int x, int y, int duration) // { // } void TasDeviceUtils::sendMouseEvent(int x, int y, Qt::MouseButton button, QEvent::Type type, uint /*pointerNumber*/) { #if defined(Q_WS_X11) Display* dpy = 0; Window root = None; dpy = XOpenDisplay(NULL); root = DefaultRootWindow(dpy); if (!dpy) { TasLogger::logger()->error("TasDeviceUtils::sendMouseEvent No Display detected! Unable to run X commands"); return; } int keycode = Button1; switch (button) { case Qt::LeftButton: keycode = Button1; break; case Qt::MidButton: keycode = Button2; break; case Qt::RightButton: keycode = Button3; break; default: break; } bool down = type == QEvent::MouseButtonPress || type == QEvent::GraphicsSceneMousePress; if (down || type == QEvent::MouseMove) { // TODO how about dblclick? // Move the Cursor to given coords XWarpPointer(dpy, None, root, 0, 0, 0, 0, x,y); XFlush(dpy); } if (type == QEvent::MouseButtonPress || type == QEvent::MouseButtonRelease || type == QEvent::GraphicsSceneMousePress || type == QEvent::GraphicsSceneMouseRelease) { XTestFakeButtonEvent(dpy, keycode, down, CurrentTime); XFlush(dpy); } XCloseDisplay(dpy); #elif defined(TAS_WAYLAND) #endif } /*! Not implemented, true returned to avoid autostart. */ bool TasDeviceUtils::isServerRunning() { return true; } int TasDeviceUtils::getOrientation() { int orientation = -1; #if defined(TAS_MAEMO) && defined(HAVE_QAPP) TasLogger::logger()->debug("how about active widget?"); QWidget* widget = QApplication::activeWindow(); if (widget) { orientation = getOrientationForWidget(widget); } else { // If the window doesn't any active window, take first one from the list. QWidgetList list = QApplication::topLevelWidgets(); if (!list.isEmpty()) { foreach(QWidget* w, list) { orientation = getOrientationForWidget(w); if (orientation != -1) { break; } } } } if (orientation == -1) { TasLogger::logger()->debug("setting orientation per meegoapp"); MApplication* app = MApplication::instance(); if (app) { // activeWindow() would SIGABORT if called without verifying the mapp instance MWindow *w = MApplication::activeWindow(); if (w) { M::OrientationAngle angle = w->orientationAngle(); switch(angle) { case M::Angle90: orientation = 90; break; case M::Angle180: orientation = 180; break; case M::Angle270: orientation = 270; break; case M::Angle0: default: break; } } } } #endif return orientation; }
/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of Testability Driver Qt Agent ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected] . ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "tasdeviceutils.h" #if defined(TAS_MAEMO) && defined(HAVE_QAPP) #include <MApplication> #include <MWindow> #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/Xatom.h> #endif #ifdef TAS_MAEMO #include <qmsystem2/qmdisplaystate.h> #endif #include <taslogger.h> #include <stdlib.h> #include <sys/resource.h> #include <time.h> #if defined(Q_WS_X11) #include <X11/Xlib.h> #include <X11/extensions/XTest.h> #endif #include <QEvent> #if defined(TAS_MAEMO) && defined(HAVE_QAPP) namespace { int getOrientationForWidget(QWidget* widget) { Display* display = QX11Info::display(); Atom orientationAngleAtom = XInternAtom(display, "_MEEGOTOUCH_ORIENTATION_ANGLE", True); int orientation = -1; Atom actual_type; int actual_format; unsigned long nitems; unsigned long bytes_after; unsigned char *prop = 0; int status; if (widget && orientationAngleAtom != None) { TasLogger::logger()->debug("got widget and orientation angle"); status = XGetWindowProperty(display, widget->effectiveWinId(), orientationAngleAtom, 0, 1024, False, AnyPropertyType, &actual_type, &actual_format, &nitems, &bytes_after, &prop); if (status!=0 || !prop || actual_format == None) { //NOP } else { TasLogger::logger()->debug("setting it!"); orientation = prop[1] * 256; orientation += prop[0]; if (prop) XFree(prop); return orientation; } } if (prop) XFree(prop); return -1; } } #endif TasDeviceUtils::TasDeviceUtils() { gpuDetailsHandler = 0; pwrDetailsHandler = 0; } void TasDeviceUtils::resetInactivity() { #ifdef TAS_MAEMO TasLogger::logger()->debug("TasDeviceUtils:: resetting inactivity"); MeeGo::QmDisplayState state; if (!state.set(MeeGo::QmDisplayState::On)) { TasLogger::logger()->warning("TasDeviceUtils:: setting displaystate failed!"); } if (!state.setBlankingPause()) { TasLogger::logger()->warning("TasDeviceUtils:: setBlankingPause failed!"); } #endif } GpuMemDetails TasDeviceUtils::gpuMemDetails() { GpuMemDetails details; details.isValid = false; return details; } PwrDetails TasDeviceUtils::pwrDetails() { PwrDetails details; details.isValid = false; return details; } void TasDeviceUtils::stopPwrData() {} // TODO remove the duplicate code (maemo version) /*! Returns the heap size of the process. -1 means not supported. */ int TasDeviceUtils::currentProcessHeapSize() { char buf[30]; unsigned size = -1; // total program size // If needed later. // unsigned resident = -1;// resident set size // unsigned share;// shared pages // unsigned text;// text (code) // unsigned lib;// library // unsigned data;// data/stack // unsigned dt;// dirty pages (unused in Linux 2.6) snprintf(buf, 30, "/proc/%u/statm", (unsigned)getpid()); FILE* pf = fopen(buf, "r"); if (pf) { fscanf(pf, "%u "/* %u %u %u %u %u " */, &size /*,&resident, &share, &text, &lib, &data */); } fclose(pf); return size; } /*! * /proc/cpuinfo data */ void TasDeviceUtils::addSystemInformation(TasObject& object) { QFile file("/proc/cpuinfo"); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { return; } TasObject& child = object.addObject(); child.setName("/proc/cpuinfo"); QTextStream in(&file); QString line = in.readLine(); while (!line.isNull()) { QStringList list = line.split(":"); if (list.size() == 2) { child.addAttribute(list[0].trimmed(),list[1].trimmed()); } line = in.readLine(); } } qreal TasDeviceUtils::currentProcessCpuTime() { struct timespec now; if(clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &now) == 0) { return (double)now.tv_sec + (double)now.tv_nsec / 1000000.0; } else { return -1.0; } } /*! Not supported */ void TasDeviceUtils::addSystemMemoryStatus(TasObject& object) { FILE *meminfo = fopen("/proc/meminfo", "r"); int ram = -1; int ramFree = -1; int cached = -1; if(meminfo == NULL) { } else { char line[256]; while(fgets(line, sizeof(line), meminfo)) { if (ram == -1) { sscanf(line, "MemTotal: %d kB", &ram); } else if (ramFree == -1) { sscanf(line, "MemFree: %d kB", &ramFree); } else if (cached == -1) { sscanf(line, "Cached: %d kB", &cached); break; } } object.addAttribute("total",QString::number(ram)); object.addAttribute("available",QString::number(ramFree)); object.addAttribute("cached",QString::number(ramFree)); // If we got here, then we couldn't find the proper line in the meminfo file: // do something appropriate like return an error code, throw an exception, etc. fclose(meminfo); } } // void TasDeviceUtils::tapScreen(int x, int y, int duration) // { // } void TasDeviceUtils::sendMouseEvent(int x, int y, Qt::MouseButton button, QEvent::Type type, uint /*pointerNumber*/) { #if defined(Q_WS_X11) Display* dpy = 0; Window root = None; dpy = XOpenDisplay(NULL); root = DefaultRootWindow(dpy); if (!dpy) { TasLogger::logger()->error("TasDeviceUtils::sendMouseEvent No Display detected! Unable to run X commands"); return; } int keycode = Button1; switch (button) { case Qt::LeftButton: keycode = Button1; break; case Qt::MidButton: keycode = Button2; break; case Qt::RightButton: keycode = Button3; break; default: break; } bool down = type == QEvent::MouseButtonPress || type == QEvent::GraphicsSceneMousePress; if (down || type == QEvent::MouseMove) { // TODO how about dblclick? // Move the Cursor to given coords XWarpPointer(dpy, None, root, 0, 0, 0, 0, x,y); XFlush(dpy); } if (type == QEvent::MouseButtonPress || type == QEvent::MouseButtonRelease || type == QEvent::GraphicsSceneMousePress || type == QEvent::GraphicsSceneMouseRelease) { XTestFakeButtonEvent(dpy, keycode, down, CurrentTime); XFlush(dpy); } XCloseDisplay(dpy); #elif defined(TAS_WAYLAND) #endif } /*! Not implemented, true returned to avoid autostart. */ bool TasDeviceUtils::isServerRunning() { return true; } int TasDeviceUtils::getOrientation() { int orientation = -1; #if defined(TAS_MAEMO) && defined(HAVE_QAPP) TasLogger::logger()->debug("how about active widget?"); QWidget* widget = QApplication::activeWindow(); if (widget) { orientation = getOrientationForWidget(widget); } else { // If the window doesn't any active window, take first one from the list. QWidgetList list = QApplication::topLevelWidgets(); if (!list.isEmpty()) { foreach(QWidget* w, list) { orientation = getOrientationForWidget(w); if (orientation != -1) { break; } } } } if (orientation == -1) { TasLogger::logger()->debug("setting orientation per meegoapp"); MApplication* app = MApplication::instance(); if (app) { // activeWindow() would SIGABORT if called without verifying the mapp instance MWindow *w = MApplication::activeWindow(); if (w) { M::OrientationAngle angle = w->orientationAngle(); switch(angle) { case M::Angle90: orientation = 90; break; case M::Angle180: orientation = 180; break; case M::Angle270: orientation = 270; break; case M::Angle0: default: break; } } } } #endif return orientation; }
Return milli-seconds instead seconds
Return milli-seconds instead seconds
C++
lgpl-2.1
nomovok-opensource/cutedriver-agent_qt,nomovok-opensource/cutedriver-agent_qt,rferrazz/cutedriver-agent_qt,rasjani/cutedriver-agent_qt,rferrazz/cutedriver-agent_qt,nomovok-opensource/cutedriver-agent_qt,rasjani/cutedriver-agent_qt,rasjani/cutedriver-agent_qt,rferrazz/cutedriver-agent_qt
ac45ac861d891817105987d1a83e678e4c02ffc7
test/modbus_poller/test_modbus_poller.cpp
test/modbus_poller/test_modbus_poller.cpp
#define CATCH_CONFIG_MAIN #include "Catch.hpp" #include <boost/asio.hpp> #include "ModbusConsts.hpp" #include "ModbusTypes.hpp" #include "ModbusEncoder.hpp" #include "ModbusDecoder.hpp" #include "SocketConnector.hpp" #include "ModbusPollTask.hpp" #include "ModbusPoller.hpp" #include <thread> boost::asio::ip::tcp::endpoint make_endpoint(const std::string& ip, uint16_t port) { return boost::asio::ip::tcp::endpoint(boost::asio::ip::address::from_string(ip), port); } boost::posix_time::milliseconds make_millisecs(std::size_t msecs) { return boost::posix_time::milliseconds(msecs); } void modbusServer(const std::vector<uint8_t>& expected_request, const::std::vector<uint8_t>& response) { boost::asio::io_service io; boost::asio::ip::tcp::acceptor acceptor(io, boost::asio::ip::tcp::endpoint(boost::asio::ip::address::from_string("127.0.0.1"), 8502)); acceptor.set_option(boost::asio::socket_base::reuse_address(true)); boost::asio::ip::tcp::socket sock(io); acceptor.accept(sock); std::vector<uint8_t> req; try { while(true) { req.resize(expected_request.size()); std::cout << "Expecting request (" << expected_request.size() << " bytes)" << std::endl; boost::asio::read(sock, boost::asio::buffer(req)); REQUIRE(expected_request == req); boost::asio::write(sock, boost::asio::buffer(response)); std::cout << "Response sent (" << response.size() << " bytes)" << std::endl; } } catch(const boost::system::system_error& ec) { REQUIRE (ec.what() == std::string("read: End of file")); } } class OneTimeTcpAcceptor { public: OneTimeTcpAcceptor(boost::asio::io_service& io) : m_timer(io), m_acceptor(io), m_client(io), m_connected(false) {} ~OneTimeTcpAcceptor() { REQUIRE(m_connected == true); } void async_accept(const boost::asio::ip::tcp::endpoint& ep, const boost::posix_time::milliseconds& delay) { m_endpoint = ep; m_timer.expires_from_now(delay); m_timer.async_wait([this] (const boost::system::error_code& ec) { REQUIRE(!ec); onTimer(); }); } private: boost::asio::deadline_timer m_timer; boost::asio::ip::tcp::acceptor m_acceptor; boost::asio::ip::tcp::socket m_client; boost::asio::ip::tcp::endpoint m_endpoint; bool m_connected; void onTimer() { m_acceptor.open(boost::asio::ip::tcp::v4()); m_acceptor.set_option(boost::asio::socket_base::reuse_address(true)); m_acceptor.bind(make_endpoint("127.0.0.1", 8502)); m_acceptor.listen(); m_acceptor.async_accept(m_client, [this](const boost::system::error_code& ec) { m_acceptor.close(); REQUIRE(!ec); m_connected = true; }); } }; TEST_CASE("ModbusPoller - no polling tasks", "[ModbusPoller]") { boost::asio::io_service io; OneTimeTcpAcceptor acceptor(io); std::shared_ptr<ModbusPoller> poller = std::make_shared<ModbusPoller>(io, make_endpoint("127.0.0.1", 8502), make_millisecs(200)); poller->start(); acceptor.async_accept(make_endpoint("127.0.0.1", 8502), make_millisecs(200)); io.run(); } TEST_CASE("ModbusPoller - one polling task", "[ModbusPoller]") { std::vector<uint8_t> req; std::vector<uint8_t> rsp; modbus::tcp::Encoder encoder(modbus::tcp::UnitId(0xab), modbus::tcp::TransactionId(0x0002)); encoder.encodeReadCoilsReq(modbus::tcp::Address(0x0123), modbus::tcp::NumBits(8), req); encoder.encodeReadCoilsRsp(std::vector<bool>{0, 1, 0, 0, 1, 1, 0, 1}, rsp); std::thread t([&req, &rsp]() { modbusServer(req, rsp); }); boost::asio::io_service io; std::shared_ptr<ModbusPoller> poller = std::make_shared<ModbusPoller>(io, make_endpoint("127.0.0.1", 8502), make_millisecs(100)); std::size_t num_samples = 0; std::vector<uint8_t> rx_buffer; poller->addPollTask(req, rx_buffer, make_millisecs(500), [&num_samples, &rx_buffer, &rsp]() { num_samples++; std::cout << "sample received" << std::endl; REQUIRE(rx_buffer == rsp); }); boost::asio::deadline_timer tmr(io); tmr.expires_from_now(make_millisecs(2200)); tmr.async_wait([poller](const boost::system::error_code& ec) { REQUIRE( !ec ); poller->cancel(); }); poller->start(); io.run(); t.join(); REQUIRE(num_samples == 5); }
#define CATCH_CONFIG_MAIN #include "Catch.hpp" #include <boost/asio.hpp> #include "ModbusConsts.hpp" #include "ModbusTypes.hpp" #include "ModbusEncoder.hpp" #include "ModbusDecoder.hpp" #include "SocketConnector.hpp" #include "ModbusPollTask.hpp" #include "ModbusPoller.hpp" #include "ModbusServerDevice.hpp" #include "ModbusServer.hpp" #include <thread> boost::asio::ip::tcp::endpoint make_endpoint(const std::string& ip, uint16_t port) { return boost::asio::ip::tcp::endpoint(boost::asio::ip::address::from_string(ip), port); } boost::posix_time::milliseconds make_millisecs(std::size_t msecs) { return boost::posix_time::milliseconds(msecs); } void modbusServer(const std::vector<uint8_t>& expected_request, const::std::vector<uint8_t>& response) { boost::asio::io_service io; boost::asio::ip::tcp::acceptor acceptor(io, boost::asio::ip::tcp::endpoint(boost::asio::ip::address::from_string("127.0.0.1"), 8502)); acceptor.set_option(boost::asio::socket_base::reuse_address(true)); boost::asio::ip::tcp::socket sock(io); acceptor.accept(sock); std::vector<uint8_t> req; try { while(true) { req.resize(expected_request.size()); std::cout << "Expecting request (" << expected_request.size() << " bytes)" << std::endl; boost::asio::read(sock, boost::asio::buffer(req)); REQUIRE(expected_request == req); boost::asio::write(sock, boost::asio::buffer(response)); std::cout << "Response sent (" << response.size() << " bytes)" << std::endl; } } catch(const boost::system::system_error& ec) { REQUIRE (ec.what() == std::string("read: End of file")); } } class OneTimeTcpAcceptor { public: OneTimeTcpAcceptor(boost::asio::io_service& io) : m_timer(io), m_acceptor(io), m_client(io), m_connected(false) {} ~OneTimeTcpAcceptor() { REQUIRE(m_connected == true); } void asyncAcceptWithDelay(const boost::asio::ip::tcp::endpoint& ep, const boost::posix_time::milliseconds& delay, std::function<void(void)> cb) { m_endpoint = ep; m_callback = cb; m_timer.expires_from_now(delay); m_timer.async_wait([this] (const boost::system::error_code& ec) { REQUIRE(!ec); onTimer(); }); } void asyncAccept(const boost::asio::ip::tcp::endpoint& ep, std::function<void(void)> cb) { m_endpoint = ep; m_callback = cb; m_timer.get_io_service().post([this]() { onTimer(); }); } boost::asio::ip::tcp::socket& getConnectedClient() { return m_client; } private: boost::asio::deadline_timer m_timer; boost::asio::ip::tcp::acceptor m_acceptor; boost::asio::ip::tcp::socket m_client; boost::asio::ip::tcp::endpoint m_endpoint; bool m_connected; std::function<void(void)> m_callback; void onTimer() { m_acceptor.open(boost::asio::ip::tcp::v4()); m_acceptor.set_option(boost::asio::socket_base::reuse_address(true)); m_acceptor.bind(make_endpoint("127.0.0.1", 8502)); m_acceptor.listen(); m_acceptor.async_accept(m_client, [this](const boost::system::error_code& ec) { m_acceptor.close(); REQUIRE(!ec); m_connected = true; m_callback(); }); } }; TEST_CASE("ModbusPoller - no polling tasks", "[ModbusPoller]") { boost::asio::io_service io; OneTimeTcpAcceptor acceptor(io); std::shared_ptr<ModbusPoller> poller = std::make_shared<ModbusPoller>(io, make_endpoint("127.0.0.1", 8502), make_millisecs(200)); poller->start(); acceptor.asyncAcceptWithDelay(make_endpoint("127.0.0.1", 8502), make_millisecs(200), []() {}); io.run(); } TEST_CASE("ModbusPoller - one polling task", "[ModbusPoller]") { class MyTest : public modbus::tcp::ServerDevice { public: MyTest() : modbus::tcp::ServerDevice(modbus::tcp::UnitId(0xab)), m_io(), m_server(m_io, *this), m_poller(std::make_shared<ModbusPoller>(m_io, make_endpoint("127.0.0.1", 8502), make_millisecs(100))), m_request(), m_expectedSample(), m_rxSample(), m_coils({0,1,0,0,1,1,0,1}), m_numReceivedSamples(0) { modbus::tcp::Encoder encoder(modbus::tcp::UnitId(0xab), modbus::tcp::TransactionId(0x0002)); encoder.encodeReadCoilsReq(modbus::tcp::Address(0x0123), modbus::tcp::NumBits(8), m_request); encoder.encodeReadCoilsRsp(m_coils, m_expectedSample); m_poller->addPollTask(m_request, m_rxSample, make_millisecs(500), [this]() { std::cout << "Sample!" << std::endl; m_numReceivedSamples++; REQUIRE(m_rxSample == m_expectedSample); if (m_numReceivedSamples == 3) { m_poller->cancel(); m_server.stop(); } }); } ~MyTest() { REQUIRE(m_numReceivedSamples == 3); } void start() { m_server.start(make_endpoint("127.0.0.1", 8502), []() {}); m_poller->start(); m_io.run(); } protected: bool getCoil(const modbus::tcp::Address& addr) const override { return m_coils.at(addr.get() - 0x0123); } private: using PModbusPoller = std::shared_ptr<ModbusPoller>; boost::asio::io_service m_io; modbus::tcp::Server m_server; PModbusPoller m_poller; std::vector<uint8_t> m_request; std::vector<uint8_t> m_expectedSample; std::vector<uint8_t> m_rxSample; std::vector<uint8_t> m_coils; std::size_t m_numReceivedSamples; }; MyTest test; test.start(); }
Modify test for ModbusPoller to use modbus::tcp::Server/ServerDevice
Modify test for ModbusPoller to use modbus::tcp::Server/ServerDevice
C++
mit
gkarvounis/libmodbusc-,gkarvounis/libmodbusc-
7376e7ce8670310a87dc8878e38e583b82d48699
src/replay.cpp
src/replay.cpp
/* * replay.cpp * * eXploration module for Autonomous Robotic Embedded Systems * * xares replay : replay dump from xares (and xares-genom) * * author: Cyril Robin <[email protected]> * created: 2013-09-19 * license: BSD */ #include <ostream> #include <fstream> #include <sys/time.h> #include "xares/xares.hpp" #include "gladys/point.hpp" #include "gladys/weight_map.hpp" int replay_genom_dump( const std::string& path_to_dump_file) {//{{{ std::ifstream dump_file; dump_file.open (path_to_dump_file) ; if ( dump_file.is_open () ) { // init struct timeval tv0, tv1; std::string line, name ; gladys::points_t r_pos; int n, max_nf ; double min_size, x_origin, y_origin, height_max, width_max ; double x, y, yaw, min_dist, max_dist ; //read data getline (dump_file,line) ; std::istringstream iss1(line); iss1 >> name >> n ; std::cerr << "[Xares replay] r_pos ["<< n << "] ="; while ( n-- > 0) { iss1 >> x >> y ; r_pos.push_back( gladys::point_xy_t {x,y} ); std::cerr << " ("<< x << "," << y << ")"; } std::cerr << std::endl; getline (dump_file,line) ; std::istringstream iss2(line); iss2 >> name >> yaw ; std::cerr << "[Xares replay] yaw = " << yaw << std::endl; // load and display internal params getline (dump_file,line) ; std::istringstream iss3(line); iss3 >> name >> max_nf >> min_size >> min_dist >> max_dist ; std::cerr << "[Xares replay] internal params " << "(max_nf,min_size,min_dist,max_dist) = (" << max_nf << "," << min_size << "," << min_dist << "," << max_dist << ")" << std::endl; std::cerr << "[Xares replay] max nbr of frontiers = " << max_nf << std::endl; getline (dump_file,line) ; gladys::weight_map wm ( line ); // weightmap : origin, size, scale std::cerr << "[Xares repay] weight map: (x0,y0,xSc,ySc,W,H) = (" << wm.get_utm_pose_x()<< "," << wm.get_utm_pose_y()<< "," << wm.get_scale_x() << "," << wm.get_scale_y() << "," << wm.get_height() << "," << wm.get_width() << ")" << std::endl; // bounded area to explore getline (dump_file,line) ; std::istringstream iss4(line); iss4 >> name >> x_origin >> y_origin >> height_max >> width_max ; std::cerr << "[Xares replay] bounded area : (x0,y0,W,H) " << x_origin << "," << y_origin << "," << height_max << "," << width_max << ")" << std::endl; dump_file.close(); // load the planner gettimeofday(&tv0, NULL); xares::xares xp( wm, x_origin, y_origin, height_max, width_max ); gettimeofday(&tv1, NULL); std::cerr << "[Xares replay] planner loaded (" << (tv1.tv_sec - tv0.tv_sec) * 1000 + (tv1.tv_usec - tv0.tv_usec) / 1000 << " ms)." << std::endl; // Set internal parameters for xares xp.set_params( max_nf, min_size, min_dist, max_dist ); std::cerr << "[Xares replay] parameters settled. Let's plan !" << std::endl; //plan (=replay !) gettimeofday(&tv0, NULL); xares::xares::return_value rv = xp.plan( r_pos, yaw ); gettimeofday(&tv1, NULL); // parse results if ( rv == xares::xares::XARES_FAILURE ) { std::cerr << "[Xares replay] #EEE# xares : unexpected data ; unable to compute frontiers :'( " << std::endl; return EXIT_SUCCESS; } if ( rv == xares::xares::XARES_NO_FRONTIER ) { std::cerr << "[Xares replay] #EEE# xares : no valuable frontier detected." << std::endl; return EXIT_SUCCESS; } // From here, there should be a valid plan std::cerr << "[Xares replay] Plan computed (" << (tv1.tv_sec - tv0.tv_sec) * 1000 + (tv1.tv_usec - tv0.tv_usec) / 1000 << " ms)" << std::endl; //get planned path const gladys::path_t& path = xp.get_goal().path ; for (unsigned int i = 0 ; i < path.size() ; i++) std::cerr << "[Xares replay ] ----waypoint #" << i << " = (" << path[i][0]<< "," << path[i][1] <<")"<<std::endl; // get poster path gladys::path_t::const_iterator it; double dist = 0.0; gladys::point_xy_t curr = path.front() ; unsigned int pt = 0 ; for ( it = path.begin(); it != path.end() ; ++it) { dist += gladys::distance( curr, *it ); curr = *it; if ( dist > 6.0 ) { std::cerr << "[Xares replay ] ---- poster waypoint #" << pt++ << " = (" << (*it)[0]<< "," << (*it)[1] <<")"<<std::endl; } } std::cerr << "[Xares replay ] ---- poster waypoint #" << pt << " = (" << curr[0]<< "," << curr[1] <<")"<<std::endl; // ASCII plot of weightmap, seed & goal std::cerr << "[Xares replay ] ASCII weight map : " << std::endl; // foreach from (origin) to (dim+origin) for ( double j = wm.get_utm_pose_y(); j < wm.get_width()*wm.get_scale_y() + wm.get_utm_pose_y(); j+= wm.get_scale_y() ) { //if ( j < -21 || j > 19 ) continue; //cropping for (double i = wm.get_utm_pose_x(); i < wm.get_height()*wm.get_scale_x() + wm.get_utm_pose_x(); i+= wm.get_scale_x() ) { //if ( i < 0 || i > 60 ) continue; //cropping // Special points // O = origin // S = Seed // G = Goal if ( i == 0 && j == 0 ) { // origin std::cerr << "O"; continue; } if ( i == r_pos[0][0] && j == r_pos[0][1] ) { // seed std::cerr << "S"; continue; } if ( i == curr[0] && j == curr[1] ) { // goal std::cerr << "G"; continue;} // Common points // u = unknown // . = known // # = obstacle double w = wm.get_weight_band()[ wm.index_utm( gladys::point_xy_t {(double)i,(double)j} )]; if (w < 0) std::cerr << "u"; //unknonwn else if (w > 100 ) std::cerr << "#"; //obstacle else std::cerr << "."; } std::cerr << std::endl; } } else { std::cerr << "[Xares replay] Cannot open provided dump file. :-(" << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }//}}} int replay_lib_dump(char dumpFile[]) {//{{{ std::cerr << "Not yet implemented..." << std::endl; return EXIT_SUCCESS; }//}}} int main(int argc, char **argv) {//{{{ int return_value ; return_value = replay_genom_dump( argv[1] ) ; std::cerr << "[Xares replay] Done." << std::endl; return return_value; }//}}}
/* * replay.cpp * * eXploration module for Autonomous Robotic Embedded Systems * * xares replay : replay dump from xares (and xares-genom) * * author: Cyril Robin <[email protected]> * created: 2013-09-19 * license: BSD */ #include <ostream> #include <fstream> #include <sys/time.h> #include "xares/xares.hpp" #include "gladys/point.hpp" #include "gladys/weight_map.hpp" int replay_genom_dump( const std::string& path_to_dump_file) {//{{{ std::ifstream dump_file; dump_file.open (path_to_dump_file) ; if ( dump_file.is_open () ) { // init struct timeval tv0, tv1; std::string line, name ; gladys::points_t r_pos; int n, max_nf ; double min_size, x_origin, y_origin, height_max, width_max ; double x, y, yaw, min_dist, max_dist ; //read data getline (dump_file,line) ; std::istringstream iss1(line); iss1 >> name >> n ; std::cerr << "[Xares replay] r_pos ["<< n << "] ="; while ( n-- > 0) { iss1 >> x >> y ; r_pos.push_back( gladys::point_xy_t {x,y} ); std::cerr << " ("<< x << "," << y << ")"; } std::cerr << std::endl; getline (dump_file,line) ; std::istringstream iss2(line); iss2 >> name >> yaw ; std::cerr << "[Xares replay] yaw = " << yaw << std::endl; // load and display internal params getline (dump_file,line) ; std::istringstream iss3(line); iss3 >> name >> max_nf >> min_size >> min_dist >> max_dist ; std::cerr << "[Xares replay] internal params " << "(max_nf,min_size,min_dist,max_dist) = (" << max_nf << "," << min_size << "," << min_dist << "," << max_dist << ")" << std::endl; std::cerr << "[Xares replay] max nbr of frontiers = " << max_nf << std::endl; getline (dump_file,line) ; gladys::weight_map wm ( line ); // weightmap : origin, size, scale std::cerr << "[Xares repay] weight map: (x0,y0,xSc,ySc,W,H) = (" << wm.get_utm_pose_x()<< "," << wm.get_utm_pose_y()<< "," << wm.get_scale_x() << "," << wm.get_scale_y() << "," << wm.get_height() << "," << wm.get_width() << ")" << std::endl; // bounded area to explore getline (dump_file,line) ; std::istringstream iss4(line); iss4 >> name >> x_origin >> y_origin >> height_max >> width_max ; std::cerr << "[Xares replay] bounded area : (x0,y0,W,H) " << x_origin << "," << y_origin << "," << height_max << "," << width_max << ")" << std::endl; dump_file.close(); // load the planner gettimeofday(&tv0, NULL); xares::xares xp( wm, x_origin, y_origin, height_max, width_max ); gettimeofday(&tv1, NULL); std::cerr << "[Xares replay] planner loaded (" << (tv1.tv_sec - tv0.tv_sec) * 1000 + (tv1.tv_usec - tv0.tv_usec) / 1000 << " ms)." << std::endl; // Set internal parameters for xares xp.set_params( max_nf, min_size, min_dist, max_dist ); std::cerr << "[Xares replay] parameters settled. Let's plan !" << std::endl; //plan (=replay !) gettimeofday(&tv0, NULL); xares::xares::return_value rv = xp.plan( r_pos, yaw ); gettimeofday(&tv1, NULL); // parse results if ( rv == xares::xares::XARES_FAILURE ) { std::cerr << "[Xares replay] #EEE# xares : unexpected data ; unable to compute frontiers :'( " << std::endl; return EXIT_SUCCESS; } if ( rv == xares::xares::XARES_NO_FRONTIER ) { std::cerr << "[Xares replay] #EEE# xares : no valuable frontier detected." << std::endl; return EXIT_SUCCESS; } // From here, there should be a valid plan std::cerr << "[Xares replay] Plan computed (" << (tv1.tv_sec - tv0.tv_sec) * 1000 + (tv1.tv_usec - tv0.tv_usec) / 1000 << " ms)" << std::endl; //get planned path const gladys::path_t& path = xp.get_goal().path ; for (unsigned int i = 0 ; i < path.size() ; i++) std::cerr << "[Xares replay ] ----waypoint #" << i << " = (" << path[i][0]<< "," << path[i][1] <<")"<<std::endl; // get poster path gladys::path_t::const_iterator it; double dist = 0.0; gladys::point_xy_t curr = path.front() ; unsigned int pt = 0 ; for ( it = path.begin(); it != path.end() ; ++it) { dist += gladys::distance( curr, *it ); curr = *it; if ( dist > 6.0 ) { std::cerr << "[Xares replay ] ---- poster waypoint #" << pt++ << " = (" << (*it)[0]<< "," << (*it)[1] <<")"<<std::endl; } } std::cerr << "[Xares replay ] ---- poster waypoint #" << pt << " = (" << curr[0]<< "," << curr[1] <<")"<<std::endl; // ASCII plot of weightmap, seed & goal std::cerr << "[Xares replay ] ASCII weight map : " << std::endl; size_t index0 = wm.index_utm( gladys::point_xy_t { 0.0 , 0.0 } ) ; //origin size_t indexS = wm.index_utm( r_pos[0] ) ; // seed (robot position) size_t indexG = wm.index_utm( curr ) ; // goal size_t index_curr ; // foreach from (origin) to (dim+origin) for ( double j = wm.get_utm_pose_y(); j < wm.get_width()*wm.get_scale_y() + wm.get_utm_pose_y(); j+= wm.get_scale_y() ) { if ( j < y_origin || j > width_max ) continue; //cropping for (double i = wm.get_utm_pose_x(); i < wm.get_height()*wm.get_scale_x() + wm.get_utm_pose_x(); i+= wm.get_scale_x() ) { if ( i < x_origin || i > height_max ) continue; //cropping index_curr = wm.index_utm( gladys::point_xy_t {(double)i,(double)j} ); // Special points // O = origin // S = Seed // G = Goal if ( index_curr == index0 ) { // origin std::cerr << "O"; continue; } if ( index_curr == indexS ) { // seed std::cerr << "S"; continue; } if ( index_curr == indexG ) { // goal std::cerr << "G"; continue;} // Common points // u = unknown // . = known // # = obstacle double w = wm.get_weight_band()[ index_curr ]; if (w < 0) std::cerr << "u"; //unknonwn else if (w > 100 ) std::cerr << "#"; //obstacle else std::cerr << "."; } std::cerr << std::endl; } } else { std::cerr << "[Xares replay] Cannot open provided dump file. :-(" << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }//}}} int replay_lib_dump(char dumpFile[]) {//{{{ std::cerr << "Not yet implemented..." << std::endl; return EXIT_SUCCESS; }//}}} int main(int argc, char **argv) {//{{{ int return_value ; return_value = replay_genom_dump( argv[1] ) ; std::cerr << "[Xares replay] Done." << std::endl; return return_value; }//}}}
Fix the display of the seed.
[replay] Fix the display of the seed. Use index comparison to find the correct position.
C++
bsd-2-clause
cyrobin/xares
c7bc32e58b861e6a8346b883fa338a8d746266b2
test/performance/packed_planar_fusion.cpp
test/performance/packed_planar_fusion.cpp
#include "Halide.h" #include <stdio.h> #include "clock.h" #include <memory> using namespace Halide; double test_copy(Image<uint8_t> src, Image<uint8_t> dst) { Var x, y, c; Func f; f(x, y, c) = src(x, y, c); for (int i = 0; i < 3; i++) { f.output_buffer() .set_stride(i, dst.stride(i)) .set_extent(i, dst.extent(i)) .set_min(i, dst.min(i)); } if (dst.stride(0) == 1) { f.vectorize(x, 16); } else if (dst.stride(0) == 3 && src.stride(0) == 3) { // For a memcpy of packed rgb data, we can fuse x and c and // vectorize over the combination. Var fused("fused"); f.reorder(c, x, y).fuse(c, x, fused).vectorize(fused, 16); } f.compile_to_assembly(std::string("copy_") + f.name() + ".s", Internal::vec<Argument>(src), "copy"); f.realize(dst); double t1 = current_time(); for (int i = 0; i < 10; i++) { f.realize(dst); } double t2 = current_time(); return t2 - t1; } Image<uint8_t> make_packed(uint8_t *host, int W, int H) { buffer_t buf = {0}; buf.host = host; buf.extent[0] = W; buf.stride[0] = 3; buf.extent[1] = H; buf.stride[1] = buf.stride[0] * buf.extent[0]; buf.extent[2] = 3; buf.stride[2] = 1; buf.elem_size = 1; return Image<uint8_t>(&buf); } Image<uint8_t> make_planar(uint8_t *host, int W, int H) { buffer_t buf = {0}; buf.host = host; buf.extent[0] = W; buf.stride[0] = 1; buf.extent[1] = H; buf.stride[1] = buf.stride[0] * buf.extent[0]; buf.extent[2] = 3; buf.stride[2] = buf.stride[1] * buf.extent[1]; buf.elem_size = 1; return Image<uint8_t>(&buf); } int main(int argc, char **argv) { const int W = 1<<11, H = 1<<11; // Allocate two 4 megapixel, 3 channel, 8-bit images -- input and output uint8_t *storage_1(new uint8_t[W * H * 3 + 32]); uint8_t *storage_2(new uint8_t[W * H * 3 + 32]); uint8_t *ptr_1 = storage_1, *ptr_2 = storage_2; while ((size_t)ptr_1 & 0x1f) ptr_1 ++; while ((size_t)ptr_2 & 0x1f) ptr_2 ++; double t_packed_packed = test_copy(make_packed(ptr_1, W, H), make_packed(ptr_2, W, H)); double t_packed_planar = test_copy(make_packed(ptr_1, W, H), make_planar(ptr_2, W, H)); double t_planar_packed = test_copy(make_planar(ptr_1, W, H), make_packed(ptr_2, W, H)); double t_planar_planar = test_copy(make_planar(ptr_1, W, H), make_planar(ptr_2, W, H)); delete[] storage_1; delete[] storage_2; if (t_planar_planar > t_packed_packed * 1.4 || t_packed_packed > t_packed_planar * 1.4 || t_packed_planar > t_planar_packed * 1.4) { printf("Times were not in expected order:\n" "planar -> planar: %f \n" "packed -> packed: %f \n" "packed -> planar: %f \n" "planar -> packed: %f \n", t_planar_planar, t_packed_packed, t_packed_planar, t_planar_packed); return -1; } printf("Success!\n"); return 0; }
#include "Halide.h" #include <stdio.h> #include "clock.h" #include <memory> using namespace Halide; double test_copy(Image<uint8_t> src, Image<uint8_t> dst) { Var x, y, c; Func f; f(x, y, c) = src(x, y, c); for (int i = 0; i < 3; i++) { f.output_buffer() .set_stride(i, dst.stride(i)) .set_extent(i, dst.extent(i)) .set_min(i, dst.min(i)); } if (dst.stride(0) == 1 && src.stride(0) == 1) { // packed -> packed f.vectorize(x, 16); } else if (dst.stride(0) == 3 && src.stride(0) == 3) { // packed -> packed Var fused("fused"); f.reorder(c, x, y).fuse(c, x, fused).vectorize(fused, 16); } else if (dst.stride(0) == 3) { // planar -> packed f.reorder(c, x, y).unroll(c).vectorize(x, 16); } else { // packed -> planar f.reorder(c, x, y).unroll(c).vectorize(x, 16); } f.realize(dst); double t = 1e20; for (int j = 0; j < 5; j++) { double t1 = current_time(); for (int i = 0; i < 10; i++) { f.realize(dst); } double t2 = current_time(); t = std::min(t, t2 - t1); } return t; } Image<uint8_t> make_packed(uint8_t *host, int W, int H) { buffer_t buf = {0}; buf.host = host; buf.extent[0] = W; buf.stride[0] = 3; buf.extent[1] = H; buf.stride[1] = buf.stride[0] * buf.extent[0]; buf.extent[2] = 3; buf.stride[2] = 1; buf.elem_size = 1; return Image<uint8_t>(&buf); } Image<uint8_t> make_planar(uint8_t *host, int W, int H) { buffer_t buf = {0}; buf.host = host; buf.extent[0] = W; buf.stride[0] = 1; buf.extent[1] = H; buf.stride[1] = buf.stride[0] * buf.extent[0]; buf.extent[2] = 3; buf.stride[2] = buf.stride[1] * buf.extent[1]; buf.elem_size = 1; return Image<uint8_t>(&buf); } int main(int argc, char **argv) { const int W = 1<<11, H = 1<<11; // Allocate two 4 megapixel, 3 channel, 8-bit images -- input and output uint8_t *storage_1(new uint8_t[W * H * 3 + 32]); uint8_t *storage_2(new uint8_t[W * H * 3 + 32]); uint8_t *ptr_1 = storage_1, *ptr_2 = storage_2; while ((size_t)ptr_1 & 0x1f) ptr_1 ++; while ((size_t)ptr_2 & 0x1f) ptr_2 ++; double t_packed_packed = test_copy(make_packed(ptr_1, W, H), make_packed(ptr_2, W, H)); double t_packed_planar = test_copy(make_packed(ptr_1, W, H), make_planar(ptr_2, W, H)); double t_planar_packed = test_copy(make_planar(ptr_1, W, H), make_packed(ptr_2, W, H)); double t_planar_planar = test_copy(make_planar(ptr_1, W, H), make_planar(ptr_2, W, H)); delete[] storage_1; delete[] storage_2; if (t_planar_planar > t_packed_packed * 2 || t_packed_packed > t_packed_planar * 2 || t_planar_packed > t_packed_planar * 2) { printf("Times were not in expected order:\n" "planar -> planar: %f \n" "packed -> packed: %f \n" "planar -> packed: %f \n" "packed -> planar: %f \n", t_planar_planar, t_packed_packed, t_planar_packed, t_packed_planar); return -1; } printf("Success!\n"); return 0; }
Make packed_planar_fusion performance test less flaky
Make packed_planar_fusion performance test less flaky
C++
mit
adasworks/Halide,kgnk/Halide,fengzhyuan/Halide,mcanthony/Halide,kgnk/Halide,jiawen/Halide,damienfir/Halide,dougkwan/Halide,tdenniston/Halide,mcanthony/Halide,fengzhyuan/Halide,smxlong/Halide,dougkwan/Halide,ayanazmat/Halide,ronen/Halide,fengzhyuan/Halide,dan-tull/Halide,mcanthony/Halide,tdenniston/Halide,damienfir/Halide,myrtleTree33/Halide,ayanazmat/Halide,delcypher/Halide,smxlong/Halide,damienfir/Halide,kgnk/Halide,adasworks/Halide,psuriana/Halide,dougkwan/Halide,kenkuang1213/Halide,aam/Halide,damienfir/Halide,tdenniston/Halide,kenkuang1213/Halide,adasworks/Halide,dougkwan/Halide,jiawen/Halide,adasworks/Halide,ayanazmat/Halide,adasworks/Halide,lglucin/Halide,jiawen/Halide,ayanazmat/Halide,rodrigob/Halide,smxlong/Halide,jiawen/Halide,psuriana/Halide,tdenniston/Halide,delcypher/Halide,jiawen/Halide,mcanthony/Halide,rodrigob/Halide,aam/Halide,myrtleTree33/Halide,psuriana/Halide,tdenniston/Halide,mcanthony/Halide,dougkwan/Halide,delcypher/Halide,aam/Halide,adasworks/Halide,kenkuang1213/Halide,dan-tull/Halide,ronen/Halide,psuriana/Halide,kenkuang1213/Halide,delcypher/Halide,dougkwan/Halide,ayanazmat/Halide,tdenniston/Halide,dougkwan/Halide,ronen/Halide,dan-tull/Halide,lglucin/Halide,kenkuang1213/Halide,ronen/Halide,psuriana/Halide,aam/Halide,ronen/Halide,kgnk/Halide,rodrigob/Halide,tdenniston/Halide,ayanazmat/Halide,fengzhyuan/Halide,smxlong/Halide,damienfir/Halide,rodrigob/Halide,myrtleTree33/Halide,delcypher/Halide,psuriana/Halide,smxlong/Halide,kenkuang1213/Halide,delcypher/Halide,myrtleTree33/Halide,ayanazmat/Halide,lglucin/Halide,aam/Halide,fengzhyuan/Halide,dan-tull/Halide,kenkuang1213/Halide,damienfir/Halide,dan-tull/Halide,myrtleTree33/Halide,ronen/Halide,rodrigob/Halide,lglucin/Halide,lglucin/Halide,smxlong/Halide,kenkuang1213/Halide,tdenniston/Halide,smxlong/Halide,ayanazmat/Halide,mcanthony/Halide,lglucin/Halide,dan-tull/Halide,myrtleTree33/Halide,jiawen/Halide,myrtleTree33/Halide,dan-tull/Halide,lglucin/Halide,mcanthony/Halide,damienfir/Halide,adasworks/Halide,smxlong/Halide,rodrigob/Halide,dougkwan/Halide,myrtleTree33/Halide,fengzhyuan/Halide,rodrigob/Halide,kgnk/Halide,kgnk/Halide,aam/Halide,delcypher/Halide,mcanthony/Halide,rodrigob/Halide,dan-tull/Halide,adasworks/Halide,psuriana/Halide,delcypher/Halide,kgnk/Halide,fengzhyuan/Halide,damienfir/Halide,fengzhyuan/Halide,kgnk/Halide,jiawen/Halide,ronen/Halide,ronen/Halide,aam/Halide
22ba216f42f6a4d6216d9dbf5f0e72b84769a775
src/s_rules.cc
src/s_rules.cc
#include <memory> #include <algorithm> #include <iterator> #include <unordered_set> #include <unordered_map> #include <utility> #include "s_rules.hh" #include "s_closure.hh" #include "cons_util.hh" #include "env.hh" #include "zs_error.hh" #include "builtin_equal.hh" #include "builtin_extra.hh" #include "builtin_util.hh" #include "printer.hh" #include "hasher.hh" #include "eval.hh" #ifndef NDEBUG #include <iostream> #endif using namespace std; typedef std::unordered_map<Lisp_ptr, Lisp_ptr, std::hash<Lisp_ptr>, eq_id_obj<Lisp_ptr> > MatchObj; typedef std::unordered_set<Lisp_ptr, std::hash<Lisp_ptr>, eq_id_obj<Lisp_ptr> > MatchSet; namespace Procedure{ namespace { Lisp_ptr pick_first(Lisp_ptr p){ if(p.tag() == Ptr_tag::cons){ auto c = p.get<Cons*>(); if(!c) throw zs_error("syntax-rules: the pattern is empty list\n"); return c->car(); }else if(p.tag() == Ptr_tag::vector){ auto v = p.get<Vector*>(); assert(v); if(v->empty()) throw zs_error("syntax-rules: the pattern is empty vector\n"); return (*v)[0]; }else{ throw zs_error("syntax-rules: informal pattern passed! (%s)\n", stringify(p.tag())); } } void check_pattern(const SyntaxRules& sr, Lisp_ptr p, MatchSet tab){ if(identifierp(p)){ for(auto l : sr.literals()){ if(eq_internal(l, p)){ // literal identifier return; } } // pattern variable if(tab.find(p) != tab.end()){ throw zs_error("syntax-rules error: duplicated pattern variable! (%s)\n", identifier_symbol(p)->name().c_str()); } tab.insert(p); return; }else if(p.tag() == Ptr_tag::cons){ if(nullp(p)) return; auto i = begin(p); for(; i; ++i){ check_pattern(sr, *i, tab); } check_pattern(sr, i.base(), tab); }else if(p.tag() == Ptr_tag::vector){ auto v = p.get<Vector*>(); for(auto i : *v){ check_pattern(sr, i, tab); } }else{ return; } } void check_pattern(const SyntaxRules& sr, Lisp_ptr p){ pick_first(p); check_pattern(sr, p, {}); } } // namespace constexpr ProcInfo SyntaxRules::sr_procinfo; SyntaxRules::SyntaxRules(Env* e, Lisp_ptr lits, Lisp_ptr rls) : env_(e), literals_(lits), rules_(rls){ for(auto i : lits){ if(!identifierp(i)) throw builtin_identifier_check_failed("syntax-rules", i); } for(auto i : rls){ bind_cons_list_strict (i, [&](Lisp_ptr pat, Lisp_ptr tmpl){ (void)tmpl; check_pattern(*this, pat); }); } } SyntaxRules::~SyntaxRules() = default; static void ensure_binding(MatchObj& match_obj, const SyntaxRules& sr, Lisp_ptr ignore_ident, Lisp_ptr pattern){ if(identifierp(pattern)){ for(auto l : sr.literals()){ if(eq_internal(l, pattern)){ return; // literal identifier } } // non-literal identifier if(!identifier_eq(sr.env(), ignore_ident, sr.env(), pattern)){ match_obj.insert({pattern, new Vector()}); } return; }else if(pattern.tag() == Ptr_tag::cons){ if(nullp(pattern)){ return; } auto p_i = begin(pattern); for(; p_i; ++p_i){ ensure_binding(match_obj, sr, ignore_ident, *p_i); } // checks length if((p_i.base().tag() == Ptr_tag::cons)){ return; }else{ // dotted list case ensure_binding(match_obj, sr, ignore_ident, p_i.base()); return; } }else if(pattern.tag() == Ptr_tag::vector){ auto p_v = pattern.get<Vector*>(); auto p_i = begin(*p_v), p_e = end(*p_v); for(; p_i != p_e; ++p_i){ ensure_binding(match_obj, sr, ignore_ident, *p_i); } }else{ return; } } static bool try_match_1(MatchObj& match_obj, const SyntaxRules& sr, Lisp_ptr ignore_ident, Lisp_ptr pattern, Env* form_env, Lisp_ptr form, bool insert_by_push){ #ifndef NDEBUG cout << __func__ << "\tpattern = " << pattern << "\n\t\tform = " << form << endl; for(auto ii : match_obj){ cout << '\t' << ii.first << " = " << ii.second << '\n'; } #endif if(form.tag() == Ptr_tag::syntactic_closure){ // destruct syntactic closure auto sc = form.get<SyntacticClosure*>(); return try_match_1(match_obj, sr, ignore_ident, pattern, form_env, sc->expr(), insert_by_push); } const auto ellipsis_sym = intern(vm.symtable(), "..."); if(identifierp(pattern)){ for(auto l : sr.literals()){ if(eq_internal(l, pattern)){ // literal identifier if(!identifierp(form)) return false; return identifier_eq(sr.env(), pattern, form_env, form); } } // non-literal identifier if(!identifier_eq(sr.env(), ignore_ident, sr.env(), pattern)){ auto val = (is_self_evaluating(form)) ? form : new SyntacticClosure(form_env, nullptr, form); if(insert_by_push){ auto place = match_obj.find(pattern); assert(place->second.tag() == Ptr_tag::vector); place->second.get<Vector*>()->push_back(val); }else{ match_obj.insert({pattern, val}); } } return true; }else if(pattern.tag() == Ptr_tag::cons){ if(form.tag() != Ptr_tag::cons){ return false; } if(nullp(pattern) && nullp(form)){ return true; } auto p_i = begin(pattern); auto f_i = begin(form); for(; p_i; ++p_i, (f_i ? ++f_i : f_i)){ // checks ellipsis auto p_n = next(p_i); if((p_n) && identifierp(*p_n) && identifier_symbol(*p_n) == ellipsis_sym){ if(eq_internal(*p_i, ignore_ident)){ throw zs_error("syntax-rules error: '...' is appeared following the first identifier.\n"); } auto p_e = p_i; while(p_e) ++p_e; if(!nullp(p_e.base())){ throw zs_error("syntax-rules error: '...' is appeared in a inproper list pattern!\n"); } // accumulating... ensure_binding(match_obj, sr, ignore_ident, *p_i); for(; f_i; ++f_i){ if(!try_match_1(match_obj, sr, ignore_ident, *p_i, form_env, *f_i, true)){ return false; } } if(!nullp(f_i.base())){ throw zs_error("syntax-rules error: '...' is used for a inproper list form!\n"); } return true; } if(!f_i) break; // this check is delayed to here, for checking the ellipsis. if(!try_match_1(match_obj, sr, ignore_ident, *p_i, form_env, *f_i, insert_by_push)){ return false; } } // checks length if((p_i.base().tag() == Ptr_tag::cons) && (f_i.base().tag() == Ptr_tag::cons)){ return (nullp(p_i.base()) && nullp(f_i.base())); }else{ // dotted list case return try_match_1(match_obj, sr, ignore_ident, p_i.base(), form_env, f_i.base(), insert_by_push); } }else if(pattern.tag() == Ptr_tag::vector){ if(form.tag() != Ptr_tag::vector){ return false; } auto p_v = pattern.get<Vector*>(); auto f_v = form.get<Vector*>(); auto p_i = begin(*p_v), p_e = end(*p_v); auto f_i = begin(*f_v), f_e = end(*f_v); for(; p_i != p_e; ++p_i, ++f_i){ // checks ellipsis auto p_n = next(p_i); if((p_n != p_e) && identifierp(*p_n) && identifier_symbol(*p_n) == ellipsis_sym){ if(eq_internal(*p_i, ignore_ident)){ throw zs_error("syntax-rules error: '...' is appeared following the first identifier.\n"); } // accumulating... ensure_binding(match_obj, sr, ignore_ident, *p_i); for(; f_i != f_e; ++f_i){ if(!try_match_1(match_obj, sr, ignore_ident, *p_i, form_env, *f_i, true)){ return false; } } return true; } if(f_i == f_e) break; // this check is delayed to here, for checking the ellipsis. if(!try_match_1(match_obj, sr, ignore_ident, *p_i, form_env, *f_i, insert_by_push)){ return false; } } // checks length if((p_i == p_e) && (f_i == f_e)){ return true; }else{ return false; } }else{ return equal_internal(pattern, form); } } static pair<Lisp_ptr, bool> expand(const MatchObj& match_obj, Lisp_ptr tmpl, int pick_depth, bool pick_limit_ok){ #ifndef NDEBUG cout << __func__ << " arg = " << tmpl << ", depth = " << pick_depth << ", flag = " << pick_limit_ok << '\n'; #endif const auto ellipsis_sym = intern(vm.symtable(), "..."); if(identifierp(tmpl)){ auto m_ret = match_obj.find(tmpl); if(m_ret != match_obj.end()){ if(pick_depth < 0){ return {m_ret->second, pick_limit_ok}; }else{ assert(m_ret->second.tag() == Ptr_tag::vector); auto m_vec = m_ret->second.get<Vector*>(); if(pick_depth < static_cast<signed>(m_vec->size())){ return {(*m_vec)[pick_depth], true}; }else{ return {{}, false}; } } }else{ return {tmpl, pick_limit_ok}; } }else if(tmpl.tag() == Ptr_tag::cons){ if(nullp(tmpl)) return {tmpl, pick_limit_ok}; GrowList gl; auto t_i = begin(tmpl); for(; t_i; ++t_i){ auto t_n = next(t_i); // check ellipsis if((t_n) && identifierp(*t_n) && identifier_symbol(*t_n) == ellipsis_sym){ int depth = 0; while(1){ auto ex = expand(match_obj, *t_i, depth, true); if(!ex.second) break; gl.push(ex.first); ++depth; } ++t_i; }else{ auto ex = expand(match_obj, *t_i, pick_depth, pick_limit_ok); if(!ex.second && (pick_depth >= 0)){ return {{}, false}; } gl.push(ex.first); } } auto ex = expand(match_obj, t_i.base(), pick_depth, pick_limit_ok); if(!ex.second && (pick_depth >= 0)){ return {{}, false}; } return {gl.extract_with_tail(ex.first), pick_limit_ok}; // }else if(tmpl.tag() == Ptr_tag::vector){ // auto t_vec = tmpl.get<Vector*>(); // Vector vec; // for(auto t_i = begin(*t_vec), t_e = end(*t_vec); t_i != t_e; ++t_i){ // auto t_n = next(t_i); // // check ellipsis // if(identifierp(*t_i) // && (t_n != t_e) && identifierp(*t_n) // && identifier_symbol(*t_n) == ellipsis_sym){ // auto m_ret = match_obj.find(*t_i); // if(m_ret == match_obj.end()){ // throw zs_error("syntax-rules error: invalid template: followed by '...', but not bound by pattern\n"); // } // if(m_ret->second.tag() == Ptr_tag::vector){ // auto m_ret_vec = m_ret->second.get<Vector*>(); // vec.insert(vec.end(), begin(*m_ret_vec), end(*m_ret_vec)); // }else{ // throw zs_error("syntax-rules error: invalid template: matched pattern variable is not followed by ...\n"); // } // ++t_i; // }else{ // vec.push_back(expand(match_obj, *t_i, pick_depth)); // } // } // return new Vector(move(vec)); }else{ return {tmpl, pick_limit_ok}; } } Lisp_ptr SyntaxRules::apply(Lisp_ptr form, Env* form_env) const{ MatchObj match_obj; #ifndef NDEBUG cout << "## " << __func__ << ": form = " << form << ", env = " << form_env << ", frame=" << vm.frame() << endl; #endif for(auto i : this->rules()){ auto pat = i.get<Cons*>()->car(); auto tmpl = i.get<Cons*>()->cdr().get<Cons*>()->car(); #ifndef NDEBUG cout << "## trying: pattern = " << pat << endl; #endif auto ignore_ident = pick_first(pat); if(try_match_1(match_obj, *this, ignore_ident, pat, form_env, form, false)){ #ifndef NDEBUG cout << "## matched!:\tpattern = " << pat << '\n'; cout << "## \t\ttemplate = " << tmpl << '\n'; cout << "## \t\tform = " << form << '\n'; for(auto ii : match_obj){ cout << '\t' << ii.first << " = " << ii.second << '\n'; } #endif auto ex = expand(match_obj, tmpl, -1, false); #ifndef NDEBUG cout << "## expand = " << ex.first << '\n'; cout << *vm.frame() << endl; #endif return ex.first; }else{ // cleaning map for(auto e : match_obj){ if(auto sc = e.second.get<SyntacticClosure*>()){ delete sc; } } match_obj.clear(); } } #ifndef NDEBUG cout << "## no match: form = " << form << endl; #endif throw zs_error("syntax-rules error: no matching pattern found!\n"); } } // Procedure
#include <memory> #include <algorithm> #include <iterator> #include <unordered_set> #include <unordered_map> #include <utility> #include "s_rules.hh" #include "s_closure.hh" #include "cons_util.hh" #include "env.hh" #include "zs_error.hh" #include "builtin_equal.hh" #include "builtin_extra.hh" #include "builtin_util.hh" #include "printer.hh" #include "hasher.hh" #include "eval.hh" #ifndef NDEBUG #include <iostream> #endif using namespace std; typedef std::unordered_map<Lisp_ptr, Lisp_ptr, std::hash<Lisp_ptr>, eq_id_obj<Lisp_ptr> > MatchObj; typedef std::unordered_set<Lisp_ptr, std::hash<Lisp_ptr>, eq_id_obj<Lisp_ptr> > MatchSet; namespace Procedure{ namespace { Lisp_ptr pick_first(Lisp_ptr p){ if(p.tag() == Ptr_tag::cons){ auto c = p.get<Cons*>(); if(!c) throw zs_error("syntax-rules: the pattern is empty list\n"); return c->car(); }else if(p.tag() == Ptr_tag::vector){ auto v = p.get<Vector*>(); assert(v); if(v->empty()) throw zs_error("syntax-rules: the pattern is empty vector\n"); return (*v)[0]; }else{ throw zs_error("syntax-rules: informal pattern passed! (%s)\n", stringify(p.tag())); } } void check_pattern(const SyntaxRules& sr, Lisp_ptr p, MatchSet tab){ if(identifierp(p)){ for(auto l : sr.literals()){ if(eq_internal(l, p)){ // literal identifier return; } } // pattern variable if(tab.find(p) != tab.end()){ throw zs_error("syntax-rules error: duplicated pattern variable! (%s)\n", identifier_symbol(p)->name().c_str()); } tab.insert(p); return; }else if(p.tag() == Ptr_tag::cons){ if(nullp(p)) return; auto i = begin(p); for(; i; ++i){ check_pattern(sr, *i, tab); } check_pattern(sr, i.base(), tab); }else if(p.tag() == Ptr_tag::vector){ auto v = p.get<Vector*>(); for(auto i : *v){ check_pattern(sr, i, tab); } }else{ return; } } void check_pattern(const SyntaxRules& sr, Lisp_ptr p){ pick_first(p); check_pattern(sr, p, {}); } } // namespace constexpr ProcInfo SyntaxRules::sr_procinfo; SyntaxRules::SyntaxRules(Env* e, Lisp_ptr lits, Lisp_ptr rls) : env_(e), literals_(lits), rules_(rls){ for(auto i : lits){ if(!identifierp(i)) throw builtin_identifier_check_failed("syntax-rules", i); } for(auto i : rls){ bind_cons_list_strict (i, [&](Lisp_ptr pat, Lisp_ptr tmpl){ (void)tmpl; check_pattern(*this, pat); }); } } SyntaxRules::~SyntaxRules() = default; static void ensure_binding(MatchObj& match_obj, const SyntaxRules& sr, Lisp_ptr ignore_ident, Lisp_ptr pattern){ if(identifierp(pattern)){ for(auto l : sr.literals()){ if(eq_internal(l, pattern)){ return; // literal identifier } } // non-literal identifier if(!identifier_eq(sr.env(), ignore_ident, sr.env(), pattern)){ match_obj.insert({pattern, new Vector()}); } return; }else if(pattern.tag() == Ptr_tag::cons){ if(nullp(pattern)){ return; } auto p_i = begin(pattern); for(; p_i; ++p_i){ ensure_binding(match_obj, sr, ignore_ident, *p_i); } // checks length if((p_i.base().tag() == Ptr_tag::cons)){ return; }else{ // dotted list case ensure_binding(match_obj, sr, ignore_ident, p_i.base()); return; } }else if(pattern.tag() == Ptr_tag::vector){ auto p_v = pattern.get<Vector*>(); auto p_i = begin(*p_v), p_e = end(*p_v); for(; p_i != p_e; ++p_i){ ensure_binding(match_obj, sr, ignore_ident, *p_i); } }else{ return; } } static bool try_match_1(MatchObj& match_obj, const SyntaxRules& sr, Lisp_ptr ignore_ident, Lisp_ptr pattern, Env* form_env, Lisp_ptr form, bool insert_by_push){ #ifndef NDEBUG cout << __func__ << "\tpattern = " << pattern << "\n\t\tform = " << form << endl; // for(auto ii : match_obj){ // cout << '\t' << ii.first << " = " << ii.second << '\n'; // } #endif if(form.tag() == Ptr_tag::syntactic_closure){ // destruct syntactic closure auto sc = form.get<SyntacticClosure*>(); return try_match_1(match_obj, sr, ignore_ident, pattern, form_env, sc->expr(), insert_by_push); } const auto ellipsis_sym = intern(vm.symtable(), "..."); if(identifierp(pattern)){ for(auto l : sr.literals()){ if(eq_internal(l, pattern)){ // literal identifier if(!identifierp(form)) return false; return identifier_eq(sr.env(), pattern, form_env, form); } } // non-literal identifier if(!identifier_eq(sr.env(), ignore_ident, sr.env(), pattern)){ auto val = (is_self_evaluating(form)) ? form : new SyntacticClosure(form_env, nullptr, form); if(insert_by_push){ auto place = match_obj.find(pattern); assert(place->second.tag() == Ptr_tag::vector); place->second.get<Vector*>()->push_back(val); }else{ match_obj.insert({pattern, val}); } } return true; }else if(pattern.tag() == Ptr_tag::cons){ if(form.tag() != Ptr_tag::cons){ return false; } if(nullp(pattern) && nullp(form)){ return true; } auto p_i = begin(pattern); auto f_i = begin(form); for(; p_i; ++p_i, (f_i ? ++f_i : f_i)){ // checks ellipsis auto p_n = next(p_i); if((p_n) && identifierp(*p_n) && identifier_symbol(*p_n) == ellipsis_sym){ if(eq_internal(*p_i, ignore_ident)){ throw zs_error("syntax-rules error: '...' is appeared following the first identifier.\n"); } auto p_e = p_i; while(p_e) ++p_e; if(!nullp(p_e.base())){ throw zs_error("syntax-rules error: '...' is appeared in a inproper list pattern!\n"); } // accumulating... ensure_binding(match_obj, sr, ignore_ident, *p_i); for(; f_i; ++f_i){ if(!try_match_1(match_obj, sr, ignore_ident, *p_i, form_env, *f_i, true)){ return false; } } if(!nullp(f_i.base())){ throw zs_error("syntax-rules error: '...' is used for a inproper list form!\n"); } return true; } if(!f_i) break; // this check is delayed to here, for checking the ellipsis. if(!try_match_1(match_obj, sr, ignore_ident, *p_i, form_env, *f_i, insert_by_push)){ return false; } } // checks length if((p_i.base().tag() == Ptr_tag::cons) && (f_i.base().tag() == Ptr_tag::cons)){ return (nullp(p_i.base()) && nullp(f_i.base())); }else{ // dotted list case return try_match_1(match_obj, sr, ignore_ident, p_i.base(), form_env, f_i.base(), insert_by_push); } }else if(pattern.tag() == Ptr_tag::vector){ if(form.tag() != Ptr_tag::vector){ return false; } auto p_v = pattern.get<Vector*>(); auto f_v = form.get<Vector*>(); auto p_i = begin(*p_v), p_e = end(*p_v); auto f_i = begin(*f_v), f_e = end(*f_v); for(; p_i != p_e; ++p_i, ++f_i){ // checks ellipsis auto p_n = next(p_i); if((p_n != p_e) && identifierp(*p_n) && identifier_symbol(*p_n) == ellipsis_sym){ if(eq_internal(*p_i, ignore_ident)){ throw zs_error("syntax-rules error: '...' is appeared following the first identifier.\n"); } // accumulating... ensure_binding(match_obj, sr, ignore_ident, *p_i); for(; f_i != f_e; ++f_i){ if(!try_match_1(match_obj, sr, ignore_ident, *p_i, form_env, *f_i, true)){ return false; } } return true; } if(f_i == f_e) break; // this check is delayed to here, for checking the ellipsis. if(!try_match_1(match_obj, sr, ignore_ident, *p_i, form_env, *f_i, insert_by_push)){ return false; } } // checks length if((p_i == p_e) && (f_i == f_e)){ return true; }else{ return false; } }else{ return equal_internal(pattern, form); } } static pair<Lisp_ptr, bool> expand(const MatchObj& match_obj, Lisp_ptr tmpl, int pick_depth, bool pick_limit_ok){ #ifndef NDEBUG cout << __func__ << " arg = " << tmpl << ", depth = " << pick_depth << ", flag = " << pick_limit_ok << '\n'; #endif const auto ellipsis_sym = intern(vm.symtable(), "..."); if(identifierp(tmpl)){ auto m_ret = match_obj.find(tmpl); if(m_ret != match_obj.end()){ if(pick_depth < 0){ return {m_ret->second, pick_limit_ok}; }else{ assert(m_ret->second.tag() == Ptr_tag::vector); auto m_vec = m_ret->second.get<Vector*>(); if(pick_depth < static_cast<signed>(m_vec->size())){ return {(*m_vec)[pick_depth], true}; }else{ return {{}, false}; } } }else{ return {tmpl, pick_limit_ok}; } }else if(tmpl.tag() == Ptr_tag::cons){ if(nullp(tmpl)) return {tmpl, pick_limit_ok}; GrowList gl; auto t_i = begin(tmpl); for(; t_i; ++t_i){ auto t_n = next(t_i); // check ellipsis if((t_n) && identifierp(*t_n) && identifier_symbol(*t_n) == ellipsis_sym){ int depth = 0; while(1){ auto ex = expand(match_obj, *t_i, depth, true); if(!ex.second) break; gl.push(ex.first); ++depth; } ++t_i; }else{ auto ex = expand(match_obj, *t_i, pick_depth, pick_limit_ok); if(!ex.second && (pick_depth >= 0)){ return {{}, false}; } gl.push(ex.first); } } auto ex = expand(match_obj, t_i.base(), pick_depth, pick_limit_ok); if(!ex.second && (pick_depth >= 0)){ return {{}, false}; } return {gl.extract_with_tail(ex.first), pick_limit_ok}; // }else if(tmpl.tag() == Ptr_tag::vector){ // auto t_vec = tmpl.get<Vector*>(); // Vector vec; // for(auto t_i = begin(*t_vec), t_e = end(*t_vec); t_i != t_e; ++t_i){ // auto t_n = next(t_i); // // check ellipsis // if(identifierp(*t_i) // && (t_n != t_e) && identifierp(*t_n) // && identifier_symbol(*t_n) == ellipsis_sym){ // auto m_ret = match_obj.find(*t_i); // if(m_ret == match_obj.end()){ // throw zs_error("syntax-rules error: invalid template: followed by '...', but not bound by pattern\n"); // } // if(m_ret->second.tag() == Ptr_tag::vector){ // auto m_ret_vec = m_ret->second.get<Vector*>(); // vec.insert(vec.end(), begin(*m_ret_vec), end(*m_ret_vec)); // }else{ // throw zs_error("syntax-rules error: invalid template: matched pattern variable is not followed by ...\n"); // } // ++t_i; // }else{ // vec.push_back(expand(match_obj, *t_i, pick_depth)); // } // } // return new Vector(move(vec)); }else{ return {tmpl, pick_limit_ok}; } } Lisp_ptr SyntaxRules::apply(Lisp_ptr form, Env* form_env) const{ MatchObj match_obj; #ifndef NDEBUG cout << "## " << __func__ << ": form = " << form << ", env = " << form_env << ", frame=" << vm.frame() << endl; #endif for(auto i : this->rules()){ auto pat = i.get<Cons*>()->car(); auto tmpl = i.get<Cons*>()->cdr().get<Cons*>()->car(); #ifndef NDEBUG cout << "## trying: pattern = " << pat << endl; #endif auto ignore_ident = pick_first(pat); if(try_match_1(match_obj, *this, ignore_ident, pat, form_env, form, false)){ #ifndef NDEBUG cout << "## matched!:\tpattern = " << pat << '\n'; cout << "## \t\ttemplate = " << tmpl << '\n'; cout << "## \t\tform = " << form << '\n'; for(auto ii : match_obj){ cout << '\t' << ii.first << " = " << ii.second << '\n'; } #endif auto ex = expand(match_obj, tmpl, -1, false); #ifndef NDEBUG cout << "## expand = " << ex.first << '\n'; cout << *vm.frame() << endl; #endif return ex.first; }else{ // cleaning map for(auto e : match_obj){ if(auto sc = e.second.get<SyntacticClosure*>()){ delete sc; } } match_obj.clear(); } } #ifndef NDEBUG cout << "## no match: form = " << form << endl; #endif throw zs_error("syntax-rules error: no matching pattern found!\n"); } } // Procedure
debug print change
debug print change
C++
bsd-2-clause
y2q-actionman/zatuscheme
490f4abcc8679969aab03c5dfc18888e1f253a27
machine-learning/StateSpace.cpp
machine-learning/StateSpace.cpp
#include "StateSpace.h" int StateSpace::angle_bins; int StateSpace::velocity_bins; int StateSpace::torque_bins; double StateSpace::angle_max; double StateSpace::velocity_max; double StateSpace::torque_max; StateSpace::StateSpace(const PriorityQueue<float, double>& queue, int _angle_bins, int _velocity_bins, int _torque_bins, double _angle_max, double _velocity_max, double _torque_max) : space(_angle_bins, std::vector<std::vector<PriorityQueue<float, double>>>(_velocity_bins, std::vector<PriorityQueue<float, double>>(_torque_bins, PriorityQueue<float, double>(queue)))) { angle_bins=_angle_bins-1; //offset is to account for array indexes starting at 0 velocity_bins=_velocity_bins-1; torque_bins=_torque_bins-1; angle_max=_angle_max; velocity_max=_velocity_max; torque_max=_torque_max; } StateSpace::SubscriptProxy1 StateSpace::operator[](const double angle) { //error if angle exceeds bounds if ( std::abs(angle) > angle_max ) { std::string error("angle argument exceeded with value: "); error+=to_string(angle); throw std::domain_error(error); } //get the coefficient double coef=0.5*angle_bins; //descretise index int discrete_index = static_cast<int>( std::round( coef*(1+angle/angle_max) ) ); //return appropriate object return SubscriptProxy1(space[discrete_index]); } //searches state space by state object PriorityQueue<float, double>& StateSpace::operator[](const State & state) { //call the subscripts with the members of the state object return (*this)[state.theta][state.theta_dot][state.torque]; }
#include "StateSpace.h" int StateSpace::angle_bins; int StateSpace::velocity_bins; int StateSpace::torque_bins; double StateSpace::angle_max; double StateSpace::velocity_max; double StateSpace::torque_max; StateSpace::StateSpace(const PriorityQueue<float, double>& queue, int _angle_bins, int _velocity_bins, int _torque_bins, double _angle_max, double _velocity_max, double _torque_max) : space(_angle_bins, std::vector<std::vector<PriorityQueue<float, double>>>(_velocity_bins, std::vector<PriorityQueue<float, double>>(_torque_bins, PriorityQueue<float, double>(queue)))) { angle_bins=_angle_bins-1; //offset is to account for array indexes starting at 0 velocity_bins=_velocity_bins-1; torque_bins=_torque_bins-1; angle_max=_angle_max; velocity_max=_velocity_max; torque_max=_torque_max; } StateSpace::SubscriptProxy1 StateSpace::operator[](const double angle) { //error if angle exceeds bounds if ( std::abs(angle) > angle_max ) { std::string error("angle argument exceeded with value: "); error+=std::to_string(angle); throw std::domain_error(error); } //get the coefficient double coef=0.5*angle_bins; //descretise index int discrete_index = static_cast<int>( std::round( coef*(1+angle/angle_max) ) ); //return appropriate object return SubscriptProxy1(space[discrete_index]); } //searches state space by state object PriorityQueue<float, double>& StateSpace::operator[](const State & state) { //call the subscripts with the members of the state object return (*this)[state.theta][state.theta_dot][state.torque]; }
Update StateSpace.cpp
Update StateSpace.cpp
C++
mit
philj56/robot-swing,philj56/robot-swing,philj56/robot-swing
ae64732375e6f2c023c141782bd4773e09e14cc0
src/server.cpp
src/server.cpp
/** * Copyright (c) Sjors Gielen, 2010 * See LICENSE for license. */ #include <cassert> #include <iostream> #include <sstream> #include <stdio.h> #include "server.h" #include "config.h" // #define DEBUG std::string Server::toString(const Server *s) { std::stringstream res; res << "Server["; if(s == 0 ) { res << "0"; } else { const ServerConfig *sc = s->config(); res << sc->host << ":" << sc->port; } res << "]"; return res.str(); } Server::Server( const ServerConfig *c, Network *n ) : config_(c) , network_(n) , irc_(0) , whois_identified_(false) { } Server::~Server() { irc_destroy_session(irc_); } const ServerConfig *Server::config() const { return config_; } void Server::disconnectFromServer( Network::DisconnectReason reason ) { std::string reasonString; switch( reason ) { case Network::ShutdownReason: reasonString = "Shutting down"; break; case Network::ConfigurationReloadReason: reasonString = "Reloading configuration"; break; case Network::SwitchingServersReason: reasonString = "Switching servers"; break; case Network::ErrorReason: reasonString = "Unknown error"; break; case Network::AdminRequestReason: reasonString = "An admin asked me to disconnect"; break; case Network::UnknownReason: default: reasonString = "See you around!"; } quit( reasonString ); } std::string Server::motd() const { fprintf(stderr, "MOTD cannot be retrieved.\n"); return std::string(); } void Server::quit( const std::string &reason ) { irc_cmd_quit(irc_, reason.c_str()); } void Server::whois( const std::string &destination ) { irc_cmd_whois(irc_, destination.c_str()); } void Server::ctcpAction( const std::string &destination, const std::string &message ) { irc_cmd_me(irc_, destination.c_str(), message.c_str()); } void Server::names( const std::string &channel ) { irc_cmd_names(irc_, channel.c_str()); } void Server::ctcpRequest( const std::string &destination, const std::string &message ) { irc_cmd_ctcp_request(irc_, destination.c_str(), message.c_str()); } void Server::join( const std::string &channel, const std::string &key ) { irc_cmd_join(irc_, channel.c_str(), key.c_str()); } void Server::part( const std::string &channel, const std::string &) { // TODO: also use "reason" here (patch libircclient for this) irc_cmd_part(irc_, channel.c_str()); } void Server::message( const std::string &destination, const std::string &message ) { std::stringstream ss(message); std::string line; while(std::getline(ss, line)) { irc_cmd_msg(irc_, destination.c_str(), line.c_str()); } } void Server::addDescriptors(fd_set *in_set, fd_set *out_set, int *maxfd) { irc_add_select_descriptors(irc_, in_set, out_set, maxfd); } void Server::processDescriptors(fd_set *in_set, fd_set *out_set) { irc_process_select_descriptors(irc_, in_set, out_set); } void Server::slotNumericMessageReceived( const std::string &origin, unsigned int code, const std::vector<std::string> &args ) { assert( network_ != 0 ); assert( network_->activeServer() == this ); // Also send out some other interesting events if(code == 311) { in_whois_for_ = args[1]; assert( !whois_identified_ ); } // TODO: should use CAP IDENTIFY_MSG for this: else if(code == 307 || code == 330) // 330 means "logged in as", but doesn't check whether nick is grouped { whois_identified_ = true; } else if(code == 318) { network_->slotWhoisReceived( origin, in_whois_for_, whois_identified_ ); std::vector<std::string> parameters; parameters.push_back(in_whois_for_); parameters.push_back(whois_identified_ ? "true" : "false"); network_->slotIrcEvent( "WHOIS", origin, parameters ); whois_identified_ = false; in_whois_for_.clear(); } // part of NAMES else if(code == 353) { std::vector<std::string> names; std::stringstream ss(args.back()); std::string name; while(std::getline(ss, name, ' ')) { in_names_.push_back(name); } } else if(code == 366) { network_->slotNamesReceived( origin, args.at(1), in_names_, args.at(0) ); std::vector<std::string> parameters; parameters.push_back(args.at(1)); std::vector<std::string>::const_iterator it; for(it = in_names_.begin(); it != in_names_.end(); ++it) { parameters.push_back(*it); } network_->slotIrcEvent( "NAMES", origin, parameters ); in_names_.clear(); } std::stringstream codestream; codestream << code; std::vector<std::string> params; params.push_back(codestream.str()); std::vector<std::string>::const_iterator it; for(it = args.begin(); it != args.end(); ++it) { params.push_back(*it); } network_->slotIrcEvent( "NUMERIC", origin, params ); } void Server::slotDisconnected() { network_->onFailedConnection(); } void Server::slotIrcEvent(const std::string &event, const std::string &origin, const std::vector<std::string> &args) { assert(network_ != 0); assert(network_->activeServer() == this); network_->slotIrcEvent(event, origin, args); } void irc_eventcode_callback(irc_session_t *s, unsigned int event, const char *origin, const char **p, unsigned int count) { Server *server = (Server*) irc_get_ctx(s); assert(server->getIrc() == s); std::vector<std::string> params; for(unsigned int i = 0; i < count; ++i) { params.push_back(std::string(p[i])); } server->slotNumericMessageReceived(std::string(origin), event, params); } void irc_callback(irc_session_t *s, const char *e, const char *o, const char **params, unsigned int count) { Server *server = (Server*) irc_get_ctx(s); assert(server->getIrc() == s); std::string event(e); // From libircclient docs, but CHANNEL_NOTICE is bullshit... if(event == "CHANNEL_NOTICE") { event = "NOTICE"; } // for now, keep these std::strings: std::string origin = std::string(o); size_t exclamMark = origin.find('!'); if(exclamMark != std::string::npos) { origin = origin.substr(0, exclamMark); } std::vector<std::string> arguments; for(unsigned int i = 0; i < count; ++i) { arguments.push_back(std::string(params[i])); } #ifdef DEBUG fprintf(stderr, "%s - %s from %s\n", server->toString().c_str, event.c_str(), origin.c_str()); #endif // TODO: handle disconnects nicely (probably using some ping and LIBIRC_ERR_CLOSED if(event == "ERROR") { fprintf(stderr, "Error received from libircclient; origin=%s.\n", origin.c_str()); server->slotDisconnected(); } else if(event == "CONNECT") { printf("Connected to server: %s\n", Server::toString(server).c_str()); } server->slotIrcEvent(event, origin, arguments); } void Server::connectToServer() { printf("Connecting to server: %s\n", toString(this).c_str()); assert( !config_->network->nickName.length() == 0 ); irc_callbacks_t callbacks; callbacks.event_connect = irc_callback; callbacks.event_nick = irc_callback; callbacks.event_quit = irc_callback; callbacks.event_join = irc_callback; callbacks.event_part = irc_callback; callbacks.event_mode = irc_callback; callbacks.event_umode = irc_callback; callbacks.event_topic = irc_callback; callbacks.event_kick = irc_callback; callbacks.event_channel = irc_callback; callbacks.event_privmsg = irc_callback; callbacks.event_notice = irc_callback; callbacks.event_invite = irc_callback; callbacks.event_ctcp_req = irc_callback; callbacks.event_ctcp_rep = irc_callback; callbacks.event_ctcp_action = irc_callback; callbacks.event_unknown = irc_callback; callbacks.event_numeric = irc_eventcode_callback; callbacks.event_dcc_chat_req = NULL; callbacks.event_dcc_send_req = NULL; irc_ = irc_create_session(&callbacks); if(!irc_) { std::cerr << "Couldn't create IRC session in Server."; abort(); } irc_set_ctx(irc_, this); assert( config_->network->nickName.length() != 0 ); irc_connect(irc_, config_->host.c_str(), config_->port, config_->network->password.c_str(), config_->network->nickName.c_str(), config_->network->userName.c_str(), config_->network->fullName.c_str()); } irc_session_t *Server::getIrc() const { return irc_; }
/** * Copyright (c) Sjors Gielen, 2010 * See LICENSE for license. */ #include <cassert> #include <iostream> #include <sstream> // libircclient.h needs cstdlib, don't remove the inclusion #include <cstdio> #include <cstdlib> #include <libircclient.h> #include "server.h" #include "config.h" // #define DEBUG std::string Server::toString(const Server *s) { std::stringstream res; res << "Server["; if(s == 0 ) { res << "0"; } else { const ServerConfig *sc = s->config(); res << sc->host << ":" << sc->port; } res << "]"; return res.str(); } Server::Server( const ServerConfig *c, Network *n ) : config_(c) , network_(n) , irc_(0) , whois_identified_(false) { } Server::~Server() { irc_destroy_session(irc_); } const ServerConfig *Server::config() const { return config_; } void Server::disconnectFromServer( Network::DisconnectReason reason ) { std::string reasonString; switch( reason ) { case Network::ShutdownReason: reasonString = "Shutting down"; break; case Network::ConfigurationReloadReason: reasonString = "Reloading configuration"; break; case Network::SwitchingServersReason: reasonString = "Switching servers"; break; case Network::ErrorReason: reasonString = "Unknown error"; break; case Network::AdminRequestReason: reasonString = "An admin asked me to disconnect"; break; case Network::UnknownReason: default: reasonString = "See you around!"; } quit( reasonString ); } std::string Server::motd() const { fprintf(stderr, "MOTD cannot be retrieved.\n"); return std::string(); } void Server::quit( const std::string &reason ) { irc_cmd_quit(irc_, reason.c_str()); } void Server::whois( const std::string &destination ) { irc_cmd_whois(irc_, destination.c_str()); } void Server::ctcpAction( const std::string &destination, const std::string &message ) { irc_cmd_me(irc_, destination.c_str(), message.c_str()); } void Server::names( const std::string &channel ) { irc_cmd_names(irc_, channel.c_str()); } void Server::ctcpRequest( const std::string &destination, const std::string &message ) { irc_cmd_ctcp_request(irc_, destination.c_str(), message.c_str()); } void Server::join( const std::string &channel, const std::string &key ) { irc_cmd_join(irc_, channel.c_str(), key.c_str()); } void Server::part( const std::string &channel, const std::string &) { // TODO: also use "reason" here (patch libircclient for this) irc_cmd_part(irc_, channel.c_str()); } void Server::message( const std::string &destination, const std::string &message ) { std::stringstream ss(message); std::string line; while(std::getline(ss, line)) { irc_cmd_msg(irc_, destination.c_str(), line.c_str()); } } void Server::addDescriptors(fd_set *in_set, fd_set *out_set, int *maxfd) { irc_add_select_descriptors(irc_, in_set, out_set, maxfd); } void Server::processDescriptors(fd_set *in_set, fd_set *out_set) { irc_process_select_descriptors(irc_, in_set, out_set); } void Server::slotNumericMessageReceived( const std::string &origin, unsigned int code, const std::vector<std::string> &args ) { assert( network_ != 0 ); assert( network_->activeServer() == this ); // Also send out some other interesting events if(code == 311) { in_whois_for_ = args[1]; assert( !whois_identified_ ); } // TODO: should use CAP IDENTIFY_MSG for this: else if(code == 307 || code == 330) // 330 means "logged in as", but doesn't check whether nick is grouped { whois_identified_ = true; } else if(code == 318) { network_->slotWhoisReceived( origin, in_whois_for_, whois_identified_ ); std::vector<std::string> parameters; parameters.push_back(in_whois_for_); parameters.push_back(whois_identified_ ? "true" : "false"); network_->slotIrcEvent( "WHOIS", origin, parameters ); whois_identified_ = false; in_whois_for_.clear(); } // part of NAMES else if(code == 353) { std::vector<std::string> names; std::stringstream ss(args.back()); std::string name; while(std::getline(ss, name, ' ')) { in_names_.push_back(name); } } else if(code == 366) { network_->slotNamesReceived( origin, args.at(1), in_names_, args.at(0) ); std::vector<std::string> parameters; parameters.push_back(args.at(1)); std::vector<std::string>::const_iterator it; for(it = in_names_.begin(); it != in_names_.end(); ++it) { parameters.push_back(*it); } network_->slotIrcEvent( "NAMES", origin, parameters ); in_names_.clear(); } std::stringstream codestream; codestream << code; std::vector<std::string> params; params.push_back(codestream.str()); std::vector<std::string>::const_iterator it; for(it = args.begin(); it != args.end(); ++it) { params.push_back(*it); } network_->slotIrcEvent( "NUMERIC", origin, params ); } void Server::slotDisconnected() { network_->onFailedConnection(); } void Server::slotIrcEvent(const std::string &event, const std::string &origin, const std::vector<std::string> &args) { assert(network_ != 0); assert(network_->activeServer() == this); network_->slotIrcEvent(event, origin, args); } void irc_eventcode_callback(irc_session_t *s, unsigned int event, const char *origin, const char **p, unsigned int count) { Server *server = (Server*) irc_get_ctx(s); assert(server->getIrc() == s); std::vector<std::string> params; for(unsigned int i = 0; i < count; ++i) { params.push_back(std::string(p[i])); } server->slotNumericMessageReceived(std::string(origin), event, params); } void irc_callback(irc_session_t *s, const char *e, const char *o, const char **params, unsigned int count) { Server *server = (Server*) irc_get_ctx(s); assert(server->getIrc() == s); std::string event(e); // From libircclient docs, but CHANNEL_NOTICE is bullshit... if(event == "CHANNEL_NOTICE") { event = "NOTICE"; } // for now, keep these std::strings: std::string origin = std::string(o); size_t exclamMark = origin.find('!'); if(exclamMark != std::string::npos) { origin = origin.substr(0, exclamMark); } std::vector<std::string> arguments; for(unsigned int i = 0; i < count; ++i) { arguments.push_back(std::string(params[i])); } #ifdef DEBUG fprintf(stderr, "%s - %s from %s\n", server->toString().c_str, event.c_str(), origin.c_str()); #endif // TODO: handle disconnects nicely (probably using some ping and LIBIRC_ERR_CLOSED if(event == "ERROR") { fprintf(stderr, "Error received from libircclient; origin=%s.\n", origin.c_str()); server->slotDisconnected(); } else if(event == "CONNECT") { printf("Connected to server: %s\n", Server::toString(server).c_str()); } server->slotIrcEvent(event, origin, arguments); } void Server::connectToServer() { printf("Connecting to server: %s\n", toString(this).c_str()); assert( !config_->network->nickName.length() == 0 ); irc_callbacks_t callbacks; callbacks.event_connect = irc_callback; callbacks.event_nick = irc_callback; callbacks.event_quit = irc_callback; callbacks.event_join = irc_callback; callbacks.event_part = irc_callback; callbacks.event_mode = irc_callback; callbacks.event_umode = irc_callback; callbacks.event_topic = irc_callback; callbacks.event_kick = irc_callback; callbacks.event_channel = irc_callback; callbacks.event_privmsg = irc_callback; callbacks.event_notice = irc_callback; callbacks.event_invite = irc_callback; callbacks.event_ctcp_req = irc_callback; callbacks.event_ctcp_rep = irc_callback; callbacks.event_ctcp_action = irc_callback; callbacks.event_unknown = irc_callback; callbacks.event_numeric = irc_eventcode_callback; callbacks.event_dcc_chat_req = NULL; callbacks.event_dcc_send_req = NULL; irc_ = irc_create_session(&callbacks); if(!irc_) { std::cerr << "Couldn't create IRC session in Server."; abort(); } irc_set_ctx(irc_, this); assert( config_->network->nickName.length() != 0 ); irc_connect(irc_, config_->host.c_str(), config_->port, config_->network->password.c_str(), config_->network->nickName.c_str(), config_->network->userName.c_str(), config_->network->fullName.c_str()); } irc_session_t *Server::getIrc() const { return irc_; }
Fix inclusion in server.cpp
Fix inclusion in server.cpp
C++
bsd-3-clause
dazeus/dazeus-core,dazeus/dazeus-core,dazeus/dazeus-core,dazeus/dazeus-core
816bbc23bfd4a4bd61eb6ce3d63d426db252f0e5
src/sudoku.cpp
src/sudoku.cpp
#include <opencv2/opencv.hpp> #include <iostream> #include "detector.hpp" #include "data.hpp" int main(int argc, char** argv ){ if(argc < 2){ std::cout << "Usage: sudoku <command> <options>" << std::endl; return -1; } std::string command(argv[1]); if(command == "detect"){ if(argc < 3){ std::cout << "Usage: sudoku detect <image>..." << std::endl; return -1; } if(argc == 3){ std::string image_source_path(argv[2]); auto source_image = cv::imread(image_source_path.c_str(), 1); if (!source_image.data){ std::cout << "Invalid source_image" << std::endl; return -1; } auto data = read_data(image_source_path); cv::Mat dest_image; auto cells = detect_grid(source_image, dest_image); split(source_image, cells); cv::namedWindow("Sudoku Grid", cv::WINDOW_AUTOSIZE); cv::imshow("Sudoku Grid", dest_image); cv::waitKey(0); } else { for(size_t i = 1; i < static_cast<size_t>(argc); ++i){ std::string image_source_path(argv[i]); std::cout << image_source_path << std::endl; auto source_image = cv::imread(image_source_path.c_str(), 1); if (!source_image.data){ std::cout << "Invalid source_image" << std::endl; continue; } cv::Mat dest_image; auto cells = detect_grid(source_image, dest_image); split(source_image, cells); image_source_path.insert(image_source_path.rfind('.'), ".lines"); imwrite(image_source_path.c_str(), dest_image); } } } else { std::cout << "Invalid command \"" << command << "\"" << std::endl; return -1; } return 0; }
#include <opencv2/opencv.hpp> #include <iostream> #include "detector.hpp" #include "data.hpp" int main(int argc, char** argv ){ if(argc < 2){ std::cout << "Usage: sudoku <command> <options>" << std::endl; return -1; } std::string command(argv[1]); if(command == "detect"){ if(argc < 3){ std::cout << "Usage: sudoku detect <image>..." << std::endl; return -1; } if(argc == 3){ std::string image_source_path(argv[2]); auto source_image = cv::imread(image_source_path.c_str(), 1); if (!source_image.data){ std::cout << "Invalid source_image" << std::endl; return -1; } cv::Mat dest_image; auto cells = detect_grid(source_image, dest_image); split(source_image, cells); cv::namedWindow("Sudoku Grid", cv::WINDOW_AUTOSIZE); cv::imshow("Sudoku Grid", dest_image); cv::waitKey(0); } else { for(size_t i = 1; i < static_cast<size_t>(argc); ++i){ std::string image_source_path(argv[i]); std::cout << image_source_path << std::endl; auto source_image = cv::imread(image_source_path.c_str(), 1); if (!source_image.data){ std::cout << "Invalid source_image" << std::endl; continue; } cv::Mat dest_image; auto cells = detect_grid(source_image, dest_image); split(source_image, cells); image_source_path.insert(image_source_path.rfind('.'), ".lines"); imwrite(image_source_path.c_str(), dest_image); } } } else if(command == "train"){ for(size_t i = 1; i < static_cast<size_t>(argc); ++i){ std::string image_source_path(argv[i]); std::cout << image_source_path << std::endl; auto source_image = cv::imread(image_source_path.c_str(), 1); if (!source_image.data){ std::cout << "Invalid source_image" << std::endl; continue; } auto data = read_data(image_source_path); cv::Mat dest_image; auto cells = detect_grid(source_image, dest_image); auto mats = split(source_image, cells); } } else { std::cout << "Invalid command \"" << command << "\"" << std::endl; return -1; } return 0; }
Prepare train
Prepare train
C++
mit
wichtounet/sudoku_recognizer
e314107e4ae9094e95039adfdafb823d7a954c7c
src/system.cpp
src/system.cpp
#include "system.hpp" #include <dirent.h> #include <sys/stat.h> #if defined ARCH_WIN #include <windows.h> #include <shellapi.h> #endif namespace rack { namespace system { std::list<std::string> listEntries(const std::string &path) { std::list<std::string> filenames; DIR *dir = opendir(path.c_str()); if (dir) { struct dirent *d; while ((d = readdir(dir))) { std::string filename = d->d_name; if (filename == "." || filename == "..") continue; filenames.push_back(path + "/" + filename); } closedir(dir); } return filenames; } bool isFile(const std::string &path) { struct stat statbuf; if (stat(path.c_str(), &statbuf)) return false; return S_ISREG(statbuf.st_mode); } bool isDirectory(const std::string &path) { struct stat statbuf; if (stat(path.c_str(), &statbuf)) return false; return S_ISDIR(statbuf.st_mode); } void copyFile(const std::string &srcPath, const std::string &destPath) { // Open files FILE *source = fopen(srcPath.c_str(), "rb"); if (!source) return; DEFER({ fclose(source); }); FILE *dest = fopen(destPath.c_str(), "wb"); if (!dest) return; DEFER({ fclose(dest); }); // Copy buffer const int bufferSize = (1<<15); char buffer[bufferSize]; while (1) { size_t size = fread(buffer, 1, bufferSize, source); if (size == 0) break; size = fwrite(buffer, 1, size, dest); if (size == 0) break; } } void createDirectory(const std::string &path) { #if defined ARCH_WIN CreateDirectory(path.c_str(), NULL); #else mkdir(path.c_str(), 0755); #endif } void openBrowser(const std::string &url) { #if defined ARCH_LIN std::string command = "xdg-open " + url; (void) std::system(command.c_str()); #endif #if defined ARCH_MAC std::string command = "open " + url; std::system(command.c_str()); #endif #if defined ARCH_WIN ShellExecute(NULL, "open", url.c_str(), NULL, NULL, SW_SHOWNORMAL); #endif } } // namespace system } // namespace rack
#include "system.hpp" #include <dirent.h> #include <sys/stat.h> #if defined ARCH_WIN #include <windows.h> #include <shellapi.h> #endif namespace rack { namespace system { std::list<std::string> listEntries(const std::string &path) { std::list<std::string> filenames; DIR *dir = opendir(path.c_str()); if (dir) { struct dirent *d; while ((d = readdir(dir))) { std::string filename = d->d_name; if (filename == "." || filename == "..") continue; filenames.push_back(path + "/" + filename); } closedir(dir); } return filenames; } bool isFile(const std::string &path) { struct stat statbuf; if (stat(path.c_str(), &statbuf)) return false; return S_ISREG(statbuf.st_mode); } bool isDirectory(const std::string &path) { struct stat statbuf; if (stat(path.c_str(), &statbuf)) return false; return S_ISDIR(statbuf.st_mode); } void copyFile(const std::string &srcPath, const std::string &destPath) { // Open files FILE *source = fopen(srcPath.c_str(), "rb"); if (!source) return; DEFER({ fclose(source); }); FILE *dest = fopen(destPath.c_str(), "wb"); if (!dest) return; DEFER({ fclose(dest); }); // Copy buffer const int bufferSize = (1<<15); char buffer[bufferSize]; while (1) { size_t size = fread(buffer, 1, bufferSize, source); if (size == 0) break; size = fwrite(buffer, 1, size, dest); if (size == 0) break; } } void createDirectory(const std::string &path) { #if defined ARCH_WIN CreateDirectory(path.c_str(), NULL); #else mkdir(path.c_str(), 0755); #endif } void setThreadName(const std::string &name) { #if defined ARCH_LIN pthread_setname_np(pthread_self(), name.c_str()); #endif } void openBrowser(const std::string &url) { #if defined ARCH_LIN std::string command = "xdg-open " + url; (void) std::system(command.c_str()); #endif #if defined ARCH_MAC std::string command = "open " + url; std::system(command.c_str()); #endif #if defined ARCH_WIN ShellExecute(NULL, "open", url.c_str(), NULL, NULL, SW_SHOWNORMAL); #endif } } // namespace system } // namespace rack
Add implementation for system::setThreadName for Linux
Add implementation for system::setThreadName for Linux
C++
mit
AndrewBelt/Rack
e19857c50eaa93d1c3bd5c75de14d19a2ca90239
src/tarlib.cpp
src/tarlib.cpp
#include <string> #include <array> #include <cstdint> #include <cstdlib> #include <cassert> #include <type_traits> #include <sstream> #include <iterator> #include <tarlib/tarlib.h> namespace { #if 0 template <unsigned int OFFSET, unsigned int COUNT> unsigned long long _base256_to_10( typename std::enable_if<COUNT == 0, const Byte*>::type ptr) { return ptr[OFFSET]; } template <unsigned int OFFSET, unsigned int COUNT> unsigned long long _base256_to_10( typename std::enable_if<COUNT != 0, const Byte*>::type ptr) { return (ptr[OFFSET] * 256 * COUNT) + _base256_to_10<OFFSET + 1, COUNT - 1>( ptr ); } #endif template <unsigned int OFFSET, unsigned int COUNT> unsigned long long base256_to_10( const char* ptr) { //return _base256_to_10<OFFSET, COUNT - 1>( ptr ); return std::strtoull( ptr, nullptr, 256 ); } unsigned long base8_to_10( const char* ptr ) { return std::strtoul( ptr, nullptr, 8 ); } // Converts octal to usable decimal values void convert( tar_header& header ) { const bool is_base_256 = header.file_bytes_octal[0] & 0x80; std::uint64_t value; const auto& field = header.file_bytes_octal; // Enforce proper file_bytes encoding header.file_bytes_terminator = '\0'; if( is_base_256 ) { value = base256_to_10<1, 10>( field ); } else { //std::ostringstream stream; value = base8_to_10( field ); } header.file_bytes = value; header.modification_time = base8_to_10( header.modification_time_octal ); } // Internal tar state struct internal { internal(); tar_headerp header( tar_headerp ); bool put( tar_stream& strm, bool continueAfterHeader ); private: void reset( tar_stream& strm ); struct { tar_headerp ptr_begin; Byte* ptr; uint16_t left; //bytes left till header is full void reset() { ptr = reinterpret_cast<Byte*>( ptr_begin ); left = TAR_HEADER_SIZE; if( ptr_begin ) { ptr_begin->done = 0; ptr_begin->file_bytes = 0; ptr_begin->modification_time = 0; } } void reset( tar_headerp header ) { ptr_begin = header; reset(); } } _header; tar_header _internal_header; std::uint64_t _left; std::uint16_t _endPadding; }; internal& intern( tar_stream& strm ) { return *static_cast<internal*>( strm.state ); } Byte* begin( tar_header& header ) { return reinterpret_cast<Byte*>( &header ); } Byte* end( tar_header& header ) { return begin(header) + TAR_HEADER_SIZE; } } internal::internal() : _header(), _internal_header(), _left( 0 ) { _header.reset( &_internal_header ); } tar_headerp internal::header( tar_headerp header ) { _header.reset( header ); return _header.ptr_begin; } void internal::reset( tar_stream& strm ) { _header.reset(); strm.ptr_out = nullptr; strm.len_out = 0; _left = 0; } bool internal::put( tar_stream& strm, bool continueAfterHeader ) { if( !_header.left && !_left ) { if( strm.avail_in ) { // Go to the next entry reset( strm ); } return false; //end of entry } if( _header.left ) { // Try to make the header full const auto distance = std::min( static_cast<decltype(strm.avail_in)>(_header.left), strm.avail_in ); assert( distance <= _header.left ); if( _header.ptr ) { std::copy( strm.next_in, strm.next_in + distance, _header.ptr ); _header.ptr += distance; } strm.next_in += distance; strm.avail_in -= distance; strm.total_in += distance; // We made sure distance is at max _header.left #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wconversion" _header.left -= distance; #pragma GCC diagnostic pop if( !_header.left ) { // We reached a full header if( _header.ptr_begin ) { tar_header& header = *_header.ptr_begin; convert( header ); _header.ptr_begin->done = 1; } //FIXME: Make working without internal header _left = _header.ptr_begin->file_bytes; _endPadding = [&]() { // Data is always rounded up to 512 static const std::uint16_t PADDING_SIZE = 512; auto quot = _left / PADDING_SIZE; if( _left % PADDING_SIZE ) { ++quot; } return static_cast<uint16_t>( quot * PADDING_SIZE - _left ); }(); _left += _endPadding; if( !continueAfterHeader ) return true; } } if( !_header.left && strm.avail_in ) { // Process file entry content strm.ptr_out = strm.next_in; uInt moveValue = [&]() { if( _left > _endPadding ) { const std::uint64_t leftContent = _left - _endPadding; // Limit to current file entry only strm.len_out = strm.avail_in < leftContent ? strm.avail_in : static_cast<decltype(strm.avail_in)>( leftContent ); assert( strm.len_out <= leftContent ); strm.total_out += strm.len_out; return strm.len_out; } else { const uInt leftPadding = static_cast<decltype(_endPadding)>( _left ); // Consume the padding but do not generate output strm.len_out = 0; strm.total_out += leftPadding; return leftPadding; } }(); strm.avail_in -= moveValue; strm.next_in += moveValue; strm.total_in += moveValue; _left -= moveValue; } return true; } // C wrapper int TAREXPORT tar_inflateInit( tar_streamp strm ) { assert( strm ); strm->total_in = 0; strm->ptr_out = nullptr; strm->len_out = 0; strm->total_out = 0; strm->state = new internal(); return TAR_OK; } int TAREXPORT tar_inflate( tar_streamp strm, int flush ) { assert( strm ); if( intern(*strm).put( *strm, flush == TAR_SYNC_FLUSH ) ) return TAR_OK; else return TAR_ENTRY_END; } int TAREXPORT tar_inflateEnd( tar_streamp strm ) { assert( strm ); delete &intern( *strm ); // Signal to externals that the stream // has ended strm->internal = nullptr; return TAR_OK; } int TAREXPORT tar_inflateGetHeader( tar_streamp strm, tar_headerp head ) { assert(strm); assert(head); auto& internal = intern( *strm ); internal.header( head ); return TAR_OK; } int TAREXPORT tar_inflateReset ( tar_streamp strm ) { assert(strm); auto& internal = intern( *strm ); internal.header( nullptr ); return TAR_OK; }
#include <string> #include <array> #include <cstdint> #include <cstdlib> #include <cassert> #include <type_traits> #include <sstream> #include <iterator> #include <tarlib/tarlib.h> namespace { #if 0 template <unsigned int OFFSET, unsigned int COUNT> unsigned long long _base256_to_10( typename std::enable_if<COUNT == 0, const Byte*>::type ptr) { return ptr[OFFSET]; } template <unsigned int OFFSET, unsigned int COUNT> unsigned long long _base256_to_10( typename std::enable_if<COUNT != 0, const Byte*>::type ptr) { return (ptr[OFFSET] * 256 * COUNT) + _base256_to_10<OFFSET + 1, COUNT - 1>( ptr ); } #endif template <unsigned int OFFSET, unsigned int COUNT> unsigned long long base256_to_10( const char* ptr) { //return _base256_to_10<OFFSET, COUNT - 1>( ptr ); return std::strtoull( ptr, nullptr, 256 ); } unsigned long base8_to_10( const char* ptr ) { return std::strtoul( ptr, nullptr, 8 ); } // Converts octal to usable decimal values void convert( tar_header& header ) { const bool is_base_256 = header.file_bytes_octal[0] & 0x80; std::uint64_t value; const auto& field = header.file_bytes_octal; // Enforce proper file_bytes encoding header.file_bytes_terminator = '\0'; if( is_base_256 ) { value = base256_to_10<1, 10>( field ); } else { //std::ostringstream stream; value = base8_to_10( field ); } header.file_bytes = value; header.modification_time = base8_to_10( header.modification_time_octal ); } // Internal tar state struct internal { internal(); tar_headerp header( tar_headerp ); bool put( tar_stream& strm, bool continueAfterHeader ); private: void reset( tar_stream& strm ); struct { tar_headerp ptr_begin; Byte* ptr; uint16_t left; //bytes left till header is full void reset() { ptr = reinterpret_cast<Byte*>( ptr_begin ); left = TAR_HEADER_SIZE; if( ptr_begin ) { ptr_begin->done = 0; ptr_begin->file_bytes = 0; ptr_begin->modification_time = 0; } } void reset( tar_headerp header ) { ptr_begin = header; reset(); } } _header; tar_header _internal_header; std::uint64_t _left; std::uint16_t _endPadding; }; internal& intern( tar_stream& strm ) { return *static_cast<internal*>( strm.state ); } Byte* begin( tar_header& header ) { return reinterpret_cast<Byte*>( &header ); } Byte* end( tar_header& header ) { return begin(header) + TAR_HEADER_SIZE; } } internal::internal() : _header(), _internal_header(), _left( 0 ) { _header.reset( &_internal_header ); } tar_headerp internal::header( tar_headerp header ) { _header.reset( header ); return _header.ptr_begin; } void internal::reset( tar_stream& strm ) { _header.reset(); strm.ptr_out = nullptr; strm.len_out = 0; _left = 0; } bool internal::put( tar_stream& strm, bool continueAfterHeader ) { if( !_header.left && !_left ) { if( strm.avail_in ) { // Go to the next entry reset( strm ); } return false; //end of entry } if( _header.left ) { // Try to make the header full const auto distance = std::min( static_cast<decltype(strm.avail_in)>(_header.left), strm.avail_in ); assert( distance <= _header.left ); if( _header.ptr ) { std::copy( strm.next_in, strm.next_in + distance, _header.ptr ); _header.ptr += distance; } strm.next_in += distance; strm.avail_in -= distance; strm.total_in += distance; // We made sure distance is at max _header.left #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wconversion" _header.left -= distance; #pragma GCC diagnostic pop if( !_header.left ) { // We reached a full header if( _header.ptr_begin ) { tar_header& header = *_header.ptr_begin; convert( header ); _header.ptr_begin->done = 1; } //FIXME: Make working without internal header _left = _header.ptr_begin->file_bytes; _endPadding = [&]() { // Data is always rounded up to 512 static const std::uint16_t PADDING_SIZE = 512; auto quot = _left / PADDING_SIZE; if( _left % PADDING_SIZE ) { ++quot; } return static_cast<uint16_t>( quot * PADDING_SIZE - _left ); }(); _left += _endPadding; if( !continueAfterHeader ) return true; } } if( !_header.left && strm.avail_in ) { // Process file entry content strm.ptr_out = strm.next_in; uInt moveValue = [&]() { if( _left > _endPadding ) { const std::uint64_t leftContent = _left - _endPadding; // Limit to current file entry only strm.len_out = strm.avail_in < leftContent ? strm.avail_in : static_cast<decltype(strm.avail_in)>( leftContent ); assert( strm.len_out <= leftContent ); strm.total_out += strm.len_out; return strm.len_out; } else { const uInt leftPadding = static_cast<decltype(_endPadding)>( _left ); // Consume the padding but do not generate output strm.len_out = 0; strm.total_out += leftPadding; return leftPadding; } }(); strm.avail_in -= moveValue; strm.next_in += moveValue; strm.total_in += moveValue; _left -= moveValue; } return true; } // C wrapper int TAREXPORT tar_inflateInit( tar_streamp strm ) { assert( strm ); strm->total_in = 0; strm->ptr_out = nullptr; strm->len_out = 0; strm->total_out = 0; strm->state = new internal(); return TAR_OK; } int TAREXPORT tar_inflate( tar_streamp strm, int flush ) { assert( strm ); if( intern(*strm).put( *strm, flush == TAR_SYNC_FLUSH ) ) return TAR_OK; else return TAR_ENTRY_END; } int TAREXPORT tar_inflateEnd( tar_streamp strm ) { assert( strm ); delete &intern( *strm ); // Signal to externals that the stream // has ended strm->state = nullptr; return TAR_OK; } int TAREXPORT tar_inflateGetHeader( tar_streamp strm, tar_headerp head ) { assert(strm); assert(head); auto& internal = intern( *strm ); internal.header( head ); return TAR_OK; } int TAREXPORT tar_inflateReset ( tar_streamp strm ) { assert(strm); auto& internal = intern( *strm ); internal.header( nullptr ); return TAR_OK; }
Make master compile again.
Make master compile again.
C++
apache-2.0
abergmeier/tarlib,abergmeier/tarlib
736417219a21715e2f661c7270956de58ed99fe8
srcs/Water.cpp
srcs/Water.cpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Water.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: pbroggi <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/06/04 15:29:11 by qlitzler #+# #+# */ /* Updated: 2015/06/11 18:39:33 by pbroggi ### ########.fr */ /* */ /* ************************************************************************** */ #include <Water.hpp> #include <Model.hpp> #include <stack> #include <iostream> /******************************************* Constructors *******************************************/ Water::Water(Model & model): AModule(model) { srand(time(nullptr)); this->_verticesSize = this->_model._grid * DIMENSIONS; this->_colorsSize = this->_model._grid * COLOR_CHANNELS; this->_normalsSize = this->_verticesSize; this->_elementsSize = this->_model._grid + (this->_model._vertexCol - 1) * (this->_model._vertexRow - 2); this->_terrainVertices = this->_model._terrain->getVertices(); this->_floodTop = this->_model._top * 0.6f; this->_normals = new GLfloat[this->_normalsSize](); this->_vertices = new GLfloat[this->_verticesSize](); this->createVertices(); this->createElements(); this->createColors(); this->createNormals(); return; } /******************************************* Destructor *******************************************/ Water::~Water(void) { return; } /******************************************* Member functions *******************************************/ void Water::createVertices(void) { for (GLuint i = 0; i < this->_verticesSize; i += DIMENSIONS) { this->_vertices[i] = this->_terrainVertices[i]; this->_vertices[i + 1] = this->_model._scenario == DRAIN ? this->_model._top : this->_terrainVertices[i + 1] - WATER_OFFSET; this->_vertices[i + 2] = this->_terrainVertices[i + 2]; } } void Water::createElements(void) { GLuint count = 0; GLuint i = 0; GLuint backwards = this->_model._col; bool offset = true; this->_elements = new GLuint[this->_elementsSize](); for (GLuint index = 0; index < this->_elementsSize; ++index) { if (count == this->_model._vertexCol + this->_model._col) { count = 0; offset = !offset; backwards = backwards == this->_model._col ? this->_model._col + 2 : this->_model._col; } this->_elements[index] = i; i += offset ? this->_model._vertexCol : -static_cast<int>(backwards); offset = !offset; ++count; } } void Water::createColors(void) { this->_colors = new GLfloat[this->_colorsSize](); for (GLuint i = 0; i < this->_colorsSize; i += COLOR_CHANNELS) { this->_colors[i] = 0.1f; this->_colors[i + 1] = 0.5f; this->_colors[i + 2] = 0.9f; this->_colors[i + 3] = 0.25f; } } void Water::createNormals(void) { for (GLuint i = 0; i < this->_normalsSize; i += DIMENSIONS) { this->_normals[i] = 0.0f; this->_normals[i + 1] = glm::normalize(static_cast<GLfloat>(rand())); this->_normals[i + 2] = 0.0f; } } void Water::assignWaterLevel(GLfloat water, GLuint start, GLuint end, GLuint step) { for (GLuint i = start; i < end; i += step) { if (this->_vertices[i + 1] > this->_model._bottom && this->_vertices[i + 1] < this->_floodTop) { this->_vertices[i + 1] += water; } } } void Water::flood(GLfloat waterLevel) { this->assignWaterLevel(waterLevel, 0, this->_model._vertexCol * DIMENSIONS, DIMENSIONS); this->assignWaterLevel(waterLevel, 0, this->_verticesSize, this->_model._vertexCol * DIMENSIONS); this->assignWaterLevel(waterLevel, this->_model._col * DIMENSIONS, this->_verticesSize, this->_model._vertexCol * DIMENSIONS); this->assignWaterLevel(waterLevel, this->_verticesSize - this->_model._vertexCol * DIMENSIONS, this->_verticesSize, DIMENSIONS); } void Water::waves(GLfloat coefficient) { static GLfloat x = 0.0f; static int t = 0; GLfloat cosinus = std::max(static_cast<double>(0), cos(x)); if (t == 0) { x += 0.1f; this->assignWaterLevel(coefficient * UNIT * cosinus, 0, this->_model._vertexCol * DIMENSIONS, DIMENSIONS); t = 3; } --t; } void Water::distribute(void) { static int adjacent[8] = { -(this->_model._stride + DIMENSIONS), 3, 3, this->_model._stride - 6, 6, this->_model._stride - 6, 3, 3 }; static GLuint skipForth[6] = {0, 3, 5, 2, 4, 7}; static GLuint skipBack[6] = {2, 4, 7, 0, 3, 5}; GLuint back; for(int i = 0; i < WATER_DISTRIBUTION_RATE; ++i) { back = this->_verticesSize - DIMENSIONS; for (GLuint forth = 0; forth < this->_verticesSize; forth += DIMENSIONS) { this->distributeGo(adjacent, skipForth, forth, 1); this->distributeGo(adjacent, skipBack, back, -1); back -= DIMENSIONS; } } } void Water::distributeGo(int adjacent[], GLuint skip[], GLuint pos, int flag) { int tmp; GLuint src, dest; GLfloat average, min, max; tmp = dest = src = pos; min = max = this->_vertices[pos + 1]; if (this->_vertices[pos + 1] > this->_terrainVertices[pos + 1]) { for (GLuint i = 0; i < 8; i++) { tmp += adjacent[i] * flag; if ((pos % (this->_model._vertexCol * DIMENSIONS) == 0 && (i == skip[0] || i == skip[1] || i == skip[2]))) { continue ; } if ((pos + 2) % (this->_model._vertexCol * DIMENSIONS) == this->_model._vertexCol * DIMENSIONS - 1 && (i == skip[3] || i == skip[4] || i == skip[5])) { continue ; } if (tmp >= 0 && tmp < static_cast<int>(this->_verticesSize)) { if (this->_vertices[tmp + 1] < min) { dest = tmp; min = this->_vertices[tmp + 1]; } if (this->_vertices[tmp + 1] > max) { src = tmp; max = this->_vertices[tmp + 1]; } } } average = (max + min) / 2.0f; this->_vertices[src + 1] = average; this->_vertices[dest + 1] = average; } }
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Water.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: qlitzler <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/06/04 15:29:11 by qlitzler #+# #+# */ /* Updated: 2015/06/13 16:01:50 by qlitzler ### ########.fr */ /* */ /* ************************************************************************** */ #include <Water.hpp> #include <Model.hpp> #include <stack> #include <iostream> /******************************************* Constructors *******************************************/ Water::Water(Model & model): AModule(model) { srand(time(nullptr)); this->_verticesSize = this->_model._grid * DIMENSIONS; this->_colorsSize = this->_model._grid * COLOR_CHANNELS; this->_normalsSize = this->_verticesSize; this->_elementsSize = this->_model._grid + (this->_model._vertexCol - 1) * (this->_model._vertexRow - 2); this->_terrainVertices = this->_model._terrain->getVertices(); this->_floodTop = this->_model._top * 0.6f; this->_normals = new GLfloat[this->_normalsSize](); this->_vertices = new GLfloat[this->_verticesSize](); this->createVertices(); this->createElements(); this->createColors(); this->createNormals(); return; } /******************************************* Destructor *******************************************/ Water::~Water(void) { return; } /******************************************* Member functions *******************************************/ void Water::createVertices(void) { for (GLuint i = 0; i < this->_verticesSize; i += DIMENSIONS) { this->_vertices[i] = this->_terrainVertices[i]; this->_vertices[i + 1] = this->_model._scenario == DRAIN ? this->_model._top : this->_terrainVertices[i + 1] - WATER_OFFSET; this->_vertices[i + 2] = this->_terrainVertices[i + 2]; } } void Water::createElements(void) { GLuint count = 0; GLuint i = 0; GLuint backwards = this->_model._col; bool offset = true; this->_elements = new GLuint[this->_elementsSize](); for (GLuint index = 0; index < this->_elementsSize; ++index) { if (count == this->_model._vertexCol + this->_model._col) { count = 0; offset = !offset; backwards = backwards == this->_model._col ? this->_model._col + 2 : this->_model._col; } this->_elements[index] = i; i += offset ? this->_model._vertexCol : -static_cast<int>(backwards); offset = !offset; ++count; } } void Water::createColors(void) { this->_colors = new GLfloat[this->_colorsSize](); for (GLuint i = 0; i < this->_colorsSize; i += COLOR_CHANNELS) { this->_colors[i] = 0.1f; this->_colors[i + 1] = 0.5f; this->_colors[i + 2] = 0.9f; this->_colors[i + 3] = 0.25f; } } void Water::createNormals(void) { for (GLuint i = 0; i < this->_normalsSize; i += DIMENSIONS) { this->_normals[i] = 0.0f; this->_normals[i + 1] = glm::normalize(static_cast<GLfloat>(rand())); this->_normals[i + 2] = 0.0f; } } void Water::assignWaterLevel(GLfloat water, GLuint start, GLuint end, GLuint step) { for (GLuint i = start; i < end; i += step) { if (this->_vertices[i + 1] > this->_model._bottom && this->_vertices[i + 1] < this->_floodTop) { this->_vertices[i + 1] += water; } } } void Water::flood(GLfloat waterLevel) { this->assignWaterLevel(waterLevel, 0, this->_model._vertexCol * DIMENSIONS, DIMENSIONS); this->assignWaterLevel(waterLevel, 0, this->_verticesSize, this->_model._vertexCol * DIMENSIONS); this->assignWaterLevel(waterLevel, this->_model._col * DIMENSIONS, this->_verticesSize, this->_model._vertexCol * DIMENSIONS); this->assignWaterLevel(waterLevel, this->_verticesSize - this->_model._vertexCol * DIMENSIONS, this->_verticesSize, DIMENSIONS); } void Water::waves(GLfloat coefficient) { static GLfloat x = 0.0f; static int t = 0; GLfloat cosinus = std::max(static_cast<double>(0), cos(x)); if (t == 0) { x += 0.1f; this->assignWaterLevel(coefficient * UNIT * cosinus, 0, this->_model._vertexCol * DIMENSIONS, DIMENSIONS); t = 3; } --t; } void Water::distribute(void) { static int adjacent[8] = { -(this->_model._stride + DIMENSIONS), 3, 3, this->_model._stride - 6, 6, this->_model._stride - 6, 3, 3 }; static GLuint skipForth[6] = {0, 3, 5, 2, 4, 7}; static GLuint skipBack[6] = {2, 4, 7, 0, 3, 5}; GLuint back; for(int i = 0; i < WATER_DISTRIBUTION_RATE; ++i) { back = this->_verticesSize - DIMENSIONS; for (GLuint forth = 0; forth < this->_verticesSize; forth += DIMENSIONS) { this->distributeGo(adjacent, skipForth, forth, 1); this->distributeGo(adjacent, skipBack, back, -1); back -= DIMENSIONS; } } } void Water::distributeGo(int adjacent[], GLuint skip[], GLuint pos, int flag) { int tmp; GLuint src, dest; GLfloat average, min, max; tmp = dest = src = pos; min = max = this->_vertices[pos + 1]; if (this->_vertices[pos + 1] > this->_terrainVertices[pos + 1]) { for (GLuint i = 0; i < 8; i++) { tmp += adjacent[i] * flag; if ((pos % (this->_model._vertexCol * DIMENSIONS) == 0 && (i == skip[0] || i == skip[1] || i == skip[2]))) { continue ; } if ((pos + 2) % (this->_model._vertexCol * DIMENSIONS) == this->_model._vertexCol * DIMENSIONS - 1 && (i == skip[3] || i == skip[4] || i == skip[5])) { continue ; } if (tmp >= 0 && tmp < static_cast<int>(this->_verticesSize)) { if (this->_vertices[tmp + 1] < min) { dest = tmp; min = this->_vertices[tmp + 1]; } else if (this->_vertices[tmp + 1] > max) { src = tmp; max = this->_vertices[tmp + 1]; } } } average = (max + min) / 2.0f; this->_vertices[src + 1] = average; this->_vertices[dest + 1] = average; } }
add else if instead of if if
add else if instead of if if
C++
mit
q-litzler/Hydrodynamic-Simulation,q-litzler/Hydrodynamic-Simulation
dceaa3de1b326a22f1f1748cb05febcf813d878c
stacer/app.cpp
stacer/app.cpp
#include "app.h" #include "ui_app.h" #include "Managers/app_manager.h" pp::~App() { delete ui; } App::App(QWidget *parent) : QMainWindow(parent), ui(new Ui::App), dashboardPage(new DashboardPage(this)), startupAppsPage(new StartupAppsPage(this)), systemCleanerPage(new SystemCleanerPage(this)), servicesPage(new ServicesPage(this)), processPage(new ProcessesPage(this)), uninstallerPage(new UninstallerPage(this)), resourcesPage(new ResourcesPage(this)), settingsPage(new SettingsPage(this)) { ui->setupUi(this); init(); } void App::init() { setGeometry( QStyle::alignedRect( Qt::LeftToRight, Qt::AlignCenter, size(), qApp->desktop()->availableGeometry()) ); // form settings ui->horizontalLayout->setContentsMargins(0,0,0,0); ui->horizontalLayout->setSpacing(0); // icon sizes of the buttons on the sidebar 30x30 for (QPushButton *btn : ui->sidebar->findChildren<QPushButton*>()) btn->setIconSize(QSize(26, 26)); // add pages ui->pageStacked->addWidget(dashboardPage); ui->pageStacked->addWidget(startupAppsPage); ui->pageStacked->addWidget(systemCleanerPage); ui->pageStacked->addWidget(servicesPage); ui->pageStacked->addWidget(processPage); ui->pageStacked->addWidget(uninstallerPage); ui->pageStacked->addWidget(resourcesPage); ui->pageStacked->addWidget(settingsPage); on_dashBtn_clicked(); } void App::pageClick(QPushButton *btn, QWidget *w, QString title) { // all button checked false for (QPushButton *b : ui->sidebar->findChildren<QPushButton*>()) b->setChecked(false); btn->setChecked(true); // clicked button set active style AppManager::ins()->updateStylesheet(); // update style ui->pageTitle->setText(title+"3232323---"); ui->pageStacked->setCurrentWidget(w); } void App::on_dashBtn_clicked() { pageClick(ui->dashBtn, dashboardPage, tr("Dashboard")); } void App::on_systemCleanerBtn_clicked() { pageClick(ui->systemCleanerBtn, systemCleanerPage, tr("System Cleaner")); } void App::on_startupAppsBtn_clicked() { pageClick(ui->startupAppsBtn, startupAppsPage, tr("System Startup Apps")); } void App::on_servicesBtn_clicked() { pageClick(ui->servicesBtn, servicesPage, tr("System Services")); } void App::on_uninstallerBtn_clicked() { pageClick(ui->uninstallerBtn, uninstallerPage, tr("Uninstaller")); } void App::on_resourcesBtn_clicked() { pageClick(ui->resourcesBtn, resourcesPage, tr("Resources")); } void App::on_processesBtn_clicked() { pageClick(ui->processesBtn, processPage, tr("Processes")); } void App::on_settingsBtn_clicked() { pageClick(ui->settingsBtn, settingsPage, tr("Settings")); }
#include "app.h" #include "ui_app.h" #include "Managers/app_manager.h" App::~App() { delete ui; } App::App(QWidget *parent) : QMainWindow(parent), ui(new Ui::App), dashboardPage(new DashboardPage(this)), startupAppsPage(new StartupAppsPage(this)), systemCleanerPage(new SystemCleanerPage(this)), servicesPage(new ServicesPage(this)), processPage(new ProcessesPage(this)), uninstallerPage(new UninstallerPage(this)), resourcesPage(new ResourcesPage(this)), settingsPage(new SettingsPage(this)) { ui->setupUi(this); init(); } void App::init() { setGeometry( QStyle::alignedRect( Qt::LeftToRight, Qt::AlignCenter, size(), qApp->desktop()->availableGeometry()) ); // form settings ui->horizontalLayout->setContentsMargins(0,0,0,0); ui->horizontalLayout->setSpacing(0); // icon sizes of the buttons on the sidebar 30x30 for (QPushButton *btn : ui->sidebar->findChildren<QPushButton*>()) btn->setIconSize(QSize(26, 26)); // add pages ui->pageStacked->addWidget(dashboardPage); ui->pageStacked->addWidget(startupAppsPage); ui->pageStacked->addWidget(systemCleanerPage); ui->pageStacked->addWidget(servicesPage); ui->pageStacked->addWidget(processPage); ui->pageStacked->addWidget(uninstallerPage); ui->pageStacked->addWidget(resourcesPage); ui->pageStacked->addWidget(settingsPage); on_dashBtn_clicked(); } void App::pageClick(QPushButton *btn, QWidget *w, QString title) { // all button checked false for (QPushButton *b : ui->sidebar->findChildren<QPushButton*>()) b->setChecked(false); btn->setChecked(true); // clicked button set active style AppManager::ins()->updateStylesheet(); // update style ui->pageTitle->setText(title+"3232323---"); ui->pageStacked->setCurrentWidget(w); } void App::on_dashBtn_clicked() { pageClick(ui->dashBtn, dashboardPage, tr("Dashboard")); } void App::on_systemCleanerBtn_clicked() { pageClick(ui->systemCleanerBtn, systemCleanerPage, tr("System Cleaner")); } void App::on_startupAppsBtn_clicked() { pageClick(ui->startupAppsBtn, startupAppsPage, tr("System Startup Apps")); } void App::on_servicesBtn_clicked() { pageClick(ui->servicesBtn, servicesPage, tr("System Services")); } void App::on_uninstallerBtn_clicked() { pageClick(ui->uninstallerBtn, uninstallerPage, tr("Uninstaller")); } void App::on_resourcesBtn_clicked() { pageClick(ui->resourcesBtn, resourcesPage, tr("Resources")); } void App::on_processesBtn_clicked() { pageClick(ui->processesBtn, processPage, tr("Processes")); } void App::on_settingsBtn_clicked() { pageClick(ui->settingsBtn, settingsPage, tr("Settings")); }
Update app.cpp
Update app.cpp
C++
mit
atakanprofile/Stoc,atakanprofile/Stoc,atakanprofile/Stoc
a255c39f247f21ac89610d0992f258aac1760a54
QFunctionalities/QmitkDataTreeFilterDemo/QmitkDataTreeFilterDemo.cpp
QFunctionalities/QmitkDataTreeFilterDemo/QmitkDataTreeFilterDemo.cpp
/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 notices for more information. =========================================================================*/ #include "QmitkDataTreeFilterDemo.h" #include "QmitkDataTreeFilterDemoControls.h" #include "QmitkPropertyViewFactory.h" #include "QmitkDataTreeComboBox.h" #include "QmitkDataTreeListView.h" #include "QmitkStdMultiWidget.h" #include "icon.xpm" #include "mitkDataTreeFilterFunctions.h" #include "mitkSurface.h" QmitkDataTreeFilterDemo::QmitkDataTreeFilterDemo(QObject *parent, const char *name, QmitkStdMultiWidget *mitkStdMultiWidget, mitk::DataTreeIteratorBase* it) : QmitkFunctionality(parent, name, it), m_MultiWidget(mitkStdMultiWidget), m_Controls(NULL), m_FilterInitialized(false) { SetAvailability(true); } QmitkDataTreeFilterDemo::~QmitkDataTreeFilterDemo() { if(m_DataTreeFilter.IsNotNull()) m_DataTreeFilter->RemoveObserver( m_ListboxModifiedConnection ); } QWidget* QmitkDataTreeFilterDemo::CreateMainWidget(QWidget* parent) { return NULL; } QWidget* QmitkDataTreeFilterDemo::CreateControlWidget(QWidget* parent) { if (!m_Controls) { m_Controls = new QmitkDataTreeFilterDemoControls(parent); } return m_Controls; } void QmitkDataTreeFilterDemo::CreateConnections() { if ( m_Controls ) { connect( m_Controls->TreeComboBox, SIGNAL(activated(const mitk::DataTreeFilter::Item*)), this, SLOT(onComboBoxItemSelected(const mitk::DataTreeFilter::Item*)) ); connect( m_Controls->TreeListBox, SIGNAL(clicked(const mitk::DataTreeFilter::Item*, bool)), this, SLOT(onListboxItemClicked(const mitk::DataTreeFilter::Item*, bool)) ); connect( m_Controls->TreeListBox, SIGNAL(newItem(const mitk::DataTreeFilter::Item*)), this, SLOT(onListboxItemAdded(const mitk::DataTreeFilter::Item*)) ); connect( m_Controls->cmbFilterFunction, SIGNAL(activated(int)), this, SLOT(onCmbFilterFunctionActivated(int)) ); connect( (QObject*)(m_Controls->chkHierarchy), SIGNAL(toggled(bool)), this, SLOT(onChkHierarchyToggled(bool)) ); } } QAction* QmitkDataTreeFilterDemo::CreateAction(QActionGroup* parent) { QAction* action; action = new QAction( tr( "Demo for mitk::DataTreeFilter" ), QPixmap((const char**)icon_xpm), tr( "DataTreeFilterDemo" ), 0, parent, "DataTreeFilterDemo" ); return action; } void QmitkDataTreeFilterDemo::TreeChanged() { } void QmitkDataTreeFilterDemo::Activated() { QmitkFunctionality::Activated(); if (!m_FilterInitialized) { // init the combobox (to show only images, which is also the default) m_Controls->TreeComboBox->SetDataTree( GetDataTreeIterator() ); m_Controls->TreeComboBox->GetFilter()->SetFilter( mitk::IsBaseDataType<mitk::Image>() ); // this line could be skipped because this filter is the default at the moment // define the list of segmentations m_DataTreeFilter = mitk::DataTreeFilter::New( GetDataTreeIterator()->GetTree() ); m_DataTreeFilter->SetSelectionMode(mitk::DataTreeFilter::SINGLE_SELECT); m_DataTreeFilter->SetHierarchyHandling(mitk::DataTreeFilter::FLATTEN_HIERARCHY); m_DataTreeFilter->SetFilter( mitk::IsGoodDataTreeNode() ); // show everything with data // define what is displayed about the segmentations mitk::DataTreeFilter::PropertyList visible_props; visible_props.push_back("visible"); visible_props.push_back("color"); visible_props.push_back("name"); m_DataTreeFilter->SetVisibleProperties(visible_props); mitk::DataTreeFilter::PropertyList editable_props; editable_props.push_back("visible"); editable_props.push_back("name"); editable_props.push_back("color"); m_DataTreeFilter->SetEditableProperties(editable_props); mitk::DataTreeFilter::PropertyList property_labels; property_labels.push_back(" "); property_labels.push_back(" "); property_labels.push_back("Name"); m_DataTreeFilter->SetPropertiesLabels(property_labels); m_Controls->TreeListBox->SetViewType("name", QmitkPropertyViewFactory::etON_DEMAND_EDIT); m_Controls->TreeListBox->SetFilter( m_DataTreeFilter ); ConnectListboxNotification(); m_FilterInitialized = true; } } void QmitkDataTreeFilterDemo::Deactivated() { QmitkFunctionality::Deactivated(); } void QmitkDataTreeFilterDemo::ConnectListboxNotification() { itk::ReceptorMemberCommand<QmitkDataTreeFilterDemo>::Pointer command = itk::ReceptorMemberCommand<QmitkDataTreeFilterDemo>::New(); command->SetCallbackFunction(this, &QmitkDataTreeFilterDemo::ListboxModifiedHandler); m_ListboxModifiedConnection = m_DataTreeFilter->AddObserver(itk::ModifiedEvent(), command); } void QmitkDataTreeFilterDemo::onComboBoxItemSelected(const mitk::DataTreeFilter::Item* item) { std::cout << "(Combobox) Item " << item << " selected." << std::endl; if (item) { const mitk::DataTreeNode* node = item->GetNode(); if (node && node->GetData()) { // reinit multi-widget for the selected image m_MultiWidget->InitializeStandardViews( node->GetData()->GetTimeSlicedGeometry() ); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } } void QmitkDataTreeFilterDemo::MoveCrossHairToItem(const mitk::DataTreeFilter::Item* item) { if (!item) return; // get tree node const mitk::DataTreeNode* node( item->GetNode() ); if (!node) return; // determine center of node mitk::Point2D p2d; if ( node->GetData() && node->GetData()->GetGeometry() ) { mitk::Point3D center( node->GetData()->GetGeometry()->GetCenter() ); // tell the multiwidget to move there m_MultiWidget->MoveCrossToPosition( center ); } } void QmitkDataTreeFilterDemo::onListboxItemClicked(const mitk::DataTreeFilter::Item* item, bool selected) { if (selected) std::cout << "(Listbox) Item " << item << " selected." << std::endl; else std::cout << "(Listbox) Item " << item << " deselected." << std::endl; if (!selected) return; MoveCrossHairToItem(item); } void QmitkDataTreeFilterDemo::onListboxItemAdded(const mitk::DataTreeFilter::Item* item) { MoveCrossHairToItem(item); } void QmitkDataTreeFilterDemo::ListboxModifiedHandler( const itk::EventObject& e ) { std::cout << "(Listbox) Something changed." << std::endl; //const mitk::DataTreeFilter::ItemList* items = m_DataTreeFilter->GetItems(); //in case you want to iterate over them } void QmitkDataTreeFilterDemo::onCmbFilterFunctionActivated(int i) { switch (i) { case 0: m_DataTreeFilter->SetFilter( mitk::IsGoodDataTreeNode() ); break; case 1: m_DataTreeFilter->SetFilter( mitk::IsBaseDataType<mitk::Image>() ); break; case 2: m_DataTreeFilter->SetFilter( mitk::IsBaseDataType<mitk::Surface>() ); break; case 3: m_DataTreeFilter->SetFilter( mitk::IsDataTreeNode() ); // probably not what the label promises break; } } void QmitkDataTreeFilterDemo::onChkHierarchyToggled(bool on) { if (on) m_DataTreeFilter->SetHierarchyHandling( mitk::DataTreeFilter::PRESERVE_HIERARCHY ); else m_DataTreeFilter->SetHierarchyHandling( mitk::DataTreeFilter::FLATTEN_HIERARCHY ); }
/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 notices for more information. =========================================================================*/ #include "QmitkDataTreeFilterDemo.h" #include "QmitkDataTreeFilterDemoControls.h" #include "QmitkPropertyViewFactory.h" #include "QmitkDataTreeComboBox.h" #include "QmitkDataTreeListView.h" #include "QmitkStdMultiWidget.h" #include "icon.xpm" #include "mitkDataTreeFilterFunctions.h" #include "mitkSurface.h" QmitkDataTreeFilterDemo::QmitkDataTreeFilterDemo(QObject *parent, const char *name, QmitkStdMultiWidget *mitkStdMultiWidget, mitk::DataTreeIteratorBase* it) : QmitkFunctionality(parent, name, it), m_MultiWidget(mitkStdMultiWidget), m_Controls(NULL), m_FilterInitialized(false) { SetAvailability(true); } QmitkDataTreeFilterDemo::~QmitkDataTreeFilterDemo() { if(m_DataTreeFilter.IsNotNull()) m_DataTreeFilter->RemoveObserver( m_ListboxModifiedConnection ); } QWidget* QmitkDataTreeFilterDemo::CreateMainWidget(QWidget* parent) { return NULL; } QWidget* QmitkDataTreeFilterDemo::CreateControlWidget(QWidget* parent) { if (!m_Controls) { m_Controls = new QmitkDataTreeFilterDemoControls(parent); } return m_Controls; } void QmitkDataTreeFilterDemo::CreateConnections() { if ( m_Controls ) { connect( m_Controls->TreeComboBox, SIGNAL(activated(const mitk::DataTreeFilter::Item*)), this, SLOT(onComboBoxItemSelected(const mitk::DataTreeFilter::Item*)) ); connect( m_Controls->TreeListBox, SIGNAL(clicked(const mitk::DataTreeFilter::Item*, bool)), this, SLOT(onListboxItemClicked(const mitk::DataTreeFilter::Item*, bool)) ); connect( m_Controls->TreeListBox, SIGNAL(newItem(const mitk::DataTreeFilter::Item*)), this, SLOT(onListboxItemAdded(const mitk::DataTreeFilter::Item*)) ); connect( m_Controls->cmbFilterFunction, SIGNAL(activated(int)), this, SLOT(onCmbFilterFunctionActivated(int)) ); connect( (QObject*)(m_Controls->chkHierarchy), SIGNAL(toggled(bool)), this, SLOT(onChkHierarchyToggled(bool)) ); } } QAction* QmitkDataTreeFilterDemo::CreateAction(QActionGroup* parent) { QAction* action; action = new QAction( tr( "Demo for mitk::DataTreeFilter" ), QPixmap((const char**)icon_xpm), tr( "DataTreeFilterDemo" ), 0, parent, "DataTreeFilterDemo" ); return action; } void QmitkDataTreeFilterDemo::TreeChanged() { } void QmitkDataTreeFilterDemo::Activated() { QmitkFunctionality::Activated(); if (!m_FilterInitialized) { // init the combobox (to show only images, which is also the default) m_Controls->TreeComboBox->SetDataTree( GetDataTreeIterator() ); m_Controls->TreeComboBox->GetFilter()->SetFilter( mitk::IsBaseDataType<mitk::Image>() ); // this line could be skipped because this filter is the default at the moment // define the list of segmentations m_DataTreeFilter = mitk::DataTreeFilter::New( GetDataTreeIterator()->GetTree() ); m_DataTreeFilter->SetSelectionMode(mitk::DataTreeFilter::SINGLE_SELECT); m_DataTreeFilter->SetHierarchyHandling(mitk::DataTreeFilter::FLATTEN_HIERARCHY); m_DataTreeFilter->SetFilter( mitk::IsGoodDataTreeNode() ); // show everything with data // define what is displayed about the segmentations mitk::DataTreeFilter::PropertyList visible_props; visible_props.push_back("visible"); visible_props.push_back("color"); visible_props.push_back("name"); m_DataTreeFilter->SetVisibleProperties(visible_props); mitk::DataTreeFilter::PropertyList editable_props; editable_props.push_back("visible"); editable_props.push_back("name"); editable_props.push_back("color"); m_DataTreeFilter->SetEditableProperties(editable_props); mitk::DataTreeFilter::PropertyList property_labels; property_labels.push_back(" "); property_labels.push_back(" "); property_labels.push_back("Name"); m_DataTreeFilter->SetPropertiesLabels(property_labels); m_Controls->TreeListBox->SetViewType("name", QmitkPropertyViewFactory::etON_DEMAND_EDIT); m_Controls->TreeListBox->SetFilter( m_DataTreeFilter ); ConnectListboxNotification(); m_FilterInitialized = true; } } void QmitkDataTreeFilterDemo::Deactivated() { QmitkFunctionality::Deactivated(); } void QmitkDataTreeFilterDemo::ConnectListboxNotification() { itk::ReceptorMemberCommand<QmitkDataTreeFilterDemo>::Pointer command = itk::ReceptorMemberCommand<QmitkDataTreeFilterDemo>::New(); command->SetCallbackFunction(this, &QmitkDataTreeFilterDemo::ListboxModifiedHandler); m_ListboxModifiedConnection = m_DataTreeFilter->AddObserver(itk::ModifiedEvent(), command); } void QmitkDataTreeFilterDemo::onComboBoxItemSelected(const mitk::DataTreeFilter::Item* item) { if ( !IsActivated() ) return; // don't do anything if functionality isn't activated std::cout << "(Combobox) Item " << item << " selected." << std::endl; if (item) { const mitk::DataTreeNode* node = item->GetNode(); if (node && node->GetData()) { // reinit multi-widget for the selected image m_MultiWidget->InitializeStandardViews( node->GetData()->GetTimeSlicedGeometry() ); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } } void QmitkDataTreeFilterDemo::MoveCrossHairToItem(const mitk::DataTreeFilter::Item* item) { if (!item) return; // get tree node const mitk::DataTreeNode* node( item->GetNode() ); if (!node) return; // determine center of node mitk::Point2D p2d; if ( node->GetData() && node->GetData()->GetGeometry() ) { mitk::Point3D center( node->GetData()->GetGeometry()->GetCenter() ); // tell the multiwidget to move there m_MultiWidget->MoveCrossToPosition( center ); } } void QmitkDataTreeFilterDemo::onListboxItemClicked(const mitk::DataTreeFilter::Item* item, bool selected) { if (selected) std::cout << "(Listbox) Item " << item << " selected." << std::endl; else std::cout << "(Listbox) Item " << item << " deselected." << std::endl; if (!selected) return; MoveCrossHairToItem(item); } void QmitkDataTreeFilterDemo::onListboxItemAdded(const mitk::DataTreeFilter::Item* item) { if ( !IsActivated() ) return; // don't do anything if functionality isn't activated MoveCrossHairToItem(item); } void QmitkDataTreeFilterDemo::ListboxModifiedHandler( const itk::EventObject& e ) { std::cout << "(Listbox) Something changed." << std::endl; //const mitk::DataTreeFilter::ItemList* items = m_DataTreeFilter->GetItems(); //in case you want to iterate over them } void QmitkDataTreeFilterDemo::onCmbFilterFunctionActivated(int i) { switch (i) { case 0: m_DataTreeFilter->SetFilter( mitk::IsGoodDataTreeNode() ); break; case 1: m_DataTreeFilter->SetFilter( mitk::IsBaseDataType<mitk::Image>() ); break; case 2: m_DataTreeFilter->SetFilter( mitk::IsBaseDataType<mitk::Surface>() ); break; case 3: m_DataTreeFilter->SetFilter( mitk::IsDataTreeNode() ); // probably not what the label promises break; } } void QmitkDataTreeFilterDemo::onChkHierarchyToggled(bool on) { if (on) m_DataTreeFilter->SetHierarchyHandling( mitk::DataTreeFilter::PRESERVE_HIERARCHY ); else m_DataTreeFilter->SetHierarchyHandling( mitk::DataTreeFilter::FLATTEN_HIERARCHY ); }
FIX test if functionality is active before reacting to data tree changes
FIX test if functionality is active before reacting to data tree changes
C++
bsd-3-clause
MITK/MITK,danielknorr/MITK,MITK/MITK,danielknorr/MITK,lsanzdiaz/MITK-BiiG,MITK/MITK,NifTK/MITK,fmilano/mitk,RabadanLab/MITKats,danielknorr/MITK,RabadanLab/MITKats,fmilano/mitk,RabadanLab/MITKats,iwegner/MITK,NifTK/MITK,danielknorr/MITK,RabadanLab/MITKats,lsanzdiaz/MITK-BiiG,danielknorr/MITK,rfloca/MITK,iwegner/MITK,fmilano/mitk,rfloca/MITK,iwegner/MITK,fmilano/mitk,danielknorr/MITK,rfloca/MITK,nocnokneo/MITK,NifTK/MITK,MITK/MITK,MITK/MITK,NifTK/MITK,nocnokneo/MITK,lsanzdiaz/MITK-BiiG,iwegner/MITK,rfloca/MITK,nocnokneo/MITK,rfloca/MITK,fmilano/mitk,lsanzdiaz/MITK-BiiG,lsanzdiaz/MITK-BiiG,rfloca/MITK,danielknorr/MITK,lsanzdiaz/MITK-BiiG,fmilano/mitk,rfloca/MITK,RabadanLab/MITKats,iwegner/MITK,fmilano/mitk,nocnokneo/MITK,MITK/MITK,lsanzdiaz/MITK-BiiG,iwegner/MITK,NifTK/MITK,RabadanLab/MITKats,NifTK/MITK,nocnokneo/MITK,nocnokneo/MITK,lsanzdiaz/MITK-BiiG,nocnokneo/MITK
369aac5dc2342ae1651ee4bfcda9fe6b195d67b4
sandbox/TestTransfer.cpp
sandbox/TestTransfer.cpp
#include <netdb.h> #include <netinet/in.h> #include <pthread.h> /* POSIX Threads */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/types.h> #include <unistd.h> void *server_main(void *); void *client_main(void *); int main() { pthread_t thread1, thread2; /* create threads 1 and 2 */ pthread_create(&thread1, NULL, server_main, (void *)NULL); pthread_create(&thread2, NULL, client_main, (void *)NULL); /* Main block now waits for both threads to terminate, before it exits If main block exits, both threads exit, even if the threads have not finished their work */ pthread_join(thread1, NULL); pthread_join(thread2, NULL); return 0; } void client_error(const char *msg) { perror(msg); fprintf(stderr, "CLIENT: %s\n", msg); fflush(stdout); fflush(stderr); exit(1); } void server_error(const char *msg) { perror(msg); fprintf(stderr, "SERVER: %s\n", msg); fflush(stdout); fflush(stderr); exit(1); } void *server_main(void *) { int sockfd, newsockfd, portno; socklen_t clilen; char buffer[256]; sockaddr_in serv_addr, cli_addr; int n; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) server_error("ERROR opening socket"); bzero((char *)&serv_addr, sizeof(serv_addr)); portno = 11223; serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons(portno); if (bind(sockfd, (sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) server_error("ERROR on binding"); listen(sockfd, 5); clilen = sizeof(cli_addr); newsockfd = accept(sockfd, (sockaddr *)&cli_addr, &clilen); if (newsockfd < 0) server_error("ERROR on accept"); bzero(buffer, 256); n = read(newsockfd, buffer, 255); if (n < 0) server_error("ERROR reading from socket"); printf("Here is the message: %s\n", buffer); if (strcmp(buffer, "Hello World!")) { server_error("Data is corrupt"); } n = write(newsockfd, "I got your message", 18); if (n < 0) server_error("ERROR writing to socket"); close(newsockfd); close(sockfd); return 0; } void *client_main(void *) { int sockfd, portno, n; sockaddr_in serv_addr; hostent *server; char buffer[256]; portno = 11223; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) client_error("ERROR opening socket"); server = gethostbyname("localhost"); if (server == NULL) { fprintf(stderr, "ERROR, no such host\n"); exit(0); } bzero((char *)&serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length); serv_addr.sin_port = htons(portno); if (connect(sockfd, (sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) client_error("ERROR connecting"); bzero(buffer, 256); sprintf(buffer, "%s", "Hello World!"); n = write(sockfd, buffer, strlen(buffer)); if (n < 0) client_error("ERROR writing to socket"); bzero(buffer, 256); n = read(sockfd, buffer, 255); if (n < 0) client_error("ERROR reading from socket"); printf("%s\n", buffer); close(sockfd); return 0; }
#include <netdb.h> #include <netinet/in.h> #include <pthread.h> /* POSIX Threads */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/types.h> #include <unistd.h> void *server_main(void *); void *client_main(void *); int main() { pthread_t thread1, thread2; /* create threads 1 and 2 */ pthread_create(&thread1, NULL, server_main, (void *)NULL); pthread_create(&thread2, NULL, client_main, (void *)NULL); /* Main block now waits for both threads to terminate, before it exits If main block exits, both threads exit, even if the threads have not finished their work */ pthread_join(thread1, NULL); pthread_join(thread2, NULL); return 0; } void client_error(const char *msg) { perror(msg); fprintf(stderr, "CLIENT: %s\n", msg); fflush(stdout); fflush(stderr); exit(1); } void server_error(const char *msg) { perror(msg); fprintf(stderr, "SERVER: %s\n", msg); fflush(stdout); fflush(stderr); exit(1); } void *server_main(void *) { int sockfd, newsockfd, portno; socklen_t clilen; char buffer[256]; sockaddr_in serv_addr, cli_addr; int n; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) server_error("ERROR opening socket"); bzero((char *)&serv_addr, sizeof(serv_addr)); portno = 11223; serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons(portno); // Also set the accept socket as reusable { int flag = 1; setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (char *)&flag, sizeof(int)); } if (bind(sockfd, (sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) server_error("ERROR on binding"); listen(sockfd, 5); clilen = sizeof(cli_addr); newsockfd = accept(sockfd, (sockaddr *)&cli_addr, &clilen); if (newsockfd < 0) server_error("ERROR on accept"); bzero(buffer, 256); n = read(newsockfd, buffer, 255); if (n < 0) server_error("ERROR reading from socket"); printf("Here is the message: %s\n", buffer); if (strcmp(buffer, "Hello World!")) { server_error("Data is corrupt"); } n = write(newsockfd, "I got your message", 18); if (n < 0) server_error("ERROR writing to socket"); close(newsockfd); close(sockfd); return 0; } void *client_main(void *) { int sockfd, portno, n; sockaddr_in serv_addr; hostent *server; char buffer[256]; portno = 11223; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) client_error("ERROR opening socket"); server = gethostbyname("localhost"); if (server == NULL) { fprintf(stderr, "ERROR, no such host\n"); exit(0); } bzero((char *)&serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length); serv_addr.sin_port = htons(portno); if (connect(sockfd, (sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) client_error("ERROR connecting"); bzero(buffer, 256); sprintf(buffer, "%s", "Hello World!"); n = write(sockfd, buffer, strlen(buffer)); if (n < 0) client_error("ERROR writing to socket"); bzero(buffer, 256); n = read(sockfd, buffer, 255); if (n < 0) client_error("ERROR reading from socket"); printf("%s\n", buffer); close(sockfd); return 0; }
Fix bug where TestTransfer would hang onto the socket and the test was not repeatable
Fix bug where TestTransfer would hang onto the socket and the test was not repeatable
C++
apache-2.0
MisterTea/EternalTCP,MisterTea/EternalTCP,MisterTea/EternalTCP
0b6b2015f035750ef830ba4619fd128aabc48ef6
scene/property_utils.cpp
scene/property_utils.cpp
/*************************************************************************/ /* property_utils.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "property_utils.h" #include "core/core_string_names.h" #include "core/engine.h" #include "core/local_vector.h" #include "editor/editor_node.h" #include "scene/resources/packed_scene.h" bool PropertyUtils::is_property_value_different(const Variant &p_a, const Variant &p_b) { if (p_a.get_type() == Variant::REAL && p_b.get_type() == Variant::REAL) { //this must be done because, as some scenes save as text, there might be a tiny difference in floats due to numerical error return !Math::is_equal_approx((float)p_a, (float)p_b); } else { // For our purposes, treating null object as NIL is the right thing to do const Variant &a = p_a.get_type() == Variant::OBJECT && (Object *)p_a == nullptr ? Variant() : p_a; const Variant &b = p_b.get_type() == Variant::OBJECT && (Object *)p_b == nullptr ? Variant() : p_b; return !a.deep_equal(b); } } Variant PropertyUtils::get_property_default_value(const Object *p_object, const StringName &p_property, bool *r_is_valid, const Vector<SceneState::PackState> *p_states_stack_cache, bool p_update_exports, const Node *p_owner, bool *r_is_class_default) { // This function obeys the way property values are set when an object is instantiated, // which is the following (the latter wins): // 1. Default value from builtin class // 2. Default value from script exported variable (from the topmost script) // 3. Value overrides from the instantiation/inheritance stack if (r_is_class_default) { *r_is_class_default = false; } if (r_is_valid) { *r_is_valid = false; } Ref<Script> topmost_script; if (const Node *node = Object::cast_to<Node>(p_object)) { // Check inheritance/instantiation ancestors const Vector<SceneState::PackState> &states_stack = p_states_stack_cache ? *p_states_stack_cache : PropertyUtils::get_node_states_stack(node, p_owner); for (int i = 0; i < states_stack.size(); ++i) { const SceneState::PackState &ia = states_stack[i]; bool found = false; Variant value_in_ancestor = ia.state->get_property_value(ia.node, p_property, found); if (found) { if (r_is_valid) { *r_is_valid = true; } return value_in_ancestor; } // Save script for later bool has_script = false; Variant script = ia.state->get_property_value(ia.node, CoreStringNames::get_singleton()->_script, has_script); if (has_script) { Ref<Script> scr = script; if (scr.is_valid()) { topmost_script = scr; } } } } // Let's see what default is set by the topmost script having a default, if any if (topmost_script.is_null()) { topmost_script = p_object->get_script(); } if (topmost_script.is_valid()) { Variant default_value; // Should be called in the editor only and not at runtime, // otherwise it can cause problems because of missing instance state support. if (p_update_exports && Engine::get_singleton()->is_editor_hint()) { topmost_script->update_exports(); } if (topmost_script->get_property_default_value(p_property, default_value)) { if (r_is_valid) { *r_is_valid = true; } return default_value; } } // Fall back to the default from the native class if (r_is_class_default) { *r_is_class_default = true; } // This is saying that properties not registered in the class DB are considered to have a default value of null // (that covers cases like synthetic properties in the style of whatever/0, whatever/1, which may not have a value in any ancestor). if (r_is_valid) { *r_is_valid = true; } return ClassDB::class_get_default_property_value(p_object->get_class_name(), p_property); } // Like SceneState::PackState, but using a raw pointer to avoid the cost of // updating the reference count during the internal work of the functions below namespace { struct _FastPackState { SceneState *state = nullptr; int node = -1; }; } // namespace static bool _collect_inheritance_chain(const Ref<SceneState> &p_state, const NodePath &p_path, LocalVector<_FastPackState> &r_states_stack) { bool found = false; LocalVector<_FastPackState> inheritance_states; Ref<SceneState> state = p_state; while (state.is_valid()) { int node = state->find_node_by_path(p_path); if (node >= 0) { // This one has state for this node inheritance_states.push_back({ state.ptr(), node }); found = true; } state = state->get_base_scene_state(); } for (int i = inheritance_states.size() - 1; i >= 0; --i) { r_states_stack.push_back(inheritance_states[i]); } return found; } Vector<SceneState::PackState> PropertyUtils::get_node_states_stack(const Node *p_node, const Node *p_owner, bool *r_instanced_by_owner) { if (r_instanced_by_owner) { *r_instanced_by_owner = true; } LocalVector<_FastPackState> states_stack; { const Node *owner = p_owner; #ifdef TOOLS_ENABLED if (!p_owner && Engine::get_singleton()->is_editor_hint()) { owner = EditorNode::get_singleton()->get_edited_scene(); } #endif const Node *n = p_node; while (n) { if (n == owner) { const Ref<SceneState> &state = n->get_scene_inherited_state(); if (_collect_inheritance_chain(state, n->get_path_to(p_node), states_stack)) { if (r_instanced_by_owner) { *r_instanced_by_owner = false; } } break; } else if (n->get_filename() != String()) { const Ref<SceneState> &state = n->get_scene_instance_state(); _collect_inheritance_chain(state, n->get_path_to(p_node), states_stack); } n = n->get_owner(); } } // Convert to the proper type for returning, inverting the vector on the go // (it was more convenient to fill the vector in reverse order) Vector<SceneState::PackState> states_stack_ret; { states_stack_ret.resize(states_stack.size()); _FastPackState *ps = states_stack.ptr(); for (int i = states_stack.size() - 1; i >= 0; --i) { states_stack_ret.write[i].state.reference_ptr(ps->state); states_stack_ret.write[i].node = ps->node; ++ps; } } return states_stack_ret; }
/*************************************************************************/ /* property_utils.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "property_utils.h" #include "core/core_string_names.h" #include "core/engine.h" #include "core/local_vector.h" #include "editor/editor_node.h" #include "scene/resources/packed_scene.h" bool PropertyUtils::is_property_value_different(const Variant &p_a, const Variant &p_b) { if (p_a.get_type() == Variant::REAL && p_b.get_type() == Variant::REAL) { //this must be done because, as some scenes save as text, there might be a tiny difference in floats due to numerical error return !Math::is_equal_approx((float)p_a, (float)p_b); } else { // For our purposes, treating null object as NIL is the right thing to do const Variant &a = p_a.get_type() == Variant::OBJECT && (Object *)p_a == nullptr ? Variant() : p_a; const Variant &b = p_b.get_type() == Variant::OBJECT && (Object *)p_b == nullptr ? Variant() : p_b; return !a.deep_equal(b); } } Variant PropertyUtils::get_property_default_value(const Object *p_object, const StringName &p_property, bool *r_is_valid, const Vector<SceneState::PackState> *p_states_stack_cache, bool p_update_exports, const Node *p_owner, bool *r_is_class_default) { // This function obeys the way property values are set when an object is instantiated, // which is the following (the latter wins): // 1. Default value from builtin class // 2. Default value from script exported variable (from the topmost script) // 3. Value overrides from the instantiation/inheritance stack if (r_is_class_default) { *r_is_class_default = false; } if (r_is_valid) { *r_is_valid = false; } Ref<Script> topmost_script; if (const Node *node = Object::cast_to<Node>(p_object)) { // Check inheritance/instantiation ancestors const Vector<SceneState::PackState> &states_stack = p_states_stack_cache ? *p_states_stack_cache : PropertyUtils::get_node_states_stack(node, p_owner); for (int i = 0; i < states_stack.size(); ++i) { const SceneState::PackState &ia = states_stack[i]; bool found = false; Variant value_in_ancestor = ia.state->get_property_value(ia.node, p_property, found); if (found) { if (r_is_valid) { *r_is_valid = true; } return value_in_ancestor; } // Save script for later bool has_script = false; Variant script = ia.state->get_property_value(ia.node, CoreStringNames::get_singleton()->_script, has_script); if (has_script) { Ref<Script> scr = script; if (scr.is_valid()) { topmost_script = scr; } } } } // Let's see what default is set by the topmost script having a default, if any if (topmost_script.is_null()) { topmost_script = p_object->get_script(); } if (topmost_script.is_valid()) { Variant default_value; // Should be called in the editor only and not at runtime, // otherwise it can cause problems because of missing instance state support. if (p_update_exports && Engine::get_singleton()->is_editor_hint()) { topmost_script->update_exports(); } if (topmost_script->get_property_default_value(p_property, default_value)) { if (r_is_valid) { *r_is_valid = true; } return default_value; } } // Fall back to the default from the native class { if (r_is_class_default) { *r_is_class_default = true; } bool valid = false; Variant value = ClassDB::class_get_default_property_value(p_object->get_class_name(), p_property, &valid); if (valid) { if (r_is_valid) { *r_is_valid = true; } return value; } else { // Heuristically check if this is a synthetic property (whatever/0, whatever/1, etc.) // because they are not in the class DB yet must have a default (null). String prop_str = String(p_property); int p = prop_str.rfind("/"); if (p != -1 && p < prop_str.length() - 1) { bool all_digits = true; for (int i = p + 1; i < prop_str.length(); i++) { if (prop_str[i] < '0' || prop_str[i] > '9') { all_digits = false; break; } } if (r_is_valid) { *r_is_valid = all_digits; } } return Variant(); } } } // Like SceneState::PackState, but using a raw pointer to avoid the cost of // updating the reference count during the internal work of the functions below namespace { struct _FastPackState { SceneState *state = nullptr; int node = -1; }; } // namespace static bool _collect_inheritance_chain(const Ref<SceneState> &p_state, const NodePath &p_path, LocalVector<_FastPackState> &r_states_stack) { bool found = false; LocalVector<_FastPackState> inheritance_states; Ref<SceneState> state = p_state; while (state.is_valid()) { int node = state->find_node_by_path(p_path); if (node >= 0) { // This one has state for this node inheritance_states.push_back({ state.ptr(), node }); found = true; } state = state->get_base_scene_state(); } for (int i = inheritance_states.size() - 1; i >= 0; --i) { r_states_stack.push_back(inheritance_states[i]); } return found; } Vector<SceneState::PackState> PropertyUtils::get_node_states_stack(const Node *p_node, const Node *p_owner, bool *r_instanced_by_owner) { if (r_instanced_by_owner) { *r_instanced_by_owner = true; } LocalVector<_FastPackState> states_stack; { const Node *owner = p_owner; #ifdef TOOLS_ENABLED if (!p_owner && Engine::get_singleton()->is_editor_hint()) { owner = EditorNode::get_singleton()->get_edited_scene(); } #endif const Node *n = p_node; while (n) { if (n == owner) { const Ref<SceneState> &state = n->get_scene_inherited_state(); if (_collect_inheritance_chain(state, n->get_path_to(p_node), states_stack)) { if (r_instanced_by_owner) { *r_instanced_by_owner = false; } } break; } else if (n->get_filename() != String()) { const Ref<SceneState> &state = n->get_scene_instance_state(); _collect_inheritance_chain(state, n->get_path_to(p_node), states_stack); } n = n->get_owner(); } } // Convert to the proper type for returning, inverting the vector on the go // (it was more convenient to fill the vector in reverse order) Vector<SceneState::PackState> states_stack_ret; { states_stack_ret.resize(states_stack.size()); _FastPackState *ps = states_stack.ptr(); for (int i = states_stack.size() - 1; i >= 0; --i) { states_stack_ret.write[i].state.reference_ptr(ps->state); states_stack_ret.write[i].node = ps->node; ++ps; } } return states_stack_ret; }
Fix too broad assumption of null property defaults
Fix too broad assumption of null property defaults (cherry picked from commit 7a66af274ab743a6045a72269e3f616254478c7a)
C++
mit
ex/godot,ex/godot,ex/godot,ex/godot,ex/godot,ex/godot,ex/godot,ex/godot
fbb3f27712aad7cf6e12bf5b317dfedb390c711e
src/optimisationProblem/blackBoxOptimisationBenchmark2009.cpp
src/optimisationProblem/blackBoxOptimisationBenchmark2009.cpp
#include <mantella_bits/optimisationProblem/blackBoxOptimisationBenchmark2009.hpp> // C++ Standard Library #include <algorithm> #include <cmath> #include <random> // Mantella #include <mantella_bits/helper/rng.hpp> #include <mantella_bits/helper/random.hpp> namespace mant { namespace bbob2009 { BlackBoxOptimisationBenchmark2009::BlackBoxOptimisationBenchmark2009( const unsigned int& numberOfDimensions) noexcept : OptimisationProblem<double>(numberOfDimensions) { setLowerBounds(arma::zeros<arma::Col<double>>(numberOfDimensions_) - 5.0); setUpperBounds(arma::zeros<arma::Col<double>>(numberOfDimensions_) + 5.0); setObjectiveValueTranslation(std::min(1000.0, std::max(-1000.0, std::cauchy_distribution<double>(0.0, 100.0)(Rng::generator)))); // TODO Check value within the paper setAcceptableObjectiveValue(objectiveValueTranslation_ + 1.0e-3); arma::Col<double> translation = arma::floor(arma::randu<arma::Col<double>>(numberOfDimensions_) * 1.0e4) / 1.0e4 * 8.0 - 4.0; translation.elem(arma::find(translation == 0)).fill(-1.0e5); setTranslation(translation); setOne(arma::zeros<arma::Col<double>>(numberOfDimensions_) + (std::bernoulli_distribution(0.5)(Rng::generator) ? 1.0 : -1.0)); setRotationR(getRandomRotationMatrix(numberOfDimensions_)); setRotationQ(getRandomRotationMatrix(numberOfDimensions_)); setDeltaC101(getRandomDeltaC101()); setLocalOptimaY101(getRandomLocalOptimaY101()); setDeltaC21(getRandomDeltaC21()); setLocalOptimaY21(getRandomLocalOptimaY21()); } void BlackBoxOptimisationBenchmark2009::setTranslation( const arma::Col<double>& translation) { if (translation.n_elem != numberOfDimensions_) { throw std::logic_error("The number of dimensions of the translation (" + std::to_string(translation.n_elem) + ") must match the number of dimensions of the optimisation problem (" + std::to_string(numberOfDimensions_) + ")."); } translation_ = translation; } void BlackBoxOptimisationBenchmark2009::setOne( const arma::Col<double>& one) { if (one.n_elem != numberOfDimensions_) { throw std::logic_error("The number of dimensions of the one vector (" + std::to_string(one.n_elem) + ") must match the number of dimensions of the optimisation problem (" + std::to_string(numberOfDimensions_) + ")."); } one_ = one; } void BlackBoxOptimisationBenchmark2009::setRotationR( const arma::Mat<double>& rotationR) { if (!rotationR.is_square()) { throw std::logic_error("The rotation matrix (" + std::to_string(rotationR.n_rows) + ", " + std::to_string(rotationR.n_cols) + ") must be square."); } else if (rotationR.n_rows != numberOfDimensions_) { throw std::logic_error("The number of dimensions of the parameter rotation maxtrix (" + std::to_string(rotationR.n_rows) + ", " + std::to_string(rotationR.n_cols) + ") must match the number of dimensions of the optimisation problem (" + std::to_string(numberOfDimensions_) + ")."); } else if(arma::any(arma::vectorise(arma::abs(rotationR.i() - rotationR.t()) > 1.0e-12 * std::max(1.0, std::abs(arma::median(arma::vectorise(rotationR))))))) { throw std::logic_error("The rotation matrix must be orthonormal."); } else if(std::abs(std::abs(arma::det(rotationR)) - 1.0) > 1.0e-12) { throw std::logic_error("The rotation matrix's determinant (" + std::to_string(arma::det(rotationR)) + ") must be either 1 or -1."); } rotationR_ = rotationR; } void BlackBoxOptimisationBenchmark2009::setRotationQ( const arma::Mat<double>& rotationQ) { if (!rotationQ.is_square()) { throw std::logic_error("The rotation matrix (" + std::to_string(rotationQ.n_rows) + ", " + std::to_string(rotationQ.n_cols) + ") must be square."); } else if (rotationQ.n_rows != numberOfDimensions_) { throw std::logic_error("The number of dimensions of the parameter rotation maxtrix (" + std::to_string(rotationQ.n_rows) + ", " + std::to_string(rotationQ.n_cols) + ") must match the number of dimensions of the optimisation problem (" + std::to_string(numberOfDimensions_) + ")."); } else if(arma::any(arma::vectorise(arma::abs(rotationQ.i() - rotationQ.t()) > 1.0e-12 * std::max(1.0, std::abs(arma::median(arma::vectorise(rotationQ))))))) { throw std::logic_error("The rotation matrix must be orthonormal."); } else if(std::abs(std::abs(arma::det(rotationQ)) - 1.0) > 1.0e-12) { throw std::logic_error("The rotation matrix's determinant (" + std::to_string(arma::det(rotationQ)) + ") must be either 1 or -1."); } rotationQ_ = rotationQ; } void BlackBoxOptimisationBenchmark2009::setDeltaC101( const arma::Mat<double>& deltaC101) { if (deltaC101.n_rows != numberOfDimensions_) { throw std::logic_error("The number of dimensions of each delta (" + std::to_string(deltaC101.n_rows) + ") must match the number of dimensions of the optimisation problem (" + std::to_string(numberOfDimensions_) + ")."); } else if (deltaC101.n_cols != 101) { throw std::logic_error("The number of deltas (" + std::to_string(deltaC101.n_cols) + ") must be 101."); } deltaC101_ = deltaC101; } void BlackBoxOptimisationBenchmark2009::setLocalOptimaY101( const arma::Mat<double>& localOptimaY101) { if (localOptimaY101.n_rows != numberOfDimensions_) { throw std::logic_error("The number of dimensions of each local optimum (" + std::to_string(localOptimaY101.n_rows) + ") must match the number of dimensions of the optimisation problem (" + std::to_string(numberOfDimensions_) + ")."); } else if (localOptimaY101.n_cols != 101) { throw std::logic_error("The number of local optima (" + std::to_string(localOptimaY101.n_cols) + ") must be 101."); } localOptimaY101_ = localOptimaY101; } void BlackBoxOptimisationBenchmark2009::setDeltaC21( const arma::Mat<double>& deltaC21) { if (deltaC21.n_rows != numberOfDimensions_) { throw std::logic_error("The number of dimensions of each delta (" + std::to_string(deltaC21.n_rows) + ") must match the number of dimensions of the optimisation problem (" + std::to_string(numberOfDimensions_) + ")."); } else if (deltaC21.n_cols != 21) { throw std::logic_error("The number of deltas (" + std::to_string(deltaC21.n_cols) + ") must be 21."); } deltaC21_ = deltaC21; } void BlackBoxOptimisationBenchmark2009::setLocalOptimaY21( const arma::Mat<double>& localOptimaY21) { if (localOptimaY21.n_rows != numberOfDimensions_) { throw std::logic_error("The number of dimensions of each local optimum (" + std::to_string(localOptimaY21.n_rows) + ") must match the number of dimensions of the optimisation problem (" + std::to_string(numberOfDimensions_) + ")."); } else if (localOptimaY21.n_cols != 21) { throw std::logic_error("The number of local optima (" + std::to_string(localOptimaY21.n_cols) + ") must be 21."); } localOptimaY21_ = localOptimaY21; } arma::Mat<double> BlackBoxOptimisationBenchmark2009::getRandomDeltaC101() const noexcept { arma::Mat<double> deltaC101(numberOfDimensions_, 101); deltaC101.col(0) = getScaling(std::sqrt(1000.0)) / std::pow(1000.0, 0.25); std::uniform_int_distribution<unsigned int> uniformIntDistribution(0, 99); for (std::size_t n = 1; n < deltaC101.n_cols; ++n) { deltaC101.col(n) = getScaling(sqrt(1000.0)) / pow(pow(1000.0, 2.0 * static_cast<double>(uniformIntDistribution(Rng::generator)) / 99.0), 0.25); } return deltaC101; } arma::Mat<double> BlackBoxOptimisationBenchmark2009::getRandomDeltaC21() const noexcept { arma::Mat<double> deltaC21(numberOfDimensions_, 21); deltaC21.col(0) = getScaling(std::sqrt(1000.0)) / std::pow(1000.0, 0.25); std::uniform_int_distribution<unsigned int> uniformIntDistribution(0, 19); for (std::size_t n = 1; n < deltaC21.n_cols; ++n) { deltaC21.col(n) = getScaling(sqrt(1000.0)) / std::pow(std::pow(1000.0, 2.0 * static_cast<double>(uniformIntDistribution(Rng::generator)) / 19.0), 0.25); } return deltaC21; } arma::Mat<double> BlackBoxOptimisationBenchmark2009::getRandomLocalOptimaY101() const noexcept { arma::Mat<double> localOptimaY101 = arma::randu<arma::Mat<double>>(numberOfDimensions_, 101) * 8.0 - 4.0; localOptimaY101.col(0) = 0.8 * localOptimaY101.col(0); return localOptimaY101; } arma::Mat<double> BlackBoxOptimisationBenchmark2009::getRandomLocalOptimaY21() const noexcept { arma::Mat<double> localOptimaY21 = arma::randu<arma::Mat<double>>(numberOfDimensions_, 21) * 9.8 - 4.9; localOptimaY21.col(0) = 0.8 * localOptimaY21.col(0); return localOptimaY21; } arma::Col<double> BlackBoxOptimisationBenchmark2009::getScaling( const double& condition) const noexcept { arma::Col<double> scaling = arma::linspace<arma::Col<double>>(0.0, 1.0, numberOfDimensions_); for (auto& scale : scaling) { scale = std::pow(condition, scale); } return scaling; } arma::Col<double> BlackBoxOptimisationBenchmark2009::getScaling( const arma::Col<double>& condition) const noexcept { arma::Col<double> scaling = arma::linspace<arma::Col<double>>(0.0, 1.0, numberOfDimensions_); for (std::size_t n = 0; n < scaling.n_elem; ++n) { scaling.at(n) = std::pow(condition.at(n), scaling.at(n)); } return scaling; } arma::Col<double> BlackBoxOptimisationBenchmark2009::getAsymmetricTransformation( const double& beta, const arma::Col<double>& parameter) const noexcept { arma::Col<double> asymmetricTransformation(parameter.n_elem); const arma::Col<double>& spacing = arma::linspace<arma::Col<double>>(0.0, 1.0, numberOfDimensions_); for (std::size_t n = 0; n < parameter.n_elem; ++n) { const double& value = parameter.at(n); if (value > 0.0) { asymmetricTransformation.at(n) = std::pow(value, 1 + beta * spacing.at(n) * std::sqrt(value)); } else { asymmetricTransformation.at(n) = value; } } return asymmetricTransformation; } double BlackBoxOptimisationBenchmark2009::getOscillationTransformation( const double& value) const noexcept { if (value != 0.0) { double c1; double c2; if (value > 0.0) { c1 = 10.0; c2 = 7.9; } else { c1 = 5.5; c2 = 3.1; } const double& x = std::log(std::abs(value)); return std::copysign(1.0, value) * std::exp(x + 0.049 * (std::sin(c1 * x) + std::sin(c2 * x))); } else { return 0.0; } } arma::Col<double> BlackBoxOptimisationBenchmark2009::getOscillationTransformation( const arma::Col<double>& parameter) const noexcept { arma::Col<double> oscillate(parameter.n_elem); for (std::size_t n = 0; n < parameter.n_elem; ++n) { oscillate.at(n) = getOscillationTransformation(parameter.at(n)); } return oscillate; } double BlackBoxOptimisationBenchmark2009::getPenality( const arma::Col<double>& parameter) const noexcept { double penality = 0.0; for (std::size_t n = 0; n < parameter.n_elem; ++n) { penality += std::pow(std::max(0.0, std::abs(parameter.at(n)) - 5.0), 2.0); } return penality; } } }
#include <mantella_bits/optimisationProblem/blackBoxOptimisationBenchmark2009.hpp> // C++ Standard Library #include <algorithm> #include <cmath> #include <random> // Mantella #include <mantella_bits/helper/rng.hpp> #include <mantella_bits/helper/random.hpp> namespace mant { namespace bbob2009 { BlackBoxOptimisationBenchmark2009::BlackBoxOptimisationBenchmark2009( const unsigned int& numberOfDimensions) noexcept : OptimisationProblem<double>(numberOfDimensions) { setLowerBounds(arma::zeros<arma::Col<double>>(numberOfDimensions_) - 5.0); setUpperBounds(arma::zeros<arma::Col<double>>(numberOfDimensions_) + 5.0); setObjectiveValueTranslation(std::min(1000.0, std::max(-1000.0, std::cauchy_distribution<double>(0.0, 100.0)(Rng::generator)))); setAcceptableObjectiveValue(objectiveValueTranslation_ + 1.0e-8); arma::Col<double> translation = arma::floor(arma::randu<arma::Col<double>>(numberOfDimensions_) * 1.0e4) / 1.0e4 * 8.0 - 4.0; translation.elem(arma::find(translation == 0)).fill(-1.0e5); setTranslation(translation); setOne(arma::zeros<arma::Col<double>>(numberOfDimensions_) + (std::bernoulli_distribution(0.5)(Rng::generator) ? 1.0 : -1.0)); setRotationR(getRandomRotationMatrix(numberOfDimensions_)); setRotationQ(getRandomRotationMatrix(numberOfDimensions_)); setDeltaC101(getRandomDeltaC101()); setLocalOptimaY101(getRandomLocalOptimaY101()); setDeltaC21(getRandomDeltaC21()); setLocalOptimaY21(getRandomLocalOptimaY21()); } void BlackBoxOptimisationBenchmark2009::setTranslation( const arma::Col<double>& translation) { if (translation.n_elem != numberOfDimensions_) { throw std::logic_error("The number of dimensions of the translation (" + std::to_string(translation.n_elem) + ") must match the number of dimensions of the optimisation problem (" + std::to_string(numberOfDimensions_) + ")."); } translation_ = translation; } void BlackBoxOptimisationBenchmark2009::setOne( const arma::Col<double>& one) { if (one.n_elem != numberOfDimensions_) { throw std::logic_error("The number of dimensions of the one vector (" + std::to_string(one.n_elem) + ") must match the number of dimensions of the optimisation problem (" + std::to_string(numberOfDimensions_) + ")."); } one_ = one; } void BlackBoxOptimisationBenchmark2009::setRotationR( const arma::Mat<double>& rotationR) { if (!rotationR.is_square()) { throw std::logic_error("The rotation matrix (" + std::to_string(rotationR.n_rows) + ", " + std::to_string(rotationR.n_cols) + ") must be square."); } else if (rotationR.n_rows != numberOfDimensions_) { throw std::logic_error("The number of dimensions of the parameter rotation maxtrix (" + std::to_string(rotationR.n_rows) + ", " + std::to_string(rotationR.n_cols) + ") must match the number of dimensions of the optimisation problem (" + std::to_string(numberOfDimensions_) + ")."); } else if(arma::any(arma::vectorise(arma::abs(rotationR.i() - rotationR.t()) > 1.0e-12 * std::max(1.0, std::abs(arma::median(arma::vectorise(rotationR))))))) { throw std::logic_error("The rotation matrix must be orthonormal."); } else if(std::abs(std::abs(arma::det(rotationR)) - 1.0) > 1.0e-12) { throw std::logic_error("The rotation matrix's determinant (" + std::to_string(arma::det(rotationR)) + ") must be either 1 or -1."); } rotationR_ = rotationR; } void BlackBoxOptimisationBenchmark2009::setRotationQ( const arma::Mat<double>& rotationQ) { if (!rotationQ.is_square()) { throw std::logic_error("The rotation matrix (" + std::to_string(rotationQ.n_rows) + ", " + std::to_string(rotationQ.n_cols) + ") must be square."); } else if (rotationQ.n_rows != numberOfDimensions_) { throw std::logic_error("The number of dimensions of the parameter rotation maxtrix (" + std::to_string(rotationQ.n_rows) + ", " + std::to_string(rotationQ.n_cols) + ") must match the number of dimensions of the optimisation problem (" + std::to_string(numberOfDimensions_) + ")."); } else if(arma::any(arma::vectorise(arma::abs(rotationQ.i() - rotationQ.t()) > 1.0e-12 * std::max(1.0, std::abs(arma::median(arma::vectorise(rotationQ))))))) { throw std::logic_error("The rotation matrix must be orthonormal."); } else if(std::abs(std::abs(arma::det(rotationQ)) - 1.0) > 1.0e-12) { throw std::logic_error("The rotation matrix's determinant (" + std::to_string(arma::det(rotationQ)) + ") must be either 1 or -1."); } rotationQ_ = rotationQ; } void BlackBoxOptimisationBenchmark2009::setDeltaC101( const arma::Mat<double>& deltaC101) { if (deltaC101.n_rows != numberOfDimensions_) { throw std::logic_error("The number of dimensions of each delta (" + std::to_string(deltaC101.n_rows) + ") must match the number of dimensions of the optimisation problem (" + std::to_string(numberOfDimensions_) + ")."); } else if (deltaC101.n_cols != 101) { throw std::logic_error("The number of deltas (" + std::to_string(deltaC101.n_cols) + ") must be 101."); } deltaC101_ = deltaC101; } void BlackBoxOptimisationBenchmark2009::setLocalOptimaY101( const arma::Mat<double>& localOptimaY101) { if (localOptimaY101.n_rows != numberOfDimensions_) { throw std::logic_error("The number of dimensions of each local optimum (" + std::to_string(localOptimaY101.n_rows) + ") must match the number of dimensions of the optimisation problem (" + std::to_string(numberOfDimensions_) + ")."); } else if (localOptimaY101.n_cols != 101) { throw std::logic_error("The number of local optima (" + std::to_string(localOptimaY101.n_cols) + ") must be 101."); } localOptimaY101_ = localOptimaY101; } void BlackBoxOptimisationBenchmark2009::setDeltaC21( const arma::Mat<double>& deltaC21) { if (deltaC21.n_rows != numberOfDimensions_) { throw std::logic_error("The number of dimensions of each delta (" + std::to_string(deltaC21.n_rows) + ") must match the number of dimensions of the optimisation problem (" + std::to_string(numberOfDimensions_) + ")."); } else if (deltaC21.n_cols != 21) { throw std::logic_error("The number of deltas (" + std::to_string(deltaC21.n_cols) + ") must be 21."); } deltaC21_ = deltaC21; } void BlackBoxOptimisationBenchmark2009::setLocalOptimaY21( const arma::Mat<double>& localOptimaY21) { if (localOptimaY21.n_rows != numberOfDimensions_) { throw std::logic_error("The number of dimensions of each local optimum (" + std::to_string(localOptimaY21.n_rows) + ") must match the number of dimensions of the optimisation problem (" + std::to_string(numberOfDimensions_) + ")."); } else if (localOptimaY21.n_cols != 21) { throw std::logic_error("The number of local optima (" + std::to_string(localOptimaY21.n_cols) + ") must be 21."); } localOptimaY21_ = localOptimaY21; } arma::Mat<double> BlackBoxOptimisationBenchmark2009::getRandomDeltaC101() const noexcept { arma::Mat<double> deltaC101(numberOfDimensions_, 101); deltaC101.col(0) = getScaling(std::sqrt(1000.0)) / std::pow(1000.0, 0.25); std::uniform_int_distribution<unsigned int> uniformIntDistribution(0, 99); for (std::size_t n = 1; n < deltaC101.n_cols; ++n) { deltaC101.col(n) = getScaling(sqrt(1000.0)) / pow(pow(1000.0, 2.0 * static_cast<double>(uniformIntDistribution(Rng::generator)) / 99.0), 0.25); } return deltaC101; } arma::Mat<double> BlackBoxOptimisationBenchmark2009::getRandomDeltaC21() const noexcept { arma::Mat<double> deltaC21(numberOfDimensions_, 21); deltaC21.col(0) = getScaling(std::sqrt(1000.0)) / std::pow(1000.0, 0.25); std::uniform_int_distribution<unsigned int> uniformIntDistribution(0, 19); for (std::size_t n = 1; n < deltaC21.n_cols; ++n) { deltaC21.col(n) = getScaling(sqrt(1000.0)) / std::pow(std::pow(1000.0, 2.0 * static_cast<double>(uniformIntDistribution(Rng::generator)) / 19.0), 0.25); } return deltaC21; } arma::Mat<double> BlackBoxOptimisationBenchmark2009::getRandomLocalOptimaY101() const noexcept { arma::Mat<double> localOptimaY101 = arma::randu<arma::Mat<double>>(numberOfDimensions_, 101) * 8.0 - 4.0; localOptimaY101.col(0) = 0.8 * localOptimaY101.col(0); return localOptimaY101; } arma::Mat<double> BlackBoxOptimisationBenchmark2009::getRandomLocalOptimaY21() const noexcept { arma::Mat<double> localOptimaY21 = arma::randu<arma::Mat<double>>(numberOfDimensions_, 21) * 9.8 - 4.9; localOptimaY21.col(0) = 0.8 * localOptimaY21.col(0); return localOptimaY21; } arma::Col<double> BlackBoxOptimisationBenchmark2009::getScaling( const double& condition) const noexcept { arma::Col<double> scaling = arma::linspace<arma::Col<double>>(0.0, 1.0, numberOfDimensions_); for (auto& scale : scaling) { scale = std::pow(condition, scale); } return scaling; } arma::Col<double> BlackBoxOptimisationBenchmark2009::getScaling( const arma::Col<double>& condition) const noexcept { arma::Col<double> scaling = arma::linspace<arma::Col<double>>(0.0, 1.0, numberOfDimensions_); for (std::size_t n = 0; n < scaling.n_elem; ++n) { scaling.at(n) = std::pow(condition.at(n), scaling.at(n)); } return scaling; } arma::Col<double> BlackBoxOptimisationBenchmark2009::getAsymmetricTransformation( const double& beta, const arma::Col<double>& parameter) const noexcept { arma::Col<double> asymmetricTransformation(parameter.n_elem); const arma::Col<double>& spacing = arma::linspace<arma::Col<double>>(0.0, 1.0, numberOfDimensions_); for (std::size_t n = 0; n < parameter.n_elem; ++n) { const double& value = parameter.at(n); if (value > 0.0) { asymmetricTransformation.at(n) = std::pow(value, 1 + beta * spacing.at(n) * std::sqrt(value)); } else { asymmetricTransformation.at(n) = value; } } return asymmetricTransformation; } double BlackBoxOptimisationBenchmark2009::getOscillationTransformation( const double& value) const noexcept { if (value != 0.0) { double c1; double c2; if (value > 0.0) { c1 = 10.0; c2 = 7.9; } else { c1 = 5.5; c2 = 3.1; } const double& x = std::log(std::abs(value)); return std::copysign(1.0, value) * std::exp(x + 0.049 * (std::sin(c1 * x) + std::sin(c2 * x))); } else { return 0.0; } } arma::Col<double> BlackBoxOptimisationBenchmark2009::getOscillationTransformation( const arma::Col<double>& parameter) const noexcept { arma::Col<double> oscillate(parameter.n_elem); for (std::size_t n = 0; n < parameter.n_elem; ++n) { oscillate.at(n) = getOscillationTransformation(parameter.at(n)); } return oscillate; } double BlackBoxOptimisationBenchmark2009::getPenality( const arma::Col<double>& parameter) const noexcept { double penality = 0.0; for (std::size_t n = 0; n < parameter.n_elem; ++n) { penality += std::pow(std::max(0.0, std::abs(parameter.at(n)) - 5.0), 2.0); } return penality; } } }
Set acceptable solution threshold according to the BBOB
devel: Set acceptable solution threshold according to the BBOB
C++
mit
SebastianNiemann/Mantella,Mantella/Mantella,SebastianNiemann/Mantella,SebastianNiemann/Mantella,Mantella/Mantella,Mantella/Mantella
8945af1042b00aa702ab79472b5d3af1f8900ee7
applications.cpp
applications.cpp
#include "applications.h" #include <QDir> #include <qdebug.h> const int Applications::NameRole = Qt::UserRole + 1; const int Applications::IconRole = Qt::UserRole + 2; const int Applications::ExecRole = Qt::UserRole + 3; const int Applications::TerminalRole = Qt::UserRole + 4; Applications::Applications(QObject *parent) : QAbstractListModel(parent) { connect(&m_parserThreadWatcher, SIGNAL(finished()), this, SLOT(parseFinished())); m_parserRunning = true; m_parserThread = QtConcurrent::run(this, &Applications::parseApplications); m_parserThreadWatcher.setFuture(m_parserThread); } Applications::~Applications() { if (m_parserThread.isRunning()) m_parserThread.cancel(); qDeleteAll(this->m_internalData); } void Applications::parseApplications() { this->m_files.append(this->readFolder(QDir::homePath() + APPLICATIONS_LOCAL_PATH)); this->m_files.append(this->readFolder(APPLICATIONS_PATH)); foreach(QString file, this->m_files) { DesktopFile* app = new DesktopFile(file); if (!app->noDisplay() && !app->terminal() && !app->isHidden()) { // qDebug() << "Adding application: " << app->name(); m_internalData.append(app); } } this->m_files.clear(); } QStringList Applications::readFolder(QString folder) { QDir dir(folder); QFileInfoList file_list = dir.entryInfoList( QStringList(APPLICATIONS_FILES), QDir::Files | QDir::Readable); QStringList files; foreach(QFileInfo file, file_list) { if (this->m_files.filter(file.fileName()).count() == 0) { files.append(file.absoluteFilePath()); } } return files; } void Applications::add(DesktopFile *item) { beginInsertRows(QModelIndex(), m_data.size(), m_data.size()); m_data.append(item); endInsertRows(); emit countChanged(m_data.size()); } void Applications::sortApps() { std::sort(this->m_data.begin(), this->m_data.end(), [](const DesktopFile* left, const DesktopFile* right) -> bool { return QString::compare(left->name(),right->name(), Qt::CaseInsensitive) < 0; }); } DesktopFile* Applications::get(int index) const { return m_data.at(index); } void Applications::filter(QString search) { if (m_parserRunning) return; beginRemoveRows(QModelIndex(), 0, m_data.size()); m_data.clear(); endRemoveRows(); foreach(DesktopFile* file, m_internalData) { if(file->name().contains(search,Qt::CaseInsensitive) || file->comment().contains(search, Qt::CaseInsensitive) || file->exec().contains(search, Qt::CaseInsensitive)) { this->add(file); } } this->sortApps(); } int Applications::rowCount(const QModelIndex &) const { return m_data.count(); } QVariant Applications::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); if (index.row() > (m_data.size()-1) ) return QVariant(); DesktopFile* obj = m_data.at(index.row()); switch(role) { case Qt::DisplayRole: case NameRole: return QVariant::fromValue(obj->name()); break; case IconRole: return QVariant::fromValue(obj->icon()); case ExecRole: return QVariant::fromValue(obj->exec()); case TerminalRole: return QVariant::fromValue(obj->terminal()); default: return QVariant(); } } QHash<int, QByteArray> Applications::roleNames() const { QHash<int, QByteArray> roles = QAbstractListModel::roleNames(); roles.insert(NameRole, QByteArray("name")); roles.insert(IconRole, QByteArray("icon")); roles.insert(ExecRole, QByteArray("exec")); roles.insert(TerminalRole, QByteArray("terminal")); return roles; } void Applications::parseFinished() { m_parserRunning = false; this->filter(""); emit ready(); }
#include "applications.h" #include <QDir> #include <qdebug.h> const int Applications::NameRole = Qt::UserRole + 1; const int Applications::IconRole = Qt::UserRole + 2; const int Applications::ExecRole = Qt::UserRole + 3; const int Applications::TerminalRole = Qt::UserRole + 4; Applications::Applications(QObject *parent) : QAbstractListModel(parent) { connect(&m_parserThreadWatcher, SIGNAL(finished()), this, SLOT(parseFinished())); m_parserRunning = true; m_parserThread = QtConcurrent::run(this, &Applications::parseApplications); m_parserThreadWatcher.setFuture(m_parserThread); } Applications::~Applications() { if (m_parserThread.isRunning()) m_parserThread.cancel(); qDeleteAll(this->m_internalData); } void Applications::parseApplications() { this->m_files.append(this->readFolder(QDir::homePath() + APPLICATIONS_LOCAL_PATH)); this->m_files.append(this->readFolder(APPLICATIONS_PATH)); foreach(QString file, this->m_files) { DesktopFile* app = new DesktopFile(file); if (!app->noDisplay() && !app->terminal() && !app->isHidden()) { // qDebug() << "Found application: " << app->name(); m_internalData.append(app); } } this->m_files.clear(); } QStringList Applications::readFolder(QString folder) { QDir dir(folder); QFileInfoList file_list = dir.entryInfoList( QStringList(APPLICATIONS_FILES), QDir::Files | QDir::Readable); QStringList files; foreach(QFileInfo file, file_list) { if (this->m_files.filter(file.fileName()).count() == 0) { files.append(file.absoluteFilePath()); } } return files; } void Applications::add(DesktopFile *item) { beginInsertRows(QModelIndex(), m_data.size(), m_data.size()); m_data.append(item); endInsertRows(); emit countChanged(m_data.size()); } void Applications::sortApps() { std::sort(this->m_data.begin(), this->m_data.end(), [](const DesktopFile* left, const DesktopFile* right) -> bool { return QString::compare(left->name(),right->name(), Qt::CaseInsensitive) < 0; }); } DesktopFile* Applications::get(int index) const { return m_data.at(index); } void Applications::filter(QString search) { if (m_parserRunning) return; beginRemoveRows(QModelIndex(), 0, m_data.size()); m_data.clear(); endRemoveRows(); foreach(DesktopFile* file, m_internalData) { if(file->name().contains(search,Qt::CaseInsensitive) || file->comment().contains(search, Qt::CaseInsensitive) || file->exec().contains(search, Qt::CaseInsensitive)) { this->add(file); } } this->sortApps(); } int Applications::rowCount(const QModelIndex &) const { return m_data.count(); } QVariant Applications::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); if (index.row() > (m_data.size()-1) ) return QVariant(); DesktopFile* obj = m_data.at(index.row()); switch(role) { case Qt::DisplayRole: case NameRole: return QVariant::fromValue(obj->name()); break; case IconRole: return QVariant::fromValue(obj->icon()); case ExecRole: return QVariant::fromValue(obj->exec()); case TerminalRole: return QVariant::fromValue(obj->terminal()); default: return QVariant(); } } QHash<int, QByteArray> Applications::roleNames() const { QHash<int, QByteArray> roles = QAbstractListModel::roleNames(); roles.insert(NameRole, QByteArray("name")); roles.insert(IconRole, QByteArray("icon")); roles.insert(ExecRole, QByteArray("exec")); roles.insert(TerminalRole, QByteArray("terminal")); return roles; } void Applications::parseFinished() { // qDebug() << "Parser finished"; m_parserRunning = false; this->filter(""); emit ready(); }
Debug notes
Debug notes
C++
mit
bayi/qdmenu,bayi/qdmenu,bayi/qdmenu
e00c6f0cdb1cc2b83cd0e4d05d3f695549d53d11
common/include/htu21d.hpp
common/include/htu21d.hpp
#pragma once #include <stdint.h> #include <avr/cpufunc.h> #include <avr/sleep.h> #include <i2c.hpp> #include <common.hpp> // port state terminology: // low - output/low // high - output/high // input - input will pull-up class IHTU21D { public: virtual bool reset() = 0; virtual bool read_temp(uint16_t& temp) = 0; virtual bool read_hum(uint16_t& hum) = 0; }; template <typename CL_t, typename DA_t> class HTU21D : public IHTU21D { public: typedef CL_t CL; typedef DA_t DA; typedef I2C<CL_t, DA_t> i2c; virtual bool reset(); virtual bool read_temp(uint16_t& temp); virtual bool read_hum(uint16_t& hum); private: static bool _reset(); static bool _read(uint8_t cmd, uint16_t& m); }; template <typename CL_t, typename DA_t> bool HTU21D<CL_t, DA_t>::reset() { i2c::start(); i2c::stop(); i2c::start(); bool ret = _reset(); i2c::stop(); return ret; } template <typename CL_t, typename DA_t> inline bool HTU21D<CL_t, DA_t>::read_temp(uint16_t& temp) { bool ret; i2c::start(); ret = _read(0xe3, temp); i2c::stop(); if (ret == false) return false; temp >>= 2; return true; } template <typename CL_t, typename DA_t> inline bool HTU21D<CL_t, DA_t>::read_hum(uint16_t& hum) { bool ret; i2c::start(); ret = _read(0xe5, hum); i2c::stop(); if (ret == false) return false; hum >>= 4; return true; } template <typename CL_t, typename DA_t> bool HTU21D<CL_t, DA_t>::_reset() { if (!i2c::send_byte(0x80)) return false; if (!i2c::send_byte(0xe6)) return false; if (!i2c::send_byte(0x02)) return false; i2c::stop(); _NOP(); i2c::start(); if (!i2c::send_byte(0x80)) return false; if (!i2c::send_byte(0xfe)) return false; return true; } template <typename CL_t, typename DA_t> bool HTU21D<CL_t, DA_t>::_read(uint8_t cmd, uint16_t& m) { if (!i2c::send_byte(0x80)) return false; if (!i2c::send_byte(cmd)) return false; i2c::stop(); _NOP(); i2c::start(); if (!i2c::send_byte(0x81)) return false; i2c::CL::set(); PCMSK = _BV(CL::pin); GIMSK |= _BV(PCIE); set_sleep_mode(SLEEP_MODE_PWR_DOWN); sleep_mode(); GIMSK &= ~_BV(PCIE); uint8_t buf[3]; buf[0] = i2c::recv_byte(); buf[1] = i2c::recv_byte(); buf[2] = i2c::recv_byte(true); if (crc8_dallas(0, buf, 2) != buf[2]) return false; m = buf[0] << 8 | buf[1]; return true; }
#pragma once #include <stdint.h> #include <avr/cpufunc.h> #include <avr/sleep.h> #include <i2c.hpp> #include <common.hpp> // port state terminology: // low - output/low // high - output/high // input - input will pull-up class IHTU21D { public: virtual bool reset() = 0; virtual bool read_temp(uint16_t& temp) = 0; virtual bool read_hum(uint16_t& hum) = 0; }; template <typename CL_t, typename DA_t> class HTU21D : public IHTU21D { public: typedef CL_t CL; typedef DA_t DA; typedef I2C<CL_t, DA_t> i2c; virtual bool reset(); virtual bool read_temp(uint16_t& temp); virtual bool read_hum(uint16_t& hum); private: static bool _reset(); static bool _read(uint8_t cmd, uint16_t& m); }; template <typename CL_t, typename DA_t> bool HTU21D<CL_t, DA_t>::reset() { i2c::start(); i2c::stop(); i2c::start(); bool ret = _reset(); i2c::stop(); return ret; } template <typename CL_t, typename DA_t> bool HTU21D<CL_t, DA_t>::read_temp(uint16_t& temp) { bool ret; i2c::start(); ret = _read(0xe3, temp); i2c::stop(); if (ret == false) return false; temp >>= 2; return true; } template <typename CL_t, typename DA_t> bool HTU21D<CL_t, DA_t>::read_hum(uint16_t& hum) { bool ret; i2c::start(); ret = _read(0xe5, hum); i2c::stop(); if (ret == false) return false; hum >>= 4; return true; } template <typename CL_t, typename DA_t> inline bool HTU21D<CL_t, DA_t>::_reset() { if (!i2c::send_byte(0x80)) return false; if (!i2c::send_byte(0xe6)) return false; if (!i2c::send_byte(0x02)) return false; i2c::stop(); _NOP(); i2c::start(); if (!i2c::send_byte(0x80)) return false; if (!i2c::send_byte(0xfe)) return false; return true; } template <typename CL_t, typename DA_t> bool HTU21D<CL_t, DA_t>::_read(uint8_t cmd, uint16_t& m) { if (!i2c::send_byte(0x80)) return false; if (!i2c::send_byte(cmd)) return false; i2c::stop(); _NOP(); i2c::start(); if (!i2c::send_byte(0x81)) return false; i2c::CL::set(); PCMSK = _BV(CL::pin); GIMSK |= _BV(PCIE); set_sleep_mode(SLEEP_MODE_PWR_DOWN); sleep_mode(); GIMSK &= ~_BV(PCIE); uint8_t buf[3]; buf[0] = i2c::recv_byte(); buf[1] = i2c::recv_byte(); buf[2] = i2c::recv_byte(true); if (crc8_dallas(0, buf, 2) != buf[2]) return false; m = buf[0] << 8 | buf[1]; return true; }
correct inline annotations for member functions
htu21d: correct inline annotations for member functions
C++
bsd-3-clause
rkojedzinszky/thermo-sensor,rkojedzinszky/thermo-sensor,rkojedzinszky/thermo-sensor
a69a555ebdb2a48be9b6078f117e2690391bf568
tests/ooo_test.cc
tests/ooo_test.cc
/* Copyright (c) 2015, Max Krasnyansky <[email protected]> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE 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 <stdio.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include <stdlib.h> #include <getopt.h> #include <sys/time.h> #include <sstream> #include <boost/format.hpp> #include "hogl/detail/refcount.hpp" #include "hogl/output-null.hpp" #include "hogl/post.hpp" #include "hogl/area.hpp" #include "hogl/mask.hpp" #include "hogl/platform.hpp" // Test output that verifies seq numbers class test_format : public hogl::format { private: uint64_t _last; uint64_t _ooo; public: test_format() : _last(0), _ooo(0) { } void process(hogl::ostrbuf &sb, const hogl::format::data &d) { uint64_t ts = d.record->timestamp; if (ts < _last) _ooo++; else _last = ts; } unsigned int ooo() const { return _ooo; } }; // Sequence count class sequence { private: uint64_t _count; public: sequence() : _count((uint64_t)0 - 1) {} uint64_t next() { return __sync_add_and_fetch(&_count, 1); } }; sequence global_sequence; // Test engine class test_thread { private: const hogl::area *_log_area; std::string _name; pthread_t _thread; volatile bool _running; volatile bool _killed; bool _failed; unsigned int _ring_capacity; unsigned int _burst_size; unsigned int _interval_usec; unsigned int _nloops; static void *entry(void *_self); void loop(); enum log_sections { INFO }; static const char *_log_sections[]; public: test_thread(const char *name, unsigned int ring_capacity, unsigned int burst_size, unsigned int interval_usec, unsigned int nloops); ~test_thread(); /** * Check if the engine is running */ bool running() const { return _running; } bool failed() const { return _failed; } }; const char *test_thread::_log_sections[] = { "INFO", 0, }; test_thread::test_thread(const char *name, unsigned int ring_capacity, unsigned int burst_size, unsigned int interval_usec, unsigned int nloops) : _name(name), _running(true), _killed(false), _failed(false), _ring_capacity(ring_capacity), _burst_size(burst_size), _interval_usec(interval_usec), _nloops(nloops) { int err; _log_area = hogl::add_area("SORT", _log_sections); if (!_log_area) abort(); err = pthread_create(&_thread, NULL, entry, (void *) this); if (err) { fprintf(stderr, "failed to create test_thread thread. %d\n", err); exit(1); } } test_thread::~test_thread() { _killed = true; pthread_join(_thread, NULL); } void *test_thread::entry(void *_self) { test_thread *self = (test_thread *) _self; hogl::platform::set_thread_title(self->_name.c_str()); // Run the loop self->loop(); return 0; } void test_thread::loop() { _running = true; // Create private thread ring hogl::ringbuf::options ring_opts = { capacity: _ring_capacity, prio: 0 }; hogl::tls tls(_name.c_str(), ring_opts); while (!_killed) { unsigned int i; for (i=0; i < _burst_size; i++) hogl::post_unlocked(_log_area, INFO, global_sequence.next()); _nloops--; if (!_nloops) break; usleep(_interval_usec); } if (tls.ring()->dropcnt()) printf("%s drop count %lu\n", _name.c_str(), (unsigned long) tls.ring()->dropcnt()); _running = false; } // ------- static unsigned int nthreads = 8; static unsigned int ring_capacity = 1024; static unsigned int burst_size = 10; static unsigned int interval_usec = 1000; static unsigned int nloops = 20000; static hogl::engine::options log_eng_opts = hogl::engine::default_options; static std::string log_output("null"); static std::string log_format("basic"); int doTest() { test_thread *thread[nthreads]; unsigned int i; for (i=0; i < nthreads; i++) { char name[100]; sprintf(name, "THREAD%u", i); thread[i] = new test_thread(name, ring_capacity, burst_size, interval_usec, nloops); } while (1) { bool all_dead = true; for (i=0; i < nthreads; i++) { if (thread[i]->running()) all_dead = false; } if (all_dead) break; usleep(10000); } bool failed = false; for (i=0; i < nthreads; i++) { failed |= thread[i]->failed(); delete thread[i]; } return failed ? -1 : 0; } // Command line args { static struct option main_lopts[] = { {"help", 0, 0, 'h'}, {"format", 1, 0, 'f'}, {"output", 1, 0, 'o'}, {"nthreads", 1, 0, 'n'}, {"ring-size", 1, 0, 'r'}, {"burst-size", 1, 0, 'b'}, {"interval", 1, 0, 'i'}, {"nloops", 1, 0, 'l'}, {"notso", 0, 0, 'N'}, {"tso-buffer", 1, 0, 'T'}, {"poll-interval", 1, 0, 'p'}, {0, 0, 0, 0} }; static char main_sopts[] = "hf:o:n:r:b:i:l:p:N:T:"; static char main_help[] = "FurLog stress test 0.1 \n" "Usage:\n" "\tstress_test [options]\n" "Options:\n" "\t--help -h Display help text\n" "\t--format -f <name> Log format (null, basic)\n" "\t--output -o <name> Log output (file name, stderr, or null)\n" "\t--poll-interval -p <N> Engine polling interval (in usec)\n" "\t--nthreads -n <N> Number of threads to start\n" "\t--ring -r <N> Ring size (number of records)\n" "\t--burst -b <N> Burst size (number of records)\n" "\t--interval -i <N> Interval between bursts (in usec)\n" "\t--notso -N Disable timestamp ordering (TSO)\n" "\t--tso-buffer -T <N> TSO buffer size (number of records)\n" "\t--nloops -l <N> Number of loops in each thread\n"; // } int main(int argc, char *argv[]) { int opt; // Parse command line args while ((opt = getopt_long(argc, argv, main_sopts, main_lopts, NULL)) != -1) { switch (opt) { case 'f': log_format = optarg; break; case 'o': log_output = optarg; break; case 'n': nthreads = atoi(optarg); break; case 'r': ring_capacity = atoi(optarg); break; case 'b': burst_size = atoi(optarg); break; case 'i': interval_usec = atoi(optarg); break; case 'l': nloops = atoi(optarg); break; case 'p': log_eng_opts.polling_interval_usec = atoi(optarg); break; case 'N': log_eng_opts.features &= ~hogl::engine::DISABLE_TSO; break; case 'T': log_eng_opts.tso_buffer_capacity = atoi(optarg); break; case 'h': default: printf("%s", main_help); exit(0); } } argc -= optind; argv += optind; if (argc < 0) { printf("%s", main_help); exit(1); } test_format fmt; hogl::output_null lo(fmt); hogl::activate(lo, log_eng_opts); hogl::platform::enable_verbose_coredump(); // Disable everything but our own output to avoid noise hogl::mask m("!.*", "SORT:INFO", 0); hogl::apply_mask(m); int err = doTest(); std::cout << "Engine stats: " << std::endl; std::cout << hogl::default_engine->get_stats(); printf("Number of OOO records %u\n", fmt.ooo()); hogl::deactivate(); if (err < 0 || fmt.ooo()) { printf("Failed\n"); return 1; } printf("Passed\n"); return 0; }
/* Copyright (c) 2015, Max Krasnyansky <[email protected]> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE 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 <stdio.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include <stdlib.h> #include <getopt.h> #include <sys/time.h> #include <sstream> #include <boost/format.hpp> #include "hogl/detail/refcount.hpp" #include "hogl/output-null.hpp" #include "hogl/post.hpp" #include "hogl/area.hpp" #include "hogl/mask.hpp" #include "hogl/platform.hpp" #define SKIP 77 // Test output that verifies seq numbers class test_format : public hogl::format { private: uint64_t _last; uint64_t _ooo; public: test_format() : _last(0), _ooo(0) { } void process(hogl::ostrbuf &sb, const hogl::format::data &d) { uint64_t ts = d.record->timestamp; if (ts < _last) _ooo++; else _last = ts; } unsigned int ooo() const { return _ooo; } }; // Sequence count class sequence { private: uint64_t _count; public: sequence() : _count((uint64_t)0 - 1) {} uint64_t next() { return __sync_add_and_fetch(&_count, 1); } }; sequence global_sequence; // Test engine class test_thread { private: const hogl::area *_log_area; std::string _name; pthread_t _thread; volatile bool _running; volatile bool _killed; bool _failed; unsigned int _ring_capacity; unsigned int _burst_size; unsigned int _interval_usec; unsigned int _nloops; static void *entry(void *_self); void loop(); enum log_sections { INFO }; static const char *_log_sections[]; public: test_thread(const char *name, unsigned int ring_capacity, unsigned int burst_size, unsigned int interval_usec, unsigned int nloops); ~test_thread(); /** * Check if the engine is running */ bool running() const { return _running; } bool failed() const { return _failed; } }; const char *test_thread::_log_sections[] = { "INFO", 0, }; test_thread::test_thread(const char *name, unsigned int ring_capacity, unsigned int burst_size, unsigned int interval_usec, unsigned int nloops) : _name(name), _running(true), _killed(false), _failed(false), _ring_capacity(ring_capacity), _burst_size(burst_size), _interval_usec(interval_usec), _nloops(nloops) { int err; _log_area = hogl::add_area("SORT", _log_sections); if (!_log_area) abort(); err = pthread_create(&_thread, NULL, entry, (void *) this); if (err) { fprintf(stderr, "failed to create test_thread thread. %d\n", err); exit(1); } } test_thread::~test_thread() { _killed = true; pthread_join(_thread, NULL); } void *test_thread::entry(void *_self) { test_thread *self = (test_thread *) _self; hogl::platform::set_thread_title(self->_name.c_str()); // Run the loop self->loop(); return 0; } void test_thread::loop() { _running = true; // Create private thread ring hogl::ringbuf::options ring_opts = { capacity: _ring_capacity, prio: 0 }; hogl::tls tls(_name.c_str(), ring_opts); while (!_killed) { unsigned int i; for (i=0; i < _burst_size; i++) hogl::post_unlocked(_log_area, INFO, global_sequence.next()); _nloops--; if (!_nloops) break; usleep(_interval_usec); } if (tls.ring()->dropcnt()) printf("%s drop count %lu\n", _name.c_str(), (unsigned long) tls.ring()->dropcnt()); _running = false; } // ------- static unsigned int nthreads = 8; static unsigned int ring_capacity = 1024; static unsigned int burst_size = 10; static unsigned int interval_usec = 1000; static unsigned int nloops = 20000; static hogl::engine::options log_eng_opts = hogl::engine::default_options; static std::string log_output("null"); static std::string log_format("basic"); int doTest() { test_thread *thread[nthreads]; unsigned int i; for (i=0; i < nthreads; i++) { char name[100]; sprintf(name, "THREAD%u", i); thread[i] = new test_thread(name, ring_capacity, burst_size, interval_usec, nloops); } while (1) { bool all_dead = true; for (i=0; i < nthreads; i++) { if (thread[i]->running()) all_dead = false; } if (all_dead) break; usleep(10000); } bool failed = false; for (i=0; i < nthreads; i++) { failed |= thread[i]->failed(); delete thread[i]; } return failed ? -1 : 0; } // Command line args { static struct option main_lopts[] = { {"help", 0, 0, 'h'}, {"format", 1, 0, 'f'}, {"output", 1, 0, 'o'}, {"nthreads", 1, 0, 'n'}, {"ring-size", 1, 0, 'r'}, {"burst-size", 1, 0, 'b'}, {"interval", 1, 0, 'i'}, {"nloops", 1, 0, 'l'}, {"notso", 0, 0, 'N'}, {"tso-buffer", 1, 0, 'T'}, {"poll-interval", 1, 0, 'p'}, {0, 0, 0, 0} }; static char main_sopts[] = "hf:o:n:r:b:i:l:p:N:T:"; static char main_help[] = "FurLog stress test 0.1 \n" "Usage:\n" "\tstress_test [options]\n" "Options:\n" "\t--help -h Display help text\n" "\t--format -f <name> Log format (null, basic)\n" "\t--output -o <name> Log output (file name, stderr, or null)\n" "\t--poll-interval -p <N> Engine polling interval (in usec)\n" "\t--nthreads -n <N> Number of threads to start\n" "\t--ring -r <N> Ring size (number of records)\n" "\t--burst -b <N> Burst size (number of records)\n" "\t--interval -i <N> Interval between bursts (in usec)\n" "\t--notso -N Disable timestamp ordering (TSO)\n" "\t--tso-buffer -T <N> TSO buffer size (number of records)\n" "\t--nloops -l <N> Number of loops in each thread\n"; // } int main(int argc, char *argv[]) { int opt; // Parse command line args while ((opt = getopt_long(argc, argv, main_sopts, main_lopts, NULL)) != -1) { switch (opt) { case 'f': log_format = optarg; break; case 'o': log_output = optarg; break; case 'n': nthreads = atoi(optarg); break; case 'r': ring_capacity = atoi(optarg); break; case 'b': burst_size = atoi(optarg); break; case 'i': interval_usec = atoi(optarg); break; case 'l': nloops = atoi(optarg); break; case 'p': log_eng_opts.polling_interval_usec = atoi(optarg); break; case 'N': log_eng_opts.features &= ~hogl::engine::DISABLE_TSO; break; case 'T': log_eng_opts.tso_buffer_capacity = atoi(optarg); break; case 'h': default: printf("%s", main_help); exit(0); } } argc -= optind; argv += optind; if (argc < 0) { printf("%s", main_help); exit(1); } test_format fmt; hogl::output_null lo(fmt); hogl::activate(lo, log_eng_opts); hogl::platform::enable_verbose_coredump(); // Disable everything but our own output to avoid noise hogl::mask m("!.*", "SORT:INFO", 0); hogl::apply_mask(m); int err = doTest(); std::cout << "Engine stats: " << std::endl; std::cout << hogl::default_engine->get_stats(); printf("Number of OOO records %u\n", fmt.ooo()); hogl::deactivate(); if (err < 0 || fmt.ooo()) { printf("Failed\n"); return SKIP; } printf("Passed\n"); return 0; }
Test suite no longer fails when OOO detected
Test suite no longer fails when OOO detected Instead return 77, which tells Automake to mark the test as SKIP.
C++
bsd-2-clause
maxk-org/hogl,maxk-org/hogl,maxk-org/hogl,maxk-org/hogl
15a3f695aabf081f8824e546a7b6dc6ad8bef516
chrome/browser/page_menu_model.cc
chrome/browser/page_menu_model.cc
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/page_menu_model.h" #include "app/l10n_util.h" #include "base/compiler_specific.h" #include "chrome/app/chrome_dll_resource.h" #include "chrome/browser/browser.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/encoding_menu_controller.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "grit/generated_resources.h" PageMenuModel::PageMenuModel(menus::SimpleMenuModel::Delegate* delegate, Browser* browser) : menus::SimpleMenuModel(delegate), browser_(browser) { Build(); } void PageMenuModel::Build() { #if !defined(OS_CHROMEOS) #if defined(OS_MACOSX) AddItemWithStringId(IDC_CREATE_SHORTCUTS, IDS_CREATE_APPLICATION_MAC); #else AddItemWithStringId(IDC_CREATE_SHORTCUTS, IDS_CREATE_SHORTCUTS); #endif AddSeparator(); #endif AddItemWithStringId(IDC_CUT, IDS_CUT); AddItemWithStringId(IDC_COPY, IDS_COPY); AddItemWithStringId(IDC_PASTE, IDS_PASTE); AddSeparator(); AddItemWithStringId(IDC_FIND, IDS_FIND); AddItemWithStringId(IDC_SAVE_PAGE, IDS_SAVE_PAGE); AddItemWithStringId(IDC_PRINT, IDS_PRINT); AddSeparator(); zoom_menu_model_.reset(new ZoomMenuModel(delegate())); AddSubMenuWithStringId(IDC_ZOOM_MENU, IDS_ZOOM_MENU, zoom_menu_model_.get()); encoding_menu_model_.reset(new EncodingMenuModel(browser_)); AddSubMenuWithStringId(IDC_ENCODING_MENU, IDS_ENCODING_MENU, encoding_menu_model_.get()); AddSeparator(); devtools_menu_model_.reset(new DevToolsMenuModel(delegate())); AddSubMenuWithStringId(IDC_DEVELOPER_MENU, IDS_DEVELOPER_MENU, devtools_menu_model_.get()); AddSeparator(); AddItemWithStringId(IDC_REPORT_BUG, IDS_REPORT_BUG); } //////////////////////////////////////////////////////////////////////////////// // EncodingMenuModel EncodingMenuModel::EncodingMenuModel(Browser* browser) : ALLOW_THIS_IN_INITIALIZER_LIST(menus::SimpleMenuModel(this)), browser_(browser) { Build(); } void EncodingMenuModel::Build() { EncodingMenuController::EncodingMenuItemList encoding_menu_items; EncodingMenuController encoding_menu_controller; encoding_menu_controller.GetEncodingMenuItems(browser_->profile(), &encoding_menu_items); int group_id = 0; EncodingMenuController::EncodingMenuItemList::iterator it = encoding_menu_items.begin(); for (; it != encoding_menu_items.end(); ++it) { int id = it->first; string16& label = it->second; if (id == 0) { AddSeparator(); } else { if (id == IDC_ENCODING_AUTO_DETECT) { AddCheckItem(id, label); } else { // Use the id of the first radio command as the id of the group. if (group_id <= 0) group_id = id; AddRadioItem(id, label, group_id); } } } } bool EncodingMenuModel::IsCommandIdChecked(int command_id) const { TabContents* current_tab = browser_->GetSelectedTabContents(); if (!current_tab) return false; EncodingMenuController controller; return controller.IsItemChecked(browser_->profile(), current_tab->encoding(), command_id); } bool EncodingMenuModel::IsCommandIdEnabled(int command_id) const { return browser_->command_updater()->IsCommandEnabled(command_id); } bool EncodingMenuModel::GetAcceleratorForCommandId( int command_id, menus::Accelerator* accelerator) { return false; } void EncodingMenuModel::ExecuteCommand(int command_id) { browser_->ExecuteCommand(command_id); } //////////////////////////////////////////////////////////////////////////////// // ZoomMenuModel ZoomMenuModel::ZoomMenuModel(menus::SimpleMenuModel::Delegate* delegate) : SimpleMenuModel(delegate) { Build(); } void ZoomMenuModel::Build() { AddItemWithStringId(IDC_ZOOM_PLUS, IDS_ZOOM_PLUS); AddItemWithStringId(IDC_ZOOM_NORMAL, IDS_ZOOM_NORMAL); AddItemWithStringId(IDC_ZOOM_MINUS, IDS_ZOOM_MINUS); } //////////////////////////////////////////////////////////////////////////////// // DevToolsMenuModel DevToolsMenuModel::DevToolsMenuModel(menus::SimpleMenuModel::Delegate* delegate) : SimpleMenuModel(delegate) { Build(); } void DevToolsMenuModel::Build() { AddItemWithStringId(IDC_VIEW_SOURCE, IDS_VIEW_SOURCE); if (g_browser_process->have_inspector_files()) { AddItemWithStringId(IDC_DEV_TOOLS, IDS_DEV_TOOLS); AddItemWithStringId(IDC_DEV_TOOLS_CONSOLE, IDS_DEV_TOOLS_CONSOLE); } AddItemWithStringId(IDC_TASK_MANAGER, IDS_TASK_MANAGER); } //////////////////////////////////////////////////////////////////////////////// // PopupPageMenuModel PopupPageMenuModel::PopupPageMenuModel( menus::SimpleMenuModel::Delegate* delegate, Browser* browser) : menus::SimpleMenuModel(delegate), browser_(browser) { Build(); } void PopupPageMenuModel::Build() { AddItemWithStringId(IDC_BACK, IDS_CONTENT_CONTEXT_BACK); AddItemWithStringId(IDC_FORWARD, IDS_CONTENT_CONTEXT_FORWARD); AddItemWithStringId(IDC_RELOAD, IDS_APP_MENU_RELOAD); AddSeparator(); AddItemWithStringId(IDC_SHOW_AS_TAB, IDS_SHOW_AS_TAB); AddSeparator(); AddItemWithStringId(IDC_CUT, IDS_CUT); AddItemWithStringId(IDC_COPY, IDS_COPY); AddItemWithStringId(IDC_PASTE, IDS_PASTE); AddSeparator(); AddItemWithStringId(IDC_FIND, IDS_FIND); AddItemWithStringId(IDC_PRINT, IDS_PRINT); zoom_menu_model_.reset(new ZoomMenuModel(delegate())); AddSubMenuWithStringId(IDC_ZOOM_MENU, IDS_ZOOM_MENU, zoom_menu_model_.get()); encoding_menu_model_.reset(new EncodingMenuModel(browser_)); AddSubMenuWithStringId(IDC_ENCODING_MENU, IDS_ENCODING_MENU, encoding_menu_model_.get()); }
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/page_menu_model.h" #include "app/l10n_util.h" #include "base/compiler_specific.h" #include "chrome/app/chrome_dll_resource.h" #include "chrome/browser/browser.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/encoding_menu_controller.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "grit/generated_resources.h" PageMenuModel::PageMenuModel(menus::SimpleMenuModel::Delegate* delegate, Browser* browser) : menus::SimpleMenuModel(delegate), browser_(browser) { Build(); } void PageMenuModel::Build() { #if !defined(OS_CHROMEOS) #if defined(OS_MACOSX) AddItemWithStringId(IDC_CREATE_SHORTCUTS, IDS_CREATE_APPLICATION_MAC); #else AddItemWithStringId(IDC_CREATE_SHORTCUTS, IDS_CREATE_SHORTCUTS); #endif AddSeparator(); #endif AddItemWithStringId(IDC_CUT, IDS_CUT); AddItemWithStringId(IDC_COPY, IDS_COPY); AddItemWithStringId(IDC_PASTE, IDS_PASTE); AddSeparator(); AddItemWithStringId(IDC_FIND, IDS_FIND); AddItemWithStringId(IDC_SAVE_PAGE, IDS_SAVE_PAGE); AddItemWithStringId(IDC_PRINT, IDS_PRINT); AddSeparator(); zoom_menu_model_.reset(new ZoomMenuModel(delegate())); AddSubMenuWithStringId(IDC_ZOOM_MENU, IDS_ZOOM_MENU, zoom_menu_model_.get()); encoding_menu_model_.reset(new EncodingMenuModel(browser_)); AddSubMenuWithStringId(IDC_ENCODING_MENU, IDS_ENCODING_MENU, encoding_menu_model_.get()); AddSeparator(); devtools_menu_model_.reset(new DevToolsMenuModel(delegate())); AddSubMenuWithStringId(IDC_DEVELOPER_MENU, IDS_DEVELOPER_MENU, devtools_menu_model_.get()); AddSeparator(); AddItemWithStringId(IDC_REPORT_BUG, IDS_REPORT_BUG); } //////////////////////////////////////////////////////////////////////////////// // EncodingMenuModel EncodingMenuModel::EncodingMenuModel(Browser* browser) : ALLOW_THIS_IN_INITIALIZER_LIST(menus::SimpleMenuModel(this)), browser_(browser) { Build(); } void EncodingMenuModel::Build() { EncodingMenuController::EncodingMenuItemList encoding_menu_items; EncodingMenuController encoding_menu_controller; encoding_menu_controller.GetEncodingMenuItems(browser_->profile(), &encoding_menu_items); int group_id = 0; EncodingMenuController::EncodingMenuItemList::iterator it = encoding_menu_items.begin(); for (; it != encoding_menu_items.end(); ++it) { int id = it->first; string16& label = it->second; if (id == 0) { AddSeparator(); } else { if (id == IDC_ENCODING_AUTO_DETECT) { AddCheckItem(id, label); } else { // Use the id of the first radio command as the id of the group. if (group_id <= 0) group_id = id; AddRadioItem(id, label, group_id); } } } } bool EncodingMenuModel::IsCommandIdChecked(int command_id) const { TabContents* current_tab = browser_->GetSelectedTabContents(); if (!current_tab) return false; EncodingMenuController controller; return controller.IsItemChecked(browser_->profile(), current_tab->encoding(), command_id); } bool EncodingMenuModel::IsCommandIdEnabled(int command_id) const { bool enabled = browser_->command_updater()->IsCommandEnabled(command_id); // Special handling for the contents of the Encoding submenu. On Mac OS, // instead of enabling/disabling the top-level menu item, the submenu's // contents get disabled, per Apple's HIG. #if defined(OS_MACOSX) enabled &= browser_->command_updater()->IsCommandEnabled(IDC_ENCODING_MENU); #endif return enabled; } bool EncodingMenuModel::GetAcceleratorForCommandId( int command_id, menus::Accelerator* accelerator) { return false; } void EncodingMenuModel::ExecuteCommand(int command_id) { browser_->ExecuteCommand(command_id); } //////////////////////////////////////////////////////////////////////////////// // ZoomMenuModel ZoomMenuModel::ZoomMenuModel(menus::SimpleMenuModel::Delegate* delegate) : SimpleMenuModel(delegate) { Build(); } void ZoomMenuModel::Build() { AddItemWithStringId(IDC_ZOOM_PLUS, IDS_ZOOM_PLUS); AddItemWithStringId(IDC_ZOOM_NORMAL, IDS_ZOOM_NORMAL); AddItemWithStringId(IDC_ZOOM_MINUS, IDS_ZOOM_MINUS); } //////////////////////////////////////////////////////////////////////////////// // DevToolsMenuModel DevToolsMenuModel::DevToolsMenuModel(menus::SimpleMenuModel::Delegate* delegate) : SimpleMenuModel(delegate) { Build(); } void DevToolsMenuModel::Build() { AddItemWithStringId(IDC_VIEW_SOURCE, IDS_VIEW_SOURCE); if (g_browser_process->have_inspector_files()) { AddItemWithStringId(IDC_DEV_TOOLS, IDS_DEV_TOOLS); AddItemWithStringId(IDC_DEV_TOOLS_CONSOLE, IDS_DEV_TOOLS_CONSOLE); } AddItemWithStringId(IDC_TASK_MANAGER, IDS_TASK_MANAGER); } //////////////////////////////////////////////////////////////////////////////// // PopupPageMenuModel PopupPageMenuModel::PopupPageMenuModel( menus::SimpleMenuModel::Delegate* delegate, Browser* browser) : menus::SimpleMenuModel(delegate), browser_(browser) { Build(); } void PopupPageMenuModel::Build() { AddItemWithStringId(IDC_BACK, IDS_CONTENT_CONTEXT_BACK); AddItemWithStringId(IDC_FORWARD, IDS_CONTENT_CONTEXT_FORWARD); AddItemWithStringId(IDC_RELOAD, IDS_APP_MENU_RELOAD); AddSeparator(); AddItemWithStringId(IDC_SHOW_AS_TAB, IDS_SHOW_AS_TAB); AddSeparator(); AddItemWithStringId(IDC_CUT, IDS_CUT); AddItemWithStringId(IDC_COPY, IDS_COPY); AddItemWithStringId(IDC_PASTE, IDS_PASTE); AddSeparator(); AddItemWithStringId(IDC_FIND, IDS_FIND); AddItemWithStringId(IDC_PRINT, IDS_PRINT); zoom_menu_model_.reset(new ZoomMenuModel(delegate())); AddSubMenuWithStringId(IDC_ZOOM_MENU, IDS_ZOOM_MENU, zoom_menu_model_.get()); encoding_menu_model_.reset(new EncodingMenuModel(browser_)); AddSubMenuWithStringId(IDC_ENCODING_MENU, IDS_ENCODING_MENU, encoding_menu_model_.get()); }
Disable the Encoding menu within the Wrench menu for Chromium-internal pages.
[Mac] Disable the Encoding menu within the Wrench menu for Chromium-internal pages. BUG=48157 TEST=Go to about:version or the NTP. Open Wrench-->Tools-->Encoding. All items are disabled. Review URL: http://codereview.chromium.org/2928001 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@51860 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
gavinp/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,yitian134/chromium,ropik/chromium,yitian134/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,gavinp/chromium,ropik/chromium,adobe/chromium,ropik/chromium,adobe/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,adobe/chromium,adobe/chromium,yitian134/chromium,gavinp/chromium,gavinp/chromium,ropik/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,yitian134/chromium,gavinp/chromium,adobe/chromium,yitian134/chromium,ropik/chromium,yitian134/chromium,ropik/chromium,ropik/chromium,yitian134/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,Crystalnix/house-of-life-chromium
1d78ae6931058ef13a19a3b822a2c2c7ec6afcf0
asc/AscNovel.hpp
asc/AscNovel.hpp
# pragma once # include <Siv3D.hpp> # include "AscChoiceManager.hpp" # include "AscMessageManager.hpp" # include "AscIMessgeButton.hpp" # include "AscSoundManager.hpp" # include "AscSpriteManager.hpp" # include "AscTimeManager.hpp" namespace asc { using namespace s3d; class Novel { private: using Commnad = std::pair<int32, String>; bool m_isUpdating; int32 m_currentLine; int32 m_lastSeekPoint; KeyCombination m_skip; Array<Commnad> m_commands; ChoiceManager m_choiceManager; MessageManager m_messageManager; SoundManager m_soundManager; SpriteManager m_spriteManager; TimeManager m_timeManager; void clearManager() { m_messageManager.clear(); m_spriteManager.clear(); m_choiceManager.clear(); m_timeManager.clear(); } void execute() { switch (m_commands[m_currentLine].first) { // Point case 0: m_isUpdating = false; return; // Text case 1: m_messageManager.setText(m_commands[m_currentLine].second); m_messageManager.start(); break; // Name case 2: m_messageManager.setName(m_commands[m_currentLine].second); break; // AddSprite case 3: m_spriteManager.add<Sprite>(m_commands[m_currentLine].second); break; // AddFixedSprite case 4: m_spriteManager.add<FixedSprite>(m_commands[m_currentLine].second); break; // Choice case 5: m_choiceManager.start(m_commands[m_currentLine].second); break; // Jump case 6: start(Parse<int32>(m_commands[m_currentLine].second)); return; // AutomaticText case 7: m_messageManager.setText(m_commands[m_currentLine].second); m_messageManager.start(true); break; // Play BGM case 8: m_soundManager.playBGM(m_commands[m_currentLine].second); break; // Stop BGM case 9: m_soundManager.stopBGM(m_commands[m_currentLine].second); break; // Lihgt Up case 10: m_spriteManager.lightUp(m_commands[m_currentLine].second); break; // Lihgt Up Spot case 11: m_spriteManager.lightUpSpot(m_commands[m_currentLine].second); break; // Bring case 12: m_spriteManager.bring(m_commands[m_currentLine].second); break; // Erase case 13: m_spriteManager.erase(m_commands[m_currentLine].second); break; // Wait case 14: m_timeManager.wait(m_commands[m_currentLine].second); break; default: break; } m_currentLine++; } void skip() { while (m_isUpdating && !m_choiceManager.isUpdating()) { execute(); } m_timeManager.clear(); m_messageManager.skip(); } public: Novel() : m_isUpdating(false), m_currentLine(0), m_lastSeekPoint(-1), m_choiceManager( [&] { m_soundManager.playMoveSound(); }, [&] { m_soundManager.playSubmitSound(); } ), m_messageManager( [&] { m_soundManager.playCharSound(); } ) {} virtual ~Novel() = default; bool load(const FilePath& path, const Optional<TextEncoding>& encoding = unspecified) { TextReader reader(path, encoding); if (!reader.isOpened()) return false; loadByString(reader.readAll()); return true; } void loadByString(const String& scenario) { const auto lines = scenario.trim().split(L'\n'); for (const auto& line : lines) { const auto pos = line.indexOf(L","); m_commands.push_back(std::make_pair(Parse<int32>(line.substr(0U, pos)), line.substr(pos + 1, line.length))); } m_commands.push_back(std::make_pair(0, L"-1")); } bool start(int32 seekPoint) { const auto size = m_commands.size() - 1; for (auto i = 0u; i < size; i++) { const auto index = (m_currentLine + i) % m_commands.size(); const auto command = m_commands[index]; if ( command.first == 0 && Parse<int32>(command.second) == seekPoint ) { clearManager(); m_currentLine = index + 1; m_lastSeekPoint = seekPoint; m_isUpdating = true; return true; } } return false; } void update() { if (m_skip.clicked) { skip(); } while ( m_isUpdating && !m_messageManager.isUpdating() && !m_choiceManager.isUpdating() && !m_timeManager.isUpdating() ) { m_choiceManager.lastSelectedSeekPoint().then([&](int32 seekPoint){ start(seekPoint); }); execute(); } m_messageManager.update(); m_choiceManager.update(); } bool isUpdating() const { return m_isUpdating; } int32 seekPoint() const { return m_lastSeekPoint; } void draw() const { m_spriteManager.draw(); m_messageManager.draw(); m_choiceManager.draw(); } Novel& setSpeed(int32 speed) { m_messageManager.setSpeed(speed); return *this; } Novel& setWaitingTime(int32 time) { m_messageManager.setTime(time); return *this; } Novel& setKey(const KeyCombination& submit, const KeyCombination& skip) { m_messageManager.setKey(submit); m_skip = skip; return *this; } Novel& setKey(const KeyCombination& submit, const KeyCombination& skip, const KeyCombination& up, const KeyCombination& down) { m_messageManager.setKey(submit); m_choiceManager.setKey(submit, up, down); m_skip = skip; return *this; } Novel& setButton(std::unique_ptr<IMessageButton>&& button) { m_messageManager.setButton(std::move(button)); return *this; } template <class Type> Novel& setButton(Type&& button) { return setButton(static_cast<std::unique_ptr<IMessageButton>>(std::make_unique<Type>(button))); } Novel& setFont(const FontAssetName& text) { return setFont(text, text); } Novel& setFont(const FontAssetName& text, const FontAssetName& name = L"") { m_messageManager.setFont(text, name); m_choiceManager.setFont(text); return *this; } Novel& setColor(const Color& color, const Color& selectedColor = Palette::Red) { m_messageManager.setColor(color); m_choiceManager.setColor(color, selectedColor); return *this; } Novel& setMessageTexture(const TextureAssetName& texture, const Rect& region) { m_messageManager.setTexture(texture, region); return *this; } Novel& setMessagePosition(const Point& text, const Point& name = Point::Zero) { m_messageManager.setPosition(text, name); return *this; } Novel& setChoiceTexture(const TextureAssetName texture, const Rect& region) { m_choiceManager.setTexture(texture, region); return *this; } Novel& setChoicePosition(const Point& position) { m_choiceManager.setPosition(position); return *this; } Novel& setBGMVolume(double volume) { m_soundManager.setBGMVolume(volume); return *this; } Novel& setSEVolume(double volume) { m_soundManager.setSEVolume(volume); return *this; } Novel& setSound(const SoundAssetName& charCount) { m_soundManager.setSE(charCount); return *this; } Novel& setSound(const SoundAssetName& charCount, const SoundAssetName& move, const SoundAssetName& submit) { m_soundManager.setSE(charCount, move, submit); return *this; } Novel& setSilentChars(const Array<wchar> silentChars) { m_messageManager.setSilentChars(silentChars); return *this; } }; }
# pragma once # include <Siv3D.hpp> # include "AscChoiceManager.hpp" # include "AscMessageManager.hpp" # include "AscIMessgeButton.hpp" # include "AscSoundManager.hpp" # include "AscSpriteManager.hpp" # include "AscTimeManager.hpp" namespace asc { using namespace s3d; using Commnad = std::pair<int32, String>; const Commnad EndOfCommand = std::pair<int32, String>(0, L"-1"); class Novel { private: bool m_isUpdating; int32 m_currentLine; int32 m_lastSeekPoint; KeyCombination m_skip; Array<Commnad> m_commands; ChoiceManager m_choiceManager; MessageManager m_messageManager; SoundManager m_soundManager; SpriteManager m_spriteManager; TimeManager m_timeManager; void clearManager() { m_messageManager.clear(); m_spriteManager.clear(); m_choiceManager.clear(); m_timeManager.clear(); } void execute() { switch (m_commands[m_currentLine].first) { // Point case 0: m_isUpdating = false; return; // Text case 1: m_messageManager.setText(m_commands[m_currentLine].second); m_messageManager.start(); break; // Name case 2: m_messageManager.setName(m_commands[m_currentLine].second); break; // AddSprite case 3: m_spriteManager.add<Sprite>(m_commands[m_currentLine].second); break; // AddFixedSprite case 4: m_spriteManager.add<FixedSprite>(m_commands[m_currentLine].second); break; // Choice case 5: m_choiceManager.start(m_commands[m_currentLine].second); break; // Jump case 6: start(Parse<int32>(m_commands[m_currentLine].second)); return; // AutomaticText case 7: m_messageManager.setText(m_commands[m_currentLine].second); m_messageManager.start(true); break; // Play BGM case 8: m_soundManager.playBGM(m_commands[m_currentLine].second); break; // Stop BGM case 9: m_soundManager.stopBGM(m_commands[m_currentLine].second); break; // Lihgt Up case 10: m_spriteManager.lightUp(m_commands[m_currentLine].second); break; // Lihgt Up Spot case 11: m_spriteManager.lightUpSpot(m_commands[m_currentLine].second); break; // Bring case 12: m_spriteManager.bring(m_commands[m_currentLine].second); break; // Erase case 13: m_spriteManager.erase(m_commands[m_currentLine].second); break; // Wait case 14: m_timeManager.wait(m_commands[m_currentLine].second); break; default: break; } m_currentLine++; } void skip() { while (m_isUpdating && !m_choiceManager.isUpdating()) { execute(); } m_timeManager.clear(); m_messageManager.skip(); } public: Novel() : m_isUpdating(false), m_currentLine(0), m_lastSeekPoint(-1), m_commands({ EndOfCommand }), m_choiceManager( [&] { m_soundManager.playMoveSound(); }, [&] { m_soundManager.playSubmitSound(); } ), m_messageManager( [&] { m_soundManager.playCharSound(); } ) {} virtual ~Novel() = default; bool load(const FilePath& path, const Optional<TextEncoding>& encoding = unspecified, bool isAdditive = false) { TextReader reader(path, encoding); if (!reader.isOpened()) return false; loadByString(reader.readAll(), isAdditive); return true; } void loadByString(const String& scenario, bool isAdditive = false) { isAdditive ? m_commands.pop_back() : m_commands.clear(); const auto lines = scenario.trim().split(L'\n'); for (const auto& line : lines) { const auto pos = line.indexOf(L","); m_commands.push_back(std::make_pair(Parse<int32>(line.substr(0U, pos)), line.substr(pos + 1U, line.length))); } m_commands.push_back(EndOfCommand); } bool start(int32 seekPoint) { const auto size = m_commands.size() - 1; for (auto i = 0u; i < size; i++) { const auto index = (m_currentLine + i) % m_commands.size(); const auto command = m_commands[index]; if ( command.first == 0 && Parse<int32>(command.second) == seekPoint ) { clearManager(); m_currentLine = index + 1; m_lastSeekPoint = seekPoint; m_isUpdating = true; return true; } } return false; } void update() { if (m_skip.clicked) { skip(); } while ( m_isUpdating && !m_messageManager.isUpdating() && !m_choiceManager.isUpdating() && !m_timeManager.isUpdating() ) { m_choiceManager.lastSelectedSeekPoint().then([&](int32 seekPoint){ start(seekPoint); }); execute(); } m_messageManager.update(); m_choiceManager.update(); } bool isUpdating() const { return m_isUpdating; } int32 seekPoint() const { return m_lastSeekPoint; } void draw() const { m_spriteManager.draw(); m_messageManager.draw(); m_choiceManager.draw(); } Novel& setSpeed(int32 speed) { m_messageManager.setSpeed(speed); return *this; } Novel& setWaitingTime(int32 time) { m_messageManager.setTime(time); return *this; } Novel& setKey(const KeyCombination& submit, const KeyCombination& skip) { m_messageManager.setKey(submit); m_skip = skip; return *this; } Novel& setKey(const KeyCombination& submit, const KeyCombination& skip, const KeyCombination& up, const KeyCombination& down) { m_messageManager.setKey(submit); m_choiceManager.setKey(submit, up, down); m_skip = skip; return *this; } Novel& setButton(std::unique_ptr<IMessageButton>&& button) { m_messageManager.setButton(std::move(button)); return *this; } template <class Type> Novel& setButton(Type&& button) { return setButton(static_cast<std::unique_ptr<IMessageButton>>(std::make_unique<Type>(button))); } Novel& setFont(const FontAssetName& text) { return setFont(text, text); } Novel& setFont(const FontAssetName& text, const FontAssetName& name = L"") { m_messageManager.setFont(text, name); m_choiceManager.setFont(text); return *this; } Novel& setColor(const Color& color, const Color& selectedColor = Palette::Red) { m_messageManager.setColor(color); m_choiceManager.setColor(color, selectedColor); return *this; } Novel& setMessageTexture(const TextureAssetName& texture, const Rect& region) { m_messageManager.setTexture(texture, region); return *this; } Novel& setMessagePosition(const Point& text, const Point& name = Point::Zero) { m_messageManager.setPosition(text, name); return *this; } Novel& setChoiceTexture(const TextureAssetName texture, const Rect& region) { m_choiceManager.setTexture(texture, region); return *this; } Novel& setChoicePosition(const Point& position) { m_choiceManager.setPosition(position); return *this; } Novel& setBGMVolume(double volume) { m_soundManager.setBGMVolume(volume); return *this; } Novel& setSEVolume(double volume) { m_soundManager.setSEVolume(volume); return *this; } Novel& setSound(const SoundAssetName& charCount) { m_soundManager.setSE(charCount); return *this; } Novel& setSound(const SoundAssetName& charCount, const SoundAssetName& move, const SoundAssetName& submit) { m_soundManager.setSE(charCount, move, submit); return *this; } Novel& setSilentChars(const Array<wchar> silentChars) { m_messageManager.setSilentChars(silentChars); return *this; } }; }
Implement load additive.
Implement load additive.
C++
mit
ChunChunMorning/AscNovel-Siv3D,ChunChunMorning/AscNovel
4a35b8965a9a92da247a96e04a344261ccb86fe5
asc/AscNovel.hpp
asc/AscNovel.hpp
# pragma once # include <Siv3D.hpp> # include "AscChoiceManager.hpp" # include "AscMessageManager.hpp" # include "AscIMessgeButton.hpp" # include "AscSoundManager.hpp" # include "AscSpriteManager.hpp" # include "AscTimeManager.hpp" namespace asc { using namespace s3d; class Novel { private: using Commnad = std::pair<int32, String>; bool m_isUpdating; int32 m_currentLine; int32 m_lastSeekPoint; KeyCombination m_skip; Array<Commnad> m_commands; ChoiceManager m_choiceManager; MessageManager m_messageManager; SoundManager m_soundManager; SpriteManager m_spriteManager; TimeManager m_timeManager; void clearManager() { m_messageManager.clear(); m_spriteManager.clear(); m_choiceManager.clear(); m_timeManager.clear(); } void execute() { switch (m_commands[m_currentLine].first) { // Point case 0: m_isUpdating = false; return; // Text case 1: m_messageManager.setText(m_commands[m_currentLine].second); m_messageManager.start(); break; // Name case 2: m_messageManager.setName(m_commands[m_currentLine].second); break; // AddSprite case 3: m_spriteManager.add<Sprite>(m_commands[m_currentLine].second); break; // AddFixedSprite case 4: m_spriteManager.add<FixedSprite>(m_commands[m_currentLine].second); break; // Choice case 5: m_choiceManager.start(m_commands[m_currentLine].second); break; // Jump case 6: start(Parse<int32>(m_commands[m_currentLine].second)); return; // AutomaticText case 7: m_messageManager.setText(m_commands[m_currentLine].second); m_messageManager.start(true); break; // Play BGM case 8: m_soundManager.playBGM(m_commands[m_currentLine].second); break; // Stop BGM case 9: m_soundManager.stopBGM(m_commands[m_currentLine].second); break; // Lihgt Up case 10: m_spriteManager.lightUp(m_commands[m_currentLine].second); break; // Lihgt Up Spot case 11: m_spriteManager.lightUpSpot(m_commands[m_currentLine].second); break; // Bring case 12: m_spriteManager.bring(m_commands[m_currentLine].second); break; // Erase case 13: m_spriteManager.erase(m_commands[m_currentLine].second); break; // Wait case 14: m_timeManager.wait(m_commands[m_currentLine].second); break; default: break; } m_currentLine++; } void skip() { while (m_isUpdating && !m_choiceManager.isUpdating()) { execute(); } m_timeManager.clear(); m_messageManager.skip(); } public: Novel() : m_isUpdating(false), m_currentLine(0), m_lastSeekPoint(-1), m_choiceManager( [&] { m_soundManager.playMoveSound(); }, [&] { m_soundManager.playSubmitSound(); } ), m_messageManager( [&] { m_soundManager.playCharSound(); } ) { m_commands.push_back({ 0, L"1"}); m_commands.push_back({ 3, L"1,character1,0,0,640,720" }); m_commands.push_back({ 3, L"3,character3,480,180,320,360" }); m_commands.push_back({ 1, L"Characters" }); m_commands.push_back({ 0, L"2" }); m_commands.push_back({ 1, L"Only Text" }); m_commands.push_back({ 0, L"3" }); m_commands.push_back({ 7, L"Show Character?" }); m_commands.push_back({ 5, L"1,Yes,2,No" }); m_commands.push_back({ 0, L"4" }); m_commands.push_back({ 1, L"Jump 2" }); m_commands.push_back({ 6, L"2" }); m_commands.push_back({ 0, L"5" }); m_commands.push_back({ 8, L"bgm1,3" }); m_commands.push_back({ 1, L"Play BGM1" }); m_commands.push_back({ 0, L"6" }); m_commands.push_back({ 9, L"bgm1,3" }); m_commands.push_back({ 8, L"bgm2,3" }); m_commands.push_back({ 1, L"Play BGM2" }); m_commands.push_back({ 9, L"bgm2,0" }); m_commands.push_back({ 1, L"Stop BGM2" }); m_commands.push_back({ 0, L"7" }); m_commands.push_back({ 3, L"1,character1,0,0,640,720" }); m_commands.push_back({ 3, L"3,character3,0,180,320,360" }); m_commands.push_back({ 10, L"1,true" }); m_commands.push_back({ 10, L"3,true" }); m_commands.push_back({ 1, L"Light Up" }); m_commands.push_back({ 10, L"1,false" }); m_commands.push_back({ 1, L"Light Down" }); m_commands.push_back({ 11, L"1" }); m_commands.push_back({ 1, L"Spot Light" }); m_commands.push_back({ 12, L"1" }); m_commands.push_back({ 1, L"Bring 1" }); m_commands.push_back({ 13, L"3" }); m_commands.push_back({ 1, L"Erase 3" }); m_commands.push_back({ 0, L"8" }); m_commands.push_back({ 7, L"Wait 3 second" }); m_commands.push_back({ 14, L"3000" }); m_commands.push_back({ 1, L"fin" }); m_commands.push_back({ 0, L"-1" }); } virtual ~Novel() = default; bool start(int32 seekPoint) { const auto size = m_commands.size() - 1; for (auto i = 0u; i < size; i++) { const auto index = (m_currentLine + i) % m_commands.size(); const auto command = m_commands[index]; if ( command.first == 0 && Parse<int32>(command.second) == seekPoint ) { clearManager(); m_currentLine = index + 1; m_lastSeekPoint = seekPoint; m_isUpdating = true; return true; } } return false; } void update() { if (m_skip.clicked && !m_choiceManager.isUpdating()) { skip(); } while ( m_isUpdating && !m_messageManager.isUpdating() && !m_choiceManager.isUpdating() && !m_timeManager.isUpdating() ) { m_choiceManager.lastSelectedSeekPoint().then([&](int32 seekPoint){ start(seekPoint); }); execute(); } m_messageManager.update(); m_choiceManager.update(); } bool isUpdating() const { return m_isUpdating; } int32 seekPoint() const { return m_lastSeekPoint; } void draw() const { m_spriteManager.draw(); m_messageManager.draw(); m_choiceManager.draw(); } Novel& setSpeed(int32 speed) { m_messageManager.setSpeed(speed); return *this; } Novel& setWaitingTime(int32 time) { m_messageManager.setTime(time); return *this; } Novel& setKey(const KeyCombination& submit, const KeyCombination& skip) { m_messageManager.setKey(submit); m_skip = skip; return *this; } Novel& setKey(const KeyCombination& submit, const KeyCombination& skip, const KeyCombination& up, const KeyCombination& down) { m_messageManager.setKey(submit); m_choiceManager.setKey(submit, up, down); m_skip = skip; return *this; } Novel& setButton(std::unique_ptr<IMessageButton>&& button) { m_messageManager.setButton(std::move(button)); return *this; } template <class Type> Novel& setButton(const Type& button) { return setButton(static_cast<std::unique_ptr<IMessageButton>>(std::make_unique<Type>(button))); } Novel& setFont(const FontAssetName& text) { return setFont(text, text); } Novel& setFont(const FontAssetName& text, const FontAssetName& name = L"") { m_messageManager.setFont(text, name); m_choiceManager.setFont(text); return *this; } Novel& setColor(const Color& color, const Color& selectedColor = Palette::Red) { m_messageManager.setColor(color); m_choiceManager.setColor(color, selectedColor); return *this; } Novel& setMessageTexture(const TextureAssetName& texture, const Rect& region) { m_messageManager.setTexture(texture, region); return *this; } Novel& setMessagePosition(const Point& text, const Point& name = Point::Zero) { m_messageManager.setPosition(text, name); return *this; } Novel& setChoiceTexture(const TextureAssetName texture, const Rect& region) { m_choiceManager.setTexture(texture, region); return *this; } Novel& setChoicePosition(const Point& position) { m_choiceManager.setPosition(position); return *this; } Novel& setBGMVolume(double volume) { m_soundManager.setBGMVolume(volume); return *this; } Novel& setSEVolume(double volume) { m_soundManager.setSEVolume(volume); return *this; } Novel& setSound(const SoundAssetName& charCount) { m_soundManager.setSE(charCount); return *this; } Novel& setSound(const SoundAssetName& charCount, const SoundAssetName& move, const SoundAssetName& submit) { m_soundManager.setSE(charCount, move, submit); return *this; } Novel& setSilentChars(const Array<wchar> silentChars) { m_messageManager.setSilentChars(silentChars); return *this; } }; }
# pragma once # include <Siv3D.hpp> # include "AscChoiceManager.hpp" # include "AscMessageManager.hpp" # include "AscIMessgeButton.hpp" # include "AscSoundManager.hpp" # include "AscSpriteManager.hpp" # include "AscTimeManager.hpp" namespace asc { using namespace s3d; class Novel { private: using Commnad = std::pair<int32, String>; bool m_isUpdating; int32 m_currentLine; int32 m_lastSeekPoint; KeyCombination m_skip; Array<Commnad> m_commands; ChoiceManager m_choiceManager; MessageManager m_messageManager; SoundManager m_soundManager; SpriteManager m_spriteManager; TimeManager m_timeManager; void clearManager() { m_messageManager.clear(); m_spriteManager.clear(); m_choiceManager.clear(); m_timeManager.clear(); } void execute() { switch (m_commands[m_currentLine].first) { // Point case 0: m_isUpdating = false; return; // Text case 1: m_messageManager.setText(m_commands[m_currentLine].second); m_messageManager.start(); break; // Name case 2: m_messageManager.setName(m_commands[m_currentLine].second); break; // AddSprite case 3: m_spriteManager.add<Sprite>(m_commands[m_currentLine].second); break; // AddFixedSprite case 4: m_spriteManager.add<FixedSprite>(m_commands[m_currentLine].second); break; // Choice case 5: m_choiceManager.start(m_commands[m_currentLine].second); break; // Jump case 6: start(Parse<int32>(m_commands[m_currentLine].second)); return; // AutomaticText case 7: m_messageManager.setText(m_commands[m_currentLine].second); m_messageManager.start(true); break; // Play BGM case 8: m_soundManager.playBGM(m_commands[m_currentLine].second); break; // Stop BGM case 9: m_soundManager.stopBGM(m_commands[m_currentLine].second); break; // Lihgt Up case 10: m_spriteManager.lightUp(m_commands[m_currentLine].second); break; // Lihgt Up Spot case 11: m_spriteManager.lightUpSpot(m_commands[m_currentLine].second); break; // Bring case 12: m_spriteManager.bring(m_commands[m_currentLine].second); break; // Erase case 13: m_spriteManager.erase(m_commands[m_currentLine].second); break; // Wait case 14: m_timeManager.wait(m_commands[m_currentLine].second); break; default: break; } m_currentLine++; } void skip() { while (m_isUpdating && !m_choiceManager.isUpdating()) { execute(); } m_timeManager.clear(); m_messageManager.skip(); } public: Novel() : m_isUpdating(false), m_currentLine(0), m_lastSeekPoint(-1), m_choiceManager( [&] { m_soundManager.playMoveSound(); }, [&] { m_soundManager.playSubmitSound(); } ), m_messageManager( [&] { m_soundManager.playCharSound(); } ) { m_commands.push_back({ 0, L"1"}); m_commands.push_back({ 3, L"1,character1,0,0,640,720" }); m_commands.push_back({ 3, L"3,character3,480,180,320,360" }); m_commands.push_back({ 1, L"Characters" }); m_commands.push_back({ 0, L"2" }); m_commands.push_back({ 1, L"Only Text" }); m_commands.push_back({ 0, L"3" }); m_commands.push_back({ 7, L"Show Character?" }); m_commands.push_back({ 5, L"1,Yes,2,No" }); m_commands.push_back({ 0, L"4" }); m_commands.push_back({ 1, L"Jump 2" }); m_commands.push_back({ 6, L"2" }); m_commands.push_back({ 0, L"5" }); m_commands.push_back({ 8, L"bgm1,3" }); m_commands.push_back({ 1, L"Play BGM1" }); m_commands.push_back({ 0, L"6" }); m_commands.push_back({ 9, L"bgm1,3" }); m_commands.push_back({ 8, L"bgm2,3" }); m_commands.push_back({ 1, L"Play BGM2" }); m_commands.push_back({ 9, L"bgm2,0" }); m_commands.push_back({ 1, L"Stop BGM2" }); m_commands.push_back({ 0, L"7" }); m_commands.push_back({ 3, L"1,character1,0,0,640,720" }); m_commands.push_back({ 3, L"3,character3,0,180,320,360" }); m_commands.push_back({ 10, L"1,true" }); m_commands.push_back({ 10, L"3,true" }); m_commands.push_back({ 1, L"Light Up" }); m_commands.push_back({ 10, L"1,false" }); m_commands.push_back({ 1, L"Light Down" }); m_commands.push_back({ 11, L"1" }); m_commands.push_back({ 1, L"Spot Light" }); m_commands.push_back({ 12, L"1" }); m_commands.push_back({ 1, L"Bring 1" }); m_commands.push_back({ 13, L"3" }); m_commands.push_back({ 1, L"Erase 3" }); m_commands.push_back({ 0, L"8" }); m_commands.push_back({ 7, L"Wait 3 second" }); m_commands.push_back({ 14, L"3000" }); m_commands.push_back({ 1, L"fin" }); m_commands.push_back({ 0, L"-1" }); } virtual ~Novel() = default; bool start(int32 seekPoint) { const auto size = m_commands.size() - 1; for (auto i = 0u; i < size; i++) { const auto index = (m_currentLine + i) % m_commands.size(); const auto command = m_commands[index]; if ( command.first == 0 && Parse<int32>(command.second) == seekPoint ) { clearManager(); m_currentLine = index + 1; m_lastSeekPoint = seekPoint; m_isUpdating = true; return true; } } return false; } void update() { if (m_skip.clicked) { skip(); } while ( m_isUpdating && !m_messageManager.isUpdating() && !m_choiceManager.isUpdating() && !m_timeManager.isUpdating() ) { m_choiceManager.lastSelectedSeekPoint().then([&](int32 seekPoint){ start(seekPoint); }); execute(); } m_messageManager.update(); m_choiceManager.update(); } bool isUpdating() const { return m_isUpdating; } int32 seekPoint() const { return m_lastSeekPoint; } void draw() const { m_spriteManager.draw(); m_messageManager.draw(); m_choiceManager.draw(); } Novel& setSpeed(int32 speed) { m_messageManager.setSpeed(speed); return *this; } Novel& setWaitingTime(int32 time) { m_messageManager.setTime(time); return *this; } Novel& setKey(const KeyCombination& submit, const KeyCombination& skip) { m_messageManager.setKey(submit); m_skip = skip; return *this; } Novel& setKey(const KeyCombination& submit, const KeyCombination& skip, const KeyCombination& up, const KeyCombination& down) { m_messageManager.setKey(submit); m_choiceManager.setKey(submit, up, down); m_skip = skip; return *this; } Novel& setButton(std::unique_ptr<IMessageButton>&& button) { m_messageManager.setButton(std::move(button)); return *this; } template <class Type> Novel& setButton(const Type& button) { return setButton(static_cast<std::unique_ptr<IMessageButton>>(std::make_unique<Type>(button))); } Novel& setFont(const FontAssetName& text) { return setFont(text, text); } Novel& setFont(const FontAssetName& text, const FontAssetName& name = L"") { m_messageManager.setFont(text, name); m_choiceManager.setFont(text); return *this; } Novel& setColor(const Color& color, const Color& selectedColor = Palette::Red) { m_messageManager.setColor(color); m_choiceManager.setColor(color, selectedColor); return *this; } Novel& setMessageTexture(const TextureAssetName& texture, const Rect& region) { m_messageManager.setTexture(texture, region); return *this; } Novel& setMessagePosition(const Point& text, const Point& name = Point::Zero) { m_messageManager.setPosition(text, name); return *this; } Novel& setChoiceTexture(const TextureAssetName texture, const Rect& region) { m_choiceManager.setTexture(texture, region); return *this; } Novel& setChoicePosition(const Point& position) { m_choiceManager.setPosition(position); return *this; } Novel& setBGMVolume(double volume) { m_soundManager.setBGMVolume(volume); return *this; } Novel& setSEVolume(double volume) { m_soundManager.setSEVolume(volume); return *this; } Novel& setSound(const SoundAssetName& charCount) { m_soundManager.setSE(charCount); return *this; } Novel& setSound(const SoundAssetName& charCount, const SoundAssetName& move, const SoundAssetName& submit) { m_soundManager.setSE(charCount, move, submit); return *this; } Novel& setSilentChars(const Array<wchar> silentChars) { m_messageManager.setSilentChars(silentChars); return *this; } }; }
Fix skip.
Fix skip.
C++
mit
ChunChunMorning/AscNovel,ChunChunMorning/AscNovel-Siv3D
d6d8e58ac6e80cc4a942276fb9b4d2f71a030fcd
src/lfwatch_osx.cpp
src/lfwatch_osx.cpp
#ifdef __APPLE__ #include <iostream> #include <string> #include <map> #include <functional> #include <CoreServices/CoreServices.h> #include "lfwatch_osx.h" namespace lfw { //Remap our notify enums to match OS X event flags, we really just need to //convert our old/new name values but to avoid any future conflicts we remap all of it uint32_t remap_file_notify(uint32_t mask){ uint32_t remap = 0; if (mask & Notify::FILE_MODIFIED){ remap |= Notify::FILE_MODIFIED; } if (mask & Notify::FILE_CREATED){ remap |= Notify::FILE_CREATED; } if (mask & Notify::FILE_REMOVED){ remap |= Notify::FILE_REMOVED; } if (mask & FILE_RENAMED_OLD_NAME || mask & FILE_RENAMED_NEW_NAME){ remap |= kFSEventStreamEventFlagItemRenamed; } return remap; } void watch_callback(ConstFSEventStreamRef stream, void *data, size_t n_events, void *event_paths, const FSEventStreamEventFlags flags[], const FSEventStreamEventId ids[]) { //Tracks if we're looking for a new name event or not bool renaming = false; WatchData *watch = static_cast<WatchData*>(data); char **paths = static_cast<char**>(event_paths); for (size_t i = 0; i < n_events; ++i){ //OS X just sends all events so we filter here if (flags[i] & remap_file_notify(watch->filter)){ //OS X sends full path so get the filename out std::string fname{paths[i]}; fname = fname.substr(fname.find_last_of('/') + 1); uint32_t action = flags[i]; //Check if it's a rename event and what type of rename we're expecting, ie. old/new name if (flags[i] & kFSEventStreamEventFlagItemRenamed){ if (!renaming){ renaming = true; if (watch->filter & Notify::FILE_RENAMED_OLD_NAME){ action = Notify::FILE_RENAMED_OLD_NAME; } } else { renaming = false; if (watch->filter & Notify::FILE_RENAMED_NEW_NAME){ action = Notify::FILE_RENAMED_NEW_NAME; } } } watch->callback(EventData{watch->dir_name, fname, watch->filter, action}); } } } //Make and schedule a stream, the stream will use the watch as its context info void make_stream(WatchData &watch){ CFStringRef cfdir = CFStringCreateWithCString(nullptr, watch.dir_name.c_str(), kCFStringEncodingUTF8); CFArrayRef cfdirs = CFArrayCreate(nullptr, (const void**)&cfdir, 1, nullptr); FSEventStreamContext ctx = { 0, &watch, nullptr, nullptr, nullptr }; watch.stream = FSEventStreamCreate(NULL, &watch_callback, &ctx, cfdirs, kFSEventStreamEventIdSinceNow, 1.0, kFSEventStreamCreateFlagFileEvents | kFSEventStreamCreateFlagNoDefer); FSEventStreamScheduleWithRunLoop(watch.stream, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode); FSEventStreamStart(watch.stream); CFRelease(cfdir); CFRelease(cfdirs); } void cancel(WatchData &watch){ //Probably should just do this in destructor FSEventStreamStop(watch.stream); FSEventStreamInvalidate(watch.stream); FSEventStreamRelease(watch.stream); } WatchData::WatchData(const std::string &dir, uint32_t filter, const Callback &cb) : dir_name(dir), filter(filter), callback(cb) {} WatchOSX::WatchOSX(){} WatchOSX::~WatchOSX(){ for (auto &pair : watchers){ cancel(pair.second); } } void WatchOSX::watch(const std::string &dir, uint32_t filters, const Callback &callback){ auto fnd = watchers.find(dir); if (fnd != watchers.end()){ fnd->second.filter = filters; fnd->second.callback = callback; return; } auto it = watchers.emplace(std::make_pair(dir, WatchData{dir, filters, callback})); make_stream(it.first->second); } void WatchOSX::remove(const std::string &dir){ auto fnd = watchers.find(dir); if (fnd != watchers.end()){ cancel(fnd->second); watchers.erase(fnd); } } void WatchOSX::update(){ CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, true); } } #endif
#ifdef __APPLE__ #include <iostream> #include <string> #include <map> #include <functional> #include <CoreServices/CoreServices.h> #include "lfwatch_osx.h" namespace lfw { //Remap our notify enums to match OS X event flags, we really just need to //convert our old/new name values but to avoid any future conflicts we remap all of it uint32_t remap_file_notify(uint32_t mask){ uint32_t remap = 0; if (mask & Notify::FILE_MODIFIED){ remap |= Notify::FILE_MODIFIED; } if (mask & Notify::FILE_CREATED){ remap |= Notify::FILE_CREATED; } if (mask & Notify::FILE_REMOVED){ remap |= Notify::FILE_REMOVED; } if (mask & FILE_RENAMED_OLD_NAME || mask & FILE_RENAMED_NEW_NAME){ remap |= kFSEventStreamEventFlagItemRenamed; } return remap; } void watch_callback(ConstFSEventStreamRef stream, void *data, size_t n_events, void *event_paths, const FSEventStreamEventFlags flags[], const FSEventStreamEventId ids[]) { //Tracks if we're looking for a new name event or not bool renaming = false; WatchData *watch = static_cast<WatchData*>(data); char **paths = static_cast<char**>(event_paths); for (size_t i = 0; i < n_events; ++i){ //OS X just sends all events so we filter here if (flags[i] & remap_file_notify(watch->filter)){ //OS X sends full path so get the filename out std::string fname{paths[i]}; fname = fname.substr(fname.find_last_of('/') + 1); uint32_t action = flags[i]; //Check if it's a rename event and what type of rename we're expecting, ie. old/new name if (flags[i] & kFSEventStreamEventFlagItemRenamed){ if (!renaming){ renaming = true; if (watch->filter & Notify::FILE_RENAMED_OLD_NAME){ action = Notify::FILE_RENAMED_OLD_NAME; } } else { renaming = false; if (watch->filter & Notify::FILE_RENAMED_NEW_NAME){ action = Notify::FILE_RENAMED_NEW_NAME; } } } watch->callback(EventData{watch->dir_name, fname, watch->filter, action}); } } } //Make and schedule a stream, the stream will use the watch as its context info void make_stream(WatchData &watch){ CFStringRef cfdir = CFStringCreateWithCString(nullptr, watch.dir_name.c_str(), kCFStringEncodingUTF8); CFArrayRef cfdirs = CFArrayCreate(nullptr, (const void**)&cfdir, 1, nullptr); FSEventStreamContext ctx = { 0, &watch, nullptr, nullptr, nullptr }; watch.stream = FSEventStreamCreate(NULL, &watch_callback, &ctx, cfdirs, kFSEventStreamEventIdSinceNow, 1.0, kFSEventStreamCreateFlagFileEvents | kFSEventStreamCreateFlagNoDefer); FSEventStreamScheduleWithRunLoop(watch.stream, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode); FSEventStreamStart(watch.stream); CFRelease(cfdir); CFRelease(cfdirs); } void cancel(WatchData &watch){ FSEventStreamStop(watch.stream); FSEventStreamInvalidate(watch.stream); FSEventStreamRelease(watch.stream); } WatchData::WatchData(const std::string &dir, uint32_t filter, const Callback &cb) : dir_name(dir), filter(filter), callback(cb) {} WatchOSX::WatchOSX(){} WatchOSX::~WatchOSX(){ for (auto &pair : watchers){ cancel(pair.second); } } void WatchOSX::watch(const std::string &dir, uint32_t filters, const Callback &callback){ auto fnd = watchers.find(dir); if (fnd != watchers.end()){ fnd->second.filter = filters; fnd->second.callback = callback; return; } auto it = watchers.emplace(std::make_pair(dir, WatchData{dir, filters, callback})); make_stream(it.first->second); } void WatchOSX::remove(const std::string &dir){ auto fnd = watchers.find(dir); if (fnd != watchers.end()){ cancel(fnd->second); watchers.erase(fnd); } } void WatchOSX::update(){ CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, true); } } #endif
Comment clean-up
Comment clean-up
C++
mit
Twinklebear/lfwatch
bf5db221e9b856d03e73ccdfa5807baf5e36c285
src/lib/KEYText.cpp
src/lib/KEYText.cpp
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* * This file is part of the libetonyek project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <cassert> #include <libwpd/libwpd.h> #include <libetonyek/KEYPresentationInterface.h> #include "KEYOutput.h" #include "KEYPath.h" #include "KEYText.h" #include "KEYTypes.h" using std::string; namespace libetonyek { struct KEYText::Paragraph { KEYParagraphStylePtr_t style; KEYObjectList_t objects; Paragraph(); }; namespace { class TextSpanObject : public KEYObject { public: TextSpanObject(const KEYCharacterStylePtr_t &style, const string &text); private: virtual void draw(const KEYOutput &output); private: const KEYCharacterStylePtr_t m_style; const string m_text; }; TextSpanObject::TextSpanObject(const KEYCharacterStylePtr_t &style, const string &text) : m_style(style) , m_text(text) { } void TextSpanObject::draw(const KEYOutput &output) { WPXPropertyList props; // TODO: fill properties output.getPainter()->setStyle(WPXPropertyList(), WPXPropertyListVector()); output.getPainter()->openSpan(props); output.getPainter()->insertText(WPXString(m_text.c_str())); output.getPainter()->closeSpan(); } } namespace { class TabObject : public KEYObject { private: virtual void draw(const KEYOutput &output); }; void TabObject::draw(const KEYOutput &output) { output.getPainter()->openSpan(WPXPropertyList()); output.getPainter()->insertTab(); output.getPainter()->closeSpan(); } } namespace { class LineBreakObject : public KEYObject { public: explicit LineBreakObject(const KEYParagraphStylePtr_t &paraStyle); private: virtual void draw(const KEYOutput &output); private: const KEYParagraphStylePtr_t m_paraStyle; }; LineBreakObject::LineBreakObject(const KEYParagraphStylePtr_t &paraStyle) : m_paraStyle(paraStyle) { } void LineBreakObject::draw(const KEYOutput &output) { WPXPropertyList props; // TODO: fill from m_paraStyle output.getPainter()->closeParagraph(); output.getPainter()->openParagraph(props, WPXPropertyListVector()); } } namespace { class TextObject : public KEYObject { public: TextObject(const KEYLayoutStylePtr_t &layoutStyle, const KEYGeometryPtr_t &boundingBox, const KEYText::ParagraphList_t &paragraphs); private: virtual void draw(const KEYOutput &output); private: const KEYLayoutStylePtr_t m_layoutStyle; const KEYGeometryPtr_t m_boundingBox; const KEYText::ParagraphList_t m_paragraphs; }; TextObject::TextObject(const KEYLayoutStylePtr_t &layoutStyle, const KEYGeometryPtr_t &boundingBox, const KEYText::ParagraphList_t &paragraphs) : m_layoutStyle(layoutStyle) , m_boundingBox(boundingBox) , m_paragraphs(paragraphs) { } void TextObject::draw(const KEYOutput &output) { const KEYTransformation tr = output.getTransformation(); WPXPropertyList props; if (bool(m_boundingBox)) { double x = m_boundingBox->position.x; double y = m_boundingBox->position.y; double w = m_boundingBox->naturalSize.width; double h = m_boundingBox->naturalSize.height; tr(x, y); tr(w, h, true); props.insert("svg:x", pt2in(x)); props.insert("svg:y", pt2in(y)); props.insert("svg:width", pt2in(w)); props.insert("svg:height", pt2in(h)); } KEYPath path; path.appendMoveTo(0, 0); path.appendLineTo(0, 1); path.appendLineTo(1, 1); path.appendLineTo(1, 0); path.appendClose(); path *= tr; output.getPainter()->startTextObject(props, path.toWPG()); for(KEYText::ParagraphList_t::const_iterator it = m_paragraphs.begin(); m_paragraphs.end() != it; ++it) { output.getPainter()->openParagraph(WPXPropertyList(), WPXPropertyListVector()); drawAll((*it)->objects, output); output.getPainter()->closeParagraph(); } output.getPainter()->endTextObject(); } } KEYText::KEYText() : m_layoutStyle() , m_paragraphs() , m_currentParagraph() , m_lineBreaks(0) , m_boundingBox() { } KEYText::Paragraph::Paragraph() : style() , objects() { } void KEYText::setLayoutStyle(const KEYLayoutStylePtr_t &style) { m_layoutStyle = style; } const KEYGeometryPtr_t &KEYText::getBoundingBox() const { return m_boundingBox; } void KEYText::setBoundingBox(const KEYGeometryPtr_t &boundingBox) { m_boundingBox = boundingBox; } void KEYText::openParagraph(const KEYParagraphStylePtr_t &style) { assert(!m_currentParagraph); m_currentParagraph.reset(new Paragraph()); m_currentParagraph->style = style; } void KEYText::closeParagraph() { assert(bool(m_currentParagraph)); m_paragraphs.push_back(m_currentParagraph); m_currentParagraph.reset(); } void KEYText::insertText(const std::string &text, const KEYCharacterStylePtr_t &style) { assert(bool(m_currentParagraph)); const KEYObjectPtr_t object(new TextSpanObject(style, text)); m_currentParagraph->objects.push_back(object); } void KEYText::insertTab() { assert(bool(m_currentParagraph)); const KEYObjectPtr_t object(new TabObject()); m_currentParagraph->objects.push_back(object); } void KEYText::insertLineBreak() { assert(bool(m_currentParagraph)); ++m_lineBreaks; } const KEYLayoutStylePtr_t &KEYText::getLayoutStyle() const { return m_layoutStyle; } const KEYText::ParagraphList_t &KEYText::getParagraphs() const { return m_paragraphs; } void KEYText::insertDeferredLineBreaks() { assert(bool(m_currentParagraph)); if (0 < m_lineBreaks) { const KEYObjectPtr_t object(new LineBreakObject(m_currentParagraph->style)); m_currentParagraph->objects.insert(m_currentParagraph->objects.end(), m_lineBreaks, object); m_lineBreaks = 0; } } bool KEYText::empty() const { return m_paragraphs.empty(); } KEYObjectPtr_t makeObject(const KEYTextPtr_t &text) { const KEYObjectPtr_t object(new TextObject(text->getLayoutStyle(), text->getBoundingBox(), text->getParagraphs())); return object; } } /* vim:set shiftwidth=2 softtabstop=2 expandtab: */
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* * This file is part of the libetonyek project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <cassert> #include <libwpd/libwpd.h> #include <libetonyek/KEYPresentationInterface.h> #include "KEYOutput.h" #include "KEYPath.h" #include "KEYText.h" #include "KEYTypes.h" using std::string; namespace libetonyek { struct KEYText::Paragraph { KEYParagraphStylePtr_t style; KEYObjectList_t objects; Paragraph(); }; namespace { class TextSpanObject : public KEYObject { public: TextSpanObject(const KEYCharacterStylePtr_t &style, const string &text); private: virtual void draw(const KEYOutput &output); private: const KEYCharacterStylePtr_t m_style; const string m_text; }; TextSpanObject::TextSpanObject(const KEYCharacterStylePtr_t &style, const string &text) : m_style(style) , m_text(text) { } void TextSpanObject::draw(const KEYOutput &output) { WPXPropertyList props; // TODO: fill properties output.getPainter()->setStyle(WPXPropertyList(), WPXPropertyListVector()); output.getPainter()->openSpan(props); output.getPainter()->insertText(WPXString(m_text.c_str())); output.getPainter()->closeSpan(); } } namespace { class TabObject : public KEYObject { private: virtual void draw(const KEYOutput &output); }; void TabObject::draw(const KEYOutput &output) { output.getPainter()->openSpan(WPXPropertyList()); output.getPainter()->insertTab(); output.getPainter()->closeSpan(); } } namespace { class LineBreakObject : public KEYObject { public: explicit LineBreakObject(const KEYParagraphStylePtr_t &paraStyle); private: virtual void draw(const KEYOutput &output); private: const KEYParagraphStylePtr_t m_paraStyle; }; LineBreakObject::LineBreakObject(const KEYParagraphStylePtr_t &paraStyle) : m_paraStyle(paraStyle) { } void LineBreakObject::draw(const KEYOutput &output) { WPXPropertyList props; // TODO: fill from m_paraStyle output.getPainter()->closeParagraph(); output.getPainter()->openParagraph(props, WPXPropertyListVector()); } } namespace { class TextObject : public KEYObject { public: TextObject(const KEYLayoutStylePtr_t &layoutStyle, const KEYGeometryPtr_t &boundingBox, const KEYText::ParagraphList_t &paragraphs); private: virtual void draw(const KEYOutput &output); private: const KEYLayoutStylePtr_t m_layoutStyle; const KEYGeometryPtr_t m_boundingBox; const KEYText::ParagraphList_t m_paragraphs; }; TextObject::TextObject(const KEYLayoutStylePtr_t &layoutStyle, const KEYGeometryPtr_t &boundingBox, const KEYText::ParagraphList_t &paragraphs) : m_layoutStyle(layoutStyle) , m_boundingBox(boundingBox) , m_paragraphs(paragraphs) { } void TextObject::draw(const KEYOutput &output) { const KEYTransformation tr = output.getTransformation(); WPXPropertyList props; double x = 0; double y = 0; tr(x, y); props.insert("svg:x", pt2in(x)); props.insert("svg:y", pt2in(y)); if (bool(m_boundingBox)) { double w = m_boundingBox->naturalSize.width; double h = m_boundingBox->naturalSize.height; tr(w, h, true); props.insert("svg:width", pt2in(w)); props.insert("svg:height", pt2in(h)); } KEYPath path; path.appendMoveTo(0, 0); path.appendLineTo(0, 1); path.appendLineTo(1, 1); path.appendLineTo(1, 0); path.appendClose(); path *= tr; output.getPainter()->startTextObject(props, path.toWPG()); for(KEYText::ParagraphList_t::const_iterator it = m_paragraphs.begin(); m_paragraphs.end() != it; ++it) { output.getPainter()->openParagraph(WPXPropertyList(), WPXPropertyListVector()); drawAll((*it)->objects, output); output.getPainter()->closeParagraph(); } output.getPainter()->endTextObject(); } } KEYText::KEYText() : m_layoutStyle() , m_paragraphs() , m_currentParagraph() , m_lineBreaks(0) , m_boundingBox() { } KEYText::Paragraph::Paragraph() : style() , objects() { } void KEYText::setLayoutStyle(const KEYLayoutStylePtr_t &style) { m_layoutStyle = style; } const KEYGeometryPtr_t &KEYText::getBoundingBox() const { return m_boundingBox; } void KEYText::setBoundingBox(const KEYGeometryPtr_t &boundingBox) { m_boundingBox = boundingBox; } void KEYText::openParagraph(const KEYParagraphStylePtr_t &style) { assert(!m_currentParagraph); m_currentParagraph.reset(new Paragraph()); m_currentParagraph->style = style; } void KEYText::closeParagraph() { assert(bool(m_currentParagraph)); m_paragraphs.push_back(m_currentParagraph); m_currentParagraph.reset(); } void KEYText::insertText(const std::string &text, const KEYCharacterStylePtr_t &style) { assert(bool(m_currentParagraph)); const KEYObjectPtr_t object(new TextSpanObject(style, text)); m_currentParagraph->objects.push_back(object); } void KEYText::insertTab() { assert(bool(m_currentParagraph)); const KEYObjectPtr_t object(new TabObject()); m_currentParagraph->objects.push_back(object); } void KEYText::insertLineBreak() { assert(bool(m_currentParagraph)); ++m_lineBreaks; } const KEYLayoutStylePtr_t &KEYText::getLayoutStyle() const { return m_layoutStyle; } const KEYText::ParagraphList_t &KEYText::getParagraphs() const { return m_paragraphs; } void KEYText::insertDeferredLineBreaks() { assert(bool(m_currentParagraph)); if (0 < m_lineBreaks) { const KEYObjectPtr_t object(new LineBreakObject(m_currentParagraph->style)); m_currentParagraph->objects.insert(m_currentParagraph->objects.end(), m_lineBreaks, object); m_lineBreaks = 0; } } bool KEYText::empty() const { return m_paragraphs.empty(); } KEYObjectPtr_t makeObject(const KEYTextPtr_t &text) { const KEYObjectPtr_t object(new TextObject(text->getLayoutStyle(), text->getBoundingBox(), text->getParagraphs())); return object; } } /* vim:set shiftwidth=2 softtabstop=2 expandtab: */
fix position of text in shape
fix position of text in shape The position is already determined by the current transformation; we only need width and height.
C++
mpl-2.0
freedesktop-unofficial-mirror/libreoffice__libetonyek,freedesktop-unofficial-mirror/libreoffice__libetonyek,LibreOffice/libetonyek,freedesktop-unofficial-mirror/libreoffice__libetonyek,LibreOffice/libetonyek,LibreOffice/libetonyek
56ea21333bf2b9c5140c8c322cfae4ac4fe41c51
modules/planning/scenarios/side_pass/stage_stop_on_wait_point.cc
modules/planning/scenarios/side_pass/stage_stop_on_wait_point.cc
/****************************************************************************** * Copyright 2018 The Apollo 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. *****************************************************************************/ /** * @file **/ #include "modules/planning/scenarios/side_pass/stage_stop_on_wait_point.h" #include <algorithm> #include <vector> #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/proto/pnc_point.pb.h" #include "modules/planning/common/frame.h" #include "modules/planning/common/obstacle_blocking_analyzer.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/common/speed_profile_generator.h" namespace apollo { namespace planning { namespace scenario { namespace side_pass { using apollo::common::PathPoint; using apollo::common::TrajectoryPoint; using apollo::common::math::Vec2d; constexpr double kSExtraMarginforStopOnWaitPointStage = 3.0; constexpr double kLExtraMarginforStopOnWaitPointStage = 0.4; Stage::StageStatus StageStopOnWaitPoint::Process( const TrajectoryPoint& planning_start_point, Frame* frame) { ADEBUG << "SIDEPASS: Stopping on wait point."; // Sanity checks. const ReferenceLineInfo& reference_line_info = frame->reference_line_info().front(); const ReferenceLine& reference_line = reference_line_info.reference_line(); const PathDecision& path_decision = reference_line_info.path_decision(); if (GetContext()->path_data_.discretized_path().empty()) { AERROR << "path data is empty."; return Stage::ERROR; } if (!GetContext()->path_data_.UpdateFrenetFramePath(&reference_line)) { return Stage::ERROR; } const auto adc_frenet_frame_point_ = reference_line.GetFrenetPoint(frame->PlanningStartPoint().path_point()); if (!GetContext()->path_data_.LeftTrimWithRefS(adc_frenet_frame_point_)) { return Stage::ERROR; } if (GetContext()->path_data_.discretized_path().empty()) { AERROR << "path data is empty after trim."; return Stage::ERROR; } for (const auto& p : GetContext()->path_data_.discretized_path()) { ADEBUG << p.ShortDebugString(); } // Get the nearest obstacle. // If the nearest obstacle, provided it exists, is moving, // then quit the side_pass stage. const Obstacle* nearest_obstacle = nullptr; if (!GetTheNearestObstacle(*frame, path_decision.obstacles(), &nearest_obstacle)) { AERROR << "Failed while running the function to get nearest obstacle."; return Stage::ERROR; } if (nearest_obstacle) { if (nearest_obstacle->speed() > GetContext()->scenario_config_.block_obstacle_min_speed()) { ADEBUG << "The nearest obstacle to side-pass is moving."; next_stage_ = ScenarioConfig::NO_STAGE; return Stage::FINISHED; } } ADEBUG << "Got the nearest obstacle if there is one."; // Get the "wait point". PathPoint first_path_point = GetContext()->path_data_.discretized_path().front(); PathPoint last_path_point; bool should_not_move_at_all = false; if (!GetMoveForwardLastPathPoint(reference_line, nearest_obstacle, &last_path_point, &should_not_move_at_all)) { ADEBUG << "Fail to get move forward last path point."; return Stage::ERROR; } if (should_not_move_at_all) { ADEBUG << "The ADC is already at a stop point."; next_stage_ = ScenarioConfig::SIDE_PASS_DETECT_SAFETY; return Stage::FINISHED; // return FINISHED if it's already at "wait point". } ADEBUG << "first_path_point: " << first_path_point.ShortDebugString(); ADEBUG << "last_path_point : " << last_path_point.ShortDebugString(); double move_forward_distance = last_path_point.s() - first_path_point.s(); ADEBUG << "move_forward_distance: " << move_forward_distance; // Wait until everything is clear. if (!IsFarAwayFromObstacles(reference_line, path_decision.obstacles(), first_path_point, last_path_point)) { // Wait here, do nothing this cycle. auto& rfl_info = frame->mutable_reference_line_info()->front(); *(rfl_info.mutable_path_data()) = GetContext()->path_data_; *(rfl_info.mutable_speed_data()) = SpeedProfileGenerator::GenerateFallbackSpeedProfile(); rfl_info.set_trajectory_type(ADCTrajectory::NORMAL); DiscretizedTrajectory trajectory; if (!rfl_info.CombinePathAndSpeedProfile( frame->PlanningStartPoint().relative_time(), frame->PlanningStartPoint().path_point().s(), &trajectory)) { AERROR << "Fail to aggregate planning trajectory."; return Stage::RUNNING; } rfl_info.SetTrajectory(trajectory); rfl_info.SetDrivable(true); ADEBUG << "Waiting until obstacles are far away."; return Stage::RUNNING; } // Proceed to the proper wait point, and stop there. // 1. call proceed with cautious constexpr double kSidePassCreepSpeed = 2.33; // m/s auto& rfl_info = frame->mutable_reference_line_info()->front(); *(rfl_info.mutable_speed_data()) = SpeedProfileGenerator::GenerateFixedDistanceCreepProfile( move_forward_distance, kSidePassCreepSpeed); for (const auto& sd : *rfl_info.mutable_speed_data()) { ADEBUG << sd.ShortDebugString(); } // 2. Combine path and speed. *(rfl_info.mutable_path_data()) = GetContext()->path_data_; rfl_info.set_trajectory_type(ADCTrajectory::NORMAL); DiscretizedTrajectory trajectory; if (!rfl_info.CombinePathAndSpeedProfile( frame->PlanningStartPoint().relative_time(), frame->PlanningStartPoint().path_point().s(), &trajectory)) { AERROR << "Fail to aggregate planning trajectory."; return Stage::RUNNING; } rfl_info.SetTrajectory(trajectory); rfl_info.SetDrivable(true); // If it arrives at the wait point, switch to SIDE_PASS_DETECT_SAFETY. constexpr double kBuffer = 0.3; if (move_forward_distance < kBuffer) { next_stage_ = ScenarioConfig::SIDE_PASS_DETECT_SAFETY; } return Stage::FINISHED; } bool StageStopOnWaitPoint::IsFarAwayFromObstacles( const ReferenceLine& reference_line, const IndexedList<std::string, Obstacle>& indexed_obstacle_list, const PathPoint& first_path_point, const PathPoint& last_path_point) { common::SLPoint first_sl_point; if (!reference_line.XYToSL(Vec2d(first_path_point.x(), first_path_point.y()), &first_sl_point)) { AERROR << "Failed to get the projection from TrajectoryPoint onto " "reference_line"; return false; } common::SLPoint last_sl_point; if (!reference_line.XYToSL(Vec2d(last_path_point.x(), last_path_point.y()), &last_sl_point)) { AERROR << "Failed to get the projection from TrajectoryPoint onto " "reference_line"; return false; } // Go through every obstacle, check if there is any in the no_obs_zone; // the no_obs_zone must be clear for successful proceed_with_caution. for (const auto* obstacle : indexed_obstacle_list.Items()) { if (obstacle->IsVirtual()) { continue; } // Check the s-direction. double obs_start_s = obstacle->PerceptionSLBoundary().start_s(); double obs_end_s = obstacle->PerceptionSLBoundary().end_s(); if (obs_end_s < first_sl_point.s() || obs_start_s > last_sl_point.s() + kSExtraMarginforStopOnWaitPointStage) { continue; } // Check the l-direction. double lane_left_width_at_start_s = 0.0; double lane_left_width_at_end_s = 0.0; double lane_right_width_at_start_s = 0.0; double lane_right_width_at_end_s = 0.0; reference_line.GetLaneWidth(obs_start_s, &lane_left_width_at_start_s, &lane_right_width_at_start_s); reference_line.GetLaneWidth(obs_end_s, &lane_left_width_at_end_s, &lane_right_width_at_end_s); double lane_left_width = std::min(std::abs(lane_left_width_at_start_s), std::abs(lane_left_width_at_end_s)); double lane_right_width = std::min(std::abs(lane_right_width_at_start_s), std::abs(lane_right_width_at_end_s)); double obs_start_l = obstacle->PerceptionSLBoundary().start_l(); double obs_end_l = obstacle->PerceptionSLBoundary().end_l(); if (obs_start_l < lane_left_width && -obs_end_l < lane_right_width) { return false; } } return true; } bool StageStopOnWaitPoint::GetTheNearestObstacle( const Frame& frame, const IndexedList<std::string, Obstacle>& indexed_obstacle_list, const Obstacle** nearest_obstacle) { // Sanity checks. if (frame.reference_line_info().size() > 1) { return false; } *nearest_obstacle = nullptr; // Get the closest front blocking obstacle. double distance_to_closest_blocking_obstacle = -100.0; bool exists_a_blocking_obstacle = false; for (const auto* obstacle : indexed_obstacle_list.Items()) { if (IsBlockingObstacleToSidePass( frame, obstacle, GetContext()->scenario_config_.block_obstacle_min_speed(), GetContext()->scenario_config_.min_front_obstacle_distance(), GetContext()->scenario_config_.enable_obstacle_blocked_check())) { exists_a_blocking_obstacle = true; double distance_between_adc_and_obstacle = GetDistanceBetweenADCAndObstacle(frame, obstacle); if (distance_to_closest_blocking_obstacle < 0.0 || distance_between_adc_and_obstacle < distance_to_closest_blocking_obstacle) { distance_to_closest_blocking_obstacle = distance_between_adc_and_obstacle; *nearest_obstacle = obstacle; } } } return exists_a_blocking_obstacle; } bool StageStopOnWaitPoint::GetMoveForwardLastPathPoint( const ReferenceLine& reference_line, const Obstacle* nearest_obstacle, PathPoint* const last_path_point, bool* should_not_move_at_all) { *should_not_move_at_all = false; int count = 0; bool exist_nearest_obs = (nearest_obstacle != nullptr); double s_max = 0.0; if (exist_nearest_obs) { ADEBUG << "There exists a nearest obstacle."; s_max = nearest_obstacle->PerceptionSLBoundary().start_s(); } for (const auto& path_point : GetContext()->path_data_.discretized_path()) { // Get the four corner points ABCD of ADC at every path point, // and keep checking until it gets out of the current lane or // reaches the nearest obstacle (in the same lane) ahead. const auto& vehicle_box = common::VehicleConfigHelper::Instance()->GetBoundingBox(path_point); std::vector<Vec2d> ABCDpoints = vehicle_box.GetAllCorners(); bool is_out_of_curr_lane = false; for (size_t i = 0; i < ABCDpoints.size(); i++) { // For each corner point, project it onto reference_line common::SLPoint curr_point_sl; if (!reference_line.XYToSL(ABCDpoints[i], &curr_point_sl)) { AERROR << "Failed to get the projection from point onto " "reference_line"; return false; } // Get the lane width at the current s indicated by path_point double curr_point_left_width = 0.0; double curr_point_right_width = 0.0; reference_line.GetLaneWidth(curr_point_sl.s(), &curr_point_left_width, &curr_point_right_width); // Check if this corner point is within the lane: if (curr_point_sl.l() > std::abs(curr_point_left_width) - kLExtraMarginforStopOnWaitPointStage || curr_point_sl.l() < -std::abs(curr_point_right_width) + kLExtraMarginforStopOnWaitPointStage) { is_out_of_curr_lane = true; break; } // Check if this corner point is before the nearest obstacle: if (exist_nearest_obs && curr_point_sl.s() > s_max) { is_out_of_curr_lane = true; break; } } if (is_out_of_curr_lane) { if (count == 0) { // The current ADC, without moving at all, is already at least // partially out of the current lane. *should_not_move_at_all = true; return true; } break; } else { *last_path_point = path_point; } CHECK_GE(path_point.s(), 0.0); ++count; } return true; } } // namespace side_pass } // namespace scenario } // namespace planning } // namespace apollo
/****************************************************************************** * Copyright 2018 The Apollo 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. *****************************************************************************/ /** * @file **/ #include "modules/planning/scenarios/side_pass/stage_stop_on_wait_point.h" #include <algorithm> #include <vector> #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/proto/pnc_point.pb.h" #include "modules/planning/common/frame.h" #include "modules/planning/common/obstacle_blocking_analyzer.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/common/speed_profile_generator.h" namespace apollo { namespace planning { namespace scenario { namespace side_pass { using apollo::common::PathPoint; using apollo::common::TrajectoryPoint; using apollo::common::math::Vec2d; constexpr double kSExtraMarginforStopOnWaitPointStage = 3.0; constexpr double kLExtraMarginforStopOnWaitPointStage = 0.4; Stage::StageStatus StageStopOnWaitPoint::Process( const TrajectoryPoint& planning_start_point, Frame* frame) { ADEBUG << "SIDEPASS: Stopping on wait point."; // Sanity checks. const ReferenceLineInfo& reference_line_info = frame->reference_line_info().front(); const ReferenceLine& reference_line = reference_line_info.reference_line(); const PathDecision& path_decision = reference_line_info.path_decision(); if (GetContext()->path_data_.discretized_path().empty()) { AERROR << "path data is empty."; return Stage::ERROR; } if (!GetContext()->path_data_.UpdateFrenetFramePath(&reference_line)) { return Stage::ERROR; } const auto adc_frenet_frame_point_ = reference_line.GetFrenetPoint(frame->PlanningStartPoint().path_point()); if (!GetContext()->path_data_.LeftTrimWithRefS(adc_frenet_frame_point_)) { return Stage::ERROR; } if (GetContext()->path_data_.discretized_path().empty()) { AERROR << "path data is empty after trim."; return Stage::ERROR; } for (const auto& p : GetContext()->path_data_.discretized_path()) { ADEBUG << p.ShortDebugString(); } // Get the nearest obstacle. // If the nearest obstacle, provided it exists, is moving, // then quit the side_pass stage. const Obstacle* nearest_obstacle = nullptr; if (!GetTheNearestObstacle(*frame, path_decision.obstacles(), &nearest_obstacle)) { AERROR << "Failed while running the function to get nearest obstacle."; next_stage_ = ScenarioConfig::SIDE_PASS_BACKUP; return Stage::FINISHED; } if (nearest_obstacle) { if (nearest_obstacle->speed() > GetContext()->scenario_config_.block_obstacle_min_speed()) { ADEBUG << "The nearest obstacle to side-pass is moving."; next_stage_ = ScenarioConfig::NO_STAGE; return Stage::FINISHED; } } ADEBUG << "Got the nearest obstacle if there is one."; // Get the "wait point". PathPoint first_path_point = GetContext()->path_data_.discretized_path().front(); PathPoint last_path_point; bool should_not_move_at_all = false; if (!GetMoveForwardLastPathPoint(reference_line, nearest_obstacle, &last_path_point, &should_not_move_at_all)) { ADEBUG << "Fail to get move forward last path point."; return Stage::ERROR; } if (should_not_move_at_all) { ADEBUG << "The ADC is already at a stop point."; next_stage_ = ScenarioConfig::SIDE_PASS_DETECT_SAFETY; return Stage::FINISHED; // return FINISHED if it's already at "wait point". } ADEBUG << "first_path_point: " << first_path_point.ShortDebugString(); ADEBUG << "last_path_point : " << last_path_point.ShortDebugString(); double move_forward_distance = last_path_point.s() - first_path_point.s(); ADEBUG << "move_forward_distance: " << move_forward_distance; // Wait until everything is clear. if (!IsFarAwayFromObstacles(reference_line, path_decision.obstacles(), first_path_point, last_path_point)) { // Wait here, do nothing this cycle. auto& rfl_info = frame->mutable_reference_line_info()->front(); *(rfl_info.mutable_path_data()) = GetContext()->path_data_; *(rfl_info.mutable_speed_data()) = SpeedProfileGenerator::GenerateFallbackSpeedProfile(); rfl_info.set_trajectory_type(ADCTrajectory::NORMAL); DiscretizedTrajectory trajectory; if (!rfl_info.CombinePathAndSpeedProfile( frame->PlanningStartPoint().relative_time(), frame->PlanningStartPoint().path_point().s(), &trajectory)) { AERROR << "Fail to aggregate planning trajectory."; return Stage::RUNNING; } rfl_info.SetTrajectory(trajectory); rfl_info.SetDrivable(true); ADEBUG << "Waiting until obstacles are far away."; return Stage::RUNNING; } // Proceed to the proper wait point, and stop there. // 1. call proceed with cautious constexpr double kSidePassCreepSpeed = 2.33; // m/s auto& rfl_info = frame->mutable_reference_line_info()->front(); *(rfl_info.mutable_speed_data()) = SpeedProfileGenerator::GenerateFixedDistanceCreepProfile( move_forward_distance, kSidePassCreepSpeed); for (const auto& sd : *rfl_info.mutable_speed_data()) { ADEBUG << sd.ShortDebugString(); } // 2. Combine path and speed. *(rfl_info.mutable_path_data()) = GetContext()->path_data_; rfl_info.set_trajectory_type(ADCTrajectory::NORMAL); DiscretizedTrajectory trajectory; if (!rfl_info.CombinePathAndSpeedProfile( frame->PlanningStartPoint().relative_time(), frame->PlanningStartPoint().path_point().s(), &trajectory)) { AERROR << "Fail to aggregate planning trajectory."; return Stage::RUNNING; } rfl_info.SetTrajectory(trajectory); rfl_info.SetDrivable(true); // If it arrives at the wait point, switch to SIDE_PASS_DETECT_SAFETY. constexpr double kBuffer = 0.3; if (move_forward_distance < kBuffer) { next_stage_ = ScenarioConfig::SIDE_PASS_DETECT_SAFETY; } return Stage::FINISHED; } bool StageStopOnWaitPoint::IsFarAwayFromObstacles( const ReferenceLine& reference_line, const IndexedList<std::string, Obstacle>& indexed_obstacle_list, const PathPoint& first_path_point, const PathPoint& last_path_point) { common::SLPoint first_sl_point; if (!reference_line.XYToSL(Vec2d(first_path_point.x(), first_path_point.y()), &first_sl_point)) { AERROR << "Failed to get the projection from TrajectoryPoint onto " "reference_line"; return false; } common::SLPoint last_sl_point; if (!reference_line.XYToSL(Vec2d(last_path_point.x(), last_path_point.y()), &last_sl_point)) { AERROR << "Failed to get the projection from TrajectoryPoint onto " "reference_line"; return false; } // Go through every obstacle, check if there is any in the no_obs_zone; // the no_obs_zone must be clear for successful proceed_with_caution. for (const auto* obstacle : indexed_obstacle_list.Items()) { if (obstacle->IsVirtual()) { continue; } // Check the s-direction. double obs_start_s = obstacle->PerceptionSLBoundary().start_s(); double obs_end_s = obstacle->PerceptionSLBoundary().end_s(); if (obs_end_s < first_sl_point.s() || obs_start_s > last_sl_point.s() + kSExtraMarginforStopOnWaitPointStage) { continue; } // Check the l-direction. double lane_left_width_at_start_s = 0.0; double lane_left_width_at_end_s = 0.0; double lane_right_width_at_start_s = 0.0; double lane_right_width_at_end_s = 0.0; reference_line.GetLaneWidth(obs_start_s, &lane_left_width_at_start_s, &lane_right_width_at_start_s); reference_line.GetLaneWidth(obs_end_s, &lane_left_width_at_end_s, &lane_right_width_at_end_s); double lane_left_width = std::min(std::abs(lane_left_width_at_start_s), std::abs(lane_left_width_at_end_s)); double lane_right_width = std::min(std::abs(lane_right_width_at_start_s), std::abs(lane_right_width_at_end_s)); double obs_start_l = obstacle->PerceptionSLBoundary().start_l(); double obs_end_l = obstacle->PerceptionSLBoundary().end_l(); if (obs_start_l < lane_left_width && -obs_end_l < lane_right_width) { return false; } } return true; } bool StageStopOnWaitPoint::GetTheNearestObstacle( const Frame& frame, const IndexedList<std::string, Obstacle>& indexed_obstacle_list, const Obstacle** nearest_obstacle) { // Sanity checks. if (frame.reference_line_info().size() > 1) { return false; } *nearest_obstacle = nullptr; // Get the closest front blocking obstacle. double distance_to_closest_blocking_obstacle = -100.0; bool exists_a_blocking_obstacle = false; for (const auto* obstacle : indexed_obstacle_list.Items()) { if (IsBlockingObstacleToSidePass( frame, obstacle, GetContext()->scenario_config_.block_obstacle_min_speed(), GetContext()->scenario_config_.min_front_obstacle_distance(), GetContext()->scenario_config_.enable_obstacle_blocked_check())) { exists_a_blocking_obstacle = true; double distance_between_adc_and_obstacle = GetDistanceBetweenADCAndObstacle(frame, obstacle); if (distance_to_closest_blocking_obstacle < 0.0 || distance_between_adc_and_obstacle < distance_to_closest_blocking_obstacle) { distance_to_closest_blocking_obstacle = distance_between_adc_and_obstacle; *nearest_obstacle = obstacle; } } } return exists_a_blocking_obstacle; } bool StageStopOnWaitPoint::GetMoveForwardLastPathPoint( const ReferenceLine& reference_line, const Obstacle* nearest_obstacle, PathPoint* const last_path_point, bool* should_not_move_at_all) { *should_not_move_at_all = false; int count = 0; bool exist_nearest_obs = (nearest_obstacle != nullptr); double s_max = 0.0; if (exist_nearest_obs) { ADEBUG << "There exists a nearest obstacle."; s_max = nearest_obstacle->PerceptionSLBoundary().start_s(); } for (const auto& path_point : GetContext()->path_data_.discretized_path()) { // Get the four corner points ABCD of ADC at every path point, // and keep checking until it gets out of the current lane or // reaches the nearest obstacle (in the same lane) ahead. const auto& vehicle_box = common::VehicleConfigHelper::Instance()->GetBoundingBox(path_point); std::vector<Vec2d> ABCDpoints = vehicle_box.GetAllCorners(); bool is_out_of_curr_lane = false; for (size_t i = 0; i < ABCDpoints.size(); i++) { // For each corner point, project it onto reference_line common::SLPoint curr_point_sl; if (!reference_line.XYToSL(ABCDpoints[i], &curr_point_sl)) { AERROR << "Failed to get the projection from point onto " "reference_line"; return false; } // Get the lane width at the current s indicated by path_point double curr_point_left_width = 0.0; double curr_point_right_width = 0.0; reference_line.GetLaneWidth(curr_point_sl.s(), &curr_point_left_width, &curr_point_right_width); // Check if this corner point is within the lane: if (curr_point_sl.l() > std::abs(curr_point_left_width) - kLExtraMarginforStopOnWaitPointStage || curr_point_sl.l() < -std::abs(curr_point_right_width) + kLExtraMarginforStopOnWaitPointStage) { is_out_of_curr_lane = true; break; } // Check if this corner point is before the nearest obstacle: if (exist_nearest_obs && curr_point_sl.s() > s_max) { is_out_of_curr_lane = true; break; } } if (is_out_of_curr_lane) { if (count == 0) { // The current ADC, without moving at all, is already at least // partially out of the current lane. *should_not_move_at_all = true; return true; } break; } else { *last_path_point = path_point; } CHECK_GE(path_point.s(), 0.0); ++count; } return true; } } // namespace side_pass } // namespace scenario } // namespace planning } // namespace apollo
fix a bug in side pass scenario.
planning: fix a bug in side pass scenario.
C++
apache-2.0
msbeta/apollo,msbeta/apollo,msbeta/apollo,msbeta/apollo,msbeta/apollo,msbeta/apollo
b586cd7c0dde9e55d6ef08b46132584a71aedfa6
src/loadOperator.cc
src/loadOperator.cc
#include "loadOperator.hh" // std #include <string> // scidb #include "query/TypeSystem.h" #include "system/SystemCatalog.h" #include "array/Array.h" #include "array/DBArray.h" // pkg #include "H5Array.hh" #include "scidbConvert.hh" void loadHdf(std::string const& filePath, std::string const& hdfPath, std::string const& arrayName) { // Do something good. H5Array ha(filePath, hdfPath); std::cout << "Retrieving descriptor for " << filePath << " --> " << hdfPath << std::endl; boost::shared_ptr<scidb::ArrayDesc> dptr(ha.getArrayDesc()); dptr->setName(arrayName); std::cout << "Set array name. Getting catalog instance." << std::endl; scidb::SystemCatalog& catalog = *scidb::SystemCatalog::getInstance(); if(catalog.containsArray(arrayName)) { // delete if existing. catalog.deleteArray(arrayName); } // Get array id; hardcode partitioning scheme for now. scidb::ArrayID aid = catalog.addArray(*dptr, scidb::psLocalNode); scidb::DBArray array(aid); std::cout << "Added array to catalog and contructed dbarray." << std::endl; // Only handle single-attribute right now. int chunkMode = 0; // chunk mode (dense/sparse) chunkMode |= scidb::ChunkIterator::NO_EMPTY_CHECK; boost::shared_ptr<scidb::ArrayIterator> ai = array.getIterator(0); //ArrayDescPtr ap = newArrayDesc(ha.getScidbAttrs(), ha.getScidbDims()); std::cout << "Iterating... " << std::endl; std::cout << "begin: " << ha.begin() << std::endl; std::cout << "end: " << ha.end() << std::endl; for(H5Array::SlabIter i = ha.begin(); i != ha.end(); ++i) { scidb::Coordinates hc(*i); scidb::Coordinates c(hc.size()); std::reverse_copy(hc.begin(), hc.end(), c.begin()); // Not sure about coordinate order. HDF: minor precedes major. std::cout << i << std::endl; //ci = ai->newChunk(*i).getIterator(chunkMode); scidb::Chunk& outChunk = ai->newChunk(hc); outChunk.allocate(i.slabAttrSize(0)); outChunk.setSparse(false); // Never sparse scidb::Chunk* outChunkPtr = &outChunk; // std::cout << "writing to buffer at " // << (void*) outChunk.getData() << std::endl; i.readInto(0, outChunk.getData()); outChunk.setCount(0); outChunk.write(); } // Fill results //res.setString("SomeArray"); // Fill in result: name of new array }
#include "loadOperator.hh" // std #include <string> // scidb #include "query/TypeSystem.h" #include "system/SystemCatalog.h" #include "array/Array.h" #include "array/DBArray.h" // pkg #include "H5Array.hh" #include "scidbConvert.hh" namespace { class Copier { public: Copier(scidb::ArrayID& arrayId) : _array(arrayId) { // Nothing for now. } void copyChunk(H5Array::SlabIter& si, int attNo) { // Not sure about coordinate order. HDF: minor precedes major. scidb::Coordinates const& coords = *si; boost::shared_ptr<scidb::ArrayIterator> ai; ai = _array.getIterator(attNo); scidb::Chunk& outChunk = ai->newChunk(coords); outChunk.allocate(si.slabAttrSize(attNo)); outChunk.setSparse(false); // Never sparse // scidb::Chunk* outChunkPtr = &outChunk; // std::cout << "writing to buffer at " // << (void*) outChunk.getData() << std::endl; si.readInto(attNo, outChunk.getData()); outChunk.setCount(0); // FIXME: Count = num of elements. outChunk.write(); } private: scidb::DBArray _array; }; } void loadHdf(std::string const& filePath, std::string const& hdfPath, std::string const& arrayName) { // Do something good. H5Array ha(filePath, hdfPath); std::cout << "Retrieving descriptor for " << filePath << " --> " << hdfPath << std::endl; boost::shared_ptr<scidb::ArrayDesc> dptr(ha.getArrayDesc()); dptr->setName(arrayName); std::cout << "Set array name. Getting catalog instance." << std::endl; scidb::SystemCatalog& catalog = *scidb::SystemCatalog::getInstance(); if(catalog.containsArray(arrayName)) { // delete if existing. catalog.deleteArray(arrayName); } // Get array id; hardcode partitioning scheme for now. scidb::ArrayID aid = catalog.addArray(*dptr, scidb::psLocalNode); Copier copier(aid); std::cout << "Added array to catalog and contructed dbarray." << std::endl; // Only handle single-attribute right now. int chunkMode = 0; // chunk mode (dense/sparse) chunkMode |= scidb::ChunkIterator::NO_EMPTY_CHECK; std::cout << "Iterating... " << std::endl; std::cout << "begin: " << ha.begin() << std::endl; std::cout << "end: " << ha.end() << std::endl; for(H5Array::SlabIter i = ha.begin(); i != ha.end(); ++i) { std::cout << i << std::endl; copier.copyChunk(i, 0); } // Fill results //res.setString("SomeArray"); // Fill in result: name of new array }
Refactor to prep for multi-attribute array support.
Refactor to prep for multi-attribute array support.
C++
apache-2.0
wangd/SciDB-HDF5
ade6d89b6da6a99c99c3b8aebca0c087cd51d480
caffe2/operators/summarize_op.cc
caffe2/operators/summarize_op.cc
/** * Copyright (c) 2016-present, Facebook, 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. */ #include "caffe2/operators/summarize_op.h" namespace caffe2 { template<> bool SummarizeOp<float, CPUContext>::RunOnDevice() { auto& X = Input(0); const int N = X.size(); DCHECK_GT(N, 0); const float* Xdata = X.data<float>(); float mean = 0; float max = Xdata[0]; float min = Xdata[0]; for (int i = 0; i < N; ++i) { mean += Xdata[i]; max = std::max(max, Xdata[i]); min = std::min(min, Xdata[i]); } mean /= N; // We will simply do a two-pass. More efficient solutions can be written but // I'll keep code simple for now. float standard_deviation = 0; for (int i = 0; i < N; ++i) { float diff = Xdata[i] - mean; standard_deviation += diff * diff; } // Unbiased or biased? Let's do unbiased now. standard_deviation = N == 1 ? 0 : std::sqrt(standard_deviation / (N - 1)); if (to_file_) { (*log_file_) << min << " " << max << " " << mean << " " << standard_deviation << std::endl; } if (OutputSize()) { auto* Y = Output(0); Y->Resize(NUM_STATS); float* Ydata = Y->mutable_data<float>(); Ydata[MIN_IDX] = min; Ydata[MAX_IDX] = max; Ydata[MEAN_IDX] = mean; Ydata[STD_IDX] = standard_deviation; } return true; } REGISTER_CPU_OPERATOR(Summarize, SummarizeOp<float, CPUContext>); // Input: X; output: if set, a summarized Tensor of shape 4, with the values // being min, max, mean and std respectively. OPERATOR_SCHEMA(Summarize) .NumInputs(1) .NumOutputs(0, 1) .SetDoc(R"DOC( Summarize computes four statistics of the input tensor (Tensor<float>)- min, max, mean and standard deviation. The output will be written to a 1-D tensor of size 4 if an output tensor is provided. Else, if the argument 'to_file' is greater than 0, the values are written to a log file in the root folder. )DOC") .Arg("to_file", "(int, default 0) flag to indicate if the summarized " "statistics have to be written to a log file.") .Input(0, "data", "The input data as Tensor<float>.") .Output(0, "output", "1-D tensor (Tensor<float>) of size 4 containing min, " "max, mean and standard deviation"); SHOULD_NOT_DO_GRADIENT(Summarize); } // namespace caffe2
/** * Copyright (c) 2016-present, Facebook, 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. */ #include "caffe2/operators/summarize_op.h" namespace caffe2 { template <> bool SummarizeOp<float, CPUContext>::RunOnDevice() { auto& X = Input(0); const auto N = X.size(); CAFFE_ENFORCE_GT(N, 0); const float* Xdata = X.data<float>(); double mean = 0; float max = Xdata[0]; float min = Xdata[0]; for (auto i = 0; i < N; ++i) { mean += static_cast<double>(Xdata[i]) / N; max = std::max(max, Xdata[i]); min = std::min(min, Xdata[i]); } // We will simply do a two-pass. More efficient solutions can be written but // I'll keep code simple for now. double standard_deviation = 0; for (auto i = 0; i < N; ++i) { double diff = Xdata[i] - mean; standard_deviation += diff * diff; } // Unbiased or biased? Let's do unbiased now. standard_deviation = N == 1 ? 0 : std::sqrt(standard_deviation / (N - 1)); if (to_file_) { (*log_file_) << min << " " << max << " " << mean << " " << standard_deviation << std::endl; } if (OutputSize()) { auto* Y = Output(0); Y->Resize(NUM_STATS); float* Ydata = Y->mutable_data<float>(); Ydata[MIN_IDX] = min; Ydata[MAX_IDX] = max; Ydata[MEAN_IDX] = static_cast<float>(mean); Ydata[STD_IDX] = static_cast<float>(standard_deviation); } return true; } REGISTER_CPU_OPERATOR(Summarize, SummarizeOp<float, CPUContext>); // Input: X; output: if set, a summarized Tensor of shape 4, with the values // being min, max, mean and std respectively. OPERATOR_SCHEMA(Summarize) .NumInputs(1) .NumOutputs(0, 1) .SetDoc(R"DOC( Summarize computes four statistics of the input tensor (Tensor<float>)- min, max, mean and standard deviation. The output will be written to a 1-D tensor of size 4 if an output tensor is provided. Else, if the argument 'to_file' is greater than 0, the values are written to a log file in the root folder. )DOC") .Arg( "to_file", "(int, default 0) flag to indicate if the summarized " "statistics have to be written to a log file.") .Input(0, "data", "The input data as Tensor<float>.") .Output( 0, "output", "1-D tensor (Tensor<float>) of size 4 containing min, " "max, mean and standard deviation"); SHOULD_NOT_DO_GRADIENT(Summarize); } // namespace caffe2
make summarize op support larger blob and more robust
make summarize op support larger blob and more robust Summary: - so that it can also summarize blob of size larger than int - the calculation of the mean and std may overflow/underflow, change to use double for intermediate calculation Differential Revision: D6278275 fbshipit-source-id: f0bb72a5279212d429fa6d09b5487cad1baacdbe
C++
apache-2.0
pietern/caffe2,sf-wind/caffe2,pietern/caffe2,xzturn/caffe2,davinwang/caffe2,Yangqing/caffe2,Yangqing/caffe2,davinwang/caffe2,pietern/caffe2,Yangqing/caffe2,davinwang/caffe2,xzturn/caffe2,sf-wind/caffe2,sf-wind/caffe2,caffe2/caffe2,pietern/caffe2,sf-wind/caffe2,sf-wind/caffe2,xzturn/caffe2,davinwang/caffe2,davinwang/caffe2,Yangqing/caffe2,Yangqing/caffe2,xzturn/caffe2,xzturn/caffe2,pietern/caffe2
38397968a55a4a41999d57801c5c142ce2d79500
tool/KCClient.cpp
tool/KCClient.cpp
#include "KCClient.h" #include <QDebug> #include <QSettings> #include <QUrlQuery> #include <QJsonDocument> #include <QFile> #include "KCShip.h" #include "KCShipMaster.h" #include "KCFleet.h" #define kClientUseCache 1 /* * This is ugly, but it's so repetitive that it's better to keep it out of the * way and synthesize it all like this than to copypaste this over and over. * One day, I will think of a better way. Until then, this stands. */ #define SYNTHESIZE_RESPONSE_HANDLERS(_id_, _var_) \ void KCClient::_process##_id_##Data(QVariant data) { \ modelizeResponse(data, _var_, this); \ emit received##_id_(); \ } \ void KCClient::on##_id_##RequestFinished() \ { \ QNetworkReply *reply = qobject_cast<QNetworkReply*>(QObject::sender()); \ ErrorCode error; \ QVariant data = this->dataFromRawResponse(reply->readAll(), &error); \ if(data.isValid()) _process##_id_##Data(data); \ else emit requestError(error); \ } SYNTHESIZE_RESPONSE_HANDLERS(MasterShips, masterShips) SYNTHESIZE_RESPONSE_HANDLERS(PlayerShips, ships) SYNTHESIZE_RESPONSE_HANDLERS(PlayerFleets, fleets) SYNTHESIZE_RESPONSE_HANDLERS(PlayerRepairs, repairDocks) SYNTHESIZE_RESPONSE_HANDLERS(PlayerConstructions, constructionDocks) // ------------------------------------------------------------------------- // KCClient::KCClient(QObject *parent) : QObject(parent) { manager = new QNetworkAccessManager(this); QSettings settings; server = settings.value("server").toString(); apiToken = settings.value("apiToken").toString(); } KCClient::~KCClient() { } bool KCClient::hasCredentials() { return (!server.isEmpty() && !server.isEmpty()); } void KCClient::setCredentials(QString server, QString apiToken) { this->server = server; this->apiToken = apiToken; if(this->hasCredentials()) { QSettings settings; settings.setValue("server", server); settings.setValue("apiToken", apiToken); settings.sync(); emit credentialsGained(); } } void KCClient::requestMasterShips() { QNetworkReply *reply = this->call("/api_get_master/ship"); if(reply) connect(reply, SIGNAL(finished()), this, SLOT(onMasterShipsRequestFinished())); } void KCClient::requestPlayerShips() { QNetworkReply *reply = this->call("/api_get_member/ship"); if(reply) connect(reply, SIGNAL(finished()), this, SLOT(onPlayerShipsRequestFinished())); } void KCClient::requestPlayerFleets() { QNetworkReply *reply = this->call("/api_get_member/deck"); if(reply) connect(reply, SIGNAL(finished()), this, SLOT(onPlayerFleetsRequestFinished())); } void KCClient::requestPlayerRepairs() { QNetworkReply *reply = this->call("/api_get_member/ndock"); if(reply) connect(reply, SIGNAL(finished()), this, SLOT(onPlayerRepairsRequestFinished())); } void KCClient::requestPlayerConstructions() { QNetworkReply *reply = this->call("/api_get_member/kdock"); if(reply) connect(reply, SIGNAL(finished()), this, SLOT(onPlayerConstructionsRequestFinished())); } void KCClient::onDockCompleted() { emit dockCompleted(qobject_cast<KCDock*>(QObject::sender())); } QNetworkReply* KCClient::call(QString endpoint, QUrlQuery params) { #if kClientUseCache QFile file(QString("cache%1.json").arg(endpoint)); if(file.open(QIODevice::ReadOnly)) { qDebug() << "Loading Fixture:" << endpoint; QVariant response = this->dataFromRawResponse(file.readAll()); if(endpoint == "/api_get_master/ship") _processMasterShipsData(response); else if(endpoint == "/api_get_member/ship") _processPlayerShipsData(response); else if(endpoint == "/api_get_member/deck") _processPlayerFleetsData(response); else if(endpoint == "/api_get_member/ndock") _processPlayerRepairsData(response); else if(endpoint == "/api_get_member/kdock") _processPlayerConstructionsData(response); return 0; } #endif QNetworkRequest request(this->urlForEndpoint(endpoint)); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); request.setRawHeader("Referer", QString("http://%1/kcs/mainD2.swf").arg(server).toUtf8()); params.addQueryItem("api_verno", "1"); params.addQueryItem("api_token", apiToken); QString query = params.toString(QUrl::FullyEncoded); return manager->post(request, query.toUtf8()); } QUrl KCClient::urlForEndpoint(QString endpoint) { return QUrl(QString("http://%1/kcsapi%2").arg(server, endpoint)); } QVariant KCClient::dataFromRawResponse(QString text, ErrorCode *error) { if(text.startsWith("svdata=")) text = text.mid(7); QJsonParseError jsonErr; QJsonDocument doc = QJsonDocument::fromJson(text.toUtf8(), &jsonErr); if(jsonErr.error != QJsonParseError::NoError) { if(error) *error = JsonError; return QVariant(); } QMap<QString, QVariant> data = doc.toVariant().toMap(); if(data.value("api_result").toInt() != NoError) { if(error) *error = (ErrorCode)data.value("api_result").toInt(); return QVariant(); } if(error) *error = NoError; return data.value("api_data"); }
#include "KCClient.h" #include <QDebug> #include <QSettings> #include <QUrlQuery> #include <QJsonDocument> #include <QFile> #include "KCShip.h" #include "KCShipMaster.h" #include "KCFleet.h" #define kClientUseCache 0 /* * This is ugly, but it's so repetitive that it's better to keep it out of the * way and synthesize it all like this than to copypaste this over and over. * One day, I will think of a better way. Until then, this stands. */ #define SYNTHESIZE_RESPONSE_HANDLERS(_id_, _var_) \ void KCClient::_process##_id_##Data(QVariant data) { \ modelizeResponse(data, _var_, this); \ emit received##_id_(); \ } \ void KCClient::on##_id_##RequestFinished() \ { \ QNetworkReply *reply = qobject_cast<QNetworkReply*>(QObject::sender()); \ if(reply->error() == QNetworkReply::NoError) \ { \ ErrorCode error; \ QVariant data = this->dataFromRawResponse(reply->readAll(), &error); \ if(data.isValid()) _process##_id_##Data(data); \ else { qDebug() << error; emit requestError(error); } \ } \ else if(reply->error() == QNetworkReply::UnknownNetworkError) \ qWarning() << "Connection Failed:" << reply->errorString(); \ } SYNTHESIZE_RESPONSE_HANDLERS(MasterShips, masterShips) SYNTHESIZE_RESPONSE_HANDLERS(PlayerShips, ships) SYNTHESIZE_RESPONSE_HANDLERS(PlayerFleets, fleets) SYNTHESIZE_RESPONSE_HANDLERS(PlayerRepairs, repairDocks) SYNTHESIZE_RESPONSE_HANDLERS(PlayerConstructions, constructionDocks) // ------------------------------------------------------------------------- // KCClient::KCClient(QObject *parent) : QObject(parent) { manager = new QNetworkAccessManager(this); QSettings settings; server = settings.value("server").toString(); apiToken = settings.value("apiToken").toString(); } KCClient::~KCClient() { } bool KCClient::hasCredentials() { return (!server.isEmpty() && !server.isEmpty()); } void KCClient::setCredentials(QString server, QString apiToken) { this->server = server; this->apiToken = apiToken; if(this->hasCredentials()) { QSettings settings; settings.setValue("server", server); settings.setValue("apiToken", apiToken); settings.sync(); emit credentialsGained(); } } void KCClient::requestMasterShips() { QNetworkReply *reply = this->call("/api_get_master/ship"); if(reply) connect(reply, SIGNAL(finished()), this, SLOT(onMasterShipsRequestFinished())); } void KCClient::requestPlayerShips() { QNetworkReply *reply = this->call("/api_get_member/ship"); if(reply) connect(reply, SIGNAL(finished()), this, SLOT(onPlayerShipsRequestFinished())); } void KCClient::requestPlayerFleets() { QNetworkReply *reply = this->call("/api_get_member/deck"); if(reply) connect(reply, SIGNAL(finished()), this, SLOT(onPlayerFleetsRequestFinished())); } void KCClient::requestPlayerRepairs() { QNetworkReply *reply = this->call("/api_get_member/ndock"); if(reply) connect(reply, SIGNAL(finished()), this, SLOT(onPlayerRepairsRequestFinished())); } void KCClient::requestPlayerConstructions() { QNetworkReply *reply = this->call("/api_get_member/kdock"); if(reply) connect(reply, SIGNAL(finished()), this, SLOT(onPlayerConstructionsRequestFinished())); } void KCClient::onDockCompleted() { emit dockCompleted(qobject_cast<KCDock*>(QObject::sender())); } QNetworkReply* KCClient::call(QString endpoint, QUrlQuery params) { #if kClientUseCache QFile file(QString("cache%1.json").arg(endpoint)); if(file.open(QIODevice::ReadOnly)) { qDebug() << "Loading Fixture:" << endpoint; QVariant response = this->dataFromRawResponse(file.readAll()); if(endpoint == "/api_get_master/ship") _processMasterShipsData(response); else if(endpoint == "/api_get_member/ship") _processPlayerShipsData(response); else if(endpoint == "/api_get_member/deck") _processPlayerFleetsData(response); else if(endpoint == "/api_get_member/ndock") _processPlayerRepairsData(response); else if(endpoint == "/api_get_member/kdock") _processPlayerConstructionsData(response); return 0; } #endif QNetworkRequest request(this->urlForEndpoint(endpoint)); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); request.setRawHeader("Referer", QString("http://%1/kcs/mainD2.swf").arg(server).toUtf8()); params.addQueryItem("api_verno", "1"); params.addQueryItem("api_token", apiToken); QString query = params.toString(QUrl::FullyEncoded); return manager->post(request, query.toUtf8()); } QUrl KCClient::urlForEndpoint(QString endpoint) { return QUrl(QString("http://%1/kcsapi%2").arg(server, endpoint)); } QVariant KCClient::dataFromRawResponse(QString text, ErrorCode *error) { if(text.startsWith("svdata=")) text = text.mid(7); QJsonParseError jsonErr; QJsonDocument doc = QJsonDocument::fromJson(text.toUtf8(), &jsonErr); if(jsonErr.error != QJsonParseError::NoError) { if(error) *error = JsonError; return QVariant(); } QMap<QString, QVariant> data = doc.toVariant().toMap(); if(data.value("api_result").toInt() != NoError) { if(error) *error = (ErrorCode)data.value("api_result").toInt(); return QVariant(); } if(error) *error = NoError; return data.value("api_data"); }
Handle network errors properly
Handle network errors properly Closes #16
C++
mit
kevin01523/KanColleTool,kevin01523/KanColleTool,KanColleTool/KanColleTool,kevin01523/KanColleTool,KanColleTool/KanColleTool
f56964eb0692d3b3079bf2c00f77551917b68b3d
tools/convert.cpp
tools/convert.cpp
#include "imzml/reader.hpp" #include "utils/string.hpp" #include "cxxopts.hpp" #ifdef SCILS_H5 #include "scils/h5reader.hpp" #endif #include "imzb/reader.hpp" #include "imzb/writer.hpp" #include <iostream> #include <vector> #include <string> #include <sstream> #include <algorithm> #include <memory> #include <queue> #include <cstdio> class Sorter { std::string fn_; std::vector<ims::Peak> buffer_; std::vector<std::string> tmp_filenames_; size_t filled_; bool closed_; uint32_t block_size_; std::string compressor_; uint8_t comp_level_; void dump() { std::sort(buffer_.begin(), buffer_.begin() + filled_, [](const ims::Peak& a, const ims::Peak& b) { return a.mz < b.mz; } ); std::stringstream tmp_fn; tmp_fn << fn_ << "." << tmp_filenames_.size(); tmp_filenames_.push_back(tmp_fn.str()); imzb::ImzbWriter writer(tmp_filenames_.back(), block_size_, "blosclz"); writer.setMask(mask_); for (size_t i = 0; i < filled_; ++i) writer.writePeak(buffer_[i]); writer.close(); filled_ = 0; } struct PeakAndFile { ims::Peak peak; size_t file_index; bool operator<(const PeakAndFile& other) const { return peak.mz > other.peak.mz; } }; void merge() { std::cout << "merging files..." << std::endl; std::priority_queue<PeakAndFile> queue; std::vector<std::shared_ptr<imzb::ImzbReader>> readers; imzb::ImzbWriter writer(fn_, block_size_, compressor_, comp_level_); writer.setMask(mask_); ims::Peak peak; for (const auto& tmp_fn: tmp_filenames_) { readers.push_back(std::make_shared<imzb::ImzbReader>(tmp_fn)); if (readers.back()->readNext(peak)) queue.push(PeakAndFile{peak, readers.size() - 1}); } size_t n = 0; while (!queue.empty()) { auto item = queue.top(); writer.writePeak(item.peak); ++n; queue.pop(); if (readers[item.file_index]->readNext(peak)) queue.push(PeakAndFile{peak, item.file_index}); } writer.close(); std::cout << "removing temporary files" << std::endl; for (const auto& r: readers) { auto fn = r->filename(); auto idx_fn = fn + ".idx"; r->close(); std::remove(fn.c_str()); std::remove(idx_fn.c_str()); } std::cout << "done!" << std::endl; } const imzb::Mask& mask_; public: Sorter(const std::string& filename, const imzb::Mask& mask, size_t buffer_size, uint32_t block_size, const std::string& compressor, uint8_t compression_level) : fn_(filename), buffer_(buffer_size), filled_(0), closed_(false), block_size_(block_size), compressor_(compressor), comp_level_(compression_level), mask_(mask) { std::cout << "dumping chunks sorted by m/z..." << std::endl; } void addPeak(const ims::Peak& peak) { if (filled_ == buffer_.size()) dump(); buffer_[filled_++] = peak; } void close() { dump(); merge(); closed_ = true; } ~Sorter() { if (!closed_) close(); } }; int convert_main(int argc, char** argv) { std::string input_filename, output_filename, compressor; uint32_t block_size; size_t buffer_size = 10000000; int compression_level; cxxopts::Options options("ims convert", " <input.imzML> <output.imzb>"); options.add_options() ("block-size", "maximum number of records in a compressed block; larger values lead to slower m/z queries but smaller file size", cxxopts::value<uint32_t>(block_size)->default_value("4096")) ("compressor", "blosc compressor to be used", cxxopts::value<std::string>(compressor)->default_value("blosclz")) ("compression-level", "compression level (0-9)", cxxopts::value<int>(compression_level)->default_value("5")) ("help", "Print help"); options.add_options("hidden") ("in", "", cxxopts::value<std::string>(input_filename)) ("out", "", cxxopts::value<std::string>(output_filename)); options.parse_positional(std::vector<std::string>{"in", "out"}); options.parse(argc, argv); if (options.count("help") || input_filename.empty() || output_filename.empty()) { std::cout << options.help({""}) << std::endl; return 0; } ims::AbstractReaderPtr reader; if (utils::endsWith(input_filename, ".imzML")) reader = std::make_shared<imzml::ImzmlReader>(input_filename); #ifdef SCILS_H5 else if (utils::endsWith(input_filename, ".h5")) reader = std::make_shared<scils::H5Reader>(input_filename); #endif else { std::cerr << "unsupported file extension" << std::endl; return -3; } imzb::Mask mask{reader->height(), reader->width()}; Sorter sorter(output_filename, mask, buffer_size, block_size, compressor, compression_level); ims::Spectrum sp; while (reader->readNextSpectrum(sp)) { mask.set(sp.coords.x, sp.coords.y); for (size_t i = 0; i < sp.mzs.size(); ++i) { // skip invalid (NaN) and zero peaks if (sp.mzs[i] > 0 && sp.intensities[i] > 0) sorter.addPeak(ims::Peak{sp.coords, sp.mzs[i], sp.intensities[i]}); } } sorter.close(); return 0; }
#include "imzml/reader.hpp" #include "utils/string.hpp" #include "cxxopts.hpp" #ifdef SCILS_H5 #include "scils/h5reader.hpp" #endif #include "imzb/reader.hpp" #include "imzb/writer.hpp" #include <iostream> #include <vector> #include <string> #include <sstream> #include <algorithm> #include <memory> #include <queue> #include <cstdio> class Sorter { std::string fn_; std::vector<ims::Peak> buffer_; std::vector<std::string> tmp_filenames_; size_t filled_; bool closed_; uint32_t block_size_; std::string compressor_; uint8_t comp_level_; void dump() { std::sort(buffer_.begin(), buffer_.begin() + filled_, [](const ims::Peak& a, const ims::Peak& b) { return a.mz < b.mz; } ); std::stringstream tmp_fn; tmp_fn << fn_ << "." << tmp_filenames_.size(); tmp_filenames_.push_back(tmp_fn.str()); imzb::ImzbWriter writer(tmp_filenames_.back(), block_size_, "blosclz"); writer.setMask(mask_); for (size_t i = 0; i < filled_; ++i) writer.writePeak(buffer_[i]); writer.close(); filled_ = 0; } struct PeakAndFile { ims::Peak peak; size_t file_index; bool operator<(const PeakAndFile& other) const { return peak.mz > other.peak.mz; } }; void merge() { std::cout << "merging files..." << std::endl; std::priority_queue<PeakAndFile> queue; std::vector<std::shared_ptr<imzb::ImzbReader>> readers; imzb::ImzbWriter writer(fn_, block_size_, compressor_, comp_level_); writer.setMask(mask_); ims::Peak peak; for (const auto& tmp_fn: tmp_filenames_) { readers.push_back(std::make_shared<imzb::ImzbReader>(tmp_fn)); if (readers.back()->readNext(peak)) queue.push(PeakAndFile{peak, readers.size() - 1}); } size_t n = 0; while (!queue.empty()) { auto item = queue.top(); writer.writePeak(item.peak); ++n; queue.pop(); if (readers[item.file_index]->readNext(peak)) queue.push(PeakAndFile{peak, item.file_index}); } writer.close(); std::cout << "removing temporary files" << std::endl; for (const auto& r: readers) { auto fn = r->filename(); auto idx_fn = fn + ".idx"; r->close(); std::remove(fn.c_str()); std::remove(idx_fn.c_str()); } std::cout << "done!" << std::endl; } const imzb::Mask& mask_; public: Sorter(const std::string& filename, const imzb::Mask& mask, size_t buffer_size, uint32_t block_size, const std::string& compressor, uint8_t compression_level) : fn_(filename), buffer_(buffer_size), filled_(0), closed_(false), block_size_(block_size), compressor_(compressor), comp_level_(compression_level), mask_(mask) { std::cout << "dumping chunks sorted by m/z..." << std::endl; } void addPeak(const ims::Peak& peak) { if (filled_ == buffer_.size()) dump(); buffer_[filled_++] = peak; } void close() { dump(); merge(); closed_ = true; } ~Sorter() { if (!closed_) close(); } }; int convert_main(int argc, char** argv) { std::string input_filename, output_filename, compressor; uint32_t block_size; size_t buffer_size = 10000000; int compression_level; cxxopts::Options options("ims convert", " <input.imzML> <output.imzb>"); options.add_options() ("block-size", "maximum number of records in a compressed block; larger values lead to slower m/z queries but smaller file size", cxxopts::value<uint32_t>(block_size)->default_value("4096")) ("compressor", "blosc compressor to be used", cxxopts::value<std::string>(compressor)->default_value("blosclz")) ("compression-level", "compression level (0-9)", cxxopts::value<int>(compression_level)->default_value("5")) ("help", "Print help"); options.add_options("hidden") ("in", "", cxxopts::value<std::string>(input_filename)) ("out", "", cxxopts::value<std::string>(output_filename)); options.parse_positional(std::vector<std::string>{"in", "out"}); options.parse(argc, argv); if (options.count("help") || input_filename.empty() || output_filename.empty()) { std::cout << options.help({""}) << std::endl; return 0; } ims::AbstractReaderPtr reader; if (utils::endsWith(input_filename, ".imzML")) reader = std::make_shared<imzml::ImzmlReader>(input_filename); #ifdef SCILS_H5 else if (utils::endsWith(input_filename, ".h5")) reader = std::make_shared<scils::H5Reader>(input_filename); #endif else { std::cerr << "unsupported file extension" << std::endl; return -3; } imzb::Mask mask{reader->height(), reader->width()}; Sorter sorter(output_filename, mask, buffer_size, block_size, compressor, compression_level); ims::Spectrum sp; while (reader->readNextSpectrum(sp)) { if (sp.coords.x >= reader->height() || sp.coords.y >= reader->width()) { std::cerr << "WARNING: skipped spectrum with invalid coordinates (" << int32_t(sp.coords.x) << ", " << int32_t(sp.coords.y) << ")" << std::endl; continue; } mask.set(sp.coords.x, sp.coords.y); for (size_t i = 0; i < sp.mzs.size(); ++i) { // skip invalid (NaN) and zero peaks if (sp.mzs[i] > 0 && sp.intensities[i] > 0) sorter.addPeak(ims::Peak{sp.coords, sp.mzs[i], sp.intensities[i]}); } } sorter.close(); return 0; }
add bounds check for spectra
add bounds check for spectra
C++
apache-2.0
alexandrovteam/ims-cpp,alexandrovteam/ims-cpp,alexandrovteam/ims-cpp
0f82df410caf8242406fa7e8bbd555e4854ffe48
tools/llc/llc.cpp
tools/llc/llc.cpp
//===-- llc.cpp - Implement the LLVM Compiler -----------------------------===// // // This is the llc compiler driver. // //===----------------------------------------------------------------------===// #include "llvm/Bytecode/Reader.h" #include "llvm/Target/Sparc.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Transforms/Instrumentation/TraceValues.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/Utils/Linker.h" #include "llvm/Assembly/PrintModulePass.h" #include "llvm/Bytecode/WriteBytecodePass.h" #include "llvm/Transforms/IPO.h" #include "llvm/Module.h" #include "llvm/PassManager.h" #include "llvm/Pass.h" #include "llvm/Support/PassNameParser.h" #include "Support/CommandLine.h" #include "Support/Signals.h" #include <memory> #include <fstream> using std::string; using std::cerr; //------------------------------------------------------------------------------ // Option declarations for LLC. //------------------------------------------------------------------------------ // Make all registered optimization passes available to llc. These passes // will all be run before the simplification and lowering steps used by the // back-end code generator, and will be run in the order specified on the // command line. The OptimizationList is automatically populated with // registered Passes by the PassNameParser. // static cl::list<const PassInfo*, bool, FilteredPassNameParser<PassInfo::Optimization> > OptimizationList(cl::desc("Optimizations available:")); // General options for llc. Other pass-specific options are specified // within the corresponding llc passes, and target-specific options // and back-end code generation options are specified with the target machine. // static cl::opt<string> InputFilename(cl::Positional, cl::desc("<input bytecode>"), cl::init("-")); static cl::opt<string> OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename")); static cl::opt<bool> Force("f", cl::desc("Overwrite output files")); static cl::opt<bool> DumpAsm("d", cl::desc("Print bytecode before native code generation"), cl::Hidden); static cl::opt<string> TraceLibPath("tracelibpath", cl::desc("Path to libinstr for trace code"), cl::value_desc("directory"), cl::Hidden); // flags set from -tracem and -trace options to control tracing static bool TraceFunctions = false; static bool TraceBasicBlocks = false; // GetFileNameRoot - Helper function to get the basename of a filename... static inline string GetFileNameRoot(const string &InputFilename) { string IFN = InputFilename; string outputFilename; int Len = IFN.length(); if (IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') { outputFilename = string(IFN.begin(), IFN.end()-3); // s/.bc/.s/ } else { outputFilename = IFN; } return outputFilename; } static bool insertTraceCodeFor(Module &M) { PassManager Passes; // Insert trace code in all functions in the module if (TraceBasicBlocks) Passes.add(createTraceValuesPassForBasicBlocks()); else if (TraceFunctions) Passes.add(createTraceValuesPassForFunction()); else return false; // Eliminate duplication in constant pool Passes.add(createConstantMergePass()); // Run passes to insert and clean up trace code... Passes.run(M); std::string ErrorMessage; // Load the module that contains the runtime helper routines neccesary for // pointer hashing and stuff... link this module into the program if possible // Module *TraceModule = ParseBytecodeFile(TraceLibPath+"libinstr.bc"); // Check if the TraceLibPath contains a valid module. If not, try to load // the module from the current LLVM-GCC install directory. This is kindof // a hack, but allows people to not HAVE to have built the library. // if (TraceModule == 0) TraceModule = ParseBytecodeFile("/home/vadve/lattner/cvs/gcc_install/lib/" "gcc-lib/llvm/3.1/libinstr.bc"); // If we still didn't get it, cancel trying to link it in... if (TraceModule == 0) cerr << "Warning, could not load trace routines to link into program!\n"; else { // Link in the trace routines... if this fails, don't panic, because the // compile should still succeed, but the native linker will probably fail. // std::auto_ptr<Module> TraceRoutines(TraceModule); if (LinkModules(&M, TraceRoutines.get(), &ErrorMessage)) cerr << "Warning: Error linking in trace routines: " << ErrorMessage << "\n"; } // Write out the module with tracing code just before code generation assert (InputFilename != "-" && "Cannot write out traced bytecode when reading input from stdin"); string TraceFilename = GetFileNameRoot(InputFilename) + ".trace.bc"; std::ofstream Out(TraceFilename.c_str()); if (!Out.good()) cerr << "Error opening '" << TraceFilename << "'!: Skipping output of trace code as bytecode\n"; else { cerr << "Emitting trace code to '" << TraceFilename << "' for comparison...\n"; WriteBytecodeToFile(&M, Out); } return true; } // Making tracing a module pass so the entire module with tracing // can be written out before continuing. struct InsertTracingCodePass: public Pass { virtual bool run(Module &M) { return insertTraceCodeFor(M); } }; //===---------------------------------------------------------------------===// // Function main() // // Entry point for the llc compiler. //===---------------------------------------------------------------------===// int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv, " llvm system compiler\n"); // Allocate a target... in the future this will be controllable on the // command line. std::auto_ptr<TargetMachine> target(allocateSparcTargetMachine()); assert(target.get() && "Could not allocate target machine!"); TargetMachine &Target = *target.get(); // Load the module to be compiled... std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename)); if (M.get() == 0) { cerr << argv[0] << ": bytecode didn't read correctly.\n"; return 1; } // Build up all of the passes that we want to do to the module... PassManager Passes; // Create a new optimization pass for each one specified on the command line // Deal specially with tracing passes, which must be run differently than opt. // for (unsigned i = 0; i < OptimizationList.size(); ++i) { const PassInfo *Opt = OptimizationList[i]; if (strcmp(Opt->getPassArgument(), "trace") == 0) TraceFunctions = !(TraceBasicBlocks = true); else if (strcmp(Opt->getPassArgument(), "tracem") == 0) TraceFunctions = !(TraceBasicBlocks = false); else { // handle other passes as normal optimization passes if (Opt->getNormalCtor()) Passes.add(Opt->getNormalCtor()()); else if (Opt->getDataCtor()) Passes.add(Opt->getDataCtor()(Target.DataLayout)); else if (Opt->getTargetCtor()) Passes.add(Opt->getTargetCtor()(Target)); else cerr << argv[0] << ": cannot create pass: " << Opt->getPassName() << "\n"; } } // Run tracing passes after other optimization passes and before llc passes. if (TraceFunctions || TraceBasicBlocks) Passes.add(new InsertTracingCodePass); // Decompose multi-dimensional refs into a sequence of 1D refs Passes.add(createDecomposeMultiDimRefsPass()); // Replace malloc and free instructions with library calls. // Do this after tracing until lli implements these lib calls. // For now, it will emulate malloc and free internally. Passes.add(createLowerAllocationsPass(Target.DataLayout)); // If LLVM dumping after transformations is requested, add it to the pipeline if (DumpAsm) Passes.add(new PrintFunctionPass("Code after xformations: \n", &cerr)); // Strip all of the symbols from the bytecode so that it will be smaller... Passes.add(createSymbolStrippingPass()); // Figure out where we are going to send the output... std::ostream *Out = 0; if (OutputFilename != "") { // Specified an output filename? if (!Force && std::ifstream(OutputFilename.c_str())) { // If force is not specified, make sure not to overwrite a file! cerr << argv[0] << ": error opening '" << OutputFilename << "': file exists!\n" << "Use -f command line argument to force output\n"; return 1; } Out = new std::ofstream(OutputFilename.c_str()); // Make sure that the Out file gets unlink'd from the disk if we get a // SIGINT RemoveFileOnSignal(OutputFilename); } else { if (InputFilename == "-") { OutputFilename = "-"; Out = &std::cout; } else { string OutputFilename = GetFileNameRoot(InputFilename); OutputFilename += ".s"; if (!Force && std::ifstream(OutputFilename.c_str())) { // If force is not specified, make sure not to overwrite a file! cerr << argv[0] << ": error opening '" << OutputFilename << "': file exists!\n" << "Use -f command line argument to force output\n"; return 1; } Out = new std::ofstream(OutputFilename.c_str()); if (!Out->good()) { cerr << argv[0] << ": error opening " << OutputFilename << "!\n"; delete Out; return 1; } // Make sure that the Out file gets unlink'd from the disk if we get a // SIGINT RemoveFileOnSignal(OutputFilename); } } Target.addPassesToEmitAssembly(Passes, *Out); // Run our queue of passes all at once now, efficiently. Passes.run(*M.get()); if (Out != &std::cout) delete Out; return 0; }
//===-- llc.cpp - Implement the LLVM Compiler -----------------------------===// // // This is the llc compiler driver. // //===----------------------------------------------------------------------===// #include "llvm/Bytecode/Reader.h" #include "llvm/Target/Sparc.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Transforms/Instrumentation/TraceValues.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/Utils/Linker.h" #include "llvm/Assembly/PrintModulePass.h" #include "llvm/Bytecode/WriteBytecodePass.h" #include "llvm/Transforms/IPO.h" #include "llvm/Module.h" #include "llvm/PassManager.h" #include "llvm/Pass.h" #include "llvm/Support/PassNameParser.h" #include "Support/CommandLine.h" #include "Support/Signals.h" #include <memory> #include <fstream> using std::string; using std::cerr; //------------------------------------------------------------------------------ // Option declarations for LLC. //------------------------------------------------------------------------------ // Make all registered optimization passes available to llc. These passes // will all be run before the simplification and lowering steps used by the // back-end code generator, and will be run in the order specified on the // command line. The OptimizationList is automatically populated with // registered Passes by the PassNameParser. // static cl::list<const PassInfo*, bool, FilteredPassNameParser<PassInfo::Optimization> > OptimizationList(cl::desc("Optimizations available:")); // General options for llc. Other pass-specific options are specified // within the corresponding llc passes, and target-specific options // and back-end code generation options are specified with the target machine. // static cl::opt<string> InputFilename(cl::Positional, cl::desc("<input bytecode>"), cl::init("-")); static cl::opt<string> OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename")); static cl::opt<bool> Force("f", cl::desc("Overwrite output files")); static cl::opt<bool> DumpAsm("d", cl::desc("Print bytecode before native code generation"), cl::Hidden); static cl::opt<string> TraceLibPath("tracelibpath", cl::desc("Path to libinstr for trace code"), cl::value_desc("directory"), cl::Hidden); // flags set from -tracem and -trace options to control tracing static bool TraceFunctions = false; static bool TraceBasicBlocks = false; // GetFileNameRoot - Helper function to get the basename of a filename... static inline string GetFileNameRoot(const string &InputFilename) { string IFN = InputFilename; string outputFilename; int Len = IFN.length(); if (IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') { outputFilename = string(IFN.begin(), IFN.end()-3); // s/.bc/.s/ } else { outputFilename = IFN; } return outputFilename; } static bool insertTraceCodeFor(Module &M) { PassManager Passes; // Insert trace code in all functions in the module if (TraceBasicBlocks) Passes.add(createTraceValuesPassForBasicBlocks()); else if (TraceFunctions) Passes.add(createTraceValuesPassForFunction()); else return false; // Eliminate duplication in constant pool Passes.add(createConstantMergePass()); // Run passes to insert and clean up trace code... Passes.run(M); std::string ErrorMessage; // Load the module that contains the runtime helper routines neccesary for // pointer hashing and stuff... link this module into the program if possible // Module *TraceModule = ParseBytecodeFile(TraceLibPath+"libinstr.bc"); // Check if the TraceLibPath contains a valid module. If not, try to load // the module from the current LLVM-GCC install directory. This is kindof // a hack, but allows people to not HAVE to have built the library. // if (TraceModule == 0) TraceModule = ParseBytecodeFile("/home/vadve/lattner/cvs/gcc_install/lib/" "gcc-lib/llvm/3.1/libinstr.bc"); // If we still didn't get it, cancel trying to link it in... if (TraceModule == 0) cerr << "Warning, could not load trace routines to link into program!\n"; else { // Link in the trace routines... if this fails, don't panic, because the // compile should still succeed, but the native linker will probably fail. // std::auto_ptr<Module> TraceRoutines(TraceModule); if (LinkModules(&M, TraceRoutines.get(), &ErrorMessage)) cerr << "Warning: Error linking in trace routines: " << ErrorMessage << "\n"; } // Write out the module with tracing code just before code generation assert (InputFilename != "-" && "Cannot write out traced bytecode when reading input from stdin"); string TraceFilename = GetFileNameRoot(InputFilename) + ".trace.bc"; std::ofstream Out(TraceFilename.c_str()); if (!Out.good()) cerr << "Error opening '" << TraceFilename << "'!: Skipping output of trace code as bytecode\n"; else { cerr << "Emitting trace code to '" << TraceFilename << "' for comparison...\n"; WriteBytecodeToFile(&M, Out); } return true; } // Making tracing a module pass so the entire module with tracing // can be written out before continuing. struct InsertTracingCodePass: public Pass { virtual bool run(Module &M) { return insertTraceCodeFor(M); } }; //===---------------------------------------------------------------------===// // Function main() // // Entry point for the llc compiler. //===---------------------------------------------------------------------===// int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv, " llvm system compiler\n"); // Allocate a target... in the future this will be controllable on the // command line. std::auto_ptr<TargetMachine> target(allocateSparcTargetMachine()); assert(target.get() && "Could not allocate target machine!"); TargetMachine &Target = *target.get(); // Load the module to be compiled... std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename)); if (M.get() == 0) { cerr << argv[0] << ": bytecode didn't read correctly.\n"; return 1; } // Build up all of the passes that we want to do to the module... PassManager Passes; // Create a new optimization pass for each one specified on the command line // Deal specially with tracing passes, which must be run differently than opt. // for (unsigned i = 0; i < OptimizationList.size(); ++i) { const PassInfo *Opt = OptimizationList[i]; if (strcmp(Opt->getPassArgument(), "trace") == 0) TraceFunctions = !(TraceBasicBlocks = true); else if (strcmp(Opt->getPassArgument(), "tracem") == 0) TraceFunctions = !(TraceBasicBlocks = false); else { // handle other passes as normal optimization passes if (Opt->getNormalCtor()) Passes.add(Opt->getNormalCtor()()); else if (Opt->getDataCtor()) Passes.add(Opt->getDataCtor()(Target.DataLayout)); else if (Opt->getTargetCtor()) Passes.add(Opt->getTargetCtor()(Target)); else cerr << argv[0] << ": cannot create pass: " << Opt->getPassName() << "\n"; } } // Run tracing passes after other optimization passes and before llc passes. if (TraceFunctions || TraceBasicBlocks) Passes.add(new InsertTracingCodePass); // Decompose multi-dimensional refs into a sequence of 1D refs Passes.add(createDecomposeMultiDimRefsPass()); // Replace malloc and free instructions with library calls. // Do this after tracing until lli implements these lib calls. // For now, it will emulate malloc and free internally. Passes.add(createLowerAllocationsPass(Target.DataLayout)); // If LLVM dumping after transformations is requested, add it to the pipeline if (DumpAsm) Passes.add(new PrintFunctionPass("Code after xformations: \n", &cerr)); // Strip all of the symbols from the bytecode so that it will be smaller... Passes.add(createSymbolStrippingPass()); // Figure out where we are going to send the output... std::ostream *Out = 0; if (OutputFilename != "") { // Specified an output filename? if (!Force && std::ifstream(OutputFilename.c_str())) { // If force is not specified, make sure not to overwrite a file! cerr << argv[0] << ": error opening '" << OutputFilename << "': file exists!\n" << "Use -f command line argument to force output\n"; return 1; } Out = new std::ofstream(OutputFilename.c_str()); // Make sure that the Out file gets unlink'd from the disk if we get a // SIGINT RemoveFileOnSignal(OutputFilename); } else { if (InputFilename == "-") { OutputFilename = "-"; Out = &std::cout; } else { string OutputFilename = GetFileNameRoot(InputFilename); OutputFilename += ".s"; if (!Force && std::ifstream(OutputFilename.c_str())) { // If force is not specified, make sure not to overwrite a file! cerr << argv[0] << ": error opening '" << OutputFilename << "': file exists!\n" << "Use -f command line argument to force output\n"; return 1; } Out = new std::ofstream(OutputFilename.c_str()); if (!Out->good()) { cerr << argv[0] << ": error opening " << OutputFilename << "!\n"; delete Out; return 1; } // Make sure that the Out file gets unlink'd from the disk if we get a // SIGINT RemoveFileOnSignal(OutputFilename); } } Target.addPassesToEmitAssembly(Passes, *Out); // Run our queue of passes all at once now, efficiently. Passes.run(*M.get()); // Delete the ostream if it's not a stdout stream if (Out != &std::cout) delete Out; return 0; }
Indent a comment right, add a new one
Indent a comment right, add a new one git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@3819 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/llvm,llvm-mirror/llvm,chubbymaggie/asap,dslab-epfl/asap,chubbymaggie/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,chubbymaggie/asap,dslab-epfl/asap,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,dslab-epfl/asap,chubbymaggie/asap,llvm-mirror/llvm,dslab-epfl/asap,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,dslab-epfl/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,dslab-epfl/asap,dslab-epfl/asap
af1465b17bf9980867a718b76dfbb1fd9ed17420
utils/TableGen/ClangDiagnosticsEmitter.cpp
utils/TableGen/ClangDiagnosticsEmitter.cpp
//=- ClangDiagnosticsEmitter.cpp - Generate Clang diagnostics tables -*- C++ -*- // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // These tablegen backends emit Clang diagnostics tables. // //===----------------------------------------------------------------------===// #include "ClangDiagnosticsEmitter.h" #include "Record.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Compiler.h" #include "llvm/ADT/DenseSet.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/VectorExtras.h" #include <set> #include <map> using namespace llvm; //===----------------------------------------------------------------------===// // Warning Tables (.inc file) generation. //===----------------------------------------------------------------------===// void ClangDiagsDefsEmitter::run(raw_ostream &OS) { // Write the #if guard if (!Component.empty()) { std::string ComponentName = UppercaseString(Component); OS << "#ifdef " << ComponentName << "START\n"; OS << "__" << ComponentName << "START = DIAG_START_" << ComponentName << ",\n"; OS << "#undef " << ComponentName << "START\n"; OS << "#endif\n\n"; } const std::vector<Record*> &Diags = Records.getAllDerivedDefinitions("Diagnostic"); for (unsigned i = 0, e = Diags.size(); i != e; ++i) { const Record &R = *Diags[i]; // Filter by component. if (!Component.empty() && Component != R.getValueAsString("Component")) continue; OS << "DIAG(" << R.getName() << ", "; OS << R.getValueAsDef("Class")->getName(); OS << ", diag::" << R.getValueAsDef("DefaultMapping")->getName(); // Description string. OS << ", \""; OS.write_escaped(R.getValueAsString("Text")) << '"'; // Warning associated with the diagnostic. if (DefInit *DI = dynamic_cast<DefInit*>(R.getValueInit("Group"))) { OS << ", \""; OS.write_escaped(DI->getDef()->getValueAsString("GroupName")) << '"'; } else { OS << ", 0"; } // SFINAE bit if (R.getValueAsBit("SFINAE")) OS << ", true"; else OS << ", false"; OS << ")\n"; } } //===----------------------------------------------------------------------===// // Warning Group Tables generation //===----------------------------------------------------------------------===// struct GroupInfo { std::vector<const Record*> DiagsInGroup; std::vector<std::string> SubGroups; unsigned IDNo; }; void ClangDiagGroupsEmitter::run(raw_ostream &OS) { // Invert the 1-[0/1] mapping of diags to group into a one to many mapping of // groups to diags in the group. std::map<std::string, GroupInfo> DiagsInGroup; std::vector<Record*> Diags = Records.getAllDerivedDefinitions("Diagnostic"); for (unsigned i = 0, e = Diags.size(); i != e; ++i) { const Record *R = Diags[i]; DefInit *DI = dynamic_cast<DefInit*>(R->getValueInit("Group")); if (DI == 0) continue; std::string GroupName = DI->getDef()->getValueAsString("GroupName"); DiagsInGroup[GroupName].DiagsInGroup.push_back(R); } // Add all DiagGroup's to the DiagsInGroup list to make sure we pick up empty // groups (these are warnings that GCC supports that clang never produces). Diags = Records.getAllDerivedDefinitions("DiagGroup"); for (unsigned i = 0, e = Diags.size(); i != e; ++i) { Record *Group = Diags[i]; GroupInfo &GI = DiagsInGroup[Group->getValueAsString("GroupName")]; std::vector<Record*> SubGroups = Group->getValueAsListOfDefs("SubGroups"); for (unsigned j = 0, e = SubGroups.size(); j != e; ++j) GI.SubGroups.push_back(SubGroups[j]->getValueAsString("GroupName")); } // Assign unique ID numbers to the groups. unsigned IDNo = 0; for (std::map<std::string, GroupInfo>::iterator I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I, ++IDNo) I->second.IDNo = IDNo; // Walk through the groups emitting an array for each diagnostic of the diags // that are mapped to. OS << "\n#ifdef GET_DIAG_ARRAYS\n"; unsigned MaxLen = 0; for (std::map<std::string, GroupInfo>::iterator I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I) { MaxLen = std::max(MaxLen, (unsigned)I->first.size()); std::vector<const Record*> &V = I->second.DiagsInGroup; if (!V.empty()) { OS << "static const short DiagArray" << I->second.IDNo << "[] = { "; for (unsigned i = 0, e = V.size(); i != e; ++i) OS << "diag::" << V[i]->getName() << ", "; OS << "-1 };\n"; } const std::vector<std::string> &SubGroups = I->second.SubGroups; if (!SubGroups.empty()) { OS << "static const char DiagSubGroup" << I->second.IDNo << "[] = { "; for (unsigned i = 0, e = SubGroups.size(); i != e; ++i) { std::map<std::string, GroupInfo>::iterator RI = DiagsInGroup.find(SubGroups[i]); assert(RI != DiagsInGroup.end() && "Referenced without existing?"); OS << RI->second.IDNo << ", "; } OS << "-1 };\n"; } } OS << "#endif // GET_DIAG_ARRAYS\n\n"; // Emit the table now. OS << "\n#ifdef GET_DIAG_TABLE\n"; for (std::map<std::string, GroupInfo>::iterator I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I) { // Group option string. OS << " { \""; OS.write_escaped(I->first) << "\"," << std::string(MaxLen-I->first.size()+1, ' '); // Diagnostics in the group. if (I->second.DiagsInGroup.empty()) OS << "0, "; else OS << "DiagArray" << I->second.IDNo << ", "; // Subgroups. if (I->second.SubGroups.empty()) OS << 0; else OS << "DiagSubGroup" << I->second.IDNo; OS << " },\n"; } OS << "#endif // GET_DIAG_TABLE\n\n"; }
//=- ClangDiagnosticsEmitter.cpp - Generate Clang diagnostics tables -*- C++ -*- // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // These tablegen backends emit Clang diagnostics tables. // //===----------------------------------------------------------------------===// #include "ClangDiagnosticsEmitter.h" #include "Record.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Compiler.h" #include "llvm/ADT/DenseSet.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/VectorExtras.h" #include <set> #include <map> using namespace llvm; //===----------------------------------------------------------------------===// // Diagnostic category computation code. //===----------------------------------------------------------------------===// namespace { class DiagGroupParentMap { std::map<const Record*, std::vector<Record*> > Mapping; public: DiagGroupParentMap() { std::vector<Record*> DiagGroups = Records.getAllDerivedDefinitions("DiagGroup"); for (unsigned i = 0, e = DiagGroups.size(); i != e; ++i) { std::vector<Record*> SubGroups = DiagGroups[i]->getValueAsListOfDefs("SubGroups"); for (unsigned j = 0, e = SubGroups.size(); j != e; ++j) Mapping[SubGroups[j]].push_back(DiagGroups[i]); } } const std::vector<Record*> &getParents(const Record *Group) { return Mapping[Group]; } }; } // end anonymous namespace. static std::string getCategoryFromDiagGroup(const Record *Group, DiagGroupParentMap &DiagGroupParents) { // If the DiagGroup has a category, return it. std::string CatName = Group->getValueAsString("CategoryName"); if (!CatName.empty()) return CatName; // The diag group may the subgroup of one or more other diagnostic groups, // check these for a category as well. const std::vector<Record*> &Parents = DiagGroupParents.getParents(Group); for (unsigned i = 0, e = Parents.size(); i != e; ++i) { CatName = getCategoryFromDiagGroup(Parents[i], DiagGroupParents); if (!CatName.empty()) return CatName; } return ""; } /// getDiagnosticCategory - Return the category that the specified diagnostic /// lives in. static std::string getDiagnosticCategory(const Record *R, DiagGroupParentMap &DiagGroupParents) { // If the diagnostic itself has a category, get it. std::string CatName = R->getValueAsString("CategoryName"); if (!CatName.empty()) return CatName; DefInit *Group = dynamic_cast<DefInit*>(R->getValueInit("Group")); if (Group == 0) return ""; // Check the diagnostic's diag group for a category. return getCategoryFromDiagGroup(Group->getDef(), DiagGroupParents); } namespace { class DiagCategoryIDMap { StringMap<unsigned> CategoryIDs; std::vector<std::string> CategoryStrings; public: DiagCategoryIDMap() { DiagGroupParentMap ParentInfo; // The zero'th category is "". CategoryStrings.push_back(""); CategoryIDs[""] = 0; std::vector<Record*> Diags = Records.getAllDerivedDefinitions("Diagnostic"); for (unsigned i = 0, e = Diags.size(); i != e; ++i) { std::string Category = getDiagnosticCategory(Diags[i], ParentInfo); if (Category.empty()) continue; // Skip diags with no category. unsigned &ID = CategoryIDs[Category]; if (ID != 0) continue; // Already seen. ID = CategoryStrings.size(); CategoryStrings.push_back(Category); } } unsigned getID(StringRef CategoryString) { return CategoryIDs[CategoryString]; } typedef std::vector<std::string>::iterator iterator; iterator begin() { return CategoryStrings.begin(); } iterator end() { return CategoryStrings.end(); } }; } // end anonymous namespace. //===----------------------------------------------------------------------===// // Warning Tables (.inc file) generation. //===----------------------------------------------------------------------===// void ClangDiagsDefsEmitter::run(raw_ostream &OS) { // Write the #if guard if (!Component.empty()) { std::string ComponentName = UppercaseString(Component); OS << "#ifdef " << ComponentName << "START\n"; OS << "__" << ComponentName << "START = DIAG_START_" << ComponentName << ",\n"; OS << "#undef " << ComponentName << "START\n"; OS << "#endif\n\n"; } const std::vector<Record*> &Diags = Records.getAllDerivedDefinitions("Diagnostic"); DiagCategoryIDMap CategoryIDs; DiagGroupParentMap DGParentMap; for (unsigned i = 0, e = Diags.size(); i != e; ++i) { const Record &R = *Diags[i]; // Filter by component. if (!Component.empty() && Component != R.getValueAsString("Component")) continue; OS << "DIAG(" << R.getName() << ", "; OS << R.getValueAsDef("Class")->getName(); OS << ", diag::" << R.getValueAsDef("DefaultMapping")->getName(); // Description string. OS << ", \""; OS.write_escaped(R.getValueAsString("Text")) << '"'; // Warning associated with the diagnostic. if (DefInit *DI = dynamic_cast<DefInit*>(R.getValueInit("Group"))) { OS << ", \""; OS.write_escaped(DI->getDef()->getValueAsString("GroupName")) << '"'; } else { OS << ", 0"; } // SFINAE bit if (R.getValueAsBit("SFINAE")) OS << ", true"; else OS << ", false"; // Category number. OS << ", " << CategoryIDs.getID(getDiagnosticCategory(&R, DGParentMap)); OS << ")\n"; } } //===----------------------------------------------------------------------===// // Warning Group Tables generation //===----------------------------------------------------------------------===// struct GroupInfo { std::vector<const Record*> DiagsInGroup; std::vector<std::string> SubGroups; unsigned IDNo; }; void ClangDiagGroupsEmitter::run(raw_ostream &OS) { // Compute a mapping from a DiagGroup to all of its parents. DiagGroupParentMap DGParentMap; // Invert the 1-[0/1] mapping of diags to group into a one to many mapping of // groups to diags in the group. std::map<std::string, GroupInfo> DiagsInGroup; std::vector<Record*> Diags = Records.getAllDerivedDefinitions("Diagnostic"); for (unsigned i = 0, e = Diags.size(); i != e; ++i) { const Record *R = Diags[i]; DefInit *DI = dynamic_cast<DefInit*>(R->getValueInit("Group")); if (DI == 0) continue; std::string GroupName = DI->getDef()->getValueAsString("GroupName"); DiagsInGroup[GroupName].DiagsInGroup.push_back(R); } // Add all DiagGroup's to the DiagsInGroup list to make sure we pick up empty // groups (these are warnings that GCC supports that clang never produces). std::vector<Record*> DiagGroups = Records.getAllDerivedDefinitions("DiagGroup"); for (unsigned i = 0, e = DiagGroups.size(); i != e; ++i) { Record *Group = DiagGroups[i]; GroupInfo &GI = DiagsInGroup[Group->getValueAsString("GroupName")]; std::vector<Record*> SubGroups = Group->getValueAsListOfDefs("SubGroups"); for (unsigned j = 0, e = SubGroups.size(); j != e; ++j) GI.SubGroups.push_back(SubGroups[j]->getValueAsString("GroupName")); } // Assign unique ID numbers to the groups. unsigned IDNo = 0; for (std::map<std::string, GroupInfo>::iterator I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I, ++IDNo) I->second.IDNo = IDNo; // Walk through the groups emitting an array for each diagnostic of the diags // that are mapped to. OS << "\n#ifdef GET_DIAG_ARRAYS\n"; unsigned MaxLen = 0; for (std::map<std::string, GroupInfo>::iterator I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I) { MaxLen = std::max(MaxLen, (unsigned)I->first.size()); std::vector<const Record*> &V = I->second.DiagsInGroup; if (!V.empty()) { OS << "static const short DiagArray" << I->second.IDNo << "[] = { "; for (unsigned i = 0, e = V.size(); i != e; ++i) OS << "diag::" << V[i]->getName() << ", "; OS << "-1 };\n"; } const std::vector<std::string> &SubGroups = I->second.SubGroups; if (!SubGroups.empty()) { OS << "static const char DiagSubGroup" << I->second.IDNo << "[] = { "; for (unsigned i = 0, e = SubGroups.size(); i != e; ++i) { std::map<std::string, GroupInfo>::iterator RI = DiagsInGroup.find(SubGroups[i]); assert(RI != DiagsInGroup.end() && "Referenced without existing?"); OS << RI->second.IDNo << ", "; } OS << "-1 };\n"; } } OS << "#endif // GET_DIAG_ARRAYS\n\n"; // Emit the table now. OS << "\n#ifdef GET_DIAG_TABLE\n"; for (std::map<std::string, GroupInfo>::iterator I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I) { // Group option string. OS << " { \""; OS.write_escaped(I->first) << "\"," << std::string(MaxLen-I->first.size()+1, ' '); // Diagnostics in the group. if (I->second.DiagsInGroup.empty()) OS << "0, "; else OS << "DiagArray" << I->second.IDNo << ", "; // Subgroups. if (I->second.SubGroups.empty()) OS << 0; else OS << "DiagSubGroup" << I->second.IDNo; OS << " },\n"; } OS << "#endif // GET_DIAG_TABLE\n\n"; // Emit the category table next. DiagCategoryIDMap CategoriesByID; OS << "\n#ifdef GET_CATEGORY_TABLE\n"; for (DiagCategoryIDMap::iterator I = CategoriesByID.begin(), E = CategoriesByID.end(); I != E; ++I) OS << "CATEGORY(\"" << *I << "\")\n"; OS << "#endif // GET_CATEGORY_TABLE\n\n"; }
add the ability to associate 'category' names with clang diagnostics and diagnostic groups. This allows the compiler to group diagnostics together (e.g. "Logic Warning", "Format String Warning", etc) like the static analyzer does. This is not exposed through anything in the compiler yet.
add the ability to associate 'category' names with clang diagnostics and diagnostic groups. This allows the compiler to group diagnostics together (e.g. "Logic Warning", "Format String Warning", etc) like the static analyzer does. This is not exposed through anything in the compiler yet. git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@103050 91177308-0d34-0410-b5e6-96231b3b80d8
C++
bsd-2-clause
chubbymaggie/asap,chubbymaggie/asap,GPUOpen-Drivers/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,dslab-epfl/asap,dslab-epfl/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,dslab-epfl/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,chubbymaggie/asap,dslab-epfl/asap,apple/swift-llvm,chubbymaggie/asap,chubbymaggie/asap,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,chubbymaggie/asap,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm
190a845505b1142166e8b25d953ab20d19276b87
selfdrive/common/util.cc
selfdrive/common/util.cc
#include "selfdrive/common/util.h" #include <cassert> #include <cerrno> #include <cstring> #include <dirent.h> #include <fstream> #include <sstream> #include <iomanip> #ifdef __linux__ #include <sys/prctl.h> #include <sys/syscall.h> #ifndef __USE_GNU #define __USE_GNU #endif #include <sched.h> #endif // __linux__ void set_thread_name(const char* name) { #ifdef __linux__ // pthread_setname_np is dumb (fails instead of truncates) prctl(PR_SET_NAME, (unsigned long)name, 0, 0, 0); #endif } int set_realtime_priority(int level) { #ifdef __linux__ long tid = syscall(SYS_gettid); // should match python using chrt struct sched_param sa; memset(&sa, 0, sizeof(sa)); sa.sched_priority = level; return sched_setscheduler(tid, SCHED_FIFO, &sa); #else return -1; #endif } int set_core_affinity(int core) { #ifdef __linux__ long tid = syscall(SYS_gettid); cpu_set_t rt_cpu; CPU_ZERO(&rt_cpu); CPU_SET(core, &rt_cpu); return sched_setaffinity(tid, sizeof(rt_cpu), &rt_cpu); #else return -1; #endif } namespace util { std::string read_file(const std::string& fn) { std::ifstream ifs(fn, std::ios::binary | std::ios::ate); if (ifs) { int pos = ifs.tellg(); if (pos > 0) { std::string result; result.resize(pos); ifs.seekg(0, std::ios::beg); ifs.read(result.data(), pos); if (ifs) { return result; } } } ifs.close(); // fallback for files created on read, e.g. procfs std::ifstream f(fn); std::stringstream buffer; buffer << f.rdbuf(); return buffer.str(); } int read_files_in_dir(const std::string &path, std::map<std::string, std::string> *contents) { DIR *d = opendir(path.c_str()); if (!d) return -1; struct dirent *de = NULL; while ((de = readdir(d))) { if (isalnum(de->d_name[0])) { (*contents)[de->d_name] = util::read_file(path + "/" + de->d_name); } } closedir(d); return 0; } int write_file(const char* path, const void* data, size_t size, int flags, mode_t mode) { int fd = open(path, flags, mode); if (fd == -1) { return -1; } ssize_t n = write(fd, data, size); close(fd); return (n >= 0 && (size_t)n == size) ? 0 : -1; } std::string readlink(const std::string &path) { char buff[4096]; ssize_t len = ::readlink(path.c_str(), buff, sizeof(buff)-1); if (len != -1) { buff[len] = '\0'; return std::string(buff); } return ""; } bool file_exists(const std::string& fn) { std::ifstream f(fn); return f.good(); } std::string getenv_default(const char* env_var, const char * suffix, const char* default_val) { const char* env_val = getenv(env_var); if (env_val != NULL) { return std::string(env_val) + std::string(suffix); } else { return std::string(default_val); } } std::string tohex(const uint8_t *buf, size_t buf_size) { std::unique_ptr<char[]> hexbuf(new char[buf_size * 2 + 1]); for (size_t i = 0; i < buf_size; i++) { sprintf(&hexbuf[i * 2], "%02x", buf[i]); } hexbuf[buf_size * 2] = 0; return std::string(hexbuf.get(), hexbuf.get() + buf_size * 2); } std::string hexdump(const std::string& in) { std::stringstream ss; ss << std::hex << std::setfill('0'); for (size_t i = 0; i < in.size(); i++) { ss << std::setw(2) << static_cast<unsigned int>(static_cast<unsigned char>(in[i])); } return ss.str(); } std::string base_name(std::string const &path) { size_t pos = path.find_last_of("/"); if (pos == std::string::npos) return path; return path.substr(pos + 1); } std::string dir_name(std::string const &path) { size_t pos = path.find_last_of("/"); if (pos == std::string::npos) return ""; return path.substr(0, pos); } bool is_valid_dongle_id(std::string const& dongle_id) { return !dongle_id.empty() && dongle_id != "UnregisteredDevice"; } struct tm get_time() { time_t rawtime; time(&rawtime); struct tm sys_time; gmtime_r(&rawtime, &sys_time); return sys_time; } bool time_valid(struct tm sys_time) { int year = 1900 + sys_time.tm_year; int month = 1 + sys_time.tm_mon; return (year > 2020) || (year == 2020 && month >= 10); } } // namespace util
#include "selfdrive/common/util.h" #include <cassert> #include <cerrno> #include <cstring> #include <dirent.h> #include <fstream> #include <sstream> #include <iomanip> #ifdef __linux__ #include <sys/prctl.h> #include <sys/syscall.h> #ifndef __USE_GNU #define __USE_GNU #endif #include <sched.h> #endif // __linux__ void set_thread_name(const char* name) { #ifdef __linux__ // pthread_setname_np is dumb (fails instead of truncates) prctl(PR_SET_NAME, (unsigned long)name, 0, 0, 0); #endif } int set_realtime_priority(int level) { #ifdef __linux__ long tid = syscall(SYS_gettid); // should match python using chrt struct sched_param sa; memset(&sa, 0, sizeof(sa)); sa.sched_priority = level; return sched_setscheduler(tid, SCHED_FIFO, &sa); #else return -1; #endif } int set_core_affinity(int core) { #ifdef __linux__ long tid = syscall(SYS_gettid); cpu_set_t rt_cpu; CPU_ZERO(&rt_cpu); CPU_SET(core, &rt_cpu); return sched_setaffinity(tid, sizeof(rt_cpu), &rt_cpu); #else return -1; #endif } namespace util { std::string read_file(const std::string& fn) { std::ifstream f(fn, std::ios::binary | std::ios::in | std::ios::ate); if (f) { int pos = f.tellg(); if (pos > 0) { std::string result; result.resize(pos); f.seekg(0, std::ios::beg); if (f.read(result.data(), pos)) { return result; } } else { // fallback for files created on read, e.g. procfs std::stringstream buffer; buffer << f.rdbuf(); return buffer.str(); } } return std::string(); } int read_files_in_dir(const std::string &path, std::map<std::string, std::string> *contents) { DIR *d = opendir(path.c_str()); if (!d) return -1; struct dirent *de = NULL; while ((de = readdir(d))) { if (isalnum(de->d_name[0])) { (*contents)[de->d_name] = util::read_file(path + "/" + de->d_name); } } closedir(d); return 0; } int write_file(const char* path, const void* data, size_t size, int flags, mode_t mode) { int fd = open(path, flags, mode); if (fd == -1) { return -1; } ssize_t n = write(fd, data, size); close(fd); return (n >= 0 && (size_t)n == size) ? 0 : -1; } std::string readlink(const std::string &path) { char buff[4096]; ssize_t len = ::readlink(path.c_str(), buff, sizeof(buff)-1); if (len != -1) { buff[len] = '\0'; return std::string(buff); } return ""; } bool file_exists(const std::string& fn) { std::ifstream f(fn); return f.good(); } std::string getenv_default(const char* env_var, const char * suffix, const char* default_val) { const char* env_val = getenv(env_var); if (env_val != NULL) { return std::string(env_val) + std::string(suffix); } else { return std::string(default_val); } } std::string tohex(const uint8_t *buf, size_t buf_size) { std::unique_ptr<char[]> hexbuf(new char[buf_size * 2 + 1]); for (size_t i = 0; i < buf_size; i++) { sprintf(&hexbuf[i * 2], "%02x", buf[i]); } hexbuf[buf_size * 2] = 0; return std::string(hexbuf.get(), hexbuf.get() + buf_size * 2); } std::string hexdump(const std::string& in) { std::stringstream ss; ss << std::hex << std::setfill('0'); for (size_t i = 0; i < in.size(); i++) { ss << std::setw(2) << static_cast<unsigned int>(static_cast<unsigned char>(in[i])); } return ss.str(); } std::string base_name(std::string const &path) { size_t pos = path.find_last_of("/"); if (pos == std::string::npos) return path; return path.substr(pos + 1); } std::string dir_name(std::string const &path) { size_t pos = path.find_last_of("/"); if (pos == std::string::npos) return ""; return path.substr(0, pos); } bool is_valid_dongle_id(std::string const& dongle_id) { return !dongle_id.empty() && dongle_id != "UnregisteredDevice"; } struct tm get_time() { time_t rawtime; time(&rawtime); struct tm sys_time; gmtime_r(&rawtime, &sys_time); return sys_time; } bool time_valid(struct tm sys_time) { int year = 1900 + sys_time.tm_year; int month = 1 + sys_time.tm_mon; return (year > 2020) || (year == 2020 && month >= 10); } } // namespace util
refactor read_file (#21295)
util.cc: refactor read_file (#21295) * mode read & open once * change return statement for better readibility * apply reviews * Update selfdrive/common/util.cc * fix Co-authored-by: Adeeb Shihadeh <[email protected]>
C++
mit
commaai/openpilot,commaai/openpilot,commaai/openpilot,commaai/openpilot,commaai/openpilot,commaai/openpilot
ecf06b9d661e933004f12dee1a31fd7ce32baab3
firmware/Adafruit_Fingerprint.cpp
firmware/Adafruit_Fingerprint.cpp
/*************************************************** This is a library for our optical Fingerprint sensor Designed specifically to work with the Adafruit BMP085 Breakout ----> http://www.adafruit.com/products/751 These displays use TTL Serial to communicate, 2 pins are required to interface Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! Written by Limor Fried/Ladyada for Adafruit Industries. BSD license, all text above must be included in any redistribution !!! Adapted for Spark Core by Paul Kourany, May 2014 !!! ****************************************************/ #include "Adafruit_Fingerprint.h" #if defined (SPARK) // #else #include <util/delay.h> #if (ARDUINO >= 100) #include <SoftwareSerial.h> #else #include <NewSoftSerial.h> #endif #endif //static SoftwareSerial mySerial = SoftwareSerial(2, 3); #if defined (SPARK) Adafruit_Fingerprint::Adafruit_Fingerprint(USARTSerial *ss) { #else #if ARDUINO >= 100 Adafruit_Fingerprint::Adafruit_Fingerprint(SoftwareSerial *ss) { #else Adafruit_Fingerprint::Adafruit_Fingerprint(NewSoftSerial *ss) { #endif #endif thePassword = 0; theAddress = 0xFFFFFFFF; mySerial = ss; } void Adafruit_Fingerprint::begin(uint16_t baudrate) { mySerial->begin(baudrate); } boolean Adafruit_Fingerprint::verifyPassword(void) { uint8_t packet[] = {FINGERPRINT_VERIFYPASSWORD, (thePassword >> 24), (thePassword >> 16), (thePassword >> 8), thePassword}; writePacket(theAddress, FINGERPRINT_COMMANDPACKET, 7, packet); uint8_t len = getReply(packet); if ((len == 1) && (packet[0] == FINGERPRINT_ACKPACKET) && (packet[1] == FINGERPRINT_OK)) return true; /* Serial.print("\nGot packet type "); Serial.print(packet[0]); for (uint8_t i=1; i<len+1;i++) { Serial.print(" 0x"); Serial.print(packet[i], HEX); } */ return false; } uint8_t Adafruit_Fingerprint::getImage(void) { uint8_t packet[] = {FINGERPRINT_GETIMAGE}; writePacket(theAddress, FINGERPRINT_COMMANDPACKET, 3, packet); uint8_t len = getReply(packet); if ((len != 1) && (packet[0] != FINGERPRINT_ACKPACKET)) return -1; return packet[1]; } uint8_t Adafruit_Fingerprint::image2Tz(uint8_t slot) { uint8_t packet[] = {FINGERPRINT_IMAGE2TZ, slot}; writePacket(theAddress, FINGERPRINT_COMMANDPACKET, sizeof(packet)+2, packet); uint8_t len = getReply(packet); if ((len != 1) && (packet[0] != FINGERPRINT_ACKPACKET)) return -1; return packet[1]; } uint8_t Adafruit_Fingerprint::createModel(void) { uint8_t packet[] = {FINGERPRINT_REGMODEL}; writePacket(theAddress, FINGERPRINT_COMMANDPACKET, sizeof(packet)+2, packet); uint8_t len = getReply(packet); if ((len != 1) && (packet[0] != FINGERPRINT_ACKPACKET)) return -1; return packet[1]; } uint8_t Adafruit_Fingerprint::storeModel(uint16_t id) { uint8_t packet[] = {FINGERPRINT_STORE, 0x01, id >> 8, id & 0xFF}; writePacket(theAddress, FINGERPRINT_COMMANDPACKET, sizeof(packet)+2, packet); uint8_t len = getReply(packet); if ((len != 1) && (packet[0] != FINGERPRINT_ACKPACKET)) return -1; return packet[1]; } uint8_t Adafruit_Fingerprint::emptyDatabase(void) { uint8_t packet[] = {FINGERPRINT_EMPTY}; writePacket(theAddress, FINGERPRINT_COMMANDPACKET, sizeof(packet)+2, packet); uint8_t len = getReply(packet); if ((len != 1) && (packet[0] != FINGERPRINT_ACKPACKET)) return -1; return packet[1]; } uint8_t Adafruit_Fingerprint::fingerFastSearch(void) { fingerID = 0xFFFF; confidence = 0xFFFF; // high speed search of slot #1 starting at page 0x0000 and page #0x00A3 uint8_t packet[] = {FINGERPRINT_HISPEEDSEARCH, 0x01, 0x00, 0x00, 0x00, 0xA3}; writePacket(theAddress, FINGERPRINT_COMMANDPACKET, sizeof(packet)+2, packet); uint8_t len = getReply(packet); if ((len != 1) && (packet[0] != FINGERPRINT_ACKPACKET)) return -1; fingerID = packet[2]; fingerID <<= 8; fingerID |= packet[3]; confidence = packet[4]; confidence <<= 8; confidence |= packet[5]; return packet[1]; } uint8_t Adafruit_Fingerprint::getTemplateCount(void) { templateCount = 0xFFFF; // get number of templates in memory uint8_t packet[] = {FINGERPRINT_TEMPLATECOUNT}; writePacket(theAddress, FINGERPRINT_COMMANDPACKET, sizeof(packet)+2, packet); uint8_t len = getReply(packet); if ((len != 1) && (packet[0] != FINGERPRINT_ACKPACKET)) return -1; templateCount = packet[2]; templateCount <<= 8; templateCount |= packet[3]; return packet[1]; } void Adafruit_Fingerprint::writePacket(uint32_t addr, uint8_t packettype, uint16_t len, uint8_t *packet) { #ifdef FINGERPRINT_DEBUG Serial.print("---> 0x"); Serial.print((uint8_t)(FINGERPRINT_STARTCODE >> 8), HEX); Serial.print(" 0x"); Serial.print((uint8_t)FINGERPRINT_STARTCODE, HEX); Serial.print(" 0x"); Serial.print((uint8_t)(addr >> 24), HEX); Serial.print(" 0x"); Serial.print((uint8_t)(addr >> 16), HEX); Serial.print(" 0x"); Serial.print((uint8_t)(addr >> 8), HEX); Serial.print(" 0x"); Serial.print((uint8_t)(addr), HEX); Serial.print(" 0x"); Serial.print((uint8_t)packettype, HEX); Serial.print(" 0x"); Serial.print((uint8_t)(len >> 8), HEX); Serial.print(" 0x"); Serial.print((uint8_t)(len), HEX); #endif #if ((ARDUINO >= 100) || defined (SPARK)) mySerial->write((uint8_t)(FINGERPRINT_STARTCODE >> 8)); mySerial->write((uint8_t)FINGERPRINT_STARTCODE); mySerial->write((uint8_t)(addr >> 24)); mySerial->write((uint8_t)(addr >> 16)); mySerial->write((uint8_t)(addr >> 8)); mySerial->write((uint8_t)(addr)); mySerial->write((uint8_t)packettype); mySerial->write((uint8_t)(len >> 8)); mySerial->write((uint8_t)(len)); #else mySerial->print((uint8_t)(FINGERPRINT_STARTCODE >> 8), BYTE); mySerial->print((uint8_t)FINGERPRINT_STARTCODE, BYTE); mySerial->print((uint8_t)(addr >> 24), BYTE); mySerial->print((uint8_t)(addr >> 16), BYTE); mySerial->print((uint8_t)(addr >> 8), BYTE); mySerial->print((uint8_t)(addr), BYTE); mySerial->print((uint8_t)packettype, BYTE); mySerial->print((uint8_t)(len >> 8), BYTE); mySerial->print((uint8_t)(len), BYTE); #endif uint16_t sum = (len>>8) + (len&0xFF) + packettype; for (uint8_t i=0; i< len-2; i++) { #if ((ARDUINO >= 100) || defined (SPARK)) mySerial->write((uint8_t)(packet[i])); #else mySerial->print((uint8_t)(packet[i]), BYTE); #endif #ifdef FINGERPRINT_DEBUG Serial.print(" 0x"); Serial.print(packet[i], HEX); #endif sum += packet[i]; } #ifdef FINGERPRINT_DEBUG //Serial.print("Checksum = 0x"); Serial.println(sum); Serial.print(" 0x"); Serial.print((uint8_t)(sum>>8), HEX); Serial.print(" 0x"); Serial.println((uint8_t)(sum), HEX); #endif #if ((ARDUINO >= 100) || defined (SPARK)) mySerial->write((uint8_t)(sum>>8)); mySerial->write((uint8_t)sum); #else mySerial->print((uint8_t)(sum>>8), BYTE); mySerial->print((uint8_t)sum, BYTE); #endif } uint8_t Adafruit_Fingerprint::getReply(uint8_t packet[], uint16_t timeout) { uint8_t reply[20], idx; uint16_t timer=0; idx = 0; #ifdef FINGERPRINT_DEBUG Serial.print("<--- "); #endif while (true) { while (!mySerial->available()) { delay(1); timer++; if (timer >= timeout) return FINGERPRINT_TIMEOUT; } // something to read! reply[idx] = mySerial->read(); #ifdef FINGERPRINT_DEBUG Serial.print(" 0x"); Serial.print(reply[idx], HEX); #endif if ((idx == 0) && (reply[0] != (FINGERPRINT_STARTCODE >> 8))) continue; idx++; // check packet! if (idx >= 9) { if ((reply[0] != (FINGERPRINT_STARTCODE >> 8)) || (reply[1] != (FINGERPRINT_STARTCODE & 0xFF))) return FINGERPRINT_BADPACKET; uint8_t packettype = reply[6]; //Serial.print("Packet type"); Serial.println(packettype); uint16_t len = reply[7]; len <<= 8; len |= reply[8]; len -= 2; //Serial.print("Packet len"); Serial.println(len); if (idx <= (len+10)) continue; packet[0] = packettype; for (uint8_t i=0; i<len; i++) { packet[1+i] = reply[9+i]; } #ifdef FINGERPRINT_DEBUG Serial.println(); #endif return len; } } }
/*************************************************** This is a library for our optical Fingerprint sensor Designed specifically to work with the Adafruit BMP085 Breakout ----> http://www.adafruit.com/products/751 These displays use TTL Serial to communicate, 2 pins are required to interface Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! Written by Limor Fried/Ladyada for Adafruit Industries. BSD license, all text above must be included in any redistribution !!! Adapted for Spark Core by Paul Kourany, May 2014 !!! ****************************************************/ #include "Adafruit_Fingerprint.h" #if defined (SPARK) // #else #include <util/delay.h> #if (ARDUINO >= 100) #include <SoftwareSerial.h> #else #include <NewSoftSerial.h> #endif #endif //static SoftwareSerial mySerial = SoftwareSerial(2, 3); #if defined (SPARK) Adafruit_Fingerprint::Adafruit_Fingerprint(USARTSerial *ss) { #else #if ARDUINO >= 100 Adafruit_Fingerprint::Adafruit_Fingerprint(SoftwareSerial *ss) { #else Adafruit_Fingerprint::Adafruit_Fingerprint(NewSoftSerial *ss) { #endif #endif thePassword = 0; theAddress = 0xFFFFFFFF; mySerial = ss; } void Adafruit_Fingerprint::begin(uint16_t baudrate) { mySerial->begin(baudrate); } boolean Adafruit_Fingerprint::verifyPassword(void) { uint8_t packet[] = {FINGERPRINT_VERIFYPASSWORD, (thePassword >> 24), (thePassword >> 16), (thePassword >> 8), thePassword}; writePacket(theAddress, FINGERPRINT_COMMANDPACKET, 7, packet); uint8_t len = getReply(packet); if ((len == 1) && (packet[0] == FINGERPRINT_ACKPACKET) && (packet[1] == FINGERPRINT_OK)) return true; /* Serial.print("\nGot packet type "); Serial.print(packet[0]); for (uint8_t i=1; i<len+1;i++) { Serial.print(" 0x"); Serial.print(packet[i], HEX); } */ return false; } uint8_t Adafruit_Fingerprint::getImage(void) { uint8_t packet[] = {FINGERPRINT_GETIMAGE}; writePacket(theAddress, FINGERPRINT_COMMANDPACKET, 3, packet); uint8_t len = getReply(packet); if ((len != 1) && (packet[0] != FINGERPRINT_ACKPACKET)) return -1; return packet[1]; } uint8_t Adafruit_Fingerprint::image2Tz(uint8_t slot) { uint8_t packet[] = {FINGERPRINT_IMAGE2TZ, slot}; writePacket(theAddress, FINGERPRINT_COMMANDPACKET, sizeof(packet)+2, packet); uint8_t len = getReply(packet); if ((len != 1) && (packet[0] != FINGERPRINT_ACKPACKET)) return -1; return packet[1]; } uint8_t Adafruit_Fingerprint::createModel(void) { uint8_t packet[] = {FINGERPRINT_REGMODEL}; writePacket(theAddress, FINGERPRINT_COMMANDPACKET, sizeof(packet)+2, packet); uint8_t len = getReply(packet); if ((len != 1) && (packet[0] != FINGERPRINT_ACKPACKET)) return -1; return packet[1]; } uint8_t Adafruit_Fingerprint::storeModel(uint16_t id) { uint8_t packet[] = {FINGERPRINT_STORE, 0x01, id >> 8, id & 0xFF}; writePacket(theAddress, FINGERPRINT_COMMANDPACKET, sizeof(packet)+2, packet); uint8_t len = getReply(packet); if ((len != 1) && (packet[0] != FINGERPRINT_ACKPACKET)) return -1; return packet[1]; } uint8_t Adafruit_Fingerprint::deleteModel(uint16_t id) { uint8_t packet[] = {FINGERPRINT_DELETE, id >> 8, id & 0xFF, 0x00, 0x01}; writePacket(theAddress, FINGERPRINT_COMMANDPACKET, sizeof(packet)+2, packet); uint8_t len = getReply(packet); if ((len != 1) && (packet[0] != FINGERPRINT_ACKPACKET)) return -1; return packet[1]; } uint8_t Adafruit_Fingerprint::emptyDatabase(void) { uint8_t packet[] = {FINGERPRINT_EMPTY}; writePacket(theAddress, FINGERPRINT_COMMANDPACKET, sizeof(packet)+2, packet); uint8_t len = getReply(packet); if ((len != 1) && (packet[0] != FINGERPRINT_ACKPACKET)) return -1; return packet[1]; } uint8_t Adafruit_Fingerprint::fingerFastSearch(void) { fingerID = 0xFFFF; confidence = 0xFFFF; // high speed search of slot #1 starting at page 0x0000 and page #0x00A3 uint8_t packet[] = {FINGERPRINT_HISPEEDSEARCH, 0x01, 0x00, 0x00, 0x00, 0xA3}; writePacket(theAddress, FINGERPRINT_COMMANDPACKET, sizeof(packet)+2, packet); uint8_t len = getReply(packet); if ((len != 1) && (packet[0] != FINGERPRINT_ACKPACKET)) return -1; fingerID = packet[2]; fingerID <<= 8; fingerID |= packet[3]; confidence = packet[4]; confidence <<= 8; confidence |= packet[5]; return packet[1]; } uint8_t Adafruit_Fingerprint::getTemplateCount(void) { templateCount = 0xFFFF; // get number of templates in memory uint8_t packet[] = {FINGERPRINT_TEMPLATECOUNT}; writePacket(theAddress, FINGERPRINT_COMMANDPACKET, sizeof(packet)+2, packet); uint8_t len = getReply(packet); if ((len != 1) && (packet[0] != FINGERPRINT_ACKPACKET)) return -1; templateCount = packet[2]; templateCount <<= 8; templateCount |= packet[3]; return packet[1]; } void Adafruit_Fingerprint::writePacket(uint32_t addr, uint8_t packettype, uint16_t len, uint8_t *packet) { #ifdef FINGERPRINT_DEBUG Serial.print("---> 0x"); Serial.print((uint8_t)(FINGERPRINT_STARTCODE >> 8), HEX); Serial.print(" 0x"); Serial.print((uint8_t)FINGERPRINT_STARTCODE, HEX); Serial.print(" 0x"); Serial.print((uint8_t)(addr >> 24), HEX); Serial.print(" 0x"); Serial.print((uint8_t)(addr >> 16), HEX); Serial.print(" 0x"); Serial.print((uint8_t)(addr >> 8), HEX); Serial.print(" 0x"); Serial.print((uint8_t)(addr), HEX); Serial.print(" 0x"); Serial.print((uint8_t)packettype, HEX); Serial.print(" 0x"); Serial.print((uint8_t)(len >> 8), HEX); Serial.print(" 0x"); Serial.print((uint8_t)(len), HEX); #endif #if ((ARDUINO >= 100) || defined (SPARK)) mySerial->write((uint8_t)(FINGERPRINT_STARTCODE >> 8)); mySerial->write((uint8_t)FINGERPRINT_STARTCODE); mySerial->write((uint8_t)(addr >> 24)); mySerial->write((uint8_t)(addr >> 16)); mySerial->write((uint8_t)(addr >> 8)); mySerial->write((uint8_t)(addr)); mySerial->write((uint8_t)packettype); mySerial->write((uint8_t)(len >> 8)); mySerial->write((uint8_t)(len)); #else mySerial->print((uint8_t)(FINGERPRINT_STARTCODE >> 8), BYTE); mySerial->print((uint8_t)FINGERPRINT_STARTCODE, BYTE); mySerial->print((uint8_t)(addr >> 24), BYTE); mySerial->print((uint8_t)(addr >> 16), BYTE); mySerial->print((uint8_t)(addr >> 8), BYTE); mySerial->print((uint8_t)(addr), BYTE); mySerial->print((uint8_t)packettype, BYTE); mySerial->print((uint8_t)(len >> 8), BYTE); mySerial->print((uint8_t)(len), BYTE); #endif uint16_t sum = (len>>8) + (len&0xFF) + packettype; for (uint8_t i=0; i< len-2; i++) { #if ((ARDUINO >= 100) || defined (SPARK)) mySerial->write((uint8_t)(packet[i])); #else mySerial->print((uint8_t)(packet[i]), BYTE); #endif #ifdef FINGERPRINT_DEBUG Serial.print(" 0x"); Serial.print(packet[i], HEX); #endif sum += packet[i]; } #ifdef FINGERPRINT_DEBUG //Serial.print("Checksum = 0x"); Serial.println(sum); Serial.print(" 0x"); Serial.print((uint8_t)(sum>>8), HEX); Serial.print(" 0x"); Serial.println((uint8_t)(sum), HEX); #endif #if ((ARDUINO >= 100) || defined (SPARK)) mySerial->write((uint8_t)(sum>>8)); mySerial->write((uint8_t)sum); #else mySerial->print((uint8_t)(sum>>8), BYTE); mySerial->print((uint8_t)sum, BYTE); #endif } uint8_t Adafruit_Fingerprint::getReply(uint8_t packet[], uint16_t timeout) { uint8_t reply[20], idx; uint16_t timer=0; idx = 0; #ifdef FINGERPRINT_DEBUG Serial.print("<--- "); #endif while (true) { while (!mySerial->available()) { delay(1); timer++; if (timer >= timeout) return FINGERPRINT_TIMEOUT; } // something to read! reply[idx] = mySerial->read(); #ifdef FINGERPRINT_DEBUG Serial.print(" 0x"); Serial.print(reply[idx], HEX); #endif if ((idx == 0) && (reply[0] != (FINGERPRINT_STARTCODE >> 8))) continue; idx++; // check packet! if (idx >= 9) { if ((reply[0] != (FINGERPRINT_STARTCODE >> 8)) || (reply[1] != (FINGERPRINT_STARTCODE & 0xFF))) return FINGERPRINT_BADPACKET; uint8_t packettype = reply[6]; //Serial.print("Packet type"); Serial.println(packettype); uint16_t len = reply[7]; len <<= 8; len |= reply[8]; len -= 2; //Serial.print("Packet len"); Serial.println(len); if (idx <= (len+10)) continue; packet[0] = packettype; for (uint8_t i=0; i<len; i++) { packet[1+i] = reply[9+i]; } #ifdef FINGERPRINT_DEBUG Serial.println(); #endif return len; } } }
Update Adafruit_Fingerprint.cpp
Update Adafruit_Fingerprint.cpp you forgot the deleteModel method! Can you update the library? tkhs
C++
bsd-3-clause
pkourany/Adafruit_Fingerprint_Library