text:
namespace raft_msg {
class CommandResponseDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<CommandResponse> {
} _CommandResponse_default_instance_;

namespace protobuf_command_5fresponse_2eproto {

namespace {

::google::protobuf::Metadata file_level_metadata[1];

}  // namespace

const ::google::protobuf::uint32 TableStruct::offsets[] = {
  GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CommandResponse, _has_bits_),
  GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CommandResponse, _internal_metadata_),
  ~0u,  // no _extensions_
  ~0u,  // no _oneof_case_
  GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CommandResponse, command_id_),
  GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CommandResponse, success_),
  GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CommandResponse, passwd_),
  GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CommandResponse, err_),
  GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CommandResponse, result_),
  2,
  3,
  0,
  4,
  1,
};

static const ::google::protobuf::internal::MigrationSchema schemas[] = {
  { 0, 9, sizeof(CommandResponse)},
};

static ::google::protobuf::Message const * const file_default_instances[] = {
  reinterpret_cast<const ::google::protobuf::Message*>(&_CommandResponse_default_instance_),
};

namespace {

void protobuf_AssignDescriptors() {
  AddDescriptors();
  ::google::protobuf::MessageFactory* factory = NULL;
  AssignDescriptors(
      "command_response.proto", schemas, file_default_instances, TableStruct::offsets, factory,
      file_level_metadata, NULL, NULL);
}

void protobuf_AssignDescriptorsOnce() {
  static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
  ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);
}

void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
  protobuf_AssignDescriptorsOnce();
  ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 1);
}

}  // namespace

void TableStruct::Shutdown() {
  _CommandResponse_default_instance_.Shutdown();
  delete file_level_metadata[0].reflection;
}

void TableStruct::InitDefaultsImpl() {
  GOOGLE_PROTOBUF_VERIFY_VERSION;

  ::google::protobuf::internal::InitProtobufDefaults();
  ::raft_msg::protobuf_raft_5fenum_2eproto::InitDefaults();
  _CommandResponse_default_instance_.DefaultConstruct();
  _CommandResponse_default_instance_.get_mutable()->result_ = const_cast< ::raft_msg::KVEntry*>(
      ::raft_msg::KVEntry::internal_default_instance());
}

void InitDefaults() {
  static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
  ::google::protobuf::GoogleOnceInit(&once, &TableStruct::InitDefaultsImpl);
}
void AddDescriptorsImpl() {
  InitDefaults();
  static const char descriptor[] = {
      "\n\026command_response.proto\022\010raft_msg\032\017raft"
      "_enum.proto\"\224\001\n\017CommandResponse\022\022\n\ncomma"
      "nd_id\030\001 \002(\004\022\017\n\007success\030\002 \002(\010\022\016\n\006passwd\030\003"
      " \002(\t\022)\n\003err\030\004 \001(\0162\034.raft_msg.CommandResp"
      "onseErr\022!\n\006result\030\005 \001(\0132\021.raft_msg.KVEnt"
      "ry"
  };
  ::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
      descriptor, 202);
  ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
    "command_response.proto", &protobuf_RegisterTypes);
  ::raft_msg::protobuf_raft_5fenum_2eproto::AddDescriptors();
  ::google::protobuf::internal::OnShutdown(&TableStruct::Shutdown);
}

void AddDescriptors() {
  static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
  ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);
}
// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer {
  StaticDescriptorInitializer() {
    AddDescriptors();
  }
} static_descriptor_initializer;

}  // namespace protobuf_command_5fresponse_2eproto

// ===================================================================

#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int CommandResponse::kCommandIdFieldNumber;
const int CommandResponse::kSuccessFieldNumber;
const int CommandResponse::kPasswdFieldNumber;
const int CommandResponse::kErrFieldNumber;
const int CommandResponse::kResultFieldNumber;
#endif  // !defined(_MSC_VER) || _MSC_VER >= 1900

CommandResponse::CommandResponse()
  : ::google::protobuf::Message(), _internal_metadata_(NULL) {
  if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
    protobuf_command_5fresponse_2eproto::InitDefaults();
  }
  SharedCtor();
  // @@protoc_insertion_point(constructor:raft_msg.CommandResponse)
}
CommandResponse::CommandResponse(const CommandResponse& from)
  : ::google::protobuf::Message(),
      _internal_metadata_(NULL),
      _has_bits_(from._has_bits_),
      _cached_size_(0) {
  _internal_metadata_.MergeFrom(from._internal_metadata_);
  passwd_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
  if (from.has_passwd()) {
    passwd_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.passwd_);
  }
  if (from.has_result()) {
    result_ = new ::raft_msg::KVEntry(*from.result_);
  } else {
    result_ = NULL;
  }
  ::memcpy(&command_id_, &from.command_id_,
    reinterpret_cast<char*>(&err_) -
    reinterpret_cast<char*>(&command_id_) + sizeof(err_));
  // @@protoc_insertion_point(copy_constructor:raft_msg.CommandResponse)
}

void CommandResponse::SharedCtor() {
  _cached_size_ = 0;
  passwd_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
  ::memset(&result_, 0, reinterpret_cast<char*>(&err_) -
    reinterpret_cast<char*>(&result_) + sizeof(err_));
}

CommandResponse::~CommandResponse() {
  // @@protoc_insertion_point(destructor:raft_msg.CommandResponse)
  SharedDtor();
}

void CommandResponse::SharedDtor() {
  passwd_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
  if (this != internal_default_instance()) {
    delete result_;
  }
}

void CommandResponse::SetCachedSize(int size) const {
  GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
  _cached_size_ = size;
  GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* CommandResponse::descriptor() {
  protobuf_command_5fresponse_2eproto::protobuf_AssignDescriptorsOnce();
  return protobuf_command_5fresponse_2eproto::file_level_metadata[0].descriptor;
}

const CommandResponse& CommandResponse::default_instance() {
  protobuf_command_5fresponse_2eproto::InitDefaults();
  return *internal_default_instance();
}

CommandResponse* CommandResponse::New(::google::protobuf::Arena* arena) const {
  CommandResponse* n = new CommandResponse;
  if (arena != NULL) {
    arena->Own(n);
  }
  return n;
}

void CommandResponse::Clear() {
// @@protoc_insertion_point(message_clear_start:raft_msg.CommandResponse)
  if (_has_bits_[0 / 32] & 3u) {
    if (has_passwd()) {
      GOOGLE_DCHECK(!passwd_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
      (*passwd_.UnsafeRawStringPointer())->clear();
    }
    if (has_result()) {
      GOOGLE_DCHECK(result_ != NULL);
      result_->::raft_msg::KVEntry::Clear();
    }
  }
  if (_has_bits_[0 / 32] & 28u) {
    ::memset(&command_id_, 0, reinterpret_cast<char*>(&err_) -
      reinterpret_cast<char*>(&command_id_) + sizeof(err_));
  }
  _has_bits_.Clear();
  _internal_metadata_.Clear();
}

bool CommandResponse::MergePartialFromCodedStream(
    ::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
  ::google::protobuf::uint32 tag;
  // @@protoc_insertion_point(parse_start:raft_msg.CommandResponse)
  for (;;) {
    ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
    tag = p.first;
    if (!p.second) goto handle_unusual;
    switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
      // required uint64 command_id = 1;
      case 1: {
        if (tag == 8u) {
          set_has_command_id();
          DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
                   ::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_UINT64>(
                 input, &command_id_)));
        } else {
          goto handle_unusual;
        }
        break;
      }

      // required bool success = 2;
      case 2: {
        if (tag == 16u) {
          set_has_success();
          DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
                   bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
                 input, &success_)));
        } else {
          goto handle_unusual;
        }
        break;
      }

      // required string passwd = 3;
      case 3: {
        if (tag == 26u) {
          DO_(::google::protobuf::internal::WireFormatLite::ReadString(
                input, this->mutable_passwd()));
          ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
            this->passwd().data(), this->passwd().length(),
            ::google::protobuf::internal::WireFormat::PARSE,
            "raft_msg.CommandResponse.passwd");
        } else {
          goto handle_unusual;
        }
        break;
      }

      // optional .raft_msg.CommandResponseErr err = 4;
      case 4: {
        if (tag == 32u) {
          int value;
          DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
                   int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
                 input, &value)));
          if (::raft_msg::CommandResponseErr_IsValid(value)) {
            set_err(static_cast< ::raft_msg::CommandResponseErr >(value));
          } else {
            mutable_unknown_fields()->AddVarint(4, value);
          }
        } else {
          goto handle_unusual;
        }
        break;
      }

      // optional .raft_msg.KVEntry result = 5;
      case 5: {
        if (tag == 42u) {
          DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
               input, mutable_result()));
        } else {
          goto handle_unusual;
        }
        break;
      }

      default: {
      handle_unusual:
        if (tag == 0 ||
            ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
            ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
          goto success;
        }
        DO_(::google::protobuf::internal::WireFormat::SkipField(
              input, tag, mutable_unknown_fields()));
        break;
      }
    }
  }
success:
  // @@protoc_insertion_point(parse_success:raft_msg.CommandResponse)
  return true;
failure:
  // @@protoc_insertion_point(parse_failure:raft_msg.CommandResponse)
  return false;
#undef DO_
}

void CommandResponse::SerializeWithCachedSizes(
    ::google::protobuf::io::CodedOutputStream* output) const {
  // @@protoc_insertion_point(serialize_start:raft_msg.CommandResponse)
  // required uint64 command_id = 1;
  if (has_command_id()) {
    ::google::protobuf::internal::WireFormatLite::WriteUInt64(1, this->command_id(), output);
  }

  // required bool success = 2;
  if (has_success()) {
    ::google::protobuf::internal::WireFormatLite::WriteBool(2, this->success(), output);
  }

  // required string passwd = 3;
  if (has_passwd()) {
    ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
      this->passwd().data(), this->passwd().length(),
      ::google::protobuf::internal::WireFormat::SERIALIZE,
      "raft_msg.CommandResponse.passwd");
    ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
      3, this->passwd(), output);
  }

  // optional .raft_msg.CommandResponseErr err = 4;
  if (has_err()) {
    ::google::protobuf::internal::WireFormatLite::WriteEnum(
      4, this->err(), output);
  }

  // optional .raft_msg.KVEntry result = 5;
  if (has_result()) {
    ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
      5, *this->result_, output);
  }

  if (_internal_metadata_.have_unknown_fields()) {
    ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
        unknown_fields(), output);
  }
  // @@protoc_insertion_point(serialize_end:raft_msg.CommandResponse)
}

::google::protobuf::uint8* CommandResponse::InternalSerializeWithCachedSizesToArray(
    bool deterministic, ::google::protobuf::uint8* target) const {
  (void)deterministic;  // Unused
  // @@protoc_insertion_point(serialize_to_array_start:raft_msg.CommandResponse)
  // required uint64 command_id = 1;
  if (has_command_id()) {
    target = ::google::protobuf::internal::WireFormatLite::WriteUInt64ToArray(1, this->command_id(), target);
  }

  // required bool success = 2;
  if (has_success()) {
    target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(2, this->success(), target);
  }

  // required string passwd = 3;
  if (has_passwd()) {
    ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
      this->passwd().data(), this->passwd().length(),
      ::google::protobuf::internal::WireFormat::SERIALIZE,
      "raft_msg.CommandResponse.passwd");
    target =
      ::google::protobuf::internal::WireFormatLite::WriteStringToArray(
        3, this->passwd(), target);
  }

  // optional .raft_msg.CommandResponseErr err = 4;
  if (has_err()) {
    target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray(
      4, this->err(), target);
  }

  // optional .raft_msg.KVEntry result = 5;
  if (has_result()) {
    target = ::google::protobuf::internal::WireFormatLite::
      InternalWriteMessageNoVirtualToArray(
        5, *this->result_, false, target);
  }

  if (_internal_metadata_.have_unknown_fields()) {
    target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
        unknown_fields(), target);
  }
  // @@protoc_insertion_point(serialize_to_array_end:raft_msg.CommandResponse)
  return target;
}

size_t CommandResponse::RequiredFieldsByteSizeFallback() const {
// @@protoc_insertion_point(required_fields_byte_size_fallback_start:raft_msg.CommandResponse)
  size_t total_size = 0;

  if (has_passwd()) {
    // required string passwd = 3;
    total_size += 1 +
      ::google::protobuf::internal::WireFormatLite::StringSize(
        this->passwd());
  }

  if (has_command_id()) {
    // required uint64 command_id = 1;
    total_size += 1 +
      ::google::protobuf::internal::WireFormatLite::UInt64Size(
        this->command_id());
  }

  if (has_success()) {
    // required bool success = 2;
    total_size += 1 + 1;
  }

  return total_size;
}
size_t CommandResponse::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:raft_msg.CommandResponse)
  size_t total_size = 0;

  if (_internal_metadata_.have_unknown_fields()) {
    total_size +=
      ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
        unknown_fields());
  }
  if (((_has_bits_[0] & 0x0000000d) ^ 0x0000000d) == 0) {  // All required fields are present.
    // required string passwd = 3;
    total_size += 1 +
      ::google::protobuf::internal::WireFormatLite::StringSize(
        this->passwd());

    // required uint64 command_id = 1;
    total_size += 1 +
      ::google::protobuf::internal::WireFormatLite::UInt64Size(
        this->command_id());

    // required bool success = 2;
    total_size += 1 + 1;

  } else {
    total_size += RequiredFieldsByteSizeFallback();
  }
  // optional .raft_msg.KVEntry result = 5;
  if (has_result()) {
    total_size += 1 +
      ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
        *this->result_);
  }

  // optional .raft_msg.CommandResponseErr err = 4;
  if (has_err()) {
    total_size += 1 +
      ::google::protobuf::internal::WireFormatLite::EnumSize(this->err());
  }

  int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
  GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
  _cached_size_ = cached_size;
  GOOGLE_SAFE_CONCURRENT_WRITES_END();
  return total_size;
}

void CommandResponse::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:raft_msg.CommandResponse)
  GOOGLE_DCHECK_NE(&from, this);
  const CommandResponse* source =
      ::google::protobuf::internal::DynamicCastToGenerated<const CommandResponse>(
          &from);
  if (source == NULL) {
  // @@protoc_insertion_point(generalized_merge_from_cast_fail:raft_msg.CommandResponse)
    ::google::protobuf::internal::ReflectionOps::Merge(from, this);
  } else {
  // @@protoc_insertion_point(generalized_merge_from_cast_success:raft_msg.CommandResponse)
    MergeFrom(*source);
  }
}

void CommandResponse::MergeFrom(const CommandResponse& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:raft_msg.CommandResponse)
  GOOGLE_DCHECK_NE(&from, this);
  _internal_metadata_.MergeFrom(from._internal_metadata_);
  if (from._has_bits_[0 / 32] & 31u) {
    if (from.has_passwd()) {
      set_has_passwd();
      passwd_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.passwd_);
    }
    if (from.has_result()) {
      mutable_result()->::raft_msg::KVEntry::MergeFrom(from.result());
    }
    if (from.has_command_id()) {
      set_command_id(from.command_id());
    }
    if (from.has_success()) {
      set_success(from.success());
    }
    if (from.has_err()) {
      set_err(from.err());
    }
  }
}

void CommandResponse::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:raft_msg.CommandResponse)
  if (&from == this) return;
  Clear();
  MergeFrom(from);
}

void CommandResponse::CopyFrom(const CommandResponse& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:raft_msg.CommandResponse)
  if (&from == this) return;
  Clear();
  MergeFrom(from);
}

bool CommandResponse::IsInitialized() const {
  if ((_has_bits_[0] & 0x0000000d) != 0x0000000d) return false;
  if (has_result()) {
    if (!this->result_->IsInitialized()) return false;
  }
  return true;
}

void CommandResponse::Swap(CommandResponse* other) {
  if (other == this) return;
  InternalSwap(other);
}
void CommandResponse::InternalSwap(CommandResponse* other) {
  passwd_.Swap(&other->passwd_);
  std::swap(result_, other->result_);
  std::swap(command_id_, other->command_id_);
  std::swap(success_, other->success_);
  std::swap(err_, other->err_);
  std::swap(_has_bits_[0], other->_has_bits_[0]);
  _internal_metadata_.Swap(&other->_internal_metadata_);
  std::swap(_cached_size_, other->_cached_size_);
}

::google::protobuf::Metadata CommandResponse::GetMetadata() const {
  protobuf_command_5fresponse_2eproto::protobuf_AssignDescriptorsOnce();
  return protobuf_command_5fresponse_2eproto::file_level_metadata[0];
}

#if PROTOBUF_INLINE_NOT_IN_HEADERS
// CommandResponse

// required uint64 command_id = 1;
bool CommandResponse::has_command_id() const {
  return (_has_bits_[0] & 0x00000004u) != 0;
}
void CommandResponse::set_has_command_id() {
  _has_bits_[0] |= 0x00000004u;
}
void CommandResponse::clear_has_command_id() {
  _has_bits_[0] &= ~0x00000004u;
}
void CommandResponse::clear_command_id() {
  command_id_ = GOOGLE_ULONGLONG(0);
  clear_has_command_id();
}
::google::protobuf::uint64 CommandResponse::command_id() const {
  // @@protoc_insertion_point(field_get:raft_msg.CommandResponse.command_id)
  return command_id_;
}
void CommandResponse::set_command_id(::google::protobuf::uint64 value) {
  set_has_command_id();
  command_id_ = value;
  // @@protoc_insertion_point(field_set:raft_msg.CommandResponse.command_id)
}

// required bool success = 2;
bool CommandResponse::has_success() const {
  return (_has_bits_[0] & 0x00000008u) != 0;
}
void CommandResponse::set_has_success() {
  _has_bits_[0] |= 0x00000008u;
}
void CommandResponse::clear_has_success() {
  _has_bits_[0] &= ~0x00000008u;
}
void CommandResponse::clear_success() {
  success_ = false;
  clear_has_success();
}
bool CommandResponse::success() const {
  // @@protoc_insertion_point(field_get:raft_msg.CommandResponse.success)
  return success_;
}
void CommandResponse::set_success(bool value) {
  set_has_success();
  success_ = value;
  // @@protoc_insertion_point(field_set:raft_msg.CommandResponse.success)
}

// required string passwd = 3;
bool CommandResponse::has_passwd() const {
  return (_has_bits_[0] & 0x00000001u) != 0;
}
void CommandResponse::set_has_passwd() {
  _has_bits_[0] |= 0x00000001u;
}
void CommandResponse::clear_has_passwd() {
  _has_bits_[0] &= ~0x00000001u;
}
void CommandResponse::clear_passwd() {
  passwd_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
  clear_has_passwd();
}
const ::std::string& CommandResponse::passwd() const {
  // @@protoc_insertion_point(field_get:raft_msg.CommandResponse.passwd)
  return passwd_.GetNoArena();
}
void CommandResponse::set_passwd(const ::std::string& value) {
  set_has_passwd();
  passwd_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
  // @@protoc_insertion_point(field_set:raft_msg.CommandResponse.passwd)
}
#if LANG_CXX11
void CommandResponse::set_passwd(::std::string&& value) {
  set_has_passwd();
  passwd_.SetNoArena(
    &::google::protobuf::internal::GetEmptyStringAlreadyInited(), std::move(value));
  // @@protoc_insertion_point(field_set_rvalue:raft_msg.CommandResponse.passwd)
}
#endif
void CommandResponse::set_passwd(const char* value) {
  set_has_passwd();
  passwd_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
  // @@protoc_insertion_point(field_set_char:raft_msg.CommandResponse.passwd)
}
void CommandResponse::set_passwd(const char* value, size_t size) {
  set_has_passwd();
  passwd_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
      ::std::string(reinterpret_cast<const char*>(value), size));
  // @@protoc_insertion_point(field_set_pointer:raft_msg.CommandResponse.passwd)
}
::std::string* CommandResponse::mutable_passwd() {
  set_has_passwd();
  // @@protoc_insertion_point(field_mutable:raft_msg.CommandResponse.passwd)
  return passwd_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
::std::string* CommandResponse::release_passwd() {
  // @@protoc_insertion_point(field_release:raft_msg.CommandResponse.passwd)
  clear_has_passwd();
  return passwd_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void CommandResponse::set_allocated_passwd(::std::string* passwd) {
  if (passwd != NULL) {
    set_has_passwd();
  } else {
    clear_has_passwd();
  }
  passwd_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), passwd);
  // @@protoc_insertion_point(field_set_allocated:raft_msg.CommandResponse.passwd)
}

// optional .raft_msg.CommandResponseErr err = 4;
bool CommandResponse::has_err() const {
  return (_has_bits_[0] & 0x00000010u) != 0;
}
void CommandResponse::set_has_err() {
  _has_bits_[0] |= 0x00000010u;
}
void CommandResponse::clear_has_err() {
  _has_bits_[0] &= ~0x00000010u;
}
void CommandResponse::clear_err() {
  err_ = 0;
  clear_has_err();
}
::raft_msg::CommandResponseErr CommandResponse::err() const {
  // @@protoc_insertion_point(field_get:raft_msg.CommandResponse.err)
  return static_cast< ::raft_msg::CommandResponseErr >(err_);
}
void CommandResponse::set_err(::raft_msg::CommandResponseErr value) {
  assert(::raft_msg::CommandResponseErr_IsValid(value));
  set_has_err();
  err_ = value;
  // @@protoc_insertion_point(field_set:raft_msg.CommandResponse.err)
}

// optional .raft_msg.KVEntry result = 5;
bool CommandResponse::has_result() const {
  return (_has_bits_[0] & 0x00000002u) != 0;
}
void CommandResponse::set_has_result() {
  _has_bits_[0] |= 0x00000002u;
}
void CommandResponse::clear_has_result() {
  _has_bits_[0] &= ~0x00000002u;
}
void CommandResponse::clear_result() {
  if (result_ != NULL) result_->::raft_msg::KVEntry::Clear();
  clear_has_result();
}
const ::raft_msg::KVEntry& CommandResponse::result() const {
  // @@protoc_insertion_point(field_get:raft_msg.CommandResponse.result)
  return result_ != NULL ? *result_
                         : *::raft_msg::KVEntry::internal_default_instance();
}
::raft_msg::KVEntry* CommandResponse::mutable_result() {
  set_has_result();
  if (result_ == NULL) {
    result_ = new ::raft_msg::KVEntry;
  }
  // @@protoc_insertion_point(field_mutable:raft_msg.CommandResponse.result)
  return result_;
}
::raft_msg::KVEntry* CommandResponse::release_result() {
  // @@protoc_insertion_point(field_release:raft_msg.CommandResponse.result)
  clear_has_result();
  ::raft_msg::KVEntry* temp = result_;
  result_ = NULL;
  return temp;
}
void CommandResponse::set_allocated_result(::raft_msg::KVEntry* result) {
  delete result_;
  result_ = result;
  if (result) {
    set_has_result();
  } else {
    clear_has_result();
  }
  // @@protoc_insertion_point(field_set_allocated:raft_msg.CommandResponse.result)
}

#endif  // PROTOBUF_INLINE_NOT_IN_HEADERS

// @@protoc_insertion_point(namespace_scope)

}  // namespace raft_msg

// @@protoc_insertion_point(global_scope)


text:
set -e
cd /usr/src/app || exit
touch .yarn.sha1
OLD_SHA=$(cat .yarn.sha1)
NEW_SHA=$(sha1sum yarn.lock)
if [ "$OLD_SHA" != "$NEW_SHA" ]; then
  echo "$NEW_SHA" > .yarn.sha1
  yarn
  rm -rf node_modules/cp-translations
  ln -s /usr/src/cp-translations node_modules/cp-translations
fi
yarn dev

redpajama_set_name: RedPajamaGithub


text:
@class PKBaseSymbol;

@protocol PKScope <NSObject>

- (void)define:(PKBaseSymbol *)sym;
- (PKBaseSymbol *)resolve:(NSString *)name;

@property (nonatomic, copy, readonly) NSString *scopeName;
@property (nonatomic, copy, readonly) id <PKScope>enclosingScope;
@end


text:
var React = require('react');
var Backbone = require('backbone');
var _ = require('underscore');
require('react-backbone');

// MODEL
var MyModel = Backbone.Model.extend({
  // add a dumb validation method which ensures first/last name length are > 5
  validate: function(attributes) {
    var errors = [];
    if (attributes.hasOwnProperty('firstName')) {
      if (!attributes.firstName || attributes.firstName.length < 5) {
        errors.push({firstName: 'The first name must be > 5 characters'});
      }
    }
    if (attributes.hasOwnProperty('lastName')) {
      if (!attributes.lastName || attributes.lastName.length < 5) {
        errors.push({lastName: 'The last name must be > 5 characters'});
      }
    }
    return errors.length && errors;
  }
});

// COMPONENTS

// create a reusable components which represent a label with an input field
var InputWithLabel = React.createClass({
  getInitialState: function() {
    return { id: _.uniqueId('form') };
  },

  render: function() {
    return

      {this.props.label}

        <input id={this.state.id} type="text" name={this.props.name} ref="input" defaultValue={this.props.value}/>

;
  },

  // allow the value of the input component to be retrieved
  getValue: function() {
    return this.refs.input.getDOMNode().value;
  }
});

// and here is the overall form component
var TestComponent = React.createClass({
  getInitialState: function() {
    // make sure this.state is not null
    return {};
  },

  // listen for the invalid event so we can message when the data is bad
  componentDidMount: function() {
    this.props.model.on('invalid', this.onInvalid);
  },
  componentWillUnmount: function() {
    this.props.model.off('invalid', this.onInvalid);
  },

  render: function() {
    var model = this.props.model,
        error = this.state.error;

    // if we've got an error, show it
    var errorComponent = error && (

        Error: {error}

    );

    // return the form and input contents
    return <form onSubmit={this.onSubmit}>
      {errorComponent}
      <InputWithLabel ref="firstName" name="firstName" label="First Name" value={model.get('firstName')}/>
      <InputWithLabel ref="lastName" name="lastName" label="Last Name" value={model.get('lastName')}/>
      <button type="submit">Click me</button>
    </form>;
  },

  onSubmit: function(ev) {
    ev.preventDefault();
    var self = this,
        attr = {};

    // populate the attr object with the user input
    _.each(['firstName', 'lastName'], function(key) {
      attr[key] = self.refs[key].getValue();
    });

    // set the model input and alert if all is ok.  if there are validation issues, the
    // onInvalid method will be executed because of the model "invalid" bindings
    if (this.props.model.set(attr, {validate: true})) {
      this.setState({error: undefined});
      alert('model validated');
    }
  },

  onInvalid: function(model, errors) {
    // for simplicity, we'll just show the first error
    var errorStr = [];
    _.each(errors, function(error) {
      _.each(error, function(message) {
        errorStr.push(message);
      });
    });
    this.setState({error: errorStr.join(', ')});
  }
});

// INITIAL RENDER
var model = new MyModel({
  firstName: 'John',
  lastName: 'Doe'
});
React.render(<TestComponent model={model}/>, document.body);


text:
namespace valkyrie
{

class Node;

class DLL_HIDDEN Force : private Entity
{
public:
    Force(int id, const std::string& name, std::shared_ptr<Node> n, double magn, double nx, double ny, double nz);

    IS_ENTITY

    std::shared_ptr<Node> get_node() { return n_; }
    const double magnitude() const { return magnitude_; }
    const double nx() const { return nx_; }
    const double ny() const { return ny_; }
    const double nz() const { return nz_; }
private:
    std::shared_ptr<Node> n_;
    double magnitude_;
    double nx_, ny_, nz_;
};

std::shared_ptr<Force> DLL_HIDDEN try_create_force(int fid, std::shared_ptr<Node> n, double magn, double nx, double ny, double nz);

}//~ns:valkyrie

#endif // VALKYRIE_FORCE_H_INCLUDED


text:
package de.mklinger.commons.junitsupport;

/**
 * @author Marc Klinger - mklinger[at]mklinger[dot]de - klingerm
 */
public class TestBean1Test extends BeanTestBase<TestBean1> {
	public TestBean1Test() {
		super(TestBean1.class);
	}

	@Override
	protected ConstructorParameters[] getConstructorParameters() {
		return new ConstructorParameters[] {
				DEFAULT_CONSTRUCTOR_PARAMETERS,
				new ConstructorParameters(new Class[] { String.class, Integer.TYPE, Boolean.TYPE }, new String[] { "s", "n", "b" })
		};
	}
}


text:
Defines Homebrew specific environment variables and aliases.

## Variables

Execute the following to list the environment variables loaded in the shell:

```sh
brew shellenv
```

## Aliases

### Homebrew Core

- `brewc` cleans outdated brews and their cached archives.
- `brewi` installs a formula.
- `brewL` lists installed formulae that are not dependencies of another
  installed formula.
- `brewl` lists installed formulae.
- `brewo` lists brews which have an update available.
- `brews` searches for a formula.
- `brewu` upgrades outdated formulae.
- `brewx` uninstalls a formula.

### Homebrew Cask

- `caski` installs a cask.
- `caskl` lists installed casks.
- `casko` lists casks which have an update available.
- `casks` searches for a cask.
- `casku` upgrades outdated casks.
- `caskx` uninstalls a cask.

## Authors

_The authors of this module should be contacted via the [issue tracker][1]._

- [Sorin Ionescu](https://github.com/sorin-ionescu)
- [Griffin Yourick](https://github.com/tough-griff)

[1]: https://github.com/sorin-ionescu/prezto/issues


text:
namespace CGoGN
{

namespace SCHNApps
{

struct MapParameters
{
    MapParameters();
    ~MapParameters();

    void start();
    void stop();

    bool m_initialized;

    Algo::Surface::Modelisation::Voxellisation m_voxellisation;
    Geom::Vec3i m_resolutions;
    Geom::BoundingBox<PFP2::VEC3> m_bb;
    int m_dilatation;
    bool m_toVoxellise;
    bool m_independant;
    bool m_extractionFaces;
    bool m_toCalculateResolutions;
};

class Surface_GenerationCage_Plugin : public PluginProcessing
{
	Q_OBJECT
	Q_INTERFACES(CGoGN::SCHNApps::Plugin)

public:
    Surface_GenerationCage_Plugin()
	{}

    ~Surface_GenerationCage_Plugin()
	{}

	virtual bool enable();
	virtual void disable();

private slots:
	void mapAdded(MapHandlerGen* map);
	void mapRemoved(MapHandlerGen* map);
    void attributeModified(unsigned int orbit, QString nameAttr);

    void openGenerationCageDialog();

    void generationCageFromDialog();
    void dilaterVoxellisationFromDialog();
    void reinitialiserVoxellisationFromDialog();

    void currentMapSelectedChangedFromDialog();
    void currentAttributeIndexChangedFromDialog(QString nameAttr);

    void resolutionToggledFromDialog(bool b);

    void resolutionXModifiedFromDialog(int value);
    void resolutionYModifiedFromDialog(int value);
    void resolutionZModifiedFromDialog(int value);

    void surfaceExtractionToggledFromDialog(bool b);

public slots:
    MapHandlerGen* generationCage(const QString& mapName, const QString& positionAttributeName);

    void voxellise(const QString& mapName, const QString &positionAttributeName);

    void dilaterVoxellisation(const QString& mapName, const QString& positionAttributeName);
    void reinitialiserVoxellisation(const QString& mapName, const QString& positionAttributeName);

    MapHandlerGen* extractionCarte(const QString& mapName, const QString& positionAttributeName);

    void calculateResolutions(const QString& mapName, const QString& positionAttributeName);
    void updateResolutions(const QString& mapName, const QString& positionAttributeName);

    Geom::Vec3i& getVoxelIndex(const QString& mapName, const QString& positionAttributeName, Geom::Vec3f a);
private:
    Dialog_GenerationCage* m_generationCageDialog;
    QAction* m_generationCageAction;

public:
    QHash<QString, MapParameters> h_parameterSet;
};

} // namespace SCHNApps

} // namespace CGoGN

#endif


text:
exit 1

alias bfg="java -jar /c/govmeeting/bfg-1.14.0.jar"

# DELETE1="{*.css.map,*.js.map,*.ogg,*.webm,app.js,BigBuck*.mp4,bootstrap*.css,bootstrap*.js,canvg*.js,jquery*.js,jquery*.map,jquery*.ts,main.bundle.js,main-es*.js,pdfmake-es*.js,polyfills-es*.js,shims.js,styles-es*.js,vendor-bundle.js,vendor-es*.js,WinSCP.exe,WinSCPnet.dll,google-translate-attribution.zip,itextsharp.dll,iTextSharp.xml}"
# cd /c/govmeeting/_sourcecode_mirror
# bfg -D $DELETE1
# git reflog expire --expire=now --all && git gc --prune=now --aggressive

# DELETE2="{*.mp4,*.flac,Maine_Acadia_National_Park.png}"
# cd /c/govmeeting/_sourcecode_mirror_copy
# bfg -D $DELETE2
# git reflog expire --expire=now --all && git gc --prune=now --aggressive

DELETE="{*.mp4,*.flac,*.css.map,*.js.map,*.ogg,*.webm,app.js,BigBuck*.mp4,bootstrap*.css,bootstrap*.js,canvg*.js,jquery*.js,jquery*.map,jquery*.ts,main.bundle.js,main-es*.js,pdfmake-es*.js,polyfills-es*.js,shims.js,styles-es*.js,vendor-bundle.js,vendor-es*.js,WinSCP.exe,WinSCPnet.dll,google-translate-attribution.zip,itextsharp.dll,iTextSharp.xml}"
cd /c/govmeeting/SOURCECODE_MIRROR_NO_PRIVATE_REFS/tmp.seC9sJ2Jkh
bfg -D $DELETE
git reflog expire --expire=now --all && git gc --prune=now --aggressive

# This is the blob id for the Maine_Acadia_National_Park.png which is 8.3 MiB.
DELETE_BLOBS="8942cb2c55d1"

# java -jar bfg-1.14.0.jar -D $DELETE _SOURCECODE_MIRROR

# java -jar bfg-1.14.0.jar -D *.js.map

# cd C:\GOVMEETING\WORKAREA\RemoveLargeFileFromGit
# cd C:/GOVMEETING/WORKAREA/RemoveLargeFileFromGit
# C:/GOVMEETING/_SOURCECODE/Utilities/BashScripts/git-show-big-files.sh


text:
import {CertificateExchangeMedium} from '../utils/CertificateProvider';
import {ClientConnection} from './ClientConnection';
import {transformCertificateExchangeMediumToType} from './Utilities';
import {
  ClientDescription,
  ClientQuery,
  SignCertificateMessage,
} from 'flipper-common';
import {SecureServerConfig} from '../utils/certificateUtils';

/**
 * ClientCsrQuery defines a client query with CSR
 * information.
 */
export type ClientCsrQuery = {
  csr?: string | undefined;
  csr_path?: string | undefined;
};

/**
 * SecureClientQuery combines a ClientQuery with
 * ClientCsrQuery. It also adds medium information.
 */
export type SecureClientQuery = ClientQuery &
  ClientCsrQuery & {medium: 1 /*FS*/ | 2 /*WWW*/ | 3 /*NONE*/ | undefined};

/**
 * Defines an interface for events triggered by a running server interacting
 * with a client.
 */
export interface ServerEventsListener {
  /**
   * Server started and listening at the specified port.
   * @param port The port in which the server is listening to.
   */
  onListening(port: number): void;
  /**
   * An insecure connection attempt has been made by a client. At this
   * point, a connection should be already be available but needs to be
   * validated by the server.
   * @param clientQuery A ClientQuery instance containing metadata about
   * the client e.g. OS, device, app, etc.
   */
  onConnectionAttempt(clientQuery: ClientQuery): void;
  /**
   * A TLS connection attempt has been made by a client. At this
   * point, a connection should be already be available but needs to be
   * validated by the server.
   * @param clientQuery A SecureClientQuery instance containing metadata about
   * the client and CSR information as exchanged on the previously
   * established insecure connection.
   */
  onSecureConnectionAttempt(clientQuery: SecureClientQuery): void;
  /**
   * CSR received by the server and needs to be processed. If successfully
   * processed, it should return a generated device identifier.
   * @param unsanitizedCSR CSR as sent by the client, will need to be sanitized
   * before usage.
   * @param clientQuery A ClientQuery instance containing metadata about
   * the client e.g. OS, device, app, etc.
   * @param appDirectory App directory in which to deploy the CA and client
   * certificates.
   * @param medium Certificate exchange medium type e.g. FS_ACCESS, WWW.
   */
  onProcessCSR(
    unsanitizedCSR: string,
    clientQuery: ClientQuery,
    appDirectory: string,
    medium: CertificateExchangeMedium,
  ): Promise<{deviceId: string}>;
  /**
   * A secure connection has been established with a validated client.
   * A promise to a Client instance needs to be returned.
   * @param clientQuery A SecureClientQuery instance containing metadata about
   * the client and CSR information as exchanged on the previously
   * established insecure connection.
   * @param clientConnection A valid client connection.
   */
  onConnectionCreated(
    clientQuery: SecureClientQuery,
    clientConnection: ClientConnection,
    downgrade?: boolean,
  ): Promise<ClientDescription>;
  /**
   * A connection with a client has been closed.
   * @param id The client identifier.
   */
  onConnectionClosed(id: string): void;
  /**
   * An error has occurred.
   * @param error An Error instance.
   */
  onError(error: Error): void;
  /**
   * A message was received for a specif client
   * // TODO: payload should become JSON
   */
  onClientMessage(clientId: string, payload: string): void;

  onClientSetupError(clientQuery: ClientQuery, error: any): void;

  onDeprecationNotice: (message: string) => void;
}

/**
 * Defines the base class to be used by any server implementation e.g.
 * RSocket, WebSocket, etc.
 */
abstract class ServerAdapter {
  constructor(protected listener: ServerEventsListener) {}

  /**
   * Start and bind server to the specified port.
   * @param port A port number. Pass 0 to get a random free port.
   * https://stackoverflow.com/a/28050404
   * @param sslConfig An optional SSL configuration to be used for
   * TLS servers.
   *
   * @returns An assigned port number
   */
  abstract start(port: number, sslConfig?: SecureServerConfig): Promise<number>;
  /**
   * Stop the server.
   */
  abstract stop(): Promise<void>;

  /**
   * Handle a message received over an insecure connection. The only
   * supported message is to sign certificates.
   * @param clientQuery A ClientQuery instance containing metadata about
   * the client e.g. OS, device, app, etc.
   * @param rawData Raw data as sent by the client.
   * @returns The response to be sent back to the client. If the received
   * request is to sign a certificate and no errors were found, the response
   * should contain the device identifier to use by the client.
   */
  protected async _onHandleUntrustedMessage(
    clientQuery: ClientQuery,
    rawData: any,
  ): Promise<string | undefined> {
    // OSS's older Client SDK might not send medium information.
    // This is not an issue for internal FB users, as Flipper release
    // is insync with client SDK through launcher.

    const message: SignCertificateMessage = rawData;

    console.info(
      `[conn] Connection attempt: ${clientQuery.app} on ${clientQuery.device}, medium: ${message.medium}, cert: ${message.destination}`,
      clientQuery,
    );

    if (message.method === 'signCertificate') {
      console.debug('CSR received from device', 'server');

      const {csr, destination, medium} = message;

      console.info(
        `[conn] Starting certificate exchange: ${clientQuery.app} on ${clientQuery.device}`,
      );
      try {
        const result = await this.listener.onProcessCSR(
          csr,
          clientQuery,
          destination,
          transformCertificateExchangeMediumToType(medium),
        );

        console.info(
          `[conn] Exchanged certificate: ${clientQuery.app} on ${result.deviceId}`,
        );
        const response = JSON.stringify({
          deviceId: result.deviceId,
        });
        return response;
      } catch (e) {
        this.listener.onClientSetupError(clientQuery, e);
      }
    }

    return undefined;
  }
}

export default ServerAdapter;


text:
"""
Module of AccessibleEventImplementation class.
"""

import os
from hatemile import helper
from hatemile.accessibleevent import AccessibleEvent
from hatemile.util.commonfunctions import CommonFunctions
from hatemile.util.idgenerator import IDGenerator
from hatemile.util.html.htmldomparser import HTMLDOMParser

class AccessibleEventImplementation(AccessibleEvent):
    """
    The AccessibleEventImplementation class is official implementation of
    :py:class:`hatemile.accessibleevent.AccessibleEvent`.
    """

    #: The id of script element that replace the event listener methods.
    ID_SCRIPT_EVENT_LISTENER = 'script-eventlistener'

    #: The id of script element that contains the list of elements that has
    #: inaccessible events.
    ID_LIST_IDS_SCRIPT = 'list-ids-script'

    #: The id of script element that modify the events of elements.
    ID_FUNCTION_SCRIPT_FIX = 'id-function-script-fix'

    #: The ID of script element that contains the common functions of scripts.
    ID_SCRIPT_COMMON_FUNCTIONS = 'hatemile-common-functions'

    def __init__(self, parser):
        """
        Initializes a new object that manipulate the accessibility of the
        Javascript events of elements of parser.

        :param parser: The HTML parser.
        :type parser: hatemile.util.html.htmldomparser.HTMLDOMParser
        """

        helper.require_not_none(parser)
        helper.require_valid_type(parser, HTMLDOMParser)

        self.parser = parser
        self.id_generator = IDGenerator('event')
        self.main_script_added = False
        self.script_list = None

    def _keyboard_access(self, element):
        """
        Provide keyboard access for element, if it not has.

        :param element: The element.
        :type element: hatemile.util.html.htmldomelement.HTMLDOMElement
        """
        # pylint: disable=no-self-use

        if not element.has_attribute('tabindex'):
            tag = element.get_tag_name()
            if (tag == 'A') and (not element.has_attribute('href')):
                element.set_attribute('tabindex', '0')
            elif (
                (tag != 'A')
                and (tag != 'INPUT')
                and (tag != 'BUTTON')
                and (tag != 'SELECT')
                and (tag != 'TEXTAREA')
            ):
                element.set_attribute('tabindex', '0')

    def _generate_main_scripts(self):
        """
        Include the scripts used by solutions.
        """

        head = self.parser.find('head').first_result()
        if head is not None:
            common_functions_script = self.parser.find(
                '#'
                + AccessibleEventImplementation.ID_SCRIPT_COMMON_FUNCTIONS
            ).first_result()
            if common_functions_script is None:
                common_functions_file = open(
                    os.path.join(
                        os.path.dirname(os.path.dirname(os.path.dirname(
                            os.path.realpath(__file__)
                        ))),
                        'js',
                        'common.js'
                    ),
                    'r'
                )
                common_functions_content = common_functions_file.read()
                common_functions_file.close()

                common_functions_script = self.parser.create_element('script')
                common_functions_script.set_attribute(
                    'id',
                    AccessibleEventImplementation.ID_SCRIPT_COMMON_FUNCTIONS
                )
                common_functions_script.set_attribute(
                    'type',
                    'text/javascript'
                )
                common_functions_script.append_text(common_functions_content)
                head.prepend_element(common_functions_script)
            if (
                self.parser.find(
                    '#'
                    + AccessibleEventImplementation.ID_SCRIPT_EVENT_LISTENER
                ).first_result() is None
            ):
                event_listener_file = open(
                    os.path.join(
                        os.path.dirname(os.path.dirname(os.path.dirname(
                            os.path.realpath(__file__)
                        ))),
                        'js',
                        'eventlistener.js'
                    ),
                    'r'
                )
                event_listener_script_content = event_listener_file.read()
                event_listener_file.close()

                script = self.parser.create_element('script')
                script.set_attribute(
                    'id',
                    AccessibleEventImplementation.ID_SCRIPT_EVENT_LISTENER
                )
                script.set_attribute('type', 'text/javascript')
                script.append_text(event_listener_script_content)
                common_functions_script.insert_after(script)
        local = self.parser.find('body').first_result()
        if local is not None:
            self.script_list = self.parser.find(
                '#'
                + AccessibleEventImplementation.ID_LIST_IDS_SCRIPT
            ).first_result()
            if self.script_list is None:
                self.script_list = self.parser.create_element('script')
                self.script_list.set_attribute(
                    'id',
                    AccessibleEventImplementation.ID_LIST_IDS_SCRIPT
                )
                self.script_list.set_attribute('type', 'text/javascript')
                self.script_list.append_text('var activeElements = [];')
                self.script_list.append_text('var hoverElements = [];')
                self.script_list.append_text('var dragElements = [];')
                self.script_list.append_text('var dropElements = [];')
                local.append_element(self.script_list)
            if self.parser.find(
                    '#'
                    + AccessibleEventImplementation.ID_FUNCTION_SCRIPT_FIX
            ).first_result() is None:
                include_file = open(
                    os.path.join(
                        os.path.dirname(os.path.dirname(os.path.dirname(
                            os.path.realpath(__file__)
                        ))),
                        'js',
                        'include.js'
                    ),
                    'r'
                )
                local_include_script_content = include_file.read()
                include_file.close()

                script_function = self.parser.create_element('script')
                script_function.set_attribute(
                    'id',
                    AccessibleEventImplementation.ID_FUNCTION_SCRIPT_FIX
                )
                script_function.set_attribute('type', 'text/javascript')
                script_function.append_text(local_include_script_content)
                local.append_element(script_function)
        self.main_script_added = True

    def _add_event_in_element(self, element, event):
        """
        Add a type of event in element.

        :param element: The element.
        :type element: hatemile.util.html.htmldomelement.HTMLDOMElement
        :param event: The type of event.
        :type event: str
        """

        if not self.main_script_added:
            self._generate_main_scripts()

        if self.script_list is not None:
            self.id_generator.generate_id(element)
            self.script_list.append_text(
                event
                + "Elements.push('"
                + element.get_attribute('id')
                + "');"
            )

    def make_accessible_drop_events(self, element):
        element.set_attribute('aria-dropeffect', 'none')

        self._add_event_in_element(element, 'drop')

    def make_accessible_drag_events(self, element):
        self._keyboard_access(element)

        element.set_attribute('aria-grabbed', 'false')

        self._add_event_in_element(element, 'drag')

    def make_accessible_all_drag_and_drop_events(self):
        draggable_elements = self.parser.find(
            '[ondrag],[ondragstart],[ondragend]'
        ).list_results()
        for draggable_element in draggable_elements:
            if CommonFunctions.is_valid_element(draggable_element):
                self.make_accessible_drag_events(draggable_element)

        droppable_elements = self.parser.find(
            '[ondrop],[ondragenter],[ondragleave],[ondragover]'
        ).list_results()
        for droppable_element in droppable_elements:
            if CommonFunctions.is_valid_element(droppable_element):
                self.make_accessible_drop_events(droppable_element)

    def make_accessible_hover_events(self, element):
        self._keyboard_access(element)

        self._add_event_in_element(element, 'hover')

    def make_accessible_all_hover_events(self):
        elements = self.parser.find(
            '[onmouseover],[onmouseout]'
        ).list_results()
        for element in elements:
            if CommonFunctions.is_valid_element(element):
                self.make_accessible_hover_events(element)

    def make_accessible_click_events(self, element):
        self._keyboard_access(element)

        self._add_event_in_element(element, 'active')

    def make_accessible_all_click_events(self):
        elements = self.parser.find(
            '[onclick],[onmousedown],[onmouseup],[ondblclick]'
        ).list_results()
        for element in elements:
            if CommonFunctions.is_valid_element(element):
                self.make_accessible_click_events(element)


text:
<?php

App::uses('AppModel', 'Model');
App::uses('AuthComponent', 'Controller/Component');
/**
 * User Model
 *
 */
class User extends AppModel {

/**
 * Validation rules
 *
 * @var array
 */
	public $validate = array(
		'username' => array(
			'notEmpty' => array(
				'rule' => array('notEmpty'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
		'password' => array(
			'notEmpty' => array(
				'rule' => array('notEmpty'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),

		 'role' => array(
            'valid' => array(
                'rule' => array('inList', array('admin')),
                'message' => 'Please enter a valid role',
                'allowEmpty' => false
            )
        )
	);

	public function beforeSave($options = array()) {
	    if (isset($this->data[$this->alias]['password'])) {
	        $this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
	    }
	    return true;
	}
}


text:
module Fog
  module Compute
    class Brightbox
      class Real
        # Get full details of the server.
        #
        # @param [String] identifier Unique reference to identify the resource
        #
        # @return [Hash] if successful Hash version of JSON object
        #
        # @see https://api.gb1.brightbox.com/1.0/#server_get_server
        #
        def get_server(identifier)
          return nil if identifier.nil? || identifier == ""
          wrapped_request("get", "/1.0/servers/#{identifier}", [200])
        end
      end
    end
  end
end


text:
// Pseudocode:

/*
Input: list of numbers
Output: sum of numbers, mean of list, median (middle value) of list
Steps:
- Declare variable that holds list of numbers
- Create new object with properties for sum, mean, and median
	- Sum property
	   - should be defined as a function that takes a list as an argument
	   - Create variable for final sum, should start equal to 0
	   - FOR loop that starts i with 0, continues while i is less than list length, and increases by 1
	 	     - in each iteration of the for loop, add the element of the list at index i to final sum
	 	     - END
	   - return final sum
	- Mean property
		 - should be defined as a function that takes a list as an argument
		 - declare variable average, set equal to sum (should be able to use function above) divided by length of list
		 - return average
	- Median property
		 - should be defined as a function that takes a list as an argument
		 - declare variable for sorted list, set value to be the sorted list
		 - declare variable for median index (index of the median value), set value to be length of list divided by 2, rounded down to nearest whole number
		 - IF length of list is an odd number
		 		- return value from list at the median index
		 - ELSE
		 		- return (value in list at median index) + (value in list at median index - 1) divided by 2
		 - END
	*/


text:
.. image:: https://travis-ci.org/wireservice/agate-sql.png
    :target: https://travis-ci.org/wireservice/agate-sql
    :alt: Build status

.. image:: https://img.shields.io/pypi/v/agate-sql.svg
    :target: https://pypi.python.org/pypi/agate-sql
    :alt: Version

.. image:: https://img.shields.io/pypi/l/agate-sql.svg
    :target: https://pypi.python.org/pypi/agate-sql
    :alt: License

.. image:: https://img.shields.io/pypi/pyversions/agate-sql.svg
    :target: https://pypi.python.org/pypi/agate-sql
    :alt: Support Python versions

agate-sql adds SQL read/write support to `agate <https://github.com/wireservice/agate>`_.

Important links:

* agate             http://agate.rtfd.org
* Documentation:    http://agate-sql.rtfd.org
* Repository:       https://github.com/wireservice/agate-sql
* Issues:           https://github.com/wireservice/agate-sql/issues


text:
namespace ts {
    export function preProcessFile(sourceText: string, readImportFiles = true, detectJavaScriptImports = false): PreProcessedFileInfo {
        const referencedFiles: FileReference[] = [];
        const typeReferenceDirectives: FileReference[] = [];
        const importedFiles: FileReference[] = [];
        let ambientExternalModules: { ref: FileReference, depth: number }[];
        let isNoDefaultLib = false;
        let braceNesting = 0;
        // assume that text represent an external module if it contains at least one top level import/export
        // ambient modules that are found inside external modules are interpreted as module augmentations
        let externalModule = false;

        function nextToken() {
            const token = scanner.scan();
            if (token === SyntaxKind.OpenBraceToken) {
                braceNesting++;
            }
            else if (token === SyntaxKind.CloseBraceToken) {
                braceNesting--;
            }
            return token;
        }

        function processTripleSlashDirectives(): void {
            const commentRanges = getLeadingCommentRanges(sourceText, 0);
            forEach(commentRanges, commentRange => {
                const comment = sourceText.substring(commentRange.pos, commentRange.end);
                const referencePathMatchResult = getFileReferenceFromReferencePath(comment, commentRange);
                if (referencePathMatchResult) {
                    isNoDefaultLib = referencePathMatchResult.isNoDefaultLib;
                    const fileReference = referencePathMatchResult.fileReference;
                    if (fileReference) {
                        const collection = referencePathMatchResult.isTypeReferenceDirective
                            ? typeReferenceDirectives
                            : referencedFiles;

                        collection.push(fileReference);
                    }
                }
            });
        }

        function getFileReference() {
            const file = scanner.getTokenValue();
            const pos = scanner.getTokenPos();
            return {
                fileName: file,
                pos: pos,
                end: pos + file.length
            };
        }

        function recordAmbientExternalModule(): void {
            if (!ambientExternalModules) {
                ambientExternalModules = [];
            }
            ambientExternalModules.push({ ref: getFileReference(), depth: braceNesting });
        }

        function recordModuleName() {
            importedFiles.push(getFileReference());

            markAsExternalModuleIfTopLevel();
        }

        function markAsExternalModuleIfTopLevel() {
            if (braceNesting === 0) {
                externalModule = true;
            }
        }

        /**
         * Returns true if at least one token was consumed from the stream
         */
        function tryConsumeDeclare(): boolean {
            let token = scanner.getToken();
            if (token === SyntaxKind.DeclareKeyword) {
                // declare module "mod"
                token = nextToken();
                if (token === SyntaxKind.ModuleKeyword) {
                    token = nextToken();
                    if (token === SyntaxKind.StringLiteral) {
                        recordAmbientExternalModule();
                    }
                }
                return true;
            }

            return false;
        }

        /**
         * Returns true if at least one token was consumed from the stream
         */
        function tryConsumeImport(): boolean {
            let token = scanner.getToken();
            if (token === SyntaxKind.ImportKeyword) {
                token = nextToken();
                if (token === SyntaxKind.OpenParenToken) {
                    token = nextToken();
                    if (token === SyntaxKind.StringLiteral) {
                        // import("mod");
                        recordModuleName();
                        return true;
                    }
                }
                else if (token === SyntaxKind.StringLiteral) {
                    // import "mod";
                    recordModuleName();
                    return true;
                }
                else {
                    if (token === SyntaxKind.Identifier || isKeyword(token)) {
                        token = nextToken();
                        if (token === SyntaxKind.FromKeyword) {
                            token = nextToken();
                            if (token === SyntaxKind.StringLiteral) {
                                // import d from "mod";
                                recordModuleName();
                                return true;
                            }
                        }
                        else if (token === SyntaxKind.EqualsToken) {
                            if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) {
                                return true;
                            }
                        }
                        else if (token === SyntaxKind.CommaToken) {
                            // consume comma and keep going
                            token = nextToken();
                        }
                        else {
                            // unknown syntax
                            return true;
                        }
                    }

                    if (token === SyntaxKind.OpenBraceToken) {
                        token = nextToken();
                        // consume "{ a as B, c, d as D}" clauses
                        // make sure that it stops on EOF
                        while (token !== SyntaxKind.CloseBraceToken && token !== SyntaxKind.EndOfFileToken) {
                            token = nextToken();
                        }

                        if (token === SyntaxKind.CloseBraceToken) {
                            token = nextToken();
                            if (token === SyntaxKind.FromKeyword) {
                                token = nextToken();
                                if (token === SyntaxKind.StringLiteral) {
                                    // import {a as A} from "mod";
                                    // import d, {a, b as B} from "mod"
                                    recordModuleName();
                                }
                            }
                        }
                    }
                    else if (token === SyntaxKind.AsteriskToken) {
                        token = nextToken();
                        if (token === SyntaxKind.AsKeyword) {
                            token = nextToken();
                            if (token === SyntaxKind.Identifier || isKeyword(token)) {
                                token = nextToken();
                                if (token === SyntaxKind.FromKeyword) {
                                    token = nextToken();
                                    if (token === SyntaxKind.StringLiteral) {
                                        // import * as NS from "mod"
                                        // import d, * as NS from "mod"
                                        recordModuleName();
                                    }
                                }
                            }
                        }
                    }
                }

                return true;
            }

            return false;
        }

        function tryConsumeExport(): boolean {
            let token = scanner.getToken();
            if (token === SyntaxKind.ExportKeyword) {
                markAsExternalModuleIfTopLevel();
                token = nextToken();
                if (token === SyntaxKind.OpenBraceToken) {
                    token = nextToken();
                    // consume "{ a as B, c, d as D}" clauses
                    // make sure it stops on EOF
                    while (token !== SyntaxKind.CloseBraceToken && token !== SyntaxKind.EndOfFileToken) {
                        token = nextToken();
                    }

                    if (token === SyntaxKind.CloseBraceToken) {
                        token = nextToken();
                        if (token === SyntaxKind.FromKeyword) {
                            token = nextToken();
                            if (token === SyntaxKind.StringLiteral) {
                                // export {a as A} from "mod";
                                // export {a, b as B} from "mod"
                                recordModuleName();
                            }
                        }
                    }
                }
                else if (token === SyntaxKind.AsteriskToken) {
                    token = nextToken();
                    if (token === SyntaxKind.FromKeyword) {
                        token = nextToken();
                        if (token === SyntaxKind.StringLiteral) {
                            // export * from "mod"
                            recordModuleName();
                        }
                    }
                }
                else if (token === SyntaxKind.ImportKeyword) {
                    token = nextToken();
                    if (token === SyntaxKind.Identifier || isKeyword(token)) {
                        token = nextToken();
                        if (token === SyntaxKind.EqualsToken) {
                            if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) {
                                return true;
                            }
                        }
                    }
                }

                return true;
            }

            return false;
        }

        function tryConsumeRequireCall(skipCurrentToken: boolean): boolean {
            let token = skipCurrentToken ? nextToken() : scanner.getToken();
            if (token === SyntaxKind.RequireKeyword) {
                token = nextToken();
                if (token === SyntaxKind.OpenParenToken) {
                    token = nextToken();
                    if (token === SyntaxKind.StringLiteral) {
                        //  require("mod");
                        recordModuleName();
                    }
                }
                return true;
            }
            return false;
        }

        function tryConsumeDefine(): boolean {
            let token = scanner.getToken();
            if (token === SyntaxKind.Identifier && scanner.getTokenValue() === "define") {
                token = nextToken();
                if (token !== SyntaxKind.OpenParenToken) {
                    return true;
                }

                token = nextToken();
                if (token === SyntaxKind.StringLiteral) {
                    // looks like define ("modname", ... - skip string literal and comma
                    token = nextToken();
                    if (token === SyntaxKind.CommaToken) {
                        token = nextToken();
                    }
                    else {
                        // unexpected token
                        return true;
                    }
                }

                // should be start of dependency list
                if (token !== SyntaxKind.OpenBracketToken) {
                    return true;
                }

                // skip open bracket
                token = nextToken();
                let i = 0;
                // scan until ']' or EOF
                while (token !== SyntaxKind.CloseBracketToken && token !== SyntaxKind.EndOfFileToken) {
                    // record string literals as module names
                    if (token === SyntaxKind.StringLiteral) {
                        recordModuleName();
                        i++;
                    }

                    token = nextToken();
                }
                return true;

            }
            return false;
        }

        function processImports(): void {
            scanner.setText(sourceText);
            nextToken();
            // Look for:
            //    import "mod";
            //    import d from "mod"
            //    import {a as A } from "mod";
            //    import * as NS  from "mod"
            //    import d, {a, b as B} from "mod"
            //    import i = require("mod");
            //    import("mod");

            //    export * from "mod"
            //    export {a as b} from "mod"
            //    export import i = require("mod")
            //    (for JavaScript files) require("mod")

            while (true) {
                if (scanner.getToken() === SyntaxKind.EndOfFileToken) {
                    break;
                }

                // check if at least one of alternative have moved scanner forward
                if (tryConsumeDeclare() ||
                    tryConsumeImport() ||
                    tryConsumeExport() ||
                    (detectJavaScriptImports && (tryConsumeRequireCall(/*skipCurrentToken*/ false) || tryConsumeDefine()))) {
                    continue;
                }
                else {
                    nextToken();
                }
            }

            scanner.setText(undefined);
        }

        if (readImportFiles) {
            processImports();
        }
        processTripleSlashDirectives();
        if (externalModule) {
            // for external modules module all nested ambient modules are augmentations
            if (ambientExternalModules) {
                // move all detected ambient modules to imported files since they need to be resolved
                for (const decl of ambientExternalModules) {
                    importedFiles.push(decl.ref);
                }
            }
            return { referencedFiles, typeReferenceDirectives, importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: undefined };
        }
        else {
            // for global scripts ambient modules still can have augmentations - look for ambient modules with depth > 0
            let ambientModuleNames: string[];
            if (ambientExternalModules) {
                for (const decl of ambientExternalModules) {
                    if (decl.depth === 0) {
                        if (!ambientModuleNames) {
                            ambientModuleNames = [];
                        }
                        ambientModuleNames.push(decl.ref.fileName);
                    }
                    else {
                        importedFiles.push(decl.ref);
                    }
                }
            }
            return { referencedFiles, typeReferenceDirectives, importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: ambientModuleNames };
        }
    }
}


text:
package org.springframework.cloud.stream.binder.kinesis.provisioning;

import java.util.List;

import com.amazonaws.services.kinesis.model.Shard;

import org.springframework.cloud.stream.provisioning.ConsumerDestination;

/**
 * The Kinesis-specific {@link ConsumerDestination} implementation.
 *
 * @author Artem Bilan
 *
 */
public final class KinesisConsumerDestination implements ConsumerDestination {

	private final String streamName;

	private final List<Shard> shards;

	private final String dlqName;

	public KinesisConsumerDestination(String streamName, List<Shard> shards) {
		this(streamName, shards, null);
	}

	public KinesisConsumerDestination(String streamName, List<Shard> shards, String dlqName) {
		this.streamName = streamName;
		this.shards = shards;
		this.dlqName = dlqName;
	}

	@Override
	public String getName() {
		return this.streamName;
	}

	public List<Shard> getShards() {
		return this.shards;
	}

	@Override
	public String toString() {
		return "KinesisConsumerDestination{" + "streamName='" + this.streamName + '\''
				+ ", shards=" + this.shards + ", dlqName='" + this.dlqName + '\'' + '}';
	}

}


text:
require "active_record"
require "authem/token"

module Authem
  class Session < ::ActiveRecord::Base
    self.table_name = :authem_sessions

    belongs_to :subject, polymorphic: true

    before_create do
      self.token ||= Authem::Token.generate
      self.ttl ||= 30.days
      self.expires_at ||= ttl_from_now
    end

    class << self
      def by_subject(record)
        where(subject_type: record.class.name, subject_id: record.id)
      end

      def active
        where(arel_table[:expires_at].gteq(Time.zone.now))
      end

      def expired
        where(arel_table[:expires_at].lt(Time.zone.now))
      end
    end

    def refresh
      self.expires_at = ttl_from_now
      save!
    end

    private

    def ttl_from_now
      ttl.to_i.from_now
    end
  end
end


text:
package org.patriques.output.technicalindicators;

import org.patriques.input.technicalindicators.Interval;
import org.patriques.output.JsonParser;
import org.patriques.output.technicalindicators.data.STOCHDataFast;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Representation of the stochastic fast (STOCHF) response from api.
 *
 * @see TechnicalIndicatorResponse
 */
public class STOCHF extends TechnicalIndicatorResponse<STOCHDataFast> {

  private STOCHF(final Map<String, String> metaData,
                final List<STOCHDataFast> indicatorData) {
    super(metaData, indicatorData);
  }

  /**
   * Creates {@code STOCHF} instance from json.
   *
   * @param interval specifies how to interpret the date key to the data json object
   * @param json string to parse
   * @return STOCHF instance
   */
  public static STOCHF from(Interval interval, String json) {
    Parser parser = new Parser(interval);
    return parser.parseJson(json);
  }

  /**
   * Helper class for parsing json to {@code STOCHF}.
   *
   * @see TechnicalIndicatorParser
   * @see JsonParser
   */
  private static class Parser extends TechnicalIndicatorParser<STOCHF> {

    public Parser(Interval interval) {
      super(interval);
    }

    @Override
    String getIndicatorKey() {
      return "Technical Analysis: STOCHF";
    }

    @Override
    STOCHF resolve(Map<String, String> metaData, Map<String, Map<String, String>> indicatorData) {
      List<STOCHDataFast> indicators = new ArrayList<>();
      indicatorData.forEach((key, values) -> indicators.add(new STOCHDataFast(
              resolveDate(key),
              Double.parseDouble(values.get("FastK")),
              Double.parseDouble(values.get("FastD"))
      )));
      return new STOCHF(metaData, indicators);
    }
  }
}


text:
import { get } from '@ember/object';
import { settled } from '@ember/test-helpers';

import { module, test } from 'qunit';
import { resolve } from 'rsvp';

import { setupTest } from 'ember-qunit';

import Adapter from '@ember-data/adapter';
import JSONAPIAdapter from '@ember-data/adapter/json-api';
import Model, { attr, belongsTo, hasMany } from '@ember-data/model';
import JSONAPISerializer from '@ember-data/serializer/json-api';

class Person extends Model {
  @attr()
  name;
  @belongsTo('tag', { async: false, inverse: 'people' })
  tag;
}

class Tag extends Model {
  @hasMany('person', { async: false, inverse: 'tag' })
  people;
}

class Tool extends Model {
  @belongsTo('person', { async: false, inverse: null })
  person;
}

module('unit/record-array - RecordArray', function (hooks) {
  setupTest(hooks);
  let store;

  hooks.beforeEach(function () {
    let { owner } = this;

    owner.register('model:person', Person);
    owner.register('model:tag', Tag);
    owner.register('model:tool', Tool);
    owner.register('adapter:application', JSONAPIAdapter.extend());
    owner.register('serializer:application', JSONAPISerializer.extend());

    store = owner.lookup('service:store');
  });

  test('a record array is backed by records', async function (assert) {
    assert.expect(3);
    this.owner.register(
      'adapter:application',
      Adapter.extend({
        shouldBackgroundReloadRecord() {
          return false;
        },
      })
    );

    store.push({
      data: [
        {
          type: 'person',
          id: '1',
          attributes: {
            name: 'Scumbag Dale',
          },
        },
        {
          type: 'person',
          id: '2',
          attributes: {
            name: 'Scumbag Katz',
          },
        },
        {
          type: 'person',
          id: '3',
          attributes: {
            name: 'Scumbag Bryn',
          },
        },
      ],
    });

    let records = await store.findByIds('person', [1, 2, 3]);
    let expectedResults = {
      data: [
        { id: '1', type: 'person', attributes: { name: 'Scumbag Dale' } },
        { id: '2', type: 'person', attributes: { name: 'Scumbag Katz' } },
        { id: '3', type: 'person', attributes: { name: 'Scumbag Bryn' } },
      ],
    };

    for (let i = 0, l = expectedResults.data.length; i < l; i++) {
      let {
        id,
        attributes: { name },
      } = expectedResults.data[i];

      assert.deepEqual(
        records[i].getProperties('id', 'name'),
        { id, name },
        'a record array materializes objects on demand'
      );
    }
  });

  test('acts as a live query', async function (assert) {
    let recordArray = store.peekAll('person');

    store.push({
      data: {
        type: 'person',
        id: '1',
        attributes: {
          name: 'wycats',
        },
      },
    });

    await settled();

    assert.strictEqual(get(recordArray, 'lastObject.name'), 'wycats');

    store.push({
      data: {
        type: 'person',
        id: '2',
        attributes: {
          name: 'brohuda',
        },
      },
    });

    await settled();

    assert.strictEqual(get(recordArray, 'lastObject.name'), 'brohuda');
  });

  test('acts as a live query (normalized names)', async function (assert) {
    this.owner.register('model:Person', Person);

    let recordArray = store.peekAll('Person');
    let otherRecordArray = store.peekAll('person');

    assert.strictEqual(recordArray, otherRecordArray, 'Person and person are the same record-array');

    store.push({
      data: {
        type: 'Person',
        id: '1',
        attributes: {
          name: 'John Churchill',
        },
      },
    });

    await settled();

    assert.deepEqual(recordArray.mapBy('name'), ['John Churchill']);

    store.push({
      data: {
        type: 'Person',
        id: '2',
        attributes: {
          name: 'Winston Churchill',
        },
      },
    });

    await settled();

    assert.deepEqual(recordArray.mapBy('name'), ['John Churchill', 'Winston Churchill']);
  });

  test('stops updating when destroyed', async function (assert) {
    assert.expect(3);

    let recordArray = store.peekAll('person');

    store.push({
      data: {
        type: 'person',
        id: '1',
        attributes: {
          name: 'wycats',
        },
      },
    });

    await settled();

    recordArray.destroy();

    await settled();

    assert.strictEqual(recordArray.get('length'), 0, 'Has no more records');
    store.push({
      data: {
        type: 'person',
        id: '2',
        attributes: {
          name: 'brohuda',
        },
      },
    });

    await settled();

    assert.strictEqual(recordArray.get('length'), 0, 'length has not been updated');
    assert.strictEqual(recordArray.get('content'), null, 'content has not been updated');
  });

  test('a loaded record is removed from a record array when it is deleted', async function (assert) {
    assert.expect(5);
    this.owner.register(
      'adapter:application',
      Adapter.extend({
        deleteRecord() {
          return resolve({ data: null });
        },
        shouldBackgroundReloadRecord() {
          return false;
        },
      })
    );

    store.push({
      data: [
        {
          type: 'person',
          id: '1',
          attributes: {
            name: 'Scumbag Dale',
          },
        },
        {
          type: 'person',
          id: '2',
          attributes: {
            name: 'Scumbag Katz',
          },
        },
        {
          type: 'person',
          id: '3',
          attributes: {
            name: 'Scumbag Bryn',
          },
        },
        {
          type: 'tag',
          id: '1',
          attributes: {},
        },
      ],
    });

    let scumbag = await store.findRecord('person', 1);
    let tag = await store.findRecord('tag', 1);
    let recordArray = tag.get('people');

    recordArray.addObject(scumbag);

    assert.strictEqual(scumbag.get('tag'), tag, "precond - the scumbag's tag has been set");
    assert.strictEqual(get(recordArray, 'length'), 1, 'precond - record array has one item');
    assert.strictEqual(get(recordArray.objectAt(0), 'name'), 'Scumbag Dale', 'item at index 0 is record with id 1');

    scumbag.deleteRecord();

    assert.strictEqual(get(recordArray, 'length'), 1, 'record is still in the record array until it is saved');

    await scumbag.save();

    assert.strictEqual(get(recordArray, 'length'), 0, 'record is removed from the array when it is saved');
  });

  test("a loaded record is not removed from a record array when it is deleted even if the belongsTo side isn't defined", async function (assert) {
    class Person extends Model {
      @attr()
      name;
    }

    class Tag extends Model {
      @hasMany('person', { async: false, inverse: null })
      people;
    }

    this.owner.unregister('model:person');
    this.owner.unregister('model:tag');
    this.owner.register('model:person', Person);
    this.owner.register('model:tag', Tag);
    this.owner.register(
      'adapter:application',
      Adapter.extend({
        deleteRecord() {
          return resolve({ data: null });
        },
      })
    );

    store.push({
      data: [
        {
          type: 'person',
          id: '1',
          attributes: {
            name: 'Scumbag Tom',
          },
        },
        {
          type: 'tag',
          id: '1',
          relationships: {
            people: {
              data: [{ type: 'person', id: '1' }],
            },
          },
        },
      ],
    });

    let scumbag = store.peekRecord('person', 1);
    let tag = store.peekRecord('tag', 1);

    scumbag.deleteRecord();

    assert.strictEqual(tag.get('people.length'), 1, 'record is not removed from the record array');
    assert.strictEqual(tag.get('people').objectAt(0), scumbag, 'tag still has the scumbag');
  });

  test("a loaded record is not removed from both the record array and from the belongs to, even if the belongsTo side isn't defined", async function (assert) {
    this.owner.register(
      'adapter:application',
      Adapter.extend({
        deleteRecord() {
          return resolve({ data: null });
        },
      })
    );

    store.push({
      data: [
        {
          type: 'person',
          id: '1',
          attributes: {
            name: 'Scumbag Tom',
          },
        },
        {
          type: 'tag',
          id: '1',
          relationships: {
            people: {
              data: [{ type: 'person', id: '1' }],
            },
          },
        },
        {
          type: 'tool',
          id: '1',
          relationships: {
            person: {
              data: { type: 'person', id: '1' },
            },
          },
        },
      ],
    });

    let scumbag = store.peekRecord('person', 1);
    let tag = store.peekRecord('tag', 1);
    let tool = store.peekRecord('tool', 1);

    assert.strictEqual(tag.get('people.length'), 1, 'record is in the record array');
    assert.strictEqual(tool.get('person'), scumbag, 'the tool belongs to the record');

    scumbag.deleteRecord();

    assert.strictEqual(tag.get('people.length'), 1, 'record is stil in the record array');
    assert.strictEqual(tool.get('person'), scumbag, 'the tool still belongs to the record');
  });

  // GitHub Issue #168
  test('a newly created record is removed from a record array when it is deleted', async function (assert) {
    let recordArray = store.peekAll('person');
    let scumbag = store.createRecord('person', {
      name: 'Scumbag Dale',
    });

    await settled();
    assert.strictEqual(get(recordArray, 'length'), 1, 'precond - record array already has the first created item');

    store.createRecord('person', { name: 'p1' });
    store.createRecord('person', { name: 'p2' });
    store.createRecord('person', { name: 'p3' });

    await settled();

    assert.strictEqual(get(recordArray, 'length'), 4, 'precond - record array has the created item');
    assert.strictEqual(recordArray.objectAt(0), scumbag, 'item at index 0 is record with id 1');

    scumbag.deleteRecord();

    assert.strictEqual(get(recordArray, 'length'), 3, 'record array no longer has the created item');
  });

  test("a record array returns undefined when asking for a member outside of its content Array's range", async function (assert) {
    store.push({
      data: [
        {
          type: 'person',
          id: '1',
          attributes: {
            name: 'Scumbag Dale',
          },
        },
        {
          type: 'person',
          id: '2',
          attributes: {
            name: 'Scumbag Katz',
          },
        },
        {
          type: 'person',
          id: '3',
          attributes: {
            name: 'Scumbag Bryn',
          },
        },
      ],
    });

    let recordArray = store.peekAll('person');

    assert.strictEqual(recordArray.objectAt(20), undefined, 'objects outside of the range just return undefined');
  });

  // This tests for a bug in the recordCache, where the records were being cached in the incorrect order.
  test('a record array should be able to be enumerated in any order', async function (assert) {
    store.push({
      data: [
        {
          type: 'person',
          id: '1',
          attributes: {
            name: 'Scumbag Dale',
          },
        },
        {
          type: 'person',
          id: '2',
          attributes: {
            name: 'Scumbag Katz',
          },
        },
        {
          type: 'person',
          id: '3',
          attributes: {
            name: 'Scumbag Bryn',
          },
        },
      ],
    });

    let recordArray = store.peekAll('person');

    assert.strictEqual(get(recordArray.objectAt(2), 'id'), '3', 'should retrieve correct record at index 2');
    assert.strictEqual(get(recordArray.objectAt(1), 'id'), '2', 'should retrieve correct record at index 1');
    assert.strictEqual(get(recordArray.objectAt(0), 'id'), '1', 'should retrieve correct record at index 0');
  });

  test("an AdapterPopulatedRecordArray knows if it's loaded or not", async function (assert) {
    assert.expect(1);
    let adapter = store.adapterFor('person');

    adapter.query = function (store, type, query, recordArray) {
      return resolve({
        data: [
          { id: '1', type: 'person', attributes: { name: 'Scumbag Dale' } },
          { id: '2', type: 'person', attributes: { name: 'Scumbag Katz' } },
          { id: '3', type: 'person', attributes: { name: 'Scumbag Bryn' } },
        ],
      });
    };

    let people = await store.query('person', { page: 1 });

    assert.true(get(people, 'isLoaded'), 'The array is now loaded');
  });
});


text:
import { delegateInit } from './BaseShape';
import { Rectangle } from './Rectangle';

const ENTITY_FIELD_NAME = 'SwitchCase';

export default delegateInit(Rectangle, ENTITY_FIELD_NAME);


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/buttonSendAll">

        <ListView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="@dimen/spacing_normal"
            android:id="@+id/listOfflineSave" />

    </LinearLayout>

    <Button
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:layout_margin="@dimen/spacing_normal"
        android:background="@drawable/button_default_bg"
        style="@style/DefaultButtonText"
        android:layout_gravity="center"
        android:gravity="center"
        android:layout_alignParentBottom="true"
        android:text="@string/txtSendAll"
        android:id="@+id/buttonSendAll"
            />
</RelativeLayout>


text:
package org.hswebframework.web.dao.mybatis.dynamic;

import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class DynamicDataSourceSqlSessionFactoryBuilder extends SqlSessionFactoryBuilder {
    @Override
    public SqlSessionFactory build(Configuration config) {
        return new DynamicSqlSessionFactory(config);
    }
}


text:
layout: post
title: OData Service Validation Tool Update
date: 2011-06-10 17:23:08.000000000 +08:00
categories:
- OData tools
tags: []
status: publish
type: post
published: true
author: OData.org Archive
---

We pushed a new update to the OData Service Validation Tool. As you know we are updating the service every 2 weeks. Below is what's new in this update:

Added 5 new JSON rules. Including the new rules pushed 2 weeks ago we now have a total of 16 JSON rules

Fixed test result classifications for MustNot and ShouldNot requirement levels

Added Rule Extension Framework for code rules.

We have been focusing on structural rules so far. We added an extension mechanism to the rule engine to be able to add code based (semantic) rules. There are no such rules in the system yet but we are working on bringing such rules in to the rule engine and the UI.

In the meantime, we are also actively working towards open sourcing the tool. We are sorry for the lack of updates on this front but we are committed to making the tool open source and we are waiting for the legal process to be completed. We investigated our options and are currently working with the legal department to create the most appropriate contribution model so that it's also possible for the community to contribute rules.

There is no ETA for the release at the moment but we are in final stages of obtaining legal approvals. We will immediately announce when the source code is available.

Thank you for your continued feedback and interest. We are all ears on the OData Mailing List. Please let us know if you have any feedback, questions and/or suggestions.


text:
/****************************************************************************************
 * Filename:	platform-defs.c
 * Author:		Craig Paton
 * Date:			Apr 2004
 *
 * Implementation of all of the core platform structures that are used extnsively
 * through the platform.  Functions are given for creation and manipluation of these
 * strucutres
 * **************************************************************************************/

#include "platform-defs.h"
#include "API/API.h"

/* initialises the platform description strucutre that is maintained by the AMS when
 * the platform is bootstrapped
 *
 * desc - the description structure that is to be initialised, it must have been allocated
 * 	before calling this function
 */
void InitPlatformDescription(PlatformDescription* desc) {
	desc->name =NULL;
	desc->services = g_array_new(FALSE, FALSE, sizeof(PlatformServiceDescription*));
}

/* initialises a DF service description structure
 *
 * desc - DF description object to be initialised which must have been previously allocated
 */
void DFServiceDescriptionInit(DFServiceDescription* desc) {
	desc->name = NULL;
	desc->type = NULL;
	desc->protocols = g_array_new(FALSE, FALSE, sizeof(GString*));
	desc->ontologies = g_array_new(FALSE, FALSE, sizeof(GString*));
	desc->languages = g_array_new(FALSE, FALSE, sizeof(GString*));
}

/* initialises a DF entry that is used within the DF registry
 *
 * desc - the description object to be initialised that must have been previously allocated
 */
void AgentDFDescriptionInit(AgentDFDescription* desc) {
	desc->id = NULL;
	desc->services = g_array_new(FALSE, FALSE, sizeof(DFServiceDescription*));
	desc->protocols = g_array_new(FALSE, FALSE, sizeof(GString*));
	desc->ontologies = g_array_new(FALSE, FALSE, sizeof(GString*));
	desc->languages = g_array_new(FALSE, FALSE, sizeof(GString*));
}

/* initialises an agent configuration strucutre that is required by all agents and platform
 * services
 *
 * config - structure that needs initialising which must have been allocated previously
 */
void AgentConfigurationInit(AgentConfiguration* config) {
	config->connection = NULL;
	config->mainLoop = NULL;
	config->baseService = NULL;
	config->identifier = NULL;
	config->messageQueue = NULL;
	config->MTSAddress = NULL;
	config->AMSAddress = NULL;
	config->DFAddress = NULL;
	config->platformName = NULL;
	config->DFEntry = g_new(AgentDFDescription,1);
	AgentDFDescriptionInit(config->DFEntry);
	config->conversationIDCounter = 0;
	config->callbackFunction = NULL;
}

//setter functions
void AgentConfigurationSetID(AgentConfiguration* config, AID* id) {
	config->identifier = id;
}

void AgentConfigurationSetMainLoop(AgentConfiguration* config, GMainLoop* loop) {
	config->mainLoop = loop;
}
void AgentConfigurationSetConnection(AgentConfiguration* config, DBusConnection* conn) {
	config->connection = conn;
}

void AgentConfigurationSetBaseService(AgentConfiguration* config, gchar* service) {
	config->baseService = g_string_new(service);
}

/* Initialises an ACL message structure that is used for agent communication
 *
 * msg - structure that should be initialised that must have been allocated previously
 */
void ACLMessageInit(ACLMessage* msg) {
	msg->performative = NULL;
	msg->sender = NULL;
	msg->receivers = g_array_new(FALSE, FALSE, sizeof(AID*));
	msg->replyTo = g_array_new(FALSE, FALSE, sizeof(AID*));
	msg->content = NULL;
	msg->language = NULL;
	msg->encoding = NULL;
	msg->ontology = NULL;
	msg->protocol = NULL;
	msg->conversationID = NULL;
	msg->replyWith = NULL;
	msg->inReplyTo = NULL;
	msg->replyBy = NULL;
}

/* reclaims memory used in a FIPA-ACL message
 *
 * msg - the message that should be freed
 */
void ACLMessageFree(ACLMessage msg) {
	g_array_free(msg.receivers, TRUE);
	g_array_free(msg.replyTo, TRUE);

	if (msg.sender !=  NULL) AIDFree(*msg.sender);

	//free all of the strings
	if (msg.performative !=  NULL) g_string_free(msg.performative, TRUE);
	if (msg.content !=  NULL) g_string_free(msg.content, TRUE);
	if (msg.language !=  NULL) g_string_free(msg.language, TRUE);
	if (msg.encoding !=  NULL) g_string_free(msg.encoding, TRUE);
	if (msg.ontology !=  NULL) g_string_free(msg.ontology, TRUE);
	if (msg.protocol !=  NULL) g_string_free(msg.protocol, TRUE);
	if (msg.conversationID !=  NULL) g_string_free(msg.conversationID, TRUE);
	if (msg.replyWith !=  NULL) g_string_free(msg.replyWith, TRUE);
	if (msg.inReplyTo !=  NULL) g_string_free(msg.inReplyTo, TRUE);
	if (msg.replyBy !=  NULL) g_string_free(msg.replyBy, TRUE);
}

/* initiailises a envelope that is used by the interaction layer for transporting messages
 * to the correct agents
 *
 * envelope - the structure that should be initialised which have been previously allocated
 */
void ACLEnvelopeInit(ACLEnvelope* envelope) {
	envelope->to = g_array_new(FALSE, FALSE, sizeof(AID*));
	envelope->from = NULL;
	envelope->aclRepresentation = NULL;
	envelope->intendedReceiver = NULL;
}

/* initialises and agent message structure that is used for all agent messages sent to
 * the interaction layer
 *
 * message - the structure to be initialised that must have been previously allocated
 */
void AgentMessageInit(AgentMessage* message) {
	message->envelope = NULL;
	message->payload = NULL;
}


text:
`pod "Mixpanel-OSX-Community", :git => "https://github.com/orta/mixpanel-osx-unofficial.git"`

This is an unofficial port of the Mixpanel API to Cocoa, its built with cocoapods in mind.
You can install this manually, the only framework you'll need is SystemConfiguration I think.

Ideally I'll keep this up to date in order to keep [ARAnalytics](https://github.com/orta/ARAnalytics/) relevant. As I use Mixpanel personally. If you work at Mixpanel and would like to take over, that'd be super-ace. Thanks.

# Initializing Mixpanel #
The first thing you need to do is initialize Mixpanel with your project token.
We recommend doing this in `applicationDidFinishLaunching:` or
`application:didFinishLaunchingWithOptions` in your Application delegate.

	- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

	    // Override point for customization after application launch.
		[Mixpanel sharedInstanceWithToken:MIXPANEL_TOKEN];

	    // Add the view controller's view to the window and display.
	    [window addSubview:viewController.view];
	    [window makeKeyAndVisible];
	    return YES;
	}

# Tracking Events #
After initializing the Mixpanel object, you are ready to track events. This can
be done with the following code snippet:

    Mixpanel *mixpanel = [Mixpanel sharedInstance];
    [mixpanel track:@"Clicked Button"];

If you want to add properties to the event you can do the following:

    Mixpanel *mixpanel = [Mixpanel sharedInstance];
    [mixpanel track:@"Player Create"
         properties:[NSDictionary dictionaryWithObjectsAndKeys:@"Female", @"Gender", @"Premium", @"Plan", nil]];

# Setting People Properties #
Use the `people` accessor on the Mixpanel object to make calls to the Mixpanel
People API. Unlike Mixpanel Engagement, you must explicitly set the distinct ID
for the current user in Mixpanel People.

    Mixpanel *mixpanel = [Mixpanel sharedInstance];
    [mixpanel.people identify:@"user123"];
    [mixpanel.people set:@"Bought Premium Plan" to:[NSDate date]];

To send your users push notifications through Mixpanel People, register device
tokens as follows.

    - (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken {
        [self.mixpanel.people addPushDeviceToken:devToken];
    }

# ARC #
The Mixpanel library supports ARC as of v2.1.0.

For versions before v2.1.0:
To integrate with an ARC project: Go to Project > Target > Build Phases, double-click on
each Mixpanel file and add the flag: `-fno-objc-arc`.

# Logging #
You can turn on Mixpanel logging by adding the following Preprocessor Macros in
Build Settings: `MIXPANEL_LOG=1` and `MIXPANEL_DEBUG=1`. Setting
`MIXPANEL_LOG=1` will cause the Mixpanel library to log tracked events and set
People properties. Setting `MIXPANEL_DEBUG=1` will cause Mixpanel to log
everything it's doing—queuing, formatting and uploading data—in a very
fine-grained way, and is useful for understanding how the library works and
debugging issues.

# Further Documentation #
1. [Events iOS Library Documentation](https://mixpanel.com/docs/integration-libraries/iphone)
2. [People iOS Library Documentation](https://mixpanel.com/docs/people-analytics/iphone)
3. [Full Headerdoc API Reference](https://mixpanel.com/site_media/doctyl/uploads/iPhone-spec/Classes/Mixpanel/index.html)

[copy]: https://raw.github.com/mixpanel/mixpanel-iphone/master/Docs/Images/copy.png "Copy"
[project]: https://raw.github.com/mixpanel/mixpanel-iphone/master/Docs/Images/project.png "Project"


text:
title: Textarea Autosize React component
components: TextareaAutosize
---

# テキストエリアの自動サイズ調整

コンテンツとともに大きくなるReactのテキストエリアコンポーネント。

- [2.1 kB gzipped](/size-snapshot).

## 空のテキストエリア

{{"demo": "pages/components/textarea-autosize/EmptyTextarea.js"}}

## 最小高さ

{{"demo": "pages/components/textarea-autosize/MinHeightTextarea.js"}}

## 最大高さ

{{"demo": "pages/components/textarea-autosize/MaxHeightTextarea.js"}}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycol. Fl. Japan 2(4): 153 (1955)

#### Original name
Stereum harmandii Lloyd, 1913

### Remarks
null