<file_sep>﻿using System;
using System.Collections.Generic;

namespace ItzWarty.Comparers
{
   public class ReverseComparer<T> : IComparer<T>
      where T : IComparable<T>
   {
      private readonly IComparer<T> m_originalComparer;

      public ReverseComparer(IComparer<T> originalComparer)
      {
         m_originalComparer = originalComparer;
      }

      public ReverseComparer()
      {
         m_originalComparer = null;
      }

      public int Compare(T x, T y)
      {
         if (m_originalComparer == null)
            return y.CompareTo(x);
         else
            return m_originalComparer.Compare(y, x);
      }
   }
}
<file_sep>using System;
using System.Collections.Generic;

namespace ItzWarty.Collections {
   public class CollectionFactory : ICollectionFactory {
      public IConcurrentDictionary<K, V> CreateConcurrentDictionary<K, V>() => new ConcurrentDictionary<K, V>();

      public IConcurrentDictionary<K, V> CreateConcurrentDictionary<K, V>(IEnumerable<KeyValuePair<K, V>> collection) => new ConcurrentDictionary<K, V>(collection);

      public IConcurrentDictionary<K, V> CreateConcurrentDictionary<K, V>(IEqualityComparer<K> comparer) => new ConcurrentDictionary<K, V>(comparer);

      public IConcurrentDictionary<K, V> CreateConcurrentDictionary<K, V>(IEnumerable<KeyValuePair<K, V>> collection, IEqualityComparer<K> comparer) => new ConcurrentDictionary<K, V>(collection, comparer);

      public IConcurrentSet<T> CreateConcurrentSet<T>() => new ConcurrentSet<T>();

      public IConcurrentSet<T> CreateConcurrentSet<T>(IEnumerable<T> collection) => new ConcurrentSet<T>(collection);

      public IConcurrentSet<T> CreateConcurrentSet<T>(IEqualityComparer<T> comparer) => new ConcurrentSet<T>(comparer);

      public IConcurrentSet<T> CreateConcurrentSet<T>(IEnumerable<T> collection, IEqualityComparer<T> comparer) => new ConcurrentSet<T>(collection, comparer);

      public IConcurrentBag<T> CreateConcurrentBag<T>() => new ConcurrentBag<T>();

      public IConcurrentBag<T> CreateConcurrentBag<T>(IEnumerable<T> collection) => new ConcurrentBag<T>(collection);

      public IHashSet<T> CreateHashSet<T>() => new HashSet<T>();

      public IHashSet<T> CreateHashSet<T>(IEnumerable<T> collection) => new HashSet<T>(collection);

      public IHashSet<T> CreateHashSet<T>(IEqualityComparer<T> comparer) => new HashSet<T>(comparer);

      public IHashSet<T> CreateHashSet<T>(IEnumerable<T> collection, IEqualityComparer<T> comparer) => new HashSet<T>(collection, comparer);

      public ISortedSet<T> CreateSortedSet<T>() => new SortedSet<T>();

      public ISortedSet<T> CreateSortedSet<T>(IEnumerable<T> collection) => new SortedSet<T>(collection);

      public ISortedSet<T> CreateSortedSet<T>(IComparer<T> comparer) => new SortedSet<T>(comparer);

      public ISortedSet<T> CreateSortedSet<T>(IEnumerable<T> collection, IComparer<T> comparer) => new SortedSet<T>(collection, comparer);

      public IReadOnlyCollection<T> CreateImmutableCollection<T>() => ImmutableCollection.Of<T>();

      public IReadOnlyCollection<T> CreateImmutableCollection<T>(params T[] args) => ImmutableCollection.Of<T>(args);

      public IReadOnlyDictionary<K, V> CreateImmutableDictionary<K, V>() => ImmutableDictionary.Of<K, V>();

      public IReadOnlyDictionary<K, V> CreateImmutableDictionary<K, V>(K k1, V v1) => ImmutableDictionary.Of<K, V>(k1, v1);

      public IReadOnlyDictionary<K, V> CreateImmutableDictionary<K, V>(K k1, V v1, K k2, V v2) => ImmutableDictionary.Of<K, V>(k1, v1, k2, v2);

      public IReadOnlyDictionary<K, V> CreateImmutableDictionary<K, V>(K k1, V v1, K k2, V v2, K k3, V v3) => ImmutableDictionary.Of<K, V>(k1, v1, k2, v2, k3, v3);

      public IReadOnlyDictionary<K, V> CreateImmutableDictionary<K, V>(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) => ImmutableDictionary.Of<K, V>(k1, v1, k2, v2, k3, v3, k4, v4);

      public IReadOnlyDictionary<K, V> CreateImmutableDictionary<K, V>(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) => ImmutableDictionary.Of<K, V>(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5);

      public IReadOnlyDictionary<K, V> CreateImmutableDictionary<K, V>(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6) => ImmutableDictionary.Of<K, V>(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6);

      public IReadOnlyDictionary<K, V> CreateImmutableDictionary<K, V>(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7) => ImmutableDictionary.Of<K, V>(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7);

      public IReadOnlyDictionary<K, V> CreateImmutableDictionary<K, V>(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8) => ImmutableDictionary.Of<K, V>(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7, k8, v8);

      public IReadOnlyDictionary<K, V> CreateImmutableDictionary<K, V>(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9) => ImmutableDictionary.Of<K, V>(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7, k8, v8, k9, v9);

      public IReadOnlyDictionary<K, V> CreateImmutableDictionary<K, V>(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9, K k10, V v10) => ImmutableDictionary.Of<K, V>(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7, k8, v8, k9, v9, k10, v10);

      public IReadOnlySet<T> CreateImmutableSet<T>() => ImmutableSet.Of<T>();

      public IReadOnlySet<T> CreateImmutableSet<T>(params T[] args) => ImmutableSet.Of<T>(args);

      public IMultiValueDictionary<K, V> CreateMultiValueDictionary<K, V>() => new MultiValueDictionary<K, V>();

      public IMultiValueDictionary<K, V> CreateMultiValueDictionary<K, V>(IEqualityComparer<K> comparer) => new MultiValueDictionary<K, V>(comparer);

      public IMultiValueSortedDictionary<K, V> CreateMultiValueSortedDictionary<K, V>() => new MultiValueSortedDictionary<K, V>();

      public IMultiValueSortedDictionary<K, V> CreateMultiValueSortedDictionary<K, V>(IComparer<K> comparer) => new MultiValueSortedDictionary<K, V>(comparer);

      public IOrderedDictionary<K, V> CreateOrderedDictionary<K, V>() => new OrderedDictionary<K, V>();

      public IOrderedDictionary<K, V> CreateOrderedDictionary<K, V>(IEqualityComparer<K> comparer) => new OrderedDictionary<K, V>(comparer);

      public IOrderedMultiValueDictionary<K, V> CreateOrderedMultiValueDictionary<K, V>(ValuesSortState valuesSortState = ValuesSortState.Unsorted) => new OrderedMultiValueDictionary<K, V>(valuesSortState);

      public IQueue<T> CreateQueue<T>() => new Queue<T>();

      public IPriorityQueue<TValue, TPriority> CreatePriorityQueue<TValue, TPriority>(int capacity)
         where TPriority : IComparable<TPriority>, IEquatable<TPriority>
         where TValue : class, IPriorityQueueNode<TPriority> => new HeapPriorityQueue<TValue, TPriority>(capacity);

      public IConcurrentQueue<T> CreateConcurrentQueue<T>() => new ConcurrentQueue<T>();

      public IConcurrentQueue<T> CreateSingleConsumerSingleProducerConcurrentQueue<T>() where T : class => new SingleConsumerSingleProducerConcurrentQueue<T>();

      public IUniqueIdentificationSet CreateUniqueIdentificationSet(bool filled) => new UniqueIdentificationSet(filled);

      public IUniqueIdentificationSet CreateUniqueIdentificationSet(uint low, uint high) => new UniqueIdentificationSet(low, high);

      public IListDictionary<K, V> CreateListDictionary<K, V>() => new ListDictionary<K, V>();

      public IDictionary<K, V> CreateDictionary<K, V>() => new Dictionary<K, V>();

      public IDictionary<K, V> CreateDictionary<K, V>(IEqualityComparer<K> comparer) => new Dictionary<K, V>(comparer);

      public IDictionary<K, V> CreateSortedDictionary<K, V>() => new SortedDictionary<K, V>();

      public IDictionary<K, V> CreateSortedDictionary<K, V>(IComparer<K> comparer) => new SortedDictionary<K, V>(comparer);
   }
}<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Net;

namespace ItzWarty
{
    /*
     * Deprecated, needs housekeeping
    public static class XHR
    {
        private static WebClient webclient = new WebClient();
        public static string GetURL(string url)
        {
            lock (webclient)
            {
                return webclient.DownloadString(url);
            }
        } public static string GetString(string url) { return GetURL(url); }
    }
     */
}
<file_sep>﻿using System;

namespace ItzWarty
{
   public static class StaticRandom
   {
      private static readonly object s_lock = new object();
      private static readonly Random s_random = new Random(10);

      public static int Next(int exclusiveUpperBound)
      {
         lock (s_lock)
            return s_random.Next(exclusiveUpperBound);
      }

      public static int Next(int inclusiveLowerBound, int exclusiveUpperBound)
      {
         lock (s_lock)
            return s_random.Next(inclusiveLowerBound, exclusiveUpperBound);
      }

      public static float NextFloat(float exclusiveUpperBound)
      {
         lock (s_lock)
            return (float)NextDouble(exclusiveUpperBound);
      }

      public static float NextFloat(float inclusiveLowerBound, float exclusiveUpperBound)
      {
         lock (s_lock)
            return (float)NextDouble(inclusiveLowerBound, exclusiveUpperBound);
      }

      public static double NextDouble()
      {
         lock(s_lock)
            return s_random.NextDouble();
      }

      public static double NextDouble(double exclusiveUpperBound)
      {
         lock(s_lock)
            return s_random.NextDouble() * exclusiveUpperBound;
      }

      public static double NextDouble(double inclusiveLowerBound, double exclusiveUpperBound)
      {
         lock (s_lock)
            return inclusiveLowerBound + s_random.NextDouble() * (exclusiveUpperBound - inclusiveLowerBound);
      }

      public static Random NextRandom()
      {
         var buffer = new byte[4];
         lock(s_lock)
            s_random.NextBytes(buffer);
         return new Random(BitConverter.ToInt32(buffer, 0));
      }

      public static bool NextBoolean()
      {
         lock (s_lock)
            return s_random.Next() % 2 == 0;
      }
   }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ItzWarty;
using ItzWarty.Database;

namespace ItzWarty.Database
{
    public class wDBTable
    {
        string rootLocation = "";
        DatabaseClient dbc;
        public wDBTable(string name, DatabaseClient root)
        {
            rootLocation = root.currentFolderLocation;
            dbc = root.Clone();
            dbc.SelectDB("$" + name);
            dbc.SetCurrentDBAsRoot();
            dbc.ReturnToRoot();
        }
        public wDBRowCollection GetRows()
        {
            dbc.ReturnToRoot();
            string[] rowNums = dbc.ListDatabases();
            List<wDBTableRow> rows = new List<wDBTableRow>();
            for (int i = 0; i < rowNums.Length; i++)
            {
                string rowNum = rowNums[i];
                dbc.SelectDB(rowNum);
                rows.Add(
                    new wDBTableRow(dbc)
                );
                dbc.ReturnToRoot();
            }
            return new wDBRowCollection(rows);
        }

        public static void CreateTable(string tableName, DatabaseClient parentDB)
        {
            if (parentDB.ExistDB("$" + tableName) == DatabaseClient.DBResponse.Exists) return;
                parentDB.CreateDB("$" + tableName);

            DatabaseClient dbc = parentDB.Clone();
            dbc.SelectDB("$" + tableName);
            dbc.SetValue(".rowsAdded", "0");
        }
        public void AddRow(string[][] keyValues)
        {
            int rowsAdded = int.Parse(dbc.GetValue(".rowsAdded"));
            dbc.ReturnToRoot();
            dbc.CreateDB(rowsAdded.ToString());
            dbc.SelectDB(rowsAdded.ToString());
            wDBTableRow row = new wDBTableRow(dbc);
            for (int i = 0; i < keyValues.Length; i++)
                row[keyValues[i][0]] = keyValues[i][1];

            dbc.ReturnToRoot();
            dbc.SetValue(".rowsAdded", rowsAdded + 1);
        }
    }
    public class wDBTableRow
    {
        DatabaseClient dbc;
        public wDBTableRow(DatabaseClient dbc)
        {
            this.dbc = dbc.Clone();
        }
        public string this[string columnName]
        {
            get
            {
                return dbc.GetValue(columnName);
            }
            set
            {
                dbc.SetValue(columnName, value);
            }
        }
    }
}
<file_sep>﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;


namespace ItzWarty.Collections {
   public class ConcurrentQueue<T> : System.Collections.Concurrent.ConcurrentQueue<T>, IConcurrentQueue<T> {
      public ConcurrentQueue() { }
      public ConcurrentQueue(IEnumerable<T> collection) : base(collection) { }
   }
}
<file_sep>﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;

namespace ItzWarty
{
   public class GeneratorExitException : Exception {
      public GeneratorExitException() : base("The Generator is unable to produce more results.  Perhaps, there is nothing left to produce?") {}
   }

   public unsafe static class Util
   {
      /// <summary>
      /// Returns whether or not the given value is within (inclusive) the other two parameters
      /// </summary>
      [MethodImpl(MethodImplOptions.AggressiveInlining)]
      public static bool IsBetween(Double a, Double value, Double b)
      {
         return (a <= value && value <= b) || (b <= value && value <= a);
      }

      /// <summary>
      /// Generates a string in a stupid way...
      /// lol
      /// </summary>
      public static string GenerateString(int length)
      {
         StringBuilder temp = new StringBuilder();
         while(temp.Length < length)
            temp.Append(Guid.NewGuid().ToByteArray().ToHex());
         return temp.ToString().Substring(0, length);
      }

      /// <summary>
      /// Creates an array using the given function N times.
      /// The function takes a parameter i, from 0 to count, and returns T.
      /// </summary>
      public static T[] Generate<T>(int count, Func<int, T> generator)
      {
         if (count < 0)
            throw new ArgumentOutOfRangeException("count < 0");
         if (generator == null)
            throw new ArgumentNullException("generator");

         T[] result = new T[count];
         for (int i = 0; i < count; i++)
            result[i] = generator(i);
         return result;
      }

      /// <summary>
      /// Creates an array using the given function N times.
      /// The function takes a parameter a from 0 to countA and a parameter b, from 0 to countB, and returns T.
      /// </summary>
      public static T[] Generate<T>(int countA, int countB, Func<int, int, T> generator)
      {
         if (countA < 0)
            throw new ArgumentOutOfRangeException("countA < 0");
         if (countB < 0)
            throw new ArgumentOutOfRangeException("countB < 0");
         if (generator == null)
            throw new ArgumentNullException("generator");

         T[] result = new T[countA * countB];
         for (int a = 0; a < countA; a++)
            for (int b = 0; b < countB; b++)
               result[a * countB + b] = generator(a, b);
         return result;
      }

      /// <summary>
      /// Creates an array using the given function N times.
      /// </summary>
      public static T[] Generate<T>(int countA, int countB, int countC, Func<int, int, int, T> generator)
      {
         if (countA < 0)
            throw new ArgumentOutOfRangeException("countA < 0");
         if (countB < 0)
            throw new ArgumentOutOfRangeException("countB < 0");
         if (countC < 0)
            throw new ArgumentOutOfRangeException("countC < 0");
         if (generator == null)
            throw new ArgumentNullException("generator");

         T[] result = new T[countA * countB * countC];
         int i = 0;
         for (int a = 0; a < countA; a++)
            for (int b = 0; b < countB; b++)
               for (int c = 0; c < countC; c++)
               result[i++] = generator(a, b, c);
         return result;
      }

      /// <summary>
      /// Generates a given output.  Returns null if we are done after this loop.
      /// Throws GeneratorFinishedException if done.
      /// </summary>
      public delegate bool GeneratorDelegate<T>(int i, out T output);

      public static T[] Generate<T>(GeneratorDelegate<T> generator) where T : class
      {
         List<T> result = new List<T>();
         bool done = false;
         int i = 0;
         try
         {
            while(!done)
            {
               T output = null;
               done = generator(i++, out output);
               result.Add(output);
            }
         }
         catch(GeneratorExitException)
         {
         }
         catch(Exception e)
         {
            throw e;
         }
         return result.ToArray();
      }

      public static T[] Concat<T>(params object[] args) {
         var result = new List<T>();
         foreach (var element in args) {
            if (element is T)
               result.Add((T)element);
            else {
               foreach (var subElement in (IEnumerable<T>)element)
                  result.Add(subElement);
            }
         }
         return result.ToArray();
      }

      /// <summary>
      /// Creates a variable of the given value repeated [count] times.
      /// Note that this just copies reference if we have a Object.
      /// </summary>
      public static T[] Repeat<T>(int count, T t)
      {
         T[] result = new T[count];
         for(int i = 0; i < count; i++)
            result[i] = t;
         return result;
      }

      public static byte FindMaximum(byte[] bytes)
      {
         byte max = bytes[0];
         for(int i = 1; i < bytes.Length; i++)
         {
            if(max < bytes[i])
               max = bytes[i];
         }
         return max;
      }

      public static byte FindMinimum(byte[] bytes)
      {
         byte min = bytes[0];
         for(int i = 1; i < bytes.Length; i++)
         {
            if(min > bytes[i])
               min = bytes[i];
         }
         return min;
      }

      public static bool ByteArraysEqual(byte[] param1, byte[] param2) {
         return ByteArraysEqual(param1, 0, param1.Length, param2, 0, param2.Length);
      }

      public static bool ByteArraysEqual(byte[] a, int aOffset, byte[] b, int bOffset, int length) {
         return ByteArraysEqual(a, aOffset, length, b, bOffset, length);
      }

      public static bool ByteArraysEqual(byte[] a, int aOffset, int aLength, byte[] b, int bOffset, int bLength) {
         if (aOffset + aLength > a.Length) {
            throw new IndexOutOfRangeException("aOffset + aLength > a.Length");
         } else if (bOffset + bLength > b.Length) {
            throw new IndexOutOfRangeException("bOffset + bLength > b.Length");
         } else if (aOffset < 0) {
            throw new IndexOutOfRangeException("aOffset < 0");
         } else if (bOffset < 0) {
            throw new IndexOutOfRangeException("bOffset < 0");
         } else if (aLength < 0) {
            throw new IndexOutOfRangeException("aLength < 0");
         } else if (bLength < 0) {
            throw new IndexOutOfRangeException("bLength < 0");
         }

         if (aLength != bLength) {
            return false;
         } else if (a == b && aOffset == bOffset && aLength == bLength) {
            return true;
         }

         fixed (byte* pABase = a)
         fixed (byte* pBBase = b) {
            byte* pACurrent = pABase + aOffset, pBCurrent = pBBase + bOffset;
            var length = aLength;
            int longCount = length / 8;
            for (var i = 0; i < longCount; i++) {
               if (*(ulong*)pACurrent != *(ulong*)pBCurrent) {
                  return false;
               }
               pACurrent += 8;
               pBCurrent += 8;
            }
            if ((length & 4) != 0) {
               if (*(uint*)pACurrent != *(uint*)pBCurrent) {
                  return false;
               }
               pACurrent += 4;
               pBCurrent += 4;
            }
            if ((length & 2) != 0) {
               if (*(ushort*)pACurrent != *(ushort*)pBCurrent) {
                  return false;
               }
               pACurrent += 2;
               pBCurrent += 2;
            }
            if ((length & 1) != 0) {
               if (*pACurrent != *pBCurrent) {
                  return false;
               }
               pACurrent += 1;
               pBCurrent += 1;
            }
            return true;
         }
      }

      public static void SubscribeToEventOnce<T>(ref EventHandler<T> @event, EventHandler<T> callback)
         where T : EventArgs
      {
         var signal = new CountdownEvent(2);
         var accessLock = new object();
         var done = false;
         var handler = new EventHandler<T>(
            (o, e) =>
               {
                  //Ensure no concurrent invocations of the event, though I'm not sure if .net allows for that
                  lock(accessLock)
                  {
                     //Check if we're done calling the event once.  If so, we don't want to invoke twice.
                     if(!done)
                     {
                        //We're now done.  Set the flag so we aren't called again.
                        done = true;

                        //Invoke the user's code for the one-time event subscription
                        callback(o, e);

                        //Signal that the user's code is done running, so the SubscribeToEventOnce caller
                        //thread can be unblocked.
                        signal.Signal();
                     }
                  }
               }
            );
         //Subscribe to the event which we are trying to listen to once
         @event += handler;

         //Signal the countdown event once to tell threads that we're done.  In a case like this where we're
         //really only running 1 thing at a time, it's not important.  If we had more than one thread, and were
         //trying to synchronize all of them, this would be more helpful.  For now, this allows us to
         //wait until the user code has been invoked before we allow this method to return.
         signal.Signal();

         //Wait for the user's callback event to be invoked
         signal.Wait();

         //Unsubscribe to the event.
         @event -= handler;
      }

      public class SingleSubscription
      {
         internal CountdownEvent m_countdown = new CountdownEvent(1);

         internal void Signal()
         {
            m_countdown.Signal();
         }

         public void Wait()
         {
            m_countdown.Wait();
         }
      }

      public static SingleSubscription SubscribeToEventOnceAsync<T>(Action<EventHandler<T>> subscribe,
                                                                    Action<EventHandler<T>> unsubscribe,
                                                                    EventHandler<T> callback)
         where T : EventArgs
      {
         var result = new SingleSubscription();
         var accessLock = new object();
         var done = false;
         EventHandler<T> handler = null;
         handler = new EventHandler<T>(
            (o, e) =>
               {
                  //Ensure no concurrent invocations of the event, though I'm not sure if .net allows for that
                  lock(accessLock)
                  {
                     //Check if we're done calling the event once.  If so, we don't want to invoke twice.
                     if(!done)
                     {
                        //We're now done.  Set the flag so we aren't called again.
                        done = true;

                        //Invoke the user's code for the one-time event subscription
                        callback(o, e);

                        //Signal that the user's code is done running, so the SubscribeToEventOnce caller
                        //thread can be unblocked.
                        result.Signal();

                        //Yay closures
                        unsubscribe(handler);
                     }
                  }
               }
            );
         //Subscribe to the event which we are trying to listen to once
         subscribe(handler);
         return result;
      }

      /// <SUMMARY>
      /// FROM: http://blogs.msdn.com/b/toub/archive/2006/05/05/590814.aspx
      /// Computes the Levenshtein Edit Distance between two enumerables.</SUMMARY>
      /// <TYPEPARAM name="T">The type of the items in the enumerables.</TYPEPARAM>
      /// <PARAM name="x">The first enumerable.</PARAM>
      /// <PARAM name="y">The second enumerable.</PARAM>
      /// <RETURNS>The edit distance.</RETURNS>
      public static int EditDistance<T>(IEnumerable<T> x, IEnumerable<T> y)
         where T : IEquatable<T>
      {
         // Validate parameters
         if(x == null) throw new ArgumentNullException("x");
         if(y == null) throw new ArgumentNullException("y");

         // Convert the parameters into IList instances
         // in order to obtain indexing capabilities
         IList<T> first = x as IList<T> ?? new List<T>(x);
         IList<T> second = y as IList<T> ?? new List<T>(y);

         // Get the length of both.  If either is 0, return
         // the length of the other, since that number of insertions
         // would be required.
         int n = first.Count, m = second.Count;
         if(n == 0) return m;
         if(m == 0) return n;

         // Rather than maintain an entire matrix (which would require O(n*m) space),
         // just store the current row and the next row, each of which has a length m+1,
         // so just O(m) space. Initialize the current row.
         int curRow = 0, nextRow = 1;
         int[][] rows = new int[][] {new int[m + 1], new int[m + 1]};
         for(int j = 0; j <= m; ++j) rows[curRow][j] = j;

         // For each virtual row (since we only have physical storage for two)
         for(int i = 1; i <= n; ++i)
         {
            // Fill in the values in the row
            rows[nextRow][0] = i;
            for(int j = 1; j <= m; ++j)
            {
               int dist1 = rows[curRow][j] + 1;
               int dist2 = rows[nextRow][j - 1] + 1;
               int dist3 = rows[curRow][j - 1] +
                           (first[i - 1].Equals(second[j - 1]) ? 0 : 1);

               rows[nextRow][j] = Math.Min(dist1, Math.Min(dist2, dist3));
            }

            // Swap the current and next rows
            if(curRow == 0)
            {
               curRow = 1;
               nextRow = 0;
            }
            else
            {
               curRow = 0;
               nextRow = 1;
            }
         }

         // Return the computed edit distance
         return rows[curRow][m];
      }

      /// <summary>
      /// Takes fileName like annieSquare.dds, AnnieSquare.dds, annie_square_dds, ANNIE_SQUARE.dds and 
      /// outputs  an array such as ["annie", "square", "dds"].  Non-alphanumeric values are deemed
      /// as delimiters as well.
      /// 
      /// Delimiters:
      ///    non-alphanumerics
      ///    In the middle of two (and only two) uppercase characters that are followed by lowercase characters
      ///       Ie: "ACar" => ["A", "Car"]
      ///    On switch from uppercase string of 3+ to lowercase
      ///       Ie: "MANmode" => ["MAN", "mode"]
      ///    On switch from lowercase string to uppercase
      ///       Ie: "ExampleText" => ["Example", "Text"]
      ///    On switch from number to alphabet or vice versa
      ///       Ie: "IHave10Apples" => ["I", "Have", "10", "Apples"]
      ///    On reaching a non-alphanumeric value
      ///       Ie; "RADS_USER_Kernel.exe" => ["RADS", "USER", "Kernel", "exe"]
      /// </summary>
      /// <param name="name"></param>
      /// <returns></returns>
      public static IEnumerable<string> ExtractFileNameTokens(string fileName)
      {
         StringBuilder sb = new StringBuilder();

         // We start as if we were just at position -1
         CharType lastlastCharType = CharType.Invalid;
         CharType lastCharType = CharType.Invalid;
         CharType charType = CharType.Invalid;
         CharType nextCharType = fileName.Length >= 1 ? GetCharType(fileName[0]) : CharType.Invalid;
         for (int i = 0; i < fileName.Length; i++)
         {
            lastlastCharType = lastCharType;
            lastCharType = charType;
            charType = nextCharType;
            nextCharType = fileName.Length > i + 1 ? GetCharType(fileName[i + 1]) : CharType.Invalid;
            char c = fileName[i];
            //Console.WriteLine("Got char " + c + " current sb " + sb.ToString());

            if (sb.Length == 0)
            {
               if (charType != CharType.Invalid)
                  sb.Append(c);
            }
            else
            {
               // Check delimit condition: In the middle of two (and only two) uppercase characters that are followed by lowercase characters
               if (lastlastCharType != CharType.Uppercase && //e, current string builder = "A"
                   lastCharType == CharType.Uppercase &&     //A
                   charType == CharType.Uppercase &&         //C
                   nextCharType == CharType.Lowercase)       //a
               {
                  yield return sb.ToString();
                  sb.Clear();
                  sb.Append(c);
               }
               else // Check delimit condition: On switch from uppercase string of 3+ to lowercase
               if (lastlastCharType == CharType.Uppercase && //M, current string builder = "A"
                   lastCharType == CharType.Uppercase &&     //A
                   charType == CharType.Uppercase &&         //N
                   nextCharType == CharType.Lowercase)       //m
               {
                  sb.Append(c);
                  yield return sb.ToString();
                  sb.Clear();
               }
               else // Check delimit condition: On switch from lowercase string to uppercase
               if (charType == CharType.Lowercase &&         //n
                   nextCharType == CharType.Uppercase)       //M
               {
                  sb.Append(c);
                  yield return sb.ToString();
                  sb.Clear();
               }
               else // Check delimit condition: On switch from number to alphabet or vice versa
               if ((charType == CharType.Number && (nextCharType == CharType.Lowercase || nextCharType == CharType.Uppercase)) ||
                  (nextCharType == CharType.Number && (charType == CharType.Lowercase || charType == CharType.Uppercase)))
               {
                  sb.Append(c);
                  yield return sb.ToString();
                  sb.Clear();
               }
               else // Check delimit condition: On reaching a non-alphanumeric value
               if (charType == CharType.Invalid)
               {
                  if (sb.Length > 0)
                     yield return sb.ToString();
                  sb.Clear();
               }
               else // Check delimit condition: On reaching a non-alphanumeric value
               if(nextCharType == CharType.Invalid)
               {
                  sb.Append(c);
                  yield return sb.ToString();
                  sb.Clear();
               }
               else // Didn't get delimited!
               {
                  // Console.WriteLine("Appending " + c + " " + lastlastCharType + " " + lastCharType + " " + charType + " " + nextCharType);
                  sb.Append(c);
               }
            }
         } // for
         if (sb.Length > 0)
            yield return sb.ToString();
         yield break;
      }

      public static string ToTitleCase(this string s) {
         return ExtractFileNameTokens(s).Select(token => char.ToUpper(token[0]) + token.Substring(1)).Join(" ");
      }

      private static CharType GetCharType(char c)
      {
         if ('a' <= c && c <= 'z')
            return CharType.Lowercase;
         else if ('A' <= c && c <= 'Z')
            return CharType.Uppercase;
         else if ('0' <= c && c <= '9')
            return CharType.Number;
         else
            return CharType.Invalid;
      }

      private enum CharType { Invalid, Lowercase, Uppercase, Number }

      /// <summary>
      /// Formats a name from UpperCamelCase to Upper Camel Case
      /// </summary>
      /// <param name="name"></param>
      /// <returns></returns>
      public static string FormatName(string name)
      {
         name = name + "   ";
         name = name[0].ToString().ToUpper() + name.Substring(1);
         //http://stackoverflow.com/questions/4511087/regex-convert-camel-case-to-all-caps-with-underscores
         string _RESULT_VAL = Regex.Replace(name, @"(?x)( [A-Z][a-z,0-9]+ | [A-Z]+(?![a-z]) )", "_$0");
         //Console.WriteLine("* " + _RESULT_VAL);
         string RESULT_VAL = _RESULT_VAL.Substring(1);
         //Console.WriteLine("# " + RESULT_VAL);

         var result = from part in RESULT_VAL.Split(new char[]{ '_', ' '})
                      let partPad = part + "  "
                      let firstChar = part.Length > 3 ? partPad[0].ToString().ToUpper() : partPad[0].ToString().ToLower()
                      select (firstChar + partPad.Substring(1).ToLower()).Trim();

         string resultString = string.Join(" ", result.Where((s)=> !string.IsNullOrWhiteSpace(s)) .ToArray()).Trim();
         
         //Make the first letter of the first term capitalized
         resultString = resultString[0].ToString().ToUpper() + resultString.Substring(1);

         //Replace multiple space occurrences
         string realResult = string.Join(" ", resultString.QASS(' '));
         //Console.WriteLine("> " + realResult);
         return realResult;
      }

      public static string RemoveNonalphanumeric(this string s)
      {
         char[] arr = s.ToCharArray();

         arr = Array.FindAll<char>(arr, (c => (char.IsLetterOrDigit(c) || char.IsWhiteSpace(c) || c == '-')));
         return new string(arr);
      }

      /// <summary>
      /// http://stackoverflow.com/questions/221925/creating-a-byte-array-from-a-stream
      /// </summary>
      /// <param name="input"></param>
      /// <returns></returns>
      public static byte[] ReadFully(Stream input)
      {
         byte[] buffer = new byte[16 * 1024];
         using (MemoryStream ms = new MemoryStream())
         {
            int read;
            while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
            {
               ms.Write(buffer, 0, read);
            }
            return ms.ToArray();
         }
      }

      /// <summary>
      /// Returns an array containing numbers spaced between 0 and the given maximum value
      /// </summary>
      /// <param name="maximum">
      /// The number which the result approaches from 0 to its last index
      /// </param>
      /// <param name="numElements">
      /// The number of elements in the result (includes 0 and maximum)
      /// </param>
      /// <param name="uniformityFactor">
      /// Greater than 0
      /// </param>
      /// <param name="getRandom">Returns a value in [0.0, 1.0)</param>
      /// <returns></returns>
      public static double[] GenerateRandomCumulativeDistribution(
         double maximum, 
         int numElements, 
         double uniformityFactor,
         Func<double> getRandom)
      {
         var weights = new double[numElements];
         weights[0] = 0.0; // actually implicit, but here for readability
         for (int i = 1; i < weights.Length; i++)
            weights[i] = getRandom() + uniformityFactor;

         // :: every element equals the sum of the elements before it
         for (int i = 1; i < weights.Length; i++)
            weights[i] += weights[i - 1];

         // :: normalize all elements to maximum value keysRemaining
         for (int i = 0; i <= weights.Length - 2; i++)
            weights[i] = maximum * weights[i] / weights[weights.Length - 1];

         weights[weights.Length - 1] = maximum;
         
         return weights;
      }

      public static double[] GenerateRandomCumulativeDistribution(
         double maximum,
         int numElements,
         double uniformityFactor)
      {
         return GenerateRandomCumulativeDistribution(
            maximum, 
            numElements, 
            uniformityFactor, 
            StaticRandom.NextDouble
         );
      }

      /// <summary>
      /// Gets the attribute of Enum value
      /// </summary>
      /// <typeparam name="TAttribute"></typeparam>
      /// <param name="enumValue"></param>
      /// <returns></returns>
      public static TAttribute GetAttributeOrNull<TAttribute>(this Enum enumValue)
         where TAttribute : Attribute {
         var enumType = enumValue.GetType();
         var memberInfo = enumType.GetTypeInfo().DeclaredMembers.First(member => member.Name.Equals(enumValue.ToString()));
         var attributes = memberInfo.GetCustomAttributes(typeof(TAttribute), false);
         return (TAttribute)attributes.FirstOrDefault();
      }

      public static TAttribute GetAttributeOrNull<TAttribute>(this object instance)
         where TAttribute : Attribute {
         var instanceType = instance as Type ?? instance.GetType();
         return GetAttributeOrNull<TAttribute>(instanceType);
      }

      public static TAttribute GetAttributeOrNull<TAttribute>(this Type type)
         where TAttribute : Attribute {
         var typeInfo = type.GetTypeInfo();
         return GetAttributeOrNull<TAttribute>(typeInfo);
      }


      public static TAttribute GetAttributeOrNull<TAttribute>(this TypeInfo typeInfo)
         where TAttribute : Attribute {
         var attributes = typeInfo.GetCustomAttributes(typeof(TAttribute), false);
         return (TAttribute)attributes.FirstOrDefault();
      }

      public static bool IsThrown<TException>(Action action) where TException : Exception {
         try {
            action();
            return false;
         } catch (TException) {
            return true;
         }
      }

      public static TValue KeepExisting<TKey, TValue>(TKey key, TValue value) {
         return value;
      }

      public static long GetUnixTimeMilliseconds() {
         return (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
      }

      public static string NextToken(string input, out string token) {
         input = input.Trim();
         var firstSpaceIndex = input.IndexOf(' ');
         string remaining;
         if (firstSpaceIndex < 0) {
            token = input;
            remaining = "";
         } else {
            token = input.Substring(0, firstSpaceIndex);
            remaining = input.Substring(firstSpaceIndex + 1);
         }
         return remaining;
      }
   }
}
<file_sep>﻿using Dargon.Ryu;
using ItzWarty.Collections;
using ItzWarty.Pooling;
using NMockito;
using Xunit;

namespace ItzWarty {
   public class RyuPackageTests : NMockitoInstance {
      [Fact]
      public void Run() {
         var ryu = new RyuFactory().Create();
         ryu.Touch<ItzWartyCommonsRyuPackage>();
         ryu.Setup();
         AssertTrue(ryu.Get<ICollectionFactory>() is CollectionFactory);
         AssertTrue(ryu.Get<ObjectPoolFactory>() is DefaultObjectPoolFactory);
      }
   }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dargon.Ryu;
using ItzWarty.Collections;
using ItzWarty.Pooling;

namespace ItzWarty {
   public class ItzWartyCommonsRyuPackage : RyuPackageV1 {
      public ItzWartyCommonsRyuPackage() {
         Singleton<ICollectionFactory, CollectionFactory>();
         Singleton<ObjectPoolFactory, DefaultObjectPoolFactory>();
      }
   }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ItzWarty.Database
{
    public class DatabaseClient
    {
        /// <summary>
        /// Root is the root database [the location of the database folder]
        /// </summary>
        public string root;

        /// <summary>
        /// Folderstack is pushed into whenever you enter, popped when you go up, and cleared when you exit...
        /// </summary>
        public List<string> folderStack = new List<string>();

        /// <summary>
        /// When we jump to root, sometimes we want to define our root to actually be a subdatabase of our root database, so we push to here
        /// When we reset, we will copy all contents from here to the folderstack again.
        /// </summary>
        public List<string> defaultFolderStack = new List<string>();

        public string currentDBPath
        {
            get
            {
                if (folderStack.Count == 0)
                    return dbName;
                else
                {
                    string final = dbName;
                    for (int i = 0; i < folderStack.Count; i++) final += "." + folderStack[i];
                    return final;
                }
            }
        }
        public string currentFolderLocation
        {
            get
            {
                string final = root + "\\";
                for (int i = 0; i < folderStack.Count; i++) final += "\\" + folderStack[i];
                return final;
            }
        }
        public string dbName;
        /// <summary>
        /// Sets the DB Root, if it doesnt exist, create the DB Root
        /// </summary>
        /// <param name="DBNAME"></param>
        public DatabaseClient(string DBNAME)
        {
            this.root = Directory.GetCurrentDirectory() + "\\" + DBNAME;
            this.dbName = DBNAME;
            this.defaultFolderStack.Clear(); //We want to be at root, so we shouldn't be inside any subfolder...
            this.ReturnToRoot();
            if (!Directory.Exists(root))
            {
                Directory.CreateDirectory(root);
                Console.WriteLine("Database \"" + dbName + "\" created");
            }
            ReturnToRoot();
        }

        public void ReturnToRoot()
        {
            this.folderStack.Clear();
            this.folderStack = new List<string>(this.defaultFolderStack.ToArray());
        }
        public void ReturnToSuperParent()
        {
            this.folderStack.Clear();
            this.defaultFolderStack.Clear();
        }
        public enum DBResponse
        {
            InvalidName,
            Exists,
            doesNotExist,
            Selected,
            Created,
            moved,
            Deleted
        }
        public string[] GetExistingDBNames()
        {
            string[] toreturn = Directory.GetDirectories(currentFolderLocation);
            string dirToReplaceToNothing = "";
            ReturnToRoot();
            SelectDB("Channels");
            dirToReplaceToNothing = currentFolderLocation;
            for (int i = 0; i < toreturn.Length; i++)
                toreturn[i] = toreturn[i].Replace(dirToReplaceToNothing, "");
            return toreturn;
        }
        public System.Collections.ArrayList dirList = new System.Collections.ArrayList();
        public string[] OutputListofDBs()
        {
            dirList.Clear();
            //Console.WriteLine(currentFolderLocation);
            foreach (string dirName in Directory.GetDirectories(currentFolderLocation))
            {
                SubOutputListofDBs(dirName);
            }
            string[] final = new string[dirList.Count];
            for (int i = 0; i < dirList.Count; i++)
            {
                //Console.WriteLine((string)dirList[i]);
                final[i] = ((string)(dirList[i]));
            }
            return final;
        }
        public void SubOutputListofDBs(string curDir)
        {
            //Console.WriteLine(curDir.Replace(currentFolderLocation, ""));
            dirList.Add(curDir.Replace(currentFolderLocation, ""));
            foreach (string dirName in Directory.GetDirectories(curDir))
            {
                SubOutputListofDBs(dirName);
            }
        }
        public bool IsWinNameOkay(string val)
        {
            //NTFS does not allow / ? < > \ : * |
            if (val.Replace("/", "!") != val) return false;
            if (val.Replace("?", "!") != val) return false;
            if (val.Replace("<", "!") != val) return false;
            if (val.Replace(">", "!") != val) return false;
            if (val.Replace("\\", "!") != val) return false;
            if (val.Replace(":", "!") != val) return false;
            if (val.Replace("*", "!") != val) return false;
            if (val.Replace("|", "!") != val) return false;
            //FAT doesnt allow the above and ^
            if (val.Replace("^", "!") != val) return false;
            //illegal folder names under windows
            if (val.ToLowerInvariant() == "com1") return false;
            if (val.ToLowerInvariant() == "com2") return false;
            if (val.ToLowerInvariant() == "com3") return false;
            if (val.ToLowerInvariant() == "com4") return false;
            if (val.ToLowerInvariant() == "com5") return false;
            if (val.ToLowerInvariant() == "com6") return false;
            if (val.ToLowerInvariant() == "com7") return false;
            if (val.ToLowerInvariant() == "com8") return false;
            if (val.ToLowerInvariant() == "com9") return false;
            if (val.ToLowerInvariant() == "lpt1") return false;
            if (val.ToLowerInvariant() == "lpt2") return false;
            if (val.ToLowerInvariant() == "lpt3") return false;
            if (val.ToLowerInvariant() == "lpt4") return false;
            if (val.ToLowerInvariant() == "lpt5") return false;
            if (val.ToLowerInvariant() == "lpt6") return false;
            if (val.ToLowerInvariant() == "lpt7") return false;
            if (val.ToLowerInvariant() == "lpt8") return false;
            if (val.ToLowerInvariant() == "lpt9") return false;
            if (val.ToLowerInvariant() == "con") return false;
            if (val.ToLowerInvariant() == "nul") return false;
            if (val.ToLowerInvariant() == "prn") return false;

            //YOu cant have a period or a space at the end of a file name
            char[] a_tDB = val.ToCharArray();
            if (a_tDB[a_tDB.Length - 1] == ' ') return false;
            if (a_tDB[a_tDB.Length - 1] == '.') return false;
            //we shold be fine o_O
            return true;
        }

        #region dbAction
        /// <summary>
        /// 
        /// </summary>
        /// <param name="oldDBNAME"></param>
        /// <param name="newDBNAME"></param>
        /// <returns>Invalid Name, exists, does not exist, moved</returns>
        public DBResponse RenameDB(string oldDBNAME, string newDBNAME)
        {
            if (!IsWinNameOkay(newDBNAME))
                return DBResponse.InvalidName;
            if (!IsWinNameOkay(oldDBNAME))
                return DBResponse.InvalidName;
            if (!Directory.Exists(currentFolderLocation+"\\"+oldDBNAME)) return DBResponse.doesNotExist;
            if (Directory.Exists(currentFolderLocation + "\\" + newDBNAME)) return DBResponse.Exists;
            Directory.Move(currentFolderLocation + "\\" + oldDBNAME, currentFolderLocation + "\\" + newDBNAME);
            return DBResponse.moved;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="targetDB"></param>
        /// <returns>DBResponses: Exists, doesNotExist</returns>
        public DBResponse ExistDB(string targetDB)
        {
            if (Directory.Exists(currentFolderLocation + "\\"+targetDB)) return DBResponse.Exists;
            return DBResponse.doesNotExist;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="targetDB"></param>
        /// <returns>Exists, Created, InvalidName</returns>
        public DBResponse CreateDB(string targetDB)
        {
            if (ExistDB(targetDB) == DBResponse.Exists) return DBResponse.Exists;
            if (!IsWinNameOkay(targetDB)) return DBResponse.InvalidName;
            //create the DB
            Directory.CreateDirectory(currentFolderLocation + "\\" + targetDB.Trim());
            //dummy file for zip archives
            //File.WriteAllLines(currentFolderLocation + "\\" + targetDB.Trim() + "\\Dummy", new string[] { "dummy" });
            Console.WriteLine("Database \"" + currentDBPath + "." + targetDB + "\" created");
            return DBResponse.Created;
        }
        //DB = folder
        //Value = file
        public DBResponse SelectDB(string targetDB)
        {
            return SelectDB(targetDB, false);
        }

        public DatabaseClient SelectDB2(string targetDB)
        {
            DatabaseClient result = this.Clone();
            DBResponse response = result.SelectDB(targetDB);
            if (response == DBResponse.doesNotExist) return null;
            else if (response == DBResponse.Selected)
                return result;
            else
                return null;
        }

        public DatabaseClient SelectDB2(string targetDB, bool autocreate)
        {
            DatabaseClient result = this.Clone();
            DBResponse response = result.SelectDB(targetDB, autocreate);
            if (response == DBResponse.doesNotExist) return null;
            else if (response == DBResponse.Selected)
                return result;
            else
                return null;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="targetDB"></param>
        /// <returns>DBResponses: Selected, doesNotExist</returns>
        public DBResponse SelectDB(string targetDB, bool autocreate)
        {
            if (autocreate)
            {
                if (ExistDB(targetDB) == DBResponse.doesNotExist)
                    CreateDB(targetDB);
            }
            if (Directory.Exists(currentFolderLocation+"\\"+ targetDB))
            {
                folderStack.Add(targetDB);
                return DBResponse.Selected;
            }
            else
            {
                Console.WriteLine(currentFolderLocation +"\\"+ targetDB + "  Doesntexist");
                return DBResponse.doesNotExist;
            }
        }
        public DBResponse DeleteDB(string targetDB)
        {
            if (ExistDB(targetDB) == DBResponse.doesNotExist) return DBResponse.doesNotExist;
            if (!IsWinNameOkay(targetDB)) return DBResponse.InvalidName;
            Directory.Delete(currentFolderLocation + "\\" + targetDB.Trim());
            return DBResponse.Deleted;
        }
        #endregion
        #region valueAction
        public bool ValueExists(string valueName)
        {
            string loc = currentFolderLocation + "\\" + valueName;
            if (!File.Exists(loc)) return false;
            return true;
        }
        public string GetValue(string valueName)
        {
            string loc = currentFolderLocation + "\\" + valueName;
            if (!File.Exists(loc)) throw new Exception("Value " + valueName + " does NOT exist in" + loc);
            return File.ReadAllText(loc);
        }

        /// <summary>
        /// Stores the value as the (string)content 
        /// </summary>
        /// <param name="valueName"></param>
        /// <param name="valueContent"></param>
        public void SetValue(string valueName, object valueContent)
        {
            if (!IsWinNameOkay(valueName)) throw new Exception(valueName + "is an INVALID windows name at " + currentFolderLocation);
            string loc = currentFolderLocation + "\\" + valueName;
            if (!File.Exists(loc))
                File.Delete(loc);
            //start anew
            FileStream myFS = File.Create(loc);
            byte[] myBytes = Encoding.ASCII.GetBytes(valueContent.ToString());
            myFS.Write(myBytes, 0, myBytes.Length);
            myFS.Close();

            Console.WriteLine(currentDBPath + "." + valueName + " now set to " + valueContent);
        }

        public bool GetBool(string valueName)
        {
            return GetValue(valueName) == "1";
        }
        public void SetBool(string valueName, bool value)
        {
            SetValue(valueName, (value) ? "1" : "0");
        }

        public int GetInt(string intName)
        {
            return int.Parse(GetValue(intName));
        }
        public void SetInt(string intName, int value)
        {
            SetValue(intName, value.ToString());
        }
        #endregion
        public bool FileExists(string fileName)
        {
            string loc = currentFolderLocation + "\\" + fileName;
            return File.Exists(loc);
        }
        public void WriteFile(string fileName, byte[] data)
        {
            string loc = currentFolderLocation + "\\" + fileName;
            FileStream fs = File.Open(loc, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); //While we are writing, you can't do anything with it, sorry.
            if (File.Exists(loc))
            {
                File.Delete(loc);
            }
        }
        public DatabaseClient Clone()
        {
            DatabaseClient copy = new DatabaseClient(this.dbName);
            copy.defaultFolderStack = new List<string>(this.defaultFolderStack.ToArray());
            copy.folderStack = new List<string>(this.folderStack.ToArray());
            return copy;
        }

        public void SetCurrentDBAsRoot()
        {
            defaultFolderStack.Clear();
            for (int i = 0; i < folderStack.Count; i++) defaultFolderStack.Add(folderStack[i]);
        }

        public void CreateTable(string tableName, string[] columns)
        {
            wDBTable.CreateTable(tableName, this);
        }
        public wDBTable GetTable(string name)
        {
            return new wDBTable(name, this);
        }
        public string[] ListDatabases()
        {
            string[] childDirs = Directory.GetDirectories(currentFolderLocation);
            for (int i = 0; i < childDirs.Length; i++)
                childDirs[i] = childDirs[i].Replace(currentFolderLocation, "");
            return childDirs;
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace ItzWarty
{
   public static partial class Extensions
   {
      [MethodImpl(MethodImplOptions.AggressiveInlining)]
      public static bool WithinII(this int value, int lower, int upper)
      {
         return value >= lower && value <= upper;
      }

      [MethodImpl(MethodImplOptions.AggressiveInlining)]
      public static bool WithinIE(this int value, int lower, int upper)
      {
         return value >= lower && value < upper;
      }
   }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ItzWarty.Collections {
   public interface ICollectionFactory {
      IConcurrentDictionary<K, V> CreateConcurrentDictionary<K, V>();
      IConcurrentDictionary<K, V> CreateConcurrentDictionary<K, V>(IEnumerable<KeyValuePair<K, V>> collection);
      IConcurrentDictionary<K, V> CreateConcurrentDictionary<K, V>(IEqualityComparer<K> comparer);
      IConcurrentDictionary<K, V> CreateConcurrentDictionary<K, V>(IEnumerable<KeyValuePair<K, V>> collection, IEqualityComparer<K> comparer);

      IConcurrentSet<T> CreateConcurrentSet<T>();
      IConcurrentSet<T> CreateConcurrentSet<T>(IEnumerable<T> collection);
      IConcurrentSet<T> CreateConcurrentSet<T>(IEqualityComparer<T> comparer);
      IConcurrentSet<T> CreateConcurrentSet<T>(IEnumerable<T> collection, IEqualityComparer<T> comparer);

      IConcurrentBag<T> CreateConcurrentBag<T>();
      IConcurrentBag<T> CreateConcurrentBag<T>(IEnumerable<T> collection);

      IHashSet<T> CreateHashSet<T>();
      IHashSet<T> CreateHashSet<T>(IEnumerable<T> collection);
      IHashSet<T> CreateHashSet<T>(IEqualityComparer<T> comparer);
      IHashSet<T> CreateHashSet<T>(IEnumerable<T> collection, IEqualityComparer<T> comparer);

      ISortedSet<T> CreateSortedSet<T>();
      ISortedSet<T> CreateSortedSet<T>(IEnumerable<T> collection);
      ISortedSet<T> CreateSortedSet<T>(IComparer<T> comparer);
      ISortedSet<T> CreateSortedSet<T>(IEnumerable<T> collection, IComparer<T> comparer);

      IReadOnlyCollection<T> CreateImmutableCollection<T>();
      IReadOnlyCollection<T> CreateImmutableCollection<T>(params T[] args);

      IReadOnlyDictionary<K, V> CreateImmutableDictionary<K, V>();
      IReadOnlyDictionary<K, V> CreateImmutableDictionary<K, V>(K k1, V v1);
      IReadOnlyDictionary<K, V> CreateImmutableDictionary<K, V>(K k1, V v1, K k2, V v2);
      IReadOnlyDictionary<K, V> CreateImmutableDictionary<K, V>(K k1, V v1, K k2, V v2, K k3, V v3);
      IReadOnlyDictionary<K, V> CreateImmutableDictionary<K, V>(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4);
      IReadOnlyDictionary<K, V> CreateImmutableDictionary<K, V>(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5);
      IReadOnlyDictionary<K, V> CreateImmutableDictionary<K, V>(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6);
      IReadOnlyDictionary<K, V> CreateImmutableDictionary<K, V>(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7);
      IReadOnlyDictionary<K, V> CreateImmutableDictionary<K, V>(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8);
      IReadOnlyDictionary<K, V> CreateImmutableDictionary<K, V>(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9);
      IReadOnlyDictionary<K, V> CreateImmutableDictionary<K, V>(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9, K k10, V v10);

      IReadOnlySet<T> CreateImmutableSet<T>();
      IReadOnlySet<T> CreateImmutableSet<T>(params T[] args);

      IMultiValueDictionary<K, V> CreateMultiValueDictionary<K, V>();
      IMultiValueDictionary<K, V> CreateMultiValueDictionary<K, V>(IEqualityComparer<K> comparer);

      IMultiValueSortedDictionary<K, V> CreateMultiValueSortedDictionary<K, V>();
      IMultiValueSortedDictionary<K, V> CreateMultiValueSortedDictionary<K, V>(IComparer<K> comparer);

      IOrderedDictionary<K, V> CreateOrderedDictionary<K, V>();
      IOrderedDictionary<K, V> CreateOrderedDictionary<K, V>(IEqualityComparer<K> comparer);
         
      IOrderedMultiValueDictionary<K, V> CreateOrderedMultiValueDictionary<K, V>(ValuesSortState valuesSortState = ValuesSortState.Unsorted);

      IQueue<T> CreateQueue<T>();
      IPriorityQueue<TValue, TPriority> CreatePriorityQueue<TValue, TPriority>(int capacity)
         where TPriority : IComparable<TPriority>, IEquatable<TPriority>
         where TValue : class, IPriorityQueueNode<TPriority>;
      IConcurrentQueue<T> CreateConcurrentQueue<T>();
      IConcurrentQueue<T> CreateSingleConsumerSingleProducerConcurrentQueue<T>() where T : class;

      IUniqueIdentificationSet CreateUniqueIdentificationSet(bool filled);
      IUniqueIdentificationSet CreateUniqueIdentificationSet(uint low, uint high);

      IListDictionary<K, V> CreateListDictionary<K, V>();

      IDictionary<K, V> CreateDictionary<K, V>();
      IDictionary<K, V> CreateDictionary<K, V>(IEqualityComparer<K> comparer);

      IDictionary<K, V> CreateSortedDictionary<K, V>();
      IDictionary<K, V> CreateSortedDictionary<K, V>(IComparer<K> comparer);
   }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ItzWarty.Database
{
    public enum ComparisonOperator
    {
        Is,
        IsNot,
        LessThan,
        LessThanEqualTo,
        GreaterThan,
        GreaterThanEqualTo,
        StartsWith
    }
    public class wDBRowCollection
    {
        public List<wDBTableRow> rows = new List<wDBTableRow>();
        public wDBRowCollection(){}
        public wDBRowCollection(List<wDBTableRow> rows)
        {
            this.rows = rows;
        }
        public wDBRowCollection Where(string what, ComparisonOperator op, object operand)
        {
            string operandTwo = "";
            if (operand is int)
                operandTwo = ((int)operand).ToString();
            else if (operand is string)
                operandTwo = (string)operand;
            else if (operand is bool)
                operandTwo = ((bool)operand) ? "1" : "0";

            wDBRowCollection newCollection = new wDBRowCollection();
            for (int i = 0; i < this.rows.Count; i++)
            {
                string operandOne = this.rows[i][what];
                double opOne = 0, opTwo = 0;
                double.TryParse(operandOne, out opOne);
                double.TryParse(operandTwo, out opTwo);
                switch(op)
                {
                    case ComparisonOperator.Is:
                        if(operandOne == operandTwo)
                            newCollection.rows.Add(this.rows[i]);
                        break;
                    case ComparisonOperator.IsNot:
                        if(operandOne != operandTwo)
                            newCollection.rows.Add(this.rows[i]);
                        break;
                    case ComparisonOperator.LessThan:
                        if(opOne < opTwo)
                            newCollection.rows.Add(this.rows[i]);
                        break;
                    case ComparisonOperator.LessThanEqualTo:
                        if(opOne <= opTwo)
                            newCollection.rows.Add(this.rows[i]);
                        break;
                    case ComparisonOperator.GreaterThan:
                        if(opOne > opTwo)
                            newCollection.rows.Add(this.rows[i]);
                        break;
                    case ComparisonOperator.GreaterThanEqualTo:
                        if(opOne >= opTwo)
                            newCollection.rows.Add(this.rows[i]);
                        break;
                    case ComparisonOperator.StartsWith:
                    {
                        if (operandOne.StartsWith(operandTwo))
                        {
                            newCollection.rows.Add(this.rows[i]);
                        }
                        break;
                    }
                }                    
            }
            return newCollection;
        }
        public int Count
        {
            get
            {
                return this.rows.Count;
            }
        }
        public wDBTableRow this[int i]
        {
            get
            {
                if (this.rows.Count >= i) return null;
                return this.rows[i];
            }
            set
            {
                this.rows[i] = value;
            }
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Text;
using ItzWarty.FormatProviders;

namespace ItzWarty
{
   public static class Extend {
      public static T[] Cast<T, U>(this U[] values, Func<U, T> cast) {
         T[] result = new T[values.Length];
         for (int i = 0; i < result.Length; i++)
            result[i] = cast(values[i]);
         return result;
      }
      public static KeyValuePair<TKey, TValue> PairValue<TKey, TValue>(this TKey key, TValue value) { return new KeyValuePair<TKey, TValue>(key, value); }
      public static KeyValuePair<TKey, TValue> PairKey<TKey, TValue>(this TValue value, TKey key) { return key.PairValue(value); }

      /// <summary>
      /// Calls the given function, passing self as the argument.
      /// </summary>
      public static T With<T>(this T self, Action<T> func) {
         func(self);
         return self;
      }

      /// <summary>
      /// Calls the given function, passing self as the argument.
      /// </summary>
      public static U With<T, U>(this T self, Func<T, U> func) {
         return func(self);
      }

      /// <summary>
      /// Runs self through the function, and returns the result.
      /// </summary>
      /// <typeparam name="T">The type of the fileName parameter</typeparam>
      /// <typeparam name="U">The type of the output result</typeparam>
      /// <param name="self">The fileName parameter which is passed through func</param>
      /// <param name="func">The function which we pass our fileName parameter through.</param>
      /// <returns>func(self)</returns>
      public static U Pass<T, U>(this T self, Func<T, U> func) {
         return func(self);
      }

      /// <summary>                                                                                              
      /// Checks whether argument is <see langword="null"/> and throws <see cref="ArgumentNullException"/> if so.
      /// </summary>                                                                                             
      /// <param name="argument">Argument to check on <see langword="null"/>.</param>                            
      /// <param name="argumentName">Argument name to pass to Exception constructor.</param>                     
      /// <returns>Specified argument.</returns>                                                                 
      /// <exception cref="ArgumentNullException"/>                                                              
      [DebuggerStepThrough]
      public static T ThrowIfNull<T>(this T argument, string argumentName)
         where T : class {
         if (argument == null) {
            throw new ArgumentNullException(argumentName);
         } else {
            return argument;
         }
      }


      public static TSource MinBy<TSource, TKey>(this IEnumerable<TSource> source,
                                                 Func<TSource, TKey> selector) {
         return source.MinBy(selector, Comparer<TKey>.Default);
      }

      public static TSource MinBy<TSource, TKey>(this IEnumerable<TSource> source,
                                                 Func<TSource, TKey> selector, IComparer<TKey> comparer) {
         source.ThrowIfNull("source");
         selector.ThrowIfNull("selector");
         comparer.ThrowIfNull("comparer");
         using (IEnumerator<TSource> sourceIterator = source.GetEnumerator()) {
            if (!sourceIterator.MoveNext()) {
               throw new InvalidOperationException("Sequence was empty");
            }
            TSource min = sourceIterator.Current;
            TKey minKey = selector(min);
            while (sourceIterator.MoveNext()) {
               TSource candidate = sourceIterator.Current;
               TKey candidateProjected = selector(candidate);
               if (comparer.Compare(candidateProjected, minKey) < 0) {
                  min = candidate;
                  minKey = candidateProjected;
               }
            }
            return min;
         }
      }

      public static TSource MaxBy<TSource, TKey>(this IEnumerable<TSource> source,
                                                 Func<TSource, TKey> selector) {
         return source.MaxBy(selector, Comparer<TKey>.Default);
      }

      public static TSource MaxBy<TSource, TKey>(this IEnumerable<TSource> source,
                                                 Func<TSource, TKey> selector, IComparer<TKey> comparer) {
         source.ThrowIfNull("source");
         selector.ThrowIfNull("selector");
         comparer.ThrowIfNull("comparer");
         using (IEnumerator<TSource> sourceIterator = source.GetEnumerator()) {
            if (!sourceIterator.MoveNext()) {
               throw new InvalidOperationException("Sequence was empty");
            }
            TSource max = sourceIterator.Current;
            TKey maxKey = selector(max);
            while (sourceIterator.MoveNext()) {
               TSource candidate = sourceIterator.Current;
               TKey candidateProjected = selector(candidate);
               if (comparer.Compare(candidateProjected, maxKey) > 0) {
                  max = candidate;
                  maxKey = candidateProjected;
               }
            }
            return max;
         }
      }

      // http://stackoverflow.com/questions/311165/how-do-you-convert-byte-array-to-hexadecimal-string-and-vice-versa
      public static string ToHex(this byte[] a)
      {
         var hex = new StringBuilder(a.Length * 2);
         foreach (byte b in a)
            hex.AppendFormat("{0:x2}", b);
         return hex.ToString();
      }

      [MethodImpl(MethodImplOptions.AggressiveInlining)]
      public static long GetUnixTime(this DateTime dateTime)
      {
         return (long)(dateTime - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
      }

      [MethodImpl(MethodImplOptions.AggressiveInlining)]
      public static long GetUnixTimeMilliseconds(this DateTime dateTime)
      {
         return (long)(dateTime - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
      }

      //http://stackoverflow.com/questions/128618/c-file-size-format-provider
      public static string ToFileSize(this long l)
      {
         return String.Format(new FileSizeFormatProvider(), "{0:fs}", l);
      }

      private delegate K TryGetValueDelegate<K, V>(K key, out V value);


      public static bool Within(this double a, double b, double epsilon)
      {
         return Math.Abs(a - b) <= epsilon;
      }

      public static bool Within(this float a, float b, float epsilon)
      {
         return Math.Abs(a - b) <= epsilon;
      }
   }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using ItzWarty.Collections;

namespace ItzWarty
{
   public static partial class Extensions
   {
      public static void ForEach<T>(this IEnumerable<T> enumerable, Action<T> action)
      {
         foreach (var element in enumerable) {
            action(element);
         }
      }

      /// <summary>
      /// Gets a subarray of the given array
      /// http://stackoverflow.com/questions/943635/c-arrays-getting-a-sub-array-from-an-existing-array
      /// </summary>
      public static T[] SubArray<T>(this T[] data, int index, int length = -1)
      {
         if (length == -1)
            length = data.Length - index;
         T[] result = new T[length];
         Array.Copy(data, index, result, 0, length);
         return result;
      }

      [MethodImpl(MethodImplOptions.AggressiveInlining)]
      public static T Get<T>(this T[] collection, int index) { return collection[index]; }

      [MethodImpl(MethodImplOptions.AggressiveInlining)]
      public static T Get<T>(this IList<T> collection, int index) { return collection[index]; }

      [MethodImpl(MethodImplOptions.AggressiveInlining)]
      public static V Get<K, V>(this IDictionary<K, V> dict, K key) { return dict[key]; }

      [MethodImpl(MethodImplOptions.AggressiveInlining)]
      public static V GetValueOrDefault<K, V>(this Dictionary<K, V> dict, K key)
      {
         return ((IDictionary<K, V>)dict).GetValueOrDefault(key);
      }

      [MethodImpl(MethodImplOptions.AggressiveInlining)]
      public static V GetValueOrDefault<K, V>(this IDictionary<K, V> dict, K key)
      {
         V result;
         dict.TryGetValue(key, out result);
         return result;
      }

      [MethodImpl(MethodImplOptions.AggressiveInlining)]
      public static V GetValueOrDefault<K, V>(this IReadOnlyDictionary<K, V> dict, K key)
      {
         V result;
         dict.TryGetValue(key, out result);
         return result;
      }

      public static bool TryAdd<K, V>(this IConcurrentDictionary<K, V> dict, K key, Func<V> valueFactory) {
         bool added = false;
         dict.AddOrUpdate(key, (k) => {
            added = true;
            return valueFactory();
         }, Util.KeepExisting);
         return added;
      }

      public static bool TryAdd<K, V>(this IConcurrentDictionary<K, V> dict, K key, Func<K, V> valueFactory) {
         bool added = false;
         dict.AddOrUpdate(key, (k) => {
            added = true;
            return valueFactory(k);
         }, Util.KeepExisting);
         return added;
      }

      public static bool TryRemove<K, V>(this IConcurrentDictionary<K, V> dict, K key, V value) {
         return dict.Remove(new KeyValuePair<K, V>(key, value));
      }
   }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ItzWarty.Collections;

namespace ItzWarty.Pooling {
   public interface ObjectPoolFactory {
      ObjectPool<T> CreatePool<T>(Func<T> generator);
      ObjectPool<T> CreatePool<T>(Func<T> generator, string name);
   }

   public class DefaultObjectPoolFactory : ObjectPoolFactory {
      private readonly ICollectionFactory collectionFactory;

      public DefaultObjectPoolFactory(ICollectionFactory collectionFactory) {
         this.collectionFactory = collectionFactory;
      }

      public ObjectPool<T> CreatePool<T>(Func<T> generator) {
         return new ObjectPoolImpl<T>(generator, collectionFactory.CreateConcurrentBag<T>());
      }

      public ObjectPool<T> CreatePool<T>(Func<T> generator, string name) {
         return new ObjectPoolImpl<T>(generator, collectionFactory.CreateConcurrentBag<T>(), name);
      }
   }
}
<file_sep>﻿//http://stackoverflow.com/questions/3130922/sortedsett-and-anonymous-icomparert-in-the-constructor-is-not-working

using System;
using System.Collections;
using System.Collections.Generic;

namespace ItzWarty.Comparers
{
    public class LambdaComparer<T> : IComparer<T>
    {
        private readonly Comparison<T> comparison;
        public LambdaComparer(Comparison<T> comparison)
        {
            this.comparison = comparison;
        }
        public int Compare(T x, T y)
        {
            return comparison(x, y);
        }
    }

    public class LambdaComparer : IComparer
    {
        private readonly Func<object, object, int> comparison;
        public LambdaComparer(Func<object, object, int> comparison)
        {
            this.comparison = comparison;
        }
        public int Compare(object x, object y)
        {
            return comparison(x, y);
        }
    }

   public class LambdaEqualityComparer<T> : IEqualityComparer<T>
   {
      private readonly Func<T, int> hashcode;
      private readonly Func<T, T, bool> equals;

      public LambdaEqualityComparer(Func<T, T, bool> equals, Func<T, int> hashcode)
      {
         this.hashcode = hashcode;
         this.equals = equals;
      }

      public bool Equals(T x, T y) { return equals(x, y); }
      public int GetHashCode(T obj) { return hashcode(obj); }
   }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SCC = System.Collections.Concurrent;

namespace ItzWarty.Collections {
   public class ConcurrentBag<T> : SCC.ConcurrentBag<T>, IConcurrentBag<T> {
      public ConcurrentBag() : base() { }
      public ConcurrentBag(IEnumerable<T> collection) : base(collection) { }
   }
}
<file_sep>﻿using System;
using ItzWarty.Collections;

namespace ItzWarty.Pooling {
   public class ObjectPoolImpl<T> : ObjectPool<T> {
      private readonly Func<T> generator;
      private readonly IConcurrentBag<T> container;
      private readonly string name;

      public ObjectPoolImpl(Func<T> generator) : this(generator, new ConcurrentBag<T>(), null) {}
      public ObjectPoolImpl(Func<T> generator, IConcurrentBag<T> container) : this(generator, container, null) { }
      public ObjectPoolImpl(Func<T> generator, string name) : this(generator, new ConcurrentBag<T>(), name) { }
      public ObjectPoolImpl(Func<T> generator, IConcurrentBag<T> container, string name) {
         generator.ThrowIfNull("generator");
         container.ThrowIfNull("container");

         this.generator = generator;
         this.container = container;
         this.name = name;
      }

      public string Name => name;
      public int Count => container.Count;

      public T TakeObject() {
         T result;
         if (!container.TryTake(out result)) {
            result = generator();
         }
         return result;
      }

      public void ReturnObject(T item) {
         container.Add(item);
      }
   }
}<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ItzWarty
{
    /// <summary>
    /// Timer class which is to be used in the using() block
    /// </summary>
    public class UsingTimer : IDisposable
    {
        private readonly Action<UsingTimer> m_onDispose;
        public DateTime StartTime { get; private set; }

        /// <summary>
        /// Creates a new using timer and sets the start time to the current time
        /// </summary>
        public UsingTimer(Action<UsingTimer> onDispose)
        {
            m_onDispose = onDispose;
            StartTime = DateTime.Now;
        }

        /// <summary>
        /// Disposes of the using timer.
        /// </summary>
        public void Dispose()
        {
            if (m_onDispose != null) m_onDispose(this);
        }

        /// <summary>
        /// The time that has elapsed since the Using Timer was created
        /// </summary>
        public TimeSpan ElapsedTime { get { return DateTime.Now - StartTime; } }

//        /// <summary>
//        /// Returns a method that formats the given string, swapping {0} for milliseconds
//        /// </summary>
//        /// <param name="format"></param>
//        /// <returns></returns>
//        public static Action<UsingTimer> PrintTimeSpanOnDispose(string s = "{0} ms")
//        {
//            return delegate(UsingTimer timer)
//            {
//                Console.WriteLine(s, timer.ElapsedTime.TotalMilliseconds);
//            };
//        }

        /// <summary>
        /// Returns a method that does nothing on dispose.
        /// 
        /// This simply returns null as the method.
        /// </summary>
        public static Action<UsingTimer> DoNothingOnDispose()
        {
            return null;
        }
    }
}
<file_sep>﻿using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;

namespace ItzWarty.Utilities {
   public static class AttributeUtilities {
      private static readonly AttributeUtilitiesInterface instance = new AttributeUtilitiesImpl();

      public static bool TryGetInterfaceGuid(Type interfaceType, out Guid guid) {
         return instance.TryGetInterfaceGuid(interfaceType, out guid);
      }
   }

   public interface AttributeUtilitiesInterface {
      bool TryGetInterfaceGuid(Type interfaceType, out Guid guid);
   }

   public class AttributeUtilitiesImpl : AttributeUtilitiesInterface {
      public bool TryGetInterfaceGuid(Type interfaceType, out Guid guid) {
         var attribute = interfaceType.GetAttributeOrNull<GuidAttribute>();
         if (attribute == null) {
            guid = Guid.Empty;
            return false;
         } else {
            guid = Guid.Parse(attribute.Value);
            return true;
         }
      }
   }
}
<file_sep>﻿//http://stackoverflow.com/questions/3130922/sortedsett-and-anonymous-icomparert-in-the-constructor-is-not-working
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ItzWarty
{
    public class FuncComparer<T> : IComparer<T>
    {
        private readonly Comparison<T> comparison;
        public FuncComparer(Comparison<T> comparison)
        {
            this.comparison = comparison;
        }
        public int Compare(T x, T y)
        {
            return comparison(x, y);
        }
    }

    public class FuncComparer : IComparer
    {
        private readonly Func<object, object, int> comparison;
        public FuncComparer(Func<object, object, int> comparison)
        {
            this.comparison = comparison;
        }
        public int Compare(object x, object y)
        {
            return comparison(x, y);
        }
    }
}
<file_sep>﻿using System;
using System.Collections;
using System.Collections.Generic;

namespace ItzWarty.Comparers
{
   public class EqualityComparer<T> : IEqualityComparer<T>, IEqualityComparer
   {
      private readonly Func<T, T, bool> m_equalityComparer;
      private readonly Func<T, int> m_hasher;

      public EqualityComparer(Func<T, T, bool> equalityComparer, Func<T, int> hasher)
      {
         m_equalityComparer = equalityComparer;
         m_hasher = hasher;
      }

      public bool Equals(T x, T y)
      {
         return m_equalityComparer(x, y);
      }

      public int GetHashCode(T obj)
      {
         return m_hasher(obj);
      }

      bool IEqualityComparer.Equals(object x, object y)
      {
         return m_equalityComparer((T)x, (T)y);
      }

      public int GetHashCode(object obj)
      {
         return m_hasher((T)obj);
      }
   }
}
