text:
namespace Microsoft.Azure.Devices.Common
{
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Diagnostics;
    using System.Diagnostics.CodeAnalysis;
    using System.Globalization;
    using System.Reflection;
    using System.Runtime.CompilerServices;
    using System.Runtime.ConstrainedExecution;
    using System.Runtime.InteropServices;
    using System.Security;
    using System.Threading;
    using System.Transactions;
    using Microsoft.Win32;

    static class Fx
    {
        // This is only used for EventLog Source therefore matching EventLog source rather than ETL source
        const string DefaultEventSource = "Microsoft.IotHub";

#if DEBUG
        const string SBRegistryKey = @"SOFTWARE\Microsoft\IotHub\v2.0";
        const string AssertsFailFastName = "AssertsFailFast";
        const string BreakOnExceptionTypesName = "BreakOnExceptionTypes";
        const string FastDebugName = "FastDebug";

        static bool breakOnExceptionTypesRetrieved;
        static Type[] breakOnExceptionTypesCache;
        static bool fastDebugRetrieved;
        static bool fastDebugCache;
#endif

#if UNUSED
        [Fx.Tag.SecurityNote(Critical = "This delegate is called from within a ConstrainedExecutionRegion, must not be settable from PT code")]
        [SecurityCritical]
        static ExceptionHandler asynchronousThreadExceptionHandler;
#endif // UNUSED

        static ExceptionTrace exceptionTrace;

        ////static DiagnosticTrace diagnosticTrace;

        ////[Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical field EtwProvider",
        ////    Safe = "Doesn't leak info\\resources")]
        ////[SuppressMessage(FxCop.Category.ReliabilityBasic, FxCop.Rule.UseNewGuidHelperRule,
        ////    Justification = "This is a method that creates ETW provider passing Guid Provider ID.")]
        ////static DiagnosticTrace InitializeTracing()
        ////{
        ////    DiagnosticTrace trace = new DiagnosticTrace(DefaultEventSource, DiagnosticTrace.DefaultEtwProviderId);
        ////    return trace;
        ////}

#if UNUSED
        public static ExceptionHandler AsynchronousThreadExceptionHandler
        {
            [Fx.Tag.SecurityNote(Critical = "access critical field", Safe = "ok for get-only access")]
            [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
            get
            {
                return Fx.asynchronousThreadExceptionHandler;
            }

            [Fx.Tag.SecurityNote(Critical = "sets a critical field")]
            [SecurityCritical]
            set
            {
                Fx.asynchronousThreadExceptionHandler = value;
            }
        }
#endif // UNUSED

        public static ExceptionTrace Exception
        {
            get
            {
                if (exceptionTrace == null)
                {
                    //need not be a true singleton. No locking needed here.
                    exceptionTrace = new ExceptionTrace(DefaultEventSource);
                }

                return exceptionTrace;
            }
        }

        ////public static DiagnosticTrace Trace
        ////{
        ////    get
        ////    {
        ////        if (diagnosticTrace == null)
        ////        {
        ////            diagnosticTrace = InitializeTracing();
        ////        }

        ////        return diagnosticTrace;
        ////    }
        ////}

        public static byte[] AllocateByteArray(int size)
        {
            try
            {
                // Safe to catch OOM from this as long as the ONLY thing it does is a simple allocation of a primitive type (no method calls).
                return new byte[size];
            }
            catch (OutOfMemoryException exception)
            {
                // Convert OOM into an exception that can be safely handled by higher layers.
                throw Fx.Exception.AsError(new InsufficientMemoryException(CommonResources.GetString(CommonResources.BufferAllocationFailed, size), exception));
            }
        }

        // Do not call the parameter "message" or else FxCop thinks it should be localized.
        [Conditional("DEBUG")]
        public static void Assert(bool condition, string description)
        {
            if (!condition)
            {
                Assert(description);
            }
        }

        [Conditional("DEBUG")]
        public static void Assert(string description)
        {
            Debug.Assert(false, description);
        }

        public static void AssertAndThrow(bool condition, string description)
        {
            if (!condition)
            {
                AssertAndThrow(description);
            }
        }

        public static void AssertIsNotNull(object objectMayBeNull, string description)
        {
            if (objectMayBeNull == null)
            {
                Fx.AssertAndThrow(description);
            }
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        public static Exception AssertAndThrow(string description)
        {
            Fx.Assert(description);
            throw Fx.Exception.AsError(new AssertionFailedException(description));
        }

        public static void AssertAndThrowFatal(bool condition, string description)
        {
            if (!condition)
            {
                AssertAndThrowFatal(description);
            }
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        public static Exception AssertAndThrowFatal(string description)
        {
            Fx.Assert(description);
            throw Fx.Exception.AsError(new FatalException(description));
        }

        public static void AssertAndFailFastService(bool condition, string description)
        {
            if (!condition)
            {
                AssertAndFailFastService(description);
            }
        }

        // This never returns.  The Exception return type lets you write 'throw AssertAndFailFast()' which tells the compiler/tools that
        // execution stops.
        [Fx.Tag.SecurityNote(Critical = "Calls into critical method Environment.FailFast",
            Safe = "The side affect of the app crashing is actually intended here")]
        [MethodImpl(MethodImplOptions.NoInlining)]
        public static Exception AssertAndFailFastService(string description)
        {
            Fx.Assert(description);
            string failFastMessage = CommonResources.GetString(CommonResources.FailFastMessage, description);

            // The catch is here to force the finally to run, as finallys don't run until the stack walk gets to a catch.
            // The catch makes sure that the finally will run before the stack-walk leaves the frame, but the code inside is impossible to reach.
            try
            {
                try
                {
                    ////MessagingClientEtwProvider.Provider.EventWriteFailFastOccurred(description);
                    Fx.Exception.TraceFailFast(failFastMessage);

                    // Mark that a FailFast is in progress, so that we can take ourselves out of the NLB if for
                    // any reason we can't kill ourselves quickly.  Wait 15 seconds so this state gets picked up for sure.
                    Fx.FailFastInProgress = true;
                    Thread.Sleep(TimeSpan.FromSeconds(15));
                }
                finally
                {
                    // ########################## NOTE ###########################
                    // Environment.FailFast does not collect crash dumps when used in Azure services.
                    // Environment.FailFast(failFastMessage);

                    // ################## WORKAROUND #############################
                    // Workaround for the issue above. Throwing an unhandled exception on a separate thread to trigger process crash and crash dump collection
                    // Throwing FatalException since our service does not morph/eat up fatal exceptions
                    // We should find the tracking bug in Azure for this issue, and remove the workaround when fixed by Azure
                    Thread failFastWorkaroundThread = new Thread(delegate()
                    {
                        throw new FatalException(failFastMessage);
                    });

                    failFastWorkaroundThread.Start();
                    failFastWorkaroundThread.Join();
                }
            }
            catch
            {
                throw;
            }

            return null; // we'll never get here since we've just fail-fasted
        }

        internal static bool FailFastInProgress { get; private set; }

        public static bool IsFatal(Exception exception)
        {
            while (exception != null)
            {
                // FYI, CallbackException is-a FatalException
                if (exception is FatalException ||
                    (exception is OutOfMemoryException && !(exception is InsufficientMemoryException)) ||
                    exception is ThreadAbortException ||
                    exception is AccessViolationException ||
                    exception is SEHException)
                {
                    return true;
                }

                // These exceptions aren't themselves fatal, but since the CLR uses them to wrap other exceptions,
                // we want to check to see whether they've been used to wrap a fatal exception.  If so, then they
                // count as fatal.
                if (exception is TypeInitializationException ||
                    exception is TargetInvocationException)
                {
                    exception = exception.InnerException;
                }
                else if (exception is AggregateException)
                {
                    // AggregateExceptions have a collection of inner exceptions, which may themselves be other
                    // wrapping exceptions (including nested AggregateExceptions).  Recursively walk this
                    // hierarchy.  The (singular) InnerException is included in the collection.
                    ReadOnlyCollection<Exception> innerExceptions = ((AggregateException)exception).InnerExceptions;
                    foreach (Exception innerException in innerExceptions)
                    {
                        if (IsFatal(innerException))
                        {
                            return true;
                        }
                    }

                    break;
                }
                else if (exception is NullReferenceException)
                {
                    ////MessagingClientEtwProvider.Provider.EventWriteNullReferenceErrorOccurred(exception.ToString());
                    break;
                }
                else
                {
                    break;
                }
            }

            return false;
        }

        // If the transaction has aborted then we switch over to a new transaction
        // which we will immediately abort after setting Transaction.Current
        public static TransactionScope CreateTransactionScope(Transaction transaction)
        {
            try
            {
                return transaction == null ? null : new TransactionScope(transaction);
            }
            catch (TransactionAbortedException)
            {
                CommittableTransaction tempTransaction = new CommittableTransaction();
                try
                {
                    return new TransactionScope(tempTransaction.Clone());
                }
                finally
                {
                    tempTransaction.Rollback();
                }
            }
        }

        public static void CompleteTransactionScope(ref TransactionScope scope)
        {
            TransactionScope localScope = scope;
            if (localScope != null)
            {
                scope = null;
                try
                {
                    localScope.Complete();
                }
                finally
                {
                    localScope.Dispose();
                }
            }
        }

#if UNUSED
        public static AsyncCallback ThunkCallback(AsyncCallback callback)
        {
            return (new AsyncThunk(callback)).ThunkFrame;
        }

        public static WaitCallback ThunkCallback(WaitCallback callback)
        {
            return (new WaitThunk(callback)).ThunkFrame;
        }

        public static TimerCallback ThunkCallback(TimerCallback callback)
        {
            return (new TimerThunk(callback)).ThunkFrame;
        }

        public static WaitOrTimerCallback ThunkCallback(WaitOrTimerCallback callback)
        {
            return (new WaitOrTimerThunk(callback)).ThunkFrame;
        }

        public static SendOrPostCallback ThunkCallback(SendOrPostCallback callback)
        {
            return (new SendOrPostThunk(callback)).ThunkFrame;
        }
#endif

        [Fx.Tag.SecurityNote(Critical = "Construct the unsafe object IOCompletionThunk")]
        [SecurityCritical]
        public static IOCompletionCallback ThunkCallback(IOCompletionCallback callback)
        {
            return (new IOCompletionThunk(callback)).ThunkFrame;
        }

        public static TransactionCompletedEventHandler ThunkTransactionEventHandler(TransactionCompletedEventHandler handler)
        {
            return (new TransactionEventHandlerThunk(handler)).ThunkFrame;
        }

#if DEBUG
        internal static bool AssertsFailFast
        {
            get
            {
                object value;
                return TryGetDebugSwitch(Fx.AssertsFailFastName, out value) &&
                    typeof(int).IsAssignableFrom(value.GetType()) && ((int)value) != 0;
            }
        }

        internal static Type[] BreakOnExceptionTypes
        {
            get
            {
                if (!Fx.breakOnExceptionTypesRetrieved)
                {
                    object value;
                    if (TryGetDebugSwitch(Fx.BreakOnExceptionTypesName, out value))
                    {
                        string[] typeNames = value as string[];
                        if (typeNames != null && typeNames.Length > 0)
                        {
                            List<Type> types = new List<Type>(typeNames.Length);
                            for (int i = 0; i < typeNames.Length; i++)
                            {
                                types.Add(Type.GetType(typeNames[i], false));
                            }
                            if (types.Count != 0)
                            {
                                Fx.breakOnExceptionTypesCache = types.ToArray();
                            }
                        }
                    }
                    Fx.breakOnExceptionTypesRetrieved = true;
                }
                return Fx.breakOnExceptionTypesCache;
            }
        }

        internal static bool FastDebug
        {
            get
            {
                if (!Fx.fastDebugRetrieved)
                {
                    object value;
                    if (TryGetDebugSwitch(Fx.FastDebugName, out value))
                    {
                        Fx.fastDebugCache = typeof(int).IsAssignableFrom(value.GetType()) && ((int)value) != 0;
                    }

                    Fx.fastDebugRetrieved = true;
                    ////MessagingClientEtwProvider.Provider.EventWriteLogAsWarning(string.Format(CultureInfo.InvariantCulture, "AppDomain({0}).Fx.FastDebug={1}", AppDomain.CurrentDomain.FriendlyName, Fx.fastDebugCache.ToString()));
                }

                return Fx.fastDebugCache;
            }
        }

        static bool TryGetDebugSwitch(string name, out object value)
        {
            value = null;
            try
            {
                RegistryKey key = Registry.LocalMachine.OpenSubKey(Fx.SBRegistryKey);
                if (key != null)
                {
                    using (key)
                    {
                        value = key.GetValue(name);
                    }
                }
            }
            catch (SecurityException)
            {
                // This debug-only code shouldn't trace.
            }
            return value != null;
        }
#endif

        [SuppressMessage(FxCop.Category.Design, FxCop.Rule.DoNotCatchGeneralExceptionTypes,
            Justification = "Don't want to hide the exception which is about to crash the process.")]
        [Fx.Tag.SecurityNote(Miscellaneous = "Must not call into PT code as it is called within a CER.")]
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
        static void TraceExceptionNoThrow(Exception exception)
        {
            try
            {
                // This call exits the CER.  However, when still inside a catch, normal ThreadAbort is prevented.
                // Rude ThreadAbort will still be allowed to terminate processing.
                Fx.Exception.TraceUnhandled(exception);
            }
            catch
            {
                // This empty catch is only acceptable because we are a) in a CER and b) processing an exception
                // which is about to crash the process anyway.
            }
        }

        [SuppressMessage(FxCop.Category.Design, FxCop.Rule.DoNotCatchGeneralExceptionTypes,
            Justification = "Don't want to hide the exception which is about to crash the process.")]
        [SuppressMessage(FxCop.Category.ReliabilityBasic, FxCop.Rule.IsFatalRule,
            Justification = "Don't want to hide the exception which is about to crash the process.")]
        [Fx.Tag.SecurityNote(Miscellaneous = "Must not call into PT code as it is called within a CER.")]
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
        static bool HandleAtThreadBase(Exception exception)
        {
            // This area is too sensitive to do anything but return.
            if (exception == null)
            {
                Fx.Assert("Null exception in HandleAtThreadBase.");
                return false;
            }

            TraceExceptionNoThrow(exception);

#if UNUSED
            try
            {
                ExceptionHandler handler = Fx.AsynchronousThreadExceptionHandler;
                return handler == null ? false : handler.HandleException(exception);
            }
            catch (Exception secondException)
            {
                // Don't let a new exception hide the original exception.
                TraceExceptionNoThrow(secondException);
            }
#endif // UNUSED

            return false;
        }

#if UNUSED
        abstract class Thunk<T> where T : class
        {
            [Fx.Tag.SecurityNote(Critical = "Make these safe to use in SecurityCritical contexts.")]
            [SecurityCritical]
            T callback;

            [Fx.Tag.SecurityNote(Critical = "Accesses critical field.", Safe = "Data provided by caller.")]
            protected Thunk(T callback)
            {
                this.callback = callback;
            }

            internal T Callback
            {
                [Fx.Tag.SecurityNote(Critical = "Accesses critical field.", Safe = "Data is not privileged.")]
                get
                {
                    return this.callback;
                }
            }
        }

        sealed class TimerThunk : Thunk<TimerCallback>
        {
            public TimerThunk(TimerCallback callback)
                : base(callback)
            {
            }

            public TimerCallback ThunkFrame
            {
                get
                {
                    return new TimerCallback(UnhandledExceptionFrame);
                }
            }

            [Fx.Tag.SecurityNote(Critical = "Calls PrepareConstrainedRegions which has a LinkDemand",
                Safe = "Guaranteed not to call into PT user code from the finally.")]
            void UnhandledExceptionFrame(object state)
            {
                RuntimeHelpers.PrepareConstrainedRegions();
                try
                {
                    Callback(state);
                }
                catch (Exception exception)
                {
                    if (!Fx.HandleAtThreadBase(exception))
                    {
                        throw;
                    }
                }
            }
        }

        sealed class WaitOrTimerThunk : Thunk<WaitOrTimerCallback>
        {
            public WaitOrTimerThunk(WaitOrTimerCallback callback)
                : base(callback)
            {
            }

            public WaitOrTimerCallback ThunkFrame
            {
                get
                {
                    return new WaitOrTimerCallback(UnhandledExceptionFrame);
                }
            }

            [Fx.Tag.SecurityNote(Critical = "Calls PrepareConstrainedRegions which has a LinkDemand",
                Safe = "Guaranteed not to call into PT user code from the finally.")]
            void UnhandledExceptionFrame(object state, bool timedOut)
            {
                RuntimeHelpers.PrepareConstrainedRegions();
                try
                {
                    Callback(state, timedOut);
                }
                catch (Exception exception)
                {
                    if (!Fx.HandleAtThreadBase(exception))
                    {
                        throw;
                    }
                }
            }
        }

        sealed class WaitThunk : Thunk<WaitCallback>
        {
            public WaitThunk(WaitCallback callback)
                : base(callback)
            {
            }

            public WaitCallback ThunkFrame
            {
                get
                {
                    return new WaitCallback(UnhandledExceptionFrame);
                }
            }

            [Fx.Tag.SecurityNote(Critical = "Calls PrepareConstrainedRegions which has a LinkDemand",
                Safe = "Guaranteed not to call into PT user code from the finally.")]
            void UnhandledExceptionFrame(object state)
            {
                RuntimeHelpers.PrepareConstrainedRegions();
                try
                {
                    Callback(state);
                }
                catch (Exception exception)
                {
                    if (!Fx.HandleAtThreadBase(exception))
                    {
                        throw;
                    }
                }
            }
        }

        sealed class AsyncThunk : Thunk<AsyncCallback>
        {
            public AsyncThunk(AsyncCallback callback)
                : base(callback)
            {
            }

            public AsyncCallback ThunkFrame
            {
                get
                {
                    return new AsyncCallback(UnhandledExceptionFrame);
                }
            }

            [Fx.Tag.SecurityNote(Critical = "Calls PrepareConstrainedRegions which has a LinkDemand",
                Safe = "Guaranteed not to call into PT user code from the finally.")]
            void UnhandledExceptionFrame(IAsyncResult result)
            {
                RuntimeHelpers.PrepareConstrainedRegions();
                try
                {
                    Callback(result);
                }
                catch (Exception exception)
                {
                    if (!Fx.HandleAtThreadBase(exception))
                    {
                        throw;
                    }
                }
            }
        }

        public abstract class ExceptionHandler
        {
            [Fx.Tag.SecurityNote(Miscellaneous = "Must not call into PT code as it is called within a CER.")]
            public abstract bool HandleException(Exception exception);
        }
#endif // UNUSED

        // This can't derive from Thunk since T would be unsafe.
        [Fx.Tag.SecurityNote(Critical = "unsafe object")]
        [SecurityCritical]
        unsafe sealed class IOCompletionThunk
        {
            [Fx.Tag.SecurityNote(Critical = "Make these safe to use in SecurityCritical contexts.")]
            IOCompletionCallback callback;

            [Fx.Tag.SecurityNote(Critical = "Accesses critical field.", Safe = "Data provided by caller.")]
            public IOCompletionThunk(IOCompletionCallback callback)
            {
                this.callback = callback;
            }

            public IOCompletionCallback ThunkFrame
            {
                [Fx.Tag.SecurityNote(Safe = "returns a delegate around the safe method UnhandledExceptionFrame")]
                get
                {
                    return new IOCompletionCallback(UnhandledExceptionFrame);
                }
            }

            [Fx.Tag.SecurityNote(Critical = "Accesses critical field, calls PrepareConstrainedRegions which has a LinkDemand",
                Safe = "Delegates can be invoked, guaranteed not to call into PT user code from the finally.")]
            void UnhandledExceptionFrame(uint error, uint bytesRead, NativeOverlapped* nativeOverlapped)
            {
                RuntimeHelpers.PrepareConstrainedRegions();
                try
                {
                    this.callback(error, bytesRead, nativeOverlapped);
                }
                catch (Exception exception)
                {
                    if (!Fx.HandleAtThreadBase(exception))
                    {
                        throw;
                    }
                }
            }
        }

#if UNUSED
        sealed class SendOrPostThunk : Thunk<SendOrPostCallback>
        {
            public SendOrPostThunk(SendOrPostCallback callback)
                : base(callback)
            {
            }

            public SendOrPostCallback ThunkFrame
            {
                get
                {
                    return new SendOrPostCallback(UnhandledExceptionFrame);
                }
            }

            [Fx.Tag.SecurityNote(Critical = "Calls PrepareConstrainedRegions which has a LinkDemand",
                Safe = "Guaranteed not to call into PT user code from the finally.")]
            void UnhandledExceptionFrame(object state)
            {
                RuntimeHelpers.PrepareConstrainedRegions();
                try
                {
                    Callback(state);
                }
                catch (Exception exception)
                {
                    if (!Fx.HandleAtThreadBase(exception))
                    {
                        throw;
                    }
                }
            }
        }
#endif // UNUSED

        sealed class TransactionEventHandlerThunk
        {
            readonly TransactionCompletedEventHandler callback;

            public TransactionEventHandlerThunk(TransactionCompletedEventHandler callback)
            {
                this.callback = callback;
            }

            public TransactionCompletedEventHandler ThunkFrame
            {
                get
                {
                    return new TransactionCompletedEventHandler(UnhandledExceptionFrame);
                }
            }

            void UnhandledExceptionFrame(object sender, TransactionEventArgs args)
            {
                RuntimeHelpers.PrepareConstrainedRegions();
                try
                {
                    this.callback(sender, args);
                }
                catch (Exception exception)
                {
                    throw AssertAndFailFastService(exception.ToString());
                }
            }
        }

        public static class Tag
        {
            public enum CacheAttrition
            {
                None,
                ElementOnTimer,

                // A finalizer/WeakReference based cache, where the elements are held by WeakReferences (or hold an
                // inner object by a WeakReference), and the weakly-referenced object has a finalizer which cleans the
                // item from the cache.
                ElementOnGC,

                // A cache that provides a per-element token, delegate, interface, or other piece of context that can
                // be used to remove the element (such as IDisposable).
                ElementOnCallback,

                FullPurgeOnTimer,
                FullPurgeOnEachAccess,
                PartialPurgeOnTimer,
                PartialPurgeOnEachAccess,
            }

            public enum Location
            {
                InProcess,
                OutOfProcess,
                LocalSystem,
                LocalOrRemoteSystem, // as in a file that might live on a share
                RemoteSystem,
            }

            public enum SynchronizationKind
            {
                LockStatement,
                MonitorWait,
                MonitorExplicit,
                InterlockedNoSpin,
                InterlockedWithSpin,

                // Same as LockStatement if the field type is object.
                FromFieldType,
            }

            [Flags]
            public enum BlocksUsing
            {
                MonitorEnter,
                MonitorWait,
                ManualResetEvent,
                AutoResetEvent,
                AsyncResult,
                IAsyncResult,
                PInvoke,
                InputQueue,
                ThreadNeutralSemaphore,
                PrivatePrimitive,
                OtherInternalPrimitive,
                OtherFrameworkPrimitive,
                OtherInterop,
                Other,

                NonBlocking, // For use by non-blocking SynchronizationPrimitives such as IOThreadScheduler
            }

            public static class Strings
            {
                internal const string ExternallyManaged = "externally managed";
                internal const string AppDomain = "AppDomain";
                internal const string DeclaringInstance = "instance of declaring class";
                internal const string Unbounded = "unbounded";
                internal const string Infinite = "infinite";
            }

            [AttributeUsage(AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Constructor,
                AllowMultiple = true, Inherited = false)]
            [Conditional("CODE_ANALYSIS")]
            public sealed class ExternalResourceAttribute : Attribute
            {
                readonly Location location;
                readonly string description;

                public ExternalResourceAttribute(Location location, string description)
                {
                    this.location = location;
                    this.description = description;
                }

                public Location Location
                {
                    get
                    {
                        return this.location;
                    }
                }

                public string Description
                {
                    get
                    {
                        return this.description;
                    }
                }
            }

            [AttributeUsage(AttributeTargets.Field)]
            [Conditional("CODE_ANALYSIS")]
            public sealed class CacheAttribute : Attribute
            {
                readonly Type elementType;
                readonly CacheAttrition cacheAttrition;

                public CacheAttribute(Type elementType, CacheAttrition cacheAttrition)
                {
                    Scope = Strings.DeclaringInstance;
                    SizeLimit = Strings.Unbounded;
                    Timeout = Strings.Infinite;

                    if (elementType == null)
                    {
                        throw Fx.Exception.ArgumentNull("elementType");
                    }

                    this.elementType = elementType;
                    this.cacheAttrition = cacheAttrition;
                }

                public Type ElementType
                {
                    get
                    {
                        return this.elementType;
                    }
                }

                public CacheAttrition CacheAttrition
                {
                    get
                    {
                        return this.cacheAttrition;
                    }
                }

                public string Scope { get; set; }
                public string SizeLimit { get; set; }
                public string Timeout { get; set; }
            }

            [AttributeUsage(AttributeTargets.Field)]
            [Conditional("CODE_ANALYSIS")]
            public sealed class QueueAttribute : Attribute
            {
                readonly Type elementType;

                public QueueAttribute(Type elementType)
                {
                    Scope = Strings.DeclaringInstance;
                    SizeLimit = Strings.Unbounded;

                    if (elementType == null)
                    {
                        throw Fx.Exception.ArgumentNull("elementType");
                    }

                    this.elementType = elementType;
                }

                public Type ElementType
                {
                    get
                    {
                        return this.elementType;
                    }
                }

                public string Scope { get; set; }
                public string SizeLimit { get; set; }
                public bool StaleElementsRemovedImmediately { get; set; }
                public bool EnqueueThrowsIfFull { get; set; }
            }

            // Set on a class when that class uses lock (this) - acts as though it were on a field
            //     private object this;
            [AttributeUsage(AttributeTargets.Field | AttributeTargets.Class, Inherited = false)]
            [Conditional("CODE_ANALYSIS")]
            public sealed class SynchronizationObjectAttribute : Attribute
            {
                public SynchronizationObjectAttribute()
                {
                    Blocking = true;
                    Scope = Strings.DeclaringInstance;
                    Kind = SynchronizationKind.FromFieldType;
                }

                public bool Blocking
                {
                    get;
                    set;
                }
                public string Scope
                {
                    get;
                    set;
                }
                public SynchronizationKind Kind
                {
                    get;
                    set;
                }
            }

            [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = true)]
            [Conditional("CODE_ANALYSIS")]
            public sealed class SynchronizationPrimitiveAttribute : Attribute
            {
                readonly BlocksUsing blocksUsing;

                public SynchronizationPrimitiveAttribute(BlocksUsing blocksUsing)
                {
                    this.blocksUsing = blocksUsing;
                }

                public BlocksUsing BlocksUsing
                {
                    get
                    {
                        return this.blocksUsing;
                    }
                }

                public bool SupportsAsync
                {
                    get;
                    set;
                }
                public bool Spins
                {
                    get;
                    set;
                }
                public string ReleaseMethod
                {
                    get;
                    set;
                }
            }

            [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)]
            [Conditional("CODE_ANALYSIS")]
            public sealed class BlockingAttribute : Attribute
            {
                public BlockingAttribute()
                {
                }

                public string CancelMethod
                {
                    get;
                    set;
                }
                public Type CancelDeclaringType
                {
                    get;
                    set;
                }
                public string Conditional
                {
                    get;
                    set;
                }
            }

            // Sometime a method will call a conditionally-blocking method in such a way that it is guaranteed
            // not to block (i.e. the condition can be Asserted false).  Such a method can be marked as
            // GuaranteeNonBlocking as an assertion that the method doesn't block despite calling a blocking method.
            //
            // Methods that don't call blocking methods and aren't marked as Blocking are assumed not to block, so
            // they do not require this attribute.
            [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)]
            [Conditional("CODE_ANALYSIS")]
            public sealed class GuaranteeNonBlockingAttribute : Attribute
            {
                public GuaranteeNonBlockingAttribute()
                {
                }
            }

            [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)]
            [Conditional("CODE_ANALYSIS")]
            public sealed class NonThrowingAttribute : Attribute
            {
                public NonThrowingAttribute()
                {
                }
            }

            [SuppressMessage(FxCop.Category.Performance, "CA1813:AvoidUnsealedAttributes",
                Justification = "This is intended to be an attribute heirarchy. It does not affect product perf.")]
            [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor,
                AllowMultiple = true, Inherited = false)]
            [Conditional("CODE_ANALYSIS")]
            public class ThrowsAttribute : Attribute
            {
                readonly Type exceptionType;
                readonly string diagnosis;

                public ThrowsAttribute(Type exceptionType, string diagnosis)
                {
                    if (exceptionType == null)
                    {
                        throw Fx.Exception.ArgumentNull("exceptionType");
                    }
                    if (string.IsNullOrEmpty(diagnosis))
                    {
                        throw Fx.Exception.ArgumentNullOrEmpty("diagnosis");
                    }

                    this.exceptionType = exceptionType;
                    this.diagnosis = diagnosis;
                }

                public Type ExceptionType
                {
                    get
                    {
                        return this.exceptionType;
                    }
                }

                public string Diagnosis
                {
                    get
                    {
                        return this.diagnosis;
                    }
                }
            }

            [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)]
            [Conditional("CODE_ANALYSIS")]
            public sealed class InheritThrowsAttribute : Attribute
            {
                public InheritThrowsAttribute()
                {
                }

                public Type FromDeclaringType
                {
                    get;
                    set;
                }
                public string From
                {
                    get;
                    set;
                }
            }

            [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class |
                AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method |
                AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface |
                AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
            [Conditional("CODE_ANALYSIS")]
            public sealed class SecurityNoteAttribute : Attribute
            {
                public SecurityNoteAttribute()
                {
                }

                public string Critical
                {
                    get;
                    set;
                }
                public string Safe
                {
                    get;
                    set;
                }
                public string Miscellaneous
                {
                    get;
                    set;
                }
            }
        }
    }
}


text:
package com.spotify.heroic.grammar;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;

import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.stream.Stream;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.verify;

@RunWith(MockitoJUnitRunner.class)
public class MinusExpressionTest extends AbstractExpressionTest<MinusExpression> {
    @Override
    protected MinusExpression build(final Context ctx) {
        return new MinusExpression(ctx, a, b);
    }

    @Override
    protected BiFunction<Expression.Visitor<Void>, MinusExpression, Void> visitorMethod() {
        return Expression.Visitor::visitMinus;
    }

    @Override
    protected Stream<Consumer<MinusExpression>> accessors() {
        return Stream.of(accessorTest(a, MinusExpression::getLeft),
            accessorTest(b, MinusExpression::getRight));
    }

    @Override
    public void evalTest() {
        super.evalTest();

        verify(a).eval(scope);
        verify(b).eval(scope);
    }
}

redpajama_set_name: RedPajamaGithub


text:
[![Build Status](https://travis-ci.org/zzzmanzzz/KsanaDB.svg?branch=master)](https://travis-ci.org/zzzmanzzz/KsanaDB)
[![Coverage Status](https://coveralls.io/repos/github/zzzmanzzz/KsanaDB/badge.svg?branch=master)](https://coveralls.io/github/zzzmanzzz/KsanaDB?branch=master)

## Document
Please read the [Wiki](https://github.com/zzzmanzzz/KsanaDB/wiki)

## Change log
Please read the release note [page](https://github.com/zzzmanzzz/KsanaDB/wiki/Release-notes-and-change-log)


text:
TRVLS.Constants.Success = "Success";
TRVLS.Constants.Failure = "Failure";
TRVLS.Constants.GenericError = "Oops...something error went wrong!";
TRVLS.Constants.ProgressText = "Loading...";
TRVLS.Constants.LoggingIn = "Logging In...";
TRVLS.Constants.FetchingTrips = "Fetching Trips...";
TRVLS.Constants.FetchingLocation = "Fetching Location...";
TRVLS.Constants.CreatingUser = "Creating User...";
TRVLS.Constants.ResettingPassword = "Resetting Password...";
TRVLS.Constants.FetchingMembers = "Fetching Members...";
TRVLS.Constants.AddingMembers = "Adding Members...";
TRVLS.Constants.DeletingMember = "Deleting Member...";
TRVLS.Constants.JoiningTrip = "Adding you to trip...";
TRVLS.Constants.NotJoiningTrip = "Removing you from the trip...";
TRVLS.Constants.ProfileName = "TRVLS_PROFILE";
TRVLS.Constants.FetchingPlaces = "Nearby Attractions...";
TRVLS.Constants.FetchingNotifications = "Fetching Notifications...";
TRVLS.Constants.FetchingAssociatedTrip = "Fetching Associated Trips...";
TRVLS.Constants.addedToTripNotification = "Trip to - ";
TRVLS.Constants.deletedFromTripNotification = "You have been removed from the trip - ";

//constant values
TRVLS.Constants.NTYPE_Trips = 1;
TRVLS.Constants.Pending = 1000;
TRVLS.Constants.Joined = 1001;
TRVLS.Constants.NotInterested = 1002;

TRVLS.Constants.MemberStatus = {
    1000: "Waiting",
    1001: "Joined",
    1002: "Not In"
};


text:
#include "PlanParser.h"

#include "rosplan_dispatch_msgs/ActionDispatch.h"
#include "rosplan_dispatch_msgs/EsterelPlan.h"
#include "rosplan_knowledge_msgs/GetDomainOperatorDetailsService.h"
#include "rosplan_knowledge_msgs/GetDomainAttributeService.h"
#include "rosplan_knowledge_msgs/GetAttributeService.h"
#include "rosplan_knowledge_msgs/DomainOperator.h"
#include "rosplan_knowledge_msgs/DomainFormula.h"
#include "diagnostic_msgs/KeyValue.h"

#include <stdlib.h>
#include <string>
#include <fstream>
#include <sstream>
#include <ctime>
#include <algorithm>

#ifndef KCL_pddl_esterel_plan_parser
#define KCL_pddl_esterel_plan_parser

/**
 * This class describes the POPFEsterelPlanParser, which parses the output of popf and generates an Esterel plan.
 */
namespace KCL_rosplan {

	class PDDLEsterelPlanParser: public PlanParser
	{
	private:

		/*---------------------------------*/
		/* ACTION SUPPORT AND INTERFERENCE */
		/*---------------------------------*/

		/**
		 * @returns True if the node satisfies the (possibly negative) condition
		 */
		bool satisfiesPrecondition(rosplan_knowledge_msgs::DomainFormula& condition, const rosplan_dispatch_msgs::EsterelPlanNode& node, bool negative_condition) {

			std::vector<rosplan_knowledge_msgs::DomainFormula>::iterator cit;

			if(!negative_condition) {

				if(node.node_type == rosplan_dispatch_msgs::EsterelPlanNode::ACTION_START) {
					cit = action_details[node.action.action_id].at_start_add_effects.begin();
					for(; cit!=action_details[node.action.action_id].at_start_add_effects.end(); cit++) {
						if(domainFormulaMatches(condition, *cit)) return true;
					}
				} else if(node.node_type == rosplan_dispatch_msgs::EsterelPlanNode::ACTION_END) {
					cit = action_details[node.action.action_id].at_end_add_effects.begin();
					for(; cit!=action_details[node.action.action_id].at_end_add_effects.end(); cit++) {
						if(domainFormulaMatches(condition, *cit)) return true;
					}
				}

			} else {

				if(node.node_type == rosplan_dispatch_msgs::EsterelPlanNode::ACTION_START) {
					cit = action_details[node.action.action_id].at_start_del_effects.begin();
					for(; cit!=action_details[node.action.action_id].at_start_del_effects.end(); cit++) {
						if(domainFormulaMatches(condition, *cit)) return true;
					}
				} else if(node.node_type == rosplan_dispatch_msgs::EsterelPlanNode::ACTION_END) {
					cit = action_details[node.action.action_id].at_end_del_effects.begin();
					for(; cit!=action_details[node.action.action_id].at_end_del_effects.end(); cit++) {
						if(domainFormulaMatches(condition, *cit)) return true;
					}
				}
			}

			return false;
		}

		/**
		 * @returns True if the effect satisfies the (possibly negative) condition
		 */
		bool satisfiesPrecondition(rosplan_knowledge_msgs::DomainFormula& condition, const rosplan_knowledge_msgs::KnowledgeItem& effect, bool negative_condition) {

			// convert KnowledgeItem to (grounded) DomainFormula
			rosplan_knowledge_msgs::DomainFormula eff;
			eff.name = effect.attribute_name;
			for(int i=0; i<effect.values.size(); i++) {
				diagnostic_msgs::KeyValue pair;
				pair.key = effect.values[i].key;
				pair.value = effect.values[i].value;
				eff.typed_parameters.push_back(pair);
			}

			return (negative_condition == effect.is_negative) && domainFormulaMatches(condition, eff);
		}

		/*---------------*/
		/* GRAPH METHODS */
		/*---------------*/

		void makeEdge(int source_node_id, int sink_node_id, int edge_type) {
			// create an ordering that only specifies after
			makeEdge(source_node_id, sink_node_id, 0, std::numeric_limits<double>::max(), edge_type);
		}

		/*------------------------*/
		/* DOMAIN FORMULA METHODS */
		/*------------------------*/

		/**
		 * Grounds the given vector of domain formulae. Resulting in e.g., (robot_at ?wp - wp01)
		 * @param formula  The domain formula to be grounded, e.g., (robot_at ?wp - waypoint)
		 * @param opParams An ordered KeyValue vector of operator parameters, e.g., (?r - robot ?wp - waypoint)
		 * @param params   An ordered vector of parameter objects, e.g., [robot01, wp01]
		 */
		void groundFormula(std::vector<rosplan_knowledge_msgs::DomainFormula> &formula, std::vector<diagnostic_msgs::KeyValue> &opParams, std::vector<std::string> &params) {

			std::vector<rosplan_knowledge_msgs::DomainFormula>::iterator cit;
			cit = formula.begin();
			for(; cit!=formula.end(); cit++) {
				// for each predicate parameter
				for(int j=0;j<cit->typed_parameters.size();j++) {
					bool found = false;
					// for each operator parameter
					for(size_t i=0; i<opParams.size(); i++) {
						// operator and predicate parmater labels match
						if(opParams[i].key == cit->typed_parameters[j].key) {
							// set predicate parameter to be: label -> value
							cit->typed_parameters[j].value = params[i];
							found = true;
						}
					}
					// if not found, then label must be a constant
					if(!found) {
						// set predicate parameter to be: value -> value
						// key could be fetched by "get_predicate_details" service, but is not required
						cit->typed_parameters[j].value = cit->typed_parameters[j].key;
					}
				}
			}
		}

		/**
		 * @returns True if the two domain formula parameters match completely.
		 */
		bool domainFormulaMatches(rosplan_knowledge_msgs::DomainFormula& a, rosplan_knowledge_msgs::DomainFormula& b) {
			if(b.name != a.name) return false;
			if(b.typed_parameters.size() != a.typed_parameters.size()) return false;
			for(size_t i=0; i<a.typed_parameters.size(); i++) {
				if(a.typed_parameters[i].value != b.typed_parameters[i].value) {
					return false;
				}
			}
			return true;
		}

		/* plan description in Esterel */
		rosplan_dispatch_msgs::EsterelPlan last_plan;
		std::map<int,rosplan_knowledge_msgs::DomainOperator> action_details;
        double epsilon_time;

		/* clients */
		ros::ServiceClient get_predicate_client;
		ros::ServiceClient get_propositions_client;
		ros::ServiceClient get_tils_client;
		ros::ServiceClient get_functions_client;
		ros::ServiceClient get_operator_details_client;

		/* TILs */
		std::multimap<double, rosplan_knowledge_msgs::KnowledgeItem> til_list;

	protected:

		/* post process plan */
		void processPDDLParameters(rosplan_dispatch_msgs::ActionDispatch &msg, std::vector<std::string> &params);
		void fetchTILs();
		void createGraph();
		bool addInterferenceEdges(std::multimap<double,int> &node_map, std::multimap<double,int>::iterator &current_node);
		void makeEdge(int source_node_id, int sink_node_id, double lower_bound, double upper_bound, int edge_type);
		bool addConditionEdge(
				std::multimap<double,int> &node_map, std::multimap<double,int>::iterator &current_node,
				rosplan_knowledge_msgs::DomainFormula &condition, bool negative_condition, bool overall_condition);

		/* virtual methods */
		void reset();
		void preparePlan();
		void publishPlan();

	public:

		/* constructor */
		PDDLEsterelPlanParser(ros::NodeHandle &nh);
		~PDDLEsterelPlanParser();

		/* ROS interface */
		ros::Publisher plan_publisher;
	};
} // close namespace

#endif


text:
Knowing the installed packages in your system is a basic tool / life skill for responsible developers / administrators. Below are methods / commands for a couple of systems to get the information you need...

For Debian/Ubuntu:
```sh
sudo dpkg --get-selections
```

For RPM system:
```sh
yum list installed
```

For BSD systems:
```sh
pkg_version
```

**pro tip**: When you're backing up stuff or migrating, it's always good to save the list of installed packages of your system. Pipe the output to a file!


text:
        {{getWord('Binding Console Server')}}

    <form class="smart-form">

        <fieldset>

                                    {{consoleserver.name}}
                                    {{consoleserver.description}}

        </fieldset>

            <button data-ng-click="bindingConsoleServer()" class="btn btn-primary">
                {{getWord('Submit')}}
            </button>
            <button type="button" class="btn btn-default" data-ng-click="closeModal()">
                {{getWord('Cancel')}}
            </button>

    </form>


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<artifactId>frostillicus.framework.plugin</artifactId>
	<packaging>eclipse-plugin</packaging>

	<build>
		<sourceDirectory>src</sourceDirectory>
	</build>

	<parent>
		<groupId>frostillicus_framework</groupId>
		<artifactId>frostillicus.framework</artifactId>
		<version>1.0.0-SNAPSHOT</version>
	</parent>

</project>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Folia cryptog. Estonica 1: 3 (1972)

#### Original name
Cladonia oxneri Rass.

### Remarks
null


text:
'use strict';

const Code = require('code');
const Lab = require('lab');
const expect = Code.expect;
const lab = exports.lab = Lab.script();
const User = require('../../api/<%= routeName %>/model/<%= capRouteName %>');
const sinon = require('sinon');

//BDD
const describe = lab.describe;
const it = lab.it;
const before = lab.before;
const after = lab.after;

//pull in hapi server
const Server = require('../../server.js');
let apiResponse = null;

describe('<%= capRouteName %>: ', () => {
    it('will create a <%= routeName %>', (done) => {
        const testPayload = {
            name: 'some name',
            description: 'some description'
        };

        const request = {
            method: 'POST',
            url: '<%= apiPrefix %>/<%= routeName %>',
            payload: testPayload
        };

        Server.inject(request, (response) => {
            expect(response.statusCode).to.equal(201);
            expect(response.result.name).to.equal(testPayload.name);

            done();
        });
    });

    it('will return back a list of <%= routeName %>', (done) => {
        const request = {
            method: 'GET',
            url: '<%= apiPrefix %>/<%= routeName %>'
        };

        Server.inject(request, (response) => {
            apiResponse = response.result;
            expect(response.statusCode).to.equal(200);

            done();
        });
    });

    it('will delete a <%= routeName %>', (done) => {
        const request = {
            method: 'DELETE',
            url: '<%= apiPrefix %>/<%= routeName %>/' + apiResponse[0]._id
        };

        Server.inject(request, (response) => {

            expect(response.statusCode).to.equal(204);

            done();
        });
    });
});


text:
from typing import List
from discord import Embed
from discord.ext.commands import command, Context, Cog
from random import randint

from ..bunkbot import BunkBot
from ..channel.channel_service import ChannelService
from ..core.bunk_user import BunkUser
from ..core.functions import get_cmd_params
from ..core.registry import USER_SERVICE, CHANNEL_SERVICE
from ..user.user_service import UserService

ROLE_DESCRIPTION: str = """Roll a random value between 0 and 100.  Optionally, you may pass a value range.\n
    Example: !roll
    Example: !roll 1-10
"""
class Roll(Cog):
    def __init__(self, channels: ChannelService, users: UserService):
        self.channels: ChannelService = channels
        self.users: UserService = users

    # roll a random number
    # optionally specify a value range with default 0-100
    @command(help=ROLE_DESCRIPTION)
    async def roll(self, ctx: Context) -> None:
        try:
            await ctx.trigger_typing()

            min_val: int = 0
            max_val: int = 100
            params: List[str] = get_cmd_params(ctx)
            user: BunkUser = self.users.get_by_id(ctx.author.id)

            if len(params) > 0:
                if "-" in params[0]:
                    p_split: str = params[0].split("-")
                    if p_split[0].isdigit() and p_split[1].isdigit():
                        val_1 = int(p_split[0])
                        val_2 = int(p_split[1])
                        min_val: int = val_1 if val_1 <= val_2 else val_2
                        max_val: int = val_1 if val_2 <= val_1 else val_2

            title: str = "Rolling ({0}-{1})".format(min_val, max_val)
            message: str = "{0} rolls {1}".format(user.name, str(randint(min_val, max_val)))

            await ctx.send(embed=Embed(title=title, description=message, color=ctx.author.color))
        except Exception as e:
            await self.channels.log_error(e, "roll")

def setup(bot: BunkBot) -> None:
    bot.add_cog(Roll(CHANNEL_SERVICE, USER_SERVICE))


text:
> My kryptonian app

## Dev

```
$ npm install
```

### Run

```
$ npm start
```

### Build

```
$ npm run build
```

Builds the app for OS X, Linux, and Windows, using [electron-packager](https://github.com/maxogden/electron-packager).

## License

MIT © [Jordan Klassen](http://forivall.github.io)


text:
[Working Demo](http://tsmarsh.github.io/Knockout-Physics/)

This builds on the fantastic work of [http://soulwire.github.com/Coffee-Physics/](http://soulwire.github.com/Coffee-Physics/), replacing the rendering subsystem with KnockoutJS.

Knockout and Angular both represent a massive shift towards client side development, dramatically simplfiying the binding of the view to the model, but are they fast for game development?

I think this spike proves that for Knockout the answer is a resounding "Yes!". Looking forward to trying this with Angular next.


text:
define(['require',
        'external/lodash/lodash.min',
        'webida-lib/util/path',
        'tern/lib/tern',
        './file-server',
        './reference',
        'text!tern/defs/browser.json',
        'text!tern/defs/ecma5.json',
        'text!tern/defs/jquery.json',
        'text!./tern-def-ecma5-keywords.json',
        'tern/plugin/doc_comment',
        'tern/plugin/requirejs',
        './tern-plugin-dojojs'],
function (require, _, pathUtil, tern, fileServer, reference, browserText,
           ecma5Text, jqueryText, ecma5KeywordsText/*, p1, p2, p3*/) {
    'use strict';

    var browserDef = JSON.parse(browserText);
    var ecma5Def = JSON.parse(ecma5Text);
    var jqueryDef = JSON.parse(jqueryText);
    var ecma5KeywordsDef = JSON.parse(ecma5KeywordsText);

    function Server(serverId) {
        this.serverId = serverId;
        this.tern = null;
        this.files = {};
        this.requirejsOptions = {
            maxDepth : 1
        };
    }

    var jshint = {};

    jshint.localServers = {};

    jshint.startServer = function (serverId) {
        var server = this.localServers[serverId];

        if (server) {
            return server;
        }

        server = new Server(serverId);
        server.onReferenceUpdate = function (file, newrefs, oldrefs) {
            newrefs = newrefs || [];
            oldrefs = oldrefs || [];
            if (server.files[file.path]) {
                var changed = false;
                var pathsToDel = _.without(oldrefs, newrefs);
                var pathsToAdd = _.without(newrefs, oldrefs);
                _.each(pathsToDel, function (filepath) {
                    changed = true;
                    jshint.delFile(server.serverId, filepath);
                });
                _.each(pathsToAdd, function (filepath) {
                    if (pathUtil.isJavaScript(filepath)) {
                        changed = true;
                        jshint.addFile(server.serverId, filepath);
                    }
                });
                if (changed) {
                    fileServer.setUpdated(server.serverId);
                }
            }
        };
        fileServer.addReferenceUpdateListener(server.onReferenceUpdate);

        this.localServers[serverId] = server;

        var ternGetFileCallback = function (filepath, c) {
            server.files[filepath] = true;
            fileServer.getFile(filepath, function (error, fileModel) {
                c(error, fileModel);
            });
        };

        server.tern = new tern.Server({
            getFile: ternGetFileCallback,
            async: true,
            defs: [browserDef, ecma5Def, jqueryDef, ecma5KeywordsDef],
            plugins: {
                'doc_comment': true,
                'requirejs': server.requirejsOptions,
                'dojojs' : true
            }
        });

        server.tern.fileServer = fileServer;
        server.tern._ccFilePath = serverId;

        return server;
    };

    jshint.stopServer = function (serverId) {
        var server = this.localServers[serverId];
        if (!server) {
            console.warn('## cc : no server for : ' + serverId);
            return;
        }

        server.tern = null;
        fileServer.removeReferenceUpdateListener(server.onReferenceUpdate);
        delete this.localServers[serverId];
    };

    jshint.addFile = function (serverId, filepath, text) {
        var server = this.localServers[serverId];
        if (!server) {
            console.warn('## cc : no server for : ' + serverId);
            return;
        }

        server.files[filepath] = true;
        var existingFile = fileServer.getLocalFile(filepath);
        if (existingFile) {
            server.onReferenceUpdate(existingFile, reference.getReferenceTos(filepath));
        }

        if (text !== undefined) {
            fileServer.setText(filepath, text);
        }

        fileServer.getFile(filepath, function (/*error, file*/) {
            if (pathUtil.isJavaScript(filepath)) {
                server.tern.addFile(filepath);
            }
        });
    };

    jshint.getFile = function (filepath, c) {
        var file = fileServer.getLocalFile(filepath);
        if (file) {
            c(undefined, file.text);
        } else {
            c('not a local file');
        }
    };

    jshint.delFile = function (serverId, filepath) {
        var server = this.localServers[serverId];
        if (!server) {
            console.warn('## cc : no server for : ' + serverId);
            return;
        }

        delete server.files[filepath];
        server.tern.delFile(filepath);
    };

    function findSubfileOfPosition(subfiles, pos) {
        var startCh = pos.ch;
        var endCh = pos.ch - 1;
        return _.find(subfiles, function (subfile) {
            return subfile.subfileStartPosition &&
                ((subfile.subfileStartPosition.line === pos.line &&
                  subfile.subfileStartPosition.ch <= startCh) ||
                 subfile.subfileStartPosition.line < pos.line) &&
                subfile.subfileEndPosition &&
                ((subfile.subfileEndPosition.line === pos.line &&
                  subfile.subfileEndPosition.ch >= endCh) ||
                 subfile.subfileEndPosition.line > pos.line);
        });
    }

    /**
     * @param {files: [{name, type, text}], query:{type: string, end:{line,ch}, file: string},
        params:[{name: string, value: string}]} body
     **/
    jshint.request = function (serverId, body, c) {
        var server = this.localServers[serverId];
        if (!server) {
            console.warn('No server for : ' + serverId);
            c({error: 'No javascript server for code completion'});
            return;
        }

        if (body.files) {
            _.each(body.files, function (file) {
                if (file.type === 'full') {
                    fileServer.setText(file.name, file.text);
                    file.type = null;
                }
            });
            body.files = _.filter(body.files, function (file) {
                return file.type !== null;
            });
        }

        if (body.params) {
            _.each(body.params, function (param) {
                if (param.name === 'maybeBaseUrl') {
                    server.requirejsOptions.maybeBaseUrl = param.value;
                }
            });
        }

        if (body.query) {
            var subfile;
            if (pathUtil.isHtml(body.query.file)) {
                var file = fileServer.getLocalFile(body.query.file);
                var subfiles = file.getHtmlScriptSubfiles();
                subfile = findSubfileOfPosition(subfiles, body.query.end);
                if (!subfile) {
                    console.log('Not in a javascript');
                    c({error: 'Not in a javascript'});
                    return;
                }
                body.query.file = subfile.path;
                body.query.end.line -= subfile.subfileStartPosition.line;
                if (body.query.end.line === 0) {
                    body.query.end.ch -= subfile.subfileStartPosition.ch;
                }
            }

            server.tern.request(body, function (error, data) {
                if (subfile && data) {
                    if (data.start) {
                        if (data.start.line === 0) {
                            data.start.ch += subfile.subfileStartPosition.ch;
                        }
                        data.start.line += subfile.subfileStartPosition.line;
                    }
                    if (data.end) {
                        if (data.end.line === 0) {
                            data.end.ch += subfile.subfileStartPosition.ch;
                        }
                        data.end.line += subfile.subfileStartPosition.line;
                    }
                }

                c(error, data);
            });
        }
    };

    return jshint;
});


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

    $("a[href*=editQuestion#]").click(function(event) {
        var editQuestionBtn = document.getElementById('_eventId_editQuestion');
        editQuestionBtn.value = $(this).val();
        event.preventDefault();
        editQuestionBtn.click();
    });

});


text:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0">
    <link rel="stylesheet" href="<?php echo get_theme_url($theme); ?>css/vendor/simple-line-icons.css">
    <link rel="stylesheet" href="<?php echo get_theme_url($theme); ?>css/vendor/tooltipster.css">
    <link rel="stylesheet" href="<?php echo get_theme_url($theme); ?>css/vendor/owl.carousel.css">
    <link rel="stylesheet" href="<?php echo get_theme_url($theme); ?>css/style.css">
    <!-- favicon -->
<!--    <link rel="icon" href="favicon.ico">-->
    <title>Emerald Dragon | Home</title>
</head>

<body>


text:
/**
 *    @file
 *      This file defines the Matter Group message counters of remote nodes for groups.
 *
 */
#pragma once

#include <array>
#include <bitset>

#include <lib/core/CHIPPersistentStorageDelegate.h>
#include <lib/core/DataModelTypes.h>
#include <lib/core/NodeId.h>
#include <lib/core/PeerId.h>
#include <lib/support/Span.h>
#include <transport/PeerMessageCounter.h>

#define GROUP_MSG_COUNTER_MIN_INCREMENT 1000

namespace chip {
namespace Transport {

class GroupSender
{
public:
    NodeId mNodeId = kUndefinedNodeId;
    PeerMessageCounter msgCounter;
};

class GroupFabric
{
public:
    FabricIndex mFabricIndex  = kUndefinedFabricIndex;
    uint8_t mControlPeerCount = 0;
    uint8_t mDataPeerCount    = 0;
    GroupSender mDataGroupSenders[CHIP_CONFIG_MAX_GROUP_DATA_PEERS];
    GroupSender mControlGroupSenders[CHIP_CONFIG_MAX_GROUP_CONTROL_PEERS];
};

class GroupPeerTable
{
public:
    CHIP_ERROR FindOrAddPeer(FabricIndex fabricIndex, NodeId nodeId, bool isControl,
                             chip::Transport::PeerMessageCounter *& counter);

    // Used in case of MCSP failure
    CHIP_ERROR RemovePeer(FabricIndex fabricIndex, NodeId nodeId, bool isControl);

    CHIP_ERROR FabricRemoved(FabricIndex fabricIndex);

    // Protected for Unit Tests inheritance
protected:
    bool RemoveSpecificPeer(GroupSender * list, NodeId nodeId, uint32_t size);
    void CompactPeers(GroupSender * list, uint32_t size);
    void RemoveAndCompactFabric(uint32_t tableIndex);

    GroupFabric mGroupFabrics[CHIP_CONFIG_MAX_FABRICS];
};

// Might want to rename this so that it is explicitly the sending side of counters
class GroupOutgoingCounters
{
public:
    GroupOutgoingCounters(){};
    GroupOutgoingCounters(chip::PersistentStorageDelegate * storage_delegate);
    CHIP_ERROR Init(chip::PersistentStorageDelegate * storage_delegate);
    uint32_t GetCounter(bool isControl);
    CHIP_ERROR IncrementCounter(bool isControl);

    // Protected for Unit Tests inheritance
protected:
    // TODO Initialize those to random value
    uint32_t mGroupDataCounter                 = 0;
    uint32_t mGroupControlCounter              = 0;
    chip::PersistentStorageDelegate * mStorage = nullptr;
};

} // namespace Transport
} // namespace chip


text:
package uk.co.alt236.bluetoothlelib.device.adrecord;

import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.SparseArray;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

import uk.co.alt236.bluetoothlelib.util.AdRecordUtils;

/**
 * The Class AdRecordStore.
 */
public class AdRecordStore implements Parcelable {
    public static final Parcelable.Creator<AdRecordStore> CREATOR = new Parcelable.Creator<AdRecordStore>() {
        public AdRecordStore createFromParcel(final Parcel in) {
            return new AdRecordStore(in);
        }

        public AdRecordStore[] newArray(final int size) {
            return new AdRecordStore[size];
        }
    };
    private final SparseArray<AdRecord> mAdRecords;
    private final String mLocalNameComplete;
    private final String mLocalNameShort;

    public AdRecordStore(final Parcel in) {
        final Bundle b = in.readBundle(getClass().getClassLoader());
        mAdRecords = b.getSparseParcelableArray("records_array");
        mLocalNameComplete = b.getString("local_name_complete");
        mLocalNameShort = b.getString("local_name_short");
    }

    /**
     * Instantiates a new Bluetooth LE device Ad Record Store.
     *
     * @param adRecords the ad records
     */
    public AdRecordStore(final SparseArray<AdRecord> adRecords) {
        mAdRecords = adRecords;

        mLocalNameComplete = AdRecordUtils.getRecordDataAsString(
                mAdRecords.get(AdRecord.TYPE_LOCAL_NAME_COMPLETE));

        mLocalNameShort = AdRecordUtils.getRecordDataAsString(
                mAdRecords.get(AdRecord.TYPE_LOCAL_NAME_SHORT));

    }

    /* (non-Javadoc)
     * @see android.os.Parcelable#describeContents()
     */
    @Override
    public int describeContents() {
        return 0;
    }

    /**
     * Gets the short local device name.
     *
     * @return the local name complete
     */
    public String getLocalNameComplete() {
        return mLocalNameComplete;
    }

    /**
     * Gets the complete local device name.
     *
     * @return the local name short
     */
    public String getLocalNameShort() {
        return mLocalNameShort;
    }

    /**
     * retrieves an individual record.
     *
     * @param record the record
     * @return the record
     */
    public AdRecord getRecord(final int record) {
        return mAdRecords.get(record);
    }

    /**
     * Gets the record data as string.
     *
     * @param record the record
     * @return the record data as string
     */
    public String getRecordDataAsString(final int record) {
        return AdRecordUtils.getRecordDataAsString(
                mAdRecords.get(record));
    }

    /**
     * Gets the record as collection.
     *
     * @return the records as collection
     */
    public Collection<AdRecord> getRecordsAsCollection() {
        return Collections.unmodifiableCollection(asList(mAdRecords));
    }

    /**
     * Checks if is record present.
     *
     * @param record the record
     * @return true, if is record present
     */
    public boolean isRecordPresent(final int record) {
        return mAdRecords.indexOfKey(record) >= 0;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "AdRecordStore [mLocalNameComplete=" + mLocalNameComplete + ", mLocalNameShort=" + mLocalNameShort + "]";
    }

    /* (non-Javadoc)
     * @see android.os.Parcelable#writeToParcel(android.os.Parcel, int)
     */
    @Override
    public void writeToParcel(final Parcel parcel, final int arg1) {
        final Bundle b = new Bundle();
        b.putString("local_name_complete", mLocalNameComplete);
        b.putString("local_name_short", mLocalNameShort);
        b.putSparseParcelableArray("records_array", mAdRecords);

        parcel.writeBundle(b);
    }

    /**
     * As list.
     *
     * @param <C>         the generic type
     * @param sparseArray the sparse array
     * @return the collection
     */
    public static <C> Collection<C> asList(final SparseArray<C> sparseArray) {
        if (sparseArray == null) return null;

        final Collection<C> arrayList = new ArrayList<>(sparseArray.size());
        for (int i = 0; i < sparseArray.size(); i++) {
            arrayList.add(sparseArray.valueAt(i));
        }

        return arrayList;
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

/** Package containing the implementations for PolicyInsightsClient. null. */
package com.azure.resourcemanager.policyinsights.implementation;


text:
import {Bean, Context, Autowired} from "../../context/context";
import {RowNode} from "../../entities/rowNode";
import {Utils as _} from "../../utils";
import {GridOptionsWrapper} from "../../gridOptionsWrapper";
import {SelectionController} from "../../selectionController";
import {EventService} from "../../eventService";
import {IRowNodeStage, StageExecuteParams} from "../../interfaces/iRowNodeStage";
import {ColumnController} from "../../columnController/columnController";

@Bean('flattenStage')
export class FlattenStage implements IRowNodeStage {

    @Autowired('gridOptionsWrapper') private gridOptionsWrapper: GridOptionsWrapper;
    @Autowired('selectionController') private selectionController: SelectionController;
    @Autowired('eventService') private eventService: EventService;
    @Autowired('context') private context: Context;
    @Autowired('columnController') private columnController: ColumnController;

    public execute(params: StageExecuteParams): RowNode[] {
        let rootNode = params.rowNode;

        // even if not doing grouping, we do the mapping, as the client might
        // of passed in data that already has a grouping in it somewhere
        let result: RowNode[] = [];

        // putting value into a wrapper so it's passed by reference
        let nextRowTop: NumberWrapper = {value: 0};

        let skipLeafNodes = this.columnController.isPivotMode();

        // if we are reducing, and not grouping, then we want to show the root node, as that
        // is where the pivot values are
        let showRootNode = skipLeafNodes && rootNode.leafGroup;
        let topList = showRootNode ? [rootNode] : rootNode.childrenAfterSort;

        // set all row tops to null, then set row tops on all visible rows. if we don't
        // do this, then the algorithm below only sets row tops, old row tops from old rows
        // will still lie around
        this.resetRowTops(rootNode);

        this.recursivelyAddToRowsToDisplay(topList, result, nextRowTop, skipLeafNodes, 0);

        return result;
    }

    private resetRowTops(rowNode: RowNode): void {
        rowNode.clearRowTop();
        if (rowNode.group) {
            if (rowNode.childrenAfterGroup) {
                for (let i = 0; i<rowNode.childrenAfterGroup.length; i++) {
                    this.resetRowTops(rowNode.childrenAfterGroup[i])
                }
            }
            if (rowNode.sibling) {
                rowNode.sibling.clearRowTop();
            }
        }
    }

    private recursivelyAddToRowsToDisplay(rowsToFlatten: RowNode[], result: RowNode[],
                                          nextRowTop: NumberWrapper, skipLeafNodes: boolean, uiLevel: number) {
        if (_.missingOrEmpty(rowsToFlatten)) { return; }

        let groupSuppressRow = this.gridOptionsWrapper.isGroupSuppressRow();
        let hideOpenParents = this.gridOptionsWrapper.isGroupHideOpenParents();
        let removeSingleChildrenGroups = this.gridOptionsWrapper.isGroupRemoveSingleChildren();

        for (let i = 0; i < rowsToFlatten.length; i++) {
            let rowNode = rowsToFlatten[i];

            // check all these cases, for working out if this row should be included in the final mapped list
            let isGroupSuppressedNode = groupSuppressRow && rowNode.group;
            let isSkippedLeafNode = skipLeafNodes && !rowNode.group;
            let isHiddenOpenParent = hideOpenParents && rowNode.expanded;
            let isRemovedSingleChildrenGroup = removeSingleChildrenGroups && rowNode.group && rowNode.childrenAfterGroup.length === 1;

            let thisRowShouldBeRendered = !isSkippedLeafNode && !isGroupSuppressedNode && !isHiddenOpenParent && !isRemovedSingleChildrenGroup;

            if (thisRowShouldBeRendered) {
                this.addRowNodeToRowsToDisplay(rowNode, result, nextRowTop, uiLevel);
            }

            // if we are pivoting, we never map below the leaf group
            if (skipLeafNodes && rowNode.leafGroup) { continue; }

            if (rowNode.group) {
                // we traverse the group if it is expended, however we always traverse if the parent node
                // was removed (as the group will never be opened if it is not displayed, we show the children instead)
                if (rowNode.expanded || isRemovedSingleChildrenGroup) {

                    // if the parent was excluded, then ui level is that of the parent
                    let uiLevelForChildren = isRemovedSingleChildrenGroup ? uiLevel : uiLevel + 1;
                    this.recursivelyAddToRowsToDisplay(rowNode.childrenAfterSort, result,
                        nextRowTop, skipLeafNodes, uiLevelForChildren);

                    // put a footer in if user is looking for it
                    if (this.gridOptionsWrapper.isGroupIncludeFooter()) {
                        this.ensureFooterNodeExists(rowNode);
                        this.addRowNodeToRowsToDisplay(rowNode.sibling, result, nextRowTop, uiLevel);
                    }
                } else {

                }
            } else if (rowNode.canFlower && rowNode.expanded) {
                let flowerNode = this.createFlowerNode(rowNode);
                this.addRowNodeToRowsToDisplay(flowerNode, result, nextRowTop, uiLevel);
            }
        }
    }

    // duplicated method, it's also in floatingRowModel
    private addRowNodeToRowsToDisplay(rowNode: RowNode, result: RowNode[], nextRowTop: NumberWrapper, uiLevel: number): void {
        result.push(rowNode);
        if (_.missing(rowNode.rowHeight)) {
            let rowHeight = this.gridOptionsWrapper.getRowHeightForNode(rowNode);
            rowNode.setRowHeight(rowHeight);
        }
        rowNode.setUiLevel(uiLevel);
        rowNode.setRowTop(nextRowTop.value);
        rowNode.setRowIndex(result.length - 1);
        nextRowTop.value += rowNode.rowHeight;
    }

    private ensureFooterNodeExists(groupNode: RowNode): void {
        // only create footer node once, otherwise we have daemons and
        // the animate screws up with the daemons hanging around
        if (_.exists(groupNode.sibling)) { return; }

        let footerNode = new RowNode();
        this.context.wireBean(footerNode);
        Object.keys(groupNode).forEach(function (key) {
            (<any>footerNode)[key] = (<any>groupNode)[key];
        });
        footerNode.footer = true;
        footerNode.rowTop = null;
        footerNode.oldRowTop = null;
        if (_.exists(footerNode.id)) {
            footerNode.id = 'rowGroupFooter_' + footerNode.id;
        }
        // get both header and footer to reference each other as siblings. this is never undone,
        // only overwritten. so if a group is expanded, then contracted, it will have a ghost
        // sibling - but that's fine, as we can ignore this if the header is contracted.
        footerNode.sibling = groupNode;
        groupNode.sibling = footerNode;
    }

    private createFlowerNode(parentNode: RowNode): RowNode {

        if (_.exists(parentNode.childFlower)) {
            return parentNode.childFlower;
        } else {
            let flowerNode = new RowNode();
            this.context.wireBean(flowerNode);
            flowerNode.flower = true;
            flowerNode.parent = parentNode;
            if (_.exists(parentNode.id)) {
                flowerNode.id = 'flowerNode_' + parentNode.id;
            }
            flowerNode.data = parentNode.data;
            flowerNode.level = parentNode.level + 1;
            parentNode.childFlower = flowerNode;
            return flowerNode;
        }

    }
}

interface NumberWrapper {
    value: number
}


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

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <link rel="stylesheet" href="docgen-resources/docgen.css" type="text/css">
  <meta name="generator" content="FreeMarker Docgen (DocBook 5)">
  <title>
    FreeMarker Manual - Old FTL syntax
  </title>

        You are here:
          FreeMarker Manual
            >
          Template Language Reference
            >
          Deprecated FTL constructs
            >
          Old FTL syntax

Bookmarks:
Alpha. index, Expressions, ?builtins, #directives, .spec_vars, FAQ, Glossary, API, Home

Next page: #{...}: Numerical interpolation

Previous page

Parent page

Contents

Old FTL syntax

With the old FTL syntax the <tt style="color: #A03D10">#</tt> was not
        required (prior 2.1 not even allowed) in the FTL tags. For example,
        you could write this:

<html>
<head>
  <title>Welcome!</title>
</head>
<body>
  <h1>Welcome ${user}!</h1>
  <p>We have there animals:
  <ul>
  <list animals as animal>
    <li>${animal.name} for ${animal.price} Euros
  </list>
  </ul>
  <include "common_footer.html">
</body>
</html>

While the <tt style="color: #A03D10">#</tt>-less syntax was more natural for
        HTML authors, it had too many drawbacks, so finally we have decided to
        deprecate it. With the newer syntax (a.k.a ``strict syntax''), the
        <tt style="color: #A03D10">#</tt> is strictly required. That is, things like
        <tt style="color: #A03D10"><include "common_footer.html"></tt> will go to the
        output as is, since they are not considered as FTL tags. Note that
        user-defined directives use <tt style="color: #A03D10">@</tt> instead
        of <tt style="color: #A03D10">#</tt>.

However, to give users time to prepare for this change, in
        FreeMarker 2.1 and 2.2 the usage of <tt style="color: #A03D10">#</tt> is optional,
        unless the programmer enables strict syntax mode in the FreeMarker
        configuration by calling <tt style="color: #A03D10">setStrictSyntaxMode(true)</tt>
        on <tt style="color: #A03D10">Configuration</tt>. In fact, we strongly recommend
        this to programmers. Starting from some later release this setting
        will be initially set to <tt style="color: #A03D10">true</tt>. Also, you can
        specify if you want to use strict syntax or old syntax in the template
        files with the <tt>ftl</tt>
        directive.

The advantages of ``strict syntax'' over the legacy FTL syntax
        are:

Since all
            <tt style="color: #A03D10"><#...></tt> and
            <tt style="color: #A03D10"></#...></tt> are
            reserved for FTL:

We can introduce new directives without breaking
                backward compatibility.

We can detect if you made a typo, i.e.
                <tt style="color: #A03D10"><#inculde
                ...></tt> is treated as
                parse-time error, rather than silently treated as simple
                text.

It is easier for third-party tools to handle templates
                (e.g. do syntax highlighting), especially since they don't
                have to know about the new directives introduced with new
                releases.

Templates are more readable, since it is easier to spot
                <tt style="color: #A03D10"><#...></tt> tags embedded into HTML or
                other markup.

<tt style="color: #A03D10"><#</tt> and <tt style="color: #A03D10"></#</tt> is
            illegal XML (except in CDATA sections), and illegal in almost all
            other SGML applications, so they can't interfere with the tags
            used in the static text parts (e.g. if you have
            <tt style="color: #A03D10">include</tt> element in the generated XML).

Next page: #{...}: Numerical interpolation

Previous page

Parent page

Contents

        You are here:
          FreeMarker Manual
            >
          Template Language Reference
            >
          Deprecated FTL constructs
            >
          Old FTL syntax

            FreeMarker Manual -- For FreeMarker 2.3.21

          HTML generated: 2014-10-12 18:53:30 GMT