text:
//------------------------------------------------------------------------------
// <copyright file="etwprovider.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
// <OWNER>[....]</OWNER>
//------------------------------------------------------------------------------
using Microsoft.Win32;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Diagnostics.Tracing;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using System;

namespace System.Diagnostics.Tracing
{
    // New in CLR4.0
    internal enum ControllerCommand
    {
        // Strictly Positive numbers are for provider-specific commands, negative number are for 'shared' commands. 256
        // The first 256 negative numbers are reserved for the framework.
        Update = 0,                 // Not used by EventPrividerBase.
        SendManifest = -1,
        Enable = -2,
        Disable = -3,
    };

    /// <summary>
    /// Only here because System.Diagnostics.EventProvider needs one more extensibility hook (when it gets a
    /// controller callback)
    /// </summary>
    [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
    internal class EventProvider : IDisposable
    {
        // This is the windows EVENT_DATA_DESCRIPTOR structure.  We expose it because this is what
        // subclasses of EventProvider use when creating efficient (but unsafe) version of
        // EventWrite.   We do make it a nested type because we really don't expect anyone to use
        // it except subclasses (and then only rarely).
        public struct EventData
        {
            internal unsafe ulong Ptr;
            internal uint Size;
            internal uint Reserved;
        }

        /// <summary>
        /// A struct characterizing ETW sessions (identified by the etwSessionId) as
        /// activity-tracing-aware or legacy. A session that's activity-tracing-aware
        /// has specified one non-zero bit in the reserved range 44-47 in the
        /// 'allKeywords' value it passed in for a specific EventProvider.
        /// </summary>
        public struct SessionInfo
        {
            internal int sessionIdBit;      // the index of the bit used for tracing in the "reserved" field of AllKeywords
            internal int etwSessionId;      // the machine-wide ETW session ID

            internal SessionInfo(int sessionIdBit_, int etwSessionId_)
            { sessionIdBit = sessionIdBit_; etwSessionId = etwSessionId_; }
        }

        [SecurityCritical]
        UnsafeNativeMethods.ManifestEtw.EtwEnableCallback m_etwCallback;     // Trace Callback function
        private long m_regHandle;                        // Trace Registration Handle
        private byte m_level;                            // Tracing Level
        private long m_anyKeywordMask;                   // Trace Enable Flags
        private long m_allKeywordMask;                   // Match all keyword
        private List<SessionInfo> m_liveSessions;        // current live sessions (Tuple<sessionIdBit, etwSessionId>)
        private bool m_enabled;                          // Enabled flag from Trace callback
        private Guid m_providerId;                       // Control Guid
        private int m_disposed;                          // when 1, provider has unregister

        [ThreadStatic]
        private static WriteEventErrorCode s_returnCode; // The last return code

        private const int s_basicTypeAllocationBufferSize = 16;
        private const int s_etwMaxMumberArguments = 32;
        private const int s_etwAPIMaxStringCount = 8;
        private const int s_maxEventDataDescriptors = 128;
        private const int s_traceEventMaximumSize = 65482;
        private const int s_traceEventMaximumStringSize = 32724;

        [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
        public enum WriteEventErrorCode : int
        {
            //check mapping to runtime codes
            NoError = 0,
            NoFreeBuffers = 1,
            EventTooBig = 2,
            NullInput = 3,
            TooManyArgs = 4,
            Other = 5,
        };

        // <SecurityKernel Critical="True" Ring="1">
        // <ReferencesCritical Name="Method: Register():Void" Ring="1" />
        // </SecurityKernel>
        /// <summary>
        /// Constructs a new EventProvider.  This causes the class to be registered with the OS and
        /// if an ETW controller turns on the logging then logging will start.
        /// </summary>
        /// <param name="providerGuid">The GUID that identifies this provider to the system.</param>
        [System.Security.SecurityCritical]
#pragma warning disable 618
        [PermissionSet(SecurityAction.Demand, Unrestricted = true)]
#pragma warning restore 618
        [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "guid")]
        protected EventProvider(Guid providerGuid)
        {
            m_providerId = providerGuid;
            //
            // Register the ProviderId with ETW
            //
            Register(providerGuid);
        }

        internal EventProvider()
        {
        }

        /// <summary>
        /// This method registers the controlGuid of this class with ETW. We need to be running on
        /// Vista or above. If not a PlatformNotSupported exception will be thrown. If for some
        /// reason the ETW Register call failed a NotSupported exception will be thrown.
        /// </summary>
        // <SecurityKernel Critical="True" Ring="0">
        // <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventRegister(System.Guid&,Microsoft.Win32.UnsafeNativeMethods.ManifestEtw+EtwEnableCallback,System.Void*,System.Int64&):System.UInt32" />
        // <SatisfiesLinkDemand Name="Win32Exception..ctor(System.Int32)" />
        // <ReferencesCritical Name="Method: EtwEnableCallBack(Guid&, Int32, Byte, Int64, Int64, Void*, Void*):Void" Ring="1" />
        // </SecurityKernel>
        [System.Security.SecurityCritical]
        internal unsafe void Register(Guid providerGuid)
        {
            m_providerId = providerGuid;
            uint status;
            m_etwCallback = new UnsafeNativeMethods.ManifestEtw.EtwEnableCallback(EtwEnableCallBack);

            status = EventRegister(ref m_providerId, m_etwCallback);
            if (status != 0)
            {
                throw new ArgumentException(Win32Native.GetMessage(unchecked((int)status)));
            }
        }

        //
        // implement Dispose Pattern to early deregister from ETW insted of waiting for
        // the finalizer to call deregistration.
        // Once the user is done with the provider it needs to call Close() or Dispose()
        // If neither are called the finalizer will unregister the provider anyway
        //
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        // <SecurityKernel Critical="True" TreatAsSafe="Does not expose critical resource" Ring="1">
        // <ReferencesCritical Name="Method: Deregister():Void" Ring="1" />
        // </SecurityKernel>
        [System.Security.SecuritySafeCritical]
        protected virtual void Dispose(bool disposing)
        {
            //
            // explicit cleanup is done by calling Dispose with true from
            // Dispose() or Close(). The disposing arguement is ignored because there
            // are no unmanaged resources.
            // The finalizer calls Dispose with false.
            //

            //
            // check if the object has been allready disposed
            //
            if (m_disposed == 1) return;

            if (Interlocked.Exchange(ref m_disposed, 1) != 0)
            {
                // somebody is allready disposing the provider
                return;
            }

            //
            // Disables Tracing in the provider, then unregister
            //

            m_enabled = false;

            Deregister();
        }

        /// <summary>
        /// This method deregisters the controlGuid of this class with ETW.
        ///
        /// </summary>
        public virtual void Close()
        {
            Dispose();
        }

        ~EventProvider()
        {
            Dispose(false);
        }

        /// <summary>
        /// This method un-registers from ETW.
        /// </summary>
        // <SecurityKernel Critical="True" Ring="0">
        // <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventUnregister(System.Int64):System.Int32" />
        // </SecurityKernel>
        //
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "Microsoft.Win32.UnsafeNativeMethods.ManifestEtw.EventUnregister(System.Int64)"), System.Security.SecurityCritical]
        private unsafe void Deregister()
        {
            //
            // Unregister from ETW using the RegHandle saved from
            // the register call.
            //

            if (m_regHandle != 0)
            {
                EventUnregister();
                m_regHandle = 0;
            }
        }

        // <SecurityKernel Critical="True" Ring="0">
        // <UsesUnsafeCode Name="Parameter filterData of type: Void*" />
        // <UsesUnsafeCode Name="Parameter callbackContext of type: Void*" />
        // </SecurityKernel>
        [System.Security.SecurityCritical]
        unsafe void EtwEnableCallBack(
                        [In] ref System.Guid sourceId,
                        [In] int controlCode,
                        [In] byte setLevel,
                        [In] long anyKeyword,
                        [In] long allKeyword,
                        [In] UnsafeNativeMethods.ManifestEtw.EVENT_FILTER_DESCRIPTOR* filterData,
                        [In] void* callbackContext
                        )
        {
            ControllerCommand command = ControllerCommand.Update;
            IDictionary<string, string> args = null;
            byte[] data;
            int keyIndex;
            bool skipFinalOnControllerCommand = false;
            EventSource.OutputDebugString(string.Format("EtwEnableCallBack(ctrl {0}, lvl {1}, any {2:x}, all {3:x})",
                                          controlCode, setLevel, anyKeyword, allKeyword));
            if (controlCode == UnsafeNativeMethods.ManifestEtw.EVENT_CONTROL_CODE_ENABLE_PROVIDER)
            {
                m_enabled = true;
                m_level = setLevel;
                m_anyKeywordMask = anyKeyword;
                m_allKeywordMask = allKeyword;

                List<Tuple<SessionInfo, bool>> sessionsChanged = GetSessions();
                foreach (var session in sessionsChanged)
                {
                    int sessionChanged = session.Item1.sessionIdBit;
                    int etwSessionId = session.Item1.etwSessionId;
                    bool bEnabling = session.Item2;

                    EventSource.OutputDebugString(string.Format(CultureInfo.InvariantCulture, "EtwEnableCallBack: session changed {0}:{1}:{2}",
                        sessionChanged, etwSessionId, bEnabling));

                    skipFinalOnControllerCommand = true;
                    args = null;                                // reinitialize args for every session...

                    // if we get more than one session changed we have no way
                    // of knowing which one "filterData" belongs to
                    if (sessionsChanged.Count > 1)
                        filterData = null;

                    // read filter data only when a session is being *added*
                    if (bEnabling &&
                        GetDataFromController(etwSessionId, filterData, out command, out data, out keyIndex))
                    {
                        args = new Dictionary<string, string>(4);
                        while (keyIndex < data.Length)
                        {
                            int keyEnd = FindNull(data, keyIndex);
                            int valueIdx = keyEnd + 1;
                            int valueEnd = FindNull(data, valueIdx);
                            if (valueEnd < data.Length)
                            {
                                string key = System.Text.Encoding.UTF8.GetString(data, keyIndex, keyEnd - keyIndex);
                                string value = System.Text.Encoding.UTF8.GetString(data, valueIdx, valueEnd - valueIdx);
                                args[key] = value;
                            }
                            keyIndex = valueEnd + 1;
                        }
                    }

                    // execute OnControllerCommand once for every session that has changed.
                    try
                    {
                        OnControllerCommand(command, args, (bEnabling ? sessionChanged : -sessionChanged), etwSessionId);
                    }
                    catch (Exception)
                    {
                        // We want to ignore any failures that happen as a result of turning on this provider as to
                        // not crash the app.
                    }
                }
            }
            else if (controlCode == UnsafeNativeMethods.ManifestEtw.EVENT_CONTROL_CODE_DISABLE_PROVIDER)
            {
                m_enabled = false;
                m_level = 0;
                m_anyKeywordMask = 0;
                m_allKeywordMask = 0;
                m_liveSessions = null;
            }
            else if (controlCode == UnsafeNativeMethods.ManifestEtw.EVENT_CONTROL_CODE_CAPTURE_STATE)
            {
                command = ControllerCommand.SendManifest;
            }
            else
                return;     // per spec you ignore commands you don't recognise.

            try
            {
                if (!skipFinalOnControllerCommand)
                    OnControllerCommand(command, args, 0, 0);
            }
            catch (Exception)
            {
                // We want to ignore any failures that happen as a result of turning on this provider as to
                // not crash the app.
            }
        }

        // New in CLR4.0
        protected virtual void OnControllerCommand(ControllerCommand command, IDictionary<string, string> arguments, int sessionId, int etwSessionId) { }
        protected EventLevel Level { get { return (EventLevel)m_level; } set { m_level = (byte)value; } }
        protected EventKeywords MatchAnyKeyword { get { return (EventKeywords)m_anyKeywordMask; } set { m_anyKeywordMask = (long)value; } }
        protected EventKeywords MatchAllKeyword { get { return (EventKeywords)m_allKeywordMask; } set { m_allKeywordMask = (long)value; } }

        static private int FindNull(byte[] buffer, int idx)
        {
            while (idx < buffer.Length && buffer[idx] != 0)
                idx++;
            return idx;
        }

        /// <summary>
        /// Determines the ETW sessions that have been added and/or removed to the set of
        /// sessions interested in the current provider. It does so by (1) enumerating over all
        /// ETW sessions that enabled 'this.m_Guid' for the current process ID, and (2)
        /// comparing the current list with a list it cached on the previous invocation.
        ///
        /// The return value is a list of tuples, where the SessionInfo specifies the
        /// ETW session that was added or remove, and the bool specifies whether the
        /// session was added or whether it was removed from the set.
        /// </summary>
        [System.Security.SecuritySafeCritical]
        private List<Tuple<SessionInfo, bool>> GetSessions()
        {
            List<SessionInfo> liveSessionList = null;

            GetSessionInfo((Action<int, long>)
                ((etwSessionId, matchAllKeywords) =>
                    GetSessionInfoCallback(etwSessionId, matchAllKeywords, ref liveSessionList)));

            List<Tuple<SessionInfo, bool>> changedSessionList = new List<Tuple<SessionInfo, bool>>();

            // first look for sessions that have gone away (or have changed)
            // (present in the m_liveSessions but not in the new liveSessionList)
            if (m_liveSessions != null)
            {
                foreach(SessionInfo s in m_liveSessions)
                {
                    int idx;
                    if ((idx = IndexOfSessionInList(liveSessionList, s.etwSessionId)) < 0 ||
                        (liveSessionList[idx].sessionIdBit != s.sessionIdBit))
                        changedSessionList.Add(Tuple.Create(s, false));

                }
            }
            // next look for sessions that were created since the last callback  (or have changed)
            // (present in the new liveSessionList but not in m_liveSessions)
            if (liveSessionList != null)
            {
                foreach (SessionInfo s in liveSessionList)
                {
                    int idx;
                    if ((idx = IndexOfSessionInList(m_liveSessions, s.etwSessionId)) < 0 ||
                        (m_liveSessions[idx].sessionIdBit != s.sessionIdBit))
                        changedSessionList.Add(Tuple.Create(s, true));
                }
            }

            m_liveSessions = liveSessionList;

            return changedSessionList;
        }

        /// <summary>
        /// This method is the callback used by GetSessions() when it calls into GetSessionInfo().
        /// It updates a List<SessionInfo> based on the etwSessionId and matchAllKeywords that
        /// GetSessionInfo() passes in.
        /// </summary>
        private static void GetSessionInfoCallback(int etwSessionId, long matchAllKeywords,
                                ref List<SessionInfo> sessionList)
        {
            uint sessionIdBitMask = (uint)SessionMask.FromEventKeywords((ulong)matchAllKeywords);
            // an ETW controller that specifies more than the mandated bit for our EventSource
            // will be ignored...
            if (bitcount(sessionIdBitMask) > 1)
                return;

            if (sessionList == null)
                sessionList = new List<SessionInfo>(8);

            if (bitcount(sessionIdBitMask) == 1)
            {
                // activity-tracing-aware etw session
                sessionList.Add(new SessionInfo(bitindex(sessionIdBitMask)+1, etwSessionId));
            }
            else
            {
                // legacy etw session
                sessionList.Add(new SessionInfo(bitcount((uint)SessionMask.All)+1, etwSessionId));
            }
        }

        /// <summary>
        /// This method enumerates over all active ETW sessions that have enabled 'this.m_Guid'
        /// for the current process ID, calling 'action' for each session, and passing it the
        /// ETW session and the 'AllKeywords' the session enabled for the current provider.
        /// </summary>
        [System.Security.SecurityCritical]
        private unsafe void GetSessionInfo(Action<int, long> action)
        {
            int buffSize = 256;     // An initial guess that probably works most of the time.
            byte* buffer;
            for (; ; )
            {
                var space = stackalloc byte[buffSize];
                buffer = space;
                var hr = 0;

                fixed (Guid* provider = &m_providerId)
                {
                    hr = UnsafeNativeMethods.ManifestEtw.EnumerateTraceGuidsEx(UnsafeNativeMethods.ManifestEtw.TRACE_QUERY_INFO_CLASS.TraceGuidQueryInfo,
                        provider, sizeof(Guid), buffer, buffSize, ref buffSize);
                }
                if (hr == 0)
                    break;
                if (hr != 122 /* ERROR_INSUFFICIENT_BUFFER */)
                    return;
            }

            var providerInfos = (UnsafeNativeMethods.ManifestEtw.TRACE_GUID_INFO*)buffer;
            var providerInstance = (UnsafeNativeMethods.ManifestEtw.TRACE_PROVIDER_INSTANCE_INFO*)&providerInfos[1];
            int processId = (int)Win32Native.GetCurrentProcessId();
            // iterate over the instances of the EventProvider in all processes
            for (int i = 0; i < providerInfos->InstanceCount; i++)
            {
                if (providerInstance->Pid == processId)
                {
                    var enabledInfos = (UnsafeNativeMethods.ManifestEtw.TRACE_ENABLE_INFO*)&providerInstance[1];
                    // iterate over the list of active ETW sessions "listening" to the current provider
                    for (int j = 0; j < providerInstance->EnableCount; j++)
                        action(enabledInfos[j].LoggerId, enabledInfos[j].MatchAllKeyword);
                }
                if (providerInstance->NextOffset == 0)
                    break;
                Contract.Assert(0 <= providerInstance->NextOffset && providerInstance->NextOffset < buffSize);
                var structBase = (byte*)providerInstance;
                providerInstance = (UnsafeNativeMethods.ManifestEtw.TRACE_PROVIDER_INSTANCE_INFO*)&structBase[providerInstance->NextOffset];
            }
        }

        /// <summary>
        /// Returns the index of the SesisonInfo from 'sessions' that has the specified 'etwSessionId'
        /// or -1 if the value is not present.
        /// <summary>
        private static int IndexOfSessionInList(List<SessionInfo> sessions, int etwSessionId)
        {
            if (sessions == null)
                return -1;
            // for non-coreclr code we could use List<T>.FindIndex(Predicate<T>), but we need this to compile
            // on coreclr as well
            for (int i = 0; i < sessions.Count; ++i)
                if (sessions[i].etwSessionId == etwSessionId)
                    return i;

            return -1;
        }

        /// <summary>
        /// Gets any data to be passed from the controller to the provider.  It starts with what is passed
        /// into the callback, but unfortunately this data is only present for when the provider is active
        /// at the the time the controller issues the command.  To allow for providers to activate after the
        /// controller issued a command, we also check the registry and use that to get the data.  The function
        /// returns an array of bytes representing the data, the index into that byte array where the data
        /// starts, and the command being issued associated with that data.
        /// </summary>
        [System.Security.SecurityCritical]
        private unsafe bool GetDataFromController(int etwSessionId,
                UnsafeNativeMethods.ManifestEtw.EVENT_FILTER_DESCRIPTOR* filterData, out ControllerCommand command, out byte[] data, out int dataStart)
        {
            data = null;
            dataStart = 0;
            if (filterData == null)
            {
                string regKey = @"\Microsoft\Windows\CurrentVersion\Winevt\Publishers\{" + m_providerId + "}";
                if (System.Runtime.InteropServices.Marshal.SizeOf(typeof(IntPtr)) == 8)
                    regKey = @"HKEY_LOCAL_MACHINE\Software" + @"\Wow6432Node" + regKey;
                else
                    regKey = @"HKEY_LOCAL_MACHINE\Software" + regKey;

                string valueName = "ControllerData_Session_" + etwSessionId.ToString(CultureInfo.InvariantCulture);

                // we need to assert this permission for partial trust scenarios
                new RegistryPermission(RegistryPermissionAccess.Read, regKey).Assert();

                data = Microsoft.Win32.Registry.GetValue(regKey, valueName, null) as byte[];
                if (data != null)
                {
                    // We only used the persisted data from the registry for updates.
                    command = ControllerCommand.Update;
                    return true;
                }
            }
            else
            {
                if (filterData->Ptr != 0 && 0 < filterData->Size && filterData->Size <= 1024)
                {
                    data = new byte[filterData->Size];
                    Marshal.Copy((IntPtr)filterData->Ptr, data, 0, data.Length);
                }
                command = (ControllerCommand) filterData->Type;
                return true;
            }

            command = ControllerCommand.Update;
            return false;
        }

        /// <summary>
        /// IsEnabled, method used to test if provider is enabled
        /// </summary>
        public bool IsEnabled()
        {
            return m_enabled;
        }

        /// <summary>
        /// IsEnabled, method used to test if event is enabled
        /// </summary>
        /// <param name="Lvl">
        /// Level  to test
        /// </param>
        /// <param name="Keyword">
        /// Keyword  to test
        /// </param>
        public bool IsEnabled(byte level, long keywords)
        {
            //
            // If not enabled at all, return false.
            //
            if (!m_enabled)
            {
                return false;
            }

            // This also covers the case of Level == 0.
            if ((level <= m_level) ||
                (m_level == 0))
            {

                //
                // Check if Keyword is enabled
                //

                if ((keywords == 0) ||
                    (((keywords & m_anyKeywordMask) != 0) &&
                     ((keywords & m_allKeywordMask) == m_allKeywordMask)))
                {
                    return true;
                }
            }

            return false;
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
        public static WriteEventErrorCode GetLastWriteEventError()
        {
            return s_returnCode;
        }

        //
        // Helper function to set the last error on the thread
        //
        private static void SetLastError(int error)
        {
            switch (error)
            {
                case UnsafeNativeMethods.ManifestEtw.ERROR_ARITHMETIC_OVERFLOW:
                case UnsafeNativeMethods.ManifestEtw.ERROR_MORE_DATA:
                    s_returnCode = WriteEventErrorCode.EventTooBig;
                    break;
                case UnsafeNativeMethods.ManifestEtw.ERROR_NOT_ENOUGH_MEMORY:
                    s_returnCode = WriteEventErrorCode.NoFreeBuffers;
                    break;
            }
        }

        // <SecurityKernel Critical="True" Ring="0">
        // <UsesUnsafeCode Name="Local intptrPtr of type: IntPtr*" />
        // <UsesUnsafeCode Name="Local intptrPtr of type: Int32*" />
        // <UsesUnsafeCode Name="Local longptr of type: Int64*" />
        // <UsesUnsafeCode Name="Local uintptr of type: UInt32*" />
        // <UsesUnsafeCode Name="Local ulongptr of type: UInt64*" />
        // <UsesUnsafeCode Name="Local charptr of type: Char*" />
        // <UsesUnsafeCode Name="Local byteptr of type: Byte*" />
        // <UsesUnsafeCode Name="Local shortptr of type: Int16*" />
        // <UsesUnsafeCode Name="Local sbyteptr of type: SByte*" />
        // <UsesUnsafeCode Name="Local ushortptr of type: UInt16*" />
        // <UsesUnsafeCode Name="Local floatptr of type: Single*" />
        // <UsesUnsafeCode Name="Local doubleptr of type: Double*" />
        // <UsesUnsafeCode Name="Local boolptr of type: Boolean*" />
        // <UsesUnsafeCode Name="Local guidptr of type: Guid*" />
        // <UsesUnsafeCode Name="Local decimalptr of type: Decimal*" />
        // <UsesUnsafeCode Name="Local booleanptr of type: Boolean*" />
        // <UsesUnsafeCode Name="Parameter dataDescriptor of type: EventData*" />
        // <UsesUnsafeCode Name="Parameter dataBuffer of type: Byte*" />
        // </SecurityKernel>
        [System.Security.SecurityCritical]
        private static unsafe string EncodeObject(ref object data, EventData* dataDescriptor, byte* dataBuffer)
        /*++

        Routine Description:

           This routine is used by WriteEvent to unbox the object type and
           to fill the passed in ETW data descriptor.

        Arguments:

           data - argument to be decoded

           dataDescriptor - pointer to the descriptor to be filled

           dataBuffer - storage buffer for storing user data, needed because cant get the address of the object

        Return Value:

           null if the object is a basic type other than string. String otherwise

        --*/
        {
            Again:
            dataDescriptor->Reserved = 0;

            string sRet = data as string;
            if (sRet != null)
            {
                dataDescriptor->Size = (uint)((sRet.Length + 1) * 2);
                return sRet;
            }

            if (data is IntPtr)
            {
                dataDescriptor->Size = (uint)sizeof(IntPtr);
                IntPtr* intptrPtr = (IntPtr*)dataBuffer;
                *intptrPtr = (IntPtr)data;
                dataDescriptor->Ptr = (ulong)intptrPtr;
            }
            else if (data is int)
            {
                dataDescriptor->Size = (uint)sizeof(int);
                int* intptr = (int*)dataBuffer;
                *intptr = (int)data;
                dataDescriptor->Ptr = (ulong)intptr;
            }
            else if (data is long)
            {
                dataDescriptor->Size = (uint)sizeof(long);
                long* longptr = (long*)dataBuffer;
                *longptr = (long)data;
                dataDescriptor->Ptr = (ulong)longptr;
            }
            else if (data is uint)
            {
                dataDescriptor->Size = (uint)sizeof(uint);
                uint* uintptr = (uint*)dataBuffer;
                *uintptr = (uint)data;
                dataDescriptor->Ptr = (ulong)uintptr;
            }
            else if (data is UInt64)
            {
                dataDescriptor->Size = (uint)sizeof(ulong);
                UInt64* ulongptr = (ulong*)dataBuffer;
                *ulongptr = (ulong)data;
                dataDescriptor->Ptr = (ulong)ulongptr;
            }
            else if (data is char)
            {
                dataDescriptor->Size = (uint)sizeof(char);
                char* charptr = (char*)dataBuffer;
                *charptr = (char)data;
                dataDescriptor->Ptr = (ulong)charptr;
            }
            else if (data is byte)
            {
                dataDescriptor->Size = (uint)sizeof(byte);
                byte* byteptr = (byte*)dataBuffer;
                *byteptr = (byte)data;
                dataDescriptor->Ptr = (ulong)byteptr;
            }
            else if (data is short)
            {
                dataDescriptor->Size = (uint)sizeof(short);
                short* shortptr = (short*)dataBuffer;
                *shortptr = (short)data;
                dataDescriptor->Ptr = (ulong)shortptr;
            }
            else if (data is sbyte)
            {
                dataDescriptor->Size = (uint)sizeof(sbyte);
                sbyte* sbyteptr = (sbyte*)dataBuffer;
                *sbyteptr = (sbyte)data;
                dataDescriptor->Ptr = (ulong)sbyteptr;
            }
            else if (data is ushort)
            {
                dataDescriptor->Size = (uint)sizeof(ushort);
                ushort* ushortptr = (ushort*)dataBuffer;
                *ushortptr = (ushort)data;
                dataDescriptor->Ptr = (ulong)ushortptr;
            }
            else if (data is float)
            {
                dataDescriptor->Size = (uint)sizeof(float);
                float* floatptr = (float*)dataBuffer;
                *floatptr = (float)data;
                dataDescriptor->Ptr = (ulong)floatptr;
            }
            else if (data is double)
            {
                dataDescriptor->Size = (uint)sizeof(double);
                double* doubleptr = (double*)dataBuffer;
                *doubleptr = (double)data;
                dataDescriptor->Ptr = (ulong)doubleptr;
            }
            else if (data is bool)
            {
                // WIN32 Bool is 4 bytes
                dataDescriptor->Size = 4;
                int* intptr = (int*)dataBuffer;
                if (((bool)data))
                {
                    *intptr = 1;
                }
                else
                {
                    *intptr = 0;
                }
                dataDescriptor->Ptr = (ulong)intptr;
            }
            else if (data is Guid)
            {
                dataDescriptor->Size = (uint)sizeof(Guid);
                Guid* guidptr = (Guid*)dataBuffer;
                *guidptr = (Guid)data;
                dataDescriptor->Ptr = (ulong)guidptr;
            }
            else if (data is decimal)
            {
                dataDescriptor->Size = (uint)sizeof(decimal);
                decimal* decimalptr = (decimal*)dataBuffer;
                *decimalptr = (decimal)data;
                dataDescriptor->Ptr = (ulong)decimalptr;
            }
            else if (data is DateTime)
            {
                long dateTimeTicks = ((DateTime)data).ToFileTimeUtc();
                dataDescriptor->Size = (uint)sizeof(long);
                long* longptr = (long*)dataBuffer;
                *longptr = dateTimeTicks;
                dataDescriptor->Ptr = (ulong)longptr;
            }
            else
            {
                if (data is System.Enum)
                {
                    Type underlyingType = Enum.GetUnderlyingType(data.GetType());
                    if (underlyingType == typeof(int))
                    {
                        data = ((IConvertible)data).ToInt32(null);
                        goto Again;
                    }
                    else if (underlyingType == typeof(long))
                    {
                        data = ((IConvertible)data).ToInt64(null);
                        goto Again;
                    }
                }

                //To our eyes, everything else is a just a string
                if (data == null)
                    sRet = "";
                else
                    sRet = data.ToString();
                dataDescriptor->Size = (uint)((sRet.Length + 1) * 2);
                return sRet;
            }

            return null;
        }

        /// <summary>
        /// WriteEvent, method to write a parameters with event schema properties
        /// </summary>
        /// <param name="EventDescriptor">
        /// Event Descriptor for this event.
        /// </param>
        // <SecurityKernel Critical="True" Ring="0">
        // <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventWrite(System.Int64,EventDescriptor&,System.UInt32,System.Void*):System.UInt32" />
        // <UsesUnsafeCode Name="Local dataBuffer of type: Byte*" />
        // <UsesUnsafeCode Name="Local pdata of type: Char*" />
        // <UsesUnsafeCode Name="Local userData of type: EventData*" />
        // <UsesUnsafeCode Name="Local userDataPtr of type: EventData*" />
        // <UsesUnsafeCode Name="Local currentBuffer of type: Byte*" />
        // <UsesUnsafeCode Name="Local v0 of type: Char*" />
        // <UsesUnsafeCode Name="Local v1 of type: Char*" />
        // <UsesUnsafeCode Name="Local v2 of type: Char*" />
        // <UsesUnsafeCode Name="Local v3 of type: Char*" />
        // <UsesUnsafeCode Name="Local v4 of type: Char*" />
        // <UsesUnsafeCode Name="Local v5 of type: Char*" />
        // <UsesUnsafeCode Name="Local v6 of type: Char*" />
        // <UsesUnsafeCode Name="Local v7 of type: Char*" />
        // <ReferencesCritical Name="Method: EncodeObject(Object&, EventData*, Byte*):String" Ring="1" />
        // </SecurityKernel>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Performance-critical code")]
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")]
        [System.Security.SecurityCritical]
        internal unsafe bool WriteEvent(ref EventDescriptor eventDescriptor, Guid* childActivityID, params object[] eventPayload)
        {
            int status = 0;

            if (IsEnabled(eventDescriptor.Level, eventDescriptor.Keywords))
            {
                int argCount = 0;
                unsafe
                {
                    argCount = eventPayload.Length;

                    if (argCount > s_etwMaxMumberArguments)
                    {
                        s_returnCode = WriteEventErrorCode.TooManyArgs;
                        return false;
                    }

                    uint totalEventSize = 0;
                    int index;
                    int stringIndex = 0;
                    List<int> stringPosition = new List<int>(s_etwAPIMaxStringCount);
                    List<string> dataString = new List<string>(s_etwAPIMaxStringCount);
                    EventData* userData = stackalloc EventData[argCount];
                    EventData* userDataPtr = (EventData*)userData;
                    byte* dataBuffer = stackalloc byte[s_basicTypeAllocationBufferSize * argCount]; // Assume 16 chars for non-string argument
                    byte* currentBuffer = dataBuffer;

                    //
                    // The loop below goes through all the arguments and fills in the data
                    // descriptors. For strings save the location in the dataString array.
                    // Calculates the total size of the event by adding the data descriptor
                    // size value set in EncodeObject method.
                    //
                    for (index = 0; index < eventPayload.Length; index++)
                    {
                        if (eventPayload[index] != null)
                        {
                            string isString;
                            isString = EncodeObject(ref eventPayload[index], userDataPtr, currentBuffer);
                            currentBuffer += s_basicTypeAllocationBufferSize;
                            totalEventSize += userDataPtr->Size;
                            userDataPtr++;
                            if (isString != null)
                            {
                                dataString.Add(isString);
                                stringPosition.Add(index);
                                stringIndex++;
                            }
                        }
                        else
                        {
                            s_returnCode = WriteEventErrorCode.NullInput;
                            return false;
                        }
                    }

                    if (totalEventSize > s_traceEventMaximumSize)
                    {
                        s_returnCode = WriteEventErrorCode.EventTooBig;
                        return false;
                    }

                    if (stringIndex < s_etwAPIMaxStringCount)
                    {
                        // Fast path: at most 8 string arguments

                        // ensure we have at least s_etwAPIMaxStringCount in dataString, so that
                        // the "fixed" statement below works
                        while (stringIndex < s_etwAPIMaxStringCount)
                        {
                            dataString.Add(null);
                            ++stringIndex;
                        }

                        //
                        // now fix any string arguments and set the pointer on the data descriptor
                        //
                        fixed (char* v0 = dataString[0], v1 = dataString[1], v2 = dataString[2], v3 = dataString[3],
                                v4 = dataString[4], v5 = dataString[5], v6 = dataString[6], v7 = dataString[7])
                        {
                            userDataPtr = (EventData*)userData;
                            if (dataString[0] != null)
                            {
                                userDataPtr[stringPosition[0]].Ptr = (ulong)v0;
                            }
                            if (dataString[1] != null)
                            {
                                userDataPtr[stringPosition[1]].Ptr = (ulong)v1;
                            }
                            if (dataString[2] != null)
                            {
                                userDataPtr[stringPosition[2]].Ptr = (ulong)v2;
                            }
                            if (dataString[3] != null)
                            {
                                userDataPtr[stringPosition[3]].Ptr = (ulong)v3;
                            }
                            if (dataString[4] != null)
                            {
                                userDataPtr[stringPosition[4]].Ptr = (ulong)v4;
                            }
                            if (dataString[5] != null)
                            {
                                userDataPtr[stringPosition[5]].Ptr = (ulong)v5;
                            }
                            if (dataString[6] != null)
                            {
                                userDataPtr[stringPosition[6]].Ptr = (ulong)v6;
                            }
                            if (dataString[7] != null)
                            {
                                userDataPtr[stringPosition[7]].Ptr = (ulong)v7;
                            }

                            if (childActivityID == null)
                                status = UnsafeNativeMethods.ManifestEtw.EventWrite(m_regHandle, ref eventDescriptor, argCount, userData);
                            else
                                status = UnsafeNativeMethods.ManifestEtw.EventWriteTransfer(m_regHandle, ref eventDescriptor, null, childActivityID, argCount, userData);
                        }
                    }
                    else
                    {
                        // Slow path: use pinned handles
                        userDataPtr = (EventData*)userData;

                        GCHandle[] rgGCHandle = new GCHandle[stringIndex];
                        for (int i = 0; i < stringIndex; ++i)
                        {
                            rgGCHandle[i] = GCHandle.Alloc(dataString[i], GCHandleType.Pinned);
                            fixed (char* p = dataString[i])
                                userDataPtr[stringPosition[i]].Ptr = (ulong)p;
                        }

                        if (childActivityID == null)
                            status = UnsafeNativeMethods.ManifestEtw.EventWrite(m_regHandle, ref eventDescriptor, argCount, userData);
                        else
                            status = UnsafeNativeMethods.ManifestEtw.EventWriteTransfer(m_regHandle, ref eventDescriptor, null, childActivityID, argCount, userData);

                        for (int i = 0; i < stringIndex; ++i)
                        {
                            rgGCHandle[i].Free();
                        }
                    }

                }
            }

            if (status != 0)
            {
                SetLastError((int)status);
                return false;
            }

            return true;
        }

        /// <summary>
        /// WriteEvent, method to be used by generated code on a derived class
        /// </summary>
        /// <param name="eventDescriptor">
        /// Event Descriptor for this event.
        /// </param>
        /// <param name="childActivityID">
        /// If this event is generating a child activity (WriteEventTransfer related activity) this is child activity
        /// This can be null for events that do not generate a child activity.
        /// </param>
        /// <param name="dataCount">
        /// number of event descriptors
        /// </param>
        /// <param name="data">
        /// pointer  do the event data
        /// </param>
        // <SecurityKernel Critical="True" Ring="0">
        // <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventWrite(System.Int64,EventDescriptor&,System.UInt32,System.Void*):System.UInt32" />
        // </SecurityKernel>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")]
        [System.Security.SecurityCritical]
        internal unsafe protected bool WriteEvent(ref EventDescriptor eventDescriptor, Guid* childActivityID, int dataCount, IntPtr data)
        {
            int status;
            if (childActivityID == null)
            {
                status = UnsafeNativeMethods.ManifestEtw.EventWrite(m_regHandle, ref eventDescriptor, dataCount, (EventData*)data);
            }
            else
            {
                // activity transfers are supported only for events that specify the Send or Receive opcode
                Contract.Assert((EventOpcode)eventDescriptor.Opcode == EventOpcode.Send ||
                                (EventOpcode)eventDescriptor.Opcode == EventOpcode.Receive);
                status = UnsafeNativeMethods.ManifestEtw.EventWriteTransfer(m_regHandle, ref eventDescriptor, null, childActivityID, dataCount, (EventData*)data);
            }
            if (status != 0)
            {
                SetLastError(status);
                return false;
            }
            return true;
        }

        [System.Security.SecurityCritical]
        internal unsafe protected bool WriteEventString(EventLevel level, long keywords, string msg)
        {
            int status;

            status = UnsafeNativeMethods.ManifestEtw.EventWriteString(m_regHandle, (byte) level, keywords, msg);

            if (status != 0)
            {
                SetLastError(status);
                return false;
            }
            return true;
        }

        // These are look-alikes to the Manifest based ETW OS APIs that have been shimmed to work
        // either with Manifest ETW or Classic ETW (if Manifest based ETW is not available).
        [SecurityCritical]
        private unsafe uint EventRegister(ref Guid providerId, UnsafeNativeMethods.ManifestEtw.EtwEnableCallback enableCallback)
        {
            m_providerId = providerId;
            m_etwCallback = enableCallback;
            return UnsafeNativeMethods.ManifestEtw.EventRegister(ref providerId, enableCallback, null, ref m_regHandle);
        }

        [SecurityCritical]
        private uint EventUnregister()
        {
            uint status = UnsafeNativeMethods.ManifestEtw.EventUnregister(m_regHandle);
            m_regHandle = 0;
            return status;
        }

        static int[] nibblebits = {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4};
        private static int bitcount(uint n)
        {
            int count = 0;
            for(; n != 0; n = n >> 4)
                count += nibblebits[n & 0x0f];
            return count;
        }
        private static int bitindex(uint n)
        {
            Contract.Assert(bitcount(n) == 1);
            int idx = 0;
            while ((n & (1 << idx)) == 0)
                idx++;
            return idx;
        }
    }
}


text:
package de.knightsoftnet.validators.client.impl;

import com.google.gwt.core.client.GWT;

import java.util.List;

import javax.validation.Configuration;
import javax.validation.ValidationException;
import javax.validation.ValidationProviderResolver;
import javax.validation.ValidatorFactory;
import javax.validation.bootstrap.GenericBootstrap;
import javax.validation.bootstrap.ProviderSpecificBootstrap;
import javax.validation.spi.BootstrapState;
import javax.validation.spi.ValidationProvider;

/**
 * This class is the entry point for Bean Validation. Bootstrapping is done as follows:
 *
 *

 * {
 *   @code
 *   ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
 * }
 *

 *
 *

 * Or, equivalently:
 *

 *
 *

 * {
 *   @code
 *   Configuration<?> configuration = Validation.byDefaultProvider().configure();
 *   ValidatorFactory factory = configuration.buildValidatorFactory();
 * }
 *

 *
 *

 * Only the default provider is available for use, and thus the {@code byProvider} and
 * {@code providerResolver} methods are not supported. Calling either of these methods will generate
 * an exception.
 *

 *

 * This class was modified by Google from the original javax.validation.Validation source to make it
 * suitable for GWT.
 *

 */
public class Validation {

  // private class, not exposed
  private static class GenericGwtBootstrapImpl implements GenericBootstrap, BootstrapState {

    private ValidationProviderResolver defaultResolver;

    @Override
    public Configuration<?> configure() {
      final ValidationProviderResolver aResolver = getDefaultValidationProviderResolver();

      List<ValidationProvider<?>> resolvers;
      try {
        resolvers = aResolver.getValidationProviders();
      } catch (final RuntimeException re) {
        throw new ValidationException("Unable to get available provider resolvers.", re);
      }

      if (resolvers.isEmpty()) {
        // FIXME looks like an assertion error almost
        throw new ValidationException("Unable to find a default provider");
      }

      Configuration<?> config;
      try {
        config = aResolver.getValidationProviders().get(0).createGenericConfiguration(this);
      } catch (final RuntimeException re) {
        throw new ValidationException("Unable to instantiate Configuration.", re);
      }

      return config;
    }

    @Override
    public ValidationProviderResolver getDefaultValidationProviderResolver() {
      if (defaultResolver == null) {
        defaultResolver = GWT.create(ValidationProviderResolver.class);
      }
      return defaultResolver;
    }

    @Override
    public ValidationProviderResolver getValidationProviderResolver() {
      return getDefaultValidationProviderResolver();
    }

    /**
     * Unsupported. Always throws an {@link UnsupportedOperationException}.
     *
     * @throws UnsupportedOperationException not supported
     */
    @Override
    public GenericBootstrap providerResolver(final ValidationProviderResolver resolver) {
      throw new UnsupportedOperationException(
          "GWT Validation does not support custom validator " + "provider resolvers");
    }
  }

  /**
   * Build and return a ValidatorFactory instance based on the default Bean Validation
   * provider.
   *

   * The provider list is resolved using the default validation provider resolver logic.
   *

   * The code is semantically equivalent to
   * Validation.byDefaultProvider().configure().buildValidatorFactory()
   *
   * @return ValidatorFactory instance.
   *
   * @throws ValidationException if the ValidatorFactory cannot be built
   */
  public static ValidatorFactory buildDefaultValidatorFactory() {
    return byDefaultProvider().configure().buildValidatorFactory();
  }

  /**
   * Build a Configuration.
   *
   *

   * Configuration<?> configuration = Validation.byDefaultProvider().configure();
   * ValidatorFactory factory = configuration.buildValidatorFactory();
   *

   *
   *

   * The first available provider will be returned.
   *

   *
   * @return instance building a generic Configuration complaint with the bootstrap
   *         state provided.
   */
  public static GenericBootstrap byDefaultProvider() {
    return new GenericGwtBootstrapImpl();
  }

  /**
   * Unsupported. Always throws an {@link UnsupportedOperationException}.
   *
   * @param <T> configuration type
   * @param  validation provider type
   *
   * @param providerType class of the provider type
   * @return provider specific bootstrap
   *
   * @throws UnsupportedOperationException not supported
   */
  public static <T extends Configuration<T>, U extends ValidationProvider<T>> //
      ProviderSpecificBootstrap<T> //
      byProvider(final Class providerType) {
    throw new UnsupportedOperationException(
        "GWT Validation does not support custom validator " + "providers");
  }
}

redpajama_set_name: RedPajamaGithub


text:
Please include the template below to ensure a more accurate response to your issue.

- **Node Version**: `node --version`
- **tiny-core-terminal version**: `npm info tiny-care-terminal | grep version:`
- **Shell**: `bash, zsh, fish, something else?`
- **Terminal Program**: `tmux, iterm, terminator, cmd, something else?`
- **Operating System**: `Mac, Windows, Linux, BSD, Really, something else?`

Thank you!


text:
$(document).ready(function(){

	// Displaying random banner ads below the game
	var bannerArray = [
		{"url":"https://www.youtube.com/watch?v=POnldqfm3Rw","banner":"img/trailerad.png"},
		{"url":"https://www.youtube.com/watch?v=POnldqfm3Rw","banner":"img/malloryad.png"},
		{"url":"https://twitter.com/hashtag/MakeFlappyWumpusGreatAgain?src=hash","banner":"img/electionad.png"},
		{"url":"https://soundcloud.com/cheesecast/its-time-to-softsoap","banner":"img/songad.png"},
		{"url":"https://www.youtube.com/watch?v=xUVz4nRmxn4","banner":"img/milliondollarsad.png"},
	    {"url":"https://twitter.com/hashtag/MakeFlappyWumpusGreatAgain?src=hash","banner":"img/mfwgaad.png"}]

	var selectBanner = bannerArray[Math.floor(Math.random()*bannerArray.length)];

	$('#bottom-banner__inner').html('');

	function setFocusGameIframe() {
		var iframe = $("#iframe")[0];
		iframe.contentWindow.focus();
	}

	$("#game-container").click(function(){
      setTimeout(setFocusGameIframe, 100);
      return false;
   });

});


text:
package com.amashchenko.eclipse.strutsclipse;

import java.util.Iterator;
import java.util.List;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IStorage;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.hyperlink.AbstractHyperlinkDetector;
import org.eclipse.jface.text.hyperlink.IHyperlink;
import org.eclipse.ui.IEditorDescriptor;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IPersistableElement;
import org.eclipse.ui.IStorageEditorInput;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.part.MultiPageEditorPart;
import org.eclipse.ui.texteditor.ITextEditor;

public abstract class AbstractStrutsHyperlinkDetector extends
		AbstractHyperlinkDetector {

	protected IHyperlink[] linksListToArray(List<IHyperlink> linksList) {
		IHyperlink[] links = null;
		if (linksList != null && !linksList.isEmpty()) {
			// remove null-s
			Iterator<IHyperlink> itr = linksList.iterator();
			while (itr.hasNext()) {
				if (itr.next() == null) {
					itr.remove();
				}
			}

			if (!linksList.isEmpty()) {
				links = linksList.toArray(new IHyperlink[linksList.size()]);
			}
		}
		return links;
	}

	// helper method for IHyperlink-s
	public static void selectAndReveal(IEditorPart editorPart,
			IRegion highlightRange) {
		ITextEditor textEditor = null;

		if (editorPart instanceof MultiPageEditorPart) {
			MultiPageEditorPart part = (MultiPageEditorPart) editorPart;

			Object editorPage = part.getSelectedPage();
			if (editorPage != null && editorPage instanceof ITextEditor) {
				textEditor = (ITextEditor) editorPage;
			}
		} else if (editorPart instanceof ITextEditor) {
			textEditor = (ITextEditor) editorPart;
		}

		// highlight range in editor if possible
		if (highlightRange != null && textEditor != null) {
			textEditor.selectAndReveal(highlightRange.getOffset(),
					highlightRange.getLength());
		}
	}

	public static class FileHyperlink implements IHyperlink {
		private final IFile fFile;
		private final IRegion fRegion;
		private final IRegion fHighlightRange;

		public FileHyperlink(IRegion region, IFile file) {
			this(region, file, null);
		}

		public FileHyperlink(IRegion region, IFile file, IRegion range) {
			fRegion = region;
			fFile = file;
			fHighlightRange = range;
		}

		@Override
		public IRegion getHyperlinkRegion() {
			return fRegion;
		}

		@Override
		public String getHyperlinkText() {
			return fFile == null ? null : fFile.getProjectRelativePath()
					.toString();
		}

		@Override
		public String getTypeLabel() {
			return null;
		}

		@Override
		public void open() {
			try {
				IWorkbenchPage page = PlatformUI.getWorkbench()
						.getActiveWorkbenchWindow().getActivePage();
				IEditorPart editor = IDE.openEditor(page, fFile, true);

				selectAndReveal(editor, fHighlightRange);
			} catch (PartInitException e) {
			}
		}
	}

	public static class JavaElementHyperlink implements IHyperlink {
		private final IJavaElement fElement;
		private final IRegion fRegion;

		public JavaElementHyperlink(IRegion region, IJavaElement element) {
			fRegion = region;
			fElement = element;
		}

		@Override
		public IRegion getHyperlinkRegion() {
			return fRegion;
		}

		@Override
		public String getHyperlinkText() {
			String name = null;
			if (fElement != null) {
				if (fElement.getParent() == null) {
					name = fElement.getElementName();
				} else {
					name = fElement.getParent().getElementName() + "#"
							+ fElement.getElementName();
				}
			}
			return name;
		}

		@Override
		public String getTypeLabel() {
			return null;
		}

		@Override
		public void open() {
			try {
				JavaUI.openInEditor(fElement);
			} catch (PartInitException e) {
			} catch (JavaModelException e) {
			}
		}
	}

	public static class StorageHyperlink implements IHyperlink {
		private final IStorage fStorage;
		private final IRegion fRegion;
		private final IRegion fHighlightRange;

		public StorageHyperlink(IRegion region, IStorage storage, IRegion range) {
			fRegion = region;
			fStorage = storage;
			fHighlightRange = range;
		}

		@Override
		public IRegion getHyperlinkRegion() {
			return fRegion;
		}

		@Override
		public String getHyperlinkText() {
			return fStorage == null ? null : fStorage.getFullPath().toString();
		}

		@Override
		public String getTypeLabel() {
			return null;
		}

		@Override
		public void open() {
			try {
				IWorkbenchPage page = PlatformUI.getWorkbench()
						.getActiveWorkbenchWindow().getActivePage();

				IEditorDescriptor editorDescriptor = IDE
						.getEditorDescriptor(fStorage.getName());

				IEditorPart editor = page.openEditor(new StorageEditorInput(
						fStorage), editorDescriptor.getId());

				selectAndReveal(editor, fHighlightRange);
			} catch (PartInitException e) {
			}
		}
	}

	private static class StorageEditorInput implements IStorageEditorInput {
		private final IStorage fStorage;

		private StorageEditorInput(IStorage storage) {
			fStorage = storage;
		}

		@Override
		public boolean exists() {
			return fStorage != null;
		}

		@Override
		public ImageDescriptor getImageDescriptor() {
			return null;
		}

		@Override
		public String getName() {
			return fStorage.getName();
		}

		@Override
		public IPersistableElement getPersistable() {
			return null;
		}

		@Override
		public IStorage getStorage() {
			return fStorage;
		}

		@Override
		public String getToolTipText() {
			return fStorage.getFullPath() != null ? fStorage.getFullPath()
					.toString() : fStorage.getName();
		}

		@Override
		public boolean equals(Object obj) {
			if (obj instanceof StorageEditorInput) {
				return fStorage.equals(((StorageEditorInput) obj).fStorage);
			}
			return super.equals(obj);
		}

		@SuppressWarnings("rawtypes")
		@Override
		public Object getAdapter(Class adapter) {
			return null;
		}
	}
}


text:
import pytest

@pytest.fixture
def page():
    return{
        'name': 'Fake Page',
    }

@pytest.fixture
def page_1(page):
    item = page.copy()
    item.update({
        'schema_version': '1',
        'news_keywords': ['RNA binding', 'Experiment', 'DNA methylation', 'promoter-like regions', 'Conferences'],
    })
    return item

@pytest.fixture
def page_2(page):
    item = page.copy()
    item.update({
        'schema_version': '1',
        'news_keywords': ['Experiment', 'promoter-like regions'],
    })
    return item

@pytest.fixture
def page_3(page):
    item = page.copy()
    item.update({
        'schema_version': '1',
    })
    return item

def test_page_upgrade_keep(upgrader, page_1):
    value = upgrader.upgrade('page', page_1, target_version='2')
    assert value['schema_version'] == '2'
    assert value['news_keywords'] == ['RNA binding', 'DNA methylation', 'Conferences']

def test_page_upgrade_empty(upgrader, page_2):
    value = upgrader.upgrade('page', page_2, target_version='2')
    assert value['schema_version'] == '2'
    assert value['news_keywords'] == []

def test_page_upgrade_none(upgrader, page_3):
    value = upgrader.upgrade('page', page_3, target_version='2')
    assert value['schema_version'] == '2'
    assert 'news_keywords' not in value


text:
(function(exports) {

    // Dependencies -----------------------------------------------------------
    var Class = require('./Class').Class;

    // Implementation ---------------------------------------------------------
    exports.Emitter = Class(function() {
        this._emitterEvents = {};

    }, {

        /**
          * {Function} Bind a @callback {Function} for any event with the @name {String}
          * in the optional @scope {Object?} and return the @callback.
          *
          * In case @once {Boolean} is set, the callback will be unbound after it has
          * been fired once.
          */
        on: function(name, callback, scope, once) {

            var events = null;
            if (!(events = this._emitterEvents[name])) {
                events = this._emitterEvents[name] = [];
            }

            events.push({
                callback: callback,
                scope: scope || this,
                once: once,
                fired: false
            });

            return callback;

        },

        /**
          * Like {Emitter#on} but will only fire once and then get removed.
          */
        once: function(name, callback, scope) {
            return this.on(name, callback, scope, true);
        },

        /**
          * Emits the event @name {String} with the params @arguments {Arguments}
          */
        emit: function(name) {

            var id = name;

            // Go up to parent
            var events = this._emitterEvents[id],
                stopped = false;

            if (events) {

                var call = Function.prototype.call;

                // Create a shallow copy to protect against unbinds
                // from within the callbacks
                var sliced = events.slice();
                for(var i = 0, l = sliced.length; i < l; i++) {

                    var event = events[i];
                    if (!event.once || !event.fired) {

                        event.fired = true;

                        var args = Array.prototype.slice.call(arguments);
                        args[0] = event.scope || this;
                        stopped = call.apply(event.callback, args) || stopped;

                    }

                    if (event.once) {
                        events.splice(i, 1);
                        i--;
                        l--;
                    }

                }

            }

            return stopped;

        },

        /**
          * {Integer} If the first argument is a {Function} all events for the given function
          * will be unbound. If only @name {String} is set, all callbacks for the
          * given event will be removed. If both parameters are set, they'll act
          * as a filter.
          *
          * Returns the number of unbound callbacks.
          */
        unbind: function(name, func) {

            if (typeof name === 'function') {
                name = null;
                func = name;
            }

            var count = 0;
            if (name) {

                if (func) {

                    var events = this._emitterEvents[name];
                    if (events) {

                        for(var i = 0, l = events.length; i < l; i++) {

                            if (events[i].callback === func) {
                                events.splice(i, 1);
                                i--;
                                l--;
                            }

                        }

                    }

                } else {
                    count = this._emitterEvents[name];
                    delete this._emitterEvents[name];
                }

            } else {

                for(var e in this._emitterEvents) {
                    if (this._emitterEvents.hasOwnProperty(e)) {
                        this.unbind(e, func);
                    }
                }

            }

        }

    });

})(typeof exports !== 'undefined' ? exports : this);


text:
package zoara.sfs2x.extension.handlers.quests;

import zoara.sfs2x.extension.simulation.ActivePlayer;
import zoara.sfs2x.extension.simulation.Quest;
import zoara.sfs2x.extension.simulation.World;
import zoara.sfs2x.extension.utils.RoomHelper;

import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.extensions.BaseClientRequestHandler;

public class NewQuestHandler extends BaseClientRequestHandler
{
    @Override
    public void handleClientRequest(User user, ISFSObject data)
    {
    	trace("Adding new quest for: " + user.getId());

		World world = RoomHelper.getWorld(this);
		ActivePlayer player = world.getPlayer(user);
		if (player == null)
			return;

		Quest quest = player.quests.addQuest(data.getUtfString("UniqueQuestID"));
		quest.setTemplateID(data.getInt("TemplateID"));
		quest.setUniqueID(data.getUtfString("UniqueQuestID"));
		//quest.setActive(data.getBool("Active"));
		if (data.containsKey("Completed"))
			quest.setCompleted(data.getBool("Completed"));
		if (data.containsKey("Failed"))
			quest.setFailed(data.getBool("Failed"));
		if (data.containsKey("CurrentStepNumber"))
			quest.setCurrentStepNumber(data.getInt("CurrentStepNumber"));
    }
}


text:
package com.healthcit.analytics.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Service;

import com.healthcit.analytics.dao.impl.UserDAO;
import com.healthcit.analytics.model.Role;
import com.healthcit.analytics.model.User;

@Service("userManager")
public class UserManager implements UserDetailsManager {

	@Autowired
	private UserDAO userDao;

	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		return this.userDao.loadUserByUsername(username);
	}

	@Override
	public void createUser(UserDetails user) {
		this.userDao.createUser(user);
	}

	@Override
	public void updateUser(UserDetails user) {
		this.userDao.updateUser(user);
	}

	@Override
	public void deleteUser(String username) {
		this.userDao.deleteUser(username);
	}

	@Override
	public void changePassword(String oldPassword, String newPassword) {
		this.userDao.changePassword(oldPassword, newPassword);

	}

	@Override
	public boolean userExists(String username) {
		return this.userDao.userExists(username);
	}

	public UserDetails loadUserById(Long id) {
		return this.userDao.loadUserById(id);
	}

	public List<User> loadUsers(){
		return this.userDao.loadUsers();
	}

	public List<Role> getRoles(){
		return this.userDao.getRoles();
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <!-- <item android:state_focused="true" android:color="@color/testcolor1"/> -->
   <item android:state_checked="true" android:color="@color/colorWhite"/>
   <!-- <item android:state_enabled="false" android:color="@color/testcolor3" />  -->
   <item android:color="@color/colorGray"/>
</selector>


text:
from flask_sqlalchemy import SQLAlchemy
import os

WTF_CSRF_ENABLED = True

# DB settings
basedir = os.path.abspath(os.path.dirname(__file__))

DATABASE = 'fletter.db'
DEBUG = True
SECRET_KEY = 'secret_key'
USERNAME = 'admin'
PASSWORD = 'admin'

# defines the full path for the database
DATABASE_PATH = os.path.join(basedir, DATABASE)

# the database uri
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + DATABASE_PATH
SQLALCHEMY_TRACK_MODIFICATIONS = 'True'


text:
siggenes(Rpackage)

Build and run the container

$docker build -t siggenes .
$docker run -it --name=demo_siggenes siggenes

Test the working of Container:

Inside the container type R and enter the R shell. Execute following commands:

>> library(siggenes)
>> x <- rnorm(10000)
>> out <- denspr(x, addx=TRUE)

OUTPUT:
Loading required package: KernSmooth
KernSmooth 2.23 loaded
Copyright M. P. Wand 1997-2009

>> plot(out)


text:
notes: Follow the if statement's logic to build a loading indicator based on the color. If an image is provided, the avatar works as expected. In all other cases, the system should generate a pseudo-avatar featuring a background-color (inline-style) and the user's initials in all caps. The default color is just an example. This could be any size. Just pass different combinations of width and height to the link (like .w-36px .h-36px in this example).
---

  {{#if image}}

  {{ else }}

    <svg width="90%" height="90%" class="db" viewBox="0 0 36 36">
      <text x="18" y="24.3" text-anchor="middle" font-family="-apple-system, BlinkMacSystemFont,roboto,'avenir next', avenir, helvetica, 'helvetica neue', ubuntu, noto, 'segoe ui', arial, sans-serif;" font-weight="700">

        {{#if userInitials}}{{userInitials}}{{else}}DM{{/if}}</text>
    </svg>

  {{/if}}


text:
var FREQUENCY = 5.0;

var AMPLITUDE = 45.0;

var cumulativeTime = 0.0;

var jointList = MyAvatar.getJointNames();
var jointMappings = "\n# Joint list start";
for (var i = 0; i < jointList.length; i++) {
    jointMappings = jointMappings + "\njointIndex = " + jointList[i] + " = " + i;
}
print(jointMappings + "\n# Joint list end");

Script.update.connect(function(deltaTime) {
    cumulativeTime += deltaTime;
    MyAvatar.setJointData("RightUpLeg", Quat.fromPitchYawRollDegrees(AMPLITUDE * Math.sin(cumulativeTime * FREQUENCY), 0.0, 0.0));
    MyAvatar.setJointData("LeftUpLeg", Quat.fromPitchYawRollDegrees(-AMPLITUDE * Math.sin(cumulativeTime * FREQUENCY), 0.0, 0.0));
    MyAvatar.setJointData("RightLeg", Quat.fromPitchYawRollDegrees(
        AMPLITUDE * (1.0 + Math.sin(cumulativeTime * FREQUENCY)),0.0, 0.0));
    MyAvatar.setJointData("LeftLeg", Quat.fromPitchYawRollDegrees(
        AMPLITUDE * (1.0 - Math.sin(cumulativeTime * FREQUENCY)),0.0, 0.0));
});

Script.scriptEnding.connect(function() {
    MyAvatar.clearJointData("RightUpLeg");
    MyAvatar.clearJointData("LeftUpLeg");
    MyAvatar.clearJointData("RightLeg");
    MyAvatar.clearJointData("LeftLeg");
});


text:
port = "COM3"
joystickIndex = 2

# start services
arduino = Runtime.createAndStart("arduino","Arduino")
joy = runtime.createAndStart("joy","Joystick")
dx 	= Runtime.createAndStart("dx","Servo")
sx	= Runtime.createAndStart("sx","Servo")

arduino.connect(port)
joy.setController(joystickIndex)

#activate joystick
joy.startPolling()

arduino.attach(dx.getName() , 3)
arduino.attach(sx.getName(), 6)
def forward():
 dx.moveTo(120)
 sx.moveTo(60)
 return
def back():
 dx.moveTo(60)
 sx.moveTo(120)
 return
def turnR ():
 dx.moveTo(120)
 sx.moveTo(120)
 return
def turnL ():
 dx.moveTo(60)
 sx.moveTo(60)
 return
def stop ():
 dx.moveTo(90)
 sx.moveTo(90)
 return

def x():
    x = msg_joy_XAxisRaw.data[0]
    print x
    if (x == 1):
     turnR()
    elif (x == -1):
     turnL()
    else :
     stop()
    return
def y():
    y = msg_joy_YAxisRaw.data[0]
    print y
    if (y == -1):
     forward()
    elif (y == 1):
     back()
    else :
     stop()
    return
#create a message route from joy to python so we can listen for button
joy.addListener("XAxisRaw", python.name, "x")
joy.addListener("YAxisRaw", python.name, "y")

stop()


text:
var fs = require('fs');

var ResponseCache = function() {
	this.cache = {};
    this.cacheKeysByFilePath = {};
};

ResponseCache.prototype.buildCacheKey = function(request) {
    return request.originalFilePaths.slice(0).sort().join(',') + (request.minify ? '|min' : '');
};

ResponseCache.prototype.get = function(request) {
    var cacheKey = this.buildCacheKey(request);
    return this.cache[cacheKey];
};

ResponseCache.prototype.put = function(request, response) {
    var self = this,
        cacheKey = this.buildCacheKey(request);
    this.cache[cacheKey] = response;
    this.watchFiles(request.files, cacheKey);
};

ResponseCache.prototype.watchFiles = function(files, cacheKey) {
    var self = this;
    for (i = 0; i < files.length; i++) {
        if (!this.cacheKeysByFilePath[files[i].resolvedPath]) {
            this.cacheKeysByFilePath[files[i].resolvedPath] = [];
            (function(filePath) {
                fs.watchFile(filePath, function(curr, prev) {
                    self.expireByFilePath(filePath);
                });
            })(files[i].resolvedPath);
        }
        this.cacheKeysByFilePath[files[i].resolvedPath].push(cacheKey);
    }
};

ResponseCache.prototype.expireByFilePath = function(filePath) {
    var cacheKey = this.cacheKeysByFilePath[filePath];
    delete this.cache[cacheKey];
};

module.exports.ResponseCache = ResponseCache;


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>20130916</title>

    <link rel="stylesheet" href="../style/base.css" type="text/css" media="screen" />
    <link rel="stylesheet" href="../style/customized.css" type="text/css" media="print" />

20130916

This document imports 2 css files: base.css & customized.css. base.css is defined as "screen", while customized.css is "print". That will make the page rendered by base.css in browser and by customized.css in printing. They can also be implemented as media property of <link>.

This picture shows local style. It has higher priorty than linked css files.


text:
<html>
<head>
  <meta charset="UTF-8">

  <!-- PLEASE NO CHANGES BELOW THIS LINE (UNTIL I SAY SO) -->
  <script language="javascript" type="text/javascript" src="libraries/p5.js"></script>
  <script language="javascript" type="text/javascript" src="bouncingball.js"></script>
  <!-- OK, YOU CAN MAKE CHANGES BELOW THIS LINE AGAIN -->

  <!-- This line removes any default padding and style.
       You might only need one of these values set. -->
  <style> body {padding: 0; margin: 0;} </style>
</head>

<body>
</body>
</html>


text:
#include <aws/managedblockchain/model/CreateProposalRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::ManagedBlockchain::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

CreateProposalRequest::CreateProposalRequest() :
    m_clientRequestToken(Aws::Utils::UUID::RandomUUID()),
    m_clientRequestTokenHasBeenSet(true),
    m_networkIdHasBeenSet(false),
    m_memberIdHasBeenSet(false),
    m_actionsHasBeenSet(false),
    m_descriptionHasBeenSet(false),
    m_tagsHasBeenSet(false)
{
}

Aws::String CreateProposalRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_clientRequestTokenHasBeenSet)
  {
   payload.WithString("ClientRequestToken", m_clientRequestToken);

  }

  if(m_memberIdHasBeenSet)
  {
   payload.WithString("MemberId", m_memberId);

  }

  if(m_actionsHasBeenSet)
  {
   payload.WithObject("Actions", m_actions.Jsonize());

  }

  if(m_descriptionHasBeenSet)
  {
   payload.WithString("Description", m_description);

  }

  if(m_tagsHasBeenSet)
  {
   JsonValue tagsJsonMap;
   for(auto& tagsItem : m_tags)
   {
     tagsJsonMap.WithString(tagsItem.first, tagsItem.second);
   }
   payload.WithObject("Tags", std::move(tagsJsonMap));

  }

  return payload.View().WriteReadable();
}


text:
using Google.Api;
using Google.Cloud.Diagnostics.Common;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;

namespace Google.Cloud.Diagnostics.AspNetCore
{
    /// <summary>
    /// Extensions to configure Google Diagnostics on the <see cref="IWebHostBuilder"/>.
    /// </summary>
    public static class GoogleDiagnosticsWebHostBuilderExtensions
    {
        /// <summary>
        /// Configures Google Diagostics services for Logging, Tracing and Error Reporting middleware.
        /// </summary>
        /// <param name="builder">The <see cref="IWebHostBuilder"/> instance.</param>
        /// <param name="projectId">
        /// The Google Cloud Platform project ID. If unspecified and running on GAE/GCE/GKE
        /// the project ID will be detected from the platform.
        /// </param>
        /// <param name="serviceName">
        /// An identifier of the service used for exception logging, such as the name of the executable or job.
        /// If unspecified and running on GAE the service name will be detected from the platform.
        /// </param>
        /// <param name="serviceVersion">
        /// A string that represents the version of the service or the source code used for exception logging.
        /// If unspecified and running on GAE the service version will be detected from the platform.
        /// </param>
        /// <returns>The <see cref="IWebHostBuilder"/> instance.</returns>
        public static IWebHostBuilder UseGoogleDiagnostics(this IWebHostBuilder builder, string projectId = null, string serviceName = null, string serviceVersion = null)
            => UseGoogleDiagnostics(builder, projectId, serviceName, serviceVersion, monitoredResource: null);

        // Overload which allows passing in a MonitoredResource instance
        // Internal for testing
        internal static IWebHostBuilder UseGoogleDiagnostics(this IWebHostBuilder builder, string projectId = null, string serviceName = null, string serviceVersion = null, MonitoredResource monitoredResource = null)
        {
            builder.ConfigureServices(services =>
            {
                projectId = Project.GetAndCheckProjectId(projectId, monitoredResource);

                services.AddLogEntryLabelProvider<TraceIdLogEntryLabelProvider>();
                services.AddSingleton<IStartupFilter>(new GoogleDiagnosticsStartupFilter(projectId, monitoredResource));
                services.AddGoogleTrace(options => options.ProjectId = projectId);
                services.AddGoogleExceptionLogging(options =>
                {
                    options.ProjectId = projectId;
                    options.ServiceName = Project.GetAndCheckServiceName(serviceName, monitoredResource);
                    options.Version = Project.GetAndCheckServiceVersion(serviceVersion, monitoredResource);
                });
            });

            return builder;
        }
    }
}


text:
package com.seanox.devwex;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

/**
 * TestSuite for com.seanox.devwex.
 *
 * @author  Seanox Software Solutions
 * @version 5.5.0 20220907
 */
@RunWith(Suite.class)
@Suite.SuiteClasses({
    GeneratorTest.class,
    InitializeTest.class,
    RemoteTest.class,
    SectionTest.class,
    ServerTest.class,
    ServiceTest.class,
    WorkerTest.class
})
public class Test extends AbstractStageTestSuite {
}


text:
<?php
/**
 * namespace para nosso modulo Core\Service
 */

namespace Core\Service;

use Doctrine\ORM\EntityManager;
use Zend\Stdlib\Hydrator\ClassMethods;

/**
 * Class AbstractService
 * @package Core\Service
 * Classe Responsável pela manipulação de dados, como inserir alterar e excluir registros.
 * @author Winston Hanun Junior <ceo@sisdeve.com.br> skype ceo_sisdeve
 * @copyright (c) 2014, Winston Hanun Junior
 * @link http://www.sisdeve.com.br
 * @version V0.1

 */
abstract class AbstractService
{
    /**
     * @var EntityManager
     */
    protected $em;
    /**
     * @var
     */
    protected $entity; // Nome da Entidade

    /**
     * @param EntityManager $em
     */
    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    /**
     * @param array $data
     * @return mixed
     */
    public function save(Array $data = array())
    {
        if (isset($data['id'])){

            $entity = $this->em->getReference($this->entity, $data['id']);

            $hydrator = new ClassMethods();
            $hydrator->hydrate($data, $entity);

        }else{
            $entity = new $this->entity($data);
        }

        $this->em->persist($entity);
        $this->em->flush();

        return $entity;
    }

    /**
     * @param array $data
     * @return mixed
     */
    public function remove(Array $data = array())
    {
        $entity = $this->em->getRepository($this->entity)->findOneBy($data);

        if ($entity){
            $this->em->remove($entity);
            $this->em->flush();

            return $entity;
        }
    }
}


text:
@extends($master)

@section('page')
    {{ trans('panichd::admin.index-title') }}
@stop

@include('panichd::shared.common')

@section('content')

{!! trans('panichd::install.pending-settings') !!}

{!! trans('panichd::install.pending-settings-description') !!}

@stop


text:
//using System;
//using LionFire.Vos;
//using LionFire.Vos.Packages;

//namespace LionFire.Vos.Stores
//{
//    public class VosStoresOptions
//    {
//        #region Construction

//        public VosStoresOptions() { }
//        public VosStoresOptions(VobReference storesLocation, PackageManagerOptions packageManagerOptions = null)
//        {
//            StoresLocation = storesLocation;
//            PackageManagerOptions = packageManagerOptions;
//        }

//        public static implicit operator VosStoresOptions(string vosPath) => new VosStoresOptions(vosPath.ToVobReference());
//        public static implicit operator VosStoresOptions(VobReference vobReference) => new VosStoresOptions(vobReference);

//        #endregion

//        public VobReference StoresLocation { get; set; }

//        public PackageManagerOptions PackageManagerOptions { get; set; }
//        public PackageManagerOptions EffectivePackageManagerOptions => PackageManagerOptions ?? PackageManagerOptions.Default;

//        public IVobReference AvailableLocation => StoresLocation?.GetRelativeOrAbsolutePath(EffectivePackageManagerOptions?.AvailableSubPath);
//    }
//}


text:
using JetBrains.Application.Environment;

namespace Resharper.Paket.CSharp
{
    [ZoneActivator]
    class PaketZoneActivator : IActivate<IPaketZone>
    {
        public bool ActivatorEnabled()
        {
            return true;
        }
    }
}


text:
/*
 * 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.
 */
package org.trellisldp.rosid.app.config;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

import io.dropwizard.configuration.YamlConfigurationFactory;
import io.dropwizard.jackson.Jackson;
import io.dropwizard.jersey.validation.Validators;

import java.io.File;
import java.util.Properties;

import org.junit.jupiter.api.Test;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;

/**
 * @author acoburn
 */
@RunWith(JUnitPlatform.class)
public class TrellisConfigurationTest {

    @Test
    public void testConfigurationGeneral1() throws Exception {
        final TrellisConfiguration config = new YamlConfigurationFactory<>(TrellisConfiguration.class,
                Validators.newValidator(), Jackson.newObjectMapper(), "")
            .build(new File(getClass().getResource("/config1.yml").toURI()));

        assertTrue(config.getAsync());
        assertEquals("Trellis", config.getDefaultName());
        assertEquals((Integer) 86400, config.getCacheMaxAge());
        assertEquals((Long) 100L, config.getJsonLdCacheSize());
        assertEquals((Long) 24L, config.getJsonLdCacheExpireHours());
        assertTrue(config.getJsonLdDomainWhitelist().isEmpty());
        assertTrue(config.getJsonLdWhitelist().contains("http://example.org/context.json"));
    }

    @Test
    public void testConfigurationAssets1() throws Exception {
        final TrellisConfiguration config = new YamlConfigurationFactory<>(TrellisConfiguration.class,
                Validators.newValidator(), Jackson.newObjectMapper(), "")
            .build(new File(getClass().getResource("/config1.yml").toURI()));

        assertEquals("http://example.org/image.icon", config.getAssets().getIcon());
        assertTrue(config.getAssets().getJs().contains("http://example.org/scripts1.js"));
        assertTrue(config.getAssets().getCss().contains("http://example.org/styles1.css"));
    }

    @Test
    public void testConfigurationLocations() throws Exception {
        final TrellisConfiguration config = new YamlConfigurationFactory<>(TrellisConfiguration.class,
                Validators.newValidator(), Jackson.newObjectMapper(), "")
            .build(new File(getClass().getResource("/config1.yml").toURI()));

        assertEquals("/tmp/trellisData/binaries", config.getBinaries().getPath());
        assertEquals("/tmp/trellisData/resources", config.getResources().getPath());
        assertEquals("http://localhost:8080/", config.getBaseUrl());
        assertEquals((Integer) 4, config.getBinaries().getLevels());
        assertEquals((Integer) 2, config.getBinaries().getLength());
    }

    @Test
    public void testConfigurationAuth1() throws Exception {
        final TrellisConfiguration config = new YamlConfigurationFactory<>(TrellisConfiguration.class,
                Validators.newValidator(), Jackson.newObjectMapper(), "")
            .build(new File(getClass().getResource("/config1.yml").toURI()));

        assertTrue(config.getAuth().getWebac().getEnabled());
        assertEquals((Long) 100L, config.getAuth().getWebac().getCacheSize());
        assertEquals((Long) 10L, config.getAuth().getWebac().getCacheExpireSeconds());
        assertTrue(config.getAuth().getAnon().getEnabled());
        assertTrue(config.getAuth().getBasic().getEnabled());
        assertEquals("users.auth", config.getAuth().getBasic().getUsersFile());
        assertTrue(config.getAuth().getJwt().getEnabled());
        assertEquals("secret", config.getAuth().getJwt().getKey());
        assertFalse(config.getAuth().getJwt().getBase64Encoded());
    }

    @Test
    public void testConfigurationNamespaces1() throws Exception {
        final TrellisConfiguration config = new YamlConfigurationFactory<>(TrellisConfiguration.class,
                Validators.newValidator(), Jackson.newObjectMapper(), "")
            .build(new File(getClass().getResource("/config1.yml").toURI()));

        assertEquals("/tmp/trellisData/namespaces.json", config.getNamespaces().getFile());
    }

    @Test
    public void testConfigurationCORS1() throws Exception {
        final TrellisConfiguration config = new YamlConfigurationFactory<>(TrellisConfiguration.class,
                Validators.newValidator(), Jackson.newObjectMapper(), "")
            .build(new File(getClass().getResource("/config1.yml").toURI()));

        assertTrue(config.getCors().getEnabled());
        assertTrue(config.getCors().getAllowOrigin().contains("*"));
        assertTrue(config.getCors().getAllowHeaders().contains("Link"));
        assertTrue(config.getCors().getAllowMethods().contains("PATCH"));
        assertTrue(config.getCors().getExposeHeaders().contains("Location"));
        assertEquals((Integer) 180, config.getCors().getMaxAge());
        assertTrue(config.getCors().getAllowCredentials());
    }

    @Test
    public void testConfigurationZookeeper1() throws Exception {
        final TrellisConfiguration config = new YamlConfigurationFactory<>(TrellisConfiguration.class,
                Validators.newValidator(), Jackson.newObjectMapper(), "")
            .build(new File(getClass().getResource("/config1.yml").toURI()));

        assertEquals("localhost:2181", config.getZookeeper().getEnsembleServers());
        assertEquals((Integer) 100, config.getZookeeper().getTimeout());
        assertEquals((Integer) 1000, config.getZookeeper().getRetryMs());
        assertEquals((Integer) 10, config.getZookeeper().getRetryMax());
        assertEquals((Integer) 50, config.getZookeeper().getRetryMaxMs());
    }

    @Test
    public void testConfigurationKafka1() throws Exception {
        final TrellisConfiguration config = new YamlConfigurationFactory<>(TrellisConfiguration.class,
                Validators.newValidator(), Jackson.newObjectMapper(), "")
            .build(new File(getClass().getResource("/config1.yml").toURI()));

        assertEquals("localhost:9092", config.getKafka().getBootstrapServers());

        final Properties props = config.getKafka().asProperties();
        assertEquals("all", props.getProperty("acks"));
        assertEquals("16384", props.getProperty("batch.size"));
        assertEquals("otherValue", props.getProperty("otherProperty"));
    }
}


text:
package brainslug.flow.execution.property;

import brainslug.flow.execution.instance.FlowInstanceProperty;
import brainslug.flow.execution.instance.FlowInstanceProperties;
import brainslug.flow.definition.Identifier;
import brainslug.flow.expression.Property;

import java.util.*;

public class ExecutionProperties implements FlowInstanceProperties<ExecutionProperties, FlowInstanceProperty<?>> {
  Map<String, FlowInstanceProperty<?>> properties;

  public ExecutionProperties() {
    this.properties = new HashMap<String, FlowInstanceProperty<?>>();
  }

  public <T extends FlowInstanceProperty> ExecutionProperties from(Collection<T> properties) {
    for (FlowInstanceProperty property : properties) {
      this.properties.put(property.getKey(), property);
    }
    return this;
  }

  @Override
  public ExecutionProperties with(Identifier key, Object value) {
    return with(key.stringValue(), value);
  }

  @Override
  public ExecutionProperties with(Identifier key, Object value, boolean isTransient) {
    return with(key.stringValue(), value, isTransient);
  }

  @Override
  public ExecutionProperties with(Property<?> key, Object value) {
    return with(key.getValue(), value);
  }

  @Override
  public ExecutionProperties with(Property<?> key, Object value, boolean isTransient) {
    return with(key.getValue(), value, isTransient);
  }

  @Override
  public ExecutionProperties with(String key, Object value) {
    properties.put(key, createPropertyFromValue(key, value, false));
    return this;
  }

  @Override
  public ExecutionProperties with(String key, Object value, boolean isTransient) {
    properties.put(key, createPropertyFromValue(key, value, isTransient));
    return this;
  }

  FlowInstanceProperty<?> createPropertyFromValue(String key, Object value, boolean isTransient) {
    return newPropertyByType(key, value).setTransient(isTransient);
  }

  private AbstractProperty<?> newPropertyByType(String key, Object value) {
    if (value instanceof Long) {
      return new LongProperty(key, (Long) value);
    } else if (value instanceof Integer) {
      return new IntProperty(key, (Integer) value);
    } else if (value instanceof Double) {
      return new DoubleProperty(key, (Double) value);
    } else if (value instanceof Float) {
      return new FloatProperty(key, (Float) value);
    } else if (value instanceof Boolean) {
      return new BooleanProperty(key, (Boolean) value);
    } else if (value instanceof String) {
      return new StringProperty(key, (String) value);
    } else if (value instanceof Date) {
      return new DateProperty(key, (Date) value);
    } else {
      return new ObjectProperty(key, value);
    }
  }

  @Override
  public ExecutionProperties withAll(ExecutionProperties executionProperties) {
    for (FlowInstanceProperty executionProperty : executionProperties.values()) {
      this.properties.put(executionProperty.getKey(), executionProperty);
    }
    return this;
  }

  @Override
  public <T> T value(String key, Class<T> clazz) {
    FlowInstanceProperty<?> property = properties.get(key);

    if (property == null) {
      throw new IllegalArgumentException("property '" + key + "' does not exist in execution properties");
    }

    return (T) properties.get(key).getValue();
  }

  @Override
  public <T> T value(Identifier id, Class<T> clazz) {
    return value(id.stringValue(), clazz);
  }

  @Override
  public <T> T value(Property<T> property) {
    return value(property.getValue(), property.getValueClass());
  }

  @Override
  public <T> FlowInstanceProperty<T> get(String key, Class<T> clazz) {
    return (FlowInstanceProperty<T>) properties.get(key);
  }

  @Override
  public <T> FlowInstanceProperty<T> get(Identifier id, Class<T> clazz) {
    return get(id.stringValue(), clazz);
  }

  @Override
  public <T> FlowInstanceProperty<T> get(Property<?> property, Class<T> clazz) {
    return get(property.getValue(), clazz);
  }

  @Override
  public FlowInstanceProperty<?> get(String key) {
    return properties.get(key);
  }

  @Override
  public FlowInstanceProperty<?> get(Identifier id) {
    return get(id.stringValue());
  }

  @Override
  public FlowInstanceProperty<?> get(Property<?> property) {
    return get(property.getValue());
  }

  @Override
  public Collection<FlowInstanceProperty<?>> values() {
    return properties.values();
  }

  public static ExecutionProperties newProperties() {
    return new ExecutionProperties();
  }

  @Override
  public String toString() {
    return "ExecutionProperties{" +
      "properties=" + properties +
      '}';
  }
}


text:
namespace Google.Cloud.Dataplex.V1.Snippets
{
    // [START dataplex_v1_generated_DataplexService_CreateLake_async]
    using Google.Api.Gax.ResourceNames;
    using Google.LongRunning;
    using System.Threading.Tasks;
    using gcdv = Google.Cloud.Dataplex.V1;

    public sealed partial class GeneratedDataplexServiceClientSnippets
    {
        /// <summary>Snippet for CreateLakeAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public async Task CreateLakeRequestObjectAsync()
        {
            // Create client
            DataplexServiceClient dataplexServiceClient = await DataplexServiceClient.CreateAsync();
            // Initialize request argument(s)
            CreateLakeRequest request = new CreateLakeRequest
            {
                ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
                LakeId = "",
                Lake = new Lake(),
                ValidateOnly = false,
            };
            // Make the request
            Operation<Lake, OperationMetadata> response = await dataplexServiceClient.CreateLakeAsync(request);

            // Poll until the returned long-running operation is complete
            Operation<Lake, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
            // Retrieve the operation result
            Lake result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            Operation<Lake, OperationMetadata> retrievedResponse = await dataplexServiceClient.PollOnceCreateLakeAsync(operationName);
            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                Lake retrievedResult = retrievedResponse.Result;
            }
        }
    }
    // [END dataplex_v1_generated_DataplexService_CreateLake_async]
}


text:
@interface TouchHandlingScene2 : SKScene

@end


text:
package org.unidal.cat.message.storage.hdfs;

import io.netty.buffer.ByteBuf;

import java.io.File;
import java.io.IOException;

import org.junit.Before;
import org.junit.Test;
import org.unidal.cat.message.storage.Bucket;
import org.unidal.lookup.ComponentTestCase;

import com.dianping.cat.config.server.ServerConfigManager;
import com.dianping.cat.message.internal.MessageId;
import com.dianping.cat.message.spi.MessageCodec;
import com.dianping.cat.message.spi.MessageTree;
import com.dianping.cat.message.spi.codec.PlainTextMessageCodec;
import com.dianping.cat.message.spi.internal.DefaultMessageTree;

public class HdfsBucketTest extends ComponentTestCase {

   @Before
   public void before() throws Exception {
      ServerConfigManager config = lookup(ServerConfigManager.class);

      config.initialize(new File(HdfsBucketTest.class.getClassLoader().getResource("server.xml").getFile()));
   }

   @Test
   public void testManager() {
      HdfsBucketManager manager = lookup(HdfsBucketManager.class);

      for (int i = 0; i < 1000; i++) {
         MessageId id = MessageId.parse("cat-0a420d73-405915-" + i);

         MessageTree message = manager.loadMessage(id);

         if (message != null) {
            System.err.println(message);
         }
      }
   }

   @Test
   public void test() {
      Bucket hdfsbucket = lookup(Bucket.class, "hdfs");
      MessageCodec m_plainText = lookup(MessageCodec.class, PlainTextMessageCodec.ID);

      try {
         MessageId id = MessageId.parse("shop-web-0a420d56-405915-16");
         hdfsbucket.initialize(id.getDomain(), "10.66.13.115", id.getHour());

         ByteBuf byteBuf = hdfsbucket.get(id);

         if (byteBuf != null) {
            MessageTree tree = new DefaultMessageTree();

            m_plainText.decode(byteBuf, tree);
            System.out.println(tree.toString());
         }
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}