text:
//===--- ImporterImpl.h - Import Clang Modules: Implementation --*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file provides the implementation class definitions for the Clang
// module loader.
//
//===----------------------------------------------------------------------===//
#ifndef SWIFT_CLANG_IMPORTER_IMPL_H
#define SWIFT_CLANG_IMPORTER_IMPL_H

#include "ClangAdapter.h"
#include "ImportEnumInfo.h"
#include "ImportName.h"
#include "SwiftLookupTable.h"
#include "swift/ClangImporter/ClangImporter.h"
#include "swift/ClangImporter/ClangModule.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/LazyResolver.h"
#include "swift/AST/Module.h"
#include "swift/AST/Type.h"
#include "swift/AST/ForeignErrorConvention.h"
#include "swift/Basic/StringExtras.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclVisitor.h"
#include "clang/Basic/IdentifierTable.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Serialization/ModuleFileExtension.h"
#include "llvm/ADT/APSInt.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/ADT/SmallBitVector.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/TinyPtrVector.h"
#include <set>

namespace llvm {

class SmallBitVector;

}

namespace clang {
class APValue;
class Decl;
class DeclarationName;
class EnumDecl;
class MacroInfo;
class MangleContext;
class NamedDecl;
class ObjCInterfaceDecl;
class ObjCMethodDecl;
class ObjCPropertyDecl;
class ParmVarDecl;
class Parser;
class QualType;
class TypedefNameDecl;
}

namespace swift {

class ASTContext;
class ClassDecl;
class ConstructorDecl;
class Decl;
class DeclContext;
class Expr;
class ExtensionDecl;
class FuncDecl;
class Identifier;
class Pattern;
class SubscriptDecl;
class ValueDecl;

/// \brief Describes the kind of conversion to apply to a constant value.
enum class ConstantConvertKind {
  /// \brief No conversion required.
  None,
  /// \brief Coerce the constant to the given type.
  Coerce,
  /// \brief Construct the given type from the constant value.
  Construction,
  /// \brief Construct the given type from the constant value, using an
  /// optional initializer.
  ConstructionWithUnwrap,
  /// \brief Perform an unchecked downcast to the given type.
  Downcast
};

/// \brief Describes the kind of type import we're performing.
enum class ImportTypeKind {
  /// \brief Import a type in its most abstract form, without any adjustment.
  Abstract,

  /// \brief Import the underlying type of a typedef.
  Typedef,

  /// \brief Import the type of a literal value.
  Value,

  /// \brief Import the type of a literal value that can be bridged.
  BridgedValue,

  /// \brief Import the declared type of a variable.
  Variable,

  /// \brief Import the declared type of an audited variable.
  ///
  /// This is exactly like ImportTypeKind::Variable, except it
  /// disables wrapping CF class types in Unmanaged.
  AuditedVariable,

  /// \brief Import the declared type of a struct or union field.
  RecordField,

  /// \brief Import the result type of a function.
  ///
  /// This provides special treatment for 'void', among other things, and
  /// enables the conversion of bridged types.
  Result,

  /// \brief Import the result type of an audited function.
  ///
  /// This is exactly like ImportTypeKind::Result, except it
  /// disables wrapping CF class types in Unmanaged.
  AuditedResult,

  /// \brief Import the type of a function parameter.
  ///
  /// This provides special treatment for C++ references (which become
  /// [inout] parameters) and C pointers (which become magic [inout]-able types),
  /// among other things, and enables the conversion of bridged types.
  /// Parameters are always considered CF-audited.
  Parameter,

  /// \brief Import the type of a parameter declared with
  /// \c CF_RETURNS_RETAINED.
  ///
  /// This ensures that the parameter is not marked as Unmanaged.
  CFRetainedOutParameter,

  /// \brief Import the type of a parameter declared with
  /// \c CF_RETURNS_NON_RETAINED.
  ///
  /// This ensures that the parameter is not marked as Unmanaged.
  CFUnretainedOutParameter,

  /// \brief Import the type pointed to by a pointer or reference.
  ///
  /// This provides special treatment for pointer-to-ObjC-pointer
  /// types, which get imported as pointers to *checked* optional,
  /// *Pointer<NSFoo?>, instead of implicitly unwrapped optional as usual.
  Pointee,

  /// \brief Import the type of an ObjC property.
  ///
  /// This enables the conversion of bridged types. Properties are always
  /// considered CF-audited.
  Property,

  /// \brief Import the type of an ObjC property accessor marked 'weak',
  /// 'assign', or 'unsafe_unretained'.
  ///
  /// Like Property, but doesn't allow bridging to a value type, since that
  /// would discard the ownership.
  PropertyWithReferenceSemantics,

  /// \brief Import the underlying type of an enum.
  ///
  /// This provides special treatment for 'NSUInteger'.
  Enum
};

/// \brief Describes the kind of the C type that can be mapped to a stdlib
/// swift type.
enum class MappedCTypeKind {
  UnsignedInt,
  SignedInt,
  UnsignedWord,
  SignedWord,
  FloatIEEEsingle,
  FloatIEEEdouble,
  FloatX87DoubleExtended,
  VaList,
  ObjCBool,
  ObjCSel,
  ObjCId,
  ObjCClass,
  CGFloat,
  Block,
};

/// \brief Describes what to do with the C name of a type that can be mapped to
/// a Swift standard library type.
enum class MappedTypeNameKind {
  DoNothing,
  DefineOnly,
  DefineAndUse
};

/// \brief Describes certain kinds of methods that need to be specially
/// handled by the importer.
enum class SpecialMethodKind {
  Regular,
  Constructor,
  PropertyAccessor,
  NSDictionarySubscriptGetter
};

#define SWIFT_NATIVE_ANNOTATION_STRING "__swift native"

#define SWIFT_PROTOCOL_SUFFIX "Protocol"
#define SWIFT_CFTYPE_SUFFIX "Ref"

/// Describes whether to classify a factory method as an initializer.
enum class FactoryAsInitKind {
  /// Infer based on name and type (the default).
  Infer,
  /// Treat as a class method.
  AsClassMethod,
  /// Treat as an initializer.
  AsInitializer
};

namespace importer {
struct PlatformAvailability {
  /// A predicate that indicates if the given platform should be
  /// considered for availability.
  std::function<bool(StringRef PlatformName)> filter;

  /// A predicate that indicates if the given platform version should
  /// should be included in the cutoff of deprecated APIs marked unavailable.
  std::function<bool(unsigned major, llvm::Optional<unsigned> minor)>
      deprecatedAsUnavailableFilter;

  /// The message to embed for implicitly unavailability if a deprecated
  /// API is now unavailable.
  std::string deprecatedAsUnavailableMessage;

  PlatformAvailability(LangOptions &opts);

private:
  PlatformAvailability(const PlatformAvailability&) = delete;
  PlatformAvailability &operator=(const PlatformAvailability &) = delete;
};
}

using LookupTableMap = llvm::StringMap<std::unique_ptr<SwiftLookupTable>>;

/// \brief Implementation of the Clang importer.
class LLVM_LIBRARY_VISIBILITY ClangImporter::Implementation
  : public LazyMemberLoader
{
  friend class ClangImporter;

public:
  Implementation(ASTContext &ctx, const ClangImporterOptions &opts);
  ~Implementation();

  /// \brief Swift AST context.
  ASTContext &SwiftContext;

  const bool ImportForwardDeclarations;
  const bool InferImportAsMember;
  const bool DisableSwiftBridgeAttr;

  constexpr static const char * const moduleImportBufferName =
    "<swift-imported-modules>";
  constexpr static const char * const bridgingHeaderBufferName =
    "<bridging-header-import>";

private:
  /// The Swift lookup table for the bridging header.
  SwiftLookupTable BridgingHeaderLookupTable;

  /// The Swift lookup tables, per module.
  ///
  /// Annoyingly, we list this table early so that it gets torn down after
  /// the underlying Clang instances that reference it
  /// (through the Swift name lookup module file extension).
  LookupTableMap LookupTables;

  /// \brief A count of the number of load module operations.
  /// FIXME: Horrible, horrible hack for \c loadModule().
  unsigned ImportCounter = 0;

  /// \brief The value of \c ImportCounter last time when imported modules were
  /// verified.
  unsigned VerifiedImportCounter = 0;

  /// \brief Clang compiler invocation.
  llvm::IntrusiveRefCntPtr<clang::CompilerInvocation> Invocation;

  /// \brief Clang compiler instance, which is used to actually load Clang
  /// modules.
  std::unique_ptr<clang::CompilerInstance> Instance;

  /// \brief Clang compiler action, which is used to actually run the
  /// parser.
  std::unique_ptr<clang::FrontendAction> Action;

  /// \brief Clang parser, which is used to load textual headers.
  std::unique_ptr<clang::Parser> Parser;

  /// \brief Clang parser, which is used to load textual headers.
  std::unique_ptr<clang::MangleContext> Mangler;

  /// The active type checker, or null if there is no active type checker.
  ///
  /// The flag is \c true if there has ever been a type resolver assigned, i.e.
  /// if type checking has begun.
  llvm::PointerIntPair<LazyResolver *, 1, bool> typeResolver;

public:
  /// \brief Mapping of already-imported declarations.
  ///
  /// The "char" in the key is a "bool" in disguise that indicates whether this
  /// is a Swift 2 name vs. a Swift 3 name.
  llvm::DenseMap<std::pair<const clang::Decl *, char>, Decl *> ImportedDecls;

  /// \brief The set of "special" typedef-name declarations, which are
  /// mapped to specific Swift types.
  ///
  /// Normal typedef-name declarations imported into Swift will maintain
  /// equality between the imported declaration's underlying type and the
  /// import of the underlying type. A typedef-name declaration is special
  /// when this is not the case, e.g., Objective-C's "BOOL" has an underlying
  /// type of "signed char", but is mapped to a special Swift struct type
  /// ObjCBool.
  llvm::SmallDenseMap<const clang::TypedefNameDecl *, MappedTypeNameKind, 16>
    SpecialTypedefNames;

  /// \brief Provide a single extension point for any given type per clang
  /// submodule
  llvm::DenseMap<std::pair<NominalTypeDecl *, const clang::Module *>,
                 ExtensionDecl *> extensionPoints;

  /// \brief Typedefs that we should not be importing.  We should be importing
  /// underlying decls instead.
  llvm::DenseSet<const clang::Decl *> SuperfluousTypedefs;

  /// Tag decls whose typedefs were imported instead.
  ///
  /// \sa SuperfluousTypedefs
  llvm::DenseSet<const clang::Decl *> DeclsWithSuperfluousTypedefs;

  /// \brief Mapping of already-imported declarations from protocols, which
  /// can (and do) get replicated into classes.
  llvm::DenseMap<std::tuple<const clang::Decl *, DeclContext *, char>, Decl *>
    ImportedProtocolDecls;

  /// Mapping from identifiers to the set of macros that have that name along
  /// with their corresponding Swift declaration.
  ///
  /// Multiple macro definitions can map to the same declaration if the
  /// macros are identically defined.
  llvm::DenseMap<Identifier,
                 SmallVector<std::pair<clang::MacroInfo *, ValueDecl *>, 2>>
    ImportedMacros;

  // Mapping from macro to value for macros that expand to constant values.
  llvm::DenseMap<const clang::MacroInfo *, std::pair<clang::APValue, Type>>
    ImportedMacroConstants;

  /// Keeps track of active selector-based lookups, so that we don't infinitely
  /// recurse when checking whether a method with a given selector has already
  /// been imported.
  llvm::DenseMap<std::pair<ObjCSelector, char>, unsigned>
    ActiveSelectors;

private:
  /// \brief Generation number that is used for crude versioning.
  ///
  /// This value is incremented every time a new module is imported.
  unsigned Generation = 1;

  void bumpGeneration() {
    ++Generation;
    SwiftContext.bumpGeneration();
  }

public:
  /// \brief Keep track of subscript declarations based on getter/setter
  /// pairs.
  llvm::DenseMap<std::pair<FuncDecl *, FuncDecl *>, SubscriptDecl *> Subscripts;

  /// Keeps track of the Clang functions that have been turned into
  /// properties.
  llvm::DenseMap<const clang::FunctionDecl *, VarDecl *> FunctionsAsProperties;

  importer::EnumInfo getEnumInfo(const clang::EnumDecl *decl) {
    return getNameImporter().getEnumInfo(decl);
  }
  importer::EnumKind getEnumKind(const clang::EnumDecl *decl) {
    return getNameImporter().getEnumKind(decl);
  }

  // TODO: drop this accessor as soon as we further de-couple the swift name
  // lookup tables from the Impl.
  LookupTableMap &getLookupTables() { return LookupTables; }

private:
  class EnumConstantDenseMapInfo {
  public:
    using PairTy = std::pair<const clang::EnumDecl *, llvm::APSInt>;
    using PointerInfo = llvm::DenseMapInfo<const clang::EnumDecl *>;
    static inline PairTy getEmptyKey() {
      return {PointerInfo::getEmptyKey(), llvm::APSInt(/*bitwidth=*/1)};
    }
    static inline PairTy getTombstoneKey() {
      return {PointerInfo::getTombstoneKey(), llvm::APSInt(/*bitwidth=*/1)};
    }
    static unsigned getHashValue(const PairTy &pair) {
      return llvm::combineHashValue(PointerInfo::getHashValue(pair.first),
                                    llvm::hash_value(pair.second));
    }
    static bool isEqual(const PairTy &lhs, const PairTy &rhs) {
      return lhs == rhs;
    }
  };

public:
  /// \brief Keep track of enum constant values that have been imported.
  llvm::DenseMap<std::pair<const clang::EnumDecl *, llvm::APSInt>,
                 EnumElementDecl *,
                 EnumConstantDenseMapInfo>
    EnumConstantValues;

  /// \brief Keep track of initializer declarations that correspond to
  /// imported methods.
  llvm::DenseMap<std::tuple<const clang::ObjCMethodDecl *, DeclContext *, char>,
                 ConstructorDecl *>
    Constructors;

  /// A mapping from imported declarations to their "alternate" declarations,
  /// for cases where a single Clang declaration is imported to two
  /// different Swift declarations.
  llvm::DenseMap<Decl *, ValueDecl *> AlternateDecls;

  /// Retrieve the alternative declaration for the given imported
  /// Swift declaration.
  ValueDecl *getAlternateDecl(Decl *decl) {
    auto known = AlternateDecls.find(decl);
    if (known == AlternateDecls.end()) return nullptr;
    return known->second;
  }

private:
  /// \brief NSObject, imported into Swift.
  Type NSObjectTy;

  /// A pair containing a ClangModuleUnit,
  /// and whether the adapters of its re-exported modules have all been forced
  /// to load already.
  using ModuleInitPair = llvm::PointerIntPair<ClangModuleUnit *, 1, bool>;

public:
  /// A map from Clang modules to their Swift wrapper modules.
  llvm::SmallDenseMap<const clang::Module *, ModuleInitPair, 16> ModuleWrappers;

  /// The module unit that contains declarations from imported headers.
  ClangModuleUnit *ImportedHeaderUnit = nullptr;

  /// The modules re-exported by imported headers.
  llvm::SmallVector<Module::ImportedModule, 8> ImportedHeaderExports;

  /// The modules that requested imported headers.
  ///
  /// These are used to look up Swift classes forward-declared with \@class.
  TinyPtrVector<Module *> ImportedHeaderOwners;

  /// \brief Clang's objectAtIndexedSubscript: selector.
  clang::Selector objectAtIndexedSubscript;

  /// \brief Clang's setObjectAt:indexedSubscript: selector.
  clang::Selector setObjectAtIndexedSubscript;

  /// \brief Clang's objectForKeyedSubscript: selector.
  clang::Selector objectForKeyedSubscript;

  /// \brief Clang's setObject:forKeyedSubscript: selector.
  clang::Selector setObjectForKeyedSubscript;

private:
  /// Records those modules that we have looked up.
  llvm::DenseMap<Identifier, Module *> checkedModules;

  /// External Decls that we have imported but not passed to the ASTContext yet.
  SmallVector<Decl *, 4> RegisteredExternalDecls;

  /// Protocol conformances that may be missing witnesses.
  SmallVector<NormalProtocolConformance *, 4> DelayedProtocolConformances;

  unsigned NumCurrentImportingEntities = 0;

  /// Mapping from delayed conformance IDs to the set of delayed
  /// protocol conformances.
  llvm::DenseMap<unsigned, SmallVector<ProtocolConformance *, 4>>
    DelayedConformances;

  /// The next delayed conformance ID to use with \c DelayedConformances.
  unsigned NextDelayedConformanceID = 0;

  /// The set of imported protocols for a declaration, used only to
  /// load all members of the declaration.
  llvm::DenseMap<const Decl *, SmallVector<ProtocolDecl *, 4>>
    ImportedProtocols;

  void startedImportingEntity();
  void finishedImportingEntity();
  void finishPendingActions();
  void finishProtocolConformance(NormalProtocolConformance *conformance);

  struct ImportingEntityRAII {
    Implementation &Impl;

    ImportingEntityRAII(Implementation &Impl) : Impl(Impl) {
      Impl.startedImportingEntity();
    }
    ~ImportingEntityRAII() {
      Impl.finishedImportingEntity();
    }
  };

public:
  importer::PlatformAvailability platformAvailability;

private:
  /// For importing names. This is initialized by the ClangImporter::create()
  /// after having set up a suitable Clang instance.
  std::unique_ptr<importer::NameImporter> nameImporter = nullptr;

public:
  importer::NameImporter &getNameImporter() {
    assert(nameImporter && "haven't finished initialization");
    return *nameImporter;
  }

  /// Tracks top level decls from the bridging header.
  std::vector<clang::Decl *> BridgeHeaderTopLevelDecls;
  std::vector<llvm::PointerUnion<clang::ImportDecl *, ImportDecl *>>
    BridgeHeaderTopLevelImports;

  /// Tracks macro definitions from the bridging header.
  std::vector<clang::IdentifierInfo *> BridgeHeaderMacros;
  /// Tracks included headers from the bridging header.
  llvm::DenseSet<const clang::FileEntry *> BridgeHeaderFiles;

  void addBridgeHeaderTopLevelDecls(clang::Decl *D);
  bool shouldIgnoreBridgeHeaderTopLevelDecl(clang::Decl *D);

public:
  void registerExternalDecl(Decl *D) {
    RegisteredExternalDecls.push_back(D);
  }

  void scheduleFinishProtocolConformance(NormalProtocolConformance *C) {
    DelayedProtocolConformances.push_back(C);
  }

  /// \brief Retrieve the Clang AST context.
  clang::ASTContext &getClangASTContext() const {
    return Instance->getASTContext();
  }

  /// \brief Retrieve the Clang Sema object.
  clang::Sema &getClangSema() const {
    return Instance->getSema();
  }

  /// \brief Retrieve the Clang AST context.
  clang::Preprocessor &getClangPreprocessor() const {
    return Instance->getPreprocessor();
  }

  clang::CodeGenOptions &getClangCodeGenOpts() const {
    return Instance->getCodeGenOpts();
  }

  /// Imports the given header contents into the Clang context.
  bool importHeader(Module *adapter, StringRef headerName, SourceLoc diagLoc,
                    bool trackParsedSymbols,
                    std::unique_ptr<llvm::MemoryBuffer> contents);

  /// \brief Retrieve the imported module that should contain the given
  /// Clang decl.
  ClangModuleUnit *getClangModuleForDecl(const clang::Decl *D,
                                         bool allowForwardDeclaration = false);

  /// Returns the module \p MI comes from, or \c None if \p MI does not have
  /// a valid associated module.
  ///
  /// The returned module may be null (but not \c None) if \p MI comes from
  /// an imported header.
  Optional<clang::Module *>
  getClangSubmoduleForMacro(const clang::MacroInfo *MI);

  ClangModuleUnit *getClangModuleForMacro(const clang::MacroInfo *MI);

  /// Whether NSUInteger can be imported as Int in certain contexts. If false,
  /// should always be imported as UInt.
  static bool shouldAllowNSUIntegerAsInt(bool isFromSystemModule,
                                         const clang::NamedDecl *decl);

  /// \brief Converts the given Swift identifier for Clang.
  clang::DeclarationName exportName(Identifier name);

  /// Imports the full name of the given Clang declaration into Swift.
  ///
  /// Note that this may result in a name very different from the Clang name,
  /// so it should not be used when referencing Clang symbols.
  ///
  /// \param D The Clang declaration whose name should be imported.
  importer::ImportedName
  importFullName(const clang::NamedDecl *D,
                 importer::ImportNameOptions options = None) {
    return getNameImporter().importName(D, options);
  }

  /// Print an imported name as a string suitable for the swift_name attribute,
  /// or the 'Rename' field of AvailableAttr.
  void printSwiftName(importer::ImportedName, bool fullyQualified,
                      llvm::raw_ostream &os);

  /// \brief Import the given Clang identifier into Swift.
  ///
  /// \param identifier The Clang identifier to map into Swift.
  ///
  /// \param removePrefix The prefix to remove from the Clang name to produce
  /// the Swift name. If the Clang name does not start with this prefix,
  /// nothing is removed.
  Identifier importIdentifier(const clang::IdentifierInfo *identifier,
                              StringRef removePrefix = "");

  /// Import an Objective-C selector.
  ObjCSelector importSelector(clang::Selector selector);

  /// Import a Swift name as a Clang selector.
  clang::Selector exportSelector(DeclName name, bool allowSimpleName = true);

  /// Export a Swift Objective-C selector as a Clang Objective-C selector.
  clang::Selector exportSelector(ObjCSelector selector);

  /// \brief Import the given Swift source location into Clang.
  clang::SourceLocation exportSourceLoc(SourceLoc loc);

  /// \brief Import the given Clang source location into Swift.
  SourceLoc importSourceLoc(clang::SourceLocation loc);

  /// \brief Import the given Clang source range into Swift.
  SourceRange importSourceRange(clang::SourceRange loc);

  /// \brief Import the given Clang preprocessor macro as a Swift value decl.
  ///
  /// \returns The imported declaration, or null if the macro could not be
  /// translated into Swift.
  ValueDecl *importMacro(Identifier name, clang::MacroInfo *macro);

  /// Map a Clang identifier name to its imported Swift equivalent.
  StringRef getSwiftNameFromClangName(StringRef name);

  /// Import attributes from the given Clang declaration to its Swift
  /// equivalent.
  ///
  /// \param ClangDecl The decl being imported.
  /// \param MappedDecl The decl to attach attributes to.
  /// \param NewContext If present, the Clang node for the context the decl is
  /// being imported into, which may affect info from API notes.
  void importAttributes(const clang::NamedDecl *ClangDecl, Decl *MappedDecl,
                        const clang::ObjCContainerDecl *NewContext = nullptr);

  /// If we already imported a given decl, return the corresponding Swift decl.
  /// Otherwise, return nullptr.
  Decl *importDeclCached(const clang::NamedDecl *ClangDecl, bool useSwift2Name);

  Decl *importDeclImpl(const clang::NamedDecl *ClangDecl,
                       bool useSwift2Name,
                       bool &TypedefIsSuperfluous,
                       bool &HadForwardDeclaration);

  Decl *importDeclAndCacheImpl(const clang::NamedDecl *ClangDecl,
                               bool useSwift2Name,
                               bool SuperfluousTypedefsAreTransparent);

  /// \brief Same as \c importDeclReal, but for use inside importer
  /// implementation.
  ///
  /// Unlike \c importDeclReal, this function for convenience transparently
  /// looks through superfluous typedefs and returns the imported underlying
  /// decl in that case.
  Decl *importDecl(const clang::NamedDecl *ClangDecl, bool useSwift2Name) {
    return importDeclAndCacheImpl(ClangDecl, useSwift2Name,
                                  /*SuperfluousTypedefsAreTransparent=*/true);
  }

  /// \brief Import the given Clang declaration into Swift.  Use this function
  /// outside of the importer implementation, when importing a decl requested by
  /// Swift code.
  ///
  /// \returns The imported declaration, or null if this declaration could
  /// not be represented in Swift.
  Decl *importDeclReal(const clang::NamedDecl *ClangDecl, bool useSwift2Name) {
    return importDeclAndCacheImpl(ClangDecl, useSwift2Name,
                                  /*SuperfluousTypedefsAreTransparent=*/false);
  }

  /// \brief Import a cloned version of the given declaration, which is part of
  /// an Objective-C protocol and currently must be a method or property, into
  /// the given declaration context.
  ///
  /// \returns The imported declaration, or null if this declaration could not
  /// be represented in Swift.
  Decl *importMirroredDecl(const clang::NamedDecl *decl, DeclContext *dc,
                           bool useSwift2Name, ProtocolDecl *proto);

  /// \brief Utility function for building simple generic signatures.
  std::pair<GenericSignature *, GenericEnvironment *>
  buildGenericSignature(GenericParamList *genericParams, DeclContext *dc);

  /// \brief Import the given Clang declaration context into Swift.
  ///
  /// Usually one will use \c importDeclContextOf instead.
  ///
  /// \returns The imported declaration context, or null if it could not
  /// be converted.
  DeclContext *importDeclContextImpl(const clang::DeclContext *dc);

  /// \brief Import the declaration context of a given Clang declaration into
  /// Swift.
  ///
  /// \param context The effective context as determined by importFullName.
  ///
  /// \returns The imported declaration context, or null if it could not
  /// be converted.
  DeclContext *importDeclContextOf(const clang::Decl *D,
                                   EffectiveClangContext context);

  /// \brief Create a new named constant with the given value.
  ///
  /// \param name The name of the constant.
  /// \param dc The declaration context into which the name will be introduced.
  /// \param type The type of the named constant.
  /// \param value The value of the named constant.
  /// \param convertKind How to convert the constant to the given type.
  /// \param isStatic Whether the constant should be a static member of \p dc.
  ValueDecl *createConstant(Identifier name, DeclContext *dc,
                            Type type, const clang::APValue &value,
                            ConstantConvertKind convertKind,
                            bool isStatic,
                            ClangNode ClangN);

  /// \brief Create a new named constant with the given value.
  ///
  /// \param name The name of the constant.
  /// \param dc The declaration context into which the name will be introduced.
  /// \param type The type of the named constant.
  /// \param value The value of the named constant.
  /// \param convertKind How to convert the constant to the given type.
  /// \param isStatic Whether the constant should be a static member of \p dc.
  ValueDecl *createConstant(Identifier name, DeclContext *dc,
                            Type type, StringRef value,
                            ConstantConvertKind convertKind,
                            bool isStatic,
                            ClangNode ClangN);

  /// \brief Create a new named constant using the given expression.
  ///
  /// \param name The name of the constant.
  /// \param dc The declaration context into which the name will be introduced.
  /// \param type The type of the named constant.
  /// \param valueExpr An expression to use as the value of the constant.
  /// \param convertKind How to convert the constant to the given type.
  /// \param isStatic Whether the constant should be a static member of \p dc.
  ValueDecl *createConstant(Identifier name, DeclContext *dc,
                            Type type, Expr *valueExpr,
                            ConstantConvertKind convertKind,
                            bool isStatic,
                            ClangNode ClangN);

  /// Determine whether the given declaration is considered
  /// 'unavailable' in Swift.
  bool isUnavailableInSwift(const clang::Decl *decl) {
    return importer::isUnavailableInSwift(
        decl, platformAvailability, SwiftContext.LangOpts.EnableObjCInterop);
  }

  /// \brief Add "Unavailable" annotation to the swift declaration.
  void markUnavailable(ValueDecl *decl, StringRef unavailabilityMsg);

  /// \brief Create a decl with error type and an "unavailable" attribute on it
  /// with the specified message.
  ValueDecl *createUnavailableDecl(Identifier name, DeclContext *dc,
                                   Type type, StringRef UnavailableMessage,
                                   bool isStatic, ClangNode ClangN);

  /// \brief Retrieve the standard library module.
  Module *getStdlibModule();

  /// \brief Retrieve the named module.
  ///
  /// \param name The name of the module.
  ///
  /// \returns The named module, or null if the module has not been imported.
  Module *getNamedModule(StringRef name);

  /// \brief Returns the "Foundation" module, if it can be loaded.
  ///
  /// After this has been called, the Foundation module will or won't be loaded
  /// into the ASTContext.
  Module *tryLoadFoundationModule();

  /// \brief Returns the "SIMD" module, if it can be loaded.
  ///
  /// After this has been called, the SIMD module will or won't be loaded
  /// into the ASTContext.
  Module *tryLoadSIMDModule();

  /// \brief Retrieves the Swift wrapper for the given Clang module, creating
  /// it if necessary.
  ClangModuleUnit *getWrapperForModule(ClangImporter &importer,
                                       const clang::Module *underlying);

  /// \brief Constructs a Swift module for the given Clang module.
  Module *finishLoadingClangModule(ClangImporter &importer,
                                   const clang::Module *clangModule,
                                   bool preferAdapter);

  /// \brief Retrieve the named Swift type, e.g., Int32.
  ///
  /// \param moduleName The name of the module in which the type should occur.
  ///
  /// \param name The name of the type to find.
  ///
  /// \returns The named type, or null if the type could not be found.
  Type getNamedSwiftType(StringRef moduleName, StringRef name);

  /// \brief Retrieve the named Swift type, e.g., Int32.
  ///
  /// \param module The module in which the type should occur.
  ///
  /// \param name The name of the type to find.
  ///
  /// \returns The named type, or null if the type could not be found.
  Type getNamedSwiftType(Module *module, StringRef name);

  /// \brief Retrieve a specialization of the named Swift type, e.g.,
  /// UnsafeMutablePointer<T>.
  ///
  /// \param module The name of the module in which the type should occur.
  ///
  /// \param name The name of the type to find.
  ///
  /// \param args The arguments to use in the specialization.
  ///
  /// \returns The named type, or null if the type could not be found.
  Type getNamedSwiftTypeSpecialization(Module *module, StringRef name,
                                       ArrayRef<Type> args);

  /// \brief Retrieve the NSObject type.
  Type getNSObjectType();

  /// \brief Retrieve the NSObject protocol type.
  Type getNSObjectProtocolType();

  /// \brief Retrieve the NSCopying protocol type.
  Type getNSCopyingType();

  /// \brief Determines whether the given type matches an implicit type
  /// bound of "Hashable", which is used to validate NSDictionary/NSSet.
  bool matchesNSObjectBound(Type type);

  /// \brief Look up and attempt to import a Clang declaration with
  /// the given name.
  Decl *importDeclByName(StringRef name);

  /// \brief Import the given Clang type into Swift.
  ///
  /// \param type The Clang type to import.
  ///
  /// \param kind The kind of type import we're performing.
  ///
  /// \param allowNSUIntegerAsInt If true, NSUInteger will be imported as Int
  ///        in certain contexts. If false, it will always be imported as UInt.
  ///
  /// \param canFullyBridgeTypes True if we can bridge types losslessly.
  ///        This is an additional guarantee on top of the ImportTypeKind
  ///        cases that allow bridging, and applies to the entire type.
  ///
  /// \returns The imported type, or null if this type could
  /// not be represented in Swift.
  Type importType(clang::QualType type,
                  ImportTypeKind kind,
                  bool allowNSUIntegerAsInt,
                  bool canFullyBridgeTypes,
                  OptionalTypeKind optional = OTK_ImplicitlyUnwrappedOptional);

  /// \brief Import the given function type.
  ///
  /// This routine should be preferred when importing function types for
  /// which we have actual function parameters, e.g., when dealing with a
  /// function declaration, because it produces a function type whose input
  /// tuple has argument names.
  ///
  /// \param clangDecl The underlying declaration, if any; should only be
  ///   considered for any attributes it might carry.
  /// \param resultType The result type of the function.
  /// \param params The parameter types to the function.
  /// \param isVariadic Whether the function is variadic.
  /// \param isNoReturn Whether the function is noreturn.
  /// \param parameterList The parameters visible inside the function body.
  ///
  /// \returns the imported function type, or null if the type cannot be
  /// imported.
  Type importFunctionType(DeclContext *dc,
                          const clang::FunctionDecl *clangDecl,
                          clang::QualType resultType,
                          ArrayRef<const clang::ParmVarDecl *> params,
                          bool isVariadic, bool isNoReturn,
                          bool isFromSystemModule,
                          bool hasCustomName,
                          ParameterList *&parameterList,
                          DeclName &name);

  /// \brief Import the given function return type.
  ///
  /// \param clangDecl The underlying declaration, if any; should only be
  ///   considered for any attributes it might carry.
  /// \param resultType The result type of the function.
  /// \param allowNSUIntegerAsInt If true, NSUInteger will be imported as Int
  ///        in certain contexts. If false, it will always be imported as UInt.
  ///
  /// \returns the imported function return type, or null if the type cannot be
  /// imported.
  Type importFunctionReturnType(DeclContext *dc,
                                const clang::FunctionDecl *clangDecl,
                                clang::QualType resultType,
                                bool allowNSUIntegerAsInt);

  /// \brief Import the parameter list for a function
  ///
  /// \param clangDecl The underlying declaration, if any; should only be
  ///   considered for any attributes it might carry.
  /// \param params The parameter types to the function.
  /// \param isVariadic Whether the function is variadic.
  /// \param allowNSUIntegerAsInt If true, NSUInteger will be imported as Int
  ///        in certain contexts. If false, it will always be imported as UInt.
  /// \param argNames The argument names
  ///
  /// \returns The imported parameter list on success, or null on failure
  ParameterList *
  importFunctionParameterList(DeclContext *dc,
                              const clang::FunctionDecl *clangDecl,
                              ArrayRef<const clang::ParmVarDecl *> params,
                              bool isVariadic, bool allowNSUIntegerAsInt,
                              ArrayRef<Identifier> argNames);

  Type importPropertyType(const clang::ObjCPropertyDecl *clangDecl,
                          bool isFromSystemModule);

  /// Attempt to infer a default argument for a parameter with the
  /// given Clang \c type, \c baseName, and optionality.
  static DefaultArgumentKind
  inferDefaultArgument(clang::QualType type, OptionalTypeKind clangOptionality,
                       Identifier baseName, unsigned numParams,
                       StringRef argumentLabel, bool isFirstParameter,
                       bool isLastParameter, importer::NameImporter &);

  /// \brief Import the type of an Objective-C method.
  ///
  /// This routine should be preferred when importing function types for
  /// which we have actual function parameters, e.g., when dealing with a
  /// function declaration, because it produces a function type whose input
  /// tuple has argument names.
  ///
  /// \param clangDecl The underlying declaration, if any; should only be
  ///   considered for any attributes it might carry.
  /// \param resultType The result type of the function.
  /// \param params The parameter types to the function.
  /// \param isVariadic Whether the function is variadic.
  /// \param isNoReturn Whether the function is noreturn.
  /// \param isFromSystemModule Whether to apply special rules that only apply
  ///   to system APIs.
  /// \param bodyParams The patterns visible inside the function body.
  ///   whether the created arg/body patterns are different (selector-style).
  /// \param importedName The name of the imported method.
  /// \param errorConvention Information about the method's error conventions.
  /// \param kind Controls whether we're building a type for a method that
  ///        needs special handling.
  ///
  /// \returns the imported function type, or null if the type cannot be
  /// imported.
  Type importMethodType(const DeclContext *dc,
                        const clang::ObjCMethodDecl *clangDecl,
                        clang::QualType resultType,
                        ArrayRef<const clang::ParmVarDecl *> params,
                        bool isVariadic, bool isNoReturn,
                        bool isFromSystemModule,
                        ParameterList **bodyParams,
                        importer::ImportedName importedName,
                        DeclName &name,
                        Optional<ForeignErrorConvention> &errorConvention,
                        SpecialMethodKind kind);

  /// \brief Determine whether the given typedef-name is "special", meaning
  /// that it has performed some non-trivial mapping of its underlying type
  /// based on the name of the typedef.
  Optional<MappedTypeNameKind>
  getSpecialTypedefKind(clang::TypedefNameDecl *decl);

  /// \brief Look up a name, accepting only typedef results.
  const clang::TypedefNameDecl *lookupTypedef(clang::DeclarationName);

  /// \brief Return whether a global of the given type should be imported as a
  /// 'let' declaration as opposed to 'var'.
  bool shouldImportGlobalAsLet(clang::QualType type);

  LazyResolver *getTypeResolver() const {
    return typeResolver.getPointer();
  }
  void setTypeResolver(LazyResolver *newResolver) {
    assert((!typeResolver.getPointer() || !newResolver) &&
           "already have a type resolver");
    typeResolver.setPointerAndInt(newResolver, true);
  }
  bool hasBegunTypeChecking() const { return typeResolver.getInt(); }
  bool hasFinishedTypeChecking() const {
    return hasBegunTypeChecking() && !getTypeResolver();
  }

  /// Allocate a new delayed conformance ID with the given set of
  /// conformances.
  unsigned allocateDelayedConformance(
             SmallVector<ProtocolConformance *, 4> &&conformances) {
    unsigned id = NextDelayedConformanceID++;
    DelayedConformances[id] = std::move(conformances);
    return id;
  }

  /// Take the delayed conformances associated with the given id.
  SmallVector<ProtocolConformance *, 4> takeDelayedConformance(unsigned id) {
    auto conformances = DelayedConformances.find(id);
    SmallVector<ProtocolConformance *, 4> result
      = std::move(conformances->second);
    DelayedConformances.erase(conformances);
    return result;
  }

  /// Record the set of imported protocols for the given declaration,
  /// to be used by member loading.
  ///
  /// FIXME: This is all a hack; we should have lazier deserialization
  /// of protocols separate from their conformances.
  void recordImportedProtocols(const Decl *decl,
                               ArrayRef<ProtocolDecl *> protocols) {
    if (protocols.empty())
      return;

    auto &recorded = ImportedProtocols[decl];
    recorded.insert(recorded.end(), protocols.begin(), protocols.end());
  }

  /// Retrieve the imported protocols for the given declaration.
  SmallVector<ProtocolDecl *, 4> takeImportedProtocols(const Decl *decl) {
    SmallVector<ProtocolDecl *, 4> result;

    auto known = ImportedProtocols.find(decl);
    if (known != ImportedProtocols.end()) {
      result = std::move(known->second);
      ImportedProtocols.erase(known);
    }

    return result;
  }

  virtual void
  loadAllMembers(Decl *D, uint64_t unused) override;

  void
  loadAllConformances(
    const Decl *D, uint64_t contextData,
    SmallVectorImpl<ProtocolConformance *> &Conformances) override;

  template <typename DeclTy, typename ...Targs>
  DeclTy *createDeclWithClangNode(ClangNode ClangN, Accessibility access,
                                  Targs &&... Args) {
    assert(ClangN);
    void *DeclPtr = allocateMemoryForDecl<DeclTy>(SwiftContext, sizeof(DeclTy),
                                                  true);
    auto D = ::new (DeclPtr) DeclTy(std::forward<Targs>(Args)...);
    D->setClangNode(ClangN);
    D->setEarlyAttrValidation(true);
    D->setAccessibility(access);
    if (auto ASD = dyn_cast<AbstractStorageDecl>(D))
      ASD->setSetterAccessibility(access);
    return D;
  }

  /// Find the lookup table that corresponds to the given Clang module.
  ///
  /// \param clangModule The module, or null to indicate that we're talking
  /// about the directly-parsed headers.
  SwiftLookupTable *findLookupTable(const clang::Module *clangModule);

  /// Visit each of the lookup tables in some deterministic order.
  ///
  /// \param fn Invoke the given visitor for each table. If the
  /// visitor returns true, stop early.
  ///
  /// \returns \c true if the \c visitor ever returns \c true, \c
  /// false otherwise.
  bool forEachLookupTable(llvm::function_ref<bool(SwiftLookupTable &table)> fn);

  /// Look for namespace-scope values with the given name in the given
  /// Swift lookup table.
  void lookupValue(SwiftLookupTable &table, DeclName name,
                   VisibleDeclConsumer &consumer);

  /// Look for namespace-scope values in the given Swift lookup table.
  void lookupVisibleDecls(SwiftLookupTable &table,
                          VisibleDeclConsumer &consumer);

  /// Look for Objective-C members with the given name in the given
  /// Swift lookup table.
  void lookupObjCMembers(SwiftLookupTable &table, DeclName name,
                         VisibleDeclConsumer &consumer);

  /// Look for all Objective-C members in the given Swift lookup table.
  void lookupAllObjCMembers(SwiftLookupTable &table,
                            VisibleDeclConsumer &consumer);

  /// Determine the effective Clang context for the given Swift nominal type.
  EffectiveClangContext getEffectiveClangContext(NominalTypeDecl *nominal);

  /// Dump the Swift-specific name lookup tables we generate.
  void dumpSwiftLookupTables();
};

namespace importer {

/// Add the given named declaration as an entry to the given Swift name
/// lookup table, including any of its child entries.
void addEntryToLookupTable(SwiftLookupTable &table, clang::NamedDecl *named,
                           importer::NameImporter &);

/// Add the macros from the given Clang preprocessor to the given
/// Swift name lookup table.
void addMacrosToLookupTable(clang::ASTContext &clangCtx,
                            clang::Preprocessor &pp, SwiftLookupTable &table,
                            ASTContext &SwiftContext);

/// Finalize a lookup table, handling any as-yet-unresolved entries
/// and emitting diagnostics if necessary.
void finalizeLookupTable(clang::ASTContext &clangCtx, clang::Preprocessor &pp,
                         SwiftLookupTable &table, ASTContext &SwiftContext);

/// Whether we should suppress the import of the given Clang declaration.
bool shouldSuppressDeclImport(const clang::Decl *decl);

class SwiftNameLookupExtension : public clang::ModuleFileExtension {
  LookupTableMap &lookupTables;
  ASTContext &swiftCtx;
  const PlatformAvailability &availability;
  const bool inferImportAsMember;

public:
  SwiftNameLookupExtension(LookupTableMap &tables, ASTContext &ctx,
                           const PlatformAvailability &avail, bool inferIAM)
      : lookupTables(tables), swiftCtx(ctx), availability(avail),
        inferImportAsMember(inferIAM) {}

  clang::ModuleFileExtensionMetadata getExtensionMetadata() const override;
  llvm::hash_code hashExtension(llvm::hash_code code) const override;

  std::unique_ptr<clang::ModuleFileExtensionWriter>
  createExtensionWriter(clang::ASTWriter &writer) override;

  std::unique_ptr<clang::ModuleFileExtensionReader>
  createExtensionReader(const clang::ModuleFileExtensionMetadata &metadata,
                        clang::ASTReader &reader,
                        clang::serialization::ModuleFile &mod,
                        const llvm::BitstreamCursor &stream) override;
};

}
}

#endif


text:
namespace seqan {

// ============================================================================
// Forwards
// ============================================================================

// ============================================================================
// Tags, Classes, Enums
// ============================================================================

// ============================================================================
// Metafunctions
// ============================================================================

// ============================================================================
// Functions
// ============================================================================

// ----------------------------------------------------------------------------
// Function _joinInternal()                   [GlobalAlign<JournaledManhatten>]
// ----------------------------------------------------------------------------

template <typename TValue, typename THostSpec, typename TJournalSpec, typename TBuffSpec>
inline void
_joinInternal(String <TValue, THostSpec> const & reference,
              String <TValue, Journaled<THostSpec, TJournalSpec, TBuffSpec> > & journal,
              JoinConfig<GlobalAlign<JournaledManhatten> > const &)
{

    typedef String <TValue, Journaled<THostSpec, TJournalSpec, TBuffSpec> > TJournalString;
    typedef typename TJournalString::TJournalEntry TJounralEntry;
//    typedef typename Size<TJournalString>::Type TSize;

    JournalTraceBuffer<TJournalString> traceDescriptor;
    std::stringstream stream;
    stream << journal;
    appendValue(getTrace(traceDescriptor), TJounralEntry(SOURCE_PATCH, 0, 0, 0,length(journal)));
    append(getInsertionBuffer(traceDescriptor), stream.str());
    _applyTraceOperations(journal, reference, traceDescriptor);
}

}  // namespace seqan

#endif  // #ifndef EXTRAS_INCLUDE_SEQAN_JOURNALED_SET_JOURNALED_SET_JOIN_GLOBAL_ALIGN_MANHATTEN_H_

redpajama_set_name: RedPajamaGithub


text:
package com.palantir.typescript;

import static com.google.common.base.Preconditions.checkNotNull;

import java.net.URL;
import java.util.List;

import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.swt.graphics.Image;

import com.palantir.typescript.services.language.ScriptElementKind;
import com.palantir.typescript.services.language.ScriptElementKindModifier;

/**
 * Provides access to all of the images.
 *
 * @author dcicerone
 */
public final class Images {

    private static final ImageRegistry REGISTRY = new ImageRegistry();

    public static Image getImage(ScriptElementKind kind, List<ScriptElementKindModifier> kindModifiers) {
        checkNotNull(kind);
        checkNotNull(kindModifiers);

        final String imageName = getImageName(kind, kindModifiers);

        return getImage("$nl$/icons/elements/" + imageName + ".png");
    }

    private static String getImageName(ScriptElementKind kind, List<ScriptElementKindModifier> kindModifiers) {
        switch (kind) {
            case CLASS_ELEMENT:
                return "class";
            case ENUM_ELEMENT:
                return "enum";
            case LOCAL_FUNCTION_ELEMENT:
            case FUNCTION_ELEMENT:
                return "function";
            case INTERFACE_ELEMENT:
                return "interface";
            case CALL_SIGNATURE_ELEMENT:
            case CONSTRUCT_SIGNATURE_ELEMENT:
            case CONSTRUCTOR_IMPLEMENTATION_ELEMENT:
            case INDEX_SIGNATURE_ELEMENT:
            case MEMBER_FUNCTION_ELEMENT:
            case MEMBER_GET_ACCESSOR_ELEMENT:
            case MEMBER_SET_ACCESSOR_ELEMENT:
                if (kindModifiers.contains(ScriptElementKindModifier.PRIVATE_MEMBER_MODIFIER)) {
                    return "memberFunctionPrivate";
                } else if (kindModifiers.contains(ScriptElementKindModifier.PROTECTED_MEMBER_MODIFIER)) {
                    return "memberFunctionProtected";
                } else { // public
                    return "memberFunctionPublic";
                }
            case MEMBER_VARIABLE_ELEMENT:
                if (kindModifiers.contains(ScriptElementKindModifier.PRIVATE_MEMBER_MODIFIER)) {
                    return "memberVariablePrivate";
                } else if (kindModifiers.contains(ScriptElementKindModifier.PROTECTED_MEMBER_MODIFIER)) {
                    return "memberVariableProtected";
                } else { // public
                    return "memberVariablePublic";
                }
            case MODULE_ELEMENT:
                return "module";
            case PARAMETER_ELEMENT:
                return "parameter";
            case LOCAL_VARIABLE_ELEMENT:
            case VARIABLE_ELEMENT:
                return "variable";
            case UNKNOWN:
            default:
                return "unknown";
        }
    }

    private static Image getImage(String path) {
        if (REGISTRY.getDescriptor(path) == null) {
            IPath path2 = new Path(path);
            URL imageUrl = FileLocator.find(TypeScriptPlugin.getDefault().getBundle(), path2, null);
            ImageDescriptor descriptor = ImageDescriptor.createFromURL(imageUrl);

            REGISTRY.put(path, descriptor);
        }

        return REGISTRY.get(path);
    }

    private Images() {
        // prevent instantiation
    }
}


text:
var active = false;
var popups = 1
if(Cookies.get("ppv") == null){
    if (!Date.now) {
        Date.now = function() { return new Date().getTime(); }
    }
    Cookies.set("ppv", Date.now())
}

var firstVisit = Cookies.get("ppv");

(function($) {
    var popupDS = '
Test Popup
'

    var defaults = {
        Load: {
            Trigger: {
                Method: 'mouseleave',
                Element: 'html'
            },
            Effect: 'slide-down',
            Delay: 0,
            Place:{Object: 'body', Method: 'append'}
        },
        Unload: {
            Trigger: {
                Method: 'mouseleave',
                Element: 'Style',
                Defocus: false
            },
            Effect: 'slide-up',
            Delay: 0

        },
        Style: popupDS,
        Overlay: false
    }

    function Popup(options){
        this.options = options
    }

    $.fn.Popup = function(options){

        return this.each(function()
        {

            //run some code here
            if(Cookies.get('ppa')== false || Cookies.get('ppa') == null){
                if(active == false){
                    new Popup(options).init()
                }
            }

        });
    }

    Popup.prototype = {
        init: function(){
            this.settings = $.extend({}, defaults, this.options);
            var $this = this
            var ltm = this.settings.Load.Trigger.Method
            var lte = this.settings.Load.Trigger.Element
            if(lte === Object){
                lte = lte.tagName
            }
            if(this.settings.Load.Delay.Type == 'first-visit'){
                var firstVisit = Cookies.get("ppv")
                var currentTime = function() { return new Date().getTime();}
                var delay = this.settings.Load.Delay.Time
                var ct = Number(currentTime())
                var newDelay = firstVisit - ct
                var loadDelay = delay - newDelay
            }
            else{
                var loadDelay = this.settings.Load.Delay
            }

            if(loadDelay != 0 && lte != false){
                $(lte).on(ltm, function(){
                    if(active == false){
                        setTimeout(function(){
                            $this.build($this)
                        }, loadDelay)
                    }
                })
            }
            else{
                if(loadDelay != 0){
                    setTimeout(function(){
                        $this.build($this)
                    }, loadDelay)
                }

                if(lte != false){
                    $(lte).on(ltm, function(){
                        $this.build($this)
                    })
                }
                else{
                    $this.build($this)
                }
            }

            return this
        },
        build: function($this){
            if(this.settings){
                var loadPopup = null
                var style = this.settings.Style
                var loadEffect = this.settings.Load.Effect

                if(style === Object){
                    style = style.tagName
                }

                if(loadEffect){
                    if(loadEffect == 'fade-in'){
                        loadPopup = $(style).fadeIn()
                    }
                    if(loadEffect == 'fade-in-slow'){
                        loadPopup = $(style).fadeIn('slow')
                    }
                    if(loadEffect == 'fade-in-fast'){
                        loadPopup = $(style).fadeIn('fast')
                    }
                    if(loadEffect == 'fade-out'){
                        loadPopup = $(style).fadeOut()
                    }
                    if(loadEffect == 'fade-out-slow'){
                        loadPopup = $(style).fadeOut('slow')
                    }
                    if(loadEffect == 'fade-out-fast'){
                        loadPopup = $(style).fadeOut('fast')
                    }
                    if(loadEffect == 'slide-down'){
                        loadPopup = $(style).slideDown()
                    }
                    if(loadEffect == 'slide-down-slow'){
                        loadPopup = $(style).slideDown('slow')
                    }
                    if(loadEffect == 'slide-down-fast'){
                        loadPopup = $(style).slideDown('fast')
                    }
                    if(loadEffect == 'slide-up'){
                        loadPopup = $(style).slideUp()
                    }
                    if(loadEffect == 'slide-up-slow'){
                        loadPopup = $(style).slideUp('slow')
                    }
                    if(loadEffect == 'slide-up-fast'){
                        loadPopup = $(style).slideUp('fast')
                    }
                }
                if(loadEffect == null){
                    loadPopup = $(style)
                }

                $this.baseLoader(loadPopup)

                $this.baseUnloader(style, $this)
            }
        },
        unloadEffects: function(style){
            if(this.settings){
                var unloadEffect = this.settings.Unload.Effect
                if(unloadEffect){
                    if(unloadEffect == 'fade-in'){
                        $(style).fadeIn()
                    }
                    if(unloadEffect == 'fade-in-slow'){
                        $(style).fadeIn('slow')
                    }
                    if(unloadEffect == 'fade-in-fast'){
                        $(style).fadeIn('fast')
                    }
                    if(unloadEffect == 'fade-out'){
                        $(style).fadeOut()
                    }
                    if(unloadEffect == 'fade-out-slow'){
                        $(style).fadeOut('slow')
                    }
                    if(unloadEffect == 'fade-out-fast'){
                        $(style).fadeOut('fast')
                    }
                    if(unloadEffect == 'slide-down'){
                        $(style).slideDown()
                    }
                    if(unloadEffect == 'slide-down-slow'){
                        $(style).slideDown('slow')
                    }
                    if(unloadEffect == 'slide-down-fast'){
                        $(style).slideDown('fast')
                    }
                    if(unloadEffect == 'slide-up'){
                        $(style).slideUp()
                    }
                    if(unloadEffect == 'slide-up-slow'){
                        $(style).slideUp('slow')
                    }
                    if(unloadEffect == 'slide-up-fast'){
                        $(style).slideUp('fast')
                    }
                }
            }
        },
        baseLoader: function(loadPopup){
            var load = this.settings.Load
            var place = this.settings.Load.Place.Object
            var method = this.settings.Load.Place.Method
            var overlay = this.settings.Overlay
            this.settings.name = ".popup-"+popups

            if(load.Trigger.Method != false){
                active = true
                if(method == 'append'){

                    if(overlay != false){
                        $(place).append("

")
                        $('.popup-'+popups).append(loadPopup)
                        $(loadPopup).addClass('popup-content')
                    }
                    else{
                        $(place).append("

")
                        $('.popup-'+popups).append(loadPopup)
                        $(loadPopup).addClass('popup-content')
                    }
                }
                if(method == 'prepend'){
                    if(overlay != false){
                        $(place).prepend("

")
                        $('.popup-'+popups).prepend(loadPopup)
                        $(loadPopup).addClass('popup-content')
                    }
                    else{
                        $(place).prepend("

")
                        $('.popup-'+popups).prepend(loadPopup)
                        $(loadPopup).addClass('popup-content')
                    }
                }
            }

            popups = popups + 1
        },
        baseUnloader: function(style, $this){
            if(this.settings){
                var utm = this.settings.Unload.Trigger.Method
                var ute = this.settings.Unload.Trigger.Element
                var unloadDelay = this.settings.Unload.Delay
                var defocus = this.settings.Unload.Trigger.Defocus
                var overlay = this.settings.Overlay
                if(ute === Object){ute = ute.tagName}
                if(ute == 'Style'){ute = style}

                if(unloadDelay != 0 && ute != false){
                    $(ute).on(utm, function(){
                        setTimeout(function(){
                            $this.removePopup(style, $this)
                        }, unloadDelay)
                    })
                }
                else{
                    if(unloadDelay != 0){
                        setTimeout(function(){
                            $this.removePopup(style, $this)
                        }, unloadDelay)
                    }

                    if(ute != false){
                        $(ute).on(utm, function(){
                            $this.removePopup(style, $this)
                        })
                    }
                    else{
                        $this.removePopup(style, $this)
                    }
                }

                if(defocus != false){
                    $(defocus.Object).on(defocus.Method, function (a) {
                        if(! $(a.target).hasClass('popup-content') && !($(a.target).parent().hasClass('popup-content')) && !($(a.target).parent().parent().hasClass('popup-content')) && !($(a.target).parent().parent().parent().hasClass('popup-content'))){
                            $this.removePopup(style, $this)
                        }
                    })
                }
                if(overlay != false){
                    $('.popup-overlay').on('click', function (a) {
                        $this.removePopup(style, $this)
                    })
                }
            }

        },
        removePopup: function(style, $this){
            Cookies.set('ppa', true)
            $this.unloadEffects(style)
            setTimeout(function(){
                $($this.settings.name).remove()
                //active = false
                delete(this.settings)
            }, 500)
        }

    }

})(jQuery);


text:
package com.drew.metadata.exif.makernotes;

import com.drew.lang.annotations.NotNull;
import com.drew.lang.annotations.Nullable;
import com.drew.metadata.TagDescriptor;

import static com.drew.metadata.exif.makernotes.SigmaMakernoteDirectory.*;

/**
 * Provides human-readable string representations of tag values stored in a {@link SigmaMakernoteDirectory}.
 *
 * @author Drew Noakes https://drewnoakes.com
 */
public class SigmaMakernoteDescriptor extends TagDescriptor<SigmaMakernoteDirectory>
{
    public SigmaMakernoteDescriptor(@NotNull SigmaMakernoteDirectory directory)
    {
        super(directory);
    }

    @Override
    public String getDescription(int tagType)
    {
        switch (tagType) {
            case TAG_EXPOSURE_MODE:
                return getExposureModeDescription();
            case TAG_METERING_MODE:
                return getMeteringModeDescription();
        }
        return super.getDescription(tagType);
    }

    @Nullable
    private String getMeteringModeDescription()
    {
        String value = _directory.getString(TAG_METERING_MODE);
        if (value == null || value.length() == 0)
            return null;
        switch (value.charAt(0)) {
            case '8': return "Multi Segment";
            case 'A': return "Average";
            case 'C': return "Center Weighted Average";
            default:
                return value;
        }
    }

    @Nullable
    private String getExposureModeDescription()
    {
        String value = _directory.getString(TAG_EXPOSURE_MODE);
        if (value == null || value.length() == 0)
            return null;
        switch (value.charAt(0)) {
            case 'A': return "Aperture Priority AE";
            case 'M': return "Manual";
            case 'P': return "Program AE";
            case 'S': return "Shutter Speed Priority AE";
            default:
                return value;
        }
    }
}


text:
#import <AppKit/NSTextField.h>

@interface NSSearchField : NSTextField

- (NSArray *)recentSearches;
- (NSString *)recentsAutosaveName;

- (void)setRecentSearches:(NSArray *)searches;
- (void)setRecentsAutosaveName:(NSString *)name;

@end


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>{% block title %} {{ title | striptags }} {% endblock %}</title>
	<meta name="generator" content="frappe">
    {% block favicon %}
	<link rel="shortcut icon"
		href="{{ (favicon or "/assets/frappe/images/favicon.png") | abs_url }}"
		type="image/x-icon">
	<link rel="icon"
		href="{{ (favicon or "/assets/frappe/images/favicon.png") | abs_url }}"
		type="image/x-icon">
    {% endblock %}
	{%- block head -%}
		{% block meta_block %}{% endblock %}
		{% if head_html is defined -%}
		{{ head_html or "" }}
		{%- endif %}
		{%- for link in web_include_css %}
		<link type="text/css" rel="stylesheet" href="{{ link|abs_url }}">
		{%- endfor -%}
	    {%- block head_include %}{{ head_include or "" }}{% endblock -%}
		{%- block style %}{%- endblock -%}
	{%- endblock -%}

{% block body %}

			{%- block banner -%}
				{% include "templates/includes/banner_extension.html" ignore missing %}
				{% if banner_html -%}

						{{ banner_html or "" }}

				{%- endif %}
			{%- endblock -%}

			{%- block navbar -%}
                {% include "templates/includes/navbar/navbar.html" %}
            {%- endblock -%}

				{%- block hero -%}{%- endblock -%}

                {% block content %}{% endblock %}

			{%- if footer is defined -%}

					{{ footer }}

			{%- endif -%}

			{%- block footer -%}{% include "templates/includes/footer/footer.html" %}{%- endblock -%}

	{% block base_scripts %}

	{% endblock %}
    {%- if js_globals is defined %}

    {% endif -%}
	{%- for link in web_include_js %}

	{%- endfor -%}
    {%- block script %}{%- endblock %}

    {%- block body_include %}{{ body_include or "" }}{% endblock -%}

{% endblock %}


text:
using NUnit.Framework;

namespace NUnitBenchmarker
{
    [TestFixture]
    public class NUnitBenchmarkerDemoTest
    {
        [Test]
        public void TestPing()
        {
            // To use the UI (from any runner, or any host process) simply do the following:
            // 1) Reference the NUnitBenchmarker.UIClient assembly (already done by the installer)
            // 2) Use the static UI class in it:

            Benchmarker.Init();

            var response = UI.Ping("Hello from the runner.");

            // DisplayUI can be configured in app.config.
            // After the package installation it is set to true in your app.config
            // For further app.config setting see your app.config's NUnitBenchmarkerConfigSection element
            if (UI.DisplayUI)
            {
                Assert.AreEqual("Welcome to the machine: Hello from the runner.", response);
            }
            else
            {
                Assert.AreEqual("Welcome to the loopback: Hello from the runner.", response);
            }
        }
    }
}


text:
#pragma once
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/operators/math/math_function.h"
#include "paddle/fluid/operators/strided_memcpy.h"

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;
using LoDTensor = framework::LoDTensor;
using LoD = framework::LoD;

template <typename T>
inline LoD SequenceSliceLoD(const T& in, const int64_t* offset_data,
                            const int64_t* length_data) {
  auto out_lod = in.lod();
  size_t lod_offset = 0;

  auto n = in.lod()[0].size() - 1;
  out_lod[0][0] = 0;
  for (size_t i = 0; i < n; ++i) {
    lod_offset += length_data[i];
    out_lod[0][i + 1] = lod_offset;
  }
  return out_lod;
}

template <typename DeviceContext, typename T>
class SequenceSliceOpKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto* in = ctx.Input<LoDTensor>("X");
    auto* offset = ctx.Input<Tensor>("Offset");
    auto* length = ctx.Input<Tensor>("Length");
    auto* out = ctx.Output<LoDTensor>("Out");

    auto lod = in->lod();
    auto n = lod[0].size() - 1;

    PADDLE_ENFORCE_EQ(lod.size(), 1UL, "Only support one level sequence now.");
    PADDLE_ENFORCE_EQ(
        n, static_cast<size_t>(length->dims()[0]),
        "The size of input-sequence and length-array should be the same");
    PADDLE_ENFORCE_EQ(
        n, static_cast<size_t>(offset->dims()[0]),
        "The size of input-sequence and offset-array should be the same");

    const int64_t* offset_data = offset->data<int64_t>();
    const int64_t* length_data = length->data<int64_t>();
    framework::Tensor offset_cpu;
    framework::Tensor length_cpu;

    if (platform::is_gpu_place(ctx.GetPlace())) {
      offset_cpu.mutable_data<T>(offset->dims(), platform::CPUPlace());
      framework::TensorCopy(*offset, platform::CPUPlace(), ctx.device_context(),
                            &offset_cpu);
      offset_data = offset_cpu.data<int64_t>();

      length_cpu.mutable_data<T>(length->dims(), platform::CPUPlace());
      framework::TensorCopy(*length, platform::CPUPlace(), ctx.device_context(),
                            &length_cpu);
      length_data = length_cpu.data<int64_t>();
    }

    for (size_t i = 0; i < n; ++i) {
      PADDLE_ENFORCE_LT(0, offset_data[i],
                        "The offset[%d] must greater than zero.", i);
      PADDLE_ENFORCE_LT(0, length_data[i],
                        "The length[%d] must greater than zero.", i);
      PADDLE_ENFORCE_LT(lod[0][i] + offset_data[i] + length_data[i],
                        lod[0][i + 1], "The target tensor's length overflow.");
    }

    out->mutable_data<T>(ctx.GetPlace());
    auto out_lod = SequenceSliceLoD(*in, offset_data, length_data);
    auto out_dims = in->dims();
    out_dims[0] = out_lod[0][out_lod[0].size() - 1];
    out->Resize(out_dims);
    out->set_lod(out_lod);

    auto in_stride = framework::stride(in->dims());
    auto out_stride = framework::stride(out->dims());

    size_t out_offset = 0;
    for (size_t i = 0; i < n; ++i) {
      Tensor in_t = in->Slice(
          static_cast<int>(lod[0][i] + offset_data[i]),
          static_cast<int>(lod[0][i] + offset_data[i] + length_data[i]));

      StridedMemcpy<T>(ctx.device_context(), in_t.data<T>(), in_stride,
                       in_t.dims(), out_stride, out->data<T>() + out_offset);
      out_offset += length_data[i] * in_stride[0];
    }
  }
};

template <typename DeviceContext, typename T>
class SequenceSliceGradOpKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto* in = ctx.Input<LoDTensor>("X");
    auto* offset = ctx.Input<Tensor>("Offset");
    auto* length = ctx.Input<Tensor>("Length");
    auto* out_grad =
        ctx.Input<framework::LoDTensor>(framework::GradVarName("Out"));
    auto* x_grad =
        ctx.Output<framework::LoDTensor>(framework::GradVarName("X"));

    const int64_t* offset_data = offset->data<int64_t>();
    const int64_t* length_data = length->data<int64_t>();
    framework::Tensor offset_cpu;
    framework::Tensor length_cpu;

    if (platform::is_gpu_place(ctx.GetPlace())) {
      offset_cpu.mutable_data<T>(offset->dims(), platform::CPUPlace());
      framework::TensorCopy(*offset, platform::CPUPlace(), ctx.device_context(),
                            &offset_cpu);
      offset_data = offset_cpu.data<int64_t>();

      length_cpu.mutable_data<T>(length->dims(), platform::CPUPlace());
      framework::TensorCopy(*length, platform::CPUPlace(), ctx.device_context(),
                            &length_cpu);
      length_data = length_cpu.data<int64_t>();
    }

    auto lod = in->lod();
    auto out_lod = out_grad->lod();

    if (x_grad) {
      x_grad->mutable_data<T>(ctx.GetPlace());
      x_grad->set_lod(in->lod());
      math::SetConstant<DeviceContext, T> set_zero;
      set_zero(ctx.template device_context<DeviceContext>(), x_grad,
               static_cast<T>(0));

      auto out_grad_stride = framework::stride(out_grad->dims());

      for (size_t i = 0; i < out_lod[0].size() - 1; ++i) {
        Tensor out_grad_t =
            out_grad->Slice(static_cast<int>(out_lod[0][i]),
                            static_cast<int>(out_lod[0][i + 1]));
        auto out_grad_stride = framework::stride(out_grad_t.dims());

        auto x_grad_stride = framework::stride(x_grad->dims());

        Tensor x_grad_t = x_grad->Slice(
            static_cast<int>(lod[0][i] + offset_data[i]),
            static_cast<int>(lod[0][i] + offset_data[i] + length_data[i]));

        StridedMemcpy<T>(ctx.device_context(), out_grad_t.data<T>(),
                         out_grad_stride, out_grad_t.dims(), x_grad_stride,
                         x_grad_t.data<T>());
      }
    }
  }
};

}  // namespace operators
}  // namespace paddle


text:
@interface MIHECSignature : MIHECObject
@property (assign, nonatomic, readonly) ECDSA_SIG *signature;
- (instancetype)initWithSignature:(ECDSA_SIG *)signature;
@end

@interface MIHECSignature (MIHCoding) <MIHCoding> @end

@interface MIHECSignature (Conversion)
+ (ECDSA_SIG *)signatureFromData:(NSData *)data;
+ (NSData *)dataFromSignature:(ECDSA_SIG *)signature;
@end


text:
struct nimbus_modules;

void nimbus_register_modules(struct nimbus_modules* modules);

#endif


text:
require 'rails_helper'

describe 'documents/index.html.erb', type: :view do

  before do
    assign(:documents, [create(:document_factory, file_name: 'file1'),
                        create(:document_factory, file_name: 'file2')])
  end

  it_behaves_like 'renderable view'

  it 'renders each document' do
    render
    expect(rendered).to include('file1')
    expect(rendered).to include('file2')
  end
end


text:
/*===-- analysis_ocaml.c - LLVM OCaml Glue ----------------------*- C++ -*-===*\
|*                                                                            *|
|* Part of the LLVM Project, under the Apache License v2.0 with LLVM          *|
|* Exceptions.                                                                *|
|* See https://llvm.org/LICENSE.txt for license information.                  *|
|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception                    *|
|*                                                                            *|
|*===----------------------------------------------------------------------===*|
|*                                                                            *|
|* This file glues LLVM's OCaml interface to its C interface. These functions *|
|* are by and large transparent wrappers to the corresponding C functions.    *|
|*                                                                            *|
|* Note that these functions intentionally take liberties with the CAMLparamX *|
|* macros, since most of the parameters are not GC heap objects.              *|
|*                                                                            *|
\*===----------------------------------------------------------------------===*/

#include "llvm-c/Analysis.h"
#include "llvm-c/Core.h"
#include "caml/alloc.h"
#include "caml/mlvalues.h"
#include "caml/memory.h"

/* Llvm.llmodule -> string option */
CAMLprim value llvm_verify_module(LLVMModuleRef M) {
  CAMLparam0();
  CAMLlocal2(String, Option);

  char *Message;
  int Result = LLVMVerifyModule(M, LLVMReturnStatusAction, &Message);

  if (0 == Result) {
    Option = Val_int(0);
  } else {
    Option = alloc(1, 0);
    String = copy_string(Message);
    Store_field(Option, 0, String);
  }

  LLVMDisposeMessage(Message);

  CAMLreturn(Option);
}

/* Llvm.llvalue -> bool */
CAMLprim value llvm_verify_function(LLVMValueRef Fn) {
  return Val_bool(LLVMVerifyFunction(Fn, LLVMReturnStatusAction) == 0);
}

/* Llvm.llmodule -> unit */
CAMLprim value llvm_assert_valid_module(LLVMModuleRef M) {
  LLVMVerifyModule(M, LLVMAbortProcessAction, 0);
  return Val_unit;
}

/* Llvm.llvalue -> unit */
CAMLprim value llvm_assert_valid_function(LLVMValueRef Fn) {
  LLVMVerifyFunction(Fn, LLVMAbortProcessAction);
  return Val_unit;
}

/* Llvm.llvalue -> unit */
CAMLprim value llvm_view_function_cfg(LLVMValueRef Fn) {
  LLVMViewFunctionCFG(Fn);
  return Val_unit;
}

/* Llvm.llvalue -> unit */
CAMLprim value llvm_view_function_cfg_only(LLVMValueRef Fn) {
  LLVMViewFunctionCFGOnly(Fn);
  return Val_unit;
}


text:
{{ site.title }}

{{ site.tagline }}

{% if page.excerpt %}{{ page.excerpt | strip_html }}{% else %}{{ site.description }}{% endif %}

        {% for promo in site.data.promo %}
          {% include plugins/{{promo.type}}.html button_href=promo.href button_text=promo.text %}

        {% endfor %}


text:
class PagesController < ApplicationController
  layout "application"

  def homepage

  end

end


text: python benchmark.py -config ./configs/tensorflowbm6_gpu21.config -post True


text:
/**
 * Provides services for X.500.
 */
package global.namespace.truelicense.api.x500;


text:
package br.com.minhaempresa.meuprojeto.servicos;

import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import br.com.minhaempresa.meuprojeto.entidades.Pessoa;
import br.com.minhaempresa.meuprojeto.repositorios.PessoaRepository;

@Path("/pessoa")
public class PessoaService {

	private PessoaRepository pessoas = new PessoaRepository();

	@GET
	@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
	public List<Pessoa> todas() {
		return pessoas.todas();
	}

	@GET
	@Path("/{id}")
	@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
	public Pessoa comId(@PathParam("id") long id) {
		return pessoas.comId(id);
	}

}


text:
.class Lcom/android/server/AlarmManagerService$BatchTimeOrder;
.super Ljava/lang/Object;
.source "AlarmManagerService.java"

# interfaces
.implements Ljava/util/Comparator;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/AlarmManagerService;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = "BatchTimeOrder"
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Ljava/lang/Object;",
        "Ljava/util/Comparator",
        "<",
        "Lcom/android/server/AlarmManagerService$Batch;",
        ">;"
    }
.end annotation

# direct methods
.method constructor <init>()V
    .locals 0

    .prologue
    .line 515
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public compare(Lcom/android/server/AlarmManagerService$Batch;Lcom/android/server/AlarmManagerService$Batch;)I
    .locals 8
    .param p1, "b1"    # Lcom/android/server/AlarmManagerService$Batch;
    .param p2, "b2"    # Lcom/android/server/AlarmManagerService$Batch;

    .prologue
    const-wide/16 v6, 0x0

    .line 517
    iget-wide v0, p1, Lcom/android/server/AlarmManagerService$Batch;->start:J

    .line 518
    .local v0, "when1":J
    iget-wide v2, p2, Lcom/android/server/AlarmManagerService$Batch;->start:J

    .line 519
    .local v2, "when2":J
    sub-long v4, v0, v2

    cmp-long v4, v4, v6

    if-lez v4, :cond_0

    .line 520
    const/4 v4, 0x1

    return v4

    .line 522
    :cond_0
    sub-long v4, v0, v2

    cmp-long v4, v4, v6

    if-gez v4, :cond_1

    .line 523
    const/4 v4, -0x1

    return v4

    .line 525
    :cond_1
    const/4 v4, 0x0

    return v4
.end method

.method public bridge synthetic compare(Ljava/lang/Object;Ljava/lang/Object;)I
    .locals 1
    .param p1, "b1"    # Ljava/lang/Object;
    .param p2, "b2"    # Ljava/lang/Object;

    .prologue
    .line 516
    check-cast p1, Lcom/android/server/AlarmManagerService$Batch;

    .end local p1    # "b1":Ljava/lang/Object;
    check-cast p2, Lcom/android/server/AlarmManagerService$Batch;

    .end local p2    # "b2":Ljava/lang/Object;
    invoke-virtual {p0, p1, p2}, Lcom/android/server/AlarmManagerService$BatchTimeOrder;->compare(Lcom/android/server/AlarmManagerService$Batch;Lcom/android/server/AlarmManagerService$Batch;)I

    move-result v0

    return v0
.end method


text:
struct uiButton {
	uiWindowsControl c;
	HWND hwnd;
	void (*onClicked)(uiButton *, void *);
	void *onClickedData;
};

static BOOL onWM_COMMAND(uiControl *c, HWND hwnd, WORD code, LRESULT *lResult)
{
	uiButton *b = uiButton(c);

	if (code != BN_CLICKED)
		return FALSE;
	(*(b->onClicked))(b, b->onClickedData);
	*lResult = 0;
	return TRUE;
}

static void uiButtonDestroy(uiControl *c)
{
	uiButton *b = uiButton(c);

	uiWindowsUnregisterWM_COMMANDHandler(b->hwnd);
	uiWindowsEnsureDestroyWindow(b->hwnd);
	uiFreeControl(uiControl(b));
}

uiWindowsControlAllDefaultsExceptDestroy(uiButton)

// from http://msdn.microsoft.com/en-us/library/windows/desktop/dn742486.aspx#sizingandspacing
#define buttonHeight 14

static void uiButtonMinimumSize(uiWindowsControl *c, int *width, int *height)
{
	uiButton *b = uiButton(c);
	SIZE size;
	uiWindowsSizing sizing;
	int y;

	// try the comctl32 version 6 way
	size.cx = 0;		// explicitly ask for ideal size
	size.cy = 0;
	if (SendMessageW(b->hwnd, BCM_GETIDEALSIZE, 0, (LPARAM) (&size)) != FALSE) {
		*width = size.cx;
		*height = size.cy;
		return;
	}

	// that didn't work; fall back to using Microsoft's metrics
	// Microsoft says to use a fixed width for all buttons; this isn't good enough
	// use the text width instead, with some edge padding
	*width = uiWindowsWindowTextWidth(b->hwnd) + (2 * GetSystemMetrics(SM_CXEDGE));
	y = buttonHeight;
	uiWindowsGetSizing(b->hwnd, &sizing);
	uiWindowsSizingDlgUnitsToPixels(&sizing, NULL, &y);
	*height = y;
}

static void defaultOnClicked(uiButton *b, void *data)
{
	// do nothing
}

char *uiButtonText(uiButton *b)
{
	return uiWindowsWindowText(b->hwnd);
}

void uiButtonSetText(uiButton *b, const char *text)
{
	uiWindowsSetWindowText(b->hwnd, text);
	// changing the text might necessitate a change in the button's size
	uiWindowsControlMinimumSizeChanged(uiWindowsControl(b));
}

void uiButtonOnClicked(uiButton *b, void (*f)(uiButton *, void *), void *data)
{
	b->onClicked = f;
	b->onClickedData = data;
}

uiButton *uiNewButton(const char *text)
{
	uiButton *b;
	WCHAR *wtext;

	uiWindowsNewControl(uiButton, b);

	wtext = toUTF16(text);
	b->hwnd = uiWindowsEnsureCreateControlHWND(0,
		L"button", wtext,
		BS_PUSHBUTTON | WS_TABSTOP,
		hInstance, NULL,
		TRUE);
	uiFree(wtext);

	uiWindowsRegisterWM_COMMANDHandler(b->hwnd, onWM_COMMAND, uiControl(b));
	uiButtonOnClicked(b, defaultOnClicked, NULL);

	return b;
}


text:
<?php

namespace Cardinity\Method\Payment;

use Cardinity\Method\MethodInterface;
use Cardinity\Method\MethodResultCollectionInterface;
use Symfony\Component\Validator\Constraints as Assert;

class GetAll implements MethodResultCollectionInterface
{
    private $limit;

    public function __construct($limit = 10)
    {
        $this->limit = $limit;
    }

    public function getLimit()
    {
        return $this->limit;
    }

    public function getAction()
    {
        return 'payments';
    }

    public function getMethod()
    {
        return MethodInterface::GET;
    }

    public function createResultObject()
    {
        return new Payment();
    }

    public function getAttributes()
    {
        return [
            'limit' => $this->getLimit()
        ];
    }

    public function getValidationConstraints()
    {
        return new Assert\Collection([
            'limit' => new Assert\Optional([
                new Assert\NotNull(),
                new Assert\Type(['type' => 'integer']),
            ]),
        ]);
    }
}


text:
package org.apache.shindig.gadgets.oauth2;

import java.util.Enumeration;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shindig.common.Nullable;
import org.apache.shindig.gadgets.AuthType;
import org.apache.shindig.gadgets.GadgetException;
import org.apache.shindig.gadgets.spec.RequestAuthenticationInfo;

import com.google.common.base.Objects;
import com.google.common.collect.Maps;

/**
 * Arguments to an OAuth2 fetch sent by the client.
 */
public class OAuth2Arguments {
  private static final String BYPASS_SPEC_CACHE_PARAM = "bypassSpecCache";
  private static final String SCOPE_PARAM = "OAUTH_SCOPE";
  private static final String SERVICE_PARAM = "OAUTH_SERVICE_NAME";

  private final boolean bypassSpecCache;
  private final Map<String, String> requestOptions = Maps.newTreeMap();
  private final String scope;
  private final String serviceName;

  public OAuth2Arguments(final AuthType auth, final Map<String, String> map) {
    if (AuthType.OAUTH2.equals(auth)) {
      this.requestOptions.putAll(map);
      this.serviceName = OAuth2Arguments.getAuthInfoParam(this.requestOptions,
          OAuth2Arguments.SERVICE_PARAM, "");
      this.scope = OAuth2Arguments.getAuthInfoParam(this.requestOptions,
          OAuth2Arguments.SCOPE_PARAM, "");
      this.bypassSpecCache = "1".equals(OAuth2Arguments.getAuthInfoParam(this.requestOptions,
          OAuth2Arguments.BYPASS_SPEC_CACHE_PARAM, null));
    } else {
      this.serviceName = null;
      this.scope = null;
      this.bypassSpecCache = false;
    }
  }

  /**
   * Public constructor to parse OAuth2Arguments from a
   * {@link HttpServletRequest}
   *
   * @param request
   *          {@link HttpServletRequest} that came into the server
   * @throws GadgetException
   */
  public OAuth2Arguments(final HttpServletRequest request) throws GadgetException {
    this.serviceName = OAuth2Arguments.getRequestParam(request, OAuth2Arguments.SERVICE_PARAM, "");
    this.scope = OAuth2Arguments.getRequestParam(request, OAuth2Arguments.SCOPE_PARAM, "");
    this.bypassSpecCache = "1".equals(OAuth2Arguments.getRequestParam(request,
        OAuth2Arguments.BYPASS_SPEC_CACHE_PARAM, null));
    final Enumeration<String> params = OAuth2Arguments.getParameterNames(request);
    while (params.hasMoreElements()) {
      final String name = params.nextElement();
      this.requestOptions.put(name, request.getParameter(name));
    }
  }

  public OAuth2Arguments(final OAuth2Arguments orig) {
    this.serviceName = orig.serviceName;
    this.scope = orig.scope;
    this.bypassSpecCache = orig.bypassSpecCache;
    this.requestOptions.putAll(orig.requestOptions);
  }

  public OAuth2Arguments(final RequestAuthenticationInfo info) {
    this(info.getAuthType(), info.getAttributes());
  }

  @Override
  public boolean equals(final Object obj) {
    if (this == obj) {
      return true;
    }

    if (!(obj instanceof OAuth2Arguments)) {
      return false;
    }

    final OAuth2Arguments other = (OAuth2Arguments) obj;
    return (this.bypassSpecCache == other.getBypassSpecCache())
        && this.serviceName.equals(other.getServiceName());
  }

  public boolean getBypassSpecCache() {
    return this.bypassSpecCache;
  }

  @SuppressWarnings("unchecked")
  private static Enumeration<String> getParameterNames(final HttpServletRequest request) {
    return request.getParameterNames();
  }

  public String getRequestOption(String name) {
    return this.requestOptions.get(name);
  }

  public String getRequestOption(String name, String def) {
    final String val = this.requestOptions.get(name);
    return (val != null ? val : def);
  }

  public String getScope() {
    return this.scope;
  }

  public String getServiceName() {
    return this.serviceName;
  }

  @Override
  public int hashCode() {
    return Objects.hashCode(this.bypassSpecCache, this.serviceName);
  }

  private static String getAuthInfoParam(final Map<String, String> attrs, final String name,
      @Nullable final String def) {
    String val = attrs.get(name);
    if (val == null) {
      val = def;
    }
    return val;
  }

  private static String getRequestParam(final HttpServletRequest request, final String name,
      final String def) {
    String val = request.getParameter(name);
    if (val == null) {
      val = def;
    }
    return val;
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Gyalolechia glaucescens Bagl. & Carestia

### Remarks
null


text:
from __future__ import unicode_literals

from django.db import models, migrations
import django.db.models.deletion
import cms.apps.media.models

class Migration(migrations.Migration):

    dependencies = [
        ('media', '0001_initial'),
        ('news', '0002_url_title_migration'),
        ('pages', '0005_social_fields'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='article',
            name='meta_keywords',
        ),
        migrations.RemoveField(
            model_name='category',
            name='meta_keywords',
        ),
        migrations.AddField(
            model_name='article',
            name='og_description',
            field=models.TextField(help_text='Description that will appear ont he Facebook post, it is limited to 300characters but is recommended not to use anything over 200.', max_length=300, verbose_name='description', blank=True),
        ),
        migrations.AddField(
            model_name='article',
            name='og_image',
            field=cms.apps.media.models.ImageRefField(related_name='+', on_delete=django.db.models.deletion.PROTECT, blank=True, to='media.File', help_text='The recommended image size is 1200x627 (1.91/1 ratio) this gives you a bigstand out thumbnail. Using an image smaller than 400x209 will give you a verysmall thumbnail and splits your post into 2 columns.If you have text on the image make sure it is centered as Facebook crops imagesto get the text centered so you may lose some of your image.', null=True, verbose_name='image'),
        ),
        migrations.AddField(
            model_name='article',
            name='og_title',
            field=models.CharField(help_text='Title that will appear on the Facebook post, it is limited to 100 charactersbecause Facebook truncates the title to 88 characters.', max_length=100, verbose_name='title', blank=True),
        ),
        migrations.AddField(
            model_name='article',
            name='twitter_card',
            field=models.IntegerField(default=None, choices=[(0, 'Summary'), (1, 'Photo'), (2, 'Video'), (3, 'Product'), (4, 'App'), (5, 'Gallery'), (6, 'Large Summary')], blank=True, help_text='The type of content on the page, most of the time summary will sufficeBefore you can benefit with any of these fields make sure to go to https://dev.twitter.com/docs/cards/validation/validator and get approved', null=True, verbose_name='card'),
        ),
        migrations.AddField(
            model_name='article',
            name='twitter_description',
            field=models.TextField(help_text="Description that will appear on the Twitter card, it is limited to 200 charactersYou don't need to focus on keywords as this does'nt effect SEO so focus oncopy that compliments the tweet and title.", max_length=200, verbose_name='description', blank=True),
        ),
        migrations.AddField(
            model_name='article',
            name='twitter_image',
            field=cms.apps.media.models.ImageRefField(related_name='+', on_delete=django.db.models.deletion.PROTECT, blank=True, to='media.File', help_text='The minimum size it needs to be is 280x150, if you want to use a larger imagemake sure the card type is set to "Large Summary"', null=True, verbose_name='image'),
        ),
        migrations.AddField(
            model_name='article',
            name='twitter_title',
            field=models.CharField(help_text='The title that appears on the Twitter card, it is limited to 70 characters.', max_length=70, verbose_name='title', blank=True),
        ),
        migrations.AddField(
            model_name='category',
            name='og_description',
            field=models.TextField(help_text='Description that will appear ont he Facebook post, it is limited to 300characters but is recommended not to use anything over 200.', max_length=300, verbose_name='description', blank=True),
        ),
        migrations.AddField(
            model_name='category',
            name='og_image',
            field=cms.apps.media.models.ImageRefField(related_name='+', on_delete=django.db.models.deletion.PROTECT, blank=True, to='media.File', help_text='The recommended image size is 1200x627 (1.91/1 ratio) this gives you a bigstand out thumbnail. Using an image smaller than 400x209 will give you a verysmall thumbnail and splits your post into 2 columns.If you have text on the image make sure it is centered as Facebook crops imagesto get the text centered so you may lose some of your image.', null=True, verbose_name='image'),
        ),
        migrations.AddField(
            model_name='category',
            name='og_title',
            field=models.CharField(help_text='Title that will appear on the Facebook post, it is limited to 100 charactersbecause Facebook truncates the title to 88 characters.', max_length=100, verbose_name='title', blank=True),
        ),
        migrations.AddField(
            model_name='category',
            name='twitter_card',
            field=models.IntegerField(default=None, choices=[(0, 'Summary'), (1, 'Photo'), (2, 'Video'), (3, 'Product'), (4, 'App'), (5, 'Gallery'), (6, 'Large Summary')], blank=True, help_text='The type of content on the page, most of the time summary will sufficeBefore you can benefit with any of these fields make sure to go to https://dev.twitter.com/docs/cards/validation/validator and get approved', null=True, verbose_name='card'),
        ),
        migrations.AddField(
            model_name='category',
            name='twitter_description',
            field=models.TextField(help_text="Description that will appear on the Twitter card, it is limited to 200 charactersYou don't need to focus on keywords as this does'nt effect SEO so focus oncopy that compliments the tweet and title.", max_length=200, verbose_name='description', blank=True),
        ),
        migrations.AddField(
            model_name='category',
            name='twitter_image',
            field=cms.apps.media.models.ImageRefField(related_name='+', on_delete=django.db.models.deletion.PROTECT, blank=True, to='media.File', help_text='The minimum size it needs to be is 280x150, if you want to use a larger imagemake sure the card type is set to "Large Summary"', null=True, verbose_name='image'),
        ),
        migrations.AddField(
            model_name='category',
            name='twitter_title',
            field=models.CharField(help_text='The title that appears on the Twitter card, it is limited to 70 characters.', max_length=70, verbose_name='title', blank=True),
        ),
        migrations.AlterField(
            model_name='article',
            name='slug',
            field=models.SlugField(help_text='A user friendly URL'),
        ),
        migrations.AlterField(
            model_name='category',
            name='slug',
            field=models.SlugField(help_text='A user friendly URL'),
        ),
    ]


text:
namespace LiveDocs.Diagrams.Graph.Executable.UnitTests.Tests
{
    using System;

    using LiveDocs.Diagrams.Graph.Executable.Builders;
    using LiveDocs.Diagrams.Graph.Executable.Models;
    using LiveDocs.Diagrams.Graph.Executable.Processors;

    using Ploeh.AutoFixture.Xunit2;

    using Xunit;

    using Action = LiveDocs.Diagrams.Graph.Executable.Models.Action;

    public class MermaidProcessorTests
    {
        [Theory]
        [AutoData]
        public void OutputsFromGraph(MermaidProcessor processor)
        {
            var loginScreen = new State("Login");
            var validCredentials = new Decision("Valid Credentials?");

            var flow = new FlowBuilder()
                .FromStartTo(loginScreen).Via(new Action("Navigate"))
                .From(loginScreen).To(validCredentials).Via(new Action("Submit"))
                .From(validCredentials).To(new State("Login Error")).Via(new Action("No"))
                .From(validCredentials).To(new State("Welcome")).Via(new Action("Yes"))
                .Build();

            var output = processor.Process(flow.ToGraph());
            Assert.NotNull(output);
        }

        [Theory]
        [AutoData]
        public void OutputsFromGraphWithSameIds(MermaidProcessor processor)
        {
            var flow = new FlowBuilder()
              .FromStartTo(new State(Guid.Parse("0B50B190-A8E3-4461-AB27-1E28775201C5"), "Login")).Via(new Action("Navigate"))
              .From(new State(Guid.Parse("0B50B190-A8E3-4461-AB27-1E28775201C5"), "Login")).To(new Decision(Guid.Parse("A4EDA007-76A1-4163-A286-9472B7BB8795"), "Valid Credentials?")).Via(new Action("Submit"))
              .From(new Decision(Guid.Parse("A4EDA007-76A1-4163-A286-9472B7BB8795"), "Valid Credentials?")).To(new State("Login Error")).Via(new Action("No"))
              .From(new Decision(Guid.Parse("A4EDA007-76A1-4163-A286-9472B7BB8795"), "Valid Credentials?")).To(new State("Welcome")).Via(new Action("Yes"))
              .Build();

            var output = processor.Process(flow.ToGraph());
            Assert.NotNull(output);
        }
    }
}


text:
md-timepicker
=============

A [Polymer](https://www.polymer-project.org) Timepicker element in [Material Design](http://google.com/design/spec).
Inspired by the Android 4.2+ timepicker in the AOSP clock app.

![md-timepicker](https://cloud.githubusercontent.com/assets/1891109/4836531/0a462358-5fc6-11e4-8cbe-4f9db72bd9df.png)

###Installation
`bower install md-timepicker`

###[Documentation](http://virtual-dev.github.io/md-timepicker/components/md-timepicker/index.html)

###[Demo](http://virtual-dev.github.io/md-timepicker/components/md-timepicker/demo.html)


text:
require 'spec_helper'

describe Marvin::Lexer do
  it 'inherits from RLTK::Lexer' do
    expect(subject).to be_a RLTK::Lexer
  end

  describe '#lex' do
    it 'recognizes parenthesis' do
      types = get_types('( )')

      expect(types).to eql [:T_LPAREN, :T_RPAREN]
    end

    it 'recognizes brackets' do
      types = get_types('{ }')

      expect(types).to eql [:T_LBRACKET, :T_RBRACKET]
    end

    it 'recognizes assignments' do
      types = get_types('=')

      expect(types).to eql [:T_ASSIGN]
    end

    it 'recognizes commas' do
      types = get_types(',')

      expect(types).to eql [:T_COMMA]
    end

    it 'recognizes integers' do
      types = get_types('0 1 2 3 4 5 6 7 8 9')

      expect(types).to eql [:T_INTEGER]
    end

    it 'recognizes floats' do
      types = get_types('0.0 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9')

      expect(types).to eql [:T_FLOAT]
    end

    it 'recognizes booleans' do
      types = get_types('true false')

      expect(types).to eql [:T_BOOLEAN]
    end

    it 'recognizes strings' do
      types = get_types('"foo"')

      expect(types).to eql [:T_STRING]
    end

    it 'recognizes identifiers' do
      types = get_types('foo')

      expect(types).to eql [:T_IDENT]
    end

    it 'recognizes integer operations' do
      types = get_types('+ - * /')

      expect(types).to eql [:T_INTOP]
    end

    it 'recognizes boolean operations' do
      types = get_types('== != > <')

      expect(types).to eql [:T_BOOLOP]
    end

    it 'recognizes print' do
      types = get_types('print')

      expect(types).to eql [:T_PRINT]
    end

    it 'recognizes if' do
      types = get_types('if')

      expect(types).to eql [:T_IF]
    end

    it 'recognizes else' do
      types = get_types('else')

      expect(types).to eql [:T_ELSE]
    end

    it 'recognizes functions' do
      types = get_types('fun')

      expect(types).to eql [:T_FUNCTION]
    end

    it 'recognizes returns' do
      types = get_types('return')

      expect(types).to eql [:T_RETURN]
    end

    it 'does nothing with spaces and newlines' do
      types = get_types(" \n")

      expect(types).to eql []
    end
  end

  def get_types(str)
    Marvin::Lexer.lex(str).map(&:type).reject { |t| t == :EOS }.uniq
  end
end