text:
namespace {
// The offset of the root node for the tree. The first two bytes is reserved to
// specify the size (num of bytes) of the address and the score in each node.
const int kRootNodeOffset = 2;

// A useful data structure to keep track of the tree nodes should be and have
// been visited during tree traversal.
struct MatchCandidate {
  // The sequences of characters from the start node to current node.
  std::string text;

  // Whether the text above can be returned as a suggestion; if false it is the
  // prefix of some other complete suggestion.
  bool is_complete_suggestion;

  // If is_complete_suggestion is true, this is the score for the suggestion;
  // Otherwise it will be set as max_score_as_root of the node.
  uint32_t score;

  // The address of the node in the model file. It is not required if
  // is_complete_suggestion is true.
  uint32_t address;
};

// Doubly linked list structure, which will be sorted based on candidates'
// scores (from low to high), to track nodes during tree search. We use two of
// this list to keep max_num_matches_to_return_ nodes in total with highest
// score during the search, and prune children and branches with low score.
// In theory, using RBTree might give a better search performance
// (i.e. log(n)) compared with linear from linked list here when inserting new
// candidates with high score into the struct, but since n is usually small,
// using linked list shall be okay.
using CandidateQueue = std::list<MatchCandidate>;

// A mini class holds all parameters needed to access the model on disk.
class OnDeviceModelParams {
 public:
  static std::unique_ptr<OnDeviceModelParams> Create(
      const std::string& model_filename,
      const uint32_t max_num_matches_to_return);

  std::ifstream* GetModelFileStream() { return &model_filestream_; }
  uint32_t score_size() const { return score_size_; }
  uint32_t address_size() const { return address_size_; }
  uint32_t max_num_matches_to_return() const {
    return max_num_matches_to_return_;
  }

  ~OnDeviceModelParams();
  OnDeviceModelParams(const OnDeviceModelParams&) = delete;
  OnDeviceModelParams& operator=(const OnDeviceModelParams&) = delete;

 private:
  OnDeviceModelParams() = default;

  std::ifstream model_filestream_;
  uint32_t score_size_;
  uint32_t address_size_;
  uint32_t max_num_matches_to_return_;
};

uint32_t ConvertByteArrayToInt(char byte_array[], uint32_t num_bytes) {
  uint32_t result = 0;
  for (uint32_t i = 0; i < num_bytes; ++i) {
    result |= (byte_array[i] & 0xff) << (8 * i);
  }
  return result;
}

bool OpenModelFileStream(OnDeviceModelParams* params,
                         const std::string& model_filename,
                         const uint32_t start_address) {
  if (model_filename.empty()) {
    DVLOG(1) << "Model filename is empty";
    return false;
  }

  // First close the file if it's still open.
  if (params->GetModelFileStream()->is_open()) {
    DVLOG(1) << "Previous file is still open";
    params->GetModelFileStream()->close();
  }

  params->GetModelFileStream()->open(model_filename,
                                     std::ios::in | std::ios::binary);
  if (!params->GetModelFileStream()->is_open()) {
    DVLOG(1) << "Failed to open model file from [" << model_filename << "]";
    return false;
  }

  if (start_address > 0) {
    params->GetModelFileStream()->seekg(start_address);
  }
  return true;
}

void MaybeCloseModelFileStream(OnDeviceModelParams* params) {
  if (params->GetModelFileStream()->is_open()) {
    params->GetModelFileStream()->close();
  }
}

// Reads next num_bytes from the file stream.
bool ReadNextNumBytes(OnDeviceModelParams* params,
                      uint32_t num_bytes,
                      char* buf) {
  uint32_t address = params->GetModelFileStream()->tellg();
  params->GetModelFileStream()->read(buf, num_bytes);
  if (params->GetModelFileStream()->fail()) {
    DVLOG(1) << "On Device Head model: ifstream read error at address ["
             << address << "], when trying to read [" << num_bytes << "] bytes";
    return false;
  }
  return true;
}

// Reads next num_bytes from the file stream but returns as an integer.
uint32_t ReadNextNumBytesAsInt(OnDeviceModelParams* params,
                               uint32_t num_bytes,
                               bool* is_successful) {
  char* buf = new char[num_bytes];
  *is_successful = ReadNextNumBytes(params, num_bytes, buf);
  if (!*is_successful) {
    delete[] buf;
    return 0;
  }

  uint32_t result = ConvertByteArrayToInt(buf, num_bytes);
  delete[] buf;

  return result;
}

// Checks if size of score and size of address read from the model file are
// valid.
// For score, we use size of 2 bytes (15 bits), 3 bytes (23 bits) or 4 bytes
// (31 bits); For address, we use size of 3 bytes (23 bits) or 4 bytes
// (31 bits).
bool AreSizesValid(OnDeviceModelParams* params) {
  bool is_score_size_valid =
      (params->score_size() >= 2 && params->score_size() <= 4);
  bool is_address_size_valid =
      (params->address_size() >= 3 && params->address_size() <= 4);
  if (!is_score_size_valid) {
    DVLOG(1) << "On Device Head model: score size [" << params->score_size()
             << "] is not valid; valid size should 2, 3 or 4 bytes.";
  }
  if (!is_address_size_valid) {
    DVLOG(1) << "On Device Head model: address size [" << params->address_size()
             << "] is not valid; valid size should be 3 or 4 bytes.";
  }
  return is_score_size_valid && is_address_size_valid;
}

void InsertCandidateToQueue(const MatchCandidate& candidate,
                            CandidateQueue* leaf_queue,
                            CandidateQueue* non_leaf_queue) {
  CandidateQueue* queue_ptr =
      candidate.is_complete_suggestion ? leaf_queue : non_leaf_queue;

  if (queue_ptr->empty() || candidate.score > queue_ptr->back().score) {
    queue_ptr->push_back(candidate);
  } else {
    auto iter = queue_ptr->begin();
    for (; iter != queue_ptr->end() && candidate.score > iter->score; ++iter) {
    }
    queue_ptr->insert(iter, candidate);
  }
}

uint32_t GetMinScoreFromQueues(OnDeviceModelParams* params,
                               const CandidateQueue& queue_1,
                               const CandidateQueue& queue_2) {
  uint32_t min_score = 0x1 << (params->score_size() * 8 - 1);
  if (!queue_1.empty()) {
    min_score = std::min(min_score, queue_1.front().score);
  }
  if (!queue_2.empty()) {
    min_score = std::min(min_score, queue_2.front().score);
  }
  return min_score;
}

// Reads block max_score_as_root at the beginning of the node from the given
// address. If there is a leaf score at the end of the block, return the leaf
// score using param leaf_candidate;
uint32_t ReadMaxScoreAsRoot(OnDeviceModelParams* params,
                            uint32_t address,
                            MatchCandidate* leaf_candidate,
                            bool* is_successful) {
  if (is_successful == nullptr) {
    DVLOG(1) << "On Device Head model: a boolean var is_successful is required "
             << "when calling function ReadMaxScoreAsRoot";
    return 0;
  }

  params->GetModelFileStream()->seekg(address);
  uint32_t max_score_block =
      ReadNextNumBytesAsInt(params, params->score_size(), is_successful);
  if (!*is_successful) {
    return 0;
  }

  // The 1st bit is the indicator so removing it when rebuilding the max
  // score as root.
  uint32_t max_score = max_score_block >> 1;

  // Read the leaf_score and set leaf_candidate when the indicator is 1.
  if ((max_score_block & 0x1) == 0x1 && leaf_candidate != nullptr) {
    uint32_t leaf_score =
        ReadNextNumBytesAsInt(params, params->score_size(), is_successful);
    if (!*is_successful) {
      return 0;
    }
    leaf_candidate->score = leaf_score;
    leaf_candidate->is_complete_suggestion = true;
  }
  return max_score;
}

// Reads a child block and move ifstream cursor to next child; returns false
// when reaching the end of the node or ifstream read error happens.
bool ReadNextChild(OnDeviceModelParams* params, MatchCandidate* candidate) {
  if (candidate == nullptr) {
    return false;
  }

  // Read block [length of text];
  bool is_successful;
  uint32_t text_length = ReadNextNumBytesAsInt(params, 1, &is_successful);
  if (!is_successful) {
    return false;
  }

  // This is the end of the node.
  if (text_length == 0) {
    return false;
  }

  // Read block [text].
  char* text_buf = new char[text_length];
  if (!ReadNextNumBytes(params, text_length, text_buf)) {
    delete[] text_buf;
    return false;
  }
  std::string text(text_buf, text_length);
  delete[] text_buf;
  // Append the text in this child such that the MatchCandidate object always
  // contains the string representing the path from the root node to here.
  candidate->text = base::StrCat({candidate->text, text});

  // Read block [1 bit indicator + address/leaf_score]
  // First read the 1 bit indicator.
  char first_byte;
  if (!ReadNextNumBytes(params, 1, &first_byte)) {
    return false;
  }
  bool is_leaf_score = (first_byte & 0x1) == 0x0;

  uint32_t length_of_leftover =
      (is_leaf_score ? params->score_size() : params->address_size()) - 1;

  char* leftover = new char[length_of_leftover];
  is_successful = ReadNextNumBytes(params, length_of_leftover, leftover);

  if (is_successful) {
    char* last_block = new char[length_of_leftover + 1];
    std::memcpy(last_block, &first_byte, 1);
    std::memcpy(last_block + 1, leftover, length_of_leftover);
    // Remove the 1 bit indicator when re-constructing the score/address.
    uint32_t score_or_address =
        ConvertByteArrayToInt(last_block, length_of_leftover + 1) >> 1;

    if (is_leaf_score) {
      // Address is not required for leaf child.
      candidate->score = score_or_address;
      candidate->is_complete_suggestion = true;
    } else {
      // For non leaf child, score has been set as the max_score_as_root
      // found at the beginning of the current node.
      candidate->address = score_or_address;
      candidate->is_complete_suggestion = false;
    }
    delete[] last_block;
  }

  delete[] leftover;
  return is_successful;
}

// Reads tree node from given match candidate, convert all possible suggestions
// and children of this node into structure MatchCandidate.
std::vector<MatchCandidate> ReadTreeNode(OnDeviceModelParams* params,
                                         const MatchCandidate& current) {
  std::vector<MatchCandidate> candidates;
  // The current candidate passed in is a leaf node and we shall stop here.
  if (current.is_complete_suggestion) {
    return candidates;
  }

  bool is_successful;
  MatchCandidate leaf_candidate;
  leaf_candidate.is_complete_suggestion = false;

  uint32_t max_score_as_root = ReadMaxScoreAsRoot(
      params, current.address, &leaf_candidate, &is_successful);
  if (!is_successful) {
    DVLOG(1) << "On Device Head model: read max_score_as_root failed at "
             << "address [" << current.address << "]";
    return candidates;
  }

  // The max_score_as_root block may contain a leaf node which corresponds to a
  // valid suggestion. Its score was set in function ReadMaxScoreAsRoot.
  if (leaf_candidate.is_complete_suggestion) {
    leaf_candidate.text = current.text;
    candidates.push_back(leaf_candidate);
  }

  // Read child blocks until we reach the end of the node.
  while (true) {
    MatchCandidate candidate;
    candidate.text = current.text;
    candidate.score = max_score_as_root;
    if (!ReadNextChild(params, &candidate)) {
      break;
    }
    candidates.push_back(candidate);
  }
  return candidates;
}

// Finds start node which matches given prefix, returns true if found and the
// start node using param match_candidate.
bool FindStartNode(OnDeviceModelParams* params,
                   const std::string& prefix,
                   MatchCandidate* start_match) {
  if (start_match == nullptr) {
    return false;
  }

  start_match->text = "";
  start_match->score = 0;
  start_match->address = kRootNodeOffset;
  start_match->is_complete_suggestion = false;

  while (start_match->text.size() < prefix.size()) {
    auto children = ReadTreeNode(params, *start_match);
    bool has_match = false;
    for (auto const& child : children) {
      // The way we build the model ensures that there will be only one child
      // matching the given prefix at each node.
      if (!child.text.empty() &&
          (base::StartsWith(child.text, prefix, base::CompareCase::SENSITIVE) ||
           base::StartsWith(prefix, child.text,
                            base::CompareCase::SENSITIVE))) {
        // A leaf only partially matching the given prefix cannot be the right
        // start node.
        if (child.is_complete_suggestion && child.text.size() < prefix.size()) {
          continue;
        }
        start_match->text = child.text;
        start_match->is_complete_suggestion = child.is_complete_suggestion;
        start_match->score = child.score;
        start_match->address = child.address;
        has_match = true;
        break;
      }
    }
    if (!has_match) {
      return false;
    }
  }

  return start_match->text.size() >= prefix.size();
}

std::vector<std::pair<std::string, uint32_t>> DoSearch(
    OnDeviceModelParams* params,
    const MatchCandidate& start_match) {
  std::vector<std::pair<std::string, uint32_t>> suggestions;

  CandidateQueue leaf_queue, non_leaf_queue;
  uint32_t min_score_in_queues = start_match.score;
  InsertCandidateToQueue(start_match, &leaf_queue, &non_leaf_queue);

  // Do the search until there is no non leaf candidates in the queue.
  while (!non_leaf_queue.empty()) {
    // Always fetch the intermediate node with highest score at the back of the
    // queue.
    auto next_candidates = ReadTreeNode(params, non_leaf_queue.back());
    non_leaf_queue.pop_back();
    min_score_in_queues =
        GetMinScoreFromQueues(params, leaf_queue, non_leaf_queue);

    for (const auto& candidate : next_candidates) {
      if (candidate.score > min_score_in_queues ||
          (leaf_queue.size() + non_leaf_queue.size() <
           params->max_num_matches_to_return())) {
        InsertCandidateToQueue(candidate, &leaf_queue, &non_leaf_queue);
      }

      // If there are too many candidates in the queues, remove the one with
      // lowest score since it will never be shown to users.
      if (leaf_queue.size() + non_leaf_queue.size() >
          params->max_num_matches_to_return()) {
        if (leaf_queue.empty() ||
            (!non_leaf_queue.empty() &&
             leaf_queue.front().score > non_leaf_queue.front().score)) {
          non_leaf_queue.pop_front();
        } else {
          leaf_queue.pop_front();
        }
      }
      min_score_in_queues =
          GetMinScoreFromQueues(params, leaf_queue, non_leaf_queue);
    }
  }

  while (!leaf_queue.empty()) {
    suggestions.emplace_back(leaf_queue.back().text, leaf_queue.back().score);
    leaf_queue.pop_back();
  }

  return suggestions;
}

}  // namespace

// static
std::unique_ptr<OnDeviceModelParams> OnDeviceModelParams::Create(
    const std::string& model_filename,
    const uint32_t max_num_matches_to_return) {
  std::unique_ptr<OnDeviceModelParams> params(new OnDeviceModelParams());

  // TODO(crbug.com/925072): Add DCHECK and code to report failures to UMA
  // histogram.
  if (!OpenModelFileStream(params.get(), model_filename, 0)) {
    DVLOG(1) << "On Device Head Params: cannot access on device head params "
             << "instance because model file cannot be opened";
    return nullptr;
  }

  char sizes[2];
  if (!ReadNextNumBytes(params.get(), 2, sizes)) {
    DVLOG(1) << "On Device Head Params: failed to read size information in the "
             << "first 2 bytes of the model file: " << model_filename;
    return nullptr;
  }

  params->address_size_ = sizes[0];
  params->score_size_ = sizes[1];
  if (!AreSizesValid(params.get())) {
    return nullptr;
  }

  params->max_num_matches_to_return_ = max_num_matches_to_return;
  return params;
}

OnDeviceModelParams::~OnDeviceModelParams() {
  if (model_filestream_.is_open()) {
    model_filestream_.close();
  }
}

// static
std::vector<std::pair<std::string, uint32_t>>
OnDeviceHeadModel::GetSuggestionsForPrefix(const std::string& model_filename,
                                           uint32_t max_num_matches_to_return,
                                           const std::string& prefix) {
  std::vector<std::pair<std::string, uint32_t>> suggestions;
  if (prefix.empty() || max_num_matches_to_return < 1) {
    return suggestions;
  }

  std::unique_ptr<OnDeviceModelParams> params =
      OnDeviceModelParams::Create(model_filename, max_num_matches_to_return);

  if (params && params->GetModelFileStream()->is_open()) {
    params->GetModelFileStream()->seekg(kRootNodeOffset);
    MatchCandidate start_match;
    if (FindStartNode(params.get(), prefix, &start_match)) {
      suggestions = DoSearch(params.get(), start_match);
    }
    MaybeCloseModelFileStream(params.get());
  }
  return suggestions;
}


text:
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/log2.h>
#include <asm/mmu_context.h>
#include <asm/processor.h>
#include <asm/uaccess.h>
#include <asm/page.h>
#include <asm/cacheflush.h>
#include <asm/cache.h>
#include <asm/elf.h>
#include <asm/io.h>
#include <asm/smp.h>
#include <asm/sh_bios.h>
#include <asm/setup.h>

#ifdef CONFIG_SH_FPU
#define cpu_has_fpu	1
#else
#define cpu_has_fpu	0
#endif

#ifdef CONFIG_SH_DSP
#define cpu_has_dsp	1
#else
#define cpu_has_dsp	0
#endif

/*
 * Generic wrapper for command line arguments to disable on-chip
 * peripherals (nofpu, nodsp, and so forth).
 */
#define onchip_setup(x)					\
static int x##_disabled __cpuinitdata = !cpu_has_##x;	\
							\
static int __cpuinit x##_setup(char *opts)			\
{							\
	x##_disabled = 1;				\
	return 1;					\
}							\
__setup("no" __stringify(x), x##_setup);

onchip_setup(fpu);
onchip_setup(dsp);

#ifdef CONFIG_SPECULATIVE_EXECUTION
#define CPUOPM		0xff2f0000
#define CPUOPM_RABD	(1 << 5)

static void __cpuinit speculative_execution_init(void)
{
	/* Clear RABD */
	__raw_writel(__raw_readl(CPUOPM) & ~CPUOPM_RABD, CPUOPM);

	/* Flush the update */
	(void)__raw_readl(CPUOPM);
	ctrl_barrier();
}
#else
#define speculative_execution_init()	do { } while (0)
#endif

#ifdef CONFIG_CPU_SH4A
#define EXPMASK			0xff2f0004
#define EXPMASK_RTEDS		(1 << 0)
#define EXPMASK_BRDSSLP		(1 << 1)
#define EXPMASK_MMCAW		(1 << 4)

static void __cpuinit expmask_init(void)
{
	unsigned long expmask = __raw_readl(EXPMASK);

	/*
	 * Future proofing.
	 *
	 * Disable support for slottable sleep instruction, non-nop
	 * instructions in the rte delay slot, and associative writes to
	 * the memory-mapped cache array.
	 */
	expmask &= ~(EXPMASK_RTEDS | EXPMASK_BRDSSLP | EXPMASK_MMCAW);

	__raw_writel(expmask, EXPMASK);
	ctrl_barrier();
}
#else
#define expmask_init()	do { } while (0)
#endif

/* 2nd-level cache init */
void __attribute__ ((weak)) l2_cache_init(void)
{
}

/*
 * Generic first-level cache init
 */
#ifdef CONFIG_SUPERH32
static void cache_init(void)
{
	unsigned long ccr, flags;

	jump_to_uncached();
	ccr = __raw_readl(CCR);

	/*
	 * At this point we don't know whether the cache is enabled or not - a
	 * bootloader may have enabled it.  There are at least 2 things that
	 * could be dirty in the cache at this point:
	 * 1. kernel command line set up by boot loader
	 * 2. spilled registers from the prolog of this function
	 * => before re-initialising the cache, we must do a purge of the whole
	 * cache out to memory for safety.  As long as nothing is spilled
	 * during the loop to lines that have already been done, this is safe.
	 * - RPC
	 */
	if (ccr & CCR_CACHE_ENABLE) {
		unsigned long ways, waysize, addrstart;

		waysize = current_cpu_data.dcache.sets;

#ifdef CCR_CACHE_ORA
		/*
		 * If the OC is already in RAM mode, we only have
		 * half of the entries to flush..
		 */
		if (ccr & CCR_CACHE_ORA)
			waysize >>= 1;
#endif

		waysize <<= current_cpu_data.dcache.entry_shift;

#ifdef CCR_CACHE_EMODE
		/* If EMODE is not set, we only have 1 way to flush. */
		if (!(ccr & CCR_CACHE_EMODE))
			ways = 1;
		else
#endif
			ways = current_cpu_data.dcache.ways;

		addrstart = CACHE_OC_ADDRESS_ARRAY;
		do {
			unsigned long addr;

			for (addr = addrstart;
			     addr < addrstart + waysize;
			     addr += current_cpu_data.dcache.linesz)
				__raw_writel(0, addr);

			addrstart += current_cpu_data.dcache.way_incr;
		} while (--ways);
	}

	/*
	 * Default CCR values .. enable the caches
	 * and invalidate them immediately..
	 */
	flags = CCR_CACHE_ENABLE | CCR_CACHE_INVALIDATE;

#ifdef CCR_CACHE_EMODE
	/* Force EMODE if possible */
	if (current_cpu_data.dcache.ways > 1)
		flags |= CCR_CACHE_EMODE;
	else
		flags &= ~CCR_CACHE_EMODE;
#endif

#if defined(CONFIG_CACHE_WRITETHROUGH)
	/* Write-through */
	flags |= CCR_CACHE_WT;
#elif defined(CONFIG_CACHE_WRITEBACK)
	/* Write-back */
	flags |= CCR_CACHE_CB;
#else
	/* Off */
	flags &= ~CCR_CACHE_ENABLE;
#endif

	l2_cache_init();

	__raw_writel(flags, CCR);
	back_to_cached();
}
#else
#define cache_init()	do { } while (0)
#endif

#define CSHAPE(totalsize, linesize, assoc) \
	((totalsize & ~0xff) | (linesize << 4) | assoc)

#define CACHE_DESC_SHAPE(desc)	\
	CSHAPE((desc).way_size * (desc).ways, ilog2((desc).linesz), (desc).ways)

static void detect_cache_shape(void)
{
	l1d_cache_shape = CACHE_DESC_SHAPE(current_cpu_data.dcache);

	if (current_cpu_data.dcache.flags & SH_CACHE_COMBINED)
		l1i_cache_shape = l1d_cache_shape;
	else
		l1i_cache_shape = CACHE_DESC_SHAPE(current_cpu_data.icache);

	if (current_cpu_data.flags & CPU_HAS_L2_CACHE)
		l2_cache_shape = CACHE_DESC_SHAPE(current_cpu_data.scache);
	else
		l2_cache_shape = -1; /* No S-cache */
}

static void __cpuinit fpu_init(void)
{
	/* Disable the FPU */
	if (fpu_disabled && (current_cpu_data.flags & CPU_HAS_FPU)) {
		printk("FPU Disabled\n");
		current_cpu_data.flags &= ~CPU_HAS_FPU;
	}

	disable_fpu();
	clear_used_math();
}

#ifdef CONFIG_SH_DSP
static void __cpuinit release_dsp(void)
{
	unsigned long sr;

	/* Clear SR.DSP bit */
	__asm__ __volatile__ (
		"stc\tsr, %0\n\t"
		"and\t%1, %0\n\t"
		"ldc\t%0, sr\n\t"
		: "=&r" (sr)
		: "r" (~SR_DSP)
	);
}

static void __cpuinit dsp_init(void)
{
	unsigned long sr;

	/*
	 * Set the SR.DSP bit, wait for one instruction, and then read
	 * back the SR value.
	 */
	__asm__ __volatile__ (
		"stc\tsr, %0\n\t"
		"or\t%1, %0\n\t"
		"ldc\t%0, sr\n\t"
		"nop\n\t"
		"stc\tsr, %0\n\t"
		: "=&r" (sr)
		: "r" (SR_DSP)
	);

	/* If the DSP bit is still set, this CPU has a DSP */
	if (sr & SR_DSP)
		current_cpu_data.flags |= CPU_HAS_DSP;

	/* Disable the DSP */
	if (dsp_disabled && (current_cpu_data.flags & CPU_HAS_DSP)) {
		printk("DSP Disabled\n");
		current_cpu_data.flags &= ~CPU_HAS_DSP;
	}

	/* Now that we've determined the DSP status, clear the DSP bit. */
	release_dsp();
}
#else
static inline void __cpuinit dsp_init(void) { }
#endif /* CONFIG_SH_DSP */

/**
 * cpu_init
 *
 * This is our initial entry point for each CPU, and is invoked on the
 * boot CPU prior to calling start_kernel(). For SMP, a combination of
 * this and start_secondary() will bring up each processor to a ready
 * state prior to hand forking the idle loop.
 *
 * We do all of the basic processor init here, including setting up
 * the caches, FPU, DSP, etc. By the time start_kernel() is hit (and
 * subsequently platform_setup()) things like determining the CPU
 * subtype and initial configuration will all be done.
 *
 * Each processor family is still responsible for doing its own probing
 * and cache configuration in cpu_probe().
 */
asmlinkage void __cpuinit cpu_init(void)
{
	current_thread_info()->cpu = hard_smp_processor_id();

	/* First, probe the CPU */
	cpu_probe();

	if (current_cpu_data.type == CPU_SH_NONE)
		panic("Unknown CPU");

	/* First setup the rest of the I-cache info */
	current_cpu_data.icache.entry_mask = current_cpu_data.icache.way_incr -
				      current_cpu_data.icache.linesz;

	current_cpu_data.icache.way_size = current_cpu_data.icache.sets *
				    current_cpu_data.icache.linesz;

	/* And the D-cache too */
	current_cpu_data.dcache.entry_mask = current_cpu_data.dcache.way_incr -
				      current_cpu_data.dcache.linesz;

	current_cpu_data.dcache.way_size = current_cpu_data.dcache.sets *
				    current_cpu_data.dcache.linesz;

	/* Init the cache */
	cache_init();

	if (raw_smp_processor_id() == 0) {
		shm_align_mask = max_t(unsigned long,
				       current_cpu_data.dcache.way_size - 1,
				       PAGE_SIZE - 1);

		/* Boot CPU sets the cache shape */
		detect_cache_shape();
	}

	fpu_init();
	dsp_init();

	/*
	 * Initialize the per-CPU ASID cache very early, since the
	 * TLB flushing routines depend on this being setup.
	 */
	current_cpu_data.asid_cache = NO_CONTEXT;

	current_cpu_data.phys_bits = __in_29bit_mode() ? 29 : 32;

	speculative_execution_init();
	expmask_init();

	/* Do the rest of the boot processor setup */
	if (raw_smp_processor_id() == 0) {
		/* Save off the BIOS VBR, if there is one */
		sh_bios_vbr_init();

		/*
		 * Setup VBR for boot CPU. Secondary CPUs do this through
		 * start_secondary().
		 */
		per_cpu_trap_init();

		/*
		 * Boot processor to setup the FP and extended state
		 * context info.
		 */
		init_thread_xstate();
	}
}

redpajama_set_name: RedPajamaGithub


text: from tinder.tinderClient import tinderClient


text:
Fabricator(:job_vacancy) do
  title "MyString"
end


text:
namespace lslboost {
namespace container {
namespace dtl {

template <class Container>
struct is_container
{
   static const bool value =
      lslboost::container::is_container_detail::
         has_member_function_callable_with_size <const Container>::value &&
      lslboost::container::is_container_detail::
         has_member_function_callable_with_empty<const Container>::value;
};

}  //namespace dtl {
}  //namespace container {
}  //namespace lslboost {

#endif   //#ifndef BOOST_CONTAINER_DETAIL_IS_CONTAINER_HPP


text:
  <fieldset>
    <legend>Name</legend>

      <input type="text" data-bind="textInput: filter.textFilter"></input>

  </fieldset>

  <fieldset>
    <legend>Origins</legend>

  </fieldset>

  <fieldset>
    <legend>Roles</legend>

      <select data-bind="options: filter.roles, optionsText: 'role_label', value: filter.selectedRole"></select>

  </fieldset>

  <fieldset>
    <legend>Alignment</legend>

  </fieldset>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.ComponentModel;
using System.IO;

namespace IPTV_Sharp
{

    public enum CrawlerStatus
    {
        Idle,
        Working,
        InvalidSite,
        CompletedWithResults,
        CompletedWithoutResults,
        Aborted
    }

    public class CrawlTaskData
    {
        public bool completed;
        public string result;
        public BackgroundWorker task;

        public CrawlTaskData()
        {
            completed = false;
            result = string.Empty;
            task = new BackgroundWorker();
        }
    }

    public class XtreamCrawler
    {
        private DictionaryManager dictionary;
        private WebClient client;
        private string server;
        private int concurrent_tasks;

        public int progress;
        public CrawlerStatus status;
        public int num_results=0;

        CrawlTaskData[] crawl_tasks;
        bool force_crawl;
        bool uppercase;

        public XtreamCrawler(DictionaryManager dictionary, string server, int concurrent_tasks, bool force_crawl, bool uppercase)
        {
            this.dictionary = dictionary;
            this.server = server;
            client = new WebClient();
            status = CrawlerStatus.Idle;
            this.concurrent_tasks = concurrent_tasks;
            this.force_crawl = force_crawl;
            this.uppercase = uppercase;
        }

        public void DoCrawl(object sender, DoWorkEventArgs e)
        {
            status = CrawlerStatus.Working;
            Crawl_Manager();
        }

        private void Crawl_Manager()
        {
            string output_result = string.Empty;
            bool found_result = false;
            progress = 0;
            num_results = 0;
            try
            {
                bool valid_site;
                if(force_crawl)
                {
                    valid_site = true;
                }
                else
                {
                    string page = client.DownloadString(server.Trim());
                    valid_site = page != "" && page.Contains("Xtream Codes");
                }

                if (valid_site && dictionary.entries.Count > 0)
                {

                    while (progress < dictionary.entries.Count)
                    {
                        int increment;
                        if ((progress + concurrent_tasks) < dictionary.entries.Count)
                        {
                            increment = concurrent_tasks;
                        }
                        else
                        {
                            increment = dictionary.entries.Count - progress;
                        }

                        crawl_tasks = new CrawlTaskData[increment];

                        for (int j = 0; j < crawl_tasks.Length; j++)
                        {
                            int x = progress + j;

                            string search_string;
                            if(uppercase)
                            {
                                search_string = dictionary.entries[x];
                            }
                            else
                            {
                                search_string = char.ToUpper(dictionary.entries[x][0]) + dictionary.entries[x].Substring(1);
                            }
                            crawl_tasks[j] = new CrawlTaskData();
                            crawl_tasks[j].task.WorkerSupportsCancellation = true;
                            crawl_tasks[j].task.WorkerReportsProgress = true;
                            crawl_tasks[j].task.DoWork += new DoWorkEventHandler(Crawl_Method);
                            var arguments = Tuple.Create<string, int>(search_string, j);
                            crawl_tasks[j].task.RunWorkerAsync(arguments);

                        }

                        WaitWorkers();

                        foreach (CrawlTaskData crawl_task in crawl_tasks)
                        {
                            if (crawl_task.result != string.Empty)
                            {
                                output_result = crawl_task.result;
                                found_result = true;
                                num_results++;
                                if (!Directory.Exists("output")) Directory.CreateDirectory("output");
                                string output = "output/tv_channels_" + num_results + ".m3u";
                                StreamWriter outputFile = new StreamWriter(output, true);
                                outputFile.WriteLine(output_result);
                                outputFile.Flush();
                                outputFile.Close();
                                outputFile.Dispose();
                            }
                        }

                        progress += increment;
                    }

                    if(found_result)
                    {
                        status = CrawlerStatus.CompletedWithResults;
                    }
                    else
                    {
                        status = CrawlerStatus.CompletedWithoutResults;
                    }
                }
                else
                {
                    status = CrawlerStatus.InvalidSite;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                status = CrawlerStatus.InvalidSite;
            }
        }

        private void WaitWorkers()
        {
            bool done;
            do
            {
                done = true;
                for (int i = 0; i < crawl_tasks.Length; i++)
                {
                    done = done && crawl_tasks[i].completed;
                }
            } while (!done);
        }

        private void Crawl_Method(object sender, DoWorkEventArgs e)
        {
            Tuple<string, int> arguments = e.Argument as Tuple<string, int>;

            string search_string = arguments.Item1;
            int index = arguments.Item2;

            try
            {
                string url = server.Trim() + "/get.php?username=" + search_string + "&password=" + search_string + "&type=m3u&output=mpegts";
                WebClient client = new WebClient();
                client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
                crawl_tasks[index].result = client.DownloadString(url);
            }
            catch(WebException ex)
            {
                Console.WriteLine(ex.Message);
            }

            crawl_tasks[index].completed = true;
        }

    }
}


text:
describe('PromiseHandler', function() {

    before(h.setupMultibrowser());

    it('should sync promises with call', function() {
        var result = '';
        return this.matrix.then(function() {
            result += '1';
        }).then(function() {
            result += '2';
        }).then(function() {
            result += '3';
        }).then(function() {
            result += '4';
        }).call(function() {
            result.should.be.equal('1234');
        });
    });

    it('should propagate results to then', function() {
        return this.matrix.getTitle().then(function(browserA, browserB) {
            browserA.should.be.equal('WebdriverJS Testpage');
            browserB.should.be.equal('WebdriverJS Testpage');
            return this.url();
        }).then(function(browserA, browserB) {
            browserA.value.should.be.equal(conf.testPage.start);
            browserB.value.should.be.equal(conf.testPage.start);
        }).then(function(result) {
            /**
             * undefined because last then doesn't return a promise
             */
            (result === undefined).should.be.true;
        });
    });

    it('should be working on custom commands', function() {
        var result = '';

        this.matrix.addCommand('fakeCommand', function(param) {
            return param;
        });

        return this.matrix.fakeCommand(0).then(function() {
            return this.fakeCommand(1);
        }).then(function(res) {
            result += res.toString();
            return this.fakeCommand(2);
        }).then(function(res) {
            result += res.toString();
            return this.fakeCommand(3);
        }).then(function(res) {
            result += res.toString();
            return this.fakeCommand(4);
        }).then(function(res) {
            result += res.toString();
        }).call(function() {
            result.should.be.equal('1234');
        });

    });

    it('should reject promise if command throws an error', function() {
        var result = null;
        return this.matrix.click('#notExisting').then(function() {
            result = false;
        }, function() {
            result = true;
        }).call(function() {
            result.should.be.equal(true);
        });
    });

    it('should handle waitfor commands within then callbacks', function() {
        return this.matrix.getTitle().then(function() {
            return this.pause(1000).pause(100).isVisible('body');
        }).then(function(browserA, browserB) {
            browserA.should.be.true;
            browserB.should.be.true;
        });
    });

    it('should provide a catch and fail method that executes if the command throws an error', function() {
        var gotExecutedCatch = false;
        return this.matrix.click('#notExisting').catch(function() {
            gotExecutedCatch = true;
        }).call(function() {
            gotExecutedCatch.should.be.true;
        });
    });

    it('should provide a catch and fail method that doesn\'t execute if the command passes', function() {
        var gotExecutedCatch = false;
        return this.matrix.click('body').catch(function() {
            gotExecutedCatch = true;
        }).call(function() {
            gotExecutedCatch.should.be.false;
        });
    });

    it('should propagate not only promises but also objects or strings', function() {
        var hasBeenExecuted = 0;
        return this.matrix.isVisible('body').then(function(browserA, browserB) {
            hasBeenExecuted++;
            return {
                browserA: browserA,
                browserB: browserB
            };
        }).then(function(isVisible) {
            hasBeenExecuted++;
            isVisible.browserA.should.be.true;
            isVisible.browserB.should.be.true;
            return 'a string';
        }).then(function(aString) {
            hasBeenExecuted++;
            aString.should.be.equal('a string');
            return { myElem: 42 };
        }).then(function(res) {
            hasBeenExecuted++;
            res.should.have.property('myElem');
            res.myElem.should.be.equal(42);
        }).call(function() {
            hasBeenExecuted.should.be.equal(4);
        });
    });

});


text:
package graph.state;

import graph.ClassNode;
import graph.Modifier;
import graph.Type;

import graph.instructions.Producer;

import java.util.Collections;
import java.util.EnumSet;
import java.util.List;

/**
 *
 */
public class Field implements State {
  private ClassNode         owner;
  private String            name;
  private EnumSet<Modifier> access;
  private Type              type;
  private Object            value;

  public Field(String name, Type type) {
    this.name  = name;
    this.type  = type;
    this.value = null;
  }

  public Field(String name, Type type, Object value) {
    this.name  = name;
    this.type  = type;
    this.value = value;
  }

  public Field(String name, String descriptor, Object value) {
    this.name  = name;
    this.type  = Type.getType(descriptor);
    this.value = value;
  }

  public Field(String name, String descriptor) {
    this.owner  = null;
    this.name   = name;
    this.access = EnumSet.noneOf(Modifier.class);
    this.type   = Type.getType(descriptor);
    this.value  = null;
  }

  public void setOwner(ClassNode clazz) {
    owner = clazz;
  }

  public ClassNode getOwner() {
    return owner;
  }

  public String getName() {
    return name;
  }

  public EnumSet<Modifier> getModifiers() {
    return access;
  }

  @Override
  public Type getType() {
    return type;
  }

  public void setDefaultValue(Object value) {
    this.value = value;
  }

  public Object getDefaultValue() {
    return value;
  }

  /**
   * Returns the static variable itself.
   *
   * @return       The static variable (this).
   */
  @Override
  public State getBase() {
    return this;
  }

  @Override
  public Producer[] getOperands() {
    return new Producer[0];
  }

  @Override
  public List<Producer> getIndicies() {
    return Collections.emptyList();
  }

  @Override
  public String toString() {
    return owner + "." + name + " [" + type + "]";
  }
}


text:
require 'test_helper'
require 'action_controller'

parameters_classes = [Delocalize::Parameters]

if defined?(ActionController::Parameters)
  # FIXME Can this happen automatically, e.g. by loading the Railtie?
  ActionController::Parameters.send(:include, Delocalize::ParameterDelocalizing)
  parameters_classes << ActionController::Parameters
end

puts "Testing parameter classes: #{parameters_classes.inspect}"

parameters_classes.each do |parameters_class|
  describe parameters_class do
    before do
      I18n.locale = I18n.default_locale
      Time.zone = 'Berlin' # make sure everything works as expected with TimeWithZone
    end

    it "delocalizes top level params based on the given options" do
      params = parameters_class.new(:released_on => '21. Mai 1986', :available_until => '25. Dezember 2013, 23:59 Uhr', :price => '1.299,99')

      delocalized_params = params.delocalize(:released_on => :date, :available_until => :time, :price => :number)

      delocalized_params[:released_on].must_equal Date.civil(1986, 5, 21)
      delocalized_params[:available_until].must_equal Time.zone.local(2013, 12, 25, 23, 59)
      delocalized_params[:price].must_equal '1299.99'
    end

    it "delocalizes nested params based on the given options" do
      params = parameters_class.new(:product => { :released_on => '21. Mai 1986', :available_until => '25. Dezember 2013, 23:59 Uhr', :price => '1.299,99' })

      delocalized_params = params.delocalize(:product => { :released_on => :date, :available_until => :time, :price => :number })

      delocalized_params[:product][:released_on].must_equal Date.civil(1986, 5, 21)
      delocalized_params[:product][:available_until].must_equal Time.zone.local(2013, 12, 25, 23, 59)
      delocalized_params[:product][:price].must_equal '1299.99'
    end

    it "delocalizes field-for type params based on the given options" do
      params = parameters_class.new(
          :product => {
              variant_attributes: {
                  "0" => { :released_on => '21. Mai 1986', :available_until => '25. Dezember 2013, 23:59 Uhr', :price => '1.299,99' },
                  "1" => { :released_on => '1. Juni 2001', :available_until => '12. November 2014, 00:00 Uhr', :price => '1.099,01' },
              }
          }
      )

      delocalized_params = params.delocalize(:product => { :variant_attributes => { :released_on => :date, :available_until => :time, :price => :number } })

      delocalized_params[:product][:variant_attributes]['0'][:released_on].must_equal Date.civil(1986, 5, 21)
      delocalized_params[:product][:variant_attributes]['0'][:available_until].must_equal Time.zone.local(2013, 12, 25, 23, 59)
      delocalized_params[:product][:variant_attributes]['0'][:price].must_equal '1299.99'

      delocalized_params[:product][:variant_attributes]['1'][:released_on].must_equal Date.civil(2001, 6, 1)
      delocalized_params[:product][:variant_attributes]['1'][:available_until].must_equal Time.zone.local(2014, 11, 12, 00, 00)
      delocalized_params[:product][:variant_attributes]['1'][:price].must_equal '1099.01'
    end

    it "delocalizes nested params on the key itself based on the given options" do
      params = parameters_class.new(:product => { :released_on => '21. Mai 1986', :available_until => '25. Dezember 2013, 23:59 Uhr', :price => '1.299,99' })

      product_params = params[:product].delocalize(:released_on => :date, :available_until => :time, :price => :number)

      product_params[:released_on].must_equal Date.civil(1986, 5, 21)
      product_params[:available_until].must_equal Time.zone.local(2013, 12, 25, 23, 59)
      product_params[:price].must_equal '1299.99'
    end

    it "delocalizes deeply nested params for one-to-one based on the given  options" do
      params = parameters_class.new(:parent => { :child => { :child_date => '21. Mai 1986', :child_time => '25. Dezember 2013, 23:59 Uhr', :child_number => '1.299,99' } })

      delocalized_params = params.delocalize(:parent => { :child => { :child_date => :date, :child_time => :time, :child_number => :number } })

      delocalized_params[:parent][:child][:child_date].must_equal Date.civil(1986, 5, 21)
      delocalized_params[:parent][:child][:child_time].must_equal Time.zone.local(2013, 12, 25, 23, 59)
      delocalized_params[:parent][:child][:child_number].must_equal '1299.99'
    end

    it "delocalizes deeply nested params for one-to-one on the key itself based on the given  options" do
      params = parameters_class.new(:parent => { :child => { :child_date => '21. Mai 1986', :child_time => '25. Dezember 2013, 23:59 Uhr', :child_number => '1.299,99' } })

      parent_params = params[:parent].delocalize(:child => { :child_date => :date, :child_time => :time, :child_number => :number })

      parent_params[:child][:child_date].must_equal Date.civil(1986, 5, 21)
      parent_params[:child][:child_time].must_equal Time.zone.local(2013, 12, 25, 23, 59)
      parent_params[:child][:child_number].must_equal '1299.99'
    end

    it "delocalizes all the things at all the levels of all the types" do
      delocalize_options = {
        :top_level_date => :date,
        :top_level_time => :time,
        :top_level_number => :number,
        :parent => {
          :parent_date => :date,
          :parent_time => :time,
          :parent_number => :number,
          :child => {
            :child_date => :date,
            :child_time => :time,
            :child_number => :number
          }
        }
      }

      params = parameters_class.new(
        :top_level_date => '21. Mai 1986',
        :top_level_time => '25. Dezember 2013, 23:59 Uhr',
        :top_level_number => '1.299,99',
        :parent => {
          :parent_date => '21. Mai 2004',
          :parent_time => '24. Dezember 2013, 23:59 Uhr',
          :parent_number => '999,99',
          :child => {
            :child_date => '21. Mai 2011',
            :child_time => '31. Dezember 2013, 23:59 Uhr',
            :child_number => '9.999'
          }
        }
      )

      delocalized_params = params.delocalize(delocalize_options)

      delocalized_params[:top_level_date].must_equal Date.civil(1986, 5, 21)
      delocalized_params[:top_level_time].must_equal Time.zone.local(2013, 12, 25, 23, 59)
      delocalized_params[:top_level_number].must_equal '1299.99'

      delocalized_params[:parent][:parent_date].must_equal Date.civil(2004, 5, 21)
      delocalized_params[:parent][:parent_time].must_equal Time.zone.local(2013, 12, 24, 23, 59)
      delocalized_params[:parent][:parent_number].must_equal '999.99'

      delocalized_params[:parent][:child][:child_date].must_equal Date.civil(2011, 5, 21)
      delocalized_params[:parent][:child][:child_time].must_equal Time.zone.local(2013, 12, 31, 23, 59)
      delocalized_params[:parent][:child][:child_number].must_equal '9999'
    end

    # TODO Figure out deeply nested params for one-to-many relations.
    # The problem is that one-to-many relations may be given as a hash or an array. Delocalize should
    # be able both cases just fine.

    it "fails for a non-existent type" do
      params = parameters_class.new(:available_until => '25. Dezember 2013, 23:59 Uhr')

      ->{ params.delocalize(:available_until => :datetime) }.must_raise(Delocalize::ParserNotFound)
    end

    it "keeps unconfigured parameters as they are while still delocalizing others" do
      params = parameters_class.new(:released_on => '1986-05-21', :price => '1.299,99')

      delocalized_params = params.delocalize(:price => :number)

      delocalized_params[:released_on].must_equal '1986-05-21'
      delocalized_params[:price].must_equal '1299.99'
    end

    it "doesn't raise when nested params given and which aren't defined in options" do
      params = parameters_class.new(:parent => { :parent_date => '21. Mai 2004' })

      ## Should not throw an error:
      params.delocalize({})
    end

    it "delocalizes arrays" do
      params = parameters_class.new(:location => ['13,456', '51,234'], :interval => ['25. Dezember 2013', '31. Januar 2014'])

      delocalized_params = params.delocalize(:location => [:number], interval: [:date])

      delocalized_params[:location].must_equal ['13.456', '51.234']
      delocalized_params[:interval].must_equal [Date.civil(2013, 12, 25), Date.civil(2014, 1, 31)]
    end

    it "keeps invalid dates in the params hash" do
      params = parameters_class.new(:first_date => "asdf", :second_date => "02.0.2017", :third_date => "02.123.2017")

      delocalized_params = params.delocalize(:first_date => :date, :second_date => :date, :third_date => :date)

      delocalized_params[:first_date].must_equal "asdf"
      delocalized_params[:second_date].must_equal "02.0.2017"
      delocalized_params[:third_date].must_equal "02.123.2017"
    end
  end
end


text:
package ca.uhn.fhir.context.copy;

import java.io.IOException;

import org.apache.commons.io.IOUtils;

import ca.uhn.fhir.model.base.composite.BaseResourceReferenceDt;
import ca.uhn.fhir.model.dstu.resource.DiagnosticReport;

public class Perf {

	private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(Perf.class);

	public static void main(String[] args) throws Exception {

		FhirContext ctx = FhirContext.forDstu1();

		String str = IOUtils.toString(Perf.class.getResourceAsStream("/contained-diagnosticreport-singlecontainedelement.xml"));
		DiagnosticReport rept = ctx.newXmlParser().parseResource(DiagnosticReport.class, str);

		long start = System.currentTimeMillis();

		for (int i = 0; i < 100000; i++) {
			if (i % 10 == 0) {
				ourLog.info("Rep: " + i);
			}
			ctx.newTerser().getAllPopulatedChildElementsOfType(rept, BaseResourceReferenceDt.class);
		}

		long delay = System.currentTimeMillis() - start;
		ourLog.info("Took: {} ms", delay);
	}

}


text:
'use strict';

import _objectSpread from "@babel/runtime/helpers/objectSpread2";
import { AnimatedEvent, attachNativeEvent } from './AnimatedEvent';
import AnimatedImplementation from './AnimatedImplementation';
import AnimatedInterpolation from './nodes/AnimatedInterpolation';
import AnimatedNode from './nodes/AnimatedNode';
import AnimatedValue from './nodes/AnimatedValue';
import AnimatedValueXY from './nodes/AnimatedValueXY';
import createAnimatedComponent from './createAnimatedComponent';
import AnimatedColor from './nodes/AnimatedColor';
/**
 * Animations are a source of flakiness in snapshot testing. This mock replaces
 * animation functions from AnimatedImplementation with empty animations for
 * predictability in tests. When possible the animation will run immediately
 * to the final state.
 */
// Prevent any callback invocation from recursively triggering another
// callback, which may trigger another animation

var inAnimationCallback = false;

function mockAnimationStart(start) {
  return callback => {
    var guardedCallback = callback == null ? callback : function () {
      if (inAnimationCallback) {
        console.warn('Ignoring recursive animation callback when running mock animations');
        return;
      }

      inAnimationCallback = true;

      try {
        callback(...arguments);
      } finally {
        inAnimationCallback = false;
      }
    };
    start(guardedCallback);
  };
}

var emptyAnimation = {
  start: () => {},
  stop: () => {},
  reset: () => {},
  _startNativeLoop: () => {},
  _isUsingNativeDriver: () => {
    return false;
  }
};

var mockCompositeAnimation = animations => _objectSpread(_objectSpread({}, emptyAnimation), {}, {
  start: mockAnimationStart(callback => {
    animations.forEach(animation => animation.start());
    callback == null ? void 0 : callback({
      finished: true
    });
  })
});

var spring = function spring(value, config) {
  var anyValue = value;
  return _objectSpread(_objectSpread({}, emptyAnimation), {}, {
    start: mockAnimationStart(callback => {
      anyValue.setValue(config.toValue);
      callback == null ? void 0 : callback({
        finished: true
      });
    })
  });
};

var timing = function timing(value, config) {
  var anyValue = value;
  return _objectSpread(_objectSpread({}, emptyAnimation), {}, {
    start: mockAnimationStart(callback => {
      anyValue.setValue(config.toValue);
      callback == null ? void 0 : callback({
        finished: true
      });
    })
  });
};

var decay = function decay(value, config) {
  return emptyAnimation;
};

var sequence = function sequence(animations) {
  return mockCompositeAnimation(animations);
};

var parallel = function parallel(animations, config) {
  return mockCompositeAnimation(animations);
};

var delay = function delay(time) {
  return emptyAnimation;
};

var stagger = function stagger(time, animations) {
  return mockCompositeAnimation(animations);
};

var loop = function loop(animation, // $FlowFixMe[prop-missing]
_temp) {
  var _ref = _temp === void 0 ? {} : _temp,
      _ref$iterations = _ref.iterations,
      iterations = _ref$iterations === void 0 ? -1 : _ref$iterations;

  return emptyAnimation;
};

export default {
  Value: AnimatedValue,
  ValueXY: AnimatedValueXY,
  Color: AnimatedColor,
  Interpolation: AnimatedInterpolation,
  Node: AnimatedNode,
  decay,
  timing,
  spring,
  add: AnimatedImplementation.add,
  subtract: AnimatedImplementation.subtract,
  divide: AnimatedImplementation.divide,
  multiply: AnimatedImplementation.multiply,
  modulo: AnimatedImplementation.modulo,
  diffClamp: AnimatedImplementation.diffClamp,
  delay,
  sequence,
  parallel,
  stagger,
  loop,
  event: AnimatedImplementation.event,
  createAnimatedComponent,
  attachNativeEvent,
  forkEvent: AnimatedImplementation.forkEvent,
  unforkEvent: AnimatedImplementation.unforkEvent,
  Event: AnimatedEvent
};


text:
package com.intellij.vcs.log.ui.actions;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.vcs.log.impl.CommonUiProperties;
import com.intellij.vcs.log.impl.VcsLogUiProperties;
import com.intellij.vcs.log.ui.VcsLogInternalDataKeys;
import com.intellij.vcs.log.ui.VcsLogUiEx;
import org.jetbrains.annotations.NotNull;

public class ShowRootsColumnAction extends BooleanPropertyToggleAction {

  public ShowRootsColumnAction() {
    super("Show Root Names");
  }

  @Override
  protected VcsLogUiProperties.VcsLogUiProperty<Boolean> getProperty() {
    return CommonUiProperties.SHOW_ROOT_NAMES;
  }

  @Override
  public void update(@NotNull AnActionEvent e) {
    super.update(e);
    VcsLogUiEx ui = e.getData(VcsLogInternalDataKeys.LOG_UI_EX);
    if (ui == null || !ui.getColorManager().hasMultiplePaths()) e.getPresentation().setEnabledAndVisible(false);
  }
}


text:
<?php
namespace factory;

class BenzFactory implements Factory
{
	public function getCar()
	{
		return new Benz();
	}
}


text:
package main

import (
	"time"
	"github.com/crabkun/DazeClient/proxy"
	"github.com/crabkun/go-args"
	"github.com/crabkun/DazeClient/control"
	"github.com/crabkun/DazeClient/helper"

	"log"
)

func main(){
	var ShowNetSpeed bool=true
	log.Println("DazeClient V3-201710051")
	args:=go_args.ReadArgs()
	//判断是否开启被控模式
	ControlAddress,ControlFlag:=args.GetArg("-control-address")
	if ControlFlag{
		go control.StartControlServer(ControlAddress)
		ShowNetSpeed=false
		goto idle
	}
	//判断是否指定了配置文件
	if path,flag:=args.GetArg("-conf");flag{
		helper.ConfFile=path
	}
	if pac,flag:=args.GetArg("-pac");flag{
		helper.PacFile=pac
	}
	helper.LoadConfig()
	proxy.StartProxy()
	idle:
	go proxy.NetSpeedMonitor(ShowNetSpeed)
	for{
		time.Sleep(time.Second*3600)
	}
}


text:
//
//  AFN_HS.h
//  KenshinPro
//
//  Created by kenshin on 17/4/18.
//  Copyright © 2017年 Kenshin. All rights reserved.
//

#import <Foundation/Foundation.h>
//封装在 HS 工作时期所用的网络请求

#define IS_PRINT_LOG YES

@interface AFN_HS : NSObject

/**
 网络请求响应代码块

 @param success     请求成功
 @param resultDic   请求结果
 @param errorMsg    请求失败描述
 */
typedef void(^HSResultBlock) (BOOL success, NSDictionary *resultDic, NSString *errorMsg);

/**
 POST 请求

 @param url         请求地址
 @param params      请求参数
 @param resultBlock 响应代码块
 */
+ (void)postWithUrl:(NSString *)url params:(NSDictionary *)params resultBlock:(HSResultBlock)resultBlock;

/**
 GET 请求 代码和POST请求一直 只是请求方式变了

 @param url         请求地址
 @param params      请求参数
 @param resultBlock 响应代码块
 */
+ (void)getWithUrl:(NSString *)url params:(NSDictionary *)params resultBlock:(HSResultBlock)resultBlock;

@end


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="">

  <title>Quinn Research Group - University of Georgia</title>

  <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

  <link href="css/modern-business.css" rel="stylesheet">

  <link href="css/fontawesome/css/all.min.css" rel="stylesheet">

      Quinn Research Group
      <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">

      </button>

            NSF CAREER

            Research

            News

            Podcast

            People

            Publications

            Presentations

            Courses

Ciliary motion analysis

Dynamic texture recognition of ciliary motion

Organellar Networks

Social networks for understanding mitochondrial morphology

Spatiotemporal modeling

Predicting flu and asthma incidence rates

Toxoplasma gondii motion analysis

Studying motility and dynamics in response to drugs

Scalable Neuroimaging

Studying neurodegeneration at tera- and peta-scales

Generative Modeling

Building parametric generative spatiotemoporal models of biological phenomena

Open Source Development

Contributing to the Open Science ecosystem

Precision Agriculture

Multi-agent multimodal monitoring of crops

        Last

        Next

Data Science for Public Health

 Big Imaging

Scalable machine learning, computer vision, and generative modeling.

 Public Health

Translational medicine, bioimaging, and disease surveillance and prediction.

 Open Science

Active contributors to open source projects and advocates for Open Science principles and practices.

Selected Projects

              Ciliary motion analysis

              Organellar networks

              T. gondii motility modeling

              Neuroimaging

              Biosurveillance

              Representation learning

Group Openings

We are an interdisciplinary group, primarily focused on how data science can be a tool for knowledge discovery in public health applications.

I am currently on sabbatical, working with Quansight to help develop the PyData ecosystem. As such, I am NOT able to accept new students through at least May 2023. I apologize for any inconvenience.

When recruiting resumes, we are looking for students with backgrounds and interests in:

statistical machine learning

computer vision

deep learning

generative models

spectral graph analytics

distributed computing

cellular biology

disease modeling

open source coding

If you are interested in pursuing interdisciplinary research in my group, please read this blog post and follow its instructions for contacting me.

If you're interested in learning more about the work we do, email me!

        Email

Copyright © Quinn Research Group 2022


text:
'''
'''
#  Licensed to the Apache Software Foundation (ASF) under one
#  or more contributor license agreements.  See the NOTICE file
#  distributed with this work for additional information
#  regarding copyright ownership.  The ASF licenses this file
#  to you under the Apache License, Version 2.0 (the
#  "License"); you may not use this file except in compliance
#  with the License.  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import os

Test.Summary = 'Test TSContScheduleOnThread API'
Test.ContinueOnFail = True

# Define default ATS
ts = Test.MakeATSProcess('ts')

Test.testName = 'Test TSContScheduleOnThread API'

ts.Disk.records_config.update({
    'proxy.config.exec_thread.autoconfig': 0,
    'proxy.config.exec_thread.autoconfig.scale': 1.5,
    'proxy.config.exec_thread.limit': 32,
    'proxy.config.accept_threads': 1,
    'proxy.config.task_threads': 2,
    'proxy.config.diags.debug.enabled': 1,
    'proxy.config.diags.debug.tags': 'TSContSchedule_test'
})

# Load plugin
Test.PrepareTestPlugin(os.path.join(Test.Variables.AtsTestPluginsDir, 'cont_schedule.so'), ts, 'thread')

# www.example.com Host
tr = Test.AddTestRun()
tr.Processes.Default.Command = 'printf "Test TSContScheduleOnThread API"'
tr.Processes.Default.ReturnCode = 0
tr.Processes.Default.StartBefore(ts)
ts.Streams.All = "gold/schedule_on_thread.gold"
ts.Streams.All += Testers.ExcludesExpression('fail', 'should not contain "fail"')


text:
package DDS;

public interface DURATION_INFINITE
{
  public static final DDS.Duration_t value = new DDS.Duration_t(
      DURATION_INFINITE_SEC.value, DURATION_INFINITE_NSEC.value );
}


text:
<!DOCTYPE html>

    <title>InstagramComment Structure Reference</title>
    <link rel="stylesheet" type="text/css" href="../css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="../css/highlight.css" />
    <meta charset="utf-8">

          SwiftInstagram Docs

         (100% documented)

        <form role="search" action="../search.json">
          <input type="text" placeholder="Search documentation" data-typeahead>
        </form>

            View on GitHub

      SwiftInstagram Reference

      InstagramComment Structure Reference

            API

                Instagram

            Authentication

                InstagramScope

            Models

                InstagramUser

                – Counts

                InstagramRelationship

                InstagramMedia

                – Count

                – Resolution

                – Images

                – Videos

                – UserInPhoto

                – CarouselMedia

                InstagramComment

                InstagramTag

                InstagramLocation

            Errors

                InstagramError

            Other Structures

                InstagramEmptyResponse

InstagramComment

public struct InstagramComment : Decodable

The struct containing an Instagram comment.

Properties

                    id

The comment identifier.

Declaration

Swift

public let id: String

                    text

The comment text.

Declaration

Swift

public let text: String

                    from

The user who created the comment.

Declaration

Swift

public let from: InstagramUser

                    createdDate

The date and time when the comment was created.

Declaration

Swift

public let createdDate: Date

Initializers

                    init(from:)

Declaration

Swift

public init(from decoder: Decoder) throws

© 2018 Ander Goig. All rights reserved. (Last updated: 2018-10-14)

Generated by jazzy ♪♫ v0.9.3, a Realm project.


text:
Title: Visibility Analysis Webinar
Date: 2010-11-20 11:47:06
Category: Riskblog
Tags: Aggregated_Blogs
Slug: visibility-analysis-webinar-jonesj-2010-11-20-11:47:06
Author: JonesJ

>[Visibility Analysis Webinar](http://feedproxy.google.com/~r/Riskanalysis/~3/97CZMAyrQ5U/) originally posted at [RiskAnalys.is](http://riskmanagementinsight.com/riskanalysis) and syndicated at [SIRA](http://societyinforisk.org)
***
The Visibility Analysis webinar on Wednesday was very well attended and has received excellent feedback.  My thanks to everyone who showed up.  If you couldn't make it, you can find the recording [here](https://cisco.webex.com/ciscosales/lsr.php?AT=pb&SP=EC&rID=47606012&rKey=a40fcbcc2bf840f7).

Also, those who attended the webinar are eligible for a 20% discount on our online FAIR training.  Please just contact me before you register so that I can give you a discount code to use.

Thanks!

Jack

![img](http://feeds.feedburner.com/~r/Riskanalysis/~4/97CZMAyrQ5U)


text:
"""
    KubeVirt API

    This is KubeVirt API an add-on for Kubernetes.

    OpenAPI spec version: 1.0.0
    Contact: kubevirt-dev@googlegroups.com
    Generated by: https://github.com/swagger-api/swagger-codegen.git
"""

from __future__ import absolute_import

import os
import sys
import unittest

import kubevirt
from kubevirt.rest import ApiException
from kubevirt.models.v1alpha2_virtual_machine_cluster_preference import V1alpha2VirtualMachineClusterPreference

class TestV1alpha2VirtualMachineClusterPreference(unittest.TestCase):
    """ V1alpha2VirtualMachineClusterPreference unit test stubs """

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def testV1alpha2VirtualMachineClusterPreference(self):
        """
        Test V1alpha2VirtualMachineClusterPreference
        """
        # FIXME: construct object with mandatory attributes with example values
        #model = kubevirt.models.v1alpha2_virtual_machine_cluster_preference.V1alpha2VirtualMachineClusterPreference()
        pass

if __name__ == '__main__':
    unittest.main()


text: Front-end application for Tournme in angular2 and typescript


text:
(function ($data, $) {

    var entityValidator = $data.Validation.Entity;
    var dateConverter = function (stringDate) {
        try {
            return new Date(Date.parse(stringDate));
        } catch (e) {
            return new Date(0);
        }
    };

    var validationMapping = {
        required: { key: 'required' },
        minValue: { key: 'min', validateMethod: true, converter: dateConverter },
        maxValue: { key: 'max', validateMethod: true, converter: dateConverter },
        length: { key: 'length' },
        minLength: { key: 'minlength' },
        maxLength: { key: 'maxlength' },
        regex: { key: 'regex', validateMethod: true },
        customValidator: { key: 'customValidator', validateMethod: true }
    };

    var defaultValidationOption = {
        required: { key: 'required' },
        customValidator: { key: 'customValidator', validateMethod: true }
    };

    var numberValidationOption = {
        required: { key: 'required' },
        customValidator: { key: 'customValidator', validateMethod: true },
        minValue: { key: 'min' },
        maxValue: { key: 'max' }
    };

    var supportedValidations = {
        '$data.Number': numberValidationOption,
        '$data.Float': numberValidationOption,
        '$data.Decimal': numberValidationOption,
        '$data.Integer': numberValidationOption,
        '$data.Int16': numberValidationOption,
        '$data.Int32': numberValidationOption,
        '$data.Int64': numberValidationOption,
        '$data.Byte': numberValidationOption,
        '$data.SByte': numberValidationOption,
        '$data.String': {
            required: { key: 'required' },
            customValidator: { key: 'customValidator', validateMethod: true },
            minLength: { key: 'minlength' },
            maxLength: { key: 'maxlength' },
            length: { key: 'length' },
            regex: { key: 'regex', validateMethod: true }
        },
        '$data.Date': {
            required: { key: 'required' },
            customValidator: { key: 'customValidator', validateMethod: true },
            minValue: { key: 'min', validateMethod: true, converter: dateConverter },
            maxValue: { key: 'max', validateMethod: true, converter: dateConverter }
        },
        '$data.DateTimeOffset': {
            required: { key: 'required' },
            customValidator: { key: 'customValidator', validateMethod: true },
            minValue: { key: 'min', validateMethod: true, converter: dateConverter },
            maxValue: { key: 'max', validateMethod: true, converter: dateConverter }
        },
        '$data.Time': {
            required: { key: 'required' },
            customValidator: { key: 'customValidator', validateMethod: true },
            minValue: { key: 'min' },
            maxValue: { key: 'max' }
        },
        '$data.Array': {
            required: { key: 'required' },
            customValidator: { key: 'customValidator', validateMethod: true },
            length: { key: 'length', validateMethod: true }
        },
        '$data.Boolean': defaultValidationOption,
        '$data.Object': defaultValidationOption
    };

    var createValidationItem = function (memDef, rule, typeName, result) {
        if (memDef[rule]) {
            var validation = supportedValidations[typeName][rule];
            var ruleName = validation.key;
            var ruleValue = entityValidator.getValidationValue(memDef, rule);
            if (validation.validateMethod === true) {
                ruleName = memDef.name + '_' + ruleName;
                $.validator.addMethod(ruleName, function (value, element) {
                    if (!value)
                        value = undefined;

                    if (value && validation.converter && typeof validation.converter == "function")
                        value = validation.converter(value);

                    return entityValidator.supportedValidations[typeName][rule](value, ruleValue);
                }, entityValidator.getValidationMessage(memDef, rule, 'Validation Error!'));
                result.rules[memDef.name] = result.rules[memDef.name] || {};
                result.rules[memDef.name][ruleName] = true;
                return;
            }
            else {
                result.rules[memDef.name] = result.rules[memDef.name] || {};
                result.rules[memDef.name][ruleName] = ruleValue;
            }

            var message = entityValidator.getValidationMessage(memDef, rule);
            if (message) {
                result.messages[memDef.name] = result.messages[memDef.name] || {};
                result.messages[memDef.name][ruleName] = message;
            }

        }
    };

    var buildValidationModel = function (type, result) {
        type.memberDefinitions.getPublicMappedProperties().forEach(function (memDef) {
            var typeName = Container.resolveName(Container.resolveType(memDef.dataType));
            if (supportedValidations[typeName]) {
                var validations = Object.keys(supportedValidations[typeName]);
                validations.forEach(function (validation) {
                    createValidationItem(memDef, validation, typeName, result);
                });
            }
        });
    };

    $data.Entity.prototype.toJQueryValidate = function (callBack) {
        if (typeof $ === 'undefined' || typeof $.validator === 'undefined') {
            Guard.raise(new Exception('jQuery and jQuery validator plugin is required', 'Not Found!'));
        }
        var model = this;

        var validateResult = { rules: {}, messages: {} };
        buildValidationModel(model.getType(), validateResult);

        callBack = $data.typeSystem.createCallbackSetting(callBack, {});
        if (callBack.success) {
            var origCallback = callBack.success;
            callBack.success = function (form, event) {
                if ($.fn.formBinder)
                    $(form).formBinder(model, false);
                origCallback.apply(this, [model, form, event]);
            };
        }
        if (typeof callBack.success == "function")
            validateResult.submitHandler = callBack.success;
        if (typeof callBack.error == "function")
            validateResult.invalidHandler = callBack.error;
        return validateResult;
    };

})($data, jQuery);


text:
class Address
  include Mongoid::Document
  field :address_type
  field :number, :type => Integer
  field :street
  field :city
  field :state
  field :post_code
  field :parent_title
  field :services, :type => Array
  key :street
  embeds_many :locations

  embedded_in :addressable, :inverse_of => :addresses do
    def extension
      "Testing"
    end
    def doctor?
      title == "Dr"
    end
  end

  named_scope :rodeo, where(:street => "Rodeo Dr")

  def set_parent=(set = false)
    self.parent_title = addressable.title if set
  end

  class << self
    def california
      where(:state => "CA")
    end

    def homes
      where(:address_type => "Home")
    end

  end
end


text:
package etcd

import (
	"bytes"
	"context"
	"fmt"
	"strings"
	"time"

	"go.etcd.io/etcd/client/v3"

	"github.com/chrislusf/seaweedfs/weed/filer"
	"github.com/chrislusf/seaweedfs/weed/glog"
	"github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
	weed_util "github.com/chrislusf/seaweedfs/weed/util"
)

const (
	DIR_FILE_SEPARATOR = byte(0x00)
)

func init() {
	filer.Stores = append(filer.Stores, &EtcdStore{})
}

type EtcdStore struct {
	client *clientv3.Client
}

func (store *EtcdStore) GetName() string {
	return "etcd"
}

func (store *EtcdStore) Initialize(configuration weed_util.Configuration, prefix string) (err error) {
	servers := configuration.GetString(prefix + "servers")
	if servers == "" {
		servers = "localhost:2379"
	}

	timeout := configuration.GetString(prefix + "timeout")
	if timeout == "" {
		timeout = "3s"
	}

	return store.initialize(servers, timeout)
}

func (store *EtcdStore) initialize(servers string, timeout string) (err error) {
	glog.Infof("filer store etcd: %s", servers)

	to, err := time.ParseDuration(timeout)
	if err != nil {
		return fmt.Errorf("parse timeout %s: %s", timeout, err)
	}

	store.client, err = clientv3.New(clientv3.Config{
		Endpoints:   strings.Split(servers, ","),
		DialTimeout: to,
	})
	if err != nil {
		return fmt.Errorf("connect to etcd %s: %s", servers, err)
	}

	return
}

func (store *EtcdStore) BeginTransaction(ctx context.Context) (context.Context, error) {
	return ctx, nil
}
func (store *EtcdStore) CommitTransaction(ctx context.Context) error {
	return nil
}
func (store *EtcdStore) RollbackTransaction(ctx context.Context) error {
	return nil
}

func (store *EtcdStore) InsertEntry(ctx context.Context, entry *filer.Entry) (err error) {
	key := genKey(entry.DirAndName())

	meta, err := entry.EncodeAttributesAndChunks()
	if err != nil {
		return fmt.Errorf("encoding %s %+v: %v", entry.FullPath, entry.Attr, err)
	}

	if len(entry.Chunks) > filer.CountEntryChunksForGzip {
		meta = weed_util.MaybeGzipData(meta)
	}

	if _, err := store.client.Put(ctx, string(key), string(meta)); err != nil {
		return fmt.Errorf("persisting %s : %v", entry.FullPath, err)
	}

	return nil
}

func (store *EtcdStore) UpdateEntry(ctx context.Context, entry *filer.Entry) (err error) {
	return store.InsertEntry(ctx, entry)
}

func (store *EtcdStore) FindEntry(ctx context.Context, fullpath weed_util.FullPath) (entry *filer.Entry, err error) {
	key := genKey(fullpath.DirAndName())

	resp, err := store.client.Get(ctx, string(key))
	if err != nil {
		return nil, fmt.Errorf("get %s : %v", fullpath, err)
	}

	if len(resp.Kvs) == 0 {
		return nil, filer_pb.ErrNotFound
	}

	entry = &filer.Entry{
		FullPath: fullpath,
	}
	err = entry.DecodeAttributesAndChunks(weed_util.MaybeDecompressData(resp.Kvs[0].Value))
	if err != nil {
		return entry, fmt.Errorf("decode %s : %v", entry.FullPath, err)
	}

	return entry, nil
}

func (store *EtcdStore) DeleteEntry(ctx context.Context, fullpath weed_util.FullPath) (err error) {
	key := genKey(fullpath.DirAndName())

	if _, err := store.client.Delete(ctx, string(key)); err != nil {
		return fmt.Errorf("delete %s : %v", fullpath, err)
	}

	return nil
}

func (store *EtcdStore) DeleteFolderChildren(ctx context.Context, fullpath weed_util.FullPath) (err error) {
	directoryPrefix := genDirectoryKeyPrefix(fullpath, "")

	if _, err := store.client.Delete(ctx, string(directoryPrefix), clientv3.WithPrefix()); err != nil {
		return fmt.Errorf("deleteFolderChildren %s : %v", fullpath, err)
	}

	return nil
}

func (store *EtcdStore) ListDirectoryPrefixedEntries(ctx context.Context, dirPath weed_util.FullPath, startFileName string, includeStartFile bool, limit int64, prefix string, eachEntryFunc filer.ListEachEntryFunc) (lastFileName string, err error) {
	return lastFileName, filer.ErrUnsupportedListDirectoryPrefixed
}

func (store *EtcdStore) ListDirectoryEntries(ctx context.Context, dirPath weed_util.FullPath, startFileName string, includeStartFile bool, limit int64, eachEntryFunc filer.ListEachEntryFunc) (lastFileName string, err error) {
	directoryPrefix := genDirectoryKeyPrefix(dirPath, "")
	lastFileStart := directoryPrefix
	if startFileName != "" {
		lastFileStart = genDirectoryKeyPrefix(dirPath, startFileName)
	}

	resp, err := store.client.Get(ctx, string(lastFileStart),
		clientv3.WithFromKey(), clientv3.WithLimit(limit+1))
	if err != nil {
		return lastFileName, fmt.Errorf("list %s : %v", dirPath, err)
	}

	for _, kv := range resp.Kvs {
		if !bytes.HasPrefix(kv.Key, directoryPrefix) {
			break
		}
		fileName := getNameFromKey(kv.Key)
		if fileName == "" {
			continue
		}
		if fileName == startFileName && !includeStartFile {
			continue
		}
		limit--
		if limit < 0 {
			break
		}
		entry := &filer.Entry{
			FullPath: weed_util.NewFullPath(string(dirPath), fileName),
		}
		if decodeErr := entry.DecodeAttributesAndChunks(weed_util.MaybeDecompressData(kv.Value)); decodeErr != nil {
			err = decodeErr
			glog.V(0).Infof("list %s : %v", entry.FullPath, err)
			break
		}
		if !eachEntryFunc(entry) {
			break
		}
		lastFileName = fileName
	}

	return lastFileName, err
}

func genKey(dirPath, fileName string) (key []byte) {
	key = []byte(dirPath)
	key = append(key, DIR_FILE_SEPARATOR)
	key = append(key, []byte(fileName)...)
	return key
}

func genDirectoryKeyPrefix(fullpath weed_util.FullPath, startFileName string) (keyPrefix []byte) {
	keyPrefix = []byte(string(fullpath))
	keyPrefix = append(keyPrefix, DIR_FILE_SEPARATOR)
	if len(startFileName) > 0 {
		keyPrefix = append(keyPrefix, []byte(startFileName)...)
	}
	return keyPrefix
}

func getNameFromKey(key []byte) string {
	sepIndex := len(key) - 1
	for sepIndex >= 0 && key[sepIndex] != DIR_FILE_SEPARATOR {
		sepIndex--
	}

	return string(key[sepIndex+1:])
}

func (store *EtcdStore) Shutdown() {
	store.client.Close()
}


text:
//===--- TypeCheckTypeWrapper.cpp - type wrappers -------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements semantic analysis for type wrappers.
//
//===----------------------------------------------------------------------===//
#include "TypeChecker.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Decl.h"
#include "swift/AST/NameLookupRequests.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/Stmt.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/Basic/LLVM.h"
#include "swift/Basic/SourceLoc.h"

using namespace swift;

static PatternBindingDecl *injectVariable(DeclContext *DC, Identifier name,
                                          Type type,
                                          VarDecl::Introducer introducer,
                                          Expr *initializer = nullptr) {
  auto &ctx = DC->getASTContext();

  auto *var = new (ctx) VarDecl(/*isStatic=*/false, introducer,
                                /*nameLoc=*/SourceLoc(), name, DC);

  var->setImplicit();
  var->setSynthesized();
  var->setInterfaceType(type);

  Pattern *pattern = NamedPattern::createImplicit(ctx, var);
  pattern->setType(type);

  pattern = TypedPattern::createImplicit(ctx, pattern, type);

  return PatternBindingDecl::createImplicit(ctx, StaticSpellingKind::None,
                                            pattern, initializer, DC);
}

/// Create a property declaration and inject it into the given type.
static VarDecl *injectProperty(NominalTypeDecl *parent, Identifier name,
                               Type type, VarDecl::Introducer introducer,
                               AccessLevel accessLevel,
                               Expr *initializer = nullptr) {
  auto *PBD = injectVariable(parent, name, type, introducer, initializer);
  auto *var = PBD->getSingleVar();

  var->setAccess(accessLevel);

  parent->addMember(PBD);
  parent->addMember(var);

  return var;
}

bool VarDecl::isAccessedViaTypeWrapper() const {
  auto *mutableSelf = const_cast<VarDecl *>(this);
  return evaluateOrDefault(getASTContext().evaluator,
                           IsPropertyAccessedViaTypeWrapper{mutableSelf},
                           false);
}

VarDecl *VarDecl::getUnderlyingTypeWrapperStorage() const {
  auto *mutableSelf = const_cast<VarDecl *>(this);
  return evaluateOrDefault(getASTContext().evaluator,
                           GetTypeWrapperStorageForProperty{mutableSelf},
                           nullptr);
}

NominalTypeDecl *NominalTypeDecl::getTypeWrapper() const {
  auto *mutableSelf = const_cast<NominalTypeDecl *>(this);
  return evaluateOrDefault(getASTContext().evaluator,
                           GetTypeWrapper{mutableSelf}, nullptr);
}

struct TypeWrapperAttrInfo {
  CustomAttr *Attr;
  NominalTypeDecl *Wrapper;
  NominalTypeDecl *AttachedTo;
};

static void
getTypeWrappers(NominalTypeDecl *decl,
                SmallVectorImpl<TypeWrapperAttrInfo> &typeWrappers) {
  auto &ctx = decl->getASTContext();

  // Attributes applied directly to the type.
  for (auto *attr : decl->getAttrs().getAttributes<CustomAttr>()) {
    auto *mutableAttr = const_cast<CustomAttr *>(attr);
    auto *nominal = evaluateOrDefault(
        ctx.evaluator, CustomAttrNominalRequest{mutableAttr, decl}, nullptr);

    if (!nominal)
      continue;

    auto *typeWrapper = nominal->getAttrs().getAttribute<TypeWrapperAttr>();
    if (typeWrapper && typeWrapper->isValid())
      typeWrappers.push_back({mutableAttr, nominal, decl});
  }

  // Do not allow transitive protocol inference between protocols.
  if (isa<ProtocolDecl>(decl))
    return;

  // Attributes inferred from (explicit) protocol conformances
  // associated with the declaration of the type.
  for (unsigned i : indices(decl->getInherited())) {
    auto inheritedType = evaluateOrDefault(
        ctx.evaluator,
        InheritedTypeRequest{decl, i, TypeResolutionStage::Interface}, Type());

    if (!(inheritedType && inheritedType->isConstraintType()))
      continue;

    auto *protocol = inheritedType->getAnyNominal();
    if (!protocol)
      continue;

    SmallVector<TypeWrapperAttrInfo, 2> inferredAttrs;
    getTypeWrappers(protocol, inferredAttrs);

    // De-duplicate inferred type wrappers. This also makes sure
    // that if both protocol and conforming type explicitly declare
    // the same type wrapper there is no clash between them.
    for (const auto &inferredAttr : inferredAttrs) {
      if (llvm::find_if(typeWrappers, [&](const TypeWrapperAttrInfo &attr) {
            return attr.Wrapper == inferredAttr.Wrapper;
          }) == typeWrappers.end())
        typeWrappers.push_back(inferredAttr);
    }
  }
}

NominalTypeDecl *GetTypeWrapper::evaluate(Evaluator &evaluator,
                                          NominalTypeDecl *decl) const {
  auto &ctx = decl->getASTContext();

  // Note that we don't actually care whether there are duplicates,
  // using the same type wrapper multiple times is still an error.
  SmallVector<TypeWrapperAttrInfo, 2> typeWrappers;

  getTypeWrappers(decl, typeWrappers);

  if (typeWrappers.empty())
    return nullptr;

  if (typeWrappers.size() != 1) {
    ctx.Diags.diagnose(decl, diag::cannot_use_multiple_type_wrappers,
                       decl->getDescriptiveKind(), decl->getName());

    for (const auto &entry : typeWrappers) {
      if (entry.AttachedTo == decl) {
        ctx.Diags.diagnose(entry.Attr->getLocation(), diag::decl_declared_here,
                           entry.Wrapper->getName());
      } else {
        ctx.Diags.diagnose(decl, diag::type_wrapper_inferred_from,
                           entry.Wrapper->getName(),
                           entry.AttachedTo->getDescriptiveKind(),
                           entry.AttachedTo->getName());
      }
    }

    return nullptr;
  }

  return typeWrappers.front().Wrapper;
}

Type GetTypeWrapperType::evaluate(Evaluator &evaluator,
                                  NominalTypeDecl *decl) const {
  SmallVector<TypeWrapperAttrInfo, 2> typeWrappers;

  getTypeWrappers(decl, typeWrappers);

  if (typeWrappers.size() != 1)
    return Type();

  auto *typeWrapperAttr = typeWrappers.front().Attr;
  auto type = evaluateOrDefault(
      evaluator,
      CustomAttrTypeRequest{typeWrapperAttr, decl->getDeclContext(),
                            CustomAttrTypeKind::TypeWrapper},
      Type());

  if (!type || type->hasError()) {
    return ErrorType::get(decl->getASTContext());
  }
  return type;
}

VarDecl *NominalTypeDecl::getTypeWrapperProperty() const {
  auto *mutableSelf = const_cast<NominalTypeDecl *>(this);
  return evaluateOrDefault(getASTContext().evaluator,
                           GetTypeWrapperProperty{mutableSelf}, nullptr);
}

ConstructorDecl *NominalTypeDecl::getTypeWrappedTypeStorageInitializer() const {
  auto *mutableSelf = const_cast<NominalTypeDecl *>(this);
  return evaluateOrDefault(
      getASTContext().evaluator,
      SynthesizeTypeWrappedTypeStorageWrapperInitializer{mutableSelf}, nullptr);
}

ConstructorDecl *
NominalTypeDecl::getTypeWrappedTypeMemberwiseInitializer() const {
  auto *mutableSelf = const_cast<NominalTypeDecl *>(this);
  return evaluateOrDefault(
      getASTContext().evaluator,
      SynthesizeTypeWrappedTypeMemberwiseInitializer{mutableSelf}, nullptr);
}

TypeDecl *NominalTypeDecl::getTypeWrapperStorageDecl() const {
  auto *mutableSelf = const_cast<NominalTypeDecl *>(this);
  return evaluateOrDefault(getASTContext().evaluator,
                           GetTypeWrapperStorage{mutableSelf}, nullptr);
}

TypeDecl *GetTypeWrapperStorage::evaluate(Evaluator &evaluator,
                                          NominalTypeDecl *parent) const {
  if (!parent->hasTypeWrapper())
    return nullptr;

  auto &ctx = parent->getASTContext();

  TypeDecl *storage = nullptr;
  if (isa<ProtocolDecl>(parent)) {
    // If type wrapper is associated with a protocol, we need to
    // inject a new associated type - $Storage.
    storage = new (ctx)
        AssociatedTypeDecl(parent, /*keywordLoc=*/SourceLoc(),
                           ctx.Id_TypeWrapperStorage, /*nameLoc=*/SourceLoc(),
                           /*defaultDefinition=*/nullptr,
                           /*trailingWhere=*/nullptr);
  } else {
    // For classes and structs we inject a new member struct - $Storage.
    storage = new (ctx)
        StructDecl(/*StructLoc=*/SourceLoc(), ctx.Id_TypeWrapperStorage,
                   /*NameLoc=*/SourceLoc(),
                   /*Inheritted=*/{},
                   /*GenericParams=*/nullptr, parent);
  }

  storage->setImplicit();
  storage->setSynthesized();
  storage->setAccess(AccessLevel::Internal);

  parent->addMember(storage);

  return storage;
}

VarDecl *
GetTypeWrapperProperty::evaluate(Evaluator &evaluator,
                                 NominalTypeDecl *parent) const {
  auto &ctx = parent->getASTContext();

  auto *typeWrapper = parent->getTypeWrapper();
  if (!typeWrapper)
    return nullptr;

  auto *storage = parent->getTypeWrapperStorageDecl();
  assert(storage);

  auto *typeWrapperType =
      evaluateOrDefault(ctx.evaluator, GetTypeWrapperType{parent}, Type())
          ->castTo<AnyGenericType>();
  assert(typeWrapperType);

  // $storage: Wrapper<<ParentType>, <ParentType>.$Storage>
  auto propertyTy = BoundGenericType::get(
      typeWrapper, /*Parent=*/typeWrapperType->getParent(),
      /*genericArgs=*/
      {parent->getSelfInterfaceType(),
       storage->getDeclaredInterfaceType()});

  return injectProperty(parent, ctx.Id_TypeWrapperProperty, propertyTy,
                        VarDecl::Introducer::Var, AccessLevel::Internal);
}

VarDecl *GetTypeWrapperStorageForProperty::evaluate(Evaluator &evaluator,
                                                    VarDecl *property) const {
  auto *wrappedType = property->getDeclContext()->getSelfNominalTypeDecl();
  if (!(wrappedType && wrappedType->hasTypeWrapper()))
    return nullptr;

  // Type wrappers support only stored `var`s.
  if (!property->isAccessedViaTypeWrapper())
    return nullptr;

  assert(!isa<ProtocolDecl>(wrappedType));

  auto *storage =
      cast<NominalTypeDecl>(wrappedType->getTypeWrapperStorageDecl());
  assert(storage);

  // Type wrapper variables are never initialized directly,
  // initialization expression (if any) becomes an default
  // argument of the initializer synthesized by the type wrapper.
  if (auto *PBD = property->getParentPatternBinding()) {
    PBD->setInitializerSubsumed(/*index=*/0);
  }

  return injectProperty(storage, property->getName(),
                        property->getValueInterfaceType(),
                        property->getIntroducer(), AccessLevel::Internal);
}

/// Given the property create a subscript to reach its type wrapper storage:
/// `$storage[storageKeyPath: \$Storage.<property>]`.
static SubscriptExpr *subscriptTypeWrappedProperty(VarDecl *var,
                                                   AccessorDecl *useDC) {
  auto &ctx = useDC->getASTContext();
  auto *parent = var->getDeclContext()->getSelfNominalTypeDecl();

  if (!(parent && parent->hasTypeWrapper()))
    return nullptr;

  auto *typeWrapperVar = parent->getTypeWrapperProperty();
  auto *storageVar = var->getUnderlyingTypeWrapperStorage();

  assert(typeWrapperVar);
  assert(storageVar);

  auto createRefToSelf = [&]() {
    return new (ctx) DeclRefExpr({useDC->getImplicitSelfDecl()},
                                 /*Loc=*/DeclNameLoc(), /*Implicit=*/true);
  };

  // \$Storage.<property-name>
  auto *storageKeyPath = KeyPathExpr::createImplicit(
      ctx, /*backslashLoc=*/SourceLoc(),
      {KeyPathExpr::Component::forProperty(
          {storageVar},
          useDC->mapTypeIntoContext(storageVar->getInterfaceType()),
          /*Loc=*/SourceLoc())},
      /*endLoc=*/SourceLoc());

  // WrappedType.<property-name>
  auto *propertyKeyPath = KeyPathExpr::createImplicit(
      ctx, /*backslashLoc=*/SourceLoc(),
      {KeyPathExpr::Component::forUnresolvedProperty(
          DeclNameRef(var->getName()), /*Loc=*/SourceLoc())},
      /*endLoc=*/SourceLoc());

  auto *subscriptBaseExpr = UnresolvedDotExpr::createImplicit(
      ctx, createRefToSelf(), typeWrapperVar->getName());

  SmallVector<Argument, 4> subscriptArgs;

  // If this is a reference type, let's see whether type wrapper supports
  // `wrappedSelf:propertyKeyPath:storageKeyPath:` overload.
  if (isa<ClassDecl>(parent)) {
    DeclName subscriptName(
        ctx, DeclBaseName::createSubscript(),
        {ctx.Id_wrappedSelf, ctx.Id_propertyKeyPath, ctx.Id_storageKeyPath});

    auto *typeWrapper = parent->getTypeWrapper();
    auto candidates = typeWrapper->lookupDirect(subscriptName);

    if (!candidates.empty()) {
      subscriptArgs.push_back(
          Argument(/*loc=*/SourceLoc(), ctx.Id_wrappedSelf, createRefToSelf()));
    }
  }

  subscriptArgs.push_back(
      Argument(/*loc=*/SourceLoc(), ctx.Id_propertyKeyPath, propertyKeyPath));
  subscriptArgs.push_back(
      Argument(/*loc=*/SourceLoc(), ctx.Id_storageKeyPath, storageKeyPath));

  // $storage[storageKeyPath: \$Storage.<property-name>]
  return SubscriptExpr::create(ctx, subscriptBaseExpr,
                               ArgumentList::createImplicit(ctx, subscriptArgs),
                               ConcreteDeclRef(), /*implicit=*/true);
}

BraceStmt *
SynthesizeTypeWrappedPropertyGetterBody::evaluate(Evaluator &evaluator,
                                                  AccessorDecl *getter) const {
  assert(getter->isGetter());

  auto &ctx = getter->getASTContext();

  auto *var = dyn_cast<VarDecl>(getter->getStorage());
  if (!var)
    return nullptr;

  auto *subscript = subscriptTypeWrappedProperty(var, getter);
  if (!subscript)
    return nullptr;

  ASTNode body = new (ctx) ReturnStmt(SourceLoc(), subscript,
                                      /*isImplicit=*/true);
  return BraceStmt::create(ctx, /*lbloc=*/var->getLoc(), body,
                           /*rbloc=*/var->getLoc(), /*implicit=*/true);
}

BraceStmt *
SynthesizeTypeWrappedPropertySetterBody::evaluate(Evaluator &evaluator,
                                                  AccessorDecl *setter) const {
  assert(setter->isSetter());

  auto &ctx = setter->getASTContext();

  auto *var = dyn_cast<VarDecl>(setter->getStorage());
  if (!var)
    return nullptr;

  auto *subscript = subscriptTypeWrappedProperty(var, setter);
  if (!subscript)
    return nullptr;

  VarDecl *newValueParam = setter->getParameters()->get(0);

  auto *assignment = new (ctx) AssignExpr(
      subscript, /*EqualLoc=*/SourceLoc(),
      new (ctx) DeclRefExpr(newValueParam, DeclNameLoc(), /*IsImplicit=*/true),
      /*Implicit=*/true);

  ASTNode body = new (ctx) ReturnStmt(SourceLoc(), assignment,
                                      /*isImplicit=*/true);
  return BraceStmt::create(ctx, /*lbloc=*/var->getLoc(), body,
                           /*rbloc=*/var->getLoc(), /*implicit=*/true);
}

bool IsPropertyAccessedViaTypeWrapper::evaluate(Evaluator &evaluator,
                                                VarDecl *property) const {
  auto *parent = property->getDeclContext()->getSelfNominalTypeDecl();
  if (!(parent && parent->hasTypeWrapper()))
    return false;

  if (property->isStatic())
    return false;

  // If this property has `@typeWrapperIgnored` attribute
  // it should not be managed by a type wrapper.
  if (property->getAttrs().hasAttribute<TypeWrapperIgnoredAttr>())
    return false;

  // `lazy` properties are not wrapped.
  if (property->getAttrs().hasAttribute<LazyAttr>() ||
      property->isLazyStorageProperty())
    return false;

  // Properties with attached property wrappers are not considered
  // accessible via type wrapper directly, only their backing storage is.
  {
    // Wrapped property itself `<name>`
    if (property->hasAttachedPropertyWrapper())
      return false;

    // Projection - `$<name>`
    if (property->getOriginalWrappedProperty(
          PropertyWrapperSynthesizedPropertyKind::Projection))
      return false;

    // Backing storage (or wrapper property) - `_<name>`.
    //
    // This is the only thing that wrapper needs to handle because
    // all access to the wrapped variable and it's projection
    // is routed through it.
    if (auto *wrappedProperty = property->getOriginalWrappedProperty(
            PropertyWrapperSynthesizedPropertyKind::Backing)) {
      // If wrapped property is ignored - its backing storage is
      // ignored as well.
      return !wrappedProperty->getAttrs()
                  .hasAttribute<TypeWrapperIgnoredAttr>();
    }
  }

  // Don't wrap any compiler synthesized properties except to
  // property wrapper backing storage (checked above).
  if (property->isImplicit())
    return false;

  // Check whether this is a computed property.
  {
    auto declaresAccessor = [&](ArrayRef<AccessorKind> kinds) -> bool {
      return llvm::any_of(kinds, [&](const AccessorKind &kind) {
        return bool(property->getParsedAccessor(kind));
      });
    };

    // property has a getter.
    if (declaresAccessor(
            {AccessorKind::Get, AccessorKind::Read, AccessorKind::Address}))
      return false;

    // property has a setter.
    if (declaresAccessor({AccessorKind::Set, AccessorKind::Modify,
                          AccessorKind::MutableAddress}))
      return false;
  }

  return true;
}

VarDecl *SynthesizeLocalVariableForTypeWrapperStorage::evaluate(
    Evaluator &evaluator, ConstructorDecl *ctor) const {
  auto &ctx = ctor->getASTContext();

  if (ctor->isImplicit() || !ctor->isDesignatedInit())
    return nullptr;

  auto *DC = ctor->getDeclContext()->getSelfNominalTypeDecl();
  if (!(DC && DC->hasTypeWrapper()))
    return nullptr;

  // Default protocol initializers do not get transformed.
  if (isa<ProtocolDecl>(DC))
    return nullptr;

  auto *storageDecl = cast<NominalTypeDecl>(DC->getTypeWrapperStorageDecl());
  assert(storageDecl);

  SmallVector<TupleTypeElt, 4> members;
  for (auto *member : storageDecl->getMembers()) {
    if (auto *var = dyn_cast<VarDecl>(member)) {
      assert(var->hasStorage() &&
             "$Storage should have stored properties only");
      members.push_back({var->getValueInterfaceType(), var->getName()});
    }
  }

  auto *PBD =
      injectVariable(ctor, ctx.Id_localStorageVar, TupleType::get(members, ctx),
                     VarDecl::Introducer::Var);
  return PBD->getSingleVar();
}

ConstructorDecl *NominalTypeDecl::getTypeWrapperInitializer() const {
  auto *mutableSelf = const_cast<NominalTypeDecl *>(this);
  return evaluateOrDefault(getASTContext().evaluator,
                           GetTypeWrapperInitializer{mutableSelf}, nullptr);
}

ConstructorDecl *
GetTypeWrapperInitializer::evaluate(Evaluator &evaluator,
                                    NominalTypeDecl *typeWrapper) const {
  auto &ctx = typeWrapper->getASTContext();
  assert(typeWrapper->getAttrs().hasAttribute<TypeWrapperAttr>());

  auto ctors = typeWrapper->lookupDirect(DeclName(
      ctx, DeclBaseName::createConstructor(), {ctx.Id_for, ctx.Id_storage}));

  if (ctors.size() != 1)
    return nullptr;

  return cast<ConstructorDecl>(ctors.front());
}


text:
var map = require('map-stream')
    , csv = require('csv')
	, fs = require('fs')
	, _ = require('lodash')
	, path = require('path')
	;

module.exports = function () {
	return map(function (file, cb) {
		var baseName = 'docs/' + path.basename(file.path, '.csv');
		var dest = baseName + '.md';
		var stream = fs.createWriteStream(dest);
		stream.once('open', function(fd) {
			stream.write('# Features of Version ' + baseName.split('-')[1] + '\n\n');
			csv()
			.from(file.path)
			.on('record', function (row, index) {
				var feature = { type: row[0], version: row[2], className: row[3], method: row[4], desc: row[5] },
					removed = feature.type === 'removed';

				stream.write('* ' + (removed ? '~~' : '') + feature.className + '.' + feature.method + ' - ' + feature.desc + (removed ? '~~ (no longer available)' : '') + '\n');
			})
			.on('end', function () {
				stream.end();
			});
		});
	});
}