text:
namespace qevercloud {

// Use this to get around strict aliasing rules.
// For example, uint64_t i = bitwise_cast<uint64_t>(returns_double());
// The most obvious implementation is to just cast a pointer,
// but that doesn't work.

// http://cellperformance.beyond3d.com/articles/2006/06/understanding-strict-aliasing.html
// http://stackoverflow.com/questions/98650/what-is-the-strict-aliasing-rule
// http://stackoverflow.com/questions/2906365/gcc-strict-aliasing-and-casting-through-a-union

// taken from thrift sources
template <typename To, typename From>
static inline To bitwise_cast(From from) {

  Q_STATIC_ASSERT_X(sizeof(From) == sizeof(To), "bitwise_cast: incompatible types");

  // BAD!!!  These are all broken with -O2.
  //return *reinterpret_cast<To*>(&from);  // BAD!!!
  //return *static_cast<To*>(static_cast<void*>(&from));  // BAD!!!
  //return *(To*)(void*)&from;  // BAD!!!

  // Super clean and partially blessed by section 3.9 of the standard.
  //unsigned char c[sizeof(from)];
  //memcpy(c, &from, sizeof(from));
  //To to;
  //memcpy(&to, c, sizeof(c));
  //return to;

  // Slightly more questionable.
  // Same code emitted by GCC.
  //To to;
  //memcpy(&to, &from, sizeof(from));
  //return to;

  // Technically undefined, but almost universally supported,
  // and the most efficient implementation.
  union {
    From f;
    To t;
  } u;
  u.f = from;
  return u.t;
}

struct ThriftFieldType {
    enum type {
      T_STOP       = 0,
      T_VOID       = 1,
      T_BOOL       = 2,
      T_BYTE       = 3,
      T_I08        = 3,
      T_I16        = 6,
      T_I32        = 8,
      T_U64        = 9,
      T_I64        = 10,
      T_DOUBLE     = 4,
      T_STRING     = 11,
      T_UTF7       = 11,
      T_STRUCT     = 12,
      T_MAP        = 13,
      T_SET        = 14,
      T_LIST       = 15,
      T_UTF8       = 16,
      T_UTF16      = 17
    };
};

struct ThriftMessageType {
    enum type {
      T_CALL       = 1,
      T_REPLY      = 2,
      T_EXCEPTION  = 3,
      T_ONEWAY     = 4
    };
};

static const qint32 VERSION_1 = ((qint32)0x80010000);
static const qint32 VERSION_MASK = ((qint32)0xffff0000);

class ThriftBinaryBufferWriter {
private:
    QByteArray buf;
    bool strict;

    void write(const quint8* bytes, const int bytesCount) {
        buf.append(reinterpret_cast<const char*>(bytes), bytesCount);
    }

public:
    ThriftBinaryBufferWriter(): strict(true) {}
    void setStrictMode(bool on) {strict = on;}

    QByteArray buffer() {return buf;}

    quint32 writeMessageBegin(QString name, const ThriftMessageType::type messageType, const qint32 seqid) {
        if (strict) {
          qint32 version = (VERSION_1) | ((qint32)messageType);
          quint32 wsize = 0;
          wsize += writeI32(version);
          wsize += writeString(name);
          wsize += writeI32(seqid);
          return wsize;
        } else {
          quint32 wsize = 0;
          wsize += writeString(name);
          wsize += writeByte((qint8)messageType);
          wsize += writeI32(seqid);
          return wsize;
        }
    }

    quint32 writeMessageEnd() {return 0;}

    inline quint32 writeStructBegin(QString name)
    {
        (void) name;
        return 0;
    }

    inline quint32 writeStructEnd() {return 0;}

    inline quint32 writeFieldBegin(QString name, const ThriftFieldType::type fieldType, const qint16 fieldId)
    {
        (void) name;
        quint32 wsize = 0;
        wsize += writeByte(static_cast<qint8>(fieldType));
        wsize += writeI16(fieldId);
        return wsize;
    }

    inline quint32 writeFieldEnd() {return 0;}
    inline quint32 writeFieldStop() {return writeByte((qint8)ThriftFieldType::T_STOP);}

    inline quint32 writeMapBegin(const ThriftFieldType::type keyType, const ThriftFieldType::type valType, const quint32 size)
    {
        quint32 wsize = 0;
        wsize += writeByte(static_cast<qint8>(keyType));
        wsize += writeByte(static_cast<qint8>(valType));
        wsize += writeI32(static_cast<qint32>(size));
        return wsize;
    }
    inline quint32 writeMapEnd() {return 0;}

    inline quint32 writeListBegin(const ThriftFieldType::type elemType, const quint32 size)
    {
        quint32 wsize = 0;
        wsize += writeByte(static_cast<qint8>(elemType));
        wsize += writeI32(static_cast<qint32>(size));
        return wsize;
    }
    inline quint32 writeListEnd() {return 0;}

    inline quint32 writeSetBegin(const ThriftFieldType::type elemType, const quint32 size)
    {
        return writeListBegin(elemType, size);
    }
    inline quint32 writeSetEnd() {return 0;}

    inline quint32 writeBool(bool value)
    {
        quint8 tmp = value ? 1 : 0;
        write(&tmp, 1);
        return 1;
    }

    inline quint32 writeByte(const qint8 byte)
    {
        write(reinterpret_cast<const quint8*>(&byte), 1);
        return 1;
    }

    inline quint32 writeI16(const qint16 i16)
    {
        qint16 net;
        qToBigEndian(i16, reinterpret_cast<uchar*>(&net));
        write(reinterpret_cast<const quint8*>(&net), 2);
        return 2;
    }

    inline quint32 writeI32(const qint32 i32)
    {
        qint32 net;
        qToBigEndian(i32, reinterpret_cast<uchar*>(&net));
        write(reinterpret_cast<const quint8*>(&net), 4);
        return 4;
    }

    inline quint32 writeI64(const qint64 i64)
    {
        qint64 net;
        qToBigEndian(i64, reinterpret_cast<uchar*>(&net));
        write(reinterpret_cast<const quint8*>(&net), 8);
        return 8;
    }

    inline quint32 writeDouble(const double dub)
    {
        Q_STATIC_ASSERT_X(sizeof(double) == sizeof(qint64) && std::numeric_limits<double>::is_iec559, "incompatible double type");

        qint64 bits = bitwise_cast<quint64>(dub);
        qToBigEndian(bits, reinterpret_cast<uchar*>(&bits));
        write(reinterpret_cast<quint8*>(&bits), 8);
        return 8;
    }

    inline quint32 writeString(const QString& str)
    {
        QByteArray utf8 = str.toUtf8();
        return writeBinary(utf8);
    }

    inline quint32 writeBinary(const QByteArray& bytes)
    {
        qint32 size = static_cast<qint32>(bytes.length());
        if(size > std::numeric_limits<qint32>::max()) {
            throw ThriftException(ThriftException::Type::PROTOCOL_ERROR, QStringLiteral("The data is too big"));
        }
        quint32 result = writeI32((qint32)size);
        if (size > 0) {
          write((const quint8*)bytes.constData(), size);
        }
        return result + size;
    }

};

class ThriftBinaryBufferReader {
    QByteArray buf;
    qint32 pos;
    qint32 stringLimit;
    bool strict;

    void read(quint8* dest, qint32 bytesCount) {
        if((pos + bytesCount) > buf.length()) {
            throw ThriftException(ThriftException::Type::PROTOCOL_ERROR, QStringLiteral("Unexpected end of data"));
        }
        std::memcpy(dest, buf.mid(pos, bytesCount).constData(), bytesCount);
        pos += bytesCount;
    }

public:

    ThriftBinaryBufferReader(QByteArray buffer): buf(buffer), pos(0), stringLimit(0), strict(false) {}
    void setStringLimit(qint32 limit) {stringLimit = limit;}
    void setStrictMode(bool on) {strict = on;}

    quint32 readMessageBegin(QString& name, ThriftMessageType::type& messageType, qint32& seqid)
    {
        quint32 result = 0;
        qint32 sz;
        result += readI32(sz);

        if (sz < 0) {
          // Check for correct version number
          qint32 version = sz & VERSION_MASK;
          if (version != VERSION_1) {
              throw ThriftException(ThriftException::Type::PROTOCOL_ERROR, QStringLiteral("Bad version identifier"));
          }
          messageType = static_cast<ThriftMessageType::type>(sz & 0x000000ff);
          result += readString(name);
          result += readI32(seqid);
        } else {
          if (strict) {
              throw ThriftException(ThriftException::Type::PROTOCOL_ERROR, QStringLiteral("No version identifier... old protocol client in strict mode?"));
          } else {
            // Handle pre-versioned input
            qint8 type;
            pos -= 4;
            result += readString(name);
            result += readByte(type);
            messageType = static_cast<ThriftMessageType::type>(type);
            result += readI32(seqid);
          }
        }
        return result;
    }

    quint32 readMessageEnd() {return 0;}

    inline quint32 readStructBegin(QString& name) {name = ""; return 0;}
    inline quint32 readStructEnd() {return 0;}
    inline quint32 readFieldBegin(QString& name, ThriftFieldType::type& fieldType, qint16& fieldId)
    {
        (void) name;
        quint32 result = 0;
        qint8 type;
        result += readByte(type);
        fieldType = static_cast<ThriftFieldType::type>(type);
        if (fieldType == ThriftFieldType::T_STOP) {
          fieldId = 0;
          return result;
        }
        result += readI16(fieldId);
        return result;
    }

    inline quint32 readFieldEnd() {return 0;}
    inline quint32 readMapBegin(ThriftFieldType::type& keyType, ThriftFieldType::type& valType, quint32& size)
    {
        qint8 k, v;
        quint32 result = 0;
        qint32 sizei;
        result += readByte(k);
        keyType = static_cast<ThriftFieldType::type>(k);
        result += readByte(v);
        valType = static_cast<ThriftFieldType::type>(v);
        result += readI32(sizei);
        if (sizei < 0) {
            throw ThriftException(ThriftException::Type::PROTOCOL_ERROR, QStringLiteral("Negative size!"));
        } else if (stringLimit > 0 && sizei > stringLimit) {
            throw ThriftException(ThriftException::Type::PROTOCOL_ERROR, QStringLiteral("The size limit is exceeded."));
        }
        size = (quint32)sizei;
        return result;
    }

    inline quint32 readMapEnd() {return 0;}
    inline quint32 readListBegin(ThriftFieldType::type& elemType, quint32& size)
    {
        qint8 e;
        quint32 result = 0;
        qint32 sizei;
        result += readByte(e);
        elemType = static_cast<ThriftFieldType::type>(e);
        result += readI32(sizei);
        if (sizei < 0) {
            throw ThriftException(ThriftException::Type::PROTOCOL_ERROR, QStringLiteral("Negative size!"));
        } else if (stringLimit > 0 && sizei > stringLimit) {
            throw ThriftException(ThriftException::Type::PROTOCOL_ERROR, QStringLiteral("The size limit is exceeded."));
        }
        size = (quint32)sizei;
        return result;
    }

    inline quint32 readListEnd() {return 0;}
    inline quint32 readSetBegin(ThriftFieldType::type& elemType, quint32& size) {return readListBegin(elemType, size);}
    inline quint32 readSetEnd() {return 0;}

    inline quint32 readBool(bool& value)
    {
        quint8 b[1];
        read(b, 1);
        value = *(qint8*)b != 0;
        return 1;
    }

    inline quint32 readByte(qint8& byte)
    {
        quint8 b[1];
        read(b, 1);
        byte = *(qint8*)b;
        return 1;
    }

    inline quint32 readI16(qint16& i16)
    {
        union bytes {
          quint8 b[2];
          qint16 all;
        } theBytes;
        read(theBytes.b, 2);
        i16 = qFromBigEndian<qint16>(theBytes.all);
        return 2;
    }

    inline quint32 readI32(qint32& i32)
    {
        union bytes {
          quint8 b[4];
          qint32 all;
        } theBytes;
        read(theBytes.b, 4);
        i32 = qFromBigEndian<qint32>(theBytes.all);
        return 4;
    }

    inline quint32 readI64(qint64& i64)
    {
        union bytes {
          quint8 b[8];
          qint64 all;
        } theBytes;
        read(theBytes.b, 8);
        i64 = qFromBigEndian<qint64>(theBytes.all);
        return 8;
    }

    inline quint32 readDouble(double& dub)
    {
        Q_STATIC_ASSERT_X(sizeof(double) == sizeof(qint64) && std::numeric_limits<double>::is_iec559, "incompatible double type");

        union bytes {
          quint8 b[8];
          qint64 all;
        } theBytes;
        read(theBytes.b, 8);
        theBytes.all = qFromBigEndian<qint64>(theBytes.all);
        dub = bitwise_cast<double>(theBytes.all);
        return 8;
    }

    inline quint32 readString(QString& str)
    {
        quint32 result;
        qint32 size;
        result = readI32(size);

        if (size < 0) {
            throw ThriftException(ThriftException::Type::PROTOCOL_ERROR, QStringLiteral("Negative size!"));
        }
        if (stringLimit > 0 && size > stringLimit) {
            throw ThriftException(ThriftException::Type::PROTOCOL_ERROR, QStringLiteral("The size limit is exceeded."));
        }

        // Catch empty string case
        if (size == 0) {
          str.clear();
          return result;
        }

        if((pos + size) > buf.length()) {
            throw ThriftException(ThriftException::Type::PROTOCOL_ERROR, QStringLiteral("Unexpected end of data"));
        }

        str = QString::fromUtf8(buf.constData() + pos, size);
        pos += size;
        result += size;

        return result;
    }

    inline quint32 readBinary(QByteArray& str)
    {
        quint32 result;
        qint32 size;
        result = readI32(size);

        if (size < 0) {
            throw ThriftException(ThriftException::Type::PROTOCOL_ERROR, QStringLiteral("Negative size!"));
        }
        if (stringLimit > 0 && size > stringLimit) {
            throw ThriftException(ThriftException::Type::PROTOCOL_ERROR, QStringLiteral("The size limit is exceeded."));
        }

        // Catch empty string case
        if (size == 0) {
          str.clear();
          return result;
        }

        if((pos + size) > buf.length()) {
            throw ThriftException(ThriftException::Type::PROTOCOL_ERROR, QStringLiteral("Unexpected end of data"));
        }

        str = buf.mid(pos, size);
        pos += size;
        result += size;

        return result;
    }

    inline quint32 skip(ThriftFieldType::type type)
    {
      switch (type) {
      case ThriftFieldType::T_BOOL:
        {
          bool boolv;
          return readBool(boolv);
        }
      case ThriftFieldType::T_BYTE:
        {
          qint8 bytev;
          return readByte(bytev);
        }
      case ThriftFieldType::T_I16:
        {
          qint16 i16;
          return readI16(i16);
        }
      case ThriftFieldType::T_I32:
        {
          qint32 i32;
          return readI32(i32);
        }
      case ThriftFieldType::T_I64:
        {
          qint64 i64;
          return readI64(i64);
        }
      case ThriftFieldType::T_DOUBLE:
        {
          double dub;
          return readDouble(dub);
        }
      case ThriftFieldType::T_STRING:
        {
          QByteArray str;
          return readBinary(str);
        }
      case ThriftFieldType::T_STRUCT:
        {
          quint32 result = 0;
          QString name;
          qint16 fid;
          ThriftFieldType::type ftype;
          result += readStructBegin(name);
          while (true) {
            result += readFieldBegin(name, ftype, fid);
            if (ftype == ThriftFieldType::T_STOP) {
              break;
            }
            result += skip(ftype);
            result += readFieldEnd();
          }
          result += readStructEnd();
          return result;
        }
      case ThriftFieldType::T_MAP:
        {
          quint32 result = 0;
          ThriftFieldType::type keyType;
          ThriftFieldType::type valType;
          quint32 i, size;
          result += readMapBegin(keyType, valType, size);
          for (i = 0; i < size; i++) {
            result += skip(keyType);
            result += skip(valType);
          }
          result += readMapEnd();
          return result;
        }
      case ThriftFieldType::T_SET:
        {
          quint32 result = 0;
          ThriftFieldType::type elemType;
          quint32 i, size;
          result += readSetBegin(elemType, size);
          for (i = 0; i < size; i++) {
            result += skip(elemType);
          }
          result += readSetEnd();
          return result;
        }
      case ThriftFieldType::T_LIST:
        {
          quint32 result = 0;
          ThriftFieldType::type elemType;
          quint32 i, size;
          result += readListBegin(elemType, size);
          for (i = 0; i < size; i++) {
            result += skip(elemType);
          }
          result += readListEnd();
          return result;
        }
      case ThriftFieldType::T_STOP:
      case ThriftFieldType::T_VOID:
      case ThriftFieldType::T_U64:
      case ThriftFieldType::T_UTF8:
      case ThriftFieldType::T_UTF16:
        break;
      }
      return 0;
    }

};

}

#endif // QEVERCLOUD_THRIFT_H


text:
package parser

// line parsers are dispatch calls that parse a single unit of text into a
// Node object which contains the whole statement. Dockerfiles have varied
// (but not usually unique, see ONBUILD for a unique example) parsing rules
// per-command, and these unify the processing in a way that makes it
// manageable.

import (
	"encoding/json"
	"errors"
	"fmt"
	"strconv"
	"strings"
)

var (
	errDockerfileJSONNesting = errors.New("You may not nest arrays in Dockerfile statements.")
)

// ignore the current argument. This will still leave a command parsed, but
// will not incorporate the arguments into the ast.
func parseIgnore(rest string) (*Node, map[string]bool, error) {
	return &Node{}, nil, nil
}

// used for onbuild. Could potentially be used for anything that represents a
// statement with sub-statements.
//
// ONBUILD RUN foo bar -> (onbuild (run foo bar))
//
func parseSubCommand(rest string) (*Node, map[string]bool, error) {
	_, child, err := parseLine(rest)
	if err != nil {
		return nil, nil, err
	}

	return &Node{Children: []*Node{child}}, nil, nil
}

// parse environment like statements. Note that this does *not* handle
// variable interpolation, which will be handled in the evaluator.
func parseEnv(rest string) (*Node, map[string]bool, error) {
	node := &Node{}
	rootnode := node
	strs := TOKEN_WHITESPACE.Split(rest, 2)

	if len(strs) < 2 {
		return nil, nil, fmt.Errorf("ENV must have two arguments")
	}

	node.Value = strs[0]
	node.Next = &Node{}
	node.Next.Value = strs[1]

	return rootnode, nil, nil
}

// parses a whitespace-delimited set of arguments. The result is effectively a
// linked list of string arguments.
func parseStringsWhitespaceDelimited(rest string) (*Node, map[string]bool, error) {
	node := &Node{}
	rootnode := node
	prevnode := node
	for _, str := range TOKEN_WHITESPACE.Split(rest, -1) { // use regexp
		prevnode = node
		node.Value = str
		node.Next = &Node{}
		node = node.Next
	}

	// XXX to get around regexp.Split *always* providing an empty string at the
	// end due to how our loop is constructed, nil out the last node in the
	// chain.
	prevnode.Next = nil

	return rootnode, nil, nil
}

// parsestring just wraps the string in quotes and returns a working node.
func parseString(rest string) (*Node, map[string]bool, error) {
	n := &Node{}
	n.Value = rest
	return n, nil, nil
}

// parseJSON converts JSON arrays to an AST.
func parseJSON(rest string) (*Node, map[string]bool, error) {
	var (
		myJson   []interface{}
		next     = &Node{}
		orignext = next
		prevnode = next
	)

	if err := json.Unmarshal([]byte(rest), &myJson); err != nil {
		return nil, nil, err
	}

	for _, str := range myJson {
		switch str.(type) {
		case string:
		case float64:
			str = strconv.FormatFloat(str.(float64), 'G', -1, 64)
		default:
			return nil, nil, errDockerfileJSONNesting
		}
		next.Value = str.(string)
		next.Next = &Node{}
		prevnode = next
		next = next.Next
	}

	prevnode.Next = nil

	return orignext, map[string]bool{"json": true}, nil
}

// parseMaybeJSON determines if the argument appears to be a JSON array. If
// so, passes to parseJSON; if not, quotes the result and returns a single
// node.
func parseMaybeJSON(rest string) (*Node, map[string]bool, error) {
	rest = strings.TrimSpace(rest)

	node, attrs, err := parseJSON(rest)

	if err == nil {
		return node, attrs, nil
	}
	if err == errDockerfileJSONNesting {
		return nil, nil, err
	}

	node = &Node{}
	node.Value = rest
	return node, nil, nil
}

// parseMaybeJSONToList determines if the argument appears to be a JSON array. If
// so, passes to parseJSON; if not, attmpts to parse it as a whitespace
// delimited string.
func parseMaybeJSONToList(rest string) (*Node, map[string]bool, error) {
	rest = strings.TrimSpace(rest)

	node, attrs, err := parseJSON(rest)

	if err == nil {
		return node, attrs, nil
	}
	if err == errDockerfileJSONNesting {
		return nil, nil, err
	}

	return parseStringsWhitespaceDelimited(rest)
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Threading;
using System.Threading.Tasks;

namespace Data.Net
{
    /// <inheritdoc />
    /// <summary>
    /// Generic database class for handling all db operations for any ADO.Net provider.
    /// </summary>
    public sealed class Database : IDisposable
    {
        private readonly IDbConnection _connection;

        private readonly IDbTransaction _transaction;

        private readonly bool _oracleProvider;

        /// <summary>
        ///     Initializes a new instance of the <see cref="Database" /> class.
        /// </summary>
        /// <param name="connection">Instance of <see cref="IDbConnection" /></param>
        public Database(IDbConnection connection)
        {
            _connection = connection ?? throw new ArgumentNullException(nameof(_connection));
            _oracleProvider = GetDbDataProvider(_connection.GetType().FullName);
        }

        /// <inheritdoc />
        /// <summary>
        /// Initializes a new instance of the <see cref="T:Data.Net.Database" /> class with Ado.Net Transaction object <see cref="T:System.Data.IDbTransaction" />.
        /// </summary>
        /// <param name="connection">Instance of <see cref="T:System.Data.IDbConnection" /></param>
        /// <param name="useTransaction">true, for creating db transaction</param>
        /// <param name="isolationLevel">Specify one of the isolation level <seealso cref="T:System.Data.IsolationLevel" /> </param>
        public Database(IDbConnection connection, bool useTransaction, IsolationLevel isolationLevel) : this(connection)
        {
            if (!useTransaction) return;

            if (_connection.State != ConnectionState.Open) _connection.Open();

            _transaction = _connection.BeginTransaction(isolationLevel);
        }

        /// <inheritdoc />
        /// <summary>
        /// Initializes a new instance of the <see cref="Database" /> class with Ado.Net Transaction object <see cref="IDbTransaction"/>.
        /// </summary>
        /// <param name="connection">Instance of <see cref="IDbConnection" /></param>
        /// <param name="useTransaction">true, for creating db transaction</param>
        public Database(IDbConnection connection, bool useTransaction) : this(connection, useTransaction, IsolationLevel.Unspecified) { }

#if NET461 || NET462 || NET47 || NET471 || NET472 || NET48
        /// <inheritdoc />
        /// <summary>
        /// Initializes a new instance of the <see cref="T:Data.Net.Database" /> class, ensure you have default connection string in the config file.
        /// </summary>
        public Database() : this(DbConnectionFactory.Connection) {}

        /// <inheritdoc />
        /// <summary>
        /// Initializes a new instance of the <see cref="T:Data.Net.Database" /> class.
        /// </summary>
        /// <param name="connectionStringName">The connection string name from web/app config</param>
        public Database(string connectionStringName) : this(DbConnectionFactory.OpenConnection(connectionStringName ?? throw new ArgumentNullException(nameof(connectionStringName)))) {}
#endif

        /// <inheritdoc />
        /// <summary>
        ///  Dispose Database connection and transaction objects.
        /// </summary>
        public void Dispose()
        {
            _transaction?.Dispose();
            _connection?.Close();
            _connection?.Dispose();
        }

        /// <summary>
        /// Executes a Transact-SQL statement and returns the number of rows affected by an insert,update or delete.
        /// </summary>
        /// <param name="sql">Transact-SQL statement</param>
        /// <param name="commandType">One of the command type of <see cref="CommandType" /></param>
        /// <param name="parameters">Parameter collection of <see cref="DataParameters" /> class.</param>
        /// <returns></returns>
        public int ExecuteNonQuery(string sql, CommandType commandType = CommandType.Text, DataParameters parameters = null)
        {
            using (var builder = new CommandBuilder(sql, _connection, _transaction, _oracleProvider, parameters, commandType))
            {
                var result = builder.Command.ExecuteNonQuery();
                builder.UpdateDataParameter();
                return result.ToValue<int>();
            }
        }

        /// <summary>
        /// Asynchronous version of Executes a Transact-SQL statement and returns the number of rows affected by an insert,update or delete.
        /// </summary>
        /// <param name="sql">Transact-SQL statement</param>
        /// <param name="commandType">One of the command type of <see cref="CommandType" /></param>
        /// <param name="parameters">Parameter collection of <see cref="DataParameters" /> class.</param>
        /// <param name="token">Cancellation token <see cref="CancellationToken" /></param>
        /// <returns></returns>
        public async Task<int> ExecuteNonQueryAsync(string sql, CommandType commandType = CommandType.Text, DataParameters parameters = null, CancellationToken token = default(CancellationToken))
        {
            using (var builder = new CommandBuilderAsync(sql, _connection, _oracleProvider, parameters, commandType))
            {
                if (builder.Command.Connection.State != ConnectionState.Open) await builder.Command.Connection.OpenAsync(token);

                if (_transaction != null) builder.Command.Transaction = _transaction as DbTransaction;

                var result = await builder.Command.ExecuteNonQueryAsync(token);

                builder.UpdateDataParameter();

                return result.ToValue<int>();
            }
        }

        /// <summary>
        /// Executes a Transact-SQL statement and returns a single value from the first row/column.
        /// </summary>
        /// <typeparam name="T">The return value type</typeparam>
        /// <param name="sql">Transact-SQL statement</param>
        /// <param name="commandType">One of the command type of <see cref="CommandType" /></param>
        /// <param name="parameters">Parameter collection of <see cref="DataParameters" /> class.</param>
        /// <returns></returns>
        public T ExecuteScalar<T>(string sql, CommandType commandType = CommandType.Text, DataParameters parameters = null)
        {
            using (var builder = new CommandBuilder(sql, _connection, _transaction, _oracleProvider, parameters, commandType))
            {
                var result = builder.Command.ExecuteScalar();
                builder.UpdateDataParameter();
                return result.ToValue<T>();
            }
        }

        /// <summary>
        /// Asynchronous version of Executes a Transact-SQL statement and returns a single value from the first row/column.
        /// </summary>
        /// <typeparam name="T">The return value type</typeparam>
        /// <param name="sql">Transact-SQL statement</param>
        /// <param name="commandType">One of the command type of <see cref="CommandType" /></param>
        /// <param name="parameters">Parameter collection of <see cref="DataParameters" /> class.</param>
        /// <param name="token">Cancellation token <see cref="CancellationToken" /></param>
        /// <returns></returns>
        public async Task<T> ExecuteScalarAsync<T>(string sql, CommandType commandType = CommandType.Text, DataParameters parameters = null, CancellationToken token = default(CancellationToken))
        {
            using (var builder = new CommandBuilderAsync(sql, _connection, _oracleProvider, parameters, commandType))
            {
                if (builder.Command.Connection.State != ConnectionState.Open) await builder.Command.Connection.OpenAsync(token);

                if (_transaction != null) builder.Command.Transaction = _transaction as DbTransaction;

                var result = await builder.Command.ExecuteScalarAsync(token);

                builder.UpdateDataParameter();

                return result.ToValue<T>();
            }
        }

        /// <summary>
        /// Execute a Transact-SQL statement and return a collection of <see cref="IDataReader" />
        /// </summary>
        /// <param name="sql">Transact-SQL statement</param>
        /// <param name="commandType">One of the command type of <see cref="CommandType" /></param>
        /// <param name="parameters">Parameter collection of <see cref="DataParameters" /> class.</param>
        /// <param name="behavior">One of the command behavior <see cref="CommandBehavior" /></param>
        /// <returns></returns>
        public IDataReader ExecuteReader(string sql, CommandType commandType = CommandType.Text,
            DataParameters parameters = null, CommandBehavior behavior = CommandBehavior.CloseConnection)
        {
            using (var builder = new CommandBuilder(sql, _connection, _transaction, _oracleProvider, parameters, commandType))
            {
                var reader = builder.Command.ExecuteReader(behavior);
                builder.UpdateDataParameter();
                return reader;
            }
        }

        /// <summary>
        /// Asynchronous version of Execute a Transact-SQL statement and return a collection of <see cref="IDataReader" />
        /// </summary>
        /// <param name="sql">Transact-SQL statement</param>
        /// <param name="commandType">One of the command type of <see cref="CommandType" /></param>
        /// <param name="parameters">Parameter collection of <see cref="DataParameters" /> class.</param>
        /// <param name="behavior">One of the command behavior <see cref="CommandBehavior" /></param>
        /// <param name="token">Cancellation token <see cref="CancellationToken" /></param>
        /// <returns></returns>
        public async Task<IDataReader> ExecuteReaderAsync(string sql, CommandType commandType = CommandType.Text,
            DataParameters parameters = null, CommandBehavior behavior = CommandBehavior.CloseConnection, CancellationToken token = default(CancellationToken))
        {
            using (var builder = new CommandBuilderAsync(sql, _connection, _oracleProvider, parameters, commandType))
            {
                if (builder.Command.Connection.State != ConnectionState.Open) await builder.Command.Connection.OpenAsync(token);

                if (_transaction != null) builder.Command.Transaction = _transaction as DbTransaction;

                var reader = await builder.Command.ExecuteReaderAsync(behavior, token);

                builder.UpdateDataParameter();

                return reader;
            }
        }

        /// <summary>
        /// Execute a Transact-SQL statement and return a collection of <see cref="List{T}" />
        /// </summary>
        /// <typeparam name="T">The return object type</typeparam>
        /// <param name="sql">Transact-SQL statement</param>
        /// <param name="commandType">One of the command type of <see cref="CommandType" /></param>
        /// <param name="parameters">Parameter collection of <see cref="DataParameters" /> class.</param>
        /// <param name="behavior">One of the command behavior <see cref="CommandBehavior" /></param>
        /// <returns></returns>
        public List<T> Query<T>(string sql, CommandType commandType = CommandType.Text, DataParameters parameters = null,
            CommandBehavior behavior = CommandBehavior.CloseConnection)
        {
            var list = default(List<T>);

            using (var builder = new CommandBuilder(sql, _connection, _transaction, _oracleProvider, parameters, commandType))
            {
                using (var reader = builder.Command.ExecuteReader(behavior))
                {
                    var row = new DataRowReader<T>(reader.FieldCount);

                    while (reader.Read())
                    {
                        var obj = row.ReaderToType(reader);

                        if (obj == null) continue;

                        if (list == default(List<T>)) list = new List<T>();

                        list.Add(obj);
                    }
                    row.Clear();
                }

                builder.UpdateDataParameter();
            }
            return list;
        }

        /// <summary>
        /// Execute a Transact-SQL statement and return a single object
        /// </summary>
        /// <typeparam name="T">The return object type</typeparam>
        /// <param name="sql">Transact-SQL statement</param>
        /// <param name="commandType">One of the command type of <see cref="CommandType" /></param>
        /// <param name="parameters">Parameter collection of <see cref="DataParameters" /> class.</param>
        /// <param name="behavior">One of the command behavior <see cref="CommandBehavior" /></param>
        /// <returns></returns>
        public T QuerySingle<T>(string sql, CommandType commandType = CommandType.Text, DataParameters parameters = null,
            CommandBehavior behavior = CommandBehavior.CloseConnection)
        {
            var result = default(T);

            using (var builder = new CommandBuilder(sql, _connection, _transaction, _oracleProvider, parameters, commandType))
            {
                using (var reader = builder.Command.ExecuteReader(behavior))
                {
                    if (reader.Read())
                    {
                        if (typeof(T).IsValueType || typeof(T) == typeof(string))
                            return reader.IsDBNull(0) ? default(T) : reader.GetValue(0).ToValue<T>();

                        var row = new DataRowReader<T>(reader.FieldCount);

                        result = row.ReaderToType(reader);

                        row.Clear();
                    }
                }

                builder.UpdateDataParameter();
            }

            return result;
        }

        /// <summary>
        /// Asynchronous version of Execute a Transact-SQL statement and return a single object
        /// </summary>
        /// <typeparam name="T">The return object type</typeparam>
        /// <param name="sql">Transact-SQL statement</param>
        /// <param name="commandType">One of the command type of <see cref="CommandType" /></param>
        /// <param name="parameters">Parameter collection of <see cref="DataParameters" /> class.</param>
        /// <param name="behavior">One of the command behavior <see cref="CommandBehavior" /></param>
        /// <param name="token">Cancellation token <see cref="CancellationToken" /></param>
        /// <returns></returns>
        public async Task<T> QuerySingleAsync<T>(string sql, CommandType commandType = CommandType.Text, DataParameters parameters = null,
            CommandBehavior behavior = CommandBehavior.CloseConnection, CancellationToken token = default(CancellationToken))
        {
            var result = default(T);

            using (var builder = new CommandBuilderAsync(sql, _connection, _oracleProvider, parameters, commandType))
            {
                if (builder.Command.Connection.State != ConnectionState.Open) await builder.Command.Connection.OpenAsync(token);

                if (_transaction != null) builder.Command.Transaction = _transaction as DbTransaction;

                using (var reader = await builder.Command.ExecuteReaderAsync(behavior, token))
                {
                    if (reader.Read())
                    {
                        if (typeof(T).IsValueType || typeof(T) == typeof(string))
                            return reader.IsDBNull(0) ? default(T) : reader.GetValue(0).ToValue<T>();

                        var row = new DataRowReader<T>(reader.FieldCount);

                        result = row.ReaderToType(reader);

                        row.Clear();
                    }
                }

                builder.UpdateDataParameter();
            }

            return result;
        }

        /// <summary>
        /// Commit a transaction
        /// </summary>
        public void CommitTransaction() => _transaction?.Commit();

        /// <summary>
        /// Rollback a transaction
        /// </summary>
        public void RollbackTransaction() => _transaction?.Rollback();

        private static bool GetDbDataProvider(string fullName) => fullName.IndexOf("Oracle.DataAccess", StringComparison.OrdinalIgnoreCase) == 0 ||
                                                                  fullName.IndexOf("Oracle.ManagedDataAccess", StringComparison.OrdinalIgnoreCase) == 0;
    }
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
Bidr. Känn. Finl. Nat. Folk 32: xxii, 415 (1879)

#### Original name
Phialocybe P. Karst.

### Remarks
null


text:
\documentclass[../../main.tex]{subfiles}

\begin{document}

\setcounter{secnumdepth}{0}

\chapter*{Conclusão}
\chaptermark{Conclusão}
\addcontentsline{toc}{chapter}{Conclusão}

A dissertação apresenta persistência em estruturas de dados, mostrando vários resultados dessa área, com atenção especial para a implementação destas estruturas de forma prática.

As implementações de deque apresentadas mostram como reduzir a complexidade pode complicar bastante a teoria e implementação de uma estrutura. Como indicado na Tabela~\ref{tab:deque_persist_comp}, para reduzir a complexidade de tempo de duas operações da deque, de logarítmico pra constante, foi necessário apresentar toda a teoria e código mais complexos do Capítulo~\ref{cap:deque3_persist}; e, na prática, com limites razoáveis para os computadores dos dias de hoje, esta solução fica mais lenta.

Apresentamos algumas técnicas gerais para tornar algumas classes de estruturas de dados em persistentes, e aplicamos algumas destas a estruturas conhecidas: apresentamos uma deque persistente que usa implementação funcional e uma árvore rubro-negra parcialmente persistente que usa node copying.

Por último, apresentamos uma aplicação de estruturas persistentes; a solução do problema de localização de ponto. É possível generalizar este tipo de solução, na qual fazemos uma linha de varredura com alguma estrutura de dados de forma offline, já que é possível utilizar uma versão parcialmente persistente da estrutura para respondermos as consultas de forma online.

\setcounter{secnumdepth}{1}

\end{document}


text:
<?php namespace Boss\Providers\Nwidart\DbExporter;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Config;

class DbExportHandlerServiceProvider extends ServiceProvider
{
    protected $defer = false;

    /**
     * @var DbMigrations $migrator
     */
    protected $migrator;

    /**
     * @var DbSeeding $seeder
     */
    protected $seeder;
    /**
     * @var DbExportHandler $handler
     */
    protected $handler;

    public function boot()
    {
        //$this->package('nwidart/db-exporter');
    }

    public function register()
    {
        // Load the classes
        $this->loadClasses();

        // Register the base export handler class
        $this->registerDbExportHandler();

        // Handle the artisan commands
        $this->registerCommands();

        // Load the alias
        $this->loadAlias();
    }

    /**
     * Load to classes
     */
    protected function loadClasses()
    {
        // Instatiate a new DbMigrations class to send to the handler
        $this->migrator = new DbMigrations($this->getDatabaseName());

        // Instatiate a new DbSeeding class to send to the handler
        $this->seeder = new DbSeeding($this->getDatabaseName());

        // Instantiate the handler
        $this->handler = new DbExportHandler($this->migrator, $this->seeder);
    }

    /**
     * Get the database name from the app/config/database.php file
     * @return String
     */
    private function getDatabaseName()
    {
        $connType = Config::get('database.default');
        $database = Config::get('database.connections.' .$connType );

        return $database['database'];
    }

    public function provides()
    {
        return array('DbExportHandler');
    }

    /**
     * Register the needed commands
     */
    public function registerCommands()
    {
        $this->registerMigrationsCommand();
        $this->registerSeedsCommand();
        $this->registerRemoteCommand();
        $this->commands(
            'dbe::migrations',
            'dbe::seeds',
            'dbe::remote'
        );
    }

    /**
     * Register the migrations command
     */
    protected function registerMigrationsCommand()
    {
        $this->app['dbe::migrations'] = $this->app->share(function()
        {
            return new Commands\MigrationsGeneratorCommand($this->handler);
        });
    }

    /**
     * Register the seeds command
     */
    protected function registerSeedsCommand()
    {
        $this->app['dbe::seeds'] = $this->app->share(function()
        {
            return new Commands\SeedGeneratorCommand($this->handler);
        });
    }

    protected function registerRemoteCommand()
    {
        $this->app['dbe::remote'] = $this->app->share(function()
        {
            return new Commands\CopyToRemoteCommand(new Server);
        });
    }

    /**
     * Register the Export handler class
     */
    protected function registerDbExportHandler()
    {
        $this->app['DbExportHandler'] = $this->app->share(function()
        {
            return $this->handler;
        });
    }

    /**
     * Load the alias = One less install step for the user
     */
    protected function loadAlias()
    {
        $this->app->booting(function()
        {
            $loader = \Illuminate\Foundation\AliasLoader::getInstance();
            $loader->alias('DbExportHandler', 'Boss\Providers\Nwidart\DbExporter\Facades\DbExportHandler');
        });
    }

}


text:
package org.projectfloodlight.protocol;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

import org.junit.Before;
import org.junit.Test;
import org.projectfloodlight.openflow.protocol.OFBundleAddMsg;
import org.projectfloodlight.openflow.protocol.OFFactories;
import org.projectfloodlight.openflow.protocol.OFFactory;
import org.projectfloodlight.openflow.protocol.OFFlowAdd;
import org.projectfloodlight.openflow.protocol.OFVersion;
import org.projectfloodlight.openflow.types.BundleId;

/** Custom tests that validate that BundleAdd messages inherit the XID from their
 *  contained message, as per OF Spec 1.4.0:
 *

 *  7.3.9.6 Adding messages to a bundle
 *

 *     Message added in a bundle should have a unique xid to help matching errors to messages,
 *     and the xid of the bundle add message must be the same.
 *

 *
 * @author Andreas Wundsam <andreas.wundsam@bigswitch.com>
 */
public class OFBundleAddTest {
    private final OFFactory factory = OFFactories.getFactory(OFVersion.OF_14);
    private OFFlowAdd flowAdd;

    @Before
    public void setup() {
        flowAdd = factory.buildFlowAdd().build();

    }

    @Test
    public void testBundleAddBuilder() {
        OFBundleAddMsg bundleAdd = createBundleAdd();
        assertThat(bundleAdd.getXid(), equalTo(flowAdd.getXid()));
    }

    private OFBundleAddMsg createBundleAdd() {
        return factory.buildBundleAddMsg()
                .setBundleId(BundleId.of(1))
                .setData(flowAdd)
                .build();
    }

    @Test
    public void testBundleAddBuilderWithParent() {
        OFBundleAddMsg bundleAdd = createBundleAdd();

        // validate BuilderWithParent
        OFBundleAddMsg builtFromOtherMessage = bundleAdd.createBuilder()
           .build();

        assertThat(builtFromOtherMessage.getXid(), equalTo(builtFromOtherMessage.getData().getXid()));
    }

    @Test
    public void testBundleAddBuilderWithParentOverwrite() {
        OFFlowAdd flowAdd2 = factory.buildFlowAdd().setXid(1234L).build();

        // BuilderWithParent, overwrite with new message
        OFBundleAddMsg bundleAdd = createBundleAdd();

        OFBundleAddMsg builtFromOtherMessage = bundleAdd.createBuilder()
           .setData(flowAdd2)
           .build();

        assertThat(builtFromOtherMessage.getXid(), equalTo(flowAdd2.getXid()));
    }

}


text:
package appeng.api.implementations.tiles;

import net.minecraft.inventory.IInventory;

public interface IViewCellStorage
{

	/**
	 * should contains at least 5 slot, the first 5
	 *
	 * @return inventory with at least 5 slot
	 */
	IInventory getViewCellStorage();

}


text:
package com.zanclus.nexus.manager;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLConnection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Deven Phillips
 *
 */
public class StaticContentServlet extends HttpServlet {

	/**
	 *
	 */
	private static final long serialVersionUID = -7883666352724679021L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		InputStream is =this.getClass().getResourceAsStream("classpath:"+req.getRequestURI());
		if (is==null) {
			resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
			resp.getOutputStream().close();
		} else {
			resp.setStatus(HttpServletResponse.SC_OK);
			resp.setHeader("Content-Type", URLConnection.guessContentTypeFromName(req.getRequestURI()));
			BufferedInputStream bis = new BufferedInputStream(is);
			OutputStream out = resp.getOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len=bis.read(buffer))>=0) {
				out.write(buffer, 0, len);
			}
			out.close();
		}
	}
}


text:
package com.intellij.openapi.editor;

import com.intellij.lang.html.HTMLLanguage;
import com.intellij.lang.xml.XMLLanguage;
import com.intellij.openapi.editor.colors.CodeInsightColors;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.colors.TextAttributesKey;

/**
 * @author yole
 */
public class XmlHighlighterColors {
  private XmlHighlighterColors() { }

  public static final TextAttributesKey XML_PROLOGUE =
    TextAttributesKey.createTextAttributesKey("XML_PROLOGUE", HighlighterColors.TEXT);
  public static final TextAttributesKey XML_COMMENT =
    TextAttributesKey.createTextAttributesKey("XML_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT);
  public static final TextAttributesKey XML_TAG =
    TextAttributesKey.createTextAttributesKey("XML_TAG", DefaultLanguageHighlighterColors.MARKUP_TAG);
  public static final TextAttributesKey XML_TAG_NAME =
    TextAttributesKey.createTextAttributesKey("XML_TAG_NAME", DefaultLanguageHighlighterColors.KEYWORD);
  public static final TextAttributesKey XML_NS_PREFIX =
    TextAttributesKey.createTextAttributesKey("XML_NS_PREFIX", DefaultLanguageHighlighterColors.INSTANCE_FIELD);
  public static final TextAttributesKey XML_ATTRIBUTE_NAME =
    TextAttributesKey.createTextAttributesKey("XML_ATTRIBUTE_NAME", DefaultLanguageHighlighterColors.MARKUP_ATTRIBUTE);
  public static final TextAttributesKey XML_ATTRIBUTE_VALUE =
    TextAttributesKey.createTextAttributesKey("XML_ATTRIBUTE_VALUE", DefaultLanguageHighlighterColors.STRING);
  public static final TextAttributesKey XML_TAG_DATA =
    TextAttributesKey.createTextAttributesKey("XML_TAG_DATA", HighlighterColors.TEXT);
  public static final TextAttributesKey XML_ENTITY_REFERENCE =
    TextAttributesKey.createTextAttributesKey("XML_ENTITY_REFERENCE", DefaultLanguageHighlighterColors.MARKUP_ENTITY);

  public static final TextAttributesKey HTML_COMMENT =
    TextAttributesKey.createTextAttributesKey("HTML_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT);
  public static final TextAttributesKey HTML_TAG =
    TextAttributesKey.createTextAttributesKey("HTML_TAG", DefaultLanguageHighlighterColors.MARKUP_TAG);
  public static final TextAttributesKey HTML_TAG_NAME =
    TextAttributesKey.createTextAttributesKey("HTML_TAG_NAME", DefaultLanguageHighlighterColors.KEYWORD);
  public static final TextAttributesKey HTML_ATTRIBUTE_NAME =
    TextAttributesKey.createTextAttributesKey("HTML_ATTRIBUTE_NAME", DefaultLanguageHighlighterColors.MARKUP_ATTRIBUTE);
  public static final TextAttributesKey HTML_ATTRIBUTE_VALUE =
    TextAttributesKey.createTextAttributesKey("HTML_ATTRIBUTE_VALUE", DefaultLanguageHighlighterColors.STRING);
  public static final TextAttributesKey HTML_ENTITY_REFERENCE =
    TextAttributesKey.createTextAttributesKey("HTML_ENTITY_REFERENCE", DefaultLanguageHighlighterColors.MARKUP_ENTITY);

  public static final TextAttributesKey HTML_CODE =
    TextAttributesKey.createTextAttributesKey("HTML_CODE", HighlighterColors.TEXT);

  public static final TextAttributesKey XML_INJECTED_LANGUAGE_FRAGMENT =
    EditorColors.createInjectedLanguageFragmentKey(XMLLanguage.INSTANCE);
  public static final TextAttributesKey HTML_INJECTED_LANGUAGE_FRAGMENT =
    EditorColors.createInjectedLanguageFragmentKey(HTMLLanguage.INSTANCE);

  public static final TextAttributesKey MATCHED_TAG_NAME =
    TextAttributesKey.createTextAttributesKey("MATCHED_TAG_NAME", CodeInsightColors.MATCHED_BRACE_ATTRIBUTES);
}


text:
<?php

namespace Dvsa\Mot\Frontend\SecurityCardModule\TemporarySignIn\ViewModel;

use Dvsa\Mot\Frontend\SecurityCardModule\LostOrForgottenCard\Controller\LostOrForgottenCardController;
use Zend\View\Model\ViewModel;

class ConfirmationViewModel extends ViewModel
{
    const GRACE_PERIOD_EXPIRES_WITHIN_ONE_DAY_WARNING_TEMPLATE = "You will not be able to sign in after %s on %s without a security card";
    const GRACE_PERIOD_EXPIRES_WARNING_TEMPLATE = "You have <strong>%d</strong> days remaining before you will be unable to sign in without a security card.";
    const VIEW_MODEL_GRACE_PERIOD_TOGGLE = 'gracePeriodToggleValue';
    const VIEW_MODEL_GRACE_PERIOD_WARNING_TEXT = 'gracePeriodWarningText';

    /** @var bool $isGracePeriodToggleOn */
    private $isGracePeriodToggleOn = false;
    /** @var \DateTime|null */
    private $gracePeriodExpirationDate = null;

    /**
     * @inheritdoc
     */
    public function __construct($variables = null, $options = null)
    {
        parent::__construct($variables, $options);
        $this->setTemplate(LostOrForgottenCardController::TEMPLATE_TEMP_SIGN_IN_CONFIRMATION);
    }

    /**
     * @param $showCardOrderLink
     */
    public function setShowCardOrderLink($showCardOrderLink)
    {
        $this->setVariable(LostOrForgottenCardController::VIEW_MODEL_PARAM_SHOW_CARD_ORDER_LINK, $showCardOrderLink);
    }

    /**
     * @param $ftValue
     */
    public function setGracePeriodFeatureToggleValue(bool $ftValue)
    {
        $this->isGracePeriodToggleOn = $ftValue;
        $this->setVariable(self::VIEW_MODEL_GRACE_PERIOD_TOGGLE, $ftValue);
    }

    /**
     * @return bool
     */
    public function isGracePeriodToggleOn()
    {
        return $this->isGracePeriodToggleOn();
    }

    /**
     * @param \DateTime $expirationDate
     */
    public function setGracePeriodExpirationDate(\DateTime $expirationDate)
    {
        $this->gracePeriodExpirationDate = $expirationDate;
    }

    /**
     * @return \DateTime|null
     */
    public function getGracePeriodExpirationDate()
    {
        return $this->gracePeriodExpirationDate;
    }

    public function setGracePeriodWarningText($text)
    {
        $this->setVariable(self::VIEW_MODEL_GRACE_PERIOD_WARNING_TEXT, $text);
    }

    /**
     * @return string
     */
    public function getGracePeriodWarningText()
    {
        if(false === $this->isGracePeriodToggleOn || null === $this->getGracePeriodExpirationDate()) {
            return '';
        }

        if ($this->gracePeriodExpiresWithinOneDay()) {
            $hourString = $this->gracePeriodExpirationDate->format('g:ia');
            $dateString = $this->gracePeriodExpirationDate->format('l jS F');
            return sprintf(self::GRACE_PERIOD_EXPIRES_WITHIN_ONE_DAY_WARNING_TEMPLATE, $hourString, $dateString);
        }
        else {
            $numberOfDaysLeft = $this->calculateNumberOfDaysLeft($this->gracePeriodExpirationDate);
            return sprintf(self::GRACE_PERIOD_EXPIRES_WARNING_TEMPLATE, $numberOfDaysLeft);
        }
    }

    /**
     * @return bool
     */
    private function gracePeriodExpiresWithinOneDay()
    {
        if(!$this->gracePeriodExpirationDate){
            return false;
        }

        $days = $this->calculateNumberOfDaysLeft($this->gracePeriodExpirationDate);
        if($days >= 1) {
            return false;
        }

        return true;
    }

    /**
     * @param \DateTime $gracePeriodExpirationDate
     * @return mixed
     */
    private function calculateNumberOfDaysLeft(\DateTime $gracePeriodExpirationDate)
    {
        //Todo: replace this with dateTimeHolder for better testability
        $now = new \DateTime('now', new \DateTimeZone('Europe/London'));
        $diff =  $now->diff($gracePeriodExpirationDate);
        return $diff->days;
    }

}


text:
package org.made.neohabitat.mods;

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

import org.elkoserver.foundation.json.JSONMethod;
import org.elkoserver.foundation.json.OptBoolean;
import org.elkoserver.foundation.json.OptInteger;
import org.elkoserver.foundation.json.OptString;
import org.elkoserver.json.EncodeControl;
import org.elkoserver.json.JSONLiteral;
import org.elkoserver.server.context.Context;
import org.elkoserver.server.context.ContextMod;
import org.elkoserver.server.context.ContextShutdownWatcher;
import org.elkoserver.server.context.Item;
import org.elkoserver.server.context.User;
import org.elkoserver.server.context.UserWatcher;
import org.elkoserver.util.ArgRunnable;
import org.made.neohabitat.Constants;
import org.made.neohabitat.Container;
import org.made.neohabitat.HabitatMod;
import org.made.neohabitat.Toggle;

/**
 * Habitat Region Mod (attached to a Elko Context)
 *
 * The Region has all the state and behaviors for the main object of Habitat. It
 * is the "room" logic, controlling how things interact with each other - not on
 * a Item to Item or User to User basis, but when interacting between multiple
 * objects in the region.
 *
 * @author randy
 *
 */

public class Region extends Container implements UserWatcher, ContextMod, ContextShutdownWatcher,  Constants {

    public static String    MOTD = "Welcome to Habitat! For help see http://neohabitat.org";

    /** Static flag on if new features should be activated. Anyone can toggle with //neohabitat */
    public static boolean   NEOHABITAT_FEATURES = true;

    /** The number of tokens to give to an avatar each new day that the user loggs in */
    public static final int STIPEND = 100;

    /** The default depth for a region. */
    public static final int DEFAULT_REGION_DEPTH = 32;

    /** The default maximum number of avatars for a Region. */
    public static final int DEFAULT_MAX_AVATARS = 6;

    /** Statics are shared amongst all regions */

    /** All the currently logged in user names for ESP lookup */
    public static Hashtable<String, User> NameToUser = new Hashtable<String, User>();

    /** All the currently instantiated regions for region transition testing  */
    public static Hashtable<String, Region> RefToRegion = new Hashtable<String, Region>();

    /** The last persisted C64 Heap Size for each region in this world */
    public static Hashtable<String, Integer> RefToHeap = new Hashtable<String, Integer>();

    public int HabitatClass() {
        return CLASS_REGION;
    }

    public String HabitatModName() {
        return "Region";
    }

    public int capacity() {
        return 255;
    }

    public int pc_state_bytes() {
        return 1;
    };

    public boolean known() {
        return true;
    }

    public boolean opaque_container() {
        return false;
    }

    public boolean filler() {
        return false;
    }

    /** A collection of server-side region status flags */
    public boolean    nitty_bits[] = new boolean[32];
    /** The lighting level in the room. 0 is Dark. */
    public int        lighting     = 0;
    /** The horizon line for the region to clip avatar motion */
    public int        depth        = DEFAULT_REGION_DEPTH;
    /** The maximum number of Avatars that can be in this Region */
    public int        max_avatars  = DEFAULT_MAX_AVATARS;

    /**
     * This is an array holding all the Mods for all the Users and Items in this
     * room.
     */
    public HabitatMod noids[]      = new HabitatMod[256];
    public int        nextNoid     = 1;
    public String     neighbors[]  = { "", "", "", "" };
    /** Direction to nearest Town */
    public String     town_dir     = "";
    /** Direction to nearest Teleport Booth */
    public String     port_dir     = "";

    public boolean is_turf  = false;
    public String  resident = "";
    public String  realm    = "unknown";
    public boolean locked   = false;

    /** A handle to the mandatory singleton ghost object for this region */

    @JSONMethod({ "style", "x", "y", "orientation", "gr_state", "nitty_bits", "depth", "lighting",
        "town_dir", "port_dir", "max_avatars", "neighbors", "is_turf", "resident", "realm", "locked", "shutdown_size" })
    public Region(OptInteger style, OptInteger x, OptInteger y, OptInteger orientation, OptInteger gr_state,
        OptInteger nitty_bits, OptInteger depth, OptInteger lighting,
        OptString town_dir, OptString port_dir, OptInteger max_avatars,
        String[] neighbors, OptBoolean is_turf, OptString resident, OptString realm,
        OptBoolean locked, OptInteger shutdown_size) {
        super(style, x, y, orientation, gr_state, new OptBoolean(false), shutdown_size);
        if (nitty_bits.value(-1) != -1) {
            this.nitty_bits = unpackBits(nitty_bits.value());
        }
        this.depth = depth.value(DEFAULT_REGION_DEPTH);
        this.lighting = lighting.value(0);
        this.max_avatars = max_avatars.value(DEFAULT_MAX_AVATARS);
        this.neighbors = neighbors;
        this.town_dir = town_dir.value("");
        this.port_dir = port_dir.value("");
        this.is_turf = is_turf.value(false);
        this.resident = resident.value("");
        this.realm = realm.value("unknown");
        this.locked = locked.value(false);
        this.noid = THE_REGION;
    }

    public Region(int style, int x, int y, int orientation, int gr_state, boolean[] nitty_bits,
        int depth, int lighting, String town_dir, String port_dir, int max_avatars,
        String[] neighbors, boolean is_turf, String resident, String realm, boolean locked, int shutdown_size) {
        super(style, x, y, orientation, gr_state, false, shutdown_size);
        this.nitty_bits = nitty_bits;
        this.depth = depth;
        this.lighting = lighting;
        this.max_avatars = max_avatars;
        this.neighbors = neighbors;
        this.town_dir = town_dir;
        this.port_dir = port_dir;
        this.is_turf = is_turf;
        this.resident = resident;
        this.realm = realm;
        this.locked = locked;
        this.noid = THE_REGION;
    }

    @Override
    public void objectIsComplete() {
        ((Context) object()).registerUserWatcher((UserWatcher) this);
        noids[THE_REGION] = this;
        note_object_creation(this);
        Region.RefToRegion.put(obj_id(), this);
    }

    public Ghost regionGhost() {
        return (Ghost) noids[GHOST_NOID];
    }

    public Ghost getGhost() {
        Ghost ghost = regionGhost();
        if (ghost == null) {
            ghost       = new Ghost(0, 4, 240, 0, 0, false);
            ghost.noid  = GHOST_NOID;
            create_object("Ghost", ghost, this, true);
            new Thread(announceGhostLater).start();
        }
        return ghost;
    }

    /**
     * It could be that the ghost is getting created at startup time, which is too soon to send messages to the clients.
     */
    protected Runnable announceGhostLater = new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(1000);
                announce_object(current_region().noids[GHOST_NOID].object(), current_region());
            } catch (InterruptedException neverHappens) {
                Thread.currentThread().interrupt();
            }
        }
    };

    public void destroyGhost(User from) {
        Ghost ghost = regionGhost();
        if (ghost != null) {
            if (from != null)
                send_neighbor_msg(from, THE_REGION, "GOAWAY_$", "target", GHOST_NOID);
            destroy_object(ghost);
        }
    }

    @Override
    public void noteContextShutdown() {
        destroyGhost(null);
        Region.RefToRegion.remove(obj_id());
    }

    public void noteUserArrival(User who) {
        Avatar avatar = (Avatar) who.getMod(Avatar.class);
        avatar.inc_record(HS$travel);
        int today = (int) (System.currentTimeMillis() / ONE_DAY);
        int time  = (int) (System.currentTimeMillis() % ONE_DAY);
        if (today > avatar.lastConnectedDay) {
            avatar.bankBalance += STIPEND;
            avatar.set_record(HS$wealth, avatar.bankBalance);
            avatar.inc_record(HS$lifetime);
        }
        avatar.lastArrivedIn        = context().baseRef();
        avatar.lastConnectedDay     = today;
        avatar.lastConnectedTime    = time;

        if(today > avatar.lastConnectedDay && avatar.health < MAX_HEALTH) {
            avatar.health += 25;
            if(avatar.health > MAX_HEALTH) {
                avatar.health = MAX_HEALTH;
            }
        }

        if (avatar.amAGhost) {
            getGhost().total_ghosts++; // Make sure the user has a ghost object..
        }
        if (avatar.firstConnection) {
            object_say(who, MOTD);
            if (NEOHABITAT_FEATURES) {
                if (NameToUser.size() < 2) {
                    object_say(who, UPGRADE_PREFIX + "You are the only one here right now.");
                } else {
                    object_say(who, UPGRADE_PREFIX + "There are " + (NameToUser.size() - 1) + " others here" +
                            (avatar.amAGhost ? "." : " Press F3 to see a list."));
                }
                if (avatar.amAGhost) {
                    object_say(who, UPGRADE_PREFIX + "You are a ghost. Press F1 to become an Avatar.");
                }
                tellEveryone(who.name() + " has arrived.");
            }
        }
        avatar.check_mail();
        Region.addUser(who);
    }

    public void noteUserDeparture(User who) {
        Region.removeUser(who);
        Avatar avatar = avatar(who);
        Ghost  ghost  = regionGhost();
        if (avatar.holding_restricted_object()) {
            avatar.heldObject().putMeBack(who, false);
        }
        if (avatar.amAGhost) {
            ghost.total_ghosts--;
            if (ghost.total_ghosts == 0) {
                destroyGhost(who);
            }
        } else {
            lights_off(avatar);
        }
        avatar.lastConnectedDay  = (int) (System.currentTimeMillis() / ONE_DAY);
        avatar.lastConnectedTime = (int) (System.currentTimeMillis() % ONE_DAY);
        avatar.gen_flags[MODIFIED] = true;
        avatar.checkpoint_object(avatar);
        gen_flags[MODIFIED] = true;
        checkpoint_object(this);		// Since we're now tracking heap usage between sessions, we need to update the region state.
    }

    private int avatarsPresent() {
        return class_ref_count[CLASS_AVATAR];
    }

    public synchronized static void addUser(User from) {
        NameToUser.put(from.name().toLowerCase(), from);
    }

    public synchronized static void removeUser(User from) {
        Avatar avatar = (Avatar) from.getMod(Avatar.class);
        NameToUser.remove(from.name().toLowerCase());
        removeContentsFromRegion(avatar);
        if (!avatar.amAGhost)
        	avatar.note_object_deletion(avatar);
        removeFromObjList(avatar);
    }

    public synchronized static List<Avatar> findOracles() {
        List<Avatar> oracleList = new ArrayList<>();
        for (User user : NameToUser.values()) {
            Avatar avatar = (Avatar) (user.getMod(Avatar.class));
            if (avatar.nitty_bits[GOD_FLAG]) {
                oracleList.add(avatar);
            }
        }
        return oracleList;
    }

    public static User getUserByName(String name) {
        if (name != null) {
            return (User) NameToUser.get(name.toLowerCase());
        }
        return null;
    }

    public static boolean IsRoomForMyAvatarIn(String regionRef, Avatar avatar) {
        Region target = Region.RefToRegion.get(regionRef);

        if (target != null)
        	return isRoomForMyAvatar(avatar, target);		// Region is instantiated, so ask that region for permission...

        // Region is "offline" - not instantiated - So we use the global store of region Heap sizes to consider rejecting the request.

        if (!RefToHeap.containsKey(regionRef))				// Never set, so there must be room. A region design constraint.
        	return true;									// TODO: RefToHeap loader at server boot to make this true across boots. FRF

        int heapAvatar = avatar.setContainerShutdownSize();
        int heapRegion = RefToHeap.get(regionRef);
        int heapRequired = heapAvatar + heapRegion + FIRST_AVATAR_HEAP_SIZE + FIRST_GHOST_HEAP_SIZE;

        if (heapRequired >= C64_HEAP_SIZE)
        	return false;          // There must be room for me, my stuff, a ghost, and whatever is already there...

        return true;

        // if there is no instantiated region, there must be room!
        // ERROR FALSE FALSE! GET newregion.shutdown_size add FIRST_AVATAR_HEAP_SIZE, avatar.shutdown_size, to compare to do normal memory tests.

    }

    // If the region we want to travel to is instantiated, we can do an in-memory check in the target region for the anticipated storage requried by the incoming avatar.
    public static boolean isRoomForMyAvatar(Avatar avatar, Region target) {

    	int    instanceSize = avatar.instance_size();		// If there are other avatars, we need only account for instance + contents.
    	int    bodies       = target.avatarsPresent();

    	if (bodies == target.max_avatars)							// TODO: Since multiple people can be between regions at once, this is currently a race. FRF
            return false;

        if (bodies == 0)
        	instanceSize = FIRST_AVATAR_HEAP_SIZE;			// If the region has only ghosts, we need to make a LOT of room.

        instanceSize += avatar.setContainerShutdownSize();

        if (target.space_usage + instanceSize >= target.c64_capacity())
            return false;

        return target.limits_ok(avatar, target); 				// Check the pocket contents for other overflows.

    }

    @Override
    public JSONLiteral encode(EncodeControl control) {
        JSONLiteral result = new JSONLiteral(HabitatModName(), control); // Normally I would call encodeCommon() but don't want to bother with the extraneous fields.
        result.addParameter("orientation", orientation);
        if (packBits(nitty_bits) != 0) {
            result.addParameter("nitty_bits", packBits(nitty_bits));
        }
        result.addParameter("depth", depth);
        result.addParameter("lighting", lighting);
        result.addParameter("neighbors", neighbors);
        result.addParameter("is_turf", is_turf);
        result.addParameter("realm", realm);
        if (control.toRepository()) {
            result.addParameter("max_avatars", max_avatars);
            result.addParameter("town_dir", town_dir);
            result.addParameter("port_dir", port_dir);
            result.addParameter("resident", resident);
            result.addParameter("locked", locked);
            result.addParameter("shutdown_size", space_usage);		// FRF TODO Is this correct at region shutdown or should I snapshot space_usage into shutdown_size elsewhere?
        }
        result.finish();
    	RefToHeap.put(object().baseRef(), space_usage);				// Update the "global" in-memory reference for the region's heap usage, in case it shuts down.
        return result;
    }

    private static int incNoid(int noid) {
        noid++;
        switch (noid) {
            case THE_REGION:
            case GHOST_NOID:
            case 256:
                return 1;
        }
        return noid;
    }

    /**
     * Add a HabitatMod to the object list for easy lookup by noid.
     * This method uses a monotonically increasing index, remembering
     * the previous noid assignment. Deleted objects will leave holes
     * that we are in no hurry to fill in. Note the reserved NOID ids
     * of THE_REGION (0) and GHOST_NOID (255).
     *
     * @param mod
     */
    public static boolean addToNoids(HabitatMod mod) {
        Region          region  = mod.current_region();
        int             noid    = region.nextNoid;
        HabitatMod[]    noids   = region.noids;

        if (region.nextNoid == -1) {
            return false; /* Too many things in this region!*/
        }

        noids[noid]     = mod;
        mod.noid        = noid;

        noid = incNoid(noid);

        while (null != noids[noid]) {
            noid = incNoid(noid);
            if (noid == region.nextNoid) {
                noid = -1;
                break;  // Searched everything, none free.
            }
        }
        region.nextNoid = noid;
        return true; // noid added, even if no
    }

    /**
     * Remove the noid from the object list.
     *
     * @param mod
     *            The object to remove from the noid list.
     */
    public static void removeFromObjList(HabitatMod mod) {
        if (mod.noid < UNASSIGNED_NOID) {
            mod.current_region().noids[mod.noid] = null;
            mod.noid = UNASSIGNED_NOID;
        }
    }

    /**
     * When items go away because their container left or closed, we must reclaim scarce resources: noids and
     *
     * @param cont
     */
    public static void removeContentsFromRegion(Container cont) {
    	cont.shutdown_size = cont.space_usage;								// Persist container/avatar client storage requirements before individual items are removed.
        for (int i = 0; i < cont.capacity(); i++) {
            HabitatMod obj = cont.contents(i);
            if (obj != null)
                removeObjectFromRegion(obj);
        }
    }

    public static void removeObjectFromRegion(HabitatMod obj) {
        if (obj == null)
            return;

        Container cont = obj.container();

        if (cont != null & obj.container_is_opaque(cont, obj.y)) {
            obj.note_instance_deletion(obj);
            obj.note_image_deletion(obj);
        } else {
            obj.note_object_deletion(obj);
        }

        removeFromObjList(obj);
    }

    public static void tellEveryone(String text) {
        tellEveryone(text, false);
    }

    public static void tellEveryone(String text, boolean shouldBeep) {
        for (String key: NameToUser.keySet()) {
            User    user    = NameToUser.get(key);
            Avatar  avatar  = (Avatar) user.getMod(Avatar.class);
            if (shouldBeep) {
                avatar.send_private_msg(user, THE_REGION, user, "PLAY_$",
                    "sfx_number", 8,
                    "from_noid", avatar.noid);
            }
            avatar.object_say(user, UPGRADE_PREFIX + text);
        }
    }

    public static void tellEveryone(int[] ascii) {
        tellEveryone(ascii, false);
    }

    public static void tellEveryone(int[] ascii, boolean shouldBeep) {
        for (String key: NameToUser.keySet()) {
            User        user    = NameToUser.get(key);
            Avatar      avatar  = (Avatar) user.getMod(Avatar.class);
            if (shouldBeep) {
                avatar.send_private_msg(user, THE_REGION, user, "PLAY_$",
                    "sfx_number", 8,
                    "from_noid", avatar.noid);
            }
            JSONLiteral msg     = avatar.new_private_msg(THE_REGION, "OBJECTSPEAK_$");
            int         send[]  = new int[ascii.length + 1];
            send[0] = UPGRADE_PREFIX.charAt(0);
            System.arraycopy(ascii, 0, send, 1, ascii.length);
            msg.addParameter("ascii", send);
            msg.addParameter("speaker", avatar.noid);
            msg.finish();
            user.send(msg);
        }
    }

    /**
     * The client is leaving the Habitat Application and wants to politely
     * disconnect.
     *
     * @param from
     *            The client disconnecting
     */
    @JSONMethod({ "reason" })
    public void LEAVE(User from, OptInteger reason) {
        if (reason.present()) {
            trace_msg("Client error " + CLIENT_ERRORS[reason.value()] + " reported by " + from.ref());
        }
        try {
            current_region().context().exit(from);
        } catch (Exception ignored) {
            trace_msg("Invalid attempt to leave by " + from.ref() + " failed: " + ignored.toString());
        }
    }

    /**
     * The client is slow and this might provide an advantage to others seeing a
     * new avatar before it can react. The server is told by this message that
     * it deal with messages before this as being before the user has appeared.
     *
     * @param from
     *            The client connection that needs to catch up...
     */
    @JSONMethod
    public void FINGER_IN_QUE(User from) {
        this.send_private_msg(from, 0, from, "CAUGHT_UP_$", "err", TRUE);
    }

    /**
     * Handle the client request to "appear" after the client is done loading
     * the region.
     *
     * @param from
     *            The client connection that has "caught up" loading the
     *            contents vector it just received.
     */
    @JSONMethod
    public void I_AM_HERE(User from) {
        Avatar who = avatar(from);
        who.gr_state &= ~INVISIBLE;
        who.showDebugInfo(from);
        send_broadcast_msg(0, "APPEARING_$", "appearing", who.noid);
        // If the avatar has any objects in their hands, perform any necessary side effects.
        lights_on(who);
    }

    public boolean grabable(HabitatMod mod) {
        if (nitty_bits[STEAL_FREE] |
            mod.HabitatClass() == CLASS_PAPER |
            mod.HabitatClass() == CLASS_BOOK |
            mod.HabitatClass() == CLASS_TOKENS |
            (mod.HabitatClass() == CLASS_MAGIC_LAMP && mod.gr_state == MAGIC_LAMP_GENIE)) {
            return false;
        }
        return true;
    }

    public void lights_off(Avatar avatar) {
        if (!empty_handed(avatar)) {
            HabitatMod light = avatar.contents(HANDS);
            if (light.HabitatClass() == CLASS_FLASHLIGHT) {
                if (((Toggle) light).on == TRUE) {
                    lighting -= 1;
                    send_broadcast_msg(THE_REGION, "CHANGELIGHT_$", "adjustment", -1);
                }
            }
        }
    }

    public void lights_on(Avatar avatar) {
        if (!empty_handed(avatar)) {
            HabitatMod held = avatar.contents(HANDS);
            /* If holding a flashheld.on entry, turn on the held. */
            if (held.HabitatClass() == CLASS_FLASHLIGHT) {
                if (((Toggle) held).on == TRUE) {
                    lighting += 1;
                    send_broadcast_msg(THE_REGION, "CHANGELIGHT_$", "adjustment", +1);
                }
            }
            /* If holding a compass, set the arrow pointer */
            if (held.HabitatClass() ==  CLASS_COMPASS) {
                held.gr_state = orientation;
                held.gen_flags[MODIFIED] = true;
            }
        }
    }

    /**
     * Handle request to change the Message of the Day.
     * Presently, this is a non-persistent change.
     *
     * @param from
     * @param MOTD
     */
    @JSONMethod ({ "MOTD" })
    public static void SET_MOTD(User from, String MOTD) {
        // TODO FRF Security is missing from this feature. Should this be a message on Admin/Session?
        Region.MOTD = MOTD;
    }

    /**
     * Handle request to send a word balloon message
     * to every user currently online.
     *
     * @param from
     * @param MOTD
     */
    @JSONMethod ({ "text", "ascii" })
    public void TELL_EVERYONE(User from, OptString text, int[] ascii) {
        // TODO FRF Security is missing from this feature. Should this be a message on Admin/Session?
        tellEveryone(" From: The Oracle   To: All Avatars: ");
        if (ascii != null) {
            tellEveryone(ascii);
        } else {
            tellEveryone(text.value("... nevermind ..."));
        }
    }

    /**
     * Handle a prompted message, overloading the text-entry field. This
     * requires some callback related storage in Avatar.
     *
     * @param from
     *            The user-connection that sent the prompt reply
     * @param text
     *            The prompt reply (includes any prompt.)
     */
    @JSONMethod({ "text" })
    public void PROMPT_REPLY(User from, OptString text) {
        String prompt = text.value("");
        String body = null;
        Avatar avatar = avatar(from);
        if (prompt.contains(GOD_TOOL_PROMPT)) {
            body = prompt.substring(GOD_TOOL_PROMPT.length());
            if (0 == body.length()) {
                avatar.savedMagical = null;
                avatar.savedTarget = null;
                return;
            }
            avatar.savedMagical.god_tool_revisited(from, body);
            return;
        }
    }

    public void describeRegion(User from, int noid) {
         String name_str = object().name();
         String help_str = "";
         if (name_str.isEmpty())
              help_str = "This region has no name";
         else
              help_str = "This region is " + name_str;

         if (!town_dir.isEmpty())
              help_str += ".  The nearest town is " + town_dir;

         if (!port_dir.isEmpty())
              help_str += ".  The nearest teleport booth is " + port_dir;

         help_str += ".";
            send_reply_msg(from, noid, "text", help_str);
    }
}


text:
///<reference path="FileDescriptor.ts"/>
///<reference path="IAdaptiveRPGroup.ts"/>
///<reference path="IBaseCallback.ts"/>
///<reference path="IFileDataStoreResultCallbackError.ts"/>
///<reference path="IFileDataStoreResultCallbackWarning.ts"/>

module Adaptive {

     /**
        Interface for Managing the File store operations callback

        @author Carlos Lozano Diez
        @since v2.0
        @version 1.0
     */
     /**
        @class Adaptive.IFileDataStoreResultCallback
     */
     export interface IFileDataStoreResultCallback extends IBaseCallback {
          /**
             @method
             Error processing data retrieval/storage operation.
             @param error Error condition encountered.
             @since v2.0
          */
          onError(error:IFileDataStoreResultCallbackError);
          /**
             @method
             Result of data storage operation.
             @param file File reference to stored data.
             @since v2.0
          */
          onResult(file:FileDescriptor);
          /**
             @method
             Result with warning of data retrieval/storage operation.
             @param file    File being loaded/stored.
             @param warning Warning condition encountered.
             @since v2.0
          */
          onWarning(file:FileDescriptor, warning:IFileDataStoreResultCallbackWarning);
     }
}

/**
------------------------------------| Engineered with ♥ in Barcelona, Catalonia |--------------------------------------
*/


text:
package com.lactozily.addict;

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.lactozily.addict.model.ProductHistory;
import com.lactozily.addict.model.ProductObject;

import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import io.realm.Realm;
import io.realm.RealmResults;

/**
 * Created by lactozily on 2/27/2016 AD.
 */
public class AddictMonitorService extends IntentService {
    public static final String TAG = AddictMonitorService.class.getSimpleName();
    public static final String NONE_PKG = "NONE_PKG";
    public static String CURRENT_APP;
    public static String PREVIOUS_APP;
    public static boolean updateQueryNeed = false;
    Realm realm;
    RealmResults<ProductObject> query;

    public AddictMonitorService() { super("addict-monitor-service"); }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "Start Monitoring");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        realm = Realm.getDefaultInstance();
        query = realm.allObjects(ProductObject.class);
        synchronized (this) {
            while (true) {
                try {
                    wait(700);

                    if(updateQueryNeed) {
                        updateQueryNeed = false;
                        Log.i("Query", "UpdateQuery");
                        Log.i("Query", query.toString());
                        break;
                    }

                    Log.i(TAG, "Monitoring");

                    if (AddictUtility.isScreenLocked(this)) {
                        Log.e(TAG, "Screen is locked");
                        CURRENT_APP = NONE_PKG;
                        continue;
                    }

                    CURRENT_APP = getCurrentPackage();
                    Log.i(TAG, "Current App: " + CURRENT_APP);

                    if (CURRENT_APP.equals(PREVIOUS_APP) || !hasPackage()) {
                        PREVIOUS_APP = CURRENT_APP;
                        Log.i(TAG, "SAME AS OR NO PKG");
                        Log.i(TAG, "Previous App: " + PREVIOUS_APP);
                        continue;
                    }

                    ProductObject productObject = query.where().equalTo("packageName", CURRENT_APP).findFirst();

                    Calendar cToday = AddictUtility.getStartTimeOfDate();
                    Calendar cTmr = AddictUtility.getEndTimeOfDate();
                    Calendar firstDateOfMonth = AddictUtility.getStartTimeOfMonth();
                    Calendar lastDateOfMonth = AddictUtility.getEndTimeOfMonth();

                    realm.beginTransaction();
                    ProductHistory history = new ProductHistory();
                    history.setTime(Calendar.getInstance().getTime());
                    productObject.getHistories().add(history);
                    productObject.setCounterAllTime(productObject.getHistories().size());
                    int counter = productObject.getHistories().where().between("time", cToday.getTime(), cTmr.getTime()).findAll().size();
                    int mCounter = productObject.getHistories().where().between("time", firstDateOfMonth.getTime(), lastDateOfMonth.getTime()).findAll().size();
                    productObject.setCounterDaily(counter);
                    productObject.setCounterMonthly(mCounter);
                    realm.commitTransaction();

                    checkUsage(counter, productObject.getProductName());
                    PREVIOUS_APP = CURRENT_APP;

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private boolean hasPackage() {
        if (query.where().equalTo("packageName", CURRENT_APP).findAll().size() == 0)
            return false;

        return true;
    }

    private String getCurrentPackage(){
        long ts = System.currentTimeMillis();
        UsageStatsManager mUsageStatsManager = (UsageStatsManager)getSystemService("usagestats");
        List<UsageStats> usageStats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, ts-10000, ts);
        if (usageStats == null || usageStats.size() == 0) {
            return NONE_PKG;
        }
        Collections.sort(usageStats, new RecentUseComparator());
        return usageStats.get(0).getPackageName();
    }

    static class RecentUseComparator implements Comparator<UsageStats> {
        @Override
        public int compare(UsageStats lhs, UsageStats rhs) {
            return (lhs.getLastTimeUsed() > rhs.getLastTimeUsed()) ? -1 : (lhs.getLastTimeUsed() == rhs.getLastTimeUsed()) ? 0 : 1;
        }
    }

    private void checkUsage(int counter, String name) {
        String text = name + " " + String.valueOf(counter) + " time today.";
        switch (counter) {
            case 20:
                notifyUsage(counter, name, "Be careful!", text);
                break;
            case 50:
                notifyUsage(counter, name, "Please, go get a life!", text);
                break;
            case 80:
                notifyUsage(counter, name, "You should stop now!", text);
                break;
            case 100:
                notifyUsage(counter, name, "RIP Real Life, GG EZ", text);
                break;
            default:
                return;
        }
    }

    //TODO: move this to NotificationService class or something like that.
    private void notifyUsage(int counter, String name, String title, String text) {
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_noti)
                .setContentTitle(title)
                .setContentText(text);

        int mNotificationId = 001;

        Intent resultIntent = new Intent(this, MainActivity.class);
        PendingIntent resultPendingIntent =
                PendingIntent.getActivity(
                        this,
                        0,
                        resultIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );
        mBuilder.setContentIntent(resultPendingIntent);

        NotificationManager mNotifyMgr =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        mNotifyMgr.notify(mNotificationId, mBuilder.build());
    }
}


text:
using FrameworkLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication.Admin.Controls
{
    public partial class SiteTree : System.Web.UI.UserControl
    {
        protected void Page_PreRender(object sender, EventArgs e)
        {
            var items = MediasMapper.GetDataModel().AllMedia.Where(i=>i.ParentMediaID == null).OrderBy(i=>i.OrderIndex);

            ListView.DataSource = items;
            ListView.DataBind();
        }

        protected void ListView_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            if (e.Item.DataItem == null)
                return;

            var media = (Media)e.Item.DataItem;
            var link = (HyperLink)e.Item.FindControl("Link");
            var childListView = (ListView)e.Item.FindControl("ChildListView");

            var mediaDetail = MediaDetailsMapper.GetAtleastOneByMedia(media, AdminBasePage.CurrentLanguage);

            if (mediaDetail != null)
            {
                link.Attributes.Add("data-mediaDetailId", mediaDetail.ID.ToString());
                link.Text = mediaDetail.SectionTitle;
                link.NavigateUrl = AdminBasePage.GetRedirectToMediaDetailUrl(mediaDetail.MediaTypeID, mediaDetail.MediaID);

                if(!mediaDetail.ShowInMenu)
                    link.CssClass +=" isHidden";

                if (mediaDetail.IsDeleted)
                    link.CssClass += " isDeleted";

                if (!mediaDetail.IsPublished)
                    link.CssClass += " unPublished";

                if (mediaDetail.ID == AdminBasePage.SelectedMediaDetail.ID)
                {
                    link.CssClass += " selected";
                    link.Attributes.Add("data-jstree", "{\"opened\":true,\"selected\":true}");
                }

            }
            else
            {
                link.Text = "MediaID:"+media.ID+" Does not have a media detail";
            }

            if (childListView != null)
            {
                childListView.DataSource = media.ChildMedias.OrderBy(i=>i.OrderIndex);
                childListView.LayoutTemplate = ListView.LayoutTemplate;
                childListView.ItemTemplate = ListView.ItemTemplate;
                childListView.DataBind();
            }
        }

        public AdminBasePage AdminBasePage
        {
            get
            {
                return (AdminBasePage)this.Page;
            }
        }
    }
}


text:
cachish
=======

Installs and configures [cachish](https://github.com/thusoy/cachish).

Pillar example:

```yaml
cachish:
    items:
        /myservice/database-url:
            module: Heroku
            parameters:
                api_token: mytoken
                app: myherokuapp
                config_key: DATABASE_URL

    auth:
        myservicetoken: /myservice/*
```


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
es5id: 15.4.4.14-9-b-i-14
description: >
    Array.prototype.indexOf - element to be retrieved is own accessor
    property that overrides an inherited accessor property on an
    Array-like object
---*/

        var obj = { length: 1 };

            Object.defineProperty(Object.prototype, "0", {
                get: function () {
                    return false;
                },
                configurable: true
            });

            Object.defineProperty(obj, "0", {
                get: function () {
                    return true;
                },
                configurable: true
            });

assert.sameValue(Array.prototype.indexOf.call(obj, true), 0, 'Array.prototype.indexOf.call(obj, true)');


text:
internal static partial class Interop
{
    internal class LuidOptions
    {
        // Access Control library.
        internal const uint ANONYMOUS_LOGON_LUID = 0x3e6;
    }

    internal class SecurityIdentifier
    {
        internal const int SECURITY_ANONYMOUS_LOGON_RID = 0x00000007;
        internal const int SECURITY_AUTHENTICATED_USER_RID = 0x0000000B;
        internal const int SECURITY_LOCAL_SYSTEM_RID = 0x00000012;
        internal const int SECURITY_BUILTIN_DOMAIN_RID = 0x00000020;
    }

    internal class SecurityGroups
    {
        internal const uint SE_GROUP_MANDATORY = 0x00000001;
        internal const uint SE_GROUP_ENABLED_BY_DEFAULT = 0x00000002;
        internal const uint SE_GROUP_ENABLED = 0x00000004;
        internal const uint SE_GROUP_OWNER = 0x00000008;
        internal const uint SE_GROUP_USE_FOR_DENY_ONLY = 0x00000010;
        internal const uint SE_GROUP_LOGON_ID = 0xC0000000;
        internal const uint SE_GROUP_RESOURCE = 0x20000000;
    }

    internal class DuplicateHandleOptions
    {
        internal const uint DUPLICATE_CLOSE_SOURCE = 0x00000001;
        internal const uint DUPLICATE_SAME_ACCESS = 0x00000002;
        internal const uint DUPLICATE_SAME_ATTRIBUTES = 0x00000004;
    }
}


text:
<!-- 水平直线布局 -->
<View style="@style/HorizontalLineTheme" />


text:
describe('When a <NavLink> is active', () => {
  it('applies its activeClassName')
  it('applies its activeStyle')
})

describe('When a <NavLink> is not active', () => {
  it('does not apply its activeClassName')
  it('does not apply its activeStyle')
})


text:
ubuntu-xenial64-mini-unity is a Unity Workspace based on the Ubuntu Xenial Server installation. It aims to provide the leanest Vagrant VM possible.

## Prerequisites
- VirtualBox
- Vagrant
- vagrant-vbguest Vagrant plugin


text:
package codingbat.warmup1;

//Given a string, return a new string where the first and last chars have been exchanged.
//
//frontBack("code") = "eodc"
//frontBack("a") = "a"
//frontBack("ab") = "ba"

public class FrontBackTest {

  public static void main(String[] args) {

    FrontBackTest test = new FrontBackTest();

    System.out.println(">" + test.frontBack("code") + "<");
    System.out.println(">" + test.frontBack("a") + "<");
    System.out.println(">" + test.frontBack("ab") + "<");
  }

  public String frontBack(String str) {
    if (str.length() > 0) {
      char[] strChars = str.toCharArray();
      char first = strChars[0];
      strChars[0] = strChars[strChars.length - 1];
      strChars[strChars.length - 1] = first;
      String result = new String(strChars);
      return result;
    }
    else {
      return str;
    }
  }

}


text:
layout: kanji-remain
v4: 2070
kanji: 皐
keyword: lunar month
strokes: 11
on-yomi: コウ
permalink: /rtk/皐/
---

## Koohii stories:

1) [synewave] 9-7-2007(20): To keep track of time on a desert island Tom Hanks puts a needle into the white part of his yin yang symbol every time a lunar month passes.

2) [ikmys] 13-4-2007(17): What's a lunar month? The amount of time it takes a white to read just ten pages of the I Ching. Reviewing the Kanji notwithstanding.

3) [astridtops] 8-11-2006(9): The I-Ching prophesy has spoken: "The next lunar month, white needles will bring you good luck.".

4) [to_nihon] 2-12-2008(4): White birds are our favorite 'other other other' white meat. We like to grill them at least ten times in a lunar month.

5) [kumakuma] 11-11-2008(4): The lunar month marks the beginning of our GRILL season. To celebrate this, we all show up dressed in WHITE at TEN a.m.


text:
class AddCompletedToTurns < ActiveRecord::Migration
  def change
    add_column(:turns, :completed, :boolean)
  end
end


text:
{% extends '_base.html' %}
{% load i18n %}{% load staticfiles %}

{% block content %}
    <link href="{% static "recipes/css/style.css" %}" rel="stylesheet">

                {% trans "Recipes" %}

{% trans "Edit recipe" %}

            {{ recipe.trigger.channel.name }}
            {{ recipe.trigger.name }}

            {{ recipe.action.channel.name }}
            {{ recipe.action.name }}

    <form action="{% url "recipes:edit" recipe.id %}" method="post">
        {% csrf_token %}

                    {% trans "Created" %} {{ recipe.creation_date }}

                    {% trans "Synopsis" %}
                    <textarea class="form-control"
                              id="synopsis"
                              name="synopsis"
                              rows="5">{{ recipe.synopsis }}</textarea>

{% trans "Trigger" %}

{{ recipe.trigger.name }}

                {% for condition in conditions %}

                    {{ condition.trigger_input.name }}
                    <input type="text"
                           id="condition_{{ condition.id }}"
                           name="condition_{{ condition.id }}"
                           class="form-control"
                           value="{{ condition.value }}">

                {% endfor %}

{% trans "Action" %}

{{ recipe.action.name }}

                {% for mapping in mappings %}

                    {{ mapping.action_input.name }}
                    {% if mapping.action_input.mime_type == "text" %}
                    <input type="text"
                           id="mapping_{{ mapping.id }}"
                           name="mapping_{{ mapping.id }}"
                           class="form-control"
                           data-bubble-input="{% for output in trigger_outputs %}{{ output.name }} {% endfor %}"
                           value="{{ mapping.trigger_output }}">
                    {% elif mapping.action_input.mime_type == "image" %}
                    <select name="mapping_{{ mapping.id }}"
                            id="mapping_{{ mapping.id }}"
                            class="form-control">
                        {% for output in trigger_outputs %}
                        {% if output.mime_type == "image" %}
                        <option value="%{{ output.name }}%">{{ output.name }}</option>
                        {% endif %}
                        {% endfor %}
                    </select>
                    {% elif mapping.action_input.mime_type == "video" %}
                    <select name="mapping_{{ mapping.id }}"
                            id="mapping_{{ mapping.id }}">
                        {% for output in trigger_outputs %}
                        {% if output.mime_type == "video" %}
                        <option value="%{{ output.name }}%">{{ output.name }}</option>
                        {% endif %}
                        {% endfor %}
                    </select>
                    {% endif %}

                {% endfor %}

                    <button id="recipe-save-btn" type="submit"
                            class="btn btn-primary btn-sm">{% trans "Save" %}

                    </button>

    </form>

{% endblock %}