text:
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Grpc.Testing {

  [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
  public static partial class Messages {

    #region Descriptor
    public static pbr::FileDescriptor Descriptor {
      get { return descriptor; }
    }
    private static pbr::FileDescriptor descriptor;

    static Messages() {
      byte[] descriptorData = global::System.Convert.FromBase64String(
          string.Concat(
            "Cg5tZXNzYWdlcy5wcm90bxIMZ3JwYy50ZXN0aW5nIkAKB1BheWxvYWQSJwoE",
            "dHlwZRgBIAEoDjIZLmdycGMudGVzdGluZy5QYXlsb2FkVHlwZRIMCgRib2R5",
            "GAIgASgMIrEBCg1TaW1wbGVSZXF1ZXN0EjAKDXJlc3BvbnNlX3R5cGUYASAB",
            "KA4yGS5ncnBjLnRlc3RpbmcuUGF5bG9hZFR5cGUSFQoNcmVzcG9uc2Vfc2l6",
            "ZRgCIAEoBRImCgdwYXlsb2FkGAMgASgLMhUuZ3JwYy50ZXN0aW5nLlBheWxv",
            "YWQSFQoNZmlsbF91c2VybmFtZRgEIAEoCBIYChBmaWxsX29hdXRoX3Njb3Bl",
            "GAUgASgIIl8KDlNpbXBsZVJlc3BvbnNlEiYKB3BheWxvYWQYASABKAsyFS5n",
            "cnBjLnRlc3RpbmcuUGF5bG9hZBIQCgh1c2VybmFtZRgCIAEoCRITCgtvYXV0",
            "aF9zY29wZRgDIAEoCSJDChlTdHJlYW1pbmdJbnB1dENhbGxSZXF1ZXN0EiYK",
            "B3BheWxvYWQYASABKAsyFS5ncnBjLnRlc3RpbmcuUGF5bG9hZCI9ChpTdHJl",
            "YW1pbmdJbnB1dENhbGxSZXNwb25zZRIfChdhZ2dyZWdhdGVkX3BheWxvYWRf",
            "c2l6ZRgBIAEoBSI3ChJSZXNwb25zZVBhcmFtZXRlcnMSDAoEc2l6ZRgBIAEo",
            "BRITCgtpbnRlcnZhbF91cxgCIAEoBSK1AQoaU3RyZWFtaW5nT3V0cHV0Q2Fs",
            "bFJlcXVlc3QSMAoNcmVzcG9uc2VfdHlwZRgBIAEoDjIZLmdycGMudGVzdGlu",
            "Zy5QYXlsb2FkVHlwZRI9ChNyZXNwb25zZV9wYXJhbWV0ZXJzGAIgAygLMiAu",
            "Z3JwYy50ZXN0aW5nLlJlc3BvbnNlUGFyYW1ldGVycxImCgdwYXlsb2FkGAMg",
            "ASgLMhUuZ3JwYy50ZXN0aW5nLlBheWxvYWQiRQobU3RyZWFtaW5nT3V0cHV0",
            "Q2FsbFJlc3BvbnNlEiYKB3BheWxvYWQYASABKAsyFS5ncnBjLnRlc3Rpbmcu",
            "UGF5bG9hZCo/CgtQYXlsb2FkVHlwZRIQCgxDT01QUkVTU0FCTEUQABISCg5V",
            "TkNPTVBSRVNTQUJMRRABEgoKBlJBTkRPTRACYgZwcm90bzM="));
      descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
          new pbr::FileDescriptor[] { },
          new pbr::GeneratedCodeInfo(new[] {typeof(global::Grpc.Testing.PayloadType), }, new pbr::GeneratedCodeInfo[] {
            new pbr::GeneratedCodeInfo(typeof(global::Grpc.Testing.Payload), new[]{ "Type", "Body" }, null, null, null),
            new pbr::GeneratedCodeInfo(typeof(global::Grpc.Testing.SimpleRequest), new[]{ "ResponseType", "ResponseSize", "Payload", "FillUsername", "FillOauthScope" }, null, null, null),
            new pbr::GeneratedCodeInfo(typeof(global::Grpc.Testing.SimpleResponse), new[]{ "Payload", "Username", "OauthScope" }, null, null, null),
            new pbr::GeneratedCodeInfo(typeof(global::Grpc.Testing.StreamingInputCallRequest), new[]{ "Payload" }, null, null, null),
            new pbr::GeneratedCodeInfo(typeof(global::Grpc.Testing.StreamingInputCallResponse), new[]{ "AggregatedPayloadSize" }, null, null, null),
            new pbr::GeneratedCodeInfo(typeof(global::Grpc.Testing.ResponseParameters), new[]{ "Size", "IntervalUs" }, null, null, null),
            new pbr::GeneratedCodeInfo(typeof(global::Grpc.Testing.StreamingOutputCallRequest), new[]{ "ResponseType", "ResponseParameters", "Payload" }, null, null, null),
            new pbr::GeneratedCodeInfo(typeof(global::Grpc.Testing.StreamingOutputCallResponse), new[]{ "Payload" }, null, null, null)
          }));
    }
    #endregion

  }
  #region Enums
  public enum PayloadType {
    COMPRESSABLE = 0,
    UNCOMPRESSABLE = 1,
    RANDOM = 2,
  }

  #endregion

  #region Messages
  [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
  public sealed partial class Payload : pb::IMessage<Payload> {
    private static readonly pb::MessageParser<Payload> _parser = new pb::MessageParser<Payload>(() => new Payload());
    public static pb::MessageParser<Payload> Parser { get { return _parser; } }

    public static pbr::MessageDescriptor Descriptor {
      get { return global::Grpc.Testing.Messages.Descriptor.MessageTypes[0]; }
    }

    pbr::MessageDescriptor pb::IMessage.Descriptor {
      get { return Descriptor; }
    }

    public Payload() {
      OnConstruction();
    }

    partial void OnConstruction();

    public Payload(Payload other) : this() {
      type_ = other.type_;
      body_ = other.body_;
    }

    public Payload Clone() {
      return new Payload(this);
    }

    public const int TypeFieldNumber = 1;
    private global::Grpc.Testing.PayloadType type_ = global::Grpc.Testing.PayloadType.COMPRESSABLE;
    public global::Grpc.Testing.PayloadType Type {
      get { return type_; }
      set {
        type_ = value;
      }
    }

    public const int BodyFieldNumber = 2;
    private pb::ByteString body_ = pb::ByteString.Empty;
    public pb::ByteString Body {
      get { return body_; }
      set {
        body_ = pb::Preconditions.CheckNotNull(value, "value");
      }
    }

    public override bool Equals(object other) {
      return Equals(other as Payload);
    }

    public bool Equals(Payload other) {
      if (ReferenceEquals(other, null)) {
        return false;
      }
      if (ReferenceEquals(other, this)) {
        return true;
      }
      if (Type != other.Type) return false;
      if (Body != other.Body) return false;
      return true;
    }

    public override int GetHashCode() {
      int hash = 1;
      if (Type != global::Grpc.Testing.PayloadType.COMPRESSABLE) hash ^= Type.GetHashCode();
      if (Body.Length != 0) hash ^= Body.GetHashCode();
      return hash;
    }

    public override string ToString() {
      return pb::JsonFormatter.Default.Format(this);
    }

    public void WriteTo(pb::CodedOutputStream output) {
      if (Type != global::Grpc.Testing.PayloadType.COMPRESSABLE) {
        output.WriteRawTag(8);
        output.WriteEnum((int) Type);
      }
      if (Body.Length != 0) {
        output.WriteRawTag(18);
        output.WriteBytes(Body);
      }
    }

    public int CalculateSize() {
      int size = 0;
      if (Type != global::Grpc.Testing.PayloadType.COMPRESSABLE) {
        size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Type);
      }
      if (Body.Length != 0) {
        size += 1 + pb::CodedOutputStream.ComputeBytesSize(Body);
      }
      return size;
    }

    public void MergeFrom(Payload other) {
      if (other == null) {
        return;
      }
      if (other.Type != global::Grpc.Testing.PayloadType.COMPRESSABLE) {
        Type = other.Type;
      }
      if (other.Body.Length != 0) {
        Body = other.Body;
      }
    }

    public void MergeFrom(pb::CodedInputStream input) {
      uint tag;
      while ((tag = input.ReadTag()) != 0) {
        switch(tag) {
          default:
            input.SkipLastField();
            break;
          case 8: {
            type_ = (global::Grpc.Testing.PayloadType) input.ReadEnum();
            break;
          }
          case 18: {
            Body = input.ReadBytes();
            break;
          }
        }
      }
    }

  }

  [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
  public sealed partial class SimpleRequest : pb::IMessage<SimpleRequest> {
    private static readonly pb::MessageParser<SimpleRequest> _parser = new pb::MessageParser<SimpleRequest>(() => new SimpleRequest());
    public static pb::MessageParser<SimpleRequest> Parser { get { return _parser; } }

    public static pbr::MessageDescriptor Descriptor {
      get { return global::Grpc.Testing.Messages.Descriptor.MessageTypes[1]; }
    }

    pbr::MessageDescriptor pb::IMessage.Descriptor {
      get { return Descriptor; }
    }

    public SimpleRequest() {
      OnConstruction();
    }

    partial void OnConstruction();

    public SimpleRequest(SimpleRequest other) : this() {
      responseType_ = other.responseType_;
      responseSize_ = other.responseSize_;
      Payload = other.payload_ != null ? other.Payload.Clone() : null;
      fillUsername_ = other.fillUsername_;
      fillOauthScope_ = other.fillOauthScope_;
    }

    public SimpleRequest Clone() {
      return new SimpleRequest(this);
    }

    public const int ResponseTypeFieldNumber = 1;
    private global::Grpc.Testing.PayloadType responseType_ = global::Grpc.Testing.PayloadType.COMPRESSABLE;
    public global::Grpc.Testing.PayloadType ResponseType {
      get { return responseType_; }
      set {
        responseType_ = value;
      }
    }

    public const int ResponseSizeFieldNumber = 2;
    private int responseSize_;
    public int ResponseSize {
      get { return responseSize_; }
      set {
        responseSize_ = value;
      }
    }

    public const int PayloadFieldNumber = 3;
    private global::Grpc.Testing.Payload payload_;
    public global::Grpc.Testing.Payload Payload {
      get { return payload_; }
      set {
        payload_ = value;
      }
    }

    public const int FillUsernameFieldNumber = 4;
    private bool fillUsername_;
    public bool FillUsername {
      get { return fillUsername_; }
      set {
        fillUsername_ = value;
      }
    }

    public const int FillOauthScopeFieldNumber = 5;
    private bool fillOauthScope_;
    public bool FillOauthScope {
      get { return fillOauthScope_; }
      set {
        fillOauthScope_ = value;
      }
    }

    public override bool Equals(object other) {
      return Equals(other as SimpleRequest);
    }

    public bool Equals(SimpleRequest other) {
      if (ReferenceEquals(other, null)) {
        return false;
      }
      if (ReferenceEquals(other, this)) {
        return true;
      }
      if (ResponseType != other.ResponseType) return false;
      if (ResponseSize != other.ResponseSize) return false;
      if (!object.Equals(Payload, other.Payload)) return false;
      if (FillUsername != other.FillUsername) return false;
      if (FillOauthScope != other.FillOauthScope) return false;
      return true;
    }

    public override int GetHashCode() {
      int hash = 1;
      if (ResponseType != global::Grpc.Testing.PayloadType.COMPRESSABLE) hash ^= ResponseType.GetHashCode();
      if (ResponseSize != 0) hash ^= ResponseSize.GetHashCode();
      if (payload_ != null) hash ^= Payload.GetHashCode();
      if (FillUsername != false) hash ^= FillUsername.GetHashCode();
      if (FillOauthScope != false) hash ^= FillOauthScope.GetHashCode();
      return hash;
    }

    public override string ToString() {
      return pb::JsonFormatter.Default.Format(this);
    }

    public void WriteTo(pb::CodedOutputStream output) {
      if (ResponseType != global::Grpc.Testing.PayloadType.COMPRESSABLE) {
        output.WriteRawTag(8);
        output.WriteEnum((int) ResponseType);
      }
      if (ResponseSize != 0) {
        output.WriteRawTag(16);
        output.WriteInt32(ResponseSize);
      }
      if (payload_ != null) {
        output.WriteRawTag(26);
        output.WriteMessage(Payload);
      }
      if (FillUsername != false) {
        output.WriteRawTag(32);
        output.WriteBool(FillUsername);
      }
      if (FillOauthScope != false) {
        output.WriteRawTag(40);
        output.WriteBool(FillOauthScope);
      }
    }

    public int CalculateSize() {
      int size = 0;
      if (ResponseType != global::Grpc.Testing.PayloadType.COMPRESSABLE) {
        size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) ResponseType);
      }
      if (ResponseSize != 0) {
        size += 1 + pb::CodedOutputStream.ComputeInt32Size(ResponseSize);
      }
      if (payload_ != null) {
        size += 1 + pb::CodedOutputStream.ComputeMessageSize(Payload);
      }
      if (FillUsername != false) {
        size += 1 + 1;
      }
      if (FillOauthScope != false) {
        size += 1 + 1;
      }
      return size;
    }

    public void MergeFrom(SimpleRequest other) {
      if (other == null) {
        return;
      }
      if (other.ResponseType != global::Grpc.Testing.PayloadType.COMPRESSABLE) {
        ResponseType = other.ResponseType;
      }
      if (other.ResponseSize != 0) {
        ResponseSize = other.ResponseSize;
      }
      if (other.payload_ != null) {
        if (payload_ == null) {
          payload_ = new global::Grpc.Testing.Payload();
        }
        Payload.MergeFrom(other.Payload);
      }
      if (other.FillUsername != false) {
        FillUsername = other.FillUsername;
      }
      if (other.FillOauthScope != false) {
        FillOauthScope = other.FillOauthScope;
      }
    }

    public void MergeFrom(pb::CodedInputStream input) {
      uint tag;
      while ((tag = input.ReadTag()) != 0) {
        switch(tag) {
          default:
            input.SkipLastField();
            break;
          case 8: {
            responseType_ = (global::Grpc.Testing.PayloadType) input.ReadEnum();
            break;
          }
          case 16: {
            ResponseSize = input.ReadInt32();
            break;
          }
          case 26: {
            if (payload_ == null) {
              payload_ = new global::Grpc.Testing.Payload();
            }
            input.ReadMessage(payload_);
            break;
          }
          case 32: {
            FillUsername = input.ReadBool();
            break;
          }
          case 40: {
            FillOauthScope = input.ReadBool();
            break;
          }
        }
      }
    }

  }

  [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
  public sealed partial class SimpleResponse : pb::IMessage<SimpleResponse> {
    private static readonly pb::MessageParser<SimpleResponse> _parser = new pb::MessageParser<SimpleResponse>(() => new SimpleResponse());
    public static pb::MessageParser<SimpleResponse> Parser { get { return _parser; } }

    public static pbr::MessageDescriptor Descriptor {
      get { return global::Grpc.Testing.Messages.Descriptor.MessageTypes[2]; }
    }

    pbr::MessageDescriptor pb::IMessage.Descriptor {
      get { return Descriptor; }
    }

    public SimpleResponse() {
      OnConstruction();
    }

    partial void OnConstruction();

    public SimpleResponse(SimpleResponse other) : this() {
      Payload = other.payload_ != null ? other.Payload.Clone() : null;
      username_ = other.username_;
      oauthScope_ = other.oauthScope_;
    }

    public SimpleResponse Clone() {
      return new SimpleResponse(this);
    }

    public const int PayloadFieldNumber = 1;
    private global::Grpc.Testing.Payload payload_;
    public global::Grpc.Testing.Payload Payload {
      get { return payload_; }
      set {
        payload_ = value;
      }
    }

    public const int UsernameFieldNumber = 2;
    private string username_ = "";
    public string Username {
      get { return username_; }
      set {
        username_ = pb::Preconditions.CheckNotNull(value, "value");
      }
    }

    public const int OauthScopeFieldNumber = 3;
    private string oauthScope_ = "";
    public string OauthScope {
      get { return oauthScope_; }
      set {
        oauthScope_ = pb::Preconditions.CheckNotNull(value, "value");
      }
    }

    public override bool Equals(object other) {
      return Equals(other as SimpleResponse);
    }

    public bool Equals(SimpleResponse other) {
      if (ReferenceEquals(other, null)) {
        return false;
      }
      if (ReferenceEquals(other, this)) {
        return true;
      }
      if (!object.Equals(Payload, other.Payload)) return false;
      if (Username != other.Username) return false;
      if (OauthScope != other.OauthScope) return false;
      return true;
    }

    public override int GetHashCode() {
      int hash = 1;
      if (payload_ != null) hash ^= Payload.GetHashCode();
      if (Username.Length != 0) hash ^= Username.GetHashCode();
      if (OauthScope.Length != 0) hash ^= OauthScope.GetHashCode();
      return hash;
    }

    public override string ToString() {
      return pb::JsonFormatter.Default.Format(this);
    }

    public void WriteTo(pb::CodedOutputStream output) {
      if (payload_ != null) {
        output.WriteRawTag(10);
        output.WriteMessage(Payload);
      }
      if (Username.Length != 0) {
        output.WriteRawTag(18);
        output.WriteString(Username);
      }
      if (OauthScope.Length != 0) {
        output.WriteRawTag(26);
        output.WriteString(OauthScope);
      }
    }

    public int CalculateSize() {
      int size = 0;
      if (payload_ != null) {
        size += 1 + pb::CodedOutputStream.ComputeMessageSize(Payload);
      }
      if (Username.Length != 0) {
        size += 1 + pb::CodedOutputStream.ComputeStringSize(Username);
      }
      if (OauthScope.Length != 0) {
        size += 1 + pb::CodedOutputStream.ComputeStringSize(OauthScope);
      }
      return size;
    }

    public void MergeFrom(SimpleResponse other) {
      if (other == null) {
        return;
      }
      if (other.payload_ != null) {
        if (payload_ == null) {
          payload_ = new global::Grpc.Testing.Payload();
        }
        Payload.MergeFrom(other.Payload);
      }
      if (other.Username.Length != 0) {
        Username = other.Username;
      }
      if (other.OauthScope.Length != 0) {
        OauthScope = other.OauthScope;
      }
    }

    public void MergeFrom(pb::CodedInputStream input) {
      uint tag;
      while ((tag = input.ReadTag()) != 0) {
        switch(tag) {
          default:
            input.SkipLastField();
            break;
          case 10: {
            if (payload_ == null) {
              payload_ = new global::Grpc.Testing.Payload();
            }
            input.ReadMessage(payload_);
            break;
          }
          case 18: {
            Username = input.ReadString();
            break;
          }
          case 26: {
            OauthScope = input.ReadString();
            break;
          }
        }
      }
    }

  }

  [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
  public sealed partial class StreamingInputCallRequest : pb::IMessage<StreamingInputCallRequest> {
    private static readonly pb::MessageParser<StreamingInputCallRequest> _parser = new pb::MessageParser<StreamingInputCallRequest>(() => new StreamingInputCallRequest());
    public static pb::MessageParser<StreamingInputCallRequest> Parser { get { return _parser; } }

    public static pbr::MessageDescriptor Descriptor {
      get { return global::Grpc.Testing.Messages.Descriptor.MessageTypes[3]; }
    }

    pbr::MessageDescriptor pb::IMessage.Descriptor {
      get { return Descriptor; }
    }

    public StreamingInputCallRequest() {
      OnConstruction();
    }

    partial void OnConstruction();

    public StreamingInputCallRequest(StreamingInputCallRequest other) : this() {
      Payload = other.payload_ != null ? other.Payload.Clone() : null;
    }

    public StreamingInputCallRequest Clone() {
      return new StreamingInputCallRequest(this);
    }

    public const int PayloadFieldNumber = 1;
    private global::Grpc.Testing.Payload payload_;
    public global::Grpc.Testing.Payload Payload {
      get { return payload_; }
      set {
        payload_ = value;
      }
    }

    public override bool Equals(object other) {
      return Equals(other as StreamingInputCallRequest);
    }

    public bool Equals(StreamingInputCallRequest other) {
      if (ReferenceEquals(other, null)) {
        return false;
      }
      if (ReferenceEquals(other, this)) {
        return true;
      }
      if (!object.Equals(Payload, other.Payload)) return false;
      return true;
    }

    public override int GetHashCode() {
      int hash = 1;
      if (payload_ != null) hash ^= Payload.GetHashCode();
      return hash;
    }

    public override string ToString() {
      return pb::JsonFormatter.Default.Format(this);
    }

    public void WriteTo(pb::CodedOutputStream output) {
      if (payload_ != null) {
        output.WriteRawTag(10);
        output.WriteMessage(Payload);
      }
    }

    public int CalculateSize() {
      int size = 0;
      if (payload_ != null) {
        size += 1 + pb::CodedOutputStream.ComputeMessageSize(Payload);
      }
      return size;
    }

    public void MergeFrom(StreamingInputCallRequest other) {
      if (other == null) {
        return;
      }
      if (other.payload_ != null) {
        if (payload_ == null) {
          payload_ = new global::Grpc.Testing.Payload();
        }
        Payload.MergeFrom(other.Payload);
      }
    }

    public void MergeFrom(pb::CodedInputStream input) {
      uint tag;
      while ((tag = input.ReadTag()) != 0) {
        switch(tag) {
          default:
            input.SkipLastField();
            break;
          case 10: {
            if (payload_ == null) {
              payload_ = new global::Grpc.Testing.Payload();
            }
            input.ReadMessage(payload_);
            break;
          }
        }
      }
    }

  }

  [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
  public sealed partial class StreamingInputCallResponse : pb::IMessage<StreamingInputCallResponse> {
    private static readonly pb::MessageParser<StreamingInputCallResponse> _parser = new pb::MessageParser<StreamingInputCallResponse>(() => new StreamingInputCallResponse());
    public static pb::MessageParser<StreamingInputCallResponse> Parser { get { return _parser; } }

    public static pbr::MessageDescriptor Descriptor {
      get { return global::Grpc.Testing.Messages.Descriptor.MessageTypes[4]; }
    }

    pbr::MessageDescriptor pb::IMessage.Descriptor {
      get { return Descriptor; }
    }

    public StreamingInputCallResponse() {
      OnConstruction();
    }

    partial void OnConstruction();

    public StreamingInputCallResponse(StreamingInputCallResponse other) : this() {
      aggregatedPayloadSize_ = other.aggregatedPayloadSize_;
    }

    public StreamingInputCallResponse Clone() {
      return new StreamingInputCallResponse(this);
    }

    public const int AggregatedPayloadSizeFieldNumber = 1;
    private int aggregatedPayloadSize_;
    public int AggregatedPayloadSize {
      get { return aggregatedPayloadSize_; }
      set {
        aggregatedPayloadSize_ = value;
      }
    }

    public override bool Equals(object other) {
      return Equals(other as StreamingInputCallResponse);
    }

    public bool Equals(StreamingInputCallResponse other) {
      if (ReferenceEquals(other, null)) {
        return false;
      }
      if (ReferenceEquals(other, this)) {
        return true;
      }
      if (AggregatedPayloadSize != other.AggregatedPayloadSize) return false;
      return true;
    }

    public override int GetHashCode() {
      int hash = 1;
      if (AggregatedPayloadSize != 0) hash ^= AggregatedPayloadSize.GetHashCode();
      return hash;
    }

    public override string ToString() {
      return pb::JsonFormatter.Default.Format(this);
    }

    public void WriteTo(pb::CodedOutputStream output) {
      if (AggregatedPayloadSize != 0) {
        output.WriteRawTag(8);
        output.WriteInt32(AggregatedPayloadSize);
      }
    }

    public int CalculateSize() {
      int size = 0;
      if (AggregatedPayloadSize != 0) {
        size += 1 + pb::CodedOutputStream.ComputeInt32Size(AggregatedPayloadSize);
      }
      return size;
    }

    public void MergeFrom(StreamingInputCallResponse other) {
      if (other == null) {
        return;
      }
      if (other.AggregatedPayloadSize != 0) {
        AggregatedPayloadSize = other.AggregatedPayloadSize;
      }
    }

    public void MergeFrom(pb::CodedInputStream input) {
      uint tag;
      while ((tag = input.ReadTag()) != 0) {
        switch(tag) {
          default:
            input.SkipLastField();
            break;
          case 8: {
            AggregatedPayloadSize = input.ReadInt32();
            break;
          }
        }
      }
    }

  }

  [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
  public sealed partial class ResponseParameters : pb::IMessage<ResponseParameters> {
    private static readonly pb::MessageParser<ResponseParameters> _parser = new pb::MessageParser<ResponseParameters>(() => new ResponseParameters());
    public static pb::MessageParser<ResponseParameters> Parser { get { return _parser; } }

    public static pbr::MessageDescriptor Descriptor {
      get { return global::Grpc.Testing.Messages.Descriptor.MessageTypes[5]; }
    }

    pbr::MessageDescriptor pb::IMessage.Descriptor {
      get { return Descriptor; }
    }

    public ResponseParameters() {
      OnConstruction();
    }

    partial void OnConstruction();

    public ResponseParameters(ResponseParameters other) : this() {
      size_ = other.size_;
      intervalUs_ = other.intervalUs_;
    }

    public ResponseParameters Clone() {
      return new ResponseParameters(this);
    }

    public const int SizeFieldNumber = 1;
    private int size_;
    public int Size {
      get { return size_; }
      set {
        size_ = value;
      }
    }

    public const int IntervalUsFieldNumber = 2;
    private int intervalUs_;
    public int IntervalUs {
      get { return intervalUs_; }
      set {
        intervalUs_ = value;
      }
    }

    public override bool Equals(object other) {
      return Equals(other as ResponseParameters);
    }

    public bool Equals(ResponseParameters other) {
      if (ReferenceEquals(other, null)) {
        return false;
      }
      if (ReferenceEquals(other, this)) {
        return true;
      }
      if (Size != other.Size) return false;
      if (IntervalUs != other.IntervalUs) return false;
      return true;
    }

    public override int GetHashCode() {
      int hash = 1;
      if (Size != 0) hash ^= Size.GetHashCode();
      if (IntervalUs != 0) hash ^= IntervalUs.GetHashCode();
      return hash;
    }

    public override string ToString() {
      return pb::JsonFormatter.Default.Format(this);
    }

    public void WriteTo(pb::CodedOutputStream output) {
      if (Size != 0) {
        output.WriteRawTag(8);
        output.WriteInt32(Size);
      }
      if (IntervalUs != 0) {
        output.WriteRawTag(16);
        output.WriteInt32(IntervalUs);
      }
    }

    public int CalculateSize() {
      int size = 0;
      if (Size != 0) {
        size += 1 + pb::CodedOutputStream.ComputeInt32Size(Size);
      }
      if (IntervalUs != 0) {
        size += 1 + pb::CodedOutputStream.ComputeInt32Size(IntervalUs);
      }
      return size;
    }

    public void MergeFrom(ResponseParameters other) {
      if (other == null) {
        return;
      }
      if (other.Size != 0) {
        Size = other.Size;
      }
      if (other.IntervalUs != 0) {
        IntervalUs = other.IntervalUs;
      }
    }

    public void MergeFrom(pb::CodedInputStream input) {
      uint tag;
      while ((tag = input.ReadTag()) != 0) {
        switch(tag) {
          default:
            input.SkipLastField();
            break;
          case 8: {
            Size = input.ReadInt32();
            break;
          }
          case 16: {
            IntervalUs = input.ReadInt32();
            break;
          }
        }
      }
    }

  }

  [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
  public sealed partial class StreamingOutputCallRequest : pb::IMessage<StreamingOutputCallRequest> {
    private static readonly pb::MessageParser<StreamingOutputCallRequest> _parser = new pb::MessageParser<StreamingOutputCallRequest>(() => new StreamingOutputCallRequest());
    public static pb::MessageParser<StreamingOutputCallRequest> Parser { get { return _parser; } }

    public static pbr::MessageDescriptor Descriptor {
      get { return global::Grpc.Testing.Messages.Descriptor.MessageTypes[6]; }
    }

    pbr::MessageDescriptor pb::IMessage.Descriptor {
      get { return Descriptor; }
    }

    public StreamingOutputCallRequest() {
      OnConstruction();
    }

    partial void OnConstruction();

    public StreamingOutputCallRequest(StreamingOutputCallRequest other) : this() {
      responseType_ = other.responseType_;
      responseParameters_ = other.responseParameters_.Clone();
      Payload = other.payload_ != null ? other.Payload.Clone() : null;
    }

    public StreamingOutputCallRequest Clone() {
      return new StreamingOutputCallRequest(this);
    }

    public const int ResponseTypeFieldNumber = 1;
    private global::Grpc.Testing.PayloadType responseType_ = global::Grpc.Testing.PayloadType.COMPRESSABLE;
    public global::Grpc.Testing.PayloadType ResponseType {
      get { return responseType_; }
      set {
        responseType_ = value;
      }
    }

    public const int ResponseParametersFieldNumber = 2;
    private static readonly pb::FieldCodec<global::Grpc.Testing.ResponseParameters> _repeated_responseParameters_codec
        = pb::FieldCodec.ForMessage(18, global::Grpc.Testing.ResponseParameters.Parser);
    private readonly pbc::RepeatedField<global::Grpc.Testing.ResponseParameters> responseParameters_ = new pbc::RepeatedField<global::Grpc.Testing.ResponseParameters>();
    public pbc::RepeatedField<global::Grpc.Testing.ResponseParameters> ResponseParameters {
      get { return responseParameters_; }
    }

    public const int PayloadFieldNumber = 3;
    private global::Grpc.Testing.Payload payload_;
    public global::Grpc.Testing.Payload Payload {
      get { return payload_; }
      set {
        payload_ = value;
      }
    }

    public override bool Equals(object other) {
      return Equals(other as StreamingOutputCallRequest);
    }

    public bool Equals(StreamingOutputCallRequest other) {
      if (ReferenceEquals(other, null)) {
        return false;
      }
      if (ReferenceEquals(other, this)) {
        return true;
      }
      if (ResponseType != other.ResponseType) return false;
      if(!responseParameters_.Equals(other.responseParameters_)) return false;
      if (!object.Equals(Payload, other.Payload)) return false;
      return true;
    }

    public override int GetHashCode() {
      int hash = 1;
      if (ResponseType != global::Grpc.Testing.PayloadType.COMPRESSABLE) hash ^= ResponseType.GetHashCode();
      hash ^= responseParameters_.GetHashCode();
      if (payload_ != null) hash ^= Payload.GetHashCode();
      return hash;
    }

    public override string ToString() {
      return pb::JsonFormatter.Default.Format(this);
    }

    public void WriteTo(pb::CodedOutputStream output) {
      if (ResponseType != global::Grpc.Testing.PayloadType.COMPRESSABLE) {
        output.WriteRawTag(8);
        output.WriteEnum((int) ResponseType);
      }
      responseParameters_.WriteTo(output, _repeated_responseParameters_codec);
      if (payload_ != null) {
        output.WriteRawTag(26);
        output.WriteMessage(Payload);
      }
    }

    public int CalculateSize() {
      int size = 0;
      if (ResponseType != global::Grpc.Testing.PayloadType.COMPRESSABLE) {
        size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) ResponseType);
      }
      size += responseParameters_.CalculateSize(_repeated_responseParameters_codec);
      if (payload_ != null) {
        size += 1 + pb::CodedOutputStream.ComputeMessageSize(Payload);
      }
      return size;
    }

    public void MergeFrom(StreamingOutputCallRequest other) {
      if (other == null) {
        return;
      }
      if (other.ResponseType != global::Grpc.Testing.PayloadType.COMPRESSABLE) {
        ResponseType = other.ResponseType;
      }
      responseParameters_.Add(other.responseParameters_);
      if (other.payload_ != null) {
        if (payload_ == null) {
          payload_ = new global::Grpc.Testing.Payload();
        }
        Payload.MergeFrom(other.Payload);
      }
    }

    public void MergeFrom(pb::CodedInputStream input) {
      uint tag;
      while ((tag = input.ReadTag()) != 0) {
        switch(tag) {
          default:
            input.SkipLastField();
            break;
          case 8: {
            responseType_ = (global::Grpc.Testing.PayloadType) input.ReadEnum();
            break;
          }
          case 18: {
            responseParameters_.AddEntriesFrom(input, _repeated_responseParameters_codec);
            break;
          }
          case 26: {
            if (payload_ == null) {
              payload_ = new global::Grpc.Testing.Payload();
            }
            input.ReadMessage(payload_);
            break;
          }
        }
      }
    }

  }

  [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
  public sealed partial class StreamingOutputCallResponse : pb::IMessage<StreamingOutputCallResponse> {
    private static readonly pb::MessageParser<StreamingOutputCallResponse> _parser = new pb::MessageParser<StreamingOutputCallResponse>(() => new StreamingOutputCallResponse());
    public static pb::MessageParser<StreamingOutputCallResponse> Parser { get { return _parser; } }

    public static pbr::MessageDescriptor Descriptor {
      get { return global::Grpc.Testing.Messages.Descriptor.MessageTypes[7]; }
    }

    pbr::MessageDescriptor pb::IMessage.Descriptor {
      get { return Descriptor; }
    }

    public StreamingOutputCallResponse() {
      OnConstruction();
    }

    partial void OnConstruction();

    public StreamingOutputCallResponse(StreamingOutputCallResponse other) : this() {
      Payload = other.payload_ != null ? other.Payload.Clone() : null;
    }

    public StreamingOutputCallResponse Clone() {
      return new StreamingOutputCallResponse(this);
    }

    public const int PayloadFieldNumber = 1;
    private global::Grpc.Testing.Payload payload_;
    public global::Grpc.Testing.Payload Payload {
      get { return payload_; }
      set {
        payload_ = value;
      }
    }

    public override bool Equals(object other) {
      return Equals(other as StreamingOutputCallResponse);
    }

    public bool Equals(StreamingOutputCallResponse other) {
      if (ReferenceEquals(other, null)) {
        return false;
      }
      if (ReferenceEquals(other, this)) {
        return true;
      }
      if (!object.Equals(Payload, other.Payload)) return false;
      return true;
    }

    public override int GetHashCode() {
      int hash = 1;
      if (payload_ != null) hash ^= Payload.GetHashCode();
      return hash;
    }

    public override string ToString() {
      return pb::JsonFormatter.Default.Format(this);
    }

    public void WriteTo(pb::CodedOutputStream output) {
      if (payload_ != null) {
        output.WriteRawTag(10);
        output.WriteMessage(Payload);
      }
    }

    public int CalculateSize() {
      int size = 0;
      if (payload_ != null) {
        size += 1 + pb::CodedOutputStream.ComputeMessageSize(Payload);
      }
      return size;
    }

    public void MergeFrom(StreamingOutputCallResponse other) {
      if (other == null) {
        return;
      }
      if (other.payload_ != null) {
        if (payload_ == null) {
          payload_ = new global::Grpc.Testing.Payload();
        }
        Payload.MergeFrom(other.Payload);
      }
    }

    public void MergeFrom(pb::CodedInputStream input) {
      uint tag;
      while ((tag = input.ReadTag()) != 0) {
        switch(tag) {
          default:
            input.SkipLastField();
            break;
          case 10: {
            if (payload_ == null) {
              payload_ = new global::Grpc.Testing.Payload();
            }
            input.ReadMessage(payload_);
            break;
          }
        }
      }
    }

  }

  #endregion

}

#endregion Designer generated code


text:
package io.vertx.mssqlclient.tck;

import io.vertx.mssqlclient.junit.MSSQLRule;
import io.vertx.ext.unit.TestContext;
import io.vertx.sqlclient.tck.PreparedQueryTestBase;
import org.junit.ClassRule;
import org.junit.Ignore;
import org.junit.Test;

public abstract class MSSQLPreparedQueryTestBase extends PreparedQueryTestBase {
  @ClassRule
  public static MSSQLRule rule = MSSQLRule.SHARED_INSTANCE;

  protected void cleanTestTable(TestContext ctx) {
    connect(ctx.asyncAssertSuccess(conn -> {
      conn.query("TRUNCATE TABLE mutable;").execute(ctx.asyncAssertSuccess(result -> {
        conn.close();
      }));
    }));
  }

  @Override
  protected String statement(String... parts) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < parts.length; i++) {
      if (i > 0) {
        sb.append("@p").append((i));
      }
      sb.append(parts[i]);
    }
    return sb.toString();
  }

  @Override
  @Test
  @Ignore
  public void testQueryCursor(TestContext ctx) {
    //TODO cursor support
    super.testQueryCursor(ctx);
  }

  @Override
  @Test
  @Ignore
  public void testQueryCloseCursor(TestContext ctx) {
    //TODO cursor support
    super.testQueryCloseCursor(ctx);
  }

  @Override
  @Test
  @Ignore
  public void testQueryStreamCloseCursor(TestContext ctx) {
    //TODO cursor support
    super.testQueryStreamCloseCursor(ctx);
  }

  @Override
  @Test
  @Ignore
  public void testStreamQueryPauseInBatch(TestContext ctx) {
    // TODO streaming support
    super.testStreamQueryPauseInBatch(ctx);
  }

  @Override
  @Test
  @Ignore
  public void testStreamQueryPauseInBatchFromAnotherThread(TestContext ctx) {
    // TODO streaming support
    super.testStreamQueryPauseInBatchFromAnotherThread(ctx);
  }

  @Override
  @Test
  @Ignore
  public void testStreamQueryPauseResume(TestContext ctx) {
    // TODO streaming support
    super.testStreamQueryPauseResume(ctx);
  }

  @Override
  @Test
  @Ignore
  public void testStreamQuery(TestContext ctx) {
    // TODO streaming support
    super.testStreamQuery(ctx);
  }

  @Override
  @Test
  @Ignore
  public void testPrepareError(TestContext ctx) {
    // prepexec prepared statement will not care about the SQL
    super.testPrepareError(ctx);
  }

  @Override
  @Test
  @Ignore
  public void testPreparedQueryParamCoercionQuantityError(TestContext ctx) {
    // can't check this for now due to prepexec cmd
    super.testPreparedQueryParamCoercionQuantityError(ctx);
  }

  @Override
  @Test
  @Ignore
  public void testPreparedQueryParamCoercionTypeError(TestContext ctx) {
    // can't check this for now due to prepexec cmd
    super.testPreparedQueryParamCoercionTypeError(ctx);
  }
}

redpajama_set_name: RedPajamaGithub


text:
layout: post
title:  "Perl Weekly Challenge 130: quick"
author: Luca Ferrari
tags:
- raku
- perlweeklychallenge
permalink: /:year/:month/:day/:title.html
---
My personal solutions to the Perl Weekly Challenge.

# Perl Weekly Challenge 130: quick

One way to let me improve my knowledge about Raku (aka Perl 6) is to implement programs in it.
Unluckily, I don't have any production code to implement in Raku yet (sob!).
So, why not try solving the [Perl Weekly Challenge](https://perlweeklychallenge.org/){:target="_blank"} tasks?

In the following, the assigned tasks for [Challenge 130](https://perlweeklychallenge.org/blog/perl-weekly-challenge-0130/){:target="_blank"}.

- [Task 1](#task1)
- [Task 2](#task2)

## PWC 130 - Task 1

The first task was quite simple: it required to find out a number in a list of arguments that appears an odd number of times. It is simple enough to solve it by means of `grep` and `for`:

```raku
sub MAIN( *@values where { @values.elems > 1 && @values.grep( * ~~ Int ).elems == @values.elems  } ) {
    $_.say and exit if  @values.grep( $_ ).elems !%% 2 for @values;
}

```

It must be read from right to left: the `for` loop values `$_` to every single element of the array, then the `if` tests if the `$_` is found in the array, and `elems` counts how many time it appears. If the number of times is odd, that is *is not even* (`!%% 2`), the value can be printed out. This is do with a `say`, and then the program exits with a low precedence `and exit`, because the task states that only one number can appear an odd even of times.

## PWC 130 - Task 2

The second task was about verifying if a tree is a balanced binary tree. *I hate trees with a passion!*

I implemented a class `Node` that has the current value, and its descendants, as well as two methods:
- `is-BST` returns `True` if this node respects the rules according to its descendants;
- `is-BST-from-here` recursively tests all the tree and its subtree.

Therefore, testing the tree is as simple as invoking the latter method on the root:

```raku
class Node {
    has Int $.value;
    has Node $.left is rw;
    has Node $.right is rw;

    method is-BST() {
        my $ok-left  = ! $!left  || ( $!left && $!left.value < $!value );
        my $ok-right = ! $!right || ( $!right && $!right.value >= $!value );
        return $ok-left && $ok-right;
    }

    method is-BST-from-here() {
        my $am-I-ok = self.is-BST();
        return False if ! $am-I-ok;

        my $ok-right = True;
        $ok-right = $!right.is-BST-from-here if $!right;
        my $ok-left  = True;
        $ok-left = $!left.is-BST-from-here if $!left;
        return $ok-right && $ok-left;
    }
}

sub MAIN() {
    my $root         = Node.new( value => 8 );
    $root.left       = Node.new( value => 5 );
    $root.left.left  = Node.new( value => 4 );
    $root.left.right = Node.new( value => 6 );
    $root.right      = Node.new( value => 9 );

    "1".say if $root.is-BST-from-here;
}

```

At the end, the program prints `1` as requested by the task only if the tree is a balanced one.


text:
<?php

class LoginFormOauth extends CFormModel
{
	public $email;
	public $password;
	public $rememberMe;
	private $_identity;
	public $token;

	/**
	 * Declares the validation rules.
	 * The rules state that email and password are required,
	 * and password needs to be authenticated.
	 */
	public function rules()
	{
		return array(
			// email and password are required
			array('email, password', 'required'),

			//array('email', 'email'),
			// rememberMe needs to be a boolean
			array('rememberMe', 'boolean'),
            array('token', 'length', 'max'=>32),
			// password needs to be authenticated
			array('password', 'authenticate'),
			array('email, password', 'safe'),
		);
	}

	/**
	 * Declares attribute labels.
	 */
	public function attributeLabels()
	{
		return array(
			'email' => 'Email',
			'password' => 'Password',
			'rememberMe' => 'Remember me next time',
		);
	}

	/**
	 * Authenticates the password.
	 * This is the 'authenticate' validator as declared in rules().
	 */
	public function authenticate($attribute,$params)
	{
		// we only want to authenticate when no input errors
		if(!$this->hasErrors())
		{
			$this->_identity=new OauthIdentity($this->email,$this->password);
			$this->_identity->authenticate();

			switch($this->_identity->errorCode)
			{
				case OauthIdentity::ERROR_NONE:
					Yii::app()->user->login($this->_identity);
					break;
				case OauthIdentity::ERROR_USERNAME_INVALID:
					$this->addError('email','Email address is incorrect.');
					break;
				default: //OauthIdentity::ERROR_PASSWORD_INVALID
					$this->addError('password','Password is incorrect.');
					break;
			}
		}
	}

	/**
	 * Logs in the user using the given email and password in the model.
	 * @return boolean whether login is successful
	 */
	public function login()
	{
		if($this->_identity===null)
		{
			if($this->token !== null)
				$this->_identity=new OauthIdentity($this->email,$this->password, $this->token);
			else
				$this->_identity=new OauthIdentity($this->email,$this->password);
			$this->_identity->authenticate();
		}
		if($this->_identity->errorCode===OauthIdentity::ERROR_NONE)
		{
			$duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days
			Yii::app()->user->login($this->_identity,$duration);
			return true;
		}
		else
			return false;
	}
}


text:
.. app documentation master file, created by
   sphinx-quickstart on Wed Oct 21 13:18:22 2009.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to app's documentation!
===============================

Contents:

.. toctree::
   :maxdepth: 2
   :glob:

   getting_started
   installation
   importing_data
   reference/index

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


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

    Copyright (c) 2014-2022 All Rights Reserved by the RWS Group for and on behalf of its affiliates and subsidiaries.

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

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

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

-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <artifactId>odata</artifactId>
        <groupId>com.sdl</groupId>
        <version>2.10-SNAPSHOT</version>
    </parent>

    <artifactId>odata_controller</artifactId>

    <name>OData Controller</name>
    <description>Tridion OData Framework Controller</description>
    <packaging>jar</packaging>

    <properties>
        <license.header.file>${project.basedir}/../src/license/sdl_license/header.txt</license.header.file>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.sdl</groupId>
            <artifactId>odata_common</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

</project>


text:
package org.knowm.xchange.okcoin.v3.dto.account;

import com.fasterxml.jackson.annotation.JsonProperty;
import java.math.BigDecimal;
import lombok.Data;
import org.knowm.xchange.okcoin.v3.dto.trade.FutureSide;

@Data
public class SwapPosition {

  /** Positions available to be closed, ie 1 */
  @JsonProperty("avail_position")
  private BigDecimal availPosition;

  /** Avg. position price, ie 11444.4 */
  @JsonProperty("avg_cost")
  private BigDecimal avgCost;

  /** Contract ID, ie BTC-USD-SWAP */
  @JsonProperty("instrument_id")
  private String instrumentId;

  /** Leverage level, ie 3 */
  private BigDecimal leverage;

  /** Estimated liquidation price, ie 0.1 */
  @JsonProperty("liquidation_price")
  private BigDecimal liquidationPrice;

  /** Maintenance Margin Ratio, ie 0.0050 */
  @JsonProperty("maint_margin_ratio")
  private BigDecimal maintMarginRatio;

  /** Margin, ie 0.0029 */
  private BigDecimal margin;

  /** Positions open, ie 1 */
  private BigDecimal position;

  /** Settlement price, ie 11444.4 */
  @JsonProperty("settlement_price")
  private BigDecimal settlementPrice;

  /** Realized PnL, ie -0.0001 */
  @JsonProperty("realized_pnl")
  private BigDecimal realizedPnl;

  /** Side, short or long */
  private FutureSide side;

  /** Creation time, ie "2019-06-25T10:43:37.728Z" */
  private String timestamp;
}


text:
DEngineManager::DEngineManager()
{
}

DEngineManager::~DEngineManager()
{
}

void DEngineManager::Initialize()
{

}

void DEngineManager::Dispose()
{

}

void DEngineManager::Update()
{

}

void DEngineManager::Render()
{

}

void DEngineManager::PullReference(const DObject *Origin)
{
	DObject::PullReference(Origin);
}


text:
<?php
/**
 * This function converts HTTP status codes to HTTP status messages
 * @param integer $Code The HTTP status code
 * @since 1.0
 * @return string
 */
function Status_Message($Code = NULL){
	$Codes = array(
	    100 => 'Continue',
	    101 => 'Switching Protocols',
	    200 => 'OK',
	    201 => 'Created',
	    202 => 'Accepted',
	    203 => 'Non-Authoritative Information',
	    204 => 'No Content',
	    205 => 'Reset Content',
	    206 => 'Partial Content',
	    300 => 'Multiple Choices',
	    301 => 'Moved Permanently',
	    302 => 'Found',
	    303 => 'See Other',
	    304 => 'Not Modified',
	    305 => 'Use Proxy',
	    306 => '(Unused)',
	    307 => 'Temporary Redirect',
	    400 => 'Bad Request',
	    401 => 'Unauthorized',
	    402 => 'Payment Required',
	    403 => 'Forbidden',
	    404 => 'Not Found',
	    405 => 'Method Not Allowed',
	    406 => 'Not Acceptable',
	    407 => 'Proxy Authentication Required',
	    408 => 'Request Timeout',
	    409 => 'Conflict',
	    410 => 'Gone',
	    411 => 'Length Required',
	    412 => 'Precondition Failed',
	    413 => 'Request Entity Too Large',
	    414 => 'Request-URI Too Long',
	    415 => 'Unsupported Media Type',
	    416 => 'Requested Range Not Satisfiable',
	    417 => 'Expectation Failed',
	    418 => "I'm a teapot",
	    500 => 'Internal Server Error',
	    501 => 'Not Implemented',
	    502 => 'Bad Gateway',
	    503 => 'Service Unavailable',
	    504 => 'Gateway Timeout',
	    505 => 'HTTP Version Not Supported'
	);
	if(!is_null($Code) && array_key_exists($Code,$Codes)){
		return $Codes[$Code];
	} else {
		return $Codes[204];
	}
}
?>


text:
simple usage:
```
require_once('printos.php');
$clientInfo = array(
	'token' => '', // token
	'secret' => '', // secret
	'baseUrl' => '' // box / siteflow url
);
$printOs = new PrintOs($clientInfo);
$printOs->setPath($method); // api method
$printOs->generateHttpHeaderString('POST');
$response = $printOs->request($postData); // data as array
```


text:
test-variable=var: 163px;
test-expression=var: test;

test-component = section {
	=>
		h1 (label) { color: red},
		p (content) {
			color: green;
			width: var(test-variable);
		},
		div (test-expression);
	main-color=var: #00f;
	label=var: Label;
	content=var: The default content;
	background-color: #ddd;
	display: block;
	width: 200px;
	height: 200px;
	color: var(main-color);
	border: 4px solid var(main-color);
};

.with-content {
	test-component: #aaa, test;
	background-color: yellow;
	label: Should not show up;
	transition: background-color 0.5s;
}
.with-content:hover {
	background-color: green;
}
pink-background = {
	background-color: #faa;
}
hello-world = test-component {
	pink-background: defaults;
	label: Hello world;
	main-color: #888;
}

/*@media -sass-debug-info{filename{font-family:style\.scss}line{font-family:\0000336}}*/
#core-test {
	padding:20px;
	=>
	test-component {
		label: Hi there;
		content: some content;
	},
	hello-world,
	.with-content
	div.parent
		div.middle1
			div.child1 { color: red;},
			div.child2
		div.middle2
		    div.child3
		    div.child4
		div.middle3#one-child
}

@xstyle end;
body {
	=>
		div "shouldn't do anything because the parser is off";
}


text:
package integration

import (
	"context"
	goruntime "runtime"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	runtime "k8s.io/cri-api/pkg/apis/runtime/v1"
)

func TestSharedPidMultiProcessContainerStop(t *testing.T) {
	for name, sbConfig := range map[string]*runtime.PodSandboxConfig{
		"hostpid": PodSandboxConfig("sandbox", "host-pid-container-stop", WithHostPid),
		"podpid":  PodSandboxConfig("sandbox", "pod-pid-container-stop", WithPodPid),
	} {
		t.Run(name, func(t *testing.T) {
			t.Log("Create a shared pid sandbox")
			sb, err := runtimeService.RunPodSandbox(sbConfig, *runtimeHandler)
			require.NoError(t, err)
			defer func() {
				assert.NoError(t, runtimeService.StopPodSandbox(sb))
				assert.NoError(t, runtimeService.RemovePodSandbox(sb))
			}()

			var (
				testImage     = GetImage(BusyBox)
				containerName = "test-container"
			)

			EnsureImageExists(t, testImage)

			t.Log("Create a multi-process container")
			cnConfig := ContainerConfig(
				containerName,
				testImage,
				WithCommand("sh", "-c", "sleep 10000 & sleep 10000"),
			)
			cn, err := runtimeService.CreateContainer(sb, cnConfig, sbConfig)
			require.NoError(t, err)

			t.Log("Start the container")
			require.NoError(t, runtimeService.StartContainer(cn))

			t.Log("Stop the container")
			require.NoError(t, runtimeService.StopContainer(cn, 0))

			t.Log("The container state should be exited")
			s, err := runtimeService.ContainerStatus(cn)
			require.NoError(t, err)
			assert.Equal(t, s.GetState(), runtime.ContainerState_CONTAINER_EXITED)
		})
	}
}

func TestContainerStopCancellation(t *testing.T) {
	if goruntime.GOOS == "windows" {
		t.Skip("Skipped on Windows.")
	}
	t.Log("Create a pod sandbox")
	sb, sbConfig := PodSandboxConfigWithCleanup(t, "sandbox", "cancel-container-stop")

	var (
		testImage     = GetImage(BusyBox)
		containerName = "test-container"
	)

	EnsureImageExists(t, testImage)

	t.Log("Create a container which traps sigterm")
	cnConfig := ContainerConfig(
		containerName,
		testImage,
		WithCommand("sh", "-c", `trap "echo ignore sigterm" TERM; sleep 1000`),
	)
	cn, err := runtimeService.CreateContainer(sb, cnConfig, sbConfig)
	require.NoError(t, err)

	t.Log("Start the container")
	require.NoError(t, runtimeService.StartContainer(cn))

	t.Log("Stop the container with 3s timeout, but 1s context timeout")
	// Note that with container pid namespace, the sleep process
	// is pid 1, and SIGTERM sent by `StopContainer` will be ignored.
	rawClient, err := RawRuntimeClient()
	require.NoError(t, err)
	ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
	defer cancel()
	_, err = rawClient.StopContainer(ctx, &runtime.StopContainerRequest{
		ContainerId: cn,
		Timeout:     3,
	})
	assert.Error(t, err)

	t.Log("The container should still be running even after 5 seconds")
	assert.NoError(t, Consistently(func() (bool, error) {
		s, err := runtimeService.ContainerStatus(cn)
		if err != nil {
			return false, err
		}
		return s.GetState() == runtime.ContainerState_CONTAINER_RUNNING, nil
	}, 100*time.Millisecond, 5*time.Second))

	t.Log("Stop the container with 1s timeout, without shorter context timeout")
	assert.NoError(t, runtimeService.StopContainer(cn, 1))

	t.Log("The container state should be exited")
	s, err := runtimeService.ContainerStatus(cn)
	require.NoError(t, err)
	assert.Equal(t, s.GetState(), runtime.ContainerState_CONTAINER_EXITED)
}


text:
%ZLMLIB ; OSE/SMH - Lock Manager M VM Specific Calls ;2019-12-31  11:26 AM
 ;;8.0;KERNEL;**10007**;
 ;
 ; (c) 2019 Sam Habiel
 ; Licensed under Apache 2.0
CACHE() Q ^%ZOSF("OS")["OpenM"
GTM()   Q ^%ZOSF("OS")["GT.M"

KILL(PID) ; [$$ Private to Package] Kill Process by ID
 I $$CACHE Q $ZU(4,PID)
 I $$GTM D KILL^ZSY(PID) Q '$zgetjpi(PID,"isprocalive")
 QUIT 0
 ;
OSUSER(PID) ; [$$ Private to Package] Get OS User by PID
 I $$CACHE N X S X=##CLASS(%SYS.ProcessQuery).Open(PID) Q X.OSUserName
 I $$GTM N X D  Q X
 . I '$zgetjpi(PID,"isprocalive") S X="" Q
 . S X=$$RETURN^%ZOSV("id -nu </proc/"_PID_"/loginuid") Q
 QUIT 0
 ;
LOCKQRY(RSET) ; [Private to Package} Get List of Locks into RSET
 ; Output
 ; RSET(lock)=pid
 I $$CACHE D  QUIT
 . N % S %="" F  S %=$O(^$L(%)) Q:%=""  S RSET(%)=^$L(%,"OWNER")
 I $$GTM D GTMLKE(.RSET)
 QUIT
 ;
GTMLKE(RSET) ; [Private] LKE in GT.M/YDB to get Locks
 I '$D(IO) S IO=$IO ; For VistA, define IO so we can go back to it
 ;
 ; read lke output & merge lines if pid is on a separate line from lock name
 ; if line is empty, or starts with %YDB or %GTM, ignore it.
 open "lke":(shell="/bin/sh":command="$gtm_dist/lke show -all":readonly)::"pipe"
 use "lke"
 new lkeout,i,line
 for  read line quit:$zeof  do
 . if line="" quit
 . if $e(line,1,4)="%YDB" quit
 . if $e(line,1,4)="%GTM" quit
 . if 2=$find(line," ") set lkeout(i)=lkeout(i)_" Owned"_$piece(line,"Owned",2)
 . else  set lkeout($increment(i))=line
 use IO close "lke"
 ;
 ; Remove REGION names
 new line set line=""
 for  set line=$order(lkeout(line)) quit:line=""  if lkeout(line)'["PID=" kill lkeout(line)
 ;
 ; Extract that data into RSET
 new line set line=""
 for  set line=$order(lkeout(line)) quit:line=""  do
 . new lock set lock=$piece(lkeout(line)," Owned by PID= ",1)
 . new pid  set pid=+$piece(lkeout(line)," Owned by PID= ",2)
 . set RSET(lock)=pid
 quit
 ;
NXTLOCK(RSET,LOCK) ; [$$ Private to Package] Loop through locks and get information
 S LOCK=$G(RSET) ; Yuck. But LOCK is newed in the external loop.
 S LOCK=$O(RSET(LOCK))
 I $L(LOCK) D  Q 1
 . S LOCK(LOCK)=LOCK ; Yuck again. Doesn't make sense.
 . S LOCK(LOCK,"PID")=RSET(LOCK)
 . S RSET=LOCK ; Yuck yuck
 E  Q 0
 ;
NODE() ; [$$ Private to Package] Node on which we are running
 I $$CACHE Q ##class(%SYS.System).GetInstanceName()
 I $$GTM   Q $P($SY,",",2)
 QUIT
 ;
VOLUME() ; [$$ Private to Package] Volume on which we are running, adapated to the Cache/GTM
 I $$CACHE Q $SYSTEM.SYS.NameSpace()
 I $$GTM   Q $ZGBLDIR
 QUIT
 ;


text:
<?php

/**
 *  @see MWSSubscriptionsService_Model
 */

require_once (dirname(__FILE__) . '/../Model.php');

/**
 * MWSSubscriptionsService_Model_ListRegisteredDestinationsResult
 *
 * Properties:
 *

 *
 *
DestinationList: MWSSubscriptionsService_Model_DestinationList

 *
 *

 */

 class MWSSubscriptionsService_Model_ListRegisteredDestinationsResult extends MWSSubscriptionsService_Model {

    public function __construct($data = null)
    {
    $this->_fields = array (
    'DestinationList' => array('FieldValue' => null, 'FieldType' => 'MWSSubscriptionsService_Model_DestinationList'),
    );
    parent::__construct($data);
    }

    /**
     * Get the value of the DestinationList property.
     *
     * @return DestinationList DestinationList.
     */
    public function getDestinationList()
    {
        return $this->_fields['DestinationList']['FieldValue'];
    }

    /**
     * Set the value of the DestinationList property.
     *
     * @param MWSSubscriptionsService_Model_DestinationList destinationList
     * @return this instance
     */
    public function setDestinationList($value)
    {
        $this->_fields['DestinationList']['FieldValue'] = $value;
        return $this;
    }

    /**
     * Check to see if DestinationList is set.
     *
     * @return true if DestinationList is set.
     */
    public function isSetDestinationList()
    {
                return !is_null($this->_fields['DestinationList']['FieldValue']);
            }

    /**
     * Set the value of DestinationList, return this.
     *
     * @param destinationList
     *             The new value to set.
     *
     * @return This instance.
     */
    public function withDestinationList($value)
    {
        $this->setDestinationList($value);
        return $this;
    }

}


text:
// Copyright 2011 the Sputnik authors.  All rights reserved.
/**
 * "caller" of bound function is poisoned (step 20)
 *
 * @path ch15/15.3/15.3.4/15.3.4.5/S15.3.4.5_A1.js
 * @description A bound function should fail to find its "caller"
 * @negative TypeError
 */

function foo() { return bar.caller; }
var bar = foo.bind({});
function baz() { return bar(); }
baz();


text:
namespace eanim
{
	class Sprite;
	class KeyFrame;

	class StagePanel : public ee::EditPanel, public ee::MultiSpritesImpl
	{
	public:
		StagePanel(wxWindow* parent);

		//
		// ee::EditPanel interface
		//
		virtual void clear();

		//
		// ee::MultiSpritesImpl interface
		//
		virtual void traverseSprites(ee::IVisitor& visitor,
			ee::TraverseType type = ee::e_allExisting,
			bool order = true) const;
		virtual void removeSprite(ee::ISprite* sprite);
		virtual void insertSprite(ee::ISprite* sprite) {}
		virtual void clearSprites();

		virtual void resetSpriteOrder(ee::ISprite* sprite, bool up) {}

		void insertSymbol(int index, wxCoord x, wxCoord y);
		void insertSkeleton(int index, wxCoord x, wxCoord y);
		void loadCurrFrameSprites();

		void resetCanvas();

	private:
		class DragSymbolTarget : public wxTextDropTarget
		{
		public:
			DragSymbolTarget(StagePanel* panel);

			virtual bool OnDropText(wxCoord x, wxCoord y, const wxString& data);

		private:
			StagePanel* m_panel;

		}; // DragTileTarget

	private:
		std::vector<Sprite*> m_sprites;

	}; // StagePanel
}


text:
/*
 * Download the Leaderboard Data and the data from 1 day, 3 days, 1 week, 1 month, 6 months, 1 year ago
 *
 * compare the data and save pos and data changes in properties for each of these dates
 */

import { GameType, Leaderboard, LeaderboardPlace } from "hive-api";
import { database, firestore } from "firebase-admin";
import { compressToBase64 } from "lz-string";
import { CollectionReference, DocumentReference, QuerySnapshot } from "@google-cloud/firestore";
import { config } from '../main';
import { BasicUpdater, Updater } from "lergins-bot-framework";
import { nameUpdater } from "./NameUpdater";

export class GameLeaderboardUpdater extends BasicUpdater {
  private _dataRef: CollectionReference;
  private _ref: CollectionReference;

  constructor(private readonly gameType: GameType) {
    super();

    this._ref = firestore().collection("gameLeaderboards");
    this._dataRef = this._ref.doc(gameType.id).collection("data");
  }

  get configId() {
    return "leaderboard_gametypes";
  }

  get id() {
    return `leaderboard_gametype_${this.gameType.id}`;
  }

  private getRefForDatePage(dateOrUtcYear: Date, page: number): DocumentReference;
  private getRefForDatePage(dateOrUtcYear: number, utcMonth: number, utcDate: number, page: number): DocumentReference;
  private getRefForDatePage(dateOrUtcYear: Date | number, utcMonthOrPage: number, utcDate?: number, page?: number): DocumentReference {
    if (typeof dateOrUtcYear === 'number') {
      return this.getRefForDatePage(new Date(Date.UTC(dateOrUtcYear, utcMonthOrPage, utcDate)), page)
    }else{
      return this._dataRef.doc(`${dateOrUtcYear.toISOString().substr(0, 10)}-${utcMonthOrPage}`) // ISO Date (without time) + page number
    }
  }

  private static removeUnimportantRawData(raw: any){
    delete raw.index;
    delete raw.humanIndex;
    delete raw.UUID;
    delete raw.username;

    // it only makes sense to save numeric values as other values can't change in a way that allowes to show a trend
    Object.entries(raw).filter(([key, val]) => typeof val !== 'number').forEach(([key]) => delete raw[key]);

    return raw;
  }

  async updateInfo() {
    try {
      const leaderboard = new Leaderboard(this.gameType);

      // we don't want the data from yesterday as that is already saved (should actually have no effect as the programm should be restarted every day)
      leaderboard.deleteCache();

      const leaderboardPlaces: Map<number, LeaderboardPlace> = await leaderboard.load(0, (await config().get('game_leaderboard_size') || 1000));

      const date = new Date();

      // convert data
      const convData: {uuid: string, name: string, player: number, [key: string]: any}[] = [... leaderboardPlaces.values()].map((place: LeaderboardPlace) => {
        let res: any = GameLeaderboardUpdater.removeUnimportantRawData(place.raw);

        res.uuid = place.player.uuid;
        res.name = place.player.name;
        res.place = place.place;

        return res;
      });

      // paginate data in pages of 100 entries to be able to load multiple places at once to not make to many requests
      // to firestore while at the same time not requesting to much data
      GameLeaderboardUpdater.paginate(convData, 100)
        // save pages to firestore
        .forEach((page,index) => {
          this.getRefForDatePage(date.getFullYear(), date.getMonth(), date.getDate(), index).create({ a: Buffer.from(compressToBase64(JSON.stringify(page)), 'base64') }).catch(err => {
            if(err.code == 6) return;

            return err;
          });
        });

        convData.forEach(entry => {
          nameUpdater.update(entry.uuid, entry.name)
        })
    } catch (err) {
      Updater.sendError(err, `leaderboard/${this.gameType.id}`);
    }
  }

  /**
   * paginates the given array into an array of arrays that each contain at most an amount of pageSize elements
   *
   * @param arr the array to paginate
   * @param pageSize amount of elements on each page
   */
  private static paginate<T>(arr: T[], pageSize: number): T[][] {
    return arr.reduce((paginated, data, index) => {
      // create a new array each time all the previously created arrays have the max size so the array is there to be filled
      if (index % pageSize === 0) {
        paginated.push([]);
      }

      // add the data to the current page
      paginated[Math.floor(index / pageSize)].push(data);

      return paginated;
    }, []);
  }
}


text:
using System;
using System.IO;

using Aspose.Cells;

namespace Aspose.Cells.Examples.CSharp.Data
{
    public class CreateNamedRangeofCells
    {
        //Output directory
        static string outputDir = RunExamples.Get_OutputDirectory();

        public static void Run()
        {
            // Opening the Excel file through the file stream
            Workbook workbook = new Workbook();

            // Accessing the first worksheet in the Excel file
            Worksheet worksheet = workbook.Worksheets[0];

            // Creating a named range
            Range range = worksheet.Cells.CreateRange("B4", "G14");

            // Setting the name of the named range
            range.Name = "TestRange";

            Style st = workbook.CreateStyle();
            st.Pattern = BackgroundType.Solid;
            st.ForegroundColor = System.Drawing.Color.Yellow;
            range.SetStyle(st);

            // Saving the modified Excel file
            workbook.Save(outputDir + "outputCreateNamedRangeofCells.xlsx");

            Console.WriteLine("CreateNamedRangeofCells executed successfully.");
        }
    }
}


text:
require 'securerandom'

module Factory

  def self.redis
    Zermelo.redis
  end

  def self.contact(attrs = {})
    redis.multi do |r|
      attrs[:id] ||= SecureRandom.uuid
      r.hmset("contact:#{attrs[:id]}:attrs", {'name' => attrs[:name]}.flatten)
      r.sadd('contact::attrs:ids', attrs[:id])
      name = attrs[:name].gsub(/%/, '%%').gsub(/ /, '%20').gsub(/:/, '%3A')
      r.sadd("contact::indices:by_name:string:#{name}", attrs[:id])
    end
  end

  def self.medium(contact, attrs = {})
    redis.multi do |r|
      attrs[:id] ||= SecureRandom.uuid
      r.hmset("medium:#{attrs[:id]}:attrs", {'transport' => attrs[:transport],
        'address' => attrs[:address], 'interval' => attrs[:interval],
        'rollup_threshold' => attrs[:rollup_threshold]}.flatten)
      r.sadd('medium::attrs:ids', attrs[:id].to_s)
      # transport is known not to contain unsafe chars
      r.sadd("medium::indices:by_transport:string:#{attrs[:transport]}", attrs[:id])

      r.sadd("contact:#{contact.id}:assocs:medium_ids", attrs[:id].to_s)
    end
  end

  def self.tag(attrs = {})
    redis.multi do |r|
      attrs[:id] ||= SecureRandom.uuid
      r.hmset("tag:#{attrs[:id]}:attrs", {'name' => attrs[:name]}.flatten)
      r.sadd('tag::attrs:ids', attrs[:id])
      name = attrs[:name].gsub(/%/, '%%').gsub(/ /, '%20').gsub(/:/, '%3A')
      r.hset("tag::indices:by_name", "string:#{name}", attrs[:id])
    end
  end

  def self.check(attrs = {})
    attrs[:state] ||= 'ok'
    redis.multi do |r|
      attrs[:id] ||= SecureRandom.uuid
      r.hmset("check:#{attrs[:id]}:attrs", {'name' => attrs[:name],
        'state' => attrs[:state], 'enabled' => (!!attrs[:enabled]).to_s}.flatten)
      r.sadd('check::attrs:ids', attrs[:id])
      name = attrs[:name].gsub(/%/, '%%').gsub(/ /, '%20').gsub(/:/, '%3A')
      r.hset("check::indices:by_name", "string:#{name}", attrs[:id])
      # state is known not to contain unsafe chars
      r.sadd("check::indices:by_state:string:#{attrs[:state]}", attrs[:id])
      r.sadd("check::indices:by_enabled:boolean:#{!!attrs[:enabled]}", attrs[:id])
    end
  end

end


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.xconns.peerdevicenet.samples.connector_wifidirect_hotspot.ConnectorByWifiDirectHotspot$PlaceholderFragment" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/net_msg"
            android:layout_width="wrap_content"
            android:layout_height="0dip"
            android:layout_gravity="top"
            android:layout_weight="1"
            android:text="@string/miss_net" />

        <Button
            android:id="@+id/button_conn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/setup_net" />
    </LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="2dip"
        android:background="#FF909090" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/conn_peers" />

    <ListView
        android:id="@+id/peers_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/button_done"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/done_return" />

</LinearLayout>


text:
This repo contains a python program that resizes the cover art JPEG image inside the ID3 tag of MP3 files down to 400x400 pixels. This is necessary in order to see the cover art in VW (Golf) cars multi media systems. This is in 2016, maybe newer VW models support higer resolutions.

Usually MP3 files use high-res cover art; well not really it's mostly 640x640 or something like that...
but that doesn't show up on the VW multi media system! I would have never guessed that if it wasn't for Haydn Williams post (http://www.haydnwilliams.com/blog/vw-golf-mk7-sd-cards-and-album-art)
I think VW uses some old-school proprietary hardware for their multimedia stuff; which they're locked into with their custom OS/software...

So you need to limit the cover art size to 400x400 pixel when you play MP3s from USB or SD card.

# Usage
the program is very short and low-tech. It walks over the "*.mp3" files in one directory. Set the directory directly in the program.

# Limitations
it's not very clever; just resizes the "APIC:Cover" thing to 400x400. So if the source wasn't quadratic in size, it will be distorted. It also doesn't exit if the source is smaller... Everything will be 400x400!

# Dependencies
mutagen, PIL

# Python
uses version 3 (I didn't test it on python2.7)

# Example
No cover art because jpeg is too large: ![too large](/doc/DSC_0003.jpg "no cover art")
cover art visible; it's 400x400 pixels now: ![just right](/doc/DSC_0004.jpg "cover art visible")


text:
package com.google.android.exoplayer2.source;

import androidx.annotation.Nullable;
import com.google.android.exoplayer2.AbstractConcatenatedTimeline;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.Timeline;
import com.google.android.exoplayer2.source.ShuffleOrder.UnshuffledShuffleOrder;
import com.google.android.exoplayer2.upstream.Allocator;
import com.google.android.exoplayer2.util.Assertions;
import java.util.HashMap;
import java.util.Map;

/**
 * Loops a {@link MediaSource} a specified number of times.
 *
 * @deprecated To loop a {@link MediaSource} indefinitely, use {@link Player#setRepeatMode(int)}
 *     instead of this class. To add a {@link MediaSource} a specific number of times to the
 *     playlist, use {@link ExoPlayer#addMediaSource} in a loop with the same {@link MediaSource}.
 *     To combine repeated {@link MediaSource} instances into one {@link MediaSource}, for example
 *     to further wrap it in another {@link MediaSource}, use {@link ConcatenatingMediaSource} with
 *     the same {@link MediaSource} {@link ConcatenatingMediaSource#addMediaSource added} multiple
 *     times.
 */
@Deprecated
public final class LoopingMediaSource extends WrappingMediaSource {

  private final int loopCount;
  private final Map<MediaPeriodId, MediaPeriodId> childMediaPeriodIdToMediaPeriodId;
  private final Map<MediaPeriod, MediaPeriodId> mediaPeriodToChildMediaPeriodId;

  /**
   * Loops the provided source indefinitely. Note that it is usually better to use {@link
   * ExoPlayer#setRepeatMode(int)}.
   *
   * @param childSource The {@link MediaSource} to loop.
   */
  public LoopingMediaSource(MediaSource childSource) {
    this(childSource, Integer.MAX_VALUE);
  }

  /**
   * Loops the provided source a specified number of times.
   *
   * @param childSource The {@link MediaSource} to loop.
   * @param loopCount The desired number of loops. Must be strictly positive.
   */
  public LoopingMediaSource(MediaSource childSource, int loopCount) {
    super(new MaskingMediaSource(childSource, /* useLazyPreparation= */ false));
    Assertions.checkArgument(loopCount > 0);
    this.loopCount = loopCount;
    childMediaPeriodIdToMediaPeriodId = new HashMap<>();
    mediaPeriodToChildMediaPeriodId = new HashMap<>();
  }

  @Override
  @Nullable
  public Timeline getInitialTimeline() {
    MaskingMediaSource maskingMediaSource = (MaskingMediaSource) mediaSource;
    return loopCount != Integer.MAX_VALUE
        ? new LoopingTimeline(maskingMediaSource.getTimeline(), loopCount)
        : new InfinitelyLoopingTimeline(maskingMediaSource.getTimeline());
  }

  @Override
  public boolean isSingleWindow() {
    return false;
  }

  @Override
  public MediaPeriod createPeriod(MediaPeriodId id, Allocator allocator, long startPositionUs) {
    if (loopCount == Integer.MAX_VALUE) {
      return mediaSource.createPeriod(id, allocator, startPositionUs);
    }
    Object childPeriodUid = LoopingTimeline.getChildPeriodUidFromConcatenatedUid(id.periodUid);
    MediaPeriodId childMediaPeriodId = id.copyWithPeriodUid(childPeriodUid);
    childMediaPeriodIdToMediaPeriodId.put(childMediaPeriodId, id);
    MediaPeriod mediaPeriod =
        mediaSource.createPeriod(childMediaPeriodId, allocator, startPositionUs);
    mediaPeriodToChildMediaPeriodId.put(mediaPeriod, childMediaPeriodId);
    return mediaPeriod;
  }

  @Override
  public void releasePeriod(MediaPeriod mediaPeriod) {
    mediaSource.releasePeriod(mediaPeriod);
    @Nullable
    MediaPeriodId childMediaPeriodId = mediaPeriodToChildMediaPeriodId.remove(mediaPeriod);
    if (childMediaPeriodId != null) {
      childMediaPeriodIdToMediaPeriodId.remove(childMediaPeriodId);
    }
  }

  @Override
  protected void onChildSourceInfoRefreshed(Timeline newTimeline) {
    Timeline loopingTimeline =
        loopCount != Integer.MAX_VALUE
            ? new LoopingTimeline(newTimeline, loopCount)
            : new InfinitelyLoopingTimeline(newTimeline);
    refreshSourceInfo(loopingTimeline);
  }

  @Override
  @Nullable
  protected MediaPeriodId getMediaPeriodIdForChildMediaPeriodId(MediaPeriodId mediaPeriodId) {
    return loopCount != Integer.MAX_VALUE
        ? childMediaPeriodIdToMediaPeriodId.get(mediaPeriodId)
        : mediaPeriodId;
  }

  private static final class LoopingTimeline extends AbstractConcatenatedTimeline {

    private final Timeline childTimeline;
    private final int childPeriodCount;
    private final int childWindowCount;
    private final int loopCount;

    public LoopingTimeline(Timeline childTimeline, int loopCount) {
      super(/* isAtomic= */ false, new UnshuffledShuffleOrder(loopCount));
      this.childTimeline = childTimeline;
      childPeriodCount = childTimeline.getPeriodCount();
      childWindowCount = childTimeline.getWindowCount();
      this.loopCount = loopCount;
      if (childPeriodCount > 0) {
        Assertions.checkState(
            loopCount <= Integer.MAX_VALUE / childPeriodCount,
            "LoopingMediaSource contains too many periods");
      }
    }

    @Override
    public int getWindowCount() {
      return childWindowCount * loopCount;
    }

    @Override
    public int getPeriodCount() {
      return childPeriodCount * loopCount;
    }

    @Override
    protected int getChildIndexByPeriodIndex(int periodIndex) {
      return periodIndex / childPeriodCount;
    }

    @Override
    protected int getChildIndexByWindowIndex(int windowIndex) {
      return windowIndex / childWindowCount;
    }

    @Override
    protected int getChildIndexByChildUid(Object childUid) {
      if (!(childUid instanceof Integer)) {
        return C.INDEX_UNSET;
      }
      return (Integer) childUid;
    }

    @Override
    protected Timeline getTimelineByChildIndex(int childIndex) {
      return childTimeline;
    }

    @Override
    protected int getFirstPeriodIndexByChildIndex(int childIndex) {
      return childIndex * childPeriodCount;
    }

    @Override
    protected int getFirstWindowIndexByChildIndex(int childIndex) {
      return childIndex * childWindowCount;
    }

    @Override
    protected Object getChildUidByChildIndex(int childIndex) {
      return childIndex;
    }
  }

  private static final class InfinitelyLoopingTimeline extends ForwardingTimeline {

    public InfinitelyLoopingTimeline(Timeline timeline) {
      super(timeline);
    }

    @Override
    public int getNextWindowIndex(
        int windowIndex, @Player.RepeatMode int repeatMode, boolean shuffleModeEnabled) {
      int childNextWindowIndex =
          timeline.getNextWindowIndex(windowIndex, repeatMode, shuffleModeEnabled);
      return childNextWindowIndex == C.INDEX_UNSET
          ? getFirstWindowIndex(shuffleModeEnabled)
          : childNextWindowIndex;
    }

    @Override
    public int getPreviousWindowIndex(
        int windowIndex, @Player.RepeatMode int repeatMode, boolean shuffleModeEnabled) {
      int childPreviousWindowIndex =
          timeline.getPreviousWindowIndex(windowIndex, repeatMode, shuffleModeEnabled);
      return childPreviousWindowIndex == C.INDEX_UNSET
          ? getLastWindowIndex(shuffleModeEnabled)
          : childPreviousWindowIndex;
    }
  }
}


text:
using System;
using System.IO;
using Microsoft.Extensions.Configuration;
using NetEscapades.Configuration.Tests.Common;
using Xunit;

namespace NetEscapades.Configuration.Yaml
{
    public class YamlConfigurationTest
    {
        private YamlConfigurationProvider LoadProvider(string Yaml)
        {
            var p = new YamlConfigurationProvider(new YamlConfigurationSource { Optional = true });
            p.Load(TestStreamHelpers.StringToStream(Yaml));
            return p;
        }

        [Fact]
        public void LoadKeyValuePairsFromValidYaml()
        {
            var yaml = @"
                firstname: test
                test.last.name: last.name
                residential.address:
                  street.name: Something street
                  zipcode: '12345'
                ";
            var yamlConfigSrc = LoadProvider(yaml);

            Assert.Equal("test", yamlConfigSrc.Get("firstname"));
            Assert.Equal("last.name", yamlConfigSrc.Get("test.last.name"));
            Assert.Equal("Something street", yamlConfigSrc.Get("residential.address:STREET.name"));
            Assert.Equal("12345", yamlConfigSrc.Get("residential.address:zipcode"));
        }

        [Fact]
        public void LoadMethodCanHandleBlankValue()
        {
            var yaml = @"
            name:
        ";
            var yamlConfigSrc = LoadProvider(yaml);
            Assert.Equal(string.Empty, yamlConfigSrc.Get("name"));
        }

        [Fact]
        public void LoadMethodCanHandleEmptyValue()
        {
            var yaml = @"
            name: ''
        ";
            var yamlConfigSrc = LoadProvider(yaml);
            Assert.Equal(string.Empty, yamlConfigSrc.Get("name"));
        }

        [Fact]
        public void LoadMethodCanHandleNullInObject()
        {
            var yaml = @"
                firstname: test
                test.suffix: ~
                test.last.name: ''
                residential.address:
                  street.name: Something street
                  zipcode: null
                ";
            var yamlConfigSrc = LoadProvider(yaml);

            Assert.Equal("test", yamlConfigSrc.Get("firstname"));
            Assert.Null(yamlConfigSrc.Get("test.suffix"));
            Assert.Equal(string.Empty, yamlConfigSrc.Get("test.last.name"));
            Assert.Equal("Something street", yamlConfigSrc.Get("residential.address:STREET.name"));
            Assert.Null(yamlConfigSrc.Get("residential.address:zipcode"));
        }

        [Fact]
        public void LoadMethodCanHandleNullValue()
        {
            var yaml = @"
                nullValue1: null
                nullValue2: Null
                nullValue3: NULL
                nullValue4: ~
                notNull1: NUll
                notNull2: NuLL
            ";

            var yamlConfigSrc = LoadProvider(yaml);
            Assert.Null(yamlConfigSrc.Get("nullValue1"));
            Assert.Null(yamlConfigSrc.Get("nullValue2"));
            Assert.Null(yamlConfigSrc.Get("nullValue3"));
            Assert.Null(yamlConfigSrc.Get("nullValue4"));
            Assert.NotNull(yamlConfigSrc.Get("notNull1"));
            Assert.NotNull(yamlConfigSrc.Get("notNull2"));
        }

        [Fact]
        public void OverrideWithNullValue()
        {
            var yaml1 = @"
                firstname: test
                ";

            var yaml2 = @"
                firstname: null
                ";

            var yamlConfigSource1 = new YamlConfigurationSource { FileProvider = TestStreamHelpers.StringToFileProvider(yaml1) };
            var yamlConfigSource2 = new YamlConfigurationSource { FileProvider = TestStreamHelpers.StringToFileProvider(yaml2) };

            var configurationBuilder = new ConfigurationBuilder();
            configurationBuilder.Add(yamlConfigSource1);
            configurationBuilder.Add(yamlConfigSource2);
            var config = configurationBuilder.Build();

            Assert.Null(config["firstname"]);
        }

        [Fact]
        public void SupportAndIgnoreComments()
        {
            var yaml = @"# Comments
                        # Comments
                        name: test
                        # Comments
                        address:
                          street: Something street # Comments
                          zipcode: '12345'
                    ";
            var yamlConfigSrc = LoadProvider(yaml);
            Assert.Equal("test", yamlConfigSrc.Get("name"));
            Assert.Equal("Something street", yamlConfigSrc.Get("address:street"));
            Assert.Equal("12345", yamlConfigSrc.Get("address:zipcode"));
        }

        [Fact]
        public void ReturnEmptyConfigWhenFileIsEmpty()
        {
            var yaml = @"";

            var yamlConfigSrc = new YamlConfigurationSource { FileProvider = TestStreamHelpers.StringToFileProvider(yaml) };

            var configurationBuilder = new ConfigurationBuilder();
            configurationBuilder.Add(yamlConfigSrc);
            var config = configurationBuilder.Build();

            Assert.Empty(config.AsEnumerable());
        }

        [Fact]
        public void ThrowExceptionWhenUnexpectedFirstCharacterInScalarValue()
        {
            var yaml = @"
                        name: test
                        address:
                          # Can't start scalar values with unclosed {
                          street: {Something street
                          zipcode: '12345'
                         ";
            var exception = Assert.Throws<Exception>(() => LoadProvider(yaml));
            Assert.NotNull(exception.Message);
        }

        [Fact]
        public void ThrowExceptionWhenUnexpectedFirstCharacterInKeyValue()
        {
            var yaml = @"
                        name: test
                        address:
                          street: Something street
                          zipcode: '12345'
                        # Can't start left value with {
                        {phone: mobile
                         ";
            var exception = Assert.Throws<FormatException>(() => LoadProvider(yaml));
            Assert.NotNull(exception.Message);
        }

        [Fact]
        public void ThrowExceptionWhenUnexpectedEndOfFile()
        {
            var yaml = @"
                        name: test
                        address
                         ";
            var exception = Assert.Throws<FormatException>(() => LoadProvider(yaml));
            Assert.NotNull(exception.Message);
        }

        [Fact]
        public void ThrowExceptionWhenPassingNullAsFilePath()
        {
            var expectedMsg = new ArgumentException(Resources.Error_InvalidFilePath, "path").Message;

            var exception = Assert.Throws<ArgumentException>(() => new ConfigurationBuilder().AddYamlFile(path: null));

            Assert.Equal(expectedMsg, exception.Message);
        }

        [Fact]
        public void ThrowExceptionWhenPassingEmptyStringAsFilePath()
        {
            var expectedMsg = new ArgumentException(Resources.Error_InvalidFilePath, "path").Message;

            var exception = Assert.Throws<ArgumentException>(() => new ConfigurationBuilder().AddYamlFile(string.Empty));

            Assert.Equal(expectedMsg, exception.Message);
        }

        [Fact]
        public void YamlConfiguration_Throws_On_Missing_Configuration_File()
        {
            var config = new ConfigurationBuilder().AddYamlFile("NotExistingConfig.Yaml", optional: false);
            var exception = Assert.Throws<FileNotFoundException>(() => config.Build());

            // Assert
            Assert.StartsWith(string.Format(Resources.Error_FileNotFound, "NotExistingConfig.Yaml"), exception.Message);
        }

        [Fact]
        public void YamlConfiguration_Does_Not_Throw_On_Optional_Configuration()
        {
            var config = new ConfigurationBuilder().AddYamlFile("NotExistingConfig.Yaml", optional: true).Build();
        }
    }
}


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

namespace wojilu.ext.ORM
{
    public class SqlBuilderX
    {
        #region GetCountSql
        /// <summary>
        /// 生成获取总数SQL
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="dbtype"></param>
        /// <returns></returns>
        public static string GetCountSql(string sql, wojilu.Data.DatabaseType dbtype)
        {
            var countSql = string.Empty;
            switch (dbtype)
            {
                case Data.DatabaseType.SqlServer:
                    countSql = GetMssqlRecordCountSql(sql);
                    break;
                case Data.DatabaseType.MySql:
                    countSql = sql;
                    break;
                default:
                    throw new Exception(string.Format("{0}未实现GetCountSql方法", dbtype.ToString()));
            }
            return string.Format("select count(0) as icount from ({0}) as pager_count_scalar ", countSql);
        }

        /// <summary>
        /// MSSQL嵌套查询时进行了排序时,必须加上top关键字,如 select count(0) from (select top 9999 * from Student order by Id) a
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        private static String GetMssqlRecordCountSql(String sql)
        {
            StringBuilder sb = new StringBuilder();
            // 查询语句中使用排序时必须加上TOP
            //if (sql.ToLower().LastIndexOf("order by") != -1 && sql.ToLower().IndexOf("top") == -1)
            if (sql.ToLower().LastIndexOf("order by") != -1)
            {

                if (sql.Replace(" ", "").ToLower().IndexOf("distinct") != -1)
                {
                    sb.Append(" select distinct top 100 percent ");
                    sb.Append(sql.Substring(sql.ToLower().IndexOf("distinct") + "distinct".Length));
                }
                else
                {
                    sb.Append(" select top 100 percent ");
                    sb.Append(sql.Substring(sql.ToLower().IndexOf("select") + "select".Length));
                }

                return sb.ToString();
            }
            else
            {
                return sql;
            }
        }
        #endregion GetCountSql

        #region GetPageSql

        public static string GetPageSql(string sql, int current, int pagesize, wojilu.Data.DatabaseType dbtype)
        {
            switch (dbtype)
            {
                case Data.DatabaseType.SqlServer:
                    return GetMssqlPageSql(sql, current, pagesize);
                case Data.DatabaseType.MySql:
                    return GetMySqlPageSql(sql, current, pagesize);
                default:
                    throw new Exception(string.Format("未实现{0}.GetPageSql()", dbtype.ToString()));
            }
        }

        private static string GetMySqlPageSql(string sql, int current, int pagesize)
        {
            int startRow = pagesize * (current - 1);
            var sb = new StringBuilder();
            sb.Append(sql);
            sb.Append(" limit ");
            sb.Append(startRow);
            sb.Append(", ");
            sb.Append(pagesize);
            return sb.ToString();
        }

        /// <summary>
        /// mssql分页
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="current"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        private static string GetMssqlPageSql(string sql, int current, int pagesize)
        {
            int startIndex = (current - 1) * pagesize;
            StringBuilder pagerSql = new StringBuilder();
            pagerSql.Append(" select * from ");
            pagerSql.Append(" ( ");
            pagerSql.Append("   select row_number() over(order by tc) rownum,* ");
            pagerSql.Append("     from ");
            pagerSql.Append("     ( ");
            var subStrStartIndex = -1;
            var isDistinct = false;
            if (sql.Replace(" ", "").ToLower().IndexOf("distinct") != -1)
            {
                isDistinct = true;
                subStrStartIndex = sql.ToLower().IndexOf("distinct") + "distinct".Length;
            }
            else
            {
                subStrStartIndex = sql.ToLower().IndexOf("select") + "select".Length;
            }

            // MSSQL查询语句中使用order by时必须加上TOP
            if (sql.ToLower().LastIndexOf("order by") != -1)
            {
                pagerSql.Append(" select " + (isDistinct ? "distinct" : "") + " top 100 percent 0 as tc, ");
                pagerSql.Append(sql.Substring(subStrStartIndex));
            }
            else
            {
                if (sql.ToLower().IndexOf("top") == -1)
                {
                    pagerSql.Append(" select 0 as tc, ");
                    pagerSql.Append(sql.Substring(subStrStartIndex));
                }
                else
                {
                    // 当语句出现top的情况下,如 select top 666 * from tbl
                    // 按照当前查询规则,语句应是 select top 666 0 as tc, * from tbl
                    String topNumStr = GetTopNumString(sql);
                    pagerSql.Append(" select " + (isDistinct ? "distinct" : "") + " top 100 percent 0 as tc, ");
                    pagerSql.Append(sql.Substring(subStrStartIndex + "top".Length + topNumStr.Length));
                }
            }

            var temp = ReplaceOrderBySqlForMSSQL(pagerSql.ToString());
            //pagerSql.Clear();  // .net 4.0以上才有Clear()
            pagerSql.Length = 0;
            pagerSql.Append(temp);
            pagerSql.Append("     ) t ");
            pagerSql.Append(" ) tt ");
            pagerSql.Append("  where rownum > ");
            pagerSql.Append(startIndex);
            pagerSql.Append(" and rownum <= ");
            pagerSql.Append(pagesize + startIndex);

            return pagerSql.ToString();
        }

        /// <summary>
        /// 获取top后面值(如果有空格也会获取)
        /// </summary>
        /// <param name="sql"></param>
        /// <remarks>如 select top 666 * from tbl,取出" 666 "</remarks>
        /// <returns></returns>
        private static string GetTopNumString(string sql)
        {
            char[] sqlx = sql.Substring(sql.IndexOf("top") + "top".Length).ToCharArray();

            int i = 0;
            string topNumStr = string.Empty;

            foreach (var item in sqlx)
            {
                topNumStr += item;

                if (item != 32)
                {
                    i++;
                }
                else
                {
                    if (i > 0)
                    {
                        break;
                    }
                }
            }

            return topNumStr;
        }

        /// <summary>
        /// 重构OrderBy
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        private static string ReplaceOrderBySqlForMSSQL(string sql)
        {
            var orderIndex = sql.ToLower().LastIndexOf(" order ");
            if (orderIndex == -1) return sql;

            var byIndex = sql.ToLower().LastIndexOf(" by ");
            if (byIndex == -1) return sql;

            var orderBy = sql.Substring(orderIndex, byIndex - orderIndex + " by ".Length);
            var orderByLastStr = sql.Substring(byIndex + " by ".Length).ToLower();

            // over(order by a.entrytime desc,a.id asc ) -错误的语法
            // over(order by ) 中不允许使用别名.字段,不然会引发"无法绑定由多个部分组成的标识符"异常
            // 这里把order by 后面的字符串提取出来,去掉别名
            var orver_order_by = orderByLastStr;
            if (orderByLastStr.IndexOf('.') != -1)
            {
                if (orderByLastStr.IndexOf(',') != -1)
                {
                    // order by 多个字段处理
                    var _arr = orderByLastStr.Split(',');
                    var _arr_temp = new string[_arr.Length];
                    for (int i = 0; i < _arr.Length; i++)
                    {
                        if (string.IsNullOrEmpty(_arr[i])) continue;
                        var _temp = _arr[i].Substring(0, _arr[i].IndexOf('.') + 1);
                        _arr_temp[i] = _arr[i].Replace(_temp, "");
                    }
                    orver_order_by = string.Join(",", _arr_temp);
                }
                else
                {
                    // order by 单个字段时的处理
                    var rpStr = orderByLastStr.Substring(0, orderByLastStr.IndexOf('.') + 1);
                    orver_order_by = orderByLastStr.Replace(rpStr, "");
                }
            }

            var sb = new StringBuilder();
            sb.Append(sql.Substring(0, sql.LastIndexOf(orderBy)));
            sb.Append(" order by ");
            sb.Append(orderByLastStr);

            return sb.ToString().Replace("over(order by tc)", "over(order by " + orver_order_by + ")");
        }

        #endregion GetPageSql
    }
}


text:
from datetime import datetime
from string import capwords

from types import TYPE_INFORMATION

## A common wrapper for all returned items.
#
# This class serves a very important purpose - it makes use of the meta type
# information to provide intelligent access to data members.
class Item:

    ## Constructs an Item to wrap the supplied dictionary.
    # @param data a dictionary
    # @param item_type the type of data
    def __init__(self, data, item_type):
        self._data      = data
        self._type_info = TYPE_INFORMATION[item_type] if item_type in TYPE_INFORMATION else {}
        self._type_name = capwords(item_type, '_').replace('_', ' ')

    ## Indicates whether the specified attribute exists in the disctionary.
    # @param index the index to retrieve
    # @return whether or not the index exists
    def __contains__(self, index):
        return index in self._data

    ## Returns the specified attribute from the dictionary.
    # @param index the index to retrieve
    # @return the item at the specified index
    def __getattr__(self, index):
        # Catch any KeyErrors and rethrow them as AttributeErrors
        try:
            # If the attribute ends with '_timestamp' then remove that part and
            # return a timestamp instead of a datetime object
            return_timestamp = False
            if index.endswith('_timestamp'):
                index = index[:-10]
                return_timestamp = True
            if index in self._type_field('date_fields', []):
                return self._data[index] if return_timestamp else datetime.fromtimestamp(self._data[index])
            # Either return the requested item or it if is another type, return a new Item instance
            if index in self._type_field('type_map', {}):
                return Item(self._data[index], self._type_info['type_map'][index])
            return self._data[index]
        except KeyError, e:
            raise AttributeError(e)

    ## Returns an internal representation of the response.
    # @return the internal representation
    def __repr__(self):
        try:
            return "<%s '%s'>" % (self._type_name, str(self),)
        except KeyError:
            return '<Unknown Item>'

    ## Returns a string representation of the response.
    # @return the string representation
    def __str__(self):
        str_field = self._type_field('str_field') if self._type_field('str_field') in self._data else self._type_field('id_field')
        if not str_field in self._data:
            raise KeyError('Unable to construct a string representation of the item.')
        return str(self._data[str_field])

    ## Returns data from the type information for this item.
    # @param index the index of the data to retrieve
    # @param default the default value to return in the event that index does not exist
    def _type_field(self, index, default=None):
        return self._type_info[index] if index in self._type_info else default

    ## Returns the ID of the item.
    # @return the ID of the item or None if unavailable
    def id(self):
        id_field = self._type_field('id_field')
        return self._data[id_field] if id_field in self._data else None


text:
// Type definitions for project-name-generator 2.1
// Project: https://github.com/aceakash/project-name-generator#readme
// Definitions by: Piotr Błażejewicz <https://github.com/peterblazejewicz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

/**
 * Generate quirky names like spiffy-waterfall, sassy-bread, mature-dew-8239 to use wherever you need a random but memorable name.
 */
declare function generate(options?: generate.Options): generate.Project;

declare namespace generate {
    interface Options {
        /**
         * Number of words generated (excluding number).
         * All words will be adjectives, except the last one which will be a noun
         * @default 2
         */
        words?: number;
        /**
         * Whether a numeric suffix is generated or not. The number is between 1 - 9999, both inclusive.
         * @default false
         */
        number?: boolean;
        /**
         * Whether to output words beginning with the same letter or not
         * @default false
         */
        alliterative?: boolean;
    }
    interface Project {
        raw: Array<string | number>;
        dashed: string;
        spaced: string;
    }
}

export = generate;