text:
using QuickFix;
using LionFire.Trading.QuickFix.ConsoleTest.Fields;
namespace LionFire.Trading.QuickFix.ConsoleTest
{
    public class TradingSessionStatus : Message
    {
        public const string MsgType = "h";

        public TradingSessionStatus():base()
        {
            this.Header.SetField(new QuickFix.Fields.MsgType(MsgType));
        }
        public TradingSessionStatus(LionFire.Trading.QuickFix.ConsoleTest.Fields.TradingSessionID aTradingSessionID,
				LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesStatus aTradSesStatus)
               : this()
        {
            this.TradingSessionID = aTradingSessionID;
			this.TradSesStatus = aTradSesStatus;
        }

        public LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesReqID TradSesReqID
        {
            get
            {
                var val = new LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesReqID();
                GetField(val);
                return val;
            }
            set { SetField(value); }
        }

        public void Set(LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesReqID val) { this.TradSesReqID = val; }

        public LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesReqID Get(LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesReqID val)
        {
            GetField(val);
            return val;
        }

        public bool IsSet(LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesReqID val) { return IsSetTradSesReqID(); }

        public bool IsSetTradSesReqID() { return IsSetField(Tags.TradSesReqID); }

        public LionFire.Trading.QuickFix.ConsoleTest.Fields.TradingSessionID TradingSessionID
        {
            get
            {
                var val = new LionFire.Trading.QuickFix.ConsoleTest.Fields.TradingSessionID();
                GetField(val);
                return val;
            }
            set { SetField(value); }
        }

        public void Set(LionFire.Trading.QuickFix.ConsoleTest.Fields.TradingSessionID val) { this.TradingSessionID = val; }

        public LionFire.Trading.QuickFix.ConsoleTest.Fields.TradingSessionID Get(LionFire.Trading.QuickFix.ConsoleTest.Fields.TradingSessionID val)
        {
            GetField(val);
            return val;
        }

        public bool IsSet(LionFire.Trading.QuickFix.ConsoleTest.Fields.TradingSessionID val) { return IsSetTradingSessionID(); }

        public bool IsSetTradingSessionID() { return IsSetField(Tags.TradingSessionID); }

        public LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesMethod TradSesMethod
        {
            get
            {
                var val = new LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesMethod();
                GetField(val);
                return val;
            }
            set { SetField(value); }
        }

        public void Set(LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesMethod val) { this.TradSesMethod = val; }

        public LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesMethod Get(LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesMethod val)
        {
            GetField(val);
            return val;
        }

        public bool IsSet(LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesMethod val) { return IsSetTradSesMethod(); }

        public bool IsSetTradSesMethod() { return IsSetField(Tags.TradSesMethod); }

        public LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesMode TradSesMode
        {
            get
            {
                var val = new LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesMode();
                GetField(val);
                return val;
            }
            set { SetField(value); }
        }

        public void Set(LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesMode val) { this.TradSesMode = val; }

        public LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesMode Get(LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesMode val)
        {
            GetField(val);
            return val;
        }

        public bool IsSet(LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesMode val) { return IsSetTradSesMode(); }

        public bool IsSetTradSesMode() { return IsSetField(Tags.TradSesMode); }

        public LionFire.Trading.QuickFix.ConsoleTest.Fields.UnsolicitedIndicator UnsolicitedIndicator
        {
            get
            {
                var val = new LionFire.Trading.QuickFix.ConsoleTest.Fields.UnsolicitedIndicator();
                GetField(val);
                return val;
            }
            set { SetField(value); }
        }

        public void Set(LionFire.Trading.QuickFix.ConsoleTest.Fields.UnsolicitedIndicator val) { this.UnsolicitedIndicator = val; }

        public LionFire.Trading.QuickFix.ConsoleTest.Fields.UnsolicitedIndicator Get(LionFire.Trading.QuickFix.ConsoleTest.Fields.UnsolicitedIndicator val)
        {
            GetField(val);
            return val;
        }

        public bool IsSet(LionFire.Trading.QuickFix.ConsoleTest.Fields.UnsolicitedIndicator val) { return IsSetUnsolicitedIndicator(); }

        public bool IsSetUnsolicitedIndicator() { return IsSetField(Tags.UnsolicitedIndicator); }

        public LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesStatus TradSesStatus
        {
            get
            {
                var val = new LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesStatus();
                GetField(val);
                return val;
            }
            set { SetField(value); }
        }

        public void Set(LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesStatus val) { this.TradSesStatus = val; }

        public LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesStatus Get(LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesStatus val)
        {
            GetField(val);
            return val;
        }

        public bool IsSet(LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesStatus val) { return IsSetTradSesStatus(); }

        public bool IsSetTradSesStatus() { return IsSetField(Tags.TradSesStatus); }

        public LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesStartTime TradSesStartTime
        {
            get
            {
                var val = new LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesStartTime();
                GetField(val);
                return val;
            }
            set { SetField(value); }
        }

        public void Set(LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesStartTime val) { this.TradSesStartTime = val; }

        public LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesStartTime Get(LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesStartTime val)
        {
            GetField(val);
            return val;
        }

        public bool IsSet(LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesStartTime val) { return IsSetTradSesStartTime(); }

        public bool IsSetTradSesStartTime() { return IsSetField(Tags.TradSesStartTime); }

        public LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesOpenTime TradSesOpenTime
        {
            get
            {
                var val = new LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesOpenTime();
                GetField(val);
                return val;
            }
            set { SetField(value); }
        }

        public void Set(LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesOpenTime val) { this.TradSesOpenTime = val; }

        public LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesOpenTime Get(LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesOpenTime val)
        {
            GetField(val);
            return val;
        }

        public bool IsSet(LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesOpenTime val) { return IsSetTradSesOpenTime(); }

        public bool IsSetTradSesOpenTime() { return IsSetField(Tags.TradSesOpenTime); }

        public LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesPreCloseTime TradSesPreCloseTime
        {
            get
            {
                var val = new LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesPreCloseTime();
                GetField(val);
                return val;
            }
            set { SetField(value); }
        }

        public void Set(LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesPreCloseTime val) { this.TradSesPreCloseTime = val; }

        public LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesPreCloseTime Get(LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesPreCloseTime val)
        {
            GetField(val);
            return val;
        }

        public bool IsSet(LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesPreCloseTime val) { return IsSetTradSesPreCloseTime(); }

        public bool IsSetTradSesPreCloseTime() { return IsSetField(Tags.TradSesPreCloseTime); }

        public LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesCloseTime TradSesCloseTime
        {
            get
            {
                var val = new LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesCloseTime();
                GetField(val);
                return val;
            }
            set { SetField(value); }
        }

        public void Set(LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesCloseTime val) { this.TradSesCloseTime = val; }

        public LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesCloseTime Get(LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesCloseTime val)
        {
            GetField(val);
            return val;
        }

        public bool IsSet(LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesCloseTime val) { return IsSetTradSesCloseTime(); }

        public bool IsSetTradSesCloseTime() { return IsSetField(Tags.TradSesCloseTime); }

        public LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesEndTime TradSesEndTime
        {
            get
            {
                var val = new LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesEndTime();
                GetField(val);
                return val;
            }
            set { SetField(value); }
        }

        public void Set(LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesEndTime val) { this.TradSesEndTime = val; }

        public LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesEndTime Get(LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesEndTime val)
        {
            GetField(val);
            return val;
        }

        public bool IsSet(LionFire.Trading.QuickFix.ConsoleTest.Fields.TradSesEndTime val) { return IsSetTradSesEndTime(); }

        public bool IsSetTradSesEndTime() { return IsSetField(Tags.TradSesEndTime); }

        public LionFire.Trading.QuickFix.ConsoleTest.Fields.TotalVolumeTraded TotalVolumeTraded
        {
            get
            {
                var val = new LionFire.Trading.QuickFix.ConsoleTest.Fields.TotalVolumeTraded();
                GetField(val);
                return val;
            }
            set { SetField(value); }
        }

        public void Set(LionFire.Trading.QuickFix.ConsoleTest.Fields.TotalVolumeTraded val) { this.TotalVolumeTraded = val; }

        public LionFire.Trading.QuickFix.ConsoleTest.Fields.TotalVolumeTraded Get(LionFire.Trading.QuickFix.ConsoleTest.Fields.TotalVolumeTraded val)
        {
            GetField(val);
            return val;
        }

        public bool IsSet(LionFire.Trading.QuickFix.ConsoleTest.Fields.TotalVolumeTraded val) { return IsSetTotalVolumeTraded(); }

        public bool IsSetTotalVolumeTraded() { return IsSetField(Tags.TotalVolumeTraded); }

        public LionFire.Trading.QuickFix.ConsoleTest.Fields.Text Text
        {
            get
            {
                var val = new LionFire.Trading.QuickFix.ConsoleTest.Fields.Text();
                GetField(val);
                return val;
            }
            set { SetField(value); }
        }

        public void Set(LionFire.Trading.QuickFix.ConsoleTest.Fields.Text val) { this.Text = val; }

        public LionFire.Trading.QuickFix.ConsoleTest.Fields.Text Get(LionFire.Trading.QuickFix.ConsoleTest.Fields.Text val)
        {
            GetField(val);
            return val;
        }

        public bool IsSet(LionFire.Trading.QuickFix.ConsoleTest.Fields.Text val) { return IsSetText(); }

        public bool IsSetText() { return IsSetField(Tags.Text); }

        public LionFire.Trading.QuickFix.ConsoleTest.Fields.EncodedTextLen EncodedTextLen
        {
            get
            {
                var val = new LionFire.Trading.QuickFix.ConsoleTest.Fields.EncodedTextLen();
                GetField(val);
                return val;
            }
            set { SetField(value); }
        }

        public void Set(LionFire.Trading.QuickFix.ConsoleTest.Fields.EncodedTextLen val) { this.EncodedTextLen = val; }

        public LionFire.Trading.QuickFix.ConsoleTest.Fields.EncodedTextLen Get(LionFire.Trading.QuickFix.ConsoleTest.Fields.EncodedTextLen val)
        {
            GetField(val);
            return val;
        }

        public bool IsSet(LionFire.Trading.QuickFix.ConsoleTest.Fields.EncodedTextLen val) { return IsSetEncodedTextLen(); }

        public bool IsSetEncodedTextLen() { return IsSetField(Tags.EncodedTextLen); }

        public LionFire.Trading.QuickFix.ConsoleTest.Fields.EncodedText EncodedText
        {
            get
            {
                var val = new LionFire.Trading.QuickFix.ConsoleTest.Fields.EncodedText();
                GetField(val);
                return val;
            }
            set { SetField(value); }
        }

        public void Set(LionFire.Trading.QuickFix.ConsoleTest.Fields.EncodedText val) { this.EncodedText = val; }

        public LionFire.Trading.QuickFix.ConsoleTest.Fields.EncodedText Get(LionFire.Trading.QuickFix.ConsoleTest.Fields.EncodedText val)
        {
            GetField(val);
            return val;
        }

        public bool IsSet(LionFire.Trading.QuickFix.ConsoleTest.Fields.EncodedText val) { return IsSetEncodedText(); }

        public bool IsSetEncodedText() { return IsSetField(Tags.EncodedText); }

    }
}


text:
// Module:  Log4CPLUS
// File:    socket.h
// Created: 4/2003
// Author:  Tad E. Smith
//
//
// Copyright 2003-2009 Tad E. Smith
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/** @file */

#ifndef LOG4CPLUS_HELPERS_SOCKET_HEADER_
#define LOG4CPLUS_HELPERS_SOCKET_HEADER_

#include "dcmtk/oflog/config.h"
#include "dcmtk/oflog/tstring.h"
#include "dcmtk/oflog/helpers/sockbuff.h"
#if defined(_WIN32)
#include <winsock.h>
#endif

namespace log4cplus {
    namespace helpers {

        enum SocketState { ok,
                           not_opened,
                           bad_address,
                           connection_failed,
                           broken_pipe,
                           invalid_access_mode,
                           message_truncated
                         };

#if !defined(_WIN32)
        typedef int SOCKET_TYPE;
#define INVALID_SOCKET -1
#else
        typedef SOCKET SOCKET_TYPE;
#endif

        class LOG4CPLUS_EXPORT AbstractSocket {
        public:
          // ctor and dtor
            AbstractSocket();
            AbstractSocket(SOCKET_TYPE sock, SocketState state, int err);
            AbstractSocket(const AbstractSocket&);
            virtual ~AbstractSocket() = 0;

          // methods
            /// Close socket
            virtual void close();
            virtual bool isOpen() const;

            AbstractSocket& operator=(const AbstractSocket& rhs);

        protected:
          // Methods
            virtual void copy(const AbstractSocket& rhs);

          // Data
            SOCKET_TYPE sock;
            SocketState state;
            int err;
        };

        /**
         * This class implements client sockets (also called just "sockets").
         * A socket is an endpoint for communication between two machines.
         */
        class LOG4CPLUS_EXPORT Socket : public AbstractSocket {
        public:
          // ctor and dtor
            Socket();
            Socket(SOCKET_TYPE sock, SocketState state, int err);
            Socket(const tstring& address, int port);
            virtual ~Socket();

          // methods
            virtual bool read(SocketBuffer& buffer);
            virtual bool write(const SocketBuffer& buffer);
        };

        /**
         * This class implements server sockets. A server socket waits for
         * requests to come in over the network. It performs some operation
         * based on that request, and then possibly returns a result to the
         * requester.
         */
        class LOG4CPLUS_EXPORT ServerSocket : public AbstractSocket {
        public:
          // ctor and dtor
            ServerSocket(int port);
            virtual ~ServerSocket();

            Socket accept();
        };

        LOG4CPLUS_EXPORT SOCKET_TYPE openSocket(unsigned short port, SocketState& state);
        LOG4CPLUS_EXPORT SOCKET_TYPE connectSocket(const log4cplus::tstring& hostn,
                                                   unsigned short port, SocketState& state);
        LOG4CPLUS_EXPORT SOCKET_TYPE acceptSocket(SOCKET_TYPE sock, SocketState& state);
        LOG4CPLUS_EXPORT int closeSocket(SOCKET_TYPE sock);

        LOG4CPLUS_EXPORT long read(SOCKET_TYPE sock, SocketBuffer& buffer);
        LOG4CPLUS_EXPORT long write(SOCKET_TYPE sock, const SocketBuffer& buffer);

        LOG4CPLUS_EXPORT tstring getHostname (bool fqdn);

    } // end namespace helpers
} // end namespace log4cplus

#endif // LOG4CPLUS_HELPERS_SOCKET_HEADER_

redpajama_set_name: RedPajamaGithub


text:
namespace Qowaiv.UnitTests.Financial;

/// Tests the BIC SVO.
public class BusinessIdentifierCodeTest
{
    /// The test instance for most tests.
    public static readonly BusinessIdentifierCode TestStruct = BusinessIdentifierCode.Parse("AEGONL2UXXX");

    #region BIC const tests

    /// BusinessIdentifierCode.Empty should be equal to the default of BIC.
    [Test]
    public void Empty_None_EqualsDefault()
    {
        Assert.AreEqual(default(BusinessIdentifierCode), BusinessIdentifierCode.Empty);
    }

    #endregion

    #region BIC IsEmpty tests

    /// BusinessIdentifierCode.IsEmpty() should be true for the default of BIC.
    [Test]
    public void IsEmpty_Default_IsTrue()
    {
        Assert.IsTrue(default(BusinessIdentifierCode).IsEmpty());
    }
    /// BusinessIdentifierCode.IsEmpty() should be false for BusinessIdentifierCode.Unknown.
    [Test]
    public void IsEmpty_Unknown_IsFalse()
    {
        Assert.IsFalse(BusinessIdentifierCode.Unknown.IsEmpty());
    }
    /// BusinessIdentifierCode.IsEmpty() should be false for the TestStruct.
    [Test]
    public void IsEmpty_TestStruct_IsFalse()
    {
        Assert.IsFalse(TestStruct.IsEmpty());
    }

    /// BusinessIdentifierCode.IsUnknown() should be false for the default of BIC.
    [Test]
    public void IsUnknown_Default_IsFalse()
    {
        Assert.IsFalse(default(BusinessIdentifierCode).IsUnknown());
    }
    /// BusinessIdentifierCode.IsUnknown() should be true for BusinessIdentifierCode.Unknown.
    [Test]
    public void IsUnknown_Unknown_IsTrue()
    {
        Assert.IsTrue(BusinessIdentifierCode.Unknown.IsUnknown());
    }
    /// BusinessIdentifierCode.IsUnknown() should be false for the TestStruct.
    [Test]
    public void IsUnknown_TestStruct_IsFalse()
    {
        Assert.IsFalse(TestStruct.IsUnknown());
    }

    /// BusinessIdentifierCode.IsEmptyOrUnknown() should be true for the default of BIC.
    [Test]
    public void IsEmptyOrUnknown_Default_IsFalse()
    {
        Assert.IsTrue(default(BusinessIdentifierCode).IsEmptyOrUnknown());
    }
    /// BusinessIdentifierCode.IsEmptyOrUnknown() should be true for BusinessIdentifierCode.Unknown.
    [Test]
    public void IsEmptyOrUnknown_Unknown_IsTrue()
    {
        Assert.IsTrue(BusinessIdentifierCode.Unknown.IsEmptyOrUnknown());
    }
    /// BusinessIdentifierCode.IsEmptyOrUnknown() should be false for the TestStruct.
    [Test]
    public void IsEmptyOrUnknown_TestStruct_IsFalse()
    {
        Assert.IsFalse(TestStruct.IsEmptyOrUnknown());
    }

    #endregion

    #region TryParse tests

    /// TryParse null should be valid.
    [Test]
    public void TryParse_Null_IsValid()
    {
        string str = null;
        Assert.IsTrue(BusinessIdentifierCode.TryParse(str, out BusinessIdentifierCode val), "Valid");
        Assert.AreEqual(string.Empty, val.ToString(), "Value");
    }

    /// TryParse string.Empty should be valid.
    [Test]
    public void TryParse_StringEmpty_IsValid()
    {
        string str = string.Empty;
        Assert.IsTrue(BusinessIdentifierCode.TryParse(str, out BusinessIdentifierCode val), "Valid");
        Assert.AreEqual(string.Empty, val.ToString(), "Value");
    }

    /// TryParse "?" should be valid and the result should be BusinessIdentifierCode.Unknown.
    [Test]
    public void TryParse_Questionmark_IsValid()
    {
        string str = "?";
        Assert.IsTrue(BusinessIdentifierCode.TryParse(str, out BusinessIdentifierCode val), "Valid");
        Assert.IsTrue(val.IsUnknown(), "Value");
    }

    /// TryParse with specified string value should be valid.
    [Test]
    public void TryParse_StringValue_IsValid()
    {
        string str = "AEGONL2UXXX";
        Assert.IsTrue(BusinessIdentifierCode.TryParse(str, out BusinessIdentifierCode val), "Valid");
        Assert.AreEqual(str, val.ToString(), "Value");
    }

    /// TryParse with specified string value should be invalid.
    [Test]
    public void TryParse_StringValue_IsNotValid()
    {
        string str = "string";
        Assert.IsFalse(BusinessIdentifierCode.TryParse(str, out BusinessIdentifierCode val), "Valid");
        Assert.AreEqual(string.Empty, val.ToString(), "Value");
    }

    [Test]
    public void Parse_Unknown_AreEqual()
    {
        using (TestCultures.En_GB.Scoped())
        {
            var act = BusinessIdentifierCode.Parse("?");
            var exp = BusinessIdentifierCode.Unknown;
            Assert.AreEqual(exp, act);
        }
    }

    [Test]
    public void Parse_InvalidInput_ThrowsFormatException()
    {
        using (TestCultures.En_GB.Scoped())
        {
            Assert.Catch<FormatException>
            (() =>
            {
                BusinessIdentifierCode.Parse("InvalidInput");
            },
            "Not a valid BIC");
        }
    }

    [Test]
    public void TryParse_TestStructInput_AreEqual()
    {
        using (TestCultures.En_GB.Scoped())
        {
            var exp = TestStruct;
            var act = BusinessIdentifierCode.TryParse(exp.ToString());

            Assert.AreEqual(exp, act);
        }
    }

    [Test]
    public void from_invalid_as_null_with_TryParse()
       => BusinessIdentifierCode.TryParse("invalid input").Should().BeNull();

    #endregion

    #region (XML) (De)serialization tests

    [Test]
    public void GetObjectData_SerializationInfo_AreEqual()
    {
        ISerializable obj = TestStruct;
        var info = new SerializationInfo(typeof(BusinessIdentifierCode), new FormatterConverter());
        obj.GetObjectData(info, default);

        Assert.AreEqual(TestStruct.ToString(), info.GetString("Value"));
    }

    [Test]
    [Obsolete("Usage of the binary formatter is considered harmful.")]
    public void SerializeDeserialize_TestStruct_AreEqual()
    {
        var input = TestStruct;
        var exp = TestStruct;
        var act = SerializeDeserialize.Binary(input);
        Assert.AreEqual(exp, act);
    }
    [Test]
    public void DataContractSerializeDeserialize_TestStruct_AreEqual()
    {
        var input = TestStruct;
        var exp = TestStruct;
        var act = SerializeDeserialize.DataContract(input);
        Assert.AreEqual(exp, act);
    }

    [Test]
    public void XmlSerialize_TestStruct_AreEqual()
    {
        var act = Serialize.Xml(TestStruct);
        var exp = "AEGONL2UXXX";
        Assert.AreEqual(exp, act);
    }

    [Test]
    public void XmlDeserialize_XmlString_AreEqual()
    {
        var act =Deserialize.Xml<BusinessIdentifierCode>("AEGONL2UXXX");
        Assert.AreEqual(TestStruct, act);
    }

    [Test]
    [Obsolete("Usage of the binary formatter is considered harmful.")]
    public void SerializeDeserialize_BusinessIdentifierCodeSerializeObject_AreEqual()
    {
        var input = new BusinessIdentifierCodeSerializeObject
        {
            Id = 17,
            Obj = TestStruct,
            Date = new DateTime(1970, 02, 14),
        };
        var exp = new BusinessIdentifierCodeSerializeObject
        {
            Id = 17,
            Obj = TestStruct,
            Date = new DateTime(1970, 02, 14),
        };
        var act = SerializeDeserialize.Binary(input);
        Assert.AreEqual(exp.Id, act.Id, "Id");
        Assert.AreEqual(exp.Obj, act.Obj, "Obj");
        Assert.AreEqual(exp.Date, act.Date, "Date");
    }
    [Test]
    public void XmlSerializeDeserialize_BusinessIdentifierCodeSerializeObject_AreEqual()
    {
        var input = new BusinessIdentifierCodeSerializeObject
        {
            Id = 17,
            Obj = TestStruct,
            Date = new DateTime(1970, 02, 14),
        };
        var exp = new BusinessIdentifierCodeSerializeObject
        {
            Id = 17,
            Obj = TestStruct,
            Date = new DateTime(1970, 02, 14),
        };
        var act = SerializeDeserialize.Xml(input);
        Assert.AreEqual(exp.Id, act.Id, "Id");
        Assert.AreEqual(exp.Obj, act.Obj, "Obj");
        Assert.AreEqual(exp.Date, act.Date, "Date");
    }
    [Test]
    public void DataContractSerializeDeserialize_BusinessIdentifierCodeSerializeObject_AreEqual()
    {
        var input = new BusinessIdentifierCodeSerializeObject
        {
            Id = 17,
            Obj = TestStruct,
            Date = new DateTime(1970, 02, 14),
        };
        var exp = new BusinessIdentifierCodeSerializeObject
        {
            Id = 17,
            Obj = TestStruct,
            Date = new DateTime(1970, 02, 14),
        };
        var act = SerializeDeserialize.DataContract(input);
        Assert.AreEqual(exp.Id, act.Id, "Id");
        Assert.AreEqual(exp.Obj, act.Obj, "Obj");
        Assert.AreEqual(exp.Date, act.Date, "Date");
    }

    [Test]
    [Obsolete("Usage of the binary formatter is considered harmful.")]
    public void SerializeDeserialize_Empty_AreEqual()
    {
        var input = new BusinessIdentifierCodeSerializeObject
        {
            Id = 17,
            Obj = BusinessIdentifierCode.Empty,
            Date = new DateTime(1970, 02, 14),
        };
        var exp = new BusinessIdentifierCodeSerializeObject
        {
            Id = 17,
            Obj = BusinessIdentifierCode.Empty,
            Date = new DateTime(1970, 02, 14),
        };
        var act = SerializeDeserialize.Binary(input);
        Assert.AreEqual(exp.Id, act.Id, "Id");
        Assert.AreEqual(exp.Obj, act.Obj, "Obj");
        Assert.AreEqual(exp.Date, act.Date, "Date");
    }
    [Test]
    public void XmlSerializeDeserialize_Empty_AreEqual()
    {
        var input = new BusinessIdentifierCodeSerializeObject
        {
            Id = 17,
            Obj = BusinessIdentifierCode.Empty,
            Date = new DateTime(1970, 02, 14),
        };
        var exp = new BusinessIdentifierCodeSerializeObject
        {
            Id = 17,
            Obj = BusinessIdentifierCode.Empty,
            Date = new DateTime(1970, 02, 14),
        };
        var act = SerializeDeserialize.Xml(input);
        Assert.AreEqual(exp.Id, act.Id, "Id");
        Assert.AreEqual(exp.Obj, act.Obj, "Obj");
        Assert.AreEqual(exp.Date, act.Date, "Date");
    }

    [Test]
    public void GetSchema_None_IsNull()
    {
        IXmlSerializable obj = TestStruct;
        Assert.IsNull(obj.GetSchema());
    }

    #endregion

    #region IFormattable / ToString tests

    [Test]
    public void ToString_Empty_StringEmpty()
    {
        var act = BusinessIdentifierCode.Empty.ToString();
        var exp = "";
        Assert.AreEqual(exp, act);
    }

    [Test]
    public void ToString_Unknown_QuestionMark()
    {
        var act = BusinessIdentifierCode.Unknown.ToString();
        var exp = "?";
        Assert.AreEqual(exp, act);
    }

    [Test]
    public void ToString_CustomFormatter_SupportsCustomFormatting()
    {
        var act = TestStruct.ToString("Unit Test Format", FormatProvider.CustomFormatter);
        var exp = "Unit Test Formatter, value: 'AEGONL2UXXX', format: 'Unit Test Format'";

        Assert.AreEqual(exp, act);
    }
    [Test]
    public void ToString_TestStruct_ComplexPattern()
    {
        var act = TestStruct.ToString("");
        var exp = "AEGONL2UXXX";
        Assert.AreEqual(exp, act);
    }

    #endregion

    #region IEquatable tests

    /// GetHash should not fail for BusinessIdentifierCode.Empty.
    [Test]
    public void GetHash_Empty_Hash()
    {
        Assert.AreEqual(0, BusinessIdentifierCode.Empty.GetHashCode());
    }

    /// GetHash should not fail for the test struct.
    [Test]
    public void GetHash_TestStruct_NotZero()
    {
        Assert.NotZero(TestStruct.GetHashCode());
    }

    [Test]
    public void Equals_EmptyEmpty_IsTrue()
    {
        Assert.IsTrue(BusinessIdentifierCode.Empty.Equals(BusinessIdentifierCode.Empty));
    }

    [Test]
    public void Equals_FormattedAndUnformatted_IsTrue()
    {
        var l = BusinessIdentifierCode.Parse("AEGONL2UXXX", CultureInfo.InvariantCulture);
        var r = BusinessIdentifierCode.Parse("AEgonL2Uxxx", CultureInfo.InvariantCulture);

        Assert.IsTrue(l.Equals(r));
    }

    [Test]
    public void Equals_TestStructTestStruct_IsTrue()
    {
        Assert.IsTrue(TestStruct.Equals(TestStruct));
    }

    [Test]
    public void Equals_TestStructEmpty_IsFalse()
    {
        Assert.IsFalse(TestStruct.Equals(BusinessIdentifierCode.Empty));
    }

    [Test]
    public void Equals_EmptyTestStruct_IsFalse()
    {
        Assert.IsFalse(BusinessIdentifierCode.Empty.Equals(TestStruct));
    }

    [Test]
    public void Equals_TestStructObjectTestStruct_IsTrue()
    {
        Assert.IsTrue(TestStruct.Equals((object)TestStruct));
    }

    [Test]
    public void Equals_TestStructNull_IsFalse()
    {
        Assert.IsFalse(TestStruct.Equals(null));
    }

    [Test]
    public void Equals_TestStructObject_IsFalse()
    {
        Assert.IsFalse(TestStruct.Equals(new object()));
    }

    [Test]
    public void OperatorIs_TestStructTestStruct_IsTrue()
    {
        var l = TestStruct;
        var r = TestStruct;
        Assert.IsTrue(l == r);
    }

    [Test]
    public void OperatorIsNot_TestStructTestStruct_IsFalse()
    {
        var l = TestStruct;
        var r = TestStruct;
        Assert.IsFalse(l != r);
    }

    #endregion

    #region IComparable tests

    /// Orders a list of BICs ascending.
    [Test]
    public void OrderBy_BusinessIdentifierCode_AreEqual()
    {
        var item0 = BusinessIdentifierCode.Parse("AEGONL2UXXX");
        var item1 = BusinessIdentifierCode.Parse("CEBUNL2U");
        var item2 = BusinessIdentifierCode.Parse("DSSBNL22");
        var item3 = BusinessIdentifierCode.Parse("FTSBNL2R");

        var inp = new List<BusinessIdentifierCode> { BusinessIdentifierCode.Empty, item3, item2, item0, item1, BusinessIdentifierCode.Empty };
        var exp = new List<BusinessIdentifierCode> { BusinessIdentifierCode.Empty, BusinessIdentifierCode.Empty, item0, item1, item2, item3 };
        var act = inp.OrderBy(item => item).ToList();

        CollectionAssert.AreEqual(exp, act);
    }

    /// Orders a list of BICs descending.
    [Test]
    public void OrderByDescending_BusinessIdentifierCode_AreEqual()
    {
        var item0 = BusinessIdentifierCode.Parse("AEGONL2UXXX");
        var item1 = BusinessIdentifierCode.Parse("CEBUNL2U");
        var item2 = BusinessIdentifierCode.Parse("DSSBNL22");
        var item3 = BusinessIdentifierCode.Parse("FTSBNL2R");

        var inp = new List<BusinessIdentifierCode> { BusinessIdentifierCode.Empty, item3, item2, item0, item1, BusinessIdentifierCode.Empty };
        var exp = new List<BusinessIdentifierCode> { item3, item2, item1, item0, BusinessIdentifierCode.Empty, BusinessIdentifierCode.Empty };
        var act = inp.OrderByDescending(item => item).ToList();

        CollectionAssert.AreEqual(exp, act);
    }

    /// Compare with a to object casted instance should be fine.
    [Test]
    public void CompareTo_ObjectTestStruct_0()
    {
        object other = TestStruct;

        var exp = 0;
        var act = TestStruct.CompareTo(other);

        Assert.AreEqual(exp, act);
    }

    /// Compare with null should return 1.
    [Test]
    public void CompareTo_null_1()
    {
        object @null = null;
        Assert.AreEqual(1, TestStruct.CompareTo(@null));
    }

    /// Compare with a random object should throw an exception.
    [Test]
    public void CompareTo_newObject_ThrowsArgumentException()
    {
        Func<int> compare = () => TestStruct.CompareTo(new object());
        compare.Should().Throw<ArgumentException>();
    }

    #endregion

    #region Properties

    [Test]
    public void Length_DefaultValue_0()
    {
        var exp = 0;
        var act = BusinessIdentifierCode.Empty.Length;
        Assert.AreEqual(exp, act);
    }
    [Test]
    public void Length_Unknown_0()
    {
        var exp = 0;
        var act = BusinessIdentifierCode.Unknown.Length;
        Assert.AreEqual(exp, act);
    }
    [Test]
    public void Length_TestStruct_IntValue()
    {
        var exp = 11;
        var act = TestStruct.Length;
        Assert.AreEqual(exp, act);
    }

    [Test]
    public void BusinessCode_DefaultValue_StringEmpty()
    {
        var exp = "";
        var act = BusinessIdentifierCode.Empty.Business;
        Assert.AreEqual(exp, act);
    }
    [Test]
    public void BusinessCode_Unknown_StringEmpty()
    {
        var exp = "";
        var act = BusinessIdentifierCode.Unknown.Business;
        Assert.AreEqual(exp, act);
    }
    [Test]
    public void BusinessCode_TestStruct_AEGO()
    {
        var exp = "AEGO";
        var act = TestStruct.Business;
        Assert.AreEqual(exp, act);
    }

    [Test]
    public void Country_DefaultValue_CountryEmpty()
    {
        var exp = Country.Empty;
        var act = BusinessIdentifierCode.Empty.Country;
        Assert.AreEqual(exp, act);
    }
    [Test]
    public void Country_Unknown_CountryUnknown()
    {
        var exp = Country.Unknown;
        var act = BusinessIdentifierCode.Unknown.Country;
        Assert.AreEqual(exp, act);
    }
    [Test]
    public void Country_TestStruct_NL()
    {
        var exp = Country.NL;
        var act = TestStruct.Country;
        Assert.AreEqual(exp, act);
    }

    [Test]
    public void LocationCode_DefaultValue_StringEmpty()
    {
        var exp = "";
        var act = BusinessIdentifierCode.Empty.Location;
        Assert.AreEqual(exp, act);
    }
    [Test]
    public void LocationCode_Unknown_StringEmpty()
    {
        var exp = "";
        var act = BusinessIdentifierCode.Unknown.Location;
        Assert.AreEqual(exp, act);
    }
    [Test]
    public void LocationCode_TestStruct_NL()
    {
        var exp = "2U";
        var act = TestStruct.Location;
        Assert.AreEqual(exp, act);
    }

    [Test]
    public void BranchCode_DefaultValue_StringEmpty()
    {
        var exp = "";
        var act = BusinessIdentifierCode.Empty.Branch;
        Assert.AreEqual(exp, act);
    }
    [Test]
    public void BranchCode_Unknown_StringEmpty()
    {
        var exp = "";
        var act = BusinessIdentifierCode.Unknown.Branch;
        Assert.AreEqual(exp, act);
    }
    [Test]
    public void BranchCode_TestStruct_NL()
    {
        var exp = "XXX";
        var act = TestStruct.Branch;
        Assert.AreEqual(exp, act);
    }
    [Test]
    public void BranchCode_AEGONL2U_StringEmpty()
    {
        var exp = "";
        var act = BusinessIdentifierCode.Parse("AEGONL2U").Branch;
        Assert.AreEqual(exp, act);
    }

    #endregion

    #region IsValid

    [TestCase(null, "null")]
    [TestCase("", "string.Empty")]
    [TestCase("1AAANL01", "digit in first four characters")]
    [TestCase("AAAANLBB1", "Branch length of 1")]
    [TestCase("AAAANLBB12", "Branch length of 2")]
    [TestCase("ABCDXX01", "Not existing country")]
    public void IsValid_False(string str, string message)
    {
        Assert.IsFalse(BusinessIdentifierCode.IsValid(str), "{0}, {1}", str, message);
    }

    [TestCase("PSTBNL21")]
    [TestCase("ABNANL2A")]
    [TestCase("BACBBEBB")]
    [TestCase("GEBABEBB36A")]
    [TestCase("DEUTDEFF")]
    [TestCase("NEDSZAJJ")]
    [TestCase("DABADKKK")]
    [TestCase("UNCRIT2B912")]
    [TestCase("DSBACNBXSHA")]
    [TestCase("AAAANLBË")]
    public void IsValid_True(string str)
    {
        Assert.IsTrue(BusinessIdentifierCode.IsValid(str), str);
    }

    #endregion
}

[Serializable]
public class BusinessIdentifierCodeSerializeObject
{
    public int Id { get; set; }
    public BusinessIdentifierCode Obj { get; set; }
    public DateTime Date { get; set; }
}


text:
/**
 *
 */
package myPackage;
/**
 * @author user
 *
 */
public class IndexExceptionExample {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// Variables
		int[] hoursWorked = {7,8,7,9,5};
		int totalHours = 0;
		// For loop
		for(int i = 0; i < hoursWorked.length; i++){
			totalHours += hoursWorked[i];
		}
		System.out.println("Total Hours = " + totalHours);
	}
}


text:
                                        发表于
                                            <time th:text="${posts.publishTime}"></time>

                                            |

                                            分类于

                                            |

                                                评论数

                                            |

                                            阅读次数


text:
package filesystems;

import cluster.IPart;

import java.io.InputStream;

/**
 * Created by Rakovskyi Dmytro on 09.10.2017.
 */
public interface IFilePart<T,P extends IPath,K extends IFilePointer> extends IPart<T> {
    InputStream getStream();
    K getPointer();
    P getPath();
    IFileSystem<P,K> getFileSystem();
    IFileFormat<T> getFileFormat();

}


text:
import Component from '@ember/component';
import { computed } from '@ember/object';
import { humanReadableBytes, isFileValid } from 'open-event-frontend/utils/file';
import { v4 } from 'ember-uuid';

export default Component.extend({

  selectedFile  : null,
  allowDragDrop : true,

  inputIdGenerated: computed('inputId', function() {
    return this.inputId ? this.inputId : v4();
  }),

  maxSize: computed('maxSizeInKb', function() {
    return humanReadableBytes(this.maxSizeInKb);
  }),

  uploadFile() {
    this.set('needsConfirmation', false);
    this.set('uploadingFile', true);
    this.loader
      .uploadFile('/upload/files', this.$(`#${this.inputIdGenerated}`))
      .then(file => {
        this.set('fileUrl', JSON.parse(file).url);
        this.notify.success(this.l10n.t('File uploaded successfully'));
      })
      .catch(() => {
        this.notify.error(this.l10n.t('Oops something went wrong. Please try again'));
      })
      .finally(() => {
        this.set('uploadingFile', false);
      });
  },

  processFiles(files) {
    if (files && files[0]) {
      isFileValid(files[0], this.maxSizeInKb, ['application/pdf', 'application/vnd.ms-powerpoint', 'video/mp4', 'application/vnd.oasis.opendocument.presentation']).then(() => {
        const reader = new FileReader();
        reader.onload = () => {
          this.uploadFile();
        };
        reader.readAsDataURL(files[0]);
      }).catch(error => {
        this.notify.error(error);
      });
    } else {
      this.notify.error(this.l10n.t('No FileReader support. Please use a more latest browser'));
    }
  },

  actions: {
    fileSelected(mode, event) {
      if (mode === 'url') {
        this.set('fileUrl', event.target.value);
      } else {
        this.processFiles(event.target.files);
      }
    },
    removeSelection() {
      if (!this.needsConfirmation || this.edit === true) {
        this.set('selectedFile', null);
        this.set('fileUrl', null);
      } else {
        this.set('needsConfirmation', false);
      }
    }
  },

  init() {
    this._super(...arguments);
    this.set('selectedFile', this.fileUrl);
    if (this.selectedFile) {
      this.set('needsConfirmation', true);
    }
  },

  didInsertElement() {
    this._super(...arguments);
    this.$()
      .on('drag dragstart dragend dragover dragenter dragleave drop', function(e) {
        e.preventDefault();
        e.stopPropagation();
      })
      .on('dragover dragenter', () => {
        this.$('.upload.segment').addClass('drag-hover');
      })
      .on('dragleave dragend drop', () => {
        this.$('.upload.segment').removeClass('drag-hover');
      })
      .on('drop', e => {
        this.processFiles(e.originalEvent.dataTransfer.files);
      });
  },

  willDestroyElement() {
    this._super(...arguments);
    this.$().off('drag dragstart dragend dragover dragenter dragleave drop');
  }

});


text:
'use strict';

const webpack = require('webpack');
const webpackMerge = require('webpack-merge');
const commonConfig = require('./webpack.common');
const { ENV, dir } = require('./helpers');
const { CheckerPlugin } = require('awesome-typescript-loader');

module.exports = (env) => {
  return webpackMerge(commonConfig({ env: ENV }), {
    devtool: 'source-map',
    module: {
      exprContextCritical: false,
      rules: [
        {
          test: /\.ts$/,
          loaders: [
            'awesome-typescript-loader',
            'angular2-template-loader'
          ],
          exclude: [/\.(spec|e2e|d)\.ts$/]
        }
      ]
    },
    entry: {
      'index': './src/index.ts'
    },
    output: {
      path: dir('release'),
      libraryTarget: 'umd',
      library: 'angular2-instagram-core',
      umdNamedDefine: true
    },
    externals: {
      '@angular/platform-browser-dynamic': '@angular/platform-browser-dynamic',
      '@angular/platform-browser': '@angular/platform-browser',
      '@angular/core': '@angular/core',
      '@angular/common': '@angular/common',
      '@angular/http': '@angular/http',
      '@ngrx/core': '@ngrx/core',
      '@ngrx/core/add/operator/select': '@ngrx/core/add/operator/select',
      '@ngrx/store': '@ngrx/store',
      '@ngrx/effects': '@ngrx/effects',
      'immutable': 'immutable',
      'rxjs': 'rxjs',
      'rxjs/Rx': 'rxjs/Rx',
      'rxjs/Observable': 'rxjs/Observable',
      'rxjs/add/operator/switchMap': 'rxjs/add/operator/switchMap',
      'rxjs/add/operator/map': 'rxjs/add/operator/map',
      'rxjs/add/operator/do': 'rxjs/add/operator/do',
      'rxjs/add/operator/catch': 'rxjs/add/operator/catch',
      'rxjs/add/observable/of': 'rxjs/add/observable/of',
      'rxjs/add/operator/distinctUntilChanged': 'rxjs/add/operator/distinctUntilChanged',
      'rxjs/add/operator/let': 'rxjs/add/operator/let',
      'rxjs/add/observable/throw': 'rxjs/add/observable/throw',
      'zone.js/dist/zone': 'zone.js/dist/zone'
    },
    plugins: [
      new CheckerPlugin()
    ]
  });
};


text:
<?php

use yii\helpers\Html;
use yii\grid\GridView;
use yii\bootstrap\Button;
use yii\helpers\Url;
use yii\bootstrap\Modal;
use yii\widgets\Pjax;

/* @var $this yii\web\View */
/* @var $searchModel app\models\StudentSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Students';
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

    <?=
         Button::widget([
             'label' => 'New Student',
                'options' => ['class' => 'btn btn-success','id'=>'createStudentButton',
                              'data-url'=>Url::to(['student/create'])
                              ],
                ]);
    ?>

<?php Pjax::begin();  ?>
    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'stud_id',
            'name',
            'dept_id',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>
<?php Pjax::end(); ?>

    <?php

        //modal for New Student
        Modal::begin([
        'header' => '
New Student
',
        'footer' => Button::widget([
                            'label'=> 'close',
                            'options'=> ['class'=>'btn ','data-dismiss'=>'modal']
                                ]),
        'id' => 'modalStudentCreate'

        ]);

        echo "

";

        Modal::end();

    ?>


text:
package org.devnexus.vo.contract;

import android.content.ContentValues;
import android.net.Uri;

import com.google.gson.Gson;

import org.devnexus.util.GsonUtils;
import org.devnexus.vo.UserCalendar;

import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by summers on 2/8/14.
 */
public final class UserCalendarContract {

    public static final Uri URI = Uri.parse("content://org.devnexus.sync/UserCalendar");
    public static final List<Date> DATES = Arrays.asList(new Date[]{asDate(Calendar.FEBRUARY, 22, 2017), asDate(Calendar.FEBRUARY, 23, 2017), asDate(Calendar.FEBRUARY, 24, 2017)});

    public static final String DATA = "DATA";
    public static final String ID = "ID";
    public static final Integer DATA_IDX = 0;
    public static final String NOTIFY = "NOTIFY";
    public static final Integer NOTIFY_IDX = 1;

    public static final String[] COLUMNS = {DATA, NOTIFY};

    private static final Gson GSON = GsonUtils.GSON;
    public static final String DATE = "DATE";
    public static final String PRESENTATION_ID = "PRESENTATION_ID";
    public static final String START_TIME = "START_TIME";

    /**
     * This method will turn a calendarItem into the appropriate ContentValues for the app.
     *
     * @param calendarItem
     * @return
     */
    public static ContentValues valueize(UserCalendar calendarItem, boolean notify) {
        ContentValues values = new ContentValues();
        values.put(DATA, GSON.toJson(calendarItem));
        values.put(NOTIFY, notify);
        return values;
    }

    public static ContentValues[] valueize(List<UserCalendar> userCalendarItems, boolean notify) {
        ContentValues[] values = new ContentValues[userCalendarItems.size()];
        for (int i = 0; i < values.length; i++) {
            values[i] = valueize(userCalendarItems.get(i), notify);
        }
        return values;
    }

    private static Date asDate(int month, int day, int year) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DATE, day);
        cal.set(Calendar.MONTH, month);
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MILLISECOND, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        return cal.getTime();
    }

}


text:
<?php

App::uses('AppHelper', 'View/Helper');

/**
 * Class GeneralHelper
 */
class GeneralHelper extends AppHelper
{
    /**
     * List of helpers used by this helper
     *
     * @var array
     */
    public $helpers = ['Time', 'Hook'];

    /**
     * Current post array
     *
     * @var array
     * @access public
     */
    public $content = array();
    private static $model = null;

    /**
     * Default Constructor
     *
     * @param View  $View     The View this helper is being attached to.
     * @param array $settings Configuration settings for the helper.
     */
    public function __construct(\View $View, $settings = array())
    {
        parent::__construct($View, $settings);

        self::$model = Inflector::singularize($View->viewPath);
    }

    /**
     * Display or Retrieve the date the current $post was written (once per date)
     *
     * Will only output the date if the current post's date is different from the
     * previous one output.
     *
     * i.e. Only one date listing will show per day worth of posts shown in the loop, even if the
     * function is called several times for each post.
     *
     * HTML output can be filtered with 'the_date'.
     * Date string output can be filtered with 'get_the_date'.
     *
     * @param string $d      Optional. PHP date format defaults to the date_format option if not specified.
     * @param string $before Optional. Output before the date.
     * @param string $after  Optional. Output after the date.
     * @param bool   $echo   Optional, default is display. Whether to echo the date or return it.
     *
     * @return string|null Null if displaying, string if retrieving.
     */
    public function theDate($d = '', $before = '', $after = '', $echo = true)
    {

        $the_date = '';

        $the_date .= $before;
        $the_date .= $this->getTheDate($d);
        $the_date .= $after;

        $the_date = $this->Hook->applyFilters('the_date', $the_date, $d, $before, $after);

        if ($echo) {
            echo $the_date;
        } else {
            return $the_date;
        }
    }

    /**
     * Retrieve the date the current $post was written.
     *
     * Unlike the_date() this function will always return the date.
     * Modify output with 'get_the_date' filter.
     *
     * @param string $d Optional. PHP date format defaults to the date_format option if not specified.
     *
     * @return string|null Null if displaying, string if retrieving.
     */
    public function getTheDate($d = '')
    {
        $the_date = '';

        if ('' == $d) {
            $the_date .= $this->Time->format(
                Configure::read('General.date_format'),
                $this->content[self::$model]['created'],
                null,
                Configure::read('General.timezone')
            );
        } else {
            $the_date .= $this->Time->format(
                $d,
                $this->content[self::$model]['created'],
                null,
                Configure::read('General.timezone')
            );
        }

        return $this->Hook->applyFilters('get_the_date', $the_date, $d);
    }

    /**
     * Display the date on which the post was last modified.
     *
     * @param string $d      Optional. PHP date format defaults to the date_format option if not specified.
     * @param string $before Optional. Output before the date.
     * @param string $after  Optional. Output after the date.
     * @param bool   $echo   Optional, default is display. Whether to echo the date or return it.
     *
     * @return string|null Null if displaying, string if retrieving.
     */
    public function theModifiedDate($d = '', $before = '', $after = '', $echo = true)
    {

        $the_modified_date = $before . $this->getTheModifiedDate($d) . $after;
        $the_modified_date = $this->Hook->applyFilters('the_modified_date', $the_modified_date, $d, $before, $after);

        if ($echo) {
            echo $the_modified_date;
        } else {
            return $the_modified_date;
        }
    }

    /**
     * Retrieve the date on which the post was last modified.
     *
     * @param string $d Optional. PHP date format. Defaults to the "date_format" option
     *
     * @return string
     */
    public function getTheModifiedDate($d = '')
    {
        if ('' == $d) {
            $the_time = $this->getPostModifiedTime(Configure::read('General.date_format'));
        } else {
            $the_time = $this->getPostModifiedTime($d);
        }

        return $this->Hook->applyFilters('get_the_modified_date', $the_time, $d);
    }

    /**
     * Display the time at which the post was written.
     *
     * @since 1.0.0
     *
     * @param string $d Either 'G', 'U', or php date format.
     */
    public function theTime($d = '')
    {
        echo $this->Hook->applyFilters('the_time', $this->getTheTime($d), $d);
    }

    /**
     * Retrieve the time at which the post was written.
     *
     * @param string $d Optional Either 'G', 'U', or php date format defaults to the value specified in the time_format option.
     *
     * @return string
     */
    public function getTheTime($d = '')
    {
        if ('' == $d) {
            $the_time = $this->getPostTime(Configure::read('General.time_format'));
        } else {
            $the_time = $this->getPostTime($d);
        }

        return $this->Hook->applyFilters('get_the_time', $the_time, $d);
    }

    /**
     * Retrieve the time at which the post was written.
     *
     * @param string $d Optional Either 'G', 'U', or php date format.
     *
     * @return string
     */
    public function getPostTime($d = 'U')
    { // returns timestamp
        $time = $this->content[self::$model]['created'];
        $time = $this->Time->format($d, $time, null, Configure::read('General.timezone'));

        return $this->Hook->applyFilters('get_post_time', $time, $d);
    }

    /**
     * Display the time at which the post was last modified.
     *
     * @param string $d Optional Either 'G', 'U', or php date format defaults to the value specified in the time_format option.
     */
    public function theModifiedTime($d = '')
    {
        echo $this->Hook->applyFilters('the_modified_time', $this->getTheModifiedTime($d), $d);
    }

    /**
     * Retrieve the time at which the post was last modified.
     *
     * @param string $d Optional Either 'G', 'U', or php date format defaults to the value specified in the time_format option.
     *
     * @return string
     */
    public function getTheModifiedTime($d = '')
    {
        if ('' == $d) {
            $the_time = $this->getPostModifiedTime(Configure::read('General.time_format'));
        } else {
            $the_time = $this->getPostModifiedTime($d);
        }

        return $this->Hook->applyFilters('get_the_modified_time', $the_time, $d);
    }

    /**
     * Retrieve the time at which the post was last modified.
     *
     * @param string $d Optional, default is 'U'. Either 'G', 'U', or php date format.
     *
     * @return string Returns timestamp
     */
    public function getPostModifiedTime($d = 'U')
    {
        $time = $this->content[self::$model]['modified'];
        $time = $this->Time->format($d, $time, null, Configure::read('General.timezone'));

        return $this->Hook->applyFilters('get_post_modified_time', $time, $d);
    }
}


text:
using Microsoft.Azure.Devices.Client;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using Repsaj.Submerged.Gateway.Common.Log;
using Repsaj.Submerged.GatewayApp.Universal.Commands;
using Repsaj.Submerged.GatewayApp.Universal.Exceptions;
using Repsaj.Submerged.GatewayApp.Universal.Models;
using Repsaj.Submerged.GatewayApp.Universal.Repositories;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Windows.System.Threading;

namespace Repsaj.Submerged.GatewayApp.Universal.Azure
{
    public class AzureConnection : IAzureConnection
    {
        public event ICommandReceived CommandReceived;
        public event Action Connected;
        public event Action Disconnected;

        string _deviceConnectionString;
        JsonSerializerSettings _settings;
        DeviceClient _deviceClient;

        public AzureConnectionStatus Status { get; internal set; }

        public AzureConnection()
        {

        }

        public async Task Init(ConnectionInformationModel connectionInfo)
        {
            try
            {
                string iotHubHostname = connectionInfo.IoTHubHostname;
                string deviceId = connectionInfo.DeviceId;
                string deviceKey = connectionInfo.DeviceKey;

                string deviceConnectionString = $"HostName={iotHubHostname};DeviceId={deviceId};SharedAccessKey={deviceKey}";

                // Initialize the device client object which is used to connect to Azure IoT hub
                // Create the IoT Hub Device Client instance
                _deviceConnectionString = deviceConnectionString;

                // use camlCasing for json objects
                _settings = new JsonSerializerSettings();
                _settings.ContractResolver = new CamelCasePropertyNamesContractResolver();

                await Connect();
            }
            catch (Exception ex)
            {
                LogEventSource.Log.Error($"Could not initialize the connection to Azure: {ex}.");
            }
        }

        private async Task Connect()
        {
            try
            {
                this.Status = AzureConnectionStatus.Connecting;

                // create the device client for Azure
                _deviceClient = DeviceClient.CreateFromConnectionString(_deviceConnectionString, TransportType.Amqp);

                if (await TestConnection())
                {
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                    ListenToCloudMessagesAsync();
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                }
            }
            catch (Exception ex)
            {
                LogEventSource.Log.Error($"Could not Connect to Azure: {ex}");
                SetDisconnected();
            }
        }

        private async Task<bool> TestConnection()
        {
            try
            {
                // send out an empty test message to see whether we have a connection
                var message = new Microsoft.Azure.Devices.Client.Message();
                await _deviceClient.SendEventAsync(message);

                SetConnected();
                return true;
            }
            catch (Exception ex) when (ex.Message.Contains("UnauthorizedException"))
            {
                LogEventSource.Log.Error($"Connecting to Azure failed with UnauthorizedException: {ex}");
                SetDisconnected();
                return false;
            }
            catch (Exception ex) when (ex.Message.Contains("DeviceNotFound"))
            {
                LogEventSource.Log.Error($"Connecting to Azure failed with DeviceNotFound exception: {ex}");
                SetDisconnected();
                return false;
            }
            catch (Exception ex)
            {
                LogEventSource.Log.Error($"Connecting to Azure failed with Exception: {ex}");
                SetDisconnected();
                return false;
            }
        }

        private void SetDisconnected()
        {
            if (_deviceClient != null)
            {
                Debug.WriteLine("Disconnecting Azure connection, disposing client.");
                _deviceClient.Dispose();
                _deviceClient = null;
            }

            if (this.Status != AzureConnectionStatus.Disconnected)
            {
                this.Status = AzureConnectionStatus.Disconnected;
                Disconnected?.Invoke();

                Task.Run(async () =>
                {
                    Debug.WriteLine("Starting a delay task to reboot the Azure connection in 5 minutes");
                    await Task.Delay(new TimeSpan(0, 0, 10));

                    Debug.WriteLine("Trying to reconnect to Azure");
                    await Connect();
                });
            }
        }

        private void SetConnected()
        {
            if (this.Status != AzureConnectionStatus.Connected)
            {
                this.Status = AzureConnectionStatus.Connected;
                Connected?.Invoke();
            }
        }

        /// <summary>
        /// Sends an event to the IoT Hub
        /// </summary>
        /// <param name="device"></param>
        /// <param name="eventData"></param>
        /// <returns></returns>
        public Task<bool> SendDeviceToCloudMessageAsync(JObject eventData)
        {
            string payload = eventData?.ToString();
            return SendDeviceToCloudMessageAsync(payload);
        }

        public async Task<bool> SendDeviceToCloudMessageAsync(string payload)
        {
            if (this.Status != AzureConnectionStatus.Connected)
            {
                LogEventSource.Log.Warn("Did not send message to Azure because the connection is down.");
                return false;
            }

            if (payload == null)
                return false;

            try
            {
                var eventId = Guid.NewGuid();
                byte[] bytes = Encoding.UTF8.GetBytes(payload);

                var message = new Microsoft.Azure.Devices.Client.Message(bytes);
                message.Properties["EventId"] = eventId.ToString();

                Debug.WriteLine("{0} > Sending IoT hub message: {1}", DateTime.UtcNow, payload);
                await _deviceClient.SendEventAsync(message);

                return true;
            }
            catch (Exception ex)
            {
                LogEventSource.Log.Error($"Failed sending message ({payload}) to Azure: {ex}");
                SetDisconnected();
                return false;
            }
        }

        private async Task ListenToCloudMessagesAsync()
        {
            try
            {
                while (true)
                {
                    Message receivedMessage = null;
                    await Task.Delay(1000);

                    try
                    {
                        if (this._deviceClient != null)
                            receivedMessage = await _deviceClient.ReceiveAsync(TimeSpan.FromSeconds(1));
                    }
                    catch (Exception ex)
                    {
                        LogEventSource.Log.Warn("Failure occurred whilst waiting for a cloud to device message: " + ex);
                    }

                    if (receivedMessage == null) continue;
                    Debug.WriteLine($"Received a message from Azure!");

                    try
                    {
                        DeserializableCommand command = new DeserializableCommand(receivedMessage);
                        await CommandReceived(command);

                        SetConnected();
                    }
                    catch (Exception ex)
                    {
                        LogEventSource.Log.Warn("Could not process the command received: " + ex);
                    }
                    finally
                    {
                        await _deviceClient.CompleteAsync(receivedMessage);
                    }
                }
            }
            catch (Exception ex)
            {
                LogEventSource.Log.Error("Unexpected exception listening to incoming cloud messages: " + ex.ToString());
            }
        }
    }
}


text:
package com.diffplug.gradle.spotless;

import static com.diffplug.spotless.kotlin.KotlinConstants.LICENSE_HEADER_DELIMITER;

import java.util.Collections;
import java.util.Map;
import java.util.Objects;

import org.gradle.api.GradleException;
import org.gradle.api.file.FileCollection;
import org.gradle.api.plugins.JavaPluginConvention;
import org.gradle.api.tasks.SourceSet;

import com.diffplug.spotless.FormatterStep;
import com.diffplug.spotless.kotlin.KtLintStep;

public class KotlinExtension extends FormatExtension implements HasBuiltinDelimiterForLicense {
	static final String NAME = "kotlin";

	public KotlinExtension(SpotlessExtension rootExtension) {
		super(rootExtension);
	}

	@Override
	public LicenseHeaderConfig licenseHeader(String licenseHeader) {
		return licenseHeader(licenseHeader, LICENSE_HEADER_DELIMITER);
	}

	@Override
	public LicenseHeaderConfig licenseHeaderFile(Object licenseHeaderFile) {
		return licenseHeaderFile(licenseHeaderFile, LICENSE_HEADER_DELIMITER);
	}

	/** Adds the specified version of [ktlint](https://github.com/shyiko/ktlint). */
	public KotlinFormatExtension ktlint(String version) {
		Objects.requireNonNull(version);
		return new KotlinFormatExtension(version, Collections.emptyMap());
	}

	public KotlinFormatExtension ktlint() {
		return ktlint(KtLintStep.defaultVersion());
	}

	public class KotlinFormatExtension {

		private final String version;
		private Map<String, String> userData;

		KotlinFormatExtension(String version, Map<String, String> config) {
			this.version = version;
			this.userData = config;
			addStep(createStep());
		}

		public void userData(Map<String, String> userData) {
			// Copy the map to a sorted map because up-to-date checking is based on binary-equals of the serialized
			// representation.
			this.userData = userData;
			replaceStep(createStep());
		}

		private FormatterStep createStep() {
			return KtLintStep.create(version, GradleProvisioner.fromProject(getProject()), userData);
		}
	}

	/** If the user hasn't specified the files yet, we'll assume he/she means all of the kotlin files. */
	@Override
	protected void setupTask(SpotlessTask task) {
		if (target == null) {
			JavaPluginConvention javaPlugin = getProject().getConvention().findPlugin(JavaPluginConvention.class);
			if (javaPlugin == null) {
				throw new GradleException("You must either specify 'target' manually or apply a kotlin plugin.");
			}
			FileCollection union = getProject().files();
			for (SourceSet sourceSet : javaPlugin.getSourceSets()) {
				union = union.plus(sourceSet.getAllSource().filter(file -> {
					String name = file.getName();
					return name.endsWith(".kt") || name.endsWith(".kts");
				}));
			}
			target = union;
		}
		super.setupTask(task);
	}
}


text:
class FacilityTypes < ActiveRecord::Migration
  def self.up
    add_column :shelters, :facility_type, :integer
    execute "UPDATE shelters SET facility_type = 0;"
  end

  def self.down
    remove_column :shelters, :facility_type
  end
end


text:
using System;

namespace Appleseed.Framework.Exceptions
{
	/// <summary>
	/// Custom exception raised when database version is behind code version. Causes redirect to Database Update page.
	/// </summary>
	[Serializable]
	public sealed class DatabaseVersionException : Exception
	{
		/// <summary>
		/// Default constructor
		/// </summary>
		public DatabaseVersionException()
		{
		}

		/// <summary>
		/// Constructor with message.
		/// </summary>
		/// <param name="message">Text message to be included in log.</param>
		public DatabaseVersionException(string message)
			: base(message)
		{
		}

		/// <summary>
		/// Constructor with message and innerException.
		/// </summary>
		/// <param name="message">Text message to be included in log.</param>
		/// <param name="inner">Inner exception.</param>
		public DatabaseVersionException(string message, Exception inner)
			: base(message, inner)
		{
		}
	}
}


text:
package kafka.utils.timer

import kafka.utils.nonthreadsafe

import java.util.concurrent.DelayQueue
import java.util.concurrent.atomic.AtomicInteger

/*
 * Hierarchical Timing Wheels
 *
 * A simple timing wheel is a circular list of buckets of timer tasks. Let u be the time unit.
 * A timing wheel with size n has n buckets and can hold timer tasks in n * u time interval.
 * Each bucket holds timer tasks that fall into the corresponding time range. At the beginning,
 * the first bucket holds tasks for [0, u), the second bucket holds tasks for [u, 2u), …,
 * the n-th bucket for [u * (n -1), u * n). Every interval of time unit u, the timer ticks and
 * moved to the next bucket then expire all timer tasks in it. So, the timer never insert a task
 * into the bucket for the current time since it is already expired. The timer immediately runs
 * the expired task. The emptied bucket is then available for the next round, so if the current
 * bucket is for the time t, it becomes the bucket for [t + u * n, t + (n + 1) * u) after a tick.
 * A timing wheel has O(1) cost for insert/delete (start-timer/stop-timer) whereas priority queue
 * based timers, such as java.util.concurrent.DelayQueue and java.util.Timer, have O(log n)
 * insert/delete cost.
 *
 * A major drawback of a simple timing wheel is that it assumes that a timer request is within
 * the time interval of n * u from the current time. If a timer request is out of this interval,
 * it is an overflow. A hierarchical timing wheel deals with such overflows. It is a hierarchically
 * organized timing wheels. The lowest level has the finest time resolution. As moving up the
 * hierarchy, time resolutions become coarser. If the resolution of a wheel at one level is u and
 * the size is n, the resolution of the next level should be n * u. At each level overflows are
 * delegated to the wheel in one level higher. When the wheel in the higher level ticks, it reinsert
 * timer tasks to the lower level. An overflow wheel can be created on-demand. When a bucket in an
 * overflow bucket expires, all tasks in it are reinserted into the timer recursively. The tasks
 * are then moved to the finer grain wheels or be executed. The insert (start-timer) cost is O(m)
 * where m is the number of wheels, which is usually very small compared to the number of requests
 * in the system, and the delete (stop-timer) cost is still O(1).
 *
 * Example
 * Let's say that u is 1 and n is 3. If the start time is c,
 * then the buckets at different levels are:
 *
 * level    buckets
 * 1        [c,c]   [c+1,c+1]  [c+2,c+2]
 * 2        [c,c+2] [c+3,c+5]  [c+6,c+8]
 * 3        [c,c+8] [c+9,c+17] [c+18,c+26]
 *
 * The bucket expiration is at the time of bucket beginning.
 * So at time = c+1, buckets [c,c], [c,c+2] and [c,c+8] are expired.
 * Level 1's clock moves to c+1, and [c+3,c+3] is created.
 * Level 2 and level3's clock stay at c since their clocks move in unit of 3 and 9, respectively.
 * So, no new buckets are created in level 2 and 3.
 *
 * Note that bucket [c,c+2] in level 2 won't receive any task since that range is already covered in level 1.
 * The same is true for the bucket [c,c+8] in level 3 since its range is covered in level 2.
 * This is a bit wasteful, but simplifies the implementation.
 *
 * 1        [c+1,c+1]  [c+2,c+2]  [c+3,c+3]
 * 2        [c,c+2]    [c+3,c+5]  [c+6,c+8]
 * 3        [c,c+8]    [c+9,c+17] [c+18,c+26]
 *
 * At time = c+2, [c+1,c+1] is newly expired.
 * Level 1 moves to c+2, and [c+4,c+4] is created,
 *
 * 1        [c+2,c+2]  [c+3,c+3]  [c+4,c+4]
 * 2        [c,c+2]    [c+3,c+5]  [c+6,c+8]
 * 3        [c,c+8]    [c+9,c+17] [c+18,c+18]
 *
 * At time = c+3, [c+2,c+2] is newly expired.
 * Level 2 moves to c+3, and [c+5,c+5] and [c+9,c+11] are created.
 * Level 3 stay at c.
 *
 * 1        [c+3,c+3]  [c+4,c+4]  [c+5,c+5]
 * 2        [c+3,c+5]  [c+6,c+8]  [c+9,c+11]
 * 3        [c,c+8]    [c+9,c+17] [c+8,c+11]
 *
 * The hierarchical timing wheels works especially well when operations are completed before they time out.
 * Even when everything times out, it still has advantageous when there are many items in the timer.
 * Its insert cost (including reinsert) and delete cost are O(m) and O(1), respectively while priority
 * queue based timers takes O(log N) for both insert and delete where N is the number of items in the queue.
 *
 * This class is not thread-safe. There should not be any add calls while advanceClock is executing.
 * It is caller's responsibility to enforce it. Simultaneous add calls are thread-safe.
 */
@nonthreadsafe
private[timer] class TimingWheel(tickMs: Long, wheelSize: Int, startMs: Long, taskCounter: AtomicInteger, queue: DelayQueue[TimerTaskList]) {
  //tickMs 当前时间轮中一个时间格标示的时间跨度
  //wheelSize 当前时间轮的格数
  //startMs 当前实践轮创建的时间

  //时间轮的跨度
  private[this] val interval = tickMs * wheelSize
  //每一项都是时间轮中的一个时间格
  private[this] val buckets = Array.tabulate[TimerTaskList](wheelSize) { _ => new TimerTaskList(taskCounter) }
  //实践轮的指针
  private[this] var currentTime = startMs - (startMs % tickMs) // rounding down to multiple of tickMs

  // overflowWheel can potentially be updated and read by two concurrent threads through add().
  // Therefore, it needs to be volatile due to the issue of Double-Checked Locking pattern with JVM
  //上层时间轮的引用
  @volatile private[this] var overflowWheel: TimingWheel = null

  //创建上层时间轮
  //上层时间轮的tickMs是当前整个时间轮的时间跨度interval
  private[this] def addOverflowWheel(): Unit = {
    synchronized {
      if (overflowWheel == null) {
        overflowWheel = new TimingWheel(
          tickMs = interval,
          wheelSize = wheelSize,
          startMs = currentTime,
          //全局唯一得而计数器
          taskCounter = taskCounter,
          //全局唯一队列
          queue
        )
      }
    }
  }

  //向实践轮中添加定时任务的功能·
  def add(timerTaskEntry: TimerTaskEntry): Boolean = {
    val expiration = timerTaskEntry.expirationMs
    //任务被取消
    if (timerTaskEntry.cancelled) {
      // Cancelled
      false
      //任务过期
    } else if (expiration < currentTime + tickMs) {
      // Already expired
      false
      //任务在当前的时间跨度内
    } else if (expiration < currentTime + interval) {
      // Put in its own bucket
      //按照任务的到期时间查找此任务的时间格
      val virtualId = expiration / tickMs
      val bucket = buckets((virtualId % wheelSize.toLong).toInt)
      //添加到TimerTaskList
      bucket.add(timerTaskEntry)
      //设置过期时间
      // Set the bucket expiration time
      if (bucket.setExpiration(virtualId * tickMs)) {
        // The bucket needs to be enqueued because it was an expired bucket
        // We only need to enqueue the bucket when its expiration time has changed, i.e. the wheel has advanced
        // and the previous buckets gets reused; further calls to set the expiration within the same wheel cycle
        // will pass in the same value and hence return false, thus the bucket with the same expiration will not
        // be enqueued multiple times.
        queue.offer(bucket)
      }
      true
    } else {
      // Out of the interval. Put it into the parent timer
      //超出了当前时间轮的时间范围,将任务添加到上层时间轮中处理
      if (overflowWheel == null) addOverflowWheel()
      overflowWheel.add(timerTaskEntry)
    }
  }

  // Try to advance the clock
  //尝试推进当前时间轮的表针currentTime
  def advanceClock(timeMs: Long): Unit = {
    //尝试一定currentTime,移动可能不止一格
    if (timeMs >= currentTime + tickMs) {
      currentTime = timeMs - (timeMs % tickMs)

      // Try to advance the clock of the overflow wheel if present
      //尝试推进上层时间轮表针
      if (overflowWheel != null) overflowWheel.advanceClock(currentTime)
    }
  }
}