text:
//===--- GenClangType.cpp - Swift IR Generation For Types -----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
//  This file implements generation of Clang AST types from Swift AST types
//  for types that are representable in Objective-C interfaces.
//
//===----------------------------------------------------------------------===//

#include "llvm/ADT/StringSwitch.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/CanTypeVisitor.h"
#include "swift/AST/Decl.h"
#include "swift/AST/NameLookup.h"
#include "swift/SIL/SILType.h"
#include "swift/ClangImporter/ClangImporter.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Attr.h"
#include "clang/AST/CanonicalType.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/Type.h"
#include "clang/Basic/TargetInfo.h"
#include "IRGenModule.h"

using namespace swift;
using namespace irgen;

/// Global information about importing clang types.
class swift::irgen::ClangTypeConverter {
  llvm::DenseMap<CanType, clang::CanQualType> Cache;

  ClangTypeConverter(const ClangTypeConverter &) = delete;
  ClangTypeConverter &operator=(const ClangTypeConverter &) = delete;

public:
  ClangTypeConverter() = default;
  clang::CanQualType convert(IRGenModule &IGM, CanType type);
  clang::CanQualType reverseBuiltinTypeMapping(IRGenModule &IGM,
                                               CanStructType type);
};

static CanType getNamedSwiftType(Module *stdlib, StringRef name) {
  auto &ctx = stdlib->getASTContext();
  SmallVector<ValueDecl*, 1> results;
  stdlib->lookupValue({}, ctx.getIdentifier(name), NLKind::QualifiedLookup,
                      results);

  // If we have one single type decl, and that decl has been
  // type-checked, return its declared type.
  //
  // ...non-type-checked types should only ever show up here because
  // of test cases using -enable-source-import, but unfortunately
  // that's a real thing.
  if (results.size() == 1) {
    if (auto typeDecl = dyn_cast<TypeDecl>(results[0]))
      if (typeDecl->hasType())
        return typeDecl->getDeclaredType()->getCanonicalType();
  }
  return CanType();
}

static clang::CanQualType getClangBuiltinTypeFromKind(
  const clang::ASTContext &context,
  clang::BuiltinType::Kind kind) {
  switch (kind) {
#define BUILTIN_TYPE(Id, SingletonId) \
  case clang::BuiltinType::Id: return context.SingletonId;
#include "clang/AST/BuiltinTypes.def"
  }
}

static clang::CanQualType getClangSelectorType(
  const clang::ASTContext &clangCtx) {
  return clangCtx.getPointerType(clangCtx.ObjCBuiltinSelTy);
}

static clang::CanQualType getClangMetatypeType(
  const clang::ASTContext &clangCtx) {
  clang::QualType clangType =
    clangCtx.getObjCObjectType(clangCtx.ObjCBuiltinClassTy, 0, 0);
  clangType = clangCtx.getObjCObjectPointerType(clangType);
  return clangCtx.getCanonicalType(clangType);
}

static clang::CanQualType getClangIdType(
  const clang::ASTContext &clangCtx) {
  clang::QualType clangType =
    clangCtx.getObjCObjectType(clangCtx.ObjCBuiltinIdTy, 0, 0);
  clangType = clangCtx.getObjCObjectPointerType(clangType);
  return clangCtx.getCanonicalType(clangType);
}

static clang::CanQualType getClangDecayedVaListType(
  const clang::ASTContext &clangCtx) {
  clang::QualType clangType =
    clangCtx.getCanonicalType(clangCtx.getBuiltinVaListType());
  if (clangType->isConstantArrayType())
    clangType = clangCtx.getDecayedType(clangType);
  return clangCtx.getCanonicalType(clangType);
}

namespace {
/// Given a Swift type, attempt to return an appropriate Clang
/// CanQualType for the purpose of generating correct code for the
/// ABI.
class GenClangType : public CanTypeVisitor<GenClangType, clang::CanQualType> {
  IRGenModule &IGM;
  ClangTypeConverter &Converter;

  clang::QualType convertFunctionType(CanFunctionType type);

public:
  GenClangType(IRGenModule &IGM, ClangTypeConverter &converter)
    : IGM(IGM), Converter(converter) {}

  const clang::ASTContext &getClangASTContext() const {
    return IGM.getClangASTContext();
  }

  /// Return the Clang struct type which was imported and resulted in
  /// this Swift struct type. We do not currently handle generating a
  /// new Clang struct type for Swift struct types that are created
  /// independently of importing a Clang module.
  clang::CanQualType visitStructType(CanStructType type);
  clang::CanQualType visitTupleType(CanTupleType type);
  clang::CanQualType visitMetatypeType(CanMetatypeType type);
  clang::CanQualType visitExistentialMetatypeType(CanExistentialMetatypeType type);
  clang::CanQualType visitProtocolType(CanProtocolType type);
  clang::CanQualType visitClassType(CanClassType type);
  clang::CanQualType visitBoundGenericClassType(CanBoundGenericClassType type);
  clang::CanQualType visitBoundGenericType(CanBoundGenericType type);
  clang::CanQualType visitEnumType(CanEnumType type);
  clang::CanQualType visitFunctionType(CanFunctionType type);
  clang::CanQualType visitProtocolCompositionType(
                                               CanProtocolCompositionType type);
  clang::CanQualType visitBuiltinRawPointerType(CanBuiltinRawPointerType type);
  clang::CanQualType visitBuiltinIntegerType(CanBuiltinIntegerType type);
  clang::CanQualType visitBuiltinFloatType(CanBuiltinFloatType type);
  clang::CanQualType visitBuiltinUnknownObjectType(
                                                CanBuiltinUnknownObjectType type);
  clang::CanQualType visitArchetypeType(CanArchetypeType type);
  clang::CanQualType visitSILFunctionType(CanSILFunctionType type);
  clang::CanQualType visitGenericTypeParamType(CanGenericTypeParamType type);
  clang::CanQualType visitDynamicSelfType(CanDynamicSelfType type);

  clang::CanQualType visitSILBlockStorageType(CanSILBlockStorageType type);

  clang::CanQualType visitType(CanType type);

  clang::CanQualType getCanonicalType(clang::QualType type) {
    return getClangASTContext().getCanonicalType(type);
  }

  clang::CanQualType convertMemberType(NominalTypeDecl *DC,
                                       StringRef memberName);
};
}

clang::CanQualType
GenClangType::convertMemberType(NominalTypeDecl *DC, StringRef memberName) {
  auto memberTypeDecl = cast<TypeDecl>(
    DC->lookupDirect(IGM.Context.getIdentifier(memberName))[0]);
  auto memberType = memberTypeDecl->getDeclaredType()->getCanonicalType();
  return Converter.convert(IGM, memberType);
}

static clang::CanQualType getClangVectorType(const clang::ASTContext &ctx,
                                             clang::BuiltinType::Kind eltKind,
                                        clang::VectorType::VectorKind vecKind,
                                             StringRef numEltsString) {
  unsigned numElts;
  bool failedParse = numEltsString.getAsInteger<unsigned>(10, numElts);
  assert(!failedParse && "vector type name didn't end in count?");
  (void) failedParse;

  auto eltTy = getClangBuiltinTypeFromKind(ctx, eltKind);
  auto vecTy = ctx.getVectorType(eltTy, numElts, vecKind);
  return ctx.getCanonicalType(vecTy);
}

clang::CanQualType GenClangType::visitStructType(CanStructType type) {
  auto &ctx = IGM.getClangASTContext();

  auto swiftDecl = type->getDecl();
  StringRef name = swiftDecl->getName().str();

  // We assume that the importer translates all of the following types
  // directly to structs in the standard library.

  // We want to recognize most of these types by name.
#define CHECK_NAMED_TYPE(NAME, CLANG_TYPE) do {                         \
    if (name == (NAME)) return CLANG_TYPE;                              \
  } while (false)

  CHECK_NAMED_TYPE("CGFloat", convertMemberType(swiftDecl, "NativeType"));
  CHECK_NAMED_TYPE("COpaquePointer", ctx.VoidPtrTy);
  CHECK_NAMED_TYPE("CVaListPointer", getClangDecayedVaListType(ctx));
  CHECK_NAMED_TYPE("DarwinBoolean", ctx.UnsignedCharTy);
  CHECK_NAMED_TYPE("NSZone", ctx.VoidPtrTy);
  CHECK_NAMED_TYPE("ObjCBool", ctx.ObjCBuiltinBoolTy);
  CHECK_NAMED_TYPE("Selector", getClangSelectorType(ctx));
#undef CHECK_NAMED_TYPE

  // Map vector types to the corresponding C vectors.
#define MAP_SIMD_TYPE(TYPE_NAME, CLANG_KIND)                           \
  if (name.startswith(#TYPE_NAME)) {                                   \
    return getClangVectorType(ctx, clang::BuiltinType::CLANG_KIND,     \
                              clang::VectorType::GenericVector,        \
                              name.drop_front(sizeof(#TYPE_NAME)-1));  \
  }
#include "swift/ClangImporter/SIMDMappedTypes.def"

  // Everything else we see here ought to be a translation of a builtin.
  return Converter.reverseBuiltinTypeMapping(IGM, type);
}

clang::CanQualType
ClangTypeConverter::reverseBuiltinTypeMapping(IRGenModule &IGM,
                                              CanStructType type) {
  // Handle builtin types by adding entries to the cache that reverse
  // the mapping done by the importer.  We could try to look at the
  // members of the struct instead, but even if that's ABI-equivalent
  // (which it had better be!), it might erase interesting semantic
  // differences like integers vs. characters.  This is important
  // because CC lowering isn't the only purpose of this conversion.
  //
  // The importer maps builtin types like 'int' to named types like
  // 'CInt', which are generally typealiases.  So what we do here is
  // map the underlying types of those typealiases back to the builtin
  // type.  These typealiases frequently create a many-to-one mapping,
  // so just use the first type that mapped to a particular underlying
  // type.
  //
  // This is the last thing that happens before asserting that the
  // struct type doesn't have a mapping.  Furthermore, all of the
  // builtin types are pre-built in the clang ASTContext.  So it's not
  // really a significant performance problem to just cache all them
  // right here; it makes making a few more entries in the cache than
  // we really need, but it also means we won't end up repeating these
  // stdlib lookups multiple times, and we have to perform multiple
  // lookups anyway because the MAP_BUILTIN_TYPE database uses
  // typealias names (like 'CInt') that aren't obviously associated
  // with the underlying C library type.

  auto stdlib = IGM.Context.getStdlibModule();
  assert(stdlib && "translating stdlib type to C without stdlib module?");
  auto &ctx = IGM.getClangASTContext();
  auto cacheStdlibType = [&](StringRef swiftName,
                             clang::BuiltinType::Kind builtinKind) {
    CanType swiftType = getNamedSwiftType(stdlib, swiftName);
    if (!swiftType) return;

    Cache.insert({swiftType, getClangBuiltinTypeFromKind(ctx, builtinKind)});
  };

#define MAP_BUILTIN_TYPE(CLANG_BUILTIN_KIND, SWIFT_TYPE_NAME)          \
  cacheStdlibType(#SWIFT_TYPE_NAME, clang::BuiltinType::CLANG_BUILTIN_KIND);
#include "swift/ClangImporter/BuiltinMappedTypes.def"

  // The above code sets up a bunch of mappings in the cache; just
  // assume that we hit one of them.
  auto it = Cache.find(type);
  assert(it != Cache.end() &&
         "cannot translate Swift type to C! type is not specially known");
  return it->second;
}

clang::CanQualType GenClangType::visitTupleType(CanTupleType type) {
  unsigned e = type->getNumElements();
  if (e == 0)
    return getClangASTContext().VoidTy;

  CanType eltTy = type.getElementType(0);
  for (unsigned i = 1; i < e; i++) {
    assert(eltTy == type.getElementType(i) &&
           "Only tuples where all element types are equal "
           "map to fixed-size arrays");
  }

  auto clangEltTy = Converter.convert(IGM, eltTy);
  if (!clangEltTy) return clang::CanQualType();

  APInt size(32, e);
  auto &ctx = getClangASTContext();
  return ctx.getCanonicalType(
      ctx.getConstantArrayType(clangEltTy, size,
          clang::ArrayType::Normal, 0));

  llvm_unreachable("Unexpected tuple type in Clang type generation!");
}

clang::CanQualType GenClangType::visitProtocolType(CanProtocolType type) {
  auto proto = type->getDecl();

  // AnyObject -> id.
  if (proto->isSpecificProtocol(KnownProtocolKind::AnyObject))
    return getClangIdType(getClangASTContext());

  // Single protocol -> id<Proto>
  if (proto->isObjC()) {
    auto &clangCtx = getClangASTContext();
    clang::IdentifierInfo *name = &clangCtx.Idents.get(proto->getName().get());
    auto *PDecl = clang::ObjCProtocolDecl::Create(
                    const_cast<clang::ASTContext &>(clangCtx),
                    clangCtx.getTranslationUnitDecl(), name,
                    clang::SourceLocation(), clang::SourceLocation(), nullptr);

    // Attach an objc_runtime_name attribute with the Objective-C name to use
    // for this protocol.
    SmallString<64> runtimeNameBuffer;
    PDecl->addAttr(clang::ObjCRuntimeNameAttr::CreateImplicit(
                     PDecl->getASTContext(),
                     proto->getObjCRuntimeName(runtimeNameBuffer)));

    auto clangType  = clangCtx.getObjCObjectType(clangCtx.ObjCBuiltinIdTy,
                                                 &PDecl, 1);
    auto ptrTy = clangCtx.getObjCObjectPointerType(clangType);
    return clangCtx.getCanonicalType(ptrTy);
  }

  return getClangIdType(getClangASTContext());
}

clang::CanQualType GenClangType::visitMetatypeType(CanMetatypeType type) {
  return getClangMetatypeType(getClangASTContext());
}

clang::CanQualType
GenClangType::visitExistentialMetatypeType(CanExistentialMetatypeType type) {
  return getClangMetatypeType(getClangASTContext());
}

clang::CanQualType GenClangType::visitClassType(CanClassType type) {
  auto &clangCtx = getClangASTContext();
  // produce the clang type INTF * if it is imported ObjC object.
  auto swiftDecl = type->getDecl();
  if (swiftDecl->isObjC()) {
    clang::IdentifierInfo *ForwardClassId =
      &clangCtx.Idents.get(swiftDecl->getName().get());
    auto *CDecl = clang::ObjCInterfaceDecl::Create(
                          clangCtx, clangCtx.getTranslationUnitDecl(),
                          clang::SourceLocation(), ForwardClassId,
                          /*typeParamList*/nullptr, /*PrevDecl=*/nullptr,
                          clang::SourceLocation());

    // Attach an objc_runtime_name attribute with the Objective-C name to use
    // for this class.
    SmallString<64> runtimeNameBuffer;
    CDecl->addAttr(clang::ObjCRuntimeNameAttr::CreateImplicit(
                     CDecl->getASTContext(),
                     swiftDecl->getObjCRuntimeName(runtimeNameBuffer)));

    auto clangType  = clangCtx.getObjCInterfaceType(CDecl);
    auto ptrTy = clangCtx.getObjCObjectPointerType(clangType);
    return clangCtx.getCanonicalType(ptrTy);
  }
  return getClangIdType(clangCtx);
}

clang::CanQualType GenClangType::visitBoundGenericClassType(
                                                CanBoundGenericClassType type) {
  // Any @objc class type in Swift that shows up in an @objc method maps 1-1 to
  // "id <SomeProto>"; with clang's encoding ignoring the protocol list.
  return getClangIdType(getClangASTContext());
}

clang::CanQualType
GenClangType::visitBoundGenericType(CanBoundGenericType type) {
  // We only expect *Pointer<T>, ImplicitlyUnwrappedOptional<T>, and Optional<T>.
  // The first two are structs; the last is an enum.
  OptionalTypeKind OTK;
  if (auto underlyingTy = SILType::getPrimitiveObjectType(type)
        .getAnyOptionalObjectType(*IGM.SILMod, OTK)) {
    // The underlying type could be a bridged type, which makes any
    // sort of casual assertion here difficult.
    return Converter.convert(IGM, underlyingTy.getSwiftRValueType());
  }

  auto swiftStructDecl = type->getDecl();

  enum class StructKind {
    Invalid,
    UnsafeMutablePointer,
    UnsafePointer,
    AutoreleasingUnsafeMutablePointer,
    Unmanaged,
    CFunctionPointer,
  } kind = llvm::StringSwitch<StructKind>(swiftStructDecl->getName().str())
    .Case("UnsafeMutablePointer", StructKind::UnsafeMutablePointer)
    .Case("UnsafePointer", StructKind::UnsafePointer)
    .Case(
      "AutoreleasingUnsafeMutablePointer",
        StructKind::AutoreleasingUnsafeMutablePointer)
    .Case("Unmanaged", StructKind::Unmanaged)
    .Case("CFunctionPointer", StructKind::CFunctionPointer)
    .Default(StructKind::Invalid);

  auto args = type.getGenericArgs();

  switch (kind) {
  case StructKind::Invalid:
    llvm_unreachable("Unexpected non-pointer generic struct type in imported"
                     " Clang module!");

  case StructKind::UnsafeMutablePointer:
  case StructKind::Unmanaged:
  case StructKind::AutoreleasingUnsafeMutablePointer: {
    assert(args.size() == 1 &&
           "*Pointer<T> should have a single generic argument!");
    auto clangCanTy = Converter.convert(IGM, args.front());
    if (!clangCanTy) return clang::CanQualType();
    return getClangASTContext().getPointerType(clangCanTy);
  }
  case StructKind::UnsafePointer: {
    assert(args.size() == 1 &&
           "*Pointer<T> should have a single generic argument!");
    clang::QualType clangTy
      = Converter.convert(IGM, args.front()).withConst();
    return getCanonicalType(getClangASTContext().getPointerType(clangTy));
  }

  case StructKind::CFunctionPointer: {
    auto &clangCtx = getClangASTContext();

    assert(args.size() == 1 &&
           "CFunctionPointer should have a single generic argument!");
    clang::QualType functionTy;
    if (auto ft = dyn_cast<FunctionType>(args[0])) {
      functionTy = convertFunctionType(ft);
    } else {
      // Fall back to void().
      functionTy = clangCtx.getFunctionNoProtoType(clangCtx.VoidTy);
    }
    auto fnPtrTy = clangCtx.getPointerType(functionTy);
    return getCanonicalType(fnPtrTy);
  }
  }
}

clang::CanQualType GenClangType::visitEnumType(CanEnumType type) {
  assert(type->getDecl()->isObjC() && "not an @objc enum?!");

  // @objc enums lower to their raw types.
  return Converter.convert(IGM,
                           type->getDecl()->getRawType()->getCanonicalType());
}

clang::QualType GenClangType::convertFunctionType(CanFunctionType type) {
  auto &clangCtx = getClangASTContext();
  SmallVector<clang::QualType, 16> paramTypes;
  CanType result = type.getResult();
  CanType input = type.getInput();
  auto resultType = Converter.convert(IGM, result);
  {
    if (resultType.isNull())
      goto no_clang_type;

    if (auto tuple = dyn_cast<TupleType>(input)) {
      for (auto argType: tuple.getElementTypes()) {
        auto clangType = Converter.convert(IGM, argType);
        if (clangType.isNull())
          goto no_clang_type;
        paramTypes.push_back(clangType);
      }
    } else {
      auto clangType = Converter.convert(IGM, input);
      if (clangType.isNull())
        goto no_clang_type;
      paramTypes.push_back(clangType);
    }
    clang::FunctionProtoType::ExtProtoInfo DefaultEPI;
    return clangCtx.getFunctionType(resultType, paramTypes, DefaultEPI);
  }
no_clang_type:
  // Fall back to void(^)() for block types we can't convert otherwise. As long
  // as it's a pointer type it doesn't matter exactly which for either ABI type
  // generation or standard Obj-C type encoding, but protocol extended method
  // encodings will break.
  return clangCtx.getFunctionNoProtoType(clangCtx.VoidTy);
}

// FIXME: We hit this building Foundation, with a call on the type
//        encoding path. It seems like we shouldn't see FunctionType
//        at that point.
clang::CanQualType GenClangType::visitFunctionType(CanFunctionType type) {
  auto &clangCtx = getClangASTContext();

  // Convert to a Clang function type.
  auto fnTy = convertFunctionType(type);
  // Turn it into a block pointer.
  auto blockTy = clangCtx.getBlockPointerType(fnTy);
  return clangCtx.getCanonicalType(blockTy);
}

clang::CanQualType GenClangType::visitSILFunctionType(CanSILFunctionType type) {
  auto &clangCtx = getClangASTContext();

  enum FunctionPointerKind {
    Block, CFunctionPointer,
  };

  FunctionPointerKind kind;

  switch (type->getRepresentation()) {
  case SILFunctionType::Representation::Block:
    kind = Block;
    break;

  case SILFunctionType::Representation::CFunctionPointer:
    kind = CFunctionPointer;
    break;

  case SILFunctionType::Representation::Thick:
  case SILFunctionType::Representation::Thin:
  case SILFunctionType::Representation::Method:
  case SILFunctionType::Representation::ObjCMethod:
  case SILFunctionType::Representation::WitnessMethod:
    llvm_unreachable("not an ObjC-compatible function");
  }

  // Convert the return and parameter types.
  auto resultType = Converter.convert(IGM,
                type->getSemanticResultSILType().getSwiftRValueType());
  if (resultType.isNull())
    return clang::CanQualType();

  SmallVector<clang::QualType, 4> paramTypes;
  for (auto paramTy : type->getParametersWithoutIndirectResult()) {
    // Blocks should only take direct +0 parameters.
    switch (paramTy.getConvention()) {
    case ParameterConvention::Direct_Guaranteed:
    case ParameterConvention::Direct_Unowned:
    case ParameterConvention::Direct_Deallocating:
      // OK.
      break;

    case ParameterConvention::Direct_Owned:
      llvm_unreachable("block takes owned parameter");
    case ParameterConvention::Indirect_In:
    case ParameterConvention::Indirect_Inout:
    case ParameterConvention::Indirect_InoutAliasable:
    case ParameterConvention::Indirect_Out:
    case ParameterConvention::Indirect_In_Guaranteed:
      llvm_unreachable("block takes indirect parameter");
    }
    auto param = Converter.convert(IGM, paramTy.getType());
    if (param.isNull())
      return clang::CanQualType();
    paramTypes.push_back(param);
  }

  // Build the Clang function type.
  clang::FunctionProtoType::ExtProtoInfo defaultEPI;
  auto fnTy = clangCtx.getFunctionType(resultType, paramTypes, defaultEPI);
  clang::QualType ptrTy;

  switch (kind) {
  case Block:
    ptrTy = clangCtx.getBlockPointerType(fnTy);
    break;
  case CFunctionPointer:
    ptrTy = clangCtx.getPointerType(fnTy);
  }
  return clangCtx.getCanonicalType(ptrTy);
}

clang::CanQualType GenClangType::visitSILBlockStorageType(CanSILBlockStorageType type) {
  // We'll select (void)(^)(). This isn't correct for all blocks, but block
  // storage type should only be converted for function signature lowering,
  // where the parameter types do not matter.
  auto &clangCtx = getClangASTContext();
  auto fnTy = clangCtx.getFunctionNoProtoType(clangCtx.VoidTy);
  auto blockTy = clangCtx.getBlockPointerType(fnTy);
  return clangCtx.getCanonicalType(blockTy);
}

clang::CanQualType GenClangType::visitProtocolCompositionType(
  CanProtocolCompositionType type) {
  // FIXME. Eventually, this will have its own helper routine.
  SmallVector<const clang::ObjCProtocolDecl *, 4> Protocols;
  for (CanType t : type.getProtocols()) {
    auto opt = cast<clang::ObjCObjectPointerType>(Converter.convert(IGM, t));
    for (auto p : opt->quals())
      Protocols.push_back(p);
  }

  auto &clangCtx = getClangASTContext();
  if (Protocols.empty())
    return getClangIdType(clangCtx);
  // id<protocol-list>
  clang::ObjCProtocolDecl **ProtoQuals = new(clangCtx) clang::ObjCProtocolDecl*[Protocols.size()];
  memcpy(ProtoQuals, Protocols.data(), sizeof(clang::ObjCProtocolDecl*)*Protocols.size());
  auto clangType = clangCtx.getObjCObjectType(clangCtx.ObjCBuiltinIdTy,
                     ProtoQuals,
                     Protocols.size());
  auto ptrTy = clangCtx.getObjCObjectPointerType(clangType);
  return clangCtx.getCanonicalType(ptrTy);
}

clang::CanQualType GenClangType::visitBuiltinRawPointerType(
  CanBuiltinRawPointerType type) {
  return getClangASTContext().VoidPtrTy;
}

clang::CanQualType GenClangType::visitBuiltinIntegerType(
                                                   CanBuiltinIntegerType type) {
  auto &ctx = getClangASTContext();
  if (type->getWidth().isPointerWidth()) {
    return ctx.getCanonicalType(ctx.getUIntPtrType());
  }
  if (type->getWidth().isFixedWidth()) {
    auto width = type->getWidth().getFixedWidth();
    if (width == 1) return ctx.BoolTy;
    return ctx.getCanonicalType(ctx.getIntTypeForBitwidth(width, /*signed*/ 0));
  }
  llvm_unreachable("");
}

clang::CanQualType GenClangType::visitBuiltinFloatType(
                                                     CanBuiltinFloatType type) {
  auto &ctx = getClangASTContext();
  auto &clangTargetInfo = ctx.getTargetInfo();
  const llvm::fltSemantics *format = &type->getAPFloatSemantics();
  if (format == &clangTargetInfo.getHalfFormat()) return ctx.HalfTy;
  if (format == &clangTargetInfo.getFloatFormat()) return ctx.FloatTy;
  if (format == &clangTargetInfo.getDoubleFormat()) return ctx.DoubleTy;
  if (format == &clangTargetInfo.getLongDoubleFormat()) return ctx.LongDoubleTy;
  llvm_unreachable("cannot translate floating-point format to C");
}

clang::CanQualType GenClangType::visitBuiltinUnknownObjectType(
  CanBuiltinUnknownObjectType type) {
  auto &clangCtx = getClangASTContext();
  auto ptrTy = clangCtx.getObjCObjectPointerType(clangCtx.VoidTy);
  return clangCtx.getCanonicalType(ptrTy);
}

clang::CanQualType GenClangType::visitArchetypeType(CanArchetypeType type) {
  // We see these in the case where we invoke an @objc function
  // through a protocol.
  return getClangIdType(getClangASTContext());
}

clang::CanQualType GenClangType::visitDynamicSelfType(CanDynamicSelfType type) {
  // Dynamic Self is equivalent to 'instancetype', which is treated as
  // 'id' within the Objective-C type system.
  return getClangIdType(getClangASTContext());
}

clang::CanQualType GenClangType::visitGenericTypeParamType(
  CanGenericTypeParamType type) {
  // We see these in the case where we invoke an @objc function
  // through a protocol argument that is a generic type.
  return getClangIdType(getClangASTContext());
}

clang::CanQualType GenClangType::visitType(CanType type) {
  llvm_unreachable("Unexpected type in Clang type generation.");
}

clang::CanQualType ClangTypeConverter::convert(IRGenModule &IGM, CanType type) {
  // Try to do this without making cache entries for obvious cases.
  if (auto nominal = dyn_cast<NominalType>(type)) {
    auto decl = nominal->getDecl();
    if (auto clangDecl = decl->getClangDecl()) {
      if (auto clangTypeDecl = dyn_cast<clang::TypeDecl>(clangDecl)) {
        auto &ctx = IGM.getClangASTContext();
        return ctx.getCanonicalType(ctx.getTypeDeclType(clangTypeDecl));
      } else if (auto ifaceDecl = dyn_cast<clang::ObjCInterfaceDecl>(clangDecl)) {
        auto &ctx = IGM.getClangASTContext();
        auto clangType  = ctx.getObjCInterfaceType(ifaceDecl);
        auto ptrTy = ctx.getObjCObjectPointerType(clangType);
        return ctx.getCanonicalType(ptrTy);
      } else if (auto protoDecl = dyn_cast<clang::ObjCProtocolDecl>(clangDecl)){
        auto &ctx = IGM.getClangASTContext();
        auto clangType  = ctx.getObjCObjectType(
                            ctx.ObjCBuiltinIdTy,
                            const_cast<clang::ObjCProtocolDecl **>(&protoDecl),
                            1);
        auto ptrTy = ctx.getObjCObjectPointerType(clangType);
        return ctx.getCanonicalType(ptrTy);
      }
    } else if (decl == IGM.Context.getBoolDecl()) {
      // FIXME: Handle _Bool and DarwinBoolean.
      auto &ctx = IGM.getClangASTContext();
      auto &TI = ctx.getTargetInfo();
      if (TI.useSignedCharForObjCBool()) {
        return ctx.SignedCharTy;
      }
    }
  }

  // Look in the cache.
  auto it = Cache.find(type);
  if (it != Cache.end()) {
    return it->second;
  }

  // If that failed, convert the type, cache, and return.
  clang::CanQualType result = GenClangType(IGM, *this).visit(type);
  Cache.insert({type, result});
  return result;
}

clang::CanQualType IRGenModule::getClangType(CanType type) {
  return ClangTypes->convert(*this, type);
}

clang::CanQualType IRGenModule::getClangType(SILType type) {
  return getClangType(type.getSwiftRValueType());
}

clang::CanQualType IRGenModule::getClangType(SILParameterInfo params) {
  auto clangType = getClangType(params.getSILType());
  // @block_storage types must be @inout_aliasable and have
  // special lowering
  if (params.isIndirectMutating() &&
      !params.getSILType().is<SILBlockStorageType>()) {
    return getClangASTContext().getPointerType(clangType);
  }
  return clangType;
}

void IRGenModule::initClangTypeConverter() {
  if (auto loader = Context.getClangModuleLoader()) {
    auto importer = static_cast<ClangImporter*>(loader);
    ClangASTContext = &importer->getClangASTContext();
    ClangTypes = new ClangTypeConverter();
  } else {
    ClangASTContext = nullptr;
    ClangTypes = nullptr;
  }
}

void IRGenModule::destroyClangTypeConverter() {
  delete ClangTypes;
}


text:
=head1 NAME

SGN::Controller::Biosource - controller for working with Biosource data, which is metadata about datasets

=cut

package SGN::Controller::Biosource;
use Moose;

BEGIN { extends 'Catalyst::Controller' }

use CXGN::Biosource::Sample;
use CXGN::GEM::Target;

=head1 PUBLIC ACTIONS

=head2 view_sample

Public path: /data_source/<ident>/view

View a biosource sample detail page.

=cut

sub view_sample : Chained('get_sample') PathPart('view') Args(0) {
    my ( $self, $c ) = @_;

    $c->forward('get_sample_targets');
    $c->forward('get_sample_files');

    $c->stash(
        sample_relations_href => { $c->stash->{sample}->get_relationship },
        pub_list              => [ $c->stash->{sample}->get_publication_list ],

        template => '/biosource/sample_detail.mas',
      );

}

### helper actions ###

# chain root for retrieving a biosource sample, URL beginning with
# /data_source/<ident>.  supports either an ID number or a sample name as
# the identifier
sub get_sample : Chained('/') CaptureArgs(1) PathPart('data_source') {
    my ( $self, $c, $ident ) = @_;

    $ident or $c->throw_client_error('invalid arguments');

    my $schema = $c->stash->{schema} = $c->dbic_schema('CXGN::Biosource::Schema','sgn_chado');

    no strict 'refs';
    my $method_name = $ident =~ /\D/ ? 'new_by_name' : 'new';
    $c->stash->{sample} = CXGN::Biosource::Sample->$method_name( $schema, $ident )
        or $c->throw_404;
}

sub get_sample_files : Private {
    my ( $self, $c ) = @_;

    $c->stash->{files} = [
            $c->stash->{sample}->get_bssample_row
                               ->search_related('bs_sample_files')
                               ->search_related('file')
                               ->all
     ];
}

# The sample can be associated expression data (search sample_id in
# gem.ge_target_element table)
sub get_sample_targets : Private {
    my ( $self, $c ) = @_;

    my $sample = $c->stash->{sample};

    return unless $sample->get_sample_id;

    my $gemschema = $c->dbic_schema('CXGN::GEM::Schema','sgn_chado');

    $c->stash->{target_list} = [
        map { CXGN::GEM::Target->new( $gemschema, $_ ) }
        $gemschema->resultset('GeTargetElement')
                  ->search({ sample_id => $sample->get_sample_id })
                  ->get_column('target_id')
                  ->all
    ];
}

1;

redpajama_set_name: RedPajamaGithub


text:
#define pr_fmt(fmt) "X.509: "fmt
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/err.h>
#include <linux/mpi.h>
#include <linux/asn1_decoder.h>
#include <keys/asymmetric-subtype.h>
#include <keys/asymmetric-parser.h>
#include <crypto/hash.h>
#include "asymmetric_keys.h"
#include "public_key.h"
#include "x509_parser.h"

static const
struct public_key_algorithm *x509_public_key_algorithms[PKEY_ALGO__LAST] = {
	[PKEY_ALGO_DSA]		= NULL,
#if defined(CONFIG_PUBLIC_KEY_ALGO_RSA) || \
	defined(CONFIG_PUBLIC_KEY_ALGO_RSA_MODULE)
	[PKEY_ALGO_RSA]		= &RSA_public_key_algorithm,
#endif
};

/*
 * Check the signature on a certificate using the provided public key
 */
static int x509_check_signature(const struct public_key *pub,
				const struct x509_certificate *cert)
{
	struct public_key_signature *sig;
	struct crypto_shash *tfm;
	struct shash_desc *desc;
	size_t digest_size, desc_size;
	int ret;

	pr_devel("==>%s()\n", __func__);

	/* Allocate the hashing algorithm we're going to need and find out how
	 * big the hash operational data will be.
	 */
	tfm = crypto_alloc_shash(pkey_hash_algo[cert->sig_hash_algo], 0, 0);
	if (IS_ERR(tfm))
		return (PTR_ERR(tfm) == -ENOENT) ? -ENOPKG : PTR_ERR(tfm);

	desc_size = crypto_shash_descsize(tfm) + sizeof(*desc);
	digest_size = crypto_shash_digestsize(tfm);

	/* We allocate the hash operational data storage on the end of our
	 * context data.
	 */
	ret = -ENOMEM;
	sig = kzalloc(sizeof(*sig) + desc_size + digest_size, GFP_KERNEL);
	if (!sig)
		goto error_no_sig;

	sig->pkey_hash_algo	= cert->sig_hash_algo;
	sig->digest		= (u8 *)sig + sizeof(*sig) + desc_size;
	sig->digest_size	= digest_size;

	desc = (void *)sig + sizeof(*sig);
	desc->tfm	= tfm;
	desc->flags	= CRYPTO_TFM_REQ_MAY_SLEEP;

	ret = crypto_shash_init(desc);
	if (ret < 0)
		goto error;

	ret = -ENOMEM;
	sig->rsa.s = mpi_read_raw_data(cert->sig, cert->sig_size);
	if (!sig->rsa.s)
		goto error;

	ret = crypto_shash_finup(desc, cert->tbs, cert->tbs_size, sig->digest);
	if (ret < 0)
		goto error_mpi;

	ret = pub->algo->verify_signature(pub, sig);

	pr_debug("Cert Verification: %d\n", ret);

error_mpi:
	mpi_free(sig->rsa.s);
error:
	kfree(sig);
error_no_sig:
	crypto_free_shash(tfm);

	pr_devel("<==%s() = %d\n", __func__, ret);
	return ret;
}

/*
 * Attempt to parse a data blob for a key as an X509 certificate.
 */
static int x509_key_preparse(struct key_preparsed_payload *prep)
{
	struct x509_certificate *cert;
	size_t srlen, sulen;
	char *desc = NULL;
	int ret;

	cert = x509_cert_parse(prep->data, prep->datalen);
	if (IS_ERR(cert))
		return PTR_ERR(cert);

	pr_devel("Cert Issuer: %s\n", cert->issuer);
	pr_devel("Cert Subject: %s\n", cert->subject);
	pr_devel("Cert Key Algo: %s\n", pkey_algo[cert->pkey_algo]);
	pr_devel("Cert Valid From: %04ld-%02d-%02d %02d:%02d:%02d\n",
		 cert->valid_from.tm_year + 1900, cert->valid_from.tm_mon + 1,
		 cert->valid_from.tm_mday, cert->valid_from.tm_hour,
		 cert->valid_from.tm_min,  cert->valid_from.tm_sec);
	pr_devel("Cert Valid To: %04ld-%02d-%02d %02d:%02d:%02d\n",
		 cert->valid_to.tm_year + 1900, cert->valid_to.tm_mon + 1,
		 cert->valid_to.tm_mday, cert->valid_to.tm_hour,
		 cert->valid_to.tm_min,  cert->valid_to.tm_sec);
	pr_devel("Cert Signature: %s + %s\n",
		 pkey_algo[cert->sig_pkey_algo],
		 pkey_hash_algo[cert->sig_hash_algo]);

	if (!cert->fingerprint || !cert->authority) {
		pr_warn("Cert for '%s' must have SubjKeyId and AuthKeyId extensions\n",
			cert->subject);
		ret = -EKEYREJECTED;
		goto error_free_cert;
	}

	cert->pub->algo = x509_public_key_algorithms[cert->pkey_algo];
	cert->pub->id_type = PKEY_ID_X509;

	/* Check the signature on the key */
	if (strcmp(cert->fingerprint, cert->authority) == 0) {
		ret = x509_check_signature(cert->pub, cert);
		if (ret < 0)
			goto error_free_cert;
	}

	/* Propose a description */
	sulen = strlen(cert->subject);
	srlen = strlen(cert->fingerprint);
	ret = -ENOMEM;
	desc = kmalloc(sulen + 2 + srlen + 1, GFP_KERNEL);
	if (!desc)
		goto error_free_cert;
	memcpy(desc, cert->subject, sulen);
	desc[sulen] = ':';
	desc[sulen + 1] = ' ';
	memcpy(desc + sulen + 2, cert->fingerprint, srlen);
	desc[sulen + 2 + srlen] = 0;

	/* We're pinning the module by being linked against it */
	__module_get(public_key_subtype.owner);
	prep->type_data[0] = &public_key_subtype;
	prep->type_data[1] = cert->fingerprint;
	prep->payload = cert->pub;
	prep->description = desc;
	prep->quotalen = 100;

	/* We've finished with the certificate */
	cert->pub = NULL;
	cert->fingerprint = NULL;
	desc = NULL;
	ret = 0;

error_free_cert:
	x509_free_certificate(cert);
	return ret;
}

static struct asymmetric_key_parser x509_key_parser = {
	.owner	= THIS_MODULE,
	.name	= "x509",
	.parse	= x509_key_preparse,
};

/*
 * Module stuff
 */
static int __init x509_key_init(void)
{
	return register_asymmetric_key_parser(&x509_key_parser);
}

static void __exit x509_key_exit(void)
{
	unregister_asymmetric_key_parser(&x509_key_parser);
}

module_init(x509_key_init);
module_exit(x509_key_exit);


text:
package com.google.debugging.sourcemap;

import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Preconditions;
import com.google.debugging.sourcemap.SourceMapConsumerV3.EntryVisitor;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Nullable;

/**
 * Collects information mapping the generated (compiled) source back to
 * its original source for debugging purposes.
 *
 * Source Map Revision 3 Proposal:
 * https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?usp=sharing
 *
 * @author johnlenz@google.com (John Lenz)
 */
@GwtIncompatible("com.google.gson")
public final class SourceMapGeneratorV3 implements SourceMapGenerator {

  /**
   * This interface provides the merging strategy when an extension conflict
   * appears because of merging two source maps on method
   * {@link #mergeMapSection}.
   */
  public interface ExtensionMergeAction {

    /**
     * Returns the merged value between two extensions with the same name when
     * merging two source maps
     *
     * @param extensionKey The extension name in conflict
     * @param currentValue The extension value in the current source map
     * @param newValue The extension value in the input source map
     * @return The merged value
     */
    Object merge(String extensionKey, Object currentValue,
        Object newValue);
  }

  private static final int UNMAPPED = -1;

  /**
   * A pre-order traversal ordered list of mappings stored in this map.
   */
  private List<Mapping> mappings = new ArrayList<>();

  /**
   * A map of source names to source name index
   */
  private LinkedHashMap<String, Integer> sourceFileMap =
       new LinkedHashMap<>();

  /**
   * A map of source names to source name index
   */
  private LinkedHashMap<String, Integer> originalNameMap =
       new LinkedHashMap<>();

  /**
   * Cache of the last mappings source name.
   */
  private String lastSourceFile = null;

  /**
   * Cache of the last mappings source name index.
   */
  private int lastSourceFileIndex = -1;

  /**
   * For validation store the last mapping added.
   */
  private Mapping lastMapping;

  /**
   * The position that the current source map is offset in the
   * buffer being used to generated the compiled source file.
   */
  private FilePosition offsetPosition = new FilePosition(0, 0);

  /**
   * The position that the current source map is offset in the
   * generated the compiled source file by the addition of a
   * an output wrapper prefix.
   */
  private FilePosition prefixPosition = new FilePosition(0, 0);

  /**
   * A list of extensions to be added to sourcemap. The value is a object
   * to permit single values, like strings or numbers, and JsonObject or
   * JsonArray objects.
   */
  private LinkedHashMap<String, Object> extensions = new LinkedHashMap<>();

  /**
   * The source root path for relocating source fails or avoid duplicate values
   * on the source entry.
   */
  private String sourceRootPath;

  /**
   * {@inheritDoc}
   */
  @Override
  public void reset() {
    mappings.clear();
    lastMapping = null;
    sourceFileMap.clear();
    originalNameMap.clear();
    lastSourceFile = null;
    lastSourceFileIndex = -1;
    offsetPosition = new FilePosition(0, 0);
    prefixPosition = new FilePosition(0, 0);
  }

  /**
   * @param validate Whether to perform (potentially costly) validation on the
   * generated source map.
   */
  @Override
  public void validate(boolean validate) {
    // Nothing currently.
  }

  /**
   * Sets the prefix used for wrapping the generated source file before
   * it is written. This ensures that the source map is adjusted for the
   * change in character offsets.
   *
   * @param prefix The prefix that is added before the generated source code.
   */
  @Override
  public void setWrapperPrefix(String prefix) {
    // Determine the current line and character position.
    int prefixLine = 0;
    int prefixIndex = 0;

    for (int i = 0; i < prefix.length(); ++i) {
      if (prefix.charAt(i) == '\n') {
        prefixLine++;
        prefixIndex = 0;
      } else {
        prefixIndex++;
      }
    }

    prefixPosition = new FilePosition(prefixLine, prefixIndex);
  }

  /**
   * Sets the source code that exists in the buffer for which the
   * generated code is being generated. This ensures that the source map
   * accurately reflects the fact that the source is being appended to
   * an existing buffer and as such, does not start at line 0, position 0
   * but rather some other line and position.
   *
   * @param offsetLine The index of the current line being printed.
   * @param offsetIndex The column index of the current character being printed.
   */
  @Override
  public void setStartingPosition(int offsetLine, int offsetIndex) {
    Preconditions.checkState(offsetLine >= 0);
    Preconditions.checkState(offsetIndex >= 0);
    offsetPosition = new FilePosition(offsetLine, offsetIndex);
  }

  /**
   * Adds a mapping for the given node.  Mappings must be added in order.
   * @param startPosition The position on the starting line
   * @param endPosition The position on the ending line.
   */
  @Override
  public void addMapping(
      String sourceName, @Nullable String symbolName,
      FilePosition sourceStartPosition,
      FilePosition startPosition, FilePosition endPosition) {

    // Don't bother if there is not sufficient information to be useful.
    if (sourceName == null || sourceStartPosition.getLine() < 0) {
      return;
    }

    FilePosition adjustedStart = startPosition;
    FilePosition adjustedEnd = endPosition;

    if (offsetPosition.getLine() != 0
        || offsetPosition.getColumn() != 0) {
      // If the mapping is found on the first line, we need to offset
      // its character position by the number of characters found on
      // the *last* line of the source file to which the code is
      // being generated.
      int offsetLine = offsetPosition.getLine();
      int startOffsetPosition = offsetPosition.getColumn();
      int endOffsetPosition = offsetPosition.getColumn();

      if (startPosition.getLine() > 0) {
        startOffsetPosition = 0;
      }

      if (endPosition.getLine() > 0) {
        endOffsetPosition = 0;
      }

      adjustedStart = new FilePosition(
          startPosition.getLine() + offsetLine,
          startPosition.getColumn() + startOffsetPosition);

      adjustedEnd = new FilePosition(
          endPosition.getLine() + offsetLine,
          endPosition.getColumn() + endOffsetPosition);
    }

    // Create the new mapping.
    Mapping mapping = new Mapping();
    mapping.sourceFile = sourceName;
    mapping.originalPosition = sourceStartPosition;
    mapping.originalName = symbolName;
    mapping.startPosition = adjustedStart;
    mapping.endPosition = adjustedEnd;

    // Validate the mappings are in a proper order.
    if (lastMapping != null) {
      int lastLine = lastMapping.startPosition.getLine();
      int lastColumn = lastMapping.startPosition.getColumn();
      int nextLine = mapping.startPosition.getLine();
      int nextColumn = mapping.startPosition.getColumn();
      Preconditions.checkState(nextLine > lastLine
          || (nextLine == lastLine && nextColumn >= lastColumn),
          "Incorrect source mappings order, previous : (%s,%s)\n"
          + "new : (%s,%s)",
          lastLine, lastColumn, nextLine, nextColumn);
    }

    lastMapping = mapping;
    mappings.add(mapping);
  }

  class ConsumerEntryVisitor implements EntryVisitor {

    @Override
    public void visit(
        String sourceName, String symbolName,
        FilePosition sourceStartPosition,
        FilePosition startPosition, FilePosition endPosition) {
      addMapping(sourceName, symbolName,
          sourceStartPosition, startPosition, endPosition);
    }
  }

  /**
   * Merges current mapping with {@code mapSectionContents} considering the
   * offset {@code (line, column)}. Any extension in the map section will be
   * ignored.
   *
   * @param line The line offset
   * @param column The column offset
   * @param mapSectionContents The map section to be appended
   * @throws SourceMapParseException
   */
  public void mergeMapSection(int line, int column, String mapSectionContents)
      throws SourceMapParseException {
    setStartingPosition(line, column);
    SourceMapConsumerV3 section = new SourceMapConsumerV3();
    section.parse(mapSectionContents);
    section.visitMappings(new ConsumerEntryVisitor());
  }

  /**
   * Works like {@link #mergeMapSection(int, int, String)}, except that
   * extensions from the @{code mapSectionContents} are merged to the top level
   * source map. For conflicts a {@code mergeAction} is performed.
   *
   * @param line The line offset
   * @param column The column offset
   * @param mapSectionContents The map section to be appended
   * @param mergeAction The merge action for conflicting extensions
   * @throws SourceMapParseException
   */
  public void mergeMapSection(int line, int column, String mapSectionContents,
      ExtensionMergeAction mergeAction)
      throws SourceMapParseException {
    setStartingPosition(line, column);
    SourceMapConsumerV3 section = new SourceMapConsumerV3();
    section.parse(mapSectionContents);
    section.visitMappings(new ConsumerEntryVisitor());
    for (Entry<String, Object> entry : section.getExtensions().entrySet()) {
       String extensionKey = entry.getKey();
       if (extensions.containsKey(extensionKey)) {
         extensions.put(extensionKey,
             mergeAction.merge(extensionKey,
                               extensions.get(extensionKey),
                               entry.getValue()));
       } else {
         extensions.put(extensionKey, entry.getValue());
       }
     }
  }

  /**
   * Writes out the source map in the following format (line numbers are for
   * reference only and are not part of the format):
   *
   * 1.  {
   * 2.    version: 3,
   * 3.    file: "out.js",
   * 4.    lineCount: 2,
   * 5.    sourceRoot: "",
   * 6.    sources: ["foo.js", "bar.js"],
   * 7.    names: ["src", "maps", "are", "fun"],
   * 8.    mappings: "a;;abcde,abcd,a;"
   * 9.    x_org_extension: value
   * 10. }
   *
   * Line 1: The entire file is a single JSON object
   * Line 2: File revision (always the first entry in the object)
   * Line 3: The name of the file that this source map is associated with.
   * Line 4: The number of lines represented in the source map.
   * Line 5: An optional source root, useful for relocating source files on a
   *     server or removing repeated prefix values in the "sources" entry.
   * Line 6: A list of sources used by the "mappings" entry relative to the
   *     sourceRoot.
   * Line 7: A list of symbol names used by the "mapping" entry.  This list
   *     may be incomplete.
   * Line 8: The mappings field.
   * Line 9: Any custom field (extension).
   */
  @Override
  public void appendTo(Appendable out, String name) throws IOException {
    int maxLine = prepMappings() + 1;

    // Add the header fields.
    out.append("{\n");
    appendFirstField(out, "version", "3");
    appendField(out, "file", escapeString(name));
    appendField(out, "lineCount", String.valueOf(maxLine));

    //optional source root
    if (this.sourceRootPath != null && !this.sourceRootPath.isEmpty()) {
      appendField(out, "sourceRoot", escapeString(this.sourceRootPath));
    }

    // Add the mappings themselves.
    appendFieldStart(out, "mappings");
    // out.append("[");
    (new LineMapper(out, maxLine)).appendLineMappings();

    // out.append("]");
    appendFieldEnd(out);

    // Files names
    appendFieldStart(out, "sources");
    out.append("[");
    addSourceNameMap(out);
    out.append("]");
    appendFieldEnd(out);

    // Files names
    appendFieldStart(out, "names");
    out.append("[");
    addSymbolNameMap(out);
    out.append("]");
    appendFieldEnd(out);

    // Extensions, only if there is any
    for (String key : this.extensions.keySet()) {
      Object objValue = this.extensions.get(key);
      String value = objValue.toString();
      if (objValue instanceof String){
        value = new Gson().toJson(value);
      }
      appendField(out, key, value);
    }

    out.append("\n}\n");
  }

  /**
   * A prefix to be added to the beginning of each sourceName passed to
   * {@link #addMapping}. Debuggers expect (prefix + sourceName) to be a URL
   * for loading the source code.
   *
   * @param path The URL prefix to save in the sourcemap file. (Not validated.)
   */
  public void setSourceRoot(String path){
    this.sourceRootPath = path;
  }

  /**
   * Adds field extensions to the json source map. The value is allowed to be
   * any value accepted by json, eg. string, JsonObject, JsonArray, etc.
   *
   * Extensions must follow the format x_orgranization_field (based on V3
   * proposal), otherwise a {@code SourceMapParseExtension} will be thrown.
   *
   * @param name The name of the extension with format organization_field
   * @param object The value of the extension as a valid json value
   * @throws SourceMapParseException  if extension name is malformed
   */
  public void addExtension(String name, Object object)
      throws SourceMapParseException{
    if (!name.startsWith("x_")){
      throw new SourceMapParseException("Extension '" + name +
                                        "' must start with 'x_'");
    }
    this.extensions.put(name, object);
  }

  /**
   * Removes an extension by name if present.
   *
   * @param name The name of the extension with format organization_field
   */
  public void removeExtension(String name) {
    if (this.extensions.containsKey(name)) {
      this.extensions.remove(name);
    }
  }

  /**
   * Check whether or not the sourcemap has an extension.
   *
   * @param name The name of the extension with format organization_field
   * @return If the extension exist
   */
  public boolean hasExtension(String name) {
    return this.extensions.containsKey(name);
  }

  /**
   * Returns the value mapped by the specified extension
   * or {@code null} if this extension does not exist.
   *
   * @param name
   * @return the extension value or {@code null}
   */
  public Object getExtension(String name) {
    return this.extensions.get(name);
  }

  /**
   * Writes the source name map to 'out'.
   */
  private void addSourceNameMap(Appendable out) throws IOException {
    addNameMap(out, sourceFileMap);
  }

  /**
   * Writes the source name map to 'out'.
   */
  private void addSymbolNameMap(Appendable out) throws IOException {
    addNameMap(out, originalNameMap);
  }

  private static void addNameMap(Appendable out, Map<String, Integer> map)
      throws IOException {
    int i = 0;
    for (Entry<String, Integer> entry : map.entrySet()) {
      String key = entry.getKey();
      if (i != 0) {
        out.append(",");
      }
      out.append(escapeString(key));
      i++;
    }
  }

  /**
   * Escapes the given string for JSON.
   */
  private static String escapeString(String value) {
    return Util.escapeString(value);
  }

  // Source map field helpers.

  private static void appendFirstField(
      Appendable out, String name, CharSequence value)
      throws IOException {
    out.append("\"");
    out.append(name);
    out.append("\"");
    out.append(":");
    out.append(value);
  }

  private static void appendField(
      Appendable out, String name, CharSequence value)
      throws IOException {
    out.append(",\n");
    out.append("\"");
    out.append(name);
    out.append("\"");
    out.append(":");
    out.append(value);
  }

  private static void appendFieldStart(Appendable out, String name)
      throws IOException {
    appendField(out, name, "");
  }

  @SuppressWarnings("unused")
  private static void appendFieldEnd(Appendable out)
     throws IOException {
  }

  /**
   * Assigns sequential ids to used mappings, and returns the last line mapped.
   */
  private int prepMappings() throws IOException {
    // Mark any unused mappings.
    (new MappingTraversal()).traverse(new UsedMappingCheck());

    // Renumber used mappings and keep track of the last line.
    int id = 0;
    int maxLine = 0;
    for (Mapping m : mappings) {
      if (m.used) {
        m.id = id++;
        int endPositionLine = m.endPosition.getLine();
        maxLine = Math.max(maxLine, endPositionLine);
      }
    }

    // Adjust for the prefix.
    return maxLine + prefixPosition.getLine();
  }

  /**
   * A mapping from a given position in an input source file to a given position
   * in the generated code.
   */
  static class Mapping {
    /**
     * A unique ID for this mapping for record keeping purposes.
     */
    int id = UNMAPPED;

    /**
     * The source file index.
     */
    String sourceFile;

    /**
     * The position of the code in the input source file. Both
     * the line number and the character index are indexed by
     * 1 for legacy reasons via the Rhino Node class.
     */
    FilePosition originalPosition;

    /**
     * The starting position of the code in the generated source
     * file which this mapping represents. Indexed by 0.
     */
    FilePosition startPosition;

    /**
     * The ending position of the code in the generated source
     * file which this mapping represents. Indexed by 0.
     */
    FilePosition endPosition;

    /**
     * The original name of the token found at the position
     * represented by this mapping (if any).
     */
    String originalName;

    /**
     * Whether the mapping is actually used by the source map.
     */
    boolean used = false;
  }

  /**
   * Mark any visited mapping as "used".
   */
  private class UsedMappingCheck implements MappingVisitor {
    /**
     * @throws IOException
     */
    @Override
    public void visit(Mapping m, int line, int col, int nextLine, int nextCol)
        throws IOException {
      if (m != null) {
        m.used = true;
      }
    }
  }

  private interface MappingVisitor {
    /**
     * @param m The mapping for the current code segment. null if the segment
     *     is unmapped.
     * @param line The starting line for this code segment.
     * @param col The starting column for this code segment.
     * @param endLine The ending line
     * @param endCol The ending column
     * @throws IOException
     */
    void visit(Mapping m, int line, int col, int endLine, int endCol)
        throws IOException;
  }

  /**
   * Walk the mappings and visit each segment of the mappings, unmapped
   * segments are visited with a null mapping, unused mapping are not visited.
   */
  private class MappingTraversal {
    // The last line and column written
    private int line;
    private int col;

    MappingTraversal() {
    }

    // Append the line mapping entries.
    void traverse(MappingVisitor v) throws IOException {
      // The mapping list is ordered as a pre-order traversal.  The mapping
      // positions give us enough information to rebuild the stack and this
      // allows the building of the source map in O(n) time.
      Deque<Mapping> stack = new ArrayDeque<>();
      for (Mapping m : mappings) {
        // Find the closest ancestor of the current mapping:
        // An overlapping mapping is an ancestor of the current mapping, any
        // non-overlapping mappings are siblings (or cousins) and must be
        // closed in the reverse order of when they encountered.
        while (!stack.isEmpty() && !isOverlapped(stack.peek(), m)) {
          Mapping previous = stack.pop();
          maybeVisit(v, previous);
        }

        // Any gaps between the current line position and the start of the
        // current mapping belong to the parent.
        Mapping parent = stack.peek();
        maybeVisitParent(v, parent, m);

        stack.push(m);
      }

      // There are no more children to be had, simply close the remaining
      // mappings in the reverse order of when they encountered.
      while (!stack.isEmpty()) {
        Mapping m = stack.pop();
        maybeVisit(v, m);
      }
    }

    /**
     * @return The line adjusted for the prefix position.
     */
    private int getAdjustedLine(FilePosition p) {
      return p.getLine() + prefixPosition.getLine();
    }

    /**
     * @return The column adjusted for the prefix position.
     */
    private int getAdjustedCol(FilePosition p) {
      int rawLine = p.getLine();
      int rawCol = p.getColumn();
      // Only the first line needs the character position adjusted.
      return (rawLine != 0)
          ? rawCol : rawCol + prefixPosition.getColumn();
    }

    /**
     * @return Whether m1 ends before m2 starts.
     */
    private boolean isOverlapped(Mapping m1, Mapping m2) {
      // No need to use adjusted values here, relative positions are sufficient.
      int l1 = m1.endPosition.getLine();
      int l2 = m2.startPosition.getLine();
      int c1 = m1.endPosition.getColumn();
      int c2 = m2.startPosition.getColumn();

      return (l1 == l2 && c1 >= c2) || l1 > l2;
    }

    /**
     * Write any needed entries from the current position to the end of the
     * provided mapping.
     */
    private void maybeVisit(MappingVisitor v, Mapping m) throws IOException {
      int nextLine = getAdjustedLine(m.endPosition);
      int nextCol = getAdjustedCol(m.endPosition);
      // If this anything remaining in this mapping beyond the
      // current line and column position, write it out now.
      if (line < nextLine || (line == nextLine && col < nextCol)) {
        visit(v, m, nextLine, nextCol);
      }
    }

    /**
     * Write any needed entries to complete the provided mapping.
     */
    private void maybeVisitParent(MappingVisitor v, Mapping parent, Mapping m)
        throws IOException {
      int nextLine = getAdjustedLine(m.startPosition);
      int nextCol = getAdjustedCol(m.startPosition);
      // If the previous value is null, no mapping exists.
      Preconditions.checkState(line < nextLine || col <= nextCol);
      if (line < nextLine || (line == nextLine && col < nextCol)) {
        visit(v, parent, nextLine, nextCol);
      }
    }

    /**
     * Write any entries needed between the current position the next position
     * and update the current position.
     */
    private void visit(MappingVisitor v, Mapping m,
        int nextLine, int nextCol)
        throws IOException {
      Preconditions.checkState(line <= nextLine);
      Preconditions.checkState(line < nextLine || col < nextCol);

      if (line == nextLine && col == nextCol) {
        // Nothing to do.
        throw new IllegalStateException();
      }

      v.visit(m, line, col, nextLine, nextCol);

      line = nextLine;
      col = nextCol;
    }
  }

  /**
   * Appends the index source map to the given buffer.
   *
   * @param out The stream to which the map will be appended.
   * @param name The name of the generated source file that this source map
   *   represents.
   * @param sections An ordered list of map sections to include in the index.
   * @throws IOException
   */
  @Override
  public void appendIndexMapTo(
      Appendable out, String name, List<SourceMapSection> sections)
      throws IOException {
    // Add the header fields.
    out.append("{\n");
    appendFirstField(out, "version", "3");
    appendField(out, "file", escapeString(name));

    // Add the line character maps.
    appendFieldStart(out, "sections");
    out.append("[\n");
    boolean first = true;
    for (SourceMapSection section : sections) {
      if (first) {
        first = false;
      } else {
        out.append(",\n");
      }
      out.append("{\n");
      appendFirstField(out, "offset",
          offsetValue(section.getLine(), section.getColumn()));
      if (section.getSectionType() == SourceMapSection.SectionType.URL) {
        appendField(out, "url", escapeString(section.getSectionValue()));
      } else if (section.getSectionType() == SourceMapSection.SectionType.MAP) {
        appendField(out, "map", section.getSectionValue());
      } else {
        throw new IOException("Unexpected section type");
      }
      out.append("\n}");
    }

    out.append("\n]");
    appendFieldEnd(out);

    out.append("\n}\n");
  }

  private static CharSequence offsetValue(int line, int column) throws IOException {
    StringBuilder out = new StringBuilder();
    out.append("{\n");
    appendFirstField(out, "line", String.valueOf(line));
    appendField(out, "column", String.valueOf(column));
    out.append("\n}");
    return out;
  }

  private int getSourceId(String sourceName) {
    if (sourceName != lastSourceFile) {
      lastSourceFile = sourceName;
      Integer index = sourceFileMap.get(sourceName);
      if (index != null) {
        lastSourceFileIndex = index;
      } else {
        lastSourceFileIndex = sourceFileMap.size();
        sourceFileMap.put(sourceName, lastSourceFileIndex);
      }
    }
    return lastSourceFileIndex;
  }

  private int getNameId(String symbolName) {
    int originalNameIndex;
    Integer index = originalNameMap.get(symbolName);
    if (index != null) {
      originalNameIndex = index;
    } else {
      originalNameIndex = originalNameMap.size();
      originalNameMap.put(symbolName, originalNameIndex);
    }
    return originalNameIndex;
  }

  private class LineMapper implements MappingVisitor {
    // The destination.
    private final Appendable out;
    private final int maxLine; // TODO(johnlenz): This shouldn't be necessary to track.

    private int previousLine = -1;
    private int previousColumn = 0;

    // Previous values used for storing relative ids.
    private int previousSourceFileId;
    private int previousSourceLine;
    private int previousSourceColumn;
    private int previousNameId;

    LineMapper(Appendable out, int maxLine) {
      this.out = out;
      this.maxLine = maxLine;
    }

    /**
     * As each segment is visited write out the appropriate line mapping.
     */
    @Override
    public void visit(Mapping m, int line, int col, int nextLine, int nextCol)
      throws IOException {
      if (previousLine != line) {
        previousColumn = 0;
      }

      if (line != nextLine || col != nextCol) {
        // TODO(johnlenz): For some reason, we have mappings beyond the max line.
        // So far they're just null mappings and we can ignore them.
        // (If they're non-null, we assert-fail.)
        if (line < maxLine) {
          if (previousLine == line) { // not the first entry for the line
            out.append(',');
          }
          writeEntry(m, col);
          previousLine = line;
          previousColumn = col;
        } else {
          Preconditions.checkState(m == null);
        }
      }

      for (int i = line; i <= nextLine && i < maxLine; i++) {
        if (i == nextLine) {
          break;
        }

        closeLine(false);
        openLine(false);
      }
    }

    /**
     * Writes an entry for the given column (of the generated text) and
     * associated mapping.
     * The values are stored as relative to the last seen values for each
     * field and encoded as Base64VLQs.
     */
    void writeEntry(Mapping m, int column) throws IOException {
      // The relative generated column number
      Base64VLQ.encode(out, column - previousColumn);
      previousColumn = column;
      if (m != null) {
        // The relative source file id
        int sourceId = getSourceId(m.sourceFile);
        Base64VLQ.encode(out, sourceId - previousSourceFileId);
        previousSourceFileId = sourceId;

        // The relative source file line and column
        int srcline = m.originalPosition.getLine();
        int srcColumn = m.originalPosition.getColumn();
        Base64VLQ.encode(out, srcline - previousSourceLine);
        previousSourceLine = srcline;

        Base64VLQ.encode(out, srcColumn - previousSourceColumn);
        previousSourceColumn = srcColumn;

        if (m.originalName != null) {
          // The relative id for the associated symbol name
          int nameId = getNameId(m.originalName);
          Base64VLQ.encode(out, (nameId - previousNameId));
          previousNameId = nameId;
        }
      }
    }

    // Append the line mapping entries.
    void appendLineMappings() throws IOException {
      // Start the first line.
      openLine(true);

      (new MappingTraversal()).traverse(this);

      // And close the final line.
      closeLine(true);
    }

    /**
     * Begin the entry for a new line.
     */
    private void openLine(boolean firstEntry) throws IOException {
      if (firstEntry) {
        out.append('\"');
      }
    }

    /**
     * End the entry for a line.
     */
    private void closeLine(boolean finalEntry) throws IOException {
      out.append(';');
      if (finalEntry) {
        out.append('\"');
      }
    }
  }

}


text:
module.exports = function pedantic(value, period) {
  period = period || '.';
  value = /[a-zA-Z0-9]$/.test(value) ? value + period : value
  // sane if it ends with some common punctuation.
  var sane = /[!?:;\.]([\*`]+)?$/.test(value);
  if(!sane) {
    // close on markdown inline formatters
    value = /[^\.][\)\]\*`]+$/.test(value) ? value + period : value;
  }
  return value;
}


text:
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;

namespace DalSoft.RestClient.Commands
{
    internal class CommandFactory
    {
        private static readonly ReadOnlyCollection<Command> Commands = new ReadOnlyCollection<Command>(new List<Command>
        {
            new HeadersCommand(),
            new EscapedResourceCommand(),
            new QueryCommand(),
            new HttpMethodCommand()
        });

        private static readonly Command DefaultCommand = new ResourceCommand();

        internal static Command GetCommandFor(string method, object[] args)
        {
            //FirstOrDefault to make sure that the default commands e.g. Get, Query Etc.
            var command = Commands.FirstOrDefault(_ => _.IsCommandFor(method, args));

            if (command == null && DefaultCommand.IsCommandFor(method, args))
            {
                return DefaultCommand; //Resource is our default it does the chaining .api.v1.users.etc
            }

            return command;
        }
    }
}


text:
Node Custom Scaffolded App
========================

##How to  get started

####1. Download and install Git

If you dont have git installed go to the git site, download and install git.
While installing there will be an option to run git from your windows command line
Please select that option to broaden the scope of the git command.

[http://git-scm.com/](http://git-scm.com/)

####2. Download and install NodeJS

If you dont have NodeJS installed please go to the home site for Node,
download and install NodeJS

[http://nodejs.org/](http://nodejs.org/)

####3. Download and install MongoDB

If you dont have MongoDb installed then please go to the home site,
Download and install MongoDB

[http://www.mongodb.org/](http://www.mongodb.org/)

> - to setup mongo on a windows pc, please view [instructions](http://www.mkyong.com/mongodb/how-to-install-mongodb-on-windows/)

> ensure to add the mongo bin folder path tou your system PATH variable. view [instructions](http://www.windows-commandline.com/set-path-command-line/)

> - for mac users, its recommended to use `homebrew`

> `brew install mongodb`

####4. Run this command to install Global Node tools

If you dont have any of the tools listed after the `-g` statement in the following command.
then run this command from your command prompt

`npm install -g yo node-inspector nodemon grunt-cli bower karma istanbul npm-check-updates`

####5. Create And/or go to a development folder
If you have  prefered development folder navigate to that directory in your command prompt.

if you dont know how to navigate using the command prompt then
watch this video: [http://youtu.be/NAciFdtSkuc?t=4m27s](http://youtu.be/NAciFdtSkuc?t=4m27s)

Assuming this folder is currently on your c drive, this dev folder is easily accessible

run `cd \dev`

####6. Clone the Git Repository

Run this command once the cd command to you development folder is successful

`git clone https://github.com/lwhiteley/angular-fullstack-custom.git`

####7. change working directory

`cd angular-fullstack-custom`

####8. set git to track your own git repository to avoid checking in changes to the template

`git remote set-url origin git://new.url.here`

####9. Run this command to install all Node dependencies

` npm install`

##Hooray, your development environment has been set up. Its that easy!

##Commands to help during development
============

####To run all tests

run command `grunt test`

####To run the Server

run command `grunt serve`

This task now starts up all prerequisites including MongoDB

####Use bower to install new javascript libraries

eg. run command `bower install --save angular`

Then

run command `grunt injectr` to  inject libraries automatically into the HTML (index.html)

####Info

Happy Hacking away!!

Code coverage is handled for frontend, looking to support coverage for backend too


text:
package com.akpwebdesign.Breakout.entity.brick;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;

import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;

public enum BrickType {
	RED("res/red_brick.png"), BLUE("res/blue_brick.png"), GREEN(
			"res/green_brick.png"), ORANGE("res/orange_brick.png"), PURPLE(
			"res/purple_brick.png");

	private Image image;

	BrickType(String image) {
		try {
			this.setImage(new Image(image));
		} catch (SlickException e) {
			e.printStackTrace();
		}
	}

	public Image getImage() {
		return image;
	}

	public void setImage(Image image) {
		this.image = image;
	}

	private static final List<BrickType> VALUES = Collections
			.unmodifiableList(Arrays.asList(values()));
	private static final int SIZE = VALUES.size();
	private static final Random RANDOM = new Random();

	public static BrickType randomType() {
		return VALUES.get(RANDOM.nextInt(SIZE));
	}

	public BrickType next() {
		int index = (this.ordinal() + 1) % BrickType.values().length;
		return BrickType.values()[index];
	}
}


text:
``` diff
 namespace System.Security.Cryptography {
     public sealed class CryptographicAttributeObjectCollection : ICollection, IEnumerable {
+        public bool IsSynchronized { get; }
+        public object SyncRoot { get; }
-        bool System.Collections.ICollection.IsSynchronized { get; }

-        object System.Collections.ICollection.SyncRoot { get; }

     }
     public sealed class SafeEvpPKeyHandle : SafeHandle {
+        public static long OpenSslVersion { get; }
     }
 }
```


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width">
	<title>Documentation Modules</title>

	<link type="text/css" rel="stylesheet" href="styles/sunlight.default.css">

	<link type="text/css" rel="stylesheet" href="styles/site.cerulean.css">

		Documentation
		<button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#topNavigation">

        </button>

				Modules

bms

dashboard

display

live

overview

settings

				Classes

bms~BMSController

display~DisplayComponent

display~DisplayComponent.DisplayComponent

overview.OverviewController

overview~SOCGauge

				Global

syncUpdates

unsyncUpdates

UtilService

                <form class="navbar-form" role="search">

                        <input type="text" class="form-control" placeholder="Search" name="q" id="search-input">

                            <button class="btn btn-default" id="search-submit"></button>

                </form>

Modules

Classes

BMSController

DisplayComponent

DisplayComponent

OverviewController

SOCGauge

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Search results

            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

	Documentation generated by JSDoc 3.4.3

		on July 19th 2017, 10:45:36 pm

	using the DocStrap template.


text:
{-# LANGUAGE DeriveFunctor              #-}
{-# LANGUAGE DeriveGeneric              #-}
{-# LANGUAGE FlexibleContexts           #-}
{-# LANGUAGE FlexibleInstances          #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses      #-}

module Math.NumberTheory.TestUtils.MyCompose
  ( MyCompose(..)
  ) where

import GHC.Generics (Generic)

import Test.QuickCheck (Arbitrary)
import Test.SmallCheck.Series (Serial)

newtype MyCompose f g a = MyCompose { getMyCompose :: f (g a) }
  deriving (Eq, Ord, Show, Functor, Num, Enum, Bounded, Real, Integral, Arbitrary, Generic)

instance (Monad m, Serial m (f (g a))) => Serial m (MyCompose f g a)


text:
<title>uvm_subscriber</title><link rel="stylesheet" type="text/css" href="../../styles/main.css">

uvm_subscriber

This class provides an analysis export for receiving transactions from a connected analysis export.  Making such a connection “subscribes” this component to any transactions emitted by the connected analysis port.

Subtypes of this class must define the write method to process the incoming transactions.  This class is particularly useful when designing a coverage collector that attaches to a monitor.

Summary

uvm_subscriber

This class provides an analysis export for receiving transactions from a connected analysis export.

Class Hierarchy

uvm_void

uvm_object

uvm_report_object

uvm_component

uvm_subscriber

Class Declaration

      virtual class uvm_subscriber #(

   	      type
      T
       =
      int

      ) extends uvm_component

Ports

analysis_export	This export provides access to the write method, which derived subscribers must implement.

Methods

new	Creates and initializes an instance of this class using the normal constructor arguments for uvm_component: name is the name of the instance, and parent is the handle to the hierarchical parent, if any.

write	A pure virtual method that must be defined in each subclass.

Ports

analysis_export

This export provides access to the write method, which derived subscribers must implement.

Methods

new

      function new (

   	      string
      name,

   	      uvm_component
      parent

      )

Creates and initializes an instance of this class using the normal constructor arguments for uvm_component: name is the name of the instance, and parent is the handle to the hierarchical parent, if any.

write

      pure virtual function void write(

   	      T
      t

      )

A pure virtual method that must be defined in each subclass.  Access to this method by outside components should be done via the analysis_export.

virtual class uvm_void

The uvm_void class is the base class for all UVM classes.

virtual class uvm_object extends uvm_void

The uvm_object class is the base class for all UVM data and hierarchical classes.

class uvm_report_object extends uvm_object

The uvm_report_object provides an interface to the UVM reporting facility.

virtual class uvm_component extends uvm_report_object

The uvm_component class is the root base class for UVM components.

      virtual class uvm_subscriber #(

   	      type
      T
       =
      int

      ) extends uvm_component

This class provides an analysis export for receiving transactions from a connected analysis export.

      function new (

   	      string
      name,

   	      uvm_component
      parent

      )

Creates and initializes an instance of this class using the normal constructor arguments for uvm_component: name is the name of the instance, and parent is the handle to the hierarchical parent, if any.

      pure virtual function void write(

   	      T
      t

      )

A pure virtual method that must be defined in each subclass.


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>com.infinities.skyport</groupId>
		<artifactId>skyport-dependencies</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>

	<artifactId>skyport-distributed</artifactId>
	<version>3.2.0-SNAPSHOT</version>
	<name>skyport-distributed</name>
	<packaging>jar</packaging>
	<description>skyport-distributed is a distributed util project</description>
	<organization>
		<name>InfinitiesSoft, Inc.</name>
		<url>http://www.infinitiessoft.com/</url>
	</organization>
	<licenses>
		<license>
			<name>Apache License, Version 2.0</name>
			<url>http://www.apache.org/licenses/LICENSE-2.0</url>
		</license>
	</licenses>

	<dependencies>
		<dependency>
			<groupId>com.infinities.skyport</groupId>
			<artifactId>skyport-driver</artifactId>
		</dependency>
		<dependency>
			<groupId>com.infinities.skyport</groupId>
			<artifactId>skyport-api</artifactId>
		</dependency>
		<dependency>
			<groupId>com.infinities.skyport</groupId>
			<artifactId>skyport-hazelcast</artifactId>
		</dependency>

		<dependency>
			<groupId>com.google.guava</groupId>
			<artifactId>guava</artifactId>
		</dependency>

		<!-- shiro -->
		<dependency>
			<groupId>org.apache.shiro</groupId>
			<artifactId>shiro-ehcache</artifactId>
		</dependency>

		<!-- logging -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
		</dependency>

		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
		</dependency>

		<!-- for testing -->
		<dependency>
			<groupId>org.jmock</groupId>
			<artifactId>jmock-junit4</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.jmock</groupId>
			<artifactId>jmock-legacy</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>

	</dependencies>

	<build>
		<plugins>
			<plugin>
				<artifactId>maven-failsafe-plugin</artifactId>
				<configuration>
					<!-- skips surefire tests without skipping failsafe tests. Property
						value seems to magically default to false -->
					<skipTests>false</skipTests>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>


text:
"""Subcommand for filtering untranslated messages."""

import os
import click
from grow.commands import shared
from grow.common import rc_config
from grow.pods import pods
from grow import storage

CFG = rc_config.RC_CONFIG.prefixed('grow.translations.filter')

@click.command(name='filter')
@shared.pod_path_argument
@click.option('-o', type=str, default=None,
              help='Where to write the extracted translation catalog. The path'
                   ' must be relative to the pod\'s root.')
@click.option('-f', default=CFG.get('force', False), is_flag=True,
              help='Whether to force an update when writing localized message'
                   ' catalogs.')
@shared.include_header_option(CFG)
@shared.include_obsolete_option(CFG)
@shared.locale_option(
    help_text='Which locale(s) to analyze when creating template catalogs'
              ' that contain only untranslated messages. This option is'
              ' only applicable when using --untranslated.')
@shared.localized_option(CFG)
@shared.out_dir_option(
    CFG, help_text=('Where to write extracted localized translation catalogs.'
                    ' The path must be relative to the pod\'s root. This option'
                    ' is only applicable when using --localized.'))
@shared.path_option
def translations_filter(pod_path, locale, o, include_obsolete, localized, path,
                        include_header, out_dir, f):
    """Filters untranslated messages from catalogs into new catalogs."""
    root = os.path.abspath(os.path.join(os.getcwd(), pod_path))
    pod = pods.Pod(root, storage=storage.FileStorage)
    with pod.profile.timer('grow_translations_filter'):
        catalogs = pod.get_catalogs()
        if not locale:
            locale = catalogs.list_locales()
        if out_dir and pod.file_exists(out_dir) and not f:
            raise click.UsageError(
                '{} exists. You must specify a directory that does not exist, or '
                'use the "-f" flag, which will force update catalogs within the '
                'specified directory.'.format(out_dir))
        catalogs.filter(out_path=o, out_dir=out_dir,
                        include_obsolete=include_obsolete,
                        localized=localized, paths=path,
                        include_header=include_header, locales=locale)
    return pod


text: Superclass for selections in a morphic based tree


text:
namespace YaR.Clouds.Base
{
    public class FileSplitInfo
    {
        public bool IsHeader { get; set; }
        public bool IsPart => PartNumber > 0;
        public int PartNumber { get; set; }
    }
}


text:
{% extends "base_site.html" %}

{% block title %}Groups - Edit{% endblock %}

{% block extrahead %}{{ block.super }}

{% endblock %}

{% block breadcrumbs %}{{ block.super }}
  » Groups
  » {{ group.acronym }}
  » Goals and Milestones
  » Edit
{% endblock %}

{% block content %}

    <form id="edit-gm" enctype="multipart/form-data" action="" method="post">

Goals and Milestones

   {{ formset.management_form }}
   {{ formset.non_form_errors }}

     {% for field in formset.forms.0.visible_fields %}
         {{ field.label|capfirst }}
     {% endfor %}

     {% for form in formset.forms %}
        {% if form.non_field_errors %}

{{ form.non_field_errors }}

        {% endif %}

          {% for hidden in form.hidden_fields %}
            {{ hidden }}
          {% endfor %}
          {% for field in form.visible_fields %}

                 {{ field.errors }}
                 {{ field }}

          {% endfor %}

     {% endfor %}

    {% include "includes/buttons_save_cancel.html" %}

    </form>

{% endblock %}


text:
namespace elysium {

class ECDSAContext
{
public:
    ECDSAContext(unsigned int flags);
    ECDSAContext(ECDSAContext const &context);
    ECDSAContext(ECDSAContext &&context);
    ~ECDSAContext();

public:
    ECDSAContext& operator=(ECDSAContext const &context);
    ECDSAContext& operator=(ECDSAContext &&context);

    secp256k1_context const *Get() const;

    static ECDSAContext CreateSignContext();
    static ECDSAContext CreateVerifyContext();

private:
    void Randomize();

private:
    secp256k1_context* context;
};

} // elysium

#endif // FIRO_ELYSIUM_ECDSA_CONTEXT_H


text:
@interface OHCalendarMonthLayout : OHCalendarLayout

@end


text:
FOUNDATION_EXPORT double Pods_Trail_ExampleVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_Trail_ExampleVersionString[];


text:
require File.expand_path(File.dirname(__FILE__) + '/../../test_resource_helper')

# The root action(s) provide basic information about the API.
class RootResourceTest < RequestTestCase

  def app; DataCatalog::Root end

  shared "return api level metadata" do
    use "return 200 Ok"

    test "body has name" do
      assert_equal "National Data Catalog API", parsed_response_body["name"]
    end

    test "body has correct version" do
      assert_equal "0.4.13", parsed_response_body["version"]
    end

    test "body has list of resources" do
      assert_include "resource_directory", parsed_response_body
      expected = { "href" => "/resources" }
      assert_equal expected, parsed_response_body["resource_directory"]
    end

    test "body contains only the expected keys" do
      assert_equal [], parsed_response_body.keys - %w(
        creator
        documentation
        name
        project_page
        resource_directory
        source_code
        version
      )
    end
  end

  context "get /" do
    context "anonymous" do
      before :all do
        get '/'
      end

      use "return api level metadata"
    end

    context "incorrect API key" do
      before :all do
        get '/', :api_key => BAD_API_KEY
      end

      use "return 401 because the API key is invalid"
    end

    context "normal API key" do
      before :all do
        get '/', :api_key => @normal_user.primary_api_key
      end

      use "return api level metadata"
    end

    context "admin API key" do
      before :all do
        get '/', :api_key => @admin_user.primary_api_key
      end

      use "return api level metadata"
    end
  end

end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using XenAdmin.Network;
using XenAdmin.Core;
using XenAPI;
using System.Text;

namespace XenAdmin.Alerts
{
    public class XenServerPatchAlert : XenServerUpdateAlert
    {
        public const string IgnorePatchKey = "XenCenter.IgnorePatches";

        public readonly XenServerPatch Patch;
        public readonly XenServerVersion NewServerVersion;

        /// <summary>
        /// Can we apply this alert. Calling this sets the CannotApplyReason where applicable
        /// </summary>
        public bool CanApply
        {
            get
            {
                var distinctHosts = DistinctHosts;

                if (distinctHosts != null)
                {
                    if (distinctHosts.All(IsHostLicenseRestricted))
                    {
                        CannotApplyReason = Messages.MANUAL_CHECK_FOR_UPDATES_UNLICENSED_INFO;
                        return false;
                    }

                    if (distinctHosts.Any(IsHostLicenseRestricted))
                    {
                        CannotApplyReason = Messages.MANUAL_CHECK_FOR_UPDATES_PARTIAL_UNLICENSED_INFO;
                        return true;
                    }
                }

                CannotApplyReason = null;
                return true;
            }
        }

        public string CannotApplyReason { get; set; }

        private bool IsHostLicenseRestricted(Host host)
        {
            if(host == null)
                return false;

            return !host.CanApplyHotfixes();
        }

        /// <summary>
        /// Creates a patch alert
        ///  </summary>
        /// <param name="patch">The patch</param>
        /// <param name="newServerVersion">The version that the patch installs, or null if the patch doesn't update the server version</param>
        public XenServerPatchAlert(XenServerPatch patch, XenServerVersion newServerVersion = null)
        {
            Patch = patch;
            NewServerVersion = newServerVersion;
            if (NewServerVersion != null)
                RequiredClientVersion = Updates.GetRequiredClientVersion(NewServerVersion);
            _priority = patch.Priority;
            _timestamp = Patch.TimeStamp;
        }

        public override string WebPageLabel => Patch.Url;

        public override AlertPriority Priority
        {
            get
            {
                if (Enum.IsDefined(typeof(AlertPriority), _priority))
                    return (AlertPriority)_priority;

                return AlertPriority.Priority2;
            }
        }

        public override string Description
        {
            get
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(Patch.Description);
                if (Patch.InstallationSize != 0)
                {
                    sb.AppendLine();
                    sb.AppendFormat(Messages.PATCH_INSTALLATION_SIZE, Util.DiskSizeString(Patch.InstallationSize));
                }
                if (RequiredClientVersion != null)
                {
                    sb.AppendLine();
                    sb.AppendFormat(Messages.PATCH_NEEDS_NEW_XENCENTER, BrandManager.BrandConsole, RequiredClientVersion.Version);
                }
                return sb.ToString();
            }
        }

        public override string Name
        {
            get
            {
                if (ShowAsNewVersion)
                    return NewServerVersion.Name;
                return Patch.Name;
            }
        }

        public override Action FixLinkAction
        {
            get { return () => Program.OpenURL(Patch.Url); }
        }

        public override string FixLinkText => Messages.ALERT_NEW_PATCH_DOWNLOAD;

        public override string HelpID => "XenServerPatchAlert";

        public override string Title
        {
            get
            {
                if (ShowAsNewVersion)
                    return string.Format(Messages.DOWLOAD_LATEST_XS_TITLE, NewServerVersion.Name);
                return string.Format(Messages.NEW_UPDATE_AVAILABLE, Patch.Name);
            }
        }

        protected override bool IsDismissed(IXenConnection connection)
        {
            Pool pool = Helpers.GetPoolOfOne(connection);
            if (pool == null)
                return false;

            Dictionary<string, string> other_config = pool.other_config;

            if (other_config.ContainsKey(IgnorePatchKey))
            {
                List<string> current = new List<string>(other_config[IgnorePatchKey].Split(','));
                if (current.Contains(Patch.Uuid, StringComparer.OrdinalIgnoreCase))
                    return true;
            }
            return false;
        }

        protected override void Dismiss(Dictionary<string, string> otherConfig)
        {
            if (otherConfig.ContainsKey(IgnorePatchKey))
            {
                var current = new List<string>(otherConfig[IgnorePatchKey].Split(','));
                if (current.Contains(Patch.Uuid, StringComparer.OrdinalIgnoreCase))
                    return;

                current.Add(Patch.Uuid);
                otherConfig[IgnorePatchKey] = string.Join(",", current.ToArray());
            }
            else
            {
                otherConfig.Add(IgnorePatchKey, Patch.Uuid);
            }
        }

        public override bool Equals(Alert other)
        {
            if (other is XenServerPatchAlert patchAlert)
                return string.Equals(Patch.Uuid, patchAlert.Patch.Uuid, StringComparison.OrdinalIgnoreCase);

            return base.Equals(other);
        }

        public bool ShowAsNewVersion => NewServerVersion != null && !NewServerVersion.PresentAsUpdate;
    }
}


text:
[Metadata]
title: Milking Cows
date: 2015-04-08 00:16:04

[Tags]
difficulty: 2.5
categories: greedy, interval, sorting
source: The Algorithm Design Manual

[Description]

There are serval cows and several workers in a farm. One worker begins to milk a cow at time `a` and ends at time `b`.

Now your are given all pairs of `a` and `b` which indicate the work time of all the workers. Please find out:

* The longest time interval at least one cow was milked.
* The longest time interval (after milking starts) during which no cows were being milked.

[Solution]

This problem is a variety of "Longest non-intersect intervals". Greedy is the way to solve it.

Firstly, we sort the pairs with key `a`. And then, we will use the induction way to prove the correctness.

Assuming we've already got a working period `<ai, bi>`, which `ai` is the earliest one among the rest periods. We call it "earliest period".

If this period doesn't not intersect with any other period which is available, we can confirm that period is a **complete working period**.

And then, we keep adding new periods to "earliest period" if we get intersection or clear the "earliest period" if the periods is not overlap. Eventually, it's easy to find out the longest working period. And the idle period is quite the same.

The implementation is right here:

```cpp
// Result: Wizmann	181	Accepted	1080 KB	7 MS	C++	1015 B
2015-04-07 23:27:49
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

#define print(x) cout << x << endl
#define input(x) cin >> x

vector<pair<int, int> > vec;

int main() {
    int n;
    int a, b;

    while (input(n)) {
        vec.clear();
        for (int i = 0; i < n; i++) {
            input(a >> b);
            vec.push_back({a, b});
        }
        sort(vec.begin(), vec.end());

        int busy = 0;
        int idle = 0;
        int start = vec.begin()->first, end = vec.begin()->second;
        for (auto& p: vec) {
            a = p.first;
            b = p.second;

            if (a > end) {
                idle = max(idle, a - end);
                start = a;
                end = b;
                busy = max(busy, end - start);
            } else {
                end = max(end, b);
                busy = max(busy, end - start);
            }
        }

        printf("%d %d\n", busy, idle);
    }
    return 0;
}
```

You can test your code [here][1].

[1]: http://acm.uestc.edu.cn/#/problem/show/181


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace AfternoonDelight
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        }
    }
}


text:
using System;
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using ReservationSystem.Common;
using ReservationSystem.Extensions;
using ReservationSystem.Services.Data.Contracts;
using ReservationSystem.ViewComponents;
using ReservationSystem.ViewModels.CalendarViewModels;

namespace ReservationSystem.Controllers
{
  public class CalendarController : Controller
  {
    private readonly IMapper mapper;
    private readonly IEfUnitOfWork unitOfWork;
    private readonly IReservationService reservationService;

    public CalendarController(IMapper mapper, IEfUnitOfWork unitOfWork, IReservationService reservationService)
    {
      this.mapper = mapper ?? throw new ArgumentNullException(
        GlobalConstants.AutoMapperRequiredExceptionMessage);
      this.unitOfWork = unitOfWork ?? throw new ArgumentNullException(
        GlobalConstants.UnitOfWorkRequiredExceptionMessage);
      this.reservationService = reservationService ?? throw new ArgumentNullException(
        GlobalConstants.ReservationServiceRequiredExceptionMessage);
    }

    [HttpGet]
    public IActionResult Index()
    {
      var currentDate = DateTime.UtcNow.Date;

      return this.View(currentDate);
    }

    [HttpPost]
    public IActionResult GetPreviousMonth(long selectedYearMonth)
    {
      var newSelectedYearMonth = new DateTime(selectedYearMonth).ToUniversalTime().Date;
      var selectedYearMonthPrevious = newSelectedYearMonth.Date.AddMonths(-1);

      return this.ViewComponent(typeof(CalendarViewComponent), new { selectedYearMonth = selectedYearMonthPrevious });
    }

    [HttpPost]
    public IActionResult GetNextMonth(long selectedYearMonth)
    {
      var newSelectedYearMonth = new DateTime(selectedYearMonth).ToUniversalTime().Date;
      var selectedYearMonthNext = newSelectedYearMonth.Date.AddMonths(1);

      return this.ViewComponent(typeof(CalendarViewComponent), new { selectedYearMonth = selectedYearMonthNext });
    }

    [HttpPost]
    [Authorize]
    [ValidateAntiForgeryToken]
    public IActionResult ReservateTheDate(DateTime date)
    {
      if (!this.User.Identity.IsAuthenticated || this.User.IsInRole(GlobalConstants.AdministratorRoleName))
      {
        return this.View(nameof(CalendarController.Index), date);
      }

      if (date < DateTime.UtcNow.Date)
      {
        return this.View(nameof(CalendarController.Index), DateTime.UtcNow.Date);
      }

      var reservation = this.reservationService.GetActiveByDate(date);

      if (!string.IsNullOrWhiteSpace(reservation.OwnerId))
      {
        return this.View(nameof(CalendarController.Index), date);
      }

      var userId = this.User.GetUserId();
      reservation.OwnerId = userId;

      this.reservationService.Update(reservation);
      this.unitOfWork.SaveChanges();

      return this.View(nameof(CalendarController.Index), date);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult GetSelectedDateData(DateTime date)
    {
      var reservation = this.reservationService.GetActiveByDate(date);

      var newModel = this.mapper.Map<SelectedDateDataViewModel>(reservation);

      return this.ViewComponent(typeof(SelectedDateDataViewComponent), new { viewModel = newModel });
    }
  }
}


text:
+++
date = "2017-05-13T22:43:16-07:00"
title = "Contact"
+++

Officers April 2017 - March 2018

_President_ - Mike Manfredi

_Vice President_ - Jeff Mullinax

_Treasurer_ - David Morrow

_Secretary_ - Gary Moody

_Trip Madame_ - Maggie Donnell - [Email](mailto:gret215@gmail.com)

Club email list: This will broadcast an email to everyone
that has registerd an email with GSR.
- [gsr_list@gainesvillestreetrods.com](mailto:gsr_list@gainesvillestreetrods.com)

Submit your event to be posted on the website - [Email](mailto:post.events@gainesvillestreetrods.com)


text:
.. django-user-media documentation master file, created by
   sphinx-quickstart on Fri Jul 13 17:17:28 2012.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to django-user-media's documentation!
=============================================

Contents:

.. toctree::
   :maxdepth: 2

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`