blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
9ea58c0a1f35de073a654753be6234236143f86c
b7f3edb5b7c62174bed808079c3b21fb9ea51d52
/content/public/test/fake_render_widget_host.h
e27094e2c8541e8bb3bb0cd6cfb220546ece1a2f
[ "BSD-3-Clause" ]
permissive
otcshare/chromium-src
26a7372773b53b236784c51677c566dc0ad839e4
64bee65c921db7e78e25d08f1e98da2668b57be5
refs/heads/webml
2023-03-21T03:20:15.377034
2020-11-16T01:40:14
2020-11-16T01:40:14
209,262,645
18
21
BSD-3-Clause
2023-03-23T06:20:07
2019-09-18T08:52:07
null
UTF-8
C++
false
false
4,534
h
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_PUBLIC_TEST_FAKE_RENDER_WIDGET_HOST_H_ #define CONTENT_PUBLIC_TEST_FAKE_RENDER_WIDGET_HOST_H_ #include <utility> #include "base/macros.h" #include "mojo/public/cpp/bindings/associated_receiver.h" #include "mojo/public/cpp/bindings/associated_remote.h" #include "mojo/public/cpp/bindings/remote.h" #include "third_party/blink/public/mojom/frame/intrinsic_sizing_info.mojom-forward.h" #include "third_party/blink/public/mojom/page/widget.mojom.h" #include "ui/base/ime/mojom/text_input_state.mojom.h" namespace content { class FakeRenderWidgetHost : public blink::mojom::FrameWidgetHost, public blink::mojom::WidgetHost, public blink::mojom::WidgetInputHandlerHost { public: FakeRenderWidgetHost(); ~FakeRenderWidgetHost() override; std::pair<mojo::PendingAssociatedRemote<blink::mojom::FrameWidgetHost>, mojo::PendingAssociatedReceiver<blink::mojom::FrameWidget>> BindNewFrameWidgetInterfaces(); std::pair<mojo::PendingAssociatedRemote<blink::mojom::WidgetHost>, mojo::PendingAssociatedReceiver<blink::mojom::Widget>> BindNewWidgetInterfaces(); // blink::mojom::FrameWidgetHost overrides. void AnimateDoubleTapZoomInMainFrame(const gfx::Point& tap_point, const gfx::Rect& rect_to_zoom) override; void ZoomToFindInPageRectInMainFrame(const gfx::Rect& rect_to_zoom) override; void SetHasTouchEventHandlers(bool has_handlers) override; void IntrinsicSizingInfoChanged( blink::mojom::IntrinsicSizingInfoPtr sizing_info) override; void AutoscrollStart(const gfx::PointF& position) override; void AutoscrollFling(const gfx::Vector2dF& position) override; void AutoscrollEnd() override; void DidFirstVisuallyNonEmptyPaint() override; // blink::mojom::WidgetHost overrides. void SetCursor(const ui::Cursor& cursor) override; void SetToolTipText(const base::string16& tooltip_text, base::i18n::TextDirection text_direction_hint) override; void TextInputStateChanged(ui::mojom::TextInputStatePtr state) override; void SelectionBoundsChanged(const gfx::Rect& anchor_rect, base::i18n::TextDirection anchor_dir, const gfx::Rect& focus_rect, base::i18n::TextDirection focus_dir, bool is_anchor_first) override; // blink::mojom::WidgetInputHandlerHost overrides. void SetTouchActionFromMain(cc::TouchAction touch_action) override; void DidOverscroll(blink::mojom::DidOverscrollParamsPtr params) override; void DidStartScrollingViewport() override; void ImeCancelComposition() override; void ImeCompositionRangeChanged( const gfx::Range& range, const std::vector<gfx::Rect>& bounds) override; void SetMouseCapture(bool capture) override; void RequestMouseLock(bool from_user_gesture, bool privileged, bool unadjusted_movement, RequestMouseLockCallback callback) override; mojo::AssociatedReceiver<blink::mojom::WidgetHost>& widget_host_receiver_for_testing() { return widget_host_receiver_; } blink::mojom::WidgetInputHandler* GetWidgetInputHandler(); blink::mojom::FrameWidgetInputHandler* GetFrameWidgetInputHandler(); gfx::Range LastCompositionRange() const { return last_composition_range_; } const std::vector<gfx::Rect>& LastCompositionBounds() const { return last_composition_bounds_; } private: gfx::Range last_composition_range_; std::vector<gfx::Rect> last_composition_bounds_; mojo::AssociatedReceiver<blink::mojom::FrameWidgetHost> frame_widget_host_receiver_{this}; mojo::AssociatedRemote<blink::mojom::FrameWidget> frame_widget_remote_; mojo::AssociatedReceiver<blink::mojom::WidgetHost> widget_host_receiver_{ this}; mojo::AssociatedRemote<blink::mojom::Widget> widget_remote_; mojo::Remote<blink::mojom::WidgetInputHandler> widget_input_handler_; mojo::Receiver<blink::mojom::WidgetInputHandlerHost> widget_input_handler_host_{this}; mojo::AssociatedRemote<blink::mojom::FrameWidgetInputHandler> frame_widget_input_handler_; DISALLOW_COPY_AND_ASSIGN(FakeRenderWidgetHost); }; } // namespace content #endif // CONTENT_PUBLIC_TEST_FAKE_RENDER_WIDGET_HOST_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
54f1c257f96563f18444f08ab0f676d07730167d
df3f0c768464eded073c1d32fb835a86112beafa
/llvm/tools/clang/include/clang/Serialization/ASTReader.h
be37186b3eedb036b1083088c44cb168c43553c6
[ "BSD-2-Clause", "NCSA" ]
permissive
mitchty/ellcc-mirror
6d9e6fd45b8087f641ba556e659f9dad3fcd8066
b03a4afac74d50cf0987554b8c0cd8209bcb92a2
refs/heads/master
2021-01-10T06:47:27.028119
2015-10-19T11:36:17
2015-10-19T11:36:17
44,582,115
1
2
NOASSERTION
2020-03-07T21:40:07
2015-10-20T04:27:47
C
UTF-8
C++
false
false
83,801
h
//===--- ASTReader.h - AST File Reader --------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the ASTReader class, which reads AST files. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_SERIALIZATION_ASTREADER_H #define LLVM_CLANG_SERIALIZATION_ASTREADER_H #include "clang/AST/DeclObjC.h" #include "clang/AST/DeclarationName.h" #include "clang/AST/TemplateBase.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/FileSystemOptions.h" #include "clang/Basic/IdentifierTable.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/Version.h" #include "clang/Lex/ExternalPreprocessorSource.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/PreprocessingRecord.h" #include "clang/Sema/ExternalSemaSource.h" #include "clang/Serialization/ASTBitCodes.h" #include "clang/Serialization/ContinuousRangeMap.h" #include "clang/Serialization/Module.h" #include "clang/Serialization/ModuleManager.h" #include "llvm/ADT/APFloat.h" #include "llvm/ADT/APInt.h" #include "llvm/ADT/APSInt.h" #include "llvm/ADT/MapVector.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/TinyPtrVector.h" #include "llvm/Bitcode/BitstreamReader.h" #include "llvm/Support/DataTypes.h" #include "llvm/Support/Timer.h" #include <deque> #include <map> #include <memory> #include <string> #include <utility> #include <vector> namespace llvm { class MemoryBuffer; } namespace clang { class AddrLabelExpr; class ASTConsumer; class ASTContext; class ASTIdentifierIterator; class ASTUnit; // FIXME: Layering violation and egregious hack. class Attr; class Decl; class DeclContext; class DefMacroDirective; class DiagnosticOptions; class NestedNameSpecifier; class CXXBaseSpecifier; class CXXConstructorDecl; class CXXCtorInitializer; class GlobalModuleIndex; class GotoStmt; class MacroDefinition; class MacroDirective; class ModuleMacro; class NamedDecl; class OpaqueValueExpr; class Preprocessor; class PreprocessorOptions; class Sema; class SwitchCase; class ASTDeserializationListener; class ASTWriter; class ASTReader; class ASTDeclReader; class ASTStmtReader; class TypeLocReader; struct HeaderFileInfo; class VersionTuple; class TargetOptions; class LazyASTUnresolvedSet; /// \brief Abstract interface for callback invocations by the ASTReader. /// /// While reading an AST file, the ASTReader will call the methods of the /// listener to pass on specific information. Some of the listener methods can /// return true to indicate to the ASTReader that the information (and /// consequently the AST file) is invalid. class ASTReaderListener { public: virtual ~ASTReaderListener(); /// \brief Receives the full Clang version information. /// /// \returns true to indicate that the version is invalid. Subclasses should /// generally defer to this implementation. virtual bool ReadFullVersionInformation(StringRef FullVersion) { return FullVersion != getClangFullRepositoryVersion(); } virtual void ReadModuleName(StringRef ModuleName) {} virtual void ReadModuleMapFile(StringRef ModuleMapPath) {} /// \brief Receives the language options. /// /// \returns true to indicate the options are invalid or false otherwise. virtual bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, bool AllowCompatibleDifferences) { return false; } /// \brief Receives the target options. /// /// \returns true to indicate the target options are invalid, or false /// otherwise. virtual bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, bool AllowCompatibleDifferences) { return false; } /// \brief Receives the diagnostic options. /// /// \returns true to indicate the diagnostic options are invalid, or false /// otherwise. virtual bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) { return false; } /// \brief Receives the file system options. /// /// \returns true to indicate the file system options are invalid, or false /// otherwise. virtual bool ReadFileSystemOptions(const FileSystemOptions &FSOpts, bool Complain) { return false; } /// \brief Receives the header search options. /// /// \returns true to indicate the header search options are invalid, or false /// otherwise. virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, bool Complain) { return false; } /// \brief Receives the preprocessor options. /// /// \param SuggestedPredefines Can be filled in with the set of predefines /// that are suggested by the preprocessor options. Typically only used when /// loading a precompiled header. /// /// \returns true to indicate the preprocessor options are invalid, or false /// otherwise. virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain, std::string &SuggestedPredefines) { return false; } /// \brief Receives __COUNTER__ value. virtual void ReadCounter(const serialization::ModuleFile &M, unsigned Value) {} /// This is called for each AST file loaded. virtual void visitModuleFile(StringRef Filename, serialization::ModuleKind Kind) {} /// \brief Returns true if this \c ASTReaderListener wants to receive the /// input files of the AST file via \c visitInputFile, false otherwise. virtual bool needsInputFileVisitation() { return false; } /// \brief Returns true if this \c ASTReaderListener wants to receive the /// system input files of the AST file via \c visitInputFile, false otherwise. virtual bool needsSystemInputFileVisitation() { return false; } /// \brief if \c needsInputFileVisitation returns true, this is called for /// each non-system input file of the AST File. If /// \c needsSystemInputFileVisitation is true, then it is called for all /// system input files as well. /// /// \returns true to continue receiving the next input file, false to stop. virtual bool visitInputFile(StringRef Filename, bool isSystem, bool isOverridden, bool isExplicitModule) { return true; } /// \brief Returns true if this \c ASTReaderListener wants to receive the /// imports of the AST file via \c visitImport, false otherwise. virtual bool needsImportVisitation() const { return false; } /// \brief If needsImportVisitation returns \c true, this is called for each /// AST file imported by this AST file. virtual void visitImport(StringRef Filename) {} }; /// \brief Simple wrapper class for chaining listeners. class ChainedASTReaderListener : public ASTReaderListener { std::unique_ptr<ASTReaderListener> First; std::unique_ptr<ASTReaderListener> Second; public: /// Takes ownership of \p First and \p Second. ChainedASTReaderListener(std::unique_ptr<ASTReaderListener> First, std::unique_ptr<ASTReaderListener> Second) : First(std::move(First)), Second(std::move(Second)) {} std::unique_ptr<ASTReaderListener> takeFirst() { return std::move(First); } std::unique_ptr<ASTReaderListener> takeSecond() { return std::move(Second); } bool ReadFullVersionInformation(StringRef FullVersion) override; void ReadModuleName(StringRef ModuleName) override; void ReadModuleMapFile(StringRef ModuleMapPath) override; bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, bool AllowCompatibleDifferences) override; bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, bool AllowCompatibleDifferences) override; bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) override; bool ReadFileSystemOptions(const FileSystemOptions &FSOpts, bool Complain) override; bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, bool Complain) override; bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain, std::string &SuggestedPredefines) override; void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override; bool needsInputFileVisitation() override; bool needsSystemInputFileVisitation() override; void visitModuleFile(StringRef Filename, serialization::ModuleKind Kind) override; bool visitInputFile(StringRef Filename, bool isSystem, bool isOverridden, bool isExplicitModule) override; }; /// \brief ASTReaderListener implementation to validate the information of /// the PCH file against an initialized Preprocessor. class PCHValidator : public ASTReaderListener { Preprocessor &PP; ASTReader &Reader; public: PCHValidator(Preprocessor &PP, ASTReader &Reader) : PP(PP), Reader(Reader) {} bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, bool AllowCompatibleDifferences) override; bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, bool AllowCompatibleDifferences) override; bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) override; bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain, std::string &SuggestedPredefines) override; bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, bool Complain) override; void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override; private: void Error(const char *Msg); }; namespace serialization { class ReadMethodPoolVisitor; namespace reader { class ASTIdentifierLookupTrait; /// \brief The on-disk hash table(s) used for DeclContext name lookup. struct DeclContextLookupTable; } } // end namespace serialization /// \brief Reads an AST files chain containing the contents of a translation /// unit. /// /// The ASTReader class reads bitstreams (produced by the ASTWriter /// class) containing the serialized representation of a given /// abstract syntax tree and its supporting data structures. An /// instance of the ASTReader can be attached to an ASTContext object, /// which will provide access to the contents of the AST files. /// /// The AST reader provides lazy de-serialization of declarations, as /// required when traversing the AST. Only those AST nodes that are /// actually required will be de-serialized. class ASTReader : public ExternalPreprocessorSource, public ExternalPreprocessingRecordSource, public ExternalHeaderFileInfoSource, public ExternalSemaSource, public IdentifierInfoLookup, public ExternalSLocEntrySource { public: typedef SmallVector<uint64_t, 64> RecordData; typedef SmallVectorImpl<uint64_t> RecordDataImpl; /// \brief The result of reading the control block of an AST file, which /// can fail for various reasons. enum ASTReadResult { /// \brief The control block was read successfully. Aside from failures, /// the AST file is safe to read into the current context. Success, /// \brief The AST file itself appears corrupted. Failure, /// \brief The AST file was missing. Missing, /// \brief The AST file is out-of-date relative to its input files, /// and needs to be regenerated. OutOfDate, /// \brief The AST file was written by a different version of Clang. VersionMismatch, /// \brief The AST file was writtten with a different language/target /// configuration. ConfigurationMismatch, /// \brief The AST file has errors. HadErrors }; /// \brief Types of AST files. friend class PCHValidator; friend class ASTDeclReader; friend class ASTStmtReader; friend class ASTIdentifierIterator; friend class serialization::reader::ASTIdentifierLookupTrait; friend class TypeLocReader; friend class ASTWriter; friend class ASTUnit; // ASTUnit needs to remap source locations. friend class serialization::ReadMethodPoolVisitor; typedef serialization::ModuleFile ModuleFile; typedef serialization::ModuleKind ModuleKind; typedef serialization::ModuleManager ModuleManager; typedef ModuleManager::ModuleIterator ModuleIterator; typedef ModuleManager::ModuleConstIterator ModuleConstIterator; typedef ModuleManager::ModuleReverseIterator ModuleReverseIterator; private: /// \brief The receiver of some callbacks invoked by ASTReader. std::unique_ptr<ASTReaderListener> Listener; /// \brief The receiver of deserialization events. ASTDeserializationListener *DeserializationListener; bool OwnsDeserializationListener; SourceManager &SourceMgr; FileManager &FileMgr; const PCHContainerReader &PCHContainerRdr; DiagnosticsEngine &Diags; /// \brief The semantic analysis object that will be processing the /// AST files and the translation unit that uses it. Sema *SemaObj; /// \brief The preprocessor that will be loading the source file. Preprocessor &PP; /// \brief The AST context into which we'll read the AST files. ASTContext &Context; /// \brief The AST consumer. ASTConsumer *Consumer; /// \brief The module manager which manages modules and their dependencies ModuleManager ModuleMgr; /// \brief A timer used to track the time spent deserializing. std::unique_ptr<llvm::Timer> ReadTimer; /// \brief The location where the module file will be considered as /// imported from. For non-module AST types it should be invalid. SourceLocation CurrentImportLoc; /// \brief The global module index, if loaded. std::unique_ptr<GlobalModuleIndex> GlobalIndex; /// \brief A map of global bit offsets to the module that stores entities /// at those bit offsets. ContinuousRangeMap<uint64_t, ModuleFile*, 4> GlobalBitOffsetsMap; /// \brief A map of negated SLocEntryIDs to the modules containing them. ContinuousRangeMap<unsigned, ModuleFile*, 64> GlobalSLocEntryMap; typedef ContinuousRangeMap<unsigned, ModuleFile*, 64> GlobalSLocOffsetMapType; /// \brief A map of reversed (SourceManager::MaxLoadedOffset - SLocOffset) /// SourceLocation offsets to the modules containing them. GlobalSLocOffsetMapType GlobalSLocOffsetMap; /// \brief Types that have already been loaded from the chain. /// /// When the pointer at index I is non-NULL, the type with /// ID = (I + 1) << FastQual::Width has already been loaded std::vector<QualType> TypesLoaded; typedef ContinuousRangeMap<serialization::TypeID, ModuleFile *, 4> GlobalTypeMapType; /// \brief Mapping from global type IDs to the module in which the /// type resides along with the offset that should be added to the /// global type ID to produce a local ID. GlobalTypeMapType GlobalTypeMap; /// \brief Declarations that have already been loaded from the chain. /// /// When the pointer at index I is non-NULL, the declaration with ID /// = I + 1 has already been loaded. std::vector<Decl *> DeclsLoaded; typedef ContinuousRangeMap<serialization::DeclID, ModuleFile *, 4> GlobalDeclMapType; /// \brief Mapping from global declaration IDs to the module in which the /// declaration resides. GlobalDeclMapType GlobalDeclMap; typedef std::pair<ModuleFile *, uint64_t> FileOffset; typedef SmallVector<FileOffset, 2> FileOffsetsTy; typedef llvm::DenseMap<serialization::DeclID, FileOffsetsTy> DeclUpdateOffsetsMap; /// \brief Declarations that have modifications residing in a later file /// in the chain. DeclUpdateOffsetsMap DeclUpdateOffsets; /// \brief Declaration updates for already-loaded declarations that we need /// to apply once we finish processing an import. llvm::SmallVector<std::pair<serialization::GlobalDeclID, Decl*>, 16> PendingUpdateRecords; enum class PendingFakeDefinitionKind { NotFake, Fake, FakeLoaded }; /// \brief The DefinitionData pointers that we faked up for class definitions /// that we needed but hadn't loaded yet. llvm::DenseMap<void *, PendingFakeDefinitionKind> PendingFakeDefinitionData; /// \brief Exception specification updates that have been loaded but not yet /// propagated across the relevant redeclaration chain. The map key is the /// canonical declaration (used only for deduplication) and the value is a /// declaration that has an exception specification. llvm::SmallMapVector<Decl *, FunctionDecl *, 4> PendingExceptionSpecUpdates; struct ReplacedDeclInfo { ModuleFile *Mod; uint64_t Offset; unsigned RawLoc; ReplacedDeclInfo() : Mod(nullptr), Offset(0), RawLoc(0) {} ReplacedDeclInfo(ModuleFile *Mod, uint64_t Offset, unsigned RawLoc) : Mod(Mod), Offset(Offset), RawLoc(RawLoc) {} }; typedef llvm::DenseMap<serialization::DeclID, ReplacedDeclInfo> DeclReplacementMap; /// \brief Declarations that have been replaced in a later file in the chain. DeclReplacementMap ReplacedDecls; /// \brief Declarations that have been imported and have typedef names for /// linkage purposes. llvm::DenseMap<std::pair<DeclContext*, IdentifierInfo*>, NamedDecl*> ImportedTypedefNamesForLinkage; /// \brief Mergeable declaration contexts that have anonymous declarations /// within them, and those anonymous declarations. llvm::DenseMap<DeclContext*, llvm::SmallVector<NamedDecl*, 2>> AnonymousDeclarationsForMerging; struct FileDeclsInfo { ModuleFile *Mod; ArrayRef<serialization::LocalDeclID> Decls; FileDeclsInfo() : Mod(nullptr) {} FileDeclsInfo(ModuleFile *Mod, ArrayRef<serialization::LocalDeclID> Decls) : Mod(Mod), Decls(Decls) {} }; /// \brief Map from a FileID to the file-level declarations that it contains. llvm::DenseMap<FileID, FileDeclsInfo> FileDeclIDs; /// \brief An array of lexical contents of a declaration context, as a sequence of /// Decl::Kind, DeclID pairs. typedef ArrayRef<llvm::support::unaligned_uint32_t> LexicalContents; /// \brief Map from a DeclContext to its lexical contents. llvm::DenseMap<const DeclContext*, std::pair<ModuleFile*, LexicalContents>> LexicalDecls; /// \brief Map from the TU to its lexical contents from each module file. std::vector<std::pair<ModuleFile*, LexicalContents>> TULexicalDecls; /// \brief Map from a DeclContext to its lookup tables. llvm::DenseMap<const DeclContext *, serialization::reader::DeclContextLookupTable> Lookups; // Updates for visible decls can occur for other contexts than just the // TU, and when we read those update records, the actual context may not // be available yet, so have this pending map using the ID as a key. It // will be realized when the context is actually loaded. struct PendingVisibleUpdate { ModuleFile *Mod; const unsigned char *Data; }; typedef SmallVector<PendingVisibleUpdate, 1> DeclContextVisibleUpdates; /// \brief Updates to the visible declarations of declaration contexts that /// haven't been loaded yet. llvm::DenseMap<serialization::DeclID, DeclContextVisibleUpdates> PendingVisibleUpdates; /// \brief The set of C++ or Objective-C classes that have forward /// declarations that have not yet been linked to their definitions. llvm::SmallPtrSet<Decl *, 4> PendingDefinitions; typedef llvm::MapVector<Decl *, uint64_t, llvm::SmallDenseMap<Decl *, unsigned, 4>, SmallVector<std::pair<Decl *, uint64_t>, 4> > PendingBodiesMap; /// \brief Functions or methods that have bodies that will be attached. PendingBodiesMap PendingBodies; /// \brief Definitions for which we have added merged definitions but not yet /// performed deduplication. llvm::SetVector<NamedDecl*> PendingMergedDefinitionsToDeduplicate; /// \brief Read the record that describes the lexical contents of a DC. bool ReadLexicalDeclContextStorage(ModuleFile &M, llvm::BitstreamCursor &Cursor, uint64_t Offset, DeclContext *DC); /// \brief Read the record that describes the visible contents of a DC. bool ReadVisibleDeclContextStorage(ModuleFile &M, llvm::BitstreamCursor &Cursor, uint64_t Offset, serialization::DeclID ID); /// \brief A vector containing identifiers that have already been /// loaded. /// /// If the pointer at index I is non-NULL, then it refers to the /// IdentifierInfo for the identifier with ID=I+1 that has already /// been loaded. std::vector<IdentifierInfo *> IdentifiersLoaded; typedef ContinuousRangeMap<serialization::IdentID, ModuleFile *, 4> GlobalIdentifierMapType; /// \brief Mapping from global identifier IDs to the module in which the /// identifier resides along with the offset that should be added to the /// global identifier ID to produce a local ID. GlobalIdentifierMapType GlobalIdentifierMap; /// \brief A vector containing macros that have already been /// loaded. /// /// If the pointer at index I is non-NULL, then it refers to the /// MacroInfo for the identifier with ID=I+1 that has already /// been loaded. std::vector<MacroInfo *> MacrosLoaded; typedef std::pair<IdentifierInfo *, serialization::SubmoduleID> LoadedMacroInfo; /// \brief A set of #undef directives that we have loaded; used to /// deduplicate the same #undef information coming from multiple module /// files. llvm::DenseSet<LoadedMacroInfo> LoadedUndefs; typedef ContinuousRangeMap<serialization::MacroID, ModuleFile *, 4> GlobalMacroMapType; /// \brief Mapping from global macro IDs to the module in which the /// macro resides along with the offset that should be added to the /// global macro ID to produce a local ID. GlobalMacroMapType GlobalMacroMap; /// \brief A vector containing submodules that have already been loaded. /// /// This vector is indexed by the Submodule ID (-1). NULL submodule entries /// indicate that the particular submodule ID has not yet been loaded. SmallVector<Module *, 2> SubmodulesLoaded; typedef ContinuousRangeMap<serialization::SubmoduleID, ModuleFile *, 4> GlobalSubmoduleMapType; /// \brief Mapping from global submodule IDs to the module file in which the /// submodule resides along with the offset that should be added to the /// global submodule ID to produce a local ID. GlobalSubmoduleMapType GlobalSubmoduleMap; /// \brief A set of hidden declarations. typedef SmallVector<Decl*, 2> HiddenNames; typedef llvm::DenseMap<Module *, HiddenNames> HiddenNamesMapType; /// \brief A mapping from each of the hidden submodules to the deserialized /// declarations in that submodule that could be made visible. HiddenNamesMapType HiddenNamesMap; /// \brief A module import, export, or conflict that hasn't yet been resolved. struct UnresolvedModuleRef { /// \brief The file in which this module resides. ModuleFile *File; /// \brief The module that is importing or exporting. Module *Mod; /// \brief The kind of module reference. enum { Import, Export, Conflict } Kind; /// \brief The local ID of the module that is being exported. unsigned ID; /// \brief Whether this is a wildcard export. unsigned IsWildcard : 1; /// \brief String data. StringRef String; }; /// \brief The set of module imports and exports that still need to be /// resolved. SmallVector<UnresolvedModuleRef, 2> UnresolvedModuleRefs; /// \brief A vector containing selectors that have already been loaded. /// /// This vector is indexed by the Selector ID (-1). NULL selector /// entries indicate that the particular selector ID has not yet /// been loaded. SmallVector<Selector, 16> SelectorsLoaded; typedef ContinuousRangeMap<serialization::SelectorID, ModuleFile *, 4> GlobalSelectorMapType; /// \brief Mapping from global selector IDs to the module in which the /// global selector ID to produce a local ID. GlobalSelectorMapType GlobalSelectorMap; /// \brief The generation number of the last time we loaded data from the /// global method pool for this selector. llvm::DenseMap<Selector, unsigned> SelectorGeneration; struct PendingMacroInfo { ModuleFile *M; uint64_t MacroDirectivesOffset; PendingMacroInfo(ModuleFile *M, uint64_t MacroDirectivesOffset) : M(M), MacroDirectivesOffset(MacroDirectivesOffset) {} }; typedef llvm::MapVector<IdentifierInfo *, SmallVector<PendingMacroInfo, 2> > PendingMacroIDsMap; /// \brief Mapping from identifiers that have a macro history to the global /// IDs have not yet been deserialized to the global IDs of those macros. PendingMacroIDsMap PendingMacroIDs; typedef ContinuousRangeMap<unsigned, ModuleFile *, 4> GlobalPreprocessedEntityMapType; /// \brief Mapping from global preprocessing entity IDs to the module in /// which the preprocessed entity resides along with the offset that should be /// added to the global preprocessing entitiy ID to produce a local ID. GlobalPreprocessedEntityMapType GlobalPreprocessedEntityMap; /// \name CodeGen-relevant special data /// \brief Fields containing data that is relevant to CodeGen. //@{ /// \brief The IDs of all declarations that fulfill the criteria of /// "interesting" decls. /// /// This contains the data loaded from all EAGERLY_DESERIALIZED_DECLS blocks /// in the chain. The referenced declarations are deserialized and passed to /// the consumer eagerly. SmallVector<uint64_t, 16> EagerlyDeserializedDecls; /// \brief The IDs of all tentative definitions stored in the chain. /// /// Sema keeps track of all tentative definitions in a TU because it has to /// complete them and pass them on to CodeGen. Thus, tentative definitions in /// the PCH chain must be eagerly deserialized. SmallVector<uint64_t, 16> TentativeDefinitions; /// \brief The IDs of all CXXRecordDecls stored in the chain whose VTables are /// used. /// /// CodeGen has to emit VTables for these records, so they have to be eagerly /// deserialized. SmallVector<uint64_t, 64> VTableUses; /// \brief A snapshot of the pending instantiations in the chain. /// /// This record tracks the instantiations that Sema has to perform at the /// end of the TU. It consists of a pair of values for every pending /// instantiation where the first value is the ID of the decl and the second /// is the instantiation location. SmallVector<uint64_t, 64> PendingInstantiations; //@} /// \name DiagnosticsEngine-relevant special data /// \brief Fields containing data that is used for generating diagnostics //@{ /// \brief A snapshot of Sema's unused file-scoped variable tracking, for /// generating warnings. SmallVector<uint64_t, 16> UnusedFileScopedDecls; /// \brief A list of all the delegating constructors we've seen, to diagnose /// cycles. SmallVector<uint64_t, 4> DelegatingCtorDecls; /// \brief Method selectors used in a @selector expression. Used for /// implementation of -Wselector. SmallVector<uint64_t, 64> ReferencedSelectorsData; /// \brief A snapshot of Sema's weak undeclared identifier tracking, for /// generating warnings. SmallVector<uint64_t, 64> WeakUndeclaredIdentifiers; /// \brief The IDs of type aliases for ext_vectors that exist in the chain. /// /// Used by Sema for finding sugared names for ext_vectors in diagnostics. SmallVector<uint64_t, 4> ExtVectorDecls; //@} /// \name Sema-relevant special data /// \brief Fields containing data that is used for semantic analysis //@{ /// \brief The IDs of all potentially unused typedef names in the chain. /// /// Sema tracks these to emit warnings. SmallVector<uint64_t, 16> UnusedLocalTypedefNameCandidates; /// \brief The IDs of the declarations Sema stores directly. /// /// Sema tracks a few important decls, such as namespace std, directly. SmallVector<uint64_t, 4> SemaDeclRefs; /// \brief The IDs of the types ASTContext stores directly. /// /// The AST context tracks a few important types, such as va_list, directly. SmallVector<uint64_t, 16> SpecialTypes; /// \brief The IDs of CUDA-specific declarations ASTContext stores directly. /// /// The AST context tracks a few important decls, currently cudaConfigureCall, /// directly. SmallVector<uint64_t, 2> CUDASpecialDeclRefs; /// \brief The floating point pragma option settings. SmallVector<uint64_t, 1> FPPragmaOptions; /// \brief The pragma clang optimize location (if the pragma state is "off"). SourceLocation OptimizeOffPragmaLocation; /// \brief The OpenCL extension settings. SmallVector<uint64_t, 1> OpenCLExtensions; /// \brief A list of the namespaces we've seen. SmallVector<uint64_t, 4> KnownNamespaces; /// \brief A list of undefined decls with internal linkage followed by the /// SourceLocation of a matching ODR-use. SmallVector<uint64_t, 8> UndefinedButUsed; /// \brief Delete expressions to analyze at the end of translation unit. SmallVector<uint64_t, 8> DelayedDeleteExprs; // \brief A list of late parsed template function data. SmallVector<uint64_t, 1> LateParsedTemplates; struct ImportedSubmodule { serialization::SubmoduleID ID; SourceLocation ImportLoc; ImportedSubmodule(serialization::SubmoduleID ID, SourceLocation ImportLoc) : ID(ID), ImportLoc(ImportLoc) {} }; /// \brief A list of modules that were imported by precompiled headers or /// any other non-module AST file. SmallVector<ImportedSubmodule, 2> ImportedModules; //@} /// \brief The directory that the PCH we are reading is stored in. std::string CurrentDir; /// \brief The system include root to be used when loading the /// precompiled header. std::string isysroot; /// \brief Whether to disable the normal validation performed on precompiled /// headers when they are loaded. bool DisableValidation; /// \brief Whether to accept an AST file with compiler errors. bool AllowASTWithCompilerErrors; /// \brief Whether to accept an AST file that has a different configuration /// from the current compiler instance. bool AllowConfigurationMismatch; /// \brief Whether validate system input files. bool ValidateSystemInputs; /// \brief Whether we are allowed to use the global module index. bool UseGlobalIndex; /// \brief Whether we have tried loading the global module index yet. bool TriedLoadingGlobalIndex; typedef llvm::DenseMap<unsigned, SwitchCase *> SwitchCaseMapTy; /// \brief Mapping from switch-case IDs in the chain to switch-case statements /// /// Statements usually don't have IDs, but switch cases need them, so that the /// switch statement can refer to them. SwitchCaseMapTy SwitchCaseStmts; SwitchCaseMapTy *CurrSwitchCaseStmts; /// \brief The number of source location entries de-serialized from /// the PCH file. unsigned NumSLocEntriesRead; /// \brief The number of source location entries in the chain. unsigned TotalNumSLocEntries; /// \brief The number of statements (and expressions) de-serialized /// from the chain. unsigned NumStatementsRead; /// \brief The total number of statements (and expressions) stored /// in the chain. unsigned TotalNumStatements; /// \brief The number of macros de-serialized from the chain. unsigned NumMacrosRead; /// \brief The total number of macros stored in the chain. unsigned TotalNumMacros; /// \brief The number of lookups into identifier tables. unsigned NumIdentifierLookups; /// \brief The number of lookups into identifier tables that succeed. unsigned NumIdentifierLookupHits; /// \brief The number of selectors that have been read. unsigned NumSelectorsRead; /// \brief The number of method pool entries that have been read. unsigned NumMethodPoolEntriesRead; /// \brief The number of times we have looked up a selector in the method /// pool. unsigned NumMethodPoolLookups; /// \brief The number of times we have looked up a selector in the method /// pool and found something. unsigned NumMethodPoolHits; /// \brief The number of times we have looked up a selector in the method /// pool within a specific module. unsigned NumMethodPoolTableLookups; /// \brief The number of times we have looked up a selector in the method /// pool within a specific module and found something. unsigned NumMethodPoolTableHits; /// \brief The total number of method pool entries in the selector table. unsigned TotalNumMethodPoolEntries; /// Number of lexical decl contexts read/total. unsigned NumLexicalDeclContextsRead, TotalLexicalDeclContexts; /// Number of visible decl contexts read/total. unsigned NumVisibleDeclContextsRead, TotalVisibleDeclContexts; /// Total size of modules, in bits, currently loaded uint64_t TotalModulesSizeInBits; /// \brief Number of Decl/types that are currently deserializing. unsigned NumCurrentElementsDeserializing; /// \brief Set true while we are in the process of passing deserialized /// "interesting" decls to consumer inside FinishedDeserializing(). /// This is used as a guard to avoid recursively repeating the process of /// passing decls to consumer. bool PassingDeclsToConsumer; /// \brief The set of identifiers that were read while the AST reader was /// (recursively) loading declarations. /// /// The declarations on the identifier chain for these identifiers will be /// loaded once the recursive loading has completed. llvm::MapVector<IdentifierInfo *, SmallVector<uint32_t, 4> > PendingIdentifierInfos; /// \brief The set of lookup results that we have faked in order to support /// merging of partially deserialized decls but that we have not yet removed. llvm::SmallMapVector<IdentifierInfo *, SmallVector<NamedDecl*, 2>, 16> PendingFakeLookupResults; /// \brief The generation number of each identifier, which keeps track of /// the last time we loaded information about this identifier. llvm::DenseMap<IdentifierInfo *, unsigned> IdentifierGeneration; /// \brief Contains declarations and definitions that will be /// "interesting" to the ASTConsumer, when we get that AST consumer. /// /// "Interesting" declarations are those that have data that may /// need to be emitted, such as inline function definitions or /// Objective-C protocols. std::deque<Decl *> InterestingDecls; /// \brief The list of redeclaration chains that still need to be /// reconstructed, and the local offset to the corresponding list /// of redeclarations. SmallVector<std::pair<Decl *, uint64_t>, 16> PendingDeclChains; /// \brief The list of canonical declarations whose redeclaration chains /// need to be marked as incomplete once we're done deserializing things. SmallVector<Decl *, 16> PendingIncompleteDeclChains; /// \brief The Decl IDs for the Sema/Lexical DeclContext of a Decl that has /// been loaded but its DeclContext was not set yet. struct PendingDeclContextInfo { Decl *D; serialization::GlobalDeclID SemaDC; serialization::GlobalDeclID LexicalDC; }; /// \brief The set of Decls that have been loaded but their DeclContexts are /// not set yet. /// /// The DeclContexts for these Decls will be set once recursive loading has /// been completed. std::deque<PendingDeclContextInfo> PendingDeclContextInfos; /// \brief The set of NamedDecls that have been loaded, but are members of a /// context that has been merged into another context where the corresponding /// declaration is either missing or has not yet been loaded. /// /// We will check whether the corresponding declaration is in fact missing /// once recursing loading has been completed. llvm::SmallVector<NamedDecl *, 16> PendingOdrMergeChecks; /// \brief Record definitions in which we found an ODR violation. llvm::SmallDenseMap<CXXRecordDecl *, llvm::TinyPtrVector<CXXRecordDecl *>, 2> PendingOdrMergeFailures; /// \brief DeclContexts in which we have diagnosed an ODR violation. llvm::SmallPtrSet<DeclContext*, 2> DiagnosedOdrMergeFailures; /// \brief The set of Objective-C categories that have been deserialized /// since the last time the declaration chains were linked. llvm::SmallPtrSet<ObjCCategoryDecl *, 16> CategoriesDeserialized; /// \brief The set of Objective-C class definitions that have already been /// loaded, for which we will need to check for categories whenever a new /// module is loaded. SmallVector<ObjCInterfaceDecl *, 16> ObjCClassesLoaded; typedef llvm::DenseMap<Decl *, SmallVector<serialization::DeclID, 2> > KeyDeclsMap; /// \brief A mapping from canonical declarations to the set of global /// declaration IDs for key declaration that have been merged with that /// canonical declaration. A key declaration is a formerly-canonical /// declaration whose module did not import any other key declaration for that /// entity. These are the IDs that we use as keys when finding redecl chains. KeyDeclsMap KeyDecls; /// \brief A mapping from DeclContexts to the semantic DeclContext that we /// are treating as the definition of the entity. This is used, for instance, /// when merging implicit instantiations of class templates across modules. llvm::DenseMap<DeclContext *, DeclContext *> MergedDeclContexts; /// \brief A mapping from canonical declarations of enums to their canonical /// definitions. Only populated when using modules in C++. llvm::DenseMap<EnumDecl *, EnumDecl *> EnumDefinitions; /// \brief When reading a Stmt tree, Stmt operands are placed in this stack. SmallVector<Stmt *, 16> StmtStack; /// \brief What kind of records we are reading. enum ReadingKind { Read_None, Read_Decl, Read_Type, Read_Stmt }; /// \brief What kind of records we are reading. ReadingKind ReadingKind; /// \brief RAII object to change the reading kind. class ReadingKindTracker { ASTReader &Reader; enum ReadingKind PrevKind; ReadingKindTracker(const ReadingKindTracker &) = delete; void operator=(const ReadingKindTracker &) = delete; public: ReadingKindTracker(enum ReadingKind newKind, ASTReader &reader) : Reader(reader), PrevKind(Reader.ReadingKind) { Reader.ReadingKind = newKind; } ~ReadingKindTracker() { Reader.ReadingKind = PrevKind; } }; /// \brief Suggested contents of the predefines buffer, after this /// PCH file has been processed. /// /// In most cases, this string will be empty, because the predefines /// buffer computed to build the PCH file will be identical to the /// predefines buffer computed from the command line. However, when /// there are differences that the PCH reader can work around, this /// predefines buffer may contain additional definitions. std::string SuggestedPredefines; /// \brief Reads a statement from the specified cursor. Stmt *ReadStmtFromStream(ModuleFile &F); struct InputFileInfo { std::string Filename; off_t StoredSize; time_t StoredTime; bool Overridden; }; /// \brief Reads the stored information about an input file. InputFileInfo readInputFileInfo(ModuleFile &F, unsigned ID); /// \brief Retrieve the file entry and 'overridden' bit for an input /// file in the given module file. serialization::InputFile getInputFile(ModuleFile &F, unsigned ID, bool Complain = true); public: void ResolveImportedPath(ModuleFile &M, std::string &Filename); static void ResolveImportedPath(std::string &Filename, StringRef Prefix); /// \brief Returns the first key declaration for the given declaration. This /// is one that is formerly-canonical (or still canonical) and whose module /// did not import any other key declaration of the entity. Decl *getKeyDeclaration(Decl *D) { D = D->getCanonicalDecl(); if (D->isFromASTFile()) return D; auto I = KeyDecls.find(D); if (I == KeyDecls.end() || I->second.empty()) return D; return GetExistingDecl(I->second[0]); } const Decl *getKeyDeclaration(const Decl *D) { return getKeyDeclaration(const_cast<Decl*>(D)); } /// \brief Run a callback on each imported key declaration of \p D. template <typename Fn> void forEachImportedKeyDecl(const Decl *D, Fn Visit) { D = D->getCanonicalDecl(); if (D->isFromASTFile()) Visit(D); auto It = KeyDecls.find(const_cast<Decl*>(D)); if (It != KeyDecls.end()) for (auto ID : It->second) Visit(GetExistingDecl(ID)); } /// \brief Get the loaded lookup tables for \p Primary, if any. const serialization::reader::DeclContextLookupTable * getLoadedLookupTables(DeclContext *Primary) const; private: struct ImportedModule { ModuleFile *Mod; ModuleFile *ImportedBy; SourceLocation ImportLoc; ImportedModule(ModuleFile *Mod, ModuleFile *ImportedBy, SourceLocation ImportLoc) : Mod(Mod), ImportedBy(ImportedBy), ImportLoc(ImportLoc) { } }; ASTReadResult ReadASTCore(StringRef FileName, ModuleKind Type, SourceLocation ImportLoc, ModuleFile *ImportedBy, SmallVectorImpl<ImportedModule> &Loaded, off_t ExpectedSize, time_t ExpectedModTime, serialization::ASTFileSignature ExpectedSignature, unsigned ClientLoadCapabilities); ASTReadResult ReadControlBlock(ModuleFile &F, SmallVectorImpl<ImportedModule> &Loaded, const ModuleFile *ImportedBy, unsigned ClientLoadCapabilities); static ASTReadResult ReadOptionsBlock( llvm::BitstreamCursor &Stream, unsigned ClientLoadCapabilities, bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener, std::string &SuggestedPredefines); ASTReadResult ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities); bool ParseLineTable(ModuleFile &F, const RecordData &Record); bool ReadSourceManagerBlock(ModuleFile &F); llvm::BitstreamCursor &SLocCursorForID(int ID); SourceLocation getImportLocation(ModuleFile *F); ASTReadResult ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F, const ModuleFile *ImportedBy, unsigned ClientLoadCapabilities); ASTReadResult ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities); static bool ParseLanguageOptions(const RecordData &Record, bool Complain, ASTReaderListener &Listener, bool AllowCompatibleDifferences); static bool ParseTargetOptions(const RecordData &Record, bool Complain, ASTReaderListener &Listener, bool AllowCompatibleDifferences); static bool ParseDiagnosticOptions(const RecordData &Record, bool Complain, ASTReaderListener &Listener); static bool ParseFileSystemOptions(const RecordData &Record, bool Complain, ASTReaderListener &Listener); static bool ParseHeaderSearchOptions(const RecordData &Record, bool Complain, ASTReaderListener &Listener); static bool ParsePreprocessorOptions(const RecordData &Record, bool Complain, ASTReaderListener &Listener, std::string &SuggestedPredefines); struct RecordLocation { RecordLocation(ModuleFile *M, uint64_t O) : F(M), Offset(O) {} ModuleFile *F; uint64_t Offset; }; QualType readTypeRecord(unsigned Index); void readExceptionSpec(ModuleFile &ModuleFile, SmallVectorImpl<QualType> &ExceptionStorage, FunctionProtoType::ExceptionSpecInfo &ESI, const RecordData &Record, unsigned &Index); RecordLocation TypeCursorForIndex(unsigned Index); void LoadedDecl(unsigned Index, Decl *D); Decl *ReadDeclRecord(serialization::DeclID ID); void markIncompleteDeclChain(Decl *Canon); /// \brief Returns the most recent declaration of a declaration (which must be /// of a redeclarable kind) that is either local or has already been loaded /// merged into its redecl chain. Decl *getMostRecentExistingDecl(Decl *D); RecordLocation DeclCursorForID(serialization::DeclID ID, unsigned &RawLocation); void loadDeclUpdateRecords(serialization::DeclID ID, Decl *D); void loadPendingDeclChain(Decl *D, uint64_t LocalOffset); void loadObjCCategories(serialization::GlobalDeclID ID, ObjCInterfaceDecl *D, unsigned PreviousGeneration = 0); RecordLocation getLocalBitOffset(uint64_t GlobalOffset); uint64_t getGlobalBitOffset(ModuleFile &M, uint32_t LocalOffset); /// \brief Returns the first preprocessed entity ID that begins or ends after /// \arg Loc. serialization::PreprocessedEntityID findPreprocessedEntity(SourceLocation Loc, bool EndsAfter) const; /// \brief Find the next module that contains entities and return the ID /// of the first entry. /// /// \param SLocMapI points at a chunk of a module that contains no /// preprocessed entities or the entities it contains are not the /// ones we are looking for. serialization::PreprocessedEntityID findNextPreprocessedEntity( GlobalSLocOffsetMapType::const_iterator SLocMapI) const; /// \brief Returns (ModuleFile, Local index) pair for \p GlobalIndex of a /// preprocessed entity. std::pair<ModuleFile *, unsigned> getModulePreprocessedEntity(unsigned GlobalIndex); /// \brief Returns (begin, end) pair for the preprocessed entities of a /// particular module. llvm::iterator_range<PreprocessingRecord::iterator> getModulePreprocessedEntities(ModuleFile &Mod) const; class ModuleDeclIterator : public llvm::iterator_adaptor_base< ModuleDeclIterator, const serialization::LocalDeclID *, std::random_access_iterator_tag, const Decl *, ptrdiff_t, const Decl *, const Decl *> { ASTReader *Reader; ModuleFile *Mod; public: ModuleDeclIterator() : iterator_adaptor_base(nullptr), Reader(nullptr), Mod(nullptr) {} ModuleDeclIterator(ASTReader *Reader, ModuleFile *Mod, const serialization::LocalDeclID *Pos) : iterator_adaptor_base(Pos), Reader(Reader), Mod(Mod) {} value_type operator*() const { return Reader->GetDecl(Reader->getGlobalDeclID(*Mod, *I)); } value_type operator->() const { return **this; } bool operator==(const ModuleDeclIterator &RHS) const { assert(Reader == RHS.Reader && Mod == RHS.Mod); return I == RHS.I; } }; llvm::iterator_range<ModuleDeclIterator> getModuleFileLevelDecls(ModuleFile &Mod); void PassInterestingDeclsToConsumer(); void PassInterestingDeclToConsumer(Decl *D); void finishPendingActions(); void diagnoseOdrViolations(); void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name); void addPendingDeclContextInfo(Decl *D, serialization::GlobalDeclID SemaDC, serialization::GlobalDeclID LexicalDC) { assert(D); PendingDeclContextInfo Info = { D, SemaDC, LexicalDC }; PendingDeclContextInfos.push_back(Info); } /// \brief Produce an error diagnostic and return true. /// /// This routine should only be used for fatal errors that have to /// do with non-routine failures (e.g., corrupted AST file). void Error(StringRef Msg); void Error(unsigned DiagID, StringRef Arg1 = StringRef(), StringRef Arg2 = StringRef()); ASTReader(const ASTReader &) = delete; void operator=(const ASTReader &) = delete; public: /// \brief Load the AST file and validate its contents against the given /// Preprocessor. /// /// \param PP the preprocessor associated with the context in which this /// precompiled header will be loaded. /// /// \param Context the AST context that this precompiled header will be /// loaded into. /// /// \param PCHContainerRdr the PCHContainerOperations to use for loading and /// creating modules. /// /// \param isysroot If non-NULL, the system include path specified by the /// user. This is only used with relocatable PCH files. If non-NULL, /// a relocatable PCH file will use the default path "/". /// /// \param DisableValidation If true, the AST reader will suppress most /// of its regular consistency checking, allowing the use of precompiled /// headers that cannot be determined to be compatible. /// /// \param AllowASTWithCompilerErrors If true, the AST reader will accept an /// AST file the was created out of an AST with compiler errors, /// otherwise it will reject it. /// /// \param AllowConfigurationMismatch If true, the AST reader will not check /// for configuration differences between the AST file and the invocation. /// /// \param ValidateSystemInputs If true, the AST reader will validate /// system input files in addition to user input files. This is only /// meaningful if \p DisableValidation is false. /// /// \param UseGlobalIndex If true, the AST reader will try to load and use /// the global module index. /// /// \param ReadTimer If non-null, a timer used to track the time spent /// deserializing. ASTReader(Preprocessor &PP, ASTContext &Context, const PCHContainerReader &PCHContainerRdr, StringRef isysroot = "", bool DisableValidation = false, bool AllowASTWithCompilerErrors = false, bool AllowConfigurationMismatch = false, bool ValidateSystemInputs = false, bool UseGlobalIndex = true, std::unique_ptr<llvm::Timer> ReadTimer = {}); ~ASTReader() override; SourceManager &getSourceManager() const { return SourceMgr; } FileManager &getFileManager() const { return FileMgr; } /// \brief Flags that indicate what kind of AST loading failures the client /// of the AST reader can directly handle. /// /// When a client states that it can handle a particular kind of failure, /// the AST reader will not emit errors when producing that kind of failure. enum LoadFailureCapabilities { /// \brief The client can't handle any AST loading failures. ARR_None = 0, /// \brief The client can handle an AST file that cannot load because it /// is missing. ARR_Missing = 0x1, /// \brief The client can handle an AST file that cannot load because it /// is out-of-date relative to its input files. ARR_OutOfDate = 0x2, /// \brief The client can handle an AST file that cannot load because it /// was built with a different version of Clang. ARR_VersionMismatch = 0x4, /// \brief The client can handle an AST file that cannot load because it's /// compiled configuration doesn't match that of the context it was /// loaded into. ARR_ConfigurationMismatch = 0x8 }; /// \brief Load the AST file designated by the given file name. /// /// \param FileName The name of the AST file to load. /// /// \param Type The kind of AST being loaded, e.g., PCH, module, main file, /// or preamble. /// /// \param ImportLoc the location where the module file will be considered as /// imported from. For non-module AST types it should be invalid. /// /// \param ClientLoadCapabilities The set of client load-failure /// capabilities, represented as a bitset of the enumerators of /// LoadFailureCapabilities. ASTReadResult ReadAST(const std::string &FileName, ModuleKind Type, SourceLocation ImportLoc, unsigned ClientLoadCapabilities); /// \brief Make the entities in the given module and any of its (non-explicit) /// submodules visible to name lookup. /// /// \param Mod The module whose names should be made visible. /// /// \param NameVisibility The level of visibility to give the names in the /// module. Visibility can only be increased over time. /// /// \param ImportLoc The location at which the import occurs. void makeModuleVisible(Module *Mod, Module::NameVisibilityKind NameVisibility, SourceLocation ImportLoc); /// \brief Make the names within this set of hidden names visible. void makeNamesVisible(const HiddenNames &Names, Module *Owner); /// \brief Take the AST callbacks listener. std::unique_ptr<ASTReaderListener> takeListener() { return std::move(Listener); } /// \brief Set the AST callbacks listener. void setListener(std::unique_ptr<ASTReaderListener> Listener) { this->Listener = std::move(Listener); } /// \brief Add an AST callback listener. /// /// Takes ownership of \p L. void addListener(std::unique_ptr<ASTReaderListener> L) { if (Listener) L = llvm::make_unique<ChainedASTReaderListener>(std::move(L), std::move(Listener)); Listener = std::move(L); } /// RAII object to temporarily add an AST callback listener. class ListenerScope { ASTReader &Reader; bool Chained; public: ListenerScope(ASTReader &Reader, std::unique_ptr<ASTReaderListener> L) : Reader(Reader), Chained(false) { auto Old = Reader.takeListener(); if (Old) { Chained = true; L = llvm::make_unique<ChainedASTReaderListener>(std::move(L), std::move(Old)); } Reader.setListener(std::move(L)); } ~ListenerScope() { auto New = Reader.takeListener(); if (Chained) Reader.setListener(static_cast<ChainedASTReaderListener *>(New.get()) ->takeSecond()); } }; /// \brief Set the AST deserialization listener. void setDeserializationListener(ASTDeserializationListener *Listener, bool TakeOwnership = false); /// \brief Determine whether this AST reader has a global index. bool hasGlobalIndex() const { return (bool)GlobalIndex; } /// \brief Return global module index. GlobalModuleIndex *getGlobalIndex() { return GlobalIndex.get(); } /// \brief Reset reader for a reload try. void resetForReload() { TriedLoadingGlobalIndex = false; } /// \brief Attempts to load the global index. /// /// \returns true if loading the global index has failed for any reason. bool loadGlobalIndex(); /// \brief Determine whether we tried to load the global index, but failed, /// e.g., because it is out-of-date or does not exist. bool isGlobalIndexUnavailable() const; /// \brief Initializes the ASTContext void InitializeContext(); /// \brief Update the state of Sema after loading some additional modules. void UpdateSema(); /// \brief Add in-memory (virtual file) buffer. void addInMemoryBuffer(StringRef &FileName, std::unique_ptr<llvm::MemoryBuffer> Buffer) { ModuleMgr.addInMemoryBuffer(FileName, std::move(Buffer)); } /// \brief Finalizes the AST reader's state before writing an AST file to /// disk. /// /// This operation may undo temporary state in the AST that should not be /// emitted. void finalizeForWriting(); /// \brief Retrieve the module manager. ModuleManager &getModuleManager() { return ModuleMgr; } /// \brief Retrieve the preprocessor. Preprocessor &getPreprocessor() const { return PP; } /// \brief Retrieve the name of the original source file name for the primary /// module file. StringRef getOriginalSourceFile() { return ModuleMgr.getPrimaryModule().OriginalSourceFileName; } /// \brief Retrieve the name of the original source file name directly from /// the AST file, without actually loading the AST file. static std::string getOriginalSourceFile(const std::string &ASTFileName, FileManager &FileMgr, const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags); /// \brief Read the control block for the named AST file. /// /// \returns true if an error occurred, false otherwise. static bool readASTFileControlBlock(StringRef Filename, FileManager &FileMgr, const PCHContainerReader &PCHContainerRdr, ASTReaderListener &Listener); /// \brief Determine whether the given AST file is acceptable to load into a /// translation unit with the given language and target options. static bool isAcceptableASTFile(StringRef Filename, FileManager &FileMgr, const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts, const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts, std::string ExistingModuleCachePath); /// \brief Returns the suggested contents of the predefines buffer, /// which contains a (typically-empty) subset of the predefines /// build prior to including the precompiled header. const std::string &getSuggestedPredefines() { return SuggestedPredefines; } /// \brief Read a preallocated preprocessed entity from the external source. /// /// \returns null if an error occurred that prevented the preprocessed /// entity from being loaded. PreprocessedEntity *ReadPreprocessedEntity(unsigned Index) override; /// \brief Returns a pair of [Begin, End) indices of preallocated /// preprocessed entities that \p Range encompasses. std::pair<unsigned, unsigned> findPreprocessedEntitiesInRange(SourceRange Range) override; /// \brief Optionally returns true or false if the preallocated preprocessed /// entity with index \p Index came from file \p FID. Optional<bool> isPreprocessedEntityInFileID(unsigned Index, FileID FID) override; /// \brief Read the header file information for the given file entry. HeaderFileInfo GetHeaderFileInfo(const FileEntry *FE) override; void ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag); /// \brief Returns the number of source locations found in the chain. unsigned getTotalNumSLocs() const { return TotalNumSLocEntries; } /// \brief Returns the number of identifiers found in the chain. unsigned getTotalNumIdentifiers() const { return static_cast<unsigned>(IdentifiersLoaded.size()); } /// \brief Returns the number of macros found in the chain. unsigned getTotalNumMacros() const { return static_cast<unsigned>(MacrosLoaded.size()); } /// \brief Returns the number of types found in the chain. unsigned getTotalNumTypes() const { return static_cast<unsigned>(TypesLoaded.size()); } /// \brief Returns the number of declarations found in the chain. unsigned getTotalNumDecls() const { return static_cast<unsigned>(DeclsLoaded.size()); } /// \brief Returns the number of submodules known. unsigned getTotalNumSubmodules() const { return static_cast<unsigned>(SubmodulesLoaded.size()); } /// \brief Returns the number of selectors found in the chain. unsigned getTotalNumSelectors() const { return static_cast<unsigned>(SelectorsLoaded.size()); } /// \brief Returns the number of preprocessed entities known to the AST /// reader. unsigned getTotalNumPreprocessedEntities() const { unsigned Result = 0; for (ModuleConstIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) { Result += (*I)->NumPreprocessedEntities; } return Result; } /// \brief Reads a TemplateArgumentLocInfo appropriate for the /// given TemplateArgument kind. TemplateArgumentLocInfo GetTemplateArgumentLocInfo(ModuleFile &F, TemplateArgument::ArgKind Kind, const RecordData &Record, unsigned &Idx); /// \brief Reads a TemplateArgumentLoc. TemplateArgumentLoc ReadTemplateArgumentLoc(ModuleFile &F, const RecordData &Record, unsigned &Idx); const ASTTemplateArgumentListInfo* ReadASTTemplateArgumentListInfo(ModuleFile &F, const RecordData &Record, unsigned &Index); /// \brief Reads a declarator info from the given record. TypeSourceInfo *GetTypeSourceInfo(ModuleFile &F, const RecordData &Record, unsigned &Idx); /// \brief Resolve a type ID into a type, potentially building a new /// type. QualType GetType(serialization::TypeID ID); /// \brief Resolve a local type ID within a given AST file into a type. QualType getLocalType(ModuleFile &F, unsigned LocalID); /// \brief Map a local type ID within a given AST file into a global type ID. serialization::TypeID getGlobalTypeID(ModuleFile &F, unsigned LocalID) const; /// \brief Read a type from the current position in the given record, which /// was read from the given AST file. QualType readType(ModuleFile &F, const RecordData &Record, unsigned &Idx) { if (Idx >= Record.size()) return QualType(); return getLocalType(F, Record[Idx++]); } /// \brief Map from a local declaration ID within a given module to a /// global declaration ID. serialization::DeclID getGlobalDeclID(ModuleFile &F, serialization::LocalDeclID LocalID) const; /// \brief Returns true if global DeclID \p ID originated from module \p M. bool isDeclIDFromModule(serialization::GlobalDeclID ID, ModuleFile &M) const; /// \brief Retrieve the module file that owns the given declaration, or NULL /// if the declaration is not from a module file. ModuleFile *getOwningModuleFile(const Decl *D); /// \brief Get the best name we know for the module that owns the given /// declaration, or an empty string if the declaration is not from a module. std::string getOwningModuleNameForDiagnostic(const Decl *D); /// \brief Returns the source location for the decl \p ID. SourceLocation getSourceLocationForDeclID(serialization::GlobalDeclID ID); /// \brief Resolve a declaration ID into a declaration, potentially /// building a new declaration. Decl *GetDecl(serialization::DeclID ID); Decl *GetExternalDecl(uint32_t ID) override; /// \brief Resolve a declaration ID into a declaration. Return 0 if it's not /// been loaded yet. Decl *GetExistingDecl(serialization::DeclID ID); /// \brief Reads a declaration with the given local ID in the given module. Decl *GetLocalDecl(ModuleFile &F, uint32_t LocalID) { return GetDecl(getGlobalDeclID(F, LocalID)); } /// \brief Reads a declaration with the given local ID in the given module. /// /// \returns The requested declaration, casted to the given return type. template<typename T> T *GetLocalDeclAs(ModuleFile &F, uint32_t LocalID) { return cast_or_null<T>(GetLocalDecl(F, LocalID)); } /// \brief Map a global declaration ID into the declaration ID used to /// refer to this declaration within the given module fule. /// /// \returns the global ID of the given declaration as known in the given /// module file. serialization::DeclID mapGlobalIDToModuleFileGlobalID(ModuleFile &M, serialization::DeclID GlobalID); /// \brief Reads a declaration ID from the given position in a record in the /// given module. /// /// \returns The declaration ID read from the record, adjusted to a global ID. serialization::DeclID ReadDeclID(ModuleFile &F, const RecordData &Record, unsigned &Idx); /// \brief Reads a declaration from the given position in a record in the /// given module. Decl *ReadDecl(ModuleFile &F, const RecordData &R, unsigned &I) { return GetDecl(ReadDeclID(F, R, I)); } /// \brief Reads a declaration from the given position in a record in the /// given module. /// /// \returns The declaration read from this location, casted to the given /// result type. template<typename T> T *ReadDeclAs(ModuleFile &F, const RecordData &R, unsigned &I) { return cast_or_null<T>(GetDecl(ReadDeclID(F, R, I))); } /// \brief If any redeclarations of \p D have been imported since it was /// last checked, this digs out those redeclarations and adds them to the /// redeclaration chain for \p D. void CompleteRedeclChain(const Decl *D) override; /// \brief Read a CXXBaseSpecifiers ID form the given record and /// return its global bit offset. uint64_t readCXXBaseSpecifiers(ModuleFile &M, const RecordData &Record, unsigned &Idx); CXXBaseSpecifier *GetExternalCXXBaseSpecifiers(uint64_t Offset) override; /// \brief Resolve the offset of a statement into a statement. /// /// This operation will read a new statement from the external /// source each time it is called, and is meant to be used via a /// LazyOffsetPtr (which is used by Decls for the body of functions, etc). Stmt *GetExternalDeclStmt(uint64_t Offset) override; /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the /// specified cursor. Read the abbreviations that are at the top of the block /// and then leave the cursor pointing into the block. static bool ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor, unsigned BlockID); /// \brief Finds all the visible declarations with a given name. /// The current implementation of this method just loads the entire /// lookup table as unmaterialized references. bool FindExternalVisibleDeclsByName(const DeclContext *DC, DeclarationName Name) override; /// \brief Read all of the declarations lexically stored in a /// declaration context. /// /// \param DC The declaration context whose declarations will be /// read. /// /// \param IsKindWeWant A predicate indicating which declaration kinds /// we are interested in. /// /// \param Decls Vector that will contain the declarations loaded /// from the external source. The caller is responsible for merging /// these declarations with any declarations already stored in the /// declaration context. void FindExternalLexicalDecls(const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant, SmallVectorImpl<Decl *> &Decls) override; /// \brief Get the decls that are contained in a file in the Offset/Length /// range. \p Length can be 0 to indicate a point at \p Offset instead of /// a range. void FindFileRegionDecls(FileID File, unsigned Offset, unsigned Length, SmallVectorImpl<Decl *> &Decls) override; /// \brief Notify ASTReader that we started deserialization of /// a decl or type so until FinishedDeserializing is called there may be /// decls that are initializing. Must be paired with FinishedDeserializing. void StartedDeserializing() override; /// \brief Notify ASTReader that we finished the deserialization of /// a decl or type. Must be paired with StartedDeserializing. void FinishedDeserializing() override; /// \brief Function that will be invoked when we begin parsing a new /// translation unit involving this external AST source. /// /// This function will provide all of the external definitions to /// the ASTConsumer. void StartTranslationUnit(ASTConsumer *Consumer) override; /// \brief Print some statistics about AST usage. void PrintStats() override; /// \brief Dump information about the AST reader to standard error. void dump(); /// Return the amount of memory used by memory buffers, breaking down /// by heap-backed versus mmap'ed memory. void getMemoryBufferSizes(MemoryBufferSizes &sizes) const override; /// \brief Initialize the semantic source with the Sema instance /// being used to perform semantic analysis on the abstract syntax /// tree. void InitializeSema(Sema &S) override; /// \brief Inform the semantic consumer that Sema is no longer available. void ForgetSema() override { SemaObj = nullptr; } /// \brief Retrieve the IdentifierInfo for the named identifier. /// /// This routine builds a new IdentifierInfo for the given identifier. If any /// declarations with this name are visible from translation unit scope, their /// declarations will be deserialized and introduced into the declaration /// chain of the identifier. IdentifierInfo *get(StringRef Name) override; /// \brief Retrieve an iterator into the set of all identifiers /// in all loaded AST files. IdentifierIterator *getIdentifiers() override; /// \brief Load the contents of the global method pool for a given /// selector. void ReadMethodPool(Selector Sel) override; /// \brief Load the set of namespaces that are known to the external source, /// which will be used during typo correction. void ReadKnownNamespaces( SmallVectorImpl<NamespaceDecl *> &Namespaces) override; void ReadUndefinedButUsed( llvm::DenseMap<NamedDecl *, SourceLocation> &Undefined) override; void ReadMismatchingDeleteExpressions(llvm::MapVector< FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> & Exprs) override; void ReadTentativeDefinitions( SmallVectorImpl<VarDecl *> &TentativeDefs) override; void ReadUnusedFileScopedDecls( SmallVectorImpl<const DeclaratorDecl *> &Decls) override; void ReadDelegatingConstructors( SmallVectorImpl<CXXConstructorDecl *> &Decls) override; void ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) override; void ReadUnusedLocalTypedefNameCandidates( llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) override; void ReadReferencedSelectors( SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) override; void ReadWeakUndeclaredIdentifiers( SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WI) override; void ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) override; void ReadPendingInstantiations( SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) override; void ReadLateParsedTemplates( llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) override; /// \brief Load a selector from disk, registering its ID if it exists. void LoadSelector(Selector Sel); void SetIdentifierInfo(unsigned ID, IdentifierInfo *II); void SetGloballyVisibleDecls(IdentifierInfo *II, const SmallVectorImpl<uint32_t> &DeclIDs, SmallVectorImpl<Decl *> *Decls = nullptr); /// \brief Report a diagnostic. DiagnosticBuilder Diag(unsigned DiagID); /// \brief Report a diagnostic. DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID); IdentifierInfo *DecodeIdentifierInfo(serialization::IdentifierID ID); IdentifierInfo *GetIdentifierInfo(ModuleFile &M, const RecordData &Record, unsigned &Idx) { return DecodeIdentifierInfo(getGlobalIdentifierID(M, Record[Idx++])); } IdentifierInfo *GetIdentifier(serialization::IdentifierID ID) override { // Note that we are loading an identifier. Deserializing AnIdentifier(this); return DecodeIdentifierInfo(ID); } IdentifierInfo *getLocalIdentifier(ModuleFile &M, unsigned LocalID); serialization::IdentifierID getGlobalIdentifierID(ModuleFile &M, unsigned LocalID); void resolvePendingMacro(IdentifierInfo *II, const PendingMacroInfo &PMInfo); /// \brief Retrieve the macro with the given ID. MacroInfo *getMacro(serialization::MacroID ID); /// \brief Retrieve the global macro ID corresponding to the given local /// ID within the given module file. serialization::MacroID getGlobalMacroID(ModuleFile &M, unsigned LocalID); /// \brief Read the source location entry with index ID. bool ReadSLocEntry(int ID) override; /// \brief Retrieve the module import location and module name for the /// given source manager entry ID. std::pair<SourceLocation, StringRef> getModuleImportLoc(int ID) override; /// \brief Retrieve the global submodule ID given a module and its local ID /// number. serialization::SubmoduleID getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID); /// \brief Retrieve the submodule that corresponds to a global submodule ID. /// Module *getSubmodule(serialization::SubmoduleID GlobalID); /// \brief Retrieve the module that corresponds to the given module ID. /// /// Note: overrides method in ExternalASTSource Module *getModule(unsigned ID) override; /// \brief Retrieve the module file with a given local ID within the specified /// ModuleFile. ModuleFile *getLocalModuleFile(ModuleFile &M, unsigned ID); /// \brief Get an ID for the given module file. unsigned getModuleFileID(ModuleFile *M); /// \brief Return a descriptor for the corresponding module. llvm::Optional<ASTSourceDescriptor> getSourceDescriptor(unsigned ID) override; /// \brief Retrieve a selector from the given module with its local ID /// number. Selector getLocalSelector(ModuleFile &M, unsigned LocalID); Selector DecodeSelector(serialization::SelectorID Idx); Selector GetExternalSelector(serialization::SelectorID ID) override; uint32_t GetNumExternalSelectors() override; Selector ReadSelector(ModuleFile &M, const RecordData &Record, unsigned &Idx) { return getLocalSelector(M, Record[Idx++]); } /// \brief Retrieve the global selector ID that corresponds to this /// the local selector ID in a given module. serialization::SelectorID getGlobalSelectorID(ModuleFile &F, unsigned LocalID) const; /// \brief Read a declaration name. DeclarationName ReadDeclarationName(ModuleFile &F, const RecordData &Record, unsigned &Idx); void ReadDeclarationNameLoc(ModuleFile &F, DeclarationNameLoc &DNLoc, DeclarationName Name, const RecordData &Record, unsigned &Idx); void ReadDeclarationNameInfo(ModuleFile &F, DeclarationNameInfo &NameInfo, const RecordData &Record, unsigned &Idx); void ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info, const RecordData &Record, unsigned &Idx); NestedNameSpecifier *ReadNestedNameSpecifier(ModuleFile &F, const RecordData &Record, unsigned &Idx); NestedNameSpecifierLoc ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record, unsigned &Idx); /// \brief Read a template name. TemplateName ReadTemplateName(ModuleFile &F, const RecordData &Record, unsigned &Idx); /// \brief Read a template argument. TemplateArgument ReadTemplateArgument(ModuleFile &F, const RecordData &Record, unsigned &Idx, bool Canonicalize = false); /// \brief Read a template parameter list. TemplateParameterList *ReadTemplateParameterList(ModuleFile &F, const RecordData &Record, unsigned &Idx); /// \brief Read a template argument array. void ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs, ModuleFile &F, const RecordData &Record, unsigned &Idx, bool Canonicalize = false); /// \brief Read a UnresolvedSet structure. void ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set, const RecordData &Record, unsigned &Idx); /// \brief Read a C++ base specifier. CXXBaseSpecifier ReadCXXBaseSpecifier(ModuleFile &F, const RecordData &Record,unsigned &Idx); /// \brief Read a CXXCtorInitializer array. CXXCtorInitializer ** ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record, unsigned &Idx); /// \brief Read a CXXCtorInitializers ID from the given record and /// return its global bit offset. uint64_t ReadCXXCtorInitializersRef(ModuleFile &M, const RecordData &Record, unsigned &Idx); /// \brief Read the contents of a CXXCtorInitializer array. CXXCtorInitializer **GetExternalCXXCtorInitializers(uint64_t Offset) override; /// \brief Read a source location from raw form. SourceLocation ReadSourceLocation(ModuleFile &ModuleFile, unsigned Raw) const { SourceLocation Loc = SourceLocation::getFromRawEncoding(Raw); assert(ModuleFile.SLocRemap.find(Loc.getOffset()) != ModuleFile.SLocRemap.end() && "Cannot find offset to remap."); int Remap = ModuleFile.SLocRemap.find(Loc.getOffset())->second; return Loc.getLocWithOffset(Remap); } /// \brief Read a source location. SourceLocation ReadSourceLocation(ModuleFile &ModuleFile, const RecordDataImpl &Record, unsigned &Idx) { return ReadSourceLocation(ModuleFile, Record[Idx++]); } /// \brief Read a source range. SourceRange ReadSourceRange(ModuleFile &F, const RecordData &Record, unsigned &Idx); /// \brief Read an integral value llvm::APInt ReadAPInt(const RecordData &Record, unsigned &Idx); /// \brief Read a signed integral value llvm::APSInt ReadAPSInt(const RecordData &Record, unsigned &Idx); /// \brief Read a floating-point value llvm::APFloat ReadAPFloat(const RecordData &Record, const llvm::fltSemantics &Sem, unsigned &Idx); // \brief Read a string static std::string ReadString(const RecordData &Record, unsigned &Idx); // \brief Read a path std::string ReadPath(ModuleFile &F, const RecordData &Record, unsigned &Idx); /// \brief Read a version tuple. static VersionTuple ReadVersionTuple(const RecordData &Record, unsigned &Idx); CXXTemporary *ReadCXXTemporary(ModuleFile &F, const RecordData &Record, unsigned &Idx); /// \brief Reads attributes from the current stream position. void ReadAttributes(ModuleFile &F, AttrVec &Attrs, const RecordData &Record, unsigned &Idx); /// \brief Reads a statement. Stmt *ReadStmt(ModuleFile &F); /// \brief Reads an expression. Expr *ReadExpr(ModuleFile &F); /// \brief Reads a sub-statement operand during statement reading. Stmt *ReadSubStmt() { assert(ReadingKind == Read_Stmt && "Should be called only during statement reading!"); // Subexpressions are stored from last to first, so the next Stmt we need // is at the back of the stack. assert(!StmtStack.empty() && "Read too many sub-statements!"); return StmtStack.pop_back_val(); } /// \brief Reads a sub-expression operand during statement reading. Expr *ReadSubExpr(); /// \brief Reads a token out of a record. Token ReadToken(ModuleFile &M, const RecordDataImpl &Record, unsigned &Idx); /// \brief Reads the macro record located at the given offset. MacroInfo *ReadMacroRecord(ModuleFile &F, uint64_t Offset); /// \brief Determine the global preprocessed entity ID that corresponds to /// the given local ID within the given module. serialization::PreprocessedEntityID getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const; /// \brief Add a macro to deserialize its macro directive history. /// /// \param II The name of the macro. /// \param M The module file. /// \param MacroDirectivesOffset Offset of the serialized macro directive /// history. void addPendingMacro(IdentifierInfo *II, ModuleFile *M, uint64_t MacroDirectivesOffset); /// \brief Read the set of macros defined by this external macro source. void ReadDefinedMacros() override; /// \brief Update an out-of-date identifier. void updateOutOfDateIdentifier(IdentifierInfo &II) override; /// \brief Note that this identifier is up-to-date. void markIdentifierUpToDate(IdentifierInfo *II); /// \brief Load all external visible decls in the given DeclContext. void completeVisibleDeclsMap(const DeclContext *DC) override; /// \brief Retrieve the AST context that this AST reader supplements. ASTContext &getContext() { return Context; } // \brief Contains the IDs for declarations that were requested before we have // access to a Sema object. SmallVector<uint64_t, 16> PreloadedDeclIDs; /// \brief Retrieve the semantic analysis object used to analyze the /// translation unit in which the precompiled header is being /// imported. Sema *getSema() { return SemaObj; } /// \brief Retrieve the identifier table associated with the /// preprocessor. IdentifierTable &getIdentifierTable(); /// \brief Record that the given ID maps to the given switch-case /// statement. void RecordSwitchCaseID(SwitchCase *SC, unsigned ID); /// \brief Retrieve the switch-case statement with the given ID. SwitchCase *getSwitchCaseWithID(unsigned ID); void ClearSwitchCaseIDs(); /// \brief Cursors for comments blocks. SmallVector<std::pair<llvm::BitstreamCursor, serialization::ModuleFile *>, 8> CommentsCursors; /// \brief Loads comments ranges. void ReadComments() override; }; /// \brief Helper class that saves the current stream position and /// then restores it when destroyed. struct SavedStreamPosition { explicit SavedStreamPosition(llvm::BitstreamCursor &Cursor) : Cursor(Cursor), Offset(Cursor.GetCurrentBitNo()) { } ~SavedStreamPosition() { Cursor.JumpToBit(Offset); } private: llvm::BitstreamCursor &Cursor; uint64_t Offset; }; inline void PCHValidator::Error(const char *Msg) { Reader.Error(Msg); } } // end namespace clang #endif
[ "rich@82857169-6e38-49d7-aaa8-07fb558f12fc" ]
rich@82857169-6e38-49d7-aaa8-07fb558f12fc
d5bf6b90c19568c536344c55f3dfd06a379902c6
6e2727e566c8c18cefd5b3c86b4f03202c2e8782
/HDU/1408.cpp
2ed3725ec0945a2a97e3ac3c522e1e880515bbd6
[]
no_license
AntSworD/ACM
6cd5c39b5e86972278d8857ecd6c965e7d9aa267
20f05035be7251cf2857a2a98c37df69cefb5dac
refs/heads/master
2021-01-19T14:12:41.253484
2013-05-17T15:56:50
2013-05-17T15:56:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
251
cpp
#include<stdio.h> int main() { double v,d; int i,sum; while(scanf("%lf %lf",&v,&d)!=EOF) { sum=v/d; if( d * sum != v ) sum++; for(i=1;;i++) { v=v-d*i; if(v>0) sum++; else break; } printf("%d\n",sum); } return 0; }
[ "zhengjj.asd@gmail.com" ]
zhengjj.asd@gmail.com
89bde34c0aeb2caebd5daf4a4d27d52e260eb0e2
cc13c060d7d3ed555d68073c770fc0aca3c67f82
/project-euler/p133.cpp
556228d7db8e0f220b40269c09d0c40b3a42bf06
[]
no_license
Devang-25/acm-icpc
8bd29cc90119a6269ccd61729d8e67a8b642b131
a036bdbba60f8b363ee2d6cb9814e82e5536e02e
refs/heads/master
2022-04-01T02:52:51.367994
2020-01-24T11:46:01
2020-01-24T11:46:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,339
cpp
#include <cstdio> #include <vector> // 2 + 3 + 5 + sum_{5 < prime p < 10^5} p * [forall n >= 1, 10^n mod ord_p(10) != 0] std::vector<int> get_primes(int n) { std::vector<bool> is_prime(n + 1, true); std::vector<int> primes; for (int d = 2; d <= n; ++ d) { if (is_prime[d]) { primes.push_back(d); } for (auto&& p : primes) { if (d * p > n) { break; } is_prime[d * p] = false; if (d % p == 0) { break; } } } return primes; } int power(int a, int n, int mod) { int result = 1; while (n) { if (n & 1) { result = (long long)result * a % mod; } a = (long long)a * a % mod; n >>= 1; } return result; } int main() { int sum = 2 + 3 + 5; for (auto&& p : get_primes(100000)) { if (p > 5) { int tmp = p - 1; int ord = 1; for (auto&& q : std::vector<int>{2, 5}) { while (tmp % q == 0) { ord *= q; tmp /= q; } } if (power(10, ord, p) != 1) { sum += p; } else { // printf("%d\n", p); } } } printf("%d\n", sum); }
[ "ftiasch0@gmail.com" ]
ftiasch0@gmail.com
62609f95b01cf512ff54a335247317f0005ac0c7
b0204aea8e281570227e5846d0c4df41ade5cc30
/macOS/JACK-insert/JARInsert/JARInsert.cpp
b0ae37bcf4051b4bb7db3aac424b40cd67af41a1
[]
no_license
jackaudio/jack-router
57413c11577156fd3309e74092ff4f8e2410900b
97ce963f7684c33c15132ed0eb7a899654b30a3a
refs/heads/main
2023-03-07T13:55:30.736356
2023-03-02T15:40:27
2023-03-02T15:40:27
304,329,196
17
10
null
2021-01-06T14:50:43
2020-10-15T13:07:29
C++
UTF-8
C++
false
false
17,226
cpp
/* JARInsert.cpp This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA (c) 2004, elementicaotici - by Johnny (Giovanni) Petrantoni, ITALY - Rome. e-mail: johnny@meskalina.it web: http://www.meskalina.it */ #include "JARInsert.h" int JARInsert::c_instances = 0; int JARInsert::c_instances_count = 0; bool JARInsert::c_printDebug = false; extern "C" void JARILog(char *fmt, ...) { if (JARInsert::c_printDebug) { va_list ap; va_start(ap, fmt); fprintf(stdout, "JARInsert Log: "); vfprintf(stdout, fmt, ap); va_end(ap); } } JARInsert::JARInsert(long host_buffer_size, int hostType) : c_error(kNoErr), c_client(NULL), c_isRunning(false), c_rBufOn(false), c_needsDeactivate(false), c_hBufferSize(host_buffer_size), c_hostType(hostType) { ReadPrefs(); UInt32 outSize; Boolean isWritable; if (!OpenAudioClient()) { JARILog("Cannot find jack client.\n"); SHOWALERT("Cannot find jack client for this application, check if Jack server is running."); return; } // Deactivate Jack callback //AudioDeviceGetPropertyInfo(c_jackDevID, 0, true, kAudioDevicePropertyDeactivateJack, &outSize, &isWritable); //AudioDeviceSetProperty(c_jackDevID, NULL, 0, true, kAudioDevicePropertyDeactivateJack, 0, NULL); int nPorts = 2; c_inPorts = (jack_port_t**)malloc(sizeof(jack_port_t*) * nPorts); c_outPorts = (float**)malloc(sizeof(float*) * nPorts); c_nInPorts = c_nOutPorts = nPorts; c_jBufferSize = jack_get_buffer_size(c_client); char name[256]; for (int i = 0;i < c_nInPorts;i++) { if (hostType == 'vst ') sprintf(name, "VSTreturn%d", JARInsert::c_instances + i + 1); else sprintf(name, "AUreturn%d", JARInsert::c_instances + i + 1); c_inPorts[i] = jack_port_register(c_client, name, JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0); JARILog("Port: %s created\n", name); } c_instance = JARInsert::c_instances; for (int i = 0; i < c_nOutPorts; i++) { UInt32 portNum = c_instance + i; if (hostType == 'vst ') { AudioDeviceGetPropertyInfo(c_jackDevID, 0, true, kAudioDevicePropertyAllocateJackPortVST, &outSize, &isWritable); AudioDeviceSetProperty(c_jackDevID, NULL, 0, true, kAudioDevicePropertyAllocateJackPortVST, portNum, NULL); AudioDeviceGetPropertyInfo(c_jackDevID, 0, true, kAudioDevicePropertyGetJackPortVST, &outSize, &isWritable); AudioDeviceGetProperty(c_jackDevID, 0, true, kAudioDevicePropertyGetJackPortVST, &portNum, &c_outPorts[i]); } else { AudioDeviceGetPropertyInfo(c_jackDevID, 0, true, kAudioDevicePropertyAllocateJackPortAU, &outSize, &isWritable); AudioDeviceSetProperty(c_jackDevID, NULL, 0, true, kAudioDevicePropertyAllocateJackPortAU, portNum, NULL); AudioDeviceGetPropertyInfo(c_jackDevID, 0, true, kAudioDevicePropertyGetJackPortAU, &outSize, &isWritable); AudioDeviceGetProperty(c_jackDevID, 0, true, kAudioDevicePropertyGetJackPortAU, &portNum, &c_outPorts[i]); } JARILog("Port: %s created\n", name); } #if 0 if (!c_isRunning) { JARILog("Jack client activated\n"); jack_activate(c_client); c_needsDeactivate = true; } else c_needsDeactivate = false; #endif if (c_jBufferSize > c_hBufferSize) { c_bsAI1 = new BSizeAlign(c_hBufferSize, c_jBufferSize); c_bsAI2 = new BSizeAlign(c_hBufferSize, c_jBufferSize); c_bsAO1 = new BSizeAlign(c_jBufferSize, c_hBufferSize); c_bsAO2 = new BSizeAlign(c_jBufferSize, c_hBufferSize); if (c_bsAI1->Ready() && c_bsAI2->Ready() && c_bsAO1->Ready() && c_bsAO2->Ready()) { c_rBufOn = true; } else { c_error = kErrInvalidBSize; Flush(); return ; } } JARInsert::c_instances += 2; JARInsert::c_instances_count++; c_canProcess = true; // (Possible) reactivate Jack callback //AudioDeviceGetPropertyInfo(c_jackDevID, 0, true, kAudioDevicePropertyActivateJack, &outSize, &isWritable); //AudioDeviceSetProperty(c_jackDevID, NULL, 0, true, kAudioDevicePropertyActivateJack, 0, NULL); } JARInsert::JARInsert(int hostType) : c_error(kNoErr), c_client(NULL), c_isRunning(false), c_rBufOn(false), c_needsDeactivate(false), c_hBufferSize(0), c_hostType(hostType) { ReadPrefs(); UInt32 outSize; Boolean isWritable; if (!OpenAudioClient()) { JARILog("Cannot find jack client.\n"); SHOWALERT("Cannot find jack client for this application, check if Jack server is running."); return ; } // Deactivate Jack callback //AudioDeviceGetPropertyInfo(c_jackDevID, 0, true, kAudioDevicePropertyDeactivateJack, &outSize, &isWritable); //AudioDeviceSetProperty(c_jackDevID, NULL, 0, true, kAudioDevicePropertyDeactivateJack, 0, NULL); int nPorts = 2; c_inPorts = (jack_port_t**)malloc(sizeof(jack_port_t*) * nPorts); c_outPorts = (float**)malloc(sizeof(float*) * nPorts); c_nInPorts = c_nOutPorts = nPorts; c_jBufferSize = jack_get_buffer_size(c_client); char name[256]; for (int i = 0; i < c_nInPorts; i++) { if (hostType == 'vst ') sprintf(name, "VSTreturn%d", JARInsert::c_instances + i + 1); else sprintf(name, "AUreturn%d", JARInsert::c_instances + i + 1); c_inPorts[i] = jack_port_register(c_client, name, JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0); JARILog("Port: %s created\n", name); } c_instance = JARInsert::c_instances; for (int i = 0; i < c_nOutPorts; i++) { UInt32 portNum = c_instance + i; if (hostType == 'vst ') { AudioDeviceGetPropertyInfo(c_jackDevID, 0, true, kAudioDevicePropertyAllocateJackPortVST, &outSize, &isWritable); AudioDeviceSetProperty(c_jackDevID, NULL, 0, true, kAudioDevicePropertyAllocateJackPortVST, portNum, NULL); AudioDeviceGetPropertyInfo(c_jackDevID, 0, true, kAudioDevicePropertyGetJackPortVST, &outSize, &isWritable); AudioDeviceGetProperty(c_jackDevID, 0, true, kAudioDevicePropertyGetJackPortVST, &portNum, &c_outPorts[i]); } else { AudioDeviceGetPropertyInfo(c_jackDevID, 0, true, kAudioDevicePropertyAllocateJackPortAU, &outSize, &isWritable); AudioDeviceSetProperty(c_jackDevID, NULL, 0, true, kAudioDevicePropertyAllocateJackPortAU, portNum, NULL); AudioDeviceGetPropertyInfo(c_jackDevID, 0, true, kAudioDevicePropertyGetJackPortAU, &outSize, &isWritable); AudioDeviceGetProperty(c_jackDevID, 0, true, kAudioDevicePropertyGetJackPortAU, &portNum, &c_outPorts[i]); } JARILog("Port: %s created\n", name); } #if 0 if (!c_isRunning) { JARILog("Jack client activated\n"); jack_activate(c_client); c_needsDeactivate = true; } else c_needsDeactivate = false; #endif JARInsert::c_instances += 2; JARInsert::c_instances_count++; c_canProcess = false; // (Possible) reactivate Jack callback //AudioDeviceGetPropertyInfo(c_jackDevID, 0, true, kAudioDevicePropertyActivateJack, &outSize, &isWritable); //AudioDeviceSetProperty(c_jackDevID, NULL, 0, true, kAudioDevicePropertyActivateJack, 0, NULL); } JARInsert::~JARInsert() { if (c_error == kNoErr) Flush(); } bool JARInsert::AllocBSizeAlign(long host_buffer_size) { JARILog("AllocBSizeAlign host_buffer_size = %ld \n", host_buffer_size); c_hBufferSize = host_buffer_size; if (c_jBufferSize > c_hBufferSize) { if (((host_buffer_size - 1) & host_buffer_size) != 0) { JARILog("Bad buffer size for BSizeAlign host_buffer_size %ld \n", host_buffer_size); c_error = kErrInvalidBSize; Flush(); return false; } JARILog("AllocBSizeAlign c_jBufferSize = %ld c_hBufferSize = %ld\n", c_jBufferSize, c_hBufferSize); c_bsAI1 = new BSizeAlign(c_hBufferSize, c_jBufferSize); c_bsAI2 = new BSizeAlign(c_hBufferSize, c_jBufferSize); c_bsAO1 = new BSizeAlign(c_jBufferSize, c_hBufferSize); c_bsAO2 = new BSizeAlign(c_jBufferSize, c_hBufferSize); if (c_bsAI1->Ready() && c_bsAI2->Ready() && c_bsAO1->Ready() && c_bsAO2->Ready()) { c_rBufOn = true; } else { JARILog("Bad buffer size for BSizeAlign c_hBufferSize %ld c_jBufferSize %ld \n",c_hBufferSize, c_jBufferSize); c_error = kErrInvalidBSize; Flush(); return false; } } else if (c_jBufferSize < c_hBufferSize) { JARILog("Bad buffer size jack<host, must be jack>host || jack==host %ld %ld \n", c_jBufferSize, c_hBufferSize); c_error = kErrInvalidBSize; Flush(); return false; } c_canProcess = true; if (c_rBufOn) JARILog("Using BSizeAlign.\n"); else JARILog("Not Using BSizeAlign.\n"); return true; } int JARInsert::Process(float** in_buffer, float** out_buffer, long host_nframes) { if (c_hBufferSize != host_nframes) { JARILog("CRITICAL ERROR: Host Buffer Size mismatch, NOT PROCESSING!! %ld c_hBufferSize %ld host_nframes \n", c_hBufferSize, host_nframes); return 1; } if (c_rBufOn) { float* out1 = c_outPorts[0]; float* out2 = c_outPorts[1]; float* in1 = (float*) jack_port_get_buffer(c_inPorts[0], (jack_nframes_t)c_jBufferSize); float* in2 = (float*) jack_port_get_buffer(c_inPorts[1], (jack_nframes_t)c_jBufferSize); c_bsAI1->AddBuffer(in_buffer[0]); c_bsAI2->AddBuffer(in_buffer[1]); if (!c_bsAO1->CanGet()) c_bsAO1->AddBuffer(in1); if (!c_bsAO2->CanGet()) c_bsAO2->AddBuffer(in2); if (c_bsAO1->CanGet()) c_bsAO1->GetBuffer(out_buffer[0]); if (c_bsAO2->CanGet()) c_bsAO2->GetBuffer(out_buffer[1]); if (c_bsAI1->CanGet()) c_bsAI1->GetBuffer(out1); if (c_bsAI2->CanGet()) c_bsAI2->GetBuffer(out2); } else { if (c_jBufferSize != host_nframes) { JARILog("CRITICAL ERROR: Host Buffer Size mismatch, NOT PROCESSING!! %ld c_hBufferSize %ld host_nframes \n", c_hBufferSize, host_nframes); return 1; } float* out1 = c_outPorts[0]; float* out2 = c_outPorts[1]; float* in1 = (float*) jack_port_get_buffer(c_inPorts[0], (jack_nframes_t)c_jBufferSize); float* in2 = (float*) jack_port_get_buffer(c_inPorts[1], (jack_nframes_t)c_jBufferSize); memcpy(out1, in_buffer[0], sizeof(float) * c_jBufferSize); memcpy(out2, in_buffer[1], sizeof(float) * c_jBufferSize); memcpy(out_buffer[0], in1, sizeof(float) * c_jBufferSize); memcpy(out_buffer[1], in2, sizeof(float) * c_jBufferSize); } return 0; } bool JARInsert::OpenAudioClient() { OSStatus err; UInt32 size; Boolean isWritable; err = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &size, &isWritable); if (err != noErr) { c_error = kErrCoreAudio; return false; } int nDevices = size / sizeof(AudioDeviceID); JARILog("There are %d audio devices\n", nDevices); AudioDeviceID *device = (AudioDeviceID*)calloc(nDevices, sizeof(AudioDeviceID)); err = AudioHardwareGetProperty(kAudioHardwarePropertyDevices, &size, device); if (err != noErr) { c_error = kErrCoreAudio; return false; } for (int i = 0; i < nDevices; i++) { JARILog("ID: %ld\n", device[i]); char name[256]; size = 256; err = AudioDeviceGetProperty(device[i], 0, true, kAudioDevicePropertyDeviceName, &size, &name); if (err == noErr) { JARILog("Name: %s\n", name); if (strcmp(&name[0], "JackRouter") == 0) { c_jackDevID = device[i]; if (device != NULL) free(device); JARILog("Get Jack client\n"); size = sizeof(UInt32); err = AudioDeviceGetProperty(c_jackDevID, 0, true, kAudioDevicePropertyGetJackClient, &size, &c_client); if (err != noErr) { JARILog("Get Jack client error = %d\n", err); c_error = kErrNoClient; return false; } JARILog("Get Jack client OK\n"); #if 0 size = sizeof(UInt32); err = AudioDeviceGetProperty(c_jackDevID, 0, true, kAudioDevicePropertyDeviceIsRunning, &size, &c_isRunning); if (err != noErr) { c_error = kErrNoClient; return false; } #endif if (c_client != NULL) { c_error = kNoErr; return true; } else return false; } } } c_error = kErrNoClient; return false; } void JARInsert::Flush() { JARILog("Running flush\n"); UInt32 outSize; Boolean isWritable; OSStatus err; if (c_client != NULL) { // Deactivate Jack callback //AudioDeviceGetPropertyInfo(c_jackDevID, 0, true, kAudioDevicePropertyDeactivateJack, &outSize, &isWritable); //AudioDeviceSetProperty(c_jackDevID, NULL, 0, true, kAudioDevicePropertyDeactivateJack, 0, NULL); if (c_rBufOn) { delete c_bsAO1; delete c_bsAO2; delete c_bsAI1; delete c_bsAI2; } #if 0 if (c_needsDeactivate) { JARILog("Needs Deactivate client\n"); jack_deactivate(c_client); } #endif // Check if client is still opened JARILog("Get Jack client\n"); outSize = sizeof(UInt32); err = AudioDeviceGetProperty(c_jackDevID, 0, true, kAudioDevicePropertyGetJackClient, &outSize, &c_client); if (err != noErr) { JARILog("Get Jack client error = %d\n", err); return; } if (!c_client) { JARILog("Jack client already desallocated...\n", err); return; } for (int i = 0; i < c_nInPorts; i++) { jack_port_unregister(c_client, c_inPorts[i]); } free(c_inPorts); for (int i = 0; i < c_nOutPorts; i++) { UInt32 portNum = c_instance + i; if (c_hostType == 'vst ') { AudioDeviceGetPropertyInfo(c_jackDevID, 0, true, kAudioDevicePropertyReleaseJackPortVST, &outSize, &isWritable); AudioDeviceSetProperty(c_jackDevID, NULL, 0, true, kAudioDevicePropertyReleaseJackPortVST, portNum, NULL); } else { AudioDeviceGetPropertyInfo(c_jackDevID, 0, true, kAudioDevicePropertyReleaseJackPortAU, &outSize, &isWritable); AudioDeviceSetProperty(c_jackDevID, NULL, 0, true, kAudioDevicePropertyReleaseJackPortAU, portNum, NULL); } } free(c_outPorts); // (Possible) reactivate Jack callback //AudioDeviceGetPropertyInfo(c_jackDevID, 0, true, kAudioDevicePropertyActivateJack, &outSize, &isWritable); //AudioDeviceSetProperty(c_jackDevID, NULL, 0, true, kAudioDevicePropertyActivateJack, 0, NULL); AudioDeviceGetPropertyInfo(c_jackDevID, 0, true, kAudioDevicePropertyReleaseJackClient, &outSize, &isWritable); AudioDeviceGetProperty(c_jackDevID, 0, true, kAudioDevicePropertyReleaseJackClient, &outSize, &c_client); JARInsert::c_instances_count--; if (JARInsert::c_instances_count == 0) JARInsert::c_instances = 0; } } bool JARInsert::ReadPrefs() { CFURLRef prefURL; FSRef prefFolderRef; OSErr err; char buf[256]; char path[256]; err = FSFindFolder(kUserDomain, kPreferencesFolderType, kDontCreateFolder, &prefFolderRef); if (err == noErr) { prefURL = CFURLCreateFromFSRef(kCFAllocatorSystemDefault, &prefFolderRef); if (prefURL) { CFURLGetFileSystemRepresentation(prefURL, FALSE, (UInt8*)buf, 256); sprintf(path, "%s/JAS.jpil", buf); FILE* prefFile; if ((prefFile = fopen(path, "rt"))) { int nullo; fscanf( prefFile, "\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d", &nullo, &nullo, &nullo, &nullo, &nullo, &nullo, &nullo, &nullo, &nullo, &nullo, &nullo, &nullo, (int*)&JARInsert::c_printDebug ); fclose(prefFile); return true; } } } return false; }
[ "falktx@falktx.com" ]
falktx@falktx.com
b0ba01b146fdf601d36e5c22af0ce0d686250972
cf19b83d1623d733a8b9744dea965b69689924a3
/10.Dielectrics/sphere.cpp
98e582c100935c61644a9ca1b11f0bf4fab25b0f
[ "MIT" ]
permissive
tusharsankhala/RaytracingOneWeek
dbc564ac9b9c4d311d21faca5e27c8d863f469ef
55cb6f6abb6bf55550f96354bca19cd76456c2d0
refs/heads/master
2021-07-25T11:52:17.367122
2020-04-08T05:12:54
2020-04-08T05:12:54
134,158,040
0
0
null
null
null
null
UTF-8
C++
false
false
1,924
cpp
#include "sphere.h" // Equation of the sphere // R ^ 2 = x ^ 2 + y ^ 2 + z ^ 2 // This is a case where the center of the sphere is at (0,0,0). If we assume that the center of the sphere is C = (cx,cy,cz), then the equation becomes // R ^ 2 = (x-cx) ^ 2 + (y-cy) ^ 2 + (z-cz) ^ 2 // In graphics, we can describe it as // R^2 = dot( p - C , p - C ) // P is again a function of P = A + t * B, which is the ray tracing equation. // So you can get it // R^2 = dot( (A + t B - C) , (A + t B - C) ) // Finally, R, A, B, and C are all parameters that we specify. We need to know the value of t. Just solve the equation. // Based on algebra knowledge, it can be introduced // dot(B,B) t ^ 2 + 2 dot( B , A-C ) * t + dot(A-C,A-C) - R^2 = 0 // Sphere hit test function. // it will return the closest hit point t for the sphere. bool sphere::hit(const Ray& r, double t_min, double t_max, hit_record& rec) const { vec3d oc = r.origin() - center; auto a = r.direction().magnitude_squared(); auto half_b = dot(oc, r.direction()); auto c = oc.magnitude_squared() - radius * radius; auto discriminant = half_b * half_b - a * c; if (discriminant > 0) { auto root = sqrt(discriminant); auto temp = (-half_b - root) / a; if (temp < t_max && temp > t_min) { rec.t = temp; rec.p = r.point_at_parameter(rec.t); vec3d outward_normal = normalize(rec.p - center); rec.Set_Face_Normal(r, outward_normal); rec.mat_ptr = mat_ptr; return true; } temp = (-half_b + root) / a; if (temp < t_max && temp > t_min) { rec.t = temp; rec.p = r.point_at_parameter(rec.t); vec3d outward_normal = normalize(rec.p - center); rec.Set_Face_Normal(r, outward_normal); rec.mat_ptr = mat_ptr; return true; } } return false; }
[ "tusharsankhala@gmail.com" ]
tusharsankhala@gmail.com
36a941a650325ea02ca277b290e1107e94b7aa25
1e59d40a86cf6d7f6b92f5e002dc21387656aec0
/JfF/CODE-JfF-M/0072.cpp
6e29020225322d38176acb5817e9ff6dd1ae5004
[]
no_license
Soplia/Codes
7bb0aecfec57d8bacb33bd1765038d0cffc19e54
3704f55b060877f61647b7a0fcf3d2eefe7fa47e
refs/heads/master
2020-04-20T14:06:36.386774
2019-02-02T23:37:21
2019-02-02T23:37:21
168,888,217
0
1
null
null
null
null
GB18030
C++
false
false
1,524
cpp
#include <stdio.h> #include <stdlib.h> void swap(int* a, int* b) { int temp = *b; *b = *a; *a = temp; } void max_heapify(int arr[], int start, int end) { //建立父节点指标和子节点指标 int dad = start; int son = dad * 2 + 1; while (son <= end) { //若子节点指标在范围内才做比较 if (son + 1 <= end && arr[son] < arr[son + 1]) //先比较两个子节点大小,选择最大的 son++; if (arr[dad] > arr[son]) //如果父节点大於子节点代表调整完毕,直接跳出函数 return; else { //否则交换父子内容再继续子节点和孙节点比较 swap(&arr[dad], &arr[son]); dad = son; son = dad * 2 + 1; } } } void heap_sort(int arr[], int len) { int i; //初始化,i从最後一个父节点开始调整 for (i = len / 2 - 1; i >= 0; i--) max_heapify(arr, i, len - 1); //先将第一个元素和已排好元素前一位做交换,再重新调整,直到排序完毕 for (i = len - 1; i > 0; i--) { swap(&arr[0], &arr[i]); max_heapify(arr, 0, i - 1); } } int main() { int arr[] = { 3, 5, 3, 0, 8, 6, 1, 5, 8, 6, 2, 4, 9, 4, 7, 0, 1, 8, 9, 7, 3, 1, 2, 5, 9, 7, 4, 0, 2, 6 }; int len = (int) sizeof(arr) / sizeof(*arr); heap_sort(arr, len); int i; for (i = 0; i < len; i++) printf("%d ", arr[i]); printf("\n"); return 0; }
[ "Soplia@github.com" ]
Soplia@github.com
d9c8bc21f9b36a2ee81a7f9405fc283c847cf488
777a75e6ed0934c193aece9de4421f8d8db01aac
/src/Providers/UNIXProviders/ProcessorCore/UNIX_ProcessorCore_ZOS.hxx
7234273c94006da9597110f4ca2b52ff60fccea2
[ "MIT" ]
permissive
brunolauze/openpegasus-providers-old
20fc13958016e35dc4d87f93d1999db0eae9010a
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
refs/heads/master
2021-01-01T20:05:44.559362
2014-04-30T17:50:06
2014-04-30T17:50:06
19,132,738
1
0
null
null
null
null
UTF-8
C++
false
false
120
hxx
#ifdef PEGASUS_OS_ZOS #ifndef __UNIX_PROCESSORCORE_PRIVATE_H #define __UNIX_PROCESSORCORE_PRIVATE_H #endif #endif
[ "brunolauze@msn.com" ]
brunolauze@msn.com
c46c2fc9aaeae1818d5bb31ac6ab98dfc585f9e5
7190717d597ae25d6352d62194389f84b518759e
/src/OIL/OilNamespaceDefinition.cpp
d16442263aeebc5a6fe374cea2d5f4f95ccdee87
[ "MIT" ]
permissive
OutOfTheVoid/OakC
59ce0447b7e1ac11c4674ff1d85d7b1d1b70109a
773934cc52bd4433f95c8c2de1ee231b8de4d0ad
refs/heads/master
2020-12-30T23:59:48.374911
2017-07-24T06:50:48
2017-07-24T06:50:48
80,559,306
2
0
null
null
null
null
UTF-8
C++
false
false
18,360
cpp
#include <OIL/OilNamespaceDefinition.h> #include <OIL/OilTypeDefinition.h> #include <OIL/OilFunctionDefinition.h> #include <OIL/OilBindingStatement.h> #include <OIL/OilConstStatement.h> #include <OIL/OilImplicitBindingInitialization.h> #include <OIL/OilTraitDefinition.h> #include <OIL/OilImplementBlock.h> #include <OIL/OilTypeAlias.h> #include <map> #include <iterator> OilNamespaceDefinition :: OilNamespaceDefinition ( const SourceRef & Ref, const std :: u32string & ID ): Parent ( NULL ), ID ( ID ), SubNamespaces (), TypeDefs (), FuncDefs (), TraitDefs (), Bindings (), ImplicitIntiailizationBody ( Ref ), Constants (), UnresImplBlocks (), Aliases (), Ref ( Ref ) { } OilNamespaceDefinition :: ~OilNamespaceDefinition () { std :: map <std :: u32string, OilNamespaceDefinition *> :: iterator FindIterator_NS = SubNamespaces.begin (); while ( FindIterator_NS != SubNamespaces.end () ) { delete FindIterator_NS -> second; FindIterator_NS ++; } std :: map <std :: u32string, OilTypeDefinition *> :: iterator FindIterator_SD = TypeDefs.begin (); while ( FindIterator_SD != TypeDefs.end () ) { delete FindIterator_SD -> second; FindIterator_SD ++; } std :: map <std :: u32string, OilFunctionDefinition *> :: iterator FindIterator_FD = FuncDefs.begin (); while ( FindIterator_FD != FuncDefs.end () ) { delete FindIterator_FD -> second; FindIterator_FD ++; } std :: map <std :: u32string, OilTraitDefinition *> :: iterator FindIterator_TD = TraitDefs.begin (); while ( FindIterator_TD != TraitDefs.end () ) { delete FindIterator_TD -> second; FindIterator_TD ++; } std :: map <std :: u32string, OilBindingStatement *> :: iterator FindIterator_B = Bindings.begin (); while ( FindIterator_B != Bindings.end () ) { delete FindIterator_B -> second; FindIterator_B ++; } std :: map <std :: u32string, OilConstStatement *> :: iterator FindIterator_C = Constants.begin (); while ( FindIterator_C != Constants.end () ) { delete FindIterator_C -> second; FindIterator_C ++; } std :: vector <OilImplementBlock *> :: iterator Iter_UIB = UnresImplBlocks.begin (); while ( Iter_UIB != UnresImplBlocks.end () ) { delete * Iter_UIB; Iter_UIB ++; } std :: map <std :: u32string, OilTypeAlias *> :: iterator FindIterator_A = Aliases.begin (); while ( FindIterator_A != Aliases.end () ) { delete FindIterator_A -> second; FindIterator_A ++; } } void OilNamespaceDefinition :: SearchName ( const std :: u32string & Name, NameSearchResult & Result ) { OilNamespaceDefinition * Namespace = FindNamespaceDefinition ( Name ); if ( Namespace != NULL ) { Result.Type = kNameSearchResultType_SubNamespace; Result.NamespaceDefinition = Namespace; return; } OilTypeDefinition * TypeDef = FindTypeDefinition ( Name ); if ( TypeDef != NULL ) { Result.Type= kNameSearchResultType_TypeDefinition; Result.TypeDefinition = TypeDef; return; } OilFunctionDefinition * FuncDef = FindFunctionDefinition ( Name ); if ( FuncDef != NULL ) { Result.Type = kNameSearchResultType_FunctionDefinition; Result.FunctionDefinition = FuncDef; return; } OilBindingStatement * Binding = FindBindingStatement ( Name ); if ( Binding != NULL ) { Result.Type = kNameSearchResultType_BindingStatement; Result.BindingStatement = Binding; return; } OilConstStatement * Const = FindConstStatement ( Name ); if ( Const != NULL ) { Result.Type = kNameSearchResultType_ConstStatement; Result.ConstStatement = Const; return; } OilTraitDefinition * TraitDef = FindTraitDefinition ( Name ); if ( TraitDef != NULL ) { Result.Type = kNameSearchResultType_TraitDefinition; Result.TraitDefinition = TraitDef; return; } OilTypeAlias * Alias = FindTypeAlias ( Name ); if ( Alias != NULL ) { Result.Type = kNameSearchResultType_TypeAlias; Result.Alias = Alias; return; } Result.Type = kNameSearchResultType_None; } void OilNamespaceDefinition :: SearchName ( const std :: u32string & Name, NameSearchResultConst & Result ) const { const OilNamespaceDefinition * Namespace = FindNamespaceDefinition ( Name ); if ( Namespace != NULL ) { Result.Type = kNameSearchResultType_SubNamespace; Result.NamespaceDefinition = Namespace; return; } const OilTypeDefinition * TypeDef = FindTypeDefinition ( Name ); if ( TypeDef != NULL ) { Result.Type = kNameSearchResultType_TypeDefinition; Result.TypeDefinition = TypeDef; return; } const OilFunctionDefinition * FuncDef = FindFunctionDefinition ( Name ); if ( FuncDef != NULL ) { Result.Type = kNameSearchResultType_FunctionDefinition; Result.FunctionDefinition = FuncDef; return; } const OilBindingStatement * Binding = FindBindingStatement ( Name ); if ( Binding != NULL ) { Result.Type = kNameSearchResultType_BindingStatement; Result.BindingStatement = Binding; return; } const OilConstStatement * Const = FindConstStatement ( Name ); if ( Const != NULL ) { Result.Type = kNameSearchResultType_ConstStatement; Result.ConstStatement = Const; return; } const OilTraitDefinition * TraitDef = FindTraitDefinition ( Name ); if ( TraitDef != NULL ) { Result.Type = kNameSearchResultType_TraitDefinition; Result.TraitDefinition = TraitDef; return; } Result.Type = kNameSearchResultType_None; } uint32_t OilNamespaceDefinition :: GetSubNamespaceDefinitionCount () const { return SubNamespaces.size (); } OilNamespaceDefinition * OilNamespaceDefinition :: GetNamespaceDefinition ( uint32_t Index ) { std :: map <std :: u32string, OilNamespaceDefinition *> :: iterator IndexIter = SubNamespaces.begin (); std :: advance ( IndexIter, Index ); if ( IndexIter == SubNamespaces.end () ) return NULL; return IndexIter -> second; } const OilNamespaceDefinition * OilNamespaceDefinition :: GetNamespaceDefinition ( uint32_t Index ) const { std :: map <std :: u32string, OilNamespaceDefinition *> :: const_iterator IndexIter = SubNamespaces.begin (); std :: advance ( IndexIter, Index ); if ( IndexIter == SubNamespaces.end () ) return NULL; return IndexIter -> second; } OilNamespaceDefinition * OilNamespaceDefinition :: FindOrCreateNamespaceDefinition ( const SourceRef & Ref, const std :: u32string & ID ) { std :: map <std :: u32string, OilNamespaceDefinition *> :: iterator FindIterator = SubNamespaces.find ( ID ); if ( FindIterator != SubNamespaces.end () ) return FindIterator -> second; OilNamespaceDefinition * NewNamespace = new OilNamespaceDefinition ( Ref, ID ); NewNamespace -> Parent = this; SubNamespaces [ ID ] = NewNamespace; return NewNamespace; } OilNamespaceDefinition * OilNamespaceDefinition :: FindNamespaceDefinition ( const std :: u32string & ID ) { std :: map <std :: u32string, OilNamespaceDefinition *> :: iterator FindIterator = SubNamespaces.find ( ID ); if ( FindIterator != SubNamespaces.end () ) return FindIterator -> second; return NULL; } const OilNamespaceDefinition * OilNamespaceDefinition :: FindNamespaceDefinition ( const std :: u32string & ID ) const { std :: map <std :: u32string, OilNamespaceDefinition *> :: const_iterator FindIterator = SubNamespaces.find ( ID ); if ( FindIterator != SubNamespaces.end () ) return FindIterator -> second; return NULL; } void OilNamespaceDefinition :: AddTypeDefinition ( OilTypeDefinition * TypeDef ) { TypeDefs [ TypeDef -> GetName () ] = TypeDef; TypeDef -> ParentNamespace = this; } uint32_t OilNamespaceDefinition :: GetTypeDefinitionCount () const { return TypeDefs.size (); } OilTypeDefinition * OilNamespaceDefinition :: GetTypeDefinition ( uint32_t Index ) { std :: map <std :: u32string, OilTypeDefinition *> :: iterator IndexIter = TypeDefs.begin (); std :: advance ( IndexIter, Index ); if ( IndexIter == TypeDefs.end () ) return NULL; return IndexIter -> second; } const OilTypeDefinition * OilNamespaceDefinition :: GetTypeDefinition ( uint32_t Index ) const { std :: map <std :: u32string, OilTypeDefinition *> :: const_iterator IndexIter = TypeDefs.begin (); std :: advance ( IndexIter, Index ); if ( IndexIter == TypeDefs.end () ) return NULL; return IndexIter -> second; } OilTypeDefinition * OilNamespaceDefinition :: FindTypeDefinition ( const std :: u32string & ID ) { std :: map <std :: u32string, OilTypeDefinition *> :: iterator FindIterator = TypeDefs.find ( ID ); if ( FindIterator != TypeDefs.end () ) return FindIterator -> second; return NULL; } const OilTypeDefinition * OilNamespaceDefinition :: FindTypeDefinition ( const std :: u32string & ID ) const { std :: map <std :: u32string, OilTypeDefinition *> :: const_iterator FindIterator = TypeDefs.find ( ID ); if ( FindIterator != TypeDefs.end () ) return FindIterator -> second; return NULL; } uint32_t OilNamespaceDefinition :: GetFunctionDefinitionCount () const { return FuncDefs.size (); } void OilNamespaceDefinition :: AddFunctionDefinition ( OilFunctionDefinition * FuncDef ) { FuncDefs [ FuncDef -> GetName () ] = FuncDef; } OilFunctionDefinition * OilNamespaceDefinition :: GetFunctionDefinition ( uint32_t Index ) { std :: map <std :: u32string, OilFunctionDefinition *> :: iterator IndexIter = FuncDefs.begin (); std :: advance ( IndexIter, Index ); if ( IndexIter == FuncDefs.end () ) return NULL; return IndexIter -> second; } const OilFunctionDefinition * OilNamespaceDefinition :: GetFunctionDefinition ( uint32_t Index ) const { std :: map <std :: u32string, OilFunctionDefinition *> :: const_iterator IndexIter = FuncDefs.begin (); std :: advance ( IndexIter, Index ); if ( IndexIter == FuncDefs.end () ) return NULL; return IndexIter -> second; } OilFunctionDefinition * OilNamespaceDefinition :: FindFunctionDefinition ( const std :: u32string & ID ) { std :: map <std :: u32string, OilFunctionDefinition *> :: iterator FindIterator = FuncDefs.find ( ID ); if ( FindIterator != FuncDefs.end () ) return FindIterator -> second; return NULL; } const OilFunctionDefinition * OilNamespaceDefinition :: FindFunctionDefinition ( const std :: u32string & ID ) const { std :: map <std :: u32string, OilFunctionDefinition *> :: const_iterator FindIterator = FuncDefs.find ( ID ); if ( FindIterator != FuncDefs.end () ) return FindIterator -> second; return NULL; } void OilNamespaceDefinition :: AddBindingStatement ( OilBindingStatement * BindingStatement ) { Bindings [ BindingStatement -> GetName () ] = BindingStatement; if ( BindingStatement -> HasInitializer () ) ImplicitIntiailizationBody.AddStatement ( new OilImplicitBindingInitialization ( BindingStatement -> GetSourceRef (), BindingStatement -> GetName () ) ); } uint32_t OilNamespaceDefinition :: GetBindingStatementCount () const { return Bindings.size (); } OilBindingStatement * OilNamespaceDefinition :: GetBindingStatement ( uint32_t Index ) { std :: map <std :: u32string, OilBindingStatement *> :: iterator IndexIter = Bindings.begin (); std :: advance ( IndexIter, Index ); if ( IndexIter == Bindings.end () ) return NULL; return IndexIter -> second; } const OilBindingStatement * OilNamespaceDefinition :: GetBindingStatement ( uint32_t Index ) const { std :: map <std :: u32string, OilBindingStatement *> :: const_iterator IndexIter = Bindings.begin (); std :: advance ( IndexIter, Index ); if ( IndexIter == Bindings.end () ) return NULL; return IndexIter -> second; } OilBindingStatement * OilNamespaceDefinition :: FindBindingStatement ( const std :: u32string & ID ) { std :: map <std :: u32string, OilBindingStatement *> :: iterator FindIterator = Bindings.find ( ID ); if ( FindIterator != Bindings.end () ) return FindIterator -> second; return NULL; } const OilBindingStatement * OilNamespaceDefinition :: FindBindingStatement ( const std :: u32string & ID ) const { std :: map <std :: u32string, OilBindingStatement *> :: const_iterator FindIterator = Bindings.find ( ID ); if ( FindIterator != Bindings.end () ) return FindIterator -> second; return NULL; } void OilNamespaceDefinition :: AddConstStatement ( OilConstStatement * ConstStatement ) { Constants [ ConstStatement -> GetName () ] = ConstStatement; } uint32_t OilNamespaceDefinition :: GetConstStatementCount () const { return Constants.size (); } OilConstStatement * OilNamespaceDefinition :: GetConstStatement ( uint32_t Index ) { std :: map <std :: u32string, OilConstStatement *> :: iterator IndexIter = Constants.begin (); std :: advance ( IndexIter, Index ); if ( IndexIter == Constants.end () ) return NULL; return IndexIter -> second; } const OilConstStatement * OilNamespaceDefinition :: GetConstStatement ( uint32_t Index ) const { std :: map <std :: u32string, OilConstStatement *> :: const_iterator IndexIter = Constants.begin (); std :: advance ( IndexIter, Index ); if ( IndexIter == Constants.end () ) return NULL; return IndexIter -> second; } OilConstStatement * OilNamespaceDefinition :: FindConstStatement ( const std :: u32string & ID ) { std :: map <std :: u32string, OilConstStatement *> :: iterator FindIterator = Constants.find ( ID ); if ( FindIterator != Constants.end () ) return FindIterator -> second; return NULL; } const OilConstStatement * OilNamespaceDefinition :: FindConstStatement ( const std :: u32string & ID ) const { std :: map <std :: u32string, OilConstStatement *> :: const_iterator FindIterator = Constants.find ( ID ); if ( FindIterator != Constants.end () ) return FindIterator -> second; return NULL; } uint32_t OilNamespaceDefinition :: GetTraitDefinitionCount () const { return TraitDefs.size (); } void OilNamespaceDefinition :: AddTraitDefinition ( OilTraitDefinition * TraitDef ) { TraitDefs [ TraitDef -> GetName () ] = TraitDef; TraitDef -> ParentNamespace = this; } OilTraitDefinition * OilNamespaceDefinition :: GetTraitDefinition ( uint32_t Index ) { std :: map <std :: u32string, OilTraitDefinition *> :: iterator IndexIter = TraitDefs.begin (); std :: advance ( IndexIter, Index ); if ( IndexIter == TraitDefs.end () ) return NULL; return IndexIter -> second; } const OilTraitDefinition * OilNamespaceDefinition :: GetTraitDefinition ( uint32_t Index ) const { std :: map <std :: u32string, OilTraitDefinition *> :: const_iterator IndexIter = TraitDefs.begin (); std :: advance ( IndexIter, Index ); if ( IndexIter == TraitDefs.end () ) return NULL; return IndexIter -> second; } OilTraitDefinition * OilNamespaceDefinition :: FindTraitDefinition ( const std :: u32string & ID ) { std :: map <std :: u32string, OilTraitDefinition *> :: iterator FindIterator = TraitDefs.find ( ID ); if ( FindIterator != TraitDefs.end () ) return FindIterator -> second; return NULL; } const OilTraitDefinition * OilNamespaceDefinition :: FindTraitDefinition ( const std :: u32string & ID ) const { std :: map <std :: u32string, OilTraitDefinition *> :: const_iterator FindIterator = TraitDefs.find ( ID ); if ( FindIterator != TraitDefs.end () ) return FindIterator -> second; return NULL; } OilStatementBody & OilNamespaceDefinition :: GetImplicitInitializationBody () { return ImplicitIntiailizationBody; } const OilStatementBody & OilNamespaceDefinition :: GetImplicitInitializationBody () const { return ImplicitIntiailizationBody; } const std :: u32string OilNamespaceDefinition :: GetID () const { return ID; } OilNamespaceDefinition * OilNamespaceDefinition :: GetParent () { return Parent; } const OilNamespaceDefinition * OilNamespaceDefinition :: GetParent () const { return Parent; } uint32_t OilNamespaceDefinition :: GetUnresolvedImplementBlockCount () const { return UnresImplBlocks.size (); } void OilNamespaceDefinition :: AddUnresolvedImplementBlock ( OilImplementBlock * Block ) { UnresImplBlocks.push_back ( Block ); } OilImplementBlock * OilNamespaceDefinition :: GetUnresolvedImplementBlock ( uint32_t Index ) { if ( Index >= UnresImplBlocks.size () ) return NULL; return UnresImplBlocks [ Index ]; } const OilImplementBlock * OilNamespaceDefinition :: GetUnresolvedImplementBlock ( uint32_t Index ) const { if ( Index >= UnresImplBlocks.size () ) return NULL; return UnresImplBlocks [ Index ]; } void OilNamespaceDefinition :: RemoveUnresolvedImplementBlock ( uint32_t Index ) { if ( Index >= UnresImplBlocks.size () ) return; UnresImplBlocks.erase ( UnresImplBlocks.begin () + Index ); } const SourceRef & OilNamespaceDefinition :: GetSourceRef () const { return Ref; } uint32_t OilNamespaceDefinition :: GetTypeAliasCount () const { return Aliases.size (); } void OilNamespaceDefinition :: AddTypeAlias ( OilTypeAlias * Alias ) { Aliases [ Alias -> GetName () ] = Alias; } OilTypeAlias * OilNamespaceDefinition :: GetTypeAlias ( uint32_t Index ) { std :: map <std :: u32string, OilTypeAlias *> :: iterator IndexIter = Aliases.begin (); std :: advance ( IndexIter, Index ); if ( IndexIter == Aliases.end () ) return NULL; return IndexIter -> second; } const OilTypeAlias * OilNamespaceDefinition :: GetTypeAlias ( uint32_t Index ) const { std :: map <std :: u32string, OilTypeAlias *> :: const_iterator IndexIter = Aliases.begin (); std :: advance ( IndexIter, Index ); if ( IndexIter == Aliases.end () ) return NULL; return IndexIter -> second; } OilTypeAlias * OilNamespaceDefinition :: FindTypeAlias ( const std :: u32string & Name ) { std :: map <std :: u32string, OilTypeAlias *> :: iterator FindIterator = Aliases.find ( Name ); if ( FindIterator != Aliases.end () ) return FindIterator -> second; return NULL; } const OilTypeAlias * OilNamespaceDefinition :: FindTypeAlias ( const std :: u32string & Name ) const { std :: map <std :: u32string, OilTypeAlias *> :: const_iterator FindIterator = Aliases.find ( Name ); if ( FindIterator != Aliases.end () ) return FindIterator -> second; return NULL; }
[ "liam.tab@gmail.com" ]
liam.tab@gmail.com
37bf1c20d53d02ec3ad4d9bc13e0a872d775450a
82c89621d2ffe5f3dc28589901c93d7c072dd4ec
/GeometryAndMesh/Mesh/Mesh.h
47a0d304c00c34c5175395202cb85f2ae1bd3ecf
[]
no_license
gezawa/LBO
b3aa74d5f0fe5fe703be7098285cae4b7776b506
dcb1342a0089e30a70dcdf2b44988057d50453d3
refs/heads/master
2020-03-07T22:25:57.704292
2015-12-18T13:09:26
2015-12-18T13:09:26
127,753,701
1
0
null
2018-04-02T12:32:49
2018-04-02T12:32:49
null
UTF-8
C++
false
false
5,463
h
#ifndef MESH_H #define MESH_H // The following ifdef block is the standard way of creating macros which make exporting // from a DLL simpler. All files within this DLL are compiled with the MESH_EXPORTS // symbol defined on the command line. This symbol should not be defined on any project // that uses this DLL. This way any other project whose source files include this file see // MESH_API functions as being imported from a DLL, whereas this DLL sees symbols // defined with this macro as being exported. #ifdef MESH_EXPORTS #define MESH_API __declspec(dllexport) #else #define MESH_API __declspec(dllimport) #endif #include "Model.h" #include <vector> #include <list> #include <string> #include <fstream> #include <sstream> #include <iostream> typedef unsigned int UINT; typedef std::list<Vector3D> _VECTORLIST; typedef std::list<UINT> _UINTLIST; #define MAX_VERTEX_PER_FACE 20 class MESH_API CVertex { public: Vector3D m_vPosition; // UINT* m_piEdge; //Ӹõ㷢İ,ҪݵĶ̬ _UINTLIST m_lEdgeList; //m_piEdgeʱ short m_nValence; //Ķ Vector3D m_vNormal; //㷨ɸ淨ƽõ Vector3D m_vRawNormal; //normals loaded from file bool m_bIsBoundary; //Ƿڱ߽ int m_nCutValence; UINT m_color; //ڱǿɫϢ; bool m_bValid; public: //constructions CVertex() { m_piEdge = NULL; m_nValence = 0; m_nCutValence = 0; m_bIsBoundary = false; m_color = 0; m_bValid = true; } CVertex(double x, double y, double z) { m_vPosition = Vector3D(x, y, z); m_piEdge = NULL; m_nValence = 0; m_bIsBoundary = false; m_nCutValence = 0; m_bValid = true; } CVertex(Vector3D v) { m_vPosition = v; m_piEdge = NULL; m_nValence = 0; m_bIsBoundary = false; m_nCutValence = 0; m_bValid = true; } virtual ~CVertex(); //operations CVertex& operator = (CVertex& v); }; class MESH_API CTexture { public: Vector2D m_vPosition; public: CTexture() { m_vPosition = Vector2D(0, 0); } CTexture(double x, double y) { m_vPosition = Vector2D(x, y); } CTexture(Vector2D v) { m_vPosition = v; } }; class MESH_API CEdge { public: UINT m_iVertex[2]; //ߵ˵㣬Vertex0>Vertex1 UINT m_iTwinEdge; //ñ߷෴һߣΪ-1ñΪ߽ UINT m_iNextEdge; //ʱ뷽һ UINT m_iFace; //ñ棬Ӧ UINT m_color; //ڱǿɫϢ; double m_length; //߳; bool m_bValid; public: bool m_bCut; int m_nCutTag; public: //constructions CEdge() { m_iVertex[0] = m_iVertex[1] = m_iTwinEdge = m_iNextEdge = m_iFace = -1; m_bCut = false; m_nCutTag = 0; m_color = 0; m_length = 0; m_bValid = true; } CEdge(UINT iV0, UINT iV1) { m_iVertex[0] = iV0; m_iVertex[1] = iV1; m_iTwinEdge = m_iNextEdge = m_iFace = -1; m_bCut = false; m_nCutTag = 0; m_bValid = true; } virtual ~CEdge(); //operations CEdge& operator = (const CEdge& e); }; class MESH_API CFace { public: short m_nType; // UINT* m_piVertex; //е UINT* m_piEdge; //б double* m_pdAngle; Vector3D m_vNormal; // Vector3D m_vMassPoint; // double m_dArea; // UINT m_color; //ڱǿɫϢ; bool m_bValid; public: //constructions CFace() { m_nType = 0; m_piVertex = m_piEdge = NULL; m_pdAngle = NULL; m_vNormal = Vector3D(0.0, 0.0, 1.0); m_dArea = 0.0; m_color = 0; m_bValid = true; } CFace(short s); virtual ~CFace(); //operations void Create(short s); CFace& operator = (const CFace& f); }; class MESH_API CMesh :public CModel { public: UINT m_nVertex; // CVertex* m_pVertex; // std::vector<CTexture> m_pTexture; CTexture maxTex; UINT m_nEdge; // CEdge* m_pEdge; //߱ UINT m_nFace; // CFace* m_pFace; // UINT m_nVertexCapacity; //ǰб UINT m_nEdgeCapacity; //ǰ߱ UINT m_nFaceCapacity; //ǰ Vector3D color; bool isVisible; unsigned m_nValidVertNum; unsigned m_nValidFaceNum; unsigned m_nValidEdgeNum; std::vector<Vector3D> isolatedPoints; double *m_pAngles; std::string filename; //ļ double scaleD; Vector3D origin; Vector3D bboxSize; //temp _UINTLIST m_lFocusEdge; _UINTLIST m_lFocusVertex; _UINTLIST m_lFocusFace; UINT m_iPickedFace; UINT m_iPickedEdge; UINT m_iPickedVertex; bool m_bClosed; public: CMesh() { m_nVertex = m_nEdge = m_nFace = 0; m_pVertex = NULL; m_pEdge = NULL; m_pFace = NULL; m_pAngles = NULL; m_iPickedFace = m_iPickedEdge = m_iPickedVertex = -1; isVisible = true; } CMesh(CMesh* pMesh); virtual ~CMesh(); public: bool Load(const char* sFileName); // load from file bool Save(const char* sFileName); // save to file MESH_API friend std::istream& operator >> (std::istream &input, CMesh &mesh); bool construct();// construct connectivity CMesh* clone(); //iEdgeڵ棨Ϊֻ߽һ棩iEdgeϸ֡ UINT split(UINT iEdge, double posPercent = -1.0); //flip edge whose two adjacent facws are in the same plane void flip(unsigned iEdge); void collapse(unsigned iEdge, Vector3D newPos); void add(Vector3D pos, unsigned iFace); //бߵı߳CEdge->m_length void calcAllEdgeLength(); private: void clear(); bool reConstruct();// construct connectivity from current mesh bool loadOBJ(const char* sFileName); bool loadOFF(const char* sFileName); bool loadM(const char* sFileName); bool loadFromSMF(std::list<Vector3D> &VertexList, std::list<UINT> &FaceList, std::vector<Vector3D> &normals); bool saveToSMF(const char* sFileName); //iķ void calFaceNormal(UINT i); //㶥iķķƽõ void calVertexNormal(UINT i); //ебٳȲʱռӱ void expandCapacity(); //ÿΧĽǶ void calcVertexAngle(); std::vector<std::string> splitString(std::string s, std::string sep); }; #endif //MESH_H
[ "xucx08@gmail.com" ]
xucx08@gmail.com
071b9192c7eb790fd820aa0643572fa98f043c99
1883b1dc60deeaa3c3950ebae4cdd49bccdd6699
/Class5/CurrencyExchange/main.cpp
bda8b2e6c0b9c8d49e1af666638f8db19b8635dd
[]
no_license
TaoTao-real/AlgorithmDesign
a31db8641d75110085ed7f201d758217dff4d3c0
13fbc2e059bbbd068e54aef850a409bc367eb4c2
refs/heads/main
2023-02-13T06:21:09.504389
2021-01-15T05:28:28
2021-01-15T05:28:28
306,902,321
0
0
null
null
null
null
UTF-8
C++
false
false
1,442
cpp
/* * @Author: your name * @Date: 2020-12-14 10:38:55 * @LastEditTime: 2020-12-14 11:53:11 * @LastEditors: Please set LastEditors * @Description: In User Settings Edit * @FilePath: /projects/AlgorithmDesign/Class5/CurrencyExchange/main.cpp */ #include <iostream> #include <algorithm> #include <vector> #include <queue> #include <stdlib.h> using namespace std; double n, m, s, v; int main(){ cin >> n >> m >> s >> v; vector<vector<vector<double>>> link(n+1); vector<double> value(n+1,0); for(int i = 0; i < m; ++i){ double A, B, RAB, CAB, RBA, CBA; cin >> A >> B >> RAB >> CAB >> RBA >> CBA; link[A].push_back(vector<double>{B, RAB, CAB}); link[B].push_back(vector<double>{A, RBA, CBA}); } deque<double> changed; value[s] = v; changed.push_back(s); for(int t = 0; t <= 2*n; ++t){ int count = changed.size(); while(count--){ double node = changed.front(); changed.pop_front(); for(vector<double> l : link[int(node)]){ double newvalue = (value[int(node)]-l[2])*l[1]; if(value[int(l[0])] < newvalue && newvalue>0){ value[int(l[0])] = newvalue; changed.push_back(l[0]); } } count = changed.size(); } } if(value[int(s)]>v) cout << "YES" << endl; else cout << "NO" << endl; return 0; }
[ "2510737554@qq.com" ]
2510737554@qq.com
b6799cae86255f0cf74dd4910a4b958a5a32aa83
d467b5dbd747f6034034a19d8978c9df1ea3d006
/algorithm/線形ソート/線形ソート/Object.cpp
8e0d86e0986b7f794651c916a75e3552dd21b1cf
[]
no_license
su-u/Class
289b0c7fb78d5559f7e75a5cd6dca8c6ab32bbaf
43ecfa37d9f74bd6f3178613d7bbaf62a0180ceb
refs/heads/master
2023-01-09T02:40:58.696279
2020-01-17T15:19:28
2020-01-17T15:19:28
135,131,365
0
0
null
2022-12-30T17:53:15
2018-05-28T08:20:45
C++
UTF-8
C++
false
false
151
cpp
#include "Object.h" Object::Object() { } Object::Object(int data) { this->data = data; } Object::~Object() { } void Object::View() { }
[ "aaaiiiuuu35@gmail.com" ]
aaaiiiuuu35@gmail.com
0b7524e2745b0056b2fb9b4ea24b8e3c6c51e45b
01bcef56ade123623725ca78d233ac8653a91ece
/materialsystem/stdshaders/solidenergy_dx9.cpp
d997d2a52e34cc23178eaab09164b15d81779b8a
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
SwagSoftware/Kisak-Strike
1085ba3c6003e622dac5ebc0c9424cb16ef58467
4c2fdc31432b4f5b911546c8c0d499a9cff68a85
refs/heads/master
2023-09-01T02:06:59.187775
2022-09-05T00:51:46
2022-09-05T00:51:46
266,676,410
921
123
null
2022-10-01T16:26:41
2020-05-25T03:41:35
C++
WINDOWS-1252
C++
false
false
7,346
cpp
//========= Copyright © Valve Corporation, All rights reserved. ============// // // Purpose: Shader for creating energy effects // //==========================================================================// #include "BaseVSShader.h" #include "solidenergy_dx9_helper.h" #include "cpp_shader_constant_register_map.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" DEFINE_FALLBACK_SHADER( SolidEnergy, SolidEnergy_dx9 ) BEGIN_VS_SHADER( SolidEnergy_dx9, "SolidEnergy" ) BEGIN_SHADER_PARAMS SHADER_PARAM( DETAIL1, SHADER_PARAM_TYPE_TEXTURE, "shader/BaseTexture", "detail map 1" ) SHADER_PARAM( DETAIL1SCALE, SHADER_PARAM_TYPE_FLOAT, "1.0", "scale detail1 as multiplier of base UVs" ) SHADER_PARAM( DETAIL1FRAME, SHADER_PARAM_TYPE_INTEGER, "0", "frame number for detail1" ) SHADER_PARAM( DETAIL1BLENDMODE, SHADER_PARAM_TYPE_INTEGER, "0", "detail 1 blend mode: 0=add, 1=mod2x, 2=mul, 3=alphamul (mul masked by base alpha)" ) SHADER_PARAM( DETAIL1BLENDFACTOR, SHADER_PARAM_TYPE_FLOAT, "1.0", "detail 1 blend factor" ) SHADER_PARAM( DETAIL1TEXTURETRANSFORM, SHADER_PARAM_TYPE_MATRIX, "center .5 .5 scale 1 1 rotate 0 translate 0 0", "detail1 texcoord transform" ) SHADER_PARAM( DETAIL2, SHADER_PARAM_TYPE_TEXTURE, "shader/BaseTexture", "detail map 2" ) SHADER_PARAM( DETAIL2SCALE, SHADER_PARAM_TYPE_FLOAT, "1.0", "scale detail1 as multiplier of base UVs" ) SHADER_PARAM( DETAIL2FRAME, SHADER_PARAM_TYPE_INTEGER, "0", "frame number for detail1" ) SHADER_PARAM( DETAIL2BLENDMODE, SHADER_PARAM_TYPE_INTEGER, "0", "detail 1 blend mode: 0=add, 1=mod2x, 2=mul, 3=detailmul (mul with detail1)" ) SHADER_PARAM( DETAIL2BLENDFACTOR, SHADER_PARAM_TYPE_FLOAT, "1.0", "detail 1 blend factor" ) SHADER_PARAM( DETAIL2TEXTURETRANSFORM, SHADER_PARAM_TYPE_MATRIX, "center .5 .5 scale 1 1 rotate 0 translate 0 0", "detail1 texcoord transform" ) SHADER_PARAM( TANGENTTOPACITYRANGES, SHADER_PARAM_TYPE_VEC4, "[1 0.9 0 0.6]", "enables view-based opacity falloff based on tangent t direction, great for cylinders, includes last term for scaling backface opacity") SHADER_PARAM( TANGENTSOPACITYRANGES, SHADER_PARAM_TYPE_VEC4, "[1 0.9 0 0.6]", "enables view-based opacity falloff based on tangent s direction, great for cylinders, includes last term for scaling backface opacity") SHADER_PARAM( FRESNELOPACITYRANGES, SHADER_PARAM_TYPE_VEC4, "[1 0.9 0 0.6]", "enables fresnel-based opacity falloff, includes last term for scaling backface opacity") SHADER_PARAM( NEEDSTANGENTT, SHADER_PARAM_TYPE_BOOL, "0", "don't need to set this explicitly, it gets set when tangenttopacityranges is defined" ) SHADER_PARAM( NEEDSTANGENTS, SHADER_PARAM_TYPE_BOOL, "0", "don't need to set this explicitly, it gets set when tangentSopacityranges is defined" ) SHADER_PARAM( NEEDSNORMALS, SHADER_PARAM_TYPE_BOOL, "0", "don't need to set this explicitly, it gets set when fresnelopacityranges is defined" ) SHADER_PARAM( DEPTHBLEND, SHADER_PARAM_TYPE_BOOL, "0", "enables depth-feathering" ) SHADER_PARAM( DEPTHBLENDSCALE, SHADER_PARAM_TYPE_FLOAT, "50.0", "Amplify or reduce DEPTHBLEND fading. Lower values make harder edges." ) SHADER_PARAM( FLOWMAP, SHADER_PARAM_TYPE_TEXTURE, "", "flowmap" ) SHADER_PARAM( FLOWMAPFRAME, SHADER_PARAM_TYPE_INTEGER, "0", "frame number for $flowmap" ) SHADER_PARAM( FLOWMAPSCROLLRATE, SHADER_PARAM_TYPE_VEC2, "[0 0", "2D rate to scroll $flowmap" ) SHADER_PARAM( FLOW_NOISE_TEXTURE, SHADER_PARAM_TYPE_TEXTURE, "", "flow noise texture" ) SHADER_PARAM( TIME, SHADER_PARAM_TYPE_FLOAT, "", "" ) SHADER_PARAM( FLOW_WORLDUVSCALE, SHADER_PARAM_TYPE_FLOAT, "", "" ) SHADER_PARAM( FLOW_NORMALUVSCALE, SHADER_PARAM_TYPE_FLOAT, "", "" ) SHADER_PARAM( FLOW_TIMEINTERVALINSECONDS, SHADER_PARAM_TYPE_FLOAT, "", "" ) SHADER_PARAM( FLOW_UVSCROLLDISTANCE, SHADER_PARAM_TYPE_FLOAT, "", "" ) SHADER_PARAM( FLOW_NOISE_SCALE, SHADER_PARAM_TYPE_FLOAT, "", "" ) SHADER_PARAM( FLOW_LERPEXP, SHADER_PARAM_TYPE_FLOAT, "", "" ) SHADER_PARAM( FLOWBOUNDS, SHADER_PARAM_TYPE_TEXTURE, "", "" ) SHADER_PARAM( POWERUP, SHADER_PARAM_TYPE_FLOAT, "", "" ) SHADER_PARAM( FLOW_COLOR_INTENSITY, SHADER_PARAM_TYPE_FLOAT, "", "" ) SHADER_PARAM( FLOW_COLOR, SHADER_PARAM_TYPE_VEC3, "", "" ) SHADER_PARAM( FLOW_VORTEX_COLOR, SHADER_PARAM_TYPE_VEC3, "", "" ) SHADER_PARAM( FLOW_VORTEX_SIZE, SHADER_PARAM_TYPE_FLOAT, "", "" ) SHADER_PARAM( FLOW_VORTEX1, SHADER_PARAM_TYPE_BOOL, "", "" ) SHADER_PARAM( FLOW_VORTEX_POS1, SHADER_PARAM_TYPE_VEC3, "", "" ) SHADER_PARAM( FLOW_VORTEX2, SHADER_PARAM_TYPE_BOOL, "", "" ) SHADER_PARAM( FLOW_VORTEX_POS2, SHADER_PARAM_TYPE_VEC3, "", "" ) SHADER_PARAM( FLOW_CHEAP, SHADER_PARAM_TYPE_BOOL, "", "" ) SHADER_PARAM( MODELFORMAT, SHADER_PARAM_TYPE_BOOL, "", "" ) SHADER_PARAM( OUTPUTINTENSITY, SHADER_PARAM_TYPE_FLOAT, "1.0", "" ); END_SHADER_PARAMS void SetupVarsSolidEnergy( SolidEnergyVars_t &info ) { info.m_nBaseTexture = BASETEXTURE; info.m_nBaseTextureTransform = BASETEXTURETRANSFORM; info.m_nDetail1Texture = DETAIL1; info.m_nDetail1Scale = DETAIL1SCALE; info.m_nDetail1Frame = DETAIL1FRAME; info.m_nDetail1BlendMode = DETAIL1BLENDMODE; info.m_nDetail1TextureTransform = DETAIL1TEXTURETRANSFORM; info.m_nDetail2Texture = DETAIL2; info.m_nDetail2Scale = DETAIL2SCALE; info.m_nDetail2Frame = DETAIL2FRAME; info.m_nDetail2BlendMode = DETAIL2BLENDMODE; info.m_nDetail2TextureTransform = DETAIL2TEXTURETRANSFORM; info.m_nTangentTOpacityRanges = TANGENTTOPACITYRANGES; info.m_nTangentSOpacityRanges = TANGENTSOPACITYRANGES; info.m_nFresnelOpacityRanges = FRESNELOPACITYRANGES; info.m_nNeedsTangentT = NEEDSTANGENTT; info.m_nNeedsTangentS = NEEDSTANGENTS; info.m_nNeedsNormals = NEEDSNORMALS; info.m_nDepthBlend = DEPTHBLEND; info.m_nDepthBlendScale = DEPTHBLENDSCALE; info.m_nFlowMap = FLOWMAP; info.m_nFlowMapFrame = FLOWMAPFRAME; info.m_nFlowMapScrollRate = FLOWMAPSCROLLRATE; info.m_nFlowNoiseTexture = FLOW_NOISE_TEXTURE; info.m_nTime = TIME; info.m_nFlowWorldUVScale = FLOW_WORLDUVSCALE; info.m_nFlowNormalUVScale = FLOW_NORMALUVSCALE; info.m_nFlowTimeIntervalInSeconds = FLOW_TIMEINTERVALINSECONDS; info.m_nFlowUVScrollDistance = FLOW_UVSCROLLDISTANCE; info.m_nFlowNoiseScale = FLOW_NOISE_SCALE; info.m_nFlowLerpExp = FLOW_LERPEXP; info.m_nFlowBoundsTexture = FLOWBOUNDS; info.m_nPowerUp = POWERUP; info.m_nFlowColorIntensity = FLOW_COLOR_INTENSITY; info.m_nFlowColor = FLOW_COLOR; info.m_nFlowVortexColor = FLOW_VORTEX_COLOR; info.m_nFlowVortexSize = FLOW_VORTEX_SIZE; info.m_nFlowVortex1 = FLOW_VORTEX1; info.m_nFlowVortexPos1 = FLOW_VORTEX_POS1; info.m_nFlowVortex2 = FLOW_VORTEX2; info.m_nFlowVortexPos2 = FLOW_VORTEX_POS2; info.m_nFlowCheap = FLOW_CHEAP; info.m_nModel = MODELFORMAT; info.m_nOutputIntensity = OUTPUTINTENSITY; } SHADER_INIT_PARAMS() { SolidEnergyVars_t info; SetupVarsSolidEnergy( info ); InitParamsSolidEnergy( this, params, pMaterialName, info ); } SHADER_FALLBACK { return 0; } SHADER_INIT { SolidEnergyVars_t info; SetupVarsSolidEnergy( info ); InitSolidEnergy( this, params, info ); } SHADER_DRAW { SolidEnergyVars_t info; SetupVarsSolidEnergy( info ); DrawSolidEnergy( this, params, pShaderAPI, pShaderShadow, info, vertexCompression, pContextDataPtr ); } END_SHADER
[ "bbchallenger100@gmail.com" ]
bbchallenger100@gmail.com
2338d782ff7956f36a292b3e83e0fd517af5e843
74a63da16e138254ff62fe5e198e280b25ba5337
/ATM2.cpp
48c7205abbc68a929eafc11bf6ed0d89d9e3f0ab
[]
no_license
aswathikb/Code_Chef_beginner
904d14f88443fd5356a7709eb2d8e699822f3e53
cae7bbb6eabcc9fb892dade0d5c2a14df94bba5f
refs/heads/master
2021-04-06T08:03:34.994625
2019-02-01T20:53:01
2019-02-01T20:53:01
125,049,975
0
0
null
null
null
null
UTF-8
C++
false
false
442
cpp
#include <bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while(t--){ int n,k; cin >> n >> k; int A[n]; for(int i = 0; i < n; i++){ cin >> A[i]; if(A[i] <= k){ cout << "1"; k = k - A[i]; } else cout << "0"; } cout << "\n"; } // your code goes here return 0; }
[ "aswathikb2018@gmail.com" ]
aswathikb2018@gmail.com
c1b2f4d385d6572eff5476c47551a833e2ba48eb
5f3b42e264e4d918a4e18b6995efbc93d5f58802
/asyn_client/asyn_tcp_client.h
8eabe822e4cc85c723c792a34b44ec73dde40ecc
[]
no_license
flames85/boost_demo
60093103227e9607193307888465869a682b9f55
edbf2a40ae0cd94cee6fcff55fd5773e9384e307
refs/heads/master
2021-01-17T14:40:15.583794
2016-08-02T06:08:51
2016-08-02T06:08:51
45,377,661
1
0
null
null
null
null
UTF-8
C++
false
false
1,466
h
// // Created by Shao.Admin on 16/7/28. // #ifndef ASYN_TCP_CLIENT_H #define ASYN_TCP_CLIENT_H #include <iostream> #include <string> #include <boost/thread.hpp> #include "boost_util.h" class asyn_tcp_client : public boost::enable_shared_from_this<asyn_tcp_client> , public boost::noncopyable { public: // 连接函数 void start(); // 停止 void stop(); // 判断是否已连接 bool connected(); // 写入 void do_write(const std::string & msg); // 子类必须实现的回调函数 virtual void did_connect_to_host(const ip::tcp::endpoint &ep) = 0; virtual void did_disconnect(const ip::tcp::endpoint &ep) = 0; virtual void did_read_data(const char* data, size_t len) = 0; virtual void did_write_bytes(size_t bytes) = 0; protected: // 隐藏的构造函数 asyn_tcp_client(shared_socket s_socket, const ip::tcp::endpoint &ep) ; // 隐藏的析构函数 virtual ~asyn_tcp_client(); // 读取 void do_read(); private: // 连接完毕后回调 void on_connect(const error_code & err); // 读取完毕后回调 void on_read(const error_code & err, size_t bytes); // 写入完毕后回调 void on_write(const error_code & err, size_t bytes); private: shared_socket s_socket_; ip::tcp::endpoint ep_; enum { max_msg = 1024*10 }; char read_buffer_[max_msg]; }; #endif //ASYN_TCP_CLIENT_H
[ "flames85@163.com" ]
flames85@163.com
cf5d94f3bfd498aa9e2d902cf5bf6938b994971e
2198e2ed0922b4dd747cd9d60354d169c2597f5b
/src/session/listen_session.h
01573d1f3ebc1c3ec1f3e3028234cf52cca2e842
[]
no_license
jingcodedream/server
0316ae09c626b2117cdb8182d5baf12a146a4caf
efdc66ed3f46f61fecbd2bab59779dea37adacfe
refs/heads/master
2021-01-19T00:59:02.675977
2016-07-15T12:11:54
2016-07-15T12:11:54
60,837,746
0
0
null
null
null
null
UTF-8
C++
false
false
1,432
h
/* * listen_session.h * * Created on: 2016年6月7日 * Author: joe */ #ifndef SRC_CORE_SESSION_LISTEN_SESSION_H_ #define SRC_CORE_SESSION_LISTEN_SESSION_H_ #include "src/session/session_interface.h" #include "src/io_server/io_server_interface.h" #include "src/timer/timer_interface.h" #include "logger.h" #include <string> class ListenSession : public SessionInterface { public: ListenSession(const std::string &listen_ipv4, uint16_t listen_port, uint32_t listen_max_connect, std::shared_ptr<IOServerInterface> io_server_, std::shared_ptr<TimerInterface> timer) : fd_(-1), listen_ipv4_(listen_ipv4), listen_port_(listen_port), listen_max_connect_(listen_max_connect), io_server_(io_server_), io_events_(IOEventsEmpty), timer_(timer) {} ~ListenSession() {} int32_t Init(); IOStatus OnRead(); int32_t GetFd() const {return fd_;} IOEvents GetIOEvents() const {return io_events_;}; void SetIOEvents(IOEvents io_events) {io_events_ = io_events;}; IOStatus OnWrite() {return IOStatusError;} IOStatus OnError() {return IOStatusError;} private: int32_t fd_; std::string listen_ipv4_; uint32_t listen_port_; uint32_t listen_max_connect_; std::shared_ptr<IOServerInterface> io_server_; std::shared_ptr<TimerInterface> timer_; IOEvents io_events_; DECL_LOGGER(logger_); }; #endif /* SRC_CORE_SESSION_LISTEN_SESSION_H_ */
[ "767302105@qq.com" ]
767302105@qq.com
637e0bde7bfc8c98fcd2e46173ff22f1e6d66ef2
56c7fdcfdfb5e69bb724ea60f4610779af8b8403
/src/realtime_pool.cpp
153fe9ba3473cac1a26f20549f2bc6afe8a95f7a
[ "MIT" ]
permissive
BrettDong/UNCALLED
19eae39a51109d64153fbabbac8d1483b57b2baa
ad854b8998e455be8934d9fd389a8eaf34f06477
refs/heads/master
2022-12-17T17:21:10.990424
2020-07-13T15:59:23
2020-07-13T15:59:23
272,932,196
0
0
MIT
2020-06-17T09:25:46
2020-06-17T09:25:46
null
UTF-8
C++
false
false
8,263
cpp
/* MIT License * * Copyright (c) 2018 Sam Kovaka <skovaka@gmail.com> * * 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 <thread> #include <chrono> #include <stdlib.h> #include <time.h> #include "realtime_pool.hpp" #include "mapper.hpp" RealtimePool::RealtimePool(Conf &conf) { conf.load_index_params(); Mapper::model = PoreModel<KLEN>(conf.kmer_model, true); Mapper::fmi.load_index(conf.bwa_prefix); for (u16 t = 0; t < conf.threads; t++) { threads_.emplace_back(mappers_); } mappers_.resize(conf.num_channels); channel_active_.resize(conf.num_channels, false); chunk_buffer_.resize(conf.num_channels); buffer_queue_.reserve(conf.num_channels); //for (u16 i = 0; i < conf.num_channels; i++) { // mappers_.push_back(Mapper()); // channel_active_.push_back(false); //} for (u16 t = 0; t < conf.threads; t++) { threads_[t].start(); } srand(time(NULL)); } void RealtimePool::buffer_chunk(Chunk &c) { u16 ch = c.get_channel_idx(); if (chunk_buffer_[ch].empty()) { buffer_queue_.push_back(ch); } else { //TODO: handle backlog (probably reset paths?) chunk_buffer_[ch].clear(); } chunk_buffer_[ch].swap(c); } //Add chunk to master buffer bool RealtimePool::add_chunk(Chunk &c) { u16 ch = c.get_channel_idx(); //Check if previous read is still aligning //If so, tell thread to reset, store chunk in pool buffer if (mappers_[ch].prev_unfinished(c.get_number())) { mappers_[ch].request_reset(); buffer_chunk(c); return true; //Previous alignment finished but mapper hasn't reset //Happens if update hasn't been called yet } else if (mappers_[ch].finished()) { if (mappers_[ch].get_read().number_ != c.get_number()){ buffer_chunk(c); } return true; //Mapper inactive - need to reset graph and assign to thread } else if (mappers_[ch].get_state() == Mapper::State::INACTIVE) { mappers_[ch].new_read(c); active_queue_.push_back(ch); return true; } else if (mappers_[ch].add_chunk(c)) { return true; } return false; } std::vector<MapResult> RealtimePool::update() { std::vector< u16 > read_counts(threads_.size()); u16 active_count = 0; std::vector<MapResult> ret; //Get alignment outputs for (u16 t = 0; t < threads_.size(); t++) { if (!threads_[t].out_chs_.empty()) { //Store and empty thread output buffer threads_[t].out_mtx_.lock(); out_chs_.swap(threads_[t].out_chs_); threads_[t].out_mtx_.unlock(); //Loop over alignments for (auto ch : out_chs_) { ReadBuffer &r = mappers_[ch].get_read(); ret.emplace_back(r.get_channel(), r.number_, r.loc_); mappers_[ch].deactivate(); } out_chs_.clear(); } //Count reads aligning in each thread read_counts[t] = threads_[t].read_count(); active_count += read_counts[t]; } if (time_.get() >= 1000 && active_count > 0) { time_.reset(); std::cout << "#thread_reads"; for (u16 c : read_counts) std::cout << "\t" << c; std::cout << "\n"; std::cout.flush(); } for (u16 i = buffer_queue_.size()-1; i < buffer_queue_.size(); i--) { u16 ch = buffer_queue_[i];//TODO: store chunks in queue Chunk &c = chunk_buffer_[ch]; bool added; if (mappers_[ch].get_state() == Mapper::State::INACTIVE) { mappers_[ch].new_read(c); active_queue_.push_back(ch); added = true; } else { added = mappers_[ch].add_chunk(c); } if (added) { if (i != buffer_queue_.size()-1) { buffer_queue_[i] = buffer_queue_.back(); } buffer_queue_.pop_back(); } } //Estimate how much to fill each thread u16 target = active_queue_.size() + active_count, per_thread = target / threads_.size() + (target % threads_.size() > 0); u16 r = (u16) rand(); for (u16 i = 0; i < threads_.size(); i++) { u16 t = (r+i) % threads_.size(); //If thread not full if (read_counts[t] < per_thread) { //Fill thread till full //TODO: compute number exactly, only lock while adding threads_[t].in_mtx_.lock(); while (!active_queue_.empty() && read_counts[t] < per_thread) { u16 ch = active_queue_.back(); active_queue_.pop_back(); threads_[t].in_chs_.push_back(ch); read_counts[t]++; } threads_[t].in_mtx_.unlock(); } } return ret; } bool RealtimePool::all_finished() { if (!buffer_queue_.empty()) return false; for (MapperThread &t : threads_) { if (t.read_count() > 0 || !t.out_chs_.empty()) return false; } return true; } void RealtimePool::stop_all() { for (MapperThread &t : threads_) { t.running_ = false; t.thread_.join(); } } u16 RealtimePool::MapperThread::num_threads = 0; RealtimePool::MapperThread::MapperThread(std::vector<Mapper> &mappers) : tid_(num_threads++), mappers_(mappers), running_(true) {} RealtimePool::MapperThread::MapperThread(MapperThread &&mt) : tid_(mt.tid_), mappers_(mt.mappers_), running_(mt.running_), thread_(std::move(mt.thread_)) {} void RealtimePool::MapperThread::start() { thread_ = std::thread(&RealtimePool::MapperThread::run, this); } u16 RealtimePool::MapperThread::read_count() const { return in_chs_.size() + active_chs_.size(); } void RealtimePool::MapperThread::run() { std::string fast5_id; std::vector<float> fast5_signal; std::vector<u16> finished; while (running_) { if (read_count() == 0) { std::this_thread::sleep_for(std::chrono::milliseconds(10)); continue; } //Read inputs (pop, lock, and swap it) if (!in_chs_.empty()) { in_mtx_.lock(); in_tmp_.swap(in_chs_); in_mtx_.unlock(); for (auto ch : in_tmp_) { active_chs_.push_back(ch); } in_tmp_.clear(); //(pop) } //Map chunks for (u16 i = 0; i < active_chs_.size() && running_; i++) { u16 ch = active_chs_[i]; mappers_[ch].process_chunk(); if (mappers_[ch].map_chunk()) { out_tmp_.push_back(i); } } //Add finished to output if (!out_tmp_.empty()) { out_mtx_.lock(); for (auto i : out_tmp_) out_chs_.push_back(active_chs_[i]); out_mtx_.unlock(); std::sort(out_tmp_.begin(), out_tmp_.end(), [](u32 a, u32 b) { return a > b; }); for (auto i : out_tmp_) { active_chs_[i] = active_chs_.back(); active_chs_.pop_back(); } out_tmp_.clear(); } } }
[ "skovaka@gmail.com" ]
skovaka@gmail.com
8a8301180ee3a3e0c5ebc74e7d8f6d09248b7437
ed260a07bacf0b7efd276831c57031b62e9dde9f
/utilities/analyzers/throughput/throughput_analyzer.cpp
ef88dd2cbd9bf47310c6b978aed9608a823a7248
[]
no_license
chunhui-pang/fade
12e124267f90330a0d89aa57a2910ca49b4ef292
7e228150d49c54e7890f09c5777f2ccd3904200c
refs/heads/master
2021-08-23T04:43:24.329186
2017-12-03T10:39:15
2017-12-03T10:39:15
108,712,033
2
1
null
null
null
null
UTF-8
C++
false
false
2,439
cpp
/** * utility to parse mininet output: throughput analysis */ #include <iostream> #include <fstream> #include <common/util.h> #include <unistd.h> #include <regex> #include <cstdlib> #include <vector> #include <string> using namespace std; bool parse_options(int argc, char *argv[], std::vector<std::string>& log_dirs); double parse_log_directory(const std::string& dir); int main(int argc, char *argv[]) { std::vector<std::string> log_dirs; if(!parse_options(argc, argv, log_dirs)) return false; double sum_throughput = 0; for(std::vector<std::string>::iterator it = log_dirs.begin(); it != log_dirs.end(); it++) sum_throughput += parse_log_directory(*it); sum_throughput /= log_dirs.size(); std::cout << sum_throughput << std::endl; return 0; } double parse_log_directory(const std::string& dir) { const static std::regex THROUGHPUT_MSG(".*iperf\\Wbetween.*\\['([\\d.]+)\\W(G|M|K).*?([\\d.]+)\\W(G|M|K).*\\]"); std::string mininet_log = get_mininet_log(dir); std::ifstream is(mininet_log); std::string line; std::smatch sm; double sum_throughput = 0; int size = 0; while(getline(is, line)) { if(std::regex_match(line, sm, THROUGHPUT_MSG)) { double throughput = std::atof(sm[1].str().c_str()); char metric = sm[2].str().at(0); if('M' == metric) throughput /= 1000; if('K' == metric) throughput /= (1000*1000); sum_throughput += throughput; throughput = std::atof(sm[3].str().c_str()); metric = sm[4].str().at(0); if('M' == metric) throughput /= 1000; if('K' == metric) throughput /= (1000*1000); sum_throughput += throughput; size += 2; } } if (size == 0) { std::cerr << "cannot find throughput message in the mininet file '" << mininet_log << "'" << std::endl; return -1.0f; } sum_throughput /= size; return sum_throughput; } bool parse_options(int argc, char *argv[], std::vector<std::string>& log_dirs) { char command; std::string tmp; while((command = getopt(argc, argv, "d:")) != -1) { switch(command) { case 'd': tmp = optarg; if(!is_valid_log_directory(tmp)) return false; log_dirs.push_back(tmp); break; case '?': default: return false; } } while(optind < argc) { tmp = argv[optind++]; if(!is_valid_log_directory(tmp)) return false; log_dirs.push_back(tmp); } if(log_dirs.size() == 0) { std::cerr << "At least one log directory should be specified!" << std::endl; return false; } return true; }
[ "pchui2012@gmail.com" ]
pchui2012@gmail.com
088ee308d5f32ba1f0d7680f3f8add2c4a6464df
df33f0a05f0b1b1e27734a7890f0844a557723a4
/Dependencies/OGRE/include/OGRE/RTShaderSystem/OgreShaderExDualQuaternionSkinning.h
e708f50d73e6a1db066ceebc831e11343a4e13bf
[]
no_license
GeometryHub/KinectV2
8c983f2ce5986a00a0888b6367abed7b991e9449
7970f849c907277a1e87f85656be582264b9d71b
refs/heads/master
2021-05-13T12:37:01.560467
2020-10-04T08:13:11
2020-10-04T08:13:11
116,677,603
6
0
null
null
null
null
UTF-8
C++
false
false
4,900
h
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org Copyright (c) 2000-2014 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #ifndef _ShaderExDualQuaternionSkinning_ #define _ShaderExDualQuaternionSkinning_ #include "OgreShaderPrerequisites.h" #ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS #include "OgreShaderExHardwareSkinningTechnique.h" namespace Ogre { namespace RTShader { /** \addtogroup Optional * @{ */ /** \addtogroup RTShader * @{ */ #define SGX_LIB_DUAL_QUATERNION "SGXLib_DualQuaternion" #define SGX_FUNC_BLEND_WEIGHT "SGX_BlendWeight" #define SGX_FUNC_ANTIPODALITY_ADJUSTMENT "SGX_AntipodalityAdjustment" #define SGX_FUNC_CALCULATE_BLEND_POSITION "SGX_CalculateBlendPosition" #define SGX_FUNC_CALCULATE_BLEND_NORMAL "SGX_CalculateBlendNormal" #define SGX_FUNC_NORMALIZE_DUAL_QUATERNION "SGX_NormalizeDualQuaternion" #define SGX_FUNC_ADJOINT_TRANSPOSE_MATRIX "SGX_AdjointTransposeMatrix" #define SGX_FUNC_BUILD_DUAL_QUATERNION_MATRIX "SGX_BuildDualQuaternionMatrix" /** Implement a sub render state which performs dual quaternion hardware skinning. This sub render state uses bone matrices converted to dual quaternions and adds calculations to transform the points and normals using their associated dual quaternions. */ class _OgreRTSSExport DualQuaternionSkinning : public HardwareSkinningTechnique { // Interface. public: /** Class default constructor */ DualQuaternionSkinning(); /** @see SubRenderState::resolveParameters. */ virtual bool resolveParameters(ProgramSet* programSet); /** @see SubRenderState::resolveDependencies. */ virtual bool resolveDependencies(ProgramSet* programSet); /** @see SubRenderState::addFunctionInvocations. */ virtual bool addFunctionInvocations(ProgramSet* programSet); // Protected methods protected: /** Adds functions to calculate position data in world, object and projective space */ void addPositionCalculations(Function* vsMain, int& funcCounter); /** Adjusts the sign of a dual quaternion depending on its orientation to the root dual quaternion */ void adjustForCorrectAntipodality(Function* vsMain, int index, int& funcCounter, const ParameterPtr& pTempWorldMatrix); /** Adds the weight of a given position for a given index @param pPositionTempParameter Requires a temp parameter with a matrix the same size of pPositionRelatedParam */ void addIndexedPositionWeight(Function* vsMain, int index, ParameterPtr& pWorldMatrix, ParameterPtr& pPositionTempParameter, ParameterPtr& pPositionRelatedOutputParam, int& funcCounter); /** Adds the calculations for calculating a normal related element */ void addNormalRelatedCalculations(Function* vsMain, ParameterPtr& pNormalIn, ParameterPtr& pNormalRelatedParam, ParameterPtr& pNormalWorldRelatedParam, int& funcCounter); protected: UniformParameterPtr mParamInScaleShearMatrices; ParameterPtr mParamLocalBlendPosition; ParameterPtr mParamBlendS; ParameterPtr mParamBlendDQ; ParameterPtr mParamInitialDQ; ParameterPtr mParamTempWorldMatrix; ParameterPtr mParamTempFloat2x4; ParameterPtr mParamTempFloat3x3; ParameterPtr mParamTempFloat3x4; ParameterPtr mParamIndex1; ParameterPtr mParamIndex2; }; } // namespace RTShader } // namespace Ogre #endif // RTSHADER_SYSTEM_BUILD_EXT_SHADERS #endif // _ShaderExDualQuaternionSkinning_
[ "geometryhub@qq.com" ]
geometryhub@qq.com
53a259f20c54f037bc72ac304ad55ca458a06e93
73120b54a6a7a08e3a7140fb53a0b018c38b499d
/hphp/util/vixl/test/test-utils-a64.cc
be5791f9a651a1e1b38fd4cd29ac393591d39512
[ "Zend-2.0", "LicenseRef-scancode-unknown-license-reference", "PHP-3.01" ]
permissive
mrotec/hiphop-php
58705a281ff6759cf1acd9735a312c486a18a594
132241f5e5b7c5f1873dbec54c5bc691c6e75f28
refs/heads/master
2021-01-18T10:10:43.051362
2013-07-31T19:11:55
2013-07-31T19:25:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,213
cc
// Copyright 2013, ARM Limited // 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 ARM Limited 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 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 "test-utils-a64.h" #include <math.h> // Needed for isnan(). #include "hphp/util/vixl/a64/macro-assembler-a64.h" #include "hphp/util/vixl/a64/simulator-a64.h" #include "hphp/util/vixl/a64/disasm-a64.h" #include "hphp/util/vixl/a64/cpu-a64.h" #define __ masm-> namespace vixl { bool Equal32(uint32_t expected, const RegisterDump*, uint32_t result) { if (result != expected) { printf("Expected 0x%08" PRIx32 "\t Found 0x%08" PRIx32 "\n", expected, result); } return expected == result; } bool Equal64(uint64_t expected, const RegisterDump*, uint64_t result) { if (result != expected) { printf("Expected 0x%016" PRIx64 "\t Found 0x%016" PRIx64 "\n", expected, result); } return expected == result; } bool EqualFP32(float expected, const RegisterDump*, float result) { if (result != expected) { printf("Expected %.20f\t Found %.20f\n", expected, result); } return expected == result; } bool EqualFP64(double expected, const RegisterDump*, double result) { if (result != expected) { printf("Expected %.20f\t Found %.20f\n", expected, result); } return expected == result; } bool Equal32(uint32_t expected, const RegisterDump* core, const Register& reg) { ASSERT(reg.Is32Bits()); // Retrieve the corresponding X register so we can check that the upper part // was properly cleared. int64_t result_x = core->xreg(reg.code()); if ((result_x & 0xffffffff00000000L) != 0) { printf("Expected 0x%08" PRIx32 "\t Found 0x%016" PRIx64 "\n", expected, result_x); return false; } uint32_t result_w = core->wreg(reg.code()); return Equal32(expected, core, result_w); } bool Equal64(uint64_t expected, const RegisterDump* core, const Register& reg) { ASSERT(reg.Is64Bits()); uint64_t result = core->xreg(reg.code()); return Equal64(expected, core, result); } bool EqualFP32(float expected, const RegisterDump* core, const FPRegister& fpreg) { ASSERT(fpreg.Is32Bits()); // Retrieve the corresponding D register so we can check that the upper part // was properly cleared. uint64_t result_64 = core->dreg_bits(fpreg.code()); if ((result_64 & 0xffffffff00000000L) != 0) { printf("Expected 0x%08" PRIx32 " (%f)\t Found 0x%016" PRIx64 "\n", float_to_rawbits(expected), expected, result_64); return false; } if (expected == 0.0) { return Equal32(float_to_rawbits(expected), core, core->sreg_bits(fpreg.code())); } else if (isnan(expected)) { return isnan(core->sreg(fpreg.code())); } else { float result = core->sreg(fpreg.code()); return EqualFP32(expected, core, result); } } bool EqualFP64(double expected, const RegisterDump* core, const FPRegister& fpreg) { ASSERT(fpreg.Is64Bits()); if (expected == 0.0) { return Equal64(double_to_rawbits(expected), core, core->dreg_bits(fpreg.code())); } else if (isnan(expected)) { return isnan(core->dreg(fpreg.code())); } else { double result = core->dreg(fpreg.code()); return EqualFP64(expected, core, result); } } bool Equal64(const Register& reg0, const RegisterDump* core, const Register& reg1) { ASSERT(reg0.Is64Bits() && reg1.Is64Bits()); int64_t expected = core->xreg(reg0.code()); int64_t result = core->xreg(reg1.code()); return Equal64(expected, core, result); } static char FlagN(uint32_t flags) { return (flags & NFlag) ? 'N' : 'n'; } static char FlagZ(uint32_t flags) { return (flags & ZFlag) ? 'Z' : 'z'; } static char FlagC(uint32_t flags) { return (flags & CFlag) ? 'C' : 'c'; } static char FlagV(uint32_t flags) { return (flags & VFlag) ? 'V' : 'v'; } bool EqualNzcv(uint32_t expected, uint32_t result) { ASSERT((expected & ~NZCVFlag) == 0); ASSERT((result & ~NZCVFlag) == 0); if (result != expected) { printf("Expected: %c%c%c%c\t Found: %c%c%c%c\n", FlagN(expected), FlagZ(expected), FlagC(expected), FlagV(expected), FlagN(result), FlagZ(result), FlagC(result), FlagV(result)); } return result == expected; } bool EqualRegisters(const RegisterDump* a, const RegisterDump* b) { for (unsigned i = 0; i < kNumberOfRegisters; i++) { if (a->xreg(i) != b->xreg(i)) { printf("x%d\t Expected 0x%016" PRIx64 "\t Found 0x%016" PRIx64 "\n", i, a->xreg(i), b->xreg(i)); return false; } } for (unsigned i = 0; i < kNumberOfFPRegisters; i++) { uint64_t a_bits = a->dreg_bits(i); uint64_t b_bits = b->dreg_bits(i); if (a_bits != b_bits) { printf("d%d\t Expected 0x%016" PRIx64 "\t Found 0x%016" PRIx64 "\n", i, a_bits, b_bits); return false; } } return true; } RegList PopulateRegisterArray(Register* w, Register* x, Register* r, int reg_size, int reg_count, RegList allowed) { RegList list = 0; int i = 0; for (unsigned n = 0; (n < kNumberOfRegisters) && (i < reg_count); n++) { if (((1UL << n) & allowed) != 0) { // Only assign allowed registers. if (r) { r[i] = Register(n, reg_size); } if (x) { x[i] = Register(n, kXRegSize); } if (w) { w[i] = Register(n, kWRegSize); } list |= (1UL << n); i++; } } // Check that we got enough registers. ASSERT(CountSetBits(list, kNumberOfRegisters) == reg_count); return list; } RegList PopulateFPRegisterArray(FPRegister* s, FPRegister* d, FPRegister* v, int reg_size, int reg_count, RegList allowed) { RegList list = 0; int i = 0; for (unsigned n = 0; (n < kNumberOfFPRegisters) && (i < reg_count); n++) { if (((1UL << n) & allowed) != 0) { // Only assigned allowed registers. if (v) { v[i] = FPRegister(n, reg_size); } if (d) { d[i] = FPRegister(n, kDRegSize); } if (s) { s[i] = FPRegister(n, kSRegSize); } list |= (1UL << n); i++; } } // Check that we got enough registers. ASSERT(CountSetBits(list, kNumberOfFPRegisters) == reg_count); return list; } void Clobber(MacroAssembler* masm, RegList reg_list, uint64_t const value) { Register first = NoReg; for (unsigned i = 0; i < kNumberOfRegisters; i++) { if (reg_list & (1UL << i)) { Register xn(i, kXRegSize); // We should never write into sp here. ASSERT(!xn.Is(sp)); if (!xn.IsZero()) { if (!first.IsValid()) { // This is the first register we've hit, so construct the literal. __ Mov(xn, value); first = xn; } else { // We've already loaded the literal, so re-use the value already // loaded into the first register we hit. __ Mov(xn, first); } } } } } void ClobberFP(MacroAssembler* masm, RegList reg_list, double const value) { FPRegister first = NoFPReg; for (unsigned i = 0; i < kNumberOfFPRegisters; i++) { if (reg_list & (1UL << i)) { FPRegister dn(i, kDRegSize); if (!first.IsValid()) { // This is the first register we've hit, so construct the literal. __ Fmov(dn, value); first = dn; } else { // We've already loaded the literal, so re-use the value already loaded // into the first register we hit. __ Fmov(dn, first); } } } } void Clobber(MacroAssembler* masm, CPURegList reg_list) { if (reg_list.type() == CPURegister::kRegister) { // This will always clobber X registers. Clobber(masm, reg_list.list()); } else if (reg_list.type() == CPURegister::kFPRegister) { // This will always clobber D registers. ClobberFP(masm, reg_list.list()); } else { UNREACHABLE(); } } void RegisterDump::Dump(MacroAssembler* masm) { ASSERT(__ StackPointer().Is(sp)); // Ensure that we don't unintentionally clobber any registers. Register old_tmp0 = __ Tmp0(); Register old_tmp1 = __ Tmp1(); FPRegister old_fptmp0 = __ FPTmp0(); __ SetScratchRegisters(NoReg, NoReg); __ SetFPScratchRegister(NoFPReg); // Preserve some temporary registers. Register dump_base = x0; Register dump = x1; Register tmp = x2; Register dump_base_w = dump_base.W(); Register dump_w = dump.W(); Register tmp_w = tmp.W(); // Offsets into the dump_ structure. const int x_offset = offsetof(dump_t, x_); const int w_offset = offsetof(dump_t, w_); const int d_offset = offsetof(dump_t, d_); const int s_offset = offsetof(dump_t, s_); const int sp_offset = offsetof(dump_t, sp_); const int wsp_offset = offsetof(dump_t, wsp_); const int flags_offset = offsetof(dump_t, flags_); __ Push(xzr, dump_base, dump, tmp); // Load the address where we will dump the state. __ Mov(dump_base, reinterpret_cast<uint64_t>(&dump_)); // Dump the stack pointer (sp and wsp). // The stack pointer cannot be stored directly; it needs to be moved into // another register first. Also, we pushed four X registers, so we need to // compensate here. __ Add(tmp, sp, 4 * kXRegSizeInBytes); __ Str(tmp, MemOperand(dump_base, sp_offset)); __ Add(tmp_w, wsp, 4 * kXRegSizeInBytes); __ Str(tmp_w, MemOperand(dump_base, wsp_offset)); // Dump X registers. __ Add(dump, dump_base, x_offset); for (unsigned i = 0; i < kNumberOfRegisters; i += 2) { __ Stp(Register::XRegFromCode(i), Register::XRegFromCode(i + 1), MemOperand(dump, i * kXRegSizeInBytes)); } // Dump W registers. __ Add(dump, dump_base, w_offset); for (unsigned i = 0; i < kNumberOfRegisters; i += 2) { __ Stp(Register::WRegFromCode(i), Register::WRegFromCode(i + 1), MemOperand(dump, i * kWRegSizeInBytes)); } // Dump D registers. __ Add(dump, dump_base, d_offset); for (unsigned i = 0; i < kNumberOfFPRegisters; i += 2) { __ Stp(FPRegister::DRegFromCode(i), FPRegister::DRegFromCode(i + 1), MemOperand(dump, i * kDRegSizeInBytes)); } // Dump S registers. __ Add(dump, dump_base, s_offset); for (unsigned i = 0; i < kNumberOfFPRegisters; i += 2) { __ Stp(FPRegister::SRegFromCode(i), FPRegister::SRegFromCode(i + 1), MemOperand(dump, i * kSRegSizeInBytes)); } // Dump the flags. __ Mrs(tmp, NZCV); __ Str(tmp, MemOperand(dump_base, flags_offset)); // To dump the values that were in tmp amd dump, we need a new scratch // register. We can use any of the already dumped registers since we can // easily restore them. Register dump2_base = x10; Register dump2 = x11; ASSERT(!AreAliased(dump_base, dump, tmp, dump2_base, dump2)); // Don't lose the dump_ address. __ Mov(dump2_base, dump_base); __ Pop(tmp, dump, dump_base, xzr); __ Add(dump2, dump2_base, w_offset); __ Str(dump_base_w, MemOperand(dump2, dump_base.code() * kWRegSizeInBytes)); __ Str(dump_w, MemOperand(dump2, dump.code() * kWRegSizeInBytes)); __ Str(tmp_w, MemOperand(dump2, tmp.code() * kWRegSizeInBytes)); __ Add(dump2, dump2_base, x_offset); __ Str(dump_base, MemOperand(dump2, dump_base.code() * kXRegSizeInBytes)); __ Str(dump, MemOperand(dump2, dump.code() * kXRegSizeInBytes)); __ Str(tmp, MemOperand(dump2, tmp.code() * kXRegSizeInBytes)); // Finally, restore dump2_base and dump2. __ Ldr(dump2_base, MemOperand(dump2, dump2_base.code() * kXRegSizeInBytes)); __ Ldr(dump2, MemOperand(dump2, dump2.code() * kXRegSizeInBytes)); // Restore the MacroAssembler's scratch registers. __ SetScratchRegisters(old_tmp0, old_tmp1); __ SetFPScratchRegister(old_fptmp0); completed_ = true; } } // namespace vixl
[ "sgolemon@fb.com" ]
sgolemon@fb.com
fe6f1cf137392e89c03cb8a01672417e1b43dd6c
58958463ae51c6af762ade55e53154cdd57e9b71
/OpenSauce/shared/Include/blamlib/Halo1/memory/byte_swapping.hpp
643eb892f327e01b8af6227560c544fa75cdb632
[]
no_license
yumiris/OpenSauce
af270d723d15bffdfb38f44dbebd90969c432c2b
d200c970c918921d40e9fb376ec685c77797c8b7
refs/heads/master
2022-10-10T17:18:20.363252
2022-08-11T20:31:30
2022-08-11T20:31:30
188,238,131
14
3
null
2020-07-14T08:48:26
2019-05-23T13:19:31
C++
UTF-8
C++
false
false
1,007
hpp
/* Yelo: Open Sauce SDK See license\OpenSauce\OpenSauce for specific license information */ #pragma once #include <blamlib/memory/byte_swapping_base.hpp> namespace Yelo { namespace blam { //////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Byte swap 1 or more structures at a given address. </summary> /// <remarks> Initializes the definition if it hasn't been already. </remarks> /// /// <param name="definition"> The structure byte swap definition. </param> /// <param name="address"> Memory address of the structure instances. </param> /// <param name="data_count"> Number of structure instances at the address. </param> void PLATFORM_API byte_swap_data(Memory::s_byte_swap_definition* definition, void* address, int32 data_count = 1); void PLATFORM_API byte_swap_data_explicit(cstring name, int32 size, byte_swap_code_t* codes, int data_count = 1, void *address = nullptr); }; };
[ "kornman00@gmail.com" ]
kornman00@gmail.com
0b594d686392a289bada85d3800d41d9f7cefc2f
8e361a056e6921c7cc9a51e33f75a37223322a79
/ValidarCedula_Cx.ino
ae14630afdb85983559b563faba0167dfd6490af
[]
no_license
MateoTito/Sistemas-Microprocesados
e7073d33d853bd6fad64499b1db4301becc2afc8
0872a8c4164a9a627e46772bcd222481e9618884
refs/heads/master
2020-04-02T15:45:42.132079
2019-02-06T03:42:01
2019-02-06T03:42:01
154,582,144
0
1
null
null
null
null
UTF-8
C++
false
false
6,244
ino
#include<stdlib.h> //Conversiones lenguaje C /* UTN FICA CIERCOM Autor: Mateo Tito Deber de Sistemas Microprocesados Programa que permite ingresar el número de cédula con el guión y posteriormente validarlo. El dato se ingresa por comunicación serial. Los crterios para la validación son: -Deben ingresarse 11 dígitos, contando el guión. -Debe existir un guión antes del último dígito. -Todos los dígitos ingresados deben ser números. -La cédula debe cumplir el criterio del *Módulo 10 para el último dígito. -Los dos primeros dígitos no deben superar 24, por las provincias. -El tercer dígito no debe ser mayor a 5. *Modulo 10: Se multiplican los 9 primeros digitos por los coeficientes 2 1 2 1 2 1 2 1 2, de manera individual, si alguno sobrepasa 10 se le resta 9, se suman todos los productos y el resultado se resta a su decena superior, este resultado deberá ser igual al último dígito de la cédula ecuatoriana. */ String cedula; //Almacena la cadena de texto int tam; //Tamaño de la cadena int probe = 0; //Comprueba el Modulo 10 int i = 0; //Contador int entero; //Comparar digitos con enteros int ctrl; //Decena superio para el Modulo 10 boolean bandera = false; //Falsa si todos los dígitos son números boolean bandera1 = false; //Falsa si los dos priemeros números son menores a 24 int dece = 0; //Extrae las decenas de la sumatoria para el Modulo 10 long num_ced; //Convertir de char a int, long para tener 32 bits de datos char ced [10]; //Comparador y almacena los dígitos comprobados int comp, comp1, comp2; //Variables para comparar los 3 primeros dígitos int j = 0; //Contador para validar el último dígito void setup() { Serial.begin(9600); //Configuracion Cx serial Serial.println("Ingrese su cedula con un guion:"); //Indica la forma de ingreso } void loop() { if (Serial.available() > 0) { //Comprueba que hay datos disponibles cedula = Serial.readString(); //Almacena los datos en una cadena de texto tam = cedula.length(); //Almacena el tamaño de la cadena de texto char vector [tam]; //Vector char con el tamaño de la cadena cedula.toCharArray(vector, tam + 1); //Se crea el vector tipo char //Serial.println(vector); if (tam == 11) { //Comprueba la cantidad correcta de datos ingresados if (vector[9] == '-') { //Verifica si cuenta con el guión for (; i < 9; i++) { // Recorre el vector para comprobar dato por dato ced [i] = vector [i]; entero = atoi(&ced[i]); //Covierte cada char en int if (isDigit(ced[i])) { //Comprueba que todos sean números bandera = false; //Bandera se mantiene en reposo } else { //Si algún digito no es un número bandera = true; //Bandera cambia a verdadero break; //Termina las iteraciones } } //Valida los 2 primeros dígitos comp = String(ced[0]).toInt(); //Transforma a entero el primer digito comp1 = String(ced[1]).toInt(); //Transforma a entero el segundo digito if (comp < 2) { //Si el primero es menor a 2 bandera1 = false; //Todo en orden } else if (comp == 2) { //Si el primero es igual a 2 if (comp1 < 5) { //El segundo no debe ser mayor a 4 bandera1 = false; //Todo en orden } else { bandera1 = true; //Cedula no valida Serial.println(""); Serial.println("Los dos primeros digitos no deben ser mayores a 24"); } } else { //De otro modo el primer dígito es mayor a 2 Serial.println(""); Serial.println("Cedula no valida"); Serial.println("Primer digito mayor que 2"); } //Valida el tercer dígito comp2 = String(ced[2]).toInt(); //Convierte el tercer dígito a entero if (comp2 >= 6) { //Si el tercero es mayor a 5 no es válida Serial.println(""); Serial.println("Cedula no valida."); Serial.println("Tercer digito mayor a 5"); } //Valida el último dígito j = 0; //Reinicio de variable contador probe = 0; //Reinicio de variable sumador for (; j < 9; j++) { //Toma los digitos en posición par if ((String(ced[j]).toInt()) * 2 > 10) { //Si su doble producto supera a 9 probe = probe + ((String(ced[j]).toInt()) * 2 - 9); //Se resta 9 y se suma al total j++; //Contador solo para pares } else { //Si su doble producto no supera 9 probe = probe + String(ced[j]).toInt() * 2; //Sumatoria total j++; //Contador solo para pares } } j = 1; //Setear el contador solo para impares for (; j < 9; j++) { probe = probe + String(ced[j]).toInt(); //Sumatoria total j++; //Doble contador para impares } i = 0; //Reseteo de contador if (bandera == false) { //Si no hay inconvenientes continua el proceso dece = probe / 10; //Obtiene las decenas de la sumatoria total ctrl = (dece + 1) * 10 - probe; //Se resta de la decena superior ced [9] = vector [10]; //Se adjunta el digito 10 if (ctrl == atoi(&ced[9])) { //Si el último digito se cumple la condicion del modulo 10 Serial.println(""); //Salto de línea (estético) Serial.println("Cedula validada"); //Todo en orden } else { Serial.println(""); Serial.println("Cedula no valida."); Serial.println("Ultimo digito incorrecto."); //No corresponde a una cedula real } } else if (bandera1 == true) { //Bandera verdadero si los dos primeros dígitos superan 24 Serial.println(""); Serial.println("Dos primeros digitos mayores a 24"); } else { Serial.println(""); Serial.println("Todos los digitos deben ser numeros"); } } else { Serial.println(""); Serial.println("Cedula no valida. Falta el guion"); //Tamaño correcto, pero falta guion } } else { Serial.println(""); Serial.println("Cedula no valida"); //Si no tiene 10 dígitos y el guión } } }
[ "44451446+MateoTito@users.noreply.github.com" ]
44451446+MateoTito@users.noreply.github.com
3ddcfe9156f1c396cb3c5a521c091224e29db2f0
b648a0ff402d23a6432643879b0b81ebe0bc9685
/vendor/thrift/compiler/cpp/src/thrift/generate/t_py_generator.cc
fe40fc2ddcb46ff3757703172a16fc911b3389fb
[ "Apache-2.0", "MIT", "FSFAP", "LicenseRef-scancode-public-domain-disclaimer", "BSD-3-Clause" ]
permissive
jviotti/binary-json-size-benchmark
4712faca2724d47d23efef241983ce875dc71cee
165b577884ef366348bf48042fddf54aacfe647a
refs/heads/main
2023-04-18T01:40:26.141995
2022-12-19T13:25:35
2022-12-19T13:25:35
337,583,132
21
1
Apache-2.0
2022-12-17T21:53:56
2021-02-10T01:18:05
C++
UTF-8
C++
false
false
100,500
cc
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 <fstream> #include <iomanip> #include <iostream> #include <limits> #include <vector> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #include <sstream> #include <algorithm> #include "thrift/platform.h" #include "thrift/version.h" #include "thrift/generate/t_generator.h" using std::map; using std::ostream; using std::ostringstream; using std::string; using std::stringstream; using std::vector; static const string endl = "\n"; // avoid ostream << std::endl flushes /** * Python code generator. * */ class t_py_generator : public t_generator { public: t_py_generator(t_program* program, const std::map<std::string, std::string>& parsed_options, const std::string& option_string) : t_generator (program) { update_keywords(); std::map<std::string, std::string>::const_iterator iter; gen_newstyle_ = true; gen_utf8strings_ = true; gen_dynbase_ = false; gen_slots_ = false; gen_tornado_ = false; gen_zope_interface_ = false; gen_twisted_ = false; gen_dynamic_ = false; coding_ = ""; gen_dynbaseclass_ = ""; gen_dynbaseclass_exc_ = ""; gen_dynbaseclass_frozen_exc_ = ""; gen_dynbaseclass_frozen_ = ""; import_dynbase_ = ""; package_prefix_ = ""; for( iter = parsed_options.begin(); iter != parsed_options.end(); ++iter) { if( iter->first.compare("new_style") == 0) { pwarning(0, "new_style is enabled by default, so the option will be removed in the near future.\n"); } else if( iter->first.compare("old_style") == 0) { gen_newstyle_ = false; pwarning(0, "old_style is deprecated and may be removed in the future.\n"); } else if( iter->first.compare("utf8strings") == 0) { pwarning(0, "utf8strings is enabled by default, so the option will be removed in the near future.\n"); } else if( iter->first.compare("no_utf8strings") == 0) { gen_utf8strings_ = false; } else if( iter->first.compare("slots") == 0) { gen_slots_ = true; } else if( iter->first.compare("package_prefix") == 0) { package_prefix_ = iter->second; } else if( iter->first.compare("dynamic") == 0) { gen_dynamic_ = true; gen_newstyle_ = false; // dynamic is newstyle if( gen_dynbaseclass_.empty()) { gen_dynbaseclass_ = "TBase"; } if( gen_dynbaseclass_frozen_.empty()) { gen_dynbaseclass_frozen_ = "TFrozenBase"; } if( gen_dynbaseclass_exc_.empty()) { gen_dynbaseclass_exc_ = "TExceptionBase"; } if( gen_dynbaseclass_frozen_exc_.empty()) { gen_dynbaseclass_frozen_exc_ = "TFrozenExceptionBase"; } if( import_dynbase_.empty()) { import_dynbase_ = "from thrift.protocol.TBase import TBase, TFrozenBase, TExceptionBase, TFrozenExceptionBase, TTransport\n"; } } else if( iter->first.compare("dynbase") == 0) { gen_dynbase_ = true; gen_dynbaseclass_ = (iter->second); } else if( iter->first.compare("dynfrozen") == 0) { gen_dynbaseclass_frozen_ = (iter->second); } else if( iter->first.compare("dynexc") == 0) { gen_dynbaseclass_exc_ = (iter->second); } else if( iter->first.compare("dynfrozenexc") == 0) { gen_dynbaseclass_frozen_exc_ = (iter->second); } else if( iter->first.compare("dynimport") == 0) { gen_dynbase_ = true; import_dynbase_ = (iter->second); } else if( iter->first.compare("zope.interface") == 0) { gen_zope_interface_ = true; } else if( iter->first.compare("twisted") == 0) { gen_twisted_ = true; gen_zope_interface_ = true; } else if( iter->first.compare("tornado") == 0) { gen_tornado_ = true; } else if( iter->first.compare("coding") == 0) { coding_ = iter->second; } else { throw "unknown option py:" + iter->first; } } if (gen_twisted_ && gen_tornado_) { throw "at most one of 'twisted' and 'tornado' are allowed"; } copy_options_ = option_string; if (gen_twisted_) { out_dir_base_ = "gen-py.twisted"; } else if (gen_tornado_) { out_dir_base_ = "gen-py.tornado"; } else { out_dir_base_ = "gen-py"; } } std::string indent_str() const override { return " "; } /** * Init and close methods */ void init_generator() override; void close_generator() override; /** * Program-level generation functions */ void generate_typedef(t_typedef* ttypedef) override; void generate_enum(t_enum* tenum) override; void generate_const(t_const* tconst) override; void generate_struct(t_struct* tstruct) override; void generate_forward_declaration(t_struct* tstruct) override; void generate_xception(t_struct* txception) override; void generate_service(t_service* tservice) override; std::string render_const_value(t_type* type, t_const_value* value); /** * Struct generation code */ void generate_py_struct(t_struct* tstruct, bool is_exception); void generate_py_thrift_spec(std::ostream& out, t_struct* tstruct, bool is_exception); void generate_py_struct_definition(std::ostream& out, t_struct* tstruct, bool is_xception = false); void generate_py_struct_reader(std::ostream& out, t_struct* tstruct); void generate_py_struct_writer(std::ostream& out, t_struct* tstruct); void generate_py_struct_required_validator(std::ostream& out, t_struct* tstruct); void generate_py_function_helpers(t_function* tfunction); /** * Service-level generation functions */ void generate_service_helpers(t_service* tservice); void generate_service_interface(t_service* tservice); void generate_service_client(t_service* tservice); void generate_service_remote(t_service* tservice); void generate_service_server(t_service* tservice); void generate_process_function(t_service* tservice, t_function* tfunction); /** * Serialization constructs */ void generate_deserialize_field(std::ostream& out, t_field* tfield, std::string prefix = ""); void generate_deserialize_struct(std::ostream& out, t_struct* tstruct, std::string prefix = ""); void generate_deserialize_container(std::ostream& out, t_type* ttype, std::string prefix = ""); void generate_deserialize_set_element(std::ostream& out, t_set* tset, std::string prefix = ""); void generate_deserialize_map_element(std::ostream& out, t_map* tmap, std::string prefix = ""); void generate_deserialize_list_element(std::ostream& out, t_list* tlist, std::string prefix = ""); void generate_serialize_field(std::ostream& out, t_field* tfield, std::string prefix = ""); void generate_serialize_struct(std::ostream& out, t_struct* tstruct, std::string prefix = ""); void generate_serialize_container(std::ostream& out, t_type* ttype, std::string prefix = ""); void generate_serialize_map_element(std::ostream& out, t_map* tmap, std::string kiter, std::string viter); void generate_serialize_set_element(std::ostream& out, t_set* tmap, std::string iter); void generate_serialize_list_element(std::ostream& out, t_list* tlist, std::string iter); void generate_python_docstring(std::ostream& out, t_struct* tstruct); void generate_python_docstring(std::ostream& out, t_function* tfunction); void generate_python_docstring(std::ostream& out, t_doc* tdoc, t_struct* tstruct, const char* subheader); void generate_python_docstring(std::ostream& out, t_doc* tdoc); /** * Helper rendering functions */ std::string py_autogen_comment(); std::string py_imports(); std::string render_includes(); std::string declare_argument(t_field* tfield); std::string render_field_default_value(t_field* tfield); std::string type_name(t_type* ttype); std::string function_signature(t_function* tfunction, bool interface = false); std::string argument_list(t_struct* tstruct, std::vector<std::string>* pre = nullptr, std::vector<std::string>* post = nullptr); std::string type_to_enum(t_type* ttype); std::string type_to_spec_args(t_type* ttype); static bool is_valid_namespace(const std::string& sub_namespace) { return sub_namespace == "twisted"; } static std::string get_real_py_module(const t_program* program, bool gen_twisted, std::string package_dir="") { if (gen_twisted) { std::string twisted_module = program->get_namespace("py.twisted"); if (!twisted_module.empty()) { return twisted_module; } } std::string real_module = program->get_namespace("py"); if (real_module.empty()) { return program->get_name(); } return package_dir + real_module; } static bool is_immutable(t_type* ttype) { std::map<std::string, std::string>::iterator it = ttype->annotations_.find("python.immutable"); if (it == ttype->annotations_.end()) { // Exceptions are immutable by default. return ttype->is_xception(); } else if (it->second == "false") { return false; } else { return true; } } private: /** * True if we should generate new-style classes. */ bool gen_newstyle_; /** * True if we should generate dynamic style classes. */ bool gen_dynamic_; bool gen_dynbase_; std::string gen_dynbaseclass_; std::string gen_dynbaseclass_frozen_; std::string gen_dynbaseclass_exc_; std::string gen_dynbaseclass_frozen_exc_; std::string import_dynbase_; bool gen_slots_; std::string copy_options_; /** * True if we should generate code for use with zope.interface. */ bool gen_zope_interface_; /** * True if we should generate Twisted-friendly RPC services. */ bool gen_twisted_; /** * True if we should generate code for use with Tornado */ bool gen_tornado_; /** * True if strings should be encoded using utf-8. */ bool gen_utf8strings_; /** * specify generated file encoding * eg. # -*- coding: utf-8 -*- */ string coding_; string package_prefix_; /** * File streams */ ofstream_with_content_based_conditional_update f_types_; ofstream_with_content_based_conditional_update f_consts_; ofstream_with_content_based_conditional_update f_service_; std::string package_dir_; std::string module_; protected: std::set<std::string> lang_keywords() const override { std::string keywords[] = { "False", "None", "True", "and", "as", "assert", "break", "class", "continue", "def", "del", "elif", "else", "except", "exec", "finally", "for", "from", "global", "if", "import", "in", "is", "lambda", "nonlocal", "not", "or", "pass", "print", "raise", "return", "try", "while", "with", "yield" }; return std::set<std::string>(keywords, keywords + sizeof(keywords)/sizeof(keywords[0]) ); } }; /** * Prepares for file generation by opening up the necessary file output * streams. * * @param tprogram The program to generate */ void t_py_generator::init_generator() { // Make output directory string module = get_real_py_module(program_, gen_twisted_); package_dir_ = get_out_dir(); module_ = module; while (true) { // TODO: Do better error checking here. MKDIR(package_dir_.c_str()); std::ofstream init_py((package_dir_ + "/__init__.py").c_str(), std::ios_base::app); init_py.close(); if (module.empty()) { break; } string::size_type pos = module.find('.'); if (pos == string::npos) { package_dir_ += "/"; package_dir_ += module; module.clear(); } else { package_dir_ += "/"; package_dir_ += module.substr(0, pos); module.erase(0, pos + 1); } } // Make output file string f_types_name = package_dir_ + "/" + "ttypes.py"; f_types_.open(f_types_name.c_str()); string f_consts_name = package_dir_ + "/" + "constants.py"; f_consts_.open(f_consts_name.c_str()); string f_init_name = package_dir_ + "/__init__.py"; ofstream_with_content_based_conditional_update f_init; f_init.open(f_init_name.c_str()); f_init << "__all__ = ['ttypes', 'constants'"; vector<t_service*> services = program_->get_services(); vector<t_service*>::iterator sv_iter; for (sv_iter = services.begin(); sv_iter != services.end(); ++sv_iter) { f_init << ", '" << (*sv_iter)->get_name() << "'"; } f_init << "]" << endl; f_init.close(); // Print header f_types_ << py_autogen_comment() << endl << py_imports() << endl << render_includes() << endl << "from thrift.transport import TTransport" << endl << import_dynbase_; f_types_ << "all_structs = []" << endl; f_consts_ << py_autogen_comment() << endl << py_imports() << endl << "from .ttypes import *" << endl; } /** * Renders all the imports necessary for including another Thrift program */ string t_py_generator::render_includes() { const vector<t_program*>& includes = program_->get_includes(); string result = ""; for (auto include : includes) { result += "import " + get_real_py_module(include, gen_twisted_, package_prefix_) + ".ttypes\n"; } return result; } /** * Autogen'd comment */ string t_py_generator::py_autogen_comment() { string coding; if (!coding_.empty()) { coding = "# -*- coding: " + coding_ + " -*-\n"; } return coding + std::string("#\n") + "# Autogenerated by Thrift Compiler (" + THRIFT_VERSION + ")\n" + "#\n" + "# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING\n" + "#\n" + "# options string: " + copy_options_ + "\n" + "#\n"; } /** * Prints standard thrift imports */ string t_py_generator::py_imports() { ostringstream ss; ss << "from thrift.Thrift import TType, TMessageType, TFrozenDict, TException, " "TApplicationException" << endl << "from thrift.protocol.TProtocol import TProtocolException" << endl << "from thrift.TRecursive import fix_spec" << endl; if (gen_utf8strings_) { ss << endl << "import sys"; } return ss.str(); } /** * Closes the type files */ void t_py_generator::close_generator() { // Fix thrift_spec definitions for recursive structs. f_types_ << "fix_spec(all_structs)" << endl; f_types_ << "del all_structs" << endl; // Close types file f_types_.close(); f_consts_.close(); } /** * Generates a typedef. This is not done in Python, types are all implicit. * * @param ttypedef The type definition */ void t_py_generator::generate_typedef(t_typedef* ttypedef) { (void)ttypedef; } /** * Generates code for an enumerated type. Done using a class to scope * the values. * * @param tenum The enumeration */ void t_py_generator::generate_enum(t_enum* tenum) { std::ostringstream to_string_mapping, from_string_mapping; f_types_ << endl << endl << "class " << tenum->get_name() << (gen_newstyle_ ? "(object)" : "") << (gen_dynamic_ ? "(" + gen_dynbaseclass_ + ")" : "") << ":" << endl; indent_up(); generate_python_docstring(f_types_, tenum); to_string_mapping << indent() << "_VALUES_TO_NAMES = {" << endl; from_string_mapping << indent() << "_NAMES_TO_VALUES = {" << endl; vector<t_enum_value*> constants = tenum->get_constants(); vector<t_enum_value*>::iterator c_iter; for (c_iter = constants.begin(); c_iter != constants.end(); ++c_iter) { int value = (*c_iter)->get_value(); indent(f_types_) << (*c_iter)->get_name() << " = " << value << endl; // Dictionaries to/from string names of enums to_string_mapping << indent() << indent() << value << ": \"" << escape_string((*c_iter)->get_name()) << "\"," << endl; from_string_mapping << indent() << indent() << '"' << escape_string((*c_iter)->get_name()) << "\": " << value << ',' << endl; } to_string_mapping << indent() << "}" << endl; from_string_mapping << indent() << "}" << endl; indent_down(); f_types_ << endl; f_types_ << to_string_mapping.str() << endl << from_string_mapping.str(); } /** * Generate a constant value */ void t_py_generator::generate_const(t_const* tconst) { t_type* type = tconst->get_type(); string name = tconst->get_name(); t_const_value* value = tconst->get_value(); indent(f_consts_) << name << " = " << render_const_value(type, value); f_consts_ << endl; } /** * Prints the value of a constant with the given type. Note that type checking * is NOT performed in this function as it is always run beforehand using the * validate_types method in main.cc */ string t_py_generator::render_const_value(t_type* type, t_const_value* value) { type = get_true_type(type); std::ostringstream out; if (type->is_base_type()) { t_base_type::t_base tbase = ((t_base_type*)type)->get_base(); switch (tbase) { case t_base_type::TYPE_STRING: if (((t_base_type*)type)->is_binary()) { out << 'b'; } out << '"' << get_escaped_string(value) << '"'; break; case t_base_type::TYPE_BOOL: out << (value->get_integer() > 0 ? "True" : "False"); break; case t_base_type::TYPE_I8: case t_base_type::TYPE_I16: case t_base_type::TYPE_I32: case t_base_type::TYPE_I64: out << value->get_integer(); break; case t_base_type::TYPE_DOUBLE: if (value->get_type() == t_const_value::CV_INTEGER) { out << "float(" << value->get_integer() << ")"; } else { out << emit_double_as_string(value->get_double()); } break; default: throw "compiler error: no const of base type " + t_base_type::t_base_name(tbase); } } else if (type->is_enum()) { out << value->get_integer(); } else if (type->is_struct() || type->is_xception()) { out << type_name(type) << "(**{" << endl; indent_up(); const vector<t_field*>& fields = ((t_struct*)type)->get_members(); vector<t_field*>::const_iterator f_iter; const map<t_const_value*, t_const_value*, t_const_value::value_compare>& val = value->get_map(); map<t_const_value*, t_const_value*, t_const_value::value_compare>::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { t_type* field_type = nullptr; for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { if ((*f_iter)->get_name() == v_iter->first->get_string()) { field_type = (*f_iter)->get_type(); } } if (field_type == nullptr) { throw "type error: " + type->get_name() + " has no field " + v_iter->first->get_string(); } indent(out) << render_const_value(g_type_string, v_iter->first) << ": " << render_const_value(field_type, v_iter->second) << "," << endl; } indent_down(); indent(out) << "})"; } else if (type->is_map()) { t_type* ktype = ((t_map*)type)->get_key_type(); t_type* vtype = ((t_map*)type)->get_val_type(); if (is_immutable(type)) { out << "TFrozenDict("; } out << "{" << endl; indent_up(); const map<t_const_value*, t_const_value*, t_const_value::value_compare>& val = value->get_map(); map<t_const_value*, t_const_value*, t_const_value::value_compare>::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { indent(out) << render_const_value(ktype, v_iter->first) << ": " << render_const_value(vtype, v_iter->second) << "," << endl; } indent_down(); indent(out) << "}"; if (is_immutable(type)) { out << ")"; } } else if (type->is_list() || type->is_set()) { t_type* etype; if (type->is_list()) { etype = ((t_list*)type)->get_elem_type(); } else { etype = ((t_set*)type)->get_elem_type(); } if (type->is_set()) { if (is_immutable(type)) { out << "frozen"; } out << "set("; } if (is_immutable(type) || type->is_set()) { out << "(" << endl; } else { out << "[" << endl; } indent_up(); const vector<t_const_value*>& val = value->get_list(); vector<t_const_value*>::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { indent(out) << render_const_value(etype, *v_iter) << "," << endl; } indent_down(); if (is_immutable(type) || type->is_set()) { indent(out) << ")"; } else { indent(out) << "]"; } if (type->is_set()) { out << ")"; } } else { throw "CANNOT GENERATE CONSTANT FOR TYPE: " + type->get_name(); } return out.str(); } /** * Generates the "forward declarations" for python structs. * These are actually full class definitions so that calls to generate_struct * can add the thrift_spec field. This is needed so that all thrift_spec * definitions are grouped at the end of the file to enable co-recursive structs. */ void t_py_generator::generate_forward_declaration(t_struct* tstruct) { generate_py_struct(tstruct, tstruct->is_xception()); } /** * Generates a python struct */ void t_py_generator::generate_struct(t_struct* tstruct) { generate_py_thrift_spec(f_types_, tstruct, false); } /** * Generates a struct definition for a thrift exception. Basically the same * as a struct but extends the Exception class. * * @param txception The struct definition */ void t_py_generator::generate_xception(t_struct* txception) { generate_py_thrift_spec(f_types_, txception, true); } /** * Generates a python struct */ void t_py_generator::generate_py_struct(t_struct* tstruct, bool is_exception) { generate_py_struct_definition(f_types_, tstruct, is_exception); } /** * Generate the thrift_spec for a struct * For example, * all_structs.append(Recursive) * Recursive.thrift_spec = ( * None, # 0 * (1, TType.LIST, 'Children', (TType.STRUCT, (Recursive, None), False), None, ), # 1 * ) */ void t_py_generator::generate_py_thrift_spec(ostream& out, t_struct* tstruct, bool /*is_exception*/) { const vector<t_field*>& sorted_members = tstruct->get_sorted_members(); vector<t_field*>::const_iterator m_iter; // Add struct definition to list so thrift_spec can be fixed for recursive structures. indent(out) << "all_structs.append(" << tstruct->get_name() << ")" << endl; if (sorted_members.empty() || (sorted_members[0]->get_key() >= 0)) { indent(out) << tstruct->get_name() << ".thrift_spec = (" << endl; indent_up(); int sorted_keys_pos = 0; for (m_iter = sorted_members.begin(); m_iter != sorted_members.end(); ++m_iter) { for (; sorted_keys_pos != (*m_iter)->get_key(); sorted_keys_pos++) { indent(out) << "None, # " << sorted_keys_pos << endl; } indent(out) << "(" << (*m_iter)->get_key() << ", " << type_to_enum((*m_iter)->get_type()) << ", " << "'" << (*m_iter)->get_name() << "'" << ", " << type_to_spec_args((*m_iter)->get_type()) << ", " << render_field_default_value(*m_iter) << ", " << ")," << " # " << sorted_keys_pos << endl; sorted_keys_pos++; } indent_down(); indent(out) << ")" << endl; } else { indent(out) << tstruct->get_name() << ".thrift_spec = ()" << endl; } } /** * Generates a struct definition for a thrift data type. * * @param tstruct The struct definition */ void t_py_generator::generate_py_struct_definition(ostream& out, t_struct* tstruct, bool is_exception) { const vector<t_field*>& members = tstruct->get_members(); const vector<t_field*>& sorted_members = tstruct->get_sorted_members(); vector<t_field*>::const_iterator m_iter; out << endl << endl << "class " << tstruct->get_name(); if (is_exception) { if (gen_dynamic_) { if (is_immutable(tstruct)) { out << "(" << gen_dynbaseclass_frozen_exc_ << ")"; } else { out << "(" << gen_dynbaseclass_exc_ << ")"; } } else { out << "(TException)"; } } else if (gen_dynamic_) { if (is_immutable(tstruct)) { out << "(" << gen_dynbaseclass_frozen_ << ")"; } else { out << "(" << gen_dynbaseclass_ << ")"; } } else if (gen_newstyle_) { out << "(object)"; } out << ":" << endl; indent_up(); generate_python_docstring(out, tstruct); out << endl; /* Here we generate the structure specification for the fastbinary codec. These specifications have the following structure: thrift_spec -> tuple of item_spec item_spec -> None | (tag, type_enum, name, spec_args, default) tag -> integer type_enum -> TType.I32 | TType.STRING | TType.STRUCT | ... name -> string_literal default -> None # Handled by __init__ spec_args -> None # For simple types | (type_enum, spec_args) # Value type for list/set | (type_enum, spec_args, type_enum, spec_args) # Key and value for map | (class_name, spec_args_ptr) # For struct/exception class_name -> identifier # Basically a pointer to the class spec_args_ptr -> expression # just class_name.spec_args TODO(dreiss): Consider making this work for structs with negative tags. */ if (gen_slots_) { indent(out) << "__slots__ = (" << endl; indent_up(); for (m_iter = sorted_members.begin(); m_iter != sorted_members.end(); ++m_iter) { indent(out) << "'" << (*m_iter)->get_name() << "'," << endl; } indent_down(); indent(out) << ")" << endl << endl; } // TODO(dreiss): Look into generating an empty tuple instead of None // for structures with no members. // TODO(dreiss): Test encoding of structs where some inner structs // don't have thrift_spec. if (members.size() > 0) { out << endl; out << indent() << "def __init__(self,"; for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) { out << " " << declare_argument(*m_iter) << ","; } out << "):" << endl; indent_up(); for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) { // Initialize fields t_type* type = (*m_iter)->get_type(); if (!type->is_base_type() && !type->is_enum() && (*m_iter)->get_value() != nullptr) { indent(out) << "if " << (*m_iter)->get_name() << " is " << "self.thrift_spec[" << (*m_iter)->get_key() << "][4]:" << endl; indent_up(); indent(out) << (*m_iter)->get_name() << " = " << render_field_default_value(*m_iter) << endl; indent_down(); } if (is_immutable(tstruct)) { if (gen_newstyle_ || gen_dynamic_) { indent(out) << "super(" << tstruct->get_name() << ", self).__setattr__('" << (*m_iter)->get_name() << "', " << (*m_iter)->get_name() << ")" << endl; } else { indent(out) << "self.__dict__['" << (*m_iter)->get_name() << "'] = " << (*m_iter)->get_name() << endl; } } else { indent(out) << "self." << (*m_iter)->get_name() << " = " << (*m_iter)->get_name() << endl; } } indent_down(); } if (is_immutable(tstruct)) { out << endl; out << indent() << "def __setattr__(self, *args):" << endl << indent() << indent_str() << "raise TypeError(\"can't modify immutable instance\")" << endl << endl; out << indent() << "def __delattr__(self, *args):" << endl << indent() << indent_str() << "raise TypeError(\"can't modify immutable instance\")" << endl << endl; // Hash all of the members in order, and also hash in the class // to avoid collisions for stuff like single-field structures. out << indent() << "def __hash__(self):" << endl << indent() << indent_str() << "return hash(self.__class__) ^ hash(("; for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) { out << "self." << (*m_iter)->get_name() << ", "; } out << "))" << endl; } if (!gen_dynamic_) { out << endl; generate_py_struct_reader(out, tstruct); generate_py_struct_writer(out, tstruct); } // For exceptions only, generate a __str__ method. This is // because when raised exceptions are printed to the console, __repr__ // isn't used. See python bug #5882 if (is_exception) { out << endl; out << indent() << "def __str__(self):" << endl << indent() << indent_str() << "return repr(self)" << endl; } if (!gen_slots_) { out << endl; // Printing utilities so that on the command line thrift // structs look pretty like dictionaries indent(out) << "def __repr__(self):" << endl; indent_up(); out << indent() << "L = ['%s=%r' % (key, value)" << endl << indent() << " for key, value in self.__dict__.items()]" << endl << indent() << "return '%s(%s)' % (self.__class__.__name__, ', '.join(L))" << endl << endl; indent_down(); // Equality and inequality methods that compare by value out << indent() << "def __eq__(self, other):" << endl; indent_up(); out << indent() << "return isinstance(other, self.__class__) and " "self.__dict__ == other.__dict__" << endl; indent_down(); out << endl; out << indent() << "def __ne__(self, other):" << endl; indent_up(); out << indent() << "return not (self == other)" << endl; indent_down(); } else if (!gen_dynamic_) { out << endl; // no base class available to implement __eq__ and __repr__ and __ne__ for us // so we must provide one that uses __slots__ indent(out) << "def __repr__(self):" << endl; indent_up(); out << indent() << "L = ['%s=%r' % (key, getattr(self, key))" << endl << indent() << " for key in self.__slots__]" << endl << indent() << "return '%s(%s)' % (self.__class__.__name__, ', '.join(L))" << endl << endl; indent_down(); // Equality method that compares each attribute by value and type, walking __slots__ out << indent() << "def __eq__(self, other):" << endl; indent_up(); out << indent() << "if not isinstance(other, self.__class__):" << endl << indent() << indent_str() << "return False" << endl << indent() << "for attr in self.__slots__:" << endl << indent() << indent_str() << "my_val = getattr(self, attr)" << endl << indent() << indent_str() << "other_val = getattr(other, attr)" << endl << indent() << indent_str() << "if my_val != other_val:" << endl << indent() << indent_str() << indent_str() << "return False" << endl << indent() << "return True" << endl << endl; indent_down(); out << indent() << "def __ne__(self, other):" << endl << indent() << indent_str() << "return not (self == other)" << endl; } indent_down(); } /** * Generates the read method for a struct */ void t_py_generator::generate_py_struct_reader(ostream& out, t_struct* tstruct) { const vector<t_field*>& fields = tstruct->get_members(); vector<t_field*>::const_iterator f_iter; if (is_immutable(tstruct)) { out << indent() << "@classmethod" << endl << indent() << "def read(cls, iprot):" << endl; } else { indent(out) << "def read(self, iprot):" << endl; } indent_up(); const char* id = is_immutable(tstruct) ? "cls" : "self"; indent(out) << "if iprot._fast_decode is not None " "and isinstance(iprot.trans, TTransport.CReadableTransport) " "and " << id << ".thrift_spec is not None:" << endl; indent_up(); if (is_immutable(tstruct)) { indent(out) << "return iprot._fast_decode(None, iprot, [cls, cls.thrift_spec])" << endl; } else { indent(out) << "iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec])" << endl; indent(out) << "return" << endl; } indent_down(); indent(out) << "iprot.readStructBegin()" << endl; if (is_immutable(tstruct)) { for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { t_field* tfield = *f_iter; std::ostringstream result; result << tfield->get_name() << " = "; if (tfield->get_value() != nullptr) { result << render_field_default_value(tfield); } else { result << "None"; } indent(out) << result.str() << endl; } } // Loop over reading in fields indent(out) << "while True:" << endl; indent_up(); // Read beginning field marker indent(out) << "(fname, ftype, fid) = iprot.readFieldBegin()" << endl; // Check for field STOP marker and break indent(out) << "if ftype == TType.STOP:" << endl; indent_up(); indent(out) << "break" << endl; indent_down(); // Switch statement on the field we are reading bool first = true; // Generate deserialization code for known cases for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { if (first) { first = false; out << indent() << "if "; } else { out << indent() << "elif "; } out << "fid == " << (*f_iter)->get_key() << ":" << endl; indent_up(); indent(out) << "if ftype == " << type_to_enum((*f_iter)->get_type()) << ":" << endl; indent_up(); if (is_immutable(tstruct)) { generate_deserialize_field(out, *f_iter); } else { generate_deserialize_field(out, *f_iter, "self."); } indent_down(); out << indent() << "else:" << endl << indent() << indent_str() << "iprot.skip(ftype)" << endl; indent_down(); } // In the default case we skip the field out << indent() << "else:" << endl << indent() << indent_str() << "iprot.skip(ftype)" << endl; // Read field end marker indent(out) << "iprot.readFieldEnd()" << endl; indent_down(); indent(out) << "iprot.readStructEnd()" << endl; if (is_immutable(tstruct)) { indent(out) << "return cls(" << endl; indent_up(); for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { indent(out) << (*f_iter)->get_name() << "=" << (*f_iter)->get_name() << "," << endl; } indent_down(); indent(out) << ")" << endl; } indent_down(); out << endl; } void t_py_generator::generate_py_struct_writer(ostream& out, t_struct* tstruct) { string name = tstruct->get_name(); const vector<t_field*>& fields = tstruct->get_sorted_members(); vector<t_field*>::const_iterator f_iter; indent(out) << "def write(self, oprot):" << endl; indent_up(); indent(out) << "if oprot._fast_encode is not None and self.thrift_spec is not None:" << endl; indent_up(); indent(out) << "oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec]))" << endl; indent(out) << "return" << endl; indent_down(); indent(out) << "oprot.writeStructBegin('" << name << "')" << endl; for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { // Write field header indent(out) << "if self." << (*f_iter)->get_name() << " is not None:" << endl; indent_up(); indent(out) << "oprot.writeFieldBegin(" << "'" << (*f_iter)->get_name() << "', " << type_to_enum((*f_iter)->get_type()) << ", " << (*f_iter)->get_key() << ")" << endl; // Write field contents generate_serialize_field(out, *f_iter, "self."); // Write field closer indent(out) << "oprot.writeFieldEnd()" << endl; indent_down(); } // Write the struct map out << indent() << "oprot.writeFieldStop()" << endl << indent() << "oprot.writeStructEnd()" << endl; out << endl; indent_down(); generate_py_struct_required_validator(out, tstruct); } void t_py_generator::generate_py_struct_required_validator(ostream& out, t_struct* tstruct) { indent(out) << "def validate(self):" << endl; indent_up(); const vector<t_field*>& fields = tstruct->get_members(); if (fields.size() > 0) { vector<t_field*>::const_iterator f_iter; for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { t_field* field = (*f_iter); if (field->get_req() == t_field::T_REQUIRED) { indent(out) << "if self." << field->get_name() << " is None:" << endl; indent(out) << indent_str() << "raise TProtocolException(message='Required field " << field->get_name() << " is unset!')" << endl; } } } indent(out) << "return" << endl; indent_down(); } /** * Generates a thrift service. * * @param tservice The service definition */ void t_py_generator::generate_service(t_service* tservice) { string f_service_name = package_dir_ + "/" + service_name_ + ".py"; f_service_.open(f_service_name.c_str()); f_service_ << py_autogen_comment() << endl << py_imports() << endl; if (tservice->get_extends() != nullptr) { f_service_ << "import " << get_real_py_module(tservice->get_extends()->get_program(), gen_twisted_, package_prefix_) << "." << tservice->get_extends()->get_name() << endl; } f_service_ << "import logging" << endl << "from .ttypes import *" << endl << "from thrift.Thrift import TProcessor" << endl << "from thrift.transport import TTransport" << endl << import_dynbase_; if (gen_zope_interface_) { f_service_ << "from zope.interface import Interface, implementer" << endl; } if (gen_twisted_) { f_service_ << "from twisted.internet import defer" << endl << "from thrift.transport import TTwisted" << endl; } else if (gen_tornado_) { f_service_ << "from tornado import gen" << endl; f_service_ << "from tornado import concurrent" << endl; } f_service_ << "all_structs = []" << endl; // Generate the three main parts of the service generate_service_interface(tservice); generate_service_client(tservice); generate_service_server(tservice); generate_service_helpers(tservice); generate_service_remote(tservice); // Close service file f_service_ << "fix_spec(all_structs)" << endl << "del all_structs" << endl; f_service_.close(); } /** * Generates helper functions for a service. * * @param tservice The service to generate a header definition for */ void t_py_generator::generate_service_helpers(t_service* tservice) { vector<t_function*> functions = tservice->get_functions(); vector<t_function*>::iterator f_iter; f_service_ << endl << "# HELPER FUNCTIONS AND STRUCTURES" << endl; for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) { t_struct* ts = (*f_iter)->get_arglist(); generate_py_struct_definition(f_service_, ts, false); generate_py_thrift_spec(f_service_, ts, false); generate_py_function_helpers(*f_iter); } } /** * Generates a struct and helpers for a function. * * @param tfunction The function */ void t_py_generator::generate_py_function_helpers(t_function* tfunction) { if (!tfunction->is_oneway()) { t_struct result(program_, tfunction->get_name() + "_result"); t_field success(tfunction->get_returntype(), "success", 0); if (!tfunction->get_returntype()->is_void()) { result.append(&success); } t_struct* xs = tfunction->get_xceptions(); const vector<t_field*>& fields = xs->get_members(); vector<t_field*>::const_iterator f_iter; for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { result.append(*f_iter); } generate_py_struct_definition(f_service_, &result, false); generate_py_thrift_spec(f_service_, &result, false); } } /** * Generates a service interface definition. * * @param tservice The service to generate a header definition for */ void t_py_generator::generate_service_interface(t_service* tservice) { string extends = ""; string extends_if = ""; if (tservice->get_extends() != nullptr) { extends = type_name(tservice->get_extends()); extends_if = "(" + extends + ".Iface)"; } else { if (gen_zope_interface_) { extends_if = "(Interface)"; } else if (gen_newstyle_ || gen_dynamic_ || gen_tornado_) { extends_if = "(object)"; } } f_service_ << endl << endl << "class Iface" << extends_if << ":" << endl; indent_up(); generate_python_docstring(f_service_, tservice); vector<t_function*> functions = tservice->get_functions(); if (functions.empty()) { f_service_ << indent() << "pass" << endl; } else { vector<t_function*>::iterator f_iter; bool first = true; for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) { if (first) { first = false; } else { f_service_ << endl; } f_service_ << indent() << "def " << function_signature(*f_iter, true) << ":" << endl; indent_up(); generate_python_docstring(f_service_, (*f_iter)); f_service_ << indent() << "pass" << endl; indent_down(); } } indent_down(); } /** * Generates a service client definition. * * @param tservice The service to generate a server for. */ void t_py_generator::generate_service_client(t_service* tservice) { string extends = ""; string extends_client = ""; if (tservice->get_extends() != nullptr) { extends = type_name(tservice->get_extends()); if (gen_zope_interface_) { extends_client = "(" + extends + ".Client)"; } else { extends_client = extends + ".Client, "; } } else { if (gen_zope_interface_ && (gen_newstyle_ || gen_dynamic_)) { extends_client = "(object)"; } } f_service_ << endl << endl; if (gen_zope_interface_) { f_service_ << "@implementer(Iface)" << endl << "class Client" << extends_client << ":" << endl << endl; } else { f_service_ << "class Client(" << extends_client << "Iface):" << endl; } indent_up(); generate_python_docstring(f_service_, tservice); // Constructor function if (gen_twisted_) { f_service_ << indent() << "def __init__(self, transport, oprot_factory):" << endl; } else if (gen_tornado_) { f_service_ << indent() << "def __init__(self, transport, iprot_factory, oprot_factory=None):" << endl; } else { f_service_ << indent() << "def __init__(self, iprot, oprot=None):" << endl; } indent_up(); if (extends.empty()) { if (gen_twisted_) { f_service_ << indent() << "self._transport = transport" << endl << indent() << "self._oprot_factory = oprot_factory" << endl << indent() << "self._seqid = 0" << endl << indent() << "self._reqs = {}" << endl; } else if (gen_tornado_) { f_service_ << indent() << "self._transport = transport" << endl << indent() << "self._iprot_factory = iprot_factory" << endl << indent() << "self._oprot_factory = (oprot_factory if oprot_factory is not None" << endl << indent() << " else iprot_factory)" << endl << indent() << "self._seqid = 0" << endl << indent() << "self._reqs = {}" << endl << indent() << "self._transport.io_loop.spawn_callback(self._start_receiving)" << endl; } else { f_service_ << indent() << "self._iprot = self._oprot = iprot" << endl << indent() << "if oprot is not None:" << endl << indent() << indent_str() << "self._oprot = oprot" << endl << indent() << "self._seqid = 0" << endl; } } else { if (gen_twisted_) { f_service_ << indent() << extends << ".Client.__init__(self, transport, oprot_factory)" << endl; } else if (gen_tornado_) { f_service_ << indent() << extends << ".Client.__init__(self, transport, iprot_factory, oprot_factory)" << endl; } else { f_service_ << indent() << extends << ".Client.__init__(self, iprot, oprot)" << endl; } } indent_down(); if (gen_tornado_ && extends.empty()) { f_service_ << endl << indent() << "@gen.engine" << endl << indent() << "def _start_receiving(self):" << endl; indent_up(); indent(f_service_) << "while True:" << endl; indent_up(); f_service_ << indent() << "try:" << endl << indent() << indent_str() << "frame = yield self._transport.readFrame()" << endl << indent() << "except TTransport.TTransportException as e:" << endl << indent() << indent_str() << "for future in self._reqs.values():" << endl << indent() << indent_str() << indent_str() << "future.set_exception(e)" << endl << indent() << indent_str() << "self._reqs = {}" << endl << indent() << indent_str() << "return" << endl << indent() << "tr = TTransport.TMemoryBuffer(frame)" << endl << indent() << "iprot = self._iprot_factory.getProtocol(tr)" << endl << indent() << "(fname, mtype, rseqid) = iprot.readMessageBegin()" << endl << indent() << "method = getattr(self, 'recv_' + fname)" << endl << indent() << "future = self._reqs.pop(rseqid, None)" << endl << indent() << "if not future:" << endl << indent() << indent_str() << "# future has already been discarded" << endl << indent() << indent_str() << "continue" << endl << indent() << "try:" << endl << indent() << indent_str() << "result = method(iprot, mtype, rseqid)" << endl << indent() << "except Exception as e:" << endl << indent() << indent_str() << "future.set_exception(e)" << endl << indent() << "else:" << endl << indent() << indent_str() << "future.set_result(result)" << endl; indent_down(); indent_down(); } // Generate client method implementations vector<t_function*> functions = tservice->get_functions(); vector<t_function*>::const_iterator f_iter; for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) { t_struct* arg_struct = (*f_iter)->get_arglist(); const vector<t_field*>& fields = arg_struct->get_members(); vector<t_field*>::const_iterator fld_iter; string funname = (*f_iter)->get_name(); f_service_ << endl; // Open function indent(f_service_) << "def " << function_signature(*f_iter, false) << ":" << endl; indent_up(); generate_python_docstring(f_service_, (*f_iter)); if (gen_twisted_) { indent(f_service_) << "seqid = self._seqid = self._seqid + 1" << endl; indent(f_service_) << "self._reqs[seqid] = defer.Deferred()" << endl << endl; indent(f_service_) << "d = defer.maybeDeferred(self.send_" << funname; } else if (gen_tornado_) { indent(f_service_) << "self._seqid += 1" << endl; if (!(*f_iter)->is_oneway()) { indent(f_service_) << "future = self._reqs[self._seqid] = concurrent.Future()" << endl; } indent(f_service_) << "self.send_" << funname << "("; } else { indent(f_service_) << "self.send_" << funname << "("; } bool first = true; if (gen_twisted_) { // we need a leading comma if there are args, since it's called as maybeDeferred(funcname, // arg) first = false; } for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) { if (first) { first = false; } else { f_service_ << ", "; } f_service_ << (*fld_iter)->get_name(); } f_service_ << ")" << endl; if (!(*f_iter)->is_oneway()) { if (gen_twisted_) { // nothing. See the next block. } else if (gen_tornado_) { indent(f_service_) << "return future" << endl; } else { f_service_ << indent(); if (!(*f_iter)->get_returntype()->is_void()) { f_service_ << "return "; } f_service_ << "self.recv_" << funname << "()" << endl; } } indent_down(); if (gen_twisted_) { // This block injects the body of the send_<> method for twisted (and a cb/eb pair) indent_up(); indent(f_service_) << "d.addCallbacks(" << endl; indent_up(); f_service_ << indent() << "callback=self.cb_send_" << funname << "," << endl << indent() << "callbackArgs=(seqid,)," << endl << indent() << "errback=self.eb_send_" << funname << "," << endl << indent() << "errbackArgs=(seqid,))" << endl; indent_down(); indent(f_service_) << "return d" << endl; indent_down(); f_service_ << endl; indent(f_service_) << "def cb_send_" << funname << "(self, _, seqid):" << endl; indent_up(); if ((*f_iter)->is_oneway()) { // if one-way, fire the deferred & remove it from _reqs f_service_ << indent() << "d = self._reqs.pop(seqid)" << endl << indent() << "d.callback(None)" << endl << indent() << "return d" << endl; } else { f_service_ << indent() << "return self._reqs[seqid]" << endl; } indent_down(); f_service_ << endl; // add an errback to fail the request if the call to send_<> raised an exception indent(f_service_) << "def eb_send_" << funname << "(self, f, seqid):" << endl; indent_up(); f_service_ << indent() << "d = self._reqs.pop(seqid)" << endl << indent() << "d.errback(f)" << endl << indent() << "return d" << endl; indent_down(); } f_service_ << endl; indent(f_service_) << "def send_" << function_signature(*f_iter, false) << ":" << endl; indent_up(); std::string argsname = (*f_iter)->get_name() + "_args"; std::string messageType = (*f_iter)->is_oneway() ? "TMessageType.ONEWAY" : "TMessageType.CALL"; // Serialize the request header if (gen_twisted_ || gen_tornado_) { f_service_ << indent() << "oprot = self._oprot_factory.getProtocol(self._transport)" << endl << indent() << "oprot.writeMessageBegin('" << (*f_iter)->get_name() << "', " << messageType << ", self._seqid)" << endl; } else { f_service_ << indent() << "self._oprot.writeMessageBegin('" << (*f_iter)->get_name() << "', " << messageType << ", self._seqid)" << endl; } f_service_ << indent() << "args = " << argsname << "()" << endl; for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) { f_service_ << indent() << "args." << (*fld_iter)->get_name() << " = " << (*fld_iter)->get_name() << endl; } // Write to the stream if (gen_twisted_ || gen_tornado_) { f_service_ << indent() << "args.write(oprot)" << endl << indent() << "oprot.writeMessageEnd()" << endl << indent() << "oprot.trans.flush()" << endl; } else { f_service_ << indent() << "args.write(self._oprot)" << endl << indent() << "self._oprot.writeMessageEnd()" << endl << indent() << "self._oprot.trans.flush()" << endl; } indent_down(); if (!(*f_iter)->is_oneway()) { std::string resultname = (*f_iter)->get_name() + "_result"; // Open function f_service_ << endl; if (gen_twisted_ || gen_tornado_) { f_service_ << indent() << "def recv_" << (*f_iter)->get_name() << "(self, iprot, mtype, rseqid):" << endl; } else { t_struct noargs(program_); t_function recv_function((*f_iter)->get_returntype(), string("recv_") + (*f_iter)->get_name(), &noargs); f_service_ << indent() << "def " << function_signature(&recv_function) << ":" << endl; } indent_up(); // TODO(mcslee): Validate message reply here, seq ids etc. if (gen_twisted_) { f_service_ << indent() << "d = self._reqs.pop(rseqid)" << endl; } else if (gen_tornado_) { } else { f_service_ << indent() << "iprot = self._iprot" << endl << indent() << "(fname, mtype, rseqid) = iprot.readMessageBegin()" << endl; } f_service_ << indent() << "if mtype == TMessageType.EXCEPTION:" << endl << indent() << indent_str() << "x = TApplicationException()" << endl; if (gen_twisted_) { f_service_ << indent() << indent_str() << "x.read(iprot)" << endl << indent() << indent_str() << "iprot.readMessageEnd()" << endl << indent() << indent_str() << "return d.errback(x)" << endl << indent() << "result = " << resultname << "()" << endl << indent() << "result.read(iprot)" << endl << indent() << "iprot.readMessageEnd()" << endl; } else { f_service_ << indent() << indent_str() << "x.read(iprot)" << endl << indent() << indent_str() << "iprot.readMessageEnd()" << endl << indent() << indent_str() << "raise x" << endl << indent() << "result = " << resultname << "()" << endl << indent() << "result.read(iprot)" << endl << indent() << "iprot.readMessageEnd()" << endl; } // Careful, only return _result if not a void function if (!(*f_iter)->get_returntype()->is_void()) { f_service_ << indent() << "if result.success is not None:" << endl; if (gen_twisted_) { f_service_ << indent() << indent_str() << "return d.callback(result.success)" << endl; } else { f_service_ << indent() << indent_str() << "return result.success" << endl; } } t_struct* xs = (*f_iter)->get_xceptions(); const std::vector<t_field*>& xceptions = xs->get_members(); vector<t_field*>::const_iterator x_iter; for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) { const string& xname = (*x_iter)->get_name(); f_service_ << indent() << "if result." << xname << " is not None:" << endl; if (gen_twisted_) { f_service_ << indent() << indent_str() << "return d.errback(result." << xname << ")" << endl; } else { f_service_ << indent() << indent_str() << "raise result." << xname << "" << endl; } } // Careful, only return _result if not a void function if ((*f_iter)->get_returntype()->is_void()) { if (gen_twisted_) { f_service_ << indent() << "return d.callback(None)" << endl; } else { f_service_ << indent() << "return" << endl; } } else { if (gen_twisted_) { f_service_ << indent() << "return d.errback(TApplicationException(TApplicationException.MISSING_RESULT, \"" << (*f_iter)->get_name() << " failed: unknown result\"))" << endl; } else { f_service_ << indent() << "raise TApplicationException(TApplicationException.MISSING_RESULT, \"" << (*f_iter)->get_name() << " failed: unknown result\")" << endl; } } // Close function indent_down(); } } indent_down(); } /** * Generates a command line tool for making remote requests * * @param tservice The service to generate a remote for. */ void t_py_generator::generate_service_remote(t_service* tservice) { vector<t_function*> functions = tservice->get_functions(); // Get all function from parents t_service* parent = tservice->get_extends(); while (parent != nullptr) { vector<t_function*> p_functions = parent->get_functions(); functions.insert(functions.end(), p_functions.begin(), p_functions.end()); parent = parent->get_extends(); } vector<t_function*>::iterator f_iter; string f_remote_name = package_dir_ + "/" + service_name_ + "-remote"; ofstream_with_content_based_conditional_update f_remote; f_remote.open(f_remote_name.c_str()); f_remote << "#!/usr/bin/env python" << endl << py_autogen_comment() << endl << "import sys" << endl << "import pprint" << endl << "if sys.version_info[0] > 2:" << endl << indent_str() << "from urllib.parse import urlparse" << endl << "else:" << endl << indent_str() << "from urlparse import urlparse" << endl << "from thrift.transport import TTransport, TSocket, TSSLSocket, THttpClient" << endl << "from thrift.protocol.TBinaryProtocol import TBinaryProtocol" << endl << endl; f_remote << "from " << module_ << " import " << service_name_ << endl << "from " << module_ << ".ttypes import *" << endl << endl; f_remote << "if len(sys.argv) <= 1 or sys.argv[1] == '--help':" << endl << indent_str() << "print('')" << endl << indent_str() << "print('Usage: ' + sys.argv[0] + ' [-h host[:port]] [-u url] [-f[ramed]] [-s[sl]] [-novalidate] [-ca_certs certs] [-keyfile keyfile] [-certfile certfile] function [arg1 [arg2...]]')" << endl << indent_str() << "print('')" << endl << indent_str() << "print('Functions:')" << endl; for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) { f_remote << indent_str() << "print(' " << (*f_iter)->get_returntype()->get_name() << " " << (*f_iter)->get_name() << "("; t_struct* arg_struct = (*f_iter)->get_arglist(); const std::vector<t_field*>& args = arg_struct->get_members(); std::vector<t_field*>::size_type num_args = args.size(); bool first = true; for (std::vector<t_field*>::size_type i = 0; i < num_args; ++i) { if (first) { first = false; } else { f_remote << ", "; } f_remote << args[i]->get_type()->get_name() << " " << args[i]->get_name(); } f_remote << ")')" << endl; } f_remote << indent_str() << "print('')" << endl << indent_str() << "sys.exit(0)" << endl << endl; f_remote << "pp = pprint.PrettyPrinter(indent=2)" << endl << "host = 'localhost'" << endl << "port = 9090" << endl << "uri = ''" << endl << "framed = False" << endl << "ssl = False" << endl << "validate = True" << endl << "ca_certs = None" << endl << "keyfile = None" << endl << "certfile = None" << endl << "http = False" << endl << "argi = 1" << endl << endl << "if sys.argv[argi] == '-h':" << endl << indent_str() << "parts = sys.argv[argi + 1].split(':')" << endl << indent_str() << "host = parts[0]" << endl << indent_str() << "if len(parts) > 1:" << endl << indent_str() << indent_str() << "port = int(parts[1])" << endl << indent_str() << "argi += 2" << endl << endl << "if sys.argv[argi] == '-u':" << endl << indent_str() << "url = urlparse(sys.argv[argi + 1])" << endl << indent_str() << "parts = url[1].split(':')" << endl << indent_str() << "host = parts[0]" << endl << indent_str() << "if len(parts) > 1:" << endl << indent_str() << indent_str() << "port = int(parts[1])" << endl << indent_str() << "else:" << endl << indent_str() << indent_str() << "port = 80" << endl << indent_str() << "uri = url[2]" << endl << indent_str() << "if url[4]:" << endl << indent_str() << indent_str() << "uri += '?%s' % url[4]" << endl << indent_str() << "http = True" << endl << indent_str() << "argi += 2" << endl << endl << "if sys.argv[argi] == '-f' or sys.argv[argi] == '-framed':" << endl << indent_str() << "framed = True" << endl << indent_str() << "argi += 1" << endl << endl << "if sys.argv[argi] == '-s' or sys.argv[argi] == '-ssl':" << endl << indent_str() << "ssl = True" << endl << indent_str() << "argi += 1" << endl << endl << "if sys.argv[argi] == '-novalidate':" << endl << indent_str() << "validate = False" << endl << indent_str() << "argi += 1" << endl << endl << "if sys.argv[argi] == '-ca_certs':" << endl << indent_str() << "ca_certs = sys.argv[argi+1]" << endl << indent_str() << "argi += 2" << endl << endl << "if sys.argv[argi] == '-keyfile':" << endl << indent_str() << "keyfile = sys.argv[argi+1]" << endl << indent_str() << "argi += 2" << endl << endl << "if sys.argv[argi] == '-certfile':" << endl << indent_str() << "certfile = sys.argv[argi+1]" << endl << indent_str() << "argi += 2" << endl << endl << "cmd = sys.argv[argi]" << endl << "args = sys.argv[argi + 1:]" << endl << endl << "if http:" << endl << indent_str() << "transport = THttpClient.THttpClient(host, port, uri)" << endl << "else:" << endl << indent_str() << "if ssl:" << endl << indent_str() << indent_str() << "socket = TSSLSocket.TSSLSocket(host, port, " "validate=validate, ca_certs=ca_certs, keyfile=keyfile, certfile=certfile)" << endl << indent_str() << "else:" << endl << indent_str() << indent_str() << "socket = TSocket.TSocket(host, port)" << endl << indent_str() << "if framed:" << endl << indent_str() << indent_str() << "transport = TTransport.TFramedTransport(socket)" << endl << indent_str() << "else:" << endl << indent_str() << indent_str() << "transport = TTransport.TBufferedTransport(socket)" << endl << "protocol = TBinaryProtocol(transport)" << endl << "client = " << service_name_ << ".Client(protocol)" << endl << "transport.open()" << endl << endl; // Generate the dispatch methods bool first = true; for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) { if (first) { first = false; } else { f_remote << "el"; } t_struct* arg_struct = (*f_iter)->get_arglist(); const std::vector<t_field*>& args = arg_struct->get_members(); std::vector<t_field*>::size_type num_args = args.size(); f_remote << "if cmd == '" << (*f_iter)->get_name() << "':" << endl; indent_up(); f_remote << indent() << "if len(args) != " << num_args << ":" << endl << indent() << indent_str() << "print('" << (*f_iter)->get_name() << " requires " << num_args << " args')" << endl << indent() << indent_str() << "sys.exit(1)" << endl << indent() << "pp.pprint(client." << (*f_iter)->get_name() << "("; indent_down(); bool first_arg = true; for (std::vector<t_field*>::size_type i = 0; i < num_args; ++i) { if (first_arg) first_arg = false; else f_remote << " "; if (args[i]->get_type()->is_string()) { f_remote << "args[" << i << "],"; } else { f_remote << "eval(args[" << i << "]),"; } } f_remote << "))" << endl; f_remote << endl; } if (functions.size() > 0) { f_remote << "else:" << endl; f_remote << indent_str() << "print('Unrecognized method %s' % cmd)" << endl; f_remote << indent_str() << "sys.exit(1)" << endl; f_remote << endl; } f_remote << "transport.close()" << endl; // Close service file f_remote.close(); #ifndef _MSC_VER // Make file executable, love that bitwise OR action chmod(f_remote_name.c_str(), S_IRUSR | S_IWUSR | S_IXUSR #ifndef _WIN32 | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH #endif ); #endif // _MSC_VER } /** * Generates a service server definition. * * @param tservice The service to generate a server for. */ void t_py_generator::generate_service_server(t_service* tservice) { // Generate the dispatch methods vector<t_function*> functions = tservice->get_functions(); vector<t_function*>::iterator f_iter; string extends = ""; string extends_processor = ""; if (tservice->get_extends() != nullptr) { extends = type_name(tservice->get_extends()); extends_processor = extends + ".Processor, "; } f_service_ << endl << endl; // Generate the header portion if (gen_zope_interface_) { f_service_ << "@implementer(Iface)" << endl << "class Processor(" << extends_processor << "TProcessor):" << endl; } else { f_service_ << "class Processor(" << extends_processor << "Iface, TProcessor):" << endl; } indent_up(); indent(f_service_) << "def __init__(self, handler):" << endl; indent_up(); if (extends.empty()) { if (gen_zope_interface_) { f_service_ << indent() << "self._handler = Iface(handler)" << endl; } else { f_service_ << indent() << "self._handler = handler" << endl; } f_service_ << indent() << "self._processMap = {}" << endl; } else { if (gen_zope_interface_) { f_service_ << indent() << extends << ".Processor.__init__(self, Iface(handler))" << endl; } else { f_service_ << indent() << extends << ".Processor.__init__(self, handler)" << endl; } } for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) { f_service_ << indent() << "self._processMap[\"" << (*f_iter)->get_name() << "\"] = Processor.process_" << (*f_iter)->get_name() << endl; } f_service_ << indent() << "self._on_message_begin = None" << endl; indent_down(); f_service_ << endl; f_service_ << indent() << "def on_message_begin(self, func):" << endl; indent_up(); f_service_ << indent() << "self._on_message_begin = func" << endl; indent_down(); f_service_ << endl; // Generate the server implementation f_service_ << indent() << "def process(self, iprot, oprot):" << endl; indent_up(); f_service_ << indent() << "(name, type, seqid) = iprot.readMessageBegin()" << endl; f_service_ << indent() << "if self._on_message_begin:" << endl; indent_up(); f_service_ << indent() << "self._on_message_begin(name, type, seqid)" << endl; indent_down(); // TODO(mcslee): validate message // HOT: dictionary function lookup f_service_ << indent() << "if name not in self._processMap:" << endl; indent_up(); f_service_ << indent() << "iprot.skip(TType.STRUCT)" << endl << indent() << "iprot.readMessageEnd()" << endl << indent() << "x = TApplicationException(TApplicationException.UNKNOWN_METHOD, 'Unknown " "function %s' % (name))" << endl << indent() << "oprot.writeMessageBegin(name, TMessageType.EXCEPTION, seqid)" << endl << indent() << "x.write(oprot)" << endl << indent() << "oprot.writeMessageEnd()" << endl << indent() << "oprot.trans.flush()" << endl; if (gen_twisted_) { f_service_ << indent() << "return defer.succeed(None)" << endl; } else { f_service_ << indent() << "return" << endl; } indent_down(); f_service_ << indent() << "else:" << endl; if (gen_twisted_ || gen_tornado_) { f_service_ << indent() << indent_str() << "return self._processMap[name](self, seqid, iprot, oprot)" << endl; } else { f_service_ << indent() << indent_str() << "self._processMap[name](self, seqid, iprot, oprot)" << endl; // Read end of args field, the T_STOP, and the struct close f_service_ << indent() << "return True" << endl; } indent_down(); // Generate the process subfunctions for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) { f_service_ << endl; generate_process_function(tservice, *f_iter); } indent_down(); } /** * Generates a process function definition. * * @param tfunction The function to write a dispatcher for */ void t_py_generator::generate_process_function(t_service* tservice, t_function* tfunction) { (void)tservice; // Open function if (gen_tornado_) { f_service_ << indent() << "@gen.coroutine" << endl << indent() << "def process_" << tfunction->get_name() << "(self, seqid, iprot, oprot):" << endl; } else { f_service_ << indent() << "def process_" << tfunction->get_name() << "(self, seqid, iprot, oprot):" << endl; } indent_up(); string argsname = tfunction->get_name() + "_args"; string resultname = tfunction->get_name() + "_result"; f_service_ << indent() << "args = " << argsname << "()" << endl << indent() << "args.read(iprot)" << endl << indent() << "iprot.readMessageEnd()" << endl; t_struct* xs = tfunction->get_xceptions(); const std::vector<t_field*>& xceptions = xs->get_members(); vector<t_field*>::const_iterator x_iter; // Declare result for non oneway function if (!tfunction->is_oneway()) { f_service_ << indent() << "result = " << resultname << "()" << endl; } if (gen_twisted_) { // Generate the function call t_struct* arg_struct = tfunction->get_arglist(); const std::vector<t_field*>& fields = arg_struct->get_members(); vector<t_field*>::const_iterator f_iter; f_service_ << indent() << "d = defer.maybeDeferred(self._handler." << tfunction->get_name() << ", "; bool first = true; for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { if (first) { first = false; } else { f_service_ << ", "; } f_service_ << "args." << (*f_iter)->get_name(); } f_service_ << ")" << endl; if (tfunction->is_oneway()) { f_service_ << indent() << "d.addErrback(self.handle_exception_" << tfunction->get_name() << ", seqid)" << endl; } else { f_service_ << indent() << "d.addCallback(self.write_results_success_" << tfunction->get_name() << ", result, seqid, oprot)" << endl << indent() << "d.addErrback(self.write_results_exception_" << tfunction->get_name() << ", result, seqid, oprot)" << endl; } f_service_ << indent() << "return d" << endl << endl; indent_down(); if (tfunction->is_oneway()) { indent(f_service_) << "def handle_exception_" << tfunction->get_name() << "(self, error, seqid):" << endl; } else { indent(f_service_) << "def write_results_success_" << tfunction->get_name() << "(self, success, result, seqid, oprot):" << endl; indent_up(); if (!tfunction->get_returntype()->is_void()) { f_service_ << indent() << "result.success = success" << endl; } f_service_ << indent() << "oprot.writeMessageBegin(\"" << tfunction->get_name() << "\", TMessageType.REPLY, seqid)" << endl << indent() << "result.write(oprot)" << endl << indent() << "oprot.writeMessageEnd()" << endl << indent() << "oprot.trans.flush()" << endl << endl; indent_down(); indent(f_service_) << "def write_results_exception_" << tfunction->get_name() << "(self, error, result, seqid, oprot):" << endl; } indent_up(); if (!tfunction->is_oneway()) { f_service_ << indent() << "msg_type = TMessageType.REPLY" << endl; } f_service_ << indent() << "try:" << endl; // Kinda absurd f_service_ << indent() << indent_str() << "error.raiseException()" << endl; if (!tfunction->is_oneway()) { for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) { const string& xname = (*x_iter)->get_name(); f_service_ << indent() << "except " << type_name((*x_iter)->get_type()) << " as " << xname << ":" << endl; indent_up(); f_service_ << indent() << "result." << xname << " = " << xname << endl; indent_down(); } } f_service_ << indent() << "except TTransport.TTransportException:" << endl << indent() << indent_str() << "raise" << endl; if (!tfunction->is_oneway()) { f_service_ << indent() << "except TApplicationException as ex:" << endl << indent() << indent_str() << "logging.exception('TApplication exception in handler')" << endl << indent() << indent_str() << "msg_type = TMessageType.EXCEPTION" << endl << indent() << indent_str() << "result = ex" << endl << indent() << "except Exception:" << endl << indent() << indent_str() << "logging.exception('Unexpected exception in handler')" << endl << indent() << indent_str() << "msg_type = TMessageType.EXCEPTION" << endl << indent() << indent_str() << "result = TApplicationException(TApplicationException.INTERNAL_ERROR, " "'Internal error')" << endl << indent() << "oprot.writeMessageBegin(\"" << tfunction->get_name() << "\", msg_type, seqid)" << endl << indent() << "result.write(oprot)" << endl << indent() << "oprot.writeMessageEnd()" << endl << indent() << "oprot.trans.flush()" << endl; } else { f_service_ << indent() << "except Exception:" << endl << indent() << indent_str() << "logging.exception('Exception in oneway handler')" << endl; } indent_down(); } else if (gen_tornado_) { // Generate the function call t_struct* arg_struct = tfunction->get_arglist(); const std::vector<t_field*>& fields = arg_struct->get_members(); vector<t_field*>::const_iterator f_iter; if (!tfunction->is_oneway()) { indent(f_service_) << "msg_type = TMessageType.REPLY" << endl; } f_service_ << indent() << "try:" << endl; indent_up(); f_service_ << indent(); if (!tfunction->is_oneway() && !tfunction->get_returntype()->is_void()) { f_service_ << "result.success = "; } f_service_ << "yield gen.maybe_future(self._handler." << tfunction->get_name() << "("; bool first = true; for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { if (first) { first = false; } else { f_service_ << ", "; } f_service_ << "args." << (*f_iter)->get_name(); } f_service_ << "))" << endl; indent_down(); if (!tfunction->is_oneway()) { for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) { const string& xname = (*x_iter)->get_name(); f_service_ << indent() << "except " << type_name((*x_iter)->get_type()) << " as " << xname << ":" << endl << indent() << indent_str() << "result." << xname << " = " << xname << endl; } } f_service_ << indent() << "except TTransport.TTransportException:" << endl << indent() << indent_str() << "raise" << endl; if (!tfunction->is_oneway()) { f_service_ << indent() << "except TApplicationException as ex:" << endl << indent() << indent_str() << "logging.exception('TApplication exception in handler')" << endl << indent() << indent_str() << "msg_type = TMessageType.EXCEPTION" << endl << indent() << indent_str() << "result = ex" << endl << indent() << "except Exception:" << endl << indent() << indent_str() << "logging.exception('Unexpected exception in handler')" << endl << indent() << indent_str() << "msg_type = TMessageType.EXCEPTION" << endl << indent() << indent_str() << "result = TApplicationException(TApplicationException.INTERNAL_ERROR, " "'Internal error')" << endl; } else { f_service_ << indent() << "except Exception:" << endl << indent() << indent_str() << "logging.exception('Exception in oneway handler')" << endl; } if (!tfunction->is_oneway()) { f_service_ << indent() << "oprot.writeMessageBegin(\"" << tfunction->get_name() << "\", msg_type, seqid)" << endl << indent() << "result.write(oprot)" << endl << indent() << "oprot.writeMessageEnd()" << endl << indent() << "oprot.trans.flush()" << endl; } // Close function indent_down(); } else { // py // Try block for a function with exceptions // It also catches arbitrary exceptions raised by handler method to propagate them to the client f_service_ << indent() << "try:" << endl; indent_up(); // Generate the function call t_struct* arg_struct = tfunction->get_arglist(); const std::vector<t_field*>& fields = arg_struct->get_members(); vector<t_field*>::const_iterator f_iter; f_service_ << indent(); if (!tfunction->is_oneway() && !tfunction->get_returntype()->is_void()) { f_service_ << "result.success = "; } f_service_ << "self._handler." << tfunction->get_name() << "("; bool first = true; for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { if (first) { first = false; } else { f_service_ << ", "; } f_service_ << "args." << (*f_iter)->get_name(); } f_service_ << ")" << endl; if (!tfunction->is_oneway()) { f_service_ << indent() << "msg_type = TMessageType.REPLY" << endl; } indent_down(); f_service_ << indent() << "except TTransport.TTransportException:" << endl << indent() << indent_str() << "raise" << endl; if (!tfunction->is_oneway()) { for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) { const string& xname = (*x_iter)->get_name(); f_service_ << indent() << "except " << type_name((*x_iter)->get_type()) << " as " << xname << ":" << endl; indent_up(); f_service_ << indent() << "msg_type = TMessageType.REPLY" << endl; f_service_ << indent() << "result." << xname << " = " << xname << endl; indent_down(); } f_service_ << indent() << "except TApplicationException as ex:" << endl << indent() << indent_str() << "logging.exception('TApplication exception in handler')" << endl << indent() << indent_str() << "msg_type = TMessageType.EXCEPTION" << endl << indent() << indent_str() << "result = ex" << endl << indent() << "except Exception:" << endl << indent() << indent_str() << "logging.exception('Unexpected exception in handler')" << endl << indent() << indent_str() << "msg_type = TMessageType.EXCEPTION" << endl << indent() << indent_str() << "result = TApplicationException(TApplicationException.INTERNAL_ERROR, " "'Internal error')" << endl << indent() << "oprot.writeMessageBegin(\"" << tfunction->get_name() << "\", msg_type, seqid)" << endl << indent() << "result.write(oprot)" << endl << indent() << "oprot.writeMessageEnd()" << endl << indent() << "oprot.trans.flush()" << endl; } else { f_service_ << indent() << "except Exception:" << endl << indent() << indent_str() << "logging.exception('Exception in oneway handler')" << endl; } // Close function indent_down(); } } /** * Deserializes a field of any type. */ void t_py_generator::generate_deserialize_field(ostream& out, t_field* tfield, string prefix) { t_type* type = get_true_type(tfield->get_type()); if (type->is_void()) { throw "CANNOT GENERATE DESERIALIZE CODE FOR void TYPE: " + prefix + tfield->get_name(); } string name = prefix + tfield->get_name(); if (type->is_struct() || type->is_xception()) { generate_deserialize_struct(out, (t_struct*)type, name); } else if (type->is_container()) { generate_deserialize_container(out, type, name); } else if (type->is_base_type() || type->is_enum()) { indent(out) << name << " = iprot."; if (type->is_base_type()) { t_base_type::t_base tbase = ((t_base_type*)type)->get_base(); switch (tbase) { case t_base_type::TYPE_VOID: throw "compiler error: cannot serialize void field in a struct: " + name; case t_base_type::TYPE_STRING: if (type->is_binary()) { out << "readBinary()"; } else if(!gen_utf8strings_) { out << "readString()"; } else { out << "readString().decode('utf-8', errors='replace') if sys.version_info[0] == 2 else iprot.readString()"; } break; case t_base_type::TYPE_BOOL: out << "readBool()"; break; case t_base_type::TYPE_I8: out << "readByte()"; break; case t_base_type::TYPE_I16: out << "readI16()"; break; case t_base_type::TYPE_I32: out << "readI32()"; break; case t_base_type::TYPE_I64: out << "readI64()"; break; case t_base_type::TYPE_DOUBLE: out << "readDouble()"; break; default: throw "compiler error: no Python name for base type " + t_base_type::t_base_name(tbase); } } else if (type->is_enum()) { out << "readI32()"; } out << endl; } else { printf("DO NOT KNOW HOW TO DESERIALIZE FIELD '%s' TYPE '%s'\n", tfield->get_name().c_str(), type->get_name().c_str()); } } /** * Generates an unserializer for a struct, calling read() */ void t_py_generator::generate_deserialize_struct(ostream& out, t_struct* tstruct, string prefix) { if (is_immutable(tstruct)) { out << indent() << prefix << " = " << type_name(tstruct) << ".read(iprot)" << endl; } else { out << indent() << prefix << " = " << type_name(tstruct) << "()" << endl << indent() << prefix << ".read(iprot)" << endl; } } /** * Serialize a container by writing out the header followed by * data and then a footer. */ void t_py_generator::generate_deserialize_container(ostream& out, t_type* ttype, string prefix) { string size = tmp("_size"); string ktype = tmp("_ktype"); string vtype = tmp("_vtype"); string etype = tmp("_etype"); t_field fsize(g_type_i32, size); t_field fktype(g_type_i8, ktype); t_field fvtype(g_type_i8, vtype); t_field fetype(g_type_i8, etype); // Declare variables, read header if (ttype->is_map()) { out << indent() << prefix << " = {}" << endl << indent() << "(" << ktype << ", " << vtype << ", " << size << ") = iprot.readMapBegin()" << endl; } else if (ttype->is_set()) { out << indent() << prefix << " = set()" << endl << indent() << "(" << etype << ", " << size << ") = iprot.readSetBegin()" << endl; } else if (ttype->is_list()) { out << indent() << prefix << " = []" << endl << indent() << "(" << etype << ", " << size << ") = iprot.readListBegin()" << endl; } // For loop iterates over elements string i = tmp("_i"); indent(out) << "for " << i << " in range(" << size << "):" << endl; indent_up(); if (ttype->is_map()) { generate_deserialize_map_element(out, (t_map*)ttype, prefix); } else if (ttype->is_set()) { generate_deserialize_set_element(out, (t_set*)ttype, prefix); } else if (ttype->is_list()) { generate_deserialize_list_element(out, (t_list*)ttype, prefix); } indent_down(); // Read container end if (ttype->is_map()) { indent(out) << "iprot.readMapEnd()" << endl; if (is_immutable(ttype)) { indent(out) << prefix << " = TFrozenDict(" << prefix << ")" << endl; } } else if (ttype->is_set()) { indent(out) << "iprot.readSetEnd()" << endl; if (is_immutable(ttype)) { indent(out) << prefix << " = frozenset(" << prefix << ")" << endl; } } else if (ttype->is_list()) { if (is_immutable(ttype)) { indent(out) << prefix << " = tuple(" << prefix << ")" << endl; } indent(out) << "iprot.readListEnd()" << endl; } } /** * Generates code to deserialize a map */ void t_py_generator::generate_deserialize_map_element(ostream& out, t_map* tmap, string prefix) { string key = tmp("_key"); string val = tmp("_val"); t_field fkey(tmap->get_key_type(), key); t_field fval(tmap->get_val_type(), val); generate_deserialize_field(out, &fkey); generate_deserialize_field(out, &fval); indent(out) << prefix << "[" << key << "] = " << val << endl; } /** * Write a set element */ void t_py_generator::generate_deserialize_set_element(ostream& out, t_set* tset, string prefix) { string elem = tmp("_elem"); t_field felem(tset->get_elem_type(), elem); generate_deserialize_field(out, &felem); indent(out) << prefix << ".add(" << elem << ")" << endl; } /** * Write a list element */ void t_py_generator::generate_deserialize_list_element(ostream& out, t_list* tlist, string prefix) { string elem = tmp("_elem"); t_field felem(tlist->get_elem_type(), elem); generate_deserialize_field(out, &felem); indent(out) << prefix << ".append(" << elem << ")" << endl; } /** * Serializes a field of any type. * * @param tfield The field to serialize * @param prefix Name to prepend to field name */ void t_py_generator::generate_serialize_field(ostream& out, t_field* tfield, string prefix) { t_type* type = get_true_type(tfield->get_type()); // Do nothing for void types if (type->is_void()) { throw "CANNOT GENERATE SERIALIZE CODE FOR void TYPE: " + prefix + tfield->get_name(); } if (type->is_struct() || type->is_xception()) { generate_serialize_struct(out, (t_struct*)type, prefix + tfield->get_name()); } else if (type->is_container()) { generate_serialize_container(out, type, prefix + tfield->get_name()); } else if (type->is_base_type() || type->is_enum()) { string name = prefix + tfield->get_name(); indent(out) << "oprot."; if (type->is_base_type()) { t_base_type::t_base tbase = ((t_base_type*)type)->get_base(); switch (tbase) { case t_base_type::TYPE_VOID: throw "compiler error: cannot serialize void field in a struct: " + name; break; case t_base_type::TYPE_STRING: if (type->is_binary()) { out << "writeBinary(" << name << ")"; } else if (!gen_utf8strings_) { out << "writeString(" << name << ")"; } else { out << "writeString(" << name << ".encode('utf-8') if sys.version_info[0] == 2 else " << name << ")"; } break; case t_base_type::TYPE_BOOL: out << "writeBool(" << name << ")"; break; case t_base_type::TYPE_I8: out << "writeByte(" << name << ")"; break; case t_base_type::TYPE_I16: out << "writeI16(" << name << ")"; break; case t_base_type::TYPE_I32: out << "writeI32(" << name << ")"; break; case t_base_type::TYPE_I64: out << "writeI64(" << name << ")"; break; case t_base_type::TYPE_DOUBLE: out << "writeDouble(" << name << ")"; break; default: throw "compiler error: no Python name for base type " + t_base_type::t_base_name(tbase); } } else if (type->is_enum()) { out << "writeI32(" << name << ")"; } out << endl; } else { printf("DO NOT KNOW HOW TO SERIALIZE FIELD '%s%s' TYPE '%s'\n", prefix.c_str(), tfield->get_name().c_str(), type->get_name().c_str()); } } /** * Serializes all the members of a struct. * * @param tstruct The struct to serialize * @param prefix String prefix to attach to all fields */ void t_py_generator::generate_serialize_struct(ostream& out, t_struct* tstruct, string prefix) { (void)tstruct; indent(out) << prefix << ".write(oprot)" << endl; } void t_py_generator::generate_serialize_container(ostream& out, t_type* ttype, string prefix) { if (ttype->is_map()) { indent(out) << "oprot.writeMapBegin(" << type_to_enum(((t_map*)ttype)->get_key_type()) << ", " << type_to_enum(((t_map*)ttype)->get_val_type()) << ", " << "len(" << prefix << "))" << endl; } else if (ttype->is_set()) { indent(out) << "oprot.writeSetBegin(" << type_to_enum(((t_set*)ttype)->get_elem_type()) << ", " << "len(" << prefix << "))" << endl; } else if (ttype->is_list()) { indent(out) << "oprot.writeListBegin(" << type_to_enum(((t_list*)ttype)->get_elem_type()) << ", " << "len(" << prefix << "))" << endl; } if (ttype->is_map()) { string kiter = tmp("kiter"); string viter = tmp("viter"); indent(out) << "for " << kiter << ", " << viter << " in " << prefix << ".items():" << endl; indent_up(); generate_serialize_map_element(out, (t_map*)ttype, kiter, viter); indent_down(); } else if (ttype->is_set()) { string iter = tmp("iter"); indent(out) << "for " << iter << " in " << prefix << ":" << endl; indent_up(); generate_serialize_set_element(out, (t_set*)ttype, iter); indent_down(); } else if (ttype->is_list()) { string iter = tmp("iter"); indent(out) << "for " << iter << " in " << prefix << ":" << endl; indent_up(); generate_serialize_list_element(out, (t_list*)ttype, iter); indent_down(); } if (ttype->is_map()) { indent(out) << "oprot.writeMapEnd()" << endl; } else if (ttype->is_set()) { indent(out) << "oprot.writeSetEnd()" << endl; } else if (ttype->is_list()) { indent(out) << "oprot.writeListEnd()" << endl; } } /** * Serializes the members of a map. * */ void t_py_generator::generate_serialize_map_element(ostream& out, t_map* tmap, string kiter, string viter) { t_field kfield(tmap->get_key_type(), kiter); generate_serialize_field(out, &kfield, ""); t_field vfield(tmap->get_val_type(), viter); generate_serialize_field(out, &vfield, ""); } /** * Serializes the members of a set. */ void t_py_generator::generate_serialize_set_element(ostream& out, t_set* tset, string iter) { t_field efield(tset->get_elem_type(), iter); generate_serialize_field(out, &efield, ""); } /** * Serializes the members of a list. */ void t_py_generator::generate_serialize_list_element(ostream& out, t_list* tlist, string iter) { t_field efield(tlist->get_elem_type(), iter); generate_serialize_field(out, &efield, ""); } /** * Generates the docstring for a given struct. */ void t_py_generator::generate_python_docstring(ostream& out, t_struct* tstruct) { generate_python_docstring(out, tstruct, tstruct, "Attributes"); } /** * Generates the docstring for a given function. */ void t_py_generator::generate_python_docstring(ostream& out, t_function* tfunction) { generate_python_docstring(out, tfunction, tfunction->get_arglist(), "Parameters"); } /** * Generates the docstring for a struct or function. */ void t_py_generator::generate_python_docstring(ostream& out, t_doc* tdoc, t_struct* tstruct, const char* subheader) { bool has_doc = false; stringstream ss; if (tdoc->has_doc()) { has_doc = true; ss << tdoc->get_doc(); } const vector<t_field*>& fields = tstruct->get_members(); if (fields.size() > 0) { if (has_doc) { ss << endl; } has_doc = true; ss << subheader << ":\n"; vector<t_field*>::const_iterator p_iter; for (p_iter = fields.begin(); p_iter != fields.end(); ++p_iter) { t_field* p = *p_iter; ss << " - " << p->get_name(); if (p->has_doc()) { ss << ": " << p->get_doc(); } else { ss << endl; } } } if (has_doc) { generate_docstring_comment(out, "\"\"\"\n", "", ss.str(), "\"\"\"\n"); } } /** * Generates the docstring for a generic object. */ void t_py_generator::generate_python_docstring(ostream& out, t_doc* tdoc) { if (tdoc->has_doc()) { generate_docstring_comment(out, "\"\"\"\n", "", tdoc->get_doc(), "\"\"\"\n"); } } /** * Declares an argument, which may include initialization as necessary. * * @param tfield The field */ string t_py_generator::declare_argument(t_field* tfield) { std::ostringstream result; result << tfield->get_name() << "="; if (tfield->get_value() != nullptr) { result << render_field_default_value(tfield); } else { result << "None"; } return result.str(); } /** * Renders a field default value, returns None otherwise. * * @param tfield The field */ string t_py_generator::render_field_default_value(t_field* tfield) { t_type* type = get_true_type(tfield->get_type()); if (tfield->get_value() != nullptr) { return render_const_value(type, tfield->get_value()); } else { return "None"; } } /** * Renders a function signature of the form 'type name(args)' * * @param tfunction Function definition * @return String of rendered function definition */ string t_py_generator::function_signature(t_function* tfunction, bool interface) { vector<string> pre; vector<string> post; string signature = tfunction->get_name() + "("; if (!(gen_zope_interface_ && interface)) { pre.emplace_back("self"); } signature += argument_list(tfunction->get_arglist(), &pre, &post) + ")"; return signature; } /** * Renders a field list */ string t_py_generator::argument_list(t_struct* tstruct, vector<string>* pre, vector<string>* post) { string result = ""; const vector<t_field*>& fields = tstruct->get_members(); vector<t_field*>::const_iterator f_iter; vector<string>::const_iterator s_iter; bool first = true; if (pre) { for (s_iter = pre->begin(); s_iter != pre->end(); ++s_iter) { if (first) { first = false; } else { result += ", "; } result += *s_iter; } } for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { if (first) { first = false; } else { result += ", "; } result += (*f_iter)->get_name(); } if (post) { for (s_iter = post->begin(); s_iter != post->end(); ++s_iter) { if (first) { first = false; } else { result += ", "; } result += *s_iter; } } return result; } string t_py_generator::type_name(t_type* ttype) { while (ttype->is_typedef()) { ttype = ((t_typedef*)ttype)->get_type(); } t_program* program = ttype->get_program(); if (ttype->is_service()) { return get_real_py_module(program, gen_twisted_, package_prefix_) + "." + ttype->get_name(); } if (program != nullptr && program != program_) { return get_real_py_module(program, gen_twisted_, package_prefix_) + ".ttypes." + ttype->get_name(); } return ttype->get_name(); } /** * Converts the parse type to a Python tyoe */ string t_py_generator::type_to_enum(t_type* type) { type = get_true_type(type); if (type->is_base_type()) { t_base_type::t_base tbase = ((t_base_type*)type)->get_base(); switch (tbase) { case t_base_type::TYPE_VOID: throw "NO T_VOID CONSTRUCT"; case t_base_type::TYPE_STRING: return "TType.STRING"; case t_base_type::TYPE_BOOL: return "TType.BOOL"; case t_base_type::TYPE_I8: return "TType.BYTE"; case t_base_type::TYPE_I16: return "TType.I16"; case t_base_type::TYPE_I32: return "TType.I32"; case t_base_type::TYPE_I64: return "TType.I64"; case t_base_type::TYPE_DOUBLE: return "TType.DOUBLE"; } } else if (type->is_enum()) { return "TType.I32"; } else if (type->is_struct() || type->is_xception()) { return "TType.STRUCT"; } else if (type->is_map()) { return "TType.MAP"; } else if (type->is_set()) { return "TType.SET"; } else if (type->is_list()) { return "TType.LIST"; } throw "INVALID TYPE IN type_to_enum: " + type->get_name(); } /** See the comment inside generate_py_struct_definition for what this is. */ string t_py_generator::type_to_spec_args(t_type* ttype) { while (ttype->is_typedef()) { ttype = ((t_typedef*)ttype)->get_type(); } if (ttype->is_binary()) { return "'BINARY'"; } else if (gen_utf8strings_ && ttype->is_base_type() && reinterpret_cast<t_base_type*>(ttype)->is_string()) { return "'UTF8'"; } else if (ttype->is_base_type() || ttype->is_enum()) { return "None"; } else if (ttype->is_struct() || ttype->is_xception()) { return "[" + type_name(ttype) + ", None]"; } else if (ttype->is_map()) { return "(" + type_to_enum(((t_map*)ttype)->get_key_type()) + ", " + type_to_spec_args(((t_map*)ttype)->get_key_type()) + ", " + type_to_enum(((t_map*)ttype)->get_val_type()) + ", " + type_to_spec_args(((t_map*)ttype)->get_val_type()) + ", " + (is_immutable(ttype) ? "True" : "False") + ")"; } else if (ttype->is_set()) { return "(" + type_to_enum(((t_set*)ttype)->get_elem_type()) + ", " + type_to_spec_args(((t_set*)ttype)->get_elem_type()) + ", " + (is_immutable(ttype) ? "True" : "False") + ")"; } else if (ttype->is_list()) { return "(" + type_to_enum(((t_list*)ttype)->get_elem_type()) + ", " + type_to_spec_args(((t_list*)ttype)->get_elem_type()) + ", " + (is_immutable(ttype) ? "True" : "False") + ")"; } throw "INVALID TYPE IN type_to_spec_args: " + ttype->get_name(); } THRIFT_REGISTER_GENERATOR( py, "Python", " zope.interface: Generate code for use with zope.interface.\n" " twisted: Generate Twisted-friendly RPC services.\n" " tornado: Generate code for use with Tornado.\n" " no_utf8strings: Do not Encode/decode strings using utf8 in the generated code. Basically no effect for Python 3.\n" " coding=CODING: Add file encoding declare in generated file.\n" " slots: Generate code using slots for instance members.\n" " dynamic: Generate dynamic code, less code generated but slower.\n" " dynbase=CLS Derive generated classes from class CLS instead of TBase.\n" " dynfrozen=CLS Derive generated immutable classes from class CLS instead of TFrozenBase.\n" " dynexc=CLS Derive generated exceptions from CLS instead of TExceptionBase.\n" " dynfrozenexc=CLS Derive generated immutable exceptions from CLS instead of TFrozenExceptionBase.\n" " dynimport='from foo.bar import CLS'\n" " Add an import line to generated code to find the dynbase class.\n" " package_prefix='top.package.'\n" " Package prefix for generated files.\n" " old_style: Deprecated. Generate old-style classes.\n")
[ "jv@jviotti.com" ]
jv@jviotti.com
db9868ced662aa6d2cee1d3972bd02432ce30076
59fa837fb7200915b5a30433762f099dc6aaa9d1
/lib/Process.h
dae0200f7743d0db3b5ee612fb5b88c1df089e8f
[ "MIT" ]
permissive
Teemperor/Nils
07a9741d86e2eaf74c7a4e1d3416b644d2211aeb
47977dd7fb87eb60d3eb51e5c479d11c407a6f83
refs/heads/master
2020-03-18T18:02:31.069411
2018-06-13T16:27:54
2018-06-13T16:27:54
135,067,922
0
0
null
2018-05-29T08:05:56
2018-05-27T17:35:28
C++
UTF-8
C++
false
false
570
h
#ifndef NILS_PROCESS_H #define NILS_PROCESS_H #include <string> #include <vector> class Process { std::string StdOut; int ExitCode = 0; std::string Exe; int filedes[2]; pid_t pid; public: Process() = default; Process(const std::string &Exe, const std::vector<std::string> &Args, const std::string &WorkingDir); void wait(); const std::string &getStdOut() const { return StdOut; } int getExitCode() const { return ExitCode; } const std::string &getExe() const { return Exe; } }; #endif //NILS_PROCESS_H
[ "teemperor@gmail.com" ]
teemperor@gmail.com
bd9efc0cd9d4f5c9cd765033f55aa83f3860eebd
19f6ebabf9f503d116697798ab83ff52f5cf313f
/src/dwarf.cc
b12bac4c2de7b223e57d9f1228ed56664abb67c3
[]
no_license
zyklyndon/CS246-Final-Project
5cbd5d10d8a09f493c99d75674d407d57b0e629b
d64ae889b3b84c8544bd89e33d9c72e1e90e07b9
refs/heads/main
2023-04-20T21:26:35.775464
2021-05-04T20:45:54
2021-05-04T20:45:54
364,317,876
0
0
null
null
null
null
UTF-8
C++
false
false
492
cc
#include "dwarf.h" #include <math.h> #include "character.h" #include "floor.h" using namespace std; dwarf::dwarf(int row, int col, Floor *f):enemy{100,20,30,row,col,f,Type::Dwarf} {} int dwarf::getGold(){ return 2; } string dwarf::getSType(){ return "Dwarf"; } enemy*dwarf::createEnemy(int row, int col, Floor *f){ enemy* d = new dwarf{row,col,f}; return d; } void dwarf::beAttackedBy(character &c){ c.attack(*this); if(hp<=0){ f->notified(*this,c); } }
[ "lyndon.zhong@praemo.com" ]
lyndon.zhong@praemo.com
a5a99203ab659aec930bd1ddc6cc09fa0603f248
e6d2fa803344cdce7375bbb3b9d0b9643aff58d6
/93-restore-ip-addresses/main.cc
e2a5c6db355fd4a4e431d214e9675cb5976a1c17
[]
no_license
ArisQ/leetcode
511303d22defc584ff1fe410ae79bca8376d0a29
023894242fc36f7b7e67ed33926858c09d27618b
refs/heads/master
2020-04-04T23:09:18.712895
2020-02-28T03:30:43
2020-02-28T03:30:43
156,348,900
0
0
null
2019-08-13T14:11:57
2018-11-06T08:13:24
C++
UTF-8
C++
false
false
2,587
cc
#define CATCH_CONFIG_MAIN #include <catch.hpp> #include <set> using namespace std; ostream &operator<<(ostream &os, const vector<int> &array) { for (auto element:array) { os.width(3); os << element; } os << endl; return os; } class Solution { vector<string> result; vector<int> dot; int n; public: vector<string> restoreIpAddresses(string s) { //0-255 n = s.size(); dot.resize(3); restoreIpAddresses(s, 0, 0); return result; } void restoreIpAddresses(string &s, int start, int part) { if (part == 3) { if (isValid(s, start, n - 1)) { string ip; ip.reserve(n + 3); int iter = 0; for (auto dotPos:dot) { for (; iter <= dotPos; ++iter) ip.push_back(s[iter]); ip.push_back('.'); } for (; iter < n; ++iter) ip.push_back(s[iter]); cout << iter << endl; result.push_back(ip); cout << ip << endl; cout << dot << endl; } return; } for (int i = 0; i < 3 && start + i < n; ++i) { if (isValid(s, start, start + i)) { dot[part] = start + i; restoreIpAddresses(s, start + i + 1, part + 1); } } } bool isValid(const string &s, int start, int end) { //[start,end] //0 0-1 0-1-2 if (end - start == 0) return true; if (end - start == 1 && s[start] != '0') return true; if (end - start == 2) { if (s[start] == '1') return true; if (s[start] == '2' && s[start + 1] < '5') return true; if (s[start] == '2' && s[start + 1] == '5' && s[start + 2] < '6') return true; } return false; } }; TEST_CASE("Restore IP Addresses") { string input = "25525511135"; vector<string> output{"255.255.11.135", "255.255.111.35"}; auto answer = Solution().restoreIpAddresses(input); REQUIRE(multiset<string>(answer.begin(), answer.end()) == multiset<string>(output.begin(), output.end())); } TEST_CASE("Restore IP Addresses - 0000") { string input = "0000"; vector<string> output{"0.0.0.0"}; auto answer = Solution().restoreIpAddresses(input); REQUIRE(multiset<string>(answer.begin(), answer.end()) == multiset<string>(output.begin(), output.end())); }
[ "qiaoli.pg@gmail.com" ]
qiaoli.pg@gmail.com
b5318116a2629624e6502f2bb7bf2e3d13d41c2f
97ecc5fde4c31ced724f99560960fdd6d2fa9de5
/muscle/libMUSCLE/muscle.h
7a22ae895194697c5084fe9ac2d2df5b4b2d360b
[ "LicenseRef-scancode-public-domain", "BSD-3-Clause" ]
permissive
marbl/parsnp
53373c36d10afb08617c2f7aa263550077a88adc
6e9586968406fbb8dc4a1eda2a78ef5aa88321ea
refs/heads/master
2023-09-05T01:25:13.798862
2023-07-27T16:07:35
2023-07-27T16:07:35
21,587,852
100
19
NOASSERTION
2023-08-17T18:58:21
2014-07-07T21:42:06
C++
UTF-8
C++
false
false
12,069
h
#if DEBUG && !_DEBUG #define _DEBUG 1 #endif #if _DEBUG && !DEBUG #define DEBUG 1 #endif #if _MSC_VER #define TIMING 0 #endif #define VER_3_52 0 #ifdef _MSC_VER // Miscrosoft compiler #pragma warning(disable : 4800) // disable int-bool conversion warning #pragma warning(disable : 4996) // deprecated names like strdup, isatty. #define _WIN32_WINNT 0x0400 // AED 9/27/5: fix for missing IsDebuggerPresent() in VS 2005 #endif #define MUSCLE_LONG_VERSION "MUSCLE v3.7 by Robert C. Edgar" #define MUSCLE_MAJOR_VERSION "3" #define MUSCLE_MINOR_VERSION "7" #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include "threadstorage.h" #define DOUBLE_AFFINE 0 #define SINGLE_AFFINE 1 #define PAF 0 #include "types.h" #include "intmath.h" #include "alpha.h" #include "params.h" #ifndef _WIN32 #define stricmp strcasecmp #define strnicmp strncasecmp #define _snprintf snprintf #define _fsopen(name, mode, share) fopen((name), (mode)) #endif #if DEBUG #undef assert #define assert(b) Call_MY_ASSERT(__FILE__, __LINE__, b, #b) void Call_MY_ASSERT(const char *file, int line, bool b, const char *msg); #else #define assert(exp) ((void)0) #endif namespace muscle { extern TLS<int> g_argc; extern TLS<char **> g_argv; #define Rotate(a, b, c) { SCORE *tmp = a; a = b; b = c; c = tmp; } const double VERY_LARGE_DOUBLE = 1e20; extern TLS<unsigned> g_uTreeSplitNode1; extern TLS<unsigned> g_uTreeSplitNode2; // Number of elements in array a[] #define countof(a) (sizeof(a)/sizeof(a[0])) // Maximum of two of any type #define Max2(a, b) ((a) > (b) ? (a) : (b)) // Maximum of three of any type #define Max3(a, b, c) Max2(Max2(a, b), c) // Minimum of two of any type #define Min2(a, b) ((a) < (b) ? (a) : (b)) // Maximum of four of any type #define Max4(a, b, c, d) Max2(Max2(a, b), Max2(c, d)) const double VERY_NEGATIVE_DOUBLE = -9e29; const float VERY_NEGATIVE_FLOAT = (float) -9e29; const double BLOSUM_DIST = 0.62; // todo settable // insane value for uninitialized variables const unsigned uInsane = 8888888; const int iInsane = 8888888; const SCORE scoreInsane = 8888888; const char cInsane = (char) 0xcd; // int 3 instruction, used e.g. for unint. memory const double dInsane = VERY_NEGATIVE_DOUBLE; const float fInsane = VERY_NEGATIVE_FLOAT; const char INVALID_STATE = '*'; const BASETYPE BTInsane = (BASETYPE) dInsane; const WEIGHT wInsane = BTInsane; extern TLS<double> g_dNAN; void Quit(const char szFormat[], ...); void Warning(const char szFormat[], ...); void TrimBlanks(char szStr[]); void TrimLeadingBlanks(char szStr[]); void TrimTrailingBlanks(char szStr[]); void Log(const char szFormat[], ...); bool Verbose(); const char *ScoreToStr(SCORE Score); const char *ScoreToStrL(SCORE Score); SCORE StrToScore(const char *pszStr); void Break(); double VecSum(const double v[], unsigned n); bool IsValidInteger(const char *Str); bool IsValidSignedInteger(const char *Str); bool IsValidIdentifier(const char *Str); bool IsValidFloatChar(char c); bool isident(char c); bool isidentf(char c); void TreeFromSeqVect(const SeqVect &c, Tree &tree, CLUSTER Cluster, DISTANCE Distance, ROOT Root, const char *SaveFileName = 0); void TreeFromMSA(const MSA &msa, Tree &tree, CLUSTER Cluster, DISTANCE Distance, ROOT Root, const char *SaveFileName = 0); void StripGaps(char szStr[]); void StripWhitespace(char szStr[]); const char *GetTimeAsStr(); unsigned CalcBLOSUMWeights(MSA &Aln, ClusterTree &BlosumCluster); void CalcGSCWeights(MSA &Aln, const ClusterTree &BlosumCluster); void AssertNormalized(const PROB p[]); void AssertNormalizedOrZero(const PROB p[]); void AssertNormalized(const double p[]); bool VectorIsZero(const double dValues[], unsigned n); void VectorSet(double dValues[], unsigned n, double d); bool VectorIsZero(const float dValues[], unsigned n); void VectorSet(float dValues[], unsigned n, float d); // @@TODO should be "not linux" #if _WIN32 double log2(double x); // Defined in <math.h> on Linux #endif double pow2(double x); double lnTolog2(double ln); double lp2(double x); SCORE SumLog(SCORE x, SCORE y); SCORE SumLog(SCORE x, SCORE y, SCORE z); SCORE SumLog(SCORE w, SCORE x, SCORE y, SCORE z); double lp2Fast(double x); double SumLogFast(double x, double y); double SumLogFast(double x, double y, double z); double SumLogFast(double w, double x, double y, double z); void chkmem(const char szMsg[] = ""); void Normalize(PROB p[], unsigned n); void Normalize(PROB p[], unsigned n, double dRequiredTotal); void NormalizeUnlessZero(PROB p[], unsigned n); void DebugPrintf(const char szFormat[], ...); void SetListFileName(const char *ptrListFileName, bool bAppend); void ModelFromAlign(const char *strInputFileName, const char *strModelFileName, double dMaxNIC); double GetMemUseMB(); double GetRAMSizeMB(); double GetPeakMemUseMB(); void CheckMemUse(); const char *ElapsedTimeAsString(); char *SecsToHHMMSS(long lSecs, char szStr[]); double GetCPUGHz(); SCORE GetBlosum62(unsigned uLetterA, unsigned uLetterB); SCORE GetBlosum62d(unsigned uLetterA, unsigned uLetterB); SCORE GetBlosum50(unsigned uLetterA, unsigned uLetterB); void AssertNormalizedDist(const PROB p[], unsigned N); void CmdLineError(const char *Format, ...); void Fatal(const char *Format, ...); void InitCmd(); void ExecCommandLine(int argc, char *argv[]); void DoCmd(); void SetLogFile(); void NameFromPath(const char szPath[], char szName[], unsigned uBytes); char *strsave(const char *s); void DistKmer20_3(const SeqVect &v, DistFunc &DF); void DistKbit20_3(const SeqVect &v, DistFunc &DF); void DistKmer6_6(const SeqVect &v, DistFunc &DF); void DistKmer4_6(const SeqVect &v, DistFunc &DF); void DistPWKimura(const SeqVect &v, DistFunc &DF); void FastDistKmer(const SeqVect &v, DistFunc &DF); void DistUnaligned(const SeqVect &v, DISTANCE DistMethod, DistFunc &DF); double PctIdToMAFFTDist(double dPctId); double KimuraDist(double dPctId); void SetFastParams(); void AssertProfsEq(const ProfPos *PA, unsigned uLengthA, const ProfPos *PB, unsigned uLengthB); void ValidateMuscleIds(const MSA &msa); void ValidateMuscleIds(const Tree &tree); void TraceBackToPath(int **TraceBack, unsigned uLengthA, unsigned uLengthB, PWPath &Path); void BitTraceBack(char **TraceBack, unsigned uLengthA, unsigned uLengthB, char LastEdge, PWPath &Path); SCORE AlignTwoMSAs(const MSA &msa1, const MSA &msa2, MSA &msaOut, PWPath &Path, bool bLockLeft = false, bool bLockRight = false); SCORE AlignTwoProfs( const ProfPos *PA, unsigned uLengthA, WEIGHT wA, const ProfPos *PB, unsigned uLengthB, WEIGHT wB, PWPath &Path, ProfPos **ptrPout, unsigned *ptruLengthOut); void AlignTwoProfsGivenPath(const PWPath &Path, const ProfPos *PA, unsigned uLengthA, WEIGHT wA, const ProfPos *PB, unsigned uLengthB, WEIGHT wB, ProfPos **ptrPOut, unsigned *ptruLengthOut); void AlignTwoMSAsGivenPathSW(const PWPath &Path, const MSA &msaA, const MSA &msaB, MSA &msaCombined); void AlignTwoMSAsGivenPath(const PWPath &Path, const MSA &msaA, const MSA &msaB, MSA &msaCombined); SCORE FastScorePath2(const ProfPos *PA, unsigned uLengthA, const ProfPos *PB, unsigned uLengthB, const PWPath &Path); SCORE GlobalAlignDiags(const ProfPos *PA, unsigned uLengthA, const ProfPos *PB, unsigned uLengthB, PWPath &Path); SCORE GlobalAlignSimple(const ProfPos *PA, unsigned uLengthA, const ProfPos *PB, unsigned uLengthB, PWPath &Path); SCORE GlobalAlignSP(const ProfPos *PA, unsigned uLengthA, const ProfPos *PB, unsigned uLengthB, PWPath &Path); SCORE GlobalAlignSPN(const ProfPos *PA, unsigned uLengthA, const ProfPos *PB, unsigned uLengthB, PWPath &Path); SCORE GlobalAlignLE(const ProfPos *PA, unsigned uLengthA, const ProfPos *PB, unsigned uLengthB, PWPath &Path); void CalcThreeWayWeights(const Tree &tree, unsigned uNode1, unsigned uNode2, WEIGHT *Weights); SCORE GlobalAlignSS(const Seq &seqA, const Seq &seqB, PWPath &Path); bool RefineHoriz(MSA &msaIn, const Tree &tree, unsigned uIters, bool bLockLeft, bool bLockRight); bool RefineVert(MSA &msaIn, const Tree &tree, unsigned uIters); SCORE GlobalAlignNoDiags(const ProfPos *PA, unsigned uLengthA, const ProfPos *PB, unsigned uLengthB, PWPath &Path); void SetInputFileName(const char *pstrFileName); void SetIter(unsigned uIter); void IncIter(); void SetMaxIters(unsigned uMaxIters); void Progress(unsigned uStep, unsigned uTotalSteps); void Progress(const char *szFormat, ...); void SetStartTime(); void ProgressStepsDone(); void SetProgressDesc(const char szDesc[]); void SetSeqStats(unsigned uSeqCount, unsigned uMaxL, unsigned uAvgL); void SetNewHandler(); void SaveCurrentAlignment(); void SetCurrentAlignment(MSA &msa); void SetOutputFileName(const char *out); #if DEBUG void SetMuscleSeqVect(SeqVect &v); void SetMuscleInputMSA(MSA &msa); void ValidateMuscleIds(const MSA &msa); void ValidateMuscleIds(const Tree &tree); #else #define SetMuscleSeqVect(x) /* empty */ #define SetMuscleInputMSA(x) /* empty */ #define ValidateMuscleIds(x) /* empty */ #endif void ProcessArgVect(int argc, char *argv[]); void ProcessArgStr(const char *Str); void Usage(); void SetParams(); void SortCounts(const FCOUNT fcCounts[], unsigned SortOrder[]); unsigned ResidueGroupFromFCounts(const FCOUNT fcCounts[]); FCOUNT SumCounts(const FCOUNT Counts[]); bool FlagOpt(const char *Name); const char *ValueOpt(const char *Name); void DoMuscle(); void ProfDB(); void DoSP(); void ProgAlignSubFams(); void Run(); void ListParams(); void OnException(); void SetSeqWeightMethod(SEQWEIGHT Method); SEQWEIGHT GetSeqWeightMethod(); WEIGHT GetMuscleSeqWeightById(unsigned uId); void ListDiagSavings(); void CheckMaxTime(); const char *MaxSecsToStr(); unsigned long GetStartTime(); void ProgressiveAlign(const SeqVect &v, const Tree &GuideTree, MSA &a); ProgNode *ProgressiveAlignE(const SeqVect &v, const Tree &GuideTree, MSA &a); void CalcDistRangeKmer6_6(const MSA &msa, unsigned uRow, float Dist[]); void CalcDistRangeKmer20_3(const MSA &msa, unsigned uRow, float Dist[]); void CalcDistRangeKmer20_4(const MSA &msa, unsigned uRow, float Dist[]); void CalcDistRangePctIdKimura(const MSA &msa, unsigned uRow, float Dist[]); void CalcDistRangePctIdLog(const MSA &msa, unsigned uRow, float Dist[]); void MakeRootMSA(const SeqVect &v, const Tree &GuideTree, ProgNode Nodes[], MSA &a); void MakeRootMSABrenner(SeqVect &v, const Tree &GuideTree, ProgNode Nodes[], MSA &a); void Refine(); void Local(); void Profile(); void PPScore(); void UPGMA2(const DistCalc &DC, Tree &tree, LINKAGE Linkage); char *GetFastaSeq(FILE *f, unsigned *ptrSeqLength, char **ptrLabel, bool DeleteGaps = true); SCORE SW(const ProfPos *PA, unsigned uLengthA, const ProfPos *PB, unsigned uLengthB, PWPath &Path); void TraceBackSW(const ProfPos *PA, unsigned uLengthA, const ProfPos *PB, unsigned uLengthB, const SCORE *DPM_, const SCORE *DPD_, const SCORE *DPI_, unsigned uPrefixLengthAMax, unsigned uPrefixLengthBMax, PWPath &Path); void DiffPaths(const PWPath &p1, const PWPath &p2, unsigned Edges1[], unsigned *ptruDiffCount1, unsigned Edges2[], unsigned *ptruDiffCount2); void SetPPScore(bool bRespectFlagOpts = true); void SetPPScore(PPSCORE p); SCORE GlobalAlignDimer(const ProfPos *PA, unsigned uLengthA, const ProfPos *PB, unsigned uLengthB, PWPath &Path); bool MissingCommand(); void Credits(); void ProfileProfile(MSA &msa1, MSA &msa2, MSA &msaOut); void MHackStart(SeqVect &v); void MHackEnd(MSA &msa); void WriteScoreFile(const MSA &msa); char ConsensusChar(const ProfPos &PP); void Stabilize(const MSA &msa, MSA &msaStable); void MuscleOutput(MSA &msa); DYN_PTR_SCOREMATRIX ReadMx(TextFile &File); void MemPlus(size_t Bytes, char *Where); void MemMinus(size_t Bytes, char *Where); } // namespace muscle
[ "treangen@gmail.com" ]
treangen@gmail.com
89773bc4d40786f9a3c5bcc755cee09501ca50a8
f1cce33dd2cd4b50a2934105142ba09081331e68
/templates/cpp-template-default/proj.win8.1-universal/App.Shared/Cocos2dRenderer.h
a6f7a9c2a364bfcd6a9b76e549271c75dd657d83
[]
no_license
Dsnoi/cocos2d-x
221301030c2f635cfb902b809aaa11a632c4e2a0
f6276dd4b3afa620c6a65a192d3e5ca7bc289bde
refs/heads/v3
2020-05-25T11:28:02.992458
2015-04-21T01:50:54
2015-04-21T01:50:54
34,305,451
1
0
null
2015-04-21T05:05:17
2015-04-21T05:05:17
null
UTF-8
C++
false
false
1,795
h
/* * cocos2d-x http://www.cocos2d-x.org * * Copyright (c) 2010-2014 - cocos2d-x community * * Portions Copyright (c) Microsoft Open Technologies, Inc. * All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include <agile.h> #include "cocos2d.h" class AppDelegate; namespace cocos2d { class Cocos2dRenderer { public: Cocos2dRenderer(int width, int height, float dpi, Windows::Graphics::Display::DisplayOrientations orientation, Windows::UI::Core::CoreDispatcher^ dispathcer, Windows::UI::Xaml::Controls::Panel^ panel); ~Cocos2dRenderer(); void Draw(GLsizei width, GLsizei height, float dpi, Windows::Graphics::Display::DisplayOrientations orientation); void QueuePointerEvent(PointerEventType type, Windows::UI::Core::PointerEventArgs^ args); void Pause(); void Resume(); void DeviceLost(); private: int m_width; int m_height; float m_dpi; // The AppDelegate for the Cocos2D app AppDelegate* m_app; Platform::Agile<Windows::UI::Core::CoreDispatcher> m_dispatcher; Platform::Agile<Windows::UI::Xaml::Controls::Panel> m_panel; Windows::Graphics::Display::DisplayOrientations m_orientation; }; }
[ "dalestam@microsoft.com" ]
dalestam@microsoft.com
5f98237b96d286a8ab2983d0889ed5d24bc082c5
1d9e84bad49940d2b8759dbcdf7411413c57d431
/git-bisect.tpp
79c8e4d71cb28d030710bdb1caca8f3210cbc83d
[]
no_license
amhk/git-talk
854fbdca1bc8c247a3b4f4947a2789bf8b7d52f3
8e0295a7be58dafaf011923d78a9e4e0d7e38af8
refs/heads/master
2021-01-23T03:54:24.271598
2012-10-25T12:58:16
2012-10-25T12:58:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
281
tpp
titl git-bisect(1) syno git bisect [start|good|bad] item Find which commit introduced degrade item Binary search, $\mathcal{O}(\mathrm{log} n)$ item Automatically jumps between candidate commits ite2 User to say if a candidate is good or bad ite2 Incrementally narrower list
[ "marten.kongstad@gmail.com" ]
marten.kongstad@gmail.com
7a95fde34b0cbec3a898b0f677014a2801311416
5dd204916f40ab76f0d9232727f5b96112588421
/exploracio/src/troba_fronteres.cpp
01fa548a70d28aeea6bd8b0b54d290cb990a1d1f
[]
no_license
gerardPlanella/HomeSoundSystem
58f24f1d66788dc7ac1a8629828bcd0963e5cb1a
28af79870638896cc658d7809427a8554a05035f
refs/heads/master
2022-10-18T17:04:56.438788
2020-06-15T10:07:38
2020-06-15T10:07:38
247,017,652
1
0
null
null
null
null
UTF-8
C++
false
false
14,449
cpp
#include "troba_fronteres.h" TrobaFronteres::TrobaFronteres(ros::NodeHandle& nh) { nh_ = nh; nh_.param<int>("tamany_min_frontera", min_frontier_size_, 5); fronteres_pub_ = nh_.advertise<exploracio::Fronteres>("fronteres", 1); mapa_fronteres_pub_ = nh_.advertise<nav_msgs::OccupancyGrid>("mapa_fronteres", 1); mapa_lliures_pub_ = nh_.advertise<nav_msgs::OccupancyGrid>("mapa_lliures", 1); mapa_filtrat_pub_ = nh_.advertise<nav_msgs::OccupancyGrid>("mapa_filtrat", 1); markers_pub_ = nh_.advertise<visualization_msgs::MarkerArray>("markers", 1); map_sub_ = nh_.subscribe("/map", 1, &TrobaFronteres::mapCallback,this); } void TrobaFronteres::mapCallback(const nav_msgs::OccupancyGrid::ConstPtr& msg) { ROS_INFO("mapa rebut!"); nav_msgs::OccupancyGrid mapa_occupacio = *msg; nav_msgs::OccupancyGrid mapa_fronteres = *msg; nav_msgs::OccupancyGrid mapa_lliures = *msg; // reseteja mapes mapa_fronteres.data.assign(mapa_fronteres.data.size(), 0); mapa_lliures.data.assign(mapa_lliures.data.size(), 0); // FILTRAR CEL·LES LLIURES DESCONNECTADES // crea mapa lliures (assigna si és lliure cada cel·la) for(int i = 0; i < mapa_lliures.data.size(); ++i) { if(mapa_occupacio.data[i] == 0) mapa_lliures.data[i] = 100; //else // mapa_lliures.data[i] = 0; } // Etiqueta lliures (connected cells) std::map<int,int> labels_lliures_sizes; std::vector<int> labels_lliures = twoPassLabeling(mapa_lliures, labels_lliures_sizes); // Classifiquem com a desconegudes tot els grups lliures menys el més gran int remaining_label = std::max_element(labels_lliures_sizes.begin(), labels_lliures_sizes.end(), [] (const std::pair<int,int> & p1, const std::pair<int,int> & p2) {return p1.second < p2.second;})->first; for(int i = 0; i < mapa_occupacio.data.size(); ++i) { if (mapa_occupacio.data[i] == 0 and labels_lliures[i] != remaining_label) { mapa_occupacio.data[i] = -1; mapa_lliures.data[i] = 0; } } // publicar mapa_lliures mapa_lliures_pub_.publish(mapa_lliures); ROS_INFO("mapa de lliures publicat!"); // publicar mapa_lliures mapa_filtrat_pub_.publish(mapa_occupacio); ROS_INFO("mapa filtrat publicat!"); // TROBAR FRONTERES // crea mapa fronteres (assigna si és frontera cada cel·la) for(int i = 0; i < mapa_fronteres.data.size(); ++i) { if(esFrontera(i, mapa_occupacio)) mapa_fronteres.data[i] = 100; //else // mapa_fronteres.data[i] = 0; } // publicar mapa_fronteres mapa_fronteres_pub_.publish(mapa_fronteres); ROS_INFO("mapa de fronteres publicat!"); // Etiqueta fronteres (connected cells) std::map<int,int> labels_sizes; std::vector<int> labels = twoPassLabeling(mapa_fronteres, labels_sizes); // Crea i omple missatge fronteres exploracio::Fronteres fronteres_msg; fronteres_msg.header = msg->header; fronteres_msg.fronteres.clear(); for (int i = 0; i < labels.size(); ++i) { if(labels[i]!=0) //cel·la etiquetada { // Si tamany frontera massa petit, continuem if (labels_sizes[labels[i]] < min_frontier_size_) continue; // Busca frontera ja existent bool new_label = true; for (unsigned int j = 0; j < fronteres_msg.fronteres.size(); j++) { // trobada if (fronteres_msg.fronteres[j].id == labels[i]) { fronteres_msg.fronteres[j].celles_celles.push_back(i); fronteres_msg.fronteres[j].celles_punts.push_back(cell2point(i,mapa_fronteres)); new_label = false; break; } } // no trobada: creem nova frontera if (new_label) { exploracio::Frontera nova_frontera; nova_frontera.id = labels[i]; nova_frontera.size = labels_sizes[labels[i]]; nova_frontera.celles_celles.push_back(i); nova_frontera.celles_punts.push_back(cell2point(i,mapa_fronteres)); fronteres_msg.fronteres.push_back(nova_frontera); } } } // Calcula cella central for(unsigned int i = 0; i < fronteres_msg.fronteres.size(); ++i) { int label = fronteres_msg.fronteres[i].id; // order the frontier cells std::deque<int> ordered_cells(0); ordered_cells.push_back(fronteres_msg.fronteres[i].celles_celles.front()); while (ordered_cells.size() < fronteres_msg.fronteres[i].size) { int initial_size = ordered_cells.size(); // connect cells to first cell std::vector<int> frontAdjacentPoints = getAdjacentPoints(ordered_cells.front(), mapa_fronteres); for (unsigned int k = 0; k<frontAdjacentPoints.size(); k++) if (frontAdjacentPoints[k] != -1 && labels[frontAdjacentPoints[k]] == label && std::find(ordered_cells.begin(), ordered_cells.end(), frontAdjacentPoints[k]) == ordered_cells.end() ) { ordered_cells.push_front(frontAdjacentPoints[k]); break; } // connect cells to last cell std::vector<int> backAdjacentPoints = getAdjacentPoints(ordered_cells.back(), mapa_fronteres); for (unsigned int k = 0; k<backAdjacentPoints.size(); k++) if (backAdjacentPoints[k] != -1 && labels[backAdjacentPoints[k]] == label && std::find(ordered_cells.begin(), ordered_cells.end(), backAdjacentPoints[k]) == ordered_cells.end() ) { ordered_cells.push_back(backAdjacentPoints[k]); break; } if (initial_size == ordered_cells.size() && ordered_cells.size() < fronteres_msg.fronteres[i].size) break; } // center cell fronteres_msg.fronteres[i].centre_cella = ordered_cells[ordered_cells.size() / 2]; fronteres_msg.fronteres[i].centre_punt = cell2point(fronteres_msg.fronteres[i].centre_cella, mapa_fronteres); // find the close free cell of the middle frontier cell std::vector<int> adjacentPoints = getAdjacentPoints(fronteres_msg.fronteres[i].centre_cella, mapa_fronteres); for (unsigned int k = 0; k<adjacentPoints.size(); k++) { if (mapa_occupacio.data[adjacentPoints[k]] == 0) // free neighbor cell { fronteres_msg.fronteres[i].centre_lliure_cella = adjacentPoints[k]; break; } if (k == 7) ROS_ERROR("findFrontiers: No free cell close to the center frontier cell!"); } fronteres_msg.fronteres[i].centre_lliure_punt = cell2point(fronteres_msg.fronteres[i].centre_lliure_cella, mapa_fronteres); } // Publica fronteres_pub_.publish(fronteres_msg); ROS_INFO("fronteres publicat!"); publishMarkers(fronteres_msg); ROS_INFO("marker array publicat!"); } // Check if a cell is frontier bool TrobaFronteres::esFrontera(const int& cell, const nav_msgs::OccupancyGrid& mapa) const { if(mapa.data[cell] == -1) //check if it is unknown { auto straightPoints = getStraightPoints(cell,mapa); for(int i = 0; i < straightPoints.size(); ++i) if(straightPoints[i] != -1 && mapa.data[straightPoints[i]] == 0) //check if any neigbor is free space return true; } // If it is obstacle or free can not be frontier return false; } // Two pass labeling to label frontiers [http://en.wikipedia.org/wiki/Connected-component_labeling] std::vector<int> TrobaFronteres::twoPassLabeling(const nav_msgs::OccupancyGrid& mapa_etiquetar, std::map<int,int>& labels_sizes) const { labels_sizes.clear(); std::vector<int> labels(mapa_etiquetar.data.size()); labels.assign(mapa_etiquetar.data.begin(), mapa_etiquetar.data.end()); std::vector<int> neigh_labels; std::vector<int> rank(1000); std::vector<int> parent(1000); boost::disjoint_sets<int*,int*> dj_set(&rank[0], &parent[0]); int current_label_=1; // 1ST PASS: Assign temporary labels to frontiers and establish relationships for(unsigned int i = 0; i < mapa_etiquetar.data.size(); i++) { if( mapa_etiquetar.data[i] != 0) { neigh_labels.clear(); // Find 8-connectivity neighbours already labeled if(upleftCell(i,mapa_etiquetar) != -1 && labels[upleftCell(i,mapa_etiquetar)] != 0) neigh_labels.push_back(labels[upleftCell(i,mapa_etiquetar)]); if(upCell(i,mapa_etiquetar) != -1 && labels[upCell(i,mapa_etiquetar)] != 0) neigh_labels.push_back(labels[upCell(i,mapa_etiquetar)]); if(uprightCell(i,mapa_etiquetar) != -1 && labels[uprightCell(i,mapa_etiquetar)] != 0) neigh_labels.push_back(labels[uprightCell(i,mapa_etiquetar)]); if(leftCell(i,mapa_etiquetar) != -1 && labels[leftCell(i,mapa_etiquetar)] != 0) neigh_labels.push_back(labels[leftCell(i,mapa_etiquetar)]); if(neigh_labels.empty()) // case: No neighbours { dj_set.make_set(current_label_); // create new set of labels labels[i] = current_label_; // update cell's label current_label_++; // update label } else // case: With neighbours { labels[i] = *std::min_element(neigh_labels.begin(), neigh_labels.end());// choose minimum label of the neighbours for(unsigned int j = 0; j < neigh_labels.size(); ++j) // update neighbours sets dj_set.union_set(labels[i],neigh_labels[j]); // unite sets minimum label with the others } } } // 2ND PASS: Assign final label dj_set.compress_sets(labels.begin(), labels.end()); // compress sets for efficiency for(unsigned int i = 0; i < mapa_etiquetar.data.size(); i++) if( labels[i] != 0) { // relabel each element with the lowest equivalent label labels[i] = dj_set.find_set(labels[i]); // increment the size of the label if (labels_sizes.count(labels[i]) == 0) labels_sizes[labels[i]] = 1; else labels_sizes[labels[i]]++; } return labels; } void TrobaFronteres::publishMarkers(const exploracio::Fronteres& fronteres_msg) { // redimensionar markers_.markers.resize(fronteres_msg.fronteres.size()*3+1); // cada frontera: celles_punts, centre_lliure_punt i id // deleteall markers_.markers[0].action = visualization_msgs::Marker::DELETEALL; // omplir for (int i = 0; i < fronteres_msg.fronteres.size(); i++) { std_msgs::ColorRGBA c; c.a = 1.0; c.r = sin(fronteres_msg.fronteres[i].id*0.3); c.g = sin(fronteres_msg.fronteres[i].id*0.3 + 2*M_PI/3); c.b = sin(fronteres_msg.fronteres[i].id*0.3 + 4*M_PI/3); // punts visualization_msgs::Marker marker_punts; marker_punts.header.frame_id = fronteres_msg.header.frame_id; marker_punts.header.stamp = ros::Time::now(); marker_punts.lifetime = ros::Duration(0); marker_punts.type = visualization_msgs::Marker::POINTS; marker_punts.pose.orientation.x = marker_punts.pose.orientation.y = marker_punts.pose.orientation.z = 0; marker_punts.pose.orientation.w = 1; marker_punts.points = fronteres_msg.fronteres[i].celles_punts; marker_punts.scale.x = marker_punts.scale.y = marker_punts.scale.z = 0.1; marker_punts.colors = std::vector<std_msgs::ColorRGBA>(marker_punts.points.size(),c); marker_punts.ns = "celles"; marker_punts.id = 3*i; markers_.markers[3*i+1] = marker_punts; // centre lliure punt visualization_msgs::Marker marker_centre; marker_centre.header.frame_id = fronteres_msg.header.frame_id; marker_centre.header.stamp = ros::Time::now(); marker_centre.lifetime = ros::Duration(0); marker_centre.type = visualization_msgs::Marker::CYLINDER; marker_centre.scale.x = marker_centre.scale.y = 0.1; marker_centre.scale.z = 0.5; marker_centre.color = c; marker_centre.ns = "centres"; marker_centre.id = 3*i+1; marker_centre.pose.position.x = fronteres_msg.fronteres[i].centre_lliure_punt.x; marker_centre.pose.position.y = fronteres_msg.fronteres[i].centre_lliure_punt.y; marker_centre.pose.position.z = marker_centre.scale.z/2; marker_centre.pose.orientation.x = marker_centre.pose.orientation.y = marker_centre.pose.orientation.z = 0; marker_centre.pose.orientation.w = 1; markers_.markers[3*i+2] = marker_centre; // id text visualization_msgs::Marker marker_id; marker_id.header.frame_id = fronteres_msg.header.frame_id; marker_id.header.stamp = ros::Time::now(); marker_id.lifetime = ros::Duration(0); marker_id.type = visualization_msgs::Marker::TEXT_VIEW_FACING; marker_id.scale.x = marker_id.scale.y = 1; marker_id.scale.z = 0.5; marker_id.text = std::to_string(fronteres_msg.fronteres[i].id); marker_id.color = c; marker_id.pose = marker_centre.pose; marker_id.pose.position.z = marker_centre.scale.z + 0.2; marker_id.ns = "ids"; marker_id.id = 3*i+2; markers_.markers[3*i+3] = marker_id; } // publicar markers_pub_.publish(markers_); } int main(int argc, char **argv) { ros::init(argc, argv, "troba_fronteres_node"); ros::NodeHandle nh("~"); TrobaFronteres node_fronteres(nh); ros::Rate loop_rate(10); while (ros::ok()) { ros::spinOnce(); loop_rate.sleep(); } return 0; }
[ "adria.arroyo@outlook.es" ]
adria.arroyo@outlook.es
b8d07493b8dd22b026c4ee97bb88c4d56167bde4
1c0d1773fc0f45178822db2afceb48cbd2f53f18
/wprg.cpp
2741629f90cd70fd556e2159871f2fe9394f8e83
[]
no_license
andrewbuss/crypto-1
0ff339dc05a7a304abf4e922305eacc7f73f05c8
40b896c679b3ad25955d7c1d532d9e4715f7152a
refs/heads/master
2021-01-01T15:41:30.493080
2013-12-07T06:05:08
2013-12-07T06:05:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,548
cpp
#include <stdio.h> #define z1 210205973 #define z2 22795300 #define z3 58776750 #define z4 121262470 #define z5 264731963 #define z6 140842553 #define z7 242590528 #define z8 195244728 #define z9 86752752 #define P 295075153 int main(){ int x, y, x1, y1; for(x1=0;x1<P;x1++){ y1 = (x1^z1); if(x1%10000000 == 0) printf("X1 %i\n",x1); //printf("%i: X = %i, Y = %i, Z = %i\n",1,x1,y1,x1^y1); x = (2*x1+5)%P; y = (3*y1+7)%P; if((x^y) != z2) continue; printf("%i: X = %i, Y = %i, Z = %i\n",2,x,y,x^y); x = (2*x+5)%P; y = (3*y+7)%P; if((x^y) != z3) continue; printf("%i: X = %i, Y = %i, Z = %i\n",3,x,y,x^y); x = (2*x+5)%P; y = (3*y+7)%P; if((x^y) != z4) continue; printf("%i: X = %i, Y = %i, Z = %i\n",4,x,y,x^y); x = (2*x+5)%P; y = (3*y+7)%P; if((x^y) != z5) continue; printf("%i: X = %i, Y = %i, Z = %i\n",5,x,y,x^y); x = (2*x+5)%P; y = (3*y+7)%P; if((x^y) != z6) continue; printf("%i: X = %i, Y = %i, Z = %i\n",6,x,y,x^y); x = (2*x+5)%P; y = (3*y+7)%P; if((x^y) != z7) continue; printf("%i: X = %i, Y = %i, Z = %i\n",7,x,y,x^y); x = (2*x+5)%P; y = (3*y+7)%P; if((x^y) != z8) continue; printf("%i: X = %i, Y = %i, Z = %i\n",8,x,y,x^y); x = (2*x+5)%P; y = (3*y+7)%P; if((x^y) != z9) continue; printf("%i: X = %i, Y = %i, Z = %i\n",9,x,y,x^y); printf("X1: %i, Y1: %i, Z1: %i\n",x1,y1,x1^y1); x = (2*x+5)%P; y = (3*y+7)%P; printf("%i: X = %i, Y = %i, Z = %i\n",10,x,y,x^y); break; } }
[ "abuss@ucsd.edu" ]
abuss@ucsd.edu
6aadfa8c1adeb0590f744de565997f1b24738fc4
c9cf0586ace11aa32fa67606d237a130a06364ee
/circular-cylinder-10-20/17.25075/phi
570e82987197de8ca2ff888cb13b5e348a2bcfc3
[]
no_license
jezvonek/CFD-Final-Project
c74cfa21f22545c27d97d85cf30eb6dc8c824dc1
7c9a7fb032d74f20888effa0a0b75b212bf899f4
refs/heads/master
2022-07-05T14:43:52.967657
2020-05-14T03:40:56
2020-05-14T03:40:56
262,370,756
1
1
null
null
null
null
UTF-8
C++
false
false
49,068
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 6.0 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class surfaceScalarField; location "17.25075"; object phi; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 3 -1 0 0 0 0]; internalField nonuniform List<scalar> 4670 ( 0.00361818 -0.422688 0.41907 0.0115297 -0.387552 0.37964 0.0210151 -0.371661 0.362175 0.0305188 -0.357591 0.348087 0.0393803 -0.342791 0.33393 0.0474323 -0.327024 0.318972 0.0547558 -0.310979 0.303655 0.0615317 -0.295468 0.288692 0.0679629 -0.281045 0.274614 -0.267945 0.26165 0.0742587 0.00378919 -0.426477 0.0116985 -0.395461 0.02097 -0.380932 0.0301098 -0.366731 0.0385268 -0.351208 0.0461153 -0.334613 0.0529979 -0.317861 0.0593745 -0.301845 0.0654547 -0.287125 -0.273945 0.0714547 0.00390547 -0.430382 0.0117238 -0.403279 0.0206925 -0.389901 0.029387 -0.375425 0.0372927 -0.359114 0.0443655 -0.341686 0.0507658 -0.324261 0.0567079 -0.307787 0.0624032 -0.292821 -0.279617 0.0680747 0.00394522 -0.434328 0.0115965 -0.41093 0.0201867 -0.398491 0.028365 -0.383604 0.0356969 -0.366446 0.0422007 -0.34819 0.0480734 -0.330134 0.0535409 -0.313254 0.0588138 -0.298094 -0.284926 0.0641234 0.00393016 -0.438258 0.0113375 -0.418338 0.0194804 -0.406634 0.0270828 -0.391206 0.0337864 -0.373149 0.039666 -0.354069 0.0449511 -0.335419 0.0498804 -0.318184 0.0546688 -0.302882 -0.289829 0.0595719 0.00385706 -0.442115 0.0109541 -0.425435 0.0185925 -0.414272 0.025575 -0.398189 0.0316156 -0.37919 0.0368343 -0.359288 0.0414782 -0.340063 0.0457923 -0.322498 0.0500111 -0.307101 -0.294259 0.0544412 0.00373789 -0.445853 0.0104684 -0.432165 0.0175478 -0.421352 0.0238634 -0.404504 0.0292079 -0.384534 0.0337494 -0.363829 0.0377428 -0.344057 0.0414137 -0.326169 0.044989 -0.310676 -0.29801 0.04874 0.00359453 -0.449447 0.00992882 -0.4385 0.0164054 -0.427828 0.0219902 -0.410089 0.0265564 -0.389101 0.0303396 -0.367613 0.0336397 -0.347357 0.0366708 -0.3292 0.0395387 -0.313544 -0.300602 0.0421302 0.0034737 -0.452921 0.00942472 -0.444451 0.0152957 -0.4337 0.020122 -0.414915 0.0238169 -0.392796 0.0266317 -0.370427 0.0288994 -0.349624 0.0309251 -0.331225 0.0328953 -0.315514 -0.302328 0.0346213 0.00344193 -0.456363 0.00902935 -0.450038 0.0143532 -0.439023 0.0185248 -0.419087 0.0214588 -0.39573 0.0232999 -0.372269 0.0241675 -0.350492 0.024211 -0.331269 0.0241513 -0.315455 -0.305668 0.0274915 0.483613 0.00288338 -0.486497 0.480661 0.00295234 0.477647 0.00301419 0.474595 0.00305173 0.471529 0.00306592 0.468467 0.00306206 0.465423 0.00304434 0.462389 0.00303365 0.459379 0.00300992 0.00301608 0.489037 0.00563524 -0.491789 0.485834 0.00615602 0.482249 0.00659858 0.478337 0.00696386 0.474145 0.0072584 0.469718 0.00748868 0.46509 0.00767297 0.460281 0.00784216 0.455275 0.00801575 0.00825321 0.470765 0.00694402 -0.472074 0.468892 0.00802929 0.466504 0.00898656 0.463656 0.00981168 0.460393 0.010521 0.456767 0.0111151 0.45281 0.0116299 0.448551 0.0121014 0.443969 0.0125977 0.0131988 0.440536 0.00714719 -0.440739 0.439793 0.00877235 0.43854 0.0102393 0.436831 0.0115208 0.434699 0.0126533 0.43221 0.0136041 0.429387 0.0144529 0.426277 0.015211 0.422859 0.0160158 0.0169706 0.409754 0.00685856 -0.409465 0.409567 0.00895962 0.408922 0.010884 0.407882 0.0125608 0.406462 0.0140731 0.404763 0.0153035 0.402784 0.0164321 0.400652 0.0173431 0.398304 0.0183636 0.0195448 0.382329 0.00651217 -0.381983 0.382258 0.00903147 0.381775 0.0113667 0.380963 0.0133728 0.379808 0.0152281 0.378482 0.0166295 0.37692 0.0179943 0.375421 0.0188421 0.3738 0.0199842 0.0210764 0.358986 0.00632274 -0.358797 0.358795 0.00922223 0.358218 0.0119442 0.357361 0.0142296 0.356158 0.0164316 0.354894 0.017893 0.35339 0.0194989 0.352278 0.0199533 0.351 0.0212621 0.0215849 0.339256 0.00635734 -0.339291 0.338865 0.00961407 0.338092 0.0127171 0.33707 0.0152509 0.335652 0.0178504 0.334261 0.0192838 0.332524 0.0212356 0.33172 0.0207577 0.330496 0.0224857 0.0208123 0.322323 0.00661837 -0.322585 0.32173 0.0102076 0.320759 0.0136884 0.31957 0.0164397 0.317906 0.0195143 0.316316 0.0208739 0.314108 0.0234434 0.313471 0.0213946 0.312401 0.0235559 0.0177586 0.307396 -0.307904 0.00712562 0.306608 0.0109965 0.305468 0.0148281 0.304167 0.0177408 0.302347 0.0213338 0.300617 0.0226045 0.297913 0.0261474 0.296745 0.0225619 0.295497 0.0248038 0.0075879 0.498553 -0.000419311 -0.498134 0.49866 -0.000106853 0.498378 0.000281973 0.497688 0.000689568 0.496603 0.00108486 0.495151 0.0014526 0.493368 0.00178262 0.491293 0.00207522 0.488985 0.00230756 0.00248871 0.489988 -0.00384989 -0.486557 0.492779 -0.00289811 0.494918 -0.00185746 0.496383 -0.00077511 0.497173 0.00029504 0.497303 0.00132209 0.496797 0.00228874 0.495688 0.00318414 0.494005 0.00399091 0.00470443 0.454918 -0.00914775 -0.44962 0.45957 -0.00754979 0.463532 -0.00581988 0.466794 -0.00403673 0.469358 -0.00226913 0.47123 -0.000550207 0.47242 0.00109916 0.472945 0.00265956 0.472821 0.00411491 0.0054513 0.415481 -0.0151691 -0.40946 0.420887 -0.0129563 0.425617 -0.0105494 0.429679 -0.00809872 0.433091 -0.00568146 0.435859 -0.00331826 0.437991 -0.00103274 0.439504 0.00114699 0.440413 0.00320581 0.00512515 0.38225 -0.0213012 -0.376118 0.387737 -0.0184431 0.392538 -0.015351 0.396704 -0.0122649 0.400262 -0.00923955 0.40322 -0.00627592 0.405597 -0.00340937 0.407418 -0.000674283 0.408702 0.00192211 0.0043614 0.356097 -0.0273598 -0.350038 0.361365 -0.0237115 0.365914 -0.0199005 0.369861 -0.0162115 0.373216 -0.0125948 0.375991 -0.00905033 0.378226 -0.00564488 0.379959 -0.0024069 0.381206 0.000675217 0.00358418 0.335441 -0.0334136 -0.329387 0.340394 -0.0286638 0.344591 -0.0240981 0.348231 -0.0198511 0.351269 -0.0156325 0.353727 -0.0115084 0.355678 -0.00759665 0.357166 -0.00389423 0.358201 -0.00035974 0.00298807 0.318549 -0.0395555 -0.312407 0.323217 -0.0333314 0.327084 -0.0279652 0.330418 -0.0231845 0.333126 -0.0183409 0.33526 -0.0136421 0.336917 -0.00925416 0.338138 -0.00511512 0.338926 -0.00114792 0.00262337 0.304209 -0.0452378 -0.298527 0.308727 -0.037849 0.312378 -0.0316163 0.315345 -0.0261515 0.317696 -0.0206921 0.31953 -0.0154758 0.320919 -0.0106432 0.321892 -0.00608848 0.322446 -0.00170178 0.00248501 0.291501 -0.290294 -0.0464447 0.296076 -0.0424239 0.300183 -0.0357235 0.302528 -0.028496 0.304345 -0.0225094 0.305876 -0.0170072 0.307001 -0.0117683 0.307713 -0.00680025 0.308015 -0.00200394 0.00259668 0.0633107 0.230743 -0.224498 -0.0695548 0.0566965 0.241422 -0.234808 0.0497182 0.253506 -0.246528 0.0423562 0.267726 -0.260363 0.0345904 0.285444 -0.277679 0.0264355 0.308906 -0.300751 0.0180217 0.341296 -0.332882 0.00980833 0.385392 -0.377179 0.00302528 0.436907 -0.430123 0.478839 -0.475814 0.0624116 0.236891 -0.0685602 0.0558811 0.247952 0.0489842 0.260403 0.0416999 0.27501 0.0340082 0.293136 0.0259296 0.316984 0.0176099 0.349616 0.00953364 0.393468 0.00293383 0.443506 0.481773 0.0612275 0.24291 -0.0672464 0.0548224 0.254357 0.0480437 0.267182 0.0408707 0.282183 0.033285 0.300722 0.0253139 0.324955 0.0171174 0.357812 0.00919964 0.401386 0.00279102 0.449915 0.484564 0.0600981 0.248839 -0.0660272 0.0537642 0.260691 0.047061 0.273885 0.0399693 0.289275 0.0324749 0.308216 0.0246111 0.332819 0.0165494 0.365874 0.00881071 0.409125 0.00262099 0.456105 0.487185 0.0584427 0.254566 -0.0641699 0.0522967 0.266837 0.0457652 0.280417 0.0388321 0.296208 0.0314895 0.315559 0.02378 0.340529 0.0158914 0.373762 0.00836747 0.416649 0.00243094 0.462041 0.489616 0.057447 0.260365 -0.0632452 0.0512106 0.273074 0.0446267 0.287001 0.0377058 0.303129 0.0304394 0.322825 0.0228595 0.348109 0.0151528 0.381469 0.00786912 0.423932 0.00221699 0.467693 0.491833 0.0551834 0.265828 -0.0606468 0.0492129 0.279044 0.0428773 0.293336 0.0361917 0.309814 0.0291411 0.329876 0.0217731 0.355476 0.0143047 0.388938 0.00730922 0.430928 0.00198193 0.473021 0.493815 0.0550127 0.272224 -0.0614087 0.0482349 0.285822 0.041502 0.300069 0.0347253 0.316591 0.0277437 0.336857 0.0205508 0.362669 0.0133414 0.396147 0.00667922 0.43759 0.00171529 0.477985 0.49553 0.0512252 0.278427 -0.0574284 0.0450259 0.292021 0.0390308 0.306064 0.0326949 0.322927 0.0260034 0.343549 0.0191017 0.369571 0.0122347 0.403014 0.00597928 0.443845 0.0014467 0.482517 0.496977 0.0497627 -0.0616297 0.0432572 0.0369138 0.0304533 0.0239639 0.0174174 0.0109718 0.0051967 0.00115681 0.0623243 0.168182 -0.162533 -0.0679736 0.0549763 0.175587 -0.168239 0.0476414 0.184154 -0.176819 0.0403528 0.194859 -0.18757 0.0330694 0.208983 -0.2017 0.0257139 0.228947 -0.221591 0.0182121 0.258645 -0.251143 0.0106485 0.303337 -0.295774 0.00378333 0.36593 -0.359065 0.44274 -0.438957 0.0617394 0.174674 -0.0682317 0.0551848 0.182142 0.0483802 0.190959 0.0413225 0.201917 0.0340172 0.216288 0.0264746 0.236489 0.0187122 0.266407 0.0109036 0.311146 0.00388505 0.372949 0.446625 0.0621491 0.180833 -0.0683079 0.0557752 0.188516 0.0490536 0.19768 0.0420083 0.208962 0.0346391 0.223658 0.026958 0.24417 0.0190113 0.274354 0.011022 0.319135 0.00388746 0.380083 0.450513 0.0629844 0.186807 -0.0689582 0.0565749 0.194925 0.0497742 0.204481 0.0426237 0.216112 0.035128 0.231153 0.0272954 0.252003 0.019183 0.282466 0.011048 0.32727 0.00384559 0.387286 0.454358 0.0637488 0.192867 -0.0698087 0.0572399 0.201434 0.0503498 0.211371 0.0430983 0.223364 0.0354853 0.238766 0.0275189 0.259969 0.0192658 0.29072 0.0110196 0.335516 0.00378588 0.39452 0.458144 0.0642875 0.199072 -0.0704927 0.0576927 0.208029 0.0507285 0.218335 0.0433979 0.230694 0.0356945 0.24647 0.0276255 0.268038 0.0192678 0.299077 0.0109455 0.343838 0.00371129 0.401754 0.461855 0.0646173 0.205391 -0.0709367 0.0579535 0.214693 0.0509289 0.22536 0.0435365 0.238087 0.0357653 0.254241 0.0276227 0.276181 0.019195 0.307505 0.0108324 0.352201 0.00362781 0.408958 0.465483 0.0647271 0.211777 -0.0711127 0.0580146 0.221405 0.0509505 0.232424 0.0435195 0.245518 0.0357065 0.262054 0.027519 0.284368 0.019053 0.315971 0.0106838 0.36057 0.00353217 0.41611 0.469015 0.0645662 0.218168 -0.0709569 0.0578464 0.228125 0.0507776 0.239493 0.0433401 0.252955 0.0355161 0.269878 0.0273151 0.292569 0.0188453 0.324441 0.0105084 0.368907 0.00344482 0.423174 0.47246 0.0641244 -0.0704553 0.0574416 0.0504065 0.0429985 0.0351978 0.0270164 0.0185751 0.0103036 0.00335365 -0.151069 0.0609535 -0.0724174 -0.145725 0.0521427 -0.0574862 -0.141736 0.0460933 -0.0500831 -0.138821 0.0387744 -0.0416885 -0.136775 0.0319696 -0.0340162 -0.135634 0.0250645 -0.026205 -0.135396 0.018177 -0.0184155 -0.136081 0.0112657 -0.0105803 -0.137693 0.00437294 -0.00276142 -0.0024422 -0.140216 0.00496548 -0.160225 0.0529394 -0.154535 0.0464532 -0.149962 0.0415202 -0.146681 0.0354932 -0.144373 0.0296615 -0.143037 0.0237281 -0.142643 0.0177836 -0.143199 0.011821 -0.144691 0.00586572 -3.65137e-05 -0.147097 -0.169408 0.0455284 -0.163818 0.0408635 -0.159065 0.0367664 -0.155485 0.0319136 -0.15291 0.0270862 -0.151322 0.0221406 -0.150696 0.0171573 -0.151024 0.0121488 -0.152292 0.0071336 0.00214605 -0.154474 -0.180488 0.0384464 -0.174777 0.0351521 -0.169878 0.0318677 -0.166031 0.0280662 -0.163157 0.0242119 -0.161254 0.0202374 -0.160308 0.0162113 -0.16031 0.0121515 -0.161251 0.00807399 0.00400383 -0.163108 -0.194824 0.0315703 -0.188926 0.0292544 -0.183818 0.0267599 -0.179666 0.0239144 -0.176435 0.0209811 -0.174138 0.0179397 -0.172772 0.0148453 -0.172334 0.0117138 -0.172819 0.00855915 0.00539843 -0.174214 -0.21473 0.0247091 -0.208613 0.0231375 -0.203227 0.0213743 -0.198698 0.019385 -0.195022 0.0173049 -0.192221 0.0151389 -0.190303 0.0129267 -0.189269 0.0106805 -0.189121 0.00841068 0.00612782 -0.18985 -0.244145 0.0177107 -0.237751 0.0167439 -0.23201 0.015633 -0.227014 0.014389 -0.222782 0.013073 -0.219342 0.0116987 -0.216705 0.0102901 -0.21488 0.00885549 -0.213868 0.00739924 0.00592743 -0.213668 -0.288662 0.0105996 -0.282032 0.0101139 -0.275945 0.00954523 -0.270475 0.00891897 -0.26565 0.00824779 -0.261497 0.00754611 -0.25803 0.00682314 -0.255259 0.00608444 -0.253187 0.00532703 0.00454941 -0.251809 -0.35245 0.00398452 -0.346169 0.00383328 -0.340275 0.00365077 -0.334828 0.00347232 -0.329852 0.00327168 -0.325369 0.00306245 -0.321389 0.00284341 -0.317923 0.00261895 -0.314979 0.00238249 0.00211229 -0.312542 -0.434972 -0.431139 -0.427488 -0.424016 -0.420744 -0.417682 -0.414838 -0.412219 -0.409837 -0.407725 -0.143613 -0.00904937 0.0124462 -0.147809 -0.0154707 0.0196664 -0.152716 -0.0215684 0.0264759 -0.158211 -0.0272471 0.0327423 -0.164125 -0.0324136 0.0383271 -0.170247 -0.0370037 0.0431258 -0.17632 -0.0410715 0.0471451 -0.182063 -0.0448183 0.0505612 -0.187793 -0.0482716 0.0540011 -0.0523847 -0.191563 0.056155 -0.150375 -0.00577116 -0.154449 -0.0113975 -0.159226 -0.0167905 -0.164592 -0.0218817 -0.170395 -0.0266109 -0.176449 -0.0309493 -0.182576 -0.0349449 -0.188684 -0.0387095 -0.19457 -0.0423855 -0.0467787 -0.200176 -0.157538 -0.00270693 -0.161415 -0.00752109 -0.166026 -0.0121797 -0.171272 -0.0166356 -0.17703 -0.020852 -0.183161 -0.0248191 -0.189539 -0.0285662 -0.196089 -0.0321603 -0.202678 -0.0357962 -0.0398932 -0.209563 -0.165862 4.70309e-05 -0.169454 -0.00392924 -0.173822 -0.00781194 -0.178886 -0.0115717 -0.184549 -0.0151888 -0.190706 -0.0186626 -0.19726 -0.0220119 -0.204131 -0.0252898 -0.211276 -0.0286508 -0.0322535 -0.218916 -0.17651 0.002343 -0.179659 -0.000779589 -0.183617 -0.0038545 -0.188322 -0.00686654 -0.193702 -0.00980846 -0.19968 -0.0126847 -0.206181 -0.0155106 -0.21314 -0.0183317 -0.22055 -0.0212405 -0.0242706 -0.228533 -0.191464 0.00395719 -0.193925 0.00168084 -0.197202 -0.000577405 -0.201256 -0.00281296 -0.206038 -0.00502608 -0.211499 -0.00722379 -0.217586 -0.00942323 -0.224258 -0.0116595 -0.231518 -0.0139805 -0.0163785 -0.23941 -0.214305 0.00459457 -0.215746 0.00312177 -0.217976 0.0016524 -0.220976 0.000187083 -0.224722 -0.00128043 -0.229188 -0.00275787 -0.234347 -0.00426366 -0.240183 -0.00582368 -0.246698 -0.00746539 -0.00917696 -0.2539 -0.251172 0.0039579 -0.251241 0.00319114 -0.252014 0.00242537 -0.253493 0.00166592 -0.255671 0.00089737 -0.258544 0.000115524 -0.262111 -0.00069656 -0.266375 -0.00156034 -0.271344 -0.00249641 -0.00350749 -0.277013 -0.310623 0.00203895 -0.309231 0.00179974 -0.308368 0.00156175 -0.308044 0.00134231 -0.308264 0.00111728 -0.309035 0.00088663 -0.310373 0.000641166 -0.312303 0.00036959 -0.314852 5.29104e-05 -0.000346091 -0.318013 -0.405686 -0.403886 -0.402324 -0.400982 -0.399865 -0.398978 -0.398337 -0.397967 -0.397914 -0.39826 0.000437338 -0.398698 0.00421845 -0.321794 0.0106346 -0.283429 0.0185337 -0.261799 0.0270563 -0.247933 0.0356543 -0.237131 0.0440372 -0.227298 0.0521694 -0.217696 0.0603469 -0.208354 -0.200029 0.0688128 0.000817865 -0.399516 0.00522959 -0.326206 0.0122996 -0.290499 0.0207789 -0.270278 0.0297663 -0.25692 0.038702 -0.246067 0.0472907 -0.235887 0.0554559 -0.225861 0.0632384 -0.216136 -0.207181 0.0703902 0.00121177 -0.400727 0.00623173 -0.331226 0.0139028 -0.29817 0.0228853 -0.279261 0.0322565 -0.266292 0.0414731 -0.255283 0.0502668 -0.244681 0.0585308 -0.234125 0.0661408 -0.223746 -0.213855 0.0728144 0.0015787 -0.402306 0.00718738 -0.336835 0.0154001 -0.306383 0.0247926 -0.288653 0.0344318 -0.275931 0.0437923 -0.264644 0.0526301 -0.253519 0.0608688 -0.242364 0.0685001 -0.231378 -0.220875 0.0755202 0.00194789 -0.404254 0.00809851 -0.342985 0.0167752 -0.31506 0.0264831 -0.298361 0.0362929 -0.285741 0.0457087 -0.274059 0.0545219 -0.262332 0.0626931 -0.250535 0.0702522 -0.238937 -0.22783 0.0772076 0.00230558 -0.40656 0.00894386 -0.349624 0.0179989 -0.324115 0.0279219 -0.308284 0.0377997 -0.295618 0.0471765 -0.283436 0.05589 -0.271045 0.0639485 -0.258593 0.0714317 -0.24642 -0.2348 0.0784014 0.0026516 -0.409211 0.00971294 -0.356685 0.0190531 -0.333455 0.0290903 -0.318321 0.0389408 -0.305469 0.0481968 -0.292692 0.0567444 -0.279593 0.0646314 -0.26648 0.0719668 -0.253755 -0.241671 0.078838 0.00297816 -0.412189 0.0103911 -0.364098 0.0199186 -0.342983 0.0299673 -0.32837 0.0396965 -0.315198 0.048754 -0.30175 0.0570773 -0.287916 0.0647544 -0.274157 0.0719257 -0.260927 -0.248462 0.0787164 0.00328709 -0.415476 0.0109731 -0.371784 0.0205834 -0.352593 0.0305393 -0.338326 0.0400553 -0.324714 0.0488392 -0.310533 0.056879 -0.295956 0.064299 -0.281577 0.0712659 -0.267894 -0.255133 0.0779377 0.00359325 0.0114492 0.0210317 0.0307931 0.0400088 0.0484477 0.0561466 0.0632615 0.0699818 0.076498 0.0685461 -1.17541 1.18112 0.0672065 -0.991519 0.992859 0.0650918 -0.867654 0.869768 0.0639999 -0.752902 0.753994 0.062454 -0.635505 0.637051 0.0602365 -0.526755 0.528972 0.0580073 -0.428112 0.430341 0.055973 -0.341431 0.343465 0.0542872 -0.266841 0.268527 0.0529925 -0.204913 0.206208 0.0521217 -0.153461 0.154332 0.0515578 -0.112432 0.112996 0.0512848 -0.0771741 0.0774471 0.0510626 -0.0452224 0.0454445 0.0504176 -0.0137186 0.0143637 0.0496026 0.0317114 -0.0308965 0.0479135 0.060786 -0.0590969 0.0475514 0.108668 -0.108305 0.0491672 0.0981853 -0.0998011 0.0511878 -0.0514843 0.061168 -1.16512 0.0581794 -0.988531 0.056244 -0.865718 0.055753 -0.752411 0.0552598 -0.635012 0.0541171 -0.525612 0.0528408 -0.426836 0.0516203 -0.340211 0.0505897 -0.265811 0.0497997 -0.204123 0.0493049 -0.152967 0.0490143 -0.112142 0.0489509 -0.0771106 0.0488679 -0.0451394 0.0483492 -0.0131999 0.0476447 0.032416 0.0461341 0.0622967 0.0460637 0.108738 0.0477507 0.0964984 0.0509542 0.0536312 -1.15068 0.0489042 -0.983804 0.0471144 -0.863928 0.0473095 -0.752606 0.0478943 -0.635597 0.0478593 -0.525577 0.0475542 -0.42653 0.0471593 -0.339816 0.0467925 -0.265444 0.0465131 -0.203844 0.046399 -0.152852 0.0463884 -0.112131 0.0465431 -0.0772652 0.046614 -0.0452103 0.0462457 -0.0128316 0.045679 0.0329827 0.0443805 0.0635952 0.0446042 0.108514 0.0463564 0.0947461 0.0507571 0.0460009 -1.13255 0.0398025 -0.977605 0.038035 -0.862161 0.0388178 -0.753389 0.0404197 -0.637199 0.0414946 -0.526652 0.0421744 -0.42721 0.0426168 -0.340258 0.0429232 -0.26575 0.0431604 -0.204081 0.0434309 -0.153123 0.0437051 -0.112406 0.0440837 -0.0776438 0.0443206 -0.0454472 0.0441239 -0.0126349 0.0437195 0.033387 0.0426601 0.0646546 0.0431741 0.108 0.0449863 0.0929339 0.0505705 0.0388642 -1.11185 0.0315145 -0.970256 0.0292718 -0.859918 0.03033 -0.754447 0.0328471 -0.639716 0.0350371 -0.528842 0.036722 -0.428895 0.0380159 -0.341552 0.0390058 -0.26674 0.0397662 -0.204842 0.0404252 -0.153782 0.0409876 -0.112968 0.0415936 -0.0782499 0.0420066 -0.0458602 0.0419996 -0.0126278 0.0417785 0.0336081 0.040979 0.0654541 0.0417749 0.107204 0.0436426 0.0910663 0.0503692 0.0322356 -1.08964 0.0230631 -0.961083 0.0198786 -0.856734 0.0212957 -0.755864 0.0249536 -0.643374 0.0284244 -0.532313 0.0311921 -0.431663 0.0333692 -0.343729 0.0350589 -0.26843 0.0363515 -0.206134 0.0374034 -0.154834 0.0382566 -0.113821 0.0390921 -0.0790854 0.0396892 -0.0464572 0.0398867 -0.0128253 0.0398664 0.0336284 0.0393415 0.0659791 0.0404075 0.106138 0.0423275 0.0891463 0.0501288 0.0222043 -1.0631 0.0102526 -0.949132 0.00749352 -0.853975 0.010632 -0.759003 0.0163078 -0.649049 0.0215 -0.537505 0.0255337 -0.435697 0.0286665 -0.346862 0.0310893 -0.270853 0.03293 -0.207975 0.0343823 -0.156286 0.0355296 -0.114968 0.036596 -0.0801518 0.0373835 -0.0472447 0.0377974 -0.0132392 0.0379918 0.033434 0.0377507 0.0662201 0.0390726 0.104816 0.0410436 0.0871753 0.0498261 0.00431343 -1.02529 -0.00761302 -0.937205 -0.00733422 -0.854253 -0.0011742 -0.765163 0.00710072 -0.657324 0.0142862 -0.54469 0.0197345 -0.441145 0.0239014 -0.351029 0.0270992 -0.27405 0.0295107 -0.210386 0.0313746 -0.15815 0.0328209 -0.116415 0.0341195 -0.0814504 0.0351025 -0.0482277 0.0357414 -0.0138781 0.036161 0.0330144 0.0362087 0.0661725 0.0377712 0.103254 0.0397936 0.085153 0.0494386 -0.00480079 -0.985865 -0.0149811 -0.927025 -0.0154728 -0.853762 -0.00951166 -0.771124 -0.000706401 -0.66613 0.00752655 -0.552923 0.0140828 -0.447701 0.0191948 -0.356141 0.0231454 -0.278001 0.0261261 -0.213367 0.0284033 -0.160427 0.0301494 -0.118161 0.0316789 -0.0829799 0.0328603 -0.0494091 0.0337294 -0.0147472 0.0343808 0.032363 0.0347173 0.065836 0.0365043 0.101467 0.0385801 0.0830772 0.0489452 0.0360885 -0.994462 0.00754843 -0.898485 -0.00650245 -0.839711 -0.00946202 -0.768164 -0.00513979 -0.670452 0.00207815 -0.560141 0.00900143 -0.454625 0.0147563 -0.361896 0.019334 -0.282579 0.0228356 -0.216869 0.0255053 -0.163097 0.0275431 -0.120198 0.0292962 -0.0847331 0.03068 -0.0507929 0.0317775 -0.0158448 0.0326617 0.0314788 0.033282 0.0652157 0.0352695 0.0994794 0.0374071 0.0809396 0.048327 0.413733 -0.840513 -0.567682 0.345295 -0.830046 0.280313 -0.774728 0.214711 -0.702562 0.165081 -0.620822 0.131772 -0.526833 0.10826 -0.431112 0.0914076 -0.345043 0.079818 -0.270989 0.0719497 -0.209 0.0667094 -0.157857 0.063286 -0.116775 0.061153 -0.0826001 0.0596067 -0.0492466 0.0581841 -0.0144221 0.0575653 0.0320976 0.0577868 0.0649942 0.0613877 0.0958785 0.0653007 0.0770267 0.0478969 0.483053 -0.689413 -0.634153 0.381478 -0.728471 0.305693 -0.698943 0.241475 -0.638344 0.189751 -0.569098 0.152195 -0.489276 0.125119 -0.404036 0.105202 -0.325126 0.0910765 -0.256864 0.0812852 -0.199209 0.0746033 -0.151175 0.0701195 -0.112291 0.0671692 -0.0796498 0.0650707 -0.047148 0.0633055 -0.0126569 0.0627901 0.032613 0.0636278 0.0641564 0.0681095 0.0913968 0.0725493 0.0725868 0.0474237 0.573014 -0.552514 -0.709913 0.461613 -0.61707 0.373297 -0.610628 0.294994 -0.560041 0.228685 -0.502789 0.179614 -0.440206 0.145325 -0.369747 0.120759 -0.30056 0.103298 -0.239403 0.091136 -0.187047 0.0827494 -0.142788 0.0770089 -0.106551 0.0730865 -0.0757274 0.070333 -0.0443946 0.0682481 -0.010572 0.0679935 0.0328677 0.0696895 0.0624604 0.0751929 0.0858934 0.0801946 0.0675852 0.0467772 0.624872 -0.420404 -0.756983 0.498306 -0.490504 0.398 -0.510322 0.321297 -0.483338 0.257407 -0.438899 0.205309 -0.388108 0.166238 -0.330676 0.137584 -0.271906 0.116626 -0.218445 0.101645 -0.172066 0.0911486 -0.132292 0.0838448 -0.0992471 0.0787355 -0.0706181 0.0752331 -0.0408922 0.0728935 -0.00823238 0.0731431 0.032618 0.0759783 0.0596252 0.082629 0.0792427 0.0882974 0.0619169 0.0457295 0.672266 -0.310851 -0.781819 0.558195 -0.376433 0.459231 -0.411359 0.376322 -0.400428 0.301798 -0.364375 0.238147 -0.324457 0.190257 -0.282786 0.156131 -0.237781 0.131207 -0.193521 0.112919 -0.153778 0.0998226 -0.119195 0.0905556 -0.0899801 0.0839955 -0.064058 0.0796501 -0.0365468 0.0771935 -0.0057758 0.0782779 0.0315336 0.082564 0.0553391 0.0905113 0.0712954 0.0970291 0.0553991 0.0439083 0.694924 -0.219768 -0.786006 0.588119 -0.269629 0.483197 -0.306436 0.393368 -0.310599 0.320155 -0.291162 0.260215 -0.264517 0.212449 -0.235019 0.175545 -0.200877 0.146956 -0.164932 0.125021 -0.131843 0.108827 -0.103002 0.097154 -0.0783066 0.0888569 -0.0557609 0.0835853 -0.0312752 0.0812299 -0.00342045 0.0835486 0.029215 0.0896285 0.0492593 0.0990907 0.0618332 0.106733 0.047757 0.0407637 0.695863 -0.146919 -0.768712 0.60853 -0.182296 0.517008 -0.214914 0.433648 -0.227239 0.362072 -0.219586 0.298989 -0.201434 0.244022 -0.180052 0.199251 -0.156105 0.164548 -0.130229 0.138076 -0.105371 0.118303 -0.0832288 0.103819 -0.0638224 0.093522 -0.0454639 0.0872736 -0.0250268 0.0853049 -0.00145178 0.089285 0.0252349 0.0975325 0.0410118 0.108852 0.0505134 0.117953 0.0386561 0.0355607 0.690946 -0.0901419 -0.747723 0.620814 -0.112163 0.540733 -0.134833 0.460395 -0.146901 0.387145 -0.146336 0.322538 -0.136827 0.266272 -0.123787 0.219206 -0.109039 0.181469 -0.0924924 0.151704 -0.0756066 0.128586 -0.06011 0.11109 -0.0463271 0.0985842 -0.0329577 0.0913467 -0.0177893 0.0900597 -0.000164749 0.0960946 0.0191999 0.106893 0.0302134 0.120561 0.0368457 0.131446 0.0277713 0.0274479 0.697494 -0.0435661 -0.744069 0.639363 -0.054033 0.570241 -0.0657105 0.49647 -0.0731302 0.424734 -0.0746003 0.358795 -0.0708884 0.299569 -0.064561 0.247805 -0.0572745 0.204429 -0.0491165 0.169337 -0.0405149 0.141647 -0.0324198 0.120441 -0.0251212 0.105364 -0.0178807 0.0970727 -0.00949769 0.0966452 0.000262773 0.105006 0.0108394 0.118688 0.0165316 0.135266 0.0202675 0.148203 0.0148336 0.0156909 0.741463 -0.785029 0.68743 0.621719 0.548589 0.473989 0.4031 0.338539 0.281265 0.232148 0.191633 0.159213 0.134092 0.116211 0.106714 0.106976 0.117816 0.134347 0.154615 0.169449 0.656753 0.000518397 -0.650146 0.661253 0.00649674 0.663193 0.012888 0.662559 0.0183741 0.658574 0.0253195 0.65157 0.0296081 0.63918 0.0385373 0.622431 0.0393109 0.594227 0.0530076 0.0341334 0.686186 -0.00334643 -0.682321 0.688615 0.00406801 0.689442 0.0120608 0.688154 0.0196622 0.684907 0.0285669 0.678674 0.0358409 0.671202 0.0460091 0.660623 0.0498901 0.653744 0.0598861 0.0537243 0.709542 -0.00480895 -0.70808 0.710554 0.00305668 0.711296 0.011318 0.711595 0.0193637 0.712278 0.0278842 0.712931 0.0351875 0.715208 0.0437318 0.716025 0.049073 0.717043 0.0588688 0.0608542 0.727036 -0.00532881 -0.726517 0.728221 0.00187214 0.730337 0.00920224 0.733282 0.016419 0.737325 0.0238404 0.741561 0.0309514 0.746311 0.0389825 0.749552 0.0458313 0.753876 0.0545451 0.0577477 0.733805 -0.00525275 -0.733881 0.73481 0.000868111 0.736921 0.00709046 0.739967 0.0133736 0.744016 0.0197907 0.748857 0.0261105 0.755263 0.0325772 0.762768 0.0383262 0.772636 0.044677 0.0485643 0.725937 -0.00459558 -0.726594 0.72658 0.000225705 0.7286 0.00507062 0.732074 0.00989878 0.737182 0.0146833 0.743936 0.0193564 0.752517 0.0239958 0.762419 0.0284246 0.77401 0.033086 0.0365685 0.710745 -0.00379955 -0.711541 0.711346 -0.000375553 0.713383 0.00303357 0.716878 0.00640427 0.721843 0.00971838 0.728245 0.0129544 0.736135 0.0161056 0.745449 0.0191104 0.756489 0.0220464 0.0243449 0.699568 -0.00277835 -0.700589 0.699795 -0.000602782 0.701282 0.00154648 0.70404 0.00364652 0.708082 0.00567571 0.713423 0.00761327 0.720087 0.00944189 0.728055 0.0111426 0.737378 0.0127229 0.0139998 0.707525 -0.00152375 -0.708779 0.707377 -0.000454871 0.708333 0.000590421 0.710382 0.00159703 0.713507 0.00255086 0.717681 0.00343899 0.722873 0.00424991 0.729042 0.00497336 0.736163 0.00560277 0.00609318 0.756387 -0.757911 0.755932 0.756523 0.75812 0.76067 0.764109 0.768359 0.773333 0.778935 0.538508 0.0147281 -0.599681 0.564198 -0.0681136 0.581275 -0.0528009 0.59035 -0.0375705 0.600379 -0.0325391 0.611624 -0.0282523 0.622511 -0.0226548 0.632625 -0.016914 0.641916 -0.0112954 -0.00563301 0.615996 0.00531291 -0.606581 0.624682 -0.0767996 0.636984 -0.0651029 0.644535 -0.0451214 0.650206 -0.0382104 0.657183 -0.0352294 0.664653 -0.0301244 0.671461 -0.0237221 0.677369 -0.0172034 -0.0105857 0.677551 -0.00520443 -0.667034 0.680684 -0.079932 0.68554 -0.0699595 0.690913 -0.0504937 0.694187 -0.0414848 0.697062 -0.0381043 0.700437 -0.0334998 0.703645 -0.0269301 0.706192 -0.01975 -0.0124737 0.735906 -0.0157303 -0.72538 0.73124 -0.0752656 0.728334 -0.0670535 0.728857 -0.0510164 0.728938 -0.0415664 0.727961 -0.0371275 0.727089 -0.0326274 0.726669 -0.0265102 0.726487 -0.0195683 -0.0125028 0.779363 -0.0252167 -0.769877 0.767136 -0.0630383 0.757252 -0.0571698 0.752234 -0.0459979 0.748563 -0.0378954 0.744418 -0.032983 0.740357 -0.0285661 0.737161 -0.0233145 0.735018 -0.0174252 -0.0113664 0.793437 -0.0298399 -0.788814 0.777607 -0.0472084 0.76396 -0.0435226 0.754907 -0.036945 0.748226 -0.0312149 0.742102 -0.0268591 0.736455 -0.0229183 0.731839 -0.0186991 0.728552 -0.0141377 -0.0094089 0.781639 -0.0263576 -0.785121 0.766715 -0.0322844 0.75329 -0.0300977 0.742984 -0.0266394 0.734926 -0.0231569 0.728063 -0.0199955 0.722111 -0.0169669 0.717265 -0.013853 0.713721 -0.0105932 -0.00722935 0.764623 -0.0182967 -0.772684 0.752366 -0.0200276 0.741068 -0.0188001 0.731492 -0.0170634 0.723486 -0.0151505 0.716698 -0.0132077 0.71097 -0.0112391 0.70633 -0.0092123 0.702852 -0.007116 -0.00496568 0.767097 -0.00928889 -0.776105 0.756829 -0.00975875 0.74724 -0.00921172 0.738646 -0.00846893 0.731107 -0.00761217 0.724592 -0.00669201 0.719078 -0.00572535 0.714583 -0.00471693 0.71114 -0.00367305 -0.00260525 0.816375 -0.825664 0.806616 0.797405 0.788936 0.781323 0.774631 0.768906 0.764189 0.760516 0.129144 0.0327891 -0.0347646 0.135349 0.100815 -0.107021 0.146595 0.172073 -0.183319 0.163672 0.250799 -0.267876 0.188333 0.337386 -0.362047 0.220464 0.435766 -0.467897 0.263532 0.53786 -0.580929 0.314253 0.648357 -0.699078 0.415497 0.726692 -0.827935 0.804525 -0.988708 0.150938 0.0302757 0.158445 0.0933084 0.172073 0.158445 0.192144 0.230729 0.222418 0.307112 0.260336 0.397848 0.318129 0.480067 0.375727 0.590759 0.497777 0.604641 0.695721 0.176243 0.027222 0.185069 0.0844827 0.201584 0.141929 0.224613 0.2077 0.261936 0.269788 0.304596 0.355189 0.380118 0.404544 0.447631 0.523246 0.56745 0.484822 0.596137 0.205644 0.0236887 0.215569 0.0745577 0.235155 0.122343 0.260396 0.18246 0.305121 0.225063 0.350297 0.310013 0.437472 0.31737 0.51376 0.446958 0.628018 0.370564 0.498775 0.239756 0.0197899 0.250576 0.0637376 0.272797 0.100122 0.29964 0.155617 0.349069 0.175635 0.396784 0.262297 0.481003 0.233151 0.568135 0.359825 0.663866 0.274833 0.392765 0.279154 0.0156106 0.290844 0.0520473 0.314135 0.0768317 0.343177 0.126574 0.390308 0.128504 0.444765 0.207841 0.511035 0.166881 0.606968 0.263892 0.681885 0.199916 0.285837 0.324501 0.0112559 0.337255 0.0392932 0.3591 0.0549869 0.391642 0.094033 0.429908 0.0902372 0.491035 0.146714 0.539018 0.118898 0.629751 0.17316 0.692019 0.137647 0.192734 0.377005 0.00712584 0.390543 0.0257557 0.409677 0.0358528 0.44361 0.0601002 0.474304 0.0595427 0.532196 0.0888219 0.572352 0.0787411 0.645151 0.100361 0.698066 0.0847318 0.118117 0.438605 0.00348415 0.451768 0.0125927 0.469426 0.0181949 0.500635 0.0288915 0.529487 0.030691 0.577065 0.0412438 0.616018 0.0397882 0.670626 0.0457538 0.715319 0.040038 0.0573311 0.511139 0.523732 0.541926 0.570818 0.601509 0.642753 0.682541 0.728295 0.768333 0.0720966 0.0353339 -0.0366488 0.0744059 0.108149 -0.110459 0.0776093 0.184839 -0.188042 0.0813593 0.26759 -0.27134 0.0852383 0.357034 -0.360913 0.0883823 0.454066 -0.45721 0.0901276 0.55669 -0.558435 0.0902295 0.672414 -0.672516 0.0859138 0.817062 -0.812746 0.999931 -0.983572 0.0719429 0.0341534 0.0739183 0.106174 0.0766297 0.182127 0.0797615 0.264458 0.082935 0.35386 0.085395 0.451606 0.0864916 0.555593 0.0861926 0.672713 0.0823984 0.820856 1.01377 0.0717462 0.0331537 0.0733429 0.104577 0.0755103 0.17996 0.0779633 0.262005 0.0803516 0.351472 0.082027 0.449931 0.0823766 0.555244 0.081565 0.673524 0.0780967 0.824324 1.02462 0.0715093 0.0323802 0.072686 0.103401 0.0742628 0.178383 0.075981 0.260287 0.07751 0.349943 0.0783003 0.44914 0.0778014 0.555743 0.0764061 0.67492 0.0733215 0.827409 1.03191 0.071235 0.0318764 0.0719541 0.102682 0.0728993 0.177438 0.0738315 0.259355 0.0744334 0.349341 0.0742425 0.449331 0.0727882 0.557197 0.0707216 0.676986 0.067547 0.830583 1.03529 0.0709259 0.0316843 0.0711533 0.102454 0.0714312 0.17716 0.0715321 0.259254 0.0711459 0.349727 0.0698827 0.450595 0.0673845 0.559695 0.0646783 0.679692 0.0620009 0.833261 1.03405 0.0705846 0.0318439 0.0702898 0.102749 0.06987 0.17758 0.0691003 0.260024 0.0676719 0.351156 0.0652454 0.453021 0.0615825 0.563358 0.0579827 0.683292 0.054497 0.836746 1.0279 0.0702131 0.032393 0.0693685 0.103593 0.0682244 0.178724 0.0665518 0.261696 0.0640355 0.353672 0.0603771 0.456679 0.0556248 0.56811 0.0514471 0.68747 0.050684 0.837509 1.01717 0.0698154 0.0333663 0.068394 0.105015 0.0664965 0.180622 0.0638963 0.264296 0.0602552 0.357313 0.0552119 0.461723 0.0490653 0.574257 0.0430424 0.693493 0.0416258 0.838926 1.00137 0.0694258 0.0674199 0.0647224 0.061143 0.0564088 0.0502344 0.0435628 0.0379778 0.0489684 0.0706239 0.0464117 -0.0462573 0.0729298 0.137155 -0.139461 0.077293 0.228763 -0.233126 0.0828758 0.32164 -0.327223 0.088438 0.413862 -0.419425 0.0927517 0.503629 -0.507943 0.0935327 0.591462 -0.592243 0.0864291 0.671954 -0.66485 0.0680387 0.739521 -0.721131 0.789117 -0.789052 0.0711122 0.046125 0.0738439 0.134423 0.0786051 0.224002 0.0847417 0.315504 0.0912242 0.40738 0.097253 0.497601 0.101639 0.587076 0.100785 0.672807 0.0919194 0.748387 0.812805 0.0714661 0.0455141 0.0744219 0.131467 0.0793086 0.219115 0.0855545 0.309258 0.0922067 0.400728 0.0984654 0.491342 0.103415 0.582126 0.103494 0.672728 0.0938768 0.758004 0.838374 0.0717485 0.0446358 0.0748483 0.128367 0.0797605 0.214203 0.0859525 0.303066 0.0924966 0.394184 0.0984096 0.485429 0.102799 0.577737 0.102091 0.673436 0.0913163 0.768778 0.860732 0.0719674 0.0435429 0.0751406 0.125194 0.0800028 0.20934 0.0860438 0.297025 0.0923769 0.38785 0.0978683 0.479937 0.101712 0.573893 0.10097 0.674179 0.0911268 0.778621 0.88205 0.0721263 0.0422871 0.075307 0.122014 0.0800549 0.204593 0.0858813 0.291198 0.0919786 0.381753 0.0971684 0.474748 0.100801 0.570261 0.100675 0.674304 0.0920587 0.787238 0.903616 0.0722274 0.0409195 0.0753517 0.118889 0.079921 0.200023 0.0854718 0.285648 0.091295 0.37593 0.0962332 0.469809 0.0997227 0.566771 0.100084 0.673943 0.0923598 0.794962 0.925039 0.0722727 0.0394907 0.0752787 0.115883 0.0796038 0.195698 0.0848113 0.28044 0.0902872 0.370454 0.0949188 0.465178 0.0981328 0.563557 0.0986647 0.673411 0.0917997 0.801827 0.945726 0.0722643 0.0380507 0.0750931 0.113054 0.0791082 0.191683 0.083901 0.275647 0.0889379 0.365417 0.0931689 0.460947 0.0959752 0.560751 0.0964911 0.672895 0.090574 0.807744 0.965343 0.0722049 0.0748007 0.0784416 0.0827489 0.0872536 0.0909903 0.0933061 0.0936858 0.0886841 0.498407 0.00806449 0.474921 0.0234857 0.437479 0.0374421 0.388731 0.0487476 0.332089 0.056642 0.271594 0.0604952 0.211755 0.0598393 0.157427 0.0543275 0.113719 0.0437088 0.0279981 0.0857206 0.42659 0.0155668 0.404648 0.0454276 0.369547 0.0725432 0.323246 0.0950485 0.268359 0.11153 0.208132 0.120722 0.146439 0.121532 0.0875605 0.113206 0.0362077 0.0950616 0.0671521 -0.00294627 0.365033 0.0225819 0.34442 0.066041 0.311147 0.105816 0.26653 0.139665 0.212519 0.165541 0.151564 0.181677 0.0861461 0.18695 0.0187035 0.180649 -0.0470172 0.160782 0.125675 -0.10554 0.312622 0.0288665 0.294012 0.0846515 0.263467 0.136361 0.221443 0.181689 0.168654 0.218329 0.106122 0.244209 0.0354586 0.257614 -0.0404474 0.256555 -0.116951 0.237286 0.196883 -0.18816 0.268083 0.0341846 0.252138 0.100596 0.225424 0.163075 0.187827 0.219286 0.139635 0.266522 0.0817742 0.30207 0.0144228 0.324965 -0.0642966 0.335274 -0.151709 0.324699 0.280542 -0.235368 0.230186 0.0384253 0.217245 0.113537 0.195005 0.185316 0.162671 0.251619 0.119347 0.309846 0.0642237 0.357193 -0.00326081 0.392449 -0.0832964 0.41531 -0.171474 0.412876 0.366027 -0.256959 0.197843 0.0416164 0.187843 0.123538 0.170168 0.202991 0.143671 0.278117 0.107186 0.346331 0.059999 0.40438 0.00242089 0.450028 -0.0686862 0.486417 -0.159624 0.503814 0.464732 -0.258329 0.170153 0.0438756 0.162794 0.130897 0.14932 0.216465 0.128259 0.299177 0.0978709 0.376719 0.0557996 0.446451 0.000602263 0.505225 -0.0678285 0.554848 -0.154242 0.590227 0.561377 -0.250886 0.146373 0.0453759 0.141235 0.136035 0.13147 0.226229 0.115548 0.315099 0.0919889 0.400279 0.0588215 0.479619 0.0141834 0.549863 -0.0412494 0.61028 -0.116444 0.665422 0.675169 -0.230236 0.125973 0.122548 0.115652 0.103528 0.0843817 0.0560571 0.0136776 -0.0408919 -0.0966008 -0.210484 0.0804143 0.00530626 0.0765665 0.00384796 0.0742394 0.00232713 0.0734583 0.000781161 0.0742469 -0.000788604 0.0766258 -0.00237891 0.0806134 -0.00398764 0.0862271 -0.00561372 0.0934836 -0.00725648 -0.00891515 0.102399 -0.00661587 0.00897587 -0.00948402 0.00671621 -0.0114635 0.0043067 -0.0124771 0.00179478 -0.012464 -0.000801713 -0.0113792 -0.00346368 -0.00919128 -0.00617559 -0.00588043 -0.00892456 -0.00143833 -0.0116986 -0.0144852 0.00413177 -0.108468 0.0119033 -0.11115 0.00939859 -0.113465 0.00662146 -0.11531 0.00364028 -0.116611 0.000498877 -0.117308 -0.00276603 -0.117362 -0.00612246 -0.116745 -0.00954138 -0.115449 -0.0129941 -0.0164506 -0.113484 -0.190792 0.014535 -0.193385 0.0119921 -0.195839 0.00907526 -0.198092 0.00589368 -0.200084 0.00249112 -0.201763 -0.0010874 -0.203087 -0.00479814 -0.204031 -0.00859781 -0.204584 -0.0124414 -0.0162814 -0.204753 -0.238523 0.0176908 -0.241553 0.0150217 -0.244523 0.0120449 -0.247382 0.00875303 -0.25007 0.0051792 -0.252537 0.00137967 -0.254748 -0.00258749 -0.256684 -0.00666183 -0.258345 -0.0107802 -0.0148778 -0.259749 -0.261218 0.0219501 -0.265037 0.0188406 -0.268759 0.015767 -0.272295 0.0122887 -0.275592 0.00847689 -0.27861 0.00439789 -0.281326 0.000128203 -0.283733 -0.00425538 -0.285838 -0.00867461 -0.0130523 -0.287664 -0.265427 0.0290477 -0.271424 0.0248382 -0.276972 0.0213145 -0.281948 0.0172646 -0.2864 0.0129288 -0.290322 0.00831981 -0.29371 0.00351706 -0.296561 -0.0014049 -0.298878 -0.00635707 -0.0112488 -0.300682 -0.260546 0.038708 -0.268607 0.0328986 -0.276169 0.0288767 -0.282869 0.0239648 -0.288761 0.0188211 -0.293803 0.0133613 -0.298006 0.00772026 -0.301379 0.00196768 -0.303941 -0.00379507 -0.00946992 -0.305719 -0.246211 0.0546827 -0.257563 0.0442502 -0.267492 0.0388064 -0.275771 0.0322438 -0.282868 0.0259182 -0.28887 0.0193626 -0.293868 0.0127183 -0.297885 0.0059849 -0.300931 -0.000748707 -0.00739081 -0.30301 -0.228218 -0.241454 -0.252731 -0.262176 -0.270274 -0.277116 -0.282813 -0.287409 -0.290919 -0.293344 0.112988 -0.0105888 0.125262 -0.0122748 0.139233 -0.0139706 0.154905 -0.0156722 0.17228 -0.0173748 0.191353 -0.019073 0.212115 -0.0207615 0.234554 -0.0224396 0.258672 -0.0241183 -0.0257942 0.284467 0.010813 -0.0172701 0.0185781 -0.0200399 0.0273848 -0.0227772 0.0371769 -0.0254642 0.0478831 -0.0280811 0.0594147 -0.0306046 0.0716612 -0.033008 0.0844948 -0.0352731 0.0978039 -0.0374274 -0.0394451 0.111455 -0.110879 -0.019875 -0.107678 -0.0232411 -0.103945 -0.0265096 -0.099763 -0.0296465 -0.0952268 -0.0326172 -0.0904613 -0.03537 -0.0856529 -0.0378164 -0.0810375 -0.0398885 -0.0766898 -0.0417751 -0.0436743 -0.0724606 -0.20457 -0.0200581 -0.204078 -0.0237328 -0.203346 -0.0272413 -0.202451 -0.0305415 -0.201465 -0.0336038 -0.200496 -0.0363388 -0.199825 -0.0384878 -0.199876 -0.0398372 -0.200532 -0.0411194 -0.0436311 -0.200575 -0.260933 -0.0188735 -0.261947 -0.0227192 -0.262862 -0.026326 -0.263749 -0.0296551 -0.264628 -0.0327242 -0.265538 -0.0354287 -0.266836 -0.03719 -0.269257 -0.0374159 -0.272547 -0.0378299 -0.0423034 -0.273874 -0.289245 -0.0172922 -0.290621 -0.0213437 -0.291858 -0.025089 -0.29303 -0.0284827 -0.29414 -0.0316148 -0.295127 -0.0344414 -0.296297 -0.0360195 -0.298638 -0.0350757 -0.302017 -0.0344508 -0.0416406 -0.30268 -0.302007 -0.0159675 -0.302885 -0.0204657 -0.303378 -0.0245957 -0.303589 -0.0282718 -0.303592 -0.0316114 -0.30332 -0.0347136 -0.302876 -0.0364631 -0.303152 -0.0348005 -0.304279 -0.0333232 -0.0426985 -0.303221 -0.306751 -0.0149358 -0.307055 -0.0201622 -0.306663 -0.0249877 -0.305664 -0.0292704 -0.30424 -0.0330353 -0.302454 -0.0364992 -0.300097 -0.0388208 -0.297486 -0.0374115 -0.295176 -0.0356325 -0.0469472 -0.290928 -0.30414 -0.0138064 -0.304329 -0.0199728 -0.303593 -0.0257242 -0.301963 -0.0309001 -0.299621 -0.0353775 -0.296862 -0.0392578 -0.293298 -0.0423848 -0.287883 -0.042827 -0.282036 -0.0414794 -0.0548168 -0.274166 -0.294704 -0.295011 -0.294259 -0.292417 -0.289467 -0.285599 -0.280839 -0.273105 -0.260583 -0.259245 0.388571 -0.104104 0.481862 -0.0932913 0.579312 -0.0974498 0.684739 -0.105427 0.792509 -0.10777 0.896204 -0.103695 0.992379 -0.096175 1.07715 -0.0847695 1.1486 -0.071448 1.2057 -0.0571055 1.24873 -0.0430257 1.27885 -0.0301231 1.29803 -0.019181 1.30609 -0.00805904 1.30733 -0.00124176 1.29751 0.00981963 1.28299 0.0145263 1.26189 0.0210998 1.23304 0.0288513 0.0223534 0.20093 -0.19358 0.267687 -0.160048 0.356525 -0.186288 0.452767 -0.201669 0.549575 -0.204578 0.643113 -0.197232 0.729006 -0.182068 0.803608 -0.159372 0.866048 -0.133888 0.915467 -0.106524 0.953306 -0.0808646 0.98028 -0.0570973 0.998263 -0.0371643 1.00801 -0.0178015 1.01127 -0.00451041 1.00709 0.0140021 0.998168 0.0234501 0.98343 0.0358381 0.963648 0.0486328 0.0381583 0.0178877 -0.283928 0.0847979 -0.226958 0.181296 -0.282786 0.278065 -0.298438 0.370583 -0.297096 0.455705 -0.282355 0.53009 -0.256453 0.592789 -0.222071 0.643651 -0.18475 0.683189 -0.146062 0.713215 -0.110892 0.734535 -0.0784164 0.749237 -0.0518668 0.757633 -0.0261975 0.761413 -0.00829051 0.759612 0.0158034 0.753701 0.0293612 0.74329 0.0462492 0.728862 0.0630602 0.0496446 -0.101107 -0.383396 -0.0156485 -0.312417 0.0834284 -0.381863 0.175512 -0.390522 0.259452 -0.381036 0.333222 -0.356125 0.395258 -0.318488 0.445927 -0.27274 0.485483 -0.224306 0.515706 -0.176286 0.538022 -0.133207 0.553887 -0.0942817 0.564841 -0.0628204 0.571193 -0.0325499 0.574703 -0.0118009 0.572903 0.0176036 0.568936 0.0333283 0.560709 0.0544764 0.548086 0.0756829 0.0581782 -0.172538 -0.484733 -0.0712904 -0.413664 0.0228378 -0.475991 0.108949 -0.476633 0.18485 -0.456937 0.24879 -0.420065 0.3004 -0.370097 0.34079 -0.313131 0.37114 -0.254656 0.39385 -0.198995 0.410096 -0.149453 0.421828 -0.106014 0.429815 -0.0708072 0.434789 -0.0375237 0.437704 -0.0147154 0.435783 0.019524 0.433469 0.0356429 0.425712 0.0622329 0.414263 0.0871316 0.0637937 -0.20863 -0.578782 -0.0992202 -0.523074 -0.0100103 -0.565201 0.0704786 -0.557122 0.138306 -0.524764 0.1926 -0.474359 0.234395 -0.411893 0.265654 -0.344389 0.288345 -0.277347 0.304902 -0.215552 0.316465 -0.161016 0.325006 -0.114555 0.330763 -0.0765642 0.334727 -0.0414869 0.336934 -0.0169233 0.335323 0.0211356 0.333893 0.0370732 0.326048 0.0700773 0.316509 0.0966706 0.0666638 -0.219153 -0.66285 -0.107391 -0.634835 -0.022177 -0.650416 0.0510525 -0.630351 0.109748 -0.58346 0.154387 -0.518998 0.187229 -0.444734 0.210793 -0.367953 0.227368 -0.293922 0.23915 -0.227335 0.247262 -0.169128 0.253394 -0.120687 0.257536 -0.0807062 0.260677 -0.044628 0.262282 -0.0185279 0.26114 0.0222778 0.259857 0.0383561 0.252234 0.0777004 0.245137 0.103767 0.0674215 -0.210889 -0.742889 -0.101232 -0.744493 -0.0202332 -0.731414 0.0437333 -0.694318 0.0924191 -0.632146 0.127737 -0.554315 0.152694 -0.469691 0.169944 -0.385204 0.181729 -0.305706 0.189905 -0.23551 0.195508 -0.174731 0.199841 -0.12502 0.202825 -0.0836904 0.205284 -0.0470871 0.206436 -0.0196795 0.205676 0.0230376 0.204187 0.039845 0.197283 0.0846044 0.192576 0.108475 0.0668437 -0.189637 -0.827418 -0.0865054 -0.847624 -0.0109263 -0.806993 0.0424094 -0.747654 0.0811196 -0.670856 0.10815 -0.581346 0.126554 -0.488095 0.138836 -0.397485 0.146983 -0.313854 0.152505 -0.241032 0.156299 -0.178526 0.159308 -0.128029 0.16146 -0.0858426 0.163361 -0.0489882 0.164179 -0.020497 0.163653 0.0235631 0.161922 0.0415759 0.156054 0.0904731 0.153311 0.111217 0.0655804 -0.157616 -0.929047 -0.0683011 -0.936939 -0.00145504 -0.873839 0.0419297 -0.791038 0.0721579 -0.701084 0.0925919 -0.60178 0.10597 -0.501473 0.114578 -0.406093 0.120082 -0.319358 0.123709 -0.24466 0.126219 -0.181036 0.128253 -0.130063 0.129814 -0.087404 0.131242 -0.0504158 0.131825 -0.0210808 0.131419 0.02397 0.129536 0.0434585 0.124822 0.0951873 0.123492 0.112547 0.0640709 0.106343 -0.966577 0.12656 -0.957156 0.13105 -0.87833 0.125947 -0.785935 0.117143 -0.692281 0.106353 -0.59099 0.0956501 -0.49077 0.086199 -0.396642 0.0785711 -0.31173 0.0728994 -0.238988 0.0690479 -0.177184 0.0667461 -0.127761 0.0655441 -0.086202 0.065212 -0.0500837 0.0650115 -0.0208803 0.064953 0.0240285 0.0643778 0.0440338 0.0631174 0.0964477 0.0643654 0.111299 0.0615854 0.118523 -1.01471 0.127089 -0.965723 0.12942 -0.88066 0.123063 -0.779578 0.114005 -0.683223 0.103664 -0.58065 0.0935625 -0.480668 0.0847229 -0.387802 0.0775955 -0.304602 0.0722718 -0.233664 0.0686259 -0.173538 0.0663949 -0.12553 0.0651699 -0.084977 0.0647274 -0.0496413 0.0643336 -0.0204864 0.0640345 0.0243276 0.0630714 0.0449968 0.0616057 0.0979134 0.0627656 0.110139 0.059455 0.114586 -1.05648 0.121448 -0.972585 0.123446 -0.882658 0.118211 -0.774343 0.109782 -0.674794 0.100309 -0.571177 0.0909896 -0.471348 0.0828273 -0.37964 0.0762321 -0.298007 0.0712802 -0.228712 0.0678625 -0.170121 0.0657272 -0.123395 0.0645052 -0.083755 0.0639854 -0.0491215 0.0634319 -0.0199329 0.0629326 0.0248269 0.0616484 0.046281 0.060055 0.0995068 0.061183 0.109011 0.0576469 0.112732 -1.09369 0.11777 -0.977623 0.117741 -0.882629 0.113099 -0.769701 0.105151 -0.666846 0.0965046 -0.56253 0.0880189 -0.462862 0.0805767 -0.372198 0.0745418 -0.291972 0.0699796 -0.22415 0.0668039 -0.166945 0.0647791 -0.12137 0.0635811 -0.082557 0.0630069 -0.0485472 0.0623264 -0.0192524 0.0616637 0.0254895 0.0601204 0.0478244 0.0584836 0.101144 0.0596182 0.107877 0.0561298 0.107358 -1.12384 0.112075 -0.98234 0.111069 -0.881623 0.107305 -0.765937 0.10009 -0.659631 0.0922838 -0.554724 0.0846526 -0.455231 0.0779502 -0.365496 0.072502 -0.286524 0.0683579 -0.220006 0.0654506 -0.164038 0.0635611 -0.119481 0.0624137 -0.0814096 0.06181 -0.0479436 0.0610351 -0.0184774 0.0602449 0.0262797 0.0585047 0.0495645 0.0569003 0.102748 0.058071 0.106706 0.0548734 0.102322 -1.14776 0.106273 -0.986291 0.104288 -0.879638 0.101057 -0.762706 0.0946464 -0.653221 0.087681 -0.547758 0.080918 -0.448468 0.074967 -0.359545 0.0701213 -0.281678 0.0664189 -0.216304 0.0638074 -0.161426 0.0620824 -0.117756 0.0610163 -0.0803434 0.0604111 -0.0473384 0.0595755 -0.0176418 0.0586936 0.0271616 0.0568191 0.051439 0.0553135 0.104254 0.0565417 0.105478 0.0538481 0.0962512 -1.16518 0.0994633 -0.989503 0.097075 -0.87725 0.0943276 -0.759958 0.0888293 -0.647723 0.0827332 -0.541662 0.0768507 -0.442586 0.0716619 -0.354356 0.0674302 -0.277447 0.0641871 -0.21306 0.0618946 -0.159134 0.0603617 -0.116223 0.0594069 -0.0793885 0.0588283 -0.0467598 0.0579661 -0.0167796 0.0570284 0.0280992 0.0550807 0.0533867 0.0537307 0.105604 0.0550301 0.104178 0.0530249 0.0899842 -1.17644 0.0921855 -0.991704 0.0895898 -0.874654 0.0872144 -0.757583 0.0826706 -0.643179 0.0774794 -0.536471 0.0724889 -0.437595 0.0680727 -0.34994 0.0644648 -0.273839 0.0616945 -0.21029 0.0597392 -0.157178 0.0584224 -0.114906 0.0576062 -0.0785724 0.0570813 -0.0462349 0.0562261 -0.0159245 0.0552681 0.0290573 0.0533062 0.0553486 0.0521583 0.106752 0.0535365 0.1028 0.0523752 0.0831414 -1.18165 0.0842943 -0.992857 0.08176 -0.87212 0.0797622 -0.755585 0.0762016 -0.639618 0.0719576 -0.532227 0.0678714 -0.433509 0.064238 -0.346306 0.0612622 -0.270863 0.0589753 -0.208003 0.0573712 -0.155574 0.0562904 -0.113825 0.0556367 -0.0779187 0.0551907 -0.0457889 0.0543751 -0.0151088 0.0534314 0.030001 0.051511 0.057269 0.0506015 0.107661 0.052061 0.101341 0.051871 0.0759677 0.0759692 0.0736176 0.0720266 0.0694594 0.0662044 0.0630364 0.0601956 0.0578597 0.0560645 0.0548224 0.0539934 0.0535219 0.0531776 0.0524325 0.0515369 0.0497091 0.0490646 0.0506043 ) ; boundaryField { inlet { type calculated; value nonuniform List<scalar> 40 ( -0.127168 -0.148425 -0.17319 -0.202111 -0.235857 -0.274975 -0.320147 -0.372875 -0.434964 -0.507655 -0.0707817 -0.0707623 -0.0707465 -0.0707358 -0.0707312 -0.0707339 -0.0707441 -0.0707623 -0.0707887 -0.0708241 -0.0707783 -0.0708254 -0.0708553 -0.0708701 -0.0708744 -0.0708705 -0.0708598 -0.0708439 -0.0708243 -0.070803 -0.506471 -0.434092 -0.372048 -0.318907 -0.273401 -0.234427 -0.201034 -0.172412 -0.147874 -0.126855 ) ; } outlet { type calculated; value nonuniform List<scalar> 40 ( 0.0657307 0.0730226 0.080841 0.0893451 0.0988503 0.109877 0.123156 0.139558 0.15996 0.185139 0.0494637 0.0479842 0.0465536 0.045173 0.0438439 0.0425678 0.0413463 0.040181 0.0390735 0.0380252 0.066851 0.064896 0.0629911 0.0611353 0.0593274 0.057567 0.0558533 0.0541861 0.0525653 0.050991 1.21068 0.947844 0.717376 0.539553 0.408648 0.313639 0.244379 0.193153 0.154575 0.125001 ) ; } top { type symmetryPlane; value uniform 0; } bottom { type symmetryPlane; value uniform 0; } cylinder { type calculated; value nonuniform List<scalar> 80 ( -2.24957e-18 -2.09323e-18 3.84833e-18 1.52795e-17 -1.51e-17 1.8551e-17 -4.38623e-18 -9.69617e-18 -1.31433e-18 2.12433e-17 2.12727e-18 -8.59637e-18 9.53378e-18 -1.28448e-17 -7.04719e-18 -1.34561e-17 -4.71905e-17 -3.74792e-18 2.98678e-17 -4.94195e-17 1.75591e-17 -2.98678e-17 3.74792e-18 1.9435e-17 1.48831e-17 -1.70841e-17 1.28448e-17 -9.53378e-18 8.59637e-18 3.10856e-19 2.24957e-18 2.09323e-18 -3.84833e-18 -1.52795e-17 3.70194e-18 5.29072e-18 3.48153e-17 9.69617e-18 -2.64412e-17 -4.47323e-17 2.12433e-17 2.64412e-17 -9.69617e-18 2.06958e-17 1.8551e-17 -3.70194e-18 1.52795e-17 3.84833e-18 -2.09323e-18 -2.24957e-18 -1.75591e-17 2.11226e-18 -3.74792e-18 -4.08916e-17 1.57265e-17 1.70841e-17 -1.28448e-17 9.53378e-18 -8.59637e-18 -3.10856e-19 3.10856e-19 8.59637e-18 -9.53378e-18 1.28448e-17 -1.70841e-17 1.48831e-17 4.08916e-17 3.74792e-18 -2.11226e-18 1.75591e-17 -2.12433e-17 1.31433e-18 9.69617e-18 4.38623e-18 3.30463e-17 1.51e-17 -1.52795e-17 -3.84833e-18 2.09323e-18 2.24957e-18 ) ; } frontandback { type empty; value nonuniform 0(); } } // ************************************************************************* //
[ "danieler@login2.stampede2.tacc.utexas.edu" ]
danieler@login2.stampede2.tacc.utexas.edu
fc5b102527d6c990a925318a2c6b9260ef67b781
5b78f566a26486b13cddb21ab9e41da285f5de99
/commands/QuitCommand.h
41b29f6e6d412f2a63bf949ee32a4aaaa191fa97
[]
no_license
Dominik1799/consoleTextEditor
677f51bbf010c8d28f346292a6a9319f307820d7
36f86cd3ee7881b072693fe9aba144f026faabe6
refs/heads/master
2023-02-27T16:16:53.472240
2021-01-30T17:01:57
2021-01-30T17:01:57
331,065,126
0
0
null
null
null
null
UTF-8
C++
false
false
429
h
#ifndef CONSOLETEXTEDITOR_QUITCOMMAND_H #define CONSOLETEXTEDITOR_QUITCOMMAND_H #include "Command.h" class QuitCommand : public Command { QuitCommand() = default; QuitCommand(QuitCommand const&) = default; static QuitCommand* instance; public: static QuitCommand* getInstance(); void execute(const std::vector<std::string>& commands, const Session& session); }; #endif //CONSOLETEXTEDITOR_QUITCOMMAND_H
[ "dom.horvath17@gmail.com" ]
dom.horvath17@gmail.com
3fe8198ab226789ef4d1e8fb5fcecd2d33f181b2
550adc0783e1e4b433bb2412d8c2574d4642349f
/src/primitive_collection.cpp
5b155d5bae1dd7ea0b551c6446ed2094696984a0
[]
no_license
Jacajack/rt
bef9160273632a5bfa6469d8c47f4f1ea7ef9758
e19b2e39fd262119a50e7b01340cc0e73b1edd42
refs/heads/master
2023-03-15T23:18:27.904051
2023-03-08T23:15:51
2023-03-08T23:15:51
275,005,874
0
0
null
null
null
null
UTF-8
C++
false
false
1,274
cpp
#include "primitive_collection.hpp" using rt::primitive_collection; primitive_collection::primitive_collection(const mesh_data &mesh) : triangles(mesh.get_triangles()) { } primitive_collection::primitive_collection(mesh_data &&mesh) : triangles(std::move(mesh.m_triangles)) { } primitive_collection::primitive_collection(const triangle &t) : triangles(1, t) { } primitive_collection::primitive_collection(const sphere &s) : spheres(1, s) { } primitive_collection::primitive_collection(const plane &p) : planes(1, p) { } void primitive_collection::apply_transform(const glm::mat4 &mat) { for (auto &p : triangles) p = p.transform(mat); for (auto &p : spheres) p = p.transform(mat); for (auto &p : planes) p = p.transform(mat); } void primitive_collection::assign_material(const abstract_material *material) { for (auto &p : triangles) if (!p.material) p.material = material; for (auto &p : spheres) if (!p.material) p.material = material; for (auto &p : planes) if (!p.material) p.material = material; } void primitive_collection::set_material(const abstract_material *material) { for (auto &p : triangles) p.material = material; for (auto &p : spheres) p.material = material; for (auto &p : planes) p.material = material; }
[ "mrjjot@gmail.com" ]
mrjjot@gmail.com
2636135364339d3b71679e06f2037536eb54c158
7c8832c9eb1820a3717f791122c6ab8812c6b0d7
/EducationShield/examples/Block3-Magic/Concepts/_3.5_sending_serial/_3.5_sending_serial.ino
8f50cc105069bb9669b3f733a9ebed29810f27b6
[]
no_license
isabella232/CTC-Arduino
0b117e5f364aabd9c085132178da9ec537efa32a
2c3e63339bb4a2366aa861820a607f56df66463b
refs/heads/master
2022-05-04T10:50:58.982645
2016-05-11T10:29:24
2016-05-11T10:29:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
107
ino
void setup() { Serial.begin(9600); } void loop() { Serial.println("Hola Caracola"); delay(1000); }
[ "x.yang@arduino.cc" ]
x.yang@arduino.cc
600dfeb07c20f3ce211d615141ebf98ea6cf66be
2e90876998f1378d9a8bf567dea5e094f45a6f8b
/sonicSensor/sonicSensor.ino
697d14fb5dfa43f3784eb09b0aa4a0ee03205421
[]
no_license
cciliberto33/ECE403
26289d50cb3a1996a3ca206e755a54ff87146662
6ab2f99f86cad17c1cef01a3807d8251f634cf3a
refs/heads/master
2020-08-11T04:46:56.385638
2019-11-19T03:30:46
2019-11-19T03:30:46
214,494,193
0
0
null
null
null
null
UTF-8
C++
false
false
1,238
ino
int trigPin = 2; int trigSensorPin = 52; int trigReadPin = A0; int echoPin = 48; int startProcessPin = 2; int edgeCount = 0; int prevEdgeCount = 0; double starttime = 0; double stoptime = 0; double duration = 0; double distance = 0; void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(trigPin,INPUT); pinMode(trigSensorPin,OUTPUT); pinMode(startProcessPin,INPUT); attachInterrupt(digitalPinToInterrupt(trigPin),riseCount,RISING); } void loop() { startProcess(); delay(10); } void lowpass_filter(double old, double &filtered, double alpha){ filtered = (1-alpha)*old + alpha*filtered; } void riseCount(){ edgeCount++; } double filtered_d; void startProcess(){ // things to fix:: add a timeout to waiting for a return signal.... delay(2); digitalWrite(trigSensorPin,HIGH); delayMicroseconds(10); digitalWrite(trigSensorPin,LOW); while(digitalRead(echoPin) == LOW){ } starttime = micros(); while(digitalRead(echoPin)== HIGH){ } stoptime = micros(); duration = stoptime - starttime; distance = duration / 148; lowpass_filter(distance, filtered_d, 0.01); Serial.print(distance); //in inches Serial.print("\t"); Serial.println(filtered_d); }
[ "cdc77@drexel.edu" ]
cdc77@drexel.edu
6cb79f0423345825dd73181f8785d1cebb237efc
a269f85bd94d43122f7d8000582d9000a3491186
/src/create/create_error_model/error_hierarchy.h
95a9e1cd6b99f6246f6e99a8bbb9877a2e001980
[ "BSD-2-Clause" ]
permissive
ufal/korektor
462265249bdc1f64689f341defd49f24ab160564
9dba14b97babfe201e016926d4029bbff2cd1b4f
refs/heads/master
2023-06-19T19:02:05.915989
2023-02-22T13:59:39
2023-02-22T13:59:39
22,339,583
19
5
null
2017-11-13T07:29:15
2014-07-28T10:56:25
C++
UTF-8
C++
false
false
6,036
h
// This file is part of korektor <http://github.com/ufal/korektor/>. // // Copyright 2015 by Institute of Formal and Applied Linguistics, Faculty // of Mathematics and Physics, Charles University in Prague, Czech Republic. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under 3-clause BSD licence. #pragma once #include <unordered_map> #include "common.h" #include "error_model/error_model.h" #include "utils/io.h" #include "utils/utf.h" namespace ufal { namespace korektor { class hierarchy_node; typedef shared_ptr<hierarchy_node> hierarchy_nodeP; class hierarchy_node { public: static unordered_map<u16string, hierarchy_nodeP> hierarchy_map; static hierarchy_nodeP root; u16string signature; hierarchy_nodeP parent; vector<hierarchy_nodeP> children; unsigned num_governed_leaves; unsigned error_count; float error_prob; unsigned edit_distance; unsigned context_count; bool is_output_node; private: hierarchy_node(const u16string &_signature): signature(_signature), num_governed_leaves(1), error_count(0), edit_distance(1), is_output_node(false) {} public: static bool ContainsNode(const u16string &_signature) { return hierarchy_map.find(_signature) != hierarchy_map.end(); } static hierarchy_nodeP GetNode(const u16string &_signature) { return hierarchy_map.find(_signature)->second; } static hierarchy_nodeP create_SP(const u16string &_signature, hierarchy_nodeP &_parent, const u16string &context_chars) { //cerr << "constructing hierarchy node: " << UTF::UTF16To8(_signature) << endl; hierarchy_nodeP ret = hierarchy_nodeP(new hierarchy_node(_signature)); ret->parent = _parent; if (_parent) { _parent->children.push_back(ret); if (_parent->children.size() > 1) { _parent->num_governed_leaves++; hierarchy_nodeP aux = _parent->parent; while (aux) { aux->num_governed_leaves++; aux = aux->parent; } } } hierarchy_map[_signature] = ret; for (unsigned i = 0; i < _signature.length(); i++) { if (_signature[i] == char16_t('.')) { u16string sig_copy = _signature; for (unsigned j = 0; j < context_chars.length(); j++) { sig_copy[i] = context_chars[j]; if (ContainsNode(sig_copy) == false) hierarchy_node::create_SP(sig_copy, ret, context_chars); } } } //cerr << "construction finished: " << UTF::UTF16To8(_signature) << endl; return ret; } static void print_hierarchy_rec(hierarchy_nodeP &node, unsigned level, ostream &os) { for (unsigned i = 0; i < level; i++) os << "\t"; string s = UTF::UTF16To8(node->signature); os << s << endl; for (auto it = node->children.begin(); it != node->children.end(); it++) print_hierarchy_rec(*it, level + 1, os); } static pair<hierarchy_nodeP, unsigned> read_hierarchy(string s, hierarchy_nodeP node, unsigned level) { //cerr << s << endl; unsigned new_level = 0; while (s[new_level] == '\t') new_level++; while (level >= new_level) { node = node->parent; level--; } assert(new_level > 0 && new_level < 10); assert(level + 1 == new_level); u16string signature = UTF::UTF8To16(s.substr(new_level)); //cerr << "signature: " << UTF::UTF16To8(signature) << endl; hierarchy_nodeP new_node = hierarchy_nodeP(new hierarchy_node(signature)); hierarchy_node::hierarchy_map.insert(make_pair(signature, new_node)); node->children.push_back(new_node); new_node->parent = node; return make_pair(new_node, new_level); } static void ReadHierarchy(istream &is) { string s; if (IO::ReadLine(is, s)) { assert(s == "root"); hierarchy_node::root = hierarchy_nodeP(new hierarchy_node(UTF::UTF8To16("root"))); hierarchy_map.insert(make_pair(root->signature, root)); pair<hierarchy_nodeP, unsigned> node_level_pair = make_pair(root, 0); while (IO::ReadLine(is, s)) { node_level_pair = read_hierarchy(s, node_level_pair.first, node_level_pair.second); } } } static void output_result_rec(hierarchy_nodeP &node, unsigned level, unsigned prop_level, float inherited_prob, u16string prop_signature, vector<pair<u16string, ErrorModelOutput>> &out_vec) { // if (level == 1) // { // if (node->is_output_node) // { // out_vec.push_back(make_pair(node->signature, ErrorModelOutput(node->edit_distance, node->error_prob))); // //ofs << UTF::UTF16To8(node->signature) << "\t" << node->edit_distance << "\t" << node->error_prob << endl; // } // } if (node->children.empty()) { if (prop_level == 1 && node->children.empty() && node->is_output_node == false) return; if (node->is_output_node) { out_vec.push_back(make_pair(node->signature, ErrorModelOutput(node->edit_distance, node->error_prob))); //ofs << UTF::UTF16To8(node->signature) << "\t" << node->edit_distance << "\t" << node->error_prob << endl; } else { out_vec.push_back(make_pair(node->signature, ErrorModelOutput(node->edit_distance, inherited_prob))); //ofs << UTF::UTF16To8(node->signature) << "\t" << node->edit_distance << "\t" << inherited_prob /*<< "(" << UTF::UTF16To8(prop_signature) << ")"*/ << endl; } } float propagated_value; if (node->is_output_node) { cerr << "propagating: " << UTF::UTF16To8(node->signature) << endl; propagated_value = node->error_prob; prop_signature = node->signature; prop_level = level; } else propagated_value = inherited_prob; for (auto it = node->children.begin(); it != node->children.end(); it++) { output_result_rec((*it), level + 1, prop_level, propagated_value, prop_signature, out_vec); } } }; } // namespace korektor } // namespace ufal
[ "fox@ucw.cz" ]
fox@ucw.cz
595f6b296f20a301f77c2c7f5a5d23ca73e3ea2a
0650aa719a8684b51967599421b913f957518590
/src/PythonObjectIndexed.cpp
3476fd12f35fe7b9da6c3aa4afda48bb4dd09fec
[ "Apache-2.0" ]
permissive
darwin/naga
2c281bda1edf70e350adf0551436a6cc7b19c009
b7c3ba2569a12c8a8dac0fdab1f74a6338ec74ca
refs/heads/master
2022-09-11T16:10:10.594172
2020-05-25T00:24:30
2020-05-25T00:24:30
251,027,228
1
0
null
null
null
null
UTF-8
C++
false
false
6,708
cpp
#include "PythonObject.h" #include "PythonExceptions.h" #include "Wrapping.h" #include "Logging.h" #include "PythonUtils.h" #include "Printing.h" #include "Utils.h" #include "V8XUtils.h" #define TRACE(...) \ LOGGER_INDENT; \ SPDLOG_LOGGER_TRACE(getLogger(kPythonObjectLogger), __VA_ARGS__) void PythonObject::IndexedGetter(uint32_t index, const v8::PropertyCallbackInfo<v8::Value>& v8_info) { TRACE("CPythonObject::IndexedGetter index={} v8_info={}", index, v8_info); auto v8_isolate = v8x::lockIsolate(v8_info.GetIsolate()); auto v8_scope = v8x::withScope(v8_isolate); auto v8_result = withPythonErrorInterception(v8_isolate, [&]() { auto py_gil = pyu::withGIL(); auto py_obj = wrap(v8_isolate, v8_info.Holder()); if (PyGen_Check(py_obj.ptr())) { return v8::Undefined(v8_isolate).As<v8::Value>(); } if (PySequence_Check(py_obj.ptr())) { if (static_cast<Py_ssize_t>(index) < PySequence_Size(py_obj.ptr())) { auto ret(py::reinterpret_steal<py::object>(PySequence_GetItem(py_obj.ptr(), index))); return wrap(ret); } else { return v8::Undefined(v8_isolate).As<v8::Value>(); } } if (PyMapping_Check(py_obj.ptr())) { char buf[65]; snprintf(buf, sizeof(buf), "%d", index); PyObject* raw_value = PyMapping_GetItemString(py_obj.ptr(), buf); if (!raw_value) { py::int_ py_index(index); raw_value = PyObject_GetItem(py_obj.ptr(), py_index.ptr()); } if (raw_value) { return wrap(py::reinterpret_steal<py::object>(raw_value)); } else { return v8::Undefined(v8_isolate).As<v8::Value>(); } } return v8::Undefined(v8_isolate).As<v8::Value>(); }); auto v8_final_result = VALUE_OR_LAZY(v8_result, v8::Undefined(v8_isolate)); v8_info.GetReturnValue().Set(v8_final_result); } void PythonObject::IndexedSetter(uint32_t index, v8::Local<v8::Value> v8_value, const v8::PropertyCallbackInfo<v8::Value>& v8_info) { TRACE("CPythonObject::IndexedSetter index={} v8_value={} v8_info={}", index, v8_value, v8_info); auto v8_isolate = v8x::lockIsolate(v8_info.GetIsolate()); auto v8_scope = v8x::withScope(v8_isolate); auto v8_result = withPythonErrorInterception(v8_isolate, [&]() { auto py_gil = pyu::withGIL(); auto py_obj = wrap(v8_isolate, v8_info.Holder()); if (PySequence_Check(py_obj.ptr())) { if (PySequence_SetItem(py_obj.ptr(), index, wrap(v8_isolate, v8_value).ptr()) < 0) { auto v8_msg = v8::String::NewFromUtf8(v8_isolate, "fail to set indexed value").ToLocalChecked(); auto v8_ex = v8::Exception::Error(v8_msg); v8_isolate->ThrowException(v8_ex); } } else if (PyMapping_Check(py_obj.ptr())) { char buf[65]; snprintf(buf, sizeof(buf), "%d", index); if (PyMapping_SetItemString(py_obj.ptr(), buf, wrap(v8_isolate, v8_value).ptr()) < 0) { auto v8_msg = v8::String::NewFromUtf8(v8_isolate, "fail to set named value").ToLocalChecked(); auto v8_ex = v8::Exception::Error(v8_msg); v8_isolate->ThrowException(v8_ex); } } return v8_value; }); auto v8_final_result = VALUE_OR_LAZY(v8_result, v8::Undefined(v8_isolate)); v8_info.GetReturnValue().Set(v8_final_result); } void PythonObject::IndexedQuery(uint32_t index, const v8::PropertyCallbackInfo<v8::Integer>& v8_info) { TRACE("CPythonObject::IndexedQuery index={} v8_info={}", index, v8_info); auto v8_isolate = v8x::lockIsolate(v8_info.GetIsolate()); auto v8_scope = v8x::withScope(v8_isolate); auto v8_result = withPythonErrorInterception(v8_isolate, [&]() { auto py_gil = pyu::withGIL(); auto py_obj = wrap(v8_isolate, v8_info.Holder()); if (PyGen_Check(py_obj.ptr())) { return v8::Integer::New(v8_isolate, v8::ReadOnly); } if (PySequence_Check(py_obj.ptr())) { if (static_cast<Py_ssize_t>(index) < PySequence_Size(py_obj.ptr())) { return v8::Integer::New(v8_isolate, v8::None); } else { return v8::Local<v8::Integer>(); } } if (PyMapping_Check(py_obj.ptr())) { // TODO: revisit this char buf[65]; snprintf(buf, sizeof(buf), "%d", index); auto py_index = py::int_(index); if (PyMapping_HasKeyString(py_obj.ptr(), buf) || PyMapping_HasKey(py_obj.ptr(), py_index.ptr())) { return v8::Integer::New(v8_isolate, v8::None); } else { return v8::Local<v8::Integer>(); } } return v8::Local<v8::Integer>(); }); auto v8_final_result = VALUE_OR_LAZY(v8_result, v8::Local<v8::Integer>()); v8_info.GetReturnValue().Set(v8_final_result); } void PythonObject::IndexedDeleter(uint32_t index, const v8::PropertyCallbackInfo<v8::Boolean>& v8_info) { TRACE("CPythonObject::IndexedDeleter index={} v8_info={}", index, v8_info); auto v8_isolate = v8x::lockIsolate(v8_info.GetIsolate()); auto v8_scope = v8x::withScope(v8_isolate); auto v8_result = withPythonErrorInterception(v8_isolate, [&]() { auto py_gil = pyu::withGIL(); auto py_obj = wrap(v8_isolate, v8_info.Holder()); if (PySequence_Check(py_obj.ptr()) && static_cast<Py_ssize_t>(index) < PySequence_Size(py_obj.ptr())) { auto result = 0 <= PySequence_DelItem(py_obj.ptr(), index); return v8::Boolean::New(v8_isolate, result); } if (PyMapping_Check(py_obj.ptr())) { char buf[65]; snprintf(buf, sizeof(buf), "%d", index); auto result = PyMapping_DelItemString(py_obj.ptr(), buf) == 0; return v8::Boolean::New(v8_isolate, result); } return v8::Local<v8::Boolean>(); }); auto v8_final_result = VALUE_OR_LAZY(v8_result, v8::Local<v8::Boolean>()); v8_info.GetReturnValue().Set(v8_final_result); } void PythonObject::IndexedEnumerator(const v8::PropertyCallbackInfo<v8::Array>& v8_info) { TRACE("CPythonObject::IndexedEnumerator v8_info={}", v8_info); auto v8_isolate = v8x::lockIsolate(v8_info.GetIsolate()); auto v8_scope = v8x::withScope(v8_isolate); auto v8_result = withPythonErrorInterception(v8_isolate, [&]() { auto py_gil = pyu::withGIL(); auto py_obj = wrap(v8_isolate, v8_info.Holder()); auto len = PySequence_Check(py_obj.ptr()) ? PySequence_Size(py_obj.ptr()) : 0; auto v8_array = v8::Array::New(v8_isolate, len); auto v8_context = v8x::getCurrentContext(v8_isolate); for (Py_ssize_t i = 0; i < len; i++) { auto v8_i = v8::Integer::New(v8_isolate, i); v8_array->Set(v8_context, v8_i, v8_i).Check(); } return v8_array; }); auto v8_final_result = VALUE_OR_LAZY(v8_result, v8::Local<v8::Array>()); v8_info.GetReturnValue().Set(v8_final_result); }
[ "antonin@hildebrand.cz" ]
antonin@hildebrand.cz
a22917d3c3f8bb7cf53e488ef04c4516c3ef5a0d
8ed61980185397f8a11ad5851e3ffff09682c501
/thirdparty/GeometricTools/WildMagic5/SamplePhysics/CollisionsMovingSpheres/SphereColliders.h
a23e5a6f8c45780b872f3e7920609c1319f5ecbf
[ "BSD-2-Clause-Views" ]
permissive
SoMa-Project/vision
8975a2b368f69538a05bd57b0c3eda553b783b55
ea8199d98edc363b2be79baa7c691da3a5a6cc86
refs/heads/melodic
2023-04-12T22:49:13.125788
2021-01-11T15:28:30
2021-01-11T15:28:30
80,823,825
1
0
NOASSERTION
2021-04-20T21:27:03
2017-02-03T11:36:44
C++
UTF-8
C++
false
false
1,466
h
// Geometric Tools, LLC // Copyright (c) 1998-2014 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // // File Version: 5.2.0 (2010/06/21) #ifndef SPHERECOLLIDERS_H #define SPHERECOLLIDERS_H #include "Colliders.h" #include "Wm5Sphere3.h" // An implementation of a class derived from Colliders to illustrate // intersection queries for spheres moving with constant linear velocity. // The member functions are based on the discussion in Section 8.3.2 of // "3D Game Engine Design, 2nd edition". class SphereColliders : public Colliders { public: // Construction and destruction. SphereColliders (const Sphere3f& sphere0, const Sphere3f& sphere1); virtual ~SphereColliders (); // Call this function after a Test or Find call *and* when // GetContactTime() returns a value T such that 0 <= T <= maxTime, // where fMaxTime > 0 is the value supplied to the Test or Find call. Vector3f GetContactPoint () const; protected: virtual float Pseudodistance (float time, const Vector3f& velocity0, const Vector3f& velocity1) const; virtual void ComputeContactInformation (CollisionType type, float time, const Vector3f& velocity0, const Vector3f& velocity1); const Sphere3f* mSphere0; const Sphere3f* mSphere1; Vector3f mContactPoint; }; #endif
[ "j.abele@tu-berlin.de" ]
j.abele@tu-berlin.de
01d079fd3731bf783105ea5592b716b1c88fe202
b06d5e9486da9aec825bc5eb3bf9c6a0e2d85200
/0235-Lowest-Common-Ancestor-Of-a-Binary-Search-Tree/main.cpp
b73b098672e44ee5364812d9bde92455ce6acf06
[]
no_license
iiicp/leetcode_practice
0687935e719215dd1c6247148d87d5880c1d4ba6
2ea942548b2f72b92c2988b7ed4641456c24de27
refs/heads/main
2023-02-11T17:11:03.464885
2021-01-07T13:30:12
2021-01-07T13:30:12
321,615,183
0
0
null
null
null
null
UTF-8
C++
false
false
2,767
cpp
/********************************** * File: main.cpp.c * * Author: caipeng * * Email: iiicp@outlook.com * * Date: 2020/12/16 ***********************************/ #include <iostream> #include <stack> #include <queue> #include <string> #include <unordered_map> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} }; /** * 重点设计:返回树的跟结点 */ void _recurseve(TreeNode* &root, int *arr, int len, int index) { if (index >= len || arr[index] == -1) { return; } // -1 mean null node root = new TreeNode(arr[index]); _recurseve(root->left, arr, len, 2 * index + 1); _recurseve(root->right, arr, len, 2 * index + 2); } TreeNode *create_tree(int *arr, int len) { TreeNode *root = nullptr; _recurseve(root, arr, len, 0); return root; } void Print(TreeNode* p) { if (NULL == p) return; cout << p->val; Print(p->left); Print(p->right); } class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if (root == nullptr) return root; assert(p && q); if (p->val < root->val && q->val < root->val) { return lowestCommonAncestor(root->left, p, q); }else if (p->val > root->val && q->val > root->val) { return lowestCommonAncestor(root->right, p, q); } return root; } }; int main() { /* * 5 * / \ * 4 8 * / \ / \ * 2 null 6 9 * 1 3 null null null null null 1 */ // [5,4,8,11,null,13,4,7,2,null,null,null,1] // 22 int arr[] = { 5,4,8,2,-1,6,9, 1,3,-1,-1,-1,-1,-1,1}; int n = sizeof(arr)/sizeof(int); TreeNode *root = create_tree(arr, n); Print(root); std::cout << std::endl; // int arr1[] = { 0, 1, 2, -1, -1, 3, -1 }; // int n1 = sizeof(arr1)/sizeof(int); // TreeNode *root1 = create_tree(arr1, n1); // Print(root1); // std::cout << std::endl; TreeNode *node = Solution().lowestCommonAncestor(root, root->left->left, root->left); if (node) { std::cout << node->val << std::endl; }else { std::cout << "null" << std::endl; } std::cout << root->val << ", " << root->left->left->val << ", " << root->right->val << std::endl; node = Solution().lowestCommonAncestor(root, root->left->left, root->right); if (node) { std::cout << node->val << std::endl; }else { std::cout << "null" << std::endl; } return 0; }
[ "2581502433@qq.com" ]
2581502433@qq.com
bd84f9f504927aeb6542b0038390d3809f704b45
064fa3a04e60f1e1e7ce508726ba770f3e2c9cc2
/Asgn09/Asgn09/Converter (2014_09_26 04_34_37 UTC).h
4e9a6ca97647cc9c091a9f2678e18988e6cc056f
[]
no_license
morellja/CSA-274_Data-Structures
b99335c8669932c31c775a4a3a10a3626ff914ef
960cb4f725386d4fc7c27b402eab79833f2fdc22
refs/heads/master
2020-09-20T18:20:12.396804
2016-08-18T19:03:32
2016-08-18T19:03:32
66,023,588
1
0
null
null
null
null
UTF-8
C++
false
false
813
h
// // Name : // Instructor Name : // Course Number and Section : // Asgn02.cpp : Defines the entry point for the console application. // #pragma once #include <string> using namespace std; class CurrencyConverter { private: double exchangeRate; string fromUnits; string toUnits; public: // Constructor for the class CurrencyConverter(string, string); // Sets the exchange rate void setExchangeRate(double); // Gets the exchange rate double getExchangeRate(void); // Exchange currency double exchangeCurrency(double); // Units string getFromUnits(void); // Units string getToUnits(void); // Print the object // Implement inline friend ostream & operator << (ostream &o, CurrencyConverter &c) { o << c.fromUnits << " to " << c.toUnits << " = " << c.exchangeRate; return o; } };
[ "jmorell1588@gmail.com" ]
jmorell1588@gmail.com
8914731c02bd2ab882e725403163bd290b13412b
c944f46d8c75ea6957585c4fcadd88dfe2bb9ca7
/01_Math/01_群论/07_区间筛.cpp
1f695c83bf4a1dda1f59d3d5b16a979ea7c31c88
[ "MIT" ]
permissive
Aichuanbaizhequn/Template
7e7cacc21295b8b339c229f30f66c4e42fcb6323
99b129284567896c37f9ac271e77099d300e7565
refs/heads/master
2023-04-29T02:36:47.845288
2021-05-07T08:48:14
2021-05-07T08:48:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
683
cpp
bool f[maxlen]; bool sieve[maxn]; // maxn 至少为 sqrt(R),预处理 void init() { for (int i = 2; i < maxn; i++) sieve[i] = true; for (int i = 2; i * i < maxn; i++) { if (sieve[i]) { for (int j = i * 2; j < maxn; j += i) { sieve[j] = false; } } } } // 计算 [L,R] 素性,f[i] 为 1 表示 i+L 为素数 void cal(ll L, ll R) { int len = R - L + 1; for (int i = 0; i < len; i++) f[i] = true; if (1 - L >= 0) f[1 - L] = false; for (ll i = 2; i * i < R; i++) { if (sieve[i]) { for (ll j = max(1ll * 2, (L - 1 + i) / i) * i; j <= R; j += i) f[j - L] = false; } } }
[ "badcw123@gmail.com" ]
badcw123@gmail.com
9161bfa812aea3a867ff3957528050ddcd31b2b8
adb23ab9c2db760afa93c09a1737687ae2431466
/DgEngine/LineSegment4.cpp
d8e02a12dd79065f4f1de7a6337bac0491fb7a9d
[]
no_license
int-Frank/SoftwareRasterizer
cb5d3234dcd59f55e6384a7152e0bb81cabc0401
f62d5bf7e16b0cefe9dd46b255341ba0cea0893d
refs/heads/master
2021-09-08T04:16:39.613309
2014-09-12T23:13:23
2014-09-12T23:13:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
21,920
cpp
//================================================================================ // @ LineSegment4.cpp // // Description: // // This file defines LineSegment4's methods and Testing functions // involving LineSegments, Rays and Lines. // // ------------------------------------------------------------------------------- // // Original Authors: James M. Van Verth, Lars M. Bishop // Retrieved From: Essential Mathematics for Games and Interactive Applications SE // On Date: 2013 // // Modified by: Frank Hart // Date last modified: 2013 // //================================================================================ #include "LineSegment4.h" #include "Line4.h" #include "Ray4.h" #include "CommonMath.h" //-------------------------------------------------------------------------------- // @ LineSegment4::LineSegment4() //-------------------------------------------------------------------------------- // Constructor //-------------------------------------------------------------------------------- LineSegment4::LineSegment4(): origin(0.0f, 0.0f, 0.0f), direction(1.0f, 0.0f, 0.0f) { } //End: LineSegment4::LineSegment4 //-------------------------------------------------------------------------------- // @ LineSegment4::LineSegment4() //-------------------------------------------------------------------------------- // Constructor //-------------------------------------------------------------------------------- LineSegment4::LineSegment4(const Point4& p1, const Point4& p2): origin(p1), direction(p2-p1) { } //End: LineSegment4::LineSegment4() //-------------------------------------------------------------------------------- // @ LineSegment4::LineSegment4() //-------------------------------------------------------------------------------- // Copy constructor //-------------------------------------------------------------------------------- LineSegment4::LineSegment4(const LineSegment4& other): origin(other.origin), direction(other.direction) { } //End: LineSegment4::LineSegment4() //-------------------------------------------------------------------------------- // @ LineSegment4::operator=() //-------------------------------------------------------------------------------- // Assignment operator //-------------------------------------------------------------------------------- LineSegment4& LineSegment4::operator= (const LineSegment4& other) { origin = other.origin; direction = other.direction; return *this; } //End: LineSegment4::operator= //-------------------------------------------------------------------------------- // @ operator<<() //-------------------------------------------------------------------------------- // Output //-------------------------------------------------------------------------------- DgWriter& operator<<(DgWriter& out, const LineSegment4& source) { out << "[" << source.GetP1() << ", " << source.GetP2() << "]"; return out; } // End of operator<<() //-------------------------------------------------------------------------------- // @ LineSegment4::Get() //-------------------------------------------------------------------------------- // Accessor //-------------------------------------------------------------------------------- void LineSegment4::Get(Point4& p1, Point4& p2) const { p1 = origin; p2 = origin + direction; } //End: LineSegment4::Get() //-------------------------------------------------------------------------------- // @ LineSegment4::Length() //-------------------------------------------------------------------------------- // Returns length of the LineSegment //-------------------------------------------------------------------------------- float LineSegment4::Length() const { return direction.Length(); } //End: LineSegment4::Length() //-------------------------------------------------------------------------------- // @ LineSegment4::LengthSquared() //-------------------------------------------------------------------------------- // Returns length squared of the LineSegment //-------------------------------------------------------------------------------- float LineSegment4::LengthSquared() const { return direction.LengthSquared(); } //End: LineSegment4::LengthSquared() //-------------------------------------------------------------------------------- // @ LineSegment4::operator==() //-------------------------------------------------------------------------------- // Are two LineSegment4's equal? //-------------------------------------------------------------------------------- bool LineSegment4::operator== (const LineSegment4& LS) const { return ((LS.origin == origin && LS.direction == direction) || (LS.origin == origin+direction && LS.direction == -direction)); } //End: LineSegment4::operator==() //-------------------------------------------------------------------------------- // @ LineSegment4::operator!=() //-------------------------------------------------------------------------------- // Are two LineSegment4's not equal? //-------------------------------------------------------------------------------- bool LineSegment4::operator!= (const LineSegment4& LS) const { return !((LS.origin == origin && LS.direction == direction) || (LS.origin == origin+direction && LS.direction == -direction)); } //End: LineSegment4::operator!= //-------------------------------------------------------------------------------- // @ LineSegment4::ClosestPoint() //--------------------------------------------------------------------------- // Returns the closest point on line segment to point //----------------------------------------------------------------------------- Point4 LineSegment4::ClosestPoint( const Point4& point ) const { Vector4 w = point - origin; float proj = Dot(w,direction); // endpoint 0 is closest point if ( proj <= 0.0f ) return origin; else { float vsq = Dot(direction,direction); // endpoint 1 is closest point if ( proj >= vsq ) return origin + direction; // else somewhere else in segment else return origin + (proj/vsq)*direction; } } //End: ClosestPoint() //-------------------------------------------------------------------------------- // @ SqDistLineSegmentLineSegment() //-------------------------------------------------------------------------------- /* Summary: Shortest distance (squared) between two LineSegments -------------------------------------- Post: returns 1. sqDist set, u1 and u2 are set. -------------------------------------- Param<LS1>: input linesegment Param<LS2>: input linesegment Param<sqDist>: squared distance between the linesegments Param<u1>: distance along LS1 to the intersection or closest point to LS2 Param<u2>: distance along LS2 to the intersection or closest point to LS1 */ //-------------------------------------------------------------------------------- uint8 SqDistLineSegmentLineSegment(const LineSegment4& LS1, const LineSegment4& LS2, float& sqDist, float& u1, float& u2) { Point4 o1 = LS1.Origin(); Point4 o2 = LS2.Origin(); Vector4 d1 = LS1.Direction(); Vector4 d2 = LS2.Direction(); //compute intermediate parameters Vector4 w0 = o1 - o2; float a = Dot(d1, d1); float b = Dot(d1, d2); float c = Dot(d2, d2); float d = Dot(d1, w0); float e = Dot(d2, w0); float denom = a*c - b*b; //parameters to compute u1 and u2 float sn, sd, tn, td; //if denom is zero, try finding closest point on LS2 to origin if (::IsZero(denom)) { sd = td = c; sn = 0.0f; tn = e; } else { //clamp u1 within [0,1] sd = td = denom; sn = b*e - c*d; tn = a*e - b*d; //clamp u1 to 0 if (sn < 0.0f) { sn = 0.0f; tn = e; td = c; } //clamp u1 to 1 else if (sn > sd) { sn = sd; tn = e + b; td = c; } } // clamp u2 within [0,1] // clamp u2 to 0 if (tn < 0.0f) { u2 = 0.0f; // clamp u1 to 0 if ( -d < 0.0f ) { u1 = 0.0f; } // clamp u1 to 1 else if ( -d > a ) { u1 = 1.0f; } else { u1 = -d/a; } } // clamp u2 to 1 else if (tn > td) { u2 = 1.0f; // clamp u1 to 0 if ( (-d+b) < 0.0f ) { u1 = 0.0f; } // clamp u1 to 1 else if ( (-d+b) > a ) { u1 = 1.0f; } else { u1 = (-d+b)/a; } } else { u2 = tn/td; u1 = sn/sd; } //compute difference vector and distance squared Vector4 wc = w0 + u1*d1 - u2*d2; sqDist = wc.LengthSquared(); return 1; } //End: SqDistLineSegmentLineSegment() //-------------------------------------------------------------------------------- // @ SqDistLineLineSegment() //-------------------------------------------------------------------------------- /* Summary: Shortest distance (squared) between a Line and a LineSegment. -------------------------------------- Post: returns 1. sqDist set, ul and uls are set. -------------------------------------- Param<L>: input line Param<LS>: input linesegment Param<sqDist>: squared distance between the linesegments Param<ul>: distance along L to the intersection or closest point to LS Param<uls>: distance along LS to the intersection or closest point to L */ //-------------------------------------------------------------------------------- uint8 SqDistLineLineSegment(const Line4& L, const LineSegment4& LS, float& sqDist, float& ul, float& uls ) { Point4 os = LS.Origin(); Point4 ol = L.Origin(); Vector4 ds = LS.Direction(); Vector4 dl = L.Direction(); //compute intermediate parameters Vector4 w0 = os - ol; float a = Dot(ds, ds); float b = Dot(ds, dl); float c = Dot(dl, dl); float d = Dot(ds, w0); float e = Dot(dl, w0); float denom = a*c - b*b; // if denom is zero, try finding closest point on segment1 to origin0 if ( ::IsZero(denom) ) { uls = 0.0f; ul = e/c; // compute difference vector and distance squared Vector4 wc = w0 - ul*dl; sqDist = Dot(wc,wc); return 1; } else { // parameters to compute uls, ul float sn; // clamp uls within [0,1] sn = b*e - c*d; // clamp uls to 0 if (sn < 0.0f) { uls = 0.0f; ul = e/c; } // clamp uls to 1 else if (sn > denom) { uls = 1.0f; ul = (e+b)/c; } else { uls = sn/denom; ul = (a*e - b*d)/denom; } // compute difference vector and distance squared Vector4 wc = w0 + uls*ds - ul*dl; sqDist = wc.LengthSquared(); return 1; } } // End of ::SqDistLineLineSegment() //-------------------------------------------------------------------------------- // @ SqDistLineSegmentRay() //-------------------------------------------------------------------------------- /* Summary: Shortest distance (squared) between a LineSegment and a Ray. -------------------------------------- Post: returns 1. sqDist set, uls and ur are set. -------------------------------------- Param<LS>: input line Param<R>: input linesegment Param<sqDist>: squared distance between the linesegments Param<uls>: distance along LS to the intersection or closest point to R Param<ur>: distance along R to the intersection or closest point to LS */ //-------------------------------------------------------------------------------- uint8 SqDistLineSegmentRay( const LineSegment4& LS, const Ray4& R, float& sqDist, float& uls, float& ur ) { Point4 os = LS.Origin(); Point4 or = R.Origin(); Vector4 ds = LS.Direction(); Vector4 dr = R.Direction(); //compute intermediate parameters Vector4 w0 = os - or; float a = Dot(ds, ds); float b = Dot(ds, dr); float c = Dot(dr, dr); float d = Dot(ds, w0); float e = Dot(dr, w0); float denom = a*c - b*b; // parameters to compute uls, ur float sn, sd, tn, td; // if denom is zero, try finding closest point on segment1 to origin0 if ( ::IsZero(denom) ) { // clamp uls to 0 sd = td = c; sn = 0.0f; tn = e; } else { // clamp uls within [0,1] sd = td = denom; sn = b*e - c*d; tn = a*e - b*d; // clamp uls to 0 if (sn < 0.0f) { sn = 0.0f; tn = e; td = c; } // clamp uls to 1 else if (sn > sd) { sn = sd; tn = e + b; td = c; } } // clamp ur within [0,+inf] // clamp ur to 0 if (tn < 0.0f) { ur = 0.0f; // clamp uls to 0 if ( -d < 0.0f ) { uls = 0.0f; } // clamp uls to 1 else if ( -d > a ) { uls = 1.0f; } else { uls = -d/a; } } else { ur = tn/td; uls = sn/sd; } // compute difference vector and distance squared Vector4 wc = w0 + uls*ds - ur*dr; sqDist = wc.LengthSquared(); return 1; } // End of ::SqDistLineSegmentRay() //-------------------------------------------------------------------------------- // @ SqDistLineSegmentPoint() //-------------------------------------------------------------------------------- /* Summary: Shortest distance (squared) between a LineSegment and a Point. -------------------------------------- Post: Case endpoint 0 is closest: returns 1. P, u set. Case endpoint 1 is closest: returns 2. P, u set. Case somewhere in the middle: returns 3. P, u set. -------------------------------------- Param<LS>: input linesegment Param<P>: closest point is stored here Param<sqDist>: distance to P Param<u>: distance along LS to the closest point to P */ //-------------------------------------------------------------------------------- uint8 SqDistLineSegmentPoint( const LineSegment4& LS, const Point4& P, float& sqDist, float& u ) { Vector4 ds = LS.Direction(); Vector4 w = P - LS.Origin(); float proj = Dot(w,ds); // endpoint 0 is closest point if ( proj <= 0 ) { u = 0.0f; sqDist = w.LengthSquared(); return 1; } else { float vsq = Dot(ds, ds); // endpoint 1 is closest point if ( proj >= vsq ) { u = 1.0f; sqDist = w.LengthSquared() - 2.0f*proj + vsq; return 2; } // otherwise somewhere else in segment else { u = proj/vsq; sqDist = w.LengthSquared() - u*proj; return 3; } } } // End of ::SqDistLineSegmentPoint() //-------------------------------------------------------------------------------- // @ ClosestPointsLineSegmentLineSegment() //-------------------------------------------------------------------------------- /* Summary: Finds the closest points between two linesegments -------------------------------------- Post: returns 1. p1, p2 set. -------------------------------------- Param<segment1>: input linesegment Param<segment2>: input linesegment Param<p1>: point along segment1 closest to segment2 Param<p2>: point along segment2 closest to segment1 */ //-------------------------------------------------------------------------------- uint8 ClosestPointsLineSegmentLineSegment( const LineSegment4& segment1, const LineSegment4& segment2, Point4& p1, Point4& p2 ) { Point4 o1 = segment1.Origin(); Point4 o2 = segment2.Origin(); Vector4 d1 = segment1.Direction(); Vector4 d2 = segment2.Direction(); //compute intermediate parameters Vector4 w0 = o1 - o2; float a = Dot(d1, d1); float b = Dot(d1, d2); float c = Dot(d2, d2); float d = Dot(d1, w0); float e = Dot(d2, w0); float denom = a*c - b*b; // parameters to compute u1, u2 float u1, u2; float sn, sd, tn, td; // if denom is zero, try finding closest point on segment1 to origin0 if ( ::IsZero(denom) ) { // clamp u1 to 0 sd = td = c; sn = 0.0f; tn = e; } else { // clamp u1 within [0,1] sd = td = denom; sn = b*e - c*d; tn = a*e - b*d; // clamp u1 to 0 if (sn < 0.0f) { sn = 0.0f; tn = e; td = c; } // clamp u1 to 1 else if (sn > sd) { sn = sd; tn = e + b; td = c; } } // clamp u2 within [0,1] // clamp u2 to 0 if (tn < 0.0f) { u2 = 0.0f; // clamp u1 to 0 if ( -d < 0.0f ) { u1 = 0.0f; } // clamp u1 to 1 else if ( -d > a ) { u1 = 1.0f; } else { u1 = -d/a; } } // clamp u2 to 1 else if (tn > td) { u2 = 1.0f; // clamp u1 to 0 if ( (-d+b) < 0.0f ) { u1 = 0.0f; } // clamp u1 to 1 else if ( (-d+b) > a ) { u1 = 1.0f; } else { u1 = (-d+b)/a; } } else { u2 = tn/td; u1 = sn/sd; } // compute closest points p1 = o1 + u1*d1; p2 = o2 + u2*d2; return 1; } // End of ClosestPointsLineSegmentLineSegment() //-------------------------------------------------------------------------------- // @ ClosestPointsLineLineSegment() //-------------------------------------------------------------------------------- /* Summary: Finds the closest points between a linesegment and a line -------------------------------------- Post: returns 1. p1, p2 set. -------------------------------------- Param<segment>: input linesegment Param<line>: input line Param<p1>: point along segment closest to line Param<p2>: point along line closest to segment */ //-------------------------------------------------------------------------------- uint8 ClosestPointsLineLineSegment( const Line4& line, const LineSegment4& segment, Point4& p1, Point4& p2) { Point4 os = segment.Origin(); Point4 ol = line.Origin(); Vector4 ds = segment.Direction(); Vector4 dl = line.Direction(); //compute intermediate parameters Vector4 w0 = os - ol; float a = Dot(ds, dl); float b = Dot(ds, dl); float c = Dot(dl, dl); float d = Dot(ds, w0); float e = Dot(dl, w0); float denom = a*c - b*b; // if denom is zero, try finding closest point on line to segment origin if ( ::IsZero(denom) ) { // compute closest points p2 = os; p1 = ol + (e/c)*dl; return 1; } else { // parameters to compute u1, u2 float u1, u2; float sn; // clamp u1 within [0,1] sn = b*e - c*d; // clamp u1 to 0 if (sn < 0.0f) { u1 = 0.0f; u2 = e/c; } // clamp u1 to 1 else if (sn > denom) { u1 = 1.0f; u2 = (e+b)/c; } else { u1 = sn/denom; u2 = (a*e - b*d)/denom; } // compute closest points p1 = ol + u2*dl; p2 = os + u1*ds; return 1; } } // End of ClosestPointsLineLineSegment() //-------------------------------------------------------------------------------- // @ ClosestPointsLineSegmentRay() //-------------------------------------------------------------------------------- /* Summary: Finds the closest points between a linesegment and a ray -------------------------------------- Post: returns 1. p1, p2 set. -------------------------------------- Param<segment>: input linesegment Param<ray>: input ray Param<p1>: point along segment closest to ray Param<p2>: point along ray closest to segment */ //-------------------------------------------------------------------------------- uint8 ClosestPointsLineSegmentRay( const LineSegment4& segment, const Ray4& ray, Point4& p1, Point4& p2 ) { Point4 os = segment.Origin(); Point4 or = ray.Origin(); Vector4 ds = segment.Direction(); Vector4 dr = ray.Direction(); //compute intermediate parameters Vector4 w0 = os - or; float a = Dot(ds, ds); float b = Dot(ds, dr); float c = Dot(dr, dr); float d = Dot(ds, w0); float e = Dot(dr, w0); float denom = a*c - b*b; // parameters to compute u1, u2 float u1, u2; float sn, sd, tn, td; // if denom is zero, try finding closest point on segment1 to origin0 if ( ::IsZero(denom) ) { // clamp u1 to 0 sd = td = c; sn = 0.0f; tn = e; } else { // clamp u1 within [0,1] sd = td = denom; sn = b*e - c*d; tn = a*e - b*d; // clamp u1 to 0 if (sn < 0.0f) { sn = 0.0f; tn = e; td = c; } // clamp u1 to 1 else if (sn > sd) { sn = sd; tn = e + b; td = c; } } // clamp u2 within [0,+inf] // clamp u2 to 0 if (tn < 0.0f) { u2 = 0.0f; // clamp u1 to 0 if ( -d < 0.0f ) { u1 = 0.0f; } // clamp u1 to 1 else if ( -d > a ) { u1 = 1.0f; } else { u1 = -d/a; } } else { u2 = tn/td; u1 = sn/sd; } // compute closest points p1 = os + u1*ds; p2 = or + u2*dr; return 1; } // End of ClosestPointsLineSegmentRay()
[ "theguv81@hotmail.com" ]
theguv81@hotmail.com
160f0faaef35c3ea28a18999204d75cf285ce460
fb5b204943101746daf897f6ff6e0a12985543c3
/examples/cxx-api/query.cc
6d0606db6d7668aa7c68004551c9167758b6ef72
[ "LicenseRef-scancode-warranty-disclaimer", "CC0-1.0", "LicenseRef-scancode-public-domain" ]
permissive
baagaard-usgs/geomodelgrids
911a31ba23ca374be44873fdeb1e36a70ff25256
7d0db3c4ca1a83fea69ceb88f6ceec258928251a
refs/heads/main
2023-08-03T07:52:25.727039
2023-07-27T21:56:19
2023-07-27T21:56:19
97,262,677
5
3
NOASSERTION
2023-03-23T03:34:45
2017-07-14T18:34:38
C++
UTF-8
C++
false
false
7,166
cc
// Application illustrating how to use the C++ API to query models. #include "geomodelgrids/serial/Query.hh" #include "geomodelgrids/utils/ErrorHandler.hh" #include "geomodelgrids/utils/constants.hh" #include <stddef.h> #include <iostream> #include <cmath> #include <cassert> int main(int argc, char* argv[]) { // In this example, we hardwire the parameters for // convenience. See the C++ query application (bin/query.cc) for a // more sophisticated interface. // Models to query. static const std::vector<std::string>& filenames{ "../../tests/data/one-block-topo.h5", "../../tests/data/three-blocks-flat.h5", }; // Values and order to be returned in queries. static const std::vector<std::string>& valueNames{ "two", "one" }; static const size_t numValues = valueNames.size(); // Coordinate reference system of points passed to queries. // // The string can be in the form of EPSG:XXXX, WKT, or Proj // parameters. In this case, we will specify the coordinates in // latitude, longitude, elevation in the WGS84 horizontal // datum. The elevation is with respect to the WGS84 ellipsoid. static const char* const crs = "EPSG:4326"; static const size_t spaceDim = 3; // Create and initialize serial query object using the parameters // stored in local variables. geomodelgrids::serial::Query query; query.initialize(filenames, valueNames, crs); // Log warnings and errors to "error.log". geomodelgrids::utils::ErrorHandler& errorHandler = query.getErrorHandler(); errorHandler.setLogFilename("error.log"); // Coordinates of points for query (latitude, longitude, elevation). static const size_t numPoints = 16; static const double points[16*3] = { // Points in one-block-topo model 37.455, -121.941, 0.0, 37.479, -121.734, -5.0e+3, 37.381, -121.581, -3.0e+3, 37.283, -121.959, -1.5e+3, 37.262, -121.684, -4.0e+3, // Points in three-blocks-flat model 35.3, -118.2, 0.0, 35.5, -117.9, -45.0e+3, 35.0, -118.1, -3.0e+3, 35.1, -117.7, -15.0e+3, 34.7, -117.9, -25.0e+3, 34.7, -117.5, -8.4e+3, // Points not in either model domain 34.7, -117.8, 1.0e+4, 35.0, -117.6, -45.1e+3, 34.3, -117.8, -3.0e+3, 35.0, -113.0, -15.0e+3, 42.0, -117.8, -25.0e+3, }; // Expected return values and query values. static const int errE[16] = { // Points in one-block-topography model 0, 0, 0, 0, 0, // Points in three-blocks-flat model 0, 0, 0, 0, 0, 0, /* Points not in either model domain */ 1, 1, 1, 1, 1, }; static const double valuesE[16*2] = { // Points in one-block-topo model 4121.65, 7662.52, -19846.6, 14510.1, -9158.54, 29696.3, 45038.7, 26938.5, 26595.3, 39942.5, // Points in three-blocks-flat model -56937.1, 62087.1, -3564.86, 121682, -44676.9, 42041.4, 37087.2, 82235.8, -17131.2, 37823.2, 71156.9, 54662, // Points not in either model domain geomodelgrids::NODATA_VALUE, geomodelgrids::NODATA_VALUE, geomodelgrids::NODATA_VALUE, geomodelgrids::NODATA_VALUE, geomodelgrids::NODATA_VALUE, geomodelgrids::NODATA_VALUE, geomodelgrids::NODATA_VALUE, geomodelgrids::NODATA_VALUE, geomodelgrids::NODATA_VALUE, geomodelgrids::NODATA_VALUE, }; static const double surfaceElevE[16] = { // Elevations for one-block-topo points 150.046, 149.775, 150.023, 150.463614, 150.521716, // Elevations for three-blocks-flat model 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, // Elevations for points outside model domain 0.0, // latitude/longitude is in model domain 0.0, // latitude/longitude is in model domain geomodelgrids::NODATA_VALUE, geomodelgrids::NODATA_VALUE, geomodelgrids::NODATA_VALUE, }; // Query for values at points. We must preallocate the array holding the values. double values[numValues]; for (size_t iPt = 0; iPt < numPoints; ++iPt) { const double latitude = points[iPt*spaceDim+0]; const double longitude = points[iPt*spaceDim+1]; const double elevation = points[iPt*spaceDim+2]; const int err = query.query(values, latitude, longitude, elevation); // Query for elevation of top surface. const double surfaceElev = query.queryTopElevation(latitude, longitude); // Use the values returned in the query. In this case we check the values against the expected ones. // // We first check the return value and then the query values. if (errE[iPt] != err) { printf("Expected a return value of %d for point (%g, %g, %g) but got a value of %d.\n", errE[iPt], latitude, longitude, elevation, err); } // if for (size_t iValue = 0; iValue < numValues; ++iValue) { const double tolerance = 1.0e-4; const double relativeDiff = (values[iValue] - valuesE[iPt*numValues+iValue]) / valuesE[iPt*numValues+iValue]; if (fabs(relativeDiff) > tolerance) { std::cout << "Expected value of " << valuesE[iPt*numValues+iValue] << " for '" << valueNames[iValue] << "' at point (" << latitude << ", " << longitude << ", " << elevation << ") but got a value of " << values[iValue] << "." << std::endl; } else { if (values[iValue] != geomodelgrids::NODATA_VALUE) { std::cout << "Point (" << latitude << ", " << longitude << ", " << elevation << "), value '" << valueNames[iValue] << "': " << values[iValue] << "." << std::endl; } else { std::cout << "No data for point (" << latitude << ", " << longitude << ", " << elevation << ")." << std::endl; } // if/else } // if/else } // for // Check ground surface elevation values. const double tolerance = 1.0e-06 * fabs(surfaceElevE[iPt]); if (fabs(surfaceElev-surfaceElevE[iPt]) > tolerance) { std::cout << "Expected ground surface elevation of " << surfaceElevE[iPt] << " at point (" << latitude << ", " << longitude << ") but got a value of " << surfaceElev << "." << std::endl; } else { if (surfaceElev != geomodelgrids::NODATA_VALUE) { std::cout << "Point (" << latitude << ", " << longitude << "), ground surface elevation: " << surfaceElev << "." << std::endl; } else { std::cout << "No ground surface elevation for point (" << latitude << ", " << longitude << ")." << std::endl; } // if/else } // if/else } // for return 0; } // main // End of file
[ "baagaard@usgs.gov" ]
baagaard@usgs.gov
0ad782f5bedc9e0e9f9c8f6d760eed618ea3e3ad
37421acb6ab434bf46afc30fe20397892b55fd93
/code/l3lib/include/cryptopp562/socketft.h
180266e9d9ea7ced44307392177dc373fff360e6
[]
no_license
achishex/thunder
cd7f78b23eaf87a83b258eb2c930d97eccbe7e81
e07135f6c496f268c8b0b043148b9a30bcc60a64
refs/heads/master
2021-05-06T10:27:23.416594
2017-09-01T16:35:36
2017-09-01T16:35:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,187
h
#ifndef CRYPTOPP_SOCKETFT_H #define CRYPTOPP_SOCKETFT_H #include "../../../l3lib/include/cryptopp562/config.h" #ifdef SOCKETS_AVAILABLE #include "../../../l3lib/include/cryptopp562/network.h" #include "../../../l3lib/include/cryptopp562/queue.h" #ifdef USE_WINDOWS_STYLE_SOCKETS # if defined(_WINSOCKAPI_) && !defined(_WINSOCK2API_) # error Winsock 1 is not supported by this library. Please include this file or winsock2.h before windows.h. # endif #include <winsock2.h> #include "../../../l3lib/include/cryptopp562/winpipes.h" #else #include <sys/time.h> #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #endif NAMESPACE_BEGIN(CryptoPP) #ifdef USE_WINDOWS_STYLE_SOCKETS typedef ::SOCKET socket_t; #else typedef int socket_t; const socket_t INVALID_SOCKET = -1; // cygwin 1.1.4 doesn't have SHUT_RD const int SD_RECEIVE = 0; const int SD_SEND = 1; const int SD_BOTH = 2; const int SOCKET_ERROR = -1; #endif #ifndef socklen_t typedef TYPE_OF_SOCKLEN_T socklen_t; // see config.h #endif //! wrapper for Windows or Berkeley Sockets class Socket { public: //! exception thrown by Socket class class Err : public OS_Error { public: Err(socket_t s, const std::string& operation, int error); socket_t GetSocket() const {return m_s;} private: socket_t m_s; }; Socket(socket_t s = INVALID_SOCKET, bool own=false) : m_s(s), m_own(own) {} Socket(const Socket &s) : m_s(s.m_s), m_own(false) {} virtual ~Socket(); bool GetOwnership() const {return m_own;} void SetOwnership(bool own) {m_own = own;} operator socket_t() {return m_s;} socket_t GetSocket() const {return m_s;} void AttachSocket(socket_t s, bool own=false); socket_t DetachSocket(); void CloseSocket(); void Create(int nType = SOCK_STREAM); void Bind(unsigned int port, const char *addr=NULL); void Bind(const sockaddr* psa, socklen_t saLen); void Listen(int backlog=5); // the next three functions return false if the socket is in nonblocking mode // and the operation cannot be completed immediately bool Connect(const char *addr, unsigned int port); bool Connect(const sockaddr* psa, socklen_t saLen); bool Accept(Socket& s, sockaddr *psa=NULL, socklen_t *psaLen=NULL); void GetSockName(sockaddr *psa, socklen_t *psaLen); void GetPeerName(sockaddr *psa, socklen_t *psaLen); unsigned int Send(const byte* buf, size_t bufLen, int flags=0); unsigned int Receive(byte* buf, size_t bufLen, int flags=0); void ShutDown(int how = SD_SEND); void IOCtl(long cmd, unsigned long *argp); bool SendReady(const timeval *timeout); bool ReceiveReady(const timeval *timeout); virtual void HandleError(const char *operation) const; void CheckAndHandleError_int(const char *operation, int result) const {if (result == SOCKET_ERROR) HandleError(operation);} void CheckAndHandleError(const char *operation, socket_t result) const {if (result == SOCKET_ERROR) HandleError(operation);} #ifdef USE_WINDOWS_STYLE_SOCKETS void CheckAndHandleError(const char *operation, BOOL result) const {assert(result==TRUE || result==FALSE); if (!result) HandleError(operation);} void CheckAndHandleError(const char *operation, bool result) const {if (!result) HandleError(operation);} #endif //! look up the port number given its name, returns 0 if not found static unsigned int PortNameToNumber(const char *name, const char *protocol="tcp"); //! start Windows Sockets 2 static void StartSockets(); //! calls WSACleanup for Windows Sockets static void ShutdownSockets(); //! returns errno or WSAGetLastError static int GetLastError(); //! sets errno or calls WSASetLastError static void SetLastError(int errorCode); protected: virtual void SocketChanged() {} socket_t m_s; bool m_own; }; class SocketsInitializer { public: SocketsInitializer() {Socket::StartSockets();} ~SocketsInitializer() {try {Socket::ShutdownSockets();} catch (...) {}} }; class SocketReceiver : public NetworkReceiver { public: SocketReceiver(Socket &s); #ifdef USE_BERKELEY_STYLE_SOCKETS bool MustWaitToReceive() {return true;} #else ~SocketReceiver(); bool MustWaitForResult() {return true;} #endif bool Receive(byte* buf, size_t bufLen); unsigned int GetReceiveResult(); bool EofReceived() const {return m_eofReceived;} unsigned int GetMaxWaitObjectCount() const {return 1;} void GetWaitObjects(WaitObjectContainer &container, CallStack const& callStack); private: Socket &m_s; bool m_eofReceived; #ifdef USE_WINDOWS_STYLE_SOCKETS WindowsHandle m_event; OVERLAPPED m_overlapped; bool m_resultPending; DWORD m_lastResult; #else unsigned int m_lastResult; #endif }; class SocketSender : public NetworkSender { public: SocketSender(Socket &s); #ifdef USE_BERKELEY_STYLE_SOCKETS bool MustWaitToSend() {return true;} #else ~SocketSender(); bool MustWaitForResult() {return true;} bool MustWaitForEof() { return true; } bool EofSent(); #endif void Send(const byte* buf, size_t bufLen); unsigned int GetSendResult(); void SendEof(); unsigned int GetMaxWaitObjectCount() const {return 1;} void GetWaitObjects(WaitObjectContainer &container, CallStack const& callStack); private: Socket &m_s; #ifdef USE_WINDOWS_STYLE_SOCKETS WindowsHandle m_event; OVERLAPPED m_overlapped; bool m_resultPending; DWORD m_lastResult; #else unsigned int m_lastResult; #endif }; //! socket-based implementation of NetworkSource class SocketSource : public NetworkSource, public Socket { public: SocketSource(socket_t s = INVALID_SOCKET, bool pumpAll = false, BufferedTransformation *attachment = NULL) : NetworkSource(attachment), Socket(s), m_receiver(*this) { if (pumpAll) PumpAll(); } private: NetworkReceiver & AccessReceiver() {return m_receiver;} SocketReceiver m_receiver; }; //! socket-based implementation of NetworkSink class SocketSink : public NetworkSink, public Socket { public: SocketSink(socket_t s=INVALID_SOCKET, unsigned int maxBufferSize=0, unsigned int autoFlushBound=16*1024) : NetworkSink(maxBufferSize, autoFlushBound), Socket(s), m_sender(*this) {} void SendEof() {ShutDown(SD_SEND);} private: NetworkSender & AccessSender() {return m_sender;} SocketSender m_sender; }; NAMESPACE_END #endif // #ifdef SOCKETS_AVAILABLE #endif
[ "“chenjiayi@tuandai.com”" ]
“chenjiayi@tuandai.com”
b11292a1c6a4fae76c428d537531a5df9aa24346
2b2da3c294d188fa7c2795364ab26859e29ffb87
/OFSample-Windows/depends/dwinternal/framework2015/dwbase/datacenter/FieldBlob.h
be1e3d49b3d2cd5dcca2cc5dc1aa496b34aa3fcc
[]
no_license
JocloudSDK/OFSample
1de97d416402b91276f9992197bc0c64961fb9bd
fa678d674b3886fa8e6a1c4a0ba6b712124e671a
refs/heads/master
2022-12-28T05:03:05.563734
2020-10-19T07:11:55
2020-10-19T07:11:55
294,078,053
4
2
null
null
null
null
GB18030
C++
false
false
1,071
h
#pragma once #include "../mempool/MemPool.h" namespace Data { class CFieldBlob { public: inline static CFieldBlob * createInstance(const BYTE * pbData, DWORD cbSize) { CFieldBlob *p = (CFieldBlob *)mp_alloc(sizeof(CFieldBlob) + cbSize); p->m_dwRef = 1; p->m_cbSize = cbSize; memcpy(p + 1, pbData, cbSize); return p; } inline const BYTE * getPtr() const { return (const BYTE *)(this + 1); } inline DWORD getSize() const { return m_cbSize; } inline BOOL isEqual(const BYTE * pbData, DWORD cbSize) const { return cbSize == m_cbSize && memcmp(getPtr(), pbData, cbSize) == 0; } inline void addRef() { assert(m_dwRef > 0 && m_dwRef < 0x7fffffff); ::InterlockedIncrement((LONG *)&m_dwRef); } inline void release() { assert(m_dwRef > 0 && m_dwRef < 0x7fffffff); if (::InterlockedDecrement((LONG *)&m_dwRef) == 0) { m_cbSize = 0; mp_free(this); } } private: CFieldBlob(void); //不用实现,调不着 ~CFieldBlob(void);//不用实现,调不着 DWORD m_dwRef; DWORD m_cbSize; }; };
[ "chenshibiao@yy.com" ]
chenshibiao@yy.com
55b81c02542b83a3ec6307728a6a2ebe51ba90fb
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/squid/new_hunk_5399.cpp
af38759c5746c22677dc1770f034fdfbcddd49f3
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
324
cpp
storeAppendPrintf(sentry, "There are no neighbors installed.\n"); for (e = peers; e; e = e->next) { assert(e->host != NULL); storeAppendPrintf(sentry, "\n%-11.11s: %s\n", neighborTypeStr(e), e->name); storeAppendPrintf(sentry, "Host : %s/%d/%d\n", e->host, e->http_port, e->icp.port);
[ "993273596@qq.com" ]
993273596@qq.com
983778877628a9642597a2af2c6027d7e09e7db2
fd0085bc4f9f21cda6c4223f7323e37f3bfc79aa
/psyche/psycheSystematics/v3r28/src/OOFVSystematics.cxx
cbff8570c58c9b57088abe5d82740bbf9bba0dcb
[]
no_license
hoganman/p0d-banff
a9341b3657233b85de63406eb96a4176603fdcdd
386692fa7480f347c022de5fb2dd1278eaacc013
refs/heads/master
2021-03-19T15:11:29.796754
2019-04-25T17:36:58
2019-04-25T17:36:58
106,490,553
0
0
null
null
null
null
UTF-8
C++
false
false
11,824
cxx
#include "OOFVSystematics.hxx" #include "ND280AnalysisUtils.hxx" #include "ToyBoxTracker.hxx" #include "BasicUtils.hxx" #include "SubDetId.hxx" #include "FiducialVolumeDefinition.hxx" #include "VersioningUtils.hxx" #include "SystId.hxx" #include "SystematicUtils.hxx" //******************************************************************** OOFVSystematics::OOFVSystematics():EventWeightBase(1){ //******************************************************************** int npars=0; if (!versionUtils::prod6_systematics) { _fgd1 = new BinnedParams("OOFVFGD1",BinnedParams::k2D_SYMMETRIC,versionUtils::Extension()); npars=_fgd1->GetNBins(); _fgd2 = new BinnedParams("OOFVFGD2",BinnedParams::k2D_SYMMETRIC,versionUtils::Extension()); npars+=_fgd2->GetNBins(); SetNParameters(npars); } else { _fgd1 = new BinnedParams("OOFV_reco_fgd1",BinnedParams::k1D_SYMMETRIC,versionUtils::Extension()); npars=_fgd1->GetNBins(); _fgd2 = new BinnedParams("OOFV_reco_fgd2",BinnedParams::k1D_SYMMETRIC,versionUtils::Extension()); npars+=_fgd2->GetNBins(); _rate = new BinnedParams("OOFV_rate",BinnedParams::k2D_SYMMETRIC,versionUtils::Extension()); npars+=_rate->GetNBins(); SetNParameters(npars); } if (!versionUtils::prod6_systematics) { for (int i=0;i<9;i++){ if (!_fgd1->GetBinValues(i, 0, _rate_corr[0][i], _rate_error[0][i],_rate_index[0][i])) _reco_index[0][i]=-1; if (!_fgd1->GetBinValues(i, 1, _reco_corr[0][i], _reco_error[0][i],_reco_index[0][i])) _rate_index[0][i]=-1; if (!_fgd2->GetBinValues(i, 0, _rate_corr[1][i], _rate_error[1][i],_rate_index[1][i])) _reco_index[1][i]=-1; if (!_fgd2->GetBinValues(i, 1, _reco_corr[1][i], _reco_error[1][i],_reco_index[1][i])) _rate_index[1][i]=-1; } } else{ for (int i=0;i<9;i++){ if (!_fgd1->GetBinValues(i, _reco_corr[0][i], _reco_error[0][i],_reco_index[0][i])) _reco_index[0][i]=-1; if (!_fgd2->GetBinValues(i, _reco_corr[1][i], _reco_error[1][i],_reco_index[1][i])) _reco_index[1][i]=-1; // if (_reco_index[0][i]>=0) _reco_index[0][i] += _rate->GetNBins(); // if (_reco_index[1][i]>=0) _reco_index[1][i] += _rate->GetNBins(); } } } //******************************************************************** void OOFVSystematics::Initialize(){ //******************************************************************** if (!versionUtils::prod6_systematics) { systUtils::AddBinnedParamsOffsetToSystematic(*this, *_fgd1, _fgd1->GetNBins()); systUtils::AddBinnedParamsOffsetToSystematic(*this, *_fgd2, _fgd2->GetNBins()); } else { systUtils::AddBinnedParamsOffsetToSystematic(*this, *_rate, _rate->GetNBins()); systUtils::AddBinnedParamsOffsetToSystematic(*this, *_fgd1, _fgd1->GetNBins()); systUtils::AddBinnedParamsOffsetToSystematic(*this, *_fgd2, _fgd2->GetNBins()); } } //******************************************************************** Int_t OOFVSystematics::GetBeamNumber(Int_t runperiod,AnaTrackB *maintrack){ //******************************************************************** //run 5 RHC if(runperiod==8) { //mu-minus if(maintrack->Charge<0) return 1; //mu-plus else return 2; } else return 0; } //******************************************************************** Int_t OOFVSystematics::GetDetNumber(SubDetId::SubDetEnum det){ //******************************************************************** if(SubDetId::IsP0DDetector(det)) return 0; else if(SubDetId::IsECALDetector(det)) return 1; else if(SubDetId::IsTECALDetector(det)) return 1; else if(SubDetId::IsPECALDetector(det)) return 1; else if(SubDetId::IsSMRDDetector(det)) return 2; else if(SubDetId::IsTPCDetector(det)) return -1; else if(SubDetId::IsFGDDetector(det)) return -1; else return 3; } //******************************************************************** Weight_h OOFVSystematics::ComputeWeight(const ToyExperiment& toy, const AnaEventC& eventBB, const ToyBoxB& boxB, const SelectionBase& sel){ //******************************************************************** const AnaEventB& event = *static_cast<const AnaEventB*>(&eventBB); // Cast the ToyBox to the appropriate type const ToyBoxTracker& box = *static_cast<const ToyBoxTracker*>(&boxB); (void)event; Weight_h eventWeight=1; if (!box.MainTrack) return eventWeight; // HMN track should exist if (!box.MainTrack->TrueObject) return eventWeight; // True track associated to HMN track should exist if (!box.MainTrack->GetTrueParticle()->TrueVertex) return eventWeight; // True vertex associated to HMN track should exist // Get the true vertex position Float_t* tvertex = box.MainTrack->GetTrueParticle()->TrueVertex->Position; // if the true vertex is inside the FGD FV this is not OOFV (RETURN EVENTWEIGHT=1) if(anaUtils::InFiducialVolume(static_cast<SubDetId::SubDetEnum>(box.DetectorFV), tvertex)) return eventWeight; // Get the true track direction and position Float_t* tdir = box.MainTrack->GetTrueParticle()->Direction; Float_t* pos = box.MainTrack->GetTrueParticle()->Position; Float_t* fgd_det_min; Float_t* fgd_det_max; double Zmin_lastmodule,zup,zdown; bool lastmodule; Int_t fgd; if(box.DetectorFV == SubDetId::kFGD1){ fgd=0; fgd_det_min = DetDef::fgd1min; fgd_det_max = DetDef::fgd1max; Zmin_lastmodule = fgd_det_max[2]-DetDef::fgdXYModuleWidth; zup =-60; zdown = 623; } else if(box.DetectorFV == SubDetId::kFGD2){ fgd=1; fgd_det_min = DetDef::fgd2min; fgd_det_max = DetDef::fgd2max; Zmin_lastmodule = 1780; zup = 1298; zdown = 1983.095; } else return eventWeight; lastmodule = ( pos[2] >Zmin_lastmodule && pos[2] < fgd_det_max[2] ); //sense of the track defined by the selection (true=FWD/HAFWD or false=BWD/HABWD). bool fwdsense = sel.IsRelevantRecObjectForSystematicInToy(eventBB, boxB, box.MainTrack, SystId::kOOFV, boxB.SuccessfulBranch); Int_t categ =-1; if (fwdsense) { //inFGD1scint. Put z condition first to be faster if ((tvertex[2] > fgd_det_min[2] && tvertex[2] < fgd_det_max[2]) && (tvertex[0] > fgd_det_min[0] && tvertex[0] < fgd_det_max[0]) && (tvertex[1] > fgd_det_min[1] && tvertex[1] < fgd_det_max[1])) categ=0; //upstreamFGD1scint else if ((tvertex[2] > zup && tvertex[2] < fgd_det_min[2]) && (tvertex[0] > -1335 && tvertex[0] < 1335) && (tvertex[1] > -1280.5 && tvertex[1] < 1280.5)) categ=1; //downstreamFGD1scint else if((tvertex[2] > fgd_det_max[2] && tvertex[2] < zdown) && (tvertex[0] > -1335 && tvertex[0] < 1335) && (tvertex[1] > -1280.5 && tvertex[1] < 1280.5)) categ=2; //neutralparent else if( box.MainTrack->GetTrueParticle()->ParentPDG == 2112 || box.MainTrack->GetTrueParticle()->ParentPDG == 22 || box.MainTrack->GetTrueParticle()->GParentPDG == 2112 || box.MainTrack->GetTrueParticle()->GParentPDG == 22) categ=3; //backwards else if(tdir[2]<=-0.5) categ=4; //highangle else if(tdir[2]>-0.5 && tdir[2]<0.5) categ=5; //verylowangle else if(fabs(tdir[0]/tdir[2])<0.07 || fabs(tdir[1]/tdir[2])<0.07) categ=6; //lastmodule else if ( lastmodule && anaUtils::InDetVolume(static_cast<SubDetId::SubDetEnum>(box.DetectorFV), box.MainTrack->PositionStart)) categ=7; else categ=8; } else { //inFGD1scint. Put z condition first to be faster if ((tvertex[2] > fgd_det_min[2] && tvertex[2] < fgd_det_max[2]) && (tvertex[0] > fgd_det_min[0] && tvertex[0] < fgd_det_max[0]) && (tvertex[1] > fgd_det_min[1] && tvertex[1] < fgd_det_max[1])) categ=0; //downstreamFGD1scint else if((tvertex[2] > fgd_det_max[2] && tvertex[2] < zdown) && (tvertex[0] > -1335 && tvertex[0] < 1335) && (tvertex[1] > -1280.5 && tvertex[1] < 1280.5)) categ=1; //upstreamFGD1scint else if ((tvertex[2] > zup && tvertex[2] < fgd_det_min[2]) && (tvertex[0] > -1335 && tvertex[0] < 1335) && (tvertex[1] > -1280.5 && tvertex[1] < 1280.5)) categ=2; //neutralparent else if( box.MainTrack->GetTrueParticle()->ParentPDG == 2112 || box.MainTrack->GetTrueParticle()->ParentPDG == 22 || box.MainTrack->GetTrueParticle()->GParentPDG == 2112 || box.MainTrack->GetTrueParticle()->GParentPDG == 22) categ=3; //forwards else if(tdir[2]>=0.5) categ=4; //highangle else if(tdir[2]>-0.5 && tdir[2]<0.5) categ=5; //verylowangle else if(fabs(tdir[0]/tdir[2])<0.07 || fabs(tdir[1]/tdir[2])<0.07) categ=6; //lastmodule else if ( lastmodule && anaUtils::InDetVolume(static_cast<SubDetId::SubDetEnum>(box.DetectorFV), box.MainTrack->PositionStart)) categ=7; else categ=8; } // Note that this is wrong for layer28-29, veryhighangle and veryforward, // for those one matching reco should be rerun to understand how reco is changed, by now it is applied as a rate uncertainty... but.... if(categ>=0 ){ if (!versionUtils::prod6_systematics){ Int_t reco_index = _reco_index[fgd][categ]; reco_index += (fgd == 0) ? systUtils::GetBinnedParamsOffsetForSystematic(*this, *_fgd1) : systUtils::GetBinnedParamsOffsetForSystematic(*this, *_fgd2); Int_t rate_index = _rate_index[fgd][categ]; rate_index += (fgd == 0) ? systUtils::GetBinnedParamsOffsetForSystematic(*this, *_fgd1) : systUtils::GetBinnedParamsOffsetForSystematic(*this, *_fgd2); eventWeight.Systematic *= (1+ _reco_corr[fgd][categ] + _reco_error[fgd][categ]*toy.GetToyVariations(_index)->Variations[reco_index]); eventWeight.Systematic *= (1+ _rate_corr[fgd][categ] + _rate_error[fgd][categ]*toy.GetToyVariations(_index)->Variations[rate_index]); eventWeight.Correction *= (1+ _reco_corr[fgd][categ]); eventWeight.Correction *= (1+ _rate_corr[fgd][categ]); } else{ SubDetId::SubDetEnum detector=anaUtils::GetDetector(tvertex); Int_t runPeriod = anaUtils::GetRunPeriod(event.EventInfo.Run); if (!_rate->GetBinValues(GetBeamNumber(runPeriod,box.MainTrack), GetDetNumber(detector), _rate_corr[0][0], _rate_error[0][0],_rate_index[0][0])) _rate_index[0][0]=-1; if (_reco_index[fgd][categ]>=0){ Int_t reco_index = _reco_index[fgd][categ]; reco_index += (fgd == 0) ? systUtils::GetBinnedParamsOffsetForSystematic(*this, *_fgd1) : systUtils::GetBinnedParamsOffsetForSystematic(*this, *_fgd2); eventWeight.Systematic *= (1+ _reco_corr[fgd][categ] + _reco_error[fgd][categ]*toy.GetToyVariations(_index)->Variations[reco_index]); eventWeight.Correction *= (1+ _reco_corr[fgd][categ]); } if (_rate_index[0][0]>=0){ Int_t rate_index = _rate_index[0][0]; rate_index += systUtils::GetBinnedParamsOffsetForSystematic(*this, *_rate); eventWeight.Systematic *= (1+ _rate_corr[0][0] + _rate_error[0][0] * toy.GetToyVariations(_index)->Variations[rate_index]); eventWeight.Correction *= (1+ _rate_corr[0][0]); } } } if (eventWeight.Systematic < 0) eventWeight.Systematic = 0; return eventWeight; }
[ "hoganman@rams.colostate.edu" ]
hoganman@rams.colostate.edu
13e600dffd1242230e009d3f0c694bd3bf47316a
4ea7ad6e3c5c1ba5839edae3a08db0ca371520ca
/UVAOJ/10653.cpp
273c2366ac524e894434c60f18e878d64b10cf80
[]
no_license
nawZeroX239/competitive-programming
144eac050fafffc51267c67afb96e60316ae2294
f52472db0e1e6fe724e9a7456deac19683fa4813
refs/heads/master
2021-03-10T12:30:42.533862
2020-12-24T00:32:01
2020-12-24T00:32:01
246,452,848
0
1
null
2020-10-02T18:22:05
2020-03-11T02:10:17
C++
UTF-8
C++
false
false
2,307
cpp
#include <algorithm> #include <array> #include <bitset> #include <climits> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <deque> #include <forward_list> #include <iomanip> #include <iostream> #include <iterator> #include <list> #include <map> #include <queue> #include <set> #include <sstream> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> #define INF 999999999 #define EPS 1e-9 using namespace std; typedef tuple<int, int, int> iii; typedef vector<int> vi; // translation int x[] = { 0, 0, 1, -1 }; int y[] = { -1, 1, 0, 0 }; template <class T> T gcd(T a, T b) { if (b == 0) { return a; } return gcd(b, a % b); } int toInt(string& s) { stringstream ss(s); int x; ss >> x; return x; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); vector<vector<int>> adj; int n, m, r, c, k, f, dist[1000][1000]; pair<int, int> u, v, s, d; bool g[1000][1000]; while (cin >> n >> m) { if (n == 0 && m == 0) break; for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) { g[i][j] = 1; dist[i][j] = INF; } cin >> k; for (int i = 0; i < k; ++i) { cin >> r >> f; for (int j = 0; j < f; ++j) { cin >> c; g[r][c] = 0; } } //for (int i = 0; i < n; ++i) { // for (int j = 0; j < m; ++j) { // if (i + 1 < n && !g[i + 1][j]) { // u = n * i + j, v = n * (i + 1) + j; // adj[u].push_back(v); // adj[v].push_back(u); // } // if (j + 1 < m && !g[i][j + 1]) { // u = n * i + j, v = n * i + j + 1; // adj[u].push_back(v); // adj[v].push_back(u); // } // dist[n * i + j] = INF; // } //} cin >> s.first >> s.second >> d.first >> d.second; queue<pair<int, int>> q; q.push(s); dist[s.first][s.second] = 0; while (q.size()) { u = q.front(); q.pop(); for (int i = 0; i < 4; ++i) { v.first = x[i] + u.first; v.second = y[i] + u.second; if (v.first >= 0 && v.first < n && v.second >= 0 && v.second <= m && g[v.first][v.second] && dist[v.first][v.second] == INF) { dist[v.first][v.second] = dist[u.first][u.second] + 1; q.push(v); if (v == s) break; } } } cout << dist[d.first][d.second] << '\n'; } }
[ "naw122333444455555@gmail.com" ]
naw122333444455555@gmail.com
640bbf8cacf37e2e4de9fdb6f57b76e0d31d53c0
fb5a7667fa36a16f312c7828837558c69fdf27e8
/SimpleExample2019.2.21/iOS-Export/SimpleExample/Classes/Native/Il2CppCodeRegistration.cpp
b873cf6432f0b668b2ad9881e0047a9948a67d3a
[]
no_license
skillz/integration-examples
048cce107e1b0f67408736c4cd0d07f3f73daf2c
f283c0624d757131d48d7af135550281709877ba
refs/heads/master
2021-12-15T06:02:38.174945
2021-12-13T22:25:38
2021-12-13T22:25:38
250,074,665
9
28
null
2021-12-13T22:25:38
2020-03-25T19:40:33
C
UTF-8
C++
false
false
129
cpp
version https://git-lfs.github.com/spec/v1 oid sha256:0abeb5bbbe3bc9eea76b4b2dd3285e00e555ebb90a473aee58a9690fa81998c7 size 4823
[ "jlin@skillz.com" ]
jlin@skillz.com
4e2d9310dbabb3668268b9bcbabe4ab387336ff6
82c37420eb3cad10df484f4555c391ec044e650c
/api/initializer.hpp
bb4964af8b847778af2b097bcab78f1a9ed5857c
[]
no_license
Maxteke/zia
14032ac6cf3d193b239869a8545d1e3ec1933fab
420172b4c33f7e3aa4b7bb83957f4a3eccaf2b9d
refs/heads/master
2023-03-14T16:32:57.810705
2021-04-01T14:34:25
2021-04-01T14:34:25
353,724,713
0
0
null
null
null
null
UTF-8
C++
false
false
465
hpp
#ifndef ZIA_INITIALIZER_API_H_ #define ZIA_INITIALIZER_API_H_ #include "event.hpp" namespace zia::api { class IZiaInitializer { public: virtual ~IZiaInitializer(){}; virtual void registerConsumer(const EventDescriptor &event, EventConsumer consumer) = 0; virtual void registerListener(const EventDescriptor &event, EventListener listener) = 0; }; } // namespace zia::api #endif
[ "maxence.pellerin@epitech.eu" ]
maxence.pellerin@epitech.eu
16206d622b431e8ec4ad4e2b4d050320ee1e9d4c
b33cd5cc98cd79b890849b82e4c5ac303a70d0cd
/OrbitService/ProcessMemoryService.h
a2a87563960104b9583a63ffab6104256a1d1efa
[ "LicenseRef-scancode-free-unknown", "BSD-2-Clause" ]
permissive
Mdlglobal-atlassian-net/orbit
4b70f4b8390ef51e5255d67a7d1153d96eae303a
e054374f69c7609b94d47c77d2f31b77dafdbf5d
refs/heads/master
2022-08-19T04:48:10.568686
2020-05-19T18:51:15
2020-05-19T18:51:15
265,451,708
0
1
BSD-2-Clause
2020-05-20T04:31:51
2020-05-20T04:31:50
null
UTF-8
C++
false
false
907
h
// Copyright (c) 2020 The Orbit Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ORBIT_CORE_PROCESS_MEMORY_SERVICE_H_ #define ORBIT_CORE_PROCESS_MEMORY_SERVICE_H_ #include <cstdint> #include "ProcessMemoryRequest.h" #include "TransactionService.h" class ProcessMemoryService { public: explicit ProcessMemoryService(TransactionService* transaction_service); ProcessMemoryService() = delete; ProcessMemoryService(const ProcessMemoryService&) = delete; ProcessMemoryService& operator=(const ProcessMemoryService&) = delete; ProcessMemoryService(ProcessMemoryService&&) = delete; ProcessMemoryService& operator=(ProcessMemoryService&&) = delete; private: void HandleRequest(const Message& message); TransactionService* transaction_service_; }; #endif // ORBIT_CORE_PROCESS_MEMORY_SERVICE_H_
[ "58685940+dpallotti@users.noreply.github.com" ]
58685940+dpallotti@users.noreply.github.com
14ac098b12ddd048e115f53e270ebe154cfe66c3
0de2ffef890b22fda1cc8867d92e56abca9168af
/Compound_types/Structs/main.cpp
d5b6ee677857dbe196b643c94fa0c58803027b59
[]
no_license
gonzrubio/learncpp
3092f7e45e5e1a0c362df7a5b5e0e20411d4fcb6
10fa984b765f3ede8deeac3606f8fd7a991c5a02
refs/heads/master
2023-04-20T04:49:32.478498
2021-04-24T20:48:29
2021-04-24T20:48:29
274,507,400
0
0
null
null
null
null
UTF-8
C++
false
false
3,967
cpp
#include <iostream> using namespace std; struct Advertising { int shown ; // Number of ads shown to readers. double perc ; // Percentage of ads clicked on by users. double aveEarn ;// How much was earned on average for each ad that was clicked. } ; struct Person { // This is a structure variable of type Person. string name ; int age ; string gender ; }; void dayProfit(Advertising website) { cout << "There were " << website.shown << " number of ads shown." << endl ; cout << website.perc << " percent of the ads were clicked on by users." << endl ; cout << "$" <<website.aveEarn << " were earned on average for each ad that was clicked." << endl ; double temp = website.perc/100 ; double profit = website.shown * temp * website.aveEarn ; cout << "The website made $" << profit << " that day." << endl ; } Advertising getInfo() { Advertising temp ; cout << "Number of ads shown: " ; cin >> temp.shown ; cout << "Percentage of ads clicked on by users: " ; cin >> temp.perc ; cout << "How much was earned on average for each ad that was clicked: " ; cin >> temp.aveEarn ; return temp ; } // Declare a struct and its identifier. struct Fraction { // Define the fields and member of the structure. int numerator ; int denominator ; }; // Note: the return type of getFraction() is 'Fraction', which in turn is of struct type. Fraction getFraction() { // No variable is neither passed-by-value nor passed-by-reference. // Need to create a struct variable to hold the user inputs. // This variable exist inside the scope of this function and the user input // is returned in pass-by-value. Fraction userInput ; cout << "Enter an integer for the numerator: " ; cin >> userInput.numerator ; cout << "Enter an integer for the denominator: " ; cin >> userInput.denominator ; cout << endl ; return userInput ; } // Note: the type of the inputs are Fractions (struct). void multiply(Fraction a,Fraction b) { //double top{a.numerator * b.numerator} ; //double bottom{a.denominator * b.denominator} ; cout << "Their product is: " << static_cast<double> (a.numerator * b.numerator)/(a.denominator * b.denominator) << endl << endl ; // cout << "Their product is: " << top << "/" << bottom << "."endl ; //cout << "Their product is: " << product << "." << endl ; } void printPersonInfo(const Person &p) { // We pass the variable by reference to avoid expensive copy. // It is a constant refernce since we want read only. cout << "The name of the person is: " << p.name << endl ; cout << "The age of the person is: " << p.age << endl ; cout << "The gender of the person is: " << p.gender << endl << endl ; } int main() { /* 2 ) Pass the advertising struct to a function that prints each of the values, and then calculates how much you made for that day (multiply all 3 fields together). */ // Advertising website = getInfo() ; // dayProfit(website) ; /* Create a struct to hold a fraction. The struct should have an integer numerator and an integer denominator member. Declare 2 fraction variables and read them in from the user. Write a function 'multiply' that takes both fractions, multiplies them together, & prints the result out as a decimal. */ // Declare two fraction variables of type struct. The fields are inputs from the user. // The function return-type of getFraction() is Fraction, which itself is a struct. Fraction fraction1 = getFraction() ; Fraction fraction2 = getFraction() ; multiply(fraction1,fraction2) ; Person Gonzalo{"Gonzalo",25,"Male"} ; Person Emma{"Emma",29,"Female"} ; printPersonInfo(Gonzalo) ; // Create a an array that holds variables of type Person and print the second person info. Person people[]{Gonzalo,Emma} ; printPersonInfo(people[1]) ; return 0; }
[ "gonzrubio95@gmail.com" ]
gonzrubio95@gmail.com
b9e1b58e082c5bf9aed0ba1c47a028e01b616c3e
710ac923ad7aaaf3c59882a057a2ebbe159ef135
/Ogre-1.9a/RenderSystems/GLES/include/OgreGLESTextureManager.h
b0a05ce987b196841b0a2499fa4f48f97bdc22bf
[]
no_license
lennonchan/OgreKit
3e8ec4b0f21653cb668d5cd7d58acc8d45de6a96
ac5ca9b9731ce5f8eb145e7a8414e781f34057ab
refs/heads/master
2021-01-01T06:04:40.107584
2013-04-19T05:02:42
2013-04-19T05:02:42
9,538,177
1
3
null
null
null
null
UTF-8
C++
false
false
2,940
h
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2008 Renato Araujo Oliveira Filho <renatox@gmail.com> Copyright (c) 2000-2012 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #ifndef __GLESTextureManager_H__ #define __GLESTextureManager_H__ #include "OgreGLESPrerequisites.h" #include "OgreTextureManager.h" #include "OgreGLESTexture.h" #include "OgreGLESSupport.h" namespace Ogre { /** GL ES-specific implementation of a TextureManager */ class _OgreGLESExport GLESTextureManager : public TextureManager { public: GLESTextureManager(GLESSupport& support); virtual ~GLESTextureManager(); GLuint getWarningTextureID() { return mWarningTextureID; } /// @copydoc TextureManager::getNativeFormat PixelFormat getNativeFormat(TextureType ttype, PixelFormat format, int usage); /// @copydoc TextureManager::isHardwareFilteringSupported bool isHardwareFilteringSupported(TextureType ttype, PixelFormat format, int usage, bool preciseFormatOnly = false); protected: friend class GLESRenderSystem; /// @copydoc ResourceManager::createImpl Resource* createImpl(const String& name, ResourceHandle handle, const String& group, bool isManual, ManualResourceLoader* loader, const NameValuePairList* createParams); /// Internal method to create a warning texture (bound when a texture unit is blank) void createWarningTexture(); GLESSupport& mGLSupport; GLuint mWarningTextureID; }; } #endif
[ "qinlong.mkl@gmail.com" ]
qinlong.mkl@gmail.com
955139e7506cc702570883de1afc71f41a597d04
58b93746108b71d94e0c56b22978bae9293e943e
/lib/grooveshark/qtokendata.cpp
1224add8f109bcbf65ece74c8251b9e7e299026c
[]
no_license
purinda/grooveshark-server
dcd977959a90bf3001ed654a4b601332e4dbff96
93f55f3dd0a5ac14600749170065fff85a8ebeb2
refs/heads/master
2021-01-01T16:56:28.545127
2017-05-08T02:31:03
2017-05-08T02:31:03
14,986,886
9
1
null
2013-12-18T02:34:30
2013-12-06T15:58:16
C++
UTF-8
C++
false
false
55
cpp
#include "qtokendata.h" QTokenData::QTokenData() { }
[ "purinda@gmail.com" ]
purinda@gmail.com
5ab866b48be005d0ba8d02fd95fc2eddbaacc742
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_2749486_0/C++/Sharjeel/problem1.cpp
182974cfe8b0f52bfe9f12ac51f4049aea6eeda2
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
5,413
cpp
#include<iostream> #include<fstream> #include<math.h> #include<string> using namespace std; int main() { ifstream alpha("B-small-attempt0.in"); ofstream beta("output.txt"); int T; alpha>>T; int i; int X,Y; char s[500]=""; for(i=1;i<=T;i++) { alpha>>X>>Y; int x=0; int y=0; int j=1; while(x!=X || y!=Y) { if(X-x==j) { x+=j; s[j]=s[j-1]; s[j-1]='E'; } else if(x-X==j) { x-=j; s[j]=s[j-1]; s[j-1]='W'; } else if(Y-y==j) { y+=j; s[j]=s[j-1]; s[j-1]='N'; } else if(y-Y==j) { y-=j; s[j]=s[j-1]; s[j-1]='S'; } else if(X-x>j) { x+=j; s[j]=s[j-1]; s[j-1]='E'; } else if(x-X>j) { x-=j; s[j]=s[j-1]; s[j-1]='W'; } else if(Y-y>j) { y+=j; s[j]=s[j-1]; s[j-1]='N'; } else if(y-Y>j) { y-=j; s[j]=s[j-1]; s[j-1]='S'; } else if(abs(X-x)<abs(Y-y)) { if(Y-y>0) { y-=j; s[j]=s[j-1]; s[j-1]='S'; j++; y+=j; s[j]=s[j-1]; s[j-1]='N'; } else { y+=j; s[j]=s[j-1]; s[j-1]='N'; j++; y-=j; s[j]=s[j-1]; s[j-1]='S'; } } else { if(X-x>0) { x-=j; s[j]=s[j-1]; s[j-1]='W'; j++; x+=j; s[j]=s[j-1]; s[j-1]='E'; } else { x+=j; s[j]=s[j-1]; s[j-1]='E'; j++; x-=j; s[j]=s[j-1]; s[j-1]='W'; } } j++; } s[j-1]=0; beta<<"Case #"<<i<<": "<<s<<endl;; } cin>>i; return 0; }
[ "eewestman@gmail.com" ]
eewestman@gmail.com
9de70ae2cda7531c62081c1be34af7b628c7a9d7
211e9aa34d1f5e25a899bf773ab39d6ddb730c2c
/alps/mediatek/platform/mt6572/hardware/camera/core/drv/isp/seninf_drv.cpp
21e4868a55dd613a681932f5d2f3caed1ab5dfac
[]
no_license
a1batross/d620_gigabyte_4_2_kernel_source_code_alto_a2
aab88b485b78c4158d0d659f8d330bda52605e10
aaaf766e5ccc868d40202bd9e90316d01672327b
refs/heads/master
2021-01-01T03:58:40.657006
2016-05-24T20:52:22
2016-05-24T20:52:22
59,596,425
1
0
null
null
null
null
UTF-8
C++
false
false
48,579
cpp
/******************************************************************************************** * LEGAL DISCLAIMER * * (Header of MediaTek Software/Firmware Release or Documentation) * * BY OPENING OR USING THIS FILE, BUYER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") RECEIVED * FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO BUYER ON AN "AS-IS" BASIS * ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR * A PARTICULAR PURPOSE OR NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY * WHATSOEVER WITH RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, * INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND BUYER AGREES TO LOOK * ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. MEDIATEK SHALL ALSO * NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE RELEASES MADE TO BUYER'S SPECIFICATION * OR TO CONFORM TO A PARTICULAR STANDARD OR OPEN FORUM. * * BUYER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND CUMULATIVE LIABILITY WITH * RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE * FEES OR SERVICE CHARGE PAID BY BUYER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * THE TRANSACTION CONTEMPLATED HEREUNDER SHALL BE CONSTRUED IN ACCORDANCE WITH THE LAWS * OF THE STATE OF CALIFORNIA, USA, EXCLUDING ITS CONFLICT OF LAWS PRINCIPLES. ************************************************************************************************/ #define LOG_TAG "SeninfDrv" // #include <fcntl.h> #include <sys/mman.h> #if (PLATFORM_VERSION_MAJOR == 2) #include <utils/threads.h> // For android::Mutex. #else #include <utils/Mutex.h> // For android::Mutex. #endif #include <cutils/atomic.h> #include <cutils/properties.h> // For property_get(). //#include <mt6589_sync_write.h> #include <cutils/xlog.h> // #include "drv_types.h" #include "camera_isp.h" #include "isp_reg.h" #include "seninf_reg.h" #include "seninf_drv.h" #include "sensor_hal.h" //#include "gpio_const.h" //#include "mt_gpio.h" #define GPIO_MODE_00 0 #define GPIO_MODE_01 1 #define GPIO_MODE_02 2 #define GPIO62 62 #define GPIO61 61 //----------------------------------------------------------------------------- #undef DBG_LOG_TAG // Decide a Log TAG for current file. #define DBG_LOG_TAG LOG_TAG #include "drv_log.h" // Note: DBG_LOG_TAG/LEVEL will be used in header file, so header must be included after definition. DECLARE_DBG_LOG_VARIABLE(seninf_drv); EXTERN_DBG_LOG_VARIABLE(seninf_drv); // Clear previous define, use our own define. #undef LOG_VRB #undef LOG_DBG #undef LOG_INF #undef LOG_WRN #undef LOG_ERR #undef LOG_AST #define LOG_VRB(fmt, arg...) do { if (seninf_drv_DbgLogEnable_VERBOSE) { BASE_LOG_VRB(fmt, ##arg); } } while(0) #define LOG_DBG(fmt, arg...) do { if (seninf_drv_DbgLogEnable_DEBUG ) { BASE_LOG_DBG(fmt, ##arg); } } while(0) #define LOG_INF(fmt, arg...) do { if (seninf_drv_DbgLogEnable_INFO ) { BASE_LOG_INF(fmt, ##arg); } } while(0) #define LOG_WRN(fmt, arg...) do { if (seninf_drv_DbgLogEnable_WARN ) { BASE_LOG_WRN(fmt, ##arg); } } while(0) #define LOG_ERR(fmt, arg...) do { if (seninf_drv_DbgLogEnable_ERROR ) { BASE_LOG_ERR(fmt, ##arg); } } while(0) #define LOG_AST(cond, fmt, arg...) do { if (seninf_drv_DbgLogEnable_ASSERT ) { BASE_LOG_AST(cond, fmt, ##arg); } } while(0) /****************************************************************************** * *******************************************************************************/ #define SENINF_DEV_NAME "/dev/mt6572-seninf" #define ISP_DEV_NAME "/dev/camera-isp" #define SCAM_ENABLE (1) // 1: enable SCAM feature. 0. disable SCAM feature. #define FPGA (0) // Jason TODO remove #define JASON_TMP (0) // Jason TODO remove, for rst/pdn sensor on FPGA #define CAM_MMSYS_CONFIG_BASE 0x14000000 //MT6572 #define CAM_MMSYS_CONFIG_RANGE 0x100 #define CAM_MIPI_RX_CONFIG_BASE 0x14015000 //MT6572 #define CAM_MIPI_RX_CONFIG_RANGE 0x100 #define CAM_MIPI_CONFIG_BASE 0x10011000 //MT6572 #define CAM_MIPI_CONFIG_RANGE 0x1000 #define CAM_GPIO_CFG_BASE 0x1020B000 //MT6572 #define CAM_GPIO_CFG_RANGE 0x100 //#define CAM_GPIO_BASE 0x10005000 //MT6572 //#define CAM_GPIO_RANGE 0x1000 //#define CAM_PLL_BASE 0x10000000 //Jason TODO Reg //#define CAM_PLL_RANGE 0x200 //#define CAM_APCONFIG_RANGE 0x1000 //#define CAM_MIPIRX_ANALOG_RANGE 0x1000 //#define CAM_MIPIPLL_RANGE 0x100 int SEN_CSI2_SETTING = 1; int SEN_CSI2_ENABLE = 0; // no need to do sync write after 89; this only for coding sync #define mt65xx_reg_sync_writel(v, a) \ do { \ *(volatile unsigned int *)(a) = (v); \ } while (0) /******************************************************************************* * ********************************************************************************/ SeninfDrv* SeninfDrv::createInstance() { DBG_LOG_CONFIG(drv, seninf_drv); return SeninfDrv::getInstance(); } /******************************************************************************* * ********************************************************************************/ static SeninfDrv singleton; SeninfDrv* SeninfDrv:: getInstance() { LOG_MSG("[getInstance] \n"); return &singleton; } /******************************************************************************* * ********************************************************************************/ void SeninfDrv:: destroyInstance() { } /******************************************************************************* * ********************************************************************************/ SeninfDrv::SeninfDrv() { LOG_MSG("[SeninfDrv] \n"); mUsers = 0; mfd = 0; } /******************************************************************************* * ********************************************************************************/ SeninfDrv::~SeninfDrv() { LOG_MSG("[~SeninfDrv] \n"); } /******************************************************************************* * ********************************************************************************/ int SeninfDrv::init() { LOG_MSG("[init]: Entry count %d \n", mUsers); MBOOL result; //MINT32 imgsys_cg_clr0 = 0x15000000; //MINT32 pll_base_hw = 0x10000000; //MINT32 mipiRx_config = 0x1500C000; //MINT32 mipiRx_analog = 0x10012000; //MINT32 mipiRx_analog = 0x10012800; //MINT32 gpio_base_addr = 0x10001000; Mutex::Autolock lock(mLock); // if (mUsers > 0) { LOG_MSG(" Has inited \n"); android_atomic_inc(&mUsers); return 0; } // open isp driver mfd = open(ISP_DEV_NAME, O_RDWR); LOG_MSG(" Open ISP kernel done \n"); if (mfd < 0) { LOG_ERR("error open kernel driver, %d, %s\n", errno, strerror(errno)); return -1; } // access mpIspHwRegAddr m_pIspDrv = IspDrv::createInstance(); LOG_MSG(" Create ISP Instance done \n"); if (!m_pIspDrv) { LOG_ERR("IspDrvImp::createInstance fail \n"); return -2; } // result = m_pIspDrv->init(); LOG_MSG(" IspDrv init done \n"); if ( MFALSE == result ) { LOG_ERR("pIspDrv->init() fail \n"); return -3; } //get isp reg for TG module use mpIspHwRegAddr = (unsigned long*)m_pIspDrv->getRegAddr(); LOG_MSG(" IspDrv getRegAddr done \n"); if ( NULL == mpIspHwRegAddr ) { LOG_ERR("getRegAddr fail \n"); return -4; } // mmap seninf reg mpSeninfHwRegAddr = (unsigned long *) mmap(0, SENINF_BASE_RANGE, (PROT_READ|PROT_WRITE|PROT_NOCACHE), MAP_SHARED, mfd, SENINF_BASE_HW); LOG_MSG(" mmap 1 done \n"); if (mpSeninfHwRegAddr == MAP_FAILED) { LOG_ERR("mmap err(1), %d, %s \n", errno, strerror(errno)); return -5; } #if (!FPGA) // Jason TODO remove // mmap gpio reg /* mt_gpio_set_mode at isp kernel driver mpGpioHwRegAddr = (unsigned long *) mmap(0, CAM_GPIO_RANGE, (PROT_READ | PROT_WRITE), MAP_SHARED, mfd, CAM_GPIO_BASE); if (mpGpioHwRegAddr == MAP_FAILED) { LOG_ERR("mmap err(6), %d, %s \n", errno, strerror(errno)); return -10; } */ mpCAMIODrvRegAddr = (unsigned long *) mmap(0, CAM_GPIO_CFG_RANGE, (PROT_READ|PROT_WRITE|PROT_NOCACHE), MAP_SHARED, mfd, CAM_GPIO_CFG_BASE); if(mpCAMIODrvRegAddr == MAP_FAILED) { return -10; } // mmap pll reg /* clkmux_sel at isp kernel driver mpPLLHwRegAddr = (unsigned long *) mmap(0, CAM_PLL_RANGE, (PROT_READ | PROT_WRITE), MAP_SHARED, mfd, CAM_PLL_BASE); if (mpPLLHwRegAddr == MAP_FAILED) { LOG_ERR("mmap err(2), %d, %s \n", errno, strerror(errno)); return -6; } mpIPllCon0RegAddr = mpPLLHwRegAddr + (0x158 /4); */ // mmap seninf clear gating reg mpCAMMMSYSRegAddr = (unsigned long *) mmap(0, CAM_MMSYS_CONFIG_RANGE, (PROT_READ|PROT_WRITE|PROT_NOCACHE), MAP_SHARED, mfd, CAM_MMSYS_CONFIG_BASE); if (mpCAMMMSYSRegAddr == MAP_FAILED) { LOG_ERR("mmap err(3), %d, %s \n", errno, strerror(errno)); return -7; } // mipi rx config address mpCSI2RxConfigRegAddr = (unsigned long *) mmap(0, CAM_MIPI_RX_CONFIG_RANGE, (PROT_READ|PROT_WRITE|PROT_NOCACHE), MAP_SHARED, mfd, CAM_MIPI_RX_CONFIG_BASE); if (mpCSI2RxConfigRegAddr == MAP_FAILED) { LOG_ERR("mmap err(4), %d, %s \n", errno, strerror(errno)); return -8; } // mipi rx analog address mpCSI2RxAnalogRegStartAddr = (unsigned long *) mmap(0, CAM_MIPI_CONFIG_RANGE, (PROT_READ|PROT_WRITE|PROT_NOCACHE), MAP_SHARED, mfd, CAM_MIPI_CONFIG_BASE); if (mpCSI2RxAnalogRegStartAddr == MAP_FAILED) { LOG_ERR("mmap err(5), %d, %s \n", errno, strerror(errno)); return -9; } mpCSI2RxAnalogRegAddr = mpCSI2RxAnalogRegStartAddr + (0x800/4); //set CMMCLK(gpio_62) mode 1 ISP_GPIO_SEL_STRUCT gpioCtrl; gpioCtrl.Pin = GPIO62; // CMMCLK gpioCtrl.Mode = GPIO_MODE_01; ioctl(mfd, ISP_IOC_GPIO_SEL_IRQ, &gpioCtrl); //set CMPCLK(gpio_61) mode 1 gpioCtrl.Pin = GPIO61; // CMPCLK gpioCtrl.Mode = GPIO_MODE_01; ioctl(mfd, ISP_IOC_GPIO_SEL_IRQ, &gpioCtrl); #endif #if (FPGA) // For FPGA LOG_WRN("Sensor init rst/pdn power up\n"); setPdnRst(1, 1); #endif android_atomic_inc(&mUsers); LOG_MSG("[init]: Exit count %d \n", mUsers); return 0; } /******************************************************************************* * ********************************************************************************/ int SeninfDrv::uninit() { LOG_MSG("[uninit]: %d \n", mUsers); MBOOL result; Mutex::Autolock lock(mLock); // if (mUsers <= 0) { // No more users return 0; } // More than one user android_atomic_dec(&mUsers); if (mUsers == 0) { // Last user setTg1CSI2(0, 0, 0, 0, 0, 0, 0, 0); // disable CSI2 setTg1PhaseCounter(0, 0, 0, 0, 0, 0, 0); #if (FPGA) // Jason TODO remove LOG_WRN("Sensor uninit rst/pdn power down"); setPdnRst(1, 0); #endif #if (!FPGA) // Jason TODO remove //set CMMCLK(gpio_62) mode 0 ISP_GPIO_SEL_STRUCT gpioCtrl; gpioCtrl.Pin = GPIO62; // CMMCLK gpioCtrl.Mode = GPIO_MODE_00; ioctl(mfd, ISP_IOC_GPIO_SEL_IRQ, &gpioCtrl); //set CMPCLK(gpio_61) mode 0 gpioCtrl.Pin = GPIO61; // CMPCLK gpioCtrl.Mode = GPIO_MODE_00; ioctl(mfd, ISP_IOC_GPIO_SEL_IRQ, &gpioCtrl); // Disable Camera PLL // Jason TODO PLL //(*mpIPllCon0RegAddr) |= 0x01; //Power Down // Jason TODO Reg //disable MIPI RX analog *(mpCSI2RxAnalogRegAddr + (0x24/4)) &= 0xFFFFFFFE;//RG_CSI_BG_CORE_EN *(mpCSI2RxAnalogRegAddr + (0x20/4)) &= 0xFFFFFFFE;//RG_CSI0_LDO_CORE_EN *(mpCSI2RxAnalogRegAddr + (0x00/4)) &= 0xFFFFFFFE;//RG_CSI0_LNRC_LDO_OUT_EN *(mpCSI2RxAnalogRegAddr + (0x04/4)) &= 0xFFFFFFFE;//RG_CSI0_LNRD0_LDO_OUT_EN *(mpCSI2RxAnalogRegAddr + (0x08/4)) &= 0xFFFFFFFE;//RG_CSI0_LNRD1_LDO_OUT_EN // munmap rx analog address if ( 0 != mpCSI2RxAnalogRegStartAddr ) { munmap(mpCSI2RxAnalogRegStartAddr, CAM_MIPI_CONFIG_RANGE); mpCSI2RxAnalogRegStartAddr = NULL; } // munmap rx config address if ( 0 != mpCSI2RxConfigRegAddr ) { munmap(mpCSI2RxConfigRegAddr, CAM_MIPI_RX_CONFIG_RANGE); mpCSI2RxConfigRegAddr = NULL; } // munmap seninf clear gating reg if ( 0 != mpCAMMMSYSRegAddr ) { munmap(mpCAMMMSYSRegAddr, CAM_MMSYS_CONFIG_RANGE); mpCAMMMSYSRegAddr = NULL; } // munmap gpio reg if ( 0 != mpCAMIODrvRegAddr ) { munmap(mpCAMIODrvRegAddr, CAM_GPIO_CFG_RANGE); mpCAMIODrvRegAddr = NULL; } #endif // munmap seninf reg if ( 0 != mpSeninfHwRegAddr ) { munmap(mpSeninfHwRegAddr, SENINF_BASE_RANGE); mpSeninfHwRegAddr = NULL; } // uninit isp mpIspHwRegAddr = NULL; result = m_pIspDrv->uninit(); if ( MFALSE == result ) { LOG_ERR("pIspDrv->uninit() fail \n"); return -3; } // if (mfd > 0) { close(mfd); mfd = -1; } } else { LOG_MSG(" Still users \n"); } return 0; } /******************************************************************************* * ********************************************************************************/ int SeninfDrv::waitSeninf1Irq(int mode) { int ret = 0; LOG_MSG("[waitIrq polling] 0x%x \n", mode); seninf_reg_t *pSeninf = (seninf_reg_t *)mpSeninfHwRegAddr; int sleepCount = 40; int sts; ret = -1; while (sleepCount-- > 0) { sts = SENINF_READ_REG(pSeninf, SENINF1_INTSTA); // Not sure CTL_INT_STATUS or CTL_INT_EN if (sts & mode) { LOG_MSG("[waitIrq polling] Done: 0x%x \n", sts); ret = 0; break; } LOG_MSG("[waitIrq polling] Sleep... %d, 0x%x \n", sleepCount, sts); usleep(100 * 1000); } return ret; } /******************************************************************************* * ********************************************************************************/ int SeninfDrv::setTg1PhaseCounter( unsigned long pcEn, unsigned long mclkSel, unsigned long clkCnt, unsigned long clkPol, unsigned long clkFallEdge, unsigned long clkRiseEdge, unsigned long padPclkInv ) { int ret = 0; isp_reg_t *pisp = (isp_reg_t *) mpIspHwRegAddr; seninf_reg_t *pSeninf = (seninf_reg_t *)mpSeninfHwRegAddr; LOG_MSG("[setTg1PhaseCounter] pcEn(%d) clkPol(%d)\n",pcEn,clkPol); #if (!FPGA) // Jason TODO remove // Enable Camera PLL first // Jason TODO PLL ISP_PLL_SEL_STRUCT pllCtrl; if (mclkSel == CAM_PLL_48_GROUP) pllCtrl.MclkSel = MCLK_USING_UNIV_48M; // 48MHz else if (mclkSel == CAM_PLL_52_GROUP) pllCtrl.MclkSel = MCLK_USING_UNIV_208M; // 208MHz ioctl(mfd, ISP_IOC_PLL_SEL_IRQ, &pllCtrl); #endif #if (FPGA) // Jason TODO remove // Jason TODO tmp, use 12M and not to 6Mhz clkCnt = 0; #endif // clkRiseEdge = 0; clkFallEdge = (clkCnt > 1)? (clkCnt+1)>>1 : 1;//avoid setting larger than clkCnt //Seninf Top pclk clear gating SENINF_WRITE_BITS(pSeninf, SENINF_TOP_CTRL, SENINF1_PCLK_EN, 1); SENINF_WRITE_BITS(pSeninf, SENINF_TOP_CTRL, SENINF2_PCLK_EN, 1); #if (!FPGA) // Jason TODO remove SENINF_WRITE_BITS(pSeninf, SENINF_TG1_SEN_CK, CLKRS, clkRiseEdge); SENINF_WRITE_BITS(pSeninf, SENINF_TG1_SEN_CK, CLKFL, clkFallEdge); //SENINF_BITS(pSeninf, SENINF_TG1_SEN_CK, CLKCNT) = clkCnt - 1; SENINF_WRITE_BITS(pSeninf, SENINF_TG1_SEN_CK, CLKCNT, clkCnt); #else SENINF_WRITE_BITS(pSeninf, SENINF_TG1_SEN_CK, CLKRS, 0); SENINF_WRITE_BITS(pSeninf, SENINF_TG1_SEN_CK, CLKFL, 1); //SENINF_BITS(pSeninf, SENINF_TG1_SEN_CK, CLKCNT) = clkCnt - 1; // 12Mhz to 6Mhz SENINF_WRITE_BITS(pSeninf, SENINF_TG1_SEN_CK, CLKCNT, 1); // Jason TODO tmp, use 12M and not to 6Mhz SENINF_WRITE_BITS(pSeninf, SENINF_TG1_SEN_CK, CLKCNT, clkCnt); #endif //TODO:remove later //SENINF_BITS(pSeninf, SENINF_TG1_SEN_CK, CLKCNT) = 0; //FPGA //SENINF_BITS(pSeninf, SENINF_TG1_SEN_CK, CLKFL) = 0; //FPGA //SENINF_BITS(pSeninf, SENINF_TG1_SEN_CK, CLKFL) = clkCnt >> 1;//fpga SENINF_WRITE_BITS(pSeninf, SENINF_TG1_PH_CNT, CLKFL_POL, (clkCnt & 0x1) ? 0 : 1); SENINF_WRITE_BITS(pSeninf, SENINF_TG1_PH_CNT, CLKPOL, clkPol); // mclkSel, 0: 122.88MHz, (others: Camera PLL) 1: 120.3MHz, 2: 52MHz SENINF_WRITE_BITS(pSeninf, SENINF_TG1_PH_CNT, TGCLK_SEL, 1);//force PLL due to ISP engine clock dynamic spread SENINF_WRITE_BITS(pSeninf, SENINF_TG1_PH_CNT, ADCLK_EN, 1);//FPGA experiment SENINF_WRITE_BITS(pSeninf, SENINF_TG1_PH_CNT, PCEN, pcEn);//FPGA experiment SENINF_WRITE_BITS(pSeninf, SENINF_TG1_PH_CNT, PAD_PCLK_INV, padPclkInv); ISP_WRITE_BITS(pisp, CAM_TG_SEN_MODE, CMOS_EN, 1); // Wait 1ms for PLL stable usleep(1000); return ret; } /******************************************************************************* * ********************************************************************************/ int SeninfDrv::setTg1GrabRange( unsigned long pixelStart, unsigned long pixelEnd, unsigned long lineStart, unsigned long lineEnd ) { int ret = 0; isp_reg_t *pisp = (isp_reg_t *) mpIspHwRegAddr; LOG_MSG("[setTg1GrabRange] \n"); // TG Grab Win Setting ISP_WRITE_BITS(pisp, CAM_TG_SEN_GRAB_PXL, PXL_E, pixelEnd); ISP_WRITE_BITS(pisp, CAM_TG_SEN_GRAB_PXL, PXL_S, pixelStart); ISP_WRITE_BITS(pisp, CAM_TG_SEN_GRAB_LIN, LIN_E, lineEnd); ISP_WRITE_BITS(pisp, CAM_TG_SEN_GRAB_LIN, LIN_S, lineStart); return ret; } /******************************************************************************* * ********************************************************************************/ int SeninfDrv::setTg1SensorModeCfg( unsigned long hsPol, unsigned long vsPol ) { int ret = 0; isp_reg_t *pisp = (isp_reg_t *) mpIspHwRegAddr; seninf_reg_t *pSeninf = (seninf_reg_t *)mpSeninfHwRegAddr; LOG_MSG("[setTg1SensorModeCfg] \n"); // Sensor Mode Config SENINF_WRITE_BITS(pSeninf, SENINF1_CTRL, SENINF_HSYNC_POL, hsPol); SENINF_WRITE_BITS(pSeninf, SENINF1_CTRL, SENINF_VSYNC_POL, vsPol); //SENINF_WRITE_BITS(pSeninf, SENINF1_NCSI2_CTL, VS_TYPE, vsPol);//VS_TYPE = 0 for 4T:vsPol(0) //if(SEN_CSI2_SETTING) // SENINF_WRITE_BITS(pSeninf, SENINF1_CSI2_CTRL, CSI2_VSYNC_TYPE, !vsPol);//VSYNC_TYPE = 1 for 4T:vsPol(0) ISP_WRITE_BITS(pisp, CAM_TG_SEN_MODE, CMOS_EN, 1); ISP_WRITE_BITS(pisp, CAM_TG_SEN_MODE, SOT_MODE, 1); return ret; } /******************************************************************************* * ********************************************************************************/ int SeninfDrv::setTg1InputCfg( PAD2CAM_DATA_ENUM padSel, SENINF_SOURCE_ENUM inSrcTypeSel, TG_FORMAT_ENUM inDataType, SENSOR_DATA_BITS_ENUM senInLsb ) { int ret = 0; isp_reg_t *pisp = (isp_reg_t *) mpIspHwRegAddr; seninf_reg_t *pSeninf = (seninf_reg_t *)mpSeninfHwRegAddr; LOG_MSG("[setTg1InputCfg] \n"); LOG_MSG("inSrcTypeSel = % d \n",inSrcTypeSel); SENINF_WRITE_BITS(pSeninf, SENINF1_CTRL, SENINF_MUX_EN, 0x1); SENINF_WRITE_BITS(pSeninf, SENINF1_CTRL, PAD2CAM_DATA_SEL, padSel); SENINF_WRITE_BITS(pSeninf, SENINF1_CTRL, SENINF_SRC_SEL, inSrcTypeSel); if(SEN_CSI2_ENABLE && (inSrcTypeSel==MIPI_SENSOR)) SENINF_WRITE_BITS(pSeninf, SENINF1_CTRL, SENINF_SRC_SEL, 0); ISP_WRITE_BITS(pisp, CAM_TG_PATH_CFG, SEN_IN_LSB, 0x0);//no matter what kind of format, set 0 //ISP_WRITE_BITS(pisp, CAM_CTL_FMT_SEL_CLR, TG1_FMT_CLR, 0x7); //ISP_WRITE_BITS(pisp, CAM_CTL_FMT_SEL_SET, TG1_FMT_SET, inDataType); ISP_WRITE_BITS(pisp, CAM_CTL_FMT_SEL, TG1_FMT, inDataType); if (MIPI_SENSOR == inSrcTypeSel) { ISP_WRITE_BITS(pisp, CAM_TG_SEN_MODE, SOF_SRC, 0x0); if (JPEG_FMT == inDataType) { SENINF_WRITE_BITS(pSeninf, SENINF1_CTRL, FIFO_FLUSH_EN, 0x18);//0x1B; SENINF_WRITE_BITS(pSeninf, SENINF1_CTRL, FIFO_PUSH_EN, 0x1E);//0x1F; SENINF_WRITE_BITS(pSeninf, SENINF1_SPARE, SENINF_FIFO_FULL_SEL, 0x1); SENINF_WRITE_BITS(pSeninf, SENINF1_SPARE, SENINF_VCNT_SEL, 0x1); SENINF_WRITE_BITS(pSeninf, SENINF1_SPARE, SENINF_CRC_SEL, 0x2); } else { SENINF_WRITE_BITS(pSeninf, SENINF1_CTRL, FIFO_FLUSH_EN, 0x1B); SENINF_WRITE_BITS(pSeninf, SENINF1_CTRL, FIFO_PUSH_EN, 0x1F); } } else if (SERIAL_SENSOR == inSrcTypeSel) { // Jason TODO Serial } else { ISP_WRITE_BITS(pisp, CAM_TG_SEN_MODE, SOF_SRC, 0x1); SENINF_WRITE_BITS(pSeninf, SENINF1_CTRL, FIFO_FLUSH_EN, 0x1B); SENINF_WRITE_BITS(pSeninf, SENINF1_CTRL, FIFO_PUSH_EN, 0x1F); } //One-pixel mode if ( JPEG_FMT != inDataType) { SENINF_WRITE_BITS(pSeninf, SENINF1_CTRL, SENINF_PIX_SEL, 0); ISP_WRITE_BITS(pisp, CAM_TG_SEN_MODE, DBL_DATA_BUS, 0); //ISP_WRITE_BITS(pisp, CAM_CTL_FMT_SEL_CLR, TWO_PIX_CLR, 1); //ISP_WRITE_BITS(pisp, CAM_CTL_FMT_SEL_SET, TWO_PIX_SET, 0); ISP_WRITE_BITS(pisp, CAM_TG_PATH_CFG, JPGINF_EN, 0); } else { SENINF_WRITE_BITS(pSeninf, SENINF1_CTRL, SENINF_PIX_SEL, 1); ISP_WRITE_BITS(pisp, CAM_TG_SEN_MODE, DBL_DATA_BUS, 1); //ISP_WRITE_BITS(pisp, CAM_CTL_FMT_SEL_CLR, TWO_PIX_CLR, 1); //ISP_WRITE_BITS(pisp, CAM_CTL_FMT_SEL_SET, TWO_PIX_SET, 1); ISP_WRITE_BITS(pisp, CAM_TG_PATH_CFG, JPGINF_EN, 1); } SENINF_WRITE_BITS(pSeninf, SENINF1_CTRL, SENINF_MUX_SW_RST, 0x1); SENINF_WRITE_BITS(pSeninf, SENINF1_CTRL, SENINF_IRQ_SW_RST, 0x1); SENINF_WRITE_BITS(pSeninf, SENINF1_CTRL, SENINF_MUX_SW_RST, 0x0); SENINF_WRITE_BITS(pSeninf, SENINF1_CTRL, SENINF_IRQ_SW_RST, 0x0); return ret; } /******************************************************************************* * ********************************************************************************/ int SeninfDrv::setTg1ViewFinderMode( unsigned long spMode, unsigned long spDelay ) { int ret = 0; isp_reg_t *pisp = (isp_reg_t *) mpIspHwRegAddr; LOG_MSG("[setTg1ViewFinderMode] \n"); // ISP_WRITE_BITS(pisp, CAM_TG_VF_CON, SPDELAY_MODE, 1); ISP_WRITE_BITS(pisp, CAM_TG_VF_CON, SINGLE_MODE, spMode); ISP_WRITE_BITS(pisp, CAM_TG_VF_CON, SP_DELAY, spDelay); return ret; } /******************************************************************************* * ********************************************************************************/ int SeninfDrv::sendCommand(int cmd, int arg1, int arg2, int arg3) { int ret = 0; LOG_MSG("[sendCommand] cmd: 0x%x \n", cmd); switch (cmd) { case CMD_SET_DEVICE: mDevice = arg1; break; case CMD_GET_SENINF_ADDR: //LOG_MSG(" CMD_GET_ISP_ADDR: 0x%x \n", (int) mpIspHwRegAddr); *(int *) arg1 = (int) mpSeninfHwRegAddr; break; default: ret = -1; break; } return ret; } /******************************************************************************* * ********************************************************************************/ unsigned long SeninfDrv::readReg(unsigned long addr) { int ret; reg_t reg[2]; int val = 0xFFFFFFFF; LOG_MSG("[readReg] addr: 0x%08x \n", (int) addr); // reg[0].addr = addr; reg[0].val = val; // ret = readRegs(reg, 1); if (ret < 0) { } else { val = reg[0].val; } return val; } /******************************************************************************* * ********************************************************************************/ int SeninfDrv::writeReg(unsigned long addr, unsigned long val) { int ret; reg_t reg[2]; LOG_MSG("[writeReg] addr/val: 0x%08x/0x%08x \n", (int) addr, (int) val); // reg[0].addr = addr; reg[0].val = val; // ret = writeRegs(reg, 1); return ret; } /******************************************************************************* * ********************************************************************************/ int SeninfDrv::readRegs(reg_t *pregs, int count) { MBOOL result = MTRUE; result = m_pIspDrv->readRegs( (ISP_DRV_REG_IO_STRUCT*) pregs, count); if ( MFALSE == result ) { LOG_ERR("MT_ISP_IOC_G_READ_REG err \n"); return -1; } return 0; } /******************************************************************************* * ********************************************************************************/ int SeninfDrv::writeRegs(reg_t *pregs, int count) { MBOOL result = MTRUE; result = m_pIspDrv->writeRegs( (ISP_DRV_REG_IO_STRUCT*) pregs, count); if ( MFALSE == result ) { LOG_ERR("MT_ISP_IOC_S_WRITE_REG err \n"); return -1; } return 0; } /******************************************************************************* * ********************************************************************************/ int SeninfDrv::holdReg(bool isHold) { int ret; int hold = isHold; //LOG_MSG("[holdReg]"); ret = ioctl(mfd, ISP_IOC_HOLD_REG, &hold); if (ret < 0) { LOG_ERR("ISP_IOC_HOLD_REG err \n"); } return ret; } /******************************************************************************* * ********************************************************************************/ int SeninfDrv::dumpReg() { int ret; LOG_MSG("[dumpReg] \n"); ret = ioctl(mfd, ISP_IOC_DUMP_REG, NULL); if (ret < 0) { LOG_ERR("ISP_IOC_DUMP_REG err \n"); } return ret; } /******************************************************************************* * ********************************************************************************/ int SeninfDrv::initTg1CSI2(bool csi2_en) { seninf_reg_t *pSeninf = (seninf_reg_t *)mpSeninfHwRegAddr; int ret = 0; unsigned int temp = 0; LOG_MSG("[initCSI2]:enable = %d\n", (int) csi2_en); //--- add for efuse ---// unsigned long* efuseAddr = (unsigned long *) mmap(0, 0x200, (PROT_READ|PROT_WRITE|PROT_NOCACHE), MAP_SHARED, mfd, 0x10009000); if (efuseAddr == MAP_FAILED) { LOG_ERR("efuse mmap err, %d, %s \n", errno, strerror(errno)); return -1; } //unsigned int mipiVar = *(mpCSI2RxAnalogRegAddr + (0x24/4)); unsigned int efuseVar = *(efuseAddr + (0x180/4)); unsigned long* mipiVar = mpCSI2RxAnalogRegAddr + (0x24/4); unsigned int tmpVar; LOG_MSG("efuseVar = 0x%08x", efuseVar); LOG_MSG("MIPI_RX_ANA24 Var original = 0x%08x", *(mipiVar)); //MIPI_RX_ANA24[15:12] = MIPI_RX_ANA24[15:12] + Offset180 [7:4] if(efuseVar&0x000000F0) { tmpVar = 0x8 + ((efuseVar&0x000000F0)>>4); *(mipiVar) &= 0xFFFF0FFF; *(mipiVar) |= ((tmpVar&0x0000000F)<<12); } //MIPI_RX_ANA24[11:8] = MIPI_RX_ANA24[11:8] + Offset180 [3:0] if(efuseVar&0x0000000F) { tmpVar = 0x8 + ((efuseVar&0x0000000F)); *(mipiVar) &= 0xFFFFF0FF; *(mipiVar) |= ((tmpVar&0x0000000F)<<8); } LOG_MSG("MIPI_RX_ANA24 Var after efuse = 0x%08x", *(mipiVar)); if ( 0 != efuseAddr ) { munmap(efuseAddr, 0x200); efuseAddr = NULL; } //--- add for efuse ---// #if (!FPGA) // Jason TODO remove if(csi2_en == 0) { // disable mipi BG *(mpCSI2RxAnalogRegAddr + (0x24/4)) &= 0xFFFFFFFE;//RG_CSI_BG_CORE_EN // Jason TODO GPIO api // disable mipi gpio pin //*(mpGpioHwRegAddr + (0x1C0/4)) |= 0xFFE0;//GPI*_IES = 1 for Parallel CAM //*(mpGpioHwRegAddr + (0x1D0/4)) |= 0x0001;//GPI*_IES = 1 for Parallel CAM // disable mipi input select *(mpCSI2RxAnalogRegAddr + (0x00/4)) &= 0xFFFFFFE7;//main & sub clock lane input select hi-Z *(mpCSI2RxAnalogRegAddr + (0x04/4)) &= 0xFFFFFFE7;//main & sub data lane 0 input select hi-Z *(mpCSI2RxAnalogRegAddr + (0x08/4)) &= 0xFFFFFFE7;//main & sub data lane 1 input select hi-Z } else { // enable mipi input select if(mDevice & SENSOR_DEV_MAIN) { *(mpCSI2RxAnalogRegAddr + (0x00/4)) |= 0x00000008;//main clock lane input select mipi *(mpCSI2RxAnalogRegAddr + (0x04/4)) |= 0x00000008;//main data lane 0 input select mipi *(mpCSI2RxAnalogRegAddr + (0x08/4)) |= 0x00000008;//main data lane 1 input select mipi *(mpCSI2RxAnalogRegAddr + (0x00/4)) &= 0xFFFFFFEF;//sub clock lane input select mipi disable *(mpCSI2RxAnalogRegAddr + (0x04/4)) &= 0xFFFFFFEF;//sub data lane 0 input select mipi disable *(mpCSI2RxAnalogRegAddr + (0x08/4)) &= 0xFFFFFFEF;//sub data lane 1 input select mipi disable } else if(mDevice & SENSOR_DEV_SUB) { *(mpCSI2RxAnalogRegAddr + (0x00/4)) |= 0x00000010;//sub clock lane input select mipi *(mpCSI2RxAnalogRegAddr + (0x04/4)) |= 0x00000010;//sub data lane 0 input select mipi *(mpCSI2RxAnalogRegAddr + (0x08/4)) |= 0x00000010;//sub data lane 1 input select mipi *(mpCSI2RxAnalogRegAddr + (0x00/4)) &= 0xFFFFFFF7;//main clock lane input select mipi disable *(mpCSI2RxAnalogRegAddr + (0x04/4)) &= 0xFFFFFFF7;//main data lane 0 input select mipi disable *(mpCSI2RxAnalogRegAddr + (0x08/4)) &= 0xFFFFFFF7;//main data lane 1 input select mipi disable } // enable mipi BG *(mpCSI2RxAnalogRegAddr + (0x24/4)) |= 0x00000001;//RG_CSI_BG_CORE_EN usleep(30); *(mpCSI2RxAnalogRegAddr + (0x20/4)) |= 0x00000001;//RG_CSI0_LDO_CORE_EN usleep(1); *(mpCSI2RxAnalogRegAddr + (0x00/4)) |= 0x00000001;//RG_CSI0_LNRC_LDO_OUT_EN *(mpCSI2RxAnalogRegAddr + (0x04/4)) |= 0x00000001;//RG_CSI0_LNRD0_LDO_OUT_EN *(mpCSI2RxAnalogRegAddr + (0x08/4)) |= 0x00000001;//RG_CSI0_LNRD1_LDO_OUT_EN // CSI Offset calibration SENINF_WRITE_BITS(pSeninf, SENINF1_CSI2_DBG, LNC_HSRXDB_EN, 1); SENINF_WRITE_BITS(pSeninf, SENINF1_CSI2_DBG, LN0_HSRXDB_EN, 1); SENINF_WRITE_BITS(pSeninf, SENINF1_CSI2_DBG, LN1_HSRXDB_EN, 1); *(mpCSI2RxConfigRegAddr + (0x38/4)) |= 0x00000004;//MIPI_RX_HW_CAL_START LOG_MSG("[initCSI2]:CSI0 calibration do !\n"); //usleep(1000); //while( !(*(mpCSI2RxConfigRegAddr + (0x44/4)) & 0x10101) ){}// polling LNRC, LNRD0, LNRD1 usleep(1000); if(!(*(mpCSI2RxConfigRegAddr + (0x44/4)) & 0x10101))// checking LNRC, LNRD0, LNRD1 { LOG_ERR("[initCSI2]: CIS2Polling calibration failed: 0x%08x", *(mpCSI2RxConfigRegAddr + (0x44/4))); ret = -1; } LOG_MSG("[initCSI2]:CSI0 calibration end !\n"); SENINF_WRITE_BITS(pSeninf, SENINF1_CSI2_DBG, LNC_HSRXDB_EN, 0); SENINF_WRITE_BITS(pSeninf, SENINF1_CSI2_DBG, LN0_HSRXDB_EN, 0); SENINF_WRITE_BITS(pSeninf, SENINF1_CSI2_DBG, LN1_HSRXDB_EN, 0); *(mpCSI2RxAnalogRegAddr + (0x20/4)) &= 0xFFFFFFDF;//bit 5:RG_CSI0_4XCLK_INVERT = 0 *(mpCSI2RxAnalogRegAddr + (0x04/4)) &= 0xFFBFFFFF;//bit 22:RG_CSI0_LNRD0_HSRX_BYPASS_SYNC = 0 *(mpCSI2RxAnalogRegAddr + (0x08/4)) &= 0xFFBFFFFF;//bit 22:RG_CSI0_LNRD1_HSRX_BYPASS_SYNC = 0 *(mpCSI2RxAnalogRegAddr + (0x20/4)) |= 0x00000040;//bit 6:RG_CSI0_4XCLK_DISABLE = 1 *(mpCSI2RxAnalogRegAddr + (0x20/4)) |= 0x00000002;//bit 1:RG_CSI0_LNRD_HSRX_BCLK_INVERT = 1 if(SEN_CSI2_SETTING) *(mpCSI2RxAnalogRegAddr + (0x20/4)) &= 0xFFFFFFBF;//bit 6:RG_CSI0_4XCLK_DISABLE = 0 } #endif return ret; } /******************************************************************************* * ********************************************************************************/ unsigned int SETTLE_TEST = 0x00001A00; bool HW_MODE = 0; int SeninfDrv::setTg1CSI2( unsigned long dataTermDelay, unsigned long dataSettleDelay, unsigned long clkTermDelay, unsigned long vsyncType, unsigned long dlane_num, unsigned long csi2_en, unsigned long dataheaderOrder, unsigned long dataFlow ) { int ret = 0,temp = 0; seninf_reg_t *pSeninf = (seninf_reg_t *)mpSeninfHwRegAddr; if(csi2_en == 1) { LOG_WRN("[configTg1CSI2]:DataTermDelay:%d SettleDelay:%d ClkTermDelay:%d VsyncType:%d dlane_num:%d CSI2 enable:%d HeaderOrder:%d DataFlow:%d\n", (int) dataTermDelay, (int) dataSettleDelay, (int) clkTermDelay, (int) vsyncType, (int) dlane_num, (int) csi2_en, (int)dataheaderOrder, (int)dataFlow); // disable NCSI2 first SENINF_WRITE_BITS(pSeninf, SENINF1_NCSI2_CTL, CLOCK_LANE_EN, 0); // add src select earlier, for countinuous MIPI clk issue SENINF_WRITE_BITS(pSeninf, SENINF1_CTRL, SENINF_SRC_SEL, 0x8); #if (FPGA) //temp = (dataSettleDelay&0xFF)<<8; //SENINF_WRITE_REG(pSeninf, SENINF1_NCSI2_LNRD_TIMING, temp); //SENINF_WRITE_BITS(pSeninf, SENINF1_NCSI2_LNRD_TIMING, SETTLE_PARAMETER, (dataSettleDelay&0xFF)); SENINF_WRITE_REG(pSeninf, SENINF1_NCSI2_LNRD_TIMING, 0x00000300); SENINF_WRITE_BITS(pSeninf, SENINF1_NCSI2_CTL, ED_SEL, 1); #else //SENINF_WRITE_REG(pSeninf, SENINF1_NCSI2_LNRD_TIMING, 0x00003000);//set 0x30 for settle delay SENINF_WRITE_REG(pSeninf, SENINF1_NCSI2_SPARE0, 0x80000000); SENINF_WRITE_BITS(pSeninf, SENINF1_NCSI2_CTL, ED_SEL, dataheaderOrder); #endif //VS_TYPE = 0 for 4T:vsPol(0) SENINF_WRITE_BITS(pSeninf, SENINF1_CTRL, SENINF_VSYNC_POL, 0); SENINF_WRITE_BITS(pSeninf, SENINF1_NCSI2_CTL, VS_TYPE, 0); //Use sw settle mode if(HW_MODE) { SENINF_WRITE_BITS(pSeninf, SENINF1_NCSI2_CTL, HSRX_DET_EN, 1); } else { SENINF_WRITE_BITS(pSeninf, SENINF1_NCSI2_CTL, HSRX_DET_EN, 0); SENINF_WRITE_REG(pSeninf, SENINF1_NCSI2_LNRD_TIMING, SETTLE_TEST); } // enable NCSI2 SENINF_WRITE_BITS(pSeninf, SENINF1_NCSI2_CTL, CLOCK_LANE_EN, csi2_en); switch(dlane_num) { case 0://SENSOR_MIPI_1_LANE SENINF_WRITE_BITS(pSeninf, SENINF1_NCSI2_CTL, DATA_LANE0_EN, 1); break; case 1://SENSOR_MIPI_2_LANE SENINF_WRITE_BITS(pSeninf, SENINF1_NCSI2_CTL, DATA_LANE0_EN, 1); SENINF_WRITE_BITS(pSeninf, SENINF1_NCSI2_CTL, DATA_LANE1_EN, 1); break; default: break; } // turn on all interrupt SENINF_WRITE_REG(pSeninf, SENINF1_NCSI2_INT_EN, 0x80007FFF); if(SEN_CSI2_SETTING) { // disable CSI2 first SENINF_WRITE_BITS(pSeninf, SENINF1_CSI2_CTRL, CSI2_EN, 0); SENINF_WRITE_REG(pSeninf, SENINF1_CSI2_DELAY, 0x00300000);//set 0x30 for settle delay SENINF_WRITE_BITS(pSeninf, SENINF1_CSI2_CTRL, CSI2_ED_SEL, dataheaderOrder); //VSYNC_TYPE = 1 for 4T:vsPol(0) SENINF_WRITE_BITS(pSeninf, SENINF1_CTRL, SENINF_VSYNC_POL, 0); SENINF_WRITE_BITS(pSeninf, SENINF1_CSI2_CTRL, CSI2_VSYNC_TYPE, 1); // enable CSI2 if(SEN_CSI2_ENABLE) { SENINF_WRITE_BITS(pSeninf, SENINF1_CSI2_CTRL, CSI2_EN, csi2_en); switch(dlane_num) { case 1://SENSOR_MIPI_2_LANE SENINF_WRITE_BITS(pSeninf, SENINF1_CSI2_CTRL, DLANE1_EN, 1); break; case 0://SENSOR_MIPI_1_LANE default: break; } } } } else { // disable NCSI2 SENINF_WRITE_BITS(pSeninf, SENINF1_NCSI2_CTL, CLOCK_LANE_EN, 0); SENINF_WRITE_BITS(pSeninf, SENINF1_NCSI2_CTL, DATA_LANE0_EN, 0); SENINF_WRITE_BITS(pSeninf, SENINF1_NCSI2_CTL, DATA_LANE1_EN, 0); if(SEN_CSI2_SETTING) { // disable CSI2 SENINF_WRITE_BITS(pSeninf, SENINF1_CSI2_CTRL, CSI2_EN, 0); SENINF_WRITE_BITS(pSeninf, SENINF1_CSI2_CTRL, DLANE1_EN, 0); SENINF_WRITE_BITS(pSeninf, SENINF1_CSI2_CTRL, DLANE2_EN, 0); } } LOG_WRN("end of setTg1CSI2\n"); //int j; //for(j = 0x600; j < 0x648; j+=4) // LOG_WRN("[%x]=0x%08x", j, *(mpSeninfHwRegAddr + (j/4))); return ret; } /******************************************************************************* * ********************************************************************************/ int SeninfDrv::initTg1Serial(bool serial_en) // Jason TODO Serial { int ret = 0; seninf_reg_t *pSeninf = (seninf_reg_t *)mpSeninfHwRegAddr; SENINF_WRITE_BITS(pSeninf, SCAM1_CON, Enable, serial_en); return ret; } /******************************************************************************* * ********************************************************************************/ // Jason TODO Serial int SeninfDrv::setTg1Serial( unsigned long clk_inv, unsigned long width, unsigned long height, unsigned long conti_mode, unsigned long csd_num) { int ret = 0; seninf_reg_t *pSeninf = (seninf_reg_t *)mpSeninfHwRegAddr; //set CMPCLK(gpio_61) mode 2 ISP_GPIO_SEL_STRUCT gpioCtrl; gpioCtrl.Pin = GPIO61; // CMPCLK gpioCtrl.Mode = GPIO_MODE_02; ioctl(mfd, ISP_IOC_GPIO_SEL_IRQ, &gpioCtrl); SENINF_WRITE_BITS(pSeninf, SCAM1_SIZE, WIDTH, width); SENINF_WRITE_BITS(pSeninf, SCAM1_SIZE, HEIGHT, height); SENINF_WRITE_BITS(pSeninf, SCAM1_CFG, Clock_inverse, clk_inv); SENINF_WRITE_BITS(pSeninf, SCAM1_CFG, Continuous_mode, conti_mode); SENINF_WRITE_BITS(pSeninf, SCAM1_CFG, CSD_NUM, csd_num); // 0(1-lane);1(2-line);2(4-lane) SENINF_WRITE_BITS(pSeninf, SCAM1_CFG, Cycle, 4); SENINF_WRITE_BITS(pSeninf, SCAM1_CFG2, DIS_GATED_CLK, 1); return ret; } /******************************************************************************* * ********************************************************************************/ int SeninfDrv::setTg1IODrivingCurrent(unsigned long ioDrivingCurrent) { /* [1: 0]: CMPCLK, CMMCLK , CMDAT0~3 00: 2mA 01: 4mA 10: 6mA 11: 8mA [3: 2]: CMPDN, CMRST [5: 4]: CMPDN2, CMRST2 */ #if (!FPGA) // Jason TODO remove unsigned long* pCAMIODrvCtl; if(mpCAMIODrvRegAddr != NULL) { pCAMIODrvCtl = mpCAMIODrvRegAddr + (0x060/4); *(pCAMIODrvCtl) &= 0xFFFFFFCF; switch(ioDrivingCurrent) { case 0x00: //2mA *(pCAMIODrvCtl) |= 0x00; break; case 0x20: //4mA *(pCAMIODrvCtl) |= 0x10; break; case 0x40: //6mA *(pCAMIODrvCtl) |= 0x20; break; case 0x60: //8mA *(pCAMIODrvCtl) |= 0x30; break; default: //4mA *(pCAMIODrvCtl) |= 0x10; break; } } LOG_MSG("[setIODrivingCurrent]:%d 0x%08x\n", (int) ioDrivingCurrent, (int) (*(pCAMIODrvCtl))); #endif return 0; } /******************************************************************************* * ********************************************************************************/ int SeninfDrv::setTg1MCLKEn(bool isEn) { int ret = 0; seninf_reg_t *pSeninf = (seninf_reg_t *)mpSeninfHwRegAddr; SENINF_WRITE_BITS(pSeninf, SENINF_TG1_PH_CNT, ADCLK_EN, isEn); return ret; } /******************************************************************************* * ********************************************************************************/ unsigned int SeninfDrv::getRegAddr(void) { LOG_MSG("mpSeninfHwRegAddr(0x%08X)",(unsigned int)mpSeninfHwRegAddr); // if(mpSeninfHwRegAddr != NULL) { return (unsigned int)mpSeninfHwRegAddr; } else { return 0; } } #if 0 // Jason TODO remove // /******************************************************************************* * ********************************************************************************/ int SeninfDrv::setFlashA(unsigned long endFrame, unsigned long startPoint, unsigned long lineUnit, unsigned long unitCount, unsigned long startLine, unsigned long startPixel, unsigned long flashPol) { int ret = 0; isp_reg_t *pisp = (isp_reg_t *) mpIspHwRegAddr; ISP_WRITE_BITS(pisp, CAM_TG_FLASHA_CTL, FLASHA_EN, 0x0); ISP_WRITE_BITS(pisp, CAM_TG_FLASHA_CTL, FLASH_POL, flashPol); ISP_WRITE_BITS(pisp, CAM_TG_FLASHA_CTL, FLASHA_END_FRM, endFrame); ISP_WRITE_BITS(pisp, CAM_TG_FLASHA_CTL, FLASHA_STARTPNT, startPoint); ISP_WRITE_BITS(pisp, CAM_TG_FLASHA_LINE_CNT, FLASHA_LUNIT_NO, unitCount); ISP_WRITE_BITS(pisp, CAM_TG_FLASHA_LINE_CNT, FLASHA_LUNIT, lineUnit); ISP_WRITE_BITS(pisp, CAM_TG_FLASHA_POS, FLASHA_PXL, startPixel); ISP_WRITE_BITS(pisp, CAM_TG_FLASHA_POS, FLASHA_LINE, startLine); ISP_WRITE_BITS(pisp, CAM_TG_FLASHA_CTL, FLASHA_EN, 0x1); return ret; } int SeninfDrv::setFlashB(unsigned long contiFrm, unsigned long startFrame, unsigned long lineUnit, unsigned long unitCount, unsigned long startLine, unsigned long startPixel) { int ret = 0; isp_reg_t *pisp = (isp_reg_t *) mpIspHwRegAddr; ISP_WRITE_BITS(pisp, CAM_TG_FLASHB_CTL, FLASHB_EN, 0x0); ISP_WRITE_BITS(pisp, CAM_TG_FLASHB_CTL, FLASHB_CONT_FRM, contiFrm); ISP_WRITE_BITS(pisp, CAM_TG_FLASHB_CTL, FLASHB_START_FRM, startFrame); ISP_WRITE_BITS(pisp, CAM_TG_FLASHB_CTL, FLASHB_STARTPNT, 0x0); ISP_WRITE_BITS(pisp, CAM_TG_FLASHB_CTL, FLASHB_TRIG_SRC, 0x0); ISP_WRITE_BITS(pisp, CAM_TG_FLASHB_LINE_CNT, FLASHB_LUNIT_NO, unitCount); ISP_WRITE_BITS(pisp, CAM_TG_FLASHB_LINE_CNT, FLASHB_LUNIT, lineUnit); ISP_WRITE_BITS(pisp, CAM_TG_FLASHB_POS, FLASHB_PXL, startPixel); ISP_WRITE_BITS(pisp, CAM_TG_FLASHB_POS, FLASHB_LINE, startLine); ISP_WRITE_BITS(pisp, CAM_TG_FLASHB_CTL, FLASHB_EN, 0x1); return ret; } int SeninfDrv::setFlashEn(bool flashEn) { int ret = 0; isp_reg_t *pisp = (isp_reg_t *) mpIspHwRegAddr; ISP_WRITE_BITS(pisp, CAM_TG_FLASHA_CTL, FLASH_EN, flashEn); return ret; } int SeninfDrv::setCCIR656Cfg(CCIR656_OUTPUT_POLARITY_ENUM vsPol, CCIR656_OUTPUT_POLARITY_ENUM hsPol, unsigned long hsStart, unsigned long hsEnd) { int ret = 0; seninf_reg_t *pSeninf = (seninf_reg_t *)mpSeninfHwRegAddr; if ((hsStart > 4095) || (hsEnd > 4095)) { LOG_ERR("CCIR656 HSTART or HEND value err \n"); ret = -1; } SENINF_WRITE_BITS(pSeninf, CCIR656_CTL, CCIR656_VS_POL, vsPol); SENINF_WRITE_BITS(pSeninf, CCIR656_CTL, CCIR656_HS_POL, hsPol); SENINF_WRITE_BITS(pSeninf, CCIR656_H, CCIR656_HS_END, hsEnd); SENINF_WRITE_BITS(pSeninf, CCIR656_H, CCIR656_HS_START, hsStart); return ret; } #endif #if (FPGA) // Jason TODO remove int SeninfDrv::setPdnRst(int camera, bool on) { int tgsel; int ret = 0; //MINT32 imgsys_cg_clr0 = 0x15000000; //MINT32 gpio_base_addr = 0x10001000; // mmap seninf clear gating reg mpCAMMMSYSRegAddr = (unsigned long *) mmap(0, CAM_MMSYS_CONFIG_RANGE, (PROT_READ|PROT_WRITE|PROT_NOCACHE), MAP_SHARED, mfd, CAM_MMSYS_CONFIG_BASE); if (mpCAMMMSYSRegAddr == MAP_FAILED) { LOG_ERR("mmap err(3), %d, %s \n", errno, strerror(errno)); return -7; } *(mpCAMMMSYSRegAddr + (0x8/4)) |= 0x03FF; //clear gate #if (!JASON_TMP) /* // mmap gpio reg mpGpioHwRegAddr = (unsigned long *) mmap(0, CAM_GPIO_RANGE, (PROT_READ | PROT_WRITE), MAP_SHARED, mfd, CAM_GPIO_BASE); if (mpGpioHwRegAddr == MAP_FAILED) { LOG_ERR("mmap err(1), %d, %s \n", errno, strerror(errno)); return -1; } // Jason TODO GPIO api // set RST/PDN/RST1/PDN1(gpio_142, 143, 89, 90) *(mpGpioHwRegAddr + (0xE84/4)) |= 0x000F; *(mpGpioHwRegAddr + (0xE88/4)) &= 0xFFF0; switch(camera) { case 1: tgsel = 0; break; case 2: tgsel = 1; break; default: tgsel = 0; break; } LOG_MSG("camera = %d tgsel = %d, On = %d \n",camera, tgsel,on); // Jason TODO GPIO api // set RST/PDN/RST1/PDN1(gpio_142, 143, 89, 90) if (0 == tgsel){//Tg1 if(1 == on){ *(mpGpioHwRegAddr + (0xE88/4)) &= 0xFFFD; *(mpGpioHwRegAddr + (0xE88/4)) |= 0x0001; } else { *(mpGpioHwRegAddr + (0xE88/4)) &= 0xFFFE; *(mpGpioHwRegAddr + (0xE88/4)) |= 0x0002; } } else { if(1 == on){ *(mpGpioHwRegAddr + (0xE88/4)) &= 0xFFF7; *(mpGpioHwRegAddr + (0xE88/4)) |= 0x0004; } else { *(mpGpioHwRegAddr + (0xE88/4)) &= 0xFFFB; *(mpGpioHwRegAddr + (0xE88/4)) |= 0x0008; } } */ #else seninf_reg_t *pSeninf = (seninf_reg_t *)mpSeninfHwRegAddr; if(1 == on) { SENINF_WRITE_BITS(pSeninf, SENINF_TG1_PH_CNT, EXT_PWRDN, 0); SENINF_WRITE_BITS(pSeninf, SENINF_TG1_PH_CNT, EXT_RST, 0); //#if defined(OV5642_YUV) SENINF_WRITE_BITS(pSeninf, SENINF_TG1_PH_CNT, EXT_PWRDN, 0); SENINF_WRITE_BITS(pSeninf, SENINF_TG1_PH_CNT, EXT_RST, 1); //#if defined(S5K4ECGX_MIPI_YUV) /* SENINF_WRITE_BITS(pSeninf, SENINF_TG1_PH_CNT, EXT_PWRDN, 1); { int i = 100; while(i--); } SENINF_WRITE_BITS(pSeninf, SENINF_TG1_PH_CNT, EXT_RST, 1); */ //#else //#error //#endif } else { //#if defined(OV5642_YUV) SENINF_WRITE_BITS(pSeninf, SENINF_TG1_PH_CNT, EXT_PWRDN, 1); SENINF_WRITE_BITS(pSeninf, SENINF_TG1_PH_CNT, EXT_RST, 0); //#if defined(S5K4ECGX_MIPI_YUV) //SENINF_WRITE_BITS(pSeninf, SENINF_TG1_PH_CNT, EXT_PWRDN, 0); //SENINF_WRITE_BITS(pSeninf, SENINF_TG1_PH_CNT, EXT_RST, 0); //#else //#error //#endif } LOG_WRN("SENINF_TG1_PH_CNT: 0x%08x", SENINF_READ_REG(pSeninf, SENINF_TG1_PH_CNT)); #endif //seninf_reg_t *pSeninf = (seninf_reg_t *)mpSeninfHwRegAddr; //LOG_WRN("SENINF_TG1_PH_CNT: 0x%08x", SENINF_READ_REG(pSeninf, SENINF_TG1_PH_CNT)); return ret; } #endif #if 0 // Jason TODO remove int SeninfDrv::setN3DCfg(unsigned long n3dEn, unsigned long i2c1En, unsigned long i2c2En, unsigned long n3dMode) { int ret = 0; seninf_reg_t *pSeninf = (seninf_reg_t *)mpSeninfHwRegAddr; SENINF_WRITE_BITS(pSeninf, N3D_CTL, N3D_EN, n3dEn); SENINF_WRITE_BITS(pSeninf, N3D_CTL, I2C1_EN, i2c1En); SENINF_WRITE_BITS(pSeninf, N3D_CTL, I2C2_EN, i2c2En); SENINF_WRITE_BITS(pSeninf, N3D_CTL, MODE, n3dMode); return ret; } int SeninfDrv::setN3DI2CPos(unsigned long n3dPos) { int ret = 0; seninf_reg_t *pSeninf = (seninf_reg_t *)mpSeninfHwRegAddr; SENINF_WRITE_BITS(pSeninf, N3D_POS, N3D_POS, n3dPos); return ret; } int SeninfDrv::setN3DTrigger(bool i2c1TrigOn, bool i2c2TrigOn) { int ret = 0; seninf_reg_t *pSeninf = (seninf_reg_t *)mpSeninfHwRegAddr; SENINF_WRITE_BITS(pSeninf, N3D_TRIG, I2CA_TRIG, i2c1TrigOn); SENINF_WRITE_BITS(pSeninf, N3D_TRIG, I2CB_TRIG, i2c2TrigOn); return ret; } #endif
[ "a1ba.omarov@gmail.com" ]
a1ba.omarov@gmail.com
ef32842cc2669361f5e84644d83df1e91f4fe983
722a65cee792297fabfea6edad74638224304b94
/chapter4/bankCharges/BankCharges/main.cpp
50606aca50edf5a3361a34e1e12e03802518aaf2
[]
no_license
brianlobo/MDC_C_PlusPlus
47f4cc839c4ad8b487a1f2a20c6627c7b5f20fbc
5f4de284bfcac8e8ddd5ea000aa66a51da911ae9
refs/heads/master
2020-04-24T17:28:50.479703
2019-04-18T13:10:52
2019-04-18T13:10:52
172,148,801
0
0
null
null
null
null
UTF-8
C++
false
false
2,652
cpp
// 14. // Bank Charges // // A bank charges $10 per month plus the following check fees for a commercial checking account: // $.10 each for fewer than 20 checks // $.08 each for 20–39 checks // $.06 each for 40–59 checks // $.04 each for 60 or more checks // // The bank also charges an extra $15 if the balance of the account falls below $400 (before // any check fees are applied). Write a program that asks for the beginning balance and the // number of checks written. Compute and display the bank’s service fees for the month. // // Input Validation: Do not accept a negative value for the number of checks written. If a // negative value is given for the beginning balance, display an urgent message indicating // the account is overdrawn. #include <iostream> #include <iomanip> using namespace std; int main() { const float MONTHLY_FEE = 10.00, BELOW_400_FEE = 15.00; float balance, costPerCheck, checkFee, total; int checksUsed; int below400 = 0; // Flag to indicate if balance is below 400 total = 0.00; // Gets # of checks used and validates the vlaue cout << "Enter number of checks used this month: "; cin >> checksUsed; if (checksUsed < 0) { cout << "\nERROR: can't have negative checks used.\n\n"; return 0; } // Gets bank balance and validates the value cout << "Enter bank balance: "; cin >> balance; if (balance < 0) cout << "\nATTENTION: Account Overdrawn!"; // Checks if balance is < 400 for the fee if (balance < 400) { total += BELOW_400_FEE; below400 = 1; } if (checksUsed >= 60) costPerCheck = .04; else if (checksUsed >= 40) costPerCheck = .06; else if (checksUsed >= 20) costPerCheck = .08; else costPerCheck = .1; checkFee = checksUsed * costPerCheck; total += MONTHLY_FEE + checkFee; cout << "\n"; cout << "--------------------------------\n"; cout << setw(25) << left << "Monthly Fee: " << "$" << setw(6) << right << setprecision(2) << fixed << MONTHLY_FEE << endl; cout << setw(25) << left << "Check Fee: " << "$" << setw(6) << right << checkFee << endl; if (below400) cout << setw(25) << left << "Account under $400: " << "$" << setw(6) << right << BELOW_400_FEE << endl; cout << "================================\n"; cout << setw(25) << left << "Total: " << "$" << setw(6) << right << total << endl; cout << "--------------------------------\n\n"; return 0; }
[ "brianlobo.code@gmail.com" ]
brianlobo.code@gmail.com
275d3488e1baea8c3d12cca11bd82b5ee4731a19
76504592b6fbf5a59c3f354692f5f5821f2c7941
/itkWeightedVotingFusionImageFilter.h
a3e94dfc2f090d50297a6a3b5c797dc4000519a3
[]
no_license
yuankaihuo/haha4D
19ebd91d83c5393db68d23590d281187113b450b
95b49c11dc83633aea63024e86a157d9d096093b
refs/heads/master
2020-09-19T23:56:58.733125
2016-12-07T04:09:09
2016-12-07T04:09:09
73,513,413
0
0
null
null
null
null
UTF-8
C++
false
false
16,193
h
/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef __itkWeightedVotingFusionImageFilter_h #define __itkWeightedVotingFusionImageFilter_h #include "itkImageToImageFilter.h" #include "itkConstNeighborhoodIterator.h" #include <vnl/vnl_matrix.h> #include <vnl/vnl_vector.h> #include <vector> #include <map> #include <set> namespace itk { /** \class WeightedVotingFusionImageFilter * \brief Implementation of the joint label fusion and joint intensity fusion algorithm * * \author Paul Yushkevich with modifications by Brian Avants and Nick Tustison * * \par REFERENCE * * H. Wang, J. W. Suh, S. Das, J. Pluta, C. Craige, P. Yushkevich, * "Multi-atlas segmentation with joint label fusion," IEEE Trans. * on Pattern Analysis and Machine Intelligence, 35(3), 611-623, 2013. * * H. Wang and P. A. Yushkevich, "Multi-atlas segmentation with joint * label fusion and corrective learning--an open source implementation," * Front. Neuroinform., 2013. * * \ingroup ImageSegmentation */ template <class TInputImage, class TOutputImage> class WeightedVotingFusionImageFilter : public ImageToImageFilter<TInputImage, TOutputImage> { public: /** Standard class typedefs. */ typedef WeightedVotingFusionImageFilter Self; typedef ImageToImageFilter<TInputImage, TOutputImage> Superclass; typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods). */ itkTypeMacro( WeightedVotingFusionImageFilter, ImageToImageFilter ); itkNewMacro( Self ); /** ImageDimension constants */ itkStaticConstMacro( ImageDimension, unsigned int, TInputImage::ImageDimension ); /** Some convenient typedefs. */ typedef TInputImage InputImageType; typedef typename InputImageType::Pointer InputImagePointer; typedef typename InputImageType::ConstPointer InputImageConstPointer; typedef typename InputImageType::PixelType InputImagePixelType; typedef std::vector<InputImagePointer> InputImageList; typedef std::vector<InputImageList> InputImageSetList; typedef std::vector<InputImagePixelType> InputImagePixelVectorType; typedef std::vector<std::vector<InputImagePixelType> > InputImagePixelVectorType2D; typedef TOutputImage OutputImageType; typedef typename OutputImageType::PixelType LabelType; typedef std::set<LabelType> LabelSetType; typedef Image<LabelType, ImageDimension> LabelImageType; typedef typename LabelImageType::Pointer LabelImagePointer; typedef std::vector<LabelImagePointer> LabelImageList; typedef Image<unsigned int, ImageDimension> CountImageType; typedef LabelImageType MaskImageType; typedef typename MaskImageType::Pointer MaskImagePointer; typedef typename InputImageType::RegionType RegionType; typedef typename InputImageType::SizeType SizeType; typedef typename InputImageType::IndexType IndexType; typedef Image<float, ImageDimension> ProbabilityImageType; typedef typename ProbabilityImageType::Pointer ProbabilityImagePointer; typedef double RealType; typedef std::vector<double> RealType2D; typedef std::vector<int> OffsetList; typedef vnl_matrix<RealType> MatrixType; typedef vnl_vector<RealType> VectorType; typedef std::map<LabelType, ProbabilityImagePointer> LabelPosteriorProbabilityMap; typedef std::map<LabelType, LabelImagePointer> LabelExclusionMap; typedef std::vector<ProbabilityImagePointer> VotingWeightImageList; typedef ConstNeighborhoodIterator<InputImageType> ConstNeighborhoodIteratorType; typedef typename ConstNeighborhoodIteratorType::RadiusType NeighborhoodRadiusType; typedef typename ConstNeighborhoodIteratorType::OffsetType NeighborhoodOffsetType; typedef typename SizeType::SizeValueType RadiusValueType; typedef Image<RadiusValueType, ImageDimension> RadiusImageType; typedef typename RadiusImageType::Pointer RadiusImagePointer; /** * Neighborhood patch similarity metric enumerated type */ enum SimilarityMetricType { PEARSON_CORRELATION, MEAN_SQUARES }; /** * Set the multimodal target image */ void SetTargetImage( InputImageList imageList ) { this->m_TargetImage = imageList; this->UpdateInputs(); } /** * Add an atlas (multi-modal image + segmentation) */ void AddAtlas( InputImageList imageList, LabelImageType *segmentation = ITK_NULLPTR ) { for( unsigned int i = 0; i < imageList.size(); i++ ) { this->m_AtlasImages.push_back( imageList ); } if( this->m_NumberOfAtlasModalities == 0 ) { itkDebugMacro( "Setting the number of modalities to " << this->m_NumberOfAtlasModalities ); this->m_NumberOfAtlasModalities = imageList.size(); } else if( this->m_NumberOfAtlasModalities != imageList.size() ) { itkExceptionMacro( "The number of atlas multimodal images is not equal to " << this->m_NumberOfAtlasModalities ); } this->m_NumberOfAtlases++; if( segmentation != ITK_NULLPTR ) { this->m_AtlasSegmentations.push_back( segmentation ); this->m_NumberOfAtlasSegmentations++; } this->UpdateInputs(); } /** * Set mask image function. If a binary mask image is specified, only * those input image voxels corresponding with mask image values equal * to one are used. */ void SetMaskImage( MaskImageType *mask ) { this->m_MaskImage = mask; this->UpdateInputs(); } /** * Add a label exclusion map */ void AddLabelExclusionImage( LabelType label, LabelImageType *exclusionImage ) { this->m_LabelExclusionImages[label] = exclusionImage; this->UpdateInputs(); } /** * Get the number of modalities used in determining the optimal label fusion * or optimal fused image. */ itkGetConstMacro( NumberOfAtlasModalities, unsigned int ); /** * Get the label set. */ itkGetConstMacro( LabelSet, LabelSetType ); /** * Set/Get the local search neighborhood for minimizing potential registration error. * Default = 3x3x3. */ itkSetMacro( SearchNeighborhoodRadius, NeighborhoodRadiusType ); itkGetConstMacro( SearchNeighborhoodRadius, NeighborhoodRadiusType ); /** * Set/Get the local search neighborhood radius image. */ void SetSearchNeighborhoodRadiusImage( RadiusImageType *image ) { this->m_SearchNeighborhoodRadiusImage = image; } /** * Set/Get the patch neighborhood for calculating the similarity measures. * Default = 2x2x2. */ itkSetMacro( PatchNeighborhoodRadius, NeighborhoodRadiusType ); itkGetConstMacro( PatchNeighborhoodRadius, NeighborhoodRadiusType ); /** * Set/Get the Alpha parameter---the regularization weight added to the matrix Mx for * the inverse. Default = 0.1. */ itkSetMacro( Alpha, RealType ); itkGetConstMacro( Alpha, RealType ); /** * Set/Get the Beta parameter---exponent for mapping intensity difference to joint error. * Default = 2.0. */ itkSetMacro( Beta, RealType ); itkGetConstMacro( Beta, RealType ); /** * Set/Get the timePoints parameter---how many time points for the target * the inverse. Default = 1. */ itkSetMacro(timePoints, unsigned int); itkGetConstMacro(timePoints, unsigned int); /** Set the requested region */ void GenerateInputRequestedRegion() ITK_OVERRIDE; /** * Boolean for retaining the posterior images. This can have a negative effect * on memory use, so it should only be done if one wishes to save the posterior * maps. The posterior maps (n = number of labels) give the probability of each * voxel in the target image belonging to each label. Default = false. */ itkSetMacro( RetainLabelPosteriorProbabilityImages, bool ); itkGetConstMacro( RetainLabelPosteriorProbabilityImages, bool ); itkBooleanMacro( RetainLabelPosteriorProbabilityImages ); /** * Boolean for retaining the voting weights images. This can have a negative effect * on memory use, so it should only be done if one wishes to save the voting weight * maps. The voting weight maps (n = number of atlases) gives the contribution of * a particular atlas to the final label/intensity fusion. */ itkSetMacro( RetainAtlasVotingWeightImages, bool ); itkGetConstMacro( RetainAtlasVotingWeightImages, bool ); itkBooleanMacro( RetainAtlasVotingWeightImages ); /** * Boolean for constraining the weights to be positive and sum to 1. We use * an implementation of the algorithm based on the algorithm by Lawson, Charles L.; * Hanson, Richard J. (1995). Solving Least Squares Problems. SIAM. */ itkSetMacro( ConstrainSolutionToNonnegativeWeights, bool ); itkGetConstMacro( ConstrainSolutionToNonnegativeWeights, bool ); itkBooleanMacro( ConstrainSolutionToNonnegativeWeights ); /** * Measurement of neighborhood similarity. */ itkSetMacro( SimilarityMetric, SimilarityMetricType ); itkGetConstMacro( SimilarityMetric, SimilarityMetricType ); /** * Get the posterior probability image corresponding to a label. */ const ProbabilityImagePointer GetLabelPosteriorProbabilityImage( LabelType label ) { if( this->m_RetainLabelPosteriorProbabilityImages ) { if( std::find( this->m_LabelSet.begin(), this->m_LabelSet.end(), label ) != this->m_LabelSet.end() ) { return this->m_LabelPosteriorProbabilityImages[label]; } else { itkDebugMacro( "Not returning a label posterior probability image. Requested label not found." ); return ITK_NULLPTR; } } else { itkDebugMacro( "Not returning a label posterior probability image. These images were not saved." ); return ITK_NULLPTR; } } /** * Get the voting weight image corresponding to an atlas. */ const ProbabilityImagePointer GetAtlasVotingWeightImage( unsigned int n ) { if( this->m_RetainAtlasVotingWeightImages ) { if( n < this->m_NumberOfAtlases ) { return this->m_AtlasVotingWeightImages[n]; } else { itkDebugMacro( "Not returning a voting weight image. Requested index is greater than the number of atlases." ); return ITK_NULLPTR; } } else { itkDebugMacro( "Not returning a voting weight image. These images were not saved." ); return ITK_NULLPTR; } } /** * Get the joint intensity fusion output image */ const ProbabilityImagePointer GetJointIntensityFusionImage( unsigned int n ) { if( n < this->m_NumberOfAtlasModalities ) { return this->m_JointIntensityFusionImage[n]; } else { itkDebugMacro( "Not returning a joint intensity fusion image. Requested index is greater than the number of modalities." ); return ITK_NULLPTR; } } protected: WeightedVotingFusionImageFilter(); ~WeightedVotingFusionImageFilter() {} void PrintSelf( std::ostream& os, Indent indent ) const ITK_OVERRIDE; void ThreadedGenerateData( const RegionType &, ThreadIdType ) ITK_OVERRIDE; void BeforeThreadedGenerateData() ITK_OVERRIDE; void AfterThreadedGenerateData() ITK_OVERRIDE; void GenerateData() ITK_OVERRIDE; private: void ThreadedGenerateDataForWeightedAveraging( const RegionType &, ThreadIdType ); void ThreadedGenerateDataForReconstruction( const RegionType &, ThreadIdType ); RealType ComputeNeighborhoodPatchSimilarity( const InputImageList &, const IndexType, const InputImagePixelVectorType &, const bool ); InputImagePixelVectorType VectorizeImageListPatch( const InputImageList &, const IndexType, const bool ); InputImagePixelVectorType VectorizeImagePatch( const InputImagePointer, const IndexType, const bool ); void GetMeanAndStandardDeviationOfVectorizedImagePatch( const InputImagePixelVectorType &, RealType &, RealType & ); VectorType NonNegativeLeastSquares( const MatrixType, const VectorType, const RealType ); void UpdateInputs(); typedef std::pair<unsigned int, RealType> DistanceIndexType; typedef std::vector<DistanceIndexType> DistanceIndexVectorType; struct DistanceIndexComparator { bool operator () ( const DistanceIndexType& left, const DistanceIndexType& right ) { return left.second < right.second; } }; bool m_IsWeightedAveragingComplete; /** Input variables */ InputImageList m_TargetImage; InputImageSetList m_AtlasImages; LabelImageList m_AtlasSegmentations; LabelExclusionMap m_LabelExclusionImages; MaskImagePointer m_MaskImage; RegionType m_TargetImageRequestedRegion; typename CountImageType::Pointer m_CountImage; LabelSetType m_LabelSet; SizeValueType m_NumberOfAtlases; SizeValueType m_NumberOfAtlasSegmentations; SizeValueType m_NumberOfAtlasModalities; NeighborhoodRadiusType m_SearchNeighborhoodRadius; NeighborhoodRadiusType m_PatchNeighborhoodRadius; SizeValueType m_PatchNeighborhoodSize; std::vector<NeighborhoodOffsetType> m_SearchNeighborhoodOffsetList; std::map<RadiusValueType, std::vector<NeighborhoodOffsetType> > m_SearchNeighborhoodOffsetSetsMap; std::vector<NeighborhoodOffsetType> m_PatchNeighborhoodOffsetList; RealType m_Alpha; RealType m_Beta; unsigned int m_timePoints; bool m_RetainLabelPosteriorProbabilityImages; bool m_RetainAtlasVotingWeightImages; bool m_ConstrainSolutionToNonnegativeWeights; SimilarityMetricType m_SimilarityMetric; ProbabilityImagePointer m_WeightSumImage; RadiusImagePointer m_SearchNeighborhoodRadiusImage; /** Output variables */ LabelPosteriorProbabilityMap m_LabelPosteriorProbabilityImages; VotingWeightImageList m_AtlasVotingWeightImages; InputImageList m_JointIntensityFusionImage; }; } // namespace itk #ifndef ITK_MANUAL_INSTANTIATION #include "itkWeightedVotingFusionImageFilter.hxx" #endif #endif
[ "huoyuankai@gmail.com" ]
huoyuankai@gmail.com
a5d51f9a1c1b66baeaba310afdd4114842fdae86
21553f6afd6b81ae8403549467230cdc378f32c9
/arm/cortex/Freescale/MK21D5/include/arch/reg/rfvbat.hpp
de5a09a51d9ac10f073b0d68140046ca8139669f
[]
no_license
digint/openmptl-reg-arm-cortex
3246b68dcb60d4f7c95a46423563cab68cb02b5e
88e105766edc9299348ccc8d2ff7a9c34cddacd3
refs/heads/master
2021-07-18T19:56:42.569685
2017-10-26T11:11:35
2017-10-26T11:11:35
108,407,162
3
1
null
null
null
null
UTF-8
C++
false
false
1,866
hpp
/* * OpenMPTL - C++ Microprocessor Template Library * * This program is a derivative representation of a CMSIS System View * Description (SVD) file, and is subject to the corresponding license * (see "Freescale CMSIS-SVD License Agreement.pdf" in the parent directory). * * 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. */ //////////////////////////////////////////////////////////////////////// // // Import from CMSIS-SVD: "Freescale/MK21D5.svd" // // vendor: Freescale Semiconductor, Inc. // vendorID: Freescale // name: MK21D5 // series: Kinetis_K // version: 1.6 // description: MK21D5 Freescale Microcontroller // -------------------------------------------------------------------- // // C++ Header file, containing architecture specific register // declarations for use in OpenMPTL. It has been converted directly // from a CMSIS-SVD file. // // https://digint.ch/openmptl // https://github.com/posborne/cmsis-svd // #ifndef ARCH_REG_RFVBAT_HPP_INCLUDED #define ARCH_REG_RFVBAT_HPP_INCLUDED #warning "using untested register declarations" #include <register.hpp> namespace mptl { /** * VBAT register file */ struct RFVBAT { static constexpr reg_addr_t base_addr = 0x4003e000; /** * VBAT register file register */ struct REG%s : public reg< uint32_t, base_addr + 0, rw, 0 > { using type = reg< uint32_t, base_addr + 0, rw, 0 >; using LL = regbits< type, 0, 8 >; /**< Low lower byte */ using LH = regbits< type, 8, 8 >; /**< Low higher byte */ using HL = regbits< type, 16, 8 >; /**< High lower byte */ using HH = regbits< type, 24, 8 >; /**< High higher byte */ }; }; } // namespace mptl #endif // ARCH_REG_RFVBAT_HPP_INCLUDED
[ "axel@tty0.ch" ]
axel@tty0.ch
276ae1a3c1ad51350f9c90f294fc116867558030
b5bb24596deb19b9114783fe44577009fdd1d296
/contrib/t38modem/tags/OriginalFromOpenH323/enginebase.h
705e2b2d5f59fda03833f6cdc44adff8f1f85665
[]
no_license
erdincay/opal-voip
0ca10d30105795272b505995309b2af5836d1079
7937e4df5833f48a273a9b3519de87c6bcdc5410
refs/heads/master
2020-05-17T18:41:42.371445
2015-09-10T17:38:14
2015-09-10T17:38:14
42,303,471
3
0
null
null
null
null
UTF-8
C++
false
false
2,118
h
/* * enginebase.h * * T38FAX Pseudo Modem * * Copyright (c) 2007 Vyacheslav Frolov * * Open H323 Project * * The contents of this file are subject to the Mozilla Public License * Version 1.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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See * the License for the specific language governing rights and limitations * under the License. * * The Original Code is Open H323 Library. * * The Initial Developer of the Original Code is Vyacheslav Frolov * * Contributor(s): * * $Log: enginebase.h,v $ * Revision 1.2 2007/04/09 08:07:12 vfrolov * Added symbolic logging ModemCallbackParam * * Revision 1.1 2007/03/23 09:54:45 vfrolov * Initial revision * * */ #ifndef _ENGINEBASE_H #define _ENGINEBASE_H /////////////////////////////////////////////////////////////// class EngineBase : public PObject { PCLASSINFO(EngineBase, PObject); public: EngineBase(const PString &_name = "") : name(_name) {} enum { diagOutOfOrder = 0x01, diagDiffSig = 0x04, // a different signal is detected diagBadFcs = 0x08, diagNoCarrier = 0x10, diagError = 0x80, // bad usage }; enum { dtNone, dtCed, dtCng, dtSilence, dtHdlc, dtRaw, }; enum ModemCallbackParam { cbpUserDataMask = 0xFF, cbpOutBufNoFull = 256, cbpReset = -1, cbpOutBufEmpty = -2, cbpUserInput = -3, }; #if PTRACING friend ostream & operator<<(ostream & o, ModemCallbackParam param); #endif /**@name Modem API */ //@{ BOOL TryLockModemCallback(); void UnlockModemCallback(); //@} protected: void ModemCallback(INT extra); PNotifier modemCallback; PTimedMutex MutexModemCallback; PMutex MutexModem; const PString name; }; /////////////////////////////////////////////////////////////// #endif // _ENGINEBASE_H
[ "csoutheren@023b2edf-31b2-4de3-b41e-bca80c47788f" ]
csoutheren@023b2edf-31b2-4de3-b41e-bca80c47788f
523d2e1f018aaeafa90f33870de25f631d4b7294
6204398c48ca7b4127c4f55202fa266bbc9be496
/Lesson15_Classes2/Source.cpp
49767a78733068cea669d0a2e27c0cb8e56d3afe
[]
no_license
aaviants/armath-edu2020
5a4d7ae907c86065d19c5d80561ad0232acfab38
fc67b6601f90d5ee3550f0dd087ec9af731377cf
refs/heads/main
2023-02-02T07:37:35.543374
2020-12-23T12:57:58
2020-12-23T12:57:58
307,345,986
0
0
null
null
null
null
UTF-8
C++
false
false
896
cpp
#include <iostream> #include "Vector.h" #include "Rectangle.h" void print(Vector v); int main() { int left(0); int top(0); int right(0); int bottom(0); Rect r1; //r1.setLeft(1); //r1.setTop(2); //r1.setRight(3); //r1.setBottom(4); r1.setCoordintes(1, 2, 3, 4); r1.print(); Rect r2(1, 2, 3, 4); r2.print(); r2.setWidth(10); int w = r2.getWidth(); r2.print(); Rect* arrRectangles = new Rect[10]; Rect* pointerToRect = new Rect(5, 6, 7, 8); (*pointerToRect).print(); pointerToRect->print(); delete pointerToRect; delete[] arrRectangles; if (false) { Vector v1; v1.setCoordinates(33, 44); v1.setX(10); v1.setX(20); print(v1); Vector v2(3.14, 2.71); print(v2); Vector v3(v2); Vector v4 = v2; } } void print(Vector v) { std::cout << "X=" << v.getX() << ", Y=" << v.getY() << ", L=" << v.getLength() << ", A=" << v.getAlpha() << std::endl; }
[ "ara.petrosyan@hotmail.com" ]
ara.petrosyan@hotmail.com
ac01af50c18419223bc3187de4d851db408806c9
8bb6d8ce77b9064da19fe3915a706904223f3f0a
/LeetCode/0066 - Plus One.cpp
32d73050b55d941cf9fbb2101f89a1577791898d
[]
no_license
wj32/Judge
8c92eb2c108839395bc902454030745b97ed7f29
d0bd7805c0d441c892c28a718470a378a38e7124
refs/heads/master
2023-08-16T19:16:59.475037
2023-08-02T03:46:12
2023-08-02T03:46:12
8,853,058
6
10
null
null
null
null
UTF-8
C++
false
false
477
cpp
class Solution { public: vector<int> plusOne(vector<int>& digits) { int carry = 1; for (int i = digits.size() - 1; i >= 0; i--) { digits[i] += carry; if (digits[i] >= 10) { digits[i] -= 10; carry = 1; } else { carry = 0; } } if (carry != 0) { digits.insert(digits.begin(), 1); } return digits; } };
[ "wj32.64@gmail.com" ]
wj32.64@gmail.com
d7df208547262f09b33644264f6bc1c230556f4f
419548555a78bf2357a8c3c1cf3aa5b3e9fb52e7
/General/Arrays.cpp
5c8105edabe4fac353c72159dc1de8f1330bee6b
[]
no_license
evan-delasota/301Prep
2c9072b5598df680fe71e50bd558b50dbf1a678e
5557545d5f2145f534e416d80b91ed957b682d19
refs/heads/master
2022-04-02T17:43:34.860286
2020-01-23T16:13:08
2020-01-23T16:13:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,919
cpp
#include <vector> #include <iostream> using namespace std; void swap(int*, int*); void bubbleSort(int[], int); void printArray(int[], int); int oddSum(int[], int); void combineArrayElements(int[], int, int[], int); const int arraySize = 10; int main2() { int arr[5]; int initArray[arraySize] = { 10, 23, 343, 1, 26 }; int oddNumbers; int size = (sizeof(arr) / sizeof(arr[0])); cout << "Initial Array: "; printArray(initArray, size); // User inputting values into an array cout << "Enter values for an array(5 max): "; for (int i = 0; i < size; ++i) { cin >> arr[i]; } cout << "Combining user input array into the initial array...\n"; combineArrayElements(initArray, arraySize, arr, size); cout << "Combined array: \n"; printArray(initArray, arraySize); cout << "Sorted: \n"; bubbleSort(initArray, arraySize); printArray(initArray, arraySize); // Returns number of odd numbers oddNumbers = oddSum(initArray, arraySize); cout << "\n This array's odd numbers equates to a total of " << oddNumbers << ".\n\n"; return 0; } void swap(int* x, int* y) { int temp = *x; *x = *y; *y = temp; } void bubbleSort(int arr[], int arrSize) { int i, j; for (i = 0; i < arrSize - 1; ++i) { for (j = 0; j < arrSize - i - 1; ++j) { if (arr[j] > arr[j + 1]) { swap(&arr[j], &arr[j + 1]); } } } } void printArray(int arr[], int arrSize) { cout << "["; for (int i = 0; i < arrSize; ++i) { if (i != arrSize - 1) { cout << arr[i] << ", "; continue; } cout << arr[i]; } cout << "]\n"; } int oddSum(int arr[], int arrSize) { int oddNumberTotal = 0; for (int i = 0; i < arrSize; ++i) { if (arr[i] % 2 == 0) { continue; } else { oddNumberTotal += arr[i]; } } return oddNumberTotal; } void combineArrayElements(int arrOne[], int arrOneSize, int arrTwo[], int arrTwoSize) { for (int i = 0; i < arrOneSize; ++i) { arrOne[i + arrTwoSize] = arrTwo[i]; } }
[ "evan.delasota@gmail.com" ]
evan.delasota@gmail.com
4fb932fcf876771cf2673b5387293ccc7c6c8d31
b1a9e8e726b608a06a17532224d376176b38ec3c
/Ejercicios/Proyecto/clientes.cpp
aadd9bb1970328d79f81a02f7e3a4ee2e5c13f88
[ "MIT" ]
permissive
MercyAle/cpp
a0c84b6e43e0832903b91ee0aaa8472f53941609
6e870e8061859ac84b7b6b8140d976fdc96dc89e
refs/heads/master
2022-12-20T02:38:36.846215
2020-10-08T06:14:13
2020-10-08T06:14:13
277,032,519
1
0
null
null
null
null
UTF-8
C++
false
false
927
cpp
#include <iostream> using namespace std; string arregloClientes[5][3] = { { "C001", "Juan Perez", "99-99-99-99"}, { "C002", "Jose Martinez", "99-88-88-88"}, { "C003", "Maria Gonzalez", "99-77-77-77" }, { "C004", "Pedro Hernandez", "99-66-66-66" }, { "C005", "Pablo Jimenez", "99-55-55-55" } }; void mostrarClientes() { system("cls"); cout << "Codigo, Nombre y Telefono" << endl; cout << "-------------------------" << endl << endl; for (int i = 0; i < 5; i++) { cout << arregloClientes[i][0] << " | "; cout << arregloClientes[i][1] << " | "; cout << arregloClientes[i][2] << " | "; cout << endl; } cout << endl; cout << endl; system("pause"); } string buscarCliente(string codigo) { for (int i = 0; i < 5; i++) { if (arregloClientes[i][0] == codigo) { return arregloClientes[i][1]; } } return ""; }
[ "Alejandra-paad@outlook.es" ]
Alejandra-paad@outlook.es
2160b505cdd8659586ba54275caddd847f61c26a
d276a9ad61586a050e861cdd48a82b7485809986
/source/webkit-2.2.8/Source/WebKit2/UIProcess/Launcher/gtk/ProcessLauncherGtk.cpp
f4ae218bf7fa8144b8b02177a387aa79fe43c9f2
[]
no_license
onecoolx/davinci
1ccea6487ec8254c520514e5a8df826fa6b08398
090696c6a957d3fc0cca867530cb3eece5fb870c
refs/heads/master
2023-06-27T10:20:41.161195
2023-06-12T12:06:37
2023-06-12T12:06:37
28,557,969
10
4
null
null
null
null
UTF-8
C++
false
false
4,068
cpp
/* * Copyright (C) 2010 Apple Inc. All rights reserved. * Portions Copyright (c) 2010 Motorola Mobility, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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 MOTOROLA INC. AND ITS 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 MOTOROLA INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "ProcessLauncher.h" #include "Connection.h" #include "ProcessExecutablePath.h" #include <WebCore/AuthenticationChallenge.h> #include <WebCore/FileSystem.h> #include <WebCore/NetworkingContext.h> #include <WebCore/ResourceHandle.h> #include <WebCore/RunLoop.h> #include <errno.h> #include <glib.h> #include <locale.h> #include <wtf/text/CString.h> #include <wtf/text/WTFString.h> #include <wtf/gobject/GOwnPtr.h> #include <wtf/gobject/GlibUtilities.h> #if OS(UNIX) #include <sys/socket.h> #endif #ifdef SOCK_SEQPACKET #define SOCKET_TYPE SOCK_SEQPACKET #else #define SOCKET_TYPE SOCK_STREAM #endif using namespace WebCore; namespace WebKit { static void childSetupFunction(gpointer userData) { int socket = GPOINTER_TO_INT(userData); close(socket); } void ProcessLauncher::launchProcess() { GPid pid = 0; int sockets[2]; if (socketpair(AF_UNIX, SOCKET_TYPE, 0, sockets) < 0) { g_printerr("Creation of socket failed: %s.\n", g_strerror(errno)); ASSERT_NOT_REACHED(); return; } String executablePath, pluginPath; CString realExecutablePath, realPluginPath; if (m_launchOptions.processType == WebProcess) executablePath = executablePathOfWebProcess(); else { executablePath = executablePathOfPluginProcess(); pluginPath = m_launchOptions.extraInitializationData.get("plugin-path"); realPluginPath = fileSystemRepresentation(pluginPath); } realExecutablePath = fileSystemRepresentation(executablePath); GOwnPtr<gchar> socket(g_strdup_printf("%d", sockets[0])); char* argv[4]; argv[0] = const_cast<char*>(realExecutablePath.data()); argv[1] = socket.get(); argv[2] = const_cast<char*>(realPluginPath.data()); argv[3] = 0; GOwnPtr<GError> error; if (!g_spawn_async(0, argv, 0, G_SPAWN_LEAVE_DESCRIPTORS_OPEN, childSetupFunction, GINT_TO_POINTER(sockets[1]), &pid, &error.outPtr())) { g_printerr("Unable to fork a new WebProcess: %s.\n", error->message); ASSERT_NOT_REACHED(); } close(sockets[0]); m_processIdentifier = pid; // We've finished launching the process, message back to the main run loop. RunLoop::main()->dispatch(bind(&ProcessLauncher::didFinishLaunchingProcess, this, m_processIdentifier, sockets[1])); } void ProcessLauncher::terminateProcess() { if (m_isLaunching) { invalidate(); return; } if (!m_processIdentifier) return; kill(m_processIdentifier, SIGKILL); m_processIdentifier = 0; } void ProcessLauncher::platformInvalidate() { } } // namespace WebKit
[ "onecoolx@gmail.com" ]
onecoolx@gmail.com
1544d7d5ebb70f27b138f1ab29c4722899518c34
a8804f93227e46fd41ac9c6c4ba7e91ee5bf6a93
/uva/11284/sol.cpp
45c04603635ac5c1142b5aa9a657c3dab7a7f647
[]
no_license
caioaao/cp-solutions
9a2b3552a09fbc22ee8c3494d54ca1e7de7269a9
8a2941a394cf09913f9cae85ae7aedfafe76a43e
refs/heads/master
2021-01-17T10:22:27.607305
2020-07-04T15:37:01
2020-07-04T15:37:01
35,003,033
0
0
null
null
null
null
UTF-8
C++
false
false
2,775
cpp
#include <bits/stdc++.h> #define ff first #define ss second #define pb push_back #define sz size #define ms(x,v) memset((x), (v), sizeof(x)) #define _NO_USE_LOG #ifdef _USE_LOG #define LOG(x) cout << x; #else #define LOG(x) #endif #define MAXN 60 #define MAXP 12 #define EPS 1e-8 #define INF 1e8 using namespace std; typedef long long L; typedef pair<L,L> PL; typedef vector<L> VL; typedef vector<VL> VVL; typedef vector<PL> VPL; typedef vector<VPL>VVPL; int n, p, t; int adj_mat[MAXN][MAXN]; int saves[MAXP]; int store_bm[MAXN]; int opera_store[MAXN]; L dist[MAXN][1 << MAXP]; int vis[MAXN][1 << MAXP]; L dp(int u, int bm_) { int bm = bm_ & ~store_bm[u]; if(vis[u][bm] < t) { vis[u][bm] = t; if(bm == 0) dist[u][bm] = adj_mat[u][0]; else { dist[u][bm] = INF; for(int i = 0; i < p; ++i) { if(bm & (1 << i)) { dist[u][bm] = min(dist[u][bm], adj_mat[u][opera_store[i]] + dp(opera_store[i], bm)); } } } } return dist[u][bm]; } L saving[(1 << MAXP)]; inline void precsaving() { for(int bm = 0; bm < (1 << p); ++bm) { saving[bm] = 0; for(int i = 0; i < p; ++i) { saving[bm] += (!!(bm & (1 << i))) * saves[i]; } } } void fw() { for(int k = 0; k < n; ++k) for(int i = 0; i < n; ++i) for(int j = 0; j < n; ++j) adj_mat[i][j] = min(adj_mat[i][k] + adj_mat[k][j], adj_mat[i][j]); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); ms(vis, -1); int tsts; int m; cin >> tsts; for(t = 0; t < tsts; ++t) { cin >> n >> m; ++n; for(int i = 0; i < n; ++i) for(int j = 0; j < n; ++j) adj_mat[i][j] = INF; while(m--){ int a, b; cin >> a >> b; double c_; cin >> c_; int c = 100*(c_ + EPS); if(adj_mat[a][b] > c) { adj_mat[a][b] = adj_mat[b][a] = c; } } fw(); cin >> p; ms(store_bm, 0); for(int i = 0; i < p; ++i) { cin >> opera_store[i]; store_bm[opera_store[i]] |= (1 << i); double c_; cin >> c_; saves[i] = 100 * (c_ + EPS); } precsaving(); L bst = 0; for(int i = 0; i < (1 << p); ++i) { LOG(bitset<14>(i) << ':' << dist[0][i] << '\n'); bst = max(bst, saving[i] - dp(0, i)); } if(bst == 0) cout << "Don't leave the house\n"; else cout << "Daniel can save $" << fixed << setprecision(2) << (bst/100.) << '\n'; } }
[ "caioaao@gmail.com" ]
caioaao@gmail.com
152048819cd97b12e4b24f36821000c22fd02c17
1a56f86df0dd925b858185dc21a189917bfb4806
/videoplayer4.8/videowidget.cpp
a924295c413c49e463945ae62caaf2875dff698a
[]
no_license
yumechua/ivp
6c9dcb5cbe141dd362800ccd3b60f12e30150345
769b1fe635a36848e334400a3c34db31cf29765d
refs/heads/master
2020-04-07T15:44:13.710021
2013-03-29T04:24:06
2013-03-29T04:24:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,408
cpp
#include "videowidget.h" #include "videowidgetsurface.h" #include <QtMultimedia> VideoWidget::VideoWidget(QWidget *parent) : QWidget(parent) , surface(0) { setAutoFillBackground(false); setAttribute(Qt::WA_NoSystemBackground, true); setAttribute(Qt::WA_PaintOnScreen, true); QPalette palette = this->palette(); palette.setColor(QPalette::Background, Qt::black); setPalette(palette); setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); surface = new VideoWidgetSurface(this); } VideoWidget::~VideoWidget() { delete surface; } QSize VideoWidget::sizeHint() const { return surface->surfaceFormat().sizeHint(); } void VideoWidget::paintEvent(QPaintEvent *event) { QPainter painter(this); if (surface->isActive()) { const QRect videoRect = surface->videoRect(); if (!videoRect.contains(event->rect())) { QRegion region = event->region(); region.subtract(videoRect); QBrush brush = palette().background(); foreach (const QRect &rect, region.rects()) painter.fillRect(rect, brush); } surface->paint(&painter); } else { painter.fillRect(event->rect(), palette().background()); } } void VideoWidget::resizeEvent(QResizeEvent *event) { QWidget::resizeEvent(event); surface->updateVideoRect(); }
[ "saluka@r-52-176-28-172.comp.nus.edu.sg" ]
saluka@r-52-176-28-172.comp.nus.edu.sg
69205d52a955302f4f9e9c55add14f14f48031c7
0fed3d6c4a6dbdb49029913b6ce96a9ede9eac6c
/HDOJ/1698.cpp
10f75e4e39a48271615b9974a64ab0610e1d1601
[]
no_license
87ouo/The-road-to-ACMer
72df2e834027dcfab04b02ba0ddd350e5078dfc0
0a39a9708a0e7fd0e3b2ffff5d1f4a793b031df5
refs/heads/master
2021-02-18T17:44:29.937434
2019-07-31T11:30:27
2019-07-31T11:30:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,165
cpp
// Just a Hook, HDU1698 /*Sample Input 1 10 2 1 5 2 5 9 3 */ #include <bits/stdc++.h> using namespace std; #define Lson L, M, node << 1 #define Rson M + 1, R, node << 1 | 1 const int maxn = 1e5 + 20; int col[maxn << 2]; //用来标记每个节点,为0则表示没有标记,否则为标记,以颜色的价值作为标记。 int sum[maxn << 2]; //求和 void PushUp(int node) //向上更新和 { sum[node] = sum[node << 1] + sum[node << 1 | 1]; } void PushDown(int node, int m) // 对某一个区间进行改变,如果被标记了,在查询的时候就得把改变传给子节点,因为查询的并不一定是当前区间 { // m为区间长度 if (col[node]) // 已经标记过,该区间被改变过 { col[node << 1] = col[node << 1 | 1] = col[node]; // 标记子节点 sum[node << 1] = (m - (m >> 1)) * col[node]; // 更新左儿子的和 sum[node << 1 | 1] = (m >> 1) * col[node]; // 更新右儿子的和 col[node] = 0; } } void build(int L, int R, int node) { col[node] = 0; // 初始化为所有节点均未标记 sum[node] = 1; // 初始值为1 if (L == R) return; int M = (L + R) >> 1; build(Lson); build(Rson); } void update(int x, int y, int c, int L, int R, int node) { if (x <= L && R <= y) { col[node] = c; sum[node] = c * (R - L + 1); // 更新代表某个区间的节点和,该节点不一定是叶子节点 return; } PushDown(node, R - L + 1); // 向下传递 int M = (L + R) >> 1; if (x <= M) update(x, y, c, Lson); // 更新左儿子 if (y > M) update(x, y, c, Rson); // 更新右儿子 PushUp(node); // 向上传递更新和 } int main() { int T; scanf("%d", &T); for (int i = 1; i <= T; i++) { int N, Q; scanf("%d", &N); build(1, N, 1); scanf("%d", &Q); while (Q--) { int add, x, y; scanf("%d%d%d", &x, &y, &add); update(x, y, add, 1, N, 1); } printf("Case %d: The total value of the hook is %d.\n", i, sum[1]); } return 0; }
[ "zbszx040504@126.com" ]
zbszx040504@126.com
ba9a91185004af2cce60bafd38b94ff65ab2f12e
0bd8d72b43a6cb965a2372f66a13f7a0f48edace
/lecture_004/b1tob2.cpp
46ed1581cce062dda679d0cfb20b95b5f2061a3b
[]
no_license
HarshitGuptaa/DS-Algo
4121e06184115fdca73326e0cdcf491d09eca1e0
3cf912e0a9205b02300d7c211207b028aae2f15d
refs/heads/master
2023-06-17T12:49:26.184729
2021-06-29T11:56:33
2021-06-29T11:56:33
279,238,431
0
1
null
null
null
null
UTF-8
C++
false
false
637
cpp
#include<iostream> using namespace std; int Dtob2(int n,int b){ int res=0,pow=1; while(n!=0){ int rem=n%b; res=rem*pow+res; n/=b; pow=pow*10; } cout<<res; } int numToD(int n,int b){ int res=0,pow=1; while(n!=0){ int rem=n%10; res=rem*pow+res; n/=10; pow=pow*b; } cout<<res<<endl; return res; } int main(int args, char **argv){ int num,base1,base2; cout<<"Enter number.."; cin>>num; cout<<"Enter base1.."; cin>>base1; cout<<"Enter base2.."; cin>>base2; int r = numToD(num,base1); Dtob2(r,base2); }
[ "gupta.harshit99@gmail.com" ]
gupta.harshit99@gmail.com
26497b10957747b17f2fe20cbf384a823654431e
641768eb03144e6e66bcc5991e6b151885952c12
/src/ANM/AnmNodeList.h
1b7bdce347bb6d812147dcb5f405df57fd8f0f25
[ "MIT" ]
permissive
victor-gil-sepulveda/PhD-ANMInternalCoordinates
47f42b0b07e5df947c163ddda2d7d6567d008445
c49b8627f08f614cef764692dee8627c182d9b6c
refs/heads/master
2021-01-21T12:49:56.260755
2015-04-08T13:26:30
2015-04-08T13:26:30
31,322,617
2
0
null
null
null
null
UTF-8
C++
false
false
687
h
/* * AnmNodeList.h * * Created on: 28/07/2014 * Author: jestrada */ #ifndef ANMNODELIST_H_ #define ANMNODELIST_H_ #include <vector> #include <string> // abstract parent class of all ANM list of nodes' types // (such as vector of atoms or vector of units). // It serves as a way to do generic algorithms that // let the specifics of dealing with the node list to // internal algorithms, which must cast the AnmNodeList // to the specific class (AnmAtomNodeList or AnmUnitNodeList) // before operating. class AnmNodeList { public: virtual ~AnmNodeList() {}; virtual std::string showNodeList() = 0; virtual unsigned int size() = 0; }; #endif /* ANMNODELIST_H_ */
[ "victor.gil.sepulveda@gmail.com" ]
victor.gil.sepulveda@gmail.com
66da46104ca3fa6f50405ed86d51fce711e78f1f
ac227cc22d5f5364e5d029a2cef83816a6954590
/applications/physbam/physbam-app/smoke/SMOKE_EXAMPLE.h
c2eb4ad2aed2b05e9c461969f58481667b8ae860
[ "BSD-3-Clause" ]
permissive
schinmayee/nimbus
597185bc8bac91a2480466cebc8b337f5d96bd2e
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
refs/heads/master
2020-03-11T11:42:39.262834
2018-04-18T01:28:23
2018-04-18T01:28:23
129,976,755
0
0
BSD-3-Clause
2018-04-17T23:33:23
2018-04-17T23:33:23
null
UTF-8
C++
false
false
3,270
h
//##################################################################### // Copyright 2009-2010, Michael Lentine, Andrew Selle. // This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt. //##################################################################### #ifndef __SMOKE_EXAMPLE__ #define __SMOKE_EXAMPLE__ #include <PhysBAM_Tools/Grids_Uniform/UNIFORM_GRID_ITERATOR_CELL.h> #include <PhysBAM_Tools/Grids_Uniform/UNIFORM_GRID_ITERATOR_FACE.h> #include <PhysBAM_Tools/Grids_Uniform_Advection/ADVECTION_SEMI_LAGRANGIAN_UNIFORM.h> #include <PhysBAM_Tools/Grids_Uniform_Arrays/ARRAYS_ND.h> #include <PhysBAM_Tools/Grids_Uniform_Boundaries/BOUNDARY_UNIFORM.h> #include <PhysBAM_Tools/Grids_Uniform_PDE_Linear/PROJECTION_UNIFORM.h> #include <PhysBAM_Tools/Read_Write/Utilities/FILE_UTILITIES.h> #include <PhysBAM_Tools/Vectors/VECTOR.h> namespace PhysBAM{ template<class TV> class SMOKE_EXAMPLE { typedef typename TV::SCALAR T; typedef typename TV::template REBIND<int>::TYPE TV_INT; enum workaround1{d=TV::m}; public: STREAM_TYPE stream_type; T initial_time; int first_frame,last_frame; T frame_rate; int restart; std::string frame_title; int write_substeps_level; bool write_debug_data; std::string output_directory; T cfl; GRID<TV> mac_grid; MPI_UNIFORM_GRID<GRID<TV> > *mpi_grid; THREAD_QUEUE* thread_queue; PROJECTION_UNIFORM<GRID<TV> > projection; ARRAY<T,FACE_INDEX<TV::dimension> > face_velocities; ADVECTION_SEMI_LAGRANGIAN_UNIFORM_BETA<GRID<TV>,T, AVERAGING_UNIFORM<GRID<TV>, FACE_LOOKUP_UNIFORM<GRID<TV> > >,LINEAR_INTERPOLATION_UNIFORM<GRID<TV>,T,FACE_LOOKUP_UNIFORM<GRID<TV> > > > advection_scalar; BOUNDARY_UNIFORM<GRID<TV>,T> boundary_scalar; BOUNDARY_UNIFORM<GRID<TV>,T> *boundary; ARRAY<T,TV_INT> density; VECTOR<VECTOR<bool,2>,TV::dimension> domain_boundary; RANGE<TV> source; pthread_mutex_t lock; SMOKE_EXAMPLE(const STREAM_TYPE stream_type_input,int refine=0); virtual ~SMOKE_EXAMPLE(); T CFL(ARRAY<T,FACE_INDEX<TV::dimension> >& face_velocities); void CFL_Threaded(RANGE<TV_INT>& domain,ARRAY<T,FACE_INDEX<TV::dimension> >& face_velocities,T& dt); T Time_At_Frame(const int frame) const {return initial_time+(frame-first_frame)/frame_rate;} void Initialize_Grid(TV_INT counts,RANGE<TV> domain) {mac_grid.Initialize(counts,domain,true);} void Initialize_Fields() {for(typename GRID<TV>::FACE_ITERATOR iterator(mac_grid);iterator.Valid();iterator.Next()) face_velocities(iterator.Full_Index())=0; for(typename GRID<TV>::CELL_ITERATOR iterator(mac_grid);iterator.Valid();iterator.Next()) density(iterator.Cell_Index())=0;} void Get_Scalar_Field_Sources(const T time) {for(typename GRID<TV>::CELL_ITERATOR iterator(mac_grid);iterator.Valid();iterator.Next()) if(source.Lazy_Inside(iterator.Location())) density(iterator.Cell_Index())=1;} virtual void Write_Output_Files(const int frame); virtual void Read_Output_Files(const int frame); virtual void Set_Boundary_Conditions(const T time); //##################################################################### }; } #endif
[ "quhang@stanford.edu" ]
quhang@stanford.edu
08279c74bb19a0e12e4707c801e67bb0cc15908c
ca652f52c6ca043344036467171b350c1d370317
/Arduino/档案室/check_palm/check_palm.ino
e3f5a0cb72a2af082191e6e4f9ec01b804d19d6f
[]
no_license
whhxp/Room_Escape
e6206065ad7578fd37a9f738d2e2a5a6ca38ab77
e3f95a6ca3a349ae9089ac66a14c3c84a76c51e4
refs/heads/master
2021-01-01T19:52:06.367369
2015-03-25T08:33:36
2015-03-25T08:33:36
32,307,751
0
0
null
null
null
null
UTF-8
C++
false
false
3,490
ino
/* */ #define DEBUG 1 #define PUSHER_DEBUG 0 #define time1 5000 #define time2 5000 #define S(n) Serial.print(n) #define Sln(nn) Serial.println(nn) #define enter() S("enter function\t");Sln(__FUNCTION__) //input //const int mapLight=4; //const int oneButtonControl2LED=5; //const int colorMixing=6; //const int timeControl=7; const int in_signal=4; const int touchhand[] = { A0,A1,A2,A3}; //output const int inner_light_pin=6; const int pusher_up_pin=7; const int pusher_down_pin=8; const int output_pin=13; int check[]={ 0,0,0,0}; int rightNum=0; int wait_signal(); int liter_pusher(int time); int wait_press_palm(); int lights_on(); int output_signal(); int pusher_up(); int pusher_down(); int pusher_stop(); void setup(){ //start serial connection Serial.begin(9600); //configure pin2 as an input and enable the internal pull-up resistor pinMode(output_pin,OUTPUT); pinMode(inner_light_pin,OUTPUT); pinMode(pusher_up_pin,OUTPUT); pinMode(pusher_down_pin,OUTPUT); } void loop(){ #if DEBUG enter(); init_output(); if (wait_signal()) { liter_pusher(time1); light_on(); if(wait_press_palm()) { light_blink(); liter_pusher(time2); output_signal(); } } #if PUSHER_DEBUG pusher_up(); pusher_stop(); pusher_up(); pusher_stop(); pusher_down(); pusher_stop(); #endif #endif } ///////////////////////////////////////////////////////////// //pusher function // // // // // int pusher_down() { enter(); digitalWrite(pusher_up_pin,HIGH); digitalWrite(pusher_down_pin,HIGH); #if PUSHER_DEBUG delay(1000); #endif } int pusher_up() { enter(); digitalWrite(pusher_up_pin,LOW); digitalWrite(pusher_down_pin,LOW); #if PUSHER_DEBUG delay(1000); #endif } int pusher_stop() { enter(); digitalWrite(pusher_up_pin,HIGH); digitalWrite(pusher_down_pin,LOW); #if PUSHER_DEBUG delay(1000); #endif } void init_output() { enter(); for(int k=0;k<4;k++) { check[k]=0; } pusher_down(); digitalWrite(inner_light_pin,HIGH); digitalWrite(output_pin,LOW); } /* function:waits for signals and returns the result of the judgement name:wait_signal para:none return value: 1:there are signals 0:no signal */ int wait_signal() { S("wait 4 question finish signal"); enter(); while(digitalRead(in_signal)==LOW); return 1; } /* function:push the box up according to the time given name:liter pusher para:time in millisec return value: 1:error 0:done */ int liter_pusher(int time) { enter(); pusher_up(); delay(time); pusher_stop(); } /* function:read the signal from palm PCB name:wait_press_palm para:none return value: 1:there are signals 0:no signal */ int wait_press_palm() { enter(); S("wait press palm\n"); while(1) { int add=0; for(int i=0;i<4;i++) { if(analogRead(touchhand[i]) < 400) { add++; Sln("touchhand:"); S(i+1); } } if(add==4) { light_blink(); Serial.println("GOOD LUCK!"); return 1; } } } int light_on() { enter(); S("light on\n"); digitalWrite(inner_light_pin,LOW); } int light_blink() { enter(); digitalWrite(inner_light_pin,LOW); delay(1000); digitalWrite(inner_light_pin,HIGH); delay(1000); digitalWrite(inner_light_pin,LOW); delay(1000); digitalWrite(inner_light_pin,HIGH); delay(1000); } int output_signal() { enter(); digitalWrite(output_pin,HIGH); while(1); }
[ "whhxp1028@gmail.com" ]
whhxp1028@gmail.com
8ae796b5730d88f3ffed3690dae133a7fedaad5b
e1a60813dfb71e5241bf9d702e9f054900bd05e4
/src/SymbolEngine.cpp
34716c9ac85f930b9d4a0b4f467d7e3dd7dd44e4
[]
no_license
ntoskrnl7/NtTrace
866be697a2c3290dbcea93f1ad424b694f7331a9
d7e88cb8e54491f667278cb9c60995a340ecbe78
refs/heads/master
2020-06-13T11:35:10.412664
2019-03-18T22:52:51
2019-03-18T22:52:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
35,139
cpp
/* NAME SymbolEngine DESCRIPTION Additional symbol engine functionality COPYRIGHT Copyright (C) 2003 by Roger Orr <rogero@howzatt.demon.co.uk> This software is distributed in the hope that it will be useful, but without WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Permission is granted to anyone to make or distribute verbatim copies of this software provided that the copyright notice and this permission notice are preserved, and that the distributor grants the recipient permission for further distribution as permitted by this notice. Comments and suggestions are always welcome. Please report bugs to rogero@howzatt.demon.co.uk. */ static char const szRCSID[] = "$Id: SymbolEngine.cpp 1603 2016-02-15 22:24:56Z Roger $"; #ifdef _MSC_VER #pragma warning( disable: 4786 ) // identifier was truncated to '255' chars #pragma warning( disable: 4511 4512 ) // copy constructor/assignment operator could not be generated #endif // _MSC_VER #include "SymbolEngine.h" #include <windows.h> #include <psapi.h> #include <comutil.h> #pragma comment( lib, "oleaut32.lib" ) #pragma comment( lib, "comsupp.lib" ) // stl #include <iostream> #include <iomanip> #include <sstream> #include <typeinfo> #include <map> #include "../include/MsvcExceptions.h" #include "../include/StrFromWchar.h" #include "../include/BasicType.h" #include "../include/readPartialMemory.h" #include "GetModuleBase.h" #pragma comment( lib, "psapi" ) // helper function namespace { // fix for problem with resource leak in symsrv void fixSymSrv(); // Show function/SEH parameters template <typename WORDSIZE> void addParams( std::ostream & os, WORDSIZE * pParams, size_t maxParams ) { for ( size_t i = 0; i < maxParams; ++i ) { WORDSIZE const param = pParams[i]; if ( ( -10 < (long)param ) && ( (long)param < 10 ) ) os << " " << (long)param; else os << " " << (PVOID)(ULONG_PTR)param; } } void showVariablesAt( std::ostream& os, DWORD64 codeOffset, DWORD64 frameOffset, or2::SymbolEngine const & eng ); ////////////////////////////////////////////////////////// // Helper function: getBaseType maps PDB type + length to C++ name std::string getBaseType( DWORD baseType, ULONG64 length ); #ifdef _M_X64 // Helper function to delay load Wow64GetThreadContext or emulate on W2K3 BOOL getWow64ThreadContext(HANDLE hProcess, HANDLE hThread, CONTEXT const &context, WOW64_CONTEXT *pWowContext); #endif // _M_X64 } namespace or2 { ///////////////////////////////////////////////////////////////////////////////////// /** Implementation class */ struct SymbolEngine::Impl { std::map< void const *, std::string > addressMap; }; ///////////////////////////////////////////////////////////////////////////////////// SymbolEngine::SymbolEngine( HANDLE hProcess ) : showLines( true ) , showParams( false ) , showVariables( false ) , maxStackDepth( -1 ) , skipCount( 0 ) , maxSehDepth( 0 ) , pImpl( new Impl ) { static bool inited = false; if ( ! inited ) { DWORD dwOpts = SymGetOptions ( ); dwOpts |= SYMOPT_LOAD_LINES | SYMOPT_OMAP_FIND_NEAREST; char const * pOption = ::getenv( "OR2_SYMOPT" ); if ( pOption ) { int extraOptions = 0; if ( sscanf( pOption, "%x", &extraOptions ) == 1 ) { dwOpts |= extraOptions; } } SymSetOptions ( dwOpts ); inited = true; } Initialise( hProcess ); } ///////////////////////////////////////////////////////////////////////////////////// //Destroy wrapper SymbolEngine::~SymbolEngine( ) { fixSymSrv(); delete pImpl; } ///////////////////////////////////////////////////////////////////////////////////// // true to show line numbers if possible void SymbolEngine::setLines( bool value ) { showLines = value; } bool SymbolEngine::getLines() const { return showLines; } // true to show parameters void SymbolEngine::setParams( bool value ) { showParams = value; } bool SymbolEngine::getParams() const { return showParams; } // true to show variables void SymbolEngine::setVariables( bool value ) { showVariables = value; } bool SymbolEngine::getVariables() const { return showVariables; } // set stack depth for walkbacks void SymbolEngine::setMaxDepth( int value ) { maxStackDepth = value; } int SymbolEngine::getMaxDepth() const { return maxStackDepth; } // set skip count for stack walkbacks void SymbolEngine::setSkipCount( int value ) { skipCount = value; } int SymbolEngine::getSkipCount() const { return skipCount; } // set seh stack depth walkbacks void SymbolEngine::setSehDepth( int value ) { maxSehDepth = value; } int SymbolEngine::getSehDepth() const { return maxSehDepth; } ///////////////////////////////////////////////////////////////////////////////////// bool SymbolEngine::printAddress( PVOID address, std::ostream& os ) const { bool cacheSymbol(true); // Despite having GetModuleBase in the call to StackWalk it needs help for the addresses ::GetModuleBase( GetProcess(), (DWORD64)address ); /////////////////////////////// // Log the module + offset MEMORY_BASIC_INFORMATION mbInfo; if ( ::VirtualQueryEx( GetProcess(), address, &mbInfo, sizeof mbInfo ) && ( ( mbInfo.State & MEM_FREE ) == 0 ) && ( ( mbInfo.Type & MEM_IMAGE ) != 0 ) ) { std::ostringstream str; HMODULE const hmod = (HMODULE)mbInfo.AllocationBase; char szFileName[ MAX_PATH ] = ""; if ( ! GetModuleFileNameWrapper( GetProcess(), hmod, szFileName, sizeof szFileName/sizeof szFileName[0] ) ) { cacheSymbol = false; str << hmod; } else str << strrchr(szFileName, '\\') + 1; str << " + 0x" << std::hex << ((ULONG_PTR)address - (ULONG_PTR)mbInfo.AllocationBase) << std::dec; os << std::setw(30) << std::left << str.str().c_str() << std::right; // c_str() fixes VC6 bug with setw } else { os << address; return false; } /////////////////////////////// // Log the symbol name // The largest (undecorated) symbol that the MS code generators can handle is 256. // I can't believe it will increase more than fourfold when undecorated... #ifdef DBGHELP_6_1_APIS struct { SYMBOL_INFO symInfo; char name[ 4 * 256 ]; } SymInfo = { { sizeof( SymInfo.symInfo ) }, "" }; PSYMBOL_INFO pSym = &SymInfo.symInfo; pSym->MaxNameLen = sizeof( SymInfo.name ); DWORD64 dwDisplacement64(0); if ( SymFromAddr( (DWORD64)address, &dwDisplacement64, pSym) ) #else struct { IMAGEHLP_SYMBOL64 symInfo; char name[ 4 * 256 ]; } SymInfo = { { sizeof( SymInfo.symInfo ) }, "" }; PIMAGEHLP_SYMBOL64 pSym = &SymInfo.symInfo; pSym->MaxNameLength = sizeof( SymInfo.name ); DWORD64 dwDisplacement64; if ( GetSymFromAddr64( (DWORD)address, &dwDisplacement64, pSym) ) #endif { os << " " << pSym->Name; if ( dwDisplacement64 != 0 ) { int displacement = static_cast<int>(dwDisplacement64); if ( displacement < 0 ) os << " - " << -displacement; else os << " + " << displacement; } } /////////////////////////////// // Log the line number if ( showLines ) { DbgInit<IMAGEHLP_LINE64> lineInfo; DWORD dwDisplacement(0); if ( GetLineFromAddr64( (DWORD64)address, &dwDisplacement, &lineInfo ) ) { os << " " << lineInfo.FileName << "(" << lineInfo.LineNumber << ")"; if (dwDisplacement != 0) { os << " + " << dwDisplacement << " byte" << (dwDisplacement == 1 ? "" : "s"); } } } return cacheSymbol; } ///////////////////////////////////////////////////////////////////////////////////// // Convert address to a string. std::string SymbolEngine::addressToName( PVOID address ) const { std::map< void const *, std::string >::iterator it = pImpl->addressMap.find( address ); if ( it == pImpl->addressMap.end() ) { std::ostringstream oss; if (!printAddress( address, oss )) return oss.str(); it = pImpl->addressMap.insert( std::make_pair( address, oss.str() ) ).first; } return it->second; } ///////////////////////////////////////////////////////////////////////////////////// // StackTrace: try to trace the stack to the given output stream void SymbolEngine::StackTrace( HANDLE hThread, const CONTEXT & context, std::ostream & os ) const { STACKFRAME64 stackFrame = {0}; CONTEXT rwContext = {0}; try { rwContext = context; } catch (...) { // stack based context may be missing later sections -- based on the flags } PVOID pContext = &rwContext; // it is claimed this is not needed on Intel...lies #ifdef _M_IX86 DWORD const machineType = IMAGE_FILE_MACHINE_I386; // StackFrame needs to be set up on Intel stackFrame.AddrPC.Offset = context.Eip; stackFrame.AddrPC.Mode = AddrModeFlat; stackFrame.AddrFrame.Offset = context.Ebp; stackFrame.AddrFrame.Mode = AddrModeFlat; stackFrame.AddrStack.Offset = context.Esp; stackFrame.AddrStack.Mode = AddrModeFlat; #elif _M_X64 DWORD machineType = IMAGE_FILE_MACHINE_AMD64; stackFrame.AddrPC.Offset = context.Rip; stackFrame.AddrPC.Mode = AddrModeFlat; stackFrame.AddrFrame.Offset = context.Rbp; stackFrame.AddrFrame.Mode = AddrModeFlat; stackFrame.AddrStack.Offset = context.Rsp; stackFrame.AddrStack.Mode = AddrModeFlat; BOOL bWow64(false); WOW64_CONTEXT wow64_context = {0}; wow64_context.ContextFlags = WOW64_CONTEXT_FULL; if (IsWow64Process(GetProcess(), &bWow64) && bWow64) { if (getWow64ThreadContext(GetProcess(), hThread, rwContext, &wow64_context)) { machineType = IMAGE_FILE_MACHINE_I386; pContext = &wow64_context; stackFrame.AddrPC.Offset = wow64_context.Eip; stackFrame.AddrFrame.Offset = wow64_context.Ebp; stackFrame.AddrStack.Offset = wow64_context.Esp; } } #else #error Unsupported target platform #endif // _M_IX86 // For loop detection DWORD64 currBp = 0; // For 'wandering stack' DWORD nonExec(0); DWORD const maxNonExec(3); // use local copies of instance data int depth = maxStackDepth; int skip = skipCount; // Despite having GetModuleBase in the call to StackWalk it needs help for the first address ::GetModuleBase(GetProcess(), stackFrame.AddrPC.Offset); while ( ::StackWalk64(machineType, GetProcess(), hThread, &stackFrame, pContext, NULL, 0, // implies ::SymFunctionTableAccess, ::GetModuleBase, NULL ) ) { if ( stackFrame.AddrFrame.Offset == 0 ) break; if (stackFrame.AddrPC.Offset == 0) { os << "Null address\n"; break; } if ( currBp != 0 ) { if ( currBp >= stackFrame.AddrFrame.Offset ) { os << "Stack frame: " << (PVOID)stackFrame.AddrFrame.Offset << " out of sequence\n"; break; } } currBp = stackFrame.AddrFrame.Offset; // This helps x64 stack walking -- I think this might be a bug as the function is // already supplied in the StackWalk64 call ... ::GetModuleBase(GetProcess(), stackFrame.AddrPC.Offset); if ( skip > 0 ) { skip--; continue; } if ( depth > -1 ) { if ( depth-- == 0 ) break; } if ( isExecutable(stackFrame.AddrPC.Offset)) { nonExec = 0; } else { ++nonExec; if (nonExec > maxNonExec) break; } os << addressToName( (PVOID)stackFrame.AddrPC.Offset ); if (nonExec) { os << " (non executable)"; } os << "\n"; #if 0 os << "AddrPC: " << (PVOID)stackFrame.AddrPC.Offset << " AddrReturn: " << (PVOID)stackFrame.AddrReturn.Offset << " AddrFrame: " << (PVOID)stackFrame.AddrFrame.Offset << " AddrStack: " << (PVOID)stackFrame.AddrStack.Offset << " FuncTableEntry: " << (PVOID)stackFrame.FuncTableEntry << " Far: " << stackFrame.Far << " Virtual: " << stackFrame.Virtual << " AddrBStore: " << (PVOID)stackFrame.AddrBStore.Offset << "\n"; #endif if ( showParams ) { os << " " << (PVOID)stackFrame.AddrFrame.Offset << ":"; addParams( os, stackFrame.Params, sizeof( stackFrame.Params ) / sizeof( stackFrame.Params[0] ) ); os << "\n"; } if ( showVariables ) { showVariablesAt( os, stackFrame.AddrPC.Offset, stackFrame.AddrFrame.Offset, *this ); } } os.flush(); } ////////////////////////////////////////////////////////// // GetCurrentThreadContext // // Get context for the current thread, correcting the stack frame to the caller // // We sort out 3 key registers after GetThreadContext to // prevent trying to stack walk after we've modified the stack... // static #ifdef _M_IX86 BOOL __declspec( naked ) SymbolEngine::GetCurrentThreadContext( CONTEXT * pContext ) { DWORD regIp, regSp, regBp; BOOL rc; _asm push ebp _asm mov ebp,esp _asm sub esp,__LOCAL_SIZE rc = ::GetThreadContext( GetCurrentThread(), pContext ); if ( rc ) { _asm mov eax,[ebp+4] ; return address _asm mov regIp,eax _asm lea eax,[ebp+0ch] ; caller's SP before pushing pContext _asm mov regSp,eax _asm mov eax,[ebp] ; caller's BP _asm mov regBp,eax pContext->Eip = regIp; pContext->Esp = regSp; pContext->Ebp = regBp; } _asm mov eax,rc _asm mov esp,ebp _asm pop ebp _asm ret } #else /** get context for the current thread, correcting the stack frame to the caller */ void (WINAPI *SymbolEngine::GetCurrentThreadContext)(PCONTEXT pContext) = RtlCaptureContext; #endif // _M_IX86 ////////////////////////////////////////////////////////// // void SymbolEngine::SEHTrace( PVOID ExceptionList, std::ostream& os ) const { // Got the first entry of the exception stack for ( int i = 0; (maxSehDepth < 0) || (i < maxSehDepth); ++i ) { if ( ExceptionList == (PVOID)(INT_PTR)-1 || ExceptionList == 0 ) break; struct Frame { PVOID previous; PVOID handler; } frame; if ( ! ReadMemory( ExceptionList, (PVOID)&frame, sizeof( frame ) ) ) { std::cerr << "ReadProcessMemory at " << ExceptionList << " failed: " << GetLastError() << std::endl; return; } os << addressToName( frame.handler ); os << "\n"; PVOID catchHandler = 0; bool isMsvcHandler = findMsvcCppHandler( frame.handler, &catchHandler ); if ( showParams ) { struct { Frame frame; DWORD Params[3]; } extendedFrame; if ( ReadMemory( ExceptionList, &extendedFrame, sizeof( extendedFrame ) ) ) { os << " " << ExceptionList << ":"; addParams( os, extendedFrame.Params, sizeof( extendedFrame.Params ) / sizeof( extendedFrame.Params[0] ) ); // For Msvc Cpp handlers params[2] is actually the return address if ( isMsvcHandler ) { os << " [" << addressToName( (PVOID)(ULONG_PTR)extendedFrame.Params[2] ) << "]"; } os << "\n"; } } if ( catchHandler ) { os << " => " << addressToName( catchHandler ) << "\n"; } if ( ExceptionList < frame.previous ) { ExceptionList = frame.previous; } else if ( ExceptionList > frame.previous ) { os << " ends (" << frame.previous << "<" << ExceptionList << ")\n"; break; } else { // Cygwin ends with self-referential handler break; } } } ////////////////////////////////////////////////////////// // Hack to try and get first catch handler for MSVC exception // // Attempt to walk the internal Microsoft structures // to find the first catch handler for a C++ exception // Returns: // false if not an Msvc C++ handler, msvcHandler = 0 // true // msvcHandler = 0 if no catch handler [implicit frame unwind code] // else handler address bool SymbolEngine::findMsvcCppHandler( PVOID sehHandler, PVOID *msvcHandler ) const { // Set the default return value *msvcHandler = 0; BYTE buffer[ 1 + sizeof( PVOID ) ]; // read mov instruction PVOID *bufptr; // pointer into buffer // Read 5 bytes from handler address and check 1st byte is // a mov eax (0xb8) if ( ( ! ReadMemory( sehHandler, (PVOID)buffer, sizeof(buffer) ) ) || ( buffer[0] != 0xb8 ) ) { return false; } // deref and read FrameHandler bufptr = (PVOID*)(buffer+1); PVOID pFrameHandler = *bufptr; MsvcFrameHandler frameHandler; if ( ! ReadMemory( pFrameHandler, (PVOID)&frameHandler, sizeof( frameHandler ) ) ) return false; // Verify 'magic number' if ( frameHandler.magic != MSVC_MAGIC_NUMBER1 ) return false; // We have definitely got an MSVC handler - has it got a catch address? if ( frameHandler.cTryEntry == 0 ) return true; // Read first try entry MsvcTryEntry tryEntry; if ( ! ReadMemory( frameHandler.pTryEntry, (PVOID)&tryEntry, sizeof( tryEntry ) ) ) return true; // Read first catch entry MsvcCatchEntry catchEntry; if ( ! ReadMemory( tryEntry.pCatchEntry, (PVOID)&catchEntry, sizeof( catchEntry ) ) ) return true; // return first target address *msvcHandler = catchEntry.catchHandler; return true; } ////////////////////////////////////////////////////////// // showMsvcThrow // // Attempt to find type information for MSVC C++ throw parameter void SymbolEngine::showMsvcThrow( std::ostream &os, PVOID throwInfo, PVOID base ) const { MsvcThrow msvcThrow = {0}; MsvcClassHeader msvcClassHeader = {0}; MsvcClassInfo msvcClassInfo = {0}; BYTE raw_type_info[ sizeof( type_info ) + 256 ] = ""; if ( ! ReadMemory( (PVOID)throwInfo, &msvcThrow, sizeof( msvcThrow ) ) || ! ReadMemory( (PVOID)((ULONG_PTR)base + msvcThrow.pClassHeader), &msvcClassHeader, sizeof( msvcClassHeader ) ) || ! ReadMemory( (PVOID)((ULONG_PTR)base + msvcClassHeader.Info[0]), &msvcClassInfo, sizeof( msvcClassInfo ) ) || ! ReadPartialProcessMemory( GetProcess(), (PVOID)((ULONG_PTR)base + msvcClassInfo.pTypeInfo), &raw_type_info, sizeof( type_info ), sizeof( raw_type_info ) -1 ) ) { return; } const std::type_info *pType_info = (const std::type_info *)raw_type_info; char buffer[ 1024 ] = ""; if ( UnDecorateSymbolName( pType_info->raw_name() + 1, buffer, sizeof( buffer ), UNDNAME_32_BIT_DECODE | UNDNAME_NO_ARGUMENTS ) ) { os << " (" << buffer << ")"; } } // Helper for ReadProcessMemory bool SymbolEngine::ReadMemory( LPCVOID lpBaseAddress, // base of memory area LPVOID lpBuffer, // data buffer SIZE_T nSize ) const // number of bytes to read { #pragma warning( disable: 4800 ) // forcing value to bool 'true' or 'false' return ReadProcessMemory( GetProcess(), lpBaseAddress, lpBuffer, nSize, 0 ); } ////////////////////////////////////////////////////////// // DbgHelp 6.1 functionality - get the name for a symbol BOOL SymbolEngine::decorateName( std::string & name, ULONG64 ModBase, ULONG TypeIndex ) const { BOOL bRet( false ); #ifdef DBGHELP_6_1_APIS WCHAR *typeName = 0; if ( GetTypeInfo( ModBase, TypeIndex, TI_GET_SYMNAME, &typeName ) ) { bool const nested = (name.length() != 0); if ( nested ) { name.insert( 0, " "); } name.insert( 0, or2::strFromWchar( typeName ) ); // free memory for typeName - by experiment with a debugger it comes from LocalAlloc LocalFree( typeName ); if ( nested ) { return true; } } bool bRecurse( false ); // set to true to recurse down the type tree enum SymTagEnum tag = (enum SymTagEnum)0; GetTypeInfo( ModBase, TypeIndex, TI_GET_SYMTAG, &tag ); switch ( tag ) { case SymTagBaseType: { DWORD baseType(0); ULONG64 length(0); GetTypeInfo( ModBase, TypeIndex, TI_GET_BASETYPE, &baseType ); GetTypeInfo( ModBase, TypeIndex, TI_GET_LENGTH, &length ); name.insert( 0, " " ); name.insert( 0, getBaseType( baseType, length ) ); bRet = true; break; } case SymTagPointerType: name.insert( 0, "*" ); bRecurse = true; break; case SymTagFunctionType: if ( name[0] == '*' ) { name.insert( 0, "(" ); name += ")"; } name += "()"; bRecurse = true; break; case SymTagArrayType: { if ( name[0] == '*' ) { name.insert( 0, "(" ); name += ")"; } DWORD Count(0); GetTypeInfo( ModBase, TypeIndex, TI_GET_COUNT, &Count ); name += "["; if ( Count ) { std::ostringstream oss; oss << Count; name += oss.str(); } name += "]"; bRecurse = true; break; } case SymTagFunction: case SymTagData: bRecurse = true; break; case SymTagBaseClass: break; default: { std::ostringstream oss; oss << tag << " "; name.insert( 0, oss.str() ); break; } } if ( bRecurse ) { DWORD ti = 0; if ( GetTypeInfo( ModBase, TypeIndex, TI_GET_TYPEID, &ti ) ) { bRet = decorateName( name, ModBase, ti ); } } _variant_t value; if ( GetTypeInfo( ModBase, TypeIndex, TI_GET_VALUE, &value ) ) { value.ChangeType( VT_BSTR ); name += "=" + or2::strFromWchar( value.bstrVal ); } #endif // DBGHELP_6_1_APIS return bRet; } /////////////////////////////////////////////////////////////////////////// /** enumerate local variables at an address */ BOOL SymbolEngine::enumLocalVariables( DWORD64 codeOffset, DWORD64 frameOffset, EnumLocalCallBack & cb ) const { #ifdef DBGHELP_6_1_APIS struct CallBack { CallBack( SymbolEngine const & eng, EnumLocalCallBack & cb ) : eng( eng ), cb( cb ) {} static BOOL CALLBACK enumSymbolsProc( PSYMBOL_INFO pSymInfo, ULONG /*SymbolSize*/, PVOID UserContext ) { CallBack& thisCb = *(CallBack*)UserContext; return thisCb.cb( thisCb.eng, pSymInfo ); } SymbolEngine const & eng; EnumLocalCallBack & cb; }; IMAGEHLP_STACK_FRAME stackFrame = {0}; stackFrame.InstructionOffset = codeOffset; stackFrame.FrameOffset = frameOffset; BOOL ret = SetContext( &stackFrame, 0 ); // Note: by experiment with SymUnpack must ignore failures from SetContext ... CallBack callBack( *this, cb ); ret = EnumSymbols( 0, "*", CallBack::enumSymbolsProc, &callBack ); return ret; #else return false; #endif // DBGHELP_6_1_APIS } /////////////////////////////////////////////////////////// /* Write a simple mini-dump for an exception in the <b>current</b> thread */ BOOL SymbolEngine::dumpSelf( std::string const & miniDumpFile, EXCEPTION_POINTERS *ExceptionInfo ) { BOOL ret( FALSE ); #ifdef DBGHELP_6_1_APIS HANDLE const hDumpFile = CreateFile( miniDumpFile.c_str(), FILE_WRITE_DATA, 0, NULL, CREATE_ALWAYS, 0, 0 ); if ( hDumpFile != INVALID_HANDLE_VALUE ) { MINIDUMP_EXCEPTION_INFORMATION ExceptionParam; ExceptionParam.ThreadId = GetCurrentThreadId(); ExceptionParam.ExceptionPointers = ExceptionInfo; ExceptionParam.ClientPointers = TRUE; ret = WriteMiniDump( ::GetCurrentProcessId(), hDumpFile, MiniDumpNormal, &ExceptionParam, 0, 0 ); CloseHandle( hDumpFile ); } #endif // DBGHELP_6_1_APIS return ret; } ///////////////////////////////////////////////////////////////////////////////////// // Read a string from the target std::string SymbolEngine::getString(PVOID address, BOOL unicode, DWORD maxStringLength) const { if (unicode) { std::vector<wchar_t> chVector(maxStringLength + 1); ReadPartialProcessMemory(GetProcess(), address, &chVector[0], sizeof(wchar_t), maxStringLength * sizeof(wchar_t)); size_t const wcLen = wcstombs(0, &chVector[0], 0); if (wcLen == (size_t)-1) { return "invalid string"; } else { std::vector<char> mbStr(wcLen + 1); wcstombs(&mbStr[0], &chVector[0], wcLen); return &mbStr[0]; } } else { std::vector<char> chVector(maxStringLength + 1); ReadPartialProcessMemory(GetProcess(), address, &chVector[0], 1, maxStringLength); return &chVector[0]; } } ///////////////////////////////////////////////////////////////////////////////////// // Returns whether address points to executable code bool SymbolEngine::isExecutable(DWORD64 address) const { bool ret(false); static const DWORD AnyExecute = PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY; MEMORY_BASIC_INFORMATION mb = { 0 }; if ( VirtualQueryEx( GetProcess(), (PVOID)address, &mb, sizeof( mb ) ) ) { if ( ( mb.Protect & (AnyExecute) ) != 0 ) { ret = true; // executable code } } return ret; } } // namespace or2 namespace { ////////////////////////////////////////////////////////// // fix for problem with resource leak in symsrv void fixSymSrv() { static bool loaded = false; if ( !loaded ) { HMODULE const hSymSrv = ::GetModuleHandle( "SymSrv" ); if ( hSymSrv != 0 ) { ::LoadLibrary( "SymSrv" ); loaded = true; } } } ////////////////////////////////////////////////////////// void showVariablesAt( std::ostream& os, DWORD64 codeOffset, DWORD64 frameOffset, or2::SymbolEngine const & eng ) { #ifdef DBGHELP_6_1_APIS struct CallBack : public or2::SymbolEngine::EnumLocalCallBack { CallBack( std::ostream &opf, DWORD64 frameOffset ) : opf(opf), frameOffset( frameOffset ) {} virtual bool operator()( or2::SymbolEngine const & eng, PSYMBOL_INFO pSymInfo ) { if ( ( pSymInfo->Flags & SYMFLAG_LOCAL ) && ( pSymInfo->Flags & SYMFLAG_REGREL ) ) { std::string name( pSymInfo->Name, pSymInfo->NameLen ); eng.decorateName( name, pSymInfo->ModBase, pSymInfo->TypeIndex ); opf << " " << name; opf << " [ebp"; if ( pSymInfo->Address > 0x7fffffff ) opf << "-" << std::hex << -(int)pSymInfo->Address << std::dec; else opf << "+" << std::hex << (int)pSymInfo->Address << std::dec; opf << "]"; if ( pSymInfo->Size == sizeof( char ) ) { unsigned char data; eng.ReadMemory( (PVOID)( frameOffset + pSymInfo->Address ), &data, sizeof( data ) ); if (isprint(data)) opf << " = '" << data << '\''; else opf << " = " << (int)data; } else if ( pSymInfo->Size == sizeof( short ) ) { unsigned short data; eng.ReadMemory( (PVOID)( frameOffset + pSymInfo->Address ), &data, sizeof( data ) ); opf << " = " << data; } else if ( ( pSymInfo->Size == sizeof(int) ) || ( pSymInfo->Size == 0 ) ) { unsigned int data; eng.ReadMemory( (PVOID)( frameOffset + pSymInfo->Address ), &data, sizeof( data ) ); opf << " = 0x" << std::hex << data << std::dec; } else if ( ( pSymInfo->Size == 8 ) && ( name.compare( 0, 6, "double" ) == 0 ) ) { double data; eng.ReadMemory( (PVOID)( frameOffset + pSymInfo->Address ), &data, sizeof( data ) ); opf << " = " << data; } else if ( ( pSymInfo->Size == 8 ) ) { LONGLONG data; eng.ReadMemory( (PVOID)( frameOffset + pSymInfo->Address ), &data, sizeof( data ) ); #if _MSC_VER <= 1200 opf << " = 0x" << std::hex << (double)data << std::dec; #else opf << " = 0x" << std::hex << data << std::dec; #endif // _MSC_VER } opf << std::endl; } return true; } std::ostream &opf; DWORD64 frameOffset; }; CallBack cb( os, frameOffset ); eng.enumLocalVariables( codeOffset, frameOffset, cb ); #endif // DBGHELP_6_1_APIS } ////////////////////////////////////////////////////////// // Helper function: getBaseType maps PDB type + length to C++ name std::string getBaseType( DWORD baseType, ULONG64 length ) { static struct { DWORD baseType; ULONG64 length; const char * name; } baseList[] = { // Table generated from dumping out 'baseTypes.cpp' { btNoType, 0, "(null)" }, // Used for __$ReturnUdt { btVoid, 0, "void" }, { btChar, sizeof( char ), "char" }, { btWChar, sizeof( wchar_t ), "wchar_t" }, { btInt, sizeof( signed char ), "signed char" }, { btInt, sizeof( short ), "short" }, { btInt, sizeof( int ), "int" }, { btInt, sizeof( __int64 ), "__int64" }, { btUInt, sizeof( unsigned char ), "unsigned char" }, // also used for 'bool' in VC6 { btUInt, sizeof( unsigned short ), "unsigned short" }, { btUInt, sizeof( unsigned int ), "unsigned int" }, { btUInt, sizeof( unsigned __int64 ),"unsigned __int64" }, { btFloat, sizeof( float ), "float" }, { btFloat, sizeof( double ), "double" }, { btFloat, sizeof( long double ), "long double" }, // btBCD { btBool, sizeof( bool ), "bool" }, // VC 7.x { btLong, sizeof( long ), "long" }, { btULong, sizeof( unsigned long ), "unsigned long" }, // btCurrency // btDate // btVariant // btComplex // btBit // btBSTR { btHresult, sizeof( HRESULT ), "HRESULT" }, }; for ( int i = 0; i < sizeof( baseList ) / sizeof( baseList[0] ); ++i ) { if ( ( baseType == baseList[i].baseType ) && ( length == baseList[i].length ) ) { return baseList[i].name; } } // Unlisted type - use the data values and then fix the code (!) std::ostringstream oss; oss << "pdb type: " << baseType << "/" << (DWORD)length; return oss.str(); } #ifdef _M_X64 static DWORD const WOW64_CS_32BIT = 0x23; // Wow64 32-bit code segment on Windows 2003 static DWORD const TLS_OFFSET = 0x1480; // offsetof(ntdll!_TEB, TlsSlots) on Windows 2003 #pragma pack(4) struct Wow64_SaveContext { ULONG unknown1; WOW64_CONTEXT context; ULONG unknown2; }; #pragma pack() typedef BOOL (WINAPI *pfnWow64GetThreadContext) (HANDLE, WOW64_CONTEXT*); typedef NTSTATUS (WINAPI *pfnNtQueryInformationThread) (HANDLE ThreadHandle, ULONG ThreadInformationClass, PVOID Buffer, ULONG Length, PULONG ReturnLength); // Helper function to delay load Wow64GetThreadContext or emulate on W2K3 BOOL getWow64ThreadContext(HANDLE hProcess, HANDLE hThread, CONTEXT const &context, WOW64_CONTEXT *pWowContext) { static HMODULE hKernel32 = ::GetModuleHandle("KERNEL32"); static pfnWow64GetThreadContext pFn = (pfnWow64GetThreadContext)::GetProcAddress(hKernel32, "Wow64GetThreadContext"); if (pFn) { // Vista and above return pFn(hThread, pWowContext); } else if (context.SegCs == WOW64_CS_32BIT) { if (pWowContext->ContextFlags & CONTEXT_CONTROL) { pWowContext->Ebp = (ULONG)context.Rbp; pWowContext->Eip = (ULONG)context.Rip; pWowContext->SegCs = context.SegCs; pWowContext->EFlags = context.EFlags; pWowContext->Esp = (ULONG)context.Rsp; pWowContext->SegSs = context.SegSs; } if (pWowContext->ContextFlags & CONTEXT_INTEGER) { pWowContext->Edi = (ULONG)context.Rdi; pWowContext->Esi = (ULONG)context.Rsi; pWowContext->Ebx = (ULONG)context.Rbx; pWowContext->Edx = (ULONG)context.Rdx; pWowContext->Ecx = (ULONG)context.Rcx; pWowContext->Eax = (ULONG)context.Rax; } return true; } else { static HMODULE hNtDll = ::GetModuleHandle("NTDLL"); static pfnNtQueryInformationThread pNtQueryInformationThread = (pfnNtQueryInformationThread)::GetProcAddress(hNtDll, "NtQueryInformationThread"); ULONG_PTR ThreadInfo[6] = {0}; if (pNtQueryInformationThread && pNtQueryInformationThread(hThread, 0, &ThreadInfo, sizeof(ThreadInfo), 0) == 0) { PVOID *pTls = (PVOID *)(ThreadInfo[1] + TLS_OFFSET); Wow64_SaveContext saveContext = {0}, *pSaveContext = 0; if (ReadProcessMemory(hProcess, pTls + 1, &pSaveContext, sizeof(pSaveContext), 0) && ReadProcessMemory(hProcess, pSaveContext, &saveContext, sizeof(saveContext), 0)) { *pWowContext = saveContext.context; return true; } } } return false; } #endif // _M_X64 } // namespace
[ "rogero@howzatt.demon.co.uk" ]
rogero@howzatt.demon.co.uk
0cd1b8784f485cf9e1e2709550a1368d06d168c9
bf278d024957a59c6f1efb36aa8b76069eff22a5
/array.h
1c03158215338a784505245a72e3ecd2b6034ebc
[ "BSD-3-Clause", "BSL-1.0" ]
permissive
byplayer/yamy
b84741fe738f5abac33edb934951ea91454fb4ca
031e57e81caeb881a0a219e2a11429795a59d845
refs/heads/master
2020-05-22T12:46:55.516053
2010-05-19T15:57:38
2010-05-19T15:57:38
3,842,546
6
0
null
null
null
null
UTF-8
C++
false
false
5,325
h
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // array.h #ifndef _ARRAY_H # define _ARRAY_H # include <memory> /// template <class T, class Allocator = std::allocator<T> > class Array { public: typedef typename Allocator::reference reference; /// typedef typename Allocator::const_reference const_reference; /// typedef typename Allocator::pointer iterator; /// typedef typename Allocator::const_pointer const_iterator; /// typedef typename Allocator::size_type size_type; /// typedef typename Allocator::difference_type difference_type; /// typedef T value_type; /// typedef Allocator allocator_type; /// typedef typename Allocator::pointer pointer; /// typedef typename Allocator::const_pointer const_pointer; /// #if 0 typedef std::reverse_iterator<iterator> reverse_iterator; /// typedef std::reverse_iterator<const_iterator> const_reverse_iterator; /// #endif private: Allocator m_allocator; /// size_type m_size; /// pointer m_buf; /// array buffer public: /// constructor explicit Array(const Allocator& i_allocator = Allocator()) : m_allocator(i_allocator), m_size(0), m_buf(NULL) { } /// constructor explicit Array(size_type i_size, const T& i_value = T(), const Allocator& i_allocator = Allocator()) : m_allocator(i_allocator), m_size(i_size), m_buf(m_allocator.allocate(m_size, 0)) { std::uninitialized_fill_n(m_buf, i_size, i_value); } /// constructor template <class InputIterator> Array(InputIterator i_begin, InputIterator i_end, const Allocator& i_allocator = Allocator()) : m_allocator(i_allocator), m_size(distance(i_begin, i_end)), m_buf(Allocator::allocate(m_size, 0)) { std::uninitialized_copy(i_begin, i_end, m_buf); } /// copy constructor Array(const Array& i_o) : m_size(0), m_buf(NULL) { operator=(i_o); } /// destractor ~Array() { clear(); } /// Array& operator=(const Array& i_o) { if (&i_o != this) { clear(); m_size = i_o.m_size; m_buf = m_allocator.allocate(m_size, 0); std::uninitialized_copy(i_o.m_buf, i_o.m_buf + m_size, m_buf); } return *this; } /// allocator_type get_allocator() const { return Allocator(); } /// return pointer to the array buffer typename allocator_type::pointer get() { return m_buf; } /// return pointer to the array buffer typename allocator_type::const_pointer get() const { return m_buf; } /// iterator begin() { return m_buf; } /// const_iterator begin() const { return m_buf; } /// iterator end() { return m_buf + m_size; } /// const_iterator end() const { return m_buf + m_size; } #if 0 /// reverse_iterator rbegin() { reverse_iterator(end()); } /// const_reverse_iterator rbegin() const { const_reverse_iterator(end()); } /// reverse_iterator rend() { reverse_iterator(begin()); } /// const_reverse_iterator rend() const { const_reverse_iterator(begin()); } #endif /// size_type size() const { return m_size; } /// size_type max_size() const { return -1; } /// resize the array buffer. NOTE: the original contents are cleared. void resize(size_type i_size, const T& i_value = T()) { clear(); m_size = i_size; m_buf = m_allocator.allocate(m_size, 0); std::uninitialized_fill_n(m_buf, i_size, i_value); } /// resize the array buffer. template <class InputIterator> void resize(InputIterator i_begin, InputIterator i_end) { clear(); m_size = distance(i_begin, i_end); m_buf = m_allocator.allocate(m_size, 0); std::uninitialized_copy(i_begin, i_end, m_buf); } /// expand the array buffer. the contents of it are copied to the new one void expand(size_type i_size, const T& i_value = T()) { ASSERT( m_size <= i_size ); if (!m_buf) resize(i_size, i_value); else { pointer buf = m_allocator.allocate(i_size, 0); std::uninitialized_copy(m_buf, m_buf + m_size, buf); std::uninitialized_fill_n(buf + m_size, i_size - m_size, i_value); clear(); m_size = i_size; m_buf = buf; } } /// bool empty() const { return !m_buf; } /// reference operator[](size_type i_n) { return *(m_buf + i_n); } /// const_reference operator[](size_type i_n) const { return *(m_buf + i_n); } /// const_reference at(size_type i_n) const { return *(m_buf + i_n); } /// reference at(size_type i_n) { return *(m_buf + i_n); } /// reference front() { return *m_buf; } /// const_reference front() const { return *m_buf; } /// reference back() { return *(m_buf + m_size - 1); } /// const_reference back() const { return *(m_buf + m_size - 1); } /// void swap(Array &i_o) { if (&i_o != this) { pointer buf = m_buf; size_type size = m_size; m_buf = i_o.m_buf; m_size = i_o.m_size; i_o.m_buf = buf; i_o.m_size = size; } } /// void clear() { if (m_buf) { for (size_type i = 0; i < m_size; i ++) m_allocator.destroy(&m_buf[i]); m_allocator.deallocate(m_buf, m_size); m_buf = 0; m_size = 0; } } }; #endif // _ARRAY_H
[ "gimy@users.sourceforge.jp" ]
gimy@users.sourceforge.jp
ca983736e71b0b8579293b7ee3648259436f0f12
948f4e13af6b3014582909cc6d762606f2a43365
/testcases/juliet_test_suite/testcases/CWE415_Double_Free/s01/CWE415_Double_Free__new_delete_array_int_42.cpp
fe1253115cb7b3890a67227a0c9c55e01a008811
[]
no_license
junxzm1990/ASAN--
0056a341b8537142e10373c8417f27d7825ad89b
ca96e46422407a55bed4aa551a6ad28ec1eeef4e
refs/heads/master
2022-08-02T15:38:56.286555
2022-06-16T22:19:54
2022-06-16T22:19:54
408,238,453
74
13
null
2022-06-16T22:19:55
2021-09-19T21:14:59
null
UTF-8
C++
false
false
3,039
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE415_Double_Free__new_delete_array_int_42.cpp Label Definition File: CWE415_Double_Free__new_delete_array.label.xml Template File: sources-sinks-42.tmpl.cpp */ /* * @description * CWE: 415 Double Free * BadSource: Allocate data using new and Deallocae data using delete * GoodSource: Allocate data using new * Sinks: * GoodSink: do nothing * BadSink : Deallocate data using delete * Flow Variant: 42 Data flow: data returned from one function to another in the same source file * * */ #include "std_testcase.h" #include <wchar.h> namespace CWE415_Double_Free__new_delete_array_int_42 { #ifndef OMITBAD static int * badSource(int * data) { data = new int[100]; /* POTENTIAL FLAW: delete the array data in the source - the bad sink deletes the array data as well */ delete [] data; return data; } void bad() { int * data; /* Initialize data */ data = NULL; data = badSource(data); /* POTENTIAL FLAW: Possibly deleting memory twice */ delete [] data; } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B() uses the GoodSource with the BadSink */ static int * goodG2BSource(int * data) { data = new int[100]; /* FIX: Do NOT delete the array data in the source - the bad sink deletes the array data */ return data; } static void goodG2B() { int * data; /* Initialize data */ data = NULL; data = goodG2BSource(data); /* POTENTIAL FLAW: Possibly deleting memory twice */ delete [] data; } /* goodB2G() uses the BadSource with the GoodSink */ static int * goodB2GSource(int * data) { data = new int[100]; /* POTENTIAL FLAW: delete the array data in the source - the bad sink deletes the array data as well */ delete [] data; return data; } static void goodB2G() { int * data; /* Initialize data */ data = NULL; data = goodB2GSource(data); /* do nothing */ /* FIX: Don't attempt to delete the memory */ ; /* empty statement needed for some flow variants */ } void good() { goodG2B(); goodB2G(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE415_Double_Free__new_delete_array_int_42; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
[ "yzhang0701@gmail.com" ]
yzhang0701@gmail.com
7e56814a38a23ff5619adc4a40de44db4ea30a97
df042f93f42f5f48f6e2a05d382a776d39353302
/queue/implements_of_the_queue.cpp
9c43e7e70c675eeccef380ff9a4c813b2306afb1
[]
no_license
hys2rang/WHrkTLQKF
37e74dce0265df27abc65fd068390f5168042482
6890f30fa1740a96681c0d4706b3ac2c7741fb49
refs/heads/master
2020-03-27T03:18:16.435464
2019-10-18T04:56:35
2019-10-18T04:56:35
145,852,206
1
0
null
null
null
null
UTF-8
C++
false
false
2,367
cpp
/* 문제 이 문제에서는 큐를 구현한다. 큐는 다음 세 개의 연산을 지원한다. Push X : 큐에 정수 X를 push한다. 만약 rear 포인터가 더 이상 뒤로 갈 수 없다면, “Overflow”를 출력한다. Pop : 큐에서 정수 하나를 pop한다. 만약 front 포인터가 더 이상 뒤로 갈 수 없다면, “Underflow”를 출력한다. Front : 큐의 front에 있는 정수를 출력한다. 만약 큐가 비어있다면 “NULL”을 출력한다. 크기가 n인 큐에 m개의 연산을 하는 프로그램을 작성하시오. 입력의 편의를 위해서 Push는 “1”, Pop은 “2”, Top은 “3”으로 표현한다. 다음은 크기 4인 큐에 10개의 연산이 입력으로 주어졌을 때의 입력과 출력의 예이다. 참고로, 다음 예제는 선형 큐의 대표적인 나쁜 예이다. 다음 예제때문에 선형 큐는 쓰이지 않는다. 입력 첫째 줄에 큐의 크기 n, 연산의 개수 m이 주어진다. ( 1 n 100, 1 m 1,000 ) 두 번째 줄부터 연산이 주어진다. 1은 Push, 2는 Pop, 3은 Front 연산을 의미한다. 출력 연산의 결과를 출력한다. 예제 입력 4 15 1 1 1 2 1 3 3 2 2 3 1 4 1 5 3 2 2 1 6 2 3 예제 출력 1 3 Overflow 3 Overflow Underflow NULL */ #include <iostream> #include <vector> using namespace std; class Queue{ vector<int> q; int f,r; public: Queue(int x){ q.resize(x,0); f=r=0; } void push(int x) { if(r>=q.size()){ cout<<"Overflow"<<endl; }else{ q[r++]=x; } } void pop() { if(r-f<=0){ cout<<"Underflow"<<endl; }else{ q[f++] = 0; } } int front() { if(r-f<=0){ return -1; }else{ return q[f]; } } }; int main() { int n,m; cin>>n>>m; Queue q(n); for(int i=0;i<m;i++){ int x; cin>>x; switch(x){ case 1: int y; cin>>y; q.push(y); break; case 2: q.pop(); break; case 3: if(q.front()==-1){ cout<<"NULL"<<endl; }else{ cout<<q.front()<<endl; } break; } } return 0; }
[ "hys2rang@gmail.com" ]
hys2rang@gmail.com
debc17e2ce43920589bb801a38d6dd8596d3721f
711e5c8b643dd2a93fbcbada982d7ad489fb0169
/XPSP1/NT/admin/hmonitor/snapin/datapointeventcontainer.cpp
a5caa18d2e8a6133e3368f4986a01e360c095b38
[]
no_license
aurantst/windows-XP-SP1
629a7763c082fd04d3b881e0d32a1cfbd523b5ce
d521b6360fcff4294ae6c5651c539f1b9a6cbb49
refs/heads/master
2023-03-21T01:08:39.870106
2020-09-28T08:10:11
2020-09-28T08:10:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
837
cpp
// DataPointEventContainer.cpp: implementation of the CDataPointEventContainer class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "Snapin.h" #include "DataPointEventContainer.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif IMPLEMENT_DYNCREATE(CDataPointEventContainer,CEventContainer) ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CDataPointEventContainer::CDataPointEventContainer() { m_pDEStatsListener = NULL; } CDataPointEventContainer::~CDataPointEventContainer() { if( m_pDEStatsListener ) { delete m_pDEStatsListener; m_pDEStatsListener = NULL; } }
[ "112426112@qq.com" ]
112426112@qq.com
6f4ae763cc8b54863a4fd0c1fe12d0b16a9e2907
c14cf1402004400e4be6f21b029c16ab22aba0af
/piece.h
a91b444c1eb327da226cb539cd310ee71521ab82
[]
no_license
MathurinCharles/chess
ff7c979ebc4242f32751b7204fbd6d395010fe08
28786948844e4b02a5f236e0b3fb57941dbfd8d3
refs/heads/master
2021-09-08T17:33:17.977550
2017-12-08T20:44:52
2017-12-08T20:44:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,832
h
#ifndef PIECE_H_ #define PIECE_H_ #include <vector> #include "global.h" #include "move.h" #include "board.h" class Board; class Move; // Abstract class for the pieces of the game. A piece has a color, a position on // the board, and a captured attribute. The only non-trivial method is getMoves() // It is reponsible to compute all possible Moves for this piece on a board. // // Typically, the 16 pieces need for the game are created at the beginning and // deleted at the end. class Piece { public: Piece(Position, Color); // returns the char used in the standard algebric notation of the piece // exception returns ' ' for a Pawn (see Pawn) virtual char notation() const = 0; // returns the char used for display of the board virtual char toChar() const = 0; // push_back in res all possible moves for this piece on board b virtual void getMoves(const Board &b, std::vector<Move *> &res) const = 0; bool isCaptured() const; void setCaptured(bool); Color getColor() const; void setPosition(Position); Position getPosition() const; virtual int heuristic() const = 0; protected: // Utility function used by the various "getMoves()" methods to transform // a starting position 'from' and a vector of position 'tos' to a vector // of moves. Each move is a basic move, with or without capture, from // position 'from' to a position in vector 'tos'. // // More specifically, the resulting moves are 'pushed back' on the vector res // given a parameter. static void positionsToMoves(const Board &g, Position from, const std::vector<Position> &tos, std::vector<Move *> &res); private: Color color_; Position position_; bool is_captured_ = false; }; #endif // PIECE_H_
[ "TMP-Charles@F214-08.e-im2ag.ujf-grenoble.fr" ]
TMP-Charles@F214-08.e-im2ag.ujf-grenoble.fr
0dae711693bf6412465d2d963911b8c2b480dcf4
5e3b9c5f17bacf6bd43ceaedc5749eacd74c055c
/evenSubstr.cpp
1c33cdae33557b641f98d1a25975e57a3c78d2f0
[]
no_license
bhaver11/fundamentals
ddf9f3eacbd467cbbaf3498379ebf880d3f0d211
c13feb43186b0768bf419e099d396dd3cd5dc438
refs/heads/master
2021-06-28T00:38:02.443004
2020-12-29T08:09:46
2020-12-29T08:11:12
189,614,845
1
0
null
null
null
null
UTF-8
C++
false
false
1,649
cpp
#include <iostream> #include<bits/stdc++.h> using namespace std; vector<int> num; int n; vector<int> l; vector<int> r; int maxEqui(int low, int high,int lof, int rof){ cout << "low : " << low << " high : " << high << " lof : " << lof << " rof : " << rof << endl; if(low>=high) return INT_MIN; if(low == high-1){ if(num[low]==num[high]) return 2; else return INT_MIN; } int mid = (low + high)/2; cout << "mid : " << mid << "," << l[mid] << "," << r[mid] << endl; if(((high-low+1)%2==0)&&(l[mid]-lof)==(r[mid+1]-rof)){ return high - low + 1; }else{ return max(maxEqui(low,mid,0,r[mid+1]), maxEqui(mid+1,high,l[mid],0)); } } int main() { //code int tests; cin >> tests; while(tests--){ string s; cin >> s; n = s.size(); cout << n << endl; vector<int> nums(n,0); vector<int> ltr(n,0); vector<int> rtl(n,0); for(int i = 0; i < n; i++){ nums[i] = s[i]-'0'; } int sum[n][n]; int maxLen = 0; for(int i = 0; i < n; i++) sum[i][i] = nums[i]; for(int len = 2; len <=n; len++){ for(int i = 0; i < n - len + 1; i++){ int j = i + len - 1; int k = len/2; //midpoint; sum[i][j] = sum[i][j-k] + sum[j-k+1][j]; if((len%2==0)&&(sum[i][j-k]==sum[j-k+1][j]) &&(len>maxLen)){ maxLen = len; } } } cout << maxLen << endl; } return 0; }
[ "bhavesy@gmail.com" ]
bhavesy@gmail.com
66ebd9d474b0e61b4374bcb8613339f76f28f570
a0037c2cc5247e453477a0e8dbd7f52115fc1ac9
/util/os/core/cpu_set_test_util.h
0024465a0c89d14195ea8aec578fb31533f88503
[ "Apache-2.0" ]
permissive
max19931/lmctfy
41cd74e5a79fead2bca381270100ff024c742753
02ab42ab4702d3cd577ada230369e3f1d7786351
refs/heads/master
2023-04-06T11:54:52.979318
2019-09-11T13:11:14
2019-09-11T13:11:14
198,486,076
0
0
NOASSERTION
2019-07-23T18:21:20
2019-07-23T18:21:20
null
UTF-8
C++
false
false
1,705
h
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // This defines some convenience functions and operator overloading to make it // easier to write more natural unit test code for cpu_set_t. #ifndef UTIL_OS_CORE_CPU_SET_TEST_UTIL_H_ #define UTIL_OS_CORE_CPU_SET_TEST_UTIL_H_ #define _GNU_SOURCE 1 // Required as per the man page for CPU_SET. #include <sched.h> #include <string> #include "base/integral_types.h" #include "util/os/core/cpu_set.h" // Equality operator. This is the minimum set of interfaces to support: // EXPECT_EQ(expected_set, set); // EXPECT_EQ(expected_int, set); // Other interfaces are not provided in order to discourage abuse. bool operator==(const cpu_set_t &lhs, const cpu_set_t &rhs); bool operator==(uint64 lhs, const cpu_set_t &rhs); // Non equality operator. This is the minimum set of interfaces to support: // EXPECT_NE(expected_set, set); // EXPECT_NE(expected_int, set); // Other interfaces are not provided in order to discourage abuse. bool operator!=(const cpu_set_t &lhs, const cpu_set_t &rhs); bool operator!=(uint64 lhs, const cpu_set_t &rhs); #endif // UTIL_OS_CORE_CPU_SET_TEST_UTIL_H_
[ "vmarmol@google.com" ]
vmarmol@google.com
e02a6e4f8b6211d633194f8dd10251f4798cd076
276b69ebb8b6fb6fcc14a3705f205ce392fac1e2
/ECDSA.cpp
2a8fe1fd514f7ade5ce2678a4258a4c25d4f3910
[ "MIT" ]
permissive
raymond-w-ko/mupbit
e88ea92253d36b4a8abbd2607770f7e03a29d39c
c16531fbd1c6ce63f00667a53c40946b59e07968
refs/heads/master
2020-06-06T10:16:31.073374
2014-02-02T05:26:31
2014-02-02T05:26:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,135
cpp
#include "StableHeaders.hpp" #include "ECDSA.hpp" const BigInt ECDSA::p( "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"); const BigInt ECDSA::a(0); const BigInt ECDSA::b(7); //const BigInt ECDSA::n( //"fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); //const BigInt ECDSA::h(1); const BigInt ECDSA::Gx( "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"); const BigInt ECDSA::Gy( "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"); BigInt ECDSA::ModP(BigInt num) { if (num < BigInt::ZERO) { auto qr = num / ECDSA::p; num = qr.second + ECDSA::p; } if (num > ECDSA::p) { auto qr = num / ECDSA::p; num = qr.second; } return num; } // http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm BigInt ECDSA::Inverse(BigInt num) { assert(num > 0 && num < ECDSA::p); BigInt t = BigInt::ZERO; BigInt newt = BigInt::ONE; BigInt r = ECDSA::p; BigInt newr = num; BigInt tmp(0); while (newr != BigInt::ZERO) { auto qr = r / newr; BigInt quotient = qr.first; tmp = newr; newr = r - (quotient * newr); r = tmp; tmp = newt; newt = t - (quotient * newt); t = tmp; } assert(r <= BigInt::ONE); if (t < BigInt::ZERO) { t = t + ECDSA::p; } return t; } Point ECDSA::Add(Point P, Point Q) { Point r; BigInt numerator = Q.y - P.y; numerator = ModP(numerator); BigInt denominator = Q.x - P.x; denominator = ModP(denominator); BigInt lambda = numerator * Inverse(denominator); lambda = ModP(lambda); r.x = (lambda ^ BigInt(2)) - P.x - Q.x; r.x = ModP(r.x); r.y = (lambda * (P.x - r.x)) - P.y; r.y = ModP(r.y); return r; } Point ECDSA::Double(Point P) { Point r; BigInt numerator = BigInt(3) * (P.x ^ 2) + a; numerator = ModP(numerator); BigInt denominator = BigInt(2) * P.y; denominator = ModP(denominator); BigInt lambda = numerator * Inverse(denominator); lambda = ModP(lambda); r.x = (lambda ^ BigInt(2)) - (BigInt(2) * P.x); r.x = ModP(r.x); r.y = (lambda * (P.x - r.x)) - P.y; r.y = ModP(r.y); return r; }
[ "raymond.w.ko@gmail.com" ]
raymond.w.ko@gmail.com
0abdac621b784ec4338485e4e4bb59d46c755912
a9b6a5c382c58c8cb78ac9ca9cbcb810269739b1
/thesisTool/ThesisTool/ThesisTool.cpp
df8c3b5d048db95f54e6c8d6861d6d08825bb430
[ "BSD-3-Clause" ]
permissive
mrozemeijer/tudatBundle
13f3eb8f510115ce49470aed3aa9d886be2ff958
ceafc35a180713d8fed280aaa7755c468920e1a9
refs/heads/master
2020-04-03T05:55:10.535580
2019-05-15T12:00:30
2019-05-15T12:00:30
177,566,611
0
0
null
2019-03-25T10:44:18
2019-03-25T10:44:18
null
UTF-8
C++
false
false
25,752
cpp
/* Copyright (c) 2010-2018, Delft University of Technology * 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 Delft University of Technology nor the names of its contributors * may be used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * * Changelog * YYMMDD Author Comment * 120522 A. Ronse First creation of code. * * References * Williams, Dr. David R., "Moon Fact Sheet", NASA (National Space Science Data Center), * http://nssdc.gsfc.nasa.gov/planetary/factsheet/moonfact.html, last accessed: 22 May 2012 * * Notes * */ #include <Tudat/SimulationSetup/tudatSimulationHeader.h> #include <ThesisTool/VehicleAerodynamicCoefficients.h> #include <ThesisTool/applicationOutput.h> #include <ThesisTool/recoverymodels.h> Eigen::Vector3d my_func(int t) { return Eigen::Vector3d (1,0,0); } Eigen::Vector3d my_func2(void) { return Eigen::Vector3d (1,0,0); } int main( ) { /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////// USING STATEMENTS ////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using namespace tudat::ephemerides; using namespace tudat::interpolators; using namespace tudat::numerical_integrators; using namespace tudat::root_finders; using namespace tudat::spice_interface; using namespace tudat::simulation_setup; using namespace tudat::basic_astrodynamics; using namespace tudat::orbital_element_conversions; using namespace tudat::unit_conversions; using namespace tudat::propagators; using namespace tudat::aerodynamics; using namespace tudat::basic_mathematics; using namespace tudat::input_output; using namespace tudat::propulsion; using namespace tudat; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////// CREATE ENVIRONMENT ////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Load Spice kernels. spice_interface::loadStandardSpiceKernels( ); // Set simulation start epoch. const double simulationStartEpoch = 0.0; // Set simulation end epoch. const double simulationEndEpoch = 3100.0; // Set numerical integration fixed step size. const double fixedStepSize = 0.5; // Define simulation body settings. std::vector< std::string > bodiesToCreate; bodiesToCreate.push_back( "Earth" ); std::map< std::string, std::shared_ptr< BodySettings > > bodySettings = getDefaultBodySettings( bodiesToCreate, simulationStartEpoch - 10.0 * fixedStepSize, simulationEndEpoch + 10.0 * fixedStepSize ); bodySettings[ "Earth" ]->ephemerisSettings = std::make_shared< simulation_setup::ConstantEphemerisSettings >( Eigen::Vector6d::Zero( ), "SSB", "J2000" ); bodySettings[ "Earth" ]->rotationModelSettings->resetOriginalFrame( "J2000" ); // Create Earth object simulation_setup::NamedBodyMap bodyMap = simulation_setup::createBodies( bodySettings ); // Create vehicle objects. bodyMap[ "Vehicle" ] = std::make_shared< simulation_setup::Body >( ); bodyMap[ "First Stage" ] = std::make_shared< simulation_setup::Body >( ); bodyMap[ "Upper Stage" ] = std::make_shared< simulation_setup::Body >( ); // Define inputs std::string atmosphereFile = "USSA1976Until100kmPer100mUntil1000kmPer1000m.dat"; std::vector< aerodynamics::AtmosphereDependentVariables > dependentVariables; dependentVariables.push_back( aerodynamics::pressure_dependent_atmosphere ); dependentVariables.push_back( aerodynamics::temperature_dependent_atmosphere ); dependentVariables.push_back( aerodynamics::specific_heat_ratio_dependent_atmosphere ); dependentVariables.push_back( aerodynamics::density_dependent_atmosphere ); double specificGasConstant = 197.0; double ratioOfSpecificHeats = 1.3; interpolators::BoundaryInterpolationType boundaryHandling = interpolators::use_default_value_with_warning; double defaultExtrapolationValue = TUDAT_NAN; // Set tabulated atmosphere bodySettings[ "Earth" ]->atmosphereSettings = std::make_shared< TabulatedAtmosphereSettings >( atmosphereFile, dependentVariables, specificGasConstant, ratioOfSpecificHeats, boundaryHandling, defaultExtrapolationValue ); /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////// CREATE VEHICLE ///////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //// USER INPUTS //// BodyProperties FirstStage; BodyProperties Vehicle; BodyProperties UpperStage; bool OrbitalLauncher=false; InitialProperties InitialConditions; InitialConditions.H0=0; InitialConditions.V0=1; InitialConditions.heading=0; InitialConditions.flightpath=85; InitialConditions.latitude=0; InitialConditions.longitude=0; // Create vehicle aerodynamic coefficients Vehicle.referenceArea = 0.0607; FirstStage.referenceArea = 0.0607; UpperStage.referenceArea = 0.0607; Vehicle.InitialWetMass=324; FirstStage.InitialWetMass=324-16; UpperStage.InitialWetMass=16; Vehicle.InitialEmptyMass=100; FirstStage.InitialEmptyMass=100; UpperStage.InitialEmptyMass=16; Vehicle.constantAOA=0; FirstStage.constantAOA=0; UpperStage.constantAOA=0; // Set Which recovery System is used This can either be "Propulsive" "Parachute" "Rotor" "Winged" // FirstStage.RecoverySystem={"Propulsive","Parachute"}; Vehicle.CDfile="C:/tudatBundle/thesisTool/ThesisTool/Vehicle_CD.txt"; Vehicle.CLfile="C:/tudatBundle/thesisTool/ThesisTool/Vehicle_CL.txt"; FirstStage.CDfile="C:/tudatBundle/thesisTool/ThesisTool/Vehicle_CD.txt"; FirstStage.CLfile="C:/tudatBundle/thesisTool/ThesisTool/Vehicle_CL.txt"; UpperStage.CDfile="C:/tudatBundle/thesisTool/ThesisTool/Vehicle_CD.txt"; UpperStage.CLfile="C:/tudatBundle/thesisTool/ThesisTool/Vehicle_CL.txt"; std::string launchThrustFile="C:/tudatBundle/thesisTool/ThesisTool/ThrustValues.txt"; ///////////// SETTINGS FOR AERODYNAMICS VALUES //////////// // Define physical meaning of independent variables, in this case Mach number and angle of attack std::vector< aerodynamics::AerodynamicCoefficientsIndependentVariables > independentVariableNames; independentVariableNames.push_back( aerodynamics::mach_number_dependent ); independentVariableNames.push_back( aerodynamics::angle_of_attack_dependent ); // Define reference frame in which the loaded coefficients are defined. bool areCoefficientsInAerodynamicFrame = true; bool areCoefficientsInNegativeAxisDirection = true; ///////////// DRAG FOR ENTIRE VEHICLE ///////////////////// // Define list of files for force coefficients. Entry 0 denotes the x-direction (C ~D~/C ~X~), 1 the y-direction (C ~S~/C ~Y~) and 2 the z-direction (C ~L~/C ~Z~) std::map< int, std::string > forceCoefficientFiles1; forceCoefficientFiles1[ 0 ] = Vehicle.CDfile; // Set drag coefficient file forceCoefficientFiles1[ 2 ] = Vehicle.CLfile; // Set lift coefficient file // Load and parse files; create coefficient settings. std::shared_ptr< AerodynamicCoefficientSettings > aerodynamicCoefficientSettings1 = readTabulatedAerodynamicCoefficientsFromFiles( forceCoefficientFiles1, Vehicle.referenceArea, independentVariableNames, areCoefficientsInAerodynamicFrame,areCoefficientsInNegativeAxisDirection ); // Create and set aerodynamic coefficients bodyMap[ "Vehicle" ]->setAerodynamicCoefficientInterface( createAerodynamicCoefficientInterface( aerodynamicCoefficientSettings1, "Vehicle" ) ); std::cout << "Loaded Aerodynamic Data: Vehicle"<<std::endl; ///////////// DRAG FOR FIRST STAGE /////////////////////// // Define list of files for force coefficients. Entry 0 denotes the x-direction (C ~D~/C ~X~), 1 the y-direction (C ~S~/C ~Y~) and 2 the z-direction (C ~L~/C ~Z~) std::map< int, std::string > forceCoefficientFiles2; forceCoefficientFiles2[ 0 ] = FirstStage.CDfile; // Set drag coefficient file forceCoefficientFiles2[ 2 ] = FirstStage.CLfile; // Set lift coefficient file // Load and parse files; create coefficient settings. std::shared_ptr< AerodynamicCoefficientSettings > aerodynamicCoefficientSettings2 = readTabulatedAerodynamicCoefficientsFromFiles( forceCoefficientFiles2, FirstStage.referenceArea, independentVariableNames, areCoefficientsInAerodynamicFrame,areCoefficientsInNegativeAxisDirection ); // Create and set aerodynamic coefficients bodyMap[ "First Stage" ]->setAerodynamicCoefficientInterface( createAerodynamicCoefficientInterface( aerodynamicCoefficientSettings2, "First Stage" ) ); std::cout << "Loaded Aerodynamic Data : First Stage"<<std::endl; ///////////// DRAG FOR FIRST STAGE ///////////////////////// // Define list of files for force coefficients. Entry 0 denotes the x-direction (C ~D~/C ~X~), 1 the y-direction (C ~S~/C ~Y~) and 2 the z-direction (C ~L~/C ~Z~) std::map< int, std::string > forceCoefficientFiles3; forceCoefficientFiles3[ 0 ] = UpperStage.CDfile; // Set drag coefficient file forceCoefficientFiles3[ 2 ] = UpperStage.CLfile; // Set lift coefficient file // Load and parse files; create coefficient settings. std::shared_ptr< AerodynamicCoefficientSettings > aerodynamicCoefficientSettings3 = readTabulatedAerodynamicCoefficientsFromFiles( forceCoefficientFiles3, UpperStage.referenceArea, independentVariableNames, areCoefficientsInAerodynamicFrame,areCoefficientsInNegativeAxisDirection ); // Create and set aerodynamic coefficients bodyMap[ "Upper Stage" ]->setAerodynamicCoefficientInterface( createAerodynamicCoefficientInterface( aerodynamicCoefficientSettings3, "Upper Stage" ) ); std::cout << "Loaded Aerodynamic Data : Upper Stage"<<std::endl; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////// Recovery Models //////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// FirstStage.setFixedRecMass(); UpperStage.FixedRecMass=0; /// Creating Total Masses FirstStage.setTotalMass(); // FirstStage.setRecoveryMass(); // FirstStage.TotalMass=FirstStage.InitialWetMass+FirstStage.RecoveryMass+FirstStage.FixedRecMass; if (OrbitalLauncher==false){ UpperStage.TotalMass=UpperStage.InitialWetMass; }; Vehicle.TotalMass=FirstStage.TotalMass+UpperStage.TotalMass; bodyMap[ "Vehicle" ]->setConstantBodyMass( Vehicle.TotalMass ); bodyMap[ "First Stage" ]->setConstantBodyMass( FirstStage.TotalMass ); bodyMap[ "Upper Stage" ]->setConstantBodyMass( UpperStage.TotalMass ); // Finalize body creation. setGlobalFrameBodyEphemerides( bodyMap, "SSB", "J2000" ); /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////// CREATE ACCELERATIONS ////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Define propagator settings variables. SelectedAccelerationMap accelerationMap; std::vector< std::string > bodiesToPropagate; std::vector< std::string > centralBodies; // Define data to be used for thrust as a function of time. const std::string cppFilePath( __FILE__ ); const std::string cppFolder = cppFilePath.substr( 0 , cppFilePath.find_last_of("/\\")+1 ); std::shared_ptr< FromFileDataMapSettings< Eigen::Vector3d > > thrustDataSettings = std::make_shared< FromFileDataMapSettings< Eigen::Vector3d > >( launchThrustFile ); // Direction Based Guidance std::function< Eigen::Vector3d(const double) > thrustunitfunction=my_func; std::function< Eigen::Vector3d() > bodyunitfunc=my_func2; std::make_shared<DirectionBasedForceGuidance> ( thrustunitfunction,"Vehicle",bodyunitfunc); // Define interpolator settings. std::shared_ptr< InterpolatorSettings > thrustInterpolatorSettings = std::make_shared< InterpolatorSettings >( linear_interpolator ); // Create data interpolation settings std::shared_ptr< DataInterpolationSettings< double, Eigen::Vector3d > > thrustDataInterpolatorSettings = std::make_shared< DataInterpolationSettings< double, Eigen::Vector3d > >( thrustDataSettings, thrustInterpolatorSettings ); // Define specific impulse double constantSpecificImpulse = 210.0; // Define propagation settings. std::map< std::string, std::vector< std::shared_ptr< AccelerationSettings > > > accelerationsOfVehicle; accelerationsOfVehicle[ "Vehicle" ].push_back( std::make_shared< ThrustAccelerationSettings >( thrustDataInterpolatorSettings, constantSpecificImpulse, lvlh_thrust_frame, "Earth" ) ); std::cout << "Thrust Loaded"<<std::endl; accelerationsOfVehicle[ "Earth" ].push_back( std::make_shared< SphericalHarmonicAccelerationSettings >( 4, 0 ) ); accelerationsOfVehicle[ "Earth" ].push_back( std::make_shared< AccelerationSettings >( aerodynamic ) ); accelerationMap[ "Vehicle" ] = accelerationsOfVehicle; bodiesToPropagate.push_back( "Vehicle" ); centralBodies.push_back( "Earth" ); // Create acceleration models and propagation settings. basic_astrodynamics::AccelerationMap accelerationModelMap = createAccelerationModelsMap( bodyMap, accelerationMap, bodiesToPropagate, centralBodies ); bodyMap.at( "Vehicle" )->getFlightConditions( )->getAerodynamicAngleCalculator( )->setOrientationAngleFunctions( [=]( ){ return Vehicle.constantAOA; } ); std::cout << "Acceleration Map Set"<<std::endl; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////// CREATE PROPAGATION SETTINGS //////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Set initial conditions for the vehicle satellite that will be propagated in this simulation. // The initial conditions are given in Keplerian elements and later on converted to Cartesian // elements. // Set Initial location of the vehicle Eigen::Vector6d InitialLaunchState; InitialLaunchState( SphericalOrbitalStateElementIndices::radiusIndex ) = spice_interface::getAverageRadius( "Earth" ) + InitialConditions.H0; InitialLaunchState( SphericalOrbitalStateElementIndices::latitudeIndex ) = unit_conversions::convertDegreesToRadians( InitialConditions.latitude ); InitialLaunchState( SphericalOrbitalStateElementIndices::longitudeIndex ) = unit_conversions::convertDegreesToRadians( InitialConditions.longitude ); InitialLaunchState( SphericalOrbitalStateElementIndices::speedIndex ) = InitialConditions.V0; InitialLaunchState( SphericalOrbitalStateElementIndices::flightPathIndex ) = unit_conversions::convertDegreesToRadians( InitialConditions.flightpath ); InitialLaunchState( SphericalOrbitalStateElementIndices::headingAngleIndex ) = unit_conversions::convertDegreesToRadians( InitialConditions.heading ); // Convert apollo state from spherical elements to Cartesian elements. Eigen::Vector6d systemInitialState = convertSphericalOrbitalToCartesianState( InitialLaunchState ); std::cout << "Initial Conditions Set"<<std::endl; // Convert the state to the global (inertial) frame. std::shared_ptr< ephemerides::RotationalEphemeris > earthRotationalEphemeris = bodyMap.at( "Earth" )->getRotationalEphemeris( ); systemInitialState = transformStateToGlobalFrame( systemInitialState, simulationStartEpoch, earthRotationalEphemeris ); // Define propagation termination conditions (when altitude is 0m). std::shared_ptr< SingleDependentVariableSaveSettings > terminationDependentVariable = std::make_shared< SingleDependentVariableSaveSettings >( altitude_dependent_variable, "Vehicle", "Earth" ); std::shared_ptr< PropagationTerminationSettings > terminationSettings = std::make_shared < propagators::PropagationDependentVariableTerminationSettings> (terminationDependentVariable,-1e3,true); // Define settings for propagation of translational dynamics. std::shared_ptr< TranslationalStatePropagatorSettings< double > > translationalPropagatorSettings = std::make_shared< TranslationalStatePropagatorSettings< double > >( centralBodies, accelerationModelMap, bodiesToPropagate, systemInitialState, terminationSettings ); // Create mass rate models std::shared_ptr< MassRateModelSettings > massRateModelSettings = std::make_shared< FromThrustMassModelSettings >( true ); std::map< std::string, std::shared_ptr< basic_astrodynamics::MassRateModel > > massRateModels; massRateModels[ "Vehicle" ] = createMassRateModel( "Vehicle", massRateModelSettings, bodyMap, accelerationModelMap ); // Create settings for propagating the mass of the vehicle. std::vector< std::string > bodiesWithMassToPropagate; bodiesWithMassToPropagate.push_back( "Vehicle" ); Eigen::VectorXd initialBodyMasses = Eigen::VectorXd( 1 ); initialBodyMasses( 0 ) = Vehicle.TotalMass; std::shared_ptr< SingleArcPropagatorSettings< double > > massPropagatorSettings = std::make_shared< MassPropagatorSettings< double > >( bodiesWithMassToPropagate, massRateModels, initialBodyMasses, terminationSettings ); // Define list of dependent variables to save. std::vector< std::shared_ptr< SingleDependentVariableSaveSettings > > dependentVariablesList; dependentVariablesList.push_back( std::make_shared< SingleAccelerationDependentVariableSaveSettings >( basic_astrodynamics::thrust_acceleration, "Vehicle", "Vehicle", 1 ) ); dependentVariablesList.push_back( std::make_shared< SingleDependentVariableSaveSettings >( lvlh_to_inertial_frame_rotation_dependent_variable, "Vehicle", "Earth" ) ); dependentVariablesList.push_back( std::make_shared< SingleDependentVariableSaveSettings >(mach_number_dependent_variable, "Vehicle" ) ); dependentVariablesList.push_back( std::make_shared< SingleDependentVariableSaveSettings >(total_acceleration_dependent_variable, "Vehicle" ) ); dependentVariablesList.push_back( std::make_shared< SingleDependentVariableSaveSettings >(altitude_dependent_variable,"Vehicle","Earth")); // Create object with list of dependent variables std::shared_ptr< DependentVariableSaveSettings > dependentVariablesToSave = std::make_shared< DependentVariableSaveSettings >( dependentVariablesList ); // Create list of propagation settings. std::vector< std::shared_ptr< SingleArcPropagatorSettings< double > > > propagatorSettingsVector; propagatorSettingsVector.push_back( translationalPropagatorSettings ); propagatorSettingsVector.push_back( massPropagatorSettings ); // Create propagation settings for mass and translational dynamics concurrently std::shared_ptr< PropagatorSettings< > > propagatorSettings = std::make_shared< MultiTypePropagatorSettings< double > >( propagatorSettingsVector, terminationSettings, dependentVariablesToSave ); // Define integrator settings std::shared_ptr< IntegratorSettings< > > integratorSettings = std::make_shared< IntegratorSettings< > >( rungeKutta4, 0.0, fixedStepSize); std::cout << "Propagation properties set"<<std::endl; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////// PROPAGATE //////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Create simulation object and propagate dynamics. SingleArcDynamicsSimulator< > dynamicsSimulator(bodyMap, integratorSettings, propagatorSettings ); std::cout << "Propagation Complete"<<std::endl; std::map< double, Eigen::VectorXd > integrationResult = dynamicsSimulator.getEquationsOfMotionNumericalSolution( ); std::map< double, Eigen::VectorXd > dependentVariableResult = dynamicsSimulator.getDependentVariableHistory( ); /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////// PROVIDE OUTPUT TO CONSOLE AND FILES ////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// std::string outputSubFolder = "Results/"; Eigen::VectorXd finalIntegratedState = ( --integrationResult.end( ) )->second; // Print the position (in km) and the velocity (in km/s) at t = 0. std::cout << "Propagation Information" << std::endl << "The initial position vector of the vehicle is [km]:" << std::endl << systemInitialState.segment( 0, 3 ) / 1E3 << std::endl << "The initial velocity vector of the vehicle is [km/s]:" << std::endl << systemInitialState.segment( 3, 3 ) / 1E3 << std::endl; // Print the position (in km) and the velocity (in km/s) at t = 100. std::cout << "After " << 100 << " seconds, the position vector of the vehicle is [km]:" << std::endl << finalIntegratedState.segment( 0, 3 ) / 1E3 << std::endl << "And the velocity vector of the vehicle is [km/s]:" << std::endl << finalIntegratedState.segment( 3, 3 ) / 1E3 << std::endl; // Write satellite propagation history to file. input_output::writeDataMapToTextFile( dependentVariableResult, "DependentVariableOutput.dat", tudat_applications::getOutputPath( ) + outputSubFolder, "", std::numeric_limits< double >::digits10, std::numeric_limits< double >::digits10, "," ); // Write satellite propagation history to file. input_output::writeDataMapToTextFile( integrationResult, "PropagationOutput.dat", tudat_applications::getOutputPath( ) + outputSubFolder, "", std::numeric_limits< double >::digits10, std::numeric_limits< double >::digits10, "," ); // Final statement. // The exit code EXIT_SUCCESS indicates that the program was successfully executed. return EXIT_SUCCESS; }
[ "mark.rozemeijer@gmail.com" ]
mark.rozemeijer@gmail.com
c046d7b823bde864aa871ba0bfbb9105fbe6b753
d32424b20ae663a143464a9277f8090bd017a7f6
/leetcode/393-UTF8Validation.cpp
4cdc2560bcf62fc7e49eef91eaf144c75358508f
[]
no_license
Vesion/Misirlou
a8df716c17a3072e5cf84b5e279c06e2eac9e6a7
95274c8ccb3b457d5e884bf26948b03967b40b32
refs/heads/master
2023-05-01T10:05:40.709033
2023-04-22T18:41:29
2023-04-22T18:43:05
51,061,447
1
0
null
null
null
null
UTF-8
C++
false
false
717
cpp
#include <iostream> #include <algorithm> #include <vector> #include <string> using namespace std; class Solution { public: bool validUtf8(vector<int>& data) { int c = 0; for (int d : data) { if (c == 0) { if ((d >> 3) == 0b11110) c = 3; else if ((d >> 4) == 0b1110) c = 2; else if ((d >> 5) == 0b110) c = 1; else if ((d >> 7) != 0) return false; } else { if ((d >> 6) != 0b10) return false; --c; } } return c == 0; } }; int main() { Solution s; vector<int> data = {197, 130, 1}; cout << s.validUtf8(data) << endl; return 0; }
[ "xuxiang19930924@126.com" ]
xuxiang19930924@126.com
d0373f7ba3aa1c819c601081cc6f24643ff5fa84
f84802f4869abda0bc4e95acf276fbb5c7fb066c
/Project/Project/Source.cpp
0c06e4ccdb586bf5df315dd52e1044d627f4e8e9
[]
no_license
minhhungft9/LearningCPP
2e22518dac5a037f556e10a2d9fe91175e0fbd69
f551b0fad5cbc2751522460b28cf8e40185e5b24
refs/heads/master
2022-03-22T08:02:02.626007
2019-12-22T16:35:17
2019-12-22T16:35:17
103,042,506
0
0
null
null
null
null
UTF-8
C++
false
false
148
cpp
#ifndef MENU_H #define MENU_H #include "menu.h" #endif int main() { Menu menu; menu.printMenu(); menu.handleCommand(); cin.get(); return 0; }
[ "minhhungft9@gmail.com" ]
minhhungft9@gmail.com
bca87c1e06d7a01474544ca7e13e96833029d113
22896ebba2e2030e7264e89a462f4e05513f31db
/Search_in_Rotated_Sorted_Array_II/stdafx.cpp
041a05470846bb9940dfdec5f585d23064384b29
[]
no_license
kennethhu418/LeetCode_Practice
9b56daf7cdef8c845d3a5d7a173a8ac8274e472e
f2303b89b1c8a9dfd947bce795e088b7dbc56196
refs/heads/master
2021-01-10T20:39:35.487442
2014-10-11T13:57:57
2014-10-11T13:57:57
null
0
0
null
null
null
null
GB18030
C++
false
false
286
cpp
// stdafx.cpp : 只包括标准包含文件的源文件 // Search_in_Rotated_Sorted_Array_II.pch 将作为预编译头 // stdafx.obj 将包含预编译类型信息 #include "stdafx.h" // TODO: 在 STDAFX.H 中 // 引用任何所需的附加头文件,而不是在此文件中引用
[ "dragon418@126.com" ]
dragon418@126.com
59138d6cbeaa05d0f02c63fa66feac8b1b2f26b4
3ae3b4fa0286228642edbda8c8ed3f0d37664323
/Project7/Project7/소스.cpp
95e4c7834281a1798ba92a108b8e8bbacb32eeb1
[]
no_license
KNDG01001/grade-1
b06d105dd09b5ca0fe81d256a6ace96b4160db13
c6f56eb6c812bc5cc0300ab000a4d285f5d4621d
refs/heads/master
2023-01-09T09:45:02.457267
2020-11-01T06:02:42
2020-11-01T06:02:42
279,789,135
0
0
null
null
null
null
UHC
C++
false
false
250
cpp
#include <stdio.h> #include <math.h> #pragma warning(disable : 4996) int main(void) { int i, a; printf("카운터의 초기값을 입력하시오."); scanf("%d", &a); for (i = a; i >= 0; i--) { if (i == 0) break; printf("%d ",i); } }
[ "ydk2001524@gmail.com" ]
ydk2001524@gmail.com
3fb8f06adb4ea9e37048610502941b88b8471e99
67e5d8bdbbeb0d093f21d48f0e6b724339594a8e
/reflow/dtls_wrapper/DtlsSocket.cxx
a40e4fcc67664533fdc676e8a53bf300e8ac6981
[ "BSD-3-Clause", "VSL-1.0", "BSD-2-Clause" ]
permissive
heibao111728/resiprocate-1.8.14
7e5e46a04bfef72e95852a598774cb8d5aa0d699
f8ddf70a6b7620fb535baec04901a4912172d4ed
refs/heads/master
2020-04-16T01:48:14.942715
2019-11-09T14:29:12
2019-11-09T14:29:12
145,299,918
1
0
null
null
null
null
UTF-8
C++
false
false
13,149
cxx
#ifdef HAVE_CONFIG_H #include "config.h" #endif #ifdef USE_SSL #include <iostream> #include <cassert> #include <string.h> #include "DtlsFactory.hxx" #include "DtlsSocket.hxx" #include "bf_dwrap.h" using namespace std; using namespace dtls; const int SRTP_MASTER_KEY_BASE64_LEN = SRTP_MASTER_KEY_LEN * 4 / 3; const int SRTP_MASTER_KEY_KEY_LEN = 16; const int SRTP_MASTER_KEY_SALT_LEN = 14; // Our local timers class dtls::DtlsSocketTimer : public DtlsTimer { public: DtlsSocketTimer(unsigned int seq,DtlsSocket *socket): DtlsTimer(seq),mSocket(socket){} ~DtlsSocketTimer() { } void expired() { mSocket->expired(this); } private: DtlsSocket *mSocket; }; int dummy_cb(int d, X509_STORE_CTX *x) { return 1; } DtlsSocket::DtlsSocket(std::auto_ptr<DtlsSocketContext> socketContext, DtlsFactory* factory, enum SocketType type): mSocketContext(socketContext), mFactory(factory), mReadTimer(0), mSocketType(type), mHandshakeCompleted(false) { mSocketContext->setDtlsSocket(this); assert(factory->mContext); mSsl=SSL_new(factory->mContext); assert(mSsl!=0); switch(type) { case Client: SSL_set_connect_state(mSsl); break; case Server: SSL_set_accept_state(mSsl); SSL_set_verify(mSsl,SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, dummy_cb); break; default: assert(0); } mInBio=BIO_new(BIO_f_dwrap()); BIO_push(mInBio,BIO_new(BIO_s_mem())); mOutBio=BIO_new(BIO_f_dwrap()); BIO_push(mOutBio,BIO_new(BIO_s_mem())); SSL_set_bio(mSsl,mInBio,mOutBio); } DtlsSocket::~DtlsSocket() { if(mReadTimer) mReadTimer->invalidate(); // Properly shutdown the socket and free it - note: this also free's the BIO's SSL_shutdown(mSsl); SSL_free(mSsl); } void DtlsSocket::expired(DtlsSocketTimer* timer) { forceRetransmit(); //delete timer; //assert(timer == mReadTimer); //mReadTimer = 0; } void DtlsSocket::startClient() { assert(mSocketType == Client); doHandshakeIteration(); } bool DtlsSocket::handlePacketMaybe(const unsigned char* bytes, unsigned int len) { DtlsFactory::PacketType pType=DtlsFactory::demuxPacket(bytes,len); if(pType!=DtlsFactory::dtls) return false; int r; BIO_reset(mInBio); BIO_reset(mOutBio); r=BIO_write(mInBio,bytes,len); assert(r==(int)len); // Can't happen // Note: we must catch any below exceptions--if there are any doHandshakeIteration(); return true; } void DtlsSocket::forceRetransmit() { BIO_reset(mInBio); BIO_reset(mOutBio); BIO_ctrl(mInBio,BIO_CTRL_DGRAM_SET_RECV_TIMEOUT,0,0); doHandshakeIteration(); } void DtlsSocket::doHandshakeIteration() { int r; char errbuf[1024]; int sslerr; if(mHandshakeCompleted) return; r=SSL_do_handshake(mSsl); errbuf[0]=0; ERR_error_string_n(ERR_peek_error(),errbuf,sizeof(errbuf)); // See what was written int outBioLen; unsigned char *outBioData; outBioLen=BIO_get_mem_data(mOutBio,&outBioData); // Now handle handshake errors */ switch(sslerr=SSL_get_error(mSsl,r)) { case SSL_ERROR_NONE: mHandshakeCompleted = true; mSocketContext->handshakeCompleted(); if(mReadTimer) mReadTimer->invalidate(); mReadTimer = 0; break; case SSL_ERROR_WANT_READ: // There are two cases here: // (1) We didn't get enough data. In this case we leave the // timers alone and wait for more packets. // (2) We did get a full flight and then handled it, but then // wrote some more message and now we need to flush them // to the network and now reset the timers // // If data was written then this means we got a complete // something or a retransmit so we need to reset the timer if(outBioLen) { if(mReadTimer) mReadTimer->invalidate(); mReadTimer=new DtlsSocketTimer(0,this); mFactory->mTimerContext->addTimer(mReadTimer,getReadTimeout()); } break; default: cerr << "SSL error " << sslerr << endl; mSocketContext->handshakeFailed(errbuf); // Note: need to fall through to propagate alerts, if any break; } // If mOutBio is now nonzero-length, then we need to write the // data to the network. TODO: warning, MTU issues! if(outBioLen) { //cerr << "Writing data: "; //cerr.write((char*)outBioData, outBioLen); //cerr << " length " << outBioLen << endl; mSocketContext->write(outBioData,outBioLen); } } bool DtlsSocket::getRemoteFingerprint(char *fprint) { X509 *x; x=SSL_get_peer_certificate(mSsl); if(!x) // No certificate return false; computeFingerprint(x,fprint); return true; } bool DtlsSocket::checkFingerprint(const char* fingerprint, unsigned int len) { char fprint[100]; if(getRemoteFingerprint(fprint)==false) return false; // used to be strncasecmp if(strncmp(fprint,fingerprint,len)){ cerr << "Fingerprint mismatch, got " << fprint << "expecting " << fingerprint << endl; return false; } return true; } void DtlsSocket::getMyCertFingerprint(char *fingerprint) { mFactory->getMyCertFingerprint(fingerprint); } SrtpSessionKeys DtlsSocket::getSrtpSessionKeys() { //TODO: probably an exception candidate assert(mHandshakeCompleted); SrtpSessionKeys keys; memset(&keys, 0x00, sizeof(keys)); keys.clientMasterKey = new unsigned char[SRTP_MASTER_KEY_KEY_LEN]; keys.clientMasterKeyLen = 0; keys.clientMasterSalt = new unsigned char[SRTP_MASTER_KEY_SALT_LEN]; keys.clientMasterSaltLen = 0; keys.serverMasterKey = new unsigned char[SRTP_MASTER_KEY_KEY_LEN]; keys.serverMasterKeyLen = 0; keys.serverMasterSalt = new unsigned char[SRTP_MASTER_KEY_SALT_LEN]; keys.serverMasterSaltLen = 0; unsigned char material[SRTP_MASTER_KEY_LEN << 1]; if (!SSL_export_keying_material( mSsl, material, sizeof(material), "EXTRACTOR-dtls_srtp", 19, NULL, 0, 0)) { return keys; } size_t offset = 0; memcpy(keys.clientMasterKey, &material[offset], SRTP_MASTER_KEY_KEY_LEN); offset += SRTP_MASTER_KEY_KEY_LEN; memcpy(keys.serverMasterKey, &material[offset], SRTP_MASTER_KEY_KEY_LEN); offset += SRTP_MASTER_KEY_KEY_LEN; memcpy(keys.clientMasterSalt, &material[offset], SRTP_MASTER_KEY_SALT_LEN); offset += SRTP_MASTER_KEY_SALT_LEN; memcpy(keys.serverMasterSalt, &material[offset], SRTP_MASTER_KEY_SALT_LEN); offset += SRTP_MASTER_KEY_SALT_LEN; keys.clientMasterKeyLen = SRTP_MASTER_KEY_KEY_LEN; keys.serverMasterKeyLen = SRTP_MASTER_KEY_KEY_LEN; keys.clientMasterSaltLen = SRTP_MASTER_KEY_SALT_LEN; keys.serverMasterSaltLen = SRTP_MASTER_KEY_SALT_LEN; return keys; } SRTP_PROTECTION_PROFILE* DtlsSocket::getSrtpProfile() { //TODO: probably an exception candidate assert(mHandshakeCompleted); return SSL_get_selected_srtp_profile(mSsl); } // Fingerprint is assumed to be long enough void DtlsSocket::computeFingerprint(X509 *cert, char *fingerprint) { unsigned char md[EVP_MAX_MD_SIZE]; int r; unsigned int i,n; //r=X509_digest(cert,EVP_sha1(),md,&n); r=X509_digest(cert,EVP_sha256(),md,&n); // !slg! TODO - is sha1 vs sha256 supposed to come from DTLS handshake? fixing to to SHA-256 for compatibility with current web-rtc implementations assert(r==1); for(i=0;i<n;i++) { sprintf(fingerprint,"%02X",md[i]); fingerprint+=2; if(i<(n-1)) *fingerprint++=':'; else *fingerprint++=0; } } //TODO: assert(0) into exception, as elsewhere void DtlsSocket::createSrtpSessionPolicies(srtp_policy_t& outboundPolicy, srtp_policy_t& inboundPolicy) { assert(mHandshakeCompleted); /* we assume that the default profile is in effect, for now */ srtp_profile_t profile = srtp_profile_aes128_cm_sha1_80; int key_len = srtp_profile_get_master_key_length(profile); int salt_len = srtp_profile_get_master_salt_length(profile); /* get keys from srtp_key and initialize the inbound and outbound sessions */ uint8_t *client_master_key_and_salt=new uint8_t[SRTP_MAX_KEY_LEN]; uint8_t *server_master_key_and_salt=new uint8_t[SRTP_MAX_KEY_LEN]; srtp_policy_t client_policy; memset(&client_policy, 0, sizeof(srtp_policy_t)); client_policy.window_size = 128; client_policy.allow_repeat_tx = 1; srtp_policy_t server_policy; memset(&server_policy, 0, sizeof(srtp_policy_t)); server_policy.window_size = 128; server_policy.allow_repeat_tx = 1; SrtpSessionKeys srtp_key = getSrtpSessionKeys(); /* set client_write key */ client_policy.key = client_master_key_and_salt; if (srtp_key.clientMasterKeyLen != key_len) { cout << "error: unexpected client key length" << endl; assert(0); } if (srtp_key.clientMasterSaltLen != salt_len) { cout << "error: unexpected client salt length" << endl; assert(0); } memcpy(client_master_key_and_salt, srtp_key.clientMasterKey, key_len); memcpy(client_master_key_and_salt + key_len, srtp_key.clientMasterSalt, salt_len); //cout << "client master key and salt: " << // octet_string_hex_string(client_master_key_and_salt, key_len + salt_len) << endl; /* initialize client SRTP policy from profile */ err_status_t err = crypto_policy_set_from_profile_for_rtp(&client_policy.rtp, profile); if (err) assert(0); err = crypto_policy_set_from_profile_for_rtcp(&client_policy.rtcp, profile); if (err) assert(0); client_policy.next = NULL; /* set server_write key */ server_policy.key = server_master_key_and_salt; if (srtp_key.serverMasterKeyLen != key_len) { cout << "error: unexpected server key length" << endl; assert(0); } if (srtp_key.serverMasterSaltLen != salt_len) { cout << "error: unexpected salt length" << endl; assert(0); } memcpy(server_master_key_and_salt, srtp_key.serverMasterKey, key_len); memcpy(server_master_key_and_salt + key_len, srtp_key.serverMasterSalt, salt_len); //cout << "server master key and salt: " << // octet_string_hex_string(server_master_key_and_salt, key_len + salt_len) << endl; /* initialize server SRTP policy from profile */ err = crypto_policy_set_from_profile_for_rtp(&server_policy.rtp, profile); if (err) assert(0); err = crypto_policy_set_from_profile_for_rtcp(&server_policy.rtcp, profile); if (err) assert(0); server_policy.next = NULL; if (mSocketType == Client) { client_policy.ssrc.type = ssrc_any_outbound; outboundPolicy = client_policy; server_policy.ssrc.type = ssrc_any_inbound; inboundPolicy = server_policy; } else { server_policy.ssrc.type = ssrc_any_outbound; outboundPolicy = server_policy; client_policy.ssrc.type = ssrc_any_inbound; inboundPolicy = client_policy; } /* zeroize the input keys (but not the srtp session keys that are in use) */ //not done...not much of a security whole imho...the lifetime of these seems odd though // memset(client_master_key_and_salt, 0x00, SRTP_MAX_KEY_LEN); // memset(server_master_key_and_salt, 0x00, SRTP_MAX_KEY_LEN); // memset(&srtp_key, 0x00, sizeof(srtp_key)); } // Wrapper for currently nonexistent OpenSSL fxn int DtlsSocket::getReadTimeout() { return 500; } #endif /* ==================================================================== Copyright (c) 2007-2008, Eric Rescorla and Derek MacDonald 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. None of the contributors names 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. ==================================================================== */
[ "heibao111728@126.com" ]
heibao111728@126.com
099402e05be1c36c6f03d751b635728e74e2becc
51c8fabe609cc7de64dc1aa8a0c702d1ae4f61fe
/63.CameraEx2_Rotation/Classes/HelloWorldScene.h
cefa80ebc5f69c9126a010ac802389682d3a7100
[]
no_license
Gasbebe/cocos2d_source
5f7720da904ff71a4951bee470b8744aab51c59d
2376f6bdb93a58ae92c0e9cbd06c0d97cd241d14
refs/heads/master
2021-01-18T22:35:30.357253
2016-05-20T08:10:55
2016-05-20T08:10:55
54,854,003
0
0
null
null
null
null
UTF-8
C++
false
false
375
h
#ifndef __HELLOWORLD_SCENE_H__ #define __HELLOWORLD_SCENE_H__ #include "cocos2d.h" class HelloWorld : public cocos2d::LayerColor { public: static cocos2d::Scene* createScene(); cocos2d::Sprite* man; virtual bool init(); virtual bool onTouchBegan(cocos2d::Touch* touch, cocos2d::Event* event); CREATE_FUNC(HelloWorld); }; #endif // __HELLOWORLD_SCENE_H__
[ "gasbebe@gmail.com" ]
gasbebe@gmail.com
0bdae3518eb3d2af9c2063dc01704416b15206bd
b36f34b6a24d019d624d1cc74f5b29062eef2ba4
/frameworks/cocos2d-x/cocos/editor-support/spine/PathAttachment.h
2492f5a198b5ba8f5f160049b4f65fd6c4c0bd90
[ "MIT" ]
permissive
zhongfq/cocos-lua
f49c1639f2c9a2a7678f9ed67e58114986ac882f
c2cf0f36ac0f0c91fb3456b555cacd8e8587be46
refs/heads/main
2023-08-17T17:13:05.705639
2023-08-17T06:06:36
2023-08-17T06:06:36
192,316,318
165
63
MIT
2023-08-14T23:59:30
2019-06-17T09:27:37
C
UTF-8
C++
false
false
2,466
h
/****************************************************************************** * Spine Runtimes License Agreement * Last updated September 24, 2021. Replaces all prior versions. * * Copyright (c) 2013-2021, Esoteric Software LLC * * Integration of the Spine Runtimes into software or otherwise creating * derivative works of the Spine Runtimes is permitted under the terms and * conditions of Section 2 of the Spine Editor License Agreement: * http://esotericsoftware.com/spine-editor-license * * Otherwise, it is permitted to integrate the Spine Runtimes into software * or otherwise create derivative works of the Spine Runtimes (collectively, * "Products"), provided that each user of the Products must obtain their own * Spine Editor license and redistribution of the Products in any form must * include this license and copyright notice. * * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) 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 * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ #ifndef Spine_PathAttachment_h #define Spine_PathAttachment_h #include <spine/VertexAttachment.h> #include <spine/Color.h> namespace spine { class SP_API PathAttachment : public VertexAttachment { friend class SkeletonBinary; friend class SkeletonJson; RTTI_DECL public: explicit PathAttachment(const String &name); /// The length in the setup pose from the start of the path to the end of each curve. Vector<float> &getLengths(); bool isClosed(); void setClosed(bool inValue); bool isConstantSpeed(); void setConstantSpeed(bool inValue); Color &getColor(); virtual Attachment *copy(); private: Vector<float> _lengths; bool _closed; bool _constantSpeed; Color _color; }; } #endif /* Spine_PathAttachment_h */
[ "codetypes@gmail.com" ]
codetypes@gmail.com
26ccdeb5d95646d8e351a07f1c8f7f747c4c45f3
72e77a6bb54f1ef043cc4a9208b65a115fe3fee4
/source/include/opcodes/vector/op_vec_ssub_impl_l0.hpp
9b59e1825b31d850aa4e8efeaf1caf1c788004e0
[]
no_license
0xABADCAFE/exvm
f69b20be6cd2c506d354e8c8ea319fd919f4b386
7b73989f0241d408e50a085d53a67de1c135560d
refs/heads/master
2021-06-03T02:30:28.032960
2020-05-07T16:43:34
2020-05-07T16:43:34
93,942,045
5
0
null
2018-04-10T13:53:12
2017-06-10T13:50:30
C++
UTF-8
C++
false
false
2,135
hpp
//****************************************************************************// //** **// //** File: op_vec_ssub_impl.hpp **// //** Description: Scalar on Vector Subtraction **// //** Comment(s): Internal developer version only **// //** Library: **// //** Created: 2017-08-15 **// //** Author(s): Karl Churchill **// //** Note(s): **// //** Copyright: (C)1996 - , eXtropia Studios **// //** All Rights Reserved. **// //** **// //****************************************************************************// // Integer _DEFINE_OP(VSSUB_I8) { // Super naive reference implementation sint8 val = vm->gpr[VARG3].s8(); sint8* src = vm->gpr[VARG2].pS8(); sint8* dst = vm->gpr[VARG1].pS8(); uint32 i = vm->gpr[VARG0].u32(); while (i--) { *dst++ = *src++ - val; } } _END_OP //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// _DEFINE_OP(VSSUB_I16) { // Super naive reference implementation sint16 val = vm->gpr[VARG3].s16(); sint16* src = vm->gpr[VARG2].pS16(); sint16* dst = vm->gpr[VARG1].pS16(); uint32 i = vm->gpr[VARG0].u32(); while (i--) { *dst++ = *src++ - val; } } _END_OP //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// _DEFINE_OP(VSSUB_I32) { // Super naive reference implementation sint32 val = vm->gpr[VARG3].s32(); sint32* src = vm->gpr[VARG2].pS32(); sint32* dst = vm->gpr[VARG1].pS32(); uint32 i = vm->gpr[VARG0].u32(); while (i--) { *dst++ = *src++ - val; } } _END_OP
[ "karl.churchill@gear4music.com" ]
karl.churchill@gear4music.com
997ee6b2449b8ee37357ea54c923b3accff52066
fac63d78f371afcd204ff325c88c0c14c600b1e9
/8 - Linear algebra/factorial.cpp
8dca06515ebda811a7aa26f232376ecd9f422670
[]
no_license
dawidsowa/Cpp-class
c381e5cd0939164111bcb07ab424b51a5cbec072
e603b9eeb9f3a87fdb3f7a02b40d2724f9743453
refs/heads/main
2023-05-15T04:23:47.253945
2021-06-10T06:49:17
2021-06-10T06:49:17
371,355,371
0
1
null
2021-06-07T12:11:02
2021-05-27T11:50:39
C++
UTF-8
C++
false
false
760
cpp
#include <math.h> #include <iostream> using namespace std; int n = 40; const bool recursive = false; unsigned long long int fac_i(int n) { if (n == 0) { return 1; } else { return fac_i(n - 1) * n; } } long double fac_r(int n) { if (n == 0) { return 1; } else { return fac_r(n - 1) * n; } } int main() { int n; cout << "n = "; cin >> n; if (recursive) { if (n > 20) { cout << n << "! = " << fac_r(n); } else { cout << n << "! = " << fac_i(n); } } else { if long double fac = 1; for (int i = 1; i <= n; i++) { fac *= i; } cout << n << "! = " << fac; } return 0; }
[ "dawid_sowa@posteo.net" ]
dawid_sowa@posteo.net
73a4eee446fa53ce6392f5155848c0ba3111e86b
98dabe0873e41cadc67797b2b38c55be56b7b16e
/chetnoye.cpp
e888dfce9634dcf3c39011983c1f0037deb64a03
[]
no_license
bulsati/hw
b9ae74916b2ac8db637dc943aefd451f0be688ad
f00b4ce14795458b9dab947970e252a13b3d76ab
refs/heads/main
2023-08-07T10:19:23.622264
2021-10-12T00:14:10
2021-10-12T00:14:10
415,725,847
0
0
null
null
null
null
UTF-8
C++
false
false
126
cpp
#include <iostream> using namespace std; int main() { int a; cin >> a; cout << ((a / 2) + 1) * 2; return 0; }
[ "akhmetsharif@gmail.com" ]
akhmetsharif@gmail.com
08b9b53d48b4b115f23ca030d37829a371eba6ab
cc40d6b758088e9ba56641e91c35e1ea85b64e07
/third_party/spirv-tools/test/opt/loop_optimizations/fusion_illegal.cpp
79121a6bd3f562df763cebc2c7c16a70fd32ee25
[ "LicenseRef-scancode-generic-cla", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
chinmaygarde/filament
1091b664f1ba4cc9b63c31c73f63ec8b449acd22
030ba324e0db96dfd31c0c1e016ae44001d92b00
refs/heads/master
2020-03-26T00:25:48.310901
2018-08-13T22:26:23
2018-08-13T22:26:23
144,320,013
1
0
Apache-2.0
2018-08-10T18:29:11
2018-08-10T18:29:11
null
UTF-8
C++
false
false
47,091
cpp
// Copyright (c) 2018 Google LLC. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <gmock/gmock.h> #include <algorithm> #include <iterator> #include <memory> #include <string> #include <vector> #include "../pass_fixture.h" #include "opt/loop_descriptor.h" #include "opt/loop_fusion.h" namespace spvtools { namespace opt { namespace { using FusionIllegalTest = PassTest<::testing::Test>; /* Generated from the following GLSL + --eliminate-local-multi-store #version 440 core void main() { int[10] a; int[10] b; int[10] c; // Illegal, loop-independent dependence will become a // backward loop-carried antidependence for (int i = 0; i < 10; i++) { a[i] = b[i] + 1; } for (int i = 0; i < 10; i++) { c[i] = a[i+1] + 2; } } */ TEST_F(FusionIllegalTest, PositiveDistanceCreatedRAW) { std::string text = R"( OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %4 "main" OpExecutionMode %4 OriginUpperLeft OpSource GLSL 440 OpName %4 "main" OpName %8 "i" OpName %23 "a" OpName %25 "b" OpName %34 "i" OpName %42 "c" %2 = OpTypeVoid %3 = OpTypeFunction %2 %6 = OpTypeInt 32 1 %7 = OpTypePointer Function %6 %9 = OpConstant %6 0 %16 = OpConstant %6 10 %17 = OpTypeBool %19 = OpTypeInt 32 0 %20 = OpConstant %19 10 %21 = OpTypeArray %6 %20 %22 = OpTypePointer Function %21 %29 = OpConstant %6 1 %48 = OpConstant %6 2 %4 = OpFunction %2 None %3 %5 = OpLabel %8 = OpVariable %7 Function %23 = OpVariable %22 Function %25 = OpVariable %22 Function %34 = OpVariable %7 Function %42 = OpVariable %22 Function OpStore %8 %9 OpBranch %10 %10 = OpLabel %53 = OpPhi %6 %9 %5 %33 %13 OpLoopMerge %12 %13 None OpBranch %14 %14 = OpLabel %18 = OpSLessThan %17 %53 %16 OpBranchConditional %18 %11 %12 %11 = OpLabel %27 = OpAccessChain %7 %25 %53 %28 = OpLoad %6 %27 %30 = OpIAdd %6 %28 %29 %31 = OpAccessChain %7 %23 %53 OpStore %31 %30 OpBranch %13 %13 = OpLabel %33 = OpIAdd %6 %53 %29 OpStore %8 %33 OpBranch %10 %12 = OpLabel OpStore %34 %9 OpBranch %35 %35 = OpLabel %54 = OpPhi %6 %9 %12 %52 %38 OpLoopMerge %37 %38 None OpBranch %39 %39 = OpLabel %41 = OpSLessThan %17 %54 %16 OpBranchConditional %41 %36 %37 %36 = OpLabel %45 = OpIAdd %6 %54 %29 %46 = OpAccessChain %7 %23 %45 %47 = OpLoad %6 %46 %49 = OpIAdd %6 %47 %48 %50 = OpAccessChain %7 %42 %54 OpStore %50 %49 OpBranch %38 %38 = OpLabel %52 = OpIAdd %6 %54 %29 OpStore %34 %52 OpBranch %35 %37 = OpLabel OpReturn OpFunctionEnd )"; std::unique_ptr<IRContext> context = BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, text, SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); Module* module = context->module(); EXPECT_NE(nullptr, module) << "Assembling failed for shader:\n" << text << std::endl; Function& f = *module->begin(); LoopDescriptor& ld = *context->GetLoopDescriptor(&f); EXPECT_EQ(ld.NumLoops(), 2u); auto loops = ld.GetLoopsInBinaryLayoutOrder(); LoopFusion fusion(context.get(), loops[0], loops[1]); EXPECT_TRUE(fusion.AreCompatible()); EXPECT_FALSE(fusion.IsLegal()); } /* Generated from the following GLSL + --eliminate-local-multi-store #version 440 core int func() { return 10; } void main() { int[10] a; int[10] b; // Illegal, function call for (int i = 0; i < 10; i++) { a[i] = func(); } for (int i = 0; i < 10; i++) { b[i] = a[i]; } } */ TEST_F(FusionIllegalTest, FunctionCall) { std::string text = R"( OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %4 "main" OpExecutionMode %4 OriginUpperLeft OpSource GLSL 440 OpName %4 "main" OpName %8 "func(" OpName %14 "i" OpName %28 "a" OpName %35 "i" OpName %43 "b" %2 = OpTypeVoid %3 = OpTypeFunction %2 %6 = OpTypeInt 32 1 %7 = OpTypeFunction %6 %10 = OpConstant %6 10 %13 = OpTypePointer Function %6 %15 = OpConstant %6 0 %22 = OpTypeBool %24 = OpTypeInt 32 0 %25 = OpConstant %24 10 %26 = OpTypeArray %6 %25 %27 = OpTypePointer Function %26 %33 = OpConstant %6 1 %4 = OpFunction %2 None %3 %5 = OpLabel %14 = OpVariable %13 Function %28 = OpVariable %27 Function %35 = OpVariable %13 Function %43 = OpVariable %27 Function OpStore %14 %15 OpBranch %16 %16 = OpLabel %51 = OpPhi %6 %15 %5 %34 %19 OpLoopMerge %18 %19 None OpBranch %20 %20 = OpLabel %23 = OpSLessThan %22 %51 %10 OpBranchConditional %23 %17 %18 %17 = OpLabel %30 = OpFunctionCall %6 %8 %31 = OpAccessChain %13 %28 %51 OpStore %31 %30 OpBranch %19 %19 = OpLabel %34 = OpIAdd %6 %51 %33 OpStore %14 %34 OpBranch %16 %18 = OpLabel OpStore %35 %15 OpBranch %36 %36 = OpLabel %52 = OpPhi %6 %15 %18 %50 %39 OpLoopMerge %38 %39 None OpBranch %40 %40 = OpLabel %42 = OpSLessThan %22 %52 %10 OpBranchConditional %42 %37 %38 %37 = OpLabel %46 = OpAccessChain %13 %28 %52 %47 = OpLoad %6 %46 %48 = OpAccessChain %13 %43 %52 OpStore %48 %47 OpBranch %39 %39 = OpLabel %50 = OpIAdd %6 %52 %33 OpStore %35 %50 OpBranch %36 %38 = OpLabel OpReturn OpFunctionEnd %8 = OpFunction %6 None %7 %9 = OpLabel OpReturnValue %10 OpFunctionEnd )"; std::unique_ptr<IRContext> context = BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, text, SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); Module* module = context->module(); EXPECT_NE(nullptr, module) << "Assembling failed for shader:\n" << text << std::endl; Function& f = *module->begin(); LoopDescriptor& ld = *context->GetLoopDescriptor(&f); EXPECT_EQ(ld.NumLoops(), 2u); auto loops = ld.GetLoopsInBinaryLayoutOrder(); LoopFusion fusion(context.get(), loops[0], loops[1]); EXPECT_TRUE(fusion.AreCompatible()); EXPECT_FALSE(fusion.IsLegal()); } /* Generated from the following GLSL + --eliminate-local-multi-store // 16 #version 440 core void main() { int[10][10] a; int[10][10] b; int[10][10] c; // Illegal outer. for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { c[i][j] = a[i][j] + 2; } } for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { b[i][j] = c[i+1][j] + 10; } } } */ TEST_F(FusionIllegalTest, PositiveDistanceCreatedRAWOuterLoop) { std::string text = R"( OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %4 "main" OpExecutionMode %4 OriginUpperLeft OpSource GLSL 440 OpName %4 "main" OpName %8 "i" OpName %19 "j" OpName %32 "c" OpName %35 "a" OpName %48 "i" OpName %56 "j" OpName %64 "b" %2 = OpTypeVoid %3 = OpTypeFunction %2 %6 = OpTypeInt 32 1 %7 = OpTypePointer Function %6 %9 = OpConstant %6 0 %16 = OpConstant %6 10 %17 = OpTypeBool %27 = OpTypeInt 32 0 %28 = OpConstant %27 10 %29 = OpTypeArray %6 %28 %30 = OpTypeArray %29 %28 %31 = OpTypePointer Function %30 %40 = OpConstant %6 2 %44 = OpConstant %6 1 %4 = OpFunction %2 None %3 %5 = OpLabel %8 = OpVariable %7 Function %19 = OpVariable %7 Function %32 = OpVariable %31 Function %35 = OpVariable %31 Function %48 = OpVariable %7 Function %56 = OpVariable %7 Function %64 = OpVariable %31 Function OpStore %8 %9 OpBranch %10 %10 = OpLabel %78 = OpPhi %6 %9 %5 %47 %13 OpLoopMerge %12 %13 None OpBranch %14 %14 = OpLabel %18 = OpSLessThan %17 %78 %16 OpBranchConditional %18 %11 %12 %11 = OpLabel OpStore %19 %9 OpBranch %20 %20 = OpLabel %82 = OpPhi %6 %9 %11 %45 %23 OpLoopMerge %22 %23 None OpBranch %24 %24 = OpLabel %26 = OpSLessThan %17 %82 %16 OpBranchConditional %26 %21 %22 %21 = OpLabel %38 = OpAccessChain %7 %35 %78 %82 %39 = OpLoad %6 %38 %41 = OpIAdd %6 %39 %40 %42 = OpAccessChain %7 %32 %78 %82 OpStore %42 %41 OpBranch %23 %23 = OpLabel %45 = OpIAdd %6 %82 %44 OpStore %19 %45 OpBranch %20 %22 = OpLabel OpBranch %13 %13 = OpLabel %47 = OpIAdd %6 %78 %44 OpStore %8 %47 OpBranch %10 %12 = OpLabel OpStore %48 %9 OpBranch %49 %49 = OpLabel %79 = OpPhi %6 %9 %12 %77 %52 OpLoopMerge %51 %52 None OpBranch %53 %53 = OpLabel %55 = OpSLessThan %17 %79 %16 OpBranchConditional %55 %50 %51 %50 = OpLabel OpStore %56 %9 OpBranch %57 %57 = OpLabel %80 = OpPhi %6 %9 %50 %75 %60 OpLoopMerge %59 %60 None OpBranch %61 %61 = OpLabel %63 = OpSLessThan %17 %80 %16 OpBranchConditional %63 %58 %59 %58 = OpLabel %68 = OpIAdd %6 %79 %44 %70 = OpAccessChain %7 %32 %68 %80 %71 = OpLoad %6 %70 %72 = OpIAdd %6 %71 %16 %73 = OpAccessChain %7 %64 %79 %80 OpStore %73 %72 OpBranch %60 %60 = OpLabel %75 = OpIAdd %6 %80 %44 OpStore %56 %75 OpBranch %57 %59 = OpLabel OpBranch %52 %52 = OpLabel %77 = OpIAdd %6 %79 %44 OpStore %48 %77 OpBranch %49 %51 = OpLabel OpReturn OpFunctionEnd )"; std::unique_ptr<IRContext> context = BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, text, SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); Module* module = context->module(); EXPECT_NE(nullptr, module) << "Assembling failed for shader:\n" << text << std::endl; Function& f = *module->begin(); { LoopDescriptor& ld = *context->GetLoopDescriptor(&f); EXPECT_EQ(ld.NumLoops(), 4u); auto loops = ld.GetLoopsInBinaryLayoutOrder(); auto loop_0 = loops[0]; auto loop_1 = loops[1]; auto loop_2 = loops[2]; auto loop_3 = loops[3]; { LoopFusion fusion(context.get(), loop_0, loop_1); EXPECT_FALSE(fusion.AreCompatible()); } { LoopFusion fusion(context.get(), loop_0, loop_2); EXPECT_TRUE(fusion.AreCompatible()); EXPECT_FALSE(fusion.IsLegal()); } { LoopFusion fusion(context.get(), loop_1, loop_2); EXPECT_FALSE(fusion.AreCompatible()); } { LoopFusion fusion(context.get(), loop_2, loop_3); EXPECT_FALSE(fusion.AreCompatible()); } } } /* Generated from the following GLSL + --eliminate-local-multi-store // 19 #version 440 core void main() { int[10] a; int[10] b; int[10] c; // Illegal, would create a backward loop-carried anti-dependence. for (int i = 0; i < 10; i++) { c[i] = a[i] + 1; } for (int i = 0; i < 10; i++) { a[i+1] = c[i] + 2; } } */ TEST_F(FusionIllegalTest, PositiveDistanceCreatedWAR) { std::string text = R"( OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %4 "main" OpExecutionMode %4 OriginUpperLeft OpSource GLSL 440 OpName %4 "main" OpName %8 "i" OpName %23 "c" OpName %25 "a" OpName %34 "i" %2 = OpTypeVoid %3 = OpTypeFunction %2 %6 = OpTypeInt 32 1 %7 = OpTypePointer Function %6 %9 = OpConstant %6 0 %16 = OpConstant %6 10 %17 = OpTypeBool %19 = OpTypeInt 32 0 %20 = OpConstant %19 10 %21 = OpTypeArray %6 %20 %22 = OpTypePointer Function %21 %29 = OpConstant %6 1 %47 = OpConstant %6 2 %4 = OpFunction %2 None %3 %5 = OpLabel %8 = OpVariable %7 Function %23 = OpVariable %22 Function %25 = OpVariable %22 Function %34 = OpVariable %7 Function OpStore %8 %9 OpBranch %10 %10 = OpLabel %52 = OpPhi %6 %9 %5 %33 %13 OpLoopMerge %12 %13 None OpBranch %14 %14 = OpLabel %18 = OpSLessThan %17 %52 %16 OpBranchConditional %18 %11 %12 %11 = OpLabel %27 = OpAccessChain %7 %25 %52 %28 = OpLoad %6 %27 %30 = OpIAdd %6 %28 %29 %31 = OpAccessChain %7 %23 %52 OpStore %31 %30 OpBranch %13 %13 = OpLabel %33 = OpIAdd %6 %52 %29 OpStore %8 %33 OpBranch %10 %12 = OpLabel OpStore %34 %9 OpBranch %35 %35 = OpLabel %53 = OpPhi %6 %9 %12 %51 %38 OpLoopMerge %37 %38 None OpBranch %39 %39 = OpLabel %41 = OpSLessThan %17 %53 %16 OpBranchConditional %41 %36 %37 %36 = OpLabel %43 = OpIAdd %6 %53 %29 %45 = OpAccessChain %7 %23 %53 %46 = OpLoad %6 %45 %48 = OpIAdd %6 %46 %47 %49 = OpAccessChain %7 %25 %43 OpStore %49 %48 OpBranch %38 %38 = OpLabel %51 = OpIAdd %6 %53 %29 OpStore %34 %51 OpBranch %35 %37 = OpLabel OpReturn OpFunctionEnd )"; std::unique_ptr<IRContext> context = BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, text, SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); Module* module = context->module(); EXPECT_NE(nullptr, module) << "Assembling failed for shader:\n" << text << std::endl; Function& f = *module->begin(); { LoopDescriptor& ld = *context->GetLoopDescriptor(&f); EXPECT_EQ(ld.NumLoops(), 2u); auto loops = ld.GetLoopsInBinaryLayoutOrder(); LoopFusion fusion(context.get(), loops[0], loops[1]); EXPECT_TRUE(fusion.AreCompatible()); EXPECT_FALSE(fusion.IsLegal()); } } /* Generated from the following GLSL + --eliminate-local-multi-store // 21 #version 440 core void main() { int[10] a; int[10] b; int[10] c; // Illegal, would create a backward loop-carried anti-dependence. for (int i = 0; i < 10; i++) { a[i] = b[i] + 1; } for (int i = 0; i < 10; i++) { a[i+1] = c[i+1] + 2; } } */ TEST_F(FusionIllegalTest, PositiveDistanceCreatedWAW) { std::string text = R"( OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %4 "main" OpExecutionMode %4 OriginUpperLeft OpSource GLSL 440 OpName %4 "main" OpName %8 "i" OpName %23 "a" OpName %25 "b" OpName %34 "i" OpName %44 "c" %2 = OpTypeVoid %3 = OpTypeFunction %2 %6 = OpTypeInt 32 1 %7 = OpTypePointer Function %6 %9 = OpConstant %6 0 %16 = OpConstant %6 10 %17 = OpTypeBool %19 = OpTypeInt 32 0 %20 = OpConstant %19 10 %21 = OpTypeArray %6 %20 %22 = OpTypePointer Function %21 %29 = OpConstant %6 1 %49 = OpConstant %6 2 %4 = OpFunction %2 None %3 %5 = OpLabel %8 = OpVariable %7 Function %23 = OpVariable %22 Function %25 = OpVariable %22 Function %34 = OpVariable %7 Function %44 = OpVariable %22 Function OpStore %8 %9 OpBranch %10 %10 = OpLabel %54 = OpPhi %6 %9 %5 %33 %13 OpLoopMerge %12 %13 None OpBranch %14 %14 = OpLabel %18 = OpSLessThan %17 %54 %16 OpBranchConditional %18 %11 %12 %11 = OpLabel %27 = OpAccessChain %7 %25 %54 %28 = OpLoad %6 %27 %30 = OpIAdd %6 %28 %29 %31 = OpAccessChain %7 %23 %54 OpStore %31 %30 OpBranch %13 %13 = OpLabel %33 = OpIAdd %6 %54 %29 OpStore %8 %33 OpBranch %10 %12 = OpLabel OpStore %34 %9 OpBranch %35 %35 = OpLabel %55 = OpPhi %6 %9 %12 %53 %38 OpLoopMerge %37 %38 None OpBranch %39 %39 = OpLabel %41 = OpSLessThan %17 %55 %16 OpBranchConditional %41 %36 %37 %36 = OpLabel %43 = OpIAdd %6 %55 %29 %46 = OpIAdd %6 %55 %29 %47 = OpAccessChain %7 %44 %46 %48 = OpLoad %6 %47 %50 = OpIAdd %6 %48 %49 %51 = OpAccessChain %7 %23 %43 OpStore %51 %50 OpBranch %38 %38 = OpLabel %53 = OpIAdd %6 %55 %29 OpStore %34 %53 OpBranch %35 %37 = OpLabel OpReturn OpFunctionEnd )"; std::unique_ptr<IRContext> context = BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, text, SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); Module* module = context->module(); EXPECT_NE(nullptr, module) << "Assembling failed for shader:\n" << text << std::endl; Function& f = *module->begin(); { LoopDescriptor& ld = *context->GetLoopDescriptor(&f); EXPECT_EQ(ld.NumLoops(), 2u); auto loops = ld.GetLoopsInBinaryLayoutOrder(); LoopFusion fusion(context.get(), loops[0], loops[1]); EXPECT_TRUE(fusion.AreCompatible()); EXPECT_FALSE(fusion.IsLegal()); } } /* Generated from the following GLSL + --eliminate-local-multi-store // 28 #version 440 core void main() { int[10] a; int[10] b; int sum_0 = 0; // Illegal for (int i = 0; i < 10; i++) { sum_0 += a[i]; } for (int j = 0; j < 10; j++) { sum_0 += b[j]; } } */ TEST_F(FusionIllegalTest, SameReductionVariable) { std::string text = R"( OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %4 "main" OpExecutionMode %4 OriginUpperLeft OpSource GLSL 440 OpName %4 "main" OpName %8 "sum_0" OpName %10 "i" OpName %24 "a" OpName %33 "j" OpName %41 "b" %2 = OpTypeVoid %3 = OpTypeFunction %2 %6 = OpTypeInt 32 1 %7 = OpTypePointer Function %6 %9 = OpConstant %6 0 %17 = OpConstant %6 10 %18 = OpTypeBool %20 = OpTypeInt 32 0 %21 = OpConstant %20 10 %22 = OpTypeArray %6 %21 %23 = OpTypePointer Function %22 %31 = OpConstant %6 1 %4 = OpFunction %2 None %3 %5 = OpLabel %8 = OpVariable %7 Function %10 = OpVariable %7 Function %24 = OpVariable %23 Function %33 = OpVariable %7 Function %41 = OpVariable %23 Function OpStore %8 %9 OpStore %10 %9 OpBranch %11 %11 = OpLabel %52 = OpPhi %6 %9 %5 %29 %14 %49 = OpPhi %6 %9 %5 %32 %14 OpLoopMerge %13 %14 None OpBranch %15 %15 = OpLabel %19 = OpSLessThan %18 %49 %17 OpBranchConditional %19 %12 %13 %12 = OpLabel %26 = OpAccessChain %7 %24 %49 %27 = OpLoad %6 %26 %29 = OpIAdd %6 %52 %27 OpStore %8 %29 OpBranch %14 %14 = OpLabel %32 = OpIAdd %6 %49 %31 OpStore %10 %32 OpBranch %11 %13 = OpLabel OpStore %33 %9 OpBranch %34 %34 = OpLabel %51 = OpPhi %6 %52 %13 %46 %37 %50 = OpPhi %6 %9 %13 %48 %37 OpLoopMerge %36 %37 None OpBranch %38 %38 = OpLabel %40 = OpSLessThan %18 %50 %17 OpBranchConditional %40 %35 %36 %35 = OpLabel %43 = OpAccessChain %7 %41 %50 %44 = OpLoad %6 %43 %46 = OpIAdd %6 %51 %44 OpStore %8 %46 OpBranch %37 %37 = OpLabel %48 = OpIAdd %6 %50 %31 OpStore %33 %48 OpBranch %34 %36 = OpLabel OpReturn OpFunctionEnd )"; std::unique_ptr<IRContext> context = BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, text, SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); Module* module = context->module(); EXPECT_NE(nullptr, module) << "Assembling failed for shader:\n" << text << std::endl; Function& f = *module->begin(); { LoopDescriptor& ld = *context->GetLoopDescriptor(&f); EXPECT_EQ(ld.NumLoops(), 2u); auto loops = ld.GetLoopsInBinaryLayoutOrder(); LoopFusion fusion(context.get(), loops[0], loops[1]); EXPECT_TRUE(fusion.AreCompatible()); EXPECT_FALSE(fusion.IsLegal()); } } /* Generated from the following GLSL + --eliminate-local-multi-store // 28 #version 440 core void main() { int[10] a; int[10] b; int sum_0 = 0; // Illegal for (int i = 0; i < 10; i++) { sum_0 += a[i]; } for (int j = 0; j < 10; j++) { sum_0 += b[j]; } } */ TEST_F(FusionIllegalTest, SameReductionVariableLCSSA) { std::string text = R"( OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %4 "main" OpExecutionMode %4 OriginUpperLeft OpSource GLSL 440 OpName %4 "main" OpName %8 "sum_0" OpName %10 "i" OpName %24 "a" OpName %33 "j" OpName %41 "b" %2 = OpTypeVoid %3 = OpTypeFunction %2 %6 = OpTypeInt 32 1 %7 = OpTypePointer Function %6 %9 = OpConstant %6 0 %17 = OpConstant %6 10 %18 = OpTypeBool %20 = OpTypeInt 32 0 %21 = OpConstant %20 10 %22 = OpTypeArray %6 %21 %23 = OpTypePointer Function %22 %31 = OpConstant %6 1 %4 = OpFunction %2 None %3 %5 = OpLabel %8 = OpVariable %7 Function %10 = OpVariable %7 Function %24 = OpVariable %23 Function %33 = OpVariable %7 Function %41 = OpVariable %23 Function OpStore %8 %9 OpStore %10 %9 OpBranch %11 %11 = OpLabel %52 = OpPhi %6 %9 %5 %29 %14 %49 = OpPhi %6 %9 %5 %32 %14 OpLoopMerge %13 %14 None OpBranch %15 %15 = OpLabel %19 = OpSLessThan %18 %49 %17 OpBranchConditional %19 %12 %13 %12 = OpLabel %26 = OpAccessChain %7 %24 %49 %27 = OpLoad %6 %26 %29 = OpIAdd %6 %52 %27 OpStore %8 %29 OpBranch %14 %14 = OpLabel %32 = OpIAdd %6 %49 %31 OpStore %10 %32 OpBranch %11 %13 = OpLabel OpStore %33 %9 OpBranch %34 %34 = OpLabel %51 = OpPhi %6 %52 %13 %46 %37 %50 = OpPhi %6 %9 %13 %48 %37 OpLoopMerge %36 %37 None OpBranch %38 %38 = OpLabel %40 = OpSLessThan %18 %50 %17 OpBranchConditional %40 %35 %36 %35 = OpLabel %43 = OpAccessChain %7 %41 %50 %44 = OpLoad %6 %43 %46 = OpIAdd %6 %51 %44 OpStore %8 %46 OpBranch %37 %37 = OpLabel %48 = OpIAdd %6 %50 %31 OpStore %33 %48 OpBranch %34 %36 = OpLabel OpReturn OpFunctionEnd )"; std::unique_ptr<IRContext> context = BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, text, SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); Module* module = context->module(); EXPECT_NE(nullptr, module) << "Assembling failed for shader:\n" << text << std::endl; Function& f = *module->begin(); { LoopDescriptor& ld = *context->GetLoopDescriptor(&f); EXPECT_EQ(ld.NumLoops(), 2u); auto loops = ld.GetLoopsInBinaryLayoutOrder(); LoopUtils utils_0(context.get(), loops[0]); utils_0.MakeLoopClosedSSA(); LoopFusion fusion(context.get(), loops[0], loops[1]); EXPECT_TRUE(fusion.AreCompatible()); EXPECT_FALSE(fusion.IsLegal()); } } /* Generated from the following GLSL + --eliminate-local-multi-store // 30 #version 440 core int x; void main() { int[10] a; int[10] b; // Illegal, x is unknown. for (int i = 0; i < 10; i++) { a[x] = a[i]; } for (int j = 0; j < 10; j++) { a[j] = b[j]; } } */ TEST_F(FusionIllegalTest, UnknownIndexVariable) { std::string text = R"( OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %4 "main" OpExecutionMode %4 OriginUpperLeft OpSource GLSL 440 OpName %4 "main" OpName %8 "i" OpName %23 "a" OpName %25 "x" OpName %34 "j" OpName %43 "b" %2 = OpTypeVoid %3 = OpTypeFunction %2 %6 = OpTypeInt 32 1 %7 = OpTypePointer Function %6 %9 = OpConstant %6 0 %16 = OpConstant %6 10 %17 = OpTypeBool %19 = OpTypeInt 32 0 %20 = OpConstant %19 10 %21 = OpTypeArray %6 %20 %22 = OpTypePointer Function %21 %24 = OpTypePointer Private %6 %25 = OpVariable %24 Private %32 = OpConstant %6 1 %4 = OpFunction %2 None %3 %5 = OpLabel %8 = OpVariable %7 Function %23 = OpVariable %22 Function %34 = OpVariable %7 Function %43 = OpVariable %22 Function OpStore %8 %9 OpBranch %10 %10 = OpLabel %50 = OpPhi %6 %9 %5 %33 %13 OpLoopMerge %12 %13 None OpBranch %14 %14 = OpLabel %18 = OpSLessThan %17 %50 %16 OpBranchConditional %18 %11 %12 %11 = OpLabel %26 = OpLoad %6 %25 %28 = OpAccessChain %7 %23 %50 %29 = OpLoad %6 %28 %30 = OpAccessChain %7 %23 %26 OpStore %30 %29 OpBranch %13 %13 = OpLabel %33 = OpIAdd %6 %50 %32 OpStore %8 %33 OpBranch %10 %12 = OpLabel OpStore %34 %9 OpBranch %35 %35 = OpLabel %51 = OpPhi %6 %9 %12 %49 %38 OpLoopMerge %37 %38 None OpBranch %39 %39 = OpLabel %41 = OpSLessThan %17 %51 %16 OpBranchConditional %41 %36 %37 %36 = OpLabel %45 = OpAccessChain %7 %43 %51 %46 = OpLoad %6 %45 %47 = OpAccessChain %7 %23 %51 OpStore %47 %46 OpBranch %38 %38 = OpLabel %49 = OpIAdd %6 %51 %32 OpStore %34 %49 OpBranch %35 %37 = OpLabel OpReturn OpFunctionEnd )"; std::unique_ptr<IRContext> context = BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, text, SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); Module* module = context->module(); EXPECT_NE(nullptr, module) << "Assembling failed for shader:\n" << text << std::endl; Function& f = *module->begin(); { LoopDescriptor& ld = *context->GetLoopDescriptor(&f); EXPECT_EQ(ld.NumLoops(), 2u); auto loops = ld.GetLoopsInBinaryLayoutOrder(); LoopFusion fusion(context.get(), loops[0], loops[1]); EXPECT_TRUE(fusion.AreCompatible()); EXPECT_FALSE(fusion.IsLegal()); } } /* Generated from the following GLSL + --eliminate-local-multi-store #version 440 core void main() { int[10] a; int[10] b; int sum = 0; // Illegal, accumulator used for indexing. for (int i = 0; i < 10; i++) { sum += a[i]; b[sum] = a[i]; } for (int j = 0; j < 10; j++) { b[j] = b[j]+1; } } */ TEST_F(FusionIllegalTest, AccumulatorIndexing) { std::string text = R"( OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %4 "main" OpExecutionMode %4 OriginUpperLeft OpSource GLSL 440 OpName %4 "main" OpName %8 "sum" OpName %10 "i" OpName %24 "a" OpName %30 "b" OpName %39 "j" %2 = OpTypeVoid %3 = OpTypeFunction %2 %6 = OpTypeInt 32 1 %7 = OpTypePointer Function %6 %9 = OpConstant %6 0 %17 = OpConstant %6 10 %18 = OpTypeBool %20 = OpTypeInt 32 0 %21 = OpConstant %20 10 %22 = OpTypeArray %6 %21 %23 = OpTypePointer Function %22 %37 = OpConstant %6 1 %4 = OpFunction %2 None %3 %5 = OpLabel %8 = OpVariable %7 Function %10 = OpVariable %7 Function %24 = OpVariable %23 Function %30 = OpVariable %23 Function %39 = OpVariable %7 Function OpStore %8 %9 OpStore %10 %9 OpBranch %11 %11 = OpLabel %57 = OpPhi %6 %9 %5 %29 %14 %55 = OpPhi %6 %9 %5 %38 %14 OpLoopMerge %13 %14 None OpBranch %15 %15 = OpLabel %19 = OpSLessThan %18 %55 %17 OpBranchConditional %19 %12 %13 %12 = OpLabel %26 = OpAccessChain %7 %24 %55 %27 = OpLoad %6 %26 %29 = OpIAdd %6 %57 %27 OpStore %8 %29 %33 = OpAccessChain %7 %24 %55 %34 = OpLoad %6 %33 %35 = OpAccessChain %7 %30 %29 OpStore %35 %34 OpBranch %14 %14 = OpLabel %38 = OpIAdd %6 %55 %37 OpStore %10 %38 OpBranch %11 %13 = OpLabel OpStore %39 %9 OpBranch %40 %40 = OpLabel %56 = OpPhi %6 %9 %13 %54 %43 OpLoopMerge %42 %43 None OpBranch %44 %44 = OpLabel %46 = OpSLessThan %18 %56 %17 OpBranchConditional %46 %41 %42 %41 = OpLabel %49 = OpAccessChain %7 %30 %56 %50 = OpLoad %6 %49 %51 = OpIAdd %6 %50 %37 %52 = OpAccessChain %7 %30 %56 OpStore %52 %51 OpBranch %43 %43 = OpLabel %54 = OpIAdd %6 %56 %37 OpStore %39 %54 OpBranch %40 %42 = OpLabel OpReturn OpFunctionEnd )"; std::unique_ptr<IRContext> context = BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, text, SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); Module* module = context->module(); EXPECT_NE(nullptr, module) << "Assembling failed for shader:\n" << text << std::endl; Function& f = *module->begin(); { LoopDescriptor& ld = *context->GetLoopDescriptor(&f); EXPECT_EQ(ld.NumLoops(), 2u); auto loops = ld.GetLoopsInBinaryLayoutOrder(); LoopFusion fusion(context.get(), loops[0], loops[1]); EXPECT_TRUE(fusion.AreCompatible()); EXPECT_FALSE(fusion.IsLegal()); } } /* Generated from the following GLSL + --eliminate-local-multi-store // 33 #version 440 core void main() { int[10] a; int[10] b; // Illegal, barrier. for (int i = 0; i < 10; i++) { a[i] = a[i] * 2; memoryBarrier(); } for (int j = 0; j < 10; j++) { b[j] = b[j] + 1; } } */ TEST_F(FusionIllegalTest, Barrier) { std::string text = R"( OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %4 "main" OpExecutionMode %4 OriginUpperLeft OpSource GLSL 440 OpName %4 "main" OpName %8 "i" OpName %23 "a" OpName %36 "j" OpName %44 "b" %2 = OpTypeVoid %3 = OpTypeFunction %2 %6 = OpTypeInt 32 1 %7 = OpTypePointer Function %6 %9 = OpConstant %6 0 %16 = OpConstant %6 10 %17 = OpTypeBool %19 = OpTypeInt 32 0 %20 = OpConstant %19 10 %21 = OpTypeArray %6 %20 %22 = OpTypePointer Function %21 %28 = OpConstant %6 2 %31 = OpConstant %19 1 %32 = OpConstant %19 3400 %34 = OpConstant %6 1 %4 = OpFunction %2 None %3 %5 = OpLabel %8 = OpVariable %7 Function %23 = OpVariable %22 Function %36 = OpVariable %7 Function %44 = OpVariable %22 Function OpStore %8 %9 OpBranch %10 %10 = OpLabel %53 = OpPhi %6 %9 %5 %35 %13 OpLoopMerge %12 %13 None OpBranch %14 %14 = OpLabel %18 = OpSLessThan %17 %53 %16 OpBranchConditional %18 %11 %12 %11 = OpLabel %26 = OpAccessChain %7 %23 %53 %27 = OpLoad %6 %26 %29 = OpIMul %6 %27 %28 %30 = OpAccessChain %7 %23 %53 OpStore %30 %29 OpMemoryBarrier %31 %32 OpBranch %13 %13 = OpLabel %35 = OpIAdd %6 %53 %34 OpStore %8 %35 OpBranch %10 %12 = OpLabel OpStore %36 %9 OpBranch %37 %37 = OpLabel %54 = OpPhi %6 %9 %12 %52 %40 OpLoopMerge %39 %40 None OpBranch %41 %41 = OpLabel %43 = OpSLessThan %17 %54 %16 OpBranchConditional %43 %38 %39 %38 = OpLabel %47 = OpAccessChain %7 %44 %54 %48 = OpLoad %6 %47 %49 = OpIAdd %6 %48 %34 %50 = OpAccessChain %7 %44 %54 OpStore %50 %49 OpBranch %40 %40 = OpLabel %52 = OpIAdd %6 %54 %34 OpStore %36 %52 OpBranch %37 %39 = OpLabel OpReturn OpFunctionEnd )"; std::unique_ptr<IRContext> context = BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, text, SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); Module* module = context->module(); EXPECT_NE(nullptr, module) << "Assembling failed for shader:\n" << text << std::endl; Function& f = *module->begin(); { LoopDescriptor& ld = *context->GetLoopDescriptor(&f); EXPECT_EQ(ld.NumLoops(), 2u); auto loops = ld.GetLoopsInBinaryLayoutOrder(); LoopFusion fusion(context.get(), loops[0], loops[1]); EXPECT_TRUE(fusion.AreCompatible()); EXPECT_FALSE(fusion.IsLegal()); } } /* Generated from the following GLSL + --eliminate-local-multi-store #version 440 core struct TestStruct { int[10] a; int b; }; void main() { TestStruct test_0; TestStruct test_1; for (int i = 0; i < 10; i++) { test_0.a[i] = i; } for (int j = 0; j < 10; j++) { test_0 = test_1; } } */ TEST_F(FusionIllegalTest, ArrayInStruct) { std::string text = R"( OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %4 "main" OpExecutionMode %4 OriginUpperLeft OpSource GLSL 440 OpName %4 "main" OpName %8 "i" OpName %22 "TestStruct" OpMemberName %22 0 "a" OpMemberName %22 1 "b" OpName %24 "test_0" OpName %31 "j" OpName %39 "test_1" %2 = OpTypeVoid %3 = OpTypeFunction %2 %6 = OpTypeInt 32 1 %7 = OpTypePointer Function %6 %9 = OpConstant %6 0 %16 = OpConstant %6 10 %17 = OpTypeBool %19 = OpTypeInt 32 0 %20 = OpConstant %19 10 %21 = OpTypeArray %6 %20 %22 = OpTypeStruct %21 %6 %23 = OpTypePointer Function %22 %29 = OpConstant %6 1 %47 = OpUndef %22 %4 = OpFunction %2 None %3 %5 = OpLabel %8 = OpVariable %7 Function %24 = OpVariable %23 Function %31 = OpVariable %7 Function %39 = OpVariable %23 Function OpStore %8 %9 OpBranch %10 %10 = OpLabel %43 = OpPhi %6 %9 %5 %30 %13 OpLoopMerge %12 %13 None OpBranch %14 %14 = OpLabel %18 = OpSLessThan %17 %43 %16 OpBranchConditional %18 %11 %12 %11 = OpLabel %27 = OpAccessChain %7 %24 %9 %43 OpStore %27 %43 OpBranch %13 %13 = OpLabel %30 = OpIAdd %6 %43 %29 OpStore %8 %30 OpBranch %10 %12 = OpLabel OpStore %31 %9 OpBranch %32 %32 = OpLabel %44 = OpPhi %6 %9 %12 %42 %35 OpLoopMerge %34 %35 None OpBranch %36 %36 = OpLabel %38 = OpSLessThan %17 %44 %16 OpBranchConditional %38 %33 %34 %33 = OpLabel OpStore %24 %47 OpBranch %35 %35 = OpLabel %42 = OpIAdd %6 %44 %29 OpStore %31 %42 OpBranch %32 %34 = OpLabel OpReturn OpFunctionEnd )"; std::unique_ptr<IRContext> context = BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, text, SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); Module* module = context->module(); EXPECT_NE(nullptr, module) << "Assembling failed for shader:\n" << text << std::endl; Function& f = *module->begin(); { LoopDescriptor& ld = *context->GetLoopDescriptor(&f); EXPECT_EQ(ld.NumLoops(), 2u); auto loops = ld.GetLoopsInBinaryLayoutOrder(); LoopFusion fusion(context.get(), loops[0], loops[1]); EXPECT_TRUE(fusion.AreCompatible()); EXPECT_FALSE(fusion.IsLegal()); } } /* Generated from the following GLSL + --eliminate-local-multi-store #version 450 struct P {float x,y,z;}; uniform G { int a; P b[2]; int c; } g; layout(location = 0) out float o; void main() { P p[2]; for (int i = 0; i < 2; ++i) { p = g.b; } for (int j = 0; j < 2; ++j) { o = p[g.a].x; } } */ TEST_F(FusionIllegalTest, NestedAccessChain) { std::string text = R"( OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %4 "main" %64 OpExecutionMode %4 OriginUpperLeft OpSource GLSL 450 OpName %4 "main" OpName %8 "i" OpName %20 "P" OpMemberName %20 0 "x" OpMemberName %20 1 "y" OpMemberName %20 2 "z" OpName %25 "p" OpName %26 "P" OpMemberName %26 0 "x" OpMemberName %26 1 "y" OpMemberName %26 2 "z" OpName %28 "G" OpMemberName %28 0 "a" OpMemberName %28 1 "b" OpMemberName %28 2 "c" OpName %30 "g" OpName %55 "j" OpName %64 "o" OpMemberDecorate %26 0 Offset 0 OpMemberDecorate %26 1 Offset 4 OpMemberDecorate %26 2 Offset 8 OpDecorate %27 ArrayStride 16 OpMemberDecorate %28 0 Offset 0 OpMemberDecorate %28 1 Offset 16 OpMemberDecorate %28 2 Offset 48 OpDecorate %28 Block OpDecorate %30 DescriptorSet 0 OpDecorate %64 Location 0 %2 = OpTypeVoid %3 = OpTypeFunction %2 %6 = OpTypeInt 32 1 %7 = OpTypePointer Function %6 %9 = OpConstant %6 0 %16 = OpConstant %6 2 %17 = OpTypeBool %19 = OpTypeFloat 32 %20 = OpTypeStruct %19 %19 %19 %21 = OpTypeInt 32 0 %22 = OpConstant %21 2 %23 = OpTypeArray %20 %22 %24 = OpTypePointer Function %23 %26 = OpTypeStruct %19 %19 %19 %27 = OpTypeArray %26 %22 %28 = OpTypeStruct %6 %27 %6 %29 = OpTypePointer Uniform %28 %30 = OpVariable %29 Uniform %31 = OpConstant %6 1 %32 = OpTypePointer Uniform %27 %36 = OpTypePointer Function %20 %39 = OpTypePointer Function %19 %63 = OpTypePointer Output %19 %64 = OpVariable %63 Output %65 = OpTypePointer Uniform %6 %4 = OpFunction %2 None %3 %5 = OpLabel %8 = OpVariable %7 Function %25 = OpVariable %24 Function %55 = OpVariable %7 Function OpStore %8 %9 OpBranch %10 %10 = OpLabel %72 = OpPhi %6 %9 %5 %54 %13 OpLoopMerge %12 %13 None OpBranch %14 %14 = OpLabel %18 = OpSLessThan %17 %72 %16 OpBranchConditional %18 %11 %12 %11 = OpLabel %33 = OpAccessChain %32 %30 %31 %34 = OpLoad %27 %33 %35 = OpCompositeExtract %26 %34 0 %37 = OpAccessChain %36 %25 %9 %38 = OpCompositeExtract %19 %35 0 %40 = OpAccessChain %39 %37 %9 OpStore %40 %38 %41 = OpCompositeExtract %19 %35 1 %42 = OpAccessChain %39 %37 %31 OpStore %42 %41 %43 = OpCompositeExtract %19 %35 2 %44 = OpAccessChain %39 %37 %16 OpStore %44 %43 %45 = OpCompositeExtract %26 %34 1 %46 = OpAccessChain %36 %25 %31 %47 = OpCompositeExtract %19 %45 0 %48 = OpAccessChain %39 %46 %9 OpStore %48 %47 %49 = OpCompositeExtract %19 %45 1 %50 = OpAccessChain %39 %46 %31 OpStore %50 %49 %51 = OpCompositeExtract %19 %45 2 %52 = OpAccessChain %39 %46 %16 OpStore %52 %51 OpBranch %13 %13 = OpLabel %54 = OpIAdd %6 %72 %31 OpStore %8 %54 OpBranch %10 %12 = OpLabel OpStore %55 %9 OpBranch %56 %56 = OpLabel %73 = OpPhi %6 %9 %12 %71 %59 OpLoopMerge %58 %59 None OpBranch %60 %60 = OpLabel %62 = OpSLessThan %17 %73 %16 OpBranchConditional %62 %57 %58 %57 = OpLabel %66 = OpAccessChain %65 %30 %9 %67 = OpLoad %6 %66 %68 = OpAccessChain %39 %25 %67 %9 %69 = OpLoad %19 %68 OpStore %64 %69 OpBranch %59 %59 = OpLabel %71 = OpIAdd %6 %73 %31 OpStore %55 %71 OpBranch %56 %58 = OpLabel OpReturn OpFunctionEnd )"; std::unique_ptr<IRContext> context = BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, text, SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); Module* module = context->module(); EXPECT_NE(nullptr, module) << "Assembling failed for shader:\n" << text << std::endl; Function& f = *module->begin(); { LoopDescriptor& ld = *context->GetLoopDescriptor(&f); EXPECT_EQ(ld.NumLoops(), 2u); auto loops = ld.GetLoopsInBinaryLayoutOrder(); LoopFusion fusion(context.get(), loops[0], loops[1]); EXPECT_TRUE(fusion.AreCompatible()); EXPECT_FALSE(fusion.IsLegal()); } } } // namespace } // namespace opt } // namespace spvtools
[ "romainguy@google.com" ]
romainguy@google.com
bd40a061a39e9cb97ce56b7ba22a89404449e1b7
9120a9b17d00f41e5af26b66f5b667c02d870df0
/INCLUDE/owl/statusba.h
530da58b6b3dc118e6559efb22954345edc75a58
[]
no_license
pierrebestwork/owl
dd77c095abb214a107f17686e6143907bf809930
807aa5ab4df9ee9faa35ba6df9a342a62b9bac76
refs/heads/master
2023-02-14T02:12:38.490348
2020-03-16T16:41:49
2020-03-16T16:41:49
326,663,704
0
0
null
null
null
null
UTF-8
C++
false
false
5,691
h
//---------------------------------------------------------------------------- // ObjectWindows // Copyright (c) 1992, 1996 by Borland International, All Rights Reserved // //$Revision: 1.27 $ // // Definition of class TStatusBar. //---------------------------------------------------------------------------- #if !defined(OWL_STATUSBA_H) #define OWL_STATUSBA_H #if !defined(OWL_MESSAGEB_H) # include <owl/messageb.h> #endif #if !defined(OWL_TEXTGADG_H) # include <owl/textgadg.h> #endif #if defined(BI_HAS_PRAGMA_ONCE) # pragma once #endif #if defined(BI_COMP_WATCOM) # pragma read_only_file #endif __OWL_BEGIN_NAMESPACE // Generic definitions/compiler options (eg. alignment) preceeding the // definition of classes #include <owl/preclass.h> // // class TStatusBar // ~~~~~ ~~~~~~~~~~ // Status bars have more options than a plain message bar: you can have // multiple text gadgets, different style borders, and you can reserve space // for mode indicators // class _OWLCLASS TStatusBar : public TMessageBar { public: enum TModeIndicator { ExtendSelection = 1, CapsLock = 1 << 1, NumLock = 1 << 2, ScrollLock = 1 << 3, Overtype = 1 << 4, RecordingMacro = 1 << 5, SizeGrip = 1 << 6 }; TStatusBar(TWindow* parent = 0, TGadget::TBorderStyle borderStyle = TGadget::Recessed, uint modeIndicators = 0, TFont* font = 0, //new TGadgetWindowFont(6), TModule* module = 0); // By default, adds "gadget" after the existing text gadgets and before // the mode indicator gadgets. Sets the border style to the style specified // during construction. // void Insert(TGadget& gadget, TPlacement = After, TGadget* sibling = 0); // Overriden method of TMessageBar to use our own text gadget // Set (or clear if 0) menu/command item hint text displayed in/on bar // virtual void SetHintText(LPCTSTR text); // In order for the mode indicator status to appear you must have // specified the mode when the window was constructed // bool GetModeIndicator(TModeIndicator i) const; void SetModeIndicator(TModeIndicator, bool state); void ToggleModeIndicator(TModeIndicator); struct TSpacing { TMargins::TUnits Units; int Value; TSpacing(); }; // Sets the spacing to be used between mode indicator gadgets // void SetSpacing(const TSpacing& spacing); // Control whether hint text is display over the whole window or in // a text gadget. // void SetWideHints(bool on); protected: void PositionGadget(TGadget* previous, TGadget* next, TPoint& point); TSpacing& GetSpacing(); uint GetNumModeIndicators(); uint GetModeIndicators() const; void SetModeIndicators(uint modeindicators); //!BGM SetModeIndicators is nearly useless; after construction, TStatusBar //!BGM pays almost no attention to the ModeIndicators member void EvOwlFrameSize(uint sizeType, TSize&); uint EvNCHitTest(TPoint& point); protected_data: TGadget::TBorderStyle BorderStyle; TSpacing Spacing; uint NumModeIndicators; uint ModeIndicators; uint ModeIndicatorState; bool WideHintText; private: bool GetGadgetAndStrings(TModeIndicator mode, TTextGadget*& gadget, LPCTSTR& strOn); bool IsModeIndicator(TGadget* gadget); void InsertSizeGrip(void); // Hidden to prevent accidental copying or assignment // TStatusBar(const TStatusBar&); TStatusBar& operator =(const TStatusBar&); DECLARE_CASTABLE; DECLARE_RESPONSE_TABLE(TStatusBar); }; // Generic definitions/compiler options (eg. alignment) following the // definition of classes #include <owl/posclass.h> //---------------------------------------------------------------------------- // Inline implementations // // // // Return true if the mode indicator is on. // inline bool TStatusBar::GetModeIndicator(TStatusBar::TModeIndicator i) const { return (ModeIndicatorState & i) ? 1 : 0; } // // Initialize spacing. // inline TStatusBar::TSpacing::TSpacing() { Units = TMargins::LayoutUnits; Value = 0; } // // Set the spacing between the mode indicator gadgets. // inline void TStatusBar::SetSpacing(const TStatusBar::TSpacing& spacing) { Spacing = spacing; } // // Return the spacing between the mode indicator gadgets. // inline TStatusBar::TSpacing& TStatusBar::GetSpacing() { return Spacing; } // // Return number of mode indicators on. // inline uint TStatusBar::GetNumModeIndicators() { return NumModeIndicators; } // // Return the bit flags for which indicator is on. // inline uint TStatusBar::GetModeIndicators() const { return ModeIndicators; } // // Set the bit flags for which indicator is on. // inline void TStatusBar::SetModeIndicators(uint modeindicators) { ModeIndicators = modeindicators; } // // Informs the StatusBar whether hints should be displayed in a text gadget // (on == false) or over the area of the whole statusbar (on == true). // inline void TStatusBar::SetWideHints(bool on) { WideHintText = on; } __OWL_END_NAMESPACE #endif // OWL_STATUSBA_H
[ "Chris.Driver@taxsystems.com" ]
Chris.Driver@taxsystems.com
d58d6afc3be4ac387d57cd1c2ecdbfb8ccfe2edd
961714d4298245d9c762e59c716c070643af2213
/ThirdParty-mod/java2cpp/java/security/IdentityScope.hpp
7251a0d845f2b7a055aba6808772c7478bcc13b4
[ "MIT" ]
permissive
blockspacer/HQEngine
b072ff13d2c1373816b40c29edbe4b869b4c69b1
8125b290afa7c62db6cc6eac14e964d8138c7fd0
refs/heads/master
2023-04-22T06:11:44.953694
2018-10-02T15:24:43
2018-10-02T15:24:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,374
hpp
/*================================================================================ code generated by: java2cpp author: Zoran Angelov, mailto://baldzar@gmail.com class: java.security.IdentityScope ================================================================================*/ #ifndef J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_JAVA_SECURITY_IDENTITYSCOPE_HPP_DECL #define J2CPP_JAVA_SECURITY_IDENTITYSCOPE_HPP_DECL namespace j2cpp { namespace java { namespace lang { class String; } } } namespace j2cpp { namespace java { namespace security { class PublicKey; } } } namespace j2cpp { namespace java { namespace security { class Principal; } } } namespace j2cpp { namespace java { namespace security { class Identity; } } } namespace j2cpp { namespace java { namespace util { class Enumeration; } } } #include <java/lang/String.hpp> #include <java/security/Identity.hpp> #include <java/security/Principal.hpp> #include <java/security/PublicKey.hpp> #include <java/util/Enumeration.hpp> namespace j2cpp { namespace java { namespace security { class IdentityScope; class IdentityScope : public object<IdentityScope> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) J2CPP_DECLARE_METHOD(1) J2CPP_DECLARE_METHOD(2) J2CPP_DECLARE_METHOD(3) J2CPP_DECLARE_METHOD(4) J2CPP_DECLARE_METHOD(5) J2CPP_DECLARE_METHOD(6) J2CPP_DECLARE_METHOD(7) J2CPP_DECLARE_METHOD(8) J2CPP_DECLARE_METHOD(9) J2CPP_DECLARE_METHOD(10) J2CPP_DECLARE_METHOD(11) J2CPP_DECLARE_METHOD(12) explicit IdentityScope(jobject jobj) : object<IdentityScope>(jobj) { } operator local_ref<java::security::Identity>() const; IdentityScope(local_ref< java::lang::String > const&); IdentityScope(local_ref< java::lang::String > const&, local_ref< java::security::IdentityScope > const&); static local_ref< java::security::IdentityScope > getSystemScope(); jint size(); local_ref< java::security::Identity > getIdentity(local_ref< java::lang::String > const&); local_ref< java::security::Identity > getIdentity(local_ref< java::security::Principal > const&); local_ref< java::security::Identity > getIdentity(local_ref< java::security::PublicKey > const&); void addIdentity(local_ref< java::security::Identity > const&); void removeIdentity(local_ref< java::security::Identity > const&); local_ref< java::util::Enumeration > identities(); local_ref< java::lang::String > toString(); }; //class IdentityScope } //namespace security } //namespace java } //namespace j2cpp #endif //J2CPP_JAVA_SECURITY_IDENTITYSCOPE_HPP_DECL #else //J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_JAVA_SECURITY_IDENTITYSCOPE_HPP_IMPL #define J2CPP_JAVA_SECURITY_IDENTITYSCOPE_HPP_IMPL namespace j2cpp { java::security::IdentityScope::operator local_ref<java::security::Identity>() const { return local_ref<java::security::Identity>(get_jobject()); } java::security::IdentityScope::IdentityScope(local_ref< java::lang::String > const &a0) : object<java::security::IdentityScope>( call_new_object< java::security::IdentityScope::J2CPP_CLASS_NAME, java::security::IdentityScope::J2CPP_METHOD_NAME(1), java::security::IdentityScope::J2CPP_METHOD_SIGNATURE(1) >(a0) ) { } java::security::IdentityScope::IdentityScope(local_ref< java::lang::String > const &a0, local_ref< java::security::IdentityScope > const &a1) : object<java::security::IdentityScope>( call_new_object< java::security::IdentityScope::J2CPP_CLASS_NAME, java::security::IdentityScope::J2CPP_METHOD_NAME(2), java::security::IdentityScope::J2CPP_METHOD_SIGNATURE(2) >(a0, a1) ) { } local_ref< java::security::IdentityScope > java::security::IdentityScope::getSystemScope() { return call_static_method< java::security::IdentityScope::J2CPP_CLASS_NAME, java::security::IdentityScope::J2CPP_METHOD_NAME(3), java::security::IdentityScope::J2CPP_METHOD_SIGNATURE(3), local_ref< java::security::IdentityScope > >(); } jint java::security::IdentityScope::size() { return call_method< java::security::IdentityScope::J2CPP_CLASS_NAME, java::security::IdentityScope::J2CPP_METHOD_NAME(5), java::security::IdentityScope::J2CPP_METHOD_SIGNATURE(5), jint >(get_jobject()); } local_ref< java::security::Identity > java::security::IdentityScope::getIdentity(local_ref< java::lang::String > const &a0) { return call_method< java::security::IdentityScope::J2CPP_CLASS_NAME, java::security::IdentityScope::J2CPP_METHOD_NAME(6), java::security::IdentityScope::J2CPP_METHOD_SIGNATURE(6), local_ref< java::security::Identity > >(get_jobject(), a0); } local_ref< java::security::Identity > java::security::IdentityScope::getIdentity(local_ref< java::security::Principal > const &a0) { return call_method< java::security::IdentityScope::J2CPP_CLASS_NAME, java::security::IdentityScope::J2CPP_METHOD_NAME(7), java::security::IdentityScope::J2CPP_METHOD_SIGNATURE(7), local_ref< java::security::Identity > >(get_jobject(), a0); } local_ref< java::security::Identity > java::security::IdentityScope::getIdentity(local_ref< java::security::PublicKey > const &a0) { return call_method< java::security::IdentityScope::J2CPP_CLASS_NAME, java::security::IdentityScope::J2CPP_METHOD_NAME(8), java::security::IdentityScope::J2CPP_METHOD_SIGNATURE(8), local_ref< java::security::Identity > >(get_jobject(), a0); } void java::security::IdentityScope::addIdentity(local_ref< java::security::Identity > const &a0) { return call_method< java::security::IdentityScope::J2CPP_CLASS_NAME, java::security::IdentityScope::J2CPP_METHOD_NAME(9), java::security::IdentityScope::J2CPP_METHOD_SIGNATURE(9), void >(get_jobject(), a0); } void java::security::IdentityScope::removeIdentity(local_ref< java::security::Identity > const &a0) { return call_method< java::security::IdentityScope::J2CPP_CLASS_NAME, java::security::IdentityScope::J2CPP_METHOD_NAME(10), java::security::IdentityScope::J2CPP_METHOD_SIGNATURE(10), void >(get_jobject(), a0); } local_ref< java::util::Enumeration > java::security::IdentityScope::identities() { return call_method< java::security::IdentityScope::J2CPP_CLASS_NAME, java::security::IdentityScope::J2CPP_METHOD_NAME(11), java::security::IdentityScope::J2CPP_METHOD_SIGNATURE(11), local_ref< java::util::Enumeration > >(get_jobject()); } local_ref< java::lang::String > java::security::IdentityScope::toString() { return call_method< java::security::IdentityScope::J2CPP_CLASS_NAME, java::security::IdentityScope::J2CPP_METHOD_NAME(12), java::security::IdentityScope::J2CPP_METHOD_SIGNATURE(12), local_ref< java::lang::String > >(get_jobject()); } J2CPP_DEFINE_CLASS(java::security::IdentityScope,"java/security/IdentityScope") J2CPP_DEFINE_METHOD(java::security::IdentityScope,0,"<init>","()V") J2CPP_DEFINE_METHOD(java::security::IdentityScope,1,"<init>","(Ljava/lang/String;)V") J2CPP_DEFINE_METHOD(java::security::IdentityScope,2,"<init>","(Ljava/lang/String;Ljava/security/IdentityScope;)V") J2CPP_DEFINE_METHOD(java::security::IdentityScope,3,"getSystemScope","()Ljava/security/IdentityScope;") J2CPP_DEFINE_METHOD(java::security::IdentityScope,4,"setSystemScope","(Ljava/security/IdentityScope;)V") J2CPP_DEFINE_METHOD(java::security::IdentityScope,5,"size","()I") J2CPP_DEFINE_METHOD(java::security::IdentityScope,6,"getIdentity","(Ljava/lang/String;)Ljava/security/Identity;") J2CPP_DEFINE_METHOD(java::security::IdentityScope,7,"getIdentity","(Ljava/security/Principal;)Ljava/security/Identity;") J2CPP_DEFINE_METHOD(java::security::IdentityScope,8,"getIdentity","(Ljava/security/PublicKey;)Ljava/security/Identity;") J2CPP_DEFINE_METHOD(java::security::IdentityScope,9,"addIdentity","(Ljava/security/Identity;)V") J2CPP_DEFINE_METHOD(java::security::IdentityScope,10,"removeIdentity","(Ljava/security/Identity;)V") J2CPP_DEFINE_METHOD(java::security::IdentityScope,11,"identities","()Ljava/util/Enumeration;") J2CPP_DEFINE_METHOD(java::security::IdentityScope,12,"toString","()Ljava/lang/String;") } //namespace j2cpp #endif //J2CPP_JAVA_SECURITY_IDENTITYSCOPE_HPP_IMPL #endif //J2CPP_INCLUDE_IMPLEMENTATION
[ "le.hoang.q@gmail.com@2e56ffda-155b-7872-b1f3-609f5c043f28" ]
le.hoang.q@gmail.com@2e56ffda-155b-7872-b1f3-609f5c043f28
a584c40946b5c28902c17e9019131726e73e465a
73108391c74a56edca65a5b01dc4449d191f8c3c
/Sima/Kukua/Classes/FallingLetters/FallingLettersEp2/SemaColliderPhysicsGameObject.cpp
db9702224c850dcb1339706df4054bc2aa64f0dd
[ "BSD-2-Clause" ]
permissive
curiouslearning/Norad-Eduapp4syria
f4b91484dfa048cf2aeab081fadce0e2a775ef85
6f3e65cd111c29c692d4eb428302ccabc1b0f7fa
refs/heads/master
2021-06-28T02:38:26.746490
2020-08-24T16:56:20
2020-08-24T16:56:20
97,040,664
5
5
BSD-2-Clause
2020-05-13T18:31:36
2017-07-12T18:34:47
Csound Document
UTF-8
C++
false
false
1,879
cpp
#include "SemaColliderPhysicsGameObject.h" #include "Fruit.h" #include "FallingLettersEp2.h" SemaColliderPhysicsGameObject::SemaColliderPhysicsGameObject(Node& parentNode, string nodeName, EventDispatcher* eventDispatcher, FallingLettersEp2* multiplicationGame) : PhysicsGameObject(parentNode, nodeName, string(), "Collider", false, false, eventDispatcher) { CCLOG("SemaColliderPhysicsGameObject"); this->multiplicationGame = multiplicationGame; physicsBody->setTag(TAG); } SemaColliderPhysicsGameObject::~SemaColliderPhysicsGameObject() { } bool SemaColliderPhysicsGameObject::onContactBegin(PhysicsContact& contact) { PhysicsGameObject::onContactBegin(contact); CCLOG("SemaColliderPhysicsGameObject - onContactBegin"); map<int, Fruit*>& fruits = multiplicationGame->getFruits(); map<int, Fruit*>::iterator fruitIterator = fruits.find(contact.getShapeA()->getBody()->getTag()); CCLOG("Tag %d", contact.getShapeA()->getBody()->getTag()); if (fruitIterator == fruits.end()) { fruitIterator = fruits.find(contact.getShapeB()->getBody()->getTag()); CCLOG("Tag %d", contact.getShapeB()->getBody()->getTag()); } if (fruitIterator != fruits.end()) { Fruit* fruit = fruitIterator->second; CocosDenshion::SimpleAudioEngine::getInstance()->playEffect((FallingLettersEp2::PATH + "Audio/fruttoappenapreso.wav").c_str()); fruit->stopFalling(fruit->getNumber() != multiplicationGame->getMultiplier()); fruit->setParent(*node); fruit->getNode().getChildByName("RootBone")->getChildByName("Sprite")->setScale(1); fruit->getNode().getChildByName("RootBone")->runAction( JumpTo::create( 0.25f, fruit->getNode().convertToNodeSpace(node->convertToWorldSpace(node->getChildByName("Collider")->getPosition() + Vec2(0.f, 50.f))), 25.f, 1 ) ); multiplicationGame->checkFruitNumber(fruit->getNumber()); } return false; }
[ "rst@knowit.no" ]
rst@knowit.no
29a47623de2edf7344fc742e69621c0f0c9cb18d
c12fba29b0cbb5071dca39ddbe67da9607b77d65
/Engine/Source/Resources/Core/ResourcesCore.cpp
4d7ca5183bcd5e40de553652a715030ace0e894b
[]
no_license
satellitnorden/Catalyst-Engine
55666b2cd7f61d4e5a311297ccbad754e901133e
c8064856f0be6ed81a5136155ab6b9b3352dca5c
refs/heads/master
2023-08-08T04:59:54.887284
2023-08-07T13:33:08
2023-08-07T13:33:08
116,288,917
21
3
null
null
null
null
UTF-8
C++
false
false
879
cpp
//Header file. #include <Resources/Core/ResourcesCore.h> //Resource constants. namespace ResourceConstants { //The type identifiers. const HashString ANIMATED_MODEL_TYPE_IDENTIFIER{ "AnimatedModel" }; const HashString ANIMATION_TYPE_IDENTIFIER{ "Animation" }; const HashString FONT_TYPE_IDENTIFIER{ "Font" }; const HashString LEVEL_TYPE_IDENTIFIER{ "Level" }; const HashString MATERIAL_TYPE_IDENTIFIER{ "Material" }; const HashString MODEL_TYPE_IDENTIFIER{ "Model" }; const HashString RAW_DATA_TYPE_IDENTIFIER{ "RawData" }; const HashString SHADER_TYPE_IDENTIFIER{ "Shader" }; const HashString SOUND_TYPE_IDENTIFIER{ "Sound" }; const HashString TEXTURE_CUBE_TYPE_IDENTIFIER{ "TextureCube" }; const HashString TEXTURE_2D_TYPE_IDENTIFIER{ "Texture2D" }; const HashString TEXTURE_3D_TYPE_IDENTIFIER{ "Texture3D" }; const HashString VIDEO_TYPE_IDENTIFIER{ "Video" }; }
[ "DennisMartenssons@gmail.com" ]
DennisMartenssons@gmail.com
5d0685073073ccaf8ffe4b7acdb28985ab1bdbba
62ed61692a097a293e4e52f414172f24f42bda2f
/Problems/Longest Common Sequence/main.cpp
d96dc9a1388c12f3a8d516f5ac55823b4066ac7f
[]
no_license
Darthron/Algorithms
d843bb8d2ca1f60fa593fd4c024ecf7cfd203c8c
0e64fcb07361df65f87c673d68f437447c9de6ce
refs/heads/master
2021-01-10T18:02:01.869678
2016-10-14T18:02:10
2016-10-14T18:02:10
45,737,392
0
0
null
null
null
null
UTF-8
C++
false
false
491
cpp
#include <fstream> using namespace std; const int MAXL = 1024; int N, M; int n[MAXL]; int m[MAXL]; int lcs(int p, int q) { if (p < 0 or q < 0) return 0; if (n[p] == m[q]) return 1 + lcs(p - 1, q - 1); return max(lcs(p - 1, q), lcs(p, q - 1)); } int main() { ifstream mama("cmlsc.in"); ofstream tata("cmlsc.out"); mama >> N; mama >> M; for (int i = 0; i < N; i += 1) mama >> n[i]; for (int i = 0; i < M; i += 1) mama >> m[i]; tata << lcs(N - 1, M - 1); return 0; }
[ "razvan_meriniuc@yahoo.com" ]
razvan_meriniuc@yahoo.com
7c545ad8073d4848ab56b15568eb30258d6892d9
5a0318980971ac7adc1feddb993f5029d4d1c144
/MEX_Code/KlustaKwikMatlabWrapper/param.cpp
194662aba2a68da0b60d2817557a6dc7c4dd00d1
[]
no_license
sychen23/Kofiko-old
070d208629482832db6ad401eb76c8a2a1cda531
fe04ddba001b568d3a0f21a068e463f5d426a3a5
refs/heads/master
2021-05-31T16:34:40.934308
2016-02-29T21:07:07
2016-02-29T21:07:07
50,534,370
2
0
null
null
null
null
UTF-8
C++
false
false
1,917
cpp
#include "param.h" typedef struct entry_t { int t; char *name; void *addr; struct entry_t *next; } entry; entry *top, *bottom; extern char HelpString[]; char help = 0; /* returns 1 if the parameter was found and changed, else zero. */ int change_param(char *name, char *value) { entry *e; int changed = 0; for(e=bottom; e; e = e->next) if (!strcmp(name, e->name)) { switch (e->t) { case FLOAT: *((float *) e->addr) = atof(value); break; case INT: *((int *) e->addr) = atoi(value); break; case BOOLEAN: if (*value == '0') *((char *) e->addr) = 0; else *((char *) e->addr) = 1; break; case STRING: strncpy((char *)e->addr, value, STRLEN); break; } changed = 1; break; } return changed; } void search_command_line(char *name) { int i; for(i=0; i<argc-1; i++) if (argv[i][0] == '-' && !strcmp(argv[i]+1, name)) change_param(argv[i] + 1, argv[i+1]); if (argv[argc-1][0] == '-' && !strcmp(argv[argc-1]+1, name)) change_param(argv[argc-1] + 1, ""); } void add_param(int t, char *name, void *addr) { entry *e; if (top == NULL) { bottom = top = e = (entry *) malloc(sizeof(entry)); } else { e = (entry *) malloc(sizeof(entry)); top->next = e; top = e; } if (e == NULL) {printf("parameter manager out of memory!\n"); exit(1);} top->t = t; top->name = name; top->addr = addr; top->next = NULL; search_command_line(name); } void print_params(FILE *fp) { entry *e; int changed = 0; add_param(BOOLEAN, "help", &help); if (help) { fprintf(fp, HelpString); } for(e=bottom; e; e = e->next) { fprintf(fp, "%s\t", e->name); switch (e->t) { case FLOAT: fprintf(fp, "%f\n", *(float *)(e->addr)); break; case INT: fprintf(fp, "%d\n", *(int *)(e->addr)); break; case BOOLEAN: fprintf(fp, "%d\n", *(char *)(e->addr)); break; case STRING: fprintf(fp, "%s\n", (char *)(e->addr)); break; } } if (help) exit(0); }
[ "sychen23@yahoo.com" ]
sychen23@yahoo.com