text:
namespace llvm {
namespace codeview {

class SymbolRecord {
protected:
  explicit SymbolRecord(SymbolRecordKind Kind) : Kind(Kind) {}

public:
  SymbolRecordKind getKind() const { return Kind; }

  SymbolRecordKind Kind;
};

// S_GPROC32, S_LPROC32, S_GPROC32_ID, S_LPROC32_ID, S_LPROC32_DPC or
// S_LPROC32_DPC_ID
class ProcSym : public SymbolRecord {
  static constexpr uint32_t RelocationOffset = 32;

public:
  explicit ProcSym(SymbolRecordKind Kind) : SymbolRecord(Kind) {}
  ProcSym(SymbolRecordKind Kind, uint32_t RecordOffset)
      : SymbolRecord(Kind), RecordOffset(RecordOffset) {}

  uint32_t getRelocationOffset() const {
    return RecordOffset + RelocationOffset;
  }

  uint32_t Parent = 0;
  uint32_t End = 0;
  uint32_t Next = 0;
  uint32_t CodeSize = 0;
  uint32_t DbgStart = 0;
  uint32_t DbgEnd = 0;
  TypeIndex FunctionType;
  uint32_t CodeOffset = 0;
  uint16_t Segment = 0;
  ProcSymFlags Flags = ProcSymFlags::None;
  StringRef Name;

  uint32_t RecordOffset = 0;
};

// S_THUNK32
class Thunk32Sym : public SymbolRecord {
public:
  explicit Thunk32Sym(SymbolRecordKind Kind) : SymbolRecord(Kind) {}
  Thunk32Sym(SymbolRecordKind Kind, uint32_t RecordOffset)
      : SymbolRecord(Kind), RecordOffset(RecordOffset) {}

  uint32_t Parent = 0;
  uint32_t End = 0;
  uint32_t Next = 0;
  uint32_t Offset = 0;
  uint16_t Segment = 0;
  uint16_t Length = 0;
  ThunkOrdinal Thunk = ThunkOrdinal::Standard;
  StringRef Name;
  ArrayRef<uint8_t> VariantData;

  uint32_t RecordOffset = 0;
};

// S_TRAMPOLINE
class TrampolineSym : public SymbolRecord {
public:
  explicit TrampolineSym(SymbolRecordKind Kind) : SymbolRecord(Kind) {}
  TrampolineSym(SymbolRecordKind Kind, uint32_t RecordOffset)
      : SymbolRecord(Kind), RecordOffset(RecordOffset) {}

  TrampolineType Type;
  uint16_t Size = 0;
  uint32_t ThunkOffset = 0;
  uint32_t TargetOffset = 0;
  uint16_t ThunkSection = 0;
  uint16_t TargetSection = 0;

  uint32_t RecordOffset = 0;
};

// S_SECTION
class SectionSym : public SymbolRecord {
public:
  explicit SectionSym(SymbolRecordKind Kind) : SymbolRecord(Kind) {}
  SectionSym(SymbolRecordKind Kind, uint32_t RecordOffset)
      : SymbolRecord(Kind), RecordOffset(RecordOffset) {}

  uint16_t SectionNumber = 0;
  uint8_t Alignment = 0;
  uint32_t Rva = 0;
  uint32_t Length = 0;
  uint32_t Characteristics = 0;
  StringRef Name;

  uint32_t RecordOffset = 0;
};

// S_COFFGROUP
class CoffGroupSym : public SymbolRecord {
public:
  explicit CoffGroupSym(SymbolRecordKind Kind) : SymbolRecord(Kind) {}
  CoffGroupSym(SymbolRecordKind Kind, uint32_t RecordOffset)
      : SymbolRecord(Kind), RecordOffset(RecordOffset) {}

  uint32_t Size = 0;
  uint32_t Characteristics = 0;
  uint32_t Offset = 0;
  uint16_t Segment = 0;
  StringRef Name;

  uint32_t RecordOffset = 0;
};

class ScopeEndSym : public SymbolRecord {
public:
  explicit ScopeEndSym(SymbolRecordKind Kind) : SymbolRecord(Kind) {}
  ScopeEndSym(SymbolRecordKind Kind, uint32_t RecordOffset)
      : SymbolRecord(Kind), RecordOffset(RecordOffset) {}

  uint32_t RecordOffset = 0;
};

class CallerSym : public SymbolRecord {
public:
  explicit CallerSym(SymbolRecordKind Kind) : SymbolRecord(Kind) {}
  CallerSym(SymbolRecordKind Kind, uint32_t RecordOffset)
      : SymbolRecord(Kind), RecordOffset(RecordOffset) {}

  std::vector<TypeIndex> Indices;

  uint32_t RecordOffset = 0;
};

struct DecodedAnnotation {
  StringRef Name;
  ArrayRef<uint8_t> Bytes;
  BinaryAnnotationsOpCode OpCode = BinaryAnnotationsOpCode::Invalid;
  uint32_t U1 = 0;
  uint32_t U2 = 0;
  int32_t S1 = 0;
};

struct BinaryAnnotationIterator
    : public iterator_facade_base<BinaryAnnotationIterator,
                                  std::forward_iterator_tag,
                                  DecodedAnnotation> {
  BinaryAnnotationIterator() = default;
  BinaryAnnotationIterator(ArrayRef<uint8_t> Annotations) : Data(Annotations) {}
  BinaryAnnotationIterator(const BinaryAnnotationIterator &Other)
      : Data(Other.Data) {}

  bool operator==(BinaryAnnotationIterator Other) const {
    return Data == Other.Data;
  }

  BinaryAnnotationIterator &operator=(const BinaryAnnotationIterator Other) {
    Data = Other.Data;
    return *this;
  }

  BinaryAnnotationIterator &operator++() {
    if (!ParseCurrentAnnotation()) {
      *this = BinaryAnnotationIterator();
      return *this;
    }
    Data = Next;
    Next = ArrayRef<uint8_t>();
    Current.reset();
    return *this;
  }

  const DecodedAnnotation &operator*() {
    ParseCurrentAnnotation();
    return Current.getValue();
  }

private:
  static uint32_t GetCompressedAnnotation(ArrayRef<uint8_t> &Annotations) {
    if (Annotations.empty())
      return -1;

    uint8_t FirstByte = Annotations.front();
    Annotations = Annotations.drop_front();

    if ((FirstByte & 0x80) == 0x00)
      return FirstByte;

    if (Annotations.empty())
      return -1;

    uint8_t SecondByte = Annotations.front();
    Annotations = Annotations.drop_front();

    if ((FirstByte & 0xC0) == 0x80)
      return ((FirstByte & 0x3F) << 8) | SecondByte;

    if (Annotations.empty())
      return -1;

    uint8_t ThirdByte = Annotations.front();
    Annotations = Annotations.drop_front();

    if (Annotations.empty())
      return -1;

    uint8_t FourthByte = Annotations.front();
    Annotations = Annotations.drop_front();

    if ((FirstByte & 0xE0) == 0xC0)
      return ((FirstByte & 0x1F) << 24) | (SecondByte << 16) |
             (ThirdByte << 8) | FourthByte;

    return -1;
  }

  static int32_t DecodeSignedOperand(uint32_t Operand) {
    if (Operand & 1)
      return -(Operand >> 1);
    return Operand >> 1;
  }

  static int32_t DecodeSignedOperand(ArrayRef<uint8_t> &Annotations) {
    return DecodeSignedOperand(GetCompressedAnnotation(Annotations));
  }

  bool ParseCurrentAnnotation() {
    if (Current.hasValue())
      return true;

    Next = Data;
    uint32_t Op = GetCompressedAnnotation(Next);
    DecodedAnnotation Result;
    Result.OpCode = static_cast<BinaryAnnotationsOpCode>(Op);
    switch (Result.OpCode) {
    case BinaryAnnotationsOpCode::Invalid:
      Result.Name = "Invalid";
      Next = ArrayRef<uint8_t>();
      break;
    case BinaryAnnotationsOpCode::CodeOffset:
      Result.Name = "CodeOffset";
      Result.U1 = GetCompressedAnnotation(Next);
      break;
    case BinaryAnnotationsOpCode::ChangeCodeOffsetBase:
      Result.Name = "ChangeCodeOffsetBase";
      Result.U1 = GetCompressedAnnotation(Next);
      break;
    case BinaryAnnotationsOpCode::ChangeCodeOffset:
      Result.Name = "ChangeCodeOffset";
      Result.U1 = GetCompressedAnnotation(Next);
      break;
    case BinaryAnnotationsOpCode::ChangeCodeLength:
      Result.Name = "ChangeCodeLength";
      Result.U1 = GetCompressedAnnotation(Next);
      break;
    case BinaryAnnotationsOpCode::ChangeFile:
      Result.Name = "ChangeFile";
      Result.U1 = GetCompressedAnnotation(Next);
      break;
    case BinaryAnnotationsOpCode::ChangeLineEndDelta:
      Result.Name = "ChangeLineEndDelta";
      Result.U1 = GetCompressedAnnotation(Next);
      break;
    case BinaryAnnotationsOpCode::ChangeRangeKind:
      Result.Name = "ChangeRangeKind";
      Result.U1 = GetCompressedAnnotation(Next);
      break;
    case BinaryAnnotationsOpCode::ChangeColumnStart:
      Result.Name = "ChangeColumnStart";
      Result.U1 = GetCompressedAnnotation(Next);
      break;
    case BinaryAnnotationsOpCode::ChangeColumnEnd:
      Result.Name = "ChangeColumnEnd";
      Result.U1 = GetCompressedAnnotation(Next);
      break;
    case BinaryAnnotationsOpCode::ChangeLineOffset:
      Result.Name = "ChangeLineOffset";
      Result.S1 = DecodeSignedOperand(Next);
      break;
    case BinaryAnnotationsOpCode::ChangeColumnEndDelta:
      Result.Name = "ChangeColumnEndDelta";
      Result.S1 = DecodeSignedOperand(Next);
      break;
    case BinaryAnnotationsOpCode::ChangeCodeOffsetAndLineOffset: {
      Result.Name = "ChangeCodeOffsetAndLineOffset";
      uint32_t Annotation = GetCompressedAnnotation(Next);
      Result.S1 = DecodeSignedOperand(Annotation >> 4);
      Result.U1 = Annotation & 0xf;
      break;
    }
    case BinaryAnnotationsOpCode::ChangeCodeLengthAndCodeOffset: {
      Result.Name = "ChangeCodeLengthAndCodeOffset";
      Result.U1 = GetCompressedAnnotation(Next);
      Result.U2 = GetCompressedAnnotation(Next);
      break;
    }
    }
    Result.Bytes = Data.take_front(Data.size() - Next.size());
    Current = Result;
    return true;
  }

  Optional<DecodedAnnotation> Current;
  ArrayRef<uint8_t> Data;
  ArrayRef<uint8_t> Next;
};

// S_INLINESITE
class InlineSiteSym : public SymbolRecord {
public:
  explicit InlineSiteSym(SymbolRecordKind Kind) : SymbolRecord(Kind) {}
  explicit InlineSiteSym(uint32_t RecordOffset)
      : SymbolRecord(SymbolRecordKind::InlineSiteSym),
        RecordOffset(RecordOffset) {}

  iterator_range<BinaryAnnotationIterator> annotations() const {
    return make_range(BinaryAnnotationIterator(AnnotationData),
                      BinaryAnnotationIterator());
  }

  uint32_t Parent = 0;
  uint32_t End = 0;
  TypeIndex Inlinee;
  std::vector<uint8_t> AnnotationData;

  uint32_t RecordOffset = 0;
};

struct PublicSym32Header {
  ulittle32_t Flags;
  ulittle32_t Offset;
  ulittle16_t Segment;
  // char Name[];
};

// S_PUB32
class PublicSym32 : public SymbolRecord {
public:
  PublicSym32() : SymbolRecord(SymbolRecordKind::PublicSym32) {}
  explicit PublicSym32(SymbolRecordKind Kind) : SymbolRecord(Kind) {}
  explicit PublicSym32(uint32_t RecordOffset)
      : SymbolRecord(SymbolRecordKind::PublicSym32),
        RecordOffset(RecordOffset) {}

  PublicSymFlags Flags = PublicSymFlags::None;
  uint32_t Offset = 0;
  uint16_t Segment = 0;
  StringRef Name;

  uint32_t RecordOffset = 0;
};

// S_REGISTER
class RegisterSym : public SymbolRecord {
public:
  explicit RegisterSym(SymbolRecordKind Kind) : SymbolRecord(Kind) {}
  explicit RegisterSym(uint32_t RecordOffset)
      : SymbolRecord(SymbolRecordKind::RegisterSym),
        RecordOffset(RecordOffset) {}

  TypeIndex Index;
  RegisterId Register;
  StringRef Name;

  uint32_t RecordOffset = 0;
};

// S_PROCREF, S_LPROCREF
class ProcRefSym : public SymbolRecord {
public:
  explicit ProcRefSym(SymbolRecordKind Kind) : SymbolRecord(Kind) {}
  explicit ProcRefSym(uint32_t RecordOffset)
      : SymbolRecord(SymbolRecordKind::ProcRefSym), RecordOffset(RecordOffset) {
  }

  uint32_t SumName = 0;
  uint32_t SymOffset = 0;
  uint16_t Module = 0;
  StringRef Name;

  uint16_t modi() const { return Module - 1; }
  uint32_t RecordOffset = 0;
};

// S_LOCAL
class LocalSym : public SymbolRecord {
public:
  explicit LocalSym(SymbolRecordKind Kind) : SymbolRecord(Kind) {}
  explicit LocalSym(uint32_t RecordOffset)
      : SymbolRecord(SymbolRecordKind::LocalSym), RecordOffset(RecordOffset) {}

  TypeIndex Type;
  LocalSymFlags Flags = LocalSymFlags::None;
  StringRef Name;

  uint32_t RecordOffset = 0;
};

struct LocalVariableAddrRange {
  uint32_t OffsetStart = 0;
  uint16_t ISectStart = 0;
  uint16_t Range = 0;
};

struct LocalVariableAddrGap {
  uint16_t GapStartOffset = 0;
  uint16_t Range = 0;
};

enum : uint16_t { MaxDefRange = 0xf000 };

// S_DEFRANGE
class DefRangeSym : public SymbolRecord {
  static constexpr uint32_t RelocationOffset = 8;

public:
  explicit DefRangeSym(SymbolRecordKind Kind) : SymbolRecord(Kind) {}
  explicit DefRangeSym(uint32_t RecordOffset)
      : SymbolRecord(SymbolRecordKind::DefRangeSym),
        RecordOffset(RecordOffset) {}

  uint32_t getRelocationOffset() const {
    return RecordOffset + RelocationOffset;
  }

  uint32_t Program = 0;
  LocalVariableAddrRange Range;
  std::vector<LocalVariableAddrGap> Gaps;

  uint32_t RecordOffset = 0;
};

// S_DEFRANGE_SUBFIELD
class DefRangeSubfieldSym : public SymbolRecord {
  static constexpr uint32_t RelocationOffset = 12;

public:
  explicit DefRangeSubfieldSym(SymbolRecordKind Kind) : SymbolRecord(Kind) {}
  explicit DefRangeSubfieldSym(uint32_t RecordOffset)
      : SymbolRecord(SymbolRecordKind::DefRangeSubfieldSym),
        RecordOffset(RecordOffset) {}

  uint32_t getRelocationOffset() const {
    return RecordOffset + RelocationOffset;
  }

  uint32_t Program = 0;
  uint16_t OffsetInParent = 0;
  LocalVariableAddrRange Range;
  std::vector<LocalVariableAddrGap> Gaps;

  uint32_t RecordOffset = 0;
};

struct DefRangeRegisterHeader {
  ulittle16_t Register;
  ulittle16_t MayHaveNoName;
};

// S_DEFRANGE_REGISTER
class DefRangeRegisterSym : public SymbolRecord {
public:
  explicit DefRangeRegisterSym(SymbolRecordKind Kind) : SymbolRecord(Kind) {}
  explicit DefRangeRegisterSym(uint32_t RecordOffset)
      : SymbolRecord(SymbolRecordKind::DefRangeRegisterSym),
        RecordOffset(RecordOffset) {}

  uint32_t getRelocationOffset() const { return RecordOffset + sizeof(DefRangeRegisterHeader); }

  DefRangeRegisterHeader Hdr;
  LocalVariableAddrRange Range;
  std::vector<LocalVariableAddrGap> Gaps;

  uint32_t RecordOffset = 0;
};

struct DefRangeSubfieldRegisterHeader {
  ulittle16_t Register;
  ulittle16_t MayHaveNoName;
  ulittle32_t OffsetInParent;
};

// S_DEFRANGE_SUBFIELD_REGISTER
class DefRangeSubfieldRegisterSym : public SymbolRecord {
public:
  explicit DefRangeSubfieldRegisterSym(SymbolRecordKind Kind)
      : SymbolRecord(Kind) {}
  explicit DefRangeSubfieldRegisterSym(uint32_t RecordOffset)
      : SymbolRecord(SymbolRecordKind::DefRangeSubfieldRegisterSym),
        RecordOffset(RecordOffset) {}

  uint32_t getRelocationOffset() const { return RecordOffset + sizeof(DefRangeSubfieldRegisterHeader); }

  DefRangeSubfieldRegisterHeader Hdr;
  LocalVariableAddrRange Range;
  std::vector<LocalVariableAddrGap> Gaps;

  uint32_t RecordOffset = 0;
};

struct DefRangeFramePointerRelHeader {
  little32_t Offset;
};

// S_DEFRANGE_FRAMEPOINTER_REL
class DefRangeFramePointerRelSym : public SymbolRecord {
  static constexpr uint32_t RelocationOffset = 8;

public:
  explicit DefRangeFramePointerRelSym(SymbolRecordKind Kind)
      : SymbolRecord(Kind) {}
  explicit DefRangeFramePointerRelSym(uint32_t RecordOffset)
      : SymbolRecord(SymbolRecordKind::DefRangeFramePointerRelSym),
        RecordOffset(RecordOffset) {}

  uint32_t getRelocationOffset() const {
    return RecordOffset + RelocationOffset;
  }

  DefRangeFramePointerRelHeader Hdr;
  LocalVariableAddrRange Range;
  std::vector<LocalVariableAddrGap> Gaps;

  uint32_t RecordOffset = 0;
};

struct DefRangeRegisterRelHeader {
  ulittle16_t Register;
  ulittle16_t Flags;
  little32_t BasePointerOffset;
};

// S_DEFRANGE_REGISTER_REL
class DefRangeRegisterRelSym : public SymbolRecord {
public:
  explicit DefRangeRegisterRelSym(SymbolRecordKind Kind) : SymbolRecord(Kind) {}
  explicit DefRangeRegisterRelSym(uint32_t RecordOffset)
      : SymbolRecord(SymbolRecordKind::DefRangeRegisterRelSym),
        RecordOffset(RecordOffset) {}

  // The flags implement this notional bitfield:
  //   uint16_t IsSubfield : 1;
  //   uint16_t Padding : 3;
  //   uint16_t OffsetInParent : 12;
  enum : uint16_t {
    IsSubfieldFlag = 1,
    OffsetInParentShift = 4,
  };

  bool hasSpilledUDTMember() const { return Hdr.Flags & IsSubfieldFlag; }
  uint16_t offsetInParent() const { return Hdr.Flags >> OffsetInParentShift; }

  uint32_t getRelocationOffset() const { return RecordOffset + sizeof(DefRangeRegisterRelHeader); }

  DefRangeRegisterRelHeader Hdr;
  LocalVariableAddrRange Range;
  std::vector<LocalVariableAddrGap> Gaps;

  uint32_t RecordOffset = 0;
};

// S_DEFRANGE_FRAMEPOINTER_REL_FULL_SCOPE
class DefRangeFramePointerRelFullScopeSym : public SymbolRecord {
public:
  explicit DefRangeFramePointerRelFullScopeSym(SymbolRecordKind Kind)
      : SymbolRecord(Kind) {}
  explicit DefRangeFramePointerRelFullScopeSym(uint32_t RecordOffset)
      : SymbolRecord(SymbolRecordKind::DefRangeFramePointerRelFullScopeSym),
        RecordOffset(RecordOffset) {}

  int32_t Offset = 0;

  uint32_t RecordOffset = 0;
};

// S_BLOCK32
class BlockSym : public SymbolRecord {
  static constexpr uint32_t RelocationOffset = 16;

public:
  explicit BlockSym(SymbolRecordKind Kind) : SymbolRecord(Kind) {}
  explicit BlockSym(uint32_t RecordOffset)
      : SymbolRecord(SymbolRecordKind::BlockSym), RecordOffset(RecordOffset) {}

  uint32_t getRelocationOffset() const {
    return RecordOffset + RelocationOffset;
  }

  uint32_t Parent = 0;
  uint32_t End = 0;
  uint32_t CodeSize = 0;
  uint32_t CodeOffset = 0;
  uint16_t Segment = 0;
  StringRef Name;

  uint32_t RecordOffset = 0;
};

// S_LABEL32
class LabelSym : public SymbolRecord {
  static constexpr uint32_t RelocationOffset = 4;

public:
  explicit LabelSym(SymbolRecordKind Kind) : SymbolRecord(Kind) {}
  explicit LabelSym(uint32_t RecordOffset)
      : SymbolRecord(SymbolRecordKind::LabelSym), RecordOffset(RecordOffset) {}

  uint32_t getRelocationOffset() const {
    return RecordOffset + RelocationOffset;
  }

  uint32_t CodeOffset = 0;
  uint16_t Segment = 0;
  ProcSymFlags Flags = ProcSymFlags::None;
  StringRef Name;

  uint32_t RecordOffset = 0;
};

// S_OBJNAME
class ObjNameSym : public SymbolRecord {
public:
  explicit ObjNameSym() : SymbolRecord(SymbolRecordKind::ObjNameSym) {}
  explicit ObjNameSym(SymbolRecordKind Kind) : SymbolRecord(Kind) {}
  explicit ObjNameSym(uint32_t RecordOffset)
      : SymbolRecord(SymbolRecordKind::ObjNameSym), RecordOffset(RecordOffset) {
  }

  uint32_t Signature = 0;
  StringRef Name;

  uint32_t RecordOffset = 0;
};

// S_ENVBLOCK
class EnvBlockSym : public SymbolRecord {
public:
  explicit EnvBlockSym(SymbolRecordKind Kind) : SymbolRecord(Kind) {}
  explicit EnvBlockSym(uint32_t RecordOffset)
      : SymbolRecord(SymbolRecordKind::EnvBlockSym),
        RecordOffset(RecordOffset) {}

  std::vector<StringRef> Fields;

  uint32_t RecordOffset = 0;
};

// S_EXPORT
class ExportSym : public SymbolRecord {
public:
  explicit ExportSym(SymbolRecordKind Kind) : SymbolRecord(Kind) {}
  explicit ExportSym(uint32_t RecordOffset)
      : SymbolRecord(SymbolRecordKind::ExportSym), RecordOffset(RecordOffset) {}

  uint16_t Ordinal = 0;
  ExportFlags Flags = ExportFlags::None;
  StringRef Name;

  uint32_t RecordOffset = 0;
};

// S_FILESTATIC
class FileStaticSym : public SymbolRecord {
public:
  explicit FileStaticSym(SymbolRecordKind Kind) : SymbolRecord(Kind) {}
  explicit FileStaticSym(uint32_t RecordOffset)
      : SymbolRecord(SymbolRecordKind::FileStaticSym),
        RecordOffset(RecordOffset) {}

  TypeIndex Index;
  uint32_t ModFilenameOffset = 0;
  LocalSymFlags Flags = LocalSymFlags::None;
  StringRef Name;

  uint32_t RecordOffset = 0;
};

// S_COMPILE2
class Compile2Sym : public SymbolRecord {
public:
  explicit Compile2Sym(SymbolRecordKind Kind) : SymbolRecord(Kind) {}
  explicit Compile2Sym(uint32_t RecordOffset)
      : SymbolRecord(SymbolRecordKind::Compile2Sym),
        RecordOffset(RecordOffset) {}

  CompileSym2Flags Flags = CompileSym2Flags::None;
  CPUType Machine;
  uint16_t VersionFrontendMajor = 0;
  uint16_t VersionFrontendMinor = 0;
  uint16_t VersionFrontendBuild = 0;
  uint16_t VersionBackendMajor = 0;
  uint16_t VersionBackendMinor = 0;
  uint16_t VersionBackendBuild = 0;
  StringRef Version;
  std::vector<StringRef> ExtraStrings;

  uint8_t getLanguage() const { return static_cast<uint32_t>(Flags) & 0xFF; }
  uint32_t getFlags() const { return static_cast<uint32_t>(Flags) & ~0xFF; }

  uint32_t RecordOffset = 0;
};

// S_COMPILE3
class Compile3Sym : public SymbolRecord {
public:
  Compile3Sym() : SymbolRecord(SymbolRecordKind::Compile3Sym) {}
  explicit Compile3Sym(SymbolRecordKind Kind) : SymbolRecord(Kind) {}
  explicit Compile3Sym(uint32_t RecordOffset)
      : SymbolRecord(SymbolRecordKind::Compile3Sym),
        RecordOffset(RecordOffset) {}

  CompileSym3Flags Flags = CompileSym3Flags::None;
  CPUType Machine;
  uint16_t VersionFrontendMajor = 0;
  uint16_t VersionFrontendMinor = 0;
  uint16_t VersionFrontendBuild = 0;
  uint16_t VersionFrontendQFE = 0;
  uint16_t VersionBackendMajor = 0;
  uint16_t VersionBackendMinor = 0;
  uint16_t VersionBackendBuild = 0;
  uint16_t VersionBackendQFE = 0;
  StringRef Version;

  void setLanguage(SourceLanguage Lang) {
    Flags = CompileSym3Flags((uint32_t(Flags) & 0xFFFFFF00) | uint32_t(Lang));
  }

  SourceLanguage getLanguage() const {
    return static_cast<SourceLanguage>(static_cast<uint32_t>(Flags) & 0xFF);
  }
  CompileSym3Flags getFlags() const {
    return static_cast<CompileSym3Flags>(static_cast<uint32_t>(Flags) & ~0xFF);
  }

  bool hasOptimizations() const {
    return CompileSym3Flags::None !=
           (getFlags() & (CompileSym3Flags::PGO | CompileSym3Flags::LTCG));
  }

  uint32_t RecordOffset = 0;
};

// S_FRAMEPROC
class FrameProcSym : public SymbolRecord {
public:
  explicit FrameProcSym(SymbolRecordKind Kind) : SymbolRecord(Kind) {}
  explicit FrameProcSym(uint32_t RecordOffset)
      : SymbolRecord(SymbolRecordKind::FrameProcSym),
        RecordOffset(RecordOffset) {}

  uint32_t TotalFrameBytes = 0;
  uint32_t PaddingFrameBytes = 0;
  uint32_t OffsetToPadding = 0;
  uint32_t BytesOfCalleeSavedRegisters = 0;
  uint32_t OffsetOfExceptionHandler = 0;
  uint16_t SectionIdOfExceptionHandler = 0;
  FrameProcedureOptions Flags = FrameProcedureOptions::None;

  /// Extract the register this frame uses to refer to local variables.
  RegisterId getLocalFramePtrReg(CPUType CPU) const {
    return decodeFramePtrReg(
        EncodedFramePtrReg((uint32_t(Flags) >> 14U) & 0x3U), CPU);
  }

  /// Extract the register this frame uses to refer to parameters.
  RegisterId getParamFramePtrReg(CPUType CPU) const {
    return decodeFramePtrReg(
        EncodedFramePtrReg((uint32_t(Flags) >> 16U) & 0x3U), CPU);
  }

  uint32_t RecordOffset = 0;

private:
};

// S_CALLSITEINFO
class CallSiteInfoSym : public SymbolRecord {
  static constexpr uint32_t RelocationOffset = 4;

public:
  explicit CallSiteInfoSym(SymbolRecordKind Kind) : SymbolRecord(Kind) {}
  explicit CallSiteInfoSym(uint32_t RecordOffset)
      : SymbolRecord(SymbolRecordKind::CallSiteInfoSym) {}

  uint32_t getRelocationOffset() const {
    return RecordOffset + RelocationOffset;
  }

  uint32_t CodeOffset = 0;
  uint16_t Segment = 0;
  TypeIndex Type;

  uint32_t RecordOffset = 0;
};

// S_HEAPALLOCSITE
class HeapAllocationSiteSym : public SymbolRecord {
  static constexpr uint32_t RelocationOffset = 4;

public:
  explicit HeapAllocationSiteSym(SymbolRecordKind Kind) : SymbolRecord(Kind) {}
  explicit HeapAllocationSiteSym(uint32_t RecordOffset)
      : SymbolRecord(SymbolRecordKind::HeapAllocationSiteSym),
        RecordOffset(RecordOffset) {}

  uint32_t getRelocationOffset() const {
    return RecordOffset + RelocationOffset;
  }

  uint32_t CodeOffset = 0;
  uint16_t Segment = 0;
  uint16_t CallInstructionSize = 0;
  TypeIndex Type;

  uint32_t RecordOffset = 0;
};

// S_FRAMECOOKIE
class FrameCookieSym : public SymbolRecord {
  static constexpr uint32_t RelocationOffset = 4;

public:
  explicit FrameCookieSym(SymbolRecordKind Kind) : SymbolRecord(Kind) {}
  explicit FrameCookieSym(uint32_t RecordOffset)
      : SymbolRecord(SymbolRecordKind::FrameCookieSym) {}

  uint32_t getRelocationOffset() const {
    return RecordOffset + RelocationOffset;
  }

  uint32_t CodeOffset = 0;
  uint16_t Register = 0;
  FrameCookieKind CookieKind;
  uint8_t Flags = 0;

  uint32_t RecordOffset = 0;
};

// S_UDT, S_COBOLUDT
class UDTSym : public SymbolRecord {
public:
  explicit UDTSym(SymbolRecordKind Kind) : SymbolRecord(Kind) {}
  explicit UDTSym(uint32_t RecordOffset)
      : SymbolRecord(SymbolRecordKind::UDTSym) {}

  TypeIndex Type;
  StringRef Name;

  uint32_t RecordOffset = 0;
};

// S_BUILDINFO
class BuildInfoSym : public SymbolRecord {
public:
  explicit BuildInfoSym(SymbolRecordKind Kind) : SymbolRecord(Kind) {}
  explicit BuildInfoSym(uint32_t RecordOffset)
      : SymbolRecord(SymbolRecordKind::BuildInfoSym),
        RecordOffset(RecordOffset) {}

  TypeIndex BuildId;

  uint32_t RecordOffset = 0;
};

// S_BPREL32
class BPRelativeSym : public SymbolRecord {
public:
  explicit BPRelativeSym(SymbolRecordKind Kind) : SymbolRecord(Kind) {}
  explicit BPRelativeSym(uint32_t RecordOffset)
      : SymbolRecord(SymbolRecordKind::BPRelativeSym),
        RecordOffset(RecordOffset) {}

  int32_t Offset = 0;
  TypeIndex Type;
  StringRef Name;

  uint32_t RecordOffset = 0;
};

// S_REGREL32
class RegRelativeSym : public SymbolRecord {
public:
  explicit RegRelativeSym(SymbolRecordKind Kind) : SymbolRecord(Kind) {}
  explicit RegRelativeSym(uint32_t RecordOffset)
      : SymbolRecord(SymbolRecordKind::RegRelativeSym),
        RecordOffset(RecordOffset) {}

  uint32_t Offset = 0;
  TypeIndex Type;
  RegisterId Register;
  StringRef Name;

  uint32_t RecordOffset = 0;
};

// S_CONSTANT, S_MANCONSTANT
class ConstantSym : public SymbolRecord {
public:
  explicit ConstantSym(SymbolRecordKind Kind) : SymbolRecord(Kind) {}
  explicit ConstantSym(uint32_t RecordOffset)
      : SymbolRecord(SymbolRecordKind::ConstantSym),
        RecordOffset(RecordOffset) {}

  TypeIndex Type;
  APSInt Value;
  StringRef Name;

  uint32_t RecordOffset = 0;
};

// S_LDATA32, S_GDATA32, S_LMANDATA, S_GMANDATA
class DataSym : public SymbolRecord {
  static constexpr uint32_t RelocationOffset = 8;

public:
  explicit DataSym(SymbolRecordKind Kind) : SymbolRecord(Kind) {}
  explicit DataSym(uint32_t RecordOffset)
      : SymbolRecord(SymbolRecordKind::DataSym), RecordOffset(RecordOffset) {}

  uint32_t getRelocationOffset() const {
    return RecordOffset + RelocationOffset;
  }

  TypeIndex Type;
  uint32_t DataOffset = 0;
  uint16_t Segment = 0;
  StringRef Name;

  uint32_t RecordOffset = 0;
};

// S_LTHREAD32, S_GTHREAD32
class ThreadLocalDataSym : public SymbolRecord {
  static constexpr uint32_t RelocationOffset = 8;

public:
  explicit ThreadLocalDataSym(SymbolRecordKind Kind) : SymbolRecord(Kind) {}
  explicit ThreadLocalDataSym(uint32_t RecordOffset)
      : SymbolRecord(SymbolRecordKind::ThreadLocalDataSym),
        RecordOffset(RecordOffset) {}

  uint32_t getRelocationOffset() const {
    return RecordOffset + RelocationOffset;
  }

  TypeIndex Type;
  uint32_t DataOffset = 0;
  uint16_t Segment = 0;
  StringRef Name;

  uint32_t RecordOffset = 0;
};

// S_UNAMESPACE
class UsingNamespaceSym : public SymbolRecord {
public:
  explicit UsingNamespaceSym(SymbolRecordKind Kind) : SymbolRecord(Kind) {}
  explicit UsingNamespaceSym(uint32_t RecordOffset)
      : SymbolRecord(SymbolRecordKind::UsingNamespaceSym),
        RecordOffset(RecordOffset) {}

  StringRef Name;

  uint32_t RecordOffset = 0;
};

// S_ANNOTATION
class AnnotationSym : public SymbolRecord {
public:
  explicit AnnotationSym(SymbolRecordKind Kind) : SymbolRecord(Kind) {}
  explicit AnnotationSym(uint32_t RecordOffset)
      : SymbolRecord(SymbolRecordKind::AnnotationSym),
        RecordOffset(RecordOffset) {}

  uint32_t CodeOffset = 0;
  uint16_t Segment = 0;
  std::vector<StringRef> Strings;

  uint32_t RecordOffset = 0;
};

using CVSymbol = CVRecord<SymbolKind>;
using CVSymbolArray = VarStreamArray<CVSymbol>;

Expected<CVSymbol> readSymbolFromStream(BinaryStreamRef Stream,
                                        uint32_t Offset);

} // end namespace codeview
} // end namespace llvm

#endif // LLVM_DEBUGINFO_CODEVIEW_SYMBOLRECORD_H


text:
#ifndef _SCHEDD_CRON_JOB_MGR_H
#define _SCHEDD_CRON_JOB_MGR_H

#include "condor_cron_job_mgr.h"

// Define a simple class to run child tasks periodically.
class ScheddCronJobMgr : public CronJobMgr
{
  public:
	ScheddCronJobMgr( void );
	~ScheddCronJobMgr( void );
	int Initialize( const char *name );
	int Shutdown( bool force );
	bool ShutdownOk( void );

  protected:
	CronJob *CreateJob( CronJobParams *params );

  private:
	bool m_shutting_down;

};

#endif /* _SCHEDD_CRON_JOB_MGR_H */

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Bot. voy. Herald 78. 1852

#### Original name
null

### Remarks
null


text: scripts to talk to the github API on the Aiai Github repository.


text:
cd "$(dirname "$0")"
node ../bin/nei.js template -p ./template-test/input -o ./template-test/output   -input test -w true -author abner -ProductName JustTest --logLevel error


text:
package org.openhealthtools.openxds.webapp.control;

import java.util.ArrayList;
import org.apache.axiom.om.OMElement;

/**
 * This class builds GetFolderAndContents query.
 * @author Anil Kumar
 */
public class GetFolderAndContents extends Sq {
	ArrayList<String> ids = null;

	String query_details() {
		return "GetFolderAndContents " + ids;
	}

	OMElement build(ArrayList<String> ids) {
		this.ids = ids;
		ArrayList<OMElement> query = build_query_wrapper("urn:uuid:b909a503-523d-4517-8acf-8e5834dfc4c7");
		String id = "'" + ids.get(0) + "'";
		if (id.startsWith("urn:uuid:"))
			add_slot(query, "$XDSFolderEntryUUID", id);
		else
			add_slot(query, "$XDSFolderUniqueId", id);
		return query.get(0);
	}

}


text:
define(function (require) {
    var activity = require("sugar-web/activity/activity");
    var icon = require("sugar-web/graphics/icon");
    var datastore = require("sugar-web/foo");

    // Manipulate the DOM only when it is ready.
    require(['domReady!'], function (doc) {

        // Initialize the activity.
        activity.setup();

        // Colorize the activity icon.
        var activityButton = document.getElementById("activity-button");
        activity.getXOColor(function (error, colors) {
            icon.colorize(activityButton, colors);
        });

        // Make the activity stop with the stop button.
        var stopButton = document.getElementById("stop-button");

        var datastoreObject = activity.getDatastoreObject();

        activity.sampleSystemCalls(function (error, values) {
            console.log("real group id of current process : "+values[0])
            console.log("process id of current process : "+values[1])
            console.log("parent process id of current process : "+values[2])
        });

        activity.sugarLogDir(function (error, values) {
            console.log(values)

        });

        stopButton.onclick = function () {
            //console.log("score : "+highscore);
            //highscore="123";
            //var jsonData = JSON.stringify(highscore.toString());
            //atastoreObject.setDataAsText(jsonData);

            //datastoreObject.save();
           // console.log(datastoreObject.save());

            //datastoreObject.save(function () {
                activity.close();
            //});

         };

        function onLoaded(error, metadata, data) {
            //console.log(metadata);
            var activityname=(metadata.activity).split('.');
            console.log(activityname[2]);
            //console.log(data);
            //highscore=parseInt(JSON.parse(data));

        }

        datastoreObject.loadAsText(onLoaded);

    });

});


text:
/*
 * listDirectory.cc
 *
 *  Created on: Nov 14, 2011
 *      Author: jchen
 */

#include "patListDirectory.h"
#include<iostream>
#include<sstream>
#include<fstream>
#include "patDisplay.h"
#include <dirent.h>
#include "patErrMiscError.h"
patListDirectory::patListDirectory() {
	//

}

patListDirectory::~patListDirectory() {
	//
}
void patListDirectory::getFilesInDeep(const string & dir_path,
		const string condition, vector<string>& file_list) {

	DIR * dip;
	struct dirent *dit;
	const char* dirName = dir_path.c_str();

	unsigned char isFile = 0x8;
	string esp("~");
	string don("#");
	string csvext("csv");
	string accel("accel");
	string bt("bt");

	if ((dip = opendir(dirName)) == NULL) {
		stringstream str;
		str << "Directory " << dirName
				<< " doesn't exist or no permission to read.";
		cout<<str.str()<<endl;
		return ;
	}
	while ((dit = readdir(dip)) != NULL) {
		string fileName(dit->d_name);
		if (dit->d_type == isFile) {
			if (fileName.find(csvext) != string::npos
					&& fileName.find(esp) == string::npos
					&& fileName.find(don) == string::npos
					&& fileName.find(accel) == string::npos
					&& fileName.find(bt) == string::npos
					&& fileName.find(".kml") == string::npos) {
//				DEBUG_MESSAGE("Found file:" << fileName);
				file_list.push_back(dir_path+"/"+fileName);
			}

		}
		else if(dit->d_type == DT_DIR && fileName.substr(0,1)!="."){
//			cout<< "go to folder "<< fileName<<endl;
			getFilesInDeep(dir_path+"/"+fileName,condition,file_list);
		}
	}

	closedir(dip);
}
list<string> patListDirectory::getListOfFiles(string directory_name,
		patError* err) {
	DIR * dip;
	struct dirent *dit;
	const char* dirName = directory_name.c_str();

	DEBUG_MESSAGE("Try to open directory " << dirName);
	if ((dip = opendir(dirName)) == NULL) {
		stringstream str;
		str << "Directory " << dirName
				<< " doesn't exist or no permission to read.";
		err = new patErrMiscError(str.str());
		WARNING(err->describe());
		return list<string>();
	}
	DEBUG_MESSAGE("Direcotry " << dirName << " is now open");
	list<string> dirContent;
	unsigned char isFile = 0x8;
	string esp("~");
	string don("#");
	string csvext("csv");
	string accel("accel");
	string bt("bt");

	while ((dit = readdir(dip)) != NULL) {
		if (dit->d_type == isFile) {
			string fileName(dit->d_name);
			if (fileName.find(csvext) != string::npos
					&& fileName.find(esp) == string::npos
					&& fileName.find(don) == string::npos
					&& fileName.find(accel) == string::npos
					&& fileName.find(bt) == string::npos
					&& fileName.find(".kml") == string::npos) {
//				DEBUG_MESSAGE("Found file:" << fileName);
				dirContent.push_back(fileName);
			}

		}
	}

	closedir(dip);
	return dirContent;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/listview_background_shape" >

    <stroke
        android:width="2dp"
        android:color="@color/red_button_stroke" />

    <corners android:radius="5dp" />

    <solid android:color="@color/red_button" />

</shape>


text:
using System;

namespace UA.Cli.Arguments.Binding
{
    public static class Reflection
    {
        public static bool IsOfGenericType(this Type type, Type genType, out Type[] genArgs)
        {
            if (type.IsGenericType)
            {
                Type genTypeDef = type.GetGenericTypeDefinition();
                if (genTypeDef == genType)
                {
                    genArgs = type.GetGenericArguments();
                    return true;
                }
            }

            genArgs = null;
            return false;
        }
    }
}


text:
using namespace std;
using namespace cv;

extern "C"
{
	__declspec(dllexport) void GetNodesNames(vector<string>& names) {
		names = { "imread", "VideoCapture", "Gaussian blur", "Canny" };
	}
	__declspec(dllexport) void NodeFactory(string name, shared_ptr<Node>& node) {
		if (name == "imread") {
			ParamList inputs{};
			ParamList outputs{ {"value", make_shared<Parameter>("value", TypeFactory::GetType("Mat"), OUTPUT_PARAM) } };

			InitializerType init = [](ParamList outputs) {
				// Create the variable
				outputs["value"]->AllocateData(make_shared<Data<Mat>>(make_shared<Mat>()));
				// Put an image in it
				(*static_pointer_cast<Data<Mat>>(outputs["value"]->GetData())->Get()) = imread("default.jpg", IMREAD_COLOR);
			};

			ComputerType computer = [](ParamList in, ParamList out) {
			};

			node = make_shared<Node>(name, inputs, outputs, init, computer);
		}
		else if (name == "VideoCapture") {
			ParamList inputs{};
			ParamList outputs{ { "value", make_shared<Parameter>("value", TypeFactory::GetType("Mat"), OUTPUT_PARAM) },
			{ "cap", make_shared<Parameter>("cap", TypeFactory::GetType("VideoCapture"), OUTPUT_PARAM) } };

			InitializerType init = [](ParamList outputs) {
				// Create the variable
				outputs["value"]->AllocateData(make_shared<Data<Mat>>(make_shared<Mat>()));
				outputs["cap"]->AllocateData(make_shared<Data<VideoCapture>>(make_shared<VideoCapture>(0)));
				(*static_pointer_cast<Data<VideoCapture>>(outputs["cap"]->GetData())->Get()).set(CV_CAP_PROP_FRAME_WIDTH, 1280);
				(*static_pointer_cast<Data<VideoCapture>>(outputs["cap"]->GetData())->Get()).set(CV_CAP_PROP_FRAME_HEIGHT, 720);
				// Put an image in it
				(*static_pointer_cast<Data<Mat>>(outputs["value"]->GetData())->Get()) = imread("default.jpg", IMREAD_COLOR);

			};

			ComputerType computer = [](ParamList in, ParamList out) {
				Mat& value = (*static_pointer_cast<Data<Mat>>(out["value"]->GetData())->Get().get());
				VideoCapture cap((*static_pointer_cast<Data<VideoCapture>>(out["cap"]->GetData())->Get().get()));

				 // open the default camera
				if (!cap.isOpened())  // check if we succeeded
					return;

				Mat tmp;
				cap >> tmp; // get a new frame from camera
				// Copy the data as by default OpenCV performs a soft-copy
				tmp.copyTo(value);
			};

			node = make_shared<Node>(name, inputs, outputs, init, computer);
		}
		else if (name == "Gaussian blur") {
			ParamList inputs{ {"src", make_shared<Parameter>("src", TypeFactory::GetType("Mat"), INPUT_PARAM) },
			{ "kernelSize", make_shared<Parameter>("kernelSize", TypeFactory::GetType("int"), INPUT_PARAM) } };
			ParamList outputs{ {"dst", make_shared<Parameter>("dst", TypeFactory::GetType("Mat"), OUTPUT_PARAM) }};

			InitializerType init = [](ParamList outputs) {
				outputs["dst"]->AllocateData(make_shared<Data<Mat>>(make_shared<Mat>()));
				(*static_pointer_cast<Data<Mat>>(outputs["dst"]->GetData())->Get()) = imread("default.jpg", IMREAD_COLOR);

			};

			ComputerType computer = [](ParamList in, ParamList out) {
				Mat& src = (*static_pointer_cast<Data<Mat>>(in["src"]->GetData())->Get().get());
				int& kernelSize = (*static_pointer_cast<Data<int>>(in["kernelSize"]->GetData())->Get().get());
				Mat& dst = (*static_pointer_cast<Data<Mat>>(out["dst"]->GetData())->Get().get());
				// Gaussian blur only accepts odd numbers in kernel size
				if (kernelSize % 2 == 0)
					return;

				GaussianBlur(src, dst, Size(kernelSize, kernelSize), 0, 0);
			};
			node = make_shared<Node>(name, inputs, outputs, init, computer);
		}
		else if (name == "Canny") {
			ParamList inputs{ { "src", make_shared<Parameter>("src", TypeFactory::GetType("Mat"), INPUT_PARAM) },
			{ "lowThreshold", make_shared<Parameter>("lowThreshold", TypeFactory::GetType("int"), INPUT_PARAM) },
			{ "ratio", make_shared<Parameter>("ratio", TypeFactory::GetType("int"), INPUT_PARAM) },
			{ "kernelSize", make_shared<Parameter>("kernelSize", TypeFactory::GetType("int"), INPUT_PARAM) } };
			ParamList outputs{ { "dst", make_shared<Parameter>("dst", TypeFactory::GetType("Mat"), OUTPUT_PARAM) } };

			InitializerType init = [](ParamList outputs) {
				outputs["dst"]->AllocateData(make_shared<Data<Mat>>(make_shared<Mat>()));
				(*static_pointer_cast<Data<Mat>>(outputs["dst"]->GetData())->Get()) = imread("default.jpg", IMREAD_COLOR);
			};

			ComputerType computer = [](ParamList in, ParamList out) {
				Mat& src = (*static_pointer_cast<Data<Mat>>(in["src"]->GetData())->Get().get());
				int& lowThreshold = (*static_pointer_cast<Data<int>>(in["lowThreshold"]->GetData())->Get().get());
				int& ratio = (*static_pointer_cast<Data<int>>(in["ratio"]->GetData())->Get().get());
				int& kernelSize = (*static_pointer_cast<Data<int>>(in["kernelSize"]->GetData())->Get().get());
				Mat& dst = (*static_pointer_cast<Data<Mat>>(out["dst"]->GetData())->Get().get());
				// Gaussian blur only accepts odd numbers in kernel size (used by Canny)
				if (kernelSize % 2 == 0 || kernelSize < 3 || lowThreshold%2==0 || lowThreshold*ratio%2==0)
					return;

				Canny(src, dst, lowThreshold, lowThreshold*ratio, kernelSize);
			};
			node = make_shared<Node>(name, inputs, outputs, init, computer);
		}
	}
}


text:
**[Elisha Terada](https://github.com/elishaterada)** – Overall document writing

**[Travis Luong](https://github.com/travisluong)** – Code examples


text:
@(username: String, pred: Predicate)(implicit flash: play.api.mvc.Flash)

@import snippets._
@defining(Profile.hasRole(username)(enums.Role.Administrator)) { case isAdmin =>

@main("Show Predicate", username) {

    Show Index
    @if(isAdmin) {

Update Predicate

Delete Predicate

    }

Show Predicate

by @profile(pred.author) on @pred.modified.toString(Messages("pattern.datetime"))

  @snippets.initJS('confirmlinks, 'postlinks, 'cmOut)
  @flashMessage(flash)

Name

@pred.name

    @defining(pred.description) { desc =>
      @if(desc.isDefined) {

Description

@lib.helper.Markup.toHtml(desc.get)

      }
    }

Definition

@pred.definition

Status

Details

@stage(Some(routes.Predicates.show(pred.id.get)))

}}


text:
<?php

abstract class F5_Content_Abstract
{
    const NO_SETTER = 'no setter method';
    public $admin_id;
    public $content_id;
    public $content_parent_id;
    public $content_name;
    protected $content_type;
    public $content_url;
    public $content_template;
    public $content_meta_title;
    public $content_meta_keywords;
    public $content_meta_description;
    public $content_order;
    protected $_contentObject;

    public function __construct($content_id = null, $content_url = null)
    {
        $this->_contentObject = new F5_Content_Content();

        if(!is_null($content_id)) {
            $this->loadContentObject(intval($content_id));

        } elseif(!is_null($content_url)) {
            $this->loadContentByUrl($content_url);
        }
    }

    protected function _getInnerRow($content_id = null)
    {
        if(is_null($content_id)) {
            $content_id = $this->content_id;
        }

        return $this->_contentObject->find($content_id)->current();
    }

    protected function _getProperties()
    {
        $propertyArray = array();
        $class = new Zend_Reflection_Class($this);
        $properties = $class->getProperties();

        foreach ($properties as $property) {
            if ($property->isPublic()) {
                $propertyArray[] = $property->getName();
            }
        }
        return $propertyArray;
    }

    protected function _callSetterMethod($property, $data)
    {
        $method = Zend_Filter::filterStatic($property, 'Word_UnderscoreToCamelCase');
        $methodName = '_set' . $method;

        if (method_exists($this, $methodName)) {
            return $this->$methodName($data);
        } else {
        	return self::NO_SETTER;
        }
    }

    protected function loadContentByUrl($content_url)
    {
        if($content_id = $this->_contentObject->getContentId($this->content_type, $content_url)) {
            $this->loadContentObject(intval($content_id));
        } else {
        	return FALSE;
        }
    }

    public function loadContentObject($content_id)
    {
        $this->content_id = $content_id;

        if($row = $this->_getInnerRow()) {
            if($row->content_type != $this->content_type) {
                return FALSE;
            }

            $this->admin_id                     = $row->admin_id;
            $this->content_id                   = $row->content_id;
            $this->content_parent_id            = $row->content_parent_id;
            $this->content_name                 = $row->content_name;
            $this->content_type                 = $row->content_type;
            $this->content_url                  = $row->content_url;
            $this->content_template             = $row->content_template;
            $this->content_meta_title           = $row->content_meta_title;
            $this->content_meta_keywords        = $row->content_meta_keywords;
            $this->content_meta_description     = $row->content_meta_description;
            $this->content_order                = $row->content_order;
            $this->content_updated              = $row->content_updated;
            $this->content_created              = $row->content_created;

            $contentNode = new F5_Content_Node();
            $nodes = $row->findDependentRowset($contentNode);

            if($nodes) {
                $properties = $this->_getProperties();

                foreach ($nodes as $node) {
                    $key = $node['node_name'];

                    if(in_array($key, $properties)) {

                        $value = $this->_callSetterMethod($key, $nodes);

                        if($value === self::NO_SETTER) {
                            $value = $node['node_content'];
                        }

                        $this->$key = $value;
                    }
                }
            }
        } else {
        	return FALSE;
        }
    }

    public function toArray()
    {
        $properties = $this->_getProperties();

        foreach ($properties as $property) {
            $array[$property] = $this->$property;
        }

        return $array;
    }

    public function save()
    {
        if(isset($this->content_id)) {
            return $this->_update();
        } else {
            return $this->_insert();
        }
    }

    protected function _insert()
    {
        $content = array(
            'admin_id'                  => $this->admin_id,
            'content_parent_id'         => $this->content_parent_id,
            'content_name'              => $this->content_name,
            'content_type'              => $this->content_type,
            'content_url'               => $this->content_url,
            'content_template'          => $this->content_template,
            'content_meta_title'        => $this->content_meta_title,
            'content_meta_keywords'     => $this->content_meta_keywords,
            'content_meta_description'  => $this->content_meta_description,
            'content_order'             => $this->content_order
        );

        if($content_id = $this->_contentObject->createContent($content)) {
            $this->content_id = $content_id;
            $this->_update();
            return TRUE;
        } else {
        	return FALSE;
        }
    }

    protected function _update()
    {
        $content = $this->toArray();
        return $this->_contentObject->updateContent($this->content_id, $content);
    }

    public function delete()
    {
        if(isset($this->content_id)) {
            return $this->_contentObject->deleteContent($this->content_id);
        }
    }

    public function getContent($order = 'content_created DESC')
    {
        return $this->_contentObject->getContent($this->content_type, $order);
    }

}


text:
<?php

// change the following paths if necessary
$yii = dirname(__FILE__).'/../yii/yii.php';
$config = require_once(dirname(__FILE__).'/../application/config/main.php');
$local = require_once(dirname(__FILE__).'/../application/config/local.php');

require_once($yii);

// Blend local and main config
$config = CMap::mergeArray($config, $local);

Yii::createWebApplication($config)->run();


text:
import axios from 'axios'
import { browserHistory } from 'react-router'
import { AUTH_USER, AUTH_ERROR, UNAUTH_USER, UPDATE_PROFILE, GET_PROFILE } from './types'

let API_URL = '' // http://localhost:8081

export function signinUser({ email, password }) {
  return function(dispatch) { // thunk
    axios.post(`${API_URL}/signin`, { email, password })
      .then(res => {
        dispatch({ type: AUTH_USER, payload: { email, profile: res.data.profile } })
        localStorage.setItem('token', res.data.token)
        localStorage.setItem('email', email)// TODO dont need?
        browserHistory.push('/dashboard')
      })
      .catch(() => {
        dispatch(authError('Invaild Email or Password'))
      })
  }
}

export function signupUser({ email, password }) { // Could DRY up with signinUser
  return function(dispatch) {
    axios.post(`${API_URL}/signup`, { email, password })
      .then(res => {
        dispatch({ type: AUTH_USER, payload: { email, profile: '' } })// flips state to logged in
        localStorage.setItem('token', res.data.token)
        localStorage.setItem('email', email)// TODO dont need?
        browserHistory.push('/dashboard')
      })
      .catch(res => {
        dispatch(authError(res.data.error))
      })
  }
}

export function authError(error) {
  return {
    type: AUTH_ERROR,
    payload: error
  }
}

export function signoutUser() {
  localStorage.clear()
  return {
    type: UNAUTH_USER
  }
}

export function updateProfile(formProps) {
  return function(dispatch) {
    axios.post(`${API_URL}/profile`, { formProps }, {
      headers: { authorization: localStorage.getItem('token') }
    })
      .then(res => {
        dispatch({
          type: UPDATE_PROFILE,
          payload: res.data
        })
      })
  }
}

export function getProfile() {
  return function(dispatch) {
    axios.get(`${API_URL}/profile`, {
      headers: { authorization: localStorage.getItem('token') }
    })
      .then(res => {
        dispatch({
          type: GET_PROFILE,
          payload: res.data.profile
        })
      })
  }
}


text:
package com.github.wjiec.stream;

import com.sun.jdi.event.StepEvent;

import java.util.Scanner;
import java.util.stream.Stream;

public class StreamCreateTest {

    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(StreamCreateTest.class.getResourceAsStream("/aliceinwonderland.txt"))) {
            Shower.show("scanner", scanner.tokens());
        }

        Stream<String> words = Stream.of("from", "Stream", "dot", "of");
        Shower.show("Stream.of", words);

        Stream<String> empty = Stream.empty();
        Shower.show("Stream.empty", empty);

        Stream<Double> random = Stream.generate(Math::random);
        Shower.show("Stream.generate", random);

        Stream<Integer> integer = Stream.iterate(0, (n) -> n + 1);
        Shower.show("Stream.iterate", integer);

        Stream<Stream> valid = Stream.ofNullable(integer);
        Shower.show("Stream.ofNullable", valid);

        Stream<Stream> nullable = Stream.ofNullable(null);
        Shower.show("Stream.ofNullable", nullable);
    }

}


text:
the protocol
============

dnode uses newline-terminated JSON messages. Each side of the connection may
request that a method be invoked on the other side.

data fields
-----------

All messages have this format:

* method :: String or Integer
* arguments :: Array
* callbacks :: Object
* links :: Array

When the method field is a string, it refers to a named method at the remote.
When the method field is an integer, it refers to an anonymous function
declared in the callbacks field of a previous request.

The arguments field contains the data to supply the remote method or callback.
The callbacks field maps an integral callback ID to an Array of elements
representing the callback's path in the arguments structure. For instance,
an arguments array before transformation of

    [ 50, 3, { "b" : function () {}, "c" : 4 }, function () {} ]

could result in a callback field of

    { 103 : [ 2, "b" ], 104 : [ 3 ] }

if the functions were assigned IDs of 103 and 104 from left to right
respectively. Function 103 is in the object at element index 2 and at the key
"b", so its path is [ 2, "b" ]. Function 104 is just at index 3 in the argument
field so its path is just [ 3 ].

The contents of the arguments array at a callback location is not used, so it
may contain any value or may be left undefined.

The Array and Object fields can be omitted, in which case they default to [] and
{}.

methods
-------

After the connection is established, each side should send a message with the
method field set to "methods". The arguments fields should contain an array with
a single element: the object that should be wrapped. The callbacks field is
populated from the arguments array given the procedure above.

Example of this initial methods message:

    {
        "method" : "methods",
        "arguments" : [ { "timesTen" : "[Function]", "moo" : "[Function]" } ],
        "callbacks" : { "0" : ["0","timesTen"], "1" : ["0","moo"] }
    }

Note that the string "[Function]" is just a placeholder and its value is
unimportant.

After methods are exchanged, each side may request methods from the other based
on named keys or numeric callback IDs.

links
-----

An optional field, "links" supports representing cyclic data structures over
JSON. The "links" field is an array of hashes with "from" and "to" keys set. The
values of the "from" and "two" keys are array encoding paths through the data
structure from the root, as in the "callbacks" field.

Example of a method call with cyclic references:

    {
        "method" : 12,
        "arguments" : [ { "a" : 5, "b" : [ { "c" : 5 } ] } ],
        "callbacks" : {},
        "links" : [ { "from" : [ 0 ], "to" : [ 0, "b", 1 ] } ]
    }
This example creates a link to the first argument within the first argument's
"b" key's second element. The previous data structure could be generated from
the following javascript where `fn` comes from the remote:

    var data = { a : 5, b : [ { c : 5 } ] };
    data.b.push(data);
    fn(data);

Note that links need not necessarily be cyclic, they can just more efficiently
encode duplicate data, for instance.


text:
#include <core/BooleanFunctionParser.hpp>
#include <vector>
#include <stdint.h>
#include <mutex>
#include <regex>
#include <core/Exceptions.hpp>
#include <core/Utils.hpp>
#include <utility>

using namespace Logic;
using namespace std;

static mutex infixTokenRegexMutex;

template <typename T>
static T topAndPop(stack<T> &_stack) {
    T top = _stack.top();
    _stack.pop();
    return top;
}

namespace Logic {
static const string BOOLEAN_FUNCTION_REGEX = "[0]{1}|[1]{1}|[\\$]?" + VARIABLE_REGEX;

static string getInfixTokensRegex() {
    static string result;
    unique_lock<mutex> lock(infixTokenRegexMutex);
    if (result.length() == 0) {
        vector<string> tokens = OPERATOR_REGEXES;
        tokens.push_back("[\\(]");
        tokens.push_back("[\\)]");
        tokens.push_back(BOOLEAN_FUNCTION_REGEX);
        result = "[\\s]*(" + // Optional leading spaces
                 join(tokens, "|") + // actual token regex
                 ")[\\s]*"; // optional trailing spaces
    }
    return result;
}

void BooleanFunctionAccumulator::push(const BooleanFunction &function) {
    _stack.push(function);
}

void BooleanFunctionAccumulator::push(UnaryOperator &_operator) {
    if (_stack.empty()) {
        throw IllegalStateException("Cannot push a unary operator on an empty stack.");
    }
    _stack.push(_operator(topAndPop(_stack)));
}

void BooleanFunctionAccumulator::push(BinaryOperator &_operator) {
    if (_stack.size() < 2) {
        throw IllegalStateException("Cannot push a binary operator on an stack of size less than 2");
    }
    BooleanFunction operand2 = topAndPop(_stack);
    BooleanFunction operand1 = topAndPop(_stack);
    _stack.push(_operator(operand1, operand2));
}

BooleanFunction BooleanFunctionAccumulator::pop() {
    if (canBePopped()) {
        return topAndPop(_stack);
    }

    throw IllegalStateException("Cannot finish accumulation, because the stack size is still > 1");
}

bool BooleanFunctionAccumulator::canBePopped() {
    return _stack.size() == 1;
}

// This will wrap even single variable names for easier application of unary operators
static vector<string> getInfixTokens(const string &function) {
    regex tokensRegex(getInfixTokensRegex());
    smatch sm;
    vector<string> tokens;
    uint64_t i = 0;
    // regex_search can't take an r-value. Need to store it in a temp variable
    string substring;
    while (i < function.length() && regex_search((substring = function.substr(i, string::npos)), sm, tokensRegex, regex_constants::match_continuous)) {
        // Index 1 => The first group in the regex
        string token = sm[1];
        if (regex_match(token, regex(BOOLEAN_FUNCTION_REGEX))) {
            // Surround by parenthesis, so that the unary operators are properly applied
            tokens.push_back("(");
            tokens.push_back(token);
            tokens.push_back(")");
        } else {
            tokens.push_back(token);
        }
        i += (uint64_t) sm.position(1) + (uint64_t) sm[1].length();
    }
    if (i != function.length()) {
        // prematurely failed lookup because of match_continuous flag. Unknown token at index i
        throw UnknownTokenException("Unknown token in the string at index " + to_string(i) + " in the boolean function");
    }
    return tokens;
}

static vector<string> getPostfixTokens(const string &function) {
    // Variables have parenthesis around them always, so that unary operators can be properly applied
    vector<string> infixTokens = getInfixTokens(function);
    stack<string> operatorStack;
    vector<string> postfixTokens;

    // These are the regexes of the tokens that are allowed before a ")".
    // In other words, these can be put in the operator stack until a ")" is encountered
    vector<string> operatorStackItems = OPERATOR_REGEXES;
    operatorStackItems.push_back("[\\(]");
    const regex stackItemsRegex(join(operatorStackItems, "|"));
    smatch sm;

    for (size_t i = 0; i < infixTokens.size(); ++i) {
        const string &token = infixTokens[i];

        // Validate that if the token is a prefix unary operator, it has a valid token that follows
        if (isKnownPrefixUnaryOperator(token)) {
            // prefix unary operator can't be the last token
            if (i == infixTokens.size() - 1 ||
            // prefix unary operator can only follow a parenthesis or another prefix unary operator
                !(infixTokens[i+1] == "(" || isKnownPrefixUnaryOperator(infixTokens[i+1]))) {
                throw BadBooleanFunctionException("Misplaced prefix unary operator: " + token);
            }
        }

        // Validate that if the token is a suffix unary operator, it has a valid token that followed
        if (isKnownSuffixUnaryOperator(token)) {
            // suffix unary operator can't be the first token
            if (i == 0 ||
                !(infixTokens[i-1] == ")" || isKnownSuffixUnaryOperator(infixTokens[i-1]))) {
                throw BadBooleanFunctionException("Misplaced suffix unary operator: " + token);
            }
        }

        // At this point, we know that prefix and suffix unary operators are at the correct logical locations

        if (token == ")") {
            while (true) {
                if (operatorStack.empty()) {
                    throw BadBooleanFunctionException("Unbalanced parenthesis: " + function);
                }

                string top = topAndPop(operatorStack);
                if (top == "(") {
                    // Prefix unary operators are expected right before the opening parenthesis.
                    // So push these to the postFixTokens list right here
                    while (!operatorStack.empty() && isKnownPrefixUnaryOperator(operatorStack.top())) {
                        string unaryOperator = topAndPop(operatorStack);
                        postfixTokens.push_back(unaryOperator);
                    }
                    break;
                } else {
                    postfixTokens.push_back(top);
                }
            }
        } else if (regex_match(token, sm, stackItemsRegex)) {
            if (isKnownSuffixUnaryOperator(token)) {
                postfixTokens.push_back(token);
            } else {
                operatorStack.push(token);
            }
        } else {
            // Not ")" or "(", and not matching operator regexes, but still in the list of infix tokens
            // => must be a variable name or a constant
            postfixTokens.push_back(token);
        }
    }

    while (!operatorStack.empty()) {
        string top = topAndPop(operatorStack);
        if (top == "(") {
            throw BadBooleanFunctionException("Unbalanced parenthesis: " + function);
        }
        postfixTokens.push_back(top);
    }

    return postfixTokens;
}

BooleanFunction BooleanFunctionParser::parse(const string &function) const {
    return parse(function, [](const string &functionName) -> const BooleanFunction& {
        throw BooleanFunctionNotFoundException("Boolean function not found: " + functionName);
    });
}

BooleanFunction BooleanFunctionParser::parse(const string &function, std::function<const BooleanFunction& (const string&)> lookupFunction) const {
    vector<string> postfixTokens = getPostfixTokens(trim(function));
    BooleanFunctionAccumulator accumulator;
    for (const string &token : postfixTokens) {
        if (isKnownUnaryOperator(token)) {
            UnaryOperator *op;
            try {
                op = createUnaryOperatorWithSymbol(token);
            } catch (const invalid_argument &ex) {
                throw BadBooleanFunctionException(ex.what());
            }
            accumulator.push(*op);
            delete op;
        } else if (isKnownBinaryOperator(token)) {
            BinaryOperator *op;
            try {
                op = createBinaryOperatorWithSymbol(token);
            } catch (const invalid_argument &ex) {
                throw BadBooleanFunctionException(ex.what());
            }
            accumulator.push(*op);
            delete op;
        } else {
            // token == variable
            if (token.c_str()[0] == '$') {
                string lookupFunctionName = token.substr(1, string::npos);
                if (lookupFunctionName.length() == 0) {
                    // someone used $ as a variable name
                    throw UnknownTokenException("'$' is reserved token, and cannot be used as a variable name.");
                }
                const BooleanFunction &function = lookupFunction(lookupFunctionName);
                accumulator.push(function);
            } else {
                if (token == "0" || token == "1") {
                    accumulator.push(BooleanFunction(token == "1"));
                } else {
                    BooleanFunction function(TruthTable({ token }));
                    function.getTruthTable()[0] = false;
                    function.getTruthTable()[1] = true;
                    accumulator.push(function);
                }
            }
        }
    }

    if (!accumulator.canBePopped()) {
        throw BadBooleanFunctionException("Missing operator tokens in the boolean function.");
    }

    return accumulator.pop();
}
}


text:
import sys
sys.path.insert(1, "../../")
import h2o, tests

def metric_json_check():

    df = h2o.import_file(path=h2o.locate("smalldata/logreg/prostate.csv"))

    # Regression metric json
    reg_mod = h2o.gbm(y=df["CAPSULE"], x=df[3:], training_frame=df, distribution="gaussian")
    reg_met = reg_mod.model_performance()
    reg_metric_json_keys_have = reg_met._metric_json.keys()
    reg_metric_json_keys_desired = [u'model_category',
                                    u'description',
                                    u'r2',
                                    u'frame',
                                    u'model_checksum',
                                    u'MSE',
                                    u'__meta',
                                    u'scoring_time',
                                    u'predictions',
                                    u'model',
                                    u'duration_in_ms',
                                    u'frame_checksum',
                                    u'mean_residual_deviance']
    reg_metric_diff = list(set(reg_metric_json_keys_have) - set(reg_metric_json_keys_desired))
    assert not reg_metric_diff, "There's a difference between the current ({0}) and the desired ({1}) regression " \
                                "metric json. The difference is {2}".format(reg_metric_json_keys_have,
                                                                            reg_metric_json_keys_desired,
                                                                            reg_metric_diff)
    # Regression metric json (GLM)
    reg_mod = h2o.glm(y=df["CAPSULE"], x=df[3:], training_frame=df, family="gaussian")
    reg_met = reg_mod.model_performance()
    reg_metric_json_keys_have = reg_met._metric_json.keys()
    reg_metric_json_keys_desired = [u'model_category',
                                    u'description',
                                    u'r2',
                                    u'residual_degrees_of_freedom',
                                    u'frame',
                                    u'model_checksum',
                                    u'MSE',
                                    u'__meta',
                                    u'null_deviance',
                                    u'scoring_time',
                                    u'null_degrees_of_freedom',
                                    u'predictions',
                                    u'AIC',
                                    u'model',
                                    u'duration_in_ms',
                                    u'frame_checksum',
                                    u'residual_deviance',
                                    u'mean_residual_deviance']
    reg_metric_diff = list(set(reg_metric_json_keys_have) - set(reg_metric_json_keys_desired))
    assert not reg_metric_diff, "There's a difference between the current ({0}) and the desired ({1}) glm-regression " \
                                "metric json. The difference is {2}".format(reg_metric_json_keys_have,
                                                                            reg_metric_json_keys_desired,
                                                                            reg_metric_diff)

    # Binomial metric json
    bin_mod = h2o.gbm(y=df["CAPSULE"].asfactor(), x=df[3:], training_frame=df, distribution="bernoulli")
    bin_met = bin_mod.model_performance()
    bin_metric_json_keys_have = bin_met._metric_json.keys()
    bin_metric_json_keys_desired = [u'AUC',
                                    u'Gini',
                                    u'model_category',
                                    u'description',
                                    u'r2',
                                    u'frame',
                                    u'model_checksum',
                                    u'MSE',
                                    u'__meta',
                                    u'logloss',
                                    u'scoring_time',
                                    u'thresholds_and_metric_scores',
                                    u'predictions',
                                    u'max_criteria_and_metric_scores',
                                    u'model',
                                    u'duration_in_ms',
                                    u'frame_checksum',
                                    u'domain']
    bin_metric_diff = list(set(bin_metric_json_keys_have) - set(bin_metric_json_keys_desired))
    assert not bin_metric_diff, "There's a difference between the current ({0}) and the desired ({1}) binomial " \
                                "metric json. The difference is {2}".format(bin_metric_json_keys_have,
                                                                            bin_metric_json_keys_desired,
                                                                            bin_metric_diff)

    # Binomial metric json (GLM)
    bin_mod = h2o.glm(y=df["CAPSULE"].asfactor(), x=df[3:], training_frame=df, family="binomial")
    bin_met = bin_mod.model_performance()
    bin_metric_json_keys_have = bin_met._metric_json.keys()
    bin_metric_json_keys_desired = [u'frame',
                                    u'residual_deviance',
                                    u'max_criteria_and_metric_scores',
                                    u'MSE',
                                    u'frame_checksum',
                                    u'AIC',
                                    u'logloss',
                                    u'Gini',
                                    u'predictions',
                                    u'AUC',
                                    u'description',
                                    u'model_checksum',
                                    u'duration_in_ms',
                                    u'model_category',
                                    u'r2',
                                    u'residual_degrees_of_freedom',
                                    u'__meta',
                                    u'null_deviance',
                                    u'scoring_time',
                                    u'null_degrees_of_freedom',
                                    u'model',
                                    u'thresholds_and_metric_scores',
                                    u'domain']
    bin_metric_diff = list(set(bin_metric_json_keys_have) - set(bin_metric_json_keys_desired))
    assert not bin_metric_diff, "There's a difference between the current ({0}) and the desired ({1}) glm-binomial " \
                                "metric json. The difference is {2}".format(bin_metric_json_keys_have,
                                                                            bin_metric_json_keys_desired,
                                                                            bin_metric_diff)

    # Multinomial metric json
    df = h2o.import_file(path=h2o.locate("smalldata/airlines/AirlinesTrain.csv.zip"))
    myX = ["Origin", "Dest", "IsDepDelayed", "UniqueCarrier", "Distance", "fDayofMonth", "fDayOfWeek"]
    myY = "fYear"
    mul_mod = h2o.gbm(x=df[myX], y=df[myY], training_frame=df, distribution="multinomial")
    mul_met = mul_mod.model_performance()
    mul_metric_json_keys_have = mul_met._metric_json.keys()
    mul_metric_json_keys_desired = [u'cm',
                                    u'model_category',
                                    u'description',
                                    u'r2',
                                    u'frame',
                                    u'model_checksum',
                                    u'MSE',
                                    u'__meta',
                                    u'logloss',
                                    u'scoring_time',
                                    u'predictions',
                                    u'hit_ratio_table',
                                    u'model',
                                    u'duration_in_ms',
                                    u'frame_checksum']
    mul_metric_diff = list(set(mul_metric_json_keys_have) - set(mul_metric_json_keys_desired))
    assert not mul_metric_diff, "There's a difference between the current ({0}) and the desired ({1}) multinomial " \
                                "metric json. The difference is {2}".format(mul_metric_json_keys_have,
                                                                            mul_metric_json_keys_desired,
                                                                            mul_metric_diff)

    # Clustering metric json
    df = h2o.import_file(path=h2o.locate("smalldata/iris/iris.csv"))
    clus_mod = h2o.kmeans(x=df[0:4], k=3, standardize=False)
    clus_met = clus_mod.model_performance()
    clus_metric_json_keys_have = clus_met._metric_json.keys()
    clus_metric_json_keys_desired = [u'tot_withinss',
                                     u'model_category',
                                     u'description',
                                     u'frame',
                                     u'model_checksum',
                                     u'MSE',
                                     u'__meta',
                                     u'scoring_time',
                                     u'betweenss',
                                     u'predictions',
                                     u'totss',
                                     u'model',
                                     u'duration_in_ms',
                                     u'frame_checksum',
                                     u'centroid_stats']
    clus_metric_diff = list(set(clus_metric_json_keys_have) - set(clus_metric_json_keys_desired))
    assert not clus_metric_diff, "There's a difference between the current ({0}) and the desired ({1}) clustering " \
                                "metric json. The difference is {2}".format(clus_metric_json_keys_have,
                                                                            clus_metric_json_keys_desired,
                                                                            clus_metric_diff)

if __name__ == "__main__":
    tests.run_test(sys.argv, metric_json_check)


text:
body {
    font-family:  'Open Sans', sans-serif;
}

.img-radius {
    border-radius: 50%;
    border:6px double #FFF;
}

.go-back-top {
    width: 50px;
    height: 50px;
    background: #7FCBCD url('../images/top.png') no-repeat center center;
    background-size:30px;
    border-radius: 50%;
    position: fixed;
    bottom:50px;
    right: 50px;
    z-index: 99999;
}

img {
    max-width: 100%;
}

.tasks {
    margin:0px;
    padding:0px;
    list-style: none;
    lost-utility: clearfix;

    .task {
        float:left;
        lost-column: 3/12 4;
        text-align: center;
        background: #7FCBCD;
        color: #FFF;
        padding:20px 15px;
        border-radius: 5px;
        min-height: 80px;

        &.deadline {
           background: #c94c4c;
        }
    }

    .task__title {
        text-align:center;
        font-size: 16px;
        font-weight: bold;
        min-height: 30px;
    }

    .task__header {
        font-family:'Orbitron', sans-serif;
        text-align:center;
        font-size: 16px;
        margin-top: 10px;
        lost-utility: clearfix;

        .task__status {
            font-weight: bold;
            float: left;
        }

        .task__date {
            font-size: 14px;
            display:inline-block;
            float:right;
        }
    }

    .taks__description {
        text-align: justify;
    }
}

.author {
    margin:0px;
    padding:0px;
    list-style: none;
    lost-utility: clearfix;

    img {
        max-width:150px;
        width:100%;
    }

    .author__item {
        float:left;
        lost-column: 4/12 3;
        text-align: center;
    }

    .author__name {
        font-family:'Orbitron', sans-serif;
        text-align:center;
        font-size: 16px;
        margin-top: 10px;
    }
}

#main {
    min-height: 500px;

}

.bg_section {
    background: #f8f8f8;
    padding:30px 0px;
}

/* Fomulário Contato */

.template-contato .ninja-forms-cont {
    padding: 30px 60px;
    width: 600px;
    margin: 0 auto;
    background-color: #0054A5;
    color: #000;
    margin-bottom: 80px;
    margin-top: 40px;
}

.template-contato .nome,
.template-contato .email,
.template-contato .mensagem {
    font-family: 'open_sansregular';
    background-color: #0054A5;
    border: none;
    border-bottom: 1px solid rgba(255,255,255,0.3);
    padding-left: 0px;
}

.template-contato .mensagem {
    height: 31px;
}

.template-contato .ninja-forms-field {
    color: #fff;
}

.template-orcamento .submit-wrap,
.template-contato .submit-wrap {
    text-align: center;
}

.template-contato .nf-desc h2 {
    font-family: 'open_sansregular';
    border-bottom: 1px solid rgba(255,255,255,0.3);
    margin-bottom: 50px;
    padding-bottom: 20px;
    font-size: 17px;
}

.template-contato .btn {
    font-family: 'open_sansregular';
    background-color: #FEF200;
    text-transform: uppercase;
    border-radius: 24px;
    border: none;
    font-size: 13px;
    color: #ED1B24;
    font-weight: bold;
    padding: 15px 40px;
    font-weight: 800;
}

.template-contato .ninja-forms-required-items {
    display: none;
}

/* Fomulário Orçamento */

.template-orcamento {
    margin-top: 40px;
}

.template-orcamento .ninja-forms-cont {
    margin: 30px 30px;
    max-width: 600px;
    margin: 0 auto;
    color: #000;
}

.template-orcamento .ninja-forms-required-items {
    display: none;
}

.template-orcamento .btn {
    background-color: #ED1B24;
    text-transform: uppercase;
    border-radius: 4px;
    border: none;
    font-size: 13px;
    color: #fff;
    font-weight: bold;
    padding: 15px 100px;
    font-weight: 800;
}

.template-orcamento .field-wrap {
    margin-bottom: 5px;
}

.template-orcamento .nome,
.template-orcamento .sobrenome,
.template-orcamento .marca,
.template-orcamento .veiculo,
.template-orcamento .modelo,
.template-orcamento .ano,
.template-orcamento .sobrenome,
.template-orcamento .email,
.template-orcamento .telefone,
.template-orcamento .mensagem {
    border: none;
    border: 2px solid #DCDCDC;
    color: #A9A9A9;
    border-radius: 4px;
}

.template-orcamento .ano {
    height: 30px;
    margin-bottom: 10px;
    padding: 5px 10px;
}

.template-orcamento .number-wrap label {
    font-weight: normal;
    color: #808080;
}

.orcamentos h1,
.template-orcamento h1 {
    font-family: 'open_sansbold';
    font-weight: bold;
    color: #0054A5;
    font-size: 70px;
    letter-spacing: -5px;
    margin: 0;
    font-weight: 800;
}

.orcamentos span,
.template-orcamento .sub-title {
    font-family: 'open_sansbold';
    color: #0054A5;
    font-size: 26px;
    letter-spacing: 5px;
    text-transform: uppercase;
    margin-left: 135px;
    position: relative;
    top: -23px;
    border-bottom: 3px solid #0054A5;
}

.align {
    text-align: center;
}

/* Página Empresa */

.page-template-template-sobre-nos header {
    margin-bottom: 0px;
}

.template-sobre-nos .missao,
.template-sobre-nos .historia {
    margin-bottom: 0;
}

.template-sobre-nos .visao .wpb_column,
.template-sobre-nos .missao .wpb_column {
    padding: 0;
}

.template-sobre-nos .missao .missao-custom01 {
    min-height: 357px;
}

.template-sobre-nos .missao .missao-custom02 {
    height: 357px;
}

.template-sobre-nos .visao .visao-custom {
    min-height: 245px;
}

.template-sobre-nos .vc_single_image-wrapper {
    display: inline ! important;
}

.template-sobre-nos .wpb_single_image img {
    width: 100%;
}

/* Formulário Home */

.slid-form {
    position: relative;
}

.home-formulario {
    position: absolute;
    top: 0;
    right: 0;
}

#circulo {
    background: #666;
    border-radius: 100%;
    width: 150px;
    height: 150px;
    background-color: #ED1B24;
    border: 8px solid #ca2128;
    cursor: pointer;
    margin: 0 auto;
}

#circulo a {
    color: #fff;
    text-decoration: none;
    display: block;
    padding: 47px 0 50px;
    text-transform: uppercase;
    font-weight: bold;
}

.orcamentos-home {
    height: 200px !important;
    margin-bottom: 50px;
    margin-top: 100px;
    padding-bottom: 50px;
    border-bottom: 1px solid #ccc;
}

@media (max-width: 768px) {
    .template-sobre-nos .missao .missao-custom02 {
        height: auto;
    }
}


text:
package org.elasticsearch.monitor.fs;

import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class FsInfo implements Iterable<FsInfo.Path>, Writeable, ToXContent {

    public static class Path implements Writeable, ToXContent {

        String path;
        @Nullable
        String mount;
        /** File system type from {@code java.nio.file.FileStore type()}, if available. */
        @Nullable
        String type;
        long total = -1;
        long free = -1;
        long available = -1;

        /** Uses Lucene's {@code IOUtils.spins} method to try to determine if the device backed by spinning media.
         *  This is null if we could not determine it, true if it possibly spins, else false. */
        Boolean spins = null;

        public Path() {
        }

        public Path(String path, @Nullable String mount, long total, long free, long available) {
            this.path = path;
            this.mount = mount;
            this.total = total;
            this.free = free;
            this.available = available;
        }

        /**
         * Read from a stream.
         */
        public Path(StreamInput in) throws IOException {
            path = in.readOptionalString();
            mount = in.readOptionalString();
            type = in.readOptionalString();
            total = in.readLong();
            free = in.readLong();
            available = in.readLong();
            spins = in.readOptionalBoolean();
        }

        @Override
        public void writeTo(StreamOutput out) throws IOException {
            out.writeOptionalString(path); // total aggregates do not have a path
            out.writeOptionalString(mount);
            out.writeOptionalString(type);
            out.writeLong(total);
            out.writeLong(free);
            out.writeLong(available);
            out.writeOptionalBoolean(spins);
        }

        public String getPath() {
            return path;
        }

        public String getMount() {
            return mount;
        }

        public String getType() {
            return type;
        }

        public ByteSizeValue getTotal() {
            return new ByteSizeValue(total);
        }

        public ByteSizeValue getFree() {
            return new ByteSizeValue(free);
        }

        public ByteSizeValue getAvailable() {
            return new ByteSizeValue(available);
        }

        public Boolean getSpins() {
            return spins;
        }

        private long addLong(long current, long other) {
            if (other == -1) {
                return current;
            }
            if (current == -1) {
                return other;
            }
            return current + other;
        }

        private double addDouble(double current, double other) {
            if (other == -1) {
                return current;
            }
            if (current == -1) {
                return other;
            }
            return current + other;
        }

        public void add(Path path) {
            total = addLong(total, path.total);
            free = addLong(free, path.free);
            available = addLong(available, path.available);
            if (path.spins != null && path.spins.booleanValue()) {
                // Spinning is contagious!
                spins = Boolean.TRUE;
            }
        }

        static final class Fields {
            static final String PATH = "path";
            static final String MOUNT = "mount";
            static final String TYPE = "type";
            static final String TOTAL = "total";
            static final String TOTAL_IN_BYTES = "total_in_bytes";
            static final String FREE = "free";
            static final String FREE_IN_BYTES = "free_in_bytes";
            static final String AVAILABLE = "available";
            static final String AVAILABLE_IN_BYTES = "available_in_bytes";
            static final String SPINS = "spins";
        }

        @Override
        public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
            builder.startObject();
            if (path != null) {
                builder.field(Fields.PATH, path);
            }
            if (mount != null) {
                builder.field(Fields.MOUNT, mount);
            }
            if (type != null) {
                builder.field(Fields.TYPE, type);
            }

            if (total != -1) {
                builder.byteSizeField(Fields.TOTAL_IN_BYTES, Fields.TOTAL, total);
            }
            if (free != -1) {
                builder.byteSizeField(Fields.FREE_IN_BYTES, Fields.FREE, free);
            }
            if (available != -1) {
                builder.byteSizeField(Fields.AVAILABLE_IN_BYTES, Fields.AVAILABLE, available);
            }
            if (spins != null) {
                builder.field(Fields.SPINS, spins.toString());
            }

            builder.endObject();
            return builder;
        }
    }

    final long timestamp;
    final Path[] paths;
    Path total;

    public FsInfo(long timestamp, Path[] paths) {
        this.timestamp = timestamp;
        this.paths = paths;
        this.total = null;
    }

    /**
     * Read from a stream.
     */
    public FsInfo(StreamInput in) throws IOException {
        timestamp = in.readVLong();
        paths = new Path[in.readVInt()];
        for (int i = 0; i < paths.length; i++) {
            paths[i] = new Path(in);
        }
    }

    @Override
    public void writeTo(StreamOutput out) throws IOException {
        out.writeVLong(timestamp);
        out.writeVInt(paths.length);
        for (Path path : paths) {
            path.writeTo(out);
        }
    }

    public Path getTotal() {
        return total();
    }

    public Path total() {
        if (total != null) {
            return total;
        }
        Path res = new Path();
        Set<String> seenDevices = new HashSet<>(paths.length);
        for (Path subPath : paths) {
            if (subPath.path != null) {
                if (!seenDevices.add(subPath.path)) {
                    continue; // already added numbers for this device;
                }
            }
            res.add(subPath);
        }
        total = res;
        return res;
    }

    public long getTimestamp() {
        return timestamp;
    }

    @Override
    public Iterator<Path> iterator() {
        return Arrays.stream(paths).iterator();
    }

    static final class Fields {
        static final String FS = "fs";
        static final String TIMESTAMP = "timestamp";
        static final String DATA = "data";
        static final String TOTAL = "total";
    }

    @Override
    public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
        builder.startObject(Fields.FS);
        builder.field(Fields.TIMESTAMP, timestamp);
        builder.field(Fields.TOTAL);
        total().toXContent(builder, params);
        builder.startArray(Fields.DATA);
        for (Path path : paths) {
            path.toXContent(builder, params);
        }
        builder.endArray();
        builder.endObject();
        return builder;
    }
}


text:
<!--

-->

<HTML lang="en-US">
<TITLE>
QuoteClientApplet
</TITLE>

<BODY>
<script src="http://www.java.com/js/deployJava.js"></script>
<script>
    var attributes = { code:'QuoteClientApplet.class',  width:500, height:100} ;
    var parameters = {codebase_lookup:'true'};
    deployJava.runApplet(attributes, parameters, '1.6');
</script>
<noscript>
A browser with JavaScript enabled is required for this page to operate properly.
</noscript>

</BODY>
</HTML>


text:
package terminal.commands;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.ECPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.util.Arrays;

import javax.smartcardio.CommandAPDU;
import javax.smartcardio.ResponseAPDU;

import terminal.crypto.ECCKeyGenerator;
import terminal.crypto.ECCSignature;
import terminal.utils.CertCounter;
import terminal.utils.Conversions;

import terminal.utils.LogToFile;

/**
 * Class that handles the communication between the vehicle and the card
 *
 * @author Federico Scrinzi
 * @author Nils Rodday
 *
 */
public class VehicleCommands {
	public static final byte CLA_VEHICLE = (byte) 0xB2;
	public static final byte CMD_VEH_INIT = (byte) 0x00;
	public static final byte CMD_VEH_START = (byte) 0x01;
	public static final byte CMD_VEH_SAVEKM = (byte) 0x02;

	public static final int SW_CONDITIONS_NOT_SATISFIED = 0x6985;

	public static final short NONCE_LENGTH = 8;

	CardCommunication comm;
	SecureRandom random;

	byte[] cardNonce;

	ECPublicKey cardKey;
	ECPublicKey companyKey;
	KeyPair vehicleKeypair;

	String carID;

	public VehicleCommands(CardCommunication c, String id) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException {
		comm = c;
		random = new SecureRandom();
		carID = id;
		vehicleKeypair = ECCKeyGenerator.loadKeys("data/cars", carID);
		companyKey = (ECPublicKey) ECCKeyGenerator.loadPublicKey("data/master", "company");
	}

	/**
	 * Initializes the communication between the vehicle and the card
	 *
	 * @throws Exception
	 */
	private void sendInit() throws Exception {
		byte[] nonce = new byte[NONCE_LENGTH];
		random.nextBytes(nonce);

		ResponseAPDU response = comm.sendCommandAPDU(
			new CommandAPDU(CLA_VEHICLE, CMD_VEH_INIT, 0x00, 0x00, nonce, 255)
		);
		if (response.getSW() != 0x9000) {
			throw new Exception("Got invalid response");
		}
		byte[] buffer = response.getData();

		//Receive nonceB
		cardNonce = Arrays.copyOfRange(buffer, 0, NONCE_LENGTH);

		//Public card key
		cardKey = (ECPublicKey) ECCKeyGenerator.decodeKey(Conversions.getChunk(buffer, NONCE_LENGTH, 0));

		//Get Cert counter
		long certCounter = Conversions.bytesToLong(Conversions.getChunk(buffer, NONCE_LENGTH, 1));

		//Get Sc
		byte[] vehicleCert = Conversions.getChunk(buffer, NONCE_LENGTH, 2);

		//Get validation Certificate
		byte[] validationCert = Conversions.getChunk(buffer, NONCE_LENGTH, 3);

		//Check that new counter is higher than old one
		long currentCounter = CertCounter.getCarCounter(carID);
		if (certCounter >= currentCounter) {
			CertCounter.setCarCounter(carID, certCounter);
		}
		else {
			throw new SecurityException("CertCounter is lower than vehicle's one. Rejecting card");
		}

		ByteArrayOutputStream dataToVerify = new ByteArrayOutputStream();

		//Verify Signature Sc
		dataToVerify.write(Conversions.encodePubKey((ECPublicKey) vehicleKeypair.getPublic()));
		dataToVerify.write(Conversions.encodePubKey(cardKey));
		dataToVerify.write(Conversions.longToBytes(certCounter));

		boolean verified = ECCSignature.verifySig(dataToVerify.toByteArray(), companyKey, vehicleCert);
		if (!verified) {
			throw new SecurityException("Vehicle certificate is not valid. Rejecting card");
		}

		dataToVerify.reset();

		//Verify Signature of NonceA and Sc
		dataToVerify.write(nonce);
		dataToVerify.write(vehicleCert);

		verified = ECCSignature.verifySig(dataToVerify.toByteArray(), cardKey, validationCert);
		if (!verified) {
			throw new SecurityException("Signature of Nonce and Signature Sc is not valid!");
		}
	}

	/**
	 * Sends a command to the card for starting the vehicle.
	 * If the operation is successful, it means that the card was authorized for this vehicle and
	 * the inUse flag on the card was set.
	 *
	 * @throws Exception
	 */
	private void sendStart() throws Exception {
		byte[] nonce = new byte[NONCE_LENGTH];
		random.nextBytes(nonce);
		byte[] signature = ECCSignature.signData(cardNonce, vehicleKeypair.getPrivate());

		ByteArrayOutputStream dataToSend = new ByteArrayOutputStream();
		dataToSend.write(nonce);
		dataToSend.write(signature.length);
		dataToSend.write(signature);

		ResponseAPDU response = comm.sendCommandAPDU(
			new CommandAPDU(CLA_VEHICLE, CMD_VEH_START, 0x00, 0x00, dataToSend.toByteArray(), 255)
		);

		if (response.getSW() == SW_CONDITIONS_NOT_SATISFIED) {
			throw new IllegalStateException(
				"InUse flag is set. The vehicle cannot be started before the previous km " +
				"value will be saved on the card"
			);
		}

		if (response.getSW() != 0x9000) {
			throw new Exception("Got invalid response");
		}

		byte[] buffer = response.getData();
		cardNonce = Arrays.copyOfRange(buffer, 0, NONCE_LENGTH);
		signature = Arrays.copyOfRange(buffer, NONCE_LENGTH, buffer.length);
		boolean verified = ECCSignature.verifySig(nonce, cardKey, signature);
		if (!verified) {
			throw new SecurityException("Card signature is not valid. Rejecting card and not starting vehicle");
		}
	}

	/**
	 * Sends a command to write the driven kilometers to the card.
	 * If the operation was successful a non-repudiation proof of the writing on the card is sent
	 * to the terminal and saved in the terminal log
	 *
	 * @param kilometers number of driven kilometers
	 * @throws Exception
	 */
	void writeKilometers(long kilometers) throws Exception {
		byte[] nonce = new byte[NONCE_LENGTH];
		random.nextBytes(nonce);

		byte[] kmBytes = Conversions.longToBytes(kilometers);

		ByteArrayOutputStream dataToSign = new ByteArrayOutputStream();
		dataToSign.write(cardNonce);
		dataToSign.write(kmBytes);
		byte[] signature = ECCSignature.signData(dataToSign.toByteArray(), vehicleKeypair.getPrivate());

		ByteArrayOutputStream dataToSend = new ByteArrayOutputStream();
		dataToSend.write(nonce);
		dataToSend.write(kmBytes.length);
		dataToSend.write(kmBytes);
		dataToSend.write(signature.length);
		dataToSend.write(signature);

		ResponseAPDU response = comm.sendCommandAPDU(
			new CommandAPDU(CLA_VEHICLE, CMD_VEH_SAVEKM, 0x00, 0x00, dataToSend.toByteArray(), 255)
		);
		if (response.getSW() != 0x9000) {
			throw new Exception("Got invalid response");
		}

		ByteArrayOutputStream dataToVerify = new ByteArrayOutputStream();
		dataToVerify.write(nonce);
		dataToVerify.write(CLA_VEHICLE);
		dataToVerify.write(CMD_VEH_SAVEKM);
		dataToVerify.write(kmBytes);

		byte[] buffer = response.getData();
		boolean verified = ECCSignature.verifySig(dataToVerify.toByteArray(), cardKey, buffer);
		if (!verified) {
			LogToFile.write("Card signature is not valid. Writing of kilometers was not successful", carID);
			throw new SecurityException("Card signature is not valid. Writing of kilometers was not successful");

		}

		LogToFile.write(
			"Nonce: " + Arrays.toString(nonce) + "\n" +
			"Kilometers: " + Arrays.toString(kmBytes) + "\n" +
			"Signature: " + Arrays.toString(buffer),
		carID);

	}

	/**
	 * Sends initialization command and checks if the card is allowed to start the vehicle
	 *
	 * @throws Exception
	 */
	public void startVehicle() throws Exception {
		sendInit();
		sendStart();
	}

	/**
	 * Sends initialization command and sends the amount of driven kilometers to the card
	 *
	 * @param kilometers number of driven kilometers
	 * @throws Exception
	 */
	public void stopVehicle(long kilometers) throws Exception {
		sendInit();
		writeKilometers(kilometers);
	}
}