text:
ASMJIT_BEGIN_NAMESPACE

// ============================================================================
// [Globals]
// ============================================================================

static const char CodeHolder_addrTabName[] = ".addrtab";

//! Encode MOD byte.
static inline uint32_t x86EncodeMod(uint32_t m, uint32_t o, uint32_t rm) noexcept {
  return (m << 6) | (o << 3) | rm;
}

// ============================================================================
// [asmjit::LabelLinkIterator]
// ============================================================================

class LabelLinkIterator {
public:
  ASMJIT_INLINE LabelLinkIterator(LabelEntry* le) noexcept { reset(le); }

  ASMJIT_INLINE explicit operator bool() const noexcept { return isValid(); }
  ASMJIT_INLINE bool isValid() const noexcept { return _link != nullptr; }

  ASMJIT_INLINE LabelLink* link() const noexcept { return _link; }
  ASMJIT_INLINE LabelLink* operator->() const noexcept { return _link; }

  ASMJIT_INLINE void reset(LabelEntry* le) noexcept {
    _pPrev = &le->_links;
    _link = *_pPrev;
  }

  ASMJIT_INLINE void next() noexcept {
    _pPrev = &_link->next;
    _link = *_pPrev;
  }

  ASMJIT_INLINE void resolveAndNext(CodeHolder* code) noexcept {
    LabelLink* linkToDelete = _link;

    _link = _link->next;
    *_pPrev = _link;

    code->_unresolvedLinkCount--;
    code->_allocator.release(linkToDelete, sizeof(LabelLink));
  }

  LabelLink** _pPrev;
  LabelLink* _link;
};

// ============================================================================
// [asmjit::ErrorHandler]
// ============================================================================

ErrorHandler::ErrorHandler() noexcept {}
ErrorHandler::~ErrorHandler() noexcept {}

// ============================================================================
// [asmjit::CodeHolder - Utilities]
// ============================================================================

static void CodeHolder_resetInternal(CodeHolder* self, uint32_t resetPolicy) noexcept {
  uint32_t i;
  const ZoneVector<BaseEmitter*>& emitters = self->emitters();

  i = emitters.size();
  while (i)
    self->detach(emitters[--i]);

  // Reset everything into its construction state.
  self->_codeInfo.reset();
  self->_emitterOptions = 0;
  self->_logger = nullptr;
  self->_errorHandler = nullptr;

  // Reset all sections.
  uint32_t numSections = self->_sections.size();
  for (i = 0; i < numSections; i++) {
    Section* section = self->_sections[i];
    if (section->_buffer.data() && !section->_buffer.isExternal())
      ::free(section->_buffer._data);
    section->_buffer._data = nullptr;
    section->_buffer._capacity = 0;
  }

  // Reset zone allocator and all containers using it.
  ZoneAllocator* allocator = self->allocator();

  self->_emitters.reset();
  self->_namedLabels.reset();
  self->_relocations.reset();
  self->_labelEntries.reset();
  self->_sections.reset();

  self->_unresolvedLinkCount = 0;
  self->_addressTableSection = nullptr;
  self->_addressTableEntries.reset();

  allocator->reset(&self->_zone);
  self->_zone.reset(resetPolicy);
}

static void CodeHolder_modifyEmitterOptions(CodeHolder* self, uint32_t clear, uint32_t add) noexcept {
  uint32_t oldOpt = self->_emitterOptions;
  uint32_t newOpt = (oldOpt & ~clear) | add;

  if (oldOpt == newOpt)
    return;

  // Modify emitter options of `CodeHolder` itself.
  self->_emitterOptions = newOpt;

  // Modify emitter options of all attached emitters.
  for (BaseEmitter* emitter : self->emitters()) {
    emitter->_emitterOptions = (emitter->_emitterOptions & ~clear) | add;
    emitter->onUpdateGlobalInstOptions();
  }
}

// ============================================================================
// [asmjit::CodeHolder - Construction / Destruction]
// ============================================================================

CodeHolder::CodeHolder() noexcept
  : _codeInfo(),
    _emitterOptions(0),
    _logger(nullptr),
    _errorHandler(nullptr),
    _zone(16384 - Zone::kBlockOverhead),
    _allocator(&_zone),
    _unresolvedLinkCount(0),
    _addressTableSection(nullptr) {}

CodeHolder::~CodeHolder() noexcept {
  CodeHolder_resetInternal(this, Globals::kResetHard);
}

// ============================================================================
// [asmjit::CodeHolder - Init / Reset]
// ============================================================================

inline void CodeHolder_setSectionDefaultName(
  Section* section,
  char c0 = 0, char c1 = 0, char c2 = 0, char c3 = 0,
  char c4 = 0, char c5 = 0, char c6 = 0, char c7 = 0) noexcept {

  section->_name.u32[0] = Support::bytepack32_4x8(uint8_t(c0), uint8_t(c1), uint8_t(c2), uint8_t(c3));
  section->_name.u32[1] = Support::bytepack32_4x8(uint8_t(c4), uint8_t(c5), uint8_t(c6), uint8_t(c7));
}

Error CodeHolder::init(const CodeInfo& info) noexcept {
  // Cannot reinitialize if it's locked or there is one or more emitter attached.
  if (isInitialized())
    return DebugUtils::errored(kErrorAlreadyInitialized);

  // If we are just initializing there should be no emitters attached.
  ASMJIT_ASSERT(_emitters.empty());

  // Create the default section and insert it to the `_sections` array.
  Error err = _sections.willGrow(&_allocator);
  if (err == kErrorOk) {
    Section* section = _allocator.allocZeroedT<Section>();
    if (ASMJIT_LIKELY(section)) {
      section->_flags = Section::kFlagExec | Section::kFlagConst;
      CodeHolder_setSectionDefaultName(section, '.', 't', 'e', 'x', 't');
      _sections.appendUnsafe(section);
    }
    else {
      err = DebugUtils::errored(kErrorOutOfMemory);
    }
  }

  if (ASMJIT_UNLIKELY(err)) {
    _zone.reset();
    return err;
  }
  else {
    _codeInfo = info;
    return kErrorOk;
  }
}

void CodeHolder::reset(uint32_t resetPolicy) noexcept {
  CodeHolder_resetInternal(this, resetPolicy);
}

// ============================================================================
// [asmjit::CodeHolder - Attach / Detach]
// ============================================================================

Error CodeHolder::attach(BaseEmitter* emitter) noexcept {
  // Catch a possible misuse of the API.
  if (ASMJIT_UNLIKELY(!emitter))
    return DebugUtils::errored(kErrorInvalidArgument);

  // Invalid emitter, this should not be possible.
  uint32_t type = emitter->emitterType();
  if (ASMJIT_UNLIKELY(type == BaseEmitter::kTypeNone || type >= BaseEmitter::kTypeCount))
    return DebugUtils::errored(kErrorInvalidState);

  // This is suspicious, but don't fail if `emitter` is already attached
  // to this code holder. This is not error, but it's not recommended.
  if (emitter->_code != nullptr) {
    if (emitter->_code == this)
      return kErrorOk;
    return DebugUtils::errored(kErrorInvalidState);
  }

  // Reserve the space now as we cannot fail after `onAttach()` succeeded.
  ASMJIT_PROPAGATE(_emitters.willGrow(&_allocator, 1));
  ASMJIT_PROPAGATE(emitter->onAttach(this));

  // Connect CodeHolder <-> BaseEmitter.
  ASMJIT_ASSERT(emitter->_code == this);
  _emitters.appendUnsafe(emitter);

  return kErrorOk;
}

Error CodeHolder::detach(BaseEmitter* emitter) noexcept {
  if (ASMJIT_UNLIKELY(!emitter))
    return DebugUtils::errored(kErrorInvalidArgument);

  if (ASMJIT_UNLIKELY(emitter->_code != this))
    return DebugUtils::errored(kErrorInvalidState);

  // NOTE: We always detach if we were asked to, if error happens during
  // `emitter->onDetach()` we just propagate it, but the BaseEmitter will
  // be detached.
  Error err = kErrorOk;
  if (!emitter->isDestroyed())
    err = emitter->onDetach(this);

  // Disconnect CodeHolder <-> BaseEmitter.
  uint32_t index = _emitters.indexOf(emitter);
  ASMJIT_ASSERT(index != Globals::kNotFound);

  _emitters.removeAt(index);
  emitter->_code = nullptr;

  return err;
}

// ============================================================================
// [asmjit::CodeHolder - Emitter Options]
// ============================================================================

static constexpr uint32_t kEmitterOptionsFilter = ~uint32_t(BaseEmitter::kOptionLoggingEnabled);

void CodeHolder::addEmitterOptions(uint32_t options) noexcept {
  CodeHolder_modifyEmitterOptions(this, 0, options & kEmitterOptionsFilter);
}

void CodeHolder::clearEmitterOptions(uint32_t options) noexcept {
  CodeHolder_modifyEmitterOptions(this, options & kEmitterOptionsFilter, 0);
}

// ============================================================================
// [asmjit::CodeHolder - Logging & Error Handling]
// ============================================================================

void CodeHolder::setLogger(Logger* logger) noexcept {
  #ifndef ASMJIT_NO_LOGGING
  _logger = logger;
  uint32_t option = !logger ? uint32_t(0) : uint32_t(BaseEmitter::kOptionLoggingEnabled);
  CodeHolder_modifyEmitterOptions(this, BaseEmitter::kOptionLoggingEnabled, option);
  #else
  ASMJIT_UNUSED(logger);
  #endif
}

// ============================================================================
// [asmjit::CodeHolder - Code Buffer]
// ============================================================================

static Error CodeHolder_reserveInternal(CodeHolder* self, CodeBuffer* cb, size_t n) noexcept {
  uint8_t* oldData = cb->_data;
  uint8_t* newData;

  if (oldData && !cb->isExternal())
    newData = static_cast<uint8_t*>(::realloc(oldData, n));
  else
    newData = static_cast<uint8_t*>(::malloc(n));

  if (ASMJIT_UNLIKELY(!newData))
    return DebugUtils::errored(kErrorOutOfMemory);

  cb->_data = newData;
  cb->_capacity = n;

  // Update pointers used by assemblers, if attached.
  for (BaseEmitter* emitter : self->emitters()) {
    if (emitter->isAssembler()) {
      BaseAssembler* a = static_cast<BaseAssembler*>(emitter);
      if (&a->_section->_buffer == cb) {
        size_t offset = a->offset();

        a->_bufferData = newData;
        a->_bufferEnd  = newData + n;
        a->_bufferPtr  = newData + offset;
      }
    }
  }

  return kErrorOk;
}

Error CodeHolder::growBuffer(CodeBuffer* cb, size_t n) noexcept {
  // The size of the section must be valid.
  size_t size = cb->size();
  if (ASMJIT_UNLIKELY(n > std::numeric_limits<uintptr_t>::max() - size))
    return DebugUtils::errored(kErrorOutOfMemory);

  // We can now check if growing the buffer is really necessary. It's unlikely
  // that this function is called while there is still room for `n` bytes.
  size_t capacity = cb->capacity();
  size_t required = cb->size() + n;
  if (ASMJIT_UNLIKELY(required <= capacity))
    return kErrorOk;

  if (cb->isFixed())
    return DebugUtils::errored(kErrorTooLarge);

  size_t kInitialCapacity = 8096;
  if (capacity < kInitialCapacity)
    capacity = kInitialCapacity;
  else
    capacity += Globals::kAllocOverhead;

  do {
    size_t old = capacity;
    if (capacity < Globals::kGrowThreshold)
      capacity *= 2;
    else
      capacity += Globals::kGrowThreshold;

    // Overflow.
    if (ASMJIT_UNLIKELY(old > capacity))
      return DebugUtils::errored(kErrorOutOfMemory);
  } while (capacity - Globals::kAllocOverhead < required);

  return CodeHolder_reserveInternal(this, cb, capacity - Globals::kAllocOverhead);
}

Error CodeHolder::reserveBuffer(CodeBuffer* cb, size_t n) noexcept {
  size_t capacity = cb->capacity();
  if (n <= capacity) return kErrorOk;

  if (cb->isFixed())
    return DebugUtils::errored(kErrorTooLarge);

  return CodeHolder_reserveInternal(this, cb, n);
}

// ============================================================================
// [asmjit::CodeHolder - Sections]
// ============================================================================

Error CodeHolder::newSection(Section** sectionOut, const char* name, size_t nameSize, uint32_t flags, uint32_t alignment) noexcept {
  *sectionOut = nullptr;

  if (nameSize == SIZE_MAX)
    nameSize = strlen(name);

  if (alignment == 0)
    alignment = 1;

  if (ASMJIT_UNLIKELY(!Support::isPowerOf2(alignment)))
    return DebugUtils::errored(kErrorInvalidArgument);

  if (ASMJIT_UNLIKELY(nameSize > Globals::kMaxSectionNameSize))
    return DebugUtils::errored(kErrorInvalidSectionName);

  uint32_t sectionId = _sections.size();
  if (ASMJIT_UNLIKELY(sectionId == Globals::kInvalidId))
    return DebugUtils::errored(kErrorTooManySections);

  ASMJIT_PROPAGATE(_sections.willGrow(&_allocator));
  Section* section = _allocator.allocZeroedT<Section>();

  if (ASMJIT_UNLIKELY(!section))
    return DebugUtils::errored(kErrorOutOfMemory);

  section->_id = sectionId;
  section->_flags = flags;
  section->_alignment = alignment;
  memcpy(section->_name.str, name, nameSize);
  _sections.appendUnsafe(section);

  *sectionOut = section;
  return kErrorOk;
}

Section* CodeHolder::sectionByName(const char* name, size_t nameSize) const noexcept {
  if (nameSize == SIZE_MAX)
    nameSize = strlen(name);

  // This could be also put in a hash-table similarly like we do with labels,
  // however it's questionable as the number of sections should be pretty low
  // in general. Create an issue if this becomes a problem.
  if (ASMJIT_UNLIKELY(nameSize <= Globals::kMaxSectionNameSize)) {
    for (Section* section : _sections)
      if (memcmp(section->_name.str, name, nameSize) == 0 && section->_name.str[nameSize] == '\0')
        return section;
  }

  return nullptr;
}

Section* CodeHolder::ensureAddressTableSection() noexcept {
  if (_addressTableSection)
    return _addressTableSection;

  newSection(&_addressTableSection, CodeHolder_addrTabName, sizeof(CodeHolder_addrTabName) - 1, 0, _codeInfo.gpSize());
  return _addressTableSection;
}

Error CodeHolder::addAddressToAddressTable(uint64_t address) noexcept {
  AddressTableEntry* entry = _addressTableEntries.get(address);
  if (entry)
    return kErrorOk;

  Section* section = ensureAddressTableSection();
  if (ASMJIT_UNLIKELY(!section))
    return DebugUtils::errored(kErrorOutOfMemory);

  entry = _zone.newT<AddressTableEntry>(address);
  if (ASMJIT_UNLIKELY(!entry))
    return DebugUtils::errored(kErrorOutOfMemory);

  _addressTableEntries.insert(entry);
  section->_virtualSize += _codeInfo.gpSize();

  return kErrorOk;
}

// ============================================================================
// [asmjit::CodeHolder - Labels / Symbols]
// ============================================================================

//! Only used to lookup a label from `_namedLabels`.
class LabelByName {
public:
  inline LabelByName(const char* key, size_t keySize, uint32_t hashCode) noexcept
    : _key(key),
      _keySize(uint32_t(keySize)),
      _hashCode(hashCode) {}

  inline uint32_t hashCode() const noexcept { return _hashCode; }

  inline bool matches(const LabelEntry* entry) const noexcept {
    return entry->nameSize() == _keySize && ::memcmp(entry->name(), _key, _keySize) == 0;
  }

  const char* _key;
  uint32_t _keySize;
  uint32_t _hashCode;
};

// Returns a hash of `name` and fixes `nameSize` if it's `SIZE_MAX`.
static uint32_t CodeHolder_hashNameAndGetSize(const char* name, size_t& nameSize) noexcept {
  uint32_t hashCode = 0;
  if (nameSize == SIZE_MAX) {
    size_t i = 0;
    for (;;) {
      uint8_t c = uint8_t(name[i]);
      if (!c) break;
      hashCode = Support::hashRound(hashCode, c);
      i++;
    }
    nameSize = i;
  }
  else {
    for (size_t i = 0; i < nameSize; i++) {
      uint8_t c = uint8_t(name[i]);
      if (ASMJIT_UNLIKELY(!c)) return DebugUtils::errored(kErrorInvalidLabelName);
      hashCode = Support::hashRound(hashCode, c);
    }
  }
  return hashCode;
}

static bool CodeHolder_writeDisplacement(void* dst, int64_t displacement, uint32_t displacementSize) {
  if (displacementSize == 4 && Support::isInt32(displacement)) {
    Support::writeI32uLE(dst, int32_t(displacement));
    return true;
  }
  else if (displacementSize == 1 && Support::isInt8(displacement)) {
    Support::writeI8(dst, int8_t(displacement));
    return true;
  }

  return false;
}

LabelLink* CodeHolder::newLabelLink(LabelEntry* le, uint32_t sectionId, size_t offset, intptr_t rel) noexcept {
  LabelLink* link = _allocator.allocT<LabelLink>();
  if (ASMJIT_UNLIKELY(!link)) return nullptr;

  link->next = le->_links;
  le->_links = link;

  link->sectionId = sectionId;
  link->relocId = Globals::kInvalidId;
  link->offset = offset;
  link->rel = rel;

  _unresolvedLinkCount++;
  return link;
}

Error CodeHolder::newLabelEntry(LabelEntry** entryOut) noexcept {
  *entryOut = 0;

  uint32_t labelId = _labelEntries.size();
  if (ASMJIT_UNLIKELY(labelId == Globals::kInvalidId))
    return DebugUtils::errored(kErrorTooManyLabels);

  ASMJIT_PROPAGATE(_labelEntries.willGrow(&_allocator));
  LabelEntry* le = _allocator.allocZeroedT<LabelEntry>();

  if (ASMJIT_UNLIKELY(!le))
    return DebugUtils::errored(kErrorOutOfMemory);

  le->_setId(labelId);
  le->_parentId = Globals::kInvalidId;
  le->_offset = 0;
  _labelEntries.appendUnsafe(le);

  *entryOut = le;
  return kErrorOk;
}

Error CodeHolder::newNamedLabelEntry(LabelEntry** entryOut, const char* name, size_t nameSize, uint32_t type, uint32_t parentId) noexcept {
  *entryOut = 0;
  uint32_t hashCode = CodeHolder_hashNameAndGetSize(name, nameSize);

  if (ASMJIT_UNLIKELY(nameSize == 0))
    return DebugUtils::errored(kErrorInvalidLabelName);

  if (ASMJIT_UNLIKELY(nameSize > Globals::kMaxLabelNameSize))
    return DebugUtils::errored(kErrorLabelNameTooLong);

  switch (type) {
    case Label::kTypeLocal:
      if (ASMJIT_UNLIKELY(parentId >= _labelEntries.size()))
        return DebugUtils::errored(kErrorInvalidParentLabel);

      hashCode ^= parentId;
      break;

    case Label::kTypeGlobal:
      if (ASMJIT_UNLIKELY(parentId != Globals::kInvalidId))
        return DebugUtils::errored(kErrorNonLocalLabelCantHaveParent);

      break;

    default:
      return DebugUtils::errored(kErrorInvalidArgument);
  }

  // Don't allow to insert duplicates. Local labels allow duplicates that have
  // different id, this is already accomplished by having a different hashes
  // between the same label names having different parent labels.
  LabelEntry* le = _namedLabels.get(LabelByName(name, nameSize, hashCode));
  if (ASMJIT_UNLIKELY(le))
    return DebugUtils::errored(kErrorLabelAlreadyDefined);

  Error err = kErrorOk;
  uint32_t labelId = _labelEntries.size();

  if (ASMJIT_UNLIKELY(labelId == Globals::kInvalidId))
    return DebugUtils::errored(kErrorTooManyLabels);

  ASMJIT_PROPAGATE(_labelEntries.willGrow(&_allocator));
  le = _allocator.allocZeroedT<LabelEntry>();

  if (ASMJIT_UNLIKELY(!le))
    return DebugUtils::errored(kErrorOutOfMemory);

  le->_hashCode = hashCode;
  le->_setId(labelId);
  le->_type = uint8_t(type);
  le->_parentId = Globals::kInvalidId;
  le->_offset = 0;
  ASMJIT_PROPAGATE(le->_name.setData(&_zone, name, nameSize));

  _labelEntries.appendUnsafe(le);
  _namedLabels.insert(allocator(), le);

  *entryOut = le;
  return err;
}

uint32_t CodeHolder::labelIdByName(const char* name, size_t nameSize, uint32_t parentId) noexcept {
  // TODO: Finalize - parent id is not used here?
  ASMJIT_UNUSED(parentId);

  uint32_t hashCode = CodeHolder_hashNameAndGetSize(name, nameSize);
  if (ASMJIT_UNLIKELY(!nameSize)) return 0;

  LabelEntry* le = _namedLabels.get(LabelByName(name, nameSize, hashCode));
  return le ? le->id() : uint32_t(Globals::kInvalidId);
}

ASMJIT_API Error CodeHolder::resolveUnresolvedLinks() noexcept {
  if (!hasUnresolvedLinks())
    return kErrorOk;

  Error err = kErrorOk;
  for (LabelEntry* le : labelEntries()) {
    if (!le->isBound())
      continue;

    LabelLinkIterator link(le);
    if (link) {
      Support::FastUInt8 of = 0;
      Section* toSection = le->section();
      uint64_t toOffset = Support::addOverflow(toSection->offset(), le->offset(), &of);

      do {
        uint32_t linkSectionId = link->sectionId;
        if (link->relocId == Globals::kInvalidId) {
          Section* fromSection = sectionById(linkSectionId);
          size_t linkOffset = link->offset;

          CodeBuffer& buf = _sections[linkSectionId]->buffer();
          ASMJIT_ASSERT(linkOffset < buf.size());

          // Calculate the offset relative to the start of the virtual base.
          uint64_t fromOffset = Support::addOverflow<uint64_t>(fromSection->offset(), linkOffset, &of);
          int64_t displacement = int64_t(toOffset - fromOffset + uint64_t(int64_t(link->rel)));

          if (!of) {
            ASMJIT_ASSERT(size_t(linkOffset) < buf.size());

            // Size of the value we are going to patch. Only BYTE/DWORD is allowed.
            uint32_t displacementSize = buf._data[linkOffset];
            ASMJIT_ASSERT(buf.size() - size_t(linkOffset) >= displacementSize);

            // Overwrite a real displacement in the CodeBuffer.
            if (CodeHolder_writeDisplacement(buf._data + linkOffset, displacement, displacementSize)) {
              link.resolveAndNext(this);
              continue;
            }
          }

          err = DebugUtils::errored(kErrorInvalidDisplacement);
          // Falls through to `link.next()`.
        }

        link.next();
      } while (link);
    }
  }

  return err;
}

ASMJIT_API Error CodeHolder::bindLabel(const Label& label, uint32_t toSectionId, uint64_t toOffset) noexcept {
  LabelEntry* le = labelEntry(label);
  if (ASMJIT_UNLIKELY(!le))
    return DebugUtils::errored(kErrorInvalidLabel);

  if (ASMJIT_UNLIKELY(toSectionId > _sections.size()))
    return DebugUtils::errored(kErrorInvalidSection);

  // Label can be bound only once.
  if (ASMJIT_UNLIKELY(le->isBound()))
    return DebugUtils::errored(kErrorLabelAlreadyBound);

  // Bind the label.
  Section* section = _sections[toSectionId];
  le->_section = section;
  le->_offset = toOffset;

  Error err = kErrorOk;
  CodeBuffer& buf = section->buffer();

  // Fix all links to this label we have collected so far if they are within
  // the same section. We ignore any inter-section links as these have to be
  // fixed later.
  LabelLinkIterator link(le);
  while (link) {
    uint32_t linkSectionId = link->sectionId;
    size_t linkOffset = link->offset;

    uint32_t relocId = link->relocId;
    if (relocId != Globals::kInvalidId) {
      // Adjust relocation data only.
      RelocEntry* re = _relocations[relocId];
      re->_payload += toOffset;
      re->_targetSectionId = toSectionId;
    }
    else {
      if (linkSectionId != toSectionId) {
        link.next();
        continue;
      }

      ASMJIT_ASSERT(linkOffset < buf.size());
      int64_t displacement = int64_t(toOffset - uint64_t(linkOffset) + uint64_t(int64_t(link->rel)));

      // Size of the value we are going to patch. Only BYTE/DWORD is allowed.
      uint32_t displacementSize = buf._data[linkOffset];
      ASMJIT_ASSERT(buf.size() - size_t(linkOffset) >= displacementSize);

      // Overwrite a real displacement in the CodeBuffer.
      if (!CodeHolder_writeDisplacement(buf._data + linkOffset, displacement, displacementSize)) {
        err = DebugUtils::errored(kErrorInvalidDisplacement);
        link.next();
        continue;
      }
    }

    link.resolveAndNext(this);
  }

  return err;
}

// ============================================================================
// [asmjit::BaseEmitter - Relocations]
// ============================================================================

Error CodeHolder::newRelocEntry(RelocEntry** dst, uint32_t relocType, uint32_t valueSize) noexcept {
  ASMJIT_PROPAGATE(_relocations.willGrow(&_allocator));

  uint32_t relocId = _relocations.size();
  if (ASMJIT_UNLIKELY(relocId == Globals::kInvalidId))
    return DebugUtils::errored(kErrorTooManyRelocations);

  RelocEntry* re = _allocator.allocZeroedT<RelocEntry>();
  if (ASMJIT_UNLIKELY(!re))
    return DebugUtils::errored(kErrorOutOfMemory);

  re->_id = relocId;
  re->_relocType = uint8_t(relocType);
  re->_valueSize = uint8_t(valueSize);
  re->_sourceSectionId = Globals::kInvalidId;
  re->_targetSectionId = Globals::kInvalidId;
  _relocations.appendUnsafe(re);

  *dst = re;
  return kErrorOk;
}

// ============================================================================
// [asmjit::BaseEmitter - Expression Evaluation]
// ============================================================================

static Error CodeHolder_evaluateExpression(CodeHolder* self, Expression* exp, uint64_t* out) noexcept {
  uint64_t value[2];
  for (size_t i = 0; i < 2; i++) {
    uint64_t v;
    switch (exp->valueType[i]) {
      case Expression::kValueNone: {
        v = 0;
        break;
      }

      case Expression::kValueConstant: {
        v = exp->value[i].constant;
        break;
      }

      case Expression::kValueLabel: {
        LabelEntry* le = exp->value[i].label;
        if (!le->isBound())
          return DebugUtils::errored(kErrorExpressionLabelNotBound);
        v = le->section()->offset() + le->offset();
        break;
      }

      case Expression::kValueExpression: {
        Expression* nested = exp->value[i].expression;
        ASMJIT_PROPAGATE(CodeHolder_evaluateExpression(self, nested, &v));
        break;
      }

      default:
        return DebugUtils::errored(kErrorInvalidState);
    }

    value[i] = v;
  }

  uint64_t result;
  uint64_t& a = value[0];
  uint64_t& b = value[1];

  switch (exp->opType) {
    case Expression::kOpAdd:
      result = a + b;
      break;

    case Expression::kOpSub:
      result = a - b;
      break;

    case Expression::kOpMul:
      result = a * b;
      break;

    case Expression::kOpSll:
      result = (b > 63) ? uint64_t(0) : uint64_t(a << b);
      break;

    case Expression::kOpSrl:
      result = (b > 63) ? uint64_t(0) : uint64_t(a >> b);
      break;

    case Expression::kOpSra:
      result = Support::sar(a, Support::min<uint64_t>(b, 63));
      break;

    default:
      return DebugUtils::errored(kErrorInvalidState);
  }

  *out = result;
  return kErrorOk;
}

// ============================================================================
// [asmjit::BaseEmitter - Utilities]
// ============================================================================

Error CodeHolder::flatten() noexcept {
  uint64_t offset = 0;
  for (Section* section : _sections) {
    uint64_t realSize = section->realSize();
    if (realSize) {
      uint64_t alignedOffset = Support::alignUp(offset, section->alignment());
      if (ASMJIT_UNLIKELY(alignedOffset < offset))
        return DebugUtils::errored(kErrorTooLarge);

      Support::FastUInt8 of = 0;
      offset = Support::addOverflow(alignedOffset, realSize, &of);

      if (ASMJIT_UNLIKELY(of))
        return DebugUtils::errored(kErrorTooLarge);
    }
  }

  // Now we know that we can assign offsets of all sections properly.
  Section* prev = nullptr;
  offset = 0;
  for (Section* section : _sections) {
    uint64_t realSize = section->realSize();
    if (realSize)
      offset = Support::alignUp(offset, section->alignment());
    section->_offset = offset;

    // Make sure the previous section extends a bit to cover the alignment.
    if (prev)
      prev->_virtualSize = offset - prev->_offset;

    prev = section;
    offset += realSize;
  }

  return kErrorOk;
}

size_t CodeHolder::codeSize() const noexcept {
  Support::FastUInt8 of = 0;
  uint64_t offset = 0;

  for (Section* section : _sections) {
    uint64_t realSize = section->realSize();

    if (realSize) {
      uint64_t alignedOffset = Support::alignUp(offset, section->alignment());
      ASMJIT_ASSERT(alignedOffset >= offset);
      offset = Support::addOverflow(alignedOffset, realSize, &of);
    }
  }

  // TODO: Not nice, maybe changing `codeSize()` to return `uint64_t` instead?
  if ((sizeof(uint64_t) > sizeof(size_t) && offset > SIZE_MAX) || of)
    return SIZE_MAX;

  return size_t(offset);
}

Error CodeHolder::relocateToBase(uint64_t baseAddress) noexcept {
  // Base address must be provided.
  if (ASMJIT_UNLIKELY(baseAddress == Globals::kNoBaseAddress))
    return DebugUtils::errored(kErrorInvalidArgument);

  _codeInfo.setBaseAddress(baseAddress);
  uint32_t gpSize = _codeInfo.gpSize();

  Section* addressTableSection = _addressTableSection;
  uint32_t addressTableEntryCount = 0;
  uint8_t* addressTableEntryData = nullptr;

  if (addressTableSection) {
    ASMJIT_PROPAGATE(
      reserveBuffer(&addressTableSection->_buffer, size_t(addressTableSection->virtualSize())));
    addressTableEntryData = addressTableSection->_buffer.data();
  }

  // Relocate all recorded locations.
  for (const RelocEntry* re : _relocations) {
    // Possibly deleted or optimized-out entry.
    if (re->relocType() == RelocEntry::kTypeNone)
      continue;

    Section* sourceSection = sectionById(re->sourceSectionId());
    Section* targetSection = nullptr;

    if (re->targetSectionId() != Globals::kInvalidId)
      targetSection = sectionById(re->targetSectionId());

    uint64_t value = re->payload();
    uint64_t sectionOffset = sourceSection->offset();
    uint64_t sourceOffset = re->sourceOffset();

    // Make sure that the `RelocEntry` doesn't go out of bounds.
    size_t regionSize = re->leadingSize() + re->valueSize() + re->trailingSize();
    if (ASMJIT_UNLIKELY(re->sourceOffset() >= sourceSection->bufferSize() ||
                        sourceSection->bufferSize() - size_t(re->sourceOffset()) < regionSize))
      return DebugUtils::errored(kErrorInvalidRelocEntry);

    uint8_t* buffer = sourceSection->data();
    size_t valueOffset = size_t(re->sourceOffset()) + re->leadingSize();

    switch (re->relocType()) {
      case RelocEntry::kTypeExpression: {
        Expression* expression = (Expression*)(uintptr_t(value));
        ASMJIT_PROPAGATE(CodeHolder_evaluateExpression(this, expression, &value));
        break;
      }

      case RelocEntry::kTypeAbsToAbs: {
        break;
      }

      case RelocEntry::kTypeRelToAbs: {
        // Value is currently a relative offset from the start of its section.
        // We have to convert it to an absolute offset (including base address).
        if (ASMJIT_UNLIKELY(!targetSection))
          return DebugUtils::errored(kErrorInvalidRelocEntry);

        //value += baseAddress + sectionOffset + sourceOffset + regionSize;
        value += baseAddress + targetSection->offset();
        break;
      }

      case RelocEntry::kTypeAbsToRel: {
        value -= baseAddress + sectionOffset + sourceOffset + regionSize;
        if (gpSize > 4 && !Support::isInt32(int64_t(value)))
          return DebugUtils::errored(kErrorRelocOffsetOutOfRange);
        break;
      }

      case RelocEntry::kTypeX64AddressEntry: {
        if (re->valueSize() != 4 || re->leadingSize() < 2)
          return DebugUtils::errored(kErrorInvalidRelocEntry);

        // First try whether a relative 32-bit displacement would work.
        value -= baseAddress + sectionOffset + sourceOffset + regionSize;
        if (!Support::isInt32(int64_t(value))) {
          // Relative 32-bit displacement is not possible, use '.addrtab' section.
          AddressTableEntry* atEntry = _addressTableEntries.get(re->payload());
          if (ASMJIT_UNLIKELY(!atEntry))
            return DebugUtils::errored(kErrorInvalidRelocEntry);

          // Cannot be null as we have just matched the `AddressTableEntry`.
          ASMJIT_ASSERT(addressTableSection != nullptr);

          if (!atEntry->hasAssignedSlot())
            atEntry->_slot = addressTableEntryCount++;

          size_t atEntryIndex = size_t(atEntry->slot()) * gpSize;
          uint64_t addrSrc = sectionOffset + sourceOffset + regionSize;
          uint64_t addrDst = addressTableSection->offset() + uint64_t(atEntryIndex);

          value = addrDst - addrSrc;
          if (!Support::isInt32(int64_t(value)))
            return DebugUtils::errored(kErrorRelocOffsetOutOfRange);

          // Bytes that replace [REX, OPCODE] bytes.
          uint32_t byte0 = 0xFF;
          uint32_t byte1 = buffer[valueOffset - 1];

          if (byte1 == 0xE8) {
            // Patch CALL/MOD byte to FF /2 (-> 0x15).
            byte1 = x86EncodeMod(0, 2, 5);
          }
          else if (byte1 == 0xE9) {
            // Patch JMP/MOD byte to FF /4 (-> 0x25).
            byte1 = x86EncodeMod(0, 4, 5);
          }
          else {
            return DebugUtils::errored(kErrorInvalidRelocEntry);
          }

          // Patch `jmp/call` instruction.
          buffer[valueOffset - 2] = uint8_t(byte0);
          buffer[valueOffset - 1] = uint8_t(byte1);

          Support::writeU64uLE(addressTableEntryData + atEntryIndex, re->payload());
        }
        break;
      }

      default:
        return DebugUtils::errored(kErrorInvalidRelocEntry);
    }

    switch (re->valueSize()) {
      case 1:
        Support::writeU8(buffer + valueOffset, uint32_t(value & 0xFFu));
        break;

      case 2:
        Support::writeU16uLE(buffer + valueOffset, uint32_t(value & 0xFFFFu));
        break;

      case 4:
        Support::writeU32uLE(buffer + valueOffset, uint32_t(value & 0xFFFFFFFFu));
        break;

      case 8:
        Support::writeU64uLE(buffer + valueOffset, value);
        break;

      default:
        return DebugUtils::errored(kErrorInvalidRelocEntry);
    }
  }

  // Fixup the virtual size of the address table if it's the last section.
  if (_sections.last() == addressTableSection) {
    size_t addressTableSize = addressTableEntryCount * gpSize;
    addressTableSection->_buffer._size = addressTableSize;
    addressTableSection->_virtualSize = addressTableSize;
  }

  return kErrorOk;
}

Error CodeHolder::copySectionData(void* dst, size_t dstSize, uint32_t sectionId, uint32_t options) noexcept {
  if (ASMJIT_UNLIKELY(!isSectionValid(sectionId)))
    return DebugUtils::errored(kErrorInvalidSection);

  Section* section = sectionById(sectionId);
  size_t bufferSize = section->bufferSize();

  if (ASMJIT_UNLIKELY(dstSize < bufferSize))
    return DebugUtils::errored(kErrorInvalidArgument);

  memcpy(dst, section->data(), bufferSize);

  if (bufferSize < dstSize && (options & kCopyWithPadding)) {
    size_t paddingSize = dstSize - bufferSize;
    memset(static_cast<uint8_t*>(dst) + bufferSize, 0, paddingSize);
  }

  return kErrorOk;
}

Error CodeHolder::copyFlattenedData(void* dst, size_t dstSize, uint32_t options) noexcept {
  size_t end = 0;
  for (Section* section : _sections) {
    if (section->offset() > dstSize)
      return DebugUtils::errored(kErrorInvalidArgument);

    size_t bufferSize = section->bufferSize();
    size_t offset = size_t(section->offset());

    if (ASMJIT_UNLIKELY(dstSize - offset < bufferSize))
      return DebugUtils::errored(kErrorInvalidArgument);

    uint8_t* dstTarget = static_cast<uint8_t*>(dst) + offset;
    size_t paddingSize = 0;
    memcpy(dstTarget, section->data(), bufferSize);

    if ((options & kCopyWithPadding) && bufferSize < section->virtualSize()) {
      paddingSize = Support::min<size_t>(dstSize - offset, size_t(section->virtualSize())) - bufferSize;
      memset(dstTarget + bufferSize, 0, paddingSize);
    }

    end = Support::max(end, offset + bufferSize + paddingSize);
  }

  // TODO: `end` is not used atm, we need an option to also pad anything beyond
  // the code in case that the destination was much larger (for example page-size).

  return kErrorOk;
}

ASMJIT_END_NAMESPACE


text:
#ifndef Warn
#define Warn(MSG,...) NSLog(@"WARNING: " #MSG,__VA_ARGS__)
#endif

/** Handy utility for assigning a new value to a retained instance variable. Use as:
        setObj(&_instanceVar, newValue);
    It releases the old value and retains the new one. */

void setObj( id *variable, id newValue );

/** Just like setObj except that it _copies_ the new value. */
void setObjCopy( id<NSCopying> *variable, id<NSCopying> newValue );

void DelayFor( NSTimeInterval interval );

void PreloadSound( NSString* name );
void PlaySound( NSString* name );
void Beep( void );

redpajama_set_name: RedPajamaGithub


text:
package iso20022

// Choice between formats to express the corporate event type.
type CorporateActionEventType16Choice struct {

	// Event types expressed as a code.
	Code *CorporateActionEventType14Code `xml:"Cd"`

	// Event types expressed as a proprietary code.
	Proprietary *GenericIdentification20 `xml:"Prtry"`
}

func (c *CorporateActionEventType16Choice) SetCode(value string) {
	c.Code = (*CorporateActionEventType14Code)(&value)
}

func (c *CorporateActionEventType16Choice) AddProprietary() *GenericIdentification20 {
	c.Proprietary = new(GenericIdentification20)
	return c.Proprietary
}


text:
namespace CopyRestAPI.Models.Permissions
{
    public class FileSystemPermission : WritePermisson { }
}


text:
> see https://aka.ms/autorest

Configuration for generating Vision SDK.

The current release is `release_1_0`.

``` yaml

tag: release_1_0
openapi-type: data-plane
```
# Releases

### Release 1.0
These settings apply only when `--tag=release_1_0` is specified on the command line.

``` yaml $(tag) == 'release_1_0'
input-file: v1.0/Face.json
```

## CSharp Settings
These settings apply only when `--csharp` is specified on the command line.
``` yaml $(csharp)
csharp:
  license-header: MICROSOFT_MIT_NO_VERSION
  azure-arm: false
  namespace: Microsoft.Azure.CognitiveServices.Vision.Face
  output-folder: $(csharp-sdks-folder)/CognitiveServices/dataPlane/Vision/Microsoft.CognitiveServices.Vision/Generated/Face
  clear-output-folder: true
```


text:
from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ("archives", "0002_auto_20201214_0939"),
    ]

    operations = [
        migrations.AlterModelOptions(
            name="archive",
            options={
                "ordering": ("created",),
                "permissions": [
                    (
                        "use_archive",
                        "Can use the objects in the archive as inputs to algorithms, reader studies and challenges.",
                    ),
                    ("upload_archive", "Can upload to archive"),
                ],
            },
        ),
    ]


text:
import sys
import json
import tia.configuration as conf

def report(_marketName, _MarketsD):
    try:
        universeSize = 0
        cumulFunds = 0; cumulItems = 0
        cumulVal = 0
        topBids = []
        topAsks = []
        # get universe state
        for Market in _MarketsD.values():
            exchangeRate = Market.exchangeRates[Market.currency]
            if conf.UNIVERSE in Market.name:
                universeSize += 1
                locFunds = Market.account.reservedFunds + Market.account.availableFunds
                cumulFunds += locFunds
                locItems = Market.account.reservedItems + Market.account.availableItems
                cumulItems += locItems
                try:
                    topBid = Market.orderbook.bids.largest_key() * exchangeRate     # for pretty printing of TM status
                    topAsk = Market.orderbook.asks.smallest_key() * exchangeRate
                    cumulVal += locFunds + locItems * Market.orderbook.bids.largest_key()
                except KeyError:
                    cumulVal += locFunds
                    topBid = 0
                    topAsk = 0

                topBids.append(float(topBid))
                topAsks.append(float(topAsk))

        # local state
        Market = _MarketsD[_marketName]
        tmpF = Market.targetManager.targetFunds
        tmpI = Market.targetManager.targetItems
        tmFunds = {}; tmItems = {}
        for p in tmpF: tmFunds[float(p)] = float(tmpF[p])
        for p in tmpI: tmItems[float(p)] = float(tmpI[p])
        #for amount in Market.targetManager.targetFunds.values(): tmFunds += amount
        #for amount in Market.targetManager.targetItems.values(): tmItems += amount
        if conf.UNIVERSE in Market.name:
            try:
                topBid = Market.orderbook.bids.largest_key()    # for loc values
                topAsk = Market.orderbook.asks.smallest_key()
                sys.stderr.write("\nuniverse\tF: %s\tI: %s\tV: %s:L1:%s|%s\tdate: %s" % (cumulFunds, cumulItems, cumulVal, topBid, topAsk, Market.lastUpdate))
                dump = {"cumulFunds": float(cumulFunds), "cumulItems": float(cumulItems), "value": float(cumulVal),
                        "tmFunds": tmFunds, "tmItems": tmItems,
                        "universeSize": universeSize,
                        "topBids": topBids,
                        "topAsks": topAsks}
                with open(conf.FN_REPORT, "a") as f:
                    json.dump(dump, f)
                    f.write("\n")
            except KeyError as ex:
                raise Exception("ex: %s, %s" % (ex, Market))
        else:
            sys.stderr.write("\nmarket not in universe: %s" %_marketName)

    except Exception: raise


text:
namespace dlib
{

// ----------------------------------------------------------------------------------------

    struct row_major_layout;

// ----------------------------------------------------------------------------------------

    template <
        typename T,
        long num_rows = 0,
        long num_cols = 0,
        typename mem_manager = default_memory_manager,
        typename layout = row_major_layout
        >
    class matrix;

// ----------------------------------------------------------------------------------------

}

#endif // DLIB_MATRIx_FWD


text:
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;
using Azure.ResourceManager.SecurityInsights;

namespace Azure.ResourceManager.SecurityInsights.Models
{
    internal partial class EntityList
    {
        internal static EntityList DeserializeEntityList(JsonElement element)
        {
            Optional<string> nextLink = default;
            IReadOnlyList<EntityData> value = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("nextLink"))
                {
                    nextLink = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("value"))
                {
                    List<EntityData> array = new List<EntityData>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(EntityData.DeserializeEntityData(item));
                    }
                    value = array;
                    continue;
                }
            }
            return new EntityList(nextLink.Value, value);
        }
    }
}


text:
package nyc.friendlyrobot.sample.data.model;

import org.immutables.value.Value;

@Value.Immutable
@Value.Style(allParameters = true)
public abstract class Bar implements BarModel{
    public static final BarModel.Mapper<Bar> MAPPER =
            new BarModel.Mapper<>((Mapper.Creator<Bar>) ImmutableBar::of);

    public static final class Marshal extends BarModel.BarMarshal {
    }
}


text:
package org.wso2.carbon.device.mgt.output.adapter.http.util;

import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterConfiguration;

import java.util.Map;

public class HTTPConnectionConfiguration {

    private String adapterName;
    private String username;
    private String password;
    private String dcrUrl;
    private String scopes;
    private String tokenUrl;
    private boolean globalCredentialSet;

    public HTTPConnectionConfiguration(OutputEventAdapterConfiguration eventAdapterConfiguration,
                                       Map<String, String> globalProperties) {
        adapterName = eventAdapterConfiguration.getName();
        this.username = eventAdapterConfiguration.getStaticProperties().get(HTTPEventAdapterConstants.ADAPTER_USERNAME);
        this.password = eventAdapterConfiguration.getStaticProperties().get(HTTPEventAdapterConstants.ADAPTER_PASSWORD);
        if ((username == null || username.isEmpty()) && (password == null || password.isEmpty())) {
            username = globalProperties.get(HTTPEventAdapterConstants.ADAPTER_USERNAME);
            password = globalProperties.get(HTTPEventAdapterConstants.ADAPTER_PASSWORD);
            globalCredentialSet = true;
        }

        this.dcrUrl = PropertyUtils
                .replaceMqttProperty(globalProperties.get(HTTPEventAdapterConstants.ADAPTER_CONF_DCR_URL));
        this.tokenUrl = PropertyUtils
                .replaceMqttProperty(globalProperties.get(HTTPEventAdapterConstants.ADAPTER_CONF_TOKEN_URL));
        this.scopes = eventAdapterConfiguration.getStaticProperties().get(HTTPEventAdapterConstants.ADAPTER_CONF_SCOPES);
        if (scopes == null) {
            this.scopes = HTTPEventAdapterConstants.EMPTY_STRING;
        }
    }

    public String getTokenUrl() {
        return tokenUrl;
    }

    public String getDcrUrl() {
        return dcrUrl;
    }

    public String getScopes() {
        return scopes;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public String getAdapterName() {
        return adapterName;
    }

    public boolean isGlobalCredentialSet() {
        return globalCredentialSet;
    }

}


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

namespace Unity_Studio
{
    class Material
    {

        public string m_Name;
        public PPtr m_Shader;
        public string[] m_ShaderKeywords;
        public int m_CustomRenderQueue;
        public TexEnv[] m_TexEnvs;
        public strFloatPair[] m_Floats;
        public strColorPair[] m_Colors;

        public Material(AssetPreloadData preloadData)
        {
            var sourceFile = preloadData.sourceFile;
            var a_Stream = preloadData.sourceFile.a_Stream;
            a_Stream.Position = preloadData.Offset;

            if (sourceFile.platform == -2)
            {
                uint m_ObjectHideFlags = a_Stream.ReadUInt32();
                PPtr m_PrefabParentObject = sourceFile.ReadPPtr();
                PPtr m_PrefabInternal = sourceFile.ReadPPtr();
            }

            m_Name = a_Stream.ReadAlignedString(a_Stream.ReadInt32());
            m_Shader = sourceFile.ReadPPtr();

            if (sourceFile.version[0] == 4 && (sourceFile.version[1] >= 2 || (sourceFile.version[1] == 1 && sourceFile.buildType[0] != "a")))
            {
                m_ShaderKeywords = new string[a_Stream.ReadInt32()];
                for (int i = 0; i < m_ShaderKeywords.Length; i++)
                {
                    m_ShaderKeywords[i] = a_Stream.ReadAlignedString(a_Stream.ReadInt32());
                }
            }
            else if (sourceFile.version[0] >= 5)//5.0 and up
            {
                m_ShaderKeywords = new string[1] { a_Stream.ReadAlignedString(a_Stream.ReadInt32()) };
                uint m_LightmapFlags = a_Stream.ReadUInt32();
                if (sourceFile.version[0] == 5 && sourceFile.version[1] >= 6 || sourceFile.version[0] > 5)//5.6.0 and up
                {
                    var m_EnableInstancingVariants = a_Stream.ReadBoolean();
                    //var m_DoubleSidedGI = a_Stream.ReadBoolean();//2017.x
                    a_Stream.AlignStream(4);
                }
            }

            if (sourceFile.version[0] > 4 || sourceFile.version[0] == 4 && sourceFile.version[1] >= 3) { m_CustomRenderQueue = a_Stream.ReadInt32(); }

            if (sourceFile.version[0] == 5 && sourceFile.version[1] >= 1 || sourceFile.version[0] > 5)//5.1 and up
            {
                string[][] stringTagMap = new string[a_Stream.ReadInt32()][];
                for (int i = 0; i < stringTagMap.Length; i++)
                {
                    stringTagMap[i] = new string[2] { a_Stream.ReadAlignedString(a_Stream.ReadInt32()), a_Stream.ReadAlignedString(a_Stream.ReadInt32()) };
                }
            }
            //disabledShaderPasses
            if ((sourceFile.version[0] == 5 && sourceFile.version[1] >= 6) || sourceFile.version[0] > 5)//5.6.0 and up
            {
                var size = a_Stream.ReadInt32();
                for (int i = 0; i < size; i++)
                {
                    a_Stream.ReadAlignedString(a_Stream.ReadInt32());
                }
            }
            //m_SavedProperties
            m_TexEnvs = new TexEnv[a_Stream.ReadInt32()];
            for (int i = 0; i < m_TexEnvs.Length; i++)
            {
                TexEnv m_TexEnv = new TexEnv()
                {
                    name = a_Stream.ReadAlignedString(a_Stream.ReadInt32()),
                    m_Texture = sourceFile.ReadPPtr(),
                    m_Scale = new float[2] { a_Stream.ReadSingle(), a_Stream.ReadSingle() },
                    m_Offset = new float[2] { a_Stream.ReadSingle(), a_Stream.ReadSingle() }
                };
                m_TexEnvs[i] = m_TexEnv;
            }

            m_Floats = new strFloatPair[a_Stream.ReadInt32()];
            for (int i = 0; i < m_Floats.Length; i++)
            {
                strFloatPair m_Float = new strFloatPair()
                {
                    first = a_Stream.ReadAlignedString(a_Stream.ReadInt32()),
                    second = a_Stream.ReadSingle()
                };
                m_Floats[i] = m_Float;
            }

            m_Colors = new strColorPair[a_Stream.ReadInt32()];
            for (int i = 0; i < m_Colors.Length; i++)
            {
                strColorPair m_Color = new strColorPair()
                {
                    first = a_Stream.ReadAlignedString(a_Stream.ReadInt32()),
                    second = new float[4] { a_Stream.ReadSingle(), a_Stream.ReadSingle(), a_Stream.ReadSingle(), a_Stream.ReadSingle() }
                };
                m_Colors[i] = m_Color;
            }
        }
    }
}


text:
using System.Runtime.Serialization;

namespace Org.Apache.Reef.Driver.Bridge
{
    [DataContract]
    public class HttpMessage : IHttpMessage
    {
        public HttpMessage(IHttpServerBridgeClr2Java httpServerBridgeClr2Java)
        {
            HttpServerBridgeClr2Java = httpServerBridgeClr2Java;
        }

        [DataMember]
        private IHttpServerBridgeClr2Java HttpServerBridgeClr2Java { get; set; }

        public string GetRequestString()
        {
            return HttpServerBridgeClr2Java.GetQueryString();
        }

        public void SetQueryResult(string responseString)
        {
            HttpServerBridgeClr2Java.SetQueryResult(responseString);
        }

        public byte[] GetQueryReuestData()
        {
            return HttpServerBridgeClr2Java.GetQueryRequestData();
        }

        public void SetQueryResponseData(byte[] responseData)
        {
            HttpServerBridgeClr2Java.SetQueryResponseData(responseData);
        }

        public void SetUriSpecification(string uriSpecification)
        {
            HttpServerBridgeClr2Java.SetUriSpecification(uriSpecification);
        }
    }
}


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

namespace Capgemini.CommonObjectUtils
{
    /// <summary>
    /// An abstract base class for Builder classes.
    /// </summary>
    /// <typeparam name="T">The type that the builder builds.</typeparam>
    /// <remarks>
    /// <para>
    /// You can inherit from this class when writing your own builders.
    /// </para>
    /// <para>
    /// Call the <see cref="M:Capgemini.CommonObjectUtils.Builder`1.Expect(System.String,Capgemini.CommonObjectUtils.Builder{`0}.Necessity)"/>
    /// method to tell the class what arguments your builder needs and which ones are
    /// mandatory.
    /// </para>
    /// <para>
    /// Call the <see cref="M:Capgemini.CommonObjectUtils.Builder`1.Receive``1(System.String,``0)"/>
    /// method as your builder gets each argument to tell the builder which arguments
    /// you have received.
    /// </para>
    /// <para>
    /// When client code calls the <see cref="M:Capgemini.CommonObjectUtils.Builder`1.Build"/>
    /// method the Builder class will check that all mandatory arguments
    /// have beens supplied and if they haven't it will throw a
    /// <see cref="T:Capgemini.CommonObjectUtils.MissingBuilderArgumentException"/>.
    /// If all the required arguments have been supplied the builder calls the
    /// <see cref="M:Capgemini.CommonObjectUtils.Builder`1.BuildImplementation"/>
    /// method
    /// that the sub-class supplies and building finishes.
    /// </para>
    /// <para>
    /// If you need to know if a particular argument got supplied you can call the
    /// <see cref="M:Capgemini.CommonObjectUtils.Builder`1.Got(System.String)"/>
    /// method instead of
    /// tracking that yourself.
    /// </para>
    /// </remarks>
    /// <example>
    /// Here is an example that builds integers with a mandatory starting value and an optional multiplier.
    /// <code>
    /// private class IntBuilder : Builder<int>
    /// {
    ///     private int value;
    ///     private int multiplier;
    ///
    ///     public IntBuilder()
    ///     {
    ///         Expect("value", Necessity.Mandatory);
    ///         Expect("multiplier", Necessity.Optional);
    ///     }
    ///
    ///     public IntBuilder SetValue(int value)
    ///     {
    ///         this.value = Receive("value", value);
    ///         return this;
    ///     }
    ///
    ///     public IntBuilder SetMultiplier(int multiplier)
    ///     {
    ///         this.multiplier = Receive("multiplier", multiplier);
    ///         return this;
    ///     }
    ///
    ///     protected override int BuildImplementation()
    ///     {
    ///         return value * (Got("multiplier") ? multiplier : 1);
    ///     }
    /// }
    /// </code>
    /// </example>
    public abstract class Builder<T>
    {
        /// <summary>
        /// A look up of expected argument names to their necessity.
        /// </summary>
        private Dictionary<string, Necessity> expectedArguments = new Dictionary<string, Necessity>();

        /// <summary>
        /// The set of received argument names.
        /// </summary>
        private HashSet<string> receivedArguments = new HashSet<string>();

        /// <summary>
        /// An enumeration that specifies the necessity of a builder argument (whether the argument is
        /// optional or mandatory).
        /// </summary>
        protected enum Necessity
        {
            /// <summary>
            /// An argument is mandatory.
            /// </summary>
            [System.Diagnostics.CodeAnalysis.SuppressMessage(
                "Microsoft.Design",
                "CA1000:DoNotDeclareStaticMembersOnGenericTypes",
                Justification = "Caller will not have to specify a type argument.")]
            Mandatory,

            /// <summary>
            /// An argument is optional.
            /// </summary>
            [System.Diagnostics.CodeAnalysis.SuppressMessage(
                "Microsoft.Design",
                "CA1000:DoNotDeclareStaticMembersOnGenericTypes",
                Justification = "Caller will not have to specify a type argument.")]
            Optional
        }

        /// <summary>
        /// Builds the target object.
        /// </summary>
        /// <returns>The built object.</returns>
        public T Build()
        {
            CheckArguments();

            return BuildImplementation();
        }

        /// <summary>
        /// Tells the builder that an argument is expected.
        /// </summary>
        /// <param name="argumentName">The argument name.</param>
        /// <param name="necessity">Whether the argument is mandatory or not.</param>
        protected void Expect(string argumentName, Necessity necessity)
        {
            expectedArguments.Add(argumentName, necessity);
        }

        /// <summary>
        /// Tells the builder that an argument was received.
        /// </summary>
        /// <typeparam name="TArg">The argument type.</typeparam>
        /// <param name="argumentName">The argument name.</param>
        /// <param name="value">The argument value.</param>
        /// <returns>The unchanged argument value.</returns>
        protected TArg Receive<TArg>(string argumentName, TArg value)
        {
            receivedArguments.Add(argumentName);
            return value;
        }

        /// <summary>
        /// Checks if an argument has received.
        /// </summary>
        /// <param name="argumentName">The argument name.</param>
        /// <returns>True if the argument was received.</returns>
        protected bool Got(string argumentName)
        {
            return receivedArguments.Contains(argumentName);
        }

        /// <summary>
        /// The internal implementation that builds the target object.
        /// </summary>
        /// <returns>The built object.</returns>
        protected abstract T BuildImplementation();

        /// <summary>
        /// Checks that all mandatory arguments have been supplied.
        /// </summary>
        /// <exception cref="MissingBuilderArgumentException">
        /// One of the builder's mandatory arguments wasn't supplied.
        /// </exception>
        private void CheckArguments()
        {
            List<string> missingArguments = new List<string>();

            foreach (string argument in expectedArguments.Keys)
            {
                if (expectedArguments[argument] == Necessity.Mandatory)
                {
                    if (!receivedArguments.Contains(argument))
                    {
                        missingArguments.Add(argument);
                    }
                }
            }

            if (missingArguments.Count > 0)
            {
                throw new MissingBuilderArgumentException(missingArguments.ToArray());
            }
        }
    }
}


text:
<?php

declare(strict_types=1);

namespace Sylius\Behat\Page\Admin\Taxon;

use Behat\Mink\Driver\Selenium2Driver;
use Behat\Mink\Element\NodeElement;
use Behat\Mink\Exception\ElementNotFoundException;
use Sylius\Behat\Behaviour\SpecifiesItsCode;
use Sylius\Behat\Page\Admin\Crud\CreatePage as BaseCreatePage;
use Sylius\Behat\Service\SlugGenerationHelper;
use Sylius\Component\Core\Model\TaxonInterface;
use Webmozart\Assert\Assert;

class CreatePage extends BaseCreatePage implements CreatePageInterface
{
    use SpecifiesItsCode;

    public function countTaxons(): int
    {
        return count($this->getLeaves());
    }

    public function countTaxonsByName(string $name): int
    {
        $matchedLeavesCounter = 0;
        $leaves = $this->getLeaves();
        foreach ($leaves as $leaf) {
            if (strpos($leaf->getText(), $name) !== false) {
                ++$matchedLeavesCounter;
            }
        }

        return $matchedLeavesCounter;
    }

    public function deleteTaxonOnPageByName(string $name): void
    {
        $leaves = $this->getLeaves();
        foreach ($leaves as $leaf) {
            if ($leaf->getText() === $name) {
                $leaf->getParent()->find('css', '.ui.red.button')->press();

                return;
            }
        }

        throw new ElementNotFoundException($this->getDriver(), 'Delete button');
    }

    public function describeItAs(string $description, string $languageCode): void
    {
        $this->getDocument()->fillField(sprintf('sylius_taxon_translations_%s_description', $languageCode), $description);
    }

    public function hasTaxonWithName(string $name): bool
    {
        return 0 !== $this->countTaxonsByName($name);
    }

    public function nameIt(string $name, string $languageCode): void
    {
        $this->activateLanguageTab($languageCode);
        $this->getElement('name', ['%language%' => $languageCode])->setValue($name);

        if ($this->getDriver() instanceof Selenium2Driver) {
            SlugGenerationHelper::waitForSlugGeneration(
                $this->getSession(),
                $this->getElement('slug', ['%language%' => $languageCode])
            );
        }
    }

    public function specifySlug(string $slug, string $languageCode): void
    {
        $this->getDocument()->fillField(sprintf('sylius_taxon_translations_%s_slug', $languageCode), $slug);
    }

    public function attachImage(string $path, string $type = null): void
    {
        $filesPath = $this->getParameter('files_path');

        $this->getDocument()->find('css', '[data-form-collection="add"]')->click();

        $imageForm = $this->getLastImageElement();
        $imageForm->fillField('Type', $type);
        $imageForm->find('css', 'input[type="file"]')->attachFile($filesPath . $path);
    }

    public function getLeaves(TaxonInterface $parentTaxon = null): array
    {
        $tree = $this->getElement('tree');
        Assert::notNull($tree);
        /** @var NodeElement[] $leaves */
        $leaves = $tree->findAll('css', '.item > .content > .header > a');

        if (null === $parentTaxon) {
            return $leaves;
        }

        foreach ($leaves as $leaf) {
            if ($leaf->getText() === $parentTaxon->getName()) {
                return $leaf->findAll('css', '.item > .content > .header');
            }
        }

        return [];
    }

    public function activateLanguageTab(string $locale): void
    {
        if (!$this->getDriver() instanceof Selenium2Driver) {
            return;
        }

        $languageTabTitle = $this->getElement('language_tab', ['%locale%' => $locale]);
        if (!$languageTabTitle->hasClass('active')) {
            $languageTabTitle->click();
        }
    }

    protected function getElement(string $name, array $parameters = []): NodeElement
    {
        if (!isset($parameters['%language%'])) {
            $parameters['%language%'] = 'en_US';
        }

        return parent::getElement($name, $parameters);
    }

    protected function getDefinedElements(): array
    {
        return array_merge(parent::getDefinedElements(), [
            'code' => '#sylius_taxon_code',
            'description' => '#sylius_taxon_translations_en_US_description',
            'images' => '#sylius_taxon_images',
            'language_tab' => '[data-locale="%locale%"] .title',
            'name' => '#sylius_taxon_translations_%language%_name',
            'slug' => '#sylius_taxon_translations_%language%_slug',
            'tree' => '.ui.list',
        ]);
    }

    private function getLastImageElement(): NodeElement
    {
        $images = $this->getElement('images');
        $items = $images->findAll('css', 'div[data-form-collection="item"]');

        Assert::notEmpty($items);

        return end($items);
    }
}


text:
/**
 *
 */
package org.joogie.errormodel;

import java.util.LinkedList;
import java.util.List;

import org.joogie.GlobalsCache;
import org.joogie.soot.SootPrelude;
import org.joogie.soot.SootProcedureInfo;
import org.joogie.soot.SootStmtSwitch;
import org.joogie.util.TranslationHelpers;

import soot.Scene;
import soot.SootClass;
import soot.Trap;
import soot.jimple.Stmt;
import boogie.ProgramFactory;
import boogie.ast.Attribute;
import boogie.ast.expression.Expression;
import boogie.ast.statement.Statement;
import boogie.enums.BinaryOperator;

/**
 * @author schaef
 *
 */
public abstract class AbstractErrorModel {

	protected SootProcedureInfo procInfo;
	protected SootStmtSwitch stmtSwitch;
	protected ProgramFactory pf;

	public AbstractErrorModel(SootProcedureInfo pinfo, SootStmtSwitch stmtswitch) {
		this.procInfo = pinfo;
		this.pf = GlobalsCache.v().getPf();
		this.stmtSwitch = stmtswitch;
	}

	/**
	 * Called if an exception is thrown that also occurs in the throws clause
	 *
	 * @param guard
	 *            the condition which must be violated in order to have the
	 *            exception thrown. May be null if the exception is always
	 *            thrown.
	 * @param exception
	 */
	abstract public void createdExpectedException(Expression guard,
			SootClass exception);

	/**
	 * Called if an exception is thrown that also occurs in NOT the throws
	 * clause
	 *
	 * @param guard
	 *            the condition which must be violated in order to have the
	 *            exception thrown. May be null if the exception is always
	 *            thrown.
	 * @param exception
	 */
	abstract public void createdUnExpectedException(Expression guard,
			SootClass exception);

	protected void createException(Expression guard, SootClass exception) {

		List<Trap> traps =  new LinkedList<Trap>();
		List<Trap> finally_traps =  new LinkedList<Trap>(); //TODO: do we have to use them here?
		TranslationHelpers.getReachableTraps(this.stmtSwitch.getCurrentStatement(), this.procInfo.getSootMethod(), traps, finally_traps);

		String transferlabel = null;
		for (Trap trap : traps) {
			if (GlobalsCache.v().isSubTypeOrEqual(exception,
					trap.getException())) {
				transferlabel = GlobalsCache.v().getUnitLabel(
						(Stmt) trap.getHandlerUnit());
				break;
			}
		}

		if (transferlabel == null) {
			// if not, check if the exception is in the throws clause
			if (GlobalsCache.v().inThrowsClause(exception, this.procInfo)) {
				createdExpectedException(guard, exception);
			} else {
				createdUnExpectedException(guard, exception);
			}
		} else {

			// if the exception is caught, create a goto
			Statement transferStatement = this.pf
					.mkGotoStatement(transferlabel);

			// now assign the exception variable to make sure that the catch
			// block
			// is feasible when we transfer there.
			Expression exception_type = GlobalsCache.v().lookupClassVariable(
					exception);
			Statement raise = SootPrelude.v().newObject(new Attribute[] {},
					this.procInfo.getExceptionVariable(), exception_type);
			// if the exception is guarded create a conditional choice,
			// otherwise just throw it.
			if (guard != null) {
				Statement[] elsePart = {TranslationHelpers
						.mkLocationAssertion(this.stmtSwitch
								.getCurrentStatement()),
						this.pf.mkAssertStatement(
								new Attribute[] { pf.mkNoVerifyAttribute()  },
								pf.mkBooleanLiteral(true)), raise,
						transferStatement };
				Statement[] thenPart = { TranslationHelpers
						.mkLocationAssertion(this.stmtSwitch
								.getCurrentStatement()) };
				this.stmtSwitch.addStatement(this.pf.mkIfStatement(guard,
						thenPart, elsePart));
			} else {
				this.stmtSwitch.addStatement(raise);
				this.stmtSwitch.addStatement(transferStatement);
			}
		}
	}

	public Statement createAssumeNonNull(Expression expr) {
		Expression guard = this.pf
				.mkBinaryExpression(this.pf.getBoolType(),
						BinaryOperator.COMPNEQ, expr, SootPrelude.v()
								.getNullConstant());
		return this.pf.mkAssumeStatement(new Attribute[0], guard);
	}

	public void createUnguardedException(SootClass exception) {
		createException(null, exception);
	}

	public void createNonNullViolationException(Expression expr) {
		Expression guard = this.pf
				.mkBinaryExpression(this.pf.getBoolType(),
						BinaryOperator.COMPNEQ, expr, SootPrelude.v()
								.getNullConstant());
		// TODO: it is actually not a java.lang.RuntimeException ... but I don't
		// have anything usefull to report!
		createException(
				guard,
				Scene.v().loadClass("java.lang.RuntimeException",
						SootClass.SIGNATURES));
	}

	public void createPreconditionViolationException(Expression expr) {
		// TODO: it is actually not a java.lang.RuntimeException ... but I don't
		// have anything usefull to report!
		createException(
				expr,
				Scene.v().loadClass("java.lang.RuntimeException",
						SootClass.SIGNATURES));
	}

	public void createPostconditionViolationException(Expression expr) {
		// TODO: it is actually not a java.lang.RuntimeException ... but I don't
		// have anything usefull to report!
		createException(
				expr,
				Scene.v().loadClass("java.lang.RuntimeException",
						SootClass.SIGNATURES));
	}

	public void createArrayBoundGuard(Expression baseExpression,
			Expression indexExpression) {
		Expression upperbound = this.pf.mkBinaryExpression(
				this.pf.getBoolType(), BinaryOperator.COMPLT, indexExpression,
				GlobalsCache.v().getArraySizeExpression(baseExpression));

		Expression lowerbound = this.pf.mkBinaryExpression(
				this.pf.getBoolType(), BinaryOperator.COMPGEQ, indexExpression,
				this.pf.mkIntLiteral("0"));

		Expression guard = this.pf.mkBinaryExpression(this.pf.getBoolType(),
				BinaryOperator.LOGICAND, upperbound, lowerbound);
		createException(
				guard,
				Scene.v().loadClass("java.lang.ArrayIndexOutOfBoundsException",
						SootClass.SIGNATURES));
	}

	public void createNonNullGuard(Expression expr) {
		Expression guard = this.pf
				.mkBinaryExpression(this.pf.getBoolType(),
						BinaryOperator.COMPNEQ, expr, SootPrelude.v()
								.getNullConstant());
		createException(
				guard,
				Scene.v().loadClass("java.lang.NullPointerException",
						SootClass.SIGNATURES));
	}

	public void createDivByZeroGuard(Expression expr) {
		Expression guard = this.pf.mkBinaryExpression(this.pf.getBoolType(),
				BinaryOperator.COMPNEQ, expr, this.pf.mkIntLiteral("0"));
		createException(
				guard,
				Scene.v().loadClass("java.lang.ArithmeticException",
						SootClass.SIGNATURES));
	}

	public void createClassCastGuard(Expression subtype, Expression supertype) {
		Expression guard = GlobalsCache.v().compareTypeExpressions(subtype,
				supertype);
		createException(
				guard,
				Scene.v().loadClass("java.lang.ClassCastException",
						SootClass.SIGNATURES));
	}
}


text:
package com.squareup.okhttp.internal.http;

import com.squareup.okhttp.Request;
import java.net.Proxy;
import java.net.URL;

public final class RequestLine {
  private RequestLine() {
  }

  /**
   * Returns the request status line, like "GET / HTTP/1.1". This is exposed
   * to the application by {@link HttpURLConnectionImpl#getHeaderFields}, so
   * it needs to be set even if the transport is SPDY.
   */
  static String get(Request request, Proxy.Type proxyType, int httpMinorVersion) {
    StringBuilder result = new StringBuilder();
    result.append(request.method());
    result.append(" ");

    if (includeAuthorityInRequestLine(request, proxyType)) {
      result.append(request.url());
    } else {
      result.append(requestPath(request.url()));
    }

    result.append(" ");
    result.append(version(httpMinorVersion));
    return result.toString();
  }

  /**
   * Returns true if the request line should contain the full URL with host
   * and port (like "GET http://android.com/foo HTTP/1.1") or only the path
   * (like "GET /foo HTTP/1.1").
   */
  private static boolean includeAuthorityInRequestLine(Request request, Proxy.Type proxyType) {
    return !request.isHttps() && proxyType == Proxy.Type.HTTP;
  }

  /**
   * Returns the path to request, like the '/' in 'GET / HTTP/1.1'. Never empty,
   * even if the request URL is. Includes the query component if it exists.
   */
  public static String requestPath(URL url) {
    String pathAndQuery = url.getFile();
    if (pathAndQuery == null) return "/";
    if (!pathAndQuery.startsWith("/")) return "/" + pathAndQuery;
    return pathAndQuery;
  }

  public static String version(int httpMinorVersion) {
    return httpMinorVersion == 1 ? "HTTP/1.1" : "HTTP/1.0";
  }
}


text:
package java.lang

import java.io._

import scala.scalajs.js
import scala.scalajs.js.Dynamic.global
import scala.scalajs.LinkingInfo.assumingES6
import scala.scalajs.runtime.{linkingInfo, SemanticsUtils}

import java.{util => ju}

object System {
  var out: PrintStream = new JSConsoleBasedPrintStream(isErr = false)
  var err: PrintStream = new JSConsoleBasedPrintStream(isErr = true)
  var in: InputStream = null

  def setIn(in: InputStream): Unit =
    this.in = in

  def setOut(out: PrintStream): Unit =
    this.out = out

  def setErr(err: PrintStream): Unit =
    this.err = err

  def currentTimeMillis(): scala.Long = {
    (new js.Date).getTime().toLong
  }

  private[this] val getHighPrecisionTime: js.Function0[scala.Double] = {
    import js.DynamicImplicits.truthValue

    if (js.typeOf(global.performance) != "undefined") {
      if (global.performance.now) {
        () => global.performance.now().asInstanceOf[scala.Double]
      } else if (global.performance.webkitNow) {
        () => global.performance.webkitNow().asInstanceOf[scala.Double]
      } else {
        () => new js.Date().getTime()
      }
    } else {
      () => new js.Date().getTime()
    }
  }

  def nanoTime(): scala.Long =
    (getHighPrecisionTime() * 1000000).toLong

  def arraycopy(src: Object, srcPos: scala.Int, dest: Object,
      destPos: scala.Int, length: scala.Int): Unit = {

    import scala.{Boolean, Char, Byte, Short, Int, Long, Float, Double}

    @inline def checkIndices(srcLen: Int, destLen: Int): Unit = {
      SemanticsUtils.arrayIndexOutOfBoundsCheck({
        srcPos < 0 || destPos < 0 || length < 0 ||
        srcPos > srcLen - length ||
        destPos > destLen - length
      }, {
        new ArrayIndexOutOfBoundsException()
      })
    }

    def mismatch(): Nothing =
      throw new ArrayStoreException("Incompatible array types")

    val forward = (src ne dest) || destPos < srcPos || srcPos + length < destPos

    def copyPrim[@specialized T](src: Array[T], dest: Array[T]): Unit = {
      checkIndices(src.length, dest.length)
      if (forward) {
        var i = 0
        while (i < length) {
          dest(i+destPos) = src(i+srcPos)
          i += 1
        }
      } else {
        var i = length-1
        while (i >= 0) {
          dest(i+destPos) = src(i+srcPos)
          i -= 1
        }
      }
    }

    def copyRef(src: Array[AnyRef], dest: Array[AnyRef]): Unit = {
      checkIndices(src.length, dest.length)
      if (forward) {
        var i = 0
        while (i < length) {
          dest(i+destPos) = src(i+srcPos)
          i += 1
        }
      } else {
        var i = length-1
        while (i >= 0) {
          dest(i+destPos) = src(i+srcPos)
          i -= 1
        }
      }
    }

    if (src == null || dest == null) {
      throw new NullPointerException()
    } else (src match {
      case src: Array[AnyRef] =>
        dest match {
          case dest: Array[AnyRef] => copyRef(src, dest)
          case _                   => mismatch()
        }
      case src: Array[Boolean] =>
        dest match {
          case dest: Array[Boolean] => copyPrim(src, dest)
          case _                    => mismatch()
        }
      case src: Array[Char] =>
        dest match {
          case dest: Array[Char] => copyPrim(src, dest)
          case _                 => mismatch()
        }
      case src: Array[Byte] =>
        dest match {
          case dest: Array[Byte] => copyPrim(src, dest)
          case _                 => mismatch()
        }
      case src: Array[Short] =>
        dest match {
          case dest: Array[Short] => copyPrim(src, dest)
          case _                  => mismatch()
        }
      case src: Array[Int] =>
        dest match {
          case dest: Array[Int] => copyPrim(src, dest)
          case _                => mismatch()
        }
      case src: Array[Long] =>
        dest match {
          case dest: Array[Long] => copyPrim(src, dest)
          case _                 => mismatch()
        }
      case src: Array[Float] =>
        dest match {
          case dest: Array[Float] => copyPrim(src, dest)
          case _                  => mismatch()
        }
      case src: Array[Double] =>
        dest match {
          case dest: Array[Double] => copyPrim(src, dest)
          case _                   => mismatch()
        }
      case _ =>
        mismatch()
    })
  }

  def identityHashCode(x: Object): scala.Int = {
    (x: Any) match {
      case null => 0
      case _:scala.Boolean | _:scala.Double | _:String | () =>
        x.hashCode()
      case _ =>
        import IDHashCode._
        if (x.getClass == null) {
          /* x is not a Scala.js object: we have delegate to x.hashCode().
           * This is very important, as we really need to go through
           * `$objectHashCode()` in `CoreJSLib` instead of using our own
           * `idHashCodeMap`. That's because `$objectHashCode()` uses the
           * intrinsic `$systemIdentityHashCode` for JS objects, regardless of
           * whether the optimizer is enabled or not. If we use our own
           * `idHashCodeMap`, we will get different hash codes when obtained
           * through `System.identityHashCode(x)` than with `x.hashCode()`.
           */
          x.hashCode()
        } else if (assumingES6 || idHashCodeMap != null) {
          // Use the global WeakMap of attributed id hash codes
          val hash = idHashCodeMap.get(x.asInstanceOf[js.Any])
          if (!js.isUndefined(hash)) {
            hash.asInstanceOf[Int]
          } else {
            val newHash = nextIDHashCode()
            idHashCodeMap.set(x.asInstanceOf[js.Any], newHash)
            newHash
          }
        } else {
          val hash = x.asInstanceOf[js.Dynamic].selectDynamic("$idHashCode$0")
          if (!js.isUndefined(hash)) {
            /* Note that this can work even if x is sealed, if
             * identityHashCode() was called for the first time before x was
             * sealed.
             */
            hash.asInstanceOf[Int]
          } else if (!js.Object.isSealed(x.asInstanceOf[js.Object])) {
            /* If x is not sealed, we can (almost) safely create an additional
             * field with a bizarre and relatively long name, even though it is
             * technically undefined behavior.
             */
            val newHash = nextIDHashCode()
            x.asInstanceOf[js.Dynamic].updateDynamic("$idHashCode$0")(newHash)
            newHash
          } else {
            // Otherwise, we unfortunately have to return a constant.
            42
          }
        }
    }
  }

  private object IDHashCode {
    private var lastIDHashCode: Int = 0

    val idHashCodeMap =
      if (assumingES6 || js.typeOf(global.WeakMap) != "undefined")
        js.Dynamic.newInstance(global.WeakMap)()
      else
        null

    def nextIDHashCode(): Int = {
      val r = lastIDHashCode + 1
      lastIDHashCode = r
      r
    }
  }

  private object SystemProperties {
    var dict: js.Dictionary[String] = loadSystemProperties()
    var properties: ju.Properties = null

    private[System] def loadSystemProperties(): js.Dictionary[String] = {
      js.Dictionary(
          "java.version" -> "1.8",
          "java.vm.specification.version" -> "1.8",
          "java.vm.specification.vendor" -> "Oracle Corporation",
          "java.vm.specification.name" -> "Java Virtual Machine Specification",
          "java.vm.name" -> "Scala.js",
          "java.vm.version" -> linkingInfo.linkerVersion,
          "java.specification.version" -> "1.8",
          "java.specification.vendor" -> "Oracle Corporation",
          "java.specification.name" -> "Java Platform API Specification",
          "file.separator" -> "/",
          "path.separator" -> ":",
          "line.separator" -> "\n"
      )
    }

    private[System] def forceProperties(): ju.Properties = {
      if (properties eq null) {
        properties = new ju.Properties
        for ((key, value) <- dict)
          properties.setProperty(key, value)
        dict = null
      }
      properties
    }
  }

  def getProperties(): ju.Properties =
    SystemProperties.forceProperties()

  def lineSeparator(): String = "\n"

  def setProperties(properties: ju.Properties): Unit = {
    if (properties eq null) {
      SystemProperties.dict = SystemProperties.loadSystemProperties()
      SystemProperties.properties = null
    } else {
      SystemProperties.dict = null
      SystemProperties.properties = properties
    }
  }

  def getProperty(key: String): String =
    if (SystemProperties.dict ne null) SystemProperties.dict.getOrElse(key, null)
    else SystemProperties.properties.getProperty(key)

  def getProperty(key: String, default: String): String =
    if (SystemProperties.dict ne null) SystemProperties.dict.getOrElse(key, default)
    else SystemProperties.properties.getProperty(key, default)

  def clearProperty(key: String): String =
    if (SystemProperties.dict ne null) SystemProperties.dict.remove(key).getOrElse(null)
    else SystemProperties.properties.remove(key).asInstanceOf[String]

  def setProperty(key: String, value: String): String = {
    if (SystemProperties.dict ne null) {
      val oldValue = getProperty(key)
      SystemProperties.dict(key) = value
      oldValue
    } else {
      SystemProperties.properties.setProperty(key, value).asInstanceOf[String]
    }
  }

  def getenv(): ju.Map[String, String] =
    ju.Collections.emptyMap()

  def getenv(name: String): String = {
    if (name eq null)
      throw new NullPointerException

    null
  }

  //def exit(status: scala.Int): Unit
  def gc(): Unit = Runtime.getRuntime().gc()
}

private[lang] final class JSConsoleBasedPrintStream(isErr: Boolean)
    extends PrintStream(new JSConsoleBasedPrintStream.DummyOutputStream) {

  import JSConsoleBasedPrintStream._

  /** Whether the buffer is flushed.
   *  This can be true even if buffer != "" because of line continuations.
   *  However, the converse is never true, i.e., !flushed => buffer != "".
   */
  private var flushed: scala.Boolean = true
  private var buffer: String = ""

  override def write(b: Int): Unit =
    write(Array(b.toByte), 0, 1)

  override def write(buf: Array[scala.Byte], off: Int, len: Int): Unit = {
    /* This does *not* decode buf as a sequence of UTF-8 code units.
     * This is not really useful, and would uselessly pull in the UTF-8 decoder
     * in all applications that use OutputStreams (not just PrintStreams).
     * Instead, we use a trivial ISO-8859-1 decoder in here.
     */
    if (off < 0 || len < 0 || len > buf.length - off)
      throw new IndexOutOfBoundsException

    var i = 0
    while (i < len) {
      print((buf(i + off) & 0xff).toChar)
      i += 1
    }
  }

  override def print(b: scala.Boolean): Unit     = printString(String.valueOf(b))
  override def print(c: scala.Char): Unit        = printString(String.valueOf(c))
  override def print(i: scala.Int): Unit         = printString(String.valueOf(i))
  override def print(l: scala.Long): Unit        = printString(String.valueOf(l))
  override def print(f: scala.Float): Unit       = printString(String.valueOf(f))
  override def print(d: scala.Double): Unit      = printString(String.valueOf(d))
  override def print(s: Array[scala.Char]): Unit = printString(String.valueOf(s))
  override def print(s: String): Unit            = printString(if (s == null) "null" else s)
  override def print(obj: AnyRef): Unit          = printString(String.valueOf(obj))

  override def println(): Unit = printString("\n")

  // This is the method invoked by Predef.println(x).
  @inline
  override def println(obj: AnyRef): Unit = printString("" + obj + "\n")

  private def printString(s: String): Unit = {
    var rest: String = s
    while (rest != "") {
      val nlPos = rest.indexOf("\n")
      if (nlPos < 0) {
        buffer += rest
        flushed = false
        rest = ""
      } else {
        doWriteLine(buffer + rest.substring(0, nlPos))
        buffer = ""
        flushed = true
        rest = rest.substring(nlPos+1)
      }
    }
  }

  /**
   * Since we cannot write a partial line in JavaScript, we write a whole
   * line with continuation symbol at the end and schedule a line continuation
   * symbol for the new line if the buffer is flushed.
   */
  override def flush(): Unit = if (!flushed) {
    doWriteLine(buffer + LineContEnd)
    buffer = LineContStart
    flushed = true
  }

  override def close(): Unit = ()

  private def doWriteLine(line: String): Unit = {
    import js.DynamicImplicits.truthValue

    if (js.typeOf(global.console) != "undefined") {
      if (isErr && global.console.error)
        global.console.error(line)
      else
        global.console.log(line)
    }
  }
}

private[lang] object JSConsoleBasedPrintStream {
  private final val LineContEnd: String = "\u21A9"
  private final val LineContStart: String = "\u21AA"

  class DummyOutputStream extends OutputStream {
    def write(c: Int): Unit =
      throw new AssertionError(
          "Should not get in JSConsoleBasedPrintStream.DummyOutputStream")
  }
}


text:
@interface HMResponseButton : UIButton

@end


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

<recipeml version="0.5">
  <recipe>
    <head>
      <title>Baked Garlic</title>
      <categories>
        <cat>None</cat></categories>
      <yield>1</yield></head>
    <ingredients>
      <ing>
        <amt>
          <qty/>
          <unit/></amt>
        <item>Garlic; (1 bulb per person)</item></ing>
      <ing>
        <amt>
          <qty/>
          <unit/></amt>
        <item>Olive oil</item></ing>
      <ing>
        <amt>
          <qty/>
          <unit/></amt>
        <item>Brie Cheese</item></ing>
      <ing>
        <amt>
          <qty/>
          <unit/></amt>
        <item>French bread Baguette loaf-sliced & toasted</item></ing></ingredients>
    <directions>
      <step>  Preheat oven to 325 degrees F. Remove any of the loose, paper-like skin and
  lightly baste bulbs of garlic with olive oil. Wrap in foil and poke a few
  holes to allow steam to escape. Bake for 1-1/4 hours. Cut garlic in half
  horizontally. To serve, warm Brie in 325 degree F oven until just starting
  to melt. Spread cheese on bread slices and then spread warm garlic pulp on
  top.

  Posted to MM-Recipes Digest V5 #010 by info@yourbestimage.com (Best Image)
  on Jan 09, 1998

</step></directions></recipe></recipeml>


text:
/* This is a lowest-common-denominator program which should compile under
   the default cc on any system, no matter how primitive (even the SunOS
   one - note the use of 1970s-vintage octal escapes).  This is necessary
   because it's compiled before we can try and select a decent compiler via
   the makefile */

#include <stdio.h>
#include <stdlib.h>

int main()
	{
	if( *( long * ) "\200\0\0\0\0\0\0\0" < 0 )
		printf( "-DDATA_BIGENDIAN" );
	else
		printf( "-DDATA_LITTLEENDIAN" );

	return( 0 );
	}


text:
#if defined (WITH_GRAPHICS)

#include <hist_graphics.hpp>
#include <err_cpu.hpp>

namespace cpu
{

template<typename T>
void copy_histogram(const Array<T> &data, const fg::Histogram* hist)
{
    CheckGL("Begin copy_histogram");

    glBindBuffer(GL_ARRAY_BUFFER, hist->vbo());
    glBufferSubData(GL_ARRAY_BUFFER, 0, hist->size(), data.get());
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    CheckGL("End copy_histogram");
}

#define INSTANTIATE(T)  \
    template void copy_histogram<T>(const Array<T> &data, const fg::Histogram* hist);

INSTANTIATE(float)
INSTANTIATE(int)
INSTANTIATE(uint)
INSTANTIATE(uchar)
INSTANTIATE(short)
INSTANTIATE(ushort)

}

#endif  // WITH_GRAPHICS


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;

namespace beRemote.GUI.Controls.FolderView
{
    [ValueConversion(typeof(bool), typeof(Visibility))]
    public class BoolToVisibilityConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (targetType != typeof(Visibility) || value.GetType() != typeof(bool))
                throw new InvalidOperationException("The target must be a boolean");

            if ((bool)value)
                return (Visibility.Visible);

            return (Visibility.Collapsed);
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if ((Visibility)value == Visibility.Visible)
                return true;

            return false;
        }
    }
}