text:
package com.weiqi.dota2.dota2apiwrapper;

public interface PlayerSteamSummary {
    public long getSteamId();

    public String getPersonaName();

    public String getProfileUrl();

    public PersonaState getPersonaState();

    public long getLastLogoff();
}

redpajama_set_name: RedPajamaGithub


text:
using System;

namespace Crosschat.Server.Domain.Seedwork.Utils
{
    internal static class IdentityGenerator
    {
        /// <summary>
        /// This algorithm generates secuential GUIDs across system boundaries, ideal for databases
        /// </summary>
        /// <returns></returns>
        public static Guid NewSequentialGuid()
        {
            byte[] uid = Guid.NewGuid().ToByteArray();
            byte[] binDate = BitConverter.GetBytes(DateTime.UtcNow.Ticks);

            var secuentialGuid = new byte[uid.Length];

            secuentialGuid[0] = uid[0];
            secuentialGuid[1] = uid[1];
            secuentialGuid[2] = uid[2];
            secuentialGuid[3] = uid[3];
            secuentialGuid[4] = uid[4];
            secuentialGuid[5] = uid[5];
            secuentialGuid[6] = uid[6];
            // set the first part of the 8th byte to '1100' so
            // later we'll be able to validate it was generated by us

            secuentialGuid[7] = (byte)(0xc0 | (0xf & uid[7]));

            // the last 8 bytes are sequential,
            // it minimizes index fragmentation
            // to a degree as long as there are not a large
            // number of Secuential-Guids generated per millisecond

            secuentialGuid[9] = binDate[0];
            secuentialGuid[8] = binDate[1];
            secuentialGuid[15] = binDate[2];
            secuentialGuid[14] = binDate[3];
            secuentialGuid[13] = binDate[4];
            secuentialGuid[12] = binDate[5];
            secuentialGuid[11] = binDate[6];
            secuentialGuid[10] = binDate[7];

            return new Guid(secuentialGuid);
        }
    }
}


text:
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ash/crosapi/browser_data_migrator_util.h"

#include <sys/stat.h>

#include <map>

#include "base/containers/contains.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/logging.h"
#include "base/strings/stringprintf.h"
#include "base/system/sys_info.h"
#include "base/test/metrics/histogram_tester.h"
#include "chrome/browser/ash/crosapi/fake_migration_progress_tracker.h"
#include "components/sync/base/model_type.h"
#include "components/sync/model/blocking_model_type_store_impl.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/leveldatabase/env_chromium.h"
#include "third_party/leveldatabase/src/include/leveldb/write_batch.h"

namespace ash::browser_data_migrator_util {

namespace {

constexpr char kDownloadsPath[] = "Downloads";
constexpr char kSharedProtoDBPath[] = "shared_proto_db";
constexpr char kBookmarksPath[] = "Bookmarks";
constexpr char kCookiesPath[] = "Cookies";
constexpr char kCachePath[] = "Cache";
constexpr char kCodeCachePath[] = "Code Cache";
constexpr char kCodeCacheUMAName[] = "CodeCache";
constexpr char kTextFileContent[] = "Hello, World!";
constexpr int kTextFileSize = sizeof(kTextFileContent);
constexpr char kMoveExtensionId[] = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

constexpr syncer::ModelType kAshSyncDataType =
    browser_data_migrator_util::kAshOnlySyncDataTypes[0];
constexpr syncer::ModelType kLacrosSyncDataType = syncer::ModelType::WEB_APPS;
static_assert(!base::Contains(browser_data_migrator_util::kAshOnlySyncDataTypes,
                              kLacrosSyncDataType));

struct TargetItemComparator {
  bool operator()(const TargetItem& t1, const TargetItem& t2) const {
    return t1.path < t2.path;
  }
};

// Checks if the file paths point to the same inode.
bool IsSameFile(const base::FilePath& file1, const base::FilePath& file2) {
  struct stat st_1;
  if (stat(file1.value().c_str(), &st_1) == -1) {
    PLOG(ERROR) << "stat failed";
    return false;
  }

  struct stat st_2;
  if (stat(file2.value().c_str(), &st_2) == -1) {
    PLOG(ERROR) << "stat failed";
    return false;
  }

  // Make sure that they are indeed the same file.
  return (st_1.st_ino == st_2.st_ino);
}

std::set<std::string> CollectDictKeys(const base::Value::Dict* dict) {
  std::set<std::string> result;
  if (dict) {
    for (const auto entry : *dict) {
      result.insert(entry.first);
    }
  }
  return result;
}

// Prepare LocalStorage-like LevelDB.
void SetUpLocalStorage(const base::FilePath& path,
                       std::unique_ptr<leveldb::DB>& db) {
  using std::string_literals::operator""s;

  leveldb_env::Options options;
  options.create_if_missing = true;
  leveldb::Status status = leveldb_env::OpenDB(options, path.value(), &db);
  ASSERT_TRUE(status.ok());

  leveldb::WriteBatch batch;
  batch.Put("VERSION", "1");

  std::string keep_extension_id =
      browser_data_migrator_util::kExtensionsAshOnly[0];
  batch.Put("META:chrome-extension://" + keep_extension_id, "meta");
  batch.Put("_chrome-extension://" + keep_extension_id + "\x00key1"s, "value1");

  std::string both_extension_id =
      browser_data_migrator_util::kExtensionsBothChromes[0];
  batch.Put("META:chrome-extension://" + both_extension_id, "meta");
  batch.Put("_chrome-extension://" + both_extension_id + "\x00key1"s, "value1");

  std::string move_extension_id = kMoveExtensionId;
  batch.Put("META:chrome-extension://" + move_extension_id, "meta");
  batch.Put("_chrome-extension://" + move_extension_id + "\x00key1"s, "value1");

  leveldb::WriteOptions write_options;
  write_options.sync = true;
  status = db->Write(write_options, &batch);
  ASSERT_TRUE(status.ok());
}

// Prepare StateStore-like LevelDB.
void SetUpStateStore(const base::FilePath& path,
                     std::unique_ptr<leveldb::DB>& db) {
  leveldb_env::Options options;
  options.create_if_missing = true;
  leveldb::Status status = leveldb_env::OpenDB(options, path.value(), &db);
  ASSERT_TRUE(status.ok());

  leveldb::WriteBatch batch;
  std::string keep_extension_id =
      browser_data_migrator_util::kExtensionsAshOnly[0];
  std::string both_extension_id =
      browser_data_migrator_util::kExtensionsBothChromes[0];
  batch.Put(keep_extension_id + ".key1", "value1");
  batch.Put(keep_extension_id + ".key2", "value2");
  batch.Put(both_extension_id + ".key1", "value1");
  batch.Put(both_extension_id + ".key2", "value2");
  batch.Put(std::string(kMoveExtensionId) + ".key1", "value1");
  batch.Put(std::string(kMoveExtensionId) + ".key2", "value2");

  leveldb::WriteOptions write_options;
  write_options.sync = true;
  status = db->Write(write_options, &batch);
  ASSERT_TRUE(status.ok());
}

// Prepare Sync Data LevelDB.
void SetUpSyncData(const base::FilePath& path,
                   std::unique_ptr<leveldb::DB>& db) {
  leveldb_env::Options options;
  options.create_if_missing = true;
  leveldb::Status status = leveldb_env::OpenDB(options, path.value(), &db);
  ASSERT_TRUE(status.ok());

  leveldb::WriteBatch batch;
  batch.Put(syncer::FormatDataPrefix(kAshSyncDataType) + kMoveExtensionId,
            "ash_data");
  batch.Put(syncer::FormatMetaPrefix(kAshSyncDataType) + kMoveExtensionId,
            "ash_metadata");
  batch.Put(syncer::FormatGlobalMetadataKey(kAshSyncDataType),
            "ash_globalmetadata");

  batch.Put(syncer::FormatDataPrefix(kLacrosSyncDataType) + kMoveExtensionId,
            "lacros_data");
  batch.Put(syncer::FormatMetaPrefix(kLacrosSyncDataType) + kMoveExtensionId,
            "lacros_metadata");
  batch.Put(syncer::FormatGlobalMetadataKey(kLacrosSyncDataType),
            "lacros_globalmetadata");

  leveldb::WriteOptions write_options;
  write_options.sync = true;
  status = db->Write(write_options, &batch);
  ASSERT_TRUE(status.ok());
}

// Return all the key-value pairs in a LevelDB.
std::map<std::string, std::string> ReadLevelDB(const base::FilePath& path) {
  leveldb_env::Options options;
  options.create_if_missing = false;

  std::unique_ptr<leveldb::DB> db;
  leveldb::Status status = leveldb_env::OpenDB(options, path.value(), &db);
  EXPECT_TRUE(status.ok());

  std::map<std::string, std::string> db_map;
  std::unique_ptr<leveldb::Iterator> it(
      db->NewIterator(leveldb::ReadOptions()));
  for (it->SeekToFirst(); it->Valid(); it->Next()) {
    db_map.emplace(it->key().ToString(), it->value().ToString());
  }

  return db_map;
}

}  // namespace

TEST(BrowserDataMigratorUtilTest, NoPathOverlaps) {
  base::span<const char* const> remain_in_ash_paths =
      base::make_span(kRemainInAshDataPaths);
  base::span<const char* const> lacros_data_paths =
      base::make_span(kLacrosDataPaths);
  base::span<const char* const> deletable_paths =
      base::make_span(kDeletablePaths);
  base::span<const char* const> common_data_paths =
      base::make_span(kNeedCopyForMoveDataPaths);

  std::vector<base::span<const char* const>> paths_groups{
      remain_in_ash_paths, lacros_data_paths, deletable_paths,
      common_data_paths};

  auto overlap_checker = [](base::span<const char* const> paths_group_a,
                            base::span<const char* const> paths_group_b) {
    for (const char* path_a : paths_group_a) {
      for (const char* path_b : paths_group_b) {
        if (base::StringPiece(path_a) == base::StringPiece(path_b)) {
          LOG(ERROR) << "The following path appears in multiple sets: "
                     << path_a;
          return false;
        }
      }
    }

    return true;
  };

  for (size_t i = 0; i < paths_groups.size() - 1; i++) {
    for (size_t j = i + 1; j < paths_groups.size(); j++) {
      SCOPED_TRACE(base::StringPrintf("i %zu j %zu", i, j));
      EXPECT_TRUE(overlap_checker(paths_groups[i], paths_groups[j]));
    }
  }
}

TEST(BrowserDataMigratorUtilTest, ComputeDirectorySizeWithoutLinks) {
  base::ScopedTempDir dir_1;
  ASSERT_TRUE(dir_1.CreateUniqueTempDir());

  ASSERT_TRUE(
      base::WriteFile(dir_1.GetPath().Append(FILE_PATH_LITERAL("file1")),
                      kTextFileContent, kTextFileSize));
  ASSERT_TRUE(
      base::CreateDirectory(dir_1.GetPath().Append(FILE_PATH_LITERAL("dir"))));
  ASSERT_TRUE(base::WriteFile(dir_1.GetPath()
                                  .Append(FILE_PATH_LITERAL("dir"))
                                  .Append(FILE_PATH_LITERAL("file2")),
                              kTextFileContent, kTextFileSize));

  // Check that `ComputeDirectorySizeWithoutLinks` returns the sum of sizes of
  // the two files in the directory.
  EXPECT_EQ(ComputeDirectorySizeWithoutLinks(dir_1.GetPath()),
            kTextFileSize * 2);

  base::ScopedTempDir dir_2;
  ASSERT_TRUE(dir_2.CreateUniqueTempDir());
  ASSERT_TRUE(
      base::WriteFile(dir_2.GetPath().Append(FILE_PATH_LITERAL("file3")),
                      kTextFileContent, kTextFileSize));

  ASSERT_TRUE(CreateSymbolicLink(
      dir_2.GetPath().Append(FILE_PATH_LITERAL("file3")),
      dir_1.GetPath().Append(FILE_PATH_LITERAL("link_to_file3"))));

  // Check that `ComputeDirectorySizeWithoutLinks` does not follow symlinks from
  // `dir_1` to `dir_2`.
  EXPECT_EQ(ComputeDirectorySizeWithoutLinks(dir_1.GetPath()),
            kTextFileSize * 2);
}

TEST(BrowserDataMigratorUtilTest, GetUMAItemName) {
  base::FilePath profile_data_dir("/home/chronos/user");

  EXPECT_STREQ(GetUMAItemName(profile_data_dir.Append(kCodeCachePath)).c_str(),
               kCodeCacheUMAName);

  EXPECT_STREQ(
      GetUMAItemName(profile_data_dir.Append(FILE_PATH_LITERAL("abcd")))
          .c_str(),
      kUnknownUMAName);
}

TEST(BrowserDataMigratorUtilTest, GetExtensionKeys) {
  using std::string_literals::operator""s;

  base::ScopedTempDir scoped_temp_dir;
  ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir());

  // Prepare LocalStorage-like LevelDB.
  std::unique_ptr<leveldb::DB> db;
  SetUpLocalStorage(
      scoped_temp_dir.GetPath().Append(FILE_PATH_LITERAL("localstorage")), db);

  ExtensionKeys keys;
  leveldb::Status status =
      GetExtensionKeys(db.get(), LevelDBType::kLocalStorage, &keys);
  EXPECT_TRUE(status.ok());
  db.reset();

  std::string keep_extension_id =
      browser_data_migrator_util::kExtensionsAshOnly[0];
  std::string both_extension_id =
      browser_data_migrator_util::kExtensionsBothChromes[0];
  ExtensionKeys expected_keys = {
      {keep_extension_id,
       {
           "META:chrome-extension://" + keep_extension_id,
           "_chrome-extension://" + keep_extension_id + "\x00key1"s,
       }},
      {both_extension_id,
       {
           "META:chrome-extension://" + both_extension_id,
           "_chrome-extension://" + both_extension_id + "\x00key1"s,
       }},
      {kMoveExtensionId,
       {
           "META:chrome-extension://" + std::string(kMoveExtensionId),
           "_chrome-extension://" + std::string(kMoveExtensionId) + "\x00key1"s,
       }},
  };
  EXPECT_EQ(expected_keys, keys);
  keys.clear();

  // Prepare StateStore-like LevelDB.
  SetUpStateStore(
      scoped_temp_dir.GetPath().Append(FILE_PATH_LITERAL("statestore")), db);

  status = GetExtensionKeys(db.get(), LevelDBType::kStateStore, &keys);
  EXPECT_TRUE(status.ok());

  expected_keys = {
      {keep_extension_id,
       {
           keep_extension_id + ".key1",
           keep_extension_id + ".key2",
       }},
      {both_extension_id,
       {
           both_extension_id + ".key1",
           both_extension_id + ".key2",
       }},
      {kMoveExtensionId,
       {
           std::string(kMoveExtensionId) + ".key1",
           std::string(kMoveExtensionId) + ".key2",
       }},
  };
  EXPECT_EQ(expected_keys, keys);
}

TEST(BrowserDataMigratorUtilTest, MigrateLevelDB) {
  using std::string_literals::operator""s;

  base::ScopedTempDir scoped_temp_dir;
  ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir());

  // Prepare LocalStorage-like LevelDB.
  std::unique_ptr<leveldb::DB> db;
  const base::FilePath localstorage_db_path =
      scoped_temp_dir.GetPath().Append(FILE_PATH_LITERAL("localstorage"));
  const base::FilePath localstorage_new_db_path =
      localstorage_db_path.AddExtension(".new");
  SetUpLocalStorage(localstorage_db_path, db);
  db.reset();

  EXPECT_TRUE(MigrateLevelDB(localstorage_db_path, localstorage_new_db_path,
                             LevelDBType::kLocalStorage));

  leveldb_env::Options options;
  options.create_if_missing = false;
  leveldb::Status status =
      leveldb_env::OpenDB(options, localstorage_new_db_path.value(), &db);
  EXPECT_TRUE(status.ok());

  ExtensionKeys keys;
  status = GetExtensionKeys(db.get(), LevelDBType::kLocalStorage, &keys);
  EXPECT_TRUE(status.ok());
  db.reset();

  std::string keep_extension_id =
      browser_data_migrator_util::kExtensionsAshOnly[0];
  std::string both_extension_id =
      browser_data_migrator_util::kExtensionsBothChromes[0];
  ExtensionKeys expected_keys = {
      {keep_extension_id,
       {
           "META:chrome-extension://" + keep_extension_id,
           "_chrome-extension://" + keep_extension_id + "\x00key1"s,
       }},
      {both_extension_id,
       {
           "META:chrome-extension://" + both_extension_id,
           "_chrome-extension://" + both_extension_id + "\x00key1"s,
       }},
  };
  EXPECT_EQ(expected_keys, keys);
  keys.clear();

  // Prepare StateStore-like LevelDB.
  const base::FilePath statestore_db_path =
      scoped_temp_dir.GetPath().Append(FILE_PATH_LITERAL("statestore"));
  const base::FilePath statestore_new_db_path =
      statestore_db_path.AddExtension(".new");
  SetUpStateStore(statestore_db_path, db);
  db.reset();

  EXPECT_TRUE(MigrateLevelDB(statestore_db_path, statestore_new_db_path,
                             LevelDBType::kStateStore));

  status = leveldb_env::OpenDB(options, statestore_new_db_path.value(), &db);
  EXPECT_TRUE(status.ok());

  status = GetExtensionKeys(db.get(), LevelDBType::kStateStore, &keys);
  EXPECT_TRUE(status.ok());

  expected_keys = {
      {keep_extension_id,
       {
           keep_extension_id + ".key1",
           keep_extension_id + ".key2",
       }},
      {both_extension_id,
       {
           both_extension_id + ".key1",
           both_extension_id + ".key2",
       }},
  };
  EXPECT_EQ(expected_keys, keys);
}

TEST(BrowserDataMigratorUtilTest, MigrateSyncDataLevelDB) {
  base::ScopedTempDir scoped_temp_dir;
  ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir());

  // Prepare Sync Data LevelDB.
  std::unique_ptr<leveldb::DB> db;
  const base::FilePath db_path =
      scoped_temp_dir.GetPath().Append(FILE_PATH_LITERAL("syncdata"));
  SetUpSyncData(db_path, db);
  db.reset();

  // Migrate Sync Data.
  const base::FilePath ash_db_path = db_path.AddExtension(".ash");
  const base::FilePath lacros_db_path = db_path.AddExtension(".lacros");
  EXPECT_TRUE(MigrateSyncDataLevelDB(db_path, ash_db_path, lacros_db_path));

  // Check resulting Ash database.
  auto ash_db_map = ReadLevelDB(ash_db_path);
  std::map<std::string, std::string> expected_ash_db_map = {
      {syncer::FormatDataPrefix(kAshSyncDataType) + kMoveExtensionId,
       "ash_data"},
      {syncer::FormatMetaPrefix(kAshSyncDataType) + kMoveExtensionId,
       "ash_metadata"},
      {syncer::FormatGlobalMetadataKey(kAshSyncDataType), "ash_globalmetadata"},
  };
  EXPECT_EQ(expected_ash_db_map, ash_db_map);

  // Check resulting Lacros database.
  auto lacros_db_map = ReadLevelDB(lacros_db_path);
  std::map<std::string, std::string> expected_lacros_db_map = {
      {syncer::FormatDataPrefix(kLacrosSyncDataType) + kMoveExtensionId,
       "lacros_data"},
      {syncer::FormatMetaPrefix(kLacrosSyncDataType) + kMoveExtensionId,
       "lacros_metadata"},
      {syncer::FormatGlobalMetadataKey(kLacrosSyncDataType),
       "lacros_globalmetadata"},
  };
  EXPECT_EQ(expected_lacros_db_map, lacros_db_map);
}

TEST(BrowserDataMigratorUtilTest, RecordUserDataSize) {
  base::HistogramTester histogram_tester;

  base::FilePath profile_data_dir("/home/chronos/user");
  // Size in bytes.
  int64_t size = 4 * 1024 * 1024;
  RecordUserDataSize(profile_data_dir.Append(kCodeCachePath), size);

  std::string uma_name =
      std::string(kUserDataStatsRecorderDataSize) + kCodeCacheUMAName;

  histogram_tester.ExpectTotalCount(uma_name, 1);
  histogram_tester.ExpectBucketCount(uma_name, size / 1024 / 1024, 1);
}

TEST(BrowserDataMigratorUtilTest, CreateHardLink) {
  base::ScopedTempDir scoped_temp_dir;
  ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir());

  const base::FilePath from_file =
      scoped_temp_dir.GetPath().Append(FILE_PATH_LITERAL("from_file"));
  const base::FilePath to_file =
      scoped_temp_dir.GetPath().Append(FILE_PATH_LITERAL("to_file"));
  base::WriteFile(from_file, "Hello, World", sizeof("Hello, World"));

  ASSERT_TRUE(CreateHardLink(from_file, to_file));

  EXPECT_TRUE(base::PathExists(to_file));

  // Make sure that they are indeed the same file.
  EXPECT_TRUE(IsSameFile(from_file, to_file));
}

TEST(BrowserDataMigratorUtilTest, CopyDirectory) {
  base::ScopedTempDir scoped_temp_dir;
  ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir());

  const base::FilePath copy_from =
      scoped_temp_dir.GetPath().Append("copy_from");

  const char subdirectory[] = "Subdirectory";
  const char data_file[] = "data";
  const char original[] = "original";
  const char symlink[] = "symlink";
  const char sensitive[] = "sensitive";

  // Setup files/directories as described below.
  // |- sensitive/original
  // |- copy_from/
  //     |- data
  //     |- Subdirectory/
  //         |- data
  //         |- Subdirectory/data
  //     |- symlink  /* symlink to original */

  ASSERT_TRUE(base::WriteFile(
      scoped_temp_dir.GetPath().Append(sensitive).Append(original),
      kTextFileContent, kTextFileSize));
  ASSERT_TRUE(base::CreateDirectory(copy_from));
  ASSERT_TRUE(base::CreateDirectory(copy_from.Append(subdirectory)));
  ASSERT_TRUE(base::CreateDirectory(
      copy_from.Append(subdirectory).Append(subdirectory)));
  ASSERT_TRUE(base::WriteFile(copy_from.Append(data_file), kTextFileContent,
                              kTextFileSize));
  ASSERT_TRUE(base::WriteFile(copy_from.Append(subdirectory).Append(data_file),
                              kTextFileContent, kTextFileSize));
  ASSERT_TRUE(base::WriteFile(
      copy_from.Append(subdirectory).Append(subdirectory).Append(data_file),
      kTextFileContent, kTextFileSize));
  base::CreateSymbolicLink(
      scoped_temp_dir.GetPath().Append(sensitive).Append(original),
      copy_from.Append(symlink));

  // Test `CopyDirectory()`.
  scoped_refptr<CancelFlag> cancelled = base::MakeRefCounted<CancelFlag>();
  FakeMigrationProgressTracker progress_tracker;
  const base::FilePath copy_to = scoped_temp_dir.GetPath().Append("copy_to");
  ASSERT_TRUE(
      CopyDirectory(copy_from, copy_to, cancelled.get(), &progress_tracker));

  // Expected `copy_to` structure after `CopyDirectory()`.
  // |- copy_to/
  //     |- data
  //     |- Subdirectory/
  //         |- data
  //         |- Subdirectory/data
  EXPECT_TRUE(base::PathExists(copy_to));
  EXPECT_TRUE(base::PathExists(copy_to.Append(data_file)));
  EXPECT_TRUE(base::PathExists(copy_to.Append(subdirectory).Append(data_file)));
  EXPECT_TRUE(base::PathExists(
      copy_to.Append(subdirectory).Append(subdirectory).Append(data_file)));
  // Make sure that symlink is not copied.
  EXPECT_FALSE(base::PathExists(copy_to.Append(symlink)));
  EXPECT_FALSE(base::PathExists(copy_to.Append(original)));

  // Test `CopyDirectoryByHardLinks()`.
  const base::FilePath copy_to_hard =
      scoped_temp_dir.GetPath().Append("copy_to_hard");
  ASSERT_TRUE(CopyDirectoryByHardLinks(copy_from, copy_to_hard));

  // Expected `copy_to_hard` structure after `CopyDirectoryByHardLinks()`.
  // |- copy_to_hard/
  //     |- data
  //     |- Subdirectory/
  //         |- data
  //         |- Subdirectory/data
  EXPECT_TRUE(base::PathExists(copy_to_hard));
  EXPECT_TRUE(base::PathExists(copy_to_hard.Append(data_file)));
  EXPECT_TRUE(
      base::PathExists(copy_to_hard.Append(subdirectory).Append(data_file)));
  EXPECT_TRUE(base::PathExists(copy_to_hard.Append(subdirectory)
                                   .Append(subdirectory)
                                   .Append(data_file)));
  // Make sure that symlink is not copied.
  EXPECT_FALSE(base::PathExists(copy_to_hard.Append(symlink)));
  EXPECT_FALSE(base::PathExists(copy_to_hard.Append(original)));

  // Make sure that they are indeed the same file.
  EXPECT_TRUE(
      IsSameFile(copy_from.Append(data_file), copy_to_hard.Append(data_file)));
  EXPECT_TRUE(IsSameFile(copy_from.Append(subdirectory).Append(data_file),
                         copy_to_hard.Append(subdirectory).Append(data_file)));
  EXPECT_TRUE(IsSameFile(
      copy_from.Append(subdirectory).Append(subdirectory).Append(data_file),
      copy_to_hard.Append(subdirectory)
          .Append(subdirectory)
          .Append(data_file)));
}

TEST(BrowserDataMigratorUtilTest, HasEnoughDiskSpace) {
  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  const int64_t free_disk_space =
      base::SysInfo::AmountOfFreeDiskSpace(temp_dir.GetPath());
  ASSERT_GE(free_disk_space, 0);
  ASSERT_GE(static_cast<uint64_t>(free_disk_space), kBuffer);

  // If total copy size is the same as `free_disk_space` then the disk is
  // exactly `kBuffer` bytes short of free space.
  EXPECT_EQ(ExtraBytesRequiredToBeFreed(free_disk_space, temp_dir.GetPath()),
            kBuffer);
  EXPECT_FALSE(HasEnoughDiskSpace(free_disk_space, temp_dir.GetPath()));

  // If total copy size is the same as `free_disk_space - kBuffer` then the disk
  // has just enough space for the migration.
  EXPECT_EQ(ExtraBytesRequiredToBeFreed(free_disk_space - kBuffer,
                                        temp_dir.GetPath()),
            0u);
  EXPECT_TRUE(
      HasEnoughDiskSpace(free_disk_space - kBuffer, temp_dir.GetPath()));

  // If there is nothing to be copied then as long as `free_disk_space >=
  // kBuffer`, there should be no extra space required to be freed.
  EXPECT_EQ(ExtraBytesRequiredToBeFreed(0, temp_dir.GetPath()), 0u);
  EXPECT_TRUE(HasEnoughDiskSpace(0, temp_dir.GetPath()));
}

TEST(BrowserDataMigratorUtilTest, IsAshOnlySyncDataType) {
  // The types that should be recognized as Ash-only are stored in
  // `browser_data_migrator_util::kAshOnlySyncDataTypes`.
  // Then any of the following can be suffixed to the type name:
  // - `kDataPrefix` = "-dt-"
  // - `kMetadataPrefix` = "-md-"
  // - `kGlobalMetadataKey` = "-GlobalMetadata"
  // `kDataPrefix` and `kMetadataPrefix` are then followed by an id, while
  // `kGlobalMetadataKey` is not.

  const constexpr char* const kTypes[] = {
      "app_list",
      "arc_package",
      "os_preferences",
      "os_priority_preferences",
      "printers",
      "printers_authorization_servers",
      "wifi_configurations",
      "workspace_desk",
  };

  const constexpr char* const kSuffixes[] = {
      "-dt-",
      "-md-",
  };

  for (const char* const type : kTypes) {
    for (const char* const suffix : kSuffixes) {
      auto key = std::string(type) + std::string(suffix) + "random_id";
      EXPECT_TRUE(IsAshOnlySyncDataType(key));
    }
    auto global_metadata_key = std::string(type) + "-GlobalMetadata";
    EXPECT_TRUE(IsAshOnlySyncDataType(global_metadata_key));
    auto global_metadata_key_with_id =
        std::string(type) + "-GlobalMetadata" + "random_id";
    EXPECT_FALSE(IsAshOnlySyncDataType(global_metadata_key_with_id));
  }

  EXPECT_FALSE(IsAshOnlySyncDataType("random_key"));
}

class BrowserDataMigratorUtilWithTargetsTest : public ::testing::Test {
 public:
  void SetUp() override {
    // Setup profile data directory.
    ASSERT_TRUE(scoped_temp_dir_.CreateUniqueTempDir());

    LOG(WARNING) << "Setting up tmp directory.";

    profile_data_dir_ = scoped_temp_dir_.GetPath();

    // Setup files/directories as described below.
    //
    // |- Bookmarks      /* lacros */
    // |- Cookies        /* lacros */
    // |- Downloads/     /* remain in ash */
    //     |- file
    //     |- file 2
    // |- shared_proto_db  /* need to copy */
    // |- Cache          /* deletable */
    // |- Code Cache/    /* deletable */
    //     |- file

    LOG(WARNING) << profile_data_dir_.Append(kBookmarksPath).value();

    // Lacros items.
    ASSERT_TRUE(base::WriteFile(profile_data_dir_.Append(kBookmarksPath),
                                kTextFileContent, kTextFileSize));
    ASSERT_TRUE(base::WriteFile(profile_data_dir_.Append(kCookiesPath),
                                kTextFileContent, kTextFileSize));
    // Remain in ash items.
    ASSERT_TRUE(
        base::CreateDirectory(profile_data_dir_.Append(kDownloadsPath)));
    ASSERT_TRUE(base::WriteFile(profile_data_dir_.Append(kDownloadsPath)
                                    .Append(FILE_PATH_LITERAL("file")),
                                kTextFileContent, kTextFileSize));
    ASSERT_TRUE(base::WriteFile(profile_data_dir_.Append(kDownloadsPath)
                                    .Append(FILE_PATH_LITERAL("file 2")),
                                kTextFileContent, kTextFileSize));

    // Need to copy items.
    ASSERT_TRUE(base::WriteFile(profile_data_dir_.Append(kSharedProtoDBPath),
                                kTextFileContent, kTextFileSize));

    // Deletable items.
    ASSERT_TRUE(base::WriteFile(profile_data_dir_.Append(kCachePath),
                                kTextFileContent, kTextFileSize));
    ASSERT_TRUE(
        base::CreateDirectory(profile_data_dir_.Append(kCodeCachePath)));
    ASSERT_TRUE(base::WriteFile(profile_data_dir_.Append(kCodeCachePath)
                                    .Append(FILE_PATH_LITERAL("file")),
                                kTextFileContent, kTextFileSize));
  }

  void TearDown() override { EXPECT_TRUE(scoped_temp_dir_.Delete()); }

  base::ScopedTempDir scoped_temp_dir_;
  base::FilePath profile_data_dir_;
};

TEST_F(BrowserDataMigratorUtilWithTargetsTest, GetTargetItems) {
  // Check for lacros data.
  std::vector<TargetItem> expected_lacros_items = {
      {profile_data_dir_.Append(kBookmarksPath), kTextFileSize,
       TargetItem::ItemType::kFile},
      {profile_data_dir_.Append(kCookiesPath), kTextFileSize,
       TargetItem::ItemType::kFile}};
  TargetItems lacros_items =
      GetTargetItems(profile_data_dir_, ItemType::kLacros);
  EXPECT_EQ(lacros_items.total_size, kTextFileSize * 2);
  ASSERT_EQ(lacros_items.items.size(), expected_lacros_items.size());
  std::sort(lacros_items.items.begin(), lacros_items.items.end(),
            TargetItemComparator());
  for (size_t i = 0; i < lacros_items.items.size(); i++) {
    SCOPED_TRACE(lacros_items.items[i].path.value());
    EXPECT_EQ(lacros_items.items[i], expected_lacros_items[i]);
  }

  // Check for remain in ash data.
  std::vector<TargetItem> expected_remain_in_ash_items = {
      {profile_data_dir_.Append(kDownloadsPath), kTextFileSize * 2,
       TargetItem::ItemType::kDirectory}};
  TargetItems remain_in_ash_items =
      GetTargetItems(profile_data_dir_, ItemType::kRemainInAsh);
  EXPECT_EQ(remain_in_ash_items.total_size, kTextFileSize * 2);
  ASSERT_EQ(remain_in_ash_items.items.size(),
            expected_remain_in_ash_items.size());
  EXPECT_EQ(remain_in_ash_items.items[0], expected_remain_in_ash_items[0]);

  // Check for items that need copies in lacros.
  std::vector<TargetItem> expected_need_copy_items = {
      {profile_data_dir_.Append(kSharedProtoDBPath), kTextFileSize,
       TargetItem::ItemType::kFile}};
  TargetItems need_copy_items =
      GetTargetItems(profile_data_dir_, ItemType::kNeedCopyForMove);
  EXPECT_EQ(need_copy_items.total_size, kTextFileSize);
  ASSERT_EQ(need_copy_items.items.size(), expected_need_copy_items.size());
  EXPECT_EQ(need_copy_items.items[0], expected_need_copy_items[0]);

  // Check for deletable items.
  std::vector<TargetItem> expected_deletable_items = {
      {profile_data_dir_.Append(kCachePath), kTextFileSize,
       TargetItem::ItemType::kFile},
      {profile_data_dir_.Append(kCodeCachePath), kTextFileSize,
       TargetItem::ItemType::kDirectory}};
  TargetItems deletable_items =
      GetTargetItems(profile_data_dir_, ItemType::kDeletable);
  std::sort(deletable_items.items.begin(), deletable_items.items.end(),
            TargetItemComparator());
  EXPECT_EQ(deletable_items.total_size, kTextFileSize * 2);
  ASSERT_EQ(deletable_items.items.size(), expected_deletable_items.size());
  for (size_t i = 0; i < deletable_items.items.size(); i++) {
    SCOPED_TRACE(deletable_items.items[i].path.value());
    EXPECT_EQ(deletable_items.items[i], expected_deletable_items[i]);
  }
}

TEST_F(BrowserDataMigratorUtilWithTargetsTest, DryRunToCollectUMA) {
  base::HistogramTester histogram_tester;

  DryRunToCollectUMA(profile_data_dir_);

  const std::string uma_name_bookmarks =
      std::string(browser_data_migrator_util::kUserDataStatsRecorderDataSize) +
      "Bookmarks";
  const std::string uma_name_cookies =
      std::string(browser_data_migrator_util::kUserDataStatsRecorderDataSize) +
      "Cookies";
  const std::string uma_name_downloads =
      std::string(browser_data_migrator_util::kUserDataStatsRecorderDataSize) +
      "Downloads";
  const std::string uma_name_shared_proto_db =
      std::string(browser_data_migrator_util::kUserDataStatsRecorderDataSize) +
      "SharedProtoDb";
  const std::string uma_name_cache =
      std::string(browser_data_migrator_util::kUserDataStatsRecorderDataSize) +
      "Cache";
  const std::string uma_name_code_cache =
      std::string(browser_data_migrator_util::kUserDataStatsRecorderDataSize) +
      "CodeCache";

  histogram_tester.ExpectBucketCount(uma_name_bookmarks,
                                     kTextFileSize / 1024 / 1024, 1);
  histogram_tester.ExpectBucketCount(uma_name_cookies,
                                     kTextFileSize / 1024 / 1024, 1);
  histogram_tester.ExpectBucketCount(uma_name_downloads,
                                     kTextFileSize * 2 / 1024 / 1024, 1);
  histogram_tester.ExpectBucketCount(uma_name_shared_proto_db,
                                     kTextFileSize / 1024 / 1024, 1);
  histogram_tester.ExpectBucketCount(uma_name_cache,
                                     kTextFileSize / 1024 / 1024, 1);
  histogram_tester.ExpectBucketCount(uma_name_code_cache,
                                     kTextFileSize / 1024 / 1024, 1);

  histogram_tester.ExpectBucketCount(kDryRunLacrosDataSize,
                                     kTextFileSize * 2 / 1024 / 1024, 1);
  histogram_tester.ExpectBucketCount(kDryRunAshDataSize,
                                     kTextFileSize * 2 / 1024 / 1024, 1);
  histogram_tester.ExpectBucketCount(kDryRunCommonDataSize,
                                     kTextFileSize / 1024 / 1024, 1);
  histogram_tester.ExpectBucketCount(kDryRunNoCopyDataSize,
                                     kTextFileSize * 2 / 1024 / 1024, 1);

  histogram_tester.ExpectTotalCount(kDryRunCopyMigrationHasEnoughDiskSpace, 1);
  histogram_tester.ExpectTotalCount(
      kDryRunDeleteAndCopyMigrationHasEnoughDiskSpace, 1);
  histogram_tester.ExpectTotalCount(kDryRunMoveMigrationHasEnoughDiskSpace, 1);
  histogram_tester.ExpectTotalCount(
      kDryRunDeleteAndCopyMigrationHasEnoughDiskSpace, 1);
}

TEST(BrowserDataMigratorUtilTest, UpdatePreferencesKeyByType) {
  const std::string keep_extension_dict_key =
      std::string("extensions.settings.") + kExtensionsAshOnly[0];
  const std::string both_extension_dict_key =
      std::string("extensions.settings.") + kExtensionsBothChromes[0];
  const std::string move_extension_dict_key =
      std::string("extensions.settings.") + kMoveExtensionId;

  base::Value::List extension_list;
  extension_list.Append(kExtensionsAshOnly[0]);
  extension_list.Append(kExtensionsBothChromes[0]);
  extension_list.Append(kMoveExtensionId);
  const std::string extension_list_key = "extensions.pinned_extensions";

  // List of dictionaries instead of list of strings as expected.
  // {"extensions.toolbar": [
  //   { <kExtensionsAshOnly[0]> : "test1"},
  //   { <kExtensionsBothChromes[0]> : "test2"},
  //   { <kMoveExtensionId> : "test3"},
  // ]}
  base::Value::Dict wrong_type_value1;
  wrong_type_value1.Set(kExtensionsAshOnly[0], "test1");
  base::Value::Dict wrong_type_value2;
  wrong_type_value2.Set(kExtensionsBothChromes[0], "test2");
  base::Value::Dict wrong_type_value3;
  wrong_type_value3.Set(kMoveExtensionId, "test3");
  base::Value::List wrong_type_list;
  wrong_type_list.Append(std::move(wrong_type_value1));
  wrong_type_list.Append(std::move(wrong_type_value2));
  wrong_type_list.Append(std::move(wrong_type_value3));
  const std::string wrong_type_key = "extensions.toolbar";

  base::Value::Dict ash_dict;
  ash_dict.SetByDottedPath(keep_extension_dict_key, "test1");
  ash_dict.SetByDottedPath(both_extension_dict_key, "test2");
  ash_dict.SetByDottedPath(move_extension_dict_key, "test3");
  ash_dict.SetByDottedPath(extension_list_key, std::move(extension_list));
  ash_dict.SetByDottedPath(wrong_type_key, std::move(wrong_type_list));
  base::Value::Dict lacros_dict = ash_dict.Clone();

  UpdatePreferencesKeyByType(&ash_dict, "extensions.settings",
                             ChromeType::kAsh);
  UpdatePreferencesKeyByType(&lacros_dict, "extensions.settings",
                             ChromeType::kLacros);

  // Test Ash against expected results.
  base::Value::Dict* d = ash_dict.FindDictByDottedPath("extensions.settings");
  std::set<std::string> expected_keys = {kExtensionsAshOnly[0],
                                         kExtensionsBothChromes[0]};
  EXPECT_EQ(expected_keys, CollectDictKeys(d));
  // If a type other than string is found in a list, it will be left unchanged.
  base::Value::List* l = ash_dict.FindListByDottedPath(wrong_type_key);
  EXPECT_NE(nullptr, l);
  EXPECT_EQ(3u, l->size());

  // Test Lacros against expected results.
  d = lacros_dict.FindDictByDottedPath("extensions.settings");
  expected_keys = {kExtensionsBothChromes[0], kMoveExtensionId};
  EXPECT_EQ(expected_keys, CollectDictKeys(d));
  l = lacros_dict.FindListByDottedPath(wrong_type_key);
  EXPECT_NE(nullptr, l);
  EXPECT_EQ(3u, l->size());
}

TEST(BrowserDataMigratorUtilTest, MigratePreferencesContents) {
  const std::string keep_extension_dict_key =
      std::string("extensions.settings.") + kExtensionsAshOnly[0];
  const std::string both_extension_dict_key =
      std::string("extensions.settings.") + kExtensionsBothChromes[0];
  const std::string move_extension_dict_key =
      std::string("extensions.settings.") + kMoveExtensionId;

  base::Value::List extension_list;
  extension_list.Append(kExtensionsAshOnly[0]);
  extension_list.Append(kExtensionsBothChromes[0]);
  extension_list.Append(kMoveExtensionId);
  const std::string extension_list_key = "extensions.pinned_extensions";

  std::string original_contents;
  base::Value::Dict dict;
  dict.SetByDottedPath(kLacrosOnlyPreferencesKeys[0], "test1");
  dict.SetByDottedPath(kAshOnlyPreferencesKeys[0], "test2");
  dict.SetByDottedPath("unrelated.key", "test3");
  dict.SetByDottedPath(keep_extension_dict_key, "test4");
  dict.SetByDottedPath(move_extension_dict_key, "test5");
  dict.SetByDottedPath(extension_list_key, std::move(extension_list));
  base::JSONWriter::Write(dict, &original_contents);

  auto contents = MigratePreferencesContents(original_contents);
  EXPECT_TRUE(contents.has_value());

  absl::optional<base::Value> ash_root = base::JSONReader::Read(contents->ash);
  EXPECT_TRUE(ash_root.has_value());
  base::Value::Dict* ash_root_dict = ash_root->GetIfDict();
  EXPECT_NE(nullptr, ash_root_dict);
  EXPECT_EQ(nullptr, ash_root_dict->FindStringByDottedPath(
                         kLacrosOnlyPreferencesKeys[0]));
  EXPECT_EQ("test2",
            *ash_root_dict->FindStringByDottedPath(kAshOnlyPreferencesKeys[0]));
  EXPECT_EQ("test3", *ash_root_dict->FindStringByDottedPath("unrelated.key"));
  EXPECT_EQ("test4",
            *ash_root_dict->FindStringByDottedPath(keep_extension_dict_key));
  EXPECT_EQ(nullptr,
            ash_root_dict->FindStringByDottedPath(move_extension_dict_key));
  base::Value::List* ash_extension_list =
      ash_root_dict->FindListByDottedPath(extension_list_key);
  EXPECT_NE(nullptr, ash_extension_list);
  EXPECT_EQ(2u, ash_extension_list->size());
  EXPECT_EQ(kExtensionsAshOnly[0], (*ash_extension_list)[0].GetString());
  EXPECT_EQ(kExtensionsBothChromes[0], (*ash_extension_list)[1].GetString());

  absl::optional<base::Value> lacros_root =
      base::JSONReader::Read(contents->lacros);
  EXPECT_TRUE(lacros_root.has_value());
  base::Value::Dict* lacros_root_dict = lacros_root->GetIfDict();
  EXPECT_NE(nullptr, lacros_root_dict);
  EXPECT_EQ("test1", *lacros_root_dict->FindStringByDottedPath(
                         kLacrosOnlyPreferencesKeys[0]));
  EXPECT_EQ(nullptr, lacros_root_dict->FindStringByDottedPath(
                         kAshOnlyPreferencesKeys[0]));
  EXPECT_EQ("test3",
            *lacros_root_dict->FindStringByDottedPath("unrelated.key"));
  EXPECT_EQ(nullptr,
            lacros_root_dict->FindStringByDottedPath(keep_extension_dict_key));
  EXPECT_EQ("test5",
            *lacros_root_dict->FindStringByDottedPath(move_extension_dict_key));
  base::Value::List* lacros_extension_list =
      lacros_root_dict->FindListByDottedPath(extension_list_key);
  EXPECT_NE(nullptr, lacros_extension_list);
  EXPECT_EQ(2u, lacros_extension_list->size());
  EXPECT_EQ(kExtensionsBothChromes[0], (*lacros_extension_list)[0].GetString());
  EXPECT_EQ(kMoveExtensionId, (*lacros_extension_list)[1].GetString());
}

TEST(BrowserDataMigratorUtilTest, MigratePreferences) {
  base::ScopedTempDir scoped_temp_dir;
  ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir());

  const base::FilePath original_preferences_path =
      scoped_temp_dir.GetPath().Append("Preferences.original");
  const base::FilePath ash_preferences_path =
      scoped_temp_dir.GetPath().Append("Preferences.ash");
  const base::FilePath lacros_preferences_path =
      scoped_temp_dir.GetPath().Append("Preferences.lacros");

  std::string original_contents;
  base::Value::Dict dict;
  dict.SetByDottedPath(kLacrosOnlyPreferencesKeys[0], "test1");
  dict.SetByDottedPath(kAshOnlyPreferencesKeys[0], "test2");
  dict.SetByDottedPath("unrelated.key", "test3");
  ASSERT_TRUE(base::JSONWriter::Write(dict, &original_contents));
  ASSERT_TRUE(base::WriteFile(original_preferences_path, original_contents));

  EXPECT_TRUE(browser_data_migrator_util::MigratePreferences(
      original_preferences_path, ash_preferences_path,
      lacros_preferences_path));

  std::string ash_contents;
  std::string lacros_contents;
  EXPECT_TRUE(base::ReadFileToString(ash_preferences_path, &ash_contents));
  EXPECT_TRUE(
      base::ReadFileToString(lacros_preferences_path, &lacros_contents));

  absl::optional<base::Value> ash_root = base::JSONReader::Read(ash_contents);
  EXPECT_TRUE(ash_root.has_value());
  base::Value::Dict* ash_root_dict = ash_root->GetIfDict();
  EXPECT_NE(nullptr, ash_root_dict);
  EXPECT_EQ(nullptr, ash_root_dict->FindStringByDottedPath(
                         kLacrosOnlyPreferencesKeys[0]));
  EXPECT_EQ("test2",
            *ash_root_dict->FindStringByDottedPath(kAshOnlyPreferencesKeys[0]));
  EXPECT_EQ("test3", *ash_root_dict->FindStringByDottedPath("unrelated.key"));

  absl::optional<base::Value> lacros_root =
      base::JSONReader::Read(lacros_contents);
  EXPECT_TRUE(lacros_root.has_value());
  base::Value::Dict* lacros_root_dict = lacros_root->GetIfDict();
  EXPECT_NE(nullptr, lacros_root_dict);
  EXPECT_EQ(nullptr, lacros_root_dict->FindStringByDottedPath(
                         kAshOnlyPreferencesKeys[0]));
  EXPECT_EQ("test1", *lacros_root_dict->FindStringByDottedPath(
                         kLacrosOnlyPreferencesKeys[0]));
  EXPECT_EQ("test3",
            *lacros_root_dict->FindStringByDottedPath("unrelated.key"));
}

}  // namespace ash::browser_data_migrator_util


text:
<?php

/**
 * Initializes the test environment.
 */
require_once(dirname(__FILE__) . '/bootstrap.php');

/**
 * Tests the advice reflection class.
 *
 * @category PHP
 * @package AspectPHP_Reflection
 * @subpackage Tests
 * @author Matthias Molitor <matthias@matthimatiker.de>
 * @copyright 2012 Matthias Molitor
 * @license http://www.opensource.org/licenses/BSD-3-Clause BSD License
 * @link https://github.com/Matthimatiker/AspectPHP
 * @since 16.04.2012
 */
class AspectPHP_Reflection_AdviceTest extends PHPUnit_Framework_TestCase
{

    /**
     * Ensures that the constructor throws an exception if the advice method
     * is not public.
     */
    public function testConstructorThrowsExceptionIfAdviceIsNotPublic()
    {
        $this->setExpectedException('AspectPHP_Reflection_Exception');
        $this->createReflection('Reflection_AdviceNotPublicAspect', 'protectedBeforeAdvice');
    }

    /**
     * Ensures that the constructor throws an exception if the advice method
     * requires more than one parameter.
     */
    public function testConstructorThrowsExceptionIfMoreThanOneParameterIsRequired()
    {
        $this->setExpectedException('AspectPHP_Reflection_Exception');
        $this->createReflection('Reflection_AdviceWithTooManyParamsAspect', 'afterAdvice');
    }

    /**
     * Checks if the constructor accepts an advice method that requires one parameter.
     */
    public function testConstructorAcceptsAdviceWithOneParameter()
    {
        $this->setExpectedException(null);
        $this->createReflection('Reflection_AdviceWithJoinPointParamAspect', 'afterAdvice');
    }

    /**
     * Ensures that the constructor throws an exception if the passed method does
     * not provide a doc comment.
     */
    public function testConstructorThrowsExceptionIfMethodDoesNotProvideDocComment()
    {
        $this->setExpectedException('AspectPHP_Reflection_Exception');
        $this->createReflection('Reflection_NoDocBlockAspect', 'notDocumentedMethod');
    }

    /**
     * Ensures that the constructor throws an exception if the doc comment contains a
     * type tag without information about the referenced pointcut.
     */
    public function testConstructorThrowsExceptionIfDocCommentContainsTagWithoutPointcutReference()
    {
        $this->setExpectedException('AspectPHP_Reflection_Exception');
        $this->createReflection('Reflection_NoPointcutReferenceAspect', 'noValidReference');
    }

    /**
     * Ensures that the constructor throws an exception if the doc comment of the method
     * does not reference any pointcut.
     */
    public function testConstructorThrowsExceptionIfMethodDoesNotReferenceAnyPointcuts()
    {
        $this->setExpectedException('AspectPHP_Reflection_Exception');
        $this->createReflection('Reflection_SimpleAspect', 'anotherMethod');
    }

    /**
     * Checks if getPointcutsByType() returns an array.
     */
    public function testGetPointcutsByTypeReturnsArray()
    {
        $reflection = $this->createReflection('Reflection_SimpleAspect', 'beforeAdvice');
        $pointcuts  = $reflection->getPointcutsByType(AspectPHP_Advice_Type::BEFORE);
        $this->assertInternalType('array', $pointcuts);
    }

    /**
     * Checks if the array that is returned by getPointcutsByType() contains only
     * objects of type AspectPHP_Reflection_Pointcut.
     */
    public function testGetPointcutsByTypeReturnsPointcutReflectionObjects()
    {
        $reflection = $this->createReflection('Reflection_SimpleAspect', 'beforeAdvice');
        $pointcuts  = $reflection->getPointcutsByType(AspectPHP_Advice_Type::BEFORE);
        $this->assertInternalType('array', $pointcuts);
        $this->assertContainsOnly('AspectPHP_Reflection_Pointcut', $pointcuts);
    }

    /**
     * Checks if getPointcutsByType() returns the correct number of pointcuts.
     */
    public function testGetPointcutsByTypeReturnsCorrectNumberOfPointcuts()
    {
        $reflection = $this->createReflection('Reflection_SimpleAspect', 'beforeAdvice');
        $pointcuts  = $reflection->getPointcutsByType(AspectPHP_Advice_Type::BEFORE);
        $this->assertInternalType('array', $pointcuts);
        $this->assertEquals(1, count($pointcuts));
    }

    /**
     * Ensures that getPointcutsByType() returns an empty array no pointcut is referenced
     * for the provided type.
     */
    public function testGetPointcutsByTypeReturnsEmptyArrayIfNoPointcutOfThatTypeWasReferenced()
    {
        $reflection = $this->createReflection('Reflection_SimpleAspect', 'beforeAdvice');
        $pointcuts  = $reflection->getPointcutsByType(AspectPHP_Advice_Type::AFTER);
        $this->assertInternalType('array', $pointcuts);
        $this->assertEquals(0, count($pointcuts));
    }

    /**
     * Ensures that getPointcutsByType() throws an exception id an invalid type is passed.
     */
    public function testGetPointcutsByTypeThrowsExceptionIfInvalidTypeIsProvided()
    {
        $this->setExpectedException('InvalidArgumentException');
        $reflection = $this->createReflection('Reflection_SimpleAspect', 'beforeAdvice');
        $reflection->getPointcutsByType('invalid');
    }

    /**
     * Ensures that getPointcutsByType() throws an exception if a referenced pointcut
     * is not declared in the corresponding aspect.
     */
    public function testGetPointcutsByTypeThrowsExceptionIfReferencedPointcutDoesNotExist()
    {
        $this->setExpectedException('AspectPHP_Reflection_Exception');
        $reflection = $this->createReflection('Reflection_PointcutMissingAspect', 'beforeAdvice');
        $reflection->getPointcutsByType(AspectPHP_Advice_Type::BEFORE);
    }

    /**
     * Ensures that referencesPointcut() returns true if the comment references a pointcut.
     */
    public function testReferencesPointcutReturnsTrueIfCommentContainsPointcutReference()
    {
        $comment = '/**'               . PHP_EOL
                 . ' * Hello'          . PHP_EOL
                 . ' *'                . PHP_EOL
                 . ' * World!'         . PHP_EOL
                 . ' *'                . PHP_EOL
                 . ' * @before test()' . PHP_EOL
                 . ' */';
        $this->assertTrue(AspectPHP_Reflection_Advice::referencesPointcut($comment));
    }

    /**
     * Ensures that referencesPointcut() returns false if the comment does not reference
     * any pointcut.
     */
    public function testReferencesPointcutReturnsFalseIfCommentDoesNotContainPointcutReference()
    {
        $comment = '/**'                    . PHP_EOL
                 . ' * Hello'               . PHP_EOL
                 . ' *'                     . PHP_EOL
                 . ' * World!'              . PHP_EOL
                 . ' *'                     . PHP_EOL
                 . ' * @param string $name' . PHP_EOL
                 . ' */';
        $this->assertFalse(AspectPHP_Reflection_Advice::referencesPointcut($comment));
    }

    /**
     * Creates a reflection object for the advice.
     *
     * @param mixed $classOrAspect
     * @param string $name The name of the advice method.
     * @return AspectPHP_Reflection_Advice
     */
    protected function createReflection($classOrAspect, $name)
    {
        if (is_string($classOrAspect)) {
            $this->loadIfNecessary($classOrAspect);
        }
        return new AspectPHP_Reflection_Advice($classOrAspect, $name);
    }

    /**
     * Loads the provided test class if it is not already available.
     *
     * @param string $class
     */
    protected function loadIfNecessary($class)
    {
        if (class_exists($class, false)) {
            // Class is already loaded.
            return;
        }
        $pathSegment = str_replace('_', '/', $class);
        require_once(dirname(__FILE__) . '/TestData/'. $pathSegment . '.php');
    }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
	<meta name="viewport" content="width=device-width">
    <title>Impact++ / Source: entities/effect-electricity.js</title>

    <link type="text/css" rel="stylesheet" href="styles/prettify.css">
    <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
    <link type="text/css" rel="stylesheet" href="styles/bootstrap.min.css">
    <link type="text/css" rel="stylesheet" href="styles/main.css">

ig.module(
    'plusplus.entities.effect-electricity'
)
    .requires(
        'plusplus.core.config',
        'plusplus.abstractities.effect'
)
    .defines(function() {

        var _c = ig.CONFIG;

        /**
         * Entity effect to show electricity.
         * <span class="alert"><strong>IMPORTANT:</strong> this entity has a defined size and animation sheet!</span>
         * @class
         * @extends ig.Effect
         * @memberof ig
         * @author Collin Hover - collinhover.com
         */
        ig.EntityEffectElectricity = ig.global.EntityEffectElectricity = ig.Effect.extend( /**@lends ig.EntityEffectElectricity.prototype */ {

            /**
             * Electricity effect does not need to move.
             * @override
             * @default static
             */
            performance: ig.EntityExtended.PERFORMANCE.STATIC,

            /**
             * @override
             * @default 32x32
             */
            size: {
                x: 32,
                y: 32
            },

            /**
             * Electricity effect does not change animations.
             * @override
             */
            animAutomatic: false,

            /**
             * @override
             * @default effect_electricity.png
             */
            animSheet: new ig.AnimationSheet(_c.PATH_TO_MEDIA + 'effect_electricity.png', 32, 32),

            /**
             * @override
             */
            animSettings: {
                moveX: {
                    sequence: [0, 1, 2, 3],
                    frameTime: 0.15
                }
            }

        });

    });


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

    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/orange_600</item>
        <!--   darker variant for the status bar and contextual app bars -->
        <item name="colorPrimaryDark">@color/orange</item>
        <!--   theme UI controls like checkboxes and text fields -->
        <item name="colorAccent">@color/orange_600</item>
        <!--   Touch feedback for ripple, etc. -->
        <item name="colorControlHighlight">@color/orange_100</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowActionBar">false</item>
        <item name="windowActionBar">false</item>
        <item name="android:textColor">@color/black</item>
        <item name="text_title_color_inverse">@color/grey_500</item>
        <item name="text_info_color">@color/grey_400</item>
        <item name="bg_color">@color/grey_200</item>
        <item name="list_item_comment_icon_color">@color/grey_400</item>
        <item name="toolbar_bg_color">@color/orange_600</item>
        <item name="toolbar_poptheme">@style/ThemeOverlay.AppCompat.Light</item>
        <item name="popup_window_bg_color">@color/grey_400</item>
        <item name="popup_window_icon_textsize_small">@drawable/ic_format_size_small</item>
        <item name="popup_window_icon_textsize_large">@drawable/ic_format_size_large</item>
        <item name="popup_window_icon_lineheight_narrow">@drawable/ic_format_line_spacing_narrow</item>
        <item name="popup_window_icon_lineheight_wide">@drawable/ic_format_line_spacing_wide</item>
    </style>

    <style name="AppTheme.Sepia">
        <item name="text_title_color_inverse">@color/sepia_light</item>
        <item name="text_info_color">@color/sepia_light</item>
        <item name="bg_color">@color/sepia</item>
        <item name="list_item_comment_icon_color">@color/sepia_light</item>
        <item name="android:textColor">@color/sepia_dark</item>
        <item name="toolbar_bg_color">@color/orange_600</item>
    </style>

    <style name="AppTheme.Dark" parent="Theme.AppCompat.NoActionBar">
        <item name="colorPrimary">@color/grey_900</item>
        <item name="colorPrimaryDark">@color/grey_900</item>
        <item name="colorAccent">@color/orange_900</item>
        <item name="colorControlHighlight">@color/orange_900</item>
        <item name="android:textColor">@color/grey_200</item>
        <item name="text_title_color_inverse">@color/grey_500</item>
        <item name="text_info_color">@color/grey_600</item>
        <item name="bg_color">@color/grey_900</item>
        <item name="list_item_comment_icon_color">@color/grey_600</item>
        <item name="toolbar_bg_color">@color/grey_800</item>
        <item name="toolbar_poptheme">@style/ThemeOverlay.AppCompat</item>
        <item name="popup_window_bg_color">@color/grey_800</item>
        <item name="popup_window_icon_textsize_small">@drawable/ic_format_size_small_dark</item>
        <item name="popup_window_icon_textsize_large">@drawable/ic_format_size_large_dark</item>
        <item name="popup_window_icon_lineheight_narrow">@drawable/ic_format_line_spacing_narrow_dark</item>
        <item name="popup_window_icon_lineheight_wide">@drawable/ic_format_line_spacing_wide_dark</item>
    </style>

    <style name="AppTheme.AMOLEDBlack" parent="AppTheme.Dark">
        <item name="colorPrimary">@android:color/black</item>
        <item name="colorPrimaryDark">@android:color/black</item>
        <item name="bg_color">@android:color/black</item>
        <item name="toolbar_bg_color">@color/grey_900</item>
        <item name="popup_window_bg_color">@color/grey_900</item>
    </style>

    <style name="ToolBarTheme" parent="Theme.AppCompat">
        <item name="autoCompleteTextViewStyle">@style/cursorColor</item>
    </style>

    <style name="SelectableItemBackground">
        <item name="android:theme">@style/SelectableItemTheme</item>
        <item name="android:background">?attr/selectableItemBackground</item>
    </style>
</resources>


text:
from __future__ import print_function
import subprocess
import os
import sys
import datetime

def update_version(utag=False, major=False, minor=False):
    from flopy import __version__
    vmajor = __version__.strip().split('.')[-3]
    vminor = __version__.strip().split('.')[-2]
    vfeature = __version__.strip().split('.')[-1]

    if major:
        vmajor = int(vmajor) + 1
        vminor = 0
        vfeature = 0
    elif minor:
        vmajor = int(vmajor)
        vminor = int(vminor) + 1
        vfeature = 0
    else:
        vmajor = int(vmajor)
        vminor = int(vminor)
        vfeature = int(vfeature) + 1

    version_type = (
    '{}'.format(vmajor), '{}'.format(vminor), '{}'.format(vfeature))
    version = '.'.join(version_type)

    b = subprocess.Popen(("git", "describe", "--match", "build"),
                         stdout=subprocess.PIPE).communicate()[0]
    build = int(b.decode().strip().split('-')[1]) + 1

    print('Updating version:')
    print('  ', __version__, '->', version)

    # write new version file
    f = open(os.path.normpath('flopy/version.py'), 'w')
    f.write('#flopy version file automatically ' +
            'created using...{0}\n'.format(os.path.basename(__file__)))
    f.write('#            created on......' +
            '{0}\n'.format(datetime.datetime.now().strftime("%B %d, %Y %H:%M:%S")))
    f.write("__version__='{0}'\n".format(version))
    f.write("__build__='{0}.{1}'\n".format(version, build))
    f.close()

    # commit version number change to github
    cmdtag = 'git commit ./flopy/version.py -m "version number update"'
    os.system(cmdtag)
    cmdtag = 'git push'
    os.system(cmdtag)

    # update version tag
    if utag:
        cmdtag = 'git tag -a {0} -m "Version {0}"'.format(version)
        os.system(cmdtag)
        cmdtag = 'git push --tags'
        os.system(cmdtag)

if __name__ == "__main__":
    utag = False
    major = False
    minor = False
    for arg in sys.argv:
        if arg.lower() == '--tag' or arg.lower() == '-t':
            utag = True
            sys.stdout.write('  Will update git tag with version number.\n')
        elif arg.lower() == '--major' or arg.lower() == '-ma':
            major = True
            sys.stdout.write('  Will update major version number by one.\n')
        elif arg.lower() == '--minor' or arg.lower() == '-mi':
            minor = True
            sys.stdout.write('  Will update minor version number by one.\n')

    update_version(utag, major, minor)


text:
function getModule(obj) {
	return require(`./${obj.constructor.name.toLowerCase()}`);
}

module.exports = {
	canRead(user, obj) {
		return getModule(obj).canRead(user, obj);
	},

	canWrite(user, obj) {
		return getModule(obj).canWrite(user, obj);
	},

	canUpdate(user, obj) {
		return getModule(obj).canUpdate(user, obj);
	},

	canCreate(user, obj) {
		return getModule(obj).canCreate(user, obj);
	},

	canDestroy(user, obj) {
		return getModule(obj).canDestroy(user, obj);
	}
};


text:
 /*****************************************************************************
  * ApiIntentReceiver.java                                                    *
  * ApiIntentReceiver                                                         *
  * Intent receiver for 3rd party software                                     *
  *                                                                           *
  *                                                                           *
  *****************************************************************************/

package org.metawatch.manager;

import org.metawatch.manager.MetaWatchService.ConnectionState;
import org.metawatch.manager.MetaWatchService.Preferences;
import org.metawatch.manager.Notification.VibratePattern;
import org.metawatch.manager.apps.AppManager;
import org.metawatch.manager.apps.ApplicationBase;
import org.metawatch.manager.apps.ExternalApp;
import org.metawatch.manager.widgets.WidgetManager;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.preference.PreferenceManager;
import android.util.Log;

public class ApiIntentReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {

		MetaWatchService.autoStartService(context);

		final String action = intent.getAction();
		if (Preferences.logging) Log.d(MetaWatch.TAG, "ApiIntentReceiver.onReceive(): received intent, action='"+action+"'");

		// add digital watch check

		if (action.equals("org.metawatch.manager.APPLICATION_UPDATE")) {
			String id = intent.hasExtra("id") ? intent.getStringExtra("id") : "anonymous";
			if (intent.hasExtra("array")) {
				Bitmap bmp = Bitmap.createBitmap(intent.getIntArrayExtra("array"),
						96, 96, Bitmap.Config.RGB_565);

				if (Preferences.invertLCD && intent.getBooleanExtra("autoinvert", false)) {
					bmp = Utils.invertBitmap(bmp);
				}

				ApplicationBase app = AppManager.getApp(id);
				if (app != null && app instanceof ExternalApp) {
					((ExternalApp)app).setBuffer(bmp);

					if (app.appState == ApplicationBase.ACTIVE_IDLE)
						Idle.updateIdle(context, true);
					else if (app.appState == ApplicationBase.ACTIVE_POPUP)
						Application.updateAppMode(context);
				}

			}
			return;
		}

		else if (action.equals("org.metawatch.manager.WIDGET_UPDATE")) {
			if (Preferences.logging) Log.d(MetaWatch.TAG, "WIDGET_UPDATE received");
			WidgetManager.getFromIntent(context, intent);
			return;
		}

		else if (action.equals("org.metawatch.manager.APPLICATION_START") ||
			action.equals("org.metawatch.manager.APPLICATION_ANNOUNCE")) {
			String id = intent.hasExtra("id") ? intent.getStringExtra("id") : "anonymous";
			String name = intent.hasExtra("name") ? intent.getStringExtra("name") : "External App";

			ApplicationBase app = AppManager.getApp(id);
			if (app==null) {
				app = new ExternalApp(id, name);
				AppManager.addApp(app);
			}

			if (MetaWatchService.connectionState == ConnectionState.CONNECTED) {
				if (action.equals("org.metawatch.manager.APPLICATION_START")) {
					int page = Idle.addAppPage(context, app);
					Idle.toPage(context, page);
				} else {
					// Auto open as a page, if it's enabled in preferences
					final String pageSetting = app.getInfo().getPageSettingName();
					SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
					if (prefs.getBoolean(pageSetting, false)) {
						Idle.addAppPage(context, app);
					}
				}
			}

			return;
		}

		else if (action.equals("org.metawatch.manager.APPLICATION_STOP")) {
			String id = intent.hasExtra("id") ? intent.getStringExtra("id") : "anonymous";

			ApplicationBase app = AppManager.getApp(id);
			if (app!=null) {
				Idle.removeAppPage(context, app);
				Idle.updateIdle(context, true);
			}

			return;
		}

		else if (action.equals("org.metawatch.manager.NOTIFICATION")) {

			/* Set up vibrate pattern. */
			VibratePattern vibrate = getVibratePatternFromIntent(intent);

			if (intent.hasExtra("oled1") || intent.hasExtra("oled1a")
					|| intent.hasExtra("oled1b") || intent.hasExtra("oled2")
					|| intent.hasExtra("oled2a") || intent.hasExtra("oled2b")) {

				byte[] line1 = Protocol.createOled1line(context, null, "");
				byte[] line2 = Protocol.createOled1line(context, null, "");
				byte[] scroll = null;
				int scrollLen = 0;
				if (intent.hasExtra("oled1")) {
					line1 = Protocol.createOled1line(context, null, intent.getStringExtra("oled1"));
				} else {
					if (intent.hasExtra("oled1a") || intent.hasExtra("oled1b")) {
						String oled1a = "";
						String oled1b = "";
						if (intent.hasExtra("oled1a")) {
							oled1a = intent.getStringExtra("oled1a");
						}
						if (intent.hasExtra("oled1b")) {
							oled1b = intent.getStringExtra("oled1b");
						}
						line1 = Protocol.createOled2lines(context, oled1a, oled1b);
					}
				}
				if (intent.hasExtra("oled2")) {
					line2 = Protocol.createOled1line(context, null, intent.getStringExtra("oled2"));
				} else {
					if (intent.hasExtra("oled2a") || intent.hasExtra("oled2b")) {
						String oled2a = "";
						String oled2b = "";
						if (intent.hasExtra("oled2a")) {
							oled2a = intent.getStringExtra("oled2a");
						}
						if (intent.hasExtra("oled2b")) {
							oled2b = intent.getStringExtra("oled2b");
						}
						scroll = new byte[800];
						scrollLen = Protocol.createOled2linesLong(context, oled2b, scroll);
						line2 = Protocol.createOled2lines(context, oled2a, oled2b);
					}
				}
				Notification.addOledNotification(context, line1, line2, scroll, scrollLen, vibrate, "API oled notification");

			} else if (intent.hasExtra("text")) {
				String title = "Notification";
				if (intent.hasExtra("title")) {
					title = intent.getStringExtra("title");
				}
				String text = intent.getStringExtra("text");

				Bitmap icon = null;
				if (intent.hasExtra("icon")) {
					icon = Bitmap.createBitmap(intent.getIntArrayExtra("icon"),
							intent.getIntExtra("iconWidth", 16),
							intent.getIntExtra("iconHeight", 16),
							Bitmap.Config.RGB_565);
				}

				boolean sticky = intent.getBooleanExtra("sticky", true);

				NotificationBuilder.createSmart(context, title, text, icon, sticky, vibrate);

				if (Preferences.logging) Log.d(MetaWatch.TAG,
						"ApiIntentReceiver.onReceive(): sending text notification; text='"
								+ text + "'");
			} else if (intent.hasExtra("array")) {
				int[] array = intent.getIntArrayExtra("array");
				Notification.addArrayNotification(context, array, vibrate, "API Array notification");
			} else if (intent.hasExtra("buffer")) {
				byte[] buffer = intent.getByteArrayExtra("buffer");
				Notification.addBufferNotification(context, buffer, vibrate, "API Buffer notification");
			}
			return;
		}

		if (action.equals("org.metawatch.manager.VIBRATE")) {
			/* Set up vibrate pattern. */
			VibratePattern vibrate = getVibratePatternFromIntent(intent);

			if(vibrate.vibrate)
				Protocol.vibrate(vibrate.on, vibrate.off, vibrate.cycles);

			return;
		}

		else if (action.equals("org.metawatch.manager.SILENTMODE")) {
			if (intent.hasExtra("enabled")) {
				MetaWatchService.setSilentMode(intent.getBooleanExtra("enabled", false));
			}
		}

	}

	private VibratePattern getVibratePatternFromIntent(Intent intent){
		/* Set up vibrate pattern. */
		VibratePattern vibrate = Notification.VibratePattern.NO_VIBRATE;
		if (intent.hasExtra("vibrate_on") && intent.hasExtra("vibrate_off") && intent.hasExtra("vibrate_cycles")) {
			int vibrateOn = intent.getIntExtra("vibrate_on", 500);
			int vibrateOff = intent.getIntExtra("vibrate_off", 500);
			int vibrateCycles = intent.getIntExtra("vibrate_cycles", 3);
			vibrate = new VibratePattern(true, vibrateOn, vibrateOff, vibrateCycles);
		}
		return vibrate;
	}

}


text:
Original Author
###############
- Michael Paddon

Core Developers
###############
- Shaun O'Keefe <shaun.okeefe.0@gmail.com>
- Matthew Duggan <mduggan@gmail.com>
- Pan, Louis <louis@pan.me>


text:
from django.db.models import CharField
from django.db.models.functions import LTrim, RTrim, Trim
from django.test import TestCase
from django.test.utils import register_lookup

from ..models import Author

class TrimTests(TestCase):
    def test_trim(self):
        Author.objects.create(name="  John ", alias="j")
        Author.objects.create(name="Rhonda", alias="r")
        authors = Author.objects.annotate(
            ltrim=LTrim("name"),
            rtrim=RTrim("name"),
            trim=Trim("name"),
        )
        self.assertQuerySetEqual(
            authors.order_by("alias"),
            [
                ("John ", "  John", "John"),
                ("Rhonda", "Rhonda", "Rhonda"),
            ],
            lambda a: (a.ltrim, a.rtrim, a.trim),
        )

    def test_trim_transform(self):
        Author.objects.create(name=" John  ")
        Author.objects.create(name="Rhonda")
        tests = (
            (LTrim, "John  "),
            (RTrim, " John"),
            (Trim, "John"),
        )
        for transform, trimmed_name in tests:
            with self.subTest(transform=transform):
                with register_lookup(CharField, transform):
                    authors = Author.objects.filter(
                        **{"name__%s" % transform.lookup_name: trimmed_name}
                    )
                    self.assertQuerySetEqual(authors, [" John  "], lambda a: a.name)


text:
package org.schoellerfamily.gedbrowser.datamodel.finder;

import java.util.Collection;

import org.schoellerfamily.gedbrowser.datamodel.FinderObject;
import org.schoellerfamily.gedbrowser.datamodel.GedObject;
import org.schoellerfamily.gedbrowser.datamodel.Person;

/**
 * @author Dick Schoeller
 */
public final class ParentFinder implements FinderStrategy {
    /**
     * Constructor.
     */
    public ParentFinder() {
        // Empty constructor.
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public GedObject find(final FinderObject owner, final String str) {
        return owner.findInParent(str);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getFilename(final FinderObject owner) {
        return owner.getParentFilename();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getDbName(final FinderObject owner) {
        return owner.getParentDbName();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void insert(final FinderObject owner, final FinderObject gob) {
        ((GedObject) owner).addAttribute((GedObject) gob);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public <T extends GedObject> T find(
            final FinderObject owner, final String str, final Class<T> clazz) {
        return owner.findInParent(str, clazz);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Collection<Person> findBySurname(final FinderObject owner,
            final String surname) {
        return owner.findInParentBySurname(surname);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Collection<String> findBySurnamesBeginWith(final FinderObject owner,
            final String beginsWith) {
        return owner.findInParentBySurnamesBeginWith(beginsWith);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Collection<String> findSurnameInitialLetters(
            final FinderObject owner) {
        return owner.findInParentSurnameInitialLetters();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public <T extends GedObject> Collection<T> find(final FinderObject owner,
            final Class<T> clazz) {
        return owner.findInParent(clazz);
    }
}


text:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;

namespace TButt.Editor
{
    public static class TBEditorExtensions
    {
        // Textures
        public const string TButtFolderPath = "TButt";
        public static Texture turboButtonHeader = EditorGUIUtility.LoadRequired(string.Format("{0}/inspector_header_tbutt.png", TButtFolderPath)) as Texture;

        // Colors
        public static readonly Color color_TButtGold = new Color(1f, 189 / 255f, 74 / 255f);

        static List<int> layerNumbers = new List<int>();

        public static void ShowHeaderImage(Texture tex)
        {
            var rect = GUILayoutUtility.GetRect(0f, 0f);
            rect.width = tex.width;
            rect.height = tex.height;
            GUILayout.Space(rect.height);
            GUI.DrawTexture(rect, tex);
        }

        public static void ResetColors()
        {
            GUI.backgroundColor = Color.white;
        }

        public static void BeginGroupedControls()
        {
            GUILayout.BeginHorizontal();
            EditorGUILayout.BeginHorizontal("AS TextArea", GUILayout.MinHeight(10f));
            GUILayout.BeginVertical();
            GUILayout.Space(2f);
        }

        public static void EndGroupedControls()
        {
            GUILayout.Space(3f);
            GUILayout.EndVertical();
            EditorGUILayout.EndHorizontal();

            GUILayout.Space(3f);
            GUILayout.EndHorizontal();

            GUILayout.Space(3f);
        }
    }
}


text:
// *****************************************************************************
//
//  © Component Factory Pty Ltd 2017. All rights reserved.
//	The software and associated documentation supplied hereunder are the
//  proprietary information of Component Factory Pty Ltd, 13 Swallows Close,
//  Mornington, Vic 3931, Australia and are supplied subject to licence terms.
//
//  Version 4.6.0.0 	www.ComponentFactory.com
// *****************************************************************************

using System;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Diagnostics;
using ComponentFactory.Krypton.Toolkit;

namespace ComponentFactory.Krypton.Ribbon
{
    /// <summary>
    /// Draws the border around the quick access toolbar.
    /// </summary>
    internal class ViewDrawRibbonQATBorder  : ViewComposite
    {
        #region Static Fields
        private static readonly Padding _minibarBorderPaddingOverlap = new Padding(8, 2, 11, 2);
        private static readonly Padding _minibarBorderPaddingNoOverlap = new Padding(17, 2, 11, 2);
        private static readonly Padding _fullbarBorderPadding_2007 = new Padding(1, 3, 2, 2);
        private static readonly Padding _fullbarBorderPadding_2010 = new Padding(2);
        private static readonly Padding _noBorderPadding = new Padding(1, 0, 1, 0);
        private static readonly int QAT_BUTTON_WIDTH = 22;
        private static readonly int QAT_HEIGHT_MINI = 26;
        private static readonly int QAT_HEIGHT_FULL = 27;
        private static readonly int QAT_MINIBAR_LEFT = 6;
        #endregion

        #region Instance Fields
        private KryptonRibbon _ribbon;
        private NeedPaintHandler _needPaintDelegate;
        private KryptonForm _kryptonForm;
        private IDisposable _memento;
        private bool _minibar;
        private bool _overlapAppButton;
        #endregion

        #region Identity
        /// <summary>
        /// Initialize a new instance of the ViewDrawRibbonQATBorder class.
        /// </summary>
        /// <param name="ribbon">Reference to owning ribbon control.</param>
        /// <param name="needPaintDelegate">Delegate for notifying paint/layout changes.</param>
        /// <param name="minibar">Minibar or full bar drawing.</param>
        public ViewDrawRibbonQATBorder(KryptonRibbon ribbon,
                                       NeedPaintHandler needPaintDelegate,
                                       bool minibar)
        {
            Debug.Assert(ribbon != null);
            Debug.Assert(needPaintDelegate != null);

            // Remember incoming references
            _ribbon = ribbon;
            _needPaintDelegate = needPaintDelegate;
            _minibar = minibar;
            _overlapAppButton = true;
        }

        /// <summary>
        /// Obtains the String representation of this instance.
        /// </summary>
        /// <returns>User readable name of the instance.</returns>
        public override string ToString()
        {
            // Return the class name and instance identifier
            return "ViewDrawRibbonQATBorder:" + Id;
        }

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_memento != null)
                {
                    _memento.Dispose();
                    _memento = null;
                }
            }

            base.Dispose(disposing);
        }
        #endregion

        #region OwnerForm
        /// <summary>
        /// Gets and sets the associated form instance.
        /// </summary>
        public KryptonForm OwnerForm
        {
            get { return _kryptonForm; }
            set { _kryptonForm = value; }
        }
        #endregion

        #region Visible
        /// <summary>
        /// Gets and sets the visible state of the element.
        /// </summary>
        public override bool Visible
        {
            get { return (_ribbon.Visible && base.Visible); }
            set { base.Visible = value; }
        }
        #endregion

        #region OverlapAppButton
        /// <summary>
        /// Should the element overlap the app button to the left.
        /// </summary>
        public bool OverlapAppButton
        {
            get { return _overlapAppButton; }
            set { _overlapAppButton = value; }
        }
        #endregion

        #region Layout
        /// <summary>
        /// Discover the preferred size of the element.
        /// </summary>
        /// <param name="context">Layout context.</param>
        public override Size GetPreferredSize(ViewLayoutContext context)
        {
            // Get size of the contained items
            Size preferredSize = base.GetPreferredSize(context);

            // Add on the border padding
            preferredSize = CommonHelper.ApplyPadding(Orientation.Horizontal, preferredSize, BarPadding);
            preferredSize.Height = Math.Max(preferredSize.Height, BarHeight);

            // If we are inside the custom chrome area
            if (OwnerForm != null)
            {
                // Calculate the maximum width allowed
                int maxWidth = ((OwnerForm.Width - 100) / 3) * 2;

                // Adjust so the width is a multiple of a button size
                int buttons = (maxWidth - BarPadding.Horizontal) / QAT_BUTTON_WIDTH;
                maxWidth = (buttons * QAT_BUTTON_WIDTH) + BarPadding.Horizontal;

                preferredSize.Width = Math.Min(maxWidth, preferredSize.Width);
            }

            return preferredSize;
        }

        /// <summary>
        /// Perform a layout of the elements.
        /// </summary>
        /// <param name="context">Layout context.</param>
        public override void Layout(ViewLayoutContext context)
        {
            Debug.Assert(context != null);

            Rectangle clientRect = context.DisplayRectangle;

            // For the minibar we have to position ourself at bottom of available area
            if (_minibar)
            {
                clientRect.Y = clientRect.Bottom - 1 - QAT_HEIGHT_MINI;
                clientRect.Height = QAT_HEIGHT_MINI;
            }

            ClientRectangle = clientRect;

            // Remove QAT border for positioning children
            context.DisplayRectangle = CommonHelper.ApplyPadding(Orientation.Horizontal, ClientRectangle, BarPadding);

            // Let children be layed out inside border area
            base.Layout(context);

            // Put back the original display value now we have finished
            context.DisplayRectangle = ClientRectangle;
        }
        #endregion

        #region Paint
        /// <summary>
        /// Perform rendering before child elements are rendered.
        /// </summary>
        /// <param name="context">Rendering context.</param>
        public override void RenderBefore(RenderContext context)
        {
            // We never draw the background/border for Office 2010 shape QAT
            if (_minibar && (_ribbon.RibbonShape == PaletteRibbonShape.Office2010))
                return;

            IPaletteRibbonBack palette;
            PaletteState state = PaletteState.Normal;
            Rectangle drawRect = ClientRectangle;

            // Get the correct drawing palette
            if (_minibar)
            {
                if (Active)
                {
                    palette = _ribbon.StateCommon.RibbonQATMinibarActive;
                    if (!OverlapAppButton)
                        state = PaletteState.CheckedNormal;
                }
                else
                {
                    palette = _ribbon.StateCommon.RibbonQATMinibarInactive;
                    state = PaletteState.Disabled;
                }

                if (OverlapAppButton)
                {
                    // If we need to overlap the app button, then shift left
                    drawRect.X -= QAT_MINIBAR_LEFT;
                    drawRect.Width += QAT_MINIBAR_LEFT;
                }
                else
                {
                    // Otherwise shift right so there is a small gap on the left
                    drawRect.X += QAT_MINIBAR_LEFT;
                    drawRect.Width -= QAT_MINIBAR_LEFT;
                }
            }
            else
                palette = _ribbon.StateCommon.RibbonQATFullbar;

            // Decide if we need to draw onto a composition area
            bool composition = (OwnerForm != null) ? OwnerForm.ApplyComposition && OwnerForm.ApplyCustomChrome : false;

            // Perform actual drawing
            _memento = context.Renderer.RenderRibbon.DrawRibbonBack(_ribbon.RibbonShape, context, drawRect, state, palette, VisualOrientation.Top, composition, _memento);
        }
        #endregion

        #region Implementation
        private bool Active
        {
            get
            {
                if (OwnerForm != null)
                    return OwnerForm.WindowActive;
                else
                    return true;
            }
        }

        private Padding BarPadding
        {
            get
            {
                if (_minibar)
                {
                    if (_ribbon.RibbonShape == PaletteRibbonShape.Office2010)
                        return _noBorderPadding;
                    else
                    {
                        if (OverlapAppButton)
                            return _minibarBorderPaddingOverlap;
                        else
                            return _minibarBorderPaddingNoOverlap;
                    }
                }
                else
                {
                    if (_ribbon.RibbonShape == PaletteRibbonShape.Office2010)
                        return _fullbarBorderPadding_2010;
                    else
                        return _fullbarBorderPadding_2007;
                }
            }
        }

        private int BarHeight
        {
            get
            {
                if (_minibar)
                    return QAT_HEIGHT_MINI;
                else
                    return QAT_HEIGHT_FULL;
            }
        }
        #endregion
    }
}


text:
package org.springframework.security.config.annotation;

/**
 * Interface for building an Object
 *
 * @author Rob Winch
 * @since 3.2
 *
 * @param <O> The type of the Object being built
 */
public interface SecurityBuilder<O> {

	/**
	 * Builds the object and returns it or null.
	 *
	 * @return the Object to be built or null if the implementation allows it.
	 * @throws Exception if an error occurred when building the Object
	 */
	O build() throws Exception;
}


text:
TaskForest - An Executive Summary

    Taskforest is a simple but expressive open-source job scheduler that
    allows you to chain jobs/tasks and create time dependencies. It uses
    text config files to specify task dependencies.

    With the TaskForest Job Scheduler you can:

schedule jobs to run at predetermined times,

have jobs be dependent on each other

rerun failed jobs

mark jobs as succeeded or failed

put jobs on hold, and release them

release all dependencies on a job

automatically rerun jobs that fail

receive custom emails or SMS when jobs fail, are retried, or succeed

check the status of all jobs scheduled to run today

interact with the included web service using your own client code

interact with the included web server using your default browser

express the relationships between jobs using a simple text-based format (a big advantage if you like using 'grep')

browse job log files using the included web server


text:
package org.apache.camel.component.elasticsearch5;

import java.lang.reflect.Constructor;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;

import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.impl.DefaultProducer;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.MultiGetRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.MultiSearchRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Represents an Elasticsearch producer.
 */
public class ElasticsearchProducer extends DefaultProducer {

    private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchProducer.class);

    protected final ElasticsearchConfiguration configuration;
    private TransportClient client;

    public ElasticsearchProducer(ElasticsearchEndpoint endpoint, ElasticsearchConfiguration configuration) {
        super(endpoint);
        this.configuration = configuration;
        this.client = endpoint.getClient();
    }

    private ElasticsearchOperation resolveOperation(Exchange exchange) {
        // 1. Operation can be driven by either (in order of preference):
        // a. If the body is an ActionRequest the operation is set by the type
        // of request.
        // b. If the body is not an ActionRequest, the operation is set by the
        // header if it exists.
        // c. If neither the operation can not be derived from the body or
        // header, the configuration is used.
        // In the event we can't discover the operation from a, b or c we throw
        // an error.
        Object request = exchange.getIn().getBody();
        if (request instanceof IndexRequest) {
            return ElasticsearchOperation.INDEX;
        } else if (request instanceof GetRequest) {
            return ElasticsearchOperation.GET_BY_ID;
        } else if (request instanceof MultiGetRequest) {
            return ElasticsearchOperation.MULTIGET;
        } else if (request instanceof UpdateRequest) {
            return ElasticsearchOperation.UPDATE;
        } else if (request instanceof BulkRequest) {
            // do we want bulk or bulk_index?
            if (configuration.getOperation() == ElasticsearchOperation.BULK_INDEX) {
                return ElasticsearchOperation.BULK_INDEX;
            } else {
                return ElasticsearchOperation.BULK;
            }
        } else if (request instanceof DeleteRequest) {
            return ElasticsearchOperation.DELETE;
        } else if (request instanceof SearchRequest) {
            return ElasticsearchOperation.SEARCH;
        } else if (request instanceof MultiSearchRequest) {
            return ElasticsearchOperation.MULTISEARCH;
        } else if (request instanceof DeleteIndexRequest) {
            return ElasticsearchOperation.DELETE_INDEX;
        }

        ElasticsearchOperation operationConfig = exchange.getIn().getHeader(ElasticsearchConstants.PARAM_OPERATION, ElasticsearchOperation.class);
        if (operationConfig == null) {
            operationConfig = configuration.getOperation();
        }
        if (operationConfig == null) {
            throw new IllegalArgumentException(ElasticsearchConstants.PARAM_OPERATION + " value '" + operationConfig + "' is not supported");
        }
        return operationConfig;
    }

    public void process(Exchange exchange) throws Exception {
        // 2. Index and type will be set by:
        // a. If the incoming body is already an action request
        // b. If the body is not an action request we will use headers if they
        // are set.
        // c. If the body is not an action request and the headers aren't set we
        // will use the configuration.
        // No error is thrown by the component in the event none of the above
        // conditions are met. The java es client
        // will throw.

        Message message = exchange.getIn();
        final ElasticsearchOperation operation = resolveOperation(exchange);

        // Set the index/type headers on the exchange if necessary. This is used
        // for type conversion.
        boolean configIndexName = false;
        String indexName = message.getHeader(ElasticsearchConstants.PARAM_INDEX_NAME, String.class);
        if (indexName == null) {
            message.setHeader(ElasticsearchConstants.PARAM_INDEX_NAME, configuration.getIndexName());
            configIndexName = true;
        }

        boolean configIndexType = false;
        String indexType = message.getHeader(ElasticsearchConstants.PARAM_INDEX_TYPE, String.class);
        if (indexType == null) {
            message.setHeader(ElasticsearchConstants.PARAM_INDEX_TYPE, configuration.getIndexType());
            configIndexType = true;
        }

        boolean configWaitForActiveShards = false;
        Integer waitForActiveShards = message.getHeader(ElasticsearchConstants.PARAM_WAIT_FOR_ACTIVE_SHARDS, Integer.class);
        if (waitForActiveShards == null) {
            message.setHeader(ElasticsearchConstants.PARAM_WAIT_FOR_ACTIVE_SHARDS, configuration.getWaitForActiveShards());
            configWaitForActiveShards = true;
        }

        if (operation == ElasticsearchOperation.INDEX) {
            IndexRequest indexRequest = message.getBody(IndexRequest.class);
            message.setBody(client.index(indexRequest).actionGet().getId());
        } else if (operation == ElasticsearchOperation.UPDATE) {
            UpdateRequest updateRequest = message.getBody(UpdateRequest.class);
            message.setBody(client.update(updateRequest).actionGet().getId());
        } else if (operation == ElasticsearchOperation.GET_BY_ID) {
            GetRequest getRequest = message.getBody(GetRequest.class);
            message.setBody(client.get(getRequest));
        } else if (operation == ElasticsearchOperation.MULTIGET) {
            MultiGetRequest multiGetRequest = message.getBody(MultiGetRequest.class);
            message.setBody(client.multiGet(multiGetRequest));
        } else if (operation == ElasticsearchOperation.BULK) {
            BulkRequest bulkRequest = message.getBody(BulkRequest.class);
            message.setBody(client.bulk(bulkRequest).actionGet());
        } else if (operation == ElasticsearchOperation.BULK_INDEX) {
            BulkRequest bulkRequest = message.getBody(BulkRequest.class);
            List<String> indexedIds = new ArrayList<>();
            for (BulkItemResponse response : client.bulk(bulkRequest).actionGet().getItems()) {
                indexedIds.add(response.getId());
            }
            message.setBody(indexedIds);
        } else if (operation == ElasticsearchOperation.DELETE) {
            DeleteRequest deleteRequest = message.getBody(DeleteRequest.class);
            message.setBody(client.delete(deleteRequest).actionGet());
        } else if (operation == ElasticsearchOperation.EXISTS) {
            // ExistsRequest API is deprecated, using SearchRequest instead with size=0 and terminate_after=1
            SearchRequest searchRequest = new SearchRequest(exchange.getIn().getHeader(ElasticsearchConstants.PARAM_INDEX_NAME, String.class));
            try {
                client.prepareSearch(searchRequest.indices()).setSize(0).setTerminateAfter(1).get();
                message.setBody(true);
            } catch (IndexNotFoundException e) {
                message.setBody(false);
            }
        } else if (operation == ElasticsearchOperation.SEARCH) {
            SearchRequest searchRequest = message.getBody(SearchRequest.class);
            message.setBody(client.search(searchRequest).actionGet());
        } else if (operation == ElasticsearchOperation.MULTISEARCH) {
            MultiSearchRequest multiSearchRequest = message.getBody(MultiSearchRequest.class);
            message.setBody(client.multiSearch(multiSearchRequest));
        } else if (operation == ElasticsearchOperation.DELETE_INDEX) {
            DeleteIndexRequest deleteIndexRequest = message.getBody(DeleteIndexRequest.class);
            message.setBody(client.admin().indices().delete(deleteIndexRequest).actionGet());
        } else {
            throw new IllegalArgumentException(ElasticsearchConstants.PARAM_OPERATION + " value '" + operation + "' is not supported");
        }

        // If we set params via the configuration on this exchange, remove them
        // now. This preserves legacy behavior for this component and enables a
        // use case where one message can be sent to multiple elasticsearch
        // endpoints where the user is relying on the endpoint configuration
        // (index/type) rather than header values. If we do not clear this out
        // sending the same message (index request, for example) to multiple
        // elasticsearch endpoints would have the effect overriding any
        // subsequent endpoint index/type with the first endpoint index/type.
        if (configIndexName) {
            message.removeHeader(ElasticsearchConstants.PARAM_INDEX_NAME);
        }

        if (configIndexType) {
            message.removeHeader(ElasticsearchConstants.PARAM_INDEX_TYPE);
        }

        if (configWaitForActiveShards) {
            message.removeHeader(ElasticsearchConstants.PARAM_WAIT_FOR_ACTIVE_SHARDS);
        }

    }

    @Override
    @SuppressWarnings("unchecked")
    protected void doStart() throws Exception {
        super.doStart();

        if (client == null) {
            LOG.info("Connecting to the ElasticSearch cluster: {}", configuration.getClusterName());
            if (configuration.getIp() != null) {
                client = createClient().addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(configuration.getIp()), configuration.getPort()));
            } else if (configuration.getTransportAddressesList() != null && !configuration.getTransportAddressesList().isEmpty()) {
                List<TransportAddress> addresses = new ArrayList<>(configuration.getTransportAddressesList().size());
                addresses.addAll(configuration.getTransportAddressesList());
                client = createClient().addTransportAddresses(addresses.toArray(new TransportAddress[addresses.size()]));
            } else {
                LOG.info("Incorrect ip address and port parameters settings for ElasticSearch cluster");
            }
        }
    }

    private TransportClient createClient() throws Exception {
        final Settings.Builder settings = getSettings();
        final CamelContext camelContext = getEndpoint().getCamelContext();
        final Class<?> clazz = camelContext.getClassResolver().resolveClass("org.elasticsearch.xpack.client.PreBuiltXPackTransportClient");
        if (clazz != null) {
            Constructor<?> ctor = clazz.getConstructor(Settings.class, Class[].class);
            settings.put("xpack.security.user", configuration.getUser() + ":" + configuration.getPassword())
                .put("xpack.security.transport.ssl.enabled", configuration.getEnableSSL());
            LOG.info("XPack Client was found on the classpath");
            return (TransportClient) ctor.newInstance(new Object[]{settings.build(), new Class[0]});
        } else {
            LOG.debug("XPack Client was not found on the classpath, using the standard client.");
            return new PreBuiltTransportClient(settings.build());
        }
    }

    private Settings.Builder getSettings() {
        final Settings.Builder settings = Settings.builder()
            .put("cluster.name", configuration.getClusterName())
            .put("client.transport.sniff", configuration.getClientTransportSniff())
            .put("transport.ping_schedule", configuration.getPingSchedule())
            .put("client.transport.ping_timeout", configuration.getPingTimeout())
            .put("client.transport.sniff", configuration.getClientTransportSniff())
            .put("request.headers.X-Found-Cluster", configuration.getClusterName());
        return settings;
    }

    @Override
    protected void doStop() throws Exception {
        if (client != null) {
            LOG.info("Disconnecting from ElasticSearch cluster: {}", configuration.getClusterName());
            client.close();
            client = null;
        }
        super.doStop();
    }

    public TransportClient getClient() {
        return client;
    }
}


text:
<?php

declare(strict_types=1);

namespace JMS\Serializer\Tests\Fixtures\MaxDepth;

class Gh1382Bar
{
    public $b = 12345;

    public $c;
}


text:
FROM lburgazzoli/debian-jessie:latest
MAINTAINER lburgazzoli

ENV JAVA_VERSION_MAJOR 8
ENV JAVA_VERSION_MINOR 60
ENV JAVA_VERSION_BUILD 27
ENV JAVA_PACKAGE       jdk
ENV JAVA_BUILD         "${JAVA_VERSION_MAJOR}u${JAVA_VERSION_MINOR}-b${JAVA_VERSION_BUILD}"
ENV JAVA_ARCHIVE       "${JAVA_PACKAGE}-${JAVA_VERSION_MAJOR}u${JAVA_VERSION_MINOR}-linux-x64.tar.gz"
ENV JAVA_HOME          "/opt/java"
ENV PATH               "/opt/java/bin:$PATH"

ADD \
    https://raw.githubusercontent.com/lburgazzoli/lb-docker/master/scripts/java-install.sh \
    /tmp/java-install.sh

RUN chmod u+x /tmp/java-install.sh
RUN /tmp/java-install.sh