text:
namespace lms {

namespace {

const ::google::protobuf::Descriptor* MetaFile_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
  MetaFile_reflection_ = NULL;
const ::google::protobuf::Descriptor* MetaFile_Channel_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
  MetaFile_Channel_reflection_ = NULL;

}  // namespace

void protobuf_AssignDesc_recording_5fmeta_2eproto() {
  protobuf_AddDesc_recording_5fmeta_2eproto();
  const ::google::protobuf::FileDescriptor* file =
    ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName(
      "recording_meta.proto");
  GOOGLE_CHECK(file != NULL);
  MetaFile_descriptor_ = file->message_type(0);
  static const int MetaFile_offsets_[1] = {
    GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetaFile, channels_),
  };
  MetaFile_reflection_ =
    new ::google::protobuf::internal::GeneratedMessageReflection(
      MetaFile_descriptor_,
      MetaFile::default_instance_,
      MetaFile_offsets_,
      GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetaFile, _has_bits_[0]),
      GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetaFile, _unknown_fields_),
      -1,
      ::google::protobuf::DescriptorPool::generated_pool(),
      ::google::protobuf::MessageFactory::generated_factory(),
      sizeof(MetaFile));
  MetaFile_Channel_descriptor_ = MetaFile_descriptor_->nested_type(0);
  static const int MetaFile_Channel_offsets_[3] = {
    GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetaFile_Channel, name_),
    GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetaFile_Channel, type_),
    GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetaFile_Channel, writing_modules_),
  };
  MetaFile_Channel_reflection_ =
    new ::google::protobuf::internal::GeneratedMessageReflection(
      MetaFile_Channel_descriptor_,
      MetaFile_Channel::default_instance_,
      MetaFile_Channel_offsets_,
      GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetaFile_Channel, _has_bits_[0]),
      GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetaFile_Channel, _unknown_fields_),
      -1,
      ::google::protobuf::DescriptorPool::generated_pool(),
      ::google::protobuf::MessageFactory::generated_factory(),
      sizeof(MetaFile_Channel));
}

namespace {

GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);
inline void protobuf_AssignDescriptorsOnce() {
  ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,
                 &protobuf_AssignDesc_recording_5fmeta_2eproto);
}

void protobuf_RegisterTypes(const ::std::string&) {
  protobuf_AssignDescriptorsOnce();
  ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
    MetaFile_descriptor_, &MetaFile::default_instance());
  ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
    MetaFile_Channel_descriptor_, &MetaFile_Channel::default_instance());
}

}  // namespace

void protobuf_ShutdownFile_recording_5fmeta_2eproto() {
  delete MetaFile::default_instance_;
  delete MetaFile_reflection_;
  delete MetaFile_Channel::default_instance_;
  delete MetaFile_Channel_reflection_;
}

void protobuf_AddDesc_recording_5fmeta_2eproto() {
  static bool already_here = false;
  if (already_here) return;
  already_here = true;
  GOOGLE_PROTOBUF_VERIFY_VERSION;

  ::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
    "\n\024recording_meta.proto\022\003lms\"s\n\010MetaFile\022"
    "\'\n\010channels\030\001 \003(\0132\025.lms.MetaFile.Channel"
    "\032>\n\007Channel\022\014\n\004name\030\001 \001(\t\022\014\n\004type\030\002 \001(\t\022"
    "\027\n\017writing_modules\030\003 \003(\t", 144);
  ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
    "recording_meta.proto", &protobuf_RegisterTypes);
  MetaFile::default_instance_ = new MetaFile();
  MetaFile_Channel::default_instance_ = new MetaFile_Channel();
  MetaFile::default_instance_->InitAsDefaultInstance();
  MetaFile_Channel::default_instance_->InitAsDefaultInstance();
  ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_recording_5fmeta_2eproto);
}

// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer_recording_5fmeta_2eproto {
  StaticDescriptorInitializer_recording_5fmeta_2eproto() {
    protobuf_AddDesc_recording_5fmeta_2eproto();
  }
} static_descriptor_initializer_recording_5fmeta_2eproto_;

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

#ifndef _MSC_VER
const int MetaFile_Channel::kNameFieldNumber;
const int MetaFile_Channel::kTypeFieldNumber;
const int MetaFile_Channel::kWritingModulesFieldNumber;
#endif  // !_MSC_VER

MetaFile_Channel::MetaFile_Channel()
  : ::google::protobuf::Message() {
  SharedCtor();
  // @@protoc_insertion_point(constructor:lms.MetaFile.Channel)
}

void MetaFile_Channel::InitAsDefaultInstance() {
}

MetaFile_Channel::MetaFile_Channel(const MetaFile_Channel& from)
  : ::google::protobuf::Message() {
  SharedCtor();
  MergeFrom(from);
  // @@protoc_insertion_point(copy_constructor:lms.MetaFile.Channel)
}

void MetaFile_Channel::SharedCtor() {
  ::google::protobuf::internal::GetEmptyString();
  _cached_size_ = 0;
  name_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
  type_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
  ::memset(_has_bits_, 0, sizeof(_has_bits_));
}

MetaFile_Channel::~MetaFile_Channel() {
  // @@protoc_insertion_point(destructor:lms.MetaFile.Channel)
  SharedDtor();
}

void MetaFile_Channel::SharedDtor() {
  if (name_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
    delete name_;
  }
  if (type_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
    delete type_;
  }
  if (this != default_instance_) {
  }
}

void MetaFile_Channel::SetCachedSize(int size) const {
  GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
  _cached_size_ = size;
  GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* MetaFile_Channel::descriptor() {
  protobuf_AssignDescriptorsOnce();
  return MetaFile_Channel_descriptor_;
}

const MetaFile_Channel& MetaFile_Channel::default_instance() {
  if (default_instance_ == NULL) protobuf_AddDesc_recording_5fmeta_2eproto();
  return *default_instance_;
}

MetaFile_Channel* MetaFile_Channel::default_instance_ = NULL;

MetaFile_Channel* MetaFile_Channel::New() const {
  return new MetaFile_Channel;
}

void MetaFile_Channel::Clear() {
  if (_has_bits_[0 / 32] & 3) {
    if (has_name()) {
      if (name_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
        name_->clear();
      }
    }
    if (has_type()) {
      if (type_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
        type_->clear();
      }
    }
  }
  writing_modules_.Clear();
  ::memset(_has_bits_, 0, sizeof(_has_bits_));
  mutable_unknown_fields()->Clear();
}

bool MetaFile_Channel::MergePartialFromCodedStream(
    ::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure
  ::google::protobuf::uint32 tag;
  // @@protoc_insertion_point(parse_start:lms.MetaFile.Channel)
  for (;;) {
    ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
    tag = p.first;
    if (!p.second) goto handle_unusual;
    switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
      // optional string name = 1;
      case 1: {
        if (tag == 10) {
          DO_(::google::protobuf::internal::WireFormatLite::ReadString(
                input, this->mutable_name()));
          ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
            this->name().data(), this->name().length(),
            ::google::protobuf::internal::WireFormat::PARSE,
            "name");
        } else {
          goto handle_unusual;
        }
        if (input->ExpectTag(18)) goto parse_type;
        break;
      }

      // optional string type = 2;
      case 2: {
        if (tag == 18) {
         parse_type:
          DO_(::google::protobuf::internal::WireFormatLite::ReadString(
                input, this->mutable_type()));
          ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
            this->type().data(), this->type().length(),
            ::google::protobuf::internal::WireFormat::PARSE,
            "type");
        } else {
          goto handle_unusual;
        }
        if (input->ExpectTag(26)) goto parse_writing_modules;
        break;
      }

      // repeated string writing_modules = 3;
      case 3: {
        if (tag == 26) {
         parse_writing_modules:
          DO_(::google::protobuf::internal::WireFormatLite::ReadString(
                input, this->add_writing_modules()));
          ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
            this->writing_modules(this->writing_modules_size() - 1).data(),
            this->writing_modules(this->writing_modules_size() - 1).length(),
            ::google::protobuf::internal::WireFormat::PARSE,
            "writing_modules");
        } else {
          goto handle_unusual;
        }
        if (input->ExpectTag(26)) goto parse_writing_modules;
        if (input->ExpectAtEnd()) goto success;
        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:lms.MetaFile.Channel)
  return true;
failure:
  // @@protoc_insertion_point(parse_failure:lms.MetaFile.Channel)
  return false;
#undef DO_
}

void MetaFile_Channel::SerializeWithCachedSizes(
    ::google::protobuf::io::CodedOutputStream* output) const {
  // @@protoc_insertion_point(serialize_start:lms.MetaFile.Channel)
  // optional string name = 1;
  if (has_name()) {
    ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
      this->name().data(), this->name().length(),
      ::google::protobuf::internal::WireFormat::SERIALIZE,
      "name");
    ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
      1, this->name(), output);
  }

  // optional string type = 2;
  if (has_type()) {
    ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
      this->type().data(), this->type().length(),
      ::google::protobuf::internal::WireFormat::SERIALIZE,
      "type");
    ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
      2, this->type(), output);
  }

  // repeated string writing_modules = 3;
  for (int i = 0; i < this->writing_modules_size(); i++) {
  ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
    this->writing_modules(i).data(), this->writing_modules(i).length(),
    ::google::protobuf::internal::WireFormat::SERIALIZE,
    "writing_modules");
    ::google::protobuf::internal::WireFormatLite::WriteString(
      3, this->writing_modules(i), output);
  }

  if (!unknown_fields().empty()) {
    ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
        unknown_fields(), output);
  }
  // @@protoc_insertion_point(serialize_end:lms.MetaFile.Channel)
}

::google::protobuf::uint8* MetaFile_Channel::SerializeWithCachedSizesToArray(
    ::google::protobuf::uint8* target) const {
  // @@protoc_insertion_point(serialize_to_array_start:lms.MetaFile.Channel)
  // optional string name = 1;
  if (has_name()) {
    ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
      this->name().data(), this->name().length(),
      ::google::protobuf::internal::WireFormat::SERIALIZE,
      "name");
    target =
      ::google::protobuf::internal::WireFormatLite::WriteStringToArray(
        1, this->name(), target);
  }

  // optional string type = 2;
  if (has_type()) {
    ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
      this->type().data(), this->type().length(),
      ::google::protobuf::internal::WireFormat::SERIALIZE,
      "type");
    target =
      ::google::protobuf::internal::WireFormatLite::WriteStringToArray(
        2, this->type(), target);
  }

  // repeated string writing_modules = 3;
  for (int i = 0; i < this->writing_modules_size(); i++) {
    ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
      this->writing_modules(i).data(), this->writing_modules(i).length(),
      ::google::protobuf::internal::WireFormat::SERIALIZE,
      "writing_modules");
    target = ::google::protobuf::internal::WireFormatLite::
      WriteStringToArray(3, this->writing_modules(i), target);
  }

  if (!unknown_fields().empty()) {
    target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
        unknown_fields(), target);
  }
  // @@protoc_insertion_point(serialize_to_array_end:lms.MetaFile.Channel)
  return target;
}

int MetaFile_Channel::ByteSize() const {
  int total_size = 0;

  if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
    // optional string name = 1;
    if (has_name()) {
      total_size += 1 +
        ::google::protobuf::internal::WireFormatLite::StringSize(
          this->name());
    }

    // optional string type = 2;
    if (has_type()) {
      total_size += 1 +
        ::google::protobuf::internal::WireFormatLite::StringSize(
          this->type());
    }

  }
  // repeated string writing_modules = 3;
  total_size += 1 * this->writing_modules_size();
  for (int i = 0; i < this->writing_modules_size(); i++) {
    total_size += ::google::protobuf::internal::WireFormatLite::StringSize(
      this->writing_modules(i));
  }

  if (!unknown_fields().empty()) {
    total_size +=
      ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
        unknown_fields());
  }
  GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
  _cached_size_ = total_size;
  GOOGLE_SAFE_CONCURRENT_WRITES_END();
  return total_size;
}

void MetaFile_Channel::MergeFrom(const ::google::protobuf::Message& from) {
  GOOGLE_CHECK_NE(&from, this);
  const MetaFile_Channel* source =
    ::google::protobuf::internal::dynamic_cast_if_available<const MetaFile_Channel*>(
      &from);
  if (source == NULL) {
    ::google::protobuf::internal::ReflectionOps::Merge(from, this);
  } else {
    MergeFrom(*source);
  }
}

void MetaFile_Channel::MergeFrom(const MetaFile_Channel& from) {
  GOOGLE_CHECK_NE(&from, this);
  writing_modules_.MergeFrom(from.writing_modules_);
  if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
    if (from.has_name()) {
      set_name(from.name());
    }
    if (from.has_type()) {
      set_type(from.type());
    }
  }
  mutable_unknown_fields()->MergeFrom(from.unknown_fields());
}

void MetaFile_Channel::CopyFrom(const ::google::protobuf::Message& from) {
  if (&from == this) return;
  Clear();
  MergeFrom(from);
}

void MetaFile_Channel::CopyFrom(const MetaFile_Channel& from) {
  if (&from == this) return;
  Clear();
  MergeFrom(from);
}

bool MetaFile_Channel::IsInitialized() const {

  return true;
}

void MetaFile_Channel::Swap(MetaFile_Channel* other) {
  if (other != this) {
    std::swap(name_, other->name_);
    std::swap(type_, other->type_);
    writing_modules_.Swap(&other->writing_modules_);
    std::swap(_has_bits_[0], other->_has_bits_[0]);
    _unknown_fields_.Swap(&other->_unknown_fields_);
    std::swap(_cached_size_, other->_cached_size_);
  }
}

::google::protobuf::Metadata MetaFile_Channel::GetMetadata() const {
  protobuf_AssignDescriptorsOnce();
  ::google::protobuf::Metadata metadata;
  metadata.descriptor = MetaFile_Channel_descriptor_;
  metadata.reflection = MetaFile_Channel_reflection_;
  return metadata;
}

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

#ifndef _MSC_VER
const int MetaFile::kChannelsFieldNumber;
#endif  // !_MSC_VER

MetaFile::MetaFile()
  : ::google::protobuf::Message() {
  SharedCtor();
  // @@protoc_insertion_point(constructor:lms.MetaFile)
}

void MetaFile::InitAsDefaultInstance() {
}

MetaFile::MetaFile(const MetaFile& from)
  : ::google::protobuf::Message() {
  SharedCtor();
  MergeFrom(from);
  // @@protoc_insertion_point(copy_constructor:lms.MetaFile)
}

void MetaFile::SharedCtor() {
  _cached_size_ = 0;
  ::memset(_has_bits_, 0, sizeof(_has_bits_));
}

MetaFile::~MetaFile() {
  // @@protoc_insertion_point(destructor:lms.MetaFile)
  SharedDtor();
}

void MetaFile::SharedDtor() {
  if (this != default_instance_) {
  }
}

void MetaFile::SetCachedSize(int size) const {
  GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
  _cached_size_ = size;
  GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* MetaFile::descriptor() {
  protobuf_AssignDescriptorsOnce();
  return MetaFile_descriptor_;
}

const MetaFile& MetaFile::default_instance() {
  if (default_instance_ == NULL) protobuf_AddDesc_recording_5fmeta_2eproto();
  return *default_instance_;
}

MetaFile* MetaFile::default_instance_ = NULL;

MetaFile* MetaFile::New() const {
  return new MetaFile;
}

void MetaFile::Clear() {
  channels_.Clear();
  ::memset(_has_bits_, 0, sizeof(_has_bits_));
  mutable_unknown_fields()->Clear();
}

bool MetaFile::MergePartialFromCodedStream(
    ::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure
  ::google::protobuf::uint32 tag;
  // @@protoc_insertion_point(parse_start:lms.MetaFile)
  for (;;) {
    ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
    tag = p.first;
    if (!p.second) goto handle_unusual;
    switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
      // repeated .lms.MetaFile.Channel channels = 1;
      case 1: {
        if (tag == 10) {
         parse_channels:
          DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
                input, add_channels()));
        } else {
          goto handle_unusual;
        }
        if (input->ExpectTag(10)) goto parse_channels;
        if (input->ExpectAtEnd()) goto success;
        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:lms.MetaFile)
  return true;
failure:
  // @@protoc_insertion_point(parse_failure:lms.MetaFile)
  return false;
#undef DO_
}

void MetaFile::SerializeWithCachedSizes(
    ::google::protobuf::io::CodedOutputStream* output) const {
  // @@protoc_insertion_point(serialize_start:lms.MetaFile)
  // repeated .lms.MetaFile.Channel channels = 1;
  for (int i = 0; i < this->channels_size(); i++) {
    ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
      1, this->channels(i), output);
  }

  if (!unknown_fields().empty()) {
    ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
        unknown_fields(), output);
  }
  // @@protoc_insertion_point(serialize_end:lms.MetaFile)
}

::google::protobuf::uint8* MetaFile::SerializeWithCachedSizesToArray(
    ::google::protobuf::uint8* target) const {
  // @@protoc_insertion_point(serialize_to_array_start:lms.MetaFile)
  // repeated .lms.MetaFile.Channel channels = 1;
  for (int i = 0; i < this->channels_size(); i++) {
    target = ::google::protobuf::internal::WireFormatLite::
      WriteMessageNoVirtualToArray(
        1, this->channels(i), target);
  }

  if (!unknown_fields().empty()) {
    target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
        unknown_fields(), target);
  }
  // @@protoc_insertion_point(serialize_to_array_end:lms.MetaFile)
  return target;
}

int MetaFile::ByteSize() const {
  int total_size = 0;

  // repeated .lms.MetaFile.Channel channels = 1;
  total_size += 1 * this->channels_size();
  for (int i = 0; i < this->channels_size(); i++) {
    total_size +=
      ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
        this->channels(i));
  }

  if (!unknown_fields().empty()) {
    total_size +=
      ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
        unknown_fields());
  }
  GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
  _cached_size_ = total_size;
  GOOGLE_SAFE_CONCURRENT_WRITES_END();
  return total_size;
}

void MetaFile::MergeFrom(const ::google::protobuf::Message& from) {
  GOOGLE_CHECK_NE(&from, this);
  const MetaFile* source =
    ::google::protobuf::internal::dynamic_cast_if_available<const MetaFile*>(
      &from);
  if (source == NULL) {
    ::google::protobuf::internal::ReflectionOps::Merge(from, this);
  } else {
    MergeFrom(*source);
  }
}

void MetaFile::MergeFrom(const MetaFile& from) {
  GOOGLE_CHECK_NE(&from, this);
  channels_.MergeFrom(from.channels_);
  mutable_unknown_fields()->MergeFrom(from.unknown_fields());
}

void MetaFile::CopyFrom(const ::google::protobuf::Message& from) {
  if (&from == this) return;
  Clear();
  MergeFrom(from);
}

void MetaFile::CopyFrom(const MetaFile& from) {
  if (&from == this) return;
  Clear();
  MergeFrom(from);
}

bool MetaFile::IsInitialized() const {

  return true;
}

void MetaFile::Swap(MetaFile* other) {
  if (other != this) {
    channels_.Swap(&other->channels_);
    std::swap(_has_bits_[0], other->_has_bits_[0]);
    _unknown_fields_.Swap(&other->_unknown_fields_);
    std::swap(_cached_size_, other->_cached_size_);
  }
}

::google::protobuf::Metadata MetaFile::GetMetadata() const {
  protobuf_AssignDescriptorsOnce();
  ::google::protobuf::Metadata metadata;
  metadata.descriptor = MetaFile_descriptor_;
  metadata.reflection = MetaFile_reflection_;
  return metadata;
}

// @@protoc_insertion_point(namespace_scope)

}  // namespace lms

// @@protoc_insertion_point(global_scope)


text:
package net.minecraft.world.storage;

import java.util.concurrent.Callable;
import net.minecraft.crash.CrashReportCategory;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.BlockPos;
import net.minecraft.world.EnumDifficulty;
import net.minecraft.world.GameRules;
import net.minecraft.world.WorldSettings;
import net.minecraft.world.WorldType;

public class WorldInfo
{
    public static final EnumDifficulty DEFAULT_DIFFICULTY = EnumDifficulty.NORMAL;

    /** Holds the seed of the currently world. */
    private long randomSeed;
    private WorldType terrainType = WorldType.DEFAULT;
    private String generatorOptions = "";

    /** The spawn zone position X coordinate. */
    private int spawnX;

    /** The spawn zone position Y coordinate. */
    private int spawnY;

    /** The spawn zone position Z coordinate. */
    private int spawnZ;

    /** Total time for this world. */
    private long totalTime;

    /** The current world time in ticks, ranging from 0 to 23999. */
    private long worldTime;

    /** The last time the player was in this world. */
    private long lastTimePlayed;

    /** The size of entire save of current world on the disk, isn't exactly. */
    private long sizeOnDisk;
    private NBTTagCompound playerTag;
    private int dimension;

    /** The name of the save defined at world creation. */
    private String levelName;

    /** Introduced in beta 1.3, is the save version for future control. */
    private int saveVersion;
    private int cleanWeatherTime;

    /** True if it's raining, false otherwise. */
    private boolean raining;

    /** Number of ticks until next rain. */
    private int rainTime;

    /** Is thunderbolts failing now? */
    private boolean thundering;

    /** Number of ticks untils next thunderbolt. */
    private int thunderTime;

    /** The Game Type. */
    private WorldSettings.GameType theGameType;

    /**
     * Whether the map features (e.g. strongholds) generation is enabled or disabled.
     */
    private boolean mapFeaturesEnabled;

    /** Hardcore mode flag */
    private boolean hardcore;
    private boolean allowCommands;
    private boolean initialized;
    private EnumDifficulty difficulty;
    private boolean difficultyLocked;
    private double borderCenterX = 0.0D;
    private double borderCenterZ = 0.0D;
    private double borderSize = 6.0E7D;
    private long borderSizeLerpTime = 0L;
    private double borderSizeLerpTarget = 0.0D;
    private double borderSafeZone = 5.0D;
    private double borderDamagePerBlock = 0.2D;
    private int borderWarningDistance = 5;
    private int borderWarningTime = 15;
    private GameRules theGameRules = new GameRules();

    protected WorldInfo()
    {
    }

    public WorldInfo(NBTTagCompound nbt)
    {
        this.randomSeed = nbt.getLong("RandomSeed");

        if (nbt.hasKey("generatorName", 8))
        {
            String s = nbt.getString("generatorName");
            this.terrainType = WorldType.parseWorldType(s);

            if (this.terrainType == null)
            {
                this.terrainType = WorldType.DEFAULT;
            }
            else if (this.terrainType.isVersioned())
            {
                int i = 0;

                if (nbt.hasKey("generatorVersion", 99))
                {
                    i = nbt.getInteger("generatorVersion");
                }

                this.terrainType = this.terrainType.getWorldTypeForGeneratorVersion(i);
            }

            if (nbt.hasKey("generatorOptions", 8))
            {
                this.generatorOptions = nbt.getString("generatorOptions");
            }
        }

        this.theGameType = WorldSettings.GameType.getByID(nbt.getInteger("GameType"));

        if (nbt.hasKey("MapFeatures", 99))
        {
            this.mapFeaturesEnabled = nbt.getBoolean("MapFeatures");
        }
        else
        {
            this.mapFeaturesEnabled = true;
        }

        this.spawnX = nbt.getInteger("SpawnX");
        this.spawnY = nbt.getInteger("SpawnY");
        this.spawnZ = nbt.getInteger("SpawnZ");
        this.totalTime = nbt.getLong("Time");

        if (nbt.hasKey("DayTime", 99))
        {
            this.worldTime = nbt.getLong("DayTime");
        }
        else
        {
            this.worldTime = this.totalTime;
        }

        this.lastTimePlayed = nbt.getLong("LastPlayed");
        this.sizeOnDisk = nbt.getLong("SizeOnDisk");
        this.levelName = nbt.getString("LevelName");
        this.saveVersion = nbt.getInteger("version");
        this.cleanWeatherTime = nbt.getInteger("clearWeatherTime");
        this.rainTime = nbt.getInteger("rainTime");
        this.raining = nbt.getBoolean("raining");
        this.thunderTime = nbt.getInteger("thunderTime");
        this.thundering = nbt.getBoolean("thundering");
        this.hardcore = nbt.getBoolean("hardcore");

        if (nbt.hasKey("initialized", 99))
        {
            this.initialized = nbt.getBoolean("initialized");
        }
        else
        {
            this.initialized = true;
        }

        if (nbt.hasKey("allowCommands", 99))
        {
            this.allowCommands = nbt.getBoolean("allowCommands");
        }
        else
        {
            this.allowCommands = this.theGameType == WorldSettings.GameType.CREATIVE;
        }

        if (nbt.hasKey("Player", 10))
        {
            this.playerTag = nbt.getCompoundTag("Player");
            this.dimension = this.playerTag.getInteger("Dimension");
        }

        if (nbt.hasKey("GameRules", 10))
        {
            this.theGameRules.readFromNBT(nbt.getCompoundTag("GameRules"));
        }

        if (nbt.hasKey("Difficulty", 99))
        {
            this.difficulty = EnumDifficulty.getDifficultyEnum(nbt.getByte("Difficulty"));
        }

        if (nbt.hasKey("DifficultyLocked", 1))
        {
            this.difficultyLocked = nbt.getBoolean("DifficultyLocked");
        }

        if (nbt.hasKey("BorderCenterX", 99))
        {
            this.borderCenterX = nbt.getDouble("BorderCenterX");
        }

        if (nbt.hasKey("BorderCenterZ", 99))
        {
            this.borderCenterZ = nbt.getDouble("BorderCenterZ");
        }

        if (nbt.hasKey("BorderSize", 99))
        {
            this.borderSize = nbt.getDouble("BorderSize");
        }

        if (nbt.hasKey("BorderSizeLerpTime", 99))
        {
            this.borderSizeLerpTime = nbt.getLong("BorderSizeLerpTime");
        }

        if (nbt.hasKey("BorderSizeLerpTarget", 99))
        {
            this.borderSizeLerpTarget = nbt.getDouble("BorderSizeLerpTarget");
        }

        if (nbt.hasKey("BorderSafeZone", 99))
        {
            this.borderSafeZone = nbt.getDouble("BorderSafeZone");
        }

        if (nbt.hasKey("BorderDamagePerBlock", 99))
        {
            this.borderDamagePerBlock = nbt.getDouble("BorderDamagePerBlock");
        }

        if (nbt.hasKey("BorderWarningBlocks", 99))
        {
            this.borderWarningDistance = nbt.getInteger("BorderWarningBlocks");
        }

        if (nbt.hasKey("BorderWarningTime", 99))
        {
            this.borderWarningTime = nbt.getInteger("BorderWarningTime");
        }
    }

    public WorldInfo(WorldSettings settings, String name)
    {
        this.populateFromWorldSettings(settings);
        this.levelName = name;
        this.difficulty = DEFAULT_DIFFICULTY;
        this.initialized = false;
    }

    public void populateFromWorldSettings(WorldSettings settings)
    {
        this.randomSeed = settings.getSeed();
        this.theGameType = settings.getGameType();
        this.mapFeaturesEnabled = settings.isMapFeaturesEnabled();
        this.hardcore = settings.getHardcoreEnabled();
        this.terrainType = settings.getTerrainType();
        this.generatorOptions = settings.getWorldName();
        this.allowCommands = settings.areCommandsAllowed();
    }

    public WorldInfo(WorldInfo worldInformation)
    {
        this.randomSeed = worldInformation.randomSeed;
        this.terrainType = worldInformation.terrainType;
        this.generatorOptions = worldInformation.generatorOptions;
        this.theGameType = worldInformation.theGameType;
        this.mapFeaturesEnabled = worldInformation.mapFeaturesEnabled;
        this.spawnX = worldInformation.spawnX;
        this.spawnY = worldInformation.spawnY;
        this.spawnZ = worldInformation.spawnZ;
        this.totalTime = worldInformation.totalTime;
        this.worldTime = worldInformation.worldTime;
        this.lastTimePlayed = worldInformation.lastTimePlayed;
        this.sizeOnDisk = worldInformation.sizeOnDisk;
        this.playerTag = worldInformation.playerTag;
        this.dimension = worldInformation.dimension;
        this.levelName = worldInformation.levelName;
        this.saveVersion = worldInformation.saveVersion;
        this.rainTime = worldInformation.rainTime;
        this.raining = worldInformation.raining;
        this.thunderTime = worldInformation.thunderTime;
        this.thundering = worldInformation.thundering;
        this.hardcore = worldInformation.hardcore;
        this.allowCommands = worldInformation.allowCommands;
        this.initialized = worldInformation.initialized;
        this.theGameRules = worldInformation.theGameRules;
        this.difficulty = worldInformation.difficulty;
        this.difficultyLocked = worldInformation.difficultyLocked;
        this.borderCenterX = worldInformation.borderCenterX;
        this.borderCenterZ = worldInformation.borderCenterZ;
        this.borderSize = worldInformation.borderSize;
        this.borderSizeLerpTime = worldInformation.borderSizeLerpTime;
        this.borderSizeLerpTarget = worldInformation.borderSizeLerpTarget;
        this.borderSafeZone = worldInformation.borderSafeZone;
        this.borderDamagePerBlock = worldInformation.borderDamagePerBlock;
        this.borderWarningTime = worldInformation.borderWarningTime;
        this.borderWarningDistance = worldInformation.borderWarningDistance;
    }

    /**
     * Gets the NBTTagCompound for the worldInfo
     */
    public NBTTagCompound getNBTTagCompound()
    {
        NBTTagCompound nbttagcompound = new NBTTagCompound();
        this.updateTagCompound(nbttagcompound, this.playerTag);
        return nbttagcompound;
    }

    /**
     * Creates a new NBTTagCompound for the world, with the given NBTTag as the "Player"
     */
    public NBTTagCompound cloneNBTCompound(NBTTagCompound nbt)
    {
        NBTTagCompound nbttagcompound = new NBTTagCompound();
        this.updateTagCompound(nbttagcompound, nbt);
        return nbttagcompound;
    }

    private void updateTagCompound(NBTTagCompound nbt, NBTTagCompound playerNbt)
    {
        nbt.setLong("RandomSeed", this.randomSeed);
        nbt.setString("generatorName", this.terrainType.getWorldTypeName());
        nbt.setInteger("generatorVersion", this.terrainType.getGeneratorVersion());
        nbt.setString("generatorOptions", this.generatorOptions);
        nbt.setInteger("GameType", this.theGameType.getID());
        nbt.setBoolean("MapFeatures", this.mapFeaturesEnabled);
        nbt.setInteger("SpawnX", this.spawnX);
        nbt.setInteger("SpawnY", this.spawnY);
        nbt.setInteger("SpawnZ", this.spawnZ);
        nbt.setLong("Time", this.totalTime);
        nbt.setLong("DayTime", this.worldTime);
        nbt.setLong("SizeOnDisk", this.sizeOnDisk);
        nbt.setLong("LastPlayed", MinecraftServer.getCurrentTimeMillis());
        nbt.setString("LevelName", this.levelName);
        nbt.setInteger("version", this.saveVersion);
        nbt.setInteger("clearWeatherTime", this.cleanWeatherTime);
        nbt.setInteger("rainTime", this.rainTime);
        nbt.setBoolean("raining", this.raining);
        nbt.setInteger("thunderTime", this.thunderTime);
        nbt.setBoolean("thundering", this.thundering);
        nbt.setBoolean("hardcore", this.hardcore);
        nbt.setBoolean("allowCommands", this.allowCommands);
        nbt.setBoolean("initialized", this.initialized);
        nbt.setDouble("BorderCenterX", this.borderCenterX);
        nbt.setDouble("BorderCenterZ", this.borderCenterZ);
        nbt.setDouble("BorderSize", this.borderSize);
        nbt.setLong("BorderSizeLerpTime", this.borderSizeLerpTime);
        nbt.setDouble("BorderSafeZone", this.borderSafeZone);
        nbt.setDouble("BorderDamagePerBlock", this.borderDamagePerBlock);
        nbt.setDouble("BorderSizeLerpTarget", this.borderSizeLerpTarget);
        nbt.setDouble("BorderWarningBlocks", (double)this.borderWarningDistance);
        nbt.setDouble("BorderWarningTime", (double)this.borderWarningTime);

        if (this.difficulty != null)
        {
            nbt.setByte("Difficulty", (byte)this.difficulty.getDifficultyId());
        }

        nbt.setBoolean("DifficultyLocked", this.difficultyLocked);
        nbt.setTag("GameRules", this.theGameRules.writeToNBT());

        if (playerNbt != null)
        {
            nbt.setTag("Player", playerNbt);
        }
    }

    /**
     * Returns the seed of current world.
     */
    public long getSeed()
    {
        return this.randomSeed;
    }

    /**
     * Returns the x spawn position
     */
    public int getSpawnX()
    {
        return this.spawnX;
    }

    /**
     * Return the Y axis spawning point of the player.
     */
    public int getSpawnY()
    {
        return this.spawnY;
    }

    /**
     * Returns the z spawn position
     */
    public int getSpawnZ()
    {
        return this.spawnZ;
    }

    public long getWorldTotalTime()
    {
        return this.totalTime;
    }

    /**
     * Get current world time
     */
    public long getWorldTime()
    {
        return this.worldTime;
    }

    /**
     * Returns the player's NBTTagCompound to be loaded
     */
    public NBTTagCompound getPlayerNBTTagCompound()
    {
        return this.playerTag;
    }

    public void setWorldTotalTime(long time)
    {
        this.totalTime = time;
    }

    /**
     * Set current world time
     */
    public void setWorldTime(long time)
    {
        this.worldTime = time;
    }

    public void setSpawn(BlockPos spawnPoint)
    {
        this.spawnX = spawnPoint.getX();
        this.spawnY = spawnPoint.getY();
        this.spawnZ = spawnPoint.getZ();
    }

    /**
     * Get current world name
     */
    public String getWorldName()
    {
        return this.levelName;
    }

    public void setWorldName(String worldName)
    {
        this.levelName = worldName;
    }

    /**
     * Returns the save version of this world
     */
    public int getSaveVersion()
    {
        return this.saveVersion;
    }

    /**
     * Sets the save version of the world
     */
    public void setSaveVersion(int version)
    {
        this.saveVersion = version;
    }

    public int getCleanWeatherTime()
    {
        return this.cleanWeatherTime;
    }

    public void setCleanWeatherTime(int cleanWeatherTimeIn)
    {
        this.cleanWeatherTime = cleanWeatherTimeIn;
    }

    /**
     * Returns true if it is thundering, false otherwise.
     */
    public boolean isThundering()
    {
        return this.thundering;
    }

    /**
     * Sets whether it is thundering or not.
     */
    public void setThundering(boolean thunderingIn)
    {
        this.thundering = thunderingIn;
    }

    /**
     * Returns the number of ticks until next thunderbolt.
     */
    public int getThunderTime()
    {
        return this.thunderTime;
    }

    /**
     * Defines the number of ticks until next thunderbolt.
     */
    public void setThunderTime(int time)
    {
        this.thunderTime = time;
    }

    /**
     * Returns true if it is raining, false otherwise.
     */
    public boolean isRaining()
    {
        return this.raining;
    }

    /**
     * Sets whether it is raining or not.
     */
    public void setRaining(boolean isRaining)
    {
        this.raining = isRaining;
    }

    /**
     * Return the number of ticks until rain.
     */
    public int getRainTime()
    {
        return this.rainTime;
    }

    /**
     * Sets the number of ticks until rain.
     */
    public void setRainTime(int time)
    {
        this.rainTime = time;
    }

    /**
     * Gets the GameType.
     */
    public WorldSettings.GameType getGameType()
    {
        return this.theGameType;
    }

    /**
     * Get whether the map features (e.g. strongholds) generation is enabled or disabled.
     */
    public boolean isMapFeaturesEnabled()
    {
        return this.mapFeaturesEnabled;
    }

    public void setMapFeaturesEnabled(boolean enabled)
    {
        this.mapFeaturesEnabled = enabled;
    }

    /**
     * Sets the GameType.
     */
    public void setGameType(WorldSettings.GameType type)
    {
        this.theGameType = type;
    }

    /**
     * Returns true if hardcore mode is enabled, otherwise false
     */
    public boolean isHardcoreModeEnabled()
    {
        return this.hardcore;
    }

    public void setHardcore(boolean hardcoreIn)
    {
        this.hardcore = hardcoreIn;
    }

    public WorldType getTerrainType()
    {
        return this.terrainType;
    }

    public void setTerrainType(WorldType type)
    {
        this.terrainType = type;
    }

    public String getGeneratorOptions()
    {
        return this.generatorOptions;
    }

    /**
     * Returns true if commands are allowed on this World.
     */
    public boolean areCommandsAllowed()
    {
        return this.allowCommands;
    }

    public void setAllowCommands(boolean allow)
    {
        this.allowCommands = allow;
    }

    /**
     * Returns true if the World is initialized.
     */
    public boolean isInitialized()
    {
        return this.initialized;
    }

    /**
     * Sets the initialization status of the World.
     */
    public void setServerInitialized(boolean initializedIn)
    {
        this.initialized = initializedIn;
    }

    /**
     * Gets the GameRules class Instance.
     */
    public GameRules getGameRulesInstance()
    {
        return this.theGameRules;
    }

    /**
     * Returns the border center X position
     */
    public double getBorderCenterX()
    {
        return this.borderCenterX;
    }

    /**
     * Returns the border center Z position
     */
    public double getBorderCenterZ()
    {
        return this.borderCenterZ;
    }

    public double getBorderSize()
    {
        return this.borderSize;
    }

    /**
     * Sets the border size
     */
    public void setBorderSize(double size)
    {
        this.borderSize = size;
    }

    /**
     * Returns the border lerp time
     */
    public long getBorderLerpTime()
    {
        return this.borderSizeLerpTime;
    }

    /**
     * Sets the border lerp time
     */
    public void setBorderLerpTime(long time)
    {
        this.borderSizeLerpTime = time;
    }

    /**
     * Returns the border lerp target
     */
    public double getBorderLerpTarget()
    {
        return this.borderSizeLerpTarget;
    }

    /**
     * Sets the border lerp target
     */
    public void setBorderLerpTarget(double lerpSize)
    {
        this.borderSizeLerpTarget = lerpSize;
    }

    /**
     * Sets the border center Z position
     */
    public void getBorderCenterZ(double posZ)
    {
        this.borderCenterZ = posZ;
    }

    /**
     * Sets the border center X position
     */
    public void getBorderCenterX(double posX)
    {
        this.borderCenterX = posX;
    }

    /**
     * Returns the border safe zone
     */
    public double getBorderSafeZone()
    {
        return this.borderSafeZone;
    }

    /**
     * Sets the border safe zone
     */
    public void setBorderSafeZone(double amount)
    {
        this.borderSafeZone = amount;
    }

    /**
     * Returns the border damage per block
     */
    public double getBorderDamagePerBlock()
    {
        return this.borderDamagePerBlock;
    }

    /**
     * Sets the border damage per block
     */
    public void setBorderDamagePerBlock(double damage)
    {
        this.borderDamagePerBlock = damage;
    }

    /**
     * Returns the border warning distance
     */
    public int getBorderWarningDistance()
    {
        return this.borderWarningDistance;
    }

    /**
     * Returns the border warning time
     */
    public int getBorderWarningTime()
    {
        return this.borderWarningTime;
    }

    /**
     * Sets the border warning distance
     */
    public void setBorderWarningDistance(int amountOfBlocks)
    {
        this.borderWarningDistance = amountOfBlocks;
    }

    /**
     * Sets the border warning time
     */
    public void setBorderWarningTime(int ticks)
    {
        this.borderWarningTime = ticks;
    }

    public EnumDifficulty getDifficulty()
    {
        return this.difficulty;
    }

    public void setDifficulty(EnumDifficulty newDifficulty)
    {
        this.difficulty = newDifficulty;
    }

    public boolean isDifficultyLocked()
    {
        return this.difficultyLocked;
    }

    public void setDifficultyLocked(boolean locked)
    {
        this.difficultyLocked = locked;
    }

    /**
     * Adds this WorldInfo instance to the crash report.
     */
    public void addToCrashReport(CrashReportCategory category)
    {
        category.addCrashSectionCallable("Level seed", new Callable<String>()
        {
            public String call() throws Exception
            {
                return String.valueOf(WorldInfo.this.getSeed());
            }
        });
        category.addCrashSectionCallable("Level generator", new Callable<String>()
        {
            public String call() throws Exception
            {
                return String.format("ID %02d - %s, ver %d. Features enabled: %b", new Object[] {Integer.valueOf(WorldInfo.this.terrainType.getWorldTypeID()), WorldInfo.this.terrainType.getWorldTypeName(), Integer.valueOf(WorldInfo.this.terrainType.getGeneratorVersion()), Boolean.valueOf(WorldInfo.this.mapFeaturesEnabled)});
            }
        });
        category.addCrashSectionCallable("Level generator options", new Callable<String>()
        {
            public String call() throws Exception
            {
                return WorldInfo.this.generatorOptions;
            }
        });
        category.addCrashSectionCallable("Level spawn location", new Callable<String>()
        {
            public String call() throws Exception
            {
                return CrashReportCategory.getCoordinateInfo((double)WorldInfo.this.spawnX, (double)WorldInfo.this.spawnY, (double)WorldInfo.this.spawnZ);
            }
        });
        category.addCrashSectionCallable("Level time", new Callable<String>()
        {
            public String call() throws Exception
            {
                return String.format("%d game time, %d day time", new Object[] {Long.valueOf(WorldInfo.this.totalTime), Long.valueOf(WorldInfo.this.worldTime)});
            }
        });
        category.addCrashSectionCallable("Level dimension", new Callable<String>()
        {
            public String call() throws Exception
            {
                return String.valueOf(WorldInfo.this.dimension);
            }
        });
        category.addCrashSectionCallable("Level storage version", new Callable<String>()
        {
            public String call() throws Exception
            {
                String s = "Unknown?";

                try
                {
                    switch (WorldInfo.this.saveVersion)
                    {
                        case 19132:
                            s = "McRegion";
                            break;

                        case 19133:
                            s = "Anvil";
                    }
                }
                catch (Throwable var3)
                {
                    ;
                }

                return String.format("0x%05X - %s", new Object[] {Integer.valueOf(WorldInfo.this.saveVersion), s});
            }
        });
        category.addCrashSectionCallable("Level weather", new Callable<String>()
        {
            public String call() throws Exception
            {
                return String.format("Rain time: %d (now: %b), thunder time: %d (now: %b)", new Object[] {Integer.valueOf(WorldInfo.this.rainTime), Boolean.valueOf(WorldInfo.this.raining), Integer.valueOf(WorldInfo.this.thunderTime), Boolean.valueOf(WorldInfo.this.thundering)});
            }
        });
        category.addCrashSectionCallable("Level game mode", new Callable<String>()
        {
            public String call() throws Exception
            {
                return String.format("Game mode: %s (ID %d). Hardcore: %b. Cheats: %b", new Object[] {WorldInfo.this.theGameType.getName(), Integer.valueOf(WorldInfo.this.theGameType.getID()), Boolean.valueOf(WorldInfo.this.hardcore), Boolean.valueOf(WorldInfo.this.allowCommands)});
            }
        });
    }
}

redpajama_set_name: RedPajamaGithub


text:
SYNONYM

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

#### Published in
Schr. naturf. Ges. Leipzig 1: 34 (1822)

#### Original name
Sphaeria rhois Schwein., 1822

### Remarks
null


text:
"""
@package ion.agents.platform.rsn.test.test_oms_util
@file    ion/agents/platform/rsn/test/test_oms_util.py
@author  Carlos Rueda
@brief   Tests for oms_util
"""

__author__ = 'Carlos Rueda'
__license__ = 'Apache 2.0'

# NOTE: If this test is run against the embedded simulator (the default),
# make sure to keep the verifications in sync upon any changes in
# ion/agents/platform/rsn/simulator/network.yml, which is the file used by
# the simulator.

from pyon.public import log
import logging

from ion.agents.platform.util.network_util import NetworkUtil
from ion.agents.platform.rsn.oms_client_factory import CIOMSClientFactory
from ion.agents.platform.rsn.oms_util import RsnOmsUtil
from ion.agents.platform.rsn.simulator.oms_simulator import CIOMSSimulator

from ion.agents.platform.test.helper import HelperTestMixin
from pyon.util.int_test import IonIntegrationTestCase

from nose.plugins.attrib import attr

@attr('INT', group='sa')
class Test(IonIntegrationTestCase, HelperTestMixin):

    @classmethod
    def setUpClass(cls):
        HelperTestMixin.setUpClass()

    def setUp(self):
        # Note that CIOMSClientFactory will create an "embedded" RSN OMS
        # simulator object by default.
        self._rsn_oms = CIOMSClientFactory.create_instance()

    def tearDown(self):
        CIOMSClientFactory.destroy_instance(self._rsn_oms)

    def test_build_network_definition(self):
        ndef = RsnOmsUtil.build_network_definition(self._rsn_oms)

        if log.isEnabledFor(logging.TRACE):
            # serialize object to string
            serialization = NetworkUtil.serialize_network_definition(ndef)
            log.trace("NetworkDefinition serialization:\n%s", serialization)

        if not isinstance(self._rsn_oms, CIOMSSimulator):
            # OK, no more tests if we are not using the embedded simulator
            return

        # Else: do some verifications against network.yml (the spec used by
        # the simulator):

        self.assertTrue("UPS" in ndef.platform_types)

        pnode = ndef.root

        self.assertEqual(pnode.platform_id, "ShoreStation")
        self.assertIn("ShoreStation_attr_1|0", pnode.attrs)
        self.assertIn("ShoreStation_port_1", pnode.ports)

        sub_pnodes = pnode.subplatforms
        self.assertIn("L3-UPS1",       sub_pnodes)
        self.assertIn("Node1A",        sub_pnodes)
        self.assertIn("input_voltage|0", sub_pnodes["Node1A"].attrs)
        self.assertIn("Node1A_port_1", sub_pnodes["Node1A"].ports)

    def _get_checksum(self, platform_id):
        # get checksum from RSN OMS:
        res = self._rsn_oms.config.get_checksum(platform_id)
        checksum = res[platform_id]
        if log.isEnabledFor(logging.DEBUG):
            log.debug("_rsn_oms: checksum: %s", checksum)
        return checksum

    def _connect_instrument(self):
        platform_id = self.PLATFORM_ID
        port_id = self.PORT_ID
        instrument_id = self.INSTRUMENT_ID
        attributes = {'maxCurrentDraw': 1, 'initCurrent': 2,
                      'dataThroughput': 3, 'instrumentType': 'FOO'}
        retval = self._rsn_oms.instr.connect_instrument(platform_id, port_id,
                                                        instrument_id, attributes)
        log.info("connect_instrument = %s" % retval)
        ports = self._verify_valid_platform_id(platform_id, retval)
        self._verify_valid_port_id(port_id, ports)

    def test_checksum(self):
        platform_id = self.PLATFORM_ID

        checksum = self._get_checksum(platform_id)

        # build network definition using RSN OMS and get checksum for the
        # corresponding PlatformNode, and verify that the checksums match:
        ndef = RsnOmsUtil.build_network_definition(self._rsn_oms)
        pnode = ndef.pnodes[platform_id]
        self.assertEquals(pnode.compute_checksum(), checksum)

        # ok; now connect an instrument and verify the new checksums again:
        self._connect_instrument()

        checksum = self._get_checksum(platform_id)
        ndef = RsnOmsUtil.build_network_definition(self._rsn_oms)
        pnode = ndef.pnodes[platform_id]
        self.assertEquals(pnode.compute_checksum(), checksum)


text:
var changed = function(v) {
  v && v.changed();
};

ReactiveMap = function(data) {
  this._values = {};
  this._size = 0;

  // Tracking the "size" method.
  this._sizeDep = new Tracker.Dependency;
  // Tracking "entries" and "all" methods.
  this._entriesDep = new Tracker.Dependency;
  // Tracking the "key" method.
  this._keysDep = new Tracker.Dependency;
  // Tracking the "values" method.
  this._valuesDep = new Tracker.Dependency;
  // Tracking key existence.
  this._keysDeps = {};
  // Tracking values under keys.
  this._valuesDeps = {};

  // Initialize a map.
  if (data) {
    this.set(data);
  }
};

_.extend(ReactiveMap.prototype, {
  _ensureKey: function(key) {
    if (!_.has(this._valuesDeps, key)) {
      this._keysDeps[key] = new Tracker.Dependency;
      this._valuesDeps[key] = new Tracker.Dependency;
    }
  },

  // Getters.

  get: function(key) {
    this._ensureKey(key);
    this._valuesDeps[key].depend();

    return this._values[key];
  },

  has: function(key) {
    this._ensureKey(key);
    this._keysDeps[key].depend();

    return _.has(this._values, key);
  },

  entries: function() {
    this._entriesDep.depend();

    return _.map(this._values, function(value, key) {
      return [key, value];
    });
  },

  all: function() {
    this._entriesDep.depend();

    var all = {};
    _.each(this._values, function(value, key) {
      all[key] = value;
    });

    return all;
  },

  keys: function() {
    this._keysDep.depend();

    return _.keys(this._values);
  },

  values: function() {
    this._valuesDep.depend();

    var values = [];
    _.each(this._values, function(value, key) {
      values.push(value);
    });

    return values;
  },

  size: function() {
    this._sizeDep.depend();

    return this._size;
  },

  // Modifiers.

  _setOne: function(key, value) {
    if (_.has(this._values, key)) {
      if (value === this._values[key]) {
        return;
      }
      this._values[key] = value;
    } else {
      this._size++;
      this._values[key] = value;

      this._sizeDep.changed();
      this._keysDep.changed();
      changed(this._keysDeps[key]);
    }

    this._valuesDep.changed();
    this._entriesDep.changed();
    changed(this._valuesDeps[key]);
  },

  _setMany: function(values) {
    var self = this;

    _.each(values, function(value, key) {
      self._setOne(key, value);
    });
  },

  set: function() {
    if (arguments.length === 1 && _.isObject(arguments[0])) {
      this._setMany.apply(this, arguments);
    } else if (arguments.length === 2) {
      this._setOne.apply(this, arguments);
    }

    return this;
  },

  delete: function(key) {
    if (!_.has(this._values, key)) {
      return false;
    }

    delete this._values[key];
    this._size--;

    changed(this._valuesDeps[key]);
    changed(this._keysDeps[key]);
    this._sizeDep.changed();
    this._entriesDep.changed();
    this._keysDep.changed();
    this._valuesDep.changed();

    return true;
  },

  clear: function() {
    var self = this;

    var keys = _.keys(this._values);
    this._values = {};
    this._size = 0;

    this._sizeDep.changed();
    this._entriesDep.changed();
    this._keysDep.changed();
    this._valuesDep.changed();

    _.each(keys, function(key) {
      changed(self._keysDeps[key]);
      changed(self._valuesDeps[key]);
    });
  }
});


text:
package cn.epai.front.api.controller;

import cn.epai.front.api.security.ShiroEncryptUtils;
import cn.epai.front.api.token.SystemTokenUtil;
import cn.epai.front.api.token.TokenManager;
import cn.epai.front.api.util.ParamVerifyUtil;
import cn.lxz.sweb.cache.Cache;
import cn.lxz.sweb.constant.SysConstant;
import cn.lxz.sweb.encode.JsonEncoder;
import cn.lxz.sweb.utils.JavaMail;
import cn.lxz.sweb.utils.StrKit;
import com.epai.contract.iface.CommonMessageService;
import com.epai.contract.iface.GameService;
import com.epai.contract.model.sys.CommonMessageResponse;
import com.epai.contract.model.sys.MessageBody;
import com.epai.contract.page.FormMap;
import com.epai.front.contract.iface.UserService;
import com.epai.front.contract.model.GameUser;
import com.epai.front.contract.model.UserResponse;
import com.epai.front.contract.rpc.ReturnStateEnum;
import com.epai.front.contract.rpc.RpcForm;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author jihua.li
 * @Date 2017/6/22 10:18
 */
@RestController
public class WebClientApiController extends BaseApiController {

    private static final Logger WEB_LOG = LoggerFactory.getLogger("web_API");

    private static final String WEB_BIND_SMS="web_bind_sms_code";

    private static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Autowired
    CommonMessageService commonMessageService;

    @Autowired
    GameService gameService;

    @Autowired
    UserService userService;

    @RequestMapping("weblogin")
    public Object login(HttpServletRequest request){
        RpcForm rpcForm = findHasHMap(RpcForm.class);
        try {
            WEB_LOG.info("weblogin_接收到的请求参数为:{}", JsonEncoder.DEFAULT.encode(rpcForm));
        } catch (Exception e) {
        }
        Map<String, Object> res = validPreRequest(request, rpcForm);
        if (null != res) {
            return JsonEncoder.DEFAULT.encode(res);
        }
        String username = rpcForm.getStr("username"), password = rpcForm.getStr("password");
        Map<String, Object> nameAndPwdValidRes = ParamVerifyUtil.validUserNameAndPwd(username, password);
        if (null != nameAndPwdValidRes) {
            return JsonEncoder.DEFAULT.encode(nameAndPwdValidRes);
        }
        if (Cache.exist(SysConstant.SYSTEM_API_WEB_USER_TOKEN, username)) {
            Cache.remove(SysConstant.SYSTEM_API_WEB_USER_TOKEN, username);
        }
        UsernamePasswordToken loginToken = new UsernamePasswordToken(username, password, false);
        Subject loginUser = SecurityUtils.getSubject();
        Map<String, Object> result = getResMap();
        try {
            loginUser.login(loginToken);
        } catch (UnknownAccountException unknownAccountExp) {
            result.put("state", ReturnStateEnum.USER_NOT_FOUND.getState());
            result.put("msg", ReturnStateEnum.USER_NOT_FOUND.getMsg());
        } catch (LockedAccountException lockedAccountExp) {
            result.put("state", ReturnStateEnum.USER_HAS_LOCKED.getState());
            result.put("msg", ReturnStateEnum.USER_HAS_LOCKED.getMsg());
        } catch (ExcessiveAttemptsException attemptTimeExp) {
            result.put("state", ReturnStateEnum.Login_Attempt_OverTimes.getState());
            result.put("msg", ReturnStateEnum.Login_Attempt_OverTimes.getMsg());
        } catch (AuthenticationException authExp) {
            result.put("state", ReturnStateEnum.WRONG_PASSWORD.getState());
            result.put("msg", ReturnStateEnum.WRONG_PASSWORD.getMsg());
        }
        if (loginUser.isAuthenticated()) {//表示登录成功
                GameUser user = Cache.get(GameUser.class, SysConstant.SYSTEM_API_GAME_USER_LOGIN_SESSION, username);
                result.put("state", ReturnStateEnum.SUCCESS.getState());
                result.put("msg", ReturnStateEnum.SUCCESS.getMsg());
                Map<String, String> data = new HashMap<>();
                String token = SystemTokenUtil.getApiWebToken(username);
                data.put("token", token);
                data.put("uin", String.valueOf(user.getUin()));
                result.put("data", data);
                TokenManager.addApiWebToken(token, username);
                try {
                    FormMap<String,Object> formMap=findHasHMap(FormMap.class);
                    formMap.put("userName", username);
                    formMap.put("userType", "网页");
                    formMap.put("userId", user.getUin());
                    formMap.put("accessTime",dateFormatter.format(LocalDateTime.now()));
                    formMap.put("ip", StrKit.getIpAddress(request));
                    commonMessageService.saveUserLoginLog(formMap);
                }catch (Exception e){}
            loginUser.logout();
            loginToken.clear();
            Cache.remove(SysConstant.SYSTEM_API_GAME_USER_LOGIN_SESSION, username);
            return JsonEncoder.DEFAULT.encode(result);
        } else {
            loginUser.logout();
            loginToken.clear();
            Cache.remove(SysConstant.SYSTEM_API_GAME_USER_LOGIN_SESSION, username);
            result.put("data", null);
            return JsonEncoder.DEFAULT.encode(result);
        }

    }

    @RequestMapping("webregister")
    public Object register(HttpServletRequest request){
        RpcForm rpcForm = findHasHMap(RpcForm.class);
        Map<String, Object> result = getResMap();
        try {
            try {
                WEB_LOG.info("webregister_接收到的请求参数为:{}", JsonEncoder.DEFAULT.encode(rpcForm));
            } catch (Exception e) {
            }
            Map<String, Object> res = validPreRequest(request, rpcForm);
            if (null != res) {
                return JsonEncoder.DEFAULT.encode(res);
            }
            String username = rpcForm.getStr("username"), password = rpcForm.getStr("password");
            Map<String, Object> nameAndPwdValidRes = ParamVerifyUtil.validUserNameAndPwd(username, password);
            if (null != nameAndPwdValidRes) {
                return JsonEncoder.DEFAULT.encode(nameAndPwdValidRes);
            }
            GameUser user = ShiroEncryptUtils.md5EncriptPassword(username, password);
            rpcForm.put("password", user.getPassword());
            rpcForm.put("credentials_salt", user.getCredentials_salt());
            rpcForm.put("register_time", dateFormatter.format(LocalDateTime.now()));
            rpcForm.put("game_id",rpcForm.getInt("game_id"));
            rpcForm.put("channel_id",rpcForm.getInt("channel_id"));
            rpcForm.put("dev_info","网页");
            rpcForm.put("dev_id","0");
            UserResponse response = userService.register(rpcForm);
            ParamVerifyUtil.convertResponse(result, response);
        }catch (Exception e){
            WEB_LOG.error("执行用户注册出错了:{}", e);
            ParamVerifyUtil.convertResponse(result, e);
        }
        return result;
    }

    @RequestMapping("webmodify_pwd")
    public Object modifyPwd(HttpServletRequest request){
        RpcForm rpcForm = findHasHMap(RpcForm.class);
        Map<String, Object> result = getResMap();
        try {
        	WEB_LOG.info("webmodify_pwd_接收到的请求参数为:{}", JsonEncoder.DEFAULT.encode(rpcForm));
        } catch (Exception e) {
        }
        try{
          	 Map<String, Object> res = validPreRequest(request, rpcForm);
               if (null != res) {
                   return JsonEncoder.DEFAULT.encode(res);
               }
               String username = rpcForm.getStr("username"), password_new = rpcForm.getStr("password_new"), password_old = rpcForm.getStr("password_old");
               Map<String, Object> pwdValidRes = ParamVerifyUtil.validModifyPwdParam(username, password_old, password_new);
               if (null != pwdValidRes) {
                   return JsonEncoder.DEFAULT.encode(pwdValidRes);
               }
               GameUser oldUser= userService.login(username).getLoginUser();
               if(oldUser==null){
              	  result.put("state", ReturnStateEnum.USER_NOT_FOUND.getState());
                    result.put("msg", ReturnStateEnum.USER_NOT_FOUND.getMsg());
                    return JsonEncoder.DEFAULT.encode(result);
               }
               boolean oldPwdCheck=ShiroEncryptUtils.verifyOldPwd(oldUser.getCredentials_salt(), oldUser.getPassword(), password_old, username);
               if(!oldPwdCheck){
              	 result.put("state", ReturnStateEnum.USER_OLD_PASSWORD_WRONG.getState());
                   result.put("msg", ReturnStateEnum.USER_OLD_PASSWORD_WRONG.getMsg());
                   return JsonEncoder.DEFAULT.encode(result);
               }
               GameUser user = ShiroEncryptUtils.md5EncriptPassword(username, password_new);
               rpcForm.put("password", user.getPassword());
               rpcForm.put("credentials_salt", user.getCredentials_salt());
               UserResponse updateResp = userService.updateGameUserInfo(rpcForm);
               if (updateResp.getState() == ReturnStateEnum.SUCCESS.getState()) {
                   result.put("state", ReturnStateEnum.SUCCESS.getState());
                   result.put("msg", ReturnStateEnum.SUCCESS.getMsg());
                   Map<String, Object> data = new HashMap<>();
                   data.put("username", username);
                   result.put("data", data);
               } else {
                   result.put("state", ReturnStateEnum.SERVER_INNER_ERROR.getState());
                   result.put("msg", ReturnStateEnum.SERVER_INNER_ERROR.getMsg());
               }
          }catch (Exception e) {
        	   WEB_LOG.error("执行修改密码出错了:{}", e);
               ParamVerifyUtil.convertResponse(result, e);
   		}
          return JsonEncoder.DEFAULT.encode(result);
    }

    @RequestMapping("webfind_pwd")
    public Object findPwd(HttpServletRequest request){
        RpcForm rpcForm = findHasHMap(RpcForm.class);
        try {
            WEB_LOG.info("webfind_pwd_接收到的请求参数为:{}", JsonEncoder.DEFAULT.encode(rpcForm));
        } catch (Exception e) {
        }
        Map<String, Object> res = validPreRequest(request, rpcForm);
        if (null != res) {
            return JsonEncoder.DEFAULT.encode(res);
        }
        String username = rpcForm.getStr("username"), phone_num = rpcForm.getStr("bind_phone");
        Map<String, Object> phoneValidRes = ParamVerifyUtil.validPhoneAndName(username, phone_num);
        if (null != phoneValidRes) {
            return JsonEncoder.DEFAULT.encode(phoneValidRes);
        }
        GameUser gameUser = userService.login(username).getLoginUser();
        Map<String, Object> nameAndPhoneValidRes = ParamVerifyUtil.userExistAndPhoneMatchValid(gameUser, phone_num,true);
        if (null != nameAndPhoneValidRes) {
            return JsonEncoder.DEFAULT.encode(nameAndPhoneValidRes);
        }
        String newPwd=String.valueOf(JavaMail.getRandNum(100000,999999));
        GameUser user = ShiroEncryptUtils.md5EncriptPassword(username, newPwd);
        Map<String,Object> result=getResMap();
        rpcForm.put("password", user.getPassword());
        rpcForm.put("credentials_salt", user.getCredentials_salt());
        UserResponse updateResp = userService.updateGameUserInfo(rpcForm);
        if (updateResp.getState() == ReturnStateEnum.SUCCESS.getState()) {
            MessageBody messageBody = new MessageBody();
            messageBody.setReceiveUser(phone_num);
            messageBody.setSendHtml("您的新密码:"+newPwd+",请注意妥善保管");
            messageBody.setSmsType(2);
            messageBody.setExtend(username);
            CommonMessageResponse response = commonMessageService.sendSms(messageBody);
            if (response.isInvokeStatus()) {
                result.put("state", ReturnStateEnum.SUCCESS.getState());
                result.put("msg", ReturnStateEnum.SUCCESS.getMsg());
            } else {
                res.put("state", ReturnStateEnum.SERVER_INNER_ERROR);
                res.put("msg", response.getErrorMessage());
            }
        } else {
            result.put("state", ReturnStateEnum.SERVER_INNER_ERROR.getState());
            result.put("msg", ReturnStateEnum.SERVER_INNER_ERROR.getMsg());
        }
        return JsonEncoder.DEFAULT.encode(result);
    }

    @RequestMapping("webgetbindcode")
    public Object getBindCode(HttpServletRequest request){
        RpcForm rpcForm = findHasHMap(RpcForm.class);
        try {
            WEB_LOG.info("webgetbindcode_接收到的请求参数为:{}", JsonEncoder.DEFAULT.encode(rpcForm));
        } catch (Exception e) {
        }
        Map<String, Object> validRes = validPreRequest(request, rpcForm);
        if (null != validRes) {
            return JsonEncoder.DEFAULT.encode(validRes);
        }
        String username = rpcForm.getStr("username"), phone_num = rpcForm.getStr("phone_num");
        Map<String, Object> phoneValidRes = ParamVerifyUtil.validPhoneAndName(username, phone_num);
        if (null != phoneValidRes) {
            return JsonEncoder.DEFAULT.encode(phoneValidRes);
        }
        GameUser gameUser = userService.login(username).getLoginUser();
        if(null==gameUser){
            validRes=new HashMap<>();
            validRes.put("state",ReturnStateEnum.USER_NOT_FOUND.getState());
            validRes.put("msg",ReturnStateEnum.USER_NOT_FOUND.getMsg());
            return JsonEncoder.DEFAULT.encode(validRes);
        }
        int randRomNum = JavaMail.getRandNum(100000, 999999);
        MessageBody messageBody = new MessageBody();
        messageBody.setReceiveUser(phone_num);
        messageBody.setCode(randRomNum + "");
        messageBody.setTime(3);
        messageBody.setSmsType(1);
        messageBody.setExtend(username);
        CommonMessageResponse response = commonMessageService.sendSms(messageBody);
        validRes=getResMap();
        if (response.isInvokeStatus()) {
            validRes.put("state", ReturnStateEnum.SUCCESS.getState());
            validRes.put("msg", ReturnStateEnum.SUCCESS.getMsg());
            validRes.put("code", randRomNum);
            validRes.put("time", 3);
            try{
                Cache.set(randRomNum,BindPhoneVerifyCode,WEB_BIND_SMS,username,phone_num);
            }catch (Exception e){
                WEB_LOG.error("绑定手机的验证码存入redis缓存失败了:{}",e.getMessage());
            }
        } else {
            validRes.put("state", ReturnStateEnum.SERVER_INNER_ERROR);
            validRes.put("msg", response.getErrorMessage());
        }
        return JsonEncoder.DEFAULT.encode(validRes);
    }

    @RequestMapping("webbind_phone")
    public Object bindPhone(HttpServletRequest request){
        RpcForm rpcForm = findHasHMap(RpcForm.class);
        try {
            WEB_LOG.info("webbind_phone_接收到的请求参数为:{}", JsonEncoder.DEFAULT.encode(rpcForm));
        } catch (Exception e) {
        }
        Map<String, Object> preValidRes = validPreRequest(request, rpcForm);
        if (null != preValidRes) {
            return JsonEncoder.DEFAULT.encode(preValidRes);
        }
        String username = rpcForm.getStr("username"), phone_num = rpcForm.getStr("phone_num"),code=rpcForm.getStr("code");
        Map<String, Object> phoneValidRes = ParamVerifyUtil.validPhoneAndName(username, phone_num);
        if (null != phoneValidRes) {
            return JsonEncoder.DEFAULT.encode(phoneValidRes);
        }
        if(StringUtils.isEmpty(code)){
            phoneValidRes=new HashMap<>();
            phoneValidRes.put("state",ReturnStateEnum.VERIFY_EMPTY_ERROR.getState());
            phoneValidRes.put("msg", ReturnStateEnum.VERIFY_EMPTY_ERROR.getMsg());
            return JsonEncoder.DEFAULT.encode(phoneValidRes);
        }
        if(!code.equals(Cache.get(String.class,BindPhoneVerifyCode,WEB_BIND_SMS,username,phone_num))){
            phoneValidRes=new HashMap<>();
            phoneValidRes.put("state",ReturnStateEnum.VERIFY_CODE_ERROR.getState());
            phoneValidRes.put("msg", ReturnStateEnum.VERIFY_CODE_ERROR.getMsg());
            return JsonEncoder.DEFAULT.encode(phoneValidRes);
        }else{
            Cache.remove(BindPhoneVerifyCode,WEB_BIND_SMS,username,phone_num);
        }
        GameUser gameUser = userService.login(username).getLoginUser();
        Map<String, Object> nameAndPhoneValidRes = ParamVerifyUtil.userExistAndPhoneMatchValid(gameUser, phone_num,false);
        if (null != nameAndPhoneValidRes) {
            return JsonEncoder.DEFAULT.encode(nameAndPhoneValidRes);
        }
        UserResponse bindPhoneResp = userService.updateGameUserInfo(rpcForm);
        Map<String, Object> result = getResMap();
        if (bindPhoneResp.getState() == ReturnStateEnum.SUCCESS.getState() && bindPhoneResp.getEffectRow() > 0) {
            result.put("state", ReturnStateEnum.SUCCESS.getState());
            result.put("msg", ReturnStateEnum.SUCCESS.getMsg());
        } else {
            result.put("state", ReturnStateEnum.SERVER_INNER_ERROR.getState());
            result.put("msg", ReturnStateEnum.SERVER_INNER_ERROR.getMsg());
        }
        return JsonEncoder.DEFAULT.encode(result);
    }

    @RequestMapping("webqueryhasbind")
    public Object queryHasBind(HttpServletRequest request){
        RpcForm rpcForm = findHasHMap(RpcForm.class);
        try {
            WEB_LOG.info("webqueryhasbind_接收到的请求参数为:{}", JsonEncoder.DEFAULT.encode(rpcForm));
        } catch (Exception e) {
        }
        Map<String, Object> preValidRes = validPreRequest(request, rpcForm);
        if (null != preValidRes) {
            return JsonEncoder.DEFAULT.encode(preValidRes);
        }
        String username=rpcForm.getStr("username");
        Map<String,Object> result=getResMap();
        if(StringUtils.isEmpty(username)){
            result.put("state",ReturnStateEnum.USER_NAME_IS_NOT_EMPTY.getState());
            result.put("msg",ReturnStateEnum.USER_NAME_IS_NOT_EMPTY.getMsg());
            return JsonEncoder.DEFAULT.encode(result);
        }
        GameUser gameUser = userService.login(username).getLoginUser();
        if(null==gameUser){
            result.put("state",ReturnStateEnum.USER_NOT_FOUND.getState());
            result.put("msg",ReturnStateEnum.USER_NOT_FOUND.getMsg());
        }else{
            if(!StringUtils.isEmpty(gameUser.getPhone_num())){
                result.put("state", ReturnStateEnum.SUCCESS.getState());
                result.put("msg", ReturnStateEnum.SUCCESS.getMsg());
                Map<String,String> temp=new HashMap<>();
                temp.put("mobile",gameUser.getPhone_num());
                result.put("data",temp);
            }else{
                result.put("state", ReturnStateEnum.BIND_PHONE_ERROR.getState());
                result.put("msg", ReturnStateEnum.BIND_PHONE_ERROR.getMsg());
            }
        }
        return JsonEncoder.DEFAULT.encode(result);
    }

    @RequestMapping("webquery_balance")
    public Object queryBalance(HttpServletRequest request){
        RpcForm rpcForm = findHasHMap(RpcForm.class);
        try {
            WEB_LOG.info("webquery_balance_接收到的请求参数为:{}", JsonEncoder.DEFAULT.encode(rpcForm));
        } catch (Exception e) {
        }
        Map<String, Object> preValidRes = validPreRequest(request, rpcForm);
        if (null != preValidRes) {
            return JsonEncoder.DEFAULT.encode(preValidRes);
        }
        String username=rpcForm.getStr("username");
        Map<String,Object> result=getResMap();
        if(StringUtils.isEmpty(username)){
            result.put("state",ReturnStateEnum.USER_NAME_IS_NOT_EMPTY.getState());
            result.put("msg",ReturnStateEnum.USER_NAME_IS_NOT_EMPTY.getMsg());
            return JsonEncoder.DEFAULT.encode(result);
        }
        GameUser gameUser = userService.login(username).getLoginUser();
        if(null==gameUser){
            result.put("state",ReturnStateEnum.USER_NOT_FOUND.getState());
            result.put("msg",ReturnStateEnum.USER_NOT_FOUND.getMsg());
        }else{
            GameUser tempUser=userService.getGameUserById(gameUser.getUin()).getLoginUser();
            int gameTotalCoin=gameUser.getPlatform_coin()+tempUser.getGameTotalCoin();
            if (gameTotalCoin <=0) {
                result.put("state", ReturnStateEnum.PLATFORM_COIN_NOT_ENOUGH.getState());
                result.put("msg", ReturnStateEnum.PLATFORM_COIN_NOT_ENOUGH.getMsg());
            } else {
                result.put("state", ReturnStateEnum.SUCCESS.getState());
                result.put("msg", ReturnStateEnum.SUCCESS.getMsg());
                result.put("total_balance", gameTotalCoin);
            }
        }
        return JsonEncoder.DEFAULT.encode(result);
    }
}


text:
layout: article
title: 题目
description: 摘要。
category: 分类
image:
    #feature: /teaser/出现在文章内容页.jpg
    teaser: /teaser/出现在首页.jpg
---
>  摘要: {{page.description}}

---

[longstreet]:    http://longstreetcc.github.io  "longstreet"

![Project Euler](https://projecteuler.net/profile/longstreet.png)


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Rua</tipo><logradouro>Hungria</logradouro><bairro>Jardins</bairro><cidade>Barreiras</cidade><uf>BA</uf><cep>47803132</cep></feed>


text:
package net.kuesters.mobile.phonegap.api;

import java.util.HashMap;
import java.util.Map;

import net.kuesters.mobile.phonegap.model.App;
import net.kuesters.mobile.phonegap.model.App.Platform;

import org.json.simple.JSONObject;

/**
 * The class to represent the data of a read app response on the PhoneGap Build API.
 *
 * @author Jens Küsters
 * @see App
 */
public class ReadAppResponse implements PhoneGapBuildApiResponse {

	/** The link. */
	private String link;

	/** The app. */
	private App app;

	/**
	 * Instantiates a new read app response.
	 *
	 * @param jsonObject
	 *            the JSON object
	 */
	public ReadAppResponse(JSONObject jsonObject) {
		init(jsonObject);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * app.services.phonegap.api.PhoneGapBuildApiResponse#init(org.json.simple
	 * .JSONObject)
	 */
	@Override
	public void init(JSONObject jsonObject) {
		this.link = (String) jsonObject.get("link");

		String title = (String) jsonObject.get("title");
		long id = (Long) jsonObject.get("id");
		String packageName = (String) jsonObject.get("package");
		String version = (String) jsonObject.get("version");
		String repo = (String) jsonObject.get("repo");
		String description = (String) jsonObject.get("description");
		boolean debug = (Boolean) jsonObject.get("debug");
		boolean privateApp = (Boolean) jsonObject.get("private");
		long buildCount = jsonObject.get("build_count") != null ? (Long) jsonObject.get("build_count") : 0;
		// the following maps stay empty. The might be filled later.
		Map<Platform, String> status = new HashMap<App.Platform, String>();
		Map<Platform, String> download = new HashMap<App.Platform, String>();
		this.app = new App(title, id, packageName, version, repo, description, debug, privateApp, buildCount, status, download);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see app.services.phonegap.api.PhoneGapBuildApiResponse#getLink()
	 */
	@Override
	public String getLink() {
		return link;
	}

	/**
	 * Gets the app.
	 *
	 * @return the app
	 */
	public App getApp() {
		return app;
	}

}


text:
import csv, string, sys

nomenclatural_statuses_to_keep = {}
for status in [
               '',
               'conservandum',
               'nom. cons.',
               'Nom. cons.',
               'nom. cons. des.',
               'nom. cons. prop.',
               'protectum',
               'Nomen novum',
               'correctum',
               'orth. cons.',
               'legitimate',
               'www.nearctica.com/nomina/beetle/colteneb.htm',
               'Ruhberg et al., 1988',
               'later usage',
               ]:
    nomenclatural_statuses_to_keep[status] = True

not_extinct = ['1531',     # Sarcopterygii
               '10565',    # Saurischia
               '118547',    # Aviculariidae
               '1402700', # Trophomera
               # '11919',    # Didelphimorphia
               # '1021564',  # Cruciplacolithus
               # '1530',     # Actinopterygii

               #'1170022',  # Tipuloidea
               #'1340611',  # Retaria
               #'1124871',  # Labyrinthulomycetes [Labyrinthomorpha??]
               #'102024',   # Ophiurinidae - problem is Ophiurina
               #'1064058',  # Rhynchonelloidea genus/superfamily
               #'1114655',  # Tetrasphaera - different from GBIF
               ]

# These are the taxa with taxonomic status '' that occurred in phylesystem as of
# June 2016 (when these taxa were deleted from OTT).  (from deprecated.tsv)

grandfathered = {}

def init_grandfathered(grandfathered):
    for (id, name) in [
        ('10180190', 'Opulaster opulifolius'),
        ('11899420', 'Palaemonetes granulosus'),
        ('11704707', 'Olivioxantho denticulatus'),
        ('10527330', 'Chamaeleolis chameleontides'),
        ('11399158', 'Phyrignathus lesuerii'),
        ('10527966', 'Cylicia magna'),
        ('11444963', 'Epicrates anguilifer'),
        ('11078615', 'Egernia whitei'),
        ('10522666', 'Trogon aurantiventris'),
        ('10692084', 'Tauraco livingstoni'),
        ('10525002', 'Piculus leucolalemus'),
        ('10520170', 'Archaeopteryx lithographica'),
        ('11444785', 'Mesopropithecus pithecoides'),
        ('11167068', 'Zalambdalestes lechei'),
        ('10531957', 'Protungulatum donnae'),
        ('11024850', 'Megaladapis madagascariensis'),
        ('11078603', 'Megaladapis grandidieri'),
        ('11458858', 'Anthropornis nordenskjoeldi'),
        ('11081142', 'Gobipteryx minuta'),
        ('11390044', 'Pagophilus groenlandica'),
        ('10793056', 'Ommatophoca rossi'),
        ('10525092', 'Sivatherium giganteum'),
        ('10692824', 'Mesohippus bairdi'),
        ('10689467', 'Penaeus semisculcatus'),
        ('10543655', 'Palaemonetes atribunes'),
        ('10530648', 'Albunea occulatus'),
        ('102843', 'Hypsidoridae'),
        ('10697026', 'Badumna longinquus'),
        ('10184114', 'Cylactis pubescens'),
        ('11256401', 'Melanobatus leucodermis'),
        ('11083597', 'Squilla mikado'),
        ('11102182', 'Basilosaurus cetoides'),
        ('11103647', 'Pseudastacus pustulosa'),
        ('10532033', 'Hyopsodus paulus'),
        ('1435408', 'Auletes'),
        ('10532250', 'Allosaurus fragilis'),
        ('10537012', 'Gallimimus bullatus'),
        ('1178867', 'Songlingornis'),
        ('10532020', 'Cypselosoma australis'),
        ('1407317', 'Lithornis'),
        ('10957072', 'Velociraptor mongoliensis'),
    ]:
        grandfathered[id] = name

init_grandfathered(grandfathered)

irmng_file_name = sys.argv[1]
profile_file_name = sys.argv[2]
taxonomy_file_name = sys.argv[3]
synonyms_file_name = sys.argv[4]

taxa = {}
synonyms = {}
roots = []

class Taxon:
    def __init__(self, id, parentid, name, rank, tstatus, nstatus):
        self.id = id
        self.parentid = parentid
        self.name = name
        self.rank = rank
        self.tstatus = tstatus
        self.nstatus = nstatus
        self.keep = False
        self.extinctp = False

def read_irmng():

    # 0 "TAXONID","SCIENTIFICNAME","SCIENTIFICNAMEAUTHORSHIP","GENUS",
    # 4 "SPECIFICEPITHET","FAMILY","TAXONRANK","TAXONOMICSTATUS",
    # 8 "NOMENCLATURALSTATUS","NAMEACCORDINGTO","ORIGINALNAMEUSAGEID",
    # 11 "NAMEPUBLISHEDIN","ACCEPTEDNAMEUSAGEID","PARENTNAMEUSAGE",
    # 14 "PARENTNAMEUSAGEID","TAXONREMARKS","MODIFIED","NOMENCLATURALCODE"

    rows = 0
    source_taxon_count = 0
    source_synonym_count = 0
    unallocated = 0

    with open(irmng_file_name, 'rb') as csvfile:
        csvreader = csv.reader(csvfile)
        header = csvreader.next()
        if header[5] != 'FAMILY':
            print >>sys.stderr, '** Unexpected column name in header row', header[-3]
        for row in csvreader:
            taxonid = row[0]
            longname = row[1]
            auth = row[2]
            rank = row[6]
            tstatus = row[7]         # TAXONOMICSTATUS
            nstatus = row[8]         # NOMENCLATURALSTATUS
            syn_target_id = row[12]
            parent = row[-4]
            synonymp = (tstatus == 'synonym' or (syn_target_id != '' and syn_target_id != taxonid))
            if synonymp:
                source_synonym_count += 1
            else:
                source_taxon_count += 1

            # Kludge to get rid of redundancies e.g. Megastoma
            if tstatus == '':
                for value in row:
                    if 'awaiting allocation' in value:
                        tstatus = 'lose'
                        unallocated += 1
                        break

            if parent == '':
                roots.append(taxonid)
            # Calculate taxon name
            genus = row[3]
            if rank == 'species':
                epithet = row[4]
                name = ('%s %s')%(genus,epithet)
            elif rank == 'genus':
                name = genus
            elif rank == 'family':
                family = row[5]
                name = family
            elif len(auth) > 0 and longname.endswith(auth):
                name = longname[0:len(longname)-len(auth)-1]
            else:
                name = longname
            taxon = Taxon(taxonid, parent, name, rank, tstatus, nstatus)
            if synonymp:
                taxon.parentid = syn_target_id
                synonyms[taxonid] = taxon
            else:
                taxa[taxonid] = taxon
            rows += 1
            if rows % 250000 == 0:
                print >>sys.stderr, rows, taxonid, name
                # FOR DEBUGGING
                # break

    print >>sys.stderr, 'Source: %s taxa, %s synonyms' % (source_taxon_count, source_synonym_count)
    print >>sys.stderr, 'Flushing %s unallocated' % unallocated

    print >>sys.stderr, 'Processed: %s taxa, %s synonyms' % (len(taxa), len(synonyms))

def fix_irmng():

    # Get rid of all synonym of a synonym

    # "10704","Decapoda Latreille, 1802","Latreille, 1802",,,,"order",,,,,,,"Malacostraca","1190","cf. Decapoda (Mollusca)","01-01-2012","ICZN"

    loser_synonyms = {}
    for syn in synonyms.itervalues():
        if syn.parentid in synonyms:
            loser_synonyms[syn.id] = True
    print >>sys.stderr, "Indirect synonyms:", len(loser_synonyms)
    for syn_id in loser_synonyms:
        del synonyms[syn_id]

    # Short-circuit taxon parents that are synonyms

    loser_parent_count = 0
    for taxon in taxa.itervalues():
        if taxon.parentid in synonyms:
            taxon.parentid = synonyms[taxon.parentid].parentid
            loser_parent_count += 1
    print >>sys.stderr, "Indirect parents:", loser_parent_count

    # Decide which taxa to keep

    keep_count = 0
    missing_parent_count = 0
    taxon_statuses_to_keep = ['accepted', 'valid', '']
    for taxon in taxa.itervalues():
        if taxon.keep:
            True    # already seen
        elif (taxon.id in grandfathered or
              (taxon.tstatus in taxon_statuses_to_keep and
                # reduces number of kept taxa from 1685133 to 1351145
               taxon.nstatus in nomenclatural_statuses_to_keep)):
            scan = taxon
            while not scan.keep:
                if scan.id in grandfathered: print >>sys.stderr, 'Grandfathering', taxon.name
                scan.keep = True
                keep_count += 1
                if scan.parentid == '':
                    break
                parent = taxa.get(scan.parentid)
                if parent == None:
                    missing_parent_count += 1
                    break
                scan = parent

    print >>sys.stderr, "Keeping %s taxa" % keep_count
    print >>sys.stderr, "%s missing parents" % missing_parent_count

    # Read the file that has the extinct annotations

    with open(profile_file_name, 'rb') as csvfile:
        csvreader = csv.reader(csvfile)
        header = csvreader.next()
        if header[1] != 'ISEXTINCT':
            print >>sys.stderr, "** Expected to find ISEXTINCT in header row but didn't:", header[1]
        for row in csvreader:
            taxonid = row[0]
            taxon = taxa.get(taxonid)
            if taxon == None: continue
            taxon.extinctp = (row[1] == 'TRUE')
            if taxonid in not_extinct:
                if not taxon.extinctp:
                    print >>sys.stderr, 'Already not extinct: %s(%s)' % (taxonid, taxon.name)
                else:
                    print >>sys.stderr, 'Fixing extinctness of %s(%s)' % (taxonid, taxon.name)
                    taxon.extinctp = False

def extinctness_report():
    # Report on nonextinct descended from extinct

    count = 0
    for taxon in taxa.itervalues():
        if taxon.keep and not taxon.extinctp:
            parentid = taxon.parentid
            parent = taxa.get(parentid)
            if parent != None and parent.extinctp:
                count += 1
                if taxon.rank != 'species':
                    print >>sys.stderr, ("Extant taxon %s(%s) with extinct parent %s(%s)"%
                                         (taxon.id, taxon.name, parentid, parent.name))

    print >>sys.stderr, 'Extant taxa with extinct parent:', count

# Write it out

# Returns True if one or more children also got written

def write_irmng():

    def write_taxon(taxon, taxfile):
        parentid = taxon.parentid
        if parentid == '':
            parentid = '0'
        flags = ''
        if taxon.extinctp:
            flags = 'extinct'
        taxfile.write('%s\t|\t%s\t|\t%s\t|\t%s\t|\t%s\t|\t\n'%(taxon.id, parentid, taxon.name, taxon.rank, flags))

    with open(taxonomy_file_name, 'w') as taxfile:
        print 'Writing %s'%taxonomy_file_name
        taxfile.write('%s\t|\t%s\t|\t%s\t|\t%s\t|\t%s\t|\t\n'%('uid', 'parent_uid', 'name', 'rank', 'flags'))
        taxfile.write('%s\t|\t%s\t|\t%s\t|\t%s\t|\t%s\t|\t\n'%('0', '', 'life', 'no rank', ''))
        for taxon in taxa.itervalues():
            if taxon.keep:
                write_taxon(taxon, taxfile)

    with open(synonyms_file_name, 'w') as synfile:
        print 'Writing %s'%synonyms_file_name
        synfile.write('uid\t|\tname\t|\ttype\t|\t\n')
        for syn in synonyms.itervalues():
            taxon = taxa.get(syn.parentid)
            if taxon != None and taxon.keep and not taxon.extinctp:
                status = syn.nstatus
                if status == '':
                    status = syn.tstatus
                    if status == '': status = 'synonym'
                synfile.write('%s\t|\t%s\t|\t%s\t|\t\n'%(syn.parentid, syn.name, status.lower()))

read_irmng()
fix_irmng()
extinctness_report()
write_irmng()


text:
/* globals jQuery */

(function($) {
  // Selector to select only not already processed elements
  $.expr[":"].notmdproc = function(obj){
    if ($(obj).data("mdproc")) {
      return false;
    } else {
      return true;
    }
  };

  function _isChar(evt) {
    if (typeof evt.which == "undefined") {
      return true;
    } else if (typeof evt.which == "number" && evt.which > 0) {
      return !evt.ctrlKey && !evt.metaKey && !evt.altKey && evt.which != 8 && evt.which != 9;
    }
    return false;
  }

  $.material =  {
    "options": {
      // These options set what will be started by $.material.init()
      "input": true,
      "ripples": true,
      "checkbox": true,
      "togglebutton": true,
      "radio": true,
      "arrive": true,
      "autofill": false,

      "withRipples": [
        ".btn:not(.btn-link)",
        ".card-image",
        ".navbar a:not(.withoutripple)",
        ".dropdown-menu a",
        ".nav-tabs a:not(.withoutripple)",
        ".withripple",
        ".pagination li:not(.active):not(.disabled) a:not(.withoutripple)"
      ].join(","),
      "inputElements": "input.form-control, textarea.form-control, select.form-control",
      "checkboxElements": ".checkbox > label > input[type=checkbox]",
      "togglebuttonElements": ".togglebutton > label > input[type=checkbox]",
      "radioElements": ".radio > label > input[type=radio]"
    },
    "checkbox": function(selector) {
      // Add fake-checkbox to material checkboxes
      $((selector) ? selector : this.options.checkboxElements)
      .filter(":notmdproc")
      .data("mdproc", true)
      .after("");
    },
    "togglebutton": function(selector) {
      // Add fake-checkbox to material checkboxes
      $((selector) ? selector : this.options.togglebuttonElements)
      .filter(":notmdproc")
      .data("mdproc", true)
      .after("");
    },
    "radio": function(selector) {
      // Add fake-radio to material radios
      $((selector) ? selector : this.options.radioElements)
      .filter(":notmdproc")
      .data("mdproc", true)
      .after("");
    },
    "input": function(selector) {
      $((selector) ? selector : this.options.inputElements)
      .filter(":notmdproc")
      .data("mdproc", true)
      .each( function() {
        var $this = $(this);

        if (!$this.attr("data-hint") && !$this.hasClass("floating-label")) {
          return;
        }
        $this.wrap("

");
        $this.after("");

        // Add floating label if required
        if ($this.hasClass("floating-label")) {
          var placeholder = $this.attr("placeholder");
          $this.attr("placeholder", null).removeClass("floating-label");
          $this.after("
" + placeholder + "
");
        }

        // Add hint label if required
        if ($this.attr("data-hint")) {
          $this.after("
" + $this.attr("data-hint") + "
");
        }

        // Set as empty if is empty (damn I must improve this...)
        if ($this.val() === null || $this.val() == "undefined" || $this.val() === "") {
          $this.addClass("empty");
        }

        // Support for file input
        if ($this.parent().next().is("[type=file]")) {
          $this.parent().addClass("fileinput");
          var $input = $this.parent().next().detach();
          $this.after($input);
        }
      });
    },
    "attachInputEventHandlers": function() {
      $(document)
      .on("change", ".checkbox input[type=checkbox]", function() { $(this).blur(); })
      .on("keydown paste", ".form-control", function(e) {
        if(_isChar(e)) {
          $(this).removeClass("empty");
        }
      })
      .on("keyup change", ".form-control", function() {
        var $this = $(this);
        if ($this.val() === "" && (typeof $this[0].checkValidity != "undefined" && !$this[0].checkValidity())) {
          $this.addClass("empty");
        } else {
          $this.removeClass("empty");
        }
      })
      .on("focus", ".form-control-wrapper.fileinput", function() {
        $(this).find("input").addClass("focus");
      })
      .on("blur", ".form-control-wrapper.fileinput", function() {
        $(this).find("input").removeClass("focus");
      })
      .on("change", ".form-control-wrapper.fileinput [type=file]", function() {
        var $this = $(this);
        var value = "";
        $.each(this.files, function(i, file) {
          value += file.name + ", ";
        });
        value = value.substring(0, value.length - 2);
        if (value) {
          $this.prev().removeClass("empty");
        } else {
          $this.prev().addClass("empty");
        }
        $this.prev().val(value);
      });
    },
    "ripples": function(selector) {
      $((selector) ? selector : this.options.withRipples).ripples();
    },
    "autofill": function() {
      // This part of code will detect autofill when the page is loading (username and password inputs for example)
      var loading = setInterval(function() {
        $("input[type!=checkbox]").each(function() {
          var $this = $(this);
          if ($this.val() && $this.val() !== $this.attr("value")) {
            $this.trigger("change");
          }
        });
      }, 100);

      // After 10 seconds we are quite sure all the needed inputs are autofilled then we can stop checking them
      setTimeout(function() {
        clearInterval(loading);
      }, 10000);
    },
    "attachAutofillEventHandlers": function() {
      // Listen on inputs of the focused form (because user can select from the autofill dropdown only when the input has focus)
      var focused;
      $(document)
      .on("focus", "input", function() {
        var $inputs = $(this).parents("form").find("input").not("[type=file]");
        focused = setInterval(function() {
          $inputs.each(function() {
            var $this = $(this);
            if ($this.val() !== $this.attr("value")) {
              $this.trigger("change");
            }
          });
        }, 100);
      })
      .on("blur", "input", function() {
        clearInterval(focused);
      });
    },
    "init": function() {
      var $document = $(document);

      if ($.fn.ripples && this.options.ripples) {
        this.ripples();
      }
      if (this.options.input) {
        this.input();
        this.attachInputEventHandlers();
      }
      if (this.options.checkbox) {
        this.checkbox();
      }
      if (this.options.togglebutton) {
        this.togglebutton();
      }
      if (this.options.radio) {
        this.radio();
      }
      if (this.options.autofill) {
        this.autofill();
        this.attachAutofillEventHandlers();
      }

      if (document.arrive && this.options.arrive) {
        if ($.fn.ripples && this.options.ripples) {
          $document.arrive(this.options.withRipples, function() {
            $.material.ripples($(this));
          });
        }
        if (this.options.input) {
          $document.arrive(this.options.inputElements, function() {
            $.material.input($(this));
          });
        }
        if (this.options.checkbox) {
          $document.arrive(this.options.checkboxElements, function() {
            $.material.checkbox($(this));
          });
        }
        if (this.options.radio) {
          $document.arrive(this.options.radioElements, function() {
            $.material.radio($(this));
          });
        }
        if (this.options.togglebutton) {
          $document.arrive(this.options.togglebuttonElements, function() {
            $.material.togglebutton($(this));
          });
        }

      }
    }
  };

})(jQuery);


text:
(function(){

  angular.module('backfeeds')
    .factory('Feedback', function($resource){
      return $resource('https://backfeeds.herokuapp.com/feedbacks/:id');
    })
    .factory('Comment', function($resource){
      return function(feedbackId) {
        return $resource('https://backfeeds.herokuapp.com/feedbacks/:feedbackId/comments/:id', { feedbackId: feedbackId });
      }
    })
    .factory('Notation', function($resource){
      return function(feedbackId) {
        return $resource('https://backfeeds.herokuapp.com/feedbacks/:feedbackId/notations/:id', { feedbackId: feedbackId });
      }
    });

})();


text:
using namespace std;

int main()
{

    subject* s = new subject();
    Observer* ob1 = new Observer();
    ObserverEx* ob2 = new ObserverEx();
    s->registerObserver(ob1);
    s->registerObserver(ob2);
    s->setState (10);

    cout<<"开始反注册观察者对象"<<endl;
    s->removeObserver(ob1);
    //s->registerObserver(ob2);
    s->setState (12);

    return 0;
}