text:
/**
 * Autogenerated by Thrift Compiler (0.7.0)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 */
package com.cloudera.flume.handlers.thrift;

import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ThriftFlumeEvent implements org.apache.thrift.TBase<ThriftFlumeEvent, ThriftFlumeEvent._Fields>, java.io.Serializable, Cloneable {
  private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("ThriftFlumeEvent");

  private static final org.apache.thrift.protocol.TField TIMESTAMP_FIELD_DESC = new org.apache.thrift.protocol.TField("timestamp", org.apache.thrift.protocol.TType.I64, (short)1);
  private static final org.apache.thrift.protocol.TField PRIORITY_FIELD_DESC = new org.apache.thrift.protocol.TField("priority", org.apache.thrift.protocol.TType.I32, (short)2);
  private static final org.apache.thrift.protocol.TField BODY_FIELD_DESC = new org.apache.thrift.protocol.TField("body", org.apache.thrift.protocol.TType.STRING, (short)3);
  private static final org.apache.thrift.protocol.TField NANOS_FIELD_DESC = new org.apache.thrift.protocol.TField("nanos", org.apache.thrift.protocol.TType.I64, (short)4);
  private static final org.apache.thrift.protocol.TField HOST_FIELD_DESC = new org.apache.thrift.protocol.TField("host", org.apache.thrift.protocol.TType.STRING, (short)5);
  private static final org.apache.thrift.protocol.TField FIELDS_FIELD_DESC = new org.apache.thrift.protocol.TField("fields", org.apache.thrift.protocol.TType.MAP, (short)6);
  private static final org.apache.thrift.protocol.TField HOST_LIST_FIELD_DESC = new org.apache.thrift.protocol.TField("hostList", org.apache.thrift.protocol.TType.LIST, (short)7);

  public long timestamp; // required
  /**
   *
   * @see Priority
   */
  public Priority priority; // required
  public ByteBuffer body; // required
  public long nanos; // required
  public String host; // required
  public Map<String,ByteBuffer> fields; // required
  public List<String> hostList; // required

  /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
  public enum _Fields implements org.apache.thrift.TFieldIdEnum {
    TIMESTAMP((short)1, "timestamp"),
    /**
     *
     * @see Priority
     */
    PRIORITY((short)2, "priority"),
    BODY((short)3, "body"),
    NANOS((short)4, "nanos"),
    HOST((short)5, "host"),
    FIELDS((short)6, "fields"),
    HOST_LIST((short)7, "hostList");

    private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();

    static {
      for (_Fields field : EnumSet.allOf(_Fields.class)) {
        byName.put(field.getFieldName(), field);
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, or null if its not found.
     */
    public static _Fields findByThriftId(int fieldId) {
      switch(fieldId) {
        case 1: // TIMESTAMP
          return TIMESTAMP;
        case 2: // PRIORITY
          return PRIORITY;
        case 3: // BODY
          return BODY;
        case 4: // NANOS
          return NANOS;
        case 5: // HOST
          return HOST;
        case 6: // FIELDS
          return FIELDS;
        case 7: // HOST_LIST
          return HOST_LIST;
        default:
          return null;
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, throwing an exception
     * if it is not found.
     */
    public static _Fields findByThriftIdOrThrow(int fieldId) {
      _Fields fields = findByThriftId(fieldId);
      if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
      return fields;
    }

    /**
     * Find the _Fields constant that matches name, or null if its not found.
     */
    public static _Fields findByName(String name) {
      return byName.get(name);
    }

    private final short _thriftId;
    private final String _fieldName;

    _Fields(short thriftId, String fieldName) {
      _thriftId = thriftId;
      _fieldName = fieldName;
    }

    public short getThriftFieldId() {
      return _thriftId;
    }

    public String getFieldName() {
      return _fieldName;
    }
  }

  // isset id assignments
  private static final int __TIMESTAMP_ISSET_ID = 0;
  private static final int __NANOS_ISSET_ID = 1;
  private BitSet __isset_bit_vector = new BitSet(2);

  public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
  static {
    Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
    tmpMap.put(_Fields.TIMESTAMP, new org.apache.thrift.meta_data.FieldMetaData("timestamp", org.apache.thrift.TFieldRequirementType.DEFAULT,
        new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64        , "Timestamp")));
    tmpMap.put(_Fields.PRIORITY, new org.apache.thrift.meta_data.FieldMetaData("priority", org.apache.thrift.TFieldRequirementType.DEFAULT,
        new org.apache.thrift.meta_data.EnumMetaData(org.apache.thrift.protocol.TType.ENUM, Priority.class)));
    tmpMap.put(_Fields.BODY, new org.apache.thrift.meta_data.FieldMetaData("body", org.apache.thrift.TFieldRequirementType.DEFAULT,
        new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING        , true)));
    tmpMap.put(_Fields.NANOS, new org.apache.thrift.meta_data.FieldMetaData("nanos", org.apache.thrift.TFieldRequirementType.DEFAULT,
        new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64)));
    tmpMap.put(_Fields.HOST, new org.apache.thrift.meta_data.FieldMetaData("host", org.apache.thrift.TFieldRequirementType.DEFAULT,
        new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
    tmpMap.put(_Fields.FIELDS, new org.apache.thrift.meta_data.FieldMetaData("fields", org.apache.thrift.TFieldRequirementType.DEFAULT,
        new org.apache.thrift.meta_data.MapMetaData(org.apache.thrift.protocol.TType.MAP,
            new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING),
            new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING            , true))));
    tmpMap.put(_Fields.HOST_LIST, new org.apache.thrift.meta_data.FieldMetaData("hostList", org.apache.thrift.TFieldRequirementType.DEFAULT,
        new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST,
            new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))));
    metaDataMap = Collections.unmodifiableMap(tmpMap);
    org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(ThriftFlumeEvent.class, metaDataMap);
  }

  public ThriftFlumeEvent() {
  }

  public ThriftFlumeEvent(
    long timestamp,
    Priority priority,
    ByteBuffer body,
    long nanos,
    String host,
    Map<String,ByteBuffer> fields,
    List<String> hostList)
  {
    this();
    this.timestamp = timestamp;
    setTimestampIsSet(true);
    this.priority = priority;
    this.body = body;
    this.nanos = nanos;
    setNanosIsSet(true);
    this.host = host;
    this.fields = fields;
    this.hostList = hostList;
  }

  /**
   * Performs a deep copy on <i>other</i>.
   */
  public ThriftFlumeEvent(ThriftFlumeEvent other) {
    __isset_bit_vector.clear();
    __isset_bit_vector.or(other.__isset_bit_vector);
    this.timestamp = other.timestamp;
    if (other.isSetPriority()) {
      this.priority = other.priority;
    }
    if (other.isSetBody()) {
      this.body = org.apache.thrift.TBaseHelper.copyBinary(other.body);
;
    }
    this.nanos = other.nanos;
    if (other.isSetHost()) {
      this.host = other.host;
    }
    if (other.isSetFields()) {
      Map<String,ByteBuffer> __this__fields = new HashMap<String,ByteBuffer>();
      for (Map.Entry<String, ByteBuffer> other_element : other.fields.entrySet()) {

        String other_element_key = other_element.getKey();
        ByteBuffer other_element_value = other_element.getValue();

        String __this__fields_copy_key = other_element_key;

        ByteBuffer __this__fields_copy_value = org.apache.thrift.TBaseHelper.copyBinary(other_element_value);
;

        __this__fields.put(__this__fields_copy_key, __this__fields_copy_value);
      }
      this.fields = __this__fields;
    }
    if (other.isSetHostList()) {
      List<String> __this__hostList = new ArrayList<String>();
      for (String other_element : other.hostList) {
        __this__hostList.add(other_element);
      }
      this.hostList = __this__hostList;
    }
  }

  public ThriftFlumeEvent deepCopy() {
    return new ThriftFlumeEvent(this);
  }

  @Override
  public void clear() {
    setTimestampIsSet(false);
    this.timestamp = 0;
    this.priority = null;
    this.body = null;
    setNanosIsSet(false);
    this.nanos = 0;
    this.host = null;
    this.fields = null;
    this.hostList = null;
  }

  public long getTimestamp() {
    return this.timestamp;
  }

  public ThriftFlumeEvent setTimestamp(long timestamp) {
    this.timestamp = timestamp;
    setTimestampIsSet(true);
    return this;
  }

  public void unsetTimestamp() {
    __isset_bit_vector.clear(__TIMESTAMP_ISSET_ID);
  }

  /** Returns true if field timestamp is set (has been assigned a value) and false otherwise */
  public boolean isSetTimestamp() {
    return __isset_bit_vector.get(__TIMESTAMP_ISSET_ID);
  }

  public void setTimestampIsSet(boolean value) {
    __isset_bit_vector.set(__TIMESTAMP_ISSET_ID, value);
  }

  /**
   *
   * @see Priority
   */
  public Priority getPriority() {
    return this.priority;
  }

  /**
   *
   * @see Priority
   */
  public ThriftFlumeEvent setPriority(Priority priority) {
    this.priority = priority;
    return this;
  }

  public void unsetPriority() {
    this.priority = null;
  }

  /** Returns true if field priority is set (has been assigned a value) and false otherwise */
  public boolean isSetPriority() {
    return this.priority != null;
  }

  public void setPriorityIsSet(boolean value) {
    if (!value) {
      this.priority = null;
    }
  }

  public byte[] getBody() {
    setBody(org.apache.thrift.TBaseHelper.rightSize(body));
    return body == null ? null : body.array();
  }

  public ByteBuffer bufferForBody() {
    return body;
  }

  public ThriftFlumeEvent setBody(byte[] body) {
    setBody(body == null ? (ByteBuffer)null : ByteBuffer.wrap(body));
    return this;
  }

  public ThriftFlumeEvent setBody(ByteBuffer body) {
    this.body = body;
    return this;
  }

  public void unsetBody() {
    this.body = null;
  }

  /** Returns true if field body is set (has been assigned a value) and false otherwise */
  public boolean isSetBody() {
    return this.body != null;
  }

  public void setBodyIsSet(boolean value) {
    if (!value) {
      this.body = null;
    }
  }

  public long getNanos() {
    return this.nanos;
  }

  public ThriftFlumeEvent setNanos(long nanos) {
    this.nanos = nanos;
    setNanosIsSet(true);
    return this;
  }

  public void unsetNanos() {
    __isset_bit_vector.clear(__NANOS_ISSET_ID);
  }

  /** Returns true if field nanos is set (has been assigned a value) and false otherwise */
  public boolean isSetNanos() {
    return __isset_bit_vector.get(__NANOS_ISSET_ID);
  }

  public void setNanosIsSet(boolean value) {
    __isset_bit_vector.set(__NANOS_ISSET_ID, value);
  }

  public String getHost() {
    return this.host;
  }

  public ThriftFlumeEvent setHost(String host) {
    this.host = host;
    return this;
  }

  public void unsetHost() {
    this.host = null;
  }

  /** Returns true if field host is set (has been assigned a value) and false otherwise */
  public boolean isSetHost() {
    return this.host != null;
  }

  public void setHostIsSet(boolean value) {
    if (!value) {
      this.host = null;
    }
  }

  public int getFieldsSize() {
    return (this.fields == null) ? 0 : this.fields.size();
  }

  public void putToFields(String key, ByteBuffer val) {
    if (this.fields == null) {
      this.fields = new HashMap<String,ByteBuffer>();
    }
    this.fields.put(key, val);
  }

  public Map<String,ByteBuffer> getFields() {
    return this.fields;
  }

  public ThriftFlumeEvent setFields(Map<String,ByteBuffer> fields) {
    this.fields = fields;
    return this;
  }

  public void unsetFields() {
    this.fields = null;
  }

  /** Returns true if field fields is set (has been assigned a value) and false otherwise */
  public boolean isSetFields() {
    return this.fields != null;
  }

  public void setFieldsIsSet(boolean value) {
    if (!value) {
      this.fields = null;
    }
  }

  public int getHostListSize() {
    return (this.hostList == null) ? 0 : this.hostList.size();
  }

  public java.util.Iterator<String> getHostListIterator() {
    return (this.hostList == null) ? null : this.hostList.iterator();
  }

  public void addToHostList(String elem) {
    if (this.hostList == null) {
      this.hostList = new ArrayList<String>();
    }
    this.hostList.add(elem);
  }

  public List<String> getHostList() {
    return this.hostList;
  }

  public ThriftFlumeEvent setHostList(List<String> hostList) {
    this.hostList = hostList;
    return this;
  }

  public void unsetHostList() {
    this.hostList = null;
  }

  /** Returns true if field hostList is set (has been assigned a value) and false otherwise */
  public boolean isSetHostList() {
    return this.hostList != null;
  }

  public void setHostListIsSet(boolean value) {
    if (!value) {
      this.hostList = null;
    }
  }

  public void setFieldValue(_Fields field, Object value) {
    switch (field) {
    case TIMESTAMP:
      if (value == null) {
        unsetTimestamp();
      } else {
        setTimestamp((Long)value);
      }
      break;

    case PRIORITY:
      if (value == null) {
        unsetPriority();
      } else {
        setPriority((Priority)value);
      }
      break;

    case BODY:
      if (value == null) {
        unsetBody();
      } else {
        setBody((ByteBuffer)value);
      }
      break;

    case NANOS:
      if (value == null) {
        unsetNanos();
      } else {
        setNanos((Long)value);
      }
      break;

    case HOST:
      if (value == null) {
        unsetHost();
      } else {
        setHost((String)value);
      }
      break;

    case FIELDS:
      if (value == null) {
        unsetFields();
      } else {
        setFields((Map<String,ByteBuffer>)value);
      }
      break;

    case HOST_LIST:
      if (value == null) {
        unsetHostList();
      } else {
        setHostList((List<String>)value);
      }
      break;

    }
  }

  public Object getFieldValue(_Fields field) {
    switch (field) {
    case TIMESTAMP:
      return Long.valueOf(getTimestamp());

    case PRIORITY:
      return getPriority();

    case BODY:
      return getBody();

    case NANOS:
      return Long.valueOf(getNanos());

    case HOST:
      return getHost();

    case FIELDS:
      return getFields();

    case HOST_LIST:
      return getHostList();

    }
    throw new IllegalStateException();
  }

  /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
  public boolean isSet(_Fields field) {
    if (field == null) {
      throw new IllegalArgumentException();
    }

    switch (field) {
    case TIMESTAMP:
      return isSetTimestamp();
    case PRIORITY:
      return isSetPriority();
    case BODY:
      return isSetBody();
    case NANOS:
      return isSetNanos();
    case HOST:
      return isSetHost();
    case FIELDS:
      return isSetFields();
    case HOST_LIST:
      return isSetHostList();
    }
    throw new IllegalStateException();
  }

  @Override
  public boolean equals(Object that) {
    if (that == null)
      return false;
    if (that instanceof ThriftFlumeEvent)
      return this.equals((ThriftFlumeEvent)that);
    return false;
  }

  public boolean equals(ThriftFlumeEvent that) {
    if (that == null)
      return false;

    boolean this_present_timestamp = true;
    boolean that_present_timestamp = true;
    if (this_present_timestamp || that_present_timestamp) {
      if (!(this_present_timestamp && that_present_timestamp))
        return false;
      if (this.timestamp != that.timestamp)
        return false;
    }

    boolean this_present_priority = true && this.isSetPriority();
    boolean that_present_priority = true && that.isSetPriority();
    if (this_present_priority || that_present_priority) {
      if (!(this_present_priority && that_present_priority))
        return false;
      if (!this.priority.equals(that.priority))
        return false;
    }

    boolean this_present_body = true && this.isSetBody();
    boolean that_present_body = true && that.isSetBody();
    if (this_present_body || that_present_body) {
      if (!(this_present_body && that_present_body))
        return false;
      if (!this.body.equals(that.body))
        return false;
    }

    boolean this_present_nanos = true;
    boolean that_present_nanos = true;
    if (this_present_nanos || that_present_nanos) {
      if (!(this_present_nanos && that_present_nanos))
        return false;
      if (this.nanos != that.nanos)
        return false;
    }

    boolean this_present_host = true && this.isSetHost();
    boolean that_present_host = true && that.isSetHost();
    if (this_present_host || that_present_host) {
      if (!(this_present_host && that_present_host))
        return false;
      if (!this.host.equals(that.host))
        return false;
    }

    boolean this_present_fields = true && this.isSetFields();
    boolean that_present_fields = true && that.isSetFields();
    if (this_present_fields || that_present_fields) {
      if (!(this_present_fields && that_present_fields))
        return false;
      if (!this.fields.equals(that.fields))
        return false;
    }

    boolean this_present_hostList = true && this.isSetHostList();
    boolean that_present_hostList = true && that.isSetHostList();
    if (this_present_hostList || that_present_hostList) {
      if (!(this_present_hostList && that_present_hostList))
        return false;
      if (!this.hostList.equals(that.hostList))
        return false;
    }

    return true;
  }

  @Override
  public int hashCode() {
    return 0;
  }

  public int compareTo(ThriftFlumeEvent other) {
    if (!getClass().equals(other.getClass())) {
      return getClass().getName().compareTo(other.getClass().getName());
    }

    int lastComparison = 0;
    ThriftFlumeEvent typedOther = (ThriftFlumeEvent)other;

    lastComparison = Boolean.valueOf(isSetTimestamp()).compareTo(typedOther.isSetTimestamp());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetTimestamp()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.timestamp, typedOther.timestamp);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    lastComparison = Boolean.valueOf(isSetPriority()).compareTo(typedOther.isSetPriority());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetPriority()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.priority, typedOther.priority);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    lastComparison = Boolean.valueOf(isSetBody()).compareTo(typedOther.isSetBody());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetBody()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.body, typedOther.body);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    lastComparison = Boolean.valueOf(isSetNanos()).compareTo(typedOther.isSetNanos());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetNanos()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.nanos, typedOther.nanos);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    lastComparison = Boolean.valueOf(isSetHost()).compareTo(typedOther.isSetHost());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetHost()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.host, typedOther.host);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    lastComparison = Boolean.valueOf(isSetFields()).compareTo(typedOther.isSetFields());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetFields()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.fields, typedOther.fields);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    lastComparison = Boolean.valueOf(isSetHostList()).compareTo(typedOther.isSetHostList());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetHostList()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.hostList, typedOther.hostList);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    return 0;
  }

  public _Fields fieldForId(int fieldId) {
    return _Fields.findByThriftId(fieldId);
  }

  public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
    org.apache.thrift.protocol.TField field;
    iprot.readStructBegin();
    while (true)
    {
      field = iprot.readFieldBegin();
      if (field.type == org.apache.thrift.protocol.TType.STOP) {
        break;
      }
      switch (field.id) {
        case 1: // TIMESTAMP
          if (field.type == org.apache.thrift.protocol.TType.I64) {
            this.timestamp = iprot.readI64();
            setTimestampIsSet(true);
          } else {
            org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type);
          }
          break;
        case 2: // PRIORITY
          if (field.type == org.apache.thrift.protocol.TType.I32) {
            this.priority = Priority.findByValue(iprot.readI32());
          } else {
            org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type);
          }
          break;
        case 3: // BODY
          if (field.type == org.apache.thrift.protocol.TType.STRING) {
            this.body = iprot.readBinary();
          } else {
            org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type);
          }
          break;
        case 4: // NANOS
          if (field.type == org.apache.thrift.protocol.TType.I64) {
            this.nanos = iprot.readI64();
            setNanosIsSet(true);
          } else {
            org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type);
          }
          break;
        case 5: // HOST
          if (field.type == org.apache.thrift.protocol.TType.STRING) {
            this.host = iprot.readString();
          } else {
            org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type);
          }
          break;
        case 6: // FIELDS
          if (field.type == org.apache.thrift.protocol.TType.MAP) {
            {
              org.apache.thrift.protocol.TMap _map0 = iprot.readMapBegin();
              this.fields = new HashMap<String,ByteBuffer>(2*_map0.size);
              for (int _i1 = 0; _i1 < _map0.size; ++_i1)
              {
                String _key2; // required
                ByteBuffer _val3; // required
                _key2 = iprot.readString();
                _val3 = iprot.readBinary();
                this.fields.put(_key2, _val3);
              }
              iprot.readMapEnd();
            }
          } else {
            org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type);
          }
          break;
        case 7: // HOST_LIST
          if (field.type == org.apache.thrift.protocol.TType.LIST) {
            {
              org.apache.thrift.protocol.TList _list4 = iprot.readListBegin();
              this.hostList = new ArrayList<String>(_list4.size);
              for (int _i5 = 0; _i5 < _list4.size; ++_i5)
              {
                String _elem6; // required
                _elem6 = iprot.readString();
                this.hostList.add(_elem6);
              }
              iprot.readListEnd();
            }
          } else {
            org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type);
          }
          break;
        default:
          org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type);
      }
      iprot.readFieldEnd();
    }
    iprot.readStructEnd();

    // check for required fields of primitive type, which can't be checked in the validate method
    validate();
  }

  public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
    validate();

    oprot.writeStructBegin(STRUCT_DESC);
    oprot.writeFieldBegin(TIMESTAMP_FIELD_DESC);
    oprot.writeI64(this.timestamp);
    oprot.writeFieldEnd();
    if (this.priority != null) {
      oprot.writeFieldBegin(PRIORITY_FIELD_DESC);
      oprot.writeI32(this.priority.getValue());
      oprot.writeFieldEnd();
    }
    if (this.body != null) {
      oprot.writeFieldBegin(BODY_FIELD_DESC);
      oprot.writeBinary(this.body);
      oprot.writeFieldEnd();
    }
    oprot.writeFieldBegin(NANOS_FIELD_DESC);
    oprot.writeI64(this.nanos);
    oprot.writeFieldEnd();
    if (this.host != null) {
      oprot.writeFieldBegin(HOST_FIELD_DESC);
      oprot.writeString(this.host);
      oprot.writeFieldEnd();
    }
    if (this.fields != null) {
      oprot.writeFieldBegin(FIELDS_FIELD_DESC);
      {
        oprot.writeMapBegin(new org.apache.thrift.protocol.TMap(org.apache.thrift.protocol.TType.STRING, org.apache.thrift.protocol.TType.STRING, this.fields.size()));
        for (Map.Entry<String, ByteBuffer> _iter7 : this.fields.entrySet())
        {
          oprot.writeString(_iter7.getKey());
          oprot.writeBinary(_iter7.getValue());
        }
        oprot.writeMapEnd();
      }
      oprot.writeFieldEnd();
    }
    if (this.hostList != null) {
      oprot.writeFieldBegin(HOST_LIST_FIELD_DESC);
      {
        oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRING, this.hostList.size()));
        for (String _iter8 : this.hostList)
        {
          oprot.writeString(_iter8);
        }
        oprot.writeListEnd();
      }
      oprot.writeFieldEnd();
    }
    oprot.writeFieldStop();
    oprot.writeStructEnd();
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder("ThriftFlumeEvent(");
    boolean first = true;

    sb.append("timestamp:");
    sb.append(this.timestamp);
    first = false;
    if (!first) sb.append(", ");
    sb.append("priority:");
    if (this.priority == null) {
      sb.append("null");
    } else {
      sb.append(this.priority);
    }
    first = false;
    if (!first) sb.append(", ");
    sb.append("body:");
    if (this.body == null) {
      sb.append("null");
    } else {
      org.apache.thrift.TBaseHelper.toString(this.body, sb);
    }
    first = false;
    if (!first) sb.append(", ");
    sb.append("nanos:");
    sb.append(this.nanos);
    first = false;
    if (!first) sb.append(", ");
    sb.append("host:");
    if (this.host == null) {
      sb.append("null");
    } else {
      sb.append(this.host);
    }
    first = false;
    if (!first) sb.append(", ");
    sb.append("fields:");
    if (this.fields == null) {
      sb.append("null");
    } else {
      sb.append(this.fields);
    }
    first = false;
    if (!first) sb.append(", ");
    sb.append("hostList:");
    if (this.hostList == null) {
      sb.append("null");
    } else {
      sb.append(this.hostList);
    }
    first = false;
    sb.append(")");
    return sb.toString();
  }

  public void validate() throws org.apache.thrift.TException {
    // check for required fields
  }

  private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
    try {
      write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
    } catch (org.apache.thrift.TException te) {
      throw new java.io.IOException(te);
    }
  }

  private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
    try {
      // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
      __isset_bit_vector = new BitSet(1);
      read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
    } catch (org.apache.thrift.TException te) {
      throw new java.io.IOException(te);
    }
  }

}


text:
package Pathogens.NonVectored;

import Pathogens.NonVectoredPathogen;

public class BodyFluids extends NonVectoredPathogen{

	public BodyFluids(int a, double b, boolean c, boolean d) {
		super(a, b, c, d);
		// TODO Auto-generated constructor stub
	}

}

redpajama_set_name: RedPajamaGithub


text:
namespace ur_msgs
{
template <class ContainerAllocator>
struct RobotStateRTMsg_
{
  typedef RobotStateRTMsg_<ContainerAllocator> Type;

  RobotStateRTMsg_()
    : time(0.0)
    , q_target()
    , qd_target()
    , qdd_target()
    , i_target()
    , m_target()
    , q_actual()
    , qd_actual()
    , i_actual()
    , tool_acc_values()
    , tcp_force()
    , tool_vector()
    , tcp_speed()
    , digital_input_bits(0.0)
    , motor_temperatures()
    , controller_timer(0.0)
    , test_value(0.0)
    , robot_mode(0.0)
    , joint_modes()  {
    }
  RobotStateRTMsg_(const ContainerAllocator& _alloc)
    : time(0.0)
    , q_target(_alloc)
    , qd_target(_alloc)
    , qdd_target(_alloc)
    , i_target(_alloc)
    , m_target(_alloc)
    , q_actual(_alloc)
    , qd_actual(_alloc)
    , i_actual(_alloc)
    , tool_acc_values(_alloc)
    , tcp_force(_alloc)
    , tool_vector(_alloc)
    , tcp_speed(_alloc)
    , digital_input_bits(0.0)
    , motor_temperatures(_alloc)
    , controller_timer(0.0)
    , test_value(0.0)
    , robot_mode(0.0)
    , joint_modes(_alloc)  {
  (void)_alloc;
    }

   typedef double _time_type;
  _time_type time;

   typedef std::vector<double, typename ContainerAllocator::template rebind<double>::other >  _q_target_type;
  _q_target_type q_target;

   typedef std::vector<double, typename ContainerAllocator::template rebind<double>::other >  _qd_target_type;
  _qd_target_type qd_target;

   typedef std::vector<double, typename ContainerAllocator::template rebind<double>::other >  _qdd_target_type;
  _qdd_target_type qdd_target;

   typedef std::vector<double, typename ContainerAllocator::template rebind<double>::other >  _i_target_type;
  _i_target_type i_target;

   typedef std::vector<double, typename ContainerAllocator::template rebind<double>::other >  _m_target_type;
  _m_target_type m_target;

   typedef std::vector<double, typename ContainerAllocator::template rebind<double>::other >  _q_actual_type;
  _q_actual_type q_actual;

   typedef std::vector<double, typename ContainerAllocator::template rebind<double>::other >  _qd_actual_type;
  _qd_actual_type qd_actual;

   typedef std::vector<double, typename ContainerAllocator::template rebind<double>::other >  _i_actual_type;
  _i_actual_type i_actual;

   typedef std::vector<double, typename ContainerAllocator::template rebind<double>::other >  _tool_acc_values_type;
  _tool_acc_values_type tool_acc_values;

   typedef std::vector<double, typename ContainerAllocator::template rebind<double>::other >  _tcp_force_type;
  _tcp_force_type tcp_force;

   typedef std::vector<double, typename ContainerAllocator::template rebind<double>::other >  _tool_vector_type;
  _tool_vector_type tool_vector;

   typedef std::vector<double, typename ContainerAllocator::template rebind<double>::other >  _tcp_speed_type;
  _tcp_speed_type tcp_speed;

   typedef double _digital_input_bits_type;
  _digital_input_bits_type digital_input_bits;

   typedef std::vector<double, typename ContainerAllocator::template rebind<double>::other >  _motor_temperatures_type;
  _motor_temperatures_type motor_temperatures;

   typedef double _controller_timer_type;
  _controller_timer_type controller_timer;

   typedef double _test_value_type;
  _test_value_type test_value;

   typedef double _robot_mode_type;
  _robot_mode_type robot_mode;

   typedef std::vector<double, typename ContainerAllocator::template rebind<double>::other >  _joint_modes_type;
  _joint_modes_type joint_modes;

  typedef boost::shared_ptr< ::ur_msgs::RobotStateRTMsg_<ContainerAllocator> > Ptr;
  typedef boost::shared_ptr< ::ur_msgs::RobotStateRTMsg_<ContainerAllocator> const> ConstPtr;

}; // struct RobotStateRTMsg_

typedef ::ur_msgs::RobotStateRTMsg_<std::allocator<void> > RobotStateRTMsg;

typedef boost::shared_ptr< ::ur_msgs::RobotStateRTMsg > RobotStateRTMsgPtr;
typedef boost::shared_ptr< ::ur_msgs::RobotStateRTMsg const> RobotStateRTMsgConstPtr;

// constants requiring out of line definition

template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::ur_msgs::RobotStateRTMsg_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::ur_msgs::RobotStateRTMsg_<ContainerAllocator> >::stream(s, "", v);
return s;
}

} // namespace ur_msgs

namespace ros
{
namespace message_traits
{

// BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False}
// {'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'ur_msgs': ['/home/us-robot/catkin_ws/src/ur5-master/universal_robot-kinetic-devel/ur_msgs/msg']}

// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']

template <class ContainerAllocator>
struct IsFixedSize< ::ur_msgs::RobotStateRTMsg_<ContainerAllocator> >
  : FalseType
  { };

template <class ContainerAllocator>
struct IsFixedSize< ::ur_msgs::RobotStateRTMsg_<ContainerAllocator> const>
  : FalseType
  { };

template <class ContainerAllocator>
struct IsMessage< ::ur_msgs::RobotStateRTMsg_<ContainerAllocator> >
  : TrueType
  { };

template <class ContainerAllocator>
struct IsMessage< ::ur_msgs::RobotStateRTMsg_<ContainerAllocator> const>
  : TrueType
  { };

template <class ContainerAllocator>
struct HasHeader< ::ur_msgs::RobotStateRTMsg_<ContainerAllocator> >
  : FalseType
  { };

template <class ContainerAllocator>
struct HasHeader< ::ur_msgs::RobotStateRTMsg_<ContainerAllocator> const>
  : FalseType
  { };

template<class ContainerAllocator>
struct MD5Sum< ::ur_msgs::RobotStateRTMsg_<ContainerAllocator> >
{
  static const char* value()
  {
    return "ce6feddd3ccb4ca7dbcd0ff105b603c7";
  }

  static const char* value(const ::ur_msgs::RobotStateRTMsg_<ContainerAllocator>&) { return value(); }
  static const uint64_t static_value1 = 0xce6feddd3ccb4ca7ULL;
  static const uint64_t static_value2 = 0xdbcd0ff105b603c7ULL;
};

template<class ContainerAllocator>
struct DataType< ::ur_msgs::RobotStateRTMsg_<ContainerAllocator> >
{
  static const char* value()
  {
    return "ur_msgs/RobotStateRTMsg";
  }

  static const char* value(const ::ur_msgs::RobotStateRTMsg_<ContainerAllocator>&) { return value(); }
};

template<class ContainerAllocator>
struct Definition< ::ur_msgs::RobotStateRTMsg_<ContainerAllocator> >
{
  static const char* value()
  {
    return "# Data structure for the realtime communications interface (aka Matlab interface)\n\
# used by the Universal Robots controller\n\
# \n\
# This data structure is send at 125 Hz on TCP port 30003\n\
# \n\
# Dokumentation can be found on the Universal Robots Support Wiki\n\
# (http://wiki03.lynero.net/Technical/RealTimeClientInterface?rev=9)\n\
\n\
float64 time\n\
float64[] q_target\n\
float64[] qd_target\n\
float64[] qdd_target\n\
float64[] i_target\n\
float64[] m_target\n\
float64[] q_actual\n\
float64[] qd_actual\n\
float64[] i_actual\n\
float64[] tool_acc_values\n\
float64[] tcp_force\n\
float64[] tool_vector\n\
float64[] tcp_speed\n\
float64 digital_input_bits\n\
float64[] motor_temperatures\n\
float64 controller_timer\n\
float64 test_value\n\
float64 robot_mode\n\
float64[] joint_modes\n\
";
  }

  static const char* value(const ::ur_msgs::RobotStateRTMsg_<ContainerAllocator>&) { return value(); }
};

} // namespace message_traits
} // namespace ros

namespace ros
{
namespace serialization
{

  template<class ContainerAllocator> struct Serializer< ::ur_msgs::RobotStateRTMsg_<ContainerAllocator> >
  {
    template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
    {
      stream.next(m.time);
      stream.next(m.q_target);
      stream.next(m.qd_target);
      stream.next(m.qdd_target);
      stream.next(m.i_target);
      stream.next(m.m_target);
      stream.next(m.q_actual);
      stream.next(m.qd_actual);
      stream.next(m.i_actual);
      stream.next(m.tool_acc_values);
      stream.next(m.tcp_force);
      stream.next(m.tool_vector);
      stream.next(m.tcp_speed);
      stream.next(m.digital_input_bits);
      stream.next(m.motor_temperatures);
      stream.next(m.controller_timer);
      stream.next(m.test_value);
      stream.next(m.robot_mode);
      stream.next(m.joint_modes);
    }

    ROS_DECLARE_ALLINONE_SERIALIZER
  }; // struct RobotStateRTMsg_

} // namespace serialization
} // namespace ros

namespace ros
{
namespace message_operations
{

template<class ContainerAllocator>
struct Printer< ::ur_msgs::RobotStateRTMsg_<ContainerAllocator> >
{
  template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::ur_msgs::RobotStateRTMsg_<ContainerAllocator>& v)
  {
    s << indent << "time: ";
    Printer<double>::stream(s, indent + "  ", v.time);
    s << indent << "q_target[]" << std::endl;
    for (size_t i = 0; i < v.q_target.size(); ++i)
    {
      s << indent << "  q_target[" << i << "]: ";
      Printer<double>::stream(s, indent + "  ", v.q_target[i]);
    }
    s << indent << "qd_target[]" << std::endl;
    for (size_t i = 0; i < v.qd_target.size(); ++i)
    {
      s << indent << "  qd_target[" << i << "]: ";
      Printer<double>::stream(s, indent + "  ", v.qd_target[i]);
    }
    s << indent << "qdd_target[]" << std::endl;
    for (size_t i = 0; i < v.qdd_target.size(); ++i)
    {
      s << indent << "  qdd_target[" << i << "]: ";
      Printer<double>::stream(s, indent + "  ", v.qdd_target[i]);
    }
    s << indent << "i_target[]" << std::endl;
    for (size_t i = 0; i < v.i_target.size(); ++i)
    {
      s << indent << "  i_target[" << i << "]: ";
      Printer<double>::stream(s, indent + "  ", v.i_target[i]);
    }
    s << indent << "m_target[]" << std::endl;
    for (size_t i = 0; i < v.m_target.size(); ++i)
    {
      s << indent << "  m_target[" << i << "]: ";
      Printer<double>::stream(s, indent + "  ", v.m_target[i]);
    }
    s << indent << "q_actual[]" << std::endl;
    for (size_t i = 0; i < v.q_actual.size(); ++i)
    {
      s << indent << "  q_actual[" << i << "]: ";
      Printer<double>::stream(s, indent + "  ", v.q_actual[i]);
    }
    s << indent << "qd_actual[]" << std::endl;
    for (size_t i = 0; i < v.qd_actual.size(); ++i)
    {
      s << indent << "  qd_actual[" << i << "]: ";
      Printer<double>::stream(s, indent + "  ", v.qd_actual[i]);
    }
    s << indent << "i_actual[]" << std::endl;
    for (size_t i = 0; i < v.i_actual.size(); ++i)
    {
      s << indent << "  i_actual[" << i << "]: ";
      Printer<double>::stream(s, indent + "  ", v.i_actual[i]);
    }
    s << indent << "tool_acc_values[]" << std::endl;
    for (size_t i = 0; i < v.tool_acc_values.size(); ++i)
    {
      s << indent << "  tool_acc_values[" << i << "]: ";
      Printer<double>::stream(s, indent + "  ", v.tool_acc_values[i]);
    }
    s << indent << "tcp_force[]" << std::endl;
    for (size_t i = 0; i < v.tcp_force.size(); ++i)
    {
      s << indent << "  tcp_force[" << i << "]: ";
      Printer<double>::stream(s, indent + "  ", v.tcp_force[i]);
    }
    s << indent << "tool_vector[]" << std::endl;
    for (size_t i = 0; i < v.tool_vector.size(); ++i)
    {
      s << indent << "  tool_vector[" << i << "]: ";
      Printer<double>::stream(s, indent + "  ", v.tool_vector[i]);
    }
    s << indent << "tcp_speed[]" << std::endl;
    for (size_t i = 0; i < v.tcp_speed.size(); ++i)
    {
      s << indent << "  tcp_speed[" << i << "]: ";
      Printer<double>::stream(s, indent + "  ", v.tcp_speed[i]);
    }
    s << indent << "digital_input_bits: ";
    Printer<double>::stream(s, indent + "  ", v.digital_input_bits);
    s << indent << "motor_temperatures[]" << std::endl;
    for (size_t i = 0; i < v.motor_temperatures.size(); ++i)
    {
      s << indent << "  motor_temperatures[" << i << "]: ";
      Printer<double>::stream(s, indent + "  ", v.motor_temperatures[i]);
    }
    s << indent << "controller_timer: ";
    Printer<double>::stream(s, indent + "  ", v.controller_timer);
    s << indent << "test_value: ";
    Printer<double>::stream(s, indent + "  ", v.test_value);
    s << indent << "robot_mode: ";
    Printer<double>::stream(s, indent + "  ", v.robot_mode);
    s << indent << "joint_modes[]" << std::endl;
    for (size_t i = 0; i < v.joint_modes.size(); ++i)
    {
      s << indent << "  joint_modes[" << i << "]: ";
      Printer<double>::stream(s, indent + "  ", v.joint_modes[i]);
    }
  }
};

} // namespace message_operations
} // namespace ros

#endif // UR_MSGS_MESSAGE_ROBOTSTATERTMSG_H


text:
<?php

namespace admin\importers;

use Yii;
use admin\models\Property;

class PropertyImporter extends \luya\base\Importer
{
    public function run()
    {
        $ids = [];

        foreach($this->getImporter()->getDirectoryFiles('properties') as $file) {
            $className = $file['ns'];

            if (class_exists($className)) {
                $object = Yii::createObject(['class' => $className, 'moduleName' => $file['module']]);
                if ($object) {
                    $ids[] = $object->install();
                    $this->getImporter()->addLog('properties', 'Property ' . $object->varName() . ' is installed and up to date.');
                }
            }
        }

        foreach(Property::find()->where(['not in', 'id', $ids])->all() as $model) {
            $this->getImporter()->addLog('properties', 'Removing property '. $model->var_name);
            $model->delete();
        }
    }
}


text:
def die(msg); puts(msg); exit!(1); end

# First thing we do is check the ruby version. This script requires 1.9, die
# if that's not the case.
die("This script requires ruby 1.9") unless RUBY_VERSION =~ /^1.9/

require 'json'
require 'net/https'
require 'pathname'
require 'optparse'

# Extensions
# ----------

# We extend Pathname a bit to get the content type.
class Pathname
  def type
    if $options[:mime_type] then
      $options[:mime_type]
    else
      flags = RUBY_PLATFORM =~ /darwin/ ? 'Ib' : 'ib'
      `file -#{flags} #{realpath}`.chomp.gsub(/;.*/,'')
    end
  end
end

# Helpers
# -------

def get_http_request(uri, token, request, params = "")
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE if $options[:skip_ssl_verification]
  request['Authorization'] = "token #{token}" if token
  return http.request(request, params)
end

def get(url, token)
  uri = URI.parse(url)
  req = Net::HTTP::Get.new(uri.path)
  return get_http_request(uri, token, req)
end

# Do a post to the given url, with the payload and optional basic auth.
def post(url, token, params, headers)
  uri = URI.parse(url)
  req = Net::HTTP::Post.new(uri.path, headers)
  return get_http_request(uri, token, req, params)
end

def delete(url, token)
  uri = URI.parse(url)
  req = Net::HTTP::Delete.new(uri.path)
  return get_http_request(uri, token, req)
end

def urlencode(str)
  str.gsub(/[^a-zA-Z0-9_\.\-]/n) {|s| sprintf('%%%02x', s[0].to_i) }
end

# Yep, ruby net/http doesn't support multipart. Write our own multipart generator.
# The order of the params is important, the file needs to go as last!
def build_multipart_content(params)
  parts, boundary = [], "#{rand(1000000)}-we-are-all-doomed-#{rand(1000000)}"

  params.each do |name, value|
    data = []
    if value.is_a?(Pathname) then
      data << "Content-Disposition: form-data; name=\"#{urlencode(name.to_s)}\"; filename=\"#{value.basename}\""
      data << "Content-Type: #{value.type}"
      data << "Content-Length: #{value.size}"
      data << "Content-Transfer-Encoding: binary"
      data << ""
      data << value.binread
    else
      data << "Content-Disposition: form-data; name=\"#{urlencode(name.to_s)}\""
      data << ""
      data << value
    end

    parts << data.join("\r\n") + "\r\n"
  end

  [ "--#{boundary}\r\n" + parts.join("--#{boundary}\r\n") + "--#{boundary}--", {
    "Content-Type" => "multipart/form-data; boundary=#{boundary}"
  }]
end

# Parse command line options using OptionParser
# -----------------------

$options = {}

OptionParser.new do |opts|

  opts.banner = "Usage: github-upload.rb <file-name> [<repository>] [options]"

  opts.on("-d", "--description [DESCRIPTION]",
      "Add a description to the uploaded file.") do |arg_description|
    $options[:file_description] = arg_description
  end

  opts.on("-n", "--name [NAME]",
      "New name of the uploaded file.") do |arg_name|
    $options[:file_name] = arg_name
  end

  opts.on("-f", "--force",
      "If a file with that name already exists on the server, replace it with this one.") do
    $options[:force_upload] = true
  end

  opts.on("-t", "--token [TOKEN]",
      "Manually specify a GitHub API token. Useful if you want to temporarily upload a file under a different GitHub account.") do |arg_token|
    $options[:token] = arg_token
  end

  opts.on("--skip-ssl-verification",
      "Skip SSL Verification in the HTTP Request.") do
    $options[:skip_ssl_verification] = true
  end

  opts.on("-m", "--mime-type [TYPE]",
      "Manually specify mime-type instead autodetection.") do |arg_type|
    $options[:mime_type] = arg_type
  end

  opts.on("-h", "--help",
      "Show this message") do
    puts opts
    exit
  end

end.parse!

# Configuration and setup
# -----------------------

# The file we want to upload, and repo where to upload it to.
die("Please specify a file to upload.") if ARGV.length < 1
file = Pathname.new(ARGV[0])
repo = ARGV[1] || `git config --get remote.origin.url`.match(/git@github.com:(.+?)\.git/)[1]

file_name =        $options[:file_name] || file.basename.to_s
file_description = $options[:file_description] || ""

# The actual, hard work
# ---------------------

# Get Oauth token for this script.
$options[:token] = `git config --get github.upload-script-token`.chomp unless $options[:token]

if $options[:force_upload]

  # Make sure the file doesn't already exist
  res = get("https://api.github.com/repos/#{repo}/downloads", $options[:token])
  info = JSON.parse(res.body)
  info.each do |remote_file|
    remote_file_name = remote_file["name"].to_s
    if remote_file_name == file_name then
      # Delete already existing files
      puts "Deleting existing file '#{remote_file_name}'"
      remote_file_id = remote_file["id"].to_s
      res = delete("https://api.github.com/repos/#{repo}/downloads/#{remote_file_id}", $options[:token])
    end
  end

end

# Register the download at github.
res = post("https://api.github.com/repos/#{repo}/downloads", $options[:token], {
  'name' => file_name, 'size' => file.size.to_s,
  'description' => file_description,
  'content_type' => file.type.gsub(/;.*/, '')
}.to_json, {})

die("File already exists named '#{file_name}'.") if res.class == Net::HTTPClientError
die("GitHub doesn't want us to upload the file.") unless res.class == Net::HTTPCreated

# Parse the body and use the info to upload the file to S3.
info = JSON.parse(res.body)
res = post(info['s3_url'], nil, *build_multipart_content({
  'key' => info['path'], 'acl' => info['acl'], 'success_action_status' => 201,
  'Filename' => info['name'], 'AWSAccessKeyId' => info['accesskeyid'],
  'Policy' => info['policy'], 'signature' => info['signature'],
  'Content-Type' => info['mime_type'], 'file' => file
}))

die("S3 is mean to us.") unless res.class == Net::HTTPCreated

# Print the URL to the file to stdout.
puts "#{info['s3_url']}#{info['path']}"


text:
package com.github.amsemy.resty.json.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Указывает что, поле класса является полем представления объекта. Применима к
 * полям POJO-классов.
 *
 * @see  RstPojo
 * @see  RstGetter
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RstField {

    /**
     * (Необязательно) Возвращает имя поля представления объекта, которое будет
     * содержать значение, возвращемое полем объекта.
     *
     * @return  Имя поля или {@code ""}.
     */
    String value() default "";

}


text:
"""Împăratul a primit serie de mesaje importante pe care este
important să le descifreze cât mai repede.

Din păcate mesagerul nu a apucat să îi spună împăratul care au fost
cheile alese pentru fiecare mesaj și tu ai fost ales să descifrezi
misterul.

Informații:
    În criptografie, cifrul lui Caesar este o metodă simplă de a cripta
un mesaj prin înlocuirea fiecărei litere cu litera de pe poziția aflată
la un n pași de ea în alfabet (unde este n este un număr întreg cunoscut
"""
# existau 2 variante de a rezolva problema cu parantezele la print
# am preferat sa o folosesc pe asta pentru a evita si eventualele probleme
# cu care ziceai tu ca o sa ne stresezi ;)
from __future__ import print_function

LETTERS = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"
# tot timpul se va gasi litera in string-ul "LETTERS"
# deci circularitatea e suficient
# reprezentata prin a-z de doua ori

def shift_letter(let, number):
    """Shifts a letter by number places in LETTERS"""
    if let.isalpha():
        # procesam doar literele
        return LETTERS[ord(let) - 97 + number]
        # returnam litera de peste n locuri in LETTERS
    else:
        return let
        # daca nu e litera, returnam caracterul original

def decripteaza(mesaj, number):
    """Decrypts every line in <mesaj>"""
    new_msg = ""
    for char in mesaj:
        new_msg += shift_letter(char, number)
    if "ave" in new_msg:
        print(new_msg)

def main():
    """Have a main docstring, pylint"""
    try:
        fisier = open("mesaje.secret", "r")
        mesaje = fisier.read()
        fisier.close()
    except IOError:
        print("Nu am putut obține mesajele.")
        return

    for mesaj in mesaje.splitlines():
        for i in range(26):
            decripteaza(mesaj, i)

if __name__ == "__main__":
    main()


text:
package springfox.documentation.swagger1.dto;

public class TokenRequestEndpoint {

    private String url;
    private String clientIdName;
    private String clientSecretName;

    public TokenRequestEndpoint() {
    }

    public TokenRequestEndpoint(String url, String clientIdName, String clientSecretName) {
        this.url = url;
        this.clientIdName = clientIdName;
        this.clientSecretName = clientSecretName;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getClientIdName() {
        return clientIdName;
    }

    public void setClientIdName(String clientIdName) {
        this.clientIdName = clientIdName;
    }

    public String getClientSecretName() {
        return clientSecretName;
    }

    public void setClientSecretName(String clientSecretName) {
        this.clientSecretName = clientSecretName;
    }
}


text:
package org.elasticsearch.cloud.aws.node;

import org.apache.lucene.util.IOUtils;
import org.elasticsearch.cloud.aws.AwsEc2Service;
import org.elasticsearch.cluster.node.DiscoveryNodeService;
import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.settings.Settings;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 */
public class Ec2CustomNodeAttributes extends AbstractComponent implements DiscoveryNodeService.CustomAttributesProvider {

    public Ec2CustomNodeAttributes(Settings settings) {
        super(settings);
    }

    @Override
    public Map<String, String> buildAttributes() {
        if (!settings.getAsBoolean("cloud.node.auto_attributes", false)) {
            return null;
        }
        Map<String, String> ec2Attributes = new HashMap<>();

        URLConnection urlConnection;
        InputStream in = null;
        try {
            URL url = new URL(AwsEc2Service.EC2_METADATA_URL + "placement/availability-zone");
            logger.debug("obtaining ec2 [placement/availability-zone] from ec2 meta-data url {}", url);
            urlConnection = url.openConnection();
            urlConnection.setConnectTimeout(2000);
            in = urlConnection.getInputStream();
            BufferedReader urlReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));

            String metadataResult = urlReader.readLine();
            if (metadataResult == null || metadataResult.length() == 0) {
                logger.error("no ec2 metadata returned from {}", url);
                return null;
            }
            ec2Attributes.put("aws_availability_zone", metadataResult);
        } catch (IOException e) {
            logger.debug("failed to get metadata for [placement/availability-zone]", e);
        } finally {
            IOUtils.closeWhileHandlingException(in);
        }

        return ec2Attributes;
    }
}


text:
import pytest
import mock

from django.apps import apps
from awx.conf.migrations._reencrypt import (
    replace_aesecb_fernet,
    encrypt_field,
    decrypt_field,
)
from awx.conf.settings import Setting
from awx.main.utils import decrypt_field as new_decrypt_field

@pytest.mark.django_db
@pytest.mark.parametrize("old_enc, new_enc, value", [
    ('$encrypted$UTF8$AES', '$encrypted$UTF8$AESCBC$', u'Iñtërnâtiônàlizætiøn'),
    ('$encrypted$AES$', '$encrypted$AESCBC$', 'test'),
])
def test_settings(old_enc, new_enc, value):
    with mock.patch('awx.conf.models.encrypt_field', encrypt_field):
        with mock.patch('awx.conf.settings.decrypt_field', decrypt_field):
            setting = Setting.objects.create(key='SOCIAL_AUTH_GITHUB_SECRET', value=value)
    assert setting.value.startswith(old_enc)

    replace_aesecb_fernet(apps, None)
    setting.refresh_from_db()

    assert setting.value.startswith(new_enc)
    assert new_decrypt_field(setting, 'value') == value

    # This is here for a side-effect.
    # Exception if the encryption type of AESCBC is not properly skipped, ensures
    # our `startswith` calls don't have typos
    replace_aesecb_fernet(apps, None)


text:
/***************************************************************************//**
 * @file em_aes.c
 * @brief Advanced Encryption Standard (AES) accelerator peripheral API.
 * @version 5.3.3
 *******************************************************************************
 * # License
 * <b>Copyright 2016 Silicon Laboratories, Inc. http://www.silabs.com</b>
 *******************************************************************************
 *
 * Permission is granted to anyone to use this software for any purpose,
 * including commercial applications, and to alter it and redistribute it
 * freely, subject to the following restrictions:
 *
 * 1. The origin of this software must not be misrepresented; you must not
 *    claim that you wrote the original software.
 * 2. Altered source versions must be plainly marked as such, and must not be
 *    misrepresented as being the original software.
 * 3. This notice may not be removed or altered from any source distribution.
 *
 * DISCLAIMER OF WARRANTY/LIMITATION OF REMEDIES: Silicon Labs has no
 * obligation to support this Software. Silicon Labs is providing the
 * Software "AS IS", with no express or implied warranties of any kind,
 * including, but not limited to, any implied warranties of merchantability
 * or fitness for any particular purpose or warranties against infringement
 * of any proprietary rights of a third party.
 *
 * Silicon Labs will not be liable for any consequential, incidental, or
 * special damages, or any other relief, or for any claim by any third party,
 * arising from your use of this Software.
 *
 ******************************************************************************/

#include "em_aes.h"
#if defined(AES_COUNT) && (AES_COUNT > 0)

#include "em_assert.h"
/***************************************************************************//**
 * @addtogroup emlib
 * @{
 ******************************************************************************/

/***************************************************************************//**
 * @addtogroup AES
 * @{
 ******************************************************************************/

/*******************************************************************************
 *******************************   DEFINES   ***********************************
 ******************************************************************************/

/** @cond DO_NOT_INCLUDE_WITH_DOXYGEN */

#define AES_BLOCKSIZE    16

/** @endcond */

/*******************************************************************************
 **************************   GLOBAL FUNCTIONS   *******************************
 ******************************************************************************/

/***************************************************************************//**
 * @brief
 *   Cipher-block chaining (CBC) cipher mode encryption/decryption, 128 bit key.
 *
 * @details
 *   Encryption:
 * @verbatim
 *           Plaintext                  Plaintext
 *               |                          |
 *               V                          V
 * InitVector ->XOR        +-------------->XOR
 *               |         |                |
 *               V         |                V
 *       +--------------+  |        +--------------+
 * Key ->| Block cipher |  |  Key ->| Block cipher |
 *       |  encryption  |  |        |  encryption  |
 *       +--------------+  |        +--------------+
 *               |---------+                |
 *               V                          V
 *           Ciphertext                 Ciphertext
 * @endverbatim
 *   Decryption:
 * @verbatim
 *         Ciphertext                 Ciphertext
 *              |----------+                |
 *              V          |                V
 *       +--------------+  |        +--------------+
 * Key ->| Block cipher |  |  Key ->| Block cipher |
 *       |  decryption  |  |        |  decryption  |
 *       +--------------+  |        +--------------+
 *               |         |                |
 *               V         |                V
 * InitVector ->XOR        +-------------->XOR
 *               |                          |
 *               V                          V
 *           Plaintext                  Plaintext
 * @endverbatim
 *   Please refer to general comments on layout and byte ordering of parameters.
 *
 * @param[out] out
 *   Buffer to place encrypted/decrypted data. Must be at least @p len long. It
 *   may be set equal to @p in, in which case the input buffer is overwritten.
 *
 * @param[in] in
 *   Buffer holding data to encrypt/decrypt. Must be at least @p len long.
 *
 * @param[in] len
 *   Number of bytes to encrypt/decrypt. Must be a multiple of 16.
 *
 * @param[in] key
 *   When doing encryption, this is the 128 bit encryption key. When doing
 *   decryption, this is the 128 bit decryption key. The decryption key may
 *   be generated from the encryption key with AES_DecryptKey128().
 *   On devices supporting key buffering this argument can be null, if so, the
 *   key will not be loaded, as it is assumed the key has been loaded
 *   into KEYHA previously.
 *
 * @param[in] iv
 *   128 bit initalization vector to use.
 *
 * @param[in] encrypt
 *   Set to true to encrypt, false to decrypt.
 ******************************************************************************/
void AES_CBC128(uint8_t *out,
                const uint8_t *in,
                unsigned int len,
                const uint8_t *key,
                const uint8_t *iv,
                bool encrypt)
{
  int            i;
  uint32_t       *_out = (uint32_t *)out;
  const uint32_t *_in  = (const uint32_t *)in;
  const uint32_t *_key = (const uint32_t *)key;
  const uint32_t *_iv  = (const uint32_t *)iv;
  /* Need to buffer one block when decrypting in case 'out' replaces 'in' */
  uint32_t       prev[4];

  EFM_ASSERT(!(len % AES_BLOCKSIZE));

  /* Number of blocks to process */
  len /= AES_BLOCKSIZE;

  #if defined(AES_CTRL_KEYBUFEN)
  if (key) {
    /* Load key into high key for key buffer usage */
    for (i = 3; i >= 0; i--) {
      AES->KEYHA = __REV(_key[i]);
    }
  }
  #endif

  if (encrypt) {
    /* Enable encryption with auto start using XOR */
    #if defined(AES_CTRL_KEYBUFEN)
    AES->CTRL = AES_CTRL_KEYBUFEN | AES_CTRL_XORSTART;
    #else
    AES->CTRL = AES_CTRL_XORSTART;
    #endif

    /* Load initialization vector, since writing to DATA, it will */
    /* not trigger encryption. */
    for (i = 3; i >= 0; i--) {
      AES->DATA = __REV(_iv[i]);
    }

    /* Encrypt data */
    while (len--) {
      #if !defined(AES_CTRL_KEYBUFEN)
      /* Load key */
      for (i = 3; i >= 0; i--) {
        AES->KEYLA = __REV(_key[i]);
      }
      #endif

      /* Load data and trigger encryption */
      for (i = 3; i >= 0; i--) {
        AES->XORDATA = __REV(_in[i]);
      }
      _in += 4;

      /* Wait for completion */
      while (AES->STATUS & AES_STATUS_RUNNING)
        ;

      /* Save encrypted data */
      for (i = 3; i >= 0; i--) {
        _out[i] = __REV(AES->DATA);
      }
      _out += 4;
    }
  } else {
    /* Select decryption mode */
    #if defined(AES_CTRL_KEYBUFEN)
    AES->CTRL = AES_CTRL_DECRYPT | AES_CTRL_KEYBUFEN | AES_CTRL_DATASTART;
    #else
    AES->CTRL = AES_CTRL_DECRYPT | AES_CTRL_DATASTART;
    #endif

    /* Copy init vector to previous buffer to avoid special handling */
    for (i = 0; i < 4; i++) {
      prev[i] = _iv[i];
    }

    /* Decrypt data */
    while (len--) {
      #if !defined(AES_CTRL_KEYBUFEN)
      /* Load key */
      for (i = 3; i >= 0; i--) {
        AES->KEYLA = __REV(_key[i]);
      }
      #endif

      /* Load data and trigger decryption */
      for (i = 3; i >= 0; i--) {
        AES->DATA = __REV(_in[i]);
      }

      /* Wait for completion */
      while (AES->STATUS & AES_STATUS_RUNNING)
        ;

      /* In order to avoid additional buffer, we use HW directly for XOR and buffer */
      /* (Writing to XORDATA will not trigger encoding, triggering enabled on DATA.) */
      for (i = 3; i >= 0; i--) {
        AES->XORDATA = __REV(prev[i]);
        prev[i]      = _in[i];
      }
      _in += 4;

      /* Then fetch decrypted data, we have to do it in a separate loop */
      /* due to internal auto-shifting of words */
      for (i = 3; i >= 0; i--) {
        _out[i] = __REV(AES->DATA);
      }
      _out += 4;
    }
  }
}

#if defined(AES_CTRL_AES256)
/***************************************************************************//**
 * @brief
 *   Cipher-block chaining (CBC) cipher mode encryption/decryption, 256 bit key.
 *
 * @details
 *   Please see AES_CBC128() for CBC figure.
 *
 *   Please refer to general comments on layout and byte ordering of parameters.
 *
 * @param[out] out
 *   Buffer to place encrypted/decrypted data. Must be at least @p len long. It
 *   may be set equal to @p in, in which case the input buffer is overwritten.
 *
 * @param[in] in
 *   Buffer holding data to encrypt/decrypt. Must be at least @p len long.
 *
 * @param[in] len
 *   Number of bytes to encrypt/decrypt. Must be a multiple of 16.
 *
 * @param[in] key
 *   When doing encryption, this is the 256 bit encryption key. When doing
 *   decryption, this is the 256 bit decryption key. The decryption key may
 *   be generated from the encryption key with AES_DecryptKey256().
 *
 * @param[in] iv
 *   128 bit initalization vector to use.
 *
 * @param[in] encrypt
 *   Set to true to encrypt, false to decrypt.
 ******************************************************************************/
void AES_CBC256(uint8_t *out,
                const uint8_t *in,
                unsigned int len,
                const uint8_t *key,
                const uint8_t *iv,
                bool encrypt)
{
  int            i;
  int            j;
  uint32_t       *_out = (uint32_t *)out;
  const uint32_t *_in  = (const uint32_t *)in;
  const uint32_t *_key = (const uint32_t *)key;
  const uint32_t *_iv  = (const uint32_t *)iv;
  /* Need to buffer one block when decrypting in case output replaces input */
  uint32_t       prev[4];

  EFM_ASSERT(!(len % AES_BLOCKSIZE));

  /* Number of blocks to process */
  len /= AES_BLOCKSIZE;

  if (encrypt) {
    /* Enable encryption with auto start using XOR */
    AES->CTRL = AES_CTRL_AES256 | AES_CTRL_XORSTART;

    /* Load initialization vector, since writing to DATA, it will */
    /* not trigger encryption. */
    for (i = 3; i >= 0; i--) {
      AES->DATA = __REV(_iv[i]);
    }

    /* Encrypt data */
    while (len--) {
      /* Load key and data and trigger encryption */
      for (i = 3, j = 7; i >= 0; i--, j--) {
        AES->KEYLA = __REV(_key[j]);
        AES->KEYHA = __REV(_key[i]);
        /* Write data last, since will trigger encryption on last iteration */
        AES->XORDATA = __REV(_in[i]);
      }
      _in += 4;

      /* Wait for completion */
      while (AES->STATUS & AES_STATUS_RUNNING)
        ;

      /* Save encrypted data */
      for (i = 3; i >= 0; i--) {
        _out[i] = __REV(AES->DATA);
      }
      _out += 4;
    }
  } else {
    /* Select decryption mode */
    AES->CTRL = AES_CTRL_AES256 | AES_CTRL_DECRYPT | AES_CTRL_DATASTART;

    /* Copy init vector to previous buffer to avoid special handling */
    for (i = 0; i < 4; i++) {
      prev[i] = _iv[i];
    }

    /* Decrypt data */
    while (len--) {
      /* Load key and data and trigger decryption */
      for (i = 3, j = 7; i >= 0; i--, j--) {
        AES->KEYLA = __REV(_key[j]);
        AES->KEYHA = __REV(_key[i]);
        /* Write data last, since will trigger encryption on last iteration */
        AES->DATA = __REV(_in[i]);
      }

      /* Wait for completion */
      while (AES->STATUS & AES_STATUS_RUNNING)
        ;

      /* In order to avoid additional buffer, we use HW directly for XOR and buffer */
      for (i = 3; i >= 0; i--) {
        AES->XORDATA = __REV(prev[i]);
        prev[i]      = _in[i];
      }
      _in += 4;

      /* Then fetch decrypted data, we have to do it in a separate loop */
      /* due to internal auto-shifting of words */
      for (i = 3; i >= 0; i--) {
        _out[i] = __REV(AES->DATA);
      }
      _out += 4;
    }
  }
}
#endif

/***************************************************************************//**
 * @brief
 *   Cipher feedback (CFB) cipher mode encryption/decryption, 128 bit key.
 *
 * @details
 *   Encryption:
 * @verbatim
 *           InitVector    +----------------+
 *               |         |                |
 *               V         |                V
 *       +--------------+  |        +--------------+
 * Key ->| Block cipher |  |  Key ->| Block cipher |
 *       |  encryption  |  |        |  encryption  |
 *       +--------------+  |        +--------------+
 *               |         |                |
 *               V         |                V
 *  Plaintext ->XOR        |   Plaintext ->XOR
 *               |---------+                |
 *               V                          V
 *           Ciphertext                 Ciphertext
 * @endverbatim
 *   Decryption:
 * @verbatim
 *          InitVector     +----------------+
 *               |         |                |
 *               V         |                V
 *       +--------------+  |        +--------------+
 * Key ->| Block cipher |  |  Key ->| Block cipher |
 *       |  encryption  |  |        |  encryption  |
 *       +--------------+  |        +--------------+
 *               |         |                |
 *               V         |                V
 *              XOR<- Ciphertext           XOR<- Ciphertext
 *               |                          |
 *               V                          V
 *           Plaintext                  Plaintext
 * @endverbatim
 *   Please refer to general comments on layout and byte ordering of parameters.
 *
 * @param[out] out
 *   Buffer to place encrypted/decrypted data. Must be at least @p len long. It
 *   may be set equal to @p in, in which case the input buffer is overwritten.
 *
 * @param[in] in
 *   Buffer holding data to encrypt/decrypt. Must be at least @p len long.
 *
 * @param[in] len
 *   Number of bytes to encrypt/decrypt. Must be a multiple of 16.
 *
 * @param[in] key
 *   128 bit encryption key is used for both encryption and decryption modes.
 *
 * @param[in] iv
 *   128 bit initalization vector to use.
 *
 * @param[in] encrypt
 *   Set to true to encrypt, false to decrypt.
 ******************************************************************************/
void AES_CFB128(uint8_t *out,
                const uint8_t *in,
                unsigned int len,
                const uint8_t *key,
                const uint8_t *iv,
                bool encrypt)
{
  int            i;
  uint32_t       *_out = (uint32_t *)out;
  const uint32_t *_in  = (const uint32_t *)in;
  const uint32_t *_key = (const uint32_t *)key;
  const uint32_t *_iv  = (const uint32_t *)iv;
  const uint32_t *data;
  uint32_t       tmp[4];

  EFM_ASSERT(!(len % AES_BLOCKSIZE));

  #if defined(AES_CTRL_KEYBUFEN)
  AES->CTRL = AES_CTRL_KEYBUFEN | AES_CTRL_DATASTART;
  #else
  AES->CTRL = AES_CTRL_DATASTART;
  #endif

  #if defined(AES_CTRL_KEYBUFEN)
  /* Load key into high key for key buffer usage */
  for (i = 3; i >= 0; i--) {
    AES->KEYHA = __REV(_key[i]);
  }
  #endif

  /* Encrypt/decrypt data */
  data = _iv;
  len /= AES_BLOCKSIZE;
  while (len--) {
    #if !defined(AES_CTRL_KEYBUFEN)
    /* Load key */
    for (i = 3; i >= 0; i--) {
      AES->KEYLA = __REV(_key[i]);
    }
    #endif

    /* Load data and trigger encryption */
    for (i = 3; i >= 0; i--) {
      AES->DATA = __REV(data[i]);
    }

    /* Do some required processing before waiting for completion */
    if (encrypt) {
      data = _out;
    } else {
      /* Must copy current ciphertext block since it may be overwritten */
      for (i = 0; i < 4; i++) {
        tmp[i] = _in[i];
      }
      data = tmp;
    }

    /* Wait for completion */
    while (AES->STATUS & AES_STATUS_RUNNING)
      ;

    /* Save encrypted/decrypted data */
    for (i = 3; i >= 0; i--) {
      _out[i] = __REV(AES->DATA) ^ _in[i];
    }
    _out += 4;
    _in  += 4;
  }
}

#if defined(AES_CTRL_AES256)
/***************************************************************************//**
 * @brief
 *   Cipher feedback (CFB) cipher mode encryption/decryption, 256 bit key.
 *
 * @details
 *   Please see AES_CFB128() for CFB figure.
 *
 *   Please refer to general comments on layout and byte ordering of parameters.
 *
 * @param[out] out
 *   Buffer to place encrypted/decrypted data. Must be at least @p len long. It
 *   may be set equal to @p in, in which case the input buffer is overwritten.
 *
 * @param[in] in
 *   Buffer holding data to encrypt/decrypt. Must be at least @p len long.
 *
 * @param[in] len
 *   Number of bytes to encrypt/decrypt. Must be a multiple of 16.
 *
 * @param[in] key
 *   256 bit encryption key is used for both encryption and decryption modes.
 *
 * @param[in] iv
 *   128 bit initalization vector to use.
 *
 * @param[in] encrypt
 *   Set to true to encrypt, false to decrypt.
 ******************************************************************************/
void AES_CFB256(uint8_t *out,
                const uint8_t *in,
                unsigned int len,
                const uint8_t *key,
                const uint8_t *iv,
                bool encrypt)
{
  int            i;
  int            j;
  uint32_t       *_out = (uint32_t *)out;
  const uint32_t *_in  = (const uint32_t *)in;
  const uint32_t *_key = (const uint32_t *)key;
  const uint32_t *_iv  = (const uint32_t *)iv;
  const uint32_t *data;
  uint32_t       tmp[4];

  EFM_ASSERT(!(len % AES_BLOCKSIZE));

  /* Select encryption mode */
  AES->CTRL = AES_CTRL_AES256 | AES_CTRL_DATASTART;

  /* Encrypt/decrypt data */
  data = _iv;
  len /= AES_BLOCKSIZE;
  while (len--) {
    /* Load key and block to be encrypted/decrypted */
    for (i = 3, j = 7; i >= 0; i--, j--) {
      AES->KEYLA = __REV(_key[j]);
      AES->KEYHA = __REV(_key[i]);
      /* Write data last, since will trigger encryption on last iteration */
      AES->DATA = __REV(data[i]);
    }

    /* Do some required processing before waiting for completion */
    if (encrypt) {
      data = _out;
    } else {
      /* Must copy current ciphertext block since it may be overwritten */
      for (i = 0; i < 4; i++) {
        tmp[i] = _in[i];
      }
      data = tmp;
    }

    while (AES->STATUS & AES_STATUS_RUNNING)
      ;

    /* Save encrypted/decrypted data */
    for (i = 3; i >= 0; i--) {
      _out[i] = __REV(AES->DATA) ^ _in[i];
    }
    _out += 4;
    _in  += 4;
  }
}
#endif

/***************************************************************************//**
 * @brief
 *   Counter (CTR) cipher mode encryption/decryption, 128 bit key.
 *
 * @details
 *   Encryption:
 * @verbatim
 *           Counter                    Counter
 *              |                          |
 *              V                          V
 *       +--------------+           +--------------+
 * Key ->| Block cipher |     Key ->| Block cipher |
 *       |  encryption  |           |  encryption  |
 *       +--------------+           +--------------+
 *              |                          |
 * Plaintext ->XOR            Plaintext ->XOR
 *              |                          |
 *              V                          V
 *         Ciphertext                 Ciphertext
 * @endverbatim
 *   Decryption:
 * @verbatim
 *           Counter                    Counter
 *              |                          |
 *              V                          V
 *       +--------------+           +--------------+
 * Key ->| Block cipher |     Key ->| Block cipher |
 *       |  encryption  |           |  encryption  |
 *       +--------------+           +--------------+
 *               |                          |
 * Ciphertext ->XOR           Ciphertext ->XOR
 *               |                          |
 *               V                          V
 *           Plaintext                  Plaintext
 * @endverbatim
 *   Please refer to general comments on layout and byte ordering of parameters.
 *
 * @param[out] out
 *   Buffer to place encrypted/decrypted data. Must be at least @p len long. It
 *   may be set equal to @p in, in which case the input buffer is overwritten.
 *
 * @param[in] in
 *   Buffer holding data to encrypt/decrypt. Must be at least @p len long.
 *
 * @param[in] len
 *   Number of bytes to encrypt/decrypt. Must be a multiple of 16.
 *
 * @param[in] key
 *   128 bit encryption key.
 *   On devices supporting key buffering this argument can be null, if so, the
 *   key will not be loaded, as it is assumed the key has been loaded
 *   into KEYHA previously.
 *
 * @param[in,out] ctr
 *   128 bit initial counter value. The counter is updated after each AES
 *   block encoding through use of @p ctrFunc.
 *
 * @param[in] ctrFunc
 *   Function used to update counter value.
 ******************************************************************************/
void AES_CTR128(uint8_t *out,
                const uint8_t *in,
                unsigned int len,
                const uint8_t *key,
                uint8_t *ctr,
                AES_CtrFuncPtr_TypeDef ctrFunc)
{
  int            i;
  uint32_t       *_out = (uint32_t *)out;
  const uint32_t *_in  = (const uint32_t *)in;
  const uint32_t *_key = (const uint32_t *)key;
  uint32_t       *_ctr = (uint32_t *)ctr;

  EFM_ASSERT(!(len % AES_BLOCKSIZE));
  EFM_ASSERT(ctrFunc);

  #if defined(AES_CTRL_KEYBUFEN)
  AES->CTRL = AES_CTRL_KEYBUFEN | AES_CTRL_DATASTART;
  #else
  AES->CTRL = AES_CTRL_DATASTART;
  #endif

  #if defined(AES_CTRL_KEYBUFEN)
  if (key) {
    /* Load key into high key for key buffer usage */
    for (i = 3; i >= 0; i--) {
      AES->KEYHA = __REV(_key[i]);
    }
  }
  #endif

  /* Encrypt/decrypt data */
  len /= AES_BLOCKSIZE;
  while (len--) {
    #if !defined(AES_CTRL_KEYBUFEN)
    /* Load key */
    for (i = 3; i >= 0; i--) {
      AES->KEYLA = __REV(_key[i]);
    }
    #endif

    /* Load ctr to be encrypted/decrypted */
    for (i = 3; i >= 0; i--) {
      AES->DATA = __REV(_ctr[i]);
    }
    /* Increment ctr for next use */
    ctrFunc(ctr);

    /* Wait for completion */
    while (AES->STATUS & AES_STATUS_RUNNING)
      ;

    /* Save encrypted/decrypted data */
    for (i = 3; i >= 0; i--) {
      _out[i] = __REV(AES->DATA) ^ _in[i];
    }
    _out += 4;
    _in  += 4;
  }
}

#if defined(AES_CTRL_AES256)
/***************************************************************************//**
 * @brief
 *   Counter (CTR) cipher mode encryption/decryption, 256 bit key.
 *
 * @details
 *   Please see AES_CTR128() for CTR figure.
 *
 *   Please refer to general comments on layout and byte ordering of parameters.
 *
 * @param[out] out
 *   Buffer to place encrypted/decrypted data. Must be at least @p len long. It
 *   may be set equal to @p in, in which case the input buffer is overwritten.
 *
 * @param[in] in
 *   Buffer holding data to encrypt/decrypt. Must be at least @p len long.
 *
 * @param[in] len
 *   Number of bytes to encrypt/decrypt. Must be a multiple of 16.
 *
 * @param[in] key
 *   256 bit encryption key.
 *
 * @param[in,out] ctr
 *   128 bit initial counter value. The counter is updated after each AES
 *   block encoding through use of @p ctrFunc.
 *
 * @param[in] ctrFunc
 *   Function used to update counter value.
 ******************************************************************************/
void AES_CTR256(uint8_t *out,
                const uint8_t *in,
                unsigned int len,
                const uint8_t *key,
                uint8_t *ctr,
                AES_CtrFuncPtr_TypeDef ctrFunc)
{
  int            i;
  int            j;
  uint32_t       *_out = (uint32_t *)out;
  const uint32_t *_in  = (const uint32_t *)in;
  const uint32_t *_key = (const uint32_t *)key;
  uint32_t       *_ctr = (uint32_t *)ctr;

  EFM_ASSERT(!(len % AES_BLOCKSIZE));
  EFM_ASSERT(ctrFunc);

  /* Select encryption mode, with auto trigger */
  AES->CTRL = AES_CTRL_AES256 | AES_CTRL_DATASTART;

  /* Encrypt/decrypt data */
  len /= AES_BLOCKSIZE;
  while (len--) {
    /* Load key and block to be encrypted/decrypted */
    for (i = 3, j = 7; i >= 0; i--, j--) {
      AES->KEYLA = __REV(_key[j]);
      AES->KEYHA = __REV(_key[i]);
      /* Write data last, since will trigger encryption on last iteration */
      AES->DATA = __REV(_ctr[i]);
    }
    /* Increment ctr for next use */
    ctrFunc(ctr);

    /* Wait for completion */
    while (AES->STATUS & AES_STATUS_RUNNING)
      ;

    /* Save encrypted/decrypted data */
    for (i = 3; i >= 0; i--) {
      _out[i] = __REV(AES->DATA) ^ _in[i];
    }
    _out += 4;
    _in  += 4;
  }
}
#endif

/***************************************************************************//**
 * @brief
 *   Update last 32 bits of 128 bit counter, by incrementing with 1.
 *
 * @details
 *   Notice that no special consideration is given to possible wrap around. If
 *   32 least significant bits are 0xFFFFFFFF, they will be updated to 0x00000000,
 *   ignoring overflow.
 *
 *   Please refer to general comments on layout and byte ordering of parameters.
 *
 * @param[in,out] ctr
 *   Buffer holding 128 bit counter to be updated.
 ******************************************************************************/
void AES_CTRUpdate32Bit(uint8_t *ctr)
{
  uint32_t *_ctr = (uint32_t *)ctr;

  _ctr[3] = __REV(__REV(_ctr[3]) + 1);
}

/***************************************************************************//**
 * @brief
 *   Generate 128 bit decryption key from 128 bit encryption key. The decryption
 *   key is used for some cipher modes when decrypting.
 *
 * @details
 *   Please refer to general comments on layout and byte ordering of parameters.
 *
 * @param[out] out
 *   Buffer to place 128 bit decryption key. Must be at least 16 bytes long. It
 *   may be set equal to @p in, in which case the input buffer is overwritten.
 *
 * @param[in] in
 *   Buffer holding 128 bit encryption key. Must be at least 16 bytes long.
 ******************************************************************************/
void AES_DecryptKey128(uint8_t *out, const uint8_t *in)
{
  int            i;
  uint32_t       *_out = (uint32_t *)out;
  const uint32_t *_in  = (const uint32_t *)in;

  /* Load key */
  for (i = 3; i >= 0; i--) {
    AES->KEYLA = __REV(_in[i]);
  }

  /* Do dummy encryption to generate decrypt key */
  AES->CTRL = 0;
  AES_IntClear(AES_IF_DONE);
  AES->CMD = AES_CMD_START;

  /* Wait for completion */
  while (AES->STATUS & AES_STATUS_RUNNING)
    ;

  /* Save decryption key */
  for (i = 3; i >= 0; i--) {
    _out[i] = __REV(AES->KEYLA);
  }
}

#if defined(AES_CTRL_AES256)
/***************************************************************************//**
 * @brief
 *   Generate 256 bit decryption key from 256 bit encryption key. The decryption
 *   key is used for some cipher modes when decrypting.
 *
 * @details
 *   Please refer to general comments on layout and byte ordering of parameters.
 *
 * @param[out] out
 *   Buffer to place 256 bit decryption key. Must be at least 32 bytes long. It
 *   may be set equal to @p in, in which case the input buffer is overwritten.
 *
 * @param[in] in
 *   Buffer holding 256 bit encryption key. Must be at least 32 bytes long.
 ******************************************************************************/
void AES_DecryptKey256(uint8_t *out, const uint8_t *in)
{
  int            i;
  int            j;
  uint32_t       *_out = (uint32_t *)out;
  const uint32_t *_in  = (const uint32_t *)in;

  /* Load key */
  for (i = 3, j = 7; i >= 0; i--, j--) {
    AES->KEYLA = __REV(_in[j]);
    AES->KEYHA = __REV(_in[i]);
  }

  /* Do dummy encryption to generate decrypt key */
  AES->CTRL = AES_CTRL_AES256;
  AES->CMD  = AES_CMD_START;

  /* Wait for completion */
  while (AES->STATUS & AES_STATUS_RUNNING)
    ;

  /* Save decryption key */
  for (i = 3, j = 7; i >= 0; i--, j--) {
    _out[j] = __REV(AES->KEYLA);
    _out[i] = __REV(AES->KEYHA);
  }
}
#endif

/***************************************************************************//**
 * @brief
 *   Electronic Codebook (ECB) cipher mode encryption/decryption, 128 bit key.
 *
 * @details
 *   Encryption:
 * @verbatim
 *          Plaintext                  Plaintext
 *              |                          |
 *              V                          V
 *       +--------------+           +--------------+
 * Key ->| Block cipher |     Key ->| Block cipher |
 *       |  encryption  |           |  encryption  |
 *       +--------------+           +--------------+
 *              |                          |
 *              V                          V
 *         Ciphertext                 Ciphertext
 * @endverbatim
 *   Decryption:
 * @verbatim
 *         Ciphertext                 Ciphertext
 *              |                          |
 *              V                          V
 *       +--------------+           +--------------+
 * Key ->| Block cipher |     Key ->| Block cipher |
 *       |  decryption  |           |  decryption  |
 *       +--------------+           +--------------+
 *              |                          |
 *              V                          V
 *          Plaintext                  Plaintext
 * @endverbatim
 *   Please refer to general comments on layout and byte ordering of parameters.
 *
 * @param[out] out
 *   Buffer to place encrypted/decrypted data. Must be at least @p len long. It
 *   may be set equal to @p in, in which case the input buffer is overwritten.
 *
 * @param[in] in
 *   Buffer holding data to encrypt/decrypt. Must be at least @p len long.
 *
 * @param[in] len
 *   Number of bytes to encrypt/decrypt. Must be a multiple of 16.
 *
 * @param[in] key
 *   When doing encryption, this is the 128 bit encryption key. When doing
 *   decryption, this is the 128 bit decryption key. The decryption key may
 *   be generated from the encryption key with AES_DecryptKey128().
 *
 * @param[in] encrypt
 *   Set to true to encrypt, false to decrypt.
 ******************************************************************************/
void AES_ECB128(uint8_t *out,
                const uint8_t *in,
                unsigned int len,
                const uint8_t *key,
                bool encrypt)
{
  int            i;
  uint32_t       *_out = (uint32_t *)out;
  const uint32_t *_in  = (const uint32_t *)in;
  const uint32_t *_key = (const uint32_t *)key;

  EFM_ASSERT(!(len % AES_BLOCKSIZE));

  #if defined(AES_CTRL_KEYBUFEN)
  /* Load key into high key for key buffer usage */
  for (i = 3; i >= 0; i--) {
    AES->KEYHA = __REV(_key[i]);
  }
  #endif

  if (encrypt) {
    /* Select encryption mode */
    #if defined(AES_CTRL_KEYBUFEN)
    AES->CTRL = AES_CTRL_KEYBUFEN | AES_CTRL_DATASTART;
    #else
    AES->CTRL = AES_CTRL_DATASTART;
    #endif
  } else {
    /* Select decryption mode */
    #if defined(AES_CTRL_KEYBUFEN)
    AES->CTRL = AES_CTRL_DECRYPT | AES_CTRL_KEYBUFEN | AES_CTRL_DATASTART;
    #else
    AES->CTRL = AES_CTRL_DECRYPT | AES_CTRL_DATASTART;
    #endif
  }

  /* Encrypt/decrypt data */
  len /= AES_BLOCKSIZE;
  while (len--) {
    #if !defined(AES_CTRL_KEYBUFEN)
    /* Load key */
    for (i = 3; i >= 0; i--) {
      AES->KEYLA = __REV(_key[i]);
    }
    #endif

    /* Load block to be encrypted/decrypted */
    for (i = 3; i >= 0; i--) {
      AES->DATA = __REV(_in[i]);
    }
    _in += 4;

    /* Wait for completion */
    while (AES->STATUS & AES_STATUS_RUNNING)
      ;

    /* Save encrypted/decrypted data */
    for (i = 3; i >= 0; i--) {
      _out[i] = __REV(AES->DATA);
    }
    _out += 4;
  }
}

#if defined(AES_CTRL_AES256)
/***************************************************************************//**
 * @brief
 *   Electronic Codebook (ECB) cipher mode encryption/decryption, 256 bit key.
 *
 * @details
 *   Please see AES_ECB128() for ECB figure.
 *
 *   Please refer to general comments on layout and byte ordering of parameters.
 *
 * @param[out] out
 *   Buffer to place encrypted/decrypted data. Must be at least @p len long. It
 *   may be set equal to @p in, in which case the input buffer is overwritten.
 *
 * @param[in] in
 *   Buffer holding data to encrypt/decrypt. Must be at least @p len long.
 *
 * @param[in] len
 *   Number of bytes to encrypt/decrypt. Must be a multiple of 16.
 *
 * @param[in] key
 *   When doing encryption, this is the 256 bit encryption key. When doing
 *   decryption, this is the 256 bit decryption key. The decryption key may
 *   be generated from the encryption key with AES_DecryptKey256().
 *
 * @param[in] encrypt
 *   Set to true to encrypt, false to decrypt.
 ******************************************************************************/
void AES_ECB256(uint8_t *out,
                const uint8_t *in,
                unsigned int len,
                const uint8_t *key,
                bool encrypt)
{
  int            i;
  int            j;
  uint32_t       *_out = (uint32_t *)out;
  const uint32_t *_in  = (const uint32_t *)in;
  const uint32_t *_key = (const uint32_t *)key;

  EFM_ASSERT(!(len % AES_BLOCKSIZE));

  if (encrypt) {
    /* Select encryption mode */
    AES->CTRL = AES_CTRL_AES256 | AES_CTRL_DATASTART;
  } else {
    /* Select decryption mode */
    AES->CTRL = AES_CTRL_DECRYPT | AES_CTRL_AES256 | AES_CTRL_DATASTART;
  }

  /* Encrypt/decrypt data */
  len /= AES_BLOCKSIZE;
  while (len--) {
    /* Load key and block to be encrypted/decrypted */
    for (i = 3, j = 7; i >= 0; i--, j--) {
      AES->KEYLA = __REV(_key[j]);
      AES->KEYHA = __REV(_key[i]);
      /* Write data last, since will trigger encryption on last iteration */
      AES->DATA = __REV(_in[i]);
    }
    _in += 4;

    /* Wait for completion */
    while (AES->STATUS & AES_STATUS_RUNNING)
      ;

    /* Save encrypted/decrypted data */
    for (i = 3; i >= 0; i--) {
      _out[i] = __REV(AES->DATA);
    }
    _out += 4;
  }
}
#endif

/***************************************************************************//**
 * @brief
 *   Output feedback (OFB) cipher mode encryption/decryption, 128 bit key.
 *
 * @details
 *   Encryption:
 * @verbatim
 *          InitVector    +----------------+
 *              |         |                |
 *              V         |                V
 *       +--------------+ |        +--------------+
 * Key ->| Block cipher | |  Key ->| Block cipher |
 *       |  encryption  | |        |  encryption  |
 *       +--------------+ |        +--------------+
 *              |         |                |
 *              |---------+                |
 *              V                          V
 * Plaintext ->XOR            Plaintext ->XOR
 *              |                          |
 *              V                          V
 *         Ciphertext                 Ciphertext
 * @endverbatim
 *   Decryption:
 * @verbatim
 *          InitVector    +----------------+
 *              |         |                |
 *              V         |                V
 *       +--------------+ |        +--------------+
 * Key ->| Block cipher | |  Key ->| Block cipher |
 *       |  encryption  | |        |  encryption  |
 *       +--------------+ |        +--------------+
 *              |         |                |
 *              |---------+                |
 *              V                          V
 * Ciphertext ->XOR           Ciphertext ->XOR
 *              |                          |
 *              V                          V
 *          Plaintext                  Plaintext
 * @endverbatim
 *   Please refer to general comments on layout and byte ordering of parameters.
 *
 * @param[out] out
 *   Buffer to place encrypted/decrypted data. Must be at least @p len long. It
 *   may be set equal to @p in, in which case the input buffer is overwritten.
 *
 * @param[in] in
 *   Buffer holding data to encrypt/decrypt. Must be at least @p len long.
 *
 * @param[in] len
 *   Number of bytes to encrypt/decrypt. Must be a multiple of 16.
 *
 * @param[in] key
 *   128 bit encryption key.
 *
 * @param[in] iv
 *   128 bit initalization vector to use.
 ******************************************************************************/
void AES_OFB128(uint8_t *out,
                const uint8_t *in,
                unsigned int len,
                const uint8_t *key,
                const uint8_t *iv)
{
  int            i;
  uint32_t       *_out = (uint32_t *)out;
  const uint32_t *_in  = (const uint32_t *)in;
  const uint32_t *_key = (const uint32_t *)key;
  const uint32_t *_iv  = (const uint32_t *)iv;

  EFM_ASSERT(!(len % AES_BLOCKSIZE));

  /* Select encryption mode, trigger explicitly by command */
  #if defined(AES_CTRL_KEYBUFEN)
  AES->CTRL = AES_CTRL_KEYBUFEN;
  #else
  AES->CTRL = 0;
  #endif

  /* Load key into high key for key buffer usage */
  /* Load initialization vector */
  for (i = 3; i >= 0; i--) {
    #if defined(AES_CTRL_KEYBUFEN)
    AES->KEYHA = __REV(_key[i]);
    #endif
    AES->DATA  = __REV(_iv[i]);
  }

  /* Encrypt/decrypt data */
  len /= AES_BLOCKSIZE;
  while (len--) {
    #if !defined(AES_CTRL_KEYBUFEN)
    /* Load key */
    for (i = 3; i >= 0; i--) {
      AES->KEYLA = __REV(_key[i]);
    }
    #endif

    AES->CMD = AES_CMD_START;

    /* Wait for completion */
    while (AES->STATUS & AES_STATUS_RUNNING)
      ;

    /* Save encrypted/decrypted data */
    for (i = 3; i >= 0; i--) {
      _out[i] = __REV(AES->DATA) ^ _in[i];
    }
    _out += 4;
    _in  += 4;
  }
}

#if defined(AES_CTRL_AES256)
/***************************************************************************//**
 * @brief
 *   Output feedback (OFB) cipher mode encryption/decryption, 256 bit key.
 *
 * @details
 *   Please see AES_OFB128() for OFB figure.
 *
 *   Please refer to general comments on layout and byte ordering of parameters.
 *
 * @param[out] out
 *   Buffer to place encrypted/decrypted data. Must be at least @p len long. It
 *   may be set equal to @p in, in which case the input buffer is overwritten.
 *
 * @param[in] in
 *   Buffer holding data to encrypt/decrypt. Must be at least @p len long.
 *
 * @param[in] len
 *   Number of bytes to encrypt/decrypt. Must be a multiple of 16.
 *
 * @param[in] key
 *   256 bit encryption key.
 *
 * @param[in] iv
 *   128 bit initalization vector to use.
 ******************************************************************************/
void AES_OFB256(uint8_t *out,
                const uint8_t *in,
                unsigned int len,
                const uint8_t *key,
                const uint8_t *iv)
{
  int            i;
  int            j;
  uint32_t       *_out = (uint32_t *)out;
  const uint32_t *_in  = (const uint32_t *)in;
  const uint32_t *_key = (const uint32_t *)key;
  const uint32_t *_iv  = (const uint32_t *)iv;

  EFM_ASSERT(!(len % AES_BLOCKSIZE));

  /* Select encryption mode, trigger explicitly by command */
  AES->CTRL = AES_CTRL_AES256;

  /* Load initialization vector */
  for (i = 3; i >= 0; i--) {
    AES->DATA = __REV(_iv[i]);
  }

  /* Encrypt/decrypt data */
  len /= AES_BLOCKSIZE;
  while (len--) {
    /* Load key */
    for (i = 3, j = 7; i >= 0; i--, j--) {
      AES->KEYLA = __REV(_key[j]);
      AES->KEYHA = __REV(_key[i]);
    }

    AES->CMD = AES_CMD_START;

    /* Wait for completion */
    while (AES->STATUS & AES_STATUS_RUNNING)
      ;

    /* Save encrypted/decrypted data */
    for (i = 3; i >= 0; i--) {
      _out[i] = __REV(AES->DATA) ^ _in[i];
    }
    _out += 4;
    _in  += 4;
  }
}
#endif

/** @} (end addtogroup AES) */
/** @} (end addtogroup emlib) */
#endif /* defined(AES_COUNT) && (AES_COUNT > 0) */