text:
// independent from idl_parser, since this code is not needed for most clients

#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"

namespace flatbuffers {
namespace cpp {

// Ensure that a type is prefixed with its namespace whenever it is used
// outside of its namespace.
static std::string WrapInNameSpace(const Parser &parser, const Namespace *ns,
                                   const std::string &name) {
  if (parser.namespaces_.back() != ns) {
    std::string qualified_name;
    for (AUTO_VAR(it, ns->components.begin());
             it != ns->components.end(); ++it) {
      qualified_name += *it + "::";
    }
    return qualified_name + name;
  } else {
    return name;
  }
}

static std::string WrapInNameSpace(const Parser &parser,
                                   const Definition &def) {
  return WrapInNameSpace(parser, def.defined_namespace, def.name);
}

// Return a C++ type from the table in idl.h
static std::string GenTypeBasic(const Parser &parser, const Type &type,
                                bool real_enum) {
  static const char *ctypename[] = {
    #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE) #CTYPE,
      FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
    #undef FLATBUFFERS_TD
  };
  return real_enum && type.enum_def
      ? WrapInNameSpace(parser, *type.enum_def)
      : std::string(ctypename[type.base_type]);
}

static std::string GenTypeWire(const Parser &parser, const Type &type,
                               const char *postfix, bool real_enum);

// Return a C++ pointer type, specialized to the actual struct/table types,
// and vector element types.
static std::string GenTypePointer(const Parser &parser, const Type &type) {
  switch (type.base_type) {
    case BASE_TYPE_STRING:
      return "flatbuffers::String";
    case BASE_TYPE_VECTOR:
      return "flatbuffers::Vector<" +
             GenTypeWire(parser, type.VectorType(), "", false) + ">";
    case BASE_TYPE_STRUCT: {
      return WrapInNameSpace(parser, *type.struct_def);
    }
    case BASE_TYPE_UNION:
      // fall through
    default:
      return "void";
  }
}

// Return a C++ type for any type (scalar/pointer) specifically for
// building a flatbuffer.
static std::string GenTypeWire(const Parser &parser, const Type &type,
                               const char *postfix, bool real_enum) {
  return IsScalar(type.base_type)
    ? GenTypeBasic(parser, type, real_enum) + postfix
    : IsStruct(type)
      ? "const " + GenTypePointer(parser, type) + " *"
      : "flatbuffers::Offset<" + GenTypePointer(parser, type) + ">" + postfix;
}

// Return a C++ type for any type (scalar/pointer) that reflects its
// serialized size.
static std::string GenTypeSize(const Parser &parser, const Type &type) {
  return IsScalar(type.base_type)
    ? GenTypeBasic(parser, type, false)
    : IsStruct(type)
      ? GenTypePointer(parser, type)
      : std::string("flatbuffers::uoffset_t");
}

// Return a C++ type for any type (scalar/pointer) specifically for
// using a flatbuffer.
static std::string GenTypeGet(const Parser &parser, const Type &type,
                              const char *afterbasic, const char *beforeptr,
                              const char *afterptr, bool real_enum) {
  return IsScalar(type.base_type)
    ? GenTypeBasic(parser, type, real_enum) + afterbasic
    : beforeptr + GenTypePointer(parser, type) + afterptr;
}

static std::string GenEnumVal(const EnumDef &enum_def, const EnumVal &enum_val,
                              const GeneratorOptions &opts) {
  return opts.prefixed_enums ? enum_def.name + "_" + enum_val.name
                             : enum_val.name;
}

// Generate an enum declaration and an enum string lookup table.
static void GenEnum(const Parser &parser, EnumDef &enum_def,
                    std::string *code_ptr, std::string *code_ptr_post,
                    const GeneratorOptions &opts) {
  if (enum_def.generated) return;
  std::string &code = *code_ptr;
  std::string &code_post = *code_ptr_post;
  flatbuffers::GenComment(enum_def.doc_comment, code_ptr);
  code += "enum " + enum_def.name + " {\n";
  for (AUTO_VAR(it, enum_def.vals.vec.begin());
       it != enum_def.vals.vec.end();
       ++it) {
    AUTO_VAR(&ev, **it);
    flatbuffers::GenComment(ev.doc_comment, code_ptr, "  ");
    code += "  " + GenEnumVal(enum_def, ev, opts) + " = ";
    code += NumToString(ev.value);
    code += (it + 1) != enum_def.vals.vec.end() ? ",\n" : "\n";
  }
  code += "};\n\n";

  // Generate a generate string table for enum values.
  // Problem is, if values are very sparse that could generate really big
  // tables. Ideally in that case we generate a map lookup instead, but for
  // the moment we simply don't output a table at all.
  AUTO_VAR(range, enum_def.vals.vec.back()->value);
  range -= enum_def.vals.vec.front()->value + 1;
  // Average distance between values above which we consider a table
  // "too sparse". Change at will.
  static const int kMaxSparseness = 5;
  if (range / static_cast<int64_t>(enum_def.vals.vec.size()) < kMaxSparseness) {
    code += "inline const char **EnumNames" + enum_def.name + "() {\n";
    code += "  static const char *names[] = { ";
    AUTO_VAR(val, enum_def.vals.vec.front()->value);
    for (AUTO_VAR(it, enum_def.vals.vec.begin());
         it != enum_def.vals.vec.end();
         ++it) {
      while (val++ != (*it)->value) code += "\"\", ";
      code += "\"" + (*it)->name + "\", ";
    }
    code += "nullptr };\n  return names;\n}\n\n";
    code += "inline const char *EnumName" + enum_def.name;
    code += "(" + enum_def.name + " e) { return EnumNames" + enum_def.name + "()[e";
    if (enum_def.vals.vec.front()->value)
      code += " - " + GenEnumVal(enum_def, *enum_def.vals.vec.front(), opts);
    code += "]; }\n\n";
  }

  if (enum_def.is_union) {
    // Generate a verifier function for this union that can be called by the
    // table verifier functions. It uses a switch case to select a specific
    // verifier function to call, this should be safe even if the union type
    // has been corrupted, since the verifiers will simply fail when called
    // on the wrong type.
    std::string signature = "inline bool Verify" + enum_def.name +
                     "(flatbuffers::Verifier &verifier, " +
                     "const void *union_obj, " + enum_def.name + " type)";
    code += signature + ";\n\n";
    code_post += signature + " {\n  switch (type) {\n";
    for (AUTO_VAR(it, enum_def.vals.vec.begin());
         it != enum_def.vals.vec.end();
         ++it) {
      AUTO_VAR(&ev, **it);
      code_post += "    case " + GenEnumVal(enum_def, ev, opts);
      if (!ev.value) {
        code_post += ": return true;\n";  // "NONE" enum value.
      } else {
        code_post += ": return verifier.VerifyTable(reinterpret_cast<const ";
        code_post += WrapInNameSpace(parser, *ev.struct_def);
        code_post += " *>(union_obj));\n";
      }
    }
    code_post += "    default: return false;\n  }\n}\n\n";
  }
}

// Generates a value with optionally a cast applied if the field has a
// different underlying type from its interface type (currently only the
// case for enums. "from" specify the direction, true meaning from the
// underlying type to the interface type.
std::string GenUnderlyingCast(const Parser &parser, const FieldDef &field,
                              bool from, const std::string &val) {
  return field.value.type.enum_def && IsScalar(field.value.type.base_type)
      ? "static_cast<" + GenTypeBasic(parser, field.value.type, from) + ">(" +
        val + ")"
      : val;
}

// Generate an accessor struct, builder structs & function for a table.
static void GenTable(const Parser &parser, StructDef &struct_def,
                     const GeneratorOptions &opts, std::string *code_ptr) {
  if (struct_def.generated) return;
  std::string &code = *code_ptr;

  // Generate an accessor struct, with methods of the form:
  // type name() const { return GetField<type>(offset, defaultval); }
  flatbuffers::GenComment(struct_def.doc_comment, code_ptr);
  code += "struct " + struct_def.name;
  code += " FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table";
  code += " {\n";
  for (AUTO_VAR(it, struct_def.fields.vec.begin());
       it != struct_def.fields.vec.end();
       ++it) {
    AUTO_VAR(&field, **it);
    if (!field.deprecated) {  // Deprecated fields won't be accessible.
      flatbuffers::GenComment(field.doc_comment, code_ptr, "  ");
      code += "  " + GenTypeGet(parser, field.value.type, " ", "const ", " *",
                                true);
      code += field.name + "() const { return ";
      // Call a different accessor for pointers, that indirects.
      std::string call = IsScalar(field.value.type.base_type)
        ? "GetField<"
        : (IsStruct(field.value.type) ? "GetStruct<" : "GetPointer<");
      call += GenTypeGet(parser, field.value.type, "", "const ", " *", false);
      call += ">(" + NumToString(field.value.offset);
      // Default value as second arg for non-pointer types.
      if (IsScalar(field.value.type.base_type))
        call += ", " + field.value.constant;
      call += ")";
      code += GenUnderlyingCast(parser, field, true, call);
      code += "; }\n";
      AUTO_VAR(nested, field.attributes.Lookup("nested_flatbuffer"));
      if (nested) {
        AUTO_VAR(nested_root, parser.structs_.Lookup(nested->constant));
        assert(nested_root);  // Guaranteed to exist by parser.
        code += "  const " + nested_root->name + " *" + field.name;
        code += "_nested_root() const { return flatbuffers::GetRoot<";
        code += nested_root->name + ">(" + field.name + "()->Data()); }\n";
      }
      // Generate a comparison function for this field if it is a key.
      if (field.key) {
        code += "  bool KeyCompareLessThan(const " + struct_def.name;
        code += " *o) const { return ";
        if (field.value.type.base_type == BASE_TYPE_STRING) code += "*";
        code += field.name + "() < ";
        if (field.value.type.base_type == BASE_TYPE_STRING) code += "*";
        code += "o->" + field.name + "(); }\n";
        code += "  int KeyCompareWithValue(";
        if (field.value.type.base_type == BASE_TYPE_STRING) {
          code += "const char *val) const { return strcmp(" + field.name;
          code += "()->c_str(), val); }\n";
        } else {
          code += GenTypeBasic(parser, field.value.type, false);
          code += " val) const { return " + field.name + "() < val ? -1 : ";
          code += field.name + "() > val; }\n";
        }
      }
    }
  }
  // Generate a verifier function that can check a buffer from an untrusted
  // source will never cause reads outside the buffer.
  code += "  bool Verify(flatbuffers::Verifier &verifier) const {\n";
  code += "    return VerifyTableStart(verifier)";
  std::string prefix = " &&\n           ";
  for (AUTO_VAR(it, struct_def.fields.vec.begin());
       it != struct_def.fields.vec.end();
       ++it) {
    AUTO_VAR(&field, **it);
    if (!field.deprecated) {
      code += prefix + "VerifyField";
      if (field.required) code += "Required";
      code += "<" + GenTypeSize(parser, field.value.type);
      code += ">(verifier, " + NumToString(field.value.offset);
      code += " /* " + field.name + " */)";
      switch (field.value.type.base_type) {
        case BASE_TYPE_UNION:
          code += prefix + "Verify" + field.value.type.enum_def->name;
          code += "(verifier, " + field.name + "(), " + field.name + "_type())";
          break;
        case BASE_TYPE_STRUCT:
          if (!field.value.type.struct_def->fixed) {
            code += prefix + "verifier.VerifyTable(" + field.name;
            code += "())";
          }
          break;
        case BASE_TYPE_STRING:
          code += prefix + "verifier.Verify(" + field.name + "())";
          break;
        case BASE_TYPE_VECTOR:
          code += prefix + "verifier.Verify(" + field.name + "())";
          switch (field.value.type.element) {
            case BASE_TYPE_STRING: {
              code += prefix + "verifier.VerifyVectorOfStrings(" + field.name;
              code += "())";
              break;
            }
            case BASE_TYPE_STRUCT: {
              if (!field.value.type.struct_def->fixed) {
                code += prefix + "verifier.VerifyVectorOfTables(" + field.name;
                code += "())";
              }
              break;
            }
            default:
              break;
          }
          break;
        default:
          break;
      }
    }
  }
  code += prefix + "verifier.EndTable()";
  code += ";\n  }\n";
  code += "};\n\n";

  // Generate a builder struct, with methods of the form:
  // void add_name(type name) { fbb_.AddElement<type>(offset, name, default); }
  code += "struct " + struct_def.name;
  code += "Builder {\n  flatbuffers::FlatBufferBuilder &fbb_;\n";
  code += "  flatbuffers::uoffset_t start_;\n";
  for (AUTO_VAR(it, struct_def.fields.vec.begin());
       it != struct_def.fields.vec.end();
       ++it) {
    AUTO_VAR(&field, **it);
    if (!field.deprecated) {
      code += "  void add_" + field.name + "(";
      code += GenTypeWire(parser, field.value.type, " ", true) + field.name;
      code += ") { fbb_.Add";
      if (IsScalar(field.value.type.base_type)) {
        code += "Element<" + GenTypeWire(parser, field.value.type, "", false);
        code += ">";
      } else if (IsStruct(field.value.type)) {
        code += "Struct";
      } else {
        code += "Offset";
      }
      code += "(" + NumToString(field.value.offset) + ", ";
      code += GenUnderlyingCast(parser, field, false, field.name);
      if (IsScalar(field.value.type.base_type))
        code += ", " + field.value.constant;
      code += "); }\n";
    }
  }
  code += "  " + struct_def.name;
  code += "Builder(flatbuffers::FlatBufferBuilder &_fbb) : fbb_(_fbb) ";
  code += "{ start_ = fbb_.StartTable(); }\n";
  code += "  " + struct_def.name + "Builder &operator=(const ";
  code += struct_def.name + "Builder &);\n";
  code += "  flatbuffers::Offset<" + struct_def.name;
  code += "> Finish() {\n    auto o = flatbuffers::Offset<" + struct_def.name;
  code += ">(fbb_.EndTable(start_, ";
  code += NumToString(struct_def.fields.vec.size()) + "));\n";
  for (AUTO_VAR(it, struct_def.fields.vec.begin());
       it != struct_def.fields.vec.end();
       ++it) {
    AUTO_VAR(&field, **it);
    if (!field.deprecated && field.required) {
      code += "    fbb_.Required(o, " + NumToString(field.value.offset);
      code += ");  // " + field.name + "\n";
    }
  }
  code += "    return o;\n  }\n};\n\n";

  // Generate a convenient CreateX function that uses the above builder
  // to create a table in one go.
  code += "inline flatbuffers::Offset<" + struct_def.name + "> Create";
  code += struct_def.name;
  code += "(flatbuffers::FlatBufferBuilder &_fbb";
  for (AUTO_VAR(it, struct_def.fields.vec.begin());
       it != struct_def.fields.vec.end();
       ++it) {
    AUTO_VAR(&field, **it);
    if (!field.deprecated) {
      code += ",\n   " + GenTypeWire(parser, field.value.type, " ", true);
      code += field.name + " = ";
      if (field.value.type.enum_def && IsScalar(field.value.type.base_type)) {
        AUTO_VAR(ev, field.value.type.enum_def->ReverseLookup(
            static_cast<int>(StringToInt(field.value.constant.c_str())), false));
        if (ev) {
          code += WrapInNameSpace(parser,
                                  field.value.type.enum_def->defined_namespace,
                                  GenEnumVal(*field.value.type.enum_def, *ev,
                                             opts));
        } else {
          code += GenUnderlyingCast(parser, field, true, field.value.constant);
        }
      } else {
        code += field.value.constant;
      }
    }
  }
  code += ") {\n  " + struct_def.name + "Builder builder_(_fbb);\n";
  for (size_t size = struct_def.sortbysize ? sizeof(largest_scalar_t) : 1;
       size;
       size /= 2) {
    for (AUTO_VAR(it, struct_def.fields.vec.rbegin());
         it != struct_def.fields.vec.rend();
         ++it) {
      AUTO_VAR(&field, **it);
      if (!field.deprecated &&
          (!struct_def.sortbysize ||
           size == SizeOf(field.value.type.base_type))) {
        code += "  builder_.add_" + field.name + "(" + field.name + ");\n";
      }
    }
  }
  code += "  return builder_.Finish();\n}\n\n";
}

static void GenPadding(const FieldDef &field,
    const std_or_boost::function<void (int bits)> &f) {
  if (field.padding) {
    for (int i = 0; i < 4; i++)
      if (static_cast<int>(field.padding) & (1 << i))
        f((1 << i) * 8);
    assert(!(field.padding & ~0xF));
  }
}

struct IPadding
{
  virtual void Execute(int bits) = 0;

  virtual ~IPadding() {}
};

#define PADDING_CALLBACK_BEGIN(NAME) \
  class Padding##NAME : public IPadding { \
  private: \
    std::string &code; \
    int &padding_id; \
  public: \
    Padding##NAME(std::string &code, int &padding_id) \
      : code(code) \
      , padding_id(padding_id) {} \
    virtual void Execute(int bits) OVERRIDE

#define PADDING_CALLBACK_END \
  }

#define GEN_PADDING_EXECUTE(NAME, FIELD) \
  Padding##NAME padding_##NAME(code, padding_id); \
  GenPadding(FIELD, \
    std::bind1st(std::mem_fun(&IPadding::Execute), &padding_##NAME))

// Generate an accessor struct with constructor for a flatbuffers struct.
static void GenStruct(const Parser &parser, StructDef &struct_def,
                      std::string *code_ptr) {
  if (struct_def.generated) return;
  std::string &code = *code_ptr;

  // Generate an accessor struct, with private variables of the form:
  // type name_;
  // Generates manual padding and alignment.
  // Variables are private because they contain little endian data on all
  // platforms.
  flatbuffers::GenComment(struct_def.doc_comment, code_ptr);
  code += "MANUALLY_ALIGNED_STRUCT(" + NumToString(struct_def.minalign) + ") ";
  code += struct_def.name + " FLATBUFFERS_FINAL_CLASS {\n private:\n";
  int padding_id = 0;

  PADDING_CALLBACK_BEGIN(IntPadding) {
    code += "  int" + flatbuffers::NumToString(bits) +
            "_t __padding" + flatbuffers::NumToString(padding_id++) + ";\n";
  } PADDING_CALLBACK_END;

  for (AUTO_VAR(it, struct_def.fields.vec.begin());
       it != struct_def.fields.vec.end();
       ++it) {
    AUTO_VAR(&field, **it);
    code += "  " + GenTypeGet(parser, field.value.type, " ", "", " ", false);
    code += field.name + "_;\n";

    GEN_PADDING_EXECUTE(IntPadding, field);
  }

  // Generate a constructor that takes all fields as arguments.
  code += "\n public:\n  " + struct_def.name + "(";
  for (AUTO_VAR(it, struct_def.fields.vec.begin());
       it != struct_def.fields.vec.end();
       ++it) {
    AUTO_VAR(&field, **it);
    if (it != struct_def.fields.vec.begin()) code += ", ";
    code += GenTypeGet(parser, field.value.type, " ", "const ", " &", true);
    code += field.name;
  }
  code += ")\n    : ";
  padding_id = 0;

  PADDING_CALLBACK_BEGIN(NextPadding) {
    (void)bits;
    code += ", __padding" + flatbuffers::NumToString(padding_id++) + "(0)";
  } PADDING_CALLBACK_END;

  for (AUTO_VAR(it, struct_def.fields.vec.begin());
       it != struct_def.fields.vec.end();
       ++it) {
    AUTO_VAR(&field, **it);
    if (it != struct_def.fields.vec.begin()) code += ", ";
    code += field.name + "_(";
    if (IsScalar(field.value.type.base_type)) {
      code += "flatbuffers::EndianScalar(";
      code += GenUnderlyingCast(parser, field, false, field.name);
      code += "))";
    } else {
      code += field.name + ")";
    }

    GEN_PADDING_EXECUTE(NextPadding, field);
  }
  code += " {";
  padding_id = 0;

  PADDING_CALLBACK_BEGIN(VoidPadding) {
    (void)bits;
    code += " (void)__padding" + flatbuffers::NumToString(padding_id++) + ";";
  } PADDING_CALLBACK_END;

  for (AUTO_VAR(it, struct_def.fields.vec.begin());
       it != struct_def.fields.vec.end();
       ++it) {
    AUTO_VAR(&field, **it);
    GEN_PADDING_EXECUTE(VoidPadding, field);
  }
  code += " }\n\n";

  // Generate accessor methods of the form:
  // type name() const { return flatbuffers::EndianScalar(name_); }
  for (AUTO_VAR(it, struct_def.fields.vec.begin());
       it != struct_def.fields.vec.end();
       ++it) {
    AUTO_VAR(&field, **it);
    flatbuffers::GenComment(field.doc_comment, code_ptr, "  ");
    code += "  " + GenTypeGet(parser, field.value.type, " ", "const ", " &",
                              true);
    code += field.name + "() const { return ";
    code += GenUnderlyingCast(parser, field, true,
      IsScalar(field.value.type.base_type)
        ? "flatbuffers::EndianScalar(" + field.name + "_)"
        : field.name + "_");
    code += "; }\n";
  }
  code += "};\nSTRUCT_END(" + struct_def.name + ", ";
  code += NumToString(struct_def.bytesize) + ");\n\n";
}

void GenerateNestedNameSpaces(Namespace *ns, std::string *code_ptr) {
  for (AUTO_VAR(it, ns->components.begin()); it != ns->components.end(); ++it) {
    *code_ptr += "namespace " + *it + " {\n";
  }
}

void CloseNestedNameSpaces(Namespace *ns, std::string *code_ptr) {
  for (AUTO_VAR(it, ns->components.rbegin()); it != ns->components.rend(); ++it) {
    *code_ptr += "}  // namespace " + *it + "\n";
  }
}

}  // namespace cpp

// Iterate through all definitions we haven't generate code for (enums, structs,
// and tables) and output them to a single file.
std::string GenerateCPP(const Parser &parser,
                        const std::string &file_name,
                        const GeneratorOptions &opts) {
  using namespace cpp;

  // Generate code for all the enum declarations.
  std::string enum_code, enum_code_post;
  for (AUTO_VAR(it, parser.enums_.vec.begin());
       it != parser.enums_.vec.end(); ++it) {
    GenEnum(parser, **it, &enum_code, &enum_code_post, opts);
  }

  // Generate forward declarations for all structs/tables, since they may
  // have circular references.
  std::string forward_decl_code_same_namespace;
  std::string forward_decl_code_other_namespace;
  Namespace *cur_name_space = nullptr;
  for (AUTO_VAR(it, parser.structs_.vec.begin());
       it != parser.structs_.vec.end(); ++it) {
    AUTO_VAR(&struct_def, **it);
    std::string decl = "struct " + struct_def.name + ";\n";
    if (struct_def.defined_namespace == parser.namespaces_.back()) {
      forward_decl_code_same_namespace += decl;
    } else {
      // Wrap this decl in the correct namespace. Only open a namespace if
      // the adjacent one is different.
      // TODO: this could be done more intelligently, by sorting to
      // namespace path and only opening/closing what is necessary, but that's
      // quite a bit more complexity.
      if (cur_name_space != struct_def.defined_namespace) {
        if (cur_name_space) {
          CloseNestedNameSpaces(cur_name_space,
                                &forward_decl_code_other_namespace);
        }
        GenerateNestedNameSpaces(struct_def.defined_namespace,
                                 &forward_decl_code_other_namespace);
        cur_name_space = struct_def.defined_namespace;
      }
      forward_decl_code_other_namespace += decl;
    }
  }
  if (cur_name_space) {
    CloseNestedNameSpaces(cur_name_space,
                          &forward_decl_code_other_namespace);
  }

  // Generate code for all structs, then all tables.
  std::string decl_code;
  for (AUTO_VAR(it, parser.structs_.vec.begin());
       it != parser.structs_.vec.end(); ++it) {
    if ((**it).fixed) GenStruct(parser, **it, &decl_code);
  }
  for (AUTO_VAR(it, parser.structs_.vec.begin());
       it != parser.structs_.vec.end(); ++it) {
    if (!(**it).fixed) GenTable(parser, **it, opts, &decl_code);
  }

  // Only output file-level code if there were any declarations.
  if (enum_code.length() || decl_code.length()) {
    std::string code;
    code = "// automatically generated by the FlatBuffers compiler,"
           " do not modify\n\n";

    // Generate include guard.
    std::string include_guard_ident = file_name;

    struct ToRemove
    {
      static bool Check(char c)
      {
        return !isalnum(c);
      }
    };
    // Remove any non-alpha-numeric characters that may appear in a filename.
    include_guard_ident.erase(
      std::remove_if(include_guard_ident.begin(),
                     include_guard_ident.end(),
                     &ToRemove::Check),
      include_guard_ident.end());
    std::string include_guard = "FLATBUFFERS_GENERATED_" + include_guard_ident;
    include_guard += "_";
    // For further uniqueness, also add the namespace.
    AUTO_VAR(name_space, parser.namespaces_.back());
    for (AUTO_VAR(it, name_space->components.begin());
             it != name_space->components.end(); ++it) {
      include_guard += *it + "_";
    }
    include_guard += "H_";
    std::transform(include_guard.begin(), include_guard.end(),
                   include_guard.begin(), ::toupper);
    code += "#ifndef " + include_guard + "\n";
    code += "#define " + include_guard + "\n\n";

    code += "#include \"flatbuffers/flatbuffers.h\"\n\n";

    if (opts.include_dependence_headers) {
      int num_includes = 0;
      for (AUTO_VAR(it, parser.included_files_.begin());
           it != parser.included_files_.end(); ++it) {
        std::string basename = flatbuffers::StripPath(
                          flatbuffers::StripExtension(it->first));
        if (basename != file_name) {
          code += "#include \"" + basename + "_generated.h\"\n";
          num_includes++;
        }
      }
      if (num_includes) code += "\n";
    }

    code += forward_decl_code_other_namespace;
    code += "\n";

    GenerateNestedNameSpaces(name_space, &code);
    code += "\n";

    code += forward_decl_code_same_namespace;
    code += "\n";

    // Output the main declaration code from above.
    code += enum_code;
    code += decl_code;
    code += enum_code_post;

    // Generate convenient global helper functions:
    if (parser.root_struct_def) {
      const std::string &name = parser.root_struct_def->name;
      // The root datatype accessor:
      code += "inline const " + name + " *Get";
      code += name;
      code += "(const void *buf) { return flatbuffers::GetRoot<";
      code += name + ">(buf); }\n\n";

      // The root verifier:
      code += "inline bool Verify";
      code += name;
      code += "Buffer(flatbuffers::Verifier &verifier) { "
              "return verifier.VerifyBuffer<";
      code += name + ">(); }\n\n";

      if (parser.file_identifier_.length()) {
        // Return the identifier
        code += "inline const char *" + name;
        code += "Identifier() { return \"" + parser.file_identifier_;
        code += "\"; }\n\n";

        // Check if a buffer has the identifier.
        code += "inline bool " + name;
        code += "BufferHasIdentifier(const void *buf) { return flatbuffers::";
        code += "BufferHasIdentifier(buf, ";
        code += name + "Identifier()); }\n\n";
      }

      // Finish a buffer with a given root object:
      code += "inline void Finish" + name;
      code += "Buffer(flatbuffers::FlatBufferBuilder &fbb, flatbuffers::Offset<";
      code += name + "> root) { fbb.Finish(root";
      if (parser.file_identifier_.length())
        code += ", " + name + "Identifier()";
      code += "); }\n\n";

    }

    CloseNestedNameSpaces(name_space, &code);

    // Close the include guard.
    code += "\n#endif  // " + include_guard + "\n";

    return code;
  }

  return std::string();
}

static std::string GeneratedFileName(const std::string &path,
                                     const std::string &file_name) {
  return path + file_name + "_generated.h";
}

bool GenerateCPP(const Parser &parser,
                 const std::string &path,
                 const std::string &file_name,
                 const GeneratorOptions &opts) {
    std::string code = GenerateCPP(parser, file_name, opts);
    return !code.length() ||
           SaveFile(GeneratedFileName(path, file_name).c_str(), code, false);
}

std::string CPPMakeRule(const Parser &parser,
                        const std::string &path,
                        const std::string &file_name,
                        const GeneratorOptions & /*opts*/) {
  std::string filebase = flatbuffers::StripPath(
      flatbuffers::StripExtension(file_name));
  std::string make_rule = GeneratedFileName(path, filebase) + ": ";
  AUTO_VAR(included_files, parser.GetIncludedFilesRecursive(file_name));
  for (AUTO_VAR(it, included_files.begin());
       it != included_files.end(); ++it) {
    make_rule += " " + *it;
  }
  return make_rule;
}

}  // namespace flatbuffers


text:
import { IModel, IFacile, IErrors } from '../interfaces';
import { LoggerInstance } from 'winston';
/**
 * Base Model Class
 *
 * @export
 * @class Model
 */
export declare class Model implements IModel {
    protected facile: IFacile;
    static type: string;
    /**
     * Creates an instance of Model.
     *
     * @param {IFacile} facile
     * @constructor
     * @memberOf Model
     */
    constructor(facile: IFacile);
    /**
     * log
     *
     * @desc exposes Facile.log to class.
     * @readonly
     * @member {LoggerInstance} log
     * @memberOf Service
     */
    readonly log: LoggerInstance;
    /**
     * errros
     *
     * @desc exposes Facile.errors to class.
     * @readonly
     * @member {IErrors}
     * @memberOf Controller
     */
    readonly errors: IErrors;
    /**
     * init
     *
     * @desc initializes the model.
     * @method init
     * @memberOf Model
     */
    init(): void;
    /**
     * service
     *
     * @method service
     * @template T
     * @param {string} name
     * @returns {T}
     *
     * @memberOf Service
     */
    service<T>(name: string): T;
    /**
     * model
     *
     * @method model
     * @template T
     * @param {string} name
     * @returns {T}
     *
     * @memberOf Service
     */
    model<T>(name: string): T;
}

redpajama_set_name: RedPajamaGithub


text:
import Ember from 'ember';
import ENV from '../config/environment';
import IntlService from '../services/intl';
import { addLocaleData } from 'ember-intl/utils/data';
import FormatDate from '../helpers/format-date';
import FormatTime from '../helpers/format-time';
import FormatRelative from '../helpers/format-relative';
import FormatNumber from '../helpers/format-number';
import FormatHtmlMessage from '../helpers/format-html-message';
import FormatMessage from '../helpers/format-message';

export var registerIntl = function (container) {
    var seen   = requirejs._eak_seen;
    var prefix = ENV.modulePrefix;

    container.optionsForType('formats', {
        singleton:   true,
        instantiate: false
    });

    container.optionsForType('locale', {
        singleton:   true,
        instantiate: true
    });

    Object.keys(seen).filter(function (key) {
        return key.indexOf(prefix + '\/cldrs\/') === 0;
    }).forEach(function (key) {
        addLocaleData(require(key, null, null, true)['default']);
    });

    if (Ember.HTMLBars) {
        Ember.HTMLBars._registerHelper('format-date', FormatDate);
        Ember.HTMLBars._registerHelper('format-time', FormatTime);
        Ember.HTMLBars._registerHelper('format-relative', FormatRelative);
        Ember.HTMLBars._registerHelper('format-number', FormatNumber);
        Ember.HTMLBars._registerHelper('format-html-message', FormatHtmlMessage);
        Ember.HTMLBars._registerHelper('format-message', FormatMessage);
    }

    // only here for backwards compat.
    container.register('intl:main', container.lookup('service:intl'), {
        instantiate: false,
        singleton:   true
    });

    container.typeInjection('controller', 'intl', 'service:intl');
    container.typeInjection('component',  'intl', 'service:intl');
    container.typeInjection('route',      'intl', 'service:intl');
    container.typeInjection('model',      'intl', 'service:intl');
    container.typeInjection('view',       'intl', 'service:intl');
    container.typeInjection('formatter',  'intl', 'service:intl');
};

export default {
    name: 'ember-intl',

    initialize: function (container, app) {
        registerIntl(container);
        app.intl = container.lookup('service:intl');
    }
};


text:
set -o errexit
set -o nounset
set -o xtrace

drive="/dev/sda"
partn="${drive}2"

parted -s ${drive} "mklabel gpt"
parted -s ${drive} "mkpart primary ext2 1 2"
parted -s ${drive} "set 1 bios_grub on"
parted -s ${drive} "mkpart primary ext4 2 100%"
mkfs.ext4 -L nixos ${partn}
mount ${partn} /mnt
nixos-generate-config --root /mnt
mv /tmp/configuration.nix /mnt/etc/nixos/configuration.nix
mv /tmp/vagrant-networks.nix /mnt/etc/nixos/vagrant-networks.nix
nixos-install


text:
module Awspec::Type
  class Elb < Base
    def initialize(id)
      super
      @resource = find_elb(id)
      @id = @resource[:load_balancer_name] if @resource
    end

    health_check_options = %w(
      target interval timeout
      unhealthy_threshold healthy_threshold
    )

    health_check_options.each do |option|
      define_method 'health_check_' + option do
        @resource[:health_check][option]
      end
    end

    def has_ec2?(id)
      ec2 = find_ec2(id)
      @resource.instances.find do |instance|
        instance.instance_id = ec2.instance_id
      end if ec2
    end

    def has_security_group?(sg_id)
      sgs = @resource[:security_groups]
      ret = sgs.find do |sg|
        sg == sg_id
      end
      return true if ret
      sg2 = find_security_group(sg_id)
      return false unless sg2.tag_name == sg_id || sg2[:group_name] == sg_id
      sgs.find do |sg|
        sg == sg2[:group_name]
      end
    end

    def has_subnet?(subnet_id)
      subnets = @resource[:subnets]
      ret = subnets.find do |s|
        s == subnet_id
      end
      return true if ret
      res = find_subnet(subnet_id)
      ret = subnets.find do |s|
        s == res[:subnet_id]
      end
    end

    def has_listener?(protocol:, port:, instance_protocol:, instance_port:)
      @resource[:listener_descriptions].find do |desc|
        listener = desc.listener
        listener.protocol == protocol && listener.load_balancer_port == port && \
          listener.instance_protocol == instance_protocol && listener.instance_port == instance_port
      end
    end
  end
end


text:
using System.ComponentModel.DataAnnotations;

namespace GigHub.Core.ViewModels
{
    public class ForgotPasswordViewModel
    {
        [Required]
        [EmailAddress]
        [Display(Name = "Email")]
        public string Email { get; set; }
    }
}


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
		<title>Flywheel Adapt</title>
		<link rel="stylesheet" href="/test/assets/css/adapt-test.css">

Flywheel Adapt Testing

			@@include( 'devices.html' )
			@@include( 'grid.html' )
			@@include( 'transforms.html' )
			@@include( 'clearfix.html' )
			@@include( 'backgrounds.html' )
			@@include( 'filters.html' )
			@@include( 'positioning.html' )
			@@include( 'sizing.html' )
			@@include( 'forms.html' )


text:
#ifndef REQUEST_PARSER_H
#define REQUEST_PARSER_H

#include "BasicDatastructures.h"

#include <boost/logic/tribool.hpp>
#include <boost/tuple/tuple.hpp>

namespace http {

class RequestParser {
public:
    RequestParser() : state_(method_start) { }
    void Reset() { state_ = method_start; }

    boost::tuple<boost::tribool, char*> Parse(Request& req, char* begin, char* end, CompressionType * compressionType) {
        while (begin != end) {
            boost::tribool result = consume(req, *begin++, compressionType);
            if (result || !result){
                return boost::make_tuple(result, begin);
            }
        }
        boost::tribool result = boost::indeterminate;
        return boost::make_tuple(result, begin);
    }

private:
    boost::tribool consume(Request& req, char input, CompressionType * compressionType) {
        switch (state_) {
        case method_start:
            if (!isChar(input) || isCTL(input) || isTSpecial(input)) {
                return false;
            } else {
                state_ = method;
                return boost::indeterminate;
            }
        case method:
            if (input == ' ') {
                state_ = uri;
                return boost::indeterminate;
            } else if (!isChar(input) || isCTL(input) || isTSpecial(input)) {
                return false;
            } else {
                return boost::indeterminate;
            }
        case uri_start:
            if (isCTL(input)) {
                return false;
            } else {
                state_ = uri;
                req.uri.push_back(input);
                return boost::indeterminate;
            }
        case uri:
            if (input == ' ') {
                state_ = http_version_h;
                return boost::indeterminate;
            } else if (isCTL(input)) {
                return false;
            } else {
                req.uri.push_back(input);
                return boost::indeterminate;
            }
        case http_version_h:
            if (input == 'H') {
                state_ = http_version_t_1;
                return boost::indeterminate;
            } else {
                return false;
            }
        case http_version_t_1:
            if (input == 'T') {
                state_ = http_version_t_2;
                return boost::indeterminate;
            } else {
                return false;
            }
        case http_version_t_2:
            if (input == 'T') {
                state_ = http_version_p;
                return boost::indeterminate;
            } else {
                return false;
            }
        case http_version_p:
            if (input == 'P') {
                state_ = http_version_slash;
                return boost::indeterminate;
            } else {
                return false;
            }
        case http_version_slash:
            if (input == '/') {
                state_ = http_version_major_start;
                return boost::indeterminate;
            } else {
                return false;
            }
        case http_version_major_start:
            if (isDigit(input)) {
                state_ = http_version_major;
                return boost::indeterminate;
            } else {
                return false;
            }
        case http_version_major:
            if (input == '.') {
                state_ = http_version_minor_start;
                return boost::indeterminate;
            } else if (isDigit(input)) {
                return boost::indeterminate;
            } else {
                return false;
            }
        case http_version_minor_start:
            if (isDigit(input)) {
                state_ = http_version_minor;
                return boost::indeterminate;
            } else {
                return false;
            }
        case http_version_minor:
            if (input == '\r') {
                state_ = expecting_newline_1;
                return boost::indeterminate;
            } else if (isDigit(input)) {
                return boost::indeterminate;
            }
            else {
                return false;
            }
        case expecting_newline_1:
            if (input == '\n') {
                state_ = header_line_start;
                return boost::indeterminate;
            } else {
                return false;
            }
        case header_line_start:
            if(header.name == "Accept-Encoding") {
                /* giving gzip precedence over deflate */
                if(header.value.find("deflate") != std::string::npos)
                    *compressionType = deflateRFC1951;
                if(header.value.find("gzip") != std::string::npos)
                    *compressionType = gzipRFC1952;
            }

            if("Referer" == header.name)
                req.referrer = header.value;

            if("User-Agent" == header.name)
                req.agent = header.value;

            if (input == '\r') {
                state_ = expecting_newline_3;
                return boost::indeterminate;
            } else if (!isChar(input) || isCTL(input) || isTSpecial(input)) {
                return false;
            } else {
                state_ = header_name;
                header.Clear();
                header.name.push_back(input);
                return boost::indeterminate;
            }
        case header_lws:
            if (input == '\r') {
                state_ = expecting_newline_2;
                return boost::indeterminate;
            } else if (input == ' ' || input == '\t') {
                return boost::indeterminate;
            }
            else if (isCTL(input)) {
                return false;
            } else {
                state_ = header_value;
                return boost::indeterminate;
            }
        case header_name:
            if (input == ':') {
                state_ = space_before_header_value;
                return boost::indeterminate;
            } else if (!isChar(input) || isCTL(input) || isTSpecial(input)) {
                return false;
            } else {
                header.name.push_back(input);
                return boost::indeterminate;
            }
        case space_before_header_value:
            if (input == ' ') {
                state_ = header_value;
                return boost::indeterminate;
            } else {
                return false;
            }
        case header_value:
            if (input == '\r') {
                state_ = expecting_newline_2;
                return boost::indeterminate;
            } else if (isCTL(input)) {
                return false;
            } else {
                header.value.push_back(input);
                return boost::indeterminate;
            }
        case expecting_newline_2:
            if (input == '\n') {
                state_ = header_line_start;
                return boost::indeterminate;
            } else {
                return false;
            }
        case expecting_newline_3:
            return (input == '\n');
        default:
            return false;
        }
    }

    inline bool isChar(int c) {
        return c >= 0 && c <= 127;
    }

    inline bool isCTL(int c) {
        return (c >= 0 && c <= 31) || (c == 127);
    }

    inline bool isTSpecial(int c) {
        switch (c) {
        case '(': case ')': case '<': case '>': case '@':
        case ',': case ';': case ':': case '\\': case '"':
        case '/': case '[': case ']': case '?': case '=':
        case '{': case '}': case ' ': case '\t':
            return true;
        default:
            return false;
        }
    }

    inline bool isDigit(int c) {
        return c >= '0' && c <= '9';
    }

    enum state {
        method_start,
        method,
        uri_start,
        uri,
        http_version_h,
        http_version_t_1,
        http_version_t_2,
        http_version_p,
        http_version_slash,
        http_version_major_start,
        http_version_major,
        http_version_minor_start,
        http_version_minor,
        expecting_newline_1,
        header_line_start,
        header_lws,
        header_name,
        space_before_header_value,
        header_value,
        expecting_newline_2,
        expecting_newline_3
    } state_;

    Header header;
};

} // namespace http

#endif // REQUEST_PARSER_H


text:
#ifndef AERON_AGENT_H
#define AERON_AGENT_H

#include "concurrent/aeron_thread.h"
#include "aeron_common.h"
#include "concurrent/aeron_atomic.h"
#include "aeronc.h"

typedef int (*aeron_agent_do_work_func_t)(void *);

typedef void (*aeron_agent_on_close_func_t)(void *);

#define AERON_AGENT_STATE_UNUSED 0
#define AERON_AGENT_STATE_INITED 1
#define AERON_AGENT_STATE_STARTED 2
#define AERON_AGENT_STATE_MANUAL 3
#define AERON_AGENT_STATE_STOPPING 4
#define AERON_AGENT_STATE_STOPPED 5

typedef struct aeron_idle_strategy_stct
{
    aeron_idle_strategy_func_t idle;
    aeron_idle_strategy_init_func_t init;
}
aeron_idle_strategy_t;

#define AERON_IDLE_STRATEGY_BACKOFF_MAX_SPINS (10)
#define AERON_IDLE_STRATEGY_BACKOFF_MAX_YIELDS (20)
#define AERON_IDLE_STRATEGY_BACKOFF_MIN_PARK_PERIOD_NS (1000LL)
#define AERON_IDLE_STRATEGY_BACKOFF_MAX_PARK_PERIOD_NS (1 * 1000 * 1000LL)

void aeron_idle_strategy_sleeping_idle(void *state, int work_count);

void aeron_idle_strategy_yielding_idle(void *state, int work_count);

void aeron_idle_strategy_busy_spinning_idle(void *state, int work_count);

void aeron_idle_strategy_noop_idle(void *state, int work_count);

void aeron_idle_strategy_backoff_idle(void *state, int work_count);

int aeron_idle_strategy_backoff_state_init(
    void **state, uint64_t max_spins, uint64_t max_yields, uint64_t min_park_period_ns, uint64_t max_park_period_ns);

int aeron_idle_strategy_init_null(void **state, const char *env_var, const char *load_args);

typedef struct aeron_agent_runner_stct
{
    const char *role_name;
    void *agent_state;
    void *idle_strategy_state;
    void *on_start_state;
    aeron_agent_on_start_func_t on_start;
    aeron_agent_do_work_func_t do_work;
    aeron_agent_on_close_func_t on_close;
    aeron_idle_strategy_func_t idle_strategy;
    aeron_thread_t thread;
    volatile bool running;
    uint8_t state;
}
aeron_agent_runner_t;

aeron_idle_strategy_func_t aeron_idle_strategy_load(
    const char *idle_strategy_name,
    void **idle_strategy_state,
    const char *env_var,
    const char *load_args);

aeron_agent_on_start_func_t aeron_agent_on_start_load(const char *name);

int aeron_agent_init(
    aeron_agent_runner_t *runner,
    const char *role_name,
    void *state,
    aeron_agent_on_start_func_t on_start,
    void *on_start_state,
    aeron_agent_do_work_func_t do_work,
    aeron_agent_on_close_func_t on_close,
    aeron_idle_strategy_func_t idle_strategy_func,
    void *idle_strategy_state);

int aeron_agent_start(aeron_agent_runner_t *runner);

inline int aeron_agent_do_work(aeron_agent_runner_t *runner)
{
    return runner->do_work(runner->agent_state);
}

inline bool aeron_agent_is_running(aeron_agent_runner_t *runner)
{
    bool running;
    AERON_GET_VOLATILE(running, runner->running);
    return running;
}

inline void aeron_agent_idle(aeron_agent_runner_t *runner, int work_count)
{
    runner->idle_strategy(runner->idle_strategy_state, work_count);
}

int aeron_agent_stop(aeron_agent_runner_t *runner);

int aeron_agent_close(aeron_agent_runner_t *runner);

#endif //AERON_AGENT_H


text:
using Neo.Cryptography;
using Neo.IO;
using System;
using System.IO;

namespace Neo.SmartContract
{
    /// <summary>
    /// +------------+-----------+------------------------------------------------------------+
    /// |   Field    |  Length   |                          Comment                           |
    /// +------------+-----------+------------------------------------------------------------+
    /// | Magic      | 4 bytes   | Magic header                                               |
    /// | Compiler   | 32 bytes  | Compiler used                                              |
    /// | Version    | 16 bytes  | Compiler version (Mayor, Minor, Build, Version)            |
    /// | ScriptHash | 20 bytes  | ScriptHash for the script                                  |
    /// +------------+-----------+------------------------------------------------------------+
    /// | Checksum   | 4 bytes   | Sha256 of the header (CRC)                                 |
    /// +------------+-----------+------------------------------------------------------------+
    /// | Script     | Var bytes | Var bytes for the payload                                  |
    /// +------------+-----------+------------------------------------------------------------+
    /// </summary>
    public class NefFile : ISerializable
    {
        /// <summary>
        /// NEO Executable Format 3 (NEF3)
        /// </summary>
        private const uint Magic = 0x3346454E;

        /// <summary>
        /// Compiler
        /// </summary>
        public string Compiler { get; set; }

        /// <summary>
        /// Version
        /// </summary>
        public Version Version { get; set; }

        /// <summary>
        /// Script Hash
        /// </summary>
        public UInt160 ScriptHash { get; set; }

        /// <summary>
        /// Checksum
        /// </summary>
        public uint CheckSum { get; set; }

        /// <summary>
        /// Script
        /// </summary>
        public byte[] Script { get; set; }

        private const int HeaderSize =
            sizeof(uint) +              // Magic
            32 +                        // Compiler
            (sizeof(int) * 4) +         // Version
            UInt160.Length +            // ScriptHash
            sizeof(uint);               // Checksum

        public int Size =>
            HeaderSize +              // Header
            Script.GetVarSize();      // Script

        public void Serialize(BinaryWriter writer)
        {
            writer.Write(Magic);
            writer.WriteFixedString(Compiler, 32);

            // Version
            writer.Write(Version.Major);
            writer.Write(Version.Minor);
            writer.Write(Version.Build);
            writer.Write(Version.Revision);

            writer.Write(ScriptHash);
            writer.Write(CheckSum);
            writer.WriteVarBytes(Script ?? new byte[0]);
        }

        public void Deserialize(BinaryReader reader)
        {
            if (reader.ReadUInt32() != Magic)
            {
                throw new FormatException("Wrong magic");
            }

            Compiler = reader.ReadFixedString(32);
            Version = new Version(reader.ReadInt32(), reader.ReadInt32(), reader.ReadInt32(), reader.ReadInt32());
            ScriptHash = reader.ReadSerializable<UInt160>();
            CheckSum = reader.ReadUInt32();

            if (CheckSum != ComputeChecksum(this))
            {
                throw new FormatException("CRC verification fail");
            }

            Script = reader.ReadVarBytes(1024 * 1024);

            if (Script.ToScriptHash() != ScriptHash)
            {
                throw new FormatException("ScriptHash is different");
            }
        }

        /// <summary>
        /// Compute checksum for a file
        /// </summary>
        /// <param name="file">File</param>
        /// <returns>Return checksum</returns>
        public static uint ComputeChecksum(NefFile file)
        {
            using (var ms = new MemoryStream())
            using (var wr = new BinaryWriter(ms))
            {
                file.Serialize(wr);
                wr.Flush();

                // Read header without CRC

                var buffer = new byte[HeaderSize - sizeof(uint)];
                ms.Seek(0, SeekOrigin.Begin);
                ms.Read(buffer, 0, buffer.Length);

                return BitConverter.ToUInt32(buffer.Sha256(), 0);
            }
        }
    }
}


text:
<?xml version="1.0"?>
<!--
  This software was produced for the U. S. Government
  under Contract No. W15P7T-11-C-F600, and is
  subject to the Rights in Noncommercial Computer Software
  and Noncommercial Computer Software Documentation
  Clause 252.227-7014 (JUN 1995)

  Copyright 2013 The MITRE Corporation. All Rights Reserved.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
  -->

<!DOCTYPE module PUBLIC
    "-//Puppy Crawl//DTD Check Configuration 1.3//EN"
    "http://www.puppycrawl.com/dtds/configuration_1_3.dtd">

<!--

  Checkstyle configuration that checks for some fairly minimal conventions. Some
    coding convention sources this is partially borrowed from are:

    - the Java Language Specification at
      http://java.sun.com/docs/books/jls/second_edition/html/index.html

    - the Sun Code Conventions at http://java.sun.com/docs/codeconv/

    - the Javadoc guidelines at
      http://java.sun.com/j2se/javadoc/writingdoccomments/index.html

    - the JDK Api documentation http://java.sun.com/j2se/docs/api/index.html

    - some best practices

  Checkstyle is very configurable. Be sure to read the documentation at
  http://checkstyle.sf.net (or in your downloaded distribution).

  Most Checks are configurable, be sure to consult the documentation.

  To completely disable a check, just comment it out or delete it from the file.

  Finally, it is worth reading the documentation.

-->

<module name="Checker">
  <property name="severity" value="warning"/>

  <!--
      If you set the basedir property below, then all reported file
      names will be relative to the specified directory. See
      http://checkstyle.sourceforge.net/5.x/config.html#Checker
  -->
  <!--<property name="basedir" value="${basedir}"/>-->

  <module name="SuppressionFilter">
    <property name="file" value="${checkstyle.suppressions.file}" default="checkstyle-suppressions.xml"/>
  </module>

  <!-- http://checkstyle.sourceforge.net/config_duplicates.html -->
  <module name="StrictDuplicateCode">
    <property name="min" value="15"/>
  </module>
  <!-- http://www.harukizaemon.com/simian/installation.html#checkstyle -->
  <!--<module name="au.com.redhillconsulting.simian.SimianCheck">-->
    <!--<property name="threshold" value="6"/>-->
  <!--</module>-->

  <!-- Checks that a package-info.java file exists for each package.     -->
  <!-- See http://checkstyle.sf.net/config_javadoc.html#JavadocPackage -->
  <!--<module name="JavadocPackage"/>-->

  <!-- Checks whether files end with a new line.                        -->
  <!-- See http://checkstyle.sf.net/config_misc.html#NewlineAtEndOfFile -->
  <!--<module name="NewlineAtEndOfFile"/>-->

  <!-- Checks that property files contain the same keys.         -->
  <!-- See http://checkstyle.sf.net/config_misc.html#Translation -->
  <module name="Translation"/>

  <!-- Checks for Size Violations.                    -->
  <!-- See http://checkstyle.sf.net/config_sizes.html -->
  <module name="FileLength"/>

  <!-- Checks for whitespace                               -->
  <!-- See http://checkstyle.sf.net/config_whitespace.html -->
  <module name="FileTabCharacter">
    <property name="severity" value="error"/>
  </module>

  <!-- Miscellaneous other checks.                   -->
  <!-- See http://checkstyle.sf.net/config_misc.html -->
  <module name="RegexpSingleline">
    <property name="format" value="\s+$"/>
    <property name="minimum" value="0"/>
    <property name="maximum" value="0"/>
    <property name="message" value="Line has trailing spaces."/>
  </module>

  <!-- Checks for Headers                                -->
  <!-- See http://checkstyle.sf.net/config_header.html   -->
  <!-- <module name="Header"> -->
  <!--   <property name="headerFile" value="${checkstyle.header.file}"/> -->
  <!--   <property name="fileExtensions" value="java"/> -->
  <!-- </module> -->

  <module name="TreeWalker">
    <property name="tabWidth" value="${checkstyle.indentChars}" default="2"/>

    <!-- Commented because a little too noisy; ideally there would be a throwsIndent option -->
    <!--<module name="Indentation">-->
      <!--<property name="severity" value="warning"/>-->
      <!--<property name="basicOffset" value="${checkstyle.indentChars}" default="2"/>-->
      <!--<property name="caseIndent" value="${checkstyle.indentChars}" default="2"/>-->
      <!--<!– https://sourceforge.net/p/checkstyle/patches/226/-->
          <!--and https://github.com/maikelsteneker/checkstyle-throwsIndent –>-->
      <!--<!–<property name="throwsIndent" value="${checkstyle.indentCharsThrows}" default="4"/>–>-->
    <!--</module>-->

    <!-- http://checkstyle.sourceforge.net/config_annotation.html -->
    <module name="MissingOverride"/>

    <!-- http://checkstyle.sourceforge.net/config_coding.html -->
    <module name="CovariantEquals"/>
    <module name="EqualsHashCode"/>

    <!-- Checks for Javadoc comments.                     -->
    <!-- See http://checkstyle.sf.net/config_javadoc.html -->
    <!--<module name="JavadocMethod"/>-->
    <!--<module name="JavadocType"/>-->
    <!--<module name="JavadocVariable"/>-->
    <!--<module name="JavadocStyle"/>-->

    <!-- Checks for Naming Conventions.                  -->
    <!-- See http://checkstyle.sf.net/config_naming.html -->
    <module name="ClassTypeParameterName">
      <property name="severity" value="error"/>
    </module>
    <!-- As per Sun convention except also allowing "logger"  or "log"
         since some people don't like references to "LOGGER" shouting out all
         over their code -->
    <module name="ConstantName">
      <property name="severity" value="warning"/><!-- TODO temporary -->
      <property name="format" value="^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$|^log(ger)?$"/>
    </module>
    <module name="LocalFinalVariableName">
    </module>
    <module name="LocalVariableName">
    </module>
    <module name="MemberName">
      <property name="severity" value="error"/>
    </module>
    <module name="MethodName">
      <property name="severity" value="error"/>
    </module>
    <module name="MethodTypeParameterName">
      <property name="severity" value="error"/>
    </module>
    <module name="PackageName">
      <property name="severity" value="error"/>
    </module>
    <module name="ParameterName">
      <property name="severity" value="warning"/><!-- TODO temporary -->
    </module>
    <module name="StaticVariableName">
      <property name="severity" value="warning"/><!-- TODO temporary -->
    </module>
    <module name="TypeName">
      <property name="severity" value="error"/>
    </module>

    <!-- Checks for imports                              -->
    <!-- See http://checkstyle.sf.net/config_import.html -->
    <!--<module name="AvoidStarImport"/>-->
    <module name="IllegalImport"/> <!-- defaults to sun.* packages -->
    <module name="RedundantImport"/>
    <module name="UnusedImports">
      <property name="processJavadoc" value="true" />
    </module>

    <!-- Checks for Size Violations.                    -->
    <!-- See http://checkstyle.sf.net/config_sizes.html -->
    <module name="LineLength">
      <property name="max" value="120"/>
      <property name="ignorePattern" value="^import " />
    </module>
    <module name="MethodLength"/>
    <module name="ParameterNumber"/>

    <!-- Checks for whitespace                               -->
    <!-- See http://checkstyle.sf.net/config_whitespace.html -->
    <!--<module name="EmptyForIteratorPad"/>-->
    <!--<module name="GenericWhitespace"/>-->
    <!--<module name="MethodParamPad"/>-->
    <!--<module name="NoWhitespaceAfter"/>-->
    <!--<module name="NoWhitespaceBefore"/>-->
    <!--<module name="OperatorWrap"/>-->
    <!--<module name="ParenPad"/>-->
    <!--<module name="TypecastParenPad"/>-->
    <!--<module name="WhitespaceAfter"/>--><!-- TODO customize -->
    <!--<module name="WhitespaceAround"/>-->

    <!-- Modifier Checks                                    -->
    <!-- See http://checkstyle.sf.net/config_modifiers.html -->
    <module name="ModifierOrder"/>
    <!--<module name="RedundantModifier"/>-->

    <!-- Checks for blocks. You know, those {}'s         -->
    <!-- See http://checkstyle.sf.net/config_blocks.html -->
    <!--<module name="AvoidNestedBlocks"/>-->
    <module name="EmptyBlock">
      <property name="severity" value="error" />
      <property name="option" value="text" /><!-- at least include a comment -->
    </module>
    <module name="LeftCurly"/>
    <!--<module name="NeedBraces"/>-->
    <module name="RightCurly"/>

    <!-- Checks for class design                         -->
    <!-- See http://checkstyle.sf.net/config_design.html -->
    <!--<module name="DesignForExtension"/>-->
    <!--<module name="FinalClass"/>-->
    <module name="HideUtilityClassConstructor"/>
    <!--<module name="InterfaceIsType"/>-->
    <!--<module name="VisibilityModifier"/>-->

    <!-- Miscellaneous other checks.                   -->
    <!-- See http://checkstyle.sf.net/config_misc.html -->
    <module name="ArrayTypeStyle">
      <property name="severity" value="error" />
    </module>
    <!--<module name="FinalParameters"/>-->
    <!--<module name="TodoComment"/>-->
    <module name="UpperEll">
      <property name="severity" value="error" />
    </module>
    <module name="OuterTypeFilename">
      <property name="severity" value="error" />
    </module>

  </module>

</module>


text:
import { BoxPlot } from "../../";

export = BoxPlot;


text:
require 'view/component_helper'

module View
  class Railtie < Rails::Railtie
    initializer 'extend ActionView' do

      ActiveSupport.on_load(:action_view) do
        self.class_eval do
          include View::ComponentHelper
        end
      end

      View::Component.send :include, View::ViewHelpers
    end
  end
end


text:
using namespace impala_udf;

namespace impala {

class Expr;
class OpcodeRegistry;
class TupleRow;

class StringFunctions {
 public:
  static StringVal Substring(FunctionContext*, const StringVal& str, const BigIntVal& pos,
                             const BigIntVal& len);
  static StringVal Substring(FunctionContext*, const StringVal& str, const BigIntVal& pos);
  static StringVal Left(FunctionContext*, const StringVal& str, const BigIntVal& len);
  static StringVal Right(FunctionContext*, const StringVal& str, const BigIntVal& len);
  static StringVal Space(FunctionContext*, const BigIntVal& len);
  static StringVal Repeat(FunctionContext*, const StringVal& str, const BigIntVal& n);
  static StringVal Lpad(FunctionContext*, const StringVal& str, const BigIntVal& len,
                        const StringVal& pad);
  static StringVal Rpad(FunctionContext*, const StringVal& str, const BigIntVal&,
                        const StringVal& pad);
  static IntVal Length(FunctionContext*, const StringVal& str);
  static IntVal CharLength(FunctionContext*, const StringVal& str);
  static StringVal Lower(FunctionContext*, const StringVal& str);
  static StringVal Upper(FunctionContext*, const StringVal& str);
  static StringVal InitCap(FunctionContext*, const StringVal& str);
  static StringVal Reverse(FunctionContext*, const StringVal& str);
  static StringVal Translate(FunctionContext*, const StringVal& str, const StringVal& src,
                             const StringVal& dst);
  static StringVal Trim(FunctionContext*, const StringVal& str);
  static StringVal Ltrim(FunctionContext*, const StringVal& str);
  static StringVal Rtrim(FunctionContext*, const StringVal& str);
  static IntVal Ascii(FunctionContext*, const StringVal& str);
  static IntVal Instr(FunctionContext*, const StringVal& str, const StringVal& substr);
  static IntVal Locate(FunctionContext*, const StringVal& substr, const StringVal& str);
  static IntVal LocatePos(FunctionContext*, const StringVal& substr, const StringVal& str,
                          const BigIntVal& start_pos);

  static void RegexpPrepare(FunctionContext*, FunctionContext::FunctionStateScope);
  static void RegexpClose(FunctionContext*, FunctionContext::FunctionStateScope);
  static StringVal RegexpExtract(FunctionContext*, const StringVal& str,
                                 const StringVal& pattern, const BigIntVal& index);
  static StringVal RegexpReplace(FunctionContext*, const StringVal& str,
                                 const StringVal& pattern, const StringVal& replace);

  static StringVal Concat(FunctionContext*, int num_children, const StringVal* strs);
  static StringVal ConcatWs(FunctionContext*, const StringVal& sep, int num_children,
                            const StringVal* strs);
  static IntVal FindInSet(FunctionContext*, const StringVal& str,
                          const StringVal& str_set);

  static void ParseUrlPrepare(FunctionContext*, FunctionContext::FunctionStateScope);
  static StringVal ParseUrl(FunctionContext*, const StringVal& url, const StringVal& part);
  static StringVal ParseUrlKey(FunctionContext*, const StringVal& url,
                               const StringVal& key, const StringVal& part);
  static void ParseUrlClose(FunctionContext*, FunctionContext::FunctionStateScope);

  /// Converts ASCII 'val' to corresponding character.
  static StringVal Chr(FunctionContext* context, const IntVal& val);

  static void BTrimPrepare(FunctionContext*, FunctionContext::FunctionStateScope);
  static void BTrimClose(FunctionContext*, FunctionContext::FunctionStateScope);

  /// Trims occurrences of the characters in 'chars_to_trim' string from
  /// both ends of string 'str'.
  static StringVal BTrimString(FunctionContext* ctx, const StringVal& str,
    const StringVal& chars_to_trim);
};
}
#endif


text:
Huge solution: redux-form or react-redux-form or whatever that
contains "redux" and "form". Downside: the JS bundle is getting
bigger for only a fraction of features you use.

Standard solution: use component state!

```javascript
class LoginForm extends React.Component {
  constructor(...args) {
    super(...args);
    this.state = {
      username: '',
      password: '',
    };
  }

  handleChangeUsername(event) {
    this.setState(() => ({ username: event.target.value }));
  }

  handleChangePassword(event) {
    this.setState(() => ({ password: event.target.value }));
  }

  handleSubmitLoginForm(event) {
    event.preventDefault();

    authenticateUser(this.state.username, this.state.password);
  }

  render() {
    return (
      <form onSubmit={this.handleSubmitLoginForm.bind(this)}>
        <input type="text" onChange={this.handleChangeUsername.bind(this)} />
        <input type="password" onChange={this.handleChangePassword.bind(this)} />
      </form>
    );
  }
}
```

Lean solution: no state (and uncontrolled inputs)!

```javascript
class LoginForm extends React.Component {
  handleSubmitLoginForm(event) {
    event.preventDefault();

    const username = event.target.username.value;
    const password = event.target.password.value;

    authenticateUser(this.state.username, this.state.password);
  }

  render() {
    return (
      <form onSubmit={this.handleSubmitLoginForm.bind(this)}>
        <input type="text" name="username" />
        <input type="password" name="password" />
      </form>
    );
  }
}
```

Reference via element's `name` attribute from submit handler has
been in browser API for ages. There's no need to substitute it
with extra layer of abstraction, putting extra work into it.

Of course it only works for browser-specific elements like text
inputs, checkboxes, and file pickers. It doesn't work for highly
customized input components like 2D-sliders or date range
pickers. I wouldn't even recommend trying to substitute state
management with hidden fields in this case. Just because it's
easier in the beginning doesn't mean it's the right way.


text:
namespace gui {

	TextField::TextField(const mw::Font& font) : TextField("", font) {
	}

	TextField::TextField(std::string initialText, const mw::Font& font) :
		font_(font), editable_(true), textColor_(0, 0, 0),
		alignment_(LEFT), markerDeltaTime_(0), markerChanged_(false) {

		setPreferredSize(150, 20);
		setBackgroundColor(0.8f, 0.8f, 0.8f);

		inputFormatter_.update(initialText.c_str());
		text_ = mw::Text(inputFormatter_.getText(), font);
		// One pixel to the right of the last character.
		markerWidth_ = text_.getWidth() + 1;
	}

	// Get the current text.
	std::string TextField::getText() const {
		return text_.getText();
	}

	// Set the current text.
	void TextField::setText(std::string text) {
		text_.setText(text);
		markerWidth_ = text_.getWidth() - 1;
	}

	// Set the textfield to be editable or not.
	void TextField::setEditable(bool editable) {
		editable_ = editable;
	}

	bool TextField::isEditable() const {
		return editable_;
	}

	void TextField::setTextColor(const mw::Color& color) {
		textColor_ = color;
	}

	void TextField::setTextColor(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha) {
		textColor_ = mw::Color(red, green, blue, alpha);
	}

	void TextField::draw(const Graphic& graphic, double deltaTime) {
		Component::draw(graphic, deltaTime);

		Dimension dim = getSize();
		float x = 0.0;
		// Text should
		switch (alignment_) {
			case Alignment::LEFT:
				x = 2;
				break;
			case Alignment::CENTER:
				x = dim.width_ * 0.5f - (text_.getWidth() - 2) * 0.5f;
				break;
			case Alignment::RIGHT:
				x = dim.width_ - text_.getWidth() - 2;
				break;
		}

		graphic.setColor(textColor_);
		graphic.drawText(text_, x, 0);
		if (editable_) {
			if (hasFocus()) {
				markerDeltaTime_ += deltaTime;
				if (markerDeltaTime_ < 0.5) {
					graphic.drawSquare(markerWidth_ + x, 1, 1, text_.getCharacterSize());
				} else if (markerDeltaTime_ > 1.0) {
					markerDeltaTime_ = 0;
				}
			} else {
				markerDeltaTime_ = 0;
			}
		}
	}

	TextField::Alignment TextField::getAlignment() const {
		return alignment_;
	}

	void TextField::setAlignment(TextField::Alignment alignment) {
		alignment_ = alignment;
	}

	void TextField::handleKeyboard(const SDL_Event& keyEvent) {
		if (editable_) {
			switch (keyEvent.type) {
				case SDL_TEXTINPUT:
					// Update only if the glyph is avaiable.
					if (font_.getTtfFont() != 0 && 0 == TTF_SizeUTF8(font_.getTtfFont(), keyEvent.text.text, 0, 0)) {
						// A Utf8 string as input.
						inputFormatter_.update(keyEvent.text.text);
						text_.setText(inputFormatter_.getText());
						markerChanged_ = true;
					}
					break;
				case SDL_KEYDOWN:
					// Reset marker animation.
					markerDeltaTime_ = 0;
					switch (keyEvent.key.keysym.sym) {
						case SDLK_v: // Paste from clipboard!
							if ((keyEvent.key.keysym.mod & KMOD_CTRL) && SDL_HasClipboardText()) {
								char* text = SDL_GetClipboardText();
								inputFormatter_.update(SDL_GetClipboardText());
								text_.setText(inputFormatter_.getText());
								markerChanged_ = true;
								SDL_free(text);
							}
							break;
						case SDLK_c: // Copy from textfield!
							if (keyEvent.key.keysym.mod & KMOD_CTRL) {
								SDL_SetClipboardText(inputFormatter_.getText().c_str());
							}
							break;
						case SDLK_x: // Cut from textfield!
							if (keyEvent.key.keysym.mod & KMOD_CTRL) {
								SDL_SetClipboardText(inputFormatter_.getText().c_str());
								inputFormatter_.clear();
								text_.setText(inputFormatter_.getText());
								markerChanged_ = true;
							}
							break;
						case SDLK_HOME:
							inputFormatter_.update(InputFormatter::INPUT_MOVE_MARKER_HOME);
							markerChanged_ = true;
							break;
						case SDLK_END:
							inputFormatter_.update(InputFormatter::INPUT_MOVE_MARKER_END);
							markerChanged_ = true;
							break;
						case SDLK_LEFT:
							inputFormatter_.update(InputFormatter::INPUT_MOVE_MARKER_LEFT);
							markerChanged_ = true;
							break;
						case SDLK_RIGHT:
							inputFormatter_.update(InputFormatter::INPUT_MOVE_MARKER_RIGHT);
							markerChanged_ = true;
							break;
						case SDLK_BACKSPACE:
							inputFormatter_.update(InputFormatter::INPUT_ERASE_LEFT);
							text_.setText(inputFormatter_.getText());
							markerChanged_ = true;
							break;
						case SDLK_DELETE:
							inputFormatter_.update(InputFormatter::INPUT_ERASE_RIGHT);
							text_.setText(inputFormatter_.getText());
							markerChanged_ = true;
							break;
						case SDLK_RETURN:
							// Fall through!
						case SDLK_KP_ENTER:
							doAction();
							break;
					}
					break;
			}
			if (markerChanged_) {
				markerChanged_ = false;
				int index = inputFormatter_.getMarkerPosition();
				std::string leftText = getText().substr(0, index);
				int w, h;
				if (font_.getTtfFont()) {
					TTF_SizeUTF8(font_.getTtfFont(), leftText.c_str(), &w, &h);
					// One pixel to the right of the last character.
				}
				markerWidth_ = (float) w + 1;
			}
		}
	}

} // Namespace gui.


text:
Our fully managed **SaaS platform** [Hub](../hub/hub_getting_started)
provides a fast and easy way to get Pachyderm up and running.

!!! Attention "**Your first 21 days are free!**"
    *Offer limited to one single user workspace with 4 vCPUs, 15GB RAM, and unlimited object storage.*

You can also deploy Pachyderm on your local machine or in your favorite cloud
provider.

Got questions? [Contact us](mailto:support@pachyderm.io), [Request a demo](https://www.pachyderm.com/request-a-demo/), or join our [Users Slack Channel](http://slack.pachyderm.io/).

Deploy on Hub

        Deploy a new cluster in seconds and try out
        basic Pachyderm features.

          Getting Started with Hub

          Beginner Tutorial

Deploy Locally

        Deploy Pachyderm on your computer and
        run our tutorials.

          Deploy Locally

          Install pachctl Autocompletion

          Beginner Tutorial


text:
package org.jvnet.jaxb2_commons.lang;

import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.transform.dom.DOMSource;

import org.custommonkey.xmlunit.Diff;
import org.jvnet.jaxb2_commons.lang.JAXBEqualsStrategy;
import org.jvnet.jaxb2_commons.locator.ObjectLocator;
import org.w3c.dom.Node;

public class ExtendedJAXBEqualsStrategy extends JAXBEqualsStrategy {

	@Override
	protected boolean equalsInternal(ObjectLocator leftLocator,
			ObjectLocator rightLocator, Object lhs, Object rhs) {

		if (lhs instanceof Node && rhs instanceof Node) {
			return equalsInternal(leftLocator, rightLocator, (Node) lhs,
					(Node) rhs);
		} else if (lhs instanceof XMLGregorianCalendar
				&& rhs instanceof XMLGregorianCalendar) {
			return equalsInternal(leftLocator, rightLocator,
					(XMLGregorianCalendar) lhs, (XMLGregorianCalendar) rhs);

		} else {
			return super.equalsInternal(leftLocator, rightLocator, lhs, rhs);
		}
	}

	protected boolean equalsInternal(ObjectLocator leftLocator,
			ObjectLocator rightLocator, XMLGregorianCalendar left,
			XMLGregorianCalendar right) {
		return equals(leftLocator, rightLocator, left.normalize()
				.toGregorianCalendar().getTimeInMillis(), right.normalize()
				.toGregorianCalendar().getTimeInMillis());
	}

	protected boolean equalsInternal(ObjectLocator leftLocator,
			ObjectLocator rightLocator, Node lhs, Node rhs) {
		final Diff diff = new Diff(new DOMSource((Node) lhs), new DOMSource(
				(Node) rhs));
		return diff.identical();
	}

}


text:
NS_ASSUME_NONNULL_BEGIN

@interface WKInterfaceSlider (Spec)

@property (nonatomic, readonly) BOOL enabled;
@property (nonatomic, readonly) float value;
@property (nonatomic, readonly) float minimum;
@property (nonatomic, readonly) float maximum;
@property (nonatomic, readonly) NSInteger numberOfSteps;
@property (nonatomic, readonly, nullable) UIImage *minimumImage;
@property (nonatomic, readonly, nullable) UIImage *maximumImage;
@property (nonatomic, readonly) BOOL continuous;

@end

NS_ASSUME_NONNULL_END


text:
module RailsWorkflow
  module Operations
    module Assignments
      extend ActiveSupport::Concern

      included do
        belongs_to :assignment, polymorphic: true, required: false

        scope :by_role, ->(role) { joins(:template).where(rails_workflow_operation_templates: { role: role }) }
        scope :by_group, ->(group) { joins(:template).where(rails_workflow_operation_templates: { group: group }) }
        scope :unassigned, -> { where(assignment_id: nil) }

        scope :waiting, -> { where(status: Operation.user_ready_statuses) }

        scope :available_for_user, ->(user) {
          waiting.unassigned.joins(:template)
                 .merge(OperationTemplate.for_user(user))
        }

        scope :by_role_or_group, ->(role, group) do
          joins(:template).by_role_or_group(role, group)
        end

        scope :assigned_to, ->(user) {
          where(assignment_id: user.id, assignment_type: user.class.to_s)
        }

        def assigned?(user)
          assignment == user
        end

        def cancel_assignment(user)
          if assigned? user
            self.assignment = nil
            self.is_active = false
            save
          end
        end

        # can_assign_to will be used to check if user/group
        # can be assigned to operation
        def can_be_assigned?(_user)
          assignment.blank?
        end

        def assign_to(user)
          self.assignment = user
          self.is_active = true
          self.assigned_at = Time.zone.now

          self.class.assigned_to(user).update_all(is_active: false)

          save
        end

        def activate
          self.is_active = true
          save
        end

        def assign(user)
          ((assigned? user) && activate) || # if already assigned to user but unactive!
            (can_be_assigned?(user) && assign_to(user)) # user first time assigned to operation
        end
      end
    end
  end
end


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

namespace ReplaceWholeWordsInFile
{
    class Program
    {
        /// <summary>
        /// Replace all word occurrences in given file by path name.
        /// </summary>
        /// <param name="path"></param>
        /// <param name="searchWord"></param>
        /// <param name="replaceWord"></param>
        static void ReplaceWordOccurencesInFile(string path, string searchWord, string replaceWord)
        {
            string pattern = string.Format(@"\b{0}\b", searchWord);
            Regex regReplace = new Regex(pattern,RegexOptions.Compiled);

            using (StreamReader read = new StreamReader(path))
            {
                using (StreamWriter write = new StreamWriter("replace.txt"))
                {
                    string line;
                    while ((line = read.ReadLine()) != null)
                    {
                        string replacedLine = regReplace.Replace(line, replaceWord);
                        write.WriteLine(replacedLine);
                    }
                }
            }
            string fileName = Path.GetFileName(path);
            File.Delete(path);
            File.Move("replace.txt", fileName);
        }

        static void Main(string[] args)
        {
            Console.Write("Enter path to text file : ");
            string filePath = Console.ReadLine();
            try
            {
                ReplaceWordOccurencesInFile(filePath, "start", "finish");
                Console.WriteLine("Operation complete.");
            }
            catch (Exception e)
            {
                Console.WriteLine("{0}", e.Message);
            }
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN""http://www.w3.org/TR/REC-html40/frameset.dtd">

<TITLE>
Xerces2 Implementation: Class  XIntPool
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Serialized
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  SUMMARY:  INNER | FIELD | CONSTR | METHOD

DETAIL:  FIELD | CONSTR | METHOD

org.apache.xerces.impl.xs.util

Class  XIntPool

java.lang.Object
  |
  +--org.apache.xerces.impl.xs.util.XIntPool

public final class XIntPool
extends java.lang.Object

INTERNAL:

Usage of this class is not supported. It may be altered or removed at any time.

Version:
$Id: XIntPool.java 446723 2006-09-15 20:37:45Z mrglavas $

Author:
Henry Zongaro, IBM

Constructor Summary

XIntPool()

Method Summary

 XInt
getXInt(int value)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

XIntPool

public XIntPool()

Method Detail

getXInt

public final XInt getXInt(int value)

      Overview
      Package
    Class
      Tree
      Serialized
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  SUMMARY:  INNER | FIELD | CONSTR | METHOD

DETAIL:  FIELD | CONSTR | METHOD

Copyright © 1999-2010 The Apache Software Foundation. All Rights Reserved.


text:
[ -z "$TEST_SRCDIR" ] && { echo "TEST_SRCDIR not set!" >&2; exit 1; }

# Load the unit-testing framework
source "${TEST_SRCDIR}/src/test/shell/unittest.bash" || \
  { echo "Failed to source unittest.bash" >&2; exit 1; }

set_up() {
  mkdir -p $TEST_TMPDIR/workspace
  cd $TEST_TMPDIR/workspace
  touch $TEST_TMPDIR/workspace/WORKSPACE
}

tear_down() {
  rm -fr $TEST_TMPDIR/workspace/*
}


text:
 Improve this Doc

Error: error:iid

Invalid ID

CacheId '{0}' is already taken!

Description

This error occurs when trying to create a new cache object via $cacheFactory with an ID that was already used to create another cache object.

To resolve the error please use a different cache ID when calling $cacheFactory.


text:
<!--
   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
-->
<view>
  <name>FAVORITE</name>
  <label>Favorite</label>
  <version>1.0.0</version>
  <parameter>
    <name>what.is.the.question</name>
    <description>Ask a question</description>
    <required>true</required>
  </parameter>
  <parameter>
    <name>i.do.not.know</name>
    <description>If you do not know</description>
    <required>true</required>
  </parameter>
  <resource>
    <name>favorite</name>
    <service-class>org.apache.ambari.view.favorite.FavoriteService</service-class>
  </resource>
</view>


text:
package slick.test.codegen

import org.junit.Test
import org.junit.Assert._
import slick.collection.heterogeneous._
import com.typesafe.slick.testkit.util.{DBTest, DBTestObject, JdbcTestDB}
import com.typesafe.slick.testkit.util.StandardTestDBs._
import scala.concurrent.ExecutionContext.Implicits.global

object CodeGeneratorRoundTripTest extends DBTestObject(H2Mem, SQLiteMem, Postgres, MySQL, DerbyMem, HsqldbMem)

class CodeGeneratorRoundTripTest(val tdb: JdbcTestDB) extends DBTest {
  import tdb.profile.api._
  import tdb.driver.quoteIdentifier

  @Test def test: Unit = runBlocking {
    object Tables extends roundtrip.Tables { val profile = tdb.profile }
    import Tables.profile.api._
    import Tables._
    GetResultPostsRow
    GetResultLargeRow

    DBIO.seq(
      schema.create,
      Categories += CategoriesRow(1,"cat"),
      Posts ++= Seq(
        PostsRow(1,"post 1",Some(1)),
        PostsRow(2,"post 2",Some(1)),
        PostsRow(3,"post 3",Some(1))
      ),
      Categories += CategoriesRow(2,"cat"),
      Posts.length.result.zip(Posts.filter(_.title =!= "post 1").map(_.title).to[List].result).map(res => assertEquals((3,List("post 2","post 3")), res)),
      sql"""select * from #${quoteIdentifier("POSTS")} where #${quoteIdentifier("id")} = 2""".as[PostsRow].head.map(res => assertEquals(PostsRow(2,"post 2",Some(1)), res)),
      SelfRef.forceInsert(SelfRefRow(1,None)),
      SelfRef.forceInsert(SelfRefRow(2,Some(1))),
      SelfRef.result,
      {
        // Testing table larger 22 columns
        val oData = 0L :: 11 :: 12 :: 13 :: 14 :: 15 :: 16 :: 21 :: 22 :: 23 :: 24 :: 25 :: 26 :: 31 :: 32 :: 33 :: 34 :: 35 :: 36 :: 41 :: 42 :: 43 :: 44 :: 45 :: 46 :: 51 :: 52 :: 53 :: 54 :: 55 :: 56 :: 61 :: 62 :: 63 :: 64 :: 65 :: 66 :: HNil
        val oData2 = LargeRow( 1L, p6i4 = 123, p1i5 = 456 )
        DBIO.seq(
          Large += oData,
          Large += oData2,
          sql"""select * from #${quoteIdentifier("LARGE")} where #${quoteIdentifier("id")} = 0""".as[LargeRow].head.map(res => assertEquals(oData, res))
        )
      },
      (X.map(r => (r.pk,r.pk2,r.column,r.schemaNameXX,r.schemaNameX)) += (1,1,1,1.1,"test")).map { _ =>
        // testing name and types especially in case of collisions
        import slick.lifted._
        X.map(r =>{(r.pk: Rep[Int]) == null})
        X.map(r =>{(r.pk2: Rep[Int]) == null})
        X.map(r =>{(r.`val`: Rep[Option[Int]]) == null})
        X.map(r =>{(r.column: Rep[Int]) == null})
        X.map(r =>{(r.schemaNameXX: Rep[Double]) == null})
        X.map(r =>{(r.schemaNameX: Rep[String]) == null})
        X.map(r =>{(r.index1: Rep[Option[Int]]) == null})
        X.map(r =>{(r.posts: Rep[Option[Int]]) == null})
        X.map(r =>{(r.pkX: PrimaryKey) == null})
        X.map(r =>{(r.postsFk: ForeignKeyQuery[Posts,PostsRow]) == null})
        X.map(r =>{(r.categoriesFk2: ForeignKeyQuery[Categories,CategoriesRow]) == null})
        X.map(r =>{(r.categoriesFk3: ForeignKeyQuery[Categories,CategoriesRow]) == null})
        X.map(r =>{(r.index1X: Index) == null})
        X.map(r =>{(r.index2: Index) == null})
        X.map(r =>{(r.index1X: Index) == null})
        X.map(r =>{(r.index2: Index) == null})
        X.map(r =>{(r.index3: Index) == null})
        X.map(r =>{(r.index4: Index) == null})

        TypeTest.map(r =>{(r.pk: PrimaryKey) == null})
      }
    ).withPinnedSession
  }
}


text:
package io.seata.serializer.protobuf.convertor;

import io.seata.serializer.protobuf.generated.GlobalBeginResponseProto;
import io.seata.core.exception.TransactionExceptionCode;
import io.seata.core.protocol.ResultCode;
import io.seata.core.protocol.transaction.GlobalBeginResponse;
import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * @author leizhiyuan
 */
public class GlobalBeginResponseConvertorTest {

    @Test
    public void convert2Proto() {

        GlobalBeginResponse globalBeginResponse = new GlobalBeginResponse();

        globalBeginResponse.setResultCode(ResultCode.Failed);
        globalBeginResponse.setMsg("msg");
        globalBeginResponse.setExtraData("extraData");
        globalBeginResponse.setXid("xid");
        globalBeginResponse.setTransactionExceptionCode(TransactionExceptionCode.BranchRollbackFailed_Retriable);

        GlobalBeginResponseConvertor convertor = new GlobalBeginResponseConvertor();
        GlobalBeginResponseProto proto = convertor.convert2Proto(globalBeginResponse);
        GlobalBeginResponse real = convertor.convert2Model(proto);
        assertThat((real.getTypeCode())).isEqualTo(globalBeginResponse.getTypeCode());
        assertThat((real.getMsg())).isEqualTo(globalBeginResponse.getMsg());
        assertThat((real.getResultCode())).isEqualTo(globalBeginResponse.getResultCode());
        assertThat((real.getTransactionExceptionCode())).isEqualTo(globalBeginResponse.getTransactionExceptionCode());
    }
}


text:
using LocalLingua.Logic.Admin;
using LocalLingua.Logic.Chat;
using LocalLingua.Logic.City;
using LocalLingua.Logic.Guide;
using LocalLingua.Logic.Ranks;
using LocalLingua.Logic.Statistics;
using LocalLingua.Logic.Trip;
using LocalLingua.Web.Infrastructure.Account;

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(LocalLingua.Web.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(LocalLingua.Web.App_Start.NinjectWebCommon), "Stop")]

namespace LocalLingua.Web.App_Start
{
    using System;
    using System.Web;

    using Microsoft.Web.Infrastructure.DynamicModuleHelper;

    using Ninject;
    using Ninject.Web.Common;
    using LocalLingua.Logic.Location;
    using Ninject.Web.WebApi;
    using System.Web.Http;

    public static class NinjectWebCommon
    {
        static readonly Bootstrapper bootstrapper = new Bootstrapper();

        /// <summary>
        /// Starts the application
        /// </summary>
        public static void Start()
        {
            DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
            DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
            bootstrapper.Initialize(CreateKernel);
        }

        /// <summary>
        /// Stops the application.
        /// </summary>
        public static void Stop()
        {
            bootstrapper.ShutDown();
        }

        /// <summary>
        /// Creates the kernel that will manage your application.
        /// </summary>
        /// <returns>The created kernel.</returns>
        static IKernel CreateKernel()
        {
            var kernel = new StandardKernel();
            try
            {
                kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
                kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

                RegisterServices(kernel);
                GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);

                return kernel;
            }
            catch
            {
                kernel.Dispose();
                throw;
            }
        }

        /// <summary>
        /// Load your modules or register your services here!
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        static void RegisterServices(IKernel kernel)
        {
            kernel.Bind<ICountryService>().To<CountryService>();
            kernel.Bind<IStatisticsService>().To<StatisticsService>();
            kernel.Bind<ICityService>().To<CityService>();
            kernel.Bind<ITripsService>().To<TripsService>();
            kernel.Bind<IAccountService>().To<AccountService>();
            kernel.Bind<IChatService>().To<ChatService>();
            kernel.Bind<IGuidesService>().To<GuidesService>();
            kernel.Bind<IRanksService>().To<RanksService>();
            kernel.Bind<IAdminService>().To<AdminService>();
        }
    }
}


text:
package org.dolphin.hotpatch.dex;

/**
 * Created by hanyanan on 2015/11/11.
 */
public class DexHotPatchConstants {
    public static final String DEX_SUFFIX = ".dex";
    public static final String CONFIG_SUFFIX = ".config.json";

    public static final String DEX_AND_CONFIG_NO_MATCH_ERROR = "dex和config文件不匹配";
    public static final String CONFIG_READ_ERROR = "读取config文件失败";
    public static final String SIGN_NO_MATCH_ERROR = "dex文件签名错误";
    public static final String USELESS_FILE = "没有被使用的文件";
    public static final String ILLEGAL_DEX_FORMATE_FILE = "无效的dex";
}


text:
package org.datavec.spark.functions;

import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.input.PortableDataStream;
import org.datavec.api.io.labels.ParentPathLabelGenerator;
import org.datavec.api.split.FileSplit;
import org.datavec.api.split.InputSplit;
import org.datavec.api.writable.Writable;
import org.datavec.image.recordreader.ImageRecordReader;
import org.datavec.spark.BaseSparkTest;
import org.datavec.spark.functions.data.FilesAsBytesFunction;
import org.datavec.spark.functions.data.RecordReaderBytesFunction;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.nd4j.linalg.io.ClassPathResource;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

public class TestRecordReaderBytesFunction extends BaseSparkTest {

    @Rule
    public TemporaryFolder testDir = new TemporaryFolder();

    @Test
    public void testRecordReaderBytesFunction() throws Exception {
        JavaSparkContext sc = getContext();

        //Local file path
        File f = testDir.newFolder();
        new ClassPathResource("datavec-spark/imagetest/").copyDirectory(f);
        List<String> labelsList = Arrays.asList("0", "1"); //Need this for Spark: can't infer without init call
        String path = f.getAbsolutePath() + "/*";

        //Load binary data from local file system, convert to a sequence file:
        //Load and convert
        JavaPairRDD<String, PortableDataStream> origData = sc.binaryFiles(path);
        JavaPairRDD<Text, BytesWritable> filesAsBytes = origData.mapToPair(new FilesAsBytesFunction());
        //Write the sequence file:
        Path p = Files.createTempDirectory("dl4j_rrbytesTest");
        p.toFile().deleteOnExit();
        String outPath = p.toString() + "/out";
        filesAsBytes.saveAsNewAPIHadoopFile(outPath, Text.class, BytesWritable.class, SequenceFileOutputFormat.class);

        //Load data from sequence file, parse via RecordReader:
        JavaPairRDD<Text, BytesWritable> fromSeqFile = sc.sequenceFile(outPath, Text.class, BytesWritable.class);
        ImageRecordReader irr = new ImageRecordReader(28, 28, 1, new ParentPathLabelGenerator());
        irr.setLabels(labelsList);
        JavaRDD<List<Writable>> dataVecData = fromSeqFile.map(new RecordReaderBytesFunction(irr));

        //Next: do the same thing locally, and compare the results
        InputSplit is = new FileSplit(f, new String[] {"bmp"}, true);
        irr = new ImageRecordReader(28, 28, 1, new ParentPathLabelGenerator());
        irr.initialize(is);

        List<List<Writable>> list = new ArrayList<>(4);
        while (irr.hasNext()) {
            list.add(irr.next());
        }

        List<List<Writable>> fromSequenceFile = dataVecData.collect();

        assertEquals(4, list.size());
        assertEquals(4, fromSequenceFile.size());

        //Check that each of the values from Spark equals exactly one of the values doing it locally
        boolean[] found = new boolean[4];
        for (int i = 0; i < 4; i++) {
            int foundIndex = -1;
            List<Writable> collection = fromSequenceFile.get(i);
            for (int j = 0; j < 4; j++) {
                if (collection.equals(list.get(j))) {
                    if (foundIndex != -1)
                        fail(); //Already found this value -> suggests this spark value equals two or more of local version? (Shouldn't happen)
                    foundIndex = j;
                    if (found[foundIndex])
                        fail(); //One of the other spark values was equal to this one -> suggests duplicates in Spark list
                    found[foundIndex] = true; //mark this one as seen before
                }
            }
        }

        int count = 0;
        for (boolean b : found)
            if (b)
                count++;
        assertEquals(4, count); //Expect all 4 and exactly 4 pairwise matches between spark and local versions
        //        System.out.println("COUNT: " + count);
    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Parmelia delisella Nyl.

### Remarks
null


text:
package yhd.widget;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.shapes.Shape;

/**
 * X形状
 * Created by haodongyuan on 2016/1/7.
 */
public class CrossShape extends Shape {
    private float strokeWidth;

    public CrossShape(float strokeWidth) {
        this.strokeWidth = strokeWidth;
    }

    @Override
    public void draw(Canvas canvas, Paint paint) {
        float w = getWidth();
        float h = getHeight();

        paint.setStrokeWidth(strokeWidth);
        paint.setStrokeCap(Paint.Cap.ROUND);

        // TODO: 重复填充了交点
        canvas.drawLine(0, 0, w, h, paint);
        canvas.drawLine(w, 0, 0, h, paint);
    }
}


text:
package com.twitter.server.lint

import com.twitter.finagle.service.FailFastFactory
import com.twitter.finagle.util.StackRegistry
import com.twitter.util.lint.{Category, Issue, Rule}

object MemcacheFailFastRule {

  def apply(stackReg: StackRegistry): Rule = {
    Rule(
      Category.Configuration,
      "Memcache client has FailFast enabled",
      """FailFast is only appropriate when a replica set is present. Memcached
        |is usually sharded. Consider disabling FailFast or using the
        |c.t.f.Memcached.client which has recommended settings built in.""".stripMargin
    ) {
      stackReg.registrants
        .filter(_.protocolLibrary == "memcached")
        .groupBy(_.name)
        .filter {
          case (_, entries) =>
            entries.head.params[FailFastFactory.FailFast].enabled == true
        }
        .map {
          case (label, _) =>
            Issue(s"$label memcache client should disable FailFast")
        }
        .toSeq
    }
  }

}


text:
package com.farseer.todo.flux.view.base;

import android.content.Context;
import android.support.v4.app.Fragment;

/**
 * Fragment基类
 *
 * @author zhaosc
 * @version 1.0.0
 * @since 2016-04-19
 */
public class BaseFragment extends Fragment {

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }
}