text:
package org.apache.calcite.sql;

import org.apache.calcite.avatica.util.TimeUnitRange;
import org.apache.calcite.rel.metadata.NullSentinel;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rel.type.RelDataTypeFactory;
import org.apache.calcite.sql.fun.SqlLiteralChainOperator;
import org.apache.calcite.sql.fun.SqlStdOperatorTable;
import org.apache.calcite.sql.parser.SqlParserPos;
import org.apache.calcite.sql.parser.SqlParserUtil;
import org.apache.calcite.sql.type.SqlTypeFamily;
import org.apache.calcite.sql.type.SqlTypeName;
import org.apache.calcite.sql.type.SqlTypeUtil;
import org.apache.calcite.sql.util.SqlVisitor;
import org.apache.calcite.sql.validate.SqlMonotonicity;
import org.apache.calcite.sql.validate.SqlValidator;
import org.apache.calcite.sql.validate.SqlValidatorScope;
import org.apache.calcite.util.BitString;
import org.apache.calcite.util.DateString;
import org.apache.calcite.util.Litmus;
import org.apache.calcite.util.NlsString;
import org.apache.calcite.util.TimeString;
import org.apache.calcite.util.TimestampString;
import org.apache.calcite.util.Util;

import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.util.Calendar;
import java.util.Objects;
import javax.annotation.Nonnull;

import static org.apache.calcite.util.Static.RESOURCE;

/**
 * A SqlLiteral is a constant. It is, appropriately, immutable.
 *
 *
How is the value stored? In that respect, the class is somewhat of a black
 * box. There is a {@link #getValue} method which returns the value as an
 * object, but the type of that value is implementation detail, and it is best
 * that your code does not depend upon that knowledge. It is better to use
 * task-oriented methods such as {@link #toSqlString(SqlDialect)} and
 * {@link #toValue}.

 *
 *
If you really need to access the value directly, you should switch on the
 * value of the {@link #typeName} field, rather than making assumptions about
 * the runtime type of the {@link #value}.

 *
 *
The allowable types and combinations are:
 *
 *

 *
Allowable types for SqlLiteral

 *

 * TypeName
 * Meaing
 * Value type
 *

 *

 * {@link SqlTypeName#NULL}
 * The null value. It has its own special type.
 * null
 *

 *

 * {@link SqlTypeName#BOOLEAN}
 * Boolean, namely TRUE, FALSE or
 * UNKNOWN.
 * {@link Boolean}, or null represents the UNKNOWN value
 *

 *

 * {@link SqlTypeName#DECIMAL}
 * Exact number, for example 0, -.5,
 * 12345.
 * {@link BigDecimal}
 *

 *

 * {@link SqlTypeName#DOUBLE}
 * Approximate number, for example 6.023E-23.
 * {@link BigDecimal}
 *

 *

 * {@link SqlTypeName#DATE}
 * Date, for example DATE '1969-04'29'
 * {@link Calendar}
 *

 *

 * {@link SqlTypeName#TIME}
 * Time, for example TIME '18:37:42.567'
 * {@link Calendar}
 *

 *

 * {@link SqlTypeName#TIMESTAMP}
 * Timestamp, for example TIMESTAMP '1969-04-29
 * 18:37:42.567'
 * {@link Calendar}
 *

 *

 * {@link SqlTypeName#CHAR}
 * Character constant, for example 'Hello, world!',
 * '', _N'Bonjour', _ISO-8859-1'It''s superman!'
 * COLLATE SHIFT_JIS$ja_JP$2. These are always CHAR, never VARCHAR.
 * {@link NlsString}
 *

 *

 * {@link SqlTypeName#BINARY}
 * Binary constant, for example X'ABC', X'7F'.
 * Note that strings with an odd number of hexits will later become values of
 * the BIT datatype, because they have an incomplete number of bytes. But here,
 * they are all binary constants, because that's how they were written. These
 * constants are always BINARY, never VARBINARY.
 * {@link BitString}
 *

 *

 * {@link SqlTypeName#SYMBOL}
 * A symbol is a special type used to make parsing easier; it is not part of
 * the SQL standard, and is not exposed to end-users. It is used to hold a
 * symbol, such as the LEADING flag in a call to the function
 * TRIM([LEADING|TRAILING|BOTH] chars FROM string).
 * An {@link Enum}
 *

 *

 * {@link SqlTypeName#INTERVAL_YEAR}
 *     .. {@link SqlTypeName#INTERVAL_SECOND}
 * Interval, for example INTERVAL '1:34' HOUR.
 * {@link SqlIntervalLiteral.IntervalValue}.
 *

 *

 */
public class SqlLiteral extends SqlNode {
  //~ Instance fields --------------------------------------------------------

  /**
   * The type with which this literal was declared. This type is very
   * approximate: the literal may have a different type once validated. For
   * example, all numeric literals have a type name of
   * {@link SqlTypeName#DECIMAL}, but on validation may become
   * {@link SqlTypeName#INTEGER}.
   */
  private final SqlTypeName typeName;

  /**
   * The value of this literal. The type of the value must be appropriate for
   * the typeName, as defined by the {@link #valueMatchesType} method.
   */
  protected final Object value;

  //~ Constructors -----------------------------------------------------------

  /**
   * Creates a SqlLiteral.
   */
  protected SqlLiteral(
      Object value,
      SqlTypeName typeName,
      SqlParserPos pos) {
    super(pos);
    this.value = value;
    this.typeName = typeName;
    assert typeName != null;
    assert valueMatchesType(value, typeName);
  }

  //~ Methods ----------------------------------------------------------------

  /** Returns the value of {@link #typeName}. */
  public SqlTypeName getTypeName() {
    return typeName;
  }

  /** Returns whether value is appropriate for its type. (We have rules about
   * these things!) */
  public static boolean valueMatchesType(
      Object value,
      SqlTypeName typeName) {
    switch (typeName) {
    case BOOLEAN:
      return (value == null) || (value instanceof Boolean);
    case NULL:
      return value == null;
    case DECIMAL:
    case DOUBLE:
      return value instanceof BigDecimal;
    case DATE:
      return value instanceof DateString;
    case TIME:
      return value instanceof TimeString;
    case TIMESTAMP:
      return value instanceof TimestampString;
    case INTERVAL_YEAR:
    case INTERVAL_YEAR_MONTH:
    case INTERVAL_MONTH:
    case INTERVAL_DAY:
    case INTERVAL_DAY_HOUR:
    case INTERVAL_DAY_MINUTE:
    case INTERVAL_DAY_SECOND:
    case INTERVAL_HOUR:
    case INTERVAL_HOUR_MINUTE:
    case INTERVAL_HOUR_SECOND:
    case INTERVAL_MINUTE:
    case INTERVAL_MINUTE_SECOND:
    case INTERVAL_SECOND:
      return value instanceof SqlIntervalLiteral.IntervalValue;
    case BINARY:
      return value instanceof BitString;
    case CHAR:
      return value instanceof NlsString;
    case SYMBOL:
      return (value instanceof Enum)
          || (value instanceof SqlSampleSpec);
    case MULTISET:
      return true;
    case INTEGER: // not allowed -- use Decimal
    case VARCHAR: // not allowed -- use Char
    case VARBINARY: // not allowed -- use Binary
    default:
      throw Util.unexpected(typeName);
    }
  }

  public SqlLiteral clone(SqlParserPos pos) {
    return new SqlLiteral(value, typeName, pos);
  }

  public @Nonnull SqlKind getKind() {
    return SqlKind.LITERAL;
  }

  /**
   * Returns the value of this literal.
   *
   *
Try not to use this method! There are so many different kinds of
   * values, it's better to to let SqlLiteral do whatever it is you want to
   * do.
   *
   * @see #booleanValue()
   * @see #symbolValue(Class)
   */
  public Object getValue() {
    return value;
  }

  /**
   * Returns the value of this literal as a given Java type.
   *
   *
Which type you may ask for depends on {@link #typeName}.
   * You may always ask for the type where we store the value internally
   * (as defined by {@link #valueMatchesType(Object, SqlTypeName)}), but may
   * ask for other convenient types.
   *
   *
For example, numeric literals' values are stored internally as
   * {@link BigDecimal}, but other numeric types such as {@link Long} and
   * {@link Double} are also allowed.
   *
   *
The result is never null. For the NULL literal, returns
   * a {@link NullSentinel#INSTANCE}.
   *
   * @param clazz Desired value type
   * @param <T> Value type
   * @return Value of the literal in desired type, never null
   *
   * @throws AssertionError if the value type is not supported
   */
  @Nonnull public <T> T getValueAs(Class<T> clazz) {
    if (clazz.isInstance(value)) {
      return clazz.cast(value);
    }
    switch (typeName) {
    case NULL:
      return clazz.cast(NullSentinel.INSTANCE);
    case CHAR:
      if (clazz == String.class) {
        return clazz.cast(((NlsString) value).getValue());
      }
      break;
    case BINARY:
      if (clazz == byte[].class) {
        return clazz.cast(((BitString) value).getAsByteArray());
      }
      break;
    case DECIMAL:
      if (clazz == Long.class) {
        return clazz.cast(((BigDecimal) value).unscaledValue().longValue());
      }
      // fall through
    case BIGINT:
    case INTEGER:
    case SMALLINT:
    case TINYINT:
    case DOUBLE:
    case REAL:
    case FLOAT:
      if (clazz == Long.class) {
        return clazz.cast(((BigDecimal) value).longValue());
      } else if (clazz == Integer.class) {
        return clazz.cast(((BigDecimal) value).intValue());
      } else if (clazz == Short.class) {
        return clazz.cast(((BigDecimal) value).shortValue());
      } else if (clazz == Byte.class) {
        return clazz.cast(((BigDecimal) value).byteValue());
      } else if (clazz == Double.class) {
        return clazz.cast(((BigDecimal) value).doubleValue());
      } else if (clazz == Float.class) {
        return clazz.cast(((BigDecimal) value).floatValue());
      }
      break;
    case DATE:
      if (clazz == Calendar.class) {
        return clazz.cast(((DateString) value).toCalendar());
      }
      break;
    case TIME:
      if (clazz == Calendar.class) {
        return clazz.cast(((TimeString) value).toCalendar());
      }
      break;
    case TIMESTAMP:
      if (clazz == Calendar.class) {
        return clazz.cast(((TimestampString) value).toCalendar());
      }
      break;
    case INTERVAL_YEAR:
    case INTERVAL_YEAR_MONTH:
    case INTERVAL_MONTH:
      final SqlIntervalLiteral.IntervalValue valMonth =
          (SqlIntervalLiteral.IntervalValue) value;
      if (clazz == Long.class) {
        return clazz.cast(valMonth.getSign()
            * SqlParserUtil.intervalToMonths(valMonth));
      } else if (clazz == BigDecimal.class) {
        return clazz.cast(BigDecimal.valueOf(getValueAs(Long.class)));
      } else if (clazz == TimeUnitRange.class) {
        return clazz.cast(valMonth.getIntervalQualifier().timeUnitRange);
      } else if (clazz == SqlIntervalQualifier.class) {
        return clazz.cast(valMonth.getIntervalQualifier());
      }
      break;
    case INTERVAL_DAY:
    case INTERVAL_DAY_HOUR:
    case INTERVAL_DAY_MINUTE:
    case INTERVAL_DAY_SECOND:
    case INTERVAL_HOUR:
    case INTERVAL_HOUR_MINUTE:
    case INTERVAL_HOUR_SECOND:
    case INTERVAL_MINUTE:
    case INTERVAL_MINUTE_SECOND:
    case INTERVAL_SECOND:
      final SqlIntervalLiteral.IntervalValue valTime =
          (SqlIntervalLiteral.IntervalValue) value;
      if (clazz == Long.class) {
        return clazz.cast(valTime.getSign()
            * SqlParserUtil.intervalToMillis(valTime));
      } else if (clazz == BigDecimal.class) {
        return clazz.cast(BigDecimal.valueOf(getValueAs(Long.class)));
      } else if (clazz == TimeUnitRange.class) {
        return clazz.cast(valTime.getIntervalQualifier().timeUnitRange);
      } else if (clazz == SqlIntervalQualifier.class) {
        return clazz.cast(valTime.getIntervalQualifier());
      }
      break;
    }
    throw new AssertionError("cannot cast " + value + " as " + clazz);
  }

  /** Returns the value as a symbol. */
  @Deprecated // to be removed before 2.0
  public <E extends Enum<E>> E symbolValue_() {
    //noinspection unchecked
    return (E) value;
  }

  /** Returns the value as a symbol. */
  public <E extends Enum<E>> E symbolValue(Class<E> class_) {
    return class_.cast(value);
  }

  /** Returns the value as a boolean. */
  public boolean booleanValue() {
    return (Boolean) value;
  }

  /**
   * Extracts the {@link SqlSampleSpec} value from a symbol literal.
   *
   * @throws ClassCastException if the value is not a symbol literal
   * @see #createSymbol(Enum, SqlParserPos)
   */
  public static SqlSampleSpec sampleValue(SqlNode node) {
    return (SqlSampleSpec) ((SqlLiteral) node).value;
  }

  /**
   * Extracts the value from a literal.
   *
   *
Cases:
   *

   *
If the node is a character literal, a chain of string
   * literals, or a CAST of a character literal, returns the value as a
   * {@link NlsString}.
   *
   *
If the node is a numeric literal, or a negated numeric literal,
   * returns the value as a {@link BigDecimal}.
   *
   *
If the node is a {@link SqlIntervalQualifier},
   * returns its {@link TimeUnitRange}.
   *
   *
If the node is INTERVAL_DAY_TIME_ in {@link SqlTypeFamily},
   * returns its sign multiplied by its millisecond equivalent value
   *
   *
If the node is INTERVAL_YEAR_MONTH_ in {@link SqlTypeFamily},
   * returns its sign multiplied by its months equivalent value
   *
   *
Otherwise throws {@link IllegalArgumentException}.
   *

   */
  public static Comparable value(SqlNode node)
      throws IllegalArgumentException {
    if (node instanceof SqlLiteral) {
      final SqlLiteral literal = (SqlLiteral) node;
      if (literal.getTypeName() == SqlTypeName.SYMBOL) {
        return (Enum) literal.value;
      }
      switch (literal.getTypeName().getFamily()) {
      case CHARACTER:
        return (NlsString) literal.value;
      case NUMERIC:
        return (BigDecimal) literal.value;
      case INTERVAL_YEAR_MONTH:
        final SqlIntervalLiteral.IntervalValue valMonth =
            (SqlIntervalLiteral.IntervalValue) literal.value;
        return valMonth.getSign() * SqlParserUtil.intervalToMonths(valMonth);
      case INTERVAL_DAY_TIME:
        final SqlIntervalLiteral.IntervalValue valTime =
            (SqlIntervalLiteral.IntervalValue) literal.value;
        return valTime.getSign() * SqlParserUtil.intervalToMillis(valTime);
      }
    }
    if (SqlUtil.isLiteralChain(node)) {
      assert node instanceof SqlCall;
      final SqlLiteral literal =
          SqlLiteralChainOperator.concatenateOperands((SqlCall) node);
      assert SqlTypeUtil.inCharFamily(literal.getTypeName());
      return (NlsString) literal.value;
    }
    switch (node.getKind()) {
    case INTERVAL_QUALIFIER:
      //noinspection ConstantConditions
      return ((SqlIntervalQualifier) node).timeUnitRange;
    case CAST:
      assert node instanceof SqlCall;
      return value(((SqlCall) node).operand(0));
    case MINUS_PREFIX:
      assert node instanceof SqlCall;
      Comparable o = value(((SqlCall) node).operand(0));
      if (o instanceof BigDecimal) {
        BigDecimal bigDecimal = (BigDecimal) o;
        return bigDecimal.negate();
      }
      // fall through
    default:
      throw new IllegalArgumentException("not a literal: " + node);
    }
  }

  /**
   * Extracts the string value from a string literal, a chain of string
   * literals, or a CAST of a string literal.
   *
   * @deprecated Use {@link #value(SqlNode)}
   */
  @Deprecated // to be removed before 2.0
  public static String stringValue(SqlNode node) {
    if (node instanceof SqlLiteral) {
      SqlLiteral literal = (SqlLiteral) node;
      assert SqlTypeUtil.inCharFamily(literal.getTypeName());
      return literal.value.toString();
    } else if (SqlUtil.isLiteralChain(node)) {
      final SqlLiteral literal =
          SqlLiteralChainOperator.concatenateOperands((SqlCall) node);
      assert SqlTypeUtil.inCharFamily(literal.getTypeName());
      return literal.value.toString();
    } else if (node instanceof SqlCall
        && ((SqlCall) node).getOperator() == SqlStdOperatorTable.CAST) {
      return stringValue(((SqlCall) node).operand(0));
    } else {
      throw new AssertionError("invalid string literal: " + node);
    }
  }

  /**
   * Converts a chained string literals into regular literals; returns regular
   * literals unchanged.
   * @throws IllegalArgumentException if {@code node} is not a string literal
   * and cannot be unchained.
   */
  public static SqlLiteral unchain(SqlNode node) {
    switch (node.getKind()) {
    case LITERAL:
      return (SqlLiteral) node;
    case LITERAL_CHAIN:
      return SqlLiteralChainOperator.concatenateOperands((SqlCall) node);
    case INTERVAL_QUALIFIER:
      final SqlIntervalQualifier q = (SqlIntervalQualifier) node;
      return new SqlLiteral(
          new SqlIntervalLiteral.IntervalValue(q, 1, q.toString()),
          q.typeName(), q.pos);
    default:
      throw new IllegalArgumentException("invalid literal: " + node);
    }
  }

  /**
   * For calc program builder - value may be different than {@link #unparse}.
   * Typical values:
   *
   *

   *
Hello, world!

   *
12.34

   *
{null}

   *
1969-04-29

   *

   *
   * @return string representation of the value
   */
  public String toValue() {
    if (value == null) {
      return null;
    }
    switch (typeName) {
    case CHAR:

      // We want 'It''s superman!', not _ISO-8859-1'It''s superman!'
      return ((NlsString) value).getValue();
    default:
      return value.toString();
    }
  }

  public void validate(SqlValidator validator, SqlValidatorScope scope) {
    validator.validateLiteral(this);
  }

  public <R> R accept(SqlVisitor<R> visitor) {
    return visitor.visit(this);
  }

  public boolean equalsDeep(SqlNode node, Litmus litmus) {
    if (!(node instanceof SqlLiteral)) {
      return litmus.fail("{} != {}", this, node);
    }
    SqlLiteral that = (SqlLiteral) node;
    if (!this.equals(that)) {
      return litmus.fail("{} != {}", this, node);
    }
    return litmus.succeed();
  }

  public SqlMonotonicity getMonotonicity(SqlValidatorScope scope) {
    return SqlMonotonicity.CONSTANT;
  }

  /**
   * Creates a NULL literal.
   *
   *
There's no singleton constant for a NULL literal. Instead, nulls must
   * be instantiated via createNull(), because different instances have
   * different context-dependent types.
   */
  public static SqlLiteral createNull(SqlParserPos pos) {
    return new SqlLiteral(null, SqlTypeName.NULL, pos);
  }

  /**
   * Creates a boolean literal.
   */
  public static SqlLiteral createBoolean(
      boolean b,
      SqlParserPos pos) {
    return b ? new SqlLiteral(Boolean.TRUE, SqlTypeName.BOOLEAN, pos)
        : new SqlLiteral(Boolean.FALSE, SqlTypeName.BOOLEAN, pos);
  }

  public static SqlLiteral createUnknown(SqlParserPos pos) {
    return new SqlLiteral(null, SqlTypeName.BOOLEAN, pos);
  }

  /**
   * Creates a literal which represents a parser symbol, for example the
   * TRAILING keyword in the call Trim(TRAILING 'x' FROM
   * 'Hello world!').
   *
   * @see #symbolValue(Class)
   */
  public static SqlLiteral createSymbol(Enum<?> o, SqlParserPos pos) {
    return new SqlLiteral(o, SqlTypeName.SYMBOL, pos);
  }

  /**
   * Creates a literal which represents a sample specification.
   */
  public static SqlLiteral createSample(
      SqlSampleSpec sampleSpec,
      SqlParserPos pos) {
    return new SqlLiteral(sampleSpec, SqlTypeName.SYMBOL, pos);
  }

  public boolean equals(Object obj) {
    if (!(obj instanceof SqlLiteral)) {
      return false;
    }
    SqlLiteral that = (SqlLiteral) obj;
    return Objects.equals(value, that.value);
  }

  public int hashCode() {
    return (value == null) ? 0 : value.hashCode();
  }

  /**
   * Returns the integer value of this literal.
   *
   * @param exact Whether the value has to be exact. If true, and the literal
   *              is a fraction (e.g. 3.14), throws. If false, discards the
   *              fractional part of the value.
   * @return Integer value of this literal
   */
  public int intValue(boolean exact) {
    switch (typeName) {
    case DECIMAL:
    case DOUBLE:
      BigDecimal bd = (BigDecimal) value;
      if (exact) {
        try {
          return bd.intValueExact();
        } catch (ArithmeticException e) {
          throw SqlUtil.newContextException(getParserPosition(),
              RESOURCE.numberLiteralOutOfRange(bd.toString()));
        }
      } else {
        return bd.intValue();
      }
    default:
      throw Util.unexpected(typeName);
    }
  }

  /**
   * Returns the long value of this literal.
   *
   * @param exact Whether the value has to be exact. If true, and the literal
   *              is a fraction (e.g. 3.14), throws. If false, discards the
   *              fractional part of the value.
   * @return Long value of this literal
   */
  public long longValue(boolean exact) {
    switch (typeName) {
    case DECIMAL:
    case DOUBLE:
      BigDecimal bd = (BigDecimal) value;
      if (exact) {
        try {
          return bd.longValueExact();
        } catch (ArithmeticException e) {
          throw SqlUtil.newContextException(getParserPosition(),
              RESOURCE.numberLiteralOutOfRange(bd.toString()));
        }
      } else {
        return bd.longValue();
      }
    default:
      throw Util.unexpected(typeName);
    }
  }

  /**
   * Returns sign of value.
   *
   * @return -1, 0 or 1
   */
  @Deprecated // to be removed before 2.0
  public int signum() {
    return bigDecimalValue().compareTo(
        BigDecimal.ZERO);
  }

  /**
   * Returns a numeric literal's value as a {@link BigDecimal}.
   */
  public BigDecimal bigDecimalValue() {
    switch (typeName) {
    case DECIMAL:
    case DOUBLE:
      return (BigDecimal) value;
    default:
      throw Util.unexpected(typeName);
    }
  }

  @Deprecated // to be removed before 2.0
  public String getStringValue() {
    return ((NlsString) value).getValue();
  }

  public void unparse(
      SqlWriter writer,
      int leftPrec,
      int rightPrec) {
    switch (typeName) {
    case BOOLEAN:
      writer.keyword(
          value == null ? "UNKNOWN" : (Boolean) value ? "TRUE" : "FALSE");
      break;
    case NULL:
      writer.keyword("NULL");
      break;
    case CHAR:
    case DECIMAL:
    case DOUBLE:
    case BINARY:
      // should be handled in subtype
      throw Util.unexpected(typeName);

    case SYMBOL:
      if (value instanceof Enum) {
        Enum enumVal = (Enum) value;
        writer.keyword(enumVal.toString());
      } else {
        writer.keyword(String.valueOf(value));
      }
      break;
    default:
      writer.literal(value.toString());
    }
  }

  public RelDataType createSqlType(RelDataTypeFactory typeFactory) {
    BitString bitString;
    switch (typeName) {
    case NULL:
    case BOOLEAN:
      RelDataType ret = typeFactory.createSqlType(typeName);
      ret = typeFactory.createTypeWithNullability(ret, null == value);
      return ret;
    case BINARY:
      bitString = (BitString) value;
      int bitCount = bitString.getBitCount();
      return typeFactory.createSqlType(SqlTypeName.BINARY, bitCount / 8);
    case CHAR:
      NlsString string = (NlsString) value;
      Charset charset = string.getCharset();
      if (null == charset) {
        charset = typeFactory.getDefaultCharset();
      }
      SqlCollation collation = string.getCollation();
      if (null == collation) {
        collation = SqlCollation.COERCIBLE;
      }
      RelDataType type =
          typeFactory.createSqlType(
              SqlTypeName.CHAR,
              string.getValue().length());
      type =
          typeFactory.createTypeWithCharsetAndCollation(
              type,
              charset,
              collation);
      return type;

    case INTERVAL_YEAR:
    case INTERVAL_YEAR_MONTH:
    case INTERVAL_MONTH:
    case INTERVAL_DAY:
    case INTERVAL_DAY_HOUR:
    case INTERVAL_DAY_MINUTE:
    case INTERVAL_DAY_SECOND:
    case INTERVAL_HOUR:
    case INTERVAL_HOUR_MINUTE:
    case INTERVAL_HOUR_SECOND:
    case INTERVAL_MINUTE:
    case INTERVAL_MINUTE_SECOND:
    case INTERVAL_SECOND:
      SqlIntervalLiteral.IntervalValue intervalValue =
          (SqlIntervalLiteral.IntervalValue) value;
      return typeFactory.createSqlIntervalType(
          intervalValue.getIntervalQualifier());

    case SYMBOL:
      return typeFactory.createSqlType(SqlTypeName.SYMBOL);

    case INTEGER: // handled in derived class
    case TIME: // handled in derived class
    case VARCHAR: // should never happen
    case VARBINARY: // should never happen

    default:
      throw Util.needToImplement(toString() + ", operand=" + value);
    }
  }

  @Deprecated // to be removed before 2.0
  public static SqlDateLiteral createDate(
      Calendar calendar,
      SqlParserPos pos) {
    return createDate(DateString.fromCalendarFields(calendar), pos);
  }

  public static SqlDateLiteral createDate(
      DateString date,
      SqlParserPos pos) {
    return new SqlDateLiteral(date, pos);
  }

  @Deprecated // to be removed before 2.0
  public static SqlTimestampLiteral createTimestamp(
      Calendar calendar,
      int precision,
      SqlParserPos pos) {
    return createTimestamp(TimestampString.fromCalendarFields(calendar),
        precision, pos);
  }

  public static SqlTimestampLiteral createTimestamp(
      TimestampString ts,
      int precision,
      SqlParserPos pos) {
    return new SqlTimestampLiteral(ts, precision, false, pos);
  }

  @Deprecated // to be removed before 2.0
  public static SqlTimeLiteral createTime(
      Calendar calendar,
      int precision,
      SqlParserPos pos) {
    return createTime(TimeString.fromCalendarFields(calendar), precision, pos);
  }

  public static SqlTimeLiteral createTime(
      TimeString t,
      int precision,
      SqlParserPos pos) {
    return new SqlTimeLiteral(t, precision, false, pos);
  }

  /**
   * Creates an interval literal.
   *
   * @param intervalStr       input string of '1:23:04'
   * @param intervalQualifier describes the interval type and precision
   * @param pos               Parser position
   */
  public static SqlIntervalLiteral createInterval(
      int sign,
      String intervalStr,
      SqlIntervalQualifier intervalQualifier,
      SqlParserPos pos) {
    return new SqlIntervalLiteral(sign, intervalStr, intervalQualifier,
        intervalQualifier.typeName(), pos);
  }

  public static SqlNumericLiteral createNegative(
      SqlNumericLiteral num,
      SqlParserPos pos) {
    return new SqlNumericLiteral(
        ((BigDecimal) num.getValue()).negate(),
        num.getPrec(),
        num.getScale(),
        num.isExact(),
        pos);
  }

  public static SqlNumericLiteral createExactNumeric(
      String s,
      SqlParserPos pos) {
    BigDecimal value;
    int prec;
    int scale;

    int i = s.indexOf('.');
    if ((i >= 0) && ((s.length() - 1) != i)) {
      value = SqlParserUtil.parseDecimal(s);
      scale = s.length() - i - 1;
      assert scale == value.scale() : s;
      prec = s.length() - 1;
    } else if ((i >= 0) && ((s.length() - 1) == i)) {
      value = SqlParserUtil.parseInteger(s.substring(0, i));
      scale = 0;
      prec = s.length() - 1;
    } else {
      value = SqlParserUtil.parseInteger(s);
      scale = 0;
      prec = s.length();
    }
    return new SqlNumericLiteral(
        value,
        prec,
        scale,
        true,
        pos);
  }

  public static SqlNumericLiteral createApproxNumeric(
      String s,
      SqlParserPos pos) {
    BigDecimal value = SqlParserUtil.parseDecimal(s);
    return new SqlNumericLiteral(value, null, null, false, pos);
  }

  /**
   * Creates a literal like X'ABAB'. Although it matters when we derive a type
   * for this beastie, we don't care at this point whether the number of
   * hexits is odd or even.
   */
  public static SqlBinaryStringLiteral createBinaryString(
      String s,
      SqlParserPos pos) {
    BitString bits;
    try {
      bits = BitString.createFromHexString(s);
    } catch (NumberFormatException e) {
      throw SqlUtil.newContextException(pos,
          RESOURCE.binaryLiteralInvalid());
    }
    return new SqlBinaryStringLiteral(bits, pos);
  }

  /**
   * Creates a literal like X'ABAB' from an array of bytes.
   *
   * @param bytes Contents of binary literal
   * @param pos   Parser position
   * @return Binary string literal
   */
  public static SqlBinaryStringLiteral createBinaryString(
      byte[] bytes,
      SqlParserPos pos) {
    BitString bits;
    try {
      bits = BitString.createFromBytes(bytes);
    } catch (NumberFormatException e) {
      throw SqlUtil.newContextException(pos, RESOURCE.binaryLiteralInvalid());
    }
    return new SqlBinaryStringLiteral(bits, pos);
  }

  /**
   * Creates a string literal in the system character set.
   *
   * @param s   a string (without the sql single quotes)
   * @param pos Parser position
   */
  public static SqlCharStringLiteral createCharString(
      String s,
      SqlParserPos pos) {
    // UnsupportedCharsetException not possible
    return createCharString(s, null, pos);
  }

  /**
   * Creates a string literal, with optional character-set.
   *
   * @param s       a string (without the sql single quotes)
   * @param charSet character set name, null means take system default
   * @param pos     Parser position
   * @return A string literal
   * @throws UnsupportedCharsetException if charSet is not null but there is
   *                                     no character set with that name in this
   *                                     environment
   */
  public static SqlCharStringLiteral createCharString(
      String s,
      String charSet,
      SqlParserPos pos) {
    NlsString slit = new NlsString(s, charSet, null);
    return new SqlCharStringLiteral(slit, pos);
  }

  /**
   * Transforms this literal (which must be of type character) into a new one
   * in which 4-digit Unicode escape sequences have been replaced with the
   * corresponding Unicode characters.
   *
   * @param unicodeEscapeChar escape character (e.g. backslash) for Unicode
   *                          numeric sequences; 0 implies no transformation
   * @return transformed literal
   */
  public SqlLiteral unescapeUnicode(char unicodeEscapeChar) {
    if (unicodeEscapeChar == 0) {
      return this;
    }
    assert SqlTypeUtil.inCharFamily(getTypeName());
    NlsString ns = (NlsString) value;
    String s = ns.getValue();
    StringBuilder sb = new StringBuilder();
    int n = s.length();
    for (int i = 0; i < n; ++i) {
      char c = s.charAt(i);
      if (c == unicodeEscapeChar) {
        if (n > (i + 1)) {
          if (s.charAt(i + 1) == unicodeEscapeChar) {
            sb.append(unicodeEscapeChar);
            ++i;
            continue;
          }
        }
        if ((i + 5) > n) {
          throw SqlUtil.newContextException(getParserPosition(),
              RESOURCE.unicodeEscapeMalformed(i));
        }
        final String u = s.substring(i + 1, i + 5);
        final int v;
        try {
          v = Integer.parseInt(u, 16);
        } catch (NumberFormatException ex) {
          throw SqlUtil.newContextException(getParserPosition(),
              RESOURCE.unicodeEscapeMalformed(i));
        }
        sb.append((char) (v & 0xFFFF));

        // skip hexits
        i += 4;
      } else {
        sb.append(c);
      }
    }
    ns = new NlsString(
        sb.toString(),
        ns.getCharsetName(),
        ns.getCollation());
    return new SqlCharStringLiteral(ns, getParserPosition());
  }

  //~ Inner Interfaces -------------------------------------------------------

  /**
   * A value must implement this interface if it is to be embedded as a
   * SqlLiteral of type SYMBOL. If the class is an {@link Enum} it trivially
   * implements this interface.
   *
   *
The {@link #toString()} method should return how the symbol should be
   * unparsed, which is sometimes not the same as the enumerated value's name
   * (e.g. "UNBOUNDED PRECEDING" versus "UnboundedPreceeding").
   */
  @Deprecated // to be removed before 2.0
  public interface SqlSymbol {
    String name();

    int ordinal();
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 322165 $ -->

<refentry xml:id="function.mysqlnd-ms-get-last-used-connection" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
 <refnamediv>
  <refname>mysqlnd_ms_get_last_used_connection</refname>
  <refpurpose>Returns an array which describes the last used connection</refpurpose>
 </refnamediv>

 <refsect1 role="description">
  &reftitle.description;
  <methodsynopsis>
   <type>array</type>
   <methodname>mysqlnd_ms_get_last_used_connection</methodname>
   <methodparam><type>mixed</type><parameter>connection</parameter></methodparam>
  </methodsynopsis>
  <para>
   Returns an array which describes the last used connection from the plugins
   connection pool currently pointed to by the user connection handle. If using the
   plugin, a user connection handle represents a pool of database connections.
   It is not possible to tell from the user connection handles properties to which
   database server from the pool the user connection handle points.
  </para>
  <para>
   The function can be used to debug or monitor PECL mysqlnd_ms.
  </para>
 </refsect1>

 <refsect1 role="parameters">
  &reftitle.parameters;
  <variablelist>
   <varlistentry>
    <term><parameter>connection</parameter></term>
    <listitem>
     <para>
      A MySQL connection handle obtained from any of the
      connect functions of the <link linkend="ref.mysqli">mysqli</link>,
      <link linkend="ref.mysql">mysql</link> or
      <link linkend="ref.pdo-mysql">PDO_MYSQL</link> extensions.
     </para>
    </listitem>
   </varlistentry>
  </variablelist>
 </refsect1>

 <refsect1 role="returnvalues">
  &reftitle.returnvalues;
  <para>
   &false; on error. Otherwise, an
   array which describes the connection used to
   execute the last statement on.
  </para>
  <para>
   Array which describes the connection.
  </para>
  <informaltable>
   <tgroup cols="3">
    <colspec colwidth="1*"/>
    <colspec colwidth="7*"/>
    <colspec colwidth="2*"/>
    <thead>
     <row>
      <entry>Property</entry>
      <entry>Description</entry>
      <entry>Version</entry>
     </row>
    </thead>
    <tbody>
     <row>
      <entry>
       <literal>scheme</literal>
      </entry>
      <entry>
       Connection scheme. Either <literal>tcp://host:port</literal>
       or <literal>unix://host:socket</literal>. If you want to
       distinguish connections from each other use a combination
       of <literal>scheme</literal> and <literal>thread_id</literal> as a unique
       key. Neither <literal>scheme</literal> nor <literal>thread_id</literal>
       alone are sufficient to distinguish two connections from each other.
       Two servers may assign the same <literal>thread_id</literal> to two
       different connections. Thus, connections in the pool may have the same
       <literal>thread_id</literal>. Also, do not rely on uniqueness of
       <literal>scheme</literal> in a pool. Your QA engineers may use the
       same MySQL server instance for two distinct logical roles and add it
       multiple times to the pool. This hack is used, for example,
       in the test suite.
      </entry>
      <entry>Since 1.1.0.</entry>
     </row>
     <row>
      <entry>
       <literal>host</literal>
      </entry>
      <entry>
       Database server host used with the connection.
       The host is only set with TCP/IP connections.
       It is empty with Unix domain or Windows named pipe connections,
      </entry>
      <entry>Since 1.1.0.</entry>
     </row>
     <row>
      <entry>
       <literal>host_info</literal>
      </entry>
      <entry>
        A character string representing the server hostname and the connection type.
      </entry>
      <entry>Since 1.1.2.</entry>
     </row>
     <row>
      <entry>
       <literal>port</literal>
      </entry>
      <entry>
       Database server port used with the connection.
      </entry>
      <entry>Since 1.1.0.</entry>
     </row>
     <row>
      <entry>
       <literal>socket_or_pipe</literal>
      </entry>
      <entry>
       Unix domain socket or Windows named pipe used with the connection.
       The value is empty for TCP/IP connections.
      </entry>
      <entry>Since 1.1.2.</entry>
     </row>
     <row>
      <entry>
       <literal>thread_id</literal>
      </entry>
      <entry>
       Connection thread id.
      </entry>
      <entry>Since 1.1.0.</entry>
     </row>
     <row>
      <entry>
       <literal>last_message</literal>
      </entry>
      <entry>
       Info message obtained from the
       MySQL C API function mysql_info(). Please, see
       <function>mysqli_info</function> for
       a description.
      </entry>
      <entry>Since 1.1.0.</entry>
     </row>
     <row>
      <entry>
       <literal>errno</literal>
      </entry>
      <entry>
       Error code.
      </entry>
      <entry>Since 1.1.0.</entry>
     </row>
     <row>
      <entry>
       <literal>error</literal>
      </entry>
      <entry>
       Error message.
      </entry>
      <entry>Since 1.1.0.</entry>
     </row>
     <row>
      <entry>
       <literal>sqlstate</literal>
      </entry>
      <entry>
       Error SQLstate code.
      </entry>
      <entry>Since 1.1.0.</entry>
     </row>
    </tbody>
   </tgroup>
  </informaltable>
 </refsect1>

 <refsect1>
  &reftitle.notes;
  <note>
   <para>
    <function>mysqlnd_ms_get_last_used_connection</function> requires
    PHP >= 5.4.0 and PECL mysqlnd_ms >> 1.1.0. Internally, it is using
    a <literal>mysqlnd</literal> library C call not available with PHP 5.3.
   </para>
  </note>
 </refsect1>

 <refsect1 role="examples">
  &reftitle.examples;
  <para>
  The example assumes that <literal>myapp</literal> refers to a
  plugin configuration file section and represents a connection pool.
  </para>
  <para>
   <example>
    <title><function>mysqlnd_ms_get_last_used_connection</function> example</title>
    <programlisting role="php">
<![CDATA[
<?php
$link = new mysqli("myapp", "user", "password", "database");
$res = $link->query("SELECT 1 FROM DUAL");
var_dump(mysqlnd_ms_get_last_used_connection($link));
?>
]]>
    </programlisting>
    &example.outputs;
    <screen>
<![CDATA[
array(10) {
  ["scheme"]=>
  string(22) "unix:///tmp/mysql.sock"
  ["host_info"]=>
  string(25) "Localhost via UNIX socket"
  ["host"]=>
  string(0) ""
  ["port"]=>
  int(3306)
  ["socket_or_pipe"]=>
  string(15) "/tmp/mysql.sock"
  ["thread_id"]=>
  int(46253)
  ["last_message"]=>
  string(0) ""
  ["errno"]=>
  int(0)
  ["error"]=>
  string(0) ""
  ["sqlstate"]=>
  string(5) "00000"
}
]]>
    </screen>
   </example>
  </para>
 </refsect1>

</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->

redpajama_set_name: RedPajamaGithub


text:
package com.easemob.qixin.parse;

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

import android.util.Log;

import com.parse.ParseClassName;
import com.parse.ParseObject;

@ParseClassName("DEPARTMENT")
public class DepartmentEntity extends ParseObject{

	private String DEPARTMENT_ID = "departmentId";
	private String DEPARTMENT_NAME = "departmentName";
	private String DEPARTMENT_MEMBERS = "departmentMembers";
	private String DEPARTMENT_SUB_ID = "departmentSubIds";
	private String DEPARTMENT_SUP_ID = "departmentSupId";

	public DepartmentEntity(){

	}

	public void setDepartmentId(String departmentId){
		put(DEPARTMENT_ID, departmentId);
	}

	public String getDepartmentId(){
		return getString(DEPARTMENT_ID);
	}

	public void setDepartmentName(String departmentName){
		put(DEPARTMENT_NAME, departmentName);
	}

	public String getDepartmentName(){
		return getString(DEPARTMENT_NAME);
	}

	public void setDepartmentMembers(String departmentMembers){
		put(DEPARTMENT_MEMBERS, departmentMembers);
	}

	@SuppressWarnings("unchecked")
	public List<String> getDepartmentMembers(){
		List<String> list = new ArrayList<String>();
		if (getList(DEPARTMENT_MEMBERS) == null) {
			return list;
		}else {
			list.addAll((List<String>) get(DEPARTMENT_MEMBERS));
		}
		return list;
	}

	public void setDepartmentSubId(String departmentList){
		put(DEPARTMENT_SUB_ID, departmentList);
	}

	@SuppressWarnings("unchecked")
	public List<String> getDepartmentSubId(){
		List<String> list = new ArrayList<String>();
		if (getList(DEPARTMENT_SUB_ID) == null) {
			return list;
		}else {
			list.addAll((List<String>) get(DEPARTMENT_SUB_ID));
		}
		return list;
	}

	public void setDepartmentSupId(String departmentSupId){
		put(DEPARTMENT_SUP_ID, departmentSupId);
	}

	public String getDepartmentSupId(){
		return getString(DEPARTMENT_SUP_ID);
	}
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ch.hsr.ifs.zebrastreifensafari.model.jpa.controllers;

import ch.hsr.ifs.zebrastreifensafari.model.jpa.entities.SpatialClarity;

import javax.persistence.EntityManagerFactory;
import java.io.Serializable;
import java.util.List;

/**
 * @author aeugster
 */
public class SpatialClarityJpaController extends EntityController implements Serializable {

    public SpatialClarityJpaController(EntityManagerFactory emf) {
        super(emf);
    }

    public List<SpatialClarity> findEntities() {
        return getEntityManager().createNamedQuery("SpatialClarity.findAll", SpatialClarity.class).getResultList();
    }
}


text:
import angular from 'angular';

import UserController from 'js/user.controller';
import AppController from 'js/app.controller';
import SocketService from 'js/socket.service'

let app = angular
  .module('coyote', [])
  .controller('UserController', UserController)
  .controller('AppController', AppController)
  .service('Socket', SocketService)
  .run(function($rootScope, Socket) {

    // Restore token
    var token = localStorage.getItem('token');

    // Doing somethings on start
    var start = function(loggedin) {
      $rootScope.loggedin = loggedin;
      $rootScope.loaded = true;
      $rootScope.$apply();
      $('#login, #app').removeAttr('style');
    };

    // Check user auth status
    if (token) {
      Socket.init(token, function(err, doc) {
        if (err) {
          localStorage.removeItem('token');
          start(false);
        } else {
          start(true);
        }
      });
    } else {
      start(false);
    }
  });

export default app;


text:
$(window).scroll(function(){
    if ( $(this).scrollTop() > 1){
        $('body').addClass("scroll");
    } else if($(this).scrollTop() <= 1 && $('body').hasClass("scroll")) {
        $('body').removeClass("scroll");
    }
});//scroll

$(function () {
    if (Array.prototype.forEach) {
        var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));
        elems.forEach(function(html) {
            var switchery = new Switchery(html);
        });
    } else {
        var elems = document.querySelectorAll('.js-switch');
        for (var i = 0; i < elems.length; i++) {
            var switchery = new Switchery(elems[i]);
        }
    }

    if ($(window).width() < 800) {
        $('body').addClass('aside-collapse');
    }

    $('.caret-aside').click(function() {
        $('body').toggleClass('aside-collapse');

        $.post("mskSaveNavMenuState", {isNavMenuCollapsed : $('body').hasClass('aside-collapse')}, function(resp){
            if (resp.status == 'ERROR'){
                //console.log(resp);
            }
        });
        setTimeout(function() {
            if(chartEngineIniter && chartEngineIniter.d3charts && chartEngineIniter.d3charts.dispatch){
                chartEngineIniter.d3charts.dispatch.resizeLineCharts();
            }
        }, 200);
    });

    $('.tooltip-bottom').tooltip({placement:'bottom', container: 'body'}).on('show', function (e) {e.stopPropagation();});
    $('.tooltip-top').tooltip({placement:'top', container: 'body'}).on('show', function (e) {e.stopPropagation();});
    $('.tooltip-left').tooltip({placement:'left', container: 'body'}).on('show', function (e) {e.stopPropagation();});
    $('.tooltip-right').tooltip({placement:'right', container: 'body'}).on('show', function (e) {e.stopPropagation();});
    $(document).tooltip({selector: '.aside-collapse .sidebar-tooltip-right', placement:'right', container: 'body'}).on('show', function (e) {e.stopPropagation();});

    $('.popover-bottom').popover({placement:'bottom', container: 'body'}).click(function(){
        $('.popover-bottom').not(this).popover('hide');
        return false;
    });

    $.tablesorter.addParser({
        // set a unique id
        id: 'commaNumber',
        is: function(s) {
            return /^[0-9]?[0-9,\.]*$/.test(s);
        },
        format: function(s) {
//            return jQuery.tablesorter.formatFloat( s.replace(/,/g,'') );
            return s.replace(/\,/g,"");
        },
        // set type, either numeric or text
        type: 'numeric'
    });

    $(".tablesorter").tablesorter();

    $(".select2").select2();

    $(".scrollbar").mCustomScrollbar();

    $(".hscrollbar").mCustomScrollbar({
        advanced:{
            updateOnContentResize: true
        },
        horizontalScroll:true
    });

    $('.hscrollbar .mCSB_scrollTools').css('position','fixed');
    $('.hscrollbar').mCustomScrollbar("update");

    $('ul.nav-sidebar > li').click(function () {
        $('ul.nav-sidebar > li').removeClass('active');
        $(this).addClass('active');
    });

    var max = 0

    $('.headcol').each(function() {
        var width = $(this).width(); if( max < width) { max = width}
    });

    $('.headcol').width(max);
    $('.table1fixed').css('margin-left', max + 39);

    var $treeTable = $("table.tree");
    if($treeTable.length > 0)
        $treeTable.treeTable();
});


text:
namespace tensorflow {

using std::placeholders::_1;
using tensorforest::BestFeatureClassification;
using tensorforest::BestFeatureRegression;

REGISTER_OP("BestSplits")
  .Attr("regression: bool = false")
  .Input("finished_nodes: int32")
  .Input("node_to_accumulator: int32")
  .Input("split_sums: float")
  .Input("split_squares: float")
  .Input("accumulator_sums: float")
  .Input("accumulator_sqaures: float")
  .Output("split_indices: int32")
  .Doc(R"doc(
  Returns the index of the best split for each finished node.

  For classification, the best split is the split with the lowest weighted
  Gini impurity, as calculated from the statistics in `split_sums` and
  `accumulator_sums`. For regression we use the lowest variance, incoporating
  the *_squares as well.

  finished_nodes:= A 1-d int32 tensor containing the indices of finished nodes.
  node_to_accumulator: `node_to_accumulator[i]` is the accumulator slot used by
    fertile node i, or -1 if node i isn't fertile.
  split_sums:= a 3-d tensor where `split_sums[a][s]` summarizes the
    training labels for examples that fall into the fertile node associated with
    accumulator slot s and have then taken the *left* branch of candidate split
    s.  For a classification problem, `split_sums[a][s][c]` is the count of such
    examples with class c and for regression problems, `split_sums[a][s]` is the
    sum of the regression labels for such examples.
  split_squares: Same as split_sums, but it contains the sum of the
    squares of the regression labels.  Only used for regression.  For
    classification problems, pass a dummy tensor into this.
  accumulator_sums:= a 2-d tensor where `accumulator_sums[a]` summarizes the
    training labels for examples that fall into the fertile node associated with
    accumulator slot s.  For a classification problem, `accumulator_sums[a][c]`
    is the count of such examples with class c and for regression problems,
    `accumulator_sums[a]` is the sum of the regression labels for such examples.
  accumulator_squares: Same as accumulator_sums, but it contains the sum of the
    squares of the regression labels.  Only used for regression.  For
    classification problems, pass a dummy tensor into this.
  split_indices: `split_indices[i]` contains the index of the split to use for
    `finished_nodes[i]`.
)doc");

class BestSplits : public OpKernel {
 public:
  explicit BestSplits(OpKernelConstruction* context) : OpKernel(context) {
    OP_REQUIRES_OK(context, context->GetAttr(
        "regression", &regression_));
  }

  void Compute(OpKernelContext* context) override {
    const Tensor& finished = context->input(0);
    const Tensor& node_to_accumulator = context->input(1);
    const Tensor& split_sums = context->input(2);
    const Tensor& split_squares = context->input(3);
    const Tensor& accumulator_sums = context->input(4);
    const Tensor& accumulator_squares = context->input(5);

    OP_REQUIRES(context, finished.shape().dims() == 1,
                errors::InvalidArgument(
                    "finished should be one-dimensional"));
    OP_REQUIRES(context, node_to_accumulator.shape().dims() == 1,
                errors::InvalidArgument(
                    "node_to_accumulator should be one-dimensional"));

    OP_REQUIRES(context, split_sums.shape().dims() == 3,
                errors::InvalidArgument(
                    "split_sums should be three-dimensional"));
    OP_REQUIRES(context, accumulator_sums.shape().dims() == 2,
                errors::InvalidArgument(
                    "accumulator_sums should be two-dimensional"));

    if (regression_) {
      OP_REQUIRES(context,
                  split_sums.shape() == split_squares.shape(),
                  errors::InvalidArgument(
                      "split_sums and split_squares should "
                      "be the same shape."));
      OP_REQUIRES(context,
                  accumulator_sums.shape() == accumulator_squares.shape(),
                  errors::InvalidArgument(
                      "accumulator_sums and accumulator_squares should "
                      "be the same shape."));
    }

    OP_REQUIRES(
        context,
        accumulator_sums.shape().dim_size(0) ==
        split_sums.shape().dim_size(0),
        errors::InvalidArgument(
            "Number of accumulators should be the same in split_sums "
            "and accumulator_sums."));

    Tensor* output_splits = nullptr;
    OP_REQUIRES_OK(context,
                   context->allocate_output(0, finished.shape(),
                                            &output_splits));
    auto best_splits = output_splits->unaligned_flat<int32>();

    const auto finished_vec = finished.unaligned_flat<int32>();
    const auto node_map = node_to_accumulator.unaligned_flat<int32>();

    const int32 num_finished = finished.shape().dim_size(0);

    std::function<int32(int32)> best_feature_func =
        std::bind(BestFeatureClassification, accumulator_sums,
                  split_sums, _1);
    if (regression_) {
       best_feature_func = std::bind(
           BestFeatureRegression, accumulator_sums, accumulator_squares,
           split_sums, split_squares, _1);
    }

    for (int i = 0; i < num_finished; i++) {
      const int32 node = finished_vec(i);
      const int32 accumulator = node_map(node);
      if (accumulator < 0) {
        LOG(ERROR) << "Something has gone wrong, we got a finished node that "
                   << "doesn't have an accumulator allocated to it.";
        continue;
      }

      best_splits(i) = best_feature_func(accumulator);
    }
  }

 private:
  bool regression_;
};

REGISTER_KERNEL_BUILDER(Name("BestSplits").Device(DEVICE_CPU), BestSplits);

}  // namespace tensorflow


text:
<?php

declare(strict_types=1);

namespace Contentful\Delivery\Resource;

use Contentful\Delivery\SystemProperties\Space as SystemProperties;

/**
 * The Space class represents a single space identified by its ID and holding some metadata.
 */
class Space extends BaseResource
{
    /**
     * @var SystemProperties
     */
    protected $sys;

    /**
     * @var string
     */
    protected $name;

    /**
     * {@inheritdoc}
     */
    public function getSystemProperties(): SystemProperties
    {
        return $this->sys;
    }

    /**
     * Returns the name of this space.
     */
    public function getName(): string
    {
        return $this->name;
    }

    /**
     * {@inheritdoc}
     */
    public function jsonSerialize(): array
    {
        return [
            'sys' => $this->sys,
            'name' => $this->name,
        ];
    }
}


text:
namespace Listy.Tests
{
    public abstract class ConcernFor<T>
    {
        protected ConcernFor()
        {
            Context();
            Subject = Given();
            When();
        }

        protected T Subject { get; private set; }

        protected virtual void Context()
        {
        }

        protected abstract T Given();

        protected virtual void When()
        {
        }
    }
}


text:
<?php

declare(strict_types=1);

namespace Ixocreate\Misc\ServiceManager;

use Ixocreate\ServiceManager\FactoryInterface;
use Ixocreate\ServiceManager\ServiceManagerInterface;

class CantCreateObjectFactory implements FactoryInterface
{
    /**
     * @param ServiceManagerInterface $container
     * @param $requestedName
     * @param array|null $options
     * @throws \Exception
     * @return mixed
     */
    public function __invoke(ServiceManagerInterface $container, $requestedName, array $options = null)
    {
        throw new \Exception('cant create');
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>GwtLocaleImpl (GWT Javadoc)</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Deprecated

Help

GWT 2.8.0-rc1

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.google.gwt.i18n.server

Class GwtLocaleImpl

java.lang.Object

com.google.gwt.i18n.server.GwtLocaleImpl

All Implemented Interfaces:

GwtLocale, java.lang.Comparable<GwtLocale>

public class GwtLocaleImpl
extends java.lang.Object
implements GwtLocale

Class representing GWT locales and conversion to/from other formats.

 These locales correspond to BCP47.

Field Summary

Fields inherited from interface com.google.gwt.i18n.shared.GwtLocale

DEFAULT_LOCALE

Constructor Summary

Constructors

Constructor and Description

GwtLocaleImpl(GwtLocaleFactory factory,
             java.lang.String language,
             java.lang.String region,
             java.lang.String script,
             java.lang.String variant)

Must only be called from a factory to preserve instance caching.

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

int
compareTo(GwtLocale o)

The default comparison is a lexical ordering.

boolean
equals(java.lang.Object obj)

java.util.List<GwtLocale>
getAliases()

Returns the list of aliases for this locale.

java.lang.String
getAsString()

Returns the locale as a fixed-format string suitable for use in searching
 for localized resources.

GwtLocale
getCanonicalForm()

Returns this locale in canonical form.

java.util.List<GwtLocale>
getCompleteSearchList()

Returns the complete list of locales to search for the current locale.

java.util.List<GwtLocale>
getInheritanceChain()

Return a list of locales to search for, in order of preference.

java.lang.String
getLanguage()

Returns the language portion of the locale, or null if none.

java.lang.String
getLanguageNotNull()

Returns the language portion of the locale, or the empty string if none.

java.lang.String
getRegion()

Returns the region portion of the locale, or null if none.

java.lang.String
getRegionNotNull()

Returns the region portion of the locale, or the empty string if none.

java.lang.String
getScript()

Returns the script portion of the locale, or null if none.

java.lang.String
getScriptNotNull()

Returns the script portion of the locale, or the empty string if none.

java.lang.String
getVariant()

Returns the variant portion of the locale, or null if none.

java.lang.String
getVariantNotNull()

Returns the variant portion of the locale, or the empty string if none.

int
hashCode()

boolean
inheritsFrom(GwtLocale parent)

Return true if this locale inherits from the specified locale.

boolean
isDefault()

Returns true if this is the default or root locale.

java.lang.String
toString()

Returns a human readable string -- "default" or the same as getAsString().

boolean
usesSameScript(GwtLocale other)

Checks if this locale uses the same script as another locale, taking into
 account default scripts.

Methods inherited from class java.lang.Object

clone, finalize, getClass, notify, notifyAll, wait, wait, wait

Constructor Detail

GwtLocaleImpl

GwtLocaleImpl(GwtLocaleFactory factory,
              java.lang.String language,
              java.lang.String region,
              java.lang.String script,
              java.lang.String variant)

Must only be called from a factory to preserve instance caching.

Method Detail

compareTo

public int compareTo(GwtLocale o)

Description copied from interface: GwtLocale

The default comparison is a lexical ordering.

Specified by:

compareTo in interface GwtLocale

Specified by:

compareTo in interface java.lang.Comparable<GwtLocale>

equals

public boolean equals(java.lang.Object obj)

Overrides:

equals in class java.lang.Object

getAliases

public java.util.List<GwtLocale> getAliases()

Description copied from interface: GwtLocale

Returns the list of aliases for this locale.  The canonical form of the
 current locale is always first on the list.

 Language/region codes have changed over time, so some systems continue to
 use the older codes.  Aliases allow GWT to use the official Unicode CLDR
 locales while still interoperating with such systems.

Specified by:

getAliases in interface GwtLocale

Returns:

alias list

getAsString

public java.lang.String getAsString()

Description copied from interface: GwtLocale

Returns the locale as a fixed-format string suitable for use in searching
 for localized resources.  The format is language_Script_REGION_VARIANT,
 where language is a 2-8 letter code (possibly with 3-letter extensions),
 script is a 4-letter code with an initial capital letter, region is a
 2-character country code or a 3-digit region code, and variant is a 5-8
 character (may be 4 if the first character is numeric) code.  If a
 component is missing, its preceding _ is also omitted.  If this is the
 default locale, the empty string will be returned.

Specified by:

getAsString in interface GwtLocale

Returns:

String representing locale

getCanonicalForm

public GwtLocale getCanonicalForm()

Returns this locale in canonical form.  Changes for canonical form are:

Deprecated language/region tags are replaced with official versions

Specified by:

getCanonicalForm in interface GwtLocale

Returns:

GwtLocale instance

getCompleteSearchList

public java.util.List<GwtLocale> getCompleteSearchList()

Description copied from interface: GwtLocale

Returns the complete list of locales to search for the current locale.
 This list will always start with the canonical form of this locale, and
 end with "default", and include all appropriate aliases along the way.

Specified by:

getCompleteSearchList in interface GwtLocale

Returns:

search list

getInheritanceChain

public java.util.List<GwtLocale> getInheritanceChain()

Return a list of locales to search for, in order of preference.  The
 current locale is always first on the list.  Aliases are not included
 in the list -- use getAliases() to expand those.

Specified by:

getInheritanceChain in interface GwtLocale

Returns:

inheritance list

getLanguage

public java.lang.String getLanguage()

Description copied from interface: GwtLocale

Returns the language portion of the locale, or null if none.

Specified by:

getLanguage in interface GwtLocale

getLanguageNotNull

public java.lang.String getLanguageNotNull()

Description copied from interface: GwtLocale

Returns the language portion of the locale, or the empty string if none.

Specified by:

getLanguageNotNull in interface GwtLocale

getRegion

public java.lang.String getRegion()

Description copied from interface: GwtLocale

Returns the region portion of the locale, or null if none.

Specified by:

getRegion in interface GwtLocale

getRegionNotNull

public java.lang.String getRegionNotNull()

Description copied from interface: GwtLocale

Returns the region portion of the locale, or the empty string if none.

Specified by:

getRegionNotNull in interface GwtLocale

getScript

public java.lang.String getScript()

Description copied from interface: GwtLocale

Returns the script portion of the locale, or null if none.

Specified by:

getScript in interface GwtLocale

getScriptNotNull

public java.lang.String getScriptNotNull()

Description copied from interface: GwtLocale

Returns the script portion of the locale, or the empty string if none.

Specified by:

getScriptNotNull in interface GwtLocale

getVariant

public java.lang.String getVariant()

Description copied from interface: GwtLocale

Returns the variant portion of the locale, or null if none.

Specified by:

getVariant in interface GwtLocale

getVariantNotNull

public java.lang.String getVariantNotNull()

Description copied from interface: GwtLocale

Returns the variant portion of the locale, or the empty string if none.

Specified by:

getVariantNotNull in interface GwtLocale

hashCode

public int hashCode()

Overrides:

hashCode in class java.lang.Object

inheritsFrom

public boolean inheritsFrom(GwtLocale parent)

Return true if this locale inherits from the specified locale.  Note that
 locale.inheritsFrom(locale) is false -- if you want that to be true, you
 should just use locale.getInheritanceChain().contains(x).

Specified by:

inheritsFrom in interface GwtLocale

Parameters:

parent - locale to test against

Returns:

true if parent is an ancestor of this locale

isDefault

public boolean isDefault()

Description copied from interface: GwtLocale

Returns true if this is the default or root locale.

Specified by:

isDefault in interface GwtLocale

toString

public java.lang.String toString()

Description copied from interface: GwtLocale

Returns a human readable string -- "default" or the same as getAsString().

Specified by:

toString in interface GwtLocale

Overrides:

toString in class java.lang.Object

usesSameScript

public boolean usesSameScript(GwtLocale other)

Checks if this locale uses the same script as another locale, taking into
 account default scripts.

Specified by:

usesSameScript in interface GwtLocale

Parameters:

other -

Returns:

true if the scripts are the same

Skip navigation links

Overview

Package

Class

Use

Deprecated

Help

GWT 2.8.0-rc1

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
/*
Package datacodec holds the data codec registry and adds known encoders and decoders supporting media types such as
`application/json` and `application/xml`.
*/
package datacodec


text:
class CreateTagsVocabularies < ActiveRecord::Migration[4.2]
  def change
    create_table :tags_vocabularies do |t|
      t.belongs_to :vocabulary, index: true
      t.belongs_to :tag, index: true
    end
  end
end


text:
import java.util.*;

public class NoteMakerHoldDefinitions{

   private ArrayList<NoteMakerDefinition> _definitions;

   public NoteMakerHoldDefinitions(){
      _definitions = new ArrayList<NoteMakerDefinition>();
   }

   public String processDefinitions(String str){
      Scanner process = new Scanner( str );
      String next = null;
      String finalResult = str;
      String variables = "";
      boolean finished = false;

      // This Process will find all the Definition Heads / Variables and after it is complete
      // We will process all the definitions with the .replaceAll function.
      while( process.hasNext() ){
         next = process.next();

         for( int i = 0; i < _definitions.size(); i++){
            if( _definitions.get( i ).isHeader( next ) ){
               for( int j = 0; j < _definitions.get( i ).getVariableCount(); j++){
                   if( j == _definitions.get( i ).getVariableCount()-1){
                     variables += process.next();
                   }else{
                     variables += process.next() + ' ';
                   }
               }
               if(0 == _definitions.get( i ).getVariableCount()){
                  finalResult = finalResult.replaceAll( next, _definitions.get( i ).processDefinition( variables ) );
               }else{
                  finalResult = finalResult.replaceAll( next + ' ' + variables , _definitions.get( i ).processDefinition( variables ) );
               }
               variables = "";
            }
         }
      }

      return( finalResult );
   }

   public int size(){
      return( _definitions.size() );
   }

   public NoteMakerDefinition get( int index ){
      return( _definitions.get( index ) );
   }

   public void add( NoteMakerDefinition singleDefinition ){
      _definitions.add( singleDefinition );
   }

   public void remove( int index ){
      _definitions.remove( index );
   }

}


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

using Duality.Serialization;

namespace Duality.Tests.Serialization
{
	public enum SomeEnum
	{
		Zero,
		First,
		Second,
		Third
	}
	public struct TestData : IEquatable<TestData>
	{
		public int IntField;
		public float FloatField;
		public string StringField;
		public SomeEnum EnumField;

		public TestData(Random rnd)
		{
			this.IntField		= rnd.Next();
			this.FloatField		= rnd.NextFloat();
			this.StringField	= rnd.Next().ToString();
			this.EnumField		= (SomeEnum)rnd.Next(10);
		}

		public static bool operator ==(TestData first, TestData second)
		{
			return first.Equals(second);
		}
		public static bool operator !=(TestData first, TestData second)
		{
			return !first.Equals(second);
		}
		public override int GetHashCode()
		{
			return MathF.CombineHashCode(
				this.IntField.GetHashCode(),
				this.FloatField.GetHashCode(),
				this.StringField != null ? this.StringField.GetHashCode() : 0,
				this.EnumField.GetHashCode());
		}
		public override bool Equals(object obj)
		{
			if (obj is TestData)
				return this.Equals((TestData)obj);
			else
				return base.Equals(obj);
		}
		public bool Equals(TestData other)
		{
			return
				other.IntField == this.IntField &&
				other.FloatField == this.FloatField &&
				other.StringField == this.StringField &&
				other.EnumField == this.EnumField;
		}
	}
	public class TestObject : IEquatable<TestObject>
	{
		public string StringField;
		public Type TypeField;
		public Func<int,bool> DelegateField;
		public TestData DataField;
		public List<int> ListField;
		public List<string> ListField2;
		public Dictionary<string,TestObject> DictField;

		private TestObject() {}
		public TestObject(Random rnd, int childCount = 5)
		{
			this.StringField	= rnd.Next().ToString();
			this.TypeField		= rnd.OneOf(new[] { typeof(int), typeof(Component), typeof(GenericOperator) });
			this.DelegateField	= rnd.OneOf(new Func<int,bool>[] { DelegateA, DelegateB });
			this.DataField		= new TestData(rnd);
			this.ListField		= Enumerable.Range(rnd.Next(-1000, 1000), 50).ToList();
			this.ListField2		= Enumerable.Range(rnd.Next(-1000, 1000), 50).Select(i => i.ToString()).ToList();
			this.DictField		= new Dictionary<string,TestObject>();

			for (int i = childCount; i > 0; i--)
			{
				this.DictField.Add(rnd.Next().ToString(), new TestObject(rnd, childCount / 2));
			}
		}
		public static TestObject CreateBackwardsCompatible(Random rnd, int maxChildren = 5)
		{
			TestObject obj = new TestObject();

			obj.StringField	= rnd.Next().ToString();
			obj.TypeField		= rnd.OneOf(new[] { typeof(int), typeof(Component), typeof(GenericOperator) });
			obj.DelegateField	= rnd.OneOf(new Func<int,bool>[] { DelegateA, DelegateB });
			obj.DataField		= new TestData(rnd);
			obj.ListField		= Enumerable.Range(rnd.Next(-1000, 1000), rnd.Next(0, 50)).ToList();
			obj.ListField2		= Enumerable.Range(rnd.Next(-1000, 1000), rnd.Next(0, 50)).Select(i => i.ToString()).ToList();
			obj.DictField		= new Dictionary<string,TestObject>();

			for (int i = rnd.Next(0, maxChildren); i > 0; i--)
			{
				obj.DictField.Add(rnd.Next().ToString(), CreateBackwardsCompatible(rnd, maxChildren / 2));
			}

			return obj;
		}

		private static bool DelegateA(int v) { return false; }
		private static bool DelegateB(int v) { return true; }

		public static bool operator ==(TestObject first, TestObject second)
		{
			return first.Equals(second);
		}
		public static bool operator !=(TestObject first, TestObject second)
		{
			return !first.Equals(second);
		}
		public override bool Equals(object obj)
		{
			if (obj is TestObject)
				return this.Equals((TestObject)obj);
			else
				return base.Equals(obj);
		}
		public override int GetHashCode()
		{
			return base.GetHashCode();
		}
		public bool Equals(TestObject other)
		{
			return
				other.StringField == this.StringField &&
				other.TypeField == this.TypeField &&
				other.DelegateField == this.DelegateField &&
				other.DataField == this.DataField &&
				ListsEqual(other.ListField, this.ListField) &&
				ListsEqual(other.ListField2, this.ListField2) &&
				DictionariesEqual(other.DictField, this.DictField);
		}

		private static bool ListsEqual<T>(IList<T> first, IList<T> second)
		{
			if (object.ReferenceEquals(first, second)) return true;
			if (object.ReferenceEquals(first, null)) return false;
			if (object.ReferenceEquals(second, null)) return false;
			return first.SequenceEqual(second);
		}
		private static bool DictionariesEqual<T,U>(IDictionary<T,U> first, IDictionary<T,U> second)
		{
			if (object.ReferenceEquals(first, second)) return true;
			if (object.ReferenceEquals(first, null)) return false;
			if (object.ReferenceEquals(second, null)) return false;
			return first.SetEqual(second);
		}
	}
	public class MemberInfoTestObject
	{
		public int Field;
		public event EventHandler Event;
		public int Property { get { return 0; } }
		public int Method(string param) { return 0; }
		public MemberInfoTestObject() { }
	}
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Xml;
using System.Xml.Linq;
using Xunit;

namespace System.ServiceModel.Syndication.Tests
{
    public class SyndicationItemTests
    {
        [Fact]
        public void Ctor_Default()
        {
            var item = new SyndicationItem();
            Assert.Empty(item.AttributeExtensions);
            Assert.Empty(item.Authors);
            Assert.Null(item.BaseUri);
            Assert.Empty(item.Categories);
            Assert.Null(item.Content);
            Assert.Null(item.Copyright);
            Assert.Empty(item.ElementExtensions);
            Assert.Null(item.Id);
            Assert.Equal(default, item.LastUpdatedTime);
            Assert.Empty(item.Links);
            Assert.Equal(default, item.PublishDate);
            Assert.Null(item.SourceFeed);
            Assert.Null(item.Summary);
            Assert.Null(item.Title);
        }

        public static IEnumerable<object[]> Ctor_String_String_Uri_TestData()
        {
            yield return new object[] { null, null, null };
            yield return new object[] { "", "", new Uri("http://microsoft.com") };
            yield return new object[] { "title", "content", new Uri("/relative", UriKind.Relative) };
        }

        [Theory]
        [MemberData(nameof(Ctor_String_String_Uri_TestData))]
        public void Ctor_String_String_Uri(string title, string content, Uri itemAlternateLink)
        {
            var item = new SyndicationItem(title, content, itemAlternateLink);
            Assert.Empty(item.AttributeExtensions);
            Assert.Empty(item.Authors);
            Assert.Null(item.BaseUri);
            Assert.Empty(item.Categories);
            if (content == null)
            {
                Assert.Null(item.Content);
            }
            else
            {
                TextSyndicationContent textContent = Assert.IsType<TextSyndicationContent>(item.Content);
                Assert.Empty(textContent.AttributeExtensions);
                Assert.Equal(content, textContent.Text);
                Assert.Equal("text", textContent.Type);
            }
            Assert.Null(item.Copyright);
            Assert.Empty(item.ElementExtensions);
            Assert.Null(item.Id);
            Assert.Equal(default, item.LastUpdatedTime);
            if (itemAlternateLink == null)
            {
                Assert.Empty(item.Links);
            }
            else
            {
                SyndicationLink link = Assert.Single(item.Links);
                Assert.Empty(link.AttributeExtensions);
                Assert.Null(link.BaseUri);
                Assert.Empty(link.ElementExtensions);
                Assert.Equal(0, link.Length);
                Assert.Null(link.MediaType);
                Assert.Equal("alternate", link.RelationshipType);
                Assert.Null(link.Title);
                Assert.Equal(itemAlternateLink, link.Uri);
            }
            Assert.Equal(default, item.PublishDate);
            Assert.Null(item.SourceFeed);
            Assert.Null(item.Summary);

            if (title == null)
            {
                Assert.Null(item.Title);
            }
            else
            {
                Assert.Empty(item.Title.AttributeExtensions);
                Assert.Equal(title, item.Title.Text);
                Assert.Equal("text", item.Title.Type);
            }
        }

        public static IEnumerable<object[]> Ctor_String_String_Uri_String_DateTimeOffset_TestData()
        {
            yield return new object[] { null, null, null, null, default(DateTimeOffset) };
            yield return new object[] { "", "", new Uri("http://microsoft.com"), "", DateTimeOffset.Now };
            yield return new object[] { "title", "content", new Uri("/relative", UriKind.Relative), "id", DateTimeOffset.Now.AddDays(2) };
        }

        [Theory]
        [MemberData(nameof(Ctor_String_String_Uri_String_DateTimeOffset_TestData))]
        public void Ctor_String_String_Uri_String_DateTimeOffset(string title, string content, Uri itemAlternateLink, string id, DateTimeOffset lastUpdatedTime)
        {
            var item = new SyndicationItem(title, content, itemAlternateLink, id, lastUpdatedTime);
            Assert.Empty(item.AttributeExtensions);
            Assert.Empty(item.Authors);
            Assert.Null(item.BaseUri);
            Assert.Empty(item.Categories);
            if (content == null)
            {
                Assert.Null(item.Content);
            }
            else
            {
                TextSyndicationContent textContent = Assert.IsType<TextSyndicationContent>(item.Content);
                Assert.Empty(textContent.AttributeExtensions);
                Assert.Equal(content, textContent.Text);
                Assert.Equal("text", textContent.Type);
            }
            Assert.Null(item.Copyright);
            Assert.Empty(item.ElementExtensions);
            Assert.Equal(id, item.Id);
            Assert.Equal(lastUpdatedTime, item.LastUpdatedTime);
            if (itemAlternateLink == null)
            {
                Assert.Empty(item.Links);
            }
            else
            {
                SyndicationLink link = Assert.Single(item.Links);
                Assert.Empty(link.AttributeExtensions);
                Assert.Null(link.BaseUri);
                Assert.Empty(link.ElementExtensions);
                Assert.Equal(0, link.Length);
                Assert.Null(link.MediaType);
                Assert.Equal("alternate", link.RelationshipType);
                Assert.Null(link.Title);
                Assert.Equal(itemAlternateLink, link.Uri);
            }
            Assert.Equal(default, item.PublishDate);
            Assert.Null(item.SourceFeed);
            Assert.Null(item.Summary);

            if (title == null)
            {
                Assert.Null(item.Title);
            }
            else
            {
                Assert.Empty(item.Title.AttributeExtensions);
                Assert.Equal(title, item.Title.Text);
                Assert.Equal("text", item.Title.Type);
            }
        }

        public static IEnumerable<object[]> Ctor_String_SyndicationContent_Uri_String_DateTimeOffset_TestData()
        {
            yield return new object[] { null, null, null, null, default(DateTimeOffset) };
            yield return new object[] { "",  new TextSyndicationContent("text"), new Uri("http://microsoft.com"), "", DateTimeOffset.Now };
            yield return new object[] { "title", new TextSyndicationContent("text", TextSyndicationContentKind.XHtml), new Uri("/relative", UriKind.Relative), "id", DateTimeOffset.Now.AddDays(2) };
        }

        [Theory]
        [MemberData(nameof(Ctor_String_SyndicationContent_Uri_String_DateTimeOffset_TestData))]
        public void Ctor_String_SyndicationContent_Uri_String_DateTimeOffset(string title, SyndicationContent content, Uri itemAlternateLink, string id, DateTimeOffset lastUpdatedTime)
        {
            var item = new SyndicationItem(title, content, itemAlternateLink, id, lastUpdatedTime);
            Assert.Empty(item.AttributeExtensions);
            Assert.Empty(item.Authors);
            Assert.Null(item.BaseUri);
            Assert.Empty(item.Categories);
            Assert.Equal(content, item.Content);
            Assert.Null(item.Copyright);
            Assert.Empty(item.ElementExtensions);
            Assert.Equal(id, item.Id);
            Assert.Equal(lastUpdatedTime, item.LastUpdatedTime);
            if (itemAlternateLink == null)
            {
                Assert.Empty(item.Links);
            }
            else
            {
                SyndicationLink link = Assert.Single(item.Links);
                Assert.Empty(link.AttributeExtensions);
                Assert.Null(link.BaseUri);
                Assert.Empty(link.ElementExtensions);
                Assert.Equal(0, link.Length);
                Assert.Null(link.MediaType);
                Assert.Equal("alternate", link.RelationshipType);
                Assert.Null(link.Title);
                Assert.Equal(itemAlternateLink, link.Uri);
            }
            Assert.Equal(default, item.PublishDate);
            Assert.Null(item.SourceFeed);
            Assert.Null(item.Summary);

            if (title == null)
            {
                Assert.Null(item.Title);
            }
            else
            {
                Assert.Empty(item.Title.AttributeExtensions);
                Assert.Equal(title, item.Title.Text);
                Assert.Equal("text", item.Title.Type);
            }
        }

        [Fact]
        public void Ctor_SyndicationItem_Full()
        {
            var original = new SyndicationItem("title", new TextSyndicationContent("content", TextSyndicationContentKind.Html), new Uri("http://microsoft.com"), "id", DateTimeOffset.MinValue.AddTicks(10));
            original.AttributeExtensions.Add(new XmlQualifiedName("name"), "value");
            original.Authors.Add(new SyndicationPerson("email", "author", "uri"));
            original.BaseUri = new Uri("http://category_baseuri.com");
            original.Categories.Add(new SyndicationCategory("category"));
            original.Contributors.Add(new SyndicationPerson("name", "contributor", "uri"));
            original.Copyright = new TextSyndicationContent("copyright", TextSyndicationContentKind.Plaintext);
            original.ElementExtensions.Add(new ExtensionObject { Value = 10 });
            original.PublishDate = DateTimeOffset.MinValue.AddTicks(11);
            original.SourceFeed = new SyndicationFeed("title", "description", new Uri("http://microsoft.com"));
            original.Summary = new TextSyndicationContent("summary", TextSyndicationContentKind.Html);

            var clone = new SyndicationItemSubclass(original);
            Assert.NotSame(clone.AttributeExtensions, original.AttributeExtensions);
            Assert.Equal(1, clone.AttributeExtensions.Count);
            Assert.Equal("value", clone.AttributeExtensions[new XmlQualifiedName("name")]);

            Assert.NotSame(clone.Authors, original.Authors);
            Assert.Equal(1, clone.Authors.Count);
            Assert.NotSame(original.Authors[0], clone.Authors[0]);
            Assert.Equal("author", clone.Authors[0].Name);

            Assert.Equal(new Uri("http://category_baseuri.com"), original.BaseUri);

            Assert.NotSame(clone.Categories, original.Categories);
            Assert.Equal(1, clone.Categories.Count);
            Assert.NotSame(original.Categories[0], clone.Categories[0]);
            Assert.Equal("category", clone.Categories[0].Name);

            Assert.NotSame(clone.Content, original.Content);
            Assert.Equal("content", Assert.IsType<TextSyndicationContent>(clone.Content).Text);

            Assert.NotSame(clone.Contributors, original.Contributors);
            Assert.Equal(1, clone.Contributors.Count);
            Assert.NotSame(original.Contributors[0], clone.Contributors[0]);
            Assert.Equal("contributor", clone.Contributors[0].Name);

            Assert.NotSame(clone.Copyright, original.Copyright);
            Assert.Equal("copyright", clone.Copyright.Text);

            Assert.NotSame(clone.ElementExtensions, original.ElementExtensions);
            Assert.Equal(1, clone.ElementExtensions.Count);
            Assert.Equal(10, clone.ElementExtensions[0].GetObject<ExtensionObject>().Value);

            Assert.Equal("id", original.Id);

            Assert.Equal(DateTimeOffset.MinValue.AddTicks(10), original.LastUpdatedTime);

            Assert.NotSame(clone.Links, original.Links);
            Assert.Equal(1, clone.Links.Count);
            Assert.NotSame(original.Links[0], clone.Links[0]);
            Assert.Equal(new Uri("http://microsoft.com"), clone.Links[0].Uri);

            Assert.Equal(DateTimeOffset.MinValue.AddTicks(11), original.PublishDate);

            Assert.NotSame(clone.SourceFeed, original.SourceFeed);
            Assert.Equal("title", clone.SourceFeed.Title.Text);

            Assert.NotSame(clone.Summary, original.Summary);
            Assert.Equal("summary", clone.Summary.Text);

            Assert.NotSame(clone.Title, original.Title);
            Assert.Equal("title", clone.Title.Text);
        }

        [Fact]
        public void Ctor_SyndicationItem_Empty()
        {
            var original = new SyndicationItem();
            var clone = new SyndicationItemSubclass(original);
            Assert.Empty(clone.AttributeExtensions);
            Assert.Empty(clone.Authors);
            Assert.Null(clone.BaseUri);
            Assert.Empty(clone.Categories);
            Assert.Null(clone.Content);
            Assert.Null(clone.Copyright);
            Assert.Empty(clone.ElementExtensions);
            Assert.Null(clone.Id);
            Assert.Equal(default, clone.LastUpdatedTime);
            Assert.Empty(clone.Links);
            Assert.Equal(default, clone.PublishDate);
            Assert.Null(clone.SourceFeed);
            Assert.Null(clone.Summary);
            Assert.Null(clone.Title);
        }

        [Fact]
        public void Ctor_NullSource_ThrowsArgumentNullException()
        {
            AssertExtensions.Throws<ArgumentNullException>("source", () => new SyndicationItemSubclass(null));
        }

        [Fact]
        public void AddPermalink_ValidPermalink_AddsToLinks()
        {
            var permalink = new Uri("http://microsoft.com");
            var item = new SyndicationItem();
            item.AddPermalink(permalink);

            SyndicationLink link = Assert.Single(item.Links);
            Assert.Empty(link.AttributeExtensions);
            Assert.Null(link.BaseUri);
            Assert.Empty(link.ElementExtensions);
            Assert.Equal(0, link.Length);
            Assert.Null(link.MediaType);
            Assert.Equal("alternate", link.RelationshipType);
            Assert.Null(link.Title);
            Assert.Equal(permalink, link.Uri);
        }

        [Fact]
        public void AddPermalink_NullPermalink_ThrowsArgumentNullException()
        {
            var item = new SyndicationItem();
            AssertExtensions.Throws<ArgumentNullException>("permalink", () => item.AddPermalink(null));
        }

        [Fact]
        public void AddPermalink_RelativePermalink_ThrowsInvalidOperationException()
        {
            var permalink = new Uri("/microsoft", UriKind.Relative);
            var item = new SyndicationItem();
            Assert.Throws<InvalidOperationException>(() => item.AddPermalink(permalink));
        }

        [Fact]
        public void Load_NullReader_ThrowsArgumentNullException()
        {
            AssertExtensions.Throws<ArgumentNullException>("reader", () => SyndicationItem.Load(null));
            AssertExtensions.Throws<ArgumentNullException>("reader", () => SyndicationItem.Load<SyndicationItem>(null));
        }

        [Fact]
        public void Clone_Full_ReturnsExpected()
        {
            var original = new SyndicationItem("title", new TextSyndicationContent("content", TextSyndicationContentKind.Html), new Uri("http://microsoft.com"), "id", DateTimeOffset.MinValue.AddTicks(10));
            original.AttributeExtensions.Add(new XmlQualifiedName("name"), "value");
            original.Authors.Add(new SyndicationPerson("email", "author", "uri"));
            original.BaseUri = new Uri("http://category_baseuri.com");
            original.Categories.Add(new SyndicationCategory("category"));
            original.Contributors.Add(new SyndicationPerson("name", "contributor", "uri"));
            original.Copyright = new TextSyndicationContent("copyright", TextSyndicationContentKind.Plaintext);
            original.ElementExtensions.Add(new ExtensionObject { Value = 10 });
            original.PublishDate = DateTimeOffset.MinValue.AddTicks(11);
            original.SourceFeed = new SyndicationFeed("title", "description", new Uri("http://microsoft.com"));
            original.Summary = new TextSyndicationContent("summary", TextSyndicationContentKind.Html);

            SyndicationItem clone = original.Clone();
            Assert.NotSame(clone.AttributeExtensions, original.AttributeExtensions);
            Assert.Equal(1, clone.AttributeExtensions.Count);
            Assert.Equal("value", clone.AttributeExtensions[new XmlQualifiedName("name")]);

            Assert.NotSame(clone.Authors, original.Authors);
            Assert.Equal(1, clone.Authors.Count);
            Assert.NotSame(original.Authors[0], clone.Authors[0]);
            Assert.Equal("author", clone.Authors[0].Name);

            Assert.Equal(new Uri("http://category_baseuri.com"), original.BaseUri);

            Assert.NotSame(clone.Categories, original.Categories);
            Assert.Equal(1, clone.Categories.Count);
            Assert.NotSame(original.Categories[0], clone.Categories[0]);
            Assert.Equal("category", clone.Categories[0].Name);

            Assert.NotSame(clone.Content, original.Content);
            Assert.Equal("content", Assert.IsType<TextSyndicationContent>(clone.Content).Text);

            Assert.NotSame(clone.Contributors, original.Contributors);
            Assert.Equal(1, clone.Contributors.Count);
            Assert.NotSame(original.Contributors[0], clone.Contributors[0]);
            Assert.Equal("contributor", clone.Contributors[0].Name);

            Assert.NotSame(clone.Copyright, original.Copyright);
            Assert.Equal("copyright", clone.Copyright.Text);

            Assert.NotSame(clone.ElementExtensions, original.ElementExtensions);
            Assert.Equal(1, clone.ElementExtensions.Count);
            Assert.Equal(10, clone.ElementExtensions[0].GetObject<ExtensionObject>().Value);

            Assert.Equal("id", original.Id);

            Assert.Equal(DateTimeOffset.MinValue.AddTicks(10), original.LastUpdatedTime);

            Assert.NotSame(clone.Links, original.Links);
            Assert.Equal(1, clone.Links.Count);
            Assert.NotSame(original.Links[0], clone.Links[0]);
            Assert.Equal(new Uri("http://microsoft.com"), clone.Links[0].Uri);

            Assert.Equal(DateTimeOffset.MinValue.AddTicks(11), original.PublishDate);

            Assert.NotSame(clone.SourceFeed, original.SourceFeed);
            Assert.Equal("title", clone.SourceFeed.Title.Text);

            Assert.NotSame(clone.Summary, original.Summary);
            Assert.Equal("summary", clone.Summary.Text);

            Assert.NotSame(clone.Title, original.Title);
            Assert.Equal("title", clone.Title.Text);
        }

        [Fact]
        public void Clone_Empty_ReturnsExpected()
        {
            var original = new SyndicationItem();
            SyndicationItem clone = original.Clone();
            Assert.Empty(clone.AttributeExtensions);
            Assert.Empty(clone.Authors);
            Assert.Null(clone.BaseUri);
            Assert.Empty(clone.Categories);
            Assert.Null(clone.Content);
            Assert.Null(clone.Copyright);
            Assert.Empty(clone.ElementExtensions);
            Assert.Null(clone.Id);
            Assert.Equal(default, clone.LastUpdatedTime);
            Assert.Empty(clone.Links);
            Assert.Equal(default, clone.PublishDate);
            Assert.Null(clone.SourceFeed);
            Assert.Null(clone.Summary);
            Assert.Null(clone.Title);
        }

        [Fact]
        public void GetAtom10Formatter_Invoke_ReturnsExpected()
        {
            var item = new SyndicationItem();
            Atom10ItemFormatter formatter = Assert.IsType<Atom10ItemFormatter>(item.GetAtom10Formatter());
            Assert.Same(item, formatter.Item);
            Assert.True(formatter.PreserveAttributeExtensions);
            Assert.True(formatter.PreserveElementExtensions);
            Assert.Equal("Atom10", formatter.Version);
        }

        [Fact]
        public void GetRss20Formatter_Invoke_ReturnsExpected()
        {
            var item = new SyndicationItem();
            Rss20ItemFormatter formatter = Assert.IsType<Rss20ItemFormatter>(item.GetRss20Formatter());
            Assert.Same(item, formatter.Item);
            Assert.True(formatter.PreserveAttributeExtensions);
            Assert.True(formatter.PreserveElementExtensions);
            Assert.True(formatter.SerializeExtensionsAsAtom);
            Assert.Equal("Rss20", formatter.Version);
        }

        [Theory]
        [InlineData(true)]
        [InlineData(false)]
        public void GetRss20Formatter_Invoke_ReturnsExpected(bool serializeExtensionsAsAtom)
        {
            var item = new SyndicationItem();
            Rss20ItemFormatter formatter = Assert.IsType<Rss20ItemFormatter>(item.GetRss20Formatter(serializeExtensionsAsAtom));
            Assert.Same(item, formatter.Item);
            Assert.True(formatter.PreserveAttributeExtensions);
            Assert.True(formatter.PreserveElementExtensions);
            Assert.Equal(serializeExtensionsAsAtom, formatter.SerializeExtensionsAsAtom);
            Assert.Equal("Rss20", formatter.Version);
        }

        [Fact]
        public void CreateCategory_Invoke_ReturnsExpected()
        {
            var item = new SyndicationItemSubclass();
            SyndicationCategory category = item.CreateCategoryEntryPoint();
            Assert.Empty(category.AttributeExtensions);
            Assert.Empty(category.ElementExtensions);
            Assert.Null(category.Name);
            Assert.Null(category.Scheme);
            Assert.Null(category.Label);
        }

        [Fact]
        public void CreateLink_Invoke_ReturnsExpected()
        {
            var item = new SyndicationItemSubclass();
            SyndicationLink link = item.CreateLinkEntryPoint();
            Assert.Empty(link.AttributeExtensions);
            Assert.Null(link.BaseUri);
            Assert.Empty(link.ElementExtensions);
            Assert.Equal(0, link.Length);
            Assert.Null(link.MediaType);
            Assert.Null(link.RelationshipType);
            Assert.Null(link.Title);
            Assert.Null(link.Uri);
        }

        [Fact]
        public void CreatePerson_Invoke_ReturnsExpected()
        {
            var item = new SyndicationItemSubclass();
            SyndicationPerson person = item.CreatePersonEntryPoint();
            Assert.Empty(person.AttributeExtensions);
            Assert.Empty(person.ElementExtensions);
            Assert.Null(person.Email);
            Assert.Null(person.Name);
            Assert.Null(person.Uri);
        }

        [Theory]
        [InlineData(null, null, null, null)]
        [InlineData("", "", "", "")]
        [InlineData("name", "ns", "value", "version")]
        [InlineData("xmlns", "ns", "value", "version")]
        [InlineData("name", "http://www.w3.org/2000/xmlns/", "value", "version")]
        [InlineData("type", "ns", "value", "version")]
        [InlineData("name", "http://www.w3.org/2001/XMLSchema-instance", "value", "version")]
        public void TryParseAttribute_Invoke_ReturnsFalse(string name, string ns, string value, string version)
        {
            var item = new SyndicationItemSubclass();
            Assert.False(item.TryParseAttributeEntryPoint(name, ns, value, version));
        }

        public static IEnumerable<object[]> TryParseContent_TestData()
        {
            yield return new object[] { null, null, null };
            yield return new object[] { new XElement("name").CreateReader(), "", "" };
            yield return new object[] { new XElement("name").CreateReader(), "contentType", "version" };
        }

        [Theory]
        [MemberData(nameof(TryParseContent_TestData))]
        public void TryParseContent_Invoke_ReturnsFalse(XmlReader reader, string contentType, string version)
        {
            var item = new SyndicationItemSubclass();
            Assert.False(item.TryParseContentEntryPoint(reader, contentType, version, out SyndicationContent content));
            Assert.Null(content);
        }

        public static IEnumerable<object[]> TryParseElement_TestData()
        {
            yield return new object[] { null, null };
            yield return new object[] { new XElement("name").CreateReader(), "" };
            yield return new object[] { new XElement("name").CreateReader(), "version" };
        }

        [Theory]
        [MemberData(nameof(TryParseElement_TestData))]
        public void TryParseElement_Invoke_ReturnsFalse(XmlReader reader, string version)
        {
            var item = new SyndicationItemSubclass();
            Assert.False(item.TryParseElementEntryPoint(reader, version));
        }

        [Theory]
        [InlineData(null)]
        [InlineData("")]
        [InlineData("version")]
        public void WriteAttributeExtensions_Invoke_ReturnsExpected(string version)
        {
            var item = new SyndicationItemSubclass();
            CompareHelper.AssertEqualWriteOutput("", writer => item.WriteAttributeExtensionsEntryPoint(writer, version));

            item.AttributeExtensions.Add(new XmlQualifiedName("name1"), "value");
            item.AttributeExtensions.Add(new XmlQualifiedName("name2", "namespace"), "");
            item.AttributeExtensions.Add(new XmlQualifiedName("name3"), null);
            CompareHelper.AssertEqualWriteOutput(@"name1=""value"" d0p1:name2="""" name3=""""", writer => item.WriteAttributeExtensionsEntryPoint(writer, "version"));
        }

        [Fact]
        public void WriteAttributeExtensions_NullWriter_ThrowsArgumentNullException()
        {
            var item = new SyndicationItemSubclass();
            AssertExtensions.Throws<ArgumentNullException>("writer", () => item.WriteAttributeExtensionsEntryPoint(null, "version"));
        }

        [Theory]
        [InlineData(null)]
        [InlineData("")]
        [InlineData("version")]
        public void WriteElementExtensions_Invoke_ReturnsExpected(string version)
        {
            var item = new SyndicationItemSubclass();
            CompareHelper.AssertEqualWriteOutput("", writer => item.WriteElementExtensionsEntryPoint(writer, version));

            item.ElementExtensions.Add(new ExtensionObject { Value = 10 });
            item.ElementExtensions.Add(new ExtensionObject { Value = 11 });
            CompareHelper.AssertEqualWriteOutput(
@"<SyndicationItemTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests"">
    <Value>10</Value>
</SyndicationItemTests.ExtensionObject>
<SyndicationItemTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests"">
    <Value>11</Value>
</SyndicationItemTests.ExtensionObject>", writer => item.WriteElementExtensionsEntryPoint(writer, version));
        }

        [Fact]
        public void WriteElementExtensions_NullWriter_ThrowsArgumentNullException()
        {
            var item = new SyndicationItemSubclass();
            AssertExtensions.Throws<ArgumentNullException>("writer", () => item.WriteElementExtensionsEntryPoint(null, "version"));
        }

        private class SyndicationItemSubclass : SyndicationItem
        {
            public SyndicationItemSubclass() : base() { }

            public SyndicationItemSubclass(SyndicationItem source) : base(source) { }

            public SyndicationCategory CreateCategoryEntryPoint() => CreateCategory();

            public SyndicationLink CreateLinkEntryPoint() => CreateLink();

            public SyndicationPerson CreatePersonEntryPoint() => CreatePerson();

            public bool TryParseAttributeEntryPoint(string name, string ns, string value, string version) => TryParseAttribute(name, ns, value, version);

            public bool TryParseContentEntryPoint(XmlReader reader, string contentType, string version, out SyndicationContent content)
            {
                return TryParseContent(reader, contentType, version, out content);
            }

            public bool TryParseElementEntryPoint(XmlReader reader, string version) => TryParseElement(reader, version);

            public void WriteAttributeExtensionsEntryPoint(XmlWriter writer, string version) => WriteAttributeExtensions(writer, version);

            public void WriteElementExtensionsEntryPoint(XmlWriter writer, string version) => WriteElementExtensions(writer, version);
        }

        [DataContract]
        private class ExtensionObject
        {
            [DataMember]
            public int Value { get; set; }
        }
    }
}