text:
using namespace llvm;
using namespace llvm::MachO;

namespace TBDv4 {

TEST(TBDv4, ReadFile) {
  static const char TBDv4File[] =
      "--- !tapi-tbd\n"
      "tbd-version: 4\n"
      "targets:  [ i386-macos, x86_64-macos, x86_64-ios ]\n"
      "uuids:\n"
      "  - target: i386-macos\n"
      "    value: 00000000-0000-0000-0000-000000000000\n"
      "  - target: x86_64-macos\n"
      "    value: 11111111-1111-1111-1111-111111111111\n"
      "  - target: x86_64-ios\n"
      "    value: 11111111-1111-1111-1111-111111111111\n"
      "flags: [ flat_namespace, installapi ]\n"
      "install-name: Umbrella.framework/Umbrella\n"
      "current-version: 1.2.3\n"
      "compatibility-version: 1.2\n"
      "swift-abi-version: 5\n"
      "parent-umbrella:\n"
      "  - targets: [ i386-macos, x86_64-macos, x86_64-ios ]\n"
      "    umbrella: System\n"
      "allowable-clients:\n"
      "  - targets: [ i386-macos, x86_64-macos, x86_64-ios ]\n"
      "    clients: [ ClientA ]\n"
      "reexported-libraries:\n"
      "  - targets: [ i386-macos ]\n"
      "    libraries: [ /System/Library/Frameworks/A.framework/A ]\n"
      "exports:\n"
      "  - targets: [ i386-macos ]\n"
      "    symbols: [ _symA ]\n"
      "    objc-classes: []\n"
      "    objc-eh-types: []\n"
      "    objc-ivars: []\n"
      "    weak-symbols: []\n"
      "    thread-local-symbols: []\n"
      "  - targets: [ x86_64-ios ]\n"
      "    symbols: [_symB]\n"
      "  - targets: [ x86_64-macos, x86_64-ios ]\n"
      "    symbols: [_symAB]\n"
      "reexports:\n"
      "  - targets: [ i386-macos ]\n"
      "    symbols: [_symC]\n"
      "    objc-classes: []\n"
      "    objc-eh-types: []\n"
      "    objc-ivars: []\n"
      "    weak-symbols: []\n"
      "    thread-local-symbols: []\n"
      "undefineds:\n"
      "  - targets: [ i386-macos ]\n"
      "    symbols: [ _symD ]\n"
      "    objc-classes: []\n"
      "    objc-eh-types: []\n"
      "    objc-ivars: []\n"
      "    weak-symbols: []\n"
      "    thread-local-symbols: []\n"
      "...\n";

  auto Result = TextAPIReader::get(MemoryBufferRef(TBDv4File, "Test.tbd"));
  EXPECT_TRUE(!!Result);
  auto File = std::move(Result.get());
  EXPECT_EQ(FileType::TBD_V4, File->getFileType());
  PlatformSet Platforms;
  Platforms.insert(PlatformKind::macOS);
  Platforms.insert(PlatformKind::iOS);
  auto Archs = AK_i386 | AK_x86_64;
  TargetList Targets = {
      Target(AK_i386, PlatformKind::macOS),
      Target(AK_x86_64, PlatformKind::macOS),
      Target(AK_x86_64, PlatformKind::iOS),
  };
  UUIDs uuids = {{Targets[0], "00000000-0000-0000-0000-000000000000"},
                 {Targets[1], "11111111-1111-1111-1111-111111111111"},
                 {Targets[2], "11111111-1111-1111-1111-111111111111"}};
  EXPECT_EQ(Archs, File->getArchitectures());
  EXPECT_EQ(uuids, File->uuids());
  EXPECT_EQ(Platforms.size(), File->getPlatforms().size());
  for (auto Platform : File->getPlatforms())
    EXPECT_EQ(Platforms.count(Platform), 1U);
  EXPECT_EQ(std::string("Umbrella.framework/Umbrella"), File->getInstallName());
  EXPECT_EQ(PackedVersion(1, 2, 3), File->getCurrentVersion());
  EXPECT_EQ(PackedVersion(1, 2, 0), File->getCompatibilityVersion());
  EXPECT_EQ(5U, File->getSwiftABIVersion());
  EXPECT_FALSE(File->isTwoLevelNamespace());
  EXPECT_TRUE(File->isApplicationExtensionSafe());
  EXPECT_TRUE(File->isInstallAPI());
  InterfaceFileRef client("ClientA", Targets);
  InterfaceFileRef reexport("/System/Library/Frameworks/A.framework/A",
                            {Targets[0]});
  EXPECT_EQ(1U, File->allowableClients().size());
  EXPECT_EQ(client, File->allowableClients().front());
  EXPECT_EQ(1U, File->reexportedLibraries().size());
  EXPECT_EQ(reexport, File->reexportedLibraries().front());

  ExportedSymbolSeq Exports, Reexports, Undefineds;
  ExportedSymbol temp;
  for (const auto *Sym : File->symbols()) {
    temp = ExportedSymbol{Sym->getKind(), std::string(Sym->getName()),
                          Sym->isWeakDefined(), Sym->isThreadLocalValue()};
    EXPECT_FALSE(Sym->isWeakReferenced());
    if (Sym->isUndefined())
      Undefineds.emplace_back(std::move(temp));
    else
      Sym->isReexported() ? Reexports.emplace_back(std::move(temp))
                          : Exports.emplace_back(std::move(temp));
  }
  llvm::sort(Exports.begin(), Exports.end());
  llvm::sort(Reexports.begin(), Reexports.end());
  llvm::sort(Undefineds.begin(), Undefineds.end());

  static ExportedSymbol ExpectedExportedSymbols[] = {
      {SymbolKind::GlobalSymbol, "_symA", false, false},
      {SymbolKind::GlobalSymbol, "_symAB", false, false},
      {SymbolKind::GlobalSymbol, "_symB", false, false},
  };

  static ExportedSymbol ExpectedReexportedSymbols[] = {
      {SymbolKind::GlobalSymbol, "_symC", false, false},
  };

  static ExportedSymbol ExpectedUndefinedSymbols[] = {
      {SymbolKind::GlobalSymbol, "_symD", false, false},
  };

  EXPECT_EQ(sizeof(ExpectedExportedSymbols) / sizeof(ExportedSymbol),
            Exports.size());
  EXPECT_EQ(sizeof(ExpectedReexportedSymbols) / sizeof(ExportedSymbol),
            Reexports.size());
  EXPECT_EQ(sizeof(ExpectedUndefinedSymbols) / sizeof(ExportedSymbol),
            Undefineds.size());
  EXPECT_TRUE(std::equal(Exports.begin(), Exports.end(),
                         std::begin(ExpectedExportedSymbols)));
  EXPECT_TRUE(std::equal(Reexports.begin(), Reexports.end(),
                         std::begin(ExpectedReexportedSymbols)));
  EXPECT_TRUE(std::equal(Undefineds.begin(), Undefineds.end(),
                         std::begin(ExpectedUndefinedSymbols)));
}

TEST(TBDv4, ReadMultipleDocuments) {
  static const char TBDv4Inlines[] =
      "--- !tapi-tbd\n"
      "tbd-version: 4\n"
      "targets: [ i386-macos, i386-maccatalyst, x86_64-macos, "
      "x86_64-maccatalyst ]\n"
      "uuids:\n"
      "  - target: i386-macos\n"
      "    value: 00000000-0000-0000-0000-000000000000\n"
      "  - target: i386-maccatalyst\n"
      "    value: 00000000-0000-0000-0000-000000000002\n"
      "  - target: x86_64-macos\n"
      "    value: 11111111-1111-1111-1111-111111111111\n"
      "  - target: x86_64-maccatalyst\n"
      "    value: 11111111-1111-1111-1111-111111111112\n"
      "install-name: /System/Library/Frameworks/Umbrella.framework/Umbrella\n"
      "parent-umbrella:\n"
      "  - targets: [ i386-macos, x86_64-macos ]\n"
      "    umbrella: System\n"
      "reexported-libraries:\n"
      "  - targets: [ i386-macos, x86_64-macos ]\n"
      "    libraries: [ /System/Library/Frameworks/A.framework/A ]\n"
      "--- !tapi-tbd\n"
      "tbd-version: 4\n"
      "targets:  [ i386-macos, x86_64-macos ]\n"
      "uuids:\n"
      "  - target: i386-macos\n"
      "    value: 20000000-0000-0000-0000-000000000000\n"
      "  - target: x86_64-macos\n"
      "    value: 21111111-1111-1111-1111-111111111111\n"
      "flags: [ flat_namespace ]\n"
      "install-name: /System/Library/Frameworks/A.framework/A\n"
      "current-version: 1.2.3\n"
      "compatibility-version: 1.2\n"
      "swift-abi-version: 5\n"
      "exports:\n"
      "  - targets: [ i386-macos ]\n"
      "    symbols: [ _symA ]\n"
      "    objc-classes: []\n"
      "    objc-eh-types: []\n"
      "    objc-ivars: []\n"
      "    weak-symbols: []\n"
      "    thread-local-symbols: []\n"
      "  - targets: [ x86_64-macos ]\n"
      "    symbols: [_symAB]\n"
      "reexports:\n"
      "  - targets: [ i386-macos ]\n"
      "    symbols: [_symC]\n"
      "    objc-classes: []\n"
      "    objc-eh-types: []\n"
      "    objc-ivars: []\n"
      "    weak-symbols: []\n"
      "    thread-local-symbols: []\n"
      "undefineds:\n"
      "  - targets: [ i386-macos ]\n"
      "    symbols: [ _symD ]\n"
      "    objc-classes: []\n"
      "    objc-eh-types: []\n"
      "    objc-ivars: []\n"
      "    weak-symbols: []\n"
      "    thread-local-symbols: []\n"
      "...\n";

  PlatformSet Platforms;
  Platforms.insert(PlatformKind::macOS);
  Platforms.insert(PlatformKind::macCatalyst);
  ArchitectureSet Archs = AK_i386 | AK_x86_64;
  TargetList Targets;
  for (auto &&Arch : Archs)
    for (auto &&Platform : Platforms)
      Targets.emplace_back(Target(Arch, Platform));
  UUIDs Uuids = {
      {Targets[0], "00000000-0000-0000-0000-000000000000"},
      {Targets[1], "00000000-0000-0000-0000-000000000002"},
      {Targets[2], "11111111-1111-1111-1111-111111111111"},
      {Targets[3], "11111111-1111-1111-1111-111111111112"},
  };

  auto Result = TextAPIReader::get(MemoryBufferRef(TBDv4Inlines, "Test.tbd"));
  EXPECT_TRUE(!!Result);
  auto File = std::move(Result.get());
  EXPECT_EQ(FileType::TBD_V4, File->getFileType());
  EXPECT_EQ(Archs, File->getArchitectures());
  EXPECT_EQ(Uuids, File->uuids());
  EXPECT_EQ(Platforms, File->getPlatforms());
  EXPECT_EQ(
      std::string("/System/Library/Frameworks/Umbrella.framework/Umbrella"),
      File->getInstallName());
  EXPECT_TRUE(File->isTwoLevelNamespace());
  EXPECT_TRUE(File->isApplicationExtensionSafe());
  EXPECT_FALSE(File->isInstallAPI());
  EXPECT_EQ(PackedVersion(1, 0, 0), File->getCurrentVersion());
  EXPECT_EQ(PackedVersion(1, 0, 0), File->getCompatibilityVersion());
  InterfaceFileRef reexport("/System/Library/Frameworks/A.framework/A",
                            {Targets[0], Targets[2]});
  EXPECT_EQ(1U, File->reexportedLibraries().size());
  EXPECT_EQ(reexport, File->reexportedLibraries().front());
  ExportedSymbolSeq Exports;
  for (const auto *Sym : File->symbols()) {
    EXPECT_FALSE(Sym->isWeakReferenced());
    EXPECT_FALSE(Sym->isUndefined());
    Exports.emplace_back(ExportedSymbol{Sym->getKind(), Sym->getName().str(),
                                        Sym->isWeakDefined(),
                                        Sym->isThreadLocalValue()});
  }
  EXPECT_EQ(0U, Exports.size());

  // Check Inlined Document
  Exports.clear();
  Targets.clear();
  Uuids.clear();
  PlatformKind Platform = PlatformKind::macOS;
  for (auto &&Arch : Archs)
    Targets.emplace_back(Target(Arch, Platform));
  Uuids = {
      {Targets[0], "20000000-0000-0000-0000-000000000000"},
      {Targets[1], "21111111-1111-1111-1111-111111111111"},
  };

  auto Document = File->documents().front();
  EXPECT_EQ(FileType::TBD_V4, Document->getFileType());
  EXPECT_EQ(Archs, Document->getArchitectures());
  EXPECT_EQ(Uuids, Document->uuids());
  EXPECT_EQ(1U, Document->getPlatforms().size());
  EXPECT_EQ(Platform, *(Document->getPlatforms().begin()));
  EXPECT_EQ(std::string("/System/Library/Frameworks/A.framework/A"),
            Document->getInstallName());
  EXPECT_EQ(PackedVersion(1, 2, 3), Document->getCurrentVersion());
  EXPECT_EQ(PackedVersion(1, 2, 0), Document->getCompatibilityVersion());
  EXPECT_EQ(5U, Document->getSwiftABIVersion());
  EXPECT_FALSE(Document->isTwoLevelNamespace());
  EXPECT_TRUE(Document->isApplicationExtensionSafe());
  EXPECT_FALSE(Document->isInstallAPI());

  ExportedSymbolSeq Reexports, Undefineds;
  for (const auto *Sym : Document->symbols()) {
    ExportedSymbol Temp =
        ExportedSymbol{Sym->getKind(), std::string(Sym->getName()),
                       Sym->isWeakDefined(), Sym->isThreadLocalValue()};
    EXPECT_FALSE(Sym->isWeakReferenced());
    if (Sym->isUndefined())
      Undefineds.emplace_back(std::move(Temp));
    else
      Sym->isReexported() ? Reexports.emplace_back(std::move(Temp))
                          : Exports.emplace_back(std::move(Temp));
  }
  llvm::sort(Exports.begin(), Exports.end());
  llvm::sort(Reexports.begin(), Reexports.end());
  llvm::sort(Undefineds.begin(), Undefineds.end());

  static ExportedSymbol ExpectedExportedSymbols[] = {
      {SymbolKind::GlobalSymbol, "_symA", false, false},
      {SymbolKind::GlobalSymbol, "_symAB", false, false},
  };

  static ExportedSymbol ExpectedReexportedSymbols[] = {
      {SymbolKind::GlobalSymbol, "_symC", false, false},
  };

  static ExportedSymbol ExpectedUndefinedSymbols[] = {
      {SymbolKind::GlobalSymbol, "_symD", false, false},
  };

  EXPECT_EQ(sizeof(ExpectedExportedSymbols) / sizeof(ExportedSymbol),
            Exports.size());
  EXPECT_EQ(sizeof(ExpectedReexportedSymbols) / sizeof(ExportedSymbol),
            Reexports.size());
  EXPECT_EQ(sizeof(ExpectedUndefinedSymbols) / sizeof(ExportedSymbol),
            Undefineds.size());
  EXPECT_TRUE(std::equal(Exports.begin(), Exports.end(),
                         std::begin(ExpectedExportedSymbols)));
  EXPECT_TRUE(std::equal(Reexports.begin(), Reexports.end(),
                         std::begin(ExpectedReexportedSymbols)));
  EXPECT_TRUE(std::equal(Undefineds.begin(), Undefineds.end(),
                         std::begin(ExpectedUndefinedSymbols)));
}

TEST(TBDv4, WriteFile) {
  static const char TBDv4File[] =
      "--- !tapi-tbd\n"
      "tbd-version:     4\n"
      "targets:         [ i386-macos, x86_64-ios-simulator ]\n"
      "uuids:\n"
      "  - target:          i386-macos\n"
      "    value:           00000000-0000-0000-0000-000000000000\n"
      "  - target:          x86_64-ios-simulator\n"
      "    value:           11111111-1111-1111-1111-111111111111\n"
      "flags:           [ installapi ]\n"
      "install-name:    'Umbrella.framework/Umbrella'\n"
      "current-version: 1.2.3\n"
      "compatibility-version: 0\n"
      "swift-abi-version: 5\n"
      "parent-umbrella:\n"
      "  - targets:         [ i386-macos, x86_64-ios-simulator ]\n"
      "    umbrella:        System\n"
      "allowable-clients:\n"
      "  - targets:         [ i386-macos ]\n"
      "    clients:         [ ClientA ]\n"
      "exports:\n"
      "  - targets:         [ i386-macos ]\n"
      "    symbols:         [ _symA ]\n"
      "    objc-classes:    [ Class1 ]\n"
      "    weak-symbols:    [ _symC ]\n"
      "  - targets:         [ x86_64-ios-simulator ]\n"
      "    symbols:         [ _symB ]\n"
      "...\n";

  InterfaceFile File;
  TargetList Targets = {
      Target(AK_i386, PlatformKind::macOS),
      Target(AK_x86_64, PlatformKind::iOSSimulator),
  };
  UUIDs uuids = {{Targets[0], "00000000-0000-0000-0000-000000000000"},
                 {Targets[1], "11111111-1111-1111-1111-111111111111"}};
  File.setInstallName("Umbrella.framework/Umbrella");
  File.setFileType(FileType::TBD_V4);
  File.addTargets(Targets);
  File.addUUID(uuids[0].first, uuids[0].second);
  File.addUUID(uuids[1].first, uuids[1].second);
  File.setCurrentVersion(PackedVersion(1, 2, 3));
  File.setTwoLevelNamespace();
  File.setInstallAPI(true);
  File.setApplicationExtensionSafe(true);
  File.setSwiftABIVersion(5);
  File.addAllowableClient("ClientA", Targets[0]);
  File.addParentUmbrella(Targets[0], "System");
  File.addParentUmbrella(Targets[1], "System");
  File.addSymbol(SymbolKind::GlobalSymbol, "_symA", {Targets[0]});
  File.addSymbol(SymbolKind::GlobalSymbol, "_symB", {Targets[1]});
  File.addSymbol(SymbolKind::GlobalSymbol, "_symC", {Targets[0]},
                 SymbolFlags::WeakDefined);
  File.addSymbol(SymbolKind::ObjectiveCClass, "Class1", {Targets[0]});

  SmallString<4096> Buffer;
  raw_svector_ostream OS(Buffer);
  auto Result = TextAPIWriter::writeToStream(OS, File);
  EXPECT_FALSE(Result);
  EXPECT_STREQ(TBDv4File, Buffer.c_str());
}

TEST(TBDv4, WriteMultipleDocuments) {
  static const char TBDv4Inlines[] =
      "--- !tapi-tbd\n"
      "tbd-version:     4\n"
      "targets:         [ i386-maccatalyst, x86_64-maccatalyst ]\n"
      "uuids:\n"
      "  - target:          i386-maccatalyst\n"
      "    value:           00000000-0000-0000-0000-000000000002\n"
      "  - target:          x86_64-maccatalyst\n"
      "    value:           11111111-1111-1111-1111-111111111112\n"
      "install-name:    "
      "'/System/Library/Frameworks/Umbrella.framework/Umbrella'\n"
      "reexported-libraries:\n"
      "  - targets:         [ i386-maccatalyst, x86_64-maccatalyst ]\n"
      "    libraries:       [ '/System/Library/Frameworks/A.framework/A' ]\n"
      "--- !tapi-tbd\n"
      "tbd-version:     4\n"
      "targets:         [ i386-maccatalyst, x86_64-maccatalyst ]\n"
      "uuids:\n"
      "  - target:          i386-maccatalyst\n"
      "    value:           00000000-0000-0000-0000-000000000000\n"
      "  - target:          x86_64-maccatalyst\n"
      "    value:           11111111-1111-1111-1111-111111111111\n"
      "install-name:    '/System/Library/Frameworks/A.framework/A'\n"
      "exports:\n"
      "  - targets:         [ i386-maccatalyst ]\n"
      "    weak-symbols:    [ _symC ]\n"
      "  - targets:         [ i386-maccatalyst, x86_64-maccatalyst ]\n"
      "    symbols:         [ _symA ]\n"
      "    objc-classes:    [ Class1 ]\n"
      "  - targets:         [ x86_64-maccatalyst ]\n"
      "    symbols:         [ _symAB ]\n"
      "...\n";

  InterfaceFile File;
  PlatformKind Platform = PlatformKind::macCatalyst;
  TargetList Targets = {
      Target(AK_i386, Platform),
      Target(AK_x86_64, Platform),
  };
  UUIDs Uuids = {{Targets[0], "00000000-0000-0000-0000-000000000002"},
                 {Targets[1], "11111111-1111-1111-1111-111111111112"}};
  File.setInstallName("/System/Library/Frameworks/Umbrella.framework/Umbrella");
  File.setFileType(FileType::TBD_V4);
  File.addTargets(Targets);
  File.addUUID(Uuids[0].first, Uuids[0].second);
  File.addUUID(Uuids[1].first, Uuids[1].second);
  File.setCompatibilityVersion(PackedVersion(1, 0, 0));
  File.setCurrentVersion(PackedVersion(1, 0, 0));
  File.setTwoLevelNamespace();
  File.setApplicationExtensionSafe(true);
  File.addReexportedLibrary("/System/Library/Frameworks/A.framework/A",
                            Targets[0]);
  File.addReexportedLibrary("/System/Library/Frameworks/A.framework/A",
                            Targets[1]);

  // Write Second Document
  Uuids = {{Targets[0], "00000000-0000-0000-0000-000000000000"},
           {Targets[1], "11111111-1111-1111-1111-111111111111"}};
  InterfaceFile Document;
  Document.setInstallName("/System/Library/Frameworks/A.framework/A");
  Document.setFileType(FileType::TBD_V4);
  Document.addTargets(Targets);
  Document.addUUID(Uuids[0].first, Uuids[0].second);
  Document.addUUID(Uuids[1].first, Uuids[1].second);
  Document.setCompatibilityVersion(PackedVersion(1, 0, 0));
  Document.setCurrentVersion(PackedVersion(1, 0, 0));
  Document.setTwoLevelNamespace();
  Document.setApplicationExtensionSafe(true);
  Document.addSymbol(SymbolKind::GlobalSymbol, "_symA", Targets);
  Document.addSymbol(SymbolKind::GlobalSymbol, "_symAB", {Targets[1]});
  Document.addSymbol(SymbolKind::GlobalSymbol, "_symC", {Targets[0]},
                     SymbolFlags::WeakDefined);
  Document.addSymbol(SymbolKind::ObjectiveCClass, "Class1", Targets);
  File.addDocument(std::make_shared<InterfaceFile>(std::move(Document)));

  SmallString<4096> Buffer;
  raw_svector_ostream OS(Buffer);
  auto Result = TextAPIWriter::writeToStream(OS, File);
  EXPECT_FALSE(Result);
  EXPECT_STREQ(TBDv4Inlines, Buffer.c_str());
}

TEST(TBDv4, MultipleTargets) {
  static const char TBDv4MultipleTargets[] =
      "--- !tapi-tbd\n"
      "tbd-version: 4\n"
      "targets: [ i386-maccatalyst, x86_64-tvos, arm64-ios ]\n"
      "install-name: Test.dylib\n"
      "...\n";

  auto Result =
      TextAPIReader::get(MemoryBufferRef(TBDv4MultipleTargets, "Test.tbd"));
  EXPECT_TRUE(!!Result);
  PlatformSet Platforms;
  Platforms.insert(PlatformKind::macCatalyst);
  Platforms.insert(PlatformKind::tvOS);
  Platforms.insert(PlatformKind::iOS);
  auto File = std::move(Result.get());
  EXPECT_EQ(FileType::TBD_V4, File->getFileType());
  EXPECT_EQ(AK_x86_64 | AK_arm64 | AK_i386, File->getArchitectures());
  EXPECT_EQ(Platforms.size(), File->getPlatforms().size());
  for (auto Platform : File->getPlatforms())
    EXPECT_EQ(Platforms.count(Platform), 1U);

  SmallString<4096> Buffer;
  raw_svector_ostream OS(Buffer);
  auto WriteResult = TextAPIWriter::writeToStream(OS, *File);
  EXPECT_TRUE(!WriteResult);
  EXPECT_EQ(stripWhitespace(TBDv4MultipleTargets),
            stripWhitespace(Buffer.c_str()));
}

TEST(TBDv4, MultipleTargetsSameArch) {
  static const char TBDv4TargetsSameArch[] =
      "--- !tapi-tbd\n"
      "tbd-version: 4\n"
      "targets: [ x86_64-tvos , x86_64-maccatalyst ]\n"
      "install-name: Test.dylib\n"
      "...\n";

  auto Result =
      TextAPIReader::get(MemoryBufferRef(TBDv4TargetsSameArch, "Test.tbd"));
  EXPECT_TRUE(!!Result);
  PlatformSet Platforms;
  Platforms.insert(PlatformKind::tvOS);
  Platforms.insert(PlatformKind::macCatalyst);
  auto File = std::move(Result.get());
  EXPECT_EQ(FileType::TBD_V4, File->getFileType());
  EXPECT_EQ(ArchitectureSet(AK_x86_64), File->getArchitectures());
  EXPECT_EQ(Platforms.size(), File->getPlatforms().size());
  for (auto Platform : File->getPlatforms())
    EXPECT_EQ(Platforms.count(Platform), 1U);

  SmallString<4096> Buffer;
  raw_svector_ostream OS(Buffer);
  auto WriteResult = TextAPIWriter::writeToStream(OS, *File);
  EXPECT_TRUE(!WriteResult);
  EXPECT_EQ(stripWhitespace(TBDv4TargetsSameArch),
            stripWhitespace(Buffer.c_str()));
}

TEST(TBDv4, MultipleTargetsSamePlatform) {
  static const char TBDv4MultipleTargetsSamePlatform[] =
      "--- !tapi-tbd\n"
      "tbd-version: 4\n"
      "targets: [ armv7k-ios , arm64-ios]\n"
      "install-name: Test.dylib\n"
      "...\n";

  auto Result = TextAPIReader::get(
      MemoryBufferRef(TBDv4MultipleTargetsSamePlatform, "Test.tbd"));
  EXPECT_TRUE(!!Result);
  auto File = std::move(Result.get());
  EXPECT_EQ(FileType::TBD_V4, File->getFileType());
  EXPECT_EQ(AK_arm64 | AK_armv7k, File->getArchitectures());
  EXPECT_EQ(File->getPlatforms().size(), 1U);
  EXPECT_EQ(PlatformKind::iOS, *File->getPlatforms().begin());

  SmallString<4096> Buffer;
  raw_svector_ostream OS(Buffer);
  auto WriteResult = TextAPIWriter::writeToStream(OS, *File);
  EXPECT_TRUE(!WriteResult);
  EXPECT_EQ(stripWhitespace(TBDv4MultipleTargetsSamePlatform),
            stripWhitespace(Buffer.c_str()));
}

TEST(TBDv4, Target_maccatalyst) {
  static const char TBDv4TargetMacCatalyst[] =
      "--- !tapi-tbd\n"
      "tbd-version: 4\n"
      "targets: [  x86_64-maccatalyst ]\n"
      "install-name: Test.dylib\n"
      "...\n";

  auto Result =
      TextAPIReader::get(MemoryBufferRef(TBDv4TargetMacCatalyst, "Test.tbd"));
  EXPECT_TRUE(!!Result);
  auto File = std::move(Result.get());
  EXPECT_EQ(FileType::TBD_V4, File->getFileType());
  EXPECT_EQ(ArchitectureSet(AK_x86_64), File->getArchitectures());
  EXPECT_EQ(File->getPlatforms().size(), 1U);
  EXPECT_EQ(PlatformKind::macCatalyst, *File->getPlatforms().begin());

  SmallString<4096> Buffer;
  raw_svector_ostream OS(Buffer);
  auto WriteResult = TextAPIWriter::writeToStream(OS, *File);
  EXPECT_TRUE(!WriteResult);
  EXPECT_EQ(stripWhitespace(TBDv4TargetMacCatalyst),
            stripWhitespace(Buffer.c_str()));
}

TEST(TBDv4, Target_x86_ios) {
  static const char TBDv4Targetx86iOS[] = "--- !tapi-tbd\n"
                                          "tbd-version: 4\n"
                                          "targets: [  x86_64-ios ]\n"
                                          "install-name: Test.dylib\n"
                                          "...\n";

  auto Result =
      TextAPIReader::get(MemoryBufferRef(TBDv4Targetx86iOS, "Test.tbd"));
  EXPECT_TRUE(!!Result);
  auto File = std::move(Result.get());
  EXPECT_EQ(FileType::TBD_V4, File->getFileType());
  EXPECT_EQ(ArchitectureSet(AK_x86_64), File->getArchitectures());
  EXPECT_EQ(File->getPlatforms().size(), 1U);
  EXPECT_EQ(PlatformKind::iOS, *File->getPlatforms().begin());

  SmallString<4096> Buffer;
  raw_svector_ostream OS(Buffer);
  auto WriteResult = TextAPIWriter::writeToStream(OS, *File);
  EXPECT_TRUE(!WriteResult);
  EXPECT_EQ(stripWhitespace(TBDv4Targetx86iOS),
            stripWhitespace(Buffer.c_str()));
}

TEST(TBDv4, Target_arm_bridgeOS) {
  static const char TBDv4PlatformBridgeOS[] = "--- !tapi-tbd\n"
                                              "tbd-version: 4\n"
                                              "targets: [  armv7k-bridgeos ]\n"
                                              "install-name: Test.dylib\n"
                                              "...\n";

  auto Result =
      TextAPIReader::get(MemoryBufferRef(TBDv4PlatformBridgeOS, "Test.tbd"));
  EXPECT_TRUE(!!Result);
  auto File = std::move(Result.get());
  EXPECT_EQ(FileType::TBD_V4, File->getFileType());
  EXPECT_EQ(File->getPlatforms().size(), 1U);
  EXPECT_EQ(PlatformKind::bridgeOS, *File->getPlatforms().begin());
  EXPECT_EQ(ArchitectureSet(AK_armv7k), File->getArchitectures());

  SmallString<4096> Buffer;
  raw_svector_ostream OS(Buffer);
  auto WriteResult = TextAPIWriter::writeToStream(OS, *File);
  EXPECT_TRUE(!WriteResult);
  EXPECT_EQ(stripWhitespace(TBDv4PlatformBridgeOS),
            stripWhitespace(Buffer.c_str()));
}

TEST(TBDv4, Target_arm_iOS) {
  static const char TBDv4ArchArm64e[] = "--- !tapi-tbd\n"
                                        "tbd-version: 4\n"
                                        "targets: [  arm64e-ios ]\n"
                                        "install-name: Test.dylib\n"
                                        "...\n";

  auto Result =
      TextAPIReader::get(MemoryBufferRef(TBDv4ArchArm64e, "Test.tbd"));
  EXPECT_TRUE(!!Result);
  auto File = std::move(Result.get());
  EXPECT_EQ(FileType::TBD_V4, File->getFileType());
  EXPECT_EQ(File->getPlatforms().size(), 1U);
  EXPECT_EQ(PlatformKind::iOS, *File->getPlatforms().begin());
  EXPECT_EQ(ArchitectureSet(AK_arm64e), File->getArchitectures());

  SmallString<4096> Buffer;
  raw_svector_ostream OS(Buffer);
  auto WriteResult = TextAPIWriter::writeToStream(OS, *File);
  EXPECT_TRUE(!WriteResult);
  EXPECT_EQ(stripWhitespace(TBDv4ArchArm64e), stripWhitespace(Buffer.c_str()));
}

TEST(TBDv4, Target_x86_macos) {
  static const char TBDv4Targetx86MacOS[] = "--- !tapi-tbd\n"
                                            "tbd-version: 4\n"
                                            "targets: [  x86_64-macos ]\n"
                                            "install-name: Test.dylib\n"
                                            "...\n";

  auto Result =
      TextAPIReader::get(MemoryBufferRef(TBDv4Targetx86MacOS, "Test.tbd"));
  EXPECT_TRUE(!!Result);
  auto File = std::move(Result.get());
  EXPECT_EQ(FileType::TBD_V4, File->getFileType());
  EXPECT_EQ(ArchitectureSet(AK_x86_64), File->getArchitectures());
  EXPECT_EQ(File->getPlatforms().size(), 1U);
  EXPECT_EQ(PlatformKind::macOS, *File->getPlatforms().begin());

  SmallString<4096> Buffer;
  raw_svector_ostream OS(Buffer);
  auto WriteResult = TextAPIWriter::writeToStream(OS, *File);
  EXPECT_TRUE(!WriteResult);
  EXPECT_EQ(stripWhitespace(TBDv4Targetx86MacOS),
            stripWhitespace(Buffer.c_str()));
}

TEST(TBDv4, Target_x86_ios_simulator) {
  static const char TBDv4Targetx86iOSSim[] =
      "--- !tapi-tbd\n"
      "tbd-version: 4\n"
      "targets: [  x86_64-ios-simulator  ]\n"
      "install-name: Test.dylib\n"
      "...\n";

  auto Result =
      TextAPIReader::get(MemoryBufferRef(TBDv4Targetx86iOSSim, "Test.tbd"));
  EXPECT_TRUE(!!Result);
  auto File = std::move(Result.get());
  EXPECT_EQ(FileType::TBD_V4, File->getFileType());
  EXPECT_EQ(ArchitectureSet(AK_x86_64), File->getArchitectures());
  EXPECT_EQ(File->getPlatforms().size(), 1U);
  EXPECT_EQ(PlatformKind::iOSSimulator, *File->getPlatforms().begin());

  SmallString<4096> Buffer;
  raw_svector_ostream OS(Buffer);
  auto WriteResult = TextAPIWriter::writeToStream(OS, *File);
  EXPECT_TRUE(!WriteResult);
  EXPECT_EQ(stripWhitespace(TBDv4Targetx86iOSSim),
            stripWhitespace(Buffer.c_str()));
}

TEST(TBDv4, Target_x86_tvos_simulator) {
  static const char TBDv4x86tvOSSim[] = "--- !tapi-tbd\n"
                                        "tbd-version: 4\n"
                                        "targets: [  x86_64-tvos-simulator  ]\n"
                                        "install-name: Test.dylib\n"
                                        "...\n";

  auto Result =
      TextAPIReader::get(MemoryBufferRef(TBDv4x86tvOSSim, "Test.tbd"));
  EXPECT_TRUE(!!Result);
  auto File = std::move(Result.get());
  EXPECT_EQ(FileType::TBD_V4, File->getFileType());
  EXPECT_EQ(ArchitectureSet(AK_x86_64), File->getArchitectures());
  EXPECT_EQ(File->getPlatforms().size(), 1U);
  EXPECT_EQ(PlatformKind::tvOSSimulator, *File->getPlatforms().begin());

  SmallString<4096> Buffer;
  raw_svector_ostream OS(Buffer);
  auto WriteResult = TextAPIWriter::writeToStream(OS, *File);
  EXPECT_TRUE(!WriteResult);
  EXPECT_EQ(stripWhitespace(TBDv4x86tvOSSim), stripWhitespace(Buffer.c_str()));
}

TEST(TBDv4, Target_i386_watchos_simulator) {
  static const char TBDv4i386watchOSSim[] =
      "--- !tapi-tbd\n"
      "tbd-version: 4\n"
      "targets: [  i386-watchos-simulator  ]\n"
      "install-name: Test.dylib\n"
      "...\n";

  auto Result =
      TextAPIReader::get(MemoryBufferRef(TBDv4i386watchOSSim, "Test.tbd"));
  EXPECT_TRUE(!!Result);
  auto File = std::move(Result.get());
  EXPECT_EQ(FileType::TBD_V4, File->getFileType());
  EXPECT_EQ(ArchitectureSet(AK_i386), File->getArchitectures());
  EXPECT_EQ(File->getPlatforms().size(), 1U);
  EXPECT_EQ(PlatformKind::watchOSSimulator, *File->getPlatforms().begin());

  SmallString<4096> Buffer;
  raw_svector_ostream OS(Buffer);
  auto WriteResult = TextAPIWriter::writeToStream(OS, *File);
  EXPECT_TRUE(!WriteResult);
  EXPECT_EQ(stripWhitespace(TBDv4i386watchOSSim),
            stripWhitespace(Buffer.c_str()));
}

TEST(TBDv4, Swift_1) {
  static const char TBDv4SwiftVersion1[] = "--- !tapi-tbd\n"
                                           "tbd-version: 4\n"
                                           "targets: [  x86_64-macos ]\n"
                                           "install-name: Test.dylib\n"
                                           "swift-abi-version: 1\n"
                                           "...\n";

  auto Result =
      TextAPIReader::get(MemoryBufferRef(TBDv4SwiftVersion1, "Test.tbd"));
  EXPECT_TRUE(!!Result);
  auto File = std::move(Result.get());
  EXPECT_EQ(FileType::TBD_V4, File->getFileType());
  EXPECT_EQ(1U, File->getSwiftABIVersion());

  // No writer test because we emit "swift-abi-version:1.0".
}

TEST(TBDv4, Swift_2) {
  static const char TBDv4Swift2[] = "--- !tapi-tbd\n"
                                    "tbd-version: 4\n"
                                    "targets: [  x86_64-macos ]\n"
                                    "install-name: Test.dylib\n"
                                    "swift-abi-version: 2\n"
                                    "...\n";

  auto Result = TextAPIReader::get(MemoryBufferRef(TBDv4Swift2, "Test.tbd"));
  EXPECT_TRUE(!!Result);
  auto File = std::move(Result.get());
  EXPECT_EQ(FileType::TBD_V4, File->getFileType());
  EXPECT_EQ(2U, File->getSwiftABIVersion());

  // No writer test because we emit "swift-abi-version:2.0".
}

TEST(TBDv4, Swift_5) {
  static const char TBDv4SwiftVersion5[] = "--- !tapi-tbd\n"
                                           "tbd-version: 4\n"
                                           "targets: [  x86_64-macos ]\n"
                                           "install-name: Test.dylib\n"
                                           "swift-abi-version: 5\n"
                                           "...\n";

  auto Result =
      TextAPIReader::get(MemoryBufferRef(TBDv4SwiftVersion5, "Test.tbd"));
  EXPECT_TRUE(!!Result);
  auto File = std::move(Result.get());
  EXPECT_EQ(FileType::TBD_V4, File->getFileType());
  EXPECT_EQ(5U, File->getSwiftABIVersion());

  SmallString<4096> Buffer;
  raw_svector_ostream OS(Buffer);
  auto WriteResult = TextAPIWriter::writeToStream(OS, *File);
  EXPECT_TRUE(!WriteResult);
  EXPECT_EQ(stripWhitespace(TBDv4SwiftVersion5),
            stripWhitespace(Buffer.c_str()));
}

TEST(TBDv4, Swift_99) {
  static const char TBDv4SwiftVersion99[] = "--- !tapi-tbd\n"
                                            "tbd-version: 4\n"
                                            "targets: [  x86_64-macos ]\n"
                                            "install-name: Test.dylib\n"
                                            "swift-abi-version: 99\n"
                                            "...\n";

  auto Result =
      TextAPIReader::get(MemoryBufferRef(TBDv4SwiftVersion99, "Test.tbd"));
  EXPECT_TRUE(!!Result);
  auto File = std::move(Result.get());
  EXPECT_EQ(FileType::TBD_V4, File->getFileType());
  EXPECT_EQ(99U, File->getSwiftABIVersion());

  SmallString<4096> Buffer;
  raw_svector_ostream OS(Buffer);
  auto WriteResult = TextAPIWriter::writeToStream(OS, *File);
  EXPECT_TRUE(!WriteResult);
  EXPECT_EQ(stripWhitespace(TBDv4SwiftVersion99),
            stripWhitespace(Buffer.c_str()));
}

TEST(TBDv4, InvalidArchitecture) {
  static const char TBDv4UnknownArch[] = "--- !tapi-tbd\n"
                                         "tbd-version: 4\n"
                                         "targets: [ foo-macos ]\n"
                                         "install-name: Test.dylib\n"
                                         "...\n";

  auto Result =
      TextAPIReader::get(MemoryBufferRef(TBDv4UnknownArch, "Test.tbd"));
  EXPECT_FALSE(!!Result);
  auto errorMessage = toString(Result.takeError());
  EXPECT_EQ("malformed file\nTest.tbd:3:12: error: unknown "
            "architecture\ntargets: [ foo-macos ]\n"
            "           ^~~~~~~~~~\n",
            errorMessage);
}

TEST(TBDv4, InvalidPlatform) {
  static const char TBDv4FInvalidPlatform[] = "--- !tapi-tbd\n"
                                              "tbd-version: 4\n"
                                              "targets: [ x86_64-maos ]\n"
                                              "install-name: Test.dylib\n"
                                              "...\n";

  auto Result =
      TextAPIReader::get(MemoryBufferRef(TBDv4FInvalidPlatform, "Test.tbd"));
  EXPECT_FALSE(!!Result);
  auto errorMessage = toString(Result.takeError());
  EXPECT_EQ("malformed file\nTest.tbd:3:12: error: unknown platform\ntargets: "
            "[ x86_64-maos ]\n"
            "           ^~~~~~~~~~~~\n",
            errorMessage);
}

TEST(TBDv4, MalformedFile1) {
  static const char TBDv4MalformedFile1[] = "--- !tapi-tbd\n"
                                            "tbd-version: 4\n"
                                            "...\n";

  auto Result =
      TextAPIReader::get(MemoryBufferRef(TBDv4MalformedFile1, "Test.tbd"));
  EXPECT_FALSE(!!Result);
  auto errorMessage = toString(Result.takeError());
  ASSERT_EQ("malformed file\nTest.tbd:2:1: error: missing required key "
            "'targets'\ntbd-version: 4\n^\n",
            errorMessage);
}

TEST(TBDv4, MalformedFile2) {
  static const char TBDv4MalformedFile2[] = "--- !tapi-tbd\n"
                                            "tbd-version: 4\n"
                                            "targets: [ x86_64-macos ]\n"
                                            "install-name: Test.dylib\n"
                                            "foobar: \"unsupported key\"\n";

  auto Result =
      TextAPIReader::get(MemoryBufferRef(TBDv4MalformedFile2, "Test.tbd"));
  EXPECT_FALSE(!!Result);
  auto errorMessage = toString(Result.takeError());
  ASSERT_EQ(
      "malformed file\nTest.tbd:5:9: error: unknown key 'foobar'\nfoobar: "
      "\"unsupported key\"\n        ^~~~~~~~~~~~~~~~~\n",
      errorMessage);
}

TEST(TBDv4, MalformedFile3) {
  static const char TBDv4MalformedSwift[] = "--- !tapi-tbd\n"
                                            "tbd-version: 4\n"
                                            "targets: [  x86_64-macos ]\n"
                                            "install-name: Test.dylib\n"
                                            "swift-abi-version: 1.1\n"
                                            "...\n";

  auto Result =
      TextAPIReader::get(MemoryBufferRef(TBDv4MalformedSwift, "Test.tbd"));
  EXPECT_FALSE(!!Result);
  auto errorMessage = toString(Result.takeError());
  EXPECT_EQ("malformed file\nTest.tbd:5:20: error: invalid Swift ABI "
            "version.\nswift-abi-version: 1.1\n                   ^~~\n",
            errorMessage);
}

} // end namespace TBDv4


text:
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE digester-rules PUBLIC
  "-//Apache Commons //DTD digester-rules XML V1.0//EN"
  "http://commons.apache.org/digester/dtds/digester-rules-3.0.dtd">

<!-- there are several objects in stack. -->
<!-- top of stack: parent object with addCheckExclusion(CheckExclusion) method -->
<digester-rules>
	<pattern value="nullable">
		<object-create-rule
			classname="net.sf.oval.constraint.exclusion.NullableExclusion" />
		<!-- read properties and set into CheckExlusion -->
		<include
			url="classpath:/com/github/nest/arcteryx/validation/oval/configuration/xml/oval-check-exclusion-properties.xml" />
		<call-method-rule methodname="addCheckExclusion"
			targetoffset="1" paramcount="1" paramtypes="net.sf.oval.CheckExclusion" />
		<call-param-rule paramnumber="0" stack-index="0" />
	</pattern>
</digester-rules>

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Tests\Inowas\AppBundle\Tests\Controller;

use FOS\UserBundle\Doctrine\UserManager;
use Inowas\AppBundle\Model\User;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class UserControllerTest extends WebTestCase
{
    /** @var  User */
    protected $user;

    /** @var  UserManager */
    protected $userManager;

    public function setUp(){

        self::bootKernel();

        $this->userManager = static::$kernel->getContainer()
            ->get('fos_user.user_manager')
        ;

        $username = 'testUser';
        $email = 'testUser@email';
        $password = 'testUserPassword';

        $this->user = $this->userManager->findUserByUsername($username);
        if (! $this->user instanceof User){
            $this->user = $this->userManager->createUser()
                ->setUsername($username)
                ->setEmail($email)
                ->setPlainPassword($password)
                ->setEnabled(true);

            $this->userManager->updateUser($this->user);
        }
    }

    public function testRetrieveAPIKeyWithCorrectCredentials(): void
    {
        $client = static::createClient();
        $client->request(
            'POST',
            '/v2/users/credentials.json',
            array(
                'username' => $this->user->getUsername(),
                'password' => 'testUserPassword'
            )
        );

        $this->assertEquals(200, $client->getResponse()->getStatusCode());
        $response = $client->getResponse()->getContent();
        $this->assertJson($response);
        $response = json_decode($response);
        $this->assertEquals($this->user->getApiKey(), $response->api_key);
    }

    public function testRetrieveAPIKeyWithInCorrectCredentialsReturns401(): void
    {

        $client = static::createClient();
        $client->request(
            'POST',
            '/v2/users/credentials.json',
            array(
                'username' => $this->user->getUsername(),
                'password' => 'sadkjfh'
            )
        );

        $this->assertEquals(401, $client->getResponse()->getStatusCode());
    }

    /**
     * @test
     */
    public function it_gets_user_data(): void
    {
        $client = static::createClient();
        $client->request(
            'GET',
            '/v2/users.json',
            [],
            [],
            ['HTTP_X-AUTH-TOKEN' => $this->user->getApiKey()]
        );

        $this->assertEquals(200, $client->getResponse()->getStatusCode());
        $response = $client->getResponse()->getContent();
        $this->assertJson($response);

        $arr = json_decode($response, true);
        $this->assertInternalType('array', $arr);
    }

    /**
     * @test
     */
    public function it_puts_user_data(): void
    {
        $client = static::createClient();
        $client->request(
            'PUT',
            '/v2/users.json',
            [],
            [],
            ['HTTP_X-AUTH-TOKEN' => $this->user->getApiKey()],
            json_encode([
                'name' => 'name',
                'email' => 'email@email.com',
                'institution' => 'inst'
            ])
        );

        $this->assertEquals(303, $client->getResponse()->getStatusCode());
        $client->followRedirect();
        $this->assertEquals(200, $client->getResponse()->getStatusCode());
        $response = $client->getResponse()->getContent();
        $this->assertJson($response);

        $arr = json_decode($response, true);
        $this->assertInternalType('array', $arr);
        $this->assertArrayHasKey('profile', $arr);
    }
}


text:
{% extends "pybb/base.html" %}
{% load i18n pybb_tags guardian_tags %}

{% block extra_script %}
    {{ block.super }}
    {% include "pybb/_sceditor.html" %}

{% endblock %}

{% block breadcrumb %}
    {% if forum %}
        {% with object=forum extra_crumb="New topic" %}
            {% include "pybb/breadcrumb.html" %}
        {% endwith %}
    {% else %}
        {% with object=topic extra_crumb="New reply" %}
            {% include "pybb/breadcrumb.html" %}
        {% endwith %}
    {% endif %}
{% endblock %}

{% block content %}

    {% include "pybb/post/form.html" %}

    {% if topic %}
        {% get_obj_perms request.user for topic.forum as "forum_perms" %}

            {% if topic.poll_type != 0 %}
                {% include "pybb/poll/detail.html" %}
            {% endif %}

                {% if first_post %}{% ifnotequal first_post post_list.0 %}
                    {% with first_post as post %}

{% include "pybb/post/template.html" %}

                    {% endwith %}
                {% endifnotequal %}{% endif %}
                {% for post in post_list %}
                    {% cycle "odd" "even" as rowcolors silent %}
                    {% include "pybb/post/template.html" with page=page_obj %}
                {% endfor %}

        {% if post_count > post_page_size %}

                {% blocktrans with page_size=post_page_size %}This discussion has more {{ page_size }} answers{% endblocktrans %}
                {% trans "Click here to see the full discussion" %}

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


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Issue Tracking</title>

JIRA

JBehave uses JIRA as issue tracking and planning tool.

We welcome user input in driving our development priorities. You can suggest new features or enhancements to an existing ones.


text:
package com.fanyo.exception;

public class AppException extends RuntimeException {
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	private String errorCode = "";

	private String errorMessage = "";

	public AppException(String errorCode){
		super(errorCode);
		this.errorCode = errorCode;
	}

	public AppException(String errorCode, String errorMessage){
		super(errorCode);
		this.errorCode = errorCode;
		this.errorMessage = errorMessage;
	}

	public String getErrorCode(){
		return errorCode;
	}

	public AppException() {
        super();
    }

    public AppException(String errorCode, Throwable cause) {
        super(errorCode, cause);
        this.errorCode = errorCode;
    }

    public AppException(String errorCode, String errorMessage, Throwable cause) {
        super(errorCode, cause);
        this.errorCode = errorCode;
        this.errorMessage = errorMessage;
    }

    public AppException(Throwable cause) {
        super(cause);
    }

	public String getErrorMessage() {
		return errorMessage;
	}

}


text:
layout: single
title: "Spatial Intro 01: Intro"
authors: [Leah Wasser]
contributors: [NEON Data Skills]
dateCreated: 2016-09-26
lastModified: 2016-11-29
packagesLibraries: [raster, rgdal, sp]
category: [course-materials]
excerpt: 'This tutorial covers the basics of key data formats that may
contain spatial information including shapefile, GeoTIFF and .csv. It also
provides a brief overview of other formats that you may encounter when working
with spatial data.'
sidebar:
  nav:
nav-title: 'spatial intro'
permalink: course-materials/intro-spatial-data-r
class-lesson: ['intro-spatial-data-r']
author_profile: false
comments: false
order: 1
---

This tutorial introduces issues associated with spatial data management.

**R Skill Level:** Beginner

# Goals / Objectives

After completing this activity, you will:

* know stuff

### Install R Packages

* **raster:** `install.packages("raster")`
* **rgdal:** `install.packages("rgdal")`

****

### Additional Resources

* Wikipedia article on

GIS file formats.

This should introduce the user to spatial data management issues - that we
will discuss in this series.

## Get Started With Your Project -  File Organization

When we work with large, spatio-temporal data, it is a good idea to store large
data sets in a general data directory that you can easily access from many
projects. If you are working in a collaborative
environment, use a shared data directory.

## One Dataset - Many Files

While text files often are self contained (one CSV) is composed of one unique file,
many spatial formats contain several files. For instance, a shapefile (discussed
below) contains 3 or more files, all of which must retain the same NAME and be
stored in the same file directory, in order for you to be able to work with them.
We will discuss these issues as they related to two key spatial data formats -
.shp (shapefile) which stores **vector** data and .tif (geotiff) which stores
**raster** data in more detail, below.

# Basic Raster vs Vector overview


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<cpanel include="conf.inc">

<title>Control Panel</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link href="cpanel.css" rel="stylesheet" type="text/css">

        Welcome to example.com


text:
import React, { Fragment } from 'react';
import PropTypes from 'prop-types';
import Helmet from 'react-helmet';
import { graphql } from 'gatsby';

import FullWidthRow from '../../components/helpers/FullWidthRow';
import { MarkdownRemark } from '../../redux/propTypes';

const propTypes = {
  data: PropTypes.shape({
    markdownRemark: MarkdownRemark
  })
};

function SuperBlockIntroductionPage({ data: { markdownRemark } }) {
  const {
    html,
    frontmatter: { superBlock }
  } = markdownRemark;
  return (
    <Fragment>
      <Helmet>
        <title>{superBlock} | freeCodeCamp.org</title>
      </Helmet>
      <FullWidthRow>
        <div
          className='intro-layout'
          dangerouslySetInnerHTML={{ __html: html }}
        />
      </FullWidthRow>
    </Fragment>
  );
}

SuperBlockIntroductionPage.displayName = 'SuperBlockIntroductionPage';
SuperBlockIntroductionPage.propTypes = propTypes;

export default SuperBlockIntroductionPage;

export const query = graphql`
  query SuperBlockIntroPageBySlug($slug: String!) {
    markdownRemark(fields: { slug: { eq: $slug } }) {
      frontmatter {
        superBlock
      }
      html
    }
  }
`;


text:
@interface PodsDummy_Pods_VOKMultiImagePicker_iOS_VOKMultiImagePicker_iOS : NSObject
@end
@implementation PodsDummy_Pods_VOKMultiImagePicker_iOS_VOKMultiImagePicker_iOS
@end


text:
using System;

using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Encoders;

namespace Org.BouncyCastle.Crypto.Generators
{
    /**
     * Generate suitable parameters for DSA, in line with FIPS 186-2, or FIPS 186-3.
     */
    public class DsaParametersGenerator
    {
        private IDigest         digest;
        private int				L, N;
        private int				certainty;
        private SecureRandom	random;
        private bool            use186_3;
        private int             usageIndex;

        public DsaParametersGenerator()
            : this(new Sha1Digest())
        {
        }

        public DsaParametersGenerator(IDigest digest)
        {
            this.digest = digest;
        }

        /// Initialise the generator
        /// <remarks>This form can only be used for older DSA (pre-DSA2) parameters</remarks>
        /// <param name="size">the size of keys in bits (from 512 up to 1024, and a multiple of 64)</param>
        /// <param name="certainty">measure of robustness of primes (at least 80 for FIPS 186-2 compliance)</param>
        /// <param name="random">the source of randomness to use</param>
        public virtual void Init(
            int             size,
            int             certainty,
            SecureRandom    random)
        {
            if (!IsValidDsaStrength(size))
                throw new ArgumentException("size must be from 512 - 1024 and a multiple of 64", "size");

            this.use186_3 = false;
            this.L = size;
            this.N = GetDefaultN(size);
            this.certainty = certainty;
            this.random = random;
        }

        /// Initialise the generator for DSA 2
        /// <remarks>You must use this Init method if you need to generate parameters for DSA 2 keys</remarks>
        /// <param name="parameters">An instance of <c>DsaParameterGenerationParameters</c> used to configure this generator</param>
        public virtual void Init(DsaParameterGenerationParameters parameters)
        {
            // TODO Should we enforce the minimum 'certainty' values as per C.3 Table C.1?
            this.use186_3 = true;
            this.L = parameters.L;
            this.N = parameters.N;
            this.certainty = parameters.Certainty;
            this.random = parameters.Random;
            this.usageIndex = parameters.UsageIndex;

            if ((L < 1024 || L > 3072) || L % 1024 != 0)
                throw new ArgumentException("Values must be between 1024 and 3072 and a multiple of 1024", "L");
            if (L == 1024 && N != 160)
                throw new ArgumentException("N must be 160 for L = 1024");
            if (L == 2048 && (N != 224 && N != 256))
                throw new ArgumentException("N must be 224 or 256 for L = 2048");
            if (L == 3072 && N != 256)
                throw new ArgumentException("N must be 256 for L = 3072");

            if (digest.GetDigestSize() * 8 < N)
                throw new InvalidOperationException("Digest output size too small for value of N");
        }

        /// Generates a set of <c>DsaParameters</c>
        /// <remarks>Can take a while...</remarks>
        public virtual DsaParameters GenerateParameters()
        {
            return use186_3
                ?	GenerateParameters_FIPS186_3()
                :	GenerateParameters_FIPS186_2();
        }

        protected virtual DsaParameters GenerateParameters_FIPS186_2()
        {
            byte[] seed = new byte[20];
            byte[] part1 = new byte[20];
            byte[] part2 = new byte[20];
            byte[] u = new byte[20];
            int n = (L - 1) / 160;
            byte[] w = new byte[L / 8];

            if (!(digest is Sha1Digest))
                throw new InvalidOperationException("can only use SHA-1 for generating FIPS 186-2 parameters");

            for (;;)
            {
                random.NextBytes(seed);

                Hash(digest, seed, part1);
                Array.Copy(seed, 0, part2, 0, seed.Length);
                Inc(part2);
                Hash(digest, part2, part2);

                for (int i = 0; i != u.Length; i++)
                {
                    u[i] = (byte)(part1[i] ^ part2[i]);
                }

                u[0] |= (byte)0x80;
                u[19] |= (byte)0x01;

                BigInteger q = new BigInteger(1, u);

                if (!q.IsProbablePrime(certainty))
                    continue;

                byte[] offset = Arrays.Clone(seed);
                Inc(offset);

                for (int counter = 0; counter < 4096; ++counter)
                {
                    for (int k = 0; k < n; k++)
                    {
                        Inc(offset);
                        Hash(digest, offset, part1);
                        Array.Copy(part1, 0, w, w.Length - (k + 1) * part1.Length, part1.Length);
                    }

                    Inc(offset);
                    Hash(digest, offset, part1);
                    Array.Copy(part1, part1.Length - ((w.Length - (n) * part1.Length)), w, 0, w.Length - n * part1.Length);

                    w[0] |= (byte)0x80;

                    BigInteger x = new BigInteger(1, w);

                    BigInteger c = x.Mod(q.ShiftLeft(1));

                    BigInteger p = x.Subtract(c.Subtract(BigInteger.One));

                    if (p.BitLength != L)
                        continue;

                    if (p.IsProbablePrime(certainty))
                    {
                        BigInteger g = CalculateGenerator_FIPS186_2(p, q, random);

                        return new DsaParameters(p, q, g, new DsaValidationParameters(seed, counter));
                    }
                }
            }
        }

        protected virtual BigInteger CalculateGenerator_FIPS186_2(BigInteger p, BigInteger q, SecureRandom r)
        {
            BigInteger e = p.Subtract(BigInteger.One).Divide(q);
            BigInteger pSub2 = p.Subtract(BigInteger.Two);

            for (;;)
            {
                BigInteger h = BigIntegers.CreateRandomInRange(BigInteger.Two, pSub2, r);
                BigInteger g = h.ModPow(e, p);

                if (g.BitLength > 1)
                    return g;
            }
        }

        /**
         * generate suitable parameters for DSA, in line with
         * FIPS 186-3 A.1 Generation of the FFC Primes p and q.
         */
        protected virtual DsaParameters GenerateParameters_FIPS186_3()
        {
// A.1.1.2 Generation of the Probable Primes p and q Using an Approved Hash Function
            IDigest d = digest;
            int outlen = d.GetDigestSize() * 8;

// 1. Check that the (L, N) pair is in the list of acceptable (L, N pairs) (see Section 4.2). If
//    the pair is not in the list, then return INVALID.
            // Note: checked at initialisation

// 2. If (seedlen < N), then return INVALID.
            // FIXME This should be configurable (must be >= N)
            int seedlen = N;
            byte[] seed = new byte[seedlen / 8];

// 3. n = ceiling(L ⁄ outlen) – 1.
            int n = (L - 1) / outlen;

// 4. b = L – 1 – (n ∗ outlen).
            int b = (L - 1) % outlen;

            byte[] output = new byte[d.GetDigestSize()];
            for (;;)
            {
// 5. Get an arbitrary sequence of seedlen bits as the domain_parameter_seed.
                random.NextBytes(seed);

// 6. U = Hash (domain_parameter_seed) mod 2^(N–1).
                Hash(d, seed, output);
                BigInteger U = new BigInteger(1, output).Mod(BigInteger.One.ShiftLeft(N - 1));

// 7. q = 2^(N–1) + U + 1 – ( U mod 2).
                BigInteger q = U.SetBit(0).SetBit(N - 1);

// 8. Test whether or not q is prime as specified in Appendix C.3.
                // TODO Review C.3 for primality checking
                if (!q.IsProbablePrime(certainty))
                {
// 9. If q is not a prime, then go to step 5.
                    continue;
                }

// 10. offset = 1.
                // Note: 'offset' value managed incrementally
                byte[] offset = Arrays.Clone(seed);

// 11. For counter = 0 to (4L – 1) do
                int counterLimit = 4 * L;
                for (int counter = 0; counter < counterLimit; ++counter)
                {
// 11.1 For j = 0 to n do
//      Vj = Hash ((domain_parameter_seed + offset + j) mod 2^seedlen).
// 11.2 W = V0 + (V1 ∗ 2^outlen) + ... + (V^(n–1) ∗ 2^((n–1) ∗ outlen)) + ((Vn mod 2^b) ∗ 2^(n ∗ outlen)).
                    // TODO Assemble w as a byte array
                    BigInteger W = BigInteger.Zero;
                    for (int j = 0, exp = 0; j <= n; ++j, exp += outlen)
                    {
                        Inc(offset);
                        Hash(d, offset, output);

                        BigInteger Vj = new BigInteger(1, output);
                        if (j == n)
                        {
                            Vj = Vj.Mod(BigInteger.One.ShiftLeft(b));
                        }

                        W = W.Add(Vj.ShiftLeft(exp));
                    }

// 11.3 X = W + 2^(L–1). Comment: 0 ≤ W < 2L–1; hence, 2L–1 ≤ X < 2L.
                    BigInteger X = W.Add(BigInteger.One.ShiftLeft(L - 1));

// 11.4 c = X mod 2q.
                    BigInteger c = X.Mod(q.ShiftLeft(1));

// 11.5 p = X - (c - 1). Comment: p ≡ 1 (mod 2q).
                    BigInteger p = X.Subtract(c.Subtract(BigInteger.One));

                    // 11.6 If (p < 2^(L - 1)), then go to step 11.9
                    if (p.BitLength != L)
                        continue;

// 11.7 Test whether or not p is prime as specified in Appendix C.3.
                    // TODO Review C.3 for primality checking
                    if (p.IsProbablePrime(certainty))
                    {
// 11.8 If p is determined to be prime, then return VALID and the values of p, q and
//      (optionally) the values of domain_parameter_seed and counter.
                        // TODO Make configurable (8-bit unsigned)?

                        if (usageIndex >= 0)
                        {
                            BigInteger g = CalculateGenerator_FIPS186_3_Verifiable(d, p, q, seed, usageIndex);
                            if (g != null)
                                return new DsaParameters(p, q, g, new DsaValidationParameters(seed, counter, usageIndex));
                        }

                        {
                            BigInteger g = CalculateGenerator_FIPS186_3_Unverifiable(p, q, random);

                            return new DsaParameters(p, q, g, new DsaValidationParameters(seed, counter));
                        }
                    }

// 11.9 offset = offset + n + 1.      Comment: Increment offset; then, as part of
//                                    the loop in step 11, increment counter; if
//                                    counter < 4L, repeat steps 11.1 through 11.8.
                    // Note: 'offset' value already incremented in inner loop
                }
// 12. Go to step 5.
            }
        }

        protected virtual BigInteger CalculateGenerator_FIPS186_3_Unverifiable(BigInteger p, BigInteger q,
            SecureRandom r)
        {
            return CalculateGenerator_FIPS186_2(p, q, r);
        }

        protected virtual BigInteger CalculateGenerator_FIPS186_3_Verifiable(IDigest d, BigInteger p, BigInteger q,
            byte[] seed, int index)
        {
            // A.2.3 Verifiable Canonical Generation of the Generator g
            BigInteger e = p.Subtract(BigInteger.One).Divide(q);
            byte[] ggen = Hex.Decode("6767656E");

            // 7. U = domain_parameter_seed || "ggen" || index || count.
            byte[] U = new byte[seed.Length + ggen.Length + 1 + 2];
            Array.Copy(seed, 0, U, 0, seed.Length);
            Array.Copy(ggen, 0, U, seed.Length, ggen.Length);
            U[U.Length - 3] = (byte)index;

            byte[] w = new byte[d.GetDigestSize()];
            for (int count = 1; count < (1 << 16); ++count)
            {
                Inc(U);
                Hash(d, U, w);
                BigInteger W = new BigInteger(1, w);
                BigInteger g = W.ModPow(e, p);

                if (g.CompareTo(BigInteger.Two) >= 0)
                    return g;
            }

            return null;
        }

        private static bool IsValidDsaStrength(
            int strength)
        {
            return strength >= 512 && strength <= 1024 && strength % 64 == 0;
        }

        protected static void Hash(IDigest d, byte[] input, byte[] output)
        {
            d.BlockUpdate(input, 0, input.Length);
            d.DoFinal(output, 0);
        }

        private static int GetDefaultN(int L)
        {
            return L > 1024 ? 256 : 160;
        }

        protected static void Inc(byte[] buf)
        {
            for (int i = buf.Length - 1; i >= 0; --i)
            {
                byte b = (byte)(buf[i] + 1);
                buf[i] = b;

                if (b != 0)
                    break;
            }
        }
    }
}


text:
REG_FIDDLE(Surface_makeSurface, 256, 96, false, 0) {
void draw(SkCanvas* canvas) {
    sk_sp<SkSurface> big(SkSurface::MakeRasterN32Premul(64, 64));
    sk_sp<SkSurface> lil(big->makeSurface(SkImageInfo::MakeN32(32, 32, kPremul_SkAlphaType)));
    big->getCanvas()->clear(SK_ColorRED);
    lil->getCanvas()->clear(SK_ColorBLACK);
    SkPixmap pixmap;
    if (big->peekPixels(&pixmap)) {
        SkBitmap bigBits;
        bigBits.installPixels(pixmap);
        canvas->drawImage(bigBits.asImage(), 0, 0);
    }
    if (lil->peekPixels(&pixmap)) {
        SkBitmap lilBits;
        lilBits.installPixels(pixmap);
        canvas->drawImage(lilBits.asImage(), 64, 64);
    }
}
}  // END FIDDLE


text:
<?php

namespace Site\UtilityBundle\Tests\Unit\Validator\Constraints;

use Site\UtilityBundle\Validator\Constraints\Url;
use Site\UtilityBundle\Validator\Constraints\UrlValidator;

/**
 * Unit test for UrlValidator. This copies from Symfony's built in UrlValidator
 * test and changing valid/invalid inputs
 *
 * @author  Yan Barreta
*/
class UrlValidatorTest extends \PHPUnit_Framework_TestCase
{
    protected $context;
    protected $validator;

    protected function setUp()
    {
        $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $this->validator = new UrlValidator();
        $this->validator->initialize($this->context);
    }

    protected function tearDown()
    {
        $this->context = null;
        $this->validator = null;
    }

    public function testNullIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate(null, new Url());
    }

    public function testEmptyStringIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate('', new Url());
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
     */
    public function testExpectsStringCompatibleType()
    {
        $this->validator->validate(new \stdClass(), new Url());
    }

    /**
     * @dataProvider getValidUrls
     */
    public function testValidUrls($url)
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate($url, new Url());
    }

    public function getValidUrls()
    {
        return array(
            array('google.com'),
            array('http://a.pl'),
            array('http://www.google.com'),
            array('http://www.google.museum'),
            array('https://google.com/'),
            array('https://google.com:80/'),
            array('http://www.example.coop/'),
            array('http://www.test-example.com/'),
            array('http://www.symfony.com/'),
            array('http://symfony.fake/blog/'),
            array('http://symfony.com/?'),
            array('http://symfony.com/search?type=&q=url+validator'),
            array('http://symfony.com/#'),
            array('http://symfony.com/#?'),
            array('http://www.symfony.com/doc/current/book/validation.html#supported-constraints'),
            array('http://very.long.domain.name.com/'),
            array('admin.test.com'),
            array('http://127.0.0.1/'),
            array('http://127.0.0.1:80/'),
            array('http://[::1]/'),
            array('http://[::1]:80/'),
            array('http://[1:2:3::4:5:6:7]/'),
            array('http://sãopaulo.com/'),
            array('http://sãopaulo.com.br/'),
            array('http://пример.испытание/'),
            array('http://مثال.إختبار/'),
            array('مثال.إختبار/'),
            array('http://例子.测试/'),
            array('http://例子.測試/'),
            array('http://例え.テスト/'),
            array('http://مثال.آزمایشی/'),
            array('http://실례.테스트/'),
            array('http://العربية.idn.icann.org/'),
            array('http://☎.com/'),
        );
    }

    /**
     * @dataProvider getInvalidUrls
     */
    public function testInvalidUrls($url)
    {
        $constraint = new Url(array(
            'message' => 'myMessage'
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ value }}' => $url,
            ));

        $this->validator->validate($url, $constraint);
    }

    public function getInvalidUrls()
    {
        return array(
            array('://google.com'),
            array('http ://google.com'),
            array('http:/google.com'),
            array('http://goog_le.com'),
            array('http://google.com::aa'),
            array('http://google.com:aa'),
            array('http://symfony.com?'),
            array('http://symfony.com#'),
            array('ftp://google.fr'),
            array('faked://google.fr'),
            array('http://127.0.0.1:aa/'),
            array('ftp://[::1]/'),
            array('http://[::1'),
        );
    }

    /**
     * @dataProvider getValidCustomUrls
     */
    public function testCustomProtocolIsValid($url)
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $constraint = new Url(array(
            'protocols' => array('ftp', 'file', 'git')
        ));

        $this->validator->validate($url, $constraint);
    }

    public function getValidCustomUrls()
    {
        return array(
            array('ftp://google.com'),
            array('file://127.0.0.1'),
            array('git://[::1]/'),
        );
    }
}


text:
@interface OpenAppEventViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic) NSMutableDictionary *params;
@property (nonatomic) NSMutableArray *paramList;

@end

@implementation OpenAppEventViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initValues];
    [self addDelegates];
    [self removeExtraRows];
    [self loadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)initValues {
    self.params = [NSMutableDictionary new];
}

- (void)addDelegates {
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
}

- (void)removeExtraRows {
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
}

- (void)loadData {
    self.paramList = [NSMutableArray new];
    for (NSString *key in self.params.allKeys) {
        [self.paramList addObject:key];
    }
    [self sortParams:self.paramList];
    [self.tableView reloadData];
}

- (void)sortParams:(NSMutableArray *)params {
    [params sortUsingComparator:^NSComparisonResult(NSString *key1, NSString *key2){
        return [key1 compare:key2];
    }];
}

- (void)addParam {
    // Add param
    [self.params setObject:self.valueTextField.text forKey:self.keyTextField.text];
    // Reload table
    [self loadData];
}

- (IBAction)addParam:(id)sender {
    // Hide keyboard
    [self hideKeyboard];
    // Validate fields
    if ([self.keyTextField.text isEqualToString:@""] || [self.valueTextField.text isEqualToString:@""]) {
        [self showAlertWithMessage:@"Please complete all param fields."];
    } else {
        [self addParam];
        [self clearFields];
    }
}

- (IBAction)clearFields:(id)sender {
    [self clearFields];
}

- (void)clearFields {
    self.keyTextField.text = @"";
    self.valueTextField.text = @"";
}

- (void)hideKeyboard {
    [self.urlTextField resignFirstResponder];
    [self.refererTextField resignFirstResponder];
    [self.keyTextField resignFirstResponder];
    [self.valueTextField resignFirstResponder];
}

- (IBAction)trackEvent:(id)sender {
    // Hide keyboard
    [self hideKeyboard];

    [self trackEvent];
    [self showSuccessAlert];
}

- (void)trackEvent {
    CLBOpenAppEvent *event = [CLBOpenAppEvent openAppEvent];
    event.url = self.urlTextField.text;
    event.referer = self.refererTextField.text;
    if (self.params.count > 0)
        [event setParams:self.params];

    [[CLBApp shared] logOpenAppEvent:event];
}

#pragma mark - TableView

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(nonnull UIView *)view forSection:(NSInteger)section {
    UITableViewHeaderFooterView *v = (UITableViewHeaderFooterView *)view;
    v.backgroundView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    v.textLabel.font = [UIFont systemFontOfSize:UIFont.systemFontSize];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.paramList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ParamCell *cell = [tableView dequeueReusableCellWithIdentifier:@"paramCell" forIndexPath:indexPath];
    cell.paramKey = [self.paramList objectAtIndex:indexPath.row];
    cell.paramValue = [self.params objectForKey:cell.paramKey];
    [cell loadParamDescription];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ParamCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    self.keyTextField.text = cell.paramKey;
    self.valueTextField.text = cell.paramValue;
}

#pragma mark - Alert

- (void)showAlertWithMessage:(NSString *)message {
    // Create alert
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Error" message:message preferredStyle:UIAlertControllerStyleAlert];
    // Create OK action
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:okAction];
    // Show alert on viewcontroller
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)showSuccessAlert {
    // Create alert
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"Event sent." preferredStyle:UIAlertControllerStyleAlert];
    // Create OK action
    __weak OpenAppEventViewController *weakSelf = self;
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }];
    [alert addAction:okAction];
    // Show alert on viewcontroller
    [self presentViewController:alert animated:YES completion:nil];
}

@end


text:
package org.apache.hadoop.dfs;

import org.apache.hadoop.io.*;
import org.apache.hadoop.fs.Path;

import java.io.*;

/******************************************************
 * DFSFileInfo tracks info about remote files, including
 * name, size, etc.
 *
 * @author Mike Cafarella
 ******************************************************/
class DFSFileInfo implements Writable {
    static {                                      // register a ctor
      WritableFactories.setFactory
        (DFSFileInfo.class,
         new WritableFactory() {
           public Writable newInstance() { return new DFSFileInfo(); }
         });
    }

    UTF8 path;
    long len;
    long contentsLen;
    boolean isDir;
    short blockReplication;

    /**
     */
    public DFSFileInfo() {
    }

    /**
     * Create DFSFileInfo by file INode
     */
    public DFSFileInfo( FSDirectory.INode node ) {
        this.path = new UTF8(node.computeName());
        this.isDir = node.isDir();
        if( isDir ) {
          this.len = 0;
          this.contentsLen = node.computeContentsLength();
        } else
          this.len = this.contentsLen = node.computeFileLength();
        this.blockReplication = node.getReplication();
    }

    /**
     */
    public String getPath() {
        return path.toString();
    }

    /**
     */
    public String getName() {
        return new Path(path.toString()).getName();
    }

    /**
     */
    public String getParent() {
      return new Path(path.toString()).getParent().toString();
    }

    /**
     */
    public long getLen() {
        return len;
    }

    /**
     */
    public long getContentsLen() {
        return contentsLen;
    }

    /**
     */
    public boolean isDir() {
        return isDir;
    }

    /**
     */
    public short getReplication() {
      return this.blockReplication;
    }

    //////////////////////////////////////////////////
    // Writable
    //////////////////////////////////////////////////
    public void write(DataOutput out) throws IOException {
        path.write(out);
        out.writeLong(len);
        out.writeLong(contentsLen);
        out.writeBoolean(isDir);
        out.writeShort(blockReplication);
    }

    public void readFields(DataInput in) throws IOException {
        this.path = new UTF8();
        this.path.readFields(in);
        this.len = in.readLong();
        this.contentsLen = in.readLong();
        this.isDir = in.readBoolean();
        this.blockReplication = in.readShort();
    }
}


text:
declare var THREE: any;
declare var createGame: any;
declare var perlin: any;
declare var walk: any;
declare var player: any;
declare var createSky: any;
declare var howler: any;
declare var Howl: any;
declare module Kube3d {
    var pluginName: string;
    var log: Logging.Logger;
    var templatePath: string;
    var havePointerLock: boolean;
    var settings: {
        destroyPods: boolean;
        music: boolean;
        blacklist: any;
    };
    var HalfPI: number;
    var QuarterPI: number;
    function rgbToHex(r: any, g: any, b: any): string;
    function randomGrey(): string;
    function webglAvailable(): boolean;
    function getParticles(THREE: any, size: any, color: any, amount: any): any;
    function placeObject(cellX: any, cellY: any, isFloor?: boolean): number[];
    function maybe(): boolean;
    function lessMaybe(): boolean;
    function flatTerrain(options?: any): (position: any, width: any) => Int8Array;
    function cityTerrain(options?: any): (position: any, width: any) => Int8Array;
    function perlinTerrain(options?: any): (position: any, width: any) => Int8Array;
    function getVolume(player: any, entity: any): number;
    function playSound(sound: any, player: any, entity: any): void;
    function getY(game: any, x: any, z: any): number;
}


text:
#include <aws/snowball/model/DescribeJobRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Snowball::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

DescribeJobRequest::DescribeJobRequest() :
    m_jobIdHasBeenSet(false)
{
}

Aws::String DescribeJobRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_jobIdHasBeenSet)
  {
   payload.WithString("JobId", m_jobId);

  }

  return payload.WriteReadable();
}

Aws::Http::HeaderValueCollection DescribeJobRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AWSIESnowballJobManagementService.DescribeJob"));
  return headers;

}


text:
package org.keyboardplaying.roman;

import org.keyboardplaying.util.BiHashMap;
import org.keyboardplaying.util.BiMap;

/**
 * Converts an integer from and to roman numerals.
 *
 * @author Cyrille Chopelet (http://keyboardplaying.org)
 */
public class RomanConverter {

    private static final int MAX_VALUE = 3777;
    private static final int MAX_10_POWER = 3;
    private static final int TEN = 10;
    private static final int FIVE = 5;

    private static final BiMap<Character, Integer> CORRESPONDANCE;

    static {
        CORRESPONDANCE = new BiHashMap<>();
        CORRESPONDANCE.put(Character.valueOf('I'), Integer.valueOf(1));
        CORRESPONDANCE.put(Character.valueOf('V'), Integer.valueOf(5));
        CORRESPONDANCE.put(Character.valueOf('X'), Integer.valueOf(10));
        CORRESPONDANCE.put(Character.valueOf('L'), Integer.valueOf(50));
        CORRESPONDANCE.put(Character.valueOf('C'), Integer.valueOf(100));
        CORRESPONDANCE.put(Character.valueOf('D'), Integer.valueOf(500));
        CORRESPONDANCE.put(Character.valueOf('M'), Integer.valueOf(1000));
    }

    /**
     * Parses a Roman numeral to an integer.
     * <p/>
     * Due to the numerous variants of Roman numerals writing, no constraint is checked. At the current time, this
     * algorithm is a dumb application of conversion rules.
     *
     * @param roman
     *            the Roman numeral
     * @return the integer version of the number
     */
    public int from(String roman) {
        int result = 0;

        if (roman != null) {
            String roman2 = roman.trim().toUpperCase();
            int length = roman2.length();
            int i = 0;
            while (i < length) {
                char current = roman2.charAt(i);
                int value = getIntValue(current);
                int group = 0;
                do {
                    group += value;
                    i++;
                } while (i < length && roman2.charAt(i) == current);

                if (i == length || getIntValue(roman2.charAt(i)) < value) {
                    result += group;
                } else {
                    result -= group;
                }
            }
        }

        return result;
    }

    private int getIntValue(char roman) {
        return CORRESPONDANCE.get(Character.valueOf(roman)).intValue();
    }

    /**
     * Parses an integer as a Roman numeral.
     *
     * @param value
     *            the integer
     * @return the Roman numeral
     */
    public String to(int value) {
        if (value < 0) {
            throw new IllegalArgumentException("Only positive values can be written as Roman numerals.");
        } else if (value > MAX_VALUE) {
            throw new IllegalArgumentException("This number is too large to be written as a Roman numeral.");
        }

        return appendRoman(new StringBuilder(), MAX_10_POWER, value).toString();
    }

    private StringBuilder appendRoman(StringBuilder sb, int power, int value) {
        if (power >= 0) {
            int rank = (int) Math.pow(TEN, power);
            int unit = value / rank;
            int remainder = value - unit * rank;

            Character unitChar = getChar(rank);
            if (unit == FIVE - 1 || unit == TEN - 1) {
                // One rank below: substract one unit to upper char
                sb.append(unitChar).append(getChar(++unit * rank));

            } else {

                // Greater than five, use the mid-dozen char
                if (unit >= FIVE) {
                    sb.append(getChar(FIVE * rank));
                    unit -= FIVE;
                }

                // Add single units
                while (unit > 0) {
                    sb.append(unitChar);
                    unit--;
                }
            }

            appendRoman(sb, power - 1, remainder);
        }
        return sb;
    }

    private Character getChar(int value) {
        return CORRESPONDANCE.getKey(Integer.valueOf(value));
    }
}


text:
/**
 * Created at 3:26:14 AM Jan 11, 2011
 */
package org.jbox2d.pooling;

import java.util.HashMap;

import org.jbox2d.collision.AABB;
import org.jbox2d.collision.Collision;
import org.jbox2d.collision.Distance;
import org.jbox2d.collision.TimeOfImpact;
import org.jbox2d.common.Mat22;
import org.jbox2d.common.Vec2;
import org.jbox2d.common.Vec3;
import org.jbox2d.dynamics.contacts.CircleContact;
import org.jbox2d.dynamics.contacts.Contact;
import org.jbox2d.dynamics.contacts.PolygonAndCircleContact;
import org.jbox2d.dynamics.contacts.PolygonContact;

/**
 * Provides object pooling for all objects used in the engine. Objects retrieved from here should
 * only be used temporarily, and then pushed back (with the exception of arrays).
 *
 * @author Daniel Murphy
 */
public class WorldPool implements IWorldPool {
  private final OrderedStackVec2 vecs;

  private final OrderedStackVec3 vec3s;
  private final OrderedStackMat22 mats;
  private final OrderedStackAABB aabbs;

  private final HashMap<Integer, float[]> afloats = new HashMap<Integer, float[]>();
  private final HashMap<Integer, int[]> aints = new HashMap<Integer, int[]>();
  private final HashMap<Integer, Vec2[]> avecs = new HashMap<Integer, Vec2[]>();

  private final MutableStack<Contact, PolygonContact> pcstack = new PolygonContactStack(this);

  private final MutableStack<Contact, CircleContact> ccstack = new CircleContactStack(this);

  private final MutableStack<Contact, PolygonAndCircleContact> cpstack = new PolygonAndCircleContactStack(this);

  private final Collision collision;
  private final TimeOfImpact toi;
  private final Distance dist;

  public WorldPool(int argSize, int argContainerSize) {
    vecs = new OrderedStackVec2(argSize, argContainerSize);
    vec3s = new OrderedStackVec3(argSize, argContainerSize);
    mats = new OrderedStackMat22(argSize, argContainerSize);
    aabbs = new OrderedStackAABB(argSize, argContainerSize);

    dist = new Distance();
    collision = new Collision(this);
    toi = new TimeOfImpact(this);
  }

  /*
   * (non-Javadoc)
   *
   * @see org.jbox2d.pooling.IWorldPool#getPolyContactStack()
   */
  @Override
  public final IDynamicStack<Contact> getPolyContactStack() {
    return pcstack;
  }

  /*
   * (non-Javadoc)
   *
   * @see org.jbox2d.pooling.IWorldPool#getCircleContactStack()
   */
  @Override
  public final IDynamicStack<Contact> getCircleContactStack() {
    return ccstack;
  }

  /*
   * (non-Javadoc)
   *
   * @see org.jbox2d.pooling.IWorldPool#getPolyCircleContactStack()
   */
  @Override
  public final IDynamicStack<Contact> getPolyCircleContactStack() {
    return cpstack;
  }

  /*
   * (non-Javadoc)
   *
   * @see org.jbox2d.pooling.IWorldPool#getVec2Stack()
   */
  @Override
  public final IOrderedStack<Vec2> getVec2Stack() {
    return vecs;
  }

  /*
   * (non-Javadoc)
   *
   * @see org.jbox2d.pooling.IWorldPool#popVec2()
   */
  @Override
  public final Vec2 popVec2() {
    return vecs.pop();
  }

  /*
   * (non-Javadoc)
   *
   * @see org.jbox2d.pooling.IWorldPool#popVec2(int)
   */
  @Override
  public final Vec2[] popVec2(int argNum) {
    return vecs.pop(argNum);
  }

  /*
   * (non-Javadoc)
   *
   * @see org.jbox2d.pooling.IWorldPool#pushVec2(int)
   */
  @Override
  public final void pushVec2(int argNum) {
    vecs.push(argNum);
  }

  /*
   * (non-Javadoc)
   *
   * @see org.jbox2d.pooling.IWorldPool#getVec3Stack()
   */
  @Override
  public final IOrderedStack<Vec3> getVec3Stack() {
    return vec3s;
  }

  /*
   * (non-Javadoc)
   *
   * @see org.jbox2d.pooling.IWorldPool#popVec3()
   */
  @Override
  public final Vec3 popVec3() {
    return vec3s.pop();
  }

  /*
   * (non-Javadoc)
   *
   * @see org.jbox2d.pooling.IWorldPool#popVec3(int)
   */
  @Override
  public final Vec3[] popVec3(int argNum) {
    return vec3s.pop(argNum);
  }

  /*
   * (non-Javadoc)
   *
   * @see org.jbox2d.pooling.IWorldPool#pushVec3(int)
   */
  @Override
  public final void pushVec3(int argNum) {
    vec3s.push(argNum);
  }

  /*
   * (non-Javadoc)
   *
   * @see org.jbox2d.pooling.IWorldPool#getMat22Stack()
   */
  @Override
  public final IOrderedStack<Mat22> getMat22Stack() {
    return mats;
  }

  /*
   * (non-Javadoc)
   *
   * @see org.jbox2d.pooling.IWorldPool#popMat22()
   */
  @Override
  public final Mat22 popMat22() {
    return mats.pop();
  }

  /*
   * (non-Javadoc)
   *
   * @see org.jbox2d.pooling.IWorldPool#popMat22(int)
   */
  @Override
  public final Mat22[] popMat22(int argNum) {
    return mats.pop(argNum);
  }

  /*
   * (non-Javadoc)
   *
   * @see org.jbox2d.pooling.IWorldPool#pushMat22(int)
   */
  @Override
  public final void pushMat22(int argNum) {
    mats.push(argNum);
  }

  /*
   * (non-Javadoc)
   *
   * @see org.jbox2d.pooling.IWorldPool#getAABBStack()
   */
  @Override
  public final IOrderedStack<AABB> getAABBStack() {
    return aabbs;
  }

  /*
   * (non-Javadoc)
   *
   * @see org.jbox2d.pooling.IWorldPool#popAABB()
   */
  @Override
  public final AABB popAABB() {
    return aabbs.pop();
  }

  /*
   * (non-Javadoc)
   *
   * @see org.jbox2d.pooling.IWorldPool#popAABB(int)
   */
  @Override
  public final AABB[] popAABB(int argNum) {
    return aabbs.pop(argNum);
  }

  /*
   * (non-Javadoc)
   *
   * @see org.jbox2d.pooling.IWorldPool#pushAABB(int)
   */
  @Override
  public final void pushAABB(int argNum) {
    aabbs.push(argNum);
  }

  /*
   * (non-Javadoc)
   *
   * @see org.jbox2d.pooling.IWorldPool#getCollision()
   */
  @Override
  public final Collision getCollision() {
    return collision;
  }

  /*
   * (non-Javadoc)
   *
   * @see org.jbox2d.pooling.IWorldPool#getTimeOfImpact()
   */
  @Override
  public final TimeOfImpact getTimeOfImpact() {
    return toi;
  }

  /*
   * (non-Javadoc)
   *
   * @see org.jbox2d.pooling.IWorldPool#getDistance()
   */
  @Override
  public final Distance getDistance() {
    return dist;
  }

  /*
   * (non-Javadoc)
   *
   * @see org.jbox2d.pooling.IWorldPool#getFloatArray(int)
   */
  @Override
  public final float[] getFloatArray(int argLength) {
    if (!afloats.containsKey(argLength)) {
      afloats.put(argLength, new float[argLength]);
    }

    assert (afloats.get(argLength).length == argLength) : "Array not built with correct length";
    return afloats.get(argLength);
  }

  /*
   * (non-Javadoc)
   *
   * @see org.jbox2d.pooling.IWorldPool#getIntArray(int)
   */
  @Override
  public final int[] getIntArray(int argLength) {
    if (!aints.containsKey(argLength)) {
      aints.put(argLength, new int[argLength]);
    }

    assert (aints.get(argLength).length == argLength) : "Array not built with correct length";
    return aints.get(argLength);
  }

  /*
   * (non-Javadoc)
   *
   * @see org.jbox2d.pooling.IWorldPool#getVec2Array(int)
   */
  @Override
  public final Vec2[] getVec2Array(int argLength) {
    if (!avecs.containsKey(argLength)) {
      Vec2[] ray = new Vec2[argLength];
      for (int i = 0; i < argLength; i++) {
        ray[i] = new Vec2();
      }
      avecs.put(argLength, ray);
    }

    assert (avecs.get(argLength).length == argLength) : "Array not built with correct length";
    return avecs.get(argLength);
  }
}


text:
@(title: String)(content: Html)
<html>
    <head>
        <title>@title</title>
        <link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/main.css")">
		<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
		<link rel="stylesheet" href="@routes.Assets.at("stylesheets/demos/jquery-ui-1.10.3.custom.min.css")" />
        <link rel="shortcut icon" type="image/png" href="@routes.Assets.at("images/favicon.png")">
        <link rel="stylesheet" href="@routes.Assets.at("stylesheets/slick.grid.css")">
        <link rel="stylesheet" href="@routes.Assets.at("stylesheets/slick.columnpicker.css")">

        <script src="@routes.Assets.at("javascripts/jquery-1.10.2.min.js")" type="text/javascript"></script>
        <script src="@routes.Assets.at("javascripts/jquery-ui-1.10.3.custom.min.js")" type="text/javascript"></script>
        <script src="@routes.Assets.at("javascripts/jquery.jsPlumb-1.5.2-min.js")" type="text/javascript"></script>
    </head>
    <body>
        @content
    </body>
</html>


text:
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.contrib.sessions.models import Session as DjangoSession
from django.db import models
from jsonfield import JSONField

from openslides.mediafiles.models import Mediafile
from openslides.utils.models import RESTModelMixin
from openslides.utils.projector import ProjectorElement

from .access_permissions import (
    ChatMessageAccessPermissions,
    ConfigAccessPermissions,
    CustomSlideAccessPermissions,
    ProjectorAccessPermissions,
    TagAccessPermissions,
)
from .exceptions import ProjectorException

class Projector(RESTModelMixin, models.Model):
    """
    Model for all projectors. At the moment we support only one projector,
    the default projector (pk=1).

    The config field contains a dictionary which uses UUIDs as keys. Every
    element must have at least the property "name". The property "stable"
    is to set whether this element should disappear on prune or clear
    requests.

    Example:

    {
        "881d875cf01741718ca926279ac9c99c": {
            "name": "core/customslide",
            "id": 1
        },
        "191c0878cdc04abfbd64f3177a21891a": {
            "name": "core/countdown",
            "stable": true,
            "status": "stop",
            "countdown_time": 20,
            "visable": true,
            "default": 42
        },
        "db670aa8d3ed4aabb348e752c75aeaaf": {
            "name": "core/clock",
            "stable": true
        }
    }

    If the config field is empty or invalid the projector shows a default
    slide.

    There are two additional fields to control the behavior of the projector
    view itself: scale and scroll.

    The projector can be controlled using the REST API with POST requests
    on e. g. the URL /rest/core/projector/1/activate_elements/.
    """
    access_permissions = ProjectorAccessPermissions()

    config = JSONField()

    scale = models.IntegerField(default=0)

    scroll = models.IntegerField(default=0)

    class Meta:
        """
        Contains general permissions that can not be placed in a specific app.
        """
        default_permissions = ()
        permissions = (
            ('can_see_projector', 'Can see the projector'),
            ('can_manage_projector', 'Can manage the projector'),
            ('can_see_frontpage', 'Can see the front page'),)

    @property
    def elements(self):
        """
        Retrieve all projector elements given in the config field. For
        every element the method check_and_update_data() is called and its
        result is also used.
        """
        # Get all elements from all apps.
        elements = {}
        for element in ProjectorElement.get_all():
            elements[element.name] = element

        # Parse result
        result = {}
        for key, value in self.config.items():
            # Use a copy here not to change the origin value in the config field.
            result[key] = value.copy()
            result[key]['uuid'] = key
            element = elements.get(value['name'])
            if element is None:
                result[key]['error'] = 'Projector element does not exist.'
            else:
                try:
                    result[key].update(element.check_and_update_data(
                        projector_object=self,
                        config_entry=value))
                except ProjectorException as e:
                    result[key]['error'] = str(e)
        return result

    @classmethod
    def get_all_requirements(cls):
        """
        Generator which returns all ProjectorRequirement instances of all
        active projector elements.
        """
        # Get all elements from all apps.
        elements = {}
        for element in ProjectorElement.get_all():
            elements[element.name] = element

        # Generator
        for projector in cls.objects.all():
            for key, value in projector.config.items():
                element = elements.get(value['name'])
                if element is not None:
                    for requirement in element.get_requirements(value):
                        yield requirement

class CustomSlide(RESTModelMixin, models.Model):
    """
    Model for slides with custom content.
    """
    access_permissions = CustomSlideAccessPermissions()

    title = models.CharField(
        max_length=256)
    text = models.TextField(
        blank=True)
    weight = models.IntegerField(
        default=0)
    attachments = models.ManyToManyField(
        Mediafile,
        blank=True)

    class Meta:
        default_permissions = ()
        ordering = ('weight', 'title', )

    def __str__(self):
        return self.title

    @property
    def agenda_item(self):
        """
        Returns the related agenda item.
        """
        # TODO: Move the agenda app in the core app to fix circular dependencies
        from openslides.agenda.models import Item
        content_type = ContentType.objects.get_for_model(self)
        return Item.objects.get(object_id=self.pk, content_type=content_type)

    @property
    def agenda_item_id(self):
        """
        Returns the id of the agenda item object related to this object.
        """
        return self.agenda_item.pk

    def get_agenda_title(self):
        return self.title

    def get_agenda_list_view_title(self):
        return self.title

    def get_search_index_string(self):
        """
        Returns a string that can be indexed for the search.
        """
        return " ".join((
            self.title,
            self.text))

class Tag(RESTModelMixin, models.Model):
    """
    Model for tags. This tags can be used for other models like agenda items,
    motions or assignments.
    """
    access_permissions = TagAccessPermissions()

    name = models.CharField(
        max_length=255,
        unique=True)

    class Meta:
        ordering = ('name',)
        default_permissions = ()
        permissions = (
            ('can_manage_tags', 'Can manage tags'),)

    def __str__(self):
        return self.name

class ConfigStore(RESTModelMixin, models.Model):
    """
    A model class to store all config variables in the database.
    """
    access_permissions = ConfigAccessPermissions()

    key = models.CharField(max_length=255, unique=True, db_index=True)
    """A string, the key of the config variable."""

    value = JSONField()
    """The value of the config variable. """

    class Meta:
        default_permissions = ()
        permissions = (
            ('can_manage_config', 'Can manage configuration'),)

    @classmethod
    def get_collection_string(cls):
        return 'core/config'

    def get_rest_pk(self):
        """
        Returns the primary key used in the REST API.
        """
        return self.key

class ChatMessage(RESTModelMixin, models.Model):
    """
    Model for chat messages.

    At the moment we only have one global chat room for managers.
    """
    access_permissions = ChatMessageAccessPermissions()

    message = models.TextField()

    timestamp = models.DateTimeField(auto_now_add=True)

    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE)

    class Meta:
        default_permissions = ()
        permissions = (
            ('can_use_chat', 'Can use the chat'),)

    def __str__(self):
        return 'Message {}'.format(self.timestamp)

class Session(DjangoSession):
    """
    Model like the Django db session, which saves the user as ForeignKey instead
    of an encoded value.
    """
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        null=True)

    @classmethod
    def get_session_store_class(cls):
        from .session_backend import SessionStore
        return SessionStore